Files
Agent-Workbench/src/client/CodeIndexPanel.tsx
T
2026-10-29 17:59:35 +08:00

85 lines
7.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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>;
}