diff --git a/frontend/app/index.tsx b/frontend/app/index.tsx index bbf4c17..c6f17c7 100644 --- a/frontend/app/index.tsx +++ b/frontend/app/index.tsx @@ -1,5 +1,5 @@ import { useEffect, useRef, useState } from 'react'; -import { Alert, Platform, SafeAreaView } from 'react-native'; +import { ActivityIndicator, Alert, Platform, SafeAreaView, Text, TouchableOpacity, View } from 'react-native'; import { useOAuth, useAuth } from "@clerk/clerk-expo"; import { useRouter } from 'expo-router'; import { StatusBar } from 'expo-status-bar'; @@ -8,6 +8,7 @@ import Animated, { useAnimatedScrollHandler, useAnimatedStyle } from 'react-nati import { UI } from '../constants/colors'; import DesktopLanding from '../components/landing/DesktopLanding'; import { useDesktopLayout } from '../utils/useDesktopLayout'; +import { recordWebStartup } from '../utils/startupTiming'; import { LandingViewportProvider, useLandingViewport } from '../components/landing/landingMotion'; import { HeroSection, @@ -44,6 +45,7 @@ function LandingPageContent() { const { startOAuthFlow } = useOAuth({ strategy: "oauth_google" }); const [loginRequested, setLoginRequested] = useState(false); const [sessionRetry, setSessionRetry] = useState(0); + const [sessionError, setSessionError] = useState(null); const oauthPending = useRef(false); const { scrollY, viewportHeight, scrollDirection } = useLandingViewport(); @@ -63,15 +65,20 @@ function LandingPageContent() { useEffect(() => { if (!isLoaded) return; + recordWebStartup('session-ready'); let cancelled = false; + setSessionError(null); async function initialize() { if (!isSignedIn) { clearSyncedUser(); return; } const token = await getToken(); - if (!token) return; + recordWebStartup('session-token-ready'); + if (!token) throw new Error('Session token is unavailable'); + if (cancelled) return; const user = await syncUser(token); + recordWebStartup('account-ready'); if (cancelled) return; if (user.username) { router.replace("/(tabs)/ask"); @@ -82,36 +89,39 @@ function LandingPageContent() { initialize().catch(error => { if (cancelled) return; console.warn('Unable to initialize session', error); - if (sessionRetry > 0) { - showSignInError('You are signed in, but PathFinder could not connect to the server. Please try again.'); - } + setSessionError('You are signed in, but PathFinder could not connect to the server. Please try again.'); }); return () => { cancelled = true; }; }, [isLoaded, isSignedIn, getToken, router, sessionRetry]); useEffect(() => { - if (!loginRequested || !isLoaded || oauthPending.current) return; - // A failed backend sync does not end the Google session. Retry that sync. + if (!loginRequested || !isLoaded) return; if (isSignedIn) { + oauthPending.current = false; setLoginRequested(false); - setSessionRetry(attempt => attempt + 1); return; } + if (oauthPending.current) return; oauthPending.current = true; // Load destination code during OAuth, without mounting either screen. void Promise.all([import('./(tabs)/ask'), import('./(tabs)/profile')]).catch(console.warn); async function login() { + let activated = false; try { const { createdSessionId, setActive } = await startOAuthFlow(); if (createdSessionId && setActive) { await setActive({ session: createdSessionId }); + activated = true; + // Keep the landing page hidden until useAuth observes the active session. + } else { + setLoginRequested(false); } } catch (err) { console.warn('OAuth error', err); showSignInError('Google sign-in could not complete. Please try again.'); - } finally { - oauthPending.current = false; setLoginRequested(false); + } finally { + if (!activated) oauthPending.current = false; } } void login(); @@ -119,6 +129,34 @@ function LandingPageContent() { const onPressGoogle = () => setLoginRequested(true); + // Only confirmed signed-out visitors should see the public homepage. + if (!isLoaded || isSignedIn || loginRequested) { + return ( + + {isLoaded && isSignedIn && sessionError ? ( + + + {sessionError} + + { + // A failed backend sync does not end the Google session. Retry that sync. + setSessionError(null); + setSessionRetry(attempt => attempt + 1); + }} + style={{ backgroundColor: UI.accent, borderRadius: 12, paddingHorizontal: 24, paddingVertical: 14 }} + > + Try again + + + ) : ( + + )} + + ); + } + if (desktop) return ; return ( diff --git a/frontend/components/landing/DesktopLanding.web.tsx b/frontend/components/landing/DesktopLanding.web.tsx index bf11962..4f28560 100644 --- a/frontend/components/landing/DesktopLanding.web.tsx +++ b/frontend/components/landing/DesktopLanding.web.tsx @@ -1,4 +1,7 @@ import { Asset } from 'expo-asset'; +import { useFonts } from 'expo-font'; +import { ArchivoNarrow_400Regular } from '@expo-google-fonts/archivo-narrow/400Regular'; +import { ArchivoNarrow_700Bold } from '@expo-google-fonts/archivo-narrow/700Bold'; import { Feather, MaterialCommunityIcons } from '@expo/vector-icons'; import { JOURNEY_TAGS, @@ -233,6 +236,7 @@ function LandingStory() { +

Our vision

@@ -290,11 +294,15 @@ function LandingStory() {

+
); } export default function DesktopLanding({ onPressGoogle }: DesktopLandingProps) { + // Load these weights only when the desktop homepage is mounted. + useFonts({ ArchivoNarrow_400Regular, ArchivoNarrow_700Bold }); + return (
diff --git a/frontend/components/landing/desktopLanding.css b/frontend/components/landing/desktopLanding.css index 8a9caf1..063b196 100644 --- a/frontend/components/landing/desktopLanding.css +++ b/frontend/components/landing/desktopLanding.css @@ -1,4 +1,8 @@ .pf-landing .continuity { + min-height: 100vh; + min-height: 100dvh; + display: grid; + grid-template-rows: auto 1fr; background: #0a0f1d; color: #fff; } @@ -53,6 +57,7 @@ color: #ff9652; } .pf-landing .continuity .hero { + margin: 0 auto; display: grid; grid-template-columns: minmax(0, 1.07fr) minmax(0, 1fr); gap: clamp(35px, 6vw, 105px); @@ -66,11 +71,11 @@ margin: 0; } .pf-landing .continuity h1 { - font-size: clamp(56px, 5.05vw, 80px); - line-height: 1.02; + font-size: clamp(42px, 3.8vw, 64px); + line-height: 1.08; font-weight: 400; letter-spacing: -0.03em; - font-family: InstrumentSerif_400Regular, Georgia, serif; + font-family: ArchivoNarrow_700Bold, Arial, sans-serif; } .pf-landing .continuity h1 .line { display: block; @@ -122,6 +127,7 @@ min-width: 0; } .pf-landing .continuity .journey h2 { + font-family: ArchivoNarrow_400Regular, Arial, sans-serif; color: #142235; font-size: clamp(23px, 1.81vw, 30px); font-weight: 400; @@ -182,6 +188,7 @@ box-shadow: none; } .pf-landing .continuity .stage { + font-family: ArchivoNarrow_400Regular, Arial, sans-serif; font-size: 14px; line-height: 19px; font-weight: 400; @@ -218,7 +225,7 @@ background: var(--st-paper); color: var(--st-text); font: - 400 16px/1.65 Manrope_400Regular, + 400 16px/1.65 ArchivoNarrow_400Regular, Arial, sans-serif; letter-spacing: normal; @@ -261,7 +268,7 @@ .pf-story h2, .pf-story h3, .pf-story h4 { - font-family: Manrope_400Regular, Arial, sans-serif; + font-family: ArchivoNarrow_400Regular, Arial, sans-serif; color: inherit; text-transform: none; } @@ -293,7 +300,7 @@ } .pf-story .st-label { font: - 400 11px/1.4 Manrope_700Bold, + 400 11px/1.4 ArchivoNarrow_700Bold, Arial, sans-serif; letter-spacing: 0.14em; @@ -303,9 +310,9 @@ } .pf-story h2.st-heading { font: - 400 clamp(32px, 3.35vw, 52px)/1.13 InstrumentSerif_400Regular, - Georgia, - serif; + 400 clamp(30px, 3vw, 46px)/1.15 ArchivoNarrow_700Bold, + Arial, + sans-serif; letter-spacing: -0.03em; max-width: 24ch; text-wrap: balance; @@ -443,9 +450,9 @@ .pf-story .st-question-list li:before { content: '“'; font: - 27px/0.9 InstrumentSerif_400Regular, - Georgia, - serif; + 27px/0.9 ArchivoNarrow_400Regular, + Arial, + sans-serif; color: #9a4409; transform: translateY(4px); } @@ -587,7 +594,7 @@ } .pf-story .st-langs li { font: - 400 14px/1.4 Manrope_400Regular, + 400 14px/1.4 ArchivoNarrow_400Regular, 'Nirmala UI', Arial, sans-serif; @@ -629,6 +636,19 @@ line-height: 1.55; margin-top: 3px; } +.pf-story .st-closing { + min-height: 100vh; + min-height: 100dvh; + display: flex; + flex-direction: column; + background: var(--st-navy); + color: #fff; +} +.pf-story .st-closing .st-vision { + flex: 1; + display: flex; + align-items: center; +} .pf-story .st-vision, .pf-story .st-footer { background: var(--st-navy); @@ -638,16 +658,16 @@ color: #ff9a56; } .pf-story .st-vision .st-inner { - padding-bottom: clamp(50px, 5.5vw, 80px); + padding: clamp(32px, 4vh, 56px) 0; } .pf-story .st-vision blockquote { font: - 400 clamp(33px, 4.7vw, 73px)/1.04 InstrumentSerif_400Regular, - Georgia, - serif; + 400 clamp(32px, 3.4vw, 52px)/1.15 ArchivoNarrow_700Bold, + Arial, + sans-serif; letter-spacing: -0.03em; color: #f9f6ef; - max-width: 27ch; + max-width: 36ch; } .pf-story .st-vision .st-copy { color: #b1b5bd; @@ -710,7 +730,7 @@ } .pf-story .st-contact h2 { font-size: 20px; - font-family: Manrope_700Bold, Arial, sans-serif; + font-family: ArchivoNarrow_700Bold, Arial, sans-serif; color: #f6f3ed; } .pf-story .st-contact-grid { @@ -721,7 +741,7 @@ } .pf-story .st-contact-person h3 { font-size: 14px; - font-family: Manrope_700Bold, Arial, sans-serif; + font-family: ArchivoNarrow_700Bold, Arial, sans-serif; color: #f6f3ed; margin-bottom: 12px; } @@ -746,7 +766,7 @@ flex: 1; min-height: 0; overflow-y: auto; - font-family: Manrope_400Regular, Arial, sans-serif; + font-family: ArchivoNarrow_400Regular, Arial, sans-serif; color: #152238; background: #faf9f6; } @@ -756,8 +776,8 @@ box-sizing: border-box; } .pf-landing - :is(button, .journey h2, h3, h4, b, strong, .stage, .st-platform b) { - font-family: Manrope_700Bold, Arial, sans-serif; + :is(button, h3, h4, b, strong, .st-platform b) { + font-family: ArchivoNarrow_700Bold, Arial, sans-serif; font-weight: 400; } .pf-landing .login { diff --git a/frontend/docs/local-web-performance.md b/frontend/docs/local-web-performance.md index d9ef066..8af77bc 100644 --- a/frontend/docs/local-web-performance.md +++ b/frontend/docs/local-web-performance.md @@ -1,5 +1,52 @@ # Local web startup investigation +## Follow-up: localhost compression stalls returned + +On 2026-11-13, the existing server on port 8082 again delivered compressed +bundles slowly despite using the project launcher. The browser recorded about +38 seconds before React mounted and 40 seconds before fonts were ready. +The standalone HTTP probe reproduced the delay without Google authentication: + +| Request on port 8082 | Before | After restarting with loopback bypass | +| --- | ---: | ---: | +| Browser-style encoding negotiation | 38,012 ms (Brotli) | 2,855 ms (first bundle, identity) | +| Explicit gzip negotiation | 39,463 ms (gzip) | 217 ms (warm bundle, identity) | +| Explicit identity negotiation | 717 ms | 148 ms | + +The before-change identity response spent only 16 ms transferring its body; +the compressed responses spent 36–38 seconds there. This isolates the dominant +observed delay to the local compressed response path, not the public internet. +Restarting also improved server response times, so the after measurements include +both the restart and transport change. The precise cause of recurring worker-pool +contention has not been established; increasing the pool alone was insufficient. + +`scripts/local-web-transport.cjs` now asks Metro to serve uncompressed bundles +only for loopback web requests with `dev=true`. It preserves the NativeWind +middleware chain. LAN/native requests and production exports retain their usual +behavior. The tradeoff is about 9.9 MB over loopback instead of 1.7–1.8 MB +compressed; no extra internet bandwidth is used for these local bundle requests. +The same development bundle serves the OAuth callback, so this stall also +delayed completion of Google sign-in. + +Browser startup diagnostics now include `session-ready`, `session-token-ready`, +and `account-ready`, separating Clerk initialization and backend account sync +from asset loading without logging credentials or user data. + +One authenticated browser navigation after the change measured: + +- Bundle response: 240 ms. +- React mounted: 2,309 ms from navigation start. +- Fonts ready: 2,747 ms. +- Clerk session ready: 4,072 ms; token ready: 4,077 ms. +- Backend account sync complete: 7,633 ms, then navigation to Ask succeeded. + +These are development measurements, not a guarantee of sub-second login. +Account sync alone still took about 3.56 seconds and includes remote Clerk and +database work. Its individual server stages and Google's interactive login time +were not measured. Internet conditions can affect those remaining round trips. + +## Initial investigation + Measured on 2026-11-11 against `http://localhost:8081/`. HTTP timings below are separate from browser startup phases and authenticated login/logout timings. diff --git a/frontend/docs/screenshots/desktop-home-closing.png b/frontend/docs/screenshots/desktop-home-closing.png new file mode 100644 index 0000000..6a2701c Binary files /dev/null and b/frontend/docs/screenshots/desktop-home-closing.png differ diff --git a/frontend/docs/screenshots/desktop-home.png b/frontend/docs/screenshots/desktop-home.png index 8dc53b1..ef6611c 100644 Binary files a/frontend/docs/screenshots/desktop-home.png and b/frontend/docs/screenshots/desktop-home.png differ diff --git a/frontend/metro.config.js b/frontend/metro.config.js index b0963fe..0fe1db7 100644 --- a/frontend/metro.config.js +++ b/frontend/metro.config.js @@ -1,6 +1,13 @@ const { getDefaultConfig } = require("expo/metro-config"); const { withNativeWind } = require("nativewind/metro"); +const { localWebTransport } = require("./scripts/local-web-transport.cjs"); const config = getDefaultConfig(__dirname); -module.exports = withNativeWind(config, { input: "./global.css" }); +const styledConfig = withNativeWind(config, { input: "./global.css" }); +const enhanceMiddleware = styledConfig.server.enhanceMiddleware; +styledConfig.server.enhanceMiddleware = (middleware, server) => localWebTransport( + enhanceMiddleware ? enhanceMiddleware(middleware, server) : middleware +); + +module.exports = styledConfig; diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 40d392e..00386ce 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -9,6 +9,7 @@ "version": "1.0.0", "dependencies": { "@clerk/clerk-expo": "^2.19.31", + "@expo-google-fonts/archivo-narrow": "^0.4.2", "@expo-google-fonts/instrument-serif": "^0.4.1", "@expo-google-fonts/inter": "^0.4.2", "@expo-google-fonts/jetbrains-mono": "^0.4.1", @@ -3753,6 +3754,12 @@ "node": ">=18.17.0" } }, + "node_modules/@expo-google-fonts/archivo-narrow": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/@expo-google-fonts/archivo-narrow/-/archivo-narrow-0.4.2.tgz", + "integrity": "sha512-uD54ZIwnpiAKH2Bjj1awgfIMkVwDTKHICGa4y8n6oXdIXNwDPjk8EYWz8CIY3l9x3wVoSSRkd85rmueckJmZbA==", + "license": "MIT AND OFL-1.1" + }, "node_modules/@expo-google-fonts/instrument-serif": { "version": "0.4.1", "resolved": "https://registry.npmjs.org/@expo-google-fonts/instrument-serif/-/instrument-serif-0.4.1.tgz", diff --git a/frontend/package.json b/frontend/package.json index 66e8662..a66e7b5 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -4,6 +4,7 @@ "main": "expo-router/entry", "dependencies": { "@clerk/clerk-expo": "^2.19.31", + "@expo-google-fonts/archivo-narrow": "^0.4.2", "@expo-google-fonts/instrument-serif": "^0.4.1", "@expo-google-fonts/inter": "^0.4.2", "@expo-google-fonts/jetbrains-mono": "^0.4.1", diff --git a/frontend/scripts/local-web-transport.cjs b/frontend/scripts/local-web-transport.cjs new file mode 100644 index 0000000..35bcbe2 --- /dev/null +++ b/frontend/scripts/local-web-transport.cjs @@ -0,0 +1,17 @@ +// Large compressed development bundles can stall in Node's shared worker pool +// on Windows. Loopback transfers are faster without compression; keep normal +// negotiation for devices on the LAN, native bundles, and production requests. +function localWebTransport(middleware) { + return (request, response, next) => { + const address = request.socket?.remoteAddress; + const loopback = address === '127.0.0.1' || address === '::1' || address === '::ffff:127.0.0.1'; + const url = new URL(request.url || '/', 'http://localhost'); + if (loopback && url.pathname.endsWith('.bundle') && + url.searchParams.get('platform') === 'web' && url.searchParams.get('dev') === 'true') { + request.headers['accept-encoding'] = 'identity'; + } + return middleware(request, response, next); + }; +} + +module.exports = { localWebTransport }; diff --git a/frontend/tests/local-web-transport.test.mjs b/frontend/tests/local-web-transport.test.mjs new file mode 100644 index 0000000..329a152 --- /dev/null +++ b/frontend/tests/local-web-transport.test.mjs @@ -0,0 +1,62 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { createRequire } from 'node:module'; +import { createServer, get } from 'node:http'; +import { once } from 'node:events'; +import { gzipSync } from 'node:zlib'; +import { localWebTransport } from '../scripts/local-web-transport.cjs'; + +const require = createRequire(import.meta.url); +const compression = require('compression'); +const bundle = 'console.log("PathFinder");\n'.repeat(200); + +test('localhost web bundle bypasses actual compression even when compression runs first', async () => { + const transport = localWebTransport((_request, response) => { + response.setHeader('Content-Type', 'application/javascript'); + response.end(bundle); + }); + const compress = compression(); + const server = createServer((request, response) => compress(request, response, () => transport(request, response))); + server.listen(0, '127.0.0.1'); + await once(server, 'listening'); + try { + const read = path => new Promise((resolve, reject) => { + get({ hostname: '127.0.0.1', port: server.address().port, path, headers: { 'Accept-Encoding': 'gzip' } }, response => { + const chunks = []; + response.on('data', chunk => chunks.push(chunk)); + response.on('end', () => resolve({ encoding: response.headers['content-encoding'], body: Buffer.concat(chunks) })); + response.on('error', reject); + }).on('error', reject); + }); + const web = await read('/entry.bundle?platform=web&dev=true'); + assert.equal(web.encoding, undefined); + assert.equal(web.body.toString(), bundle); + const native = await read('/entry.bundle?platform=ios&dev=true'); + assert.equal(native.encoding, 'gzip'); + assert.deepEqual(native.body, gzipSync(bundle)); + } finally { + await new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve())); + } +}); + +test('LAN, production, fonts, and unrelated requests retain compression negotiation', () => { + for (const [address, url] of [ + ['192.168.1.20', '/entry.bundle?platform=web&dev=true'], + ['127.0.0.1', '/entry.bundle?platform=web&dev=false'], + ['127.0.0.1', '/font.ttf'], + ['127.0.0.1', '/auth/sync'], + [undefined, '/entry.bundle?platform=web&dev=true'], + ]) { + const request = { socket: { remoteAddress: address }, url, headers: { 'accept-encoding': 'gzip, br' } }; + const response = {}, next = () => {}; + let calls = 0; + localWebTransport((req, res, callback) => { + calls++; + assert.equal(req, request); + assert.equal(res, response); + assert.equal(callback, next); + assert.equal(req.headers['accept-encoding'], 'gzip, br'); + })(request, response, next); + assert.equal(calls, 1); + } +}); diff --git a/frontend/tests/startup.test.mjs b/frontend/tests/startup.test.mjs index 0bfb03b..c45131a 100644 --- a/frontend/tests/startup.test.mjs +++ b/frontend/tests/startup.test.mjs @@ -73,7 +73,7 @@ test('Clerk starts while fonts are still loading', () => { assert.ok(includes(tree, 'ClerkProvider')); assert.ok(includes(tree, 'Spinner')); }); -test('public homepage does not wait for Clerk or unrelated app fonts', () => { +test('home route mounts its session gate without waiting for unrelated app fonts', () => { const tree = renderRoot({ home: true, landingReady: true, appReady: false }); assert.ok(includes(tree, 'Slot')); assert.ok(!includes(tree, 'ClerkLoaded')); @@ -105,11 +105,11 @@ test('failed logout does not navigate or pretend the session ended', async () => assert.equal(navigated, false); }); -function landingSession({ signedIn = true, syncUser, startOAuthFlow = async () => ({}) }) { - const hooks = [], navigations = [], alerts = []; +function landingSession({ signedIn = true, loaded = true, getToken = async () => 'test-token', syncUser, startOAuthFlow = async () => ({}), refreshOAuth = false }) { + const hooks = [], navigations = [], alerts = [], renders = []; let cursor = 0, pendingEffects = [], scheduled = false, landing; const router = { replace: path => navigations.push(path) }; - const auth = { isLoaded: true, isSignedIn: signedIn, getToken: async () => 'test-token' }; + const auth = { isLoaded: loaded, isSignedIn: signedIn, getToken }; const schedule = () => { if (scheduled) return; scheduled = true; @@ -146,8 +146,17 @@ function landingSession({ signedIn = true, syncUser, startOAuthFlow = async () = const page = compile('../app/index.tsx', name => { if (name === 'react') return react; if (name === 'react/jsx-runtime') return { jsx, jsxs: jsx }; - if (name === 'react-native') return { Platform: { OS: 'ios' }, Alert: { alert: (_title, message) => alerts.push(message) } }; - if (name === '@clerk/clerk-expo') return { useAuth: () => auth, useOAuth: () => ({ startOAuthFlow }) }; + if (name === 'react-native') return { + Platform: { OS: 'ios' }, Alert: { alert: (_title, message) => alerts.push(message) }, + View: 'View', Text: 'Text', TouchableOpacity: 'Button', ActivityIndicator: 'Spinner', + }; + if (name.includes('constants/colors')) return { UI: {} }; + if (name.includes('startupTiming')) return { recordWebStartup() {} }; + if (name.includes('DesktopLanding')) return { __esModule: true, default: 'DesktopLanding' }; + if (name === '@clerk/clerk-expo') return { + useAuth: () => auth, + useOAuth: () => ({ startOAuthFlow: refreshOAuth ? () => startOAuthFlow() : startOAuthFlow }), + }; if (name === 'expo-router') return { useRouter: () => router }; if (name.includes('auth.api')) return { syncUser, clearSyncedUser() {} }; if (name.includes('useDesktopLayout')) return { useDesktopLayout: () => true }; @@ -160,10 +169,23 @@ function landingSession({ signedIn = true, syncUser, startOAuthFlow = async () = pendingEffects = []; const content = page.default().props.children; landing = content.type(); + renders.push(landing); for (const effect of pendingEffects) effect(); } render(); - return { press: () => landing.props.onPressGoogle(), navigations, alerts }; + function find(tree, type) { + if (!tree || typeof tree !== 'object') return; + if (tree.type === type) return tree; + return [tree.props?.children].flat().map(child => find(child, type)).find(Boolean); + } + return { + press: () => landing.props.onPressGoogle(), + retry: () => find(landing, 'Button').props.onPress(), + get tree() { return landing; }, + get signIn() { return landing.props.onPressGoogle; }, + setAuth: update => { Object.assign(auth, update); render(); }, + navigations, alerts, renders, + }; } const settleSession = () => new Promise(resolve => setImmediate(resolve)); @@ -179,11 +201,14 @@ test('signed-in visitor retries failed backend sync without reopening Google OAu }); await settleSession(); assert.deepEqual(page.navigations, []); - page.press(); + assert.ok(!includes(page.tree, 'DesktopLanding')); + assert.ok(includes(page.tree, 'Button')); + page.retry(); await settleSession(); assert.equal(syncCalls, 2); assert.equal(oauthCalls, 0); assert.deepEqual(page.navigations, ['/(tabs)/ask']); + assert.ok(page.renders.every(tree => !includes(tree, 'DesktopLanding'))); }); test('signed-in visitor without a username still reaches profile setup', async () => { @@ -203,23 +228,112 @@ test('signed-out visitor starts Google OAuth once, even with repeated clicks', a return new Promise(resolve => { finishOAuth = resolve; }); }, }); - page.press(); + const clickSignIn = page.signIn; + clickSignIn(); await settleSession(); - page.press(); + clickSignIn(); await settleSession(); assert.equal(oauthCalls, 1); finishOAuth({ createdSessionId: 'test-session', setActive: async session => activeSessions.push(session) }); await settleSession(); assert.deepEqual(activeSessions, [{ session: 'test-session' }]); + assert.ok(includes(page.tree, 'Spinner')); + assert.ok(page.renders.slice(1).every(tree => !includes(tree, 'DesktopLanding'))); }); test('failed manual session retry gives feedback without claiming success', async () => { const page = landingSession({ syncUser: async () => { throw Error('offline'); } }); await settleSession(); assert.deepEqual(page.alerts, []); + page.retry(); + await settleSession(); + assert.deepEqual(page.navigations, []); + assert.ok(includes(page.tree, 'Button')); + assert.match(JSON.stringify(page.tree), /could not connect to the server/); + assert.ok(page.renders.every(tree => !includes(tree, 'DesktopLanding'))); +}); + +test('unknown session never renders the homepage; confirmed signed-out session does', async () => { + let syncCalls = 0; + const page = landingSession({ loaded: false, signedIn: undefined, syncUser: async () => { syncCalls++; } }); + assert.ok(includes(page.tree, 'Spinner')); + assert.ok(!includes(page.tree, 'DesktopLanding')); + page.setAuth({ isLoaded: true, isSignedIn: false }); + await settleSession(); + assert.ok(includes(page.tree, 'DesktopLanding')); + assert.equal(syncCalls, 0); +}); + +test('restored session stays behind the loader until backend sync and navigation finish', async () => { + let finishSync; + const page = landingSession({ loaded: false, syncUser: () => new Promise(resolve => { finishSync = resolve; }) }); + page.setAuth({ isLoaded: true, isSignedIn: true }); + await settleSession(); + assert.ok(includes(page.tree, 'Spinner')); + assert.deepEqual(page.navigations, []); + finishSync({ username: 'existing-user' }); + await settleSession(); + assert.deepEqual(page.navigations, ['/(tabs)/ask']); + assert.ok(page.renders.every(tree => !includes(tree, 'DesktopLanding'))); +}); + +test('successful OAuth does not flash the homepage before Clerk publishes the session', async () => { + let syncCalls = 0, oauthCalls = 0; + const page = landingSession({ + signedIn: false, + refreshOAuth: true, + startOAuthFlow: async () => { oauthCalls++; return { createdSessionId: 'session', setActive: async () => {} }; }, + syncUser: async () => { syncCalls++; return { username: 'existing-user' }; }, + }); page.press(); await settleSession(); + assert.ok(includes(page.tree, 'Spinner')); + page.setAuth({ isSignedIn: false }); + await settleSession(); + assert.equal(oauthCalls, 1); + page.setAuth({ isSignedIn: true }); + await settleSession(); + assert.equal(syncCalls, 1); + assert.deepEqual(page.navigations, ['/(tabs)/ask']); + assert.ok(page.renders.slice(1).every(tree => !includes(tree, 'DesktopLanding'))); +}); + +for (const failure of ['cancelled', 'failed', 'activation failed']) { + test(`${failure} OAuth returns signed-out visitors to the homepage`, async () => { + const page = landingSession({ + signedIn: false, + syncUser: async () => { throw Error('must not sync'); }, + startOAuthFlow: async () => { + if (failure === 'failed') throw Error('OAuth unavailable'); + if (failure === 'activation failed') return { + createdSessionId: 'session', setActive: async () => { throw Error('activation unavailable'); }, + }; + return {}; + }, + }); + page.press(); + await settleSession(); + assert.ok(includes(page.tree, 'DesktopLanding')); + assert.deepEqual(page.navigations, []); + assert.equal(page.alerts.length, failure === 'cancelled' ? 0 : 1); + }); +} + +test('missing session token offers retry instead of leaving a permanent spinner', async () => { + const page = landingSession({ getToken: async () => null, syncUser: async () => { throw Error('must not sync'); } }); + await settleSession(); + assert.ok(includes(page.tree, 'Button')); + assert.ok(!includes(page.tree, 'DesktopLanding')); + assert.deepEqual(page.navigations, []); +}); + +test('sign-out reveals the homepage and ignores stale backend sync completion', async () => { + let finishSync; + const page = landingSession({ syncUser: () => new Promise(resolve => { finishSync = resolve; }) }); + await settleSession(); + page.setAuth({ isSignedIn: false }); + finishSync({ username: 'previous-user' }); + await settleSession(); + assert.ok(includes(page.tree, 'DesktopLanding')); assert.deepEqual(page.navigations, []); - assert.equal(page.alerts.length, 1); - assert.match(page.alerts[0], /could not connect to the server/); });