优化:未分类连续维护与柏拉图预汇总,同步已发布修复

This commit is contained in:
2026-11-01 12:40:50 +08:00
parent 572873c6b8
commit 38290f5fec
135 changed files with 17613 additions and 663 deletions
@@ -0,0 +1,27 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { partialAnalysisNotice } from '../src/analysisConversationState.ts';
import { buildAnalysisReadingModel } from '../src/analysisReadingModel.ts';
test('partial status distinguishes successful reads from incomplete narration and charts', () => {
assert.match(partialAnalysisNotice('evidence_incomplete', {answerQuality:{version:1,dataComplete:true,narrativeComplete:false,chartsComplete:true}}), /数据已查齐,答案/);
assert.match(partialAnalysisNotice('evidence_incomplete', {answerQuality:{version:1,dataComplete:true,narrativeComplete:true,chartsComplete:false}}), /图表/);
assert.match(partialAnalysisNotice('evidence_incomplete', {answerQuality:{version:1,dataComplete:false,narrativeComplete:false,chartsComplete:true}}), /数据尚未通过/);
});
test('combined ranking chart remains visible beside a verified five-product summary', () => {
const visual={id:'combined',type:'bar',title:'产品规格报废总重排名',subtitle:'黑片+亮片',unit:'kg',
scope:{releaseId:'release',year:2026,month:9,view:'product'},period:{year:2026,month:9},
categories:[1,2,3,4,5].map(i=>({key:`p${i}`,label:`规格${i}`})),
series:[{key:'current_scrap_weight',label:'报废总重',values:[65,60,41,41,30]}],
evidenceRefs:['Q11111111'],requiredFields:['black_scrap_weight','bright_scrap_weight'],
metric:'current_scrap_weight',originTurnId:'turn',sectionKey:'product',dimension:'product',
coverage:{totalRows:20,returnedRows:5,truncated:true,shareBasis:'all_scope_weight',denominator:1000}};
const task={period:{year:2026,month:9},filters:{},dimensions:['product'],fields:['rate','scrapWeight'],stages:[],
queryPlan:[{purpose:'ranking',dimension:'product',fields:['rate','scrapWeight'],stages:[],limit:5,selector:{kind:'base'},visualType:'bar',visualPreference:'auto',comparisonRequired:false}]};
const answer='已列出5项重点规格。[Q11111111]';
const turn={id:'turn',task,result:{answer,task,releaseId:'release',visuals:[visual],queryEvidenceRefs:['Q11111111'],
readingSummary:{version:1,lead:answer,evidence:[],notices:[],evidenceRefs:['Q11111111'],visualIds:['combined']}}};
const reading=buildAnalysisReadingModel(answer,[visual],'产品不良TOP5',turn);
assert.deepEqual(reading.primaryVisuals.map(item=>item.id),['combined']);
});
@@ -0,0 +1,297 @@
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 { buildAnalysisReadingModel, conclusionMarkdown } from '../src/analysisReadingModel.ts';
import { parseAnalysisVisuals, combineStageDefectVisuals } from '../src/analysisVisualsModel.ts';
import { analysisIsRunning, compactAnalysisTimeline, duplicatesFinalAnalysisAnswer } from '../src/analysisConversationState.ts';
import { sanitizeAnalysisDisplayText } from '../src/analysisDisplayText.ts';
import { orderedAnalysisProcess, groupAdjacentThinking } from '../src/analysisModelThinking.ts';
const snapshotSource = readFileSync(new URL('../src/analysisSnapshot.ts', import.meta.url), 'utf8');
const snapshotResultSource = snapshotSource.slice(snapshotSource.indexOf('export function analysisSnapshotResult'), snapshotSource.indexOf('\nfunction canonical('));
const analysisSnapshotResult = new Function('object', ts.transpileModule(snapshotResultSource.replace(/^export /gm, ''), {
fileName: 'analysisSnapshotResult.ts', compilerOptions: { target: ts.ScriptTarget.ES2022 },
}).outputText + '\nreturn analysisSnapshotResult;')(value => value && typeof value === 'object' && !Array.isArray(value) ? value : {});
const reportVisualSource = readFileSync(new URL('../src/AnalysisReportVisuals.tsx', import.meta.url), 'utf8');
const reportVisualsSource = reportVisualSource.slice(reportVisualSource.indexOf('export function reportVisuals'), reportVisualSource.indexOf('\nexport function useReportVisualImages'));
const reportVisuals = new Function('analysisSnapshotResult', 'parseAnalysisVisuals', 'combineStageDefectVisuals',
ts.transpileModule(reportVisualsSource.replace(/^export /gm, ''), {
fileName: 'reportVisuals.ts', compilerOptions: { target: ts.ScriptTarget.ES2022 },
}).outputText + '\nreturn reportVisuals;')(analysisSnapshotResult, parseAnalysisVisuals, combineStageDefectVisuals);
const processSource = readFileSync(new URL('../src/AnalysisProcess.tsx', import.meta.url), 'utf8').replace(/^import .*;\n/gm, '').replace(/^export /gm, '');
const icon = () => React.createElement('i');
let activeHooks;
const Process = new Function('React', 'useEffect', 'useRef', 'useState', 'Spin', 'CheckCircleOutlined', 'CloseCircleOutlined', 'ClockCircleOutlined', 'RightOutlined',
'analysisIsRunning', 'compactAnalysisTimeline', 'duplicatesFinalAnalysisAnswer', 'sanitizeAnalysisDisplayText', 'AiMarkdown', 'orderedAnalysisProcess', 'groupAdjacentThinking', 'AnalysisThinkingBlock',
ts.transpileModule(`${processSource}\nreturn AnalysisProcess;`, {
fileName: 'AnalysisProcess.tsx', compilerOptions: { target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.React },
}).outputText)(React, (...args) => activeHooks.useEffect(...args), (...args) => activeHooks.useRef(...args), (...args) => activeHooks.useState(...args), icon, icon, icon, icon, icon, analysisIsRunning, compactAnalysisTimeline,
duplicatesFinalAnalysisAnswer, sanitizeAnalysisDisplayText, ({ content }) => React.createElement('p', null, content), orderedAnalysisProcess, groupAdjacentThinking, () => null);
function hookHarness() {
const state = { values: [], refs: [], deps: [], cursor: 0, refCursor: 0, effectCursor: 0, pending: [] };
const useState = initial => {
const index = state.cursor++;
if (!(index in state.values)) state.values[index] = initial;
return [state.values[index], next => { state.values[index] = typeof next === 'function' ? next(state.values[index]) : next; }];
};
const useEffect = (effect, deps = []) => {
const index = state.effectCursor++;
const previous = state.deps[index];
if (!previous || deps.some((value, at) => !Object.is(value, previous[at]))) {
state.deps[index] = [...deps];
state.pending.push(effect);
}
};
const useRef = initial => {
const index = state.refCursor++;
if (!(index in state.refs)) state.refs[index] = { current: initial };
return state.refs[index];
};
activeHooks = { useState, useEffect, useRef };
const render = turn => {
const pass = () => {
state.cursor = 0; state.refCursor = 0; state.effectCursor = 0; state.pending = [];
const element = Process({ turn });
const pending = state.pending.splice(0);
for (const effect of pending) effect();
return element;
};
let element = pass();
if (state.pending.length === 0) element = pass();
return element;
};
return { render };
}
test('a valid reading summary keeps the full normal Markdown after its conclusion, but filters audit appendices', () => {
const lead = '本月已核实2项重点规格。[Q11111111]';
const answer = `${lead}\n\n## 重点规格\n\n| 排名 | 规格 | 报废总重 |\n| --- | --- | --- |\n| 1 | 规格甲 | 20 kg |\n| 2 | 规格乙 | 10 kg |\n\n### 变化说明\n规格甲报废总重高于规格乙,建议优先核对。\n\n## 证据审计\nQ11111111 是内部引用。\n\n## 完整统计依据\n这段冗长原始附录不能进入结论展示。`;
const turn = { id: 'reading-turn', result: { answer, queryEvidenceRefs: ['Q11111111'], readingSummary: {
version: 1, lead, evidence: [], notices: [], evidenceRefs: ['Q11111111'],
} } };
const reading = buildAnalysisReadingModel(answer, [], '本月产品不良Top2', turn).reading;
const markdown = conclusionMarkdown(reading);
assert.ok(markdown.indexOf('本月已核实2项重点规格') < markdown.indexOf('## 重点规格'));
assert.match(markdown, /\| 1 \| 规格甲 \| 20 kg \|/);
assert.match(markdown, /\| 2 \| 规格乙 \| 10 kg \|/);
assert.match(markdown, /规格甲报废总重高于规格乙/);
assert.equal((markdown.match(/本月已核实2项重点规格/g) || []).length, 1);
assert.doesNotMatch(markdown, /Q11111111|证据审计|内部引用|完整统计依据|冗长原始附录/);
});
test('summary values repeated in Markdown headings and table cells do not delete those complete blocks', () => {
const answer = '20 kg。[Q11111111]\n\n## 规格甲\n\n| 规格 | 报废总重 |\n| --- | --- |\n| 规格甲 | 20 kg |';
const turn = { id: 'reading-cell-turn', result: { answer, queryEvidenceRefs: ['Q11111111'], readingSummary: {
version: 1, lead: '20 kg', evidence: ['规格甲'], notices: [], evidenceRefs: ['Q11111111'],
} } };
const markdown = conclusionMarkdown(buildAnalysisReadingModel(answer, [], '规格甲报废排名', turn).reading);
assert.match(markdown, /## 规格甲/);
assert.match(markdown, /\| 规格甲 \| 20 kg \|/);
assert.equal((markdown.match(/\| 规格甲 \| 20 kg \|/g) || []).length, 1);
});
test('selected tables and defect lists stay under their original headings and in source order', () => {
const lead = '9月正式综合指标已核实。';
const productTable = '| 规格 | 报废增量(kg) |\n|---|---:|\n| 规格甲 | 758.76 |';
const defectList = '- 黑片缺角:+2,407.78 kg';
const answer = `${lead}\n\n### 1. 总体变化\n\n| 口径 | 变化 |\n|---|---:|\n| 综合合格率 | -0.44个百分点 |\n\n### 3. 重点规格\n\n${productTable}\n\n### 4. 缺陷线索\n\n${defectList}`;
const turn = { id: 'reading-structure-turn', result: { answer, queryEvidenceRefs: ['Q11111111'], readingSummary: {
version: 1, lead, evidence: [productTable, defectList], notices: [], evidenceRefs: ['Q11111111'],
} } };
const markdown = conclusionMarkdown(buildAnalysisReadingModel(answer, [], '分析重点变化', turn).reading);
assert.ok(markdown.indexOf('### 1. 总体变化') < markdown.indexOf('### 3. 重点规格'));
assert.ok(markdown.indexOf('### 3. 重点规格') < markdown.indexOf('| 规格 | 报废增量(kg) |'));
assert.ok(markdown.indexOf('### 4. 缺陷线索') < markdown.indexOf('- 黑片缺角:+2,407.78 kg'));
assert.equal((markdown.match(/### 3\. 重点规格/g) || []).length, 1);
assert.equal((markdown.match(/\| 规格甲 \| 758\.76 \|/g) || []).length, 1);
assert.equal((markdown.match(/- 黑片缺角:\+2,407\.78 kg/g) || []).length, 1);
});
test('a partial reason appears once across summary and controlled fallback copies while different gaps remain', () => {
const reason = '正文解释未完成事实核验,已按已确认数据生成简短报告';
const answer = `已核实正式数值。\n\n## 尚未覆盖的范围\n\n- ${reason}。\n\n尚未解决:${reason},报告保持部分完成。`;
const turn = { id: 'partial-history', result: { answer, queryEvidenceRefs: ['Q11111111'], readingSummary: {
version: 1, lead: '已核实正式数值。', evidence: [],
notices: [reason, reason + ',报告保持部分完成。', '黑片尚缺5项。', '亮片尚缺3项。'], evidenceRefs: ['Q11111111'],
} } };
const markdown = conclusionMarkdown(buildAnalysisReadingModel(answer, [], '汇总历史', turn).reading);
assert.equal(markdown.split(reason).length - 1, 1);
assert.match(markdown, /黑片尚缺5项/);
assert.match(markdown, /亮片尚缺3项/);
assert.doesNotMatch(markdown, /尚未覆盖的范围|尚未解决/);
});
const defectVisual = (stage, id, ref, value) => ({
id, type: 'bar', title: `${stage}具体缺陷报废重量`, subtitle: '', unit: 'kg',
scope: { releaseId: 'release', year: 2026, month: 9, stage }, period: { year: 2026, month: 9 },
categories: [{ key: 'crack', label: '隐裂' }],
series: [{ key: 'source_defect_weight', label: '报废重量', values: [value] }],
evidenceRefs: [ref], requiredFields: [`${stage}_scrap_weight`], metric: 'source_defect_weight',
originTurnId: 'visual-turn', stage, sectionKey: `defect_${stage}`, dimension: 'defect',
coverage: { totalRows: 1, returnedRows: 1, truncated: false },
});
test('report summary selection uses the prepared combined figure ID while preserving raw scope and evidence checks', () => {
const black = defectVisual('black', 'black', 'Q11111111', 2);
const bright = defectVisual('bright', 'bright', 'Q22222222', 3);
const answer = '已核实黑片与亮片隐裂报废情况。[Q11111111][Q22222222]';
const turn = { id: 'visual-turn', status: 'COMPLETED', plan: { task: {
kind: 'analysis', visualPreference: 'auto', period: { year: 2026, month: 9 }, filters: {},
stages: ['black', 'bright'], fields: ['scrapWeight'], dimensions: ['defect'],
} }, result: { answer, releaseId: 'release', visualSchemaVersion: 1, visuals: [black, bright],
queryEvidenceRefs: ['Q11111111', 'Q22222222'], readingSummary: {
version: 1, lead: answer, evidence: [], notices: [], evidenceRefs: ['Q11111111', 'Q22222222'], visualIds: ['black', 'bright'],
} } };
const prepared = reportVisuals(turn);
const model = buildAnalysisReadingModel(answer, prepared, '分析9月黑片亮片具体缺陷', turn);
assert.deepEqual(prepared.map(item => item.id), ['combined-black-bright']);
assert.deepEqual(model.primaryVisuals.map(item => item.id), ['combined-black-bright']);
assert.deepEqual(model.primaryVisuals[0].evidenceRefs, ['Q11111111', 'Q22222222']);
const revoked = structuredClone(turn);
revoked.result.queryEvidenceRefs = ['Q11111111'];
const revokedPrepared = reportVisuals(revoked);
assert.deepEqual(buildAnalysisReadingModel(answer, revokedPrepared, '分析9月黑片亮片具体缺陷', revoked).primaryVisuals, []);
});
const historyTurn = () => {
const august = defectVisual('black', 'history-aug', 'Q11111111', 2);
august.scope = { releaseId: 'release-a', year: 2026, month: 8, product: '规格甲', stage: 'black' };
august.period = { year: 2026, month: 8 };
august.originTurnId = 'history-report';
const september = defectVisual('bright', 'history-sep', 'Q22222222', 3);
september.scope = { releaseId: 'release-b', year: 2026, month: 9, group: '海外组', stage: 'bright' };
september.period = { year: 2026, month: 9 };
september.originTurnId = 'history-report';
const unbound = defectVisual('black', 'unlineaged', 'Q33333333', 4);
unbound.scope = { releaseId: 'release-c', year: 2026, month: 10, product: '规格乙', stage: 'black' };
unbound.period = { year: 2026, month: 10 };
unbound.originTurnId = 'history-report';
const sources = [august, september].map(visual => ({
visualId: visual.id, sourceTurnId: `source-${visual.id}`, scope: structuredClone(visual.scope),
period: structuredClone(visual.period), comparisonPeriod: null, dimension: visual.dimension,
stage: visual.stage, metric: visual.metric, evidenceRefs: [...visual.evidenceRefs],
}));
const answer = '已整合两个来源期间的历史结果。[Q11111111][Q22222222][Q33333333]';
const turn = { id: 'history-report', status: 'COMPLETED', plan: { task: {
kind: 'report', historyMode: 'all', freshQuery: false,
visualPreference: 'auto', visualType: null, period: null, filters: {}, stages: [], fields: [],
} }, result: { answer, completionMethod: 'confirmed_history_report', historyEvidence: {
importId: 'import-2026-10', snapshotHash: 'f'.repeat(64),
}, historyVisualSources: sources, releaseId: 'history-release', visualSchemaVersion: 1,
visuals: [august, september, unbound], queryEvidenceRefs: ['Q11111111', 'Q22222222', 'Q33333333'], readingSummary: {
version: 1, lead: answer, evidence: [], notices: [], evidenceRefs: ['Q11111111', 'Q22222222', 'Q33333333'],
visualIds: ['history-aug', 'history-sep', 'unlineaged'],
} } };
return turn;
};
const selectedHistoryIds = turn => {
const prepared = reportVisuals(turn);
return buildAnalysisReadingModel(turn.result.answer, prepared, '综合历史报告', turn).primaryVisuals.map(visual => visual.id);
};
test('server-confirmed history reports select individually bound charts across distinct periods and scopes', () => {
const turn = historyTurn();
assert.deepEqual(selectedHistoryIds(turn), ['history-aug', 'history-sep']);
});
test('history reports honor auto, required, and text-only chart display preferences without weakening lineage', () => {
for (const preference of ['auto', 'required']) {
const turn = structuredClone(historyTurn());
turn.plan.task.visualPreference = preference;
assert.deepEqual(selectedHistoryIds(turn), ['history-aug', 'history-sep']);
}
const textOnly = structuredClone(historyTurn());
textOnly.plan.task.visualPreference = 'none';
assert.deepEqual(selectedHistoryIds(textOnly), []);
const invalidRequired = structuredClone(historyTurn());
invalidRequired.plan.task.visualPreference = 'required';
invalidRequired.result.visuals[0].originTurnId = 'stale-source-turn';
assert.deepEqual(selectedHistoryIds(invalidRequired), ['history-sep']);
});
test('history chart lineage rejects missing proof, wrong completion, scope tampering, stale origins and unbound visuals', () => {
const missingProof = structuredClone(historyTurn()); delete missingProof.result.historyEvidence;
assert.deepEqual(selectedHistoryIds(missingProof), []);
const wrongMethod = structuredClone(historyTurn()); wrongMethod.result.completionMethod = 'normal_analysis';
assert.deepEqual(selectedHistoryIds(wrongMethod), []);
const changedScope = structuredClone(historyTurn()); changedScope.result.historyVisualSources[0].scope.product = '伪造规格';
assert.deepEqual(selectedHistoryIds(changedScope), ['history-sep']);
const changedOrigin = structuredClone(historyTurn()); changedOrigin.result.visuals[0].originTurnId = 'another-turn';
assert.deepEqual(selectedHistoryIds(changedOrigin), ['history-sep']);
const noLineage = structuredClone(historyTurn()); noLineage.result.historyVisualSources = noLineage.result.historyVisualSources.slice(1);
assert.deepEqual(selectedHistoryIds(noLineage), ['history-sep']);
const duplicateLineage = structuredClone(historyTurn());
duplicateLineage.result.historyVisualSources.push(structuredClone(duplicateLineage.result.historyVisualSources[0]));
assert.deepEqual(selectedHistoryIds(duplicateLineage), ['history-sep']);
});
test('history lineage must exactly bind period, comparison, dimension, stage, metric, and evidence', () => {
const tamper = [
lineage => { lineage.period.month = 7; },
lineage => { lineage.comparisonPeriod = { year: 2026, month: 7 }; },
lineage => { lineage.dimension = 'product'; },
lineage => { lineage.stage = 'bright'; },
lineage => { lineage.metric = 'source_defect_delta_weight'; },
lineage => { lineage.evidenceRefs = ['Q22222222']; },
lineage => { lineage.sourceTurnId = ''; },
];
for (const alter of tamper) {
const changed = structuredClone(historyTurn());
alter(changed.result.historyVisualSources[0]);
assert.deepEqual(selectedHistoryIds(changed), ['history-sep']);
}
});
test('history lineage retains the common-scope stage merge and the image model ID', () => {
const turn = structuredClone(historyTurn());
const bright = turn.result.visuals.find(visual => visual.id === 'history-sep');
bright.scope = { releaseId: 'release-a', year: 2026, month: 8, product: '规格甲', stage: 'bright' };
bright.period = { year: 2026, month: 8 };
const brightLineage = turn.result.historyVisualSources.find(item => item.visualId === 'history-sep');
brightLineage.scope = structuredClone(bright.scope);
brightLineage.period = structuredClone(bright.period);
assert.deepEqual(selectedHistoryIds(turn), ['combined-history-aug-history-sep']);
});
test('history proof and lineage in model-controlled task fields cannot authorize ordinary charts', () => {
const turn = structuredClone(historyTurn());
delete turn.result.completionMethod;
delete turn.result.historyEvidence;
delete turn.result.historyVisualSources;
turn.plan.task.historyVisualSources = historyTurn().result.historyVisualSources;
assert.deepEqual(selectedHistoryIds(turn), []);
});
test('running process starts folded, stays open after a user opens it, closes on completion, and ignores late running status', () => {
const harness = hookHarness();
const turn = { id: 'process-turn', status: 'RUNNING', steps: [{ tool: 'read', label: '读取数据', status: 'running' }] };
let element = harness.render(turn);
assert.equal(element.type, 'details');
assert.equal(element.props.open, false);
element.props.onToggle({ currentTarget: { open: true } });
turn.steps = [...turn.steps, { tool: 'mcp_call', label: '查询质量数据', status: 'running' }];
element = harness.render(turn);
assert.equal(element.props.open, true);
turn.status = 'COMPLETED';
turn.steps = [...turn.steps, { tool: 'mcp_call', label: '查询质量数据', status: 'completed' }];
element = harness.render(turn);
assert.equal(element.props.open, false);
turn.status = 'RUNNING';
element = harness.render(turn);
assert.equal(element.props.open, false);
});
+135 -5
View File
@@ -68,12 +68,12 @@ const hooks = { useMemo: fn => fn(), useState: initial => [initial, () => {}], u
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,
AnalysisVisuals: ({ visuals = [] }) => React.createElement('div', null, visuals.map(visual => React.createElement('figure', { key: visual.id, 'data-chat-visual-id': visual.id }, React.createElement('h3', { className: 'analysis-visual-heading-copy' }, visual.title), React.createElement('p', null, visual.subtitle)))), 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 }) });
reportVisuals: source => source.result?.visuals || source.visuals || [], ReportVisualFigure: ({ visual }) => React.createElement('figure', { 'data-report-visual-id': visual.id }, React.createElement('strong', { className: 'q-report-visual-heading' }, visual.title), React.createElement('figcaption', null, visual.subtitle)), 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];
@@ -117,6 +117,41 @@ test('reference-style cards and chapters keep chat/report values, figures and or
assert.equal(fenced.sections.some(x=>x.title==='不作为章节'),false);
});
test('pure chart chapter title is rendered once in chat and report while chart caption and scope remain', () => {
const title = '产品规格报废总重排名';
const ranking = { ...chart, id: 'ranking', type: 'bar', title, unit: 'kg', subtitle: '黑片+亮片',
scope: { year: 2026, month: 9, releaseId: 'release' }, period: { year: 2026, month: 9 }, comparisonPeriod: undefined,
categories: [{ key: 'product-a', label: '规格甲' }], series: [{ key: 'current_scrap_weight', label: '报废总重', values: [65] }],
evidenceRefs: ['Q11111111'], requiredFields: ['black_scrap_weight', 'bright_scrap_weight'], metric: 'current_scrap_weight',
sectionKey: 'product', dimension: 'product', coverage: { totalRows: 20, returnedRows: 1, truncated: true, shareBasis: 'all_scope_weight', denominator: 1000 } };
const data = turn({ ...summary(), lead: '本月重点规格报废情况已核验。[Q11111111]', evidence: [`### ${title}\n\n[Q11111111]`], notices: [], evidenceRefs: ['Q11111111'], visualIds: ['ranking'] });
data.result.answer = `${data.result.readingSummary.lead}\n\n${data.result.readingSummary.evidence[0]}`;
data.result.visuals = [ranking];
data.result.queryEvidenceRefs = ['Q11111111'];
data.plan = { task: { version: 1, kind: 'metrics', visualPreference: 'required', visualType: 'bar', fields: ['scrapWeight'], dimensions: ['product'], stages: [], period: { year: 2026, month: 9 }, comparisonRequired: false, filters: {} } };
for (const html of [renderChat(data), renderReport(data)]) {
assert.equal((html.match(new RegExp(title, 'g')) || []).length, 1, html);
assert.match(html, /黑片+亮片/);
}
const withBody = structuredClone(data);
withBody.result.readingSummary.evidence = [`### ${title}\n\n| 规格 | 报废总重 |\n| --- | --- |\n| 规格甲 | 65 kg |\n[Q11111111]`];
withBody.result.answer = `${withBody.result.readingSummary.lead}\n\n${withBody.result.readingSummary.evidence[0]}`;
for (const html of [renderChat(withBody), renderReport(withBody)]) {
assert.equal((html.match(new RegExp(title, 'g')) || []).length, 2, html);
assert.match(html, /<table>/);
assert.match(html, /规格甲/);
}
const semanticTitle = structuredClone(data);
semanticTitle.result.readingSummary.evidence = ['### 重点规格\n\n[Q11111111]'];
semanticTitle.result.answer = `${semanticTitle.result.readingSummary.lead}\n\n${semanticTitle.result.readingSummary.evidence[0]}`;
for (const html of [renderChat(semanticTitle), renderReport(semanticTitle)]) {
assert.match(html, /重点规格/);
assert.equal((html.match(new RegExp(title, 'g')) || []).length, 1, html);
}
});
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);
@@ -210,6 +245,90 @@ const historySummary = () => ({ version: 1, lead: '已导入的缺角线索增
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() } });
const historyRankingVisual = (overrides = {}) => ({ id: 'ranking-a', type: 'bar', title: '产品规格报废总重排名', subtitle: '黑片+亮片;综合合格率见本节表格', unit: 'kg',
categories: [{ key: 'product-a', label: '规格甲' }, { key: 'product-b', label: '规格乙' }],
series: [{ key: 'current_scrap_weight', label: '报废总重', values: [65, 60] }], evidenceRefs: ['Q11111111'],
requiredFields: ['black_scrap_weight', 'bright_scrap_weight'], scope: { year: 2026, month: 9, department: '消费电子产业部', group: '消费电子-3C', view: 'product', releaseId: 'release', includeUnassigned: false },
period: { year: 2026, month: 9 }, comparisonPeriod: undefined, stage: undefined, metric: 'current_scrap_weight',
coverage: { totalRows: 551, returnedRows: 2, truncated: true, shareBasis: 'all_scope_weight', denominator: 6979.16273 },
originTurnId: 'history-report', sectionKey: 'product', dimension: 'product', ...overrides });
const confirmedHistoryTurn = (visuals, turnId = 'history-report') => {
const refs = [...new Set(visuals.flatMap(visual => visual.evidenceRefs))];
const readingSummary = { version: 1, lead: `历史范围已核验。[${refs[0]}]`, evidence: [], notices: [], evidenceRefs: refs, visualIds: visuals.map(visual => visual.id) };
const historyVisualSources = visuals.map((visual, index) => ({ visualId: visual.id, sourceTurnId: `source-${index + 1}`,
scope: structuredClone(visual.scope), period: structuredClone(visual.period), comparisonPeriod: visual.comparisonPeriod ?? null,
dimension: visual.dimension ?? null, stage: visual.stage ?? null, metric: visual.metric, evidenceRefs: [...visual.evidenceRefs] }));
return { id: turnId, question: '综合历史报告', result: { answer: readingSummary.lead, completionMethod: 'confirmed_history_report', visualSchemaVersion: 1,
historyEvidence: { importId: 'import-1', snapshotHash: 'snapshot-1' }, queryEvidenceRefs: refs, historyVisualSources,
readingSummary, visuals: structuredClone(visuals) } };
};
test('confirmed history displays one exact duplicate business chart while preserving distinct scopes', () => {
const first = historyRankingVisual({ id: 'ranking-current-top5', evidenceRefs: ['Q11111111'] });
const sameBusinessFigure = historyRankingVisual({ id: 'ranking-current-followup', evidenceRefs: ['Q22222222'] });
const olderOverall = historyRankingVisual({ id: 'ranking-older-overall', evidenceRefs: ['Q33333333'],
scope: { year: 2026, month: 8, view: 'product', releaseId: 'release', includeUnassigned: false },
period: { year: 2026, month: 8 }, categories: [{ key: 'old-a', label: '旧规格甲' }, { key: 'old-b', label: '旧规格乙' }, { key: 'old-c', label: '旧规格丙' }],
series: [{ key: 'current_scrap_weight', label: '报废总重', values: [100, 90, 80] }],
coverage: { totalRows: 2249, returnedRows: 3, truncated: true, shareBasis: 'all_scope_weight', denominator: 62726.7476 } });
const data = confirmedHistoryTurn([first, sameBusinessFigure, olderOverall]);
const before = structuredClone(data);
const { primaryVisuals } = buildAnalysisReadingModel(data.result.answer, data.result.visuals, data.question, data);
assert.equal(data.result.visuals.length, 3);
assert.equal(data.result.historyVisualSources.length, 3);
assert.deepEqual(data, before);
assert.deepEqual(primaryVisuals.map(visual => visual.id), ['ranking-current-top5', 'ranking-older-overall']);
assert.deepEqual(primaryVisuals[0].categories, first.categories);
assert.deepEqual(primaryVisuals[0].series, first.series);
assert.deepEqual(primaryVisuals[0].coverage, first.coverage);
});
test('confirmed history keeps charts when any ordered business field differs', () => {
const first = historyRankingVisual({ id: 'ranking-current-top5', evidenceRefs: ['Q11111111'] });
const distinctCases = [
['scope', visual => { visual.scope.group = '消费电子-其他'; }],
['period', visual => { visual.scope.month = 8; visual.period.month = 8; }],
['comparison period', visual => { visual.comparisonPeriod = { year: 2026, month: 8 }; }],
['stage', visual => { visual.stage = 'black'; visual.scope.stage = 'black'; visual.requiredFields = ['black_scrap_weight']; }],
['metric', visual => { visual.metric = 'scrap_delta'; visual.series[0].key = 'scrap_delta'; }],
['category order', visual => { visual.categories.reverse(); visual.series[0].values.reverse(); }],
['series value', visual => { visual.series[0].values[0] += 0.01; }],
['coverage denominator', visual => { visual.coverage.denominator += 1; }],
['chart type', visual => { visual.type = 'column'; }],
['unit', visual => { visual.unit = 'count'; }],
['title', visual => { visual.title = '产品规格报废重量排名'; }],
];
for (const [label, mutate] of distinctCases) {
const distinct = historyRankingVisual({ id: 'ranking-current-followup', evidenceRefs: ['Q22222222'] });
mutate(distinct);
const oldScope = historyRankingVisual({ id: 'ranking-older-overall', evidenceRefs: ['Q33333333'],
scope: { year: 2026, month: 8, view: 'product', releaseId: 'release', includeUnassigned: false }, period: { year: 2026, month: 8 },
categories: [{ key: 'old-a', label: '旧规格甲' }, { key: 'old-b', label: '旧规格乙' }, { key: 'old-c', label: '旧规格丙' }],
series: [{ key: 'current_scrap_weight', label: '报废总重', values: [100, 90, 80] }],
coverage: { totalRows: 2249, returnedRows: 3, truncated: true, shareBasis: 'all_scope_weight', denominator: 62726.7476 } });
const data = confirmedHistoryTurn([first, distinct, oldScope]);
const selected = buildAnalysisReadingModel(data.result.answer, data.result.visuals, data.question, data).primaryVisuals;
assert.equal(selected.length, 3, `${label} difference must preserve the chart`);
assert.ok(selected.some(visual => visual.id === 'ranking-current-followup'), `${label} chart must remain selected`);
}
const plusZero = historyRankingVisual({ id: 'ranking-plus-zero', evidenceRefs: ['Q11111111'], series: [{ key: 'current_scrap_weight', label: '报废总重', values: [0, 60] }] });
const minusZero = historyRankingVisual({ id: 'ranking-minus-zero', evidenceRefs: ['Q22222222'], series: [{ key: 'current_scrap_weight', label: '报废总重', values: [-0, 60] }] });
const older = historyRankingVisual({ id: 'ranking-older', evidenceRefs: ['Q33333333'], scope: { year: 2026, month: 8, view: 'product', releaseId: 'release' }, period: { year: 2026, month: 8 } });
const signedZeroTurn = confirmedHistoryTurn([plusZero, minusZero, older]);
assert.equal(buildAnalysisReadingModel(signedZeroTurn.result.answer, signedZeroTurn.result.visuals, signedZeroTurn.question, signedZeroTurn).primaryVisuals.length, 3);
});
test('ordinary single-turn selections do not deduplicate identical charts', () => {
const first = historyRankingVisual({ id: 'ranking-a', originTurnId: 'single-turn', evidenceRefs: ['Q11111111'],
scope: { year: 2026, month: 9, releaseId: 'release' } });
const second = historyRankingVisual({ id: 'ranking-b', originTurnId: 'single-turn', evidenceRefs: ['Q22222222'],
scope: { year: 2026, month: 9, releaseId: 'release' } });
const turn = { id: 'single-turn', question: '9月产品规格排名', plan: { task: { version: 1, kind: 'metrics', visualPreference: 'required', visualType: 'bar',
fields: ['scrapWeight'], dimensions: ['product'], stages: [], period: { year: 2026, month: 9 }, comparisonRequired: false, filters: {} } },
result: { answer: '本月重点规格报废情况已核验。[Q11111111]', releaseId: 'release', visuals: [first, second],
queryEvidenceRefs: ['Q11111111', 'Q22222222'], readingSummary: { version: 1, lead: '本月重点规格报废情况已核验。[Q11111111]', evidence: [], notices: [], evidenceRefs: ['Q11111111', 'Q22222222'] } } };
assert.equal(buildAnalysisReadingModel(turn.result.answer, turn.result.visuals, turn.question, turn).primaryVisuals.length, 2);
});
test('real imported history fact IDs pass only the explicit server allowlist and render shared clickable citations', () => {
const data = historyTurn();
@@ -275,12 +394,14 @@ const requiredTask = () => ({ version: 1, kind: 'metrics', visualPreference: 're
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', () => {
test('explicit server-required charts appear in chat and reports while normal Markdown stays visible', () => {
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, /附录:完整分析、数据与图表|第四段原因线索/);
assert.doesNotMatch(html, /附录:完整分析、数据与图表/);
assert.match(html, /第四段原因线索/);
assert.match(html, /末行/);
}
});
@@ -390,6 +511,15 @@ test('required monthly trend descriptors match the exact server numeric frame wi
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无需展示的额外审计过程。';
data.result.answer=summary().lead+'\n\n### 重点规格:[Q22222222]\n\n| 规格 | 率 |\n| --- | --- |\n| 甲 | 95.13% |\n\n## 证据审计\n\n无需展示的额外审计过程。';
for(const html of [renderChat(data),renderReport(data)]) {assert.match(html,/<table>/);assert.match(html,/95.13%/);assert.doesNotMatch(html,/额外审计过程|Q22222222/);}
});
test('existing rank columns do not gain a duplicate sequence column', () => {
for (const label of ['序号','排名','名次']) {
const html=renderToStaticMarkup(React.createElement(AiMarkdown,{content:`| ${label} | 产品 |\n| --- | --- |\n| 1 | 规格甲 |`}));
assert.equal((html.match(/<th/g)||[]).length,3); // thead plus two header cells
assert.equal((html.match(/<td/g)||[]).length,2);
}
});
+26 -4
View File
@@ -104,6 +104,27 @@ test('a broad visual remains the root when another visual is narrowed by keyword
visual({id:'filtered',scope:{year:2026,month:9,releaseId:'release-a',productSearch:'16.33'}}),
]}), '2026年9月 · 对比 2026年8月 · 当前授权范围 · 不含未分类');
});
test('a multi-period historical report never inherits the current query month or its broadest chart',()=>{
const value={completionMethod:'confirmed_history_report',plan:{context:{year:2026,month:9,view:'overall'}},
historySources:[{turnId:'a',available:true},{turnId:'b',available:true}],
historySections:[{sourceTurnId:'a',period:{year:2026,month:9},filters:{department:'消费电子产业部',group:'消费电子-3C'}},
{sourceTurnId:'b',period:{year:2026,month:8},filters:{}}],visuals:[visual()]};
assert.equal(analysisScopeText(value),'');
assert.equal(analysisScopeText({...value,historySections:[value.historySections[0],{...value.historySections[0],filters:{department:'其他产业部'}}]}),'');
});
test('a single historical scope uses its authorized source frame, including its actual comparison only',()=>{
const source={sourceTurnId:'a',period:{year:2026,month:8},filters:{department:'产业部甲',group:'分组甲',includeUnassigned:false}};
const value={completionMethod:'confirmed_history_report',plan:{context:{year:2026,month:9},semantic:{compare:true,priorContext:{year:2025,month:1}}},
historySources:[{turnId:'a',available:true}],historySections:[source,{...source}]};
assert.equal(analysisScopeText(value),'2026年8月 · 产业部:产业部甲 · 业务分组:分组甲 · 不含未分类');
assert.equal(analysisScopeText({...value,historySources:[{turnId:'a',available:false}]}),'');
});
test('the current nested result cannot borrow stale flattened historical scope metadata',()=>{
const value={completionMethod:'confirmed_history_report',historySources:[{turnId:'old',available:true}],
historySections:[{sourceTurnId:'old',period:{year:2025,month:1},filters:{group:'旧分组'}}],
result:{completionMethod:'formal_metrics',plan:{context:{year:2026,month:9,group:'当前分组'}}}};
assert.equal(analysisScopeText(value),'2026年9月 · 业务分组:当前分组');
});
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);
@@ -126,9 +147,9 @@ const thinkingSource=fs.readFileSync(new URL('../src/ModelThinkingPanel.tsx',imp
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',
const Process=new Function('React','useEffect','useRef','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);
)(React,React.useEffect,React.useRef,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']){
@@ -137,9 +158,10 @@ test('settled process is collapsed, with the original records retained inside',(
assert.doesNotMatch(html,/<details class="analysis-process-history analysis-agent-process" open/);
}
});
test('running process remains visible instead of being hidden behind the completed fold',()=>{
test('running process stays folded by default while retaining its current records inside',()=>{
const html=renderToStaticMarkup(React.createElement(Process,{turn:processTurn('RUNNING')}));
assert.match(html,/读取数据/);assert.match(html,/<details class="analysis-process-history analysis-agent-process" open/);
assert.match(html,/读取数据/);assert.match(html,/<details class="analysis-process-history analysis-agent-process"/);
assert.doesNotMatch(html,/<details class="analysis-process-history analysis-agent-process" open/);
});
test('a submitted follow-up rearms following only when its own turn is rendered',()=>{
+54 -1
View File
@@ -217,9 +217,56 @@ test('stage scrap rates preserve values above 100 percent and expand every ratio
assert.equal(buildAnalysisVisualExportOption(below100, 1280, 'report').option.yAxis.max, 100);
});
test('only correctly declared stage scrap-rate metrics accept above-one ratios', () => {
test('formal black and composite rates above 100 percent remain visible in live and exported charts', () => {
const products = [
{ name: '42.1X42.1X35异形+Z', composite: 1.2430959504537282, black: 1.277660594439118 },
{ name: 'R43X38.1X9.5X60+Q', composite: 1.0601991884176734, black: 1.1147540983606556 },
];
const composite = visual({
type: 'column', title: '综合合格率', metric: 'composite_rate', dimension: 'product',
requiredFields: ['black_good_weight', 'black_total_weight', 'bright_good_weight', 'bright_total_weight'],
categories: products.map((item, index) => ({ key: `product-${index}`, label: item.name })),
series: [{ key: 'composite_rate', label: '综合合格率', values: products.map(item => item.composite) }],
scope: { year: 2026, month: 9, releaseId: 'release-a' }, period: { year: 2026, month: 9 }, comparisonPeriod: undefined,
});
const parsed = parseAnalysisVisuals([composite]).visuals[0];
assert.equal(parsed.chartable, true);
assert.deepEqual(parsed.series[0].values, products.map(item => item.composite));
const option = buildAnalysisVisualOption(parsed);
assert.deepEqual(option.series[0].data.map(item => typeof item === 'number' ? item : item.value), products.map(item => item.composite * 100).map(value => Number(value.toFixed(7))));
assert.ok(option.yAxis.max > 124.3);
assert.ok(buildAnalysisVisualExportOption(parsed, 1280, 'standalone').option.yAxis.max > 124.3);
assert.ok(buildAnalysisVisualExportOption(parsed, 1280, 'report').option.yAxis.max > 124.3);
assert.match(formatVisualValue(products[0].composite, 'ratio'), /124\.3/);
const black = parseAnalysisVisuals([visual({
type: 'column', title: '黑片合格率', metric: 'black_rate', stage: 'black',
requiredFields: ['black_good_weight', 'black_total_weight'],
categories: products.map((item, index) => ({ key: `product-${index}`, label: item.name })),
series: [{ key: 'black_rate', label: '黑片合格率', values: products.map(item => item.black) }],
scope: { year: 2026, month: 9, releaseId: 'release-a', stage: 'black' }, period: { year: 2026, month: 9 }, comparisonPeriod: undefined,
})]).visuals[0];
assert.equal(black.chartable, true);
assert.ok(buildAnalysisVisualOption(black).yAxis.max > products[0].black * 100);
const compositeWithoutHeadquarters = parseAnalysisVisuals([visual({
title: '综合合格率(不含总部报废)', metric: 'composite_rate_without_headquarters_scrap',
requiredFields: ['black_good_weight', 'black_total_weight', 'bright_good_weight', 'bright_total_weight'],
series: [{ key: 'composite_rate_without_headquarters_scrap', label: '综合合格率', values: [1.04, 1.02] }],
})]).visuals[0];
assert.equal(compositeWithoutHeadquarters.chartable, true);
assert.ok(buildAnalysisVisualOption(compositeWithoutHeadquarters).yAxis.max > 104);
const horizontal = parseAnalysisVisuals([{ ...composite, type: 'bar' }]).visuals[0];
assert.equal(horizontal.chartable, true);
assert.ok(buildAnalysisVisualOption(horizontal).xAxis.max > 124.3);
assert.ok(buildAnalysisVisualExportOption(horizontal, 1280, 'report').option.xAxis.max > 124.3);
});
test('only official adjusted-denominator rates accept above-one ratios', () => {
for (const input of [
visual({ series: [{ key: 'r', label: '率', values: [1.02, null] }] }),
visual({ metric: 'bright_rate', stage: 'bright', requiredFields: ['bright_good_weight', 'bright_total_weight'], 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' }),
]) {
@@ -229,6 +276,12 @@ test('only correctly declared stage scrap-rate metrics accept above-one ratios',
const negative = parseAnalysisVisuals([scrapRate('bright', [-0.01, 1.02])]).visuals[0];
assert.equal(negative.chartable, false);
assert.deepEqual(negative.invalidValueCells, ['0:0']);
for (const value of [-0.01, Number.NaN, Number.POSITIVE_INFINITY]) {
const official = parseAnalysisVisuals([visual({ metric: 'composite_rate', series: [{ key: 'r', label: '综合合格率', values: [value, 0.95] }] })]).visuals[0];
assert.equal(official.chartable, false);
assert.deepEqual(official.invalidValueCells, ['0:0']);
}
});
test('empty subtitle and extra-filter maps survive strict parsing', () => {
@@ -0,0 +1,59 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {ClassificationQueue,classificationHides} from '../src/classificationQueue.ts';
const deferred=()=>{let resolve,reject;const promise=new Promise((a,b)=>{resolve=a;reject=b;});return{promise,resolve,reject};};
const tick=()=>new Promise(resolve=>setImmediate(resolve));
const row={stage:'black',department:'A',product:'P',pdtCode:'',salesRegion:'X'};
const command=(product='P',target='G')=>({selection:{kind:'group',row:{...row,product}},target,options:{stage:'all',conditions:[{field:'@department',operator:'EQUALS',value:'A'},{field:'销售片区',operator:'EQUALS',value:'X'}]}});
const base={matchRules:[],other:{untouched:true}};
const deps=extra=>({status:async()=>({currentReleaseId:'r',activeMapping:{definition:base}}),apply:async()=>({operationId:'job',status:'QUEUED'}),operation:async()=>({status:'COMPLETED',operationId:'job',currentReleaseId:'r2'}),wait:()=>tick(),persist:()=>{},completed:()=>{},...extra});
test('save hides all matching inventory rows immediately without any preview, and later commands use the latest mapping',async()=>{
const first=deferred(),requests=[],events=[];let definition=base,release='r',count=0;
const queue=new ClassificationQueue(deps({status:async()=>({currentReleaseId:release,activeMapping:{definition}}),apply:async(value,expected)=>{requests.push({value,expected});definition=value;return{operationId:'job'+(++count),status:'QUEUED'};},operation:async id=>id==='job1'?first.promise:{operationId:id,status:'COMPLETED',currentReleaseId:'r3'},completed:()=>events.push('done')}));
queue.enqueue(command(),base,[]);
assert.equal(classificationHides({...row,stage:'bright',product:'Other'},'group',queue.snapshot()),true);
assert.equal(classificationHides({...row,salesRegion:'x'},'group',queue.snapshot()),false);
const second={...command('Q','H'),options:{stage:'black',conditions:[{field:'@product',operator:'EQUALS',value:'Q'}]}};
queue.enqueue(second,base,[]);await tick();assert.equal(requests.length,1);assert.equal(queue.snapshot()[1].status,'queued');
release='r2';first.resolve({operationId:'job1',status:'COMPLETED',currentReleaseId:'r2'});await tick();await tick();
assert.equal(requests.length,2);assert.equal(requests[1].expected,'r2');assert.equal(requests[1].value.matchRules.length,2);assert.deepEqual(requests[1].value.other,base.other);assert.equal(events.length,2);
assert.equal(classificationHides(row,'group',queue.snapshot()),true,'completed job remains hidden until refreshed inventory arrives');
queue.acknowledge(queue.snapshot().map(job=>job.id));assert.equal(queue.snapshot().length,0);
});
test('a failed update restores hidden rows; failure does not prevent a following independent classification',async()=>{
const failed=deferred();let count=0;
const queue=new ClassificationQueue(deps({apply:async()=>({operationId:'job'+(++count),status:'QUEUED'}),operation:async id=>id==='job1'?failed.promise:{operationId:id,status:'COMPLETED'}}));
const id=queue.enqueue(command(),base,[]);await tick();
failed.resolve({operationId:'job1',status:'FAILED',errors:[{message:'规则校验失败'}]});await tick();
assert.equal(queue.snapshot()[0].status,'failed');assert.equal(classificationHides(row,'group',queue.snapshot()),false);
queue.enqueue({...command(),options:{stage:'black',conditions:[{field:'@product',operator:'EQUALS',value:'Q'}]}},base,[]);await tick();await tick();
assert.equal(queue.snapshot()[1].status,'completed');queue.dismiss(id);assert.equal(queue.snapshot().length,1);
});
test('network loss while reading progress pauses submission, retry resumes the same operation, reload does not create duplicates',async()=>{
let creates=0,reads=0;
const queue=new ClassificationQueue(deps({apply:async()=>{creates++;return{operationId:'same',status:'QUEUED'};},operation:async()=>{if(++reads===1)throw new Error('offline');return{operationId:'same',status:'COMPLETED'};}}));
const id=queue.enqueue(command(),base,[]);await tick();assert.equal(queue.snapshot()[0].status,'paused');queue.retry(id);await tick();assert.equal(creates,1);assert.equal(reads,2);assert.equal(queue.snapshot()[0].status,'completed');
const resumed=new ClassificationQueue(deps({apply:async()=>{throw new Error('must not create');}}),[{...command(),id:'restored',status:'running',operationId:'same'}]);await resumed.run();assert.equal(resumed.snapshot()[0].status,'completed');
});
test('queue validates conflicts before hiding and restores rows if target was removed before submission',async()=>{
const hold=deferred();const queue=new ClassificationQueue(deps({operation:()=>hold.promise}));queue.enqueue(command(),base,[]);
assert.throws(()=>queue.enqueue(command('P','Different'),base,[]),/相同条件/);assert.equal(queue.snapshot().length,1);
const missing=new ClassificationQueue(deps({status:async()=>({currentReleaseId:'r',activeMapping:{definition:{masterData:{groups:[]},matchRules:[]}}})}));missing.enqueue(command(),base,[]);await tick();assert.equal(missing.snapshot()[0].status,'failed');assert.equal(classificationHides(row,'group',missing.snapshot()),false);
hold.resolve({operationId:'job',status:'COMPLETED'});
});
test('project classifications hide only the matching customer/group key and preserve other dimensions',()=>{
const job={id:'p',status:'running',selection:{kind:'projectGroup',row:{customerCode:'001',businessGroup:'G'}},target:'Project',options:{}};
assert.equal(classificationHides({customerCode:'001',businessGroup:'G'},'projectGroup',[job]),true);
assert.equal(classificationHides({customerCode:'002',businessGroup:'G'},'projectGroup',[job]),false);
assert.equal(classificationHides(row,'group',[job]),false);
});
test('retry after a confirmed server failure creates a new update rather than polling the failed job forever',async()=>{
let creates=0;const queue=new ClassificationQueue(deps({apply:async()=>({operationId:'try'+(++creates),status:'QUEUED'}),operation:async id=>({operationId:id,status:id==='try1'?'FAILED':'COMPLETED'})}));
const id=queue.enqueue(command(),base,[]);await tick();assert.equal(queue.snapshot()[0].status,'failed');queue.retry(id);await tick();assert.equal(creates,2);assert.equal(queue.snapshot()[0].status,'completed');
});