修复:分析会话独立加载并保持加载布局稳定

This commit is contained in:
2026-11-02 12:38:40 +08:00
parent 903fa94c00
commit 1b0274974c
5 changed files with 137 additions and 21 deletions
+50 -17
View File
@@ -967,6 +967,7 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
const initialParams = new URLSearchParams(initialSearch ?? window.location.search);
const initialSessionId = initialParams.get('sessionId') || '';
const initialTurnId = initialParams.get('turnId') || '';
const pendingTurnLink = useRef(initialTurnId);
const [initialLink] = useState(() => decodeAnalysisLinkContext(initialParams.get('context')));
const [query, setQuery] = useState('');
const [sessionId, setSessionId] = useState(initialSessionId);
@@ -974,7 +975,10 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
const [sessionContext, setSessionContext] = useState<Record<string, unknown> | null>(null);
const [sessions, setSessions] = useState<Record<string, unknown>[]>([]);
const [sessionsLoaded, setSessionsLoaded] = useState(false);
const sessionReadRequest = useRef<Promise<void> | null>(null);
const [sessionsLoading, setSessionsLoading] = useState(true);
const [sessionsError, setSessionsError] = useState('');
const showSessionsLoading = useDelayedIndicator(sessionsLoading && active, 150);
const sessionReadRequest = useRef<Promise<Record<string, unknown>[] | undefined> | null>(null);
const [turns, setTurns] = useState<Record<string, unknown>[]>([]);
const [options, setOptions] = useState<OptionsResponse | null>(null);
const [historyLoading, setHistoryLoading] = useState(true);
@@ -1108,19 +1112,43 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
}, [lastTurn, busy, turns, sessionId, active]);
const loadSessions = async () => {
if (!mounted.current || !active || document.visibilityState !== 'visible') return;
// 隐藏时的定时刷新由 useVisiblePolling 暂停;首次恢复不能因后台打开标签页而丢失。
if (!mounted.current || !active) return;
if (sessionReadRequest.current) return sessionReadRequest.current;
setSessionsLoading(true);
const request = (async () => {
try { const items = collectionItems(await api.analysisSessions()); if (mounted.current) { setSessions(items); setSessionsLoaded(true); setError(''); } }
catch (value) { if (mounted.current && !onUnauthorized(value)) setError(apiMessage(value)); }
try { const items = collectionItems(await api.analysisSessions()); if (mounted.current) { setSessions(items); setSessionsLoaded(true); setSessionsError(''); } return items; }
catch (value) { if (mounted.current && !onUnauthorized(value)) setSessionsError(apiMessage(value)); }
finally { if (mounted.current) setSessionsLoading(false); }
})();
sessionReadRequest.current = request;
try { await request; }
try { return await request; }
finally { if (sessionReadRequest.current === request) sessionReadRequest.current = null; }
};
const retrySessions = async () => { setHistoryLoading(true); await loadSessions(); if (mounted.current) setHistoryLoading(false); };
const retrySessions = async () => {
const generation = navigationGeneration.current;
setHistoryLoading(true);
const listRequest = loadSessions();
try {
const focusTurnId = pendingTurnLink.current;
let target = sessionId;
if (!target && focusTurnId) {
const turn = await api.analysisTurn(focusTurnId);
if (!mounted.current || generation !== navigationGeneration.current) return;
target = String(turn.sessionId || '');
if (!target) throw new Error('服务端未返回目标轮次所属会话');
}
if (target) await openSession(target, focusTurnId || undefined);
else {
const items = await listRequest;
const id = items && !initialLink.present ? defaultAnalysisSession(user.id, items) : '';
if (mounted.current && generation === navigationGeneration.current && id) await openSession(id);
}
} catch (value) { if (mounted.current && generation === navigationGeneration.current && !onUnauthorized(value)) setError(apiMessage(value)); }
finally { if (mounted.current && generation === navigationGeneration.current) setHistoryLoading(false); }
};
useEffect(() => {
if (!active || optionsRequestStarted.current) return;
if (!active || !initialLink.present || initialSessionId || initialTurnId || optionsRequestStarted.current) return;
optionsRequestStarted.current = true;
void optionsRead.run(async () => {
try { const value = await api.options(); if (mounted.current) { setOptions(value); setOptionsError(''); } }
@@ -1129,7 +1157,7 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
}, [active, onUnauthorized, optionsRead.run]);
const hasBackgroundTurns = sessions.some(item => analysisIsRunning(item.activeTurnStatus));
useVisiblePolling(loadSessions, 5000, active && hasBackgroundTurns);
useVisiblePolling(async () => { await loadSessions(); }, 5000, active && hasBackgroundTurns);
const wasActive = useRef(active);
useEffect(() => {
if (active && !wasActive.current && hasBackgroundTurns) void loadSessions();
@@ -1232,6 +1260,7 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
}, [active, refreshKey]);
const openSession = async (id: string, focusTurnId?: string): Promise<boolean> => {
if (!focusTurnId) pendingTurnLink.current = '';
userSelectionMade.current = true;
beginAnalysisSelection(user.id);
const generation = ++navigationGeneration.current;
@@ -1271,12 +1300,14 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
setLastTurn(restored);
if (analysisIsRunning(restored.status)) void followTurn(selectedTurnId, String(restored.question || ''), id);
}
pendingTurnLink.current = '';
return true;
} catch (value) { if (current() && !onUnauthorized(value)) setError(apiMessage(value)); return false; }
finally { if (current()) setHistoryLoading(false); }
};
const newSession = () => {
pendingTurnLink.current = '';
userSelectionMade.current = true;
beginAnalysisSelection(user.id);
setQueuedFollowup('');
@@ -1463,10 +1494,7 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
const requestedAt = navigationGeneration.current;
setHistoryLoading(true);
try {
const items = collectionItems(await api.analysisSessions());
if (!mounted.current || requestedAt !== navigationGeneration.current) return;
setSessions(items);
setSessionsLoaded(true);
const listRequest = loadSessions();
let linkedSession = initialSessionId;
if (initialTurnId) {
const linkedTurn = await api.analysisTurn(initialTurnId);
@@ -1475,7 +1503,11 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
if (linkedSession && turnSession && linkedSession !== turnSession) throw new Error('分析轮次与会话链接不匹配');
linkedSession ||= turnSession;
}
if (!linkedSession && !initialLink.present) linkedSession = defaultAnalysisSession(user.id, items);
if (!linkedSession && !initialLink.present) {
const items = await listRequest;
if (!mounted.current || requestedAt !== navigationGeneration.current) return;
if (items) linkedSession = defaultAnalysisSession(user.id, items);
}
if (mounted.current && requestedAt === navigationGeneration.current && linkedSession) await openSession(linkedSession, initialTurnId || undefined);
} catch (value) { if (mounted.current && !onUnauthorized(value)) setError(apiMessage(value)); }
finally { if (mounted.current && requestedAt === navigationGeneration.current && !initialLink.present) setHistoryLoading(false); }
@@ -1687,11 +1719,11 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
<PageHeader title="智能分析" />
{error && <Alert type="error" showIcon message="智能分析状态" description={error} action={<>{retryQuestion && <Button size="small" onClick={() => void submit(retryQuestion)}>重试上一问</Button>}<Button size="small" onClick={() => void retrySessions()}>重新读取会话</Button></>} />}
{optionsError && <Alert type="error" showIcon message="分析选项读取失败" description={options ? `${optionsError};已成功读取的选项仍保留。` : optionsError} action={<Button size="small" onClick={() => { optionsRequestStarted.current = false; setOptionsError(''); optionsRequestStarted.current = true; void optionsRead.run(async () => { try { setOptions(await api.options()); setOptionsError(''); } catch (value) { if (!onUnauthorized(value)) setOptionsError(apiMessage(value)); } }); }}>重试</Button>} />}
{!options && optionsRead.busy && <div className="loading-panel compact"><Spin />读取分析选项…</div>}
<div className="analysis-workspace">
<aside className="panel analysis-session-panel">
<div className="analysis-session-heading"><strong>会话</strong><Button type="primary" size="small" onClick={newSession}>新会话</Button></div>
{showHistoryLoading ? <div className="loading-panel compact"><Spin />正在读取会话…</div> : sessionsLoaded ? sessions.length ? <div className="analysis-session-list">{sessions.map(item => <div key={String(item.id)} className={`analysis-session-row ${sessionId === item.id ? 'active' : ''}`}><button className="analysis-session-item" onClick={() => void openSession(String(item.id))}><strong>{toText(item.title || '未命名会话')}</strong><small>{String(item.updatedAt || item.createdAt || '').slice(0, 10)}{analysisIsRunning(item.activeTurnStatus) && <span className="analysis-session-state">{item.activeTurnStatus === 'QUEUED' ? '排队中' : '分析中'}</span>}</small></button><Dropdown trigger={['click']} menu={{ items: [
{sessionsError && <Alert type="error" message="会话列表读取失败" description={sessionsError} action={<Button size="small" onClick={() => { if (!userSelectionMade.current && !sessionId) void retrySessions(); else void loadSessions(); }}>重试</Button>} />}
{!sessionsLoaded && showSessionsLoading ? <div className="analysis-region-loading" role="status"><Spin />正在读取会话列表…</div> : sessionsLoaded ? sessions.length ? <div className="analysis-session-list">{sessions.map(item => <div key={String(item.id)} className={`analysis-session-row ${sessionId === item.id ? 'active' : ''}`}><button className="analysis-session-item" onClick={() => void openSession(String(item.id))}><strong>{toText(item.title || '未命名会话')}</strong><small>{String(item.updatedAt || item.createdAt || '').slice(0, 10)}{analysisIsRunning(item.activeTurnStatus) && <span className="analysis-session-state">{item.activeTurnStatus === 'QUEUED' ? '排队中' : '分析中'}</span>}</small></button><Dropdown trigger={['click']} menu={{ items: [
{ key: 'rename', icon: <EditOutlined />, label: '重命名' },
{ key: 'delete', icon: <DeleteOutlined />, label: '删除', danger: true, disabled: analysisIsRunning(item.activeTurnStatus) },
], onClick: ({ key }) => {
@@ -1700,7 +1732,7 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
} }}><Button className="analysis-session-menu" type="text" icon={<MoreOutlined />} aria-label={`会话操作 ${toText(item.title || '未命名会话')}`} /></Dropdown></div>)}</div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无历史会话" /> : null}
</aside>
<section className="panel analysis-chat-panel">
<div className="analysis-conversation" ref={conversation} aria-live="polite" onWheel={event => {
<div className="analysis-conversation" ref={conversation} aria-live="polite" aria-busy={historyLoading} onWheel={event => {
const direction = event.deltaY < 0 ? 'up' : event.deltaY > 0 ? 'down' : null;
if (direction) handleUserScrollIntent(event.currentTarget, direction);
}} onPointerDown={event => {
@@ -1739,7 +1771,8 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
}}>
{turns.map((turn, index) => <AnalysisTurn key={String(turn.id || index)} turn={turn} onRetry={sessionReadOnly ? undefined : (id) => void retryTurn(turns.find(item => String(item.id || '') === id) || turn)} onResume={id => { if (!historyLoading) void followTurn(id, String(turn.question || '')); }} onUnauthorized={onUnauthorized} retryDisabled={sessionReadOnly || busy || historyLoading} />)}
{lastTurn && <AnalysisTurn turn={lastTurn} onClarify={sessionReadOnly ? undefined : question => submit(question)} onRetry={sessionReadOnly ? undefined : () => void retryTurn(lastTurn)} onResume={id => { if (!historyLoading) void followTurn(id, String(lastTurn.question || '')); }} onUnauthorized={onUnauthorized} retryDisabled={sessionReadOnly || busy || historyLoading} />}
{!turns.length && !lastTurn && !busy && <div className="analysis-empty"><RobotOutlined /><strong>想了解哪些质量情况?</strong><span>例如:9月汽车交通的合格率为什么下降?</span></div>}
{!turns.length && !lastTurn && showHistoryLoading && <div className="analysis-region-loading" role="status"><Spin />正在读取会话…</div>}
{!turns.length && !lastTurn && !busy && !historyLoading && !error && !sessionsError && <div className="analysis-empty"><RobotOutlined /><strong>想了解哪些质量情况?</strong><span>例如:9月汽车交通的合格率为什么下降?</span></div>}
</div>
{hasNewContent && <Button size="small" type="text" className="analysis-new-content" onClick={() => {
const element = conversation.current;