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 function analysisScrollFollows(previousTop: number, currentTop: number, distanceFromBottom: number, following: boolean): boolean { if (currentTop < previousTop - 0.1) return false; return distanceFromBottom <= 24 ? true : following; } export function partialAnalysisNotice(reason: unknown): string { const value = String(reason || ''); if (value === 'mcp_error') return '部分数据查询未成功,已保留其余分析结果。可以重试或继续追问。'; if (value === 'length') return '回答达到输出长度上限,已保存现有内容。可以重试或继续追问。'; if (/timeout|超时/.test(value)) return '本轮分析达到处理时限,已保存现有结果。可以重试或继续追问。'; if (value === 'evidence_incomplete') return '所需数据尚未齐全,已展示现有结果。可以继续追问。'; return '本轮分析未完整结束,已保存现有结果。可以重试或继续追问。'; } /** 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))); }