Files
deerflow-code/frontend-web/src/pages/deep-research/DeepResearchWorkbench.tsx
T

4543 lines
203 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use client";
import {
useOrdinaryKnowledgeRetrievalSettings,
usePageDescriptionsSettings,
} from "@/core/system-settings/hooks";
import type { PageHeaderDescription } from "@/core/system-settings/api";
import { normalizeKnowledgeRetrievalMode, resolveKnowledgeRetrievalRequestContext, resolveSmartKnowledgeRetrievalAvailability, type KnowledgeRetrievalMode } from "@/core/threads/knowledge-retrieval-mode";
import { LlmWikiKnowledgeSelector } from "@/components/workspace/llmwiki-knowledge-selector";
/**
* Conversation-first Deep Research workbench (AI-writing-style, third round).
*
* Collection stage = a real collector-agent conversation on the session's
* runtime LangGraph thread (reuses the normal chat MessageList + streaming
* machinery). The composer is the AI-writing white-card PromptInput suite
* (model row + textarea + status-aware submit). When a turn ends without a
* pending clarification, a virtual approval message injects the report-config
* card into the conversation flow (like AI writing's intent-confirmation
* form); the writing job then harvests the conversation's materials
* then 「开始撰写」 reuses ordinary Q&A writing mode: the collector LangGraph
* thread calls `deep_research_report` in-process (custom events, no job store).
* The report streams into the REAL workspace sandbox on the right
* (stub-thread mechanism — see useReportSandbox): streaming shows
* the code view auto-scrolling, and the sandbox auto-switches to the rendered
* Markdown preview once writing finishes.
*
* Legacy sessions (created before the chat flow, or via the 经典模式 rollback)
* keep the original auto-start timeline path and share the same sandbox rail.
*/
import { memo, useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { useSearchParams } from "react-router-dom";
import type { Message } from "@langchain/langgraph-sdk";
import ReactMarkdown from "react-markdown";
import { Select as TSelect } from "tdesign-react";
import {
AlertCircle,
Bot,
CheckCircle2,
ChevronRight,
CircleStop,
ExternalLink,
FileCode2,
FileDown,
FileText,
FileType2,
FolderOpen,
ImagePlus,
Loader2,
MessageSquareText,
PanelRightOpen,
RotateCcw,
Sparkles,
Telescope,
Trash2,
UserRound,
} from "lucide-react";
import { toast } from "sonner";
import {
PromptInput,
PromptInputFooter,
PromptInputSubmit,
PromptInputTextarea,
} from "@/components/ai-elements/prompt-input";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { MessageList } from "@/components/workspace/messages";
import { ThreadContext } from "@/components/workspace/messages/context";
import { ArtifactFileList, ArtifactsProvider } from "@/components/workspace/artifacts";
import {
DEEP_RESEARCH_REPORT_REWRITE_REQUESTED_EVENT,
DOCUMENT_REWRITE_UNDONE_EVENT,
DocumentRewritePresentationProvider,
useDocumentRewritePresentation,
} from "@/core/document-rewrite/context";
import { ScrollArea } from "@/components/ui/scroll-area";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Textarea } from "@/components/ui/textarea";
import { SubtasksProvider } from "@/core/tasks/context";
import { useLocalSettings } from "@/core/settings/hooks";
import { useModels } from "@/core/models/hooks";
import type { DocumentRewriteStreamEvent, DocumentRewriteSummary } from "@/open-canvas/api/rewrite";
import { useDocumentRewrite } from "@/open-canvas/hooks/useDocumentRewrite";
import {
stopActiveThreadBeforeClarificationReply,
stopThreadRun,
useThreadStream,
} from "@/core/threads/hooks";
import {
clearResearchReportStream,
composeResearchDisplayMessages,
useResearchReportStream,
} from "@/core/threads/use-research-report-stream";
import {
collectorWriteSucceeded,
inlineWriteFinished,
overlayLiveSession,
RESEARCH_REPORT_FILE,
threadHasReportArtifact,
} from "./report-file-card";
import {
extractContentFromMessage,
extractReasoningContentFromMessage,
extractToolResultPayload,
hasOnlyInternalToolCalls,
hasVisibleToolCalls,
} from "@/core/messages/utils";
import { normalizeSearchResults } from "@/core/messages/search-results";
import { downloadMarkdownAsDocx } from "@/core/scheduled-tasks/markdown-docx";
import {
type DeepResearchSession,
type DeepResearchSource,
type FollowUpRewritePreview,
type ProgressEvent,
type ResearchMode,
type ResearchTone,
cancelFullResearchReportRewrite,
createResearchReportVariant,
exportReport,
getSession as getResearchSession,
getLatestFullResearchReportRewrite,
joinFullResearchReportRewrite,
streamResearchMessage,
streamResearchRewrite,
streamFullResearchReportRewrite,
streamJob,
patchCachedResearchSession,
useCapabilities,
useResearchActions,
useResearchMessages,
useResearchReportVariants,
useResearchSession,
useResearchSessions,
useResearchSources,
} from "@/strategy-components/api/deep-research";
import {
type ReportStructureMode,
composeCollectorQueryWithDirections,
normalizeRetrievalDirections,
normalizeRetrievalSkills,
useReportStructures,
} from "@/strategy-components/api/report-structures";
import {
AdvancedResearchOptions,
DEFAULT_ADVANCED_OPTIONS,
advancedOptionsFromConfig,
buildReportCardConfig,
ReportConfigCard,
ReportOutlineEditor,
} from "./ReportConfigCard";
import { ResearchSandboxPanel } from "./ResearchSandboxPanel";
import { WorkflowConfigButton } from "./WorkflowConfigDialog";
import { REPORT_OUTPUT_PATH, useReportSandbox } from "./useReportSandbox";
import {
PLANNER_AGENT_ID,
OUTLINE_PLANNER_OPTIONS,
buildCollectAfterPlanPrompt,
buildStartSearchAfterTermsPrompt,
hasCollectAfterPlanTurn,
hasCollectionSummary,
hasRetrievalAfterPlan,
hasRetrievalToolTurn,
hasStartSearchAfterTermsTurn,
isCollectAfterPlanPrompt,
isStartSearchAfterTermsPrompt,
normalizeOutlinePlanner,
outlineFromLatestAssistant,
shouldAutoCollectAfterPlan,
shouldFinishCollection,
shouldNudgeSearchAfterTerms,
} from "./outline-plan";
const WORKBENCH_WRITE_PROMPT_MARKER = "请立即开始撰写研究报告";
function isWorkbenchWritePrompt(text: string): boolean {
return text.includes(WORKBENCH_WRITE_PROMPT_MARKER);
}
/** Model echo of the hidden workbench write trigger — never show in the feed. */
function isWorkbenchWriteEcho(text: string): boolean {
const normalized = text.trim();
if (!normalized) return false;
if (isWorkbenchWritePrompt(normalized)) return true;
return normalized.length <= 120 && /开始撰写/.test(normalized) && !/已完成|完成撰写/.test(normalized);
}
const COLLECTOR_AGENT_ID = "deep-research-collector";
/** TDesign Select sentinel: do not send a per-session model override. */
const DEFAULT_MODEL_VALUE = "__deep_research_default_model__";
const DEFAULT_AVAILABLE_MODES: ResearchMode[] = ["basic", "quick", "detailed", "deep", "multi_agent"];
// Route completed-report input by intent before opening its SSE stream. The
// backend validates the same target again; this client guard only selects the
// dedicated writing endpoint instead of sending an obvious edit to report Q&A.
const REPORT_REWRITE_ACTION_RE = /(?:重新\s*(?:生成|撰写|写)|再\s*(?:生成|撰写|写)|重写|改写|修改|润色|优化|重述|更新|rewrite|revise)/i;
const REPORT_REWRITE_TARGET_RE = /(?:第\s*[0-9一二三四五六七八九十]+\s*(?:段落?|部分|节|章节|section)|摘要|引言|结论|建议|全文|整篇|整个报告|全篇|full report|entire report)/i;
function isExplicitReportRewriteInstruction(text: string): boolean {
return REPORT_REWRITE_ACTION_RE.test(text) && REPORT_REWRITE_TARGET_RE.test(text);
}
const MODE_LABELS: Record<ResearchMode, string> = {
basic: "基础",
quick: "快速",
detailed: "详细",
deep: "深度",
multi_agent: "多智能体",
};
const PHASE_LABELS: Record<string, string> = {
initializing: "准备研究环境",
planning: "规划研究问题",
collecting: "收集可信资料",
curating: "筛选与核验来源",
compressing: "整理研究上下文",
deepening: "补充关键问题",
writing: "写入研究报告",
reviewing: "核对报告结论",
summarizing: "生成报告摘要",
illustrating: "生成报告配图",
exporting: "整理交付文件",
done: "研究完成",
};
const STATUS_LABELS: Record<DeepResearchSession["status"], string> = {
draft: "待开始",
collecting: "收集中",
awaiting_report: "待撰写",
running: "进行中",
awaiting_input: "等待确认",
completed: "已完成",
failed: "失败",
cancelled: "已取消",
};
type WorkbenchRun = {
jobId: string | null;
events: ProgressEvent[];
phase: string;
planText: string;
planReasoning: string;
/** Live-only model thinking while report Markdown is being streamed. */
reportThinking: string;
/** Live-only model thinking while the post-report digest is being written. */
summaryThinking: string;
report: string;
reportTargets: Record<string, { content: string; version: number }>;
reportVersion: number;
summaryText: string;
error: string | null;
};
type FollowUpStreamState = {
content: string;
rewrite: FollowUpRewritePreview | null;
};
/**
* A structurally regenerated report is a durable child file rendered inside
* its parent's conversation. It never becomes a separate history-rail item.
*/
type InlineGeneratedReport = {
parentSessionId: string;
session: DeepResearchSession;
/** Frozen visible trace for the report that was already in the conversation. */
parentRun: WorkbenchRun;
};
const EMPTY_RUN: WorkbenchRun = {
jobId: null,
events: [],
phase: "initializing",
planText: "",
planReasoning: "",
reportThinking: "",
summaryThinking: "",
report: "",
reportTargets: {},
reportVersion: 1,
summaryText: "",
error: null,
};
function localWriteJobStartedEvent(jobId: string): ProgressEvent {
return {
seq: 0,
liveId: `write-job-started-local:${jobId}`,
sessionId: "",
jobId,
type: "warning",
phase: "collecting",
payload: {
code: "write_job_started",
message: "写作任务已启动,正在读取已收集材料",
recoverable: true,
},
};
}
function emptyRunForJob(jobId: string): WorkbenchRun {
return {
...EMPTY_RUN,
jobId,
phase: "collecting",
events: [localWriteJobStartedEvent(jobId)],
};
}
function eventKey(event: ProgressEvent): string {
return event.seq > 0
? `seq:${event.seq}`
: `live:${event.liveId ?? `${event.type}:${event.timestamp ?? ""}:${String(event.payload.delta ?? event.payload.summary ?? "")}`}`;
}
function appendReportDelta(current: string, delta: string, offset?: unknown): string {
if (!delta) return current;
if (typeof offset !== "number" || !Number.isFinite(offset) || offset < 0) return current + delta;
if (offset >= current.length) return current + delta;
if (current.slice(offset, offset + delta.length) === delta) return current;
return current.slice(0, offset) + delta;
}
function assembleStreamingReport(targets: Record<string, { content: string; version: number }>): string {
if (targets.report?.content) return targets.report.content;
const parts = Object.entries(targets)
.filter(([, draft]) => draft.content)
.sort(([left], [right]) => {
const rank = (target: string) => target === "introduction" ? -1 : target === "conclusion" ? 10_000 : Number.parseInt(target.replace("section:", ""), 10) || 0;
return rank(left) - rank(right);
})
.map(([target, draft]) => {
if (target === "introduction") return `# 引言\n\n${draft.content}`;
if (target === "conclusion") return `# 结论\n\n${draft.content}`;
if (target.startsWith("section:")) return `## 研究章节 ${Number.parseInt(target.slice("section:".length), 10) + 1}\n\n${draft.content}`;
return draft.content;
});
return parts.join("\n\n");
}
const REPORT_REFUSAL_PATTERN = /(?:无法|不能|未能|不可以).{0,24}?(?:生成|撰写|产出|输出).{0,12}?报告/s;
function isRefusalReportText(value: string): boolean {
const text = value || "";
const compact = text.replace(/\s+/g, "");
// Empty means the writer has not emitted Markdown yet (thinking / connecting).
// Treating that as a refusal opened the sandbox on an error card while the
// model was still working.
if (!compact) return false;
const headings = text.match(/^#{1,6}\s+\S+/gm) ?? [];
// A structured report may discuss evidence gaps. Only treat a short,
// unstructured refusal as “no report”, otherwise the zero-source fallback
// is hidden behind the diagnostic card and looks like writing failed.
if (headings.length >= 2) return false;
return REPORT_REFUSAL_PATTERN.test(compact);
}
function researchExportBaseName(session: DeepResearchSession): string {
const title = (session.title || session.query || "研究报告")
.replace(/[\\/:*?"<>|]/g, "-")
.replace(/\s+/g, " ")
.trim();
return `深度研究-${title.slice(0, 80) || "研究报告"}`;
}
/**
* The history file card is a presentation of the virtual report artifact, so
* use the Markdown H1 as its filename while keeping the real sandbox path
* fixed at report.md. This gives the user a meaningful report-title card
* without changing artifact loading or exporting semantics.
*/
function reportCardDisplayPath(session: DeepResearchSession): string {
const heading = session.reportMarkdown
?.match(/^\s{0,3}#\s+(.+?)\s*#*\s*$/m)?.[1]
?.replace(/\[([^\]]+)\]\([^)]*\)/g, "$1")
.replace(/[\*_`~]/g, "")
.trim();
const title = (heading || session.title || session.query || "")
.replace(/[\\/:*?"<>|]/g, "-")
.replace(/\s+/g, " ")
.trim()
.slice(0, 80);
return `/mnt/user-data/outputs/${title || "report"}.md`;
}
function reportStructureLabel(
session: DeepResearchSession,
structures: { title: string; content: string }[],
): string {
const config = session.config ?? {};
const outline = typeof config.custom_outline === "string"
? config.custom_outline.trim()
: typeof config.customOutline === "string"
? config.customOutline.trim()
: "";
if (!outline) return "默认报告结构";
return structures.find((structure) => structure.content.trim() === outline)?.title ?? "自定义报告结构";
}
function buildResearchWordMarkdown(session: DeepResearchSession, sources: DeepResearchSource[]): string {
const references = sources
.map((source, index) => `${index + 1}. ${source.title || `来源 ${index + 1}`}${source.url ? `\n ${source.url}` : ""}`)
.join("\n");
return [
`> 研究课题:${session.query}\n> 导出时间:${new Date().toLocaleString("zh-CN")}`,
session.reportMarkdown || "",
references ? `## 参考来源\n\n${references}` : "",
].filter(Boolean).join("\n\n");
}
function downloadText(content: string, name: string, mime: string) {
const url = URL.createObjectURL(new Blob([content], { type: mime }));
const anchor = document.createElement("a");
anchor.href = url;
anchor.download = name;
anchor.click();
URL.revokeObjectURL(url);
}
/** A clarification tool call after the last human message is still unanswered. */
function hasPendingClarification(
messages: { id?: string; type?: string; name?: string }[] | undefined,
): boolean {
if (!messages?.length) return false;
let lastHuman = -1;
for (let i = messages.length - 1; i >= 0; i--) {
if (messages[i]?.type === "human") {
lastHuman = i;
break;
}
}
for (let i = lastHuman + 1; i < messages.length; i++) {
const message = messages[i];
if (message && message.type === "tool" && message.name === "ask_clarification") return true;
}
return false;
}
/**
* The chat-entry job harvests tool outputs from the real collector thread.
* Count the same user-visible result shapes here so the report-config card can
* tell the user how many materials have already been collected before a job
* exists (the persisted source list is populated only after writing starts).
*/
function countCollectorMaterials(messages: readonly Message[] | undefined): number {
if (!messages?.length) return 0;
const unique = new Set<string>();
const addCandidate = (candidate: unknown, fallback: string) => {
if (!candidate || typeof candidate !== "object" || Array.isArray(candidate)) return;
const item = candidate as Record<string, unknown>;
const text = (value: unknown) => typeof value === "string" ? value.trim() : "";
const url = text(item.url) || text(item.source_url) || text(item.link);
const id = text(item.id) || text(item.recUuid) || text(item.rec_uuid) || text(item.uuid);
const title = text(item.title) || text(item.name);
const content = text(item.content) || text(item.snippet) || text(item.content_preview) || text(item.text);
if (!url && !id && !title && !content) return;
unique.add(url || id || `${title}\n${content.slice(0, 240)}` || fallback);
};
const visitPayload = (payload: unknown, fallback: string) => {
if (typeof payload === "string") {
try {
visitPayload(JSON.parse(payload), fallback);
} catch {
// Plain-text tool output is not reliably separable into source rows.
}
return;
}
if (Array.isArray(payload)) {
payload.forEach((item, index) => addCandidate(item, `${fallback}:${index}`));
return;
}
if (!payload || typeof payload !== "object") return;
const record = payload as Record<string, unknown>;
for (const key of ["results", "items", "records", "documents", "hits", "data"]) {
if (Array.isArray(record[key])) {
record[key].forEach((item, index) => addCandidate(item, `${fallback}:${key}:${index}`));
return;
}
}
addCandidate(record, fallback);
};
for (const message of messages) {
if (message.type !== "tool" || message.name === "ask_clarification" || message.name === "write_todos") continue;
visitPayload(extractToolResultPayload(message), message.id ?? message.name ?? "tool");
}
// The backend deliberately falls back to the collector's visible conclusion
// when a skill narrated findings but returned no structured source rows.
if (unique.size === 0) {
const hasCollectorSummary = messages.some(
(message) => message.type === "ai" && extractContentFromMessage(message).trim().length > 0,
);
if (hasCollectorSummary) return 1;
}
return unique.size;
}
const COLLECTOR_PERSIST_LIMIT = 80;
const WRITE_FALLBACK_MATERIAL_LIMIT = 20;
const SKIP_COLLECTOR_PERSIST_TOOLS = new Set(["ask_clarification", "write_todos"]);
function collectorMaterialKey(item: Record<string, unknown>): string {
const text = (value: unknown) => typeof value === "string" ? value.trim() : "";
return text(item.id) || text(item.url) || `${text(item.title)}\n${text(item.raw_content).slice(0, 240)}`;
}
function isCompleteToolPayload(message: Message): boolean {
const payload = extractToolResultPayload(message);
if (payload == null) return false;
if (typeof payload === "string") {
const trimmed = payload.trim();
if (!trimmed) return false;
if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
try {
JSON.parse(trimmed);
return true;
} catch {
return false;
}
}
return trimmed.length > 20;
}
return typeof payload === "object";
}
/** Freeze a compact evidence pool for a worker-independent report job. */
function snapshotCollectorMaterials(
messages: readonly Message[] | undefined,
options?: { limit?: number; includeSummary?: boolean },
): Record<string, unknown>[] {
if (!messages?.length) return [];
const limit = options?.limit ?? COLLECTOR_PERSIST_LIMIT;
const frozen: Record<string, unknown>[] = [];
const seen = new Set<string>();
const text = (value: unknown) => typeof value === "string" ? value.trim() : "";
const addNormalized = (item: ReturnType<typeof normalizeSearchResults>[number], toolName: string) => {
const url = text(item.url);
const id = text(item.id) || text(item.recUuid) || text(item.uuid) || text(item.docId);
const title = text(item.title) || `检索结果 ${frozen.length + 1}`;
const content = text(item.content) || text(item.snippet);
if (!url && !id && !content) return;
const key = id || url || `${title}\n${content.slice(0, 240)}`;
if (seen.has(key) || frozen.length >= limit) return;
seen.add(key);
frozen.push({
id: id || undefined,
title: title.slice(0, 500),
url: url.slice(0, 2_000) || undefined,
raw_content: content.slice(0, 6_000),
snippet: (text(item.snippet) || content).slice(0, 500) || undefined,
source: text(item.source) || toolName || "collector",
source_type: toolName === "web_search" ? "web" : "other",
published_at: text(item.published_date) || text(item.publishedDate) || text(item.date) || undefined,
rec_uuid: text(item.recUuid) || text(item.uuid) || undefined,
});
};
for (const message of messages) {
if (message.type === "tool" && message.name && SKIP_COLLECTOR_PERSIST_TOOLS.has(message.name)) {
continue;
}
const toolName = message.name || (message.type === "tool" ? "collector_tool" : "");
const payload = message.type === "tool" || message.type === "ai"
? extractToolResultPayload(message)
: undefined;
const rows = normalizeSearchResults(
payload && typeof payload === "object" && !Array.isArray(payload)
? payload
: typeof payload === "string"
? payload
: undefined,
);
for (const row of rows) addNormalized(row, toolName || "collector");
}
if (!frozen.length && options?.includeSummary !== false) {
const summary = [...messages].reverse().find(
(message) => message.type === "ai" && extractContentFromMessage(message).trim(),
);
const content = summary ? extractContentFromMessage(summary).trim() : "";
if (content) {
frozen.push({
title: "收集员小结",
raw_content: content.slice(0, 6_000),
snippet: content.slice(0, 500),
source: "collector",
source_type: "other",
});
}
}
return frozen;
}
function countEventMaterials(events: ProgressEvent[]): number {
const unique = new Set<string>();
let completedCount = 0;
for (const event of events) {
if (event.type === "collection_completed") {
const count = Number(event.payload.materialCount ?? 0);
if (Number.isFinite(count)) completedCount = Math.max(completedCount, count);
continue;
}
if (event.type !== "source_added") continue;
const source = event.payload.source;
const record = source && typeof source === "object" && !Array.isArray(source)
? source as Record<string, unknown>
: {};
const id = typeof event.payload.sourceId === "string" ? event.payload.sourceId : "";
const url = typeof record.url === "string" ? record.url : "";
const title = typeof record.title === "string" ? record.title : "";
unique.add(id || url || title || `event:${event.seq}`);
}
return Math.max(unique.size, completedCount);
}
export default function DeepResearchWorkbench({
modeTabs,
}: {
modeTabs?: ReactNode;
} = {}) {
// ArtifactsProvider 必须包住整个工作台:useReportSandbox(选中/自动展开报告
// 产物)与右侧沙箱的 ArtifactFileDetail 要共享同一份 artifacts 上下文。
return (
<DocumentRewritePresentationProvider>
<ArtifactsProvider>
<DeepResearchWorkbenchInner modeTabs={modeTabs} />
</ArtifactsProvider>
</DocumentRewritePresentationProvider>
);
}
function DeepResearchWorkbenchInner({
modeTabs,
}: {
modeTabs?: ReactNode;
}) {
const queryClient = useQueryClient();
// 「?session=<id>」深链:对话历史页「深度研究」Tab 等外部入口直接定位到某条
// 研究记录。仅作初始选中(首帧读取一次);之后的切换仍走页内状态,不回写 URL。
const [searchParams] = useSearchParams();
const [selectedId, setSelectedId] = useState<string | null>(() =>
searchParams.get("session"),
);
// Clicking a history row (or opening ?session=) is browse-only: render the
// saved thread and do not auto-collect, auto-write, or auto-flip status.
// Explicit composer / card actions turn this off.
const [historyBrowseOnly, setHistoryBrowseOnly] = useState(() => Boolean(searchParams.get("session")));
const [mode, setMode] = useState<ResearchMode>("basic");
const [generateImages, setGenerateImages] = useState(false);
const [advancedOptions, setAdvancedOptions] = useState<AdvancedResearchOptions>(DEFAULT_ADVANCED_OPTIONS);
// A session's initial config is deliberately frozen when collection starts.
// Keep only post-start outline choices separately so another research record
// cannot leak its workflow selection into this record's writing card.
const [reportCardOutlineOverrides, setReportCardOutlineOverrides] = useState<Record<string, string>>({});
const [reportCardStructureModeOverrides, setReportCardStructureModeOverrides] = useState<Record<string, ReportStructureMode>>({});
const [reportCardRetrievalDirectionsOverrides, setReportCardRetrievalDirectionsOverrides] = useState<Record<string, string[]>>({});
const [reportCardRetrievalSkillsOverrides, setReportCardRetrievalSkillsOverrides] = useState<Record<string, string[]>>({});
const [classicMode, setClassicMode] = useState(false);
const retrievalSettings = useOrdinaryKnowledgeRetrievalSettings();
const pageDescriptions = usePageDescriptionsSettings();
const deepResearchPageDescription = pageDescriptions.data?.deep_research;
const [draftRetrievalMode, setDraftRetrievalMode] = useState<KnowledgeRetrievalMode>("classic");
const [draftKnowledgeBaseIds, setDraftKnowledgeBaseIds] = useState<string[]>([]);
const [selectedModel, setSelectedModel] = useState<string | null>(null);
const [settingsOpen, setSettingsOpen] = useState(false);
const [sandboxOpen, setSandboxOpen] = useState(false);
const [downloadDialogOpen, setDownloadDialogOpen] = useState(false);
const [downloadTargetSession, setDownloadTargetSession] = useState<DeepResearchSession | null>(null);
const [documentRewriteDialogRequest, setDocumentRewriteDialogRequest] = useState(0);
const [documentRewriteDialogPurpose, setDocumentRewriteDialogPurpose] = useState<"rewrite" | "regenerate">("rewrite");
// A structural regeneration owns a fresh report session. Keep that
// identity while its first model token is pending so the right sandbox can
// never fall back to the parent report's stale stub content.
const [newReportSandboxSessionId, setNewReportSandboxSessionId] = useState<string | null>(null);
const [inlineGeneratedReport, setInlineGeneratedReport] = useState<InlineGeneratedReport | null>(null);
// The normal “改写新报告” action can target an inline generated fork even
// though its parent research conversation remains selected.
const [rewriteTargetSession, setRewriteTargetSession] = useState<DeepResearchSession | null>(null);
const [run, setRun] = useState<WorkbenchRun>(EMPTY_RUN);
// Bound from the write POST itself. A lagging GET /session can restore
// ``awaiting_report`` and would otherwise hide the writing UI / tear down SSE.
const [pendingWriteJobId, setPendingWriteJobId] = useState<string | null>(null);
// Confirm-card write now runs on the collector thread (writing-mode pipeline),
// not POST /report. Keep the card hidden until the session row is completed.
const [pendingInlineWrite, setPendingInlineWrite] = useState(false);
// 「选择结构再生成」 writes on the parent collector thread but persists to
// this child session. A leftover first-write completion must not mark it done.
const [pendingVariantWriteId, setPendingVariantWriteId] = useState<string | null>(null);
const [pendingFollowUp, setPendingFollowUp] = useState<string | null>(null);
const [followUpStream, setFollowUpStream] = useState<FollowUpStreamState | null>(null);
const reportDocumentRewrite = useDocumentRewrite();
const rewritePresentation = useDocumentRewritePresentation();
const reportRewritePresentationId = useRef<string | null>(null);
const reportRewriteJobId = useRef<string | null>(null);
const hydratedReportRewriteSessionId = useRef<string | null>(null);
const pendingSandboxOpenSessionId = useRef<string | null>(null);
const mirroredReportRequirementsPlanRef = useRef<{ presentationId: string | null; plan: string }>({
presentationId: null,
plan: "",
});
const mirroredReportRewriteThinkingRef = useRef<{ presentationId: string | null; thinking: string }>({
presentationId: null,
thinking: "",
});
const sessions = useResearchSessions();
const sessionQuery = useResearchSession(selectedId);
const reportVariants = useResearchReportVariants(selectedId);
const sources = useResearchSources(selectedId);
const messages = useResearchMessages(selectedId);
const capabilities = useCapabilities();
const actions = useResearchActions();
const [localSettings] = useLocalSettings();
const { models, isLoading: modelsLoading } = useModels();
const seenEventKeys = useRef(new Set<string>());
// Live provider deltas can legitimately repeat the same text (including a
// single space). They have no durable sequence, so never deduplicate them
// by payload or a thought token could disappear from the visible trace.
const liveEventSerial = useRef(0);
const replayedTraceJobs = useRef(new Set<string>());
const pendingReportEvents = useRef<ProgressEvent[]>([]);
const reportAnimationFrame = useRef<number | null>(null);
const boundStreamJobRef = useRef<string | null>(null);
const openReportRef = useRef<() => void>(() => {});
const refetchLiveJobRef = useRef<() => void>(() => {});
const inlineGenerationSessionRef = useRef<DeepResearchSession | null>(null);
// Chat-collection flow bookkeeping.
const pendingInitialQuery = useRef<string | null>(null);
const finishedTurnKey = useRef<string | null>(null);
const persistedCollectorKey = useRef("");
const persistedCollectorToolIds = useRef(new Set<string>());
const persistedCollectorMaterialKeys = useRef(new Set<string>());
const collectorPersistChain = useRef(Promise.resolve());
const collectorSessionIdRef = useRef<string | null>(null);
const followUpAbortRef = useRef<AbortController | null>(null);
const outlinePlanKeyRef = useRef("");
const pendingCollectAfterPlanRef = useRef("");
const pendingSearchNudgeRef = useRef("");
const inlineWriteTargetIdRef = useRef<string | null>(null);
const refetchSession = sessionQuery.refetch;
const refetchSessions = sessions.refetch;
const refetchSources = sources.refetch;
const refetchReportVariants = reportVariants.refetch;
const session = sessionQuery.data;
const loggedSessionDiagnosticKey = useRef<string | null>(null);
useEffect(() => {
if (!session) return;
const diagnostics = session.runtimeDiagnostics;
if (!session.error && !diagnostics) return;
const key = `${session.id}:${session.activeJobId ?? session.usage?.lastJobId ?? ""}:${session.error ?? ""}`;
if (loggedSessionDiagnosticKey.current === key) return;
loggedSessionDiagnosticKey.current = key;
console.warn("[深度研究] session_runtime_diagnostic", {
sessionId: session.id,
status: session.status,
error: session.error,
activeJobId: session.activeJobId,
runtimeDiagnostics: diagnostics,
});
}, [session]);
useEffect(() => {
if (!pendingWriteJobId) return;
if (session?.status === "completed" || session?.status === "failed" || session?.status === "cancelled") {
setPendingWriteJobId(null);
}
}, [pendingWriteJobId, session?.status]);
const generatedReportVariants = useMemo(() => {
const byId = new Map((reportVariants.data ?? []).map((item) => [item.id, item]));
if (inlineGeneratedReport && session && inlineGeneratedReport.parentSessionId === session.id) {
byId.set(inlineGeneratedReport.session.id, inlineGeneratedReport.session);
}
return [...byId.values()].sort((left, right) => String(left.createdAt ?? "").localeCompare(String(right.createdAt ?? "")));
}, [inlineGeneratedReport, reportVariants.data, session?.id]);
// Sessions created by the chat flow carry a runtime collector thread; legacy
// sessions (old data + 经典模式 rollback) keep the original timeline flow.
// Structural report variants receive the same hidden runtime thread as the
// first report and therefore reuse the same conversation/timeline layout.
const collectorThreadId = session?.runtimeThreadId ?? null;
const inlineReport = useResearchReportStream(collectorThreadId);
const isReportVariant = session?.config?.report_variant === true
|| session?.title.includes(" · 新结构报告") === true;
const isChatSession = Boolean(collectorThreadId);
const inlineGenerationSession = inlineGeneratedReport && inlineGeneratedReport.parentSessionId === session?.id
? inlineGeneratedReport.session
: generatedReportVariants.find((item) => item.status === "running" || item.status === "awaiting_input") ?? null;
const jobSession = inlineGenerationSession ?? session;
const activeJobId = jobSession?.activeJobId ?? pendingWriteJobId ?? null;
const isRunning = Boolean(pendingWriteJobId)
|| pendingInlineWrite
|| Boolean(pendingVariantWriteId)
|| (
jobSession?.status === "running"
&& (Boolean(jobSession.activeJobId) || Boolean(inlineGenerationSession) || !isChatSession)
);
const isAwaitingReview = jobSession?.status === "awaiting_input";
const isAwaitingReport = isChatSession && session?.status === "awaiting_report" && !pendingWriteJobId && !pendingInlineWrite;
const isCollecting = isChatSession && (session?.status === "collecting" || session?.status === "draft");
const lastCompletedJobId = jobSession?.status === "completed" && typeof jobSession.usage?.lastJobId === "string"
? jobSession.usage.lastJobId
: null;
const streamJobId = activeJobId ?? lastCompletedJobId;
const reportCardOutlineOverride = session ? reportCardOutlineOverrides[session.id] : undefined;
const reportCardStructureModeOverride = session ? reportCardStructureModeOverrides[session.id] : undefined;
const reportCardRetrievalDirectionsOverride = session ? reportCardRetrievalDirectionsOverrides[session.id] : undefined;
const reportCardRetrievalSkillsOverride = session ? reportCardRetrievalSkillsOverrides[session.id] : undefined;
const availableModes = useMemo<ResearchMode[]>(
() => capabilities.data?.modes ?? DEFAULT_AVAILABLE_MODES,
[capabilities.data?.modes],
);
const imageGenerationAvailable = capabilities.data?.imageGeneration?.available === true;
// A new writing run starts with an intentionally blank sandbox. Do not use
// a previous durable report as a placeholder before the first write delta.
const isGeneratingNewReport = inlineGenerationSession !== null;
// Honor an explicit file-card click over the live generation session. Otherwise
// a regenerated child would keep owning the sandbox, and the parent's card
// would reopen the new report.md instead of its own preserved copy.
const sandboxSessionId = newReportSandboxSessionId ?? inlineGenerationSession?.id ?? session?.id ?? "draft";
const sandboxVariantSession = generatedReportVariants.find((item) => item.id === sandboxSessionId) ?? null;
// First-generation writes have no child session. Treat "the session whose
// job is streaming" as the live sandbox target so report_delta can open it.
const liveWriteSessionId = inlineGenerationSession?.id ?? (isRunning ? session?.id : null);
const viewingLiveGeneration = Boolean(
isRunning && liveWriteSessionId && sandboxSessionId === liveWriteSessionId,
);
const viewingParentReport = Boolean(session && sandboxSessionId === session.id);
// A follow-up rewrite is deliberately only a candidate. The sandbox remains
// on the durable report until the user explicitly applies that candidate.
const reportRewritePreview =
(reportDocumentRewrite.isActive || reportDocumentRewrite.run.stage === "completed") &&
reportDocumentRewrite.run.draft.trim()
? reportDocumentRewrite.run.draft
: "";
// 全文改写启动后,右侧只渲染临时草稿:首个 token 到达前保持空白,
// 不把旧报告混在新稿前面。真实 report.md 仍只在后台校验 + CAS 成功后替换。
const rawDisplayedReport = reportDocumentRewrite.isActive
? reportDocumentRewrite.run.draft
: reportRewritePreview
|| (viewingLiveGeneration
? run.report
: viewingParentReport
? (session?.reportMarkdown || run.report || "")
: sandboxVariantSession?.reportMarkdown || "");
// Never hide a backend response. Hiding refusal prose also removed the
// virtual report file and its sandbox-open trigger, leaving operators with
// neither a report nor an error. The backend now replaces refusal output at
// its final persistence gate; this client-side signal remains visible when
// a worker is stale or a new provider wording escapes that guard.
const refusalReportDetected = isRefusalReportText(rawDisplayedReport);
const hasUsableDisplayedReport = Boolean(rawDisplayedReport.trim()) && !refusalReportDetected;
const streamStillOpen = Boolean(run.jobId && run.phase !== "done" && run.phase !== "failed");
const liveWriting = Boolean(
isRunning
|| isAwaitingReview
|| reportDocumentRewrite.isActive
|| streamStillOpen
|| (viewingLiveGeneration && run.phase !== "done"),
);
// Never replace a live write with the operator diagnostic. An empty sandbox
// during thinking is normal; the JSON dump is only for a finished run that
// still has no usable Markdown.
const repairOnlyError = typeof session?.error === "string"
&& session.error.includes("session_read_repair");
const showRunDiagnostic = Boolean(
!liveWriting && !hasUsableDisplayedReport && (
refusalReportDetected
|| session?.status === "failed"
|| (Boolean(session?.error) && !repairOnlyError)
),
);
const runtimeDiagnosticText = JSON.stringify(
session?.runtimeDiagnostics ?? {
revision: "frontend-fallback-diagnostic",
session: {
id: session?.id,
status: session?.status,
sourceCount: session?.sourceCount ?? 0,
activeJobId: session?.activeJobId,
},
error: session?.error ?? "报告正文被识别为拒绝型输出",
invalidOutputPreview: refusalReportDetected ? rawDisplayedReport.slice(0, 1_200) : undefined,
},
null,
2,
);
const diagnosticMarkdown = showRunDiagnostic
? [
"## 系统运行说明",
"",
"> 本次报告生成链路出现异常。系统不能据此判断为‘没有收集到素材’,已有素材不会被删除。请将下面的诊断信息复制给管理员排查。",
"",
"```json",
runtimeDiagnosticText,
"```",
].join("\n")
: "";
// Invalid refusal prose (or a failed run with no report) is replaced instead
// of repeated to the user. Any usable normal/fallback/partial report is shown
// as-is and never receives diagnostic text.
const displayedReport = showRunDiagnostic
? `# 报告生成异常\n\n${diagnosticMarkdown}`
: rawDisplayedReport;
const updateFullReportRewritePresentation = useCallback(
(presentationId: string | null, event: DocumentRewriteStreamEvent) => {
if (!presentationId || !rewritePresentation) return;
switch (event.type) {
case "snapshot_fixed":
rewritePresentation.update(presentationId, {
stage: "requirements",
originalCharCount: event.originalCharCount,
requirementsPlan: "",
});
break;
case "requirements_started":
rewritePresentation.update(presentationId, { stage: "requirements", requirementsPlan: "" });
break;
case "requirements_checkpoint":
case "requirements_completed":
rewritePresentation.update(presentationId, {
stage: "requirements",
requirementsPlan: event.content,
});
break;
case "requirements_resolved":
rewritePresentation.update(presentationId, {
stage: "writing",
...(event.plan ? { requirementsPlan: event.plan } : {}),
});
break;
case "rewrite_delta":
case "rewrite_checkpoint":
rewritePresentation.update(presentationId, {
stage: "writing",
writtenCharCount: event.charCount,
});
break;
case "validation_started":
rewritePresentation.update(presentationId, { stage: "validation" });
break;
case "validation_completed":
rewritePresentation.update(presentationId, { warnings: event.warnings });
break;
case "comparison_ready":
rewritePresentation.update(presentationId, { summary: event.summary });
break;
case "commit_started":
rewritePresentation.update(presentationId, { stage: "committing" });
break;
case "committed":
rewritePresentation.update(presentationId, { versionId: event.versionId ?? null });
break;
case "done":
rewritePresentation.update(presentationId, {
stage: "completed",
versionId: event.versionId ?? null,
});
break;
case "conflict":
rewritePresentation.update(presentationId, { stage: "conflict", error: event.message });
break;
case "error":
rewritePresentation.update(presentationId, {
stage: "error",
error: event.message,
diagnostic: event.diagnostic ?? null,
});
break;
default:
break;
}
},
[rewritePresentation],
);
// ── 真沙箱右栏(stub 线程机制,见 useReportSandbox)──────────────────────
// 撰写中(summarizing/done 除外)stub isLoading=true:流式 code 视图自动滚底;
// 进入摘要阶段翻 false:沙箱自动切换 Markdown 预览(「生成完直接切预览」)。
const sandboxWriting =
(viewingLiveGeneration && run.phase !== "summarizing" && run.phase !== "done") ||
reportDocumentRewrite.isActive;
const handleFirstReportContent = useCallback(() => {
if (historyBrowseOnly) return;
setSandboxOpen(true);
}, [historyBrowseOnly]);
const { stubMessages, openReport } = useReportSandbox({
threadKey: sandboxSessionId,
report: displayedReport,
writing: sandboxWriting,
onFirstReportContent: handleFirstReportContent,
// Open only after thinking has finished and the first write token exists.
// Thinking stays on the left progress card; an empty writing-phase stub
// must not steal the right panel.
activity: Boolean(run.report.trim()),
// Open on the first visible write, including first-generation reports and
// a new sibling. Stay put if the user has already switched to another card.
autoOpen: viewingLiveGeneration || reportDocumentRewrite.isActive,
});
openReportRef.current = openReport;
inlineGenerationSessionRef.current = inlineGenerationSession;
refetchLiveJobRef.current = () => {
void Promise.all([refetchSession(), refetchSessions(), refetchSources(), refetchReportVariants()]);
};
const sandboxVisible = sandboxOpen && Boolean(
displayedReport || isRunning || isAwaitingReview || reportDocumentRewrite.isActive || isGeneratingNewReport,
);
const handleOpenSandbox = useCallback(() => {
setSandboxOpen(true);
openReport();
}, [openReport]);
useEffect(() => {
if (!viewingLiveGeneration && !reportDocumentRewrite.isActive) return;
if (!run.report.trim()) return;
setSandboxOpen(true);
openReport();
}, [openReport, reportDocumentRewrite.isActive, run.report, viewingLiveGeneration]);
// ArtifactFileList invokes its handler synchronously. Switch the virtual
// sandbox file first, then open it from an effect once useReportSandbox has
// rebuilt its URL for the generated report session.
const handleOpenInlineGeneratedReport = useCallback((target: DeepResearchSession) => {
if (sandboxSessionId === target.id) {
setRewriteTargetSession(target);
setSandboxOpen(true);
openReport();
return;
}
pendingSandboxOpenSessionId.current = target.id;
setNewReportSandboxSessionId(target.id);
setRewriteTargetSession(target);
}, [openReport, sandboxSessionId]);
useEffect(() => {
if (pendingSandboxOpenSessionId.current !== sandboxSessionId) return;
pendingSandboxOpenSessionId.current = null;
setSandboxOpen(true);
openReport();
}, [openReport, sandboxSessionId]);
useEffect(() => {
if (!availableModes.includes(mode)) setMode(availableModes[0] ?? "basic");
}, [availableModes, mode]);
useEffect(() => {
reportDocumentRewrite.reset();
reportRewritePresentationId.current = null;
reportRewriteJobId.current = null;
hydratedReportRewriteSessionId.current = null;
}, [reportDocumentRewrite.reset, session?.id]);
// Selecting another research record ends the inline result context. The
// generated fork itself is still present in the history rail, but it no
// longer owns the sandbox or the current conversation's result slot.
useEffect(() => {
if (inlineGeneratedReport && session?.id !== inlineGeneratedReport.parentSessionId) {
setInlineGeneratedReport(null);
setNewReportSandboxSessionId(null);
setRewriteTargetSession(null);
}
}, [inlineGeneratedReport, session?.id]);
// A document rewrite is a backend job, not a component-owned fetch. When
// the user refreshes halfway through, restore the newest rewrite timeline
// and join its persisted event stream instead of starting a second rewrite.
useEffect(() => {
if (!session || !rewritePresentation || hydratedReportRewriteSessionId.current === session.id) return;
hydratedReportRewriteSessionId.current = session.id;
let disposed = false;
void (async () => {
try {
const latest = await getLatestFullResearchReportRewrite(session.id);
if (disposed || !latest.job) return;
const presentationId = rewritePresentation.create({
threadId: collectorThreadId ?? session.id,
operation: latest.request.operation,
source: { kind: "deep_research_report", id: session.id, path: "report.md" },
fileName: "report.md",
instruction: latest.request.instruction || "AI 全文改写",
style: latest.request.style,
modelName: latest.request.modelName ?? null,
requirementsPlan: typeof latest.result.requirementsPlan === "string"
? latest.result.requirementsPlan
: "",
});
reportRewritePresentationId.current = presentationId;
reportRewriteJobId.current = latest.job.id;
const resultStatus = String(latest.result.status ?? "");
if (["completed", "failed", "cancelled"].includes(latest.job.status)) {
const summary = latest.result.summary;
rewritePresentation.update(presentationId, {
stage:
resultStatus === "conflict"
? "conflict"
: latest.job.status === "failed" || latest.job.status === "cancelled"
? "error"
: "completed",
versionId: typeof latest.result.versionId === "string" ? latest.result.versionId : null,
summary:
summary && typeof summary === "object"
? (summary as DocumentRewriteSummary)
: null,
error:
resultStatus === "conflict"
? "报告在改写期间已变化,候选稿没有覆盖原报告。"
: latest.job.errorMessage ?? null,
});
return;
}
void reportDocumentRewrite.start(
{
threadId: collectorThreadId ?? session.id,
path: REPORT_OUTPUT_PATH,
instruction: latest.request.instruction || "AI 全文改写",
style: latest.request.style,
modelName: latest.request.modelName ?? undefined,
},
{
stream: (signal) => joinFullResearchReportRewrite(latest.job!.id, signal),
onEvent: (event) => updateFullReportRewritePresentation(presentationId, event),
onCommitted: (rewritten) => {
setRun((current) => ({ ...current, report: rewritten }));
void Promise.all([refetchSession(), refetchSessions(), messages.refetch()]);
},
},
);
} catch {
// A completed report remains usable even if historical rewrite
// telemetry was pruned; do not turn a recovery miss into a page error.
}
})();
return () => {
disposed = true;
};
}, [
collectorThreadId,
getLatestFullResearchReportRewrite,
joinFullResearchReportRewrite,
messages,
refetchSession,
refetchSessions,
reportDocumentRewrite,
rewritePresentation,
session,
updateFullReportRewritePresentation,
]);
// Requirements deltas are rAF-coalesced by the shared rewrite hook. Mirror
// that coalesced plan into the ordinary chat timeline, so report rewrites
// have the same visible understanding stage as sandbox Markdown rewrites.
useEffect(() => {
const presentationId = reportRewritePresentationId.current;
const plan = reportDocumentRewrite.run.requirementsPlan;
if (!presentationId || !rewritePresentation || !plan) return;
// The context provider creates a new value for every update. Deduplicate
// the mirrored stream value so that value change does not feed back into
// this effect and cause React's maximum-update-depth error.
const previous = mirroredReportRequirementsPlanRef.current;
if (previous.presentationId === presentationId && previous.plan === plan) return;
mirroredReportRequirementsPlanRef.current = { presentationId, plan };
rewritePresentation.update(presentationId, {
requirementsPlan: plan,
});
}, [reportDocumentRewrite.run.requirementsPlan, rewritePresentation]);
useEffect(() => {
const presentationId = reportRewritePresentationId.current;
const thinking = reportDocumentRewrite.run.thinkingText;
if (!presentationId || !rewritePresentation || !thinking) return;
const previous = mirroredReportRewriteThinkingRef.current;
if (previous.presentationId === presentationId && previous.thinking === thinking) return;
mirroredReportRewriteThinkingRef.current = { presentationId, thinking };
rewritePresentation.update(presentationId, { thinkingText: thinking });
}, [reportDocumentRewrite.run.thinkingText, rewritePresentation]);
useEffect(() => {
const handleRewriteUndo = (event: Event) => {
const detail = (event as CustomEvent<{
source?: { kind?: string; id?: string };
content?: string;
}>).detail;
if (
detail?.source?.kind !== "deep_research_report" ||
detail.source.id !== session?.id ||
typeof detail.content !== "string"
) {
return;
}
const restoredReport = detail.content;
reportDocumentRewrite.reset();
setRun((current) => ({ ...current, report: restoredReport }));
void Promise.all([refetchSession(), refetchSessions(), messages.refetch()]);
};
window.addEventListener(DOCUMENT_REWRITE_UNDONE_EVENT, handleRewriteUndo);
return () => window.removeEventListener(DOCUMENT_REWRITE_UNDONE_EVENT, handleRewriteUndo);
}, [
messages,
refetchSession,
refetchSessions,
reportDocumentRewrite.reset,
session?.id,
]);
useEffect(() => {
if (!imageGenerationAvailable) setGenerateImages(false);
}, [imageGenerationAvailable]);
// ── collector-agent conversation stream (normal-chat machinery) ───────────
const outlinePlannerMode = session
? normalizeOutlinePlanner(session.config?.outline_planner)
: advancedOptions.outlinePlanner;
const sessionOutline = (
session
? (
Object.prototype.hasOwnProperty.call(reportCardOutlineOverrides, session.id)
? reportCardOutlineOverrides[session.id]
: (typeof session.config?.custom_outline === "string" ? session.config.custom_outline : "")
)
: advancedOptions.customOutline
).trim();
const [activeAgentId, setActiveAgentId] = useState(COLLECTOR_AGENT_ID);
const researchKnowledgeBaseIds = useMemo(() => {
if (!session) return draftKnowledgeBaseIds;
const ids = session.config?.llmwiki_knowledge_base_ids;
return Array.isArray(ids) ? ids.filter((id): id is string => typeof id === "string") : [];
}, [session, draftKnowledgeBaseIds]);
const researchRetrievalMode = session
? normalizeKnowledgeRetrievalMode(session.config?.knowledge_retrieval_mode)
: draftRetrievalMode;
const smartRetrievalAvailability = resolveSmartKnowledgeRetrievalAvailability({
settingsLoading: retrievalSettings.isLoading,
settingsError: retrievalSettings.isError,
smartReasoningEnabled: retrievalSettings.data?.smart_reasoning_enabled === true,
knowledgeSelectionReady: true,
ordinaryKnowledgeBaseCount: researchKnowledgeBaseIds.length,
assistantKnowledgeBaseCount: 0,
});
const collectorContext = useMemo(
() => {
const skills = normalizeRetrievalSkills(
advancedOptions.retrievalSkills.length > 0
? advancedOptions.retrievalSkills
: session?.config?.retrieval_skills,
);
return {
...localSettings.context,
model_name: selectedModel ?? localSettings.context.model_name,
agent_id: activeAgentId,
...resolveKnowledgeRetrievalRequestContext({
mode: researchRetrievalMode,
smartReasoningEnabled: retrievalSettings.data?.smart_reasoning_enabled === true,
knowledgeSelectionReady: true,
ordinaryKnowledgeBaseIds: researchKnowledgeBaseIds,
assistantKnowledgeBaseIds: [],
}),
...(skills.length > 0 ? { extra_skills: skills } : {}),
};
},
[activeAgentId, advancedOptions.retrievalSkills, localSettings.context, selectedModel, session?.config?.retrieval_skills, researchKnowledgeBaseIds, researchRetrievalMode, retrievalSettings.data?.smart_reasoning_enabled],
);
const [collectorThread, collectorSendMessage, , boundCollectorThreadId] = useThreadStream({
threadId: isChatSession ? collectorThreadId : undefined,
assistantId: activeAgentId,
context: collectorContext,
});
const collectorStreaming = collectorThread.isLoading;
const collectorMessagesLength = collectorThread.messages?.length ?? 0;
const collectorThreadLoading = collectorThread.isThreadLoading;
const collectorPendingClarification = useMemo(
() => hasPendingClarification(collectorThread.messages),
[collectorThread.messages],
);
const collectAfterPlanStarted = hasCollectAfterPlanTurn(
collectorThread.messages,
extractContentFromMessage,
);
const collectionSummaryReady = hasCollectionSummary(
collectorThread.messages,
extractContentFromMessage,
);
const retrievalAfterPlanReady = hasRetrievalAfterPlan(
collectorThread.messages,
extractContentFromMessage,
);
const retrievalToolsReady = hasRetrievalToolTurn(collectorThread.messages);
const searchNudgeStarted = hasStartSearchAfterTermsTurn(
collectorThread.messages,
extractContentFromMessage,
);
const hasWorkbenchWriteTurn = Boolean(
collectorThread.messages?.some((message) => (
message.type === "human"
&& (
message.additional_kwargs?.workbench_write_now === true
|| isWorkbenchWritePrompt(extractContentFromMessage(message))
)
)),
);
const collectorWriteDone = collectorWriteSucceeded(collectorThread.messages)
|| threadHasReportArtifact(collectorThread.values?.artifacts);
const inlineWriteDone = inlineWriteFinished({
sessionStatus: session?.status,
inlineReportStatus: inlineReport?.status,
inlineReportPhase: inlineReport?.phase,
runPhase: run.jobId ? run.phase : null,
writeSucceeded: collectorWriteDone,
});
const liveReportText = (
session?.reportMarkdown || run.report || inlineReport?.reportText || ""
).trim();
const isFollowUp = inlineWriteDone && Boolean(liveReportText);
useEffect(() => {
if (!pendingInlineWrite) return;
if (session?.status === "failed" || session?.status === "cancelled") {
setPendingInlineWrite(false);
return;
}
if (inlineWriteDone) setPendingInlineWrite(false);
}, [inlineWriteDone, pendingInlineWrite, session?.status]);
const patchedCompletedSessionRef = useRef<string | null>(null);
useEffect(() => {
if (historyBrowseOnly) {
patchedCompletedSessionRef.current = null;
return;
}
if (!inlineWriteDone) {
patchedCompletedSessionRef.current = null;
return;
}
if (!session?.id || patchedCompletedSessionRef.current === session.id) return;
patchedCompletedSessionRef.current = session.id;
patchCachedResearchSession(queryClient, session.id, {
status: "completed",
reportMarkdown: liveReportText || session.reportMarkdown,
error: undefined,
activeJobId: undefined,
});
void refetchSessions();
}, [historyBrowseOnly, inlineWriteDone, liveReportText, queryClient, refetchSessions, session]);
const railSessions = useMemo(
() => overlayLiveSession(
sessions.data?.items ?? [],
inlineWriteDone && session
? {
...session,
status: "completed" as const,
reportMarkdown: liveReportText || session.reportMarkdown,
}
: session,
),
[inlineWriteDone, liveReportText, session, sessions.data?.items],
);
const isPlanningOutline = !historyBrowseOnly
&& outlinePlannerMode === "agent"
&& !sessionOutline
&& !collectAfterPlanStarted
&& !(collectionSummaryReady && retrievalToolsReady)
&& isChatSession
&& (session?.status === "collecting" || session?.status === "draft");
const sendCollectorMessage = useCallback(
async (text: string, options?: {
silentStatusPatch?: boolean;
hideFromUI?: boolean;
withDirections?: boolean;
withSkills?: boolean;
}) => {
const threadId = session?.runtimeThreadId;
const trimmed = text.trim();
if (!threadId || !trimmed) return;
if (!options?.silentStatusPatch && session && session.status !== "collecting") {
void actions.updateStatus.mutate({ sessionId: session.id, status: "collecting" });
}
const useDirections = options?.withDirections === true
|| (options?.withDirections !== false && (collectorThread.messages?.length ?? 0) === 0 && !isPlanningOutline);
const useSkills = options?.withSkills === true || (options?.withSkills !== false && useDirections);
const payload = composeCollectorQueryWithDirections(
trimmed,
useDirections
? (advancedOptions.retrievalDirections.length > 0
? advancedOptions.retrievalDirections
: session?.config?.retrieval_directions)
: [],
useSkills
? (advancedOptions.retrievalSkills.length > 0
? advancedOptions.retrievalSkills
: session?.config?.retrieval_skills)
: [],
);
try {
await collectorSendMessage(
threadId,
{ text: payload, files: [] },
selectedModel ? { model_name: selectedModel } : undefined,
options?.hideFromUI ? { additionalKwargs: { hide_from_ui: true } } : undefined,
);
} catch (error) {
toast.error(error instanceof Error ? error.message : "发送失败,请重试");
}
},
[
actions.updateStatus,
advancedOptions.retrievalDirections,
advancedOptions.retrievalSkills,
collectorSendMessage,
collectorThread.messages?.length,
isPlanningOutline,
selectedModel,
session,
],
);
const handleClarificationSubmit = useCallback(
async (text: string) => {
setHistoryBrowseOnly(false);
const threadId = session?.runtimeThreadId;
await stopActiveThreadBeforeClarificationReply(threadId, collectorThread);
await sendCollectorMessage(text);
},
[collectorThread, sendCollectorMessage, session?.runtimeThreadId],
);
useEffect(() => {
if (!session?.id) {
setActiveAgentId(COLLECTOR_AGENT_ID);
return;
}
const shouldPlanFirst = normalizeOutlinePlanner(session.config?.outline_planner) === "agent"
&& !String(session.config?.custom_outline ?? "").trim()
&& !Object.prototype.hasOwnProperty.call(reportCardOutlineOverrides, session.id);
const nextAgentId = shouldPlanFirst ? PLANNER_AGENT_ID : COLLECTOR_AGENT_ID;
setActiveAgentId((current) => (current === nextAgentId ? current : nextAgentId));
}, [reportCardOutlineOverrides, session?.config?.custom_outline, session?.config?.outline_planner, session?.id]);
// The very first research topic: auto-sent once the runtime thread is ready.
// 「提纲预编制」先发给规划员;规划完成后再切到收集员。
useEffect(() => {
const query = pendingInitialQuery.current;
if (historyBrowseOnly || !query || !isChatSession || !collectorThreadId) return;
if (session && session.status !== "draft" && session.status !== "collecting") {
pendingInitialQuery.current = null;
return;
}
if (collectorThreadLoading || collectorStreaming || collectorMessagesLength > 0) return;
const planFirst = outlinePlannerMode === "agent" && !sessionOutline;
if (planFirst && activeAgentId !== PLANNER_AGENT_ID) return;
if (!planFirst && activeAgentId !== COLLECTOR_AGENT_ID) return;
pendingInitialQuery.current = null;
if (session && session.status === "draft") {
void actions.updateStatus.mutate({ sessionId: session.id, status: "collecting" });
}
void sendCollectorMessage(query, {
silentStatusPatch: true,
withDirections: !planFirst,
});
}, [
actions.updateStatus,
activeAgentId,
collectorMessagesLength,
collectorStreaming,
collectorThreadLoading,
collectorThreadId,
historyBrowseOnly,
isChatSession,
outlinePlannerMode,
sendCollectorMessage,
session,
sessionOutline,
]);
// Persist each completed search as it lands in the step list, instead of
// waiting until the whole collection turn finishes and writing 80 rows at once.
useEffect(() => {
collectorSessionIdRef.current = session?.id ?? null;
persistedCollectorToolIds.current = new Set();
persistedCollectorMaterialKeys.current = new Set();
persistedCollectorKey.current = "";
collectorPersistChain.current = Promise.resolve();
pendingCollectAfterPlanRef.current = "";
pendingSearchNudgeRef.current = "";
finishedTurnKey.current = null;
outlinePlanKeyRef.current = "";
inlineWriteTargetIdRef.current = null;
setPendingVariantWriteId(null);
}, [session?.id]);
useEffect(() => {
if (historyBrowseOnly) return;
if (!isChatSession || !session?.id) return;
if (session.status !== "collecting" && session.status !== "draft") return;
const remaining = COLLECTOR_PERSIST_LIMIT - persistedCollectorMaterialKeys.current.size;
if (remaining <= 0) return;
const pending: Record<string, unknown>[] = [];
const claimedToolIds: string[] = [];
const claimedKeys: string[] = [];
for (const message of collectorThread.messages ?? []) {
if (message.type !== "tool" || !message.id) continue;
if (message.name && SKIP_COLLECTOR_PERSIST_TOOLS.has(message.name)) continue;
if (persistedCollectorToolIds.current.has(message.id)) continue;
if (!isCompleteToolPayload(message)) continue;
const rows = snapshotCollectorMaterials([message], {
limit: remaining - pending.length,
includeSummary: false,
});
persistedCollectorToolIds.current.add(message.id);
claimedToolIds.push(message.id);
for (const row of rows) {
const key = collectorMaterialKey(row);
if (!key || persistedCollectorMaterialKeys.current.has(key)) continue;
persistedCollectorMaterialKeys.current.add(key);
claimedKeys.push(key);
pending.push(row);
if (pending.length >= remaining) break;
}
if (pending.length >= remaining) break;
}
if (!pending.length) return;
const sessionId = session.id;
collectorPersistChain.current = collectorPersistChain.current
.then(() => actions.persistCollectorMaterials.mutateAsync({
sessionId,
collectorMaterials: pending,
quiet: true,
}))
.catch(() => {
if (collectorSessionIdRef.current !== sessionId) return;
for (const toolId of claimedToolIds) persistedCollectorToolIds.current.delete(toolId);
for (const key of claimedKeys) persistedCollectorMaterialKeys.current.delete(key);
});
}, [
actions.persistCollectorMaterials,
collectorThread.messages,
historyBrowseOnly,
isChatSession,
session?.id,
session?.status,
]);
// Turn finished without a pending clarification → either ask the collector
// to plan the outline in the message list, or surface the config card.
// Requiring a non-human tail closes the window between the optimistic user
// message and the run flag flipping, where the turn would look "ended".
const collectorMessages = collectorThread.messages;
const collectorTailIsHuman = collectorMessagesLength > 0
&& collectorMessages?.[collectorMessagesLength - 1]?.type === "human";
const showReportConfigCard = isAwaitingReport
&& !inlineWriteDone
&& !pendingInlineWrite
&& !collectorWriteDone
&& !hasWorkbenchWriteTurn
&& !isPlanningOutline
&& (outlinePlannerMode !== "agent"
|| collectAfterPlanStarted
|| retrievalAfterPlanReady
|| (collectionSummaryReady && retrievalToolsReady));
const persistLeftoverCollectorMaterials = useCallback(() => {
if (!session) return [] as Record<string, unknown>[];
const leftover = snapshotCollectorMaterials(collectorThread.messages, {
limit: COLLECTOR_PERSIST_LIMIT,
}).filter((item) => {
const materialKey = collectorMaterialKey(item);
if (!materialKey || persistedCollectorMaterialKeys.current.has(materialKey)) return false;
persistedCollectorMaterialKeys.current.add(materialKey);
return true;
});
persistedCollectorKey.current = `${session.id}:${persistedCollectorMaterialKeys.current.size}`;
return leftover;
}, [collectorThread.messages, session]);
const applyPlannerOutline = useCallback((outline: string) => {
if (!session || !outline.trim()) return;
const next = outline.trim();
const applyKey = `${session.id}:${next}`;
const alreadyApplied = outlinePlanKeyRef.current === applyKey;
setReportCardOutlineOverrides((current) => (
current[session.id] === next ? current : { ...current, [session.id]: next }
));
setAdvancedOptions((current) => (
current.customOutline === next ? current : { ...current, customOutline: next }
));
if (alreadyApplied) return;
outlinePlanKeyRef.current = applyKey;
if (String(session.config?.custom_outline ?? "").trim() === next && session.status !== "draft") {
return;
}
void actions.updateStatus.mutate({
sessionId: session.id,
status: session.status === "awaiting_report" ? "awaiting_report" : "collecting",
customOutline: next,
});
}, [actions.updateStatus, session]);
useEffect(() => {
// Only extract while the outline is still missing. After it is stored,
// calling apply again would mutate the session every render and white-screen
// the chat (Maximum update depth exceeded in ScrollArea).
if (!isPlanningOutline || collectorStreaming || collectorTailIsHuman) return;
if (!session || collectorMessagesLength === 0) return;
const planned = outlineFromLatestAssistant(collectorMessages, extractContentFromMessage);
if (!planned) return;
applyPlannerOutline(planned);
}, [
applyPlannerOutline,
collectorMessages,
collectorMessagesLength,
collectorStreaming,
collectorTailIsHuman,
isPlanningOutline,
session,
]);
useEffect(() => {
if (!isChatSession || !session || collectorStreaming || collectorThreadLoading) return;
if (boundCollectorThreadId !== collectorThreadId) return;
if (activeAgentId !== COLLECTOR_AGENT_ID) return;
if (!shouldAutoCollectAfterPlan({
status: session.status,
outlinePlanner: outlinePlannerMode,
collectAfterPlanStarted,
hasOutline: Boolean(sessionOutline),
messagesReady: collectorMessagesLength > 0,
tailIsHuman: collectorTailIsHuman,
pendingClarification: collectorPendingClarification,
allowAutoActions: !historyBrowseOnly,
hasRetrievalAfterPlan: retrievalAfterPlanReady,
hasCollectionSummary: collectionSummaryReady,
hasRetrievalTools: retrievalToolsReady,
})) return;
const planned = sessionOutline || outlineFromLatestAssistant(collectorMessages, extractContentFromMessage);
if (!planned) return;
const key = `${session.id}:collect:${planned}`;
if (pendingCollectAfterPlanRef.current === key) return;
pendingCollectAfterPlanRef.current = key;
void sendCollectorMessage(buildCollectAfterPlanPrompt(session.query, planned), {
silentStatusPatch: session.status !== "awaiting_report",
hideFromUI: true,
withDirections: false,
withSkills: true,
});
}, [
activeAgentId,
boundCollectorThreadId,
collectAfterPlanStarted,
collectionSummaryReady,
collectorMessages,
collectorMessagesLength,
collectorPendingClarification,
collectorStreaming,
collectorTailIsHuman,
collectorThreadId,
collectorThreadLoading,
historyBrowseOnly,
isChatSession,
outlinePlannerMode,
retrievalAfterPlanReady,
retrievalToolsReady,
sendCollectorMessage,
session,
sessionOutline,
]);
useEffect(() => {
if (!isChatSession || !session || collectorStreaming || collectorThreadLoading) return;
if (boundCollectorThreadId !== collectorThreadId) return;
if (activeAgentId !== COLLECTOR_AGENT_ID) return;
if (!shouldNudgeSearchAfterTerms({
status: session.status,
outlinePlanner: outlinePlannerMode,
collectAfterPlanStarted,
nudgeStarted: searchNudgeStarted,
hasRetrievalAfterPlan: retrievalAfterPlanReady,
hasRetrievalTools: retrievalToolsReady,
messagesReady: collectorMessagesLength > 0,
tailIsHuman: collectorTailIsHuman,
pendingClarification: collectorPendingClarification,
allowAutoActions: !historyBrowseOnly,
})) return;
const key = `${session.id}:search-nudge:${collectorMessagesLength}`;
if (pendingSearchNudgeRef.current === key) return;
pendingSearchNudgeRef.current = key;
void sendCollectorMessage(buildStartSearchAfterTermsPrompt(), {
silentStatusPatch: true,
hideFromUI: true,
withDirections: false,
withSkills: true,
});
}, [
activeAgentId,
boundCollectorThreadId,
collectAfterPlanStarted,
collectorMessagesLength,
collectorPendingClarification,
collectorStreaming,
collectorTailIsHuman,
collectorThreadId,
collectorThreadLoading,
historyBrowseOnly,
isChatSession,
outlinePlannerMode,
retrievalAfterPlanReady,
retrievalToolsReady,
searchNudgeStarted,
sendCollectorMessage,
session,
]);
useEffect(() => {
if (historyBrowseOnly) return;
if (!isChatSession || collectorStreaming || collectorMessagesLength === 0) return;
if (collectorTailIsHuman) return;
if (collectorPendingClarification || isPlanningOutline) return;
if (!shouldFinishCollection({
status: session?.status,
outlinePlanner: outlinePlannerMode,
collectAfterPlanStarted,
hasRetrievalAfterPlan: retrievalAfterPlanReady,
hasRetrievalTools: retrievalToolsReady,
hasCollectionSummary: collectionSummaryReady,
})) return;
const key = `${session?.id ?? ""}:${collectorMessagesLength}`;
if (finishedTurnKey.current === key) return;
finishedTurnKey.current = key;
if (!session) return;
const leftover = persistLeftoverCollectorMaterials();
void actions.updateStatus.mutate({
sessionId: session.id,
status: "awaiting_report",
...(leftover.length ? { collectorMaterials: leftover } : {}),
});
}, [
actions.updateStatus,
collectAfterPlanStarted,
collectionSummaryReady,
collectorMessagesLength,
collectorPendingClarification,
collectorStreaming,
collectorTailIsHuman,
historyBrowseOnly,
isChatSession,
isPlanningOutline,
outlinePlannerMode,
persistLeftoverCollectorMaterials,
retrievalAfterPlanReady,
retrievalToolsReady,
session,
]);
// After a refresh the collector messages reload from the thread. Persist
// anything the incremental writer missed so 「选择结构再生成」 still has rows.
useEffect(() => {
if (historyBrowseOnly) return;
if (!isChatSession || !session?.id) return;
if (pendingWriteJobId || pendingInlineWrite) return;
if (session.status !== "awaiting_report") return;
const leftover = snapshotCollectorMaterials(collectorThread.messages, {
limit: COLLECTOR_PERSIST_LIMIT,
}).filter((item) => {
const materialKey = collectorMaterialKey(item);
if (!materialKey || persistedCollectorMaterialKeys.current.has(materialKey)) return false;
persistedCollectorMaterialKeys.current.add(materialKey);
return true;
});
if (!leftover.length) return;
const persistKey = `${session.id}:${persistedCollectorMaterialKeys.current.size}`;
if (persistedCollectorKey.current === persistKey) return;
persistedCollectorKey.current = persistKey;
void actions.persistCollectorMaterials.mutateAsync({
sessionId: session.id,
collectorMaterials: leftover,
quiet: true,
}).catch(() => {
persistedCollectorKey.current = "";
for (const item of leftover) {
persistedCollectorMaterialKeys.current.delete(collectorMaterialKey(item));
}
});
}, [
actions.persistCollectorMaterials,
collectorThread.messages,
historyBrowseOnly,
isChatSession,
pendingInlineWrite,
pendingWriteJobId,
session?.id,
session?.status,
]);
const collectedMaterialCount = useMemo(
() => countCollectorMaterials(collectorThread.messages),
[collectorThread.messages],
);
const materialCount = Math.max(
collectedMaterialCount,
countEventMaterials(run.events),
sources.data?.items?.length ?? 0,
session?.sourceCount ?? 0,
);
// 对话流的统一注入:配置卡和需要用户操作的计划卡仍走 slot;撰写步骤则构造为
// 普通消息列表的 tool-call 分组,摘要从生成开始就是普通 assistant 消息并随 SSE
// 增量刷新。这样两者都使用 Q&A 原有的消息流与步骤条,而不是在列表中再起一套卡片式会话。
const collectorDisplayThread = useMemo(() => {
const original = (collectorThread.messages ?? []).filter((message) => {
const text = extractContentFromMessage(message);
if (message.type === "human") {
if (message.additional_kwargs?.hide_from_ui === true) return false;
if (message.additional_kwargs?.workbench_write_now === true) return false;
return !isCollectAfterPlanPrompt(text)
&& !isStartSearchAfterTermsPrompt(text)
&& !isWorkbenchWritePrompt(text);
}
if (message.type === "ai" && isWorkbenchWriteEcho(text)) return false;
return true;
});
type Injected = (typeof original)[number];
let base: Injected[] = [...original];
const followUps = messages.data ?? [];
const sessionId = session?.id ?? "draft";
const pushActionCard = (kind: string, suffix = "") => {
base.push({
id: `dr-${kind}-${sessionId}${suffix}`,
type: "ai",
content: "",
additional_kwargs: { setup_research_approval: { kind } },
} as Injected);
};
// A regenerated report has no collector conversation to replay. Seed the
// visible topic bubble only; the normal report job supplies every progress
// step, summary and file card that follows it.
if (isReportVariant && base.length === 0 && session) {
base.push({
id: `dr-regenerate-topic-${sessionId}`,
type: "human",
content: session.query,
} as Injected);
}
const appendFollowUps = () => {
for (const item of followUps) {
base.push({
id: `dr-followup-${item.id}`,
type: item.role === "user" ? "human" : "ai",
content: item.role === "assistant" && item.citationSourceIds.length > 0
? `${item.content}\n\n> 基于 ${item.citationSourceIds.length} 条已选来源回答`
: item.content,
} as Injected);
if (item.role === "assistant" && item.rewriteProposal?.status === "pending") {
base.push({
id: `dr-rewrite-proposal-${item.id}`,
type: "ai",
content: "",
additional_kwargs: {
setup_research_approval: {
kind: "rewrite_proposal",
messageId: item.id,
label: item.rewriteProposal.label,
},
},
} as Injected);
}
}
if (pendingFollowUp) {
base.push({
id: `dr-followup-user-pending-${sessionId}`,
type: "human",
content: pendingFollowUp,
} as Injected);
const rewriteLabel = followUpStream?.rewrite?.label;
base.push({
id: `dr-followup-answer-pending-${sessionId}`,
type: "ai",
content: followUpStream?.content || (rewriteLabel
? `正在生成报告${rewriteLabel}的改写建议…`
: "正在基于报告与已选来源回答…"),
// The follow-up endpoint is not a LangGraph thread stream, but this
// marker lets the existing assistant row use the same incremental
// renderer as a normal Q&A response.
additional_kwargs: { deep_research_follow_up_streaming: true },
} as Injected);
}
};
const appendReportTimeline = ({
target,
targetRun,
jobId,
active,
includeFile,
includeFollowUpRows,
includeWritingProgress = true,
spliceIntoThread = false,
}: {
target: DeepResearchSession;
targetRun: WorkbenchRun;
jobId: string | null;
active: boolean;
includeFile: boolean;
includeFollowUpRows: boolean;
includeWritingProgress?: boolean;
spliceIntoThread?: boolean;
}) => {
const parentLiveReport = (target.reportMarkdown || run.report || inlineReport?.reportText || "").trim();
const writeFinished = target.id === session?.id
? inlineWriteDone
: target.status === "completed";
const completed = writeFinished && (
Boolean(parentLiveReport)
|| (target.id === session?.id && collectorWriteDone)
|| Boolean(target.reportMarkdown)
);
const completedSession = completed
? { ...target, reportMarkdown: target.reportMarkdown || parentLiveReport, status: "completed" as const }
: target;
const awaitingReview = target.status === "awaiting_input";
if (includeWritingProgress && (active || awaitingReview || completed)) {
const progressMessage = {
id: `dr-writing-progress-${target.id}-${jobId ?? target.id}`,
type: "ai",
content: "",
tool_calls: buildWritingProgressToolCalls({
phase: completed ? "done" : targetRun.phase,
materialCount: Math.max(materialCount, target.sourceCount),
error: targetRun.error,
thinking: targetRun.reportThinking,
summaryThinking: targetRun.summaryThinking,
events: targetRun.events,
requestedImageCount: requestedReportImageCount(target.config),
}),
} as Injected;
// Same splice as Q&A writing mode: bar sits after `deep_research_report`
// and before the model's wrap-up, so the summary is never above the steps.
base = spliceIntoThread
? composeResearchDisplayMessages(base, [progressMessage])
: [...base, progressMessage];
}
if (awaitingReview && jobId) pushActionCard("plan_review", `-${jobId}`);
if (["failed", "cancelled"].includes(target.status)) pushActionCard("failed", `-${jobId ?? target.id}`);
const streamingSummary = active && targetRun.phase === "summarizing";
if (streamingSummary || completed) {
base.push({
id: `dr-report-summary-${sessionId}-${jobId ?? target.id}`,
type: "ai",
content: completed
? buildCompletedReportMessage({
sourceCount: Math.max(materialCount, target.sourceCount),
summaryText: targetRun.summaryText,
imageCount: countEmbeddedReportImages(completedSession.reportMarkdown),
})
: buildStreamingSummaryMessage(targetRun.summaryText, targetRun.summaryThinking),
additional_kwargs: streamingSummary
? { deep_research_summary_streaming: true }
: undefined,
} as Injected);
}
if (completed) {
pushActionCard("regenerate_report", `-${jobId ?? target.id}`);
if (includeFile) {
base.push({
id: `dr-report-file-${sessionId}-${jobId ?? target.id}`,
type: "ai",
content: "",
tool_calls: [{
id: `dr-report-file-${sessionId}-${jobId ?? target.id}-present`,
name: "present_files",
args: { filepaths: [
completedSession.reportMarkdown
? reportCardDisplayPath(completedSession)
: RESEARCH_REPORT_FILE,
] },
}],
} as Injected);
}
if (includeFollowUpRows) appendFollowUps();
}
};
if (showReportConfigCard) pushActionCard("config");
if (generatedReportVariants.length > 0 && session) {
// Keep the original conversation intact, then append each independent
// generation in chronological order beneath it. Persisted children make
// this layout survive refreshes and history navigation.
appendReportTimeline({
target: session,
targetRun: inlineGeneratedReport?.parentSessionId === session.id
? inlineGeneratedReport.parentRun
: inlineGenerationSession
? EMPTY_RUN
: run,
jobId: typeof session.usage?.lastJobId === "string" ? session.usage.lastJobId : null,
active: false,
includeFile: true,
includeFollowUpRows: true,
// The original writing bar sits above the file card. A new report's
// live bar must come after that card, so skip the parent's steps here.
includeWritingProgress: false,
});
for (const variant of generatedReportVariants) {
const ownsLiveRun = inlineGenerationSession?.id === variant.id;
appendReportTimeline({
target: variant,
targetRun: ownsLiveRun ? run : EMPTY_RUN,
jobId: variant.activeJobId
?? (typeof variant.usage?.lastJobId === "string" ? variant.usage.lastJobId : null),
active: !historyBrowseOnly && ownsLiveRun && (
variant.status === "running"
|| variant.status === "awaiting_input"
|| pendingVariantWriteId === variant.id
),
// Child files use session-aware cards below MessageList so clicking
// one can never open the parent's report.md by mistake.
includeFile: false,
includeFollowUpRows: false,
});
}
} else if (session) {
appendReportTimeline({
target: session,
targetRun: run,
jobId: streamJobId,
active: isRunning && !historyBrowseOnly,
includeFile: true,
includeFollowUpRows: true,
spliceIntoThread: true,
});
}
return { ...collectorThread, messages: base } as typeof collectorThread;
}, [
collectorThread,
generatedReportVariants,
inlineGeneratedReport,
inlineGenerationSession,
showReportConfigCard,
isRunning,
isReportVariant,
materialCount,
messages.data,
pendingFollowUp,
followUpStream,
historyBrowseOnly,
run.error,
run.events,
run.phase,
run.reportThinking,
run.summaryText,
run.summaryThinking,
run.report,
inlineReport,
session,
streamJobId,
collectorWriteDone,
inlineWriteDone,
pendingVariantWriteId,
]);
// 对话还没有任何消息时显示欢迎屏(对齐 AI 写作空状态)。
const collectorEmpty = collectorMessagesLength === 0
&& !collectorStreaming
&& !collectorThreadLoading
&& !isReportVariant;
// 首 token 到达前的「正在整理…」占位:收集员在跑但当前助手回合还没有任何
// 可见输出(无答案文本、无思考、无工具调用)——避免用户以为卡死。
const showThinkingPlaceholder = useMemo(() => {
if (historyBrowseOnly || !collectorStreaming) return false;
const last = collectorMessages?.[collectorMessagesLength - 1];
if (!last || last.type !== "ai") return true; // 还停在用户消息,AI 尚未开口
if (hasOnlyInternalToolCalls(last)) return true;
const hasOutput =
Boolean(extractContentFromMessage(last).trim()) ||
Boolean(extractReasoningContentFromMessage(last)) ||
hasVisibleToolCalls(last);
return !hasOutput;
}, [collectorMessages, collectorMessagesLength, collectorStreaming, historyBrowseOnly]);
// ── writing-job SSE (legacy timeline + regenerate-variant jobs only) ──────
useEffect(() => {
if (historyBrowseOnly) return;
if (pendingInlineWrite || pendingVariantWriteId) return;
const replayingTerminalTrace = session?.status === "completed" && !activeJobId;
if (!streamJobId || (!isRunning && !isAwaitingReview && !replayingTerminalTrace)) return;
if (replayingTerminalTrace && replayedTraceJobs.current.has(streamJobId)) return;
if (replayingTerminalTrace) replayedTraceJobs.current.add(streamJobId);
const keepCurrentSandbox = Boolean(
inlineGenerationSessionRef.current && sandboxSessionId !== inlineGenerationSessionRef.current.id,
);
const jobChanged = boundStreamJobRef.current !== streamJobId;
if (jobChanged) {
boundStreamJobRef.current = streamJobId;
seenEventKeys.current = new Set();
liveEventSerial.current = 0;
pendingReportEvents.current = [];
setRun(emptyRunForJob(streamJobId));
// Only close the sandbox when a *new* job starts. Reconnecting the same
// write stream used to wipe the live draft and flip auto-open off, so
// thinking could finish while the right panel stayed closed.
if (!replayingTerminalTrace && !keepCurrentSandbox) setSandboxOpen(false);
}
const flushReportEvents = () => {
reportAnimationFrame.current = null;
const queued = pendingReportEvents.current.splice(0);
if (!queued.length) return;
setRun((current) => {
if (current.jobId !== streamJobId) return current;
let report = current.report;
let reportVersion = current.reportVersion;
let reportTargets = current.reportTargets;
let planText = current.planText;
let planReasoning = current.planReasoning;
let reportThinking = current.reportThinking;
let summaryThinking = current.summaryThinking;
let summaryText = current.summaryText;
let phase = current.phase;
for (const event of queued) {
phase = event.phase || phase;
if (event.type === "plan_delta" && event.phase === "planning") {
planText += typeof event.payload.delta === "string" ? event.payload.delta : "";
continue;
}
if (event.type === "plan_reasoning" && event.phase === "planning") {
planReasoning += typeof event.payload.delta === "string" ? event.payload.delta : "";
continue;
}
if (event.type === "summary_thinking" || (event.type === "report_thinking" && event.phase === "summarizing")) {
summaryThinking += typeof event.payload.delta === "string" ? event.payload.delta : "";
continue;
}
if (event.type === "report_thinking") {
reportThinking += typeof event.payload.delta === "string" ? event.payload.delta : "";
continue;
}
if (event.type === "summary_delta") {
summaryText += typeof event.payload.delta === "string" ? event.payload.delta : "";
continue;
}
if (event.type === "summary_completed") {
summaryText = typeof event.payload.summary === "string" ? event.payload.summary : summaryText;
continue;
}
if (event.type === "report_reset") {
report = "";
reportTargets = {};
reportThinking = "";
reportVersion = typeof event.payload.reportVersion === "number" ? event.payload.reportVersion : reportVersion + 1;
continue;
}
const version = typeof event.payload.reportVersion === "number" ? event.payload.reportVersion : reportVersion;
if (version < reportVersion) continue;
const target = typeof event.payload.target === "string" ? event.payload.target : "report";
const currentTarget = reportTargets[target];
if (!currentTarget || version >= currentTarget.version) {
const content = version === currentTarget?.version
? appendReportDelta(currentTarget.content, typeof event.payload.delta === "string" ? event.payload.delta : "", event.payload.offset)
: String(event.payload.delta ?? "");
reportTargets = { ...reportTargets, [target]: { content, version } };
report = assembleStreamingReport(reportTargets);
reportVersion = Math.max(reportVersion, version);
}
}
return { ...current, report, reportTargets, reportVersion, phase, planText, planReasoning, reportThinking, summaryThinking, summaryText };
});
};
const stop = streamJob(
streamJobId,
{
onEvent: (event) => {
const key = event.seq === 0 && !event.liveId
? `live-arrival:${++liveEventSerial.current}`
: eventKey(event);
if (seenEventKeys.current.has(key)) return;
seenEventKeys.current.add(key);
const firstWriteToken = (
event.type === "report_delta" || event.type === "report_chunk"
) && typeof event.payload?.delta === "string" && event.payload.delta.trim();
if (firstWriteToken && !keepCurrentSandbox) {
setSandboxOpen(true);
openReportRef.current();
}
if (
event.type === "plan_delta" ||
event.type === "plan_reasoning" ||
event.type === "report_thinking" ||
event.type === "summary_thinking" ||
event.type === "report_delta" ||
event.type === "report_chunk" ||
event.type === "report_reset" ||
event.type === "summary_delta" ||
event.type === "summary_completed"
) {
pendingReportEvents.current.push(event);
if (reportAnimationFrame.current === null) {
reportAnimationFrame.current = window.requestAnimationFrame(flushReportEvents);
}
return;
}
setRun((current) => {
if (current.jobId !== streamJobId) return current;
return {
...current,
// The trace is an audit-friendly research record. Keep every
// durable event for this bounded job instead of trimming older
// query/source rows while the report is still running.
events: [...current.events, event],
phase: event.phase || current.phase,
};
});
if (event.type === "awaiting_input") void refetchSession();
},
onTerminal: () => {
if (!replayingTerminalTrace) replayedTraceJobs.current.add(streamJobId);
const liveInline = inlineGenerationSessionRef.current;
if (liveInline) {
void getResearchSession(liveInline.id).then((completed) => {
setInlineGeneratedReport((current) => current?.session.id === completed.id
? { ...current, session: completed }
: current);
setRewriteTargetSession(completed);
}).catch((error) => {
console.error("刷新新报告状态失败:", error);
});
}
refetchLiveJobRef.current();
},
onError: (detail) => setRun((current) => current.jobId === streamJobId ? { ...current, error: detail } : current),
},
0,
);
return () => {
stop();
if (reportAnimationFrame.current !== null) {
window.cancelAnimationFrame(reportAnimationFrame.current);
reportAnimationFrame.current = null;
}
pendingReportEvents.current = [];
};
}, [activeJobId, historyBrowseOnly, isAwaitingReview, isRunning, pendingInlineWrite, pendingVariantWriteId, sandboxSessionId, session?.status, streamJobId]);
useEffect(() => {
if (historyBrowseOnly) return;
if (!inlineReport) return;
const writeCompleted = inlineReport.status === "success"
|| (inlineReport.phase === "done" && Boolean(inlineReport.reportText?.trim()));
const phase = inlineReport.status === "success" || writeCompleted
? "done"
: inlineReport.status === "error"
? "failed"
: (inlineReport.phase || undefined);
setRun((current) => {
const jobId = inlineReport.jobId || current.jobId;
const nextPhase = phase || current.phase;
if (
current.jobId === jobId
&& current.phase === nextPhase
&& current.report === inlineReport.reportText
&& current.reportThinking === inlineReport.thinking
&& current.error === (writeCompleted ? undefined : inlineReport.error)
) {
return current;
}
return {
...current,
jobId,
phase: nextPhase,
report: inlineReport.reportText || current.report,
reportThinking: inlineReport.thinking,
error: writeCompleted ? undefined : inlineReport.error,
events: current.events.length > 0 ? current.events : [localWriteJobStartedEvent(jobId || `inline-${session?.id ?? "draft"}`)],
};
});
if (inlineReport.status !== "active" || writeCompleted) {
const persistSessionId = inlineWriteTargetIdRef.current;
if (writeCompleted && persistSessionId) {
const reportText = inlineReport.reportText || (
persistSessionId === session?.id ? session.reportMarkdown : ""
);
patchCachedResearchSession(queryClient, persistSessionId, {
status: "completed",
reportMarkdown: reportText,
error: undefined,
activeJobId: undefined,
});
if (persistSessionId !== session?.id) {
setInlineGeneratedReport((current) => (
current && current.session.id === persistSessionId
? {
...current,
session: {
...current.session,
status: "completed",
reportMarkdown: reportText,
activeJobId: undefined,
},
}
: current
));
setPendingVariantWriteId(null);
}
} else if (inlineReport.status === "error") {
setPendingVariantWriteId(null);
}
if (inlineReport.status === "success" || inlineReport.status === "error" || writeCompleted) {
void Promise.all([
refetchSession(),
refetchSessions(),
...(persistSessionId && persistSessionId !== session?.id ? [refetchReportVariants()] : []),
]);
}
}
}, [
historyBrowseOnly,
inlineReport,
pendingVariantWriteId,
queryClient,
refetchReportVariants,
refetchSession,
refetchSessions,
session?.id,
session?.reportMarkdown,
]);
useEffect(() => {
if (!session?.reportMarkdown) return;
// A background regeneration writes into `run` for the child job. Do not
// copy the parent markdown over that live stream.
if (inlineGenerationSession && inlineGenerationSession.id !== session.id) return;
// A new write must start from a blank sandbox. Copying the previous
// durable report into `run` opened the panel with stale text, then the
// model only thought (summary / reasoning) and the sandbox never grew.
if (isRunning || isAwaitingReview) return;
const lastJobId = typeof session.usage?.lastJobId === "string" ? session.usage.lastJobId : null;
setRun((current) => {
if (current.jobId !== streamJobId) return current;
if (current.jobId && lastJobId !== current.jobId) return current;
if (current.report === session.reportMarkdown) return current;
return { ...current, report: session.reportMarkdown! };
});
}, [inlineGenerationSession, isAwaitingReview, isRunning, session?.id, session?.reportMarkdown, session?.usage?.lastJobId, streamJobId]);
// ── actions ────────────────────────────────────────────────────────────────
const handleNewResearch = useCallback(() => {
followUpAbortRef.current?.abort();
followUpAbortRef.current = null;
setHistoryBrowseOnly(false);
setAdvancedOptions(DEFAULT_ADVANCED_OPTIONS);
outlinePlanKeyRef.current = "";
pendingCollectAfterPlanRef.current = "";
pendingSearchNudgeRef.current = "";
setActiveAgentId(COLLECTOR_AGENT_ID);
setSelectedId(null);
setDownloadTargetSession(null);
setInlineGeneratedReport(null);
setNewReportSandboxSessionId(null);
setRewriteTargetSession(null);
setRun(EMPTY_RUN);
setPendingWriteJobId(null);
setPendingInlineWrite(false);
setPendingVariantWriteId(null);
setSandboxOpen(false);
setPendingFollowUp(null);
setFollowUpStream(null);
pendingInitialQuery.current = null;
finishedTurnKey.current = null;
inlineWriteTargetIdRef.current = null;
persistedCollectorKey.current = "";
persistedCollectorToolIds.current = new Set();
persistedCollectorMaterialKeys.current = new Set();
collectorPersistChain.current = Promise.resolve();
}, []);
// 历史报告不抢占对话区域:切换研究记录时总是先折叠右侧沙箱;用户可通过
// 消息流里的 report.md 文件卡(或顶部“报告”按钮)显式打开对应会话的内容。
const handleSelectResearch = useCallback((id: string) => {
followUpAbortRef.current?.abort();
followUpAbortRef.current = null;
setHistoryBrowseOnly(true);
setSelectedId(id);
setDownloadTargetSession(null);
setInlineGeneratedReport(null);
setNewReportSandboxSessionId(null);
setRewriteTargetSession(null);
setRun(EMPTY_RUN);
setPendingWriteJobId(null);
setPendingInlineWrite(false);
setPendingVariantWriteId(null);
setSandboxOpen(false);
setPendingFollowUp(null);
setFollowUpStream(null);
pendingInitialQuery.current = null;
}, []);
const handleCreate = useCallback(async (query: string) => {
if (!query) return;
setHistoryBrowseOnly(false);
const modelConfig = selectedModel
? { fast_model: selectedModel, smart_model: selectedModel, strategic_model: selectedModel }
: {};
try {
if (classicMode) {
// 经典模式 rollback: the original auto-start pipeline, unchanged.
const created = await actions.create.mutateAsync({
query,
config: {
collection_mode: "legacy",
...modelConfig,
...buildReportCardConfig(mode, generateImages, advancedOptions),
},
});
setSelectedId(created.id);
setSandboxOpen(false);
await actions.startJob.mutateAsync({ sessionId: created.id });
toast.success("深度研究已启动");
return;
}
// Chat collection: freeze model + advanced defaults into the snapshot;
// the collector conversation starts as soon as the thread is ready, and
// the report config card re-offers every option at write time.
const created = await actions.create.mutateAsync({
query,
config: { collection_mode: "chat", ...modelConfig, ...buildReportCardConfig("basic", generateImages, advancedOptions), llmwiki_knowledge_base_ids: draftKnowledgeBaseIds, knowledge_retrieval_mode: draftRetrievalMode },
});
pendingInitialQuery.current = query;
finishedTurnKey.current = null;
pendingCollectAfterPlanRef.current = "";
pendingSearchNudgeRef.current = "";
inlineWriteTargetIdRef.current = null;
setPendingVariantWriteId(null);
persistedCollectorKey.current = "";
persistedCollectorToolIds.current = new Set();
persistedCollectorMaterialKeys.current = new Set();
collectorPersistChain.current = Promise.resolve();
setSelectedId(created.id);
setSandboxOpen(false);
} catch (error) {
toast.error(error instanceof Error ? error.message : "启动研究失败");
}
}, [actions, advancedOptions, classicMode, generateImages, mode, selectedModel, draftKnowledgeBaseIds, draftRetrievalMode]);
const handleFollowUp = useCallback(async (message: string) => {
if (!session || !message) return;
setHistoryBrowseOnly(false);
const controller = new AbortController();
followUpAbortRef.current = controller;
setPendingFollowUp(message);
setFollowUpStream({ content: "", rewrite: null });
let streamedContent = "";
let rewrite: FollowUpRewritePreview | null = null;
const isRewriteRequest = isExplicitReportRewriteInstruction(message);
const streamInteraction = isRewriteRequest
? streamResearchRewrite
: streamResearchMessage;
try {
await streamInteraction(
session.id,
message,
{
onEvent: (event) => {
if (event.type === "start") {
rewrite = event.rewrite ?? null;
setFollowUpStream({ content: "", rewrite });
return;
}
if (event.type === "delta") {
streamedContent += event.delta ?? "";
setFollowUpStream({ content: streamedContent, rewrite });
return;
}
if (event.type === "complete") {
if (event.assistant?.content) streamedContent = event.assistant.content;
setFollowUpStream({ content: streamedContent, rewrite: event.rewrite ?? rewrite });
}
},
},
controller.signal,
);
await Promise.all([messages.refetch(), refetchSession(), refetchSessions()]);
} catch (error) {
if (!controller.signal.aborted) {
toast.error(error instanceof Error ? error.message : isRewriteRequest ? "报告改写失败" : "报告追问失败");
}
} finally {
if (followUpAbortRef.current === controller) {
followUpAbortRef.current = null;
setPendingFollowUp(null);
setFollowUpStream(null);
}
}
}, [messages, refetchSession, refetchSessions, session]);
const handleStopFollowUp = useCallback(() => {
followUpAbortRef.current?.abort();
}, []);
const handleStartFullReportRewrite = useCallback(
async (input: {
instruction: string;
style: "formal_analysis" | "professional" | "concise" | "readable";
modelName: string | null;
reportOutline: string;
structureMode?: ReportStructureMode;
createNewReport?: boolean;
}) => {
if (!session) {
toast.error("请先完成报告生成后再进行全文改写。");
return;
}
setHistoryBrowseOnly(false);
const isNewReport = input.createNewReport === true;
const sourceSession = isNewReport ? session : (rewriteTargetSession ?? session);
if (!sourceSession.reportMarkdown?.trim()) {
toast.error("请先完成报告生成后再进行全文改写。");
return;
}
let targetSession = sourceSession;
if (isNewReport) {
const threadId = session.runtimeThreadId;
if (!threadId) {
toast.error("当前会话没有写作线程,无法按新结构生成。");
return;
}
try {
// Fork first so the parent report stays untouched, then write through
// the same LangGraph pipeline as 「开始撰写」. The MySQL/SSE job path
// is what freezes on the production gateway.
const parentRunSnapshot = run;
targetSession = await createResearchReportVariant(session.id, {
reportOutline: input.reportOutline || undefined,
structureMode: input.structureMode,
});
reportDocumentRewrite.reset();
const toneByStyle = {
formal_analysis: "analytical",
professional: "objective",
concise: "objective",
readable: "objective",
} as const;
const inlineJobId = `inline-${targetSession.id}`;
const runningTarget: DeepResearchSession = {
...targetSession,
status: "running",
activeJobId: undefined,
};
if (collectorThreadId) clearResearchReportStream(collectorThreadId);
inlineWriteTargetIdRef.current = targetSession.id;
setPendingVariantWriteId(targetSession.id);
setActiveAgentId(COLLECTOR_AGENT_ID);
setInlineGeneratedReport({
parentSessionId: session.id,
session: runningTarget,
parentRun: parentRunSnapshot,
});
setNewReportSandboxSessionId(targetSession.id);
setRewriteTargetSession(session);
setRun(emptyRunForJob(inlineJobId));
await collectorSendMessage(
threadId,
{ text: `${WORKBENCH_WRITE_PROMPT_MARKER}。按新结构撰写研究报告。课题:${session.query}`, files: [] },
{
...(input.modelName || selectedModel
? { model_name: input.modelName || selectedModel || undefined }
: {}),
agent_id: COLLECTOR_AGENT_ID,
writing_mode: true,
workbench_write_now: true,
workbench_session_id: targetSession.id,
writing_report_config: {
topic: session.query,
custom_outline: input.reportOutline || undefined,
structure_mode: input.structureMode,
report_instruction: input.instruction,
tone: toneByStyle[input.style],
},
thinking_enabled: true,
},
{
additionalKwargs: {
hide_from_ui: true,
workbench_write_now: true,
workbench_topic: session.query,
workbench_focus: input.instruction,
},
},
);
await Promise.all([refetchSessions(), refetchReportVariants()]);
return;
} catch (error) {
inlineWriteTargetIdRef.current = session.id;
setPendingVariantWriteId(null);
setInlineGeneratedReport(null);
setNewReportSandboxSessionId(null);
toast.error(error instanceof Error ? error.message : "创建新结构报告失败");
return;
}
}
const targetReport = targetSession.reportMarkdown?.trim();
if (!targetReport) {
toast.error("新报告快照创建失败,请稍后重试。");
return;
}
// Clear the current rewrite draft before changing the sandbox identity.
// `useReportSandbox` treats the new id as a separate file, so no parent
// report remains visible during the provider's first-token delay.
reportDocumentRewrite.reset();
if (inlineGeneratedReport?.session.id !== targetSession.id) {
// A normal rewrite of the parent must return sandbox ownership to the
// parent; only an inline generated fork continues to own it.
setNewReportSandboxSessionId(null);
}
setSandboxOpen(false);
const presentationId = rewritePresentation?.create({
threadId: collectorThreadId ?? session.id,
operation: "rewrite",
source: { kind: "deep_research_report", id: targetSession.id, path: "report.md" },
fileName: "report.md",
instruction: input.instruction,
style: input.style,
modelName: input.modelName,
});
reportRewritePresentationId.current = presentationId ?? null;
reportRewriteJobId.current = null;
void reportDocumentRewrite.start(
{
threadId: collectorThreadId ?? session.id,
path: REPORT_OUTPUT_PATH,
instruction: input.instruction,
style: input.style,
modelName: input.modelName ?? undefined,
reportOutline: input.reportOutline || undefined,
structureMode: input.structureMode,
},
{
stream: (signal) =>
streamFullResearchReportRewrite(
targetSession.id,
{
operation: "rewrite",
instruction: input.instruction,
style: input.style,
modelName: input.modelName ?? undefined,
reportOutline: input.reportOutline || undefined,
structureMode: input.structureMode,
},
signal,
(jobId) => {
reportRewriteJobId.current = jobId;
},
),
onEvent: (event) => updateFullReportRewritePresentation(presentationId ?? null, event),
onCommitted: (rewritten, { versionSnapshotFailed }) => {
setRun((current) => ({ ...current, report: rewritten }));
if (versionSnapshotFailed) {
console.error(
"报告全文改写已完成,但撤销版本快照保存失败。",
versionSnapshotFailed,
);
} else {
toast.success("报告全文改写完成,已安全替换原报告。");
}
if (targetSession.config?.report_variant === true) {
const completedSession = {
...targetSession,
reportMarkdown: rewritten,
status: "completed" as const,
};
setInlineGeneratedReport((current) => current && current.session.id === targetSession.id
? { ...current, session: completedSession }
: current);
setRewriteTargetSession(completedSession);
setNewReportSandboxSessionId(targetSession.id);
setSandboxOpen(true);
void Promise.all([refetchSessions(), refetchReportVariants()]);
return;
}
void Promise.all([refetchSession(), refetchSessions(), messages.refetch()]);
},
},
);
},
[
collectorSendMessage,
collectorThreadId,
createResearchReportVariant,
inlineGeneratedReport,
messages,
refetchSession,
refetchReportVariants,
refetchSessions,
reportDocumentRewrite,
rewriteTargetSession,
rewritePresentation,
run,
selectedModel,
session,
updateFullReportRewritePresentation,
],
);
const handleOpenReportRegeneration = useCallback(() => {
if (!session?.reportMarkdown || reportDocumentRewrite.isActive) return;
setRewriteTargetSession(session);
setDocumentRewriteDialogPurpose("regenerate");
setDocumentRewriteDialogRequest((current) => current + 1);
}, [reportDocumentRewrite.isActive, session?.reportMarkdown]);
const handleOpenFullReportRewrite = useCallback((targetSession?: DeepResearchSession) => {
const rewriteTarget = targetSession ?? session;
if (!rewriteTarget?.reportMarkdown || reportDocumentRewrite.isActive) return;
setRewriteTargetSession(rewriteTarget);
setSandboxOpen(true);
setDocumentRewriteDialogPurpose("rewrite");
setDocumentRewriteDialogRequest((current) => current + 1);
}, [reportDocumentRewrite.isActive, session?.reportMarkdown]);
useEffect(() => {
const handleRequestedReportRewrite = (event: Event) => {
const detail = (event as CustomEvent<{ sessionId?: string }>).detail;
const inlineTarget = generatedReportVariants.find((item) => item.id === detail?.sessionId) ?? null;
if (detail?.sessionId === session?.id) {
handleOpenFullReportRewrite(session);
} else if (inlineTarget) {
handleOpenFullReportRewrite(inlineTarget);
}
};
window.addEventListener(DEEP_RESEARCH_REPORT_REWRITE_REQUESTED_EVENT, handleRequestedReportRewrite);
return () => window.removeEventListener(DEEP_RESEARCH_REPORT_REWRITE_REQUESTED_EVENT, handleRequestedReportRewrite);
}, [generatedReportVariants, handleOpenFullReportRewrite, session]);
const handleCancelFullReportRewrite = useCallback(() => {
const jobId = reportRewriteJobId.current;
if (jobId) {
// Aborting an SSE connection alone deliberately does not cancel a
// durable rewrite (refresh must be safe); this explicit user action does.
void cancelFullResearchReportRewrite(jobId).catch(() => undefined);
}
reportDocumentRewrite.cancel();
const presentationId = reportRewritePresentationId.current;
if (presentationId && rewritePresentation) {
rewritePresentation.update(presentationId, {
stage: "cancelled",
error: "已停止全文改写,原报告未被修改。",
});
}
}, [reportDocumentRewrite, rewritePresentation]);
const handleRewriteProposal = useCallback(async (
messageId: string,
action: "apply" | "dismiss",
) => {
if (!session) return;
try {
await actions.resolveRewriteProposal.mutateAsync({
sessionId: session.id,
messageId,
action,
});
await Promise.all([messages.refetch(), refetchSession(), refetchSessions()]);
if (action === "apply") {
handleOpenSandbox();
toast.success("已将改写内容替换到报告对应位置");
} else {
toast.success("已保留报告原文");
}
} catch (error) {
toast.error(error instanceof Error ? error.message : "处理改写建议失败");
}
}, [actions.resolveRewriteProposal, handleOpenSandbox, messages, refetchSession, refetchSessions, session]);
const handleCancelJob = useCallback(async () => {
if (!activeJobId) return;
try {
await actions.cancelJob.mutateAsync(activeJobId);
setPendingWriteJobId(null);
toast.success("已停止撰写");
await Promise.all([refetchSession(), refetchSessions()]);
} catch (error) {
const message = error instanceof Error ? error.message : "停止研究失败";
if (/not in a cancellable state/i.test(message) || /409/.test(message)) {
setPendingWriteJobId(null);
toast.success("已停止撰写");
await Promise.all([refetchSession(), refetchSessions()]);
return;
}
toast.error(message);
}
}, [actions.cancelJob, activeJobId, refetchSession, refetchSessions]);
const handleStopCollector = useCallback(async () => {
try {
await collectorThread.stop();
if (collectorThreadId) await stopThreadRun(collectorThreadId);
} catch {
// Aborting an already-finished run is harmless.
}
}, [collectorThread, collectorThreadId]);
const handlePlanReview = useCallback(async (action: "approve" | "revise", feedback?: string) => {
if (!activeJobId) return;
setHistoryBrowseOnly(false);
try {
await actions.resumeJob.mutateAsync({ jobId: activeJobId, action, payload: feedback ? { feedback } : {} });
toast.success(action === "approve" ? "研究计划已确认" : "已提交计划调整意见");
await refetchSession();
} catch (error) {
toast.error(error instanceof Error ? error.message : "提交失败");
}
}, [actions.resumeJob, activeJobId, refetchSession]);
const handleReopenReportCard = useCallback(async () => {
if (!session) return;
setHistoryBrowseOnly(false);
try {
await actions.updateStatus.mutateAsync({
sessionId: session.id,
status: "awaiting_report",
collectorMaterials: snapshotCollectorMaterials(collectorThread.messages, {
limit: COLLECTOR_PERSIST_LIMIT,
}),
});
await refetchSession();
} catch (error) {
toast.error(error instanceof Error ? error.message : "打开报告配置失败");
}
}, [actions.updateStatus, collectorThread.messages, refetchSession, session]);
const handleConfirmReportCard = useCallback(async (
config: Record<string, unknown>,
extras?: { writeWithoutMaterials?: boolean },
) => {
const threadId = session?.runtimeThreadId;
if (!session || !threadId) return;
setHistoryBrowseOnly(false);
const writeWithoutMaterials = extras?.writeWithoutMaterials === true;
const collectorMaterials = writeWithoutMaterials
? []
: snapshotCollectorMaterials(collectorThread.messages, { limit: WRITE_FALLBACK_MATERIAL_LIMIT });
console.warn("[深度研究] inline_write_starting", {
sessionId: session.id,
threadId,
messageCount: collectorThread.messages?.length ?? 0,
snapshotCount: collectorMaterials.length,
writeWithoutMaterials,
});
setActiveAgentId(COLLECTOR_AGENT_ID);
inlineWriteTargetIdRef.current = session.id;
setPendingInlineWrite(true);
setSandboxOpen(false);
setRun(emptyRunForJob(`inline-${session.id}`));
try {
if (!writeWithoutMaterials && collectorMaterials.length > 0) {
void actions.persistCollectorMaterials.mutateAsync({
sessionId: session.id,
collectorMaterials,
quiet: true,
}).catch(() => undefined);
}
await collectorSendMessage(
threadId,
{ text: `${WORKBENCH_WRITE_PROMPT_MARKER}。课题:${session.query}`, files: [] },
{
...(selectedModel ? { model_name: selectedModel } : {}),
agent_id: COLLECTOR_AGENT_ID,
writing_mode: true,
workbench_write_now: true,
workbench_session_id: session.id,
writing_report_config: { ...config, topic: session.query },
force_no_materials: writeWithoutMaterials,
thinking_enabled: config.thinking_enabled !== false,
},
{
additionalKwargs: {
hide_from_ui: true,
workbench_write_now: true,
workbench_topic: session.query,
},
},
);
if (writeWithoutMaterials) {
toast.warning("已按无素材模式启动撰写,对话里收集到的资料本次不会送入写作。");
}
} catch (error) {
setPendingInlineWrite(false);
console.error("[深度研究] inline_write_failed", {
sessionId: session.id,
query: session.query,
detail: error instanceof Error ? error.message : String(error),
error,
});
toast.error(error instanceof Error ? error.message : "启动报告撰写失败");
}
}, [actions.persistCollectorMaterials, collectorSendMessage, collectorThread.messages, selectedModel, session]);
const handleRestartLegacy = useCallback(async () => {
if (!session) return;
setHistoryBrowseOnly(false);
if (session.runtimeThreadId) {
await handleConfirmReportCard((session.config ?? {}) as Record<string, unknown>);
return;
}
try {
await actions.startJob.mutateAsync({ sessionId: session.id });
setSandboxOpen(false);
toast.success("已重新开始研究");
} catch (error) {
toast.error(error instanceof Error ? error.message : "重新开始失败");
}
}, [actions.startJob, handleConfirmReportCard, session]);
const handleContinueCollecting = useCallback(() => {
document.getElementById("deep-research-composer")?.focus();
}, []);
const updateAdvancedOption = useCallback(
<K extends keyof AdvancedResearchOptions>(key: K, value: AdvancedResearchOptions[K]) => {
setAdvancedOptions((current) => ({ ...current, [key]: value }) as AdvancedResearchOptions);
if (!session?.id) return;
if (key === "customOutline") {
setReportCardOutlineOverrides((current) => (
current[session.id] === value
? current
: { ...current, [session.id]: value as string }
));
}
if (key === "structureMode") {
setReportCardStructureModeOverrides((current) => (
current[session.id] === value
? current
: { ...current, [session.id]: value as ReportStructureMode }
));
}
if (key === "retrievalDirections") {
const next = normalizeRetrievalDirections(value);
setReportCardRetrievalDirectionsOverrides((current) => {
const prev = current[session.id];
if (prev && prev.join("\n") === next.join("\n")) return current;
return { ...current, [session.id]: next };
});
}
if (key === "retrievalSkills") {
const next = normalizeRetrievalSkills(value);
setReportCardRetrievalSkillsOverrides((current) => {
const prev = current[session.id];
if (prev && prev.join("\n") === next.join("\n")) return current;
return { ...current, [session.id]: next };
});
}
},
[session?.id],
);
const applyReportStructure = useCallback((content: string, structureMode: ReportStructureMode, retrievalDirections: string[] = [], retrievalSkills: string[] = []) => {
updateAdvancedOption("customOutline", content);
updateAdvancedOption("structureMode", structureMode);
updateAdvancedOption("retrievalDirections", normalizeRetrievalDirections(retrievalDirections));
updateAdvancedOption("retrievalSkills", normalizeRetrievalSkills(retrievalSkills));
}, [updateAdvancedOption]);
const handleDelete = useCallback(async (id: string) => {
try {
await actions.delete.mutateAsync(id);
if (selectedId === id) handleNewResearch();
toast.success("研究记录已删除");
} catch (error) {
toast.error(error instanceof Error ? error.message : "删除失败");
}
}, [actions.delete, handleNewResearch, selectedId]);
const handleExport = useCallback(async (format: "word" | "markdown" | "html") => {
const target = downloadTargetSession ?? session;
if (!target?.reportMarkdown) return;
try {
if (format === "word") {
await downloadMarkdownAsDocx(
buildResearchWordMarkdown(target, sources.data?.items ?? []),
researchExportBaseName(target),
target.title || target.query,
);
} else {
const output = await exportReport(target.id, format);
downloadText(output.content, `${researchExportBaseName(target)}.${format === "html" ? "html" : "md"}`, format === "html" ? "text/html" : "text/markdown");
}
toast.success(`${format === "word" ? "Word" : format.toUpperCase()} 已导出`);
} catch (error) {
toast.error(error instanceof Error ? error.message : "导出失败");
}
}, [downloadTargetSession, session, sources.data?.items]);
// ── composer variant resolution(AI 写作同款白卡片输入框)────────────────
const composerBusy = actions.create.isPending || actions.startJob.isPending || pendingInlineWrite || Boolean(pendingVariantWriteId) || Boolean(pendingFollowUp);
const jobWriting = isRunning || isAwaitingReview;
let composerPlaceholder = "输入研究课题,例如:人工智能在教育领域的应用与趋势";
if (pendingFollowUp) {
composerPlaceholder = "正在流式处理报告追问(点停止按钮可中止)";
} else if (session && isChatSession) {
if (!historyBrowseOnly && jobWriting) composerPlaceholder = "报告撰写中;完成后可继续追问(撰写中点提交 = 停止)";
else if (isFollowUp) composerPlaceholder = "基于当前报告继续追问,例如:哪些结论还需要补充验证?";
else if (isPlanningOutline) composerPlaceholder = "正在根据课题拟定报告大纲,完成后将开始收集资料";
else if (collectorMessagesLength > 0) composerPlaceholder = "补充要求或新的检索方向,例如:再查一下 2025 年的数据";
}
// streaming 状态下提交按钮变「停止」:点击 → 停止当前流(写作 job / 收集员)。
const composerStatus: "ready" | "streaming" | "error" = run.error
? "error"
: !historyBrowseOnly && (jobWriting || collectorStreaming || Boolean(pendingFollowUp))
? "streaming"
: "ready";
const handleComposerSubmit = useCallback(
(text: string) => {
const trimmed = text.trim();
if (!historyBrowseOnly) {
if (jobWriting) {
void handleCancelJob();
return;
}
if (collectorStreaming) {
void handleStopCollector();
return;
}
if (pendingFollowUp) {
handleStopFollowUp();
return;
}
}
if (!trimmed) return;
setHistoryBrowseOnly(false);
if (isFollowUp) {
void handleFollowUp(trimmed);
return;
}
if (session && isChatSession) {
void sendCollectorMessage(trimmed);
return;
}
void handleCreate(trimmed);
},
[
collectorStreaming,
handleCancelJob,
handleCreate,
handleFollowUp,
handleStopCollector,
historyBrowseOnly,
isChatSession,
isFollowUp,
jobWriting,
pendingFollowUp,
sendCollectorMessage,
session,
handleStopFollowUp,
],
);
// Card shows the model frozen at session-create time (survives reloads).
const configModel = session?.config?.fast_model;
const modelLabel = selectedModel ?? (typeof configModel === "string" ? configModel : "");
const modelOptions = useMemo(
() => [
{ label: "默认模型(系统配置)", value: DEFAULT_MODEL_VALUE },
...models.map((model) => ({
label: model.display_name || model.name,
value: model.name,
})),
],
[models],
);
const composerModelValue = selectedModel ?? DEFAULT_MODEL_VALUE;
// A selected model belongs to one durable research run; do not let either
// the chat or legacy flow mutate it while a job is active or paused.
const composerModelDisabled = Boolean(activeJobId || collectorStreaming || jobWriting || isFollowUp);
// Legacy sessions + the 经典模式 rollback keep the inline mode selector.
const composerClassic = classicMode || !isChatSession;
// 仅把需要用户操作的配置 / 计划确认 / 失败重试消息交给 slot。撰写阶段已是
// MessageGroup 的原生步骤条,完成摘要和追问也都是普通消息列表行。
const renderResearchCard = (message: Message): React.ReactNode => {
// 所有注入消息都以 session 存在为前提(push 条件都来自 session 状态)。
if (!session) return null;
const payload = (message.additional_kwargs?.setup_research_approval ?? {}) as {
kind?: string;
messageId?: string;
label?: string;
};
switch (payload.kind) {
case "config":
return (
<ReportConfigCard
// A new durable config-card message is a new editing session. Do
// not remount for ordinary collector/event refreshes: that would
// discard the user's in-progress “生成配图” toggle.
key={`${session.id}:${payload.messageId ?? "report-config"}`}
availableModes={availableModes}
defaultMode={session.mode}
defaultOptions={advancedOptionsFromConfig(session.config)}
outlineOverride={reportCardOutlineOverride}
structureModeOverride={reportCardStructureModeOverride}
retrievalDirectionsOverride={reportCardRetrievalDirectionsOverride}
retrievalSkillsOverride={reportCardRetrievalSkillsOverride}
defaultGenerateImages={session.config?.generate_images === true}
modelLabel={modelLabel}
materialCount={materialCount}
imageGenerationAvailable={imageGenerationAvailable}
imageLimit={capabilities.data?.imageGeneration?.maxImages ?? 4}
submitting={pendingInlineWrite || collectorStreaming}
onConfirm={(config, extras) => void handleConfirmReportCard(config, extras)}
onContinueCollecting={handleContinueCollecting}
/>
);
case "plan_review":
return (
<PlanReviewCard
plan={session?.plan}
submitting={actions.resumeJob.isPending}
onSubmit={handlePlanReview}
/>
);
case "rewrite_proposal":
return payload.messageId ? (
<RewriteProposalCard
label={payload.label || "报告内容"}
submitting={actions.resolveRewriteProposal.isPending}
onApply={() => void handleRewriteProposal(payload.messageId!, "apply")}
onDismiss={() => void handleRewriteProposal(payload.messageId!, "dismiss")}
/>
) : null;
case "regenerate_report":
return (
<ReportRegenerationCard
disabled={reportDocumentRewrite.isActive || Boolean(pendingVariantWriteId)}
onConfigure={handleOpenReportRegeneration}
/>
);
case "failed":
return (
<AssistantTurn>
<div className="rounded-2xl rounded-tl-md border border-border bg-card p-4 shadow-sm">
<div className="flex items-start gap-2">
<AlertCircle className="mt-0.5 h-4 w-4 text-primary" />
<div className="min-w-0">
<p className="text-sm font-medium">{session?.status === "failed" ? "这次报告撰写未完成" : "报告撰写已停止"}</p>
<p className="mt-1 text-sm leading-6 text-muted-foreground">{session?.error || "收集到的资料仍在,可以调整配置后重新撰写。"}</p>
</div>
</div>
<Button className="mt-4" size="sm" onClick={() => void handleReopenReportCard()} disabled={actions.updateStatus.isPending}>
{actions.updateStatus.isPending && <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />}
<RotateCcw className="mr-1.5 h-3.5 w-3.5" />
重新配置并撰写
</Button>
</div>
</AssistantTurn>
);
default:
return null;
}
};
return (
<div className="relative flex h-full min-h-0 overflow-hidden bg-background">
<ResearchSessionRail
sessions={railSessions}
loading={sessions.isLoading}
selectedId={selectedId}
onSelect={handleSelectResearch}
onNew={handleNewResearch}
onDelete={handleDelete}
modeTabs={modeTabs}
/>
<section className="flex min-w-0 flex-1 flex-col overflow-hidden">
<header className="flex h-14 shrink-0 items-center justify-between border-b border-border/70 px-5">
<div className="flex min-w-0 items-center gap-2">
<Telescope className="h-4 w-4 shrink-0 text-primary" />
<span className="truncate text-sm font-semibold">{session?.title || session?.query || "深度研究"}</span>
{session && <StatusBadge status={inlineWriteDone ? "completed" : session.status} />}
</div>
<div className="flex items-center gap-2">
<Button variant="ghost" size="sm" className="lg:hidden" onClick={handleNewResearch}>
<Telescope className="mr-1.5 h-4 w-4" /> 新建
</Button>
{displayedReport && (
<Button
variant="ghost"
size="sm"
className="xl:hidden"
onClick={() => (sandboxVisible ? setSandboxOpen(false) : handleOpenSandbox())}
>
<PanelRightOpen className="mr-1.5 h-4 w-4" /> 报告
</Button>
)}
{(isRunning || isAwaitingReview) && !historyBrowseOnly && (
<Button variant="outline" size="sm" onClick={() => void handleCancelJob()}>
<CircleStop className="mr-1.5 h-4 w-4" /> 停止
</Button>
)}
</div>
</header>
<ResearchSandboxPanel
threadId={sandboxSessionId}
stubMessages={stubMessages}
writing={sandboxWriting}
open={sandboxVisible}
onClose={() => setSandboxOpen(false)}
onDownload={() => {
setDownloadTargetSession(sandboxVariantSession);
setDownloadDialogOpen(true);
}}
onDocumentRewriteStart={handleStartFullReportRewrite}
documentRewriteActive={reportDocumentRewrite.isActive}
documentRewriteOperation={reportDocumentRewrite.isActive
? isGeneratingNewReport
? "generate"
: "rewrite"
: null}
onCancelDocumentRewrite={handleCancelFullReportRewrite}
documentRewriteDialogRequest={documentRewriteDialogRequest}
documentRewriteDialogPurpose={documentRewriteDialogPurpose}
initialDocumentRewriteOutline={
typeof session?.config?.custom_outline === "string" && session.config.custom_outline.trim()
? session.config.custom_outline
: advancedOptions.customOutline
}
reportCharCount={(
rewriteTargetSession?.reportMarkdown
?? session?.reportMarkdown
?? displayedReport
).replace(/\s/g, "").length}
>
<main className="flex h-full min-w-0 flex-col">
{!session || (isChatSession && collectorEmpty) ? (
<div className="flex min-h-0 flex-1 items-center justify-center">
<ResearchWelcome
pageDescription={deepResearchPageDescription}
onStart={() => document.getElementById("deep-research-composer")?.focus()}
/>
</div>
) : isChatSession ? (
<>
<ThreadContext.Provider value={{ thread: collectorDisplayThread }}>
<SubtasksProvider>
<MessageList
className="min-h-0 flex-1"
contentClassName="max-w-none pt-8"
threadId={collectorThreadId as string}
thread={collectorDisplayThread}
onClarificationSubmit={handleClarificationSubmit}
researchApprovalSlot={renderResearchCard}
onOpenArtifact={() => {
if (session) handleOpenInlineGeneratedReport(session);
else handleOpenSandbox();
}}
onDownloadArtifact={() => {
setDownloadTargetSession(null);
setDownloadDialogOpen(true);
}}
afterDocumentRewriteItems={
generatedReportVariants.some((item) => item.status === "completed" && item.reportMarkdown) ? (
<div className="space-y-3">
{generatedReportVariants
.filter((item) => item.status === "completed" && item.reportMarkdown)
.map((item) => (
<InlineGeneratedReportFileCard
key={item.id}
session={item}
onOpen={() => handleOpenInlineGeneratedReport(item)}
onDownload={() => {
setDownloadTargetSession(item);
setDownloadDialogOpen(true);
}}
/>
))}
</div>
) : null
}
/>
</SubtasksProvider>
</ThreadContext.Provider>
{showThinkingPlaceholder && (
<div className="shrink-0 border-t border-border/70 bg-background px-4 py-2">
<div className="flex items-center gap-2 text-xs text-muted-foreground">
<span className="inline-block size-1.5 animate-pulse rounded-full bg-blue-500" />
正在整理…
</div>
</div>
)}
</>
) : (
<ScrollArea className="min-h-0 flex-1">
<div className="mx-auto w-full max-w-3xl px-5 py-8 sm:px-8">
<ResearchConversation
session={session}
events={run.events}
phase={run.phase}
planText={run.planText}
planReasoning={run.planReasoning}
reportStarted={Boolean(run.report)}
streamError={run.error}
sourceCount={sources.data?.items?.length ?? session.sourceCount}
messages={messages.data ?? []}
pendingFollowUp={pendingFollowUp}
pendingFollowUpContent={followUpStream?.content ?? ""}
onOpenSandbox={handleOpenSandbox}
onRestart={() => void handleRestartLegacy()}
onExport={handleExport}
onRegenerateReport={handleOpenReportRegeneration}
onRewriteReport={handleOpenFullReportRewrite}
reportRegenerationDisabled={reportDocumentRewrite.isActive || Boolean(pendingVariantWriteId)}
isRestarting={actions.startJob.isPending}
showReportFileCard={isReportVariant}
onDownloadReport={() => {
setDownloadTargetSession(null);
setDownloadDialogOpen(true);
}}
planReview={isAwaitingReview ? (
<PlanReviewCard
plan={session.plan}
submitting={actions.resumeJob.isPending}
onSubmit={handlePlanReview}
/>
) : null}
/>
</div>
</ScrollArea>
)}
<div className="shrink-0 border-t border-border/70 bg-background px-4 py-4 sm:px-6">
{/* AI 写作同款白卡片输入框:宽度跟随父元素(无 max-w),模型行 + PromptInput 套件(流式中提交键变停止) */}
<div className="space-y-3 rounded-2xl border border-border bg-card p-3 shadow-[0_8px_30px_rgba(0,0,0,0.06)]">
<div className="flex flex-wrap items-center justify-between gap-3">
<div className="flex min-w-0 items-center gap-2 text-xs text-muted-foreground">
<Telescope className="size-3.5 shrink-0 text-primary" />
<span className="shrink-0">{composerClassic ? "研究模式" : "深度研究"}</span>
{composerClassic && (
<>
<Select value={mode} onValueChange={(next) => setMode(next as ResearchMode)} disabled={Boolean(isFollowUp) || jobWriting}>
<SelectTrigger className="h-7 min-w-[7.5rem] max-w-[10rem] border border-input bg-background px-2 text-xs shadow-xs outline-none">
<SelectValue />
</SelectTrigger>
<SelectContent>
{availableModes.map((item) => (
<SelectItem key={item} value={item}>{MODE_LABELS[item]}</SelectItem>
))}
</SelectContent>
</Select>
</>
)}
{!advancedOptions.customOutline.trim() && (
<Select
value={outlinePlannerMode}
onValueChange={(next) => setAdvancedOptions((current) => (
current.outlinePlanner === next ? current : { ...current, outlinePlanner: normalizeOutlinePlanner(next) }
))}
disabled={Boolean(session) || Boolean(isFollowUp) || jobWriting || collectorStreaming}
>
<SelectTrigger
className="h-7 min-w-[9rem] max-w-[12rem] border border-input bg-background px-2 text-xs shadow-xs outline-none"
aria-label="提纲生成策略"
title={OUTLINE_PLANNER_OPTIONS.find((item) => item.value === outlinePlannerMode)?.hint}
>
<SelectValue />
</SelectTrigger>
<SelectContent>
{OUTLINE_PLANNER_OPTIONS.map((item) => (
<SelectItem key={item.value} value={item.value} title={item.hint}>
{item.label}
</SelectItem>
))}
</SelectContent>
</Select>
)}
</div>
<div className="flex shrink-0 items-center gap-2">
{composerClassic && imageGenerationAvailable && !isFollowUp && (
<button
type="button"
aria-pressed={generateImages}
onClick={() => setGenerateImages(!generateImages)}
className={`inline-flex h-7 items-center gap-1.5 rounded-md px-2 text-xs transition-colors ${generateImages ? "bg-primary/10 text-primary" : "text-muted-foreground hover:bg-muted"}`}
>
<ImagePlus className="h-3.5 w-3.5" />配图
</button>
)}
<WorkflowConfigButton
variant="ghost"
className="h-7 px-2 text-xs"
disabled={jobWriting}
appliedContent={advancedOptions.customOutline}
onApply={applyReportStructure}
/>
</div>
</div>
<PromptInput onSubmit={({ text }) => handleComposerSubmit(text)}>
<PromptInputTextarea
id="deep-research-composer"
placeholder={composerPlaceholder}
disabled={composerBusy}
/>
<PromptInputFooter className="flex-wrap items-center justify-between gap-2">
<p className="text-[11px] text-muted-foreground">
{isFollowUp
? "追问仅基于本报告及已选来源,不会自动发起新的联网检索。Enter 发送,Shift + Enter 换行。"
: "Enter 发送,Shift + Enter 换行。收集员智能体会理解课题、拆分检索词并沿用联网检索与技能检索能力。"}
</p>
<div className="ml-auto flex shrink-0 items-center gap-2">
{!classicMode && (
<LlmWikiKnowledgeSelector
value={researchKnowledgeBaseIds}
onChange={setDraftKnowledgeBaseIds}
readOnly={Boolean(session)}
disabled={composerBusy || actions.create.isPending}
label="研究知识库"
panelTitle="选择 Weknora 知识库"
panelDescription="资料收集问答将检索所选知识库,选择随研究记录保存。"
/>
)}
{!classicMode && (
<TSelect
size="small"
aria-label="知识库检索模式"
value={researchRetrievalMode}
disabled={Boolean(session) || composerBusy || actions.create.isPending}
options={[
{ label: "经典检索", value: "classic" },
{ label: "智能检索", value: "smart_reasoning", disabled: !smartRetrievalAvailability.available },
]}
title={smartRetrievalAvailability.reason || "经典检索召回原文;智能检索综合原文与 Wiki 线索"}
onChange={(value) => setDraftRetrievalMode(normalizeKnowledgeRetrievalMode(value))}
className="w-[120px]"
/>
)}
<TSelect
size="small"
aria-label="切换深度研究模型"
value={composerModelValue}
options={modelOptions}
disabled={composerModelDisabled || collectorStreaming || modelsLoading || actions.create.isPending || actions.startJob.isPending}
onChange={(value) => setSelectedModel(value === DEFAULT_MODEL_VALUE ? null : String(value))}
className="w-[180px] max-w-full [&_.t-input]:!h-8 [&_.t-input]:!rounded-md [&_.t-input]:!border-border [&_.t-input]:!bg-background [&_.t-input]:!px-2 [&_.t-input]:!text-xs [&_.t-input]:!shadow-xs"
popupProps={{ overlayClassName: "z-[80]" }}
/>
<PromptInputSubmit status={composerStatus} disabled={composerBusy && composerStatus !== "streaming"} />
</div>
</PromptInputFooter>
</PromptInput>
</div>
</div>
</main>
</ResearchSandboxPanel>
</section>
{/* 沙箱「下载」按钮的格式选择弹窗:Markdown / Word(替代完成卡上的导出按钮) */}
<Dialog open={downloadDialogOpen} onOpenChange={setDownloadDialogOpen}>
<DialogContent className="max-w-sm">
<DialogHeader>
<DialogTitle>下载报告</DialogTitle>
<DialogDescription>选择导出格式;Word 会把参考来源列表一并附在文末。</DialogDescription>
</DialogHeader>
<div className="grid grid-cols-2 gap-3">
<button
type="button"
disabled={!(downloadTargetSession ?? session)?.reportMarkdown}
className="flex flex-col items-center gap-1.5 rounded-xl border border-border bg-card p-4 transition-colors hover:border-primary/40 hover:bg-primary/5 disabled:opacity-50"
onClick={() => {
setDownloadDialogOpen(false);
void handleExport("markdown");
}}
>
<FileCode2 className="h-5 w-5 text-primary" />
<span className="text-sm font-medium">Markdown</span>
<span className="text-[11px] text-muted-foreground">.md 源文件</span>
</button>
<button
type="button"
disabled={!(downloadTargetSession ?? session)?.reportMarkdown}
className="flex flex-col items-center gap-1.5 rounded-xl border border-border bg-card p-4 transition-colors hover:border-primary/40 hover:bg-primary/5 disabled:opacity-50"
onClick={() => {
setDownloadDialogOpen(false);
void handleExport("word");
}}
>
<FileDown className="h-5 w-5 text-primary" />
<span className="text-sm font-medium">Word</span>
<span className="text-[11px] text-muted-foreground">.docx 文档</span>
</button>
</div>
</DialogContent>
</Dialog>
<AdvancedResearchSettingsDialog
open={settingsOpen}
onOpenChange={setSettingsOpen}
mode={mode}
options={advancedOptions}
classicMode={classicMode}
onClassicModeChange={setClassicMode}
imageGenerationAvailable={imageGenerationAvailable}
imageLimit={capabilities.data?.imageGeneration?.maxImages ?? 4}
onChange={updateAdvancedOption}
/>
</div>
);
}
// ── chat-flow stage components ───────────────────────────────────────────────
const CHAT_WRITING_PHASE_ORDER = [
"initializing",
"planning",
"collecting",
"deepening",
"curating",
"compressing",
"writing",
"reviewing",
"illustrating",
"exporting",
"summarizing",
"done",
];
function chatPhaseRank(phase: string): number {
const index = CHAT_WRITING_PHASE_ORDER.indexOf(phase);
return index === -1 ? 0 : index;
}
type WritingProgressToolCall = {
id: string;
name: "deep_research_progress";
args: {
label: string;
detail: string;
status: "complete" | "active";
thinking?: string;
};
};
/**
* Convert Deep Research's writing lifecycle into ordinary message-list tool
* steps. The MessageGroup component renders these with the same collapsible
* ChainOfThought UI used by normal Q&A search/tool calls.
*/
function buildWritingProgressToolCalls({
phase,
materialCount,
error,
thinking,
summaryThinking,
events,
requestedImageCount,
}: {
phase: string;
materialCount: number;
error: string | null;
thinking: string;
summaryThinking: string;
events: ProgressEvent[];
requestedImageCount: number;
}): WritingProgressToolCall[] {
const rank = chatPhaseRank(phase);
const outlineStarted = events.some((event) => event.payload?.code === "intent_outline_started");
const outlineReady = events.some((event) => (
(event.type === "plan_created" && event.payload?.source === "intent")
|| event.payload?.code === "intent_outline_fallback"
));
const planningOutline = outlineStarted && !outlineReady;
const reconnecting = events.some((event) => event.payload?.code === "stream_reconnecting");
const jobStarted = events.some((event) => event.payload?.code === "write_job_started");
const harvestCompleted = events.some((event) => event.type === "collection_completed");
const harvestDetail = materialCount > 0
? `已从收集对话整理 ${materialCount} 条资料`
: reconnecting
? "进度连接中断,正在自动重连…"
: harvestCompleted
? "已收到写作素材,正在进入撰写"
: jobStarted
? "写作任务已启动,正在读取已收集材料"
: "正在读取收集对话中的检索结果";
const imageSnapshot = buildTraceSnapshot(events);
const imageStageVisible = requestedImageCount > 0 || imageSnapshot.imageTotal > 0 || imageSnapshot.images.length > 0;
const imageTotal = imageSnapshot.imageTotal || requestedImageCount;
const generatedImages = imageSnapshot.images.filter((image) => image.status === "completed").length;
const failedImages = imageSnapshot.images.filter((image) => image.status === "failed").length;
const stages = [
{
id: "harvest",
label: "收割对话资料",
boundary: chatPhaseRank("curating"),
detail: harvestDetail,
},
{
id: "compress",
label: "筛选并压缩上下文",
boundary: chatPhaseRank("writing"),
detail: "去重筛选后整理为报告写作上下文",
},
{
id: "write",
label: planningOutline ? "生成报告结构" : "流式撰写报告",
boundary: chatPhaseRank("reviewing"),
detail: planningOutline
? "未选择报告结构,正在根据课题和已收集材料规划章节"
: "正在逐字写入右侧沙箱中的 report.md",
},
...(imageStageVisible ? [{
id: "illustrate",
label: "生成报告配图",
boundary: chatPhaseRank("exporting"),
detail: generatedImages > 0
? `已生成 ${generatedImages} 张报告配图并嵌入 report.md${failedImages ? `;另有 ${failedImages} 张未生成,文字报告已保留` : ""}`
: failedImages > 0
? `配图未生成,已保留完整文字报告${imageTotal ? `(已处理 ${failedImages}/${imageTotal} 张)` : ""}`
: imageTotal > 0
? `正在生成报告配图,已处理 ${generatedImages + failedImages}/${imageTotal} 张`
: "正在为报告关键章节生成配图",
}] : []),
{
id: "summary",
label: "生成报告摘要",
boundary: chatPhaseRank("done"),
detail: rank >= chatPhaseRank("summarizing") && rank < chatPhaseRank("done") && summaryThinking.trim()
? "模型正在思考摘要,思考结束后会写入总结"
: "报告完成后生成简要总结",
},
];
const activeIndex = stages.findIndex((stage) => rank < stage.boundary);
const visibleLast = activeIndex === -1 ? stages.length - 1 : activeIndex;
return stages.slice(0, visibleLast + 1).map((stage, index) => {
const complete = rank >= stage.boundary;
const detail = index === visibleLast && !complete && error
? `${stage.detail};实时连接提示:${error}`
: stage.detail;
return {
id: `deep-research-writing-${stage.id}`,
name: "deep_research_progress",
args: {
label: stage.label,
detail,
status: complete ? "complete" : "active",
...(stage.id === "write" && thinking.trim() ? { thinking } : {}),
...(stage.id === "summary" && summaryThinking.trim() ? { thinking: summaryThinking } : {}),
},
};
});
}
/** Plain Markdown so the final state uses the normal assistant message row. */
function buildCompletedReportMessage({
sourceCount,
summaryText,
imageCount,
}: {
sourceCount: number;
summaryText: string;
imageCount: number;
}): string {
const parts = [
"## 研究报告已完成",
`已基于 ${sourceCount} 条资料完成报告,正文已在右侧沙箱中打开;可通过沙箱工具栏下载 Markdown 或 Word。`,
];
if (imageCount > 0) {
parts.push(`已生成 ${imageCount} 张报告配图,并嵌入正文对应章节。`);
}
if (summaryText.trim()) {
parts.push(`### 报告摘要\n\n${summaryText.trim()}`);
}
return parts.join("\n\n");
}
/** 摘要阶段使用普通 assistant 行,内容由 summary_delta 逐帧更新。 */
function buildStreamingSummaryMessage(summaryText: string, thinking = ""): string {
return [
"## 正在生成报告摘要",
summaryText.trim() || (thinking.trim() ? "模型正在思考摘要,思考结束后会写入总结…" : "正在根据完整报告提炼摘要…"),
].join("\n\n");
}
// ── session rail / status ────────────────────────────────────────────────────
function ResearchSessionRail({
sessions,
loading,
selectedId,
onSelect,
onNew,
onDelete,
modeTabs,
}: {
sessions: DeepResearchSession[];
loading: boolean;
selectedId: string | null;
onSelect: (id: string) => void;
onNew: () => void;
onDelete: (id: string) => void;
modeTabs?: ReactNode;
}) {
return (
<aside className="hidden w-60 shrink-0 flex-col border-r border-border/70 bg-muted/10 lg:flex">
{modeTabs ? (
<div className="flex shrink-0 items-center gap-2 border-b border-slate-100 px-3 py-2 dark:border-[#2b8ffe]/20">
{modeTabs}
</div>
) : null}
<div className="border-b border-border/70 p-3">
<Button className="w-full justify-start" onClick={onNew}>
<Telescope className="mr-2 h-4 w-4" /> 新建研究
</Button>
</div>
<ScrollArea className="min-h-0 flex-1 px-2 py-3">
<div className="mb-2 px-2 text-xs font-medium text-muted-foreground">研究记录</div>
{loading ? (
<div className="flex items-center justify-center py-8 text-xs text-muted-foreground"><Loader2 className="mr-2 h-3.5 w-3.5 animate-spin" />加载中</div>
) : sessions.length ? (
<div className="space-y-1">
{sessions.map((item) => (
<div
key={item.id}
className={`group flex cursor-pointer items-start gap-2 rounded-xl px-2.5 py-2.5 transition-colors ${selectedId === item.id ? "bg-primary/10 text-foreground" : "hover:bg-muted"}`}
onClick={() => onSelect(item.id)}
onKeyDown={(event) => { if (event.key === "Enter" || event.key === " ") onSelect(item.id); }}
role="button"
tabIndex={0}
>
<MessageSquareText className={`mt-0.5 h-3.5 w-3.5 shrink-0 ${selectedId === item.id ? "text-primary" : "text-muted-foreground"}`} />
<div className="min-w-0 flex-1">
<div className="line-clamp-2 text-xs font-medium leading-5">{item.title || item.query}</div>
<div className="mt-1 flex items-center gap-1.5 text-[10px] text-muted-foreground">
<span>{STATUS_LABELS[item.status]}</span>
{item.sourceCount > 0 && <span>· {item.sourceCount} 来源</span>}
</div>
</div>
<button
type="button"
aria-label={`删除研究:${item.title || item.query}`}
className="mt-0.5 hidden rounded p-1 text-muted-foreground hover:bg-background hover:text-destructive group-hover:block focus:block"
onClick={(event) => { event.stopPropagation(); onDelete(item.id); }}
>
<Trash2 className="h-3 w-3" />
</button>
</div>
))}
</div>
) : (
<div className="px-2 py-8 text-center text-xs leading-5 text-muted-foreground">从一个课题开始,研究过程和报告都会保存在这里。</div>
)}
</ScrollArea>
</aside>
);
}
function StatusBadge({ status }: { status: DeepResearchSession["status"] }) {
const tone = status === "completed" ? "bg-emerald-500/12 text-emerald-700 dark:text-emerald-300"
: status === "failed" ? "bg-destructive/10 text-destructive"
: status === "cancelled" ? "bg-muted text-muted-foreground"
: "bg-primary/10 text-primary";
return <Badge variant="outline" className={`border-0 px-2 py-0.5 text-[11px] ${tone}`}>{STATUS_LABELS[status]}</Badge>;
}
function ResearchWelcome({
pageDescription,
onStart,
}: {
pageDescription?: PageHeaderDescription;
onStart: () => void;
}) {
return (
<div className="flex min-h-[440px] flex-col items-center justify-center text-center">
<div className="mb-5 flex h-14 w-14 items-center justify-center rounded-2xl bg-primary/10 text-primary"><Telescope className="h-7 w-7" /></div>
<h1 className="text-2xl font-semibold tracking-tight">
{pageDescription?.title || "开始一项深度研究"}
</h1>
<p className="mt-3 max-w-md text-sm leading-6 text-muted-foreground">
{pageDescription?.description || "输入研究课题后,内置的收集员智能体会像普通对话一样理解课题、拆分检索词并联网/知识库检索;完成后确认报告写法,系统会基于收集到的资料在右侧沙箱撰写报告。"}
</p>
<Button className="mt-6" onClick={onStart}><Sparkles className="mr-2 h-4 w-4" />输入研究课题</Button>
</div>
);
}
function UserBubble({ content, compact = false }: { content: string; compact?: boolean }) {
return <div className="flex justify-end"><div className={`max-w-[82%] rounded-2xl rounded-tr-md bg-gradient-to-r from-primary to-primary/85 text-primary-foreground shadow-sm ${compact ? "px-3.5 py-2.5 text-sm" : "px-4 py-3 text-sm"}`}><div className="mb-1 flex items-center justify-end gap-1.5 text-[11px] text-primary-foreground/75"><span>我</span><UserRound className="h-3 w-3" /></div><p className="whitespace-pre-wrap leading-6">{content}</p></div></div>;
}
function AssistantTurn({ children }: { children: React.ReactNode }) {
return <div className="flex items-start gap-3"><div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-xl bg-primary/10 text-primary"><Bot className="h-4 w-4" /></div><div className="min-w-0 flex-1"><div className="mb-2 text-xs font-medium text-muted-foreground">深度研究助手</div>{children}</div></div>;
}
/** A deliberate confirmation boundary between a streamed candidate and report mutation. */
function RewriteProposalCard({
label,
submitting,
onApply,
onDismiss,
}: {
label: string;
submitting: boolean;
onApply: () => void;
onDismiss: () => void;
}) {
return (
<div className="rounded-2xl rounded-tl-md border border-primary/20 bg-card p-4 shadow-sm">
<div className="flex items-start gap-3">
<div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-xl bg-primary/10 text-primary">
<FileText className="h-4 w-4" />
</div>
<div className="min-w-0">
<p className="text-sm font-semibold">{label}的改写建议已生成</p>
<p className="mt-1 text-sm leading-6 text-muted-foreground">
候选内容已在上方消息中完整显示。确认应用后,才会替换右侧报告中的对应位置。
</p>
</div>
</div>
<div className="mt-4 flex flex-wrap justify-end gap-2">
<Button type="button" variant="outline" size="sm" disabled={submitting} onClick={onDismiss}>
保留原文
</Button>
<Button type="button" size="sm" disabled={submitting} onClick={onApply}>
{submitting ? <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" /> : <CheckCircle2 className="mr-1.5 h-3.5 w-3.5" />}
应用到报告
</Button>
</div>
</div>
);
}
// ── legacy conversation (old sessions + 经典模式) ────────────────────────────
function ResearchConversation({
session,
events,
phase,
planText,
planReasoning,
reportStarted,
streamError,
sourceCount,
messages,
pendingFollowUp,
pendingFollowUpContent,
onOpenSandbox,
onRestart,
onExport,
onRegenerateReport,
onRewriteReport,
reportRegenerationDisabled,
isRestarting,
showReportFileCard,
onDownloadReport,
planReview,
}: {
session: DeepResearchSession;
events: ProgressEvent[];
phase: string;
planText: string;
planReasoning: string;
reportStarted: boolean;
streamError: string | null;
sourceCount: number;
messages: { id: string; role: "user" | "assistant"; content: string; citationSourceIds: string[] }[];
pendingFollowUp: string | null;
pendingFollowUpContent: string;
onOpenSandbox: () => void;
onRestart: () => void;
onExport: (format: "word" | "markdown" | "html") => void;
onRegenerateReport: () => void;
onRewriteReport: () => void;
reportRegenerationDisabled: boolean;
isRestarting: boolean;
showReportFileCard: boolean;
onDownloadReport: () => void;
planReview: React.ReactNode;
}) {
const active = session.status === "running" || session.status === "awaiting_input";
const hasTrace = active || events.length > 0;
const streamedSourceCount = countEventMaterials(events);
const liveSourceCount = Math.max(sourceCount, streamedSourceCount);
const requestedImageCount = requestedReportImageCount(session.config);
return (
<div className="space-y-6">
<UserBubble content={session.query} />
{hasTrace && (
<AssistantTurn>
<ResearchTrace
events={events}
phase={phase}
planText={planText}
planReasoning={planReasoning}
sourceCount={liveSourceCount}
reportStarted={reportStarted}
error={streamError}
onOpenSandbox={onOpenSandbox}
active={active}
requestedImageCount={requestedImageCount}
/>
</AssistantTurn>
)}
{planReview}
{(session.status === "failed" || session.status === "cancelled" || session.status === "draft") && (
<AssistantTurn>
<div className="rounded-2xl border border-border bg-card p-4 shadow-sm">
<div className="flex items-start gap-2">
<AlertCircle className="mt-0.5 h-4 w-4 text-primary" />
<div className="min-w-0"><p className="text-sm font-medium">{session.status === "draft" ? "研究尚未开始" : session.status === "failed" ? "这次研究未完成" : "研究已停止"}</p><p className="mt-1 text-sm leading-6 text-muted-foreground">{session.error || "可以在保留当前课题的前提下重新开始一次研究。"}</p></div>
</div>
<Button className="mt-4" size="sm" onClick={onRestart} disabled={isRestarting}>{isRestarting && <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />}<RotateCcw className="mr-1.5 h-3.5 w-3.5" />重新开始</Button>
</div>
</AssistantTurn>
)}
{session.status === "completed" && session.reportMarkdown && (
<AssistantTurn>
<CompletionSummary
session={session}
sourceCount={sourceCount}
onOpenSandbox={onOpenSandbox}
onExport={onExport}
onRegenerateReport={onRegenerateReport}
onRewriteReport={onRewriteReport}
reportRegenerationDisabled={reportRegenerationDisabled}
/>
</AssistantTurn>
)}
{showReportFileCard && session.status === "completed" && session.reportMarkdown && (
<InlineGeneratedReportFileCard
session={session}
onOpen={onOpenSandbox}
onDownload={onDownloadReport}
/>
)}
{messages.map((message) => message.role === "user" ? <UserBubble key={message.id} content={message.content} compact /> : <AssistantTurn key={message.id}><div className="rounded-2xl rounded-tl-md border border-border bg-card px-4 py-3 text-sm leading-7 shadow-sm"><ReactMarkdown>{message.content}</ReactMarkdown>{message.citationSourceIds.length > 0 && <div className="mt-2 text-xs text-muted-foreground">基于 {message.citationSourceIds.length} 条已选来源回答</div>}</div></AssistantTurn>)}
{pendingFollowUp && <><UserBubble content={pendingFollowUp} compact /><AssistantTurn><div className="rounded-2xl rounded-tl-md border border-border bg-card px-4 py-3 text-sm leading-7 shadow-sm">{pendingFollowUpContent ? <ReactMarkdown>{pendingFollowUpContent}</ReactMarkdown> : <div className="flex items-center gap-2 text-muted-foreground"><Loader2 className="h-4 w-4 animate-spin text-primary" />正在基于报告与已选来源回答…</div>}</div></AssistantTurn></>}
</div>
);
}
type TraceQueryStatus = "queued" | "running" | "completed";
type TraceQuery = {
query: string;
group: string;
status: TraceQueryStatus;
resultCount?: number;
sourceIds: string[];
};
type TraceSource = {
id: string;
title: string;
url?: string;
sourceType: string;
query: string;
snippet?: string;
};
type TraceImage = {
position: number;
section: string;
status: "generating" | "completed" | "failed";
name?: string;
alt?: string;
error?: string;
};
type TraceSnapshot = {
groups: { title: string; queries: string[] }[];
subtopics: string[];
queries: TraceQuery[];
sources: TraceSource[];
selectedIds: Set<string>;
removedIds: Set<string>;
curationReason?: string;
compressedSourceCount?: number;
reportCompleted: boolean;
imageTotal: number;
images: TraceImage[];
imagePhaseFinished: boolean;
warnings: string[];
diagnostics: Record<string, unknown>[];
};
function traceRecord(value: unknown): Record<string, unknown> {
return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
}
function traceString(value: unknown): string | undefined {
return typeof value === "string" && value.trim() ? value.trim() : undefined;
}
function traceStrings(value: unknown): string[] {
return Array.isArray(value) ? value.map(traceString).filter((item): item is string => Boolean(item)) : [];
}
function numberValue(value: unknown): number | undefined {
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
}
function countEmbeddedReportImages(markdown?: string): number {
return (markdown?.match(/!\[[^\]]*\]\(deep-research:\/\/[^)\s]+\)/g) ?? []).length;
}
function requestedReportImageCount(config?: Record<string, unknown>): number {
if (config?.generate_images !== true) return 0;
const configured = numberValue(config.max_generated_images);
return Math.max(1, Math.min(4, Math.floor(configured ?? 2)));
}
function buildTraceSnapshot(events: ProgressEvent[]): TraceSnapshot {
const groupQueries = new Map<string, string[]>();
const subtopics: string[] = [];
const queryMap = new Map<string, TraceQuery>();
const sourceMap = new Map<string, TraceSource>();
const imageMap = new Map<number, TraceImage>();
const selectedIds = new Set<string>();
const removedIds = new Set<string>();
const warnings: string[] = [];
const diagnostics: Record<string, unknown>[] = [];
const diagnosticKeys = new Set<string>();
let curationReason: string | undefined;
let compressedSourceCount: number | undefined;
let reportCompleted = false;
let imageTotal = 0;
let imagePhaseFinished = false;
const addQuery = (query: string, group = "研究课题") => {
const normalized = query.trim();
if (!normalized) return;
const groupItems = groupQueries.get(group) ?? [];
if (!groupItems.includes(normalized)) groupItems.push(normalized);
groupQueries.set(group, groupItems);
if (!queryMap.has(normalized)) {
queryMap.set(normalized, { query: normalized, group, status: "queued", sourceIds: [] });
}
};
for (const event of events) {
const payload = event.payload ?? {};
if (event.type === "phase_changed") {
const from = traceString(payload.from);
const to = traceString(payload.to);
if (from === "illustrating" || to === "exporting") imagePhaseFinished = true;
}
if (event.type === "plan_created") {
const plan = traceRecord(payload.plan);
for (const subtopic of traceStrings(payload.subtopics).concat(traceStrings(plan.subtopics))) {
if (!subtopics.includes(subtopic)) subtopics.push(subtopic);
}
for (const query of traceStrings(plan.queries)) addQuery(query);
for (const branch of Array.isArray(plan.branches) ? plan.branches : []) {
const branchQuery = traceString(traceRecord(branch).query);
if (branchQuery) addQuery(branchQuery, "递归检索分支");
}
continue;
}
if (event.type === "queries_planned") {
const group = traceString(payload.parentTopic) ?? "研究课题";
for (const query of traceStrings(payload.queries)) addQuery(query, group);
continue;
}
if (event.type === "query_started" || event.type === "query_completed") {
const query = traceString(payload.query);
if (!query) continue;
addQuery(query);
const item = queryMap.get(query)!;
item.status = event.type === "query_started" ? "running" : "completed";
if (event.type === "query_completed") item.resultCount = numberValue(payload.resultCount) ?? item.sourceIds.length;
continue;
}
if (event.type === "deep_branch_started" || event.type === "deep_branch_completed") {
const query = traceString(payload.query);
if (!query) continue;
addQuery(query, "递归补充检索");
const item = queryMap.get(query)!;
item.status = event.type === "deep_branch_started" ? "running" : "completed";
if (event.type === "deep_branch_completed") item.resultCount = numberValue(payload.resultCount) ?? item.sourceIds.length;
continue;
}
if (event.type === "source_added") {
const source = traceRecord(payload.source);
const query = traceString(source.first_seen_query) ?? traceString(payload.query) ?? "未标注检索词";
addQuery(query);
const id = traceString(payload.sourceId) ?? traceString(source.id) ?? traceString(source.url) ?? `${query}:${traceString(payload.title) ?? "source"}`;
const title = traceString(payload.title) ?? traceString(source.title) ?? "未命名资料";
sourceMap.set(id, {
id,
title,
url: traceString(payload.url) ?? traceString(source.url),
sourceType: traceString(payload.sourceType) ?? traceString(source.source_type) ?? "检索资料",
query,
snippet: traceString(source.snippet) ?? traceString(source.raw_content),
});
const traceQuery = queryMap.get(query)!;
if (!traceQuery.sourceIds.includes(id)) traceQuery.sourceIds.push(id);
continue;
}
if (event.type === "sources_curated") {
selectedIds.clear();
removedIds.clear();
for (const id of traceStrings(payload.selectedIds)) selectedIds.add(id);
for (const id of traceStrings(payload.removedIds)) removedIds.add(id);
curationReason = traceString(payload.reason);
continue;
}
if (event.type === "context_compressed") {
compressedSourceCount = numberValue(payload.sourceCount) ?? compressedSourceCount;
continue;
}
if (event.type === "report_completed") {
reportCompleted = true;
continue;
}
if (event.type === "image_generation_started" || event.type === "image_generated") {
const position = Math.max(1, Math.floor(numberValue(payload.position) ?? imageMap.size + 1));
const total = numberValue(payload.total);
if (total !== undefined) imageTotal = Math.max(imageTotal, Math.floor(total));
imageTotal = Math.max(imageTotal, position);
const prior = imageMap.get(position);
imageMap.set(position, {
position,
section: traceString(payload.section) ?? prior?.section ?? `第 ${position} 张配图`,
status: event.type === "image_generated" ? "completed" : prior?.status === "completed" ? "completed" : "generating",
name: traceString(payload.name) ?? prior?.name,
alt: traceString(payload.alt) ?? prior?.alt,
});
continue;
}
if (event.type === "warning" || event.type === "error") {
const message = traceString(payload.message) ?? traceString(payload.detail);
if (message && !warnings.includes(message)) warnings.push(message);
const diagnostic = traceRecord(payload.diagnostic);
if (Object.keys(diagnostic).length > 0) {
const item = {
code: traceString(payload.code) ?? event.type,
...(message ? { message } : {}),
...diagnostic,
};
const key = JSON.stringify(item);
if (!diagnosticKeys.has(key)) {
diagnosticKeys.add(key);
diagnostics.push(item);
}
}
if (traceString(payload.code) === "image_generation_failed") {
const position = Math.max(1, Math.floor(numberValue(payload.position) ?? imageMap.size + 1));
const total = numberValue(payload.total);
if (total !== undefined) imageTotal = Math.max(imageTotal, Math.floor(total));
imageTotal = Math.max(imageTotal, position);
const prior = imageMap.get(position);
imageMap.set(position, {
position,
section: traceString(payload.section) ?? prior?.section ?? `第 ${position} 张配图`,
status: "failed",
name: prior?.name,
alt: prior?.alt,
error: message ?? "报告配图生成失败",
});
}
}
}
return {
groups: [...groupQueries].map(([title, queries]) => ({ title, queries })),
subtopics,
queries: [...queryMap.values()],
sources: [...sourceMap.values()],
selectedIds,
removedIds,
curationReason,
compressedSourceCount,
reportCompleted,
imageTotal,
images: [...imageMap.values()].sort((left, right) => left.position - right.position),
imagePhaseFinished,
warnings,
diagnostics,
};
}
function phaseAtOrAfter(phase: string, boundary: string): boolean {
const order = ["initializing", "planning", "collecting", "curating", "compressing", "deepening", "writing", "summarizing", "reviewing", "illustrating", "exporting", "done"];
return Math.max(0, order.indexOf(phase)) >= Math.max(0, order.indexOf(boundary));
}
function TraceStage({ number, title, detail, done, current, children }: { number: number; title: string; detail: string; done: boolean; current: boolean; children: React.ReactNode }) {
return <section className="relative pl-9"><span className={`absolute left-0 top-0 flex h-6 w-6 items-center justify-center rounded-full text-xs font-semibold ${done ? "bg-emerald-500/15 text-emerald-700 dark:text-emerald-300" : current ? "bg-primary text-primary-foreground" : "bg-muted text-muted-foreground"}`}>{done ? <CheckCircle2 className="h-3.5 w-3.5" /> : number}</span><div className="min-w-0"><div className="flex flex-wrap items-center gap-x-2 gap-y-1"><h3 className="text-sm font-medium">{title}</h3>{current && <span className="text-[11px] text-primary">进行中</span>}{done && <span className="text-[11px] text-emerald-700 dark:text-emerald-300">已完成</span>}</div><p className="mt-0.5 text-xs leading-5 text-muted-foreground">{detail}</p><div className="mt-2.5">{children}</div></div></section>;
}
/** Extract completed quoted strings from the streamed (partial) planning JSON. */
function parseStreamedQueries(text: string): string[] {
const start = text.indexOf("[");
if (start === -1) return [];
const matches = text.slice(start + 1).match(/"(?:[^"\\]|\\.)*"/g) ?? [];
return matches
.map((match) => match.slice(1, -1).replace(/\\(["\\])/g, "$1").trim())
.filter(Boolean);
}
/** Live reasoning text that keeps itself scrolled to the newest line. */
function ReasoningStream({ text }: { text: string }) {
const scroller = useRef<HTMLDivElement>(null);
useEffect(() => {
const el = scroller.current;
if (el) el.scrollTop = el.scrollHeight;
}, [text]);
return (
<div ref={scroller} className="max-h-36 overflow-y-auto whitespace-pre-wrap break-words pr-1 text-[11px] leading-5 text-muted-foreground">
{text}
</div>
);
}
const ResearchTrace = memo(function ResearchTrace({ events, phase, planText, planReasoning, sourceCount, reportStarted, error, onOpenSandbox, active, requestedImageCount }: { events: ProgressEvent[]; phase: string; planText: string; planReasoning: string; sourceCount: number; reportStarted: boolean; error: string | null; onOpenSandbox: () => void; active: boolean; requestedImageCount: number }) {
const [expanded, setExpanded] = useState(true);
const snapshot = useMemo(() => buildTraceSnapshot(events), [events]);
const sourcesById = useMemo(() => new Map(snapshot.sources.map((source) => [source.id, source])), [snapshot.sources]);
const queryTotal = snapshot.queries.length;
const completedQueries = snapshot.queries.filter((query) => query.status === "completed").length;
const progress = queryTotal ? Math.round((completedQueries / queryTotal) * 100) : 0;
const sourceTotal = Math.max(sourceCount, snapshot.sources.length);
const planningDone = phaseAtOrAfter(phase, "collecting") || snapshot.groups.length > 0;
const collectingDone = phaseAtOrAfter(phase, "curating");
const curatingDone = phaseAtOrAfter(phase, "writing") || snapshot.selectedIds.size > 0;
const writingDone = snapshot.reportCompleted || phase === "done";
const streamedQueries = planningDone ? [] : parseStreamedQueries(planText);
const imageStageVisible = requestedImageCount > 0 || snapshot.imageTotal > 0 || snapshot.images.length > 0;
const imageTotal = snapshot.imageTotal || requestedImageCount;
const completedImages = snapshot.images.filter((image) => image.status === "completed").length;
const failedImages = snapshot.images.filter((image) => image.status === "failed").length;
const processedImages = completedImages + failedImages;
const imageDone = imageStageVisible && (snapshot.imagePhaseFinished || phaseAtOrAfter(phase, "exporting") || (!active && phase === "done"));
const imageCurrent = imageStageVisible && !imageDone && (phase === "illustrating" || snapshot.images.some((image) => image.status === "generating"));
const imageProgress = imageTotal ? Math.min(100, Math.round((processedImages / imageTotal) * 100)) : 0;
return (
<div className="overflow-hidden rounded-2xl rounded-tl-md border border-border bg-card shadow-sm">
<div className="flex items-center justify-between gap-3 border-b border-border/70 px-4 py-3">
<div className="min-w-0"><div className="flex items-center gap-2">{active ? <Loader2 className="h-4 w-4 shrink-0 animate-spin text-primary" /> : <CheckCircle2 className="h-4 w-4 shrink-0 text-emerald-600" />}<span className="text-sm font-medium">{active ? "正在进行研究" : "研究过程"}</span></div><p className="mt-1 text-[11px] text-muted-foreground">拆分 {queryTotal} 个检索词 · 完成 {completedQueries}/{queryTotal} · 收集 {sourceTotal} 条资料{snapshot.selectedIds.size ? ` · 采纳 ${snapshot.selectedIds.size} 条` : ""}</p></div>
<Button variant="ghost" size="sm" className="h-7 shrink-0 px-2 text-xs" onClick={() => setExpanded((value) => !value)}>{expanded ? "收起过程" : "展开过程"}<ChevronRight className={`ml-1 h-3.5 w-3.5 transition-transform ${expanded ? "rotate-90" : ""}`} /></Button>
</div>
{expanded && <div className="space-y-5 p-4">
<TraceStage number={1} title="拆分研究范围与检索词" detail={snapshot.groups.length ? `已形成 ${queryTotal} 个可执行检索词,按研究方向分组展示。` : planReasoning.trim() || streamedQueries.length ? "模型正在思考并逐个产出检索词,产出即刻显示。" : "正在根据课题规划检索方向。"} done={planningDone} current={!planningDone}>
{snapshot.subtopics.length > 0 && <div className="mb-2 flex flex-wrap gap-1.5">{snapshot.subtopics.map((topic) => <span key={topic} className="rounded-full bg-primary/10 px-2 py-1 text-[11px] text-primary">研究方向:{topic}</span>)}</div>}
{!planningDone && planReasoning.trim() && (
<div className="mb-2 rounded-lg border border-border/70 bg-muted/[0.3] px-3 py-2">
<p className="mb-1 flex items-center gap-1.5 text-[11px] font-medium text-muted-foreground"><Loader2 className="h-3 w-3 animate-spin text-primary" />模型思考中…</p>
<ReasoningStream text={planReasoning} />
</div>
)}
{snapshot.groups.length > 0 ? <div className="space-y-2">{snapshot.groups.map((group) => <div key={group.title} className="rounded-lg border border-border/70 bg-muted/[0.22] p-2.5"><p className="mb-1.5 text-[11px] font-medium text-muted-foreground">{group.title}</p><div className="flex flex-wrap gap-1.5">{group.queries.map((query) => <span key={query} className="rounded-md border border-border bg-background px-2 py-1 text-xs">{query}</span>)}</div></div>)}</div> : streamedQueries.length > 0 ? <div className="rounded-lg border border-border/70 bg-muted/[0.22] p-2.5"><p className="mb-1.5 flex items-center gap-1.5 text-[11px] font-medium text-muted-foreground"><Loader2 className="h-3 w-3 animate-spin text-primary" />正在拆分检索词…</p><div className="flex flex-wrap gap-1.5">{streamedQueries.map((query) => <span key={query} className="rounded-md border border-border bg-background px-2 py-1 text-xs">{query}</span>)}</div></div> : <div className="rounded-lg border border-dashed border-border px-3 py-2 text-xs text-muted-foreground">等待规划结果…</div>}
</TraceStage>
<TraceStage number={2} title="按顺序执行检索" detail={queryTotal ? `检索按顺序逐个执行;每个检索词的命中资料直接显示在对应检索词下方。进度 ${completedQueries}/${queryTotal}。` : "等待检索词生成后开始逐个调用已有的检索能力。"} done={collectingDone} current={!collectingDone && planningDone}>
<div className="mb-3 h-2 overflow-hidden rounded-full bg-muted"><div className="h-full rounded-full bg-primary transition-[width] duration-300" style={{ width: `${collectingDone ? 100 : progress}%` }} /></div>
{queryTotal > 0 ? <div className="space-y-2.5">{snapshot.queries.map((query, index) => { const done = query.status === "completed"; const running = query.status === "running"; const resultCount = query.resultCount ?? query.sourceIds.length; const querySources = query.sourceIds.map((id) => sourcesById.get(id)).filter((source): source is TraceSource => Boolean(source)); return <div key={`${query.group}:${query.query}`} className="rounded-lg border border-border/70 bg-muted/[0.12]"><div className="flex min-w-0 items-center gap-2 px-3 py-2"><span className={`flex h-5 w-5 shrink-0 items-center justify-center rounded-full text-[10px] ${done ? "bg-emerald-500/15 text-emerald-700" : running ? "bg-primary/12 text-primary" : "bg-muted text-muted-foreground"}`}>{done ? <CheckCircle2 className="h-3 w-3" /> : running ? <Loader2 className="h-3 w-3 animate-spin" /> : index + 1}</span><p className="min-w-0 flex-1 truncate text-xs font-medium">{query.query}</p><span className="shrink-0 text-[11px] text-muted-foreground">{done ? `${resultCount} 条命中` : running ? "检索中" : "等待执行"}</span></div><div className="h-1 overflow-hidden rounded-full bg-muted"><div className={`h-full rounded-full transition-[width] duration-300 ${done ? "w-full bg-emerald-500" : running ? "w-3/5 bg-primary" : "w-0 bg-muted"}`} /></div>{querySources.length > 0 && <div className="space-y-1.5 px-3 pb-2.5 pt-2">{querySources.map((source, sourceIndex) => <div key={source.id} className="rounded-md border border-border/70 bg-background px-2.5 py-2"><div className="flex items-start gap-2"><span className="mt-0.5 text-[10px] text-muted-foreground">{sourceIndex + 1}</span><div className="min-w-0 flex-1"><div className="flex flex-wrap items-center gap-x-2 gap-y-1"><p className="min-w-0 truncate text-[11px] font-medium">{source.title}</p>{source.url && <a href={source.url} target="_blank" rel="noreferrer" className="inline-flex shrink-0 items-center gap-1 text-[11px] text-primary hover:underline">打开来源 <ExternalLink className="h-3 w-3" /></a>}{snapshot.selectedIds.has(source.id) ? <span className="shrink-0 rounded bg-emerald-500/10 px-1.5 py-0.5 text-[10px] text-emerald-700 dark:text-emerald-300">已采纳</span> : snapshot.removedIds.has(source.id) ? <span className="shrink-0 rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground">已排除</span> : null}</div><p className="mt-0.5 text-[10px] text-muted-foreground">{source.sourceType}</p>{source.snippet && <p className="mt-1 line-clamp-2 text-[11px] leading-5 text-muted-foreground">{source.snippet}</p>}</div></div></div>)}</div>}</div>; })}</div> : <div className="rounded-lg border border-dashed border-border px-3 py-2 text-xs text-muted-foreground">检索任务尚未开始。</div>}
</TraceStage>
<TraceStage number={3} title="去重、筛选并压缩上下文" detail={snapshot.selectedIds.size ? `已保留 ${snapshot.selectedIds.size} 条可用来源${snapshot.removedIds.size ? `,排除 ${snapshot.removedIds.size} 条` : ""}${snapshot.compressedSourceCount !== undefined ? `;压缩后使用 ${snapshot.compressedSourceCount} 条上下文` : ""}。` : "完成检索后会去重、筛选可引用来源,再整理为写作上下文。"} done={curatingDone} current={!curatingDone && collectingDone}>
<div className="flex flex-wrap gap-2 text-xs"><span className="rounded-md bg-muted px-2.5 py-1.5">收集:{sourceTotal} 条</span><span className="rounded-md bg-emerald-500/10 px-2.5 py-1.5 text-emerald-700 dark:text-emerald-300">采纳:{snapshot.selectedIds.size} 条</span>{snapshot.removedIds.size > 0 && <span className="rounded-md bg-muted px-2.5 py-1.5">排除:{snapshot.removedIds.size} 条</span>}{snapshot.curationReason && <span className="rounded-md bg-muted px-2.5 py-1.5">规则:{snapshot.curationReason}</span>}</div>
</TraceStage>
<TraceStage number={4} title="流式写入研究报告" detail={writingDone ? "报告已写入 report.md,并保留完整研究过程供回看。" : reportStarted ? "正在把模型输出逐帧合并并写入右侧 report.md。" : "正在整理资料,随后会开始写入报告。"} done={writingDone} current={!writingDone && phaseAtOrAfter(phase, "writing")}>
<button type="button" onClick={onOpenSandbox} className="inline-flex items-center gap-1.5 rounded-md bg-primary/8 px-2.5 py-1.5 text-xs font-medium text-primary hover:bg-primary/12"><FileText className="h-3.5 w-3.5" />{writingDone ? "查看已保存的 report.md" : "打开正在写入的 report.md"}<ChevronRight className="h-3.5 w-3.5" /></button>
</TraceStage>
{imageStageVisible && <TraceStage number={5} title="生成报告配图" detail={imageDone ? completedImages > 0 ? `已生成 ${completedImages} 张配图并嵌入 report.md${failedImages ? `;另有 ${failedImages} 张未生成,文字报告已保留` : ""}。` : "配图未生成,已保留完整文字报告。" : imageCurrent ? `正在生成报告配图,已处理 ${processedImages}/${imageTotal || "?"} 张。` : "报告写完后会为关键章节生成并嵌入配图。"} done={imageDone} current={imageCurrent}>
{imageTotal > 0 && <div className="mb-3 h-2 overflow-hidden rounded-full bg-muted"><div className="h-full rounded-full bg-primary transition-[width] duration-300" style={{ width: `${imageDone ? 100 : imageProgress}%` }} /></div>}
{snapshot.images.length > 0 ? <div className="space-y-2">{snapshot.images.map((image) => <div key={image.position} className="flex min-w-0 items-center gap-2 rounded-lg border border-border/70 bg-muted/[0.12] px-3 py-2"><ImagePlus className={`h-3.5 w-3.5 shrink-0 ${image.status === "completed" ? "text-emerald-600" : image.status === "failed" ? "text-amber-600" : "animate-pulse text-primary"}`} /><div className="min-w-0 flex-1"><p className="truncate text-xs font-medium">第 {image.position} 张 · {image.section}</p><p className="mt-0.5 text-[11px] text-muted-foreground">{image.status === "completed" ? `${image.name ?? "已保存并嵌入报告"}` : image.status === "failed" ? image.error ?? "生成失败,已保留文字报告" : "正在调用图片模型…"}</p></div><span className={`shrink-0 text-[11px] ${image.status === "completed" ? "text-emerald-700 dark:text-emerald-300" : image.status === "failed" ? "text-amber-700 dark:text-amber-300" : "text-primary"}`}>{image.status === "completed" ? "已生成" : image.status === "failed" ? "未生成" : "生成中"}</span></div>)}</div> : <div className="rounded-lg border border-dashed border-border px-3 py-2 text-xs text-muted-foreground">{imageCurrent ? "正在准备第一张报告配图…" : `最多生成 ${imageTotal || requestedImageCount} 张,并在完成后插入对应章节。`}</div>}
{completedImages > 0 && <button type="button" onClick={onOpenSandbox} className="mt-3 inline-flex items-center gap-1.5 rounded-md bg-primary/8 px-2.5 py-1.5 text-xs font-medium text-primary hover:bg-primary/12"><ImagePlus className="h-3.5 w-3.5" />查看已嵌入报告的配图<ChevronRight className="h-3.5 w-3.5" /></button>}
</TraceStage>}
{snapshot.warnings.length > 0 && <div className="rounded-lg bg-amber-500/10 px-3 py-2.5 text-xs leading-5 text-amber-800 dark:text-amber-200"><p className="font-medium">过程提示</p>{snapshot.warnings.map((warning) => <p key={warning} className="mt-1">{warning}</p>)}</div>}
{snapshot.diagnostics.length > 0 && <details className="rounded-lg border border-amber-500/20 bg-amber-500/[0.05] px-3 py-2 text-xs"><summary className="cursor-pointer font-medium text-amber-800 dark:text-amber-200">运行诊断(用于排查,可复制)</summary><pre className="mt-2 max-h-52 overflow-auto whitespace-pre-wrap break-all rounded bg-background/70 p-2 text-[11px] leading-5 text-muted-foreground">{snapshot.diagnostics.map((item) => JSON.stringify(item, null, 2)).join("\n\n")}</pre></details>}
{error && <p className="rounded-lg bg-destructive/10 px-3 py-2 text-xs text-destructive">实时连接提示:{error}。研究仍会继续,页面会从已保存的事件记录恢复。</p>}
</div>}
</div>
);
});
function ReportRegenerationCard({ disabled, onConfigure }: { disabled: boolean; onConfigure: () => void }) {
return (
<div className="rounded-2xl rounded-tl-md border border-primary/20 bg-card p-4 shadow-sm">
<div className="flex items-start gap-2.5">
<div className="mt-0.5 rounded-full bg-primary/10 p-1.5 text-primary">
<Sparkles className="h-4 w-4" />
</div>
<div className="min-w-0 flex-1">
<p className="text-sm font-semibold">想换一种报告结构?</p>
<p className="mt-1 text-xs leading-5 text-muted-foreground">
可选择另一套工作流结构后另生成一篇报告。当前报告与来源会完整保留。
</p>
</div>
</div>
<div className="mt-4 flex justify-end">
<Button size="sm" disabled={disabled} onClick={onConfigure}>
{disabled && <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />}
<Sparkles className="mr-1.5 h-3.5 w-3.5" />
{disabled ? "正在重新生成" : "选择结构再生成"}
</Button>
</div>
</div>
);
}
/**
* The report is stored as a hidden child of the current history record, and its
* result belongs directly below the timeline that produced it. Reusing the normal
* artifact card keeps the open/download affordances identical to any report
* file shown in the conversation.
*/
function InlineGeneratedReportFileCard({
session,
onOpen,
onDownload,
}: {
session: DeepResearchSession;
onOpen: () => void;
onDownload: () => void;
}) {
const structuresQuery = useReportStructures();
const filepath = reportCardDisplayPath(session);
const description = `Markdown file · 报告结构:${reportStructureLabel(session, structuresQuery.data ?? [])}`;
return (
<ArtifactFileList
className="w-full"
files={[filepath]}
threadId={session.id}
onOpenArtifact={onOpen}
onDownloadArtifact={onDownload}
fileDescriptions={{ [filepath]: description }}
/>
);
}
function CompletionSummary({ session, sourceCount, onOpenSandbox, onExport, onRegenerateReport, onRewriteReport, reportRegenerationDisabled }: { session: DeepResearchSession; sourceCount: number; onOpenSandbox: () => void; onExport: (format: "word" | "markdown" | "html") => void; onRegenerateReport: () => void; onRewriteReport: () => void; reportRegenerationDisabled: boolean }) {
const imageCount = countEmbeddedReportImages(session.reportMarkdown);
return <div className="rounded-2xl rounded-tl-md border border-emerald-500/20 bg-card p-4 shadow-sm"><div className="flex items-start gap-2"><div className="mt-0.5 rounded-full bg-emerald-500/12 p-1 text-emerald-600"><CheckCircle2 className="h-3.5 w-3.5" /></div><div><p className="text-sm font-medium">研究报告已完成</p><p className="mt-1 text-sm leading-6 text-muted-foreground">已基于 {sourceCount || session.sourceCount} 条资料完成报告,并保留来源供后续追问。报告正文在右侧沙箱中打开。</p>{imageCount > 0 && <p className="mt-1.5 flex items-center gap-1.5 text-sm leading-6 text-emerald-700 dark:text-emerald-300"><ImagePlus className="h-3.5 w-3.5" />已生成 {imageCount} 张报告配图,已嵌入正文对应章节。</p>}</div></div><div className="mt-4 flex flex-wrap gap-2"><Button size="sm" onClick={onOpenSandbox}><FolderOpen className="mr-1.5 h-3.5 w-3.5" />查看报告</Button><Button size="sm" disabled={reportRegenerationDisabled} onClick={onRegenerateReport}>{reportRegenerationDisabled && <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />}<Sparkles className="mr-1.5 h-3.5 w-3.5" />选择结构再生成</Button><Button size="sm" variant="outline" onClick={onRewriteReport}><FileText className="mr-1.5 h-3.5 w-3.5" />改写报告</Button><Button size="sm" variant="outline" onClick={() => onExport("word")}><FileDown className="mr-1.5 h-3.5 w-3.5" />Word</Button><Button size="sm" variant="outline" onClick={() => onExport("markdown")}><FileCode2 className="mr-1.5 h-3.5 w-3.5" />Markdown</Button><Button size="sm" variant="outline" onClick={() => onExport("html")}><FileType2 className="mr-1.5 h-3.5 w-3.5" />HTML</Button></div></div>;
}
function PlanReviewCard({ plan, submitting, onSubmit }: { plan: Record<string, unknown> | undefined; submitting: boolean; onSubmit: (action: "approve" | "revise", feedback?: string) => void }) {
const [feedback, setFeedback] = useState("");
const objective = typeof plan?.objective === "string" ? plan.objective : "研究计划已生成,确认后继续收集资料。";
return <AssistantTurn><div className="rounded-2xl border border-primary/20 bg-primary/[0.03] p-4 shadow-sm"><p className="text-sm font-medium">请确认研究计划</p><p className="mt-2 text-sm leading-6 text-muted-foreground">{objective}</p><Textarea value={feedback} onChange={(event) => setFeedback(event.target.value)} className="mt-3 min-h-[68px] resize-none text-sm" placeholder="需要调整范围或重点吗?可在这里说明。" /><div className="mt-3 flex justify-end gap-2"><Button size="sm" variant="outline" disabled={submitting || !feedback.trim()} onClick={() => onSubmit("revise", feedback.trim())}>提交调整</Button><Button size="sm" disabled={submitting} onClick={() => onSubmit("approve")}>{submitting && <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />}确认并继续</Button></div></div></AssistantTurn>;
}
// ── advanced settings dialog ─────────────────────────────────────────────────
function AdvancedResearchSettingsDialog({
open,
onOpenChange,
mode,
options,
classicMode,
onClassicModeChange,
imageGenerationAvailable,
imageLimit,
onChange,
}: {
open: boolean;
onOpenChange: (open: boolean) => void;
mode: ResearchMode;
options: AdvancedResearchOptions;
classicMode: boolean;
onClassicModeChange: (value: boolean) => void;
imageGenerationAvailable: boolean;
imageLimit: number;
onChange: <K extends keyof AdvancedResearchOptions>(key: K, value: AdvancedResearchOptions[K]) => void;
}) {
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-h-[88vh] w-[calc(100vw-2rem)] max-w-none overflow-y-auto sm:w-[600px] sm:max-w-[600px]">
<DialogHeader>
<DialogTitle>高级研究配置</DialogTitle>
<DialogDescription>
本次设置会作为下一次研究的默认值;对话式收集的最终选项在报告配置卡片中确认。
</DialogDescription>
</DialogHeader>
<div className="rounded-xl border border-border p-3">
<label className="flex cursor-pointer gap-3">
<input
type="checkbox"
checked={classicMode}
onChange={(event) => onClassicModeChange(event.target.checked)}
className="mt-0.5 accent-primary"
/>
<span>
<span className="block text-sm font-medium">经典模式</span>
<span className="mt-1 block text-xs leading-5 text-muted-foreground">
回退到旧全流程:输入框直接选模式并自动开始研究,不经过收集对话与报告配置卡片。仅影响下一次新建的研究。
</span>
</span>
</label>
</div>
<div className="grid gap-5 py-2 sm:grid-cols-2">
<SettingSelect
label="输出语言"
value={options.language}
onValueChange={(value) => onChange("language", value as AdvancedResearchOptions["language"])}
options={[
{ value: "zh-CN", label: "中文" },
{ value: "en-US", label: "English" },
]}
/>
<SettingSelect
label="报告语气"
value={options.tone}
onValueChange={(value) => onChange("tone", value as ResearchTone)}
options={[
{ value: "objective", label: "客观" },
{ value: "formal", label: "正式" },
{ value: "analytical", label: "分析" },
{ value: "persuasive", label: "说服" },
]}
/>
<NumberSetting label="单次查询结果" hint="1–20 条" value={options.maxSearchResults} onChange={(value) => onChange("maxSearchResults", value)} />
<NumberSetting label="子问题轮数" hint="1–10 轮" value={options.maxIterations} onChange={(value) => onChange("maxIterations", value)} />
<NumberSetting label="最大并发" hint="1–8 路" value={options.maxConcurrency} onChange={(value) => onChange("maxConcurrency", value)} />
<NumberSetting label="上下文词数" hint="500–120000" value={options.maxContextWords} onChange={(value) => onChange("maxContextWords", value)} />
{(mode === "detailed" || mode === "multi_agent") && (
<NumberSetting label="最多子主题" hint="1–20 个" value={options.maxSubtopics} onChange={(value) => onChange("maxSubtopics", value)} />
)}
{mode === "deep" && (
<>
<NumberSetting label="深挖广度" hint="1–8" value={options.deepBreadth} onChange={(value) => onChange("deepBreadth", value)} />
<NumberSetting label="深挖层级" hint="1–4" value={options.deepDepth} onChange={(value) => onChange("deepDepth", value)} />
</>
)}
{mode === "multi_agent" && (
<NumberSetting label="修订轮数" hint="0–5 轮" value={options.maxRevisionLoops} onChange={(value) => onChange("maxRevisionLoops", value)} />
)}
</div>
<ReportOutlineEditor
id="research-outline"
value={options.customOutline}
onChange={(value) => onChange("customOutline", value)}
structureMode={options.structureMode}
onStructureModeChange={(mode) => onChange("structureMode", mode)}
onRetrievalDirectionsChange={(directions) => onChange("retrievalDirections", directions)}
onRetrievalSkillsChange={(skills) => onChange("retrievalSkills", skills)}
/>
{/* 工作流配置:报告结构库(后台 /api/report-structures),选中卡片即填充上方报告结构 */}
<div className="flex items-center justify-between gap-3 rounded-xl border border-border p-3">
<span className="text-xs leading-5 text-muted-foreground">
<span className="block text-sm font-medium text-foreground">报告结构库</span>
在「工作流配置」中管理并选择报告结构;选中卡片后自动填充到上方报告结构。
</span>
<WorkflowConfigButton
appliedContent={options.customOutline}
onApply={(content, structureMode, retrievalDirections, retrievalSkills) => {
onChange("customOutline", content);
onChange("structureMode", structureMode);
onChange("retrievalDirections", retrievalDirections);
onChange("retrievalSkills", retrievalSkills);
}}
/>
</div>
<div className="grid gap-3 sm:grid-cols-2">
<label className="flex cursor-pointer gap-3 rounded-xl border p-3">
<input
type="checkbox"
checked={options.thinkingEnabled}
onChange={(event) => onChange("thinkingEnabled", event.target.checked)}
className="mt-0.5 accent-primary"
/>
<span>
<span className="block text-sm font-medium">启用模型深度思考</span>
<span className="mt-1 block text-xs leading-5 text-muted-foreground">
仅在当前系统默认模型支持时生效,会增加响应时延与模型消耗。
</span>
</span>
</label>
{imageGenerationAvailable && (
<div className="rounded-xl border p-3">
<NumberSetting
label="最多报告配图"
hint={`1–${imageLimit} 张`}
value={options.maxGeneratedImages}
onChange={(value) => onChange("maxGeneratedImages", value)}
/>
</div>
)}
</div>
<DialogFooter>
<Button onClick={() => onOpenChange(false)}>保存配置</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
function NumberSetting({ label, hint, value, onChange }: { label: string; hint: string; value: string; onChange: (value: string) => void }) { return <label className="block"><span className="mb-2 block text-sm font-medium">{label}</span><Input value={value} inputMode="numeric" onChange={(event) => onChange(event.target.value)} /><span className="mt-1 block text-xs text-muted-foreground">{hint}</span></label>; }
function SettingSelect({ label, value, onValueChange, options }: { label: string; value: string; onValueChange: (value: string) => void; options: { value: string; label: string }[] }) { return <label className="block"><span className="mb-2 block text-sm font-medium">{label}</span><Select value={value} onValueChange={onValueChange}><SelectTrigger><SelectValue /></SelectTrigger><SelectContent>{options.map((option) => <SelectItem key={option.value} value={option.value}>{option.label}</SelectItem>)}</SelectContent></Select></label>; }