Files
Agent-Workbench/docs/messages-m-evidence/source-bytes/src/client/ResearchPanel.tsx
T

128 lines
16 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 { ArrowRight, ArrowUpLeft, Download, FileSearch, Fingerprint, LoaderCircle, Play, RefreshCw, ShieldCheck, Square } from 'lucide-react';
import { api, downloadArtifact, downloadResearchDocument } from './api';
import { Modal } from './components';
import type { ArtifactPreview, Project, ReaAvailability, ResearchJob, ResearchPage, ResearchTarget, Session } from './types';
import './ResearchPanel.css';
const active = ['queued', 'connecting', 'analyzing', 'stopping'];
const operations = [
{ id: 'javascript', extensions: ['.asar'], label: 'JavaScript / Electron' },
{ id: 'pe-imports', extensions: ['.exe', '.dll'], label: 'PE 导入表' },
{ id: 'pe-resources', extensions: ['.exe', '.dll'], label: 'PE 静态资源' },
];
const states: Record<string, string> = { queued: '已排队', connecting: '核对 REA 连接', analyzing: '正在静态分析', stopping: '正在停止', completed: '原证据已核验', stale: '工件版本变化', unverified: '原响应尚未核验', failed: '分析未完成', cancelled: '已停止', unknown: '结果待核对', interrupted: '已中断' };
const date = (value: string) => new Date(value).toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' });
const escapeField = (value: string) => value.replace(/~/g, '~0').replace(/\//g, '~1');
type Preview = { job: ResearchJob; kind: 'evidence' | 'raw' | 'trace'; page: ResearchPage };
export function ResearchPanel({ project, session, busy, onSession, onError }: { project: Project; session: Session; busy: boolean; onSession: (value: Session) => void; onError: (error: unknown) => void }) {
const [availability, setAvailability] = useState<ReaAvailability | null>(null);
const [filename, setFilename] = useState(''), [label, setLabel] = useState(''), [goal, setGoal] = useState('');
const [choices, setChoices] = useState<Record<string, string>>({});
const [pending, setPending] = useState(false), [checking, setChecking] = useState(false), [viewBusy, setViewBusy] = useState(false);
const [retry, setRetry] = useState<ResearchJob | null>(null), [preview, setPreview] = useState<Preview | null>(null);
const mounted = useRef(true), request = useRef(0), scope = useRef(0), viewRequest = useRef(0);
const taskId = session.execution?.task?.id ?? null;
const targets = session.execution?.researchTargets ?? [], jobs = (session.execution?.researchJobs ?? []).slice().reverse();
const running = jobs.some(job => active.includes(job.status)), disabled = busy || running || pending;
useEffect(() => { mounted.current = true; return () => { mounted.current = false; request.current++; scope.current++; viewRequest.current++; }; }, []);
useEffect(() => { scope.current++; viewRequest.current++; setPreview(null); setRetry(null); setPending(false); setViewBusy(false); }, [taskId]);
useEffect(() => { void detect(); }, []);
async function detect() {
const current = ++request.current; setChecking(true);
try { const value = await api<ReaAvailability>('/research/availability'); if (mounted.current && current === request.current) setAvailability(value); }
catch (error) { if (mounted.current && current === request.current) onError(error); }
finally { if (mounted.current && current === request.current) setChecking(false); }
}
async function register() {
const current = scope.current; setPending(true);
try {
const value = await api<{ target: ResearchTarget; session: Session }>('/sessions/' + session.id + '/research/targets',
{ path: filename.trim(), ...(label.trim() ? { label: label.trim() } : {}), ...(goal.trim() ? { goal: goal.trim() } : {}) });
if (!mounted.current || current !== scope.current) return;
onSession(value.session); setFilename(''); setLabel(''); setGoal('');
} catch (error) { if (mounted.current && current === scope.current) onError(error); }
finally { if (mounted.current && current === scope.current) setPending(false); }
}
async function analyze(targetId: string, operation: string, refresh = false) {
const current = scope.current; setPending(true);
try {
const value = await api<{ job: ResearchJob; session: Session }>('/sessions/' + session.id + '/research/jobs', { targetId, operation, refresh });
if (mounted.current && current === scope.current) { onSession(value.session); setRetry(null); }
} catch (error) { if (mounted.current && current === scope.current) onError(error); }
finally { if (mounted.current && current === scope.current) setPending(false); }
}
async function stop() {
const current = scope.current; setPending(true);
try { const value = await api<Session>('/sessions/' + session.id + '/research/stop', {}); if (mounted.current && current === scope.current) onSession(value); }
catch (error) { if (mounted.current && current === scope.current) onError(error); }
finally { if (mounted.current && current === scope.current) setPending(false); }
}
async function openView(job: ResearchJob, kind: Preview['kind'] = 'evidence', pointer = '/normalized_result', offset = 0) {
const current = ++viewRequest.current, currentScope = scope.current; setViewBusy(true);
try {
let page: ResearchPage;
if (kind === 'trace') {
const value = await api<ArtifactPreview>('/artifacts/' + job.traceArtifactId + '?session=' + session.id + '&offset=' + offset + '&limit=4000');
page = { content: value.content, offset: value.offset, next_offset: value.offset + value.content.length, total_characters: value.totalCharacters,
truncated: value.truncated, source_document_sha256: value.sha256 };
} else page = await api<ResearchPage>('/sessions/' + session.id + '/research/jobs/' + job.id + '/' + (kind === 'raw' ? 'raw' : 'evidence')
+ '?pointer=' + encodeURIComponent(pointer) + '&offset=' + offset + '&limit=4000');
if (mounted.current && currentScope === scope.current && current === viewRequest.current) setPreview({ job, kind, page });
} catch (error) { if (mounted.current && currentScope === scope.current && current === viewRequest.current) onError(error); }
finally { if (mounted.current && currentScope === scope.current && current === viewRequest.current) setViewBusy(false); }
}
async function download(job: ResearchJob, kind: Preview['kind']) {
const current = scope.current;
try { if (kind === 'trace' && job.traceArtifactId) await downloadArtifact(session.id, job.traceArtifactId, 'agent-workbench-rea-transport-' + job.id + '.json');
else await downloadResearchDocument(session.id, job.id, kind === 'raw' ? 'raw' : 'bundle'); }
catch (error) { if (mounted.current && current === scope.current) onError(error); }
}
return <div className="rea-panel">
<header className="rea-heading"><div><span className="rea-eyebrow">{project.name} · 当前任务</span><h3>从工件取得原证据</h3><p>登记一个本地工件,分析其代码、导入或资源,再把原依据交给同一编程任务。</p></div>
<div className="rea-availability"><span className={availability?.status === 'available' ? 'found' : ''}>{checking ? '正在检测' : availability?.status === 'available' ? '已找到 REA ' + availability.version : 'REA 尚未就绪'}</span>
<button type="button" className="text-button" onClick={() => void detect()} disabled={checking}><RefreshCw size={13} />重新检测</button></div></header>
{availability && availability.status !== 'available' && <div className="rea-install-note">{availability.status === 'unsupported' ? '当前分析契约使用 REA 6.8.0,请使用匹配的发行包。' : '请使用包含 REA 的工作台发行包,再重新检测本地安装。'}</div>}
<div className="rea-grid"><section className="rea-registration">
<form onSubmit={event => { event.preventDefault(); void register(); }}>
<h4><FileSearch size={16} />登记研究工件</h4>
<label className="form-field">本地工件路径<input aria-label="REA工件路径" value={filename} onChange={event => setFilename(event.target.value)} placeholder="D:\Applications\app.asar" required disabled={disabled} /></label>
<label className="form-field">工件名称<input aria-label="REA工件名称" value={label} onChange={event => setLabel(event.target.value)} placeholder="例如:代理客户端发行包" maxLength={160} disabled={disabled} /></label>
<label className="form-field">研究问题(选填)<textarea aria-label="REA研究问题" value={goal} onChange={event => setGoal(event.target.value)} placeholder="例如:工具执行与取消如何协作?" rows={3} disabled={disabled} /></label>
<p className="rea-hint">支持 ASAR、EXE 和 DLL。名称与 SHA256 将保存在本任务;首次登记会创建研究任务。</p>
<button type="submit" className="button primary" disabled={disabled || !filename.trim()}>{pending ? <LoaderCircle size={14} className="spin" /> : <Fingerprint size={14} />}登记工件</button>
</form>
<div className="rea-targets"><h4>本任务工件 <span>{targets.length}</span></h4>
{!targets.length && <p className="rea-empty">登记后,模型可以选择这个工件进行静态分析。</p>}
{targets.map(target => { const choicesForFile = operations.filter(operation => operation.extensions.includes(target.extension)), operation = choices[target.id] ?? choicesForFile[0]?.id;
return <article className="rea-target" key={target.id}><strong>{target.label}</strong><small>{target.path}</small><code title={target.sha256}>SHA256 {target.sha256}</code>
<div className="rea-target-actions"><select aria-label={'分析方式 ' + target.label} value={operation} onChange={event => setChoices(previous => ({ ...previous, [target.id]: event.target.value }))} disabled={disabled}>{choicesForFile.map(value => <option key={value.id} value={value.id}>{value.label}</option>)}</select>
<button type="button" className="button secondary" onClick={() => void analyze(target.id, operation)} disabled={disabled || availability?.status !== 'available'}><Play size={13} />分析</button></div></article>; })}
</div>
</section><section className="rea-results"><div className="rea-results-heading"><h4>分析与原依据</h4>{running && <button type="button" className="text-button" onClick={() => void stop()} disabled={pending}><Square size={13} />停止分析</button>}</div>
{!jobs.length && <div className="rea-empty-result"><FileSearch size={28} /><strong>原结果将在这里保留</strong><p>分析完成后可选择原字段、查看限制并下载完整 Evidence Bundle。</p></div>}
{jobs.map(job => { const target = targets.find(value => value.id === job.targetId), verified = job.status === 'completed' && job.evidenceBinding?.verified;
return <article className={'rea-job ' + (verified ? 'verified' : '')} key={job.id} data-research-job={job.id}><div className="rea-job-heading"><div><strong>{target?.label ?? '历史工件'}</strong><span>{operations.find(value => value.id === job.operationId)?.label ?? job.operation}</span></div><span className={'rea-job-state ' + job.status}>{active.includes(job.status) && <LoaderCircle size={12} className="spin" />}{states[job.status] ?? job.status}</span></div>
<p className="rea-job-summary">{job.summary}</p>
{verified && <div className="rea-source-chain" aria-label="已核验原证据来源"><div><Fingerprint size={13} /><span>工件 SHA<code>{job.targetSha256.slice(0, 12)}</code></span></div><ArrowRight size={12} /><div><ShieldCheck size={13} /><span>REA<code>{job.installation.version}</code></span></div><ArrowRight size={12} /><div><FileSearch size={13} /><span>原 Evidence<code>{job.evidenceId?.slice(3, 15)}</code></span></div></div>}
{job.reusedFromJobId && <p className="rea-reused">复用既有原证据,本次没有再次调用 REA。</p>}
<div className="rea-job-actions">{verified && <><button type="button" className="button secondary" onClick={() => void openView(job)} disabled={viewBusy}><FileSearch size={13} />查看原字段</button><button type="button" className="text-button" onClick={() => void openView(job, 'evidence', '/limitations')} disabled={viewBusy}>原限制</button><button type="button" className="text-button" onClick={() => void download(job, 'evidence')}><Download size={13} />完整证据</button></>}
{job.raw && <button type="button" className="text-button" onClick={() => void openView(job, 'raw')} disabled={viewBusy}>原响应</button>}
{job.traceArtifactId && <button type="button" className="text-button" onClick={() => void openView(job, 'trace')} disabled={viewBusy}>连接记录</button>}
{!active.includes(job.status) && !verified && target && <button type="button" className="text-button" onClick={() => setRetry(job)} disabled={disabled}><RefreshCw size={13} />重新分析</button>}</div>
<details className="rea-origin"><summary>{date(job.startedAt)} · 静态工件观测</summary><dl><dt>Task</dt><dd><code>{job.taskId}</code></dd><dt>Run</dt><dd><code>{job.runId}</code></dd><dt>目标 SHA256</dt><dd><code>{job.targetSha256}</code></dd>{job.evidenceId && <><dt>原 Evidence</dt><dd><code>{job.evidenceId}</code></dd></>}<dt>进程关闭</dt><dd>{job.cleanup ? job.cleanup.rootExited ? '所属根进程已退出' : '关闭结果待核对' : job.reusedFromJobId ? '复用原依据,没有新进程' : '尚未记录关闭结果'}</dd></dl></details>
</article>; })}
</section></div>
{retry && <Modal title="重新运行静态分析" description="这会创建新的分析记录。此前停止、失败或未知的原记录仍会保留。" onClose={() => setRetry(null)}><p>{targets.find(value => value.id === retry.targetId)?.label} · {operations.find(value => value.id === retry.operationId)?.label}</p><div className="modal-actions"><button className="button secondary" onClick={() => setRetry(null)}>返回原记录</button><button className="button primary" onClick={() => void analyze(retry.targetId, retry.operationId, true)} disabled={disabled}>确认重新分析</button></div></Modal>}
{preview && <Modal title={preview.kind === 'evidence' ? '原 Evidence 字段' : preview.kind === 'raw' ? 'REA 原响应' : 'REA 连接记录'} description={preview.kind === 'evidence' ? '原字段与完整证据来源已经校验。静态关系及未知覆盖以原限制为准。' : '此处保留当次实际返回记录;记录存在不表示分析已经核验完成。'} wide onClose={() => { viewRequest.current++; setPreview(null); setViewBusy(false); }}>
<div className="rea-evidence-view"><div className="rea-evidence-meta"><span>原文 SHA256</span><code>{preview.page.source_document_sha256}</code></div>
{preview.kind === 'evidence' && <><div className="rea-pointer"><code>{preview.page.pointer}</code>{preview.page.pointer !== '/normalized_result' && <button className="text-button" onClick={() => void openView(preview.job)} disabled={viewBusy}><ArrowUpLeft size={13} />返回分析字段</button>}</div>
{!!preview.page.available_fields?.length && <div className="rea-field-picker" aria-label="原Evidence字段">{preview.page.available_fields.map(field => <button key={field} type="button" onClick={() => void openView(preview.job, 'evidence', preview.page.pointer + '/' + escapeField(field))} disabled={viewBusy}>{field}<ArrowRight size={11} /></button>)}</div>}</>}
<pre className="rea-original-content" aria-label="原Evidence内容">{preview.page.content}</pre><div className="rea-page-controls"><span>{preview.page.offset.toLocaleString()}–{preview.page.next_offset.toLocaleString()} / {preview.page.total_characters.toLocaleString()} 字符</span>
<button className="button secondary" onClick={() => void openView(preview.job, preview.kind, preview.page.pointer, 0)} disabled={viewBusy || preview.page.offset === 0}>回到首页</button><button className="button secondary" onClick={() => void openView(preview.job, preview.kind, preview.page.pointer, preview.page.next_offset)} disabled={viewBusy || !preview.page.truncated}>{viewBusy ? <LoaderCircle className="spin" size={13} /> : <ArrowRight size={13} />}下一页</button></div>
<div className="modal-actions"><button className="button secondary" onClick={() => void download(preview.job, preview.kind)}><Download size={14} />{preview.kind === 'evidence' ? '下载完整 Evidence Bundle' : '下载完整原记录'}</button></div>
</div></Modal>}
</div>;
}