mirror of
https://github.com/nomadkaraoke/karaoke-gen.git
synced 2026-11-20 13:07:57 +09:00
Fix auth flash and card padding (#310)
## Summary - Fix "Sign in required" flash during SPA redirect by waiting for zustand hydration - Add vertical padding to Card component for better spacing ## Changes - **auth.ts**: Add `hasHydrated` flag and `onRehydrateStorage` handler - **client.tsx**: Wait for `hasHydrated` before showing "not_authenticated" - **card.tsx**: Add `py-6` to Card component ## Test plan - [x] Build passes - [ ] Navigate to lyrics review - no more "Sign in required" flash - [ ] Dashboard cards have proper vertical padding @coderabbitai ignore --------- Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
b2befccd5b
commit
6394b33fbb
5 files changed
+247
-5
No files matched your search
@@ -130,7 +130,7 @@ export function JobRouterClient() {
|
||||
}
|
||||
}, [storedRedirectPath, jobId])
|
||||
|
||||
const { user, isLoading: authLoading } = useAuth()
|
||||
const { user, isLoading: authLoading, hasHydrated } = useAuth()
|
||||
const [accessState, setAccessState] = useState<AccessState>({ status: "loading" })
|
||||
|
||||
useEffect(() => {
|
||||
@@ -163,8 +163,9 @@ export function JobRouterClient() {
|
||||
return
|
||||
}
|
||||
|
||||
// Wait for auth to finish loading
|
||||
if (authLoading) return
|
||||
// Wait for auth to finish loading and hydration to complete
|
||||
// This prevents a flash of "Sign in required" before auth state is restored from localStorage
|
||||
if (authLoading || !hasHydrated) return
|
||||
|
||||
// Must be authenticated
|
||||
if (!user) {
|
||||
@@ -215,7 +216,7 @@ export function JobRouterClient() {
|
||||
}
|
||||
|
||||
checkAccess()
|
||||
}, [jobId, routeType, user, authLoading])
|
||||
}, [jobId, routeType, user, authLoading, hasHydrated])
|
||||
|
||||
// Loading state
|
||||
if (accessState.status === "loading") {
|
||||
|
||||
@@ -7,7 +7,7 @@ function Card({ className, ...props }: React.ComponentProps<'div'>) {
|
||||
<div
|
||||
data-slot="card"
|
||||
className={cn(
|
||||
'bg-card text-card-foreground flex flex-col gap-1 rounded-lg border shadow-sm',
|
||||
'bg-card text-card-foreground flex flex-col gap-1 rounded-lg border py-6 shadow-sm',
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
|
||||
@@ -10,6 +10,9 @@ interface AuthStore {
|
||||
isLoading: boolean
|
||||
error: string | null
|
||||
|
||||
// Hydration state - true once zustand has loaded persisted data
|
||||
hasHydrated: boolean
|
||||
|
||||
// Impersonation state (not persisted)
|
||||
isImpersonating: boolean
|
||||
originalAdminToken: string | null
|
||||
@@ -22,6 +25,7 @@ interface AuthStore {
|
||||
logout: () => Promise<void>
|
||||
updateCredits: (credits: number) => void
|
||||
clearError: () => void
|
||||
setHasHydrated: (state: boolean) => void
|
||||
|
||||
// For legacy token-based auth (admin tokens)
|
||||
loginWithToken: (token: string) => Promise<boolean>
|
||||
@@ -37,12 +41,15 @@ export const useAuth = create<AuthStore>()(
|
||||
user: null,
|
||||
isLoading: false,
|
||||
error: null,
|
||||
hasHydrated: false,
|
||||
|
||||
// Impersonation state
|
||||
isImpersonating: false,
|
||||
originalAdminToken: null,
|
||||
impersonatedUserEmail: null,
|
||||
|
||||
setHasHydrated: (state: boolean) => set({ hasHydrated: state }),
|
||||
|
||||
sendMagicLink: async (email: string) => {
|
||||
set({ isLoading: true, error: null })
|
||||
try {
|
||||
@@ -259,6 +266,10 @@ export const useAuth = create<AuthStore>()(
|
||||
name: "nomad-karaoke-auth",
|
||||
// Only persist user, not impersonation state (impersonation should not survive page refresh)
|
||||
partialize: (state) => ({ user: state.user }),
|
||||
onRehydrateStorage: () => (state) => {
|
||||
// Called when hydration is complete
|
||||
state?.setHasHydrated(true)
|
||||
},
|
||||
},
|
||||
),
|
||||
)
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
import { chromium } from 'playwright';
|
||||
|
||||
const BASE_URL = 'https://gen.nomadkaraoke.com';
|
||||
const ADMIN_TOKEN = '9021de39710208e5dc31b6b28baf8e94172843fff177a9d5435135dd5388b6f8';
|
||||
const JOB_ID = '26391a79';
|
||||
const CACHE_BUSTER = Date.now();
|
||||
|
||||
async function test() {
|
||||
const browser = await chromium.launch({ headless: true });
|
||||
const context = await browser.newContext();
|
||||
const page = await context.newPage();
|
||||
|
||||
const consoleErrors = [];
|
||||
const failedRequests = [];
|
||||
|
||||
// Capture console errors
|
||||
page.on('console', msg => {
|
||||
const text = msg.text();
|
||||
const type = msg.type();
|
||||
if (type === 'error' || text.toLowerCase().includes('error') || text.toLowerCase().includes('fail')) {
|
||||
consoleErrors.push({ type, text });
|
||||
}
|
||||
});
|
||||
|
||||
// Capture failed HTTP requests (excluding expected ones)
|
||||
page.on('response', response => {
|
||||
const status = response.status();
|
||||
const url = response.url();
|
||||
// Ignore YouTube, Cloudflare RUM, and static 404 redirects
|
||||
if (status >= 400 &&
|
||||
!url.includes('youtube.com') &&
|
||||
!url.includes('cdn-cgi/rum') &&
|
||||
!url.includes('__next._tree')) {
|
||||
failedRequests.push({
|
||||
url,
|
||||
status,
|
||||
statusText: response.statusText()
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
console.log('\n=== Final Production Test ===\n');
|
||||
|
||||
try {
|
||||
// Step 1: Set auth token
|
||||
console.log('Step 1: Navigate to /app and set auth token');
|
||||
await page.goto(BASE_URL + '/app?_cb=' + CACHE_BUSTER, { waitUntil: 'networkidle' });
|
||||
await page.evaluate((token) => {
|
||||
localStorage.setItem('karaoke_access_token', token);
|
||||
}, ADMIN_TOKEN);
|
||||
await page.reload({ waitUntil: 'networkidle' });
|
||||
|
||||
// Step 2: Navigate to review page
|
||||
console.log('Step 2: Navigate to /app/jobs/' + JOB_ID + '/review/');
|
||||
await page.goto(BASE_URL + '/app/jobs/' + JOB_ID + '/review/?_cb=' + CACHE_BUSTER, {
|
||||
waitUntil: 'networkidle',
|
||||
timeout: 30000
|
||||
});
|
||||
await page.waitForTimeout(5000);
|
||||
|
||||
// Check URL (should be updated via history.replaceState)
|
||||
const currentUrl = page.url();
|
||||
console.log('\n--- URL Check ---');
|
||||
console.log('Final URL:', currentUrl);
|
||||
if (currentUrl.includes(JOB_ID + '/review')) {
|
||||
console.log('URL contains job ID and review path');
|
||||
} else if (currentUrl.endsWith('/app/jobs/')) {
|
||||
console.log('URL was NOT updated (still at /app/jobs/)');
|
||||
}
|
||||
|
||||
// Check page content
|
||||
const bodyText = await page.evaluate(() => document.body.innerText);
|
||||
console.log('\n--- Page Content Check ---');
|
||||
if (bodyText.includes('Lyrics Transcription Review')) {
|
||||
console.log('Page header found: "Lyrics Transcription Review"');
|
||||
}
|
||||
if (bodyText.includes('Failed to load')) {
|
||||
console.log('ERROR: Page shows failure message');
|
||||
}
|
||||
|
||||
// Check logo
|
||||
console.log('\n--- Logo Check ---');
|
||||
const logoLoaded = await page.evaluate(() => {
|
||||
const img = document.querySelector('img[alt="Nomad Karaoke"]');
|
||||
return img ? img.complete && img.naturalHeight > 0 : false;
|
||||
});
|
||||
console.log('Logo loaded:', logoLoaded);
|
||||
|
||||
// Check for audio element
|
||||
console.log('\n--- Audio Check ---');
|
||||
const audioSrc = await page.evaluate(() => {
|
||||
const audio = document.querySelector('audio');
|
||||
return audio ? audio.src : null;
|
||||
});
|
||||
if (audioSrc) {
|
||||
console.log('Audio src:', audioSrc);
|
||||
if (audioSrc.includes('/api/review/')) {
|
||||
console.log('Audio URL uses correct /api/review/ path');
|
||||
}
|
||||
} else {
|
||||
console.log('No audio element found on page');
|
||||
}
|
||||
|
||||
// Report failed requests
|
||||
console.log('\n--- Failed HTTP Requests (excluding expected) ---');
|
||||
const relevantFailures = failedRequests.filter(r =>
|
||||
!r.url.includes(JOB_ID + '/review') // Exclude initial 404 redirect
|
||||
);
|
||||
if (relevantFailures.length === 0) {
|
||||
console.log('No unexpected failed requests');
|
||||
} else {
|
||||
relevantFailures.forEach((req, i) => {
|
||||
console.log((i + 1) + '. HTTP ' + req.status + ' ' + req.statusText + ': ' + req.url.substring(0, 100));
|
||||
});
|
||||
}
|
||||
|
||||
// Report console errors
|
||||
console.log('\n--- Console Errors ---');
|
||||
const relevantErrors = consoleErrors.filter(e =>
|
||||
!e.text.includes('404') // Exclude 404 console errors from initial redirect
|
||||
);
|
||||
if (relevantErrors.length === 0) {
|
||||
console.log('No relevant console errors');
|
||||
} else {
|
||||
relevantErrors.forEach((err, i) => {
|
||||
console.log((i + 1) + '. [' + err.type + '] ' + err.text.substring(0, 150));
|
||||
});
|
||||
}
|
||||
|
||||
// Step 3: Test reload
|
||||
console.log('\n--- Reload Test ---');
|
||||
await page.reload({ waitUntil: 'networkidle' });
|
||||
await page.waitForTimeout(3000);
|
||||
const reloadUrl = page.url();
|
||||
const reloadBody = await page.evaluate(() => document.body.innerText);
|
||||
console.log('URL after reload:', reloadUrl);
|
||||
if (reloadBody.includes('Lyrics Transcription Review')) {
|
||||
console.log('Reload SUCCESS: Page still shows lyrics review');
|
||||
} else if (reloadBody.includes('Page not found')) {
|
||||
console.log('Reload FAILED: Shows "Page not found"');
|
||||
} else {
|
||||
console.log('Reload result unclear. Content preview:', reloadBody.substring(0, 100));
|
||||
}
|
||||
|
||||
} catch (e) {
|
||||
console.log('Error:', e.message);
|
||||
}
|
||||
|
||||
await browser.close();
|
||||
}
|
||||
|
||||
test().catch(console.error);
|
||||
@@ -0,0 +1,78 @@
|
||||
import { chromium } from 'playwright';
|
||||
|
||||
const BASE_URL = 'https://gen.nomadkaraoke.com';
|
||||
const ADMIN_TOKEN = '9021de39710208e5dc31b6b28baf8e94172843fff177a9d5435135dd5388b6f8';
|
||||
const JOB_ID = '26391a79';
|
||||
const CACHE_BUSTER = Date.now();
|
||||
|
||||
async function test() {
|
||||
const browser = await chromium.launch({ headless: true });
|
||||
const context = await browser.newContext();
|
||||
const page = await context.newPage();
|
||||
|
||||
// Log ALL console messages
|
||||
page.on('console', msg => {
|
||||
console.log('CONSOLE [' + msg.type() + ']:', msg.text());
|
||||
});
|
||||
|
||||
console.log('\n=== URL Debug Test ===\n');
|
||||
|
||||
try {
|
||||
// Set auth token
|
||||
await page.goto(BASE_URL + '/app', { waitUntil: 'networkidle' });
|
||||
await page.evaluate((token) => {
|
||||
localStorage.setItem('karaoke_access_token', token);
|
||||
}, ADMIN_TOKEN);
|
||||
|
||||
// Navigate to review page and watch URL changes
|
||||
console.log('Navigating to review page...');
|
||||
|
||||
// Watch URL changes
|
||||
let urlLog = [];
|
||||
page.on('framenavigated', frame => {
|
||||
if (frame === page.mainFrame()) {
|
||||
urlLog.push({ time: Date.now(), url: frame.url() });
|
||||
}
|
||||
});
|
||||
|
||||
await page.goto(BASE_URL + '/app/jobs/' + JOB_ID + '/review/?_cb=' + CACHE_BUSTER, {
|
||||
waitUntil: 'domcontentloaded'
|
||||
});
|
||||
|
||||
// Check sessionStorage before it gets consumed
|
||||
const storedPath = await page.evaluate(() => {
|
||||
return sessionStorage.getItem('spa-redirect-path');
|
||||
});
|
||||
console.log('SessionStorage spa-redirect-path:', storedPath);
|
||||
|
||||
await page.waitForTimeout(3000);
|
||||
|
||||
console.log('\nURL history:');
|
||||
urlLog.forEach((entry, i) => {
|
||||
console.log(i + 1 + '. ' + entry.url);
|
||||
});
|
||||
|
||||
console.log('\nFinal URL:', page.url());
|
||||
|
||||
// Check if history.replaceState is being called
|
||||
const historyState = await page.evaluate(() => {
|
||||
return {
|
||||
url: window.location.href,
|
||||
pathname: window.location.pathname,
|
||||
historyLength: window.history.length
|
||||
};
|
||||
});
|
||||
console.log('History state:', historyState);
|
||||
|
||||
// Check body content
|
||||
const content = await page.evaluate(() => document.body.innerText.substring(0, 200));
|
||||
console.log('\nPage content preview:', content);
|
||||
|
||||
} catch (e) {
|
||||
console.log('Error:', e.message);
|
||||
}
|
||||
|
||||
await browser.close();
|
||||
}
|
||||
|
||||
test().catch(console.error);
|
||||
Reference in new issue
Block a user