圆桌草稿持久化: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

@@ -31,9 +31,12 @@ import { MessageStepsCard } from "./MessageStepsCard";
import type { IntentSummary } from "../api/intent";
import {
filterRecommendCandidates,
listRecommendHistory,
parseRecommendStreamContent,
saveRecommendHistory,
streamRecommend,
type RecommendCandidate,
type RecommendHistoryItem,
type RecommendStreamPhase,
} from "../api/recommend";
import { useAutoScroll } from "../hooks/useAutoScroll";
@@ -56,6 +59,13 @@ export interface RecommendAgentsDialogProps {
intent: IntentSummary | null;
/** Falls back to the recommender's own default if omitted. */
model?: string;
/**
* Draft/session id this recommendation belongs to. When present, the dialog
* shows the session's last recommendation on open (with a「重新分析」button)
* and persists each fresh run to history. Null → behaves statelessly (always
* runs a fresh recommendation, no history).
*/
draftId?: string | null;
onCancel: () => void;
/** Called with the user's final selection of agent ids (in display order). */
onConfirm: (agents: Array<{ agent_id: string; name: string }>) => void;
@@ -81,6 +91,8 @@ const FALLBACK_AGENT_IDS = [
type DialogPhase =
| "idle"
| "loading_agents"
| "loading_history"
| "history"
| "recommending"
| "ready"
| "fallback"
@@ -111,6 +123,8 @@ interface InternalState {
warning: string | null;
/** Latest error message; only shown when `phase === "error"`. */
errorMessage: string | null;
/** ISO time of the historical record being shown (phase === "history"). */
historyCreatedAt: string | null;
}
const INITIAL_STATE: InternalState = {
@@ -123,6 +137,7 @@ const INITIAL_STATE: InternalState = {
recommendedIds: [],
warning: null,
errorMessage: null,
historyCreatedAt: null,
};
/** 推荐流程的 phase → 中文标签;与 RoundtablePlanningPage::phaseLabel 风格保持一致。 */
@@ -164,6 +179,7 @@ export function RecommendAgentsDialog({
open,
intent,
model,
draftId,
onCancel,
onConfirm,
}: RecommendAgentsDialogProps) {
@@ -185,172 +201,240 @@ export function RecommendAgentsDialog({
}, []);
/**
* The full pipeline: fetch agents → run recommendation → seed selection.
* Wrapped so the user can re-trigger it via the "重新推荐" button.
* Render a stored history record as the current view (no streaming). Used on
* open when the session already has a prior recommendation. The user can
* confirm these picks directly or click「重新分析」to run a fresh one.
*/
const runRecommendation = useCallback(async () => {
if (!intent || !intent.objective) {
setState({
...INITIAL_STATE,
phase: "error",
errorMessage: "缺少任务目标,无法启动推荐",
});
return;
const applyHistory = useCallback((item: RecommendHistoryItem, candidates: RecommendCandidate[]) => {
const reasons: Record<string, string> = {};
const recommendedIds: string[] = [];
for (const p of item.picks) {
reasons[p.agent_id] = p.reason;
recommendedIds.push(p.agent_id);
}
cancelInflight();
const myGen = ++generationRef.current;
const controller = new AbortController();
abortRef.current = controller;
setState({ ...INITIAL_STATE, phase: "loading_agents" });
setSelectedIds(new Set());
let agents: Agent[];
try {
agents = await listAgents();
} catch (err) {
if (myGen !== generationRef.current) return;
setState({
...INITIAL_STATE,
phase: "error",
errorMessage: `加载智能体列表失败:${err instanceof Error ? err.message : String(err)}`,
});
return;
}
if (myGen !== generationRef.current) return;
const candidates = filterRecommendCandidates(agents);
if (candidates.length === 0) {
setState({
...INITIAL_STATE,
phase: "error",
errorMessage: "候选智能体池为空,请先在系统里创建至少 2 个智能体",
});
return;
}
const seed = intersectInOrder(recommendedIds, candidates);
setSelectedIds(new Set(seed));
const { rationale } = parseRecommendStreamContent(item.rationale || "");
setState((prev) => ({
...prev,
phase: "recommending",
phase: "history",
candidates,
rationale: "",
streamPhase: "connecting",
// 推荐开始,清空上一轮的步骤时间线并打第一条点。
steps: [
{ id: "0", key: "connecting", label: recommendPhaseLabel("connecting"), ts: nowTimeStr() },
],
rationale: rationale || item.rationale || "",
recommendedIds: seed,
reasons,
streamPhase: null,
steps: [],
warning: null,
historyCreatedAt: item.createdAt || null,
}));
}, []);
try {
const result = await streamRecommend({
intent,
/**
* Stream a fresh recommendation over the given candidate pool, seed the
* selection, and (when bound to a draft) persist the run to history.
*/
const analyze = useCallback(
async (candidates: RecommendCandidate[], myGen: number, signal: AbortSignal) => {
if (!intent) return;
setState((prev) => ({
...prev,
phase: "recommending",
candidates,
model,
signal: controller.signal,
onRationaleUpdate: (rationale) => {
if (myGen !== generationRef.current) return;
setState((prev) => ({ ...prev, rationale }));
},
onPicksUpdate: (picks) => {
if (myGen !== generationRef.current) return;
const reasons: Record<string, string> = {};
const recommendedIds: string[] = [];
for (const p of picks) {
rationale: "",
reasons: {},
recommendedIds: [],
warning: null,
historyCreatedAt: null,
streamPhase: "connecting",
// 推荐开始,清空上一轮的步骤时间线并打第一条点。
steps: [
{ id: "0", key: "connecting", label: recommendPhaseLabel("connecting"), ts: nowTimeStr() },
],
}));
setSelectedIds(new Set());
try {
const result = await streamRecommend({
intent,
candidates,
model,
signal,
onRationaleUpdate: (rationale) => {
if (myGen !== generationRef.current) return;
setState((prev) => ({ ...prev, rationale }));
},
onPicksUpdate: (picks) => {
if (myGen !== generationRef.current) return;
const reasons: Record<string, string> = {};
const recommendedIds: string[] = [];
for (const p of picks) {
reasons[p.agent_id] = p.reason;
recommendedIds.push(p.agent_id);
}
const seed = intersectInOrder(recommendedIds, candidates);
setSelectedIds((prev) => {
const next = new Set(prev);
for (const id of seed) next.add(id);
return next;
});
setState((prev) => ({ ...prev, recommendedIds, reasons }));
},
onPhaseChange: (phase) => {
if (myGen !== generationRef.current) return;
setState((prev) => {
const key = phase;
const last = prev.steps[prev.steps.length - 1];
const steps =
last && last.key === key
? prev.steps
: [
...prev.steps,
{
id: String(prev.steps.length),
key,
label: recommendPhaseLabel(phase),
ts: nowTimeStr(),
},
];
return { ...prev, streamPhase: phase, steps };
});
},
});
if (myGen !== generationRef.current) return;
const reasons: Record<string, string> = {};
const recommendedIds: string[] = [];
if (result.picks) {
for (const p of result.picks) {
reasons[p.agent_id] = p.reason;
recommendedIds.push(p.agent_id);
}
const seed = intersectInOrder(recommendedIds, candidates);
setSelectedIds((prev) => {
const next = new Set(prev);
for (const id of seed) next.add(id);
return next;
});
setState((prev) => ({
...prev,
recommendedIds,
reasons,
}));
},
onPhaseChange: (phase) => {
if (myGen !== generationRef.current) return;
setState((prev) => {
const key = phase;
const last = prev.steps[prev.steps.length - 1];
// 连续重复阶段不重复 push,只在阶段切换时打点。
const steps =
last && last.key === key
? prev.steps
: [
...prev.steps,
{
id: String(prev.steps.length),
key,
label: recommendPhaseLabel(phase),
ts: nowTimeStr(),
},
];
return { ...prev, streamPhase: phase, steps };
});
},
});
if (myGen !== generationRef.current) return;
const reasons: Record<string, string> = {};
const recommendedIds: string[] = [];
if (result.picks) {
for (const p of result.picks) {
reasons[p.agent_id] = p.reason;
recommendedIds.push(p.agent_id);
}
}
if (result.status === "done" && recommendedIds.length >= MIN_SELECTED) {
const seed = intersectInOrder(recommendedIds, candidates);
setSelectedIds(new Set(seed));
const { rationale } = parseRecommendStreamContent(result.content || "");
let finalPhase: DialogPhase;
let finalIds: string[];
let warning: string | null;
if (result.status === "done" && recommendedIds.length >= MIN_SELECTED) {
finalPhase = "ready";
finalIds = intersectInOrder(recommendedIds, candidates);
warning = null;
} else {
// Fallback: status === "asking" or picks too few. Use the 6 built-in
// roundtable seats, intersected against the live pool.
finalPhase = "fallback";
const fallback = intersectInOrder(FALLBACK_AGENT_IDS, candidates);
finalIds =
fallback.length >= MIN_SELECTED
? fallback
: candidates.slice(0, MIN_SELECTED).map((c) => c.agent_id);
warning = "智能推荐未生成有效结果,已为你勾选默认的圆桌席位,可手动调整。";
}
setSelectedIds(new Set(finalIds));
setState((prev) => ({
...prev,
phase: "ready",
phase: finalPhase,
rationale: rationale || prev.rationale,
recommendedIds,
recommendedIds: finalIds,
reasons,
streamPhase: null,
warning: null,
warning,
}));
// Persist this run to the session's history (best-effort).
if (draftId) {
const picks = finalIds.map((id) => ({ agent_id: id, reason: reasons[id] ?? "" }));
void saveRecommendHistory(draftId, {
objective: intent.objective,
status: finalPhase === "ready" ? "done" : "fallback",
model,
rationale: rationale || result.content || "",
picks,
candidates,
}).catch((err) => console.warn("[recommend] 保存推荐历史失败:", err));
}
} catch (err) {
if (myGen !== generationRef.current) return;
// AbortError fires when the user closes the dialog mid-stream — no
// state update needed because the dialog is going away.
if (err instanceof DOMException && err.name === "AbortError") return;
setState((prev) => ({
...prev,
phase: "error",
streamPhase: null,
errorMessage: `推荐过程出错:${err instanceof Error ? err.message : String(err)}`,
}));
}
},
[intent, model, draftId],
);
/**
* Open pipeline: load candidates → (unless forceFresh) show the session's
* last recommendation from history → otherwise run a fresh analysis.
* `forceFresh=true` is the「重新分析」/「重新推荐」path.
*/
const start = useCallback(
async (forceFresh: boolean) => {
if (!intent || !intent.objective) {
setState({ ...INITIAL_STATE, phase: "error", errorMessage: "缺少任务目标,无法启动推荐" });
return;
}
// Fallback: status === "asking" or picks too few. Use the 6 built-in
// roundtable seats, intersected against the live pool.
const fallback = intersectInOrder(FALLBACK_AGENT_IDS, candidates);
const seed = fallback.length >= MIN_SELECTED
? fallback
: candidates.slice(0, MIN_SELECTED).map((c) => c.agent_id);
setSelectedIds(new Set(seed));
const { rationale } = parseRecommendStreamContent(result.content || "");
setState((prev) => ({
...prev,
phase: "fallback",
rationale: rationale || prev.rationale,
recommendedIds: seed,
reasons,
streamPhase: null,
warning: "智能推荐未生成有效结果,已为你勾选默认的圆桌席位,可手动调整。",
}));
} catch (err) {
cancelInflight();
const myGen = ++generationRef.current;
const controller = new AbortController();
abortRef.current = controller;
setState({ ...INITIAL_STATE, phase: "loading_agents" });
setSelectedIds(new Set());
let agents: Agent[];
try {
agents = await listAgents();
} catch (err) {
if (myGen !== generationRef.current) return;
setState({
...INITIAL_STATE,
phase: "error",
errorMessage: `加载智能体列表失败:${err instanceof Error ? err.message : String(err)}`,
});
return;
}
if (myGen !== generationRef.current) return;
// AbortError fires when the user closes the dialog mid-stream — no
// state update needed because the dialog is going away.
if (err instanceof DOMException && err.name === "AbortError") return;
setState((prev) => ({
...prev,
phase: "error",
streamPhase: null,
errorMessage: `推荐过程出错:${err instanceof Error ? err.message : String(err)}`,
}));
}
}, [intent, model, cancelInflight]);
const candidates = filterRecommendCandidates(agents);
if (candidates.length === 0) {
setState({
...INITIAL_STATE,
phase: "error",
errorMessage: "候选智能体池为空,请先在系统里创建至少 2 个智能体",
});
return;
}
// 若该会话已有推荐历史,默认展示最近一次(可重新分析),不自动重跑模型。
if (!forceFresh && draftId) {
setState((prev) => ({ ...prev, phase: "loading_history", candidates }));
try {
const history = await listRecommendHistory(draftId);
if (myGen !== generationRef.current) return;
if (history.length > 0) {
applyHistory(history[0], candidates);
return;
}
} catch (err) {
if (myGen !== generationRef.current) return;
// 历史拉取失败不阻断:退化为直接跑一次新推荐。
console.warn("[recommend] 拉取推荐历史失败,回退到新推荐:", err);
}
}
await analyze(candidates, myGen, controller.signal);
},
[intent, draftId, cancelInflight, analyze, applyHistory],
);
// Trigger the pipeline whenever the dialog opens. Closing it aborts any
// in-flight stream so the next open starts clean.
@@ -359,11 +443,11 @@ export function RecommendAgentsDialog({
cancelInflight();
return;
}
void runRecommendation();
void start(false);
return () => {
cancelInflight();
};
}, [open, runRecommendation, cancelInflight]);
}, [open, start, cancelInflight]);
const handleToggle = useCallback((agentId: string) => {
setSelectedIds((prev) => {
@@ -391,7 +475,7 @@ export function RecommendAgentsDialog({
const selectedCount = selectedIds.size;
const canConfirm =
(state.phase === "ready" || state.phase === "fallback") &&
(state.phase === "ready" || state.phase === "fallback" || state.phase === "history") &&
selectedCount >= MIN_SELECTED &&
selectedCount <= MAX_SELECTED;
@@ -452,7 +536,9 @@ export function RecommendAgentsDialog({
============================================================ */}
<CollapsibleModelOutput
isLoading={
state.phase === "loading_agents" || state.phase === "recommending"
state.phase === "loading_agents" ||
state.phase === "loading_history" ||
state.phase === "recommending"
}
phase={state.phase}
scrollDeps={[state.rationale, state.steps, state.streamPhase]}
@@ -497,8 +583,20 @@ export function RecommendAgentsDialog({
</div>
)}
</>
) : (state.phase === "ready" || state.phase === "fallback") ? (
) : (state.phase === "ready" || state.phase === "fallback" || state.phase === "history") ? (
<>
{state.phase === "history" && (
<div className="text-xs text-sky-700 dark:text-sky-300 p-2 border border-sky-300/50 dark:border-sky-700/50 rounded-md bg-sky-50 dark:bg-sky-950/30 flex items-center justify-between gap-2">
<span>
📌 这是本会话上次的推荐结果
{state.historyCreatedAt
? `(${new Date(state.historyCreatedAt).toLocaleString("zh-CN", { hour12: false })})`
: ""}
,可直接进入研讨,或点「重新分析」让模型重新推荐。
</span>
</div>
)}
{state.warning && (
<div className="text-xs text-amber-700 dark:text-amber-300 p-2 border border-amber-300/50 dark:border-amber-700/50 rounded-md bg-amber-50 dark:bg-amber-950/30">
{state.warning}
@@ -551,15 +649,18 @@ export function RecommendAgentsDialog({
>
{selectionHint}
</span>
{(state.phase === "ready" || state.phase === "fallback" || state.phase === "error") && (
{(state.phase === "ready" ||
state.phase === "fallback" ||
state.phase === "history" ||
state.phase === "error") && (
<Button
variant="ghost"
variant={state.phase === "history" ? "secondary" : "ghost"}
size="sm"
onClick={() => void runRecommendation()}
onClick={() => void start(true)}
className="h-7 px-2 text-xs"
>
<RefreshCwIcon className="size-3 mr-1" />
重新推荐
{state.phase === "history" ? "重新分析" : "重新推荐"}
</Button>
)}
</div>
@@ -624,7 +725,8 @@ function CollapsibleModelOutput({
hasAutoClosedRef.current = false;
return;
}
const isCompleted = phase === "ready" || phase === "fallback" || phase === "error";
const isCompleted =
phase === "ready" || phase === "fallback" || phase === "error" || phase === "history";
if (isCompleted && !hasAutoClosedRef.current && open) {
const timer = setTimeout(() => {
setOpen(false);
@@ -639,6 +741,10 @@ function CollapsibleModelOutput({
switch (phase) {
case "loading_agents":
return { label: "加载候选", className: "bg-slate-100 text-slate-600" };
case "loading_history":
return { label: "读取历史", className: "bg-slate-100 text-slate-600" };
case "history":
return { label: "历史记录", className: "bg-sky-50 text-sky-700 border border-sky-200" };
case "recommending":
return { label: "正在生成", className: "bg-purple-50 text-purple-700 border border-purple-200" };
case "ready":
@@ -713,11 +819,11 @@ function CollapsibleModelOutput({
* - 流式中正文末尾跟一个闪烁竖线
*/
function RecommenderOutput({ state }: { state: InternalState }) {
if (state.phase === "loading_agents") {
if (state.phase === "loading_agents" || state.phase === "loading_history") {
return (
<div className="flex items-center gap-2 text-muted-foreground text-sm">
<Loader2Icon className="size-4 animate-spin" />
正在加载候选智能体...
{state.phase === "loading_history" ? "正在读取历史推荐..." : "正在加载候选智能体..."}
</div>
);
}
@@ -733,7 +839,8 @@ function RecommenderOutput({ state }: { state: InternalState }) {
const showRationaleStage =
state.phase === "recommending" ||
state.phase === "ready" ||
state.phase === "fallback";
state.phase === "fallback" ||
state.phase === "history";
if (!showRationaleStage) return null;
const isStreaming = state.phase === "recommending";