统一:DSH 智能分析、Top100 与图表静默恢复

接入 DSH 专用运行时和对话界面,保留模型原始回答,支持会话分页、连续追问与显式报告。
补齐组合筛选、各维度 Top100、分组查询到排名图的转换,图表故障静默省略并基于保存数据自动恢复。
优化报告风格、图表顺序和表格换行,更新接入说明及构建输入。

验证:独立目录前后端构建通过;118 项 Java、102 项前端、102 项图表、14 项 DSH 应用和 13 项组合筛选检查通过。
仅提交相关源码、锁定依赖与测试;不包含凭据、会话、业务数据或本地产物。
This commit is contained in:
2026-11-12 11:57:41 +08:00
parent cc8832c8e5
commit f1a2fbd494
166 changed files with 26281 additions and 2248 deletions
+27 -5
View File
@@ -29,10 +29,15 @@ function isTableStart(lines: string[], index: number): boolean {
return separators.length > 0 && separators.every(cell => /^:?-{3,}:?$/.test(cell));
}
function isRule(line: string): boolean {
return /^\s{0,3}(?:(?:-\s*){3,}|(?:\*\s*){3,}|(?:_\s*){3,})$/.test(line);
}
function isBlockStart(lines: string[], index: number): boolean {
const line = lines[index];
return /^\s*#{1,6}\s+/.test(line)
|| /^\s*```/.test(line)
|| isRule(line) || /^\s{0,3}>/.test(line)
|| /^\s*(?:[-*+]\s+|\d+[.)]\s+)/.test(line)
|| isTableStart(lines, index);
}
@@ -57,9 +62,9 @@ function readingSentences(value: string, boundaries = '。!?;'): string[]
}
/** Renders the small Markdown subset used by analysis answers with React text nodes only. */
export function AiMarkdown({ content, className, evidenceLabels, evidencePrefix, layout }: { content: string; className?: string; evidenceLabels?: Record<string, string>; evidencePrefix?: string; layout?: 'conclusions' | 'sections' }) {
export function AiMarkdown({ content, className, evidenceLabels, evidencePrefix, layout, preserveSource = false }: { content: string; className?: string; evidenceLabels?: Record<string, string>; evidencePrefix?: string; layout?: 'conclusions' | 'sections'; preserveSource?: boolean }) {
const inline = (value: string, key: string) => inlineMarkdown(value, key, evidenceLabels, evidencePrefix);
const lines = sanitizeAnalysisDisplayText(content).replaceAll('\r\n', '\n').replaceAll('\r', '\n').split('\n');
const lines = (preserveSource ? content : sanitizeAnalysisDisplayText(content)).replaceAll('\r\n', '\n').replaceAll('\r', '\n').split('\n');
const blocks: ReactNode[] = [];
let index = 0;
let leadPending = layout === 'conclusions';
@@ -100,6 +105,22 @@ export function AiMarkdown({ content, className, evidenceLabels, evidencePrefix,
const line = lines[index];
if (!line.trim()) { index += 1; continue; }
if (isRule(line)) {
blocks.push(<hr key={`rule-${blocks.length}`} />);
index += 1;
continue;
}
if (/^\s{0,3}>/.test(line)) {
const quote: string[] = [];
while (index < lines.length && /^\s{0,3}>/.test(lines[index])) quote.push(lines[index++].replace(/^\s{0,3}> ?/, ''));
blocks.push(<blockquote key={`quote-${blocks.length}`}>{quote.flatMap((part, partIndex) => [
...(partIndex ? [<br key={`break-${partIndex}`} />] : []),
...inline(part, `quote-${blocks.length}-${partIndex}`),
])}</blockquote>);
continue;
}
const fence = line.match(/^\s*```([^`]*)$/);
if (fence) {
leadPending = false;
@@ -129,14 +150,15 @@ export function AiMarkdown({ content, className, evidenceLabels, evidencePrefix,
if (isTableStart(lines, index)) {
leadPending = false;
const headers = tableCells(lines[index]);
const hasIndex = ['序号', '排名', '名次'].includes(headers[0]?.replace(/[*`]/g, '').trim() || '');
const existingIndex = ['序号', '排名', '名次'].includes(headers[0]?.replace(/[*`]/g, '').trim() || '');
const hasIndex = preserveSource || existingIndex;
index += 2;
const body: string[][] = [];
while (index < lines.length && lines[index].trim() && lines[index].includes('|')) body.push(tableCells(lines[index++]));
const alignments = headers.map((header, column) => tableTextAlignment(header, body.map(row => row[column])));
blocks.push(<div className="ai-markdown-table-wrap" key={`table-${blocks.length}`}><table>
<thead><tr>{!hasIndex && <th className="ai-markdown-index">序号</th>}{headers.map((cell, cellIndex) => <th key={cellIndex} style={{ textAlign: alignments[cellIndex] === 'left' ? 'left' : undefined }} className={hasIndex && cellIndex === 0 ? 'ai-markdown-index' : undefined}>{inline(cell, `th-${cellIndex}`)}</th>)}</tr></thead>
<tbody>{body.map((row, rowIndex) => <tr key={rowIndex}>{!hasIndex && <td className="ai-markdown-index">{rowIndex + 1}</td>}{headers.map((_, cellIndex) => <td key={cellIndex} style={{ textAlign: alignments[cellIndex] === 'left' ? 'left' : undefined }} className={hasIndex && cellIndex === 0 ? 'ai-markdown-index' : undefined}>{inline(row[cellIndex] || '', `td-${rowIndex}-${cellIndex}`)}</td>)}</tr>)}</tbody>
<thead><tr>{!hasIndex && <th className="ai-markdown-index">序号</th>}{headers.map((cell, cellIndex) => <th key={cellIndex} style={{ textAlign: alignments[cellIndex] === 'left' ? 'left' : undefined }} className={existingIndex && cellIndex === 0 ? 'ai-markdown-index' : undefined}>{inline(cell, `th-${cellIndex}`)}</th>)}</tr></thead>
<tbody>{body.map((row, rowIndex) => <tr key={rowIndex}>{!hasIndex && <td className="ai-markdown-index">{rowIndex + 1}</td>}{headers.map((_, cellIndex) => <td key={cellIndex} style={{ textAlign: alignments[cellIndex] === 'left' ? 'left' : undefined }} className={[existingIndex && cellIndex === 0 && 'ai-markdown-index', alignments[cellIndex] === 'left' && 'ai-markdown-prose'].filter(Boolean).join(' ') || undefined}>{inline(row[cellIndex] || '', `td-${rowIndex}-${cellIndex}`)}</td>)}</tr>)}</tbody>
</table></div>);
if (tableNote) { blocks.push(note(tableNote)); tableNote = ''; }
continue;
+1 -1
View File
@@ -67,7 +67,7 @@ export function AnalysisApiSettings({ onUnauthorized }: { onUnauthorized: (error
<Button type="text" size="small" icon={<SettingOutlined />} onClick={() => void load()}>API 配置</Button>
<Modal title="API 配置" open={active && open} width={540} onCancel={close} footer={<>
<Button onClick={close} disabled={saving}>关闭</Button>
<Button loading={testing} disabled={loading || saving || !settings} onClick={() => void submit(true)}>测试连接</Button>
<Button loading={testing} disabled={loading || saving || !settings} onClick={() => void submit(true)}>测试模型连接</Button>
<Button type="primary" loading={saving} disabled={loading || testing || !settings} onClick={() => void submit(false)}>保存并使用</Button>
</>}>
{showLoading && !settings ? <div style={{ padding: 32, textAlign: 'center' }}><Spin /></div> : <>
+1 -1
View File
@@ -14,7 +14,7 @@ export function AnalysisConclusion({ reading, visuals, renderVisuals }: {
const repeatedFigureTitle = section.markdown.trim() === '' && section.visuals.length === 1
&& section.title === section.visuals[0].title && !(index === 0 && comparison);
return <section key={section.id} className="analysis-conclusion-section" data-conclusion-section={section.id}>
{!repeatedFigureTitle && <h3 className="analysis-conclusion-title">{section.title}</h3>}
{!section.implicitTitle && !repeatedFigureTitle && <h3 className="analysis-conclusion-title">{section.title}</h3>}
{index === 0 && comparison && <div className="analysis-comparison" aria-label={comparison.original}>
<div className="analysis-comparison-name">{comparison.metric}</div>
<div className="analysis-comparison-values">
+21
View File
@@ -0,0 +1,21 @@
import { analysisMemberListFullyRead, analysisMemberListPeriod, parseAnalysisMemberList } from './analysisMembersModel';
import { tableTextAlignment } from './tableTextAlignment';
export function AnalysisMemberListReport({ value }: { value: unknown }) {
const memberList = parseAnalysisMemberList(value);
if (!memberList) return null;
const alignments = Object.fromEntries(memberList.fields.map(field => [field.key, tableTextAlignment(field.label, memberList.rows.map(row => row.values[field.key]))]));
const coverage = analysisMemberListFullyRead(memberList) ? `已读取全部 ${memberList.rowsReturned} 条`
: `${memberList.queryComplete ? '已读取' : '读取未完成'} ${memberList.rowsReturned} / ${memberList.totalCount} 条`;
return <details className="q-member-list"><summary>完整成员清单</summary>
<h2>成员清单</h2>
<p>{analysisMemberListPeriod(memberList.period)} · {coverage}</p>
<div className="ai-markdown-table-wrap"><table>
<thead><tr><th>序号</th>{memberList.fields.map(field => <th key={field.key} style={{ textAlign: alignments[field.key] === 'left' ? 'left' : undefined }}>{field.label}</th>)}<th>阶段</th></tr></thead>
<tbody>{memberList.rows.map((row, index) => <tr key={index}>
<td>{index + 1}</td>{memberList.fields.map(field => <td key={field.key} style={{ textAlign: alignments[field.key] === 'left' ? 'left' : undefined }}>{row.values[field.key] == null || row.values[field.key] === '' ? '—' : String(row.values[field.key])}</td>)}
<td>{row.stages.map(stage => stage === 'black' ? '黑片' : '亮片').join('、')}</td>
</tr>)}</tbody>
</table></div>
</details>;
}
+6 -19
View File
@@ -1,4 +1,5 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { AnalysisMemberListReport } from './AnalysisMemberListReport';
import { Alert, Button, Modal } from 'antd';
import { DownloadOutlined } from '@ant-design/icons';
import { AnalysisLegacyResults } from './AnalysisLegacyResults';
@@ -16,10 +17,9 @@ import { reportSnapshotIdentity } from './analysisSnapshot';
import { analysisDisplayTextRemovalRanges, sanitizeAnalysisDisplayText } from './analysisDisplayText';
import { resolveAnalysisReportTitle, stripDuplicateFirstMarkdownH1 } from './analysisReportTitle';
import { useReportVisualImages, type ReportVisualImage } from './AnalysisReportVisuals';
import { analysisMemberListFullyRead, analysisMemberListPeriod, parseAnalysisMemberList } from './analysisMembersModel';
import { AnalysisRecordListReport, appendAnalysisRecordReportHtml } from './AnalysisRecordList';
import { useDelayedIndicator } from './useDelayedBusy';
import { alignReportTableText, tableTextAlignment } from './tableTextAlignment';
import { alignReportTableText } from './tableTextAlignment';
type Row = Record<string, unknown>;
const record = (value: unknown): Row => value && typeof value === 'object' && !Array.isArray(value) ? value as Row : {};
@@ -44,14 +44,10 @@ export function ReportDocument({ turn, stamp, visualImages }: { turn: Row; stamp
const sourceAnswer = sanitizeAnalysisDisplayText(text(reportMarkdown || result.answer || turn.answer));
const model = buildAnalysisNarrative(sourceAnswer, result.visuals || turn.visuals);
const scope = analysisScopeText(turn);
const title = resolveAnalysisReportTitle(result.reportTitle, turn.reportTitle, reportMarkdown, model.period, scope);
const title = resolveAnalysisReportTitle(result.reportTitle, turn.reportTitle, reportMarkdown, model.period, scope,
model.sections?.flatMap(section => section.visuals ?? [])[0]?.title);
const answer = sanitizeAnalysisDisplayText(stripDuplicateFirstMarkdownH1(sourceAnswer, title));
const memberList = parseAnalysisMemberList(result.memberList ?? turn.memberList);
const memberAlignments = Object.fromEntries(memberList?.fields.map(field => [field.key, tableTextAlignment(field.label, memberList.rows.map(row => row.values[field.key]))]) ?? []);
const recordListValue = result.recordList ?? turn.recordList;
const memberListStatus = memberList && analysisMemberListFullyRead(memberList)
? `已读取全部 ${memberList.rowsReturned} 条`
: memberList ? `${memberList.queryComplete ? '已读取' : '读取未完成'} ${memberList.rowsReturned} / ${memberList.totalCount} 条` : '';
return <div className="q-report">
<style>{reportCss}</style>
<header><div className="q-eyebrow">质量数据分析平台 · 分析报告</div><h1>{title}</h1>
@@ -62,16 +58,7 @@ export function ReportDocument({ turn, stamp, visualImages }: { turn: Row; stamp
<AnalysisReportNarrative turn={turn} answer={answer} images={visualImages} mode="full" />
<AnalysisLegacyResults turn={turn} />
{recordListValue !== undefined && recordListValue !== null && <details className="q-report-appendix"><summary>附录:完整来源记录</summary><AnalysisRecordListReport value={recordListValue} /></details>}
{memberList && <details className="q-report-appendix"><summary>附录:完整成员清单</summary><section className="q-member-list">
<h2>成员清单</h2>
<p className="q-note">{analysisMemberListPeriod(memberList.period)} · {memberListStatus}</p>
<table><thead><tr><th>序号</th>{memberList.fields.map(field => <th key={field.key} style={{ textAlign: memberAlignments[field.key] === 'left' ? 'left' : undefined }}>{field.label}</th>)}<th>阶段</th></tr></thead>
<tbody>{memberList.rows.map((row, index) => <tr key={index}>
<td>{index + 1}</td>{memberList.fields.map(field => <td key={field.key} style={{ textAlign: memberAlignments[field.key] === 'left' ? 'left' : undefined }}>{text(row.values[field.key])}</td>)}
<td>{row.stages.map(stage => stage === 'black' ? '黑片' : '亮片').join('、')}</td>
</tr>)}</tbody>
</table>
</section></details>}
<AnalysisMemberListReport value={result.memberList ?? turn.memberList} />
{!parseServerReadingSummary(turn) && <footer>数据来源:质量数据分析平台。指标沿用正式计算口径;现场原因以实际核查为准。</footer>}
</div>;
}
@@ -253,7 +240,7 @@ function ReportExportDialog({ turn, reportMarkdown, reportHtml, native = false }
const answer = sanitizeAnalysisDisplayText(text(markdown || result.answer || reportTurn.answer));
const metadata = buildAnalysisNarrative(answer, result.visuals || reportTurn.visuals);
const title = resolveAnalysisReportTitle(result.reportTitle, reportTurn.reportTitle, markdown,
metadata.period, analysisScopeText(reportTurn));
metadata.period, analysisScopeText(reportTurn), metadata.sections?.flatMap(section => section.visuals ?? [])[0]?.title);
const withNarrative = integrateNativeReportNarrative(safeNativeHtml(reportHtml, title), reportTurn, visualReport.images);
return compactNativeReportReading(appendAnalysisRecordReportHtml(withNarrative, result.recordList ?? reportTurn.recordList), reportTurn);
}, [reportHtml, reportTurn, visualReport.images]);
+26 -16
View File
@@ -1,21 +1,28 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { parseAnalysisVisuals, combineStageDefectVisuals, renderVisualPng, visualPeriodSummary, visualScopeSummary, visualCategoryLabel } from './analysisVisualsModel';
import { parseAnalysisVisuals, combineStageDefectVisuals, renderVisualSvg, visualPeriodSummary, visualScopeSummary, visualCategoryLabel } from './analysisVisualsModel';
import { analysisSnapshotResult, authorizeAnalysisSnapshot, reportSnapshotIdentity } from './analysisSnapshot';
import type { AnalysisVisual } from './analysisVisualsModel';
import type { AnalysisVisual, AnalysisVisualRenderContext } from './analysisVisualsModel';
import { analysisVisualCumulativeShares, analysisVisualShares } from './analysisVisualPresentation';
import { agentReportVisuals, agentReportChartWidth } from './agent/agentReportLayout';
type Row = Record<string, unknown>;
export type ReportVisualImage = { id: string; png?: string; failed?: boolean };
export type ReportVisualImage = { id: string; svg?: string; png?: string; failed?: boolean };
export function reportVisuals(turn: Row) {
const result = analysisSnapshotResult(turn);
return result.visualSchemaVersion === 1 ? combineStageDefectVisuals(parseAnalysisVisuals(result.visuals, 1).visuals) : [];
export function reportVisualImageSource(image?: ReportVisualImage): string {
if (image?.svg && /^data:image\/svg\+xml;charset=utf-8,(?:%[0-9a-f]{2}|[a-z0-9_.!~*'()-])*$/i.test(image.svg)) return image.svg;
return image?.png && /^data:image\/png;base64,[A-Za-z0-9+/=]+$/.test(image.png) ? image.png : '';
}
export function useReportVisualImages(turn: Row, open: boolean) {
export function reportVisuals(turn: Row, context: AnalysisVisualRenderContext = 'report') {
const result = analysisSnapshotResult(turn);
const visuals = result.visualSchemaVersion === 1 ? parseAnalysisVisuals(result.visuals, 1).visuals : [];
return context === 'agent-document' ? agentReportVisuals(visuals, String(turn.question || '')) : combineStageDefectVisuals(visuals);
}
export function useReportVisualImages(turn: Row, open: boolean, context: AnalysisVisualRenderContext = 'report') {
const signature = `${String(turn.id || turn.turnId || '')}:${reportSnapshotIdentity(turn)}`;
const visualsSignature = JSON.stringify(reportVisuals(turn));
const visuals = useMemo(() => reportVisuals(turn), [visualsSignature]);
const visualsSignature = JSON.stringify(reportVisuals(turn, context));
const visuals = useMemo(() => reportVisuals(turn, context), [visualsSignature]);
const [images, setImages] = useState<ReportVisualImage[]>([]);
const [loading, setLoading] = useState(false);
const [progress, setProgress] = useState('');
@@ -45,7 +52,8 @@ export function useReportVisualImages(turn: Row, open: boolean) {
for (const [index, visual] of plotted.entries()) {
if (controller.signal.aborted) return;
setProgress(`正在准备图表 ${index + 1}/${plotted.length}`);
try { next.push({ id: visual.id, png: await renderVisualPng(visual, controller.signal, 'report') }); }
try { next.push({ id: visual.id, svg: await renderVisualSvg(visual, controller.signal, context,
context === 'agent-document' ? agentReportChartWidth(visual, plotted, String(turn.question || '')) : undefined) }); }
catch { if (controller.signal.aborted) return; next.push({ id: visual.id, failed: true }); }
}
if (!controller.signal.aborted) setImages(next);
@@ -56,7 +64,7 @@ export function useReportVisualImages(turn: Row, open: boolean) {
}
})();
return () => controller.abort();
}, [open, revision, signature, String(turn.id || turn.turnId || '')]);
}, [open, revision, signature, context, String(turn.id || turn.turnId || '')]);
const current = open && authorization.revision === revision && authorization.signature === signature;
const authorize = async () => {
try { await authorizeAnalysisSnapshot(turn); }
@@ -85,12 +93,14 @@ export function ReportVisualDataTable({ visual }: { visual: AnalysisVisual }) {
<tbody>{visual.categories.map((category, index) => <tr key={category.key}><td>{index + 1}</td><td>{visualCategoryLabel(visual, index)}</td>{visual.series.map(series => <td key={series.key}>{shown(series.values[index] ?? null, visual.unit, visual.metric)}</td>)}{shares && <td>{(shares[index] * 100).toFixed(2)}%</td>}{cumulativeShares && <td>{(cumulativeShares[index] * 100).toFixed(2)}%</td>}</tr>)}</tbody></table>;
}
export function ReportVisualFigure({ visual, image, evidenceLabels = {}, evidencePrefix = '', hideEvidence = false }: { visual: AnalysisVisual; image?: ReportVisualImage; evidenceLabels?: Record<string, string>; evidencePrefix?: string; hideEvidence?: boolean }) {
export function ReportVisualFigure({ visual, image, evidenceLabels = {}, evidencePrefix = '', hideEvidence = false, quiet = false }: { visual: AnalysisVisual; image?: ReportVisualImage; evidenceLabels?: Record<string, string>; evidencePrefix?: string; hideEvidence?: boolean; quiet?: boolean }) {
const source = reportVisualImageSource(image);
if (quiet && (!source || image?.failed || !visual.chartable)) return null;
return <figure className="q-report-visual">
<div className="q-report-visual-heading"><strong>{visual.title}</strong><span>{visual.unit === 'pp' ? '百分点' : visual.unit === 'ratio' ? '%' : visual.unit}</span></div>
{image?.png && <img src={image.png} alt={visual.title} />}
{(!image?.png || image.failed || !visual.chartable) && <><p className="q-partial">此图以同一份结果的数据表显示。</p><ReportVisualDataTable visual={visual} /></>}
{source && <img src={source} alt={visual.title} />}
{(!source || image?.failed || !visual.chartable) && <><p className="q-partial">此图以同一份结果的数据表显示。</p><ReportVisualDataTable visual={visual} /></>}
<figcaption>{visualPeriodSummary(visual)}{visualScopeSummary(visual.scope) ? ` · ${visualScopeSummary(visual.scope)}` : ''}{visual.coverage.truncated ? ` · 展示 ${visual.coverage.returnedRows} / ${visual.coverage.totalRows} 项` : ''}
{visual.note && <span> · {visual.note}</span>}
{!hideEvidence && visual.evidenceRefs.map(ref => <a className="analysis-evidence-ref" key={ref} href={`#${evidencePrefix}${ref}`} title={ref}>{evidenceLabels[ref] || ref}</a>)}
@@ -112,10 +122,10 @@ export function reportVisualHtml(turn: Row, images: ReportVisualImage[]): string
const cumulativeShares = analysisVisualCumulativeShares(visual);
const headers = visual.series.map(series => `<th>${escapeHtml(series.label)}</th>`).join('') + (shares ? `<th>${visual.coverage.shareBasis === 'all_scope_weight' ? '占全部重量' : '占已列类别合计'}</th>` : '') + (cumulativeShares ? `<th>${visual.coverage.shareBasis === 'all_scope_weight' ? '累计占全部重量' : '累计占已列类别合计'}</th>` : '');
const rows = visual.categories.map((_category, index) => `<tr><td>${index + 1}</td><td>${escapeHtml(visualCategoryLabel(visual, index))}</td>${visual.series.map(series => `<td>${escapeHtml(shown(series.values[index] ?? null, visual.unit, visual.metric))}</td>`).join('')}${shares ? `<td>${(shares[index] * 100).toFixed(2)}%</td>` : ''}${cumulativeShares ? `<td>${(cumulativeShares[index] * 100).toFixed(2)}%</td>` : ''}</tr>`).join('');
const png = image?.png && /^data:image\/png;base64,[A-Za-z0-9+/=]+$/.test(image.png) ? image.png : '';
const source = reportVisualImageSource(image);
const context = `期间:${visualPeriodSummary(visual)}${visualScopeSummary(visual.scope) ? ` · 范围:${visualScopeSummary(visual.scope)}` : ''}`;
const table = `<table style="width:100%;border-collapse:collapse;font-size:13px" border="1"><thead><tr><th>序号</th><th>对象 / 期间</th>${headers}</tr></thead><tbody>${rows}</tbody></table>`;
const picture = png ? `<img alt="${escapeHtml(visual.title)}" src="${png}" style="display:block;width:100%;height:auto">` : '';
const picture = source ? `<img alt="${escapeHtml(visual.title)}" src="${escapeHtml(source)}" style="display:block;width:100%;height:auto">` : '';
const detail = picture ? `<details style="margin:10px 0;font-size:12px"><summary style="cursor:pointer">查看本图数据</summary>${table}</details>` : `<p>此图以数据表显示。</p>${table}`;
return `<section class="platform-report-visual" style="break-inside:avoid;padding:14px 0;color:#202b3c;background:white"><h3 style="margin:6px 0 10px;font-size:16px">${escapeHtml(visual.title)}</h3>${picture}<p style="font-size:12px;color:#65748b">${escapeHtml(context)}${visual.note ? ` · ${escapeHtml(visual.note)}` : ''}</p>${detail}<p style="font-size:11px;color:#65748b">数据依据:${escapeHtml(visual.evidenceRefs.join('、'))}</p></section>`;
}).join('');
+9 -5
View File
@@ -27,6 +27,7 @@ export interface AnalysisVisualsProps {
embedded?: boolean;
hideEvidence?: boolean;
combineStages?: boolean;
quiet?: boolean;
}
interface VisualTableRow {
@@ -114,11 +115,12 @@ function chartSummary(visual: AnalysisVisual): string {
return `${visual.title}。${visual.subtitle}。期间:${visualPeriodSummary(visual)}。${visual.categories.length} 个对象,${visual.series.map(item => item.label).join('、')}。${visualScopeSummary(visual.scope)}`;
}
export function AnalysisVisualCard({ visual, beforeExport, loadRuntime = loadAnalysisVisualECharts, hideEvidence = false }: {
export function AnalysisVisualCard({ visual, beforeExport, loadRuntime = loadAnalysisVisualECharts, hideEvidence = false, quiet = false }: {
visual: AnalysisVisual;
beforeExport?: () => Promise<void>;
loadRuntime?: typeof loadAnalysisVisualECharts;
hideEvidence?: boolean;
quiet?: boolean;
}) {
const cardRef = useRef<HTMLElement>(null);
const chartNodeRef = useRef<HTMLDivElement>(null);
@@ -293,6 +295,7 @@ export function AnalysisVisualCard({ visual, beforeExport, loadRuntime = loadAna
? `本图展示 ${visual.coverage.returnedRows} / 共 ${visual.coverage.totalRows} 项`
: `共 ${visual.coverage.totalRows} 项`;
if (quiet && (accessBlocked || chartError || !visual.chartable)) return null;
if (accessBlocked) return <article className="analysis-visual-card" ref={cardRef}>
<p role="alert">{exportError || '无法验证此图表的访问权限,已隐藏原数据。'}</p>
<Button size="small" loading={retrying} onClick={() => void retryChart()}>重试图表</Button>
@@ -329,7 +332,7 @@ export function AnalysisVisualCard({ visual, beforeExport, loadRuntime = loadAna
tabIndex={chartError ? -1 : 0}
aria-label={`${chartSummary(visual)}。按 Enter 或空格查看数据。`}
aria-busy={chartLoading}
style={visual.sectionKey === 'defect_combined' ? { height: Math.max(320, visual.categories.length * 38 + 48) } : undefined}
style={visual.type === 'bar' ? { height: Math.max(320, visual.categories.length * 38 + 48) } : undefined}
onClick={chartError ? undefined : openData}
onKeyDown={event => {
if (chartError) return;
@@ -355,7 +358,7 @@ export function AnalysisVisualCard({ visual, beforeExport, loadRuntime = loadAna
<p className="analysis-visual-chart-error" role="status">{visual.chartIssue || '此图表暂以数据表显示'}</p>
<ChartDataTable visual={visual} compact />
</>}
{exportError && <p className="analysis-visual-export-error" role="alert">{exportError}</p>}
{!quiet && exportError && <p className="analysis-visual-export-error" role="alert">{exportError}</p>}
<Modal
className="analysis-visual-modal"
open={dataOpen}
@@ -377,19 +380,20 @@ export function AnalysisVisualCard({ visual, beforeExport, loadRuntime = loadAna
}
/** A bad or old visual payload is confined to this module; it never interrupts the answer text. */
export function AnalysisVisuals({ visuals, visualState, beforeExport, embedded = false, hideEvidence = false, combineStages = true }: AnalysisVisualsProps) {
export function AnalysisVisuals({ visuals, visualState, beforeExport, embedded = false, hideEvidence = false, combineStages = true, quiet = false }: AnalysisVisualsProps) {
const parsed = useMemo(() => {
const result = parseAnalysisVisuals(visuals);
return { ...result, visuals: combineStages ? combineStageDefectVisuals(result.visuals) : result.visuals };
}, [visuals, combineStages]);
if (!parsed.visuals.length) {
if (quiet) return null;
const state = visualStateName(visualState);
if (state === 'building') return <div className="analysis-visual-state" role="status">图表整理中</div>;
if (state === 'failed' || state === 'unavailable') return <div className="analysis-visual-state" role="status">图表暂不可用,已保留分析结果。</div>;
return null;
}
return <section className={`analysis-visuals${embedded ? ' is-embedded' : ''}`} aria-label="分析图表">
{parsed.visuals.map(visual => <AnalysisVisualCard key={visual.id} visual={visual} beforeExport={beforeExport} hideEvidence={hideEvidence} />)}
{parsed.visuals.map(visual => <AnalysisVisualCard key={visual.id} visual={visual} beforeExport={beforeExport} hideEvidence={hideEvidence} quiet={quiet} />)}
</section>;
}
+4 -2
View File
@@ -13,13 +13,15 @@ import { canAccessWorkspacePage } from './userRoles';
const loadQueryPage = () => import('./QueryPage');
const loadStageProductPage = () => import('./StageProductPage');
const loadManagementPages = () => import('./ManagementPages');
const loadAgentWorkspace = () => import('./agent/AgentWorkspace');
const QueryPage = lazy(loadQueryPage);
const StageProductPage = lazy(loadStageProductPage);
const ManagementPages = lazy(loadManagementPages);
const AgentWorkspace = lazy(loadAgentWorkspace);
export function preloadWorkspacePage(page: PageKey): Promise<unknown> {
return page === 'blackProduct' || page === 'brightProduct' ? loadStageProductPage()
: QUERY_PAGES.includes(page) ? loadQueryPage() : loadManagementPages();
: page === 'analysis' ? loadAgentWorkspace() : QUERY_PAGES.includes(page) ? loadQueryPage() : loadManagementPages();
}
const QUERY_PAGES: PageKey[] = ['overall', 'department', 'group', 'product', 'blackProduct', 'brightProduct'];
const retained = (_page: PageKey) => true;
@@ -186,7 +188,7 @@ export const CachedWorkspacePages = forwardRef<WorkspaceNavigation, {
return <div key={`${name}-${entry.key}`} className="page-view" data-page={name} hidden={!active} inert={active && navigationBusy} style={!active ? { display: 'none' } : undefined}>
<PageCacheContext.Provider value={{ active, initialSearch: entry.initialSearch, refreshKey: refreshKey + (entry.revision || 0), currentReleaseId: revisions.current?.currentReleaseId, authRevision: revisions.current?.authRevision, dataRevision: revisions.current?.dataRevision, onLocationChange: search => { entry.search = search; } }}>
<Suspense fallback={<div className="loading-panel"><Spin />正在打开页面…</div>}>
{!canAccessWorkspacePage(user, name) ? <Alert type="info" showIcon message="当前角色没有此页面的访问权限" action={<Button onClick={() => navigate('overall')}>返回质量查询</Button>} /> : name === 'blackProduct' || name === 'brightProduct' ? <StageProductPage stage={name === 'blackProduct' ? 'black' : 'bright'} onUnauthorized={onUnauthorized} /> : QUERY_PAGES.includes(name) ? <QueryPage page={name} onUnauthorized={onUnauthorized} onNavigate={navigate} /> : <ManagementPages page={name} user={user} onUnauthorized={onUnauthorized} onNavigate={navigate} />}
{!canAccessWorkspacePage(user, name) ? <Alert type="info" showIcon message="当前角色没有此页面的访问权限" action={<Button onClick={() => navigate('overall')}>返回质量查询</Button>} /> : name === 'analysis' ? <AgentWorkspace user={user} onUnauthorized={onUnauthorized} /> : name === 'blackProduct' || name === 'brightProduct' ? <StageProductPage stage={name === 'blackProduct' ? 'black' : 'bright'} onUnauthorized={onUnauthorized} /> : QUERY_PAGES.includes(name) ? <QueryPage page={name} onUnauthorized={onUnauthorized} onNavigate={navigate} /> : <ManagementPages page={name} user={user} onUnauthorized={onUnauthorized} onNavigate={navigate} />}
</Suspense>
</PageCacheContext.Provider>
</div>;
File diff suppressed because it is too large Load Diff
+165
View File
@@ -0,0 +1,165 @@
import { memo, useEffect, useMemo, useState } from 'react';
import { Button } from 'antd';
import { ApartmentOutlined, CheckOutlined, ClockCircleOutlined, CloseOutlined, FileTextOutlined, LoadingOutlined, RightOutlined } from '@ant-design/icons';
import { AnalysisClarification } from '../AnalysisClarification';
import { AnalysisMemberListPanel } from '../AnalysisMemberList';
import { AnalysisVisuals } from '../AnalysisVisuals';
import { AnalysisRecordListPanel } from '../AnalysisRecordList';
import { AiMarkdown } from '../AiMarkdown';
import { AnalysisThinkingBlock } from '../ModelThinkingPanel';
import { analysisIsRunning, compactAnalysisTimeline } from '../analysisConversationState';
import { orderedAnalysisProcess, type ModelThinking } from '../analysisModelThinking';
import { analysisScopeText } from '../analysisScope';
import { analysisSnapshotResult, authorizeAnalysisSnapshot } from '../analysisSnapshot';
import { sanitizeAnalysisDisplayText } from '../analysisDisplayText';
import { useAnalysisVisualRecovery } from '../analysisVisualRecovery';
import { authoredReport } from './AgentDeliverable';
type Row = Record<string, unknown>;
const record = (value: unknown): Row => value && typeof value === 'object' && !Array.isArray(value) ? value as Row : {};
const string = (value: unknown) => typeof value === 'string' ? value : '';
const FILTER_LABELS: Record<string, string> = {
year: '年', month: '月', quarter: '季度', monthStart: '起始月份', monthEnd: '结束月份',
department: '产业部', group: '业务分组', product: '产品', projectGroup: '项目组',
period: '期间', comparisonPeriod: '对比期间', filters: '筛选', dimension: '维度',
stage: '阶段', category: '报废类别', defect: '具体缺陷', metric: '排名指标', limit: '数量',
};
const FILTER_VALUES: Record<string, string> = { overall: '总体', department: '产业部', group: '业务分组', product: '产品', black: '黑片', bright: '亮片', both: '黑片和亮片', all: '全部', totalWeight: '投入重量', scrapWeight: '报废重量' };
function fieldValue(value: unknown): string {
if (typeof value === 'string') return sanitizeAnalysisDisplayText(FILTER_VALUES[value] || value).slice(0, 160);
if (typeof value === 'number' && Number.isFinite(value)) return String(value);
if (typeof value === 'boolean') return value ? '是' : '否';
if (Array.isArray(value)) return value.slice(0, 12).map(fieldValue).filter(Boolean).join('、');
return Object.entries(record(value)).flatMap(([key, item]) => {
const label = FILTER_LABELS[key];
const field = label ? fieldValue(item) : '';
return field ? [`${label} ${field}`] : [];
}).join(' · ');
}
function executionEvents(turn: Row): Row[] {
const result = analysisSnapshotResult(turn);
const plan = record(turn.plan);
const entries = turn.timeline ?? result.timeline ?? plan.timeline;
const steps = turn.steps ?? result.steps ?? plan.steps;
const timeline = compactAnalysisTimeline(Array.isArray(entries) ? entries.map(record) : []);
const fallback = Array.isArray(steps) ? steps.map((value, index) => {
const step = record(value);
return { ...step, kind: 'tool', sequence: index, at: step.startedAt, text: step.outputSummary,
hasResult: ['COMPLETED', 'SUCCEEDED', 'FAILED'].includes(String(step.status || '').toUpperCase()) };
}) : [];
return orderedAnalysisProcess(turn, (timeline.length ? timeline : fallback).filter(entry => entry.kind === 'tool'));
}
function eventState(entry: Row, running: boolean) {
const status = String(entry.status || '').toUpperCase();
if (entry.recovered || ['COMPLETED', 'SUCCEEDED'].includes(status)) return 'complete';
if (['FAILED', 'ERROR'].includes(status)) return 'failed';
if (entry.hasResult) return 'complete';
return running ? 'running' : 'stopped';
}
function ToolCall({ entry, running }: { entry: Row; running: boolean }) {
const state = eventState(entry, running);
const label = sanitizeAnalysisDisplayText(string(entry.label)) || '查询质量数据';
const description = sanitizeAnalysisDisplayText(string(entry.text || entry.outputSummary));
const fields = Object.entries(record(entry.input)).flatMap(([key, value]) => {
const label = FILTER_LABELS[key];
const shown = label ? fieldValue(value) : '';
return shown ? [{ key, label, shown }] : [];
});
const statuses = { complete: '已返回', failed: '未成功', running: '执行中', stopped: '已停止' };
return <details className={`agent-tool-call is-${state}`} data-agent-tool={String(entry.toolCallId || entry.key || '')}>
<summary>
{state === 'running' ? <LoadingOutlined /> : state === 'complete' ? <CheckOutlined /> : state === 'failed' ? <CloseOutlined /> : <ClockCircleOutlined />}
<span className="agent-tool-name">{label}</span>
<span className="agent-tool-status">{statuses[state]}</span>
<RightOutlined className="agent-disclosure" aria-hidden="true" />
</summary>
<div className="agent-tool-detail">
{fields.length > 0 && <dl>{fields.map(field => <div key={field.key}><dt>{field.label}</dt><dd>{field.shown}</dd></div>)}</dl>}
{description && <p>{description}</p>}
</div>
</details>;
}
function RunStatus({ turn }: { turn: Row }) {
const running = analysisIsRunning(turn.status) || turn.status === 'SUBMITTING';
const [clock, setClock] = useState(Date.now);
useEffect(() => {
if (!running) return;
setClock(Date.now());
const interval = window.setInterval(() => setClock(Date.now()), 1000);
return () => clearInterval(interval);
}, [running, turn.id, turn.startedAt]);
const plan = record(turn.plan);
const status = String(turn.status || '');
const labels: Record<string, string> = { SUBMITTING: '提交中', QUEUED: '排队中', RUNNING: '分析中', COMPLETED: '已完成', PARTIAL: '部分完成',
FAILED: '未完成', CANCELLED: '已停止', NEEDS_CLARIFICATION: '需要补充条件' };
const phase = running ? sanitizeAnalysisDisplayText(string(turn.progressMessage ?? plan.progressMessage)) : '';
const started = Date.parse(string(turn.startedAt ?? turn.createdAt ?? turn._uiSubmittedAt));
const duration = !running && typeof turn.durationMs === 'number' ? turn.durationMs : running && Number.isFinite(started) ? Math.max(0, clock - started) : undefined;
const seconds = duration === undefined ? undefined : Math.floor(duration / 1000);
return <span className={running ? 'agent-run-status is-running' : 'agent-run-status'}>
{running && <LoadingOutlined aria-hidden="true" />}
<span>{phase || labels[status] || '分析记录'}</span>
{seconds !== undefined && <time>{seconds >= 60 ? `${Math.floor(seconds / 60)} 分 ` : ''}{seconds % 60} 秒</time>}
</span>;
}
function ExecutionEvents({ events, running }: { events: Row[]; running: boolean }) {
return <div className="agent-execution-events">{events.map(entry => entry.kind === 'thinking'
? <AnalysisThinkingBlock key={String(entry.key)} entry={entry as unknown as ModelThinking} running={running} />
: <ToolCall key={String(entry.toolCallId || entry.key)} entry={entry} running={running} />)}</div>;
}
export const AgentConversationTurn = memo(function AgentConversationTurn({ turn: source, canAct, latest, onUnauthorized, onPrompt, onRetry, onReport }: {
turn: Row; canAct: boolean; latest: boolean; onUnauthorized: (error: unknown) => boolean;
onPrompt: (question: string) => Promise<void>; onRetry: (id: string) => void; onReport: (id: string) => void;
}) {
const recovery = useAnalysisVisualRecovery(source, onUnauthorized, canAct);
const turn = recovery.turn;
const result = analysisSnapshotResult(turn);
const status = String(turn.status || result.status || '').toUpperCase();
const id = String(turn.id || '');
const question = string(turn.question);
const answer = string(result.modelAnswer ?? turn.modelAnswer ?? result.answer ?? turn.answer);
const running = analysisIsRunning(status) || status === 'SUBMITTING';
const draft = running ? string(turn.dshDraft) : '';
const events = useMemo(() => executionEvents(turn), [turn]);
const artifact = !running ? authoredReport(turn) : null;
const [open, setOpen] = useState(running);
useEffect(() => { setOpen(running); }, [running, id]);
const notice = !answer && !running ? sanitizeAnalysisDisplayText(string(result.message ?? turn.message)
|| (status === 'FAILED' ? string(record(result.completion).reason ?? result.stopReason ?? turn.stopReason) : '')) : '';
const scope = running ? '' : analysisScopeText(turn);
const canRetry = canAct && latest && id && turn.retryAvailable !== false && ['FAILED', 'CANCELLED', 'PARTIAL'].includes(status);
return <article className="agent-turn" data-analysis-turn-id={id} data-analysis-status={status}>
{question && <div className="agent-user-message">{question}</div>}
<div className="agent-assistant-message">
{events.length ? <details className="agent-run-disclosure" open={open} onToggle={event => setOpen(event.currentTarget.open)}>
<summary><ApartmentOutlined /><RunStatus turn={turn} /><RightOutlined className="agent-disclosure" /></summary>
{open && <ExecutionEvents events={events} running={running} />}
</details> : <RunStatus turn={turn} />}
{artifact && scope && <div className="agent-answer-meta">
{scope && <p className="agent-turn-scope">{scope}</p>}
</div>}
{running && draft && <div className="agent-draft" aria-label="生成中的草稿"><small>草稿 · 正在生成</small><AiMarkdown content={draft} preserveSource /></div>}
{!running && status === 'NEEDS_CLARIFICATION' && latest && <AnalysisClarification turn={turn} disabled={!canAct} onContinue={onPrompt} />}
{!running && status !== 'NEEDS_CLARIFICATION' && (artifact
? <AiMarkdown content={answer} className="agent-model-answer" preserveSource />
: answer ? <><AiMarkdown content={answer} className="agent-model-answer" preserveSource />
{result.visualSchemaVersion === 1 && <AnalysisVisuals visuals={result.visuals} visualState={result.visualState}
beforeExport={() => authorizeAnalysisSnapshot(turn)} embedded quiet />}</>
: notice ? <p className="agent-turn-notice" role="status">{notice}</p> : null)}
{artifact && <button type="button" className="agent-report-open" onClick={() => onReport(id)}><FileTextOutlined />{artifact.title}.html<RightOutlined /></button>}
{canRetry && <div className="agent-turn-actions">
{canRetry && <Button type="text" size="small" onClick={() => onRetry(id)}>重新分析</Button>}
</div>}
{!running && result.memberList != null && <AnalysisMemberListPanel turn={turn} value={result.memberList} onUnauthorized={onUnauthorized} />}
{!running && result.recordList != null && <AnalysisRecordListPanel turn={turn} value={result.recordList} onUnauthorized={onUnauthorized} />}
</div>
</article>;
});
+170
View File
@@ -0,0 +1,170 @@
import { useLayoutEffect, useRef, useState } from 'react';
import { Alert, Button, Modal, Spin } from 'antd';
import { DownloadOutlined } from '@ant-design/icons';
import { AnalysisMemberListReport } from '../AnalysisMemberListReport';
import { AiMarkdown } from '../AiMarkdown';
import { AnalysisRecordListReport } from '../AnalysisRecordList';
import { ReportVisualFigure, reportVisualImageSource, reportVisuals, useReportVisualImages } from '../AnalysisReportVisuals';
import { captureReportLongImage } from '../analysisReportCapture';
import { downloadAuthorizedReport } from '../analysisReportFiles';
import { stripDuplicateFirstMarkdownH1 } from '../analysisReportTitle';
import { analysisSnapshotResult, reportSnapshotIdentity } from '../analysisSnapshot';
import { analysisScopeText } from '../analysisScope';
import documentCss from './agent-document.css?inline';
import './agent-document.css';
import { buildAgentReportLayout, agentReportPrimary, agentReportSupplementary } from './agentReportLayout';
type Row = Record<string, unknown>;
export function reportRequested(question: string): boolean {
const clauses = question.split(/[。!?;\n]/);
return clauses.some(clause => /报告|简报|排查纪要/.test(clause)
&& !/(?:不用|不必|不要|无需|不需要|别|避免|不生成|不输出|不写)/.test(clause)
&& /(?:生成|输出|编写|撰写|写|制作|形成|起草|给我|提供|整理|出|做).*(?:报告|简报|排查纪要)|(?:分析|对比|质量|复盘|管理|诊断|专题)(?:报告|简报)\s*$/.test(clause));
}
export function authoredReport(turn: Row) {
if (!['COMPLETED', 'PARTIAL', 'FAILED', 'CANCELLED'].includes(String(turn.status))) return null;
const result = analysisSnapshotResult(turn);
const plan = (turn.plan || {}) as Row;
const task = (result.task || result.agentTask || turn.task || plan.task || {}) as Row;
const selection = (task.aggregateSelection || {}) as Row;
if (!reportRequested(String(turn.question || '')) && !(result.reportMarkdown && reportRequested(String(selection.requestQuestion || '')))) return null;
const reportSource = typeof result.reportMarkdown === 'string' && result.reportMarkdown.trim()
? result.reportMarkdown : result.reportHtml && typeof result.answer === 'string' ? result.answer : '';
const markdown = typeof result.modelAnswer === 'string' ? result.modelAnswer : reportSource;
if (!markdown.trim()) return null;
const title = (typeof result.reportTitle === 'string' && result.reportTitle.trim()
? result.reportTitle : markdown.match(/^#(?!#)\s+(.+?)\s*#*$/m)?.[1] || '质量分析报告').trim();
return { title, markdown: stripDuplicateFirstMarkdownH1(markdown, title) };
}
export function AgentDeliverable({ turn, onClose }: { turn: Row; onClose: () => void }) {
const report = authoredReport(turn);
const snapshot = reportSnapshotIdentity(turn);
const access = useReportVisualImages(turn, Boolean(report), 'agent-document');
const article = useRef<HTMLElement>(null);
const generation = useRef(0);
const [exporting, setExporting] = useState<'html' | 'png' | null>(null);
const [error, setError] = useState('');
useLayoutEffect(() => { setExporting(null); setError(''); return () => { generation.current += 1; }; }, [snapshot]);
if (!report) return null;
const result = analysisSnapshotResult(turn);
const visuals = reportVisuals(turn, 'agent-document');
const layout = buildAgentReportLayout(report.markdown, visuals);
const headings = layout.sections.filter(section => section.label);
const topLevel = headings.filter(section => /^##\s/m.test(section.markdown));
const chapters = topLevel.length > 1 ? topLevel : headings;
const imageFor = (id: string) => access.images.find(image => image.id === id);
const chartSections = layout.sections.map(section => ({ ...section,
figures: section.charts.figures.filter(visual => reportVisualImageSource(imageFor(visual.id))),
})).filter(section => section.figures.length);
const primary = agentReportPrimary(chartSections.flatMap(section => section.figures), String(turn.question || ''));
const primarySection = chartSections.find(section => section.figures.some(visual => visual.id === primary?.id));
const wide = (visual: typeof visuals[number]) => ['bar', 'heatmap', 'pareto'].includes(visual.type);
const available = chartSections.flatMap(section => section.figures);
const secondary = available.filter(visual => visual.id !== primary?.id && !agentReportSupplementary(visual, available, String(turn.question || '')));
const supplemental = available.filter(visual => agentReportSupplementary(visual, available, String(turn.question || '')));
const chart = (visual: typeof visuals[number]) => <div key={visual.id} className={wide(visual) ? 'is-wide' : undefined}><ReportVisualFigure visual={visual} image={imageFor(visual.id)} hideEvidence quiet /></div>;
const scope = analysisScopeText(turn);
const focus = /前后(?:月份|月)|相邻(?:月份|月)/.test(String(turn.question || ''))
? String(turn.question || '').match(/(20\d{2})年(1[0-2]|[1-9])月/) : null;
const parsedDate = Date.parse(String(turn.finishedAt || turn.createdAt || ''));
const date = Number.isFinite(parsedDate)
? new Intl.DateTimeFormat('sv-SE', { timeZone: 'Asia/Shanghai' }).format(parsedDate) : '';
const title = report.title.replace(/[&<>]/g, character => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' }[character]!));
const exportReport = async (format: 'html' | 'png') => {
const node = article.current;
if (!node || !access.authorized || access.loading || exporting) return;
const revision = ++generation.current;
const isCurrent = () => revision === generation.current && node.isConnected;
const showError = (error: unknown) => setError(error instanceof Error ? error.message : '无法下载报告');
setExporting(format);
setError('');
try {
await access.authorize();
if (!isCurrent()) return;
const capture = async () => {
const closed = Array.from(node.querySelectorAll<HTMLDetailsElement>('.agent-document-supplement:not([open])'));
const scroller = node.closest('.ant-modal-body');
const scrollTop = scroller?.scrollTop;
try {
closed.forEach(details => { details.open = true; });
return await captureReportLongImage(node, { skipFonts: true }, () => !isCurrent());
} finally {
closed.forEach(details => { details.open = false; });
if (scroller && scrollTop !== undefined) scroller.scrollTop = scrollTop;
}
};
const blob = format === 'png' ? await capture()
: new Blob([`<!doctype html><html lang="zh-CN"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; img-src data:"><title>${title}</title><style>body{margin:0;background:#fff;padding:0}${documentCss}</style><body>${node.outerHTML}</body></html>`], { type: 'text/html;charset=utf-8' });
await downloadAuthorizedReport({ authorize: access.authorize, isCurrent, onDenied: showError, download: () => {
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = `${report.title.replace(/[\\/:*?"<>|\x00-\x1f]/g, '_')}.${format}`;
document.body.append(link);
link.click();
link.remove();
window.setTimeout(() => URL.revokeObjectURL(url), 1500);
} });
} catch (error) {
if (isCurrent()) showError(error);
} finally {
if (isCurrent()) setExporting(null);
}
};
return <Modal open centered title="报告预览" onCancel={onClose} width={1240} className="agent-report-modal"
footer={<>
<Button onClick={onClose}>关闭</Button>
<Button icon={<DownloadOutlined />} loading={exporting === 'html'} disabled={!access.authorized || access.loading || Boolean(exporting)} onClick={() => void exportReport('html')}>下载 HTML</Button>
<Button type="primary" icon={<DownloadOutlined />} loading={exporting === 'png'} disabled={!access.authorized || access.loading || Boolean(exporting)} onClick={() => void exportReport('png')}>下载长图</Button>
</>}>
{(error || access.authorizationError) && <Alert showIcon type="error" message={access.authorizationError || error} />}
{access.loading && <p className="agent-report-loading" role="status"><Spin size="small" /> {access.progress || '正在打开报告'}</p>}
{access.authorized && <article className="agent-document" ref={article}>
<header className="agent-document-masthead"><span>质量数据分析平台</span></header>
<div className="agent-document-cover">
<h1>{report.title}</h1>
{(scope || date) && <dl className="agent-document-meta">
{focus && <div><dt>分析月份</dt><dd>{focus[1]}年{focus[2]}月</dd></div>}
{scope && <div><dt>{focus ? '比较范围' : '报告期'}</dt><dd>{scope}</dd></div>}
{date && <div><dt>生成日</dt><dd><time dateTime={date}>{date}</time></dd></div>}
</dl>}
</div>
{!primary && layout.lead && <AiMarkdown className="agent-document-lead" content={layout.lead} preserveSource />}
{layout.metrics.length > 0 && <dl className="agent-document-metrics">
{layout.metrics.map(metric => <div key={metric.label}><dt>{metric.label}</dt><dd>{metric.value}<small>{metric.unit}</small></dd></div>)}
</dl>}
{chapters.length > 1 && <nav className="agent-document-contents" aria-label="报告章节">
{chapters.map(chapter => <a key={chapter.id} href={`#${chapter.id}`} onClick={event => {
const target = article.current?.querySelector<HTMLElement>(`#${chapter.id}`);
const scroller = article.current?.closest('.ant-modal-body');
if (!target || !scroller) return;
event.preventDefault();
scroller.scrollTop += target.getBoundingClientRect().top - scroller.getBoundingClientRect().top - 18;
}}>{chapter.label}</a>)}
</nav>}
{chartSections.length > 0 && <div className="agent-document-overview">
{primary && <div className={layout.lead ? 'agent-document-feature has-reading' : 'agent-document-feature'}>
<div className="agent-document-primary">
<ReportVisualFigure visual={primary} image={imageFor(primary.id)} hideEvidence />
{Boolean(primarySection?.charts.stats.length) && <dl className="agent-document-chart-stats">
{primarySection!.charts.stats.map(stat => <div key={stat.label}><dt>{stat.label}</dt><dd>{stat.value} {stat.unit}</dd></div>)}
</dl>}
</div>
{layout.lead && <aside className="agent-document-reading"><h2>主要发现</h2><AiMarkdown className="agent-document-lead" content={layout.lead} preserveSource /></aside>}
</div>}
{secondary.length > 0 && <div className="agent-document-secondary">{secondary.map(chart)}</div>}
{supplemental.length > 0 && <details className="agent-document-supplement"><summary>补充图表</summary>
<div className="agent-document-secondary">{supplemental.map(chart)}</div>
</details>}
</div>}
{layout.sections.map(section => <section className="agent-document-section" id={section.id} key={section.id}>
{section.markdown && <AiMarkdown className="agent-document-prose" content={section.markdown} preserveSource />}
</section>)}
<AnalysisMemberListReport value={result.memberList} />
{result.recordList != null && <AnalysisRecordListReport value={result.recordList} />}
</article>}
</Modal>;
}
+339
View File
@@ -0,0 +1,339 @@
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore, type FormEvent } from 'react';
import { Alert, App, Button, Drawer, Dropdown, Input, Modal, Spin } from 'antd';
import { ArrowUpOutlined, DeleteOutlined, EditOutlined, EllipsisOutlined, MenuFoldOutlined, MenuUnfoldOutlined, MessageOutlined, PlusCircleOutlined, SearchOutlined, StopOutlined } from '@ant-design/icons';
import type { AuthUser } from '../types';
import { usePageCache } from '../pageCache';
import { useVisiblePolling } from '../useVisiblePolling';
import { analysisIsRunning, type AnalysisScrollIntent } from '../analysisConversationState';
import { AnalysisApiSettings } from '../AnalysisApiSettings';
import { createAnalysisSessionClient } from './sessionClient';
import { decodeAnalysisLinkContext } from './analysisLink';
import { AgentConversationTurn } from './AgentConversation';
import { AgentDeliverable, authoredReport } from './AgentDeliverable';
import { scrollTopFromVisualOffset, transcriptFollowState } from './transcriptScroll';
import '../analysis-chat.css';
import './agent-workspace.css';
const examples = [
'分析最近6个已发布月份合格率的变化趋势',
'找出近期报废重量最高的产品',
'生成一份最近月份的质量分析报告',
];
function relativeTime(value: unknown) {
const timestamp = Date.parse(String(value || ''));
if (!Number.isFinite(timestamp)) return '';
const minutes = Math.max(0, Math.floor((Date.now() - timestamp) / 60000));
if (minutes < 1) return '刚刚';
if (minutes < 60) return `${minutes} 分钟前`;
if (minutes < 1440) return `${Math.floor(minutes / 60)} 小时前`;
return new Intl.DateTimeFormat('zh-CN', { month: 'numeric', day: 'numeric', timeZone: 'Asia/Shanghai' }).format(timestamp);
}
export default function AgentWorkspace({ user, onUnauthorized }: { user: AuthUser; onUnauthorized: (error: unknown) => boolean }) {
const page = usePageCache();
const latest = useRef({ page, onUnauthorized });
latest.current = { page, onUnauthorized };
const { modal } = App.useApp();
const client = useMemo(() => createAnalysisSessionClient({
userId: user.id,
onUnauthorized: error => latest.current.onUnauthorized(error),
onLocationChange: (sessionId, turnId) => {
if (!latest.current.page.active) return;
const location = new URL(window.location.href);
location.searchParams.set('page', 'analysis');
if (sessionId) location.searchParams.set('sessionId', sessionId); else location.searchParams.delete('sessionId');
if (turnId) location.searchParams.set('turnId', turnId); else location.searchParams.delete('turnId');
location.searchParams.delete('context');
window.history.replaceState(window.history.state, '', location);
latest.current.page.onLocationChange(location.search);
},
}), [user.id]);
const state = useSyncExternalStore(client.subscribe, client.getSnapshot, client.getSnapshot);
const initial = useMemo(() => {
const params = new URLSearchParams(page.initialSearch ?? window.location.search);
return { sessionId: params.get('sessionId') || undefined, turnId: params.get('turnId') || undefined, link: decodeAnalysisLinkContext(params.get('context')) };
}, [page.initialSearch]);
const [input, setInput] = useState(initial.link.resultRef ? '请解释当前排名结果,并说明可核查的来源依据。' : '');
const [sidebar, setSidebar] = useState(true);
const [mobileSidebar, setMobileSidebar] = useState(false);
const [searching, setSearching] = useState(false);
const [filter, setFilter] = useState('');
const [rename, setRename] = useState<{ id: string; title: string } | null>(null);
const [renaming, setRenaming] = useState(false);
const [deliverable, setDeliverable] = useState<string | undefined>();
const [linkError, setLinkError] = useState(initial.link.error || '');
const initialized = useRef(false);
const refreshKey = useRef(page.refreshKey);
const scroller = useRef<HTMLDivElement>(null);
const follow = useRef(true);
const scrollInput = useRef({ until: 0, top: 0, intent: null as AnalysisScrollIntent });
const focusTurn = useRef('');
const anchor = useRef<{ element: HTMLElement; top: number } | null>(null);
const [showLatest, setShowLatest] = useState(false);
const active = page.active;
useEffect(() => {
if (!active) return;
client.resume();
if (!initialized.current) {
initialized.current = true;
const linked = initial.link.present && !initial.sessionId && !initial.turnId;
if (linked && initial.link.query) {
const context = { ...initial.link.query, ...(initial.link.resultRef ? { resultRef: initial.link.resultRef } : {}) };
client.newSession({ releaseId: initial.link.query.releaseId, context, preserveLocation: true });
}
void client.openInitial({ sessionId: initial.sessionId, turnId: initial.turnId, selectRecent: !linked });
}
return () => client.suspend();
}, [active, client, initial]);
useEffect(() => {
if (active && refreshKey.current !== page.refreshKey) {
refreshKey.current = page.refreshKey;
void client.refreshSessions();
if (state.sessionId && !state.busy) void client.openSession(state.sessionId);
}
}, [active, client, page.refreshKey, state.busy, state.sessionId]);
useVisiblePolling(async () => { await client.refreshSessions(); }, 5000, active && state.sessions.some(item => analysisIsRunning(item.activeTurnStatus)));
useEffect(() => {
if (!active) return;
const shortcut = (event: KeyboardEvent) => {
if (!(event.metaKey || event.ctrlKey) || event.altKey || event.key.toLowerCase() !== 'k') return;
event.preventDefault();
if (window.matchMedia('(max-width: 820px)').matches) setMobileSidebar(true);
else setSidebar(true);
setSearching(true);
};
window.addEventListener('keydown', shortcut);
return () => window.removeEventListener('keydown', shortcut);
}, [active]);
const restoreLatest = useCallback(() => {
const element = scroller.current;
if (!element) return;
scrollInput.current = { until: 0, top: element.scrollTop, intent: null };
element.scrollTop = element.scrollHeight;
follow.current = true;
setShowLatest(false);
}, []);
useLayoutEffect(() => {
if (!active || !scroller.current) return;
if (anchor.current && !state.loadingOlder) {
const previous = anchor.current;
anchor.current = null;
if (previous.element.isConnected) {
const box = scroller.current;
box.scrollTop = scrollTopFromVisualOffset(box, previous.element.getBoundingClientRect().top - previous.top);
setShowLatest(transcriptFollowState(box, false, null).showLatest);
return;
}
}
const target = state.focusTurnId;
if (target && focusTurn.current !== target) {
const element = [...scroller.current.querySelectorAll<HTMLElement>('[data-analysis-turn-id]')].find(node => node.dataset.analysisTurnId === target);
if (element) {
focusTurn.current = target;
if (!state.busy) {
const box = scroller.current;
const bounds = box.getBoundingClientRect();
box.scrollTop = scrollTopFromVisualOffset(box, element.getBoundingClientRect().top - bounds.top, 16);
follow.current = false;
setShowLatest(transcriptFollowState(box, false, null).showLatest);
return;
}
}
}
if (follow.current) restoreLatest();
}, [active, state.turns, state.focusTurnId, state.loadingOlder, state.busy, restoreLatest]);
const hasTurns = state.turns.length > 0;
useEffect(() => {
if (!active || !scroller.current || typeof ResizeObserver === 'undefined') return;
const element = scroller.current.firstElementChild;
if (!element) return;
const observer = new ResizeObserver(() => { if (follow.current) restoreLatest(); });
observer.observe(element);
return () => observer.disconnect();
}, [active, hasTurns, restoreLatest]);
const newSession = (releaseId?: string) => {
client.newSession({ releaseId });
setInput('');
setLinkError('');
setMobileSidebar(false);
setDeliverable(undefined);
follow.current = true;
focusTurn.current = '';
};
const openSession = (id: string) => {
setInput('');
setLinkError('');
setMobileSidebar(false);
setDeliverable(undefined);
follow.current = true;
focusTurn.current = '';
void client.openSession(id);
};
const prompt = useCallback(async (question: string) => {
const state = client.getSnapshot();
const text = question.trim();
if (!text || state.historyLoading || state.readOnly || state.stopping || (state.busy && state.queuedQuestion)) return;
follow.current = true;
setShowLatest(false);
setInput('');
await client.submit(text, { releaseId: state.releaseId, context: state.sessionContext || undefined });
}, [client]);
const retry = useCallback((id: string) => { void client.retry(id); }, [client]);
const submit = (event: FormEvent) => { event.preventDefault(); void prompt(input); };
const noteScrollInput = (intent: AnalysisScrollIntent = null) => {
scrollInput.current = { until: performance.now() + 700, top: scroller.current?.scrollTop || 0, intent };
if (intent === 'up') follow.current = false;
};
const loadOlder = () => {
if (state.loadingOlder) return;
const first = scroller.current?.querySelector<HTMLElement>('[data-analysis-turn-id]');
if (first) anchor.current = { element: first, top: first.getBoundingClientRect().top };
follow.current = false;
void client.loadOlder();
};
const selected = deliverable ? state.turns.find(turn => turn.id === deliverable) : undefined;
const sessions = state.sessions.filter(row => !filter || String(row.title || '').toLocaleLowerCase().includes(filter.trim().toLocaleLowerCase()));
const title = state.sessionTitle || '新会话';
const lastTurn = state.turns.at(-1);
const waiting = state.historyLoading && !state.turns.length;
const blank = !state.turns.length && !waiting && !state.historyError;
const sendDisabled = !input.trim() || state.historyLoading || state.readOnly || state.stopping || Boolean(state.busy && state.queuedQuestion);
const error = linkError || state.historyError || state.error;
const toggleSidebar = () => {
if (window.matchMedia('(max-width: 820px)').matches) setMobileSidebar(true);
else setSidebar(value => !value);
};
const sessionList = () => <>
<div className="agent-sidebar-heading">
<span><MessageOutlined aria-hidden="true" /> 会话</span>
<button type="button" className="agent-icon" aria-label="搜索会话" title="搜索会话" onClick={() => setSearching(value => !value)}><SearchOutlined /></button>
</div>
<button type="button" className="agent-new-session" onClick={() => newSession()}><PlusCircleOutlined /> 新会话</button>
{searching && <Input className="agent-search" value={filter} onChange={event => setFilter(event.target.value)} placeholder="搜索会话" aria-label="搜索会话标题" allowClear autoFocus />}
{state.sessionsError && <button type="button" className="agent-session-retry" onClick={() => {
if (state.sessionId || initial.link.present) void client.refreshSessions();
else void client.openInitial({ sessionId: initial.sessionId, turnId: initial.turnId });
}}>重新读取会话</button>}
<div className="agent-session-list" aria-label="会话列表">
{state.sessionsLoading && !state.sessions.length && <div className="agent-list-state" role="status"><Spin size="small" /> 读取会话</div>}
{!state.sessionsLoading && !state.sessionsError && !sessions.length && <div className="agent-list-state">{filter ? '未找到匹配会话' : '暂无会话'}</div>}
{sessions.map(row => {
const id = String(row.id || '');
const name = String(row.title || '新会话');
const running = analysisIsRunning(row.activeTurnStatus) || id === state.sessionId && state.busy;
return <div key={id} className={id === state.sessionId ? 'agent-session-row is-current' : 'agent-session-row'}>
<button type="button" onClick={() => openSession(id)} className="agent-session-link" title={name} aria-current={id === state.sessionId ? 'page' : undefined}>
{running ? <span className="agent-running-dot" aria-label="运行中" /> : <MessageOutlined aria-hidden="true" />}
<span>{name}</span><time>{relativeTime(row.updatedAt || row.createdAt)}</time>
</button>
<Dropdown trigger={['click']} menu={{ items: [
{ key: 'rename', label: '重命名', icon: <EditOutlined />, onClick: () => setRename({ id, title: name }) },
{ key: 'delete', label: '删除', danger: true, icon: <DeleteOutlined />, disabled: running, onClick: () => {
modal.confirm({ title: '删除会话?', content: name, okText: '删除', okButtonProps: { danger: true }, cancelText: '取消', onOk: () => client.deleteSession(id) });
} },
] }}>
<button type="button" className="agent-icon agent-session-menu" title="会话操作" aria-label={`${name} 的会话操作`}><EllipsisOutlined /></button>
</Dropdown>
</div>;
})}
</div>
</>;
return <div className={sidebar ? 'dsh-workspace has-sidebar' : 'dsh-workspace'}>
{sidebar && <aside className="agent-sidebar" aria-label="会话导航">{sessionList()}</aside>}
<Drawer open={active && mobileSidebar} placement="left" width={300} onClose={() => setMobileSidebar(false)} title="质量分析" className="agent-mobile-drawer">
{sessionList()}
</Drawer>
<main className={blank ? 'agent-main is-empty' : 'agent-main'}>
<header className="agent-header">
<button type="button" className="agent-icon" title="切换会话栏" aria-label="切换会话栏" onClick={toggleSidebar}>{sidebar ? <MenuFoldOutlined /> : <MenuUnfoldOutlined />}</button>
<span className="agent-session-title" title={title}>{title}</span>
{state.connection === 'reconnecting' && <span className="agent-connection" role="status">重新连接中</span>}
</header>
{error && <Alert className="agent-error" type="error" showIcon message={error} action={
state.historyError ? <Button size="small" onClick={() => {
if (state.sessionId) void client.openSession(state.sessionId, state.focusTurnId);
else void client.openInitial({ sessionId: initial.sessionId, turnId: initial.turnId });
}}>重试</Button>
: state.retryQuestion ? <Button size="small" onClick={() => void prompt(state.retryQuestion)}>重试</Button>
: <Button size="small" onClick={() => { setLinkError(''); client.clearError(); }}>关闭</Button>
} />}
{blank && <div className="agent-welcome">
<h1>开始质量分析</h1>
<div className="agent-suggestions">{examples.map(example => <button type="button" key={example} onClick={() => setInput(example)}>{example}</button>)}</div>
</div>}
{!blank && <div className="agent-transcript" ref={scroller} tabIndex={0} aria-label="对话消息"
onWheel={event => { if (event.deltaY) noteScrollInput(event.deltaY < 0 ? 'up' : 'down'); }}
onTouchMove={() => noteScrollInput()}
onPointerDown={event => { if (event.target === event.currentTarget) noteScrollInput(); }}
onKeyDown={event => {
if (['ArrowUp', 'PageUp', 'Home'].includes(event.key)) noteScrollInput('up');
if (['ArrowDown', 'PageDown', 'End', ' '].includes(event.key)) noteScrollInput(event.shiftKey ? 'up' : 'down');
}}
onScroll={event => {
const element = event.currentTarget;
const input = scrollInput.current;
const intent = performance.now() < input.until
? input.intent || (element.scrollTop < input.top ? 'up' : 'down') : null;
input.top = element.scrollTop;
const next = transcriptFollowState(element, follow.current, intent);
follow.current = next.follows;
setShowLatest(next.showLatest);
}}>
<div className="agent-transcript-body">
{state.olderCursor && <button type="button" className="agent-older" disabled={state.loadingOlder} onClick={loadOlder}>{state.loadingOlder ? '正在读取' : '加载更早消息'}</button>}
{waiting && <div className="agent-list-state" role="status"><Spin size="small" /> 读取会话</div>}
{state.turns.map((turn, index) => <AgentConversationTurn key={String(turn.id || `pending-${index}`)} turn={turn}
canAct={!state.readOnly && !state.busy && !state.historyLoading} latest={turn === lastTurn}
onUnauthorized={onUnauthorized} onPrompt={prompt} onRetry={retry}
onReport={setDeliverable} />)}
</div>
</div>}
{showLatest && !blank && <button type="button" className="agent-latest" onClick={restoreLatest}>回到最新 ↓</button>}
<div className="agent-composer-region">
{state.readOnly ? <div className="agent-readonly"><span>历史会话</span><Button size="small" onClick={() => newSession(state.releaseId)}>新会话</Button></div> : <form className="agent-composer" onSubmit={submit}>
{state.queuedQuestion && <div className="agent-queued"><span title={state.queuedQuestion}>待发送 · {state.queuedQuestion}</span><button type="button" onClick={() => {
const queued = client.takeQueued();
setInput(previous => [queued, previous].filter(Boolean).join('\n'));
}}>取回编辑</button></div>}
<Input.TextArea id="analysis-query" aria-label="质量问题" value={input} onChange={event => setInput(event.target.value)}
placeholder="描述你的质量分析需求…" variant="borderless" autoSize={{ minRows: 2, maxRows: 7 }} maxLength={1600}
disabled={state.historyLoading} onPressEnter={event => {
if (event.shiftKey || event.nativeEvent.isComposing) return;
event.preventDefault();
if (!sendDisabled) void prompt(input);
}} />
<div className="agent-composer-actions">
<div className="agent-model-control">{user.roles.includes('SYSTEM_ADMIN') && <AnalysisApiSettings onUnauthorized={onUnauthorized} />}</div>
{state.busy && <button type="button" className="agent-stop" aria-label="停止分析" title="停止分析" disabled={state.stopping} onClick={() => void client.cancel()}><StopOutlined /></button>}
<button type="submit" className="agent-send" aria-label={state.busy ? '排队发送' : '发送'} title={state.busy ? '排队发送' : '发送'} disabled={sendDisabled}><ArrowUpOutlined /></button>
</div>
</form>}
</div>
</main>
{active && selected && authoredReport(selected) && <AgentDeliverable key={String(selected.id)} turn={selected} onClose={() => setDeliverable(undefined)} />}
<Modal open={active && Boolean(rename)} title="重命名会话" okText="保存" cancelText="取消" confirmLoading={renaming}
onCancel={() => { if (!renaming) setRename(null); }} okButtonProps={{ disabled: !rename?.title.trim() }}
onOk={async () => {
if (!rename?.title.trim()) return;
setRenaming(true);
try {
await client.renameSession(rename.id, rename.title.trim());
setRename(null);
} finally { setRenaming(false); }
}}>
<Input aria-label="会话名称" maxLength={160} value={rename?.title || ''} onChange={event => setRename(previous => previous ? { ...previous, title: event.target.value } : null)} />
</Modal>
</div>;
}
+107
View File
@@ -0,0 +1,107 @@
.agent-document {
--document-ink: #18202b;
--document-muted: #596574;
--document-line: #cbd2db;
--document-blue: #074bd4;
color: var(--document-ink);
background: #fff;
box-sizing: border-box;
max-width: 1180px;
margin: 0 auto;
padding: 0 clamp(22px, 4vw, 48px) 52px;
font: 15px/1.8 -apple-system, BlinkMacSystemFont, "PingFang SC", "Microsoft YaHei", sans-serif;
font-variant-numeric: tabular-nums;
overflow-wrap: anywhere;
}
.agent-document *, .agent-document *::before, .agent-document *::after { box-sizing: border-box; }
.agent-document-masthead { display: flex; justify-content: space-between; align-items: center; padding: 25px 0 20px; border-bottom: 3px solid var(--document-ink); }
.agent-document-masthead span { font-size: 23px; font-weight: 750; letter-spacing: -.035em; }
.agent-document-cover { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: 28px; padding: 31px 0 28px; }
.agent-document h1 { margin: 0; color: var(--document-ink); font: 780 clamp(28px, 4.2vw, 50px)/1.35 -apple-system, BlinkMacSystemFont, "PingFang SC", "Microsoft YaHei", sans-serif; letter-spacing: -.035em; }
.agent-document-meta { margin: 0; min-width: 170px; max-width: 225px; font-size: 14px; line-height: 1.7; }
.agent-document-meta > div { display: flex; align-items: baseline; gap: 10px; }
.agent-document-meta dt { flex: none; color: var(--document-muted); }
.agent-document-meta dd { margin: 0; }
.agent-document-metrics { display: flex; margin: 0; padding: 24px 0 27px; border-block: 2px solid var(--document-ink); }
.agent-document-metrics > div { flex: 1 1 0; min-width: 0; padding: 0 28px; border-left: 1px solid var(--document-line); }
.agent-document-metrics > div:first-child { border-left: 0; padding-left: 0; }
.agent-document-metrics dt { color: var(--document-ink); font-size: 18px; font-weight: 650; }
.agent-document-metrics dd { margin: 8px 0 0; color: var(--document-blue); font: 740 clamp(36px, 4.7vw, 64px)/1 Arial, Helvetica, sans-serif; letter-spacing: -.055em; white-space: nowrap; }
.agent-document-metrics small { margin-left: 2px; font-size: .52em; letter-spacing: -.035em; }
.agent-document-contents { display: flex; flex-wrap: wrap; gap: 6px 23px; padding: 12px 0; font-size: 12px; }
.agent-document-contents a { color: var(--document-muted); text-decoration: none; }
.agent-document-contents a:hover { color: var(--document-blue); text-decoration: underline; }
.agent-document-contents a:focus-visible { outline: 2px solid var(--document-blue); outline-offset: 3px; }
.agent-document-overview { padding-top: 12px; margin-bottom: 30px; border-bottom: 2px solid var(--document-ink); }
.agent-document-feature { min-width: 0; padding-bottom: 24px; }
.agent-document-feature.has-reading { display: grid; grid-template-columns: minmax(0, 1.8fr) minmax(240px, 1fr); gap: 28px; }
.agent-document-primary { min-width: 0; }
.agent-document-reading { border-left: 1px solid var(--document-line); padding-left: 25px; }
.agent-document .agent-document-reading h2 { margin: 0 0 16px; font-size: 21px; line-height: 1.5; }
.agent-document .agent-document-lead { color: #243954; font-size: 16px; line-height: 1.85; }
.agent-document .agent-document-reading .agent-document-lead > p { padding-left: 14px; border-left: 3px solid var(--document-blue); }
.agent-document .agent-document-lead strong { color: var(--document-blue); }
.agent-document .agent-document-lead p:last-child { margin-bottom: 0; }
.agent-document-cover + .agent-document-lead { margin: 0 0 24px; max-width: 74ch; }
.agent-document-secondary { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 28px; padding: 26px 0; border-top: 1px solid var(--document-line); }
.agent-document-secondary > div { min-width: 0; }
.agent-document-secondary > .is-wide { grid-column: 1 / -1; border-top: 1px solid var(--document-line); padding-top: 22px; }
.agent-document-secondary > .is-wide:first-child { border-top: 0; padding-top: 0; }
.agent-document-supplement { border-top: 1px solid var(--document-line); padding: 12px 0 16px; }
.agent-document-supplement > summary { cursor: pointer; width: max-content; white-space: nowrap; color: var(--document-muted); font-size: 13px; }
.agent-document-supplement[open] > summary { color: var(--document-blue); }
.agent-document-supplement .agent-document-secondary { border-top: 0; padding-bottom: 0; }
.agent-document-section { scroll-margin-top: 18px; }
.agent-document-section { margin-top: 28px; }
.agent-document h2 { margin: 27px 0 13px; color: var(--document-ink); font-size: 23px; line-height: 1.45; font-weight: 720; letter-spacing: -.025em; }
.agent-document h3, .agent-document h4 { margin: 21px 0 10px; color: var(--document-ink); font-size: 17px; font-weight: 650; }
.agent-document .agent-document-prose { color: inherit; font: inherit; }
.agent-document p, .agent-document ul, .agent-document ol { margin: 0 0 16px; }
.agent-document .agent-document-prose > p { max-width: 76ch; }
.agent-document hr { margin: 25px 0; border: 0; border-top: 1px solid var(--document-line); }
.agent-document ul, .agent-document ol { padding-left: 22px; }
.agent-document li + li { margin-top: 7px; }
.agent-document li::marker { color: var(--document-blue); }
.agent-document blockquote { margin: 17px 0; padding: 10px 16px; border-left: 3px solid var(--document-blue); background: #f2f5fb; }
.agent-document .ai-markdown table { width: 100%; border-collapse: collapse; color: var(--document-ink); font-size: 13px; line-height: 1.7; }
.agent-document .ai-markdown :is(th, td) { padding: 10px 12px; text-align: right; vertical-align: top; border: 0; border-bottom: 1px solid var(--document-line); white-space: nowrap; overflow-wrap: normal; word-break: normal; }
.agent-document .ai-markdown td.ai-markdown-prose { min-width: 16em; white-space: normal; overflow-wrap: anywhere; }
.agent-document .ai-markdown :is(th, td):first-child { text-align: left; }
.agent-document .ai-markdown th { background: #e9edf3; color: var(--document-ink); border-top: 1px solid #919ba9; font-weight: 650; }
.agent-document .ai-markdown tr:nth-child(even) td { background: #f6f8fb; }
.agent-document :is(.ai-table-wrap, .ai-markdown-table-wrap) { max-width: 100%; overflow-x: auto; height: auto; max-height: none; margin: 16px 0 23px; border: 0; border-radius: 0; background: transparent; }
.agent-document :is(.ai-table-wrap, .ai-markdown-table-wrap) table { table-layout: auto; }
.agent-document :is(.ai-table-wrap, .ai-markdown-table-wrap) .ai-markdown-index { width: 3em; }
.agent-document figure { margin: 0; }
.agent-document .q-report-visual-heading { display: flex; justify-content: space-between; align-items: baseline; gap: 12px; font-size: 18px; line-height: 1.5; }
.agent-document .q-report-visual-heading strong { font-weight: 700; }
.agent-document .q-report-visual-heading > span { color: var(--document-muted); font-size: 12px; }
.agent-document figcaption { color: var(--document-muted); font-size: 11px; line-height: 1.6; }
.agent-document img { display: block; width: 100%; height: auto; margin: 8px 0 6px; }
.agent-document-chart-stats { display: flex; flex-wrap: wrap; gap: 7px 24px; margin: 12px 0 0; padding-top: 10px; border-top: 1px solid var(--document-line); color: var(--document-muted); font-size: 12px; }
.agent-document-chart-stats > div { display: flex; gap: 6px; }
.agent-document-chart-stats dd { margin: 0; color: var(--document-ink); font-weight: 700; }
.agent-document pre { white-space: pre-wrap; }
.agent-document a { color: var(--document-blue); }
.agent-document :is(.q-source-record-list, .q-member-list) { margin-top: 30px; }
.agent-document :is(.q-source-record-list, .q-member-list) summary { cursor: pointer; font-weight: 650; }
.agent-document .q-source-record-list :is(th, td):first-child { width: 48px; min-width: 48px; white-space: nowrap; }
.agent-document .q-source-record-list :is(th, td):nth-child(2) { width: 140px; }
@media (max-width: 700px) {
.agent-document { padding: 0 20px 30px; font-size: 14px; }
.agent-document-masthead { padding: 19px 0 15px; }
.agent-document-masthead span { font-size: 18px; }
.agent-document-cover { grid-template-columns: 1fr; gap: 14px; padding: 23px 0; }
.agent-document-meta { display: flex; flex-wrap: wrap; gap: 5px 18px; max-width: none; font-size: 11px; }
.agent-document-metrics { padding: 19px 0; }
.agent-document-metrics > div { padding-inline: 9px; }
.agent-document-metrics dt { font-size: 11px; }
.agent-document-metrics dd { font-size: clamp(21px, 7.2vw, 35px); }
.agent-document-feature.has-reading, .agent-document-secondary { grid-template-columns: minmax(0, 1fr); }
.agent-document-reading { border-left: 0; border-top: 1px solid var(--document-line); padding: 20px 0 0; }
.agent-document .agent-document-lead { font-size: 14px; }
.agent-document .q-report-visual-heading { font-size: 16px; }
.agent-document figure, .agent-document :is(.ai-table-wrap, .ai-markdown-table-wrap) { overflow-x: auto; }
.agent-document .q-report-visual img { min-width: 460px; }
.agent-document .ai-markdown :is(th, td) { min-width: 78px; padding: 9px 8px; }
}
+130
View File
@@ -0,0 +1,130 @@
.dsh-workspace {
--agent-main: var(--surface, #fff);
--agent-side: color-mix(in srgb, var(--agent-main), var(--ink, #18212a) 3%);
--agent-tint: color-mix(in srgb, var(--agent-main), var(--ink, #18212a) 6%);
--agent-accent: var(--primary, #2369c4);
display: grid;
grid-template-columns: minmax(0, 1fr);
width: 100%;
height: calc(100dvh - 112px);
min-height: 440px;
overflow: hidden;
color: var(--ink);
border: 1px solid var(--line);
border-radius: 12px;
background: var(--agent-main);
}
.dsh-workspace.has-sidebar { grid-template-columns: 254px minmax(0, 1fr); }
.agent-sidebar { background: var(--agent-side); border-right: 1px solid var(--line); min-height: 0; display: flex; flex-direction: column; padding: 13px 10px 10px; }
.agent-sidebar-heading { display: flex; align-items: center; justify-content: space-between; padding: 0 4px 10px 8px; font-weight: 650; }
.agent-sidebar-heading > span { display: flex; align-items: center; gap: 8px; }
.dsh-workspace button:not(.ant-btn), .agent-mobile-drawer button:not(.ant-btn) { font: inherit; cursor: pointer; }
.dsh-workspace button:disabled { cursor: default; }
.dsh-workspace button:focus-visible, .agent-mobile-drawer button:focus-visible { outline: 2px solid var(--agent-accent, #2369c4); outline-offset: 2px; }
.agent-icon { display: inline-grid; place-items: center; background: none; border: 0; color: var(--muted-ink); border-radius: 7px; width: 30px; height: 30px; flex: none; }
.agent-icon:hover { background: var(--agent-tint, var(--hover)); color: var(--ink); }
.agent-new-session { display: flex; align-items: center; justify-content: center; gap: 8px; height: 38px; margin: 0 3px 10px; border: 1px solid var(--line); background: var(--surface); color: var(--ink); border-radius: 8px; }
.agent-new-session:hover { background: var(--hover); }
.agent-search { margin-bottom: 7px; }
.agent-session-list { overflow: auto; min-height: 0; overscroll-behavior: contain; }
.agent-list-state { color: var(--muted-ink); font-size: 13px; text-align: center; padding: 16px 8px; }
.agent-session-retry { align-self: center; border: none; background: none; color: var(--agent-accent); }
.agent-session-row { display: flex; align-items: center; gap: 1px; border-radius: 8px; min-height: 36px; margin: 1px 0; }
.agent-session-row:hover, .agent-session-row.is-current { background: var(--agent-tint, var(--hover)); }
.agent-session-link { display: flex; flex: 1; min-width: 0; gap: 8px; align-items: center; padding: 8px 0 8px 8px; color: var(--ink); border: 0; background: none; text-align: start; }
.agent-session-link > span:nth-child(2) { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1; font-size: 13px; }
.agent-session-link .anticon, .agent-session-link time { color: var(--muted-ink); flex: none; }
.agent-session-link time { font-size: 10px; white-space: nowrap; }
.agent-session-menu { width: 24px; height: 27px; opacity: .65; }
.agent-session-menu:hover, .agent-session-menu:focus-visible { opacity: 1; }
.agent-running-dot { width: 7px; height: 7px; margin: 0 3px; flex: none; border-radius: 50%; background: #277b72; }
.agent-main { display: flex; min-height: 0; min-width: 0; flex-direction: column; position: relative; }
.agent-header { display: flex; align-items: center; gap: 10px; min-height: 52px; padding: 7px 16px; border-bottom: 1px solid var(--line); }
.agent-session-title { flex: 1; min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; font-weight: 650; }
.agent-connection { font-size: 11px; color: var(--muted-ink); }
.agent-welcome { margin: auto auto 0; padding: 18px 16px; text-align: center; }
.agent-welcome h1 { margin: 0 0 18px; font-size: clamp(24px, 3vw, 34px); letter-spacing: -.035em; }
.agent-suggestions { display: flex; justify-content: center; flex-wrap: wrap; gap: 8px; }
.agent-suggestions button { padding: 7px 11px; border: 1px solid var(--line); border-radius: 8px; color: var(--muted-ink); background: transparent; }
.agent-suggestions button:hover { background: var(--agent-side); color: var(--ink); }
.agent-transcript { flex: 1; min-height: 0; overflow: auto; overscroll-behavior: contain; scrollbar-gutter: stable; }
.agent-transcript-body { width: min(100%, 904px); margin: 0 auto; padding: 16px 28px 28px; box-sizing: border-box; }
.agent-older, .agent-latest { display: block; margin: 0 auto 12px; padding: 6px 12px; border: 1px solid var(--line); border-radius: 16px; color: var(--muted-ink); background: var(--agent-main); }
.agent-latest { margin-bottom: 4px; }
.agent-turn { padding: 12px 0 24px; }
.agent-turn + .agent-turn { border-top: 1px solid var(--line); }
.agent-user-message { width: fit-content; max-width: min(100%, 680px); margin: 0 0 16px auto; padding: 10px 15px; border-radius: 14px 14px 4px 14px; background: var(--agent-tint); white-space: pre-wrap; overflow-wrap: anywhere; line-height: 1.65; }
.agent-assistant-message { min-width: 0; }
.agent-run-status { display: inline-flex; align-items: center; min-width: 0; flex-wrap: wrap; gap: 7px; color: var(--muted-ink); font-size: 12px; }
.agent-run-status > time { color: var(--muted-ink); font-variant-numeric: tabular-nums; white-space: nowrap; }
.agent-run-status.is-running { color: var(--agent-accent); }
.agent-run-disclosure { margin-bottom: 10px; }
.agent-run-disclosure > summary, .agent-tool-call > summary { display: flex; align-items: center; gap: 8px; cursor: pointer; list-style: none; color: var(--muted-ink); }
.agent-run-disclosure > summary::-webkit-details-marker, .agent-tool-call > summary::-webkit-details-marker { display: none; }
.agent-disclosure { font-size: 10px; }
.agent-run-disclosure[open] > summary > .agent-disclosure, .agent-tool-call[open] > summary > .agent-disclosure { transform: rotate(90deg); }
.agent-execution-events { border-left: 1px solid var(--line); padding-left: 11px; margin: 8px 0 8px 6px; }
.agent-tool-call { margin: 3px 0; font-size: 12px; }
.agent-tool-call > summary { width: fit-content; min-height: 28px; padding: 2px 6px; border-radius: 6px; }
.agent-tool-call > summary:hover { background: var(--agent-side); }
.agent-tool-name { color: var(--ink); }
.agent-tool-call.is-complete > summary > .anticon:first-child { color: #298176; }
.agent-tool-call.is-failed > summary > .anticon:first-child { color: #bb4747; }
.agent-tool-call.is-running > summary > .anticon:first-child { color: var(--agent-accent); }
.agent-tool-detail { color: var(--muted-ink); padding: 3px 10px 8px 24px; overflow-wrap: anywhere; }
.agent-tool-detail:empty { display: none; }
.agent-tool-detail dl, .agent-tool-detail p { margin: 3px 0; }
.agent-tool-detail dl > div { display: flex; gap: 10px; }
.agent-tool-detail dt { flex: none; }
.agent-tool-detail dd { margin: 0; }
.agent-draft { margin-top: 10px; border-left: 2px solid var(--line); padding-left: 12px; }
.agent-answer-meta { display: flex; align-items: center; justify-content: space-between; gap: 8px 18px; flex-wrap: wrap; margin: 8px 0 18px; }
.agent-turn-scope { margin: 0; font-size: 12px; color: var(--muted-ink); }
.agent-report-open { display: inline-flex; align-items: center; gap: 7px; padding: 6px 10px; border: 1px solid var(--line); border-radius: 7px; background: transparent; color: var(--ink); font: inherit; font-size: 12px; cursor: pointer; margin-left: auto; }
.agent-report-open:hover { background: var(--agent-side); border-color: var(--agent-accent); }
.agent-report-open:focus-visible { outline: 2px solid var(--agent-accent); outline-offset: 3px; }
.agent-report-open > .anticon:last-child { font-size: 9px; }
.agent-model-answer { font-size: 15px; line-height: 1.85; color: var(--ink); overflow-wrap: anywhere; }
.agent-model-answer :is(h1, h2, h3, h4) { color: var(--ink); line-height: 1.5; font-weight: 650; }
.agent-model-answer h1 { font-size: 26px; margin: 0 0 20px; letter-spacing: -.025em; }
.agent-model-answer h2 { font-size: 20px; margin: 30px 0 12px; }
.agent-model-answer :is(h3, h4) { font-size: 16px; margin: 22px 0 9px; }
.agent-model-answer p { margin: 0 0 16px; max-width: 72ch; }
.agent-model-answer :is(ul, ol) { margin: 10px 0 20px; padding-left: 23px; }
.agent-model-answer li + li { margin-top: 7px; }
.agent-model-answer hr { margin: 28px 0; border: 0; border-top: 1px solid var(--line); }
.agent-model-answer blockquote { margin: 18px 0; padding: 10px 16px; border-left: 3px solid var(--line); background: var(--agent-side); color: var(--muted-ink); }
.agent-model-answer .ai-markdown-table-wrap { margin: 14px 0 22px; border-radius: 7px; }
.agent-model-answer table { table-layout: auto; font-size: 14px; font-variant-numeric: tabular-nums; }
.agent-model-answer :is(th, td) { padding: 10px 14px; text-align: right; vertical-align: top; word-break: normal; }
.agent-model-answer :is(th, td):first-child { text-align: left; }
.agent-model-answer th { font-weight: 600; }
.agent-draft small, .agent-turn-notice { color: var(--muted-ink); }
.agent-turn-actions { margin-top: 8px; }
.agent-composer-region { margin: 0 auto; width: min(100%, 904px); padding: 4px 28px 17px; box-sizing: border-box; }
.agent-main.is-empty .agent-composer-region { margin-bottom: auto; }
.agent-composer { border: 1px solid var(--line); border-radius: 15px; padding: 7px 9px; background: var(--agent-main); box-shadow: 0 3px 11px #162d3e0b; }
.agent-composer:focus-within { border-color: color-mix(in srgb, var(--agent-accent) 55%, var(--line)); }
.agent-composer textarea.ant-input { display: block; padding: 6px 8px; resize: none; color: var(--ink); }
.agent-composer-actions { display: flex; align-items: center; gap: 8px; }
.agent-model-control { margin-right: auto; }
.agent-send, .agent-stop { display: inline-grid; place-items: center; width: 33px; height: 33px; border-radius: 9px; border: 0; }
.agent-send { background: var(--agent-accent); color: #fff; }
.agent-send:disabled { opacity: .35; }
.agent-stop { background: var(--agent-tint); color: var(--ink); }
.agent-queued, .agent-readonly { display: flex; align-items: center; justify-content: space-between; gap: 10px; color: var(--muted-ink); font-size: 12px; padding: 4px 7px; }
.agent-queued > span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.agent-queued button { flex: none; border: 0; background: transparent; color: var(--agent-accent); }
.agent-error { margin: 9px 16px 0; }
.agent-report-modal .ant-modal-body { max-height: calc(100dvh - 156px); overflow: auto; background: #f1f3f6; padding: 13px; }
.agent-report-loading { color: var(--muted-ink); text-align: center; }
.agent-mobile-drawer .ant-drawer-body { display: flex; flex-direction: column; padding: 12px; }
@media (max-width: 820px) {
.dsh-workspace.has-sidebar { grid-template-columns: minmax(0, 1fr); }
.agent-sidebar { display: none; }
.agent-header { padding-inline: 8px; }
.agent-transcript-body, .agent-composer-region { padding-inline: 12px; }
.agent-report-modal .ant-modal-body { padding: 4px; }
.agent-model-answer h1 { font-size: 23px; }
.agent-model-answer :is(th, td) { min-width: 85px; padding: 9px 10px; }
}
+251
View File
@@ -0,0 +1,251 @@
import { analysisTextEvidenceRefs } from '../analysisEvidenceRefs.ts';
import { sanitizeAnalysisDisplayText } from '../analysisDisplayText.ts';
import { originalAnalysisSections } from '../analysisOriginalBody.ts';
import { parseAnalysisVisuals, combineStageDefectVisuals, type AnalysisVisual } from '../analysisVisualsModel.ts';
export type ReportMetric = { label: string; value: string; unit: '%' | 'pp' };
type ChartGroup = { figures: AnalysisVisual[]; paired: boolean; stats: ReportMetric[] };
const rateLabels = ['综合合格率', '黑片合格率', '亮片合格率'];
const rateText = (value: string) => value.trim().match(/^(-?\d{1,3}(?:\.\d+)?)\s*%$/)?.[1];
function plain(value: string) {
let text = sanitizeAnalysisDisplayText(value).replace(/\*\*|\x60/g, '');
for (const ref of analysisTextEvidenceRefs(text)) text = text.replaceAll(`[${ref}]`, '');
return text.trim();
}
/** Only an explicitly labelled aggregate row may populate period-level rates. */
function aggregateMetrics(markdown: string): ReportMetric[] {
let rates: string[] = [];
let aggregateSection = false;
let stageRates = new Map<string, string>();
const lines = markdown.split('\n');
const cells = (line: string) => plain(line).replace(/^\||\|$/g, '').split('|').map(cell => cell.trim());
for (const [index, line] of lines.entries()) {
if (/^#{1,6}\s/.test(line)) aggregateSection = /期间汇总|全期汇总|区间汇总|正式聚合|聚合值/.test(plain(line));
else if (!line.trim().startsWith('|') && /^(?:期间|全期|区间)汇总/.test(plain(line))) aggregateSection = true;
if (!line.trim().startsWith('|')) { rates = []; stageRates = new Map(); continue; }
const row = cells(line);
if (cells(lines[index + 1] || '').every(cell => /^:?-{3,}:?$/.test(cell))) {
rates = row;
stageRates = new Map();
continue;
}
// Native models may put the three stages in rows rather than columns.
// A period aggregate heading is required, so a monthly stage table never
// becomes a period KPI. The authored table remains unchanged in the body.
if (aggregateSection && ['阶段', '指标'].includes(rates[0])) {
const label = rateLabels.find(label => label === row[0] || label.replace('合格率', '') === row[0]);
const column = rates.findIndex(value => ['合格率', '正式值', '期间合格率'].includes(value));
const value = column >= 0 ? rateText(row[column] || '') : undefined;
if (label && value !== undefined) stageRates.set(label, value);
if (stageRates.size === rateLabels.length) return rateLabels.map(label => ({ label, value: stageRates.get(label)!, unit: '%' }));
}
if (!/^(?:期间|全期|区间)汇总$/.test(row[0])) continue;
const metrics = rateLabels.flatMap(label => {
const position = rates.indexOf(label);
const value = position >= 0 ? rateText(row[position] || '') : undefined;
return value === undefined ? [] : [{ label, value, unit: '%' as const }];
});
if (metrics.length) return metrics;
}
for (const paragraph of markdown.split(/\n\s*\n/).slice(0, 4)) {
const text = plain(paragraph);
// A single-month company summary is eligible only within its first clause.
// Never collect a later department's rate as a company headline metric.
const periodAggregate = /期间|全期|区间|\d{1,2}[—–至-]\d{1,2}月/.test(text);
const companyClause = text.split(/[。;;]/, 1)[0];
if (/^[#|]/.test(text) || (!periodAggregate && (!/全公司|总体|整体/.test(companyClause) || /产业部|业务分组|项目组/.test(companyClause)))) continue;
const source = periodAggregate ? text : companyClause;
const metrics = rateLabels.flatMap(label => {
const matches = [...source.matchAll(new RegExp(`${label}\\s*(?:为|是|[::])?\\s*(-?\\d{1,3}(?:\\.\\d+)?)\\s*%`, 'g'))];
return matches.length === 1 ? [{ label, value: matches[0][1], unit: '%' as const }] : [];
});
if (metrics.length === rateLabels.length) return metrics;
}
// A model may label stages in columns and write the composite rate in prose.
// Read only an explicit overall section and the exact rate row; never infer
// stage values from "respectively" prose, monthly rows or another object.
const lead = markdown.split(/\n\s*\n/, 1)[0];
for (const section of originalAnalysisSections(markdown, [])) {
if (!/^#{1,6}\s+[^\n]*(?:总体|期间汇总|全期汇总|区间汇总)/m.test(section.markdown)) continue;
const composite = new Set([...plain(lead + '\n' + section.markdown).matchAll(/综合合格率\s*(?:为|是|[::=])?\s*(-?\d{1,3}(?:\.\d+)?)\s*%/g)].map(match => match[1]));
if (composite.size !== 1) continue;
const tableLines = section.markdown.split('\n');
let columns: string[] = [];
let stages = new Map<string, string>();
for (const [index, line] of tableLines.entries()) {
if (!line.trim().startsWith('|')) { columns = []; stages = new Map(); continue; }
const row = cells(line);
if (cells(tableLines[index + 1] || '').every(cell => /^:?-{3,}:?$/.test(cell))) { columns = row; stages = new Map(); continue; }
if (columns[0] === '阶段' && ['黑片', '亮片'].includes(row[0])) {
const value = rateText(row[columns.indexOf('合格率')] || '');
if (value !== undefined) stages.set(row[0], value);
if (stages.size === 2) return [
{ label: rateLabels[0], value: [...composite][0], unit: '%' },
{ label: rateLabels[1], value: stages.get('黑片')!, unit: '%' },
{ label: rateLabels[2], value: stages.get('亮片')!, unit: '%' },
];
}
if (row[0] !== '合格率') continue;
const black = rateText(row[columns.indexOf('黑片')] || '');
const bright = rateText(row[columns.indexOf('亮片')] || '');
if (black !== undefined && bright !== undefined) return [
{ label: rateLabels[0], value: [...composite][0], unit: '%' },
{ label: rateLabels[1], value: black, unit: '%' },
{ label: rateLabels[2], value: bright, unit: '%' },
];
}
}
return [];
}
function matchingMonthlyFigures(a: AnalysisVisual, b: AnalysisVisual) {
const scope = (v: AnalysisVisual) => JSON.stringify(Object.entries(v.scope).filter(([key]) => key !== 'stage').sort(([a], [b]) => a.localeCompare(b)));
return scope(a) === scope(b) && a.categories.map(row => row.key).join('|') === b.categories.map(row => row.key).join('|');
}
/** A presentation view of two authorized series; saved charts and values stay intact. */
export function agentReportVisuals(visuals: AnalysisVisual[], question = ''): AnalysisVisual[] {
const scope = (visual: AnalysisVisual) => JSON.stringify([visual.originTurnId, visual.period, visual.comparisonPeriod,
visual.metric, visual.dimension, visual.stage, Object.entries(visual.scope).sort(([a], [b]) => a.localeCompare(b))]);
const points = (visual: AnalysisVisual) => new Map(visual.categories.map((category, index) =>
[category.key, JSON.stringify(visual.series.map(series => [series.key, series.values[index]]))]));
const limit = Number(question.match(/(?:top|前)\s*(\d+)/i)?.[1]);
const unique = visuals.filter((visual, index) => !visuals.some((candidate, other) => {
if (index === other || scope(visual) !== scope(candidate)) return false;
const a = points(visual), b = points(candidate);
if (![...a].every(([key, value]) => b.get(key) === value)) return false;
// An exact requested Top count wins over an expanded version of that list.
if (limit && visual.categories.length === limit && candidate.categories.length !== limit) return false;
if (limit && candidate.categories.length === limit && visual.categories.length !== limit) return true;
return b.size > a.size || b.size === a.size && other < index;
}));
// A larger response is also a duplicate when the requested Top is its exact prefix.
const plotted = unique.filter(visual => !limit || visual.categories.length <= limit || !unique.some(candidate =>
scope(candidate) === scope(visual) && candidate.categories.length === limit
&& candidate.categories.every((category, index) => category.key === visual.categories[index]?.key
&& points(candidate).get(category.key) === points(visual).get(category.key))));
const requested = plotted.map(visual => {
if (!(limit > 0 && visual.categories.length > limit
&& ['department', 'group', 'product', 'defect'].includes(visual.dimension || '')
&& ['bar', 'column', 'pareto'].includes(visual.type))) return visual;
const { chartable: _chartable, chartIssue: _issue, invalidValueCells: _invalid, ...raw } = visual;
return parseAnalysisVisuals([{ ...raw, categories: visual.categories.slice(0, limit),
series: visual.series.map(series => ({ ...series, values: series.values.slice(0, limit) })),
coverage: { ...visual.coverage, returnedRows: limit, truncated: true } }], 1).visuals[0] || visual;
});
visuals = combineStageDefectVisuals(requested);
const used = new Set<string>();
return visuals.flatMap(visual => {
if (used.has(visual.id)) return [];
if (!monthlyRate(visual) || !['black_rate', 'bright_rate'].includes(visual.metric) || !visual.chartable) return [visual];
const companion = visuals.find(candidate => candidate.id !== visual.id && !used.has(candidate.id)
&& monthlyRate(candidate) && candidate.chartable && candidate.type === visual.type
&& candidate.metric === (visual.metric === 'black_rate' ? 'bright_rate' : 'black_rate')
&& candidate.originTurnId === visual.originTurnId && matchingMonthlyFigures(visual, candidate)
&& JSON.stringify(candidate.period) === JSON.stringify(visual.period)
&& JSON.stringify(candidate.comparisonPeriod) === JSON.stringify(visual.comparisonPeriod));
if (!companion) return [visual];
const black = visual.metric === 'black_rate' ? visual : companion;
const bright = visual.metric === 'bright_rate' ? visual : companion;
const { stage: _stage, ...scope } = black.scope;
const { chartable: _chartable, chartIssue: _issue, invalidValueCells: _invalid, ...raw } = black;
const combined = parseAnalysisVisuals([{ ...raw, type: 'line', id: `${black.id}-stages`, title: '阶段合格率', stage: undefined, scope,
series: [...black.series, ...bright.series],
evidenceRefs: [...new Set([...black.evidenceRefs, ...bright.evidenceRefs])],
requiredFields: [...new Set([...black.requiredFields, ...bright.requiredFields])],
}], 1).visuals[0];
if (!combined?.chartable) return [visual];
used.add(black.id); used.add(bright.id);
return [combined];
});
}
/** Choose only an existing result, without deriving a missing chart or rewriting prose. */
export function agentReportPrimary(visuals: AnalysisVisual[], question = ''): AnalysisVisual | undefined {
if (/结构|构成|占比|分类/.test(question) && !/总体|综合/.test(question)) {
const composition = visuals.find(visual => visual.dimension === 'category' || visual.sectionKey === 'composition')
|| visuals.find(visual => visual.dimension === 'defect' && ['bar', 'column', 'pareto'].includes(visual.type));
if (composition) return composition;
}
if (/排名|top\s*\d+|前\s*\d+/i.test(question) && !/总体|诊断|异常/.test(question)) {
const ranking = visuals.find(visual => ['department', 'group', 'product'].includes(visual.dimension || '') && ['bar', 'column', 'pareto'].includes(visual.type));
if (ranking) return ranking;
}
return visuals.find(visual => visual.metric === 'composite_rate' && ['line', 'area'].includes(visual.type))
|| visuals.find(visual => visual.unit === 'ratio' && ['line', 'area'].includes(visual.type) && visual.series.length > 1)
|| visuals.find(visual => ['line', 'area'].includes(visual.type)) || visuals[0];
}
export function agentReportChartWidth(visual: AnalysisVisual, visuals: AnalysisVisual[], question = ''): number {
if (visual.id === agentReportPrimary(visuals, question)?.id) return 660;
return visual.type === 'bar' || visual.type === 'heatmap' || visual.type === 'pareto' ? 1040 : 500;
}
/** Complementary rates and volume traces remain available, without crowding the requested story. */
export function agentReportSupplementary(visual: AnalysisVisual, visuals: AnalysisVisual[], question: string): boolean {
if (/具体缺陷|缺陷\s*(?:top|前)/i.test(question) && !/规格|产品/.test(question) && visual.dimension === 'product') return true;
if (/(?:产业部|部门).*top/i.test(question) && !/业务分组/.test(question) && visual.dimension === 'group') return true;
if (/报废/.test(question) && !/投入|生产|产量/.test(question) && /total_weight/.test(visual.metric)) return true;
if (!['line', 'area'].includes(visual.type) || visual.id === agentReportPrimary(visuals, question)?.id) return false;
if (/结构|构成|占比/.test(question) && !/月度|趋势|变化/.test(question)) return true;
if (['black_scrap_rate', 'bright_scrap_rate'].includes(visual.metric)) {
return !/报废率/.test(question) && visuals.some(item => ['black_rate', 'bright_rate', 'composite_rate'].includes(item.metric));
}
return ['black_total_weight', 'bright_total_weight'].includes(visual.metric) && !/投入|生产|产量|重量趋势/.test(question);
}
function monthlyRate(visual: AnalysisVisual) {
return ['line', 'area'].includes(visual.type) && visual.unit === 'ratio' && visual.sectionKey === 'trend' &&
!visual.dimension && visual.categories.length >= 3 && visual.categories.every(item => /^\d{4}-(?:0[1-9]|1[0-2])$/.test(item.label));
}
function change(value: number) {
return `${value > 0 ? '+' : ''}${value.toFixed(2)}`;
}
function chartGroup(figures: AnalysisVisual[]): ChartGroup {
const overall = figures.find(visual => monthlyRate(visual) && visual.metric === 'composite_rate');
if (!overall) return { figures, paired: false, stats: [] };
const paired = figures.length > 1 && figures.every(visual => visual === overall ||
monthlyRate(visual) && ['black_rate', 'bright_rate'].includes(visual.metric) && matchingMonthlyFigures(overall, visual));
const values = overall.series.find(series => series.key === 'composite_rate')?.values || [];
const complete = values.length === overall.categories.length && values.every((value): value is number => value != null);
return { figures, paired, stats: complete ? [
{ label: '末月较首月', value: change((values.at(-1)! - values[0]) * 100), unit: 'pp' },
{ label: '综合率月度极差', value: ((Math.max(...values) - Math.min(...values)) * 100).toFixed(2), unit: 'pp' },
] : [] };
}
function comparisonMetrics(visuals: AnalysisVisual[]): ReportMetric[] {
const comparable = visuals.filter(visual => visual.unit === 'ratio' && visual.metric === 'composite_rate' && visual.comparisonPeriod &&
visual.categories.length === 2 && visual.categories[0].key === 'comparison' && visual.categories[1].key === 'current');
if (comparable.length !== 1) return [];
const visual = comparable[0];
const [previous, current] = visual.series.find(series => series.key === 'composite_rate')?.values ?? [];
if (previous == null || current == null) return [];
return [
{ label: visual.categories[0].label, value: (previous * 100).toFixed(2), unit: '%' },
{ label: visual.categories[1].label, value: (current * 100).toFixed(2), unit: '%' },
{ label: '综合合格率变化', value: change((current - previous) * 100), unit: 'pp' },
];
}
export function buildAgentReportLayout(markdown: string, visuals: AnalysisVisual[]) {
const clean = markdown.trim();
const firstParagraph = clean.split(/\n{2,}/, 1)[0];
const prose = firstParagraph.replace(/^\*\*[^*\n]+\*\*\s*/, '').trim();
const lead = firstParagraph.length > 0 && firstParagraph.length <= 650 && prose.length > 0
&& !/^[#>|*+`-]|^\d+[.)]/.test(prose) && !firstParagraph.includes('\n')
? firstParagraph : '';
const body = lead ? clean.slice(lead.length).trimStart() : clean;
const sections = originalAnalysisSections(body, visuals).map(section => ({
id: `document-${section.id}`,
markdown: section.markdown,
label: plain(section.markdown.match(/^#{2,6}\s+(.+?)\s*#*\s*$/m)?.[1] || ''),
charts: chartGroup(section.visuals),
}));
const aggregate = aggregateMetrics(clean);
return { lead, sections, metrics: aggregate.length ? aggregate : comparisonMetrics(visuals) };
}
+52
View File
@@ -0,0 +1,52 @@
import { decodeQueryValueList } from '../api';
import { isValidAnalysisPeriodContext } from '../analysisPeriodModel';
import type { QueryParams, ViewKind } from '../types';
type AnalysisResultRef = { kind: 'TOP'; resultId: string; releaseId: string };
type AnalysisLinkContext = { present: boolean; query?: QueryParams; resultRef?: AnalysisResultRef; error?: string };
export function decodeAnalysisLinkContext(encoded: string | null): AnalysisLinkContext {
if (!encoded) return { present: false };
try {
const binary = atob(encoded.replaceAll('-', '+').replaceAll('_', '/').padEnd(Math.ceil(encoded.length / 4) * 4, '='));
const bytes = Uint8Array.from(binary, character => character.charCodeAt(0));
const payload: unknown = JSON.parse(new TextDecoder().decode(bytes));
if (!payload || typeof payload !== 'object') throw new Error('分析条件链接格式无效');
const source = payload as Record<string, unknown>;
const rawQuery = source.query && typeof source.query === 'object' ? source.query as Record<string, unknown> : null;
if (!rawQuery) throw new Error('分析条件链接缺少查询上下文');
const year = Number(rawQuery.year);
if (!Number.isInteger(year) || year < 2000 || year > 2100) throw new Error('分析条件链接中的年份无效');
const month = rawQuery.month === undefined || rawQuery.month === null ? undefined : Number(rawQuery.month);
const quarter = rawQuery.quarter === undefined || rawQuery.quarter === null ? undefined : Number(rawQuery.quarter);
const monthStart = rawQuery.monthStart === undefined || rawQuery.monthStart === null ? undefined : Number(rawQuery.monthStart);
const monthEnd = rawQuery.monthEnd === undefined || rawQuery.monthEnd === null ? undefined : Number(rawQuery.monthEnd);
if (!isValidAnalysisPeriodContext({ year, month, quarter, monthStart, monthEnd }, 2000, 2100)) throw new Error('分析条件链接中的统计期间无效');
const views: ViewKind[] = ['overall', 'department', 'group', 'product', 'projectGroup'];
if (!views.includes(rawQuery.view as ViewKind)) throw new Error('分析条件链接中的查询维度无效');
const view = rawQuery.view as ViewKind;
const query: QueryParams = { year, ...(month !== undefined ? { month } : {}), ...(quarter !== undefined ? { quarter } : {}),
...(monthStart !== undefined ? { monthStart } : {}), ...(monthEnd !== undefined ? { monthEnd } : {}), view };
for (const key of ['department', 'group', 'product', 'projectGroup'] as const) {
const value = rawQuery[key];
if (value === undefined || value === null || value === '') continue;
if (typeof value !== 'string') throw new Error(`分析条件链接中的${key}筛选无效`);
if (value.startsWith('~qv1~') && decodeQueryValueList(value).length === 0) throw new Error(`分析条件链接中的${key}多选值无效`);
query[key] = value;
}
if (rawQuery.extraFilters && typeof rawQuery.extraFilters === 'object') query.extraFilters = rawQuery.extraFilters as Record<string,string[]>;
if (rawQuery.releaseId && typeof rawQuery.releaseId === 'string') query.releaseId = rawQuery.releaseId;
if (typeof rawQuery.includeUnassigned === 'boolean') query.includeUnassigned = rawQuery.includeUnassigned;
const rawRef = source.resultRef && typeof source.resultRef === 'object' ? source.resultRef as Record<string, unknown> : undefined;
let resultRef: AnalysisResultRef | undefined;
if (rawRef) {
if (rawRef.kind !== 'TOP' || typeof rawRef.resultId !== 'string' || !rawRef.resultId || typeof rawRef.releaseId !== 'string' || !rawRef.releaseId) throw new Error('排名结果引用不完整,请重新打开分析');
if (query.releaseId && query.releaseId !== rawRef.releaseId) throw new Error('查询数据已更新,请重新打开分析');
query.releaseId = rawRef.releaseId;
resultRef = { kind: 'TOP', resultId: rawRef.resultId, releaseId: rawRef.releaseId };
}
return { present: true, query, ...(resultRef ? { resultRef } : {}) };
} catch (error) {
return { present: true, error: error instanceof Error ? error.message : '分析条件链接无法读取' };
}
}
+812
View File
@@ -0,0 +1,812 @@
import { acceptAnalysisEvent, analysisIsRunning, analysisStreamStatus, defaultAnalysisSession, rememberAnalysisSession } from '../analysisConversationState.ts';
import { mergeModelThinking, modelThinkingEntries } from '../analysisModelThinking.ts';
import { beginAnalysisSubmission, submissionOutcomeUnknown, type AnalysisSubmission } from '../analysisSubmission.ts';
import type { StreamEvent } from '../eventStream.ts';
import type { AnalysisSessionClientOptions, AnalysisSessionSnapshot, AnalysisSessionTransport, AnalysisSessionTurn, InitialSession, NewSession, PromptContext, SessionRecord } from './sessionTypes.ts';
const terminalStatuses = new Set(['COMPLETED', 'PARTIAL', 'FAILED', 'CANCELLED', 'NEEDS_CLARIFICATION']);
const retryableStatuses = new Set(['PARTIAL', 'FAILED', 'CANCELLED']);
const record = (value: unknown): SessionRecord | undefined =>
value !== null && typeof value === 'object' && !Array.isArray(value) ? value as SessionRecord : undefined;
const string = (value: unknown): string => typeof value === 'string' ? value : '';
const statusOf = (value: unknown): string => string(value).toUpperCase();
const statusCode = (error: unknown): number => Number(record(error)?.status);
const errorText = (error: unknown): string => error instanceof Error ? error.message : '服务请求失败';
const isAccessError = (error: unknown): boolean => [401, 403, 404].includes(statusCode(error));
function freshSession(options: PromptContext = {}): Omit<AnalysisSessionSnapshot, 'sessions' | 'sessionsLoading' | 'sessionsError'> {
return {
sessionId: '', sessionTitle: '', sessionContext: options.context ?? null, releaseId: options.releaseId,
readOnly: false, turns: [], focusTurnId: '', activeTurnId: '', historyLoading: false, historyError: '',
olderCursor: '', loadingOlder: false, busy: false, stopping: false, queuedQuestion: '', pendingQuestion: '',
retryQuestion: '', error: '', connection: 'idle',
};
}
function modelAnswer(row: SessionRecord | undefined): string {
const original = string(row?.modelAnswer);
const resultOriginal = string(record(row?.result)?.modelAnswer);
return original.trim() ? original : resultOriginal.trim() ? resultOriginal : '';
}
/** A durable baseline never includes a transient draft. */
function savedTurn(row: SessionRecord, sessionId: string, prior?: AnalysisSessionTurn): AnalysisSessionTurn {
const result = record(row.result);
const combined = { ...result, ...row } as AnalysisSessionTurn;
combined.sessionId = sessionId;
const original = modelAnswer(row) || modelAnswer(prior) ||
(['PARTIAL', 'FAILED', 'CANCELLED'].includes(statusOf(row.status)) ? string(prior?.dshDraft) : '');
if (original) combined.modelAnswer = original;
if (result?.visualRecovery && result.originalStatus === row.status) {
combined.status = string(result.status) || string(row.status);
}
return withoutDraft(combined);
}
function withoutDraft(row: AnalysisSessionTurn): AnalysisSessionTurn {
if (row.dshDraft === undefined && row.dshDraftAttemptId === undefined) return row;
const next = { ...row };
delete next.dshDraft;
delete next.dshDraftAttemptId;
return next;
}
function clearDrafts(turns: readonly AnalysisSessionTurn[]): readonly AnalysisSessionTurn[] {
return turns.some(row => row.dshDraft !== undefined || row.dshDraftAttemptId !== undefined) ? turns.map(withoutDraft) : turns;
}
function byCreation(a: AnalysisSessionTurn, b: AnalysisSessionTurn): number {
const firstStamp = string(a.createdAt), secondStamp = string(b.createdAt);
const first = Date.parse(firstStamp), second = Date.parse(secondStamp);
if (!Number.isFinite(first)) return Number.isFinite(second) ? 1 : 0;
if (!Number.isFinite(second)) return -1;
if (first !== second) return first - second;
// Date.parse drops sub-millisecond precision. If the Host returned equal
// display timestamps, stable sorting preserves the ordered history page.
const fraction = (value: string) => Number((value.match(/\.(\d+)/)?.[1] || '').padEnd(9, '0'));
return fraction(firstStamp) - fraction(secondStamp);
}
function upsert(turns: readonly AnalysisSessionTurn[], next: AnalysisSessionTurn): AnalysisSessionTurn[] {
const index = next.id ? turns.findIndex(row => row.id === next.id) : -1;
if (index < 0) return [...turns, next];
return turns.map((row, rowIndex) => rowIndex === index ? next : row);
}
function wait(ms: number, signal: AbortSignal): Promise<void> {
if (signal.aborted) return Promise.resolve();
return new Promise(resolve => {
const finish = () => {
clearTimeout(timer);
signal.removeEventListener('abort', finish);
resolve();
};
const timer = setTimeout(finish, ms);
signal.addEventListener('abort', finish, { once: true });
});
}
interface QueuedPrompt {
question: string;
context: PromptContext;
held?: boolean;
}
/** React-free mirror of one selected DSH session. The Host owns all saved data. */
export class AnalysisSessionClient {
private readonly options: AnalysisSessionClientOptions;
private readonly listeners = new Set<() => void>();
private state: AnalysisSessionSnapshot = { ...freshSession(), sessions: [], sessionsLoading: false, sessionsError: '' };
private generation = 0;
private listGeneration = 0;
private listRequest?: Promise<readonly SessionRecord[]>;
private initialSelection?: InitialSession;
private initialRequest = 0;
private followController?: AbortController;
private olderController?: AbortController;
private cancelledTailController?: AbortController;
private cursor = new Map<string, string>();
private queued?: QueuedPrompt;
private submission: AnalysisSubmission | null = null;
private expectedTurnId = '';
private loadedOlder = false;
private suspended = false;
private disposed = false;
constructor(options: AnalysisSessionClientOptions) {
this.options = options;
}
readonly getSnapshot = (): AnalysisSessionSnapshot => this.state;
readonly subscribe = (listener: () => void): (() => void) => {
this.listeners.add(listener);
return () => { this.listeners.delete(listener); };
};
private async transport(): Promise<AnalysisSessionTransport> {
return this.options.transport ?? (await import('../api.ts')).api;
}
private update(patch: Partial<AnalysisSessionSnapshot>): void {
if (this.disposed || Object.entries(patch).every(([key, value]) => this.state[key as keyof AnalysisSessionSnapshot] === value)) return;
this.state = { ...this.state, ...patch };
this.listeners.forEach(listener => listener());
}
private current(generation: number): boolean {
return !this.disposed && generation === this.generation;
}
private message(error: unknown): string {
return this.options.onUnauthorized?.(error) ? '' : errorText(error);
}
private location(sessionId: string, turnId?: string): void {
rememberAnalysisSession(this.options.userId, sessionId);
this.options.onLocationChange?.(sessionId, turnId);
}
private stopFollow(): void {
this.followController?.abort();
this.followController = undefined;
}
private navigate(): void {
this.generation += 1;
this.cancelledTailController?.abort();
this.stopFollow();
this.olderController?.abort();
this.olderController = undefined;
this.cursor.clear();
this.initialSelection = undefined;
this.expectedTurnId = '';
this.loadedOlder = false;
this.submission = null;
this.queued = undefined;
}
readonly clearError = (): void => this.update({ error: '', historyError: '' });
readonly refreshSessions = (): Promise<readonly SessionRecord[]> => this.readSessions();
private readSessions(force = false): Promise<readonly SessionRecord[]> {
if (this.disposed) return Promise.resolve([]);
if (!force && this.listRequest) return this.listRequest;
const generation = ++this.listGeneration;
this.update({ sessionsLoading: true, sessionsError: '' });
const request = (async () => {
try {
const api = await this.transport();
const data = await api.analysisSessions();
const sessions = Array.isArray(data.items) ? data.items.filter(item => string(item.id)) : [];
if (!this.disposed && generation === this.listGeneration) this.update({ sessions, sessionsError: '' });
return sessions;
} catch (error) {
if (!this.disposed && generation === this.listGeneration) {
this.update({ ...(isAccessError(error) ? { sessions: [] } : {}), sessionsError: this.message(error) });
}
return [];
} finally {
if (!this.disposed && generation === this.listGeneration) {
this.listRequest = undefined;
this.update({ sessionsLoading: false });
}
}
})();
this.listRequest = request;
return request;
}
readonly openInitial = async (initial: InitialSession = {}): Promise<boolean> => {
if (this.disposed) return false;
this.initialSelection = initial;
const generation = this.generation;
const request = ++this.initialRequest;
const current = () => this.current(generation) && request === this.initialRequest && !this.suspended;
const list = this.refreshSessions();
let id = initial.sessionId || '';
const selectRecent = initial.selectRecent !== false;
if (!id && (initial.turnId || selectRecent)) this.update({ historyLoading: true, historyError: '' });
try {
if (!id && initial.turnId) {
const api = await this.transport();
const turn = await api.analysisTurn(initial.turnId);
if (!current()) return false;
id = string(turn.sessionId);
if (!id) throw new Error('未找到该分析所属的会话');
}
if (!id && selectRecent) {
const sessions = await list;
if (!current()) return false;
if (this.state.sessionsError) {
this.update({ historyLoading: false, historyError: this.state.sessionsError });
return false;
}
id = defaultAnalysisSession(this.options.userId, [...sessions]);
}
if (!current()) return false;
if (id) return await this.openSession(id, initial.turnId);
this.initialSelection = undefined;
this.update({ historyLoading: false, historyError: '' });
return true;
} catch (error) {
if (current()) this.update({ historyLoading: false, historyError: this.message(error) });
return false;
}
};
readonly openSession = (id: string, focusTurnId = ''): Promise<boolean> => {
if (!id || this.disposed) return Promise.resolve(false);
this.navigate();
this.update({ ...freshSession(), sessionId: id, focusTurnId, historyLoading: true });
return this.connect();
};
readonly newSession = (options: NewSession = {}): void => {
if (this.disposed) return;
this.navigate();
this.update(freshSession(options));
if (!options.preserveLocation) this.location('');
};
readonly suspend = (): void => {
if (this.disposed || this.suspended) return;
this.suspended = true;
this.stopFollow();
this.olderController?.abort();
this.olderController = undefined;
this.update({ connection: 'idle', loadingOlder: false, turns: clearDrafts(this.state.turns) });
};
readonly resume = (): void => {
if (this.disposed) return;
this.suspended = false;
if (!this.state.sessionId && this.initialSelection) {
void this.openInitial(this.initialSelection);
return;
}
if (this.state.sessionId && !this.followController) void this.connect();
void this.refreshSessions();
};
readonly dispose = (): void => {
this.navigate();
this.disposed = true;
this.listeners.clear();
};
private connect(): Promise<boolean> {
if (this.disposed || this.suspended || !this.state.sessionId) return Promise.resolve(false);
this.stopFollow();
const controller = new AbortController();
this.followController = controller;
const generation = this.generation;
const id = this.state.sessionId;
const current = () => this.current(generation) && this.followController === controller && !controller.signal.aborted;
this.update({ connection: 'connecting', historyError: '', turns: clearDrafts(this.state.turns) });
return new Promise(resolve => {
const settle = (loaded: boolean) => {
controller.signal.removeEventListener('abort', aborted);
resolve(loaded);
};
const aborted = () => settle(false);
controller.signal.addEventListener('abort', aborted, { once: true });
void this.follow(id, controller.signal, current, settle).finally(() => {
settle(false);
if (current()) {
this.followController = undefined;
this.update({ connection: 'idle', historyLoading: false });
}
});
});
}
private async follow(id: string, signal: AbortSignal, current: () => boolean, loaded: (success: boolean) => void): Promise<void> {
try {
const api = await this.transport();
if (!current()) return;
let established = false, attempts = 0, transportFallback = false, terminal = false;
const publishBaseline = (page: SessionRecord): Promise<void> | undefined => {
if (!current()) return;
this.applyBaseline(id, page);
if (established) return;
established = true;
const focused = this.state.focusTurnId;
this.location(id, focused || undefined);
if (!focused || this.state.turns.some(turn => turn.id === focused)) {
loaded(true);
return;
}
return (async () => {
try {
const detail = await api.analysisTurn(focused);
if (!current()) return;
if (detail.sessionId !== id) throw new Error('分析轮次与会话链接不匹配');
this.update({ turns: [savedTurn(detail, id, this.state.turns.find(row => row.id === focused)), ...this.state.turns.filter(row => row.id !== focused)].sort(byCreation) });
} catch (error) {
if (current()) this.update({ historyError: this.message(error) });
}
if (current()) loaded(true);
})();
};
while (current()) {
let snapshotReceived = false;
let baseline: Promise<void> | undefined;
terminal = false;
let receivedEvents = false;
const stream = new AbortController();
const abortStream = () => stream.abort();
signal.addEventListener('abort', abortStream, { once: true });
const openingDeadline = setTimeout(abortStream, 15000);
const onEvent = (event: StreamEvent) => {
if (!current()) return;
if (event.event === 'snapshot') {
const page = record(event.data);
if (!page) throw new Error('会话快照格式异常');
snapshotReceived = true;
clearTimeout(openingDeadline);
baseline = publishBaseline(page);
return;
}
if (!snapshotReceived) throw new Error('会话事件缺少开场快照');
receivedEvents = true;
if (this.applyEvent(event)) terminal = true;
};
try {
if (transportFallback) {
const page = await api.analysisSessionPage(id, undefined, signal);
snapshotReceived = true;
clearTimeout(openingDeadline);
baseline = publishBaseline(page);
if (!current()) return;
const activeId = this.state.activeTurnId;
if (activeId) {
await api.analysisTurnEvents(activeId, {
signal, lastEventId: this.cursor.get(activeId), onEvent,
});
}
} else {
await api.analysisSessionFollow(id, { signal: stream.signal, onEvent });
}
await baseline;
if (!snapshotReceived) throw new Error('未收到会话快照,请重试');
} catch (error) {
await baseline;
if (!current()) return;
// A rolling deployment can briefly pair the current UI with the old Host.
if (!snapshotReceived && !transportFallback &&
(stream.signal.aborted || [404, 405, 406].includes(statusCode(error)))) {
transportFallback = true;
continue;
}
if (isAccessError(error) || !established) throw error;
} finally {
clearTimeout(openingDeadline);
signal.removeEventListener('abort', abortStream);
abortStream();
}
if (!current()) return;
if (terminal) {
// The terminal event carries the checked result. One replacement
// snapshot updates the persisted timestamps and report metadata.
void this.refreshSessions();
continue;
}
if (!this.state.activeTurnId && !this.expectedTurnId) {
this.drainQueued();
return;
}
this.update({ connection: 'reconnecting', turns: clearDrafts(this.state.turns) });
attempts = receivedEvents ? 0 : Math.min(attempts + 1, 4);
await wait(Math.min(500 * 2 ** attempts, 8000), signal);
}
} catch (error) {
if (!current()) return;
const denied = isAccessError(error);
this.update({
historyError: this.message(error),
...(denied ? { turns: [], olderCursor: '', readOnly: true, activeTurnId: '', busy: false, stopping: false } :
this.state.historyLoading ? { readOnly: true } : {}),
});
loaded(false);
}
}
private applyBaseline(id: string, page: SessionRecord): void {
if (page.id !== id || !Array.isArray(page.turns)) throw new Error('会话快照与当前会话不匹配');
const rows = page.turns.flatMap(value => {
const row = record(value);
return row && string(row.id) ? [savedTurn(row, id, this.state.turns.find(turn => turn.id === row.id))] : [];
});
const byId = new Map(rows.map(row => [row.id, row]));
const existing = this.state.turns.filter(row => row.id && !byId.has(row.id)).map(withoutDraft);
const pending = this.state.turns.filter(row => !row.id && row.status === 'SUBMITTING');
this.cursor = new Map(rows.flatMap(row => row.id && row.eventCursor ? [[row.id, row.eventCursor]] : []));
if (this.expectedTurnId && byId.has(this.expectedTurnId)) this.expectedTurnId = '';
const activeId = string(page.activeTurnId) || [...rows].reverse().find(row => analysisIsRunning(row.status))?.id || this.expectedTurnId;
const context = record(page.context) ?? null;
const releaseId = string(page.releaseId) || string(context?.releaseId) || undefined;
this.update({
sessionTitle: string(page.title),
sessionContext: context,
releaseId,
readOnly: page.readOnly === true,
turns: [...existing, ...rows, ...pending].sort(byCreation),
activeTurnId: activeId,
busy: Boolean(activeId || this.submission?.inFlight),
stopping: Boolean(activeId && this.state.stopping),
historyLoading: false,
historyError: '',
connection: 'live',
...(this.loadedOlder ? {} : { olderCursor: string(page.before) }),
});
}
private applyEvent(event: StreamEvent, local = false): boolean {
const data = record(event.data);
const id = string(data?.turnId);
const prior = id && this.state.turns.find(row => row.id === id);
if (!data || !prior) return false;
if (event.event === 'draft') {
const attemptId = string(data.attemptId);
if (id !== this.state.activeTurnId || !analysisIsRunning(prior.status) || !attemptId || typeof data.text !== 'string') return false;
const next = data.text ? { ...prior, dshDraft: data.text.slice(0, 4096), dshDraftAttemptId: attemptId } : withoutDraft(prior);
if (next.dshDraft !== prior.dshDraft || next.dshDraftAttemptId !== prior.dshDraftAttemptId)
this.update({ turns: upsert(this.state.turns, next) });
return false;
}
if ((!event.id && !local) || !acceptAnalysisEvent(event.id, this.cursor.get(id))) return false;
if (event.id) this.cursor.set(id, event.id);
if (terminalStatuses.has(statusOf(prior.status))) {
const original = modelAnswer(data);
if (original) this.update({ turns: upsert(this.state.turns, { ...prior, modelAnswer: original, ...(event.id ? { eventCursor: event.id } : {}) }) });
return false;
}
const status = analysisStreamStatus(prior.status, event.event, data.status);
const finished = terminalStatuses.has(status);
const result = finished ? record(data.result) : undefined;
const base = finished ? withoutDraft(prior) : prior;
const original = modelAnswer(data) || modelAnswer(prior) ||
(['PARTIAL', 'FAILED', 'CANCELLED'].includes(status) ? string(prior.dshDraft) : '');
const next: AnalysisSessionTurn = {
...base,
...(result || {}),
...(original ? { modelAnswer: original } : {}),
id, sessionId: prior.sessionId, question: prior.question,
status,
latestEvent: event.event,
...(event.id ? { eventCursor: event.id } : {}),
...(result ? { result } : {}),
...(Array.isArray(data.steps) ? { steps: data.steps } : {}),
...(Array.isArray(data.timeline) ? { timeline: data.timeline } : {}),
...(record(data.plan) ? { plan: data.plan } : {}),
...(typeof data.message === 'string' ? { progressMessage: data.message } : {}),
...(typeof data.dshActivity === 'string' ? { dshActivity: data.dshActivity } : {}),
...(typeof data.startedAt === 'string' ? { startedAt: data.startedAt } : {}),
...(typeof data.updatedAt === 'string' ? { updatedAt: data.updatedAt } : {}),
...(typeof data.stopReason === 'string' ? { stopReason: data.stopReason } : {}),
...(data.thinkingDelta ? { modelThinking: mergeModelThinking(modelThinkingEntries(prior), data.thinkingDelta) } : {}),
};
if (finished && this.expectedTurnId === id) this.expectedTurnId = '';
this.update({
turns: upsert(this.state.turns, next),
activeTurnId: finished ? '' : id,
busy: !finished || Boolean(this.submission?.inFlight),
...(finished ? { stopping: false, retryQuestion: '' } : {}),
});
return finished;
}
readonly loadOlder = async (): Promise<boolean> => {
const { sessionId: id, olderCursor } = this.state;
if (this.disposed || this.suspended || !id || !olderCursor || this.olderController) return false;
const controller = new AbortController();
this.olderController = controller;
const generation = this.generation;
const current = () => this.current(generation) && this.olderController === controller && !controller.signal.aborted;
this.update({ loadingOlder: true, historyError: '' });
try {
const api = await this.transport();
const page = await api.analysisSessionPage(id, olderCursor, controller.signal);
if (!current()) return false;
if (page.id !== id || !Array.isArray(page.turns)) throw new Error('历史页与当前会话不匹配');
const loaded = new Set<string>();
const rows = page.turns.flatMap(value => {
const row = record(value);
if (!row || !string(row.id) || loaded.has(string(row.id))) return [];
loaded.add(string(row.id));
return [savedTurn(row, id, this.state.turns.find(turn => turn.id === row.id))];
});
this.loadedOlder = true;
const nextCursor = string(page.before);
const rest = this.state.turns.filter(row => !row.id || !loaded.has(row.id));
this.update({ turns: [...rows, ...rest].sort(byCreation), olderCursor: nextCursor === olderCursor ? '' : nextCursor });
return true;
} catch (error) {
if (current()) {
if (isAccessError(error)) {
this.stopFollow();
this.update({ turns: [], olderCursor: '', readOnly: true, busy: false, activeTurnId: '', stopping: false, connection: 'idle' });
}
this.update({ historyError: this.message(error) });
}
return false;
} finally {
if (current()) {
this.olderController = undefined;
this.update({ loadingOlder: false });
}
}
};
readonly takeQueued = (): string => {
const question = this.queued?.question || '';
this.queued = undefined;
this.update({ queuedQuestion: '' });
return question;
};
private drainQueued(): void {
const queued = this.queued;
const latest = this.state.turns.at(-1);
if (!queued || queued.held || this.state.busy || this.state.stopping || !latest ||
!['COMPLETED', 'PARTIAL', 'FAILED'].includes(statusOf(latest.status))) return;
this.takeQueued();
void this.submit(queued.question, queued.context);
}
readonly submit = async (input: string, options: PromptContext = {}): Promise<boolean> => {
const question = input.trim();
if (!question || this.disposed || this.suspended || this.state.historyLoading || this.state.readOnly || this.state.stopping) return false;
if (this.state.busy || this.submission?.inFlight) {
if (this.queued) return false;
this.queued = { question, context: options };
this.update({ queuedQuestion: question });
return true;
}
const sessionId = this.state.sessionId;
const releaseId = options.releaseId || this.state.releaseId;
const context = options.context ?? this.state.sessionContext ?? undefined;
const previous = this.submission;
// Creating a session can disclose a server-selected release after the first
// POST. Retrying an uncertain receipt from the same composer preserves the
// exact request that may already have been accepted.
const sameComposer = (!options.releaseId || options.releaseId === this.state.releaseId) &&
(!options.context || options.context === this.state.sessionContext);
const retryUncertain = sameComposer && previous?.uncertain && previous.sessionId === sessionId &&
previous.question === question && previous.generation === this.generation;
const requestContext = retryUncertain ? previous.context : releaseId ? { ...context, releaseId } : context;
let attempt: AnalysisSubmission;
try {
attempt = beginAnalysisSubmission(previous, { sessionId, question, context: requestContext, generation: this.generation });
} catch (error) {
this.update({ error: this.message(error), retryQuestion: question });
return false;
}
this.submission = attempt;
const current = () => this.current(attempt.generation) && this.submission === attempt;
const optimistic: AnalysisSessionTurn = {
question, status: 'SUBMITTING', _uiSubmittedAt: new Date().toISOString(), _uiFollowKey: attempt.idempotencyKey,
};
this.update({
turns: [...this.state.turns.filter(row => row.id), optimistic],
pendingQuestion: question, busy: true, retryQuestion: '', error: '',
});
try {
const api = await this.transport();
if (!current()) return false;
if (!attempt.sessionId) {
const created = await api.createAnalysisSession({ title: question.slice(0, 60), releaseId, context: requestContext });
attempt.sessionId = string(created.session.id);
if (!attempt.sessionId) throw new Error('服务端未返回分析会话编号');
if (!current()) return false;
this.update({
sessionId: attempt.sessionId,
sessionTitle: string(created.session.title) || question.slice(0, 60),
releaseId: string(created.session.releaseId) || releaseId,
sessionContext: record(created.session.context) ?? requestContext ?? null,
});
this.location(attempt.sessionId);
}
if (attempt.cancelRequested && !attempt.turnRequestStarted) {
this.update({ turns: this.state.turns.filter(row => row.id), busy: false, stopping: false, pendingQuestion: '' });
void this.refreshSessions();
return false;
}
attempt.turnRequestStarted = true;
const response = await api.startAnalysisTurn(attempt.sessionId, { question, context: requestContext, idempotencyKey: attempt.idempotencyKey });
return await this.acceptSubmission(response.turn, attempt, optimistic, current);
} catch (error) {
attempt.uncertain = attempt.turnRequestStarted && !attempt.acceptedTurnId && submissionOutcomeUnknown(error);
if (current()) this.submissionFailure(error, question);
return false;
} finally {
this.releaseSubmission(attempt);
}
};
private async acceptSubmission(row: SessionRecord, attempt: AnalysisSubmission, optimistic: AnalysisSessionTurn, current: () => boolean): Promise<boolean> {
const id = string(row.id);
if (!id) throw new Error('服务端未返回分析任务编号');
const sessionId = string(row.sessionId) || attempt.sessionId;
if (sessionId !== attempt.sessionId) throw new Error('提交结果与当前会话不匹配');
attempt.acceptedTurnId = id;
attempt.uncertain = false;
if (current()) {
this.expectedTurnId = id;
const next = { ...optimistic, ...savedTurn(row, sessionId), id, status: string(row.status) || 'QUEUED' };
this.update({
turns: upsert(this.state.turns.filter(item => item.id), next),
activeTurnId: analysisIsRunning(next.status) ? id : '',
focusTurnId: id, pendingQuestion: '', retryQuestion: '',
});
this.location(sessionId, id);
}
// A stop clicked while POST was in transit still belongs to that turn,
// even if the user selected a different conversation before its receipt.
if (attempt.cancelRequested) await this.cancelAccepted(id, current, false);
if (current()) {
attempt.inFlight = false;
void this.connect();
void this.refreshSessions();
}
return true;
}
private submissionFailure(error: unknown, question: string): void {
this.update({
turns: this.state.turns.filter(row => row.id),
error: this.message(error), retryQuestion: question, pendingQuestion: '', busy: Boolean(this.state.activeTurnId), stopping: false,
});
}
private releaseSubmission(attempt: AnalysisSubmission): void {
attempt.inFlight = false;
if (this.submission === attempt && !attempt.uncertain) this.submission = null;
}
readonly retry = async (id: string): Promise<boolean> => {
const turn = this.state.turns.find(row => row.id === id);
if (!turn || this.disposed || this.suspended || this.state.busy || this.state.readOnly || this.state.historyLoading ||
!retryableStatuses.has(statusOf(turn.status)) || turn.retryAvailable === false) return false;
this.cancelledTailController?.abort();
const question = string(turn.question);
let attempt: AnalysisSubmission;
try {
attempt = beginAnalysisSubmission(null, { sessionId: this.state.sessionId, question, generation: this.generation });
} catch (error) {
this.update({ error: this.message(error) });
return false;
}
this.submission = attempt;
const current = () => this.current(attempt.generation) && this.submission === attempt;
const optimistic: AnalysisSessionTurn = {
question, status: 'SUBMITTING', _uiSubmittedAt: new Date().toISOString(), _uiFollowKey: attempt.idempotencyKey,
};
// Retry reuses the turn ID. Detach the old follow before the same row
// starts a new attempt, so its terminal event cannot settle the retry.
this.stopFollow();
this.cursor.delete(id);
this.update({ turns: upsert(this.state.turns, { ...optimistic, id }), busy: true, pendingQuestion: question,
error: '', retryQuestion: '', connection: 'idle' });
try {
const api = await this.transport();
if (!current()) return false;
const response = await api.retryAnalysisTurn(id);
return await this.acceptSubmission(response.turn, attempt, optimistic, current);
} catch (error) {
if (current()) {
this.update({ turns: upsert(this.state.turns, turn) });
this.submissionFailure(error, '');
if (submissionOutcomeUnknown(error)) void this.connect();
}
return false;
} finally {
this.releaseSubmission(attempt);
}
};
private async cancelAccepted(id: string, current: () => boolean, reopen = true): Promise<boolean> {
try {
const api = await this.transport();
const response = await api.cancelAnalysisTurn(id, '用户请求停止');
if (current() && terminalStatuses.has(statusOf(response.status))) {
this.applyEvent({ event: statusOf(response.status).toLowerCase(), data: { ...response, turnId: id } }, true);
this.update({ busy: false, stopping: false });
if (statusOf(response.status) === 'CANCELLED') this.refreshCancelledTail(id);
if (reopen) void this.connect();
}
return true;
} catch (error) {
if (current()) this.update({ error: this.message(error), stopping: false });
return false;
}
}
private refreshCancelledTail(id: string): void {
this.cancelledTailController?.abort();
const controller = new AbortController();
this.cancelledTailController = controller;
const generation = this.generation;
const sessionId = this.state.sessionId;
const prior = this.state.turns.find(row => row.id === id);
const attemptId = string(prior?.attemptId);
const current = () => this.current(generation) && !controller.signal.aborted &&
this.state.sessionId === sessionId && this.state.turns.some(row => row.id === id && row.status === 'CANCELLED');
void (async () => {
const api = await this.transport();
for (const delay of [350, 650]) {
await wait(delay, controller.signal);
if (!current()) return;
try {
const beforeRead = modelAnswer(this.state.turns.find(row => row.id === id));
const detail = await api.analysisTurn(id);
if (!current()) return;
if (detail.id !== id || detail.sessionId !== sessionId || statusOf(detail.status) !== 'CANCELLED' ||
(attemptId && string(detail.attemptId) !== attemptId)) return;
const original = modelAnswer(detail);
const latest = this.state.turns.find(row => row.id === id);
if (original && latest && modelAnswer(latest) === beforeRead)
this.update({ turns: upsert(this.state.turns, { ...latest, modelAnswer: original }) });
} catch {
// The durable follow or a later history read can recover a failed tail read.
}
}
})().catch(() => {});
}
readonly cancel = async (): Promise<boolean> => {
if (this.disposed || this.state.stopping) return false;
// Keep unsent input editable, even if the current turn happens to finish
// before the stop request reaches the Host.
if (this.queued) this.queued.held = true;
const attempt = this.submission;
if (attempt?.inFlight && !attempt.acceptedTurnId) {
attempt.cancelRequested = true;
this.update({ stopping: true });
return true;
}
const id = this.state.activeTurnId;
if (!id) return false;
const generation = this.generation;
this.update({ stopping: true });
return this.cancelAccepted(id, () => this.current(generation));
};
readonly renameSession = async (id: string, input: string): Promise<boolean> => {
const title = input.trim();
if (!title || this.disposed) return false;
try {
const api = await this.transport();
const updated = await api.renameAnalysisSession(id, title);
this.update({
sessions: this.state.sessions.map(row => row.id === id ? { ...row, title: updated.title } : row),
...(this.state.sessionId === id ? { sessionTitle: updated.title } : {}),
});
void this.readSessions(true);
return true;
} catch (error) {
if (!this.disposed) this.update({ error: this.message(error) });
return false;
}
};
readonly deleteSession = async (id: string): Promise<boolean> => {
if (this.disposed) return false;
try {
const api = await this.transport();
await api.deleteAnalysisSession(id);
if (this.state.sessionId === id) this.newSession();
this.update({ sessions: this.state.sessions.filter(row => row.id !== id) });
void this.readSessions(true);
return true;
} catch (error) {
if (!this.disposed) this.update({ error: this.message(error) });
return false;
}
};
}
export function createAnalysisSessionClient(options: AnalysisSessionClientOptions): AnalysisSessionClient {
return new AnalysisSessionClient(options);
}
+66
View File
@@ -0,0 +1,66 @@
import type { api } from '../api';
export type SessionRecord = Record<string, unknown>;
export type AnalysisSessionTurn = SessionRecord & {
id?: string;
sessionId?: string;
question?: string;
status?: string;
result?: SessionRecord;
modelAnswer?: string;
eventCursor?: string;
dshDraft?: string;
dshDraftAttemptId?: string;
};
export type AnalysisSessionTransport = Pick<typeof api,
'analysisSessions' | 'analysisSessionPage' | 'analysisSessionFollow' | 'analysisTurn' | 'analysisTurnEvents' |
'createAnalysisSession' | 'startAnalysisTurn' | 'retryAnalysisTurn' | 'cancelAnalysisTurn' |
'renameAnalysisSession' | 'deleteAnalysisSession'>;
export interface AnalysisSessionSnapshot {
readonly sessions: readonly SessionRecord[];
readonly sessionsLoading: boolean;
readonly sessionsError: string;
readonly sessionId: string;
readonly sessionTitle: string;
readonly sessionContext: SessionRecord | null;
readonly releaseId?: string;
readonly readOnly: boolean;
readonly turns: readonly AnalysisSessionTurn[];
readonly focusTurnId: string;
readonly activeTurnId: string;
readonly historyLoading: boolean;
readonly historyError: string;
readonly olderCursor: string;
readonly loadingOlder: boolean;
readonly busy: boolean;
readonly stopping: boolean;
readonly queuedQuestion: string;
readonly pendingQuestion: string;
readonly retryQuestion: string;
readonly error: string;
readonly connection: 'idle' | 'connecting' | 'live' | 'reconnecting';
}
export interface AnalysisSessionClientOptions {
userId: string;
onUnauthorized?: (error: unknown) => boolean;
onLocationChange?: (sessionId: string, turnId?: string) => void;
transport?: AnalysisSessionTransport;
}
export interface InitialSession {
sessionId?: string;
turnId?: string;
selectRecent?: boolean;
}
export interface PromptContext {
releaseId?: string;
context?: SessionRecord;
}
export interface NewSession extends PromptContext {
preserveLocation?: boolean;
}
+14
View File
@@ -0,0 +1,14 @@
import { analysisScrollFollows, type AnalysisScrollIntent } from '../analysisConversationState.ts';
type ScrollGeometry = Pick<HTMLElement, 'scrollTop' | 'scrollHeight' | 'clientHeight' | 'offsetHeight' | 'getBoundingClientRect'>;
export function scrollTopFromVisualOffset(viewport: ScrollGeometry, visualOffset: number, inset = 0): number {
const scale = viewport.offsetHeight ? viewport.getBoundingClientRect().height / viewport.offsetHeight : 1;
return viewport.scrollTop + visualOffset / (scale || 1) - inset;
}
export function transcriptFollowState(viewport: ScrollGeometry, following: boolean, intent: AnalysisScrollIntent) {
const distance = viewport.scrollHeight - viewport.clientHeight - viewport.scrollTop;
const follows = analysisScrollFollows(distance, following, intent);
return { follows, showLatest: !follows && distance > 24 };
}
+3 -2
View File
@@ -29,8 +29,9 @@
.ai-markdown pre{max-width:100%;overflow:auto;padding:12px;background:#f4f6f9;border:1px solid #e5eaf0;white-space:pre-wrap;overflow-wrap:anywhere}
.ai-markdown pre code{padding:0;background:transparent;white-space:pre-wrap}
.ai-markdown-table-wrap{max-width:100%;margin:10px 0 14px;overflow:auto;border:1px solid var(--line,#dfe5ed);border-radius:6px;background:var(--surface,#fff)}
.ai-markdown table{width:100%;border-collapse:collapse;table-layout:fixed;font-size:var(--font-body);line-height:1.65}
.ai-markdown th,.ai-markdown td{padding:9px 12px;border:1px solid var(--line,#dfe5ef);text-align:center;vertical-align:middle;overflow-wrap:anywhere;word-break:break-word}
.ai-markdown table{width:100%;border-collapse:collapse;table-layout:auto;font-size:var(--font-body);line-height:1.65}
.ai-markdown th,.ai-markdown td{padding:9px 12px;border:1px solid var(--line,#dfe5ef);text-align:center;vertical-align:middle;white-space:nowrap;overflow-wrap:normal;word-break:normal}
.ai-markdown td.ai-markdown-prose{min-width:16em;white-space:normal;overflow-wrap:anywhere;word-break:normal}
.ai-markdown th{background:color-mix(in srgb,var(--surface,#fff) 84%,var(--blue-soft,#eef1ff));font-weight:650}
.ai-markdown tbody tr:nth-child(even)>td{background:color-mix(in srgb,var(--surface,#fff) 96%,var(--blue-soft,#eef1ff))}
.ai-markdown .ai-markdown-index{width:64px;color:var(--muted-ink,#738198);font-variant-numeric:tabular-nums;white-space:nowrap}
+4 -3
View File
@@ -9,6 +9,7 @@ export interface ConclusionComparison {
}
export interface ConclusionSection {
id: string; title: string; markdown: string; note: string; visuals: AnalysisVisual[];
implicitTitle?: boolean;
}
/** Read only an explicit, checked comparison sentence. No KPI or difference is calculated. */
@@ -39,7 +40,7 @@ function topicMatches(title: string, visual: AnalysisVisual): boolean {
/** Chapters preserve the model's checked words/order; figures must also share its actual reference. */
export function buildConclusionDocument(reading: AnalysisReadingSummary, visuals: AnalysisVisual[]) {
const raw = conclusionMarkdown(reading, true);
const chunks: Array<{ title: string; lines: string[]; note: string }> = [{ title: '核心结论', lines: [], note: '' }];
const chunks: Array<{ title: string; lines: string[]; note: string; implicitTitle?: boolean }> = [{ title: '核心结论', lines: [], note: '', implicitTitle: true }];
const lines = raw.split('\n');
let fenced = false;
for (let index = 0; index < lines.length; index += 1) {
@@ -56,9 +57,9 @@ export function buildConclusionDocument(reading: AnalysisReadingSummary, visuals
} else chunks.at(-1)!.lines.push(line);
}
const clean = (value: string) => conclusionDisplayText(value, reading.evidenceRefs);
const sections = chunks.filter(chunk => chunk.lines.join('').trim() || chunk.note).map((chunk, index) => {
const sections: Array<ConclusionSection & { refs: string[] }> = chunks.filter(chunk => chunk.lines.join('').trim() || chunk.note).map((chunk, index) => {
const cited = chunk.lines.join('\n').trim();
return { id: `conclusion-${index + 1}`, title: clean(chunk.title), markdown: clean(cited), note: clean(chunk.note), visuals: [] as AnalysisVisual[], refs: analysisTextEvidenceRefs(cited) };
return { id: `conclusion-${index + 1}`, title: clean(chunk.title), implicitTitle: chunk.implicitTitle === true, markdown: clean(cited), note: clean(chunk.note), visuals: [] as AnalysisVisual[], refs: analysisTextEvidenceRefs(cited) };
});
// The card replaces exactly one explicit comparison sentence. Other words,
// such as scope, mechanisms and limitations, remain in their original section.
+3
View File
@@ -14,6 +14,9 @@ export function originalAnalysisBody(turn?: Row): OriginalAnalysisBody | null {
const saved = text(result.answer);
// Explicitly empty/redacted answers must not be replenished from an older transcript.
if (!saved.trim()) return { answer: '', source: 'unavailable' };
// DSH publishes an evidence-checked composition. Its investigation timeline
// is a draft and must never replace a rejected/partial final composition.
if ([result.engine, turn.engine, plan.engine].includes('DSH')) return { answer: saved, source: 'saved' };
const lead = text(object(result.readingSummary).lead);
const replaced = /已取得本轮统计结果,答案整理尚未完整完成|已取得本轮统计结果,部分解释尚未完成|现有证据不足以支持本轮完整分析,已保留可核验统计结果/.test(lead || saved.slice(0, 160));
if (!replaced) return { answer: saved, source: 'saved' };
+1 -1
View File
@@ -12,7 +12,7 @@ export function longReportImageSize(rawWidth: number, rawHeight: number) {
throw new Error('报告尺寸无效,请重新打开报告。');
}
const width = Math.ceil(rawWidth), height = Math.ceil(rawHeight);
const pixelRatio = Math.min(1.5, 30000 / width, 30000 / height, Math.sqrt(48000000 / (width * height)));
const pixelRatio = Math.min(2, 30000 / width, 30000 / height, Math.sqrt(48000000 / (width * height)));
return { width, height, pixelRatio };
}
+8 -2
View File
@@ -11,6 +11,8 @@ const cleanTitle = (value: unknown): string => {
return cleaned.length > 100 ? `${cleaned.slice(0, 99).trimEnd()}…` : cleaned;
};
const genericTitles = new Set(['质量数据分析', '质量分析', '质量分析报告', '分析报告']);
function headingLineIndex(lines: string[]): number {
let fence = '';
for (let index = 0; index < lines.length; index += 1) {
@@ -65,15 +67,19 @@ export function resolveAnalysisReportTitle(
reportMarkdown: string,
period: string,
scope: string,
verifiedTopic?: string,
): string {
const generated = cleanTitle(resultTitle) || cleanTitle(turnTitle);
const generated = [cleanTitle(resultTitle), cleanTitle(turnTitle)]
.find(value => value && !genericTitles.has(value));
if (generated) return generated;
const legacyHeading = firstMarkdownH1(reportMarkdown);
if (legacyHeading) return legacyHeading;
if (legacyHeading && !genericTitles.has(legacyHeading)) return legacyHeading;
const periodLabel = cleanTitle(period)
|| cleanTitle(scope.split(/\s*[·|]\s*/).find(part => /^(?:19|20)\d{2}/.test(part)) || '');
const scopeLabel = specificScopeLabel(scope);
const anchor = [periodLabel, scopeLabel].filter(Boolean).join(' · ');
const topic = cleanTitle(verifiedTopic);
if (topic && !genericTitles.has(topic)) return cleanTitle([anchor, topic].filter(Boolean).join(' '));
return cleanTitle(anchor ? `${anchor}质量分析报告` : '质量分析报告');
}
+5 -5
View File
@@ -25,14 +25,14 @@ export function reportSnapshotIdentity(turn: Row): string {
const result = analysisSnapshotResult(turn);
const value = (key: string, fallback: unknown) => ['readingSummary', 'queryEvidenceRefs'].includes(key)
? result[key] ?? fallback : result[key] ?? turn[key] ?? fallback;
return canonical({ originalTranscript: originalTranscript(turn), answer: value('answer', ''), visuals: value('visuals', []),
return canonical({ originalTranscript: originalTranscript(turn), modelAnswer: value('modelAnswer', ''), answer: value('answer', ''), visuals: value('visuals', []),
results: value('results', []), reportMarkdown: value('reportMarkdown', ''),
reportHtml: value('reportHtml', ''), memberList: value('memberList', null),
reportTitle: value('reportTitle', ''), reportHtml: value('reportHtml', ''), memberList: value('memberList', null),
recordList: value('recordList', null), readingSummary: value('readingSummary', null), queryEvidenceRefs: value('queryEvidenceRefs', []), question: turn.question || '' });
}
export function reportSnapshotDifferences(left: Row, right: Row): string[] {
const fields = ['answer', 'visuals', 'results', 'reportMarkdown', 'reportHtml', 'memberList', 'recordList', 'readingSummary', 'queryEvidenceRefs', 'question', 'originalTranscript'];
const fields = ['modelAnswer', 'answer', 'visuals', 'results', 'reportMarkdown', 'reportTitle', 'reportHtml', 'memberList', 'recordList', 'readingSummary', 'queryEvidenceRefs', 'question', 'originalTranscript'];
return fields.filter(key => {
const value = (turn: Row) => {
if (key === 'originalTranscript') return originalTranscript(turn);
@@ -49,12 +49,12 @@ export async function authorizeAnalysisSnapshot(turn: Row): Promise<void> {
const id = String(turn.id || turn.turnId || '');
if (!id) throw new Error('分析结果尚未保存,请稍后再试。');
const current = await api.analysisTurnSnapshot(id);
if (!['COMPLETED', 'PARTIAL', 'CANCELLED'].includes(String(current.status || '').toUpperCase())) {
if (!['COMPLETED', 'PARTIAL', 'CANCELLED', 'FAILED'].includes(String(current.status || '').toUpperCase())) {
throw new Error('分析结果仍在更新,请完成后再生成报告。');
}
const differences = reportSnapshotDifferences(current, turn);
if (differences.length) {
const labels: Record<string, string> = { answer: '回答', visuals: '图表', results: '查询结果', reportMarkdown: '报告正文', reportHtml: '报告 HTML', memberList: '成员清单', recordList: '原始记录', readingSummary: '核心结论', queryEvidenceRefs: '数据依据', question: '问题', originalTranscript: '原始正文' };
const labels: Record<string, string> = { modelAnswer: '模型原文', answer: '回答', visuals: '图表', results: '查询结果', reportMarkdown: '报告正文', reportTitle: '报告标题', reportHtml: '报告 HTML', memberList: '成员清单', recordList: '原始记录', readingSummary: '核心结论', queryEvidenceRefs: '数据依据', question: '问题', originalTranscript: '原始正文' };
throw new Error(`分析结果或访问权限已变化(${differences.map(key => labels[key] || key).join('、')}),请重新打开这条分析后再导出。`);
}
}
+8 -1
View File
@@ -8,6 +8,7 @@ const object = (value: unknown): Row => value && typeof value === 'object' && !A
export function canRecoverAnalysisVisuals(turn: Row): boolean {
const result=analysisSnapshotResult(turn),plan=object(turn.plan),task=object(plan.task);
const state=String(result.visualState||'');
if (task.aggregateSelection && state === 'not_requested') return false;
const status=String(turn.status||result.status||'').toUpperCase();
const planned=Array.isArray(task.queryPlan)&&task.queryPlan.some(raw=>{
const node=object(raw);return ['ranking','trend','defects'].includes(String(node.purpose))&&node.visualPreference!=='none';
@@ -21,11 +22,12 @@ export function canRecoverAnalysisVisuals(turn: Row): boolean {
}
/** A late chart recovery can replace only presentation belonging to this exact saved execution. */
export function useAnalysisVisualRecovery(source: Row,onUnauthorized:(error:unknown)=>boolean) {
export function useAnalysisVisualRecovery(source: Row,onUnauthorized:(error:unknown)=>boolean, auto = false) {
const plan=object(source.plan);
const key=JSON.stringify([source.id||source.turnId,plan.attemptId,plan.executionId,plan.revision,reportSnapshotIdentity(source)]);
const identity=useRef(key);identity.current=key;
const generation=useRef(0),pending=useRef(false);
const attempted=useRef('');
const [recovered,setRecovered]=useState<{key:string;turn:Row}|null>(null);
const [recovering,setRecovering]=useState(false),[error,setError]=useState('');
useEffect(()=>{
@@ -51,5 +53,10 @@ export function useAnalysisVisualRecovery(source: Row,onUnauthorized:(error:unkn
}
},[source,key,onUnauthorized]);
const turn=recovered?.key===key?recovered.turn:source;
useEffect(()=>{
if(!auto||attempted.current===key||!canRecoverAnalysisVisuals(turn))return;
attempted.current=key;
void recover();
},[auto,key,recover,turn]);
return {turn,recover,recovering,error,available:canRecoverAnalysisVisuals(turn)};
}
+62 -32
View File
@@ -63,7 +63,7 @@ export interface VisualChartTheme {
export const MAX_ANALYSIS_VISUALS = 12;
export const MAX_VISUAL_BYTES = 256 * 1024;
export const MAX_VISUAL_CATEGORIES = 36;
export const MAX_VISUAL_CATEGORIES = 100;
export const MAX_VISUAL_SERIES = 4;
const UNIT_VALUES = new Set<AnalysisVisualUnit>(['ratio', 'kg', 'pp', 'count']);
@@ -431,7 +431,7 @@ function visualSemanticIssue(visual: AnalysisVisual): string | undefined {
if (visual.unit !== 'kg' || !combined && !/^(?:black|bright)_(?:total|scrap)_weight$/.test(visual.metric)
|| !combined && (!visual.stage || !visual.metric.startsWith(`${visual.stage}_`)) || visual.comparisonPeriod
|| !['product','department','group'].includes(visual.dimension || '')
|| visual.categories.length < 1 || visual.categories.length > 10 || visual.series.length !== 1
|| visual.categories.length < 1 || visual.categories.length > 100 || visual.series.length !== 1
|| visual.coverage.returnedRows !== visual.categories.length || typeof total !== 'number' || !(total > 0)
|| values.some((v,i) => v === null || !Number.isFinite(v) || v < 0 || i > 0 && v > (values[i-1] as number))) return '分组重量柏拉图缺少全范围总量或有效排名';
if (values.reduce<number>((sum,v)=>sum+(v as number),0) > total + Math.max(0.00001,total*1e-10)) return 'Top重量不能大于全范围总量';
@@ -1016,10 +1016,18 @@ export interface AnalysisVisualExportOption {
}
/** Add static report context around the complete, unfiltered snapshot for PNG export. */
export type AnalysisVisualRenderContext = 'standalone' | 'report';
export type AnalysisVisualRenderContext = 'standalone' | 'report' | 'agent-document';
export function buildAnalysisVisualExportOption(visual: AnalysisVisual, width = 1280, context: AnalysisVisualRenderContext = 'standalone'): AnalysisVisualExportOption {
const reportMode = context === 'report';
const reportMode = context !== 'standalone';
const editorial = context === 'agent-document';
const rateTrend = editorial && visual.unit === 'ratio' && ['line', 'area'].includes(visual.type);
const values = rateTrend ? visual.series.flatMap(series => series.values.flatMap(value => value == null ? [] : [value * 100])) : [];
const low = values.length ? Math.min(...values) : 0;
const high = values.length ? Math.max(...values) : 100;
const step = [0.1, 0.25, 0.5, 1, 2, 5, 10, 20, 50, 100].find(candidate => candidate * 5 >= high - low) || 100;
const trendMin = Math.max(0, Math.floor((low - step / 3) / step) * step);
const trendMax = Math.ceil((high + step / 3) / step) * step;
const titleLines = reportMode ? [] : wrapLines(visual.title, 34, 3);
const headerParts = reportMode ? [] : [
visual.subtitle,
@@ -1050,7 +1058,9 @@ export function buildAnalysisVisualExportOption(visual: AnalysisVisual, width =
const allScopeWeight = visual.type === 'pareto' && visual.coverage.shareBasis === 'all_scope_weight';
const rankingLabelWidth = Math.max(16, (width - 174) / Math.max(1, visual.categories.length) - 8);
const wrappedCategories = visual.categories.map((_category, index) => allScopeWeight
const monthAxis = editorial && ['line', 'area'].includes(visual.type) && visual.categories.every(category => /^\d{4}-\d{2}$/.test(category.label))
&& new Set(visual.categories.map(category => category.label.slice(0, 4))).size === 1;
const wrappedCategories = visual.categories.map((_category, index) => monthAxis ? [visual.categories[index].label.slice(-2)] : allScopeWeight
? wrapAxisLabel(visualCategoryLabel(visual, index), rankingLabelWidth, reportMode ? 14 : 10)
: wrapLines(visualCategoryLabel(visual, index), 14));
const categoryLabelHeight = wrappedCategories.reduce((total, lines) => total + Math.max(28, lines.length * 14 + 8), 0);
@@ -1064,7 +1074,7 @@ export function buildAnalysisVisualExportOption(visual: AnalysisVisual, width =
+ Math.cos(reportRotation * Math.PI / 180) * maxCategoryLines * 18) + 22;
const reportLegendHeight = visual.series.length > 1 ? 30 : 0;
const reportPlotHeight = 230;
const chartHeight = visual.type === 'donut' ? (reportMode ? Math.max(390, 290 + maxCategoryLines * 20) : Math.max(600, 300 + maxCategoryLines * 20))
const chartHeight = visual.type === 'donut' ? (editorial ? 320 : reportMode ? Math.max(390, 290 + maxCategoryLines * 20) : Math.max(600, 300 + maxCategoryLines * 20))
: visual.type === 'waterfall' ? (reportMode ? 300 : 480)
: visual.type === 'heatmap' ? Math.max(reportMode ? 180 : 240, visual.series.length * (reportMode ? 62 : 90))
: visual.type === 'pareto' ? (allScopeWeight ? 330 + maxCategoryLines * (reportMode ? 18 : 14) : reportMode ? Math.max(300, 170 + maxCategoryLines * 18) : Math.max(480, categoryLabelHeight))
@@ -1072,7 +1082,10 @@ export function buildAnalysisVisualExportOption(visual: AnalysisVisual, width =
: reportCartesian ? reportPlotHeight + reportLabelHeight + reportLegendHeight
: reportMode ? visual.type === 'bar' ? Math.max(230, categoryLabelHeight * 1.3) : Math.max(230, 165 + maxCategoryLines * 20) : Math.max(480, categoryLabelHeight);
const height = chartTop + chartHeight + chartBottom;
const base = buildAnalysisVisualOption(visual, { ink: '#263c5a', mutedInk: '#65748b', line: '#dfe5ef', surface: '#ffffff' });
const base = buildAnalysisVisualOption(visual, editorial
? { ink: '#17202c', mutedInk: '#596473', line: '#d5dbe3', surface: '#fff',
colors: rateTrend && visual.series.length > 1 ? ['#073fae', '#00a477'] : visual.stage === 'bright' ? ['#00a477', '#0750d9', '#8ca4c5'] : ['#0750d9', '#00a477', '#8ca4c5', '#566579'] }
: { ink: '#263c5a', mutedInk: '#65748b', line: '#dfe5ef', surface: '#ffffff' });
const categories = wrappedCategories.map(lines => lines.join('\n'));
const donutShares = visual.type === 'donut' ? visualDonutShares(visual) : [];
const valueAxisLabel = (value: number) => visual.unit === 'ratio'
@@ -1081,7 +1094,7 @@ export function buildAnalysisVisualExportOption(visual: AnalysisVisual, width =
const allSeriesSelected = Object.fromEntries(visual.series.map(series => [plainRichText(series.label), true]));
const legendOption = visual.type === 'donut'
? {
show: true,
show: !editorial,
selectedMode: false,
type: 'scroll' as const,
orient: 'horizontal' as const,
@@ -1143,8 +1156,8 @@ export function buildAnalysisVisualExportOption(visual: AnalysisVisual, width =
graphic: {
elements: [
...(donutShares.length ? [{
type: 'text', left: 'center', top: chartTop + chartHeight * 0.39 - 22, silent: true,
style: { text: `所列类别合计\n${formatChartValue(donutShares.reduce((sum, item) => sum + item.valueKg, 0), 'kg')}`, textAlign: 'center', fill: '#263c5a', font: '600 16px sans-serif', lineHeight: 25 },
type: 'text', left: 'center', top: chartTop + chartHeight * (editorial ? 0.45 : 0.39) - 22, silent: true,
style: { text: `所列类别合计\n${formatChartValue(donutShares.reduce((sum, item) => sum + item.valueKg, 0), 'kg')}`, textAlign: 'center', fill: '#263c5a', font: editorial ? '600 13px sans-serif' : '600 16px sans-serif', lineHeight: editorial ? 21 : 25 },
}] : []),
...(footerLines.length ? [{
type: 'text', left: 56, top: chartTop + chartHeight + 14, silent: true,
@@ -1154,10 +1167,10 @@ export function buildAnalysisVisualExportOption(visual: AnalysisVisual, width =
},
series: [{
...(Array.isArray((base as any).series) ? (base as any).series[0] : {}),
center: [width / 2, chartTop + chartHeight * 0.39],
radius: ['21%', '34%'],
center: [width / 2, chartTop + chartHeight * (editorial ? 0.45 : 0.39)],
radius: editorial ? ['34%', '56%'] : ['21%', '34%'],
label: {
show: true, position: 'outside', alignTo: 'labelLine', edgeDistance: 26, width: 235,
show: true, position: 'outside', alignTo: editorial ? 'edge' : 'labelLine', edgeDistance: editorial ? 16 : 26, width: editorial ? 160 : 235,
overflow: 'break', lineHeight: 17, color: '#263c5a', fontSize: 11,
formatter: (params: { dataIndex?: number }) => {
const index = Number.isInteger(params?.dataIndex) ? params.dataIndex as number : -1;
@@ -1227,10 +1240,12 @@ export function buildAnalysisVisualExportOption(visual: AnalysisVisual, width =
? {
xAxis: {
type: 'value',
min: visual.unit === 'ratio' ? 0 : undefined,
max: ratioAxisMax(visual),
min: rateTrend ? trendMin : visual.unit === 'ratio' ? 0 : undefined,
max: rateTrend ? trendMax : ratioAxisMax(visual),
interval: rateTrend ? step : undefined,
scale: visual.unit !== 'ratio' ? false : undefined,
axisLabel: { color: '#65748b', formatter: valueAxisLabel },
splitNumber: 3,
axisLabel: { color: '#65748b', formatter: valueAxisLabel, hideOverlap: true },
axisLine: { show: false },
splitLine: { lineStyle: { color: '#dfe5ef', type: 'dashed' } },
},
@@ -1255,8 +1270,9 @@ export function buildAnalysisVisualExportOption(visual: AnalysisVisual, width =
},
yAxis: {
type: 'value',
min: visual.unit === 'ratio' ? 0 : undefined,
max: ratioAxisMax(visual),
min: rateTrend ? trendMin : visual.unit === 'ratio' ? 0 : undefined,
max: rateTrend ? trendMax : ratioAxisMax(visual),
interval: rateTrend ? step : undefined,
scale: visual.unit !== 'ratio' ? false : undefined,
axisLabel: { color: '#65748b', formatter: valueAxisLabel },
axisLine: { show: false },
@@ -1269,6 +1285,15 @@ export function buildAnalysisVisualExportOption(visual: AnalysisVisual, width =
: { left: 64, right: 42, top: chartTop, bottom: chartBottom + (visual.type === 'column' ? 80 : 68), containLabel: true },
}),
};
if (rateTrend && visual.series.length === 1) {
option.series = ((option.series || []) as any[]).map(series => ({ ...series,
label: { show: true, position: 'top', color: '#344155', fontSize: 12,
formatter: ({ dataIndex }: { dataIndex: number }) => {
const value = visual.series[0].values[dataIndex];
return value == null ? '' : `${(value * 100).toFixed(2)}%`;
} }, areaStyle: { color: '#eef3fc', opacity: 1 },
}));
}
if (reportMode) {
// 图片按报告正文列宽显示,确保缩放后的标签仍然可读。
const enlargeText = (value: unknown): void => {
@@ -1425,15 +1450,6 @@ function throwIfAborted(signal?: AbortSignal): void {
if (signal?.aborted) throw new DOMException('图表导出已取消', 'AbortError');
}
function waitForFrame(signal?: AbortSignal): Promise<void> {
return new Promise((resolve, reject) => {
throwIfAborted(signal);
const frame = requestAnimationFrame(() => { signal?.removeEventListener('abort', abort); resolve(); });
const abort = () => { cancelAnimationFrame(frame); reject(new DOMException('图表导出已取消', 'AbortError')); };
signal?.addEventListener('abort', abort, { once: true });
});
}
function waitForFont(signal?: AbortSignal): Promise<void> {
if (!('fonts' in document)) return Promise.resolve();
return new Promise((resolve, reject) => {
@@ -1485,14 +1501,16 @@ function svgToPng(svg: string, width: number, height: number, signal?: AbortSign
});
}
/** Render a snapshot independently of any visible chart instance or current legend state. */
export async function renderVisualPng(visualOrUnknown: AnalysisVisual | unknown, signal?: AbortSignal, context: AnalysisVisualRenderContext = 'standalone'): Promise<string> {
/** Render a vector snapshot independently of the visible chart and browser animation frames. */
async function renderVisualSnapshot(visualOrUnknown: AnalysisVisual | unknown, signal?: AbortSignal, context: AnalysisVisualRenderContext = 'standalone', exportWidth?: number) {
const parsed = parseAnalysisVisuals([visualOrUnknown]);
const visual = parsed.visuals[0];
if (!visual || !visual.chartable) throw new Error(visual?.chartIssue || parsed.issues[0] || '没有可导出的图表数据');
if (typeof document === 'undefined') throw new Error('图表图片只能在浏览器中生成');
throwIfAborted(signal);
const { option, width, height } = buildAnalysisVisualExportOption(visual, context === 'report' ? 900 : 1280, context);
const editorialTrend = context === 'agent-document' && visual.unit === 'ratio' && ['line', 'area'].includes(visual.type);
const plotWidth = exportWidth ?? (editorialTrend ? visual.series.length > 1 ? 420 : 660 : context !== 'standalone' ? 900 : 1280);
const { option, width, height } = buildAnalysisVisualExportOption(visual, plotWidth, context);
const node = document.createElement('div');
Object.assign(node.style, { position: 'fixed', left: '-10000px', top: '0', width: `${width}px`, height: `${height}px`, background: '#ffffff', color: '#263c5a', pointerEvents: 'none' });
document.body.appendChild(node);
@@ -1506,12 +1524,24 @@ export async function renderVisualPng(visualOrUnknown: AnalysisVisual | unknown,
const finished = waitForChartFinished(chart, signal);
chart.setOption(option, { notMerge: true, lazyUpdate: false });
await finished;
await waitForFrame(signal);
throwIfAborted(signal);
const svg = chart.renderToSVGString({ useViewBox: true });
return await svgToPng(svg, width, height, signal);
return { svg, width, height };
} finally {
chart?.dispose();
node.remove();
}
}
/** Keep vector text and geometry intact in report previews and portable HTML. */
export async function renderVisualSvg(visual: AnalysisVisual | unknown, signal?: AbortSignal,
context: AnalysisVisualRenderContext = 'report', exportWidth?: number): Promise<string> {
const { svg } = await renderVisualSnapshot(visual, signal, context, exportWidth);
return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
}
export async function renderVisualPng(visual: AnalysisVisual | unknown, signal?: AbortSignal,
context: AnalysisVisualRenderContext = 'standalone'): Promise<string> {
const { svg, width, height } = await renderVisualSnapshot(visual, signal, context);
return svgToPng(svg, width, height, signal);
}
+7
View File
@@ -506,6 +506,10 @@ export const api = {
analysisSession(id: string) {
return request<Record<string, unknown>>(`/api/analysis/sessions/${encodeURIComponent(id)}`);
},
analysisSessionPage(id: string, before?: string, signal?: AbortSignal) {
const cursor = before ? `?before=${encodeURIComponent(before)}` : '';
return request<Record<string, unknown>>(`/api/analysis/sessions/${encodeURIComponent(id)}/history${cursor}`, { signal });
},
deleteAnalysisSession(id: string) {
return mutate<{ deleted: boolean; sessionId: string }>(`/api/analysis/sessions/${encodeURIComponent(id)}`, undefined, 'DELETE');
},
@@ -545,6 +549,9 @@ export const api = {
analysisTurnEvents(id: string, options: { signal?: AbortSignal; lastEventId?: string; onEvent: (event: StreamEvent) => void }) {
return readEventStream(`/api/analysis/turns/${encodeURIComponent(id)}/events`, options);
},
analysisSessionFollow(id: string, options: { signal?: AbortSignal; onEvent: (event: StreamEvent) => void }) {
return readEventStream(`/api/analysis/sessions/${encodeURIComponent(id)}/follow`, options);
},
cancelAnalysisTurn(id: string, reason?: string) {
return mutate<Record<string, unknown>>(`/api/analysis/turns/${encodeURIComponent(id)}/cancel`, reason ? { reason } : {});
},
@@ -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 { buildAgentReportLayout, agentReportPrimary, agentReportSupplementary } from '../src/agent/agentReportLayout.ts';
import { stripDuplicateFirstMarkdownH1 } from '../src/analysisReportTitle.ts';
import { tableTextAlignment } from '../src/tableTextAlignment.ts';
import { sanitizeAnalysisDisplayText } from '../src/analysisDisplayText.ts';
import { analysisEvidenceParts } from '../src/analysisEvidenceRefs.ts';
function load(file, exported, bindings) {
const source=fs.readFileSync(new URL(file,import.meta.url),'utf8').replace(/^import .*;\n/gm,'').replaceAll('export function ','function ').replaceAll('export async function ','async function ');
return new Function(...Object.keys(bindings),ts.transpileModule(source+'\nreturn '+exported+';', {compilerOptions:{target:ts.ScriptTarget.ES2022,jsx:ts.JsxEmit.React}}).outputText.replace(/^export\s*\{\s*\};?$/gm,''))(...Object.values(bindings));
}
const AiMarkdown=load('../src/AiMarkdown.tsx','AiMarkdown',{React,tableTextAlignment,sanitizeAnalysisDisplayText,analysisEvidenceParts});
const figures=[{id:'trend',title:'月度趋势',type:'line',unit:'ratio',metric:'composite_rate',sectionKey:'trend',scope:{},categories:[],series:[],evidenceRefs:[]},
{id:'scrap',title:'报废结构',type:'bar',unit:'kg',metric:'scrap_weight',sectionKey:'category',scope:{},categories:[],series:[],evidenceRefs:[]}];
let images=[];
const Empty=()=>null;
const Document=load('../src/agent/AgentDeliverable.tsx','AgentDeliverable',{
React,useLayoutEffect:()=>{},useRef:value=>({current:value}),useState:value=>[value,()=>{}],
Alert:Empty,Spin:Empty,DownloadOutlined:Empty,Button:Empty,Modal:({children})=>React.createElement('main',null,children),
AnalysisMemberListReport:Empty,AnalysisRecordListReport:Empty,AiMarkdown,
ReportVisualFigure:({visual,image})=>image?.svg?React.createElement('figure',{'data-chart':visual.id},visual.title):React.createElement('table',{'data-fallback':visual.id},React.createElement('tbody',null,React.createElement('tr',null,React.createElement('td',null,visual.title)))),
reportVisualImageSource:image=>image?.svg||'',reportVisuals:()=>figures,
useReportVisualImages:()=>({authorized:true,loading:false,images}),analysisSnapshotResult:turn=>turn.result,
reportSnapshotIdentity:()=>'',analysisScopeText:()=>'',stripDuplicateFirstMarkdownH1,buildAgentReportLayout,agentReportPrimary,agentReportSupplementary,
captureReportLongImage:()=>{},downloadAuthorizedReport:()=>{},documentCss:'',
});
const answer='# 原始报告\n\n原始导读。\n\n## 月度趋势\n\n原始分析。\n\n| 月份 | 值 |\n|---|---|\n| 10月 | 95.46% |\n\n## 报废大类\n\n原始说明。';
function render() {return renderToStaticMarkup(React.createElement(Document,{turn:{status:'COMPLETED',question:'生成报告',result:{modelAnswer:answer,answer:'此替代回答不应显示'}},onClose:()=>{}}));}
test('every report figure precedes the original detail table, appears once, and leaves the source intact',()=>{
images=figures.map(v=>({id:v.id,svg:'data:image/svg+xml,test'}));
const html=render();
for(const id of ['trend','scrap']) {
assert.equal((html.match(new RegExp('data-chart="'+id+'"','g'))||[]).length,1);
assert.ok(html.indexOf('data-chart="'+id+'"')<html.indexOf('<table>'));
}
assert.ok(html.indexOf('原始分析。')<html.indexOf('原始说明。'));
assert.equal((html.match(/原始导读。/g)||[]).length,1);
assert.match(html,/95.46%/);assert.doesNotMatch(html,/此替代回答/);
});
test('a missing image is omitted while the healthy figure and original answer remain',()=>{
images=[{id:'trend',svg:'data:image/svg+xml,test'},{id:'scrap',failed:true}];
const html=render();
assert.equal((html.match(/data-chart=/g)||[]).length,1);
assert.doesNotMatch(html,/data-fallback|重试|暂不可用/);
assert.ok(html.indexOf('data-chart="trend"')<html.indexOf('<table>'));
assert.match(html,/原始说明。/);
});
test('no image yields no empty gallery and all original data remains accessible',()=>{
images=[];const html=render();assert.doesNotMatch(html,/agent-document-overview/);assert.match(html,/95.46%/);
assert.equal((html.match(/data-fallback=/g)||[]).length,0);
});
test('the real report figure quietly omits unavailable images',()=>{
const Figure=load('../src/AnalysisReportVisuals.tsx','ReportVisualFigure',{React,visualPeriodSummary:()=>'',visualScopeSummary:()=>''});
for(const image of [undefined,{id:'trend',failed:true}]) {
assert.equal(renderToStaticMarkup(React.createElement(Figure,{visual:{...figures[0],chartable:true},image,quiet:true})), '');
}
const image={id:'trend',svg:'data:image/svg+xml;charset=utf-8,%3Csvg%2F%3E'};
const html=renderToStaticMarkup(React.createElement(Figure,{visual:{...figures[0],chartable:true,coverage:{truncated:false}},image,quiet:true}));
assert.match(html,/<figure/);assert.match(html,/<img/);assert.doesNotMatch(html,/q-partial|暂不可用/);
});
test('ordinary AI replies never become a report even when a legacy report field exists',()=>{
const authored=load('../src/agent/AgentDeliverable.tsx','authoredReport',{analysisSnapshotResult:turn=>turn.result,stripDuplicateFirstMarkdownH1});
for(const question of ['2026年8月综合合格率是多少?','一句话回答,不生成报告。','对比9月10月,简短回答,不需要生成报告。','沿用上面,只回答这两项。']) {
assert.equal(authored({status:'COMPLETED',question,result:{modelAnswer:answer,reportMarkdown:answer}}),null);
}
assert.ok(authored({status:'COMPLETED',question:'生成亮片报废结构专题报告',result:{modelAnswer:answer}}));
assert.ok(authored({status:'COMPLETED',question:'生成质量异常诊断简报',result:{modelAnswer:answer}}));
});
@@ -0,0 +1,42 @@
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 { tableTextAlignment } from '../src/tableTextAlignment.ts';
import { sanitizeAnalysisDisplayText } from '../src/analysisDisplayText.ts';
import { analysisEvidenceParts } from '../src/analysisEvidenceRefs.ts';
const source = fs.readFileSync(new URL('../src/AiMarkdown.tsx', import.meta.url), 'utf8')
.replace(/^import .*;$/gm, '').replace('export function AiMarkdown', 'function AiMarkdown');
const Markdown = new Function('React', 'tableTextAlignment', 'sanitizeAnalysisDisplayText', 'analysisEvidenceParts',
ts.transpileModule(`${source}\nreturn AiMarkdown;`, { compilerOptions: { target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.React } }).outputText
)(React, tableTextAlignment, sanitizeAnalysisDisplayText, analysisEvidenceParts);
test('original answers preserve wording, table headers, headings and escaped markup', () => {
const answer = '## 模型原始回答\n\n数学说明保留。\n\n| 月份 | 原始值 |\n| --- | --- |\n| 8月 | 98.35% |\n\n<script>alert(1)</script>';
const html = renderToStaticMarkup(React.createElement(Markdown, { content: answer, preserveSource: true }));
assert.match(html, /<h2>模型原始回答<\/h2>/);
assert.match(html, /数学说明保留/);
assert.match(html, /&lt;script&gt;alert\(1\)&lt;\/script&gt;/);
assert.doesNotMatch(html, /<script|序号|核心结论/);
assert.equal((html.match(/<th(?:>| )/g) || []).length, 2);
});
test('report layout preserves original Markdown instead of converting bold prose into chapters', async () => {
const { buildAgentReportLayout } = await import('../src/agent/agentReportLayout.ts');
const text = '**原始小节**\n\n原始正文。\n\n1. 原始项目。';
const report = buildAgentReportLayout(text, []);
assert.equal(report.sections.map(section => section.markdown).join('\n\n'), text);
});
test('original Markdown rules and quotes render semantically without altering their words or tables', () => {
const answer = '首句。\n---\n> **范围:**2026年10月\n> 保留 <script> 原文\n\n| 对象 | 值 |\n| --- | --- |\n| 总体 | 95.46% |\n\n***\n\n末句。';
const html = renderToStaticMarkup(React.createElement(Markdown, { content: answer, preserveSource: true }));
assert.equal((html.match(/<hr\/>/g) || []).length, 2);
assert.match(html, /<blockquote><strong>范围:<\/strong>2026年10月<br\/>保留 &lt;script&gt; 原文<\/blockquote>/);
assert.equal((html.match(/<table>/g) || []).length, 1);
assert.match(html, /首句。/); assert.match(html, /末句。/);
assert.doesNotMatch(html, /<script>|序号/);
});
@@ -0,0 +1,29 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import ts from 'typescript';
const source = fs.readFileSync(new URL('../src/agent/AgentDeliverable.tsx', import.meta.url), 'utf8');
const start = source.indexOf('export function reportRequested');
const end = source.indexOf('export function AgentDeliverable(');
const code = ts.transpileModule(source.slice(start, end).replaceAll('export function', 'function'), {
compilerOptions: { target: ts.ScriptTarget.ES2022 },
}).outputText;
const authoredReport = new Function('analysisSnapshotResult', 'stripDuplicateFirstMarkdownH1', code + '\nreturn authoredReport;')(
turn => turn.result || turn, text => text,
);
test('a restored clarification answer retains the explicitly requested report and raw body', () => {
const original = '# 排名报告\n\n模型原始正文';
const turn = { status: 'COMPLETED', question: '黑片or亮片', modelAnswer: original, reportMarkdown: original,
task: { aggregateSelection: { requestQuestion: '筛选10月合格率最低Top20产品,并生成报告' } } };
assert.equal(authoredReport(turn).markdown, original);
assert.equal(authoredReport({ ...turn, result: { modelAnswer: original, reportMarkdown: original, task: turn.task } }).markdown, original);
});
test('ordinary replies and new requests without an authored report cannot inherit a report card', () => {
const turn = { status: 'COMPLETED', question: '只回答名单,不生成报告', modelAnswer: '原始回答',
task: { aggregateSelection: { requestQuestion: '此前要求生成报告' } } };
assert.equal(authoredReport(turn), null);
assert.equal(authoredReport({ ...turn, task: {}, reportMarkdown: '原始回答' }), null);
});
@@ -0,0 +1,196 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { agentReportVisuals, buildAgentReportLayout, agentReportPrimary, agentReportChartWidth, agentReportSupplementary } from '../src/agent/agentReportLayout.ts';
import { parseAnalysisVisuals } from '../src/analysisVisualsModel.ts';
const trend = (metric, scope = {}, values = [.9515, .9529, .9546]) => ({
id: metric, metric, type: 'line', unit: 'ratio', sectionKey: 'trend',
title: metric, subtitle: '', period: { year: 2026, monthStart: 8, monthEnd: 10 },
originTurnId: 'turn-layout', requiredFields: [], coverage: { totalRows: 3, returnedRows: 3, truncated: false },
scope: { year: 2026, monthStart: 8, monthEnd: 10, ...scope },
categories: ['2026-08', '2026-09', '2026-10'].map(key => ({ key, label: key })),
series: [{ key: metric, label: metric, values }], evidenceRefs: [],
});
test('an authorized period aggregate populates the header and the report keeps authored chapter order', () => {
const markdown = `9月需要关注。\n\n## 趋势与阶段对照\n\n本期走势。\n\n## 月度明细\n\n| 月份 | 综合合格率 | 黑片合格率 | 亮片合格率 |\n|---|---|---|---|\n| 2026-08 | 95.15% | 97.31% | 97.77% |\n| 期间汇总 | 95.35% | 97.57% | 97.73% |`;
const result = buildAgentReportLayout(markdown, [trend('composite_rate'), trend('black_rate', { stage: 'black' }), trend('bright_rate', { stage: 'bright' })]);
assert.equal(result.lead, '9月需要关注。');
assert.deepEqual(result.sections.map(section => section.label), ['趋势与阶段对照', '月度明细']);
assert.deepEqual(result.metrics.map(metric => metric.value), ['95.35', '97.57', '97.73']);
assert.equal(result.sections[0].charts.paired, true);
assert.equal(result.sections[0].charts.stats[0].value, '+0.31');
});
test('unmatched chart scopes cannot be paired and missing months cannot produce trend summaries', () => {
const monthly = trend('composite_rate', {}, [.9515, null, .9546]);
const result = buildAgentReportLayout('## 月度趋势\n\n按月观察。', [monthly, trend('black_rate', { department: '另一个范围' })]);
assert.equal(result.sections[0].charts.paired, false);
assert.deepEqual(result.sections[0].charts.stats, []);
assert.deepEqual(result.metrics, []);
});
test('two-month comparison uses unrounded signed values from the bound figure', () => {
const visual = { ...trend('composite_rate'), type: 'column', sectionKey: 'overview', comparisonPeriod: { year: 2026, month: 9 },
categories: [{ key: 'comparison', label: '2026-09' }, { key: 'current', label: '2026-10' }],
series: [{ key: 'composite_rate', values: [.9803797366305572, .977442975471237] }],
};
const result = buildAgentReportLayout('下降0.29个百分点。\n\n## 口径说明\n\n同范围比较。', [visual]);
assert.equal(result.lead, '下降0.29个百分点。');
assert.deepEqual(result.metrics.map(metric => metric.value), ['98.04', '97.74', '-0.29']);
});
test('a checklist keeps the requested chapters and does not acquire invented metrics or charts', () => {
const markdown = '先核对计量记录。\n\n## 现场核查\n\n1. 核对工位。\n2. 核对批次。\n\n## 待证实\n\n待核实现场。';
const result = buildAgentReportLayout(markdown, []);
assert.deepEqual(result.sections.map(section => section.label), ['现场核查', '待证实']);
assert.match(result.sections[0].markdown, /1\. 核对工位。\n2\. 核对批次。/);
assert.ok(result.sections.every(section => section.charts.figures.length === 0));
assert.deepEqual(result.metrics, []);
});
test('the live model stage-row aggregate table produces the same three header metrics without rewriting its text', () => {
const markdown = `## 二、期间汇总正式指标(公司总体,1—10月聚合值)
| 阶段 | 合格率 | 报废率 | 投入重量 |
|---|---:|---:|---:|
| 综合 | **95.35%** | — | — |
| 黑片 | 97.57% | 2.46% | 12,129,113.00 kg |
| 亮片 | 97.73% | 2.27% | 12,702,288.25 kg |`;
const result = buildAgentReportLayout(markdown, []);
assert.deepEqual(result.metrics.map(({ label, value }) => ({ label, value })), [
{ label: '综合合格率', value: '95.35' }, { label: '黑片合格率', value: '97.57' }, { label: '亮片合格率', value: '97.73' },
]);
assert.equal(result.sections.map(section => section.markdown).join(''), markdown);
});
test('a stage table for a single month cannot be mistaken for the period aggregate', () => {
const markdown = `## 5月阶段对照
| 阶段 | 合格率 |
|---|---:|
| 综合 | 95.12% |
| 黑片 | 97.31% |
| 亮片 | 97.75% |`;
assert.deepEqual(buildAgentReportLayout(markdown, []).metrics, []);
});
test('a model-authored aggregate caption binds its following indicator-value table', () => {
const markdown = '## 核心发现\n\n**期间汇总正式合格率**\n\n| 指标 | 正式值 |\n|---|---|\n| 综合合格率 | 95.35% |\n| 黑片合格率 | 97.57% |\n| 亮片合格率 | 97.73% |';
assert.deepEqual(buildAgentReportLayout(markdown, []).metrics.map(metric => metric.value), ['95.35', '97.57', '97.73']);
});
test('an explicit period lead can present all three authored rates without a duplicate table', () => {
const markdown = '2026年1—10月期间,综合合格率为 **95.35%**,黑片合格率为 **97.57%**,亮片合格率为 **97.73%**。\n\n## 趋势与阶段对照\n\n5月需要关注。';
const layout = buildAgentReportLayout(markdown, []);
assert.deepEqual(layout.metrics.map(metric => metric.value), ['95.35', '97.57', '97.73']);
assert.equal(layout.lead, markdown.split('\n\n')[0]);
});
test('the two stage trends share one report panel with their original tenors and scopes preserved', () => {
const inputs = [trend('composite_rate'), { ...trend('black_rate', { stage: 'black' }), chartable: true, requiredFields: [] },
{ ...trend('bright_rate', { stage: 'bright' }), chartable: true, requiredFields: [] }];
const before = JSON.stringify(inputs);
const panels = agentReportVisuals(inputs);
assert.equal(panels.length, 2);
assert.deepEqual(panels[1].series.map(series => series.key), ['black_rate', 'bright_rate']);
assert.deepEqual(panels[1].series[1].values, inputs[2].series[0].values);
assert.equal(parseAnalysisVisuals([panels[1]], 1).visuals[0]?.chartable, true);
assert.equal(JSON.stringify(inputs), before);
assert.equal(buildAgentReportLayout('## 趋势与阶段对照', panels).sections[0].charts.paired, true);
const mismatched = { ...inputs[2], scope: { ...inputs[2].scope, department: '其他产业部' } };
assert.equal(agentReportVisuals([inputs[1], mismatched]).length, 2);
});
test('a bold-prefixed original introduction becomes the lead exactly once', () => {
const lead = '**主要发现:**2026年10月全公司综合合格率为 **95.46%**,黑片合格率97.54%,亮片合格率97.86%;产业部差异见下表。';
const body = '## 产业部差异\n\n保留原文。\n\n---\n\n## 报废结构\n\n原始表格。';
const result = buildAgentReportLayout(`${lead}\n\n${body}`, []);
assert.equal(result.lead, lead);
assert.equal(result.sections.map(section => section.markdown.trim()).join('\n\n'), body);
assert.deepEqual(result.metrics.map(metric => metric.value), ['95.46', '97.54', '97.86']);
});
test('company headline metrics never borrow a later department or infer absent stage rates', () => {
for (const text of [
'全公司综合合格率95.46%;产业部黑片合格率97.54%,亮片合格率97.86%。',
'全公司产业部对比:综合合格率95.46%,黑片合格率97.54%,亮片合格率97.86%。',
'综合合格率95.46%,黑片合格率97.54%,亮片合格率97.86%。',
]) assert.deepEqual(buildAgentReportLayout(text, []).metrics, []);
});
test('an explicit overall stage-column table supplies cards without rewriting shorthand prose', () => {
const lead = '期间综合合格率95.35%,黑片、亮片合格率分别为97.57%和97.73%。';
const body = '## 一、总体表现\n\n综合合格率为95.35%。\n\n| 指标 | 黑片 | 亮片 |\n|---|---:|---:|\n| 合格率 | 97.57% | 97.73% |\n| 剔除本部报废后合格率 | — | 97.81% |';
const result = buildAgentReportLayout(lead + '\n\n' + body, []);
assert.deepEqual(result.metrics.map(metric => metric.value), ['95.35', '97.57', '97.73']);
assert.equal(result.lead, lead);
assert.equal(result.sections[0].markdown, body);
assert.deepEqual(buildAgentReportLayout(body.replace('总体表现', '5月对照'), []).metrics, []);
assert.deepEqual(buildAgentReportLayout(body.replace('综合合格率为95.35%。', '综合合格率为95.35%,综合合格率为95.46%。'), []).metrics, []);
});
test('the live stage-row report retains its three stated metrics and authored body', () => {
const text='**导读:**全公司综合合格率95.35%,黑片97.57%、亮片97.73%。\n\n## 一、总体表现\n\n期间正式综合合格率为95.35%。\n\n| 阶段 | 投入重量 | 合格率 |\n|---|---:|---:|\n| 黑片 | 100 | 97.57% |\n| 亮片 | 200 | 97.73% |';
const layout=buildAgentReportLayout(text,[]);
assert.deepEqual(layout.metrics.map(metric=>metric.value),['95.35','97.57','97.73']);
assert.equal(layout.lead+'\n\n'+layout.sections[0].markdown,text);
});
test('the primary chart uses an existing composite trend or the available stages without inventing a series', () => {
const stages={...trend('black_rate'),id:'stages',series:[{key:'black_rate',values:[.97,.98,.97]},{key:'bright_rate',values:[.98,.97,.98]}]};
const overall=trend('composite_rate'),before=JSON.stringify([stages,overall]);
assert.equal(agentReportPrimary([stages,overall]),overall);
assert.equal(agentReportPrimary([stages]),stages);
assert.equal(agentReportChartWidth(overall,[stages,overall]),660);
assert.equal(agentReportChartWidth(stages,[stages,overall]),500);
assert.equal(agentReportPrimary([]),undefined);
assert.equal(JSON.stringify([stages,overall]),before);
});
test('supplementary trends remain primary content when the question requests them', () => {
const overall=trend('composite_rate'),scrap=trend('black_scrap_rate'),volume=trend('black_total_weight');
const inputs=[overall,scrap,volume];
assert.equal(agentReportSupplementary(scrap,inputs,'总体质量报告'),true);
assert.equal(agentReportSupplementary(volume,inputs,'总体质量报告'),true);
assert.equal(agentReportSupplementary(scrap,inputs,'分析报废率变化'),false);
assert.equal(agentReportSupplementary(volume,inputs,'分析投入重量变化'),false);
assert.equal(agentReportSupplementary(scrap,[scrap],'总体质量报告'),false);
});
test('structure reports use formal composition before a monthly weight trend', () => {
const monthly = { ...trend('current_scrap_weight'), unit: 'kg' };
const composition = { ...monthly, id: 'categories', type: 'donut', dimension: 'category', sectionKey: 'composition', metric: 'source_defect_weight' };
assert.equal(agentReportPrimary([monthly, composition], '亮片报废结构专题报告'), composition);
assert.equal(agentReportSupplementary(monthly, [monthly, composition], '亮片报废结构专题报告'), true);
});
test('repeated rankings preserve the requested Top and keep distinct metrics and scopes', () => {
const ranking = { ...trend('bright_scrap_weight'), type: 'bar', unit: 'kg', dimension: 'group', sectionKey: 'group',
categories: ['a','b','c','d','e'].map(key=>({key,label:key})), series: [{key:'bright_scrap_weight',values:[5,4,3,2,1]}] };
const expanded = { ...ranking, id: 'expanded', categories: [...ranking.categories,{key:'f',label:'f'}], series:[{key:'bright_scrap_weight',values:[5,4,3,2,1,.5]}] };
const copy = { ...ranking, id:'duplicate', evidenceRefs:['another-read'] };
const another = { ...ranking, id:'another-scope',scope:{department:'other'} };
const original = JSON.stringify([ranking,expanded,copy,another]);
const figures=agentReportVisuals([ranking,expanded,copy,another], '业务分组Top5对比简报');
assert.deepEqual(figures.map(v=>v.id),[ranking.id,another.id]);
assert.equal(JSON.stringify([ranking,expanded,copy,another]),original);
});
test('a saved structure report without a formal composition image prefers its actual defect ranking over a trend',()=>{
const monthly={...trend('current_scrap_weight'),unit:'kg'};
const defects={...monthly,id:'defect-bars',type:'bar',dimension:'defect',metric:'source_defect_weight'};
assert.equal(agentReportPrimary([monthly,defects],'亮片报废结构专题报告'),defects);
});
test('an available Top10 snapshot displays the requested Top5 without changing saved data or composition',()=>{
const ten={...trend('source_defect_weight'),unit:'kg',type:'bar',dimension:'defect',
categories:Array.from({length:10},(_,i)=>({key:String(i),label:'项目'+i})),
series:[{key:'source_defect_weight',label:'来源细分重量',values:[10,9,8,7,6,5,4,3,2,1]}],coverage:{totalRows:21,returnedRows:10,truncated:true}};
const pie={...ten,id:'composition',dimension:'category',type:'donut',categories:ten.categories.slice(0,4),series:[{key:'source_defect_weight',label:'正式类别重量',values:[4,3,2,1]}]};
const before=JSON.stringify([ten,pie]);const figures=agentReportVisuals([ten,pie],'亮片报废结构,具体缺陷Top5');
assert.equal(figures[0].categories.length,5);assert.deepEqual(figures[0].series[0].values,[10,9,8,7,6]);
assert.equal(figures[0].coverage.returnedRows,5);assert.equal(figures[0].coverage.totalRows,21);
assert.equal(figures[1].categories.length,4);assert.equal(JSON.stringify([ten,pie]),before);
assert.equal(parseAnalysisVisuals([figures[0]],1).visuals[0]?.chartable,true,'the cropped visual must remain renderable by the export parser');
});
@@ -83,20 +83,18 @@ test('a refreshed question clears prior selections; disabled views cannot submit
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('the DSH workspace wires clarification only for the latest turn and editable sessions', () => {
const workspace = fs.readFileSync(new URL('../src/agent/AgentWorkspace.tsx', import.meta.url), 'utf8');
const conversation = fs.readFileSync(new URL('../src/agent/AgentConversation.tsx', import.meta.url), 'utf8');
assert.match(workspace, /canAct=\{!state\.readOnly && !state\.busy && !state\.historyLoading\} latest=\{turn === lastTurn\}/);
assert.match(workspace, /onPrompt=\{prompt\}/);
assert.match(conversation, /status === 'NEEDS_CLARIFICATION' && latest && <AnalysisClarification turn=\{turn\} disabled=\{!canAct\} onContinue=\{onPrompt\}/);
});
test('reopened conversations restore only the newest unanswered clarification to the current turn', () => {
test('reopened conversations can identify the newest unanswered clarification', () => {
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\)\)/);
});
+114 -53
View File
@@ -3,60 +3,121 @@ import assert from 'node:assert/strict';
import fs from 'node:fs';
import ts from 'typescript';
import React from 'react';
import {renderToStaticMarkup} from 'react-dom/server';
import {analysisStreamStatus,analysisIsRunning,acceptAnalysisEvent,settledAnalysisTurn} from '../src/analysisConversationState.ts';
const source=fs.readFileSync(new URL('../src/ManagementPages.tsx',import.meta.url),'utf8');
const compile=code=>ts.transpileModule(code,{fileName:'status.tsx',compilerOptions:{target:ts.ScriptTarget.ES2022,jsx:ts.JsxEmit.React}}).outputText;
const tick=()=>new Promise(resolve=>setImmediate(resolve));
const deferred=()=>{let resolve;const promise=new Promise(r=>resolve=r);return{promise,resolve};};
const isObjectRecord=v=>!!v&&typeof v==='object'&&!Array.isArray(v);
const finalStatuses=new Set(['COMPLETED','PARTIAL','FAILED','CANCELLED','NEEDS_CLARIFICATION']);
function fixture(){
let lastTurn={id:'t1',question:'q',status:'QUEUED',createdAt:'2026-11-02T01:00:00Z'},onEvent,reads=0;
const stream=deferred(),firstRead=deferred(),secondRead=deferred();
const env={mounted:{current:true},streamController:{current:null},subscriptionGeneration:{current:0},sessionId:'s1',eventCursors:{current:{}},ANALYSIS_FINAL_STATUSES:finalStatuses,
setLastTurn:next=>lastTurn=typeof next==='function'?next(lastTurn):next,writeAnalysisLocation(){},setActiveTurnId(){},setBusy(){},setRetryQuestion(){},setTurns(){},setError(){},loadSessions:async()=>{},onUnauthorized:()=>false,apiMessage:e=>e.message,
isObjectRecord,analysisStreamStatus,analysisIsRunning,acceptAnalysisEvent,settledAnalysisTurn,collectionItems:value=>value.items||[],modelThinkingEntries:()=>[],mergeModelThinking:()=>[]};
const api={analysisTurnEvents:async(_id,options)=>{onEvent=options.onEvent;return stream.promise;},analysisSessionTurns:()=>{reads++;return reads===1?firstRead.promise:secondRead.promise;}};
const code=source.slice(source.indexOf(' const followTurn = async'),source.indexOf('\n useEffect(() => {\n if (!active || restoreStarted.current)'));
const follow=new Function('api',...Object.keys(env),compile(code+'\nreturn followTurn;'))(api,...Object.values(env));
const work=follow('t1','q','s1');
return{get:()=>lastTurn,reads:()=>reads,switchTurn(){env.subscriptionGeneration.current++;lastTurn={id:'other',status:'RUNNING'};},emit(event,data){onEvent({id:String(Math.random()),event,data});},firstRead,secondRead,async close(){env.streamController.current?.abort();stream.resolve();await work;}};
import { renderToStaticMarkup } from 'react-dom/server';
import { analysisStreamStatus, analysisIsRunning } from '../src/analysisConversationState.ts';
import { sanitizeAnalysisDisplayText } from '../src/analysisDisplayText.ts';
import { createAnalysisSessionClient } from '../src/agent/sessionClient.ts';
const CREATED_AT = '2026-11-02T01:00:00Z';
const STARTED_AT = '2026-11-02T01:00:05Z';
const initialTurn = { id: 't1', question: '质量查询', status: 'QUEUED', createdAt: CREATED_AT, eventCursor: '10' };
const page = (id, turn, activeTurnId = turn.id) => ({ id, activeTurnId, turns: [turn] });
function fixture(t) {
const connections = [];
const pages = { s1: page('s1', initialTurn), s2: page('s2', { id: 'other', status: 'RUNNING' }) };
let auxiliaryReads = 0;
const unexpectedRead = async () => { auxiliaryReads++; throw new Error('Unexpected auxiliary read'); };
const client = createAnalysisSessionClient({
userId: 'status-fixture',
transport: {
analysisSessions: async () => ({ items: [] }),
analysisSessionPage: unexpectedRead,
analysisTurn: unexpectedRead,
analysisTurnEvents: unexpectedRead,
analysisSessionTurns: unexpectedRead,
analysisSessionFollow: (id, { signal, onEvent }) => new Promise(resolve => {
connections.push({ id, signal, emit: onEvent, close: resolve });
signal.addEventListener('abort', resolve, { once: true });
onEvent({ event: 'snapshot', data: pages[id] });
}),
},
});
t.after(client.dispose);
return { client, connections, pages, auxiliaryReads: () => auxiliaryReads };
}
test('tool step events keep the whole turn running and terminal status does not regress',()=>{
assert.equal(analysisStreamStatus('RUNNING','tool_started',undefined),'RUNNING');
assert.equal(analysisStreamStatus('RUNNING','tool_completed','completed'),'RUNNING');
assert.equal(analysisStreamStatus('RUNNING','completed','COMPLETED'),'COMPLETED');
assert.equal(analysisStreamStatus('COMPLETED','progress','RUNNING'),'COMPLETED');
});
test('actual event subscriber keeps status live and fills the server clock without re-entering',async()=>{
const ui=fixture();assert.equal(ui.reads(),1);
ui.emit('progress',{status:'RUNNING'});
ui.firstRead.resolve({items:[{id:'t1',createdAt:'2026-11-02T01:00:00Z',startedAt:''}]});await tick();
assert.equal(ui.reads(),2,'a running event during an initial queued timing read schedules one non-overlapping follow-up');
ui.secondRead.resolve({items:[{id:'t1',startedAt:'2026-11-02T01:00:05Z'}]});await tick();
ui.emit('tool_started',{step:{status:'running'}});
assert.equal(ui.get().status,'RUNNING');assert.equal(ui.get().startedAt,'2026-11-02T01:00:05Z');
ui.emit('tool_completed',{step:{status:'completed'}});assert.equal(ui.get().status,'RUNNING');
assert.equal(ui.reads(),2);await ui.close();
});
test('late timing metadata cannot update a different selected turn',async()=>{
const ui=fixture();ui.switchTurn();await ui.close();ui.firstRead.resolve({items:[{id:'t1',startedAt:'2026-11-02T01:00:05Z'}]});await tick();
assert.equal(ui.get().startedAt,undefined);
});
test('metadata renders a waiting clock immediately and a spinning running clock after server start',()=>{
const code=source.slice(source.indexOf('function AnalysisTurnMetadata('),source.indexOf('\nfunction isObjectRecord('));
const Metadata=new Function('React','useState','useEffect','analysisIsRunning','isObjectRecord','LoadingOutlined',compile(code+'\nreturn AnalysisTurnMetadata;'))(React,initial=>[initial,()=>{}],()=>{},analysisIsRunning,isObjectRecord,props=>React.createElement('i',props));
const now=Date.now();
const waiting=renderToStaticMarkup(React.createElement(Metadata,{turn:{_uiSubmittedAt:new Date(now-30000).toISOString()},status:'SUBMITTING',compact:true}));
assert.match(waiting,/提交中/);assert.match(waiting,/已等待 30秒/);
const running=renderToStaticMarkup(React.createElement(Metadata,{turn:{startedAt:new Date(now-10000).toISOString()},status:'RUNNING',compact:true}));
assert.match(running,/已运行 10秒/);assert.match(running,/analysis-runtime-spinner/);
const currentTurn = client => client.getSnapshot().turns.at(-1);
const tick = () => new Promise(resolve => setImmediate(resolve));
test('tool status is independent of the turn status and terminal status stays settled', () => {
assert.equal(analysisStreamStatus('RUNNING', 'tool_started', undefined), 'RUNNING');
assert.equal(analysisStreamStatus('RUNNING', 'tool_completed', 'completed'), 'RUNNING');
assert.equal(analysisStreamStatus('RUNNING', 'completed', 'COMPLETED'), 'COMPLETED');
assert.equal(analysisStreamStatus('COMPLETED', 'progress', 'RUNNING'), 'COMPLETED');
});
test('partial remains a backend state without an extra partial label in conversation metadata',()=>{
const code=source.slice(source.indexOf('function AnalysisTurnMetadata('),source.indexOf('\nfunction isObjectRecord('));
const Metadata=new Function('React','useState','useEffect','analysisIsRunning','isObjectRecord','LoadingOutlined',compile(code+'\nreturn AnalysisTurnMetadata;'))(React,initial=>[initial,()=>{}],()=>{},analysisIsRunning,isObjectRecord,()=>null);
const html=renderToStaticMarkup(React.createElement(Metadata,{turn:{durationMs:6000},status:'PARTIAL',compact:true}));
assert.doesNotMatch(html,/部分完成/);assert.match(html,/运行时长 6秒/);
test('the follow connection supplies the server start time without an auxiliary read', async t => {
const { client, connections, auxiliaryReads } = fixture(t);
assert.equal(await client.openSession('s1'), true);
assert.equal(currentTurn(client).status, 'QUEUED');
assert.equal(currentTurn(client).createdAt, CREATED_AT);
assert.equal(currentTurn(client).startedAt, undefined);
const { emit } = connections[0];
emit({ id: '11', event: 'progress', data: { turnId: 't1', status: 'RUNNING', startedAt: STARTED_AT } });
emit({ id: '12', event: 'tool_started', data: { turnId: 't1', step: { status: 'running' } } });
emit({ id: '13', event: 'tool_completed', data: { turnId: 't1', status: 'completed' } });
assert.equal(currentTurn(client).status, 'RUNNING');
assert.equal(currentTurn(client).startedAt, STARTED_AT);
assert.equal(client.getSnapshot().busy, true);
assert.equal(auxiliaryReads(), 0);
assert.equal(connections.length, 1);
});
test('late server clock events from an aborted connection cannot update the newly selected turn', async t => {
const { client, connections } = fixture(t);
await client.openSession('s1');
await client.openSession('s2');
assert.equal(connections[0].signal.aborted, true);
connections[0].emit({ id: '11', event: 'progress', data: { turnId: 't1', status: 'RUNNING', startedAt: STARTED_AT } });
assert.equal(currentTurn(client).id, 'other');
assert.equal(currentTurn(client).startedAt, undefined);
});
test('the terminal event settles immediately and the replacement snapshot supplies the saved duration', async t => {
const { client, connections, pages, auxiliaryReads } = fixture(t);
await client.openSession('s1');
const { emit, close } = connections[0];
emit({ id: '11', event: 'completed', data: { turnId: 't1', status: 'COMPLETED', result: { answer: '已核验答复' } } });
assert.equal(currentTurn(client).status, 'COMPLETED');
assert.equal(currentTurn(client).answer, '已核验答复');
assert.equal(client.getSnapshot().busy, false);
pages.s1 = page('s1', { ...initialTurn, status: 'COMPLETED', eventCursor: '11', durationMs: 6000, result: { answer: '已核验答复' } }, '');
close();
await tick();
assert.equal(connections.length, 2);
assert.equal(currentTurn(client).durationMs, 6000);
assert.equal(auxiliaryReads(), 0);
});
const source = fs.readFileSync(new URL('../src/agent/AgentConversation.tsx', import.meta.url), 'utf8');
const statusSource = source.slice(source.indexOf('function RunStatus('), source.indexOf('\nfunction ExecutionEvents('));
const statusJavaScript = ts.transpileModule(`${statusSource}\nreturn RunStatus;`, {
fileName: 'status.tsx', compilerOptions: { target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.React },
}).outputText;
const fixedClock = class extends Date { static now() { return Date.parse('2026-11-02T01:00:15Z'); } };
const record = value => value && typeof value === 'object' && !Array.isArray(value) ? value : {};
const string = value => typeof value === 'string' ? value : '';
const LoadingOutlined = () => React.createElement('i', { className: 'test-loading-icon' });
const RunStatus = new Function('React', 'useState', 'useEffect', 'analysisIsRunning', 'sanitizeAnalysisDisplayText',
'record', 'string', 'LoadingOutlined', 'Date', statusJavaScript)(React, React.useState, React.useEffect,
analysisIsRunning, sanitizeAnalysisDisplayText, record, string, LoadingOutlined, fixedClock);
const renderStatus = turn => renderToStaticMarkup(React.createElement(RunStatus, { turn }));
test('run status renders a submission clock and prefers the actual server start time while running', () => {
const waiting = renderStatus({ _uiSubmittedAt: '2026-11-02T00:59:45Z', status: 'SUBMITTING' });
assert.match(waiting, /提交中/);
assert.match(waiting, /<time>30 秒<\/time>/);
const running = renderStatus({ createdAt: CREATED_AT, startedAt: STARTED_AT, status: 'RUNNING' });
assert.match(running, /分析中/);
assert.match(running, /agent-run-status is-running/);
assert.match(running, /test-loading-icon/);
assert.match(running, /<time>10 秒<\/time>/);
});
test('a partial result renders its status once and shows the saved duration', () => {
const html = renderStatus({ durationMs: 6000, status: 'PARTIAL' });
assert.equal(html.match(/部分完成/g)?.length, 1);
assert.match(html, /<time>6 秒<\/time>/);
assert.doesNotMatch(html, /is-running|test-loading-icon/);
});
+176 -65
View File
@@ -1,77 +1,188 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import ts from 'typescript';
import {analysisComposerState} from '../src/analysisScope.ts';
const source=fs.readFileSync(new URL('../src/ManagementPages.tsx',import.meta.url),'utf8');
const tick=()=>new Promise(resolve=>setImmediate(resolve));
const deferred=()=>{let resolve;const promise=new Promise(r=>resolve=r);return{promise,resolve};};
function restoreFixture({sessionId='',turnId='',link=false}={}){
const list=deferred(),opens=[];let effect,loading=true;
const env={active:true,restoreStarted:{current:false},mounted:{current:true},navigationGeneration:{current:0},initialSessionId:sessionId,initialTurnId:turnId,initialLink:{present:link},user:{id:'u'},
useEffect:fn=>{effect=fn;},setHistoryLoading:v=>{loading=v;},setSessions(){},setSessionsLoaded(){},setSessionsLoading(){},collectionItems:v=>v.items||[],
loadSessions:async()=>(await list.promise).items,api:{analysisSessions:()=>list.promise,analysisTurn:async()=>({sessionId:'linked-session'})},defaultAnalysisSession:(_u,items)=>items[0]?.id,
openSession:async(...args)=>{opens.push(args);loading=false;return true;},onUnauthorized:()=>false,setError(){},apiMessage:e=>e.message};
const marker=' useEffect(() => {\n if (!active || restoreStarted.current)';const start=source.indexOf(marker);const end=source.indexOf('\n useEffect(() => {',start+marker.length);
const code=ts.transpileModule(source.slice(start,end),{compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText;
new Function(...Object.keys(env),code)(...Object.values(env));effect();
return{list,opens,get loading(){return loading;}};
import { createAnalysisSessionClient } from '../src/agent/sessionClient.ts';
const tick = () => new Promise(resolve => setImmediate(resolve));
const deferred = () => {
let resolve, reject;
const promise = new Promise((yes, no) => { resolve = yes; reject = no; });
return { promise, resolve, reject };
};
function fixture(t, overrides = {}) {
const calls = { lists: 0, followed: [], details: [], options: 0, submissions: 0 };
const transport = {
analysisSessions: async () => { calls.lists++; return { items: [] }; },
analysisTurn: async id => {
calls.details.push(id);
return { id, sessionId: 'linked-session', status: 'COMPLETED' };
},
analysisSessionFollow: async (id, { onEvent }) => {
calls.followed.push(id);
onEvent({ event: 'snapshot', data: {
id, title: '授权会话', turns: [{ id: 'requested-turn', status: 'COMPLETED', result: { answer: '已保存答复' } }],
} });
},
options: async () => { calls.options++; return {}; },
createAnalysisSession: async () => { calls.submissions++; throw new Error('Unexpected submission'); },
startAnalysisTurn: async () => { calls.submissions++; throw new Error('Unexpected submission'); },
...overrides,
};
const client = createAnalysisSessionClient({ userId: 'loading-fixture', transport });
t.after(client.dispose);
return { client, calls };
}
test('an explicit history link loads its body without waiting for the unrelated session list',async()=>{
const ui=restoreFixture({sessionId:'requested-session'});await tick();assert.deepEqual(ui.opens,[['requested-session',undefined]]);
ui.list.resolve({items:[]});await tick();
});
test('a turn link can resolve its session while the session list is still pending',async()=>{
const ui=restoreFixture({turnId:'requested-turn'});await tick();assert.deepEqual(ui.opens,[['linked-session','requested-turn']]);
ui.list.resolve({items:[]});await tick();
});
test('default history selection still waits for the list before choosing a session',async()=>{
const ui=restoreFixture();await tick();assert.equal(ui.opens.length,0);ui.list.resolve({items:[{id:'recent'}]});await tick();assert.deepEqual(ui.opens,[['recent',undefined]]);
test('an explicit session opens its saved answer while the session list is still pending', async t => {
const list = deferred();
const { client, calls } = fixture(t, { analysisSessions: () => list.promise });
assert.equal(await client.openInitial({ sessionId: 'requested-session' }), true);
assert.deepEqual(calls.followed, ['requested-session']);
assert.equal(client.getSnapshot().turns[0].answer, '已保存答复');
assert.equal(client.getSnapshot().historyLoading, false);
assert.equal(client.getSnapshot().sessionsLoading, true);
list.reject(new Error('list unavailable'));
await tick();
assert.equal(client.getSnapshot().sessionsError, 'list unavailable');
assert.equal(client.getSnapshot().historyError, '');
assert.equal(client.getSnapshot().turns[0].answer, '已保存答复');
});
function listFixture(){
const read=deferred();let reads=0,state={busy:false,loaded:false,items:[],error:''};
const env={mounted:{current:true},active:true,sessionReadRequest:{current:null},setSessionsLoading:v=>{state.busy=v;},setSessions:v=>{state.items=v;},setSessionsLoaded:v=>{state.loaded=v;},setSessionsError:v=>{state.error=v;},onUnauthorized:()=>false,apiMessage:e=>e.message,collectionItems:v=>v.items||[],api:{analysisSessions:()=>{reads++;return read.promise;}}};
const start=source.indexOf(' const loadSessions = async');const end=source.indexOf('\n const retrySessions =',start);
const code=ts.transpileModule(source.slice(start,end)+'\nreturn loadSessions;',{compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText;
return{read,state,reads:()=>reads,load:new Function(...Object.keys(env),code)(...Object.values(env))};
}
test('session-list reads are shared, and failure stays within the list resource',async()=>{
const ui=listFixture();const a=ui.load(),b=ui.load();assert.equal(ui.reads(),1);assert.equal(ui.state.busy,true);
ui.read.resolve({items:[{id:'recent'}]});assert.deepEqual(await a,[{id:'recent'}]);await b;assert.equal(ui.state.loaded,true);assert.equal(ui.state.busy,false);
ui.read.resolve({items:[]});
});
test('a failed list read ends its own loading state and cannot masquerade as an empty successful list',async()=>{
const ui=listFixture();const work=ui.load();ui.read.resolve(Promise.reject(new Error('list unavailable')));assert.equal(await work,undefined);
assert.equal(ui.state.busy,false);assert.equal(ui.state.loaded,false);assert.equal(ui.state.error,'list unavailable');
});
test('ordinary and explicit historical conversations never download the unused options resource',()=>{
const start=source.indexOf(' useEffect(() => {\n if (!active || !initialLink.present');assert.notEqual(start,-1);
const end=source.indexOf('\n\n',start);const code=ts.transpileModule(source.slice(start,end),{compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText;
for(const [present,session,turn] of [[false,'',''],[false,'s',''],[true,'s',''],[true,'','t']]){
let reads=0;const env={useEffect:fn=>fn(),active:true,initialLink:{present},initialSessionId:session,initialTurnId:turn,optionsRequestStarted:{current:false},optionsRead:{run:()=>{reads++;}},onUnauthorized:()=>false};
new Function(...Object.keys(env),code)(...Object.values(env));assert.equal(reads,0);
}
test('a turn-only link resolves and focuses its session while the list is pending', async t => {
const list = deferred();
const { client, calls } = fixture(t, { analysisSessions: () => list.promise });
assert.equal(await client.openInitial({ turnId: 'requested-turn' }), true);
assert.deepEqual(calls.details, ['requested-turn']);
assert.deepEqual(calls.followed, ['linked-session']);
assert.equal(client.getSnapshot().focusTurnId, 'requested-turn');
assert.equal(client.getSnapshot().sessionsLoading, true);
list.resolve({ items: [] });
});
function retryFixture(sessionId='',turnId=''){
const list=deferred(),opens=[],navigationGeneration={current:0},state={historyLoading:false};
const env={sessionId,navigationGeneration,pendingTurnLink:{current:turnId},mounted:{current:true},initialLink:{present:false},user:{id:'u'},setHistoryLoading:v=>{state.historyLoading=v;},loadSessions:()=>list.promise,api:{analysisTurn:async()=>({sessionId:'target-session'})},openSession:async(id,focus)=>opens.push([id,focus]),defaultAnalysisSession:(_u,items)=>items[0]?.id,onUnauthorized:()=>false,setError(){},apiMessage:e=>e.message};
const start=source.indexOf(' const retrySessions = async');const end=source.indexOf('\n useEffect(',start);
const code=ts.transpileModule(source.slice(start,end)+'\nreturn retrySessions;',{compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText;
return{list,opens,state,navigationGeneration,retry:new Function(...Object.keys(env),code)(...Object.values(env))};
}
test('retrying a linked history does not wait for a slow list',async()=>{
const ui=retryFixture('selected');await ui.retry();assert.deepEqual(ui.opens,[['selected',undefined]]);ui.list.resolve([]);
test('default restoration waits for the recent session list', async t => {
const list = deferred();
const { client, calls } = fixture(t, { analysisSessions: () => list.promise });
const opening = client.openInitial();
await tick();
assert.deepEqual(calls.followed, []);
assert.equal(client.getSnapshot().historyLoading, true);
list.resolve({ items: [{ id: 'recent' }] });
assert.equal(await opening, true);
assert.deepEqual(calls.followed, ['recent']);
assert.equal(client.getSnapshot().historyLoading, false);
});
test('default-list retry cannot navigate over a newer user selection',async()=>{
const ui=retryFixture();const work=ui.retry();ui.navigationGeneration.current++;ui.list.resolve([{id:'old-default'}]);await work;assert.deepEqual(ui.opens,[]);
test('concurrent sidebar refreshes share a single list request', async t => {
const list = deferred();
let reads = 0;
const { client } = fixture(t, { analysisSessions: () => { reads++; return list.promise; } });
const first = client.refreshSessions();
const second = client.refreshSessions();
assert.equal(first, second);
await tick();
assert.equal(reads, 1);
assert.equal(client.getSnapshot().sessionsLoading, true);
list.resolve({ items: [{ id: 'recent' }] });
assert.deepEqual(await first, [{ id: 'recent' }]);
assert.deepEqual(client.getSnapshot().sessions, [{ id: 'recent' }]);
assert.equal(client.getSnapshot().sessionsLoading, false);
assert.equal(client.getSnapshot().sessionsError, '');
});
test('retry of a turn-only link re-resolves the requested turn instead of opening an unrelated default',async()=>{
const ui=retryFixture('','requested-turn');ui.list.resolve([{id:'unrelated-default'}]);await ui.retry();assert.deepEqual(ui.opens,[['target-session','requested-turn']]);
test('a failed list request exposes its own error and permits retry', async t => {
let reads = 0;
const { client } = fixture(t, { analysisSessions: async () => {
if (++reads === 1) throw new Error('list unavailable');
return { items: [{ id: 'restored' }] };
} });
await client.refreshSessions();
assert.equal(client.getSnapshot().sessionsLoading, false);
assert.equal(client.getSnapshot().sessionsError, 'list unavailable');
assert.equal(client.getSnapshot().historyError, '');
await client.refreshSessions();
assert.equal(client.getSnapshot().sessionsError, '');
assert.deepEqual(client.getSnapshot().sessions, [{ id: 'restored' }]);
});
test('default-history retry locks sending until its target resolves, so a late list cannot replace a new submission',async()=>{
const ui=retryFixture();const work=ui.retry();assert.equal(ui.state.historyLoading,true);
assert.equal(analysisComposerState(false,false,ui.state.historyLoading,'新问题').sendDisabled,true);
ui.list.resolve([{id:'default'}]);await work;assert.equal(ui.state.historyLoading,false);
test('ordinary and linked history restoration do not request analysis options', async t => {
for (const initial of [{}, { sessionId: 'selected' }, { turnId: 'requested-turn' }, { selectRecent: false }]) {
const { client, calls } = fixture(t);
assert.equal(await client.openInitial(initial), true);
assert.equal(calls.lists, 1);
assert.equal(calls.options, 0);
}
const workspace = fs.readFileSync(new URL('../src/agent/AgentWorkspace.tsx', import.meta.url), 'utf8');
assert.doesNotMatch(workspace, /\b(?:optionsRead|analysisOptions)\b|\bapi\.options\s*\(/);
});
test('retrying an explicitly selected history opens its snapshot while the list is slow', async t => {
const list = deferred();
const reads = [];
const { client } = fixture(t, {
analysisSessions: () => list.promise,
analysisSessionFollow: async (id, { onEvent }) => {
reads.push(id);
if (reads.length === 1) throw new Error('history unavailable');
onEvent({ event: 'snapshot', data: { id, turns: [] } });
},
});
assert.equal(await client.openInitial({ sessionId: 'selected' }), false);
const failed = client.getSnapshot();
assert.equal(failed.historyError, 'history unavailable');
assert.equal(await client.openSession(failed.sessionId, failed.focusTurnId), true);
assert.deepEqual(reads, ['selected', 'selected']);
assert.equal(client.getSnapshot().sessionsLoading, true);
list.resolve({ items: [] });
});
test('a late default-list retry cannot navigate over a newer user selection', async t => {
const retry = deferred();
let reads = 0;
const { client, calls } = fixture(t, { analysisSessions: async () => {
if (++reads === 1) throw new Error('list unavailable');
return retry.promise;
} });
assert.equal(await client.openInitial(), false);
const retrying = client.openInitial();
assert.equal(await client.openSession('selected'), true);
retry.resolve({ items: [{ id: 'old-default' }] });
assert.equal(await retrying, false);
assert.deepEqual(calls.followed, ['selected']);
assert.equal(client.getSnapshot().sessionId, 'selected');
});
test('retrying an unresolved turn link resolves the same turn before choosing any default', async t => {
const reads = [];
const { client, calls } = fixture(t, {
analysisSessions: async () => ({ items: [{ id: 'unrelated-default' }] }),
analysisTurn: async id => {
reads.push(id);
if (reads.length === 1) throw new Error('turn unavailable');
return { id, sessionId: 'linked-session', status: 'COMPLETED' };
},
});
const initial = { turnId: 'requested-turn' };
assert.equal(await client.openInitial(initial), false);
assert.equal(await client.openInitial(initial), true);
assert.deepEqual(reads, ['requested-turn', 'requested-turn']);
assert.deepEqual(calls.followed, ['linked-session']);
assert.equal(client.getSnapshot().focusTurnId, 'requested-turn');
});
test('retrying default restoration keeps submission locked until its target resolves', async t => {
const retry = deferred();
let reads = 0;
const { client, calls } = fixture(t, { analysisSessions: async () => {
if (++reads === 1) throw new Error('list unavailable');
return retry.promise;
} });
assert.equal(await client.openInitial(), false);
const retrying = client.openInitial();
assert.equal(client.getSnapshot().historyLoading, true);
assert.equal(await client.submit('新问题'), false);
assert.equal(calls.submissions, 0);
retry.resolve({ items: [{ id: 'default' }] });
assert.equal(await retrying, true);
assert.equal(client.getSnapshot().historyLoading, false);
});
+30 -15
View File
@@ -5,6 +5,7 @@ import ts from 'typescript';
import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { emptyAnalysisNotice } from '../src/analysisConversationState.ts';
import { sanitizeAnalysisDisplayText } from '../src/analysisDisplayText.ts';
import {
analysisMemberListFullyRead,
analysisMemberListPage,
@@ -110,21 +111,35 @@ test('the chat table renders raw member values as escaped text, not HTML or link
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', 'emptyAnalysisNotice',
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:turn.recoveryError||''}), () => 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, emptyAnalysisNotice);
const html = renderToStaticMarkup(React.createElement(component, { turn: { id: 'old-turn', status: 'COMPLETED', answer: '| old | Markdown table |' }, onUnauthorized: () => false }));
assert.match(html, /legacy-markdown/);
test('member-list display is opt-in and historical plain answers do not acquire report actions', () => {
const source = fs.readFileSync(new URL('../src/agent/AgentConversation.tsx', import.meta.url), 'utf8');
const start = source.indexOf('export const AgentConversationTurn');
const code = source.slice(start).replace('export const AgentConversationTurn', 'const AgentConversationTurn');
const view = {
React, memo: value => value, useMemo: callback => callback(), useState: value => [value, () => {}], useEffect: () => {},
useAnalysisVisualRecovery: turn => ({ turn, available: false, recovering: false, error: turn.recoveryError || '' }),
analysisSnapshotResult: turn => turn.result || turn, partialAnswerIsOnlyProgress: () => false, analysisIsRunning: () => false,
executionEvents: () => [], RunStatus: () => null, authoredReport: () => null, analysisScopeText: () => '', emptyAnalysisNotice,
string: value => typeof value === 'string' ? value : '', record: value => value || {}, sanitizeAnalysisDisplayText,
AiMarkdown: ({ content }) => React.createElement('div', { className: 'model-original' }, content),
AnalysisMemberListPanel: () => React.createElement('div', { className: 'analysis-member-list' }),
Button: ({ children }) => React.createElement('button', null, children),
};
const component = new Function(...Object.keys(view), ts.transpileModule(`${code}
return AgentConversationTurn;`, {
fileName: 'agent-turn.tsx', compilerOptions: { target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.React }
}).outputText)(...Object.values(view));
const render = turn => renderToStaticMarkup(React.createElement(component, { turn, canAct: true, latest: true }));
const html = render({ id: 'old-turn', status: 'COMPLETED', answer: '| old | Markdown table |' });
assert.match(html, /model-original/);
assert.match(html, /\| old \| Markdown table \|/);
assert.doesNotMatch(html, /analysis-member-list/);
const empty = renderToStaticMarkup(React.createElement(component, { turn: { id: 'empty-turn', status: 'PARTIAL', answer: '', answerQuality: { dataComplete: true, narrativeComplete: false } }, onUnauthorized: () => false, onRetry: () => {} }));
assert.match(empty, /role="status">数据查询已完成,但未生成分析正文。请重新分析。/);
assert.doesNotMatch(html, /analysis-member-list|生成报告|查看报告/);
assert.match(render({ id: 'members', status: 'COMPLETED', result: { memberList: fixture() } }), /analysis-member-list/);
const empty = render({ id: 'empty-turn', status: 'PARTIAL', answer: '', answerQuality: { dataComplete: true, narrativeComplete: false } });
assert.doesNotMatch(empty, /数据查询已完成|核心结论/);
assert.match(empty, /<button>重新分析<\/button>/);
const failedRecovery=renderToStaticMarkup(React.createElement(component,{turn:{id:'old-turn',status:'PARTIAL',answer:'原答案',recoveryError:'图表恢复暂不可用'},onUnauthorized:()=>false}));
assert.match(failedRecovery,/role="alert">图表恢复暂不可用/);assert.match(failedRecovery,/原答案/);
assert.match(render({id:'failed-turn',status:'FAILED',answer:'',completion:{reason:'任务理解未完成,请重试'}}), /任务理解未完成,请重试/);
const recovery = render({ id: 'old-turn', status: 'PARTIAL', answer: '原答案', recoveryError: '图表恢复暂不可用' });
assert.match(recovery, /role="alert">图表恢复暂不可用/);
assert.match(recovery, /原答案/);
});
@@ -5,29 +5,22 @@ 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('tableTextAlignment', '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',
const source = fs.readFileSync(new URL('../src/AnalysisMemberListReport.tsx', import.meta.url), 'utf8');
const script = source.replace(/^import .+;\n/gm, '').replace('export function ', 'function ');
const ReportDocument = new Function('tableTextAlignment', 'React',
'analysisMemberListFullyRead', 'analysisMemberListPeriod', 'parseAnalysisMemberList',
ts.transpileModule(`${script}
return AnalysisMemberListReport;`, {
fileName: 'analysis-member-report.tsx',
compilerOptions: { target: ts.ScriptTarget.ES2022, jsx: ts.JsxEmit.React },
}).outputText
)(tableTextAlignment, 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);
)(tableTextAlignment, React, analysisMemberListFullyRead, analysisMemberListPeriod, parseAnalysisMemberList);
function memberListFixture() {
return {
schemaVersion: 1,
@@ -46,8 +39,7 @@ function memberListFixture() {
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: [],
value: memberListFixture(),
}));
assert.match(html, /<h2>成员清单<\/h2>/);
@@ -71,8 +63,7 @@ test('the report accepts a root memberList and labels incomplete coverage', () =
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: [],
value: source,
}));
assert.equal((html.match(/<tr/g) || []).length, 161);
assert.match(html, /读取未完成 160 \/ 181 条/);
@@ -37,6 +37,15 @@ test('figures are inserted after the associated complete chapter without removin
test('alternate historical evidence fallback also recovers native prose',()=>{
const data=legacy();data.result.readingSummary.lead='现有证据不足以支持本轮完整分析,已保留可核验统计结果。';assert.equal(originalAnalysisBody(data).answer,original);
});
test('DSH never restores an unverified investigation draft over a checked partial result',()=>{
const data=legacy();data.result.engine='DSH';
data.result.answer='已取得本轮统计结果,答案整理尚未完整完成。';
data.plan.timeline.at(-1).text='TOP5全部属于缺角。';
const body=originalAnalysisBody(data);
assert.equal(body.source,'saved');assert.equal(body.answer,data.result.answer);
assert.doesNotMatch(body.answer,/全部属于缺角/);
data.result.answer='';assert.deepEqual(originalAnalysisBody(data),{answer:'',source:'unavailable'});
});
test('black and bright figures cannot be attached to the opposite stage chapter',()=>{
const body='## 黑片阶段\n\n黑片完整解释。\n\n## 亮片阶段\n\n亮片完整解释。';
const figures=[{id:'black',type:'column',stage:'black',metric:'black_rate',evidenceRefs:[]},{id:'bright',type:'column',stage:'bright',metric:'bright_rate',evidenceRefs:[]}];
@@ -72,6 +72,20 @@ 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 });
test('explicit report chapters do not gain an extra generic conclusion heading', () => {
const reading = { ...summary(), evidence: [], notices: [], evidenceRefs: [],
lead: '已核实的范围如下。\n\n## 一、已确认事实\n\n合成产品06报废36.00 kg。\n\n## 二、数据局限\n\n现场原因尚未验证。\n\n## 三、下一步核查\n\n按原范围核对生产记录。' };
reading.fullAnswer = reading.lead;
const html = renderToStaticMarkup(React.createElement(AnalysisConclusion, {
reading, visuals: [], renderVisuals: () => null,
}));
const headings = [...html.matchAll(/<h3[^>]*>(.*?)<\/h3>/g)].map(match => match[1]);
assert.deepEqual(headings, ['一、已确认事实', '二、数据局限', '三、下一步核查']);
assert.match(html, /已核实的范围如下。/);
assert.match(html, /合成产品06报废36.00 kg。/);
});
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 }, 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' }) };
@@ -20,6 +20,14 @@ test('fallback title comes from the period and scope, never the user question',
assert.notEqual(title, question);
});
test('generic titles use the topic of a verified figure while specific generated titles retain priority', () => {
assert.equal(resolveAnalysisReportTitle('质量数据分析', '', '', '2026年10月', '', '产品规格报废总重排名'),
'2026年10月 产品规格报废总重排名');
assert.equal(resolveAnalysisReportTitle('质量数据分析', '产品报废核查', '', '2026年10月', '', '产品规格报废总重排名'),
'产品报废核查');
assert.equal(resolveAnalysisReportTitle('质量数据分析', '', '', '2026年10月', ''), '2026年10月质量分析报告');
});
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生成标题');
@@ -41,8 +49,8 @@ test('download names stay concise and use a single report suffix', () => {
});
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);
assert.deepEqual(longReportImageSize(900, 11912), { width: 900, height: 11912, pixelRatio: 2 });
assert.equal(longReportImageSize(900, 11912).height * 2, 23824);
});
test('very long reports fit one bounded canvas by scaling the entire image without dropping content', () => {
@@ -54,7 +62,7 @@ test('very long reports fit one bounded canvas by scaling the entire image witho
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.deepEqual(longReportImageSize(900, 830.2), { width: 900, height: 831, pixelRatio: 2 });
assert.throws(() => longReportImageSize(900, NaN), /尺寸无效/);
});
@@ -0,0 +1,109 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createAnalysisSessionClient } from '../src/agent/sessionClient.ts';
const tick = () => new Promise(resolve => setImmediate(resolve));
const deferred = () => {
let resolve, reject;
const promise = new Promise((yes, no) => { resolve = yes; reject = no; });
return { promise, resolve, reject };
};
function restoreFixture({ readList = async () => ({ items: [] }), readTurn } = {}) {
const opened = [];
const authorizationChecks = [];
const client = createAnalysisSessionClient({
userId: 'restore-fixture',
onUnauthorized: error => { authorizationChecks.push(error); return false; },
transport: {
analysisSessions: readList,
analysisTurn: readTurn,
analysisSessionFollow: async (id, { onEvent }) => {
opened.push(id);
onEvent({ event: 'snapshot', data: { id, turns: [{ id: 'requested-turn', status: 'COMPLETED' }] } });
},
},
});
return { client, opened, authorizationChecks };
}
test('replaying mount discards a stale turn lookup even before the replacement resolves', async t => {
const oldTurn = deferred();
const currentTurn = deferred();
let requests = 0;
const { client, opened, authorizationChecks } = restoreFixture({
readTurn: () => (++requests === 1 ? oldTurn.promise : currentTurn.promise),
});
t.after(client.dispose);
client.resume();
const first = client.openInitial({ turnId: 'requested-turn' });
client.suspend();
client.resume();
await tick();
assert.equal(requests, 2);
oldTurn.reject(Object.assign(new Error('old request unavailable'), { status: 503 }));
assert.equal(await first, false);
assert.equal(client.getSnapshot().historyLoading, true);
assert.equal(client.getSnapshot().historyError, '');
assert.deepEqual(authorizationChecks, []);
currentTurn.resolve({ sessionId: 'current-session' });
await tick();
assert.equal(client.getSnapshot().historyLoading, false);
assert.equal(client.getSnapshot().focusTurnId, 'requested-turn');
assert.deepEqual(opened, ['current-session']);
});
test('replaying mount shares a list read and finishes loading an empty history', async t => {
const list = deferred();
let requests = 0;
const { client, opened } = restoreFixture({ readList: () => { requests++; return list.promise; } });
t.after(client.dispose);
client.resume();
const first = client.openInitial();
client.suspend();
client.resume();
assert.equal(client.getSnapshot().historyLoading, true);
assert.equal(await client.submit('must wait for selection'), false);
list.resolve({ items: [] });
assert.equal(await first, false);
await tick();
assert.equal(requests, 1);
assert.equal(client.getSnapshot().historyLoading, false);
assert.equal(client.getSnapshot().historyError, '');
assert.deepEqual(opened, []);
});
test('a failed recent-session lookup can be retried without creating a conversation', async t => {
let requests = 0;
const { client, opened } = restoreFixture({
readList: async () => {
if (++requests === 1) throw new Error('session list unavailable');
return { items: [{ id: 'recent' }] };
},
});
t.after(client.dispose);
assert.equal(await client.openInitial(), false);
assert.equal(client.getSnapshot().historyLoading, false);
assert.equal(client.getSnapshot().historyError, 'session list unavailable');
assert.equal(await client.openInitial(), true);
assert.equal(client.getSnapshot().historyError, '');
assert.equal(client.getSnapshot().sessionId, 'recent');
assert.deepEqual(opened, ['recent']);
});
test('starting a new conversation invalidates a pending automatic selection', async t => {
const list = deferred();
const { client, opened } = restoreFixture({ readList: () => list.promise });
t.after(client.dispose);
const opening = client.openInitial();
client.newSession();
list.resolve({ items: [{ id: 'recent' }] });
assert.equal(await opening, false);
assert.equal(client.getSnapshot().historyLoading, false);
assert.equal(client.getSnapshot().sessionId, '');
assert.deepEqual(opened, []);
});
+24 -114
View File
@@ -6,6 +6,7 @@ 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 { scrollTopFromVisualOffset, transcriptFollowState } from '../src/agent/transcriptScroll.ts';
import { sanitizeAnalysisDisplayText } from '../src/analysisDisplayText.ts';
import { modelThinkingEntries, thinkingStatus, orderedAnalysisProcess, groupAdjacentThinking } from '../src/analysisModelThinking.ts';
@@ -180,126 +181,35 @@ test('manual downward movement near the bottom resumes follow, while layout scro
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);
}
const viewport = (scrollTop, zoom = 1, scrollHeight = 2600) => ({
scrollTop, scrollHeight, clientHeight: 600, offsetHeight: 600,
getBoundingClientRect: () => ({ height: 600 * zoom }),
});
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('focusing and prepending history convert visual positions to layout pixels at each zoom', () => {
for (const zoom of [.8, 1, 1.25]) {
assert.equal(scrollTopFromVisualOffset(viewport(500, zoom), 316 * zoom, 16), 800);
assert.equal(scrollTopFromVisualOffset(viewport(500, zoom), 240 * zoom), 740);
}
});
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('follow remains active through new output when the reader stayed at the bottom', () => {
assert.deepEqual(transcriptFollowState(viewport(2000, 1, 2600), true, null), { follows: true, showLatest: false });
assert.deepEqual(transcriptFollowState(viewport(2000, 1, 3200), true, null), { follows: true, showLatest: 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('scrolling up keeps the reader in history as live output arrives', () => {
assert.deepEqual(transcriptFollowState(viewport(1000), true, 'up'), { follows: false, showLatest: true });
assert.deepEqual(transcriptFollowState(viewport(1000, 1, 3200), false, null), { follows: false, showLatest: true });
});
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('layout clamp cannot restore follow after the reader moved up', () => {
assert.deepEqual(transcriptFollowState(viewport(500, 1, 1100), false, null), { follows: false, showLatest: false });
});
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('returning downward near the end re-arms follow and clears the latest button', () => {
assert.deepEqual(transcriptFollowState(viewport(1960), false, 'down'), { follows: false, showLatest: true });
assert.deepEqual(transcriptFollowState(viewport(1980), false, 'down'), { follows: true, showLatest: false });
});
test('provider thinking is complete, escaped and separate from conclusions',()=>{
@@ -0,0 +1,339 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createAnalysisSessionClient } from '../src/agent/sessionClient.ts';
function deferred() {
let resolve, reject;
const promise = new Promise((yes, no) => { resolve = yes; reject = no; });
return { promise, resolve, reject };
}
async function until(condition, description) {
for (let i = 0; i < 100; i++) {
if (condition()) return;
await new Promise(resolve => setImmediate(resolve));
}
assert.fail(description || 'The expected session state was not reached');
}
const turn = (id, status = 'COMPLETED', extras = {}) => ({
id, status, question: 'Question ' + id, createdAt: '2026-11-11T04:05:06.001234Z', ...extras,
});
const snapshot = (id, turns, before = '', activeTurnId = '') => ({
id, title: id, turns, before, activeTurnId, context: { releaseId: 'release' },
});
function host(pages, overrides = {}) {
const connections = [];
const calls = { pages: [], cancels: [], starts: [], creates: [] };
const transport = {
analysisSessions: async () => ({ items: Object.keys(pages).map(id => ({ id, title: id })) }),
analysisSessionFollow: (id, { signal, onEvent }) => {
const stream = deferred();
const entry = { id, signal, emit: onEvent, close: stream.resolve, fail: stream.reject };
connections.push(entry);
signal.addEventListener('abort', () => stream.resolve(), { once: true });
if (pages[id]) onEvent({ event: 'snapshot', data: pages[id] });
return stream.promise;
},
analysisSessionPage: async (id, before) => {
calls.pages.push([id, before]);
return pages[id];
},
analysisTurn: async () => { throw new Error('Unexpected standalone turn request'); },
analysisTurnEvents: async () => { throw new Error('Unexpected fallback stream'); },
createAnalysisSession: async body => {
calls.creates.push(body);
return { session: { id: 'new', releaseId: 'release' } };
},
startAnalysisTurn: async (id, body) => {
calls.starts.push([id, body]);
return { turn: { id: 'new-turn', sessionId: id, status: 'QUEUED' } };
},
cancelAnalysisTurn: async id => {
calls.cancels.push(id);
return { turnId: id, status: 'CANCELLED', cancelRequested: true };
},
...overrides,
};
const client = createAnalysisSessionClient({ userId: 'actor', transport });
return { client, connections, calls };
}
test('the follow stream opens the tail in one snapshot and older pages cannot duplicate a focused turn', async t => {
const pages = { A: snapshot('A', [turn('5'), turn('6')], '5') };
let fullHistoryRequests = 0;
const detail = { ...turn('2'), sessionId: 'A', answer: 'historical' };
const { client } = host(pages, {
analysisTurn: async id => { assert.equal(id, '2'); return detail; },
analysisSessionPage: async (id, before) => {
fullHistoryRequests++;
assert.deepEqual([id, before], ['A', '5']);
return snapshot('A', [turn('1'), turn('2', 'COMPLETED', { result: { answer: 'refreshed history' } }), turn('3'), turn('4')]);
},
});
t.after(() => client.dispose());
assert.equal(await client.openSession('A', '2'), true);
const initial = client.getSnapshot();
assert.equal(client.getSnapshot(), initial);
assert.equal(fullHistoryRequests, 0);
assert.equal(initial.historyLoading, false);
assert.equal(initial.focusTurnId, '2');
assert.deepEqual(initial.turns.map(row => row.id), ['2', '5', '6']);
assert.equal(await client.loadOlder(), true);
const expanded = client.getSnapshot();
assert.equal(expanded.olderCursor, '');
assert.deepEqual(expanded.turns.map(row => row.id), ['1', '2', '3', '4', '5', '6']);
assert.equal(expanded.turns[1].answer, 'refreshed history');
});
test('draft replacements remain ephemeral and large durable cursors reject old events', async t => {
const pages = { A: snapshot('A', [turn('1', 'RUNNING', { eventCursor: '9007199254740994' })], '', '1') };
const { client, connections } = host(pages);
t.after(() => client.dispose());
await client.openSession('A');
const { emit } = connections[0];
emit({ event: 'draft', data: { turnId: '1', attemptId: 'p', text: 'unverified draft' } });
const draft = client.getSnapshot().turns[0];
assert.equal(draft.dshDraft, 'unverified draft');
assert.equal(draft.answer, undefined);
emit({ id: '9007199254740993', event: 'progress', data: { turnId: '1', message: 'stale event' } });
assert.equal(client.getSnapshot().turns[0], draft);
emit({ id: '9007199254740995', event: 'tool_result', data: { turnId: '1', status: 'COMPLETED', steps: [{ name: 'metric' }] } });
assert.equal(client.getSnapshot().busy, true);
assert.equal(client.getSnapshot().turns[0].eventCursor, '9007199254740995');
assert.equal(client.getSnapshot().turns[0].dshDraft, 'unverified draft');
emit({ id: '9007199254740996', event: 'completed', data: { turnId: '1', result: { answer: 'checked answer' } } });
emit({ event: 'draft', data: { turnId: '1', attemptId: 'p', text: 'late draft' } });
const result = client.getSnapshot().turns[0];
assert.equal(result.dshDraft, undefined);
assert.equal(result.result.answer, 'checked answer');
assert.equal(result.status, 'COMPLETED');
assert.equal(client.getSnapshot().busy, false);
});
test('switching and suspending abort reads without stopping a turn or accepting stale data', async t => {
const older = deferred();
const pages = { A: snapshot('A', [turn('4', 'RUNNING')], '4', '4'), B: snapshot('B', [turn('10')]) };
const { client, connections, calls } = host(pages, { analysisSessionPage: async () => older.promise });
t.after(() => client.dispose());
await client.openSession('A');
const loading = client.loadOlder();
await client.openSession('B');
const replacement = client.getSnapshot();
assert.equal(connections[0].signal.aborted, true);
older.resolve(snapshot('A', [turn('1'), turn('2'), turn('3')]));
assert.equal(await loading, false);
connections[0].emit({ event: 'draft', data: { turnId: '4', attemptId: 'a', text: 'unselected draft' } });
assert.equal(client.getSnapshot(), replacement);
client.suspend();
assert.equal(connections[1].signal.aborted, true);
assert.deepEqual(calls.cancels, []);
client.resume();
await until(() => connections.length === 3);
assert.equal(connections[2].id, 'B');
});
test('an uncertain submission reuses its receipt even after the server assigns the release', async t => {
const bodies = [];
const pages = { new: snapshot('new', []) };
const { client, calls } = host(pages, {
startAnalysisTurn: async (id, body) => {
assert.equal(id, 'new');
bodies.push(body);
if (bodies.length === 1) throw new Error('Connection ended before receipt');
pages.new = snapshot('new', [turn('new-turn', 'QUEUED')], '', 'new-turn');
return { turn: { id: 'new-turn', sessionId: id, status: 'QUEUED' } };
},
});
t.after(() => client.dispose());
assert.equal(await client.submit('同一个问题'), false);
assert.equal(client.getSnapshot().retryQuestion, '同一个问题');
assert.equal(client.getSnapshot().releaseId, 'release');
assert.equal(await client.submit('同一个问题', { releaseId: client.getSnapshot().releaseId }), true);
assert.deepEqual(bodies[0], bodies[1]);
assert.equal(calls.creates.length, 1);
});
test('a pending stop follows the accepted receipt across navigation and does not cancel the new session', async t => {
const receipt = deferred();
let posting = false;
const pages = { A: snapshot('A', []), B: snapshot('B', [turn('b', 'RUNNING')], '', 'b') };
const { client, calls } = host(pages, {
startAnalysisTurn: () => { posting = true; return receipt.promise; },
});
t.after(() => client.dispose());
await client.openSession('A');
const sending = client.submit('first');
await until(() => posting);
assert.equal(await client.cancel(), true);
await client.openSession('B');
receipt.resolve({ turn: { id: 'a', sessionId: 'A', status: 'RUNNING' } });
assert.equal(await sending, true);
assert.deepEqual(calls.cancels, ['a']);
assert.equal(client.getSnapshot().activeTurnId, 'b');
assert.equal(client.getSnapshot().sessionId, 'B');
});
test('the queued prompt waits for the durable completion and is submitted once with the new baseline context', async t => {
const pages = { A: snapshot('A', [turn('1', 'RUNNING', { eventCursor: '10' })], '', '1') };
const { client, connections, calls } = host(pages);
t.after(() => client.dispose());
await client.openSession('A');
assert.equal(await client.submit('next'), true);
assert.equal(client.getSnapshot().queuedQuestion, 'next');
assert.equal(calls.starts.length, 0);
const first = connections[0];
pages.A = { ...snapshot('A', [turn('1', 'COMPLETED')]), context: { releaseId: 'release', stage: 'black' } };
first.emit({ id: '11', event: 'completed', data: { turnId: '1', result: { answer: 'checked' } } });
first.close();
await until(() => connections.length >= 2);
connections[1].close();
await until(() => calls.starts.length === 1);
assert.equal(calls.starts[0][1].question, 'next');
assert.equal(calls.starts[0][1].context.stage, 'black');
assert.equal(client.getSnapshot().queuedQuestion, '');
});
test('restarting a saved turn drops the previous stream before reusing the same turn ID', async t => {
const receipt = deferred();
const pages = { A: snapshot('A', [turn('1', 'FAILED')]) };
const { client, connections } = host(pages, { retryAnalysisTurn: () => receipt.promise });
t.after(() => client.dispose());
await client.openSession('A');
const pending = client.retry('1');
assert.equal(connections[0].signal.aborted, true);
connections[0].emit({ id: '100', event: 'completed', data: { turnId: '1', result: { answer: 'old attempt' } } });
assert.equal(client.getSnapshot().turns[0].status, 'SUBMITTING');
pages.A = snapshot('A', [turn('1', 'QUEUED', { eventCursor: '110' })], '', '1');
receipt.resolve({ turn: { id: '1', sessionId: 'A', status: 'QUEUED' } });
assert.equal(await pending, true);
await until(() => connections.length === 2);
assert.equal(client.getSnapshot().turns[0].answer, undefined);
assert.equal(client.getSnapshot().turns[0].status, 'QUEUED');
});
test('the full original model answer survives summaries, draft clearing, and replacement snapshots', async t => {
const original = ' # 模型原文\n\n' + '完整分析内容。'.repeat(900) + '\n';
const pages = { A: snapshot('A', [turn('1', 'RUNNING', { eventCursor: '1' })], '', '1') };
const { client, connections } = host(pages);
t.after(() => client.dispose());
await client.openSession('A');
const { emit } = connections[0];
emit({ id: '2', event: 'progress', data: { turnId: '1', modelAnswer: original } });
emit({ event: 'draft', data: { turnId: '1', attemptId: 'attempt', text: 'temporary draft' } });
emit({ event: 'draft', data: { turnId: '1', attemptId: 'attempt', text: '' } });
assert.equal(client.getSnapshot().turns[0].modelAnswer, original);
assert.equal(client.getSnapshot().turns[0].dshDraft, undefined);
emit({ id: '3', event: 'completed', data: { turnId: '1', result: { answer: 'fixed summary' } } });
assert.equal(client.getSnapshot().turns[0].modelAnswer, original);
emit({ event: 'snapshot', data: snapshot('A', [turn('1', 'COMPLETED', { answer: 'another summary', eventCursor: '3' })]) });
const persisted = client.getSnapshot().turns[0];
assert.equal(persisted.modelAnswer, original);
assert.equal(persisted.status, 'COMPLETED');
});
test('cancelled and failed tasks retain the latest prose and accept a later full original', async t => {
for (const status of ['CANCELLED', 'FAILED', 'PARTIAL']) {
const pages = { A: snapshot('A', [turn('1', 'RUNNING', { eventCursor: '1' })], '', '1') };
const { client, connections } = host(pages);
t.after(() => client.dispose());
await client.openSession('A');
const { emit } = connections[0];
emit({ event: 'draft', data: { turnId: '1', attemptId: 'attempt', text: '模型已输出的原文' } });
emit({ id: '2', event: status.toLowerCase(), data: { turnId: '1', status, result: { answer: 'lifecycle message' } } });
let row = client.getSnapshot().turns[0];
assert.equal(row.modelAnswer, '模型已输出的原文');
assert.equal(row.dshDraft, undefined);
assert.equal(row.status, status);
emit({ id: '3', event: status.toLowerCase(), data: {
turnId: '1', status, result: { modelAnswer: '模型已输出的完整原文\n包含末尾文本', answer: 'summary' },
} });
row = client.getSnapshot().turns[0];
assert.equal(row.modelAnswer, '模型已输出的完整原文\n包含末尾文本');
assert.equal(row.eventCursor, '3');
assert.equal(row.status, status);
}
});
test('history and older-page refresh preserve explicit raw originals independently of summary answers', async t => {
const pages = { A: snapshot('A', [
turn('1', 'COMPLETED', { result: { modelAnswer: ' 已保存原文\n', answer: 'summary' } }),
turn('2'),
], '2') };
const { client } = host(pages, {
analysisSessionPage: async () => snapshot('A', [turn('1', 'COMPLETED', { result: { answer: 'updated summary', modelAnswer: '' } })]),
});
t.after(() => client.dispose());
await client.openSession('A');
assert.equal(client.getSnapshot().turns[0].modelAnswer, ' 已保存原文\n');
await client.loadOlder();
assert.equal(client.getSnapshot().turns[0].modelAnswer, ' 已保存原文\n');
});
test('retry clears the previous attempt original before the new attempt starts', async t => {
const receipt = deferred();
const pages = { A: snapshot('A', [turn('1', 'FAILED', { modelAnswer: 'previous attempt', dshDraft: 'old intermediate' })]) };
const { client } = host(pages, { retryAnalysisTurn: () => receipt.promise });
t.after(() => client.dispose());
await client.openSession('A');
const pending = client.retry('1');
assert.equal(client.getSnapshot().turns[0].modelAnswer, undefined);
assert.equal(client.getSnapshot().turns[0].dshDraft, undefined);
pages.A = snapshot('A', [turn('1', 'QUEUED')], '', '1');
receipt.resolve({ turn: { id: '1', sessionId: 'A', status: 'QUEUED' } });
await pending;
assert.equal(client.getSnapshot().turns[0].modelAnswer, undefined);
});
test('cancel refreshes the bounded final original tail after the terminal follow closes', async t => {
const original = 'original before cancellation';
const pages = { A: snapshot('A', [turn('1', 'RUNNING', { modelAnswer: original, attemptId: 'attempt' })], '', '1') };
let reads = 0;
const { client } = host(pages, {
cancelAnalysisTurn: async () => {
pages.A = snapshot('A', [turn('1', 'CANCELLED', { modelAnswer: original, attemptId: 'attempt' })]);
return { status: 'CANCELLED' };
},
analysisTurn: async () => {
reads++;
return { ...turn('1', 'CANCELLED', { attemptId: 'attempt', modelAnswer: reads === 1 ? original : original + '\nfinal 250ms tail' }), sessionId: 'A' };
},
});
t.after(() => client.dispose());
await client.openSession('A');
await client.cancel();
await new Promise(resolve => setTimeout(resolve, 1100));
assert.equal(reads, 2);
assert.equal(client.getSnapshot().turns[0].modelAnswer, original + '\nfinal 250ms tail');
});
test('a cancel-tail detail already in flight cannot overwrite a retried attempt', async t => {
const detail = deferred();
const pages = { A: snapshot('A', [turn('1', 'RUNNING', { attemptId: 'old' })], '', '1') };
let reads = 0;
const { client } = host(pages, {
cancelAnalysisTurn: async () => {
pages.A = snapshot('A', [turn('1', 'CANCELLED', { attemptId: 'old' })]);
return { status: 'CANCELLED' };
},
analysisTurn: () => { reads++; return detail.promise; },
retryAnalysisTurn: async () => {
const next = turn('1', 'QUEUED', { attemptId: 'new' });
pages.A = snapshot('A', [next], '', '1');
return { turn: next };
},
});
t.after(() => client.dispose());
await client.openSession('A');
await client.cancel();
await new Promise(resolve => setTimeout(resolve, 400));
assert.equal(reads, 1);
await client.retry('1');
detail.resolve({ ...turn('1', 'CANCELLED', { attemptId: 'old', modelAnswer: 'stale old tail' }), sessionId: 'A' });
await new Promise(resolve => setImmediate(resolve));
assert.equal(client.getSnapshot().turns[0].modelAnswer, undefined);
assert.equal(client.getSnapshot().turns[0].status, 'QUEUED');
});
+278 -171
View File
@@ -1,214 +1,321 @@
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';
import { beginAnalysisSubmission, submissionOutcomeUnknown } from '../src/analysisSubmission.ts';
import { createAnalysisSessionClient } from '../src/agent/sessionClient.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 }));
const deferred = () => {
let resolve, reject;
const promise = new Promise((yes, no) => { resolve = yes; reject = no; });
return { promise, resolve, reject };
};
const saved = (id, status, extras = {}) => ({ id, question: 'saved question', status, ...extras });
const page = (id, turns = [], extra = {}) => ({ id, turns, ...extra });
// 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);
function fixture(t, overrides = {}, initialPages = { 'session-1': page('session-1') }) {
const pages = { ...initialPages };
const requests = { starts: [], cancels: [], retries: [], follows: [] };
const transport = {
analysisSessions: async () => ({ items: Object.keys(pages).map(id => ({ id })) }),
analysisSessionFollow: (id, { signal, onEvent }) => {
const end = deferred();
requests.follows.push({ id, emit: onEvent, close: end.resolve });
signal.addEventListener('abort', end.resolve, { once: true });
onEvent({ event: 'snapshot', data: pages[id] || page(id) });
return end.promise;
},
createAnalysisSession: async () => ({ session: { id: 'session-1' } }),
startAnalysisTurn: async (id, body) => {
requests.starts.push({ id, ...body });
const turn = saved('turn-1', 'QUEUED', { sessionId: id, question: body.question });
pages[id] = page(id, [...(pages[id]?.turns || []), turn], { activeTurnId: turn.id });
return { turn };
},
retryAnalysisTurn: async id => { requests.retries.push(id); throw new Error('Unexpected retry'); },
cancelAnalysisTurn: async id => {
requests.cancels.push(id);
for (const [sessionId, previous] of Object.entries(pages)) {
const turns = previous.turns.map(turn => turn.id === id ? { ...turn, status: 'CANCELLED' } : turn);
pages[sessionId] = { ...previous, turns, activeTurnId: previous.activeTurnId === id ? '' : previous.activeTurnId };
}
return { status: 'CANCELLED', turnId: id };
},
...overrides,
};
const client = createAnalysisSessionClient({ userId: 'submission-fixture', transport });
t.after(client.dispose);
return { client, pages, requests, state: client.getSnapshot };
}
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('read-only history cannot submit or retry and keeps its saved turn', async t => {
const legacy = saved('legacy-turn', 'FAILED', { result: { answer: 'saved answer' } });
const { client, requests, state } = fixture(t, {}, { 'session-1': page('session-1', [legacy], { readOnly: true }) });
await client.openSession('session-1');
assert.equal(await client.submit('new question'), false);
assert.equal(await client.retry('legacy-turn'), false);
assert.deepEqual(requests.starts, []);
assert.deepEqual(requests.retries, []);
assert.equal(state().turns[0].result.answer, 'saved answer');
assert.equal(state().busy, false);
assert.equal(state().queuedQuestion, '');
});
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');
const input = { sessionId: 's', question: 'q', generation: 1, context: { month: 9, year: 2026 } };
const prior = beginAnalysisSubmission(null, input, () => 'first-key');
prior.uncertain = true;
prior.inFlight = false;
assert.equal(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(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);
for (const status of [400, 401, 403, 404, 409, 413, 422, 429]) assert.equal(submissionOutcomeUnknown({ status }), false);
for (const status of [0, 200, 408, 500, 502, 503]) assert.equal(submissionOutcomeUnknown({ status }), true);
assert.equal(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 during turn creation is fulfilled once the receipt identifies the turn', async t => {
const receipt = deferred();
const { client, pages, requests, state } = fixture(t, { startAnalysisTurn: () => receipt.promise });
await client.openSession('session-1');
const pending = client.submit('q');
await tick();
assert.equal(await client.cancel(), true);
assert.deepEqual(requests.cancels, []);
const turn = saved('turn-1', 'QUEUED');
pages['session-1'] = page('session-1', [turn], { activeTurnId: 'turn-1' });
receipt.resolve({ turn });
assert.equal(await pending, true);
assert.deepEqual(requests.cancels, ['turn-1']);
assert.equal(state().turns.at(-1).status, 'CANCELLED');
assert.equal(state().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('stop before the new session is created prevents a model turn from starting', async t => {
const created = deferred();
const { client, requests, state } = fixture(t, { createAnalysisSession: () => created.promise }, {});
const pending = client.submit('q');
assert.equal(await client.cancel(), true);
created.resolve({ session: { id: 'new-session' } });
assert.equal(await pending, false);
assert.deepEqual(requests.starts, []);
assert.deepEqual(state().turns, []);
assert.equal(state().pendingQuestion, '');
assert.equal(state().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('a follow-up waits for the accepted task to settle and then sends once', async t => {
const { client, requests, pages, state } = fixture(t);
await client.openSession('session-1');
assert.equal(await client.submit('initial question'), true);
await tick();
assert.equal(await client.submit('follow-up question'), true);
assert.equal(await client.submit('second queued question'), false);
assert.equal(state().queuedQuestion, 'follow-up question');
assert.deepEqual(requests.starts.map(request => request.question), ['initial question']);
pages['session-1'] = page('session-1', [saved('turn-1', 'COMPLETED', { question: 'initial question' })]);
const current = requests.follows.at(-1);
current.emit({ id: '1', event: 'completed', data: { turnId: 'turn-1', result: { answer: 'done' } } });
current.close();
await tick();
requests.follows.at(-1).close();
await tick();
assert.deepEqual(requests.starts.map(request => request.question), ['initial question', 'follow-up question']);
assert.equal(state().queuedQuestion, '');
});
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('session-list refresh cannot delay following or the stop target', async t => {
const list = deferred();
const { client, requests, state } = fixture(t, { analysisSessions: () => list.promise });
await client.openSession('session-1');
assert.equal(await client.submit('q'), true);
await tick();
assert.equal(state().sessionsLoading, true);
assert.equal(requests.follows.length, 2);
assert.equal(state().activeTurnId, 'turn-1');
assert.equal(await client.cancel(), true);
assert.deepEqual(requests.cancels, ['turn-1']);
list.resolve({ items: [] });
});
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('a lost accepted response retries the same key without archiving a phantom turn', async t => {
const bodies = [];
const { client, pages, state } = fixture(t, {
startAnalysisTurn: async (id, body) => {
bodies.push(body);
if (bodies.length === 1) throw Object.assign(new Error('service unavailable'), { status: 503 });
const turn = saved('original-turn', 'RUNNING', { question: body.question });
pages[id] = page(id, [turn], { activeTurnId: turn.id });
return { turn };
},
});
await client.openSession('session-1');
assert.equal(await client.submit('q'), false);
assert.equal(state().retryQuestion, 'q');
assert.equal(state().error, 'service unavailable');
assert.equal(state().busy, false);
assert.equal(state().activeTurnId, '');
assert.deepEqual(state().turns, []);
assert.equal(await client.submit(state().retryQuestion), true);
assert.equal(bodies.length, 2);
assert.equal(bodies[0].idempotencyKey, bodies[1].idempotencyKey);
assert.deepEqual(state().turns.map(turn => turn.id), ['original-turn']);
});
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('an explicit 400 rejection gives the same editable question a fresh key without showing it as running', async t => {
const keys = [];
const { client, state } = fixture(t, {
startAnalysisTurn: async (_id, body) => {
keys.push(body.idempotencyKey);
throw Object.assign(new Error('invalid question'), { status: 400 });
},
});
await client.openSession('session-1');
assert.equal(await client.submit('rejected question'), false);
assert.equal(state().retryQuestion, 'rejected question');
assert.equal(state().error, 'invalid question');
assert.equal(state().busy, false);
assert.deepEqual(state().turns, []);
assert.equal(await client.submit(state().retryQuestion), false);
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('a pending stop applies only to its original turn after navigation', async t => {
const receipt = deferred();
const { client, requests, state } = fixture(t, { startAnalysisTurn: () => receipt.promise });
await client.openSession('session-1');
const pending = client.submit('q');
await tick();
assert.equal(await client.cancel(), true);
await client.openSession('session-2');
receipt.resolve({ turn: saved('old-turn', 'RUNNING', { sessionId: 'session-1' }) });
assert.equal(await pending, true);
assert.deepEqual(requests.cancels, ['old-turn']);
assert.deepEqual(state().turns, []);
assert.equal(state().activeTurnId, '');
assert.equal(state().sessionId, 'session-2');
});
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('stop during retry waits for requeue and targets the original saved turn', async t => {
const receipt = deferred();
const savedTurn = saved('partial-turn', 'PARTIAL');
const { client, pages, requests, state } = fixture(t, { retryAnalysisTurn: () => receipt.promise }, {
'session-1': page('session-1', [savedTurn, saved('newest-turn', 'COMPLETED')]),
});
await client.openSession('session-1');
const pending = client.retry('partial-turn');
assert.equal(await client.cancel(), true);
assert.deepEqual(requests.cancels, []);
const turn = { ...savedTurn, status: 'QUEUED' };
pages['session-1'] = page('session-1', [turn, saved('newest-turn', 'COMPLETED')], { activeTurnId: 'partial-turn' });
receipt.resolve({ turn });
assert.equal(await pending, true);
assert.deepEqual(requests.cancels, ['partial-turn']);
assert.equal(state().busy, false);
assert.equal(state().turns.find(row => row.id === 'partial-turn').status, 'CANCELLED');
});
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('a late cancellation failure cannot put an error in a newly selected session', async t => {
const cancel = deferred();
const { client, state } = fixture(t, { cancelAnalysisTurn: () => cancel.promise });
await client.openSession('session-1');
await client.submit('q');
const stopping = client.cancel();
await client.openSession('other');
cancel.reject(new Error('cancellation response lost'));
assert.equal(await stopping, false);
assert.equal(state().error, '');
assert.deepEqual(state().turns, []);
});
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('repeated stop clicks share one request until the task settles', async t => {
const cancellation = deferred();
let count = 0;
const { client, pages, state } = fixture(t, { cancelAnalysisTurn: () => { count++; return cancellation.promise; } });
await client.openSession('session-1');
await client.submit('q');
const first = client.cancel();
assert.equal(await client.cancel(), false);
assert.equal(count, 1);
assert.equal(state().stopping, true);
pages['session-1'] = page('session-1', [saved('turn-1', 'CANCELLED')]);
cancellation.resolve({ status: 'CANCELLED', turnId: 'turn-1' });
assert.equal(await first, true);
assert.equal(state().busy, false);
});
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('stopping keeps the queued question available for editing and does not send it', async t => {
const { client, requests, state } = fixture(t);
await client.openSession('session-1');
await client.submit('initial');
await client.submit('queued follow-up');
await client.cancel();
await tick();
requests.follows.at(-1).close();
await tick();
assert.equal(state().queuedQuestion, 'queued follow-up');
assert.deepEqual(requests.starts.map(request => request.question), ['initial']);
assert.equal(client.takeQueued(), 'queued follow-up');
assert.equal(state().queuedQuestion, '');
});
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('a failed stop request allows another explicit stop attempt', async t => {
let count = 0;
const { client, pages, state } = fixture(t, {
cancelAnalysisTurn: async id => {
if (++count === 1) throw new Error('offline');
pages['session-1'] = page('session-1', [saved(id, 'CANCELLED')]);
return { status: 'CANCELLED', turnId: id };
},
});
await client.openSession('session-1');
await client.submit('initial');
assert.equal(await client.cancel(), false);
assert.equal(state().stopping, false);
assert.equal(state().busy, true);
assert.equal(await client.cancel(), true);
assert.equal(count, 2);
assert.equal(state().busy, false);
});
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.doesNotMatch(html,/提交结果暂未确认/);
assert.doesNotMatch(html,/排队中|正在准备分析|仍在运行/);
assert.equal(ui.get().lastTurn.status,undefined);
test('a fresh submission immediately carries waiting status and a clock before acceptance', async t => {
const receipt = deferred();
const { client, pages, state } = fixture(t, { startAnalysisTurn: () => receipt.promise });
await client.openSession('session-1');
const pending = client.submit('即时状态');
assert.equal(state().turns.at(-1).status, 'SUBMITTING');
assert.ok(Number.isFinite(Date.parse(state().turns.at(-1)._uiSubmittedAt)));
const turn = saved('accepted', 'RUNNING', { question: '即时状态', createdAt: new Date().toISOString() });
pages['session-1'] = page('session-1', [turn], { activeTurnId: turn.id });
receipt.resolve({ turn });
assert.equal(await pending, true);
assert.equal(state().turns.at(-1).id, 'accepted');
assert.ok(Number.isFinite(Date.parse(state().turns.at(-1).createdAt)));
});
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.doesNotMatch(html,/本次提交未成功/);
assert.doesNotMatch(html,/排队中|正在准备分析|仍在运行|恢复原任务/);
assert.equal(ui.get().lastTurn.status,undefined);
});
test('a fresh submission immediately carries waiting status and a clock before acceptance',async()=>{
const pending=deferred();const ui=fixture({startAnalysisTurn:()=>pending.promise});
const work=ui.submit('即时状态');assert.equal(ui.get().lastTurn.status,'SUBMITTING');
assert.ok(Number.isFinite(Date.parse(ui.get().lastTurn._uiSubmittedAt)));
pending.resolve({turn:{id:'accepted',status:'RUNNING'}});await work;
assert.ok(Number.isFinite(Date.parse(ui.get().lastTurn._uiSubmittedAt)));
});
test('retry starts a fresh waiting clock without displaying the old body or plan clock',async()=>{
const response=deferred();const ui=fixture({retryAnalysisTurn:()=>response.promise,analysisTurn:async()=>({id:'old',status:'QUEUED'})});
const work=ui.retryTurn({id:'old',status:'PARTIAL',answer:'old text',createdAt:'2020-01-01T00:00:00Z',startedAt:'2020-01-01T00:00:01Z',plan:{startedAt:'2020-01-01T00:00:01Z'}});
assert.equal(ui.get().lastTurn.status,'SUBMITTING');assert.equal(ui.get().lastTurn.answer,undefined);assert.equal(ui.get().lastTurn.plan,undefined);
response.resolve({turn:{id:'old',sessionId:'session-1',status:'QUEUED'}});await work;
test('retry starts a fresh waiting clock without the old answer or plan clock', async t => {
const receipt = deferred();
const old = saved('old', 'PARTIAL', {
answer: 'old text', createdAt: '2020-01-01T00:00:00Z', startedAt: '2020-01-01T00:00:01Z',
plan: { startedAt: '2020-01-01T00:00:01Z' },
});
const { client, pages, state } = fixture(t, { retryAnalysisTurn: () => receipt.promise }, {
'session-1': page('session-1', [old]),
});
await client.openSession('session-1');
const pending = client.retry('old');
const current = state().turns[0];
assert.equal(current.status, 'SUBMITTING');
assert.ok(Number.isFinite(Date.parse(current._uiSubmittedAt)));
assert.equal(current.answer, undefined);
assert.equal(current.plan, undefined);
assert.equal(current.startedAt, undefined);
const turn = saved('old', 'QUEUED');
pages['session-1'] = page('session-1', [turn], { activeTurnId: turn.id });
receipt.resolve({ turn });
assert.equal(await pending, true);
});
@@ -8,14 +8,14 @@ const saved=()=>({id:'turn1',status:'PARTIAL',question:'原问题',plan:{protoco
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};
function fixture(request,auto=false){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;};
const render=()=>{let n=0;do{dirty=false;queue=[];cursor=0;value=useHook(source,denied,auto);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.
@@ -32,3 +32,14 @@ test('a duplicate click recovers only charts and retains facts',async()=>{const
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();}});
test('a completed empty aggregate selection has no chart retry while real chart errors remain recoverable',()=>{
const ui=fixture(async()=>{throw Error('should not query');});ui.render();
const value={...ui.source,status:'COMPLETED',visualState:'not_requested',plan:{...ui.source.plan,task:{kind:'analysis',executionMode:'native_agent',visualPreference:'auto',aggregateSelection:{metric:'rate'}}}};
ui.replace(value);assert.equal(ui.value.available,false);
ui.replace({...value,visualState:'failed'});assert.equal(ui.value.available,true);ui.unmount();
});
test('automatic presentation recovery runs once per saved execution and retains the original answer on failure',async()=>{
const ui=fixture(async()=>{throw Error('temporary chart failure');},true);
ui.render();await ui.settle();await ui.settle();assert.equal(ui.calls.api,1);
assert.equal(ui.value.turn.answer,'原答案');assert.equal(ui.value.turn.visualState,'failed');ui.unmount();
});
@@ -85,6 +85,11 @@ test('late authorization for an older snapshot cannot remount or overwrite a cha
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('quiet chart failures remove the card and expose no error or retry controls',async()=>{
const ui=fixture();ui.props.quiet=true;ui.render();const tree=await ui.settle();
assert.equal(tree,null);assert.doesNotMatch(text(tree),/failed|重试|失败/);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);
});
+1 -1
View File
@@ -1,7 +1,7 @@
import { defineConfig } from 'vite';
const apiTarget = process.env.QUALITY_DEV_API_TARGET || 'http://127.0.0.1:5281';
if (!/^http:\/\/127\.0\.0\.1:(5281|5283|5284|5285)$/.test(apiTarget)) throw new Error('Unsupported local API target');
if (!/^http:\/\/127\.0\.0\.1:(5281|5283|5284|5285|5287)$/.test(apiTarget)) throw new Error('Unsupported local API target');
export default defineConfig({
server: {