完善:质量分析平台查询与分析功能
This commit is contained in:
+203
-99
@@ -1,5 +1,6 @@
|
||||
import { FilterFieldSettings } from './FilterFieldSettings';
|
||||
import { isInternalDataField, publicJson } from './publicDataDisplay';
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import {
|
||||
Alert,
|
||||
App,
|
||||
@@ -16,11 +17,11 @@ import {
|
||||
Select,
|
||||
Spin,
|
||||
Switch,
|
||||
Table,
|
||||
Tabs,
|
||||
Tag,
|
||||
} from 'antd';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
import { QualityTable as Table } from './QualityTable';
|
||||
import { DeleteOutlined, DownloadOutlined, ReloadOutlined, RobotOutlined } from '@ant-design/icons';
|
||||
import { ApiError, api, collectionItems, decodeQueryValueList } from './api';
|
||||
import type { AuthUser, Collection, OptionsResponse, QueryParams, SourceItem, ViewKind } from './types';
|
||||
@@ -32,10 +33,12 @@ import { TargetVersionAdmin } from './AnalyticsCompletion';
|
||||
import { AnalysisReportExport, NativeAnalysisReport } from './AnalysisReportExport';
|
||||
import { AiMarkdown } from './AiMarkdown';
|
||||
import { AnalysisApiSettings } from './AnalysisApiSettings';
|
||||
import { AnalysisProcess } from './AnalysisProcess';
|
||||
import { activeAnalysisTurn, analysisIsRunning, beginAnalysisSelection, defaultAnalysisSession, rememberAnalysisSession, rememberPendingAnalysisSession, settledAnalysisTurn } from './analysisConversationState';
|
||||
import './analysis-chat.css';
|
||||
|
||||
const TABLE_PAGE_SIZE = 20;
|
||||
import { DataWorkflowHub, MasterWorkbookUpload, ReadableConfigDefinition, SourceFilesPanel } from './NoCodeDataWorkflow';
|
||||
import { DataWorkflowHub, MasterWorkbookUpload, ReadableConfigDefinition, SourceFilesPanel, type PendingSourceDeletion } from './NoCodeDataWorkflow';
|
||||
import { MappingDefinitionEditor, MasterDataDefinitionEditor, MatchRulesDefinitionEditor, RuleDefinitionEditor, TechnicalDefinitionEditor, validateStructuredMappingDefinition, type ConfigDefinition } from './StructuredConfigEditors';
|
||||
import { useDataWorkflowOperation } from './useDataWorkflowOperation';
|
||||
import { BackupOperationsPanel, CostConfigurationPanel, OperationsMonitorPanel, ServiceIdentityPanel, SourceGovernancePanel, UserAccessPolicyPanel } from './GovernanceCompletion';
|
||||
@@ -60,7 +63,7 @@ function restoredAnalysisTurns(history: Record<string, unknown>, metadata: Colle
|
||||
return collectionItems(metadata).slice().reverse().map(turn => {
|
||||
const found = saved.find(item => item.id === turn.id);
|
||||
const answer = found && isObjectRecord(found.result) ? found.result : {};
|
||||
return { ...answer, ...turn, sessionId: history.id };
|
||||
return { ...found, ...answer, ...turn, sessionId: history.id };
|
||||
});
|
||||
}
|
||||
|
||||
@@ -104,6 +107,7 @@ function decodeAnalysisLinkContext(encoded: string | null): AnalysisLinkContext
|
||||
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;
|
||||
@@ -163,7 +167,7 @@ function unwrapItems(value: unknown): { items: Record<string, unknown>[]; total?
|
||||
return { items: [] };
|
||||
}
|
||||
|
||||
function DynamicTable({ items, rowKey = 'id', paginate = true }: { items: Record<string, unknown>[]; rowKey?: string; paginate?: boolean }) {
|
||||
function DynamicTable({ items, rowKey = 'id', paginate = true, indexOffset = 0 }: { items: Record<string, unknown>[]; rowKey?: string; paginate?: boolean; indexOffset?: number }) {
|
||||
const keys = useMemo(() => {
|
||||
const discovered = new Set<string>();
|
||||
for (const item of items.slice(0, 30)) Object.keys(item).filter(key => !isInternalDataField(key)).forEach(key => discovered.add(key));
|
||||
@@ -185,7 +189,7 @@ function DynamicTable({ items, rowKey = 'id', paginate = true }: { items: Record
|
||||
render: value => readableValue(value),
|
||||
}));
|
||||
return items.length
|
||||
? <div className="resource-table"><Table size="small" bordered columns={columns} dataSource={items} rowKey={item => String(item[rowKey] ?? JSON.stringify(item))} pagination={paginate ? { pageSize: TABLE_PAGE_SIZE, showSizeChanger: false } : false} scroll={{ x: 'max-content' }} />
|
||||
? <div className="resource-table"><Table size="small" bordered columns={columns} dataSource={items} rowKey={item => String(item[rowKey] ?? JSON.stringify(item))} pagination={paginate ? { pageSize: TABLE_PAGE_SIZE, showSizeChanger: false } : false} indexOffset={indexOffset} scroll={{ x: 'max-content' }} />
|
||||
<p className="table-caption">显示服务端返回的 {items.length} 条记录</p></div>
|
||||
: <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="服务端当前返回空列表" />;
|
||||
}
|
||||
@@ -194,12 +198,12 @@ export default function ManagementPages({ page, user, onUnauthorized, onNavigate
|
||||
page: PageKey; user: AuthUser; onUnauthorized: (error: unknown) => boolean;
|
||||
onNavigate: (page: PageKey) => void;
|
||||
}) {
|
||||
if (page === 'sources') return <SourcesPage onUnauthorized={onUnauthorized} user={user} />;
|
||||
if (page === 'sources' || page === 'imports') return <SourcesPage onUnauthorized={onUnauthorized} user={user} />;
|
||||
if (page === 'analysis') return <AnalysisPage onUnauthorized={onUnauthorized} user={user} />;
|
||||
if (page === 'access') return <AccessPage user={user} onUnauthorized={onUnauthorized} />;
|
||||
if (page === 'basis') return <BasisPage onUnauthorized={onUnauthorized} />;
|
||||
if (page === 'rules') return <><ConfigManagementPage kind={page} user={user} onUnauthorized={onUnauthorized} onNavigate={onNavigate} /><MetricDictionaryPanel user={user} onUnauthorized={onUnauthorized} />{user.roles.some(role => ['SYSTEM_ADMIN', 'RULE_MAINTAINER'].includes(role)) && <TargetVersionAdmin onUnauthorized={onUnauthorized} />}</>;
|
||||
if (page === 'masterData') return <ConfigManagementPage kind={page} user={user} onUnauthorized={onUnauthorized} onNavigate={onNavigate} />;
|
||||
if (page === 'masterData') return <><FilterFieldSettings canManage={user.roles.some(role => ['SYSTEM_ADMIN','DATA_MAINTAINER'].includes(role))} onUnauthorized={onUnauthorized} /><ConfigManagementPage kind={page} user={user} onUnauthorized={onUnauthorized} onNavigate={onNavigate} /></>;
|
||||
if (page === 'mappings') return <><ConfigManagementPage kind={page} user={user} onUnauthorized={onUnauthorized} onNavigate={onNavigate} /><MappingIssueResolutionPanel user={user} onUnauthorized={onUnauthorized} /><CostConfigurationPanel user={user} onUnauthorized={onUnauthorized} /></>;
|
||||
const resource: Record<string, { endpoint: 'imports' | 'tasks'; title: string; subtitle: string }> = {
|
||||
imports: { endpoint: 'imports', title: '导入与校验记录', subtitle: '接收后的来源文件及其校验任务状态。' },
|
||||
@@ -218,6 +222,22 @@ function SourcesPage({ onUnauthorized, user }: { onUnauthorized: (error: unknown
|
||||
const [currentReleaseId, setCurrentReleaseId] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState('');
|
||||
const [maintenanceBusy, setMaintenanceBusy] = useState(false);
|
||||
const [historyOpen, setHistoryOpen] = useState(() => new URLSearchParams(window.location.search).get('showImportHistory') === '1');
|
||||
const pendingKey = `quality-pending-source-deletions:${user.id}`;
|
||||
const [pendingDeletion, setPendingDeletion] = useState<PendingSourceDeletion>(() => {
|
||||
try {
|
||||
const saved = JSON.parse(localStorage.getItem(pendingKey) || 'null');
|
||||
if (saved && Array.isArray(saved.ids) && saved.ids.length <= 50 && saved.ids.every((id: unknown) => typeof id === 'string') && (saved.releaseId === null || typeof saved.releaseId === 'string')) return saved;
|
||||
} catch { /* Pending changes are optional when storage is unavailable. */ }
|
||||
return { ids: [], releaseId: null };
|
||||
});
|
||||
useEffect(() => { try { if (pendingDeletion.ids.length) localStorage.setItem(pendingKey, JSON.stringify(pendingDeletion)); else localStorage.removeItem(pendingKey); } catch { /* Keep in-memory changes available. */ } }, [pendingKey, pendingDeletion]);
|
||||
const onDeleted = useCallback((ids: string[]) => setPendingDeletion(previous => ({ ...previous, ids: previous.ids.filter(id => !ids.includes(id)) })), []);
|
||||
const toggleDelete = (id: string) => setPendingDeletion(previous => previous.ids.includes(id)
|
||||
? { ...previous, ids: previous.ids.filter(value => value !== id) }
|
||||
: previous.ids.length >= 50 ? previous : { ids: [...previous.ids, id], releaseId: previous.ids.length ? previous.releaseId : currentReleaseId });
|
||||
|
||||
const load = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
@@ -228,14 +248,31 @@ function SourcesPage({ onUnauthorized, user }: { onUnauthorized: (error: unknown
|
||||
};
|
||||
useEffect(() => { void load(); }, []);
|
||||
return <div className="management-page">
|
||||
<PageHeader title="数据接入" description="上传、替换和发布质量数据;按向导完成,无需改文件名或填写技术配置。" actions={<Button icon={<ReloadOutlined />} onClick={() => void load()}>刷新</Button>} />
|
||||
{error && <Alert showIcon type="error" message="来源清单读取失败" description={error} action={<Button size="small" onClick={() => void load()}>重试</Button>} />}
|
||||
<DataWorkflowHub user={user} sources={sources} currentReleaseId={currentReleaseId} onUnauthorized={onUnauthorized} onRefresh={() => void load()} />
|
||||
<SourceFilesPanel user={user} sources={sources} loading={loading} onUnauthorized={onUnauthorized} onRefresh={() => void load()} />
|
||||
<DataWorkflowHub user={user} sources={sources} currentReleaseId={currentReleaseId} pendingDeletion={pendingDeletion} onDeleted={onDeleted} onBusyChange={setMaintenanceBusy} onUnauthorized={onUnauthorized} onRefresh={() => void load()} />
|
||||
<SourceFilesPanel user={user} sources={sources} loading={loading} pendingIds={pendingDeletion.ids} maintenanceBusy={maintenanceBusy} onToggleDelete={toggleDelete} onClearDeletes={() => setPendingDeletion({ ids: [], releaseId: null })} onUnauthorized={onUnauthorized} onRefresh={() => void load()} />
|
||||
<details className="nc-advanced-records" open={historyOpen} onToggle={event => setHistoryOpen(event.currentTarget.open)}><summary>导入记录与失败详情</summary>{historyOpen && <ImportHistoryPanel user={user} currentReleaseId={currentReleaseId} onUnauthorized={onUnauthorized} />}</details>
|
||||
<details className="nc-advanced-records"><summary>高级来源记录与审计</summary><SourceGovernancePanel user={user} currentReleaseId={currentReleaseId} onUnauthorized={onUnauthorized} /></details>
|
||||
</div>;
|
||||
}
|
||||
|
||||
function ImportHistoryPanel({ user, currentReleaseId, onUnauthorized }: { user: AuthUser; currentReleaseId: string | null; onUnauthorized: (error: unknown) => boolean }) {
|
||||
const [items, setItems] = useState<Record<string, unknown>[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState('');
|
||||
const load = useCallback(async () => {
|
||||
try { const result = unwrapItems(await api.tasks()); setItems(result.items.filter(item => String(item.type).toUpperCase() === 'IMPORT')); setError(''); }
|
||||
catch (value) { if (!onUnauthorized(value)) setError(apiMessage(value)); }
|
||||
finally { setLoading(false); }
|
||||
}, [onUnauthorized]);
|
||||
useEffect(() => { void load(); }, [load, currentReleaseId]);
|
||||
useEffect(() => { if (items.some(item => ['QUEUED', 'RUNNING'].includes(String(item.status).toUpperCase()))) { const timer = window.setTimeout(() => void load(), 2000); return () => window.clearTimeout(timer); } }, [items, load]);
|
||||
return <section className="panel section-panel"><div className="resource-toolbar"><strong>导入记录</strong><span>{items.length} 条 · 可查看处理结果和逐行校验问题</span></div>
|
||||
{error && <Alert showIcon type="error" message="导入记录读取失败" description={error} action={<Button onClick={() => void load()}>重试</Button>} />}
|
||||
{loading ? <Spin /> : <TaskTable items={items} importOnly user={user} onUnauthorized={onUnauthorized} onRefresh={() => void load()} />}
|
||||
</section>;
|
||||
}
|
||||
|
||||
function ImportIssuesDrawer({ runId, onClose, onUnauthorized }: { runId: string; onClose: () => void; onUnauthorized: (error: unknown) => boolean }) {
|
||||
const [result, setResult] = useState<Collection | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
@@ -253,7 +290,7 @@ function ImportIssuesDrawer({ runId, onClose, onUnauthorized }: { runId: string;
|
||||
const items = unwrapItems(result).items;
|
||||
return <Drawer className="management-drawer" open={Boolean(runId)} title="导入校验问题" width={Math.min(900, window.innerWidth)} onClose={onClose}>
|
||||
{error && <Alert showIcon type="error" message="问题清单读取失败" description={error} />}
|
||||
{loading ? <div className="loading-panel"><Spin />正在读取问题行…</div> : <DynamicTable items={items} paginate={false} />}
|
||||
{loading ? <div className="loading-panel"><Spin />正在读取问题行…</div> : <DynamicTable items={items} paginate={false} indexOffset={(page - 1) * TABLE_PAGE_SIZE} />}
|
||||
{result?.total && result.total > TABLE_PAGE_SIZE && <Pagination className="records-pagination" current={page} pageSize={TABLE_PAGE_SIZE} total={result.total} showTotal={count => `共 ${count} 条问题`} onChange={setPage} />}
|
||||
</Drawer>;
|
||||
}
|
||||
@@ -702,7 +739,7 @@ function MappingIssueResolutionPanel({ user, onUnauthorized }: { user: AuthUser;
|
||||
<PageHeader title="未命中映射问题" description="按源键汇总真实未命中行;裁决会创建独立映射草稿,不直接修改已发布事实。" actions={<div className="completion-actions"><Select aria-label="映射问题状态" value={status} options={[{ label: '待处理', value: 'OPEN' }, { label: '已裁决', value: 'DECIDED' }, { label: '已退回', value: 'RETURNED' }, { label: '已重验', value: 'REVALIDATED' }, { label: '全部状态', value: '' }]} onChange={value => { setStatus(value); setPage(1); }} /><Button icon={<ReloadOutlined />} onClick={() => void load()}>刷新</Button></div>} />
|
||||
{error && <Alert showIcon type="error" message="映射问题操作失败" description={error} />}
|
||||
{!canResolve && <Alert showIcon type="info" message="当前账号仅可查看" description="问题裁决需映射维护、数据维护或系统管理授权。" />}
|
||||
<section className="panel section-panel"><div className="resource-toolbar"><strong>源键命中汇总</strong><span>共 {total} 条</span></div>{loading ? <div className="loading-panel"><Spin />正在读取未命中问题…</div> : items.length ? <div className="resource-table"><Table size="small" bordered columns={columns} dataSource={items} rowKey={row => String(row.id)} pagination={false} scroll={{ x: 1050 }} /></div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前状态没有未命中映射问题" />}{total > TABLE_PAGE_SIZE && <Pagination className="records-pagination" current={page} pageSize={TABLE_PAGE_SIZE} total={total} showTotal={count => `共 ${count} 条问题`} onChange={setPage} />}</section>
|
||||
<section className="panel section-panel"><div className="resource-toolbar"><strong>源键命中汇总</strong><span>共 {total} 条</span></div>{loading ? <div className="loading-panel"><Spin />正在读取未命中问题…</div> : items.length ? <div className="resource-table"><Table size="small" bordered columns={columns} dataSource={items} rowKey={row => String(row.id)} pagination={false} indexOffset={(page - 1) * TABLE_PAGE_SIZE} scroll={{ x: 1050 }} /></div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前状态没有未命中映射问题" />}{total > TABLE_PAGE_SIZE && <Pagination className="records-pagination" current={page} pageSize={TABLE_PAGE_SIZE} total={total} showTotal={count => `共 ${count} 条问题`} onChange={setPage} />}</section>
|
||||
<Drawer className="management-drawer" open={Boolean(selectedId)} title="未命中映射问题处理" width={Math.min(1000, window.innerWidth)} onClose={() => { setSelectedId(''); setDetail(null); }}>
|
||||
{!detail ? <div className="completion-loading"><Spin />读取源键命中与历史裁决…</div> : <>
|
||||
<div className="governance-monitor-grid"><div><small>源键</small><strong>{toText(issue.sourceKey)}</strong></div><div><small>映射类型</small><strong>{toText(issue.mappingType)}</strong></div><div><small>汇总行数</small><strong>{toText(issue.rowCount)}</strong></div><div><small>总重量</small><strong>{toText(issue.totalWeight)}</strong></div></div>
|
||||
@@ -879,12 +916,13 @@ function TaskTable({ items, importOnly, user, onUnauthorized, onRefresh }: { ite
|
||||
} catch (error) { if (!onUnauthorized(error)) message.error(apiMessage(error)); if (error instanceof ApiError && error.status === 409) onRefresh(); }
|
||||
finally { setBusyId(''); }
|
||||
};
|
||||
const importState = (value: unknown) => ({ COMPLETED: '导入完成', SUCCEEDED: '导入完成', FAILED: '导入失败', ERROR: '导入失败', RUNNING: '正在导入', QUEUED: '等待导入', CANCELLED: '已取消' }[String(value).toUpperCase()] || toText(value));
|
||||
const columns: ColumnsType<Record<string, unknown>> = [
|
||||
{ title: '任务 ID', dataIndex: 'id', key: 'id', fixed: 'left', width: 220, ellipsis: true },
|
||||
{ title: '任务类型', dataIndex: 'type', key: 'type', width: 130 },
|
||||
{ title: '状态', dataIndex: 'status', key: 'status', width: 130, render: value => <Tag color={String(value).toUpperCase().includes('FAIL') || String(value).toUpperCase() === 'ERROR' ? 'red' : String(value).toUpperCase() === 'SUCCEEDED' || String(value).toUpperCase() === 'COMPLETED' ? 'green' : 'blue'}>{toText(value)}</Tag> },
|
||||
{ title: '状态', dataIndex: 'status', key: 'status', width: 130, render: value => <Tag color={String(value).toUpperCase().includes('FAIL') || String(value).toUpperCase() === 'ERROR' ? 'red' : String(value).toUpperCase() === 'SUCCEEDED' || String(value).toUpperCase() === 'COMPLETED' ? 'green' : 'blue'}>{importOnly ? importState(value) : toText(value)}</Tag> },
|
||||
{ title: '处理阶段', dataIndex: 'stage', key: 'stage', width: 150 },
|
||||
{ title: '进度(服务端)', dataIndex: 'progress', key: 'progress', width: 145, align: 'right' },
|
||||
{ title: importOnly ? '进度' : '进度(服务端)', dataIndex: 'progress', key: 'progress', width: 145, align: 'right', render: value => importOnly ? `${toText(value)}%` : toText(value) },
|
||||
{ title: '已处理 / 总数', key: 'processed', width: 140, align: 'right', render: (_, row) => `${toText(row.processed)} / ${toText(row.total)}` },
|
||||
{ title: '错误码', dataIndex: 'errorCode', key: 'errorCode', width: 150, render: value => value ? <Tag color="red">{toText(value)}</Tag> : '—' },
|
||||
{ title: '错误信息', dataIndex: 'errorMessage', key: 'errorMessage', width: 300, ellipsis: true, render: value => value ? <span className="task-error">{toText(value)}</span> : '—' },
|
||||
@@ -897,10 +935,10 @@ function TaskTable({ items, importOnly, user, onUnauthorized, onRefresh }: { ite
|
||||
</span> },
|
||||
];
|
||||
return <>
|
||||
{items.length ? <div className="resource-table"><Table size="small" bordered columns={columns} dataSource={items} rowKey={row => String(row.id ?? JSON.stringify(row))} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 1600 }} />
|
||||
<p className="table-caption">错误信息、进度和结果均按任务服务实际返回展示。</p></div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="服务端当前没有后台任务" />}
|
||||
{items.length ? <div className="resource-table"><Table size="small" bordered columns={importOnly ? columns.filter(column => ['createdAt', 'status', 'progress', 'processed', 'errorMessage', 'detail'].includes(String(column.key))) : columns} dataSource={items} rowKey={row => String(row.id ?? JSON.stringify(row))} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: importOnly ? 1000 : 1600 }} />
|
||||
{!importOnly && <p className="table-caption">错误信息、进度和结果均按任务服务实际返回展示。</p>}</div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="服务端当前没有后台任务" />}
|
||||
<Drawer className="management-drawer" open={Boolean(selected)} title="任务详情" width={Math.min(760, window.innerWidth)} onClose={() => setSelected(null)}>
|
||||
{selected && <><div className="task-detail-summary"><strong>{toText(selected.type)} · {toText(selected.status)}</strong><span>{toText(selected.stage)} · {toText(selected.id)}</span>{selected.errorMessage !== null && selected.errorMessage !== undefined && selected.errorMessage !== '' && <Alert showIcon type="error" message={toText(selected.errorCode || '任务错误')} description={toText(selected.errorMessage)} />}</div><pre className="json-result">{publicJson(selected)}</pre></>}
|
||||
{selected && <><div className="task-detail-summary"><strong>{importOnly ? importState(selected.status) : `${toText(selected.type)} · ${toText(selected.status)}`}</strong>{!importOnly && <span>{toText(selected.stage)} · {toText(selected.id)}</span>}{selected.errorMessage !== null && selected.errorMessage !== undefined && selected.errorMessage !== '' && <Alert showIcon type="error" message={toText(selected.errorCode || '任务错误')} description={toText(selected.errorMessage)} />}</div>{importOnly ? <dl className="nc-form-grid"><dt>处理状态</dt><dd>{importState(selected.status)}</dd><dt>处理行数</dt><dd>{toText(selected.processed)} / {toText(selected.total)}</dd><dt>创建时间</dt><dd>{toText(selected.createdAt)}</dd></dl> : <pre className="json-result">{publicJson(selected)}</pre>}</>}
|
||||
</Drawer>
|
||||
<ImportIssuesDrawer runId={issuesRunId} onClose={() => setIssuesRunId('')} onUnauthorized={onUnauthorized} />
|
||||
</>;
|
||||
@@ -918,35 +956,49 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
const [sessions, setSessions] = useState<Record<string, unknown>[]>([]);
|
||||
const [turns, setTurns] = useState<Record<string, unknown>[]>([]);
|
||||
const [options, setOptions] = useState<OptionsResponse | null>(null);
|
||||
const [historyLoading, setHistoryLoading] = useState(false);
|
||||
const [historyLoading, setHistoryLoading] = useState(true);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [retryQuestion, setRetryQuestion] = useState('');
|
||||
const [lastTurn, setLastTurn] = useState<Record<string, unknown> | null>(null);
|
||||
const [activeTurnId, setActiveTurnId] = useState('');
|
||||
const [, setStreamProgress] = useState('');
|
||||
const [streamProgress, setStreamProgress] = useState('');
|
||||
const streamController = useRef<AbortController | null>(null);
|
||||
const eventCursors = useRef<Record<string, string>>({});
|
||||
const deepLinkStarted = useRef(false);
|
||||
const mounted = useRef(true);
|
||||
const userSelectionMade = useRef(false);
|
||||
const navigationGeneration = useRef(0);
|
||||
const subscriptionGeneration = useRef(0);
|
||||
const [releaseId, setReleaseId] = useState<string>();
|
||||
const [sourceResultRef, setSourceResultRef] = useState<AnalysisResultRef>();
|
||||
const conversationEnd = useRef<HTMLDivElement>(null);
|
||||
useEffect(() => { conversationEnd.current?.scrollIntoView({ block: 'nearest' }); }, [lastTurn, busy]);
|
||||
|
||||
const loadSessions = async () => {
|
||||
try { setSessions(collectionItems(await api.analysisSessions())); }
|
||||
catch (value) { if (!onUnauthorized(value)) setError(apiMessage(value)); }
|
||||
try { const items = collectionItems(await api.analysisSessions()); if (mounted.current) setSessions(items); }
|
||||
catch (value) { if (mounted.current && !onUnauthorized(value)) setError(apiMessage(value)); }
|
||||
};
|
||||
useEffect(() => {
|
||||
api.options().then(value => { setOptions(value); })
|
||||
.catch(value => { if (!onUnauthorized(value)) setError(apiMessage(value)); });
|
||||
void loadSessions();
|
||||
let alive = true;
|
||||
api.options().then(value => { if (alive) setOptions(value); })
|
||||
.catch(value => { if (alive && !onUnauthorized(value)) setError(apiMessage(value)); });
|
||||
return () => { alive = false; };
|
||||
}, []);
|
||||
|
||||
const hasBackgroundTurns = sessions.some(item => analysisIsRunning(item.activeTurnStatus));
|
||||
useEffect(() => {
|
||||
if (!initialLink.present || initialSessionId || initialTurnId || !options) return;
|
||||
if (!hasBackgroundTurns) return;
|
||||
const timer = window.setInterval(() => void loadSessions(), 5000);
|
||||
return () => window.clearInterval(timer);
|
||||
}, [hasBackgroundTurns]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!initialLink.present || initialSessionId || initialTurnId || !options || userSelectionMade.current) return;
|
||||
const generation = navigationGeneration.current;
|
||||
const selection = beginAnalysisSelection(user.id);
|
||||
if (initialLink.error || !initialLink.query) {
|
||||
setError(initialLink.error || '分析链接缺少有效查询条件');
|
||||
setHistoryLoading(false);
|
||||
return;
|
||||
}
|
||||
const linkedQuery = initialLink.query;
|
||||
@@ -954,6 +1006,7 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
const allowedReleaseIds = new Set((options.releases || []).map(item => item.id));
|
||||
if (linkedRelease && !allowedReleaseIds.has(linkedRelease)) {
|
||||
setError('链接对应的数据当前不可访问,请从当前查询结果重新打开分析。');
|
||||
setHistoryLoading(false);
|
||||
return;
|
||||
}
|
||||
setReleaseId(linkedRelease);
|
||||
@@ -961,6 +1014,7 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
if (initialLink.resultRef) setQuery('请解释已绑定的阶段 TOP 排名,并说明可核查的来源依据。');
|
||||
const context: Record<string, unknown> = {
|
||||
year: linkedQuery.year,
|
||||
...(linkedQuery.extraFilters ? { extraFilters: linkedQuery.extraFilters } : {}),
|
||||
...(linkedQuery.month !== undefined ? { month: linkedQuery.month } : {}),
|
||||
...(linkedQuery.quarter !== undefined ? { quarter: linkedQuery.quarter } : {}),
|
||||
view: linkedQuery.view,
|
||||
@@ -973,7 +1027,7 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
...(initialLink.resultRef ? { resultRef: initialLink.resultRef } : {}),
|
||||
};
|
||||
setSessionContext(context);
|
||||
const requestKey = JSON.stringify({ query: linkedQuery, resultRef: initialLink.resultRef || null });
|
||||
const requestKey = JSON.stringify({ userId: user.id, query: linkedQuery, resultRef: initialLink.resultRef || null });
|
||||
const pageWindow = window as AnalysisPageWindow;
|
||||
let linkedSessionRequest = pageWindow.__qualityAnalysisLinkedSessionRequest;
|
||||
if (!linkedSessionRequest || linkedSessionRequest.key !== requestKey) {
|
||||
@@ -987,24 +1041,30 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
setHistoryLoading(true);
|
||||
linkedSessionRequest.promise
|
||||
.then(created => {
|
||||
if (!alive) return;
|
||||
if (!alive || !mounted.current || generation !== navigationGeneration.current) return;
|
||||
const id = String(created.session.id || '');
|
||||
if (!id) throw new Error('服务端未返回分析会话编号');
|
||||
setSessionId(id);
|
||||
rememberPendingAnalysisSession(user.id, id, selection);
|
||||
writeAnalysisLocation(id);
|
||||
if (pageWindow.__qualityAnalysisLinkedSessionRequest === linkedSessionRequest) delete pageWindow.__qualityAnalysisLinkedSessionRequest;
|
||||
void loadSessions();
|
||||
})
|
||||
.catch(value => {
|
||||
if (!alive) return;
|
||||
if (!alive || !mounted.current || generation !== navigationGeneration.current) return;
|
||||
if (pageWindow.__qualityAnalysisLinkedSessionRequest === linkedSessionRequest) delete pageWindow.__qualityAnalysisLinkedSessionRequest;
|
||||
if (!onUnauthorized(value)) setError(apiMessage(value));
|
||||
})
|
||||
.finally(() => { if (alive) setHistoryLoading(false); });
|
||||
.finally(() => {
|
||||
if (pageWindow.__qualityAnalysisLinkedSessionRequest === linkedSessionRequest) delete pageWindow.__qualityAnalysisLinkedSessionRequest;
|
||||
if (alive && mounted.current && generation === navigationGeneration.current) setHistoryLoading(false);
|
||||
});
|
||||
return () => { alive = false; };
|
||||
}, [options]);
|
||||
|
||||
const writeAnalysisLocation = (selectedSessionId?: string, selectedTurnId?: string) => {
|
||||
if (!mounted.current) return;
|
||||
if (selectedSessionId) rememberAnalysisSession(user.id, selectedSessionId);
|
||||
const url = new URL(window.location.href);
|
||||
url.searchParams.set('page', 'analysis');
|
||||
if (selectedSessionId) url.searchParams.set('sessionId', selectedSessionId); else url.searchParams.delete('sessionId');
|
||||
@@ -1014,14 +1074,23 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
};
|
||||
|
||||
const openSession = async (id: string, focusTurnId?: string): Promise<boolean> => {
|
||||
setHistoryLoading(true);
|
||||
userSelectionMade.current = true;
|
||||
beginAnalysisSelection(user.id);
|
||||
const generation = ++navigationGeneration.current;
|
||||
subscriptionGeneration.current += 1;
|
||||
streamController.current?.abort(); streamController.current = null;
|
||||
setBusy(false); setActiveTurnId(''); setHistoryLoading(true);
|
||||
const current = () => mounted.current && generation === navigationGeneration.current;
|
||||
try {
|
||||
const [history, turnHistory] = await Promise.all([api.analysisSession(id), api.analysisSessionTurns(id)]);
|
||||
if (!current()) return false;
|
||||
const historyTurns = restoredAnalysisTurns(history, turnHistory);
|
||||
const active = activeAnalysisTurn(historyTurns);
|
||||
const selectedTurnId = focusTurnId || (active ? String(active.id || '') : '');
|
||||
setSessionId(id);
|
||||
setTurns(restoredAnalysisTurns(history, turnHistory).filter(turn => !focusTurnId || String(turn.id || '') !== focusTurnId));
|
||||
writeAnalysisLocation(id, focusTurnId);
|
||||
setLastTurn(null);
|
||||
setError('');
|
||||
setTurns(historyTurns.filter(turn => !selectedTurnId || String(turn.id || '') !== selectedTurnId));
|
||||
writeAnalysisLocation(id, selectedTurnId || undefined);
|
||||
setLastTurn(null); setError(''); setRetryQuestion('');
|
||||
const context = history.context && typeof history.context === 'object' ? history.context as Record<string, unknown> : {};
|
||||
const restoredContext = { ...context };
|
||||
const fixedRelease = typeof history.releaseId === 'string' ? history.releaseId : typeof context.releaseId === 'string' ? context.releaseId : '';
|
||||
@@ -1032,13 +1101,27 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
setSourceResultRef(resultRef.kind === 'TOP' && typeof resultRef.resultId === 'string' && typeof resultRef.releaseId === 'string' && resultRef.releaseId === String(history.releaseId || context.releaseId || '')
|
||||
? { kind: 'TOP', resultId: resultRef.resultId, releaseId: resultRef.releaseId }
|
||||
: undefined);
|
||||
if (selectedTurnId) {
|
||||
const detail = await api.analysisTurn(selectedTurnId);
|
||||
if (!current()) return false;
|
||||
if (String(detail.sessionId || '') !== id) throw new Error('分析轮次与会话链接不匹配');
|
||||
const restored = { ...historyTurns.find(item => item.id === selectedTurnId), ...detail };
|
||||
setLastTurn(restored);
|
||||
if (analysisIsRunning(restored.status)) void followTurn(selectedTurnId, String(restored.question || ''), id);
|
||||
}
|
||||
return true;
|
||||
} catch (value) { if (!onUnauthorized(value)) setError(apiMessage(value)); return false; }
|
||||
finally { setHistoryLoading(false); }
|
||||
} catch (value) { if (current() && !onUnauthorized(value)) setError(apiMessage(value)); return false; }
|
||||
finally { if (current()) setHistoryLoading(false); }
|
||||
};
|
||||
|
||||
const newSession = () => {
|
||||
if (busy) return;
|
||||
userSelectionMade.current = true;
|
||||
beginAnalysisSelection(user.id);
|
||||
setBusy(false); setActiveTurnId(''); setStreamProgress('');
|
||||
navigationGeneration.current += 1; subscriptionGeneration.current += 1;
|
||||
streamController.current?.abort(); streamController.current = null;
|
||||
rememberAnalysisSession(user.id, '');
|
||||
setHistoryLoading(false);
|
||||
setSessionId(''); setTurns([]); setLastTurn(null); setQuery(''); setError(''); setRetryQuestion('');
|
||||
setSessionContext(null);
|
||||
setReleaseId(undefined);
|
||||
@@ -1047,9 +1130,10 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
};
|
||||
|
||||
const deleteSession = async (id: string) => {
|
||||
const generation = navigationGeneration.current;
|
||||
try {
|
||||
await api.deleteAnalysisSession(id);
|
||||
if (sessionId === id) newSession();
|
||||
if (mounted.current && navigationGeneration.current === generation && sessionId === id) newSession();
|
||||
await loadSessions();
|
||||
message.success('会话已删除');
|
||||
} catch (value) {
|
||||
@@ -1058,13 +1142,17 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
};
|
||||
|
||||
const followTurn = async (id: string, question: string, sessionOverride?: string) => {
|
||||
if (!mounted.current) return;
|
||||
streamController.current?.abort();
|
||||
const generation = ++subscriptionGeneration.current;
|
||||
const current = () => mounted.current && generation === subscriptionGeneration.current;
|
||||
const linkedSessionId = sessionOverride || sessionId;
|
||||
if (linkedSessionId) writeAnalysisLocation(linkedSessionId, id);
|
||||
setActiveTurnId(id); setBusy(true); setStreamProgress('分析任务已排队,等待服务端步骤…');
|
||||
const controller = new AbortController(); streamController.current = controller;
|
||||
let streamedResult: Record<string, unknown> = {};
|
||||
let terminalEventStatus = '';
|
||||
setLastTurn(previous => ({ ...(previous || {}), id, question, status: 'QUEUED' }));
|
||||
setLastTurn(previous => ({ ...(previous || {}), id, question, status: previous?.status || 'QUEUED' }));
|
||||
try {
|
||||
let detail: Record<string, unknown> = {};
|
||||
let reconnectAttempt = 0;
|
||||
@@ -1075,10 +1163,11 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
signal: controller.signal,
|
||||
lastEventId: eventCursors.current[id],
|
||||
onEvent: event => {
|
||||
if (!current()) return;
|
||||
receivedEvents += 1;
|
||||
if (event.id) eventCursors.current[id] = event.id;
|
||||
const data = event.data && typeof event.data === 'object' ? event.data as Record<string, unknown> : {};
|
||||
const messageText = typeof data.message === 'string' ? data.message : event.event.replaceAll('_', ' ');
|
||||
const messageText = typeof data.message === 'string' ? data.message : event.event === 'answer' ? '正在整理分析结论…' : '正在分析…';
|
||||
setStreamProgress(messageText);
|
||||
const eventResult = isObjectRecord(data.result) ? data.result : undefined;
|
||||
if (eventResult) streamedResult = { ...streamedResult, ...eventResult };
|
||||
@@ -1099,6 +1188,10 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
status,
|
||||
latestEvent: event.event,
|
||||
eventStep: data.step,
|
||||
...(Array.isArray(data.steps) ? { steps: data.steps } : {}),
|
||||
...(typeof data.startedAt === 'string' ? { startedAt: data.startedAt } : {}),
|
||||
...(typeof data.updatedAt === 'string' ? { updatedAt: data.updatedAt } : {}),
|
||||
progressMessage: messageText,
|
||||
plan: data.plan || prior.plan,
|
||||
...(eventResult ? { result: { ...priorResult, ...eventResult } } : {}),
|
||||
};
|
||||
@@ -1109,14 +1202,23 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
},
|
||||
});
|
||||
} catch (streamError) {
|
||||
if (!(controller.signal.aborted && terminalEventStatus)) throw streamError;
|
||||
if (!current() || (controller.signal.aborted && !terminalEventStatus)) return;
|
||||
if (streamError instanceof ApiError && [401, 403, 404].includes(streamError.status)) throw streamError;
|
||||
if (!terminalEventStatus) setStreamProgress('连接暂时中断,后台仍在分析,正在恢复…');
|
||||
}
|
||||
|
||||
if (!current() || (controller.signal.aborted && !terminalEventStatus)) return;
|
||||
// A normal SSE close is not necessarily turn completion: the server
|
||||
// rotates its event stream while long-running analyses continue.
|
||||
for (const delayMs of [0, 250, 500, 750, 1000, 1000, 1200]) {
|
||||
if (delayMs) await new Promise(resolve => setTimeout(resolve, delayMs));
|
||||
detail = await api.analysisTurn(id);
|
||||
try { detail = await api.analysisTurn(id); }
|
||||
catch (readError) {
|
||||
if (!current()) return;
|
||||
if (readError instanceof ApiError && [401, 403, 404].includes(readError.status)) throw readError;
|
||||
setStreamProgress('连接暂时中断,后台仍在分析,正在恢复…');
|
||||
}
|
||||
if (!current()) return;
|
||||
if (ANALYSIS_FINAL_STATUSES.has(String(detail.status || '').toUpperCase())) break;
|
||||
if (controller.signal.aborted && !terminalEventStatus) break;
|
||||
}
|
||||
@@ -1126,20 +1228,8 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
const reconnectDelay = Math.min(500 * (2 ** reconnectAttempt), 8000);
|
||||
await new Promise(resolve => setTimeout(resolve, reconnectDelay));
|
||||
}
|
||||
const detailResult = isObjectRecord(detail.result) ? detail.result : {};
|
||||
const combinedResult: Record<string, unknown> = { ...detail, ...detailResult, ...streamedResult };
|
||||
delete combinedResult.result;
|
||||
const detailStatus = String(detail.status || '').toUpperCase();
|
||||
const settledStatus = ANALYSIS_FINAL_STATUSES.has(detailStatus) ? detailStatus : terminalEventStatus || detailStatus;
|
||||
const settledTurn = {
|
||||
...detail,
|
||||
...detailResult,
|
||||
...streamedResult,
|
||||
id,
|
||||
question,
|
||||
...(settledStatus ? { status: settledStatus } : {}),
|
||||
result: combinedResult,
|
||||
};
|
||||
if (!current()) return;
|
||||
const settledTurn = settledAnalysisTurn(id, question, detail, streamedResult, terminalEventStatus);
|
||||
setLastTurn(settledTurn);
|
||||
if (ANALYSIS_FINAL_STATUSES.has(String(settledTurn.status || '').toUpperCase())) {
|
||||
setRetryQuestion(''); setQuery('');
|
||||
@@ -1147,99 +1237,104 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
if (parentSessionId) {
|
||||
try {
|
||||
const [savedHistory, savedMetadata] = await Promise.all([api.analysisSession(parentSessionId), api.analysisSessionTurns(parentSessionId)]);
|
||||
if (!current()) return;
|
||||
const historyTurns = restoredAnalysisTurns(savedHistory, savedMetadata);
|
||||
setTurns(historyTurns.filter(item => String(item.id || '') !== id));
|
||||
} catch (historyError) { if (!onUnauthorized(historyError)) setError(apiMessage(historyError)); }
|
||||
} catch (historyError) { if (current() && !onUnauthorized(historyError)) setError(apiMessage(historyError)); }
|
||||
await loadSessions();
|
||||
}
|
||||
}
|
||||
} catch (value) {
|
||||
if (!(value instanceof DOMException && value.name === 'AbortError')) {
|
||||
if (current() && !(value instanceof DOMException && value.name === 'AbortError')) {
|
||||
if (!onUnauthorized(value)) setError(apiMessage(value));
|
||||
try { setLastTurn({ ...(await api.analysisTurn(id)), id, question }); } catch (refreshError) { if (!onUnauthorized(refreshError)) setError(apiMessage(refreshError)); }
|
||||
try { const detail = await api.analysisTurn(id); if (current()) setLastTurn({ ...detail, id, question }); } catch (refreshError) { if (current() && !onUnauthorized(refreshError)) setError(apiMessage(refreshError)); }
|
||||
}
|
||||
} finally {
|
||||
if (streamController.current === controller) {
|
||||
if (current() && streamController.current === controller) {
|
||||
streamController.current = null; setBusy(false); setActiveTurnId('');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (deepLinkStarted.current || (!initialSessionId && !initialTurnId)) return;
|
||||
deepLinkStarted.current = true;
|
||||
mounted.current = true;
|
||||
let cancelled = false;
|
||||
const restore = async () => {
|
||||
const requestedAt = navigationGeneration.current;
|
||||
setHistoryLoading(true);
|
||||
try {
|
||||
const items = collectionItems(await api.analysisSessions());
|
||||
if (cancelled || requestedAt !== navigationGeneration.current) return;
|
||||
setSessions(items);
|
||||
let linkedSession = initialSessionId;
|
||||
let linkedTurn: Record<string, unknown> | undefined;
|
||||
if (initialTurnId) {
|
||||
linkedTurn = await api.analysisTurn(initialTurnId);
|
||||
const linkedTurn = await api.analysisTurn(initialTurnId);
|
||||
if (cancelled || requestedAt !== navigationGeneration.current) return;
|
||||
const turnSession = String(linkedTurn.sessionId || '');
|
||||
if (linkedSession && turnSession && linkedSession !== turnSession) throw new Error('分析轮次与会话链接不匹配');
|
||||
linkedSession ||= turnSession;
|
||||
}
|
||||
if (!linkedSession) throw new Error('链接缺少可恢复的会话编号');
|
||||
if (cancelled) return;
|
||||
const opened = await openSession(linkedSession, initialTurnId || undefined);
|
||||
if (!opened || cancelled || !linkedTurn) return;
|
||||
const question = typeof linkedTurn.question === 'string' ? linkedTurn.question : '';
|
||||
const restored = { ...linkedTurn, id: initialTurnId, question, sessionId: linkedSession };
|
||||
setLastTurn(restored);
|
||||
const turnStatus = String(linkedTurn.status || '').toUpperCase();
|
||||
if (['QUEUED', 'RUNNING', 'PLANNING', 'TOOL_RUNNING', 'PROCESSING'].includes(turnStatus)) {
|
||||
await followTurn(initialTurnId, question, linkedSession);
|
||||
}
|
||||
} catch (value) {
|
||||
if (!cancelled && !onUnauthorized(value)) setError(apiMessage(value));
|
||||
} finally { if (!cancelled) setHistoryLoading(false); }
|
||||
if (!linkedSession && !initialLink.present) linkedSession = defaultAnalysisSession(user.id, items);
|
||||
if (!cancelled && requestedAt === navigationGeneration.current && linkedSession) await openSession(linkedSession, initialTurnId || undefined);
|
||||
} catch (value) { if (!cancelled && !onUnauthorized(value)) setError(apiMessage(value)); }
|
||||
finally { if (!cancelled && requestedAt === navigationGeneration.current && !initialLink.present) setHistoryLoading(false); }
|
||||
};
|
||||
void restore();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
deepLinkStarted.current = false;
|
||||
streamController.current?.abort();
|
||||
cancelled = true; mounted.current = false;
|
||||
navigationGeneration.current += 1; subscriptionGeneration.current += 1;
|
||||
// Unsubscribe from updates only. The accepted server task continues independently.
|
||||
streamController.current?.abort(); streamController.current = null;
|
||||
};
|
||||
}, []);
|
||||
|
||||
const cancelTurn = async () => {
|
||||
if (!activeTurnId) return;
|
||||
const generation = navigationGeneration.current;
|
||||
const id = activeTurnId;
|
||||
try {
|
||||
await api.cancelAnalysisTurn(id, '用户请求停止');
|
||||
streamController.current?.abort();
|
||||
if (!mounted.current || generation !== navigationGeneration.current) return;
|
||||
setStreamProgress('正在停止分析…');
|
||||
const detail = await api.analysisTurn(id);
|
||||
setLastTurn(previous => ({ ...detail, id, question: previous?.question }));
|
||||
if (mounted.current && generation === navigationGeneration.current) setLastTurn(previous => ({ ...detail, id, question: previous?.question }));
|
||||
} catch (value) { if (!onUnauthorized(value)) setError(apiMessage(value)); }
|
||||
};
|
||||
|
||||
const retryTurn = async (turn: Record<string, unknown>) => {
|
||||
if (busy) return;
|
||||
if (busy || historyLoading) return;
|
||||
const id = String(turn.id || '');
|
||||
const status = String(turn.status || '').toUpperCase();
|
||||
if (!id || !['FAILED', 'CANCELLED', 'PARTIAL'].includes(status)) return;
|
||||
const selection = beginAnalysisSelection(user.id);
|
||||
const generation = navigationGeneration.current;
|
||||
const current = () => mounted.current && generation === navigationGeneration.current;
|
||||
const question = typeof turn.question === 'string' ? turn.question : '';
|
||||
const targetSessionId = String(turn.sessionId || sessionId || '');
|
||||
setError(''); setBusy(true); setActiveTurnId(id); setStreamProgress('正在按原冻结计划重新排队…');
|
||||
try {
|
||||
const response = await api.retryAnalysisTurn(id);
|
||||
const retried = response.turn;
|
||||
if (!current()) { rememberPendingAnalysisSession(user.id, String(retried.sessionId || targetSessionId), selection); return; }
|
||||
const retryId = String(retried.id || id);
|
||||
const retrySessionId = String(retried.sessionId || targetSessionId);
|
||||
if (!retrySessionId) throw new Error('无法确定原分析会话,已停止重试。');
|
||||
setSessionId(retrySessionId);
|
||||
setTurns(previous => previous.filter(item => String(item.id || '') !== id));
|
||||
const retriedDetail = await api.analysisTurn(retryId);
|
||||
if (!current()) return;
|
||||
setLastTurn({ ...retriedDetail, ...retried, id: retryId, sessionId: retrySessionId, question });
|
||||
writeAnalysisLocation(retrySessionId, retryId);
|
||||
await loadSessions();
|
||||
if (!current()) return;
|
||||
setBusy(false);
|
||||
await followTurn(retryId, question, retrySessionId);
|
||||
if (current()) await followTurn(retryId, question, retrySessionId);
|
||||
} catch (value) {
|
||||
if (!current()) return;
|
||||
if (!onUnauthorized(value)) setError(apiMessage(value));
|
||||
try {
|
||||
const detail = await api.analysisTurn(id);
|
||||
if (!current()) return;
|
||||
setLastTurn({ ...turn, ...detail, id, question, sessionId: targetSessionId });
|
||||
} catch (refreshError) { if (!onUnauthorized(refreshError)) setError(apiMessage(refreshError)); }
|
||||
setBusy(false); setActiveTurnId(''); setStreamProgress('');
|
||||
@@ -1248,7 +1343,11 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
|
||||
const submit = async (question = query) => {
|
||||
if (!question.trim()) return;
|
||||
if (busy) return;
|
||||
if (busy || historyLoading) return;
|
||||
const selection = beginAnalysisSelection(user.id);
|
||||
rememberAnalysisSession(user.id, '');
|
||||
const generation = navigationGeneration.current;
|
||||
const current = () => mounted.current && generation === navigationGeneration.current;
|
||||
setBusy(true);
|
||||
setError('');
|
||||
setRetryQuestion(question.trim());
|
||||
@@ -1266,19 +1365,23 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
const created = await api.createAnalysisSession({ title: question.trim().slice(0, 60), ...(releaseId ? { releaseId } : {}), ...(context ? { context } : {}) });
|
||||
selectedSessionId = String(created.session.id || '');
|
||||
if (!selectedSessionId) throw new Error('服务端未返回会话编号');
|
||||
setSessionId(selectedSessionId);
|
||||
rememberPendingAnalysisSession(user.id, selectedSessionId, selection);
|
||||
if (current()) setSessionId(selectedSessionId);
|
||||
}
|
||||
const started = await api.startAnalysisTurn(selectedSessionId, { question: question.trim(), ...(context ? { context } : {}), idempotencyKey: crypto.randomUUID() });
|
||||
const turn = started.turn;
|
||||
const turnId = String(turn.id || '');
|
||||
if (!turnId) throw new Error('服务端未返回分析任务编号');
|
||||
rememberPendingAnalysisSession(user.id, selectedSessionId, selection);
|
||||
if (!current()) return;
|
||||
setLastTurn({ ...turn, id: turnId, question: question.trim(), sessionId: selectedSessionId });
|
||||
writeAnalysisLocation(selectedSessionId, turnId);
|
||||
await loadSessions();
|
||||
if (!current()) return;
|
||||
setBusy(false);
|
||||
await followTurn(turnId, question.trim(), selectedSessionId);
|
||||
}
|
||||
catch (value) { if (!onUnauthorized(value)) { setError(apiMessage(value)); message.error(apiMessage(value)); } setBusy(false); }
|
||||
catch (value) { if (current()) { if (!onUnauthorized(value)) { setError(apiMessage(value)); message.error(apiMessage(value)); } setBusy(false); } }
|
||||
};
|
||||
|
||||
return <div className="management-page analysis-simple-page">
|
||||
@@ -1286,20 +1389,20 @@ function AnalysisPage({ onUnauthorized, user }: { onUnauthorized: (error: unknow
|
||||
{error && <Alert type="error" showIcon message="智能分析状态" description={error} action={retryQuestion && <Button size="small" onClick={() => void submit(retryQuestion)}>重试上一问</Button>} />}
|
||||
<div className="analysis-workspace">
|
||||
<aside className="panel analysis-session-panel">
|
||||
<div className="analysis-session-heading"><strong>会话</strong><Button type="primary" size="small" disabled={busy} onClick={newSession}>新会话</Button></div>
|
||||
{historyLoading ? <div className="loading-panel compact"><Spin />正在读取会话…</div> : sessions.length ? <div className="analysis-session-list">{sessions.map(item => <div key={String(item.id)} className={`analysis-session-row ${sessionId === item.id ? 'active' : ''}`}><button disabled={busy} className="analysis-session-item" onClick={() => void openSession(String(item.id))}><strong>{toText(item.title || '未命名会话')}</strong><small>{String(item.updatedAt || item.createdAt || '').slice(0, 10)}</small></button><Popconfirm title="删除此会话及其分析记录?" description="删除后无法恢复" okText="删除" cancelText="取消" okButtonProps={{ danger: true }} onConfirm={() => void deleteSession(String(item.id))}><Button className="analysis-session-delete" type="text" danger icon={<DeleteOutlined />} aria-label={`删除会话 ${toText(item.title || '未命名会话')}`} disabled={busy} /></Popconfirm></div>)}</div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无历史会话" />}
|
||||
<div className="analysis-session-heading"><strong>会话</strong><Button type="primary" size="small" onClick={newSession}>新会话</Button></div>
|
||||
{historyLoading ? <div className="loading-panel compact"><Spin />正在读取会话…</div> : sessions.length ? <div className="analysis-session-list">{sessions.map(item => <div key={String(item.id)} className={`analysis-session-row ${sessionId === item.id ? 'active' : ''}`}><button className="analysis-session-item" onClick={() => void openSession(String(item.id))}><strong>{toText(item.title || '未命名会话')}</strong><small>{String(item.updatedAt || item.createdAt || '').slice(0, 10)}{analysisIsRunning(item.activeTurnStatus) && <span className="analysis-session-state">{item.activeTurnStatus === 'QUEUED' ? '排队中' : '分析中'}</span>}</small></button><Popconfirm title="删除此会话及其分析记录?" description="删除后无法恢复" okText="删除" cancelText="取消" okButtonProps={{ danger: true }} onConfirm={() => void deleteSession(String(item.id))}><Button className="analysis-session-delete" type="text" danger icon={<DeleteOutlined />} aria-label={`删除会话 ${toText(item.title || '未命名会话')}`} disabled={analysisIsRunning(item.activeTurnStatus)} /></Popconfirm></div>)}</div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无历史会话" />}
|
||||
</aside>
|
||||
<section className="panel analysis-chat-panel">
|
||||
<div className="analysis-conversation" aria-live="polite">
|
||||
{turns.map((turn, index) => <AnalysisTurn key={String(turn.id || index)} turn={turn} onRetry={(id) => void retryTurn(turns.find(item => String(item.id || '') === id) || turn)} onResume={id => void followTurn(id, String(turn.question || ''))} onGenerateReport={() => void submit(generateReportPrompt(turn))} retryDisabled={busy} />)}
|
||||
{lastTurn && <AnalysisTurn turn={lastTurn} onRetry={() => void retryTurn(lastTurn)} onResume={id => void followTurn(id, String(lastTurn.question || ''))} onGenerateReport={() => void submit(generateReportPrompt(lastTurn))} retryDisabled={busy} />}
|
||||
{busy && <div className="analysis-progress"><Spin size="small" />正在分析…<Button size="small" danger onClick={() => void cancelTurn()}>停止分析</Button></div>}
|
||||
{turns.map((turn, index) => <AnalysisTurn key={String(turn.id || index)} turn={turn} onRetry={(id) => void retryTurn(turns.find(item => String(item.id || '') === id) || turn)} onResume={id => { if (!historyLoading) void followTurn(id, String(turn.question || '')); }} onGenerateReport={() => void submit(generateReportPrompt(turn))} retryDisabled={busy || historyLoading} />)}
|
||||
{lastTurn && <AnalysisTurn turn={lastTurn} onRetry={() => void retryTurn(lastTurn)} onResume={id => { if (!historyLoading) void followTurn(id, String(lastTurn.question || '')); }} onGenerateReport={() => void submit(generateReportPrompt(lastTurn))} retryDisabled={busy || historyLoading} />}
|
||||
{busy && <div className="analysis-progress"><span>{streamProgress || '正在分析…'}</span><Button size="small" danger onClick={() => void cancelTurn()}>停止分析</Button></div>}
|
||||
{!turns.length && !lastTurn && !busy && <div className="analysis-empty"><RobotOutlined /><strong>想了解哪些质量情况?</strong><span>例如:9月汽车交通的合格率为什么下降?</span></div>}
|
||||
<div ref={conversationEnd} />
|
||||
</div>
|
||||
<div className="analysis-composer">
|
||||
<Input.TextArea id="analysis-query" value={query} onChange={event => setQuery(event.target.value)} autoSize={{ minRows: 2, maxRows: 5 }} maxLength={1600} aria-label="质量问题" placeholder="直接描述问题,或继续追问…" onPressEnter={event => { if (!event.shiftKey && !event.nativeEvent.isComposing) { event.preventDefault(); void submit(); } }} />
|
||||
<div className="ai-actions"><span>Enter 发送 · Shift + Enter 换行</span><div className="analysis-composer-buttons">{user.roles.includes('SYSTEM_ADMIN') && <AnalysisApiSettings onUnauthorized={onUnauthorized} />}<Button type="primary" aria-label="发送" loading={busy} disabled={!query.trim() || busy} onClick={() => void submit()}>发送</Button></div></div>
|
||||
<Input.TextArea id="analysis-query" disabled={historyLoading} value={query} onChange={event => setQuery(event.target.value)} autoSize={{ minRows: 2, maxRows: 5 }} maxLength={1600} aria-label="质量问题" placeholder="直接描述问题,或继续追问…" onPressEnter={event => { if (!event.shiftKey && !event.nativeEvent.isComposing) { event.preventDefault(); void submit(); } }} />
|
||||
<div className="ai-actions"><span>Enter 发送 · Shift + Enter 换行</span><div className="analysis-composer-buttons">{user.roles.includes('SYSTEM_ADMIN') && <AnalysisApiSettings onUnauthorized={onUnauthorized} />}<Button type="primary" aria-label="发送" loading={busy} disabled={!query.trim() || busy || historyLoading} onClick={() => void submit()}>发送</Button></div></div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
@@ -1323,6 +1426,7 @@ function AnalysisTurn({ turn, onResume, onRetry, onGenerateReport, retryDisabled
|
||||
: failure;
|
||||
return <article className="analysis-turn">
|
||||
{question && <div className="analysis-question"><p>{question}</p></div>}
|
||||
<AnalysisProcess turn={turn} />
|
||||
{(answer || !resumable || !retryDisabled) && <div className="analysis-answer">
|
||||
{answer ? <AiMarkdown content={answer} className="ai-answer" /> : <p className={resumable ? 'analysis-chat-notice' : undefined}>{resumable ? '分析任务仍在运行,尚未返回完整回答。' : emptyStatus}</p>}
|
||||
{status === 'PARTIAL' && <p className="analysis-chat-notice">部分分析尚未完成,可以重试或继续追问。</p>}
|
||||
@@ -1331,7 +1435,7 @@ function AnalysisTurn({ turn, onResume, onRetry, onGenerateReport, retryDisabled
|
||||
{!reportMarkdown.trim() && engine === 'NAO' && status === 'COMPLETED' && answer && onGenerateReport && <Button type="text" size="small" icon={<DownloadOutlined />} disabled={retryDisabled} onClick={onGenerateReport}>生成报告</Button>}
|
||||
{!reportMarkdown.trim() && engine !== 'NAO' && answer && ['COMPLETED', 'PARTIAL'].includes(status) && <AnalysisReportExport turn={turn} />}
|
||||
{['FAILED', 'CANCELLED', 'PARTIAL'].includes(status) && typeof turn.id === 'string' && onRetry && <Button size="small" type="text" disabled={retryDisabled} onClick={() => onRetry(String(turn.id))}>重新分析</Button>}
|
||||
{resumable && typeof turn.id === 'string' && onResume && <Button size="small" type="text" disabled={retryDisabled} onClick={() => onResume(String(turn.id))}>继续分析</Button>}
|
||||
{resumable && !retryDisabled && typeof turn.id === 'string' && onResume && <Button size="small" type="text" onClick={() => onResume(String(turn.id))}>继续分析</Button>}
|
||||
</div>
|
||||
</div>}
|
||||
</article>;
|
||||
@@ -1377,7 +1481,7 @@ function ResourceTab({ onUnauthorized }: { onUnauthorized: (error: unknown) => b
|
||||
return <div className="resource-tab">
|
||||
{error && <Alert type="error" showIcon message="审计记录读取失败" description={error} />}
|
||||
<div className="resource-toolbar"><strong>审计事件</strong><span>{result?.total !== undefined ? `共 ${result.total} 条` : `${items.length} 条`}</span><Button icon={<ReloadOutlined />} onClick={() => void load(page)}>刷新</Button></div>
|
||||
{loading ? <div className="loading-panel"><Spin />正在读取…</div> : <DynamicTable items={items} paginate={false} />}
|
||||
{loading ? <div className="loading-panel"><Spin />正在读取…</div> : <DynamicTable items={items} paginate={false} indexOffset={(page - 1) * TABLE_PAGE_SIZE} />}
|
||||
{total > TABLE_PAGE_SIZE && <Pagination className="records-pagination" current={page} pageSize={TABLE_PAGE_SIZE} total={total} showTotal={count => `共 ${count} 条`} onChange={setPage} />}
|
||||
</div>;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user