业务链条

This commit is contained in:
fengxiangdebaozi committed 2026-06-02 21:15:46 +08:00
1 parent 30410b0a93
commit 9ae6184dc1
20 files changed
+2440 -24

No files matched your search

@@ -0,0 +1,266 @@
/**
* 业务链条选择面板(推荐弹窗「业务链条」模式的内容区)。
*
* 拉取当前用户的业务链条(`listChains()`),渲染卡片列表:
* - 卡片标题(链条 title)+ 存活席位计数。
* - 标题下一排**智能体名 tag**:按链条顺序从左到右排列、不同颜色(`getAvatarTypeFor`
* → `chainTagClasses`),tag 之间用 `→`(ArrowRight)箭头连接表达发言次序。
* - 链条里有 agent 已被删除 → 该 tag 置灰删除线 + 提示;卡片只用**存活**席位,
* 存活不足 `CHAIN_MIN_SEATS` 则不可使用。
*
* 选中一条 → 高亮;底部「进入研讨」回传 `SeatSelectionResult{ mode:"chain" }`,
* 由父弹窗的 `onConfirm` 透传给主页面(席位顺序 = 链条顺序)。
*
* 详见 `docs/multi-agent-business-chain-dev.md` §6.2 / §7 阶段 3。
*/
import { Fragment, useEffect, useMemo, useState } from "react";
import {
ArrowRightIcon,
CheckIcon,
LayersIcon,
Loader2Icon,
SettingsIcon,
TriangleAlertIcon,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { DialogFooter } from "@/components/ui/dialog";
import { cn } from "@/lib/utils";
import { listAgents } from "@/core/agents";
import { filterRecommendCandidates } from "../api/recommend";
import { listChains } from "../api/chains";
import {
CHAIN_MIN_SEATS,
chainTagClasses,
type BusinessChain,
type SeatSelectionResult,
} from "../lib/business-chain";
import { getAvatarTypeFor } from "../lib/roundtable-constants";
export interface BusinessChainPickerProps {
onConfirm: (result: SeatSelectionResult) => void;
onCancel: () => void;
/** 跳转到业务链条配置页(同时关闭弹窗)。 */
onGoConfig: () => void;
}
export function BusinessChainPicker({
onConfirm,
onCancel,
onGoConfig,
}: BusinessChainPickerProps) {
const [chains, setChains] = useState<BusinessChain[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [selectedId, setSelectedId] = useState<string | null>(null);
// null = 候选池未知(agent 列表加载失败)→ 不把任何席位判成「已删除」。
const [existingIds, setExistingIds] = useState<Set<string> | null>(null);
const [nameById, setNameById] = useState<Map<string, string>>(new Map());
useEffect(() => {
let cancelled = false;
void (async () => {
try {
const [chainList, agents] = await Promise.all([
listChains(),
listAgents().catch(() => null), // agent 列表失败不阻断链条展示
]);
if (cancelled) return;
setChains(chainList);
if (agents) {
const candidates = filterRecommendCandidates(agents);
setExistingIds(new Set(candidates.map((c) => c.agent_id)));
setNameById(new Map(candidates.map((c) => [c.agent_id, c.name])));
} else {
setExistingIds(null);
}
} catch (err) {
if (cancelled) return;
setError(err instanceof Error ? err.message : String(err));
} finally {
if (!cancelled) setLoading(false);
}
})();
return () => {
cancelled = true;
};
}, []);
const isExisting = useMemo(
() => (agentId: string) => existingIds === null || existingIds.has(agentId),
[existingIds],
);
const selectedChain = useMemo(
() => chains.find((c) => c.id === selectedId) ?? null,
[chains, selectedId],
);
const survivingSeats = useMemo(
() => (selectedChain ? selectedChain.seats.filter((s) => isExisting(s.agent_id)) : []),
[selectedChain, isExisting],
);
const canUse = !!selectedChain && survivingSeats.length >= CHAIN_MIN_SEATS;
const handleUse = () => {
if (!canUse || !selectedChain) return;
const agents = survivingSeats.map((s) => ({
agent_id: s.agent_id,
name: nameById.get(s.agent_id) ?? s.name,
}));
onConfirm({
agents,
mode: "chain",
chain: { id: selectedChain.id, title: selectedChain.title },
});
};
return (
<>
<section className="flex-1 min-h-0 flex flex-col overflow-hidden">
<div className="min-h-0 flex-1 overflow-y-auto custom-scrollbar pr-1 -mr-1">
{loading ? (
<div className="flex items-center gap-2 px-1 py-8 text-sm text-muted-foreground">
<Loader2Icon className="size-4 animate-spin" />
正在加载业务链条…
</div>
) : error ? (
<div className="rounded-md border border-destructive/30 bg-destructive/5 p-4 text-sm text-destructive">
加载业务链条失败:{error}
</div>
) : chains.length === 0 ? (
<div className="flex h-full flex-col items-center justify-center gap-3 px-6 py-10 text-center">
<LayersIcon className="size-10 text-primary/40" />
<div className="text-sm font-semibold">还没有业务链条</div>
<p className="max-w-sm text-xs leading-relaxed text-muted-foreground">
业务链条是可复用的有序智能体编排。先去配置页面创建第一条链条,
之后即可在这里选择使用。
</p>
<Button variant="outline" size="sm" onClick={onGoConfig} className="gap-1.5">
<SettingsIcon className="size-4" />
去配置业务链条
</Button>
</div>
) : (
<div className="space-y-2.5 py-0.5">
{chains.map((chain) => (
<ChainCard
key={chain.id}
chain={chain}
selected={chain.id === selectedId}
isExisting={isExisting}
nameById={nameById}
onSelect={() => setSelectedId(chain.id)}
/>
))}
</div>
)}
</div>
</section>
<DialogFooter className="shrink-0 flex-row sm:justify-between items-center gap-2 flex-wrap border-t pt-3 mt-1">
<Button variant="ghost" size="sm" onClick={onGoConfig} className="h-8 gap-1.5 text-xs">
<SettingsIcon className="size-3.5" />
配置链条
</Button>
<div className="flex items-center gap-2">
{selectedChain && !canUse && (
<span className="text-xs text-destructive">存活席位不足 {CHAIN_MIN_SEATS} 个</span>
)}
<Button variant="outline" onClick={onCancel}>
取消
</Button>
<Button onClick={handleUse} disabled={!canUse}>
进入研讨
</Button>
</div>
</DialogFooter>
</>
);
}
// ── 单张链条卡片 ─────────────────────────────────────────────────────────
function ChainCard({
chain,
selected,
isExisting,
nameById,
onSelect,
}: {
chain: BusinessChain;
selected: boolean;
isExisting: (agentId: string) => boolean;
nameById: Map<string, string>;
onSelect: () => void;
}) {
const survivingCount = chain.seats.filter((s) => isExisting(s.agent_id)).length;
const deletedCount = chain.seats.length - survivingCount;
const usable = survivingCount >= CHAIN_MIN_SEATS;
return (
<button
type="button"
onClick={onSelect}
className={cn(
"w-full rounded-xl border p-3 text-left transition-all",
selected
? "border-primary bg-primary/[0.06] ring-1 ring-primary/40"
: "border-border bg-card hover:border-primary/40 hover:bg-primary/[0.03]",
)}
>
{/* 标题行 */}
<div className="flex items-center gap-2">
<div className="truncate text-sm font-semibold">{chain.title || "未命名链条"}</div>
{selected && (
<span className="flex size-4 shrink-0 items-center justify-center rounded-full bg-primary text-primary-foreground">
<CheckIcon className="size-3" />
</span>
)}
<span className="ml-auto shrink-0 rounded-full bg-muted px-1.5 py-0.5 text-[10px] font-medium tabular-nums text-muted-foreground">
{chain.seats.length} 席
</span>
</div>
{chain.description && (
<div className="mt-1 line-clamp-1 text-xs text-muted-foreground">{chain.description}</div>
)}
{/* 智能体名 tag(按顺序,← 箭头连接) */}
<div className="mt-2 flex flex-wrap items-center gap-1">
{chain.seats.map((seat, i) => {
const alive = isExisting(seat.agent_id);
const label = nameById.get(seat.agent_id) ?? seat.name ?? seat.agent_id;
return (
<Fragment key={seat.agent_id}>
{i > 0 && (
<ArrowRightIcon className="size-3 shrink-0 text-muted-foreground/50" />
)}
<span
className={cn(
"rounded border px-1.5 py-0.5 text-[11px] font-medium",
alive
? chainTagClasses(getAvatarTypeFor(seat.agent_id, i))
: "border-dashed border-border bg-muted text-muted-foreground/60 line-through",
)}
title={alive ? undefined : "该智能体已不存在"}
>
{label}
</span>
</Fragment>
);
})}
</div>
{/* 删除提示 */}
{deletedCount > 0 && (
<div className="mt-2 flex items-center gap-1 text-[11px] text-amber-600 dark:text-amber-400">
<TriangleAlertIcon className="size-3 shrink-0" />
{usable
? `${deletedCount} 个智能体已删除,将按存活 ${survivingCount} 个席位研讨`
: `${deletedCount} 个智能体已删除,存活不足 ${CHAIN_MIN_SEATS} 个,暂不可用`}
</div>
)}
</button>
);
}
@@ -1,10 +1,12 @@
"use client";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useNavigate } from "react-router-dom";
import {
CheckIcon,
ChevronDownIcon,
ChevronUpIcon,
LayersIcon,
Loader2Icon,
RefreshCwIcon,
SparklesIcon,
@@ -29,7 +31,9 @@ import {
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 {
filterRecommendCandidates,
listRecommendHistory,
@@ -68,8 +72,12 @@ export interface RecommendAgentsDialogProps {
*/
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;
/**
* 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;
@@ -189,6 +197,9 @@ export function RecommendAgentsDialog({
// 映射也作用于弹窗;浅色不挂,弹窗浅色外观不变。
const { theme } = useTheme();
const isDark = theme === "dark";
const navigate = useNavigate();
// 席位来源模式:智能推荐 / 业务链条。默认**业务链条**。
const [mode, setMode] = useState<"recommend" | "chain">("chain");
const [state, setState] = useState<InternalState>(INITIAL_STATE);
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
@@ -442,18 +453,27 @@ export function RecommendAgentsDialog({
[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.
// 推荐管线只在「智能推荐」模式下跑一次。默认是业务链条模式 —— 此时不触发推荐
// 模型调用,等用户切到「智能推荐」tab 才启动;每次 open 内只跑一次(切 tab 来回
// 不重复跑),关闭时复位 latch。
const recommendStartedRef = useRef(false);
// 关闭 / 卸载时中止 in-flight 推荐流。
useEffect(() => {
if (!open) {
cancelInflight();
return;
}
void start(false);
return () => {
cancelInflight();
};
}, [open, start, 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) => {
@@ -510,9 +530,14 @@ export function RecommendAgentsDialog({
for (const c of otherCards) {
if (selectedIds.has(c.agent_id)) ordered.push({ agent_id: c.agent_id, name: c.name });
}
onConfirm(ordered);
onConfirm({ agents: ordered, mode: "recommend" });
}, [canConfirm, recommendedCards, otherCards, selectedIds, onConfirm]);
const handleGoConfig = useCallback(() => {
onCancel();
navigate("/page/workspace/roundtable/chains");
}, [navigate, onCancel]);
const handleOpenChange = useCallback(
(next: boolean) => {
if (!next) onCancel();
@@ -534,10 +559,45 @@ export function RecommendAgentsDialog({
选择参会智能体
</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>
{/* ===== 智能推荐模式(现状,零行为变更)===== */}
{mode === "recommend" && (
<>
{/* ============================================================
TOP: 模型生成内容
包含状态行 + 步骤卡 + 思考过程(`<think>`)+ 推荐理由 markdown。
@@ -684,6 +744,17 @@ export function RecommendAgentsDialog({
</Button>
</div>
</DialogFooter>
</>
)}
{/* ===== 业务链条模式 ===== */}
{mode === "chain" && (
<BusinessChainPicker
onConfirm={onConfirm}
onCancel={onCancel}
onGoConfig={handleGoConfig}
/>
)}
</DialogContent>
</Dialog>
);