feat: integrate task-bound REA research and portable runtime
This commit is contained in:
+14
-2
@@ -7,6 +7,7 @@ import { DiagnosticsPanel } from './DiagnosticsPanel';
|
||||
import { TaskPanel } from './TaskPanel';
|
||||
import { CodeIndexPanel } from './CodeIndexPanel';
|
||||
import { ChangesInspector } from './ChangesInspector';
|
||||
import { ResearchPanel } from './ResearchPanel';
|
||||
|
||||
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 };
|
||||
@@ -60,6 +61,7 @@ export default function App() {
|
||||
const [projectInput, setProjectInput] = useState('');
|
||||
const [toast, setToast] = useState('');
|
||||
const [researchOpen, setResearchOpen] = useState(false);
|
||||
const [reaOpen, setReaOpen] = useState(false);
|
||||
const [researchDocs, setResearchDocs] = useState<ResearchDoc[]>([]);
|
||||
const [report, setReport] = useState<{ title: string; content: string } | null>(null);
|
||||
const chatEnd = useRef<HTMLDivElement>(null);
|
||||
@@ -81,7 +83,8 @@ export default function App() {
|
||||
const isRunning = !!session && (activeStates.includes(session.status) || session.execution?.checks.some(job => ['queued', 'running'].includes(job.status)) === true
|
||||
|| session.execution?.deliveries?.some(job => ['queued', 'preparing', 'prepared', 'publishing', 'committed', 'reporting'].includes(job.status)) === true
|
||||
|| session.execution?.changeSets?.some(set => ['applying', 'rolling_back'].includes(set.status)) === true
|
||||
|| session.execution?.workspaces?.some(value => ['creating', 'verifying', 'registering'].includes(value.status)) === true);
|
||||
|| session.execution?.workspaces?.some(value => ['creating', 'verifying', 'registering'].includes(value.status)) === true
|
||||
|| session.execution?.researchJobs?.some(value => ['queued', 'connecting', 'analyzing', 'stopping'].includes(value.status)) === true);
|
||||
const anyRunning = isRunning || briefs.some(item => activeStates.includes(item.status));
|
||||
const pending = session?.changes.filter(change => ['pending', 'conflict'].includes(change.status)) || [];
|
||||
const reviewedRun = session?.execution?.run;
|
||||
@@ -119,7 +122,7 @@ export default function App() {
|
||||
function failure(error: unknown) { notify(error instanceof Error ? error.message : String(error)); }
|
||||
function selectSession(id: string) {
|
||||
if (selectedSessionRef.current === id) return;
|
||||
workspaceRequest.current++; selectedSessionRef.current = id; setSessionId(id); setSession(null); setToast('');
|
||||
workspaceRequest.current++; selectedSessionRef.current = id; setSessionId(id); setSession(null); setToast(''); setReaOpen(false);
|
||||
localStorage.setItem('awb-session', id); setChangeId(''); setEventId('');
|
||||
}
|
||||
function acceptSession(updated: Session) {
|
||||
@@ -342,6 +345,13 @@ export default function App() {
|
||||
try { setResearchDocs(await api<ResearchDoc[]>('/research')); setReport(await api('/research/overview')); setResearchOpen(true); }
|
||||
catch (error) { failure(error); }
|
||||
}
|
||||
async function openRea() {
|
||||
const originProject = selectedProjectRef.current, originSession = selectedSessionRef.current;
|
||||
try {
|
||||
const target = session || await newSession();
|
||||
if (target && selectedProjectRef.current === originProject && selectedSessionRef.current === target.id) setReaOpen(true);
|
||||
} catch (error) { if (selectedProjectRef.current === originProject && selectedSessionRef.current === originSession) 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); }
|
||||
@@ -485,6 +495,7 @@ export default function App() {
|
||||
<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>
|
||||
<IconButton label="查看任务记录" onClick={() => showInspector('task')}><ClipboardCheck size={15} /></IconButton>
|
||||
<IconButton label="REA 工件研究" onClick={() => void openRea()} disabled={!selectedProject || creatingSession}><BookOpenText 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>
|
||||
@@ -522,6 +533,7 @@ export default function App() {
|
||||
{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><label>运行时间(分钟)<input aria-label="运行时间预算" type="number" min={1} max={60} value={settings.maxRunDurationMs / 60000} onChange={event => setSettings(previous => ({ ...previous, maxRunDurationMs: Number(event.target.value) * 60000 }))} /></label><label>单次运行 tokens<input aria-label="单次运行token预算" type="number" min={1000} max={2000000} value={settings.maxRunTokens} onChange={event => setSettings(previous => ({ ...previous, maxRunTokens: Number(event.target.value) }))} /></label><label>任务累计 tokens<input aria-label="任务累计token预算" type="number" min={1000} max={10000000} value={settings.maxTaskTokens} onChange={event => setSettings(previous => ({ ...previous, maxTaskTokens: Number(event.target.value) }))} /></label></div><p>上下文使用本地估算;实际用量与未知用量分开保存。达到预算会暂停,已完成的工具结果保留。</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>}
|
||||
{reaOpen && session && selectedProject && <Modal title="REA 工件研究" description="原分析与同一项目、任务和运行绑定。" wide onClose={() => setReaOpen(false)}><ResearchPanel key={session.id} project={selectedProject} session={session} onSession={acceptSession} onError={failure} busy={isRunning} /></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>
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
.rea-panel { color: var(--ink); min-width: 0; }
|
||||
.rea-heading { display: flex; justify-content: space-between; align-items: flex-start; gap: 24px; margin-bottom: 22px; }
|
||||
.rea-heading > div:first-child { max-width: 570px; }
|
||||
.rea-eyebrow { color: var(--teal); font-size: 11px; letter-spacing: .04em; }
|
||||
.rea-heading h3 { font-size: 23px; letter-spacing: -.04em; line-height: 1.4; margin: 5px 0 8px; font-weight: 650; }
|
||||
.rea-heading p, .rea-hint, .rea-empty { color: var(--muted); font-size: 12px; line-height: 1.8; }
|
||||
.rea-availability { display: flex; align-items: flex-end; flex-direction: column; gap: 9px; flex-shrink: 0; padding-top: 5px; }
|
||||
.rea-availability > span { color: #8b5734; font-size: 11px; padding: 5px 9px; border: 1px solid #e8dccc; border-radius: 5px; }
|
||||
.rea-availability > span.found { color: var(--teal); border-color: #c6ded4; background: #eff7f3; }
|
||||
.rea-install-note { padding: 12px 15px; border: 1px solid #e6d6c4; background: #fbf6ee; line-height: 1.8; margin-bottom: 18px; }
|
||||
.rea-grid { display: grid; grid-template-columns: minmax(240px, .82fr) minmax(0, 1.45fr); gap: 24px; }
|
||||
.rea-registration, .rea-results { min-width: 0; }
|
||||
.rea-registration form { padding: 18px; background: var(--paper); border: 1px solid var(--line); border-radius: 7px; }
|
||||
.rea-panel h4 { font-size: 13px; font-weight: 650; display: flex; gap: 8px; align-items: center; margin-bottom: 14px; }
|
||||
.rea-registration form .form-field { margin-bottom: 14px; }
|
||||
.rea-registration textarea { resize: vertical; min-height: 77px; width: 100%; border: 1px solid var(--line); border-radius: 6px; background: #fff; padding: 10px 11px; color: var(--ink); font-size: 12px; line-height: 1.7; }
|
||||
.rea-hint { margin: -2px 0 15px; }
|
||||
.rea-targets { padding-top: 21px; }
|
||||
.rea-targets h4 span { color: var(--muted); font-size: 11px; font-weight: 400; }
|
||||
.rea-target { border-top: 1px solid var(--line); padding: 14px 0 16px; min-width: 0; }
|
||||
.rea-target strong { display: block; font-size: 12px; }
|
||||
.rea-target small { display: block; overflow-wrap: anywhere; color: var(--muted); line-height: 1.65; margin: 7px 0; }
|
||||
.rea-target > code { display: block; color: #526a66; font-size: 10px; overflow-wrap: anywhere; line-height: 1.65; }
|
||||
.rea-target-actions { display: flex; gap: 8px; margin-top: 12px; align-items: center; }
|
||||
.rea-target-actions select { min-width: 0; flex: 1; padding: 7px 8px; border: 1px solid var(--line); border-radius: 5px; background: var(--paper); font-size: 11px; }
|
||||
.rea-results-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; }
|
||||
.rea-empty-result { border: 1px dashed #cbdcd3; padding: 42px 24px; display: flex; flex-direction: column; align-items: flex-start; color: var(--muted); gap: 12px; border-radius: 7px; }
|
||||
.rea-empty-result strong { color: var(--ink); font-size: 15px; font-weight: 550; }
|
||||
.rea-empty-result p { line-height: 1.8; font-size: 12px; max-width: 380px; }
|
||||
.rea-job { border: 1px solid var(--line); background: var(--paper); padding: 17px; border-radius: 7px; margin-bottom: 13px; min-width: 0; }
|
||||
.rea-job.verified { border-left: 3px solid #5b9886; padding-left: 15px; }
|
||||
.rea-job-heading { display: flex; justify-content: space-between; align-items: flex-start; gap: 12px; }
|
||||
.rea-job-heading > div { min-width: 0; }
|
||||
.rea-job-heading strong { font-size: 13px; display: block; overflow-wrap: anywhere; }
|
||||
.rea-job-heading > div > span { font-size: 11px; color: var(--muted); display: block; margin-top: 5px; }
|
||||
.rea-job-state { display: inline-flex; align-items: center; gap: 5px; font-size: 10px; color: #766449; flex-shrink: 0; padding-top: 2px; }
|
||||
.rea-job-state.completed { color: var(--teal); }
|
||||
.rea-job-state.failed, .rea-job-state.stale, .rea-job-state.unknown { color: #a34d35; }
|
||||
.rea-job-summary { color: var(--muted); line-height: 1.85; margin: 13px 0; font-size: 12px; overflow-wrap: anywhere; }
|
||||
.rea-source-chain { display: flex; align-items: center; justify-content: space-between; gap: 7px; border-top: 1px solid #e3ece7; border-bottom: 1px solid #e3ece7; padding: 13px 0; margin-bottom: 12px; color: #42685e; }
|
||||
.rea-source-chain > div { display: flex; align-items: center; gap: 7px; min-width: 0; }
|
||||
.rea-source-chain span { font-size: 9px; display: block; color: var(--muted); }
|
||||
.rea-source-chain code { color: var(--teal); display: block; margin-top: 4px; font-size: 10px; overflow-wrap: anywhere; }
|
||||
.rea-job-actions { display: flex; align-items: center; flex-wrap: wrap; gap: 8px 11px; }
|
||||
.rea-job-actions .button { font-size: 11px; padding: 7px 9px; }
|
||||
.rea-job-actions .text-button { font-size: 11px; }
|
||||
.rea-reused { color: #587867; font-size: 11px; margin: 3px 0 12px; line-height: 1.7; }
|
||||
.rea-origin { margin-top: 14px; border-top: 1px solid var(--line); padding-top: 10px; color: var(--muted); font-size: 10px; }
|
||||
.rea-origin summary { cursor: pointer; }
|
||||
.rea-origin dl { display: grid; grid-template-columns: 74px minmax(0, 1fr); gap: 9px; margin: 14px 0 0; }
|
||||
.rea-origin dt, .rea-origin dd { margin: 0; min-width: 0; overflow-wrap: anywhere; line-height: 1.65; }
|
||||
.rea-evidence-view { min-width: 0; }
|
||||
.rea-evidence-meta { border-bottom: 1px solid var(--line); padding-bottom: 12px; color: var(--muted); font-size: 11px; }
|
||||
.rea-evidence-meta code { display: block; overflow-wrap: anywhere; margin-top: 7px; font-size: 10px; }
|
||||
.rea-pointer { display: flex; justify-content: space-between; gap: 12px; align-items: center; padding: 14px 0; min-width: 0; }
|
||||
.rea-pointer code { color: var(--teal); overflow-wrap: anywhere; min-width: 0; }
|
||||
.rea-field-picker { display: flex; flex-wrap: wrap; gap: 7px; margin-bottom: 15px; }
|
||||
.rea-field-picker button { font-family: "Cascadia Code", Consolas, monospace; font-size: 10px; display: inline-flex; align-items: center; gap: 7px; padding: 5px 8px; border: 1px solid var(--line); border-radius: 4px; overflow-wrap: anywhere; max-width: 100%; }
|
||||
.rea-field-picker button:hover { color: var(--teal); background: #ecf5ef; }
|
||||
.rea-original-content { margin: 0; padding: 17px; background: #f1f5f2; border: 1px solid var(--line); border-radius: 5px; line-height: 1.8; font-size: 11px; max-height: 44vh; overflow: auto; white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.rea-page-controls { display: flex; align-items: center; gap: 9px; margin-top: 14px; flex-wrap: wrap; font-size: 11px; color: var(--muted); }
|
||||
.rea-page-controls > span { margin-right: auto; }
|
||||
@media (max-width: 800px) {
|
||||
.rea-grid { grid-template-columns: minmax(0, 1fr); gap: 26px; }
|
||||
.rea-registration form { padding: 15px; }
|
||||
}
|
||||
@media (max-width: 620px) {
|
||||
.rea-heading { display: block; margin-bottom: 18px; }
|
||||
.rea-heading h3 { font-size: 21px; }
|
||||
.rea-availability { flex-direction: row; align-items: center; justify-content: space-between; padding-top: 14px; }
|
||||
.rea-job { padding: 13px; }
|
||||
.rea-job.verified { padding-left: 11px; }
|
||||
.rea-job-heading { flex-wrap: wrap; gap: 8px; }
|
||||
.rea-job-state { padding-top: 0; }
|
||||
.rea-source-chain { gap: 4px; }
|
||||
.rea-source-chain > div { gap: 4px; }
|
||||
.rea-source-chain code { font-size: 9px; }
|
||||
.rea-source-chain > div > svg { display: none; }
|
||||
.rea-pointer { align-items: flex-start; flex-wrap: wrap; }
|
||||
.rea-original-content { padding: 12px; max-height: 42vh; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) { .rea-panel .spin { animation: none; } }
|
||||
@@ -0,0 +1,127 @@
|
||||
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>;
|
||||
}
|
||||
@@ -24,6 +24,11 @@ export async function downloadArtifact(sessionId: string, artifactId: string, na
|
||||
}
|
||||
downloadBlob(await response.blob(), name);
|
||||
}
|
||||
export async function downloadResearchDocument(sessionId: string, jobId: string, kind: 'bundle' | 'raw' = 'bundle') {
|
||||
const response = await fetch('/api/sessions/' + sessionId + '/research/jobs/' + jobId + '/download?kind=' + kind, { headers: { 'X-Workbench-Token': accessToken } });
|
||||
if (!response.ok) { const value = await response.json().catch(() => ({})); throw new Error(value.error || '研究证据下载失败。'); }
|
||||
downloadBlob(await response.blob(), 'agent-workbench-rea-' + kind + '-' + jobId + '.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();
|
||||
|
||||
@@ -29,6 +29,8 @@ export function Modal({ title, description, children, onClose, wide = false }: {
|
||||
const previous = document.activeElement as HTMLElement | null;
|
||||
panel.current?.querySelector<HTMLElement>('input, select, textarea, button')?.focus();
|
||||
const handle = (event: KeyboardEvent) => {
|
||||
const dialogs = document.querySelectorAll('[role="dialog"][aria-modal="true"]');
|
||||
if (dialogs[dialogs.length - 1] !== panel.current) return;
|
||||
if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); close.current(); }
|
||||
if (event.key === 'Tab') {
|
||||
const elements = Array.from(panel.current?.querySelectorAll<HTMLElement>('button, input, select, textarea, a[href]') || [])
|
||||
@@ -39,7 +41,7 @@ export function Modal({ title, description, children, onClose, wide = false }: {
|
||||
}
|
||||
};
|
||||
document.addEventListener('keydown', handle);
|
||||
return () => { document.removeEventListener('keydown', handle); previous?.focus(); };
|
||||
return () => { document.removeEventListener('keydown', handle); if (previous?.isConnected) previous.focus(); };
|
||||
}, []);
|
||||
return createPortal(<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' : '')}>
|
||||
|
||||
+12
-1
@@ -130,4 +130,15 @@ export interface ChangeSet {
|
||||
snapshotArtifactId: string; sourceRunId: string; restoreError?: string }[];
|
||||
observations?: { path: string; state: string; exists: boolean | null; actualSha256: string | null; problem?: string }[];
|
||||
}
|
||||
export interface ExecutionSnapshot { schemaVersion: number; task: Task | null; run: Run | null; runs: RunBrief[]; progress: { totalTools: number; completedTools: number; requiresVerification: { id: string; tool: string; state: string; callId: string }[] }; artifacts: Artifact[]; checks: CheckJob[]; plans?: CheckPlan[]; deliveries?: DeliveryJob[]; deliveryPlans?: DeliveryPlan[]; changeSets?: ChangeSet[]; contextPlans?: ContextPlan[]; workspaces?: WorkspaceRecord[]; workspaceIdentity?: WorkspaceIdentity; accountedTaskTokens: number }
|
||||
export interface ExecutionSnapshot { schemaVersion: number; task: Task | null; run: Run | null; runs: RunBrief[]; progress: { totalTools: number; completedTools: number; requiresVerification: { id: string; tool: string; state: string; callId: string }[] }; artifacts: Artifact[]; checks: CheckJob[]; plans?: CheckPlan[]; deliveries?: DeliveryJob[]; deliveryPlans?: DeliveryPlan[]; changeSets?: ChangeSet[]; contextPlans?: ContextPlan[]; workspaces?: WorkspaceRecord[]; researchTargets?: ResearchTarget[]; researchJobs?: ResearchJob[]; workspaceIdentity?: WorkspaceIdentity; accountedTaskTokens: number }
|
||||
export interface ReaAvailability { status: string; version?: string; declaredVersion?: string; message?: string; packageRoot?: string; protocolVersion?: string; operations?: { id: string; name: string; extensions: string[]; label: string }[] }
|
||||
export interface ResearchTarget { id: string; taskId: string; runId: string; projectId: string; sessionId: string; path: string; sha256: string; bytes: number; extension: string; label: string; source: string; registeredAt: string }
|
||||
export interface ResearchJob {
|
||||
id: string; taskId: string; runId: string; targetId: string; targetSha256: string; operation: string; operationId: string;
|
||||
status: string; summary: string; startedAt: string; finishedAt: string | null; evidenceId?: string; reusedFromJobId?: string;
|
||||
evidenceBinding?: { verified: boolean; statistics?: Record<string, unknown>; limitations: string[]; scope: string } | null;
|
||||
installation: ReaAvailability; before?: { path: string }; raw?: { id: string; documentSha256: string }; traceArtifactId?: string;
|
||||
cleanup?: { rootExited: boolean }; requiresVerification: boolean;
|
||||
}
|
||||
export interface ResearchPage { content: string; offset: number; next_offset: number; total_characters: number; truncated: boolean; pointer?: string;
|
||||
evidence_id?: string; target_sha256?: string; source_document_sha256: string; available_fields?: string[] }
|
||||
|
||||
Reference in New Issue
Block a user