修复:分析会话独立加载并保持加载布局稳定
This commit is contained in:
+50
-17
@@ -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;
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
.management-page.analysis-simple-page{gap:12px}
|
||||
.analysis-simple-page .analysis-region-loading{display:flex;align-items:center;justify-content:center;gap:10px;min-height:120px;color:var(--muted-ink,#738198)}
|
||||
.analysis-simple-page .analysis-conversation>.analysis-region-loading{flex:1}
|
||||
.analysis-simple-page .analysis-workspace{height:calc(var(--dynamic-viewport-height) - 105px);min-height:540px;grid-template-columns:205px minmax(0,1fr)}
|
||||
.page-heading.page-actions-only{min-height:0;margin:0;justify-content:flex-end}
|
||||
.analysis-composer-buttons{display:flex;align-items:center;gap:8px}
|
||||
|
||||
@@ -7,21 +7,23 @@ import '../src/styles.css';
|
||||
import '../src/workspace-finish.css';
|
||||
const user={id:'original-fixture',username:'fixture',displayName:'本地验收',roles:['SYSTEM_ADMIN'],departments:[],groups:[]};
|
||||
const modelAnswer='## 结论\n\n本期合格率下降,两个阶段的变化机制不同。完整模型正文必须保留。\n\n### 总体与阶段\n\n黑片合格率从97.58%降至97.27%,变化为 -0.30 pp。\n\n| 阶段 | 变化 |\n| --- | --- |\n| 黑片 | -0.30 pp |\n\n表格之后继续解释投入规模与报废规模,不能因为增加图表就丢掉这段。[Q11111111]\n\n### 下一步\n\n上述是统计线索,仍需现场核实生产原因。';
|
||||
let question='',status='QUEUED',createdAt='',startedAt='',finishedAt='';let timeline:Record<string,unknown>[]=[];
|
||||
const loadingCase=new URLSearchParams(location.search).get('loadingCase');
|
||||
if(loadingCase)history.replaceState({},'',`${location.pathname}?page=analysis&sessionId=fixture-session&loadingCase=${encodeURIComponent(loadingCase)}`);
|
||||
let question=loadingCase?'为什么合格率下降?':'',status=loadingCase?'PARTIAL':'QUEUED',createdAt='',startedAt='',finishedAt='';let timeline:Record<string,unknown>[]=loadingCase?[{kind:'assistant',sequence:1,text:modelAnswer}]:[];
|
||||
const visual={id:'stage-change',type:'column',title:'黑片合格率变化',subtitle:'',unit:'pp',metric:'rate_drop_pp',stage:'black',categories:[{key:'black',label:'黑片'}],series:[{key:'rateDrop',label:'合格率降幅',values:[.30]}],evidenceRefs:['Q11111111'],requiredFields:['black_good_weight','black_total_weight'],scope:{year:2026,month:9,releaseId:'fixture'},period:{year:2026,month:9},comparisonPeriod:{year:2026,month:8},originTurnId:'fixture-turn',coverage:{totalRows:1,returnedRows:1,truncated:false}};
|
||||
const saved=()=>({id:'fixture-turn',sessionId:'fixture-session',question,status,createdAt,startedAt,finishedAt,executionMode:'native_agent',plan:{timeline},answer:'已取得本轮统计结果,答案整理尚未完整完成。',readingSummary:{version:1,lead:'已取得本轮统计结果,答案整理尚未完整完成。',evidence:[],notices:[],evidenceRefs:['Q11111111']},queryEvidenceRefs:['Q11111111'],visualSchemaVersion:1,visualState:'ready',visuals:[visual],stopReason:'evidence_incomplete'});
|
||||
const json=(value:unknown)=>new Response(JSON.stringify(value),{headers:{'Content-Type':'application/json'}});
|
||||
window.fetch=async(input,init)=>{
|
||||
const path=new URL(String(input),location.origin).pathname;
|
||||
if(path==='/api/auth/csrf')return json({token:'fixture'});
|
||||
if(path==='/api/options')return json({years:[2026],departments:[],groups:[],products:[],projectGroups:[]});
|
||||
if(path==='/api/options'){if(loadingCase)await new Promise(r=>setTimeout(r,45000));return json({years:[2026],departments:[],groups:[],products:[],projectGroups:[]});}
|
||||
if(path==='/api/analysis/sessions'&&init?.method==='POST'){await new Promise(r=>setTimeout(r,1500));return json({session:{id:'fixture-session'}});}
|
||||
if(path==='/api/analysis/sessions')return json({items:question?[{id:'fixture-session',title:question,activeTurnStatus:status}]:[]});
|
||||
if(path==='/api/analysis/sessions'){if(loadingCase)await new Promise(r=>setTimeout(r,45000));return loadingCase==='error'?new Response('{}',{status:403}):json({items:question?[{id:'fixture-session',title:question,activeTurnStatus:status}]:[]});}
|
||||
if(path==='/api/analysis/sessions/fixture-session/turns'&&init?.method==='POST'){
|
||||
question=JSON.parse(String(init.body)).question;createdAt=new Date().toISOString();await new Promise(r=>setTimeout(r,300));return json({turn:{id:'fixture-turn',sessionId:'fixture-session',status,createdAt}});
|
||||
}
|
||||
if(path==='/api/analysis/sessions/fixture-session/turns')return json({items:[{id:'fixture-turn',status,createdAt,startedAt,finishedAt}]});
|
||||
if(path==='/api/analysis/sessions/fixture-session')return json({id:'fixture-session',context:{year:2026},turns:status==='PARTIAL'?[saved()]:[]});
|
||||
if(path==='/api/analysis/sessions/fixture-session'){if(loadingCase==='body')await new Promise(r=>setTimeout(r,30000));return json({id:'fixture-session',context:{year:2026},turns:status==='PARTIAL'?[saved()]:[]});}
|
||||
if(path==='/api/analysis/turns/fixture-turn'||path.endsWith('/snapshot'))return json(saved());
|
||||
if(path.endsWith('/events')){
|
||||
const encoder=new TextEncoder();let closed=false;const timers:ReturnType<typeof setTimeout>[]=[];
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import ts from 'typescript';
|
||||
import {analysisComposerState} from '../src/analysisScope.ts';
|
||||
const source=fs.readFileSync(new URL('../src/ManagementPages.tsx',import.meta.url),'utf8');
|
||||
const tick=()=>new Promise(resolve=>setImmediate(resolve));
|
||||
const deferred=()=>{let resolve;const promise=new Promise(r=>resolve=r);return{promise,resolve};};
|
||||
function restoreFixture({sessionId='',turnId='',link=false}={}){
|
||||
const list=deferred(),opens=[];let effect,loading=true;
|
||||
const env={active:true,restoreStarted:{current:false},mounted:{current:true},navigationGeneration:{current:0},initialSessionId:sessionId,initialTurnId:turnId,initialLink:{present:link},user:{id:'u'},
|
||||
useEffect:fn=>{effect=fn;},setHistoryLoading:v=>{loading=v;},setSessions(){},setSessionsLoaded(){},setSessionsLoading(){},collectionItems:v=>v.items||[],
|
||||
loadSessions:async()=>(await list.promise).items,api:{analysisSessions:()=>list.promise,analysisTurn:async()=>({sessionId:'linked-session'})},defaultAnalysisSession:(_u,items)=>items[0]?.id,
|
||||
openSession:async(...args)=>{opens.push(args);loading=false;return true;},onUnauthorized:()=>false,setError(){},apiMessage:e=>e.message};
|
||||
const marker=' useEffect(() => {\n if (!active || restoreStarted.current)';const start=source.indexOf(marker);const end=source.indexOf('\n useEffect(() => {',start+marker.length);
|
||||
const code=ts.transpileModule(source.slice(start,end),{compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText;
|
||||
new Function(...Object.keys(env),code)(...Object.values(env));effect();
|
||||
return{list,opens,get loading(){return loading;}};
|
||||
}
|
||||
test('an explicit history link loads its body without waiting for the unrelated session list',async()=>{
|
||||
const ui=restoreFixture({sessionId:'requested-session'});await tick();assert.deepEqual(ui.opens,[['requested-session',undefined]]);
|
||||
ui.list.resolve({items:[]});await tick();
|
||||
});
|
||||
test('a turn link can resolve its session while the session list is still pending',async()=>{
|
||||
const ui=restoreFixture({turnId:'requested-turn'});await tick();assert.deepEqual(ui.opens,[['linked-session','requested-turn']]);
|
||||
ui.list.resolve({items:[]});await tick();
|
||||
});
|
||||
test('default history selection still waits for the list before choosing a session',async()=>{
|
||||
const ui=restoreFixture();await tick();assert.equal(ui.opens.length,0);ui.list.resolve({items:[{id:'recent'}]});await tick();assert.deepEqual(ui.opens,[['recent',undefined]]);
|
||||
});
|
||||
|
||||
function listFixture(){
|
||||
const read=deferred();let reads=0,state={busy:false,loaded:false,items:[],error:''};
|
||||
const env={mounted:{current:true},active:true,sessionReadRequest:{current:null},setSessionsLoading:v=>{state.busy=v;},setSessions:v=>{state.items=v;},setSessionsLoaded:v=>{state.loaded=v;},setSessionsError:v=>{state.error=v;},onUnauthorized:()=>false,apiMessage:e=>e.message,collectionItems:v=>v.items||[],api:{analysisSessions:()=>{reads++;return read.promise;}}};
|
||||
const start=source.indexOf(' const loadSessions = async');const end=source.indexOf('\n const retrySessions =',start);
|
||||
const code=ts.transpileModule(source.slice(start,end)+'\nreturn loadSessions;',{compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText;
|
||||
return{read,state,reads:()=>reads,load:new Function(...Object.keys(env),code)(...Object.values(env))};
|
||||
}
|
||||
test('session-list reads are shared, and failure stays within the list resource',async()=>{
|
||||
const ui=listFixture();const a=ui.load(),b=ui.load();assert.equal(ui.reads(),1);assert.equal(ui.state.busy,true);
|
||||
ui.read.resolve({items:[{id:'recent'}]});assert.deepEqual(await a,[{id:'recent'}]);await b;assert.equal(ui.state.loaded,true);assert.equal(ui.state.busy,false);
|
||||
ui.read.resolve({items:[]});
|
||||
});
|
||||
test('a failed list read ends its own loading state and cannot masquerade as an empty successful list',async()=>{
|
||||
const ui=listFixture();const work=ui.load();ui.read.resolve(Promise.reject(new Error('list unavailable')));assert.equal(await work,undefined);
|
||||
assert.equal(ui.state.busy,false);assert.equal(ui.state.loaded,false);assert.equal(ui.state.error,'list unavailable');
|
||||
});
|
||||
test('ordinary and explicit historical conversations never download the unused options resource',()=>{
|
||||
const start=source.indexOf(' useEffect(() => {\n if (!active || !initialLink.present');assert.notEqual(start,-1);
|
||||
const end=source.indexOf('\n\n',start);const code=ts.transpileModule(source.slice(start,end),{compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText;
|
||||
for(const [present,session,turn] of [[false,'',''],[false,'s',''],[true,'s',''],[true,'','t']]){
|
||||
let reads=0;const env={useEffect:fn=>fn(),active:true,initialLink:{present},initialSessionId:session,initialTurnId:turn,optionsRequestStarted:{current:false},optionsRead:{run:()=>{reads++;}},onUnauthorized:()=>false};
|
||||
new Function(...Object.keys(env),code)(...Object.values(env));assert.equal(reads,0);
|
||||
}
|
||||
});
|
||||
|
||||
function retryFixture(sessionId='',turnId=''){
|
||||
const list=deferred(),opens=[],navigationGeneration={current:0},state={historyLoading:false};
|
||||
const env={sessionId,navigationGeneration,pendingTurnLink:{current:turnId},mounted:{current:true},initialLink:{present:false},user:{id:'u'},setHistoryLoading:v=>{state.historyLoading=v;},loadSessions:()=>list.promise,api:{analysisTurn:async()=>({sessionId:'target-session'})},openSession:async(id,focus)=>opens.push([id,focus]),defaultAnalysisSession:(_u,items)=>items[0]?.id,onUnauthorized:()=>false,setError(){},apiMessage:e=>e.message};
|
||||
const start=source.indexOf(' const retrySessions = async');const end=source.indexOf('\n useEffect(',start);
|
||||
const code=ts.transpileModule(source.slice(start,end)+'\nreturn retrySessions;',{compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText;
|
||||
return{list,opens,state,navigationGeneration,retry:new Function(...Object.keys(env),code)(...Object.values(env))};
|
||||
}
|
||||
test('retrying a linked history does not wait for a slow list',async()=>{
|
||||
const ui=retryFixture('selected');await ui.retry();assert.deepEqual(ui.opens,[['selected',undefined]]);ui.list.resolve([]);
|
||||
});
|
||||
test('default-list retry cannot navigate over a newer user selection',async()=>{
|
||||
const ui=retryFixture();const work=ui.retry();ui.navigationGeneration.current++;ui.list.resolve([{id:'old-default'}]);await work;assert.deepEqual(ui.opens,[]);
|
||||
});
|
||||
test('retry of a turn-only link re-resolves the requested turn instead of opening an unrelated default',async()=>{
|
||||
const ui=retryFixture('','requested-turn');ui.list.resolve([{id:'unrelated-default'}]);await ui.retry();assert.deepEqual(ui.opens,[['target-session','requested-turn']]);
|
||||
});
|
||||
test('default-history retry locks sending until its target resolves, so a late list cannot replace a new submission',async()=>{
|
||||
const ui=retryFixture();const work=ui.retry();assert.equal(ui.state.historyLoading,true);
|
||||
assert.equal(analysisComposerState(false,false,ui.state.historyLoading,'新问题').sendDisabled,true);
|
||||
ui.list.resolve([{id:'default'}]);await work;assert.equal(ui.state.historyLoading,false);
|
||||
});
|
||||
Reference in New Issue
Block a user