代码提交
This commit is contained in:
1 parent
70da7c5649
commit
178572bc7f
79 files changed
+13456
-798
No files matched your search
@@ -31,7 +31,7 @@ export type RewriteStreamEvent =
|
||||
|
||||
// ── SSE parser ────────────────────────────────────────────────────────────────
|
||||
|
||||
async function* parseSse(body: ReadableStream<Uint8Array>): AsyncGenerator<{ event: string; data: string }> {
|
||||
export async function* parseSse(body: ReadableStream<Uint8Array>): AsyncGenerator<{ event: string; data: string }> {
|
||||
const reader = body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let buffer = "";
|
||||
@@ -106,3 +106,288 @@ export async function* streamRewrite(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export type DocumentRewriteStyle =
|
||||
| "formal_analysis"
|
||||
| "professional"
|
||||
| "concise"
|
||||
| "readable";
|
||||
|
||||
export interface DocumentRewriteRequest {
|
||||
threadId: string;
|
||||
path: string;
|
||||
instruction: string;
|
||||
style?: DocumentRewriteStyle;
|
||||
modelName?: string;
|
||||
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[];
|
||||
}
|
||||
|
||||
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: "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 }
|
||||
| { type: "done"; committedHash: string; versionId?: string }
|
||||
| { 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;
|
||||
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 "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,
|
||||
};
|
||||
case "done":
|
||||
return {
|
||||
type: "done",
|
||||
committedHash: String(parsed.committedHash ?? ""),
|
||||
versionId: typeof parsed.versionId === "string" ? parsed.versionId : undefined,
|
||||
};
|
||||
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,
|
||||
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);
|
||||
}
|
||||
Reference in new issue
Block a user