feat: add project index and exact patch review

This commit is contained in:
Agent Workbench Dev
2026-10-29 17:59:35 +08:00
parent 5ec85b0319
commit 14ce622028
45 changed files with 1290 additions and 82 deletions
+29 -12
View File
@@ -5,13 +5,14 @@ import { api, downloadBlob, exportSession, setToken } from './api';
import { DiffView, EmptyInspector, IconButton, Modal, ResearchContent, Status, ToolRow, FailureCard } from './components';
import { DiagnosticsPanel } from './DiagnosticsPanel';
import { TaskPanel } from './TaskPanel';
import { CodeIndexPanel } from './CodeIndexPanel';
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, maxRunDurationMs: 600000, maxRunTokens: 200000, maxTaskTokens: 1000000 };
export default function App() {
const [token, setAccess] = useState('');
const [version, setVersion] = useState('1.2.0');
const [version, setVersion] = useState('1.3.0');
const [diagnosticsOpen, setDiagnosticsOpen] = useState(false);
const [diagnostics, setDiagnostics] = useState<RuntimeDiagnostics | null>(null);
const [diagnosticsBusy, setDiagnosticsBusy] = useState(false);
@@ -29,6 +30,8 @@ export default function App() {
const [collapsed, setCollapsed] = useState<Set<string>>(new Set());
const [openFile, setOpenFile] = useState<OpenFile | null>(null);
const [fileLoading, setFileLoading] = useState(false);
const [fileLine, setFileLine] = useState<number | null>(null);
const [fileNotice, setFileNotice] = useState('');
const [draftSaving, setDraftSaving] = useState(false);
const [changeBusy, setChangeBusy] = useState('');
const [deciding, setDeciding] = useState(false);
@@ -37,7 +40,7 @@ export default function App() {
const [composer, setComposer] = useState('');
const [sending, setSending] = useState(false);
const [creatingSession, setCreatingSession] = useState(false);
const [tab, setTab] = useState<'file' | 'changes' | 'trace' | 'task'>('file');
const [tab, setTab] = useState<'file' | 'changes' | 'trace' | 'task' | 'index'>('file');
const [changeId, setChangeId] = useState('');
const [eventId, setEventId] = useState('');
const [wide, setWide] = useState(false);
@@ -59,6 +62,7 @@ export default function App() {
const [report, setReport] = useState<{ title: string; content: string } | null>(null);
const chatEnd = useRef<HTMLDivElement>(null);
const conversationRef = useRef<HTMLElement>(null);
const codeViewRef = useRef<HTMLDivElement>(null);
const composerRef = useRef<HTMLTextAreaElement>(null);
const filterRef = useRef<HTMLInputElement>(null);
const selectedSessionRef = useRef('');
@@ -122,7 +126,7 @@ export default function App() {
.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
});
}
function showInspector(next: 'file' | 'changes' | 'trace' | 'task') {
function showInspector(next: 'file' | 'changes' | 'trace' | 'task' | 'index') {
setTab(next);
if (window.innerWidth <= 940) setWide(true);
if (window.innerWidth <= 620) setSidebarOpen(false);
@@ -136,7 +140,7 @@ export default function App() {
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('');
setOpenFile(null); setFiles([]); setFileLoading(false); setFileLine(null); setFileNotice(''); setEditing(false); setCollapsed(new Set()); setFilter('');
const candidate = preferredSession || briefs.find(item => item.projectId === id)?.id || '';
selectSession(candidate);
if (window.innerWidth <= 620) setSidebarOpen(false);
@@ -188,13 +192,17 @@ export default function App() {
notify('已打开项目 ' + project.name);
} catch (error) { failure(error); }
}
async function loadFile(relative: string) {
async function loadFile(relative: string, location?: { line: number; expectedSha256: string }) {
if (!projectId) return;
const targetProject = projectId, request = ++fileRequest.current;
showInspector('file'); setFileLoading(true); setEditing(false);
showInspector('file'); setFileLoading(true); setEditing(false); setFileLine(null); setFileNotice('');
try {
const file = await api<OpenFile>('/projects/' + targetProject + '/file?path=' + encodeURIComponent(relative));
if (fileRequest.current === request && selectedProjectRef.current === targetProject) { setOpenFile(file); setDraft(file.content); }
if (fileRequest.current === request && selectedProjectRef.current === targetProject) {
setOpenFile(file); setDraft(file.content);
if (location && file.sha256 !== location.expectedSha256) setFileNotice('文件在索引后已变化,已打开当前内容。请回到索引刷新后重新定位。');
else if (location && location.line >= 1 && location.line <= file.content.split('\n').length) setFileLine(location.line);
}
} catch (error) { if (fileRequest.current === request) failure(error); }
finally { if (fileRequest.current === request) setFileLoading(false); }
}
@@ -218,7 +226,7 @@ export default function App() {
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); }
if (selectedProjectRef.current === targetProject && currentFileRequest === fileRequest.current) { setOpenFile(file); setDraft(file.content); setEditing(false); setFileLine(null); setFileNotice(''); }
}
notify(action === 'apply' ? '已应用 ' + change.path : '已撤回提案。');
} catch (error) { failure(error); } finally { setChangeBusy(''); }
@@ -363,6 +371,14 @@ export default function App() {
const viewport = conversationRef.current;
if (viewport) viewport.scrollTop = viewport.scrollHeight;
}, [session?.messages.length, session?.events.length, approval?.id]);
useEffect(() => {
if (!fileLine || tab !== 'file' || editing) return;
const frame = requestAnimationFrame(() => {
const viewport = codeViewRef.current, line = viewport?.querySelector<HTMLElement>('[data-line="' + fileLine + '"]');
if (viewport && line) viewport.scrollTop += line.getBoundingClientRect().top - viewport.getBoundingClientRect().top - viewport.clientHeight * .35;
});
return () => cancelAnimationFrame(frame);
}, [openFile?.sha256, fileLine, tab, wide, editing]);
useEffect(() => {
let previousMobile = window.innerWidth <= 620;
const update = () => {
@@ -435,12 +451,13 @@ export default function App() {
</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><button className={tab === 'task' ? 'selected' : ''} onClick={() => setTab('task')}><ClipboardCheck 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" />)}
<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><button className={tab === 'task' ? 'selected' : ''} onClick={() => setTab('task')}><ClipboardCheck size={14} />任务</button><button className={tab === 'index' ? 'selected' : ''} onClick={() => setTab('index')}><Search 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{fileLine ? ' · 定位第 ' + fileLine + ' 行' : ''}</span><span className="code-utility">{openFile.sha256.slice(0, 10)}</span></div>{fileNotice && <div className="file-index-notice" role="status">{fileNotice}</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" ref={codeViewRef}>{openFile.content.split('\n').map((line, index) => <div key={index} data-line={index + 1} className={fileLine === index + 1 ? 'code-line-target' : ''}><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>{selectedChange.patch && <p className="patch-detail">精确补丁 · {selectedChange.patch.edits} 处替换 · {selectedChange.patch.lineEnding === 'mixed' ? '按原文核对混合换行' : '保留 ' + selectedChange.patch.lineEnding.toUpperCase() + ' 换行'}{selectedChange.patch.preservedBom ? ' · 保留 BOM' : ''}</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" />)}
{tab === 'task' && (session ? <TaskPanel key={session.id} session={session} onSession={acceptSession} onError={failure} busy={isRunning} /> : <EmptyInspector kind="trace" />)}
<div className="inspector-footer"><ShieldCheck size={13} /><span>{tab === 'changes' ? '应用前会核对文件基线' : tab === 'trace' ? '中断调用保留待核实状态' : tab === 'task' ? '任务目标、检查与结果持久保存' : '读取范围限定在当前项目'}</span></div>
{selectedProject && <CodeIndexPanel key={selectedProject.id} project={selectedProject} active={tab === 'index'} onOpen={(path, line, expectedSha256) => void loadFile(path, { line, expectedSha256 })} />}
<div className="inspector-footer"><ShieldCheck size={13} /><span>{tab === 'changes' ? '应用前会核对文件基线' : tab === 'trace' ? '中断调用保留待核实状态' : tab === 'task' ? '任务目标、检查与结果持久保存' : tab === 'index' ? '结果绑定当前项目及文件 SHA256' : '读取范围限定在当前项目'}</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>
+34
View File
@@ -0,0 +1,34 @@
.code-index-panel{display:flex;flex:1;flex-direction:column;min-height:0;overflow:hidden;background:#FCFDFC}
.code-index-panel[hidden]{display:none}
.index-heading{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:17px 16px 13px;border-bottom:1px solid #dde8e3}
.index-heading>div{min-width:0}.index-heading .field-eyebrow{display:block;max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.index-heading h3{margin:7px 0 0;font-family:Bahnschrift,'Segoe UI','Microsoft YaHei',sans-serif;font-size:20px;font-weight:600;color:#154B4A}
.index-search{padding:13px 16px;border-bottom:1px solid #dde8e3;background:#FCFDFC}
.index-query{display:flex;align-items:center;gap:8px;padding:0 10px;border:1px solid #b8ccc4;border-radius:7px;color:#154B4A;background:white}
.index-query:focus-within{border-color:#4664D9;box-shadow:0 0 0 2px #4664D918}
.index-query input{flex:1;min-width:0;width:100%;border:0!important;box-shadow:none!important;padding:10px 0;background:transparent;outline:none;font-size:12px;color:#1C2E32}
.index-query input:focus-visible{outline:none!important}
.index-search-controls{display:flex;justify-content:space-between;gap:9px;margin-top:9px}.index-search-controls select{min-width:0;flex:1;border:1px solid #ccdcd4;background:#EDF3F1;border-radius:6px;padding:7px 9px;color:#1C2E32;font-size:12px}
.index-search-controls .button{padding:7px 13px;font-size:12px;min-width:78px;justify-content:center}
.index-scroll{flex:1;min-height:0;overflow:auto;padding:13px 16px 20px}
.index-coverage{border-left:3px solid #154B4A;background:#EDF3F1;padding:11px 12px;font-size:11px;line-height:1.6;color:#526b63}
.index-coverage>div{display:flex;justify-content:space-between;gap:8px}.index-coverage strong{color:#154B4A;font-size:12px}.index-coverage p{margin:5px 0;color:#1C2E32;font-variant-numeric:tabular-nums}.index-coverage.partial{border-color:#A16C21;background:#A16C210B}.index-coverage.partial strong{color:#A16C21}
.index-scope{margin:10px 0 16px;font-size:11px;color:#526b63;line-height:1.8}.index-scope summary{cursor:pointer;color:#154B4A}.index-scope p{margin:7px 0}.index-scope>code{display:block;font-size:10px;overflow-wrap:anywhere;line-height:1.7;margin-top:5px}
.index-result-caption{display:flex;justify-content:space-between;gap:8px;font-size:11px;color:#60736d;padding:0 0 9px}.index-result-caption>span:first-child{min-width:0;overflow-wrap:anywhere}.index-result-caption>span:last-child{flex-shrink:0}
.index-results{display:flex;flex-direction:column;gap:8px}
.index-result{width:100%;text-align:left;padding:12px 10px;border:1px solid #d8e4de;border-radius:7px;background:#FCFDFC;transition:border-color .15s,background .15s;color:#1C2E32;cursor:pointer}
.index-result:hover:not(:disabled){border-color:#154B4A;background:#EDF3F150}.index-result:disabled{opacity:.55;cursor:default}.index-result:focus-visible{outline:2px solid #4664D9;outline-offset:2px}
.index-result-title{display:flex;align-items:center;gap:6px;color:#154B4A}.index-result-title>strong{font-family:'Cascadia Code',Consolas,monospace;font-size:12px;overflow-wrap:anywhere;min-width:0;flex:1}.index-result-title>span{flex-shrink:0;font-size:10px;color:#526b63;padding:1px 5px;background:#EDF3F1;border-radius:3px}.index-result-title>svg{flex-shrink:0}
.index-result-location{display:flex;align-items:baseline;gap:1px;margin:7px 0;color:#526b63;font-family:'Cascadia Code',Consolas,monospace;font-size:11px}.index-result-location>span{min-width:0;overflow-wrap:anywhere}.index-result-location>b{color:#4664D9;font-weight:500;flex-shrink:0}
.index-signature{display:block;width:100%;font-size:10px;color:#61736c;white-space:nowrap;text-overflow:ellipsis;overflow:hidden}.index-target{font-size:10px;overflow-wrap:anywhere;color:#526b63;line-height:1.7;margin:6px 0 0}
.index-result-evidence{display:flex;justify-content:space-between;gap:6px;margin-top:8px;font-size:10px;color:#73827b}.index-result-evidence>code{font-size:10px;flex-shrink:0}
.index-empty{text-align:center;padding:35px 13px;color:#60736d;font-size:12px;line-height:1.8}.index-empty>svg{color:#154B4A}.index-empty h4{font-size:14px;color:#154B4A;margin:12px 0 4px}.index-empty p{margin:0}
.index-limit{font-size:11px;line-height:1.8;margin:14px 0 0;color:#60736d}.index-error,.index-warnings{font-size:11px;line-height:1.8;background:#A16C210B;border:1px solid #A16C2135;border-radius:6px;padding:10px;margin:0 0 12px;color:#76541f}.index-error p,.index-warnings p{margin:5px 0;overflow-wrap:anywhere}.index-warnings p>span{display:block;font-family:'Cascadia Code',Consolas,monospace;color:#1C2E32;font-size:10px}
.file-index-notice{padding:10px 13px;border-bottom:1px solid #A16C2135;background:#A16C210B;color:#76541f;font-size:11px;line-height:1.7;flex-shrink:0}
.code-view>div.code-line-target{background:#4664D915;box-shadow:inset 3px 0 #4664D9}.code-view>div.code-line-target>span{color:#4664D9;font-weight:600}
.patch-detail{color:#154B4A!important;font-size:11px!important}
.inspector-tabs{gap:3px;padding-left:8px;padding-right:8px}.inspector-tabs>button:not(.icon-button){white-space:nowrap;flex-shrink:0;padding-left:6px;padding-right:6px;gap:4px}.inspector-tabs>.icon-button{flex-shrink:0}
.diff-caption{position:sticky;top:0;z-index:1;background:#FCFDFC}.diff-jump{font-size:10px;color:#4664D9;white-space:nowrap;padding:3px 5px;border-radius:3px}.diff-jump:hover{background:#4664D910}
@media(max-width:1250px){.inspector-tabs{gap:1px;padding-left:7px;padding-right:7px}.inspector-tabs>button:not(.icon-button){padding-left:7px;padding-right:7px}}
@media(max-width:620px){.index-heading,.index-search{padding-left:13px;padding-right:13px}.index-scroll{padding-left:13px;padding-right:13px}}
@media(prefers-reduced-motion:reduce){.index-result{transition:none}}
+84
View File
@@ -0,0 +1,84 @@
import { useEffect, useRef, useState } from 'react';
import { ArrowUpRight, FileCode2, LoaderCircle, RefreshCw, Search } from 'lucide-react';
import { api } from './api';
import type { CodeQuery, CodeQueryKind, CodeResult, Project } from './types';
import './CodeIndexPanel.css';
const kindNames: Record<string, string> = { function: '函数', method: '方法', class: '类', interface: '接口', type: '类型', enum: '枚举', binding: '变量' };
const resultName = (result: CodeResult) => result.resultKind === 'symbol' ? result.qualifiedName || result.name : result.name;
export function CodeIndexPanel({ project, active, onOpen }: {
project: Project; active: boolean; onOpen: (path: string, line: number, sha256: string) => void;
}) {
const [query, setQuery] = useState('');
const [kind, setKind] = useState<CodeQueryKind>('all');
const [result, setResult] = useState<CodeQuery | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
const request = useRef(0);
const initialLoad = useRef(false);
async function search(nextKind = kind) {
const current = ++request.current;
setBusy(true); setError('');
try {
const response = await api<CodeQuery>('/projects/' + project.id + '/code-query?query=' + encodeURIComponent(query.trim()) + '&kind=' + nextKind + '&limit=40');
if (current !== request.current || response.index.projectId !== project.id) return;
setResult(response);
} catch (cause) {
if (current === request.current) setError(cause instanceof Error ? cause.message : String(cause));
} finally { if (current === request.current) setBusy(false); }
}
useEffect(() => () => { request.current++; initialLoad.current = false; }, [project.id, project.root]);
useEffect(() => {
if (active && !initialLoad.current) { initialLoad.current = true; void search(); }
}, [active]);
const index = result?.index, coverage = index?.coverage;
return <section className="code-index-panel" aria-label="工程索引" hidden={!active}>
<header className="index-heading"><div><span className="field-eyebrow">当前项目 · {project.name}</span><h3>定位代码</h3></div>
<button className="icon-button" aria-label="刷新工程索引" title="重新核对文件变化并刷新结果" disabled={busy} onClick={() => void search()}>
{busy ? <LoaderCircle size={16} className="spin" /> : <RefreshCw size={16} />}
</button>
</header>
<form className="index-search" onSubmit={event => { event.preventDefault(); void search(); }}>
<label className="index-query"><Search size={15} /><input aria-label="索引查询" maxLength={200} placeholder="函数、类、文件名或导入" value={query} onChange={event => setQuery(event.target.value)} /></label>
<div className="index-search-controls"><select aria-label="索引结果类型" value={kind} onChange={event => { const next = event.target.value as CodeQueryKind; setKind(next); void search(next); }}>
<option value="all">全部结果</option><option value="symbols">符号声明</option><option value="imports">导入关系</option><option value="files">项目文件</option>
</select><button className="button primary" type="submit" disabled={busy}>{busy ? <LoaderCircle size={14} className="spin" /> : <Search size={14} />}查找</button></div>
</form>
<div className="index-scroll" aria-busy={busy}>
{error && <div className="index-error" role="alert"><strong>索引未刷新</strong><p>{error}</p><button className="button secondary" disabled={busy} onClick={() => void search()}>重试索引</button></div>}
{index && coverage && <>
<div className={'index-coverage ' + (coverage.truncated ? 'partial' : '')}>
<div><strong>{coverage.truncated ? '部分结果' : '当前范围已索引'}</strong><span>{new Date(index.generatedAt).toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', second: '2-digit' })}</span></div>
<p>{coverage.fileCount} 个文件 · {coverage.symbolCount} 个符号 · {coverage.importCount} 处导入</p>
<span>本次 {index.refresh.updatedFiles} 更新 · {index.refresh.reusedFiles} 复用 · {index.refresh.removedFiles} 移除</span>
</div>
<details className="index-scope"><summary>查看索引范围与依据</summary>
<p>{coverage.astFiles} 个 JS/TS/React 文件采用静态声明分析;{coverage.pythonCandidateFiles} 个 Python 文件提供声明候选。</p>
<p>已检查 {index.sourceScope.scannedFiles} 个文件,快照上限 {index.sourceScope.maximumFiles} 个文件;单文件符号分析上限 {Math.round(coverage.maximumFileBytes / 1000)} KB。</p>
<p>{index.sourceScope.note}</p>{index.notes.map(note => <p key={note}>{note}</p>)}
<code title={index.indexFingerprint}>索引 {index.indexFingerprint}</code>
<code title={index.sourceFingerprint}>源码 {index.sourceFingerprint}</code>
</details>
{index.warnings.length > 0 && <div className="index-warnings"><strong>{coverage.unindexedFiles} 个文件需要补充核对</strong>
{index.warnings.slice(0, 4).map(warning => <p key={warning.path}><span>{warning.path}</span>{warning.message}</p>)}
{index.warnings.length > 4 && <p>其余文件可按名称查询后读取当前内容。</p>}
</div>}
<div className="index-result-caption" role="status"><span>{result!.query ? `“${result!.query}”` : '当前结果'} · {result!.totalMatches} 项匹配</span><span>显示 {result!.results.length} 项</span></div>
<div className="index-results">{result!.results.map((item, position) => <button type="button" className="index-result" key={item.resultKind + item.path + item.line + position}
disabled={busy || !!error} aria-label={'打开 ' + item.path + ' 第 ' + item.line + ' 行 ' + resultName(item)} onClick={() => onOpen(item.path, item.line, item.sha256)}>
<div className="index-result-title"><FileCode2 size={14} /><strong>{resultName(item)}</strong><span>{item.resultKind === 'symbol' ? kindNames[item.kind] || '声明' : item.resultKind === 'import' ? '导入' : '文件'}</span><ArrowUpRight size={13} /></div>
<div className="index-result-location"><span>{item.path}</span><b>:{item.line}</b></div>
{item.signature && <code className="index-signature" title={item.signature}>{item.signature}</code>}
{item.resultKind === 'import' && <p className="index-target">{item.target ? '文件候选 → ' + item.target : item.status === 'external-or-alias' ? '外部模块或路径别名,目标未解析' : '当前范围没有对应本地文件'}</p>}
<div className="index-result-evidence"><span>{item.evidenceMethod === 'python-declaration-candidate' ? 'Python 候选 · 需读源码核对' : item.evidenceMethod === 'javascript-typescript-ast' ? '静态声明' : '文件指纹'}{item.exported ? ' · 已导出' : ''}</span><code>{item.sha256.slice(0, 10)}</code></div>
</button>)}</div>
{result!.results.length === 0 && <div className="index-empty"><Search size={22} /><h4>当前范围没有匹配</h4><p>调整名称、路径或结果类型;文件刚有变化时可刷新索引。</p></div>}
{result!.truncated && <p className="index-limit">这里只展示当前范围的有限结果。可以增加查询词缩小范围;无匹配不代表整个项目都没有该代码。</p>}
</>}
{!result && !error && <div className="index-empty"><LoaderCircle className="spin" size={22} /><h4>正在核对项目文件</h4><p>读取实际声明、导入及文件指纹。</p></div>}
</div>
</section>;
}
+14 -4
View File
@@ -47,6 +47,15 @@ export function Modal({ title, description, children, onClose, wide = false }: {
</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) {
@@ -57,8 +66,8 @@ export function DiffView({ change }: { change: Change }) {
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>
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>
@@ -70,8 +79,9 @@ export function ToolRow({ event, selected = false, onSelect }: { event: ToolEven
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 || '')
: event.tool === 'read_file' || event.tool === 'propose_file' ? String(event.input?.path || '')
: event.tool === 'search_files' ? String(event.input?.query || '') : event.tool === 'list_files' ? '项目目录'
: ['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>
+17 -1
View File
@@ -18,6 +18,8 @@ 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;
editKind?: 'exact-patch';
patch?: { edits: number; lineEnding: 'lf' | 'crlf' | 'mixed'; preservedBom: boolean; ranges: { startLine: number; endLine: number; anchorSha256: string; replacementSha256: string }[] };
}
export interface Approval { id: string; command: string; reason: string; cwd: string; shell?: string; status: string; createdAt: string; checkPlanId?: string; checkScripts?: { name: string; script: string; lifecycle: { name: string; script: string }[] }[] }
export interface Session {
@@ -45,10 +47,24 @@ export interface RuntimeDiagnostics {
} | 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 OpenFile { path: string; content: string; sha256: string; bytes: number; bom?: boolean }
export interface Bootstrap { token: string; version: string; config: Config; projects: Project[]; sessions: SessionBrief[]; exampleProjectId: string | null; environment?: ExecutionEnvironment; eventCursor?: number; storage?: { engine: string; schemaVersion: number }; runtimeRoot?: string }
export interface ResearchDoc { id: string; title: string; description: string }
export type CodeQueryKind = 'all' | 'symbols' | 'imports' | 'files';
export interface CodeIndexSummary {
schemaVersion: number; projectId: string; projectName: string; parser: string; generatedAt: string; sourceFingerprint: string; indexFingerprint: string;
coverage: { snapshotComplete: boolean; fileCount: number; symbolCount: number; importCount: number; astFiles: number; pythonCandidateFiles: number; unindexedFiles: number; truncated: boolean; maximumFileBytes: number; maximumSymbols: number };
refresh: { updatedFiles: number; reusedFiles: number; removedFiles: number };
sourceScope: { complete: boolean; scannedFiles: number; bytes: number; maximumFiles: number; maximumBytes: number; excludedFiles: number; note: string };
warnings: { path: string; sha256: string; status: string; message: string; line: number }[]; notes: string[];
}
export interface CodeResult {
resultKind: 'symbol' | 'import' | 'file'; path: string; line: number; sha256: string; name: string; kind: string;
qualifiedName?: string; signature?: string; evidenceMethod: string; exported?: boolean; status?: string; target?: string | null;
}
export interface CodeQuery { query: string; kind: CodeQueryKind; results: CodeResult[]; totalMatches: number; truncated: boolean; index: CodeIndexSummary }
export interface ModelSnapshot { mode: string; model: string; baseUrl: string; verified?: boolean; contextLimit?: number; maxOutputTokens?: number }
export interface Usage { requests: number; inputTokens: number; outputTokens: number; totalTokens: number; unknownRequests: number; estimatedUnknownTokens: number }
export interface RunBudget { maxSteps: number; maxDurationMs: number; maxTokens: number; maxTaskTokens: number }