import { useEffect, useRef } from 'react'; import type { ReactNode, ButtonHTMLAttributes } from 'react'; import { createPortal } from 'react-dom'; import { AlertTriangle, Check, ChevronRight, Circle, Clock3, FileCode2, LoaderCircle, RotateCw, ShieldQuestion, SquareTerminal, X, XCircle } from 'lucide-react'; import type { Change, ToolEvent, RuntimeFailure } from './types'; import { ModelErrorDetails } from './ModelErrorDetails'; const statusNames: Record = { idle: '就绪', running: '执行中', awaiting_approval: '等待确认', needs_review: '待审查', completed: '已完成', paused: '已暂停', failed: '需要处理', stopping: '正在停止', pending: '待审查', applied: '已应用', rejected: '已撤回', conflict: '文件已变化', waiting: '等待确认', denied: '已拒绝', interrupted: '已中断', retrying: '自动重试', queued: '待执行', validating: '核对中', unknown: '结果待核对', unverified: '未验证', not_configured: '尚未检查', passed: '检查通过', cancelled: '已取消', stale: '需重新检查', planned: '待确认', preparing: '准备提交', prepared: '准备完成', publishing: '发布本地提交', committed: '已生成提交', reporting: '生成报告', ready: '可核验', blocked: '等待前置', verified: '已核验', incomplete: '尚未完成', needs_update: '要求已更新', not_planned: '尚未规划', snapshotting: '封存构建', launching: '启动浏览器', closing: '关闭浏览器', observed: '页面已观察', applying: '应用中', rolling_back: '回退中', rolled_back: '已回退', partial: '部分结果待核对', resolved_external: '已保留外部修改', external_preserved: '外部内容已保留', }; export function Status({ value }: { value: string }) { return {statusNames[value] || value}; } export function IconButton({ label, children, className = '', ...props }: ButtonHTMLAttributes & { label: string; children: ReactNode }) { return ; } export function Modal({ title, description, children, onClose, wide = false }: { title: string; description?: string; children: ReactNode; onClose: () => void; wide?: boolean }) { const panel = useRef(null); const close = useRef(onClose); close.current = onClose; useEffect(() => { const previous = document.activeElement as HTMLElement | null; panel.current?.querySelector('input, select, textarea, button')?.focus(); const handle = (event: KeyboardEvent) => { const dialogs = document.querySelectorAll('[role="dialog"][aria-modal="true"]'); if (dialogs[dialogs.length - 1] !== panel.current) return; if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); close.current(); } if (event.key === 'Tab') { const elements = Array.from(panel.current?.querySelectorAll('button, input, select, textarea, a[href]') || []) .filter(element => !element.hasAttribute('disabled') && element.offsetParent !== null); const first = elements[0], last = elements.at(-1); if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last?.focus(); } else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first?.focus(); } } }; document.addEventListener('keydown', handle); return () => { document.removeEventListener('keydown', handle); if (previous?.isConnected) previous.focus(); }; }, []); return createPortal(
{ if (event.target === event.currentTarget) onClose(); }}>

{title}

{description &&

{description}

}
{children}
, document.body); } export function DiffView({ change }: { change: Change }) { const viewport = useRef(null); function jumpToFirstChange() { const area = viewport.current, row = area?.querySelector('.diff-added, .diff-removed'); if (area && row) area.scrollTop += row.getBoundingClientRect().top - area.getBoundingClientRect().top - 85; } useEffect(() => { const frame = requestAnimationFrame(jumpToFirstChange); return () => cancelAnimationFrame(frame); }, [change.id]); let before = 1, after = 1; const rows: { before: number | null; after: number | null; text: string; kind: string }[] = []; for (const part of change.diff) { const lines = part.value.split('\n'); if (lines.at(-1) === '') lines.pop(); for (const line of lines) { rows.push({ before: part.added ? null : before++, after: part.removed ? null : after++, text: line.replace(/\r$/, ''), kind: part.added ? 'added' : part.removed ? 'removed' : 'same' }); } } return
{change.baseExists ? '原文件 → 建议内容' : '新建文件'}{change.baseSha256?.slice(0, 10) || 'NEW'}
{rows.length ? rows.map((row, index) =>
{row.before}{row.after} {row.kind === 'added' ? '+' : row.kind === 'removed' ? '−' : ' '}{row.text || ' '}
) :

建议内容为空。

}
; } export function ToolRow({ event, selected = false, onSelect }: { event: ToolEvent; selected?: boolean; onSelect: () => void }) { const phase = event.phase; const label = event.kind === 'model' && event.diagnostic?.kind === 'model_identity' ? event.diagnostic.title : event.label; const Symbol = ['waiting', 'unknown', 'unverified', 'queued', 'validating'].includes(phase) ? ShieldQuestion : ['running', 'retrying'].includes(phase) ? LoaderCircle : ['failed', 'denied', 'interrupted'].includes(phase) ? XCircle : Check; const detail = event.tool === 'run_command' ? String(event.input?.command || '') : ['read_file', 'propose_file', 'propose_patch'].includes(event.tool || '') ? String(event.input?.path || '') : ['search_files', 'query_code'].includes(event.tool || '') ? String(event.input?.query || '') : event.tool === 'list_files' ? '项目目录' : event.tool === 'index_project' ? '当前项目 · 声明与导入' : event.tool === 'inspect_session' ? '会话 · 错误 · 当前状态' : event.kind === 'model' ? '模型服务' + (event.attempts && event.attempts > 1 ? ' · 第 ' + event.attempts + ' 次' : '') : ''; return ; } export function ModelStreamPreview({ event }: { event: ToolEvent }) { const stream = event.stream; if (!stream || stream.status === 'completed') return null; return
{stream.status === 'receiving' ? '正在接收' : '输出未完成'}{stream.protocol === 'responses' ? 'Responses' : 'Chat Completions'} · {stream.textCharacters ?? 0} 字符{stream.toolFragments ? ' · ' + stream.toolFragments + ' 个工具参数片段' : ''}
{stream.textPreview &&
{stream.textPreview}
}

片段仅供查看。完整响应核对前不执行工具;中断后保留原记录。

; } export function FailureCard({ failure, onDiagnose, onRetry, busy = false }: { failure: RuntimeFailure; onDiagnose: () => void; onRetry?: () => void; busy?: boolean }) { return
{failure.source === 'model_connection' ? '模型连接' : '工作台运行'}{failure.title}

{failure.message}

{failure.suggestion &&

{failure.suggestion}

}
{failure.stage === 'model_request' ? '发生在请求模型响应时' : '发生在工作台任务执行时'}{failure.attempts && {failure.attempts} 次请求}{failure.httpStatus && HTTP {failure.httpStatus}}{failure.code && {failure.code}}
{onRetry && }
; } export function EmptyInspector({ kind }: { kind: 'file' | 'changes' | 'trace' }) { const Icon = kind === 'file' ? FileCode2 : kind === 'changes' ? Check : SquareTerminal; return

{kind === 'file' ? '查看项目文件' : kind === 'changes' ? '这里展示待审查改动' : '执行过程会记录在这里'}

{kind === 'file' ? '从左侧打开文件,或让助手先读取项目。' : kind === 'changes' ? '助手提出修改后,可以查看完整差异,再决定是否应用。' : '每次工具调用都会保留参数、结果和完成状态。'}

; } function inlineText(text: string): ReactNode[] { const pattern = /(`[^`]+`|\*\*[^*]+\*\*|\[[^\]]+\]\([^)]+\))/g; const nodes: ReactNode[] = []; let previous = 0; for (const match of text.matchAll(pattern)) { const index = match.index!; if (index > previous) nodes.push(text.slice(previous, index)); const token = match[0]; if (token.startsWith('`')) nodes.push({token.slice(1, -1)}); else if (token.startsWith('**')) nodes.push({token.slice(2, -2)}); else { const parts = token.match(/^\[([^\]]+)\]\(([^)]+)\)$/)!; nodes.push(/^https?:\/\//.test(parts[2]) ? {parts[1]} : {parts[1]}); } previous = index + token.length; } if (previous < text.length) nodes.push(text.slice(previous)); return nodes; } export function ResearchContent({ content }: { content: string }) { const lines = content.replaceAll('\r', '').split('\n'); const blocks: ReactNode[] = []; const cells = (line: string) => line.replace(/^\|/, '').replace(/\|$/, '').split('|').map(cell => cell.trim()); for (let index = 0; index < lines.length; index++) { const line = lines[index]; if (!line.trim()) continue; const heading = line.match(/^(#{1,4})\s+(.+)/); if (heading) { const Tag = heading[1].length <= 1 ? 'h2' : heading[1].length === 2 ? 'h3' : 'h4'; blocks.push({inlineText(heading[2])}); continue; } if (line.startsWith('```')) { const body = []; const key = index; while (++index < lines.length && !lines[index].startsWith('```')) body.push(lines[index]); blocks.push(
{body.join('\n')}
); continue; } if (line.includes('|') && /^\s*\|?[\s:|-]+\|?\s*$/.test(lines[index + 1] ?? '') && lines[index + 1]?.includes('---')) { const headings = cells(line), rows = [], key = index; index++; while (lines[index + 1]?.includes('|') && lines[index + 1].trim()) rows.push(cells(lines[++index])); blocks.push(
{headings.map((cell, column) => )}{rows.map((row, position) => {row.map((cell, column) => )})}
{inlineText(cell)}
{inlineText(cell)}
); continue; } const list = line.match(/^\s*(-|\d+\.)\s+(.+)/); if (list) { const ordered = list[1] !== '-', values = [list[2]], key = index; while (true) { const next = lines[index + 1]?.match(/^\s*(-|\d+\.)\s+(.+)/); if (!next || (next[1] !== '-') !== ordered) break; values.push(next[2]); index++; } const Tag = ordered ? 'ol' : 'ul'; blocks.push({values.map((value, position) =>
  • {inlineText(value)}
  • )}
    ); continue; } const body = [line], key = index; while (lines[index + 1]?.trim() && !/^(#{1,4}\s|```|\s*(-|\d+\.)\s|\|)/.test(lines[index + 1])) body.push(lines[++index]); blocks.push(

    {inlineText(body.join(' '))}

    ); } return
    {blocks}
    ; } export function PhaseIcon({ phase }: { phase: string }) { if (phase === 'running') return ; if (phase === 'waiting') return ; if (phase === 'completed') return ; return ; }