feat: 新增 agentfx 任务深链与研判报告入库流程

支持 goPath=agentfx 的 iframe 嵌入问答、内置研判助手种子与报告导入协助卡,并完善深度研究流式报告能力。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
董宏凯andCursor committed 2026-08-27 16:32:22 +08:00
1 parent 6e9e89a6cb
commit 52b9cbf707
34 files changed
+4488 -392

No files matched your search

@@ -0,0 +1,116 @@
/**
* 「agentfx」任务深链:复制自 [[task-deeplink]] 的 3qfx 单智能体模式,供新系统 iframe 嵌入
* (``${loginBase}?password=xxx&taskId=xxx&goPath=agentfx&embed=1&hideJump=1&theme=dark-blue``)。
*
* 与 3qfx 的差异(也是单独复制一份的原因,后续逻辑改动互不影响):
* 1. 任务详情不走外部 consumer(``VITE_AIPI_CONSUMER_URL``),改调本系统 Gateway 的
* ``GET {backend}/taskAnalyseSearch/cop-task-detail?taskId=``(带 DeerFlow 登录态,任务数据
* 来自 TaskCOP 任务表,即任务列表 / 报告导入用的同一份)。
* 2. **固定使用内置智能体** ``agentfx-analyst``(后端 seeder ``_agentfx_seed.py`` 启动时补建:
* 搜集信息 → 生成 report.md + task-reports.json(14 类)→ 总结 → 前端「入库」协助卡 /
* task-report-import 技能入库),不走「配置管理」业务映射。
* 3. 路由挂在 ``plan-task-agentfx`` 前缀下,页面代码见 [[AgentFxWorkspace]]。
*
* 任务详情整包仍暂存到与 3qfx 相同的 sessionStorage 键(``login.copTaskDetail``,见
* [[persistCopTaskDetail]]):该键按标签页隔离(嵌入态无跨标签污染),工作区「当前任务」
* 卡片与 AgentChatPage 的 taskBind 自恢复逻辑都读它,保持行为一致。
*/
import { apiFetch } from "@/core/api/fetch-client";
import { getBackendBaseURL } from "@/core/config";
import { clearTaskContext, persistTaskContext } from "@/core/auth/task-purpose";
import {
type CopTaskDetail,
type TaskDeeplinkTarget,
} from "@/core/auth/task-deeplink";
/** 深链 goPath 基础码(大小写不敏感匹配;不支持 ``-A`` 会商后缀)。 */
export const AGENTFX_GOPATH = "agentfx";
/**
* 固定使用的内置智能体 id(后端 ``_agentfx_seed.py`` 启动时补建并 upsert 进 agents 表,
* ``user_id IS NULL`` 对所有用户可见)。前端深链不查业务映射,直接进该智能体的问答。
*/
export const AGENTFX_BUILTIN_AGENT_ID = "agentfx-analyst";
/** 工作区路由前缀(与 StrategyRoutes 的 plan-task-agentfx 子树一致)。 */
export const AGENTFX_TASK_BASE = "/page/strategy/task-management/plan-task-agentfx";
/** 判断 goPath 是否为 agentfx(大小写不敏感)。 */
export function isAgentfxGoPath(goPath: string): boolean {
return goPath.trim().toLowerCase() === AGENTFX_GOPATH;
}
/**
* 拉取任务详情:本系统 Gateway 的 cop-task-detail(返回与旧 consumer 同构的
* ``{state, msg, data}`` 信封)。任务不存在 / 网络失败时返回 null,调用方(LoginPage)
* 用仅含任务 id 的 stub 兜底继续跳转。
*/
export async function fetchAgentfxTaskDetail(taskId: string): Promise<CopTaskDetail | null> {
if (!taskId) return null;
try {
// apiFetch 已统一注入 DeerFlow 登录态(Authorization / cookie),登录刚完成即可用。
const query = new URLSearchParams({ taskId });
const res = await apiFetch(
`${getBackendBaseURL()}/taskAnalyseSearch/cop-task-detail?${query.toString()}`,
{ method: "GET" },
);
if (!res.ok) {
console.warn("[agentfx-deeplink] cop-task-detail failed", { taskId, status: res.status });
return null;
}
const body = (await res.json().catch(() => null)) as { data?: unknown } | null;
const data = body && typeof body === "object" ? body.data : null;
if (!data || typeof data !== "object") return null;
const d = data as Record<string, unknown>;
return {
id: (d.id as string | number | null) ?? null,
overview: typeof d.overview === "string" ? d.overview : "",
taskDirection: typeof d.taskDirection === "string" ? d.taskDirection : "",
taskName: typeof d.taskName === "string" ? d.taskName : "",
taskContent: typeof d.taskContent === "string" ? d.taskContent : "",
};
} catch (error) {
console.warn("[agentfx-deeplink] cop-task-detail failed", { taskId, error });
return null;
}
}
/**
* 用 taskName / taskContent 拼开场信息文本;末尾附任务 id(task_id)供后端识别任务。
* 复制自 task-deeplink 的 buildOpeningText 基础三行(无 xdfx 行动追加),便于后续按新系统
* 要求单独调整格式。
*/
export function buildAgentfxOpeningText(detail: CopTaskDetail, taskId: string): string {
return [
detail.taskName ? `任务名称:${detail.taskName}` : "",
detail.taskContent ? `任务内容:${detail.taskContent}` : "",
taskId ? `任务id(task_id)为${taskId}` : "",
]
.filter(Boolean)
.join("\n");
}
/**
* 解析 agentfx 跳转目标:内置「任务研判报告智能体」的问答工作区(任务↔对话 1:N,按
* taskId + agentId 隔离)。清残留任务上下文 → 暂存任务上下文(taskId + agentId + 开场
* 信息)→ 返回 chats 索引路径,由工作区决定开最新历史对话 / 新建(首次无历史自动发
* 开场信息,见 AgentChatPage 的 taskBind)。
*/
export async function resolveAgentfxDeeplinkTarget(
detail: CopTaskDetail,
taskId: string,
): Promise<TaskDeeplinkTarget | null> {
// 清掉上一次深链可能残留的任务上下文(下面用本次任务重新写入)。
clearTaskContext();
const agentId = AGENTFX_BUILTIN_AGENT_ID;
persistTaskContext({
taskId,
agentId,
openingText: buildAgentfxOpeningText(detail, taskId),
actionId: taskId,
partitionByAction: false,
});
return { path: `${AGENTFX_TASK_BASE}/agent/${agentId}/chats` };
}
+22
View File
@@ -26,6 +26,8 @@ interface AssistantSetupReportStructureApprovalGroup extends GenericMessageGroup
interface AssistantResearchApprovalGroup extends GenericMessageGroup<"assistant:research-approval"> {}
interface AssistantTaskReportImportGroup extends GenericMessageGroup<"assistant:task-report-import"> {}
interface AssistantSubagentGroup extends GenericMessageGroup<"assistant:subagent"> {}
type MessageGroup =
@@ -38,6 +40,7 @@ type MessageGroup =
| AssistantSetupWritingApprovalGroup
| AssistantSetupReportStructureApprovalGroup
| AssistantResearchApprovalGroup
| AssistantTaskReportImportGroup
| AssistantSubagentGroup;
export function groupMessages<T>(
@@ -146,6 +149,16 @@ export function groupMessages<T>(
});
continue;
}
// agentfx「入库」协助卡:虚拟 ai 消息(additional_kwargs.task_report_import_approval),
// 由任务工作区宿主(AgentChatPage taskBind)注入,经 taskReportImportSlot 渲染。
if (hasTaskReportImportApproval(message)) {
groups.push({
id: message.id,
type: "assistant:task-report-import",
messages: [message],
});
continue;
}
if (hasPresentFiles(message)) {
groups.push({
id: message.id,
@@ -452,6 +465,15 @@ export function hasResearchApproval(message: Message) {
);
}
/** agentfx「入库」协助卡:宿主注入的虚拟 ai 消息(additional_kwargs.task_report_import_approval)。 */
export function hasTaskReportImportApproval(message: Message) {
return (
message.type === "ai" &&
typeof message.additional_kwargs?.task_report_import_approval === "object" &&
message.additional_kwargs.task_report_import_approval !== null
);
}
export function extractPresentFilesFromMessage(message: Message) {
if (message.type !== "ai" || !hasPresentFiles(message)) {
return [];
+31 -2
View File
@@ -24,6 +24,10 @@ import type { UploadedFileInfo } from "../uploads";
import { promptInputFilePartToFile, uploadFiles } from "../uploads";
import type { AgentThread, AgentThreadState } from "./types";
import {
finalizeResearchReportStream,
ingestResearchReportEvent,
} from "./use-research-report-stream";
import {
collectHumanMessageIds,
hasServerEchoedOptimisticHuman,
@@ -774,6 +778,25 @@ export function useThreadStream({
},
onCustomEvent(event: unknown) {
markStreamActivity();
// 写作模式内联深度研究的进度帧(deep_research_report 工具经
// get_stream_writer 转发):归约进 per-thread 状态,聊天页据此注入
// 进度步骤条与 report.md 流式预览。
if (
typeof event === "object" &&
event !== null &&
"type" in event &&
event.type === "deep_research_report" &&
"event" in event &&
typeof (event as { event?: unknown }).event === "object" &&
(event as { event?: unknown }).event !== null
) {
const tid = threadIdRef.current ?? onStreamThreadId ?? null;
const frame = (event as { event: Record<string, unknown> }).event;
if (tid && typeof frame.type === "string") {
ingestResearchReportEvent(tid, frame as Parameters<typeof ingestResearchReportEvent>[1]);
}
return;
}
if (
typeof event === "object" &&
event !== null &&
@@ -912,6 +935,10 @@ export function useThreadStream({
return;
}
setStreamHoldOpen(false);
// run 真正终结(非 rejoin):若深度研究报告流仍 active(tool_finished
// 帧丢失/被取消),标记中断,避免进度条永久转圈。
const finThreadId = threadIdRef.current ?? onStreamThreadId ?? null;
if (finThreadId) finalizeResearchReportStream(finThreadId);
listeners.current.onFinish?.(state.values);
void queryClient.invalidateQueries({ queryKey: ["threads", "search"] });
});
@@ -1618,8 +1645,10 @@ export function useThreadStream({
activeRunIdRef.current ?? (tid ? readActiveRunId(tid) : null);
setStreamHoldOpen(false);
activeRunIdRef.current = null;
if (tid && runId) {
persistActiveRunId(tid, runId);
if (tid) {
// 用户显式停止:深度研究报告流立即定格为中断。
finalizeResearchReportStream(tid);
if (runId) persistActiveRunId(tid, runId);
}
try {
await Promise.resolve(threadStreamRef.current?.stop());
@@ -0,0 +1,216 @@
import assert from "node:assert/strict";
import test from "node:test";
import type { ResearchReportStreamState } from "./use-research-report-stream";
import {
buildResearchFeedMessages,
buildResearchProgressToolCalls,
buildResearchReportVirtualUrl,
clearResearchReportStream,
finalizeResearchReportStream,
ingestResearchReportEvent,
peekResearchReportStream,
subscribeResearchReportStream,
} from "./use-research-report-stream";
import { buildWriteFileVirtualUrl } from "../artifacts/streaming-write-preview";
// 模块级 store 按 threadId 隔离;每个测试用独立 threadId 避免串扰。
let seq = 0;
const nextThread = () => `t-${++seq}`;
function ingestAll(threadId: string, frames: Array<Record<string, unknown>>) {
for (const frame of frames) {
ingestResearchReportEvent(
threadId,
frame as Parameters<typeof ingestResearchReportEvent>[1],
);
}
}
function streamOf(overrides: Partial<ResearchReportStreamState> = {}): ResearchReportStreamState {
return {
status: "active",
jobId: "j",
phase: "initializing",
queries: [],
completedQueries: 0,
sourceCount: 0,
reportText: "",
thinking: "",
error: null,
...overrides,
};
}
test("ingest accumulates plan/collect progress frames", () => {
const tid = nextThread();
ingestAll(tid, [
{ type: "phase_changed", jobId: "j1", phase: "planning", payload: { to: "planning" } },
{ type: "queries_planned", jobId: "j1", payload: { queries: ["q1", "q2", "q3"] } },
{ type: "phase_changed", jobId: "j1", phase: "collecting", payload: { to: "collecting" } },
{ type: "query_completed", jobId: "j1", payload: { query: "q1", resultCount: 5 } },
{ type: "query_completed", jobId: "j1", payload: { query: "q2", resultCount: 3 } },
{ type: "sources_curated", jobId: "j1", payload: { selectedIds: ["a", "b", "c", "d"] } },
]);
const state = peekResearchReportStream(tid);
assert.equal(state?.jobId, "j1");
assert.equal(state?.phase, "collecting");
assert.deepEqual(state?.queries, ["q1", "q2", "q3"]);
assert.equal(state?.completedQueries, 2);
// query_completed 累计 8,sources_curated 的 4 条选中集覆盖为最终值。
assert.equal(state?.sourceCount, 4);
assert.equal(state?.status, "active");
});
test("report_delta and report_chunk dedupe by offset when both arrive", () => {
const tid = nextThread();
ingestAll(tid, [
{ type: "report_delta", jobId: "j2", phase: "writing", payload: { delta: "第一段", offset: 0 } },
{ type: "report_chunk", jobId: "j2", phase: "writing", payload: { delta: "第一段", offset: 0 } },
{ type: "report_chunk", jobId: "j2", phase: "writing", payload: { delta: "第二段", offset: 3 } },
{ type: "report_delta", jobId: "j2", phase: "writing", payload: { delta: "第二段", offset: 3 } },
]);
assert.equal(peekResearchReportStream(tid)?.reportText, "第一段第二段");
});
test("an offset-0 frame with different content rewrites from that offset (workbench parity)", () => {
const tid = nextThread();
ingestAll(tid, [
{ type: "report_delta", jobId: "j2b", payload: { delta: "第一段第二段", offset: 0 } },
// 生产端从头重写(如 reset 后重发):内容不匹配 → 从 offset 0 覆盖。
{ type: "report_delta", jobId: "j2b", payload: { delta: "全新开头", offset: 0 } },
]);
assert.equal(peekResearchReportStream(tid)?.reportText, "全新开头");
});
test("non-report targets (sources/plan json) never pollute reportText", () => {
const tid = nextThread();
ingestAll(tid, [
{ type: "report_delta", jobId: "j3", payload: { target: "sources", delta: "[1] 来源", offset: 0 } },
{ type: "report_chunk", jobId: "j3", payload: { target: "report", delta: "# 报告", offset: 0 } },
]);
assert.equal(peekResearchReportStream(tid)?.reportText, "# 报告");
});
test("a new jobId resets prior state", () => {
const tid = nextThread();
ingestAll(tid, [
{ type: "report_delta", jobId: "old", payload: { delta: "旧报告", offset: 0 } },
{ type: "queries_planned", jobId: "new", payload: { queries: ["n1"] } },
]);
const state = peekResearchReportStream(tid);
assert.equal(state?.jobId, "new");
assert.equal(state?.reportText, "");
assert.deepEqual(state?.queries, ["n1"]);
});
test("tool_finished marks success and finalize guards only active runs", () => {
const tid = nextThread();
ingestAll(tid, [
{ type: "report_delta", jobId: "j4", payload: { delta: "正文", offset: 0 } },
{ type: "tool_finished", jobId: "j4", payload: { status: "success" } },
]);
assert.equal(peekResearchReportStream(tid)?.status, "success");
// 已 success 的状态不被 finalize 翻转。
finalizeResearchReportStream(tid);
assert.equal(peekResearchReportStream(tid)?.status, "success");
const tid2 = nextThread();
ingestAll(tid2, [
{ type: "report_delta", jobId: "j5", payload: { delta: "写到一半", offset: 0 } },
]);
finalizeResearchReportStream(tid2);
const interrupted = peekResearchReportStream(tid2);
assert.equal(interrupted?.status, "error");
assert.equal(interrupted?.error, "已中断");
clearResearchReportStream(tid2);
assert.equal(peekResearchReportStream(tid2), null);
});
test("progress tool calls reveal stages stepwise and mark interruption", () => {
const active = streamOf({
jobId: "j6",
phase: "collecting",
queries: ["q1", "q2"],
completedQueries: 1,
sourceCount: 3,
});
const calls = buildResearchProgressToolCalls(active);
assert.equal(calls.length, 2); // 拆解已完成 + 检索进行中
assert.equal(calls[0].args.status, "complete");
assert.equal(calls[1].args.status, "active");
assert.match(calls[1].args.detail, /1\/2/);
const writing = streamOf({ jobId: "j7", phase: "writing", reportText: "# x" });
assert.equal(buildResearchProgressToolCalls(writing).length, 3);
assert.equal(buildResearchProgressToolCalls(writing)[2].args.status, "active");
const failed = streamOf({ jobId: "j8", phase: "writing", status: "error", error: "模型超时" });
const failedCalls = buildResearchProgressToolCalls(failed);
assert.match(failedCalls.at(-1)?.args.label ?? "", /已中断/);
assert.match(failedCalls.at(-1)?.args.detail ?? "", /模型超时/);
});
test("feed messages attach the write_file stub only once report text exists", () => {
const noText = streamOf({ jobId: "j9", phase: "collecting" });
assert.equal(buildResearchFeedMessages(noText).length, 1);
assert.equal(buildResearchFeedMessages(noText)[0].tool_calls[0].name, "deep_research_progress");
const withText = streamOf({ jobId: "j10", phase: "writing", reportText: "# 报告正文" });
const feed = buildResearchFeedMessages(withText);
assert.equal(feed.length, 2);
const stub = feed[1].tool_calls[0];
assert.equal(stub.name, "write_file");
assert.equal(stub.args.path, "/mnt/user-data/outputs/report.md");
assert.equal(stub.args.content, "# 报告正文");
});
test("virtual URL matches the message-list ArtifactWriteToolCall URL (one suppression key)", () => {
const state = streamOf({ jobId: "j11", phase: "writing", reportText: "# x" });
// 显式自动开沙箱(useResearchWritingFeed)与消息列表里 ArtifactWriteToolCall
// 各自构造的 write-file 虚拟 URL 必须完全一致:二者共用同一 previewKey
// (`message_id:tool_call_id`),用户手动关闭一次即对两条路径同时生效。
assert.equal(
buildResearchReportVirtualUrl(state),
buildWriteFileVirtualUrl({
path: "/mnt/user-data/outputs/report.md",
messageId: "research-report-j11",
toolCallId: "research-report-j11-write",
}),
);
});
test("token-frame notifications are coalesced; terminal frames flush immediately", async () => {
const tid = nextThread();
let notifications = 0;
const unsubscribe = subscribeResearchReportStream(tid, () => {
notifications += 1;
});
try {
ingestAll(tid, [
{ type: "report_thinking", jobId: "jc", phase: "writing", payload: { delta: "思考" } },
{ type: "report_delta", jobId: "jc", phase: "writing", payload: { delta: "第一", offset: 0 } },
{ type: "report_delta", jobId: "jc", phase: "writing", payload: { delta: "第二", offset: 2 } },
{ type: "report_delta", jobId: "jc", phase: "writing", payload: { delta: "第三", offset: 4 } },
]);
// 状态同步更新(快照立即可见),但通知被合并——节流窗口内一次不发。
assert.equal(peekResearchReportStream(tid)?.reportText, "第一第二第三");
assert.equal(notifications, 0);
// 窗口(100ms)过后一次性通知。
await new Promise((resolve) => setTimeout(resolve, 200));
assert.equal(notifications, 1);
// 终态帧不等待节流窗口,立即通知。
ingestAll(tid, [{ type: "tool_finished", jobId: "jc", payload: { status: "success" } }]);
assert.equal(peekResearchReportStream(tid)?.status, "success");
assert.equal(notifications, 2);
} finally {
unsubscribe();
}
});
@@ -0,0 +1,378 @@
"use client";
/**
* 聊天「写作模式」内联深度研究报告的流式状态。
*
* 后端 `deep_research_report` 工具把引擎事件经 LangGraph custom 通道
* (`get_stream_writer`)以 `{type: "deep_research_report", event: {...}}`
* 帧发到前端 `onCustomEvent`;本模块按 threadId 归约这些帧,供聊天页注入
* 进度步骤条(`deep_research_progress` 虚拟工具调用)与 report.md 的
* `write_file` stub 流式预览(复用沙箱 write-file 虚拟 URL 机制)。
*
* 与工作台 SSE 不同:custom 事件不落库、断线不重放,刷新页面即丢——
* 报告完成后 md 已持久化在聊天线程 artifacts,由真实产物接管展示。
*/
import { useCallback, useSyncExternalStore } from "react";
/** 深度研究 basic 管线的阶段序(与后端 events.ALL_PHASES 对齐的子集)。 */
const PHASE_ORDER = [
"initializing",
"planning",
"collecting",
"curating",
"compressing",
"writing",
"done",
] as const;
function phaseRank(phase: string): number {
const index = PHASE_ORDER.indexOf(phase as (typeof PHASE_ORDER)[number]);
return index === -1 ? 0 : index;
}
export type ResearchReportStreamState = {
/** "active" | "success" | "error"(含被取消/断流)。 */
status: "active" | "success" | "error";
/** 工具调用 id(帧里的 jobId),一次写作轮一个。 */
jobId: string;
phase: string;
queries: string[];
completedQueries: number;
sourceCount: number;
/** report_delta/report_chunk 按 offset 去重拼装的报告全文。 */
reportText: string;
/** report_thinking 增量(写作思考,可选展示)。 */
thinking: string;
error: string | null;
};
type Listener = () => void;
type StoreEntry = {
state: ResearchReportStreamState | null;
listeners: Set<Listener>;
emitTimer: ReturnType<typeof setTimeout> | null;
};
const EMPTY_ACTIVE: ResearchReportStreamState = {
status: "active",
jobId: "",
phase: "initializing",
queries: [],
completedQueries: 0,
sourceCount: 0,
reportText: "",
thinking: "",
error: null,
};
const stores = new Map<string, StoreEntry>();
function getStore(threadId: string): StoreEntry {
let store = stores.get(threadId);
if (!store) {
store = { state: null, listeners: new Set(), emitTimer: null };
stores.set(threadId, store);
}
return store;
}
/**
* token 帧的通知合并间隔(ms)。report_delta / report_thinking 是 token 级
* 高频帧(每秒可达数十帧);状态本身同步更新(字符串拼接很便宜),但订阅
* 通知若逐帧发出,会让聊天页整棵树(长消息列表 + 沙箱 Markdown 预览)按
* token 频率重渲染,页面直接卡死。工作台用 requestAnimationFrame 批处理
* (DeepResearchWorkbench),聊天这里等效地按固定间隔合并——每秒最多
* 10 次通知,流式观感不受影响。终态帧(tool_finished)与
* finalize/clear 立即 flush,结束态不滞后。
*/
const EMIT_COALESCE_MS = 100;
function emitNow(store: StoreEntry) {
if (store.emitTimer !== null) {
clearTimeout(store.emitTimer);
store.emitTimer = null;
}
for (const listener of store.listeners) listener();
}
function emitCoalesced(store: StoreEntry) {
if (store.emitTimer !== null) return;
store.emitTimer = setTimeout(() => {
store.emitTimer = null;
for (const listener of store.listeners) listener();
}, EMIT_COALESCE_MS);
}
export function clearResearchReportStream(threadId: string) {
const store = getStore(threadId);
if (store.state === null) return;
store.state = null;
emitNow(store);
}
/** run 结束(成功/失败/取消/断流)时收尾仍处于 active 的状态。 */
export function finalizeResearchReportStream(threadId: string) {
const store = getStore(threadId);
if (store.state?.status !== "active") return;
store.state = { ...store.state, status: "error", error: store.state.error ?? "已中断" };
emitNow(store);
}
/** 与工作台 appendReportDelta 相同的 offset 去重追加。 */
function appendWithOffset(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;
}
/** onCustomEvent 深度研究帧的 event 载荷。 */
export type ResearchReportEventFrame = {
type: string;
phase?: string;
payload?: Record<string, unknown>;
};
export function ingestResearchReportEvent(threadId: string, frame: ResearchReportEventFrame) {
const store = getStore(threadId);
const jobId = typeof (frame as { jobId?: unknown }).jobId === "string"
? String((frame as { jobId?: unknown }).jobId)
: "";
const previous = store.state;
// 新一轮工具调用(jobId 变化)从零开始,旧状态自然淘汰。
const base: ResearchReportStreamState = previous && previous.jobId === jobId
? previous
: { ...EMPTY_ACTIVE, jobId };
const payload = frame.payload ?? {};
let next = base;
switch (frame.type) {
case "phase_changed":
next = { ...base, phase: typeof payload.to === "string" ? payload.to : base.phase };
break;
case "queries_planned":
next = {
...base,
queries: Array.isArray(payload.queries)
? payload.queries.filter((q): q is string => typeof q === "string")
: base.queries,
completedQueries: 0,
};
break;
case "query_completed":
next = {
...base,
completedQueries: base.completedQueries + 1,
sourceCount: base.sourceCount + (typeof payload.resultCount === "number" ? payload.resultCount : 0),
};
break;
case "sources_curated": {
const selected = Array.isArray(payload.selectedIds) ? payload.selectedIds.length : null;
next = {
...base,
sourceCount: selected !== null && selected > 0 ? selected : base.sourceCount,
};
break;
}
case "report_delta":
case "report_chunk": {
if (typeof payload.target === "string" && payload.target !== "report") break;
const delta = typeof payload.delta === "string" ? payload.delta : "";
const reportText = appendWithOffset(base.reportText, delta, payload.offset);
next = reportText === base.reportText ? base : { ...base, reportText };
break;
}
case "report_thinking": {
const delta = typeof payload.delta === "string" ? payload.delta : "";
next = delta ? { ...base, thinking: base.thinking + delta } : base;
break;
}
case "report_completed":
next = {
...base,
phase: "writing",
sourceCount: typeof payload.sourceCount === "number" && payload.sourceCount > 0
? payload.sourceCount
: base.sourceCount,
};
break;
case "warning":
case "error": {
const message = typeof payload.message === "string" ? payload.message : "";
if (payload.recoverable === false && message) {
next = { ...base, error: message };
}
break;
}
case "tool_finished":
next = {
...base,
status: payload.status === "success" ? "success" : "error",
error: typeof payload.error === "string" ? payload.error : base.error,
phase: payload.status === "success" ? "done" : base.phase,
};
break;
default:
break;
}
if (frame.phase && next === base) next = { ...base, phase: frame.phase };
if (next !== previous) {
store.state = next;
// 状态同步更新(peek/快照立即可见);通知按 token 帧频率合并,终态立即。
if (frame.type === "tool_finished") {
emitNow(store);
} else {
emitCoalesced(store);
}
}
}
/** 订阅某线程的报告流状态;无进行中/已结束状态时返回 null。 */
export function useResearchReportStream(threadId: string | null | undefined): ResearchReportStreamState | null {
const subscribe = useCallback(
(listener: Listener) => {
if (!threadId) return () => {};
return subscribeResearchReportStream(threadId, listener);
},
[threadId],
);
const getSnapshot = useCallback(() => (threadId ? getStore(threadId).state : null), [threadId]);
return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
}
/**
* 直接订阅某线程的通知(节流合并后触发,非逐 token 帧);返回退订函数。
* `useResearchReportStream` 内部也走这里,测试可直接验证合并语义。
*/
export function subscribeResearchReportStream(threadId: string, listener: Listener): () => void {
const store = getStore(threadId);
store.listeners.add(listener);
return () => {
store.listeners.delete(listener);
};
}
/** 非订阅式快照读取(测试 / 调试用)。 */
export function peekResearchReportStream(threadId: string): ResearchReportStreamState | null {
return getStore(threadId).state;
}
// ── 聊天页注入消息构造 ────────────────────────────────────────────────────────
export const RESEARCH_REPORT_OUTPUT_PATH = "/mnt/user-data/outputs/report.md";
export type ResearchProgressToolCall = {
id: string;
name: "deep_research_progress";
args: {
label: string;
detail: string;
status: "complete" | "active";
thinking?: string;
};
};
/** 结构与工作台 buildWritingProgressToolCalls 相同;步骤固定为 basic 管线四段。 */
export function buildResearchProgressToolCalls(state: ResearchReportStreamState): ResearchProgressToolCall[] {
const rank = phaseRank(state.phase);
const finished = state.status !== "active";
const effectiveRank = finished && state.status === "success" ? PHASE_ORDER.length - 1 : rank;
const stages = [
{
id: "plan",
label: "拆解检索问题",
boundary: phaseRank("collecting"),
detail: state.queries.length > 0
? `已拆出 ${state.queries.length} 个检索子问题`
: "正在围绕课题拆解检索子问题",
},
{
id: "collect",
label: "检索参考资料",
boundary: phaseRank("compressing"),
detail: state.queries.length > 0
? `已检索 ${Math.min(state.completedQueries, state.queries.length)}/${state.queries.length} 个子问题 · 累计 ${state.sourceCount} 条资料`
: state.sourceCount > 0
? `已检索到 ${state.sourceCount} 条资料`
: "正在逐个子问题检索资料",
},
{
id: "write",
label: "撰写研究报告",
boundary: PHASE_ORDER.length,
detail: state.reportText
? "正在按「通用分析结构」逐字撰写,右侧沙箱同步预览"
: "正在整理资料并开始撰写报告",
},
];
const activeIndex = stages.findIndex((stage) => effectiveRank < stage.boundary);
const visibleLast = activeIndex === -1 ? stages.length - 1 : activeIndex;
return stages.slice(0, visibleLast + 1).map((stage, index) => {
const complete = effectiveRank >= stage.boundary;
const failed = finished && state.status === "error" && index === visibleLast && !complete;
return {
id: `research-progress-${state.jobId}-${stage.id}`,
name: "deep_research_progress" as const,
args: {
label: failed ? `${stage.label}(已中断)` : stage.label,
detail: failed && state.error ? `${stage.detail};${state.error}` : stage.detail,
status: complete ? ("complete" as const) : ("active" as const),
...(stage.id === "write" && state.thinking.trim() ? { thinking: state.thinking } : {}),
},
};
});
}
export type ResearchFeedMessage = {
id: string;
type: "ai";
content: string;
tool_calls: {
id: string;
name: string;
args: Record<string, unknown>;
}[];
};
/**
* 组装聊天页要注入的两条虚拟 ai 消息:进度步骤条 + report.md 的 write_file
* stub(沙箱 write-file 虚拟 URL 预览的数据源)。仅在报告尚无正文或仍在
* 流式时输出 stub —— 完成后由真实 artifacts 接管。
*/
export function buildResearchFeedMessages(state: ResearchReportStreamState): ResearchFeedMessage[] {
const messages: ResearchFeedMessage[] = [
{
id: `research-progress-${state.jobId}`,
type: "ai",
content: "",
tool_calls: buildResearchProgressToolCalls(state),
},
];
if (state.reportText.trim()) {
messages.push({
id: `research-report-${state.jobId}`,
type: "ai",
content: "",
tool_calls: [
{
id: `research-report-${state.jobId}-write`,
name: "write_file",
args: { path: RESEARCH_REPORT_OUTPUT_PATH, content: state.reportText },
},
],
});
}
return messages;
}
/** write-file 虚拟 URL(ArtifactFileDetail 用它从 stub 消息读流式内容)。 */
export function buildResearchReportVirtualUrl(state: ResearchReportStreamState): string {
return new URL(
`write-file:${RESEARCH_REPORT_OUTPUT_PATH}?message_id=${encodeURIComponent(`research-report-${state.jobId}`)}&tool_call_id=${encodeURIComponent(`research-report-${state.jobId}-write`)}&language=markdown`,
).toString();
}
@@ -0,0 +1,107 @@
"use client";
/**
* 聊天页「写作模式」深度研究进度注入。
*
* 把 `useResearchReportStream` 的流式状态转成 displayThread 尾部追加的
* 虚拟消息(进度步骤条 + 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 {
buildResearchFeedMessages,
buildResearchReportVirtualUrl,
RESEARCH_REPORT_OUTPUT_PATH,
useResearchReportStream,
} from "./use-research-report-stream";
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],
);
// 报告首帧正文到达且仍在写入 → 主动展开右侧沙箱并选中 write-file 虚拟
// 预览,报告在沙箱里边写边流式渲染。
useEffect(() => {
if (!research || research.status !== "active" || !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;
if (current !== null && current !== buildResearchReportVirtualUrl(research)) {
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(() => {
if (feedMessages.length === 0) return thread;
const messages = [
...thread.messages,
...(feedMessages as unknown as Message[]),
];
return {
...thread,
values: { ...thread.values, messages },
messages,
} as T;
}, [feedMessages, thread]);
return { displayThread };
}