Files
Agent-Workbench/src/client/TaskPanel.tsx
T
2026-10-30 20:34:54 +08:00

145 lines
18 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 { Check, ClipboardCheck, FileText, GitBranch, LoaderCircle, Play, RefreshCw, ShieldQuestion } from 'lucide-react';
import type { ArtifactPreview, CheckPlan, Project, PythonRuntimeIdentity, Run, Session } from './types';
import { api } from './api';
import { Modal, Status } from './components';
import { DeliveryPanel } from './DeliveryPanel';
import { RequestContextPanel } from './RequestContextPanel';
import { WorkspacePanel } from './WorkspacePanel';
import { BrowserPanel } from './BrowserPanel';
import { TaskPlanPanel } from './TaskPlanPanel';
import { TaskCheckpointPanel } from './TaskCheckpointPanel';
import { McpJobHistory } from './McpJobHistory';
import './TaskPanel.css';
const stopReasons: Record<string, string> = { no_progress: '重复读取未推进任务,请核对后继续', context_limit: '完整任务要求超过请求上下文预算', time_limit: '到达运行时间预算', token_limit: '到达本次 token 预算', task_token_limit: '到达任务累计预算', step_limit: '到达工具轮次上限', cancelled: '用户停止', model_error: '模型请求失败', interrupted: '进程中断' };
const number = (value: number | undefined) => (value ?? 0).toLocaleString('zh-CN');
stopReasons.git_review = 'Git预览已保存,等待审查与确认';
stopReasons.git_review_declined = 'Git预览已撤回,文件和检查记录保留';
stopReasons.task_plan_incomplete = '执行计划仍有未核验或失效步骤,请核对后继续';
const time = (value: string | null | undefined) => value ? new Date(value).toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' }) : '执行中';
export function TaskPanel({ project, session, onSession, onError, busy, onWorkspaceRefresh, onWorkspaceNavigate }: { project: Project; session: Session; onSession: (value: Session) => void; onError: (error: unknown) => void; busy: boolean; onWorkspaceRefresh: (projectId: string, sessionId: string, isCurrent?: () => boolean) => Promise<void>; onWorkspaceNavigate: (projectId: string, sessionId: string, isCurrent?: () => boolean) => Promise<void> }) {
const execution = session.execution, task = execution?.task;
const [runId, setRunId] = useState('');
const [historicalRun, setHistoricalRun] = useState<Run | null>(null);
const [preview, setPreview] = useState<ArtifactPreview | null>(null);
const [previewBusy, setPreviewBusy] = useState(false);
const [planning, setPlanning] = useState(false);
const [confirmPlan, setConfirmPlan] = useState<CheckPlan | null>(null);
const [selectedChecks, setSelectedChecks] = useState<string[]>([]);
const [starting, setStarting] = useState(false);
const artifactRequest = useRef(0);
const actionScope = useRef(0);
const id = runId || execution?.run?.id || '';
const run = id === execution?.run?.id ? execution.run : historicalRun;
const plans = execution?.plans ?? [];
const latestPlan = plans.filter(plan => plan.taskId === task?.id).at(-1);
const checkChoices = latestPlan ? [...(latestPlan.project.packageManager === 'npm' ? latestPlan.project.scripts ?? [] : []), ...(latestPlan.project.python?.checks ?? [])] : [];
const checksChanged = !!latestPlan && JSON.stringify(selectedChecks.slice().sort()) !== JSON.stringify(latestPlan.checks.map(check => check.name).sort());
const jobs = execution?.checks ?? [];
const checkRunning = jobs.some(job => ['queued', 'running'].includes(job.status));
useEffect(() => { setSelectedChecks(latestPlan?.checks.map(check => check.name) ?? []); }, [latestPlan?.id]);
useEffect(() => { setRunId(''); setHistoricalRun(null); setPreview(null); setPreviewBusy(false); setConfirmPlan(null); setPlanning(false); setStarting(false); artifactRequest.current++; actionScope.current++;
return () => { artifactRequest.current++; actionScope.current++; };
}, [session.id, task?.id]);
useEffect(() => {
if (!id || id === execution?.run?.id) return;
let alive = true; setHistoricalRun(null);
api<Run>('/sessions/' + session.id + '/runs/' + id).then(value => { if (alive) setHistoricalRun(value); }).catch(error => { if (alive) onError(error); });
return () => { alive = false; };
}, [session.id, id, execution?.run?.id]);
async function openArtifact(artifactId: string, offset = 0) {
const request = ++artifactRequest.current; setPreviewBusy(true);
try {
const value = await api<ArtifactPreview>('/artifacts/' + artifactId + '?session=' + session.id + '&offset=' + offset + '&limit=16000');
if (artifactRequest.current === request) setPreview(value);
} catch (error) { if (artifactRequest.current === request) onError(error); }
finally { if (artifactRequest.current === request) setPreviewBusy(false); }
}
async function planChecks(names?: string[]) {
const scope = actionScope.current;
setPlanning(true);
try { const value = await api<Session>('/sessions/' + session.id + '/check-plans', names ? { names } : {}); if (actionScope.current === scope) onSession(value); }
catch (error) { if (actionScope.current === scope) onError(error); } finally { if (actionScope.current === scope) setPlanning(false); }
}
async function runChecks() {
if (!confirmPlan) return; setStarting(true);
const scope = actionScope.current;
try { const value = await api<Session>('/sessions/' + session.id + '/check-jobs', { planId: confirmPlan.id }); if (actionScope.current === scope) { onSession(value); setConfirmPlan(null); } }
catch (error) { if (actionScope.current === scope) onError(error); } finally { if (actionScope.current === scope) setStarting(false); }
}
async function stopCheck(jobId: string) {
const scope = actionScope.current;
try { const value = await api<Session>('/sessions/' + session.id + '/check-jobs/' + jobId + '/stop', {}); if (actionScope.current === scope) onSession(value); }
catch (error) { if (actionScope.current === scope) onError(error); }
}
return <div className="task-record" aria-label="任务记录">
<WorkspacePanel project={project} session={session} busy={busy} onRefresh={onWorkspaceRefresh} onNavigate={onWorkspaceNavigate} onError={onError} />
<section className="task-record-section">
<div className="record-heading"><ClipboardCheck size={15} /><h3>任务目标</h3>{task && <Status value={task.status} />}</div>
{task ? <><p className="task-goal">{task.goal}</p><code className="record-id" title={task.id}>{task.id.slice(0, 8)} · 任务</code>
{!!task.instructions.length && <details className="task-instructions"><summary>追加要求 · {task.instructions.length}</summary>{task.instructions.map(instruction => <p key={instruction.id}>{instruction.content}</p>)}</details>}
</> : <p className="record-empty">发送任务后,这里保存目标、每次运行和实际结果。</p>}
</section>
{task && <TaskPlanPanel session={session} busy={busy} onSession={onSession} onError={onError} openArtifact={openArtifact} />}
{task && <TaskCheckpointPanel session={session} busy={busy} onSession={onSession} onError={onError} openArtifact={openArtifact} />}
{execution?.progress.requiresVerification.length ? <section className="verification-note" role="status"><ShieldQuestion size={17} /><div><strong>{execution.progress.requiresVerification.length} 项结果需要核对</strong><p>这些调用已进入执行,但缺少可靠结果。继续任务会保留记录。</p>{execution.progress.requiresVerification.map(tool => <code key={tool.id}>{tool.tool} · {tool.id.slice(0, 8)}</code>)}</div></section> : null}
{task && !!execution?.mcpJobs?.length && <McpJobHistory session={session} jobs={execution.mcpJobs} busy={busy} onSession={onSession} onError={onError} />}
{task && <section className="task-record-section">
<div className="record-heading"><h3>运行记录</h3><span>{execution?.runs.filter(item => item.taskId === task.id).length} 次</span></div>
<label className="run-picker">选择一次运行<select aria-label="选择运行记录" value={id} onChange={event => setRunId(event.target.value)}>{execution?.runs.filter(item => item.taskId === task.id).map((item, index) => <option key={item.id} value={item.id}>第 {index + 1} 次 · {time(item.startedAt)}{item.resumeOf ? ' · 接续' : ''}</option>)}</select></label>
{run ? <><div className="run-status"><Status value={run.status} /><code title={run.id}>{run.id.slice(0, 8)}</code></div>
<dl className="record-fields"><dt>实际模型</dt><dd>{run.model?.verified === false ? '历史模型信息未记录' : run.model?.mode === 'demo' ? '离线演示 · 固定脚本' : run.model?.model || '未记录'}</dd><dt>接口</dt><dd className="record-endpoint">{run.model?.verified === false ? '未记录' : run.model?.baseUrl || '本地演示'}</dd>{run.workspaceIdentity && <><dt>执行目录</dt><dd className="record-endpoint">{run.workspaceIdentity.root}</dd>{run.workspaceIdentity.branch && <><dt>独立分支</dt><dd className="record-endpoint">{run.workspaceIdentity.branch}</dd></>}</>}<dt>开始 / 结束</dt><dd>{time(run.startedAt)}<br />{time(run.finishedAt)}</dd><dt>模型轮次 / 工具</dt><dd>{run.steps} / {run.toolCalls}</dd><dt>已报告用量</dt><dd>{number(run.usage?.totalTokens)} tokens<br /><small>输入 {number(run.usage?.inputTokens)} · 输出 {number(run.usage?.outputTokens)}</small></dd>
{!!run.usage?.unknownRequests && <><dt>未报告用量</dt><dd>{run.usage.unknownRequests} 次请求 · 估算 {number(run.usage.estimatedUnknownTokens)} tokens</dd></>}
<dt>本次预算</dt><dd>{number(run.budget?.maxTokens)} tokens · {Math.round((run.budget?.maxDurationMs ?? 0) / 60000)} 分钟 · {run.budget?.maxSteps} 轮</dd><dt>任务累计</dt><dd>{number(execution?.accountedTaskTokens)} / {number(task.budget.maxTokens)} tokens</dd>
</dl>{run.stopReason && <p className="run-stop">{stopReasons[run.stopReason] || run.stopReason}</p>}
<p className="record-footnote">用量以服务返回为准;未报告的请求单独估算。</p>
</> : <p className="record-empty"><LoaderCircle size={14} className="spin" />正在读取运行记录</p>}
</section>}
{run && <RequestContextPanel session={session} runId={run.id} onError={onError} openArtifact={openArtifact} />}
<section className="task-record-section project-checks">
<div className="record-heading"><GitBranch size={15} /><h3>工程检查</h3><Status value={task?.verification.status || 'not_configured'} /></div>
<p className="record-footnote">检查对应当时的工程快照。先识别测试与执行环境,再确认检查;项目变化后重新检查。</p>
<button type="button" className="button secondary" disabled={!task || busy || planning || checkRunning} onClick={() => planChecks()}>{planning ? <LoaderCircle size={14} className="spin" /> : <RefreshCw size={14} />}{latestPlan ? '重新识别检查计划' : '识别工程与检查'}</button>
{latestPlan && <div className="check-plan"><p><strong>{latestPlan.project.name}</strong> · {latestPlan.project.languages.join(' / ') || '待识别'}</p><p className="check-baseline"><GitBranch size={12} />{latestPlan.project.git.available ? `${latestPlan.project.git.branch || 'detached'} · ${latestPlan.project.git.head?.slice(0, 8) || '尚无提交'}${latestPlan.project.git.dirty ? ' · 有未提交改动' : ' · 工作区干净'}` : '项目尚未启用 Git'}</p>
{latestPlan.project.python?.status === 'invalid' && <p className="record-empty">{latestPlan.project.python.message}</p>}
{checkChoices.length > 0 && <fieldset className="check-selection" disabled={busy || planning || starting || checkRunning}>
<legend>选择检查范围</legend>
{checkChoices.map(check => <label key={check.name}><input type="checkbox" aria-label={'启用检查 ' + check.name} checked={selectedChecks.includes(check.name)} onChange={event => setSelectedChecks(current => event.target.checked ? [...current, check.name] : current.filter(name => name !== check.name))} /><span>{check.name}</span></label>)}
{checksChanged && <><p>按所选范围重新识别,确认后执行新计划。</p><button type="button" className="button secondary" disabled={!selectedChecks.length || selectedChecks.length > 6} onClick={() => planChecks(selectedChecks)}>重新识别所选检查</button></>}
</fieldset>}
{latestPlan.checks.length ? <><ul>{latestPlan.checks.map(check => <li key={check.id}><span>{check.name}</span><code>{check.command}</code></li>)}</ul>
{latestPlan.checks.find(check => check.python)?.python && <PythonRuntimeInfo runtime={latestPlan.checks.find(check => check.python)!.python!.runtime} />}
<button type="button" className="button primary" disabled={busy || starting || checkRunning || checksChanged} onClick={() => setConfirmPlan(latestPlan)}><Play size={14} />执行这些检查</button></> : <p className="record-empty">没有识别到可执行的检查。请配置项目测试或构建。</p>}
</div>}
{jobs.slice().reverse().map(job => <div key={job.id} className="check-job">
<div className="record-heading"><Status value={job.stale ? 'stale' : job.status} /><code title={job.id}>{job.id.slice(0, 8)}</code>{['queued', 'running'].includes(job.status) && <button type="button" className="text-button" onClick={() => stopCheck(job.id)}>停止检查</button>}</div>
<time>{time(job.startedAt)}</time>{job.currentCheck && <p className="check-current"><LoaderCircle size={12} className="spin" />正在执行 <code>{job.currentCheck.command}</code></p>}{job.summary && <p>{job.summary}</p>}
{job.results.map(result => <div key={result.id} className="check-result"><div><strong>{result.name}</strong><Status value={result.status} /></div>
<p>退出码 {result.exitCode === null ? '未返回' : result.exitCode} · {(result.durationMs / 1000).toFixed(1)} 秒{result.tests && ` · 测试 ${result.tests.passed}/${result.tests.total} 通过`}{!!result.tests?.failed && ` · 失败 ${result.tests.failed}`}{!!result.tests?.skipped && ` · 跳过 ${result.tests.skipped}`}{!!result.collectionErrors && ` · 收集错误 ${result.collectionErrors}`}</p>
{result.python && <PythonRuntimeInfo runtime={result.python.runtime} />}
{result.compilation && <p>语法编译 {result.compilation.compiled}/{result.compilation.total} 个源码文件</p>}
{result.reason && <p>{result.reason}</p>}
{result.logArtifactId && <button type="button" className="text-button" disabled={previewBusy} onClick={() => openArtifact(result.logArtifactId!)}><FileText size={13} />查看检查日志</button>}
{result.metricsArtifactId && <button type="button" className="text-button" disabled={previewBusy} onClick={() => openArtifact(result.metricsArtifactId!)}><ClipboardCheck size={13} />查看实际测试依据</button>}
</div>)}
</div>)}
</section>
{task && <BrowserPanel session={session} busy={busy} onSession={onSession} onError={onError} />}
{task && <DeliveryPanel session={session} busy={busy} onSession={onSession} onError={onError} openArtifact={openArtifact} />}
{!!execution?.artifacts.length && <section className="task-record-section"><div className="record-heading"><FileText size={15} /><h3>结果工件</h3><span>最近 {execution.artifacts.length} 项</span></div><div className="artifact-list">{execution.artifacts.filter(artifact => !artifact.mediaType?.startsWith('image/')).slice().reverse().map(artifact => <button type="button" key={artifact.id} disabled={previewBusy} onClick={() => openArtifact(artifact.id)}><span>{artifact.kind === 'browser-result' ? '原页面执行记录' : artifact.kind === 'browser-plan' ? '页面检查计划' : artifact.kind === 'browser-binding' ? '页面结果来源' : artifact.kind === 'check-log' ? '检查日志' : artifact.kind === 'check-metrics' ? '实际检查统计' : artifact.kind === 'check-input' ? '检查源码与目标' : artifact.kind === 'check-plan' ? '检查计划' : artifact.kind === 'project-inspection' ? '工程识别' : artifact.kind === 'delivery-report' ? '交付报告 · JSON' : artifact.kind === 'delivery-report-markdown' ? '交付报告 · Markdown' : artifact.kind === 'delivery-diff' ? '提交差异' : artifact.kind === 'model-request' ? '模型请求正文' : artifact.kind === 'context-plan' ? '请求计划' : artifact.kind === 'context-history-index' ? '完整历史索引' : artifact.kind === 'context-latest-tools' ? '最新工具反馈' : artifact.kind.startsWith('context-group') ? '完整历史记录' : '工具结果'}<code>{artifact.sha256.slice(0, 10)}</code></span><small>{number(artifact.bytes)} B</small></button>)}</div></section>}
{confirmPlan && <Modal title="执行工程检查" description="以下检查在当前项目执行,保存实际执行环境、退出码和结果。" onClose={() => setConfirmPlan(null)}><div className="check-confirm">{confirmPlan.checks.map(check => <div key={check.id}><strong>{check.command}</strong><pre>{check.script}{check.lifecycle?.length ? '\n\n' + check.lifecycle.map(item => item.name + ': ' + item.script).join('\n') : ''}</pre>{check.python && <PythonRuntimeInfo runtime={check.python.runtime} />}</div>)}<p>{confirmPlan.project.name}</p></div><div className="modal-actions"><button type="button" className="button secondary" disabled={starting} onClick={() => setConfirmPlan(null)}>取消</button><button type="button" className="button primary" disabled={starting} onClick={runChecks}><Check size={14} />确认执行检查</button></div></Modal>}
{preview && <Modal title="执行结果工件" description={`SHA256 ${preview.sha256}`} wide onClose={() => { artifactRequest.current++; setPreview(null); setPreviewBusy(false); }}><pre className="artifact-preview">{preview.content}</pre><div className="artifact-pagination"><span>字符 {number(preview.offset)}–{number(preview.offset + preview.content.length)} / {number(preview.totalCharacters)}</span><button type="button" className="button secondary" disabled={previewBusy || preview.offset === 0} onClick={() => openArtifact(preview.id, Math.max(0, preview.offset - 16000))}>上一段</button><button type="button" className="button secondary" disabled={previewBusy || !preview.truncated} onClick={() => openArtifact(preview.id, preview.offset + preview.content.length)}>下一段</button></div></Modal>}
</div>;
}
function PythonRuntimeInfo({ runtime }: { runtime: PythonRuntimeIdentity }) {
return <div className="check-python-runtime"><strong>Python {runtime.version || (runtime.status === 'deferred' ? '执行时核对版本' : '尚未找到')}</strong>
<code>{runtime.logicalExecutable || runtime.executable || '请安装Python或配置项目虚拟环境'}</code>{runtime.message && <p>{runtime.message}</p>}</div>;
}