修复:完整展示AI原文并穿插图表,统一运行反馈与变化符号
This commit is contained in:
@@ -0,0 +1 @@
|
||||
<!doctype html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>AI原文与运行状态验收</title></head><body><div id="root"></div><script type="module" src="./analysis-original.tsx"></script></body></html>
|
||||
@@ -0,0 +1,41 @@
|
||||
// Local acceptance fixture: all requests are intercepted; no model, API or database writes.
|
||||
import React from 'react';
|
||||
import {createRoot} from 'react-dom/client';
|
||||
import {App,ConfigProvider} from 'antd';
|
||||
import ManagementPages from '../src/ManagementPages';
|
||||
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 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/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/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/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>[]=[];
|
||||
const stream=new ReadableStream({start(controller){
|
||||
let eventId=0;const send=(event:string,data:unknown)=>{if(!closed)controller.enqueue(encoder.encode(`id: ${++eventId}\nevent: ${event}\ndata: ${JSON.stringify(data)}\n\n`));};
|
||||
send('progress',{status:'QUEUED'});
|
||||
timers.push(setTimeout(()=>{status='RUNNING';startedAt=new Date().toISOString();send('progress',{status,message:'正在理解本轮目标和连续追问…'});},300));
|
||||
timers.push(setTimeout(()=>{timeline=[{kind:'tool_start',sequence:1,tool:'read',toolCallId:'read-1',label:'核对正式指标',status:'running'}];send('tool_started',{timeline,step:timeline[0]});},800));
|
||||
timers.push(setTimeout(()=>{timeline.push({kind:'tool_result',sequence:2,tool:'read',toolCallId:'read-1',label:'核对正式指标',status:'completed'});send('tool_completed',{timeline,step:timeline[1]});},6000));
|
||||
timers.push(setTimeout(()=>{status='PARTIAL';finishedAt=new Date().toISOString();timeline.push({kind:'assistant',sequence:3,text:modelAnswer});send('partial',{status,result:saved()});if(!closed){closed=true;controller.close();}},30000));
|
||||
init?.signal?.addEventListener('abort',()=>{if(!closed){closed=true;controller.close();}timers.forEach(clearTimeout);},{once:true});
|
||||
},cancel(){closed=true;timers.forEach(clearTimeout);}});
|
||||
return new Response(stream,{headers:{'Content-Type':'text/event-stream'}});
|
||||
}
|
||||
return json({items:[]});
|
||||
};
|
||||
createRoot(document.getElementById('root')!).render(<ConfigProvider><App><main style={{padding:18,maxWidth:1500,margin:'auto'}}><ManagementPages page="analysis" user={user} onUnauthorized={()=>false} onNavigate={()=>{}}/></main></App></ConfigProvider>);
|
||||
@@ -0,0 +1,62 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import ts from 'typescript';
|
||||
import React from 'react';
|
||||
import {renderToStaticMarkup} from 'react-dom/server';
|
||||
import {analysisStreamStatus,analysisIsRunning,acceptAnalysisEvent,settledAnalysisTurn} from '../src/analysisConversationState.ts';
|
||||
const source=fs.readFileSync(new URL('../src/ManagementPages.tsx',import.meta.url),'utf8');
|
||||
const compile=code=>ts.transpileModule(code,{fileName:'status.tsx',compilerOptions:{target:ts.ScriptTarget.ES2022,jsx:ts.JsxEmit.React}}).outputText;
|
||||
const tick=()=>new Promise(resolve=>setImmediate(resolve));
|
||||
const deferred=()=>{let resolve;const promise=new Promise(r=>resolve=r);return{promise,resolve};};
|
||||
const isObjectRecord=v=>!!v&&typeof v==='object'&&!Array.isArray(v);
|
||||
const finalStatuses=new Set(['COMPLETED','PARTIAL','FAILED','CANCELLED','NEEDS_CLARIFICATION']);
|
||||
function fixture(){
|
||||
let lastTurn={id:'t1',question:'q',status:'QUEUED',createdAt:'2026-11-02T01:00:00Z'},onEvent,reads=0;
|
||||
const stream=deferred(),firstRead=deferred(),secondRead=deferred();
|
||||
const env={mounted:{current:true},streamController:{current:null},subscriptionGeneration:{current:0},sessionId:'s1',eventCursors:{current:{}},ANALYSIS_FINAL_STATUSES:finalStatuses,
|
||||
setLastTurn:next=>lastTurn=typeof next==='function'?next(lastTurn):next,writeAnalysisLocation(){},setActiveTurnId(){},setBusy(){},setRetryQuestion(){},setTurns(){},setError(){},loadSessions:async()=>{},onUnauthorized:()=>false,apiMessage:e=>e.message,
|
||||
isObjectRecord,analysisStreamStatus,analysisIsRunning,acceptAnalysisEvent,settledAnalysisTurn,collectionItems:value=>value.items||[],modelThinkingEntries:()=>[],mergeModelThinking:()=>[]};
|
||||
const api={analysisTurnEvents:async(_id,options)=>{onEvent=options.onEvent;return stream.promise;},analysisSessionTurns:()=>{reads++;return reads===1?firstRead.promise:secondRead.promise;}};
|
||||
const code=source.slice(source.indexOf(' const followTurn = async'),source.indexOf('\n useEffect(() => {\n if (!active || restoreStarted.current)'));
|
||||
const follow=new Function('api',...Object.keys(env),compile(code+'\nreturn followTurn;'))(api,...Object.values(env));
|
||||
const work=follow('t1','q','s1');
|
||||
return{get:()=>lastTurn,reads:()=>reads,switchTurn(){env.subscriptionGeneration.current++;lastTurn={id:'other',status:'RUNNING'};},emit(event,data){onEvent({id:String(Math.random()),event,data});},firstRead,secondRead,async close(){env.streamController.current?.abort();stream.resolve();await work;}};
|
||||
}
|
||||
test('tool step events keep the whole turn running and terminal status does not regress',()=>{
|
||||
assert.equal(analysisStreamStatus('RUNNING','tool_started',undefined),'RUNNING');
|
||||
assert.equal(analysisStreamStatus('RUNNING','tool_completed','completed'),'RUNNING');
|
||||
assert.equal(analysisStreamStatus('RUNNING','completed','COMPLETED'),'COMPLETED');
|
||||
assert.equal(analysisStreamStatus('COMPLETED','progress','RUNNING'),'COMPLETED');
|
||||
});
|
||||
test('actual event subscriber keeps status live and fills the server clock without re-entering',async()=>{
|
||||
const ui=fixture();assert.equal(ui.reads(),1);
|
||||
ui.emit('progress',{status:'RUNNING'});
|
||||
ui.firstRead.resolve({items:[{id:'t1',createdAt:'2026-11-02T01:00:00Z',startedAt:''}]});await tick();
|
||||
assert.equal(ui.reads(),2,'a running event during an initial queued timing read schedules one non-overlapping follow-up');
|
||||
ui.secondRead.resolve({items:[{id:'t1',startedAt:'2026-11-02T01:00:05Z'}]});await tick();
|
||||
ui.emit('tool_started',{step:{status:'running'}});
|
||||
assert.equal(ui.get().status,'RUNNING');assert.equal(ui.get().startedAt,'2026-11-02T01:00:05Z');
|
||||
ui.emit('tool_completed',{step:{status:'completed'}});assert.equal(ui.get().status,'RUNNING');
|
||||
assert.equal(ui.reads(),2);await ui.close();
|
||||
});
|
||||
test('late timing metadata cannot update a different selected turn',async()=>{
|
||||
const ui=fixture();ui.switchTurn();await ui.close();ui.firstRead.resolve({items:[{id:'t1',startedAt:'2026-11-02T01:00:05Z'}]});await tick();
|
||||
assert.equal(ui.get().startedAt,undefined);
|
||||
});
|
||||
test('metadata renders a waiting clock immediately and a spinning running clock after server start',()=>{
|
||||
const code=source.slice(source.indexOf('function AnalysisTurnMetadata('),source.indexOf('\nfunction isObjectRecord('));
|
||||
const Metadata=new Function('React','useState','useEffect','analysisIsRunning','isObjectRecord','LoadingOutlined',compile(code+'\nreturn AnalysisTurnMetadata;'))(React,initial=>[initial,()=>{}],()=>{},analysisIsRunning,isObjectRecord,props=>React.createElement('i',props));
|
||||
const now=Date.now();
|
||||
const waiting=renderToStaticMarkup(React.createElement(Metadata,{turn:{_uiSubmittedAt:new Date(now-30000).toISOString()},status:'SUBMITTING',compact:true}));
|
||||
assert.match(waiting,/提交中/);assert.match(waiting,/已等待 30秒/);
|
||||
const running=renderToStaticMarkup(React.createElement(Metadata,{turn:{startedAt:new Date(now-10000).toISOString()},status:'RUNNING',compact:true}));
|
||||
assert.match(running,/已运行 10秒/);assert.match(running,/analysis-runtime-spinner/);
|
||||
});
|
||||
|
||||
test('partial remains a backend state without an extra partial label in conversation metadata',()=>{
|
||||
const code=source.slice(source.indexOf('function AnalysisTurnMetadata('),source.indexOf('\nfunction isObjectRecord('));
|
||||
const Metadata=new Function('React','useState','useEffect','analysisIsRunning','isObjectRecord','LoadingOutlined',compile(code+'\nreturn AnalysisTurnMetadata;'))(React,initial=>[initial,()=>{}],()=>{},analysisIsRunning,isObjectRecord,()=>null);
|
||||
const html=renderToStaticMarkup(React.createElement(Metadata,{turn:{durationMs:6000},status:'PARTIAL',compact:true}));
|
||||
assert.doesNotMatch(html,/部分完成/);assert.match(html,/运行时长 6秒/);
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { originalAnalysisBody, originalAnalysisSections } from '../src/analysisOriginalBody.ts';
|
||||
const original='## 结论\n\n合格率下降来自两个不同的阶段。\n\n### 总体与阶段\n\n先说明投入规模。\n\n| 阶段 | 变化 |\n| --- | --- |\n| 黑片 | -0.30 pp |\n\n表格之后的完整解释不能挪走。[Q11111111]\n\n### 组织维度\n\n国内与海外结构不同。\n\n### 局限\n\n不能据此认定生产根因。';
|
||||
const legacy=()=>({status:'PARTIAL',result:{executionMode:'native_agent',answer:'已取得本轮统计结果,答案整理尚未完整完成。\n\n正式统计表',readingSummary:{lead:'已取得本轮统计结果,答案整理尚未完整完成。'}},plan:{timeline:[{kind:'assistant',text:'先进行查询。'},{kind:'tool_start',sequence:1},{kind:'tool_result',sequence:2},{kind:'assistant',sequence:3,text:original}]}});
|
||||
test('legacy native fallback restores the entire final model body instead of another summary',()=>{
|
||||
const body=originalAnalysisBody(legacy());assert.equal(body.source,'timeline');assert.equal(body.answer,original);
|
||||
assert.doesNotMatch(body.answer,/已取得本轮统计结果/);
|
||||
});
|
||||
test('new saved original body wins over an 8000-character transcript and remains complete',()=>{
|
||||
const data=legacy();const answer='正文'.repeat(6000);data.result.answer=answer;delete data.result.readingSummary;
|
||||
data.plan.timeline.at(-1).text=answer.slice(0,8000)+'…';assert.equal(originalAnalysisBody(data).answer,answer);
|
||||
});
|
||||
test('a capped historical transcript cannot masquerade as the complete original body',()=>{
|
||||
const data=legacy();data.plan.timeline.at(-1).text='原'.repeat(8000);
|
||||
assert.deepEqual(originalAnalysisBody(data),{answer:'',source:'unavailable'});
|
||||
});
|
||||
test('a failed native result with no formal evidence still renders its saved original body',()=>{
|
||||
assert.deepEqual(originalAnalysisBody({status:'FAILED',result:{executionMode:'native_agent',answer:original,results:[],answerQuality:{dataComplete:false}}}),{answer:original,source:'saved'});
|
||||
});
|
||||
test('earlier assistant progress, redacted answers, and unavailable originals are never promoted',()=>{
|
||||
const data=legacy();data.plan.timeline.pop();assert.deepEqual(originalAnalysisBody(data),{answer:'',source:'unavailable'});
|
||||
data.result.answer='';data.plan.timeline.push({kind:'assistant',text:original});assert.equal(originalAnalysisBody(data).answer,'');
|
||||
delete data.result.executionMode;assert.equal(originalAnalysisBody(data),null);
|
||||
});
|
||||
test('original Markdown lines, table placement and scope caveats stay in their exact order',()=>{
|
||||
const parts=originalAnalysisSections(original,[]);assert.equal(parts.map(p=>p.markdown).join('\n'),original);
|
||||
assert.ok(parts[1].markdown.indexOf('| 黑片')<parts[1].markdown.indexOf('表格之后'));
|
||||
assert.match(parts.at(-1).markdown,/不能据此认定生产根因/);
|
||||
});
|
||||
test('figures are inserted after the associated complete chapter without removing prose or tables',()=>{
|
||||
const visual={id:'stage',title:'阶段合格率',metric:'black_rate',type:'column',evidenceRefs:['Q11111111']};
|
||||
const sections=originalAnalysisSections(original,[visual]);assert.equal(sections[1].visuals[0],visual);
|
||||
assert.equal(sections.flatMap(s=>s.visuals).length,1);assert.equal(sections.map(s=>s.markdown).join('\n'),original);
|
||||
});
|
||||
|
||||
test('alternate historical evidence fallback also recovers native prose',()=>{
|
||||
const data=legacy();data.result.readingSummary.lead='现有证据不足以支持本轮完整分析,已保留可核验统计结果。';assert.equal(originalAnalysisBody(data).answer,original);
|
||||
});
|
||||
test('black and bright figures cannot be attached to the opposite stage chapter',()=>{
|
||||
const body='## 黑片阶段\n\n黑片完整解释。\n\n## 亮片阶段\n\n亮片完整解释。';
|
||||
const figures=[{id:'black',type:'column',stage:'black',metric:'black_rate',evidenceRefs:[]},{id:'bright',type:'column',stage:'bright',metric:'bright_rate',evidenceRefs:[]}];
|
||||
const sections=originalAnalysisSections(body,figures);assert.equal(sections[0].visuals[0].id,'black');assert.equal(sections[1].visuals[0].id,'bright');
|
||||
});
|
||||
@@ -274,17 +274,17 @@ test('history proof and lineage in model-controlled task fields cannot authorize
|
||||
assert.deepEqual(selectedHistoryIds(turn), []);
|
||||
});
|
||||
|
||||
test('running process starts folded, stays open after a user opens it, closes on completion, and ignores late running status', () => {
|
||||
test('running process starts open, honors manual collapse, and closes on completion', () => {
|
||||
const harness = hookHarness();
|
||||
const turn = { id: 'process-turn', status: 'RUNNING', steps: [{ tool: 'read', label: '读取数据', status: 'running' }] };
|
||||
let element = harness.render(turn);
|
||||
assert.equal(element.type, 'details');
|
||||
assert.equal(element.props.open, false);
|
||||
assert.equal(element.props.open, true);
|
||||
|
||||
element.props.onToggle({ currentTarget: { open: true } });
|
||||
element.props.onToggle({ currentTarget: { open: false } });
|
||||
turn.steps = [...turn.steps, { tool: 'mcp_call', label: '查询质量数据', status: 'running' }];
|
||||
element = harness.render(turn);
|
||||
assert.equal(element.props.open, true);
|
||||
assert.equal(element.props.open, false);
|
||||
|
||||
turn.status = 'COMPLETED';
|
||||
turn.steps = [...turn.steps, { tool: 'mcp_call', label: '查询质量数据', status: 'completed' }];
|
||||
@@ -293,5 +293,5 @@ test('running process starts folded, stays open after a user opens it, closes on
|
||||
|
||||
turn.status = 'RUNNING';
|
||||
element = harness.render(turn);
|
||||
assert.equal(element.props.open, false);
|
||||
assert.equal(element.props.open, true);
|
||||
});
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { originalAnalysisBody, originalAnalysisSections } from '../src/analysisOriginalBody.ts';
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
@@ -22,7 +23,9 @@ const turn = (readingSummary = summary()) => ({ id: 'turn', question: '9月合
|
||||
releaseId: 'release', visuals: [chart], queryEvidenceRefs: ['Q11111111', 'Q22222222'], readingSummary,
|
||||
} });
|
||||
|
||||
let OriginalContent=()=>null;
|
||||
function component(source, name, bindings) {
|
||||
bindings={originalAnalysisBody,AnalysisOriginalContent:props=>React.createElement(OriginalContent,props),...bindings};
|
||||
const cleaned = source.replace(/^import .*;\n/gm, '').replace(/^export /gm, '');
|
||||
return new Function('React', ...Object.keys(bindings), ts.transpileModule(`${cleaned}\nreturn ${name};`, {
|
||||
fileName: `${name}.tsx`, compilerOptions: { target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.React },
|
||||
@@ -30,6 +33,7 @@ function component(source, name, bindings) {
|
||||
}
|
||||
const markdownSource = readFileSync(new URL('../src/AiMarkdown.tsx', import.meta.url), 'utf8');
|
||||
const AiMarkdown = component(markdownSource, 'AiMarkdown', { sanitizeAnalysisDisplayText, analysisEvidenceParts });
|
||||
OriginalContent=component(readFileSync(new URL('../src/AnalysisOriginalContent.tsx',import.meta.url),'utf8'),'AnalysisOriginalContent',{AiMarkdown,originalAnalysisSections});
|
||||
|
||||
test('conclusion layout separates the lead, findings and table titles without rewriting checked facts', () => {
|
||||
const content = '9月综合合格率**95.13%**,较8月的**95.57%**下降**0.44个百分点**。主要来自**黑片阶段**,正式影响为**-0.30个百分点**;亮片影响**-0.15个百分点**。\n\n'
|
||||
@@ -81,7 +85,7 @@ const visibleSummary = html => html.match(/<div class="ai-markdown[^"]*">([\s\S]
|
||||
test('comparison readout uses the checked change, preserving rounded stage values and explicit scope', () => {
|
||||
const sentence='汽车交通2026年9月黑片合格率**97.27%**,较8月的**97.58%**下降**0.30个百分点**。';
|
||||
const value=checkedConclusionComparison(sentence);
|
||||
assert.equal(value.change,'0.30'); assert.equal(value.currentLabel,'汽车交通2026年9月');
|
||||
assert.equal(value.change,'-0.30'); assert.equal(value.currentLabel,'汽车交通2026年9月');
|
||||
assert.equal(value.previousLabel,'8月'); assert.equal(value.current,'97.27%'); assert.equal(value.previous,'97.58%');
|
||||
for (const invalid of ['9月合格率95.13%。','9月合格率95.13%,较8月95.57%。','9月合格率101.00%,较8月95.57%下降0.44个百分点。']) assert.equal(checkedConclusionComparison(invalid),null);
|
||||
assert.equal(checkedConclusionComparison('9月合格率0.00%,较8月95.57%下降95.57个百分点。').current,'0.00%');
|
||||
@@ -93,7 +97,7 @@ test('conclusion chapters put each authorized figure beside its cited topic, wit
|
||||
'**重点规格**:甲规格报废增加128.45 kg。[Q11111111]']});
|
||||
const figures=[{...chart,id:'department',metric:'rate_drop_pp',dimension:'department',evidenceRefs:['Q22222222']},{...chart,id:'product',metric:'scrap_delta',dimension:'product'}];
|
||||
const document=buildConclusionDocument(buildAnalysisReadingModel('',[],data.question,data).reading,figures);
|
||||
assert.equal(document.comparison.change,'0.44');
|
||||
assert.equal(document.comparison.change,'-0.44');
|
||||
assert.deepEqual(document.sections.find(x=>x.title==='产业部变化').visuals.map(v=>v.id),['department']);
|
||||
assert.deepEqual(document.sections.find(x=>x.title==='重点规格').visuals.map(v=>v.id),['product']);
|
||||
assert.deepEqual(document.sections.flatMap(x=>x.visuals.map(v=>v.id)),['department','product']);
|
||||
@@ -109,7 +113,7 @@ test('reference-style cards and chapters keep chat/report values, figures and or
|
||||
data.result.answer=data.result.readingSummary.lead+'\n\n'+data.result.readingSummary.evidence[0];
|
||||
for(const html of [renderChat(data),renderReport(data)]) {
|
||||
assert.match(html,/analysis-comparison-current[^>]*><span>2026年9月<\/span><strong>95.13%<\/strong>/);
|
||||
assert.match(html,/下降 0.44/); assert.match(html,/95.57%/);
|
||||
assert.match(html,/-0.44/); assert.match(html,/95.57%/);
|
||||
assert.equal((html.match(/<table>/g)||[]).length,1);
|
||||
assert.doesNotMatch(html,/Q11111111|Q22222222|关键依据|数据依据|analysis-full-appendix/);
|
||||
}
|
||||
|
||||
@@ -158,10 +158,10 @@ test('settled process is collapsed, with the original records retained inside',(
|
||||
assert.doesNotMatch(html,/<details class="analysis-process-history analysis-agent-process" open/);
|
||||
}
|
||||
});
|
||||
test('running process stays folded by default while retaining its current records inside',()=>{
|
||||
test('running process is expanded by default while retaining its current records inside',()=>{
|
||||
const html=renderToStaticMarkup(React.createElement(Process,{turn:processTurn('RUNNING')}));
|
||||
assert.match(html,/读取数据/);assert.match(html,/<details class="analysis-process-history analysis-agent-process"/);
|
||||
assert.doesNotMatch(html,/<details class="analysis-process-history analysis-agent-process" open/);
|
||||
assert.match(html,/<details class="analysis-process-history analysis-agent-process" open/);
|
||||
});
|
||||
|
||||
test('a submitted follow-up rearms following only when its own turn is rendered',()=>{
|
||||
@@ -329,7 +329,8 @@ test('agent process interleaves thoughts, tool calls and text with one runtime h
|
||||
]};
|
||||
const html=renderToStaticMarkup(React.createElement(Process,{turn,metadata:React.createElement('span',null,'运行时长 25秒')}));
|
||||
assert.equal((html.match(/运行时长/g)||[]).length,1);
|
||||
const positions=['先核对范围','我来查询两个期间。','读取数据','再整理结果'].map(value=>html.indexOf(value));
|
||||
assert.doesNotMatch(html,/我来查询两个期间。/);
|
||||
const positions=['先核对范围','读取数据','再整理结果'].map(value=>html.indexOf(value));
|
||||
assert.ok(positions.every((p,i)=>p>=0&&(!i||p>positions[i-1])));
|
||||
assert.equal((html.match(/class="analysis-thinking-block"/g)||[]).length,2);
|
||||
for(const hidden of ['model-hidden','任务理解','整理结论','analysis-thinking-heading','展示接口实际返回'])assert.ok(!html.includes(hidden),hidden);
|
||||
|
||||
@@ -182,7 +182,7 @@ test('unknown 503 submission renders recovery notice without claiming a queued o
|
||||
await ui.submit('question with unknown outcome');
|
||||
assert.equal(ui.get().attempt.uncertain,true);
|
||||
const html=renderDraft(ui.get().lastTurn);
|
||||
assert.match(html,/提交结果暂未确认,请重试上一问恢复原任务/);
|
||||
assert.doesNotMatch(html,/提交结果暂未确认/);
|
||||
assert.doesNotMatch(html,/排队中|正在准备分析|仍在运行/);
|
||||
assert.equal(ui.get().lastTurn.status,undefined);
|
||||
});
|
||||
@@ -192,7 +192,23 @@ test('an explicit 400 rejection renders an unsuccessful draft without a running
|
||||
await ui.submit('rejected question');
|
||||
assert.equal(ui.get().attempt,null);
|
||||
const html=renderDraft(ui.get().lastTurn);
|
||||
assert.match(html,/本次提交未成功,请检查错误提示后重试/);
|
||||
assert.doesNotMatch(html,/本次提交未成功/);
|
||||
assert.doesNotMatch(html,/排队中|正在准备分析|仍在运行|恢复原任务/);
|
||||
assert.equal(ui.get().lastTurn.status,undefined);
|
||||
});
|
||||
|
||||
|
||||
test('a fresh submission immediately carries waiting status and a clock before acceptance',async()=>{
|
||||
const pending=deferred();const ui=fixture({startAnalysisTurn:()=>pending.promise});
|
||||
const work=ui.submit('即时状态');assert.equal(ui.get().lastTurn.status,'SUBMITTING');
|
||||
assert.ok(Number.isFinite(Date.parse(ui.get().lastTurn._uiSubmittedAt)));
|
||||
pending.resolve({turn:{id:'accepted',status:'RUNNING'}});await work;
|
||||
assert.ok(Number.isFinite(Date.parse(ui.get().lastTurn._uiSubmittedAt)));
|
||||
});
|
||||
|
||||
test('retry starts a fresh waiting clock without displaying the old body or plan clock',async()=>{
|
||||
const response=deferred();const ui=fixture({retryAnalysisTurn:()=>response.promise,analysisTurn:async()=>({id:'old',status:'QUEUED'})});
|
||||
const work=ui.retryTurn({id:'old',status:'PARTIAL',answer:'old text',createdAt:'2020-01-01T00:00:00Z',startedAt:'2020-01-01T00:00:01Z',plan:{startedAt:'2020-01-01T00:00:01Z'}});
|
||||
assert.equal(ui.get().lastTurn.status,'SUBMITTING');assert.equal(ui.get().lastTurn.answer,undefined);assert.equal(ui.get().lastTurn.plan,undefined);
|
||||
response.resolve({turn:{id:'old',sessionId:'session-1',status:'QUEUED'}});await work;
|
||||
});
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
visualUnitLabel,
|
||||
} from '../src/analysisVisualsModel.ts';
|
||||
import { buildAnalysisNarrative } from '../src/analysisReportModel.ts';
|
||||
import { buildConclusionDocument, checkedConclusionComparison } from '../src/analysisConclusionModel.ts';
|
||||
|
||||
function visual(overrides = {}) {
|
||||
return {
|
||||
@@ -305,6 +306,64 @@ test('negative percentage point changes remain signed and keep a zero baseline',
|
||||
assert.equal(formatVisualValue(0.5, 'pp'), '+0.5 pp');
|
||||
});
|
||||
|
||||
test('legacy rate-drop charts normalize once and chat tables and exports use current minus prior', () => {
|
||||
const legacy = visual({
|
||||
id: 'legacy-rate-drop', type: 'bar', title: '业务分组合格率降幅线索', subtitle: '8月 → 9月',
|
||||
unit: 'pp', metric: 'rate_drop_pp', dimension: 'group', sectionKey: 'group',
|
||||
categories: [{ key: 'g1', label: '分组一' }, { key: 'g2', label: '分组二' }],
|
||||
series: [{ key: 'rate_drop_pp', label: '合格率变化(pp)', values: [2.5, -4] }],
|
||||
evidenceRefs: ['evidence-1'], requiredFields: ['black_good_weight', 'black_total_weight'],
|
||||
scope: { department: '工业电机' }, period: { label: '2026-09' }, comparisonPeriod: { label: '2026-08' },
|
||||
coverage: { totalRows: 2, returnedRows: 2, truncated: false },
|
||||
note: '条形末端显示具体变化:正值为下降,负值为改善,单位是百分点。本图只按率降幅排序,未纳入投入规模。',
|
||||
});
|
||||
const model = parseAnalysisVisuals([legacy], 1).visuals[0];
|
||||
assert.deepEqual(model.series[0].values, [-2.5, 4]);
|
||||
assert.match(model.note, /本期减比较期/);
|
||||
assert.match(model.note, /仍按率降幅排序|只按率降幅排序/);
|
||||
assert.deepEqual(parseAnalysisVisuals([model], 1).visuals[0].series[0].values, [-2.5, 4]);
|
||||
|
||||
const legacyNotes = [
|
||||
'正值表示合格率下降,负值表示改善;百分点取自正式分组率差。',
|
||||
'正值表示综合合格率下降,负值表示改善;按正式综合率比较,不作为生产根因。',
|
||||
undefined,
|
||||
];
|
||||
for (const [index, note] of legacyNotes.entries()) {
|
||||
const snapshot = { ...legacy, id: `legacy-rate-drop-${index}`, note };
|
||||
const normalized = parseAnalysisVisuals([snapshot], 1).visuals[0];
|
||||
assert.deepEqual(normalized.series[0].values, [-2.5, 4]);
|
||||
assert.match(normalized.note, /本期减比较期/);
|
||||
assert.deepEqual(parseAnalysisVisuals([normalized], 1).visuals[0].series[0].values, [-2.5, 4]);
|
||||
}
|
||||
|
||||
const chart = buildAnalysisVisualOption(model);
|
||||
assert.deepEqual(chart.series[0].data, [-2.5, 4]);
|
||||
const table = renderVisualTableHtml(legacy);
|
||||
assert.match(table, /-2\.5 pp/);
|
||||
assert.match(table, /\+4 pp/);
|
||||
const exported = buildAnalysisVisualExportOption(model, 1280, 'report');
|
||||
assert.deepEqual(exported.option.series[0].data, [-2.5, 4]);
|
||||
|
||||
const modern = { ...legacy, id: 'current-rate-drop', note: '正值表示本期合格率上升,负值表示下降;变化值为本期减比较期。',
|
||||
series: [{ ...legacy.series[0], values: [-2.5, 4] }] };
|
||||
assert.deepEqual(parseAnalysisVisuals([modern], 1).visuals[0].series[0].values, [-2.5, 4]);
|
||||
|
||||
const reading = { lead: '分组变化', evidence: [], notices: [], evidenceRefs: ['evidence-1'],
|
||||
hasAppendix: false, fullAnswer: '### 业务分组变化\n\n合格率有变化。[evidence-1]', visualCount: 1 };
|
||||
const conclusion = buildConclusionDocument(reading, [model]);
|
||||
assert.deepEqual(conclusion.sections.find(section => section.title === '业务分组变化').visuals[0].series[0].values, [-2.5, 4]);
|
||||
});
|
||||
|
||||
test('checked conclusion comparisons give declines negative pp and increases positive pp', () => {
|
||||
const down = checkedConclusionComparison('9月综合合格率95.13%,较8月的95.57%下降0.44个百分点。');
|
||||
const up = checkedConclusionComparison('9月综合合格率95.57%,较8月的95.13%上升0.44个百分点。');
|
||||
assert.equal(down.change, '-0.44');
|
||||
assert.equal(up.change, '+0.44');
|
||||
assert.equal(down.direction, '下降');
|
||||
assert.equal(up.direction, '上升');
|
||||
assert.equal(checkedConclusionComparison('9月综合合格率95.13%,较8月的95.57%上升0.44个百分点。'), null);
|
||||
});
|
||||
|
||||
test('non-finite and out-of-range ratio values degrade to a table while retaining zero and null', () => {
|
||||
const parsed = parseAnalysisVisuals([visual({ series: [{ key: 'r', label: '率', values: [0, Number.NaN] }] })]);
|
||||
assert.equal(parsed.visuals.length, 1);
|
||||
|
||||
Reference in New Issue
Block a user