fix: 节流会商流式写文件预览,避免 Maximum update depth

write_file 的 content 在每个 SSE chunk 中持续增长,原先会反复触发 React 状态更新并打断整页;现改为按身份入参去重、节流发布 stub,并收口第 3 步为 Markdown 报告工作台。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
董宏凯andCursor committed 2026-08-18 23:23:46 +08:00
1 parent dcfaa199bf
commit 30799f17be
14 files changed
+644 -703

No files matched your search

@@ -507,6 +507,14 @@ export function useStep2Orchestration(
Record<string, StubAiMessage[]>
>({});
const seatStubMessagesRef = useRef<Record<string, StubAiMessage[]>>({});
// write_file 的 tool args 会在一个 SSE response 里高频增长。ref 始终保留最新全文,
// 供自动打开 / 最终收口等同步逻辑立即读取;但不要逐帧把整份 stub 写进 React state。
// 后者会重建沙箱 ThreadContext 并让 ArtifactFileDetail 的预览 effect 连锁执行,
// 在「继续会商 + 正在写文件」的高密度帧下曾触发 Maximum update depth exceeded。
const pendingSeatStubMessagesRef = useRef<
Record<string, StubAiMessage[]> | null
>(null);
const seatStubFlushTimerRef = useRef<number | null>(null);
const [selectedAgents, setSelectedAgents] = useState<SelectedAgent[]>(
DEFAULT_SELECTED_AGENTS,
);
@@ -552,6 +560,11 @@ export function useStep2Orchestration(
new Map(),
);
const parallelFlushTimerRef = useRef<number | null>(null);
// 非并行的 leader / 单席位流同样不能逐 token 直接 setState。SSE reader 可能在一次
// 浏览器任务里吐出大量已缓冲帧;逐帧 setState 会与消息区的 effect 连锁,最终触发
// React 的 Maximum update depth 保护。先累积到 ref,再以固定节流频率提交到界面。
const directStreamDeltaRef = useRef<Map<number, string>>(new Map());
const directStreamFlushTimerRef = useRef<number | null>(null);
// flush 时要读「当前选中席位」与「批次 bubbleId↔agentId 映射」—— 打到 ref 避免
// 把 flush 函数绑进会频繁变化的 state 依赖。
const selectedParallelSeatsRef = useRef<string[]>([]);
@@ -684,6 +697,57 @@ export function useStep2Orchestration(
return ids[agentName] ?? ids[agentName.toLowerCase()];
}, []);
/**
* 把写文件预览的 stub 以约 12fps 合并交给 React。
*
* `seatStubMessagesRef` 已在调用处同步更新,故这里的延迟只影响右侧 Markdown
* 重绘频率,不影响随后读取最新 path/content、也不影响自动打开沙箱。
*/
const flushSeatStubMessages = useCallback(() => {
seatStubFlushTimerRef.current = null;
const pending = pendingSeatStubMessagesRef.current;
if (!pending) return;
pendingSeatStubMessagesRef.current = null;
setSeatStubMessages((previous) => (previous === pending ? previous : pending));
}, []);
const scheduleSeatStubMessagesFlush = useCallback(() => {
if (seatStubFlushTimerRef.current !== null) return;
seatStubFlushTimerRef.current = window.setTimeout(
flushSeatStubMessages,
80,
);
}, [flushSeatStubMessages]);
/** 清掉未提交的流式预览,并立即发布一个确定的快照(草稿恢复 / 重置时使用)。 */
const replaceSeatStubMessages = useCallback(
(next: Record<string, StubAiMessage[]>) => {
pendingSeatStubMessagesRef.current = null;
if (seatStubFlushTimerRef.current !== null) {
window.clearTimeout(seatStubFlushTimerRef.current);
seatStubFlushTimerRef.current = null;
}
seatStubMessagesRef.current = next;
setSeatStubMessages((previous) => (previous === next ? previous : next));
},
[],
);
const resetSeatStubMessages = useCallback(() => {
replaceSeatStubMessages({});
}, [replaceSeatStubMessages]);
// 卸载时清理挂起的预览 flush,避免已离开的页面仍收到一次 setState。
useEffect(
() => () => {
if (seatStubFlushTimerRef.current !== null) {
window.clearTimeout(seatStubFlushTimerRef.current);
seatStubFlushTimerRef.current = null;
}
},
[],
);
/**
* 把工具调用幂等地写进 seat 的 stub ai message —— **同 (toolName, path)** 视为同一次
* 调用,后续帧只更新 args(LangGraph 流式期间会多次发送完整 tool_calls 覆盖 args)。
@@ -734,10 +798,11 @@ export function useStep2Orchestration(
[seatThreadId]: [nextAiMsg],
};
seatStubMessagesRef.current = nextMap;
setSeatStubMessages(nextMap);
pendingSeatStubMessagesRef.current = nextMap;
scheduleSeatStubMessagesFlush();
return { messageId: nextAiMsg.id, toolCallId };
},
[],
[scheduleSeatStubMessagesFlush],
);
/**
@@ -1026,12 +1091,6 @@ export function useStep2Orchestration(
args,
);
const virtualUrl = buildWriteFileVirtualUrl(path, messageId, toolCallId);
if (typeof window !== "undefined") {
console.debug(
"[roundtable-sandbox] auto-open from phase",
{ toolName, path, seatThreadId, virtualUrl },
);
}
openSeatVirtualArtifact(seatThreadId, virtualUrl, true);
},
[
@@ -1272,9 +1331,15 @@ export function useStep2Orchestration(
const setDialogueConfidence = useCallback(
(id: number, confidence: string) => {
setStep2RoundtableDialogues((prev) =>
prev.map((d) => (d.id === id ? { ...d, confidence } : d)),
);
setStep2RoundtableDialogues((prev) => {
const index = prev.findIndex((dialogue) => dialogue.id === id);
// onPhaseChange 可在一个 SSE read 内收到多帧相同的 phase。状态文字没有变化
// 时必须返回原数组;否则 React 会把无意义的新数组当成一次嵌套更新。
if (index < 0 || prev[index].confidence === confidence) return prev;
const next = [...prev];
next[index] = { ...prev[index], confidence };
return next;
});
},
[],
);
@@ -1286,30 +1351,39 @@ export function useStep2Orchestration(
key: string,
args?: Record<string, unknown>,
) => {
setStep2RoundtableDialogues((prev) =>
prev.map((d) => {
if (d.id !== bubbleId) return d;
const steps: Step2Dialogue["steps"] = d.steps ?? [];
const last = steps[steps.length - 1];
if (last && last.key === key) {
// 同 phase:tool 重复回调 —— 流式累积期 args 会持续长大(present_files
// 多文件分批、write_file 内容增长),拿最新 args 覆盖,不要早早定死。
if (args && args !== last.args) {
const next = [...steps];
next[next.length - 1] = { ...last, args };
return { ...d, steps: next };
}
return d;
}
return {
...d,
setStep2RoundtableDialogues((prev) => {
const dialogueIndex = prev.findIndex((dialogue) => dialogue.id === bubbleId);
if (dialogueIndex < 0) return prev;
const dialogue = prev[dialogueIndex];
const steps: Step2Dialogue["steps"] = dialogue.steps ?? [];
const last = steps[steps.length - 1];
let nextDialogue: Step2Dialogue;
if (last && last.key === key) {
// 同一个工具调用在流式期间会反复带来增量入参。步骤卡只需在「首次拿到
// 可见参数」时补一次;文件正文由 upstream frame 同步给沙箱,不能随每个
// content chunk 更新对话 state。
const hasVisibleArgs = (value?: Record<string, unknown>) =>
!!value && Object.keys(value).some((argKey) => argKey !== "content");
if (hasVisibleArgs(last.args) || !hasVisibleArgs(args)) return prev;
const nextSteps = [...steps];
nextSteps[nextSteps.length - 1] = { ...last, args };
nextDialogue = { ...dialogue, steps: nextSteps };
} else {
nextDialogue = {
...dialogue,
steps: [
...steps,
{ id: `${bubbleId}-${steps.length}`, key, label, ts: nowTime(), args },
],
};
}),
);
}
const next = [...prev];
next[dialogueIndex] = nextDialogue;
return next;
});
},
[],
);
@@ -1342,20 +1416,45 @@ export function useStep2Orchestration(
[],
);
/** 将非并行流的已积累增量一次性写入 React state(约 20fps)。 */
const flushDirectStreamDeltas = useCallback(() => {
directStreamFlushTimerRef.current = null;
const pending = directStreamDeltaRef.current;
if (pending.size === 0) return;
directStreamDeltaRef.current = new Map();
setStep2RoundtableDialogues((prev) => {
let changed = false;
const next = prev.map((dialogue) => {
const delta = pending.get(dialogue.id);
if (!delta) return dialogue;
changed = true;
return { ...dialogue, content: (dialogue.content ?? "") + delta };
});
return changed ? next : prev;
});
}, []);
const scheduleDirectStreamFlush = useCallback(() => {
if (directStreamFlushTimerRef.current !== null) return;
directStreamFlushTimerRef.current = window.setTimeout(flushDirectStreamDeltas, 50);
}, [flushDirectStreamDeltas]);
const appendToDialogue = useCallback((id: number, deltaText: string) => {
if (!deltaText) return;
setStep2RoundtableDialogues((prev) =>
prev.map((d) =>
d.id === id ? { ...d, content: (d.content ?? "") + deltaText } : d,
),
);
}, []);
const pending = directStreamDeltaRef.current;
pending.set(id, (pending.get(id) ?? "") + deltaText);
scheduleDirectStreamFlush();
}, [scheduleDirectStreamFlush]);
/** 整段替换某气泡正文(§6 flush:把 ref 里累积的全文一次性挂上去)。 */
const setDialogueContent = useCallback((id: number, fullText: string) => {
setStep2RoundtableDialogues((prev) =>
prev.map((d) => (d.id === id ? { ...d, content: fullText } : d)),
);
setStep2RoundtableDialogues((prev) => {
const index = prev.findIndex((dialogue) => dialogue.id === id);
if (index < 0 || prev[index].content === fullText) return prev;
const next = [...prev];
next[index] = { ...prev[index], content: fullText };
return next;
});
}, []);
/**
@@ -1372,6 +1471,7 @@ export function useStep2Orchestration(
const who = info.agentName || "智能体";
triggerToast(`「${info.failedModel}」模型${info.reason},已自动切换「${info.nextModel}」继续`);
if (isParallel) parallelStreamRef.current.delete(bubbleId);
directStreamDeltaRef.current.delete(bubbleId);
const systemBubble: Step2Dialogue = {
id: Date.now() + Math.random(),
sender: "系统提示",
@@ -1440,8 +1540,17 @@ export function useStep2Orchestration(
}
}, []);
const resetDirectStreamDeltas = useCallback(() => {
directStreamDeltaRef.current = new Map();
if (directStreamFlushTimerRef.current !== null) {
window.clearTimeout(directStreamFlushTimerRef.current);
directStreamFlushTimerRef.current = null;
}
}, []);
// 卸载兜底:清掉可能挂起的 flush 定时器。
useEffect(() => resetParallelStreams, [resetParallelStreams]);
useEffect(() => resetDirectStreamDeltas, [resetDirectStreamDeltas]);
// 选中变化 → 立刻把 ref 里已累积的全文挂给**新选中**的席位(切头像即显全部输出,
// 证明流没丢、只是之前没渲染,§6.5)。
@@ -1508,21 +1617,40 @@ export function useStep2Orchestration(
const finalizeDialogue = useCallback(
(id: number, finalContent: string, confidence?: string) => {
setStep2RoundtableDialogues((prev) =>
prev.map((d) => {
// 最终结果已经是完整文本,丢弃尚未 flush 的 token 缓冲,避免收尾后旧增量反写。
directStreamDeltaRef.current.delete(id);
if (
directStreamDeltaRef.current.size === 0 &&
directStreamFlushTimerRef.current !== null
) {
window.clearTimeout(directStreamFlushTimerRef.current);
directStreamFlushTimerRef.current = null;
}
setStep2RoundtableDialogues((prev) => {
let changed = false;
const next = prev.map((d) => {
if (d.id !== id) return d;
const next =
finalContent && finalContent.trim().length > 0
? finalContent
: d.content || "(无文本输出)";
if (
d.content === next &&
d.confidence === (confidence ?? d.confidence) &&
d.streaming === false
) {
return d;
}
changed = true;
return {
...d,
content: next,
confidence: confidence ?? d.confidence,
streaming: false,
};
}),
);
});
return changed ? next : prev;
});
},
[],
);
@@ -2552,7 +2680,7 @@ export function useStep2Orchestration(
seatSkillDirective: seatSkillDirectivesRef.current[agentId] ?? false,
signal: subAborter.signal,
// §6:并行席位走 ref 全量累积 + 节流 flush(只渲染选中的);单节点
// stage 实际串行,1 路流直接 setState 不卡,沿用 appendToDialogue。
// stage 也经 appendToDialogue 的节流缓冲,避免高频 SSE 帧嵌套更新。
onModelSwitch: makeModelSwitchHandler(bubbleId, isParallel),
onTextDelta: (text) =>
isParallel ? ingestParallelDelta(bubbleId, text) : appendToDialogue(bubbleId, text),
@@ -3182,6 +3310,7 @@ export function useStep2Orchestration(
// 需要 ref 立刻可读到作业的真实线程,否则读到旧值导致接管失败。
threadIdsRef.current = snapshot.threadIds;
coordinatorNameRef.current = snapshot.coordinatorName;
resetDirectStreamDeltas();
// 历史快照是**静止记录**:任何残留「流式/加载中」的气泡(用户中途点了「停止」,
// 或草稿在流式期间被自动保存)都强制收尾为静止态。否则用户点聊天记录回看时,这些
// 气泡仍显示「调度中 / 等待响应 / 正在输出…」+ 加载光标,让人误以为还在进行(其实早已结束)。
@@ -3203,15 +3332,14 @@ export function useStep2Orchestration(
setConsensusPercentage(snapshot.consensusPercentage);
setBudgetLimit(snapshot.budgetLimit);
const restoredStubs = snapshot.seatStubMessages ?? {};
seatStubMessagesRef.current = restoredStubs;
setSeatStubMessages(restoredStubs);
replaceSeatStubMessages(restoredStubs);
// 草稿里历史 write_file 的虚拟 URL 与当前会话无关 —— 清空守卫,允许新 run 触发自动打开。
hasAutoOpenedRef.current = new Set();
// 调用方根据 furthestStep 决定是否置 init 闸门为已 init;这里默认置上,
// 调用方需要的话再 resetInitGate()。
step2InitRef.current = true;
},
[],
[replaceSeatStubMessages, resetDirectStreamDeltas],
);
// 「查看=恢复流程」:后台作业 SSE 帧 → 第二步实时画面(只更新展示数据,不动
@@ -3225,13 +3353,12 @@ export function useStep2Orchestration(
lastLeaderContent: string;
}) => {
setStep2RoundtableDialogues(frame.dialogues);
seatStubMessagesRef.current = frame.seatStubMessages;
setSeatStubMessages(frame.seatStubMessages);
replaceSeatStubMessages(frame.seatStubMessages);
setConsensusPercentage(frame.consensusPercentage);
setHasConsensus(frame.hasConsensus);
if (frame.lastLeaderContent) setLastLeaderContent(frame.lastLeaderContent);
},
[],
[replaceSeatStubMessages],
);
// 「后台挂起接管」:取消后端作业 + hydrateFromDraft(恢复作业真实线程/协调名/对话)后,
@@ -3279,11 +3406,11 @@ export function useStep2Orchestration(
setSelectedParallelSeats([]);
setDagNodeStates({});
resetParallelStreams();
resetDirectStreamDeltas();
setActiveArtifactThreadId(null);
artifactPathsRef.current = [];
setArtifacts([]);
seatStubMessagesRef.current = {};
setSeatStubMessages({});
resetSeatStubMessages();
hasAutoOpenedRef.current = new Set();
pendingInjectPromptRef.current = null;
dagPlanExecutedRef.current = false;
@@ -3292,7 +3419,14 @@ export function useStep2Orchestration(
gatheredDeliveriesRef.current = [];
deselectArtifact();
step2InitRef.current = false;
}, [abortAllInFlight, deselectArtifact, setArtifacts, resetParallelStreams]);
}, [
abortAllInFlight,
deselectArtifact,
setArtifacts,
resetParallelStreams,
resetDirectStreamDeltas,
resetSeatStubMessages,
]);
return {
selectedAgents,