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

185 lines
24 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 { ModelIdentityDetails } from './ModelIdentityDetails';
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 { RequirementPanel } from './RequirementPanel';
import { TurnProgress } from './TurnProgress';
import { TaskCheckpointPanel } from './TaskCheckpointPanel';
import { McpJobHistory } from './McpJobHistory';
import './TaskPanel.css';
import { EnvironmentPanel } from './EnvironmentPanel';
import { PreviewPanel } from './PreviewPanel';
import { FileResultsPanel } from './FileResultsPanel';
import { TaskFollowUp } from './TaskFollowUp';
const stopReasons: Record<string, string> = { model_identity: '模型返回型号需要核对', 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.change_set_review = '完整文件批次已封存,等待审查与应用';
stopReasons.git_review_declined = 'Git预览已撤回,文件和检查记录保留';
stopReasons.task_plan_incomplete = '执行计划仍有未核验或失效步骤,请核对后继续';
stopReasons.diagnostic_answered = '诊断答复已完成;原任务的目标与交付状态保持';
stopReasons.verification_incomplete = '答复已收到,当前任务的工程检查尚未通过';
stopReasons.delivery_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' }) : '执行中';
stopReasons.requirements_incomplete = '用户要求仍有待复核、失效或未审阅来源';
export function TaskPanel({ project, session, onSession, onError, busy, onWorkspaceRefresh, onWorkspaceNavigate, onOpenPreview }: { project: Project; session: Session; onSession: (value: Session) => void; onError: (error: unknown) => void; busy: boolean; onOpenPreview?:()=>void; 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.contract?.goal || task.goal}</p><code className="record-id" title={task.id}>{task.id.slice(0, 8)} · 任务</code>
{task.contract?.checks === 'skip' && <p className="record-footnote">检查约定:按用户要求不自动测试。</p>}
{task.contract?.inheritedFromTaskId && <p className="record-footnote">原目标续接自 {task.contract.inheritedFromTaskId.slice(0, 8)},历史记录保留。</p>}
{task.delivery?.status === 'files_applied' && <div role="status"><strong>文件已应用</strong>{task.delivery.paths.map(path => <p key={path}><code>{path}</code></p>)}{task.delivery.checks === 'not_requested' && <p className="record-footnote">已按原要求交付文件,未运行测试。</p>}</div>}
{!!task.instructions.length && <details className="task-instructions"><summary>追加要求 · {task.instructions.length}</summary>{task.instructions.map(instruction => <p key={instruction.id}><small>{instruction.source && instruction.source !== 'user' ? '系统操作 · ' + instruction.source : '用户要求'}</small><br />{instruction.content}</p>)}</details>}
</> : <p className="record-empty">发送任务后,这里保存目标、每次运行和实际结果。</p>}
</section>
{task && <TaskFollowUp session={session} openArtifact={openArtifact} />}
{task && <FileResultsPanel session={session} busy={busy} onSession={onSession} openArtifact={openArtifact} />}
{task && <TaskPlanPanel session={session} busy={busy} onSession={onSession} onError={onError} openArtifact={openArtifact} />}
{task && <RequirementPanel 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>
{run.status === 'needs_review' && task.delivery?.status === 'files_applied' && <p className="record-footnote">这次运行在文件审查前结束;文件此后已应用,当前交付状态见上方任务目标。</p>}
{run.purpose === 'diagnostic' && <p className="record-footnote">本次为只读诊断,运行结束仅表示答复完成;原任务状态另行保留。</p>}
{run.purpose === 'diagnostic' && run.diagnosticContext && <p className="record-footnote">原执行 {run.diagnosticContext.originalRunId?.slice(0, 8) ?? '未记录'}<button className="text-button" onClick={() => openArtifact(run.diagnosticContext!.artifactId)}>查看原绑定</button></p>}
<dl className="record-fields"><ActualModelFields run={run} session={session} />{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>{run.budget?.maxTokens === 0 ? 'tokens 不限' : number(run.budget?.maxTokens) + ' tokens'} · {run.budget?.maxDurationMs === 0 ? '时长不限' : Math.round((run.budget?.maxDurationMs ?? 0) / 60000) + ' 分钟'} · {run.budget?.maxSteps === 0 ? '轮次不限' : run.budget?.maxSteps + ' 轮'}</dd><dt>任务累计</dt><dd>{number(execution?.accountedTaskTokens)} / {task.budget.maxTokens === 0 ? '不限' : number(task.budget.maxTokens)} tokens</dd>
</dl>{run.stopReason && <p className="run-stop">{stopReasons[run.stopReason] || run.stopReason}</p>}
<p className="record-footnote">用量按请求尝试累计,包含失败响应已报告的 tokens;未报告的请求单独估算。历史缺失不补造,tokens 不等于费用。</p>
<TurnProgress run={run} openArtifact={openArtifact} />
</> : <p className="record-empty"><LoaderCircle size={14} className="spin" />正在读取运行记录</p>}
</section>}
{run && <RequestContextPanel session={session} runId={run.id} onError={onError} openArtifact={openArtifact} />}
{task && <EnvironmentPanel project={project} session={session} busy={busy} onSession={onSession} onError={onError} openArtifact={openArtifact} />}
{task && <PreviewPanel onOpen={onOpenPreview} project={project} session={session} busy={busy} onSession={onSession} 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>
{task?.verification.status === 'failed' && <p className="record-footnote" role="status">原工程检查有失败记录;文件应用或答复完成不代表检查通过。</p>}
{task?.contract?.checks === 'skip' && <p className="record-footnote">原任务无需测试。下方操作只在你明确选择并确认后执行。</p>}
<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.environment&&<p className="record-footnote">环境:Node {latestPlan.environment.runtime.node.version} · npm {latestPlan.environment.runtime.npm?.version??'未找到'} · {latestPlan.environment.status==='ready'?'依赖已就绪':'依赖需要核对,请先查看上方工程环境'}{latestPlan.environment.preparation&&' · 引用依赖准备 '+latestPlan.environment.preparation.jobId.slice(0,8)}</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 ActualModelFields({ run, session }: { run: Run; session: Session }) {
const receipts = run.consumption ?? [];
const events = session.events.filter(event => event.runId === run.id && event.actualModel && event.connectionId);
const observed = receipts.length ? receipts.map(receipt => ({ id: receipt.connectionId, name: receipt.connectionName, model: receipt.model, endpoint: receipt.endpoint, identity: receipt.modelIdentity }))
: events.map(event => { const member = run.model.routing?.members?.find(member => member.id === event.connectionId); return { id: event.connectionId, name: member?.name, model: event.actualModel!, endpoint: member?.baseUrl, identity: undefined }; });
const routes = observed.filter((value, index) => observed.findIndex(candidate => candidate.id === value.id && candidate.model === value.model && candidate.endpoint === value.endpoint && JSON.stringify(candidate.identity) === JSON.stringify(value.identity)) === index);
return <><dt>启动选择</dt><dd>{run.model?.verified === false ? '历史配置未记录' : run.model?.mode === 'demo' ? '离线演示 · 固定脚本' : run.model.routing?.name || run.model.model || '未记录'}</dd>
<dt>实际调用</dt><dd>{routes.length ? routes.map((route, index) => <div key={index}><span>{route.name ? route.name + ' · ' : ''}{route.model}</span><ModelIdentityDetails identity={route.identity} requestedModel={route.model} />{route.endpoint && <small className="record-endpoint"><br />{route.endpoint}</small>}</div>) : run.model.mode === 'demo' ? '未调用模型服务' : '尚无可核对的实际连接记录'}</dd>
{!receipts.length && run.model.mode !== 'demo' && <><dt>启动接口</dt><dd className="record-endpoint">{run.model.baseUrl || '未记录'}<br /><small>启动配置不代表实际池成员</small></dd></>}
{!!receipts.length && <><dt>用量凭据</dt><dd>{receipts.length} 次请求尝试 · {receipts.filter(receipt => receipt.usageStatus === 'reported').length} 次已报告</dd></>}
</>;
}
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>;
}