fix: 修复白屏 — SW networkFirst + initSession try/catch + Error Boundary

1. sw.js: /index.html 导航请求使用 networkFirst 策略替代 cacheFirst,
   避免旧 SW 缓存不存在的旧 hash 资源导致 404 白屏
2. App.tsx: initSession 添加 try/catch 异常保护,防止初始化
   失败导致整个 React 树崩溃
3. 新建 ErrorBoundary.tsx: React 错误边界组件,捕获渲染异常
   显示友好错误页面而非白屏
This commit is contained in:
2026-05-20 21:29:37 +08:00
parent 4058aae1e4
commit 76ef31e153
3 changed files with 167 additions and 66 deletions
+38 -7
View File
@@ -38,18 +38,28 @@ self.addEventListener('message', (event) => {
}
});
// Fetch: 缓存优先策略(对 API 请求使用网络优先)
// Fetch: HTML 导航请求使用 networkFirst,静态资源使用 cacheFirst
self.addEventListener('fetch', (event) => {
const url = new URL(event.request.url);
// API 请求:网络优先,失败时返回离线 JSON
if (url.pathname.startsWith('/api/')) {
event.respondWith(networkFirst(event.request));
} else if (url.pathname.startsWith('/ws')) {
// WebSocket 连接不缓存
// WebSocket 连接不缓存
if (url.pathname.startsWith('/ws')) {
event.respondWith(fetch(event.request));
return;
}
// 导航请求(HTML 页面):网络优先,避免旧缓存引用不存在的 hash 资源 → 白屏
const isNavigation =
event.request.mode === 'navigate' ||
(event.request.headers.get('Accept') || '').includes('text/html');
if (isNavigation) {
event.respondWith(networkFirstForHTML(event.request));
} else if (url.pathname.startsWith('/api/')) {
// API 请求:网络优先,失败时返回离线 JSON
event.respondWith(networkFirst(event.request));
} else {
// 静态资源:缓存优先
// 静态资源JS/CSS/图片等):缓存优先
event.respondWith(cacheFirst(event.request));
}
});
@@ -73,6 +83,27 @@ async function cacheFirst(request) {
}
}
async function networkFirstForHTML(request) {
try {
const response = await fetch(request);
if (response.ok) {
const cache = await caches.open(CACHE_NAME);
cache.put(request, response.clone());
}
return response;
} catch (e) {
const cached = await caches.match(request);
if (cached) return cached;
// 最终 fallback:离线页面
const offline = await caches.match('/offline.html');
if (offline) return offline;
return new Response('离线状态,请检查网络连接', {
status: 503,
headers: { 'Content-Type': 'text/plain; charset=utf-8' },
});
}
}
async function networkFirst(request) {
try {
const response = await fetch(request);
+68 -59
View File
@@ -2,6 +2,7 @@ import { useState, useEffect, useCallback, useRef } from 'react';
import { AppLayout } from '@/components/layout/AppLayout';
import { ChatContainer } from '@/components/chat/ChatContainer';
import { ChatInput } from '@/components/chat/ChatInput';
import { ErrorBoundary } from '@/components/ErrorBoundary';
import { useAuth } from '@/hooks/useAuth';
import { useChat } from '@/hooks/useChat';
import { useSessionStore, isAdminUser } from '@/store/sessionStore';
@@ -58,67 +59,73 @@ export default function App() {
if (!userId || initializedRef.current) return;
initializedRef.current = true;
const admin = isAdminUser(userId);
try {
const admin = isAdminUser(userId);
// 1. 从服务端加载会话列表
await loadSessionsFromServer(userId);
const currentSessions = useSessionStore.getState().sessions;
// 1. 从服务端加载会话列表
await loadSessionsFromServer(userId);
const currentSessions = useSessionStore.getState().sessions;
// 2. 检查 URL hash
const hashId = getSessionIdFromHash();
// 2. 检查 URL hash
const hashId = getSessionIdFromHash();
if (hashId) {
// 尝试加载 hash 指定的会话
const found = currentSessions.find((s) => s.id === hashId);
if (found) {
setCurrentSessionId(found.id);
setHashSessionId(found.id);
await loadMessagesFromServer(found.id);
return;
}
// 会话可能已被删除,尝试从 API 获取消息(404 时 catch
try {
const resp = await fetchMessages(hashId);
if (resp.messages && resp.messages.length > 0) {
// 消息存在说明会话仍有效(虽然不在列表里,可能是刚创建的)
setCurrentSessionId(hashId);
setHashSessionId(hashId);
const msgs = resp.messages.map((m: any, i: number) => ({
id: m.id ? String(m.id) : `hist_${i}_${Date.now()}`,
role: m.role,
content: m.content,
timestamp: typeof m.created_at === 'number' ? m.created_at : Date.now(),
isStreaming: false,
}));
setMessages(msgs);
useChatStore.getState().setMessages(msgs);
if (hashId) {
// 尝试加载 hash 指定的会话
const found = currentSessions.find((s) => s.id === hashId);
if (found) {
setCurrentSessionId(found.id);
setHashSessionId(found.id);
await loadMessagesFromServer(found.id);
return;
}
} catch {
// 会话不存在,回退
// 会话可能已被删除,尝试从 API 获取消息(404 时 catch
try {
const resp = await fetchMessages(hashId);
if (resp.messages && resp.messages.length > 0) {
// 消息存在说明会话仍有效(虽然不在列表里,可能是刚创建的)
setCurrentSessionId(hashId);
setHashSessionId(hashId);
const msgs = resp.messages.map((m: any, i: number) => ({
id: m.id ? String(m.id) : `hist_${i}_${Date.now()}`,
role: m.role,
content: m.content,
timestamp: typeof m.created_at === 'number' ? m.created_at : Date.now(),
isStreaming: false,
}));
setMessages(msgs);
useChatStore.getState().setMessages(msgs);
return;
}
} catch {
// 会话不存在,回退
}
// 回退:清除 hash,加载最新/主对话
setHashSessionId(null);
}
// 回退:清除 hash,加载最新/主对话
setHashSessionId(null);
}
// 3. 无 hash 或 hash 无效:加载最新会话
if (admin) {
// 管理员:确保主对话存在
const mainSession = await ensureMainSession(userId);
if (mainSession) {
setCurrentSessionId(mainSession.id);
setHashSessionId(mainSession.id);
await loadMessagesFromServer(mainSession.id);
return;
// 3. 无 hash 或 hash 无效:加载最新会话
if (admin) {
// 管理员:确保主对话存在
const mainSession = await ensureMainSession(userId);
if (mainSession) {
setCurrentSessionId(mainSession.id);
setHashSessionId(mainSession.id);
await loadMessagesFromServer(mainSession.id);
return;
}
}
}
// 普通用户:选择最新会话
if (currentSessions.length > 0) {
const latest = currentSessions[0]; // 已按 updated_at DESC 排序
setCurrentSessionId(latest.id);
setHashSessionId(latest.id);
await loadMessagesFromServer(latest.id);
// 普通用户:选择最新会话
if (currentSessions.length > 0) {
const latest = currentSessions[0]; // 已按 updated_at DESC 排序
setCurrentSessionId(latest.id);
setHashSessionId(latest.id);
await loadMessagesFromServer(latest.id);
}
} catch (error) {
console.error('[App] initSession failed:', error);
// 重置状态避免死锁,允许后续重试
initializedRef.current = false;
}
}, [userId, loadSessionsFromServer, ensureMainSession, setCurrentSessionId, setMessages, loadMessagesFromServer]);
@@ -317,13 +324,15 @@ export default function App() {
// 聊天界面
return (
<AppLayout>
<div className="flex flex-col h-full overflow-hidden">
<div className="flex-1 min-h-0 overflow-hidden">
<ChatContainer />
<ErrorBoundary>
<AppLayout>
<div className="flex flex-col h-full overflow-hidden">
<div className="flex-1 min-h-0 overflow-hidden">
<ChatContainer />
</div>
<ChatInput onSend={send} />
</div>
<ChatInput onSend={send} />
</div>
</AppLayout>
</AppLayout>
</ErrorBoundary>
);
}
@@ -0,0 +1,61 @@
import React, { Component, ErrorInfo, ReactNode } from 'react'
interface Props {
children: ReactNode
fallback?: ReactNode
}
interface State {
hasError: boolean
error: Error | null
}
export class ErrorBoundary extends Component<Props, State> {
constructor(props: Props) {
super(props)
this.state = { hasError: false, error: null }
}
static getDerivedStateFromError(error: Error): State {
return { hasError: true, error }
}
componentDidCatch(error: Error, errorInfo: ErrorInfo) {
console.error('[ErrorBoundary] Caught error:', error, errorInfo)
}
handleReset = () => {
this.setState({ hasError: false, error: null })
}
render() {
if (this.state.hasError) {
if (this.props.fallback) return this.props.fallback
return (
<div style={{
display: 'flex', flexDirection: 'column', alignItems: 'center',
justifyContent: 'center', height: '100vh', padding: '2rem',
background: '#0f172a', color: '#e2e8f0', fontFamily: 'system-ui'
}}>
<h1 style={{ fontSize: '1.5rem', marginBottom: '0.5rem' }}> </h1>
<p style={{ color: '#94a3b8', marginBottom: '1rem', maxWidth: '400px', textAlign: 'center' }}>
{this.state.error?.message || '未知错误'}
</p>
<button
onClick={this.handleReset}
style={{
padding: '0.5rem 1.5rem', borderRadius: '0.5rem',
background: '#3b82f6', color: 'white', border: 'none',
cursor: 'pointer', fontSize: '0.875rem'
}}
>
</button>
</div>
)
}
return this.props.children
}
}
export default ErrorBoundary