Files
Agent-Workbench/src/client/CodeIndexPanel.tsx
T

124 lines
12 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, ProjectCacheStatus } 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;
const reasons: Record<string, string> = { cold: '首次建立', memory: '本次进程复用', disk: '从本机派生缓存载入', disabled: '缓存已关闭',
'process-only': '仅本次进程', 'incomplete-scan': '读取范围不完整,重新分析可读文件', 'identity-changed': '分支、解析配置或项目身份变化',
'source-or-access-changed': '源码或读取权限变化', 'files-added-or-removed': '文件新增、删除或重命名', corrupt: '派生材料损坏,已重建',
unavailable: '派生缓存不可用,已重建', capacity: '超出缓存容量,保留当前检索结果', stored: '已保存派生材料', 'cleared-during-refresh': '核对期间已清除,未重新填入缓存' };
const reason = (value: string) => reasons[value] ?? value;
const size = (bytes: number) => bytes < 1024 * 1024 ? (bytes / 1024).toFixed(1) + ' KiB' : (bytes / (1024 * 1024)).toFixed(1) + ' MiB';
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 [cacheInfo, setCacheInfo] = useState<ProjectCacheStatus | null>(null);
const [cacheMessage, setCacheMessage] = useState('');
const [cacheError, setCacheError] = useState('');
const request = useRef(0);
const initialLoad = useRef(false);
async function search(nextKind = kind) {
const current = ++request.current;
setBusy(true); setError(''); setCacheMessage('');
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);
if (response.index.cache) setCacheInfo({ ...response.index.cache, latest: response.index.cache });
} catch (cause) {
if (current === request.current) setError(cause instanceof Error ? cause.message : String(cause));
} finally { if (current === request.current) setBusy(false); }
}
async function changeCache(action: 'toggle' | 'clear', enabled?: boolean) {
const current = ++request.current; setBusy(true); setCacheError(''); setCacheMessage('');
try {
const response = await (action === 'toggle' ? api<ProjectCacheStatus>('/project-cache', { enabled })
: api<ProjectCacheStatus>('/projects/' + project.id + '/index-cache', {}, 'DELETE'));
if (current !== request.current) return;
setCacheInfo(response);
setCacheMessage(action === 'clear' ? '本项目派生缓存已清除;下次查询重新分析。工程、会话与原工件保留。'
: enabled ? '本机解析缓存已启用;下次查询按当前源码核对。' : '本机解析缓存已关闭;后续查询从当前源码重新分析。');
} catch (cause) { if (current === request.current) setCacheError(cause instanceof Error ? cause.message : String(cause)); }
finally { if (current === request.current) setBusy(false); }
}
useEffect(() => { request.current++; initialLoad.current = false; setResult(null); setCacheInfo(null); setCacheMessage(''); setCacheError('');
return () => { request.current++; initialLoad.current = false; }; }, [project.id, project.root]);
useEffect(() => {
if (active && !initialLoad.current) { initialLoad.current = true; void search(); }
}, [active, project.id, project.root]);
const index = result?.index, coverage = index?.coverage, metrics = cacheInfo?.latest ?? index?.cache;
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>
{cacheInfo && <details className="index-cache"><summary>解析缓存 · {cacheInfo.enabled ? '已启用' : '已关闭'}</summary>
<div className="index-cache-controls"><label><input type="checkbox" role="switch" aria-label="启用本机解析缓存" checked={cacheInfo.enabled} disabled={busy}
onChange={event => void changeCache('toggle', event.target.checked)} />启用本机解析缓存</label>
<button className="button secondary" disabled={busy} onClick={() => void changeCache('clear')}>清除本项目缓存</button></div>
<p>开关作用于本机所有项目;清除仅移除当前项目的派生解析材料。</p>
<p>{cacheInfo.diskProjects} / {cacheInfo.maximumProjects} 个项目 · 磁盘 {size(cacheInfo.diskBytes)} / {size(cacheInfo.maximumBytes)} · 单项目上限 {size(cacheInfo.maximumEntryBytes)}</p>
{metrics && <dl className="index-cache-metrics"><dt>上次检索核对</dt><dd>{new Date(metrics.checkedAt).toLocaleString('zh-CN')} · {metrics.sourceVerified ? `${metrics.verificationPasses} 轮 SHA 核对` : '范围不完整'}</dd>
<dt>解析材料</dt><dd>{reason(metrics.origin)} · {metrics.reusedFiles} 复用 / {metrics.parsedFiles} 重新解析</dd>
<dt>失效原因</dt><dd>{metrics.invalidation ? reason(metrics.invalidation) : '未发现已缓存来源变化'}</dd>
<dt>本次检索用时</dt><dd>{Math.round(metrics.durationMs)} ms · 其中解析 {metrics.parseMs.toFixed(1)} ms</dd>
<dt>派生存储</dt><dd>{reason(metrics.storageReason)}</dd></dl>}
<p>每次查询都核对当前来源。本地复用量与模型服务的 token 计费分别记录。</p>
{cacheInfo.error && <p className="index-cache-warning">{cacheInfo.error}</p>}
{cacheError && <p className="index-cache-warning" role="alert">缓存操作未完成:{cacheError} 可重试本次操作。</p>}
{cacheMessage && <p className="index-cache-feedback" aria-live="polite">{cacheMessage}</p>}
</details>}
<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>;
}