Files
董宏凯andCursor 51afebb394 feat: 报告结构支持检索方向/来源与智能新增,并修复协助卡停轮与宿主跳转
为深度研究报告结构增加检索方向与技能来源、对话式智能新增页与详情排版;澄清中间件在 after_model 可靠结束本轮,避免弱模型出卡后继续生成;任务按钮补充 host 跳转与相关深链能力。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-22 17:46:06 +08:00

452 lines
16 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { apiFetch } from "@/core/api/fetch-client";
import { getBackendBaseURL } from "@/core/config";
export type RewriteAction = "polish" | "expand" | "shorten" | "tone" | "imitate";
export type RewriteTone =
| "professional"
| "casual"
| "readable"
| "academic"
| "expressive";
export interface RewriteRequest {
threadId?: string | null;
selection: { from: number; to: number; text: string };
action: RewriteAction;
tone?: RewriteTone;
modelName?: string;
surroundingContext?: { before?: string; after?: string };
customInstruction?: string;
/** 仿写参考范文(action="imitate" 时使用):AI 模仿其文风/句式/语气改写所选文字。 */
referenceText?: string;
followUpInstruction?: string;
previousResult?: string;
}
export type RewriteStreamEvent =
| { type: "thinking"; chunk: string }
| { type: "text"; chunk: string }
| { type: "done" }
| { type: "error"; message: string };
// ── SSE parser ────────────────────────────────────────────────────────────────
export async function* parseSse(body: ReadableStream<Uint8Array>): AsyncGenerator<{ event: string; data: string }> {
const reader = body.getReader();
const decoder = new TextDecoder();
let buffer = "";
let currentEvent = "";
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split("\n");
buffer = lines.pop() ?? "";
for (const line of lines) {
const trimmed = line.trimEnd();
if (trimmed.startsWith("event: ")) {
currentEvent = trimmed.slice(7);
} else if (trimmed.startsWith("data: ")) {
yield { event: currentEvent, data: trimmed.slice(6) };
currentEvent = "";
}
// empty line resets event field (SSE spec)
else if (trimmed === "") {
currentEvent = "";
}
}
}
} finally {
reader.releaseLock();
}
}
// ── Streaming entry point ─────────────────────────────────────────────────────
export async function* streamRewrite(
req: RewriteRequest,
signal?: AbortSignal,
): AsyncGenerator<RewriteStreamEvent> {
const res = await apiFetch(`${getBackendBaseURL()}/api/writing/rewrite`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(req),
signal,
});
if (!res.ok) {
const body = await res.json().catch(() => ({})) as Record<string, unknown>;
const msg = (body?.detail as string | undefined) ?? (body?.message as string | undefined) ?? `HTTP ${res.status}`;
throw new Error(msg);
}
if (!res.body) throw new Error("No response body");
for await (const { event, data } of parseSse(res.body)) {
if (signal?.aborted) return;
try {
const parsed = JSON.parse(data) as Record<string, unknown>;
if (event === "thinking") {
yield { type: "thinking", chunk: parsed.chunk as string };
} else if (event === "text") {
yield { type: "text", chunk: parsed.chunk as string };
} else if (event === "done") {
yield { type: "done" };
return;
} else if (event === "error") {
yield { type: "error", message: parsed.message as string };
return;
}
} catch {
// skip malformed frame
}
}
}
export type DocumentRewriteStyle =
| "formal_analysis"
| "professional"
| "concise"
| "readable";
export interface DocumentRewriteRequest {
threadId: string;
path: string;
instruction: string;
style?: DocumentRewriteStyle;
modelName?: string;
/** Optional Markdown chapter structure selected from the report-structure library. */
reportOutline?: string;
/** ``fixed`` reproduces the outline; ``adaptive`` keeps the material-driven layout. */
structureMode?: "fixed" | "adaptive";
/** Generate locally saved illustration assets after the prose rewrite. */
generateImages?: boolean;
/** Bounded server-side to 1–4. Ignored unless generateImages is true. */
maxGeneratedImages?: number;
expectedHash?: string;
}
export interface DocumentRewriteSummary {
sourceDisplayName: string;
instruction: string;
modelName: string;
originalCharCount: number;
rewrittenCharCount: number;
charChangeRatio: number;
changedBlockCount: number;
headingCountBefore: number;
headingCountAfter: number;
headingChanges?: {
added: string[];
removed: string[];
reordered: boolean;
levelWarnings: string[];
};
requestedOptimizations?: string[];
validationWarnings?: string[];
generatedImageCount?: number;
requestedImageCount?: number;
}
export type DocumentRewriteStreamEvent =
| { type: "job_started"; jobId: string; reused: boolean }
| { type: "snapshot_fixed"; fileName: string; originalCharCount: number; baseHash: string }
| { type: "requirements_started" }
/** Small live rewrite plan shown in the message-list requirements step. */
| { type: "requirements_delta"; delta: string }
/** Durable recovery point for a plan produced before an SSE reconnect. */
| { type: "requirements_checkpoint"; content: string }
| { type: "requirements_completed"; content: string; fallback: boolean }
| { type: "requirements_resolved"; instruction: string; style: string; modelName: string; plan?: string }
| { type: "thinking"; chunk: string }
| { type: "rewrite_delta"; delta: string; charCount: number }
/** Durable full-draft recovery point used after an SSE reconnect. */
| { type: "rewrite_checkpoint"; content: string; charCount: number }
| { type: "illustration_started"; section: string; position: number; total: number }
| {
type: "illustration_generated";
section: string;
position: number;
total: number;
generatedCount?: number;
}
| { type: "illustration_completed"; generatedCount: number; requestedCount: number; warnings: string[] }
| { type: "validation_started" }
| { type: "validation_completed"; passed: boolean; warnings: string[] }
| { type: "comparison_ready"; summary: DocumentRewriteSummary }
| { type: "commit_started" }
| {
type: "committed";
content: string;
committedHash: string;
versionId?: string;
/** The rewrite is usable, but its optional undo snapshot was not saved. */
versionSnapshotFailed?: boolean;
}
| { type: "done"; committedHash: string; versionId?: string; versionSnapshotFailed?: boolean }
| { type: "conflict"; message: string }
| { type: "cancelled"; message: string }
| { type: "error"; message: string; stage?: string };
export interface DurableDocumentRewriteJob {
id: string;
status: string;
phase: string;
progress: number;
createdAt?: string | null;
result: Record<string, unknown>;
request: {
instruction: string;
style: DocumentRewriteStyle;
modelName: string | null;
reportOutline: string;
generateImages: boolean;
maxGeneratedImages: number;
originalContent: string;
};
}
async function readDocumentRewriteEvent(
event: string,
data: string,
): Promise<DocumentRewriteStreamEvent | null> {
try {
const parsed = JSON.parse(data) as Record<string, unknown>;
switch (event) {
case "snapshot_fixed":
return {
type: "snapshot_fixed",
fileName: String(parsed.fileName ?? ""),
originalCharCount: Number(parsed.originalCharCount ?? 0),
baseHash: String(parsed.baseHash ?? ""),
};
case "requirements_resolved":
return {
type: "requirements_resolved",
instruction: String(parsed.instruction ?? ""),
style: String(parsed.style ?? ""),
modelName: String(parsed.modelName ?? ""),
plan: typeof parsed.plan === "string" ? parsed.plan : undefined,
};
case "requirements_started":
return { type: "requirements_started" };
case "requirements_delta":
return { type: "requirements_delta", delta: String(parsed.delta ?? "") };
case "requirements_checkpoint":
return { type: "requirements_checkpoint", content: String(parsed.content ?? "") };
case "requirements_completed":
return {
type: "requirements_completed",
content: String(parsed.content ?? ""),
fallback: parsed.fallback === true,
};
case "thinking":
return { type: "thinking", chunk: String(parsed.chunk ?? "") };
case "rewrite_delta":
return {
type: "rewrite_delta",
delta: String(parsed.delta ?? ""),
charCount: Number(parsed.charCount ?? 0),
};
case "rewrite_checkpoint":
return {
type: "rewrite_checkpoint",
content: String(parsed.content ?? ""),
charCount: Number(parsed.charCount ?? 0),
};
case "illustration_started":
return {
type: "illustration_started",
section: String(parsed.section ?? ""),
position: Number(parsed.position ?? 0),
total: Number(parsed.total ?? 0),
};
case "illustration_generated":
return {
type: "illustration_generated",
section: String(parsed.section ?? ""),
position: Number(parsed.position ?? 0),
total: Number(parsed.total ?? 0),
generatedCount: Number(parsed.generatedCount ?? parsed.position ?? 0),
};
case "illustration_completed":
return {
type: "illustration_completed",
generatedCount: Number(parsed.generatedCount ?? 0),
requestedCount: Number(parsed.requestedCount ?? 0),
warnings: Array.isArray(parsed.warnings)
? parsed.warnings.filter((item): item is string => typeof item === "string")
: [],
};
case "validation_started":
return { type: "validation_started" };
case "validation_completed":
return {
type: "validation_completed",
passed: parsed.passed === true,
warnings: Array.isArray(parsed.warnings)
? parsed.warnings.filter((item): item is string => typeof item === "string")
: [],
};
case "comparison_ready":
return { type: "comparison_ready", summary: parsed as unknown as DocumentRewriteSummary };
case "commit_started":
return { type: "commit_started" };
case "committed":
return {
type: "committed",
content: String(parsed.content ?? ""),
committedHash: String(parsed.committedHash ?? ""),
versionId: typeof parsed.versionId === "string" ? parsed.versionId : undefined,
versionSnapshotFailed: parsed.versionSnapshotFailed === true,
};
case "done":
return {
type: "done",
committedHash: String(parsed.committedHash ?? ""),
versionId: typeof parsed.versionId === "string" ? parsed.versionId : undefined,
versionSnapshotFailed: parsed.versionSnapshotFailed === true,
};
case "conflict":
return { type: "conflict", message: String(parsed.message ?? "文件内容已变化") };
case "cancelled":
return { type: "cancelled", message: String(parsed.message ?? "已停止全文改写") };
case "error":
return {
type: "error",
message: String(parsed.message ?? "全文改写失败"),
stage: typeof parsed.stage === "string" ? parsed.stage : undefined,
};
default:
return null;
}
} catch {
return null;
}
}
async function startDurableDocumentRewrite(
req: DocumentRewriteRequest,
signal?: AbortSignal,
): Promise<{ jobId: string; reused: boolean }> {
const response = await apiFetch(getBackendBaseURL() + "/api/writing/document-rewrite/jobs", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(req),
signal,
});
const body = await response.json().catch(() => ({})) as Record<string, unknown>;
if (!response.ok || typeof body.jobId !== "string") {
throw new Error(
(body.detail as string | undefined) ??
(body.message as string | undefined) ??
`HTTP ${response.status}`,
);
}
return { jobId: body.jobId, reused: body.reused === true };
}
export async function* streamDurableDocumentRewriteJob(
req: Pick<DocumentRewriteRequest, "threadId" | "path">,
jobId: string,
signal?: AbortSignal,
after = 0,
): AsyncGenerator<DocumentRewriteStreamEvent> {
const query = new URLSearchParams({
thread_id: req.threadId,
path: req.path,
after: String(after),
});
const response = await apiFetch(
`${getBackendBaseURL()}/api/writing/document-rewrite/jobs/${encodeURIComponent(jobId)}/stream?${query.toString()}`,
{ method: "GET", signal },
);
if (!response.ok || !response.body) {
const body = await response.json().catch(() => ({})) as Record<string, unknown>;
throw new Error((body.detail as string | undefined) ?? `HTTP ${response.status}`);
}
for await (const { event, data } of parseSse(response.body)) {
if (signal?.aborted) return;
const parsed = await readDocumentRewriteEvent(event, data);
if (!parsed) continue;
yield parsed;
if (["done", "conflict", "cancelled", "error"].includes(parsed.type)) return;
}
}
export async function getLatestDurableDocumentRewrite(
req: Pick<DocumentRewriteRequest, "threadId" | "path">,
): Promise<DurableDocumentRewriteJob | null> {
const jobs = await listDurableDocumentRewrites(req, 1);
return jobs[0] ?? null;
}
export async function listDurableDocumentRewrites(
req: Pick<DocumentRewriteRequest, "threadId" | "path">,
limit = 20,
): Promise<DurableDocumentRewriteJob[]> {
const query = new URLSearchParams({
thread_id: req.threadId,
path: req.path,
limit: String(Math.min(Math.max(limit, 1), 20)),
});
const response = await apiFetch(
`${getBackendBaseURL()}/api/writing/document-rewrite/jobs?${query.toString()}`,
{ method: "GET" },
);
const body = await response.json().catch(() => ({})) as Record<string, unknown>;
if (!response.ok) throw new Error((body.detail as string | undefined) ?? `HTTP ${response.status}`);
const rows = Array.isArray(body.items) ? body.items : [];
return rows.flatMap((item) => {
if (!item || typeof item !== "object") return [];
const job = item as Record<string, unknown>;
if (typeof job.id !== "string") return [];
const request = (job.request ?? {}) as Record<string, unknown>;
return [{
id: job.id,
status: String(job.status ?? "queued"),
phase: String(job.phase ?? "initializing"),
progress: Number(job.progress ?? 0),
createdAt: typeof job.createdAt === "string" ? job.createdAt : null,
result: (job.result ?? {}) as Record<string, unknown>,
request: {
instruction: String(request.instruction ?? ""),
style: (request.style ?? "professional") as DocumentRewriteStyle,
modelName: typeof request.modelName === "string" ? request.modelName : null,
reportOutline: typeof request.reportOutline === "string" ? request.reportOutline : "",
generateImages: request.generateImages === true,
maxGeneratedImages: Number(request.maxGeneratedImages ?? 2),
originalContent: String(request.originalContent ?? ""),
},
}];
});
}
export async function cancelDurableDocumentRewrite(
req: Pick<DocumentRewriteRequest, "threadId" | "path">,
jobId: string,
): Promise<void> {
const query = new URLSearchParams({ thread_id: req.threadId, path: req.path });
const response = await apiFetch(
`${getBackendBaseURL()}/api/writing/document-rewrite/jobs/${encodeURIComponent(jobId)}/cancel?${query.toString()}`,
{ method: "POST" },
);
if (!response.ok) {
const body = await response.json().catch(() => ({})) as Record<string, unknown>;
throw new Error((body.detail as string | undefined) ?? "停止全文改写失败");
}
}
export async function* streamDocumentRewrite(
req: DocumentRewriteRequest,
signal?: AbortSignal,
): AsyncGenerator<DocumentRewriteStreamEvent> {
const started = await startDurableDocumentRewrite(req, signal);
yield { type: "job_started", jobId: started.jobId, reused: started.reused };
yield* streamDurableDocumentRewriteJob(req, started.jobId, signal);
}