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); });