功能说明:\n- 新增报告协作页(Report Collaboration)核心状态层、消息适配与会话面板,支持按节点/阶段选择和协作上下文展示\n- 补齐 report-collaboration API 与类型定义,并接入页面路由/构建路径,形成可运行的协作链路\n- 重构多轮 RAG 与 write/artefact 消息分组逻辑,优化 AgentChat 与 DeepResearch 场景下的消息展示顺序与可读性\n- 新增/更新 DeepResearch 前端页面(Workbench、报告配置、沙箱联动)以承接报告生成与复用能力\n- 增加报表协作相关单测,覆盖事件归并、消息适配与关键 reducer 行为
200 lines
8.0 KiB
TypeScript
200 lines
8.0 KiB
TypeScript
"use client";
|
||
|
||
/**
|
||
* 深度研究「真沙箱」报告预览 hook —— 仿圆桌 `useStep3Report` 的 stub 机制。
|
||
*
|
||
* 深度研究的报告不是任何 LangGraph 线程里的真实 write_file 工具调用,而是写作
|
||
* job 通过 SSE(report_delta)流出、由 workbench 在内存里拼装的文本。要让工作区
|
||
* 的 `ArtifactFileDetail`(真沙箱)能预览它,这里构造一条**stub ai 消息**:携带
|
||
* 一个 `write_file(report.md)` 的 tool_call,args.content 就是当前报告全文。
|
||
* `ArtifactFileDetail` 通过虚拟 URL `write-file:...?message_id=...&tool_call_id=...`
|
||
* 从 ThreadContext 的 stub 消息里直接读取内容(见 `core/artifacts/loader.ts`),
|
||
* 于是免费获得沙箱的全部既有能力:
|
||
* - 流式期(stub isLoading=true):code 视图自动滚底;
|
||
* - isLoading 翻 false:自动切换 Markdown 预览(Streamdown 渲染)+ 脉冲提示;
|
||
* - 复制 / 另存 / 展示层脱敏等。
|
||
*/
|
||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||
|
||
import {
|
||
artifactPreviewKey,
|
||
useArtifacts,
|
||
} from "@/components/workspace/artifacts";
|
||
import { stripInlineThinkTags } from "@/core/streamdown/inline-think";
|
||
|
||
/** 报告在沙箱中的固定虚拟路径(与 runner 实际写入的 artifacts 路径一致)。 */
|
||
export const REPORT_OUTPUT_PATH = "/mnt/user-data/outputs/report.md";
|
||
|
||
export type ReportStubAiMessage = {
|
||
id: string;
|
||
type: "ai";
|
||
content: string;
|
||
tool_calls: {
|
||
id: string;
|
||
name: string;
|
||
args: Record<string, unknown>;
|
||
}[];
|
||
};
|
||
|
||
export type ReportStubToolMessage = {
|
||
id: string;
|
||
type: "tool";
|
||
name: "write_file";
|
||
tool_call_id: string;
|
||
content: string;
|
||
};
|
||
|
||
interface UseReportSandboxOptions {
|
||
/** stub 线程标识(建议用 sessionId/jobId 派生,切换会话即切换 stub)。 */
|
||
threadKey: string;
|
||
/** 当前报告全文:流式期间为逐帧拼装的文本,完成后为已保存的 reportMarkdown。 */
|
||
report: string;
|
||
/** 报告是否正在流式写入 —— 作为 stub thread 的 isLoading。 */
|
||
writing: boolean;
|
||
/** First visible Markdown has arrived; the host can expand the right panel then. */
|
||
onFirstReportContent?: () => void;
|
||
/**
|
||
* The writing run has produced something observable (report text or model
|
||
* reasoning). Report text streams as non-durable live frames, so on a
|
||
* multi-worker backend it can lag well behind the actual write; this lets
|
||
* the host open the sandbox on the first sign of progress instead.
|
||
*/
|
||
activity?: boolean;
|
||
/**
|
||
* A structural regeneration writes a sibling file in the background. Leave
|
||
* the currently displayed report in the sandbox until the user opens that
|
||
* new card; do not steal the panel for the incoming stream.
|
||
*/
|
||
autoOpen?: boolean;
|
||
}
|
||
|
||
export function useReportSandbox({
|
||
threadKey,
|
||
report,
|
||
writing,
|
||
onFirstReportContent,
|
||
activity = false,
|
||
autoOpen = true,
|
||
}: UseReportSandboxOptions) {
|
||
const { select, setOpen, openStreamedArtifact } = useArtifacts();
|
||
const [stubMessage, setStubMessage] = useState<ReportStubAiMessage | null>(null);
|
||
// Each writing pass opens only once, once it has actual Markdown content.
|
||
const autoOpenedRef = useRef(false);
|
||
const wasWritingRef = useRef(writing);
|
||
|
||
const messageId = `dr-report-${threadKey}`;
|
||
const toolCallId = `dr-report-${threadKey}-write`;
|
||
|
||
const virtualUrl = useMemo(
|
||
() =>
|
||
new URL(
|
||
`write-file:${REPORT_OUTPUT_PATH}?message_id=${encodeURIComponent(messageId)}&tool_call_id=${encodeURIComponent(toolCallId)}`,
|
||
).toString(),
|
||
[messageId, toolCallId],
|
||
);
|
||
|
||
useEffect(() => {
|
||
autoOpenedRef.current = false;
|
||
setStubMessage(null);
|
||
}, [threadKey]);
|
||
|
||
useEffect(() => {
|
||
if (writing && !wasWritingRef.current) autoOpenedRef.current = false;
|
||
wasWritingRef.current = writing;
|
||
}, [writing]);
|
||
|
||
const hadReportRef = useRef(Boolean(report.trim()));
|
||
useEffect(() => {
|
||
const hasReport = Boolean(report.trim());
|
||
// Keep the panel closed through reasoning. When the first Markdown token
|
||
// arrives, allow auto-open even if an earlier empty stub was prepared.
|
||
if (writing && hasReport && !hadReportRef.current) autoOpenedRef.current = false;
|
||
hadReportRef.current = hasReport;
|
||
}, [report, writing]);
|
||
|
||
// 每帧 upsert stub。普通空帧不抹掉已渲染的文件,但写作过程中的
|
||
// 空正文表示后端要求重置报告版本(report_reset)或新稿尚未出首字,
|
||
// 此时必须清掉旧版,避免把首版失败文本继续展示在沙箱里。
|
||
//
|
||
// 清掉的是**正文**而不是文件本身:多 worker 部署下 report_delta 属于
|
||
// 进程内 live 帧,观察端可能连在另一个 worker 上,首帧要等 0.8s 的
|
||
// 落库轮询(report_chunk)才到。若此时把 stub 置为 null,右栏就没有
|
||
// 可打开的虚拟文件,"开始撰写即打开沙箱" 会整段失效。
|
||
useEffect(() => {
|
||
if (!report) {
|
||
if (writing) {
|
||
setStubMessage({
|
||
id: messageId,
|
||
type: "ai",
|
||
content: "",
|
||
tool_calls: [
|
||
{ id: toolCallId, name: "write_file", args: { path: REPORT_OUTPUT_PATH, content: "" } },
|
||
],
|
||
});
|
||
}
|
||
return;
|
||
}
|
||
setStubMessage((prev) => {
|
||
const prevArgs = prev?.tool_calls?.[0]?.args as { content?: unknown } | undefined;
|
||
const prevContent = typeof prevArgs?.content === "string" ? prevArgs.content : "";
|
||
// Backstop the report sandbox against providers that expose reasoning
|
||
// through raw `<think>` tags in ordinary text chunks. The backend
|
||
// filters them at the source; this also protects historical/replayed
|
||
// streams generated by an older service.
|
||
const visibleReport = stripInlineThinkTags(report);
|
||
const content = visibleReport.trim() ? visibleReport : prevContent;
|
||
return {
|
||
id: messageId,
|
||
type: "ai",
|
||
content: "",
|
||
tool_calls: [{ id: toolCallId, name: "write_file", args: { path: REPORT_OUTPUT_PATH, content } }],
|
||
};
|
||
});
|
||
}, [messageId, report, toolCallId, writing]);
|
||
|
||
// 思考结束后的报告正文首帧到达且仍在写入 → 自动展开右栏并选中虚拟 URL。
|
||
// openStreamedArtifact 尊重用户手动关闭(suppress),不会强行弹回。
|
||
useEffect(() => {
|
||
if (!autoOpen || (!report.trim() && !activity) || !writing || autoOpenedRef.current) return;
|
||
autoOpenedRef.current = true;
|
||
onFirstReportContent?.();
|
||
openStreamedArtifact(virtualUrl, artifactPreviewKey(virtualUrl));
|
||
}, [activity, autoOpen, onFirstReportContent, openStreamedArtifact, report, virtualUrl, writing]);
|
||
|
||
/** 手动打开(头部「报告」按钮 / 完成卡「查看报告」):始终选中虚拟 URL。 */
|
||
const openReport = useCallback(() => {
|
||
select(virtualUrl, false);
|
||
setOpen(true);
|
||
}, [select, setOpen, virtualUrl]);
|
||
|
||
// Effects clear the previous message after a thread switch. Do not wait
|
||
// for that post-render effect before changing what is rendered: a report
|
||
// regeneration must show an empty new file immediately, never one frame of
|
||
// the previous report while the model is still preparing its first token.
|
||
const currentStubMessage = stubMessage?.id === messageId ? stubMessage : null;
|
||
|
||
return {
|
||
virtualUrl,
|
||
stubMessages: useMemo(
|
||
() => {
|
||
if (!currentStubMessage) return [];
|
||
if (writing) return [currentStubMessage];
|
||
// ArtifactFileDetail determines whether a write is still streaming by
|
||
// matching the write_file call with its tool result. `isLoading=false`
|
||
// alone is intentionally ignored there, so completed and historical
|
||
// virtual reports must include this synthetic completion receipt.
|
||
const completedWrite: ReportStubToolMessage = {
|
||
id: `${toolCallId}-result`,
|
||
type: "tool",
|
||
name: "write_file",
|
||
tool_call_id: toolCallId,
|
||
content: "ok",
|
||
};
|
||
return [currentStubMessage, completedWrite];
|
||
},
|
||
[currentStubMessage, toolCallId, writing],
|
||
),
|
||
openReport,
|
||
};
|
||
}
|