101 lines
12 KiB
TypeScript
101 lines
12 KiB
TypeScript
import { useEffect, useRef, useState } from 'react';
|
||
import { Check, FileText, Plus, RefreshCw, ListChecks } from 'lucide-react';
|
||
import { api } from './api';
|
||
import { Modal } from './components';
|
||
import type { RequirementDraft, RequirementItem, RequirementView, Session, TaskPlanStep } from './types';
|
||
import { RequirementDraftEditor, RequirementScopeFields, requirementInput as clean, requirementRoles } from './RequirementDraftEditor';
|
||
import './RequirementPanel.css';
|
||
import { requirementStates as states } from '../shared/contracts/task-follow-up.mjs';
|
||
|
||
const kinds: Record<TaskPlanStep['kind'], string> = { analysis: '研究与读取', changes: '已应用改动', results: '当前文件', checks: '工程检查', browser: '页面断言' };
|
||
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 [proposal, setProposal] = useState<RequirementDraft | null>(null);
|
||
const [notice, setNotice] = useState('');
|
||
const disabled = busy || saving || ['running', 'awaiting_approval', 'stopping'].includes(session.status);
|
||
useEffect(() => { generation.current++; setView(null); setDraft(null); setProposal(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; draft?: RequirementDraft; 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' ? '要求与原文来源已保存。' : action === 'requirement-drafts' ? '草案已整理,尚未成为要求或完成依据。' : '本次复核已记录。');
|
||
if (reply.draft) setProposal(reply.draft);
|
||
if (action === 'requirements') { setDraft(null); setProposal(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'} onClick={() => void mutate('requirement-drafts', { source_set_sha256: view!.source_set_sha256 })}><ListChecks 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 className="requirement-role">{requirementRoles[row.role ?? 'requirement']}{row.method !== 'scope' ? ' · ' + kinds[row.kind] + (row.paths?.length ? ' · ' + row.paths.join('、') : '') : ''}</p>
|
||
<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>}
|
||
{row.method === 'scope' && <p className="record-footnote">{row.role === 'unknown' ? '请先澄清原文的用途或验收范围。' : row.role === 'reference' ? '参考资料不计为需要修改或交付的文件。' : '仅记录禁止事项;是否遵守仍需实际证据,不代表验收通过。'}</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, source_set_sha256: view.source_set_sha256,
|
||
reviewed_source_ids: [...new Set([...view.sources.filter(row => !view.unreviewed_sources?.includes(row.id)).map(row => row.id), ...(source && draft.source.start === 0 && draft.source.end === source.text.length ? [source.id] : [])])] }); }}>
|
||
<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>
|
||
<RequirementScopeFields row={draft} change={setDraft} />
|
||
</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>}
|
||
{proposal && view && <RequirementDraftEditor value={proposal} view={view} saving={saving} close={() => setProposal(null)} submit={input => void mutate('requirements', input)} />}
|
||
</section>;
|
||
}
|