Files
deerflow-code/frontend-web/src/roundtable-planning/components/Step1Panel.tsx
T
董宏凯andClaude Opus 4.8 03b6fb724c feat(roundtable): 深链策划流程小图 + 流程图弹窗横向/缩略图/深蓝适配
- Step1 消息列表头部:深链 taskId 模式取到目的树后,左侧标题换成「策划流程」
  彩色层级小图(任务→目的→…→叙事,每级配色对齐流程图节点 + 类型小图标),
  点击打开任务目的流程图弹窗;仅第一步、有数据时出现。
- TaskPurposeDialog 流程图:横向(LR)布局 + 右下角缩略图(MiniMap)。
- FlowGraphPanel 深蓝主题适配(随 ThemeContext):容器/头部/画布点阵/连线/图例/
  小地图/节点详情弹窗 + 节点配色(FLOW_NODE_TYPE_META_DARK),浅色红主题不受影响。
- 圆桌侧栏深色兜底:neutral 家族 + 米色 hex(#FAF6F5/#ECE7E4/#E8D0CC) 映射到深蓝
  token(关系图背板、第N步 tag 等不再泛白)。

附带提交工作区其余暂存改动(AI 写作等),不含 config.yaml。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-18 17:39:19 +08:00

596 lines
25 KiB
TypeScript

/**
* Step 1 主面板 —— 任务意图理解人机问答区。
*
* 主页面把所有 Step 1 状态(`useStep1Intent` 的返回值)+ 输入框 + 按钮处理函数
* 透传过来,这里只关心:对话列表渲染、INTENT_READY 摘要卡、澄清卡片嵌入气泡、
* 输入框 + 发送 / 暂停 / 跳过 / 继续追问 / 进入研讨 等底部按钮。
*
* 气泡通用渲染部分(头像 / header / loading 占位 / 流式 cursor / markdown 渲染)
* 复用 `MessageBubble.tsx` 暴露的原子件,与 Step 2 保持一致。
*
* **不要**在这里再 fetch / 建 thread / 跑 SSE —— 这些逻辑都在 `useStep1Intent`,
* 本组件保持纯展示 + 透传事件。
*/
import { useRef, useState } from "react";
import {
CheckCircle,
FileText,
Loader2,
MessageSquare,
Paperclip,
Pause,
Repeat,
Save,
Send,
Smile,
Sparkles,
X,
} from "lucide-react";
/** 人类可读的文件大小(B / KB / MB)。 */
function formatFileSize(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
}
import { AutoGrowTextarea } from "@/components/ui/auto-grow-textarea";
import { Button } from "@/components/ui/button";
import { useLocalSettings } from "@/core/settings";
import type { MessageMetric } from "@/components/workspace/messages/use-message-metrics";
import { Man1Avatar, RobotAvatar } from "@/roundtable-planning/components/Avatars";
import { DialogueSpeedMeter } from "@/roundtable-planning/components/DialogueSpeedMeter";
import {
clarificationKey,
IntentClarificationCard,
type IntentClarificationSelection,
} from "@/roundtable-planning/components/IntentClarificationCard";
import {
MarkdownContent,
MessageBubble,
MessageLoadingPlaceholder,
ReasoningBlock,
StreamingCursor,
} from "@/roundtable-planning/components/MessageBubble";
import { MessageStepsCard } from "@/roundtable-planning/components/MessageStepsCard";
import { ScrollToBottomButton } from "@/roundtable-planning/components/ScrollToBottomButton";
import { useAutoScroll } from "@/roundtable-planning/hooks/useAutoScroll";
import { useDialogueSpeedMetrics } from "@/roundtable-planning/hooks/useDialogueSpeedMetrics";
import type { InteractiveMessage } from "@/roundtable-planning/hooks/useStep1Intent";
import { useDesensitizeSubtree } from "@/roundtable-planning/lib/use-desensitize-subtree";
import { splitInlineReasoning } from "@/roundtable-planning/lib/reasoning";
import { splitIntentReadyBlock } from "@/roundtable-planning/lib/roundtable-constants";
import type {
ClarificationPayload,
} from "@/roundtable-planning/api/multi-agent";
import type { IntentSummary } from "@/roundtable-planning/api/intent";
export interface Step1PanelProps {
// ─── State ────────────────────────────────────────────────────
/**
* 头部左侧自定义内容(深链 taskId 模式:用「策划流程」小图取代默认标题)。
* 不传 → 显示默认「任务意图理解 (人机问答)」标题。右侧「问答轮次」始终保留。
*/
headerLeftSlot?: React.ReactNode;
interactiveMessages: InteractiveMessage[];
intentThreadId: string | null;
intentReady: object | null;
isIntentSending: boolean;
pendingIntentClarificationMsgId: number | null;
intentClarificationSelections: Map<string, IntentClarificationSelection>;
// ─── Setters / Handlers ──────────────────────────────────────
setIntentClarificationSelections: React.Dispatch<
React.SetStateAction<Map<string, IntentClarificationSelection>>
>;
onSendMessage: (text: string, files?: File[]) => void;
onStopIntent: () => void;
onSkipQuestion: () => void;
onFollowUp: () => void;
onEnterRoundtable: () => void;
onManualSave: () => void;
onTriggerToast: (msg: string) => void;
submitIntentClarifications: (
msgId: number,
clarifications: ClarificationPayload[],
overrideByKey?: Record<string, IntentClarificationSelection>,
) => void;
}
export function Step1Panel(props: Step1PanelProps) {
const {
headerLeftSlot,
interactiveMessages,
intentThreadId,
intentReady,
isIntentSending,
pendingIntentClarificationMsgId,
intentClarificationSelections,
setIntentClarificationSelections,
onSendMessage,
onStopIntent,
onSkipQuestion,
onFollowUp,
onEnterRoundtable,
onManualSave,
onTriggerToast,
submitIntentClarifications,
} = props;
const step1ScrollRef = useRef<HTMLDivElement>(null);
const { atBottom: step1AtBottom, scrollToBottom: scrollStep1ToBottom } =
useAutoScroll(step1ScrollRef, [interactiveMessages]);
// 「回答速度指示器」—— 与主页面共用全局开关 streamSpeedMeterEnabled。
const [localSettings] = useLocalSettings();
const speedMeterEnabled = localSettings.display.streamSpeedMeterEnabled;
const messageMetrics = useDialogueSpeedMetrics(interactiveMessages);
// 输入框完全是本地状态 —— 提到 Page 层会导致每次打字都重渲整页。
const [inputText, setInputText] = useState<string>("");
// 待发送的本地附件(点发送时连同文本一起上传)。
const [attachedFiles, setAttachedFiles] = useState<File[]>([]);
const fileInputRef = useRef<HTMLInputElement>(null);
const charactersLeft = inputText.length;
const handlePickFiles = (e: React.ChangeEvent<HTMLInputElement>) => {
const picked = Array.from(e.target.files ?? []);
if (picked.length > 0) {
// 去重(按 名称+大小),追加到已选列表。
setAttachedFiles((prev) => {
const seen = new Set(prev.map((f) => `${f.name}:${f.size}`));
return [...prev, ...picked.filter((f) => !seen.has(`${f.name}:${f.size}`))];
});
}
// 清空 input 值,允许再次选同名文件。
e.target.value = "";
};
const removeAttachedFile = (idx: number) => {
setAttachedFiles((prev) => prev.filter((_, i) => i !== idx));
};
const handleSend = () => {
if (!inputText.trim() && attachedFiles.length === 0) return;
onSendMessage(inputText, attachedFiles.length > 0 ? attachedFiles : undefined);
setInputText("");
setAttachedFiles([]);
};
// 顶部标题栏整片脱敏(消息列表正文在下方,不在此容器内,保持原文)。
const headerDzRef = useDesensitizeSubtree<HTMLDivElement>();
return (
<div className="flex-1 flex flex-col min-h-0">
{/* Dialogue Header */}
<div ref={headerDzRef} className="shrink-0 px-6 py-4.5 border-b border-slate-100 flex items-center justify-between gap-3 bg-slate-50/50">
{headerLeftSlot ?? (
<div className="flex items-center gap-2">
<MessageSquare className="w-4.5 h-4.5 text-primary" strokeWidth={2.5} />
<h3 className="text-sm font-extrabold text-slate-900">
任务意图理解 (人机问答)
</h3>
</div>
)}
<span className="shrink-0 text-[11px] font-bold text-slate-400 bg-white border px-2 py-0.5 rounded-md">
问答轮次:{interactiveMessages.filter((m) => m.sender === "user").length} 轮
</span>
</div>
{/* Chat list */}
<div className="relative flex-1 min-h-0 flex flex-col font-normal">
<div
ref={step1ScrollRef}
className="flex-1 min-h-0 overflow-y-auto p-6 space-y-4 bg-white"
>
{interactiveMessages.map((msg) => (
<Step1Message
key={msg.id}
msg={msg}
metric={speedMeterEnabled ? messageMetrics.get(msg.id) : undefined}
intentReady={intentReady}
pendingIntentClarificationMsgId={pendingIntentClarificationMsgId}
intentClarificationSelections={intentClarificationSelections}
setIntentClarificationSelections={setIntentClarificationSelections}
isIntentSending={isIntentSending}
submitIntentClarifications={submitIntentClarifications}
/>
))}
</div>
{!step1AtBottom && <ScrollToBottomButton onClick={scrollStep1ToBottom} />}
</div>
{/* Bottom input area */}
<div className="shrink-0 p-4 border-t border-slate-100 bg-[#fcfcfd]">
<div className="relative border border-slate-200 focus-within:border-primary focus-within:ring-2 focus-within:ring-[var(--brand-200)]/50 transition-all rounded-xl overflow-hidden bg-white px-3 py-2.5">
{/* 已选附件预览(点发送时随消息上传) */}
{attachedFiles.length > 0 && (
<div className="flex flex-wrap gap-1.5 pb-2 mb-2 border-b border-slate-100">
{attachedFiles.map((file, idx) => (
<span
key={`${file.name}-${file.size}-${idx}`}
className="inline-flex items-center gap-1.5 bg-slate-50 border border-slate-200 rounded-lg pl-2 pr-1 py-1 text-[11px] text-slate-600 max-w-[200px]"
>
<FileText className="w-3 h-3 shrink-0 text-primary" />
<span className="truncate font-medium" title={file.name}>
{file.name}
</span>
<span className="shrink-0 text-slate-400">
{formatFileSize(file.size)}
</span>
<button
type="button"
onClick={() => removeAttachedFile(idx)}
className="shrink-0 p-0.5 rounded hover:bg-slate-200 text-slate-400 hover:text-slate-600 transition"
title="移除"
>
<X className="w-3 h-3" />
</button>
</span>
))}
</div>
)}
<AutoGrowTextarea
id="input-text-area"
value={inputText}
onChange={(e) => setInputText(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
handleSend();
}
}}
placeholder={
pendingIntentClarificationMsgId
? "也可在此输入自定义回答 (Enter 发送 / Shift+Enter 换行)"
: "请输入补充信息 / 回答问题 / 继续澄清 (Enter 发送 / Shift+Enter 换行)"
}
className="w-full text-xs text-slate-700 placeholder:text-slate-400 min-h-[48px] max-h-80 focus:outline-none leading-relaxed font-normal"
maxHeight={320}
maxLength={500}
/>
<div className="flex items-center justify-between border-t border-slate-50 pt-2 text-[#94a3b8]">
<div className="flex items-center gap-1.5">
<button
onClick={() => onTriggerToast("😄 表情包功能仍在微调状态(仅供演示)")}
className="p-1 hover:text-primary hover:bg-slate-50 rounded transition"
>
<Smile className="w-4 h-4" />
</button>
<input
ref={fileInputRef}
type="file"
multiple
className="hidden"
onChange={handlePickFiles}
/>
<button
type="button"
onClick={() => fileInputRef.current?.click()}
title="上传参考文件(智能体将读取文件内容辅助理解任务)"
className="p-1 hover:text-primary hover:bg-slate-50 rounded transition"
>
<Paperclip className="w-4 h-4" />
</button>
</div>
<span className="text-[10px] font-mono text-slate-400">{charactersLeft}/500</span>
</div>
</div>
<div className="flex items-center justify-between mt-3">
<div className="flex items-center gap-2">
<button
id="send-message-btn"
onClick={handleSend}
disabled={isIntentSending || !intentThreadId}
className="bg-primary text-white hover:bg-[var(--brand-900)] disabled:bg-slate-300 disabled:cursor-not-allowed text-xs font-bold px-4 py-2.5 rounded-xl flex items-center gap-1.5 transition-all shadow-[0_2px_8px_rgba(245,34,45,0.15)] active:scale-95"
>
{isIntentSending ? <Loader2 className="w-3 h-3 animate-spin" /> : <Send className="w-3 h-3" />}
{isIntentSending ? "发送中" : "发送"}
</button>
{isIntentSending && (
<button
id="pause-intent-btn"
type="button"
onClick={onStopIntent}
className="bg-amber-100 hover:bg-amber-200 text-amber-800 text-xs font-bold px-3 py-2.5 rounded-xl flex items-center gap-1.5 transition border border-amber-200/40 shadow-sm active:scale-95"
>
<Pause className="w-3 h-3" />
暂停
</button>
)}
<button
id="suggest-followup-btn"
onClick={onFollowUp}
className="bg-white hover:bg-slate-50 border border-slate-200 text-slate-700 text-xs font-bold px-3 py-2.5 rounded-xl flex items-center gap-1.5 transition"
>
<Repeat className="w-3 h-3 text-slate-500" />
继续追问
</button>
<button
id="skip-question-btn"
onClick={onSkipQuestion}
className="bg-white hover:bg-slate-50 border border-slate-200 text-slate-700 text-xs font-bold px-3 py-2.5 rounded-xl flex items-center gap-1.5 transition"
>
<X className="w-3 h-3 text-slate-500" strokeWidth={2.5} />
跳过此项
</button>
<button
id="enter-roundtable-btn"
onClick={onEnterRoundtable}
disabled={!intentReady}
title={intentReady ? undefined : "请先完成任务意图澄清"}
className={`text-xs font-black px-4 py-2.5 rounded-xl transition flex items-center gap-1.5 active:scale-95 shadow-md shadow-emerald-500/10 ${
intentReady
? "bg-emerald-600 hover:bg-emerald-700 text-white cursor-pointer"
: "bg-emerald-600/40 text-white cursor-not-allowed"
}`}
>
<Sparkles className="w-3.5 h-3.5 text-emerald-100" />
进入多智能体研讨 &gt;
</button>
</div>
<button
id="save-draft-btn"
onClick={onManualSave}
className="bg-white hover:bg-slate-50 border border-slate-200 text-slate-700 text-xs font-bold px-3 py-2.5 rounded-xl flex items-center gap-1.5 transition"
>
<Save className="w-3 h-3 text-slate-500" />
保存草稿
</button>
</div>
</div>
</div>
);
}
/**
* 单条 Step 1 消息。
*
* 拆成独立函数避免主 panel 里大量嵌套 JSX。三种正文形态:
* - 流式中、还没首字节 → MessageLoadingPlaceholder
* - agent 消息 → splitIntentReadyBlock 拆出前 / 摘要 / 后,分别渲染
* + IntentClarificationCard(若待澄清)
* - user 消息 → 纯文本
*/
interface Step1MessageProps {
msg: InteractiveMessage;
/**
* 本条气泡的「回答速度」度量(tok/s + 时长)。仅对流式过的智能体发言有值;
* 由调用方按全局开关 streamSpeedMeterEnabled 决定是否传入(关则传 undefined)。
*/
metric?: MessageMetric;
intentReady: object | null;
pendingIntentClarificationMsgId: number | null;
intentClarificationSelections: Map<string, IntentClarificationSelection>;
setIntentClarificationSelections: React.Dispatch<
React.SetStateAction<Map<string, IntentClarificationSelection>>
>;
isIntentSending: boolean;
submitIntentClarifications: (
msgId: number,
clarifications: ClarificationPayload[],
overrideByKey?: Record<string, IntentClarificationSelection>,
) => void;
}
function Step1Message({
msg,
metric,
intentReady,
pendingIntentClarificationMsgId,
intentClarificationSelections,
setIntentClarificationSelections,
isIntentSending,
submitIntentClarifications,
}: Step1MessageProps) {
const isStreaming = msg.streaming === true;
const isAgent = msg.sender !== "user";
// 先把 `<think>...</think>` 抽出来作 reasoning,剩下的正文再走 INTENT_READY 解析。
// 顺序很关键:若先 split INTENT_READY 再抽 think,think 块如果横跨 INTENT_READY
// 标记会导致 JSON 解析失败。
const rawContent = msg.content ?? "";
const { content: thoughtFreeContent, reasoning } = isAgent
? splitInlineReasoning(rawContent)
: { content: rawContent, reasoning: null };
const hasContent = thoughtFreeContent.length > 0;
// 一轮可能有多条澄清问题(任务理解智能体一次问多个)。流式期就逐个灌进来,
// 实时展示「协助过程」;终态再以权威集合覆盖。
const clarifications = msg.clarifications ?? [];
const parts = isAgent
? splitIntentReadyBlock(thoughtFreeContent)
: { before: thoughtFreeContent, summary: null as IntentSummary | null, after: "" };
// 是否展示澄清卡(还没出 summary / 还没整体就绪时)。流式中也展示(只读),
// 终态且该消息为当前待澄清条目时才可交互。
const showClarifications =
isAgent && clarifications.length > 0 && !intentReady && !parts.summary;
// 一轮多个问题才进入「逐题作答 + 合并发送」模式;单问题沿用「点击即发送」。
const multiQuestion = clarifications.length > 1;
const isPending = pendingIntentClarificationMsgId === msg.id;
const clarificationsInteractive = isPending && !isStreaming;
const introText =
clarifications.length === 1 &&
parts.before.trim() === (clarifications[0].question || "").trim()
? ""
: parts.before;
// 主聊天里步骤卡放在「正文之上」(气泡内,header 之下),Step 2 也是这样。
// 流式中默认显示 last tool call + 折叠 "查看其他 N 个步骤";完成后保留卡。
const stepsCard =
isAgent && Array.isArray(msg.steps) && msg.steps.length > 0 ? (
<MessageStepsCard steps={msg.steps} streaming={isStreaming} />
) : null;
// 「思考过程」折叠卡 —— 流式中默认展开,完成后自动延迟收起。
const reasoningBlock =
isAgent && reasoning ? (
<ReasoningBlock streaming={isStreaming}>{reasoning}</ReasoningBlock>
) : null;
return (
<MessageBubble
avatar={
msg.sender === "user" ? (
<Man1Avatar size="h-9 w-9 shrink-0" />
) : (
<RobotAvatar bg="bg-[var(--brand-200)]/50" size="h-9 w-9 shrink-0" />
)
}
senderName={msg.senderName}
senderNameClassName={msg.sender === "user" ? "text-primary" : undefined}
badge={isStreaming ? msg.phase : undefined}
time={msg.time}
>
{stepsCard}
{reasoningBlock}
{isStreaming && !hasContent ? (
<MessageLoadingPlaceholder label={msg.phase} />
) : isAgent ? (
<div className="roundtable-chat-message text-slate-700 font-medium break-words space-y-2">
{introText && <MarkdownContent>{introText}</MarkdownContent>}
{parts.summary && <IntentReadySummaryCard summary={parts.summary} />}
{/*
parts.after 是模型违反 SOUL §0「硬规则 3」在 [INTENT_READY] 块后
继续输出的内容(典型:"那么我先帮你列一下大纲……")。后端 intent.py
的终态帧已经把 content 截断到 marker 结尾,但流式期间 LangGraph
messages-tuple 还是会把那段废话逐 token 推过来——故意在 UI 层
把它丢弃,让用户看到的就是"复述 + 摘要卡",干净结束。
*/}
{isStreaming && <StreamingCursor />}
{showClarifications && (
<div className="space-y-2">
{clarifications.map((clar, index) => {
const key = clarificationKey(msg.id, clar.id, index);
const selection =
intentClarificationSelections.get(key) ?? {
selectedIds: [],
custom: "",
};
return (
<IntentClarificationCard
key={key}
payload={clar}
fallbackContent={clar.question || parts.before || undefined}
selection={selection}
// 单问题:沿用原交互(单选点击即发送 / 多选 / 自定义走卡片自己的按钮)。
// 多问题:才 defer —— 逐题只记录选择,由下方一个合并按钮统一发送。
deferSubmit={multiQuestion}
onSelectionChange={(next) => {
setIntentClarificationSelections((prev) => {
const map = new Map(prev);
map.set(key, next);
return map;
});
}}
disabled={!clarificationsInteractive}
submitting={isIntentSending && isPending}
onSubmit={(override) =>
submitIntentClarifications(
msg.id,
clarifications,
// 单题单选「点击即发送」时选择还没进 state map,把即时值
// 按 key 传进去直接用。
override ? { [key]: override } : undefined,
)
}
/>
);
})}
{/* 合并提交按钮仅多问题时出现;单问题点选项即发送,无需此按钮。 */}
{multiQuestion && clarificationsInteractive && (
<div className="flex items-center justify-between gap-2 pt-0.5">
<span className="text-[10px] text-slate-400">
共 {clarifications.length} 个问题,可逐个作答后一并发送
</span>
<Button
type="button"
size="sm"
disabled={isIntentSending}
onClick={() => submitIntentClarifications(msg.id, clarifications)}
className="h-8 rounded-xl px-4 text-xs font-bold"
>
{isIntentSending ? "发送中…" : "发送全部回答"}
</Button>
</div>
)}
</div>
)}
</div>
) : (
<div className="space-y-2">
{msg.files && msg.files.length > 0 && (
<div className="flex flex-wrap gap-1.5">
{msg.files.map((file, i) => (
<span
key={`${file.filename}-${i}`}
className="inline-flex items-center gap-1.5 bg-white/70 border border-slate-200 rounded-lg px-2 py-1 text-[11px] text-slate-600 max-w-[200px]"
>
<FileText className="w-3 h-3 shrink-0 text-primary" />
<span className="truncate font-medium" title={file.filename}>
{file.filename}
</span>
<span className="shrink-0 text-slate-400">
{formatFileSize(file.size)}
</span>
</span>
))}
</div>
)}
{msg.content && (
<div className="roundtable-chat-message text-slate-700 font-medium whitespace-pre-wrap break-words">
{msg.content}
</div>
)}
</div>
)}
{metric && <DialogueSpeedMeter metric={metric} />}
</MessageBubble>
);
}
/** [INTENT_READY] 标记块解析出 IntentSummary 后的绿色摘要卡。 */
function IntentReadySummaryCard({ summary }: { summary: IntentSummary }) {
return (
<div className="mt-1 border border-emerald-200 bg-emerald-50/50 rounded-xl p-3 space-y-2">
<div className="flex items-center gap-1.5">
<CheckCircle className="w-3.5 h-3.5 text-emerald-600" />
<span className="text-[10.5px] font-black text-emerald-700 tracking-wide">
任务意图已明确
</span>
</div>
<div className="space-y-1">
<span className="text-[10px] font-bold text-slate-500 uppercase tracking-wider">核心目标</span>
<p className="text-[11.5px] text-slate-800 leading-relaxed">{summary.objective}</p>
</div>
{summary.constraints?.length > 0 && (
<div className="space-y-1">
<span className="text-[10px] font-bold text-slate-500 uppercase tracking-wider">约束条件</span>
<ul className="list-disc pl-4 space-y-0.5 text-[11px] text-slate-700">
{summary.constraints.map((c, i) => (
<li key={i} className="leading-snug">{c}</li>
))}
</ul>
</div>
)}
{summary.assumptions && summary.assumptions.length > 0 && (
<div className="space-y-1">
<span className="text-[10px] font-bold text-slate-500 uppercase tracking-wider">关键假设</span>
<ul className="list-disc pl-4 space-y-0.5 text-[11px] text-slate-700">
{summary.assumptions.map((a, i) => (
<li key={i} className="leading-snug">{a}</li>
))}
</ul>
</div>
)}
</div>
);
}