chore: baseline Agent Workbench 1.0.0

This commit is contained in:
Agent Workbench Dev
2026-10-29 11:23:43 +08:00
commit bac87da23e
167 changed files with 30172 additions and 0 deletions
+160
View File
@@ -0,0 +1,160 @@
import { useEffect, useRef } from 'react';
import type { ReactNode, ButtonHTMLAttributes } from 'react';
import { AlertTriangle, Check, ChevronRight, Circle, Clock3, FileCode2, LoaderCircle, RotateCw, ShieldQuestion, SquareTerminal, X, XCircle } from 'lucide-react';
import type { Change, ToolEvent, RuntimeFailure } from './types';
const statusNames: Record<string, string> = {
idle: '就绪', running: '执行中', awaiting_approval: '等待确认', needs_review: '待审查', completed: '已完成',
paused: '已暂停', failed: '需要处理', stopping: '正在停止', pending: '待审查', applied: '已应用',
rejected: '已撤回', conflict: '文件已变化', waiting: '等待确认', denied: '已拒绝', interrupted: '已中断',
retrying: '自动重试',
};
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) => {
if (event.key === 'Escape') { event.preventDefault(); 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); previous?.focus(); };
}, []);
return <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>;
}
export function DiffView({ change }: { change: Change }) {
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}>
<div className="diff-caption"><span>{change.baseExists ? '原文件 → 建议内容' : '新建文件'}</span><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 Symbol = phase === 'waiting' ? ShieldQuestion : ['running', 'retrying'].includes(phase) ? LoaderCircle
: ['failed', 'denied', 'interrupted'].includes(phase) ? XCircle : Check;
const detail = event.tool === 'run_command' ? String(event.input?.command || '')
: event.tool === 'read_file' || event.tool === 'propose_file' ? String(event.input?.path || '')
: event.tool === 'search_files' ? String(event.input?.query || '') : event.tool === 'list_files' ? '项目目录'
: 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>{event.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 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>
{failure.detail && failure.detail !== failure.message && <details><summary>查看错误详情</summary><p>{failure.detail}</p></details>}
<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} />;
}