feat(web): 角色群像按定位配比生成(role_mix 缩减版)

- 契约: CharacterGenerateRequest 加 role_mix{定位:数量},model_validator 归一
  count=各值之和(每项≥1、总和≤12),缺省退回单一 role+count
- @llm: build_character_gen_context/run_character_gen 加 role_mix 参并注入配比块
  (确定性、无时间戳,守 assemble 纯函数);router 穿参
- character-gen.md 加"按配比严格分配 role"纪律 + regen prompt_hashes 金标准
- 前端: sanitizeRoleMix/roleMixTotal + buildCharacterGenerateRequest 第4参 +
  useCharacterGen 穿参 + RoleMixEditor + CharacterGenerator 单一/配比双模
This commit is contained in:
Yaojia Wang
2026-07-06 17:24:16 +02:00
parent 72b3c81146
commit 7babb4854b
16 changed files with 428 additions and 50 deletions

View File

@@ -7,6 +7,7 @@ import { ThinkingIndicator } from "@/components/ThinkingIndicator";
import { Button } from "@/components/ui/Button";
import { Field } from "@/components/ui/Field";
import { SectionHeader } from "@/components/ui/SectionHeader";
import { SegmentedControl } from "@/components/ui/SegmentedControl";
import { StatusNote } from "@/components/ui/StatusNote";
import { TextInput } from "@/components/ui/TextInput";
import type { CharacterCardView } from "@/lib/api/types";
@@ -14,11 +15,26 @@ import {
clampCharacterCount,
MAX_CHARACTER_COUNT,
MIN_CHARACTER_COUNT,
roleMixTotal,
sanitizeRoleMix,
updateCard,
} from "@/lib/generation/cards";
import { useCharacterGen } from "@/lib/generation/useCharacterGen";
import { CharacterCardItem } from "./CharacterCardItem";
import { ConflictAdjudication } from "./ConflictAdjudication";
import { RoleMixEditor, type RoleMixRow } from "./RoleMixEditor";
type GenMode = "single" | "mix";
const MODE_OPTIONS: Array<{ value: GenMode; label: string }> = [
{ value: "single", label: "单一定位" },
{ value: "mix", label: "按定位配比" },
];
const DEFAULT_MIX_ROWS: RoleMixRow[] = [
{ role: "主角", count: 1 },
{ role: "对手", count: 1 },
];
interface CharacterGeneratorProps {
projectId: string;
@@ -35,6 +51,10 @@ export function CharacterGenerator({
const [brief, setBrief] = useState("");
const [count, setCount] = useState(MIN_CHARACTER_COUNT);
const [role, setRole] = useState("");
const [mode, setMode] = useState<GenMode>("single");
const [mixRows, setMixRows] = useState<RoleMixRow[]>(DEFAULT_MIX_ROWS);
// 配比模式下的有效合计sanitize 后,已按 MAX 截断)——门控生成按钮。
const mixTotal = roleMixTotal(sanitizeRoleMix(mixRows));
// 编辑态卡片(预览返回后拷贝进本地,允许就地改)。
const [drafts, setDrafts] = useState<CharacterCardView[]>([]);
const [selected, setSelected] = useState<Set<number>>(new Set());
@@ -46,8 +66,17 @@ export function CharacterGenerator({
}, []);
const onGenerate = useCallback(async () => {
if (mode === "mix") {
await gen.generate({
projectId,
brief,
count,
roleMix: sanitizeRoleMix(mixRows),
});
return;
}
await gen.generate({ projectId, brief, count, role });
}, [gen, projectId, brief, count, role]);
}, [gen, projectId, brief, count, role, mode, mixRows]);
// gen.cards 变化(新预览)→ 重新同步本地草稿。
const previewKey = gen.cards.map((c) => c.name).join("|");
@@ -96,43 +125,64 @@ export function CharacterGenerator({
placeholder="如:一个亦正亦邪的剑修,背负灭门血仇"
/>
</Field>
<div className="flex flex-wrap items-end gap-3">
<Field
label="数量"
className="w-28"
help={`${MIN_CHARACTER_COUNT}${MAX_CHARACTER_COUNT}`}
>
<TextInput
type="number"
min={MIN_CHARACTER_COUNT}
max={MAX_CHARACTER_COUNT}
value={count}
onChange={(e) =>
setCount(clampCharacterCount(Number(e.target.value)))
}
/>
</Field>
<Field label="定位(可选)" className="min-w-[12rem] flex-1">
<TextInput
value={role}
onChange={(e) => setRole(e.target.value)}
placeholder="主角 / CP / 对手 / 导师 / 工具人"
/>
</Field>
<Button
onClick={() => void onGenerate()}
disabled={
generating ||
brief.trim().length === 0 ||
count < MIN_CHARACTER_COUNT ||
count > MAX_CHARACTER_COUNT
}
variant="primary"
>
<Sparkles className="h-4 w-4" aria-hidden="true" />
{generating ? "生成中…" : "生成"}
</Button>
<div className="mb-3">
<SegmentedControl
options={MODE_OPTIONS}
value={mode}
onChange={setMode}
ariaLabel="生成模式"
/>
</div>
{mode === "mix" ? (
<Field
label="角色定位配比"
className="mb-3"
help="每个定位产出对应数量,合计即总张数"
>
<RoleMixEditor rows={mixRows} onChange={setMixRows} />
</Field>
) : (
<div className="mb-3 flex flex-wrap items-end gap-3">
<Field
label="数量"
className="w-28"
help={`${MIN_CHARACTER_COUNT}${MAX_CHARACTER_COUNT}`}
>
<TextInput
type="number"
min={MIN_CHARACTER_COUNT}
max={MAX_CHARACTER_COUNT}
value={count}
onChange={(e) =>
setCount(clampCharacterCount(Number(e.target.value)))
}
/>
</Field>
<Field label="定位(可选)" className="min-w-[12rem] flex-1">
<TextInput
value={role}
onChange={(e) => setRole(e.target.value)}
placeholder="主角 / CP / 对手 / 导师 / 工具人"
/>
</Field>
</div>
)}
<Button
onClick={() => void onGenerate()}
disabled={
generating ||
brief.trim().length === 0 ||
(mode === "mix"
? mixTotal < MIN_CHARACTER_COUNT
: count < MIN_CHARACTER_COUNT || count > MAX_CHARACTER_COUNT)
}
variant="primary"
>
<Sparkles className="h-4 w-4" aria-hidden="true" />
{generating ? "生成中…" : "生成"}
</Button>
</div>
{generating ? (

View File

@@ -0,0 +1,82 @@
"use client";
import { Plus, X } from "lucide-react";
import { Button } from "@/components/ui/Button";
import { TextInput } from "@/components/ui/TextInput";
import {
MAX_CHARACTER_COUNT,
MIN_CHARACTER_COUNT,
roleMixTotal,
sanitizeRoleMix,
} from "@/lib/generation/cards";
// 单行配比:某定位 + 该定位要生成的数量。
export interface RoleMixRow {
role: string;
count: number;
}
interface RoleMixEditorProps {
rows: RoleMixRow[];
onChange: (rows: RoleMixRow[]) => void;
}
// 群像按定位配比编辑器(⑦):一组「定位 + 数量」行;合计封顶 MAX_CHARACTER_COUNT。
// 不可变更新——每次编辑返回新数组,不改入参。
export function RoleMixEditor({ rows, onChange }: RoleMixEditorProps) {
// 有效合计 = sanitize 后的总数(已按 MAX 截断),即实际会生成的张数。
const effectiveTotal = roleMixTotal(sanitizeRoleMix(rows));
const updateRow = (index: number, patch: Partial<RoleMixRow>): void => {
onChange(rows.map((r, i) => (i === index ? { ...r, ...patch } : r)));
};
const addRow = (): void => onChange([...rows, { role: "", count: 1 }]);
const removeRow = (index: number): void =>
onChange(rows.filter((_, i) => i !== index));
return (
<div className="flex flex-col gap-2" aria-label="角色定位配比">
{rows.map((row, i) => (
<div key={i} className="flex items-center gap-2">
<TextInput
value={row.role}
onChange={(e) => updateRow(i, { role: e.target.value })}
placeholder="定位:主角 / 对手 / 配角"
aria-label={`${i + 1} 行定位`}
className="min-w-[10rem] flex-1"
/>
<TextInput
type="number"
min={MIN_CHARACTER_COUNT}
max={MAX_CHARACTER_COUNT}
value={row.count}
onChange={(e) =>
updateRow(i, { count: Math.round(Number(e.target.value)) })
}
aria-label={`${i + 1} 行数量`}
className="w-20"
/>
<Button
variant="ghost"
size="icon"
onClick={() => removeRow(i)}
disabled={rows.length <= 1}
aria-label={`删除第 ${i + 1}`}
>
<X className="h-4 w-4" aria-hidden="true" />
</Button>
</div>
))}
<div className="flex items-center justify-between">
<Button variant="outline" size="sm" onClick={addRow}>
<Plus className="h-4 w-4" aria-hidden="true" />
</Button>
<span className="text-xs text-ink-soft">
{effectiveTotal} / {MAX_CHARACTER_COUNT}
</span>
</div>
</div>
);
}

View File

@@ -997,6 +997,10 @@ export interface components {
/**
* CharacterGenerateRequest
* @description POST /projects/:id/characters/generate据需求生成角色卡预览群像防雷同
*
* `role_mix`(⑦ 群像按定位配比)与 `count` 的关系:`role_mix` 在场时 `count` 取各值之和
* (忽略客户端显式 count每项数量须 ≥ 1、总和须 ≤ `MAX_GENERATE_COUNT`;缺省则退回
* 单一 `role` + `count` 语义。
*/
CharacterGenerateRequest: {
/**
@@ -1006,7 +1010,7 @@ export interface components {
brief: string;
/**
* Count
* @description 生成数量
* @description 生成数量role_mix 在场时取各值之和)
* @default 1
*/
count: number;
@@ -1015,6 +1019,13 @@ export interface components {
* @description 角色定位(主角/CP/对手/导师/工具人 等)
*/
role?: string | null;
/**
* Role Mix
* @description 按定位配比生成 {定位: 数量};在场时 count=各值之和每项≥1、总和≤12
*/
role_mix?: {
[key: string]: number;
} | null;
};
/**
* CharacterIngestRequest

View File

@@ -16,6 +16,8 @@ import {
mergeCharacterCards,
mergeWorldEntities,
MIN_CHARACTER_COUNT,
roleMixTotal,
sanitizeRoleMix,
updateCard,
worldEntityRules,
} from "./cards";
@@ -62,6 +64,62 @@ describe("buildCharacterGenerateRequest", () => {
role: "对手",
});
});
it("uses role_mix (count=sum, no single role) when a mix is supplied", () => {
expect(
buildCharacterGenerateRequest("群像", 1, "忽略", {
主角: 1,
对手: 2,
配角: 3,
}),
).toEqual({
brief: "群像",
count: 6,
role_mix: { 主角: 1, 对手: 2, 配角: 3 },
});
});
it("falls back to count/role when role_mix is empty", () => {
expect(buildCharacterGenerateRequest("群像", 4, "主角", {})).toEqual({
brief: "群像",
count: 4,
role: "主角",
});
});
});
describe("sanitizeRoleMix", () => {
it("trims roles, drops blanks, clamps counts to >=1, dedups", () => {
expect(
sanitizeRoleMix([
{ role: " 主角 ", count: 2 },
{ role: "", count: 3 }, // 空定位丢弃
{ role: "对手", count: 0 }, // clamp 到 1
{ role: "主角", count: 5 }, // 重复定位丢弃(先到先得)
]),
).toEqual({ 主角: 2, 对手: 1 });
});
it("caps the running total at MAX_CHARACTER_COUNT", () => {
const out = sanitizeRoleMix([
{ role: "主角", count: 10 },
{ role: "对手", count: 5 }, // 只剩 2 额度
{ role: "配角", count: 3 }, // 无额度,丢弃
]);
expect(out).toEqual({ 主角: 10, 对手: 2 });
expect(roleMixTotal(out)).toBe(MAX_CHARACTER_COUNT);
});
it("returns empty object when no valid rows", () => {
expect(sanitizeRoleMix([{ role: " ", count: 3 }])).toEqual({});
});
});
describe("roleMixTotal", () => {
it("sums counts", () => {
expect(roleMixTotal({ 主角: 1, 对手: 2 })).toBe(3);
expect(roleMixTotal({})).toBe(0);
});
});
describe("buildCharacterIngestRequest", () => {

Binary file not shown.

View File

@@ -53,6 +53,24 @@ describe("useCharacterGen", () => {
expect(toast).not.toHaveBeenCalled();
});
it("按定位配比生成:请求体带 role_mix、count 取各值之和", async () => {
post.mockResolvedValue({ data: { cards: [] }, error: null });
const { result } = renderHook(() => useCharacterGen());
await act(async () => {
await result.current.generate({
projectId: "p1",
brief: "群像",
count: 1,
role: "忽略",
roleMix: { 主角: 1, 对手: 2 },
});
});
const body = post.mock.calls[0]?.[1]?.body;
expect(body.role_mix).toEqual({ 主角: 1, 对手: 2 });
expect(body.count).toBe(3);
expect(body.role).toBeUndefined();
});
it("生成成功但 cards 缺失:回退为空数组", async () => {
post.mockResolvedValue({ data: { cards: null }, error: null });
const { result } = renderHook(() => useCharacterGen());

View File

@@ -21,6 +21,8 @@ export interface CharacterGenInput {
brief: string;
count: number;
role?: string | null;
// 群像按定位配比(⑦);在场时后端把 count 定为各值之和,忽略 count/role。
roleMix?: Readonly<Record<string, number>> | null;
}
export interface UseCharacterGen {
@@ -50,7 +52,7 @@ export function useCharacterGen(): UseCharacterGen {
const toast = useToast();
const generate = useCallback<UseCharacterGen["generate"]>(
async ({ projectId, brief, count, role }) => {
async ({ projectId, brief, count, role, roleMix }) => {
setGenStatus("generating");
setCards([]);
setConflicts(null);
@@ -60,7 +62,7 @@ export function useCharacterGen(): UseCharacterGen {
"/projects/{project_id}/characters/generate",
{
params: { path: { project_id: projectId } },
body: buildCharacterGenerateRequest(brief, count, role),
body: buildCharacterGenerateRequest(brief, count, role, roleMix),
},
);
if (error || !data) {