feat(roundtable): 圆桌 Step2 分层 DAG 编排(并行/沙箱双模式 + 流程图 + 按需取全文)

数据模型/编辑器:链条加 stages 分层(前后端 + alembic 20260607_03);BusinessChainEditorPage 竖列 Stage 编辑 + 底部只读流程图预览;lib/dag-types + chain-stages 纯逻辑(含单测)。

调度(runDagOrchestration,方案 A 总控驱动):每个 stage 由总控经 agent_orchestration 派活给计划钉死的席位,批内 Promise.all 并行、批间 barrier 串行;末尾交回 runOrchestration 收口。抑制 leader 预广播 + 干净席位任务,根治『席位模仿派活』。

执行子模式:快速(双列·产物走正文·禁写文件 seat_parallel)/ 沙箱(单列·写 .md·沙箱跟随预览 seat);统一禁 bash(防 .py 脚本),提示词禁 .py。

显示:头像条 + 两列/单列 + ref 全量累积 + 节流 flush(仅选中渲染);DAG 流程图弹窗(按 stage 分列,节点随执行点亮,只到共识);沙箱跟随当前席位(防错位 + 修第一个席位自动开沙箱)。

按需取全文:新增 harness 只读工具 read_peer_delivery(从 run context 取网关注入的前序席位完整交付),席位默认看摘要、需要时取全文。

修:宽表溢出、并行自动下滑、data-lov-id Fragment 警告等。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
董宏凯andClaude Opus 4.8 committed 2026-06-07 21:20:58 +08:00
1 parent 5164fd362c
commit 7b8c11852e
26 files changed
+3719 -216

No files matched your search

@@ -5,21 +5,18 @@
* - 左栏:候选智能体列表(`listAgents()` + `filterRecommendCandidates` 复用,剔除
* intent/recommender/coordinator),支持**名称检索 + 标签筛选**(`TagSearchBar`,
* 服务端过滤),竖排卡片,可拖到右栏、也可点击快捷加入。
* - 右栏:当前链条的**有序**长条卡片(序号 + 名称 + 描述),可拖拽排序、上/下移、
* 删除单项;左栏拖入时按落点插入到对应位置。
* - 右栏:**分层编排** —— 把席位分到若干 **Stage**(竖向分组):同一 Stage 内并行、
* Stage 之间串行。可拖席位跨 Stage、整段 Stage 上下移、新建 / 删除 Stage;也提供
* 按钮(并入上/下一阶段、独立成阶段、移除)做无拖拽兜底。全单席位 Stage = 线性链。
*
* 拖拽用 `@dnd-kit`:右栏是 `SortableContext`(席位互相排序),左栏卡片是
* `useDraggable`(pool→右栏插入)。落点计算在 `onDragEnd`。
* 拖拽用 `@dnd-kit`:每个 Stage 是一个 droppable,Stage 内席位 `SortableContext`;
* 左栏卡片 `useDraggable`(pool→某 Stage / 新建 Stage 区插入)。落点计算在 `onDragEnd`。
*
* 视觉:对齐设计稿 `yewuliantiao`(浅红 / 绛红风格)。统一走 app 语义 token
* (`primary` 在浅色主题即设计稿的绛红 #c25555,深色主题自动切蓝),配规范小圆角
* (输入/按钮/tag 2px、卡片/分栏 4px)+ 克制阴影。**不**套圆桌页的
* `roundtable-planning` scope。
* 持久化走 `api/chains.ts`:`seats` = 各 Stage 展平的有序席位;`stages` = 分层(全单
* 席位时存 null,即线性,老行为不变)。席位数约束 2 ≤ N ≤ 8、agent 去重。分层操作的
* 纯逻辑在 `lib/chain-stages.ts`(可单测)。
*
* 持久化走 `api/chains.ts`(后端 MySQL `/api/roundtable-chains`)。席位数约束
* 2 ≤ N ≤ 8、agent 去重,保存时校验(后端 `_validate_seats` 也兜底)。
*
* 详见 `docs/multi-agent-business-chain-dev.md` §7 阶段 1。
* 详见 `docs/roundtable-dag-orchestration.md` §2(Phase 2,分层编辑器)。
*/
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useNavigate, useSearchParams } from "react-router-dom";
@@ -30,11 +27,13 @@ import {
Bot,
ChevronDown,
ChevronUp,
GitBranch,
GripVertical,
ListOrdered,
Layers,
Loader2,
Plus,
Save,
SplitSquareVertical,
Trash2,
UserPlus,
X,
@@ -53,7 +52,6 @@ import {
} from "@dnd-kit/core";
import {
SortableContext,
arrayMove,
useSortable,
verticalListSortingStrategy,
} from "@dnd-kit/sortable";
@@ -81,11 +79,30 @@ import {
type BusinessChain,
type ChainSeat,
} from "@/roundtable-planning/lib/business-chain";
import {
addEmptyStage,
addSeatAsNewStage,
addSeatToStage,
chainToStageGroups,
countSeats,
deleteStage as deleteStageGroup,
findStageIndexOfSeat,
moveSeatToStage,
moveStage,
removeSeat as removeSeatFromGroups,
seatExistsInGroups,
splitSeatToNewStage,
stageGroupsToSeats,
stageGroupsToStagePayload,
type StageGroups,
} from "@/roundtable-planning/lib/chain-stages";
import { getAvatarTypeFor } from "@/roundtable-planning/lib/roundtable-constants";
import { DagFlowChart } from "@/roundtable-planning/components/DagFlowChart";
const POOL_PREFIX = "pool::";
const SEAT_PREFIX = "seat::";
const SEATS_DROPPABLE_ID = "seats-droppable";
const STAGE_PREFIX = "stage::";
const NEWSTAGE_DROPPABLE_ID = "newstage-droppable";
// 规范圆角(§4):输入/按钮/tag 2px,卡片/分栏 4px。app 默认 --radius=12px 偏大,
// 这里用 arbitrary 值精确命中规范。
@@ -115,7 +132,8 @@ export default function BusinessChainEditorPage() {
const [currentChainId, setCurrentChainId] = useState<string | null>(null);
const [title, setTitle] = useState("");
const [description, setDescription] = useState("");
const [seats, setSeats] = useState<ChainSeat[]>([]);
// 分层编排是唯一数据源;落库时展平为 seats + 折叠为 stages。
const [stageGroups, setStageGroups] = useState<StageGroups>([]);
const [saving, setSaving] = useState(false);
const [activeDrag, setActiveDrag] = useState<ActiveDrag>(null);
@@ -130,7 +148,34 @@ export default function BusinessChainEditorPage() {
for (const a of pool) m.set(a.agent_id, a);
return m;
}, [pool]);
const seatIdSet = useMemo(() => new Set(seats.map((s) => s.agent_id)), [seats]);
const seatIdSet = useMemo(
() => new Set(stageGroups.flat().map((s) => s.agent_id)),
[stageGroups],
);
const seatCount = useMemo(() => countSeats(stageGroups), [stageGroups]);
// ─── Phase 7 只读流程图预览(§2.2 底部 / §7)──────────────────────────────
// 把当前分层(去掉空 stage)映射成 DagFlowChart 的 stages,并提供席位名/配色解析。
const previewStages = useMemo(
() =>
stageGroups
.filter((g) => g.length > 0)
.map((g, i) => ({ id: `stage-${i}`, agentIds: g.map((s) => s.agent_id) })),
[stageGroups],
);
const seatNameById = useMemo(() => {
const m = new Map<string, string>();
for (const g of stageGroups)
for (const s of g) m.set(s.agent_id.toLowerCase(), s.name || s.agent_id);
return m;
}, [stageGroups]);
const resolvePreviewSeat = useCallback(
(agentId: string, order: number) => ({
name: seatNameById.get(agentId.toLowerCase()) ?? agentId,
avatarType: getAvatarTypeFor(agentId, order),
}),
[seatNameById],
);
// ─── 链条列表(一次性)─────────────────────────────────────────────────
const refreshChains = useCallback(async () => {
@@ -175,14 +220,14 @@ export default function BusinessChainEditorPage() {
setCurrentChainId(chain.id);
setTitle(chain.title);
setDescription(chain.description ?? "");
setSeats(chain.seats.map((s) => ({ ...s })));
setStageGroups(chainToStageGroups(chain));
}, []);
const startNewChain = useCallback(() => {
setCurrentChainId(null);
setTitle("");
setDescription("");
setSeats([]);
setStageGroups([]);
}, []);
// ─── URL 参数 chainId:从「业务链条」弹窗点「设置」进来时自动切到该链条 ──────
@@ -198,43 +243,65 @@ export default function BusinessChainEditorPage() {
appliedChainParamRef.current = true; // 命中或链条已不存在,都不再重试
}, [chains, searchParams, loadChain]);
// ─── 席位增删改 ───────────────────────────────────────────────────────
const addAgentToSeats = useCallback(
(agentId: string, atIndex?: number) => {
// ─── 席位增删改(全部委托给 lib/chain-stages 纯函数)────────────────────
const toChainSeat = useCallback(
(agentId: string): ChainSeat | null => {
const agent = poolById.get(agentId);
if (!agent) return;
setSeats((prev) => {
if (prev.some((s) => s.agent_id === agentId)) {
toast.info(`「${agent.name}」已在链条中`);
return prev;
}
if (prev.length >= CHAIN_MAX_SEATS) {
toast.warning(`链条最多 ${CHAIN_MAX_SEATS} 个席位`);
return prev;
}
const seat: ChainSeat = {
agent_id: agent.agent_id,
name: agent.name,
description: agent.description,
};
const next = [...prev];
const i = atIndex == null ? next.length : Math.max(0, Math.min(atIndex, next.length));
next.splice(i, 0, seat);
return next;
});
if (!agent) return null;
return { agent_id: agent.agent_id, name: agent.name, description: agent.description };
},
[poolById],
);
/** pool 点击加入:末尾追加一个新单席位 Stage(线性追加,默认行为)。 */
const addAgentAsNewStage = useCallback(
(agentId: string) => {
const seat = toChainSeat(agentId);
if (!seat) return;
setStageGroups((prev) => {
if (seatExistsInGroups(prev, agentId)) {
toast.info(`「${seat.name}」已在链条中`);
return prev;
}
if (countSeats(prev) >= CHAIN_MAX_SEATS) {
toast.warning(`链条最多 ${CHAIN_MAX_SEATS} 个席位`);
return prev;
}
return addSeatAsNewStage(prev, seat);
});
},
[toChainSeat],
);
const removeSeat = useCallback((agentId: string) => {
setSeats((prev) => prev.filter((s) => s.agent_id !== agentId));
setStageGroups((prev) => removeSeatFromGroups(prev, agentId));
}, []);
const moveSeat = useCallback((index: number, dir: -1 | 1) => {
setSeats((prev) => {
const target = index + dir;
if (target < 0 || target >= prev.length) return prev;
return arrayMove(prev, index, target);
const mergeSeatToStage = useCallback((agentId: string, targetStageIdx: number) => {
setStageGroups((prev) => moveSeatToStage(prev, agentId, targetStageIdx));
}, []);
const splitSeat = useCallback((agentId: string) => {
setStageGroups((prev) => splitSeatToNewStage(prev, agentId));
}, []);
const reorderStage = useCallback((stageIdx: number, dir: -1 | 1) => {
setStageGroups((prev) => moveStage(prev, stageIdx, dir));
}, []);
const appendEmptyStage = useCallback(() => {
setStageGroups((prev) => addEmptyStage(prev));
}, []);
const removeStage = useCallback((stageIdx: number) => {
setStageGroups((prev) => {
const stage = prev[stageIdx];
if (stage && stage.length > 0) {
if (!window.confirm(`删除 Stage ${stageIdx + 1} 会移除其中 ${stage.length} 个席位,确认?`)) {
return prev;
}
}
return deleteStageGroup(prev, stageIdx);
});
}, []);
@@ -248,11 +315,11 @@ export default function BusinessChainEditorPage() {
setActiveDrag({ kind: "pool", agentId, name: a?.name ?? agentId });
} else if (id.startsWith(SEAT_PREFIX)) {
const agentId = id.slice(SEAT_PREFIX.length);
const s = seats.find((x) => x.agent_id === agentId);
setActiveDrag({ kind: "seat", agentId, name: s?.name ?? agentId });
const a = poolById.get(agentId);
setActiveDrag({ kind: "seat", agentId, name: a?.name ?? agentId });
}
},
[poolById, seats],
[poolById],
);
const onDragEnd = useCallback(
@@ -262,33 +329,57 @@ export default function BusinessChainEditorPage() {
const overId = e.over ? String(e.over.id) : null;
if (!overId) return;
const overSeatIndex = overId.startsWith(SEAT_PREFIX)
? seats.findIndex((s) => SEAT_PREFIX + s.agent_id === overId)
: -1;
// 解析落点 → 目标 Stage 下标 + 该 Stage 内插入位置;-1 表示「新建 Stage 区」。
let targetStage = -1;
let atIndex: number | undefined;
if (overId === NEWSTAGE_DROPPABLE_ID) {
targetStage = -1;
} else if (overId.startsWith(STAGE_PREFIX)) {
targetStage = Number(overId.slice(STAGE_PREFIX.length));
} else if (overId.startsWith(SEAT_PREFIX)) {
const overAgent = overId.slice(SEAT_PREFIX.length);
targetStage = findStageIndexOfSeat(stageGroups, overAgent);
atIndex = stageGroups[targetStage]?.findIndex((s) => s.agent_id === overAgent);
}
const toNewStage = overId === NEWSTAGE_DROPPABLE_ID;
if (activeId.startsWith(POOL_PREFIX)) {
const agentId = activeId.slice(POOL_PREFIX.length);
const insertAt = overSeatIndex >= 0 ? overSeatIndex : seats.length;
addAgentToSeats(agentId, insertAt);
if (seatIdSet.has(agentId)) return;
const seat = toChainSeat(agentId);
if (!seat) return;
if (seatCount >= CHAIN_MAX_SEATS) {
toast.warning(`链条最多 ${CHAIN_MAX_SEATS} 个席位`);
return;
}
setStageGroups((prev) =>
toNewStage || targetStage < 0
? addSeatAsNewStage(prev, seat)
: addSeatToStage(prev, seat, targetStage, atIndex),
);
return;
}
if (activeId.startsWith(SEAT_PREFIX)) {
const fromIndex = seats.findIndex(
(s) => SEAT_PREFIX + s.agent_id === activeId,
);
if (fromIndex < 0) return;
const toIndex = overSeatIndex >= 0 ? overSeatIndex : seats.length - 1;
if (fromIndex === toIndex) return;
setSeats((prev) => arrayMove(prev, fromIndex, toIndex));
const agentId = activeId.slice(SEAT_PREFIX.length);
setStageGroups((prev) => {
if (toNewStage) {
// 拖到「新建 Stage」区 = 抽出独立成最后一个 Stage。
const withEmpty = addEmptyStage(prev);
return moveSeatToStage(withEmpty, agentId, withEmpty.length - 1);
}
if (targetStage < 0) return prev;
return moveSeatToStage(prev, agentId, targetStage, atIndex);
});
}
},
[seats, addAgentToSeats],
[stageGroups, seatIdSet, seatCount, toChainSeat],
);
// ─── 保存 / 删除 ──────────────────────────────────────────────────────
const seatCountInvalid =
seats.length < CHAIN_MIN_SEATS || seats.length > CHAIN_MAX_SEATS;
const seatCountInvalid = seatCount < CHAIN_MIN_SEATS || seatCount > CHAIN_MAX_SEATS;
const hasEmptyStage = stageGroups.some((g) => g.length === 0);
const canSave = title.trim().length > 0 && !seatCountInvalid && !saving;
const handleSave = useCallback(async () => {
@@ -302,16 +393,20 @@ export default function BusinessChainEditorPage() {
}
setSaving(true);
try {
const payloadSeats = seats.map((s) => ({
// 展平 + 折叠:seats 用候选池最新 name/description 覆盖快照;stages 全单席位 → null。
const flat = stageGroupsToSeats(stageGroups);
const payloadSeats = flat.map((s) => ({
agent_id: s.agent_id,
name: poolById.get(s.agent_id)?.name ?? s.name,
description: poolById.get(s.agent_id)?.description ?? s.description ?? "",
}));
const stages = stageGroupsToStagePayload(stageGroups);
if (currentChainId) {
const updated = await updateChain(currentChainId, {
title: title.trim(),
description: description.trim() || undefined,
seats: payloadSeats,
stages,
});
if (!updated) {
toast.error("链条已不存在,可能被删除");
@@ -327,6 +422,7 @@ export default function BusinessChainEditorPage() {
title: title.trim(),
description: description.trim() || undefined,
seats: payloadSeats,
stages,
});
setCurrentChainId(created.id);
toast.success("已创建业务链条");
@@ -340,7 +436,7 @@ export default function BusinessChainEditorPage() {
}, [
title,
description,
seats,
stageGroups,
seatCountInvalid,
currentChainId,
poolById,
@@ -367,7 +463,6 @@ export default function BusinessChainEditorPage() {
}, [currentChainId, title, startNewChain, refreshChains]);
// ─── Render ──────────────────────────────────────────────────────────
const seatItemIds = seats.map((s) => SEAT_PREFIX + s.agent_id);
const triggerLabel = currentChainId ? title || "未命名链条" : "+ 新建链条…";
return (
@@ -399,7 +494,7 @@ export default function BusinessChainEditorPage() {
<div className="leading-tight">
<div className="text-base font-bold text-foreground">业务链条配置</div>
<div className="text-[11px] font-medium tracking-wide text-muted-foreground">
编排有序的智能体研讨链路
分层编排:同层并行 · 层间串行
</div>
</div>
</div>
@@ -449,7 +544,7 @@ export default function BusinessChainEditorPage() {
)}
>
<span className="truncate">
{c.title || "未命名链条"}({c.seats.length} 席)
{c.title || "未命名链条"}({c.seats.length} 席{c.stages?.length ? " · 分层" : ""})
</span>
{c.id === currentChainId && (
<span className={cn("ml-2 shrink-0 bg-primary/15 px-1.5 py-0.5 text-[10px] text-primary", R_CTRL)}>
@@ -620,20 +715,25 @@ export default function BusinessChainEditorPage() {
key={a.agent_id}
agent={a}
inChain={seatIdSet.has(a.agent_id)}
onAdd={() => addAgentToSeats(a.agent_id)}
onAdd={() => addAgentAsNewStage(a.agent_id)}
/>
))
)}
</div>
</section>
{/* 右栏:有序席位 */}
<SeatsColumn
seats={seats}
seatItemIds={seatItemIds}
{/* 右栏:分层 Stage */}
<StagesColumn
stageGroups={stageGroups}
seatCount={seatCount}
seatCountInvalid={seatCountInvalid}
onRemove={removeSeat}
onMove={moveSeat}
hasEmptyStage={hasEmptyStage}
onAddStage={appendEmptyStage}
onRemoveStage={removeStage}
onReorderStage={reorderStage}
onRemoveSeat={removeSeat}
onMergeSeat={mergeSeatToStage}
onSplitSeat={splitSeat}
/>
</main>
@@ -652,9 +752,27 @@ export default function BusinessChainEditorPage() {
</DragOverlay>
</DndContext>
{/* Phase 7:分层 DAG 只读流程图预览(§2.2 底部)。空编排时不渲染。 */}
{previewStages.length > 0 && (
<section className="shrink-0 border-t border-border bg-card px-6 py-2">
<div className="mb-1 flex items-center gap-2 text-[11px] font-semibold text-muted-foreground">
<span>编排预览</span>
<span className="text-muted-foreground/50">
总控派活 → 各 Stage(串行)→ 共识 → 结果绘制
</span>
</div>
<DagFlowChart
stages={previewStages}
resolveSeat={resolvePreviewSeat}
showReportMilestone={false}
compact
/>
</section>
)}
{/* 页脚 */}
<footer className="shrink-0 select-none border-t border-border bg-card px-6 py-3 text-center text-[11px] text-muted-foreground">
编排有序的业务链条,让智能体决策更有深度。保存后,配置将自动同步至圆桌。
分层编排:同一 Stage 内的席位并行研讨,Stage 之间串行。全单席位 = 线性链。保存后自动同步至圆桌。
</footer>
</div>
);
@@ -733,22 +851,42 @@ function PoolAgentCard({
);
}
// ── 右栏(droppable 容器 + sortable 列表)───────────────────────────────
// ── 右栏(分层 Stage 容器)───────────────────────────────────────────────
function SeatsColumn({
seats,
seatItemIds,
function StagesColumn({
stageGroups,
seatCount,
seatCountInvalid,
onRemove,
onMove,
hasEmptyStage,
onAddStage,
onRemoveStage,
onReorderStage,
onRemoveSeat,
onMergeSeat,
onSplitSeat,
}: {
seats: ChainSeat[];
seatItemIds: string[];
stageGroups: StageGroups;
seatCount: number;
seatCountInvalid: boolean;
onRemove: (agentId: string) => void;
onMove: (index: number, dir: -1 | 1) => void;
hasEmptyStage: boolean;
onAddStage: () => void;
onRemoveStage: (stageIdx: number) => void;
onReorderStage: (stageIdx: number, dir: -1 | 1) => void;
onRemoveSeat: (agentId: string) => void;
onMergeSeat: (agentId: string, targetStageIdx: number) => void;
onSplitSeat: (agentId: string) => void;
}) {
const { setNodeRef, isOver } = useDroppable({ id: SEATS_DROPPABLE_ID });
// 跨 Stage 的全局序号(头像编号):每个 Stage 起始累加。
const stageStartIndex = useMemo(() => {
const out: number[] = [];
let acc = 0;
for (const g of stageGroups) {
out.push(acc);
acc += g.length;
}
return out;
}, [stageGroups]);
return (
<section
className={cn(
@@ -760,16 +898,26 @@ function SeatsColumn({
<div className="flex shrink-0 items-center justify-between border-b border-border bg-muted/40 px-5 py-4">
<div className="flex items-center gap-2">
<span className={cn("flex size-5 items-center justify-center bg-primary/10", R_CTRL)}>
<ListOrdered className="size-3.5 text-primary" />
<Layers className="size-3.5 text-primary" />
</span>
<h2 className="text-sm font-bold tracking-wide text-foreground">链条席位</h2>
<h2 className="text-sm font-bold tracking-wide text-foreground">链条编排</h2>
<span className={cn("border border-border bg-muted px-2 py-0.5 text-[10px] font-bold text-muted-foreground", R_CTRL)}>
按顺序发言
同层并行 · 层间串行
</span>
</div>
<div className="flex select-none items-center gap-1 text-xs">
<span className="font-medium text-muted-foreground">配置席位</span>
<div className="flex select-none items-center gap-2 text-xs">
<button
type="button"
onClick={onAddStage}
className={cn(
"flex items-center gap-1 border border-primary/30 bg-primary/5 px-2 py-1 font-medium text-primary transition hover:bg-primary/10",
R_CTRL,
)}
>
<Plus className="size-3.5" />
新建 Stage
</button>
<span
className={cn(
"border px-2 py-0.5 font-bold tabular-nums",
@@ -779,20 +927,14 @@ function SeatsColumn({
: "border-primary/30 bg-primary/10 text-primary",
)}
>
{seats.length} / {CHAIN_MAX_SEATS}
{seats.length < CHAIN_MIN_SEATS && ` · 至少 ${CHAIN_MIN_SEATS}`}
{seatCount} / {CHAIN_MAX_SEATS}
{seatCount < CHAIN_MIN_SEATS && ` · 至少 ${CHAIN_MIN_SEATS}`}
</span>
</div>
</div>
<div
ref={setNodeRef}
className={cn(
"min-h-0 flex-1 space-y-3 overflow-y-auto p-5 transition-colors",
isOver && "bg-primary/[0.03]",
)}
>
{seats.length === 0 ? (
<div className="min-h-0 flex-1 space-y-3 overflow-y-auto p-5">
{seatCount === 0 && stageGroups.length === 0 ? (
<div
className={cn(
"m-1 flex h-full flex-col items-center justify-center border border-dashed border-border bg-card/50 px-8 py-16 text-center",
@@ -800,29 +942,166 @@ function SeatsColumn({
)}
>
<div className="mb-3 flex size-12 items-center justify-center rounded-full bg-primary/10 text-primary">
<ListOrdered className="size-6" />
<Layers className="size-6" />
</div>
<h3 className="mb-1 text-sm font-bold text-foreground">暂无席位</h3>
<p className="max-w-sm text-xs leading-relaxed text-muted-foreground">
该业务链条当前为空。请从左侧「候选智能体」点击或拖拽,将其按顺序编排加入此处。
从左侧「候选智能体」点击或拖拽加入。每次加入是一个串行 Stage;把席位拖到同一个
Stage 里即可让它们并行。
</p>
</div>
) : (
<>
{stageGroups.map((group, stageIdx) => (
<StageSection
key={stageIdx}
stageIdx={stageIdx}
group={group}
stageCount={stageGroups.length}
startIndex={stageStartIndex[stageIdx]}
onRemoveStage={() => onRemoveStage(stageIdx)}
onReorderStage={(dir) => onReorderStage(stageIdx, dir)}
onRemoveSeat={onRemoveSeat}
onMergeSeat={onMergeSeat}
onSplitSeat={onSplitSeat}
/>
))}
<NewStageDropZone hasEmptyStage={hasEmptyStage} onAddStage={onAddStage} />
</>
)}
</div>
</section>
);
}
// ── 单个 Stage(droppable 容器 + Stage 内 sortable 列表)──────────────────
function StageSection({
stageIdx,
group,
stageCount,
startIndex,
onRemoveStage,
onReorderStage,
onRemoveSeat,
onMergeSeat,
onSplitSeat,
}: {
stageIdx: number;
group: ChainSeat[];
stageCount: number;
startIndex: number;
onRemoveStage: () => void;
onReorderStage: (dir: -1 | 1) => void;
onRemoveSeat: (agentId: string) => void;
onMergeSeat: (agentId: string, targetStageIdx: number) => void;
onSplitSeat: (agentId: string) => void;
}) {
const { setNodeRef, isOver } = useDroppable({ id: STAGE_PREFIX + stageIdx });
const isParallel = group.length > 1;
const isFirstStage = stageIdx === 0;
const isLastStage = stageIdx === stageCount - 1;
const seatItemIds = group.map((s) => SEAT_PREFIX + s.agent_id);
return (
<div className={cn("border border-border bg-muted/20", R_CARD, PANEL_SHADOW)}>
{/* Stage 头 */}
<div className="flex items-center justify-between gap-2 border-b border-border bg-muted/40 px-3 py-2">
<div className="flex items-center gap-2">
<span
className={cn(
"flex items-center gap-1 border px-2 py-0.5 text-[11px] font-bold tabular-nums",
R_CTRL,
"border-primary/30 bg-primary/10 text-primary",
)}
>
<GitBranch className="size-3" />
Stage {stageIdx + 1}
</span>
<span
className={cn(
"border px-1.5 py-0.5 text-[10px] font-semibold",
R_CTRL,
isParallel
? "border-amber-400/40 bg-amber-400/10 text-amber-600 dark:text-amber-300"
: "border-border bg-muted text-muted-foreground",
)}
>
{isParallel ? `并行 ${group.length}` : "串行"}
</span>
</div>
<div className="flex items-center gap-0.5">
<button
type="button"
onClick={() => onReorderStage(-1)}
disabled={isFirstStage}
title="上移 Stage"
className={cn(
"p-1 transition",
R_CTRL,
isFirstStage
? "pointer-events-none text-muted-foreground/30"
: "text-muted-foreground hover:bg-muted hover:text-foreground",
)}
>
<ChevronUp className="size-3.5" />
</button>
<button
type="button"
onClick={() => onReorderStage(1)}
disabled={isLastStage}
title="下移 Stage"
className={cn(
"p-1 transition",
R_CTRL,
isLastStage
? "pointer-events-none text-muted-foreground/30"
: "text-muted-foreground hover:bg-muted hover:text-foreground",
)}
>
<ChevronDown className="size-3.5" />
</button>
<button
type="button"
onClick={onRemoveStage}
title="删除 Stage"
className={cn("ml-0.5 p-1 text-muted-foreground/60 transition-colors hover:bg-primary/10 hover:text-primary", R_CTRL)}
>
<Trash2 className="size-3.5" />
</button>
</div>
</div>
{/* Stage 内席位 */}
<div
ref={setNodeRef}
className={cn("space-y-2 p-2.5 transition-colors", isOver && "bg-primary/[0.04]")}
>
{group.length === 0 ? (
<div className={cn("border border-dashed border-border bg-card/40 px-3 py-4 text-center text-[11px] text-muted-foreground", R_CARD)}>
空 Stage —— 把席位拖到此处,或删除该 Stage。
</div>
) : (
<SortableContext items={seatItemIds} strategy={verticalListSortingStrategy}>
{seats.map((seat, index) => (
{group.map((seat, i) => (
<SeatStrip
key={seat.agent_id}
seat={seat}
index={index}
total={seats.length}
onRemove={() => onRemove(seat.agent_id)}
onMove={(dir) => onMove(index, dir)}
globalIndex={startIndex + i}
stageIdx={stageIdx}
isFirstStage={isFirstStage}
isLastStage={isLastStage}
canSplit={isParallel}
onRemove={() => onRemoveSeat(seat.agent_id)}
onMergeUp={() => onMergeSeat(seat.agent_id, stageIdx - 1)}
onMergeDown={() => onMergeSeat(seat.agent_id, stageIdx + 1)}
onSplit={() => onSplitSeat(seat.agent_id)}
/>
))}
</SortableContext>
)}
</div>
</section>
</div>
);
}
@@ -830,22 +1109,29 @@ function SeatsColumn({
function SeatStrip({
seat,
index,
total,
globalIndex,
isFirstStage,
isLastStage,
canSplit,
onRemove,
onMove,
onMergeUp,
onMergeDown,
onSplit,
}: {
seat: ChainSeat;
index: number;
total: number;
globalIndex: number;
stageIdx: number;
isFirstStage: boolean;
isLastStage: boolean;
canSplit: boolean;
onRemove: () => void;
onMove: (dir: -1 | 1) => void;
onMergeUp: () => void;
onMergeDown: () => void;
onSplit: () => void;
}) {
const { attributes, listeners, setNodeRef, transform, transition, isDragging } =
useSortable({ id: SEAT_PREFIX + seat.agent_id });
const avatarType = getAvatarTypeFor(seat.agent_id, index);
const isFirst = index === 0;
const isLast = index === total - 1;
const avatarType = getAvatarTypeFor(seat.agent_id, globalIndex);
return (
<div
ref={setNodeRef}
@@ -863,7 +1149,7 @@ function SeatStrip({
className="flex w-7 shrink-0 cursor-grab touch-none items-center justify-center border-r border-border bg-muted/40 text-muted-foreground/60 transition-colors hover:text-foreground active:cursor-grabbing"
{...attributes}
{...listeners}
title="拖动排序"
title="拖动到其它 Stage / 排序"
>
<GripVertical className="size-3.5" />
</button>
@@ -877,7 +1163,7 @@ function SeatStrip({
chainTagClasses(avatarType),
)}
>
{index + 1}
{globalIndex + 1}
</span>
</div>
@@ -891,17 +1177,17 @@ function SeatStrip({
)}
</div>
{/* 控制:上移 / 下移 / 移除 */}
{/* 控制:并入上一阶段 / 独立成阶段 / 并入下一阶段 / 移除 */}
<div className="flex shrink-0 items-center gap-0.5 border-l border-border px-2">
<button
type="button"
onClick={() => onMove(-1)}
disabled={isFirst}
title="上移席位"
onClick={onMergeUp}
disabled={isFirstStage}
title="并入上一阶段(与其并行)"
className={cn(
"p-1 transition",
R_CTRL,
isFirst
isFirstStage
? "pointer-events-none text-muted-foreground/30"
: "text-muted-foreground hover:bg-muted hover:text-foreground",
)}
@@ -910,13 +1196,28 @@ function SeatStrip({
</button>
<button
type="button"
onClick={() => onMove(1)}
disabled={isLast}
title="下移席位"
onClick={onSplit}
disabled={!canSplit}
title="从本阶段拆出,独立成新阶段"
className={cn(
"p-1 transition",
R_CTRL,
isLast
!canSplit
? "pointer-events-none text-muted-foreground/30"
: "text-muted-foreground hover:bg-muted hover:text-foreground",
)}
>
<SplitSquareVertical className="size-3.5" />
</button>
<button
type="button"
onClick={onMergeDown}
disabled={isLastStage}
title="并入下一阶段(与其并行)"
className={cn(
"p-1 transition",
R_CTRL,
isLastStage
? "pointer-events-none text-muted-foreground/30"
: "text-muted-foreground hover:bg-muted hover:text-foreground",
)}
@@ -938,3 +1239,35 @@ function SeatStrip({
</div>
);
}
// ── 「新建 Stage」落区(拖席位到此 = 独立成最后一个 Stage)──────────────────
function NewStageDropZone({
hasEmptyStage,
onAddStage,
}: {
hasEmptyStage: boolean;
onAddStage: () => void;
}) {
const { setNodeRef, isOver } = useDroppable({ id: NEWSTAGE_DROPPABLE_ID });
return (
<button
type="button"
ref={setNodeRef}
onClick={onAddStage}
disabled={hasEmptyStage}
className={cn(
"flex w-full items-center justify-center gap-1.5 border border-dashed px-3 py-3 text-xs font-medium transition",
R_CARD,
isOver
? "border-primary bg-primary/[0.06] text-primary"
: "border-border bg-card/40 text-muted-foreground hover:border-primary/40 hover:text-primary",
hasEmptyStage && "cursor-not-allowed opacity-50 hover:border-border hover:text-muted-foreground",
)}
title={hasEmptyStage ? "已有空 Stage,先填充它" : "新建一个串在最后的 Stage"}
>
<Plus className="size-3.5" />
新建 Stage(串在最后) · 或把席位拖到此处独立成阶段
</button>
);
}
@@ -51,6 +51,7 @@ import {
import { useTheme } from "@/contexts/ThemeContext";
import { useArtifacts } from "@/components/workspace/artifacts";
import { useSidebarSafe } from "@/components/ui/sidebar";
import { cn } from "@/lib/utils";
import { useModels } from "@/core/models/hooks";
@@ -84,6 +85,7 @@ import {
type SelectedAgent,
} from "@/roundtable-planning/lib/roundtable-constants";
import type { SeatSelectionResult } from "@/roundtable-planning/lib/business-chain";
import type { OrchestrationPlan } from "@/roundtable-planning/lib/dag-types";
import { getJobByDraft, startJob } from "@/roundtable-planning/api/roundtable-jobs";
export default function RoundtablePlanningPage() {
@@ -104,13 +106,19 @@ export default function RoundtablePlanningPage() {
// 「导入会商」弹窗(输入分享码把别人分享的会商复制到本账号)。
const [isImportOpen, setIsImportOpen] = useState<boolean>(false);
const [selectedModel, setSelectedModel] = useState<string>("");
// Step 2 编排模式:recommend = 总控自由派活;chain = 总控按业务链条顺序派活。
// Step 2 编排模式:recommend = 总控自由派活;chain = 总控按业务链条顺序派活;
// dag = 分层 DAG(stage 内并行、stage 间串行,配合 orchestrationPlan)。
// 由推荐弹窗确认时的 SeatSelectionResult.mode 决定(见 handleConfirmAgents)。
const [orchestrationMode, setOrchestrationMode] = useState<"recommend" | "chain">(
const [orchestrationMode, setOrchestrationMode] = useState<"recommend" | "chain" | "dag">(
"recommend",
);
// chain 模式来源链条(仅展示/持久化用)。
const [chainMeta, setChainMeta] = useState<{ id: string; title: string } | null>(null);
// dag 模式的分层编排计划(Phase 2 编辑器产出;持久化进 step2.orchestrationPlan)。
const [orchestrationPlan, setOrchestrationPlan] = useState<OrchestrationPlan | null>(null);
// dag 执行子模式:fast(并行双列禁写)/ sandbox(并行单列可写、沙箱跟随)。
// 由推荐弹窗的「执行方式」选择决定(仅 dag 有意义)。
const [dagExecMode, setDagExecMode] = useState<"fast" | "sandbox">("fast");
const [step2SidebarExpanded, setStep2SidebarExpanded] = useState(true);
const [step2Runs, setStep2Runs] = useState<DraftStep2RunSnapshot[]>([]);
const [activeStep2RunId, setActiveStep2RunId] = useState<string | null>(null);
@@ -121,6 +129,9 @@ export default function RoundtablePlanningPage() {
const [step3SavedTick, setStep3SavedTick] = useState<number>(0);
const step2RunsRef = useRef<DraftStep2RunSnapshot[]>([]);
const activeStep2RunIdRef = useRef<string | null>(null);
// 并行执行时收起左侧栏 —— 全局工作区侧栏(最左)走 useSidebarSafe(与「打开沙箱」同一路径,
// 见 artifacts/context.tsx 的 sidebar.setOpen(false)),圆桌「参与角色」栏走 step2SidebarExpanded。
const sidebar = useSidebarSafe();
// 角色面板(LeftSidebar)。原页面把它当成两步共用的展示数据,这里继续放在
// 主页 —— Step 1 / Step 2 / Step 3 都会读 / 写它,任何 hook 单独持有都不合适。
@@ -194,6 +205,8 @@ export default function RoundtablePlanningPage() {
currentStep,
selectedModel,
orchestrationMode,
orchestrationPlan,
dagExecMode,
buildInitialIntent,
triggerToast,
setRoles,
@@ -243,10 +256,14 @@ export default function RoundtablePlanningPage() {
seatStubMessages: step2.seatStubMessages,
orchestrationMode,
chain: chainMeta,
orchestrationPlan,
dagExecMode,
}),
[
chainMeta,
orchestrationMode,
orchestrationPlan,
dagExecMode,
step2.budgetLimit,
step2.consensusPercentage,
step2.coordinatorName,
@@ -279,6 +296,8 @@ export default function RoundtablePlanningPage() {
seatStubMessages: snapshot.seatStubMessages ?? {},
orchestrationMode: snapshot.orchestrationMode,
chain: snapshot.chain ?? null,
orchestrationPlan: snapshot.orchestrationPlan ?? null,
dagExecMode: snapshot.dagExecMode,
step3: step3Report,
}),
[step3Report],
@@ -362,6 +381,8 @@ export default function RoundtablePlanningPage() {
(run: DraftStep2RunSnapshot) => {
setOrchestrationMode(run.orchestrationMode ?? "recommend");
setChainMeta(run.chain ?? null);
setOrchestrationPlan(run.orchestrationPlan ?? null);
setDagExecMode(run.dagExecMode ?? "fast");
setStep3Report(run.step3 ?? null);
step2.hydrateFromDraft(run as unknown as Step2Snapshot);
},
@@ -421,6 +442,8 @@ export default function RoundtablePlanningPage() {
}
setOrchestrationMode(snapshot.orchestrationMode ?? "recommend");
setChainMeta(snapshot.chain ?? null);
setOrchestrationPlan(snapshot.orchestrationPlan ?? null);
setDagExecMode(snapshot.dagExecMode ?? "fast");
step2.hydrateFromDraft(snapshot as unknown as Step2Snapshot);
},
cancelAllStreams: () => {
@@ -504,6 +527,19 @@ export default function RoundtablePlanningPage() {
drafts.loadedFromDraftRef,
]);
// 并行执行 → 收起左侧栏腾出横向空间放两列(和「打开沙箱」一样的收起体验):
// - 全局工作区侧栏(最左):sidebar.setOpen(false)(与 artifacts 打开沙箱同一路径);
// - 圆桌「参与角色」栏:setStep2SidebarExpanded(false)。
// **不自动复原**:并行结束后再进入单智能体回答时保持收起(用户需要时手动展开),
// 与沙箱收起后不自动回弹一致。
useEffect(() => {
if (step2.isParallelRunning) {
sidebar?.setOpen(false);
setStep2SidebarExpanded(false);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [step2.isParallelRunning]);
// ─── 步骤间转场 handler ───────────────────────────────────
const handleConfirmAgents = useCallback(
(result: SeatSelectionResult) => {
@@ -537,7 +573,10 @@ export default function RoundtablePlanningPage() {
budgetLimit: step2.budgetLimit,
seatStubMessages: {},
orchestrationMode: result.mode,
chain: result.mode === "chain" ? result.chain ?? null : null,
// chain / dag 都来自业务链条,保留来源链名;recommend 无。
chain: result.mode === "recommend" ? null : result.chain ?? null,
orchestrationPlan: result.mode === "dag" ? result.plan ?? null : null,
dagExecMode: result.mode === "dag" ? result.dagExecMode ?? "fast" : undefined,
step3: null,
};
setStep2Runs([...syncedRuns, newRun]);
@@ -546,15 +585,20 @@ export default function RoundtablePlanningPage() {
step2.resetStep2State();
step2.setSelectedAgents(normalized);
step2.resetInitGate();
// result.mode 决定 Step 2 编排:recommend = 总控自由派活;chain = 按链条顺序派活。
// result.mode 决定 Step 2 编排:recommend = 总控自由派活;chain = 按链条顺序派活;
// dag = 分层并行(来源链条带 stages,携带 result.plan)。
setOrchestrationMode(result.mode);
setChainMeta(result.mode === "chain" ? result.chain ?? null : null);
setChainMeta(result.mode === "recommend" ? null : result.chain ?? null);
setOrchestrationPlan(result.mode === "dag" ? result.plan ?? null : null);
setDagExecMode(result.mode === "dag" ? result.dagExecMode ?? "fast" : "fast");
setIsRecommendDialogOpen(false);
setCurrentStep(2);
triggerToast(
result.mode === "chain"
? `成功确认!将按业务链条「${result.chain?.title ?? ""}」顺序研讨`
: "成功确认!已切换至第二阶段圆桌研讨系统",
result.mode === "dag"
? `成功确认!将按业务链条「${result.chain?.title ?? ""}」分层并行研讨`
: result.mode === "chain"
? `成功确认!将按业务链条「${result.chain?.title ?? ""}」顺序研讨`
: "成功确认!已切换至第二阶段圆桌研讨系统",
);
},
[buildCurrentStep2Snapshot, mergeActiveRun, step2, step3Report, triggerToast],
@@ -570,6 +614,8 @@ export default function RoundtablePlanningPage() {
setActiveStep2RunId(null);
setOrchestrationMode("recommend");
setChainMeta(null);
setOrchestrationPlan(null);
setDagExecMode("fast");
setStep3Report(null);
step1.stopIntentStream();
drafts.loadedFromDraftRef.current = false;
@@ -609,7 +655,9 @@ export default function RoundtablePlanningPage() {
intent: buildInitialIntent(),
agents,
model: selectedModel || undefined, // 模型沿用第二步选择
orchestrationMode,
// 后台作业引擎暂不支持 dag(分层 DAG 只在前端 runDagOrchestration 跑);
// 挂起到后台时降级为 recommend(总控自由派活)。
orchestrationMode: orchestrationMode === "dag" ? "recommend" : orchestrationMode,
chain: chainMeta,
// 不传 threadIds:后台作业由真网关自建全新线程,绝不复用前端本地研讨的线程
// (那些线程可能有活跃 run,复用会撞 409)。
@@ -878,6 +926,13 @@ export default function RoundtablePlanningPage() {
agentConfigs={step2.agentConfigs}
selectedAgentId={step2.selectedAgentId}
roles={roles}
parallelBatch={step2.parallelBatch}
selectedParallelSeats={step2.selectedParallelSeats}
isParallelRunning={step2.isParallelRunning}
onToggleParallelSeat={step2.toggleParallelSeat}
orchestrationMode={orchestrationMode}
orchestrationPlan={orchestrationPlan}
dagNodeStates={step2.dagNodeStates}
agentNameToRole={step2.agentNameToRole}
selectedModel={selectedModel}
availableModels={availableModels}