接口联调

This commit is contained in:
董宏凯 committed 2026-05-23 23:05:01 +08:00
1 parent 43df9175df
commit 8673eb5eca
148 files changed
+2050 -37963

No files matched your search

@@ -1,4 +1,6 @@
import React, { useState, useEffect, useRef, useCallback } from "react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import { HighFidelityReport } from "@/roundtable-planning/components/HighFidelityReport";
import { useTheme } from "@/contexts/ThemeContext";
import { cn } from "@/lib/utils";
@@ -6,7 +8,9 @@ import { useModels } from "@/core/models/hooks";
import {
initMultiAgent,
streamMultiAgent,
type ClarificationPayload,
type LeaderDispatch,
type StreamPhase,
type ThreadIdMap,
} from "@/roundtable-planning/api/multi-agent";
import {
@@ -39,7 +43,8 @@ import {
Cpu,
CornerDownRight,
Star,
ShieldCheck
ShieldCheck,
Loader2,
} from "lucide-react";
// --- Custom Crisp SVGs to Match High Fidelity Avatars ---
@@ -306,6 +311,11 @@ export default function RoundtablePlanningPage() {
const [isInitializing, setIsInitializing] = useState<boolean>(false);
const [initError, setInitError] = useState<string | null>(null);
const [isOrchestrating, setIsOrchestrating] = useState<boolean>(false);
// When the coordinator calls ask_clarification, the leader run ends with
// this payload populated; the page renders a question card and only
// resumes orchestration once the user replies.
const [pendingClarification, setPendingClarification] = useState<ClarificationPayload | null>(null);
const [clarificationDraft, setClarificationDraft] = useState<string>("");
const orchestrationCancelRef = useRef<boolean>(false);
const step2InitRef = useRef<boolean>(false);
// Tracks every AbortController active in this Step 2 visit so the "停止" /
@@ -368,6 +378,38 @@ export default function RoundtablePlanningPage() {
]);
}, []);
// Translate an inferred SSE phase into a human-readable confidence label
// for the dialogue bubble. We keep the bubble's existing in-progress
// confidence ("调度中" / "正在输出…") when phase doesn't add information,
// and switch to a specific label when something specific is happening.
const phaseLabel = useCallback((phase: StreamPhase, agentType: "leader" | "special", toolName?: string): string => {
switch (phase) {
case "connecting":
return "调度中";
case "connected":
return "已连接,等待响应";
case "tool_calling":
if (toolName === "agent_orchestration") return "正在派活";
if (toolName === "ask_clarification") return "正在提问";
if (toolName === "present_files") return "正在交付文件";
return toolName ? `调用工具:${toolName}` : "调用工具";
case "tool_result":
return "处理工具结果";
case "streaming":
return agentType === "leader" ? "正在派活说明" : "正在输出";
default:
return agentType === "leader" ? "调度中" : "正在输出…";
}
}, []);
// Update only the confidence field of a streaming card by id. Used by the
// phase callback so we can change the label without touching content.
const setDialogueConfidence = useCallback((id: number, confidence: string) => {
setStep2RoundtableDialogues(prev =>
prev.map(d => (d.id === id ? { ...d, confidence } : d)),
);
}, []);
// Streaming variant: append a placeholder card and return its id so subsequent
// text deltas can be appended in-place via appendToDialogue.
const appendStreamingDialogue = useCallback((card: {
@@ -501,8 +543,10 @@ export default function RoundtablePlanningPage() {
safetyCounter += 1;
highlightSpeaker(2);
// Leader bubble — created BEFORE the call so users see "正在输出…" the
// moment the request is in flight, then text fills in as deltas arrive.
// Leader bubble — created BEFORE the call so users see "调度中" the
// moment the request is in flight, then phase changes flip the
// confidence label so the user sees what the backend is actually
// doing during the ~1-2s first-token wait.
const leaderBubbleId = appendStreamingDialogue({
sender: "总控协调",
avatarType: "blue",
@@ -523,6 +567,9 @@ export default function RoundtablePlanningPage() {
model: DEFAULT_MODEL,
signal: leaderAborter.signal,
onTextDelta: (text) => appendToDialogue(leaderBubbleId, text),
onPhaseChange: (phase, toolName) => {
setDialogueConfidence(leaderBubbleId, phaseLabel(phase, "leader", toolName));
},
});
} catch (err) {
activeAbortersRef.current.delete(leaderAborter);
@@ -536,6 +583,18 @@ export default function RoundtablePlanningPage() {
if (orchestrationCancelRef.current) break;
// Clarification branch — leader asked the user a question. Stop the
// auto loop, surface the question card, and wait for the user to
// reply before another leader cycle.
if (leaderRes.clarification) {
finalizeDialogue(leaderBubbleId, leaderRes.content, "等待用户澄清");
highlightSpeaker(null);
setPendingClarification(leaderRes.clarification);
setClarificationDraft("");
triggerToast("❓ 总控需要补充信息,请回答下方问题后继续");
break;
}
finalizeDialogue(
leaderBubbleId,
leaderRes.content,
@@ -549,52 +608,59 @@ export default function RoundtablePlanningPage() {
break;
}
// Dispatch all sub-agents in parallel; per-seat model preference
// overrides the default if the user picked one in the drawer. Each
// sub-agent gets its own streaming bubble that fills independently.
await Promise.allSettled(
leaderRes.dispatched.map(async ([subName, task]) => {
if (orchestrationCancelRef.current) return;
const meta = AGENT_NAME_TO_ROLE[subName.toLowerCase()];
// Add this speaker to the concurrent active set so its avatar
// lights up alongside any other sub-agents streaming in parallel.
if (meta) markSpeakerStreaming(meta.speakerId);
const perSeatModel = meta ? agentConfigs[meta.speakerId]?.model : undefined;
// Dispatch sub-agents sequentially (one at a time). Running them in
// parallel meant N concurrent SSE streams each triggering a full-list
// setState on every token delta, which made the browser stutter badly
// when the leader 派活给多个席位。改为顺序后,同一时刻只有一个 SSE 在跑。
for (const [subName, task] of leaderRes.dispatched) {
if (orchestrationCancelRef.current) break;
const meta = AGENT_NAME_TO_ROLE[subName.toLowerCase()];
if (meta) markSpeakerStreaming(meta.speakerId);
const perSeatModel = meta ? agentConfigs[meta.speakerId]?.model : undefined;
const subBubbleId = appendStreamingDialogue({
sender: meta?.displayName ?? subName,
avatarType: meta?.avatarType ?? "blue",
initialContent: "",
confidence: "正在输出…",
const subBubbleId = appendStreamingDialogue({
sender: meta?.displayName ?? subName,
avatarType: meta?.avatarType ?? "blue",
initialContent: "",
confidence: "调度中",
});
const subAborter = new AbortController();
activeAbortersRef.current.add(subAborter);
let aborted = false;
try {
const specRes = await streamMultiAgent({
agentType: "special",
dAgentThreadId: ids,
agentName: subName,
newMessage: task,
model: perSeatModel || DEFAULT_MODEL,
signal: subAborter.signal,
onTextDelta: (text) => appendToDialogue(subBubbleId, text),
onPhaseChange: (phase, toolName) => {
setDialogueConfidence(subBubbleId, phaseLabel(phase, "special", toolName));
},
});
const subAborter = new AbortController();
activeAbortersRef.current.add(subAborter);
try {
const specRes = await streamMultiAgent({
agentType: "special",
dAgentThreadId: ids,
agentName: subName,
newMessage: task,
model: perSeatModel || DEFAULT_MODEL,
signal: subAborter.signal,
onTextDelta: (text) => appendToDialogue(subBubbleId, text),
});
if (orchestrationCancelRef.current) return;
if (orchestrationCancelRef.current) {
finalizeDialogue(subBubbleId, specRes.content || "(已停止)", "已停止");
aborted = true;
} else {
finalizeDialogue(subBubbleId, specRes.content, "子智能体交付");
} catch (err) {
if (subAborter.signal.aborted || (err as Error).name === "AbortError") {
finalizeDialogue(subBubbleId, "(已停止)", "已停止");
} else {
console.error(`[special:${subName}] error:`, err);
finalizeDialogue(subBubbleId, `(错误) ${(err as Error).message}`, "调用失败");
}
} finally {
activeAbortersRef.current.delete(subAborter);
if (meta) markSpeakerIdle(meta.speakerId);
}
}),
);
} catch (err) {
if (subAborter.signal.aborted || (err as Error).name === "AbortError") {
finalizeDialogue(subBubbleId, "(已停止)", "已停止");
aborted = true;
} else {
console.error(`[special:${subName}] error:`, err);
finalizeDialogue(subBubbleId, `(错误) ${(err as Error).message}`, "调用失败");
}
} finally {
activeAbortersRef.current.delete(subAborter);
if (meta) markSpeakerIdle(meta.speakerId);
}
if (aborted) break;
}
if (orchestrationCancelRef.current) break;
@@ -635,6 +701,12 @@ export default function RoundtablePlanningPage() {
abortAllInFlight();
step2InitRef.current = false;
setIsOrchestrating(false);
setPendingClarification(null);
setClarificationDraft("");
// Re-entering step 2 should start with the discussion nominally
// "running" so the suspend button comes back; the prior visit might
// have ended in a paused state.
setIsRoundTableRunning(true);
return;
}
@@ -654,6 +726,23 @@ export default function RoundtablePlanningPage() {
agentNames: ROUNDTABLE_AGENT_IDS,
mainAgentName: coord,
model: DEFAULT_MODEL,
// As each sub-agent's thread comes online, flip every role that
// shares the agentId to "在线". Some seats reuse the same agent
// (e.g. seat 8 reuses roundtable-summary) so we match on agentId
// rather than a single id.
onSeatReady: ({ agentName }) => {
if (cancelled) return;
const id = agentName.toLowerCase();
setRoles(prev =>
prev.map(r => (r.agentId === id ? { ...r, status: "在线" } : r)),
);
},
// Coordinator readiness is a no-op for the role list (the
// coordinator isn't rendered as a seat), but we keep the hook in
// case we want to drop a "系统" toast later.
onCoordinatorReady: () => {
if (cancelled) return;
},
});
if (cancelled) return;
setThreadIds(initRes.thread_ids);
@@ -851,11 +940,15 @@ export default function RoundtablePlanningPage() {
};
// Step 2 role statuses transition when entering roundtable!
// On Step 2 entry we set every agent seat to "正在上线" (spinner state);
// the /init SSE stream then flips each one to "在线" as its thread/agent
// actually finishes on the backend. Seat 1 (human commander) stays online
// throughout — it's not part of the bring-up.
useEffect(() => {
if (currentStep === 1) {
setRoles(makeRoles("等待激活", { 2: "在线" }));
} else if (currentStep === 2) {
setRoles(makeRoles("在线", { 8: "等待陈述" }));
setRoles(makeRoles("正在上线", { 1: "在线" }));
} else {
setRoles(makeRoles("已完成"));
}
@@ -887,6 +980,36 @@ export default function RoundtablePlanningPage() {
void runOrchestration(`用户人工干预新指令:${userText}\n\n请结合当前讨论状态,决定是否继续派活或直接给出更新后的结论。`, threadIds, coordinatorName);
};
// Submit the user's answer to the coordinator's clarification question and
// resume orchestration. The reply is fed back as the next leader prompt on
// the same coordinator thread (no re-init needed).
const submitClarification = (rawAnswer: string) => {
const answer = rawAnswer.trim();
if (!answer) return;
if (!threadIds || !coordinatorName) {
triggerToast("⚠️ 圆桌尚未就绪,无法回复澄清");
return;
}
if (isOrchestrating) {
triggerToast("⏳ 当前轮次仍在进行中,请稍候");
return;
}
const question = pendingClarification?.question || "(澄清问题)";
appendDialogue({
sender: "用户 (澄清回复)",
avatarType: "human",
content: `🗣 回复总控提问:${answer}`,
confidence: "澄清回复",
});
setPendingClarification(null);
setClarificationDraft("");
void runOrchestration(
`用户已回复你刚才的澄清问题。\n问题:${question}\n用户回答:${answer}\n请基于该回答继续派活或给出结论。`,
threadIds,
coordinatorName,
);
};
return (
<div
className={cn(
@@ -1182,13 +1305,18 @@ export default function RoundtablePlanningPage() {
{roles.map((role) => {
const isActive = role.status === "在线" || role.status === "研讨中" || role.status === "已完成";
const isOngoing = role.status === "研讨中";
const isBootingUp = role.status === "正在上线";
return (
<div
<div
id={`role-item-${role.id}`}
key={role.id}
key={role.id}
className={`flex items-center justify-between p-2 rounded-xl transition ${
isActive ? "bg-slate-50 border border-slate-100" : "opacity-60"
isActive
? "bg-slate-50 border border-slate-100"
: isBootingUp
? "bg-amber-50/60 border border-amber-100"
: "opacity-60"
}`}
>
<div className="flex items-center gap-2.5">
@@ -1229,18 +1357,22 @@ export default function RoundtablePlanningPage() {
</span>
) : role.status === "已完成" ? (
<Check className="h-3.5 w-3.5 text-emerald-500 font-bold" />
) : isBootingUp ? (
<Loader2 className="h-3 w-3 text-amber-500 animate-spin" />
) : (
<span className="h-1.5 w-1.5 rounded-full bg-slate-300" />
)}
<span className={`text-[10px] font-semibold ${
isOngoing
? "text-[var(--brand-900)]"
isOngoing
? "text-[var(--brand-900)]"
: role.status === "在线"
? "text-emerald-600 font-bold"
: role.status === "已完成"
? "text-emerald-600"
: "text-slate-400"
: isBootingUp
? "text-amber-600"
: "text-slate-400"
}`}>
{role.status}
</span>
@@ -1608,23 +1740,33 @@ export default function RoundtablePlanningPage() {
>极速</button>
</div>
{isRoundTableRunning ? (
<button
{/* Suspend / resume button visibility:
- Show "挂起协商" only while a run is actually in flight
(isOrchestrating + still nominally running). When the
discussion finishes naturally there's nothing to
suspend, so the button hides; it'll come back the
next time orchestration starts (user "干预研审" or
clarification reply).
- Show "恢复会商" any time the user has explicitly paused
(!isRoundTableRunning) regardless of orchestration
state, so they can always recover from a manual pause. */}
{isRoundTableRunning && isOrchestrating ? (
<button
onClick={() => { setIsRoundTableRunning(false); triggerToast("⏸️ 会商模拟暂挂!智能体挂起..."); }}
className="bg-amber-100 hover:bg-amber-200 text-amber-800 text-[10px] font-bold px-2.5 py-1 rounded-xl flex items-center gap-1 transition border border-amber-200/40 shadow-sm"
>
<Pause className="w-3.5 h-3.5" />
挂起协商
</button>
) : (
<button
) : !isRoundTableRunning ? (
<button
onClick={() => { setIsRoundTableRunning(true); triggerToast("▶️ 恢复大模型并行博弈与推理决策"); }}
className="bg-emerald-100 hover:bg-emerald-200 text-emerald-800 text-[10px] font-bold px-2.5 py-1 rounded-xl flex items-center gap-1 transition border border-emerald-200/40 shadow-sm"
>
<Play className="w-3.5 h-3.5 fill-emerald-800" />
恢复会商
</button>
)}
) : null}
</div>
</div>
@@ -1995,17 +2137,165 @@ export default function RoundtablePlanningPage() {
</div>
<span className="text-[10px] text-slate-400 font-mono font-medium">{msg.time}</span>
</div>
<p className="text-xs text-slate-700 leading-relaxed font-medium whitespace-pre-wrap break-words">
{msg.content}
<div className="text-xs text-slate-700 leading-relaxed font-medium break-words roundtable-md">
{/* Pre-streaming hint — when the bubble is created but
no AI token has arrived yet, show a small spinner
+ the current phase label so the user can see the
backend is doing something (调度中 → 已连接 →
正在派活/调用工具 → 流式输出). */}
{msg.streaming && !msg.content && (
<div className="flex items-center gap-2 py-1 text-[11px] text-slate-500 italic">
<Loader2 className="w-3 h-3 animate-spin text-primary" />
<span>{msg.confidence}</span>
</div>
)}
<ReactMarkdown
remarkPlugins={[remarkGfm]}
components={{
// Compact spacing for chat bubbles — react-markdown's
// default block margins are too tall for this UI.
p: ({ children }) => <p className="my-1 whitespace-pre-wrap">{children}</p>,
ul: ({ children }) => <ul className="list-disc pl-5 my-1 space-y-0.5">{children}</ul>,
ol: ({ children }) => <ol className="list-decimal pl-5 my-1 space-y-0.5">{children}</ol>,
li: ({ children }) => <li className="leading-snug">{children}</li>,
h1: ({ children }) => <h1 className="text-sm font-bold mt-2 mb-1">{children}</h1>,
h2: ({ children }) => <h2 className="text-sm font-bold mt-2 mb-1">{children}</h2>,
h3: ({ children }) => <h3 className="text-xs font-bold mt-1.5 mb-0.5">{children}</h3>,
h4: ({ children }) => <h4 className="text-xs font-bold mt-1 mb-0.5">{children}</h4>,
strong: ({ children }) => <strong className="font-bold text-slate-900">{children}</strong>,
em: ({ children }) => <em className="italic">{children}</em>,
code: ({ children, className }) => {
const isBlock = /language-/.test(className ?? "");
if (isBlock) {
return (
<pre className="bg-slate-100 text-slate-800 rounded-md p-2 my-1 overflow-x-auto text-[11px] font-mono">
<code>{children}</code>
</pre>
);
}
return (
<code className="bg-slate-100 text-slate-800 rounded px-1 py-0.5 text-[11px] font-mono">
{children}
</code>
);
},
blockquote: ({ children }) => (
<blockquote className="border-l-2 border-slate-300 pl-2 my-1 text-slate-600 italic">
{children}
</blockquote>
),
a: ({ children, href }) => (
<a
href={href}
target="_blank"
rel="noopener noreferrer"
className="text-primary underline hover:opacity-80"
>
{children}
</a>
),
table: ({ children }) => (
<table className="my-1 border-collapse text-[11px]">{children}</table>
),
th: ({ children }) => (
<th className="border border-slate-300 px-1.5 py-0.5 bg-slate-50 font-bold text-left">
{children}
</th>
),
td: ({ children }) => (
<td className="border border-slate-200 px-1.5 py-0.5">{children}</td>
),
hr: () => <hr className="my-2 border-slate-200" />,
}}
>
{msg.content ?? ""}
</ReactMarkdown>
{msg.streaming && (
<span className="inline-block w-1 h-3 ml-0.5 bg-primary align-middle animate-pulse" />
)}
</p>
</div>
</div>
</div>
))}
</div>
{/* Clarification card — shown only when the coordinator asked
the user a question via ask_clarification. The auto-loop is
paused; replying resumes orchestration on the same threads. */}
{pendingClarification && (
<div className="shrink-0 px-4 pt-3 bg-amber-50 border-t-2 border-amber-300">
<div className="flex items-start gap-3">
<HelpCircle className="w-5 h-5 text-amber-600 shrink-0 mt-0.5" />
<div className="flex-1 space-y-2">
<div className="flex items-center gap-2">
<span className="text-xs font-extrabold text-amber-900">
总控协调需要澄清
</span>
{pendingClarification.clarificationType && (
<span className="text-[9px] font-mono font-black uppercase text-amber-900 bg-amber-200 border border-amber-300 px-1.5 py-0.2 rounded">
{pendingClarification.clarificationType}
</span>
)}
</div>
{pendingClarification.context && (
<p className="text-[11px] text-amber-800 italic">
{pendingClarification.context}
</p>
)}
<p className="text-xs text-slate-800 leading-relaxed font-medium whitespace-pre-wrap break-words">
{pendingClarification.question}
</p>
{Array.isArray(pendingClarification.options) &&
pendingClarification.options.length > 0 && (
<div className="flex flex-wrap gap-2 pt-1">
{pendingClarification.options.map((opt, idx) => {
const label =
typeof opt === "string"
? opt
: opt && typeof opt === "object" && "label" in (opt as object)
? String((opt as { label: unknown }).label ?? "")
: String(opt ?? "");
if (!label) return null;
return (
<button
key={`${idx}-${label}`}
type="button"
onClick={() => submitClarification(label)}
className="text-[11px] font-bold px-3 py-1.5 rounded-full bg-white border border-amber-300 text-amber-900 hover:bg-amber-100 transition active:scale-95 cursor-pointer"
>
{label}
</button>
);
})}
</div>
)}
{pendingClarification.allowCustom !== false && (
<div className="flex items-center gap-2 pt-1">
<input
type="text"
value={clarificationDraft}
onChange={(e) => setClarificationDraft(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") submitClarification(clarificationDraft);
}}
placeholder="输入你的回答…"
className="flex-1 bg-white border border-amber-300 rounded-xl px-3 py-2 text-xs focus:outline-none focus:border-amber-500 focus:ring-1 focus:ring-amber-200 font-medium"
/>
<button
type="button"
onClick={() => submitClarification(clarificationDraft)}
disabled={!clarificationDraft.trim()}
className="bg-amber-600 hover:bg-amber-700 disabled:bg-slate-300 disabled:cursor-not-allowed text-white text-xs font-bold px-4 py-2 rounded-xl transition shrink-0 cursor-pointer active:scale-95 shadow-md shadow-amber-500/10"
>
回复
</button>
</div>
)}
</div>
</div>
</div>
)}
{/* Console control / Custom injection bar */}
<div className="shrink-0 p-4 bg-slate-50 border-t border-slate-100 flex items-center gap-3">
<input