138 lines
14 KiB
TypeScript
138 lines
14 KiB
TypeScript
import { useEffect, useRef, useState } from 'react';
|
||
import { ArrowDownToLine, Check, FileCheck2, FileText, GitCommitHorizontal, LoaderCircle, RefreshCw, ShieldQuestion } from 'lucide-react';
|
||
import { api, downloadArtifact } from './api';
|
||
import { Modal, Status } from './components';
|
||
import type { DeliveryPlan, Session } from './types';
|
||
import './DeliveryPanel.css';
|
||
|
||
const active = ['queued', 'preparing', 'prepared', 'publishing', 'committed', 'reporting'];
|
||
const stageLabel: Record<string, string> = { queued: '正在核对提交基线', preparing: '正在准备已审核文件', prepared: '文件快照已准备', publishing: '正在生成本地提交', committed: '正在核对实际提交', reporting: '正在生成交付报告' };
|
||
const date = (value: string | null) => value ? new Date(value).toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' }) : '执行中';
|
||
|
||
export function DeliveryPanel({ 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;
|
||
const jobs = session.execution?.deliveries ?? [];
|
||
const [message, setMessage] = useState('');
|
||
const [authorName, setAuthorName] = useState('');
|
||
const [authorEmail, setAuthorEmail] = useState('');
|
||
const [planning, setPlanning] = useState(false);
|
||
const [confirm, setConfirm] = useState<DeliveryPlan | null>(null);
|
||
const [submitting, setSubmitting] = useState(false);
|
||
const [reporting, setReporting] = useState(false);
|
||
const [reconciling, setReconciling] = useState('');
|
||
const [downloading, setDownloading] = useState(false);
|
||
const identity = useRef(0);
|
||
const inFlight = useRef(false);
|
||
const running = jobs.some(job => active.includes(job.status));
|
||
const unresolved = jobs.some(job => job.requiresVerification);
|
||
const pending = session.changes.some(change => ['pending', 'conflict'].includes(change.status));
|
||
const hasApplied = session.changes.some(change => change.taskId === task?.id && change.status === 'applied');
|
||
const existingOnly = !hasApplied && !!session.execution?.fileResults?.length;
|
||
const reports = session.execution?.artifacts.filter(artifact => artifact.kind === 'delivery-report-markdown') ?? [];
|
||
const latestReport = reports.at(-1);
|
||
const waitingPlan = (session.execution?.deliveryPlans ?? []).filter(plan => plan.taskId === task?.id
|
||
&& plan.runId === session.execution?.run?.id && ['planned', 'accepted'].includes(plan.status)
|
||
&& (session.execution?.run?.review?.status === 'pending' && session.execution.run.review.planId === plan.id || plan.preparedBy === 'agent' && plan.status === 'planned')).at(-1);
|
||
|
||
useEffect(() => {
|
||
identity.current++; setConfirm(null); setPlanning(false); setSubmitting(false); setReporting(false); setReconciling('');
|
||
setMessage(task ? '完成:' + task.goal.replace(/\s+/g, ' ').slice(0, 90) : ''); setAuthorName(''); setAuthorEmail('');
|
||
inFlight.current = false;
|
||
return () => { identity.current++; };
|
||
}, [session.id, task?.id]);
|
||
|
||
async function prepare() {
|
||
if (inFlight.current) return;
|
||
inFlight.current = true; setPlanning(true); const request = identity.current;
|
||
try {
|
||
const result = await api<Session>('/sessions/' + session.id + '/delivery-plans', { message, ...(authorName.trim() ? { authorName: authorName.trim() } : {}), ...(authorEmail.trim() ? { authorEmail: authorEmail.trim() } : {}) });
|
||
if (request !== identity.current) return;
|
||
onSession(result); setConfirm(result.execution?.deliveryPlans?.at(-1) ?? null);
|
||
} catch (error) { if (request === identity.current) onError(error); }
|
||
finally { if (request === identity.current) { inFlight.current = false; setPlanning(false); } }
|
||
}
|
||
async function commit() {
|
||
if (!confirm || inFlight.current) return;
|
||
inFlight.current = true; setSubmitting(true); const request = identity.current;
|
||
try {
|
||
const result = await api<Session>('/sessions/' + session.id + '/delivery-jobs', { planId: confirm.id });
|
||
if (request === identity.current) { onSession(result); setConfirm(null); }
|
||
} catch (error) { if (request === identity.current) onError(error); }
|
||
finally { if (request === identity.current) { inFlight.current = false; setSubmitting(false); } }
|
||
}
|
||
async function discard() {
|
||
if (!waitingPlan || inFlight.current) return;
|
||
inFlight.current = true; setSubmitting(true); const request = identity.current;
|
||
try {
|
||
const result = await api<Session>('/sessions/' + session.id + '/delivery-plans/' + waitingPlan.id + '/discard', {});
|
||
if (request === identity.current) { onSession(result); setConfirm(null); }
|
||
} catch (error) { if (request === identity.current) onError(error); }
|
||
finally { if (request === identity.current) { inFlight.current = false; setSubmitting(false); } }
|
||
}
|
||
async function report() {
|
||
if (inFlight.current) return;
|
||
inFlight.current = true; setReporting(true); const request = identity.current;
|
||
try {
|
||
const result = await api<Session>('/sessions/' + session.id + '/delivery-reports', {});
|
||
if (request !== identity.current) return;
|
||
onSession(result);
|
||
const artifact = result.execution?.artifacts.filter(value => value.kind === 'delivery-report-markdown').at(-1);
|
||
if (artifact) openArtifact(artifact.id);
|
||
} catch (error) { if (request === identity.current) onError(error); }
|
||
finally { if (request === identity.current) { inFlight.current = false; setReporting(false); } }
|
||
}
|
||
async function reconcile(jobId: string) {
|
||
if (inFlight.current) return;
|
||
inFlight.current = true; setReconciling(jobId); const request = identity.current;
|
||
try {
|
||
const result = await api<Session>('/sessions/' + session.id + '/delivery-jobs/' + jobId + '/reconcile', {});
|
||
if (request === identity.current) onSession(result);
|
||
} catch (error) { if (request === identity.current) onError(error); }
|
||
finally { if (request === identity.current) { inFlight.current = false; setReconciling(''); } }
|
||
}
|
||
async function download(id: string, extension: string) {
|
||
setDownloading(true);
|
||
try { await downloadArtifact(session.id, id, 'Agent-Workbench-delivery-' + (task?.id.slice(0, 8) ?? session.id.slice(0, 8)) + extension); }
|
||
catch (error) { onError(error); } finally { setDownloading(false); }
|
||
}
|
||
|
||
return <section className="task-record-section git-delivery" aria-label="Git交付">
|
||
<div className="record-heading"><GitCommitHorizontal size={16} /><h3>审核提交与交付</h3></div>
|
||
<p className="record-footnote">核对当前任务已应用的文件和实际测试,预览后生成本地提交。其他项目改动保留。</p>
|
||
<div className="delivery-route" aria-label="交付步骤"><span className={hasApplied && !pending ? 'done' : ''}>文件已审查</span><i>→</i><span className={task?.verification.status === 'passed' ? 'done' : ''}>实际检查</span><i>→</i><span className={jobs.some(job => job.status === 'completed') ? 'done' : ''}>本地提交</span></div>
|
||
{waitingPlan && <div className="delivery-attention delivery-review-boundary" aria-label="等待Git确认"><strong>Git预览已保存,等待确认</strong><p>{waitingPlan.paths.length} 个文件 · {waitingPlan.baseline.branch} · HEAD {waitingPlan.baseline.head.slice(0, 12)}</p><p>任务已暂停请求模型。审查现有预览后确认提交,或撤回预览再继续。</p><div className="delivery-report-actions"><button type="button" className="button primary" disabled={busy || running || submitting || waitingPlan.status !== 'planned'} onClick={() => setConfirm(waitingPlan)}>查看待确认预览</button><button type="button" className="button secondary" disabled={busy || running || unresolved || submitting} onClick={discard}>撤回预览</button></div>{waitingPlan.status === 'accepted' && <p>这份预览已尝试执行;请核对原结果,确认未提交后重新预览。</p>}</div>}
|
||
<label className="form-field delivery-message">提交说明<textarea aria-label="提交说明" rows={2} value={message} maxLength={1600} disabled={busy || running} onChange={event => setMessage(event.target.value)} /></label>
|
||
<details className="delivery-author"><summary>Git署名</summary><p>默认采用项目Git署名;尚未配置时使用 Agent Workbench 本地身份。预览会展示实际署名。</p><label className="form-field">提交者姓名<input value={authorName} disabled={busy || running} onChange={event => setAuthorName(event.target.value)} placeholder="采用默认署名" autoComplete="off" /></label><label className="form-field">提交者邮箱<input type="email" value={authorEmail} disabled={busy || running} onChange={event => setAuthorEmail(event.target.value)} placeholder="采用默认邮箱" autoComplete="off" /></label></details>
|
||
<button type="button" className="button primary" aria-label="预览Git提交" disabled={!task || !hasApplied || pending || busy || running || unresolved || planning || !message.trim()} onClick={prepare}>{planning ? <LoaderCircle size={14} className="spin" /> : <GitCommitHorizontal size={14} />}预览Git提交</button>
|
||
{existingOnly ? <p className="record-footnote">本任务沿用已有成果,无新增修改,不创建空提交。可生成报告核对成果与原检查。</p> : (!hasApplied || pending) && <p className="record-footnote">应用本任务的文件提案后,可以准备Git提交。</p>}
|
||
{jobs.slice().reverse().map(job => <div key={job.id} className={'delivery-job ' + (job.requiresVerification ? 'delivery-attention' : '')}>
|
||
<div className="record-heading"><Status value={job.status} /><code>{job.id.slice(0, 8)}</code>{active.includes(job.status) && <button type="button" className="text-button" onClick={() => api<Session>('/sessions/' + session.id + '/delivery-jobs/' + job.id + '/stop', {}).then(onSession).catch(onError)}>停止提交</button>}</div>
|
||
<time>{date(job.startedAt)} · {job.branch}</time>
|
||
{active.includes(job.status) && <p className="delivery-current"><LoaderCircle size={13} className="spin" />{stageLabel[job.status]}</p>}
|
||
{job.commit && <div className="delivery-commit"><GitCommitHorizontal size={14} /><code title={job.commit}>{job.commit}</code></div>}
|
||
<ul className="delivery-paths">{job.paths.map(relative => <li key={relative}>{relative}</li>)}</ul>
|
||
{job.summary && <p>{job.summary}</p>}
|
||
{job.requiresVerification && <><p className="delivery-warning"><ShieldQuestion size={14} />先核对实际提交;本次不会再次提交文件。匹配本次遗留索引锁时会完成索引恢复。</p><button type="button" className="button secondary" disabled={busy || !!reconciling} onClick={() => reconcile(job.id)}>{reconciling === job.id ? <LoaderCircle size={14} className="spin" /> : <RefreshCw size={14} />}核对提交结果</button></>}
|
||
{job.status === 'completed' && <p className="delivery-preserved"><FileCheck2 size={13} />实际提交已核对 · 无关修改已保留</p>}
|
||
{job.reportError && <p className="delivery-warning">提交已保存;报告生成失败,可以再次生成报告。</p>}
|
||
{job.reportMarkdownArtifactId && <div className="delivery-report-actions"><button type="button" className="text-button" onClick={() => openArtifact(job.reportMarkdownArtifactId!)}><FileText size={13} />查看交付报告</button><button type="button" className="text-button" disabled={downloading} onClick={() => download(job.reportMarkdownArtifactId!, '.md')}><ArrowDownToLine size={13} />下载Markdown</button>{job.reportArtifactId && <button type="button" className="text-button" disabled={downloading} onClick={() => download(job.reportArtifactId!, '.json')}>下载JSON</button>}</div>}
|
||
</div>)}
|
||
<div className="delivery-report-summary"><button type="button" className="button secondary" disabled={!task || busy || running || reporting || planning} onClick={report}>{reporting ? <LoaderCircle size={14} className="spin" /> : <FileText size={14} />}生成交付报告</button>
|
||
{latestReport && <button type="button" className="text-button" onClick={() => openArtifact(latestReport.id)}>查看最新报告</button>}
|
||
<p className="record-footnote">报告记录实际源码、检查、提交和模型用量,注明尚待确认的结果。</p>
|
||
</div>
|
||
{confirm && <Modal title="确认本地Git提交" description="核对以下文件、实际检查和提交署名后确认。" wide onClose={() => { if (!submitting) setConfirm(null); }}>
|
||
<div className="delivery-confirm">
|
||
<div className="delivery-confirm-overview"><strong>{confirm.paths.length} 个文件 · {confirm.baseline.branch}</strong><span>Task {confirm.taskId.slice(0, 8)} · HEAD {confirm.baseline.head.slice(0, 12)}</span></div>
|
||
<dl className="record-fields"><dt>提交说明</dt><dd className="delivery-confirm-message">{confirm.message}</dd><dt>实际署名</dt><dd>{confirm.author.name} <{confirm.author.email}>{confirm.author.source === 'workbench-local' && <small> · 工作台本地默认身份</small>}</dd><dt>源文件指纹</dt><dd><code>{confirm.sourceFingerprint}</code></dd><dt>检查记录</dt><dd><code>{confirm.checkJobId}</code></dd></dl>
|
||
<ul className="delivery-checks">{confirm.checkSummary.map(check => <li key={check.name}><Check size={13} /><strong>{check.command}</strong><span>退出码 {check.exitCode}{check.tests ? ' · ' + check.tests.passed + '/' + check.tests.total + ' 测试通过' : ''}</span></li>)}</ul>
|
||
<p className="delivery-policy">{confirm.policy.note}</p>
|
||
<div className="delivery-diffs">{confirm.files.map(file => <details key={file.path} open={confirm.files.length === 1}><summary><span>{file.path}</span><small>+{file.additions} / −{file.deletions}</small></summary><p>{file.reason}</p><pre aria-label={'提交差异 ' + file.path}>{file.diff}</pre><code className="delivery-file-hash">SHA256 {file.sha256}</code></details>)}</div>
|
||
</div>
|
||
<div className="modal-actions"><button type="button" className="button secondary" disabled={submitting} onClick={() => setConfirm(null)}>返回修改</button><button type="button" className="button primary" aria-label="确认创建本地提交" disabled={submitting} onClick={commit}>{submitting ? <LoaderCircle size={14} className="spin" /> : <Check size={14} />}确认创建本地提交</button></div>
|
||
</Modal>}
|
||
</section>;
|
||
}
|