Skip to content

Keep Studio windows signed in during concurrent session refresh - #16468

Merged
danielhanchen merged 13 commits into
mainfrom
fix/studio-session-continuity-154
Nov 3, 2026
Merged

danielhanchen merged 13 commits into
mainfrom
fix/studio-session-continuity-154

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 2, 2026 •

Copy link
Copy Markdown
Member

Opening the same Studio session in two windows can log both windows out when their access tokens expire together. Refresh tokens are single-use, but refresh coordination was limited to each window: the losing 401 could clear shared credentials before the successful refresh saved its rotated pair.

This branch includes the reviewed #16471 spacing fix as a shared frontend CI dependency. The Settings component is byte-identical to that PR. Merge #16471 first to keep the remaining diffs focused; the dependency is already present here for validation.

Serialize refresh across same-origin windows using Web Locks, then reuse a peer's rotated token only within the same session. Lock acquisition is bounded without cancelling a submitted refresh request. Existing sessions retain their session marker, and logout and account-switch boundaries remain enforced. Browsers without Web Locks retain the existing behavior.

Validation:

  • Matching-head scoped staging passes 21 Python auth/font checks and 75 Node checks on each of Linux, Apple Silicon macOS and Windows, with zero failures or skips. Raw logs and exact source-head ancestry were checked. The real frontend/backend reproductions below provide the actual Studio UI evidence.
  • The current head also carries Respect interface scaling in Settings search and rich-paste badge #16471's rich-paste badge correction for the font-contract CI regression introduced by Studio: paste links, tables, lists and formatting into the composer as Markdown #16298. Both Settings components are byte-identical to the parent. Local validation passes 21 Python checks, 75 Node checks and the full frontend suite: 14,747 passing, zero failing and one existing skip. Refreshed cross-platform checks include the Python font contract. The first expanded frontend run used symlinked dependencies outside Vite's root and is excluded; the passing run uses a normal local dependency installation.
  • Full Studio pages and the real backend refresh endpoint reproduce the race in Chromium. Seeded invalid access plus a real refresh token and a controlled two-second successful-response delivery delay produce base responses 401 / 200, both windows at /login, and credentials cleared. This branch produces one 200, both windows at /chat, and credentials retained. The delay forces ordering; it is not a claim about natural frequency or backend task survival.
  • Two real pages running the production auth modules against a single-use refresh endpoint reproduce the failure in Chromium, Firefox, WebKit and Edge. Base sends two refresh requests and loses credentials; this branch sends one, both pages return ok, and the rotated credentials remain stored.
  • Identical differential tests against refreshed merge base 242f14b1d: base 27 pass / 6 fail; branch 33 pass / 0 fail / 0 skip. Five are behavioral fixes; one calls a new session helper and is counted as a new API check, rather than a repaired baseline defect. Base production sources and test-file hashes were verified. The broader original focused auth selection passes 72 tests.
  • The local switchboard reports NO_REGRESSION for auth, settings and route crawling: 38 same steps and one zero-pixel Hub DOM variation. The signed-in chat route, composer and stored session also survive a real reload on both sides.
  • Linux, macOS and Windows staging checks complete. Paired Studio journeys pass the functional gate on Linux and macOS Intel. The original Apple Silicon paired arms were cancelled before acquiring runners; macOS smoke checks ran separately. The final paired native run with the hardened test client passes all ten Desktop steps on both sides, with exact rc=0 receipts and a passing strict evidence gate. One dropped body-text response is recovered on the base arm; navigation, clicks and assertions are not replayed. Earlier native transport failures remain recorded, and the client hardening is isolated in unslothai/scripts#790. One baseline route screenshot is missing after a dropped GET response; that visual comparison is not claimed.
  • The refreshed combined application tree with Keep a verified live Desktop backend after watchdog recovery #16470 and Respect interface scaling in Settings search and rich-paste badge #16471 passes its production build and all 62 actual Tauri command tests. Its frontend Git tree equals this branch's tested tree.
  • The CPU auth fixture now exports the two session helpers that its production module imports. Its nine redirect checks pass without relaxing their assertions. The merged parity normalizer from studiobench parity: treat every data-*-id attribute as an instance id #16464 is included. Current organization CI remains queued or running; the completed owned staging results above provide scoped evidence.

This fixes a demonstrated refresh race; the report of backend jobs actually being cancelled has not been reproduced. Plain HTTP LAN origins without Web Locks retain the existing race limitation. Core inference, notebooks, backend token rules and model prompts are unchanged.

Two real Studio windows after the controlled refresh race:

Two-window refresh before and after

The shared spacing dependency below is the exact #16471 change; this comparison validates that dependency.

Shared Settings spacing dependency before and after

The inherited rich-paste badge correction is also byte-identical to #16471. At the enlarged font setting it scales from the previous fixed 10 px to 15 px, with the feature and switch retained:

Shared rich-paste font-scaling dependency before and after

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 2, 2026
danielhanchen pushed a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 2, 2026
@chatgpt-codex-connector

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

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-03T05:08:25.398459Z a8cec31 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.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

Reviewed commit: 54143b01ab

ℹ️ 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".

shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Nov 3, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: d10f715d8e

ℹ️ 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".

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Another round soon, please!

Reviewed commit: 5e776c119c

ℹ️ 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".

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: a8cec310ec

ℹ️ 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".

shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Nov 3, 2026
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Nov 3, 2026
…slothai#16471)

The Settings search field introduced three fixed pixel offsets in unslothai#16455 while its height and icons already follow the interface spacing scale. Those offsets break the existing spacing guard and leave the search icon, text inset and clear button out of proportion at non-default interface sizes.

Scale the three offsets with the same interface spacing variable. Their exact original values remain at the default scale. The existing regression test is unchanged.

The same validation pass found a second font-scaling regression in unslothai#16298: its rich-paste Beta badge used `text-[10px]`. Preserve the new feature and use the existing `text-ui-10` typography token, which follows the font preference. That shared token computes to 9.375 px at the default preference and 15 px at the enlarged setting; the former fixed value was 10 px at both. The existing font-contract test is unchanged. [Tailwind's typography documentation](https://tailwindcss.com/docs/font-size) describes how the theme token supplies the generated utility.

Validation:

- Matching-head strict staging passes 12 Python font-contract checks and 42 Node spacing/control checks on [Linux](https://github.com/Imagineer99/unsloth/actions/runs/41582365621), [Apple Silicon macOS](https://github.com/Imagineer99/unsloth/actions/runs/41582365722) and [Windows](https://github.com/Imagineer99/unsloth/actions/runs/41582365773), with zero failures or skips. Logs and staged ancestry were checked. The initial generic advisory jobs are not counted as correctness gates.
- The badge regression reproduces on merge base `242f14b1d`: 11 font-contract checks pass and one fails. All 12 pass after the one-line correction. Two isolated real Studio installs show the enlarged badge at 10 px before and 15 px after, retaining the feature label and switch. A separate [strict live-Studio staging probe](https://github.com/Imagineer99/unsloth/actions/runs/41582365955) confirms 9.375 / 15 px and visible controls on the published head; this is separate from the synthetic test-kit smoke.
- Production-built stylesheet probes pass in Chromium, Firefox, WebKit and Edge on both badge arms at default and enlarged settings. The current dependent auth frontend passes 14,747 tests, zero failures and one existing skip after a normal local dependency installation. A first run using symlinked dependencies was rejected by Vite's filesystem boundary and is excluded from passing evidence.
- The baseline spacing guard fails on exactly these three offsets. The focused spacing, icon and Settings visibility selection passes 31 tests with the fix.
- The refreshed combined application tree, including unslothai#16468 and unslothai#16470, passes 14,747 frontend tests, no failures and one existing skip. Its frontend Git tree equals the tested auth head. The production build and all 62 actual Tauri command tests pass.
- Real Studio rendering at default scale preserves icon/text/clear offsets of 13.5 / 39.5 / 12.5 px. At 1.4 scale the branch computes 18.9 / 55.3 / 17.5 px; base incorrectly retains the default offsets.
- Chromium, Firefox, WebKit and Edge all compute the intended geometry at default and 1.5 scale using the production-built stylesheet and representative search markup.
- Linux, Apple Silicon macOS and Windows staging checks complete. The selected UI suites also run successfully on both arms on a GPU-equipped cloud worker. No training or inference kernel is changed or benchmarked.

An initial local auth journey hit an intermittent blank frontend boot before the auth request. The same-head confirmation and a fresh paired auth run both pass all nine steps. Its cause remains unproven, and the redirect assertion and timeout are unchanged. The fresh paired Studio/Desktop run with the corrected harness passes its strict gate: 49 steps, all ten native Desktop steps successful on both sides, and no failed or VOID steps. The older failed run is retained as a driver failure, not relabelled as a pass.

The latest organization CPU security job was cancelled, without a test failure. Its exact four-file suite passes 105 tests locally. The same strict, unmasked job also passes [105 tests on an owned Linux CPU runner](https://github.com/Imagineer99/unsloth/actions/runs/41596344327), with zero failures or skips. The staged job equals the source job, contains this PR head and uses identical test-file blobs.

Earlier official CI included cancelled checks, which are not counted as passes. Matching owned staging checks are complete for the current head; organization CI is still running, and no all-green organization CI claim is made.

Comparison at 1.4 spacing scale:

![Settings search spacing before and after](https://raw.githubusercontent.com/danielhanchen/unsloth-staging-2/pr-media/pr/16471/pr16471_before_after-a78db41ffd5e.png)

Rich-paste badge at the enlarged font preference, from merge base `242f14b1d` and head `e3a4e3a06`; the feature and switch are preserved:

![Rich-paste badge font scaling before and after](https://raw.githubusercontent.com/danielhanchen/unsloth-staging-2/pr-media/pr/16471/pr16471_before_after-3e473cadeed6.png)
danielhanchen added a commit to Etherll/unsloth that referenced this pull request Nov 3, 2026
…ai#16470)

Desktop can stop a healthy Studio backend after earlier health probes time out. Its final, wider probe may verify that the backend is alive, but the watchdog previously accepted that answer only when inference was active. A live idle answer still fell through to backend shutdown and a server-crashed event.

This branch includes the reviewed unslothai#16471 spacing fix as a shared frontend CI dependency. The Settings component is byte-identical to that PR. Merge unslothai#16471 first to keep the remaining diffs focused; the dependency is already present here for validation.

Respect a positively verified live confirmation, reset the failure count, and set the inference latch from that answer. Protection for a busy backend whose probe times out remains in place. Ownership verification, generation checks, shutdown checks and failure budgets are unchanged.

Validation:

- Matching-head native [Rust decision checks](https://github.com/LeoBorcherding/unsloth/actions/runs/41583955027) compile the production function on Linux x86_64, Apple Silicon macOS and Windows MSVC against refreshed merge base `242f14b1d`. Each base reproduces two false-stop decisions; each head matches all eight expected states. Artifact source hashes match both actual revisions. Separate scoped checks pass 12 Python and 42 Node tests on [Linux](https://github.com/LeoBorcherding/unsloth/actions/runs/41583941228), [Apple Silicon macOS](https://github.com/LeoBorcherding/unsloth/actions/runs/41583941300) and [Windows](https://github.com/LeoBorcherding/unsloth/actions/runs/41583941248), with zero failures or skips. This does not replace the unperformed full asynchronous native-app fault injection.
- The current head also carries unslothai#16471's rich-paste badge correction for the font-contract CI regression introduced by unslothai#16298. Both Settings components are byte-identical to the parent. Local font checks pass 12 Python and 42 Node tests; the native decision reproduction also passes against the refreshed merge base. Refreshed platform checks include the font contract and native Rust compilation.
- An identical harness extracted from the production Rust helpers and tests reports four passes / two failures on base, then six passes / no failures on this branch. Live idle confirmation is retained; a later idle stall still uses the ordinary failure budget.
- A fresh production frontend build followed by the actual Tauri commands test suite passes all 62 tests. The final run uses real built frontend assets.
- The eight predicate combinations preserve six decisions and widen two to retain a verified live response; no prior keep decision becomes a stop decision.
- The local auth/settings/crawl switchboard reports `NO_REGRESSION`, with baseline startup flakes and nonfunctional DOM/visual differences recorded. Paired staging reports also say `NO_REGRESSION` on Linux, Apple Silicon macOS and Windows. The initial native Settings failures were traced to a hidden-control selector in the test. With the corrected harness from unslothai/scripts#790, both native arms now pass all ten steps, including a displayed Settings dialog and IPC, with exact `rc=0` receipts. The new paired run reports `NO_REGRESSION` across 49 steps with no failed or VOID steps.
- The refreshed combined application tree with unslothai#16468 and unslothai#16471 passes 14,747 frontend tests, no failures and one existing skip; its frontend Git tree equals the tested auth head. The production build and all 62 actual Tauri command tests pass. Merge unslothai#16471 first to keep the dependent diffs focused.

The watchdog fix preserves download concurrency, timeout budgets, notebook code and model loading. The shared unslothai#16471 dependency supplies the separately reviewed interface-spacing correction. This demonstrates a watchdog false-stop, not the cause of every download-time exit in the Discord report. A full asynchronous watchdog fault injection into the native app has not been run.

Current organization CI remains queued or running. Matching owned staging checks are complete for the current head; no all-green organization CI claim is made.

The normal signed-in chat remains unchanged in the browser comparison; this picture does not simulate a watchdog failure.

![Normal chat before and after](https://raw.githubusercontent.com/danielhanchen/unsloth-staging-2/pr-media/pr/16470/pr16470_before_after-09f3b79f9dfe.png)

The shared spacing dependency below is the exact unslothai#16471 change; this comparison validates that dependency.

![Shared Settings spacing dependency before and after](https://raw.githubusercontent.com/danielhanchen/unsloth-staging-2/pr-media/pr/16471/pr16471_before_after-a78db41ffd5e.png)

The inherited rich-paste badge correction is also byte-identical to unslothai#16471. At the enlarged font setting it scales from the previous fixed 10 px to 15 px, with the feature and switch retained:

![Shared rich-paste font-scaling dependency before and after](https://raw.githubusercontent.com/danielhanchen/unsloth-staging-2/pr-media/pr/16471/pr16471_before_after-3e473cadeed6.png)
@danielhanchen
danielhanchen merged commit c1a6513 into main Nov 3, 2026
@danielhanchen
danielhanchen deleted the fix/studio-session-continuity-154 branch November 3, 2026 13:31
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 7, 2026
…fresh at once (unslothai#16755)

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](https://raw.githubusercontent.com/LeoBorcherding/unsloth/pr-media/pr/741/session_reset_multitab_before_after.png)

## What was wrong

Refresh tokens are single-use. unslothai#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:

```mermaid
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
```

- 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](https://raw.githubusercontent.com/danielhanchen/unsloth-staging-2/pr-media/pr/16755/pr16755_multitab_before_after-e802a97c73db.png)

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

---------

Co-authored-by: Daniel Han <[email protected]>
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.

1 participant