type StorageAccess = Pick; export const ACTIVE_ANALYSIS_STATUSES = new Set(['QUEUED', 'RUNNING', 'PLANNING', 'TOOL_RUNNING', 'PROCESSING']); export function analysisIsRunning(status: unknown): boolean { return ACTIVE_ANALYSIS_STATUSES.has(String(status || '').toUpperCase()); } const keyFor = (userId: string) => `quality.analysis.lastSession.${userId}`; const selections = new Map(); export function beginAnalysisSelection(userId: string): number { const next = (selections.get(userId) || 0) + 1; selections.set(userId, next); return next; } export function rememberPendingAnalysisSession(userId: string, id: string, selection: number, storage?: StorageAccess): void { if (selections.get(userId) === selection) rememberAnalysisSession(userId, id, storage); } export function rememberAnalysisSession(userId: string, id: string, storage?: StorageAccess): void { try { const target = storage || window.localStorage; if (id) target.setItem(keyFor(userId), id); else target.removeItem(keyFor(userId)); } catch { /* Storage may be disabled; server history remains available. */ } } export function defaultAnalysisSession(userId: string, sessions: Record[], storage?: StorageAccess): string { let remembered: string | null = null; try { remembered = (storage || window.localStorage).getItem(keyFor(userId)); } catch { /* use server history */ } if (remembered && sessions.some(item => item.id === remembered)) return remembered; return sessions.length ? String(sessions[0].id || '') : ''; } export function activeAnalysisTurn(turns: Record[]): Record | undefined { return turns.slice().reverse().find(turn => analysisIsRunning(turn.status)); } export function settledAnalysisTurn(id: string, question: string, detail: Record, streamed: Record, terminalEventStatus: string): Record { const detailResult = detail.result && typeof detail.result === 'object' && !Array.isArray(detail.result) ? detail.result as Record : {}; const finalStatuses = new Set(['COMPLETED', 'PARTIAL', 'FAILED', 'CANCELLED', 'NEEDS_CLARIFICATION']); const detailStatus = String(detail.status || '').toUpperCase(); const status = finalStatuses.has(detailStatus) ? detailStatus : terminalEventStatus || detailStatus; // An SSE rotation may stop on a partial answer just before the saved task // finishes. The final durable result must win, even when it is empty/redacted. const durable = { ...detail, ...detailResult }; const result = finalStatuses.has(detailStatus) ? { ...streamed, ...durable } : { ...durable, ...streamed }; delete result.result; return { ...result, id, question, status, result }; } /** Durable SSE IDs are decimal database sequences, potentially larger than JS integers. */ export function acceptAnalysisEvent(id: string | undefined, cursor: string | undefined): boolean { if (!id || !cursor) return true; if (/^\d+$/.test(id) && /^\d+$/.test(cursor)) return BigInt(id) > BigInt(cursor); return id !== cursor; } /** Providers may prefix streamed text with whitespace that the saved answer trims. */ export function duplicatesFinalAnalysisAnswer(segment: string, answer: string): boolean { const text = segment.trimStart(); return Boolean(text.trim()) && answer.trimStart().startsWith(text); } /** Render a call once, updating its original row when the result arrives. */ export function compactAnalysisTimeline(entries: Record[]): Record[] { const rows: Record[] = []; const calls = new Map(); for (const entry of entries) { if (entry.kind === 'assistant') { rows.push({ ...entry }); continue; } if (!['tool_start', 'tool_result'].includes(String(entry.kind))) continue; const id = typeof entry.toolCallId === 'string' ? entry.toolCallId : ''; const index = id ? calls.get(id) : undefined; if (index === undefined) { if (id) calls.set(id, rows.length); rows.push({ ...entry, kind: 'tool', hasResult: entry.kind === 'tool_result' }); } else { const prior = rows[index]; if (entry.kind === 'tool_result') rows[index] = { ...prior, ...entry, kind: 'tool', sequence: prior.sequence, at: prior.at, finishedAt: entry.at, input: prior.input || entry.input, hasResult: true }; else if (!prior.input && entry.input) rows[index] = { ...prior, input: entry.input }; } } return rows; } export type AnalysisScrollIntent = 'up' | 'down' | null; /** Only explicit user movement changes follow state; layout-driven scroll events preserve it. */ export function analysisScrollFollows(distanceFromBottom: number, following: boolean, intent: AnalysisScrollIntent = null): boolean { if (intent === 'up') return false; if (intent === 'down' && distanceFromBottom <= 24) return true; return following; } export function partialAnalysisNotice(reason: unknown, result: Record = {}): string { const value = String(reason || ''); const quality = result.answerQuality && typeof result.answerQuality === 'object' && !Array.isArray(result.answerQuality) ? result.answerQuality as Record : {}; if (quality.version === 1) { if (quality.dataComplete === true && quality.narrativeComplete === false) return '数据已查齐,答案尚未完整整理。已保留核验结果,可重新分析。'; if (quality.dataComplete === true && quality.chartsComplete === false) return '数据与文字已完成,部分图表尚未生成。可重试图表。'; if (quality.dataComplete === false) return '部分所需数据尚未通过完整性核验,当前仅展示可确认的结果。具体缺口见本轮说明。'; } if (value === 'mcp_error') return '部分数据查询未成功,已保留其余分析结果。可以重试或继续追问。'; if (value === 'length') return '回答达到输出长度上限,已保存现有内容。可以重试或继续追问。'; if (/timeout|超时/.test(value)) return '本轮分析达到处理时限,已保存现有结果。可以重试或继续追问。'; if (value === 'evidence_incomplete') return '本轮分析被标记为部分完成,已展示现有结果。可以继续追问。'; return '本轮分析未完整结束,已保存现有结果。可以重试或继续追问。'; } /** An ended turn without a visible answer still needs an explanation beside retry. */ export function emptyAnalysisNotice(turn: Record, displayedAnswer: string): string { const result = turn.result && typeof turn.result === 'object' && !Array.isArray(turn.result) ? turn.result as Record : turn; const status = String(turn.status || result.status || '').toUpperCase(); if (displayedAnswer.trim() || !['PARTIAL', 'FAILED', 'CANCELLED', 'COMPLETED'].includes(status)) return ''; if ([result.memberList, turn.memberList, result.recordList, turn.recordList].some(value => value !== undefined && value !== null) || [result.reportMarkdown, turn.reportMarkdown, result.reportHtml, turn.reportHtml].some(value => typeof value === 'string' && value.trim())) return ''; if (status === 'CANCELLED') return '分析已停止,尚未生成回答。'; if (status === 'COMPLETED') return '此记录没有可显示的回答,请新建会话重试。'; const quality = result.answerQuality && typeof result.answerQuality === 'object' ? result.answerQuality as Record : {}; return quality.dataComplete === true ? '数据查询已完成,但未生成分析正文。请重新分析。' : '本轮未生成可显示的回答,请重新分析。'; } /** Old answers keep their original wording; surface their explicitly recorded scope limitation. */ export function hasUnreconciledEvidence(turn: Record): boolean { const record = (value: unknown): Record => value && typeof value === 'object' && !Array.isArray(value) ? value as Record : {}; const result = record(turn.result), plan = record(turn.plan || result.plan); const entries = turn.timeline || result.timeline || plan.timeline; const checks = new Map(); if (Array.isArray(entries)) for (const item of entries) { const event = record(item); if (event.kind !== 'tool_result' || event.status !== 'completed') continue; for (const [key, status] of Object.entries(record(event.evidenceChecks))) { if (/^[a-f0-9]{16}$/.test(key) && typeof status === 'string' && ['unresolved', 'checked', 'expected'].includes(status)) checks.set(key, status); } } if (checks.size) return [...checks.values()].includes('unresolved'); const text = [turn.answer, result.answer, ...(Array.isArray(entries) ? entries.map(item => record(item).text) : [])].filter(item => typeof item === 'string').join('\n'); return /未(?:与|和)[^。!?\n]{0,24}(?:对账|核对)|未(?:完全)?对账/.test(text); } /** A stopped turn may save its last pre-tool progress note; keep it in chronology, * but do not repeat it as a final answer below later tool results. */ export function partialAnswerIsOnlyProgress(turn: Record): boolean { const record = (value: unknown): Record => value && typeof value === 'object' && !Array.isArray(value) ? value as Record : {}; const result = record(turn.result), plan = record(turn.plan || result.plan); if (String(turn.status || result.status).toUpperCase() !== 'PARTIAL') return false; const answer = String(result.answer || turn.answer || '').trim(); const entries = turn.timeline || result.timeline || plan.timeline; if (!answer || !Array.isArray(entries)) return false; let lastAssistant = -1; for (let index = entries.length - 1; index >= 0; index--) { if (record(entries[index]).kind === 'assistant') { lastAssistant = index; break; } } if (lastAssistant < 0 || String(record(entries[lastAssistant]).text || '').trim() !== answer) return false; return entries.slice(lastAssistant + 1).some(item => ['tool_start', 'tool_result'].includes(String(record(item).kind))); } /** Tool event names describe a step, never the lifecycle of the whole turn. */ export function analysisStreamStatus(previous: unknown, event: string, reported: unknown): string { const prior = String(previous || '').toUpperCase(); const terminal = new Set(['COMPLETED', 'PARTIAL', 'FAILED', 'CANCELLED', 'NEEDS_CLARIFICATION']); if (terminal.has(prior)) return prior; const name = event.toUpperCase().replaceAll('.', '_').replaceAll('-', '_'); const status = String(reported || '').toUpperCase(); if (/^(?:TURN_)?(COMPLETED|PARTIAL|FAILED|CANCELLED|NEEDS_CLARIFICATION)$/.test(name)) return name.replace(/^TURN_/, ''); if (!name.startsWith('TOOL_') && (analysisIsRunning(status) || terminal.has(status))) return status; if (name.startsWith('TOOL_') || name === 'ANSWER') return 'RUNNING'; return analysisIsRunning(prior) ? prior : 'RUNNING'; }