统一:DSH 智能分析、Top100 与图表静默恢复
接入 DSH 专用运行时和对话界面,保留模型原始回答,支持会话分页、连续追问与显式报告。 补齐组合筛选、各维度 Top100、分组查询到排名图的转换,图表故障静默省略并基于保存数据自动恢复。 优化报告风格、图表顺序和表格换行,更新接入说明及构建输入。 验证:独立目录前后端构建通过;118 项 Java、102 项前端、102 项图表、14 项 DSH 应用和 13 项组合筛选检查通过。 仅提交相关源码、锁定依赖与测试;不包含凭据、会话、业务数据或本地产物。
This commit is contained in:
+27
-5
@@ -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;
|
||||
|
||||
@@ -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> : <>
|
||||
|
||||
@@ -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">
|
||||
|
||||
@@ -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>;
|
||||
}
|
||||
@@ -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]);
|
||||
|
||||
@@ -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('');
|
||||
|
||||
@@ -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>;
|
||||
}
|
||||
|
||||
|
||||
@@ -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>;
|
||||
|
||||
+4
-992
File diff suppressed because it is too large
Load Diff
@@ -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>;
|
||||
});
|
||||
@@ -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 => ({ '&': '&', '<': '<', '>': '>' }[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>;
|
||||
}
|
||||
@@ -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>;
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
@@ -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) };
|
||||
}
|
||||
@@ -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 : '分析条件链接无法读取' };
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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}
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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' };
|
||||
|
||||
@@ -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 };
|
||||
}
|
||||
|
||||
|
||||
@@ -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}质量分析报告` : '质量分析报告');
|
||||
}
|
||||
|
||||
@@ -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,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)};
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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 } : {});
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user