Skip to content

CanvasAnvil is an open source AI diagram maker and flowchart generator - an infinite-canvas diagram editor and self-hosted drawio alternative that writes editable .drawio files. Text to diagram, then fix nodes, layout and labels in place. Also AI presentations, interior design CAD/BOM, posters and infographics.

fix(ppt): actually send a slide's material images to the image model

codingFeng1013df8f1ba6681
diff --git a/client/ai/client.ts b/client/ai/client.ts
index a621e96..3cb64ed 100644
--- a/client/ai/client.ts
+++ b/client/ai/client.ts
@@ -4,6 +4,7 @@ import { getAIConfig } from "@/ai/storage";
import { applyUiLanguagePolicy } from "@/ai/language-policy";
import { createLimiter } from "@/ai/limiter";
import {
+ MAX_GENERATION_REFERENCE_IMAGES,
MAX_REFERENCE_IMAGES,
cleanUrl,
normalizeImageUrlForModel,
@@ -208,7 +209,7 @@ export async function generateImage(request: ImageGenerationRequest, signal?: Ab
: null;
const additionalReferenceImageUrls = await normalizeImageUrlsForModel(
Array.isArray(request.additionalReferenceImageUrls) ? request.additionalReferenceImageUrls : [],
- Math.max(0, MAX_REFERENCE_IMAGES - (referenceImageUrl ? 1 : 0)),
+ Math.max(0, MAX_GENERATION_REFERENCE_IMAGES - (referenceImageUrl ? 1 : 0)),
);
try {
diff --git a/client/ai/images.ts b/client/ai/images.ts
index daab9f3..c0c7e68 100644
--- a/client/ai/images.ts
+++ b/client/ai/images.ts
@@ -11,8 +11,19 @@ const MAX_DIMENSION = 1536;
const MAX_DATA_URL_LENGTH = 1_800_000;
const JPEG_QUALITY = 0.86;
+/** Pictures a vision request may carry alongside its prompt. */
export const MAX_REFERENCE_IMAGES = 3;
+/**
+ * Pictures an image-generation request may carry.
+ *
+ * Higher than the vision cap because a slide's references are the deck's
+ * template plus whatever the user attached to that page, and the template
+ * alone used to leave room for two. Each one is downscaled first, so the
+ * ceiling here is roughly 10MB of request body.
+ */
+export const MAX_GENERATION_REFERENCE_IMAGES = 6;
+
export function cleanUrl(url: string) {
if (!url) return null;
if (url.startsWith('http')) return url;
diff --git a/client/workspaces/ppt/canvas/PptCanvas.tsx b/client/workspaces/ppt/canvas/PptCanvas.tsx
index 9681186..92bba51 100644
--- a/client/workspaces/ppt/canvas/PptCanvas.tsx
+++ b/client/workspaces/ppt/canvas/PptCanvas.tsx
@@ -831,7 +831,7 @@ export function PptCanvas({
templateImage || undefined,
[
...styleRefRefs.map((x) => ({ url: x.url, label: x.label })),
- ...materials.getImageRefs(id),
+ ...materials.getImageRefs(id, page.description || ""),
],
[instruction.trim(), styleReferenceInstruction].filter(Boolean).join("\n")
);
@@ -854,7 +854,7 @@ export function PptCanvas({
templateImage || undefined,
[
...styleRefRefs.map((x) => ({ url: x.url, label: x.label })),
- ...materials.getImageRefs(id),
+ ...materials.getImageRefs(id, page.description || ""),
],
[instruction.trim(), styleReferenceInstruction].filter(Boolean).join("\n")
);
@@ -872,7 +872,7 @@ export function PptCanvas({
...styleRefImageUrls,
...explicitMaterialImageUrls,
...uploadedImages,
- ...materials.getImageUrls(id),
+ ...materials.getImageUrls(id, page.description || ""),
]))
);
if (editedUrl) {
@@ -987,7 +987,7 @@ export function PptCanvas({
templateImage || undefined,
[
...styleRefRefs.map((x) => ({ url: x.url, label: x.label })),
- ...materials.getImageRefs(id),
+ ...materials.getImageRefs(id, page.description || ""),
],
[
kind === "both" && instruction.trim() ? instruction : "",
@@ -1046,7 +1046,7 @@ export function PptCanvas({
].filter(Boolean).join("\n"),
currentUrl || undefined,
templateImage || undefined,
- Array.from(new Set([...styleRefImageUrls, ...uploadedImages, ...materials.getImageUrls(id)]))
+ Array.from(new Set([...styleRefImageUrls, ...uploadedImages, ...materials.getImageUrls(id, page.description || "")]))
);
if (editedUrl) {
await pushImageVersionAndProcess(slide, editedUrl, "edited", instruction);
@@ -1766,7 +1766,7 @@ export function PptCanvas({
pages[i],
uiLang as "zh" | "en",
templateImage || undefined,
- materials.getImageRefs(pages[i].id || `slide-${i + 1}`)
+ materials.getImageRefs(pages[i].id || `slide-${i + 1}`, pages[i].description || "")
);
progressTracker.markBaseReady();
baseReady = true;
@@ -1822,7 +1822,7 @@ export function PptCanvas({
pages[pageIndex],
uiLang as "zh" | "en",
templateImage || undefined,
- materials.getImageRefs(currentSlide.id || `slide-${pageIndex + 1}`)
+ materials.getImageRefs(currentSlide.id || `slide-${pageIndex + 1}`, pages[pageIndex]?.description || "")
);
if (imageUrl) {
diff --git a/client/workspaces/ppt/canvas/hooks/use-slide-materials.ts b/client/workspaces/ppt/canvas/hooks/use-slide-materials.ts
index b541303..8fb7ac6 100644
--- a/client/workspaces/ppt/canvas/hooks/use-slide-materials.ts
+++ b/client/workspaces/ppt/canvas/hooks/use-slide-materials.ts
@@ -8,6 +8,7 @@ import {
materialLabel,
materialToken,
removeMaterialToken,
+ referencedMaterials,
} from "@/workspaces/ppt/canvas/lib/material-tokens";
import type { SlideData, SlideMaterialImage } from "@/workspaces/ppt/canvas/types";
@@ -123,11 +124,22 @@ export function useSlideMaterials({
}
};
- const getImageUrls = (slideId: string) =>
- (slideMaterials[slideId] || []).map((x) => x.dataUrl).filter(Boolean);
+ /**
+ * The pictures a slide's description asks for.
+ *
+ * Attached is not the same as referenced: a picture the user uploaded and
+ * then did not mention is not sent, because the prompt names and places
+ * each reference image it is given, and one it cannot account for only
+ * confuses the model.
+ */
+ const getReferenced = (slideId: string, description: string) =>
+ referencedMaterials(description, slideMaterials[slideId] || []);
+
+ const getImageUrls = (slideId: string, description: string) =>
+ getReferenced(slideId, description).map((x) => x.dataUrl).filter(Boolean);
- const getImageRefs = (slideId: string) =>
- (slideMaterials[slideId] || [])
+ const getImageRefs = (slideId: string, description: string) =>
+ getReferenced(slideId, description)
.map((x) => ({ url: x.dataUrl, label: x.name }))
.filter((x) => !!x.url);
diff --git a/client/workspaces/ppt/canvas/lib/material-tokens.ts b/client/workspaces/ppt/canvas/lib/material-tokens.ts
index 9de378a..d577827 100644
--- a/client/workspaces/ppt/canvas/lib/material-tokens.ts
+++ b/client/workspaces/ppt/canvas/lib/material-tokens.ts
@@ -37,6 +37,29 @@ export function removeMaterialToken(description: string, name: string): string {
.replace(/ *\n */g, "\n");
}
+/**
+ * The materials a description actually asks for, in the order it mentions
+ * them.
+ *
+ * A slide's attachments are not the same thing as its references: the user
+ * can upload a picture and then not use it, or delete the token but keep the
+ * file. Only the referenced ones are worth sending -- the model is told to
+ * place each one, so an unreferenced picture is a reference image nothing in
+ * the prompt accounts for. Ordering by first mention means that if a cap does
+ * bite, what survives is what the description leads with.
+ */
+export function referencedMaterials<T extends { name: string }>(
+ description: string,
+ materials: T[],
+): T[] {
+ const text = String(description || "");
+ return materials
+ .map((material) => ({ material, at: text.indexOf(materialToken(material.name)) }))
+ .filter((entry) => entry.at >= 0)
+ .sort((a, b) => a.at - b.at)
+ .map((entry) => entry.material);
+}
+
const PLACEMENTS: Record<MaterialLang, string[]> = {
zh: [
"放在左侧主视觉区域,约占画面宽度 40%",
diff --git a/server/ai/image.ts b/server/ai/image.ts
index 123262c..764f372 100644
--- a/server/ai/image.ts
+++ b/server/ai/image.ts
@@ -16,7 +16,11 @@ import type { ImageRequest } from "../../contracts/ai";
*/
type Route = (req: ImageRequest) => Promise<string>;
-function referenceImageUrls(req: ImageRequest): string[] {
+/**
+ * Every picture a request wants the model to look at: the template first, if
+ * there is one, then whatever the caller attached.
+ */
+export function referenceImageUrls(req: ImageRequest): string[] {
return [
...(req.referenceImageUrl ? [req.referenceImageUrl] : []),
...(req.additionalReferenceImageUrls || []).filter(Boolean),
@@ -51,11 +55,29 @@ function readChatImage(content: any): string | null {
return textPart ? fromText(textPart.text) : null;
}
+/**
+ * Sends every reference image, not just the first.
+ *
+ * A slide carries the deck's template *and* whatever pictures the user
+ * attached to that page, and the prompt names them and tells the model to use
+ * them. Sending one meant the model was told about images it never received,
+ * so it invented something to match the label instead -- which looks like a
+ * picture that is simply wrong rather than one that never arrived.
+ */
const editRoute: Route = async (req) => {
+ const urls = referenceImageUrls(req);
+ if (urls.length === 0) throw new Error("No reference image to edit.");
+
const form = new FormData();
form.append("model", req.channel.model);
form.append("prompt", req.prompt);
- form.append("image", await dataUrlToFile(req.referenceImageUrl!, "reference.png"));
+ const files = await Promise.all(
+ urls.map((url, i) => dataUrlToFile(url, i === 0 ? "reference.png" : `material-${i}.png`)),
+ );
+ // Repeated `image[]` is how the images API takes more than one; a gateway
+ // that only understands a single `image` still reads the first.
+ const field = files.length > 1 ? "image[]" : "image";
+ for (const file of files) form.append(field, file);
if (req.maskImageUrl) {
form.append("mask", await dataUrlToFile(req.maskImageUrl, "mask.png"));
}
@@ -92,10 +114,20 @@ const chatRoute: Route = async (req) => {
return await toDataUrl(url);
};
+/**
+ * The routes to try, in order.
+ *
+ * Chosen by whether there is any picture to send, not by whether a template
+ * was set. The generations route carries no images at all, so a slide with
+ * material pictures and no template used to lose them there.
+ */
+export function routeNamesFor(req: ImageRequest): Array<"edit" | "generation" | "chat"> {
+ return referenceImageUrls(req).length > 0 ? ["edit", "chat"] : ["generation", "chat"];
+}
+
export async function generateImage(req: ImageRequest): Promise<string> {
- const routes: Route[] = req.referenceImageUrl
- ? [editRoute, chatRoute]
- : [generationRoute, chatRoute];
+ const byName = { edit: editRoute, generation: generationRoute, chat: chatRoute };
+ const routes: Route[] = routeNamesFor(req).map((name) => byName[name]);
let firstError: unknown = null;
for (const route of routes) {
diff --git a/tests/image-routes.test.ts b/tests/image-routes.test.ts
new file mode 100644
index 0000000..0650448
--- /dev/null
+++ b/tests/image-routes.test.ts
@@ -0,0 +1,57 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import { referenceImageUrls, routeNamesFor } from "../server/ai/image";
+import type { ImageRequest } from "../contracts/ai";
+
+/**
+ * Which pictures reach the image model, and by which route.
+ *
+ * This is where a slide's material images used to vanish. The prompt names
+ * every reference image and tells the model where to place it, so an image
+ * that is described but never sent does not leave a gap -- the model invents
+ * something to match the label, which reads as a wrong picture rather than a
+ * missing one. That is why it went unnoticed, and why it is pinned here.
+ */
+
+const req = (over: Partial<ImageRequest> = {}): ImageRequest =>
+ ({ prompt: "p", channel: { model: "gpt-image-1", apiKey: "k", baseUrl: "b" }, ...over }) as ImageRequest;
+
+test("the template comes first, then the materials", () => {
+ const urls = referenceImageUrls(
+ req({ referenceImageUrl: "template.png", additionalReferenceImageUrls: ["mat-1.png", "mat-2.png"] }),
+ );
+ assert.deepEqual(urls, ["template.png", "mat-1.png", "mat-2.png"]);
+});
+
+test("materials are carried even with no template", () => {
+ assert.deepEqual(referenceImageUrls(req({ additionalReferenceImageUrls: ["mat-1.png"] })), ["mat-1.png"]);
+});
+
+test("a request with no pictures carries none", () => {
+ assert.deepEqual(referenceImageUrls(req()), []);
+ assert.deepEqual(referenceImageUrls(req({ additionalReferenceImageUrls: [] })), []);
+});
+
+test("blank entries are dropped rather than sent as empty files", () => {
+ assert.deepEqual(referenceImageUrls(req({ additionalReferenceImageUrls: ["", "mat-1.png"] })), ["mat-1.png"]);
+});
+
+test("materials without a template still take an image-carrying route", () => {
+ // The regression: this used to pick the generations route, which sends the
+ // prompt alone, so the user's picture never left the browser's request.
+ assert.deepEqual(routeNamesFor(req({ additionalReferenceImageUrls: ["mat-1.png"] })), ["edit", "chat"]);
+});
+
+test("a template takes an image-carrying route", () => {
+ assert.deepEqual(routeNamesFor(req({ referenceImageUrl: "template.png" })), ["edit", "chat"]);
+});
+
+test("only a prompt takes the generations route", () => {
+ assert.deepEqual(routeNamesFor(req()), ["generation", "chat"]);
+});
+
+test("chat is always the fallback, because it can carry every picture", () => {
+ for (const r of [req(), req({ referenceImageUrl: "t.png" }), req({ additionalReferenceImageUrls: ["m.png"] })]) {
+ assert.equal(routeNamesFor(r).at(-1), "chat");
+ }
+});
diff --git a/tests/ppt-material-references.test.ts b/tests/ppt-material-references.test.ts
new file mode 100644
index 0000000..24563ef
--- /dev/null
+++ b/tests/ppt-material-references.test.ts
@@ -0,0 +1,56 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import {
+ materialToken,
+ referencedMaterials,
+} from "../client/workspaces/ppt/canvas/lib/material-tokens";
+
+/**
+ * Which of a slide's attached pictures are actually sent to the image model.
+ *
+ * Attached is not the same as referenced. The prompt names every reference
+ * image it is given and tells the model where to put it, so a picture the
+ * user uploaded and never mentioned is one the prompt cannot account for.
+ */
+
+const mat = (name: string) => ({ name, dataUrl: `${name}.png` });
+
+test("only the pictures the description mentions come through", () => {
+ const picked = referencedMaterials(
+ `左侧放 ${materialToken("第1张")},右侧留白。`,
+ [mat("第1张"), mat("第2张")],
+ );
+ assert.deepEqual(picked.map((m) => m.name), ["第1张"]);
+});
+
+test("an upload nobody referenced is not sent", () => {
+ assert.deepEqual(referencedMaterials("一张普通的示意图,没有引用任何素材。", [mat("第1张")]), []);
+});
+
+test("references are ordered by where the description mentions them", () => {
+ // If a cap ever bites, what survives should be what the description leads
+ // with, not whatever order the files happened to be uploaded in.
+ const description = `先看 ${materialToken("第3张")},再看 ${materialToken("第1张")}。`;
+ const picked = referencedMaterials(description, [mat("第1张"), mat("第2张"), mat("第3张")]);
+ assert.deepEqual(picked.map((m) => m.name), ["第3张", "第1张"]);
+});
+
+test("a description that mentions everything keeps everything", () => {
+ const description = `${materialToken("第1张")} ${materialToken("第2张")}`;
+ const picked = referencedMaterials(description, [mat("第1张"), mat("第2张")]);
+ assert.equal(picked.length, 2);
+});
+
+test("an empty description references nothing", () => {
+ assert.deepEqual(referencedMaterials("", [mat("第1张")]), []);
+ assert.deepEqual(referencedMaterials(undefined as unknown as string, [mat("第1张")]), []);
+});
+
+test("a name that only appears as bare text is not a reference", () => {
+ // The token is the reference; the words around it are just prose.
+ assert.deepEqual(referencedMaterials("把第1张放在左边", [mat("第1张")]), []);
+});
+
+test("no attachments means nothing to send", () => {
+ assert.deepEqual(referencedMaterials(`看 ${materialToken("第1张")}`, []), []);
+});