feat(web): Scope B B1 — 多章工作流链前端 UI(发起/轮询/裁决续跑)

链页 app/projects/[id]/chains(RSC fetchProject)+ ChainPage/ChainStarter/
ChainProgress/ChainAdjudication;lib/chain 纯函数(result 收窄/相位映射/resume 组装)。
复用 useJobPoll 轮询、ConflictCard + decisions.ts 裁决、normalizeConflicts/latestReview、
friendlyError;nav 加 chains 入口。awaiting(interrupt)→ 读该章冲突渲 ConflictCard →
POST .../chains/runs/{job_id}/resume 续跑。gen:api 纳入 chains run/resume。
守 #5(链暂停=等裁决,token/正文不入 job result)。
This commit is contained in:
Yaojia Wang
2026-06-23 19:21:00 +02:00
parent 416caed56b
commit a2dcd89881
11 changed files with 874 additions and 4 deletions

View File

@@ -0,0 +1,176 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { ConflictCard } from "@/components/review/ConflictCard";
import { useToast } from "@/components/Toast";
import { api } from "@/lib/api/client";
import { buildResumeRequest } from "@/lib/chain/chain";
import { friendlyError } from "@/lib/errors/messages";
import type { ReviewConflict } from "@/lib/review/sse";
import {
allResolved,
emptyDecisions,
setNote,
setVerdict,
unresolvedIndices,
type DecisionDraft,
type Verdict,
} from "@/lib/review/decisions";
import { latestReview, normalizeConflicts } from "@/lib/review/history";
interface ChainAdjudicationProps {
projectId: string;
jobId: string;
// interrupt 命中的章号(读其最近审稿冲突供裁决)。
chapterNo: number;
// 续跑发起后回调(父层重启轮询)。
onResumed: () => void;
}
type LoadState = "loading" | "ready" | "error";
// 链裁决面板(净新但复用满):读 awaiting 章最近审稿 → 渲 ConflictCard每冲突一张复用审稿页
// 组件 + decisions.ts 纯逻辑)→ 全决后 POST resumebuildResumeRequest 复用 accept 裁决组装)。
// 链无在手草稿正文 → 无段内定位snippet=null/locatable=false裁决纯靠 suggestion + 补丁对。
export function ChainAdjudication({
projectId,
jobId,
chapterNo,
onResumed,
}: ChainAdjudicationProps) {
const toast = useToast();
const [loadState, setLoadState] = useState<LoadState>("loading");
const [conflicts, setConflicts] = useState<ReviewConflict[]>([]);
const [drafts, setDrafts] = useState<DecisionDraft[]>([]);
const [resuming, setResuming] = useState(false);
useEffect(() => {
let active = true;
setLoadState("loading");
void (async () => {
try {
const { data, error } = await api.GET(
"/projects/{project_id}/chapters/{chapter_no}/reviews",
{
params: {
path: { project_id: projectId, chapter_no: chapterNo },
},
},
);
if (!active) return;
if (error || !data) {
setLoadState("error");
return;
}
const next = normalizeConflicts(latestReview(data.reviews));
setConflicts(next);
setDrafts(emptyDecisions(next.length));
setLoadState("ready");
} catch {
if (active) setLoadState("error");
}
})();
return () => {
active = false;
};
}, [projectId, chapterNo]);
const onVerdict = useCallback((index: number, verdict: Verdict): void => {
setDrafts((prev) => setVerdict(prev, index, verdict));
}, []);
const onNote = useCallback((index: number, note: string): void => {
setDrafts((prev) => setNote(prev, index, note));
}, []);
const onResume = useCallback(async (): Promise<void> => {
if (!allResolved(drafts)) {
toast("仍有未裁决的冲突,请先逐条裁决。", "error");
return;
}
setResuming(true);
try {
const { error } = await api.POST(
"/projects/{project_id}/chains/runs/{job_id}/resume",
{
params: { path: { project_id: projectId, job_id: jobId } },
body: buildResumeRequest(drafts),
},
);
if (error) {
toast(friendlyError(undefined).text, "error");
setResuming(false);
return;
}
onResumed();
} catch {
toast("续跑请求异常,请检查网络。", "error");
setResuming(false);
}
}, [drafts, projectId, jobId, onResumed, toast]);
if (loadState === "loading") {
return <p className="text-sm text-ink-soft"> {chapterNo} </p>;
}
if (loadState === "error") {
return (
<p className="text-sm text-conflict">
{chapterNo} 稿
</p>
);
}
const pending = unresolvedIndices(drafts);
return (
<section
className="flex flex-col gap-3 rounded border border-line bg-panel p-5"
aria-label={`${chapterNo} 章冲突裁决`}
>
<h2 className="font-serif text-lg text-ink">
{chapterNo} {conflicts.length}
</h2>
{conflicts.length === 0 ? (
<p className="text-sm text-ink-soft">
</p>
) : (
<ul className="flex flex-col gap-3">
{conflicts.map((conflict, i) => {
const draft = drafts[i] ?? { verdict: null, note: "" };
return (
<ConflictCard
key={i}
index={i}
conflict={conflict}
draft={draft}
missing={false}
snippet={null}
locatable={false}
rewriting={false}
onVerdict={onVerdict}
onNote={onNote}
onJump={() => {}}
/>
);
})}
</ul>
)}
<button
type="button"
onClick={() => void onResume()}
disabled={resuming || !allResolved(drafts)}
className="self-start rounded bg-cinnabar px-4 py-2 text-sm text-white disabled:opacity-50"
>
{resuming ? "续跑中…" : "裁决完成,续跑"}
</button>
{pending.length > 0 ? (
<p className="text-xs text-conflict">
{pending.length}
</p>
) : null}
</section>
);
}

View File

@@ -0,0 +1,119 @@
"use client";
import { useCallback, useEffect, useMemo, useState } from "react";
import { AppShell } from "@/components/AppShell";
import { useToast } from "@/components/Toast";
import { api } from "@/lib/api/client";
import { chainPhase, chainResultView } from "@/lib/chain/chain";
import { friendlyError } from "@/lib/errors/messages";
import { useJobPoll } from "@/lib/jobs/useJobPoll";
import type { ProjectResponse } from "@/lib/api/types";
import { ChainAdjudication } from "./ChainAdjudication";
import { ChainProgress } from "./ChainProgress";
import { ChainStarter } from "./ChainStarter";
interface ChainPageProps {
project: ProjectResponse;
}
const CHAIN_KEY = "draft_volume";
// 多章工作流链页Scope B B1发起链(POST run)→job 轮询进度→interrupt 命中则读该章冲突裁决→
// POST resume 续跑。复用 useJobPoll轮询+ ConflictCard/decisions裁决+ friendlyError文案
// 链是后台任务,走 job 轮询而非 SSE。awaiting 时停轮询(后端把 job 置 awaiting_input
// narrowJob 抹平成 queued 会无限轮询)→ 裁决面板 resume 后再重启轮询同一 job。
export function ChainPage({ project }: ChainPageProps) {
const poll = useJobPoll();
const toast = useToast();
const [jobId, setJobId] = useState<string | null>(null);
const [starting, setStarting] = useState(false);
const job = poll.job;
const result = useMemo(
() => (job ? chainResultView(job) : null),
[job],
);
const awaitingChapter = result?.awaitingChapter ?? null;
const phase = chainPhase(poll.status, awaitingChapter);
// awaiting 命中:停轮询(后端 job=awaiting_input 被 narrowJob 抹成 queued 会空转)。
useEffect(() => {
if (phase === "awaiting") poll.reset();
}, [phase, poll]);
const onStart = useCallback(
async (startChapterNo: number, count: number): Promise<void> => {
setStarting(true);
try {
const { data, error } = await api.POST(
"/projects/{project_id}/chains/{chain_key}/run",
{
params: {
path: { project_id: project.id, chain_key: CHAIN_KEY },
},
body: { start_chapter_no: startChapterNo, count },
},
);
if (error || !data) {
toast(friendlyError(undefined).text, "error");
return;
}
setJobId(data.job_id);
poll.poll(data.job_id);
} catch {
toast("发起链请求异常,请检查网络。", "error");
} finally {
setStarting(false);
}
},
[project.id, poll, toast],
);
// 续跑成功:重启轮询同一 jobresume 已 202图从检查点续
const onResumed = useCallback((): void => {
if (jobId) poll.poll(jobId);
}, [jobId, poll]);
const showProgress = jobId !== null && result !== null;
// 链运行中/等待裁决时禁止重复发起。
const busy = starting || (jobId !== null && phase === "running");
return (
<AppShell
title={project.title}
subtitle="多章工作流链"
projectId={project.id}
activeNav="chains"
>
<div className="mx-auto flex w-full max-w-3xl flex-col gap-6 p-6">
<ChainStarter onStart={(s, c) => void onStart(s, c)} disabled={busy} />
{showProgress && result ? (
<ChainProgress phase={phase} progress={poll.progress} result={result} />
) : null}
{phase === "awaiting" &&
awaitingChapter !== null &&
jobId !== null ? (
<ChainAdjudication
projectId={project.id}
jobId={jobId}
chapterNo={awaitingChapter}
onResumed={onResumed}
/>
) : null}
{phase === "failed" ? (
<p className="text-sm text-conflict">
{poll.error ?? "链运行失败,请重试。"}
</p>
) : null}
{phase === "completed" ? (
<p className="text-sm text-pass"></p>
) : null}
</div>
</AppShell>
);
}

View File

@@ -0,0 +1,63 @@
"use client";
import type { ChainPhase, ChainResultView } from "@/lib/chain/chain";
interface ChainProgressProps {
phase: ChainPhase;
progress: number;
result: ChainResultView;
}
const PHASE_LABEL: Record<ChainPhase, string> = {
running: "运行中",
awaiting: "等待裁决",
completed: "已完成",
failed: "已失败",
};
// 链进度视图:相位徽标 + 进度条 + 已写章号清单token/正文绝不展示result 只含元数据)。
export function ChainProgress({ phase, progress, result }: ChainProgressProps) {
return (
<section
className="flex flex-col gap-3 rounded border border-line bg-panel p-5"
aria-label="链进度"
>
<div className="flex items-center justify-between gap-3">
<h2 className="font-serif text-lg text-ink"></h2>
<span
className="rounded bg-cinnabar/10 px-2 py-0.5 text-xs text-cinnabar"
aria-live="polite"
>
{PHASE_LABEL[phase]}
</span>
</div>
<div
className="h-2 w-full overflow-hidden rounded bg-bg"
role="progressbar"
aria-valuenow={progress}
aria-valuemin={0}
aria-valuemax={100}
>
<div
className="h-full bg-cinnabar transition-all"
style={{ width: `${progress}%` }}
/>
</div>
<p className="text-sm text-ink-soft">
{result.written.length}
{result.written.length > 0 ? (
<span className="ml-1 font-mono text-ink">
{result.written.join("、")}
</span>
) : null}
</p>
{phase === "awaiting" && result.awaitingChapter !== null ? (
<p className="text-sm text-conflict">
{result.awaitingChapter}
</p>
) : null}
</section>
);
}

View File

@@ -0,0 +1,80 @@
"use client";
import { useState } from "react";
interface ChainStarterProps {
// 发起一条链(起始章 + 章数);父层负责 POST run + 轮询。
onStart: (startChapterNo: number, count: number) => void;
// 链正在运行/等待裁决时禁用(避免重复发起)。
disabled: boolean;
}
const DEFAULT_START = 1;
const DEFAULT_COUNT = 3;
const MAX_COUNT = 50;
// 链发起表单(净新):选起始章号 + 连续写几章 → 调 onStart。
// count 1..50(对齐后端 ChainRunRequest Field 约束;前端先拦一道,越界后端 422 兜底)。
export function ChainStarter({ onStart, disabled }: ChainStarterProps) {
const [start, setStart] = useState(String(DEFAULT_START));
const [count, setCount] = useState(String(DEFAULT_COUNT));
const startNo = Number.parseInt(start, 10);
const countNo = Number.parseInt(count, 10);
const valid =
Number.isInteger(startNo) &&
startNo >= 1 &&
Number.isInteger(countNo) &&
countNo >= 1 &&
countNo <= MAX_COUNT;
return (
<form
className="flex flex-col gap-4 rounded border border-line bg-panel p-5"
aria-label="发起多章链"
onSubmit={(e) => {
e.preventDefault();
if (valid && !disabled) onStart(startNo, countNo);
}}
>
<div>
<h2 className="font-serif text-lg text-ink"></h2>
<p className="mt-1 text-sm text-ink-soft">
</p>
</div>
<div className="flex flex-wrap gap-4">
<label className="block text-sm text-ink-soft">
<input
type="number"
min={1}
value={start}
onChange={(e) => setStart(e.target.value)}
className="mt-1 w-32 rounded border border-line bg-bg px-3 py-2 text-sm text-ink"
aria-label="起始章号"
/>
</label>
<label className="block text-sm text-ink-soft">
1..{MAX_COUNT}
<input
type="number"
min={1}
max={MAX_COUNT}
value={count}
onChange={(e) => setCount(e.target.value)}
className="mt-1 w-32 rounded border border-line bg-bg px-3 py-2 text-sm text-ink"
aria-label="连续章数"
/>
</label>
</div>
<button
type="submit"
disabled={disabled || !valid}
className="self-start rounded bg-cinnabar px-4 py-2 text-sm text-white disabled:opacity-50"
>
{disabled ? "运行中…" : "发起多章链"}
</button>
</form>
);
}