Files
deerflow-code/frontend-web/src/core/threads/use-research-writing-feed.ts
T
董宏凯 4964967295 fix: writing mode first-report allows only the pipeline to write the report
- Strip write_file/str_replace/bash from the model binding in the
  first-report run: after_model rewrites only fire after a full model
  response, so any bound write tool let weak models draft the whole
  essay into tool args (write_file content or bash cat>/python
  heredocs) for tens of invisible seconds before interception
- Hallucinated hand-writes are still handled: after_model rewrites
  bash cat >/python open('w')/tee and leftover write calls to
  deep_research_report; wrap_tool_call rejects whatever reaches the
  tool layer; post-success writes are dropped, nudged to a 2-3
  sentence summary, and patched with a fallback closing message so
  the turn never ends silently
- The rewritten pipeline call carries topic = original request
  (clarification answers skipped) plus focus = clarification answers,
  so the pipeline writes the clarified subject instead of the raw
  prompt text; prompts updated to match (tools unavailable, call the
  tool directly, do not draft first)
- Frontend write-step interception and streaming preview scoping now
  applies only in writing mode; normal mode shows/previews writes
  exactly as before
2026-08-30 15:53:43 +08:00

124 lines
4.8 KiB
TypeScript

"use client";
/**
* 聊天页「写作模式」深度研究进度注入。
*
* 把 `useResearchReportStream` 的流式状态插到 `deep_research_report`
* 工具结果之后、模型总结之前(进度步骤条 + report.md 的 write_file stub):
*
* - 进行中 / 中断:始终注入(中断态展示「已中断」,下一轮 jobId 变化自然淘汰);
* - 成功:注入到真实 report.md 产物落地为止(artifacts 出现该路径即撤出),
* 之后由真实的工具消息 + 产物卡片接管展示,避免闪烁与重复。
*
* 沙箱时机:报告首帧正文到达且仍在写入时,这里直接调 `openStreamedArtifact`
* 选中 write-file 虚拟预览并展开右侧沙箱,让报告「打开沙箱后在沙箱里边写边
* 预览」——与工作台 `useReportSandbox` 同一语义,不依赖消息列表里
* `ArtifactWriteToolCall` 的 isLast/isLoading 判定(长工具运行期间该链路不
* 稳定);用户手动关闭本条预览后不会强行弹回。完成后(真实 report.md 落
* 地、stub 撤出前)再把沙箱选中项从虚拟预览交接到真实产物。
*/
import { useEffect, useMemo, useRef } from "react";
import type { Message } from "@langchain/langgraph-sdk";
import {
artifactPreviewKey,
useArtifactsOptional,
} from "@/components/workspace/artifacts/context";
import { resolveWriteFilePath } from "@/core/artifacts/write-file-in-flight";
import {
buildResearchFeedMessages,
buildResearchReportVirtualUrl,
composeResearchDisplayMessages,
RESEARCH_REPORT_OUTPUT_PATH,
useResearchReportStream,
} from "./use-research-report-stream";
import { isInterceptedWritingReportWrite } from "./writing-mode";
type FeedThreadLike = {
messages: Message[];
values: { artifacts?: string[] } & Record<string, unknown>;
isLoading?: boolean;
};
export function useResearchWritingFeed<T extends FeedThreadLike>(
threadId: string | null | undefined,
thread: T,
): { displayThread: T } {
const research = useResearchReportStream(threadId);
const artifacts = useArtifactsOptional();
// 一次写作轮(jobId)只在首帧正文到达时打开一次沙箱。
const autoOpenedJobRef = useRef<string | null>(null);
const handedOverJobRef = useRef<string | null>(null);
const hasRealArtifact = useMemo(
() => (thread.values?.artifacts ?? []).some((path) => path === RESEARCH_REPORT_OUTPUT_PATH),
[thread.values?.artifacts],
);
// 正文首 token 到达且仍在写入 → 主动展开右侧沙箱。思考阶段不打开,
// 避免「写入文件 report.md」出现在模型还在想的时候。
useEffect(() => {
if (
!research ||
research.status !== "active" ||
research.phase !== "writing" ||
!research.reportText.trim()
) {
return;
}
if (autoOpenedJobRef.current === research.jobId) return;
autoOpenedJobRef.current = research.jobId;
const virtualUrl = buildResearchReportVirtualUrl(research);
artifacts?.openStreamedArtifact(virtualUrl, artifactPreviewKey(virtualUrl));
}, [artifacts, research]);
// 完成交接:真实 report.md 落地、stub 即将撤出时,把沙箱从 write-file
// 虚拟预览切到真实产物(否则虚拟 URL 的内容源消失会白屏,且 chat-box 的
// 新产物自动选中因 selectedArtifact 非空而被跳过)。用户中途手动切到别
// 的产物则不打扰。
useEffect(() => {
if (!research || research.status !== "success" || !hasRealArtifact) return;
if (handedOverJobRef.current === research.jobId) return;
if (!artifacts) return;
handedOverJobRef.current = research.jobId;
const current = artifacts.selectedArtifact;
const virtualUrl = buildResearchReportVirtualUrl(research);
const currentPath = current ? resolveWriteFilePath(current) : "";
const keepUserSelection =
current !== null &&
current !== virtualUrl &&
current !== RESEARCH_REPORT_OUTPUT_PATH &&
// research 流存在即本线程跑过写作模式管线,这里恒按写作模式判定。
!isInterceptedWritingReportWrite(currentPath, undefined, undefined, true);
if (keepUserSelection) {
return;
}
artifacts.select(RESEARCH_REPORT_OUTPUT_PATH);
artifacts.setOpen(true);
}, [artifacts, hasRealArtifact, research]);
const feedMessages = useMemo(() => {
if (!research) return [];
if (research.status === "success" && hasRealArtifact) return [];
return buildResearchFeedMessages(research);
}, [hasRealArtifact, research]);
const displayThread = useMemo(() => {
const messages = composeResearchDisplayMessages(
thread.messages,
feedMessages as unknown as Message[],
);
if (messages === thread.messages) return thread;
return {
...thread,
values: { ...thread.values, messages },
messages,
} as T;
}, [feedMessages, thread]);
return { displayThread };
}