"use client"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { useNavigate } from "react-router-dom"; import { CheckIcon, ChevronDownIcon, ChevronUpIcon, LayersIcon, Loader2Icon, RefreshCwIcon, SparklesIcon, } from "lucide-react"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "@/components/ui/dialog"; import { Button } from "@/components/ui/button"; import { listAgents, type Agent } from "@/core/agents"; import { useTheme } from "@/contexts/ThemeContext"; import { desensitize } from "@/lib/desensitize"; import { cn } from "@/lib/utils"; import { MarkdownContent, ReasoningBlock, StreamingCursor, } from "./MessageBubble"; import { MessageStepsCard } from "./MessageStepsCard"; import { BusinessChainPicker } from "./BusinessChainPicker"; import type { IntentSummary } from "../api/intent"; import type { SeatSelectionResult } from "../lib/business-chain"; import { DEFAULT_SEAT_MODE, SEAT_MODE_OPTIONS, type SeatMode, } from "../lib/seat-mode"; import { filterRecommendCandidates, listRecommendHistory, parseRecommendStreamContent, saveRecommendHistory, streamRecommend, type RecommendCandidate, type RecommendHistoryItem, type RecommendStreamPhase, } from "../api/recommend"; import { useAutoScroll } from "../hooks/useAutoScroll"; import { splitInlineReasoning } from "../lib/reasoning"; import { ScrollToBottomButton } from "./ScrollToBottomButton"; /** * Picks-selection dialog that sits between Step 1 (intent) and Step 2 * (roundtable). Opens with a streaming recommendation from * `roundtable-recommender`, defaults its picks to checked, and lets the user * trim or extend the selection from the rest of the agent pool before * confirming. * * Selection bounds (2 ≤ N ≤ 8) are enforced on the confirm button — the * backend also clamps but UI feedback is faster here. */ export interface RecommendAgentsDialogProps { open: boolean; 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 seat selection + the orchestration mode. * 智能推荐模式回传 `{ agents, mode: "recommend" }`;业务链条模式(阶段 3) * 回传 `{ agents, mode: "chain", chain }`。 */ onConfirm: (result: SeatSelectionResult) => void; } const MIN_SELECTED = 2; const MAX_SELECTED = 8; /** * Default selection when the recommender fails or returns < 2 valid picks. * Intersected with the live candidate pool at runtime so missing built-ins * don't break the dialog. */ const FALLBACK_AGENT_IDS = [ "roundtable-intelligence", "roundtable-environment", "roundtable-solution-design", "roundtable-risk-review", "roundtable-execution-plan", "roundtable-summary", ]; type DialogPhase = | "idle" | "loading_agents" | "loading_history" | "history" | "recommending" | "ready" | "fallback" | "error"; interface RecommendStep { id: string; key: string; label: string; ts: string; } interface InternalState { phase: DialogPhase; /** Streaming + final rationale text from the recommender. */ rationale: string; /** Streaming SSE phase from the recommender helper. */ streamPhase: RecommendStreamPhase | null; /** 推荐流程阶段时间线 —— 调度 / 已连接 / 流式生成 …… 用 ChainOfThought 折叠展示。 */ steps: RecommendStep[]; /** Pre-filtered candidate pool fetched from `/api/agents`. */ candidates: RecommendCandidate[]; /** Reason-by-agent_id, only for picks returned by the recommender. */ reasons: Record; /** Agent ids the recommender returned (in order). */ recommendedIds: string[]; /** User-visible warning ("推荐失败,已使用默认席位") for the fallback case. */ 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 = { phase: "idle", rationale: "", streamPhase: null, steps: [], candidates: [], reasons: {}, recommendedIds: [], warning: null, errorMessage: null, historyCreatedAt: null, }; /** 推荐流程的 phase → 中文标签;与 RoundtablePlanningPage::phaseLabel 风格保持一致。 */ function recommendPhaseLabel(phase: RecommendStreamPhase): string { switch (phase) { case "connecting": return "调度推荐智能体"; case "connected": return "已连接,等待响应"; case "streaming": return "正在生成推荐"; default: return phase; } } function nowTimeStr(): string { return new Date().toLocaleTimeString("zh-CN", { hour12: false }); } /** * Resolve which candidate ids should be checked by default given a set of * recommended ids. The result preserves recommendation order and silently * drops ids that aren't in the candidate pool. */ function intersectInOrder(preferred: string[], pool: RecommendCandidate[]): string[] { const poolIds = new Set(pool.map((c) => c.agent_id)); const seen = new Set(); const out: string[] = []; for (const id of preferred) { if (!poolIds.has(id) || seen.has(id)) continue; out.push(id); seen.add(id); } return out; } export function RecommendAgentsDialog({ open, intent, model, draftId, onCancel, onConfirm, }: RecommendAgentsDialogProps) { // 弹窗经 Radix portal 渲染到 .roundtable-planning 之外,页面的深蓝 scoped 样式 // 够不着它。深色下手动挂上 .roundtable-planning--dark,让同一套深蓝 token + 兜底 // 映射也作用于弹窗;浅色不挂,弹窗浅色外观不变。 const { theme } = useTheme(); const isDark = theme === "dark"; const navigate = useNavigate(); // 席位来源模式:智能推荐 / 业务链条。默认**业务链条**。 const [mode, setMode] = useState<"recommend" | "chain">("chain"); // 席位执行模式(快速/思考/专业问答/多智能体问答)——推荐 / 业务链条两种来源通用, // 决定第二步每个子智能体席位的推理深度。默认 pro(= 改造前席位固定行为)。 const [seatMode, setSeatMode] = useState(DEFAULT_SEAT_MODE); const [state, setState] = useState(INITIAL_STATE); const [selectedIds, setSelectedIds] = useState>(new Set()); // Latest stream abort controller, so closing or re-running cancels the // in-flight request instead of leaking it. const abortRef = useRef(null); // Generation token guards against stale completion handlers writing into // state after a re-run (e.g. user clicks "重新推荐" mid-stream). const generationRef = useRef(0); const cancelInflight = useCallback(() => { if (abortRef.current) { abortRef.current.abort(); abortRef.current = null; } }, []); /** * 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 applyHistory = useCallback((item: RecommendHistoryItem, candidates: RecommendCandidate[]) => { const reasons: Record = {}; const recommendedIds: string[] = []; for (const p of item.picks) { reasons[p.agent_id] = p.reason; recommendedIds.push(p.agent_id); } const seed = intersectInOrder(recommendedIds, candidates); setSelectedIds(new Set(seed)); const { rationale } = parseRecommendStreamContent(item.rationale || ""); setState((prev) => ({ ...prev, phase: "history", candidates, rationale: rationale || item.rationale || "", recommendedIds: seed, reasons, streamPhase: null, steps: [], warning: null, historyCreatedAt: item.createdAt || null, })); }, []); /** * 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, 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 = {}; 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 = {}; const recommendedIds: string[] = []; if (result.picks) { for (const p of result.picks) { reasons[p.agent_id] = p.reason; recommendedIds.push(p.agent_id); } } 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: finalPhase, rationale: rationale || prev.rationale, recommendedIds: finalIds, reasons, streamPhase: 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; } 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; } // 若该会话已有推荐历史,默认展示最近一次(可重新分析),不自动重跑模型。 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], ); // 推荐管线只在「智能推荐」模式下跑一次。默认是业务链条模式 —— 此时不触发推荐 // 模型调用,等用户切到「智能推荐」tab 才启动;每次 open 内只跑一次(切 tab 来回 // 不重复跑),关闭时复位 latch。 const recommendStartedRef = useRef(false); // 关闭 / 卸载时中止 in-flight 推荐流。 useEffect(() => { return () => { cancelInflight(); }; }, [cancelInflight]); useEffect(() => { if (!open) { recommendStartedRef.current = false; cancelInflight(); return; } if (mode === "recommend" && !recommendStartedRef.current) { recommendStartedRef.current = true; void start(false); } }, [open, mode, start, cancelInflight]); const handleToggle = useCallback((agentId: string) => { setSelectedIds((prev) => { const next = new Set(prev); if (next.has(agentId)) next.delete(agentId); else next.add(agentId); return next; }); }, []); // Split candidates into "recommended" and "other" — order within each // group matches the recommender's pick order / the API's list order so the // dialog is deterministic between renders. const { recommendedCards, otherCards } = useMemo(() => { const recSet = new Set(state.recommendedIds); const byId = new Map(state.candidates.map((c) => [c.agent_id, c])); const recommended: RecommendCandidate[] = []; for (const id of state.recommendedIds) { const c = byId.get(id); if (c) recommended.push(c); } const others = state.candidates.filter((c) => !recSet.has(c.agent_id)); return { recommendedCards: recommended, otherCards: others }; }, [state.candidates, state.recommendedIds]); const selectedCount = selectedIds.size; const canConfirm = (state.phase === "ready" || state.phase === "fallback" || state.phase === "history") && selectedCount >= MIN_SELECTED && selectedCount <= MAX_SELECTED; const selectionHint = (() => { if (selectedCount < MIN_SELECTED) { return `至少再选 ${MIN_SELECTED - selectedCount} 个`; } if (selectedCount > MAX_SELECTED) { return `已超出上限 ${selectedCount - MAX_SELECTED} 个`; } return `已选 ${selectedCount} / ${MAX_SELECTED}`; })(); // 统一在回传前合并席位模式,推荐 / 业务链条两条确认路径共用,保证 seatMode 总被带上。 const handleConfirmWithMode = useCallback( (result: SeatSelectionResult) => { onConfirm({ ...result, seatMode }); }, [onConfirm, seatMode], ); const handleConfirm = useCallback(() => { if (!canConfirm) return; // Order: recommended-and-selected first (in recommender order), then // user-added picks (in pool order). Keeps the leader's "可调度智能体" // list visually stable. // // 传完整对象(含 name)而不是只传 agent_id —— 非内置 agent 的 id 是 UUID, // 上游若只拿 id,在左侧席位列表就会显示 UUID 而非中文名。 const ordered: Array<{ agent_id: string; name: string }> = []; for (const c of recommendedCards) { if (selectedIds.has(c.agent_id)) ordered.push({ agent_id: c.agent_id, name: c.name }); } for (const c of otherCards) { if (selectedIds.has(c.agent_id)) ordered.push({ agent_id: c.agent_id, name: c.name }); } handleConfirmWithMode({ agents: ordered, mode: "recommend" }); }, [canConfirm, recommendedCards, otherCards, selectedIds, handleConfirmWithMode]); const handleGoConfig = useCallback(() => { onCancel(); navigate("/page/workspace/roundtable/chains"); }, [navigate, onCancel]); const handleOpenChange = useCallback( (next: boolean) => { if (!next) onCancel(); }, [onCancel], ); return ( 选择参会智能体 {mode === "recommend" ? "根据你的任务目标,系统为你推荐了最合适的智能体。你可以取消勾选,也可以从下方添加其他智能体。" : "从已配置的业务链条中选择一条,Step 2 将按链条顺序进行多智能体研讨。"} {/* 模式选择:智能推荐 / 业务链条 */}
{/* 席位执行模式:快速 / 思考 / 专业问答 / 多智能体问答。推荐 & 业务链条通用, 决定第二步每个子智能体席位的推理深度(thinking/reasoning/subagent)。 */}
执行模式
{SEAT_MODE_OPTIONS.map((opt) => ( ))}

{SEAT_MODE_OPTIONS.find((o) => o.value === seatMode)?.description}

{/* ===== 智能推荐模式(现状,零行为变更)===== */} {mode === "recommend" && ( <> {/* ============================================================ TOP: 模型生成内容 包含状态行 + 步骤卡 + 思考过程(``)+ 推荐理由 markdown。 与主聊天消息气泡内容区视觉对齐。 **可折叠** —— 流式中默认展开方便观察生成过程,完成后自动收起一次, 让 UI 焦点转到下方推荐卡片;用户手动切换后不再自动收起(尊重偏好)。 ============================================================ */} {/* ============================================================ BOTTOM: 推荐的智能体(可勾选) 滚动区,占据剩余高度。 ============================================================ */}
推荐参会智能体
{state.phase === "error" ? (
{state.errorMessage ?? "未知错误"}
) : state.phase === "recommending" ? ( <> {recommendedCards.length > 0 ? (
{recommendedCards.map((c) => ( handleToggle(c.agent_id)} streaming /> ))}
) : (
等待推荐结果...
)} ) : (state.phase === "ready" || state.phase === "fallback" || state.phase === "history") ? ( <> {state.phase === "history" && (
这是本会话上次的推荐结果 {state.historyCreatedAt ? `(${new Date(state.historyCreatedAt).toLocaleString("zh-CN", { hour12: false })})` : ""} ,可直接进入研讨,或点「重新分析」让模型重新推荐。
)} {state.warning && (
{state.warning}
)} {recommendedCards.length > 0 && (
{recommendedCards.map((c) => ( handleToggle(c.agent_id)} /> ))}
)} {otherCards.length > 0 && (
{otherCards.map((c) => ( handleToggle(c.agent_id)} /> ))}
)} ) : null}
MAX_SELECTED ? "text-destructive" : "text-muted-foreground", )} > {selectionHint} {(state.phase === "ready" || state.phase === "fallback" || state.phase === "history" || state.phase === "error") && ( )}
)} {/* ===== 业务链条模式 ===== */} {mode === "chain" && ( { // 选中链条若配了默认执行模式 → 把顶部模式选择器默认设为它(用户仍可临时改)。 if (chain?.seatMode) setSeatMode(chain.seatMode); }} /> )}
); } /** * 「模型生成内容」整段的可折叠外壳。 * * 默认行为: * - 「正在加载候选」+「正在生成推荐」期间(`isLoading=true`)始终保持展开, * 让用户看到内部 spinner / 实时生成内容,不会在中途被自动收起。 * - 推荐完成(切到 `ready`/`fallback`/`error`)后延迟 1s 自动收起一次, * 把焦点让给下方推荐卡片 * - 用户**手动**点击 toggle 后,`userTouchedRef` 置 true,后续不再自动改变 * * 收起态 header 上显示: * - 加载中/生成中 → 旋转 spinner 图标(替代静态 ✨),即便折叠也能看到在加载 * - 完成态 → 静态 ✨ + 状态徽标(已生成 / 已使用兜底 / 推荐失败) */ const MODEL_OUTPUT_AUTO_CLOSE_DELAY_MS = 1000; function CollapsibleModelOutput({ isLoading, phase, scrollDeps, children, }: { /** True 时面板保持展开 + header 显示 spinner;涵盖加载候选 + 流式生成。 */ isLoading: boolean; phase: DialogPhase; /** 内容变化时触发自动滚到底(与 Step1/Step2 对话区同一套 useAutoScroll)。 */ scrollDeps: React.DependencyList; children: React.ReactNode; }) { const [open, setOpen] = useState(true); const userTouchedRef = useRef(false); const hasAutoClosedRef = useRef(false); const modelOutputScrollRef = useRef(null); const { atBottom: modelOutputAtBottom, scrollToBottom: scrollModelOutputToBottom } = useAutoScroll(modelOutputScrollRef, scrollDeps); // 加载中 → 保持展开(用户没手动动过的前提下)。 // 加载完成 → 延迟自动收起一次(仅一次),让出焦点给下方推荐卡片。 // 关键区分:idle / loading_agents 早期阶段以前会被 1s 计时器误关—— // 现在只有真正进入「已完成/兜底/失败」三种终态才触发自动收起。 useEffect(() => { if (userTouchedRef.current) return; if (isLoading) { setOpen(true); hasAutoClosedRef.current = false; return; } const isCompleted = phase === "ready" || phase === "fallback" || phase === "error" || phase === "history"; if (isCompleted && !hasAutoClosedRef.current && open) { const timer = setTimeout(() => { setOpen(false); hasAutoClosedRef.current = true; }, MODEL_OUTPUT_AUTO_CLOSE_DELAY_MS); return () => clearTimeout(timer); } return undefined; }, [isLoading, phase, open]); const statusBadge = (() => { 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": return { label: "推荐已生成", className: "bg-emerald-50 text-emerald-700 border border-emerald-200" }; case "fallback": return { label: "已使用兜底", className: "bg-amber-50 text-amber-700 border border-amber-200" }; case "error": return { label: "推荐失败", className: "bg-red-50 text-red-700 border border-red-200" }; default: return null; } })(); return (
{open && (
{children}
{!modelOutputAtBottom && ( )}
)}
); } /** * 推荐弹窗顶部「模型生成内容」面板。 * * 视觉与交互对齐主聊天 chats/new 的消息列表: * - 顶部一行 spinner + 阶段文案(连接中 / 流式 / 完成) * - 步骤折叠卡(MessageStepsCard,与对话气泡里同一实现) * - 「思考过程」折叠卡(从 `` 抽出来 reasoning,流式中默认展开) * - 正文 Markdown(去掉了 `` 标签后的 rationale) * - 流式中正文末尾跟一个闪烁竖线 */ function RecommenderOutput({ state }: { state: InternalState }) { if (state.phase === "loading_agents" || state.phase === "loading_history") { return (
{state.phase === "loading_history" ? "正在读取历史推荐..." : "正在加载候选智能体..."}
); } if (state.phase === "error") { return (
推荐失败,请使用下方的「重新推荐」重试,或取消后再次进入。
); } const showRationaleStage = state.phase === "recommending" || state.phase === "ready" || state.phase === "fallback" || state.phase === "history"; if (!showRationaleStage) return null; const isStreaming = state.phase === "recommending"; // 顶部状态行:跟主聊天的「正在思考...」类似,只是文案换成推荐阶段。 const streamingLabel = isStreaming ? state.streamPhase === "connecting" ? "调度推荐智能体..." : state.streamPhase === "connected" ? "已连接,等待响应..." : "正在生成推荐..." : null; // 把 `...` 抽出来作 reasoning,剩下的 rationale 用 markdown 渲染。 // 这与 Step1Panel / Step2Panel 的处理方式完全一致。 const { content: cleanedRationale, reasoning } = splitInlineReasoning(state.rationale); const hasRationale = cleanedRationale.length > 0; const hasReasoning = !!reasoning; return (
{streamingLabel && (
{streamingLabel}
)} {state.steps.length > 0 && ( )} {hasReasoning && ( {reasoning!} )} {!hasRationale && !hasReasoning && isStreaming && (

正在分析任务与候选智能体...

)} {hasRationale && (
{cleanedRationale} {isStreaming && }
)}
); } function Section({ title, children, collapsible = false, defaultOpen = true, }: { title: string; children: React.ReactNode; /** True 时 header 可点击折叠/展开;false 保持原行为(始终展开,不可点击)。 */ collapsible?: boolean; /** 仅当 collapsible=true 时生效。 */ defaultOpen?: boolean; }) { const [open, setOpen] = useState(defaultOpen); return (
{collapsible ? ( ) : (
{title}
)} {/* flex flex-col + w-full + items-stretch:替代原 `grid gap-2`, 强制所有 AgentCard 满父宽。grid 在某些浏览器对
); } interface AgentCardProps { candidate: RecommendCandidate; reason: string | undefined; recommended: boolean; checked: boolean; onToggle: () => void; /** Card is still being filled in from the SSE stream. */ streaming?: boolean; } function AgentCard({ candidate, reason, recommended, checked, onToggle, streaming = false, }: AgentCardProps) { return ( ); }