ai-chatbot/lib/client/batch-instruction-edit.ts

73 lines
2.5 KiB
TypeScript

import type { ParsedImage } from "@/lib/canvas/generate-image";
const statusEndpoint = "/api/canvas/generate/image";
type InstructionTask = {
status: "waiting" | "pending" | "running" | "succeeded" | "failed";
error?: string;
failure?: { outcome?: "failed" | "unknown" };
result?: { images?: ParsedImage[] };
};
export class BatchInstructionEditError extends Error {
constructor(message: string, readonly canStartNewTask: boolean) {
super(message);
}
}
export async function runBatchInstructionEdit(input: {
taskId: string;
image: string;
reference?: string;
instruction: string;
square: boolean;
submitted?: boolean;
}, onSubmitted: () => void) {
const taskPath = `${statusEndpoint}?taskId=${encodeURIComponent(input.taskId)}`;
if (!input.submitted) {
// A retry with the same identifier can only find or create the original task.
const response = await fetch("/api/canvas/batch-instruction", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(input),
signal: AbortSignal.timeout(20_000),
}).catch(() => null);
if (response?.ok) onSubmitted();
if (response && (response.status === 400 || response.status === 403)) {
const body = await response.json().catch(() => null);
throw new BatchInstructionEditError(body?.error || "任务未提交", true);
}
}
const deadline = Date.now() + 20 * 60_000;
let failures = 0;
while (Date.now() < deadline && failures < 5) {
const response = await fetch(taskPath, {
cache: "no-store",
signal: AbortSignal.timeout(12_000),
}).catch(() => null);
const task = response?.ok
? (await response.json().catch(() => null))?.task as InstructionTask | undefined
: undefined;
if (task) {
failures = 0;
onSubmitted();
if (task.status === "failed") {
throw new BatchInstructionEditError(
task.error || "图片编辑失败",
task.failure?.outcome === "failed",
);
}
if (task.status === "succeeded") {
const image = task.result?.images?.[0];
if (!image?.originalUrl) throw new BatchInstructionEditError("任务已完成,但暂时无法取回图片", false);
return { result: image.thumbnailUrl || image.originalUrl, originalUrl: image.originalUrl };
}
} else {
failures++;
}
await new Promise(resolve => setTimeout(resolve, 2500));
}
throw new BatchInstructionEditError("暂时无法确认结果,请继续查询原任务", false);
}