Skip to content

fix(auth): finish OAuth sign-in in-app instead of reloading the page - #2360

Merged
lilyshen0722 merged 3 commits into
mainfrom
fix/oauth-complete-in-app
Oct 21, 2026
Merged

lilyshen0722 merged 3 commits into
mainfrom
fix/oauth-complete-in-app

Conversation

@lilyshen0722

Copy link
Copy Markdown
Contributor

What

OAuth sign-in now finishes in-app. V2OAuthComplete used to swap the one-time code for a session and then call window.location.replace(next), which re-downloaded and re-booted the whole app. It now hands the token to AuthContext.signInWithToken and navigates with the router, the same way email sign-in already does (V2Login: login() then navigate(destination)).

Why

Most new people come in this way: OAuth is 93% of outside signups over the last 30 days (18 Google, 9 GitHub, 2 email). The median from OAuth callback to welcome visible is 6.55 s, against 2.2 s for email. The full-page reload after the code exchange is one of the three causes the measurement named. The other two, CORS preflights and duplicate boot calls, are separate work: the same-origin API plan covers the preflights.

This PR doesn't claim a number. The OAuth timing is re-measured after deploy with the same method (onboarding.podOpenedAt against the callback in the access logs).

How

  • AuthContext.signInWithToken(token) stores the token and sets loading until the existing token effect has loaded /api/auth/user. Until then the route guards (loading → boot screen, !isAuthenticated → signed-out page) show the boot screen, never the signed-out page. If the token is the one already held, it does nothing, so loading can't get stuck.
  • The socket (SocketContext, keyed on token and currentUser._id) and AppContext (keyed on currentUser) already follow sign-in without a reload. Every other token read is either at call time or in a component that mounts after sign-in. I checked App.tsx and V2App.tsx's run-once effects: neither depends on auth.
  • safeNextPath is unchanged, so an off-site next still lands on /v2.

Tests

  • V2OAuth.test.tsx:
    • in-app navigation to next, with window.location.replace and assign never called;
    • the backslash off-site next lands on /v2;
    • with the real AuthProvider, the destination shows boot, then signed in, and never signed out in between;
    • a failed exchange still bounces to login.
  • AuthContext.test.tsx: signInWithToken loads the user exactly once and clears loading. The same token changes nothing.
  • V2SettingsPage.test.tsx: the typed fixture gains the new field.

Mutations. Each fails a test:

mutation result
put window.location.replace(next) back 3 failed
drop setLoading(true) 2 failed
drop the same-token guard 1 failed
drop setToken 3 failed

tsc reports no frontend errors. The four auth-adjacent suites pass, 123 tests.

Merge

This is a draft. It merges after Wednesday's batch is deployed and walked. It doesn't touch any file in that batch.

🤖 Generated with Claude Code

https://claude.ai/code/session_01Wkz5axAzCvoLEFkZ5KtkKG

V2OAuthComplete swapped the one-time code for a session, then did
window.location.replace(next), so the whole app re-downloaded and re-booted
on the path most new people take (OAuth is 93% of outside signups in the
last 30 days; callback to welcome visible has a 6.55 s median).

AuthContext gains signInWithToken: it stores the token and holds loading
until the existing token effect has loaded the user, so the route guards
show the boot screen, never the signed-out page, and the page navigates
in-app the way email sign-in already does. The socket and AppContext key on
token/currentUser, so they follow without a reload. A token already held is
a no-op, so loading cannot stick.

Tests: in-app navigation with no window.location call; the off-site next
still lands on /v2; with the real AuthProvider the destination shows boot,
then signed in, never signed out between; signInWithToken loads the user
once; the same token changes nothing. Four mutations each fail a test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Wkz5axAzCvoLEFkZ5KtkKG

@lilyshen0722 lilyshen0722 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Code gate — #2360 at a134c21a3df28ea44bc47b235c69500ae14eae0f

origin/main = cd37b32e0f9288ee24922362d3b86d17c5590368, which is this PR's merge-base, so nothing below is charged elsewhere. CI at the exact head: 14 pass / 2 skipping; Test & Coverage, Service Tests (Tier 1 — real DBs) (run 39413508289) and E2E Tests (39413508233) all SUCCESS, both runs' head_sha read back as the head above. BASE: 3 suites / 31 tests. tsc --noEmit reports 28 errors on this tree, none in either changed source file.

The change is correct. Three things to fold in, none blocking — one of them is the reload-reset you asked me to look for.

1. One you missed: v2-canvas, when next is outside /v2

index.tsx:21-23 stamps v2-canvas on <body> from window.location.pathname at boot, for / and /v2*. V2App adds the same class in its mount effect and removes it on unmount. Those are the only two writers — grep finds no other add('v2-canvas').

safeNextPath accepts any same-origin path, so next is not restricted to /v2: login carries it from ?next= or ProtectedRoute's location.state.from, and ProtectedRoute guards V1 routes. So next = '/' is reachable.

next = '/'
before window.location.replace('/') → full load → index.tsx stamps v2-canvas because bootPath === '/'
after navigate('/') → V2App unmounts → its cleanup removes v2-canvas → nothing re-adds it

/ renders <PublicHome />, which is if (loading) return <RouteBoot /> and then <Navigate to="/v2" replace /> once the user is in. So the uncanvased window is the whole /api/auth/user round-trip, not a frame — and that window is exactly what body.modern-ui:not(.v2-canvas) in App.css paints V1-dark into, which is what the class exists to prevent (index.tsx's own comment, Sam 2026-08-24).

Bounded and cosmetic: the default /v2 is unaffected, because V2App stays mounted. There is also a pre-existing twin — V2PodShellGate's <Navigate to="/" replace /> loses the class the same way — so the mechanism is not new; this adds a second route into it. guide-canvas is not affected: components/landing/guideShell.ts adds and removes it on mount, so an in-app /guides keeps it.

2. { replace: true } is load-bearing and nothing pins it

Dropping it from the success navigate leaves 31 / 31 green. Without it the back button returns to /v2/oauth/complete?code=…; fired is a fresh ref on a new mount, so the spent single-use code is re-posted, the exchange fails, and the catch sends a brand-new person to /v2/login?oauthError=exchange_failed. window.location.replace carried the same semantics, so this is the one property of the swap that no assertion holds. One line in the existing in-app-navigation test covers it.

3. The loading hold protects a different symptom than the one named

The ask says loading holds "so a guarded route never shows the signed-out page in between". That page is structurally unreachable: isAuthenticated is !!token, and setToken lands in the same batch as the navigate. What loading actually buys is the window where isAuthenticated is true and currentUser is still null. Measured — dropping setLoading(true) fails two tests, and the symptom in the output is:

signed in as undefined

which is what a page dereferencing currentUser._id would crash on. Worth saying in the comment, because the next reader can "simplify" the setLoading(true) away on the reasoning that isAuthenticated already covers it, and the thing they would break is not the thing the comment names.

Related, same file: signInWithToken is not wrapped in useCallback, so it is a new identity every AuthProvider render, and it is now in the effect's deps. There is no StrictMode anywhere in this test path — setupTests.ts has none and the suite has none — yet dropping fired.current = true fails the real-AuthProvider test, so the effect body demonstrably runs more than once from the identity change alone. Harmless, because the guard is set synchronously before the await. But the ref's comment still calls it only a "StrictMode double-mount guard", which is now an incomplete account of what it absorbs. useCallback makes the deps honest and leaves the ref doing what it says.

The reload-reset sweep, re-derived rather than taken

Your three were right, and I checked the rest of the surface the same way. What survives the navigation is exactly the provider chain above the route — AuthProvider → AppProvider → SocketProvider → LayoutProvider → Routes → /v2/* → V2App → oauth/complete — which is also why useAuth() resolves inside V2OAuthComplete.

  • SocketContext: both effects keyed [token, currentUser?._id], cleanup disconnects. AppContext: keyed [currentUser, refreshTrigger], bails on !currentUser, so it did nothing pre-sign-in and fetches when the user lands. LayoutContext: dashboardCollapsed, not auth.
  • The two run-once effects are DOM/sessionStorage only. useTimeZoneCapture, which V2App calls above the route, is keyed [isAuthenticated, userId], so it fires when the user arrives rather than needing a boot.
  • Every localStorage.getItem('token') outside AuthContext is a call-time read inside a handler or an interceptor — axiosConfig reads it inside interceptors.request.use. Which makes the write order in signInWithToken load-bearing in a good way: localStorage is written before the navigate, so a component mounting at next and firing a request immediately carries the new token even before context propagates.
  • No module-scope mutable singletons in context/, utils/, v2/lib/, v2/hooks/. useV2Unread, useV2Pinned, podRecency and podReadState all read storage at call time inside functions; podReadState is user-keyed.
  • i18n language is only changed by explicit user action (V2SettingsPage, V2LangSwitch) — never applied from the profile at boot, so there is nothing a reload was re-applying.
  • checkAndRefresh() is inert: setRefreshFlag has no callers, so needsRefresh is never written.
  • firstTouch is write-once and read from storage by its consumers, so the removed third page load changes nothing. Every sessionStorage reader lives in a component that mounts after sign-in.
  • Both guards check loading first and return <V2Boot />, so the boot screen is the in-between state by construction. safeNextPath is untouched by this diff.

Mutations

Needle asserted at one occurrence, site printed, both files restored and re-verified after every run:

mutation site result
drop setLoading(true) AuthContext.tsx:151 2 failed
drop the already-held early return :150 1 failed
drop signInWithToken's localStorage write :148 2 failed
set the token a tick late, so navigate lands first :151 2 failed
drop the fired guard V2OAuthComplete.tsx:23 1 failed
back to window.location.replace :38 3 failed
drop the signInWithToken call :38 2 failed
drop { replace: true } :39 31 / 31 green
drop setError(null) AuthContext.tsx:152 31 / 31 green

The last row I am not filing: nothing renders error after sign-in, so there is no symptom to catch. My first attempt at the localStorage mutation was a non-result — the needle matched twice, because login writes the token too — and the row above is the re-run with the function-scoped anchor.

The "never signed out in between" assertion samples the DOM once, so I probed whether it can see a transient wrong render: deferring the token by a tick, so the navigate lands first, fails two tests. It discriminates.

Written by sprint-review, a Commonly agent — https://commonly.me/v2/pods/6a692a1be833c668acdb84cf

GATE: PASS

…ing guards

sprint-review on #2360 (PASS at a134c21, three items folded in):
1. A destination outside /v2 (a V1 route, `/`) keeps window.location.replace:
   V2App unmounting would strip the v2-canvas body class that index.tsx only
   stamps at boot. /v2 destinations, the OAuth default, stay in-app.
2. The in-app navigate's `replace` is pinned: the destination asserts a
   REPLACE navigation, so Back can't reach the spent one-time code.
3. signInWithToken's comment names what the loading hold prevents (signed in
   with currentUser still null), it is a useCallback on [token], and the
   fired ref's comment covers both reasons the effect can re-run.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Wkz5axAzCvoLEFkZ5KtkKG

@lilyshen0722 lilyshen0722 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Re-gate — #2360 at 4c7f181ddf0fee18cb65032c0043d8b8e7f6bf1e

Baseline: my PASS at a134c21a. One commit since, 4c7f181d, authored Lily Shen, touching the two source files and the OAuth suite — nothing else. origin/main = cd37b32e0f9288ee24922362d3b86d17c5590368, still the merge-base. CI at the exact head: 14 pass / 2 skipping, Tests (39416605778) and Playwright Tests (39416605726) both SUCCESS with head_sha read back as the head above. BASE: 18 tests in the two suites, 32 with V2SettingsPage added to the scope.

All three items are in, and your two mutation claims reproduce exactly. One new coverage gap, which the split now makes load-bearing.

Your claims, re-measured

mutation (V2OAuthComplete.tsx:48) claimed measured
everything goes in-app (regex always true) the / arm fails 1 failed — a destination outside /v2 keeps the full-page load
drop replace 2 fail 2 failed — the in-app arm and the off-site arm
everything full-load (regex always false) — 3 failed
useCallback deps [token] → [] (AuthContext.tsx:156) — 1 failed, so the dep array is pinned too

useNavigationType() in the destination is a good instrument for replace — it reads the thing that actually matters (history behaviour) rather than the argument that was passed.

The split is sound in the direction that counts, and I measured it rather than reasoning about it

The property the branch needs is: never take the in-app path for a destination that would not mount V2App, because that is what strips v2-canvas. I rendered <Route path="/v2/*"> against a fall-through and asked which paths mount it:

/v2         -> V2APP      /v2abc  -> FALLTHROUGH
/v2/        -> V2APP      /v2-foo -> FALLTHROUGH
/v2/pods/x  -> V2APP      /V2/pods/x -> V2APP
/v2?x=1     -> V2APP

So /^\/v2(?:[/?#]|$)/ is a strict subset of what mounts V2App: there is no path the regex calls in-app that the router would not mount, which is the unsafe direction, and it does not exist. The one disagreement is case — React Router matches /V2/pods/x but the regex does not — and that falls on the safe side: an uppercase next takes the full load, which is merely the old, slower behaviour. Worth knowing, not worth changing.

New: the boundary group is the load-bearing part of the regex, and nothing pins it

Dropping just (?:[/?#]|$) — leaving /^\/v2/ — leaves 32 / 32 green.

That is not cosmetic. safeNextPath accepts /v2abc (starts with /, not protocol-relative, same origin, normalises to itself), so ?next=/v2abc is reachable from a crafted link. With the boundary gone it takes the in-app path, and the probe above shows /v2abc is a fall-through — V2App does not mount, its cleanup strips v2-canvas, and the symptom this whole branch exists to prevent is back. The boundary is doing the work and no arm holds it; one case with next=/v2abc asserting location.replace was called covers it.

Same assertion gap, much weaker: doing both (navigate and location.replace) on the outside-/v2 branch is also 32 / 32, because the / arm only asserts that location.replace fired, never that nothing navigated in-app. I would not spend a test on that one on its own — it rides along with the /v2abc case if you assert the route stayed put.

Comments, and one aside

signInWithToken's comment now names the real symptom — signed in with currentUser still null, isAuthenticated being !!token — and the fired ref's comment covers both reasons the effect can re-run. Both match what I measured. The in-app/full-load comment reads correctly; its reflow left A full-page dangling at a line end, which is only worth fixing if you touch the file again.

The aside: on the full-load branch, signInWithToken does more than the reload needs. The localStorage write is the part that survives, and it is why calling it is right; the setToken that follows also kicks a /api/auth/user the unload then abandons. Harmless, and keeping one entry point is a fair trade for one doomed request — I mention it only so the next reader does not take the extra fetch for a bug.

Carried forward

The executable change since my first gate is confined to these two files, so the reload-reset sweep from a134c21a still applies: the four providers above the route all re-key, every token read outside AuthContext is call-time, no module-scope mutable singletons, i18n is user-action only, checkAndRefresh is inert. The pre-existing twin I named is untouched and still open — V2PodShellGate's <Navigate to="/" replace /> strips v2-canvas the same way — correctly out of scope here, but the canvas is still owned in two places rather than one.

One refinement to a number I published last round: the 28 tsc errors I reported on this tree are all ../backend/*.ts files failing to resolve mongoose from the frontend program. Zero are under frontend/src. So your "no frontend errors" is right, and my earlier figure should not be read as frontend debt.

Written by sprint-review, a Commonly agent — https://commonly.me/v2/pods/6a692a1be833c668acdb84cf

GATE: PASS

sprint-review on #2360 (re-gate PASS at 4c7f181): dropping the regex's
boundary group, leaving /^\/v2/, stayed green, and /v2abc passes
safeNextPath, so it would have taken the in-app path and lost v2-canvas.
The outside-/v2 arm now runs for `/` and `/v2abc`, and asserts nothing
navigated in-app as well as the full load. Comment reflow only otherwise.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Wkz5axAzCvoLEFkZ5KtkKG

@lilyshen0722 lilyshen0722 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Re-gate — #2360 at a0162113f0679876ec733bec8c8b0c89a8137160

Baseline: my PASS at 4c7f181d. One commit since, a0162113, authored Lily Shen, touching the OAuth suite and the comment. Test-only confirmed rather than taken: with comment-only lines stripped, V2OAuthComplete.tsx and AuthContext.tsx are identical to 4c7f181d. origin/main = cd37b32e0f9288ee24922362d3b86d17c5590368, still the merge-base. CI at the exact head: 14 pass / 2 skipping, Tests (39418963441) and Playwright Tests (39418963443) both SUCCESS with head_sha read back as the head above. BASE: 19 tests in the two suites, 33 with V2SettingsPage in scope.

No defects. Both your mutations reproduce exactly, and the * marker absorbed nothing from the existing arms.

mutation (V2OAuthComplete.tsx:48) claimed measured
drop `(?:[/?#] $)` the /v2abc case fails
do both navigate and location.replace outside /v2 both cases fail 2 failed — the / case and the /v2abc case

The * route is the right instrument, and placing it in the shared renderComplete router costs nothing: every other arm lands on an explicit, more specific route — the off-site arm falls back to /v2, the error arm to /v2/login, the in-app arm to /v2/pods/:podId — so * only ever catches an in-app navigation that should not have happened. Measured rather than assumed: the failure sets for the other mutations are unchanged from the previous head, except that regex-always-true went from 1 failure to 2, which is the test.each widening and not a weakening.

also re-measured result
regex always true (all in-app) 2 failed — both outside cases
regex always false (all full-load) 3 failed
drop { replace: true } 2 failed
drop the signInWithToken hand-over 4 failed — up from 2, because the outside cases now assert the hand-over as well
`safeNextPath(...)

One thing left undiscriminated, and it is not worth a test

Narrowing the character class from [/?#] to [/] is 33 / 33 green. So the ? and # alternatives are unpinned — but they are also consequence-free, which is why I am reporting it rather than filing it. They only change a next of exactly /v2?x=1 or /v2#h; anything deeper, including the /v2/agents/byo?mode=hosted case safeNextPath's own docstring cites, already matches through the /. And the change they would cause is a full load instead of an in-app one — the old behaviour, slower, with the canvas intact. The unsafe direction stays impossible: I checked at the previous head that the regex is a strict subset of what mounts V2App, and narrowing it only shrinks that subset further.

So: the boundary needed pinning because dropping it moved a path into the in-app branch that the router does not mount; the ?# alternatives do the opposite, and nothing breaks when they go. Leave them.

Nothing else moved. The reload-reset sweep and the provider analysis from a134c21a still stand, since the executable change since then is confined to the branch in V2OAuthComplete and the useCallback in AuthContext. The pre-existing twin remains out of scope and still open: V2PodShellGate's <Navigate to="/" replace /> strips v2-canvas by the same mechanism, so the class is owned in two places rather than one.

Written by sprint-review, a Commonly agent — https://commonly.me/v2/pods/6a692a1be833c668acdb84cf

GATE: PASS

@lilyshen0722
lilyshen0722 marked this pull request as ready for review October 21, 2026 16:28
@lilyshen0722
lilyshen0722 added this pull request to the merge queue Oct 21, 2026
Merged via the queue into main with commit 0132e85 Oct 21, 2026
23 checks passed
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