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
+410
View File
@@ -0,0 +1,410 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { Activity, RotateCw, ArrowDownToLine, ArrowRight, ArrowUp, BookOpenText, Check, ChevronDown, ChevronRight, Code2, Copy, File, FileCode2, Folder, FolderOpen, GitBranch, Link2, LoaderCircle, Maximize2, MessageSquare, Minimize2, PanelLeftClose, PanelLeftOpen, Pencil, Play, Plus, Search, Settings2, ShieldCheck, Square, SquareTerminal, Trash2, X } from 'lucide-react';
import type { Bootstrap, Change, Config, FileEntry, OpenFile, Project, ResearchDoc, Session, SessionBrief, ToolEvent, RuntimeDiagnostics, RuntimeFailure } from './types';
import { api, downloadBlob, exportSession, setToken } from './api';
import { DiffView, EmptyInspector, IconButton, Modal, ResearchContent, Status, ToolRow, FailureCard } from './components';
import { DiagnosticsPanel } from './DiagnosticsPanel';
const activeStates = ['running', 'awaiting_approval', 'stopping'];
const defaultConfig: Config = { mode: 'demo', baseUrl: 'http://127.0.0.1:11434/v1', model: '', contextLimit: 16000, maxSteps: 12, maxOutputTokens: 2048, hasKey: false };
export default function App() {
const [token, setAccess] = useState('');
const [version, setVersion] = useState('1.0.0');
const [diagnosticsOpen, setDiagnosticsOpen] = useState(false);
const [diagnostics, setDiagnostics] = useState<RuntimeDiagnostics | null>(null);
const [diagnosticsBusy, setDiagnosticsBusy] = useState(false);
const [resuming, setResuming] = useState(false);
const [modelCheck, setModelCheck] = useState<{ kind: 'success' | 'error'; message: string } | null>(null);
const [projects, setProjects] = useState<Project[]>([]);
const [briefs, setBriefs] = useState<SessionBrief[]>([]);
const [projectId, setProjectId] = useState('');
const [sessionId, setSessionId] = useState('');
const [session, setSession] = useState<Session | null>(null);
const [config, setConfig] = useState<Config>(defaultConfig);
const [exampleId, setExampleId] = useState<string | null>(null);
const [files, setFiles] = useState<FileEntry[]>([]);
const [filter, setFilter] = useState('');
const [collapsed, setCollapsed] = useState<Set<string>>(new Set());
const [openFile, setOpenFile] = useState<OpenFile | null>(null);
const [fileLoading, setFileLoading] = useState(false);
const [draftSaving, setDraftSaving] = useState(false);
const [changeBusy, setChangeBusy] = useState('');
const [deciding, setDeciding] = useState(false);
const [editing, setEditing] = useState(false);
const [draft, setDraft] = useState('');
const [composer, setComposer] = useState('');
const [sending, setSending] = useState(false);
const [creatingSession, setCreatingSession] = useState(false);
const [tab, setTab] = useState<'file' | 'changes' | 'trace'>('file');
const [changeId, setChangeId] = useState('');
const [eventId, setEventId] = useState('');
const [wide, setWide] = useState(false);
const [sidebarOpen, setSidebarOpen] = useState(() => window.innerWidth > 620);
const [narrow, setNarrow] = useState(() => window.innerWidth <= 940);
const [mobile, setMobile] = useState(() => window.innerWidth <= 620);
const [connected, setConnected] = useState(false);
const [settingsOpen, setSettingsOpen] = useState(false);
const [settings, setSettings] = useState<Config>(defaultConfig);
const [keyValue, setKeyValue] = useState('');
const [clearKey, setClearKey] = useState(false);
const [models, setModels] = useState<string[]>([]);
const [settingsBusy, setSettingsBusy] = useState(false);
const [projectOpen, setProjectOpen] = useState(false);
const [projectInput, setProjectInput] = useState('');
const [toast, setToast] = useState('');
const [researchOpen, setResearchOpen] = useState(false);
const [researchDocs, setResearchDocs] = useState<ResearchDoc[]>([]);
const [report, setReport] = useState<{ title: string; content: string } | null>(null);
const chatEnd = useRef<HTMLDivElement>(null);
const conversationRef = useRef<HTMLElement>(null);
const composerRef = useRef<HTMLTextAreaElement>(null);
const filterRef = useRef<HTMLInputElement>(null);
const selectedSessionRef = useRef('');
const selectedProjectRef = useRef('');
const revisions = useRef(new Map<string, number>());
const filesRequest = useRef(0);
const fileRequest = useRef(0);
const reportRequest = useRef(0);
const sessionCreation = useRef<Promise<Session | null> | null>(null);
const selectedProject = projects.find(project => project.id === projectId);
const isRunning = !!session && activeStates.includes(session.status);
const anyRunning = briefs.some(item => activeStates.includes(item.status));
const pending = session?.changes.filter(change => ['pending', 'conflict'].includes(change.status)) || [];
const selectedChange = session?.changes.find(change => change.id === changeId) || pending[0] || session?.changes.at(-1);
const selectedEvent = session?.events.find(event => event.id === eventId) || session?.events.at(-1);
const approval = session?.approvals.find(item => item.status === 'pending');
const projectSessions = briefs.filter(item => item.projectId === projectId);
const visibleFiles = useMemo(() => {
const children = new Map<string, FileEntry[]>();
for (const file of files) {
const parent = file.path.split('/').slice(0, -1).join('/');
children.set(parent, [...(children.get(parent) ?? []), file]);
}
const ordered: FileEntry[] = [];
function visit(parent: string) {
const siblings = (children.get(parent) ?? []).sort((a, b) => Number(b.kind === 'directory') - Number(a.kind === 'directory') || a.name.localeCompare(b.name));
for (const file of siblings) { ordered.push(file); if (file.kind === 'directory') visit(file.path); }
}
visit('');
return ordered.filter(file => {
if (filter) return file.path.toLocaleLowerCase().includes(filter.toLocaleLowerCase());
const parts = file.path.split('/');
for (let index = 1; index < parts.length; index++) if (collapsed.has(parts.slice(0, index).join('/'))) return false;
return true;
});
}, [files, filter, collapsed]);
function notify(message: string) { setToast(message); }
function failure(error: unknown) { notify(error instanceof Error ? error.message : String(error)); }
function selectSession(id: string) {
selectedSessionRef.current = id; setSessionId(id); setSession(null);
localStorage.setItem('awb-session', id); setChangeId(''); setEventId('');
}
function acceptSession(updated: Session) {
const revision = updated.revision ?? 0;
if (revision < (revisions.current.get(updated.id) ?? 0)) return;
revisions.current.set(updated.id, revision);
if (selectedSessionRef.current === updated.id && selectedProjectRef.current === updated.projectId) {
setSession(previous => previous?.id === updated.id && previous.revision > revision ? previous : updated);
}
setBriefs(previous => {
const remaining = previous.filter(item => item.id !== updated.id);
if (updated.archived) return remaining;
return [{ id: updated.id, projectId: updated.projectId, title: updated.title, status: updated.status, revision,
updatedAt: updated.updatedAt, changeCount: updated.changes.filter(change => ['pending', 'conflict'].includes(change.status)).length }, ...remaining]
.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
});
}
function showInspector(next: 'file' | 'changes' | 'trace') {
setTab(next);
if (window.innerWidth <= 940) setWide(true);
if (window.innerWidth <= 620) setSidebarOpen(false);
}
async function refreshFiles(id = selectedProjectRef.current) {
if (!id) return;
const request = ++filesRequest.current;
const result = await api<{ files: FileEntry[]; truncated: boolean }>('/projects/' + id + '/files');
if (request === filesRequest.current && selectedProjectRef.current === id) setFiles(result.files);
}
async function chooseProject(id: string, preferredSession?: string) {
selectedProjectRef.current = id; setProjectId(id); localStorage.setItem('awb-project', id);
filesRequest.current++; fileRequest.current++;
setOpenFile(null); setFiles([]); setFileLoading(false); setEditing(false); setCollapsed(new Set()); setFilter('');
const candidate = preferredSession || briefs.find(item => item.projectId === id)?.id || '';
selectSession(candidate);
if (window.innerWidth <= 620) setSidebarOpen(false);
}
async function chooseSession(id: string) {
selectSession(id);
if (window.innerWidth <= 620) setSidebarOpen(false);
}
async function newSession() {
if (sessionCreation.current) return sessionCreation.current;
if (!projectId) { setProjectOpen(true); return null; }
const targetProject = projectId, targetSelection = selectedSessionRef.current;
setCreatingSession(true);
const request = (async () => {
try {
const created = await api<Session>('/sessions', { projectId: targetProject });
if (selectedProjectRef.current !== targetProject || selectedSessionRef.current !== targetSelection) { acceptSession(created); return null; }
selectSession(created.id); acceptSession(created); setTab('file');
if (window.innerWidth <= 620) setSidebarOpen(false);
return created;
} finally { sessionCreation.current = null; setCreatingSession(false); }
})();
sessionCreation.current = request;
return request;
}
async function submit() {
if (!composer.trim() || sending || isRunning || (sessionId && !session)) return;
if (config.mode === 'compatible' && !config.model) { openSettings(); notify('请先填写模型名称。'); return; }
setSending(true);
const content = composer.trim();
try {
const target = session || await newSession();
if (!target) return;
acceptSession(await api<Session>('/sessions/' + target.id + '/messages', { content }));
if (selectedSessionRef.current === target.id) {
setComposer(previous => previous.trim() === content ? '' : previous); composerRef.current?.focus();
}
} catch (error) { failure(error); }
finally { setSending(false); }
}
async function openProject() {
if (!projectInput.trim()) return;
try {
const project = await api<Project>('/projects', { root: projectInput.trim() });
setProjects(previous => [project, ...previous.filter(item => item.id !== project.id)]);
await chooseProject(project.id); setProjectOpen(false); setProjectInput('');
notify('已打开项目 ' + project.name);
} catch (error) { failure(error); }
}
async function loadFile(relative: string) {
if (!projectId) return;
const targetProject = projectId, request = ++fileRequest.current;
showInspector('file'); setFileLoading(true); setEditing(false);
try {
const file = await api<OpenFile>('/projects/' + targetProject + '/file?path=' + encodeURIComponent(relative));
if (fileRequest.current === request && selectedProjectRef.current === targetProject) { setOpenFile(file); setDraft(file.content); }
} catch (error) { if (fileRequest.current === request) failure(error); }
finally { if (fileRequest.current === request) setFileLoading(false); }
}
async function saveDraft() {
if (!openFile || draftSaving) return;
const file = openFile, content = draft;
setDraftSaving(true);
try {
const target = session || await newSession(); if (!target) return;
const updated = await api<Session>('/sessions/' + target.id + '/proposals', { path: file.path, content, reason: '手动编辑文件', base_sha256: file.sha256 });
acceptSession(updated);
if (selectedSessionRef.current === target.id) { setChangeId(updated.changes.at(-1)?.id || ''); setEditing(false); showInspector('changes'); notify('编辑内容已保存为待审查提案。'); }
} catch (error) { failure(error); } finally { setDraftSaving(false); }
}
async function changeAction(change: Change, action: 'apply' | 'reject') {
if (!session || changeBusy || isRunning) return;
const targetSession = session.id, targetProject = projectId, currentFileRequest = fileRequest.current;
setChangeBusy(change.id);
try {
const updated = await api<Session>('/sessions/' + targetSession + '/changes/' + change.id + '/' + action, {});
acceptSession(updated); await refreshFiles(targetProject);
if (action === 'apply' && openFile?.path === change.path && selectedProjectRef.current === targetProject && currentFileRequest === fileRequest.current) {
const file = await api<OpenFile>('/projects/' + targetProject + '/file?path=' + encodeURIComponent(change.path));
if (selectedProjectRef.current === targetProject && currentFileRequest === fileRequest.current) { setOpenFile(file); setDraft(file.content); setEditing(false); }
}
notify(action === 'apply' ? '已应用 ' + change.path : '已撤回提案。');
} catch (error) { failure(error); } finally { setChangeBusy(''); }
}
async function decide(allow: boolean) {
if (!session || !approval || deciding) return;
setDeciding(true);
try { acceptSession(await api<Session>('/sessions/' + session.id + '/approvals/' + approval.id, { allow })); }
catch (error) { failure(error); } finally { setDeciding(false); }
}
function openSettings() { setSettings(config); setKeyValue(''); setClearKey(false); setModels([]); setModelCheck(null); setSettingsOpen(true); }
async function saveSettings() {
setSettingsBusy(true);
try {
const payload = { ...settings, ...(keyValue || clearKey ? { apiKey: clearKey ? '' : keyValue } : {}) };
const saved = await api<Config>('/config', payload); setConfig(saved); setSettingsOpen(false);
notify(saved.mode === 'demo' ? '已切换到离线演示。' : '模型连接已保存。API Key 仅在本次服务内存中使用。');
} catch (error) { failure(error); } finally { setSettingsBusy(false); }
}
async function readModels() {
setSettingsBusy(true);
try {
const result = await api<{ models: string[] }>('/config/models', { baseUrl: settings.baseUrl, ...(keyValue || clearKey ? { apiKey: clearKey ? '' : keyValue } : {}) });
setModels(result.models);
if (!settings.model && result.models[0]) setSettings(previous => ({ ...previous, model: result.models[0] }));
notify('读到 ' + result.models.length + ' 个模型。');
} catch (error) { failure(error); } finally { setSettingsBusy(false); }
}
async function openDiagnostics() {
const targetId = sessionId;
setDiagnosticsOpen(true); setDiagnosticsBusy(true);
if (diagnostics?.session?.session.id !== targetId) setDiagnostics(null);
try { const value = await api<RuntimeDiagnostics>('/diagnostics' + (targetId ? '?session=' + encodeURIComponent(targetId) : '')); if (selectedSessionRef.current === targetId) setDiagnostics(value); }
catch (error) { failure(error); } finally { setDiagnosticsBusy(false); }
}
async function resumeSession() {
if (!session || resuming || isRunning) return;
setResuming(true);
try { acceptSession(await api<Session>('/sessions/' + session.id + '/resume', {})); }
catch (error) { failure(error); } finally { setResuming(false); }
}
async function testModel() {
setSettingsBusy(true); setModelCheck(null);
try {
const result = await api<{ ok: boolean; durationMs: number }>('/config/test', { baseUrl: settings.baseUrl, model: settings.model,
...(keyValue || clearKey ? { apiKey: clearKey ? '' : keyValue } : {}) });
setModelCheck({ kind: 'success', message: '模型响应验证通过,用时 ' + (result.durationMs / 1000).toFixed(1) + ' 秒。' });
} catch (error) { setModelCheck({ kind: 'error', message: error instanceof Error ? error.message : String(error) }); }
finally { setSettingsBusy(false); }
}
function failureForMessage(message: { id: string; content: string; createdAt: string }): RuntimeFailure | null {
if (session?.failure?.messageId === message.id) return session.failure;
const recorded = session?.events.filter(event => event.kind === 'error' && event.output === message.content && event.diagnostic).at(-1);
if (recorded?.diagnostic) return recorded.diagnostic;
if (message.content.trim() === 'fetch failed') return { source: 'model_connection', stage: 'model_request', kind: 'network',
title: '模型服务连接失败', message: '工作台在请求模型响应时发生连接失败。已应用改动和执行记录保留。',
detail: '这是旧版的 fetch failed 记录,旧版未保存更具体的连接原因。', suggestion: '可以查看当前运行诊断和模型连接。', occurredAt: message.createdAt, historical: true };
return null;
}
async function openResearch() {
try { setResearchDocs(await api<ResearchDoc[]>('/research')); setReport(await api('/research/overview')); setResearchOpen(true); }
catch (error) { failure(error); }
}
async function loadReport(id: string) {
const request = ++reportRequest.current;
try { const document = await api<{ title: string; content: string }>('/research/' + id); if (request === reportRequest.current) setReport(document); }
catch (error) { if (request === reportRequest.current) failure(error); }
}
useEffect(() => {
let alive = true;
api<Bootstrap>('/bootstrap').then(result => {
if (!alive) return;
setToken(result.token); setAccess(result.token); setVersion(result.version); setProjects(result.projects); setBriefs(result.sessions); setConfig(result.config); setSettings(result.config); setExampleId(result.exampleProjectId);
const savedProject = localStorage.getItem('awb-project');
const id = result.projects.some(project => project.id === savedProject) ? savedProject! : result.exampleProjectId || result.projects[0]?.id || '';
selectedProjectRef.current = id; setProjectId(id);
const savedSession = localStorage.getItem('awb-session');
const session = result.sessions.find(item => item.id === savedSession && item.projectId === id) || result.sessions.find(item => item.projectId === id);
if (session) selectSession(session.id);
}).catch(error => { if (alive) failure(error); });
return () => { alive = false; };
}, []);
useEffect(() => { if (token && projectId) refreshFiles(projectId).catch(failure); }, [token, projectId]);
useEffect(() => {
if (!token || !sessionId) return;
let alive = true;
api<Session>('/sessions/' + sessionId).then(result => { if (alive) acceptSession(result); }).catch(error => { if (alive) failure(error); });
return () => { alive = false; };
}, [token, sessionId]);
useEffect(() => {
if (!token) return;
const source = new EventSource('/api/events?token=' + encodeURIComponent(token));
source.onopen = () => {
setConnected(true);
const current = selectedSessionRef.current;
if (current) api<Session>('/sessions/' + current).then(acceptSession).catch(failure);
};
source.onerror = () => setConnected(false);
source.onmessage = event => {
const update = JSON.parse(event.data);
if (update.kind !== 'session') return;
acceptSession(update.session as Session);
};
return () => source.close();
}, [token]);
useEffect(() => { if (toast) { const timeout = setTimeout(() => setToast(''), 6000); return () => clearTimeout(timeout); } }, [toast]);
useEffect(() => {
const viewport = conversationRef.current;
if (viewport) viewport.scrollTop = viewport.scrollHeight;
}, [session?.messages.length, session?.events.length, approval?.id]);
useEffect(() => {
let previousMobile = window.innerWidth <= 620;
const update = () => {
const nextMobile = window.innerWidth <= 620;
setNarrow(window.innerWidth <= 940); setMobile(nextMobile);
if (nextMobile && !previousMobile) { setSidebarOpen(false); setWide(false); }
previousMobile = nextMobile;
};
window.addEventListener('resize', update); return () => window.removeEventListener('resize', update);
}, []);
useEffect(() => {
const handler = (event: KeyboardEvent) => {
if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 'k') { event.preventDefault(); setSidebarOpen(true); setWide(false); requestAnimationFrame(() => filterRef.current?.focus()); }
if (event.key === 'Escape') { if (window.innerWidth <= 940) setWide(false); if (window.innerWidth <= 620) setSidebarOpen(false); }
};
window.addEventListener('keydown', handler); return () => window.removeEventListener('keydown', handler);
}, []);
const entries = [...(session?.messages || []).map(message => ({ id: message.id, date: message.createdAt, message })),
...(session?.events || []).filter(event => event.kind !== 'error').map(event => ({ id: event.id, date: event.createdAt, event }))].sort((a, b) => a.date.localeCompare(b.date));
const toolEvents = session?.events || [];
const lineCount = openFile?.content.split('\n').length || 0;
const ready = !!token && connected;
return (
<div className={'workbench ' + (sidebarOpen ? '' : 'sidebar-hidden ') + (wide ? 'inspector-wide' : '')}>
<aside className="project-sidebar">
<div className="brand"><span className="brand-mark">AW</span><div><strong>Agent Workbench</strong><span>本地编程工作台 · 正式版</span></div><IconButton label="收起项目栏" onClick={() => setSidebarOpen(false)}><PanelLeftClose size={16} /></IconButton></div>
<div className="project-selector"><span className="field-eyebrow">当前项目</span><div className="project-select-row"><FolderOpen size={17} /><select aria-label="当前项目" value={projectId} onChange={event => chooseProject(event.target.value)}>{projects.map(project => <option key={project.id} value={project.id}>{project.name}{project.id === exampleId ? '(示例)' : ''}</option>)}{!projects.length && <option value="">选择一个项目</option>}</select><IconButton label="打开项目" onClick={() => setProjectOpen(true)}><Plus size={15} /></IconButton></div>{selectedProject && <span className="project-root" title={selectedProject.root}>{selectedProject.root}</span>}{projectId === exampleId && <span className="example-tag">当前为自带示例,可打开自己的项目开始开发</span>}</div>
<div className="sidebar-section sessions-section"><div className="section-label"><span>任务会话</span><IconButton label="新建任务" disabled={creatingSession} onClick={() => newSession().catch(failure)}><Plus size={15} /></IconButton></div>
<button type="button" className="new-task-button" disabled={creatingSession} onClick={() => newSession().catch(failure)}><Plus size={15} />新建任务<span>↵</span></button>
<div className="session-list">{projectSessions.slice(0, 15).map(item => <div key={item.id} className={'session-item ' + (item.id === sessionId ? 'selected' : '')}>
<button type="button" className="session-select" onClick={() => chooseSession(item.id)}><MessageSquare size={14} /><span>{item.title}</span>{item.changeCount > 0 && <b>{item.changeCount}</b>}</button>
{!activeStates.includes(item.status) && <IconButton label={'归档会话 ' + item.title} onClick={() => api('/sessions/' + item.id + '/archive', {}).then(() => { if (item.id === selectedSessionRef.current) selectSession(''); }).catch(failure)}><Trash2 size={12} /></IconButton>}
</div>)}{!projectSessions.length && <p className="sidebar-hint">开始一个任务,过程会自动保存。</p>}</div>
</div>
<div className="sidebar-section file-section"><div className="section-label"><span>项目文件 <b>{files.filter(file => file.kind === 'file').length}</b></span><IconButton label="刷新文件" onClick={() => refreshFiles().catch(failure)}><Folder size={14} /></IconButton></div>
<div className="file-filter"><Search size={14} /><input ref={filterRef} value={filter} onChange={event => setFilter(event.target.value)} placeholder="筛选文件" aria-label="筛选文件" /><kbd>⌃ K</kbd></div>
<div className="file-tree">{visibleFiles.map(file => <button key={file.path} type="button" title={file.path} className={'tree-row ' + (openFile?.path === file.path ? 'selected' : '')} style={{ paddingLeft: 10 + Math.min(file.path.split('/').length - 1, 6) * 13 }} onClick={() => {
if (file.kind === 'directory') setCollapsed(previous => { const next = new Set(previous); if (next.has(file.path)) next.delete(file.path); else next.add(file.path); return next; }); else loadFile(file.path);
}}>{file.kind === 'directory' ? <><span className="tree-chevron">{collapsed.has(file.path) ? <ChevronRight size={11} /> : <ChevronDown size={11} />}</span><Folder size={14} /></> : <><span className="tree-chevron" /><File size={13} /></>}<span>{filter ? file.path : file.name}</span></button>)}{filter && !visibleFiles.length && <p className="sidebar-hint">没有匹配的文件。</p>}</div>
</div>
<div className="sidebar-footer"><button onClick={openResearch}><BookOpenText size={16} />机制研究与设计<ChevronRight size={13} /></button><button onClick={() => openDiagnostics()}><Activity size={16} />运行诊断<ChevronRight size={13} /></button><button onClick={openSettings}><Settings2 size={16} />模型连接<ChevronRight size={13} /></button><div className={'connection ' + (ready ? 'connected' : '')}><span />{ready ? '本地服务已连接' : '正在连接本地服务'}<small>v{version}</small></div></div>
</aside>
<main className="task-pane">
<header className="work-header"><div className="work-title">{(!sidebarOpen || mobile) && <IconButton label="展开项目栏" onClick={() => setSidebarOpen(true)}><PanelLeftOpen size={18} /></IconButton>}<span className="header-symbol"><Code2 size={17} /></span><div><span className="header-breadcrumb">{selectedProject?.name || '工作空间'} <ChevronRight size={12} /> 任务</span><h1>{session?.title || '让任务走到完成'}</h1></div></div>
<button className={'model-button ' + (config.mode === 'demo' ? 'demo' : '')} onClick={openSettings}><span className="model-light" />{config.mode === 'demo' ? '离线演示' : config.model || '选择模型'}<ChevronDown size={13} /></button>
</header>
<div className="task-toolbar"><span className="task-local"><GitBranch size={13} />本地项目</span>{session ? <Status value={session.status} /> : <span className="subtle">等待新任务</span>}<div className="toolbar-actions">
<IconButton label="运行诊断" onClick={() => openDiagnostics()}><Activity size={15} /></IconButton>
{narrow && <><IconButton label="查看文件" onClick={() => showInspector('file')}><FileCode2 size={16} /></IconButton><IconButton label="查看改动" onClick={() => showInspector('changes')}><GitBranch size={16} /></IconButton><IconButton label="查看执行轨迹" onClick={() => showInspector('trace')}><SquareTerminal size={16} /></IconButton></>}
{pending.length > 0 && <button className="text-button review-toolbar" onClick={() => { setChangeId(pending[0].id); showInspector('changes'); }}><FileCode2 size={13} />审核 {pending.length} 项</button>}
{session && <><IconButton label="导出会话" onClick={() => exportSession(session.id).catch(failure)}><ArrowDownToLine size={15} /></IconButton>
{!isRunning && pending.length === 0 && ['failed', 'paused'].includes(session.status) && <button className="text-button" disabled={resuming} onClick={() => resumeSession()}><RotateCw size={13} />{session.status === 'failed' && session.failure?.source === 'model_connection' ? '重试模型请求' : '继续任务'}</button>}</>}
</div></div>
<section ref={conversationRef} className="conversation" aria-label="任务对话">
{!session?.messages.length && !session?.events.length ? <div className="welcome"><span className="welcome-label"><span />从项目到结果</span><h2>读懂项目。<br />把每一步做好。</h2><p>给出一个任务,读取依据、工具执行和文件改动会在这里连成完整过程。</p><div className="starter-prompts">{['了解这个项目,并提出一项改进', '查找关键实现,解释调用关系', '检查项目,并准备可审查的修改'].map((prompt, index) => <button key={prompt} onClick={() => { setComposer(prompt); composerRef.current?.focus(); }}><span>{index === 0 ? <FolderOpen size={17} /> : index === 1 ? <Link2 size={17} /> : <FileCode2 size={17} />}</span>{prompt}<ArrowRight size={14} /></button>)}</div><div className="welcome-note"><ShieldCheck size={16} /><span>文件修改先审查,终端命令逐次确认。</span></div>{config.mode === 'demo' && <div className="demo-note"><span>演示</span>固定脚本会调用真实本地工具,不进行模型推理。</div>}</div> : <div className="conversation-entries">
{session?.recoveryNotice && <div className="recovery-note"><ShieldCheck size={16} /><div><strong>已恢复会话记录</strong><p>{session.recoveryNotice}</p></div></div>}
{entries.map(entry => 'message' in entry && entry.message ? <div key={entry.id} className={'message message-' + entry.message.role}><span className="message-avatar">{entry.message.role === 'user' ? '你' : entry.message.role === 'assistant' ? 'AW' : '·'}</span><div className="message-body"><div className="message-label">{entry.message.role === 'user' ? '你的任务' : entry.message.role === 'assistant' ? session?.executionMode === 'demo' ? '演示执行器' : '编程助手' : '工作台'}<time>{new Date(entry.date).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })}</time></div><div className="message-text">{entry.message.role === 'system' && failureForMessage(entry.message)
? <FailureCard failure={failureForMessage(entry.message)!} onDiagnose={() => openDiagnostics()} onRetry={session?.status === 'failed' && session?.failure?.messageId === entry.message.id ? () => resumeSession() : undefined} busy={resuming || isRunning} />
: entry.message.role === 'assistant' ? <ResearchContent content={entry.message.content} /> : entry.message.content}</div></div></div> : 'event' in entry && entry.event ? <div key={entry.id} className="inline-event">{['tool', 'model'].includes(entry.event.kind) ? <ToolRow event={entry.event} onSelect={() => { setEventId(entry.event!.id); showInspector('trace'); }} /> : <div className={'system-event event-' + entry.event.phase}><span />{entry.event.label}{entry.event.output && <p>{entry.event.output}</p>}</div>}</div> : null)}
{isRunning && !approval && <div className="working-note"><LoaderCircle size={14} className="spin" /><span>{session?.executionMode === 'demo' ? '正在执行演示流程' : '正在处理任务'}</span></div>}
</div>}
{approval && <div className="approval-card"><div className="approval-heading"><span><ShieldCheck size={17} /></span><div><strong>确认这次终端执行</strong><p>{approval.reason}</p></div></div><pre>{approval.command}</pre><div className="approval-path"><Folder size={12} /><span>{approval.cwd}</span></div><p className="approval-shell">{approval.shell || '项目终端'} · UTF-8</p><p className="approval-scope">确认后以你的系统权限执行。</p><div className="approval-actions"><button className="button secondary" onClick={() => decide(false)} disabled={deciding}>拒绝执行</button><button className="button primary" onClick={() => decide(true)} disabled={deciding}><Play size={14} />确认执行</button></div></div>}
{pending.length > 0 && !isRunning && <button className="review-callout" onClick={() => { setChangeId(pending[0].id); showInspector('changes'); }}><FileCode2 size={17} /><span><strong>{pending.length} 项改动等待审查</strong><small>查看差异后,再应用到项目文件。</small></span><ArrowRight size={17} /></button>}
<div ref={chatEnd} />
</section>
<footer className="composer-wrap"><form className="composer" onSubmit={event => { event.preventDefault(); submit(); }}><textarea ref={composerRef} aria-label="任务内容" placeholder={config.mode === 'demo' ? '先体验完整流程,或连接自己的模型开始开发…' : '描述项目任务,或询问工作台的执行状态与报错…'} value={composer} onChange={event => setComposer(event.target.value)} onKeyDown={event => { if ((event.ctrlKey || event.metaKey) && event.key === 'Enter') { event.preventDefault(); submit(); } }} maxLength={20000} rows={3} /><div className="composer-bottom"><span><Folder size={13} />{selectedProject?.name || '选择项目'}<span className="composer-divider" />{config.mode === 'demo' ? '固定演示脚本' : '兼容模型服务'}</span>{isRunning ? <button type="button" className="stop-button" onClick={() => session && api('/sessions/' + session.id + '/stop', {}).catch(failure)}><Square size={13} />停止</button> : <button type="submit" className="send-button" aria-label="发送任务" disabled={!composer.trim() || sending || creatingSession || !ready || !!(sessionId && !session)}>{sending ? <LoaderCircle size={17} className="spin" /> : <ArrowUp size={18} />}</button>}</div></form><div className="composer-footnote"><span>Ctrl + Enter 发送 · 会话自动保存</span><span>{session?.estimatedTokens ? '上下文估算 ' + session.estimatedTokens.toLocaleString() + ' tokens' : '改动与执行结果可追溯'}</span></div></footer>
</main>
{((mobile && sidebarOpen) || (narrow && wide)) && <button type="button" className="panel-scrim" aria-label="关闭侧边面板" onClick={() => { setSidebarOpen(false); setWide(false); }} />}
<aside className="inspector">
<div className="inspector-tabs"><button className={tab === 'file' ? 'selected' : ''} onClick={() => setTab('file')}><FileCode2 size={14} />文件</button><button className={tab === 'changes' ? 'selected' : ''} onClick={() => setTab('changes')}><GitBranch size={14} />改动{pending.length > 0 && <b>{pending.length}</b>}</button><button className={tab === 'trace' ? 'selected' : ''} onClick={() => setTab('trace')}><SquareTerminal size={14} />轨迹</button><IconButton label={narrow ? '关闭检视区' : wide ? '缩小检视区' : '放大检视区'} onClick={() => setWide(previous => !previous)}>{narrow ? <X size={16} /> : wide ? <Minimize2 size={14} /> : <Maximize2 size={14} />}</IconButton></div>
{tab === 'file' && (fileLoading ? <div className="loading-inspector"><LoaderCircle className="spin" size={24} />正在读取文件</div> : openFile ? <div className="file-inspector"><div className="file-heading"><FileCode2 size={15} /><span title={openFile.path}>{openFile.path}</span><IconButton label="复制文件内容" onClick={() => navigator.clipboard.writeText(openFile.content).then(() => notify('已复制文件内容。')).catch(failure)}><Copy size={14} /></IconButton><IconButton label={editing ? '取消编辑' : '编辑文件'} onClick={() => { setEditing(previous => !previous); setDraft(openFile.content); }}><Pencil size={14} /></IconButton></div><div className="file-details"><span>{lineCount} 行 · {openFile.bytes.toLocaleString()} B</span><span className="code-utility">{openFile.sha256.slice(0, 10)}</span></div>{editing ? <><textarea className="code-editor" aria-label="编辑文件内容" spellCheck={false} value={draft} onChange={event => setDraft(event.target.value)} /><div className="editor-actions"><button className="button primary" onClick={saveDraft} disabled={draft === openFile.content || draftSaving}><GitBranch size={14} />保存为提案</button></div></> : <div className="code-view">{openFile.content.split('\n').map((line, index) => <div key={index}><span>{index + 1}</span><code>{line.replace(/\r$/, '') || ' '}</code></div>)}</div>}</div> : <EmptyInspector kind="file" />)}
{tab === 'changes' && (selectedChange ? <div className="changes-inspector"><div className="change-list">{session?.changes.map(change => <button key={change.id} className={selectedChange.id === change.id ? 'selected' : ''} onClick={() => setChangeId(change.id)}><FileCode2 size={14} /><span>{change.path}</span><span className="change-stats"><b>+{change.additions}</b><i>−{change.deletions}</i></span></button>)}</div><div className="change-summary"><div><strong>{selectedChange.path}</strong><Status value={selectedChange.status} /></div><p>{selectedChange.reason}</p></div><DiffView change={selectedChange} /><div className="change-actions">{['pending', 'conflict'].includes(selectedChange.status) ? <><button className="button secondary" onClick={() => changeAction(selectedChange, 'reject')} disabled={!!changeBusy || isRunning}>撤回提案</button><button className="button primary" disabled={selectedChange.status !== 'pending' || !!changeBusy || isRunning} onClick={() => changeAction(selectedChange, 'apply')}><Check size={14} />应用这项改动</button></> : <span className="subtle">{selectedChange.status === 'applied' ? '这项改动已写入项目。' : '这项提案已结束。'}</span>}<IconButton label="下载建议内容" onClick={() => downloadBlob(new Blob([selectedChange.content], { type: 'text/plain;charset=utf-8' }), selectedChange.path.split('/').at(-1) || 'proposal.txt')}><ArrowDownToLine size={15} /></IconButton></div></div> : <EmptyInspector kind="changes" />)}
{tab === 'trace' && (session?.events.length ? <div className="trace-inspector"><div className="trace-caption"><span>完整执行记录</span><span>{toolEvents.length} 次工具调用</span></div><div className="trace-list">{session.events.map(event => <ToolRow key={event.id} event={event} selected={selectedEvent?.id === event.id} onSelect={() => setEventId(event.id)} />)}</div>{selectedEvent && <div className="event-details"><div className="event-detail-heading"><strong>{selectedEvent.label}</strong><Status value={selectedEvent.phase} /></div>{selectedEvent.input && <><h4>输入</h4><pre>{JSON.stringify(selectedEvent.input, null, 2)}</pre></>}<h4>结果</h4><pre>{selectedEvent.output || (selectedEvent.phase === 'waiting' ? '等待确认后执行。' : '正在等待工具结果。')}</pre>{selectedEvent.durationMs !== undefined && <p className="subtle">耗时 {(selectedEvent.durationMs / 1000).toFixed(2)} 秒,包含确认等待。</p>}</div>}</div> : <EmptyInspector kind="trace" />)}
<div className="inspector-footer"><ShieldCheck size={13} /><span>{tab === 'changes' ? '应用前会核对文件基线' : tab === 'trace' ? '中断调用保留待核实状态' : '读取范围限定在当前项目'}</span></div>
</aside>
{projectOpen && <Modal title="打开项目" description="选择要在本机读取和开发的项目文件夹。" onClose={() => setProjectOpen(false)}><form onSubmit={event => { event.preventDefault(); openProject(); }}><label className="form-field">项目文件夹<input autoFocus value={projectInput} onChange={event => setProjectInput(event.target.value)} placeholder="C:\Projects\my-app" aria-label="项目文件夹路径" /></label><div className="modal-actions">{exampleId && <button type="button" className="button secondary" onClick={() => { chooseProject(exampleId); setProjectOpen(false); }}>打开示例项目</button>}<button type="submit" className="button primary" disabled={!projectInput.trim()}><FolderOpen size={15} />打开项目</button></div></form></Modal>}
{settingsOpen && <Modal title="模型连接" description="同一套项目工具,可以使用离线演示或你自己的模型服务。" onClose={() => setSettingsOpen(false)}><form onSubmit={event => { event.preventDefault(); saveSettings(); }}><div className="mode-picker"><button type="button" className={settings.mode === 'demo' ? 'selected' : ''} onClick={() => setSettings(previous => ({ ...previous, mode: 'demo' }))}><Play size={18} /><strong>离线演示</strong><span>固定脚本,真实本地工具</span></button><button type="button" className={settings.mode === 'compatible' ? 'selected' : ''} onClick={() => setSettings(previous => ({ ...previous, mode: 'compatible' }))}><Link2 size={18} /><strong>兼容模型服务</strong><span>使用自己的本地或远程模型</span></button></div>
{settings.mode === 'compatible' && <><div className="connection-presets"><button type="button" onClick={() => setSettings(previous => ({ ...previous, baseUrl: 'http://127.0.0.1:11434/v1' }))}>Ollama</button><button type="button" onClick={() => setSettings(previous => ({ ...previous, baseUrl: 'http://127.0.0.1:8000/v1' }))}>vLLM</button><span>Chat Completions 兼容接口</span></div><label className="form-field">接口根地址<input type="url" value={settings.baseUrl} onChange={event => setSettings(previous => ({ ...previous, baseUrl: event.target.value }))} placeholder="http://127.0.0.1:11434/v1" /></label><label className="form-field">API Key(按服务要求填写)<input type="password" autoComplete="off" value={keyValue} onChange={event => { setKeyValue(event.target.value); setClearKey(false); }} placeholder={config.hasKey ? '本次运行已设置,留空保留' : '本地服务可以不填'} /></label><div className="key-note"><span>只在本次服务内存中使用,不写入会话与配置。</span>{config.hasKey && <button type="button" onClick={() => { setClearKey(true); setKeyValue(''); }}>{clearKey ? '保存后清除' : '清除 Key'}</button>}</div><div className="model-field"><label className="form-field">模型名称<input list="model-list" value={settings.model} onChange={event => setSettings(previous => ({ ...previous, model: event.target.value }))} placeholder="例如 qwen3:8b" /><datalist id="model-list">{models.map(model => <option key={model} value={model} />)}</datalist></label><button className="button secondary" type="button" onClick={readModels} disabled={settingsBusy || anyRunning}>{settingsBusy ? <LoaderCircle size={14} className="spin" /> : <Search size={14} />}读取模型列表</button></div><div className="model-test-row"><span>填写服务提供的接口根地址。</span><button type="button" className="button secondary" onClick={testModel} disabled={settingsBusy || anyRunning || !settings.model}><Activity size={14} />验证模型响应</button></div>{modelCheck && <div className={'model-check model-check-' + modelCheck.kind} role="status">{modelCheck.message}</div>}</>}
<details className="budget-settings"><summary>上下文与任务预算<ChevronDown size={13} /></summary><div className="budget-fields"><label>上下文预算<input type="number" min={1000} max={200000} value={settings.contextLimit} onChange={event => setSettings(previous => ({ ...previous, contextLimit: Number(event.target.value) }))} /></label><label>最大工具轮次<input type="number" min={1} max={30} value={settings.maxSteps} onChange={event => setSettings(previous => ({ ...previous, maxSteps: Number(event.target.value) }))} /></label><label>输出上限<input type="number" min={256} max={16000} value={settings.maxOutputTokens} onChange={event => setSettings(previous => ({ ...previous, maxOutputTokens: Number(event.target.value) }))} /></label></div><p>上下文使用本地估算,服务返回的实际 usage 另行保留。</p></details>{anyRunning && <p className="form-warning">有任务在执行,请先停止任务再改变连接。</p>}<div className="modal-actions"><button type="button" className="button secondary" onClick={() => setSettingsOpen(false)}>取消</button><button type="submit" className="button primary" disabled={settingsBusy || anyRunning}><Check size={15} />保存连接</button></div></form></Modal>}
{diagnosticsOpen && <Modal title="运行诊断" description="查看工作台的模型连接、终端环境、最近错误和文件实际状态。" wide onClose={() => setDiagnosticsOpen(false)}><DiagnosticsPanel value={diagnostics} busy={diagnosticsBusy} onRefresh={() => openDiagnostics()} /></Modal>}
{researchOpen && <Modal title="机制研究与独立设计" description="从分发客户端的静态证据提炼产品机制。运行时与远端服务的未知部分在报告中说明。" wide onClose={() => setResearchOpen(false)}><div className="research-layout"><nav>{researchDocs.map(document => <button className={report?.title === document.title ? 'selected' : ''} key={document.id} onClick={() => loadReport(document.id)}><BookOpenText size={15} /><span><strong>{document.title}</strong><small>{document.description}</small></span></button>)}</nav><article className="research-document">{report && <ResearchContent content={report.content} />}</article></div></Modal>}
{toast && <div className="toast" role="status"><span>{toast}</span><IconButton label="关闭提示" onClick={() => setToast('')}><X size={14} /></IconButton></div>}
</div>
);
}
+17
View File
@@ -0,0 +1,17 @@
import { Activity, LoaderCircle, RotateCw } from 'lucide-react';
import type { RuntimeDiagnostics } from './types';
import { Status } from './components';
export function DiagnosticsPanel({ value, busy, onRefresh }: { value: RuntimeDiagnostics | null; busy: boolean; onRefresh: () => void }) {
if (!value) return <div className="diagnostic-loading"><LoaderCircle size={20} className="spin" />{busy ? '正在读取本机执行记录…' : '诊断记录暂时不可用,请刷新重试。'}<button type="button" className="button secondary" disabled={busy} onClick={onRefresh}>刷新</button></div>;
const failure = value.session?.lastFailure;
return <div className="diagnostic-panel">
<div className="diagnostic-intro"><Activity size={18} /><div><strong>Agent Workbench {value.version}</strong><p>依据本机保存的执行记录检查当前状态。</p></div><button type="button" className="button secondary" onClick={onRefresh} disabled={busy}><RotateCw size={13} className={busy ? 'spin' : ''} />刷新</button></div>
<div className="diagnostic-grid"><section><h3>运行环境</h3><dl><dt>终端</dt><dd>{value.environment.shell}</dd><dt>Node.js</dt><dd>{value.environment.node}</dd><dt>输入与输出</dt><dd>{value.environment.encoding}</dd></dl><p className="diagnostic-note">{value.environment.shellSyntax}</p></section>
<section><h3>模型连接</h3><dl><dt>模式</dt><dd>{value.connection.mode === 'demo' ? '离线演示' : '兼容模型服务'}</dd><dt>模型</dt><dd>{value.connection.model || '未配置'}</dd><dt>服务地址</dt><dd>{value.connection.endpoint}</dd><dt>凭据状态</dt><dd>{value.connection.hasKey ? '本次运行已配置' : '未配置'}</dd></dl>{value.connection.lastRequest && <p className="diagnostic-note">最近请求:{value.connection.lastRequest.status === 'completed' ? '成功' : value.connection.lastRequest.status === 'retrying' ? '重试中' : value.connection.lastRequest.status === 'interrupted' ? '已停止' : '失败'} · {value.connection.lastRequest.attempts ?? 1} 次</p>}</section></div>
{value.session && <section className="diagnostic-session"><div className="diagnostic-section-heading"><h3>当前项目与会话</h3><Status value={value.session.session.status} /></div><strong>{value.session.project.name}</strong><p className="diagnostic-path">{value.session.project.root}</p><p className="diagnostic-note">{value.session.changes.filter(change => change.status === 'applied').length} 项已应用 · {value.session.changes.filter(change => ['pending', 'conflict'].includes(change.status)).length} 项待处理</p></section>}
{failure && <section className="diagnostic-failure"><div className="diagnostic-section-heading"><h3>最近的错误记录</h3><span>{failure.source === 'model_connection' ? '模型服务请求' : '工作台任务'}</span></div><strong>{failure.title}</strong><p>{failure.message}</p>{failure.detail && <p>{failure.detail}</p>}{failure.occurredAt && <small>{new Date(failure.occurredAt).toLocaleString('zh-CN')}</small>}{failure.suggestion && <p className="diagnostic-note">{failure.suggestion}</p>}</section>}
{!!value.session?.changes.length && <section><h3>文件改动的实际状态</h3><div className="diagnostic-changes">{value.session.changes.map(change => <div key={change.id}><code>{change.path}</code><Status value={change.status} /></div>)}</div></section>}
{!!value.session?.recentTools.length && <section><h3>近期工具结果</h3><div className="diagnostic-tools">{value.session.recentTools.slice(-8).map((tool, index) => <details key={index}><summary><code>{tool.tool}</code><Status value={tool.phase} />{tool.exitCode !== null && <span>退出码 {tool.exitCode}</span>}</summary><pre>{tool.outputExcerpt || '没有文本输出。'}</pre></details>)}</div></section>}
</div>;
}
+23
View File
@@ -0,0 +1,23 @@
let accessToken = '';
export function setToken(token: string) { accessToken = token; }
export async function api<T>(path: string, input?: unknown): Promise<T> {
const response = await fetch('/api' + path, {
method: input === undefined ? 'GET' : 'POST',
headers: { 'Content-Type': 'application/json', ...(accessToken ? { 'X-Workbench-Token': accessToken } : {}) },
...(input === undefined ? {} : { body: JSON.stringify(input) }),
});
const body = await response.json();
if (!response.ok) throw new Error(body.error || '请求失败,请重试。');
return body as T;
}
export async function exportSession(id: string) {
const response = await fetch('/api/sessions/' + id + '/export', { headers: { 'X-Workbench-Token': accessToken } });
if (!response.ok) throw new Error('会话导出失败。');
const blob = await response.blob();
downloadBlob(blob, 'agent-workbench-session-' + id + '.json');
}
export function downloadBlob(blob: Blob, name: string) {
const url = URL.createObjectURL(blob);
const link = document.createElement('a'); link.href = url; link.download = name; link.click();
setTimeout(() => URL.revokeObjectURL(url), 1000);
}
+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} />;
}
+5
View File
@@ -0,0 +1,5 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import './styles.css';
ReactDOM.createRoot(document.getElementById('root')!).render(<React.StrictMode><App /></React.StrictMode>);
File diff suppressed because one or more lines are too long
+46
View File
@@ -0,0 +1,46 @@
export interface Config {
mode: 'demo' | 'compatible'; baseUrl: string; model: string;
contextLimit: number; maxSteps: number; maxOutputTokens: number; hasKey: boolean;
}
export interface Project { id: string; root: string; name: string; addedAt: string }
export interface SessionBrief { id: string; projectId: string; title: string; status: string; revision: number; updatedAt: string; changeCount: number }
export interface Message { id: string; role: string; content: string; createdAt: string }
export interface ToolEvent {
id: string; kind: string; label: string; phase: string; createdAt: string; tool?: string;
input?: Record<string, unknown>; output?: string; durationMs?: number; startedAt?: string; finishedAt?: string;
source?: string; attempts?: number; diagnostic?: RuntimeFailure; exitCode?: number;
}
export interface DiffPart { value: string; count: number; added?: boolean; removed?: boolean }
export interface Change {
id: string; path: string; reason: string; status: string; baseExists: boolean; baseSha256: string | null;
baseContent: string; content: string; sha256: string; diff: DiffPart[]; additions: number; deletions: number;
createdAt: string; appliedAt?: string;
}
export interface Approval { id: string; command: string; reason: string; cwd: string; shell?: string; status: string; createdAt: string }
export interface Session {
id: string; projectId: string; title: string; status: string; revision: number; updatedAt: string; createdAt: string;
messages: Message[]; events: ToolEvent[]; changes: Change[]; approvals: Approval[];
compactions: number; estimatedTokens: number; usage: { prompt_tokens?: number; completion_tokens?: number } | null;
archived: boolean; recoveryNotice?: string | null; executionMode?: string;
failure?: RuntimeFailure | null; lastFailure?: RuntimeFailure | null;
}
export interface RuntimeFailure {
source: string; stage: string; kind: string; title: string; message: string; messageId?: string;
detail?: string; suggestion?: string; attempts?: number; httpStatus?: number; code?: string | null;
occurredAt?: string; retryable?: boolean; historical?: boolean; endpoint?: string; model?: string;
}
export interface ExecutionEnvironment { platform: string; node: string; shell: string; encoding: string; shellSyntax: string }
export interface RuntimeDiagnostics {
version: string; environment: ExecutionEnvironment;
connection: { mode: string; endpoint: string; model: string; hasKey: boolean; lastRequest: { status?: string; attempts?: number; durationMs?: number } | null };
session: {
project: { name: string; root: string }; session: { id: string; status: string; revision: number };
lastFailure: RuntimeFailure | null;
changes: { id: string; path: string; status: string }[];
recentTools: { tool: string; phase: string; outputExcerpt: string; exitCode: number | null }[];
} | null;
}
export interface FileEntry { path: string; name: string; kind: string; bytes: number }
export interface OpenFile { path: string; content: string; sha256: string; bytes: number }
export interface Bootstrap { token: string; version: string; config: Config; projects: Project[]; sessions: SessionBrief[]; exampleProjectId: string | null; environment?: ExecutionEnvironment }
export interface ResearchDoc { id: string; title: string; description: string }