代码提交

This commit is contained in:
董宏凯 committed 2026-08-16 19:17:45 +08:00
1 parent 70da7c5649
commit 178572bc7f
79 files changed
+13456 -798

No files matched your search

@@ -17,6 +17,11 @@ import {
import { apiFetch } from "@/core/api/fetch-client";
import { getBackendBaseURL } from "@/core/config";
import type {
DocumentRewriteSummary,
DocumentRewriteStreamEvent,
DocumentRewriteStyle,
} from "@/open-canvas/api/rewrite";
// ── base URL ────────────────────────────────────────────────────────────────
@@ -26,8 +31,12 @@ const BASE = () => `${getBackendBaseURL()}/api/deep-research`;
export type ResearchMode = "basic" | "quick" | "detailed" | "deep" | "multi_agent";
export type ResearchTone = "objective" | "formal" | "analytical" | "persuasive";
/** How the materials are collected: chat = collector-agent conversation (new), legacy = runner search tiers. */
export type CollectionMode = "chat" | "legacy";
export type SessionStatus =
| "draft"
| "collecting"
| "awaiting_report"
| "running"
| "awaiting_input"
| "completed"
@@ -56,6 +65,8 @@ export interface DeepResearchSession {
usage?: Record<string, unknown>;
activeJobId?: string;
error?: string;
/** The real LangGraph thread the collector agent chats on (chat collection). */
runtimeThreadId?: string;
createdAt?: string;
updatedAt?: string;
}
@@ -95,9 +106,31 @@ export interface DeepResearchMessage {
content: string;
citationSourceIds: string[];
usage?: Record<string, unknown>;
rewriteProposal?: RewriteProposal;
createdAt?: string;
}
export interface RewriteProposal {
/** User-facing target label, for example “第 1 段” or “摘要”. */
label: string;
/** A candidate only updates the report after a user decision. */
status: "pending" | "applied" | "dismissed";
}
export interface FollowUpRewritePreview {
/** User-facing target label, for example “第 1 段” or “摘要”. */
label: string;
}
export interface FollowUpStreamEvent {
type: "start" | "delta" | "complete" | "error";
delta?: string;
detail?: string;
assistantId?: string;
assistant?: DeepResearchMessage;
rewrite?: FollowUpRewritePreview | null;
}
export interface ProgressEvent {
seq: number;
/** Local live-stream identifier. Durable replay events use their seq instead. */
@@ -119,6 +152,8 @@ export interface Capabilities {
maxImages: number;
};
maxActiveJobsPerUser: number;
/** Built-in collector agent id the chat collection flow talks to. */
collectionAgentId?: string;
}
export const TERMINAL_JOB_STATUSES: JobStatus[] = [
@@ -183,6 +218,7 @@ function normalizeSession(row: WireRecord): DeepResearchSession {
usage: (pick(row, "usage", "usage_snapshot") ?? undefined) as Record<string, unknown> | undefined,
activeJobId: pick<string>(row, "activeJobId", "active_job_id"),
error: typeof row.error === "string" ? row.error : undefined,
runtimeThreadId: pick<string>(row, "runtimeThreadId", "runtime_thread_id"),
createdAt: pick<string>(row, "createdAt", "created_at"),
updatedAt: pick<string>(row, "updatedAt", "updated_at"),
};
@@ -221,6 +257,12 @@ function normalizeSource(row: WireRecord): DeepResearchSource {
}
function normalizeMessage(row: WireRecord): DeepResearchMessage {
const rewriteRaw = pick<WireRecord>(row, "rewriteProposal", "rewrite_proposal");
const rawStatus = typeof rewriteRaw?.status === "string" ? rewriteRaw.status : "";
const rewriteProposal = rewriteRaw && typeof rewriteRaw.label === "string"
&& (rawStatus === "pending" || rawStatus === "applied" || rawStatus === "dismissed")
? { label: rewriteRaw.label, status: rawStatus as RewriteProposal["status"] }
: undefined;
return {
id: String(row.id ?? ""),
sessionId: String(pick<string>(row, "sessionId", "session_id") ?? ""),
@@ -230,6 +272,7 @@ function normalizeMessage(row: WireRecord): DeepResearchMessage {
? (pick<string[]>(row, "citationSourceIds", "citation_source_ids") ?? []).map(String)
: [],
usage: (pick(row, "usage", "usage_snapshot") ?? undefined) as Record<string, unknown> | undefined,
rewriteProposal,
createdAt: pick<string>(row, "createdAt", "created_at"),
};
}
@@ -272,7 +315,7 @@ export async function getSession(id: string): Promise<DeepResearchSession> {
export async function updateSession(
id: string,
patch: { title?: string },
patch: { title?: string; status?: "collecting" | "awaiting_report" },
): Promise<DeepResearchSession> {
const res = await apiFetch(`${BASE()}/sessions/${id}`, {
method: "PATCH",
@@ -291,14 +334,31 @@ export async function deleteSession(id: string): Promise<void> {
// ── job lifecycle ─────────────────────────────────────────────────────────────
export interface StartJobOptions {
requestId?: string;
/**
* "chat" harvests the collector-agent conversation's materials as the pool;
* "legacy" (default) keeps the runner-driven search tiers.
*/
entry?: "chat" | "legacy";
/** Report-config card choices merged over the frozen session snapshot. */
config?: Record<string, unknown>;
}
export async function startJob(
sessionId: string,
requestId?: string,
optionsOrRequestId?: StartJobOptions | string,
): Promise<{ jobId: string; sessionId: string; status: string; reused: boolean }> {
const opts: StartJobOptions =
typeof optionsOrRequestId === "string" ? { requestId: optionsOrRequestId } : optionsOrRequestId ?? {};
const res = await apiFetch(`${BASE()}/sessions/${sessionId}/jobs`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ request_id: requestId ?? crypto.randomUUID() }),
body: JSON.stringify({
request_id: opts.requestId ?? crypto.randomUUID(),
entry: opts.entry ?? "legacy",
config: opts.config ?? null,
}),
});
return readJson(res, "startJob");
}
@@ -487,6 +547,307 @@ export async function sendResearchMessage(
};
}
/**
* Native SSE follow-up stream. Unlike the legacy JSON `/chat` endpoint, this
* surfaces every model delta to the normal message list. Explicit rewrites
* identify the candidate target but stay out of the sandbox until the user
* confirms the candidate through the proposal endpoint.
*/
export async function streamResearchMessage(
sessionId: string,
message: string,
handlers: {
onEvent: (event: FollowUpStreamEvent) => void;
},
signal?: AbortSignal,
streamKind: "qa" | "rewrite" = "qa",
): Promise<void> {
const path = streamKind === "rewrite" ? "rewrite/stream" : "chat/stream";
const res = await apiFetch(`${BASE()}/sessions/${encodeURIComponent(sessionId)}/${path}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ message, allow_new_research: false }),
signal,
});
if (!res.ok || !res.body) {
await readJson(res, "streamResearchMessage");
return;
}
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true }).replace(/\r\n/g, "\n");
const frames = buffer.split("\n\n");
buffer = frames.pop() ?? "";
for (const frame of frames) {
const dataLine = frame.split("\n").find((line) => line.startsWith("data:"));
if (!dataLine) continue;
try {
const raw = JSON.parse(dataLine.slice("data:".length).trim()) as WireRecord;
const type = raw.type;
if (type !== "start" && type !== "delta" && type !== "complete" && type !== "error") continue;
const rewriteRaw = raw.rewrite;
const rewrite = rewriteRaw && typeof rewriteRaw === "object" && !Array.isArray(rewriteRaw)
? {
label: String((rewriteRaw as WireRecord).label ?? "报告内容"),
}
: null;
const event: FollowUpStreamEvent = {
type,
delta: typeof raw.delta === "string" ? raw.delta : undefined,
detail: typeof raw.detail === "string" ? raw.detail : undefined,
assistantId: typeof raw.assistantId === "string" ? raw.assistantId : undefined,
assistant: raw.assistant && typeof raw.assistant === "object"
? normalizeMessage(asRecord(raw.assistant))
: undefined,
rewrite,
};
handlers.onEvent(event);
if (event.type === "error") throw new Error(event.detail || "报告追问生成失败");
} catch (error) {
if (error instanceof Error) throw error;
}
}
}
}
/**
* Dedicated completed-report writing stream. Its only successful output is a
* scoped replacement candidate; report Q&A stays on `streamResearchMessage`.
*/
export function streamResearchRewrite(
sessionId: string,
instruction: string,
handlers: { onEvent: (event: FollowUpStreamEvent) => void },
signal?: AbortSignal,
): Promise<void> {
return streamResearchMessage(sessionId, instruction, handlers, signal, "rewrite");
}
export async function cancelFullResearchReportRewrite(jobId: string): Promise<void> {
await cancelJob(jobId);
}
export interface LatestFullReportRewrite {
job: DeepResearchJob | null;
result: Record<string, unknown>;
request: { instruction: string; style: DocumentRewriteStyle; modelName?: string | null };
}
export async function getLatestFullResearchReportRewrite(
sessionId: string,
): Promise<LatestFullReportRewrite> {
const response = await apiFetch(
`${BASE()}/sessions/${encodeURIComponent(sessionId)}/document-rewrite/jobs/latest`,
{ method: "GET" },
);
const data = await readJson<WireRecord>(response, "getLatestFullResearchReportRewrite");
const jobRecord = data.job && typeof data.job === "object" ? asRecord(data.job) : null;
const request = asRecord(data.request);
return {
job: jobRecord ? normalizeJob(jobRecord) : null,
result: asRecord(data.result),
request: {
instruction: String(request.instruction ?? ""),
style: (request.style ?? "formal_analysis") as DocumentRewriteStyle,
modelName: typeof request.modelName === "string" ? request.modelName : null,
},
};
}
/**
* Join an already-created durable complete-report rewrite.
*
* The task continues on the backend if this iterator is aborted (for example,
* a page refresh). Re-opening the stream with its last durable sequence
* replays milestones/checkpoints and then receives new live deltas.
*/
export async function* joinFullResearchReportRewrite(
jobId: string,
signal?: AbortSignal,
): AsyncGenerator<DocumentRewriteStreamEvent> {
let afterSeq = 0;
let terminal = false;
let retryDelay = 250;
while (!terminal && !signal?.aborted) {
try {
const response = await apiFetch(
`${BASE()}/jobs/${encodeURIComponent(jobId)}/stream?after=${afterSeq}`,
{ method: "GET", signal },
);
if (!response.ok || !response.body) {
await readJson(response, "streamFullResearchReportRewrite");
return;
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
try {
while (!signal?.aborted) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true }).replace(/\r\n/g, "\n");
const frames = buffer.split("\n\n");
buffer = frames.pop() ?? "";
for (const frame of frames) {
const dataLine = frame.split("\n").find((line) => line.startsWith("data:"));
if (!dataLine) continue;
let progress: ProgressEvent;
try {
progress = JSON.parse(dataLine.slice("data:".length).trim()) as ProgressEvent;
} catch {
continue;
}
if (progress.seq > 0) afterSeq = Math.max(afterSeq, progress.seq);
if (progress.type === "job_status") {
const status = String(progress.payload?.status ?? "");
if (status === "cancelled") {
yield { type: "error", message: "已停止全文改写,原报告未被修改。", stage: "cancelled" };
terminal = true;
} else if (status === "failed") {
yield { type: "error", message: "报告全文改写失败,请稍后重试。" };
terminal = true;
}
continue;
}
if (progress.type !== "document_rewrite") continue;
const raw = asRecord(progress.payload);
const type = String(raw.type ?? "");
if (type === "snapshot_fixed") {
yield {
type,
fileName: String(raw.fileName ?? "report.md"),
originalCharCount: Number(raw.originalCharCount ?? 0),
baseHash: String(raw.baseHash ?? ""),
};
} else if (type === "requirements_started") {
yield { type };
} else if (type === "requirements_delta") {
yield { type, delta: String(raw.delta ?? "") };
} else if (type === "requirements_checkpoint") {
yield { type, content: String(raw.content ?? "") };
} else if (type === "requirements_completed") {
yield {
type,
content: String(raw.content ?? ""),
fallback: raw.fallback === true,
};
} else if (type === "requirements_resolved") {
yield {
type,
instruction: String(raw.instruction ?? ""),
style: String(raw.style ?? ""),
modelName: String(raw.modelName ?? "deep_research_smart_model"),
plan: typeof raw.plan === "string" ? raw.plan : undefined,
};
} else if (type === "rewrite_delta") {
yield { type, delta: String(raw.delta ?? ""), charCount: Number(raw.charCount ?? 0) };
} else if (type === "rewrite_checkpoint") {
yield { type, content: String(raw.content ?? ""), charCount: Number(raw.charCount ?? 0) };
} else if (type === "validation_started" || type === "commit_started") {
yield { type };
} else if (type === "validation_completed") {
yield {
type,
passed: raw.passed === true,
warnings: Array.isArray(raw.warnings)
? raw.warnings.filter((item): item is string => typeof item === "string")
: [],
};
} else if (type === "comparison_ready") {
yield { type, summary: raw as unknown as DocumentRewriteSummary };
} else if (type === "committed") {
yield {
type,
content: String(raw.content ?? ""),
committedHash: String(raw.committedHash ?? ""),
versionId: typeof raw.versionId === "string" ? raw.versionId : undefined,
};
} else if (type === "done") {
yield {
type,
committedHash: String(raw.committedHash ?? ""),
versionId: typeof raw.versionId === "string" ? raw.versionId : undefined,
};
terminal = true;
} else if (type === "conflict") {
yield { type, message: String(raw.message ?? "报告内容已变化") };
terminal = true;
} else if (type === "error") {
yield {
type,
message: String(raw.message ?? "报告全文改写失败"),
stage: typeof raw.stage === "string" ? raw.stage : undefined,
};
terminal = true;
}
}
}
} finally {
reader.releaseLock();
}
retryDelay = 250;
} catch (error) {
if (signal?.aborted) return;
// Browser/proxy SSE connections can transiently end. Keep the server
// job alive and join it again from the last durable event sequence.
if (retryDelay > 4_000) {
throw error instanceof Error ? error : new Error("全文改写流连接失败");
}
await new Promise((resolve) => window.setTimeout(resolve, retryDelay));
retryDelay *= 2;
}
}
}
/** Start and join the sandbox's durable complete-report rewrite. */
export async function* streamFullResearchReportRewrite(
sessionId: string,
input: { instruction: string; style: DocumentRewriteStyle; modelName?: string },
signal?: AbortSignal,
onJobStarted?: (jobId: string) => void,
): AsyncGenerator<DocumentRewriteStreamEvent> {
const startResponse = await apiFetch(
`${BASE()}/sessions/${encodeURIComponent(sessionId)}/document-rewrite`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(input),
signal,
},
);
const started = await readJson<WireRecord>(startResponse, "startFullResearchReportRewrite");
const jobId = String(pick<string>(started, "jobId", "job_id") ?? "");
if (!jobId) throw new Error("全文改写任务未返回任务编号");
onJobStarted?.(jobId);
yield* joinFullResearchReportRewrite(jobId, signal);
}
/** Resolve a durable rewrite candidate after the user has reviewed its stream. */
export async function resolveResearchRewriteProposal(
sessionId: string,
messageId: string,
action: "apply" | "dismiss",
): Promise<{ session: DeepResearchSession; message: DeepResearchMessage }> {
const res = await apiFetch(
`${BASE()}/sessions/${encodeURIComponent(sessionId)}/messages/${encodeURIComponent(messageId)}/rewrite-proposal`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ action }),
},
);
const data = await readJson<WireRecord>(res, "resolveResearchRewriteProposal");
return {
session: normalizeSession(asRecord(data.session)),
message: normalizeMessage(asRecord(data.message)),
};
}
// ── capabilities ─────────────────────────────────────────────────────────────
export async function getCapabilities(): Promise<Capabilities> {
@@ -571,8 +932,29 @@ export function useResearchActions() {
queryClient.invalidateQueries({ queryKey: [DEEP_RESEARCH_SESSIONS_KEY] }),
}),
startJob: useMutation({
mutationFn: (sessionId: string) => startJob(sessionId),
onSuccess: (_result, sessionId) => {
mutationFn: ({
sessionId,
entry,
config,
}: {
sessionId: string;
entry?: "chat" | "legacy";
config?: Record<string, unknown>;
}) => startJob(sessionId, { entry, config }),
onSuccess: (_result, { sessionId }) => {
queryClient.invalidateQueries({ queryKey: [DEEP_RESEARCH_SESSIONS_KEY] });
queryClient.invalidateQueries({ queryKey: [DEEP_RESEARCH_SESSION_KEY, sessionId] });
},
}),
updateStatus: useMutation({
mutationFn: ({
sessionId,
status,
}: {
sessionId: string;
status: "collecting" | "awaiting_report";
}) => updateSession(sessionId, { status }),
onSuccess: (_result, { sessionId }) => {
queryClient.invalidateQueries({ queryKey: [DEEP_RESEARCH_SESSIONS_KEY] });
queryClient.invalidateQueries({ queryKey: [DEEP_RESEARCH_SESSION_KEY, sessionId] });
},
@@ -619,6 +1001,22 @@ export function useResearchActions() {
queryClient.invalidateQueries({ queryKey: [DEEP_RESEARCH_MESSAGES_KEY, sessionId] });
},
}),
resolveRewriteProposal: useMutation({
mutationFn: ({
sessionId,
messageId,
action,
}: {
sessionId: string;
messageId: string;
action: "apply" | "dismiss";
}) => resolveResearchRewriteProposal(sessionId, messageId, action),
onSuccess: (_result, { sessionId }) => {
queryClient.invalidateQueries({ queryKey: [DEEP_RESEARCH_SESSIONS_KEY] });
queryClient.invalidateQueries({ queryKey: [DEEP_RESEARCH_SESSION_KEY, sessionId] });
queryClient.invalidateQueries({ queryKey: [DEEP_RESEARCH_MESSAGES_KEY, sessionId] });
},
}),
setSourceSelected: useMutation({
mutationFn: ({
sessionId,