圆桌草稿持久化:localStorage 迁至后端 MySQL

新增 /api/roundtable-drafts 草稿 CRUD 与会话级推荐历史;前端 useDraftPersistence 改走 api/drafts,删除本地 drafts.ts。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
董宏凯andCursor committed 2026-05-31 00:23:25 +08:00
1 parent 24e92c437d
commit 838cae0d2d
16 files changed
+1410 -480

No files matched your search

@@ -0,0 +1,211 @@
/**
* Backend-persisted draft storage for /page/roundtable/planning.
*
* One draft = one full roundtable session (Step 1 intent + Step 2 multi-agent
* roundtable). Persisted server-side (MySQL) bound to the logged-in user, so it
* follows the account across devices/sessions — replacing the old browser-only
* `localStorage` storage (see git history of `utils/drafts.ts`).
*
* The list endpoint returns lightweight metadata only; the full step1/step2
* snapshots are fetched on demand via {@link getDraft}. This keeps the history
* dropdown cheap and guarantees a load always reads the freshest server copy
* (the old localStorage path loaded from a possibly-stale in-memory array).
*/
import { apiFetch } from "@/core/api/fetch-client";
import { getBackendBaseURL } from "@/core/config";
import type { IntentSummary } from "@/roundtable-planning/api/intent";
import type { ThreadIdMap } from "@/roundtable-planning/api/multi-agent";
/**
* Step 1 snapshot. Shapes for the chat / timeline lists stay loose (`unknown[]`)
* because their inline types in the hooks are wide; the hook casts on hydrate.
*/
export interface DraftStep1Snapshot {
intentThreadId: string | null;
intentReady: IntentSummary | null;
interactiveMessages: unknown[];
timelineEntries: unknown[];
}
export interface DraftStep2Snapshot {
threadIds: ThreadIdMap | null;
coordinatorName: string | null;
step2RoundtableDialogues: unknown[];
lastLeaderContent: string;
hasConsensus: boolean;
consensusPercentage: number;
budgetLimit: number;
/** Per-seat stub AI messages for the sandbox `write-file:` virtual URL loader. */
seatStubMessages?: Record<string, unknown[]>;
}
/** Lightweight metadata row returned by the list endpoint. */
export interface DraftMeta {
id: string;
/** Auto-derived task summary (objective → first user message → timestamp). */
title: string;
furthestStep: 1 | 2 | 3;
createdAt: string;
updatedAt: string;
}
/** Full record including the step snapshots. */
export interface DraftRecord extends DraftMeta {
step1: DraftStep1Snapshot | null;
step2: DraftStep2Snapshot | null;
}
/** Fields accepted when creating a draft. */
export interface DraftCreatePayload {
/** Optional stable id so the client can keep one id across create + updates. */
id?: string;
title: string;
furthestStep: 1 | 2 | 3;
step1: DraftStep1Snapshot;
step2: DraftStep2Snapshot;
}
/** Partial update — send only what changed. Omitting `title` preserves a rename. */
export interface DraftUpdatePayload {
title?: string;
furthestStep?: 1 | 2 | 3;
step1?: DraftStep1Snapshot;
step2?: DraftStep2Snapshot;
}
const BASE = () => `${getBackendBaseURL()}/api/roundtable-drafts`;
async function readJson<T>(res: Response, ctx: string): Promise<T> {
if (!res.ok) {
const text = await res.text().catch(() => "");
throw new Error(`${ctx} failed (${res.status}): ${text}`);
}
return (await res.json()) as T;
}
// ── server ⇄ client field mapping ──────────────────────────────────────────
// Backend uses snake_case (furthest_step / created_at / updated_at); the rest
// of the frontend reads camelCase. Map at this boundary so callers stay clean.
interface ServerDraftMeta {
id: string;
title: string;
furthest_step: number;
created_at: string | null;
updated_at: string | null;
}
interface ServerDraftFull extends ServerDraftMeta {
step1: DraftStep1Snapshot | null;
step2: DraftStep2Snapshot | null;
}
function toMeta(s: ServerDraftMeta): DraftMeta {
const step = Math.min(3, Math.max(1, s.furthest_step || 1)) as 1 | 2 | 3;
return {
id: s.id,
title: s.title ?? "",
furthestStep: step,
createdAt: s.created_at ?? "",
updatedAt: s.updated_at ?? "",
};
}
function toRecord(s: ServerDraftFull): DraftRecord {
return { ...toMeta(s), step1: s.step1 ?? null, step2: s.step2 ?? null };
}
function fromCreate(p: DraftCreatePayload) {
return {
...(p.id ? { id: p.id } : {}),
title: p.title,
furthest_step: p.furthestStep,
step1: p.step1,
step2: p.step2,
};
}
function fromUpdate(p: DraftUpdatePayload) {
const out: Record<string, unknown> = {};
if (p.title !== undefined) out.title = p.title;
if (p.furthestStep !== undefined) out.furthest_step = p.furthestStep;
if (p.step1 !== undefined) out.step1 = p.step1;
if (p.step2 !== undefined) out.step2 = p.step2;
return out;
}
// ── CRUD ────────────────────────────────────────────────────────────────────
/** List the current user's drafts, newest first (lightweight metadata only). */
export async function listDrafts(): Promise<DraftMeta[]> {
const res = await apiFetch(BASE(), { method: "GET" });
const data = await readJson<{ drafts: ServerDraftMeta[] }>(res, "list drafts");
return (data.drafts ?? []).map(toMeta);
}
/** Fetch the full draft (incl. step1/step2). Returns null on 404. */
export async function getDraft(id: string): Promise<DraftRecord | null> {
const res = await apiFetch(`${BASE()}/${encodeURIComponent(id)}`, { method: "GET" });
if (res.status === 404) return null;
const data = await readJson<ServerDraftFull>(res, "get draft");
return toRecord(data);
}
export async function createDraft(payload: DraftCreatePayload): Promise<DraftRecord> {
const res = await apiFetch(BASE(), {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(fromCreate(payload)),
});
const data = await readJson<ServerDraftFull>(res, "create draft");
return toRecord(data);
}
export async function updateDraft(id: string, patch: DraftUpdatePayload): Promise<DraftRecord | null> {
const res = await apiFetch(`${BASE()}/${encodeURIComponent(id)}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(fromUpdate(patch)),
});
if (res.status === 404) return null;
const data = await readJson<ServerDraftFull>(res, "update draft");
return toRecord(data);
}
export async function deleteDraft(id: string): Promise<void> {
const res = await apiFetch(`${BASE()}/${encodeURIComponent(id)}`, { method: "DELETE" });
if (!res.ok && res.status !== 404) {
const text = await res.text().catch(() => "");
throw new Error(`delete draft failed (${res.status}): ${text}`);
}
}
/**
* Derive a short task-summary name from whatever the user supplied so far.
* Preference: intent objective → first user message → timestamp. Trimmed to
* ~40 chars so dropdown rows stay scannable. (Ported from the old utils/drafts.)
*/
export function deriveDraftName(args: {
intentReady?: IntentSummary | null;
interactiveMessages?: unknown[];
}): string {
const MAX = 40;
const truncate = (s: string) => (s.length > MAX ? s.slice(0, MAX) + "…" : s);
const objective = args.intentReady?.objective?.trim();
if (objective) return truncate(objective);
if (Array.isArray(args.interactiveMessages)) {
for (const m of args.interactiveMessages) {
if (!m || typeof m !== "object") continue;
const obj = m as Record<string, unknown>;
if (obj.sender === "user" && typeof obj.content === "string" && obj.content.trim()) {
return truncate(obj.content.trim());
}
}
}
return `未命名草稿 ${new Date().toLocaleString("zh-CN", { hour12: false })}`;
}
@@ -198,6 +198,104 @@ function extractAiTextDelta(parsed: unknown): { text: string; id: string } | nul
return { text, id };
}
/**
* One persisted recommendation run, bound to a draft/session. Returned by
* {@link listRecommendHistory}; lets the dialog show "last recommendation for
* this session" before deciding whether to re-analyze.
*/
export interface RecommendHistoryItem {
id: string;
draftId: string;
objective: string;
/** How the run ended on the backend: "done" | "fallback" | "asking" | "error". */
status: string;
model: string | null;
rationale: string | null;
picks: RecommendPick[];
/** Candidate-pool snapshot captured at recommend time. */
candidates: RecommendCandidate[];
createdAt: string;
}
/** Payload persisted after a recommendation run completes. */
export interface SaveRecommendHistoryPayload {
objective: string;
status: string;
model?: string;
rationale?: string;
picks: RecommendPick[];
candidates: RecommendCandidate[];
}
interface ServerHistoryItem {
id: string;
draft_id: string;
objective: string;
status: string;
model: string | null;
rationale: string | null;
picks: RecommendPick[];
candidates: RecommendCandidate[];
created_at: string | null;
}
function toHistoryItem(s: ServerHistoryItem): RecommendHistoryItem {
return {
id: s.id,
draftId: s.draft_id,
objective: s.objective ?? "",
status: s.status ?? "done",
model: s.model ?? null,
rationale: s.rationale ?? null,
picks: Array.isArray(s.picks) ? s.picks : [],
candidates: Array.isArray(s.candidates) ? s.candidates : [],
createdAt: s.created_at ?? "",
};
}
/** List a draft's recommendation history, newest first. */
export async function listRecommendHistory(draftId: string): Promise<RecommendHistoryItem[]> {
const res = await apiFetch(
`${getBackendBaseURL()}/api/roundtable-drafts/${encodeURIComponent(draftId)}/recommendations`,
{ method: "GET" },
);
if (res.status === 404) return [];
if (!res.ok) {
const text = await res.text().catch(() => "");
throw new Error(`list recommend history failed (${res.status}): ${text}`);
}
const data = (await res.json()) as { history: ServerHistoryItem[] };
return (data.history ?? []).map(toHistoryItem);
}
/** Append one recommendation run to a draft's history. */
export async function saveRecommendHistory(
draftId: string,
payload: SaveRecommendHistoryPayload,
): Promise<RecommendHistoryItem | null> {
const res = await apiFetch(
`${getBackendBaseURL()}/api/roundtable-drafts/${encodeURIComponent(draftId)}/recommendations`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
objective: payload.objective,
status: payload.status,
model: payload.model,
rationale: payload.rationale,
picks: payload.picks,
candidates: payload.candidates,
}),
},
);
if (res.status === 404) return null; // draft gone — skip silently
if (!res.ok) {
const text = await res.text().catch(() => "");
throw new Error(`save recommend history failed (${res.status}): ${text}`);
}
return toHistoryItem((await res.json()) as ServerHistoryItem);
}
/**
* Open an SSE connection to `/api/recommend/stream` and resolve once the
* upstream stream finishes. Each call is one recommendation round — the