134 lines
16 KiB
TypeScript
134 lines
16 KiB
TypeScript
import { useEffect, useRef, useState } from 'react';
|
||
import { Check, Circle, FileText, GitPullRequestArrow, LoaderCircle, Plus, RefreshCw } from 'lucide-react';
|
||
import { api } from './api';
|
||
import { Modal, Status } from './components';
|
||
import type { Session, TaskPlanReply, TaskPlanStep, TaskPlanView } from './types';
|
||
import './TaskPlanPanel.css';
|
||
|
||
const kinds: Record<TaskPlanStep['kind'], string> = { analysis: '读取工程', changes: '源码改动', results: '当前文件成果', checks: '工程检查', browser: '页面验收' };
|
||
const readTools = { inspect_project: '识别工程', read_file: '读取文件', list_files: '文件清单', search_files: '搜索文件', index_project: '工程索引', query_code: '定位符号', read_research_evidence: 'REA原结果', inspect_engine_checks: '引擎核验', read_browser_result: '原页面记录' };
|
||
const browserActions = { fill: '填写', select: '选择', click: '点击', assert_text: '文本断言', assert_count: '数量断言', assert_visible: '可见断言' };
|
||
const cleanStep = (step: TaskPlanStep): TaskPlanStep => ({ key: step.key, title: step.title, criterion: step.criterion, kind: step.kind, depends_on: [...step.depends_on],
|
||
...(step.kind === 'analysis' ? { tools: [...(step.tools ?? [])] } : ['changes', 'results'].includes(step.kind) ? { paths: (step.paths ?? []).map(value => value.trim()).filter(Boolean) }
|
||
: step.kind === 'checks' ? { checks: (step.checks ?? []).map(value => value.trim()).filter(Boolean) } : { viewport_width: step.viewport_width, actions: [...(step.actions ?? [])] }) });
|
||
const freshStep = (kind: TaskPlanStep['kind'] = 'analysis'): TaskPlanStep => ({ key: 'step_' + crypto.randomUUID().slice(0, 8), title: kinds[kind], criterion: '', kind, depends_on: [],
|
||
...(kind === 'analysis' ? { tools: ['inspect_project'] } : ['changes', 'results'].includes(kind) ? { paths: [] } : kind === 'checks' ? { checks: ['test', 'build'] } : { viewport_width: 1280, actions: ['assert_visible'] }) });
|
||
const scopeText = (step: TaskPlanStep) => step.kind === 'analysis' ? (step.tools ?? []).map(tool => readTools[tool as keyof typeof readTools] ?? tool).join(' / ')
|
||
: ['changes', 'results'].includes(step.kind) ? step.paths?.join('、') : step.kind === 'checks' ? step.checks?.join(' / ')
|
||
: `${step.viewport_width}px · ${(step.actions ?? []).map(action => browserActions[action as keyof typeof browserActions]).join(' / ')}`;
|
||
|
||
export function TaskPlanPanel({ 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 selection = useRef(identity); selection.current = identity;
|
||
const requests = useRef(0);
|
||
const [view, setView] = useState<TaskPlanView | null>(null);
|
||
const [loading, setLoading] = useState(false), [mutating, setMutating] = useState(false);
|
||
const [editor, setEditor] = useState(false), [draft, setDraft] = useState<TaskPlanStep[]>([]), [fixed, setFixed] = useState(0);
|
||
const [picked, setPicked] = useState<Record<string, string>>({}), [notice, setNotice] = useState('');
|
||
const currentPlan = session.execution?.taskPlans?.at(-1)?.id, currentProof = session.execution?.taskProofs?.at(-1)?.id;
|
||
const disabled = busy || mutating || ['running', 'awaiting_approval', 'stopping'].includes(session.status);
|
||
|
||
useEffect(() => { selection.current = identity; setView(null); setLoading(false); setEditor(false); setMutating(false); setPicked({}); setNotice(''); requests.current++;
|
||
return () => { requests.current++; if (selection.current === identity) selection.current = ''; };
|
||
}, [identity]);
|
||
useEffect(() => { const timer = setTimeout(() => { void load(); }, 120); return () => clearTimeout(timer); }, [identity, currentPlan, currentProof, session.status]);
|
||
|
||
async function load() {
|
||
if (!task) return;
|
||
const request = ++requests.current, scope = identity; setLoading(true);
|
||
try { const value = await api<TaskPlanView>(`/sessions/${session.id}/task-plan?taskId=${task.id}`);
|
||
if (selection.current === scope && requests.current === request) setView(value);
|
||
} catch (error) { if (selection.current === scope && requests.current === request) onError(error); }
|
||
finally { if (selection.current === scope && requests.current === request) setLoading(false); }
|
||
}
|
||
function edit() {
|
||
const steps = view?.steps.map(cleanStep) ?? [];
|
||
setFixed(steps.length); setDraft(steps.length ? steps : [freshStep()]); setNotice(''); setEditor(true);
|
||
}
|
||
function update(index: number, patch: Partial<TaskPlanStep>) { setDraft(steps => steps.map((step, at) => at === index ? { ...step, ...patch } : step)); }
|
||
async function save() {
|
||
if (!task || !run || !view) return;
|
||
const scope = identity; setMutating(true); setNotice(''); requests.current++;
|
||
try {
|
||
const value = await api<TaskPlanReply>(`/sessions/${session.id}/task-plans`, { taskId: task.id, runId: run.id, expected_revision: view.revision, steps: draft.map(cleanStep) });
|
||
if (selection.current === scope) { onSession(value.session); setView(value.plan); setEditor(false); setNotice('执行计划已保存,按实际结果核验步骤。'); }
|
||
} catch (error) { if (selection.current === scope) onError(error); }
|
||
finally { if (selection.current === scope) { setMutating(false); setLoading(false); } }
|
||
}
|
||
async function verify(stepKey: string, evidenceId: string) {
|
||
if (!task || !run || !view?.plan_id || !evidenceId) return;
|
||
const scope = identity; setMutating(true); setNotice(''); requests.current++;
|
||
try {
|
||
const value = await api<TaskPlanReply>(`/sessions/${session.id}/task-proofs`, { taskId: task.id, runId: run.id,
|
||
plan_id: view.plan_id, expected_revision: view.revision, step_key: stepKey, evidence_id: evidenceId });
|
||
if (selection.current === scope) { onSession(value.session); setView(value.plan);
|
||
setNotice(value.verification?.status === 'completed' ? '原结果核验完成,没有再次执行工具。' : value.verification?.message ?? '核验未通过,请查看原结果。'); }
|
||
} catch (error) { if (selection.current === scope) onError(error); }
|
||
finally { if (selection.current === scope) { setMutating(false); setLoading(false); } }
|
||
}
|
||
|
||
return <section className="task-record-section task-plan-panel" aria-label="执行计划" aria-busy={loading || mutating}>
|
||
<div className="record-heading"><GitPullRequestArrow size={15} /><h3>执行计划</h3><span>{view?.configured ? `${view.verified_steps ?? 0} / ${view.total_steps ?? view.steps.length}` : '按结果核验'}</span></div>
|
||
<div className="plan-toolbar"><button type="button" className="text-button" disabled={loading || mutating} onClick={() => void load()}>
|
||
{loading ? <LoaderCircle size={13} className="spin" /> : <RefreshCw size={13} />}核对当前计划</button>
|
||
<button type="button" className="text-button" disabled={disabled || !view || task?.status === 'completed' || !!view.error} onClick={edit}><Plus size={13} />{view?.configured ? '补充步骤' : '建立计划'}</button>
|
||
</div>
|
||
{notice && <p className="plan-notice" role="status">{notice}</p>}
|
||
{!view ? <p className="record-empty">正在核对任务计划。</p> : !view.configured ? <p className="record-empty">{task?.status === 'completed' ? '本任务未设置执行计划。新任务可先固定步骤与通过条件。' : '先固定要完成的步骤,再用读取、改动、检查或页面结果核验。'}</p> : <>
|
||
<div className="plan-overview"><Status value={view.status} /><small>第 {view.revision} 版</small></div>
|
||
{view.error && <p className="plan-problem">{view.error}</p>}
|
||
{view.requirements_current === false && <p className="plan-problem">任务要求已更新。保留原步骤,补充新要求后重新核验仍有效的结果。</p>}
|
||
<ol className="plan-steps">{view.steps.map((step, index) => {
|
||
const evidenceId = picked[step.key] ?? step.evidence?.id ?? step.candidates?.find(candidate => ['completed', 'passed', 'applied'].includes(candidate.status))?.id ?? step.candidates?.[0]?.id ?? '';
|
||
const blockers = step.blockers.map(key => view.steps.find(value => value.key === key)?.title ?? key);
|
||
return <li key={step.key} className={`plan-step plan-step-${step.status}`}>
|
||
<div className="plan-step-marker" aria-hidden="true">{step.status === 'verified' ? <Check size={13} /> : <Circle size={11} />}</div>
|
||
<div className="plan-step-main"><div className="plan-step-heading"><strong>{index + 1}. {step.title}</strong><Status value={step.status} /></div>
|
||
<p>{step.criterion}</p><small className="plan-step-scope">{kinds[step.kind]} · {scopeText(step)}</small>
|
||
{!!step.depends_on.length && <p className="plan-dependencies">前置:{step.depends_on.map(key => view.steps.find(value => value.key === key)?.title ?? key).join('、')}</p>}
|
||
{!!blockers.length && <p className="plan-problem">先核验:{blockers.join('、')}</p>}
|
||
{step.error && <p className="plan-problem">{step.error}</p>}
|
||
{step.last_rejection && <details className="plan-rejection"><summary>最近一次核验未通过</summary><p>{step.last_rejection.message}</p></details>}
|
||
<details className="plan-evidence" open={['ready', 'stale', 'unverified'].includes(step.status)}><summary>{step.status === 'verified' ? '查看核验依据' : '选择实际结果'}</summary>
|
||
<label>原执行结果<select aria-label={`步骤${index + 1}原证据`} value={evidenceId} disabled={disabled} onChange={event => setPicked(values => ({ ...values, [step.key]: event.target.value }))}>
|
||
<option value="">选择此任务的实际结果</option>{step.candidates?.map(candidate => <option key={candidate.id} value={candidate.id}>{candidate.label} · {candidate.status} · {candidate.id.slice(0, 8)}</option>)}
|
||
</select></label>
|
||
<button type="button" className="button secondary" disabled={disabled || !evidenceId || !!blockers.length || view.requirements_current === false} onClick={() => void verify(step.key, evidenceId)}><Check size={13} />核验此步骤</button>
|
||
{step.proof_artifact_id && <button type="button" className="text-button" onClick={() => openArtifact(step.proof_artifact_id!)}><FileText size={13} />查看原核验记录</button>}
|
||
{step.evidence?.artifacts?.map(artifact => <button type="button" className="text-button" key={artifact.id} onClick={() => openArtifact(artifact.id)}><FileText size={13} />原依据 · {artifact.sha256.slice(0, 8)}</button>)}
|
||
</details>
|
||
</div>
|
||
</li>;
|
||
})}</ol>
|
||
{view.contract_artifact_id && <button type="button" className="text-button" onClick={() => openArtifact(view.contract_artifact_id!)}><FileText size={13} />查看原计划</button>}
|
||
<p className="record-footnote">核验依据为实际操作和当前文件;业务含义仍需独立验收。</p>
|
||
</>}
|
||
{editor && <Modal title="编辑执行计划" description="固定步骤、前置依赖和通过条件。保存计划不会运行工具。" wide onClose={() => { if (!mutating) setEditor(false); }}>
|
||
<form onSubmit={event => { event.preventDefault(); void save(); }} className="plan-editor">
|
||
<div className="plan-editor-scroll">{draft.map((step, index) => <fieldset className="plan-editor-step" key={step.key} disabled={mutating || index < fixed}>
|
||
<legend>步骤 {index + 1}{index < fixed ? ' · 已封存' : ''}</legend>
|
||
<label>步骤名称<input aria-label={`步骤${index + 1}名称`} value={step.title} maxLength={100} required onChange={event => update(index, { title: event.target.value })} /></label>
|
||
<label>通过条件<textarea aria-label={`步骤${index + 1}通过条件`} value={step.criterion} maxLength={300} required rows={2} placeholder="说明这一步完成后应该得到什么实际结果" onChange={event => update(index, { criterion: event.target.value })} /></label>
|
||
<label>结果类别<select aria-label={`步骤${index + 1}类别`} value={step.kind} onChange={event => {
|
||
const next = freshStep(event.target.value as TaskPlanStep['kind']); setDraft(steps => steps.map((value, at) => at === index ? { ...next, key: value.key, title: value.title, criterion: value.criterion, depends_on: value.depends_on } : value));
|
||
}}>{Object.entries(kinds).map(([key, label]) => <option key={key} value={key}>{label}</option>)}</select></label>
|
||
{step.kind === 'analysis' && <div className="plan-option-list"><span>可核验的读取结果(任一)</span>{Object.entries(readTools).map(([key, label]) => <label key={key}><input type="checkbox" checked={step.tools?.includes(key) ?? false} onChange={event => update(index, { tools: event.target.checked ? [...(step.tools ?? []), key] : step.tools?.filter(tool => tool !== key) })} />{label}</label>)}</div>}
|
||
{['changes', 'results'].includes(step.kind) && <label>{step.kind === 'results' ? '成果文件' : '改动文件'}(每行一项)<textarea aria-label={`步骤${index + 1}文件范围`} rows={3} value={step.paths?.join('\n') ?? ''} placeholder="src/main.tsx" onChange={event => update(index, { paths: event.target.value.split('\n') })} /></label>}
|
||
{step.kind === 'checks' && <label>检查名称(逗号分隔)<input aria-label={`步骤${index + 1}检查范围`} value={step.checks?.join(',') ?? ''} placeholder="test,build 或 python:test,python:compile" onChange={event => update(index, { checks: event.target.value.split(',') })} /></label>}
|
||
{step.kind === 'browser' && <><label>页面宽度<select aria-label={`步骤${index + 1}页面宽度`} value={step.viewport_width} onChange={event => update(index, { viewport_width: Number(event.target.value) })}><option value={1280}>桌面 · 1280px</option><option value={390}>手机 · 390px</option>{![1280, 390].includes(step.viewport_width ?? 0) && <option value={step.viewport_width}>{step.viewport_width}px</option>}</select></label>
|
||
<div className="plan-option-list"><span>必须实际完成的操作</span>{Object.entries(browserActions).map(([key, label]) => <label key={key}><input type="checkbox" checked={step.actions?.includes(key) ?? false} onChange={event => update(index, { actions: event.target.checked ? [...(step.actions ?? []), key] : step.actions?.filter(action => action !== key) })} />{label}</label>)}</div></>}
|
||
{index > 0 && <div className="plan-option-list"><span>前置步骤</span>{draft.slice(0, index).map(previous => <label key={previous.key}><input type="checkbox" checked={step.depends_on.includes(previous.key)} onChange={event => update(index, { depends_on: event.target.checked ? [...step.depends_on, previous.key] : step.depends_on.filter(key => key !== previous.key) })} />{previous.title}</label>)}</div>}
|
||
{index >= fixed && draft.length > Math.max(1, fixed) && <button type="button" className="text-button" onClick={() => setDraft(steps => steps.filter(value => value.key !== step.key).map(value => ({ ...value, depends_on: value.depends_on.filter(key => key !== step.key) })))}>移除此新步骤</button>}
|
||
</fieldset>)}
|
||
<button type="button" className="button secondary" disabled={mutating || draft.length >= 12} onClick={() => setDraft(steps => [...steps, freshStep()])}><Plus size={14} />追加步骤</button>
|
||
{fixed > 0 && <p className="record-footnote">原步骤和通过条件已封存,新增要求以追加步骤保留。</p>}
|
||
</div>
|
||
<div className="modal-actions"><button type="button" className="button secondary" disabled={mutating} onClick={() => setEditor(false)}>取消</button><button type="submit" className="button primary" disabled={mutating || draft.length > 12}>{mutating ? <LoaderCircle size={14} className="spin" /> : <Check size={14} />}保存执行计划</button></div>
|
||
</form>
|
||
</Modal>}
|
||
</section>;
|
||
}
|