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:
1 parent
5164fd362c
commit
7b8c11852e
26 files changed
+3719
-216
No files matched your search
@@ -25,6 +25,12 @@ import {
|
||||
type StreamPhase,
|
||||
type ThreadIdMap,
|
||||
} from "@/roundtable-planning/api/multi-agent";
|
||||
import {
|
||||
buildDagStageLeaderTask,
|
||||
pickDagSeatTask,
|
||||
type OrchestrationPlan,
|
||||
} from "@/roundtable-planning/lib/dag-types";
|
||||
import type { ChainNodeState } from "@/roundtable-planning/lib/job-types";
|
||||
import {
|
||||
DEFAULT_SELECTED_AGENTS,
|
||||
MAX_CYCLES,
|
||||
@@ -56,6 +62,20 @@ export type Step2Dialogue = {
|
||||
}>;
|
||||
};
|
||||
|
||||
/**
|
||||
* 并行批次里的一个席位视图(§5 并行显示)。`runDagOrchestration` 在真并行 stage
|
||||
* 期间发布整批;头像条 / 两列主区据此渲染,`bubbleId` 指向 `step2RoundtableDialogues`
|
||||
* 里该席位的流式气泡。
|
||||
*/
|
||||
export interface ParallelSeatView {
|
||||
agentId: string;
|
||||
displayName: string;
|
||||
avatarType: string;
|
||||
status: "running" | "done" | "error";
|
||||
/** 该席位流式气泡在 step2RoundtableDialogues 里的 id。 */
|
||||
bubbleId: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stub AI message —— 用于把 special seat SSE 拿到的工具调用注入到 ThreadContext
|
||||
* 的 `thread.messages` 里,让 `useArtifactContent` 在沙箱里通过虚拟 URL
|
||||
@@ -110,9 +130,11 @@ export type Step2Snapshot = {
|
||||
* 注:该字段是主页面 state,由页面在 getStep2Snapshot/hydrateStep2 里读写,
|
||||
* step2 hook 的 hydrateFromDraft 不直接消费它。
|
||||
*/
|
||||
orchestrationMode?: "recommend" | "chain";
|
||||
orchestrationMode?: "recommend" | "chain" | "dag";
|
||||
/** chain 模式来源链条(仅展示用,如「按业务链条 X 研讨」)。 */
|
||||
chain?: { id: string; title: string } | null;
|
||||
/** dag 模式的分层编排计划(见 `lib/dag-types.ts`)。同样是主页面 state,hook 经 option 读取。 */
|
||||
orchestrationPlan?: OrchestrationPlan | null;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -191,11 +213,25 @@ export interface UseStep2OrchestrationOptions {
|
||||
/**
|
||||
* 编排模式:
|
||||
* - `recommend`(默认)—— 总控自由派活循环(`runOrchestration`);
|
||||
* - `chain` —— 总控**按业务链条顺序**逐位派活(`runChainOrchestration`)。
|
||||
* - `chain` —— 总控**按业务链条顺序**逐位派活(`runChainOrchestration`);
|
||||
* - `dag` —— **分层 DAG**:前端直派,stage 内并行、stage 间串行(`runDagOrchestration`,
|
||||
* 需配合 `orchestrationPlan`)。
|
||||
* 由推荐弹窗确认时的 `SeatSelectionResult.mode` 决定;chain 模式下席位顺序 =
|
||||
* `selectedAgents` 的顺序。
|
||||
*/
|
||||
orchestrationMode: "recommend" | "chain";
|
||||
orchestrationMode: "recommend" | "chain" | "dag";
|
||||
/**
|
||||
* dag 模式的分层编排计划。`orchestrationMode === "dag"` 且本计划非空时,
|
||||
* `runActiveOrchestration` 走 `runDagOrchestration`;否则回退到 recommend / chain。
|
||||
*/
|
||||
orchestrationPlan?: OrchestrationPlan | null;
|
||||
/**
|
||||
* dag 执行子模式(仅 `orchestrationMode === "dag"` 生效):
|
||||
* - `fast`(默认):同 stage 席位并行、主区**双列**、**禁写文件**(seat_parallel);
|
||||
* - `sandbox`:同 stage 席位仍并行,但主区**单列**、**允许写文件**(seat),沙箱跟随当前
|
||||
* 显示的席位(切头像 → 沙箱内容随之切换/关闭)。
|
||||
*/
|
||||
dagExecMode?: "fast" | "sandbox";
|
||||
/** 进入 Step 2 时拼装第一轮 leader prompt 的函数(读 Step 1 状态)。 */
|
||||
buildInitialIntent: () => string;
|
||||
/** 主页面统一的 toast。 */
|
||||
@@ -228,6 +264,17 @@ export interface UseStep2OrchestrationReturn {
|
||||
budgetLimit: number;
|
||||
agentConfigs: Record<number, AgentConfig>;
|
||||
selectedAgentId: number | null;
|
||||
// ─── 并行显示(§5)────────────────────────────────────────────────────
|
||||
/** 当前并行批次(非空 = 正在并行 stage)。 */
|
||||
parallelBatch: ParallelSeatView[];
|
||||
/** 主区当前并排显示的席位 agentId(最多 2)。 */
|
||||
selectedParallelSeats: string[];
|
||||
/** 是否正在并行执行(左侧栏折叠 / 头像条 / 两列显示的总开关)。 */
|
||||
isParallelRunning: boolean;
|
||||
/** 点头像切换主区显示的席位(LRU,最多 2)。 */
|
||||
toggleParallelSeat: (agentId: string) => void;
|
||||
/** Phase 7 DAG 流程图执行态:agentId(小写) → pending/active/done。非 dag 模式为空。 */
|
||||
dagNodeStates: Record<string, ChainNodeState>;
|
||||
// ─── Derived ────────────────────────────────────────────────────────
|
||||
roleTemplates: ReadonlyArray<Omit<RoleEntry, "status">>;
|
||||
agentNameToRole: Record<
|
||||
@@ -297,6 +344,8 @@ export function useStep2Orchestration(
|
||||
currentStep,
|
||||
selectedModel,
|
||||
orchestrationMode,
|
||||
orchestrationPlan,
|
||||
dagExecMode = "fast",
|
||||
buildInitialIntent,
|
||||
triggerToast,
|
||||
setRoles,
|
||||
@@ -364,6 +413,30 @@ export function useStep2Orchestration(
|
||||
DEFAULT_AGENT_CONFIGS,
|
||||
);
|
||||
const [selectedAgentId, setSelectedAgentId] = useState<number | null>(null);
|
||||
// 并行批次(§5):runDagOrchestration 在真并行 stage 期间发布;空 = 非并行。
|
||||
const [parallelBatch, setParallelBatch] = useState<ParallelSeatView[]>([]);
|
||||
// Phase 7 DAG 流程图执行态(§7):agentId(小写) → pending/active/done。
|
||||
// runDagOrchestration 跨 stage 维护;DagFlowChart 据此实时点亮节点。非 dag 模式 = 空。
|
||||
const [dagNodeStates, setDagNodeStates] = useState<Record<string, ChainNodeState>>({});
|
||||
// 主区当前并排显示的席位(最多 2,固定 2 列;窄屏只渲染第 1 个)。
|
||||
const [selectedParallelSeats, setSelectedParallelSeats] = useState<string[]>([]);
|
||||
// §6 流式高性能:所有并行席位的增量文本**全量累积进 ref**(O(1),不触发渲染);
|
||||
// 只有被选中的席位才在节流 flush 时把全文挂到 React state 渲染 Markdown。
|
||||
// key = bubbleId。
|
||||
const parallelStreamRef = useRef<Map<number, { text: string; charCount: number }>>(
|
||||
new Map(),
|
||||
);
|
||||
const parallelFlushTimerRef = useRef<number | null>(null);
|
||||
// flush 时要读「当前选中席位」与「批次 bubbleId↔agentId 映射」—— 打到 ref 避免
|
||||
// 把 flush 函数绑进会频繁变化的 state 依赖。
|
||||
const selectedParallelSeatsRef = useRef<string[]>([]);
|
||||
const parallelBatchRef = useRef<ParallelSeatView[]>([]);
|
||||
useEffect(() => {
|
||||
selectedParallelSeatsRef.current = selectedParallelSeats;
|
||||
}, [selectedParallelSeats]);
|
||||
useEffect(() => {
|
||||
parallelBatchRef.current = parallelBatch;
|
||||
}, [parallelBatch]);
|
||||
|
||||
// ─── Derived ──────────────────────────────────────────────────────
|
||||
const roleTemplates = useMemo(
|
||||
@@ -403,10 +476,29 @@ export function useStep2Orchestration(
|
||||
const isOrchestratingRef = useRef<boolean>(isOrchestrating);
|
||||
// chain 编排:模式 + 当前选中席位(=链条顺序)。同样打到 ref,让编排函数 deps 收窄。
|
||||
const orchestrationModeRef = useRef(orchestrationMode);
|
||||
const orchestrationPlanRef = useRef<OrchestrationPlan | null>(orchestrationPlan ?? null);
|
||||
// dag 执行子模式(fast/sandbox) + 沙箱模式下「当前允许显示沙箱的席位 thread」。
|
||||
// sandbox 模式单列:只有**当前显示**的席位才可自动打开沙箱;后台并行席位写文件不抢占
|
||||
// (见 openSeatVirtualArtifact 的 auto 守卫)。null = 非 sandbox 模式 / 无限制。
|
||||
const dagExecModeRef = useRef<"fast" | "sandbox">(dagExecMode);
|
||||
const sandboxFollowThreadIdRef = useRef<string | null>(null);
|
||||
// 「上次已 reconcile 的显示席位」键(`${mode}:${seat}`)。沙箱跟随 effect 只在**显示席位真正
|
||||
// 变化**时开/关沙箱,避免每次 render(deps 身份变化)都强制重开,把用户手动关闭的沙箱又弹回来。
|
||||
const lastReconciledSeatRef = useRef<string>("");
|
||||
useEffect(() => {
|
||||
dagExecModeRef.current = dagExecMode;
|
||||
}, [dagExecMode]);
|
||||
// dag 计划「已跑过一遍」闸门:DAG 编排只在初次执行一次计划;之后的用户干预 / 恢复 /
|
||||
// 澄清回复都改走 **leader 自由派活循环**(runOrchestration),由总控接着派活,而**不是**
|
||||
// 重新把整张 DAG 从头跑一遍(致命 bug 修复)。新任务 / 重新进入时由 resetInitGate 复位。
|
||||
const dagPlanExecutedRef = useRef<boolean>(false);
|
||||
const selectedAgentsRef = useRef<SelectedAgent[]>(selectedAgents);
|
||||
useEffect(() => {
|
||||
orchestrationModeRef.current = orchestrationMode;
|
||||
}, [orchestrationMode]);
|
||||
useEffect(() => {
|
||||
orchestrationPlanRef.current = orchestrationPlan ?? null;
|
||||
}, [orchestrationPlan]);
|
||||
useEffect(() => {
|
||||
selectedAgentsRef.current = selectedAgents;
|
||||
}, [selectedAgents]);
|
||||
@@ -504,6 +596,24 @@ export function useStep2Orchestration(
|
||||
if (hasAutoOpenedRef.current.has(virtualUrl)) return;
|
||||
const flags = autoOpenFlagsRef.current;
|
||||
if (!flags.autoOpen || !flags.autoSelect) return;
|
||||
// 快速模式(双列)DAG 并行批次:**完全不**自动开沙箱 —— 双列只看正文,多席位并发写
|
||||
// 文件(现已放开 write_file)会让单沙箱预览反复串台。文件仍写盘,Step3 / 文件卡可查看。
|
||||
if (
|
||||
orchestrationModeRef.current === "dag" &&
|
||||
dagExecModeRef.current === "fast" &&
|
||||
parallelBatchRef.current.length > 0
|
||||
) {
|
||||
return;
|
||||
}
|
||||
// sandbox 单列模式:并行的**后台**席位写文件时不要抢占沙箱 —— 只有当前显示的
|
||||
// 席位(sandboxFollowThreadIdRef)才允许自动打开,否则沙箱内容会和主区列表错位。
|
||||
if (
|
||||
dagExecModeRef.current === "sandbox" &&
|
||||
sandboxFollowThreadIdRef.current &&
|
||||
sandboxFollowThreadIdRef.current !== seatThreadId
|
||||
) {
|
||||
return;
|
||||
}
|
||||
hasAutoOpenedRef.current.add(virtualUrl);
|
||||
}
|
||||
setActiveArtifactThreadId(seatThreadId);
|
||||
@@ -530,6 +640,32 @@ export function useStep2Orchestration(
|
||||
[],
|
||||
);
|
||||
|
||||
/**
|
||||
* sandbox 模式「沙箱跟随」用:打开某席位 thread **最新**写入文件的虚拟预览(强制 auto=false)。
|
||||
* 从该 thread 的 stub messages 里倒序找第一个 write_file / str_replace 的 path。
|
||||
* 无产物返回 false(调用方据此关闭沙箱)。
|
||||
*/
|
||||
const openSeatLatestArtifact = useCallback(
|
||||
(seatThreadId: string): boolean => {
|
||||
const stub = seatStubMessagesRef.current[seatThreadId]?.[0];
|
||||
if (!stub) return false;
|
||||
for (let i = stub.tool_calls.length - 1; i >= 0; i -= 1) {
|
||||
const tc = stub.tool_calls[i];
|
||||
if (tc.name !== "write_file" && tc.name !== "str_replace") continue;
|
||||
const path =
|
||||
typeof (tc.args as { path?: unknown })?.path === "string"
|
||||
? ((tc.args as { path?: string }).path as string)
|
||||
: "";
|
||||
if (!path) continue;
|
||||
const virtualUrl = buildWriteFileVirtualUrl(path, stub.id, tc.id);
|
||||
openSeatVirtualArtifact(seatThreadId, virtualUrl, false);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
[buildWriteFileVirtualUrl, openSeatVirtualArtifact],
|
||||
);
|
||||
|
||||
/**
|
||||
* 反查某个产出文件是由哪个席位 thread 写入的。
|
||||
*
|
||||
@@ -888,6 +1024,120 @@ export function useStep2Orchestration(
|
||||
);
|
||||
}, []);
|
||||
|
||||
/** 整段替换某气泡正文(§6 flush:把 ref 里累积的全文一次性挂上去)。 */
|
||||
const setDialogueContent = useCallback((id: number, fullText: string) => {
|
||||
setStep2RoundtableDialogues((prev) =>
|
||||
prev.map((d) => (d.id === id ? { ...d, content: fullText } : d)),
|
||||
);
|
||||
}, []);
|
||||
|
||||
// ─── §6 并行流式:全接收 / 惰性渲染 / 节流 ───────────────────────────────
|
||||
/**
|
||||
* 节流 flush(~80ms 一拍,约 12fps):**仅被选中**的席位把 ref 累积的全文挂到
|
||||
* React state 渲染 Markdown(≤2 个)。未选中席位只在 ref 里累积、不挂 DOM —— 6+
|
||||
* 并行也不卡。切到它时下拍即显全文(再叠加选中变化 effect 的即时挂载)。
|
||||
*/
|
||||
const flushParallelStreams = useCallback(() => {
|
||||
parallelFlushTimerRef.current = null;
|
||||
const store = parallelStreamRef.current;
|
||||
if (store.size === 0) return;
|
||||
const selected = new Set(selectedParallelSeatsRef.current);
|
||||
for (const seat of parallelBatchRef.current) {
|
||||
if (selected.has(seat.agentId)) {
|
||||
const entry = store.get(seat.bubbleId);
|
||||
if (entry) setDialogueContent(seat.bubbleId, entry.text);
|
||||
}
|
||||
}
|
||||
}, [setDialogueContent]);
|
||||
|
||||
const scheduleParallelFlush = useCallback(() => {
|
||||
if (parallelFlushTimerRef.current !== null) return;
|
||||
parallelFlushTimerRef.current = window.setTimeout(flushParallelStreams, 80);
|
||||
}, [flushParallelStreams]);
|
||||
|
||||
/** 并行席位的 onTextDelta:全量累积进 ref(O(1)),再调度一次节流 flush。 */
|
||||
const ingestParallelDelta = useCallback(
|
||||
(bubbleId: number, text: string) => {
|
||||
if (!text) return;
|
||||
const store = parallelStreamRef.current;
|
||||
const cur = store.get(bubbleId) ?? { text: "", charCount: 0 };
|
||||
cur.text += text;
|
||||
cur.charCount = cur.text.length;
|
||||
store.set(bubbleId, cur);
|
||||
scheduleParallelFlush();
|
||||
},
|
||||
[scheduleParallelFlush],
|
||||
);
|
||||
|
||||
/** 清空并行流式 store + 取消挂起的 flush(stage 结束 / 抢占 / 异常兜底)。 */
|
||||
const resetParallelStreams = useCallback(() => {
|
||||
parallelStreamRef.current = new Map();
|
||||
if (parallelFlushTimerRef.current !== null) {
|
||||
window.clearTimeout(parallelFlushTimerRef.current);
|
||||
parallelFlushTimerRef.current = null;
|
||||
}
|
||||
}, []);
|
||||
|
||||
// 卸载兜底:清掉可能挂起的 flush 定时器。
|
||||
useEffect(() => resetParallelStreams, [resetParallelStreams]);
|
||||
|
||||
// 选中变化 → 立刻把 ref 里已累积的全文挂给**新选中**的席位(切头像即显全部输出,
|
||||
// 证明流没丢、只是之前没渲染,§6.5)。
|
||||
useEffect(() => {
|
||||
const store = parallelStreamRef.current;
|
||||
if (store.size === 0) return;
|
||||
const selected = new Set(selectedParallelSeats);
|
||||
for (const seat of parallelBatchRef.current) {
|
||||
if (selected.has(seat.agentId)) {
|
||||
const entry = store.get(seat.bubbleId);
|
||||
if (entry) setDialogueContent(seat.bubbleId, entry.text);
|
||||
}
|
||||
}
|
||||
}, [selectedParallelSeats, setDialogueContent]);
|
||||
|
||||
// sandbox 单列模式「沙箱跟随」(防 bug 重点,用户特别强调):切换当前显示的席位时,
|
||||
// 沙箱内容必须等于该席位的内容 —— 有产物则打开它的沙箱,无产物则关闭沙箱面板。
|
||||
// 并把「当前允许显示沙箱的席位 thread」记到 sandboxFollowThreadIdRef,供 openSeatVirtualArtifact
|
||||
// 的 auto 守卫拦掉后台并行席位的抢占(见该函数)。非 sandbox 模式 / 无选中时清空,不干预沙箱。
|
||||
useEffect(() => {
|
||||
const seat = dagExecMode === "sandbox" ? selectedParallelSeats[0] ?? "" : "";
|
||||
// 只在「显示席位真正变化」时 reconcile。否则:本 effect 的 deps(openSeatLatestArtifact /
|
||||
// setArtifactsOpen 等)身份每次 render 都可能变 → effect 反复跑 → 把用户刚手动关闭的沙箱
|
||||
// 又强制重开,表现为「关闭按钮关不掉」。用 key 守卫后,用户关闭(席位没变)时直接早退。
|
||||
const key = `${dagExecMode}:${seat}`;
|
||||
if (lastReconciledSeatRef.current === key) return;
|
||||
lastReconciledSeatRef.current = key;
|
||||
|
||||
if (dagExecMode !== "sandbox" || !seat) {
|
||||
sandboxFollowThreadIdRef.current = null;
|
||||
return;
|
||||
}
|
||||
const ids = threadIdsRef.current;
|
||||
if (!ids) {
|
||||
sandboxFollowThreadIdRef.current = null;
|
||||
return;
|
||||
}
|
||||
const tid = resolveSeatThreadId(ids, seat);
|
||||
sandboxFollowThreadIdRef.current = tid ?? null;
|
||||
if (!tid) return;
|
||||
const opened = openSeatLatestArtifact(tid);
|
||||
if (!opened) {
|
||||
// 当前显示席位**暂时**还没有沙箱产物(常见:并行批次第一个席位刚选中、还没写文件)→
|
||||
// 关闭沙箱面板,但**只用 deselect**(它走 raw setOpen(false),**不**关掉 autoOpen);
|
||||
// 千万别再调 setArtifactsOpen(false) —— 那个 wrapped setter 会把 autoOpen 置 false
|
||||
// (context.tsx:73),导致该席位**随后 live 写文件时 openSeatVirtualArtifact 的
|
||||
// `!autoOpen` 守卫拦掉自动打开**(正是「第一个席位不自动开沙箱、要手动开」的 bug)。
|
||||
setActiveArtifactThreadId(null);
|
||||
deselectArtifact();
|
||||
}
|
||||
}, [
|
||||
selectedParallelSeats,
|
||||
dagExecMode,
|
||||
resolveSeatThreadId,
|
||||
openSeatLatestArtifact,
|
||||
deselectArtifact,
|
||||
]);
|
||||
|
||||
const finalizeDialogue = useCallback(
|
||||
(id: number, finalContent: string, confidence?: string) => {
|
||||
setStep2RoundtableDialogues((prev) =>
|
||||
@@ -975,6 +1225,43 @@ export function useStep2Orchestration(
|
||||
);
|
||||
}, [setRoles]);
|
||||
|
||||
/**
|
||||
* DAG 并行批次:把**一整批**席位同时标为「研讨中」(与 markSpeakerStreaming
|
||||
* 的"排他单发"不同 —— 并行就是要多个 sub 同时高亮)。其余历史残留的"研讨中"清成"在线"。
|
||||
* activeSpeakerSet 天然是 Set,这里放整批 speakerId。
|
||||
*/
|
||||
const markParallelSpeakers = useCallback(
|
||||
(speakerIds: number[]) => {
|
||||
const wanted = new Set(speakerIds);
|
||||
setActiveSpeakerSet(new Set(speakerIds));
|
||||
setRoles((prev) =>
|
||||
prev.map((item) => {
|
||||
if (wanted.has(item.id)) return { ...item, status: "研讨中" };
|
||||
if (item.status === "研讨中") return { ...item, status: "在线" };
|
||||
return item;
|
||||
}),
|
||||
);
|
||||
},
|
||||
[setRoles],
|
||||
);
|
||||
|
||||
/**
|
||||
* 点头像切换主区显示的席位(§5.3):已选中→取消;未选中→加入,超过 2 个按 LRU
|
||||
* 踢掉最早选中的。被换下的席位停止渲染但流仍在内存累积(气泡始终在列表里)。
|
||||
*/
|
||||
const toggleParallelSeat = useCallback((agentId: string) => {
|
||||
setSelectedParallelSeats((prev) => {
|
||||
// sandbox 单列:点头像 = 切换到该席位(始终保留 1 个,点已选中的不取消到空)。
|
||||
if (dagExecModeRef.current === "sandbox") {
|
||||
return prev.length === 1 && prev[0] === agentId ? prev : [agentId];
|
||||
}
|
||||
// fast 双列:点已选中 → 取消;未选中 → 加入,超过 2 个按 LRU 踢最早的。
|
||||
if (prev.includes(agentId)) return prev.filter((id) => id !== agentId);
|
||||
const next = [...prev, agentId];
|
||||
return next.length > 2 ? next.slice(next.length - 2) : next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
// ─── Abort ────────────────────────────────────────────────────────
|
||||
const abortAllInFlight = useCallback(() => {
|
||||
activeAbortersRef.current.forEach((ctrl) => {
|
||||
@@ -1483,13 +1770,363 @@ export function useStep2Orchestration(
|
||||
],
|
||||
);
|
||||
|
||||
// ─── DAG orchestration loop ───────────────────────────────────────
|
||||
// dag 模式(§3 + §3.2 方案 A,2026-06-07 改成「总控驱动」):分层执行 —— stage 内**并行**
|
||||
// (Promise.all)、stage 间**串行**(Promise.all 即 barrier)。每个 stage 的流程与串行同构:
|
||||
// 1) **总控派活轮**:由【总控】对本 stage 计划钉死的席位**真正派活**(buildDagStageLeaderTask
|
||||
// 约束它只派给这些席位、且每个都派到;不自由乱派、不收口)。总控本轮也"承上"——后端
|
||||
// _build_seat_status_block 走轻量 last-ai-message 把此前各席位真实交付(摘要)注入其输入
|
||||
// (§传摘要按需传全文);
|
||||
// 2) **批内并行**:本 stage 席位并行跑总控派给各自的 task(pickDagSeatTask 命中其 agent_name,
|
||||
// 漏派则回退总控正文/模板,不借用别席位 task);完成后交付经后端 detached 广播回总控;
|
||||
// 3) barrier 后进入下一 stage,总控再派下一批(它已能看到上一批交付摘要)。
|
||||
// 所有 stage 跑完后,把锁交回 runOrchestration 由总控综合 / 收口(此时 synthesisMode 才按需
|
||||
// 注入各席位**完整交付正文**——全文只在收口这一轮付出)。
|
||||
//
|
||||
// 与「前端直派(方案 B)」的区别:每 stage 都经总控决策派活(像串行/链条那样),计划只钉死
|
||||
// 「派给谁」、总控负责「派什么活 + 承上启下」。与 chain 模式同构,区别是一次钉死一批、批内并行。
|
||||
//
|
||||
// 与 runOrchestration / runChainOrchestration 的「不要 Promise.all」不变量不同 ——
|
||||
// DAG 并行就是要 Promise.all;N 路 token 级 setState 的卡顿由 Phase 6(全接收 /
|
||||
// 惰性渲染 / 节流)解决,且单 stage 并行度有 warning 上限(PARALLEL_DEGREE_WARN_THRESHOLD)。
|
||||
const runDagOrchestration = useCallback(
|
||||
async (seedMessage: string, ids: ThreadIdMap, coord: string) => {
|
||||
const plan = orchestrationPlanRef.current;
|
||||
if (!plan || plan.stages.length === 0) {
|
||||
triggerToast("⚠️ 没有可执行的 DAG 编排计划");
|
||||
return;
|
||||
}
|
||||
if (isOrchestratingRef.current) return;
|
||||
// 同步抢占编排锁(原因同 runOrchestration):堵住人工干预 / 恢复 toggle 在同一
|
||||
// tick 内的二次触发,避免并发双发。
|
||||
isOrchestratingRef.current = true;
|
||||
setIsOrchestrating(true);
|
||||
orchestrationCancelRef.current = false;
|
||||
const myEpoch = (orchestrationEpochRef.current += 1);
|
||||
const isStale = () =>
|
||||
orchestrationCancelRef.current || orchestrationEpochRef.current !== myEpoch;
|
||||
// 标记 DAG 计划已开始执行:此后任何 runActiveOrchestration(干预 / 恢复 / 澄清)
|
||||
// 都改走 leader 循环,不再重跑整张 DAG。
|
||||
dagPlanExecutedRef.current = true;
|
||||
|
||||
const leaderThreadId = resolveSeatThreadId(ids, coord);
|
||||
let finishedAllStages = true;
|
||||
// 跨 stage 累积的**完整交付** {name, content}[] —— 注入下一 stage 席位的 run context
|
||||
// (peerDeliveries),供 read_peer_delivery 工具按需取全文(§12.9 传摘要按需传全文)。
|
||||
const priorDeliveries: Array<{ name: string; content: string }> = [];
|
||||
|
||||
// Phase 7:初始化 DAG 流程图节点状态 —— 计划内所有席位置 pending,执行过程中逐个点亮。
|
||||
const markDagNode = (agentId: string, state: ChainNodeState) =>
|
||||
setDagNodeStates((prev) => ({ ...prev, [agentId.toLowerCase()]: state }));
|
||||
setDagNodeStates(
|
||||
Object.fromEntries(
|
||||
plan.stages.flatMap((st) => st.agentIds.map((id) => [id.toLowerCase(), "pending" as ChainNodeState])),
|
||||
),
|
||||
);
|
||||
|
||||
try {
|
||||
for (let s = 0; s < plan.stages.length; s += 1) {
|
||||
if (isStale()) {
|
||||
finishedAllStages = false;
|
||||
break;
|
||||
}
|
||||
const stage = plan.stages[s];
|
||||
const isParallel = stage.agentIds.length > 1;
|
||||
// 本 stage 计划钉死的席位元数据(供派活轮 + 并行执行共用)。
|
||||
const stageSeats = stage.agentIds.map((agentId) => {
|
||||
const meta = agentNameToRoleRef.current[agentId.toLowerCase()];
|
||||
return { agentId, meta, name: meta?.displayName ?? agentId };
|
||||
});
|
||||
|
||||
// ── (a) 总控派活轮(§3.2 方案 A + 批内并行):由【总控】对本 stage 计划钉死的
|
||||
// 席位**真正派活**(约束只派给这些席位、且每个都派到),而不是前端直发。总控本轮
|
||||
// 也"承上":后端 _build_seat_status_block 已把此前各席位真实交付(摘要)注入其输入
|
||||
// (传摘要按需传全文)。它不自由乱派、不收口。与 chain 同构,区别是一次钉死一批、批内并行。
|
||||
highlightSpeaker(null);
|
||||
const leaderBubbleId = appendStreamingDialogue({
|
||||
sender: "总控协调",
|
||||
avatarType: "blue",
|
||||
initialContent: "",
|
||||
confidence: s === 0 ? "派活中" : "承上派活中",
|
||||
agentThreadId: leaderThreadId,
|
||||
});
|
||||
const leaderTask = buildDagStageLeaderTask({
|
||||
seedMessage,
|
||||
stageIndex: s,
|
||||
totalStages: plan.stages.length,
|
||||
seats: stageSeats.map((p) => ({ agentId: p.agentId, name: p.name })),
|
||||
isFirst: s === 0,
|
||||
});
|
||||
const leaderAborter = new AbortController();
|
||||
activeAbortersRef.current.add(leaderAborter);
|
||||
let leaderRes;
|
||||
try {
|
||||
leaderRes = await streamMultiAgent({
|
||||
agentType: "leader",
|
||||
dAgentThreadId: ids,
|
||||
agentName: coord,
|
||||
newMessage: leaderTask,
|
||||
// 派活轮:传 false,后端只注入各席位摘要;完整交付正文留给末尾收口的 synthesis 轮。
|
||||
synthesisMode: false,
|
||||
// 抑制预广播:别把总控的派活 prompt 播进席位 thread(否则弱模型从历史里捡到派活
|
||||
// 意图、跟着模仿派活 / 绕道 bash 调内部接口)。席位任务由 pickDagSeatTask 干净下发。
|
||||
suppressPreBroadcast: true,
|
||||
model: selectedModelRef.current || undefined,
|
||||
signal: leaderAborter.signal,
|
||||
onTextDelta: (text) => appendToDialogue(leaderBubbleId, text),
|
||||
onPhaseChange: (phase, toolName, args) => {
|
||||
const label = phaseLabel(phase, "leader", toolName);
|
||||
setDialogueConfidence(leaderBubbleId, label);
|
||||
appendStepIfNew(leaderBubbleId, label, `${phase}:${toolName ?? ""}`, args);
|
||||
handleArtifactToolPhase(phase, toolName, args, leaderThreadId);
|
||||
},
|
||||
onUpstreamFrame: (frame) => handleUpstreamFrame(frame, leaderThreadId),
|
||||
});
|
||||
} catch (err) {
|
||||
activeAbortersRef.current.delete(leaderAborter);
|
||||
if (leaderAborter.signal.aborted || (err as Error).name === "AbortError") {
|
||||
finalizeDialogue(leaderBubbleId, "(已停止)", "已停止");
|
||||
finishedAllStages = false;
|
||||
break;
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
activeAbortersRef.current.delete(leaderAborter);
|
||||
if (isStale()) {
|
||||
finalizeDialogue(leaderBubbleId, leaderRes.content || "(已停止)", "已停止");
|
||||
finishedAllStages = false;
|
||||
break;
|
||||
}
|
||||
// 派活轮也可能要求澄清 → 暂停 DAG(回复后走 leader 自由派活、不重跑 DAG)。
|
||||
if (leaderRes.clarification) {
|
||||
finalizeDialogue(leaderBubbleId, leaderRes.content, "等待用户澄清");
|
||||
setPendingClarification(leaderRes.clarification);
|
||||
setClarificationDraft("");
|
||||
triggerToast("❓ 总控需要补充信息,请回答下方问题后继续");
|
||||
finishedAllStages = false;
|
||||
break;
|
||||
}
|
||||
finalizeDialogue(leaderBubbleId, leaderRes.content, "派活说明");
|
||||
if (leaderRes.content) setLastLeaderContent(leaderRes.content);
|
||||
|
||||
// ── (b) 本 stage 席位【并行】执行总控下发的 task ──
|
||||
// 预备各席位气泡(在 Promise.all 之前同步建好,这样并行显示(§5)的头像条/两列
|
||||
// 能立刻拿到每个席位的 bubbleId 去渲染对应消息流)。
|
||||
const seatPrep = stageSeats.map(({ agentId, meta, name }) => {
|
||||
const avatarType = meta?.avatarType ?? "blue";
|
||||
const seatThreadId = resolveSeatThreadId(ids, agentId);
|
||||
const bubbleId = appendStreamingDialogue({
|
||||
sender: name,
|
||||
avatarType,
|
||||
initialContent: "",
|
||||
confidence: "调度中",
|
||||
agentThreadId: seatThreadId,
|
||||
});
|
||||
return { agentId, meta, seatName: name, avatarType, seatThreadId, bubbleId };
|
||||
});
|
||||
|
||||
// 整批高亮(并行)。单节点 stage 退化为高亮一个,行为与串行一致。
|
||||
markParallelSpeakers(
|
||||
seatPrep.map((p) => p.meta?.speakerId).filter((v): v is number => typeof v === "number"),
|
||||
);
|
||||
// Phase 7:本 stage 席位置 active(流程图点亮当前列)。
|
||||
for (const p of seatPrep) markDagNode(p.agentId, "active");
|
||||
|
||||
// 并行 stage(≥2 席位)才发布「并行批次」给前端头像条 + 主区显示。
|
||||
// fast(双列)默认选中最先两个;sandbox(单列)只选最先一个,点头像切换。
|
||||
if (isParallel) {
|
||||
setParallelBatch(
|
||||
seatPrep.map((p) => ({
|
||||
agentId: p.agentId,
|
||||
displayName: p.seatName,
|
||||
avatarType: p.avatarType,
|
||||
status: "running" as const,
|
||||
bubbleId: p.bubbleId,
|
||||
})),
|
||||
);
|
||||
const cols = dagExecModeRef.current === "sandbox" ? 1 : 2;
|
||||
setSelectedParallelSeats(seatPrep.slice(0, cols).map((p) => p.agentId));
|
||||
}
|
||||
const markBatchStatus = (agentId: string, status: ParallelSeatView["status"]) =>
|
||||
setParallelBatch((prev) =>
|
||||
prev.map((p) => (p.agentId === agentId ? { ...p, status } : p)),
|
||||
);
|
||||
|
||||
// ── 批内并行:对 stage 内每个席位发 special run,跑总控本轮派给它的 task ──
|
||||
// 每个席位独立 try/catch 兜底,保证**单席位失败不拖垮整 stage**(§9):
|
||||
// 任务函数永不 reject → Promise.all 不会因一个席位异常整体崩。
|
||||
const stageResults = await Promise.all(
|
||||
seatPrep.map(async ({ agentId, meta, seatName, seatThreadId, bubbleId }): Promise<{ name: string; content: string } | null> => {
|
||||
const perSeatModel = meta
|
||||
? agentConfigsRef.current[meta.speakerId]?.model
|
||||
: undefined;
|
||||
// 用总控本轮派给该席位的 task(命中其 agent_name);总控没用工具只写文字时,
|
||||
// pickDagSeatTask 给干净本职任务、**不**注入总控派活叙述(根治「席位模仿派活」)。
|
||||
// 带上 seedMessage:预广播已抑制,席位 thread 里没有用户原始消息,靠 task 补背景。
|
||||
const task = pickDagSeatTask(
|
||||
leaderRes.dispatched,
|
||||
agentId,
|
||||
seatName,
|
||||
seedMessage,
|
||||
priorDeliveries.length > 0,
|
||||
dagExecModeRef.current === "sandbox", // 仅沙箱模式要求写 .md 文件;快速模式产物走正文
|
||||
);
|
||||
|
||||
const subAborter = new AbortController();
|
||||
activeAbortersRef.current.add(subAborter);
|
||||
try {
|
||||
const specRes = await streamMultiAgent({
|
||||
agentType: "special",
|
||||
dAgentThreadId: ids,
|
||||
agentName: agentId,
|
||||
displayName: seatName,
|
||||
newMessage: task,
|
||||
// 写文件只在 **沙箱模式**(seat policy)开放;**快速模式一律禁写文件**(seat_parallel,
|
||||
// 产物走正文,§12.10 用户要求 fast 不生成文件)。与 stage 是否并行无关:fast 单节点
|
||||
// stage 也禁写(保持 fast=无文件的一致体验)。
|
||||
parallelNoFile: dagExecModeRef.current !== "sandbox",
|
||||
// 前序各阶段的完整交付 → 供本席位 read_peer_delivery 按需取全文(§12.9)。
|
||||
peerDeliveries: priorDeliveries,
|
||||
model: perSeatModel || selectedModelRef.current || undefined,
|
||||
signal: subAborter.signal,
|
||||
// §6:并行席位走 ref 全量累积 + 节流 flush(只渲染选中的);单节点
|
||||
// stage 实际串行,1 路流直接 setState 不卡,沿用 appendToDialogue。
|
||||
onTextDelta: (text) =>
|
||||
isParallel ? ingestParallelDelta(bubbleId, text) : appendToDialogue(bubbleId, text),
|
||||
onPhaseChange: (phase, toolName, args) => {
|
||||
const label = phaseLabel(phase, "special", toolName);
|
||||
setDialogueConfidence(bubbleId, label);
|
||||
appendStepIfNew(bubbleId, label, `${phase}:${toolName ?? ""}`, args);
|
||||
handleArtifactToolPhase(phase, toolName, args, seatThreadId);
|
||||
},
|
||||
onUpstreamFrame: (frame) => handleUpstreamFrame(frame, seatThreadId),
|
||||
});
|
||||
if (isStale()) {
|
||||
finalizeDialogue(bubbleId, specRes.content || "(已停止)", "已停止");
|
||||
markBatchStatus(agentId, "done");
|
||||
return null;
|
||||
}
|
||||
finalizeDialogue(bubbleId, specRes.content, "子智能体交付");
|
||||
markBatchStatus(agentId, "done");
|
||||
return specRes.content?.trim() ? { name: seatName, content: specRes.content } : null;
|
||||
} catch (err) {
|
||||
if (subAborter.signal.aborted || (err as Error).name === "AbortError") {
|
||||
finalizeDialogue(bubbleId, "(已停止)", "已停止");
|
||||
markBatchStatus(agentId, "done");
|
||||
} else {
|
||||
console.error(`[dag-special:${agentId}] error:`, err);
|
||||
finalizeDialogue(bubbleId, `(错误) ${(err as Error).message}`, "调用失败");
|
||||
markBatchStatus(agentId, "error");
|
||||
}
|
||||
return null;
|
||||
} finally {
|
||||
activeAbortersRef.current.delete(subAborter);
|
||||
if (meta) markSpeakerIdle(meta.speakerId);
|
||||
// Phase 7:席位到终态(成功/失败/抢占)→ 流程图节点打勾。ChainNodeState 无
|
||||
// error 态,失败也归 done(节点已结束);失败细节体现在气泡正文。
|
||||
markDagNode(agentId, "done");
|
||||
// 终态后从 ref store 删除,节流 flush 不再覆盖已 finalize 的正文。
|
||||
parallelStreamRef.current.delete(bubbleId);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
// 本 stage 结束(barrier 到达):收起并行批次,回到普通流式列表 + 清流式 store。
|
||||
if (isParallel) {
|
||||
setParallelBatch([]);
|
||||
setSelectedParallelSeats([]);
|
||||
resetParallelStreams();
|
||||
}
|
||||
|
||||
// Promise.all 即 barrier:本 stage 全部终态后才进入下一 stage(批间串行)。
|
||||
// 下一 stage 的总控派活轮会"承上"(后端注入本批真实交付摘要),无需前端再拼摘要。
|
||||
if (isStale()) {
|
||||
finishedAllStages = false;
|
||||
break;
|
||||
}
|
||||
// 累积本 stage 的**完整交付**,供后续 stage 席位 read_peer_delivery 按需取全文(§12.9)。
|
||||
for (const r of stageResults) {
|
||||
if (r && r.content?.trim()) priorDeliveries.push(r);
|
||||
}
|
||||
setConsensusPercentage(
|
||||
Math.min(95, Math.round(((s + 1) / plan.stages.length) * 90)),
|
||||
);
|
||||
}
|
||||
|
||||
// ── 计划阶段全部完成 → **交给总控(leader 自由派活循环)继续** ──
|
||||
// 关键修复:并行/各阶段输出完后,一定要回到总控,由它综合并**按需继续派活 / 收口**,
|
||||
// 而不是停在一次性 synthesis。这里把 DAG 的编排锁释放,委托给 runOrchestration
|
||||
// (它有自己的重入守卫 + epoch + 收敛逻辑)。后续用户干预 / 恢复同样走 leader
|
||||
// (见 runActiveOrchestration 的 dagPlanExecutedRef 闸门),不再重跑整张 DAG。
|
||||
if (!isStale() && finishedAllStages && plan.finalSynthesis) {
|
||||
highlightSpeaker(null);
|
||||
isOrchestratingRef.current = false; // 释放锁,让 runOrchestration 即刻接管
|
||||
setIsOrchestrating(false);
|
||||
await runOrchestration(
|
||||
"各阶段席位已按依赖编排完成交付。请你作为总控,综合各席位的交付:若仍需补充则继续派活,否则直接输出最终方案并收口。",
|
||||
ids,
|
||||
coord,
|
||||
);
|
||||
return;
|
||||
} else if (!isStale() && finishedAllStages) {
|
||||
// 不收口(plan.finalSynthesis=false):全部 stage 跑完即视为完成,不再叫总控。
|
||||
setConsensusPercentage(100);
|
||||
setHasConsensus(true);
|
||||
triggerToast("✅ 依赖编排各阶段已全部完成");
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("dag orchestration error:", err);
|
||||
triggerToast(`❌ 依赖编排研讨异常: ${(err as Error).message}`);
|
||||
} finally {
|
||||
highlightSpeaker(null);
|
||||
clearAllStreamingSpeakers();
|
||||
// 兜底收起并行批次(正常路径已在 stage 结束时清空,异常 / 抢占时这里保证不残留)。
|
||||
setParallelBatch([]);
|
||||
setSelectedParallelSeats([]);
|
||||
resetParallelStreams();
|
||||
setIsOrchestrating(false);
|
||||
}
|
||||
},
|
||||
[
|
||||
appendStreamingDialogue,
|
||||
appendToDialogue,
|
||||
appendStepIfNew,
|
||||
setDialogueConfidence,
|
||||
phaseLabel,
|
||||
finalizeDialogue,
|
||||
highlightSpeaker,
|
||||
markParallelSpeakers,
|
||||
markSpeakerIdle,
|
||||
clearAllStreamingSpeakers,
|
||||
triggerToast,
|
||||
handleArtifactToolPhase,
|
||||
handleUpstreamFrame,
|
||||
resolveSeatThreadId,
|
||||
ingestParallelDelta,
|
||||
resetParallelStreams,
|
||||
runOrchestration,
|
||||
],
|
||||
);
|
||||
|
||||
// 按当前模式分发到对应编排函数。init / 恢复 / 干预 / 澄清回复统一走这里。
|
||||
const runActiveOrchestration = useCallback(
|
||||
(seedMessage: string, ids: ThreadIdMap, coord: string) =>
|
||||
orchestrationModeRef.current === "chain"
|
||||
? runChainOrchestration(seedMessage, ids, coord)
|
||||
: runOrchestration(seedMessage, ids, coord),
|
||||
[runOrchestration, runChainOrchestration],
|
||||
(seedMessage: string, ids: ThreadIdMap, coord: string) => {
|
||||
const mode = orchestrationModeRef.current;
|
||||
// dag:**只在计划尚未跑过时**执行整张 DAG;一旦跑过(用户干预 / 恢复 / 澄清回复),
|
||||
// 改走 leader 自由派活循环,由总控接着派活,而不是把 DAG 从头重跑一遍。
|
||||
if (
|
||||
mode === "dag" &&
|
||||
!dagPlanExecutedRef.current &&
|
||||
(orchestrationPlanRef.current?.stages.length ?? 0) > 0
|
||||
) {
|
||||
return runDagOrchestration(seedMessage, ids, coord);
|
||||
}
|
||||
if (mode === "chain") {
|
||||
return runChainOrchestration(seedMessage, ids, coord);
|
||||
}
|
||||
return runOrchestration(seedMessage, ids, coord);
|
||||
},
|
||||
[runOrchestration, runChainOrchestration, runDagOrchestration],
|
||||
);
|
||||
|
||||
// ─── Effects ─────────────────────────────────────────────────────
|
||||
@@ -1766,6 +2403,8 @@ export function useStep2Orchestration(
|
||||
|
||||
const resetInitGate = useCallback(() => {
|
||||
step2InitRef.current = false;
|
||||
// 新一轮研讨:允许 DAG 计划重新执行一遍。
|
||||
dagPlanExecutedRef.current = false;
|
||||
setInitNonce((n) => n + 1);
|
||||
}, []);
|
||||
|
||||
@@ -1821,6 +2460,10 @@ export function useStep2Orchestration(
|
||||
setLastLeaderContent("");
|
||||
setHasConsensus(false);
|
||||
setConsensusPercentage(0);
|
||||
setParallelBatch([]);
|
||||
setSelectedParallelSeats([]);
|
||||
setDagNodeStates({});
|
||||
resetParallelStreams();
|
||||
setActiveArtifactThreadId(null);
|
||||
artifactPathsRef.current = [];
|
||||
setArtifacts([]);
|
||||
@@ -1828,9 +2471,10 @@ export function useStep2Orchestration(
|
||||
setSeatStubMessages({});
|
||||
hasAutoOpenedRef.current = new Set();
|
||||
pendingInjectPromptRef.current = null;
|
||||
dagPlanExecutedRef.current = false;
|
||||
deselectArtifact();
|
||||
step2InitRef.current = false;
|
||||
}, [abortAllInFlight, deselectArtifact, setArtifacts]);
|
||||
}, [abortAllInFlight, deselectArtifact, setArtifacts, resetParallelStreams]);
|
||||
|
||||
return {
|
||||
selectedAgents,
|
||||
@@ -1850,6 +2494,11 @@ export function useStep2Orchestration(
|
||||
activeSpeakerSet,
|
||||
customAgentInput,
|
||||
isUpperPanelCollapsed,
|
||||
parallelBatch,
|
||||
selectedParallelSeats,
|
||||
isParallelRunning: parallelBatch.length > 0,
|
||||
toggleParallelSeat,
|
||||
dagNodeStates,
|
||||
budgetLimit,
|
||||
agentConfigs,
|
||||
selectedAgentId,
|
||||
|
||||
Reference in new issue
Block a user