feat: M1 — 立项→写章草稿(SSE)→自动保存;连一家 provider
- 薄自建 LLM 网关:OpenAI 兼容适配器(DeepSeek) + instructor 结构化输出 + usage_ledger 记账 + 档位路由 - 记忆服务 assemble:确定性选择(显式+主角+近况) + 渲染卡 + 缓存断点(中性文本) - LangGraph 写章节点 + Postgres checkpointer + SSE 归一(token/done/error) - API:立项 + 写章 draft(SSE) + PUT 自动保存 + 提供商凭据(Fernet 加密/测试连接) - 前端:AppShell + 作品库 + 5 步立项向导 + 写作工作台(流式打字机+自动保存) + 设置页 - M1 E2E:真实 DB + mock 网关零 token 走通闭环
This commit is contained in:
80
apps/web/app/page.tsx
Normal file
80
apps/web/app/page.tsx
Normal file
@@ -0,0 +1,80 @@
|
||||
import Link from "next/link";
|
||||
|
||||
import { AppShell } from "@/components/AppShell";
|
||||
import { ProjectCard } from "@/components/ProjectCard";
|
||||
import { fetchProjects } from "@/lib/api/server";
|
||||
import type { ProjectResponse } from "@/lib/api/types";
|
||||
|
||||
// 作品库(Dashboard 入口,UX §6.1)。Server Component 读取。
|
||||
export default async function DashboardPage() {
|
||||
let projects: ProjectResponse[] = [];
|
||||
let loadError = false;
|
||||
try {
|
||||
const data = await fetchProjects();
|
||||
projects = data.projects ?? [];
|
||||
} catch {
|
||||
loadError = true;
|
||||
}
|
||||
|
||||
return (
|
||||
<AppShell>
|
||||
<div className="mx-auto max-w-5xl px-8 py-10">
|
||||
<div className="mb-8 flex items-center justify-between">
|
||||
<h1 className="font-serif text-3xl text-ink">我的作品</h1>
|
||||
<Link
|
||||
href="/projects/new"
|
||||
className="rounded bg-cinnabar px-4 py-2 text-sm text-panel hover:opacity-90"
|
||||
>
|
||||
+ 新建作品
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{loadError ? (
|
||||
<p className="rounded border border-conflict bg-panel p-6 text-conflict">
|
||||
无法连接后端服务,请确认 API 已启动后刷新。
|
||||
</p>
|
||||
) : projects.length === 0 ? (
|
||||
<EmptyState />
|
||||
) : (
|
||||
<ul className="grid grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-3">
|
||||
{projects.map((p) => (
|
||||
<li key={p.id}>
|
||||
<ProjectCard project={p} />
|
||||
</li>
|
||||
))}
|
||||
<li>
|
||||
<NewProjectCard />
|
||||
</li>
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
</AppShell>
|
||||
);
|
||||
}
|
||||
|
||||
function EmptyState() {
|
||||
return (
|
||||
<div className="flex flex-col items-center gap-4 rounded border border-line bg-panel py-20 text-center">
|
||||
<p className="font-serif text-2xl text-ink">还没有作品</p>
|
||||
<p className="text-ink-soft">从一句灵感开始你的第一本书。</p>
|
||||
<Link
|
||||
href="/projects/new"
|
||||
className="rounded bg-cinnabar px-5 py-2 text-sm text-panel hover:opacity-90"
|
||||
>
|
||||
+ 新建作品
|
||||
</Link>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function NewProjectCard() {
|
||||
return (
|
||||
<Link
|
||||
href="/projects/new"
|
||||
className="flex h-full min-h-[160px] flex-col items-center justify-center rounded border border-dashed border-line bg-panel text-center hover:border-cinnabar"
|
||||
>
|
||||
<span className="font-serif text-xl text-cinnabar">+ 新建</span>
|
||||
<span className="mt-2 text-sm text-ink-soft">从一句灵感开始一本书</span>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
19
apps/web/app/projects/[id]/write/page.tsx
Normal file
19
apps/web/app/projects/[id]/write/page.tsx
Normal file
@@ -0,0 +1,19 @@
|
||||
import { notFound } from "next/navigation";
|
||||
|
||||
import { Workbench } from "@/components/workbench/Workbench";
|
||||
import { fetchProject } from "@/lib/api/server";
|
||||
|
||||
interface PageProps {
|
||||
params: Promise<{ id: string }>;
|
||||
}
|
||||
|
||||
// 写作工作台页(UX §6.3)。Server Component 取项目,Workbench 负责编辑/流式/保存。
|
||||
export default async function WritePage({ params }: PageProps) {
|
||||
const { id } = await params;
|
||||
try {
|
||||
const project = await fetchProject(id);
|
||||
return <Workbench project={project} />;
|
||||
} catch {
|
||||
notFound();
|
||||
}
|
||||
}
|
||||
12
apps/web/app/projects/new/page.tsx
Normal file
12
apps/web/app/projects/new/page.tsx
Normal file
@@ -0,0 +1,12 @@
|
||||
import { AppShell } from "@/components/AppShell";
|
||||
import { ProjectWizard } from "@/components/ProjectWizard";
|
||||
|
||||
export default function NewProjectPage() {
|
||||
return (
|
||||
<AppShell>
|
||||
<div className="px-8 py-10">
|
||||
<ProjectWizard />
|
||||
</div>
|
||||
</AppShell>
|
||||
);
|
||||
}
|
||||
29
apps/web/app/settings/providers/page.tsx
Normal file
29
apps/web/app/settings/providers/page.tsx
Normal file
@@ -0,0 +1,29 @@
|
||||
import { AppShell } from "@/components/AppShell";
|
||||
import { ProvidersSettings } from "@/components/settings/ProvidersSettings";
|
||||
import { fetchProviders } from "@/lib/api/server";
|
||||
import type { ProvidersResponse } from "@/lib/api/types";
|
||||
|
||||
// 模型与提供商设置(UX §6.10)。Server Component 取初始数据。
|
||||
export default async function ProvidersSettingsPage() {
|
||||
let initial: ProvidersResponse = { providers: [], tier_routing: [] };
|
||||
let loadError = false;
|
||||
try {
|
||||
initial = await fetchProviders();
|
||||
} catch {
|
||||
loadError = true;
|
||||
}
|
||||
|
||||
return (
|
||||
<AppShell title="设置 › 模型与提供商">
|
||||
<div className="mx-auto max-w-3xl px-8 py-10">
|
||||
{loadError ? (
|
||||
<p className="rounded border border-conflict bg-panel p-6 text-conflict">
|
||||
无法连接后端服务,请确认 API 已启动后刷新。
|
||||
</p>
|
||||
) : (
|
||||
<ProvidersSettings initial={initial} />
|
||||
)}
|
||||
</div>
|
||||
</AppShell>
|
||||
);
|
||||
}
|
||||
26
apps/web/components/ProjectCard.tsx
Normal file
26
apps/web/components/ProjectCard.tsx
Normal file
@@ -0,0 +1,26 @@
|
||||
import Link from "next/link";
|
||||
|
||||
import type { ProjectResponse } from "@/lib/api/types";
|
||||
|
||||
interface ProjectCardProps {
|
||||
project: ProjectResponse;
|
||||
}
|
||||
|
||||
// 作品卡(UX §6.1):书名衬线大字、题材、一句话故事。
|
||||
// M1 无字数/章数/待办统计端点 → 暂不展示该徽标(避免编造 API)。
|
||||
export function ProjectCard({ project }: ProjectCardProps) {
|
||||
return (
|
||||
<Link
|
||||
href={`/projects/${project.id}/write`}
|
||||
className="flex h-full min-h-[160px] flex-col rounded border border-line bg-panel p-6 shadow-paper hover:border-cinnabar"
|
||||
>
|
||||
<h2 className="font-serif text-2xl text-ink">〈{project.title}〉</h2>
|
||||
{project.genre ? (
|
||||
<p className="mt-2 text-sm text-ink-soft">{project.genre}</p>
|
||||
) : null}
|
||||
{project.logline ? (
|
||||
<p className="mt-3 line-clamp-3 text-sm text-ink">{project.logline}</p>
|
||||
) : null}
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
301
apps/web/components/ProjectWizard.tsx
Normal file
301
apps/web/components/ProjectWizard.tsx
Normal file
@@ -0,0 +1,301 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useState } from "react";
|
||||
|
||||
import { api } from "@/lib/api/client";
|
||||
import { useToast } from "@/components/Toast";
|
||||
import {
|
||||
GENRES,
|
||||
SELLING_POINT_PRESETS,
|
||||
STRUCTURES,
|
||||
WIZARD_STEPS,
|
||||
canAdvance,
|
||||
canSubmit,
|
||||
clampStep,
|
||||
emptyWizardForm,
|
||||
toCreateRequest,
|
||||
type WizardForm,
|
||||
} from "@/lib/wizard/wizard";
|
||||
|
||||
const STEP_TITLES = [
|
||||
"书名 + 题材",
|
||||
"一句话故事 + 卖点 + 结构",
|
||||
"立意 / 总纲",
|
||||
"主角 / 金手指",
|
||||
"基础世界观",
|
||||
];
|
||||
|
||||
// 立项向导(UX §6.2)。Client Component:收集字段 → POST /projects → 进工作台。
|
||||
export function ProjectWizard() {
|
||||
const router = useRouter();
|
||||
const toast = useToast();
|
||||
const [step, setStep] = useState(1);
|
||||
const [form, setForm] = useState<WizardForm>(emptyWizardForm);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
|
||||
const update = (patch: Partial<WizardForm>): void =>
|
||||
setForm((prev) => ({ ...prev, ...patch }));
|
||||
|
||||
const toggleSellingPoint = (point: string): void =>
|
||||
setForm((prev) => ({
|
||||
...prev,
|
||||
sellingPoints: prev.sellingPoints.includes(point)
|
||||
? prev.sellingPoints.filter((p) => p !== point)
|
||||
: [...prev.sellingPoints, point],
|
||||
}));
|
||||
|
||||
const goBack = (): void => setStep((s) => clampStep(s - 1));
|
||||
const goNext = (): void => setStep((s) => clampStep(s + 1));
|
||||
|
||||
const submit = async (): Promise<void> => {
|
||||
if (!canSubmit(form)) {
|
||||
toast("请先填写书名", "error");
|
||||
setStep(1);
|
||||
return;
|
||||
}
|
||||
setSubmitting(true);
|
||||
const { data, error } = await api.POST("/projects", {
|
||||
body: toCreateRequest(form),
|
||||
});
|
||||
if (error || !data) {
|
||||
setSubmitting(false);
|
||||
toast("创建作品失败,请重试", "error");
|
||||
return;
|
||||
}
|
||||
router.push(`/projects/${data.id}/write`);
|
||||
};
|
||||
|
||||
const isLast = step === WIZARD_STEPS;
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-2xl rounded border border-line bg-panel p-8 shadow-paper">
|
||||
<div className="mb-6 flex items-center justify-between">
|
||||
<h1 className="font-serif text-2xl text-ink">新建作品</h1>
|
||||
<StepDots current={step} />
|
||||
</div>
|
||||
<p className="mb-4 text-sm text-ink-soft">
|
||||
步骤 {step}/{WIZARD_STEPS} · {STEP_TITLES[step - 1]}
|
||||
</p>
|
||||
|
||||
<div className="min-h-[220px]">
|
||||
{step === 1 && <StepBasics form={form} update={update} />}
|
||||
{step === 2 && (
|
||||
<StepStory
|
||||
form={form}
|
||||
update={update}
|
||||
toggleSellingPoint={toggleSellingPoint}
|
||||
/>
|
||||
)}
|
||||
{step === 3 && <StepPremise form={form} update={update} />}
|
||||
{step === 4 && <StepProtagonist form={form} update={update} />}
|
||||
{step === 5 && <StepWorld />}
|
||||
</div>
|
||||
|
||||
<div className="mt-8 flex items-center justify-between">
|
||||
<button
|
||||
type="button"
|
||||
onClick={goBack}
|
||||
disabled={step === 1}
|
||||
className="rounded border border-line px-4 py-2 text-sm text-ink disabled:opacity-40"
|
||||
>
|
||||
← 上一步
|
||||
</button>
|
||||
{isLast ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={submit}
|
||||
disabled={submitting || !canSubmit(form)}
|
||||
className="rounded bg-cinnabar px-5 py-2 text-sm text-panel disabled:opacity-40"
|
||||
>
|
||||
{submitting ? "创建中…" : "完成立项 →"}
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={goNext}
|
||||
disabled={!canAdvance(step, form)}
|
||||
className="rounded bg-cinnabar px-5 py-2 text-sm text-panel disabled:opacity-40"
|
||||
>
|
||||
下一步 →
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function StepDots({ current }: { current: number }) {
|
||||
return (
|
||||
<div className="flex gap-1.5" aria-hidden="true">
|
||||
{Array.from({ length: WIZARD_STEPS }, (_, i) => (
|
||||
<span
|
||||
key={i}
|
||||
className={`h-2 w-2 rounded-full ${
|
||||
i + 1 <= current ? "bg-cinnabar" : "bg-line"
|
||||
}`}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface StepProps {
|
||||
form: WizardForm;
|
||||
update: (patch: Partial<WizardForm>) => void;
|
||||
}
|
||||
|
||||
function Field({
|
||||
label,
|
||||
children,
|
||||
}: {
|
||||
label: string;
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<label className="mb-4 block">
|
||||
<span className="mb-1 block text-sm text-ink-soft">{label}</span>
|
||||
{children}
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
||||
const inputCls =
|
||||
"w-full rounded border border-line bg-bg px-3 py-2 text-ink focus:border-cinnabar focus:outline-none";
|
||||
|
||||
function StepBasics({ form, update }: StepProps) {
|
||||
return (
|
||||
<div>
|
||||
<Field label="书名(必填)">
|
||||
<input
|
||||
className={inputCls}
|
||||
value={form.title}
|
||||
onChange={(e) => update({ title: e.target.value })}
|
||||
placeholder="例:逐光而行"
|
||||
autoFocus
|
||||
/>
|
||||
</Field>
|
||||
<Field label="题材">
|
||||
<select
|
||||
className={inputCls}
|
||||
value={form.genre}
|
||||
onChange={(e) => update({ genre: e.target.value })}
|
||||
>
|
||||
<option value="">未选择</option>
|
||||
{GENRES.map((g) => (
|
||||
<option key={g} value={g}>
|
||||
{g}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Field>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function StepStory({
|
||||
form,
|
||||
update,
|
||||
toggleSellingPoint,
|
||||
}: StepProps & { toggleSellingPoint: (p: string) => void }) {
|
||||
return (
|
||||
<div>
|
||||
<Field label="一句话故事(logline)">
|
||||
<textarea
|
||||
className={`${inputCls} h-20 resize-none`}
|
||||
value={form.logline}
|
||||
onChange={(e) => update({ logline: e.target.value })}
|
||||
placeholder="废柴少年觉醒禁忌血脉,在仙门倾轧中逆势封神。"
|
||||
/>
|
||||
</Field>
|
||||
<Field label="故事结构">
|
||||
<div className="flex gap-2">
|
||||
{STRUCTURES.map((s) => (
|
||||
<button
|
||||
type="button"
|
||||
key={s}
|
||||
onClick={() => update({ structure: s })}
|
||||
className={`rounded border px-3 py-1.5 text-sm ${
|
||||
form.structure === s
|
||||
? "border-cinnabar bg-[var(--color-cinnabar-wash)] text-cinnabar"
|
||||
: "border-line text-ink"
|
||||
}`}
|
||||
>
|
||||
{s}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</Field>
|
||||
<fieldset>
|
||||
<legend className="mb-1 block text-sm text-ink-soft">核心卖点</legend>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{SELLING_POINT_PRESETS.map((p) => (
|
||||
<button
|
||||
type="button"
|
||||
key={p}
|
||||
aria-pressed={form.sellingPoints.includes(p)}
|
||||
onClick={() => toggleSellingPoint(p)}
|
||||
className={`rounded border px-3 py-1.5 text-sm ${
|
||||
form.sellingPoints.includes(p)
|
||||
? "border-cinnabar bg-[var(--color-cinnabar-wash)] text-cinnabar"
|
||||
: "border-line text-ink"
|
||||
}`}
|
||||
>
|
||||
{p}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</fieldset>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function StepPremise({ form, update }: StepProps) {
|
||||
return (
|
||||
<div>
|
||||
<Field label="立意(premise)">
|
||||
<textarea
|
||||
className={`${inputCls} h-20 resize-none`}
|
||||
value={form.premise}
|
||||
onChange={(e) => update({ premise: e.target.value })}
|
||||
placeholder="故事的核心命题与前提。"
|
||||
/>
|
||||
</Field>
|
||||
<Field label="主题(theme)">
|
||||
<input
|
||||
className={inputCls}
|
||||
value={form.theme}
|
||||
onChange={(e) => update({ theme: e.target.value })}
|
||||
placeholder="例:抗争与代价"
|
||||
/>
|
||||
</Field>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function StepProtagonist({ form, update }: StepProps) {
|
||||
// M1 projects 表无独立主角/金手指字段;先并入立意/总纲文本,避免编造 API。
|
||||
return (
|
||||
<div>
|
||||
<p className="mb-3 text-sm text-ink-soft">
|
||||
主角与金手指(M1 暂并入总纲,后续设定库独立建模)。
|
||||
</p>
|
||||
<Field label="主角 / 金手指概要">
|
||||
<textarea
|
||||
className={`${inputCls} h-28 resize-none`}
|
||||
value={form.premise}
|
||||
onChange={(e) => update({ premise: e.target.value })}
|
||||
placeholder="主角设定、金手指来源与限制……"
|
||||
/>
|
||||
</Field>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function StepWorld() {
|
||||
return (
|
||||
<div className="rounded border border-dashed border-line bg-bg p-6 text-sm text-ink-soft">
|
||||
基础世界观将在「设定库」里建模(后续里程碑)。现在可直接完成立项,进入工作台开始写第一章。
|
||||
</div>
|
||||
);
|
||||
}
|
||||
209
apps/web/components/settings/ProvidersSettings.tsx
Normal file
209
apps/web/components/settings/ProvidersSettings.tsx
Normal file
@@ -0,0 +1,209 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
|
||||
import { api } from "@/lib/api/client";
|
||||
import { useToast } from "@/components/Toast";
|
||||
import { KNOWN_PROVIDERS, TIER_LABELS } from "@/lib/settings/providers";
|
||||
import type {
|
||||
CapabilitiesView,
|
||||
ProvidersResponse,
|
||||
TierRoutingView,
|
||||
} from "@/lib/api/types";
|
||||
|
||||
interface ProvidersSettingsProps {
|
||||
initial: ProvidersResponse;
|
||||
}
|
||||
|
||||
interface TestResult {
|
||||
ok: boolean;
|
||||
capabilities: CapabilitiesView;
|
||||
}
|
||||
|
||||
// 设置页主体(UX §6.10):档位路由(只读展示)+ 凭据行(脱敏 / 添加更新 / 测试连接)。
|
||||
export function ProvidersSettings({ initial }: ProvidersSettingsProps) {
|
||||
const toast = useToast();
|
||||
const [providers, setProviders] = useState(initial.providers ?? []);
|
||||
const tierRouting: TierRoutingView[] = initial.tier_routing ?? [];
|
||||
const [drafts, setDrafts] = useState<Record<string, string>>({});
|
||||
const [savingId, setSavingId] = useState<string | null>(null);
|
||||
const [testingId, setTestingId] = useState<string | null>(null);
|
||||
const [results, setResults] = useState<Record<string, TestResult>>({});
|
||||
|
||||
const maskedFor = (id: string): string | null =>
|
||||
providers.find((p) => p.provider === id)?.masked_key ?? null;
|
||||
|
||||
const saveCredential = async (providerId: string): Promise<void> => {
|
||||
const apiKey = (drafts[providerId] ?? "").trim();
|
||||
if (!apiKey) {
|
||||
toast("请先输入 API Key", "error");
|
||||
return;
|
||||
}
|
||||
setSavingId(providerId);
|
||||
const { data, error } = await api.PUT("/settings/providers", {
|
||||
body: { credentials: [{ provider: providerId, api_key: apiKey }] },
|
||||
});
|
||||
setSavingId(null);
|
||||
if (error || !data) {
|
||||
toast("保存凭据失败,请重试", "error");
|
||||
return;
|
||||
}
|
||||
setProviders(data.providers ?? []);
|
||||
setDrafts((prev) => ({ ...prev, [providerId]: "" }));
|
||||
toast("凭据已保存", "success");
|
||||
};
|
||||
|
||||
const testConnection = async (providerId: string): Promise<void> => {
|
||||
setTestingId(providerId);
|
||||
const { data, error } = await api.POST("/settings/providers/test", {
|
||||
body: { provider: providerId },
|
||||
});
|
||||
setTestingId(null);
|
||||
if (error || !data) {
|
||||
toast("测试连接失败", "error");
|
||||
return;
|
||||
}
|
||||
setResults((prev) => ({
|
||||
...prev,
|
||||
[providerId]: { ok: data.ok, capabilities: data.capabilities },
|
||||
}));
|
||||
toast(data.ok ? "连接成功" : "连接未通过", data.ok ? "success" : "error");
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<section className="mb-10">
|
||||
<h2 className="mb-3 font-serif text-xl text-ink">能力档位路由</h2>
|
||||
{tierRouting.length === 0 ? (
|
||||
<p className="rounded border border-dashed border-line bg-panel p-4 text-sm text-ink-soft">
|
||||
尚未配置档位路由。连接提供商后将使用默认路由。
|
||||
</p>
|
||||
) : (
|
||||
<ul className="divide-y divide-line rounded border border-line bg-panel">
|
||||
{tierRouting.map((t) => (
|
||||
<li
|
||||
key={t.tier}
|
||||
className="flex items-center gap-4 px-4 py-3 text-sm"
|
||||
>
|
||||
<span className="w-20 text-ink">
|
||||
{TIER_LABELS[t.tier] ?? t.tier}
|
||||
</span>
|
||||
<span className="font-mono text-ink-soft">
|
||||
{t.provider} · {t.model}
|
||||
</span>
|
||||
{t.fallback && t.fallback.length > 0 ? (
|
||||
<span className="ml-auto font-mono text-xs text-ink-soft">
|
||||
回退 {t.fallback.join(", ")}
|
||||
</span>
|
||||
) : null}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<h2 className="mb-3 font-serif text-xl text-ink">提供商凭据</h2>
|
||||
{providers.length === 0 ? (
|
||||
<p className="mb-4 rounded border border-dashed border-line bg-panel p-4 text-sm text-ink-soft">
|
||||
至少连接一个提供商即可开始写作(求质量选 Anthropic / 求性价比选
|
||||
DeepSeek)。
|
||||
</p>
|
||||
) : null}
|
||||
<ul className="divide-y divide-line rounded border border-line bg-panel">
|
||||
{KNOWN_PROVIDERS.map((prov) => {
|
||||
const masked = maskedFor(prov.id);
|
||||
const result = results[prov.id];
|
||||
return (
|
||||
<li key={prov.id} className="px-4 py-4">
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<span
|
||||
className={`h-2 w-2 rounded-full ${masked ? "bg-pass" : "bg-line"}`}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<span className="w-28 text-sm text-ink">{prov.label}</span>
|
||||
{masked ? (
|
||||
<span className="font-mono text-xs text-ink-soft">
|
||||
{masked}
|
||||
</span>
|
||||
) : null}
|
||||
<label className="sr-only" htmlFor={`key-${prov.id}`}>
|
||||
{prov.label} API Key
|
||||
</label>
|
||||
<input
|
||||
id={`key-${prov.id}`}
|
||||
type="password"
|
||||
autoComplete="off"
|
||||
value={drafts[prov.id] ?? ""}
|
||||
onChange={(e) =>
|
||||
setDrafts((prev) => ({
|
||||
...prev,
|
||||
[prov.id]: e.target.value,
|
||||
}))
|
||||
}
|
||||
placeholder={masked ? "输入新 Key 以更新" : "输入 API Key"}
|
||||
className="min-w-[12rem] flex-1 rounded border border-line bg-bg px-3 py-1.5 text-sm text-ink focus:border-cinnabar focus:outline-none"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => saveCredential(prov.id)}
|
||||
disabled={savingId === prov.id}
|
||||
className="rounded bg-cinnabar px-3 py-1.5 text-sm text-panel disabled:opacity-40"
|
||||
>
|
||||
{savingId === prov.id
|
||||
? "保存中…"
|
||||
: masked
|
||||
? "更新凭据"
|
||||
: "添加凭据"}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => testConnection(prov.id)}
|
||||
disabled={testingId === prov.id}
|
||||
className="rounded border border-line px-3 py-1.5 text-sm text-ink disabled:opacity-40"
|
||||
>
|
||||
{testingId === prov.id ? "测试中…" : "测试连接"}
|
||||
</button>
|
||||
</div>
|
||||
{result ? (
|
||||
<div className="mt-2 flex items-center gap-2 pl-5">
|
||||
<span
|
||||
className={`text-xs ${result.ok ? "text-pass" : "text-conflict"}`}
|
||||
>
|
||||
{result.ok ? "✓ 已连接" : "✗ 未连接"}
|
||||
</span>
|
||||
<CapabilityBadges caps={result.capabilities} />
|
||||
</div>
|
||||
) : null}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</section>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function CapabilityBadges({ caps }: { caps: CapabilitiesView }) {
|
||||
const badges: { on: boolean; label: string }[] = [
|
||||
{ on: caps.structured_output, label: "结构化" },
|
||||
{ on: caps.prefix_cache, label: "前缀缓存" },
|
||||
{ on: caps.thinking, label: "思考" },
|
||||
];
|
||||
return (
|
||||
<div className="flex gap-1.5">
|
||||
{badges.map((b) => (
|
||||
<span
|
||||
key={b.label}
|
||||
className={`rounded px-2 py-0.5 text-[11px] ${
|
||||
b.on
|
||||
? "bg-[var(--color-cinnabar-wash)] text-cinnabar"
|
||||
: "bg-bg text-ink-soft/50"
|
||||
}`}
|
||||
>
|
||||
{b.label}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
27
apps/web/components/workbench/ChapterAssistant.tsx
Normal file
27
apps/web/components/workbench/ChapterAssistant.tsx
Normal file
@@ -0,0 +1,27 @@
|
||||
// 右栏「本章助手」(UX §6.3)。
|
||||
// M1 无端点暴露注入选择轨迹/四审结果 → 占位说明,不编造 API。
|
||||
export function ChapterAssistant() {
|
||||
return (
|
||||
<aside className="hidden border-l border-line bg-panel p-4 lg:block">
|
||||
<h2 className="text-sm font-semibold text-ink">本章助手</h2>
|
||||
|
||||
<section className="mt-4">
|
||||
<h3 className="text-xs font-semibold uppercase tracking-wide text-ink-soft">
|
||||
本章注入(透明)
|
||||
</h3>
|
||||
<p className="mt-2 rounded border border-dashed border-line bg-bg p-3 text-xs text-ink-soft">
|
||||
M1 暂未接:注入的设定/伏笔选择轨迹尚无对应端点,将在记忆服务接入后展示。
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<section className="mt-4">
|
||||
<h3 className="text-xs font-semibold uppercase tracking-wide text-ink-soft">
|
||||
四审
|
||||
</h3>
|
||||
<p className="mt-2 rounded border border-dashed border-line bg-bg p-3 text-xs text-ink-soft">
|
||||
M2 开放:一致性 / 伏笔 / 文风 / 节奏。
|
||||
</p>
|
||||
</section>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
24
apps/web/components/workbench/ChapterList.tsx
Normal file
24
apps/web/components/workbench/ChapterList.tsx
Normal file
@@ -0,0 +1,24 @@
|
||||
interface ChapterListProps {
|
||||
currentChapterNo: number;
|
||||
}
|
||||
|
||||
// 左栏目录(UX §6.3)。M1 无章节列表端点 → 仅展示当前章占位。
|
||||
export function ChapterList({ currentChapterNo }: ChapterListProps) {
|
||||
return (
|
||||
<aside className="hidden border-r border-line bg-panel py-4 lg:block">
|
||||
<h2 className="px-4 text-xs font-semibold uppercase tracking-wide text-ink-soft">
|
||||
目录
|
||||
</h2>
|
||||
<ul className="mt-2">
|
||||
<li>
|
||||
<span className="flex items-center gap-2 border-l-2 border-cinnabar bg-[var(--color-cinnabar-wash)] px-4 py-2 text-sm text-cinnabar">
|
||||
<span aria-hidden="true">●</span>第 {currentChapterNo} 章
|
||||
</span>
|
||||
</li>
|
||||
</ul>
|
||||
<p className="mt-4 px-4 text-xs text-ink-soft/70">
|
||||
多卷多章目录将在大纲模块开放(后续里程碑)。
|
||||
</p>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
34
apps/web/components/workbench/Editor.tsx
Normal file
34
apps/web/components/workbench/Editor.tsx
Normal file
@@ -0,0 +1,34 @@
|
||||
"use client";
|
||||
|
||||
interface EditorProps {
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
streaming: boolean;
|
||||
}
|
||||
|
||||
// 中栏正文编辑器:宋体、720px 居中、行高 1.9(UX §2.3 / §6.3)。
|
||||
// 流式中显示朱砂光标提示(prefers-reduced-motion 下不闪烁,见 globals.css)。
|
||||
export function Editor({ value, onChange, streaming }: EditorProps) {
|
||||
return (
|
||||
<div className="mx-auto max-w-prose">
|
||||
<label htmlFor="chapter-editor" className="sr-only">
|
||||
正文编辑器
|
||||
</label>
|
||||
<textarea
|
||||
id="chapter-editor"
|
||||
value={value}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
readOnly={streaming}
|
||||
aria-busy={streaming}
|
||||
placeholder="夜色如墨……点击「写本章」让 AI 起草,或直接在此书写。"
|
||||
className="min-h-[60vh] w-full resize-none bg-transparent font-serif text-[18px] leading-[1.9] text-ink placeholder:text-ink-soft/50 focus:outline-none"
|
||||
/>
|
||||
{streaming ? (
|
||||
<span
|
||||
className="typewriter-cursor ml-0.5 inline-block h-[1.2em] w-[2px] translate-y-1 bg-cinnabar align-middle"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
156
apps/web/components/workbench/Workbench.tsx
Normal file
156
apps/web/components/workbench/Workbench.tsx
Normal file
@@ -0,0 +1,156 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
|
||||
import { AppShell } from "@/components/AppShell";
|
||||
import type { ProjectResponse } from "@/lib/api/types";
|
||||
import { useAutosave } from "@/lib/autosave/useAutosave";
|
||||
import { useDraftStream } from "@/lib/stream/useDraftStream";
|
||||
import { ChapterList } from "./ChapterList";
|
||||
import { ChapterAssistant } from "./ChapterAssistant";
|
||||
import { Editor } from "./Editor";
|
||||
|
||||
interface WorkbenchProps {
|
||||
project: ProjectResponse;
|
||||
}
|
||||
|
||||
// M1:单章工作台。章节列表为占位(无章节列表端点);默认第 1 章。
|
||||
const M1_CHAPTER_NO = 1;
|
||||
|
||||
export function Workbench({ project }: WorkbenchProps) {
|
||||
const chapterNo = M1_CHAPTER_NO;
|
||||
const [text, setText] = useState("");
|
||||
const autosave = useAutosave(project.id, chapterNo);
|
||||
const stream = useDraftStream();
|
||||
const lastStreamText = useRef("");
|
||||
|
||||
// 流式 token 累积进编辑器(打字机);停止/结束后已生成部分留在草稿。
|
||||
useEffect(() => {
|
||||
const streamed = stream.state.text;
|
||||
if (
|
||||
(stream.state.phase === "streaming" ||
|
||||
stream.state.phase === "done" ||
|
||||
stream.state.phase === "aborted") &&
|
||||
streamed !== lastStreamText.current
|
||||
) {
|
||||
lastStreamText.current = streamed;
|
||||
setText(streamed);
|
||||
autosave.onChange(streamed);
|
||||
}
|
||||
}, [stream.state.phase, stream.state.text, autosave]);
|
||||
|
||||
const onWrite = (): void => {
|
||||
void stream.start(project.id, chapterNo);
|
||||
};
|
||||
|
||||
const onEditorChange = (value: string): void => {
|
||||
setText(value);
|
||||
autosave.onChange(value);
|
||||
};
|
||||
|
||||
const wordCount = text.length;
|
||||
|
||||
return (
|
||||
<AppShell
|
||||
title={`〈${project.title}〉`}
|
||||
subtitle={`第 ${chapterNo} 章`}
|
||||
>
|
||||
<div className="grid h-[calc(100vh-4rem)] grid-cols-1 lg:grid-cols-[12rem_1fr_18rem]">
|
||||
<ChapterList currentChapterNo={chapterNo} />
|
||||
|
||||
<section className="flex min-w-0 flex-col bg-bg">
|
||||
<div className="flex-1 overflow-auto px-6 py-8">
|
||||
<Editor
|
||||
value={text}
|
||||
onChange={onEditorChange}
|
||||
streaming={stream.isStreaming}
|
||||
/>
|
||||
</div>
|
||||
<Toolbar
|
||||
projectId={project.id}
|
||||
chapterNo={chapterNo}
|
||||
wordCount={wordCount}
|
||||
savedLabel={autosave.savedLabel}
|
||||
saveStatus={autosave.status}
|
||||
streaming={stream.isStreaming}
|
||||
streamError={stream.state.error}
|
||||
onWrite={onWrite}
|
||||
onStop={stream.stop}
|
||||
/>
|
||||
</section>
|
||||
|
||||
<ChapterAssistant />
|
||||
</div>
|
||||
</AppShell>
|
||||
);
|
||||
}
|
||||
|
||||
interface ToolbarProps {
|
||||
projectId: string;
|
||||
chapterNo: number;
|
||||
wordCount: number;
|
||||
savedLabel: string | null;
|
||||
saveStatus: ReturnType<typeof useAutosave>["status"];
|
||||
streaming: boolean;
|
||||
streamError: { code: string; message: string } | null;
|
||||
onWrite: () => void;
|
||||
onStop: () => void;
|
||||
}
|
||||
|
||||
function Toolbar({
|
||||
projectId,
|
||||
chapterNo,
|
||||
wordCount,
|
||||
savedLabel,
|
||||
saveStatus,
|
||||
streaming,
|
||||
streamError,
|
||||
onWrite,
|
||||
onStop,
|
||||
}: ToolbarProps) {
|
||||
return (
|
||||
<div className="border-t border-line bg-panel px-6 py-3">
|
||||
{streamError ? (
|
||||
<p className="mb-2 text-sm text-conflict">
|
||||
写章失败({streamError.code}):{streamError.message}
|
||||
</p>
|
||||
) : null}
|
||||
<div className="flex items-center gap-4">
|
||||
{streaming ? (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onStop}
|
||||
className="rounded border border-conflict px-4 py-2 text-sm text-conflict"
|
||||
>
|
||||
停
|
||||
</button>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onWrite}
|
||||
className="rounded bg-cinnabar px-4 py-2 text-sm text-panel hover:opacity-90"
|
||||
>
|
||||
✍ 写本章
|
||||
</button>
|
||||
)}
|
||||
<span className="font-mono text-xs text-ink-soft">
|
||||
字数 {wordCount.toLocaleString()}
|
||||
</span>
|
||||
<Link
|
||||
href={`/projects/${projectId}/review?chapter=${chapterNo}`}
|
||||
className="rounded border border-cinnabar px-4 py-2 text-sm text-cinnabar hover:bg-[var(--color-cinnabar-wash)]"
|
||||
>
|
||||
审稿 →
|
||||
</Link>
|
||||
<span className="ml-auto font-mono text-xs text-ink-soft">
|
||||
{saveStatus === "saving"
|
||||
? "保存中…"
|
||||
: saveStatus === "error"
|
||||
? "保存失败"
|
||||
: (savedLabel ?? "尚未保存")}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
61
apps/web/lib/autosave/autosave.test.ts
Normal file
61
apps/web/lib/autosave/autosave.test.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { createDebouncedSaver, formatSavedAt } from "./autosave";
|
||||
|
||||
describe("createDebouncedSaver", () => {
|
||||
beforeEach(() => vi.useFakeTimers());
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
it("saves only once after the debounce window for rapid edits", () => {
|
||||
const save = vi.fn().mockResolvedValue(undefined);
|
||||
const saver = createDebouncedSaver(save, 1000);
|
||||
saver.schedule("a");
|
||||
saver.schedule("ab");
|
||||
saver.schedule("abc");
|
||||
expect(save).not.toHaveBeenCalled();
|
||||
vi.advanceTimersByTime(1000);
|
||||
expect(save).toHaveBeenCalledTimes(1);
|
||||
expect(save).toHaveBeenCalledWith("abc");
|
||||
});
|
||||
|
||||
it("flush triggers the pending save immediately", () => {
|
||||
const save = vi.fn().mockResolvedValue(undefined);
|
||||
const saver = createDebouncedSaver(save, 1000);
|
||||
saver.schedule("hello");
|
||||
saver.flush();
|
||||
expect(save).toHaveBeenCalledTimes(1);
|
||||
expect(save).toHaveBeenCalledWith("hello");
|
||||
// No double-fire when the timer would have elapsed.
|
||||
vi.advanceTimersByTime(1000);
|
||||
expect(save).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("cancel prevents a scheduled save", () => {
|
||||
const save = vi.fn().mockResolvedValue(undefined);
|
||||
const saver = createDebouncedSaver(save, 1000);
|
||||
saver.schedule("x");
|
||||
saver.cancel();
|
||||
vi.advanceTimersByTime(2000);
|
||||
expect(save).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("each new schedule resets the timer (only last value persists)", () => {
|
||||
const save = vi.fn().mockResolvedValue(undefined);
|
||||
const saver = createDebouncedSaver(save, 1000);
|
||||
saver.schedule("one");
|
||||
vi.advanceTimersByTime(800);
|
||||
saver.schedule("two");
|
||||
vi.advanceTimersByTime(800);
|
||||
expect(save).not.toHaveBeenCalled();
|
||||
vi.advanceTimersByTime(200);
|
||||
expect(save).toHaveBeenCalledTimes(1);
|
||||
expect(save).toHaveBeenCalledWith("two");
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatSavedAt", () => {
|
||||
it("formats as 保存于 hh:mm zero-padded", () => {
|
||||
const d = new Date(2026, 5, 18, 9, 4);
|
||||
expect(formatSavedAt(d)).toBe("保存于 09:04");
|
||||
});
|
||||
});
|
||||
52
apps/web/lib/autosave/autosave.ts
Normal file
52
apps/web/lib/autosave/autosave.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
// 自动保存的纯逻辑:防抖调度器 + 时间格式化。与 React 解耦,便于单测。
|
||||
|
||||
export const AUTOSAVE_DELAY_MS = 1200;
|
||||
|
||||
export type SaveFn = (text: string) => Promise<void>;
|
||||
|
||||
export interface DebouncedSaver {
|
||||
schedule: (text: string) => void;
|
||||
flush: () => void;
|
||||
cancel: () => void;
|
||||
}
|
||||
|
||||
// 防抖:最后一次输入静默 delayMs 后才真正保存。flush 立即触发待保存项。
|
||||
export function createDebouncedSaver(
|
||||
save: SaveFn,
|
||||
delayMs: number = AUTOSAVE_DELAY_MS,
|
||||
): DebouncedSaver {
|
||||
let timer: ReturnType<typeof setTimeout> | null = null;
|
||||
let pending: string | null = null;
|
||||
|
||||
const run = (): void => {
|
||||
if (pending === null) return;
|
||||
const text = pending;
|
||||
pending = null;
|
||||
timer = null;
|
||||
void save(text);
|
||||
};
|
||||
|
||||
return {
|
||||
schedule(text: string): void {
|
||||
pending = text;
|
||||
if (timer !== null) clearTimeout(timer);
|
||||
timer = setTimeout(run, delayMs);
|
||||
},
|
||||
flush(): void {
|
||||
if (timer !== null) clearTimeout(timer);
|
||||
run();
|
||||
},
|
||||
cancel(): void {
|
||||
if (timer !== null) clearTimeout(timer);
|
||||
timer = null;
|
||||
pending = null;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// 「保存于 hh:mm」标签。
|
||||
export function formatSavedAt(date: Date): string {
|
||||
const hh = String(date.getHours()).padStart(2, "0");
|
||||
const mm = String(date.getMinutes()).padStart(2, "0");
|
||||
return `保存于 ${hh}:${mm}`;
|
||||
}
|
||||
74
apps/web/lib/autosave/useAutosave.ts
Normal file
74
apps/web/lib/autosave/useAutosave.ts
Normal file
@@ -0,0 +1,74 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
|
||||
import { api } from "@/lib/api/client";
|
||||
import { useToast } from "@/components/Toast";
|
||||
import {
|
||||
AUTOSAVE_DELAY_MS,
|
||||
createDebouncedSaver,
|
||||
formatSavedAt,
|
||||
type DebouncedSaver,
|
||||
} from "./autosave";
|
||||
|
||||
export type SaveStatus = "idle" | "saving" | "saved" | "error";
|
||||
|
||||
export interface UseAutosave {
|
||||
status: SaveStatus;
|
||||
savedLabel: string | null;
|
||||
onChange: (text: string) => void;
|
||||
flush: () => void;
|
||||
}
|
||||
|
||||
// 防抖自动保存草稿:乐观置 saving → PUT 成功置 saved(落「保存于 hh:mm」);
|
||||
// 失败回滚状态 + toast,不丢正文(已在编辑器里)。
|
||||
export function useAutosave(
|
||||
projectId: string,
|
||||
chapterNo: number,
|
||||
): UseAutosave {
|
||||
const [status, setStatus] = useState<SaveStatus>("idle");
|
||||
const [savedLabel, setSavedLabel] = useState<string | null>(null);
|
||||
const toast = useToast();
|
||||
const lastSavedRef = useRef<string | null>(null);
|
||||
|
||||
const save = useCallback(
|
||||
async (text: string): Promise<void> => {
|
||||
if (text === lastSavedRef.current) return;
|
||||
setStatus("saving");
|
||||
const { error } = await api.PUT(
|
||||
"/projects/{project_id}/chapters/{chapter_no}/draft",
|
||||
{
|
||||
params: { path: { project_id: projectId, chapter_no: chapterNo } },
|
||||
body: { text },
|
||||
},
|
||||
);
|
||||
if (error) {
|
||||
setStatus("error");
|
||||
toast("自动保存失败,稍后重试(正文未丢失)", "error");
|
||||
return;
|
||||
}
|
||||
lastSavedRef.current = text;
|
||||
setSavedLabel(formatSavedAt(new Date()));
|
||||
setStatus("saved");
|
||||
},
|
||||
[projectId, chapterNo, toast],
|
||||
);
|
||||
|
||||
const saver: DebouncedSaver = useMemo(
|
||||
() => createDebouncedSaver(save, AUTOSAVE_DELAY_MS),
|
||||
[save],
|
||||
);
|
||||
|
||||
useEffect(() => () => saver.cancel(), [saver]);
|
||||
|
||||
const onChange = useCallback(
|
||||
(text: string) => {
|
||||
saver.schedule(text);
|
||||
},
|
||||
[saver],
|
||||
);
|
||||
|
||||
const flush = useCallback(() => saver.flush(), [saver]);
|
||||
|
||||
return { status, savedLabel, onChange, flush };
|
||||
}
|
||||
16
apps/web/lib/settings/providers.ts
Normal file
16
apps/web/lib/settings/providers.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
// 已知提供商(UX §6.10)。后端按 provider 字符串识别;这里只是 UI 候选列表。
|
||||
export const KNOWN_PROVIDERS: { id: string; label: string }[] = [
|
||||
{ id: "anthropic", label: "Anthropic" },
|
||||
{ id: "deepseek", label: "DeepSeek" },
|
||||
{ id: "kimi", label: "Kimi" },
|
||||
{ id: "openai", label: "OpenAI" },
|
||||
{ id: "qwen", label: "通义千问" },
|
||||
{ id: "glm", label: "智谱 GLM" },
|
||||
{ id: "gemini", label: "Gemini" },
|
||||
];
|
||||
|
||||
export const TIER_LABELS: Record<string, string> = {
|
||||
writer: "写手档",
|
||||
analyst: "分析档",
|
||||
light: "轻量档",
|
||||
};
|
||||
96
apps/web/lib/stream/sse.test.ts
Normal file
96
apps/web/lib/stream/sse.test.ts
Normal file
@@ -0,0 +1,96 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
SseFrameBuffer,
|
||||
initialStreamState,
|
||||
parseSseBlock,
|
||||
reduceStream,
|
||||
type SseEvent,
|
||||
} from "./sse";
|
||||
|
||||
describe("parseSseBlock", () => {
|
||||
it("parses a token frame", () => {
|
||||
const evt = parseSseBlock('event:token\ndata:{"text":"夜"}');
|
||||
expect(evt).toEqual({ event: "token", data: { text: "夜" } });
|
||||
});
|
||||
|
||||
it("parses a done frame", () => {
|
||||
const evt = parseSseBlock('event:done\ndata:{"length":12}');
|
||||
expect(evt).toEqual({ event: "done", data: { length: 12 } });
|
||||
});
|
||||
|
||||
it("parses an error frame with request_id", () => {
|
||||
const evt = parseSseBlock(
|
||||
'event:error\ndata:{"code":"INTERNAL","message":"boom","request_id":"r1"}',
|
||||
);
|
||||
expect(evt).toEqual({
|
||||
event: "error",
|
||||
data: { code: "INTERNAL", message: "boom", request_id: "r1" },
|
||||
});
|
||||
});
|
||||
|
||||
it("ignores comment/heartbeat lines and tolerates leading space after colon", () => {
|
||||
const evt = parseSseBlock(': keep-alive\nevent: token\ndata: {"text":"x"}');
|
||||
expect(evt).toEqual({ event: "token", data: { text: "x" } });
|
||||
});
|
||||
|
||||
it("returns null for unknown event types", () => {
|
||||
expect(parseSseBlock('event:section\ndata:{"x":1}')).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null for malformed json", () => {
|
||||
expect(parseSseBlock("event:token\ndata:{not json")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("SseFrameBuffer", () => {
|
||||
it("emits complete blocks split by blank line and buffers the tail", () => {
|
||||
const buf = new SseFrameBuffer();
|
||||
const first = buf.push('event:token\ndata:{"text":"a"}\n\nevent:tok');
|
||||
expect(first).toEqual([{ event: "token", data: { text: "a" } }]);
|
||||
const second = buf.push('en\ndata:{"text":"b"}\n\n');
|
||||
expect(second).toEqual([{ event: "token", data: { text: "b" } }]);
|
||||
});
|
||||
|
||||
it("handles CRLF boundaries", () => {
|
||||
const buf = new SseFrameBuffer();
|
||||
const out = buf.push('event:token\r\ndata:{"text":"z"}\r\n\r\n');
|
||||
expect(out).toEqual([{ event: "token", data: { text: "z" } }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("reduceStream", () => {
|
||||
it("accumulates token text and marks streaming", () => {
|
||||
const tokens: SseEvent[] = [
|
||||
{ event: "token", data: { text: "夜色" } },
|
||||
{ event: "token", data: { text: "如墨" } },
|
||||
];
|
||||
const state = tokens.reduce(reduceStream, initialStreamState);
|
||||
expect(state.text).toBe("夜色如墨");
|
||||
expect(state.phase).toBe("streaming");
|
||||
});
|
||||
|
||||
it("marks done on done event preserving text", () => {
|
||||
let s = reduceStream(initialStreamState, {
|
||||
event: "token",
|
||||
data: { text: "abc" },
|
||||
});
|
||||
s = reduceStream(s, { event: "done", data: { length: 3 } });
|
||||
expect(s.phase).toBe("done");
|
||||
expect(s.text).toBe("abc");
|
||||
});
|
||||
|
||||
it("captures error and retains partial text", () => {
|
||||
let s = reduceStream(initialStreamState, {
|
||||
event: "token",
|
||||
data: { text: "partial" },
|
||||
});
|
||||
s = reduceStream(s, {
|
||||
event: "error",
|
||||
data: { code: "LLM_UNAVAILABLE", message: "no key" },
|
||||
});
|
||||
expect(s.phase).toBe("error");
|
||||
expect(s.text).toBe("partial");
|
||||
expect(s.error?.code).toBe("LLM_UNAVAILABLE");
|
||||
});
|
||||
});
|
||||
106
apps/web/lib/stream/sse.ts
Normal file
106
apps/web/lib/stream/sse.ts
Normal file
@@ -0,0 +1,106 @@
|
||||
// SSE 帧解析 + 草稿流归一(对齐 C3 / ARCH §7.3)。
|
||||
// 帧格式:`event:<token|done|error>\ndata:<json>\n\n`。
|
||||
// 纯逻辑,便于单测(不依赖浏览器/DOM)。
|
||||
|
||||
export interface TokenEvent {
|
||||
event: "token";
|
||||
data: { text: string };
|
||||
}
|
||||
export interface DoneEvent {
|
||||
event: "done";
|
||||
data: { length: number };
|
||||
}
|
||||
export interface ErrorEvent {
|
||||
event: "error";
|
||||
data: { code: string; message: string; request_id?: string | null };
|
||||
}
|
||||
export type SseEvent = TokenEvent | DoneEvent | ErrorEvent;
|
||||
|
||||
const KNOWN_EVENTS = new Set(["token", "done", "error"]);
|
||||
|
||||
// 把一个完整 SSE 块(多行)解析成事件;无法解析则返回 null(跳过)。
|
||||
export function parseSseBlock(block: string): SseEvent | null {
|
||||
let event = "";
|
||||
const dataLines: string[] = [];
|
||||
for (const rawLine of block.split("\n")) {
|
||||
const line = rawLine.replace(/\r$/, "");
|
||||
if (line.startsWith(":")) continue; // 注释/心跳
|
||||
const sep = line.indexOf(":");
|
||||
if (sep === -1) continue;
|
||||
const field = line.slice(0, sep);
|
||||
const value = line.slice(sep + 1).replace(/^ /, "");
|
||||
if (field === "event") event = value;
|
||||
else if (field === "data") dataLines.push(value);
|
||||
}
|
||||
if (!KNOWN_EVENTS.has(event) || dataLines.length === 0) return null;
|
||||
let data: unknown;
|
||||
try {
|
||||
data = JSON.parse(dataLines.join("\n"));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
return { event, data } as SseEvent;
|
||||
}
|
||||
|
||||
// 增量缓冲:吃进一段文本,吐出已完成的事件块(以空行分隔),保留未完成尾部。
|
||||
export class SseFrameBuffer {
|
||||
private buf = "";
|
||||
|
||||
push(chunk: string): SseEvent[] {
|
||||
this.buf += chunk;
|
||||
const events: SseEvent[] = [];
|
||||
let idx: number;
|
||||
// 块之间以空行(\n\n,兼容 \r\n\r\n)分隔。
|
||||
while ((idx = this.findBoundary(this.buf)) !== -1) {
|
||||
const block = this.buf.slice(0, idx.valueOf());
|
||||
this.buf = this.buf.slice(this.boundaryEnd(this.buf, idx));
|
||||
const evt = parseSseBlock(block);
|
||||
if (evt) events.push(evt);
|
||||
}
|
||||
return events;
|
||||
}
|
||||
|
||||
private findBoundary(s: string): number {
|
||||
const a = s.indexOf("\n\n");
|
||||
const b = s.indexOf("\r\n\r\n");
|
||||
if (a === -1) return b;
|
||||
if (b === -1) return a;
|
||||
return Math.min(a, b);
|
||||
}
|
||||
|
||||
private boundaryEnd(s: string, idx: number): number {
|
||||
return s.startsWith("\r\n\r\n", idx) ? idx + 4 : idx + 2;
|
||||
}
|
||||
}
|
||||
|
||||
export type StreamPhase = "idle" | "streaming" | "done" | "error" | "aborted";
|
||||
|
||||
export interface StreamState {
|
||||
phase: StreamPhase;
|
||||
text: string;
|
||||
error: { code: string; message: string; request_id?: string | null } | null;
|
||||
}
|
||||
|
||||
export const initialStreamState: StreamState = {
|
||||
phase: "idle",
|
||||
text: "",
|
||||
error: null,
|
||||
};
|
||||
|
||||
// 纯 reducer:把单个事件折叠进状态(打字机文本累积)。
|
||||
export function reduceStream(state: StreamState, event: SseEvent): StreamState {
|
||||
switch (event.event) {
|
||||
case "token":
|
||||
return {
|
||||
...state,
|
||||
phase: "streaming",
|
||||
text: state.text + event.data.text,
|
||||
};
|
||||
case "done":
|
||||
return { ...state, phase: "done" };
|
||||
case "error":
|
||||
return { ...state, phase: "error", error: event.data };
|
||||
default:
|
||||
return state;
|
||||
}
|
||||
}
|
||||
122
apps/web/lib/stream/useDraftStream.ts
Normal file
122
apps/web/lib/stream/useDraftStream.ts
Normal file
@@ -0,0 +1,122 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useReducer, useRef } from "react";
|
||||
|
||||
import { API_BASE_PUBLIC } from "@/lib/api/config";
|
||||
import {
|
||||
SseFrameBuffer,
|
||||
initialStreamState,
|
||||
reduceStream,
|
||||
type StreamState,
|
||||
} from "./sse";
|
||||
|
||||
type Action =
|
||||
| { type: "start" }
|
||||
| { type: "events"; events: ReturnType<SseFrameBuffer["push"]> }
|
||||
| { type: "abort" }
|
||||
| { type: "fail"; code: string; message: string }
|
||||
| { type: "reset"; text: string };
|
||||
|
||||
function reducer(state: StreamState, action: Action): StreamState {
|
||||
switch (action.type) {
|
||||
case "start":
|
||||
return { phase: "streaming", text: "", error: null };
|
||||
case "events":
|
||||
return action.events.reduce(reduceStream, state);
|
||||
case "abort":
|
||||
return { ...state, phase: "aborted" };
|
||||
case "fail":
|
||||
return {
|
||||
...state,
|
||||
phase: "error",
|
||||
error: { code: action.code, message: action.message },
|
||||
};
|
||||
case "reset":
|
||||
return { ...initialStreamState, text: action.text };
|
||||
default:
|
||||
return state;
|
||||
}
|
||||
}
|
||||
|
||||
export interface UseDraftStream {
|
||||
state: StreamState;
|
||||
isStreaming: boolean;
|
||||
start: (projectId: string, chapterNo: number) => Promise<void>;
|
||||
stop: () => void;
|
||||
reset: (text: string) => void;
|
||||
}
|
||||
|
||||
// 消费 POST .../draft 的 SSE 流。用 fetch+ReadableStream(EventSource 不支持 POST)。
|
||||
// "停" = abort 连接(已生成部分保留在 state.text,由调用方落入草稿)。
|
||||
export function useDraftStream(): UseDraftStream {
|
||||
const [state, dispatch] = useReducer(reducer, initialStreamState);
|
||||
const controllerRef = useRef<AbortController | null>(null);
|
||||
|
||||
const stop = useCallback(() => {
|
||||
controllerRef.current?.abort();
|
||||
controllerRef.current = null;
|
||||
dispatch({ type: "abort" });
|
||||
}, []);
|
||||
|
||||
const reset = useCallback((text: string) => {
|
||||
dispatch({ type: "reset", text });
|
||||
}, []);
|
||||
|
||||
const start = useCallback(async (projectId: string, chapterNo: number) => {
|
||||
const controller = new AbortController();
|
||||
controllerRef.current = controller;
|
||||
dispatch({ type: "start" });
|
||||
try {
|
||||
const res = await fetch(
|
||||
`${API_BASE_PUBLIC}/projects/${projectId}/chapters/${chapterNo}/draft`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: { Accept: "text/event-stream" },
|
||||
signal: controller.signal,
|
||||
},
|
||||
);
|
||||
if (!res.ok || !res.body) {
|
||||
// 流前错误(如无凭据 → 503 LLM_UNAVAILABLE,JSON 信封而非帧)。
|
||||
let code = "STREAM_FAILED";
|
||||
let message = `写章请求失败(${res.status})`;
|
||||
try {
|
||||
const body = (await res.json()) as {
|
||||
error?: { code?: string; message?: string };
|
||||
};
|
||||
if (body.error?.code) code = body.error.code;
|
||||
if (body.error?.message) message = body.error.message;
|
||||
} catch {
|
||||
// 非 JSON 信封,沿用默认文案。
|
||||
}
|
||||
dispatch({ type: "fail", code, message });
|
||||
return;
|
||||
}
|
||||
const reader = res.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
const buffer = new SseFrameBuffer();
|
||||
for (;;) {
|
||||
const { value, done } = await reader.read();
|
||||
if (done) break;
|
||||
const events = buffer.push(decoder.decode(value, { stream: true }));
|
||||
if (events.length > 0) dispatch({ type: "events", events });
|
||||
}
|
||||
} catch (err: unknown) {
|
||||
if (err instanceof DOMException && err.name === "AbortError") {
|
||||
// 用户主动停止:state 已置 aborted。
|
||||
return;
|
||||
}
|
||||
const message = err instanceof Error ? err.message : "未知网络错误";
|
||||
dispatch({ type: "fail", code: "NETWORK", message });
|
||||
} finally {
|
||||
controllerRef.current = null;
|
||||
}
|
||||
}, []);
|
||||
|
||||
return {
|
||||
state,
|
||||
isStreaming: state.phase === "streaming",
|
||||
start,
|
||||
stop,
|
||||
reset,
|
||||
};
|
||||
}
|
||||
81
apps/web/lib/wizard/wizard.test.ts
Normal file
81
apps/web/lib/wizard/wizard.test.ts
Normal file
@@ -0,0 +1,81 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
canAdvance,
|
||||
canSubmit,
|
||||
clampStep,
|
||||
emptyWizardForm,
|
||||
toCreateRequest,
|
||||
WIZARD_STEPS,
|
||||
type WizardForm,
|
||||
} from "./wizard";
|
||||
|
||||
describe("wizard step gating", () => {
|
||||
it("blocks advancing past step 1 without a title", () => {
|
||||
expect(canAdvance(1, emptyWizardForm)).toBe(false);
|
||||
});
|
||||
|
||||
it("allows advancing step 1 once title is set", () => {
|
||||
expect(canAdvance(1, { ...emptyWizardForm, title: "逐光而行" })).toBe(true);
|
||||
});
|
||||
|
||||
it("allows advancing later steps even when fields are empty", () => {
|
||||
expect(canAdvance(3, emptyWizardForm)).toBe(true);
|
||||
});
|
||||
|
||||
it("clamps step within bounds", () => {
|
||||
expect(clampStep(0)).toBe(1);
|
||||
expect(clampStep(WIZARD_STEPS + 3)).toBe(WIZARD_STEPS);
|
||||
expect(clampStep(3)).toBe(3);
|
||||
});
|
||||
|
||||
it("requires a title to submit", () => {
|
||||
expect(canSubmit(emptyWizardForm)).toBe(false);
|
||||
expect(canSubmit({ ...emptyWizardForm, title: "x" })).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("toCreateRequest", () => {
|
||||
it("maps form to snake_case request, nulling empty optionals", () => {
|
||||
const form: WizardForm = {
|
||||
title: " 逐光而行 ",
|
||||
genre: "玄幻",
|
||||
logline: "",
|
||||
sellingPoints: ["逆袭", "系统流"],
|
||||
structure: "三幕",
|
||||
premise: " ",
|
||||
theme: "抗争",
|
||||
};
|
||||
expect(toCreateRequest(form)).toEqual({
|
||||
title: "逐光而行",
|
||||
genre: "玄幻",
|
||||
logline: null,
|
||||
premise: null,
|
||||
theme: "抗争",
|
||||
selling_points: ["逆袭", "系统流"],
|
||||
structure: "三幕",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// wizard→create 流程:归一后的请求体经 mock 客户端提交,返回新建项目 id。
|
||||
describe("wizard create flow (mocked client)", () => {
|
||||
it("submits the normalized body and resolves a project id", async () => {
|
||||
const post = async (
|
||||
_path: string,
|
||||
opts: { body: ReturnType<typeof toCreateRequest> },
|
||||
): Promise<{ data: { id: string }; error: null }> => {
|
||||
expect(opts.body.title).toBe("青冥录");
|
||||
expect(opts.body.selling_points).toEqual(["群像"]);
|
||||
return { data: { id: "proj-123" }, error: null };
|
||||
};
|
||||
|
||||
const form: WizardForm = {
|
||||
...emptyWizardForm,
|
||||
title: "青冥录",
|
||||
sellingPoints: ["群像"],
|
||||
};
|
||||
const { data } = await post("/projects", { body: toCreateRequest(form) });
|
||||
expect(data.id).toBe("proj-123");
|
||||
});
|
||||
});
|
||||
62
apps/web/lib/wizard/wizard.ts
Normal file
62
apps/web/lib/wizard/wizard.ts
Normal file
@@ -0,0 +1,62 @@
|
||||
import type { ProjectCreateRequest } from "@/lib/api/types";
|
||||
|
||||
// 立项向导 5 步(UX §6.2)。表单状态用字符串/数组,提交时归一为 ProjectCreateRequest。
|
||||
export interface WizardForm {
|
||||
title: string;
|
||||
genre: string;
|
||||
logline: string;
|
||||
sellingPoints: string[];
|
||||
structure: string;
|
||||
premise: string;
|
||||
theme: string;
|
||||
}
|
||||
|
||||
export const WIZARD_STEPS = 5;
|
||||
|
||||
export const emptyWizardForm: WizardForm = {
|
||||
title: "",
|
||||
genre: "",
|
||||
logline: "",
|
||||
sellingPoints: [],
|
||||
structure: "",
|
||||
premise: "",
|
||||
theme: "",
|
||||
};
|
||||
|
||||
export const GENRES = ["玄幻", "仙侠", "都市", "科幻", "历史", "悬疑"];
|
||||
export const STRUCTURES = ["三幕", "故事圈", "雪花"];
|
||||
export const SELLING_POINT_PRESETS = ["逆袭", "打脸", "系统流", "双男主", "群像"];
|
||||
|
||||
// 每一步可否前进:仅第 1 步(书名)必填,其余可空着继续(草稿式立项)。
|
||||
export function canAdvance(step: number, form: WizardForm): boolean {
|
||||
if (step === 1) return form.title.trim().length > 0;
|
||||
return true;
|
||||
}
|
||||
|
||||
// 整个向导可否提交:书名必填。
|
||||
export function canSubmit(form: WizardForm): boolean {
|
||||
return form.title.trim().length > 0;
|
||||
}
|
||||
|
||||
export function clampStep(step: number): number {
|
||||
if (step < 1) return 1;
|
||||
if (step > WIZARD_STEPS) return WIZARD_STEPS;
|
||||
return step;
|
||||
}
|
||||
|
||||
// 归一为后端请求体(snake_case,空值落 null/省略)。
|
||||
export function toCreateRequest(form: WizardForm): ProjectCreateRequest {
|
||||
const trim = (s: string): string | null => {
|
||||
const v = s.trim();
|
||||
return v.length > 0 ? v : null;
|
||||
};
|
||||
return {
|
||||
title: form.title.trim(),
|
||||
genre: trim(form.genre),
|
||||
logline: trim(form.logline),
|
||||
premise: trim(form.premise),
|
||||
theme: trim(form.theme),
|
||||
selling_points: form.sellingPoints,
|
||||
structure: trim(form.structure),
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user