多智能体协作

This commit is contained in:
董宏凯 committed 2026-05-25 17:48:59 +08:00
1 parent 9a70329db2
commit 525218f9a7
13 files changed
+753 -180

No files matched your search

@@ -21,6 +21,11 @@ import {
type IntentStreamPhase,
type IntentSummary,
} from "@/roundtable-planning/api/intent";
import {
IntentClarificationCard,
formatIntentClarificationAnswer,
type IntentClarificationSelection,
} from "@/roundtable-planning/components/IntentClarificationCard";
import { RecommendAgentsDialog } from "@/roundtable-planning/components/RecommendAgentsDialog";
import {
deleteDraft,
@@ -447,6 +452,10 @@ export default function RoundtablePlanningPage() {
const [intentReady, setIntentReady] = useState<IntentSummary | null>(null);
const [intentInitError, setIntentInitError] = useState<string | null>(null);
const [isIntentSending, setIsIntentSending] = useState<boolean>(false);
const [pendingIntentClarificationMsgId, setPendingIntentClarificationMsgId] = useState<number | null>(null);
const [intentClarificationSelections, setIntentClarificationSelections] = useState<
Map<number, IntentClarificationSelection>
>(new Map());
const step1InitRef = useRef<boolean>(false);
// Monotonic counter incremented every time Step 1 init starts. The in-flight
// async checks this on completion and bails if a newer init has begun (e.g.
@@ -522,6 +531,22 @@ export default function RoundtablePlanningPage() {
step1ScrollRef,
[interactiveMessages],
);
// Sync intentReady when [INTENT_READY] appears in chat but the stream frame
// missed it (e.g. clarification returned before summary was parsed).
useEffect(() => {
if (intentReady) return;
for (let i = interactiveMessages.length - 1; i >= 0; i--) {
const msg = interactiveMessages[i];
if (msg.sender === "user") continue;
const { summary } = splitIntentReadyBlock(msg.content ?? "");
if (summary) {
setIntentReady(summary);
setPendingIntentClarificationMsgId(null);
break;
}
}
}, [interactiveMessages, intentReady]);
const { atBottom: step2AtBottom, scrollToBottom: scrollStep2ToBottom } = useAutoScroll(
step2ScrollRef,
[step2RoundtableDialogues],
@@ -1105,6 +1130,8 @@ export default function RoundtablePlanningPage() {
setIntentReady(null);
setIntentInitError(null);
setIntentThreadId(null);
setPendingIntentClarificationMsgId(null);
setIntentClarificationSelections(new Map());
setTimelineEntries([]);
setInteractiveMessages([
{
@@ -1373,10 +1400,11 @@ export default function RoundtablePlanningPage() {
// Chat sender logic for Step 1 interaction — drives the real intent agent
// via /api/intent/stream. The agent streams its reply into a placeholder
// bubble; if its final status is "done" we capture the structured summary
// for the Step 2 handoff.
const handleSendMessage = async () => {
const userText = inputText.trim();
if (!userText) return;
// for the Step 2 handoff. When status is "clarification", render option
// cards like the main chat ClarificationCard.
const sendIntentMessage = async (userText: string) => {
const trimmed = userText.trim();
if (!trimmed) return;
if (!intentThreadId) {
triggerToast("⚠️ 任务理解智能体尚未就绪,请稍候");
return;
@@ -1386,33 +1414,31 @@ export default function RoundtablePlanningPage() {
return;
}
setPendingIntentClarificationMsgId(null);
const userMsgTime = nowTime();
const userMsgId = Date.now() + Math.random();
const userMsg = {
id: userMsgId,
sender: "user",
senderName: "用户",
content: userText,
content: trimmed,
time: userMsgTime,
};
setInteractiveMessages(prev => [...prev, userMsg]);
setInputText("");
setCharactersLeft(0);
// Right-side timeline gets a short summary too.
setTimelineEntries(prev => [
...prev,
{
id: prev.length + 1,
time: userMsgTime,
title: "用户实时反馈",
desc: userText.length > 25 ? userText.substring(0, 25) + "..." : userText,
desc: trimmed.length > 25 ? trimmed.substring(0, 25) + "..." : trimmed,
},
]);
// Placeholder agent bubble — text deltas accumulate into it. `phase`
// tracks the inferred SSE stage so the "in flight" caption can flip from
// "调度中" → "已连接,等待响应" → "正在思考问题" as the run progresses.
const agentMsgId = Date.now() + Math.random() + 0.01;
setInteractiveMessages(prev => [
...prev,
@@ -1427,9 +1453,6 @@ export default function RoundtablePlanningPage() {
} as any,
]);
// Map an inferred phase + (optional) tool name to a human-readable label
// shown next to the spinner. Tool-call phases highlight ask_clarification
// explicitly since that's the only tool the intent agent normally uses.
const intentPhaseLabel = (phase: IntentStreamPhase, toolName?: string): string => {
switch (phase) {
case "connecting":
@@ -1450,7 +1473,7 @@ export default function RoundtablePlanningPage() {
try {
const res = await streamIntent({
threadId: intentThreadId,
message: userText,
message: trimmed,
model: DEFAULT_MODEL,
onTextDelta: (delta) => {
setInteractiveMessages(prev =>
@@ -1464,29 +1487,44 @@ export default function RoundtablePlanningPage() {
);
},
});
// Finalize the bubble with the authoritative final text from the
// status frame (covers cases where deltas didn't accumulate cleanly).
const parsedFromContent = splitIntentReadyBlock(res.content || "").summary;
const resolvedSummary = res.summary ?? parsedFromContent;
setInteractiveMessages(prev =>
prev.map(m =>
m.id === agentMsgId
? { ...m, content: res.content || m.content || "(无文本输出)", streaming: false } as any
? {
...m,
content: res.content || m.content || "(无文本输出)",
streaming: false,
clarification: resolvedSummary ? undefined : res.clarification ?? undefined,
} as any
: m,
),
);
if (res.status === "done" && res.summary) {
setIntentReady(res.summary);
if (resolvedSummary) {
setIntentReady(resolvedSummary);
setPendingIntentClarificationMsgId(null);
setTimelineEntries(prev => [
...prev,
{
id: prev.length + 1,
time: nowTime(),
title: "任务意图已明确",
desc: res.summary!.objective.length > 25
? res.summary!.objective.substring(0, 25) + "..."
: res.summary!.objective,
desc: resolvedSummary.objective.length > 25
? resolvedSummary.objective.substring(0, 25) + "..."
: resolvedSummary.objective,
},
]);
triggerToast("✅ 任务理解完成,可进入多智能体圆桌研讨");
} else if (res.status === "clarification" && res.clarification) {
setPendingIntentClarificationMsgId(agentMsgId);
setIntentClarificationSelections(prev => {
const next = new Map(prev);
next.set(agentMsgId, { selectedIds: [], custom: "" });
return next;
});
} else if (res.status === "error") {
triggerToast(`❌ 智能体调用失败: ${res.content}`);
}
@@ -1505,6 +1543,29 @@ export default function RoundtablePlanningPage() {
}
};
const handleSendMessage = () => {
void sendIntentMessage(inputText);
};
const submitIntentClarification = (
msgId: number,
payload: ClarificationPayload,
overrideSelection?: IntentClarificationSelection,
) => {
const selection =
overrideSelection ??
intentClarificationSelections.get(msgId) ?? {
selectedIds: [],
custom: "",
};
const answer = formatIntentClarificationAnswer(payload, selection);
if (!answer) {
triggerToast("请先选择选项或输入回答");
return;
}
void sendIntentMessage(answer);
};
// Skip step logic
const handleSkipQuestion = () => {
const systemSkipMsg = {
@@ -2324,12 +2385,26 @@ export default function RoundtablePlanningPage() {
const isStreaming = (msg as { streaming?: boolean }).streaming === true;
const hasContent = (msg.content ?? "").length > 0;
const isAgent = msg.sender !== "user";
// Only agent replies carry markdown / [INTENT_READY]; user
// messages stay as plain text so casing/whitespace are
// preserved verbatim.
const clarification = (msg as { clarification?: ClarificationPayload }).clarification;
const parts = isAgent
? splitIntentReadyBlock(msg.content ?? "")
: { before: msg.content ?? "", summary: null, after: "" };
const isPendingClarification =
isAgent &&
clarification &&
!intentReady &&
!parts.summary &&
pendingIntentClarificationMsgId === msg.id;
const clarificationSelection =
intentClarificationSelections.get(msg.id) ?? {
selectedIds: [],
custom: "",
};
const introText =
clarification &&
parts.before.trim() === (clarification.question || "").trim()
? ""
: parts.before;
return (
<div key={msg.id} className="flex items-start justify-between gap-3 border-b border-slate-100/50 pb-2.5 last:border-0 last:pb-0">
<div className="flex items-start gap-2.5 min-w-0">
@@ -2352,7 +2427,7 @@ export default function RoundtablePlanningPage() {
</span>
) : isAgent ? (
<div className="text-xs text-slate-700 leading-normal font-normal break-words space-y-2">
{parts.before && (
{introText && (
<ReactMarkdown
remarkPlugins={[remarkGfm]}
components={{
@@ -2388,7 +2463,7 @@ export default function RoundtablePlanningPage() {
),
}}
>
{parts.before}
{introText}
</ReactMarkdown>
)}
{parts.summary && (
@@ -2433,6 +2508,25 @@ export default function RoundtablePlanningPage() {
{isStreaming && (
<span className="inline-block w-1 h-3 ml-0.5 bg-primary align-middle animate-pulse" />
)}
{isPendingClarification && clarification && (
<IntentClarificationCard
payload={clarification}
fallbackContent={parts.before || undefined}
selection={clarificationSelection}
onSelectionChange={(next) => {
setIntentClarificationSelections(prev => {
const map = new Map(prev);
map.set(msg.id, next);
return map;
});
}}
disabled={!isPendingClarification}
submitting={isIntentSending && isPendingClarification}
onSubmit={(override) =>
submitIntentClarification(msg.id, clarification, override)
}
/>
)}
</div>
) : (
<span className="text-xs text-slate-700 leading-normal font-normal whitespace-pre-wrap break-words">
@@ -2468,7 +2562,11 @@ export default function RoundtablePlanningPage() {
handleSendMessage();
}
}}
placeholder="请输入补充信息 / 回答问题 / 继续澄清 (Enter 快速发送)"
placeholder={
pendingIntentClarificationMsgId
? "也可在此输入自定义回答 (Enter 快速发送)"
: "请输入补充信息 / 回答问题 / 继续澄清 (Enter 快速发送)"
}
className="w-full text-xs text-slate-700 placeholder:text-slate-400 resize-none h-[48px] focus:outline-none leading-relaxed font-normal"
maxLength={500}
/>