ai-chatbot/tests/routes/canvas-toolbar-capability.test.ts

245 lines
14 KiB
TypeScript
Raw 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 { expect, test } from "@playwright/test";
import { createCanvasSaveQueue } from "@/lib/client/canvas-save-queue";
import { executeCanvasToolbarCapability } from "@/lib/client/canvas-toolbar-capability";
import { createCanvasCapabilityClientCommand } from "@/lib/canvas/capabilities/client-command";
import { useCanvasStore } from "@/store/canvas";
import { canvasService } from "@/services/canvas";
import { formatRequestFailure, getRequestFailureDetails } from "@/lib/request-error";
const originalFetch = globalThis.fetch;
const node = (id: string) => ({ id, type: "image", position: { x: 0, y: 0 },
size: { width: 100, height: 100 }, data: { src: `https://example.com/${id}.png` } });
const command = () => createCanvasCapabilityClientCommand({
projectId: "project-a", capabilityId: "image.remove_watermark", nodeIds: ["source"], source: "toolbar",
});
test.beforeEach(() => {
useCanvasStore.getState().clearCanvas();
useCanvasStore.getState().setProject("project-a");
useCanvasStore.getState().loadCanvas({ nodes: [node("source") as any], edges: [] });
useCanvasStore.getState().setCanvasRevision("r1", "r1");
});
test.afterEach(() => { globalThis.fetch = originalFetch; });
test("waits for the selected image to be saved before submitting and keeps subsequent saves behind the result", async () => {
const queue = createCanvasSaveQueue();
const events: string[] = [];
let finishSave!: () => void;
const pendingSave = new Promise<void>(resolve => { finishSave = resolve; });
const pending = queue.enqueueOperation(async () => {
events.push("saving"); await pendingSave; events.push("saved"); return true;
}, async () => { events.push("submitted"); });
const autosave = queue.enqueue(async () => { events.push("autosaved"); });
await Promise.resolve();
expect(events).toEqual(["saving"]);
finishSave();
await Promise.all([pending, autosave]);
expect(events).toEqual(["saving", "saved", "submitted", "autosaved"]);
});
test("a failed save does not submit a paid image task or block later saves", async () => {
const queue = createCanvasSaveQueue();
let submissions = 0;
await expect(queue.enqueueOperation(async () => false, async () => { submissions++; })).rejects.toThrow("尚未保存成功");
expect(submissions).toBe(0);
expect(await queue.enqueue(async () => "saved")).toBe("saved");
});
test("merges the result with edits made while processing and advances the save revision", async () => {
globalThis.fetch = (async (url) => {
if (String(url).endsWith("/capabilities")) {
useCanvasStore.getState().moveNode("source", { x: 50, y: 80 });
return Response.json({ success: true, task: { status: "succeeded" } });
}
return Response.json({ success: true, data: {
updatedAt: "r2", canvasData: { nodes: [node("source"), node("result")], edges: [] },
} });
}) as typeof fetch;
await executeCanvasToolbarCapability(command());
const state = useCanvasStore.getState();
expect(state.nodes.map(n => n.id)).toEqual(["source", "result"]);
expect(state.nodes[0].position).toEqual({ x: 50, y: 80 });
expect(state.canvasRevision).toBe("r2");
});
test("a provider failure is shown without reloading or changing the canvas", async () => {
globalThis.fetch = (async () => Response.json({ success: false, error: "去水印服务繁忙" }, { status: 503 })) as typeof fetch;
await expect(executeCanvasToolbarCapability(command())).rejects.toThrow("去水印服务繁忙");
expect(useCanvasStore.getState().nodes.map(n => n.id)).toEqual(["source"]);
expect(useCanvasStore.getState().canvasRevision).toBe("r1");
});
test("a lost submission response polls the original task and never resubmits", async () => {
const requests: { method: string; url: string }[] = [];
const originalSetTimeout = globalThis.setTimeout;
let polls = 0;
globalThis.setTimeout = ((fn: () => void) => originalSetTimeout(fn, 0)) as typeof setTimeout;
globalThis.fetch = (async (url, init) => {
requests.push({ method: init?.method || "GET", url: String(url) });
if (init?.method === "POST") throw new TypeError("fetch failed");
if (String(url).includes("/capabilities?")) return Response.json({ success: true, task: { status: ++polls === 1 ? "running" : "succeeded" } });
return Response.json({ success: true, data: { updatedAt: "r2", canvasData: { nodes: [node("source"), node("result")], edges: [] } } });
}) as typeof fetch;
const submitted = command();
try { await executeCanvasToolbarCapability(submitted); } finally { globalThis.setTimeout = originalSetTimeout; }
expect(requests.filter(r => r.method === "POST")).toHaveLength(1);
expect(requests.filter(r => r.url.includes("/capabilities?"))).toHaveLength(2);
expect(requests.filter(r => r.url.includes("/capabilities?")).every(r => r.url.includes(encodeURIComponent(submitted.requestId)))).toBe(true);
expect(useCanvasStore.getState().nodes.map(n => n.id)).toEqual(["source", "result"]);
});
test("a recovered matting rejection shows its dimensions and advice without changing the canvas or resubmitting", async () => {
const submitted = createCanvasCapabilityClientCommand({ projectId: "project-a", capabilityId: "image.remove_background", nodeIds: ["source"], source: "toolbar" });
const failure = getRequestFailureDetails("抠图参考图分辨率超限(5056×3392 像素),当前 AOS 上游要求宽、高均不超过 4096 像素。");
const message = formatRequestFailure(failure, submitted.requestId);
let posts = 0;
globalThis.fetch = (async (url, options) => {
if (options?.method === "POST") { posts++; return new Response(null, { status: 504 }); }
expect(String(url)).toContain(encodeURIComponent(submitted.requestId));
return Response.json({ success: true, task: { status: "failed", failure, error: message } });
}) as typeof fetch;
await expect(executeCanvasToolbarCapability(submitted)).rejects.toThrow(message);
expect(posts).toBe(1);
expect(useCanvasStore.getState().nodes.map(n => n.id)).toEqual(["source"]);
expect(useCanvasStore.getState().canvasRevision).toBe("r1");
});
test("a lost box-cutout response recovers the same selection into its original canvas with one submission", async () => {
const submitted = createCanvasCapabilityClientCommand({ projectId: "project-a", capabilityId: "image.box_cutout", nodeIds: ["source"], source: "toolbar", args: { x: 0.25, y: 0.2, width: 0.4, height: 0.5, paddingRatio: 0.08 } });
let posts = 0, polls = 0;
const selected = { ...node("cutout"), data: { src: "https://example.com/cutout.png", metadata: { editMode: "box-cutout", cropRectApplied: submitted.args } } };
globalThis.fetch = (async (url, options) => {
if (options?.method === "POST") {
posts++;
expect(JSON.parse(String(options.body))).toMatchObject({ capabilityId: "image.box_cutout", requestId: submitted.requestId, args: submitted.args });
useCanvasStore.getState().moveNode("source", { x: 20, y: 30 });
return new Response(null, { status: 524 });
}
if (String(url).includes("/capabilities?")) {
polls++;
expect(String(url)).toContain(encodeURIComponent(submitted.requestId));
return Response.json({ success: true, task: { status: "succeeded" } });
}
return Response.json({ success: true, data: { updatedAt: "r2", canvasData: { nodes: [node("source"), selected], edges: [] } } });
}) as typeof fetch;
await executeCanvasToolbarCapability(submitted);
expect({ posts, polls }).toEqual({ posts: 1, polls: 1 });
const state = useCanvasStore.getState();
expect(state.projectId).toBe("project-a");
expect(state.nodes.map(n => n.id)).toEqual(["source", "cutout"]);
expect(state.nodes[0].position).toEqual({ x: 20, y: 30 });
expect(state.nodes[1].data).toEqual(selected.data);
});
test("switching projects during processing does not load the old result into the new project", async () => {
globalThis.fetch = (async (url) => {
if (String(url).endsWith("/capabilities")) {
useCanvasStore.getState().setProject("project-b");
useCanvasStore.getState().loadCanvas({ nodes: [node("other") as any], edges: [] });
return Response.json({ success: true, task: { status: "succeeded" } });
}
return Response.json({ success: true, data: { updatedAt: "r2", canvasData: { nodes: [node("result")], edges: [] } } });
}) as typeof fetch;
await executeCanvasToolbarCapability(command());
expect(useCanvasStore.getState().nodes.map(n => n.id)).toEqual(["other"]);
expect(useCanvasStore.getState().canvasRevision).toBe("r1");
});
test("cover updates advance the local revision before the next queued save", async () => {
const queue = createCanvasSaveQueue();
globalThis.fetch = (async () => Response.json({
success: true, previousCanvasRevision: "r1", data: { updatedAt: "r2" },
})) as typeof fetch;
const cover = queue.enqueue(() => canvasService.updateProject("project-a", { thumbnail: "https://example.com/source.png" }));
const nextSave = queue.enqueue(async () => useCanvasStore.getState().canvasRevision);
await cover;
expect(await nextSave).toBe("r2");
});
test("metadata changes never adopt an unseen remote canvas revision", async () => {
globalThis.fetch = (async () => Response.json({
success: true, previousCanvasRevision: "external-edit", data: { updatedAt: "r3" },
})) as typeof fetch;
await canvasService.updateProject("project-a", { title: "Renamed" });
expect(useCanvasStore.getState().canvasRevision).toBe("r1");
});
test("reading a result without applying it cannot authorize an old snapshot to overwrite the result", async () => {
const previousWindow = Object.getOwnPropertyDescriptor(globalThis, "window");
Object.defineProperty(globalThis, "window", { configurable: true, value: {} });
let remoteNodes = [node("source"), node("result")];
globalThis.fetch = (async (_url, options) => {
if (options?.method === "PUT") {
const body = JSON.parse(String(options.body));
if (body.baseCanvasRevision !== "r2") return Response.json({ success: false, error: "画布已更新" }, { status: 409 });
remoteNodes = body.canvasData.nodes;
return Response.json({ success: true, data: { updatedAt: "r3" } });
}
return Response.json({ success: true, data: { id: "project-a", updatedAt: "r2", canvasData: { nodes: remoteNodes, edges: [] } } });
}) as typeof fetch;
try {
await canvasService.getProject("project-a");
const saved = await canvasService.saveCanvasState("project-a", useCanvasStore.getState().getCanvasState());
expect(saved).toMatchObject({ success: false, status: 409 });
expect(remoteNodes.map(n => n.id)).toEqual(["source", "result"]);
expect(useCanvasStore.getState().canvasRevision).toBe("r1");
} finally {
if (previousWindow) Object.defineProperty(globalThis, "window", previousWindow);
else Reflect.deleteProperty(globalThis, "window");
}
});
test("a delayed read cannot change the revision of a newly selected project", async () => {
const previousWindow = Object.getOwnPropertyDescriptor(globalThis, "window");
Object.defineProperty(globalThis, "window", { configurable: true, value: {} });
let complete!: (response: Response) => void;
globalThis.fetch = (() => new Promise<Response>(resolve => { complete = resolve; })) as typeof fetch;
try {
const pending = canvasService.getProject("project-a");
useCanvasStore.getState().setProject("project-b");
useCanvasStore.getState().loadCanvas({ nodes: [node("other") as any], edges: [] });
useCanvasStore.getState().setCanvasRevision("r9", "r9");
complete(Response.json({ success: true, data: { id: "project-a", updatedAt: "r2", canvasData: { nodes: [node("result")], edges: [] } } }));
await pending;
expect(useCanvasStore.getState().canvasRevision).toBe("r9");
expect(useCanvasStore.getState().nodes.map(n => n.id)).toEqual(["other"]);
} finally {
if (previousWindow) Object.defineProperty(globalThis, "window", previousWindow);
else Reflect.deleteProperty(globalThis, "window");
}
});
test("a delayed save cannot change the revision of a newly selected project", async () => {
const previousWindow = Object.getOwnPropertyDescriptor(globalThis, "window");
Object.defineProperty(globalThis, "window", { configurable: true, value: {} });
let complete!: (response: Response) => void;
globalThis.fetch = (() => new Promise<Response>(resolve => { complete = resolve; })) as typeof fetch;
try {
const pending = canvasService.saveCanvasState("project-a", useCanvasStore.getState().getCanvasState());
useCanvasStore.getState().setProject("project-b");
useCanvasStore.getState().loadCanvas({ nodes: [node("other") as any], edges: [] });
useCanvasStore.getState().setCanvasRevision("r9", "r9");
complete(Response.json({ success: true, data: { updatedAt: "r2" } }));
await pending;
expect(useCanvasStore.getState().canvasRevision).toBe("r9");
expect(useCanvasStore.getState().nodes.map(n => n.id)).toEqual(["other"]);
} finally {
if (previousWindow) Object.defineProperty(globalThis, "window", previousWindow);
else Reflect.deleteProperty(globalThis, "window");
}
});
test("a result merge conflict retains both the local edit and its original revision", async () => {
globalThis.fetch = (async (url) => {
if (String(url).endsWith("/capabilities")) {
useCanvasStore.getState().moveNode("source", { x: 50, y: 80 });
return Response.json({ success: true, task: { status: "succeeded" } });
}
return Response.json({ success: true, data: { updatedAt: "r2", canvasData: {
nodes: [{ ...node("source"), position: { x: 200, y: 80 } }, node("result")], edges: [],
} } });
}) as typeof fetch;
await expect(executeCanvasToolbarCapability(command())).rejects.toThrow("画布有冲突");
expect(useCanvasStore.getState().canvasRevision).toBe("r1");
expect(useCanvasStore.getState().nodes[0].position).toEqual({ x: 50, y: 80 });
});