feat(tasks): review sourced requirements against current original evidence

This commit is contained in:
Agent Workbench Dev
2026-11-04 10:36:50 +08:00
parent ce3afb2f0d
commit 785dd0c54d
70 changed files with 6103 additions and 7 deletions
+19
View File
@@ -0,0 +1,19 @@
.requirement-list { list-style: none; padding: 0; margin: 0; }
.requirement-list > li { padding: 14px 0; border-top: 1px solid #dce7e2; font-size: 12px; line-height: 1.65; overflow-wrap: anywhere; }
.requirement-heading { display: flex; justify-content: space-between; align-items: baseline; gap: 10px; }
.requirement-heading strong { font-size: 13px; }
.requirement-state { color: #674917; background: #fbf2df; padding: 2px 6px; border-radius: 3px; flex-shrink: 0; font-size: 11px; }
.requirement-evidence_verified, .requirement-user_confirmed { color: #154b4a; background: #edf3f1; }
.requirement-list summary, .requirement-history summary { cursor: pointer; color: #526a70; }
.requirement-list blockquote, .requirement-quote { margin: 9px 0; border-left: 2px solid #bbcfc7; padding: 6px 12px; white-space: pre-wrap; font-size: 12px; max-height: 150px; overflow: auto; }
.requirement-list code { font-size: 10px; overflow-wrap: anywhere; }
.requirement-actions { display: flex; flex-wrap: wrap; gap: 12px; margin: 7px 0; }
.requirement-confirm label { display: grid; gap: 6px; }
.requirement-confirm textarea { width: 100%; box-sizing: border-box; font: inherit; padding: 8px; border: 1px solid #cbded3; border-radius: 5px; margin-bottom: 8px; }
.requirement-history { font-size: 11px; margin-top: 12px; }
.requirement-history p { display: grid; gap: 4px; }
.requirement-editor { max-height: 72vh; overflow: auto; }
.requirement-offsets { display: flex; gap: 12px; margin: 12px 0; }
.requirement-offsets label { min-width: 0; font-size: 12px; }
.requirement-panel button:focus-visible, .requirement-panel textarea:focus-visible, .requirement-editor :is(input, select, textarea):focus-visible { outline: 2px solid #4664d9; outline-offset: 2px; }
@media (max-width: 600px) { .requirement-heading { flex-direction: column; gap: 4px; } .requirement-panel .button { min-height: 36px; } }
+102
View File
@@ -0,0 +1,102 @@
import { useEffect, useRef, useState } from 'react';
import { Check, FileText, Plus, RefreshCw } from 'lucide-react';
import { api } from './api';
import { Modal } from './components';
import type { RequirementItem, RequirementView, Session, TaskPlanStep } from './types';
import './RequirementPanel.css';
const states: Record<string, string> = { pending: '待复核', failed: '复核未通过', stale: '依据已失效', unverified: '原记录待核对',
evidence_verified: '所选证据已核对', user_confirmed: '用户已确认', not_requested: '按约定未执行' };
const kinds: Record<TaskPlanStep['kind'], string> = { analysis: '研究与读取', changes: '已应用改动', results: '当前文件', checks: '工程检查', browser: '页面断言' };
const clean = (row: RequirementItem) => ({ key: row.key, title: row.title, criterion: row.criterion, kind: row.kind, method: row.method,
source: { kind: row.source.kind, id: row.source.id, start: row.source.start, end: row.source.end },
...(row.kind === 'analysis' ? { tools: row.tools } : ['changes', 'results'].includes(row.kind) ? { paths: row.paths }
: row.kind === 'checks' ? { checks: row.checks } : { viewport_width: row.viewport_width, actions: row.actions }) });
const scope = (kind: TaskPlanStep['kind']) => kind === 'analysis' ? { tools: ['read_file'] } : ['changes', 'results'].includes(kind)
? { paths: [] } : kind === 'checks' ? { checks: ['test', 'build'] } : { viewport_width: 1280, actions: ['assert_visible'] };
export function RequirementPanel({ session, busy, onSession, onError, openArtifact }: {
session: Session; busy: boolean; onSession: (value: Session) => void; onError: (error: unknown) => void; openArtifact: (id: string) => void;
}) {
const task = session.execution?.task, run = session.execution?.run;
const identity = `${session.projectId}/${session.id}/${task?.id}/${run?.id}`;
const selected = useRef(identity); selected.current = identity;
const generation = useRef(0), mutation = useRef(false);
const [view, setView] = useState<RequirementView | null>(null), [loading, setLoading] = useState(false), [saving, setSaving] = useState(false);
const [draft, setDraft] = useState<RequirementItem | null>(null), [picked, setPicked] = useState<Record<string, string>>({}), [notes, setNotes] = useState<Record<string, string>>({});
const [notice, setNotice] = useState('');
const disabled = busy || saving || ['running', 'awaiting_approval', 'stopping'].includes(session.status);
useEffect(() => { generation.current++; setView(null); setDraft(null); setPicked({}); setNotes({}); setNotice(''); setSaving(false); mutation.current = false;
return () => { generation.current++; }; }, [identity]);
useEffect(() => { const timer = setTimeout(() => { void load(); }, 120); return () => clearTimeout(timer); }, [identity, session.revision, session.status]);
async function load() {
if (!task || mutation.current) return;
const scopeId = identity, request = ++generation.current; setLoading(true);
try { const result = await api<RequirementView>(`/sessions/${session.id}/requirements?taskId=${task.id}`);
if (selected.current === scopeId && generation.current === request) setView(result);
} catch (error) { if (selected.current === scopeId && generation.current === request) onError(error); }
finally { if (selected.current === scopeId && generation.current === request) setLoading(false); }
}
async function mutate(action: string, input: object) {
if (!task || !run || !view || mutation.current) return;
mutation.current = true; generation.current++; setSaving(true); setNotice(''); const scopeId = identity;
try {
const reply = await api<{ session: Session; requirements: RequirementView; verification?: { status: string; message?: string } }>(`/sessions/${session.id}/${action}`,
{ taskId: task.id, runId: run.id, expected_revision: view.revision, ...input });
if (selected.current !== scopeId) return;
setView(reply.requirements); onSession(reply.session);
setNotice(reply.verification?.status === 'error' ? reply.verification.message ?? '复核未通过,原失败已保留。' : action === 'requirements' ? '要求与原文来源已保存。' : '本次复核已记录。');
if (action === 'requirements') setDraft(null);
} catch (error) { if (selected.current === scopeId) onError(error); }
finally { if (selected.current === scopeId) { mutation.current = false; setSaving(false); setLoading(false); } }
}
function edit(row?: RequirementItem) {
const source = view?.sources[0]; if (!source) return;
setDraft(row ? { ...clean(row), depends_on: [] } : { key: 'req_' + crypto.randomUUID().slice(0, 8), title: '', criterion: '', kind: 'analysis', method: 'evidence',
source: { kind: source.kind, id: source.id, start: 0, end: source.text.length }, depends_on: [], ...scope('analysis') });
}
const source = view?.sources.find(row => row.id === draft?.source.id && row.kind === draft?.source.kind);
return <section className="task-record-section requirement-panel" aria-label="要求与证据">
<div className="record-heading"><h3>要求与证据</h3><span>{view?.items.length ?? 0} 项</span></div>
<p className="record-footnote">逐项保留用户原文与实际依据,工程证据和用户体验分别记录。</p>
<div className="plan-toolbar"><button className="text-button" disabled={loading || disabled} onClick={() => void load()}><RefreshCw size={13} />刷新复核</button>
<button className="button secondary" disabled={disabled || !view || view.status === 'unverified' || (view.items.length >= 24)} onClick={() => edit()}><Plus size={13} />记录要求</button></div>
{notice && <p className="plan-notice" role="status">{notice}</p>}
{view?.error && <p className="plan-problem" role="alert">{view.error}</p>}
{!!view?.unreviewed_sources?.length && <p className="plan-problem">有 {view.unreviewed_sources.length} 份用户来源尚未审阅。核对原目标和追加要求后保存要求;旧复核记录保留。</p>}
{view && !view.items.length && <p className="record-empty">尚未逐项记录要求。模型的完成答复保留在原会话中。</p>}
<ol className="requirement-list">{view?.items.map(row => <li key={row.key}>
<div className="requirement-heading"><strong>{row.title}</strong><span className={'requirement-state requirement-' + row.status}>{states[row.status ?? 'pending'] ?? row.status}</span></div>
<p>{row.criterion}</p>
<details><summary>用户原文 · {row.source.kind === 'goal' ? '原目标' : '追加要求'} · 要求修订 {row.revision}</summary>
<blockquote>{row.source.quote}</blockquote><code>{row.source.id} [{row.source.start}, {row.source.end})</code></details>
{row.error && <p className="plan-problem">{row.error}</p>}{row.last_rejection && <p className="plan-problem">原复核失败:{row.last_rejection.message}</p>}
{row.user_note && <p>用户确认:{row.user_note}</p>}
<div className="requirement-actions"><button className="text-button" disabled={disabled} onClick={() => edit(row)}>修订此要求</button>
{row.proof_artifact_id && <button className="text-button" onClick={() => openArtifact(row.proof_artifact_id!)}><FileText size={13} />原复核记录</button>}</div>
{row.method === 'evidence' && <div className="plan-evidence"><label>选择实际依据 · {kinds[row.kind]}<select aria-label={`要求依据 ${row.title}`} disabled={disabled} value={picked[row.key] ?? ''} onChange={event => setPicked(values => ({ ...values, [row.key]: event.target.value }))}>
<option value="">选择此任务的原结果</option>{row.candidates?.map(candidate => <option key={candidate.id} value={candidate.id}>{candidate.label} · {candidate.status} · {candidate.id.slice(0, 8)}</option>)}</select></label>
<button className="button secondary" disabled={disabled || !picked[row.key]} onClick={() => void mutate('requirement-proofs', { key: row.key, evidence_id: picked[row.key] })}><Check size={13} />复核所选证据</button></div>}
{row.method === 'user' && <div className="requirement-confirm"><label>实际体验与结论<textarea aria-label={`用户确认 ${row.title}`} rows={2} maxLength={1000} disabled={disabled} value={notes[row.key] ?? ''} onChange={event => setNotes(values => ({ ...values, [row.key]: event.target.value }))} /></label>
<button className="button secondary" disabled={disabled || !notes[row.key]?.trim()} onClick={() => void mutate('requirement-proofs', { key: row.key, note: notes[row.key] })}>记录用户确认</button></div>}
{row.method === 'not_requested' && <p className="record-footnote">检查未执行,不计为测试通过。</p>}
</li>)}</ol>
{!!view?.history?.length && <details className="requirement-history"><summary>原复核历史 · {view.history.length} 条</summary>{view.history.map(row => <p key={row.id}><button className="text-button" onClick={() => openArtifact(row.artifact_id)}>{row.key} · 修订 {row.revision} · {row.status === 'rejected' ? '未通过' : '已记录'}</button>{row.error && <span>{row.error}</span>}</p>)}</details>}
{draft && view && <Modal title="记录用户要求" description="选定用户原文、验收范围和复核方式;修订保留旧要求与原失败。" wide onClose={() => { if (!saving) setDraft(null); }}>
<form className="plan-editor requirement-editor" onSubmit={event => { event.preventDefault(); const rows = view.items.some(row => row.key === draft.key) ? view.items.map(row => row.key === draft.key ? clean(draft) : clean(row)) : [...view.items.map(clean), clean(draft)]; void mutate('requirements', { requirements: rows }); }}>
<fieldset disabled={saving} className="plan-editor-step">
<label>要求名称<input aria-label="要求名称" maxLength={100} required value={draft.title} onChange={event => setDraft({ ...draft, title: event.target.value })} /></label>
<label>验收条件<textarea aria-label="要求验收条件" rows={2} required maxLength={300} value={draft.criterion} onChange={event => setDraft({ ...draft, criterion: event.target.value })} /></label>
<label>用户原文来源<select aria-label="要求原文来源" value={draft.source.id} onChange={event => { const row = view.sources.find(value => value.id === event.target.value)!; setDraft({ ...draft, source: { kind: row.kind, id: row.id, start: 0, end: row.text.length } }); }}>{view.sources.map((row, i) => <option key={row.id} value={row.id}>{row.kind === 'goal' ? '原目标' : `追加要求 ${i}`} · {row.text.slice(0, 65)}</option>)}</select></label>
<blockquote className="requirement-quote">{source?.text.slice(draft.source.start, draft.source.end)}</blockquote>
<div className="requirement-offsets"><label>原文起点<input aria-label="原文起点" type="number" min={0} max={Math.max(0, (source?.text.length ?? 1) - 1)} value={draft.source.start} onChange={event => setDraft({ ...draft, source: { ...draft.source, start: Number(event.target.value) } })} /></label><label>原文终点<input aria-label="原文终点" type="number" min={draft.source.start + 1} max={source?.text.length} value={draft.source.end} onChange={event => setDraft({ ...draft, source: { ...draft.source, end: Number(event.target.value) } })} /></label></div>
<label>复核方式<select aria-label="要求复核方式" value={draft.method} onChange={event => setDraft({ ...draft, method: event.target.value as RequirementItem['method'], ...(event.target.value === 'not_requested' ? { kind: 'checks', checks: ['test', 'build'] } : {}) })}><option value="evidence">核对实际证据</option><option value="user">用户体验确认</option><option value="not_requested">按用户约定不执行检查</option></select></label>
{draft.method === 'evidence' && <><label>证据类别<select aria-label="要求证据类别" value={draft.kind} onChange={event => { const kind = event.target.value as TaskPlanStep['kind']; setDraft({ ...draft, kind, ...scope(kind) }); }}>{Object.entries(kinds).map(([key, label]) => <option key={key} value={key}>{label}</option>)}</select></label>
{['results', 'changes'].includes(draft.kind) && <label>文件范围(每行一项)<textarea aria-label="要求文件范围" required value={draft.paths?.join('\n') ?? ''} onChange={event => setDraft({ ...draft, paths: event.target.value.split('\n').filter(Boolean) })} /></label>}
{draft.kind === 'analysis' && <label>读取工具(逗号分隔)<input aria-label="要求读取工具" required value={draft.tools?.join(',') ?? ''} onChange={event => setDraft({ ...draft, tools: event.target.value.split(',').map(value => value.trim()) })} /></label>}
{draft.kind === 'checks' && <label>检查名称(逗号分隔)<input aria-label="要求检查名称" required value={draft.checks?.join(',') ?? ''} onChange={event => setDraft({ ...draft, checks: event.target.value.split(',').map(value => value.trim()) })} /></label>}
{draft.kind === 'browser' && <label>验收视口<select aria-label="要求验收视口" value={draft.viewport_width} onChange={event => setDraft({ ...draft, viewport_width: Number(event.target.value) })}><option value={1280}>桌面 · 1280px</option><option value={390}>手机 · 390px</option></select></label>}</>}
</fieldset><div className="modal-actions"><button type="button" className="button secondary" disabled={saving} onClick={() => setDraft(null)}>取消</button><button className="button primary" disabled={saving}>保存要求</button></div>
</form></Modal>}
</section>;
}
+3
View File
@@ -9,6 +9,7 @@ import { RequestContextPanel } from './RequestContextPanel';
import { WorkspacePanel } from './WorkspacePanel';
import { BrowserPanel } from './BrowserPanel';
import { TaskPlanPanel } from './TaskPlanPanel';
import { RequirementPanel } from './RequirementPanel';
import { TaskCheckpointPanel } from './TaskCheckpointPanel';
import { McpJobHistory } from './McpJobHistory';
import './TaskPanel.css';
@@ -26,6 +27,7 @@ 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;
@@ -99,6 +101,7 @@ export function TaskPanel({ project, session, onSession, onError, busy, onWorksp
</section>
{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} />}
+11
View File
@@ -228,6 +228,17 @@ export interface TaskPlanView {
contract_artifact_id?: string; contract_sha256?: string; checked_at?: string; error?: string;
}
export interface TaskPlanReply { session: Session; plan: TaskPlanView; verification?: { status: string; reused?: boolean; proof_id: string; message?: string } }
export interface RequirementSource { kind: 'goal' | 'instruction'; id: string; text: string; sha256: string; at: string | null }
export interface RequirementItem extends TaskPlanStep {
method: 'evidence' | 'user' | 'not_requested'; source: { kind: string; id: string; start: number; end: number; quote?: string; sourceSha256?: string; at?: string | null };
revision?: number; status?: string; error?: string | null; proof_id?: string | null; proof_artifact_id?: string | null; user_note?: string | null;
evidence?: TaskPlanStepView['evidence']; candidates?: TaskPlanStepView['candidates']; last_rejection?: { message: string } | null;
}
export interface RequirementView {
configured: boolean; task_id: string; revision: number; status: string; items: RequirementItem[]; sources: RequirementSource[];
all_resolved: boolean; unreviewed_sources?: string[]; error?: string; note: string; contract_artifact_id?: string;
history?: { id: string; key: string; revision: number; status: string; error: string | null; at: string; artifact_id: 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[]; mcpJobs?: McpJob[]; plans?: CheckPlan[]; deliveries?: DeliveryJob[]; deliveryPlans?: DeliveryPlan[]; changeSets?: ChangeSet[]; contextPlans?: ContextPlan[]; workspaces?: WorkspaceRecord[]; researchTargets?: ResearchTarget[]; researchJobs?: ResearchJob[]; engineJobs?: EngineJob[]; engineRuns?: EngineRunView[]; browserPlans?: BrowserPlan[]; browserJobs?: BrowserJob[]; taskPlans?: TaskPlanRecord[]; taskProofs?: { id: string; planId: string; stepKey: string; status: string }[]; collaborations?: CollaborationGroup[]; workers?: WorkerRecord[]; workspaceIdentity?: WorkspaceIdentity; accountedTaskTokens: number }
export interface WorkerBudget { maxTokens: number; maxSteps: number; maxToolCalls: number }
export interface WorkerDefinition { id: string; label: string; goal: string; paths: string[]; budget: WorkerBudget; workspaceId: string; projectId: string; sessionId: string; taskId: string; engine?: ControlledEngineAvailability }