同步:完善质量分析工作台并更新主题字体
同步已上线的智能分析执行协议、来源查询、图表报告与管理页面配套代码。 补齐数据库迁移、运行依赖和回归测试,保留原有指标计算口径。 统一午夜黑及其他主题的控件细节、中文和业务数字字体。 排除本地业务数据、凭据、预览、发布与验收产物。 验证:生产构建通过,320项前端回归通过;本轮仅同步Git,不再次部署。
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>消息流交互验收</title></head><body><div id="root"></div><script type="module" src="./agent-flow.tsx"></script></body></html>
|
||||
@@ -0,0 +1,34 @@
|
||||
// Deterministic local UI fixture. No model calls, database changes or production writes.
|
||||
import React, { useState } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { AnalysisProcess } from '../src/AnalysisProcess';
|
||||
import '../src/styles.css';
|
||||
import '../src/analysis-chat.css';
|
||||
|
||||
const stamp = (second: number) => `2026-10-26T00:00:${String(second).padStart(2,'0')}Z`;
|
||||
function Fixture() {
|
||||
const [step,setStep]=useState(0),[long,setLong]=useState(false);
|
||||
const active=step<4;
|
||||
const thought=(id:string,at:number,text:string,running:boolean)=>({id,source:'api',model:'local-fixture',phase:'analysis',status:running?'running':'completed',version:step+1,text,streaming:true,truncated:false,at:stamp(at)});
|
||||
const first='先核对两个期间与业务范围,再使用正式指标查询。';
|
||||
const thoughts=[thought('api-abcd1234-1',1,step===0?'先核对两个期间':first,step===0),
|
||||
...(step>=2?[thought('api-abcd1234-2',4,'查询结果已经返回,继续核对变化方向并整理结论。'+(step>=3?'保留原始指标口径。':''),step<4)]:[])];
|
||||
if(long)thoughts[thoughts.length-1].text+='\n中文长文保留原始换行,完整显示。🙂 <img src=x onerror=alert(1)>\n'.repeat(1800);
|
||||
const timeline=step>=1?[
|
||||
{kind:'assistant',sequence:1,at:stamp(2),text:'我来对比这两个期间的质量表现。'},
|
||||
{kind:'tool_start',sequence:2,at:stamp(3),tool:'mcp_call',toolCallId:'query-1',label:'查询期间对比',status:'started',input:{mode:'compare',year:2026,month:9}},
|
||||
...(step>=2?[{kind:'tool_result',sequence:3,at:stamp(4),tool:'mcp_call',toolCallId:'query-1',label:'查询期间对比',status:'completed',text:'两个期间的正式指标已返回。'}]:[]),
|
||||
...(step>=3?[{kind:'assistant',sequence:4,at:stamp(5),text:'指标已核对,接下来整理重点变化。'}]:[]),
|
||||
]:[];
|
||||
return <main style={{maxWidth:1000,margin:'auto',padding:24}}>
|
||||
<div style={{display:'flex',gap:12,marginBottom:24}}>
|
||||
<button disabled={step===4} onClick={()=>setStep(value=>value+1)}>下一步</button>
|
||||
<button onClick={()=>{setStep(0);setLong(false);}}>重新开始</button>
|
||||
<button onClick={()=>setLong(value=>!value)}>切换长文</button>
|
||||
</div>
|
||||
<AnalysisProcess turn={{id:'ordered-flow',status:active?'RUNNING':'COMPLETED',modelThinking:thoughts,timeline}}
|
||||
metadata={<span className="analysis-turn-metadata"><span>{active?'运行中':'已完成'}</span><span>运行时长 {step+1}秒</span></span>}/>
|
||||
{!active&&<div className="analysis-answer"><p>两个期间的质量指标已完成核对,以下为本轮最终结论。</p></div>}
|
||||
</main>;
|
||||
}
|
||||
createRoot(document.getElementById('root')!).render(<Fixture/>);
|
||||
@@ -0,0 +1,102 @@
|
||||
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 { analysisClarificationRequest, clarificationContinuation, pendingClarificationTurnId } from '../src/analysisClarificationModel.ts';
|
||||
|
||||
const turn = () => ({ id: 'clarify-1', status: 'NEEDS_CLARIFICATION', result: { clarificationRequest: {
|
||||
question: '请选择分析规格。', options: [{ label: '规格 T', value: '18X15X4+T', description: '授权候选' }, { label: '规格 Z', value: '18X15X4+Z' }], allowCustom: true,
|
||||
} } });
|
||||
const find = (tree, predicate) => {
|
||||
if (!tree || typeof tree !== 'object') return;
|
||||
if (predicate(tree)) return tree;
|
||||
for (const child of React.Children.toArray(tree.props?.children)) { const found = find(child, predicate); if (found) return found; }
|
||||
};
|
||||
|
||||
function fixture(initial = turn(), onContinue = async () => {}) {
|
||||
let cursor = 0, queued = [], dirty = false, tree;
|
||||
const state = new Map(), refs = new Map(), effects = new Map();
|
||||
const hooks = {
|
||||
useState(initial) { const id = cursor++; if (!state.has(id)) state.set(id, initial); return [state.get(id), value => { const next = typeof value === 'function' ? value(state.get(id)) : value; if (!Object.is(next, state.get(id))) { state.set(id, next); dirty = true; } }]; },
|
||||
useRef(initial) { const id = cursor++; if (!refs.has(id)) refs.set(id, { current: initial }); return refs.get(id); },
|
||||
useEffect(fn, deps) { const id = cursor++, old = effects.get(id); if (!old || deps.some((value, i) => !Object.is(value, old[i]))) { effects.set(id, deps); queued.push(fn); } },
|
||||
};
|
||||
const source = fs.readFileSync(new URL('../src/AnalysisClarification.tsx', import.meta.url), 'utf8');
|
||||
const body = ts.transpileModule(source.slice(source.indexOf('export function')).replace('export function', 'function'), {
|
||||
fileName: 'clarification.tsx', compilerOptions: { target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.React },
|
||||
}).outputText;
|
||||
const Component = new Function('React', 'hooks', 'analysisClarificationRequest', 'clarificationContinuation', `
|
||||
const {useState,useRef,useEffect}=hooks; const Button='Button',Input={TextArea:'TextArea'};
|
||||
${body}
|
||||
return AnalysisClarification;
|
||||
`)(React, hooks, analysisClarificationRequest, clarificationContinuation);
|
||||
const props = { turn: initial, onContinue, disabled: false };
|
||||
const render = () => { let n = 0; do { dirty = false; cursor = 0; queued = []; tree = Component(props); queued.forEach(fn => fn()); if (++n > 15) throw Error('render loop'); } while (dirty); return tree; };
|
||||
return { props, render, choose(value) { find(tree, node => node.type === 'input' && node.props.value === value).props.onChange(); return render(); },
|
||||
input(value) { find(tree, node => node.type === 'TextArea').props.onChange({ target: { value } }); return render(); },
|
||||
confirm() { return find(tree, node => node.type === 'Button').props.onClick(); },
|
||||
button: () => find(tree, node => node.type === 'Button'),
|
||||
radios: () => { const nodes = []; const visit = node => { if (!node || typeof node !== 'object') return; if (node.type === 'input') nodes.push(node); React.Children.toArray(node.props?.children).forEach(visit); }; visit(tree); return nodes; },
|
||||
};
|
||||
}
|
||||
|
||||
test('saved product ambiguity exposes only server candidate names, not names parsed from prose', () => {
|
||||
const current = { status: 'NEEDS_CLARIFICATION', answer: '请选择 A 或 B', plan: { task: { productResolution: { productMatch: { status: 'ambiguous', candidates: [{ name: 'A' }, { name: 'B' }] } } } } };
|
||||
assert.deepEqual(analysisClarificationRequest(current).options.map(item => item.value), ['A', 'B']);
|
||||
assert.equal(analysisClarificationRequest({ status: 'NEEDS_CLARIFICATION', answer: '请选择 A 或 B' }).options.length, 0);
|
||||
assert.equal(analysisClarificationRequest({ ...current, status: 'FAILED' }), null);
|
||||
});
|
||||
|
||||
test('continuations reject forged choices and preserve the original goal, selected value, and supplement', () => {
|
||||
const request = analysisClarificationRequest(turn());
|
||||
assert.equal(clarificationContinuation(request, 'forged', ''), null);
|
||||
assert.equal(clarificationContinuation(request, '', ' '), null);
|
||||
const result = clarificationContinuation(request, '18X15X4+T', '只看黑片');
|
||||
assert.match(result, /保留未修改的原目标和条件/); assert.match(result, /我的选择:18X15X4\+T/); assert.match(result, /补充说明:只看黑片/);
|
||||
assert.doesNotMatch(result, /18X15X4\+Z/);
|
||||
});
|
||||
|
||||
test('no option is preselected or automatically submitted; explicit confirmation sends one selection', async () => {
|
||||
const calls = []; let done;
|
||||
const ui = fixture(turn(), question => { calls.push(question); return new Promise(resolve => { done = resolve; }); });
|
||||
ui.render(); assert.equal(calls.length, 0); assert.equal(ui.button().props.disabled, true); assert.ok(ui.radios().every(input => !input.props.checked));
|
||||
ui.confirm(); assert.equal(calls.length, 0);
|
||||
ui.choose('18X15X4+T'); assert.equal(calls.length, 0); assert.equal(ui.button().props.disabled, false);
|
||||
ui.confirm(); ui.confirm(); ui.render(); assert.equal(calls.length, 1); assert.equal(ui.button().props.disabled, true);
|
||||
done(); await new Promise(resolve => setImmediate(resolve)); ui.render();
|
||||
assert.match(calls[0], /18X15X4\+T/);
|
||||
});
|
||||
|
||||
test('free text alone can continue a missing-condition question and failure keeps it editable', async () => {
|
||||
let calls = 0;
|
||||
const current = { id: 'missing', status: 'NEEDS_CLARIFICATION', result: { clarificationRequest: { question: '请补充比较期间。', options: [] } } };
|
||||
const ui = fixture(current, () => { calls++; throw Error('连接中断'); });
|
||||
ui.render(); ui.input('2026年9月与8月'); ui.confirm(); await new Promise(resolve => setImmediate(resolve)); const tree = ui.render();
|
||||
assert.equal(calls, 1); assert.ok(find(tree, node => node.props?.role === 'alert')); assert.equal(ui.button().props.disabled, false);
|
||||
});
|
||||
|
||||
test('a refreshed question clears prior selections; disabled views cannot submit', () => {
|
||||
const calls = [], ui = fixture(turn(), question => { calls.push(question); });
|
||||
ui.render(); ui.choose('18X15X4+Z'); ui.input('保留原期间');
|
||||
ui.props.turn = { ...turn(), id: 'clarify-2' }; ui.render(); assert.ok(ui.radios().every(input => !input.props.checked)); assert.equal(ui.button().props.disabled, true);
|
||||
ui.choose('18X15X4+T'); ui.props.disabled = true; ui.render(); ui.confirm(); assert.deepEqual(calls, []);
|
||||
});
|
||||
|
||||
test('current page wires clarification only to the latest editable turn through normal submission', () => {
|
||||
const source = fs.readFileSync(new URL('../src/ManagementPages.tsx', import.meta.url), 'utf8');
|
||||
const historical = source.slice(source.indexOf('{turns.map((turn, index)'), source.indexOf('{lastTurn && <AnalysisTurn'));
|
||||
assert.doesNotMatch(historical, /onClarify=/);
|
||||
assert.match(source, /onClarify=\{sessionReadOnly \? undefined : question => submit\(question\)\}/);
|
||||
});
|
||||
|
||||
|
||||
test('reopened conversations restore only the newest unanswered clarification to the current turn', () => {
|
||||
const waiting = turn();
|
||||
assert.equal(pendingClarificationTurnId([]), '');
|
||||
assert.equal(pendingClarificationTurnId([{id:'old', status:'COMPLETED'}, waiting]), waiting.id);
|
||||
assert.equal(pendingClarificationTurnId([waiting, {id:'answered',status:'COMPLETED'}]), '');
|
||||
assert.equal(pendingClarificationTurnId([{id:'failed', status:'FAILED'}]), '');
|
||||
const source = fs.readFileSync(new URL('../src/ManagementPages.tsx', import.meta.url), 'utf8');
|
||||
assert.match(source, /focusTurnId \|\| \(active \? String\(active.id \|\| ''\) : pendingClarificationTurnId\(historyTurns\)\)/);
|
||||
});
|
||||
@@ -0,0 +1,124 @@
|
||||
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 {
|
||||
analysisMemberListFullyRead,
|
||||
analysisMemberListPage,
|
||||
authorizedMemberListRead,
|
||||
parseAnalysisMemberList,
|
||||
} from '../src/analysisMembersModel.ts';
|
||||
|
||||
const snapshotSource = fs.readFileSync(new URL('../src/analysisSnapshot.ts', import.meta.url), 'utf8')
|
||||
.replace(/^import .*;$/gm, '').replaceAll('export function ', 'function ').replaceAll('export async function ', 'async function ');
|
||||
const reportSnapshotIdentity = new Function('api', `${ts.transpileModule(`${snapshotSource}\nreturn reportSnapshotIdentity;`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText}`)({});
|
||||
|
||||
const fixture = overrides => ({
|
||||
schemaVersion: 1, releaseId: 'release-26-09', period: { year: 2026, month: 9 },
|
||||
fields: [{ key: 'member', label: '成员' }, { key: 'note', label: '说明' }],
|
||||
rows: Array.from({ length: 123 }, (_, index) => ({ values: { member: `成员${index + 1}`, note: null }, stages: index % 2 ? ['bright'] : ['black', 'bright'] })),
|
||||
totalCount: 123, rowsReturned: 123, queryComplete: true, ...overrides,
|
||||
});
|
||||
|
||||
test('validates the versioned snapshot shape and rejects inconsistent or unsafe cells', () => {
|
||||
const parsed = parseAnalysisMemberList(fixture());
|
||||
assert.equal(parsed.fields.length, 2);
|
||||
assert.equal(parsed.rows.length, 123);
|
||||
for (const overrides of [
|
||||
{ schemaVersion: 2 },
|
||||
{ fields: [{ key: 'x', label: 'X' }, { key: 'x', label: '重名' }] },
|
||||
{ fields: [] },
|
||||
{ fields: Array.from({ length: 6 }, (_, index) => ({ key: `k${index}`, label: `字段${index}` })) },
|
||||
{ rowsReturned: 122 },
|
||||
{ rows: [{ values: { member: { html: '<b>' }, note: null }, stages: ['black'] }], rowsReturned: 1, totalCount: 1, queryComplete: false },
|
||||
{ rows: [{ values: { member: 'A', note: null }, stages: ['other'] }], rowsReturned: 1, totalCount: 1, queryComplete: false },
|
||||
{ rows: [{ values: { member: 'A' }, stages: ['black'] }], rowsReturned: 1, totalCount: 1, queryComplete: false },
|
||||
{ rows: [{ values: { member: 'A', note: null }, stages: [] }], rowsReturned: 1, totalCount: 1, queryComplete: false },
|
||||
{ rows: [{ values: { member: 'A', note: null }, stages: ['black', 'black'] }], rowsReturned: 1, totalCount: 1, queryComplete: false },
|
||||
{ rows: fixture().rows.slice(0, 122), queryComplete: true, rowsReturned: 122, totalCount: 123 },
|
||||
{ rows: Array.from({ length: 4001 }, () => ({ values: { member: 'A', note: null }, stages: ['black'] })), rowsReturned: 4001, totalCount: 4001, queryComplete: true },
|
||||
{ period: { year: 2026, month: 9, quarter: 3 } },
|
||||
]) assert.equal(parseAnalysisMemberList(fixture(overrides)), null);
|
||||
});
|
||||
|
||||
test('pagination reaches all returned rows and allows a selected page size', () => {
|
||||
const parsed = parseAnalysisMemberList(fixture());
|
||||
const first = analysisMemberListPage(parsed, 1, 50);
|
||||
const last = analysisMemberListPage(parsed, 3, 50);
|
||||
assert.equal(first.rows.length, 50);
|
||||
assert.equal(last.offset, 100);
|
||||
assert.equal(last.rows.length, 23);
|
||||
assert.equal(analysisMemberListPage(parsed, 99, 100).page, 2);
|
||||
assert.equal(analysisMemberListPage(parsed, 2, 100).rows.length, 23);
|
||||
});
|
||||
|
||||
test('full-read status requires both query completion and the declared total', () => {
|
||||
const complete = parseAnalysisMemberList(fixture());
|
||||
assert.equal(analysisMemberListFullyRead(complete), true);
|
||||
const shortRead = parseAnalysisMemberList(fixture({ rows: fixture().rows.slice(0, 50), rowsReturned: 50, queryComplete: false }));
|
||||
assert.equal(analysisMemberListFullyRead(shortRead), false);
|
||||
const unfinished = parseAnalysisMemberList(fixture({ queryComplete: false }));
|
||||
assert.equal(analysisMemberListFullyRead(unfinished), false);
|
||||
});
|
||||
|
||||
test('a failed permission refresh clears the list data and calls the existing unauthorized callback', async () => {
|
||||
const data = parseAnalysisMemberList(fixture());
|
||||
const denied = Object.assign(new Error('permission changed'), { status: 403 });
|
||||
let callbackError;
|
||||
const result = await authorizedMemberListRead(data, async () => { throw denied; }, error => { callbackError = error; return true; });
|
||||
assert.equal(result.data, null);
|
||||
assert.equal(callbackError, denied);
|
||||
assert.match(result.error, /成员清单已清空/);
|
||||
});
|
||||
|
||||
test('a failed snapshot recheck exposes only the sanitized error message', async () => {
|
||||
const data = parseAnalysisMemberList(fixture());
|
||||
const result = await authorizedMemberListRead(data,
|
||||
async () => { throw new Error('快照复核失败:release_id: 123e4567-e89b-12d3-a456-426614174000,请重新打开'); },
|
||||
() => false);
|
||||
assert.equal(result.data, null);
|
||||
assert.match(result.error, /快照复核失败/);
|
||||
assert.match(result.error, /请重新打开/);
|
||||
assert.doesNotMatch(result.error, /123e4567-e89b-12d3-a456-426614174000/);
|
||||
});
|
||||
|
||||
test('snapshot identity includes the member list so stale rows fail the existing authorization check', () => {
|
||||
const before = { id: 'turn-1', status: 'COMPLETED', answer: 'summary', memberList: fixture({ rows: [{ values: { member: 'A', note: null }, stages: ['black'] }], rowsReturned: 1, totalCount: 1 }) };
|
||||
const after = { ...before, memberList: fixture({ rows: [{ values: { member: 'B', note: null }, stages: ['black'] }], rowsReturned: 1, totalCount: 1 }) };
|
||||
assert.notEqual(reportSnapshotIdentity(before), reportSnapshotIdentity(after));
|
||||
});
|
||||
|
||||
test('the chat table renders raw member values as escaped text, not HTML or links', () => {
|
||||
const source = fs.readFileSync(new URL('../src/AnalysisMemberList.tsx', import.meta.url), 'utf8')
|
||||
.replace(/^import[\s\S]*?;\s*$/gm, '').replace('export function AnalysisMemberListPanel', 'function AnalysisMemberListPanel');
|
||||
const stateReady = () => [{ status: 'ready', page: 1, pageSize: 50, error: '' }, () => {}];
|
||||
const Table = props => React.createElement('table', null, ...props.dataSource.map(row => React.createElement('tr', { key: props.rowKey(row) },
|
||||
...props.columns.map(column => React.createElement('td', { key: column.key }, column.render ? column.render(undefined, row) : row[column.dataIndex])))));
|
||||
const passthrough = ({ children }) => React.createElement('div', null, children);
|
||||
const Panel = new Function('React', 'useCallback', 'useEffect', 'useMemo', 'useRef', 'useState', 'Alert', 'Empty', 'Pagination', 'Select', 'Spin', 'Tag', 'Table', 'authorizeAnalysisSnapshot',
|
||||
'analysisMemberListFullyRead', 'analysisMemberListPage', 'analysisMemberListPeriod', 'authorizedMemberListRead', 'parseAnalysisMemberList',
|
||||
ts.transpileModule(`${source}\nreturn AnalysisMemberListPanel;`, { fileName: 'analysis-members.tsx', compilerOptions: { target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.React } }).outputText
|
||||
)(React, callback => callback, () => {}, callback => callback(), value => ({ current: value }), stateReady,
|
||||
passthrough, { PRESENTED_IMAGE_SIMPLE: 'simple' }, passthrough, passthrough, passthrough, passthrough, Table, async () => {},
|
||||
analysisMemberListFullyRead, analysisMemberListPage, () => '2026年9月', async data => ({ data, error: '' }), parseAnalysisMemberList);
|
||||
const danger = '<img src=x onerror=alert(1)> https://example.test';
|
||||
const html = renderToStaticMarkup(React.createElement(Panel, { turn: { id: 'turn-1' }, value: fixture({ rows: [{ values: { member: danger, note: null }, stages: ['black'] }], rowsReturned: 1, totalCount: 1 }), onUnauthorized: () => false }));
|
||||
assert.match(html, /<img src=x onerror=alert\(1\)> https:\/\/example\.test/);
|
||||
assert.doesNotMatch(html, /<img|<a\b/);
|
||||
});
|
||||
|
||||
test('member-list display is opt-in, keeping earlier Markdown answers on their existing path', () => {
|
||||
const source = fs.readFileSync(new URL('../src/ManagementPages.tsx', import.meta.url), 'utf8');
|
||||
const turn = source.slice(source.indexOf('function AnalysisTurn('), source.indexOf('function AnalysisTurnMetadata('))
|
||||
.replace('function AnalysisTurn(', 'function AnalysisTurn(');
|
||||
const component = new Function('React', 'useAnalysisVisualRecovery', 'partialAnswerIsOnlyProgress', 'analysisScopeText', 'isObjectRecord', 'AnalysisProcess', 'AnalysisTurnMetadata', 'AiMarkdown', 'AnalysisNarrative', 'NativeAnalysisReport', 'AnalysisReportExport', 'Button', 'AnalysisMemberListPanel',
|
||||
ts.transpileModule(`${turn}\nreturn AnalysisTurn;`, { fileName: 'analysis-turn.tsx', compilerOptions: { target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.React } }).outputText
|
||||
)(React, turn => ({turn,available:false,recovering:false,error:''}), () => false, () => '', value => Boolean(value) && typeof value === 'object' && !Array.isArray(value), () => null, () => null, ({ content }) => React.createElement('p', null, content),
|
||||
({ answer }) => React.createElement('div', { className: 'legacy-markdown' }, answer), () => null, () => null, ({ children }) => React.createElement('button', null, children), () => null);
|
||||
const html = renderToStaticMarkup(React.createElement(component, { turn: { id: 'old-turn', status: 'COMPLETED', answer: '| old | Markdown table |' }, onUnauthorized: () => false }));
|
||||
assert.match(html, /legacy-markdown/);
|
||||
assert.match(html, /\| old \| Markdown table \|/);
|
||||
assert.doesNotMatch(html, /analysis-member-list/);
|
||||
});
|
||||
@@ -0,0 +1,78 @@
|
||||
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 { parseServerReadingSummary } from '../src/analysisReadingModel.ts';
|
||||
import {
|
||||
analysisMemberListFullyRead,
|
||||
analysisMemberListPeriod,
|
||||
parseAnalysisMemberList,
|
||||
} from '../src/analysisMembersModel.ts';
|
||||
|
||||
const exportSource = fs.readFileSync(new URL('../src/AnalysisReportExport.tsx', import.meta.url), 'utf8');
|
||||
const reportDocumentSource = exportSource.slice(exportSource.indexOf('function ReportDocument('), exportSource.indexOf('\nfunction reportHtmlFromElement('));
|
||||
const node = (tag, props) => React.createElement(tag, props, props?.children);
|
||||
const ReportDocument = new Function('React', 'reportCss', 'record', 'text', 'buildAnalysisNarrative', 'analysisScopeText',
|
||||
'parseServerReadingSummary', 'resolveAnalysisReportTitle', 'sanitizeAnalysisDisplayText', 'stripDuplicateFirstMarkdownH1', 'AnalysisReportNarrative',
|
||||
'AnalysisLegacyResults', 'AnalysisRecordListReport', 'analysisMemberListFullyRead', 'analysisMemberListPeriod', 'parseAnalysisMemberList',
|
||||
ts.transpileModule(`${reportDocumentSource}\nreturn ReportDocument;`, {
|
||||
fileName: 'analysis-report-document.tsx',
|
||||
compilerOptions: { target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.React },
|
||||
}).outputText
|
||||
)(React, '', value => value && typeof value === 'object' && !Array.isArray(value) ? value : {},
|
||||
value => value === null || value === undefined || value === '' ? '—' : String(value),
|
||||
() => ({ period: '2026年9月' }), () => '', parseServerReadingSummary, () => '分析报告', value => value, value => value,
|
||||
({ answer }) => node('div', { className: 'report-summary', children: answer }), () => null, () => null,
|
||||
analysisMemberListFullyRead, analysisMemberListPeriod, parseAnalysisMemberList);
|
||||
|
||||
function memberListFixture() {
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
releaseId: 'release-2026-09',
|
||||
period: { year: 2026, month: 9 },
|
||||
fields: [{ key: 'member', label: '成员' }, { key: 'note', label: '备注' }],
|
||||
rows: Array.from({ length: 181 }, (_, index) => ({
|
||||
values: { member: index === 180 ? '最后一行成员181' : `成员${index + 1}`, note: index === 0 ? '<img src=x onerror=alert(1)>' : index % 3 ? `备注${index + 1}` : null },
|
||||
stages: [index % 2 ? 'bright' : 'black'],
|
||||
})),
|
||||
totalCount: 181,
|
||||
rowsReturned: 181,
|
||||
queryComplete: true,
|
||||
};
|
||||
}
|
||||
|
||||
test('the report includes every member row beyond the former 150-row limit as a static escaped table', () => {
|
||||
const html = renderToStaticMarkup(React.createElement(ReportDocument, {
|
||||
turn: { id: 'turn-1', status: 'COMPLETED', result: { answer: '摘要内容', memberList: memberListFixture() } },
|
||||
stamp: '2026-10-27 12:00:00', visualImages: [],
|
||||
}));
|
||||
|
||||
assert.match(html, /<h2>成员清单<\/h2>/);
|
||||
assert.match(html, /<th>成员<\/th>/);
|
||||
assert.match(html, /<th>备注<\/th>/);
|
||||
assert.match(html, /<th>阶段<\/th>/);
|
||||
assert.equal((html.match(/<tr/g) || []).length, 182);
|
||||
assert.match(html, /最后一行成员181/);
|
||||
assert.match(html, /黑片/);
|
||||
assert.match(html, /亮片/);
|
||||
assert.match(html, /—/);
|
||||
assert.match(html, /已读取全部 181 条/);
|
||||
assert.match(html, /<img src=x onerror=alert\(1\)>/);
|
||||
assert.doesNotMatch(html, /<img|<a\b/);
|
||||
assert.doesNotMatch(html, /分页|每页显示|下一页/);
|
||||
});
|
||||
|
||||
test('the report accepts a root memberList and labels incomplete coverage', () => {
|
||||
const source = memberListFixture();
|
||||
source.rows = source.rows.slice(0, 160);
|
||||
source.rowsReturned = 160;
|
||||
source.queryComplete = false;
|
||||
const html = renderToStaticMarkup(React.createElement(ReportDocument, {
|
||||
turn: { id: 'turn-2', status: 'PARTIAL', answer: '摘要', memberList: source },
|
||||
stamp: '2026-10-27 12:00:00', visualImages: [],
|
||||
}));
|
||||
assert.equal((html.match(/<tr/g) || []).length, 161);
|
||||
assert.match(html, /读取未完成 160 \/ 181 条/);
|
||||
});
|
||||
@@ -0,0 +1,68 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {mergeModelThinking,modelThinkingEntries,thinkingStatus,orderedAnalysisProcess,groupAdjacentThinking} from '../src/analysisModelThinking.ts';
|
||||
const block={id:'api-abcd1234-1',model:'fixture',source:'api',phase:'planning',status:'running',streaming:true,truncated:false};
|
||||
|
||||
test('replayed chunks cannot duplicate or shorten full provider thinking',()=>{
|
||||
let rows=mergeModelThinking([],{...block,version:1,text:'先核对🙂'});
|
||||
rows=mergeModelThinking(rows,{...block,version:2,baseVersion:1,delta:'再比较'});
|
||||
rows=mergeModelThinking(rows,{...block,version:2,baseVersion:1,delta:'再比较'});
|
||||
assert.equal(rows[0].text,'先核对🙂再比较');
|
||||
const turn={modelThinking:rows,plan:{modelThinking:[{...block,version:1,text:'先核对🙂'}]}};
|
||||
assert.equal(modelThinkingEntries(turn)[0].text,'先核对🙂再比较');
|
||||
});
|
||||
test('a missed chunk waits for an authoritative checkpoint instead of inventing missing text',()=>{
|
||||
let rows=mergeModelThinking([],{...block,version:2,baseVersion:1,delta:'尾部'});
|
||||
assert.equal(rows[0].text,'');assert.equal(rows[0].recovering,true);
|
||||
rows=mergeModelThinking(rows,{...block,version:3,baseVersion:2,delta:'不能假装补齐'});
|
||||
assert.equal(rows[0].recovering,true);assert.equal(rows[0].text,'');
|
||||
rows=mergeModelThinking(rows,{...block,version:4,text:'完整的接口文本'});
|
||||
assert.equal(rows[0].text,'完整的接口文本');assert.equal(rows[0].recovering,false);
|
||||
});
|
||||
test('new attempts reset prior thought text, while history remains complete beyond 8000 characters',()=>{
|
||||
let rows=mergeModelThinking([],{...block,version:10,text:'上次内容'});
|
||||
rows=mergeModelThinking(rows,{...block,id:'api-eeee1111-1',reset:true,version:1,text:'长文本'.repeat(5000)});
|
||||
assert.equal(rows.length,1);assert.equal(rows[0].text.length,15000);
|
||||
assert.equal(thinkingStatus({...rows[0],status:'not_returned'},false),'接口未返回思考文本');
|
||||
assert.match(thinkingStatus(rows[0],false),/已中断/);
|
||||
assert.deepEqual(modelThinkingEntries({answer:'这不能被当作思考'}),[]);
|
||||
});
|
||||
|
||||
test('stream ordering uses first text time and never moves a growing thought below later tools',()=>{
|
||||
const first={...block,version:1,text:'先思考',at:'2026-10-26T00:00:01Z'};
|
||||
let rows=mergeModelThinking([] ,first);
|
||||
rows=mergeModelThinking(rows,{...first,text:undefined,version:2,baseVersion:1,delta:'继续思考',finishedAt:'2026-10-26T00:00:04Z'});
|
||||
const ordered=orderedAnalysisProcess({modelThinking:rows},[{kind:'tool',sequence:1,at:'2026-10-26T00:00:02Z'}]);
|
||||
assert.deepEqual(ordered.map(row=>row.kind),['thinking','tool']);assert.equal(ordered[0].text,'先思考继续思考');
|
||||
});
|
||||
test('legacy thoughts without times retain text without claiming an invented date',()=>{
|
||||
const ordered=orderedAnalysisProcess({modelThinking:[{...block,version:1,text:'旧记录'}]},[]);
|
||||
assert.equal(ordered[0].at,undefined);assert.equal(ordered[0].text,'旧记录');
|
||||
});
|
||||
|
||||
test('saved result plan remains readable when no top-level plan is present',()=>{
|
||||
assert.equal(modelThinkingEntries({result:{plan:{modelThinking:[{...block,version:1,text:'保存的思考全文'}]}}})[0].text,'保存的思考全文');
|
||||
});
|
||||
|
||||
test('adjacent thinking shares one disclosure while tool and narrative boundaries remain in place',()=>{
|
||||
const entries=[{kind:'thinking',id:'a',key:'a',text:'第一段',status:'completed'}, {kind:'thinking',id:'b',key:'b',text:'第二段',status:'running'}, {kind:'tool',key:'c'}, {kind:'thinking',id:'d',key:'d',text:'第三段',status:'completed'}];
|
||||
const grouped=groupAdjacentThinking(entries);
|
||||
assert.deepEqual(grouped.map(r=>r.kind),['thinking','tool','thinking']);
|
||||
assert.equal(grouped[0].text,'第一段\n\n第二段');assert.equal(grouped[0].status,'running');assert.equal(grouped[0].id,'a');
|
||||
assert.equal(entries[0].text,'第一段');
|
||||
assert.equal(groupAdjacentThinking(entries.map(e=>({...e,status:'completed'})))[0].status,'completed');
|
||||
});
|
||||
|
||||
test('thinking frames reveal received text smoothly and preserve complete Unicode at completion',async()=>{
|
||||
const {thinkingTextFrame}=await import('../src/analysisModelThinking.ts');
|
||||
const from='已收到:',target=from+'核对🙂之后比较,再生成图表。';
|
||||
let previous=from;
|
||||
for(let ms=0;ms<=100;ms+=5){
|
||||
const frame=thinkingTextFrame(from,target,ms);
|
||||
assert.ok(target.startsWith(frame));assert.ok(frame.startsWith(previous));
|
||||
assert.doesNotMatch(frame,/[\uD800-\uDBFF]$/);previous=frame;
|
||||
}
|
||||
assert.equal(previous,target);
|
||||
assert.equal(thinkingTextFrame('旧调用','新调用原文',10),'新调用原文');
|
||||
assert.equal(thinkingTextFrame(from,target,1000),target);
|
||||
});
|
||||
@@ -0,0 +1,106 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import ts from 'typescript';
|
||||
import { analysisPeriodLabel, isValidAnalysisPeriodContext, parseAnalysisPeriod } from '../src/analysisPeriodModel.ts';
|
||||
import { analysisScopeText } from '../src/analysisScope.ts';
|
||||
import { analysisMemberListPeriod, parseAnalysisMemberList } from '../src/analysisMembersModel.ts';
|
||||
import { buildAnalysisNarrative } from '../src/analysisReportModel.ts';
|
||||
import { parseAnalysisVisuals, renderVisualTableHtml, visualPeriodSummary } from '../src/analysisVisualsModel.ts';
|
||||
|
||||
const snapshotSource = readFileSync(new URL('../src/analysisSnapshot.ts', import.meta.url), 'utf8').replace(/^import .*;$/gm, '').replace(/^export /gm, '');
|
||||
const snapshotIdentity = new Function(ts.transpileModule(snapshotSource, {
|
||||
compilerOptions: { target: ts.ScriptTarget.ES2022 },
|
||||
}).outputText + '\nreturn { reportSnapshotIdentity, reportSnapshotDifferences };')();
|
||||
|
||||
const range = { year: 2026, monthStart: 1, monthEnd: 9 };
|
||||
const visual = (period = range, overrides = {}) => ({
|
||||
id: 'range-chart', type: 'line', title: '连续月份趋势', subtitle: '正式指标', unit: 'ratio',
|
||||
categories: [{ key: '2026-01', label: '1月' }, { key: '2026-09', label: '9月' }],
|
||||
series: [{ key: 'overall', label: '综合', values: [0.95, 0.94] }],
|
||||
evidenceRefs: ['Q1234ABCD'], requiredFields: ['composite_rate'],
|
||||
scope: { ...range, releaseId: 'release-a' }, period,
|
||||
metric: 'composite_rate', coverage: { totalRows: 2, returnedRows: 2, truncated: false }, originTurnId: 'turn-a',
|
||||
...overrides,
|
||||
});
|
||||
|
||||
test('month ranges validate as a paired period and keep old year/month/quarter forms', () => {
|
||||
assert.deepEqual(parseAnalysisPeriod(range), range);
|
||||
assert.equal(analysisPeriodLabel(range), '2026年1—9月');
|
||||
assert.equal(analysisPeriodLabel({ year: 2026, month: 9 }), '2026年9月');
|
||||
assert.equal(analysisPeriodLabel({ year: 2026, quarter: 3 }), '2026年第3季度');
|
||||
assert.equal(analysisPeriodLabel({ year: 2026 }), '2026年');
|
||||
for (const invalid of [
|
||||
{ year: 2026, monthStart: 1 },
|
||||
{ year: 2026, monthEnd: 9 },
|
||||
{ year: 2026, monthStart: 10, monthEnd: 9 },
|
||||
{ year: 2026, monthStart: 0, monthEnd: 9 },
|
||||
{ year: 2026, monthStart: 1, monthEnd: 13 },
|
||||
{ year: 2026, month: 9, monthStart: 1, monthEnd: 9 },
|
||||
{ year: 2026, quarter: 3, monthStart: 1, monthEnd: 9 },
|
||||
]) {
|
||||
assert.equal(isValidAnalysisPeriodContext(invalid), false, JSON.stringify(invalid));
|
||||
assert.equal(analysisPeriodLabel(invalid), '');
|
||||
}
|
||||
});
|
||||
|
||||
test('scope and visual labels retain a month range through report narrative and table export', () => {
|
||||
const summary = parseAnalysisVisuals([visual(range, { comparisonPeriod: { year: 2025, monthStart: 1, monthEnd: 9 } })]);
|
||||
assert.equal(summary.visuals.length, 1);
|
||||
const chart = summary.visuals[0];
|
||||
assert.equal(visualPeriodSummary(chart), '2025年1—9月 → 2026年1—9月');
|
||||
assert.match(renderVisualTableHtml(chart), /2025年1—9月 → 2026年1—9月/);
|
||||
const narrative = buildAnalysisNarrative('', [chart]);
|
||||
assert.equal(narrative.period, '2025年1—9月 → 2026年1—9月');
|
||||
assert.equal(analysisScopeText({ plan: { context: range } }), '2026年1—9月');
|
||||
assert.equal(parseAnalysisVisuals([visual({ ...range, monthEnd: 0 })]).visuals.length, 0);
|
||||
assert.equal(parseAnalysisVisuals([visual(range, { scope: { ...range, month: 9 } })]).visuals.length, 0);
|
||||
});
|
||||
|
||||
test('exclusion and source-column filters remain visible in the bound scope summary', () => {
|
||||
const scope = {
|
||||
...range,
|
||||
exclusions: { product: ['MIMO-V14'], group: ['海外组'] },
|
||||
columnFilters: [{ field: 'customerCode', stages: ['black'], operator: 'not_in', values: ['000123'] }],
|
||||
columnLabels: { customerCode: '客户代码' },
|
||||
};
|
||||
const chart = parseAnalysisVisuals([visual(range, { scope, evidenceRefs: ['Q1234ABCD'] })]).visuals[0];
|
||||
const turn = { id: 'turn-a', question: '看MIMO-V14趋势', plan: { context: scope }, visuals: [chart] };
|
||||
const text = analysisScopeText(turn);
|
||||
assert.match(text, /排除产品:MIMO-V14/);
|
||||
assert.match(text, /排除业务分组:海外组/);
|
||||
assert.match(text, /黑片 客户代码排除000123/);
|
||||
});
|
||||
|
||||
test('member-list snapshots accept and label ranges while keeping single-month snapshots compatible', () => {
|
||||
const base = {
|
||||
schemaVersion: 1, releaseId: 'release-a', period: range,
|
||||
fields: [{ key: 'product', label: '产品' }],
|
||||
rows: [{ values: { product: 'A' }, stages: ['black'] }],
|
||||
totalCount: 1, rowsReturned: 1, queryComplete: true,
|
||||
};
|
||||
const parsed = parseAnalysisMemberList(base);
|
||||
assert.ok(parsed);
|
||||
assert.equal(analysisMemberListPeriod(parsed.period), '2026年1—9月');
|
||||
assert.equal(parseAnalysisMemberList({ ...base, period: { year: 2026, month: 9 } }).period.month, 9);
|
||||
assert.equal(parseAnalysisMemberList({ ...base, period: { year: 2026, monthStart: 10, monthEnd: 9 } }), null);
|
||||
});
|
||||
|
||||
test('report snapshot identity retains ranges in visuals and normalizes nested versus flat turn fields', () => {
|
||||
const chart = visual(range, { comparisonPeriod: { year: 2025, monthStart: 1, monthEnd: 9 } });
|
||||
const turn = { id: 'turn-a', question: '总结', result: { answer: '报告正文', visuals: [chart], results: [], memberList: null } };
|
||||
const flattened = { id: 'turn-a', question: '总结', ...turn.result };
|
||||
assert.equal(snapshotIdentity.reportSnapshotIdentity(turn), snapshotIdentity.reportSnapshotIdentity(flattened));
|
||||
const changed = { ...turn, result: { ...turn.result, visuals: [visual({ ...range, monthEnd: 8 })] } };
|
||||
assert.notEqual(snapshotIdentity.reportSnapshotIdentity(turn), snapshotIdentity.reportSnapshotIdentity(changed));
|
||||
assert.deepEqual(snapshotIdentity.reportSnapshotDifferences(changed, turn), ['visuals']);
|
||||
|
||||
const scoped = visual(range, { scope: { ...range, exclusions: { product: ['MIMO-V14'] }, columnFilters: [{ field: 'customerCode', stages: ['black'], operator: 'not_in', values: ['000123'] }] } });
|
||||
const withScope = { ...turn, result: { ...turn.result, visuals: [scoped] } };
|
||||
const changedExclusion = { ...withScope, result: { ...withScope.result, visuals: [visual(range, { scope: { ...scoped.scope, exclusions: { product: ['MIMO-V13'] } } })] } };
|
||||
assert.notEqual(snapshotIdentity.reportSnapshotIdentity(withScope), snapshotIdentity.reportSnapshotIdentity(changedExclusion));
|
||||
assert.deepEqual(snapshotIdentity.reportSnapshotDifferences(withScope, changedExclusion), ['visuals']);
|
||||
const changedColumnRule = { ...withScope, result: { ...withScope.result, visuals: [visual(range, { scope: { ...scoped.scope, columnFilters: [{ ...scoped.scope.columnFilters[0], values: ['000999'] }] } })] } };
|
||||
assert.notEqual(snapshotIdentity.reportSnapshotIdentity(withScope), snapshotIdentity.reportSnapshotIdentity(changedColumnRule));
|
||||
assert.deepEqual(snapshotIdentity.reportSnapshotDifferences(withScope, changedColumnRule), ['visuals']);
|
||||
});
|
||||
@@ -0,0 +1,121 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import React from 'react';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import ts from 'typescript';
|
||||
import { resolveProductDrilldown, productDrilldownQuery, productTrendVisual } from '../src/analysisProductDrilldown.ts';
|
||||
|
||||
const row = { product: '16.33X15.5X3.75+T', stage: 'all', scrapDelta: '+758.76', rateChange: '下降1.95个百分点', rateLabel: '综合率', basis: '按报废增量排序', detail: '两期投入与阶段数据', evidenceRefs: ['Q1234ABCD'] };
|
||||
const visual = overrides => ({ id: 'product-chart', type: 'bar', title: '重点产品', subtitle: '', unit: 'kg', metric: 'scrap_delta',
|
||||
categories: [{ key: row.product, label: row.product }], series: [{ key: 'scrap_delta', label: '报废增量', values: [758.76] }],
|
||||
dimension: 'product', evidenceRefs: ['Q1234ABCD'], requiredFields: [], originTurnId: 'turn-old',
|
||||
scope: { year: 2026, month: 9, includeUnassigned: false, releaseId: 'release-old' }, period: { year: 2026, month: 9 }, comparisonPeriod: { year: 2026, month: 8 },
|
||||
coverage: { totalRows: 1, returnedRows: 1, truncated: false }, ...overrides });
|
||||
const turn = overrides => ({ id: 'turn-old', status: 'COMPLETED', releaseId: 'release-old', plan: { context: { releaseId: 'release-old' }, frozenContext: { releaseId: 'release-old' } }, visuals: [visual()], ...overrides });
|
||||
const resolved = (t = turn(), r = row) => { const result = resolveProductDrilldown(t, r); assert.ok(result.binding, result.reason); return result.binding; };
|
||||
const denied = (t, r = row) => { const result = resolveProductDrilldown(t, r); assert.ok(result.reason); assert.equal(result.binding, undefined); return result.reason; };
|
||||
|
||||
test('exact cited product carries both original periods and the saved release', () => {
|
||||
const binding = resolved();
|
||||
assert.deepEqual(binding.stages, ['black', 'bright']);
|
||||
assert.deepEqual(binding.query, { year: 2026, month: 9, view: 'product', releaseId: 'release-old', product: row.product, includeUnassigned: false });
|
||||
assert.deepEqual(productDrilldownQuery(binding, binding.periods[1].period), { ...binding.query, month: 8 });
|
||||
});
|
||||
test('org selections, keyword, extra source filters and explicit unassigned inclusion survive', () => {
|
||||
const scope = { ...visual().scope, department: ['产业部甲', '产业部乙'], group: '国内', projectGroup: '项目A', productSearch: '16.33', extraFilters: { factory: ['一厂'], platingLine: ['线1', '线2'] }, includeUnassigned: true };
|
||||
const binding = resolved(turn({ visuals: [visual({ scope })], plan: { context: scope, frozenContext: scope } }));
|
||||
assert.ok(binding.query.department.startsWith('~qv1~'));
|
||||
assert.equal(binding.query.group, '国内'); assert.equal(binding.query.productSearch, '16.33');
|
||||
assert.deepEqual(binding.query.extraFilters, scope.extraFilters); assert.equal(binding.query.includeUnassigned, true);
|
||||
binding.query.extraFilters.factory.push('二厂'); assert.deepEqual(scope.extraFilters.factory, ['一厂']);
|
||||
});
|
||||
test('a stage-specific product never gains the other stage', () => {
|
||||
const binding = resolved(turn({ visuals: [visual({ stage: 'bright', scope: { ...visual().scope, stage: 'bright' } })] }), { ...row, stage: 'bright' });
|
||||
assert.deepEqual(binding.stages, ['bright']);
|
||||
denied(turn({ visuals: [visual({ stage: 'black' })] }), { ...row, stage: 'bright' });
|
||||
});
|
||||
test('no question prose, current session or unrelated chart can invent row provenance', () => {
|
||||
denied(turn({ question: '2026年9月看产品', visuals: [] }));
|
||||
denied(turn({ visuals: [visual({ evidenceRefs: ['Q9999ABCD'] })] }));
|
||||
denied(turn({ visuals: [visual({ originTurnId: 'turn-new' })] }));
|
||||
denied(turn({ visuals: [visual({ dimension: 'department' })] }));
|
||||
denied(turn({ visuals: [visual({ categories: [{ key: 'other', label: row.product }] })] }));
|
||||
});
|
||||
test('unknown/missing/conflicting releases and ambiguous cited ranges block requests', () => {
|
||||
denied(turn({ releaseId: undefined, plan: {}, visuals: [visual({ scope: { year: 2026, month: 9 } })] }));
|
||||
denied(turn({ releaseId: 'latest-release' }));
|
||||
denied(turn({ visuals: [visual(), visual({ id: 'second', comparisonPeriod: { year: 2026, month: 7 } })] }));
|
||||
});
|
||||
test('unsupported exclusions, unknown filters and malformed periods fail closed', () => {
|
||||
for (const exclusions of [{ product: ['other'] }, 'invalid']) denied(turn({ visuals: [visual({ scope: { ...visual().scope, exclusions } })] }));
|
||||
denied(turn({ visuals: [visual({ scope: { ...visual().scope, customFilter: 'a' } })] }));
|
||||
denied(turn({ visuals: [visual({ period: { year: 2026, month: 13 } })] }));
|
||||
denied(turn({ visuals: [visual({ period: { year: 2026, month: 9, quarter: 3 } })] }));
|
||||
});
|
||||
test('frozen conditions cannot disappear or be changed by the cited chart', () => {
|
||||
for (const context of [{ group: '国内' }, { year: 2025 }, { productSearch: '18' }, { extraFilters: { 厂区: ['一厂'] } }, { includeUnassigned: true }]) {
|
||||
denied(turn({ plan: { frozenContext: { releaseId: 'release-old', ...context } } }));
|
||||
}
|
||||
});
|
||||
test('a narrowed row must belong to its exact original product and keyword filter', () => {
|
||||
resolved(turn({ visuals: [visual({ scope: { ...visual().scope, product: [row.product, 'other'] } })] }));
|
||||
denied(turn({ visuals: [visual({ scope: { ...visual().scope, product: 'other' } })] }));
|
||||
denied(turn({ visuals: [visual({ scope: { ...visual().scope, productSearch: 'other' } })] }));
|
||||
});
|
||||
test('comparison-period filters cannot silently reuse current-period filters', () => {
|
||||
resolved(turn({ plan: { semantic: { compare: true, priorContext: { year: 2026, month: 8 } } } }));
|
||||
denied(turn({ plan: { semantic: { compare: true, priorContext: { year: 2026, month: 8, group: 'another' } } } }));
|
||||
denied(turn({ plan: { semantic: { compare: true, priorContext: { year: 2026, month: 7 } } } }));
|
||||
});
|
||||
test('period switch removes month before selecting a quarter or another year', () => {
|
||||
const binding = resolved();
|
||||
const { month: _month, ...expected } = binding.query;
|
||||
assert.deepEqual(productDrilldownQuery(binding, { year: 2025, quarter: 4 }), { ...expected, year: 2025, quarter: 4 });
|
||||
});
|
||||
|
||||
const metric = (rate = .95, blackRows = 1, brightRows = 1) => ({ key: row.product, label: row.product, department: null, group: null, product: row.product, compositeRate: rate, black: { rate, defects: [] }, bright: { rate, defects: [] }, coverage: { blackRows, brightRows } });
|
||||
const snapshot = (rate, trend = []) => ({ release: { id: 'release-old' }, summary: metric(rate), trend });
|
||||
test('monthly trend uses only two original server summaries and keeps original values', () => {
|
||||
const visuals = productTrendVisual(resolved(), [snapshot(.9513, [{ ...metric(.1), month: 1 }]), snapshot(.9557)]);
|
||||
assert.equal(visuals.length, 1);
|
||||
assert.deepEqual(visuals[0].categories.map(item => item.key), ['2026-08', '2026-09']);
|
||||
assert.deepEqual(visuals[0].series[0].values, [.9557, .9513]);
|
||||
});
|
||||
test('quarter trend discards other months returned by annual API trend', () => {
|
||||
const binding = resolved(turn({ visuals: [visual({ period: { year: 2026, quarter: 3 }, scope: { year: 2026, quarter: 3, releaseId: 'release-old' }, comparisonPeriod: undefined })] }));
|
||||
const values = Array.from({ length: 12 }, (_, i) => ({ ...metric(.9), month: i + 1 }));
|
||||
const visuals = productTrendVisual(binding, [snapshot(.9, values)]);
|
||||
assert.deepEqual(visuals[0].categories.map(item => item.key), ['2026-07', '2026-08', '2026-09']);
|
||||
});
|
||||
test('continuous month ranges survive product drilldown and exclude trend months outside the bound range', () => {
|
||||
const period = { year: 2026, monthStart: 1, monthEnd: 9 };
|
||||
const binding = resolved(turn({ visuals: [visual({ period, scope: { ...period, releaseId: 'release-old' }, comparisonPeriod: undefined })] }));
|
||||
assert.deepEqual(binding.query, { ...period, view: 'product', releaseId: 'release-old', product: row.product, includeUnassigned: false });
|
||||
assert.deepEqual(productDrilldownQuery(binding, binding.periods[0].period), binding.query);
|
||||
const values = [1, 9, 10].map(month => ({ ...metric(.9), month }));
|
||||
const charts = productTrendVisual(binding, [snapshot(.9, values)]);
|
||||
assert.deepEqual(charts[0].categories.map(item => item.key), ['2026-01', '2026-09']);
|
||||
});
|
||||
test('missing stage coverage remains null, with no fabricated zero rates', () => {
|
||||
const data = snapshot(.8); data.summary = metric(.8, 1, 0);
|
||||
const visuals = productTrendVisual(resolved(), [data, data]);
|
||||
assert.deepEqual(visuals[0].series.find(item => item.key === 'bright_rate').values, [null, null]);
|
||||
assert.deepEqual(visuals[0].series.find(item => item.key === 'composite_rate').values, [null, null]);
|
||||
const empty = snapshot(.8); empty.summary = metric(.8, 0, 0);
|
||||
assert.deepEqual(productTrendVisual(resolved(), [empty, empty]), []);
|
||||
assert.throws(() => productTrendVisual(resolved(), [{ ...data, release: { id: 'new' } }, data]), /版本/);
|
||||
});
|
||||
|
||||
const source = fs.readFileSync(new URL('../src/AnalysisNarrative.tsx', import.meta.url), 'utf8');
|
||||
const component = source.slice(source.indexOf('export function FocusProductTable'), source.indexOf('/** 聊天')).replace('export function', 'function');
|
||||
const FocusProductTable = new Function('React', 'Button', 'AiMarkdown', ts.transpileModule(`${component}\nreturn FocusProductTable;`, { fileName: 'focus.tsx', compilerOptions: { target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.React } }).outputText)(React, props => React.createElement('button', null, props.children), () => null);
|
||||
test('export reuse has no buttons while chat has exactly three compact actions', () => {
|
||||
const props = { rows: [row], evidenceLabels: {}, evidencePrefix: 'test-' };
|
||||
const exported = renderToStaticMarkup(React.createElement(FocusProductTable, props));
|
||||
assert.doesNotMatch(exported, /button|看缺陷|看趋势|看来源明细/);
|
||||
const chat = renderToStaticMarkup(React.createElement(FocusProductTable, { ...props, onDrilldown() {} }));
|
||||
assert.equal((chat.match(/<button/g) || []).length, 3);
|
||||
const blocked = renderToStaticMarkup(React.createElement(FocusProductTable, { ...props, onDrilldown() {}, drilldownUnavailableReason: () => '条件缺失' }));
|
||||
assert.doesNotMatch(blocked, /<button/); assert.match(blocked, /条件缺失/);
|
||||
});
|
||||
@@ -0,0 +1,395 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import ts from 'typescript';
|
||||
import React from 'react';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import { buildAnalysisNarrative } from '../src/analysisReportModel.ts';
|
||||
import { analysisReadingSummary, buildAnalysisReadingModel, parseServerReadingSummary, selectPrimaryAnalysisVisuals, conclusionMarkdown, conclusionDisplayText, selectConclusionAnalysisVisuals } from '../src/analysisReadingModel.ts';
|
||||
import { sanitizeAnalysisDisplayText } from '../src/analysisDisplayText.ts';
|
||||
import { analysisEvidenceParts, nativeReadingEvidenceTargets } from '../src/analysisEvidenceRefs.ts';
|
||||
import { buildConclusionDocument, checkedConclusionComparison } from '../src/analysisConclusionModel.ts';
|
||||
|
||||
const chart = { id: 'all-groups', type: 'column', title: '综合合格率期间比较', subtitle: '', unit: 'ratio', categories: [{ key: 'comparison', label: '8月' }, { key: 'current', label: '9月' }],
|
||||
series: [{ key: 'composite_rate', label: '合格率', values: [0.95, 0.94] }], evidenceRefs: ['Q11111111'], requiredFields: ['black_good_weight','black_total_weight','bright_good_weight','bright_total_weight'],
|
||||
scope: { year: 2026, month: 9, releaseId: 'release' }, period: { year: 2026, month: 9 }, comparisonPeriod: { year: 2026, month: 8 }, metric: 'composite_rate', originTurnId: 'turn', coverage: { totalRows: 2, returnedRows: 2, truncated: false } };
|
||||
const summary = () => ({ version: 1,
|
||||
lead: '9月合格率下降,缺角报废增加是已核对的缺陷线索,生产原因仍需核查。[Q11111111]',
|
||||
evidence: ['缺角报废增加128.45 kg。[Q22222222]', '乙组按合格率降幅排第一,下降1.90个百分点;甲组第二,下降0.66个百分点。[Q11111111]'],
|
||||
notices: ['亮片未覆盖全部月份,不能据此判定生产原因。'], evidenceRefs: ['Q11111111', 'Q22222222'] });
|
||||
const turn = (readingSummary = summary()) => ({ id: 'turn', question: '9月合格率下降原因', result: {
|
||||
answer: '只描述原始总体值95.13%。[Q11111111]\n\n第二段原始内容。\n\n第三段原始内容。\n\n第四段原因线索:缺角增加128.45 kg。[Q22222222]\n\n| 对象 | 值 |\n| --- | --- |\n| 末行 | 8 |\n\n```text\n完整代码块\n```',
|
||||
releaseId: 'release', visuals: [chart], queryEvidenceRefs: ['Q11111111', 'Q22222222'], readingSummary,
|
||||
} });
|
||||
|
||||
function component(source, name, 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 },
|
||||
}).outputText)(React, ...Object.values(bindings));
|
||||
}
|
||||
const markdownSource = readFileSync(new URL('../src/AiMarkdown.tsx', import.meta.url), 'utf8');
|
||||
const AiMarkdown = component(markdownSource, 'AiMarkdown', { sanitizeAnalysisDisplayText, analysisEvidenceParts });
|
||||
|
||||
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'
|
||||
+ '**重点分组**(缺少正式贡献值,只作为核查方向):\n\n| 分组 | 变化 |\n| --- | --- |\n| 汽车交通-国内 | 下降0.62个百分点 |\n\n'
|
||||
+ '其中**责废缺角**由15,105.38 kg增至17,513.16 kg(增减+2,407.78 kg),**料废缺角**由11,665.01 kg增至13,949.63 kg(增减+2,284.62 kg);不能认定生产根因。';
|
||||
const render = layout => renderToStaticMarkup(React.createElement(AiMarkdown, { content, layout }));
|
||||
const html = render('conclusions');
|
||||
assert.match(html, /class="analysis-conclusion-lead"[^>]*>9月综合合格率/);
|
||||
assert.match(html, /<h3[^>]*>重点分组<\/h3>/);
|
||||
assert.equal((html.match(/<table>/g) || []).length, 1);
|
||||
assert.ok(html.indexOf('analysis-conclusion-context') > html.indexOf('</table>'));
|
||||
assert.match(html, /analysis-conclusion-points/);
|
||||
assert.match(html, /<li[^>]*><strong>料废缺角<\/strong>/);
|
||||
// Layout may move the table qualifier below its table, but no numeric token
|
||||
// or uncertainty can be lost, changed, recalculated or added.
|
||||
const numbers = value => (value.match(/-?\d[\d,.]*/g) || []).sort();
|
||||
assert.deepEqual(numbers(html.replace(/<[^>]+>/g, '')), numbers(render(undefined).replace(/<[^>]+>/g, '')));
|
||||
for (const value of ['缺少正式贡献值,只作为核查方向', '不能认定生产根因', '汽车交通-国内']) assert.ok(html.includes(value));
|
||||
assert.doesNotMatch(render(undefined), /analysis-conclusion-(lead|points|context)/);
|
||||
});
|
||||
|
||||
test('conclusion layout preserves lists, code, decimal values, parenthetical caveats and numeric-only answers', () => {
|
||||
const content = '## 结论\n\n**95.13%**\n\n- 原有重点\n- 不调整顺序\n\n```text\n原始值1.52;不能拆开代码\n```\n\n' + '缺陷仍需核查(包括料废;责废)。没有依据确认生产原因。';
|
||||
const html = renderToStaticMarkup(React.createElement(AiMarkdown, { content, layout: 'conclusions' }));
|
||||
assert.match(html, /analysis-conclusion-lead[^>]*><strong>95.13%<\/strong>/);
|
||||
assert.match(html, /<li>原有重点<\/li><li>不调整顺序<\/li>/);
|
||||
assert.match(html, /<pre><code>原始值1.52;不能拆开代码<\/code><\/pre>/);
|
||||
assert.match(html, /缺陷仍需核查(包括料废;责废)。没有依据确认生产原因。/);
|
||||
const listed = renderToStaticMarkup(React.createElement(AiMarkdown, { content: '- 已核实结论\n\n亮片未完整核实。', layout: 'conclusions' }));
|
||||
assert.doesNotMatch(listed, /analysis-conclusion-lead/);
|
||||
});
|
||||
const narrativeSource = readFileSync(new URL('../src/AnalysisNarrative.tsx', import.meta.url), 'utf8');
|
||||
const readingSource = narrativeSource.slice(narrativeSource.indexOf('export function ReadingSummary('), narrativeSource.indexOf('\nfunction metricName('));
|
||||
const ReadingSummary = component(readingSource, 'ReadingSummary', { AiMarkdown });
|
||||
const hooks = { useMemo: fn => fn(), useState: initial => [initial, () => {}], useRef: initial => ({ current: initial }), useEffect: () => {} };
|
||||
const conclusionSource = readFileSync(new URL('../src/AnalysisConclusion.tsx', import.meta.url), 'utf8');
|
||||
const AnalysisConclusion = component(conclusionSource, 'AnalysisConclusion', { AiMarkdown, buildConclusionDocument });
|
||||
const common = { ...hooks, AiMarkdown, AnalysisConclusion, ReadingSummary, buildAnalysisReadingModel, buildAnalysisNarrative, conclusionMarkdown,
|
||||
AnalysisVisuals: ({ visuals = [] }) => React.createElement('div', null, visuals.map(visual => React.createElement('figure', { key: visual.id, 'data-chat-visual-id': visual.id }))), NarrativeEvidence: () => null, FocusProductTable: () => null,
|
||||
useCompactRateComparison: () => false, AnalysisProductDrilldown: () => null, resolveProductDrilldown: () => ({ reason: 'test' }) };
|
||||
const AnalysisNarrative = component(narrativeSource.slice(narrativeSource.indexOf('export function AnalysisNarrative(')), 'AnalysisNarrative', common);
|
||||
const reportSource = readFileSync(new URL('../src/AnalysisReportNarrative.tsx', import.meta.url), 'utf8');
|
||||
const AnalysisReportNarrative = component(reportSource, 'AnalysisReportNarrative', { ...common,
|
||||
reportVisuals: source => source.result?.visuals || source.visuals || [], ReportVisualFigure: ({ visual }) => React.createElement('figure', { 'data-report-visual-id': visual.id }), ReportVisualDataTable: ({ visual }) => React.createElement('table', { 'data-report-table-id': visual.id }) });
|
||||
const renderChat = data => renderToStaticMarkup(React.createElement(AnalysisNarrative, { answer: data.result.answer, visuals: data.result.visuals, question: data.question, turnId: data.id, turn: data }));
|
||||
const renderReport = data => renderToStaticMarkup(React.createElement(AnalysisReportNarrative, { turn: data, answer: data.result.answer, images: [] }));
|
||||
const visibleSummary = html => html.match(/<div class="ai-markdown[^"]*">([\s\S]*?)<\/div>/)?.[1];
|
||||
|
||||
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.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%');
|
||||
});
|
||||
|
||||
test('conclusion chapters put each authorized figure beside its cited topic, without inventing additional charts', () => {
|
||||
const data=turn({...summary(),lead:'2026年9月综合合格率95.13%,较8月的95.57%下降0.44个百分点。[Q11111111]',evidence:[
|
||||
'**产业部变化**(仅作核查方向):\n\n| 产业部 | 变化 |\n| --- | --- |\n| 甲 | 下降0.60个百分点 |\n[Q22222222]',
|
||||
'**重点规格**:甲规格报废增加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.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']);
|
||||
assert.equal(document.sections.find(x=>x.title==='产业部变化').note,'(仅作核查方向)');
|
||||
assert.ok(document.sections.every(x=>!x.markdown.includes('[Q')));
|
||||
const mismatch=buildConclusionDocument(buildAnalysisReadingModel('',[],data.question,data).reading,[{...figures[0],evidenceRefs:['Q11111111']}]);
|
||||
assert.equal(mismatch.sections.find(x=>x.title==='产业部变化').visuals.length,0);
|
||||
assert.equal(mismatch.sections.at(-1).visuals[0].id,'department');
|
||||
});
|
||||
|
||||
test('reference-style cards and chapters keep chat/report values, figures and ordering identical without source labels', () => {
|
||||
const data=turn({...summary(),lead:'2026年9月综合合格率**95.13%**,较8月的**95.57%**下降**0.44个百分点**。[Q11111111]',evidence:['### 重点规格\n\n| 规格 | 变化 |\n| --- | --- |\n| 甲 | 下降0.60个百分点 |\n[Q22222222]']});
|
||||
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.equal((html.match(/<table>/g)||[]).length,1);
|
||||
assert.doesNotMatch(html,/Q11111111|Q22222222|关键依据|数据依据|analysis-full-appendix/);
|
||||
}
|
||||
const fenced=buildConclusionDocument({...buildAnalysisReadingModel('',[],data.question,data).reading,evidence:['```text\n### 不作为章节\n```'],fullAnswer:''},[]);
|
||||
assert.equal(fenced.sections.some(x=>x.title==='不作为章节'),false);
|
||||
});
|
||||
|
||||
test('cause summary follows the server semantic selection including late defect clues and exact rate ranking', () => {
|
||||
const data = turn(), { model, reading } = buildAnalysisReadingModel(data.result.answer, data.result.visuals, data.question, data);
|
||||
const before = JSON.stringify(model);
|
||||
assert.equal(reading.lead, summary().lead);
|
||||
assert.deepEqual(reading.evidence, summary().evidence);
|
||||
assert.deepEqual(reading.notices, summary().notices);
|
||||
assert.equal(reading.fullAnswer, data.result.answer);
|
||||
assert.equal(reading.hasAppendix, true); assert.equal(reading.visualCount, 1);
|
||||
assert.equal(JSON.stringify(model), before);
|
||||
assert.match(reading.lead, /缺角/); assert.match(reading.evidence[1], /乙组.*第一.*甲组第二/);
|
||||
});
|
||||
|
||||
test('chat and report show conclusions once without evidence or an appendix', () => {
|
||||
const data = turn(); data.result.answer = summary().lead + '\n\n' + summary().evidence.join('\n\n') + '\n\n## 完整统计依据\n\n第四段原因线索、完整代码块。';
|
||||
assert.equal(visibleSummary(renderChat(data)), visibleSummary(renderReport(data)));
|
||||
for (const html of [renderChat(data), renderReport(data)]) {
|
||||
assert.match(html, /缺角报废增加128.45/);
|
||||
assert.doesNotMatch(html, /完整代码块|第四段原因线索|analysis-full-appendix|关键依据|数据依据|Q11111111|Q22222222|analysis-evidence-ref/);
|
||||
assert.equal((html.match(/9月合格率下降,缺角报废增加/g) || []).length, 1);
|
||||
assert.equal((html.match(/亮片未覆盖全部月份,不能据此判定生产原因/g) || []).length, 1);
|
||||
}
|
||||
});
|
||||
|
||||
test('historical paragraphs remain complete and visible without synthesized core summary or appendix', () => {
|
||||
const data = turn(undefined); delete data.result.readingSummary;
|
||||
const reading = analysisReadingSummary(data.result.answer, buildAnalysisNarrative(data.result.answer, [chart]));
|
||||
assert.equal(reading.hasAppendix, false); assert.equal(reading.lead, ''); assert.deepEqual(reading.evidence, []);
|
||||
assert.equal(reading.fullAnswer, data.result.answer);
|
||||
for (const html of [renderChat(data), renderReport(data)]) {
|
||||
assert.doesNotMatch(html, /analysis-reading-summary|analysis-full-appendix/);
|
||||
for (const fragment of ['第二段原始内容', '第三段原始内容', '第四段原因线索', '末行', '完整代码块']) assert.match(html, new RegExp(fragment));
|
||||
}
|
||||
});
|
||||
|
||||
test('malformed summaries and undeclared or unauthorized refs safely fall back to all original paragraphs', () => {
|
||||
const cases = [null, [], {}, { ...summary(), version: 2 }, { ...summary(), lead: '' }, { ...summary(), evidence: 'bad' },
|
||||
{ ...summary(), notices: [null] }, { ...summary(), extra: 'untrusted' }, { ...summary(), evidenceRefs: ['Q99999999'] },
|
||||
{ ...summary(), lead: '伪造依据[Q99999999]' }, { ...summary(), lead: 'illegal\u0000text' }];
|
||||
for (const invalid of cases) {
|
||||
const data = turn(invalid);
|
||||
assert.equal(parseServerReadingSummary(data), null, JSON.stringify(invalid));
|
||||
for (const html of [renderChat(data), renderReport(data)]) {
|
||||
assert.doesNotMatch(html, /analysis-reading-summary|analysis-full-appendix/);
|
||||
assert.match(html, /第四段原因线索/); assert.match(html, /完整代码块/);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('current empty allowlists or redacted nested results cannot borrow stale flattened data or charts', () => {
|
||||
const data = turn(); data.result.queryEvidenceRefs = [];
|
||||
assert.equal(parseServerReadingSummary(data), null);
|
||||
assert.equal(parseServerReadingSummary({ ...turn().result, result: { answer: '当前权限已收窄', readingSummary: null, queryEvidenceRefs: [] } }), null);
|
||||
assert.equal(parseServerReadingSummary({ ...turn().result, result: { answer: '当前权限已收窄' } }), null);
|
||||
});
|
||||
|
||||
test('older server refs remain compatible while summary-only refs get usable evidence anchors', () => {
|
||||
const data = turn(); delete data.result.queryEvidenceRefs;
|
||||
data.result.evidence = [{ evidenceRef: 'Q22222222' }];
|
||||
assert.deepEqual(parseServerReadingSummary(data), summary());
|
||||
data.result.answer = '全部原文,不含摘要独有的缺陷引用。';
|
||||
const { model } = buildAnalysisReadingModel(data.result.answer, data.result.visuals, data.question, data);
|
||||
assert.ok(model.evidence.some(entry => entry.ref === 'Q22222222'));
|
||||
assert.ok(model.evidenceLabels.Q22222222);
|
||||
delete data.result.evidence; data.result.results = [{ evidenceRef: 'Q22222222' }];
|
||||
assert.deepEqual(parseServerReadingSummary(data), summary());
|
||||
});
|
||||
|
||||
test('summary content renders as escaped text without executing HTML', () => {
|
||||
const data = turn({ ...summary(), lead: '<script>alert(1)</script> [Q11111111]' }); data.result.answer = data.result.readingSummary.lead;
|
||||
for (const html of [renderChat(data), renderReport(data)]) {
|
||||
assert.match(html, /<script>alert\(1\)<\/script>/);
|
||||
assert.doesNotMatch(html, /<script/);
|
||||
}
|
||||
});
|
||||
|
||||
const snapshotSource = readFileSync(new URL('../src/analysisSnapshot.ts', import.meta.url), 'utf8').replace(/^import .*;$/gm, '').replace(/^export /gm, '');
|
||||
const snapshot = new Function(ts.transpileModule(snapshotSource, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText
|
||||
+ '\nreturn { reportSnapshotIdentity, reportSnapshotDifferences };')();
|
||||
test('summary and evidence authorization changes invalidate prepared report snapshots', () => {
|
||||
const data = turn();
|
||||
for (const key of ['readingSummary', 'queryEvidenceRefs']) {
|
||||
const changed = structuredClone(data); changed.result[key] = key === 'readingSummary' ? { ...summary(), lead: '新的核心结论' } : ['Q11111111'];
|
||||
assert.notEqual(snapshot.reportSnapshotIdentity(data), snapshot.reportSnapshotIdentity(changed));
|
||||
assert.deepEqual(snapshot.reportSnapshotDifferences(data, changed), [key]);
|
||||
}
|
||||
assert.equal(snapshot.reportSnapshotIdentity(data), snapshot.reportSnapshotIdentity({ id: data.id, question: data.question, ...data.result }));
|
||||
});
|
||||
|
||||
const historySummary = () => ({ version: 1, lead: '已导入的缺角线索增加128.45 kg。[history-fact:F1]',
|
||||
evidence: ['原始历史范围的乙组降幅第一。[turn-abc:fact:00002]'], notices: [],
|
||||
evidenceRefs: ['history-fact:F1', 'turn-abc:fact:00002'] });
|
||||
const historyTurn = () => ({ id: 'turn', question: '综合历史生成报告', result: { answer: historySummary().lead + '\n\n' + historySummary().evidence.join('\n\n'), visuals: [],
|
||||
queryEvidenceRefs: ['history-fact:F1', 'turn-abc:fact:00002'], readingSummary: historySummary() } });
|
||||
|
||||
test('real imported history fact IDs pass only the explicit server allowlist and render shared clickable citations', () => {
|
||||
const data = historyTurn();
|
||||
assert.deepEqual(parseServerReadingSummary(data), historySummary());
|
||||
const { model, reading } = buildAnalysisReadingModel(data.result.answer, [], data.question, data);
|
||||
assert.equal(reading.hasAppendix, true);
|
||||
assert.deepEqual(model.evidence.map(entry => entry.ref), historySummary().evidenceRefs);
|
||||
const chat = renderChat(data), report = renderReport(data);
|
||||
assert.equal(visibleSummary(chat), visibleSummary(report));
|
||||
for (const html of [chat, report]) {
|
||||
assert.match(html, /缺角线索增加128.45/);
|
||||
assert.doesNotMatch(html, /history-fact:F1|turn-abc:fact:00002|analysis-evidence-ref/);
|
||||
assert.doesNotMatch(html, /Q[A-F0-9]{8}/);
|
||||
}
|
||||
});
|
||||
|
||||
test('unknown history facts, missing history allowlists, malformed Q IDs and changed history access fall back', () => {
|
||||
for (const mutate of [
|
||||
data => { data.result.readingSummary.lead = '未导入事实[history-fact:UNKNOWN]'; },
|
||||
data => { data.result.queryEvidenceRefs = ['history-fact:F1']; },
|
||||
data => { delete data.result.queryEvidenceRefs; data.result.evidence = [{ evidenceRef: 'history-fact:F1' }, { evidenceRef: 'turn-abc:fact:00002' }]; },
|
||||
data => { data.result.queryEvidenceRefs = []; },
|
||||
data => { data.result.readingSummary.evidenceRefs = ['QNOTVALID']; data.result.queryEvidenceRefs = ['QNOTVALID']; },
|
||||
]) {
|
||||
const data = historyTurn(); mutate(data);
|
||||
assert.equal(parseServerReadingSummary(data), null);
|
||||
assert.doesNotMatch(renderChat(data), /analysis-reading-summary/);
|
||||
assert.match(renderChat(data), /已导入的缺角线索增加128.45/);
|
||||
}
|
||||
});
|
||||
|
||||
test('native history summary links resolve only to unique actual fact anchors and never create placeholder history targets', () => {
|
||||
const fact = (ref, id) => ({ id, getAttribute: key => key === 'data-history-fact-id' ? ref : null });
|
||||
const first = fact('history-fact:F1', 'history-fact:history-fact:F1');
|
||||
const second = fact('turn-abc:fact:00002', 'history-fact:turn-abc:fact:00002');
|
||||
const doc = elements => ({ querySelectorAll: () => elements, getElementById: id => elements.find(element => element.id === id) });
|
||||
const refs = ['Q11111111', 'history-fact:F1', 'turn-abc:fact:00002', 'history-fact:MISSING'];
|
||||
assert.deepEqual(nativeReadingEvidenceTargets(doc([first, second]), refs), {
|
||||
Q11111111: '#platform-evidence-Q11111111',
|
||||
'history-fact:F1': '#history-fact%3Ahistory-fact%3AF1',
|
||||
'turn-abc:fact:00002': '#history-fact%3Aturn-abc%3Afact%3A00002',
|
||||
});
|
||||
assert.deepEqual(nativeReadingEvidenceTargets(doc([first, fact('history-fact:F1', 'duplicate-ref')]), ['history-fact:F1']), {});
|
||||
assert.deepEqual(nativeReadingEvidenceTargets(doc([first, fact('other-fact', first.id)]), ['history-fact:F1']), {});
|
||||
});
|
||||
|
||||
test('summary citation labels stay identical when report appendices contain additional references', () => {
|
||||
const data = turn();
|
||||
const chat = renderChat(data);
|
||||
const report = renderToStaticMarkup(React.createElement(AnalysisReportNarrative, { turn: data, answer: '更多历史正文。[Q99999999]\n\n' + data.result.answer, images: [] }));
|
||||
assert.equal(visibleSummary(chat), visibleSummary(report));
|
||||
});
|
||||
|
||||
test('ordinary opaque-looking words do not borrow inherited evidence label properties', () => {
|
||||
const html = renderToStaticMarkup(React.createElement(AiMarkdown, { content: '[constructor] [toString] [history-fact:F1]', evidenceLabels: { 'history-fact:F1': '真实依据' }, evidencePrefix: 'test-' }));
|
||||
assert.equal((html.match(/<a /g) || []).length, 1);
|
||||
assert.match(html, /\[constructor\]/); assert.match(html, /\[toString\]/);
|
||||
assert.match(html, /href="#test-history-fact:F1"/);
|
||||
});
|
||||
|
||||
const requiredTask = () => ({ version: 1, kind: 'metrics', visualPreference: 'required', visualType: 'column',
|
||||
fields: ['rate'], dimensions: [], stages: [], period: { year: 2026, month: 9 }, comparisonPeriod: { year: 2026, month: 8 }, comparisonRequired: true, filters: {} });
|
||||
const requiredTurn = () => { const data = turn(); data.plan = { task: requiredTask() }; return data; };
|
||||
const primary = data => { const { model } = buildAnalysisReadingModel(data.result.answer, data.result.visuals, data.question, data); return selectPrimaryAnalysisVisuals(model, data); };
|
||||
|
||||
test('explicit server-required charts appear in chat and reports before the appendix exactly once', () => {
|
||||
const data = requiredTurn();
|
||||
assert.deepEqual(primary(data).map(visual => visual.id), [chart.id]);
|
||||
for (const [html, attribute] of [[renderChat(data), 'data-chat-visual-id'], [renderReport(data), 'data-report-visual-id']]) {
|
||||
assert.equal((html.match(new RegExp(attribute + '="' + chart.id + '"', 'g')) || []).length, 1);
|
||||
assert.doesNotMatch(html, /附录:完整分析、数据与图表|第四段原因线索/);
|
||||
}
|
||||
});
|
||||
|
||||
test('auto shows authorized charts while none shows no charts', () => {
|
||||
const data=requiredTurn(); data.plan.task.visualPreference='auto'; assert.deepEqual(primary(data), []);
|
||||
assert.match(renderChat(data), /data-chat-visual-id/);
|
||||
data.plan.task.visualPreference='none'; assert.doesNotMatch(renderChat(data), /data-chat-visual-id|analysis-full-appendix/);
|
||||
const old=requiredTurn();delete old.result.readingSummary; assert.deepEqual(primary(old), []);
|
||||
assert.doesNotMatch(renderChat(old), /analysis-full-appendix/);
|
||||
});
|
||||
|
||||
test('short Markdown tables survive without source labels and ordinary brackets remain', () => {
|
||||
const data=turn({...summary(),evidence:['### 重点对象\n\n| 对象 | 合格率 |\n| --- | --- |\n| 甲组 | 95.13% |\n[Q22222222]']}); 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, /<table>/);assert.match(html, /<h3[^>]*>重点对象<\/h3>/);assert.match(html, /95.13%/);
|
||||
assert.doesNotMatch(html, /Q22222222|数据依据|关键依据/);
|
||||
}
|
||||
assert.equal(conclusionDisplayText('保留[constructor]及[说明],隐藏[Q11111111]。'),'保留[constructor]及[说明],隐藏。');
|
||||
});
|
||||
|
||||
test('selected charts cannot borrow stale origin, foreign scope or withdrawn evidence', () => {
|
||||
const data=requiredTurn();data.plan.task.visualPreference='auto';data.result.readingSummary.visualIds=[chart.id,'invented'];
|
||||
const select=d=>selectConclusionAnalysisVisuals(buildAnalysisReadingModel(d.result.answer,d.result.visuals,d.question,d).model,d);
|
||||
assert.deepEqual(select(data).map(v=>v.id),[chart.id]);
|
||||
for (const mutate of [d=>{d.result.visuals[0].originTurnId='old'},d=>{d.result.queryEvidenceRefs=[]},d=>{d.result.visuals[0].scope.releaseId='other'},d=>{d.plan.task.filters={department:'wrong'}}]) {
|
||||
const bad=structuredClone(data);mutate(bad);assert.deepEqual(select(bad),[]);
|
||||
}
|
||||
});
|
||||
|
||||
test('current evidence, scope, stage, metric, type, period and frozen authoritative task are required', () => {
|
||||
for (const mutate of [
|
||||
data => { data.result.visuals[0].originTurnId = 'another-turn'; },
|
||||
data => { data.result.visuals[0].evidenceRefs = ['Q99999999']; },
|
||||
data => { data.plan.task.filters = { product: 'another-product' }; },
|
||||
data => { data.plan.task.filters = { unsupported: 'must-not-ignore' }; },
|
||||
data => { data.result.visuals[0].scope.untrackedNarrowing = 'must-not-ignore'; },
|
||||
data => { data.plan.task.sort = 'rate_drop'; },
|
||||
data => { data.plan.task.stages = ['black']; },
|
||||
data => { data.plan.task.fields = ['scrapWeight']; },
|
||||
data => { data.plan.task.visualType = 'line'; },
|
||||
data => { data.plan.task.period = { year: 2026, month: 10 }; },
|
||||
data => { data.plan.task.comparisonPeriod = { year: 2026, month: 7 }; },
|
||||
data => { data.result.visuals[0].series[0].values = [null, null]; },
|
||||
data => { data.plan.task.visualPreference = 'auto'; data.agentTask = requiredTask(); },
|
||||
data => { data.plan.task.columnFilters = [{ field: 'customer', operator: 'in', values: ['A'], stages: ['black'] }]; },
|
||||
]) {
|
||||
const data = structuredClone(requiredTurn()); mutate(data);
|
||||
assert.deepEqual(primary(data), []);
|
||||
}
|
||||
for (const path of ['task', 'agentTask', 'result.agentTask']) {
|
||||
const data = structuredClone(requiredTurn()); delete data.plan;
|
||||
if (path === 'result.agentTask') data.result.agentTask = requiredTask(); else data[path] = requiredTask();
|
||||
assert.equal(primary(data).length, 1, path);
|
||||
}
|
||||
});
|
||||
|
||||
test('multiple required catalog scopes match their real target, leaving unrelated or derived scopes supplementary', () => {
|
||||
const data = requiredTurn();
|
||||
data.plan.task = { ...requiredTask(), visualType: null, fields: ['rate'], dimensions: ['product'], stages: ['black'], comparisonRequired: false,
|
||||
comparisonPeriod: null, queryPlan: [{ nodeId: 'trend', purpose: 'trend', fields: ['rate'], stages: ['black'], visualPreference: 'required', visualType: 'line', comparisonRequired: false,
|
||||
selector: { kind: 'catalog_members', dimension: 'product', names: ['A', 'B'] } }] };
|
||||
const trend = product => ({ ...structuredClone(chart), id: 'trend-' + product, type: 'line', stage: 'black', metric: 'black_rate', comparisonPeriod: undefined,
|
||||
scope: { year: 2026, month: 9, releaseId: 'release', product, stage: 'black' }, sectionKey: 'trend',
|
||||
categories: [{ key: '2026-09-01', label: '1日' }, { key: '2026-09-02', label: '2日' }] });
|
||||
data.result.visuals = [trend('unrelated'), trend('B'), trend('A')];
|
||||
assert.deepEqual(primary(data).map(visual => visual.id).sort(), ['trend-A', 'trend-B']);
|
||||
data.plan.task.queryPlan[0].selector = { kind: 'ranking_top', sourceNodeId: 'rank', count: 2 };
|
||||
assert.deepEqual(primary(data), []);
|
||||
});
|
||||
|
||||
test('explicit zero-rate ranking remains chartable and preserves server ranking order when promoted', () => {
|
||||
const data = requiredTurn(); data.plan.task = { ...requiredTask(), visualType: 'bar', comparisonRequired: false, comparisonPeriod: null, dimensions: ['product'] };
|
||||
const ranking = { ...structuredClone(chart), id: 'ranking-zero', type: 'bar', dimension: 'product', comparisonPeriod: undefined,
|
||||
categories: [{ key: 'B', label: 'B' }, { key: 'A', label: 'A' }], series: [{ key: 'composite_rate', label: '率', values: [0, 0] }] };
|
||||
data.result.visuals = [ranking];
|
||||
const selected = primary(data);
|
||||
assert.equal(selected.length, 1); assert.deepEqual(selected[0].categories.map(row => row.key), ['B', 'A']); assert.deepEqual(selected[0].series[0].values, [0, 0]);
|
||||
});
|
||||
|
||||
test('required monthly trend descriptors match the exact server numeric frame without using display labels', () => {
|
||||
const data = requiredTurn();
|
||||
data.plan.task = { ...requiredTask(), trendRequired: true, comparisonRequired: false, comparisonPeriod: null,
|
||||
period: { year: 2026, monthStart: 8, monthEnd: 9 }, visualType: null, filters: { department: '新能源汽车磁钢' },
|
||||
queryPlan: [{ nodeId: 'trend', purpose: 'trend', visualType: 'line', visualPreference: 'required', fields: ['rate'], stages: [], comparisonRequired: false, selector: { kind: 'base' } }] };
|
||||
data.result.visuals = [{ ...structuredClone(chart), id: 'real-descriptor-trend', type: 'line', comparisonPeriod: undefined,
|
||||
period: { start: '2026-08', end: '2026-09', granularity: 'month', label: '2026-08 至 2026-09' },
|
||||
scope: { year: 2026, monthStart: 8, monthEnd: 9, department: '新能源汽车磁钢', includeUnassigned: false, view: 'overall', releaseId: 'release' } }];
|
||||
assert.deepEqual(primary(data).map(visual => visual.id), ['real-descriptor-trend']);
|
||||
const before = JSON.stringify(data);
|
||||
const html = renderChat(data);
|
||||
assert.match(html, /data-chat-visual-id/); assert.doesNotMatch(html, /附录:完整分析、数据与图表/);
|
||||
assert.equal(JSON.stringify(data), before);
|
||||
for (const invalid of [
|
||||
{ start: '2026-08', end: '2026-10', granularity: 'month', label: '2026-08 至 2026-09' },
|
||||
{ start: '2026-08', end: '2027-09', granularity: 'month' },
|
||||
{ start: '2026-9', end: '2026-08', granularity: 'month' },
|
||||
{ start: '2026-08', end: '2026-09', granularity: 'day' },
|
||||
{ year: 2026, monthStart: 8, monthEnd: 9, start: '2026-07', end: '2026-09', granularity: 'month' },
|
||||
{ label: '2026-08 至 2026-09' },
|
||||
]) {
|
||||
const changed = structuredClone(data); changed.result.visuals[0].period = invalid;
|
||||
assert.deepEqual(primary(changed), []);
|
||||
}
|
||||
const narrowed = structuredClone(data); narrowed.result.visuals[0].scope.monthStart = 7;
|
||||
assert.deepEqual(primary(narrowed), []);
|
||||
});
|
||||
|
||||
test('a checked comparison table stays with its selected title while unrelated details stay out', () => {
|
||||
const data=turn({...summary(),evidence:['### 重点规格:[Q22222222]']});
|
||||
data.result.answer=summary().lead+'\n\n### 重点规格:[Q22222222]\n\n| 规格 | 率 |\n| --- | --- |\n| 甲 | 95.13% |\n\n无需展示的额外审计过程。';
|
||||
for(const html of [renderChat(data),renderReport(data)]) {assert.match(html,/<table>/);assert.match(html,/95.13%/);assert.doesNotMatch(html,/额外审计过程|Q22222222/);}
|
||||
});
|
||||
@@ -0,0 +1,355 @@
|
||||
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 {
|
||||
analysisSourceRecordListFullyRead,
|
||||
analysisSourceRecordCompletenessNotice,
|
||||
analysisSourceRecordEmptyState,
|
||||
analysisSourceRecordPage,
|
||||
analysisSourceRecordSetFullyRead,
|
||||
analysisSourceRecordSetLabel,
|
||||
analysisSourceRecordSetReadStatus,
|
||||
authorizedSourceRecordRead,
|
||||
parseAnalysisSourceRecordList,
|
||||
} from '../src/analysisRecordsModel.ts';
|
||||
import { sanitizeAnalysisDisplayText } from '../src/analysisDisplayText.ts';
|
||||
|
||||
function record(rowNumber, overrides = {}) {
|
||||
return {
|
||||
recordId: `record-${rowNumber}`, sourceRevisionId: 'revision-1', buildId: 'build-1',
|
||||
sourceFile: '黑片数据.xlsx', sheet: '缺陷记录', rowNumber, product: 'A型产品', group: '一组',
|
||||
values: { 缺陷描述: `缺陷${rowNumber}`, 数量: rowNumber }, ...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function set(id, stage, rowStart, count = 123, overrides = {}) {
|
||||
const rows = Array.from({ length: count }, (_, index) => record(rowStart + index));
|
||||
return {
|
||||
id, nodeId: `node-internal-${id}`, scopeId: `scope-internal-${id}`, label: `${stage === 'black' ? '黑片' : '亮片'}明细`, stage,
|
||||
period: { year: 2026, month: 9 }, filters: { product: ['A型产品'] }, fields: ['缺陷描述', '数量'],
|
||||
totalRows: count, loadedRows: count, complete: true, rows, ...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function fixture(overrides = {}) {
|
||||
const sets = [set('black-set', 'black', 1), set('bright-set', 'bright', 124)];
|
||||
return { schemaVersion: 1, kind: 'source_record_list', releaseId: 'release-2026-09', queryComplete: true,
|
||||
totalRows: 246, loadedRows: 246, sets, ...overrides };
|
||||
}
|
||||
|
||||
function createHookHarness() {
|
||||
const slots = [];
|
||||
let cursor = 0;
|
||||
let scheduledEffects = [];
|
||||
const sameDeps = (left, right) => left && right && left.length === right.length && left.every((item, index) => Object.is(item, right[index]));
|
||||
const slot = (index, kind, initial) => {
|
||||
if (!slots[index]) slots[index] = { kind, ...initial };
|
||||
assert.equal(slots[index].kind, kind, `hook order changed at slot ${index}`);
|
||||
return slots[index];
|
||||
};
|
||||
const hooks = {
|
||||
useState(initial) {
|
||||
const index = cursor++;
|
||||
const state = slot(index, 'state', { value: typeof initial === 'function' ? initial() : initial });
|
||||
if (!state.set) state.set = value => { state.value = typeof value === 'function' ? value(state.value) : value; };
|
||||
return [state.value, state.set];
|
||||
},
|
||||
useRef(initial) {
|
||||
const index = cursor++;
|
||||
const ref = slot(index, 'ref', { value: { current: initial } });
|
||||
return ref.value;
|
||||
},
|
||||
useMemo(factory, deps) {
|
||||
const index = cursor++;
|
||||
const memo = slot(index, 'memo', { deps: undefined, value: undefined });
|
||||
if (!sameDeps(memo.deps, deps)) { memo.value = factory(); memo.deps = deps; }
|
||||
return memo.value;
|
||||
},
|
||||
useCallback(callback, deps) { return hooks.useMemo(() => callback, deps); },
|
||||
useEffect(effect, deps) {
|
||||
const index = cursor++;
|
||||
const state = slot(index, 'effect', { deps: undefined, cleanup: null });
|
||||
if (!sameDeps(state.deps, deps)) { state.deps = deps; scheduledEffects.push({ index, effect }); }
|
||||
},
|
||||
};
|
||||
return {
|
||||
hooks,
|
||||
render(Component, props) {
|
||||
cursor = 0;
|
||||
scheduledEffects = [];
|
||||
const tree = Component(props);
|
||||
const effects = scheduledEffects;
|
||||
scheduledEffects = [];
|
||||
for (const item of effects) {
|
||||
const effectSlot = slots[item.index];
|
||||
effectSlot.cleanup?.();
|
||||
effectSlot.cleanup = item.effect() || null;
|
||||
}
|
||||
return tree;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function findElement(root, type, predicate = () => true) {
|
||||
if (Array.isArray(root)) {
|
||||
for (const child of root) { const found = findElement(child, type, predicate); if (found) return found; }
|
||||
return null;
|
||||
}
|
||||
if (!root || typeof root !== 'object') return null;
|
||||
if (root.type === type && predicate(root.props || {})) return root;
|
||||
return findElement(root.props?.children, type, predicate);
|
||||
}
|
||||
|
||||
test('strictly validates the versioned raw-record list and preserves repeated business rows', () => {
|
||||
const parsed = parseAnalysisSourceRecordList(fixture());
|
||||
assert.equal(parsed?.sets.length, 2);
|
||||
assert.equal(parsed?.loadedRows, 246);
|
||||
assert.equal(parsed?.sets[0].rows[0].values['缺陷描述'], '缺陷1');
|
||||
assert.equal(analysisSourceRecordListFullyRead(parsed), true);
|
||||
assert.equal(analysisSourceRecordSetFullyRead(parsed.sets[0]), true);
|
||||
|
||||
const duplicatedBusiness = fixture({ sets: [set('black-set', 'black', 1, 2), set('bright-set', 'bright', 1, 2)], totalRows: 4, loadedRows: 4 });
|
||||
assert.equal(parseAnalysisSourceRecordList(duplicatedBusiness)?.loadedRows, 4, 'the same source row remains present in separate sets');
|
||||
});
|
||||
|
||||
test('rejects malformed set identity, physical duplicates, bad counts, stages, fields, and false completion claims', () => {
|
||||
const good = fixture();
|
||||
const badCases = [
|
||||
{ ...good, kind: 'other' },
|
||||
{ ...good, unexpected: true },
|
||||
{ ...good, loadedRows: 245 },
|
||||
{ ...good, queryComplete: true, totalRows: 247 },
|
||||
{ ...good, sets: [good.sets[0], { ...good.sets[1], id: good.sets[0].id }] },
|
||||
{ ...good, sets: [{ ...good.sets[0], stage: 'mixed' }] , totalRows: 123, loadedRows: 123},
|
||||
{ ...good, sets: [{ ...good.sets[0], loadedRows: 122, complete: true, rows: good.sets[0].rows.slice(0, 122), totalRows: 123 }], totalRows: 123, loadedRows: 122, queryComplete: false },
|
||||
{ ...good, sets: [{ ...good.sets[0], totalRows: 2, loadedRows: 2, rows: [good.sets[0].rows[0], { ...good.sets[0].rows[1], rowNumber: 1 }] }], totalRows: 2, loadedRows: 2, queryComplete: true },
|
||||
{ ...good, sets: [{ ...good.sets[0], totalRows: 2, loadedRows: 2, rows: [good.sets[0].rows[0], { ...good.sets[0].rows[1], recordId: 'record-1' }] }], totalRows: 2, loadedRows: 2, queryComplete: true },
|
||||
{ ...good, sets: [{ ...good.sets[0], totalRows: 1, loadedRows: 1, rows: [{ ...good.sets[0].rows[0], values: { '缺陷描述': '缺陷', extra: 1 } }] }], totalRows: 1, loadedRows: 1, queryComplete: true },
|
||||
{ ...good, sets: [{ ...good.sets[0], fields: ['重复', '重复'] }] },
|
||||
];
|
||||
for (const candidate of badCases) assert.equal(parseAnalysisSourceRecordList(candidate), null);
|
||||
});
|
||||
|
||||
test('an incomplete query with no returned sets is not presented as a completed empty result', () => {
|
||||
const partial = parseAnalysisSourceRecordList({ schemaVersion: 1, kind: 'source_record_list', releaseId: 'r', queryComplete: false,
|
||||
totalRows: 0, loadedRows: 0, sets: [] });
|
||||
assert.ok(partial);
|
||||
assert.equal(analysisSourceRecordEmptyState(partial), '查询尚未完成,尚未取得可展示记录');
|
||||
assert.equal(analysisSourceRecordCompletenessNotice(partial), '本轮原始记录尚未查全,以下为已读取部分。');
|
||||
const completeEmpty = parseAnalysisSourceRecordList({ schemaVersion: 1, kind: 'source_record_list', releaseId: 'r', queryComplete: true,
|
||||
totalRows: 0, loadedRows: 0, sets: [] });
|
||||
assert.equal(analysisSourceRecordEmptyState(completeEmpty), '本次分析没有原始记录');
|
||||
assert.equal(analysisSourceRecordCompletenessNotice(completeEmpty), '');
|
||||
});
|
||||
|
||||
test('partial coverage keeps loaded rows, reports totals, and pagination reaches the last row', () => {
|
||||
const source = fixture({ queryComplete: false, totalRows: 400, loadedRows: 246,
|
||||
sets: [set('black-set', 'black', 1, 123, { totalRows: 200, complete: false }), set('bright-set', 'bright', 124, 123, { totalRows: 200, complete: false })] });
|
||||
const parsed = parseAnalysisSourceRecordList(source);
|
||||
assert.equal(analysisSourceRecordListFullyRead(parsed), false);
|
||||
assert.equal(analysisSourceRecordSetFullyRead(parsed.sets[0]), false);
|
||||
assert.match(analysisSourceRecordSetReadStatus(parsed.sets[0]), /读取未完成.*123 \/ 200/);
|
||||
assert.equal(analysisSourceRecordPage(parsed.sets[0], 3, 50).offset, 100);
|
||||
assert.equal(analysisSourceRecordPage(parsed.sets[0], 3, 50).rows.at(-1).rowNumber, 123);
|
||||
assert.equal(analysisSourceRecordPage(parsed.sets[0], 99, 100).page, 2);
|
||||
});
|
||||
|
||||
test('a same-content parent refresh keeps the selected set and page, then authorizes reads against the latest turn', async () => {
|
||||
const listA = {
|
||||
schemaVersion: 1, kind: 'source_record_list', releaseId: 'release-2026-09', queryComplete: true,
|
||||
totalRows: 895, loadedRows: 895,
|
||||
sets: [set('black-set', 'black', 1, 365), set('bright-set', 'bright', 366, 530)],
|
||||
};
|
||||
const turnA = { id: 'turn-1', status: 'COMPLETED', answer: 'answer', result: { answer: 'answer', recordList: listA } };
|
||||
const listB = JSON.parse(JSON.stringify(listA));
|
||||
const turnB = { ...turnA, result: { ...turnA.result, recordList: listB } };
|
||||
const snapshotSource = fs.readFileSync(new URL('../src/analysisSnapshot.ts', import.meta.url), 'utf8')
|
||||
.replace(/^import .*;$/gm, '').replaceAll('export function ', 'function ').replaceAll('export async function ', 'async function ');
|
||||
const reportSnapshotIdentity = new Function('api', `${ts.transpileModule(`${snapshotSource}\nreturn reportSnapshotIdentity;`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText}`)({});
|
||||
assert.equal(reportSnapshotIdentity(turnA), reportSnapshotIdentity(turnB));
|
||||
|
||||
const source = fs.readFileSync(new URL('../src/AnalysisRecordList.tsx', import.meta.url), 'utf8');
|
||||
const panelSource = source.slice(source.indexOf('function display('), source.indexOf('export function AnalysisRecordListReport'))
|
||||
.replaceAll('export function ', 'function ');
|
||||
const componentCode = ts.transpileModule(`${panelSource}\nreturn AnalysisRecordListPanel;`, {
|
||||
fileName: 'analysis-record-panel.tsx', compilerOptions: { target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.React },
|
||||
}).outputText;
|
||||
const React = {
|
||||
Fragment: Symbol('Fragment'),
|
||||
createElement: (type, props, ...children) => ({ type, props: { ...(props || {}), ...(children.length ? { children: children.length === 1 ? children[0] : children } : {}) } }),
|
||||
};
|
||||
const Stub = () => null;
|
||||
const Empty = Object.assign(function EmptyStub() {}, { PRESENTED_IMAGE_SIMPLE: 'simple' });
|
||||
const harness = createHookHarness();
|
||||
const authTurns = [];
|
||||
let denyAuthorization = false;
|
||||
let unauthorizedACalls = 0;
|
||||
let unauthorizedBCalls = 0;
|
||||
let unauthorizedCCalls = 0;
|
||||
const authorizeAnalysisSnapshot = async turn => {
|
||||
authTurns.push(turn);
|
||||
if (denyAuthorization) throw new Error('访问权限已更新');
|
||||
};
|
||||
const onUnauthorizedA = () => { unauthorizedACalls += 1; return true; };
|
||||
const onUnauthorizedB = () => { unauthorizedBCalls += 1; return true; };
|
||||
const onUnauthorizedC = () => { unauthorizedCCalls += 1; return true; };
|
||||
const Panel = new Function(
|
||||
'React', 'useCallback', 'useEffect', 'useMemo', 'useRef', 'useState', 'Alert', 'Empty', 'Pagination', 'Select', 'Spin', 'Table',
|
||||
'authorizeAnalysisSnapshot', 'reportSnapshotIdentity', 'analysisSourceRecordCompletenessNotice', 'analysisSourceRecordEmptyState',
|
||||
'analysisSourceRecordPage', 'analysisSourceRecordSetLabel', 'analysisSourceRecordSetReadStatus', 'authorizedSourceRecordRead', 'parseAnalysisSourceRecordList',
|
||||
`${componentCode}`,
|
||||
)(
|
||||
React, harness.hooks.useCallback, harness.hooks.useEffect, harness.hooks.useMemo, harness.hooks.useRef, harness.hooks.useState,
|
||||
Stub, Empty, Stub, Stub, Stub, Stub, authorizeAnalysisSnapshot, reportSnapshotIdentity,
|
||||
analysisSourceRecordCompletenessNotice, analysisSourceRecordEmptyState, analysisSourceRecordPage,
|
||||
analysisSourceRecordSetLabel, analysisSourceRecordSetReadStatus, authorizedSourceRecordRead, parseAnalysisSourceRecordList,
|
||||
);
|
||||
const propsA = { turn: turnA, value: listA, onUnauthorized: onUnauthorizedA };
|
||||
const settle = () => new Promise(resolve => setImmediate(resolve));
|
||||
|
||||
harness.render(Panel, propsA);
|
||||
await settle();
|
||||
let tree = harness.render(Panel, propsA);
|
||||
let setSelect = findElement(tree, Stub, props => props['aria-label'] === '记录集');
|
||||
assert.equal(setSelect.props.value, 'black-set');
|
||||
setSelect.props.onChange('bright-set');
|
||||
await settle();
|
||||
tree = harness.render(Panel, propsA);
|
||||
setSelect = findElement(tree, Stub, props => props['aria-label'] === '记录集');
|
||||
assert.equal(setSelect.props.value, 'bright-set');
|
||||
|
||||
const authorizedBeforeRefresh = authTurns.length;
|
||||
const propsB = { turn: turnB, value: listB, onUnauthorized: onUnauthorizedB };
|
||||
tree = harness.render(Panel, propsB);
|
||||
await settle();
|
||||
tree = harness.render(Panel, propsB);
|
||||
setSelect = findElement(tree, Stub, props => props['aria-label'] === '记录集');
|
||||
assert.equal(setSelect.props.value, 'bright-set', 'new object references with the same turn identity and snapshot must not reset selection');
|
||||
assert.equal(findElement(tree, Stub, props => props['aria-label'] === '每页显示数量').props.value, 50);
|
||||
assert.equal(authTurns.length, authorizedBeforeRefresh, 'an identical parent refresh must not force a redundant authorization read');
|
||||
|
||||
const pageControl = findElement(tree, Stub, props => typeof props.current === 'number' && typeof props.onChange === 'function');
|
||||
assert.ok(pageControl);
|
||||
pageControl.props.onChange(2);
|
||||
await settle();
|
||||
tree = harness.render(Panel, propsB);
|
||||
const table = findElement(tree, Stub, props => Array.isArray(props.dataSource));
|
||||
assert.equal(table.props.dataSource.length, 50);
|
||||
assert.equal(table.props.dataSource[0].rowNumber, 416, 'the next page still reads bright-sheet rows 51–100');
|
||||
assert.equal(authTurns.at(-1), turnB, 'the recheck uses the latest turn object');
|
||||
|
||||
const listC = JSON.parse(JSON.stringify(listB));
|
||||
const turnC = { ...turnB, result: { ...turnB.result, recordList: listC } };
|
||||
const propsC = { turn: turnC, value: listC, onUnauthorized: onUnauthorizedC };
|
||||
const authorizedBeforeSecondRefresh = authTurns.length;
|
||||
tree = harness.render(Panel, propsC);
|
||||
await settle();
|
||||
tree = harness.render(Panel, propsC);
|
||||
assert.equal(findElement(tree, Stub, props => props['aria-label'] === '记录集').props.value, 'bright-set');
|
||||
assert.equal(findElement(tree, Stub, props => props['aria-label'] === '每页显示数量').props.value, 50);
|
||||
assert.equal(findElement(tree, Stub, props => typeof props.current === 'number' && typeof props.onChange === 'function').props.current, 2,
|
||||
'a same-content refresh also keeps a non-first page');
|
||||
assert.equal(authTurns.length, authorizedBeforeSecondRefresh);
|
||||
|
||||
denyAuthorization = true;
|
||||
const pageSize = findElement(tree, Stub, props => props['aria-label'] === '每页显示数量');
|
||||
pageSize.props.onChange(100);
|
||||
await settle();
|
||||
harness.render(Panel, propsC);
|
||||
assert.equal(unauthorizedACalls, 0);
|
||||
assert.equal(unauthorizedBCalls, 0);
|
||||
assert.equal(unauthorizedCCalls, 1, 'a failed recheck uses the latest unauthorized callback');
|
||||
assert.equal(authTurns.at(-1), turnC);
|
||||
});
|
||||
|
||||
test('enforces the global row and serialized-size limits', () => {
|
||||
const tooMany = { schemaVersion: 1, kind: 'source_record_list', releaseId: 'r', queryComplete: false, totalRows: 4001, loadedRows: 4001,
|
||||
sets: [set('many', 'black', 1, 4001, { complete: false, totalRows: 4001 })] };
|
||||
assert.equal(parseAnalysisSourceRecordList(tooMany), null);
|
||||
const oversized = { schemaVersion: 1, kind: 'source_record_list', releaseId: 'r', queryComplete: true, totalRows: 1, loadedRows: 1,
|
||||
sets: [set('large', 'black', 1, 1, { rows: [record(1, { values: { 缺陷描述: 'x'.repeat(4 * 1024 * 1024), 数量: 1 } })] })] };
|
||||
assert.equal(parseAnalysisSourceRecordList(oversized), null);
|
||||
});
|
||||
|
||||
test('snapshot identity and difference checks include the raw-record snapshot', () => {
|
||||
const source = fs.readFileSync(new URL('../src/analysisSnapshot.ts', import.meta.url), 'utf8')
|
||||
.replace(/^import .*;$/gm, '').replaceAll('export function ', 'function ').replaceAll('export async function ', 'async function ');
|
||||
const exports = new Function('api', `${ts.transpileModule(`${source}\nreturn { reportSnapshotIdentity, reportSnapshotDifferences };`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText}`)({});
|
||||
const before = { id: 'turn-1', answer: 'same', recordList: fixture() };
|
||||
const changedRows = before.recordList.sets[0].rows.map((row, index) => index === 0 ? { ...row, values: { ...row.values, 缺陷描述: 'changed' } } : row);
|
||||
const after = { ...before, recordList: fixture({ sets: [{ ...before.recordList.sets[0], rows: changedRows }, before.recordList.sets[1]] }) };
|
||||
assert.notEqual(exports.reportSnapshotIdentity(before), exports.reportSnapshotIdentity(after));
|
||||
assert.ok(exports.reportSnapshotDifferences(before, after).includes('recordList'));
|
||||
});
|
||||
|
||||
test('the report appendix includes all rows and set coverage, escaping source and cell values', () => {
|
||||
const rawSourceText = '数学 A!! <script>&';
|
||||
const recordList = fixture({ totalRows: 246, loadedRows: 246, sets: [
|
||||
set('black-set', 'black', 1, 123, {
|
||||
label: '数学A',
|
||||
fields: [rawSourceText, '数量'],
|
||||
rows: Array.from({ length: 123 }, (_, i) => record(i + 1, {
|
||||
sourceFile: i === 0 ? rawSourceText : '黑片数据.xlsx',
|
||||
sheet: i === 0 ? rawSourceText : '缺陷记录',
|
||||
product: i === 0 ? rawSourceText : 'A型产品',
|
||||
group: i === 0 ? rawSourceText : '一组',
|
||||
values: { [rawSourceText]: i === 0 ? rawSourceText : `黑片缺陷${i + 1}`, 数量: i + 1 },
|
||||
})),
|
||||
}),
|
||||
set('bright-set', 'bright', 124, 123, { label: 'A', rows: Array.from({ length: 123 }, (_, i) => record(i + 124, { values: { 缺陷描述: `亮片缺陷${i + 1}`, 数量: i + 1 } })) }),
|
||||
] });
|
||||
const parsed = parseAnalysisSourceRecordList(recordList);
|
||||
assert.deepEqual(parsed.sets.map(analysisSourceRecordSetLabel), ['数学A · 黑片 · 2026年9月', 'A · 亮片 · 2026年9月'],
|
||||
'the same label helper used by the record-set dropdown keeps distinct catalog names distinct');
|
||||
const componentSource = fs.readFileSync(new URL('../src/AnalysisRecordList.tsx', import.meta.url), 'utf8');
|
||||
const helpers = componentSource.slice(componentSource.indexOf('function display('), componentSource.indexOf('export function AnalysisRecordListPanel'))
|
||||
+ componentSource.slice(componentSource.indexOf('export function AnalysisRecordListReport'), componentSource.indexOf('/** Add the same all-row appendix'));
|
||||
const Component = new Function('React', 'analysisSourceRecordSetLabel', 'analysisSourceRecordSetReadStatus', 'parseAnalysisSourceRecordList',
|
||||
ts.transpileModule(`${helpers.replaceAll('export function ', 'function ')}\nreturn AnalysisRecordListReport;`, { fileName: 'analysis-record-report.tsx', compilerOptions: { target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.React } }).outputText
|
||||
)(React, analysisSourceRecordSetLabel, analysisSourceRecordSetReadStatus, parseAnalysisSourceRecordList);
|
||||
const html = renderToStaticMarkup(React.createElement(Component, { value: recordList }));
|
||||
assert.equal((html.match(/<tr/g) || []).length, 248);
|
||||
assert.match(html, /数学A · 黑片 · 2026年9月/);
|
||||
assert.match(html, /A · 亮片 · 2026年9月/);
|
||||
assert.match(html, /<th>序号<\/th>/);
|
||||
assert.match(html, /已读取全部 123 \/ 123 条/);
|
||||
assert.match(html, /黑片缺陷123/);
|
||||
assert.match(html, /亮片缺陷123/);
|
||||
assert.match(html, /<td>123<\/td><td>黑片数据\.xlsx<\/td><td>缺陷记录<\/td><td>246<\/td>/,
|
||||
'the last row of each set keeps its local sequence number and physical source row number');
|
||||
assert.match(html, /<th>数学 A!! <script>&<\/th>/);
|
||||
assert.equal((html.match(/<td>数学 A!! <script>&<\/td>/g) || []).length, 5,
|
||||
'source file, sheet, product, group, and raw cell keep exact text while HTML is escaped');
|
||||
assert.doesNotMatch(html, /<script\b|node-internal|scope-internal|record-1/);
|
||||
assert.doesNotMatch(html, /<script\b/);
|
||||
assert.doesNotMatch(html, /分页|每页显示|下一页/);
|
||||
});
|
||||
|
||||
test('chat cell rendering preserves source text while React escapes markup', () => {
|
||||
const source = fs.readFileSync(new URL('../src/AnalysisRecordList.tsx', import.meta.url), 'utf8');
|
||||
const displaySource = source.slice(source.indexOf('function display('), source.indexOf('\nfunction normalizedHeader('));
|
||||
const display = new Function('React', 'sanitizeAnalysisDisplayText',
|
||||
ts.transpileModule(`${displaySource}\nreturn display;`, { fileName: 'analysis-record-cell.tsx', compilerOptions: { target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.React } }).outputText
|
||||
)(React, sanitizeAnalysisDisplayText);
|
||||
const html = renderToStaticMarkup(display('数学 A!! <script>&'));
|
||||
assert.match(html, /数学 A!! <script>&/);
|
||||
assert.doesNotMatch(html, /<script\b/);
|
||||
});
|
||||
|
||||
test('the raw-record table keeps horizontal scrolling and caps the viewport at 420px', () => {
|
||||
const source = fs.readFileSync(new URL('../src/AnalysisRecordList.tsx', import.meta.url), 'utf8');
|
||||
assert.match(source, /indexOffset=\{page\.offset\} scroll=\{\{ x: 'max-content', y: 420 \}\}/);
|
||||
});
|
||||
|
||||
test('native HTML appendix puts a narrow serial column before the 140px source-file column', () => {
|
||||
const source = fs.readFileSync(new URL('../src/AnalysisRecordList.tsx', import.meta.url), 'utf8');
|
||||
const reportSource = fs.readFileSync(new URL('../src/AnalysisReportExport.tsx', import.meta.url), 'utf8');
|
||||
assert.match(source, /const headers = \['序号', '来源文件', '工作表', '原始行号'/);
|
||||
assert.match(source, /const cells: Array<string \| number> = \[index \+ 1, row\.sourceFile, row\.sheet, row\.rowNumber/);
|
||||
assert.match(source, /th:first-child,\.q-source-record-list td:first-child\{width:48px;min-width:48px;white-space:nowrap/);
|
||||
assert.match(reportSource, /\.q-report \.q-source-record-list th:first-child,\.q-report \.q-source-record-list td:first-child\{width:48px;min-width:48px;white-space:nowrap/);
|
||||
assert.match(source, /th:nth-child\(2\),\.q-source-record-list td:nth-child\(2\)\{width:140px\}/);
|
||||
});
|
||||
@@ -101,3 +101,96 @@ test('scoped comparisons cannot enter a global overview or stage chapter',()=>{
|
||||
const matched=buildAnalysisNarrative(`总体变化。[Q1234ABCD]\n\n### 重点产品\n${product} 的变化。`,[visual(),local,stage]);
|
||||
assert.equal(matched.sections.find(s=>s.kind==='product').visuals.length,2);
|
||||
});
|
||||
|
||||
const productTable = ({ product = '16.33X15.5X3.75+T', ref = 'Q9594C354', stage = '', delta = '+758.76', change = '下降1.95个百分点', weight = '1,286.11', rate = '97.11%→95.16%', input = '黑片投入17,361.74→26,276.07 kg;亮片投入19,009.25→26,288.80 kg', order = '报废增量' } = {}) => {
|
||||
const name = stage ? `${stage}合格率` : '综合率';
|
||||
return `### ${stage}${order === '合格率降幅' ? '产品率变化线索' : '重点产品'}(按${order},本次返回前5)\n\n| 规格 | 本期报废 / 增量(kg) | ${name}:比较期→本期 / 变化 | 阶段投入:比较期→本期(kg) |\n| --- | --- | --- | --- |\n| ${product.replaceAll('|', '\\|')} | ${weight} / ${delta} | ${rate};${change} | ${input} |\n\n[${ref}] 查询共有3566个对象,保留分阶段投入。`;
|
||||
};
|
||||
const productFact = ({ product = '16.33X15.5X3.75+T', ref = 'Q9594C354', delta = '+758.76', change = '下降1.95个百分点', stage = '', input = '黑片投入17,361.74→26,276.07 kg;亮片投入19,009.25→26,288.80 kg' } = {}) =>
|
||||
`- ${product}:${stage}报废527.35→1,286.11 kg,增量${delta} kg;${stage ? `${stage}合格率` : '综合率'}97.11%→95.16%,${change};${input}。[${ref}]`;
|
||||
|
||||
test('selected product facts become a cited comparison immediately after the overview without recalculation', () => {
|
||||
const first = { product: 'A', ref: 'Q11111111', delta: '+758.76' };
|
||||
const second = { product: 'B', ref: 'Q22222222', delta: '+757.56', change: '下降0.68个百分点' };
|
||||
const source = `整体下降。[Q1234ABCD]\n\n${productTable(first)}\n\n${productTable(second)}\n\n### 重点关注\n\n${productFact(second)}\n${productFact(first)}\n\n范围:当前授权范围,默认不含未分类。`;
|
||||
const model = buildAnalysisNarrative(source, [visual()]);
|
||||
assert.equal(model.sections[0].kind, 'overview');
|
||||
const focused = model.sections[1];
|
||||
assert.equal(focused.id, 'focus-product-summary');
|
||||
assert.deepEqual(focused.focusProducts.map(row => [row.product, row.scrapDelta, row.rateChange, row.basis]), [
|
||||
['B', '+757.56', '下降0.68个百分点', '按报废增量排序'],
|
||||
['A', '+758.76', '下降1.95个百分点', '按报废增量排序'],
|
||||
]);
|
||||
assert.equal(focused.focusProducts[0].detail, productFact(second).slice(2));
|
||||
assert.match(focused.focusProducts[0].detail, /黑片投入17,361.74→26,276.07 kg/);
|
||||
assert.equal(model.sections.filter(section => section.narrative.includes('B:')).length, 0);
|
||||
assert.ok(model.sections.some(section => section.narrative.includes('默认不含未分类')));
|
||||
assert.equal(model.sections.flatMap(section => section.tables).length, 2);
|
||||
assert.equal(model.sections.flatMap(section => section.visuals).length, 1);
|
||||
assert.equal(model.evidenceLabels.Q22222222, '依据 3');
|
||||
});
|
||||
|
||||
test('unrecognized old product reports and uncited focus prose remain intact', () => {
|
||||
for (const focus of ['- A:这是旧格式的分析。', '- 另一规格:增量+758.76 kg,下降1.95个百分点。[Q9594C354]', '- 16.33X15.5X3.75+T:增量+758.76 kg,下降1.95个百分点。[Q00000000]']) {
|
||||
const model = buildAnalysisNarrative(`${productTable()}\n\n### 重点关注\n\n${focus}`, []);
|
||||
assert.ok(!model.sections.some(section => section.focusProducts));
|
||||
assert.equal(model.sections.at(-1).narrative, focus);
|
||||
}
|
||||
});
|
||||
|
||||
test('missing values are retained as unavailable and never converted to zero', () => {
|
||||
const data = { delta: '—', weight: '—', rate: '—→—', change: '不可比', input: '黑片投入—→— kg;亮片投入—→— kg' };
|
||||
const model = buildAnalysisNarrative(`总体比较。\n\n${productTable(data)}\n\n### 重点关注\n\n${productFact(data)}`, []);
|
||||
const row = model.sections.find(section => section.focusProducts).focusProducts[0];
|
||||
assert.equal(row.scrapDelta, '—'); assert.equal(row.rateChange, '不可比');
|
||||
assert.match(row.detail, /黑片投入—→— kg/);
|
||||
});
|
||||
|
||||
test('stage and ordering context follow the exact cited row, including rate-only leads', () => {
|
||||
const black = { product: 'A', ref: 'Q11111111', stage: '黑片', delta: '+20.00', change: '下降5.00个百分点', order: '合格率降幅' };
|
||||
const bright = { product: 'A', ref: 'Q22222222', stage: '亮片', delta: '+40.00', change: '下降2.00个百分点', order: '当前报废重量' };
|
||||
const model = buildAnalysisNarrative(`概况。\n\n${productTable(black)}\n\n${productTable(bright)}\n\n### 重点关注\n\n${productFact(black)}\n${productFact(bright)}`, []);
|
||||
const rows = model.sections.find(section => section.focusProducts).focusProducts;
|
||||
assert.deepEqual(rows.map(row => row.rateLabel), ['黑片合格率', '亮片合格率']);
|
||||
assert.deepEqual(rows.map(row => row.basis), ['黑片 · 按合格率降幅排序,仅作率变化线索', '亮片 · 按当前报废重量排序']);
|
||||
assert.deepEqual(rows.map(row => row.evidenceRefs[0]), ['Q11111111', 'Q22222222']);
|
||||
});
|
||||
|
||||
test('ambiguous references, changed numbers, and unknown table fields fall back to full original prose', () => {
|
||||
const fact = productFact();
|
||||
const cases = [
|
||||
`${productTable()}\n\n${productTable()}`,
|
||||
productTable({ delta: '+999.99' }),
|
||||
productTable().replace('阶段投入:比较期→本期(kg)', '其他数据'),
|
||||
];
|
||||
for (const tables of cases) {
|
||||
const model = buildAnalysisNarrative(`${tables}\n\n### 重点关注\n\n${fact}`, []);
|
||||
assert.ok(!model.sections.some(section => section.focusProducts));
|
||||
assert.equal(model.sections.at(-1).narrative, fact);
|
||||
}
|
||||
});
|
||||
|
||||
test('mixed focus items and fenced examples are retained while recognized products move', () => {
|
||||
const other = '- 核对责废分类是否完整。[Q1234ABCD]';
|
||||
const code = `\`\`\`text\n${productFact()}\n\`\`\``;
|
||||
const model = buildAnalysisNarrative(`${productTable()}\n\n### 重点关注\n\n${productFact()}\n${other}\n\n${code}`, []);
|
||||
assert.equal(model.sections.find(section => section.focusProducts).focusProducts.length, 1);
|
||||
assert.equal(model.sections.at(-1).kind, 'action');
|
||||
assert.ok(model.sections.at(-1).narrative.includes(other));
|
||||
assert.ok(model.sections.at(-1).narrative.includes(code));
|
||||
});
|
||||
|
||||
test('long specifications and escaped Markdown delimiters remain literal product data', () => {
|
||||
const product = 'R127.985X57.516X15.786X75.485X32.232°X5.5|<img src=x onerror=alert(1)>';
|
||||
const model = buildAnalysisNarrative(`${productTable({ product })}\n\n### 重点关注\n\n${productFact({ product })}`, []);
|
||||
const row = model.sections.find(section => section.focusProducts).focusProducts[0];
|
||||
assert.equal(row.product, product); assert.equal(row.detail, productFact({ product }).slice(2));
|
||||
});
|
||||
|
||||
test('more than five selected products remain available in original order for expanded details', () => {
|
||||
const data = Array.from({ length: 6 }, (_, index) => ({ product: `规格${index + 1}`, ref: `Q1111111${index}` }));
|
||||
const model = buildAnalysisNarrative(`总体变化。\n\n${data.map(item => productTable(item)).join('\n\n')}\n\n### 重点关注\n\n${data.map(item => productFact(item)).join('\n')}`, []);
|
||||
const rows = model.sections.find(section => section.focusProducts).focusProducts;
|
||||
assert.equal(rows.length, 6); assert.deepEqual(rows.map(row => row.product), data.map(item => item.product));
|
||||
assert.equal(model.evidence.length, 6);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { downloadAuthorizedReport, longReportImageSize, reportDownloadName } from '../src/analysisReportFiles.ts';
|
||||
import { resolveAnalysisReportTitle, stripDuplicateFirstMarkdownH1 } from '../src/analysisReportTitle.ts';
|
||||
import { selectAnalysisReport } from '../src/analysisReportSummary.ts';
|
||||
|
||||
const exportSource = readFileSync(new URL('../src/AnalysisReportExport.tsx', import.meta.url), 'utf8');
|
||||
|
||||
test('report title prefers generated result and turn titles, then a legacy report H1', () => {
|
||||
assert.equal(resolveAnalysisReportTitle('AI生成标题', 'turn标题', '# Markdown标题', '2026年9月', ''), 'AI生成标题');
|
||||
assert.equal(resolveAnalysisReportTitle('', 'turn标题', '# Markdown标题', '2026年9月', ''), 'turn标题');
|
||||
assert.equal(resolveAnalysisReportTitle('', '', '# 旧报告 AI 标题\n\n正文', '2026年9月', ''), '旧报告 AI 标题');
|
||||
});
|
||||
|
||||
test('fallback title comes from the period and scope, never the user question', () => {
|
||||
const question = '综合以上生成报告';
|
||||
const title = resolveAnalysisReportTitle('', '', '', '2026年9月', '2026年9月 · 产品:新能源磁钢 · 黑片与亮片');
|
||||
assert.equal(title, '2026年9月 · 新能源磁钢质量分析报告');
|
||||
assert.notEqual(title, question);
|
||||
});
|
||||
|
||||
test('a matching Markdown H1 is removed from the body without dropping detailed report content', () => {
|
||||
const markdown = '# AI生成标题\n\n## 执行摘要\n综合合格率下降。\n\n## 重点产品\n完整投入、报废重量与率变化明细。';
|
||||
const body = stripDuplicateFirstMarkdownH1(markdown, 'AI生成标题');
|
||||
assert.equal(body.includes('# AI生成标题'), false);
|
||||
assert.match(body, /^## 执行摘要/);
|
||||
assert.match(body, /## 重点产品/);
|
||||
assert.match(body, /完整投入、报废重量与率变化明细/);
|
||||
});
|
||||
|
||||
test('the export has one detailed-report path and no summary mode selector', () => {
|
||||
assert.doesNotMatch(exportSource, /Segmented|setMode|简版摘要/);
|
||||
assert.match(exportSource, /<AnalysisReportNarrative[^>]*mode="full"/);
|
||||
assert.equal((exportSource.match(/下载长图/g) || []).length, 3); // one action with its button/ready-state wording
|
||||
});
|
||||
|
||||
test('download names stay concise and use a single report suffix', () => {
|
||||
assert.equal(reportDownloadName('2026-08 → 2026-09'), '质量分析_2026-08至09_报告');
|
||||
assert.equal(reportDownloadName(''), '质量分析_报告');
|
||||
});
|
||||
|
||||
test('the complete long report retains its dimensions beyond the old canvas auto-scale limit', () => {
|
||||
assert.deepEqual(longReportImageSize(900, 11912), { width: 900, height: 11912, pixelRatio: 1.5 });
|
||||
assert.equal(longReportImageSize(900, 11912).height * 1.5, 17868);
|
||||
});
|
||||
|
||||
test('very long reports fit one bounded canvas by scaling the entire image without dropping content', () => {
|
||||
for (const [width, height] of [[900, 50000], [6000, 40000]]) {
|
||||
const result = longReportImageSize(width, height);
|
||||
assert.equal(result.width, width); assert.equal(result.height, height);
|
||||
assert.ok(result.pixelRatio > 0);
|
||||
assert.ok(width * result.pixelRatio <= 30000);
|
||||
assert.ok(height * result.pixelRatio <= 30000);
|
||||
assert.ok(width * height * result.pixelRatio ** 2 <= 48000001);
|
||||
}
|
||||
assert.deepEqual(longReportImageSize(900, 830.2), { width: 900, height: 831, pixelRatio: 1.5 });
|
||||
assert.throws(() => longReportImageSize(900, NaN), /尺寸无效/);
|
||||
});
|
||||
|
||||
const section = (id, kind, extra = {}) => ({ id, kind, title: id, markdown: id, narrative: id, tables: [], visuals: [], evidenceRefs: [], ...extra });
|
||||
const model = sections => ({ sections, title: '质量报告', period: '2026年9月 对比8月', scope: '电机', evidenceLabels: { Q11111111: '依据1', Q22222222: '依据2' }, evidence: [{ ref: 'Q11111111', label: '依据1', context: '正式指标' }, { ref: 'Q22222222', label: '依据2', context: '细分数据' }] });
|
||||
|
||||
test('summary retains exact overview, stages, selected product inputs, chart, action and evidence', () => {
|
||||
const detail = '黑片投入17,361.74→26,276.07 kg;亮片投入19,009.25→26,288.80 kg';
|
||||
const source = model([
|
||||
section('overall', 'overview', { evidenceRefs: ['Q11111111'], tables: ['| 正式值 | 95.13% |'] }),
|
||||
section('focus', 'product', { focusProducts: [{ product: 'A', scrapDelta: '+758.76', rateChange: '下降1.95个百分点', basis: '按报废增量排序', detail, evidenceRefs: ['Q11111111'] }] }),
|
||||
section('stages', 'stage', { visuals: [{ id: 'stage-chart', evidenceRefs: ['Q11111111'] }] }),
|
||||
section('product-detail', 'product', { evidenceRefs: ['Q22222222'], tables: ['full table'], visuals: [{ id: 'focus-chart', evidenceRefs: ['Q11111111'] }, { id: 'unrelated-chart', evidenceRefs: ['Q22222222'] }] }),
|
||||
section('defect-detail', 'defect', { evidenceRefs: ['Q22222222'] }),
|
||||
section('scope-note', 'other', { narrative: '范围不含未分类;来源字段不代表正式总量。' }),
|
||||
section('actions', 'action'),
|
||||
]);
|
||||
const summary = selectAnalysisReport(source, 'summary');
|
||||
assert.deepEqual(summary.sections.map(item => item.id), ['overall','focus','stages','scope-note','actions']);
|
||||
assert.equal(summary.sections[1].focusProducts[0].detail, detail);
|
||||
assert.deepEqual(summary.sections[1].visuals.map(item => item.id), ['focus-chart']);
|
||||
assert.deepEqual(summary.sections[0].tables, ['| 正式值 | 95.13% |']);
|
||||
assert.equal(summary.sections[2].visuals[0].id, 'stage-chart');
|
||||
assert.equal(summary.scope, source.scope);
|
||||
assert.deepEqual(summary.evidence.map(item => item.ref), ['Q11111111']);
|
||||
assert.equal(source.sections.length, 7);
|
||||
assert.strictEqual(selectAnalysisReport(source, 'full'), source);
|
||||
});
|
||||
|
||||
test('unrecognized historic answers keep their complete content and unavailable values', () => {
|
||||
const source = model([section('旧格式', 'other', { narrative: '不可比;正式值—', tables: ['全部原始表格'] }), section('特别说明', 'other')]);
|
||||
const summary = selectAnalysisReport(source, 'summary');
|
||||
assert.deepEqual(summary.sections, source.sections);
|
||||
const narrow = model([section('具体缺陷', 'defect', { evidenceRefs: ['Q22222222'] })]);
|
||||
assert.deepEqual(selectAnalysisReport(narrow, 'summary').sections, narrow.sections);
|
||||
});
|
||||
|
||||
function pendingAuthorization() {
|
||||
let resolve, reject;
|
||||
const promise = new Promise((yes, no) => { resolve = yes; reject = no; });
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
|
||||
for (const kind of ['HTML', '长图']) {
|
||||
test(`${kind} download rechecks authorization before using the prepared file`, async () => {
|
||||
const auth = pendingAuthorization();
|
||||
const events = [];
|
||||
const action = downloadAuthorizedReport({
|
||||
authorize: () => { events.push('authorize'); return auth.promise; },
|
||||
isCurrent: () => true,
|
||||
download: () => events.push('download'),
|
||||
onDenied: () => events.push('denied'),
|
||||
});
|
||||
assert.deepEqual(events, ['authorize']);
|
||||
auth.resolve();
|
||||
await action;
|
||||
assert.deepEqual(events, ['authorize', 'download']);
|
||||
});
|
||||
|
||||
test(`${kind} permission revoked after preparation clears files and reports denial`, async () => {
|
||||
const auth = pendingAuthorization();
|
||||
const files = new Set(['html-url', 'image-url']);
|
||||
const revoked = [];
|
||||
let shownError = '';
|
||||
let downloaded = false;
|
||||
const action = downloadAuthorizedReport({
|
||||
authorize: () => auth.promise,
|
||||
isCurrent: () => true,
|
||||
download: () => { downloaded = true; },
|
||||
onDenied: error => { for (const url of files) revoked.push(url); files.clear(); shownError = error.message; },
|
||||
});
|
||||
auth.reject(new Error('权限已撤销'));
|
||||
await action;
|
||||
assert.equal(downloaded, false);
|
||||
assert.deepEqual(revoked, ['html-url', 'image-url']);
|
||||
assert.equal(files.size, 0);
|
||||
assert.equal(shownError, '权限已撤销');
|
||||
});
|
||||
|
||||
for (const change of ['dialog closed', 'snapshot changed']) {
|
||||
test(`${kind} is not downloaded or modified when ${change} during authorization`, async () => {
|
||||
for (const outcome of ['allow', 'deny']) {
|
||||
const auth = pendingAuthorization();
|
||||
let current = true;
|
||||
const events = [];
|
||||
const action = downloadAuthorizedReport({
|
||||
authorize: () => auth.promise,
|
||||
isCurrent: () => current,
|
||||
download: () => events.push('download'),
|
||||
onDenied: () => events.push('denied'),
|
||||
});
|
||||
current = false;
|
||||
if (outcome === 'allow') auth.resolve(); else auth.reject(new Error('denied'));
|
||||
await action;
|
||||
assert.deepEqual(events, []);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
test('prepared export buttons route through the authorization gate', () => {
|
||||
assert.match(exportSource, /downloadPrepared\(preparedHtml, 'html'\)/);
|
||||
assert.match(exportSource, /downloadPrepared\(prepared, 'image'\)/);
|
||||
assert.doesNotMatch(exportSource, /href=\{prepared(?:Html)?\.url\}/);
|
||||
});
|
||||
@@ -0,0 +1,246 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { inflateSync } from 'node:zlib';
|
||||
import { encodeRgbaStripsToPng, reportLongImagePixelLimit } from '../src/analysisReportPng.ts';
|
||||
import { requiresFullResolutionStripCapture } from '../src/analysisReportFiles.ts';
|
||||
import {
|
||||
assertReportFooterAfterLastRecord,
|
||||
assertReportMeasurementAtOneX,
|
||||
createReportSvgStripMarkupFactory,
|
||||
findReportTailMarkerTop,
|
||||
isDocumentNodeFollowing,
|
||||
normalizeReportRectOffset,
|
||||
requiresMeasuredReportSnapshot,
|
||||
reportSvgDataUrl,
|
||||
resolveReportCanvasPixelRatio,
|
||||
resolveReportSnapshotHeight,
|
||||
} from '../src/analysisReportCapture.ts';
|
||||
|
||||
const signature = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
|
||||
const captureSource = readFileSync(new URL('../src/analysisReportCapture.ts', import.meta.url), 'utf8');
|
||||
|
||||
function crc32(bytes) {
|
||||
let crc = 0xffffffff;
|
||||
for (const byte of bytes) {
|
||||
crc ^= byte;
|
||||
for (let bit = 0; bit < 8; bit += 1) crc = crc & 1 ? 0xedb88320 ^ (crc >>> 1) : crc >>> 1;
|
||||
}
|
||||
return (crc ^ 0xffffffff) >>> 0;
|
||||
}
|
||||
|
||||
function parsePng(bytes) {
|
||||
assert.deepEqual(bytes.subarray(0, 8), signature);
|
||||
const chunks = [];
|
||||
let offset = 8;
|
||||
while (offset < bytes.length) {
|
||||
const length = bytes.readUInt32BE(offset);
|
||||
const type = bytes.toString('ascii', offset + 4, offset + 8);
|
||||
const data = bytes.subarray(offset + 8, offset + 8 + length);
|
||||
const expectedCrc = bytes.readUInt32BE(offset + 8 + length);
|
||||
assert.equal(crc32(bytes.subarray(offset + 4, offset + 8 + length)), expectedCrc, `${type} CRC`);
|
||||
chunks.push({ type, data });
|
||||
offset += length + 12;
|
||||
if (type === 'IEND') break;
|
||||
}
|
||||
assert.equal(offset, bytes.length, 'no bytes after IEND');
|
||||
return chunks;
|
||||
}
|
||||
|
||||
function makePixels(width, height) {
|
||||
const pixels = new Uint8Array(width * height * 4);
|
||||
for (let y = 0; y < height; y += 1) {
|
||||
for (let x = 0; x < width; x += 1) {
|
||||
const offset = (y * width + x) * 4;
|
||||
pixels[offset] = (x * 31 + y * 13) & 0xff;
|
||||
pixels[offset + 1] = (x * 7 + y * 47) & 0xff;
|
||||
pixels[offset + 2] = (x * 73 + y * 3) & 0xff;
|
||||
pixels[offset + 3] = (x + y * 19) & 0xff;
|
||||
}
|
||||
}
|
||||
return pixels;
|
||||
}
|
||||
|
||||
async function* splitPixels(pixels, width, height, stripHeight) {
|
||||
for (let y = 0; y < height; y += stripHeight) {
|
||||
const rows = Math.min(stripHeight, height - y);
|
||||
const start = y * width * 4;
|
||||
yield { y, height: rows, data: pixels.subarray(start, start + rows * width * 4) };
|
||||
}
|
||||
}
|
||||
|
||||
test('full-resolution strip capture is limited to reports the legacy canvas would shrink', () => {
|
||||
assert.equal(requiresFullResolutionStripCapture(900, 11912), false);
|
||||
assert.equal(requiresFullResolutionStripCapture(900, 91800), true);
|
||||
assert.equal(reportLongImagePixelLimit, 100_000_000);
|
||||
});
|
||||
|
||||
test('raw-record reports always use measured snapshot layout while unrelated short reports keep the fast path', () => {
|
||||
assert.equal(requiresMeasuredReportSnapshot(true, false), true, 'short raw appendices also reflow after cloning');
|
||||
assert.equal(requiresMeasuredReportSnapshot(true, true), true);
|
||||
assert.equal(requiresMeasuredReportSnapshot(false, true), true, 'overlong reports still use bounded strips');
|
||||
assert.equal(requiresMeasuredReportSnapshot(false, false), false, 'unrelated short reports retain the old canvas path');
|
||||
});
|
||||
|
||||
test('raw-record output matches the 1x tail probe while other reports retain their normal canvas scale', () => {
|
||||
assert.equal(resolveReportCanvasPixelRatio(true, 1.2567), 1);
|
||||
assert.equal(resolveReportCanvasPixelRatio(true, 1), 1);
|
||||
assert.equal(resolveReportCanvasPixelRatio(true, 0.8), 0.8, 'long raw reports continue through the 1x strip path');
|
||||
assert.equal(resolveReportCanvasPixelRatio(false, 1.2567), 1.2567);
|
||||
assert.match(captureSource, /resolveReportCanvasPixelRatio\(hasSourceRecordList, measuredSize\.pixelRatio\)/);
|
||||
});
|
||||
|
||||
test('SVG strip viewports crop one full-height foreignObject without changing report content', () => {
|
||||
const fullReport = '<svg xmlns="http://www.w3.org/2000/svg" width="900" height="92000" viewBox="0 0 900 92000">'
|
||||
+ '<foreignObject width="100%" height="100%" x="0" y="0"><div xmlns="http://www.w3.org/1999/xhtml" style="height:92000px">'
|
||||
+ '<p>首行内容</p><p>末行内容</p></div></foreignObject></svg>';
|
||||
const source = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(fullReport)}`;
|
||||
const viewportFor = createReportSvgStripMarkupFactory(source, 900, 92000);
|
||||
|
||||
const first = viewportFor(0, 2048);
|
||||
assert.match(first, /<svg[^>]*width="900" height="2048" viewBox="0 0 900 2048"/);
|
||||
assert.match(first, /<foreignObject width="900" height="92000"/);
|
||||
assert.match(first, /首行内容/);
|
||||
assert.match(first, /末行内容/);
|
||||
|
||||
const last = viewportFor(90112, 1888);
|
||||
assert.match(last, /<svg[^>]*width="900" height="1888" viewBox="0 90112 900 1888"/);
|
||||
assert.match(last, /<foreignObject width="900" height="92000"/);
|
||||
assert.throws(() => viewportFor(91000, 2048), /条带范围无效/);
|
||||
});
|
||||
|
||||
test('SVG strip rasterization uses html-to-image compatible encoded data URLs, never Blob URLs', () => {
|
||||
const source = '<svg xmlns="http://www.w3.org/2000/svg"><foreignObject/></svg>';
|
||||
const dataUrl = reportSvgDataUrl(source);
|
||||
assert.equal(dataUrl, `data:image/svg+xml;charset=utf-8,${encodeURIComponent(source)}`);
|
||||
assert.equal(decodeURIComponent(dataUrl.slice(dataUrl.indexOf(',') + 1)), source);
|
||||
assert.match(captureSource, /image\.src = reportSvgDataUrl\(template\.viewportMarkup\(top, stripHeight, finalHeight\)\)/);
|
||||
assert.doesNotMatch(captureSource, /createObjectURL|revokeObjectURL/);
|
||||
});
|
||||
|
||||
test('final snapshot height uses logical layout metrics and rejects a footer before the last record', () => {
|
||||
assert.equal(resolveReportSnapshotHeight({
|
||||
layoutOffsetHeight: 91596,
|
||||
layoutScrollHeight: 91700,
|
||||
footerBottom: 91720,
|
||||
footerTextBottom: 91712,
|
||||
lastRecordBottom: 91684,
|
||||
}), 91720);
|
||||
assert.equal(resolveReportSnapshotHeight({
|
||||
layoutOffsetHeight: 300,
|
||||
layoutScrollHeight: 300,
|
||||
footerBottom: 0,
|
||||
footerTextBottom: 0,
|
||||
lastRecordBottom: 620,
|
||||
}), 620, 'a body-level raw appendix contributes to the measured full height');
|
||||
assert.equal(resolveReportSnapshotHeight({
|
||||
layoutOffsetHeight: 100,
|
||||
layoutScrollHeight: 100,
|
||||
footerBottom: 130,
|
||||
footerTextBottom: 155,
|
||||
lastRecordBottom: 0,
|
||||
}), 155, 'the end of footer text can extend beyond its reported box height');
|
||||
assert.equal(normalizeReportRectOffset(400, 1000, 500), 800, 'bounding-box positions are scaled back to logical layout units');
|
||||
assert.doesNotThrow(() => assertReportMeasurementAtOneX(900.5, 900));
|
||||
assert.doesNotThrow(() => assertReportMeasurementAtOneX(900, 900));
|
||||
assert.throws(() => assertReportMeasurementAtOneX(901.01, 900), /原始比例下测量/);
|
||||
assert.throws(() => assertReportMeasurementAtOneX(720, 900), /原始比例下测量/);
|
||||
assert.equal(isDocumentNodeFollowing(4), true);
|
||||
assert.equal(isDocumentNodeFollowing(2), false);
|
||||
assert.doesNotThrow(() => assertReportFooterAfterLastRecord(91720, 91684));
|
||||
assert.throws(() => assertReportFooterAfterLastRecord(91558, 91570), /末行与报告页脚排版重叠/);
|
||||
assert.match(captureSource, /style\.setProperty\('height', 'auto', 'important'\)/);
|
||||
assert.match(captureSource, /\.q-source-record-set,table,thead,tbody,tr,th,td/);
|
||||
assert.match(captureSource, /await measurementDocument\.fonts\?\.ready/);
|
||||
assert.match(captureSource, /image\.decode\?\.\(\)\.catch/);
|
||||
assert.match(captureSource, /measurementFrame\.setAttribute\('sandbox', 'allow-same-origin'\)/);
|
||||
assert.match(captureSource, /measurementFrame\.srcdoc = .*zoom:1!important/);
|
||||
assert.match(captureSource, /border:0;margin:0;padding:0;box-sizing:border-box/);
|
||||
assert.match(captureSource, /assertReportMeasurementAtOneX\(clonedRoot\.getBoundingClientRect\(\)\.width, clonedRoot\.offsetWidth\)/);
|
||||
assert.doesNotMatch(captureSource, /clonedRoot\.style\.height/);
|
||||
assert.match(captureSource, /measurementFrame\.remove\(\)/);
|
||||
assert.match(captureSource, /const layoutRoot = clonedRoot/);
|
||||
assert.match(captureSource, /layoutRoot\.querySelectorAll<HTMLElement>\('\.q-source-record-list tbody tr,tr\[data-record-provenance\]'\)/);
|
||||
assert.match(captureSource, /isDocumentNodeFollowing\(lastRecordRow\.compareDocumentPosition\(candidate\)\)/);
|
||||
assert.match(captureSource, /layoutOffsetHeight: layoutRoot\.offsetHeight/);
|
||||
assert.match(captureSource, /await measurementDocument\.fonts\?\.ready/);
|
||||
assert.match(captureSource, /range\.getBoundingClientRect\(\)/);
|
||||
assert.match(captureSource, /footerTextBottom: footerTextRangeBottom/);
|
||||
assert.doesNotMatch(captureSource, /DEBUG-source-record-tail/);
|
||||
assert.match(captureSource, /:root,:root>body\{/);
|
||||
assert.match(captureSource, /:root>body\{min-height:0!important\}/);
|
||||
assert.match(captureSource, /canvas\.width = width \* capturePixelRatio/);
|
||||
assert.match(captureSource, /foreignObject\.append\(marker\)/);
|
||||
assert.match(captureSource, /return findReportTailMarkerTop\(pixels, width, probeHeight, probeTop\)/);
|
||||
assert.match(captureSource, /const finalHeight = await calibrateReportTailHeight/);
|
||||
assert.match(captureSource, /REPORT_TAIL_MARKER_HEIGHT \+ 1/);
|
||||
});
|
||||
|
||||
test('raster tail probe finds a full 2-color marker row without treating antialiased edges as its top', async () => {
|
||||
const width = 64, height = 24, markerTop = 8, probeTop = 23_000;
|
||||
const pixels = new Uint8ClampedArray(width * height * 4);
|
||||
for (let i = 0; i < pixels.length; i += 4) pixels.set([255, 255, 255, 255], i);
|
||||
for (let y = markerTop; y < markerTop + 8; y += 1) {
|
||||
for (let x = 0; x < 32; x += 1) {
|
||||
pixels.set(x < 16 ? [255, 0, 255, 255] : [0, 255, 255, 255], (y * width + x) * 4);
|
||||
}
|
||||
}
|
||||
// A partial magenta row above the marker is deliberately insufficient by itself.
|
||||
for (let x = 0; x < 32; x += 1) pixels.set([255, 80, 255, 255], ((markerTop - 1) * width + x) * 4);
|
||||
assert.equal(findReportTailMarkerTop(pixels, width, height, probeTop), probeTop + markerTop + 1,
|
||||
'the output boundary includes the first marker pixel to avoid clipping from subpixel antialiasing');
|
||||
|
||||
const oneRow = pixels.slice();
|
||||
for (let y = markerTop + 1; y < markerTop + 8; y += 1) {
|
||||
for (let x = 0; x < 32; x += 1) oneRow.set([255, 255, 255, 255], (y * width + x) * 4);
|
||||
}
|
||||
await assert.rejects(async () => findReportTailMarkerTop(oneRow, width, height, probeTop), /未能确认报告长图尾部位置/);
|
||||
});
|
||||
|
||||
test('strip encoder keeps full dimensions and row order in one valid multi-IDAT PNG', async () => {
|
||||
const width = 300, height = 300;
|
||||
const expected = makePixels(width, height);
|
||||
const blob = await encodeRgbaStripsToPng(width, height, splitPixels(expected, width, height, 37));
|
||||
assert.equal(blob.type, 'image/png');
|
||||
|
||||
const chunks = parsePng(Buffer.from(await blob.arrayBuffer()));
|
||||
assert.equal(chunks[0].type, 'IHDR');
|
||||
assert.equal(chunks.at(-1).type, 'IEND');
|
||||
assert.ok(chunks.slice(1, -1).length > 1);
|
||||
assert.ok(chunks.slice(1, -1).every(chunk => chunk.type === 'IDAT'));
|
||||
assert.ok(chunks.slice(1, -1).every(chunk => chunk.data.length <= 64 * 1024));
|
||||
|
||||
const header = chunks[0].data;
|
||||
assert.equal(header.readUInt32BE(0), width);
|
||||
assert.equal(header.readUInt32BE(4), height);
|
||||
assert.equal(header[8], 8);
|
||||
assert.equal(header[9], 6);
|
||||
const compressed = Buffer.concat(chunks.slice(1, -1).map(chunk => chunk.data));
|
||||
const raw = inflateSync(compressed);
|
||||
const scanlineLength = width * 4 + 1;
|
||||
assert.equal(raw.length, scanlineLength * height);
|
||||
const decoded = new Uint8Array(width * height * 4);
|
||||
for (let row = 0; row < height; row += 1) {
|
||||
const source = row * scanlineLength;
|
||||
assert.equal(raw[source], 0, `filter for row ${row}`);
|
||||
decoded.set(raw.subarray(source + 1, source + scanlineLength), row * width * 4);
|
||||
}
|
||||
assert.deepEqual(decoded, expected);
|
||||
});
|
||||
|
||||
test('strip encoder rejects canceled exports instead of returning a partial PNG', async () => {
|
||||
let cancelled = false;
|
||||
async function* strips() {
|
||||
yield { y: 0, height: 1, data: new Uint8Array([1, 2, 3, 4]) };
|
||||
cancelled = true;
|
||||
yield { y: 1, height: 1, data: new Uint8Array([5, 6, 7, 8]) };
|
||||
}
|
||||
await assert.rejects(encodeRgbaStripsToPng(1, 2, strips(), () => cancelled), /已取消长图准备/);
|
||||
});
|
||||
|
||||
test('strip encoder rejects missing rows and reports over the total-pixel safety limit', async () => {
|
||||
async function* incomplete() { yield { y: 0, height: 1, data: new Uint8Array(4) }; }
|
||||
await assert.rejects(encodeRgbaStripsToPng(1, 2, incomplete()), /未完整栅格化/);
|
||||
async function* empty() { /* no rows */ }
|
||||
await assert.rejects(encodeRgbaStripsToPng(10_000, 10_001, empty()), /安全尺寸上限/);
|
||||
});
|
||||
@@ -0,0 +1,314 @@
|
||||
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 { analysisScopeText, analysisComposerState, restoredAnalysisDraft, analysisFollowRequestReady } from '../src/analysisScope.ts';
|
||||
import { analysisIsRunning, analysisScrollFollows, compactAnalysisTimeline, duplicatesFinalAnalysisAnswer } from '../src/analysisConversationState.ts';
|
||||
import { sanitizeAnalysisDisplayText } from '../src/analysisDisplayText.ts';
|
||||
import { modelThinkingEntries, thinkingStatus, orderedAnalysisProcess, groupAdjacentThinking } from '../src/analysisModelThinking.ts';
|
||||
|
||||
const visual = (overrides = {}) => ({
|
||||
id:'main',type:'column',title:'期间比较',subtitle:'',unit:'ratio',
|
||||
categories:[{key:'prior',label:'8月'},{key:'current',label:'9月'}],
|
||||
series:[{key:'composite_rate',label:'综合合格率',values:[.95,.94]}],
|
||||
evidenceRefs:['Q1234ABCD'],requiredFields:['black_good_weight','black_total_weight','bright_good_weight','bright_total_weight'],
|
||||
scope:{year:2026,month:9,releaseId:'release-a',includeUnassigned:false},period:{year:2026,month:9},comparisonPeriod:{year:2026,month:8},
|
||||
metric:'composite_rate',coverage:{totalRows:2,returnedRows:2,truncated:false},originTurnId:'turn-a',...overrides,
|
||||
});
|
||||
|
||||
test('a draft does not invent a period or company scope from question prose',()=>{
|
||||
assert.equal(analysisScopeText({question:'2026年9月全公司整体情况',status:'QUEUED'}),'');
|
||||
assert.equal(analysisScopeText({plan:{context:{releaseId:'private'}}}),'');
|
||||
});
|
||||
test('resolved per-turn scope wins over frozen submission and unrelated chart scope',()=>{
|
||||
const scope=analysisScopeText({id:'turn-a',plan:{context:{year:2026,quarter:3,product:'18X15X4+T',stage:'bright',includeUnassigned:false},frozenContext:{year:2025,month:1},semantic:{compare:true,priorContext:{year:2026,quarter:2}}},visuals:[visual()]});
|
||||
assert.equal(scope,'2026年第3季度 · 对比 2026年第2季度 · 产品:18X15X4+T · 亮片 · 不含未分类');
|
||||
});
|
||||
test('a single-value query does not treat previous context as a comparison period',()=>{
|
||||
for(const compare of [false,undefined]){
|
||||
const scope=analysisScopeText({plan:{context:{year:2026,month:9,product:'新产品'},semantic:{compare,priorContext:{year:2026,month:8,product:'旧产品'}}}});
|
||||
assert.equal(scope,'2026年9月 · 产品:新产品');
|
||||
}
|
||||
});
|
||||
test('changing products in the same month does not add an implicit comparison',()=>{
|
||||
const scope=analysisScopeText({plan:{context:{year:2026,month:9,product:'B'},semantic:{compare:false,priorContext:{year:2026,month:9,product:'A'}}}});
|
||||
assert.equal(scope,'2026年9月 · 产品:B');
|
||||
});
|
||||
test('native historical scope uses the unique broadest binding, not local product charts',()=>{
|
||||
const scope=analysisScopeText({id:'turn-a',plan:{context:{releaseId:'release-a'},frozenContext:{releaseId:'release-a'}},visuals:[
|
||||
visual({id:'local',scope:{year:2026,month:9,product:'小规格',stage:'black',releaseId:'release-a'},stage:'black'}),visual(),
|
||||
]});
|
||||
assert.equal(scope,'2026年9月 · 对比 2026年8月 · 当前授权范围 · 不含未分类');
|
||||
});
|
||||
test('equal-depth conflicting periods are never joined into one scope',()=>{
|
||||
const scope=analysisScopeText({id:'turn-a',visuals:[visual(),visual({id:'other',period:{year:2026,month:7}})]});
|
||||
assert.equal(scope,'');
|
||||
});
|
||||
test('two stages combine only when every other binding is identical',()=>{
|
||||
assert.equal(analysisScopeText({id:'turn-a',visuals:[visual({id:'black',stage:'black'}),visual({id:'bright',stage:'bright'})]}),
|
||||
'2026年9月 · 对比 2026年8月 · 当前授权范围 · 黑片与亮片 · 不含未分类');
|
||||
});
|
||||
test('native product follow-up keeps its product and both explicit stages',()=>{
|
||||
const scope={year:2026,month:9,product:'16.33X15.5X3.75+T',includeUnassigned:false,releaseId:'release-a'};
|
||||
assert.equal(analysisScopeText({id:'turn-a',plan:{context:{releaseId:'release-a'},frozenContext:{releaseId:'release-a'}},visuals:[
|
||||
visual({id:'black',metric:'black_rate',scope:{...scope,stage:'black'},stage:'black'}),
|
||||
visual({id:'bright',metric:'bright_rate',scope:{...scope,stage:'bright'},stage:'bright'}),
|
||||
]}), '2026年9月 · 对比 2026年8月 · 产品:16.33X15.5X3.75+T · 黑片与亮片 · 不含未分类');
|
||||
});
|
||||
test('opposite stages cannot combine different products, periods or data releases',()=>{
|
||||
const scope={year:2026,month:9,product:'A',releaseId:'release-a'};
|
||||
const first=visual({id:'black',scope:{...scope,stage:'black'},stage:'black'});
|
||||
for(const change of [{scope:{...scope,product:'B',stage:'bright'}},{period:{year:2026,month:7}},{scope:{...scope,releaseId:'release-b',stage:'bright'}}]){
|
||||
assert.equal(analysisScopeText({id:'turn-a',visuals:[first,visual({id:'bright',scope:{...scope,stage:'bright'},stage:'bright',...change})]}),'');
|
||||
}
|
||||
});
|
||||
test('scope ignores a visual explicitly bound to another turn',()=>{
|
||||
assert.equal(analysisScopeText({id:'turn-b',visuals:[visual()]}),'');
|
||||
});
|
||||
test('identical root bindings are accepted while nested result payloads are supported',()=>{
|
||||
assert.equal(analysisScopeText({id:'turn-a',result:{visuals:[visual(),visual({id:'second'})]}}),
|
||||
'2026年9月 · 对比 2026年8月 · 当前授权范围 · 不含未分类');
|
||||
});
|
||||
test('compatible actual chart period refines a year-only submitted context',()=>{
|
||||
assert.equal(analysisScopeText({id:'turn-a',plan:{context:{year:2026}},visuals:[visual()]}),
|
||||
'2026年9月 · 对比 2026年8月 · 当前授权范围 · 不含未分类');
|
||||
});
|
||||
test('every bound extra condition stays visible instead of claiming a broader scope',()=>{
|
||||
assert.equal(analysisScopeText({plan:{context:{year:2026,month:9,group:'["国内","海外"]',extraFilters:{厂区:['一厂']},exclusions:{product:['旧规格']}}}}),
|
||||
'2026年9月 · 业务分组:国内、海外 · 厂区:一厂 · 排除产品:旧规格');
|
||||
});
|
||||
test('a product keyword remains visible even with the overall view',()=>{
|
||||
assert.equal(analysisScopeText({plan:{context:{year:2026,month:9,view:'overall',productSearch:'16.33'}}}),
|
||||
'2026年9月 · 产品检索:16.33');
|
||||
});
|
||||
test('a visual carrying the same keyword may refine the period without losing the filter',()=>{
|
||||
const scope={year:2026,month:9,releaseId:'release-a',productSearch:'16.33',includeUnassigned:false};
|
||||
assert.equal(analysisScopeText({id:'turn-a',plan:{context:{year:2026,productSearch:'16.33'}},visuals:[visual({scope})]}),
|
||||
'2026年9月 · 对比 2026年8月 · 产品检索:16.33 · 不含未分类');
|
||||
});
|
||||
test('a different visual keyword cannot overwrite or enrich the bound query',()=>{
|
||||
assert.equal(analysisScopeText({id:'turn-a',plan:{context:{year:2026,month:9,productSearch:'16.33'}},
|
||||
visuals:[visual({scope:{year:2026,month:9,releaseId:'release-a',productSearch:'18X15'}})]}),
|
||||
'2026年9月 · 产品检索:16.33');
|
||||
});
|
||||
test('equal-depth visual bindings with different keywords are not combined',()=>{
|
||||
assert.equal(analysisScopeText({id:'turn-a',visuals:[
|
||||
visual({id:'first',scope:{year:2026,month:9,releaseId:'release-a',productSearch:'16.33'}}),
|
||||
visual({id:'second',scope:{year:2026,month:9,releaseId:'release-a',productSearch:'18X15'}}),
|
||||
]}), '');
|
||||
});
|
||||
test('a broad visual remains the root when another visual is narrowed by keyword',()=>{
|
||||
assert.equal(analysisScopeText({id:'turn-a',visuals:[visual(),
|
||||
visual({id:'filtered',scope:{year:2026,month:9,releaseId:'release-a',productSearch:'16.33'}}),
|
||||
]}), '2026年9月 · 对比 2026年8月 · 当前授权范围 · 不含未分类');
|
||||
});
|
||||
test('typing and queuing followups never removes the stop control',()=>{
|
||||
for(const draft of ['','follow-up'])for(const queued of ['','queued']){
|
||||
const state=analysisComposerState(true,false,false,draft,queued);
|
||||
assert.equal(state.showStop,true);assert.equal(state.stopDisabled,false);
|
||||
assert.equal(state.sendDisabled,!draft || !!queued);assert.equal(state.sendLabel,'排队发送');
|
||||
}
|
||||
assert.equal(analysisComposerState(true,true,false,'draft','').stopDisabled,true);
|
||||
assert.equal(analysisComposerState(true,true,false,'draft','').sendDisabled,true);
|
||||
assert.equal(analysisComposerState(false,false,false,'draft','').showStop,false);
|
||||
});
|
||||
test('restoring a queued draft does not overwrite another unsent question',()=>{
|
||||
assert.equal(restoredAnalysisDraft('new','queued'),'queued\n\nnew');
|
||||
assert.equal(restoredAnalysisDraft('','queued'),'queued');
|
||||
assert.equal(restoredAnalysisDraft('same','same'),'same');
|
||||
});
|
||||
|
||||
const processSource=fs.readFileSync(new URL('../src/AnalysisProcess.tsx',import.meta.url),'utf8').replace(/^import .*;$/gm,'').replace('export function AnalysisProcess','function AnalysisProcess');
|
||||
const icon=()=>React.createElement('i');
|
||||
const thinkingSource=fs.readFileSync(new URL('../src/ModelThinkingPanel.tsx',import.meta.url),'utf8').replace(/^import .*;$/gm,'').replace('export function AnalysisThinkingBlock','function AnalysisThinkingBlock');
|
||||
const Thinking=new Function('React','useEffect','useLayoutEffect','useRef','useState','LoadingOutlined','RightOutlined','analysisScrollFollows','modelThinkingEntries','thinkingStatus',
|
||||
ts.transpileModule(`${thinkingSource}\nreturn AnalysisThinkingBlock;`,{fileName:'thinking.tsx',compilerOptions:{target:ts.ScriptTarget.ES2022,jsx:ts.JsxEmit.React}}).outputText
|
||||
)(React,React.useEffect,React.useLayoutEffect,React.useRef,React.useState,icon,icon,analysisScrollFollows,modelThinkingEntries,thinkingStatus);
|
||||
const Process=new Function('React','useEffect','useState','Spin','CheckCircleOutlined','CloseCircleOutlined','ClockCircleOutlined','RightOutlined','analysisIsRunning','compactAnalysisTimeline','duplicatesFinalAnalysisAnswer','sanitizeAnalysisDisplayText','AiMarkdown','orderedAnalysisProcess','groupAdjacentThinking','AnalysisThinkingBlock',
|
||||
ts.transpileModule(`${processSource}\nreturn AnalysisProcess;`,{fileName:'process.tsx',compilerOptions:{target:ts.ScriptTarget.ES2022,jsx:ts.JsxEmit.React}}).outputText
|
||||
)(React,React.useEffect,React.useState,icon,icon,icon,icon,icon,analysisIsRunning,compactAnalysisTimeline,duplicatesFinalAnalysisAnswer,sanitizeAnalysisDisplayText,({content})=>React.createElement('p',null,content),orderedAnalysisProcess,groupAdjacentThinking,Thinking);
|
||||
const processTurn=status=>({status,steps:[{tool:'read',label:'读取数据',status:'completed'}]});
|
||||
test('settled process is collapsed, with the original records retained inside',()=>{
|
||||
for(const status of ['COMPLETED','PARTIAL','FAILED','CANCELLED']){
|
||||
const html=renderToStaticMarkup(React.createElement(Process,{turn:processTurn(status)}));
|
||||
assert.match(html,/<details class="analysis-process-history analysis-agent-process"/);assert.match(html,/已完成/);assert.match(html,/读取数据/);
|
||||
assert.doesNotMatch(html,/<details class="analysis-process-history analysis-agent-process" open/);
|
||||
}
|
||||
});
|
||||
test('running process remains visible instead of being hidden behind the completed fold',()=>{
|
||||
const html=renderToStaticMarkup(React.createElement(Process,{turn:processTurn('RUNNING')}));
|
||||
assert.match(html,/读取数据/);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',()=>{
|
||||
const key='fresh-request';
|
||||
assert.equal(analysisFollowRequestReady(key,{id:'previous-turn',question:'same question',status:'COMPLETED',_uiFollowKey:'previous-key'}),false);
|
||||
assert.equal(analysisFollowRequestReady(key,{question:'same question',status:'QUEUED',_uiFollowKey:key}),true);
|
||||
assert.equal(analysisFollowRequestReady(key,{id:'fresh-turn',status:'COMPLETED',_uiFollowKey:key}),true);
|
||||
assert.equal(analysisFollowRequestReady(null,{id:'fresh-turn',status:'COMPLETED',_uiFollowKey:key}),false);
|
||||
});
|
||||
|
||||
test('manual downward movement near the bottom resumes follow, while layout scroll events preserve the state',()=>{
|
||||
assert.equal(analysisScrollFollows(24,false,'down'),true);
|
||||
assert.equal(analysisScrollFollows(25,false,'down'),false);
|
||||
assert.equal(analysisScrollFollows(0,false,null),false);
|
||||
assert.equal(analysisScrollFollows(0,true,null),true);
|
||||
assert.equal(analysisScrollFollows(0,true,'up'),false);
|
||||
});
|
||||
|
||||
// Exercise the component's scrolling and update effect, including the browser's
|
||||
// scroll-range clamp. Rectangles are zoomed, while scrollTop stays in layout units.
|
||||
const pageSource=fs.readFileSync(new URL('../src/ManagementPages.tsx',import.meta.url),'utf8');
|
||||
const scrollSource=pageSource.slice(pageSource.indexOf(' const scrollToLatest ='),pageSource.indexOf('\n useEffect(() => {\n if (!busy)'));
|
||||
const updateStart=pageSource.indexOf(' useEffect(() => {\n if (analysisFollowRequestReady');
|
||||
const updateSource=pageSource.slice(updateStart,pageSource.indexOf('\n\n const loadSessions',updateStart));
|
||||
function scrollFixture({scale=.8,turnOffset=1200,maxScroll=2000,following=true}={}){
|
||||
const body=`
|
||||
let lastTurn=null,busy=true,active=true,turns=[],sessionId='session-a',hasNewContent=false;
|
||||
const followOutput={current:following},explicitlyFollowing={current:false},followRequest={current:null},seenConclusion={current:null};
|
||||
const previousScrollTop={current:0},readingPosition={current:0};
|
||||
const ANALYSIS_FINAL_STATUSES=new Set(['COMPLETED','PARTIAL','FAILED','CANCELLED','NEEDS_CLARIFICATION']);
|
||||
const setHasNewContent=value=>{hasNewContent=value;};
|
||||
let position=0,updateEffect;
|
||||
const latest={dataset:{},getBoundingClientRect:()=>({top:56.5+(turnOffset-position)*scale})};
|
||||
const element={
|
||||
offsetHeight:600,clientTop:0,scrollHeight:maxScroll+600,
|
||||
get scrollTop(){return position;},set scrollTop(value){position=Math.max(0,Math.min(value,maxScroll));},
|
||||
getBoundingClientRect:()=>({top:56.5,height:600*scale}),querySelector:()=>latest,
|
||||
};
|
||||
const conversation={current:element},useEffect=callback=>{updateEffect=callback;};
|
||||
${scrollSource}
|
||||
${updateSource}
|
||||
return {
|
||||
update(turn,running=true){lastTurn=turn;busy=running;latest.dataset={analysisStatus:turn.status,analysisTurnId:turn.id};updateEffect();},
|
||||
scroll(top,intent='up'){
|
||||
element.scrollTop=top;
|
||||
const distance=maxScroll-position;
|
||||
followOutput.current=analysisScrollFollows(distance,followOutput.current,intent);
|
||||
if(intent==='up') explicitlyFollowing.current=false;
|
||||
else if(intent==='down'&&followOutput.current) explicitlyFollowing.current=true;
|
||||
if(followOutput.current) hasNewContent=false;
|
||||
previousScrollTop.current=position;readingPosition.current=position;
|
||||
},
|
||||
programmaticScroll(top){
|
||||
element.scrollTop=top;previousScrollTop.current=position;readingPosition.current=position;
|
||||
followOutput.current=analysisScrollFollows(maxScroll-position,followOutput.current,null);
|
||||
},
|
||||
returnToLatest(){
|
||||
followOutput.current=true;explicitlyFollowing.current=true;hasNewContent=false;
|
||||
element.scrollTop=element.scrollHeight;previousScrollTop.current=position;readingPosition.current=position;
|
||||
},
|
||||
submit(key){followRequest.current=key;},
|
||||
get:()=>({position,hasNewContent,following:followOutput.current,seen:seenConclusion.current}),
|
||||
};
|
||||
`;
|
||||
return new Function('analysisFollowRequestReady','analysisScrollFollows','scale','turnOffset','maxScroll','following',
|
||||
ts.transpileModule(body,{compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText
|
||||
)(analysisFollowRequestReady,analysisScrollFollows,scale,turnOffset,maxScroll,following);
|
||||
}
|
||||
|
||||
test('completion anchors the same layout position at workspace zoom levels',()=>{
|
||||
for(const scale of [.8,1,1.25]){
|
||||
const ui=scrollFixture({scale});
|
||||
ui.update({id:'turn-a',status:'COMPLETED'});
|
||||
assert.equal(ui.get().position,1200);
|
||||
assert.equal(ui.get().seen,'turn-a');
|
||||
}
|
||||
});
|
||||
test('short conclusions safely clamp at the end of the conversation',()=>{
|
||||
const ui=scrollFixture({maxScroll:1150});
|
||||
ui.update({id:'turn-a',status:'COMPLETED'});
|
||||
assert.equal(ui.get().position,1150);
|
||||
assert.equal(ui.get().hasNewContent,false);
|
||||
});
|
||||
test('terminal detail and history refreshes cannot resurrect the unread indicator',()=>{
|
||||
const ui=scrollFixture();
|
||||
ui.update({id:'turn-a',status:'RUNNING'});
|
||||
ui.update({id:'turn-a',status:'COMPLETED'}); // Terminal SSE, busy remains true.
|
||||
assert.equal(ui.get().following,false);
|
||||
ui.update({id:'turn-a',status:'COMPLETED',answer:'saved answer'}); // Durable detail.
|
||||
ui.update({id:'turn-a',status:'COMPLETED',answer:'saved answer'}); // History refresh.
|
||||
ui.update({id:'turn-a',status:'COMPLETED',answer:'saved answer'},false);
|
||||
assert.equal(ui.get().hasNewContent,false);
|
||||
assert.equal(ui.get().position,1200);
|
||||
});
|
||||
test('completion still signals unread output when the reader stayed on an older turn',()=>{
|
||||
const ui=scrollFixture({following:false});
|
||||
ui.update({id:'turn-a',status:'RUNNING'});
|
||||
ui.update({id:'turn-a',status:'COMPLETED'});
|
||||
ui.update({id:'turn-a',status:'COMPLETED'},false);
|
||||
assert.equal(ui.get().hasNewContent,true);
|
||||
assert.equal(ui.get().position,0);
|
||||
});
|
||||
test('scrolling up pauses, returning near the bottom resumes, and completed output stays followed after an explicit return',()=>{
|
||||
const ui=scrollFixture();
|
||||
ui.update({id:'turn-a',status:'RUNNING'});
|
||||
ui.scroll(1500,'up');
|
||||
ui.update({id:'turn-a',status:'RUNNING',answer:'streaming update'});
|
||||
assert.equal(ui.get().position,1500);
|
||||
assert.equal(ui.get().following,false);
|
||||
ui.scroll(1990,'down');
|
||||
assert.equal(ui.get().following,true);
|
||||
assert.equal(ui.get().hasNewContent,false);
|
||||
ui.update({id:'turn-a',status:'COMPLETED'});
|
||||
assert.equal(ui.get().position,2000);
|
||||
assert.equal(ui.get().following,true);
|
||||
ui.returnToLatest();
|
||||
ui.update({id:'turn-a',status:'COMPLETED',answer:'final durable answer'});
|
||||
assert.equal(ui.get().following,true);
|
||||
assert.equal(ui.get().position,2000);
|
||||
});
|
||||
test('layout-driven movement to the bottom does not rearm a reader who moved up',()=>{
|
||||
const ui=scrollFixture({following:false});
|
||||
ui.programmaticScroll(2000);
|
||||
assert.equal(ui.get().position,2000);
|
||||
assert.equal(ui.get().following,false);
|
||||
});
|
||||
test('a fresh request resets the seen conclusion and follows its own output',()=>{
|
||||
const ui=scrollFixture();
|
||||
ui.update({id:'old-turn',status:'COMPLETED'},false);
|
||||
ui.submit('new-request');
|
||||
ui.update({id:'new-turn',status:'RUNNING',_uiFollowKey:'new-request'});
|
||||
assert.equal(ui.get().following,true);
|
||||
assert.equal(ui.get().seen,null);
|
||||
assert.equal(ui.get().position,2000);
|
||||
ui.scroll(300);
|
||||
ui.update({id:'new-turn',status:'COMPLETED'});
|
||||
assert.equal(ui.get().hasNewContent,true);
|
||||
assert.equal(ui.get().position,300);
|
||||
});
|
||||
|
||||
test('provider thinking is complete, escaped and separate from conclusions',()=>{
|
||||
const text='完整接口文本'.repeat(2000)+'<img src=x onerror=alert(1)>';
|
||||
const turn={id:'thinking',status:'RUNNING',modelThinking:[{id:'api-abcd1234-1',model:'fixture',phase:'analysis',status:'running',version:1,source:'api',text,streaming:true}]};
|
||||
const html=renderToStaticMarkup(React.createElement(Process,{turn}));
|
||||
assert.ok(html.includes('完整接口文本'.repeat(2000)));
|
||||
assert.ok(html.includes('<img'));
|
||||
assert.ok(!html.includes('<img src=x'));
|
||||
assert.doesNotMatch(html.match(/<details[^>]*class="analysis-thinking-block"[^>]*>/)[0],/\sopen(?:=|\s|>)/);
|
||||
const archived=renderToStaticMarkup(React.createElement(Process,{turn:{...turn,status:'COMPLETED'}}));
|
||||
assert.doesNotMatch(archived.match(/<details[^>]*class="analysis-thinking-block"[^>]*>/)[0],/\sopen(?:=|\s|>)/);
|
||||
assert.ok(archived.includes('完整接口文本'.repeat(2000)));
|
||||
});
|
||||
|
||||
|
||||
test('agent process interleaves thoughts, tool calls and text with one runtime header',()=>{
|
||||
const stamp=n=>`2026-10-26T00:00:0${n}Z`;
|
||||
const blocks=[
|
||||
{id:'api-abcd1234-1',model:'model-hidden',phase:'planning',status:'completed',version:1,source:'api',text:'先核对范围',streaming:true,at:stamp(1)},
|
||||
{id:'api-abcd1234-2',model:'model-hidden',phase:'finalizing',status:'completed',version:1,source:'api',text:'再整理结果',streaming:true,at:stamp(4)},
|
||||
];
|
||||
const turn={id:'agent',status:'COMPLETED',modelThinking:blocks,timeline:[
|
||||
{kind:'assistant',sequence:1,at:stamp(2),text:'我来查询两个期间。'},
|
||||
{kind:'tool_start',sequence:2,at:stamp(3),tool:'read',toolCallId:'call-1',label:'读取数据'},
|
||||
{kind:'tool_result',sequence:3,at:stamp(5),tool:'read',toolCallId:'call-1',status:'completed',text:'查询已完成'},
|
||||
]};
|
||||
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.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);
|
||||
});
|
||||
@@ -0,0 +1,198 @@
|
||||
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 * as helpers from '../src/analysisSubmission.ts';
|
||||
import { restoredAnalysisDraft } from '../src/analysisScope.ts';
|
||||
|
||||
const deferred = () => { let resolve, reject; const promise = new Promise((r,j) => { resolve = r; reject = j; }); return { promise, resolve, reject }; };
|
||||
const tick = () => new Promise(resolve => setImmediate(resolve));
|
||||
const source = fs.readFileSync(new URL('../src/ManagementPages.tsx', import.meta.url), 'utf8');
|
||||
const page = source.slice(source.indexOf('function AnalysisPage('));
|
||||
const closures = page.slice(page.indexOf(' const cancelAcceptedTurn = async'), page.indexOf('\n useEffect(() => { void sendQueuedFollowup(); }'));
|
||||
const turnComponent = source.slice(source.indexOf('function AnalysisTurn('), source.indexOf('function AnalysisTurnMetadata('));
|
||||
const renderDraft = turn => {
|
||||
const component = new Function('React', 'useAnalysisVisualRecovery', ts.transpileModule(`${turnComponent}\nreturn AnalysisTurn;`, {
|
||||
fileName: 'submission-render.tsx', compilerOptions: {target:ts.ScriptTarget.ES2022,jsx:ts.JsxEmit.React},
|
||||
}).outputText)(React, turn => ({turn,available:false,recovering:false,error:''}));
|
||||
return renderToStaticMarkup(React.createElement(component, { turn }));
|
||||
};
|
||||
|
||||
// Run the component's current submission/cancellation closures with API doubles.
|
||||
// This catches wiring errors that helper-only assertions would miss, without DOM or network.
|
||||
function fixture(api, hooks = {}, initialSession = 'session-1') {
|
||||
const body = `
|
||||
const {beginAnalysisSubmission,requestSubmissionCancellation,submissionOutcomeUnknown}=helpers;
|
||||
let query='',sessionId=${JSON.stringify(initialSession)},sessionContext=null,releaseId=undefined,sourceResultRef=undefined;
|
||||
let sessionReadOnly=false,stopping=false,busy=false,historyLoading=false,lastTurn=null,turns=[],activeTurnId='',retryQuestion='',error='',progress='',queuedFollowup='';
|
||||
const mounted={current:true},navigationGeneration={current:0},subscriptionGeneration={current:0},streamController={current:null},submissionAttempt={current:null},followOutput={current:true},explicitlyFollowing={current:false},followRequest={current:null},cancellationRequest={current:null};
|
||||
const user={id:'fixture-user'},ANALYSIS_FINAL_STATUSES=new Set(['COMPLETED','PARTIAL','FAILED','CANCELLED','NEEDS_CLARIFICATION']);
|
||||
const beginAnalysisSelection=()=>1,rememberAnalysisSession=()=>{},rememberPendingAnalysisSession=()=>{},writeAnalysisLocation=()=>{};
|
||||
const onUnauthorized=()=>false,apiMessage=e=>e.message,message={error(){},info(){}};
|
||||
const setStopping=v=>{stopping=v;},setBusy=v=>{busy=v;if(!v){stopping=false;cancellationRequest.current=null;}},setError=v=>{error=v;},setRetryQuestion=v=>{retryQuestion=v;},setQuery=v=>{query=v;},setSessionId=v=>{sessionId=v;};
|
||||
const setLastTurn=v=>{lastTurn=typeof v==='function'?v(lastTurn):v;},setTurns=v=>{turns=typeof v==='function'?v(turns):v;};
|
||||
const setActiveTurnId=v=>{activeTurnId=v;},setStreamProgress=v=>{progress=v;},setQueuedFollowup=v=>{queuedFollowup=v;};
|
||||
const loadSessions=async()=>{if(hooks.loadSessions)await hooks.loadSessions();};
|
||||
const followTurn=async id=>{activeTurnId=id;busy=true;if(hooks.followTurn)await hooks.followTurn(id);};
|
||||
${closures}
|
||||
return {submit,cancelTurn,retryTurn,queueFollowup,sendQueuedFollowup,
|
||||
setReadOnly(value){sessionReadOnly=value;},
|
||||
seedTurn(turn){lastTurn=turn;},
|
||||
setInput(value){query=value;},
|
||||
finishCurrent(){busy=false;lastTurn={...lastTurn,status:'COMPLETED'};},
|
||||
switchSession(id){navigationGeneration.current++;submissionAttempt.current=null;sessionId=id;busy=false;lastTurn=null;activeTurnId='';error='';},
|
||||
get:()=>({busy,stopping,lastTurn,turns,activeTurnId,retryQuestion,error,progress,queuedFollowup,query,attempt:submissionAttempt.current})};
|
||||
`;
|
||||
return new Function('api', 'helpers', 'hooks', 'restoredAnalysisDraft', ts.transpileModule(body, {compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText)(api, helpers, hooks, restoredAnalysisDraft);
|
||||
}
|
||||
|
||||
test('read-only history cannot submit, retry, or queue analysis and keeps its saved turn and draft', async () => {
|
||||
const calls=[];const ui=fixture({startAnalysisTurn:async()=>calls.push('start'),retryAnalysisTurn:async()=>calls.push('retry')});
|
||||
const turn={id:'legacy-turn',status:'FAILED',question:'old question',result:{answer:'saved answer'}};
|
||||
ui.seedTurn(turn);ui.setInput('new question');ui.setReadOnly(true);
|
||||
await ui.submit();await ui.retryTurn(turn);ui.queueFollowup();
|
||||
assert.deepEqual(calls,[]);assert.equal(ui.get().lastTurn,turn);assert.equal(ui.get().query,'new question');
|
||||
assert.equal(ui.get().busy,false);assert.equal(ui.get().queuedFollowup,'');
|
||||
});
|
||||
|
||||
test('unknown result retries reuse the key only for identical frozen submission', () => {
|
||||
const input={sessionId:'s',question:'q',generation:1,context:{month:9,year:2026}};
|
||||
const prior=helpers.beginAnalysisSubmission(null,input,()=> 'first-key');prior.uncertain=true;prior.inFlight=false;
|
||||
assert.equal(helpers.beginAnalysisSubmission(prior,{...input,context:{year:2026,month:9}},()=> 'new-key'),prior);
|
||||
for(const change of [{question:'other'},{sessionId:'other'},{generation:2},{context:{month:8,year:2026}}])
|
||||
assert.equal(helpers.beginAnalysisSubmission(prior,{...input,...change},()=> 'new-key').idempotencyKey,'new-key');
|
||||
});
|
||||
|
||||
test('explicit client rejection differs from an unknown network/server outcome', () => {
|
||||
for(const status of [400,401,403,404,409,413,422,429])assert.equal(helpers.submissionOutcomeUnknown({status}),false);
|
||||
for(const status of [0,200,408,500,502,503])assert.equal(helpers.submissionOutcomeUnknown({status}),true);
|
||||
assert.equal(helpers.submissionOutcomeUnknown(new Error('connection lost')),true);
|
||||
});
|
||||
|
||||
test('stop during turn creation is fulfilled once its response identifies the turn', async () => {
|
||||
const start=deferred(),cancelled=[];
|
||||
const ui=fixture({startAnalysisTurn:()=>start.promise,cancelAnalysisTurn:async id=>cancelled.push(id),analysisTurn:async()=>({status:'CANCELLED'})});
|
||||
const pending=ui.submit('q');await ui.cancelTurn();assert.deepEqual(cancelled,[]);
|
||||
start.resolve({turn:{id:'turn-1',status:'QUEUED'}});await pending;
|
||||
assert.deepEqual(cancelled,['turn-1']);assert.equal(ui.get().lastTurn.status,'CANCELLED');assert.equal(ui.get().busy,false);
|
||||
});
|
||||
|
||||
test('stop before the new session is created prevents a model turn from starting', async () => {
|
||||
const created=deferred();let starts=0;
|
||||
const ui=fixture({createAnalysisSession:()=>created.promise,startAnalysisTurn:async()=>{starts++;}}, {}, '');
|
||||
const pending=ui.submit('q');await ui.cancelTurn();created.resolve({session:{id:'new-session'}});await pending;
|
||||
assert.equal(starts,0);assert.equal(ui.get().lastTurn.status,'CANCELLED');assert.equal(ui.get().busy,false);
|
||||
});
|
||||
|
||||
test('a follow-up entered while analysis runs is sent after the current turn settles', async () => {
|
||||
const following=deferred(),questions=[];
|
||||
const ui=fixture({startAnalysisTurn:async(_session,body)=>{questions.push(body.question);return {turn:{id:`turn-${questions.length}`}};}},
|
||||
{followTurn:()=>following.promise});
|
||||
const first=ui.submit('initial question');await tick();
|
||||
ui.setInput('follow-up question');ui.queueFollowup();
|
||||
assert.equal(ui.get().queuedFollowup,'follow-up question');
|
||||
assert.equal(ui.get().query,'');
|
||||
assert.deepEqual(questions,['initial question']);
|
||||
following.resolve();await first;ui.finishCurrent();
|
||||
await ui.sendQueuedFollowup();
|
||||
assert.deepEqual(questions,['initial question','follow-up question']);
|
||||
assert.equal(ui.get().queuedFollowup,'');
|
||||
});
|
||||
|
||||
test('session-list refresh cannot delay turn following or its stop target', async () => {
|
||||
const list=deferred(),following=deferred(),followed=[];
|
||||
const ui=fixture({startAnalysisTurn:async()=>({turn:{id:'turn-1'}})}, {loadSessions:()=>list.promise,followTurn:id=>{followed.push(id);return following.promise;}});
|
||||
const pending=ui.submit('q');await tick();assert.deepEqual(followed,['turn-1']);assert.equal(ui.get().activeTurnId,'turn-1');
|
||||
following.resolve();list.resolve();await pending;
|
||||
});
|
||||
|
||||
test('a lost accepted response retries the same key without archiving an unsaved phantom turn', async () => {
|
||||
const calls=[];
|
||||
const ui=fixture({startAnalysisTurn:async(session,body)=>{calls.push({session,...body});if(calls.length===1)throw Object.assign(new Error('lost response'),{status:0});return {turn:{id:'original-turn'}};}});
|
||||
await ui.submit('q');assert.equal(ui.get().attempt.uncertain,true);
|
||||
await ui.submit(ui.get().retryQuestion);assert.equal(calls.length,2);assert.equal(calls[0].idempotencyKey,calls[1].idempotencyKey);
|
||||
assert.equal(ui.get().lastTurn.id,'original-turn');assert.deepEqual(ui.get().turns,[]);
|
||||
});
|
||||
|
||||
test('an explicit rejection clears the attempt so a corrected retry gets a fresh key', async () => {
|
||||
const keys=[];
|
||||
const ui=fixture({startAnalysisTurn:async(_session,body)=>{keys.push(body.idempotencyKey);throw Object.assign(new Error('validation rejected'),{status:400});}});
|
||||
await ui.submit('q');assert.equal(ui.get().attempt,null);await ui.submit('corrected q');assert.notEqual(keys[0],keys[1]);
|
||||
});
|
||||
|
||||
test('switching session while creation is pending cannot cancel or render into the new session', async () => {
|
||||
const start=deferred(),cancelled=[];
|
||||
const ui=fixture({startAnalysisTurn:()=>start.promise,cancelAnalysisTurn:async id=>cancelled.push(id)});
|
||||
const pending=ui.submit('q');await ui.cancelTurn();ui.switchSession('session-2');start.resolve({turn:{id:'old-turn'}});await pending;
|
||||
assert.deepEqual(cancelled,[]);assert.equal(ui.get().lastTurn,null);assert.equal(ui.get().activeTurnId,'');
|
||||
});
|
||||
|
||||
test('stop during retry waits for requeue instead of cancelling the old terminal state', async () => {
|
||||
const retry=deferred(),cancelled=[];
|
||||
const ui=fixture({retryAnalysisTurn:()=>retry.promise,cancelAnalysisTurn:async id=>cancelled.push(id),analysisTurn:async()=>({status:'CANCELLED'})});
|
||||
ui.seedTurn({id:'newest-turn',question:'newest question',status:'COMPLETED'});
|
||||
const pending=ui.retryTurn({id:'partial-turn',sessionId:'session-1',question:'q',status:'PARTIAL'});
|
||||
await ui.cancelTurn();assert.deepEqual(cancelled,[]);
|
||||
retry.resolve({turn:{id:'partial-turn',sessionId:'session-1',status:'QUEUED'}});await pending;
|
||||
assert.deepEqual(cancelled,['partial-turn']);assert.equal(ui.get().busy,false);assert.equal(ui.get().lastTurn.question,'q');
|
||||
});
|
||||
|
||||
test('a late cancellation failure cannot put an error in a newly selected session', async () => {
|
||||
const cancel=deferred(),following=deferred();
|
||||
const ui=fixture({startAnalysisTurn:async()=>({turn:{id:'turn-1'}}),cancelAnalysisTurn:()=>cancel.promise}, {followTurn:()=>following.promise});
|
||||
const pending=ui.submit('q');await tick();const stopping=ui.cancelTurn();ui.switchSession('other');cancel.reject(new Error('cancellation response lost'));await stopping;following.resolve();await pending;
|
||||
assert.equal(ui.get().error,'');assert.equal(ui.get().lastTurn,null);
|
||||
});
|
||||
|
||||
test('repeated stop clicks make one cancellation request until the task settles', async () => {
|
||||
const cancel=deferred(),following=deferred();let cancellationCount=0,detailReads=0;
|
||||
const ui=fixture({startAnalysisTurn:async()=>({turn:{id:'turn-1'}}),cancelAnalysisTurn:()=>{cancellationCount++;return cancel.promise;},
|
||||
analysisTurn:async()=>{detailReads++;return {id:'turn-1',status:'CANCELLED'};}}, {followTurn:()=>following.promise});
|
||||
const pending=ui.submit('q');await tick();const first=ui.cancelTurn(),second=ui.cancelTurn();
|
||||
await second;assert.equal(cancellationCount,1);assert.equal(ui.get().stopping,true);
|
||||
cancel.resolve();await first;assert.equal(ui.get().attempt,null);assert.equal(ui.get().busy,false);assert.equal(detailReads,1);
|
||||
following.resolve();await pending;
|
||||
});
|
||||
|
||||
test('stopping retains a queued question and any newer draft without sending either', async () => {
|
||||
const following=deferred(),questions=[];
|
||||
const ui=fixture({startAnalysisTurn:async(_session,body)=>{questions.push(body.question);return {turn:{id:'turn-1'}};},
|
||||
cancelAnalysisTurn:async()=>{},analysisTurn:async()=>({id:'turn-1',status:'CANCELLED'})}, {followTurn:()=>following.promise});
|
||||
const pending=ui.submit('initial');await tick();
|
||||
ui.setInput('queued follow-up');ui.queueFollowup();ui.setInput('new unsent draft');
|
||||
await ui.cancelTurn();await ui.sendQueuedFollowup();
|
||||
assert.equal(ui.get().query,'queued follow-up\n\nnew unsent draft');assert.equal(ui.get().queuedFollowup,'');
|
||||
assert.deepEqual(questions,['initial']);following.resolve();await pending;
|
||||
});
|
||||
|
||||
test('a failed stop request allows another explicit stop attempt', async () => {
|
||||
const following=deferred();let cancellationCount=0;
|
||||
const ui=fixture({startAnalysisTurn:async()=>({turn:{id:'turn-1'}}),cancelAnalysisTurn:async()=>{cancellationCount++;if(cancellationCount===1)throw new Error('offline');},
|
||||
analysisTurn:async()=>({id:'turn-1',status:'CANCELLED'})}, {followTurn:()=>following.promise});
|
||||
const pending=ui.submit('initial');await tick();await ui.cancelTurn();
|
||||
assert.equal(ui.get().stopping,false);assert.equal(ui.get().busy,true);
|
||||
await ui.cancelTurn();assert.equal(cancellationCount,2);assert.equal(ui.get().busy,false);
|
||||
following.resolve();await pending;
|
||||
});
|
||||
|
||||
test('unknown 503 submission renders recovery notice without claiming a queued or running task', async () => {
|
||||
const ui=fixture({startAnalysisTurn:async()=>{throw Object.assign(new Error('service unavailable'),{status:503});}});
|
||||
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.equal(ui.get().lastTurn.status,undefined);
|
||||
});
|
||||
|
||||
test('an explicit 400 rejection renders an unsuccessful draft without a running status', async () => {
|
||||
const ui=fixture({startAnalysisTurn:async()=>{throw Object.assign(new Error('invalid question'),{status:400});}});
|
||||
await ui.submit('rejected question');
|
||||
assert.equal(ui.get().attempt,null);
|
||||
const html=renderDraft(ui.get().lastTurn);
|
||||
assert.match(html,/本次提交未成功,请检查错误提示后重试/);
|
||||
assert.doesNotMatch(html,/排队中|正在准备分析|仍在运行|恢复原任务/);
|
||||
assert.equal(ui.get().lastTurn.status,undefined);
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { effectiveThinkingEffort, supportsThinkingEffort } from '../src/analysisThinking.ts';
|
||||
test('MiMo V2.6 exposes its binary thinking capability without fictitious strength tiers', () => {
|
||||
for (const model of ['mimo-v2.6-flash', 'MiMo-V2.6-Pro']) {
|
||||
assert.equal(supportsThinkingEffort(model), false);
|
||||
assert.equal(effectiveThinkingEffort(model, 'high'), 'auto');
|
||||
}
|
||||
});
|
||||
test('Qwen keeps independently saved effort while new or unknown models retain current compatibility', () => {
|
||||
assert.equal(supportsThinkingEffort('qwen3.8-27b-local'), true);
|
||||
assert.equal(effectiveThinkingEffort('qwen3.8-27b-local', 'low'), 'low');
|
||||
assert.equal(effectiveThinkingEffort('another-model', undefined), 'medium');
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import ts from 'typescript';
|
||||
const compile=path=>ts.transpileModule(fs.readFileSync(new URL(path,import.meta.url),'utf8').replace(/^import .*;\n/gm,''),{compilerOptions:{module:ts.ModuleKind.ES2022,target:ts.ScriptTarget.ES2022}}).outputText.replace(/^export /gm,'');
|
||||
const snapshotBody=compile('../src/analysisSnapshot.ts'),hookBody=compile('../src/analysisVisualRecovery.ts');
|
||||
const saved=()=>({id:'turn1',status:'PARTIAL',question:'原问题',plan:{protocolVersion:1,attemptId:'attempt1',executionId:'exec1',revision:2,task:{kind:'metrics',trendRequired:true,visualPreference:'required'}},answer:'原答案',results:[{value:2}],visualState:'failed',visuals:[]});
|
||||
const complete=source=>({...structuredClone(source),status:'COMPLETED',visualState:'ready',visualRecovery:{complete:true},visuals:[{id:'chart1',series:[2]}]});
|
||||
const deferred=()=>{let resolve,reject;const promise=new Promise((r,j)=>{resolve=r;reject=j;});return{promise,resolve,reject};};
|
||||
const tick=()=>new Promise(r=>setImmediate(r));
|
||||
function fixture(request){let cursor=0,dirty=false,queue=[],source=saved(),value;const states=new Map(),refs=new Map(),effects=new Map(),calls={api:0,denied:0};
|
||||
const hooks={useState(initial){const i=cursor++;if(!states.has(i))states.set(i,initial);return[states.get(i),next=>{states.set(i,next);dirty=true;}];},useRef(initial){const i=cursor++;if(!refs.has(i))refs.set(i,{current:initial});return refs.get(i);},useCallback(fn){cursor++;return fn;},useEffect(fn,deps){const i=cursor++,old=effects.get(i);if(!old||deps.some((d,j)=>!Object.is(d,old.deps[j])))queue.push(()=>{old?.cleanup?.();effects.set(i,{deps,cleanup:fn()});});}};
|
||||
const api={recoverAnalysisVisuals:async id=>{calls.api++;assert.equal(id,source.id);return request();}};
|
||||
// Separate modules retain their own helper bindings just as in production.
|
||||
const snapshot=new Function('api',snapshotBody+';return {analysisSnapshotResult,reportSnapshotDifferences,reportSnapshotIdentity};')(api);
|
||||
const useHook=new Function('api','snapshot','hooks',`const {analysisSnapshotResult,reportSnapshotDifferences,reportSnapshotIdentity}=snapshot;const {useState,useEffect,useRef,useCallback}=hooks;${hookBody};return useAnalysisVisualRecovery;`)(api,snapshot,hooks);
|
||||
const denied=error=>{if(error.message==='DENIED'){calls.denied++;return true;}return false;};
|
||||
const render=()=>{let n=0;do{dirty=false;queue=[];cursor=0;value=useHook(source,denied);queue.forEach(fn=>fn());if(++n>15)throw Error('render loop');}while(dirty);return value;};
|
||||
return{calls,render,get value(){return value;},get source(){return source;},replace(next){source=next;return render();},async settle(){await tick();return render();},unmount(){effects.forEach(e=>e.cleanup?.());}};
|
||||
}
|
||||
// Resolve its imported snapshot helper explicitly.
|
||||
const snapshot=new Function('api',snapshotBody+';return {analysisSnapshotResult};')({});
|
||||
const canRecover=new Function('analysisSnapshotResult',hookBody.slice(0,hookBody.indexOf('/**'))+';return canRecoverAnalysisVisuals;')(snapshot.analysisSnapshotResult);
|
||||
test('only a saved protocol task requesting a chart offers recovery',()=>{assert.equal(canRecover(saved()),true);for(const source of [{...saved(),status:'RUNNING'},{...saved(),plan:{...saved().plan,protocolVersion:0}},{...saved(),plan:{...saved().plan,task:{...saved().plan.task,visualPreference:'none'}}},{...complete(saved())}])assert.equal(canRecover(source),false);});
|
||||
test('a duplicate click recovers only charts and retains facts',async()=>{const response=deferred(),ui=fixture(()=>response.promise);ui.render();const a=ui.value.recover(),b=ui.value.recover();ui.render();assert.equal(ui.calls.api,1);response.resolve(complete(ui.source));await Promise.all([a,b]);await ui.settle();assert.equal(ui.value.turn.status,'COMPLETED');assert.equal(ui.value.turn.answer,'原答案');assert.equal(ui.value.available,false);ui.unmount();});
|
||||
test('a changed fact, source execution, or returned turn is rejected',async()=>{for(const change of [v=>({...v,answer:'换了答案'}),v=>({...v,id:'turn2'}),v=>({...v,plan:{...v.plan,executionId:'exec2'}})]){let ui;ui=fixture(async()=>change(complete(ui.source)));ui.render();await ui.value.recover();await ui.settle();assert.equal(ui.value.turn.status,'PARTIAL');assert.match(ui.value.error,/原分析已变化/);ui.unmount();}});
|
||||
test('late recovery cannot overwrite a changed revision or an unmounted view',async()=>{const response=deferred(),ui=fixture(()=>response.promise);ui.render();const before=structuredClone(ui.source),request=ui.value.recover();ui.replace({...before,plan:{...before.plan,revision:3},answer:'新答案'});response.resolve(complete(before));await request;await ui.settle();assert.equal(ui.value.turn.answer,'新答案');assert.equal(ui.value.turn.status,'PARTIAL');ui.unmount();});
|
||||
test('failure retains the saved answer and permission errors reach the access handler',async()=>{for(const message of ['暂时失败','DENIED']){const ui=fixture(async()=>{throw Error(message);});ui.render();await ui.value.recover();await ui.settle();assert.equal(ui.value.turn.answer,'原答案');assert.equal(ui.value.turn.status,'PARTIAL');assert.equal(ui.calls.denied,message==='DENIED'?1:0);if(message!=='DENIED')assert.equal(ui.value.error,message);ui.unmount();}});
|
||||
@@ -0,0 +1,87 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import ts from 'typescript';
|
||||
import React from 'react';
|
||||
|
||||
const tick = () => new Promise(resolve => setImmediate(resolve));
|
||||
const deferred = () => { let resolve, reject; const promise = new Promise((r,j) => { resolve=r; reject=j; }); return {promise,resolve,reject}; };
|
||||
const text = tree => typeof tree === 'string' ? tree : !tree || typeof tree !== 'object' ? '' : React.Children.toArray(tree.props?.children).map(text).join('');
|
||||
const find = (tree, predicate) => {
|
||||
if (!tree || typeof tree !== 'object') return;
|
||||
if (tree.type === 'Modal' && !tree.props.open) return;
|
||||
if (predicate(tree)) return tree;
|
||||
for (const child of React.Children.toArray(tree.props?.children)) { const hit=find(child,predicate); if(hit)return hit; }
|
||||
};
|
||||
const visual = () => ({ id:'same-id',title:'正式趋势',subtitle:'已核实数据',chartable:true,type:'line',metric:'composite_rate',
|
||||
period:{year:2026,monthStart:8,monthEnd:9},scope:{product:'原规格'},categories:[{key:'2026-08'},{key:'2026-09'}],
|
||||
series:[{key:'composite_rate',label:'合格率',values:[.82,.84]}],evidenceRefs:['QFIXTURE'],coverage:{totalRows:2,returnedRows:2,truncated:false} });
|
||||
|
||||
// Run the actual component, attaching host refs before its actual effect callbacks.
|
||||
function fixture({ authorize=async()=>{}, load }={}) {
|
||||
const states=new Map(),refs=new Map(),effects=new Map(),nodes=new Map();let cursor=0,dirty=false,queued=[],tree,attached=new Set();
|
||||
const calls={loads:0,authorization:0,disposed:0,options:[]};
|
||||
const runtime={init:()=>({setOption(option){calls.options.push(option);},resize(){},dispose(){calls.disposed++;}})};
|
||||
const hooks={
|
||||
useState(initial){const i=cursor++;if(!states.has(i))states.set(i,typeof initial==='function'?initial():initial);return [states.get(i),value=>{const next=typeof value==='function'?value(states.get(i)):value;if(!Object.is(next,states.get(i))){states.set(i,next);dirty=true;}}];},
|
||||
useRef(initial){const i=cursor++;if(!refs.has(i))refs.set(i,{current:initial});return refs.get(i);},
|
||||
useCallback(fn){cursor++;return fn;},
|
||||
useEffect(fn,deps){const i=cursor++,old=effects.get(i);if(!old||deps.some((d,j)=>!Object.is(d,old.deps[j])))queued.push(()=>{old?.cleanup?.();effects.set(i,{deps,cleanup:fn()});});},
|
||||
};
|
||||
const source=fs.readFileSync(new URL('../src/AnalysisVisuals.tsx',import.meta.url),'utf8');
|
||||
const componentSource=source.slice(source.indexOf('export function AnalysisVisualCard('),source.indexOf('export function AnalysisVisuals(')).replace('export function','function');
|
||||
const body=ts.transpileModule(componentSource,{fileName:'component.tsx',compilerOptions:{target:ts.ScriptTarget.ES2022,jsx:ts.JsxEmit.React}}).outputText;
|
||||
const Component=new Function('React','hooks','runtime',`
|
||||
const {useState,useRef,useEffect,useCallback}=hooks;
|
||||
const Button='Button',Dropdown='Dropdown',Tag='Tag',Modal='Modal',TableOutlined='TableOutlined',DownloadOutlined='DownloadOutlined',MoreOutlined='MoreOutlined',ChartDataTable='ChartDataTable';
|
||||
const document={visibilityState:'visible',documentElement:{},addEventListener(){},removeEventListener(){}};
|
||||
const documentIsHidden=()=>false,visualTheme=()=>({}),visualPeriodSummary=()=>'',visualScopeSummary=()=>'',chartSummary=v=>v.title,analysisVisualTypeLabel=()=>'',visualUnitLabel=()=>'';
|
||||
const buildAnalysisVisualOption=v=>structuredClone({scope:v.scope,series:v.series}),renderVisualPng=()=>{throw Error('unexpected export');},safeFilename=()=>'';
|
||||
const loadAnalysisVisualECharts=async()=>runtime,requestAnimationFrame=fn=>fn();
|
||||
class IntersectionObserver {constructor(fn){this.fn=fn;}observe(){this.fn([{isIntersecting:true}]);}disconnect(){}}
|
||||
class ResizeObserver {observe(){}disconnect(){}}
|
||||
class MutationObserver {observe(){}disconnect(){}}
|
||||
${body}
|
||||
return AnalysisVisualCard;
|
||||
`)(React,hooks,runtime);
|
||||
const props={visual:visual(),beforeExport:async()=>{calls.authorization++;return authorize();},loadRuntime:async()=>{
|
||||
calls.loads++;if(load)return load(calls.loads,runtime);if(calls.loads===1)throw Error('render failed');return runtime;
|
||||
}};
|
||||
function render(){let n=0;do{
|
||||
dirty=false;cursor=0;queued=[];tree=Component(props);
|
||||
const next=new Set();const attach=node=>{if(!node||typeof node!=='object')return;const ref=node.props?.ref;if(ref){next.add(ref);if(!nodes.has(ref))nodes.set(ref,{getBoundingClientRect:()=>({width:800,height:320})});ref.current=nodes.get(ref);}React.Children.toArray(node.props?.children).forEach(attach);};attach(tree);
|
||||
attached.forEach(ref=>{if(!next.has(ref))ref.current=null;});attached=next;queued.forEach(fn=>fn());
|
||||
if(++n>20)throw Error('render loop');
|
||||
}while(dirty);return tree;}
|
||||
return {props,calls,render,async settle(){await tick();return render();},retry(){const button=find(tree,node=>node.type==='Button'&&text(node)==='重试图表');assert.ok(button,'retry button');button.props.onClick({stopPropagation(){}});},unmount(){effects.forEach(effect=>effect.cleanup?.());attached.forEach(ref=>ref.current=null);}};
|
||||
}
|
||||
|
||||
test('a chart-only retry reauthorizes once, keeps the data table, and remounts the same verified values',async()=>{
|
||||
const auth=deferred(),ui=fixture({authorize:()=>auth.promise});ui.render();let tree=await ui.settle();
|
||||
assert.ok(find(tree,node=>node.type==='ChartDataTable'));assert.equal(ui.calls.loads,1);
|
||||
ui.retry();ui.retry();tree=ui.render();assert.equal(ui.calls.authorization,1);assert.equal(ui.calls.loads,1);
|
||||
assert.ok(find(tree,node=>node.type==='ChartDataTable'));
|
||||
auth.resolve();await ui.settle();tree=await ui.settle();assert.equal(ui.calls.loads,2);
|
||||
assert.equal(find(tree,node=>node.type==='ChartDataTable'),undefined);assert.deepEqual(ui.calls.options.at(-1).series[0].values,[.82,.84]);ui.unmount();
|
||||
});
|
||||
|
||||
test('failed authorization hides cached data and never retries the renderer until access is restored',async()=>{
|
||||
let denied=true;const ui=fixture({authorize:async()=>{if(denied)throw Error('无权读取');}});ui.render();await ui.settle();ui.retry();let tree=await ui.settle();
|
||||
assert.match(text(tree),/无权读取/);assert.equal(find(tree,node=>node.type==='ChartDataTable'),undefined);assert.equal(ui.calls.loads,1);
|
||||
denied=false;ui.retry();await ui.settle();tree=await ui.settle();assert.equal(ui.calls.loads,2);assert.doesNotMatch(text(tree),/无权读取/);ui.unmount();
|
||||
});
|
||||
|
||||
test('late authorization for an older snapshot cannot remount or overwrite a changed scope with the same visual id',async()=>{
|
||||
const auth=deferred(),ui=fixture({authorize:()=>auth.promise});ui.render();await ui.settle();ui.retry();
|
||||
ui.props.visual={...visual(),scope:{product:'新规格'},series:[{key:'composite_rate',values:[.91,.93]}]};ui.render();await ui.settle();const loads=ui.calls.loads;
|
||||
auth.resolve();await ui.settle();assert.equal(ui.calls.loads,loads);assert.equal(ui.calls.options.at(-1).scope.product,'新规格');assert.deepEqual(ui.calls.options.at(-1).series[0].values,[.91,.93]);ui.unmount();
|
||||
});
|
||||
|
||||
test('unmounting while authorization is pending prevents a late renderer start',async()=>{
|
||||
const auth=deferred(),ui=fixture({authorize:()=>auth.promise});ui.render();await ui.settle();ui.retry();ui.unmount();auth.resolve();await tick();assert.equal(ui.calls.loads,1);
|
||||
});
|
||||
|
||||
test('switching snapshots clears the previous permission error and closes its data dialog',async()=>{
|
||||
const ui=fixture({authorize:async()=>{throw Error('旧结果无权读取');}});ui.render();await ui.settle();ui.retry();let tree=await ui.settle();assert.match(text(tree),/旧结果无权读取/);
|
||||
ui.props.visual={...visual(),scope:{product:'新结果'}};ui.render();tree=await ui.settle();assert.doesNotMatch(text(tree),/旧结果无权读取/);assert.equal(ui.calls.options.at(-1).scope.product,'新结果');ui.unmount();
|
||||
});
|
||||
@@ -10,7 +10,11 @@ import {
|
||||
visualCategoryLabel,
|
||||
visualDonutShares,
|
||||
visualParetoPoints,
|
||||
columnFilterSummary,
|
||||
visualScopeSummary,
|
||||
visualUnitLabel,
|
||||
} from '../src/analysisVisualsModel.ts';
|
||||
import { buildAnalysisNarrative } from '../src/analysisReportModel.ts';
|
||||
|
||||
function visual(overrides = {}) {
|
||||
return {
|
||||
@@ -84,6 +88,64 @@ function waterfall(overrides = {}) {
|
||||
});
|
||||
}
|
||||
|
||||
function scrapRate(stage = 'black', values = [0.82, 0.84], overrides = {}) {
|
||||
const metric = `${stage}_scrap_rate`;
|
||||
const weight = `${stage}_scrap_weight`;
|
||||
const total = `${stage}_total_weight`;
|
||||
return visual({
|
||||
title: `${stage === 'black' ? '黑片' : '亮片'}正式报废率`, subtitle: '正式报废重量÷投入重量',
|
||||
unit: 'ratio', stage, metric,
|
||||
requiredFields: [weight, total], scope: { department: '工业电机', stage },
|
||||
series: [{ key: metric, label: '报废率', values }],
|
||||
...overrides,
|
||||
});
|
||||
}
|
||||
|
||||
test('Top product Pareto uses all-product total and does not force the last share to 100%', () => {
|
||||
const input = pareto({metric:'bright_total_weight',stage:'bright',dimension:'product',
|
||||
requiredFields:['bright_total_weight'],comparisonPeriod:undefined,
|
||||
categories:[{key:'p1',label:'A'},{key:'p2',label:'B'}],
|
||||
series:[{key:'bright_total_weight',label:'亮片投入重量',values:[80,60]}],
|
||||
coverage:{totalRows:3,returnedRows:2,truncated:true,shareBasis:'all_scope_weight',denominator:150}});
|
||||
const model = parseAnalysisVisuals([input]).visuals[0];
|
||||
assert.equal(model.chartable,true);
|
||||
const points = visualParetoPoints(model);
|
||||
assert.equal(points[0].share,80/150);
|
||||
assert.equal(points[1].cumulativeShare,140/150);
|
||||
assert.ok(points[1].cumulativeShare<1);
|
||||
const option = buildAnalysisVisualOption(model);
|
||||
assert.equal(option.series[1].name,'累计占全部重量');
|
||||
for (const denominator of [0,-1,100,NaN]) {
|
||||
const invalid=parseAnalysisVisuals([{...input,coverage:{...input.coverage,denominator}}]);
|
||||
assert.ok(!invalid.visuals.length || !invalid.visuals[0].chartable);
|
||||
}
|
||||
});
|
||||
|
||||
test('weight ranking export retains the all-scope denominator label and readable full product names', () => {
|
||||
const names=Array.from({length:10},(_,i)=>`52HR-L0.385XR26.46XR26.46X2.888+R+Z-${i}`);
|
||||
const input=pareto({metric:'bright_total_weight',stage:'bright',dimension:'product',requiredFields:['bright_total_weight'],comparisonPeriod:undefined,
|
||||
categories:names.map((label,i)=>({key:'p'+i,label})),series:[{key:'bright_total_weight',label:'亮片投入重量',values:[100,90,80,70,60,50,40,30,20,10]}],
|
||||
coverage:{totalRows:20,returnedRows:10,truncated:true,shareBasis:'all_scope_weight',denominator:1000}});
|
||||
const model=parseAnalysisVisuals([input]).visuals[0];
|
||||
const live=buildAnalysisVisualOption(model);
|
||||
assert.equal(live.yAxis[1].name,'累计占全部重量');
|
||||
const report=buildAnalysisVisualExportOption(model,900,'report').option;
|
||||
assert.equal(report.legend.data[1],'累计占全部重量');
|
||||
assert.equal(report.yAxis[1].name,'累计占全部重量');
|
||||
assert.deepEqual(report.xAxis.data.map(name=>name.replaceAll('\n','')),names);
|
||||
assert.equal(report.xAxis.axisLabel.rotate,0);
|
||||
assert.ok(report.grid.height>=240);
|
||||
assert.equal(report.series[1].label.formatter({dataIndex:9,data:55}),'55%');
|
||||
assert.deepEqual(report.series[0].data,input.series[0].values);
|
||||
});
|
||||
|
||||
test('historical stage decomposition labels omit the requested wording', () => {
|
||||
const model=parseAnalysisVisuals([waterfall({title:'综合率变化的数学影响拆解',
|
||||
categories:[{key:'black',label:'黑片数学影响'},{key:'bright',label:'亮片数学影响'},{key:'total',label:'合计'}]})]).visuals[0];
|
||||
assert.equal(model.title,'综合率变化的影响拆解');
|
||||
assert.equal(model.categories[0].label,'黑片影响');
|
||||
});
|
||||
|
||||
test('parser preserves zero and null as different values', () => {
|
||||
const parsed = parseAnalysisVisuals([visual({ series: [{ key: 'a', label: 'A', values: [null, 0] }] })]);
|
||||
assert.equal(parsed.visuals.length, 1);
|
||||
@@ -135,6 +197,40 @@ test('ratio charts use 0 to 100 percent and convert raw ratios only for plotting
|
||||
assert.equal(formatVisualValue(0.8425, 'ratio'), '84.25%');
|
||||
});
|
||||
|
||||
test('stage scrap rates preserve values above 100 percent and expand every ratio value axis', () => {
|
||||
for (const stage of ['black', 'bright']) {
|
||||
const parsed = parseAnalysisVisuals([scrapRate(stage, [1.23, 0.94])]);
|
||||
assert.equal(parsed.visuals[0].chartable, true);
|
||||
assert.deepEqual(parsed.visuals[0].series[0].values, [1.23, 0.94]);
|
||||
assert.equal(buildAnalysisVisualOption(parsed.visuals[0]).series[0].data[0], 123);
|
||||
assert.ok(buildAnalysisVisualOption(parsed.visuals[0]).yAxis.max > 123);
|
||||
assert.ok(buildAnalysisVisualExportOption(parsed.visuals[0], 1280, 'standalone').option.yAxis.max > 123);
|
||||
assert.ok(buildAnalysisVisualExportOption(parsed.visuals[0], 1280, 'report').option.yAxis.max > 123);
|
||||
assert.equal(formatVisualValue(1.23, 'ratio'), '123%');
|
||||
}
|
||||
const horizontal = parseAnalysisVisuals([scrapRate('black', [1.23, 0.94], { type: 'bar' })]).visuals[0];
|
||||
assert.ok(buildAnalysisVisualOption(horizontal).xAxis.max > 123);
|
||||
assert.ok(buildAnalysisVisualExportOption(horizontal, 1280, 'report').option.xAxis.max > 123);
|
||||
|
||||
const below100 = parseAnalysisVisuals([scrapRate('black', [0.91, 0.84])]).visuals[0];
|
||||
assert.equal(buildAnalysisVisualOption(below100).yAxis.max, 100);
|
||||
assert.equal(buildAnalysisVisualExportOption(below100, 1280, 'report').option.yAxis.max, 100);
|
||||
});
|
||||
|
||||
test('only correctly declared stage scrap-rate metrics accept above-one ratios', () => {
|
||||
for (const input of [
|
||||
visual({ series: [{ key: 'r', label: '率', values: [1.02, null] }] }),
|
||||
scrapRate('black', [1.02, 0.8], { requiredFields: ['bright_scrap_weight', 'bright_total_weight'] }),
|
||||
scrapRate('black', [1.02, 0.8], { unit: 'kg' }),
|
||||
]) {
|
||||
const parsed = parseAnalysisVisuals([input]).visuals[0];
|
||||
assert.equal(parsed.chartable, false);
|
||||
}
|
||||
const negative = parseAnalysisVisuals([scrapRate('bright', [-0.01, 1.02])]).visuals[0];
|
||||
assert.equal(negative.chartable, false);
|
||||
assert.deepEqual(negative.invalidValueCells, ['0:0']);
|
||||
});
|
||||
|
||||
test('empty subtitle and extra-filter maps survive strict parsing', () => {
|
||||
const parsed = parseAnalysisVisuals([visual({ subtitle: ' ', scope: { extraFilters: { quality_type: ['A级', 'B级'] } } })]);
|
||||
assert.equal(parsed.visuals.length, 1);
|
||||
@@ -628,7 +724,8 @@ test('waterfall validates authorized inputs and renders signed stages from a zer
|
||||
const exported = buildAnalysisVisualExportOption(model, 1280, 'report');
|
||||
assert.equal(exported.option.title.show, false);
|
||||
assert.equal(exported.option.legend.show, false);
|
||||
assert.match(exported.option.graphic.elements[0].style.text, /数学拆解/);
|
||||
assert.match(exported.option.graphic.elements[0].style.text, /拆解/);
|
||||
assert.doesNotMatch(exported.option.graphic.elements[0].style.text, /数学/);
|
||||
assert.match(exported.option.graphic.elements[0].style.text, /不代表生产根因/);
|
||||
assert.equal(exported.option.yAxis.name, '变化(百分点)');
|
||||
assert.ok(exported.height < 440);
|
||||
@@ -724,3 +821,73 @@ test('report export fully wraps long donut, Pareto, and trend category names', (
|
||||
assert.ok(trendExport.option.xAxis.data[0].replaceAll('\n', '').includes(longName));
|
||||
assert.equal(trendExport.option.xAxis.axisLabel.hideOverlap, false);
|
||||
});
|
||||
|
||||
|
||||
test('source column filters preserve stage and literal values in chart scope', () => {
|
||||
const rule={field:'src_any',stages:['bright'],operator:'in',values:['000123']};
|
||||
const value=visual({scope:{columnFilters:[rule],columnLabels:{src_any:'任意业务列'}}});
|
||||
const parsed=parseAnalysisVisuals([value]);
|
||||
assert.equal(parsed.visuals.length,1);
|
||||
assert.deepEqual(parsed.visuals[0].scope.columnFilters,[rule]);
|
||||
assert.deepEqual(columnFilterSummary(parsed.visuals[0].scope.columnFilters,parsed.visuals[0].scope.columnLabels),['亮片 任意业务列为000123']);
|
||||
assert.equal(parseAnalysisVisuals([visual({scope:{columnFilters:[{...rule,stages:['other']}]}})]).visuals.length,0);
|
||||
});
|
||||
|
||||
test('canonical exclusions and source-column not-in filters survive chart, report, and HTML export context', () => {
|
||||
const scope = {
|
||||
exclusions: { product: ['MIMO-V14', ' 保留空格 '], group: ['海外组'] },
|
||||
columnFilters: [{ field: 'customerCode', stages: ['black', 'bright'], operator: 'not_in', values: ['000123', 'C-09'] }],
|
||||
columnLabels: { customerCode: '客户代码' },
|
||||
extraFilters: { factory: ['一厂'] },
|
||||
};
|
||||
const parsed = parseAnalysisVisuals([visual({ scope })]);
|
||||
assert.equal(parsed.visuals.length, 1);
|
||||
const chart = parsed.visuals[0];
|
||||
assert.deepEqual(chart.scope.exclusions, scope.exclusions);
|
||||
assert.deepEqual(chart.scope.columnFilters, scope.columnFilters);
|
||||
|
||||
const summary = visualScopeSummary(chart.scope);
|
||||
assert.match(summary, /排除业务分组:海外组/);
|
||||
assert.match(summary, /排除产品:MIMO-V14、 保留空格 /);
|
||||
assert.match(summary, /黑片、亮片 客户代码排除000123、C-09/);
|
||||
assert.match(summary, /额外筛选 1 项/);
|
||||
assert.match(renderVisualTableHtml(chart), /排除产品:MIMO-V14、 保留空格 /);
|
||||
const report = buildAnalysisNarrative('', [chart]);
|
||||
assert.equal(report.scope, summary);
|
||||
assert.match(report.evidence[0].context, /黑片、亮片 客户代码排除000123、C-09/);
|
||||
});
|
||||
|
||||
test('visual parsing rejects malformed exclusions and malformed source-column filters', () => {
|
||||
for (const exclusions of [
|
||||
{ customerCode: ['000123'] },
|
||||
{ product: [] },
|
||||
{ group: [' '] },
|
||||
{ product: ['A', 4] },
|
||||
{ product: Array.from({ length: 51 }, (_, index) => `P${index}`) },
|
||||
]) {
|
||||
assert.equal(parseAnalysisVisuals([visual({ scope: { exclusions } })]).visuals.length, 0);
|
||||
}
|
||||
assert.equal(parseAnalysisVisuals([visual({ scope: { columnFilters: [{ field: 'customerCode', stages: ['black'], operator: 'not_in', values: [] }] } })]).visuals.length, 0);
|
||||
});
|
||||
|
||||
|
||||
test('scrap-rate data and export unit labels preserve the requested indicator', () => {
|
||||
const visual = { unit: 'ratio', metric: 'black_scrap_rate' };
|
||||
assert.equal(visualUnitLabel(visual), '报废率(%)');
|
||||
assert.equal(visualUnitLabel({ ...visual, metric: 'bright_scrap_rate' }), '报废率(%)');
|
||||
assert.equal(visualUnitLabel({ ...visual, metric: 'composite_rate' }), '合格率(%)');
|
||||
});
|
||||
|
||||
|
||||
test('low scrap-rate trends use a readable zero-based percentage axis without changing values', () => {
|
||||
const item = parseAnalysisVisuals([scrapRate('black', [.03657, .02995])]).visuals[0];
|
||||
const option = buildAnalysisVisualOption(item);
|
||||
assert.equal(option.yAxis.min, 0);
|
||||
assert.ok(option.yAxis.max > 3.657 && option.yAxis.max < 20);
|
||||
assert.deepEqual(item.series[0].values, [.03657, .02995]);
|
||||
assert.equal(buildAnalysisVisualExportOption(item, 1280, 'report').option.yAxis.max, option.yAxis.max);
|
||||
const zero = parseAnalysisVisuals([scrapRate('bright', [0, 0])]).visuals[0];
|
||||
assert.ok(buildAnalysisVisualOption(zero).yAxis.max > 0);
|
||||
const goodRate = parseAnalysisVisuals([visual({ metric: 'black_rate', stage: 'black', requiredFields: ['black_good_weight', 'black_total_weight'], series: [{ key: 'black_rate', label: '黑片合格率', values: [.03657, .02995] }] })]).visuals[0];
|
||||
assert.equal(buildAnalysisVisualOption(goodRate).yAxis.max, 100);
|
||||
});
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
<!doctype html><html lang="zh-CN"><meta charset="UTF-8"><title>查询口径与明细预览(模拟数据)</title><div id="root"></div><script type="module" src="./business-query.tsx"></script></html>
|
||||
@@ -0,0 +1,28 @@
|
||||
// Isolated browser acceptance with simulated data; never calls the business API.
|
||||
const stage = { qualifiedWeight: 42243.6, scrapWeight: 372.2, totalWeight: 42615.8, rate: .991265, headquartersScrapWeight: 25.6, rateWithoutHeadquartersScrap: .9918, defects: [{ name: '裂纹', weight: 230.1, rate: .0054 }, { name: '缺角', weight: 142.1, rate: .0033 }] };
|
||||
const products = ['62.8X36.8X51', '30X8.4X1.6+T', '16.33X15.5X3.75+T', ...Array.from({length:15},(_,i)=>`产品规格-${i+4}`)];
|
||||
const rows = products.map((product,i)=>({ key: String(i), label: product, department:'工业电机产业部', group:'工业电机-VCM', product, compositeRate:.9751,black:{...stage,qualifiedWeight:38582.1},bright:stage,coverage:{blackRows:5,brightRows:5} }));
|
||||
const json = (value: unknown) => new Response(JSON.stringify(value), {headers:{'Content-Type':'application/json'}});
|
||||
window.fetch = async (target) => {
|
||||
const url = new URL(String(target), location.origin);
|
||||
if(url.pathname==='/api/auth/me')return json({user:{id:'local-fixture',username:'admin',displayName:'admin',roles:['SYSTEM_ADMIN'],departments:[],groups:[]}});
|
||||
if(url.pathname==='/api/workspace/state')return json({authRevision:'fixture',dataRevision:'fixture'});
|
||||
if(url.pathname==='/api/options')return json({years:[2026],departments:['工业电机产业部'],groups:['工业电机-VCM'],groupDepartments:{'工业电机-VCM':'工业电机产业部'},products,projectGroupStatus:'READY',projectGroups:[],releases:[{id:'fixture-release',name:'本地验收',status:'PUBLISHED'}]});
|
||||
if(url.pathname==='/api/filter-fields')return json([]);
|
||||
if(url.pathname==='/api/metrics') {
|
||||
const view=url.searchParams.get('view');
|
||||
const product=url.searchParams.get('product');
|
||||
let visible=product?rows.filter(r=>r.product===product):rows;
|
||||
if(view==='department')visible=[{...rows[0],key:'工业电机产业部',label:'工业电机产业部'}];
|
||||
if(view==='group')visible=[{...rows[0],key:'工业电机-VCM',label:'工业电机-VCM'}];
|
||||
return json({release:{id:'fixture-release',name:'本地验收',status:'PUBLISHED'},context:{metricFormulaDescriptions:{blackRate:'blackGood / blackTotal;运算空值=PROPAGATE;零分母=ONE;空结果=ONE',brightRate:'brightGood / (brightGood + brightScrap);运算空值=PROPAGATE;零分母=ONE;空结果=ONE',compositeRate:'blackRate * brightRate;运算空值=PROPAGATE;零分母=ONE;空结果=NULL',brightRateWithoutHeadquartersScrap:'(brightGood + headquartersScrap) / brightTotal;运算空值=PROPAGATE;零分母=NULL;空结果=NULL',compositeRateWithoutHeadquartersScrap:'blackRate * brightRateWithoutHeadquartersScrap;运算空值=PROPAGATE;零分母=ONE;空结果=NULL'}},summary:rows[0],rows:visible,trend:Array.from({length:9},(_,i)=>({...rows[0],key:`month-${i+1}`,month:i+1,period:`2026-${String(i+1).padStart(2,'0')}`})),defects:{black:stage.defects,bright:stage.defects},coverage:{sourceMonths:[{year:2026,month:9,blackRows:90,brightRows:90}],rawRows:180,includedRows:180,excludedBlankRows:0,unmappedRows:0,projectGroupUnconfiguredRows:0,missingStages:[]}});
|
||||
}
|
||||
if(url.pathname==='/api/analysis/defects')return json({rows:[],kind:'fine_defect_top',sourceRows:0,releaseId:'fixture-release'});
|
||||
if(url.pathname==='/api/records')return json({rows:[{id:'fixture-1',month:9,raw:{'产品规格':products[0],'重量':42},normalized:{qualifiedWeight:42,scrapWeight:0,totalWeight:42},components:{black_good_weight:42,black_scrap_weight:0,black_total_weight:42}}],page:1,pageSize:20,total:1});
|
||||
return json({items:[]});
|
||||
};
|
||||
const originalGet = Storage.prototype.getItem;
|
||||
const originalSet = Storage.prototype.setItem;
|
||||
Storage.prototype.getItem = function(key) { return key === 'quality-workbench-theme' ? 'light' : originalGet.call(this, key); };
|
||||
Storage.prototype.setItem = function(key, value) { if(key !== 'quality-workbench-theme') originalSet.call(this, key, value); };
|
||||
await import('../src/main');
|
||||
@@ -0,0 +1,40 @@
|
||||
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 { isInternalDataField, readableMetricFormula, readableRuleDescription } from '../src/publicDataDisplay.ts';
|
||||
const source = fs.readFileSync(new URL('../src/BusinessValue.tsx', import.meta.url), 'utf8').replace(/^import .*\n/gm, '').replace(/export /g, '');
|
||||
const code = ts.transpileModule(source, {compilerOptions:{jsx:ts.JsxEmit.React,target:ts.ScriptTarget.ES2022}}).outputText;
|
||||
const {BusinessValue,currentMetricFormula} = new Function('React','isInternalDataField','readableMetricFormula',code+';return {BusinessValue,currentMetricFormula};')(React,isInternalDataField,readableMetricFormula);
|
||||
test('current formula and nondefault policies take priority over reference text',()=>{
|
||||
const row=Object.freeze({formula:'REFERENCE',formulaStatus:'CURRENT',currentFormula:'blackGood / (blackTotal + 7);运算空值=ZERO;零分母=ZERO;空结果=NULL'});
|
||||
assert.equal(currentMetricFormula(row),'黑片合格重量 ÷ (黑片总重量 + 7);运算中遇到空值:按0处理;分母为0:取0;计算结果为空:保留空值');
|
||||
});
|
||||
test('missing current formula never silently uses a reference formula',()=>{
|
||||
for(const row of [{formula:'REFERENCE'}, {formula:'REFERENCE',formulaStatus:'CURRENT',currentFormula:''}]) {
|
||||
assert.match(currentMetricFormula(row),/暂不可用/); assert.doesNotMatch(currentMetricFormula(row),/REFERENCE/);
|
||||
}
|
||||
assert.equal(currentMetricFormula({formulaStatus:'NO_CURRENT_DATA',formula:'REFERENCE'}),'暂无已生效数据');
|
||||
});
|
||||
test('Chinese rule details hide metadata and translate status and policies',()=>{
|
||||
const value=Object.freeze({schemaVersion:'private',metricRules:{blackRate:{formula:'blackGood / blackTotal',zeroDenominatorPolicy:'ONE'}},enabled:true});
|
||||
const html=renderToStaticMarkup(React.createElement(BusinessValue,{value}));
|
||||
assert.match(html,/黑片合格率/);assert.match(html,/返回1/);assert.match(html,/已启用/);assert.doesNotMatch(html,/private|schemaVersion|zeroDenominatorPolicy|true/);
|
||||
});
|
||||
test('original source strings are preserved, including slashes and formulas as data',()=>{
|
||||
const html=renderToStaticMarkup(React.createElement(BusinessValue,{value:{'产品':'A/B','备注':'blackGood / blackTotal'}}));
|
||||
assert.match(html,/A\/B/);assert.match(html,/blackGood \/ blackTotal/);
|
||||
});
|
||||
|
||||
test('seeded technical descriptions are displayed as business wording while custom descriptions remain intact',()=>{
|
||||
assert.equal(readableRuleDescription('保留原 PQ / PP 计算口径,后续可直接维护字段、逐行公式和指标公式。'),'可维护来源字段、逐行计算和指标公式。');
|
||||
assert.equal(readableRuleDescription('保留原模型本部报废调整版本,不改变默认正式亮片率。'),'将本部报废重量计入亮片合格重量,总重量不变。');
|
||||
assert.equal(readableRuleDescription('自定义业务说明'),'自定义业务说明');
|
||||
});
|
||||
|
||||
test('real source mapping states are translated without changing source codes',()=>{
|
||||
const html=renderToStaticMarkup(React.createElement(BusinessValue,{value:{projectGroupStatus:'mapped_null',categoryMappingStatus:'mapped',sourcePdtCode:'P008'}}));
|
||||
assert.match(html,/已匹配(归属为空)/); assert.match(html,/已匹配/);assert.match(html,/P008/);assert.doesNotMatch(html,/mapped_null/);
|
||||
});
|
||||
@@ -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>图表独立重试验收</title></head><body><div id="root"></div><script type="module" src="./chart-retry.tsx"></script></body></html>
|
||||
@@ -0,0 +1,47 @@
|
||||
// Local rendering fixture only: no model or business query calls.
|
||||
import React, { useCallback, useRef, useState } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { AnalysisVisualCard } from '../src/AnalysisVisuals';
|
||||
import { loadAnalysisVisualECharts, parseAnalysisVisuals } from '../src/analysisVisualsModel';
|
||||
import '../src/styles.css';
|
||||
|
||||
function Fixture() {
|
||||
const [version, setVersion] = useState(1);
|
||||
const [denied, setDenied] = useState(false);
|
||||
const [delay, setDelay] = useState(false);
|
||||
const [checks, setChecks] = useState(0);
|
||||
const [loads, setLoads] = useState(0);
|
||||
const failNext = useRef(true);
|
||||
const deferred = useRef<(() => void) | undefined>(undefined);
|
||||
const loadRuntime = useCallback(async () => {
|
||||
setLoads(value => value + 1);
|
||||
if (failNext.current) { failNext.current = false; throw new Error('isolated render failure'); }
|
||||
return loadAnalysisVisualECharts();
|
||||
}, []);
|
||||
const authorize = async () => {
|
||||
setChecks(value => value + 1);
|
||||
if (delay) await new Promise<void>(resolve => { deferred.current = resolve; });
|
||||
if (denied) throw new Error('当前无权读取此图表,已隐藏原数据。');
|
||||
};
|
||||
const visual = parseAnalysisVisuals([{
|
||||
id: `fixture-${version}`, type: 'line', title: `结果 ${version} 月度合格率`, subtitle: '本地渲染验收',
|
||||
unit: 'ratio', categories: [{ key: '2026-08', label: '2026-08' }, { key: '2026-09', label: '2026-09' }],
|
||||
series: [{ key: 'composite_rate', label: '综合合格率', values: version === 1 ? [0.82, 0.84] : [0.91, 0.93] }],
|
||||
evidenceRefs: ['QFIXTURE'], requiredFields: ['black_good_weight', 'black_total_weight', 'bright_good_weight', 'bright_total_weight'],
|
||||
scope: { releaseId: 'fixture-release', product: `规格-${version}` }, period: { year: 2026, monthStart: 8, monthEnd: 9 },
|
||||
metric: 'composite_rate', coverage: { totalRows: 2, returnedRows: 2, truncated: false }, originTurnId: `fixture-turn-${version}`,
|
||||
}], 1).visuals[0];
|
||||
return <main style={{ maxWidth: 1000, margin: 'auto', padding: 24 }}>
|
||||
<h1>图表独立重试验收</h1>
|
||||
<p>已核实结论:正文和原查询数据保留;本页面不调用模型或业务查询。</p>
|
||||
<div style={{ display: 'flex', gap: 12, marginBottom: 16 }}>
|
||||
<button onClick={() => { failNext.current = true; setVersion(value => value + 1); }}>切换结果并模拟失败</button>
|
||||
<label><input type="checkbox" checked={denied} onChange={event => setDenied(event.target.checked)} />拒绝访问</label>
|
||||
<label><input type="checkbox" checked={delay} onChange={event => setDelay(event.target.checked)} />延迟验证</label>
|
||||
<button onClick={() => { deferred.current?.(); deferred.current = undefined; }}>完成验证</button>
|
||||
</div>
|
||||
<p role="status">权限复核 {checks} 次;图表加载 {loads} 次;模型调用 0 次;业务查询 0 次。</p>
|
||||
{visual && <AnalysisVisualCard visual={visual} beforeExport={authorize} loadRuntime={loadRuntime} />}
|
||||
</main>;
|
||||
}
|
||||
createRoot(document.getElementById('root')!).render(<Fixture />);
|
||||
@@ -0,0 +1 @@
|
||||
<!doctype html><html lang="zh-CN"><meta charset="UTF-8"><title>配置页面预览(模拟数据)</title><div id="root"></div><script type="module" src="./configuration-pages.tsx"></script></html>
|
||||
@@ -0,0 +1,29 @@
|
||||
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/quality-table.css';
|
||||
const page=new URLSearchParams(location.search).get('page') as 'rules'|'mappings'|'masterData'|'tasks'|'access'|'sources' || 'rules';
|
||||
const longText='本条说明完整保留,按照当前生效规则先汇总同阶段的重量分量,再计算合格率;来源字段、扣减项目、空值处理和零分母处理均与当前查询一致。';
|
||||
const definition={schemaVersion:'preview',sourceFields:{},rowRules:[],metricRules:{},masterData:{departments:[],groups:[],products:[],projectGroups:[]}};
|
||||
const rule={id:'rule-preview',name:'原计算规则名称',status:'ACTIVE',createdAt:'2026-10-21T05:57:31Z',definition};
|
||||
const mapping={id:'mapping-preview',name:'原基础数据名称',status:'ACTIVE',createdAt:'2026-10-21T08:38:49Z',definition};
|
||||
const json=(value:unknown)=>new Response(JSON.stringify(value),{headers:{'Content-Type':'application/json'}});
|
||||
window.fetch=async target=>{
|
||||
const path=new URL(String(target),location.origin).pathname;
|
||||
if(path==='/api/filter-fields')return json(['客户代码','坯料生产单位'].map((label,index)=>({key:`preview_${index}`,label,blackColumn:label,brightColumn:label,enabled:true,allowEmpty:true,sortOrder:index})));
|
||||
if(path==='/api/filter-fields/columns')return json({black:['客户代码','坯料生产单位'],bright:['客户代码','坯料生产单位']});
|
||||
if(path==='/api/tasks/overview')return json({items:[{id:'task-1',sourceKind:'TASK',type:'IMPORT',status:'RUNNING',createdAt:'2026-10-30T00:00:00Z',processed:600,total:1000,progress:60},{id:'task-2',sourceKind:'TASK',type:'IMPORT',status:'FAILED',createdAt:'2026-10-29T23:00:00Z',errorMessage:longText}]});
|
||||
if(path==='/api/metric-dictionary')return json({items:['黑片合格率','亮片合格率','综合合格率'].map((name,index)=>({code:`METRIC_${index}`,name,description:index===1?'按当前范围计算':longText,unit:'RATE',dimensions:['期间','产业部','业务分组','产品','项目组'],enabled:true,formulaStatus:'CURRENT',currentFormula:'blackGood / blackTotal;运算空值=PROPAGATE;零分母=ONE;空结果=ONE',aliases:[]}))});
|
||||
if(path==='/api/sources/upload-options')return json({currentReleaseId:'preview',targets:[],fields:{black:[],bright:[]},scopes:['ALL'],currentSourceIds:['source-1','source-2'],currentSourcesComplete:true});
|
||||
if(path==='/api/sources')return json({items:[{id:'source-1',sourceFile:'2026年9月黑片质量数据汇总表_汽车交通产业部_完整来源及客户代码与检验备注.xlsx',stage:'black',year:2026,month:9,status:'IMPORTED',sizeBytes:123456},{id:'source-2',sourceFile:'2026年9月亮片.xlsx',stage:'bright',year:2026,month:9,status:'IMPORTED',sizeBytes:234567}]});
|
||||
if(path==='/api/releases')return json({items:[],currentReleaseId:'preview'});
|
||||
if(path==='/api/rules')return json({items:[rule]});
|
||||
if(path==='/api/mappings')return json({items:[mapping]});
|
||||
if(path==='/api/rules/schema')return json({schemaVersion:'preview',sourceFields:{black:{platingWeight:'送电镀重量',shipmentWeight:'黑片出货重量',responsibilityScrap:'责废总重量',materialScrap:'料废重量',externalScrap:'外废重量',issueLocation:'发料地点',inspectionNote:'检验备注'},bright:{goodWeight:'合格重量',scrapWeight:'检包入废品库重量'}},rowTargets:{},defaultDefinition:definition});
|
||||
if(path==='/api/data-workflow/status')return json({mode:'TEST',simplified:true,currentReleaseId:'preview',activeRule:rule,activeMapping:mapping,capabilities:{canApplyRule:true,canApplyMapping:true}});
|
||||
if(path.includes('reference'))return json({departments:[],groups:[],products:[],projectGroups:[],groupDepartments:{}});
|
||||
return json({items:[]});
|
||||
};
|
||||
createRoot(document.getElementById('root')!).render(<ConfigProvider><App><main className="app-shell" style={{padding:24,background:'#f2f7fb',minHeight:'100vh'}}><div className="page-view" data-page={page}><ManagementPages page={page} user={{id:'preview',username:'preview',roles:['SYSTEM_ADMIN'],departments:[],groups:[]}} onUnauthorized={()=>false} onNavigate={()=>{}} /></div></main></App></ConfigProvider>);
|
||||
@@ -0,0 +1,15 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { configurationDateTime, currentConfigurationName } from '../src/configurationName.ts';
|
||||
test('date names use Shanghai time rather than the device timezone',()=>{
|
||||
assert.equal(configurationDateTime('2026-12-31T16:00:00Z'),'2027-01-01 00:00:00');
|
||||
assert.equal(configurationDateTime('2026-10-21T05:57:31.164921Z'),'2026-10-21 13:57:31');
|
||||
});
|
||||
test('legacy configurations display their own creation time, not the current time',()=>{
|
||||
assert.equal(currentConfigurationName('原规则名称','2026-10-21T05:57:31Z'),'2026-10-21 13:57:31');
|
||||
assert.equal(currentConfigurationName('旧记录',undefined),'');
|
||||
assert.equal(configurationDateTime('invalid'),'');
|
||||
});
|
||||
test('the server generated date name stays stable when its creation time is a few seconds later',()=>{
|
||||
assert.equal(currentConfigurationName('2026-10-29 14:05:30','2026-10-29T06:05:35Z'),'2026-10-29 14:05:30');
|
||||
});
|
||||
@@ -0,0 +1,197 @@
|
||||
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 { freezeSourceRecordsQuery } from '../src/sourceRecordsContext.ts';
|
||||
|
||||
const read = name => fs.readFileSync(new URL(`../src/${name}`, import.meta.url), 'utf8');
|
||||
const transpile = body => ts.transpileModule(body, {fileName:'fixture.tsx',compilerOptions:{target:ts.ScriptTarget.ES2022,jsx:ts.JsxEmit.React}}).outputText;
|
||||
const deferred = () => {let resolve,reject;const promise=new Promise((r,j)=>{resolve=r;reject=j;});return {promise,resolve,reject};};
|
||||
const tick = () => new Promise(resolve=>setImmediate(resolve));
|
||||
|
||||
function policyFixture(api, validate) {
|
||||
const panel=read('GovernanceCompletion.tsx').split('export function UserAccessPolicyPanel')[1];
|
||||
const selection=panel.slice(panel.indexOf(' const selectUser'),panel.indexOf(' const userOptions'));
|
||||
const load=panel.slice(panel.indexOf(' const load ='),panel.indexOf(' useEffect('));
|
||||
const actions=panel.slice(panel.indexOf(' const save ='),panel.indexOf(' const scopeCounts'));
|
||||
return new Function('api','validate',transpile(`
|
||||
let userId,policy=null,effective=null,scopePreview=null,previewBusy=false,loading=false,saving=false,error='',fields={};
|
||||
const selectedUser={current:undefined},policyGeneration={current:0},savingRef={current:false},mounted={current:true};
|
||||
const obj=v=>v,text=(v,f)=>v??f,onUnauthorized=()=>false,message={success(){},error(){}};
|
||||
class ApiError extends Error{}
|
||||
const form={resetFields(){fields={};},setFieldsValue(v){fields={...fields,...v};},async validateFields(){return validate?validate():{...fields,reason:'fixture reason'};}};
|
||||
const setUserId=v=>userId=v,setPolicy=v=>policy=v,setEffective=v=>effective=v,setScopePreview=v=>scopePreview=v,
|
||||
setPreviewBusy=v=>previewBusy=v,setLoading=v=>loading=v,setSaving=v=>saving=v,setError=v=>error=v;
|
||||
${selection}${load}${actions}
|
||||
return {selectUser,load,save,preview,get:()=>({userId,policy,effective,scopePreview,loading,saving,error,fields})};
|
||||
`))(api,validate);
|
||||
}
|
||||
|
||||
test('late A policy cannot overwrite B or submit A fields to B',async()=>{
|
||||
const a=deferred(),b=deferred(),writes=[];
|
||||
const ui=policyFixture({userAccessPolicy:id=>id==='A'?a.promise:b.promise,updateUserAccessPolicy:async(id,body)=>writes.push({id,body})});
|
||||
ui.selectUser('A');const pa=ui.load('A');ui.selectUser('B');const pb=ui.load('B');
|
||||
b.resolve({policy:{userId:'B',rowVersion:0,detailAllowed:false,allowedFields:['limited']}});await pb;
|
||||
a.resolve({policy:{userId:'A',rowVersion:0,detailAllowed:true,allowedFields:['*']}});await pa;
|
||||
assert.equal(ui.get().policy.userId,'B');assert.equal(ui.get().fields.detailAllowed,false);await ui.save();
|
||||
assert.equal(writes[0].id,'B');assert.deepEqual(writes[0].body.allowedFields,['limited']);
|
||||
});
|
||||
|
||||
test('failed B read clears A form and disables a cross-entity save',async()=>{
|
||||
const writes=[];const ui=policyFixture({userAccessPolicy:async id=>{if(id==='B')throw Error('offline');return {policy:{userId:id,allowedFields:['*']}};},updateUserAccessPolicy:async(...v)=>writes.push(v)});
|
||||
ui.selectUser('A');await ui.load('A');ui.selectUser('B');assert.equal(ui.get().policy,null);assert.deepEqual(ui.get().fields,{});
|
||||
await ui.load('B');await ui.save();assert.deepEqual(writes,[]);assert.match(ui.get().error,/offline/);
|
||||
});
|
||||
|
||||
test('selection is locked before async form validation and save keeps its own entity',async()=>{
|
||||
const validation=deferred(),writes=[];
|
||||
const ui=policyFixture({userAccessPolicy:async id=>({policy:{userId:id,rowVersion:0,allowedFields:['A-field']}}),updateUserAccessPolicy:async(id,body)=>writes.push({id,body})},()=>validation.promise);
|
||||
ui.selectUser('A');await ui.load('A');const saving=ui.save();ui.selectUser('B');assert.equal(ui.get().userId,'A');
|
||||
validation.resolve({allowedFields:'A-field',reason:'fixture'});await saving;assert.equal(writes[0].id,'A');assert.equal(ui.get().saving,false);
|
||||
});
|
||||
|
||||
test('old preview response and mismatched policy identity are rejected',async()=>{
|
||||
const preview=deferred();const ui=policyFixture({userAccessPolicy:async id=>({policy:{userId:id==='C'?'wrong':id}}),effectiveUserAccess:()=>preview.promise});
|
||||
ui.selectUser('A');await ui.load('A');const pending=ui.preview('effective');ui.selectUser('B');await ui.load('B');
|
||||
preview.resolve({userId:'A'});await pending;assert.equal(ui.get().effective,null);
|
||||
ui.selectUser('C');await ui.load('C');assert.equal(ui.get().policy,null);assert.match(ui.get().error,/不匹配/);
|
||||
});
|
||||
|
||||
// Minimal hook scheduler: execute actual components and effect cleanups, inspecting
|
||||
// the React element tree without replacing their request/state implementation.
|
||||
function hookRenderer(factory) {
|
||||
const values=new Map(),refs=new Map(),effects=new Map();let cursor=0,dirty=false,queued=[],tree;
|
||||
const hooks={
|
||||
useState(initial){const i=cursor++;if(!values.has(i))values.set(i,typeof initial==='function'?initial():initial);return [values.get(i),v=>{values.set(i,typeof v==='function'?v(values.get(i)):v);dirty=true;}];},
|
||||
useRef(initial){const i=cursor++;if(!refs.has(i))refs.set(i,{current:initial});return refs.get(i);},
|
||||
useMemo(fn){cursor++;return fn();},
|
||||
useEffect(fn,deps){const i=cursor++,old=effects.get(i);if(!old||deps.some((d,j)=>!Object.is(d,old.deps[j]))){queued.push(()=>{old?.cleanup?.();effects.set(i,{deps,cleanup:fn()});});}},
|
||||
};
|
||||
const component=factory(hooks);
|
||||
return {render(props){let attempts=0;do{dirty=false;cursor=0;queued=[];tree=component(props);queued.forEach(fn=>fn());if(++attempts>10)throw Error('render loop');}while(dirty);return tree;},unmount(){effects.forEach(e=>e.cleanup?.());}};
|
||||
}
|
||||
function find(tree,predicate){if(!tree||typeof tree!=='object')return; if(predicate(tree))return tree;for(const child of React.Children.toArray(tree.props?.children)){const found=find(child,predicate);if(found)return found;}}
|
||||
const textOf = tree => typeof tree==='string'?tree:!tree||typeof tree!=='object'?'':React.Children.toArray(tree.props?.children).map(textOf).join('');
|
||||
const baseQuery={year:2026,month:1,view:'overall'};
|
||||
|
||||
test('source filters, row/month and release are frozen together without modifying live query',()=>{
|
||||
const query={...baseQuery,quarter:1,extraFilters:{customer:['001']}};
|
||||
const row={key:'product-1',product:'product-1'};
|
||||
const frozen=freezeSourceRecordsQuery(query,'release-A','product',row,2);
|
||||
query.extraFilters.customer.push('002');query.releaseId='release-B';
|
||||
assert.equal(frozen.releaseId,'release-A');assert.equal(frozen.month,2);assert.equal(frozen.quarter,undefined);assert.equal(frozen.product,'product-1');
|
||||
assert.deepEqual(frozen.extraFilters,{customer:['001']});assert.equal(query.quarter,1);
|
||||
assert.throws(()=>freezeSourceRecordsQuery(query,'','overall',null),/尚未就绪/);
|
||||
});
|
||||
|
||||
test('the actual summary click stores release A and filters until a new detail is explicitly opened',()=>{
|
||||
const source=read('QueryPage.tsx'),start=source.indexOf(' const openRecords = useCallback');
|
||||
const callback=source.slice(start,source.indexOf(' const summaryMetricsError',start));
|
||||
const ui=new Function('freezeSourceRecordsQuery',transpile(`
|
||||
let summaryMetricsData={release:{id:'release-A'}},queryParams={year:2026,month:1,view:'overall',extraFilters:{customer:['001']}},snapshot;
|
||||
const drilledProduct=false,defectQueryParams=queryParams,view='overall',message={info(){}},useCallback=fn=>fn;
|
||||
const setRecordQuerySnapshot=value=>snapshot=value,setSelectedRecord=()=>{},setRecordStage=()=>{},setRecordMonth=()=>{},setRecordsOpen=()=>{};
|
||||
${callback}
|
||||
return {openRecords,get:()=>snapshot,changeCurrent(){summaryMetricsData={release:{id:'release-B'}};queryParams.month=2;queryParams.extraFilters.customer.push('002');}};
|
||||
`))(freezeSourceRecordsQuery);
|
||||
ui.openRecords(null,'black');ui.changeCurrent();assert.equal(ui.get().releaseId,'release-A');assert.equal(ui.get().month,1);assert.deepEqual(ui.get().extraFilters.customer,['001']);
|
||||
ui.openRecords(null,'black');assert.equal(ui.get().releaseId,'release-B');assert.equal(ui.get().month,2);
|
||||
});
|
||||
|
||||
function drawerFixture() {
|
||||
const source=read('QueryPage.tsx');const code=source.slice(source.indexOf('function RecordsDrawer(')).replace(/export \{ fullYearTrend \};/, '');
|
||||
const requests=[],exports=[];let downloaded=0;
|
||||
const props={open:true,row:null,stage:'black',onStage(){},onClose(){},query:freezeSourceRecordsQuery(baseQuery,'release-A','overall',null),onUnauthorized:()=>false};
|
||||
const renderer=hookRenderer(hooks=>new Function('React','hooks','api',transpile(`
|
||||
const {useState,useRef,useMemo,useEffect}=hooks;const TABLE_PAGE_SIZE=20,MONTHS=Array.from({length:12},(_,i)=>i+1+'月');
|
||||
const Drawer='Drawer',Segmented='Segmented',Select='Select',Button='Button',Alert='Alert',Spin='Spin',Table='Table',Pagination='Pagination',SearchOutlined='SearchOutlined',DownloadOutlined='DownloadOutlined';
|
||||
const Input='Input',readableSelectPopup={},Empty=Object.assign(()=>null,{PRESENTED_IMAGE_SIMPLE:'empty'}),App={useApp:()=>({message:{success(){},error(){}}})};
|
||||
const isSystemVersionField=()=>false,chooseError=e=>e.message,withoutSystemVersionFields=v=>v;
|
||||
const window={innerWidth:1400,setTimeout:fn=>fn()},document={createElement:()=>({click(){api.downloaded();},remove(){}}),body:{appendChild(){}}};
|
||||
${code}
|
||||
return RecordsDrawer;
|
||||
`))(React,hooks,{records(params,signal){const d=deferred();requests.push({params,signal,...d});return d.promise;},async exportRecords(params,signal){exports.push({params,signal});return {blob:new Blob(['fixture']),filename:'fixture.xlsx'};},downloaded(){downloaded++;}}));
|
||||
return {requests,exports,props,render:()=>renderer.render(props),unmount:()=>renderer.unmount(),get downloaded(){return downloaded;}};
|
||||
}
|
||||
|
||||
test('actual drawer clears prior rows during page load/failure and offers retry on the same frozen release',async()=>{
|
||||
const ui=drawerFixture();ui.render();assert.equal(ui.requests[0].params.page,1);assert.equal(ui.requests[0].params.releaseId,'release-A');
|
||||
ui.requests[0].resolve({rows:[{id:'A-1',raw:{field:'value'}}],total:45,pageSize:20,page:1});await tick();let tree=ui.render();
|
||||
assert.equal(find(tree,n=>n.type==='Table').props.dataSource[0].id,'A-1');find(tree,n=>n.type==='Pagination').props.onChange(2);tree=ui.render();
|
||||
assert.equal(find(tree,n=>n.type==='Table'),undefined);ui.requests[1].reject(Error('page failed'));await tick();tree=ui.render();assert.equal(find(tree,n=>n.type==='Table'),undefined);
|
||||
const alert=find(tree,n=>n.type==='Alert');assert.equal(alert.props.description,'page failed');alert.props.action.props.onClick();ui.render();
|
||||
assert.equal(ui.requests[2].params.page,2);assert.equal(ui.requests[2].params.releaseId,'release-A');ui.unmount();assert.equal(ui.requests[2].signal.aborted,true);
|
||||
});
|
||||
|
||||
test('actual drawer recovers an out-of-range page to the only valid first page',async()=>{
|
||||
const ui=drawerFixture();ui.render();ui.requests[0].resolve({rows:[{id:'A'}],total:45,pageSize:20,page:1});await tick();let tree=ui.render();
|
||||
find(tree,n=>n.type==='Pagination').props.onChange(2);ui.render();ui.requests[1].resolve({rows:[],total:3,pageSize:20,page:2});await tick();ui.render();
|
||||
assert.equal(ui.requests[2].params.page,1);ui.requests[2].resolve({rows:[{id:'only-row'}],total:3,pageSize:20,page:1});await tick();tree=ui.render();
|
||||
assert.equal(find(tree,n=>n.type==='Table').props.dataSource[0].id,'only-row');ui.unmount();
|
||||
});
|
||||
|
||||
test('closing and reopening a different month remounts page/search state and ignores late prior reads',async()=>{
|
||||
const first=drawerFixture();first.render();first.unmount();first.requests[0].resolve({rows:[{id:'late-old'}],total:50,pageSize:20,page:1});await tick();
|
||||
const next=drawerFixture();next.props.query=freezeSourceRecordsQuery({...baseQuery,month:2},'release-A','overall',null);next.render();
|
||||
assert.equal(next.requests[0].params.page,1);assert.equal(next.requests[0].params.search,undefined);assert.equal(next.requests[0].params.month,2);
|
||||
assert.equal(find(next.render(),n=>n.type==='Table'),undefined);next.unmount();
|
||||
assert.match(read('QueryPage.tsx'),/recordsOpen && recordQuerySnapshot && <RecordsDrawer/);
|
||||
});
|
||||
|
||||
test('export from the actual drawer keeps the clicked release even after current publication changes',async()=>{
|
||||
const ui=drawerFixture();ui.render();const tree=ui.render();
|
||||
await find(tree,n=>n.type==='Button'&&textOf(n)==='导出明细 Excel').props.onClick();
|
||||
assert.equal(ui.exports[0].params.releaseId,'release-A');assert.equal(ui.exports[0].params.month,1);assert.equal(ui.downloaded,1);ui.unmount();
|
||||
});
|
||||
|
||||
function tableFixture(props) {
|
||||
const code=read('QualityTable.tsx').slice(read('QualityTable.tsx').indexOf('type QualityTableProps')).replace('export function QualityTable','function QualityTable');
|
||||
const renderer=hookRenderer(hooks=>new Function('React','useState','useContext','CompactManagementTables','AntdTable',transpile(`${code}\nreturn QualityTable;`))(React,hooks.useState,()=>false,{},'AntdTable'));
|
||||
return {render:()=>find(renderer.render(props),n=>n.type==='AntdTable').props,props};
|
||||
}
|
||||
|
||||
test('uncontrolled table rows number continuously across page/size changes while preserving callbacks',()=>{
|
||||
const calls=[];const ui=tableFixture({dataSource:Array.from({length:45},(_,i)=>({id:i})),columns:[],pagination:{pageSize:20},onChange:(...args)=>calls.push(args)});
|
||||
let table=ui.render();assert.equal(table.columns[0].render(null,null,0),1);
|
||||
table.onChange({current:2,pageSize:20},{},[],{action:'paginate'});table=ui.render();assert.equal(table.columns[0].render(null,null,0),21);assert.equal(calls.length,1);
|
||||
table.onChange({current:1,pageSize:10},{},[],{action:'paginate'});ui.props.pagination.pageSize=10;table=ui.render();assert.equal(table.columns[0].render(null,null,0),1);
|
||||
});
|
||||
|
||||
test('table numbering respects default, controlled and externally paginated offsets',()=>{
|
||||
const rows=Array.from({length:45},()=>({}));
|
||||
let ui=tableFixture({dataSource:rows,pagination:{defaultCurrent:2,defaultPageSize:20}});assert.equal(ui.render().columns[0].render(null,null,0),21);
|
||||
ui=tableFixture({dataSource:rows,pagination:{current:3,pageSize:20,total:45}});assert.equal(ui.render().columns[0].render(null,null,0),41);
|
||||
ui=tableFixture({dataSource:rows,pagination:false,indexOffset:100});assert.equal(ui.render().columns[0].render(null,null,0),101);
|
||||
});
|
||||
|
||||
function thinkingFixture() {
|
||||
const code=read('ModelThinkingPanel.tsx').slice(read('ModelThinkingPanel.tsx').indexOf('export function')).replace('export function','function');
|
||||
const props={running:true,entry:{id:'api-first',status:'running',text:'第一段原文🙂'}};
|
||||
const renderer=hookRenderer(hooks=>new Function('React','hooks',transpile(`
|
||||
const {useState,useRef,useEffect}=hooks;const RightOutlined='RightOutlined';
|
||||
const window={matchMedia:()=>({matches:true})};const thinkingTextFrame=(from,target)=>target;
|
||||
${code}
|
||||
return AnalysisThinkingBlock;
|
||||
`))(React,hooks));
|
||||
return {props,render:()=>renderer.render(props)};
|
||||
}
|
||||
test('actual thinking panel collapses once and late adjacent activity cannot reopen it',()=>{
|
||||
const ui=thinkingFixture();let initial=ui.render();assert.equal(initial.props.open,false);
|
||||
initial.props.onToggle({currentTarget:{open:true}});assert.equal(ui.render().props.open,true);
|
||||
ui.props.entry={...ui.props.entry,status:'completed'};assert.equal(ui.render().props.open,false);
|
||||
ui.props.entry={...ui.props.entry,status:'running',text:'第一段原文🙂后续原文'};
|
||||
let tree=ui.render();assert.equal(tree.props.open,false);
|
||||
tree.props.onToggle({currentTarget:{open:true}});tree=ui.render();
|
||||
assert.equal(tree.props.open,true);assert.equal(find(tree,n=>n.type==='pre').props.children,'第一段原文🙂后续原文');
|
||||
});
|
||||
test('actual thinking panel preserves manual state during output and new groups start collapsed',()=>{
|
||||
const ui=thinkingFixture();let tree=ui.render();assert.equal(tree.props.open,false);
|
||||
tree.props.onToggle({currentTarget:{open:true}});
|
||||
ui.props.entry={...ui.props.entry,text:'第一段原文🙂手动展开后收到更多'};assert.equal(ui.render().props.open,true);
|
||||
tree=ui.render();tree.props.onToggle({currentTarget:{open:false}});
|
||||
ui.props.entry={...ui.props.entry,text:'第一段原文🙂收到更多'};assert.equal(ui.render().props.open,false);
|
||||
ui.props.entry={...ui.props.entry,id:'api-new-group',text:'新的独立思考原文'};
|
||||
assert.equal(ui.render().props.open,false);
|
||||
ui.props.running=false;assert.equal(ui.render().props.open,false);
|
||||
});
|
||||
@@ -0,0 +1 @@
|
||||
<!doctype html><html lang="zh-CN"><head><meta charset="UTF-8"><title>汇总表本地验收</title></head><body><div id="root"></div><script type="module" src="./metric-table.tsx"></script></body></html>
|
||||
@@ -0,0 +1,28 @@
|
||||
// Isolated browser acceptance with simulated data; never calls the business API.
|
||||
const stage = { qualifiedWeight: 42243.6, scrapWeight: 372.2, totalWeight: 42615.8, rate: .991265, headquartersScrapWeight: 25.6, rateWithoutHeadquartersScrap: .9918, defects: [{ name: '裂纹', weight: 230.1, rate: .0054 }, { name: '缺角', weight: 142.1, rate: .0033 }] };
|
||||
const products = ['62.8X36.8X51', '30X8.4X1.6+T', '16.33X15.5X3.75+T', ...Array.from({length:15},(_,i)=>`产品规格-${i+4}`)];
|
||||
const rows = products.map((product,i)=>({ key: String(i), label: product, department:'工业电机产业部', group:'工业电机-VCM', product, compositeRate:.9751,black:{...stage,qualifiedWeight:38582.1},bright:stage,coverage:{blackRows:5,brightRows:5} }));
|
||||
const json = (value: unknown) => new Response(JSON.stringify(value), {headers:{'Content-Type':'application/json'}});
|
||||
window.fetch = async (target) => {
|
||||
const url = new URL(String(target), location.origin);
|
||||
if(url.pathname==='/api/auth/me')return json({user:{id:'local-fixture',username:'admin',displayName:'admin',roles:['SYSTEM_ADMIN'],departments:[],groups:[]}});
|
||||
if(url.pathname==='/api/workspace/state')return json({authRevision:'fixture',dataRevision:'fixture'});
|
||||
if(url.pathname==='/api/options')return json({years:[2026],departments:['工业电机产业部'],groups:['工业电机-VCM'],groupDepartments:{'工业电机-VCM':'工业电机产业部'},products,projectGroupStatus:'READY',projectGroups:[],releases:[{id:'fixture-release',name:'本地验收',status:'PUBLISHED'}]});
|
||||
if(url.pathname==='/api/filter-fields')return json([]);
|
||||
if(url.pathname==='/api/metrics') {
|
||||
const view=url.searchParams.get('view');
|
||||
const product=url.searchParams.get('product');
|
||||
let visible=product?rows.filter(r=>r.product===product):rows;
|
||||
if(view==='department')visible=[{...rows[0],key:'工业电机产业部',label:'工业电机产业部'}];
|
||||
if(view==='group')visible=[{...rows[0],key:'工业电机-VCM',label:'工业电机-VCM'}];
|
||||
return json({release:{id:'fixture-release',name:'本地验收',status:'PUBLISHED'},context:{},summary:rows[0],rows:visible,trend:Array.from({length:9},(_,i)=>({...rows[0],key:`month-${i+1}`,month:i+1,period:`2026-${String(i+1).padStart(2,'0')}`})),defects:{black:stage.defects,bright:stage.defects},coverage:{sourceMonths:[{year:2026,month:9,blackRows:90,brightRows:90}],rawRows:180,includedRows:180,excludedBlankRows:0,unmappedRows:0,projectGroupUnconfiguredRows:0,missingStages:[]}});
|
||||
}
|
||||
if(url.pathname==='/api/analysis/defects')return json({rows:[],kind:'fine_defect_top',sourceRows:0,releaseId:'fixture-release'});
|
||||
if(url.pathname==='/api/records')return json({rows:[{id:'fixture-1',month:9,raw:{'产品规格':products[0],'重量':42},normalized:{},components:{}}],page:1,pageSize:20,total:1});
|
||||
return json({items:[]});
|
||||
};
|
||||
const originalGet = Storage.prototype.getItem;
|
||||
const originalSet = Storage.prototype.setItem;
|
||||
Storage.prototype.getItem = function(key) { return key === 'quality-workbench-theme' ? 'light' : originalGet.call(this, key); };
|
||||
Storage.prototype.setItem = function(key, value) { if(key !== 'quality-workbench-theme') originalSet.call(this, key, value); };
|
||||
await import('../src/main');
|
||||
@@ -0,0 +1,113 @@
|
||||
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 { defectWeightRate } from '../src/trendMetrics.ts';
|
||||
import { createMetricWorkbook, workbookColumns } from '../src/metricWorkbook.ts';
|
||||
|
||||
const source = fs.readFileSync(new URL('../src/QueryPage.tsx', import.meta.url), 'utf8');
|
||||
const slice = (start, end) => source.slice(source.indexOf(start), source.indexOf(end, source.indexOf(start)));
|
||||
const helpers = slice('function numberText(', 'const SYSTEM_SOURCE_VERSION_KEYS')
|
||||
+ slice('function hasStageRows(', 'function fullYearTrend(')
|
||||
+ slice('function objectLabel(', 'interface ChartTooltipParam');
|
||||
const table = slice('export function MetricTable(', 'function MetricTablePagination(').replace('export function', 'function');
|
||||
function fixture(props) {
|
||||
let exported, detail = 0, basis = 0;
|
||||
const ref = {};
|
||||
const render = new Function('React', 'useImperativeHandle', 'defectWeightRate', 'downloadMetricWorkbook', ts.transpileModule(`
|
||||
const MONTHS=Array.from({length:12},(_,i)=>String(i+1).padStart(2,'0')+'月');
|
||||
const SUMMARY_PAGE_SIZE=15;
|
||||
const useCompactTable=()=>false, useState=v=>[v,()=>{}], useEffect=()=>{};
|
||||
const Button='Button', Table='Table', MetricTablePagination='Pagination';
|
||||
${helpers}\n${table}\nreturn MetricTable;
|
||||
`, {compilerOptions:{jsx:ts.JsxEmit.React,target:ts.ScriptTarget.ES2022}}).outputText)(React, (target, create) => Object.assign(target, create()), defectWeightRate, async (filename, columns, rows, value) => {
|
||||
exported = { filename, columns, rows, workbook: await createMetricWorkbook(columns, rows, value) };
|
||||
});
|
||||
const tree = render({ref,exportFilename:'验收',period:'month',month:9,quarter:3,rateBasis:'original',fullFields:false,onDetail(){detail++;},onBasis(){basis++;},onDrilldown(){},...props});
|
||||
return {tree, ref, get exported(){return exported;}, get detail(){return detail;}, get basis(){return basis;}};
|
||||
}
|
||||
function find(node, predicate) {
|
||||
if (!node || typeof node !== 'object') return;
|
||||
if (predicate(node)) return node;
|
||||
for (const child of React.Children.toArray(node.props?.children)) { const hit=find(child,predicate);if(hit)return hit; }
|
||||
}
|
||||
const stage = {qualifiedWeight:1234.567,scrapWeight:0,totalWeight:1250,headquartersScrapWeight:3,rate:0.987654,rateWithoutHeadquartersScrap:0.99,defects:[{name:'裂纹',weight:12.345,rate:0.01}]};
|
||||
const row = {key:'p',label:'=1+2',product:'=1+2',department:'产业部',group:'业务分组',projectGroup:'项目组',compositeRate:0.975,compositeRateWithoutHeadquartersScrap:0.98,black:stage,bright:stage,coverage:{blackRows:1,brightRows:1}};
|
||||
|
||||
for (const view of ['overall','department','group','product','projectGroup']) {
|
||||
for (const fullFields of [false,true]) test(`${view}: ${fullFields?'full':'key'} export uses all rows and exactly the visible data columns`, async () => {
|
||||
const rows=Array.from({length:18},(_,i)=>({...row,key:String(i)}));
|
||||
const ui=fixture({rows,view,fullFields});
|
||||
const table=find(ui.tree,n=>n.type==='Table');
|
||||
assert.equal(table.props.dataSource.length,15);
|
||||
await ui.ref.exportExcel();
|
||||
const {workbook,columns}=ui.exported;
|
||||
const fields=workbookColumns(columns), sheet=workbook.getWorksheet('质量汇总');
|
||||
if(view==='product')assert.equal(find(columns.find(c=>c.key==='object').render(null,row),n=>n.type==='small'),undefined);
|
||||
assert.equal(sheet.rowCount,19);assert.equal(sheet.columnCount,fullFields?13:8);
|
||||
assert.deepEqual(sheet.getRow(1).values.slice(1),fields.map(v=>v.header));
|
||||
assert.equal(sheet.getRow(2).getCell(3).value,1234.567);
|
||||
assert.equal(sheet.getRow(2).getCell(4).value,fullFields?1250:0);
|
||||
assert.equal(fields.some(f=>f.key.includes('defect-')),fullFields);
|
||||
assert.equal(fields.some(f=>f.key.endsWith('headquartersScrapWeight')),fullFields);
|
||||
assert.equal(fields.some(f=>f.key==='actions'),false);
|
||||
assert.equal(sheet.getColumn(2).numFmt,'0.00%');
|
||||
assert.equal(sheet.getColumn(3).numFmt,'#,##0.0');
|
||||
for (const field of columns.flatMap(c=>c.children||[c]).filter(c=>c.key!=='actions'&&c.key!=='object')) {
|
||||
const rendered=field.render(null,row);
|
||||
assert.equal(rendered.type,field.key==='compositeRate'?'button':'Button');assert.equal(rendered.props.onClick,undefined);
|
||||
}
|
||||
const action=columns.find(c=>c.key==='actions').render(null,row);
|
||||
action.props.onClick();assert.equal(ui.detail,1);
|
||||
const reread=await createMetricWorkbook([],[],()=>null);
|
||||
await reread.xlsx.load(await workbook.xlsx.writeBuffer());
|
||||
assert.equal(reread.getWorksheet('质量汇总').rowCount,19);
|
||||
if(view==='product')assert.equal(reread.getWorksheet('质量汇总').getCell('A2').value,'=1+2');
|
||||
});
|
||||
}
|
||||
|
||||
test('adjusted rates, missing stage and zero weight retain their meaning', async () => {
|
||||
const ui=fixture({rows:[row,{...row,key:'missing',black:{...stage,qualifiedWeight:null,rate:null},coverage:{blackRows:0,brightRows:1}}],view:'product',rateBasis:'withoutHeadquartersScrap'});
|
||||
await ui.ref.exportExcel();const sheet=ui.exported.workbook.getWorksheet('质量汇总');
|
||||
assert.equal(sheet.getCell('B2').value,0.98);assert.equal(sheet.getCell('H2').value,0.99);
|
||||
assert.equal(sheet.getCell('E3').value,null);assert.equal(sheet.getCell('C3').value,null);assert.equal(sheet.getCell('D2').value,0);
|
||||
});
|
||||
|
||||
test('overall yearly export preserves month labels and leaves unavailable values blank', async () => {
|
||||
const ui=fixture({rows:[{...row,month:2},{...row,key:'missing',month:3,noData:true,black:{...stage,qualifiedWeight:null,rate:null},bright:{...stage,qualifiedWeight:null,rate:null},coverage:{blackRows:0,brightRows:0}}],view:'overall',period:'year'});
|
||||
await ui.ref.exportExcel();const sheet=ui.exported.workbook.getWorksheet('质量汇总');
|
||||
assert.equal(sheet.getCell('A2').value,'02月');assert.equal(sheet.getCell('A3').value,'03月');assert.equal(sheet.getCell('B3').value,null);
|
||||
});
|
||||
|
||||
for (const view of ['overall','department','group','product','projectGroup']) test(`${view}: defect-rate mode uses same-stage total and exports numeric percentages`,async()=>{
|
||||
const data={...row,black:{...stage,totalWeight:1000,scrapWeight:200,defects:[{name:'责废',weight:120,rate:.99}]},bright:{...stage,totalWeight:2000,scrapWeight:100,headquartersScrapWeight:30,defects:[{name:'责废',weight:80,rate:.99}]}};
|
||||
const ui=fixture({rows:[data],view,fullFields:true,defectDisplay:'rate'});
|
||||
await ui.ref.exportExcel();
|
||||
const fields=workbookColumns(ui.exported.columns),sheet=ui.exported.workbook.getWorksheet('质量汇总');
|
||||
const at=key=>fields.findIndex(field=>field.key===key)+1;
|
||||
assert.equal(sheet.getRow(2).getCell(at('black-defect-责废')).value,.12);
|
||||
assert.equal(sheet.getRow(2).getCell(at('bright-defect-责废')).value,.04);
|
||||
assert.equal(sheet.getRow(2).getCell(at('black-scrapWeight')).value,.2);
|
||||
assert.equal(sheet.getRow(2).getCell(at('bright-headquartersScrapWeight')).value,.015);
|
||||
assert.equal(sheet.getColumn(at('black-defect-责废')).numFmt,'0.00%');
|
||||
assert.equal(fields[at('black-defect-责废')-1].header,'黑片 / 责废率');
|
||||
assert.equal(fields[at('bright-headquartersScrapWeight')-1].header,'亮片 / 本部报废率');
|
||||
assert.match(fields[at('black-totalWeight')-1].header,/总重量 \/ kg$/);
|
||||
assert.equal(sheet.getRow(2).getCell(at('black-totalWeight')).value,1000);
|
||||
const rendered=ui.exported.columns.flatMap(column=>column.children||[column]).find(column=>column.key==='black-defect-责废').render(null,data);
|
||||
assert.equal(rendered.props.children,'12.00%');
|
||||
const restored=fixture({rows:[data],view,fullFields:true,defectDisplay:'weight'});await restored.ref.exportExcel();
|
||||
const originalFields=workbookColumns(restored.exported.columns),index=originalFields.findIndex(field=>field.key==='black-defect-责废')+1;
|
||||
assert.equal(restored.exported.workbook.getWorksheet('质量汇总').getRow(2).getCell(index).value,120);
|
||||
assert.equal(data.black.defects[0].weight,120);
|
||||
});
|
||||
test('single-stage rate mode exports only its stage; missing or zero denominator stays blank and zero defect stays zero',async()=>{
|
||||
const rows=[{...row,key:'zero',black:{...stage,totalWeight:0}}, {...row,key:'null',black:{...stage,totalWeight:null}}, {...row,key:'valid',black:{...stage,totalWeight:100,scrapWeight:0}}];
|
||||
const ui=fixture({rows,view:'product',fullFields:true,onlyStage:'black',defectDisplay:'rate'});await ui.ref.exportExcel();
|
||||
const fields=workbookColumns(ui.exported.columns),sheet=ui.exported.workbook.getWorksheet('质量汇总'),at=key=>fields.findIndex(f=>f.key===key)+1;
|
||||
assert.equal(fields.some(f=>f.key.startsWith('bright-')),false);
|
||||
assert.equal(sheet.getRow(2).getCell(at('black-scrapWeight')).value,null);
|
||||
assert.equal(sheet.getRow(3).getCell(at('black-defect-裂纹')).value,null);
|
||||
assert.equal(sheet.getRow(4).getCell(at('black-scrapWeight')).value,0);
|
||||
});
|
||||
@@ -0,0 +1,192 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as echarts from 'echarts/core';
|
||||
import { BarChart, LineChart } from 'echarts/charts';
|
||||
import { GridComponent, LegendComponent, TooltipComponent, GraphicComponent, TitleComponent } from 'echarts/components';
|
||||
import { SVGRenderer } from 'echarts/renderers';
|
||||
import {
|
||||
buildAnalysisVisualExportOption,
|
||||
parseAnalysisVisuals,
|
||||
visualParetoPoints,
|
||||
} from '../src/analysisVisualsModel.ts';
|
||||
|
||||
echarts.use([BarChart, LineChart, GridComponent, LegendComponent, TooltipComponent, GraphicComponent, TitleComponent, SVGRenderer]);
|
||||
|
||||
const WIDTH = 900;
|
||||
const LONG_LABEL_CHARS = 160;
|
||||
const FOOTER = '累计占比=所列累计重量÷同范围全部重量;Top未覆盖全量时不补足100%';
|
||||
|
||||
function productNames() {
|
||||
const alphabet = [...'高性能新能源汽车驱动电机磁钢规格型号材料检验工艺质量稳定强度'];
|
||||
const names = Array.from({ length: 10 }, (_, index) => {
|
||||
const marker = [...'一二三四五六七八九十'][index];
|
||||
const body = Array.from({ length: LONG_LABEL_CHARS - 1 }, (_unused, offset) =>
|
||||
alphabet[(offset * 7 + index * 3) % alphabet.length]).join('');
|
||||
return marker + body;
|
||||
});
|
||||
assert.ok(names.every(name => name.length === LONG_LABEL_CHARS));
|
||||
return names;
|
||||
}
|
||||
|
||||
function rankingVisual(names, weights) {
|
||||
return {
|
||||
id: 'ranking-long-labels', type: 'pareto', title: '黑片投入重量排名', subtitle: '按规格全量排名', unit: 'kg',
|
||||
categories: names.map((label, index) => ({ key: `product-${index + 1}`, label })),
|
||||
series: [{ key: 'black_total_weight', label: '黑片投入重量', values: weights }],
|
||||
evidenceRefs: ['Q12345678'], requiredFields: ['black_total_weight'], scope: { department: '新能源汽车磁钢' },
|
||||
period: { year: 2026 }, stage: 'black', metric: 'black_total_weight', dimension: 'product',
|
||||
coverage: { totalRows: 24, returnedRows: 10, truncated: true,
|
||||
shareBasis: 'all_scope_weight', denominator: 10000 },
|
||||
originTurnId: 'ranking-svg-layout-turn',
|
||||
};
|
||||
}
|
||||
|
||||
function boundsInCanvas(element) {
|
||||
const rect = element.getBoundingRect();
|
||||
const transform = element.getComputedTransform();
|
||||
assert.ok(rect && transform, 'SSR text display item must expose a rectangle and transform');
|
||||
const [a, b, c, d, e, f] = transform;
|
||||
const corners = [
|
||||
[rect.x, rect.y], [rect.x + rect.width, rect.y],
|
||||
[rect.x, rect.y + rect.height], [rect.x + rect.width, rect.y + rect.height],
|
||||
].map(([x, y]) => [a * x + c * y + e, b * x + d * y + f]);
|
||||
return {
|
||||
left: Math.min(...corners.map(([x]) => x)), right: Math.max(...corners.map(([x]) => x)),
|
||||
top: Math.min(...corners.map(([_x, y]) => y)), bottom: Math.max(...corners.map(([_x, y]) => y)),
|
||||
centerX: e,
|
||||
};
|
||||
}
|
||||
|
||||
function svgTextBoxes(chart, option, footerText = FOOTER) {
|
||||
const displayList = chart.getZr().storage.getDisplayList(true);
|
||||
const textElements = displayList.filter(element => element.type === 'tspan'
|
||||
&& typeof element.style?.text === 'string');
|
||||
const footer = textElements.find(element => element.style.text === footerText);
|
||||
assert.ok(footer, `SVG SSR displayList must contain footer text: ${footerText}`);
|
||||
const footerBounds = boundsInCanvas(footer);
|
||||
const grid = option.grid;
|
||||
const plotBottom = Number(grid.top) + Number(grid.height);
|
||||
const plotLeft = Number(grid.left);
|
||||
const plotRight = WIDTH - Number(grid.right);
|
||||
const labels = textElements.flatMap(element => {
|
||||
const text = element.style.text;
|
||||
if (!/[\u3400-\u9fff]/u.test(text)) return [];
|
||||
const bounds = boundsInCanvas(element);
|
||||
if (bounds.top < plotBottom - 2 || bounds.top >= footerBounds.top
|
||||
|| bounds.left < plotLeft - 1 || bounds.right > plotRight + 1) return [];
|
||||
return [{ text, bounds }];
|
||||
});
|
||||
const byCategoryCenter = new Map();
|
||||
for (const label of labels) {
|
||||
const key = Math.round(label.bounds.centerX * 100) / 100;
|
||||
const existing = byCategoryCenter.get(key) || [];
|
||||
existing.push(label);
|
||||
byCategoryCenter.set(key, existing);
|
||||
}
|
||||
const categories = [...byCategoryCenter.entries()].sort(([left], [right]) => left - right).map(([center, lines]) => ({
|
||||
center,
|
||||
text: lines.sort((left, right) => left.bounds.top - right.bounds.top).map(line => line.text).join(''),
|
||||
left: Math.min(...lines.map(line => line.bounds.left)), right: Math.max(...lines.map(line => line.bounds.right)),
|
||||
top: Math.min(...lines.map(line => line.bounds.top)), bottom: Math.max(...lines.map(line => line.bounds.bottom)),
|
||||
}));
|
||||
return { categories, footerBounds, displayList };
|
||||
}
|
||||
|
||||
function renderExport(visual, width = WIDTH) {
|
||||
const exported = buildAnalysisVisualExportOption(visual, width, 'report');
|
||||
const chart = echarts.init(null, undefined, {
|
||||
renderer: 'svg', width, height: exported.height, ssr: true,
|
||||
});
|
||||
chart.setOption(exported.option, { notMerge: true, lazyUpdate: false });
|
||||
return { ...exported, chart, svg: chart.renderToSVGString() };
|
||||
}
|
||||
|
||||
function displayedCategoryVisual() {
|
||||
const labels = productNames().slice(0, 3);
|
||||
return {
|
||||
id: 'displayed-category-pareto', type: 'pareto', title: '黑片来源类别重量柏拉图', subtitle: '仅显示全部正式类别', unit: 'kg',
|
||||
categories: [
|
||||
{ key: 'black_responsibility_scrap', label: labels[0] },
|
||||
{ key: 'black_material_scrap', label: labels[1] },
|
||||
{ key: 'black_external_scrap', label: labels[2] },
|
||||
],
|
||||
series: [{ key: 'source_defect_weight', label: '类别重量', values: [80, 15, 5] }],
|
||||
evidenceRefs: ['Q12345678'], requiredFields: ['source_defect_weight'], scope: { department: '新能源汽车磁钢' },
|
||||
period: { year: 2026 }, stage: 'black', metric: 'source_defect_weight',
|
||||
coverage: { totalRows: 3, returnedRows: 3, truncated: false, shareBasis: 'displayed_categories' },
|
||||
originTurnId: 'ranking-svg-layout-turn',
|
||||
};
|
||||
}
|
||||
|
||||
test('900px SVG SSR wraps 160-character Pareto labels without overlap or footer collision', () => {
|
||||
const names = productNames();
|
||||
const weights = [1000, 900, 800, 700, 600, 500, 400, 300, 200, 100];
|
||||
const parsed = parseAnalysisVisuals([rankingVisual(names, weights)]);
|
||||
assert.equal(parsed.visuals.length, 1);
|
||||
const model = parsed.visuals[0];
|
||||
assert.equal(model.chartable, true);
|
||||
|
||||
const rendered = renderExport(model);
|
||||
try {
|
||||
assert.match(rendered.svg, new RegExp(`<svg width="${WIDTH}" height="${rendered.height}"`));
|
||||
assert.equal(rendered.option.legend.data[1], '累计占全部重量');
|
||||
assert.equal(rendered.option.yAxis[1].name, '累计占全部重量');
|
||||
assert.equal(model.coverage.denominator, 10000);
|
||||
assert.deepEqual(rendered.option.xAxis.data.map(label => label.replaceAll('\n', '')), names);
|
||||
assert.deepEqual(rendered.option.series[0].data, weights);
|
||||
assert.deepEqual(visualParetoPoints(model).map(point => point.valueKg), weights);
|
||||
assert.deepEqual(visualParetoPoints(model).map(point => point.cumulativeShare),
|
||||
weights.map((_weight, index) => weights.slice(0, index + 1).reduce((sum, value) => sum + value, 0) / 10000));
|
||||
|
||||
const { categories, footerBounds } = svgTextBoxes(rendered.chart, rendered.option);
|
||||
assert.equal(categories.length, 10, 'SSR must render one positioned label group per product');
|
||||
assert.deepEqual(categories.map(category => category.text), names, 'all full product names must survive SVG layout');
|
||||
assert.ok(footerBounds.top >= 0 && footerBounds.bottom <= rendered.height,
|
||||
'export footer stays inside the SVG canvas');
|
||||
const maxLabelBottom = Math.max(...categories.map(category => category.bottom));
|
||||
assert.ok(maxLabelBottom < footerBounds.top && maxLabelBottom <= rendered.height,
|
||||
'all axis text ends above the footer and within the SVG canvas');
|
||||
for (const [index, category] of categories.entries()) {
|
||||
assert.ok(category.left >= -0.5, `label ${index} starts beyond the left canvas edge`);
|
||||
assert.ok(category.right <= WIDTH + 0.5, `label ${index} ends beyond the right canvas edge`);
|
||||
assert.ok(category.bottom < footerBounds.top, `label ${index} collides with the export footer`);
|
||||
if (index > 0) {
|
||||
assert.ok(categories[index - 1].right <= category.left + 0.5,
|
||||
`labels ${index - 1} and ${index} overlap horizontally`);
|
||||
}
|
||||
}
|
||||
|
||||
const axisTitle = rendered.chart.getZr().storage.getDisplayList(true).filter(element =>
|
||||
element.type === 'tspan' && element.style?.text === '累计占全部重量');
|
||||
assert.ok(axisTitle.length >= 1, 'full cumulative-weight axis title remains in SVG');
|
||||
for (const item of axisTitle) {
|
||||
const box = boundsInCanvas(item);
|
||||
assert.ok(box.left >= 0 && box.right <= WIDTH && box.top >= 0 && box.bottom < footerBounds.top,
|
||||
'axis title remains inside canvas and above the footer');
|
||||
}
|
||||
} finally {
|
||||
rendered.chart.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
test('all-scope export keeps denominator semantics and displayed_categories arithmetic unchanged', () => {
|
||||
const names = productNames();
|
||||
const weights = [1000, 900, 800, 700, 600, 500, 400, 300, 200, 100];
|
||||
const allScope = parseAnalysisVisuals([rankingVisual(names, weights)]).visuals[0];
|
||||
assert.equal(allScope.coverage.shareBasis, 'all_scope_weight');
|
||||
assert.equal(allScope.coverage.denominator, 10000);
|
||||
assert.equal(visualParetoPoints(allScope)[0].share, 1000 / 10000);
|
||||
|
||||
const displayed = parseAnalysisVisuals([displayedCategoryVisual()]).visuals[0];
|
||||
const exportResult = buildAnalysisVisualExportOption(displayed, WIDTH, 'report');
|
||||
const points = visualParetoPoints(displayed);
|
||||
assert.equal(displayed.coverage.shareBasis, 'displayed_categories');
|
||||
assert.equal(displayed.coverage.denominator, undefined);
|
||||
assert.deepEqual(exportResult.option.xAxis.data.map(label => label.replaceAll('\n', '')),
|
||||
displayed.categories.map(category => category.label));
|
||||
assert.deepEqual(exportResult.option.series[0].data, [80, 15, 5]);
|
||||
assert.equal(points[0].share, 80 / 100);
|
||||
assert.deepEqual(points.map(point => point.cumulativeShare), [0.8, 0.95, 1]);
|
||||
assert.deepEqual(exportResult.option.series[1].data, [80, 95, 100]);
|
||||
assert.equal(points.at(-1).cumulativeShare, 1);
|
||||
});
|
||||
@@ -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>核心结论验收</title></head><body><div id="root"></div><script type="module" src="./reading-summary.tsx"></script></body></html>
|
||||
@@ -0,0 +1,77 @@
|
||||
import React from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { AnalysisNarrative } from '../src/AnalysisNarrative';
|
||||
import { AnalysisReportNarrative } from '../src/AnalysisReportNarrative';
|
||||
import { compactNativeReportReading, integrateNativeReportNarrative } from '../src/nativeReportNarrative';
|
||||
import { renderVisualPng } from '../src/analysisVisualsModel';
|
||||
import '../src/styles.css';
|
||||
import '../src/analysis-chat.css';
|
||||
|
||||
const answer = `9月综合合格率95.13%,较8月下降0.44个百分点。[Q11111111]
|
||||
|
||||
### 阶段变化
|
||||
黑片合格率下降0.29个百分点,亮片合格率下降0.15个百分点。[Q11111111]
|
||||
|
||||
### 业务分组变化
|
||||
乙组下降1.90个百分点,甲组下降0.66个百分点,保持服务端按降幅的排名。[Q11111111]
|
||||
|
||||
### 具体缺陷变化
|
||||
缺角报废增加128.45 kg,是已核对的缺陷线索;仍需结合现场核查生产原因。[Q22222222]
|
||||
|
||||
| 缺陷 | 增量(kg) |
|
||||
| --- | --- |
|
||||
| 缺角 | 128.45 |
|
||||
| 末行:隐裂 | 12.00 |
|
||||
|
||||
### 覆盖说明
|
||||
亮片未覆盖全部月份,不能据此判定生产原因。`;
|
||||
const readingSummary = { version: 1, lead: '9月综合合格率下降0.44个百分点,缺角报废增加是已核对的缺陷线索,生产原因仍需现场核查。[Q11111111]',
|
||||
evidence: ['缺角报废增加128.45 kg。[Q22222222]', '业务分组合格率降幅:乙组第一,下降1.90个百分点;甲组第二,下降0.66个百分点。[Q11111111]'],
|
||||
notices: ['亮片未覆盖全部月份,不能据此判定生产原因。'], evidenceRefs: ['Q11111111', 'Q22222222'] };
|
||||
const turn = { id: 'reading-fixture', status: 'COMPLETED', question: '9月合格率下降原因', result: { answer, visuals: [], queryEvidenceRefs: ['Q11111111', 'Q22222222'], readingSummary } };
|
||||
const oldTurn = { ...turn, id: 'historical-fixture', result: { ...turn.result, readingSummary: undefined } };
|
||||
const nativeSource = '<!doctype html><html><head><title>9月质量分析报告</title></head><body><h1>9月质量分析报告</h1><p>第一段原始总体结论。</p><p>第二段原文。</p><p>第三段原文。</p><p>第四段缺角原因线索仍完整保留。</p><table><tbody><tr><td>末行:隐裂</td><td>12.00</td></tr></tbody></table></body></html>';
|
||||
const native = compactNativeReportReading(nativeSource, turn);
|
||||
const nativeDoc = new DOMParser().parseFromString(native, 'text/html');
|
||||
const nativeChecks = [nativeDoc.querySelector('.platform-reading-summary')?.textContent?.includes('缺角报废增加128.45'), nativeDoc.querySelector('.platform-full-content')?.textContent?.includes('第四段缺角原因线索仍完整保留'), nativeDoc.querySelector('.platform-full-content td')?.textContent === '末行:隐裂', compactNativeReportReading(nativeSource, oldTurn) === nativeSource];
|
||||
const historyRef = 'source-turn:fact:00001';
|
||||
const historyTurn = { id: 'history-report-fixture', question: '综合历史生成报告', result: { answer: '原始历史答案。', visuals: [], queryEvidenceRefs: [historyRef],
|
||||
readingSummary: { version: 1, lead: '已导入历史中的缺角线索增加128.45 kg。[' + historyRef + ']', evidence: [], notices: [], evidenceRefs: [historyRef] } } };
|
||||
const historySource = '<!doctype html><html><head><title>历史质量报告</title></head><body><table><tbody><tr><td>缺角原表</td><td>128.45</td></tr></tbody></table><details><summary>历史事实依据</summary><ol><li id="history-fact:' + historyRef + '" data-history-fact-id="' + historyRef + '">来源事实原文,缺角增加128.45 kg。</li></ol></details></body></html>';
|
||||
const historyNative = compactNativeReportReading(historySource, historyTurn);
|
||||
const historyDoc = new DOMParser().parseFromString(historyNative, 'text/html');
|
||||
const historyLink = historyDoc.querySelector('.platform-reading-summary a');
|
||||
const historyAnchor = historyDoc.getElementById('history-fact:' + historyRef);
|
||||
const missingAnchorDoc = new DOMParser().parseFromString(compactNativeReportReading('<html><body><p>原表尚无事实锚点</p></body></html>', historyTurn), 'text/html');
|
||||
const historyChecks = [!!historyAnchor, historyLink?.getAttribute('href') === '#' + encodeURIComponent(historyAnchor?.id || ''), historyDoc.querySelector('.platform-full-content td')?.textContent === '缺角原表', !historyDoc.querySelector('[id="platform-evidence-' + historyRef + '"]'), !missingAnchorDoc.querySelector('.platform-reading-summary a'), missingAnchorDoc.querySelector('.platform-reading-summary')?.textContent?.includes('[' + historyRef + ']')];
|
||||
const requestedChart = { id: 'explicit-rate-trend', type: 'line', title: '汽车交通月度综合合格率', subtitle: '', unit: 'ratio',
|
||||
categories: [{ key: '2026-08', label: '8月' }, { key: '2026-09', label: '9月' }], series: [{ key: 'composite_rate', label: '综合合格率', values: [0.9557, 0.9513] }],
|
||||
evidenceRefs: ['Q11111111'], requiredFields: ['black_good_weight', 'black_total_weight', 'bright_good_weight', 'bright_total_weight'],
|
||||
scope: { year: 2026, monthStart: 8, monthEnd: 9, releaseId: 'fixture-release', department: '汽车交通' }, period: { start: '2026-08', end: '2026-09', granularity: 'month', label: '2026-08 至 2026-09' },
|
||||
metric: 'composite_rate', originTurnId: 'explicit-required', sectionKey: 'trend', coverage: { totalRows: 2, returnedRows: 2, truncated: false } };
|
||||
const supplementaryChart = { ...requestedChart, id: 'supplementary-other-product', title: '其它规格补充趋势', scope: { ...requestedChart.scope, product: '附属规格' } };
|
||||
const requiredTurn = { id: 'explicit-required', question: '把2026年8到9月汽车交通月度综合率画成折线图', plan: { task: { visualPreference: 'required', visualType: 'line',
|
||||
kind: 'metrics', trendRequired: true, comparisonRequired: false, period: { year: 2026, monthStart: 8, monthEnd: 9 }, fields: ['rate'], stages: [], dimensions: [], filters: { department: '汽车交通' } } },
|
||||
result: { answer, visuals: [requestedChart, supplementaryChart], visualSchemaVersion: 1, queryEvidenceRefs: ['Q11111111', 'Q22222222'], readingSummary } };
|
||||
const chartPng = await renderVisualPng(requestedChart).catch(() => '');
|
||||
const supplementaryPng = await renderVisualPng(supplementaryChart).catch(() => '');
|
||||
const requiredImages = [{ id: requestedChart.id, png: chartPng }, { id: supplementaryChart.id, png: supplementaryPng }];
|
||||
const requiredNative = compactNativeReportReading(integrateNativeReportNarrative(nativeSource, requiredTurn, requiredImages), requiredTurn);
|
||||
const requiredDoc = new DOMParser().parseFromString(requiredNative, 'text/html');
|
||||
const requiredNode = requiredDoc.querySelector('[data-analysis-visual-id="explicit-rate-trend"]');
|
||||
const primaryChecks = [!!chartPng, !!requiredNode, requiredDoc.querySelectorAll('[data-analysis-visual-id="explicit-rate-trend"]').length === 1,
|
||||
!requiredDoc.querySelector('.platform-full-appendix [data-analysis-visual-id="explicit-rate-trend"]'), !!requiredDoc.querySelector('.platform-full-appendix [data-analysis-visual-id="supplementary-other-product"]')];
|
||||
const valid = [...nativeChecks, ...historyChecks, ...primaryChecks].every(Boolean);
|
||||
document.documentElement.dataset.fixtureStatus = valid ? 'passed' : 'failed';
|
||||
|
||||
createRoot(document.getElementById('root')!).render(<main style={{ maxWidth: 980, margin: '28px auto', padding: 28, background: '#fff' }}>
|
||||
<style>{'body{background:#f2f6fb}.fixture-block{margin:0 0 50px;border-bottom:1px solid #dfe5ef;padding-bottom:24px}.fixture-block>h2{font-size:17px;margin-bottom:22px;color:#66778d}.fixture-block iframe{border:0;width:100%;height:600px}.analysis-narrative{font-size:14px;line-height:1.85}.q-report .analysis-narrative{font-size:14px}'}</style>
|
||||
<section className="fixture-block"><h2>明确要求绘图:聊天主图</h2><AnalysisNarrative answer={answer} visuals={requiredTurn.result.visuals} question={requiredTurn.question} turnId={requiredTurn.id} turn={requiredTurn} /></section>
|
||||
<section className="fixture-block q-report"><h2>明确要求绘图:报告主图</h2><AnalysisReportNarrative answer={answer} turn={requiredTurn} images={requiredImages} /></section>
|
||||
<section className="fixture-block"><h2>明确要求绘图:原生报告</h2><p role="status">主图与补充图检查:{primaryChecks.every(Boolean) ? '通过' : '失败'}</p><iframe title="明确要求绘图的原生报告" srcDoc={requiredNative} /></section>
|
||||
<section className="fixture-block"><h2>聊天</h2><AnalysisNarrative answer={answer} visuals={[]} question={turn.question} turnId={turn.id} turn={turn} /></section>
|
||||
<section className="fixture-block q-report"><h2>报告</h2><AnalysisReportNarrative answer={answer} turn={turn} images={[]} /></section>
|
||||
<section className="fixture-block"><h2>历史答案</h2><AnalysisNarrative answer={answer} visuals={[]} question={turn.question} turnId={oldTurn.id} turn={oldTurn} /></section>
|
||||
<section className="fixture-block"><h2>历史报告真实事实引用</h2><AnalysisNarrative answer={historyTurn.result.answer} visuals={[]} question={historyTurn.question} turnId={historyTurn.id} turn={historyTurn} /><iframe title="历史原生报告" srcDoc={historyNative} /></section>
|
||||
<section className="fixture-block"><h2>原生 HTML 报告</h2><p role="status">原生报告完整性检查:{valid ? '通过' : '失败'}</p><iframe title="原生报告" srcDoc={native} /></section>
|
||||
</main>);
|
||||
@@ -0,0 +1 @@
|
||||
<!doctype html><html lang="zh-CN"><head><meta charset="UTF-8"><title>质量平台本地验收</title></head><body><div id="root"></div><script type="module" src="./reliability.tsx"></script></body></html>
|
||||
@@ -0,0 +1,85 @@
|
||||
// Local browser acceptance only. No API, database, model, or production writes.
|
||||
import React from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { App, ConfigProvider } from 'antd';
|
||||
import QueryPage from '../src/QueryPage';
|
||||
import ManagementPages from '../src/ManagementPages';
|
||||
import '../src/styles.css';
|
||||
import '../src/analysis-chat.css';
|
||||
|
||||
const scenario = new URL(location.href).searchParams.get('case') || 'live';
|
||||
const fixtureUser = { id: 'acceptance-fixture', username: 'fixture', displayName: '本地验收', roles: ['SYSTEM_ADMIN'], departments: [], groups: [] };
|
||||
const input = { mode: 'defects', period: { year: 2026, month: 9 }, stage: 'black' };
|
||||
const timeline = [
|
||||
{ sequence: 1, kind: 'assistant', text: '先核查9月黑片来源细分及对账覆盖。' },
|
||||
{ sequence: 2, kind: 'tool_start', tool: 'mcp_call', toolCallId: 'q1', label: '分析具体缺陷', input, status: 'started' },
|
||||
{ sequence: 3, kind: 'tool_result', tool: 'mcp_call', toolCallId: 'q1', label: '分析具体缺陷', status: 'completed', text: '证据:Q-fixture;返回 1 条结果;来源 10 行;细分与正式大类未对账:仅作为变化线索,不能据此判定正式报废主因' },
|
||||
{ sequence: 4, kind: 'assistant', text: '来源细分缺角重量为12.5 kg;这是变化线索,需核对正式大类。证据 Q-fixture。' },
|
||||
];
|
||||
let state = scenario === 'partial' ? 'PARTIAL' : ['history','legacy'].includes(scenario) ? 'COMPLETED' : scenario === 'retry' ? 'FAILED' : 'RUNNING';
|
||||
let sent = ['history','legacy','partial'].includes(scenario) ? 4 : scenario === 'retry' ? 3 : 0;
|
||||
let sessionTitle = '验收模拟会话';
|
||||
let attempt = 0;
|
||||
const answer = timeline[3].text;
|
||||
const turn = () => ({ id: 'fixture-turn', sessionId: 'fixture-session', status: state, startedAt: '2026-10-23T05:21:11Z', ...(scenario==='partial'?{finishedAt:'2026-10-23T05:25:23Z',durationMs:252000,stopReason:'mcp_error'}:{}),question: '验收模拟:核查9月黑片来源缺陷', engine: 'NAO', answer: sent === 4 ? answer : '', plan: scenario==='legacy'?{nativeRuntime:true,steps:[{label:'核查来源',status:'completed',outputSummary:'已返回结果'}]}:{ nativeRuntime: true, timeline: timeline.slice(0, sent) }, context: { year: 2026, view: 'overall' }, result: { engine: 'NAO', answer: sent === 4 ? answer : '', ...(scenario==='legacy'?{}:{timeline: timeline.slice(0,sent)}) } });
|
||||
const json = (value: unknown) => new Response(JSON.stringify(value), {headers:{'Content-Type':'application/json'}});
|
||||
const encoder = new TextEncoder();
|
||||
window.fetch = async (target, init) => {
|
||||
const url = new URL(String(target), location.origin);
|
||||
const path = url.pathname;
|
||||
if (path === '/api/auth/csrf') return json({token:'fixture-only'});
|
||||
if (path === '/api/options') {
|
||||
if (scenario === 'gateway') return new Response('<html><h1>502 Bad Gateway</h1></html>', {status:502});
|
||||
return json({years:[2026],departments:[],groups:[],products:[],releases:[{id:'fixture-release',name:'本地验收',status:'PUBLISHED'}]});
|
||||
}
|
||||
if (path === '/api/metrics' && scenario==='network') throw new TypeError('Failed to fetch');
|
||||
if (path === '/api/metrics' && scenario==='empty') {
|
||||
const stage={qualifiedWeight:null,scrapWeight:null,totalWeight:null,rate:null,defects:[]};
|
||||
const summary={key:'overall',label:'全公司',department:null,group:null,product:null,compositeRate:null,black:stage,bright:stage,coverage:{blackRows:0,brightRows:0}};
|
||||
return json({release:null,context:{},summary,rows:[],trend:[],defects:{black:[],bright:[]},coverage:{rawRows:0,includedRows:0,excludedBlankRows:0,unmappedRows:0,projectGroupUnconfiguredRows:0,missingStages:[],sourceMonths:[]}});
|
||||
}
|
||||
if (path === '/api/metrics') return new Response('<html><h1>502 Bad Gateway</h1></html>', {status:502});
|
||||
if (path === '/api/filter-fields') return json([]);
|
||||
if (path === '/api/analytics/targets') return json({items:[]});
|
||||
if (path === '/api/analysis/sessions/fixture-session' && init?.method==='PATCH') {sessionTitle=JSON.parse(String(init.body)).title;return json({sessionId:'fixture-session',title:sessionTitle});}
|
||||
if (path === '/api/analysis/sessions') return json({items:[{id:'fixture-session',title:sessionTitle,activeTurnStatus:state,updatedAt:'2026-10-23'}]});
|
||||
if (path === '/api/analysis/sessions/fixture-session') return json({id:'fixture-session',releaseId:'fixture-release',context:{year:2026,view:'overall'},turns:[{...turn(),result:turn().result}]});
|
||||
if (path === '/api/analysis/sessions/fixture-session/turns') return json({items:[turn()]});
|
||||
if (path === '/api/analysis/turns/fixture-turn') return json(turn());
|
||||
if (path.endsWith('/cancel')) { state='CANCELLED'; return json({status:state}); }
|
||||
if (path.endsWith('/retry')) {state='RUNNING';sent=0;attempt=0;return json({turn:turn()});}
|
||||
if (path.endsWith('/events')) {
|
||||
attempt++;
|
||||
const currentAttempt=attempt;
|
||||
let cancelled=false;
|
||||
const body=new ReadableStream({
|
||||
start(controller) {
|
||||
const emit=(id:number, event:string, data:unknown) => { if (!cancelled) controller.enqueue(encoder.encode(`id: ${id}\nevent: ${event}\ndata: ${JSON.stringify(data)}\n\n`)); };
|
||||
const send=(count:number,id:number) => {sent=count;emit(id,'progress',{status:'RUNNING',message:'正在核查模拟数据',timeline:timeline.slice(0,count)});};
|
||||
send(1,1);
|
||||
setTimeout(()=>send(2,2),250);
|
||||
setTimeout(()=>{
|
||||
if (scenario==='disconnect' && currentAttempt===1) { cancelled=true;controller.error(new TypeError('fixture disconnect'));return; }
|
||||
if (scenario==='cancel') return;
|
||||
send(3,3);
|
||||
// A duplicate and an out-of-order snapshot must not overwrite the newer state.
|
||||
emit(3,'progress',{status:'RUNNING',timeline:[]});
|
||||
emit(2,'progress',{status:'RUNNING',timeline:[]});
|
||||
},550);
|
||||
setTimeout(()=>{
|
||||
if (cancelled) return;
|
||||
if (scenario==='cancel') {if(state==='CANCELLED'){emit(4,'cancelled',{status:state,result:turn().result});controller.close();cancelled=true;}return;}
|
||||
sent=4;state='COMPLETED';
|
||||
emit(4,'completed',{status:state,result:turn().result});
|
||||
controller.close();cancelled=true;
|
||||
},scenario==='cancel'?7000:1600);
|
||||
},
|
||||
cancel(){cancelled=true;},
|
||||
});
|
||||
init?.signal?.addEventListener('abort',()=>{void body.cancel().catch(()=>{});});
|
||||
return new Response(body,{headers:{'Content-Type':'text/event-stream'}});
|
||||
}
|
||||
return json({items:[]});
|
||||
};
|
||||
const stopUnauthorized=()=>false;
|
||||
createRoot(document.getElementById('root')!).render(<ConfigProvider><App><main style={{padding:24,maxWidth:1400,margin:'auto'}}><p role="note">本地验收模拟数据,不是业务结论 · 场景 {scenario}</p>{['gateway','empty','network'].includes(scenario)?<QueryPage page="overall" onUnauthorized={stopUnauthorized}/>:<ManagementPages page="analysis" user={fixtureUser} onUnauthorized={stopUnauthorized} onNavigate={()=>{}}/>}</main></App></ConfigProvider>);
|
||||
@@ -0,0 +1 @@
|
||||
<!doctype html><html lang="zh-CN"><meta charset="UTF-8"><title>计算规则文案预览(模拟数据)</title><div id="root"></div><script type="module" src="./rules-business-copy.tsx"></script></html>
|
||||
@@ -0,0 +1,15 @@
|
||||
import React from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { App, ConfigProvider } from 'antd';
|
||||
import ManagementPages from '/src/ManagementPages';
|
||||
import '/src/styles.css';
|
||||
const json = (v: unknown) => new Response(JSON.stringify(v), {headers:{'Content-Type':'application/json'}});
|
||||
const items = [{"code": "COMPOSITE_RATE", "name": "综合合格率", "formula": "黑片合格率 × 亮片合格率;月、季、年先汇总重量再计算,不平均月度合格率", "unit": "%", "dimensions": ["期间", "产业部", "业务分组", "产品", "项目组"], "enabled": true, "description": "按当前筛选范围汇总计算。", "aliases": []}, {"code": "BLACK_RATE", "name": "黑片合格率", "formula": "黑片合格重量 ÷ 黑片适用总重量;适用总重量扣除利用料及废品库相关重量,结果允许超过100%;分母为零或空时取1", "unit": "%", "dimensions": ["期间", "产业部", "业务分组", "产品", "项目组"], "enabled": true, "description": "按当前筛选范围汇总计算。", "aliases": []}, {"code": "BRIGHT_RATE", "name": "亮片合格率", "formula": "适用亮片合格重量 ÷(适用亮片合格重量 + 适用亮片报废重量);仅统计来料标志为“是”的记录,分母为零或空时取1", "unit": "%", "dimensions": ["期间", "产业部", "业务分组", "产品", "项目组"], "enabled": true, "description": "按当前筛选范围汇总计算。", "aliases": []}, {"code": "BRIGHT_RATE_WITHOUT_HEADQUARTERS_SCRAP", "name": "亮片合格率(去本部报废)", "formula": "(适用亮片合格重量 + 当前范围全部本部报废重量)÷ 亮片适用总重量;分母不变", "unit": "%", "dimensions": ["期间", "产业部", "业务分组", "产品", "项目组"], "enabled": true, "description": "按当前筛选范围汇总计算。", "aliases": []}, {"code": "COMPOSITE_RATE_WITHOUT_HEADQUARTERS_SCRAP", "name": "综合合格率(去本部报废)", "formula": "黑片合格率 × 去本部报废后的亮片合格率", "unit": "%", "dimensions": ["期间", "产业部", "业务分组", "产品", "项目组"], "enabled": true, "description": "按当前筛选范围汇总计算。", "aliases": []}];
|
||||
window.fetch = async (target) => {
|
||||
const path = new URL(String(target),location.origin).pathname;
|
||||
if(path==='/api/rules') return json({items:[{id:'example',name:'基础计算规则',status:'ACTIVE',createdAt:'2026-10-29',definition:{metricRules:{blackRate:{formula:'blackGood / blackTotal',zeroDenominatorPolicy:'ONE',nullResultPolicy:'ONE'}}}}]});
|
||||
if(path==='/api/metric-dictionary') return json({items: items.map((item, index) => ({...item, formulaStatus:new URLSearchParams(location.search).get('scenario') === 'missing' ? 'NO_CURRENT_DATA' : 'CURRENT', currentFormula:index === 1 && new URLSearchParams(location.search).get('scenario') === 'custom' ? 'blackGood / (blackTotal + 7);运算空值=ZERO;零分母=ZERO;空结果=NULL' : item.formula}))});
|
||||
if(path==='/api/data-workflow/status') return json({simplified:true,mode:'TEST',capabilities:{canApplyRule:false},activeRule:{id:'example',name:'基础计算规则',definition:{rowRules:[{stage:'black',target:'black_good_weight',formula:'platingWeight + shipmentWeight',nullPolicy:'PROPAGATE'}],metricRules:{blackRate:{formula:'blackGood / blackTotal',zeroDenominatorPolicy:'ONE'}}}}});
|
||||
return json({items:[]});
|
||||
};
|
||||
createRoot(document.getElementById('root')!).render(<ConfigProvider><App><div style={{padding:24,background:'#f1f7fa',minHeight:'100vh'}}><ManagementPages page="rules" user={{id:'preview',username:'preview',displayName:'预览',roles:['QUALITY_VIEWER']}} onUnauthorized={()=>false} onNavigate={()=>{}} /></div></App></ConfigProvider>);
|
||||
@@ -0,0 +1 @@
|
||||
<!doctype html><html lang="zh-CN"><meta charset="UTF-8"><title>来源字段预览(模拟数据)</title><div id="root"></div><script type="module" src="./source-fields-clean.tsx"></script></html>
|
||||
@@ -0,0 +1,8 @@
|
||||
import React, {useState} from 'react';
|
||||
import {createRoot} from 'react-dom/client';
|
||||
import {App} from 'antd';
|
||||
import {RuleDefinitionEditor} from '../src/StructuredConfigEditors';
|
||||
import '../src/styles.css';
|
||||
const schema={schemaVersion:'preview',sourceFields:{black:{platingWeight:'送电镀重量',shipmentWeight:'黑片出货重量'},bright:{applicability:'是否电镀来料/二等品库来料',goodWeight:'合格重量',scrapWeight:'检包入废品库重量',headquartersScrap:'本部报废重量',platingScrap:'镀废重量合计',materialScrap:'材料废重量合计',processingScrap:'加工废重量合计',diffusionScrap:'晶界扩散报废合计重量'}}};
|
||||
function Preview(){const[value,setValue]=useState({schemaVersion:'preview'} as Record<string,unknown>);return <App><main style={{padding:32,background:'white'}}><RuleDefinitionEditor value={value} onChange={setValue} schema={schema} schemaError="" /></main></App>}
|
||||
createRoot(document.getElementById('root')!).render(<Preview/>);
|
||||
@@ -0,0 +1 @@
|
||||
<!doctype html><html lang="zh-CN"><meta charset="UTF-8"><title>黑片亮片查询预览</title><output id="request-log" hidden></output><output id="fine-request-log" hidden></output><div id="root"></div><script type="module" src="./stage-products.tsx"></script></html>
|
||||
@@ -0,0 +1,22 @@
|
||||
const json=(value:unknown)=>new Response(JSON.stringify(value),{headers:{'Content-Type':'application/json'}});
|
||||
const requests:unknown[]=[];
|
||||
const user={id:'preview',username:'admin',displayName:'admin',roles:['SYSTEM_ADMIN'],departments:['*'],groups:['*']};
|
||||
const fields=[{key:'customer',label:'客户代码',type:'source_value',stages:['black','bright'],columns:{black:'客户代码',bright:'客户代码'}},{key:'blackBatch',label:'黑片批号',type:'source_value',stages:['black'],columns:{black:'黑片批号'}},{key:'brightBatch',label:'亮片批号',type:'source_value',stages:['bright'],columns:{bright:'亮片批号'}}];
|
||||
const metric=(qualified:number,scrap:number)=>({qualifiedWeight:qualified,scrapWeight:scrap,totalWeight:qualified+scrap,rate:qualified/(qualified+scrap),headquartersScrapWeight:0,rateWithoutHeadquartersScrap:qualified/(qualified+scrap),defects:[{name:'材料废',weight:scrap*.5,rate:.5},{name:'加工废',weight:scrap*.3,rate:.3},{name:'镀废',weight:scrap*.2,rate:.2}]});
|
||||
window.fetch=async(target,init)=>{
|
||||
const url=new URL(String(target),location.origin),path=url.pathname;
|
||||
if(path==='/api/auth/me')return json({user});if(path==='/api/auth/csrf')return json({token:'local-preview'});if(path==='/api/workspace/state')return json({authRevision:'preview',dataRevision:'preview'});
|
||||
if(path==='/api/options')return json({years:[2026],departments:['汽车交通产业部','工业电机产业部'],groups:['汽车交通-国内','汽车交通-海外','工业电机-中国区'],products:['P001 磁钢','P002 磁环'],projectGroupStatus:'READY',projectGroups:['新能源汽车'],groupDepartments:{'汽车交通-国内':'汽车交通产业部','汽车交通-海外':'汽车交通产业部','工业电机-中国区':'工业电机产业部'},organizationPaths:[{department:'汽车交通产业部',group:'汽车交通-国内',product:'P001 磁钢'},{department:'工业电机产业部',group:'工业电机-中国区',product:'P002 磁环'}]});
|
||||
if(path==='/api/analysis/source/catalog')return json({releaseId:'preview-published',sourceFields:fields});
|
||||
if(path==='/api/analysis/source/values')return json({values:['0007','0012','0090'],hasMore:false,totalCount:3});
|
||||
if(path==='/api/metrics'){
|
||||
const stage=url.searchParams.get('stage')==='black'?'black':'bright',filters=JSON.parse(url.searchParams.get('columnFilters')||'[]');requests.push({stage,filters,trendGranularity:url.searchParams.get('trendGranularity'),group:url.searchParams.get('group'),department:url.searchParams.get('department')});document.getElementById('request-log')!.textContent=JSON.stringify(requests);
|
||||
const selected=stage==='black'?metric(900,100):metric(920,80),empty={qualifiedWeight:0,scrapWeight:0,totalWeight:0,rate:null,defects:[]};
|
||||
const row={key:'P001',label:'P001 磁钢',department:'汽车交通产业部',group:'汽车交通-国内',product:'P001 磁钢',projectGroup:'新能源汽车',black:stage==='black'?selected:empty,bright:stage==='bright'?selected:empty,compositeRate:selected.rate,coverage:{blackRows:stage==='black'?20:0,brightRows:stage==='bright'?20:0}};
|
||||
return json({release:{id:'preview-published',name:'当前数据',status:'PUBLISHED'},context:{stage,metricFormulaDescriptions:{blackRate:'黑片合格重量 / 黑片适用总重量',brightRate:'亮片合格重量 / 亮片适用总重量',brightRateWithoutHeadquartersScrap:'(亮片合格重量 + 本部报废重量)/ 亮片适用总重量'}},summary:row,rows:[row,{...row,key:'P002',label:'P002 磁环',product:'P002 磁环',[stage]:stage==='black'?metric(1800,200):metric(460,40)}],trend:(url.searchParams.get('trendGranularity')==='year'?[2024,2025,2026].map(year=>({...row,year,month:String(year),period:String(year),periodLabel:`${year}年`,granularity:'year'})):url.searchParams.get('trendGranularity')==='quarter'?[1,2,3].map(quarter=>({...row,quarter,month:`2026-Q${quarter}`,period:`2026-Q${quarter}`,periodLabel:`第${quarter}季度`,granularity:'quarter'})):[7,8,9].map(month=>({...row,month:`2026-${String(month).padStart(2,'0')}`,period:`2026-${String(month).padStart(2,'0')}`,periodLabel:`${month}月`,granularity:'month'}))),defects:{black:row.black.defects,bright:row.bright.defects},coverage:{rawRows:20,includedRows:20,excludedBlankRows:0,unmappedRows:0,projectGroupUnconfiguredRows:0,missingStages:[],sourceMonths:[{year:2026,month:9,...row.coverage}]}});
|
||||
}
|
||||
if(path==='/api/analysis/defects'){const body=JSON.parse(String(init?.body||'{}'));document.getElementById('fine-request-log')!.textContent=JSON.stringify(body);const rows=[{key:'裂纹',label:'裂纹',category:'材料废',weight:40},{key:'缺角',label:'缺角',category:'加工废',weight:25},{key:'镀层不良',label:'镀层不良',category:'镀废',weight:15}];return json({kind:'fine_defect_top',releaseId:'preview-published',sourceRows:20,rows,sourceFields:rows,coverage:{categories:[]}});}
|
||||
if(path==='/api/records')return json({rows:[],total:0,page:1,pageSize:20});
|
||||
return json({items:[]});
|
||||
};
|
||||
await import('../src/main');
|
||||
@@ -0,0 +1,25 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { activeStageFilters, stageProductQuery, sortStageRowsByTotalWeight } from '../src/stageProductQuery.ts';
|
||||
test('stage query preserves all organizational selections and only its stage',()=>{
|
||||
const original={year:2026,month:9,view:'product',department:'产业部A',group:'业务组A',product:'产品A',releaseId:'published'};
|
||||
const rule={field:'customer',stages:['bright'],operator:'in',values:['0007','0']};
|
||||
const query=stageProductQuery(original,'black',[rule]);
|
||||
assert.equal(query.stage,'black');assert.equal(query.group,'业务组A');assert.equal(query.department,'产业部A');assert.deepEqual(query.columnFilters[0].values,['0007','0']);assert.deepEqual(query.columnFilters[0].stages,['black']);assert.deepEqual(rule.stages,['bright']);
|
||||
});
|
||||
test('unfilled selections do not become empty IN filters, explicit empty checks remain',()=>{
|
||||
const filters=[{field:'a',stages:['black'],operator:'in',values:[]},{field:'b',stages:['black'],operator:'is_empty',values:[]}];
|
||||
assert.deepEqual(activeStageFilters(filters,'black').map(v=>v.field),['b']);
|
||||
});
|
||||
test('product rows sort by selected stage total descending without mutating rows; ties are stable and unknown totals are last',()=>{
|
||||
const rows=[
|
||||
{key:'unknown',black:{totalWeight:null},bright:{totalWeight:10}},
|
||||
{key:'small',black:{totalWeight:10},bright:{totalWeight:40}},
|
||||
{key:'large',black:{totalWeight:30},bright:{totalWeight:20}},
|
||||
{key:'tie',black:{totalWeight:30},bright:{totalWeight:30}},
|
||||
{key:'negative',black:{totalWeight:-5},bright:{totalWeight:0}},
|
||||
];
|
||||
assert.deepEqual(sortStageRowsByTotalWeight(rows,'black').map(row=>row.key),['large','tie','small','negative','unknown']);
|
||||
assert.deepEqual(sortStageRowsByTotalWeight(rows,'bright').map(row=>row.key),['small','tie','large','unknown','negative']);
|
||||
assert.deepEqual(rows.map(row=>row.key),['unknown','small','large','tie','negative']);
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { alertsForStatus, alertObject, backupSummary, orderedTasks, taskFailure, taskPercent } from '../src/taskMonitorModel.ts';
|
||||
test('recovered alerts do not appear as current alerts; backend objectId is used',()=>{
|
||||
const alerts=[{status:'RECOVERED',alertType:'BACKUP_STALE'},{status:'OPEN',alertType:'TASK_FAILURE',objectId:'task-1'}];
|
||||
assert.equal(alertsForStatus(alerts,'OPEN').length,1);assert.equal(alertObject(alerts[0]),'备份');assert.equal(alertObject(alerts[1]),'task-1');
|
||||
});
|
||||
test('unknown progress stays unknown and does not become a made-up zero',()=>{
|
||||
assert.equal(taskPercent({status:'RUNNING'}),null);assert.equal(taskPercent({status:'COMPLETED'}),100);
|
||||
assert.equal(taskPercent({status:'RUNNING',progress:36.5}),36.5);
|
||||
});
|
||||
test('failures are readable from workflow errors and successful tasks do not show stale errors',()=>{
|
||||
assert.equal(taskFailure({status:'FAILED',errors:[{code:'X',message:'来源文件缺失'}]}),'来源文件缺失');
|
||||
assert.equal(taskFailure({status:'COMPLETED',errorMessage:'旧错误'}),'—');
|
||||
assert.equal(taskFailure({status:'PARTIAL',errorMessage:'evidence_incomplete'}),'分析证据不完整,本轮仅部分完成');
|
||||
});
|
||||
test('active and failed tasks remain visible ahead of recent successes; filters preserve partial results',()=>{
|
||||
const tasks=[{status:'COMPLETED',createdAt:'2026-10-29'},{status:'FAILED',createdAt:'2026-10-20'},{status:'RUNNING',createdAt:'2026-10-21'},{status:'PARTIAL',createdAt:'2026-10-22'}];
|
||||
assert.deepEqual(orderedTasks(tasks,'all').map(r=>r.status),['RUNNING','PARTIAL','FAILED','COMPLETED']);
|
||||
assert.equal(orderedTasks(tasks,'failed').length,2);assert.equal(tasks[0].status,'COMPLETED');
|
||||
});
|
||||
test('backup summary does not claim full file verification from a database-only restore',()=>{
|
||||
assert.equal(backupSummary({}),'暂无备份记录');
|
||||
assert.equal(backupSummary({createdAt:'2026-10-29',status:'BACKUP_CREATED_NOT_RESTORE_VERIFIED'}),'已备份,未验证恢复');
|
||||
const b={createdAt:'2026-10-29',status:'ISOLATED_RESTORE_VERIFIED',verification:{databaseRestoreVerified:true}};
|
||||
assert.notEqual(backupSummary(b),'数据库及文件恢复验证通过');
|
||||
for(const key of ['applicationFilesVerified','requiredApplicationInputsVerified','archiveFilesVerified','archiveReferencesVerified'])b.verification[key]=true;
|
||||
assert.equal(backupSummary(b),'数据库及文件恢复验证通过');
|
||||
b.verification.applicationStartupVerified=false;assert.equal(backupSummary(b),'数据库及文件恢复验证通过');
|
||||
});
|
||||
@@ -0,0 +1 @@
|
||||
<!doctype html><html lang="zh-CN"><meta charset="UTF-8"><title>任务页本地验收</title><output id="requests" hidden></output><div id="root"></div><script type="module" src="./tasks-monitor.tsx"></script></html>
|
||||
@@ -0,0 +1,30 @@
|
||||
import React from 'react';
|
||||
import {createRoot} from 'react-dom/client';
|
||||
import {App,ConfigProvider} from 'antd';
|
||||
import zhCN from 'antd/locale/zh_CN';
|
||||
import {TasksMonitorPage} from '../src/TasksMonitorPage';
|
||||
import data from './tasks-monitor-data.json';
|
||||
import '../src/styles.css';
|
||||
const params=new URLSearchParams(location.search);
|
||||
const role=params.get('role')==='maintainer'?'DATA_MAINTAINER':'SYSTEM_ADMIN';
|
||||
const scenario=params.get('scenario');
|
||||
const json=(value:unknown)=>new Response(JSON.stringify(value),{headers:{'Content-Type':'application/json'}});
|
||||
const calls:string[]=[];
|
||||
const recent=data.backups.items.reduce((a,b)=>String(b.createdAt)>String(a.createdAt)?b:a,data.backups.items[0]);
|
||||
window.fetch=async target=>{
|
||||
const path=new URL(String(target),location.origin).pathname;
|
||||
calls.push(path);document.getElementById('requests')!.textContent=JSON.stringify(calls);
|
||||
if(path==='/api/tasks/overview')return json({items:scenario==='empty'?[]:[
|
||||
{id:'running-preview',sourceKind:'WORKFLOW',type:'WORKFLOW_RECALCULATE',status:'RUNNING',stage:'REBUILDING',createdAt:'2026-10-29T06:00:00Z'},
|
||||
{id:'failure-preview',sourceKind:'WORKFLOW',type:'WORKFLOW_APPLY_RULE',status:'FAILED',errors:[{message:'来源文件缺失,请重新接入文件后再试。'}],createdAt:'2026-10-29T05:55:00Z'},
|
||||
...data.tasks.items.map(row=>({...row,sourceKind:'TASK'}))]});
|
||||
if(path==='/api/governance/backups/latest')return json({latest:scenario==='empty'?{}:recent,planActive:data.backups.plan.active});
|
||||
if(role!=='SYSTEM_ADMIN')return new Response('{}',{status:403});
|
||||
if(path==='/api/governance/backups')return json(data.backups);
|
||||
if(path==='/api/governance/monitor')return json({...data.monitor,summary:{...data.monitor.summary,openAlerts:scenario==='open'?1:0},alerts:scenario==='open'?[...data.monitor.alerts,{id:'open-preview',alertType:'TASK_FAILURE',severity:'ERROR',status:'OPEN',objectId:'fixture-task',message:'来源文件缺失,请重新接入文件后再试。',lastSeen:'2026-10-29T06:00:00Z'}]:data.monitor.alerts});
|
||||
if(path==='/api/governance/monitor/alert-policy')return json({policy:{queueAgeMinutes:30,backupAgeHours:24}});
|
||||
if(path.includes('inspection-strategies'))return json(data.strategies);
|
||||
return json({items:[]});
|
||||
};
|
||||
const unauthorized=()=>false;
|
||||
createRoot(document.getElementById('root')!).render(<ConfigProvider locale={zhCN}><App><main style={{padding:24,background:'#f2f7fb',minHeight:'100vh'}}><TasksMonitorPage user={{id:'preview',username:'preview',displayName:'本地验收',roles:[role],departments:[],groups:[]}} onUnauthorized={unauthorized}/></main></App></ConfigProvider>);
|
||||
@@ -0,0 +1 @@
|
||||
<!doctype html><html lang="zh-CN"><head><meta charset="UTF-8"><title>思考折叠交互验收</title></head><body><div id="root"></div><script type="module" src="./thinking-lifecycle.tsx"></script></body></html>
|
||||
@@ -0,0 +1,27 @@
|
||||
import React,{useState,useEffect} from 'react';
|
||||
import {createRoot} from 'react-dom/client';
|
||||
import {AnalysisThinkingBlock} from '../src/ModelThinkingPanel';
|
||||
import '../src/styles.css';
|
||||
import '../src/analysis-chat.css';
|
||||
function Fixture(){
|
||||
const [step,setStep]=useState(0);
|
||||
const [stream,setStream]=useState('');
|
||||
useEffect(()=>{
|
||||
if(step!==3)return;
|
||||
setStream('');let index=0;
|
||||
const timer=setInterval(()=>{
|
||||
index++;setStream(('核对已返回的查询依据,按指定期间和黑片阶段整理缺陷排名。🙂\n').repeat(index));
|
||||
if(index===15)clearInterval(timer);
|
||||
},200);
|
||||
return ()=>clearInterval(timer);
|
||||
},[step]);
|
||||
return <main style={{padding:24,maxWidth:900,margin:'auto'}}>
|
||||
<div style={{display:'flex',gap:12,marginBottom:16}}>
|
||||
<button onClick={()=>setStep(1)}>模拟思考结束</button>
|
||||
<button onClick={()=>setStep(2)}>模拟后续相邻调用</button>
|
||||
<button onClick={()=>setStep(3)}>模拟流式思考</button>
|
||||
</div>
|
||||
<AnalysisThinkingBlock running={true} entry={{id:step===3?'api-abcd1234-2':'api-abcd1234-1',source:'api',model:'local-fixture',phase:'analysis',version:step+1,status:step===1?'completed':'running',text:step===3?stream:'第一段已经收到的思考全文。'+(step===2?'后续调用补充的原始文字。':''),streaming:true,truncated:false}}/>
|
||||
</main>;
|
||||
}
|
||||
createRoot(document.getElementById('root')!).render(<Fixture/>);
|
||||
@@ -0,0 +1 @@
|
||||
<!doctype html><html lang="zh-CN"><head><meta charset="UTF-8"><title>思考全文本地验收</title></head><body><div id="root"></div><script type="module" src="./thinking.tsx"></script></body></html>
|
||||
@@ -0,0 +1,32 @@
|
||||
// Explicit synthetic transport fixture. No API, model, database or production writes.
|
||||
import React,{useEffect,useState} from 'react';
|
||||
import {createRoot} from 'react-dom/client';
|
||||
import {AnalysisProcess} from '../src/AnalysisProcess';
|
||||
import {mergeModelThinking} from '../src/analysisModelThinking';
|
||||
import '../src/styles.css';
|
||||
import '../src/analysis-chat.css';
|
||||
|
||||
function Fixture(){
|
||||
const [running,setRunning]=useState(false),[rows,setRows]=useState<any[]>([]),[night,setNight]=useState(false);
|
||||
useEffect(()=>{
|
||||
if(!running)return;
|
||||
let version=1;
|
||||
const base={id:'api-abcd1234-1',source:'api',model:'模拟接口',phase:'analysis',status:'running',streaming:true,truncated:false};
|
||||
setRows(mergeModelThinking([],{...base,version:1,text:'本页仅模拟接口返回文本,用于验收长文、滚动与换行。\n'}));
|
||||
const timer=setInterval(()=>{version++;setRows(prior=>mergeModelThinking(prior,{...base,version,baseVersion:version-1,
|
||||
delta:`模拟文本第${version}段:这是接口返回的完整文本,验证长内容保持原样,不压缩成摘要。\n中文与🙂保持完整;<img src=x onerror=alert(1)>作为纯文本展示,不执行。\n`.repeat(3)}));},300);
|
||||
return()=>clearInterval(timer);
|
||||
},[running]);
|
||||
return <main style={{maxWidth:1040,margin:'auto',padding:24,minHeight:'100vh',background:night?'#182435':'#fff',color:night?'#e3eaf4':'#263c5a',
|
||||
'--ink':night?'#e3eaf4':'#263c5a','--muted-ink':night?'#9aaec8':'#63758b','--line':night?'#34465f':'#e5ebf3'} as React.CSSProperties}>
|
||||
<p role="note">本地模拟验收,不是模型分析或业务结论。</p>
|
||||
<div style={{display:'flex',gap:12,marginBottom:18}}>
|
||||
<button onClick={()=>setRunning(true)} disabled={running}>开始模拟输出</button>
|
||||
<button onClick={()=>{setRunning(false);setRows(prior=>prior.map(row=>({...row,status:'completed',version:row.version+1})));}}>结束输出</button>
|
||||
<button onClick={()=>setNight(value=>!value)}>切换明暗主题</button>
|
||||
</div>
|
||||
<AnalysisProcess turn={{id:'thinking-fixture',status:running?'RUNNING':'COMPLETED',modelThinking:rows,answer:running?'':'模拟输出已结束。'}}/>
|
||||
<p>正文区域保持独立,思考文本不会作为正式结论。</p>
|
||||
</main>;
|
||||
}
|
||||
createRoot(document.getElementById('root')!).render(<Fixture/>);
|
||||
@@ -0,0 +1,47 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as echarts from 'echarts/core';
|
||||
import {LineChart,BarChart} from 'echarts/charts';
|
||||
import {GridComponent,LegendComponent,TooltipComponent,GraphicComponent,TitleComponent} from 'echarts/components';
|
||||
import {SVGRenderer} from 'echarts/renderers';
|
||||
import {buildAnalysisVisualExportOption} from '../src/analysisVisualsModel.ts';
|
||||
echarts.use([LineChart,BarChart,GridComponent,LegendComponent,TooltipComponent,GraphicComponent,TitleComponent,SVGRenderer]);
|
||||
function visual(type='line') {
|
||||
const values=[.9025,.8931,.9012,.8671,.8914,.8982,.8606,.8639,.8794];
|
||||
return {id:'monthly-export',type,title:'正式指标趋势',unit:'ratio',
|
||||
categories:values.map((_,i)=>({key:`2026-${String(i+1).padStart(2,'0')}`,label:`2026-${String(i+1).padStart(2,'0')}`})),
|
||||
series:[{key:'composite_rate',label:'综合合格率',values}],scope:{releaseId:'release'},
|
||||
period:{start:'2026-01',end:'2026-09',granularity:'month'},metric:'composite_rate',sectionKey:'trend',
|
||||
evidenceRefs:['Q12345678'],requiredFields:['black_good_weight','black_total_weight','bright_good_weight','bright_total_weight'],
|
||||
coverage:{totalRows:9,returnedRows:9,truncated:false},originTurnId:'export-turn'};
|
||||
}
|
||||
for(const type of ['line','area'])test(`900px report ${type} keeps a positive plot and the actual monthly vertical movement`,()=>{
|
||||
const v=visual(type),out=buildAnalysisVisualExportOption(v,900,'report');
|
||||
const chart=echarts.init(null,undefined,{renderer:'svg',width:out.width,height:out.height,ssr:true});
|
||||
try {
|
||||
chart.setOption(out.option,{notMerge:true});
|
||||
const rect=chart.getModel().getComponent('grid').coordinateSystem.getRect();
|
||||
assert.ok(rect.height>=180,`plot collapsed: ${rect.height}`);
|
||||
assert.ok(rect.y+rect.height+30<out.height,'category labels need space below plot');
|
||||
const points=Array.from(chart.getModel().getSeriesByIndex(0).getData().getLayout('points'));
|
||||
assert.equal(points.length,18);
|
||||
const ys=points.filter((_,i)=>i%2===1);
|
||||
assert.ok(Math.max(...ys)-Math.min(...ys)>8,'different rates must not become a flat line');
|
||||
ys.forEach((y,i)=>assert.ok(Math.abs(y-(rect.y+rect.height*(1-v.series[0].values[i])))<.001));
|
||||
assert.match(chart.renderToSVGString(),/<svg/);
|
||||
} finally {chart.dispose();}
|
||||
});
|
||||
test('report period comparison bars keep enough plot height and preserve their weight ratio',()=>{
|
||||
const v={...visual('column'),unit:'kg',metric:'black_total_weight',stage:'black',sectionKey:'stage',
|
||||
categories:[{key:'previous',label:'2026-08'},{key:'current',label:'2026-09'}],
|
||||
series:[{key:'black_total_weight',label:'黑片投入重量',values:[20,60]}],coverage:{totalRows:2,returnedRows:2,truncated:false}};
|
||||
const out=buildAnalysisVisualExportOption(v,900,'report');
|
||||
const chart=echarts.init(null,undefined,{renderer:'svg',width:out.width,height:out.height,ssr:true});
|
||||
try {
|
||||
chart.setOption(out.option,{notMerge:true});
|
||||
assert.ok(chart.getModel().getComponent('grid').coordinateSystem.getRect().height>=180);
|
||||
const data=chart.getModel().getSeriesByIndex(0).getData();
|
||||
const first=Math.abs(data.getItemLayout(0).height),second=Math.abs(data.getItemLayout(1).height);
|
||||
assert.ok(first>30&&second>90);assert.ok(Math.abs(second/first-3)<1e-10);
|
||||
} finally {chart.dispose();}
|
||||
});
|
||||
Reference in New Issue
Block a user