feat(frontend): 上线报告协作与多轮 RAG 消息聚合体验

功能说明:\n- 新增报告协作页(Report Collaboration)核心状态层、消息适配与会话面板,支持按节点/阶段选择和协作上下文展示\n- 补齐 report-collaboration API 与类型定义,并接入页面路由/构建路径,形成可运行的协作链路\n- 重构多轮 RAG 与 write/artefact 消息分组逻辑,优化 AgentChat 与 DeepResearch 场景下的消息展示顺序与可读性\n- 新增/更新 DeepResearch 前端页面(Workbench、报告配置、沙箱联动)以承接报告生成与复用能力\n- 增加报表协作相关单测,覆盖事件归并、消息适配与关键 reducer 行为
This commit is contained in:
董宏凯 committed 2026-09-04 23:18:27 +08:00
1 parent e58da3fbdf
commit 438772f0b7
25 files changed
+1740 -399

No files matched your search

@@ -174,12 +174,20 @@ export function isTerminalJobStatus(status: JobStatus): boolean {
async function readJson<T>(res: Response, ctx: string): Promise<T> {
if (!res.ok) {
let detail = `${ctx} failed (${res.status})`;
let body: unknown;
try {
const body = await res.json();
detail = body.detail || detail;
body = await res.json();
const record = body && typeof body === "object" ? body as Record<string, unknown> : {};
detail = typeof record.detail === "string" ? record.detail : detail;
} catch {
// ignore parse error
}
console.error(`[深度研究] ${ctx}_failed`, {
status: res.status,
url: res.url,
detail,
body,
});
throw new Error(detail);
}
return res.json() as Promise<T>;
@@ -323,12 +331,25 @@ export async function getSession(id: string): Promise<DeepResearchSession> {
export async function updateSession(
id: string,
patch: { title?: string; status?: "collecting" | "awaiting_report" },
patch: {
title?: string;
status?: "collecting" | "awaiting_report";
collectorMaterials?: Record<string, unknown>[];
},
): Promise<DeepResearchSession> {
const res = await apiFetch(`${BASE()}/sessions/${id}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(patch),
body: JSON.stringify({
...(patch.title !== undefined ? { title: patch.title } : {}),
...(patch.status !== undefined ? { status: patch.status } : {}),
...(patch.collectorMaterials !== undefined
? {
collector_materials: patch.collectorMaterials,
collectorMaterials: patch.collectorMaterials,
}
: {}),
}),
});
return normalizeSession(await readJson<WireRecord>(res, "updateSession"));
}
@@ -352,27 +373,90 @@ export interface StartJobOptions {
entry?: "chat" | "legacy" | "regenerate";
/** Report-config card choices merged over the frozen session snapshot. */
config?: Record<string, unknown>;
/** Topic text frozen by the browser. Empty materials still write a report. */
query?: string;
title?: string;
/** Compact collector evidence frozen before the report job starts. */
collectorMaterials?: Record<string, unknown>[];
/** Skip harvested / leftover sources and take the no-material writer. */
forceNoMaterials?: boolean;
}
export async function startJob(
sessionId: string,
optionsOrRequestId?: StartJobOptions | string,
): Promise<{ jobId: string; sessionId: string; status: string; reused: boolean }> {
): Promise<{
jobId: string;
sessionId: string;
status: string;
reused: boolean;
collectorMaterialCount?: number;
persistedSourceCount?: number;
diagnostics?: Array<{
code?: string;
stage?: string;
message?: string;
recoverable?: boolean;
errorType?: string;
detail?: string;
[key: string]: unknown;
}>;
}> {
const opts: StartJobOptions =
typeof optionsOrRequestId === "string" ? { requestId: optionsOrRequestId } : optionsOrRequestId ?? {};
const res = await apiFetch(`${BASE()}/sessions/${sessionId}/jobs`, {
const entry = opts.entry ?? "legacy";
const collectorMaterials = opts.collectorMaterials ?? (entry === "chat" ? [] : null);
// First write posts materials to the dedicated report API. GET /jobs/{id}/stream
// only replays progress and cannot carry evidence.
const path = entry === "chat"
? `${BASE()}/sessions/${sessionId}/report`
: `${BASE()}/sessions/${sessionId}/jobs`;
const res = await apiFetch(path, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
request_id: opts.requestId ?? createClientId(),
entry: opts.entry ?? "legacy",
config: opts.config ?? null,
collector_materials: opts.collectorMaterials ?? null,
}),
body: JSON.stringify(
entry === "chat"
? {
request_id: opts.requestId ?? createClientId(),
query: opts.query ?? "",
title: opts.title ?? "",
config: opts.config ?? null,
collector_materials: collectorMaterials ?? [],
collectorMaterials: collectorMaterials ?? [],
force_no_materials: opts.forceNoMaterials === true,
forceNoMaterials: opts.forceNoMaterials === true,
}
: {
request_id: opts.requestId ?? createClientId(),
entry,
config: opts.config ?? null,
collector_materials: collectorMaterials,
collectorMaterials,
},
),
});
return readJson(res, "startJob");
const started = await readJson<{
jobId: string;
sessionId: string;
status: string;
reused: boolean;
collectorMaterialCount?: number;
persistedSourceCount?: number;
diagnostics?: Array<{
code?: string;
stage?: string;
message?: string;
recoverable?: boolean;
errorType?: string;
detail?: string;
[key: string]: unknown;
}>;
}>(res, entry === "chat" ? "writeReport" : "startJob");
for (const item of started.diagnostics ?? []) {
const code = String(item.code || "write_report_diagnostic");
console.warn(`[深度研究] ${code}`, item);
}
return started;
}
export async function getJob(jobId: string): Promise<DeepResearchJob> {
@@ -384,6 +468,9 @@ export async function cancelJob(
jobId: string,
): Promise<{ jobId: string; status: string }> {
const res = await apiFetch(`${BASE()}/jobs/${jobId}/cancel`, { method: "POST" });
if (res.status === 409) {
return { jobId, status: "cancelled" };
}
return readJson(res, "cancelJob");
}
@@ -402,6 +489,54 @@ export async function resumeJob(
// ── SSE streaming ────────────────────────────────────────────────────────────
const DIAGNOSTIC_EVENT_TYPES = new Set([
"warning",
"error",
"report_reset",
]);
/**
* Print backend diagnostics in the browser console.
*
* Production operators cannot always read Gateway logs. These frames already
* travel on the job SSE stream; echoing them here makes the real exception
* (errorType / diagnostic.detail / code) copyable from DevTools.
*/
function logDeepResearchDiagnostic(event: ProgressEvent): void {
const payload = event.payload ?? {};
const jobFailed =
event.type === "job_status" &&
(Boolean(payload.errorCode) || Boolean(payload.errorMessage) || payload.status === "failed");
const degraded = payload.eventPersistenceDegraded === true;
const emptyCollection =
event.type === "collection_completed" && Number(payload.materialCount ?? 0) === 0;
if (!DIAGNOSTIC_EVENT_TYPES.has(event.type) && !jobFailed && !degraded && !emptyCollection) return;
const summary = {
jobId: event.jobId,
sessionId: event.sessionId,
seq: event.seq,
type: event.type,
phase: event.phase,
code: payload.code ?? payload.errorCode ?? event.type,
message: payload.message ?? payload.errorMessage,
errorType: payload.errorType,
detail: payload.detail,
recoverable: payload.recoverable,
reason: payload.reason,
status: payload.status,
diagnostic: payload.diagnostic,
diagnostics: payload.diagnostics,
payload,
};
const label = `[深度研究] ${String(summary.code)}`;
if (event.type === "error" || jobFailed) {
console.error(label, summary);
return;
}
console.warn(label, summary);
}
export interface StreamJobHandlers {
onEvent: (event: ProgressEvent) => void;
onTerminal?: (status: string) => void;
@@ -428,7 +563,9 @@ export function streamJob(
{ method: "GET", signal: controller.signal },
);
if (!res.ok || !res.body) {
handlers.onError?.(`stream failed (${res.status})`);
const detail = `stream failed (${res.status})`;
console.error("[深度研究] stream_open_failed", { jobId, afterSeq, status: res.status });
handlers.onError?.(detail);
return;
}
const reader = res.body.getReader();
@@ -460,6 +597,7 @@ export function streamJob(
} catch {
continue;
}
logDeepResearchDiagnostic(event);
handlers.onEvent(event);
// Check for terminal status in the payload.
@@ -475,7 +613,9 @@ export function streamJob(
}
} catch (err) {
if (!controller.signal.aborted) {
handlers.onError?.(err instanceof Error ? err.message : String(err));
const detail = err instanceof Error ? err.message : String(err);
console.error("[深度研究] stream_disconnected", { jobId, afterSeq, detail, error: err });
handlers.onError?.(detail);
}
}
})();
@@ -1010,13 +1150,19 @@ export function useResearchActions() {
sessionId,
entry,
config,
query,
title,
collectorMaterials,
forceNoMaterials,
}: {
sessionId: string;
entry?: "chat" | "legacy" | "regenerate";
config?: Record<string, unknown>;
query?: string;
title?: string;
collectorMaterials?: Record<string, unknown>[];
}) => startJob(sessionId, { entry, config, collectorMaterials }),
forceNoMaterials?: boolean;
}) => startJob(sessionId, { entry, config, query, title, collectorMaterials, forceNoMaterials }),
onSuccess: (_result, { sessionId }) => {
queryClient.invalidateQueries({ queryKey: [DEEP_RESEARCH_SESSIONS_KEY] });
queryClient.invalidateQueries({ queryKey: [DEEP_RESEARCH_SESSION_KEY, sessionId] });
@@ -1026,15 +1172,32 @@ export function useResearchActions() {
mutationFn: ({
sessionId,
status,
collectorMaterials,
}: {
sessionId: string;
status: "collecting" | "awaiting_report";
}) => updateSession(sessionId, { status }),
collectorMaterials?: Record<string, unknown>[];
}) => updateSession(sessionId, { status, collectorMaterials }),
onSuccess: (_result, { sessionId }) => {
queryClient.invalidateQueries({ queryKey: [DEEP_RESEARCH_SESSIONS_KEY] });
queryClient.invalidateQueries({ queryKey: [DEEP_RESEARCH_SESSION_KEY, sessionId] });
},
}),
persistCollectorMaterials: useMutation({
mutationFn: ({
sessionId,
collectorMaterials,
}: {
sessionId: string;
collectorMaterials: Record<string, unknown>[];
quiet?: boolean;
}) => updateSession(sessionId, { collectorMaterials }),
onSuccess: (_result, { sessionId, quiet }) => {
if (quiet) return;
queryClient.invalidateQueries({ queryKey: [DEEP_RESEARCH_SESSIONS_KEY] });
queryClient.invalidateQueries({ queryKey: [DEEP_RESEARCH_SESSION_KEY, sessionId] });
},
}),
cancelJob: useMutation({
mutationFn: (jobId: string) => cancelJob(jobId),
onSuccess: () => {