191 lines
14 KiB
TypeScript
191 lines
14 KiB
TypeScript
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<string, string> = {
|
||
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 <span className={'status status-' + value}><span className="status-dot" />{statusNames[value] || value}</span>;
|
||
}
|
||
export function IconButton({ label, children, className = '', ...props }: ButtonHTMLAttributes<HTMLButtonElement> & { label: string; children: ReactNode }) {
|
||
return <button type="button" className={'icon-button ' + className} aria-label={label} title={label} {...props}>{children}</button>;
|
||
}
|
||
export function Modal({ title, description, children, onClose, wide = false }: { title: string; description?: string; children: ReactNode; onClose: () => void; wide?: boolean }) {
|
||
const panel = useRef<HTMLDivElement>(null);
|
||
const close = useRef(onClose); close.current = onClose;
|
||
useEffect(() => {
|
||
const previous = document.activeElement as HTMLElement | null;
|
||
panel.current?.querySelector<HTMLElement>('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<HTMLElement>('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(<div className="modal-backdrop" onMouseDown={event => { if (event.target === event.currentTarget) onClose(); }}>
|
||
<div ref={panel} role="dialog" aria-modal="true" aria-label={title} className={'modal ' + (wide ? 'modal-wide' : '')}>
|
||
<div className="modal-heading"><div><h2>{title}</h2>{description && <p>{description}</p>}</div><IconButton label="关闭窗口" onClick={onClose}><X size={18} /></IconButton></div>
|
||
{children}
|
||
</div>
|
||
</div>, document.body);
|
||
}
|
||
export function DiffView({ change }: { change: Change }) {
|
||
const viewport = useRef<HTMLDivElement>(null);
|
||
function jumpToFirstChange() {
|
||
const area = viewport.current, row = area?.querySelector<HTMLElement>('.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 <div className="diff-view" aria-label={'文件差异 ' + change.path} ref={viewport}>
|
||
<div className="diff-caption"><span>{change.baseExists ? '原文件 → 建议内容' : '新建文件'}</span><button type="button" className="diff-jump" onClick={jumpToFirstChange}>定位首处改动</button><span className="code-utility">{change.baseSha256?.slice(0, 10) || 'NEW'}</span></div>
|
||
{rows.length ? rows.map((row, index) => <div key={index} className={'diff-line diff-' + row.kind}>
|
||
<span className="line-number">{row.before}</span><span className="line-number">{row.after}</span>
|
||
<span className="diff-sign">{row.kind === 'added' ? '+' : row.kind === 'removed' ? '−' : ' '}</span><code>{row.text || ' '}</code>
|
||
</div>) : <p className="subtle empty-line">建议内容为空。</p>}
|
||
</div>;
|
||
}
|
||
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 <button type="button" onClick={onSelect} className={'tool-row ' + (selected ? 'selected ' : '') + 'tool-' + phase}>
|
||
<span className="tool-symbol"><Symbol size={14} className={['running', 'retrying'].includes(phase) ? 'spin' : ''} /></span>
|
||
<span className="tool-name"><strong>{label}</strong>{detail && <span>{detail}</span>}</span>
|
||
<span className="tool-end">{event.durationMs !== undefined ? (event.durationMs / 1000).toFixed(1) + 's' : phase === 'waiting' ? '待确认' : '…'}<ChevronRight size={13} /></span>
|
||
</button>;
|
||
}
|
||
|
||
export function ModelStreamPreview({ event }: { event: ToolEvent }) {
|
||
const stream = event.stream;
|
||
if (!stream || stream.status === 'completed') return null;
|
||
return <div className="model-stream-preview" aria-label="模型输出片段"><div><strong>{stream.status === 'receiving' ? '正在接收' : '输出未完成'}</strong><span>{stream.protocol === 'responses' ? 'Responses' : 'Chat Completions'} · {stream.textCharacters ?? 0} 字符{stream.toolFragments ? ' · ' + stream.toolFragments + ' 个工具参数片段' : ''}</span></div>
|
||
{stream.textPreview && <pre>{stream.textPreview}</pre>}<p>片段仅供查看。完整响应核对前不执行工具;中断后保留原记录。</p></div>;
|
||
}
|
||
|
||
export function FailureCard({ failure, onDiagnose, onRetry, busy = false }: { failure: RuntimeFailure; onDiagnose: () => void; onRetry?: () => void; busy?: boolean }) {
|
||
return <div className="failure-card" role="alert">
|
||
<div className="failure-heading"><AlertTriangle size={17} /><span>{failure.source === 'model_connection' ? '模型连接' : '工作台运行'}</span><strong>{failure.title}</strong></div>
|
||
<p>{failure.message}</p>
|
||
{failure.suggestion && <p className="failure-suggestion">{failure.suggestion}</p>}
|
||
<div className="failure-meta"><span>{failure.stage === 'model_request' ? '发生在请求模型响应时' : '发生在工作台任务执行时'}</span>{failure.attempts && <span>{failure.attempts} 次请求</span>}{failure.httpStatus && <code>HTTP {failure.httpStatus}</code>}{failure.code && <code>{failure.code}</code>}</div>
|
||
<ModelErrorDetails failure={failure} />
|
||
<div className="failure-actions"><button type="button" className="button secondary" onClick={onDiagnose}>查看运行诊断</button>{onRetry && <button type="button" className="button primary" onClick={onRetry} disabled={busy}><RotateCw size={14} />{failure.source === 'model_connection' ? '重试模型请求' : '继续任务'}</button>}</div>
|
||
</div>;
|
||
}
|
||
export function EmptyInspector({ kind }: { kind: 'file' | 'changes' | 'trace' }) {
|
||
const Icon = kind === 'file' ? FileCode2 : kind === 'changes' ? Check : SquareTerminal;
|
||
return <div className="empty-inspector"><span className="empty-inspector-symbol"><Icon size={25} strokeWidth={1.5} /></span>
|
||
<h3>{kind === 'file' ? '查看项目文件' : kind === 'changes' ? '这里展示待审查改动' : '执行过程会记录在这里'}</h3>
|
||
<p>{kind === 'file' ? '从左侧打开文件,或让助手先读取项目。' : kind === 'changes' ? '助手提出修改后,可以查看完整差异,再决定是否应用。' : '每次工具调用都会保留参数、结果和完成状态。'}</p>
|
||
</div>;
|
||
}
|
||
|
||
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(<code key={index}>{token.slice(1, -1)}</code>);
|
||
else if (token.startsWith('**')) nodes.push(<strong key={index}>{token.slice(2, -2)}</strong>);
|
||
else {
|
||
const parts = token.match(/^\[([^\]]+)\]\(([^)]+)\)$/)!;
|
||
nodes.push(/^https?:\/\//.test(parts[2]) ? <a key={index} href={parts[2]} target="_blank" rel="noreferrer">{parts[1]}</a> : <span key={index} title={parts[2]}>{parts[1]}</span>);
|
||
}
|
||
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(<Tag key={index}>{inlineText(heading[2])}</Tag>); continue;
|
||
}
|
||
if (line.startsWith('```')) {
|
||
const body = []; const key = index;
|
||
while (++index < lines.length && !lines[index].startsWith('```')) body.push(lines[index]);
|
||
blocks.push(<pre key={key}><code>{body.join('\n')}</code></pre>); 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(<div key={key} className="research-table"><table><thead><tr>{headings.map((cell, column) => <th key={column}>{inlineText(cell)}</th>)}</tr></thead><tbody>{rows.map((row, position) => <tr key={position}>{row.map((cell, column) => <td key={column}>{inlineText(cell)}</td>)}</tr>)}</tbody></table></div>); 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(<Tag key={key}>{values.map((value, position) => <li key={position}>{inlineText(value)}</li>)}</Tag>); 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(<p key={key}>{inlineText(body.join(' '))}</p>);
|
||
}
|
||
return <div className="research-content">{blocks}</div>;
|
||
}
|
||
export function PhaseIcon({ phase }: { phase: string }) {
|
||
if (phase === 'running') return <LoaderCircle size={15} className="spin" />;
|
||
if (phase === 'waiting') return <Clock3 size={15} />;
|
||
if (phase === 'completed') return <Check size={15} />;
|
||
return <Circle size={15} />;
|
||
}
|