import React, { useCallback, useEffect, useMemo, useState } from "react"; import ReactMarkdown from "react-markdown"; import remarkGfm from "remark-gfm"; import { CheckCircle, ChevronDown, ChevronRight, Download, Eye, FileText, Loader2, Printer, RefreshCw, Sparkles, } from "lucide-react"; import { useArtifacts } from "@/components/workspace/artifacts"; import { buildArtifactDownloadUrl, listSessionArtifacts, type SessionArtifactFile, type ThreadIdMap, } from "@/roundtable-planning/api/multi-agent"; import { ArtifactPreviewModal } from "@/roundtable-planning/components/ArtifactPreviewModal"; import { markdownComponents } from "@/roundtable-planning/components/markdown-components"; import { Step3ReportMode, type ModelOption, } from "@/roundtable-planning/components/Step3ReportMode"; import type { DraftStep3Snapshot } from "@/roundtable-planning/api/drafts"; import type { ReportIntent } from "@/roundtable-planning/hooks/useStep3Report"; /** * Text-ish files we render in an in-app preview modal. Other types (pdf, * images, html) keep the original window.open behaviour so the browser's * native viewer handles them. */ function shouldPreviewInModal(file: { name: string; mimeType: string | null }): boolean { const mime = file.mimeType ?? ""; if (mime === "text/markdown" || mime === "text/plain" || mime === "text/csv" || mime === "application/json") { return true; } if (mime.startsWith("text/")) return true; return /\.(md|markdown|txt|json|csv|log|yml|yaml|xml)$/i.test(file.name); } interface SeatDelivery { /** Display name of the seat (e.g. "情报收集"). */ sender: string; /** Avatar color hint inherited from the dialogue card. Unused for layout right now. */ avatarType: string; /** The seat's final markdown delivery from Step 2. */ content: string; } interface HighFidelityReportProps { threadIds: ThreadIdMap | null; coordinatorName: string | null; /** The most recent leader-agent text — rendered as the final consensus. */ consensusText: string; /** True once leader.dispatched === [] was observed (natural convergence). */ hasConsensus: boolean; /** Each sub-agent's final delivery, filtered out of step2 dialogues. */ seatDeliveries: SeatDelivery[]; /** lowercase agent name → display name (e.g. "roundtable-intelligence" → "情报收集"). */ seatNameMap: Record; /** Step 1 整理出的结构化意图 —— 喂给「结果绘制」的方案可视化智能体。 */ intentReady: ReportIntent | null; /** 当前推理模型 —— 跑可视化智能体用。 */ selectedModel: string; /** 可选模型列表 + 加载态 + 切换器 —— 结果绘制右侧的模型选择(对齐第 2 步)。 */ availableModels: ReadonlyArray; modelsLoading: boolean; setSelectedModel: (model: string) => void; /** 草稿里已存的上次绘制结果 —— 透传给「结果绘制」恢复展示。 */ savedReport?: DraftStep3Snapshot | null; /** 一次绘制完成时回调,把结果交给上层存进草稿 step3。 */ onReportSaved?: (snapshot: DraftStep3Snapshot) => void; /** Resets state and navigates back to Step 1. */ onReset: () => void; } interface SeatArtifacts { agentName: string; displayName: string; threadId: string; files: SessionArtifactFile[]; loading: boolean; error: string | null; } function formatBytes(n: number): string { if (n < 1024) return `${n} B`; if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`; if (n < 1024 * 1024 * 1024) return `${(n / (1024 * 1024)).toFixed(1)} MB`; return `${(n / (1024 * 1024 * 1024)).toFixed(2)} GB`; } function formatGeneratedAt(d: Date): string { const pad = (n: number) => n.toString().padStart(2, "0"); return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`; } export const HighFidelityReport: React.FC = ({ threadIds, coordinatorName, consensusText, hasConsensus, seatDeliveries, seatNameMap, intentReady, selectedModel, availableModels, modelsLoading, setSelectedModel, savedReport, onReportSaved, onReset, }) => { // 「结果绘制」模式:把现有报告内容收起到左栏,右侧由方案可视化智能体绘制图表 HTML。 const [drawMode, setDrawMode] = useState(false); // 进入第三步即关闭并清空第二步遗留的沙箱(artifacts 面板全局共享,第二步打开后 // 不会自动关)。点「结果绘制」后 Step3ReportMode 会按需开自己的沙箱,互不串扰。 const { deselect: deselectArtifact } = useArtifacts(); useEffect(() => { deselectArtifact(); }, [deselectArtifact]); // Build the per-seat list (excludes the coordinator). useMemo so the file // fetch effect doesn't re-fire on every parent render. const seatThreadEntries = useMemo(() => { if (!threadIds) return [] as Array<{ agentName: string; threadId: string; displayName: string }>; return Object.entries(threadIds) .filter(([name]) => !coordinatorName || name !== coordinatorName) .map(([agentName, threadId]) => ({ agentName, threadId, displayName: seatNameMap[agentName.toLowerCase()] ?? agentName, })); }, [threadIds, coordinatorName, seatNameMap]); // Map sender display name → its delivery content for the accordion rows. // Built once per seatDeliveries change; later entries with the same sender // win so the *latest* delivery wins. const deliveryByDisplay = useMemo(() => { const m = new Map(); for (const d of seatDeliveries) m.set(d.sender, d.content); return m; }, [seatDeliveries]); const [artifactsBySeat, setArtifactsBySeat] = useState([]); const [expandedSeats, setExpandedSeats] = useState>(new Set()); const [reloadKey, setReloadKey] = useState(0); // Active preview target — non-null means the modal is open. We carry the // owning threadId so the modal can fetch + build download URLs without // needing a second prop drill. const [previewing, setPreviewing] = useState<{ threadId: string; file: SessionArtifactFile } | null>(null); const generatedAt = useMemo(() => formatGeneratedAt(new Date()), []); // Fetch artifact listings for every seat thread in parallel. Re-runs when // the user clicks "刷新文件清单" (reloadKey ticks) or when the thread set // changes (rare — only on a true re-init). useEffect(() => { if (seatThreadEntries.length === 0) { setArtifactsBySeat([]); return; } const initial: SeatArtifacts[] = seatThreadEntries.map((s) => ({ ...s, files: [], loading: true, error: null, })); setArtifactsBySeat(initial); const abort = new AbortController(); let cancelled = false; (async () => { const results = await Promise.all( seatThreadEntries.map(async (seat) => { try { const res = await listSessionArtifacts(seat.threadId, { signal: abort.signal }); return { seat, files: res.files, error: null as string | null }; } catch (err) { if ((err as Error).name === "AbortError") { return { seat, files: [] as SessionArtifactFile[], error: null }; } return { seat, files: [] as SessionArtifactFile[], error: (err as Error).message }; } }), ); if (cancelled) return; setArtifactsBySeat( results.map(({ seat, files, error }) => ({ ...seat, files, loading: false, error, })), ); })(); return () => { cancelled = true; abort.abort(); }; }, [seatThreadEntries, reloadKey]); const totalFileCount = useMemo( () => artifactsBySeat.reduce((sum, s) => sum + s.files.length, 0), [artifactsBySeat], ); const toggleSeat = useCallback((key: string) => { setExpandedSeats((prev) => { const next = new Set(prev); if (next.has(key)) next.delete(key); else next.add(key); return next; }); }, []); const handlePreview = useCallback( (threadId: string, file: SessionArtifactFile) => { // Text-ish artifacts (markdown / txt / json / csv / yaml / ...) open // in our in-app modal so the user can read the content without leaving // the planning page. Binary or active content (pdf / png / html) still // hands off to the browser's native viewer via the original tab. if (shouldPreviewInModal({ name: file.name, mimeType: file.mimeType })) { setPreviewing({ threadId, file }); return; } if (typeof window !== "undefined") { const url = buildArtifactDownloadUrl(threadId, file.path); window.open(url, "_blank", "noopener,noreferrer"); } }, [], ); const handleDownload = useCallback( (threadId: string, file: SessionArtifactFile) => { const url = buildArtifactDownloadUrl(threadId, file.path, { download: true }); if (typeof window !== "undefined") { window.open(url, "_blank", "noopener,noreferrer"); } }, [], ); if (drawMode) { return ( setDrawMode(false)} /> ); } return (
{/* Header */}

最终方案展示

{hasConsensus && ( ● 已达成共识 )} 生成时间:{generatedAt}
{/* Section 1: Coordinator consensus conclusion */}

总控最终结论

{consensusText ? (
{consensusText}
) : (

暂无总控结论。返回 Step 2 完成至少一轮研讨后再查看此页。

)}
{/* Section 2: Per-seat deliveries (collapsible) */}

各席位最终交付 {seatDeliveries.length}

{seatDeliveries.length === 0 ? (

本次研讨尚未产生子智能体交付。Leader 派活并收到子智能体回复后,该区块会自动填充。

) : (
{seatDeliveries.map((seat, idx) => { const key = `${seat.sender}-${idx}`; const expanded = expandedSeats.has(key); return (
{expanded && (
{seat.content || "(空)"}
)}
); })}
)}
{/* Section 3: Generated files per seat —— 各席位产出的 md 文件,点击预览弹窗查看内容 */}

生成的报告文件 {totalFileCount}

{artifactsBySeat.length === 0 ? (

尚未初始化席位线程,无法列出文件。

) : (
{artifactsBySeat.map((seat) => (
{seat.displayName} {seat.loading ? "加载中…" : `${seat.files.length} 个文件`}
{seat.loading ? (
正在查询 outputs 目录…
) : seat.error ? (
读取失败:{seat.error}
) : seat.files.length === 0 ? (
该席位未产生输出文件
) : (
    {seat.files.map((f) => (
  • {f.name}
    {formatBytes(f.sizeBytes)}
  • ))}
)}
))}
)}
{/* Footer */}
如需重新立项,可清空当前研讨,回到任务理解阶段重新起草。
{previewing && ( setPreviewing(null)} /> )}
); };