- 席位执行模式:选择参会智能体弹窗加模式选择器,映射 thinking/reasoning/subagent 透传 recommend/chain/dag 三条编排;后端 _special_run 覆盖 seat policy(仅席位, 总控不变);ultra 解锁席位 task 子代理(custom 流回传 task_running 实时进度)。 - 子智能体任务卡片:复用主聊天 SubtaskCard + SubtaskContext,从席位流解析 task 调用/结果,在 Step2 气泡渲染多张任务卡片(覆盖业务链条路径)。 - 后台挂起也按所选模式跑(StartParams→inprocess gateway→run_seat 覆盖 policy)。 - 后台作业完成全工作区跨页通知:RoundtableJobNotifier 挂在 PageLayout 常驻层, 作业终态弹「达成共识」同款浮窗。 - 业务链条可配「默认执行模式」并持久化(roundtable_chains.seat_mode;选链时弹窗 默认用它,仍可临时改)。 - 修复后台 Step3 HTML 看板概率截断:deepseek max_tokens=4096 单轮写不完长 HTML, 产物自愈重试上限 2→5,让 append 续写写完整(同惠及 summary/dashboard)。 Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
1148 lines
42 KiB
TypeScript
1148 lines
42 KiB
TypeScript
"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 { 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<string, string>;
|
||
/** 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<string>();
|
||
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<SeatMode>(DEFAULT_SEAT_MODE);
|
||
const [state, setState] = useState<InternalState>(INITIAL_STATE);
|
||
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
|
||
|
||
// Latest stream abort controller, so closing or re-running cancels the
|
||
// in-flight request instead of leaking it.
|
||
const abortRef = useRef<AbortController | null>(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<string, string> = {};
|
||
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<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 { 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 (
|
||
<Dialog open={open} onOpenChange={handleOpenChange}>
|
||
<DialogContent
|
||
className={cn(
|
||
"sm:max-w-3xl max-h-[85vh] flex flex-col overflow-hidden gap-3",
|
||
isDark && "roundtable-planning--dark",
|
||
)}
|
||
>
|
||
<DialogHeader className="shrink-0">
|
||
<DialogTitle className="flex items-center gap-2">
|
||
<SparklesIcon className="size-5 text-purple-500" />
|
||
选择参会智能体
|
||
</DialogTitle>
|
||
<DialogDescription>
|
||
{mode === "recommend"
|
||
? "根据你的任务目标,系统为你推荐了最合适的智能体。你可以取消勾选,也可以从下方添加其他智能体。"
|
||
: "从已配置的业务链条中选择一条,Step 2 将按链条顺序进行多智能体研讨。"}
|
||
</DialogDescription>
|
||
</DialogHeader>
|
||
|
||
{/* 模式选择:智能推荐 / 业务链条 */}
|
||
<div className="shrink-0 inline-flex self-start rounded-lg border border-border bg-muted/40 p-0.5 text-xs font-medium">
|
||
<button
|
||
type="button"
|
||
onClick={() => setMode("recommend")}
|
||
className={cn(
|
||
"flex items-center gap-1.5 rounded-md px-3 py-1.5 transition-colors",
|
||
mode === "recommend"
|
||
? "bg-card text-primary shadow-sm"
|
||
: "text-muted-foreground hover:text-foreground",
|
||
)}
|
||
>
|
||
<SparklesIcon className="size-3.5" />
|
||
智能推荐
|
||
</button>
|
||
<button
|
||
type="button"
|
||
onClick={() => setMode("chain")}
|
||
className={cn(
|
||
"flex items-center gap-1.5 rounded-md px-3 py-1.5 transition-colors",
|
||
mode === "chain"
|
||
? "bg-card text-primary shadow-sm"
|
||
: "text-muted-foreground hover:text-foreground",
|
||
)}
|
||
>
|
||
<LayersIcon className="size-3.5" />
|
||
业务链条
|
||
</button>
|
||
</div>
|
||
|
||
{/* 席位执行模式:快速 / 思考 / 专业问答 / 多智能体问答。推荐 & 业务链条通用,
|
||
决定第二步每个子智能体席位的推理深度(thinking/reasoning/subagent)。 */}
|
||
<div className="shrink-0 space-y-1.5">
|
||
<div className="flex flex-wrap items-center gap-2">
|
||
<span className="text-xs font-medium text-muted-foreground">执行模式</span>
|
||
<div className="inline-flex rounded-lg border border-border bg-muted/40 p-0.5 text-xs font-medium">
|
||
{SEAT_MODE_OPTIONS.map((opt) => (
|
||
<button
|
||
key={opt.value}
|
||
type="button"
|
||
onClick={() => setSeatMode(opt.value)}
|
||
title={opt.description}
|
||
className={cn(
|
||
"rounded-md px-2.5 py-1 transition-colors",
|
||
seatMode === opt.value
|
||
? "bg-card text-primary shadow-sm"
|
||
: "text-muted-foreground hover:text-foreground",
|
||
)}
|
||
>
|
||
{opt.label}
|
||
</button>
|
||
))}
|
||
</div>
|
||
</div>
|
||
<p className="text-[11px] leading-relaxed text-muted-foreground">
|
||
{SEAT_MODE_OPTIONS.find((o) => o.value === seatMode)?.description}
|
||
</p>
|
||
</div>
|
||
|
||
{/* ===== 智能推荐模式(现状,零行为变更)===== */}
|
||
{mode === "recommend" && (
|
||
<>
|
||
{/* ============================================================
|
||
TOP: 模型生成内容
|
||
包含状态行 + 步骤卡 + 思考过程(`<think>`)+ 推荐理由 markdown。
|
||
与主聊天消息气泡内容区视觉对齐。
|
||
**可折叠** —— 流式中默认展开方便观察生成过程,完成后自动收起一次,
|
||
让 UI 焦点转到下方推荐卡片;用户手动切换后不再自动收起(尊重偏好)。
|
||
============================================================ */}
|
||
<CollapsibleModelOutput
|
||
isLoading={
|
||
state.phase === "loading_agents" ||
|
||
state.phase === "loading_history" ||
|
||
state.phase === "recommending"
|
||
}
|
||
phase={state.phase}
|
||
scrollDeps={[state.rationale, state.steps, state.streamPhase]}
|
||
>
|
||
<RecommenderOutput state={state} />
|
||
</CollapsibleModelOutput>
|
||
|
||
{/* ============================================================
|
||
BOTTOM: 推荐的智能体(可勾选)
|
||
滚动区,占据剩余高度。
|
||
============================================================ */}
|
||
<section className="flex-1 min-h-0 flex flex-col overflow-hidden">
|
||
<div className="text-[10px] font-bold text-slate-500 uppercase tracking-wider mb-2 flex items-center gap-1.5 shrink-0">
|
||
<CheckIcon className="size-3 text-emerald-500" />
|
||
推荐参会智能体
|
||
</div>
|
||
<div className="flex-1 min-h-0 overflow-y-auto custom-scrollbar pr-1 -mr-1 space-y-4">
|
||
{state.phase === "error" ? (
|
||
<div className="text-sm text-destructive p-4 border border-destructive/30 rounded-md bg-destructive/5">
|
||
{state.errorMessage ?? "未知错误"}
|
||
</div>
|
||
) : state.phase === "recommending" ? (
|
||
<>
|
||
{recommendedCards.length > 0 ? (
|
||
<Section title={`推荐参会 (${recommendedCards.length})`} collapsible defaultOpen>
|
||
{recommendedCards.map((c) => (
|
||
<AgentCard
|
||
key={c.agent_id}
|
||
candidate={c}
|
||
reason={state.reasons[c.agent_id]}
|
||
recommended
|
||
checked={selectedIds.has(c.agent_id)}
|
||
onToggle={() => handleToggle(c.agent_id)}
|
||
streaming
|
||
/>
|
||
))}
|
||
</Section>
|
||
) : (
|
||
<div className="flex items-center gap-2 text-xs text-muted-foreground px-1 py-2">
|
||
<Loader2Icon className="size-3 animate-spin" />
|
||
等待推荐结果...
|
||
</div>
|
||
)}
|
||
</>
|
||
) : (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}
|
||
</div>
|
||
)}
|
||
|
||
{recommendedCards.length > 0 && (
|
||
<Section title={`推荐参会 (${recommendedCards.length})`} collapsible defaultOpen>
|
||
{recommendedCards.map((c) => (
|
||
<AgentCard
|
||
key={c.agent_id}
|
||
candidate={c}
|
||
reason={state.reasons[c.agent_id]}
|
||
recommended
|
||
checked={selectedIds.has(c.agent_id)}
|
||
onToggle={() => handleToggle(c.agent_id)}
|
||
/>
|
||
))}
|
||
</Section>
|
||
)}
|
||
|
||
{otherCards.length > 0 && (
|
||
<Section title={`其他候选 (${otherCards.length})`}>
|
||
{otherCards.map((c) => (
|
||
<AgentCard
|
||
key={c.agent_id}
|
||
candidate={c}
|
||
reason={undefined}
|
||
recommended={false}
|
||
checked={selectedIds.has(c.agent_id)}
|
||
onToggle={() => handleToggle(c.agent_id)}
|
||
/>
|
||
))}
|
||
</Section>
|
||
)}
|
||
</>
|
||
) : null}
|
||
</div>
|
||
</section>
|
||
|
||
<DialogFooter className="shrink-0 flex-row sm:justify-between items-center gap-2 flex-wrap border-t pt-3 mt-1">
|
||
<div className="flex items-center gap-3 text-xs">
|
||
<span
|
||
className={cn(
|
||
"tabular-nums",
|
||
selectedCount < MIN_SELECTED || selectedCount > MAX_SELECTED
|
||
? "text-destructive"
|
||
: "text-muted-foreground",
|
||
)}
|
||
>
|
||
{selectionHint}
|
||
</span>
|
||
{(state.phase === "ready" ||
|
||
state.phase === "fallback" ||
|
||
state.phase === "history" ||
|
||
state.phase === "error") && (
|
||
<Button
|
||
variant={state.phase === "history" ? "secondary" : "ghost"}
|
||
size="sm"
|
||
onClick={() => void start(true)}
|
||
className="h-7 px-2 text-xs"
|
||
>
|
||
<RefreshCwIcon className="size-3 mr-1" />
|
||
{state.phase === "history" ? "重新分析" : "重新推荐"}
|
||
</Button>
|
||
)}
|
||
</div>
|
||
<div className="flex gap-2">
|
||
<Button variant="outline" onClick={onCancel}>
|
||
取消
|
||
</Button>
|
||
<Button onClick={handleConfirm} disabled={!canConfirm}>
|
||
进入研讨
|
||
</Button>
|
||
</div>
|
||
</DialogFooter>
|
||
</>
|
||
)}
|
||
|
||
{/* ===== 业务链条模式 ===== */}
|
||
{mode === "chain" && (
|
||
<BusinessChainPicker
|
||
onConfirm={handleConfirmWithMode}
|
||
onCancel={onCancel}
|
||
onGoConfig={handleGoConfig}
|
||
onSelectedChainChange={(chain) => {
|
||
// 选中链条若配了默认执行模式 → 把顶部模式选择器默认设为它(用户仍可临时改)。
|
||
if (chain?.seatMode) setSeatMode(chain.seatMode);
|
||
}}
|
||
/>
|
||
)}
|
||
</DialogContent>
|
||
</Dialog>
|
||
);
|
||
}
|
||
|
||
/**
|
||
* 「模型生成内容」整段的可折叠外壳。
|
||
*
|
||
* 默认行为:
|
||
* - 「正在加载候选」+「正在生成推荐」期间(`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<boolean>(true);
|
||
const userTouchedRef = useRef<boolean>(false);
|
||
const hasAutoClosedRef = useRef<boolean>(false);
|
||
const modelOutputScrollRef = useRef<HTMLDivElement>(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 (
|
||
<section className="border rounded-md bg-muted/20 shrink-0 max-h-[38vh] flex flex-col min-h-0 overflow-hidden">
|
||
<button
|
||
type="button"
|
||
onClick={() => {
|
||
userTouchedRef.current = true;
|
||
setOpen((v) => !v);
|
||
}}
|
||
className="w-full shrink-0 flex items-center gap-2 px-3 py-2 text-[10px] font-bold text-slate-500 uppercase tracking-wider hover:bg-muted/40 transition-colors cursor-pointer"
|
||
>
|
||
{isLoading ? (
|
||
<Loader2Icon className="size-3 text-purple-500 shrink-0 animate-spin" />
|
||
) : (
|
||
<SparklesIcon className="size-3 text-purple-500 shrink-0" />
|
||
)}
|
||
<span className="flex-1 text-left">模型生成内容</span>
|
||
{statusBadge && (
|
||
<span
|
||
className={cn(
|
||
"text-[9.5px] font-bold uppercase tracking-wide px-1.5 py-0.5 rounded normal-case",
|
||
statusBadge.className,
|
||
)}
|
||
>
|
||
{statusBadge.label}
|
||
</span>
|
||
)}
|
||
<ChevronDownIcon
|
||
className={cn(
|
||
"size-3.5 text-slate-400 shrink-0 transition-transform",
|
||
open ? "rotate-180" : "rotate-0",
|
||
)}
|
||
/>
|
||
</button>
|
||
{open && (
|
||
<div className="relative min-h-0 flex-1 flex flex-col">
|
||
<div
|
||
ref={modelOutputScrollRef}
|
||
className="px-3 pb-3 min-h-0 flex-1 overflow-y-auto custom-scrollbar"
|
||
>
|
||
{children}
|
||
</div>
|
||
{!modelOutputAtBottom && (
|
||
<ScrollToBottomButton onClick={scrollModelOutputToBottom} />
|
||
)}
|
||
</div>
|
||
)}
|
||
</section>
|
||
);
|
||
}
|
||
|
||
/**
|
||
* 推荐弹窗顶部「模型生成内容」面板。
|
||
*
|
||
* 视觉与交互对齐主聊天 chats/new 的消息列表:
|
||
* - 顶部一行 spinner + 阶段文案(连接中 / 流式 / 完成)
|
||
* - 步骤折叠卡(MessageStepsCard,与对话气泡里同一实现)
|
||
* - 「思考过程」折叠卡(从 `<think>` 抽出来 reasoning,流式中默认展开)
|
||
* - 正文 Markdown(去掉了 `<think>` 标签后的 rationale)
|
||
* - 流式中正文末尾跟一个闪烁竖线
|
||
*/
|
||
function RecommenderOutput({ state }: { state: InternalState }) {
|
||
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>
|
||
);
|
||
}
|
||
|
||
if (state.phase === "error") {
|
||
return (
|
||
<div className="text-sm text-destructive">
|
||
推荐失败,请使用下方的「重新推荐」重试,或取消后再次进入。
|
||
</div>
|
||
);
|
||
}
|
||
|
||
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;
|
||
|
||
// 把 `<think>...</think>` 抽出来作 reasoning,剩下的 rationale 用 markdown 渲染。
|
||
// 这与 Step1Panel / Step2Panel 的处理方式完全一致。
|
||
const { content: cleanedRationale, reasoning } = splitInlineReasoning(state.rationale);
|
||
const hasRationale = cleanedRationale.length > 0;
|
||
const hasReasoning = !!reasoning;
|
||
|
||
return (
|
||
<div className="space-y-2">
|
||
{streamingLabel && (
|
||
<div className="flex items-center gap-2 text-muted-foreground text-xs">
|
||
<Loader2Icon className="size-3 animate-spin" />
|
||
{streamingLabel}
|
||
</div>
|
||
)}
|
||
|
||
{state.steps.length > 0 && (
|
||
<MessageStepsCard steps={state.steps} streaming={isStreaming} />
|
||
)}
|
||
|
||
{hasReasoning && (
|
||
<ReasoningBlock
|
||
streaming={isStreaming}
|
||
contentClassName={cn(
|
||
"overflow-y-auto custom-scrollbar",
|
||
isStreaming ? "max-h-none" : "max-h-48",
|
||
)}
|
||
>
|
||
{reasoning!}
|
||
</ReasoningBlock>
|
||
)}
|
||
|
||
{!hasRationale && !hasReasoning && isStreaming && (
|
||
<p className="text-xs text-muted-foreground">正在分析任务与候选智能体...</p>
|
||
)}
|
||
|
||
{hasRationale && (
|
||
<div
|
||
className={cn(
|
||
"overflow-y-auto custom-scrollbar rounded-md border border-slate-200 bg-white px-3 py-2.5 text-sm text-slate-700 leading-relaxed",
|
||
isStreaming ? "max-h-none" : "max-h-40",
|
||
)}
|
||
>
|
||
<MarkdownContent>{cleanedRationale}</MarkdownContent>
|
||
{isStreaming && <StreamingCursor />}
|
||
</div>
|
||
)}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
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 (
|
||
<div className="space-y-2">
|
||
{collapsible ? (
|
||
<button
|
||
type="button"
|
||
onClick={() => setOpen((v) => !v)}
|
||
className="flex w-full items-center gap-1 text-xs font-medium text-muted-foreground uppercase tracking-wide hover:text-foreground transition-colors cursor-pointer"
|
||
>
|
||
{open ? (
|
||
<ChevronUpIcon className="size-3" />
|
||
) : (
|
||
<ChevronDownIcon className="size-3" />
|
||
)}
|
||
<span>{title}</span>
|
||
</button>
|
||
) : (
|
||
<div className="text-xs font-medium text-muted-foreground uppercase tracking-wide">
|
||
{title}
|
||
</div>
|
||
)}
|
||
{/* flex flex-col + w-full + items-stretch:替代原 `grid gap-2`,
|
||
强制所有 AgentCard 满父宽。grid 在某些浏览器对 <button> 子项的
|
||
justify-self: stretch 处理不一致,导致"推荐参会"与"其他候选"
|
||
两个 Section 视觉上有几像素宽度差。 */}
|
||
{(!collapsible || open) && (
|
||
<div className="flex w-full flex-col gap-2">{children}</div>
|
||
)}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
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 (
|
||
<button
|
||
type="button"
|
||
onClick={onToggle}
|
||
className={cn(
|
||
// w-full:`<button>` 默认 inline-block,在 grid cell 里不一定拉满;
|
||
// 显式 w-full 保证推荐区与其他候选区的卡片**宽度严格一致**。
|
||
"w-full text-left rounded-md border p-3 transition-colors flex gap-3 items-start",
|
||
checked
|
||
? "border-primary bg-primary/5 hover:bg-primary/10"
|
||
: "border-border hover:bg-muted/40",
|
||
streaming && "animate-in fade-in slide-in-from-bottom-1 duration-300",
|
||
)}
|
||
>
|
||
{/* Visual check box — simulated, since the project ships no Checkbox primitive */}
|
||
<span
|
||
className={cn(
|
||
"mt-0.5 size-4 rounded border flex items-center justify-center shrink-0",
|
||
checked ? "border-primary bg-primary text-primary-foreground" : "border-input bg-background",
|
||
)}
|
||
>
|
||
{checked && <CheckIcon className="size-3" />}
|
||
</span>
|
||
<div className="flex-1 min-w-0">
|
||
<div className="flex items-center gap-2 flex-wrap">
|
||
<div className="font-medium text-sm truncate">{candidate.name || candidate.agent_id}</div>
|
||
{recommended && (
|
||
<span className="text-[10px] px-1.5 py-0.5 rounded bg-purple-500/10 text-purple-700 dark:text-purple-300 font-medium">
|
||
推荐
|
||
</span>
|
||
)}
|
||
</div>
|
||
{candidate.description && (
|
||
<div className="text-xs text-muted-foreground mt-0.5 line-clamp-2">
|
||
{candidate.description}
|
||
</div>
|
||
)}
|
||
{reason ? (
|
||
<div className="text-xs text-primary/80 mt-1 italic">
|
||
<span className="font-medium not-italic">推荐理由:</span> {reason}
|
||
</div>
|
||
) : streaming ? (
|
||
<div className="text-xs text-muted-foreground mt-1 italic">正在生成推荐理由...</div>
|
||
) : null}
|
||
</div>
|
||
</button>
|
||
);
|
||
}
|