feat(web): F1/F2/F3 前端——拆书入库为规则 / 续写式链选择 / 模板库

- gen:api 纳入 /templates、chain continue_volume、teardown rules ingest 端点
- F1:GeneratorRunner 识别拆书为单对象入库(整 preview 作一条 teardown),
  ingestTable(BookTeardownResult)=rules,buildIngestRequest 组装 teardown 体,
  按 isSingleObjectIngest 隐藏勾选框、改文案「入库为规则」
- F2:ChainStarter 加链类型单选(draft_volume 从头写 / continue_volume 续写),
  chain_key 作 path 参传给 run(CHAIN_KINDS 对齐后端 SUPPORTED_CHAINS)
- F3:模板库页 app/templates + 全局 nav 入口 + TemplatesManager(列/建/删,乐观更新回滚);
  GeneratorRunner 加 TemplateFiller「从模板填入」(body 填进 brief/text,纯前端)
- vitest 覆盖 templates/ingest teardown/templateFillTarget/CHAIN_KINDS 纯逻辑
This commit is contained in:
Yaojia Wang
2026-06-23 20:29:48 +02:00
parent 5d8e619408
commit 1a402f5ccc
18 changed files with 869 additions and 19 deletions

View File

@@ -5,7 +5,7 @@ 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 { chainPhase, chainResultView, type ChainKind } from "@/lib/chain/chain";
import { friendlyError } from "@/lib/errors/messages";
import { useJobPoll } from "@/lib/jobs/useJobPoll";
import type { ProjectResponse } from "@/lib/api/types";
@@ -17,8 +17,6 @@ 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
@@ -43,14 +41,18 @@ export function ChainPage({ project }: ChainPageProps) {
}, [phase, poll]);
const onStart = useCallback(
async (startChapterNo: number, count: number): Promise<void> => {
async (
chainKey: ChainKind,
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 },
path: { project_id: project.id, chain_key: chainKey },
},
body: { start_chapter_no: startChapterNo, count },
},
@@ -89,7 +91,10 @@ export function ChainPage({ project }: ChainPageProps) {
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} />
<ChainStarter
onStart={(k, s, c) => void onStart(k, s, c)}
disabled={busy}
/>
{showProgress && result ? (
<ChainProgress phase={phase} progress={poll.progress} result={result} />

View File

@@ -2,9 +2,11 @@
import { useState } from "react";
import { CHAIN_KINDS, type ChainKind } from "@/lib/chain/chain";
interface ChainStarterProps {
// 发起一条链(起始章 + 章数);父层负责 POST run + 轮询。
onStart: (startChapterNo: number, count: number) => void;
// 发起一条链(链类型 + 起始章 + 章数);父层负责 POST run + 轮询。
onStart: (chainKey: ChainKind, startChapterNo: number, count: number) => void;
// 链正在运行/等待裁决时禁用(避免重复发起)。
disabled: boolean;
}
@@ -12,10 +14,12 @@ interface ChainStarterProps {
const DEFAULT_START = 1;
const DEFAULT_COUNT = 3;
const MAX_COUNT = 50;
const DEFAULT_CHAIN: ChainKind = "draft_volume";
// 链发起表单(净新):选起始章号 + 连续写几章 → 调 onStart。
// count 1..50(对齐后端 ChainRunRequest Field 约束;前端先拦一道,越界后端 422 兜底)。
export function ChainStarter({ onStart, disabled }: ChainStarterProps) {
const [chainKey, setChainKey] = useState<ChainKind>(DEFAULT_CHAIN);
const [start, setStart] = useState(String(DEFAULT_START));
const [count, setCount] = useState(String(DEFAULT_COUNT));
@@ -34,7 +38,7 @@ export function ChainStarter({ onStart, disabled }: ChainStarterProps) {
aria-label="发起多章链"
onSubmit={(e) => {
e.preventDefault();
if (valid && !disabled) onStart(startNo, countNo);
if (valid && !disabled) onStart(chainKey, startNo, countNo);
}}
>
<div>
@@ -43,6 +47,33 @@ export function ChainStarter({ onStart, disabled }: ChainStarterProps) {
</p>
</div>
<fieldset className="flex flex-col gap-2">
<legend className="text-sm text-ink-soft"></legend>
<div className="flex flex-wrap gap-4">
{CHAIN_KINDS.map((kind) => (
<label
key={kind.key}
className="flex items-start gap-2 text-sm text-ink"
>
<input
type="radio"
name="chain-kind"
value={kind.key}
checked={chainKey === kind.key}
onChange={() => setChainKey(kind.key)}
className="mt-1"
aria-label={kind.label}
/>
<span>
<span className="block">{kind.label}</span>
<span className="block text-xs text-ink-soft">
{kind.description}
</span>
</span>
</label>
))}
</div>
</fieldset>
<div className="flex flex-wrap gap-4">
<label className="block text-sm text-ink-soft">

View File

@@ -0,0 +1,181 @@
"use client";
import { useCallback, useState } from "react";
import { useToast } from "@/components/Toast";
import { api } from "@/lib/api/client";
import type { TemplateResponse } from "@/lib/api/types";
import {
buildTemplateCreateRequest,
EMPTY_TEMPLATE_DRAFT,
isTemplateDraftValid,
type TemplateDraft,
} from "@/lib/templates/templates";
interface TemplatesManagerProps {
// 初始模板列表Server Component 预取;失败给空数组 + loadError 文案)。
initial: TemplateResponse[];
}
// 提示词/模板库管理F3单用户本地版列出 / 新建 / 删除。
// 列表本地维护乐观更新失败回滚CRUD 走 OpenAPI 客户端。分享/市场不做(需多租户)。
export function TemplatesManager({ initial }: TemplatesManagerProps) {
const toast = useToast();
const [templates, setTemplates] = useState<TemplateResponse[]>(initial);
const [draft, setDraft] = useState<TemplateDraft>(EMPTY_TEMPLATE_DRAFT);
const [creating, setCreating] = useState(false);
const setField = useCallback(
(field: keyof TemplateDraft, value: string): void => {
setDraft((prev) => ({ ...prev, [field]: value }));
},
[],
);
const onCreate = useCallback(async (): Promise<void> => {
if (!isTemplateDraftValid(draft)) {
toast("请填写标题与正文。", "error");
return;
}
setCreating(true);
try {
const { data, error } = await api.POST("/templates", {
body: buildTemplateCreateRequest(draft),
});
if (error || !data) {
toast("新建模板失败,请重试。", "error");
return;
}
setTemplates((prev) => [data, ...prev]);
setDraft(EMPTY_TEMPLATE_DRAFT);
toast("已新建模板。", "success");
} catch {
toast("新建模板请求异常,请检查网络。", "error");
} finally {
setCreating(false);
}
}, [draft, toast]);
const onDelete = useCallback(
async (id: string): Promise<void> => {
const prev = templates;
// 乐观删除:先移除,失败回滚。
setTemplates((cur) => cur.filter((t) => t.id !== id));
try {
const { error } = await api.DELETE("/templates/{template_id}", {
params: { path: { template_id: id } },
});
if (error) {
setTemplates(prev);
toast("删除模板失败,请重试。", "error");
return;
}
toast("已删除模板。", "success");
} catch {
setTemplates(prev);
toast("删除模板请求异常,请检查网络。", "error");
}
},
[templates, toast],
);
return (
<div className="flex flex-col gap-6">
<form
className="flex flex-col gap-3 rounded border border-line bg-panel p-5"
aria-label="新建模板"
onSubmit={(e) => {
e.preventDefault();
void onCreate();
}}
>
<h2 className="font-serif text-lg text-ink"></h2>
<label className="block text-sm text-ink-soft">
*
<input
type="text"
value={draft.title}
onChange={(e) => setField("title", e.target.value)}
className="mt-1 w-full 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">
* brief/
<textarea
value={draft.body}
onChange={(e) => setField("body", e.target.value)}
rows={4}
className="mt-1 w-full resize-y rounded border border-line bg-bg px-3 py-2 text-sm text-ink"
aria-label="正文"
/>
</label>
<div className="flex flex-wrap gap-4">
<label className="block text-sm text-ink-soft">
<input
type="text"
value={draft.category}
onChange={(e) => setField("category", e.target.value)}
className="mt-1 w-48 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">
key
<input
type="text"
value={draft.toolKey}
onChange={(e) => setField("toolKey", e.target.value)}
className="mt-1 w-48 rounded border border-line bg-bg px-3 py-2 text-sm text-ink"
aria-label="关联生成器 key"
/>
</label>
</div>
<button
type="submit"
disabled={creating || !isTemplateDraftValid(draft)}
className="self-start rounded bg-cinnabar px-4 py-2 text-sm text-white disabled:opacity-50"
>
{creating ? "新建中…" : "新建模板"}
</button>
</form>
<section className="flex flex-col gap-3" aria-label="模板列表">
<h2 className="font-serif text-lg text-ink">{templates.length}</h2>
{templates.length === 0 ? (
<p className="text-sm text-ink-soft"></p>
) : (
<ul className="flex flex-col gap-2">
{templates.map((t) => (
<li
key={t.id}
className="flex items-start justify-between gap-4 rounded border border-line bg-bg p-3 text-sm"
>
<div className="min-w-0 flex-1">
<p className="font-serif text-base text-ink">{t.title}</p>
{t.category || t.tool_key ? (
<p className="text-xs text-ink-soft">
{[t.category, t.tool_key].filter(Boolean).join(" · ")}
</p>
) : null}
<p className="mt-1 whitespace-pre-wrap text-ink-soft">
{t.body}
</p>
</div>
<button
type="button"
onClick={() => void onDelete(t.id)}
className="shrink-0 rounded border border-line px-3 py-1 text-ink-soft hover:text-conflict"
aria-label={`删除模板 ${t.title}`}
>
</button>
</li>
))}
</ul>
)}
</section>
</div>
);
}

View File

@@ -10,11 +10,13 @@ import {
initialFieldValues,
missingRequiredFields,
previewRows,
templateFillTarget,
type FieldValues,
type PreviewItem,
} from "@/lib/toolbox/toolbox";
import { ingestTable } from "@/lib/toolbox/ingest";
import { ingestTable, isSingleObjectIngest } from "@/lib/toolbox/ingest";
import { useGenerator } from "@/lib/toolbox/useGenerator";
import { TemplateFiller } from "./TemplateFiller";
interface GeneratorRunnerProps {
projectId: string;
@@ -42,6 +44,12 @@ export function GeneratorRunner({
setValues((prev) => ({ ...prev, [name]: value }));
}, []);
// 「从模板填入」的目标字段brief / text无则不渲染
const fillTarget = useMemo(
() => templateFillTarget(tool.input_fields),
[tool.input_fields],
);
const onGenerate = useCallback(async (): Promise<void> => {
const missing = missingRequiredFields(tool.input_fields, values);
if (missing.length > 0) {
@@ -58,7 +66,15 @@ export function GeneratorRunner({
);
const table = gen.outputKind ? ingestTable(gen.outputKind) : null;
const canIngest = tool.ingestable && table !== null && rows.length > 0;
// 单对象产物(如拆书):整个 preview 即一条入库项,无逐行勾选;行式产物按勾选入库。
const singleObject = gen.outputKind
? isSingleObjectIngest(gen.outputKind)
: false;
const hasPreview = (gen.preview?.items.length ?? 0) > 0;
const canIngest =
tool.ingestable &&
table !== null &&
(singleObject ? hasPreview : rows.length > 0);
const toggle = useCallback((idx: number): void => {
setSelected((prev) => {
@@ -81,14 +97,17 @@ export function GeneratorRunner({
async (acknowledge: boolean): Promise<void> => {
if (!gen.outputKind) return;
const chapterNo = Number(values["chapter_no"]?.trim() || "") || null;
// 单对象产物(拆书):整个 rawPreview 作唯一入库行;行式产物用勾选行。
const ingestRows =
singleObject && gen.rawPreview ? [gen.rawPreview] : selectedRows;
await gen.ingest(projectId, tool.key, {
outputKind: gen.outputKind,
rows: selectedRows,
rows: ingestRows,
chapterNo,
acknowledgeConflicts: acknowledge,
});
},
[gen, projectId, tool.key, selectedRows, values],
[gen, projectId, tool.key, selectedRows, values, singleObject],
);
const generating = gen.genStatus === "generating";
@@ -120,6 +139,7 @@ export function GeneratorRunner({
void onGenerate();
}}
>
<TemplateFiller targetField={fillTarget} onFill={setField} />
{(tool.input_fields ?? []).map((field) => (
<FormField
key={field.name}
@@ -141,7 +161,11 @@ export function GeneratorRunner({
<div className="flex flex-col gap-3">
<h3 className="font-serif text-sm text-ink">
{gen.preview.items.length}
{canIngest ? "(勾选后可入库)" : null}
{canIngest
? singleObject
? "(可入库)"
: "(勾选后可入库)"
: null}
</h3>
<ul className="flex flex-col gap-2">
{gen.preview.items.map((item, i) => (
@@ -149,7 +173,7 @@ export function GeneratorRunner({
key={i}
item={item}
index={i}
selectable={canIngest}
selectable={canIngest && !singleObject}
checked={selected.has(i)}
onToggle={toggle}
/>
@@ -160,10 +184,14 @@ export function GeneratorRunner({
<button
type="button"
onClick={() => void runIngest(false)}
disabled={ingesting || selected.size === 0}
disabled={ingesting || (!singleObject && selected.size === 0)}
className="self-start rounded border border-cinnabar px-4 py-2 text-sm text-cinnabar disabled:opacity-50"
>
{ingesting ? "入库中…" : `入库选中(${selected.size})至 ${table}`}
{ingesting
? "入库中…"
: singleObject
? `入库为规则至 ${table}`
: `入库选中(${selected.size})至 ${table}`}
</button>
) : null}

View File

@@ -0,0 +1,102 @@
"use client";
import { useCallback, useEffect, useState } from "react";
import { useToast } from "@/components/Toast";
import { api } from "@/lib/api/client";
import type { TemplateResponse } from "@/lib/api/types";
interface TemplateFillerProps {
// 可填入的目标输入字段名(如 brief / text空 → 不渲染(无可填字段)。
targetField: string | null;
// 选定模板 → 把其 body 填进目标字段(纯前端,不改生成器后端)。
onFill: (field: string, body: string) => void;
}
// 「从模板填入」F3纯前端进场懒加载模板库选一个把 body 填进生成器的 brief/原文输入。
// 与生成器后端解耦——只读 /templates 并回写本地表单值。无模板/无目标字段则不渲染。
export function TemplateFiller({ targetField, onFill }: TemplateFillerProps) {
const toast = useToast();
const [templates, setTemplates] = useState<TemplateResponse[] | null>(null);
const [open, setOpen] = useState(false);
const load = useCallback(async (): Promise<void> => {
try {
const { data, error } = await api.GET("/templates", {});
if (error || !data) {
toast("加载模板失败。", "error");
setTemplates([]);
return;
}
setTemplates(data);
} catch {
toast("加载模板请求异常,请检查网络。", "error");
setTemplates([]);
}
}, [toast]);
useEffect(() => {
if (open && templates === null) void load();
}, [open, templates, load]);
if (!targetField) return null;
const field = targetField;
if (!open) {
return (
<button
type="button"
onClick={() => setOpen(true)}
className="self-start rounded border border-line px-3 py-1 text-sm text-ink-soft hover:text-ink"
>
</button>
);
}
return (
<div
className="flex flex-col gap-2 rounded border border-line bg-bg p-3"
aria-label="从模板填入"
>
<div className="flex items-center justify-between">
<span className="text-sm text-ink-soft">{field}</span>
<button
type="button"
onClick={() => setOpen(false)}
className="text-xs text-ink-soft hover:text-ink"
>
</button>
</div>
{templates === null ? (
<p className="text-sm text-ink-soft"></p>
) : templates.length === 0 ? (
<p className="text-sm text-ink-soft"></p>
) : (
<ul className="flex flex-col gap-1">
{templates.map((t) => (
<li key={t.id}>
<button
type="button"
onClick={() => {
onFill(field, t.body);
setOpen(false);
toast(`已填入模板「${t.title}」。`, "success");
}}
className="w-full rounded border border-line px-3 py-2 text-left text-sm text-ink hover:border-cinnabar"
>
<span className="font-serif">{t.title}</span>
{t.tool_key ? (
<span className="ml-2 text-xs text-ink-soft">
{t.tool_key}
</span>
) : null}
</button>
</li>
))}
</ul>
)}
</div>
);
}