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

@@ -377,6 +377,50 @@ export interface paths {
patch?: never;
trace?: never;
};
"/templates": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
/**
* List Templates
* @description 列出当前用户stub的模板。
*/
get: operations["list_templates_templates_get"];
put?: never;
/**
* Create Template
* @description 新建模板201。title/body 空 → FastAPI 422schema `min_length=1`)。
*/
post: operations["create_template_templates_post"];
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/templates/{template_id}": {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
get?: never;
put?: never;
post?: never;
/**
* Delete Template
* @description 删除模板204。不存在 → 404 NOT_FOUND。
*/
delete: operations["delete_template_templates__template_id__delete"];
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/projects/{project_id}/world/generate": {
parameters: {
query?: never;
@@ -1719,6 +1763,78 @@ export interface components {
*/
job_id: string;
};
/**
* TeardownIngestView
* @description 拆书入库产物(贴 ww_agents.BookTeardownResult落 rules 表。F1。
*/
TeardownIngestView: {
/**
* Themes
* @description 核心主题/立意清单
*/
themes?: string[];
/**
* Archetypes
* @description 人物原型/角色模板清单
*/
archetypes?: string[];
/**
* Structure
* @description 叙事结构概述
* @default
*/
structure: string;
/**
* Hooks
* @description 抓人钩子/爽点套路清单
*/
hooks?: string[];
};
/**
* TemplateCreateRequest
* @description POST /templates新建一条提示词模板。
*/
TemplateCreateRequest: {
/**
* Title
* @description 模板标题
*/
title: string;
/**
* Body
* @description 模板正文(一键填入生成器的 brief/text
*/
body: string;
/**
* Category
* @description 可选分类
*/
category?: string | null;
/**
* Tool Key
* @description 可选关联生成器NULL=通用)
*/
tool_key?: string | null;
};
/**
* TemplateResponse
* @description 模板视图(列出/创建后回显snake_case
*/
TemplateResponse: {
/**
* Id
* Format: uuid
*/
id: string;
/** Title */
title: string;
/** Body */
body: string;
/** Category */
category?: string | null;
/** Tool Key */
tool_key?: string | null;
};
/**
* TestConnectionRequest
* @description POST /test最小探测请求。
@@ -1861,7 +1977,8 @@ export interface components {
*
* 仅声明了 `ingest` 的工具可用。按入库表取用对应字段:
* - world_entities金手指/词条)→ `world_entities`(贴 WorldEntityCardViewtype/name/rules
* - outline细纲→ `chapter_no` + `scenes`(贴 OutlineSceneIngestView
* - outline细纲→ `chapter_no` + `scenes`(贴 OutlineSceneIngestView
* - rules拆书→ `teardown`(贴 TeardownIngestViewthemes/archetypes/structure/hooks
* `acknowledge_conflicts`:作者已查看并接受 continuity 预检冲突时置 true 放行(仿 accept gate
*/
ToolIngestRequest: {
@@ -1880,6 +1997,8 @@ export interface components {
* @description outline 入库的场景行(细纲)
*/
scenes?: components["schemas"]["OutlineSceneIngestView"][];
/** @description rules 入库的拆书结论F1拍平为可读规则条目 */
teardown?: components["schemas"]["TeardownIngestView"] | null;
/**
* Acknowledge Conflicts
* @description 作者已知悉并接受 continuity 冲突 → 放行入库
@@ -2866,6 +2985,88 @@ export interface operations {
};
};
};
list_templates_templates_get: {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
requestBody?: never;
responses: {
/** @description Successful Response */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["TemplateResponse"][];
};
};
};
};
create_template_templates_post: {
parameters: {
query?: never;
header?: never;
path?: never;
cookie?: never;
};
requestBody: {
content: {
"application/json": components["schemas"]["TemplateCreateRequest"];
};
};
responses: {
/** @description Successful Response */
201: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["TemplateResponse"];
};
};
/** @description Validation Error */
422: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["HTTPValidationError"];
};
};
};
};
delete_template_templates__template_id__delete: {
parameters: {
query?: never;
header?: never;
path: {
template_id: string;
};
cookie?: never;
};
requestBody?: never;
responses: {
/** @description Successful Response */
204: {
headers: {
[name: string]: unknown;
};
content?: never;
};
/** @description Validation Error */
422: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["HTTPValidationError"];
};
};
};
};
generate_world_projects__project_id__world_generate_post: {
parameters: {
query?: never;

View File

@@ -13,6 +13,7 @@ import type {
RuleListResponse,
SkillListResponse,
StyleFingerprintResponse,
TemplateResponse,
ToolboxListResponse,
WorldEntityListResponse,
} from "./types";
@@ -149,6 +150,16 @@ export async function fetchOutline(
}
}
// 提示词/模板库列表GET /templates全局只读裸数组
// 任何错误(含后端未上线)降级为空列表,模板页照常渲染(进页不阻塞)。
export async function fetchTemplates(): Promise<TemplateResponse[]> {
try {
return await getJson<TemplateResponse[]>("/templates");
} catch {
return [];
}
}
// 已存草稿GET .../draft含正文供工作台重访重载编辑器
// 404尚无草稿新章→ null由调用方当空编辑器处理不抛错。
export async function fetchDraft(

View File

@@ -85,6 +85,11 @@ export type CharacterListResponse =
export type WorldEntityListResponse =
components["schemas"]["WorldEntityListResponse"];
// F3 提示词/模板库单用户本地版GET/POST/DELETE /templates
export type TemplateResponse = components["schemas"]["TemplateResponse"];
export type TemplateCreateRequest =
components["schemas"]["TemplateCreateRequest"];
// K1 Kimi Code OAuth device-flowC3 扩 K1.3)。
export type OAuthStartResponse = components["schemas"]["OAuthStartResponse"];
export type OAuthDisconnectResponse =
@@ -113,3 +118,6 @@ export type ToolIngestRequest = components["schemas"]["ToolIngestRequest"];
export type ToolIngestResponse = components["schemas"]["ToolIngestResponse"];
export type OutlineSceneIngestView =
components["schemas"]["OutlineSceneIngestView"];
// F1拆书入库产物themes/archetypes/structure/hooks → 项目 rules 条目)。
export type TeardownIngestView =
components["schemas"]["TeardownIngestView"];

View File

@@ -4,6 +4,7 @@ import { emptyDecisions, setNote, setVerdict } from "@/lib/review/decisions";
import type { JobView } from "@/lib/jobs/job";
import {
buildResumeRequest,
CHAIN_KINDS,
chainPhase,
chainResultView,
} from "./chain";
@@ -110,3 +111,19 @@ describe("buildResumeRequest", () => {
expect(buildResumeRequest([])).toEqual({ decisions: [] });
});
});
describe("CHAIN_KINDS", () => {
it("exposes both built-in chain kinds aligned with backend SUPPORTED_CHAINS", () => {
expect(CHAIN_KINDS.map((k) => k.key)).toEqual([
"draft_volume",
"continue_volume",
]);
});
it("gives each kind a non-empty label and description", () => {
for (const kind of CHAIN_KINDS) {
expect(kind.label.length).toBeGreaterThan(0);
expect(kind.description.length).toBeGreaterThan(0);
}
});
});

View File

@@ -6,6 +6,29 @@ import type { ChainResumeRequest } from "@/lib/api/types";
import type { JobView, PollStatus } from "@/lib/jobs/job";
import { buildAcceptRequest, type DecisionDraft } from "@/lib/review/decisions";
// 内置链类型(对齐后端 SUPPORTED_CHAINSdraft_volume=从 start 章按记忆量产;
// continue_volume=续写式(每章以上一章 accepted 正文末尾作前文引子,比纯 digest 更顺)。
export type ChainKind = "draft_volume" | "continue_volume";
export interface ChainKindOption {
key: ChainKind;
label: string;
description: string;
}
export const CHAIN_KINDS: readonly ChainKindOption[] = [
{
key: "draft_volume",
label: "从头写",
description: "按记忆与大纲量产,每章独立写。",
},
{
key: "continue_volume",
label: "续写",
description: "每章以上一章已验收正文末尾作前文引子,承接更顺。",
},
];
// 链 job result 的视图模型(与后端 `_chain_result` 字段对齐chain_key/written/completed/
// awaiting_chapter。token/正文绝不入 result不变量 #5 / chain §5故此处只有进度元数据。
export interface ChainResultView {

View File

@@ -22,6 +22,7 @@ export interface NavItem {
export const GLOBAL_NAV_ITEMS: readonly NavItem[] = [
{ href: "/", label: "作品库" },
{ href: "/templates", label: "模板库" },
{ href: "/settings/providers", label: "设置" },
];

View File

@@ -0,0 +1,62 @@
import { describe, expect, it } from "vitest";
import {
buildTemplateCreateRequest,
EMPTY_TEMPLATE_DRAFT,
isTemplateDraftValid,
type TemplateDraft,
} from "./templates";
const draft = (over: Partial<TemplateDraft>): TemplateDraft => ({
...EMPTY_TEMPLATE_DRAFT,
...over,
});
describe("isTemplateDraftValid", () => {
it("returns true when title and body are both non-empty", () => {
expect(isTemplateDraftValid(draft({ title: "标题", body: "正文" }))).toBe(
true,
);
});
it("returns false when title is blank", () => {
expect(isTemplateDraftValid(draft({ title: " ", body: "正文" }))).toBe(
false,
);
});
it("returns false when body is blank", () => {
expect(isTemplateDraftValid(draft({ title: "标题", body: "" }))).toBe(false);
});
it("returns false for the empty draft", () => {
expect(isTemplateDraftValid(EMPTY_TEMPLATE_DRAFT)).toBe(false);
});
});
describe("buildTemplateCreateRequest", () => {
it("trims title and body and includes optional fields", () => {
const body = buildTemplateCreateRequest(
draft({
title: " 脑洞模板 ",
body: " 写一个穿越故事 ",
category: " 脑洞 ",
toolKey: " idea ",
}),
);
expect(body).toEqual({
title: "脑洞模板",
body: "写一个穿越故事",
category: "脑洞",
tool_key: "idea",
});
});
it("nulls out blank category and tool_key", () => {
const body = buildTemplateCreateRequest(
draft({ title: "t", body: "b", category: " ", toolKey: "" }),
);
expect(body.category).toBeNull();
expect(body.tool_key).toBeNull();
});
});

View File

@@ -0,0 +1,39 @@
// 提示词/模板库前端纯逻辑F3新建表单值校验 + 请求体组装。
// 纯逻辑(无 React / 无 fetch便于 node 环境单测。后端 title/body 非空校验为权威422 兜底),
// 前端先拦一道给即时反馈(守边界:不信输入,提交前 trim 判空)。
import type { TemplateCreateRequest } from "@/lib/api/types";
// 新建模板的草稿表单值(受控输入原始值)。
export interface TemplateDraft {
title: string;
body: string;
category: string;
toolKey: string;
}
export const EMPTY_TEMPLATE_DRAFT: TemplateDraft = {
title: "",
body: "",
category: "",
toolKey: "",
};
// 草稿是否可提交title/body 去空白后非空)。
export function isTemplateDraftValid(draft: TemplateDraft): boolean {
return draft.title.trim().length > 0 && draft.body.trim().length > 0;
}
// 草稿 → 创建请求体trim title/body空 category/toolKey 省略为 null后端可空
export function buildTemplateCreateRequest(
draft: TemplateDraft,
): TemplateCreateRequest {
const category = draft.category.trim();
const toolKey = draft.toolKey.trim();
return {
title: draft.title.trim(),
body: draft.body.trim(),
category: category.length > 0 ? category : null,
tool_key: toolKey.length > 0 ? toolKey : null,
};
}

View File

@@ -1,12 +1,17 @@
import { describe, expect, it } from "vitest";
import { buildIngestRequest, ingestTable } from "./ingest";
import {
buildIngestRequest,
ingestTable,
isSingleObjectIngest,
} from "./ingest";
describe("ingestTable", () => {
it("maps ingestable kinds to their target table", () => {
expect(ingestTable("GoldenFingerResult")).toBe("world_entities");
expect(ingestTable("GlossaryResult")).toBe("world_entities");
expect(ingestTable("DetailedOutlineResult")).toBe("outline");
expect(ingestTable("BookTeardownResult")).toBe("rules");
});
it("returns null for non-ingestable kinds", () => {
@@ -15,6 +20,18 @@ describe("ingestTable", () => {
});
});
describe("isSingleObjectIngest", () => {
it("flags teardown as single-object ingest", () => {
expect(isSingleObjectIngest("BookTeardownResult")).toBe(true);
});
it("treats row-based kinds as not single-object", () => {
expect(isSingleObjectIngest("GoldenFingerResult")).toBe(false);
expect(isSingleObjectIngest("DetailedOutlineResult")).toBe(false);
expect(isSingleObjectIngest("unknown")).toBe(false);
});
});
describe("buildIngestRequest", () => {
it("maps golden finger rows into world_entities with merged rules", () => {
const body = buildIngestRequest({
@@ -81,6 +98,36 @@ describe("buildIngestRequest", () => {
expect(body?.acknowledge_conflicts).toBe(false);
});
it("maps teardown single object to a teardown body", () => {
const body = buildIngestRequest({
outputKind: "BookTeardownResult",
rows: [
{
themes: ["逆袭", "成长"],
archetypes: ["废柴主角"],
structure: "三幕式",
hooks: ["开局打脸"],
},
],
acknowledgeConflicts: true,
});
expect(body).toEqual({
teardown: {
themes: ["逆袭", "成长"],
archetypes: ["废柴主角"],
structure: "三幕式",
hooks: ["开局打脸"],
},
acknowledge_conflicts: true,
});
});
it("returns null for teardown with no rows", () => {
expect(
buildIngestRequest({ outputKind: "BookTeardownResult", rows: [] }),
).toBeNull();
});
it("returns null for non-ingestable output kind", () => {
expect(
buildIngestRequest({ outputKind: "IdeaListResult", rows: [] }),

View File

@@ -4,6 +4,7 @@
import type {
OutlineSceneIngestView,
TeardownIngestView,
ToolIngestRequest,
WorldEntityCardView,
} from "@/lib/api/types";
@@ -63,6 +64,17 @@ function rowToScene(
};
}
// 拆书结构化产物 → TeardownIngestView贴后端 schema后端再拍平为可读 rules 条目)。
// 单对象产物:整个 preview 对象即一条入库项(无逐行勾选)。
function rowToTeardown(row: Record<string, unknown>): TeardownIngestView {
return {
themes: asStringArray(row["themes"]),
archetypes: asStringArray(row["archetypes"]),
structure: asString(row["structure"]),
hooks: asStringArray(row["hooks"]),
};
}
export interface IngestBuildInput {
outputKind: string;
// 作者勾选要入库的预览行(结构化产物原始记录)。
@@ -72,6 +84,15 @@ export interface IngestBuildInput {
acknowledgeConflicts?: boolean;
}
// 单对象入库的 output_kind整个 preview 即一条入库项(无逐行勾选)。
// 当前仅拆书(结构化结论拍平为 rules。行式产物金手指/词条/细纲)不在此列。
const SINGLE_OBJECT_INGEST_KINDS = new Set(["BookTeardownResult"]);
// 该产物是否「单对象入库」UI 据此隐藏勾选框、改文案、用整个 rawPreview 作唯一行)。
export function isSingleObjectIngest(outputKind: string): boolean {
return SINGLE_OBJECT_INGEST_KINDS.has(outputKind);
}
// 入库目标表(供 UI 文案 / 判定)。未知 → null不可入库
export function ingestTable(outputKind: string): string | null {
switch (outputKind) {
@@ -80,6 +101,8 @@ export function ingestTable(outputKind: string): string | null {
return "world_entities";
case "DetailedOutlineResult":
return "outline";
case "BookTeardownResult":
return "rules";
default:
return null;
}
@@ -107,6 +130,12 @@ export function buildIngestRequest(
scenes: input.rows.map((row, i) => rowToScene(row, i)),
acknowledge_conflicts,
};
case "BookTeardownResult": {
// 单对象产物:取首行(整个拆书结论)作 teardown无产物 → null。
const row = input.rows[0];
if (!row) return null;
return { teardown: rowToTeardown(row), acknowledge_conflicts };
}
default:
return null;
}

View File

@@ -9,6 +9,7 @@ import {
missingRequiredFields,
previewRows,
resolveLegacyRoute,
templateFillTarget,
} from "./toolbox";
const field = (over: Partial<ToolInputFieldView> = {}): ToolInputFieldView => ({
@@ -210,3 +211,20 @@ describe("isLegacyTool", () => {
).toBe(false);
});
});
describe("templateFillTarget", () => {
it("prefers brief when present", () => {
expect(
templateFillTarget([field({ name: "brief" }), field({ name: "text" })]),
).toBe("brief");
});
it("falls back to text when brief absent", () => {
expect(templateFillTarget([field({ name: "text" })])).toBe("text");
});
it("returns null when no fillable field exists", () => {
expect(templateFillTarget([field({ name: "count" })])).toBeNull();
expect(templateFillTarget(undefined)).toBeNull();
});
});

View File

@@ -292,6 +292,21 @@ function fallbackItem(row: Record<string, unknown>): PreviewItem {
return { heading, fields, body: null };
}
// —— 模板填入目标 ——
// 模板 body 一键填入的目标输入字段:优先 brief多数生成器主输入否则 text原文输入类
// 都没有则 null不渲染「从模板填入」。F3纯前端不改生成器后端。
const TEMPLATE_FILL_FIELDS = ["brief", "text"] as const;
export function templateFillTarget(
fields: readonly ToolInputFieldView[] | undefined,
): string | null {
const names = new Set((fields ?? []).map((f) => f.name));
for (const candidate of TEMPLATE_FILL_FIELDS) {
if (names.has(candidate)) return candidate;
}
return null;
}
// —— legacy 路由解析 ——
// legacy 工具的 legacy_route 含 {id} 占位(如 /projects/{id}/codex?gen=world→ 替换为真实 projectId。
export function resolveLegacyRoute(