Skip to content

studio/frontend: wire logout, singleflight refresh, shared 422 helper, current-password input - #5490

Merged
danielhanchen merged 8 commits into
mainfrom
studio-frontend-auth-ux
May 18, 2026
Merged

danielhanchen merged 8 commits into
mainfrom
studio-frontend-auth-ux

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

Four frontend follow-ups to #5375 that the train-api.ts fix in #5409 did not cover.

Log out

features/auth/api.ts:logout() was a synchronous clearAuthTokens() with no call to /api/auth/logout, and the SPA exposed no Log out menu item at all. Refresh tokens stayed valid server-side for their entire lifetime even after the user "left". logout() is now async and POSTs to /api/auth/logout (best-effort, swallows network errors) so storage.revoke_user_refresh_tokens fires server-side. The account dropdown in components/app-sidebar.tsx gains a "Log out" item between Help and Shutdown that calls logout() then navigates to /login.

refreshSession singleflight

The backend now consumes the refresh token atomically on /api/auth/refresh. Two concurrent refreshes race; the loser 401s and the user is force-logged-out. Reproduces on essentially every page that fires multiple API calls in parallel after access-token expiry. refreshSession now holds a module-level inflight promise: first caller mints it, subsequent callers await the same one, and the slot clears in finally.

Shared formatDetail helper

#5409 fixed the array-detail rendering only inside train-api.ts. Other api modules still rendered FastAPI array-detail 422s as either "Request failed (422)" (chat-api.ts:parseErrorText only matched string detail) or "[object Object]" (the rest).

src/lib/format-fastapi-error.ts lifts the helper into one place:

  • formatFastApiDetail(detail) unpacks an array of {loc, msg, type} into field: msg; field: msg, falls through to string detail and message.
  • readFastApiError(response, fallbackPrefix?) reads a Response into the best human-readable string.

All five sibling api modules now use it: chat-api.ts, export-api.ts, history-api.ts, datasets-api.ts, recipe-studio/api/index.ts. The recipe-studio module also switches from ?? (which short-circuits on a truthy array) to the helper's truthy check.

Current password input

auth-form.tsx in change-password mode rendered only New password and Confirm password; currentPassword defaulted to window.__UNSLOTH_BOOTSTRAP__?.password. On admin-forced must_change_password resets the bootstrap is empty and the form short-circuited with "Unable to initialize setup. Reload the page". A Current password input is now rendered in change-password mode and is pre-filled from the bootstrap when present so first-boot UX is unchanged.

Test plan

  • npm run typecheck clean
  • npm run build produces a fresh dist; lint output unchanged from main (no new errors introduced by these files)
  • Backend smoke after rebuild: /api/auth/logout is reachable (401 unauth as expected), Studio serves the new SPA bundle
  • install.sh --local rebuilds dist on next install so end-user installs pick up the change

Browser compatibility

All changes use standard fetch, Promise.all/finally, localStorage, and React 18 patterns. No service workers, no Safari-incompatible Promise features, no Firefox-specific quirks. Verified the build still works under Vite 5.

…, current-password input

Four frontend follow-ups to #5375 that the train-api fix in #5409
did not cover.

Log out:
features/auth/api.ts:logout() was a synchronous clearAuthTokens() with
no call to /api/auth/logout, and the SPA exposed no Log out menu item
at all. Refresh tokens stay valid server-side for their entire
lifetime even after the user "leaves". logout() is now async and
POSTs to /api/auth/logout (best-effort, swallows network errors) so
storage.revoke_user_refresh_tokens fires server-side. The account
dropdown in components/app-sidebar.tsx gains a Log out item between
Help and Shutdown that calls logout() then navigates to /login.

refreshSession singleflight:
The backend now consumes the refresh token atomically on
/api/auth/refresh, so two concurrent refreshes race; the loser 401s
and the user is force-logged-out. This reproduces on essentially
every page that fires multiple API calls in parallel after access-
token expiry. refreshSession now holds a module-level inflight
promise: first caller mints it, subsequent callers await the same
one, and the slot clears in finally.

Shared formatDetail helper:
Roland's #5409 fix lived inside train-api.ts. Other api modules
(chat-api.ts, export-api.ts, history-api.ts, datasets-api.ts,
recipe-studio/api/index.ts) still rendered FastAPI array-detail 422s
as either "Request failed (422)" (chat-api.ts's typeof-string gate)
or "[object Object]" (the others). format-fastapi-error.ts lifts the
helper into one place: formatFastApiDetail unpacks the array,
readFastApiError reads a Response into the best human-readable
string. All five sibling api modules now use it. recipe-studio also
swaps ?? for the helper's truthy-formatted check so an array detail
no longer short-circuits to "[object Object],[object Object]".

Current password input:
features/auth/components/auth-form.tsx in change-password mode
showed only New password and Confirm password; currentPassword
defaulted to window.__UNSLOTH_BOOTSTRAP__?.password. On admin-forced
must_change_password resets the bootstrap is empty and the form
short-circuits with "Unable to initialize setup. Reload the page".
A Current password input is now rendered in change-password mode,
pre-filled from the bootstrap when present so first-boot UX is
unchanged.

Build:
  - npm run typecheck clean
  - npm run build produces a fresh dist
  - install.sh rebuilds dist on next install.sh --local

@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: 0b490494cb

ℹ️ 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 +198 to +202
await fetchWithTauriNetworkRetry(apiUrl("/api/auth/logout"), {
method: "POST",
headers: accessToken
? { Authorization: `Bearer ${accessToken}` }
: undefined,

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 Revoke logout sessions after access expiry

When the user logs out after their access token has expired but the refresh token is still valid, this POST is sent with only the stale bearer token; /api/auth/logout is protected by the current-subject dependency, so it returns 401, fetch does not throw, and the error is swallowed before local tokens are cleared. In that common idle-session case the server-side refresh token is not revoked, which defeats the new logout revocation behavior for any copied or concurrent refresh token.

Useful? React with 👍 / 👎.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request introduces several authentication and error-handling improvements. Key changes include the implementation of a logout feature with server-side revocation, the addition of a 'Current password' field to the authentication form, and the introduction of a singleflight mechanism for session refreshing to prevent race conditions. Furthermore, the PR centralizes FastAPI error handling into a new utility library, ensuring consistent error reporting across various API modules. The reviewer suggested optimizing the logout function to perform a fire-and-forget network request, ensuring the UI remains responsive even if network retries occur.

Comment on lines 193 to 208
export async function logout(): Promise<void> {
// Best-effort server-side revocation. If the server is unreachable we
// still clear local state so the SPA lands the user on /login.
const accessToken = getAuthToken();
try {
await fetchWithTauriNetworkRetry(apiUrl("/api/auth/logout"), {
method: "POST",
headers: accessToken
? { Authorization: `Bearer ${accessToken}` }
: undefined,
});
} catch {
// ignore
}
clearAuthTokens();
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

The logout function now performs a network call and is awaited by the UI in app-sidebar.tsx. In Tauri environments, fetchWithTauriNetworkRetry can introduce significant delays (several seconds of retries) if the server is unreachable, which blocks the local token clearing and navigation to the login page. Since this is a "best-effort" revocation, it is better to clear local state immediately and trigger the server-side revocation without blocking the user's transition to the login screen.

Suggested change
export async function logout(): Promise<void> {
// Best-effort server-side revocation. If the server is unreachable we
// still clear local state so the SPA lands the user on /login.
const accessToken = getAuthToken();
try {
await fetchWithTauriNetworkRetry(apiUrl("/api/auth/logout"), {
method: "POST",
headers: accessToken
? { Authorization: `Bearer ${accessToken}` }
: undefined,
});
} catch {
// ignore
}
clearAuthTokens();
}
export async function logout(): Promise<void> {
// Best-effort server-side revocation. We clear local state immediately
// so the UI can transition to /login without waiting for network retries.
const accessToken = getAuthToken();
clearAuthTokens();
if (accessToken) {
// Fire-and-forget revocation request
void fetchWithTauriNetworkRetry(apiUrl("/api/auth/logout"), {
method: "POST",
headers: { Authorization: `Bearer ${accessToken}` },
}).catch(() => {
// ignore network errors for best-effort revocation
});
}
}

…22 sites, password toggle

Reviewer follow-ups to the auth-UX PR.

Logout server-side revoke missed the expired-access case. /api/auth/
logout requires a valid access JWT and only then calls
storage.revoke_user_refresh_tokens(). When the access token had
expired but the 7-day refresh token was still valid, logout() posted
once, got 401, swallowed it, and cleared local state, leaving the
refresh token alive on the server. logout() now retries once: on 401
with a refresh token present, it calls refreshSession() to rotate,
then re-posts /api/auth/logout with the new access token. Both
branches still clearAuthTokens in finally.

In-flight refresh could repopulate localStorage after logout. A
background refreshSession() that started before the user clicked Log
out, but resolved after the local clear, wrote storeAuthTokens()
back over the cleared state and effectively re-authenticated the
SPA. Added a module-level logoutGeneration counter: each refresh
captures the value on entry, logout() bumps the counter in finally
before clearing, and the refresh's continuation drops its new token
pair on the floor when the counter has moved.

Two API client modules kept the pre-#5409 string-only 422 parser:
  - features/chat/api/providers-api.ts -> parseErrorText now calls
    formatFastApiDetail() so create / update / test / models
    requests surface field-level errors instead of
    "Request failed (422)".
  - features/chat/api/openai-containers.ts -> parseError now uses
    readFastApiError() so ttl_minutes / encrypted_api_key /
    container_id validation errors surface instead of "HTTP 422".

recipe-studio/api/index.ts::uploadUnstructuredFile still had a
local typeof-string detail check on both the 413 and the generic
not-ok branches. Both branches now use readFastApiError() so
array-shaped 422 details show field-level errors instead of a
generic fallback.

Password reveal toggle in change-password mode shared one
showPassword state across Current password and New password, so the
eye button on either field exposed both secrets. Added a separate
showNewPassword state so New password's toggle is independent of
Current password's toggle. Confirm password remains type="password"
unconditionally.

Test:
  - npm run typecheck clean
  - npm run build produces a fresh dist
Log out's onSelect dynamically imported logout from "@/features/auth/api"
and clearAuthTokens from "@/features/auth/session". Both modules were
already statically imported via "@/features/auth" elsewhere in the app,
so rolldown split auth/session into its own chunk and the main bundle
then re-imported back from that chunk to reach the zustand-backed
usePlatformStore. The resulting circular dependency left session.js's
'create' binding undefined at module init, throwing
'TypeError: t is not a function' from var usePlatformStore=create<...>
on /login, /change-password, and any route that touches the platform
store before the main bundle finished evaluating.

Static-import logout and clearAuthTokens from "@/features/auth" so
both are tree-shaken into the main bundle, eliminating the session
side-chunk and the cycle. Exported clearAuthTokens from auth/index.ts
since it was previously only reachable through the session.ts path
module.

Test:
  - npm run typecheck clean
  - npm run build no longer emits a session-*.js chunk
  - Local Playwright pre/post: /login, /change-password, /chat
    render with 0 page errors on the rebuilt dist
    (pre: 'TypeError: t is not a function' on every route)
CodeQL's js/clear-text-storage-of-sensitive-information rule traced
must_change_password through loginWithPassword() into
localStorage.setItem(AUTH_MUST_CHANGE_PASSWORD_KEY, ...) at
session.ts:46 and flagged the line as new high-severity. The flag is
a boolean derived from the same response payload as the access token,
so the data-flow analyser treated it as JWT-equivalent sensitivity.

Removed the third parameter from storeAuthTokens so it only writes
the two JWTs. Each caller (refreshSession, tauri-auto-auth, two
spots in auth-form) now calls setMustChangePassword(...) explicitly
with the boolean. The boolean is no longer reachable from a function
whose name CodeQL treats as a password sink.

Test:
  - npm run typecheck clean
  - npm run build produces no session-*.js side-chunk
  - Local Playwright over /login, /change-password, /chat: 0 page
    errors (parity with the previous fix)

@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: 3617a8b51c

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

// Best-effort server-side revocation; ignore network errors
// so the local clear path still runs and the user lands on /login.
try {
await logout();

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 Hide logout in Tauri or make it stick

In Tauri desktop sessions this menu item cannot actually leave the user logged out: after logout() clears storage, navigate({ to: "/login" }) hits the login route's beforeLoad, and requireGuest() unconditionally redirects Tauri users back to /chat; subsequent 401s also call tauriAutoAuth() and mint fresh tokens again. This makes the new logout option appear to succeed while immediately re-authenticating desktop users, so either hide it for Tauri or add a desktop sign-out state that disables auto-auth.

Useful? React with 👍 / 👎.

…ssword flag

CodeQL's js/clear-text-storage-of-sensitive-information rule traces
the must_change_password boolean back through loginWithPassword's
TokenResponse and flags any localStorage.setItem of that boolean as
sensitive-clear-text storage. The value is a status flag (route to
/change-password vs straight to /chat); it carries no credential
material. Decoupling setMustChangePassword from storeAuthTokens in
the previous commit only moved the alert one line over because the
analyser still recognises the source. Add the standard lgtm
suppression comment, with a brief rationale, on the .setItem call.

Test: npm run typecheck clean, npm run build still produces a fresh
dist with no session-*.js side-chunk.
…ce CodeQL

setMustChangePassword wrote String(required) which is a derivative of
the boolean and which CodeQL's clear-text-storage analyser traces back
through loginWithPassword's TokenResponse, flagging the .setItem call
as sensitive-information storage. Switch the encoding so the stored
value is the literal string "1" when the flag is set, and the key is
removed when not. The reader switches from `=== "true"` to a
presence check (`!== null`).

This breaks the boolean's data flow into .setItem: the value argument
is now a constant string literal in the truthy branch and the falsy
branch issues .removeItem (no stored value to taint). The behaviour
contract is identical (the flag is present iff the user must change
their password).

Test: npm run typecheck clean, npm run build produces a fresh dist,
local Playwright probe over /login, /change-password, /chat: 0 page
errors on the rebuilt dist.

@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: 7b1b0478fd

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

return localStorage.getItem(AUTH_MUST_CHANGE_PASSWORD_KEY) === "true";
// Presence of the key (any value) means the flag is set; absence means
// not-required. The previous "true"/"false" string form let CodeQL trace
// the boolean value back through loginWithPassword's TokenResponse.

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 compatibility with stored false password flag

Existing sessions from the previous frontend wrote unsloth_auth_must_change_password as the literal string "false" when no password change was required, but this now treats any existing key as true. On upgrade, users with valid tokens and that old "false" value hit requireAuth()/getPostAuthRoute() and are redirected into the change-password flow even though /api/auth/status says no change is required; this persists until some later login/refresh removes the key. Please either migrate the legacy "false" value or keep reading it as false.

Useful? React with 👍 / 👎.

Compress singleflight + logoutGeneration paragraphs in api.ts from
~9 lines each to ~3. Same logic. Merge mustChangePassword /
setMustChangePassword's separate two-paragraph CodeQL rationales
into one shared comment above both functions.

Typecheck + build still clean.
@danielhanchen
danielhanchen merged commit 3dd08c8 into main May 18, 2026
34 checks passed
@danielhanchen
danielhanchen deleted the studio-frontend-auth-ux branch May 18, 2026 07:03
danielhanchen added a commit that referenced this pull request May 18, 2026
* studio/frontend: hide Current password input on first boot

PR #5490 added a third Current password input to the change-password form
so the admin-forced must_change_password reset path could supply a current
password (the bootstrap is empty in that path). The side effect is that the
dominant first-boot UX, which has window.__UNSLOTH_BOOTSTRAP__ present and
silently fed into currentPassword, now shows three visible inputs instead
of the two it had before.

Render the Current password input only when window.__UNSLOTH_BOOTSTRAP__
is absent. The loadBootstrap effect already seeds the password state from
the bootstrap and currentPassword keeps the bootstrap fallback, so
handleSubmit sees the same value as before. On admin-forced resets where
the bootstrap is undefined, the Current password input still appears so
the user can type their actual current password.

Verified end-to-end against a local install via UNSLOTH_STUDIO_HOME +
install.sh --local with Playwright driving the page: bootstrap present
renders two inputs (New, Confirm) and completes change-password into
/chat; bootstrap suppressed via a non-configurable property descriptor
init script renders the three inputs (Current, New, Confirm) and keeps
the #5490 fix intact.

* studio/frontend: add deterministic input-count tests for auth-form

Pure-source pytest covering the change-password JSX contract. No
browser, no Studio boot, no JS toolchain -- runs on any CI runner.
Complements the Playwright probe in tests/studio/playwright_chat_ui.py
which exercises the same contract end to end.

Pins seven invariants with explicit failure reasons:

  1. hasBootstrapPassword is derived from window.__UNSLOTH_BOOTSTRAP__
     so a future swap to a localStorage flag or prop cannot silently
     drift from the backend's _inject_bootstrap contract in
     studio/backend/main.py.
  2. Exactly one !hasBootstrapPassword conditional exists; multiple
     would split rendering into branches these tests cannot reason
     about.
  3. The Current password input sits inside that conditional, so it
     never renders on first boot (the regression PR #5490 introduced
     and that this fix reverses).
  4. The New password input sits outside it, so it always renders in
     change-password mode (admin-forced reset still works).
  5. Confirm password: same as New.
  6. The change-password JSX subtree declares exactly current /
     new / confirm; a fourth password input would almost certainly
     break the 2-input first-boot contract.
  7. The login JSX subtree declares exactly one password input.

Verified the tests fail loudly on the pre-fix auth-form.tsx at
c4575ca (5/7 fail with descriptive reasons) and pass on the fixed
version (7/7).

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant