From 3786f6d2b17ee691aac69cfe83e81d9313f2a5a2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20=C5=9Anie=C5=BCy=C5=84ski?= <27588547+msniezynski@users.noreply.github.com> Date: Sun, 22 Nov 2026 23:25:01 +0100 Subject: [PATCH] chore: release 0.2.1 with chat reference uploads and GIFs from references --- CHANGELOG.md | 8 ++ docs/cloudflare.md | 2 +- docs/configuration.md | 2 +- docs/model-profiles.md | 2 +- package.json | 2 +- scripts/build-mcp-views.ts | 9 +++ skills/image-queue/SKILL.md | 2 +- src/app/website/setup-prompt.tsx | 2 +- src/components/workspace.tsx | 6 +- src/core/job-status.ts | 8 ++ src/core/model-profiles.ts | 2 - src/core/notes.ts | 8 +- src/core/service.ts | 8 +- src/mcp/apps.ts | 36 ++++++++- src/mcp/server.ts | 8 +- src/mcp/tool-annotations.ts | 2 +- src/mcp/views/compact-app.ts | 3 + src/mcp/views/gallery-html.ts | 4 +- src/mcp/views/image-html.ts | 4 +- src/mcp/views/job-html.ts | 4 +- src/mcp/views/job.ts | 8 +- src/mcp/views/reference-file.ts | 68 +++++++++++++++++ src/mcp/views/reference-html.ts | 3 + src/mcp/views/reference.ts | 116 +++++++++++++++++++++++++++++ src/sources/providers.ts | 115 ++++++++++++++++++++-------- src/storage/local-references.ts | 2 +- tests/core.test.ts | 5 +- tests/http-secret-boundary.test.ts | 2 + tests/mcp-http-session.test.ts | 4 +- tests/mcp-reference-upload.test.ts | 115 ++++++++++++++++++++++++++++ tests/mcp.test.ts | 2 - tests/model-profiles.test.ts | 2 +- tests/prepare-correction.test.ts | 20 ++++- tests/providers.test.ts | 31 ++++++++ tests/workspace.test.tsx | 5 +- wrangler.jsonc | 2 +- 36 files changed, 546 insertions(+), 76 deletions(-) create mode 100644 src/mcp/views/reference-file.ts create mode 100644 src/mcp/views/reference-html.ts create mode 100644 src/mcp/views/reference.ts create mode 100644 tests/mcp-reference-upload.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index cfa493b..4e6de0a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 0.2.1 - 2026-11-22 + +- Use an image attached to the chat as a reference: `upload_reference` shows a card in Claude where you choose, drop or paste the image on a computer or phone, and the card sends the reference ID back. Claude cannot pass a chat attachment to a tool, and the hosted server cannot read local paths. +- GIF requests accept reference images. They are sent to the OpenAI edits endpoint with the frame settings, and the next version of such a GIF keeps the original's references. +- A hosted server cannot scale an animated GIF, so a GIF request whose size the model does not render natively is refused before submission, with the size to request instead (for example 608x1088 for a tall GIF of up to 12 frames). Locally such GIFs are still scaled. +- A blocked job whose generated file was saved can be previewed with `view_image` and downloaded from the job view, as the web panel already allowed. +- The Cloudflare generation queue runs up to 20 jobs at once instead of 4. + ## 0.2.0 — 2026-11-20 - Deploy image-queue to your own Cloudflare account with `pnpm cloudflare:setup`: D1, R2, a generation queue, a custom domain, Cloudflare Access with Managed OAuth and the Worker secrets in one repeatable command. See [docs/cloudflare.md](docs/cloudflare.md) and [ADR-0020](docs/decisions/0020-remote-mcp-behind-cloudflare-access.md). diff --git a/docs/cloudflare.md b/docs/cloudflare.md index 60f910a..9a8a5ad 100644 --- a/docs/cloudflare.md +++ b/docs/cloudflare.md @@ -139,6 +139,6 @@ node scripts/cloudflare-acceptance.mjs ## Limits - The Codex file queue and its local workers cannot run on Cloudflare. Cloud jobs use the API. -- `add_reference` reads local files, so it does not work against the hosted endpoint. Upload references in the panel instead. +- `add_reference` reads local files, so it does not work against the hosted endpoint. Claude also cannot pass an image attached to the chat to a tool. Ask Claude to use a reference instead: it calls `upload_reference`, which shows a card where you choose, drop or paste the image on a computer or phone. The card uploads it, scaling photos over 3 MB down to 2048 px, and sends the reference ID back to Claude. - The hosted MCP endpoint is stateless. It always lists the MCP Apps views (request, image and gallery), because it never sees the client's initialize request. - All allowed users share one workspace. diff --git a/docs/configuration.md b/docs/configuration.md index a1dc936..c9ba77f 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -110,7 +110,7 @@ Step-by-step setup and client connection instructions are in [Cloudflare deploym pnpm build:cloudflare ``` -The application includes a D1/R2 storage adapter and migrations. Cloudflare thumbnail generation uses the IMAGES binding; generated thumbnails are cached in R2 by content hash. API generation runs from the `image-queue-generation` Cloudflare Queue: a request creates the job and returns at once, and the queue consumer runs one job per invocation without automatic retries, so a client time limit cannot interrupt a paid attempt. A job whose lock is held by another operation is offered again every 10 seconds for about five minutes; nothing is sent to the provider until the lock is taken. D1 locks carry a 20-minute lease, longer than a consumer's 15-minute limit, so a lock left by a stopped Worker is released. See [ADR-0020](decisions/0020-remote-mcp-behind-cloudflare-access.md). +The application includes a D1/R2 storage adapter and migrations. Cloudflare thumbnail generation uses the IMAGES binding; generated thumbnails are cached in R2 by content hash. API generation runs from the `image-queue-generation` Cloudflare Queue: a request creates the job and returns at once, and the queue consumer runs one job per invocation without automatic retries, so a client time limit cannot interrupt a paid attempt. Up to 20 jobs run at once (`max_concurrency` of the queue consumer in `wrangler.jsonc`); each one is a separate billed provider call. A job whose lock is held by another operation is offered again every 10 seconds for about five minutes; nothing is sent to the provider until the lock is taken. D1 locks carry a 20-minute lease, longer than a consumer's 15-minute limit, so a lock left by a stopped Worker is released. See [ADR-0020](decisions/0020-remote-mcp-behind-cloudflare-access.md). Before deploying, create the D1 database, the R2 bucket and the queue, replace the local D1 ID in `wrangler.jsonc`, apply the files in `migrations/` in order, and attach a custom domain. The Worker is not served on `workers.dev` or preview URLs. Configure `IMAGE_QUEUE_STORAGE_DRIVER=cloudflare`, `IMAGE_QUEUE_CF_ACCESS_TEAM_DOMAIN` (for example `team.cloudflareaccess.com`), `IMAGE_QUEUE_CF_ACCESS_AUDIENCE` (the Access application's AUD tag) and `IMAGE_QUEUE_ACCESS_ALLOWED_EMAILS` (comma-separated). Provider API keys are Cloudflare platform secrets using the prefixed names above; use a dedicated key with a monthly spend limit. diff --git a/docs/model-profiles.md b/docs/model-profiles.md index 29ed6d7..3dc7798 100644 --- a/docs/model-profiles.md +++ b/docs/model-profiles.md @@ -42,7 +42,7 @@ Sources: The OpenAI Platform playground also offers "Extra high" and "Max" complexity for 2.6 Sunburst. The API reference and the guide list only low, medium and high, so the profiles follow the API documentation. -An API request may set `outputFormat` to a value in that model's `outputFormats`. Omitting it stores PNG. The same request may set `frameCount` (2–16) and `frameDurationMs` (20–2000) only for GIF. SVG cannot be combined with reference images or frame settings, and each SVG job is its own generation with `n=1`. GIF output with reference images is not supported by this application yet. Queue requests cannot set a format or frame timing. Quality, complexity and output format are refused for queue requests and for models that do not list them. A transparent background is refused unless the format is PNG or WebP. +An API request may set `outputFormat` to a value in that model's `outputFormats`. Omitting it stores PNG. The same request may set `frameCount` (2–16) and `frameDurationMs` (20–2000) only for GIF. SVG cannot be combined with reference images or frame settings, and each SVG job is its own generation with `n=1`. GIF output may include reference images; they guide the animation. Queue requests cannot set a format or frame timing. Quality, complexity and output format are refused for queue requests and for models that do not list them. A transparent background is refused unless the format is PNG or WebP. PNG, WebP and JPEG results are fitted to the requested exact size in that format. GIF keeps its animation when it can be fitted without upscaling; otherwise the generated animation is stored and the job records why fitting failed. SVG is stored as generated, and its width and height are the provider size. Exact sizes that are off the 16-pixel grid or below the minimum pixel count, such as 256 × 256 sprites, are generated at the smallest covering size and fitted down; sizes above the limits are refused, never upscaled. diff --git a/package.json b/package.json index c95a4eb..3099b26 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "image-queue", - "version": "0.2.0", + "version": "0.2.1", "description": "Local-first image queue and generation workspace", "scripts": { "dev": "next dev --hostname 127.0.0.1 --port 3215", diff --git a/scripts/build-mcp-views.ts b/scripts/build-mcp-views.ts index 9e79f16..aeb34c0 100644 --- a/scripts/build-mcp-views.ts +++ b/scripts/build-mcp-views.ts @@ -61,3 +61,12 @@ const imageScript = imageBuild.outputFiles[0].text.replaceAll("

Loading image…

Describe a change and save it. If it is about one place, tap that place on the image first. Request next version then generates a new image with your saved changes.

Saved changes

    `; reportViewSize("image", imageHtml); await writeFile("src/mcp/views/image-html.ts", `// Generated by scripts/build-mcp-views.ts\nexport const imageViewHtml = ${JSON.stringify(imageHtml)};\nexport const imageViewVersion = ${JSON.stringify(viewVersion(imageHtml))};\n`); + +const referenceBuild = await build({ + entryPoints: ["src/mcp/views/reference.ts"], bundle: true, write: false, + format: "iife", platform: "browser", minify: true, +}); +const referenceScript = referenceBuild.outputFiles[0].text.replaceAll("

    Connecting to image-queue…

    Claude cannot pass a file attached to the chat to image-queue, so choose the same image here. PNG, JPEG or WebP; large photos are scaled down to 2048 px.

    or drop or paste it here

      `; +reportViewSize("reference", referenceHtml); +await writeFile("src/mcp/views/reference-html.ts", `// Generated by scripts/build-mcp-views.ts\nexport const referenceViewHtml = ${JSON.stringify(referenceHtml)};\nexport const referenceViewVersion = ${JSON.stringify(viewVersion(referenceHtml))};\n`); diff --git a/skills/image-queue/SKILL.md b/skills/image-queue/SKILL.md index ba49b07..d881fc8 100644 --- a/skills/image-queue/SKILL.md +++ b/skills/image-queue/SKILL.md @@ -22,7 +22,7 @@ Changing a setting alone is not approval for extra generations. Submit the image ## Prepare an accurate request -Choose the intended project from `list_projects`. Read available models and their supported options rather than guessing dimensions or capabilities. For queue requests use the requested `aspectRatio`, or exact `width` and `height` when the user needs them. For API requests use the returned size profile, `transparency`, `qualities`, `complexities` and `outputFormats`; pass `quality`, `complexity` or `outputFormat` only for API requests and only with a listed value. Omit `outputFormat` for PNG. Transparent output is PNG or WebP only. GIF may set `frameCount` (2–16) and `frameDurationMs` (20–2000). SVG cannot include reference images or frame settings. GIF output with reference images is not supported by this application yet. `count` (1–10) creates that many independent jobs; replay the same idempotency key and count to get the same jobs. `request_images` counts the expanded jobs toward 20. Capabilities under `documentedOnly`, and every capability of a model with `generationVerified: false`, come from provider documentation without a generation receipt: check the delivered file. The final raster may be fitted down from a supported provider size; GIF keeps its animation when fitting is possible, and SVG is stored as generated. Do not promise a native size or invent support for transparency. +Choose the intended project from `list_projects`. Read available models and their supported options rather than guessing dimensions or capabilities. For queue requests use the requested `aspectRatio`, or exact `width` and `height` when the user needs them. For API requests use the returned size profile, `transparency`, `qualities`, `complexities` and `outputFormats`; pass `quality`, `complexity` or `outputFormat` only for API requests and only with a listed value. Omit `outputFormat` for PNG. Transparent output is PNG or WebP only. GIF may set `frameCount` (2–16) and `frameDurationMs` (20–2000). SVG cannot include reference images or frame settings. GIF output may include reference images; they guide the animation. `count` (1–10) creates that many independent jobs; replay the same idempotency key and count to get the same jobs. `request_images` counts the expanded jobs toward 20. Capabilities under `documentedOnly`, and every capability of a model with `generationVerified: false`, come from provider documentation without a generation receipt: check the delivered file. The final raster may be fitted down from a supported provider size; GIF keeps its animation when fitting is possible, and SVG is stored as generated. Do not promise a native size or invent support for transparency. Keep the user's prompt literal. Add style instructions only when requested or approved. Do not silently shorten or rewrite a failed prompt to get a different result. Keep provider-native controls separate from prompt text. diff --git a/src/app/website/setup-prompt.tsx b/src/app/website/setup-prompt.tsx index cb99fbf..6a3d1af 100644 --- a/src/app/website/setup-prompt.tsx +++ b/src/app/website/setup-prompt.tsx @@ -7,7 +7,7 @@ import { CopyButton } from "@/components/copy-button"; export const setupPrompt = `Set up image-queue on this Mac. Work locally, not in the cloud. If local file access and shell commands are unavailable, stop and explain what I need to enable. 1. Check git, Node.js 24 or newer, pnpm 10.28.2, and the Codex CLI. Tell me what is missing before installing anything. Ask before each tool installation. Do not use sudo without explaining why and receiving my approval. -2. Check https://github.com/corgicorner/image-queue for release v0.2.0. If that release is unavailable, stop and tell me; do not silently install main or a different version. +2. Check https://github.com/corgicorner/image-queue for release v0.2.1. If that release is unavailable, stop and tell me; do not silently install main or a different version. 3. Install that release into ~/image-queue. If the folder already exists, stop and ask me. Do not overwrite it. 4. Run pnpm install --frozen-lockfile, pnpm build and pnpm build:mcp in that folder. Start with pnpm start and verify http://127.0.0.1:3215 responds. If the port is occupied, identify the process and ask me; do not stop it. 5. Run codex login status. If I am not signed in with ChatGPT, explain the step I must complete myself. Never read authentication files, request credentials in chat, or change my existing login. Do not use an API-key login as a substitute for my ChatGPT plan. diff --git a/src/components/workspace.tsx b/src/components/workspace.tsx index f0b6f8a..844365e 100644 --- a/src/components/workspace.tsx +++ b/src/components/workspace.tsx @@ -957,7 +957,7 @@ export function Workspace({ : unique; }, [selectedModel]); const vectorFormats = orderedFormats.some(value => value === "gif" || value === "svg"); - const formatBlocked = (value: string) => (value === "gif" || value === "svg") && (transparent || refs.length > 0); + const formatBlocked = (value: string) => ((value === "gif" || value === "svg") && transparent) || (value === "svg" && refs.length > 0); useEffect(() => { if (source !== "api" && Number(variants) > 4) setVariants("4"); }, [source, variants]); @@ -977,11 +977,11 @@ export function Workspace({ : outputFormat === "gif" || outputFormat === "svg" ? "Transparent background is available with PNG or WebP output." : transparent && refs.length - ? "Transparent background requires PNG or WebP output. GIF output with reference images is not supported by this application yet. SVG output cannot be combined with reference images." + ? "Transparent background requires PNG or WebP output. SVG output cannot be combined with reference images." : transparent ? "Transparent background requires PNG or WebP output." : refs.length - ? "GIF output with reference images is not supported by this application yet. SVG output cannot be combined with reference images." + ? "SVG output cannot be combined with reference images." : ""; const referencesById = useMemo(() => new Map(data.references.map(reference => [reference.id, reference])), [data.references]); const selectedRefs = refs.flatMap(id => { diff --git a/src/core/job-status.ts b/src/core/job-status.ts index 1cdaacb..552a32d 100644 --- a/src/core/job-status.ts +++ b/src/core/job-status.ts @@ -13,3 +13,11 @@ export const jobStatusLabels: Record = { export function isReserved(job: Pick) { return job.source === "queue" && job.status === "running" && job.claim?.reserved === true; } + +/** + * A finished image, or a generated one that could not be adapted to the + * requested size: that file was saved and blocked only for review. + */ +export function hasSavedResult(job: Pick) { + return job.status === "done" || (job.status === "blocked" && Boolean(job.blobKey)); +} diff --git a/src/core/model-profiles.ts b/src/core/model-profiles.ts index 8846200..040a8a7 100644 --- a/src/core/model-profiles.ts +++ b/src/core/model-profiles.ts @@ -176,8 +176,6 @@ export function assertModelOptions( throw new UserFacingError("Transparent background requires PNG or WebP output."); if (format === "svg" && request.referenceIds?.length) throw new UserFacingError("SVG output cannot be combined with reference images."); - if (format === "gif" && request.referenceIds?.length) - throw new UserFacingError("GIF output with reference images is not supported by this application yet."); if ((request.frameCount !== undefined || request.frameDurationMs !== undefined) && format !== "gif") throw new UserFacingError("Frame count and duration apply only to GIF output."); } diff --git a/src/core/notes.ts b/src/core/notes.ts index 2e3f283..16f4e30 100644 --- a/src/core/notes.ts +++ b/src/core/notes.ts @@ -224,6 +224,12 @@ export async function createCorrection( throw new UserFacingError("Could not verify the original image's transparency. Re-import it before editing."); transparent = actual; } + // A regenerated animation keeps the references the original followed, so + // the character stays the same; references deleted since then are skipped. + const keptReferences = regenerate && !intent?.request + ? (await Promise.all((original.referenceIds ?? []).map(async id => + (await api.store.get("references", id)) ? id : undefined))).filter((id): id is string => Boolean(id)) + : []; const request = intent?.request ?? { projectId: original.projectId, topicId: original.topicId, @@ -249,7 +255,7 @@ export async function createCorrection( quality: original.quality, complexity: original.complexity, outputFormat: original.outputFormat, frameCount: original.frameCount, frameDurationMs: original.frameDurationMs, } : {}), - referenceIds: input.referenceIds, + referenceIds: regenerate ? keptReferences : input.referenceIds, idempotencyKey: input.idempotencyKey, }; if (request.prompt.length > 12000) diff --git a/src/core/service.ts b/src/core/service.ts index 295c04f..ae1eafa 100644 --- a/src/core/service.ts +++ b/src/core/service.ts @@ -140,8 +140,14 @@ export class ImageService { if (sizeProfile) { const resolved = resolveModelSize(sizeProfile, parsed); const native = /^(\d+)x(\d+)$/.exec(String((resolved.parameters as { size?: string }).size ?? "")); - if ((parsed.outputFormat ?? "png") === "gif" && native) + if ((parsed.outputFormat ?? "png") === "gif" && native) { assertGifSheetFits(sizeProfile, { width: Number(native[1]), height: Number(native[2]) }, parsed.frameCount); + // The Worker cannot scale an animated GIF, so it is generated at a size the model renders. + if (resolved.requiresResize && parsed.exactDimensions !== false && configuration("STORAGE_DRIVER") === "cloudflare") + throw new UserFacingError( + `This server cannot resize an animated GIF, and the model renders ${parsed.width}x${parsed.height} as ${native[1]}x${native[2]}. ` + + `Request ${native[1]}x${native[2]}, or pass only aspectRatio. Nothing was sent or billed.`); + } } const profile = applyVerifiedModelProfiles(stored).find(model => model.id === parsed.model); if (profile) assertModelOptions(profile, parsed); diff --git a/src/mcp/apps.ts b/src/mcp/apps.ts index 503d617..48ada88 100644 --- a/src/mcp/apps.ts +++ b/src/mcp/apps.ts @@ -10,8 +10,10 @@ import { galleryViewHtml, galleryViewVersion } from "./views/gallery-html"; import { ResourceTemplate } from "@modelcontextprotocol/server"; import { storage } from "../storage"; import type { Job } from "../core/schema"; +import { hasSavedResult } from "../core/job-status"; import { thumbnail } from "../sources/thumbnail"; import { jobViewHtml, jobViewVersion } from "./views/job-html"; +import { referenceViewHtml, referenceViewVersion } from "./views/reference-html"; import { z } from "zod"; import { idSchema } from "../core/schema"; import { refreshedJob, refreshedJobs, service, dispatch } from "../core/runtime"; @@ -27,6 +29,7 @@ import { export const JOB_VIEW_URI = `ui://image-queue/job-${jobViewVersion}`; export const GALLERY_VIEW_URI = `ui://image-queue/gallery-${galleryViewVersion}`; export const IMAGE_VIEW_URI = `ui://image-queue/image-${imageViewVersion}`; +export const REFERENCE_VIEW_URI = `ui://image-queue/reference-${referenceViewVersion}`; /** Register optional resources only after the host advertises MCP Apps. */ export function configureAppViews(server: McpServer, tools: RegisteredTool[], galleryTool?: RegisteredTool, imageTool?: RegisteredTool, mode: "negotiate" | "always" = "negotiate", panelUrl?: string) { @@ -60,6 +63,35 @@ function installAppViews(server: McpServer, tools: RegisteredTool[], galleryTool _meta: { ui: { csp: { connectDomains: [], resourceDomains: [] } } } }], })); } + // Claude passes only text to a tool, never a file attached to the chat, so + // the user hands the image to this card, which uploads it through the host. + server.registerTool("upload_reference", { + description: "Show a card in which the user chooses, drops or pastes an image from their computer or phone to use as a reference in projectId. Use it whenever the user attached an image to the conversation and wants it as a reference: an attached file cannot be passed to image-queue, so ask the user to pick the same image in the card. Also use it on the hosted server, where add_reference cannot read local files. The card sends the new referenceId back as a message; wait for it, then pass it in referenceIds.", + inputSchema: { projectId: idSchema }, + _meta: { ui: { resourceUri: REFERENCE_VIEW_URI } }, + }, async ({ projectId }) => { + const api = await service(); + if (projectId !== "inbox" && !(await api.store.get("projects", projectId))) throw new UserFacingError("Project does not exist"); + return { content: [{ type: "text" as const, text: JSON.stringify({ projectId, next: "Ask the user to choose the image in the card. The card replies with its referenceId." }) }] }; + }); + server.registerTool("save_uploaded_reference", { + description: "Store one image the user chose in the reference upload card", + inputSchema: z.object({ + projectId: idSchema, + name: z.string().trim().min(1).max(200), + mime: z.enum(["image/png", "image/jpeg", "image/webp"]), + // 20 MB as base64. + data: z.string().min(1).max(28_000_000), + }), + _meta: { ui: { visibility: ["app"] } }, + }, async ({ projectId, name, mime, data }) => { + const reference = await (await service()).addReference(projectId, name, mime, new Uint8Array(Buffer.from(data, "base64"))); + return { content: [{ type: "text" as const, text: JSON.stringify({ id: reference.id, name: reference.name, projectId: reference.projectId, mime: reference.mime }) }] }; + }); + registerAppResource(server, "Upload reference", REFERENCE_VIEW_URI, {}, async () => ({ + contents: [{ uri: REFERENCE_VIEW_URI, mimeType: RESOURCE_MIME_TYPE, text: referenceViewHtml, + _meta: { ui: { csp: { connectDomains: [], resourceDomains: [] } } } }], + })); server.registerTool("add_notes_to_queue", { description: "Create one correction from the image's unsent notes after the user clicks Request next version", inputSchema: z.object({ imageId: idSchema, idempotencyKey: idSchema.max(96), instruction: z.string().trim().max(12000).optional() }), @@ -186,7 +218,7 @@ const extensions: Record = { export async function readImageFile(id: string) { const store = await storage(); const job = await store.get("jobs", id); - if (!job || job.trashedAt || job.status !== "done" || !job.blobKey) throw new UserFacingError("Image is unavailable"); + if (!job || job.trashedAt || !hasSavedResult(job) || !job.blobKey) throw new UserFacingError("Image is unavailable"); const blob = await store.getBlob(job.blobKey); if (!blob) throw new UserFacingError("Image is unavailable"); const mime = extensions[blob.mime] ? blob.mime : "image/png"; @@ -201,7 +233,7 @@ export async function readImageFile(id: string) { export async function readThumbnail(id: string, options: { animated?: boolean } = {}) { const store = await storage(); const job = await store.get("jobs", id); - if (!job || job.trashedAt || job.status !== "done") + if (!job || job.trashedAt || !hasSavedResult(job)) throw new UserFacingError("Image is unavailable"); let blob = job.blobKey ? await store.getBlob(job.blobKey) : undefined; if (!blob && job.source === "queue") { diff --git a/src/mcp/server.ts b/src/mcp/server.ts index 52e9dc6..ab09c48 100644 --- a/src/mcp/server.ts +++ b/src/mcp/server.ts @@ -155,7 +155,7 @@ export function createServer({ appViews = "negotiate", panelUrl }: { appViews?: "request_image", { description: - "Queue one or more images. If source is omitted, use the saved default from get_generation_source; an explicit source overrides it for this request. API calls are billed separately. For the agent queue provide aspectRatio (1:1, 3:2, 2:3, 4:3, 3:4, 16:9, 9:16, 21:9) or exact width and height. API aspect-only requests require a verified size profile; models with a dimensions profile (GPT Image 2, 2.5 and 2.6) render each ratio natively on their pixel grid, and smaller exact sizes such as 256x256 sprites are generated at the smallest allowed size and fitted down. transparent=true needs a model with transparency and PNG or WebP output. quality (low, medium, high, xhigh, max, auto), complexity (low, medium, high; GPT Image 2.6 only) and outputFormat (png, webp, jpeg, gif, svg) are API-only and must be listed for the model by list_models. Omit outputFormat for PNG. GIF accepts frameCount (2–16) and frameDurationMs (20–2000). All GIF frames are rendered as one sheet that must fit the model limits, so 1024x1024 never works for a GIF: with GPT Image 2.6 request width and height of 960x960 or smaller for 2 to 9 frames and 816x816 for 10 to 12 frames; more than 12 frames do not fit. GIF output with reference images is not supported by this application yet. SVG cannot include reference images or frame settings; each SVG job is a separate call. idempotencyKey must be new for every new or changed request (add a random suffix); reuse a key only to repeat exactly the same request. count (1–10) creates that many independent jobs with the same parameters. The first uses idempotencyKey and the rest use idempotencyKey-2 through idempotencyKey-N. Replaying that same key and count returns those jobs and creates nothing. count 1 or omitted returns the single job; a larger count also includes a jobs array. For a Google model that lists resolution levels, pass resolution (512, 1K, 2K or 4K) from that list. Reference inputs must be real PNG, JPEG or WebP files (maximum 20 MB each): import them with add_reference, then pass returned referenceIds. SVG, GIF, PDF, Markdown, URLs and renamed non-image files are not accepted; convert to PNG before importing. A Codex queue job waits for the local runner; if paused, the user must resume it in the dashboard.", + "Queue one or more images. If source is omitted, use the saved default from get_generation_source; an explicit source overrides it for this request. API calls are billed separately. For the agent queue provide aspectRatio (1:1, 3:2, 2:3, 4:3, 3:4, 16:9, 9:16, 21:9) or exact width and height. API aspect-only requests require a verified size profile; models with a dimensions profile (GPT Image 2, 2.5 and 2.6) render each ratio natively on their pixel grid, and smaller exact sizes such as 256x256 sprites are generated at the smallest allowed size and fitted down. transparent=true needs a model with transparency and PNG or WebP output. quality (low, medium, high, xhigh, max, auto), complexity (low, medium, high; GPT Image 2.6 only) and outputFormat (png, webp, jpeg, gif, svg) are API-only and must be listed for the model by list_models. Omit outputFormat for PNG. GIF accepts frameCount (2–16) and frameDurationMs (20–2000). All GIF frames are rendered as one sheet that must fit the model limits, so 1024x1024 never works for a GIF: with GPT Image 2.6 request width and height of 960x960 or smaller for 2 to 9 frames and 816x816 for 10 to 12 frames; more than 12 frames do not fit. A GIF cannot be scaled after generation on the hosted server: for a GIF pass only aspectRatio, or a width and height the model renders natively (multiples of 16 and at least the model's minimum pixels, e.g. 608x1088 for a tall GIF of up to 12 frames; aspectRatio 9:16 alone gives 720x1280, which fits at most 9 frames). GIF output may include reference images; they guide the animation. SVG cannot include reference images or frame settings; each SVG job is a separate call. idempotencyKey must be new for every new or changed request (add a random suffix); reuse a key only to repeat exactly the same request. count (1–10) creates that many independent jobs with the same parameters. The first uses idempotencyKey and the rest use idempotencyKey-2 through idempotencyKey-N. Replaying that same key and count returns those jobs and creates nothing. count 1 or omitted returns the single job; a larger count also includes a jobs array. For a Google model that lists resolution levels, pass resolution (512, 1K, 2K or 4K) from that list. Reference inputs must be real PNG, JPEG or WebP files (maximum 20 MB each): import them with add_reference (a local path on the local server) or upload_reference (an image attached to the chat, or any image on the hosted server), then pass returned referenceIds. SVG, GIF, PDF, Markdown, URLs and renamed non-image files are not accepted; convert to PNG before importing. A Codex queue job waits for the local runner; if paused, the user must resume it in the dashboard.", inputSchema: mcpRequestSchema.shape, }, async (input) => { @@ -209,7 +209,7 @@ export function createServer({ appViews = "negotiate", panelUrl }: { appViews?: server.registerTool( "view_image", { - description: "Show a 640 px preview of one finished image as image content, so the user can see the result in chat, for example in the Claude mobile app. Use after get_job or wait_for_job reports status done.", + description: "Show a 640 px preview of one finished image as image content, so the user can see the result in chat, for example in the Claude mobile app. Use after get_job or wait_for_job reports status done, or status blocked with a saved file whose size could not be adapted.", inputSchema: { id: idSchema }, }, async ({ id }) => { @@ -247,7 +247,7 @@ export function createServer({ appViews = "negotiate", panelUrl }: { appViews?: "request_images", { description: - "Submit image requests without opening an inline view. Omitting source uses the saved default; an explicit source overrides it per request. API calls are billed separately. Each queue request accepts aspectRatio or exact width and height. API requests also accept transparent, quality, complexity and outputFormat within the model's capabilities from list_models. GIF accepts frameCount and frameDurationMs. GIF output with reference images is not supported by this application yet. SVG cannot include references or frame settings. Each request may set count (1–10) and expands into that many independent jobs. The 20-image cap counts the expanded jobs. All size and option inputs are validated before the first submission. References must be imported PNG, JPEG or WebP images (up to 20 MB each), supplied by referenceIds; no SVG, PDF, Markdown or URLs.", + "Submit image requests without opening an inline view. Omitting source uses the saved default; an explicit source overrides it per request. API calls are billed separately. Each queue request accepts aspectRatio or exact width and height. API requests also accept transparent, quality, complexity and outputFormat within the model's capabilities from list_models. GIF accepts frameCount and frameDurationMs. GIF output may include reference images; they guide the animation. SVG cannot include references or frame settings. Each request may set count (1–10) and expands into that many independent jobs. The 20-image cap counts the expanded jobs. All size and option inputs are validated before the first submission. References must be imported PNG, JPEG or WebP images (up to 20 MB each), supplied by referenceIds; no SVG, PDF, Markdown or URLs.", inputSchema: { requests: z.array(mcpRequestSchema).min(1).max(20) }, }, async ({ requests }) => { @@ -310,7 +310,7 @@ export function createServer({ appViews = "negotiate", panelUrl }: { appViews?: "add_reference", { description: - "Import a real PNG, JPEG (.jpg/.jpeg) or WebP file, maximum 20 MB, under configured REFERENCE_ROOTS. Returns a reference ID for request_image/referenceIds. SVG, GIF, PDF, Markdown/text and URLs are not image references. Convert unsupported formats to PNG first; renaming an extension is not conversion.", + "Import a real PNG, JPEG (.jpg/.jpeg) or WebP file from a local path, maximum 20 MB, under configured REFERENCE_ROOTS. Works only on the local server; for an image attached to the chat or on the hosted server call upload_reference instead. Returns a reference ID for request_image/referenceIds. SVG, GIF, PDF, Markdown/text and URLs are not image references. Convert unsupported formats to PNG first; renaming an extension is not conversion.", inputSchema: { projectId: idSchema, filePath: z.string().max(4096).describe("Local path to a PNG, JPEG or WebP image, up to 20 MB; must be under an allowed reference directory") }, }, async ({ projectId, filePath }) => { diff --git a/src/mcp/tool-annotations.ts b/src/mcp/tool-annotations.ts index 0b2c82b..258f49c 100644 --- a/src/mcp/tool-annotations.ts +++ b/src/mcp/tool-annotations.ts @@ -8,7 +8,7 @@ import type { ToolAnnotations } from "@modelcontextprotocol/server"; const READ_ONLY = new Set([ "get_generation_source", "get_queue_processing", "list_projects", "list_jobs", "show_image", "show_images", "view_image", "get_job", "show_job", "wait_for_job", "list_models", "list_topics", "list_untagged", "list_notes", - "list_thumbnails", "get_image_details", "get_job_state", "read_thumbnail", "read_image_file", + "list_thumbnails", "get_image_details", "get_job_state", "read_thumbnail", "read_image_file", "upload_reference", ]); /** Tools that cancel or end work, so hosts keep asking before they run. */ diff --git a/src/mcp/views/compact-app.ts b/src/mcp/views/compact-app.ts index d69e139..a066cc3 100644 --- a/src/mcp/views/compact-app.ts +++ b/src/mcp/views/compact-app.ts @@ -102,6 +102,9 @@ export class CompactApp { openLink(params: Parameters[0]) { return this.request>>("ui/open-link", params); } + sendMessage(params: Parameters[0]) { + return this.request>>("ui/message", params); + } updateModelContext(params: Parameters[0]) { return this.request>>("ui/update-model-context", params); } diff --git a/src/mcp/views/gallery-html.ts b/src/mcp/views/gallery-html.ts index bf9f475..15bf437 100644 --- a/src/mcp/views/gallery-html.ts +++ b/src/mcp/views/gallery-html.ts @@ -1,3 +1,3 @@ // Generated by scripts/build-mcp-views.ts -export const galleryViewHtml = "

      Loading images…

      "; -export const galleryViewVersion = "ef29184889"; +export const galleryViewHtml = "

      Loading images…

      "; +export const galleryViewVersion = "26e45e3f72"; diff --git a/src/mcp/views/image-html.ts b/src/mcp/views/image-html.ts index 88dbddd..90a7af5 100644 --- a/src/mcp/views/image-html.ts +++ b/src/mcp/views/image-html.ts @@ -1,3 +1,3 @@ // Generated by scripts/build-mcp-views.ts -export const imageViewHtml = "

      Loading image…

      Describe a change and save it. If it is about one place, tap that place on the image first. Request next version then generates a new image with your saved changes.

      Saved changes

        "; -export const imageViewVersion = "364ae1229b"; +export const imageViewHtml = "

        Loading image…

        Describe a change and save it. If it is about one place, tap that place on the image first. Request next version then generates a new image with your saved changes.

        Saved changes

          "; +export const imageViewVersion = "dfee83ab0e"; diff --git a/src/mcp/views/job-html.ts b/src/mcp/views/job-html.ts index 2802cfe..588648f 100644 --- a/src/mcp/views/job-html.ts +++ b/src/mcp/views/job-html.ts @@ -1,3 +1,3 @@ // Generated by scripts/build-mcp-views.ts -export const jobViewHtml = "

          Image request

          Connecting to image-queue…

          "; -export const jobViewVersion = "bfdc8012bf"; +export const jobViewHtml = "

          Image request

          Connecting to image-queue…

          "; +export const jobViewVersion = "7589e6d9e4"; diff --git a/src/mcp/views/job.ts b/src/mcp/views/job.ts index 92e9463..8bfd5a2 100644 --- a/src/mcp/views/job.ts +++ b/src/mcp/views/job.ts @@ -1,5 +1,5 @@ import { workersOfflineMessage } from "../../core/workspace-state"; -import { isReserved, jobStatusLabels } from "../../core/job-status"; +import { hasSavedResult, isReserved, jobStatusLabels } from "../../core/job-status"; import type { Job } from "../../core/schema"; import { CompactApp, @@ -191,7 +191,7 @@ function render(result: { content?: unknown[] }) { return; } if (id !== job.id) started = Date.now(); - if (id !== job.id || job.trashedAt || job.status !== "done") { + if (id !== job.id || job.trashedAt || !hasSavedResult(job)) { previewId = ""; if (play) play.hidden = true; const element = document.querySelector("#preview"); @@ -222,7 +222,7 @@ function render(result: { content?: unknown[] }) { id = job.id; document.body.dataset.status = job.trashedAt ? "trashed" : job.status; if (openApp) openApp.hidden = !document.body.dataset.dashboard; - if (download) download.hidden = job.status !== "done" || Boolean(job.trashedAt); + if (download) download.hidden = !hasSavedResult(job) || Boolean(job.trashedAt); const reserved = isReserved(job); const statusLabel = reserved ? "Reserved" : jobStatusLabels[job.status as Job["status"]]; const label = job.source === "queue" && job.status === "running" && Number.isSafeInteger(job.workerSlot) && job.workerSlot > 0 @@ -245,7 +245,7 @@ function render(result: { content?: unknown[] }) { if (jobChanged || pathChanged) copyPath.textContent = "Copy path"; } finished = !["queued", "running"].includes(job.status); - if (!job.trashedAt && job.status === "done" && previewId !== id) { + if (!job.trashedAt && hasSavedResult(job) && previewId !== id) { previewId = id; const requestedId = id; const isGif = job.outputFormat === "gif"; diff --git a/src/mcp/views/reference-file.ts b/src/mcp/views/reference-file.ts new file mode 100644 index 0000000..30d739d --- /dev/null +++ b/src/mcp/views/reference-file.ts @@ -0,0 +1,68 @@ +/** A reference image ready for save_uploaded_reference: a PNG, JPEG or WebP file as base64. */ +export type PreparedReference = { name: string; mime: string; data: string }; + +const accepted = new Set(["image/png", "image/jpeg", "image/webp"]); +/** + * Files up to this size go to the server unchanged. Larger photos are scaled + * down first, because the host relays every byte of a view's tool call. + */ +export const MAX_UNCHANGED_BYTES = 3 * 1024 * 1024; +/** Longest side of a scaled-down reference; the image models work below it. */ +export const MAX_SCALED_SIDE = 2048; + +/** Whether a file can be sent as it is, or must be decoded and re-encoded first. */ +export function referenceUploadPlan(file: { type: string; size: number }) { + return accepted.has(file.type) && file.size <= MAX_UNCHANGED_BYTES ? "as-is" : "re-encode"; +} + +/** The size a scaled-down copy gets, keeping the aspect ratio. */ +export function scaledSize(width: number, height: number, maxSide = MAX_SCALED_SIDE) { + const scale = Math.min(1, maxSide / Math.max(width, height)); + return { width: Math.max(1, Math.round(width * scale)), height: Math.max(1, Math.round(height * scale)) }; +} + +export function renamed(name: string, mime: string) { + const extension = mime === "image/png" ? "png" : mime === "image/webp" ? "webp" : "jpg"; + const base = name.replace(/\.[^./]+$/, "") || "reference"; + return `${base}.${extension}`; +} + +function base64(bytes: Uint8Array) { + let binary = ""; + for (let offset = 0; offset < bytes.length; offset += 0x8000) + binary += String.fromCharCode(...bytes.subarray(offset, offset + 0x8000)); + return btoa(binary); +} + +async function encode(canvas: HTMLCanvasElement, mime: string, quality?: number) { + const blob = await new Promise(resolve => canvas.toBlob(resolve, mime, quality)); + if (!blob) throw new Error("This image could not be converted."); + return blob; +} + +/** Read a picked or dropped file, scaling photos down and converting HEIC or other formats to JPEG. */ +export async function prepareReferenceFile(file: File): Promise { + if (!file.type.startsWith("image/") || file.type === "image/svg+xml" || file.type === "image/gif") + throw new Error(`${file.name} is not a photo or picture. Use a PNG, JPEG or WebP image.`); + if (referenceUploadPlan(file) === "as-is") + return { name: file.name, mime: file.type, data: base64(new Uint8Array(await file.arrayBuffer())) }; + let bitmap: ImageBitmap; + try { + bitmap = await createImageBitmap(file); + } catch { + throw new Error(`${file.name} cannot be read here. Convert it to PNG or JPEG first.`); + } + const canvas = document.createElement("canvas"); + Object.assign(canvas, scaledSize(bitmap.width, bitmap.height)); + canvas.getContext("2d")!.drawImage(bitmap, 0, 0, canvas.width, canvas.height); + bitmap.close(); + // PNG keeps transparency; a photo that is still too large becomes JPEG. + let mime = file.type === "image/png" ? "image/png" : "image/jpeg"; + let blob = await encode(canvas, mime, mime === "image/jpeg" ? 0.9 : undefined); + if (blob.size > MAX_UNCHANGED_BYTES && mime === "image/png") { + mime = "image/jpeg"; + blob = await encode(canvas, mime, 0.9); + } + if (blob.size > MAX_UNCHANGED_BYTES) blob = await encode(canvas, "image/jpeg", 0.75); + return { name: renamed(file.name, mime), mime, data: base64(new Uint8Array(await blob.arrayBuffer())) }; +} diff --git a/src/mcp/views/reference-html.ts b/src/mcp/views/reference-html.ts new file mode 100644 index 0000000..821e52a --- /dev/null +++ b/src/mcp/views/reference-html.ts @@ -0,0 +1,3 @@ +// Generated by scripts/build-mcp-views.ts +export const referenceViewHtml = "

          Connecting to image-queue…

          Claude cannot pass a file attached to the chat to image-queue, so choose the same image here. PNG, JPEG or WebP; large photos are scaled down to 2048 px.

          or drop or paste it here

            "; +export const referenceViewVersion = "666c4e4ab2"; diff --git a/src/mcp/views/reference.ts b/src/mcp/views/reference.ts new file mode 100644 index 0000000..a309204 --- /dev/null +++ b/src/mcp/views/reference.ts @@ -0,0 +1,116 @@ +import { CompactApp, applyDocumentTheme, applyHostFonts, applyHostStyleVariables } from "./compact-app"; +import { prepareReferenceFile, type PreparedReference } from "./reference-file"; + +const app = new CompactApp({ name: "image-queue-reference", version: "1.0.0" }); +const status = document.querySelector("[role=status]")!; +const drop = document.querySelector("#drop")!; +const input = document.querySelector("#file")!; +const choose = document.querySelector("#choose")!; +const list = document.querySelector("#uploaded")!; +let projectId = ""; +let busy = false; +let disposed = false; + +type Uploaded = { id: string; name: string }; + +function read(params: { structuredContent?: unknown; content?: { type: string; text?: string }[] }) { + const text = params.content?.find(item => item.type === "text")?.text; + try { + return (params.structuredContent ?? (text ? JSON.parse(text) : undefined)) as { projectId?: string; error?: string } | undefined; + } catch { + return undefined; + } +} + +function setProject(value: unknown) { + if (typeof value === "string" && value) { + projectId = value; + if (!busy) status.textContent = "Choose or drop the image to use as a reference."; + choose.disabled = false; + } +} + +app.ontoolinput = params => setProject((params.arguments as { projectId?: unknown } | undefined)?.projectId); +app.ontoolresult = params => { + const result = read(params as never); + if (result?.error) status.textContent = result.error; + setProject(result?.projectId); +}; + +async function upload(files: File[]) { + if (busy || disposed || !files.length) return; + if (!projectId) { status.textContent = "Waiting for the project from Claude…"; return; } + busy = true; + choose.disabled = true; + const uploaded: Uploaded[] = []; + try { + for (const [index, file] of files.slice(0, 8).entries()) { + status.textContent = files.length > 1 ? `Uploading ${index + 1} of ${Math.min(files.length, 8)}…` : "Uploading…"; + let prepared: PreparedReference; + try { + prepared = await prepareReferenceFile(file); + } catch (error) { + status.textContent = error instanceof Error ? error.message : "This file cannot be used as a reference."; + continue; + } + const result = await app.callServerTool({ name: "save_uploaded_reference", arguments: { projectId, ...prepared } }); + const text = result.content?.find(item => item.type === "text"); + const body = text && "text" in text ? JSON.parse(text.text) as { id?: string; name?: string; error?: string } : undefined; + if (result.isError || !body?.id) { + status.textContent = body?.error ?? "Upload failed."; + continue; + } + uploaded.push({ id: body.id, name: body.name ?? prepared.name }); + const item = document.createElement("li"); + item.textContent = `${body.name ?? prepared.name}: ${body.id}`; + list.append(item); + } + if (!uploaded.length) return; + const summary = `Uploaded ${uploaded.length === 1 ? "a reference image" : `${uploaded.length} reference images`} to project ${projectId}: ` + + uploaded.map(item => `${item.name} (referenceId ${item.id})`).join(", ") + ". Use them as referenceIds and continue."; + let sent = false; + try { + const reply = await app.sendMessage({ role: "user", content: [{ type: "text", text: summary }] }); + sent = !reply?.isError; + } catch { + sent = false; + } + if (!sent) { + try { await app.updateModelContext({ content: [{ type: "text", text: summary }] }); } catch { /* the ID stays on screen */ } + } + status.textContent = sent ? "Uploaded. Claude continues with the reference." : "Uploaded. Send any message so Claude continues with the reference."; + } catch (error) { + status.textContent = error instanceof Error ? `Upload failed: ${error.message}` : "Upload failed."; + } finally { + busy = false; + choose.disabled = !projectId; + input.value = ""; + } +} + +choose.addEventListener("click", () => input.click()); +input.addEventListener("change", () => void upload([...input.files ?? []])); +drop.addEventListener("dragover", event => { event.preventDefault(); drop.dataset.over = ""; }); +drop.addEventListener("dragleave", () => { delete drop.dataset.over; }); +drop.addEventListener("drop", event => { + event.preventDefault(); + delete drop.dataset.over; + void upload([...event.dataTransfer?.files ?? []]); +}); +document.addEventListener("paste", event => { + const files = [...event.clipboardData?.files ?? []]; + if (files.length) { event.preventDefault(); void upload(files); } +}); + +app.onhostcontextchanged = context => { + if (context.theme) applyDocumentTheme(context.theme); + if (context.styles?.variables) applyHostStyleVariables(context.styles.variables); + if (context.styles?.css?.fonts) applyHostFonts(context.styles.css.fonts); +}; +app.onteardown = async () => { disposed = true; return {}; }; +app.connect().then(() => { + const context = app.getHostContext(); + if (context?.theme) applyDocumentTheme(context.theme); + if (context?.styles?.variables) applyHostStyleVariables(context.styles.variables); + if (context?.styles?.css?.fonts) applyHostFonts(context.styles.css.fonts); +}).catch(() => { if (!disposed) status.textContent = "Unable to connect to the host."; }); diff --git a/src/sources/providers.ts b/src/sources/providers.ts index 11133ed..b07b304 100644 --- a/src/sources/providers.ts +++ b/src/sources/providers.ts @@ -137,17 +137,21 @@ export async function generate( const providerOptions: Parameters[0]["providerOptions"] = job.resolution && job.provider === "google" ? { google: { imageConfig: { imageSize: job.resolution } } } : Object.keys(openaiOptions).length ? { openai: openaiOptions } : undefined; - const result = await generateImage({ - model, - prompt: references.length - ? { text: job.prompt, images: references } - : job.prompt, - size: sizeParameters.size, - aspectRatio: sizeParameters.aspectRatio, - maxRetries: 0, - abortSignal: AbortSignal.timeout(240000), - providerOptions, - }); + // The SDK's edit request drops GIF output and frame settings, so a GIF that + // follows reference images goes to the edits endpoint directly. + const result = rasterFormat === "gif" && references.length + ? await editGif(job, key, sizeParameters.size, references) + : await generateImage({ + model, + prompt: references.length + ? { text: job.prompt, images: references } + : job.prompt, + size: sizeParameters.size, + aspectRatio: sizeParameters.aspectRatio, + maxRetries: 0, + abortSignal: AbortSignal.timeout(240000), + providerOptions, + }); const generatedDimensions = imageSize(result.image.uint8Array); let bytes = result.image.uint8Array; let mime = mimeOf(bytes); @@ -201,29 +205,37 @@ function mimeOf(bytes: Uint8Array) { throw new UserFacingError("The provider returned an unreadable image. Try again later."); } -/** SVG is rejected by the installed SDK schema, and the edits endpoint cannot return it. */ -async function generateSvg(job: Job, key: string, size: `${number}x${number}` | undefined, referenceCount: number) { - if (job.provider !== "openai") - throw new UserFacingError("SVG output requires an OpenAI image model"); - if (referenceCount) - throw new UserFacingError("SVG output cannot be combined with reference images."); - if (!size) throw new UserFacingError("SVG output requires a pixel size."); - const [width, height] = size.split("x").map(Number); - if (!width || !height) throw new UserFacingError("SVG output requires a pixel size."); - const body = { - model: job.model, - prompt: job.prompt, - n: 1, - size, - output_format: "svg", - ...(job.quality ? { quality: job.quality } : {}), - ...(job.complexity ? { complexity: job.complexity } : {}), - ...(job.transparent ? { background: "transparent" } : {}), - }; - const response = await fetch("https://api.openai.com/v1/images/generations", { +/** An animated GIF guided by reference images, from POST /v1/images/edits. */ +async function editGif(job: Job, key: string, size: `${number}x${number}` | undefined, references: Uint8Array[]) { + if (!size) throw new UserFacingError("GIF output requires a pixel size."); + const form = new FormData(); + form.append("model", job.model); + form.append("prompt", job.prompt); + form.append("n", "1"); + form.append("size", size); + form.append("output_format", "gif"); + if (job.frameCount !== undefined) form.append("frame_count", String(job.frameCount)); + if (job.frameDurationMs !== undefined) form.append("frame_duration_ms", String(job.frameDurationMs)); + if (job.quality) form.append("quality", job.quality); + if (job.complexity) form.append("complexity", job.complexity); + const field = references.length === 1 ? "image" : "image[]"; + references.forEach((bytes, index) => { + const mime = mimeOf(bytes); + const extension = mime === outputMime.jpeg ? "jpg" : mime === outputMime.webp ? "webp" : "png"; + form.append(field, new Blob([bytes as Uint8Array], { type: mime }), `reference-${index + 1}.${extension}`); + }); + const payload = await postImageRequest("https://api.openai.com/v1/images/edits", key, form); + return { image: { uint8Array: payload.bytes }, usage: payload.usage }; +} + +/** Send one image request outside the SDK and return the first image's bytes and token usage. */ +async function postImageRequest(url: string, key: string, body: FormData | object) { + const response = await fetch(url, { method: "POST", - headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json" }, - body: JSON.stringify(body), + headers: body instanceof FormData + ? { Authorization: `Bearer ${key}` } + : { Authorization: `Bearer ${key}`, "Content-Type": "application/json" }, + body: body instanceof FormData ? body : JSON.stringify(body), signal: AbortSignal.timeout(240000), }).catch(() => { throw new UserFacingError("Could not reach the provider. Check your connection and try again."); @@ -243,6 +255,11 @@ async function generateSvg(job: Job, key: string, size: `${number}x${number}` | }); const parsed = z.object({ data: z.array(z.object({ b64_json: z.string().min(1) })).min(1), + usage: z.object({ + input_tokens: z.number().optional(), + output_tokens: z.number().optional(), + total_tokens: z.number().optional(), + }).optional(), }).safeParse(payload); if (!parsed.success) throw new UserFacingError("The provider returned an unreadable image. Try again later."); @@ -253,6 +270,38 @@ async function generateSvg(job: Job, key: string, size: `${number}x${number}` | } catch { throw new UserFacingError("The provider returned an unreadable image. Try again later."); } + if (!bytes.length) throw new UserFacingError("The provider returned an unreadable image. Try again later."); + const usage = parsed.data.usage; + return { + bytes, + usage: { + inputTokens: usage?.input_tokens, + outputTokens: usage?.output_tokens, + totalTokens: usage?.total_tokens, + }, + }; +} + +/** SVG is rejected by the installed SDK schema, and the edits endpoint cannot return it. */ +async function generateSvg(job: Job, key: string, size: `${number}x${number}` | undefined, referenceCount: number) { + if (job.provider !== "openai") + throw new UserFacingError("SVG output requires an OpenAI image model"); + if (referenceCount) + throw new UserFacingError("SVG output cannot be combined with reference images."); + if (!size) throw new UserFacingError("SVG output requires a pixel size."); + const [width, height] = size.split("x").map(Number); + if (!width || !height) throw new UserFacingError("SVG output requires a pixel size."); + const body = { + model: job.model, + prompt: job.prompt, + n: 1, + size, + output_format: "svg", + ...(job.quality ? { quality: job.quality } : {}), + ...(job.complexity ? { complexity: job.complexity } : {}), + ...(job.transparent ? { background: "transparent" } : {}), + }; + const { bytes } = await postImageRequest("https://api.openai.com/v1/images/generations", key, body); if (!bytes.length || !svgDocument(bytes)) throw new UserFacingError("The provider returned an unreadable image. Try again later."); return { diff --git a/src/storage/local-references.ts b/src/storage/local-references.ts index dd3ceb5..d96fae9 100644 --- a/src/storage/local-references.ts +++ b/src/storage/local-references.ts @@ -9,7 +9,7 @@ export async function addLocalReference( filePath: string, ) { if (configuration("STORAGE_DRIVER") === "cloudflare") - throw new UserFacingError("Local files require the local MCP server"); + throw new UserFacingError("The hosted image-queue cannot read local files or files attached to the chat. Call upload_reference so the user can choose the image in a card."); const { pathSettings } = await import("../core/paths"); const roots = (await pathSettings(api.store)).referenceDirectories; const file = await realpath(filePath); diff --git a/tests/core.test.ts b/tests/core.test.ts index aa6e45a..2db05bd 100644 --- a/tests/core.test.ts +++ b/tests/core.test.ts @@ -67,7 +67,7 @@ describe("image requests", () => { await expect(service.create({ ...input, frameDurationMs: 200 })).rejects.toThrow("Output format and frame settings apply only to API generation"); expect(await service.jobs()).toEqual([]); }); - it("refuses GIF output with reference images before storing a job", async () => { + it("accepts GIF output with reference images", async () => { const project = await service.createProject("GIF"); await service.store.put("models", "openai", [{ id: "gpt-image-2.6-sunburst", provider: "openai", name: "Sunburst", @@ -78,8 +78,7 @@ describe("image requests", () => { await expect(service.create({ ...request(project.id), source: "api", model: "gpt-image-2.6-sunburst", transparent: false, outputFormat: "gif", referenceIds: [reference.id], - })).rejects.toThrow("GIF output with reference images is not supported by this application yet."); - expect(await service.jobs()).toEqual([]); + })).resolves.toMatchObject({ outputFormat: "gif", referenceIds: [reference.id] }); }); it("requires a project and model for API requests", async () => { await expect(service.create(request("missing"))).rejects.toThrow("Project"); diff --git a/tests/http-secret-boundary.test.ts b/tests/http-secret-boundary.test.ts index 85dbbd5..8e3512e 100644 --- a/tests/http-secret-boundary.test.ts +++ b/tests/http-secret-boundary.test.ts @@ -73,6 +73,8 @@ it("keeps a stored provider credential out of every HTTP surface and its logs", ["get_generation_source", {}], ["set_generation_source", { source: "queue" }], ["list_thumbnails", {}], ["get_image_details", { id: "missing" }], ["get_job_state", { id: "missing" }], ["read_thumbnail", { id: "missing" }], ["read_image_file", { id: "missing" }], + ["upload_reference", { projectId: "missing" }], + ["save_uploaded_reference", { projectId: "missing", name: "audit.png", mime: "image/png", data: "AA==" }], ["add_notes_to_queue", { imageId: "missing", idempotencyKey: "audit-notes" }], ["list_models", {}], ["refresh_models", {}], ["list_projects", {}], ["list_jobs", {}], ["create_project", { name: "MCP audit project" }], diff --git a/tests/mcp-http-session.test.ts b/tests/mcp-http-session.test.ts index 90feb81..8df340a 100644 --- a/tests/mcp-http-session.test.ts +++ b/tests/mcp-http-session.test.ts @@ -1,4 +1,4 @@ -import { GALLERY_VIEW_URI, IMAGE_VIEW_URI, JOB_VIEW_URI } from "../src/mcp/apps"; +import { GALLERY_VIEW_URI, IMAGE_VIEW_URI, JOB_VIEW_URI, REFERENCE_VIEW_URI } from "../src/mcp/apps"; import { expect, it, vi } from "vitest"; import { DELETE, POST } from "../src/app/api/mcp/route"; import { syntheticAccess } from "./access-fixture"; @@ -32,7 +32,7 @@ it("preserves negotiated MCP Apps resources across authenticated HTTP requests", expect((await send({ method: "notifications/initialized" }, session!)).status).toBe(202); const resources = await send({ id: 2, method: "resources/list" }, session!); expect((await resources.json()).result.resources.map((resource: { uri: string }) => resource.uri).sort()) - .toEqual([GALLERY_VIEW_URI, IMAGE_VIEW_URI, JOB_VIEW_URI]); + .toEqual([GALLERY_VIEW_URI, IMAGE_VIEW_URI, JOB_VIEW_URI, REFERENCE_VIEW_URI].sort()); const unauthorized = await POST(new Request(url, { method: "POST", headers: { "mcp-session-id": session! }, })); diff --git a/tests/mcp-reference-upload.test.ts b/tests/mcp-reference-upload.test.ts new file mode 100644 index 0000000..136587f --- /dev/null +++ b/tests/mcp-reference-upload.test.ts @@ -0,0 +1,115 @@ +import { REFERENCE_VIEW_URI } from "../src/mcp/apps"; +import { mkdtemp, rm } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { Client } from "@modelcontextprotocol/client"; +import { InMemoryTransport } from "@modelcontextprotocol/server"; +import { afterEach, beforeEach, expect, it } from "vitest"; +import { createServer } from "../src/mcp/server"; +import { png } from "./fixtures"; +import { referenceUploadPlan, renamed, scaledSize } from "../src/mcp/views/reference-file"; + +let root: string; +beforeEach(async () => { + root = await mkdtemp(path.join(os.tmpdir(), "mcp-reference-upload-")); + process.env.STORAGE_DIR = path.join(root, "store"); + process.env.CODEX_QUEUE_DIR = path.join(root, "queue"); +}); +afterEach(async () => { + await rm(root, { recursive: true, force: true }); + delete process.env.STORAGE_DIR; + delete process.env.CODEX_QUEUE_DIR; + delete process.env.STORAGE_DRIVER; +}); + +async function connected() { + const server = createServer({ appViews: "always" }); + const client = new Client({ name: "test", version: "1" }); + const [a, b] = InMemoryTransport.createLinkedPair(); + await server.connect(a); + await client.connect(b); + return { client, close: async () => { await client.close(); await server.close(); } }; +} +const text = (result: unknown) => JSON.parse((result as { content: { text: string }[] }).content[0].text); + +it("offers an upload card for images attached to the chat and keeps the storing tool for the card only", async () => { + const { client, close } = await connected(); + const tools = Object.fromEntries((await client.listTools()).tools.map(tool => [tool.name, tool])); + const resources = (await client.listResources()).resources.map(resource => resource.uri); + await close(); + expect(tools.upload_reference?._meta).toMatchObject({ ui: { resourceUri: REFERENCE_VIEW_URI } }); + expect(tools.upload_reference?.annotations).toMatchObject({ readOnlyHint: true }); + expect(tools.upload_reference?.description).toContain("attached"); + expect(tools.save_uploaded_reference?._meta).toMatchObject({ ui: { visibility: ["app"] } }); + expect(resources).toContain(REFERENCE_VIEW_URI); +}); + +it("stores an image the card sends and returns a reference ID that request tools accept", async () => { + const { client, close } = await connected(); + try { + expect(text(await client.callTool({ name: "upload_reference", arguments: { projectId: "inbox" } }))).toMatchObject({ projectId: "inbox" }); + const saved = text(await client.callTool({ name: "save_uploaded_reference", arguments: { + projectId: "inbox", name: "cat.png", mime: "image/png", data: Buffer.from(png).toString("base64"), + } })); + expect(saved).toMatchObject({ name: "cat.png", projectId: "inbox", mime: "image/png" }); + expect(saved.id).toMatch(/^[0-9a-f-]{36}$/); + const rejected = await client.callTool({ name: "save_uploaded_reference", arguments: { + projectId: "inbox", name: "fake.png", mime: "image/png", data: Buffer.from("not an image").toString("base64"), + } }); + expect(rejected.isError).toBe(true); + } finally { + await close(); + } +}); + +it("tells Claude on the hosted server to use the upload card instead of a local path", async () => { + process.env.STORAGE_DRIVER = "cloudflare"; + const { addLocalReference } = await import("../src/storage/local-references"); + await expect(addLocalReference({} as never, "inbox", "/tmp/a.png")).rejects.toThrow("upload_reference"); +}); + +it("sends small PNG, JPEG and WebP files unchanged and re-encodes large or other photos", () => { + expect(referenceUploadPlan({ type: "image/jpeg", size: 1_000_000 })).toBe("as-is"); + expect(referenceUploadPlan({ type: "image/png", size: 5_000_000 })).toBe("re-encode"); + expect(referenceUploadPlan({ type: "image/heic", size: 900_000 })).toBe("re-encode"); + expect(scaledSize(4032, 3024)).toEqual({ width: 2048, height: 1536 }); + expect(scaledSize(800, 600)).toEqual({ width: 800, height: 600 }); + expect(renamed("IMG_0001.HEIC", "image/jpeg")).toBe("IMG_0001.jpg"); +}); + +it("refuses a hosted GIF that would need resizing, naming the size the model renders, before anything is billed", async () => { + const { ImageService } = await import("../src/core/service"); + const { MemoryStorage } = await import("../src/storage/memory"); + const store = new MemoryStorage(); + const api = new ImageService(store); + const project = await api.createProject("GIF"); + await store.put("models", "openai", [{ + id: "gpt-image-2.6-sunburst", provider: "openai", name: "Sunburst", references: true, transparency: true, + sizeProfile: { mode: "dimensions", minSide: 16, maxSide: 3840, multiple: 16, minPixels: 655360, maxPixels: 8294400, minRatio: 1 / 3, maxRatio: 3 }, + outputFormats: ["png", "gif"], + }]); + const gif = { projectId: project.id, prompt: "A cat hides under a blanket", source: "api" as const, provider: "openai" as const, + model: "gpt-image-2.6-sunburst", transparent: false, outputFormat: "gif" as const, frameCount: 12, referenceIds: [] }; + process.env.STORAGE_DRIVER = "cloudflare"; + await expect(api.create({ ...gif, width: 448, height: 800, idempotencyKey: "small-gif" })) + .rejects.toThrow("Request 608x1088, or pass only aspectRatio. Nothing was sent or billed."); + await expect(api.create({ ...gif, width: 608, height: 1088, idempotencyKey: "native-gif" })).resolves.toMatchObject({ width: 608, height: 1088 }); + delete process.env.STORAGE_DRIVER; + await expect(api.create({ ...gif, width: 448, height: 800, idempotencyKey: "local-gif" })).resolves.toMatchObject({ width: 448, height: 800 }); +}); + +it("shows and downloads a generated file that was saved but blocked because its size could not be adapted", async () => { + const { readImageFile, readThumbnail } = await import("../src/mcp/apps"); + const { storage } = await import("../src/storage"); + const store = await storage(); + const sharp = (await import("sharp")).default; + const image = new Uint8Array(await sharp({ create: { width: 256, height: 256, channels: 3, background: "white" } }).png().toBuffer()); + await store.putBlob("results/blocked", image, "image/png"); + await store.put("jobs", "IMG-blocked", { id: "IMG-blocked", projectId: "inbox", prompt: "p", source: "api", status: "blocked", + error: "The generated image was saved. It could not be fitted.", blobKey: "results/blocked", width: 256, height: 256, transparent: false, referenceIds: [] }); + await store.put("jobs", "IMG-waiting", { id: "IMG-waiting", projectId: "inbox", prompt: "p", source: "queue", status: "blocked", + width: 256, height: 256, transparent: false, referenceIds: [] }); + expect((await readImageFile("IMG-blocked")).mime).toBe("image/png"); + expect((await readThumbnail("IMG-blocked")).bytes.length).toBeGreaterThan(0); + await expect(readThumbnail("IMG-waiting")).rejects.toThrow("Image is unavailable"); +}); diff --git a/tests/mcp.test.ts b/tests/mcp.test.ts index 72c7f9a..5198576 100644 --- a/tests/mcp.test.ts +++ b/tests/mcp.test.ts @@ -942,8 +942,6 @@ it("rejects an output format the source or model cannot use before creating any const reference = await api.addReference(project.id, "ref.png", "image/png", png); await expect(call("request_image", { ...base, outputFormat: "svg", referenceIds: [reference.id], idempotencyKey: "svg-ref" })) .rejects.toThrow("cannot be combined with reference images"); - await expect(call("request_image", { ...base, outputFormat: "gif", referenceIds: [reference.id], idempotencyKey: "gif-ref" })) - .rejects.toThrow("GIF output with reference images is not supported by this application yet."); await expect(call("request_image", { ...base, outputFormat: "svg", frameCount: 4, idempotencyKey: "svg-frames" })) .rejects.toThrow("only to GIF"); await expect(call("request_image", { ...base, outputFormat: "png", frameDurationMs: 200, idempotencyKey: "png-frames" })) diff --git a/tests/model-profiles.test.ts b/tests/model-profiles.test.ts index 0d7b602..6dd77d7 100644 --- a/tests/model-profiles.test.ts +++ b/tests/model-profiles.test.ts @@ -108,7 +108,7 @@ it("refuses an output format, transparency pairing, SVG combination or frame set expect(() => assertModelOptions(vector, { transparent: true, outputFormat: "webp" })).not.toThrow(); expect(() => assertModelOptions(vector, { transparent: true })).not.toThrow(); expect(() => assertModelOptions(vector, { outputFormat: "svg", referenceIds: ["ref-1"] })).toThrow("cannot be combined with reference images"); - expect(() => assertModelOptions(vector, { outputFormat: "gif", referenceIds: ["ref-1"] })).toThrow("GIF output with reference images is not supported by this application yet."); + expect(() => assertModelOptions(vector, { outputFormat: "gif", referenceIds: ["ref-1"] })).not.toThrow(); expect(() => assertModelOptions(vector, { outputFormat: "gif", frameCount: 4 })).not.toThrow(); expect(() => assertModelOptions(vector, { outputFormat: "svg", frameCount: 4 })).toThrow("only to GIF"); expect(() => assertModelOptions(vector, { outputFormat: "png", frameDurationMs: 200 })).toThrow("only to GIF"); diff --git a/tests/prepare-correction.test.ts b/tests/prepare-correction.test.ts index 6d8c07c..5f5580f 100644 --- a/tests/prepare-correction.test.ts +++ b/tests/prepare-correction.test.ts @@ -33,7 +33,7 @@ it("rejects an imported GIF and any SVG, which have no prompt to generate again await expect(prepareCorrection(api, { imageId: job.id, idempotencyKey: "svg" })).rejects.toThrow("cannot be used as references"); expect(await store.list("references")).toEqual([]); }); -it("generates a GIF again from its prompt with the requested changes, without references", async () => { +it("generates a GIF again from its prompt with the requested changes", async () => { const store = new MemoryStorage(); const api = new ImageService(store); const project = await api.createProject("Test"); @@ -253,3 +253,21 @@ it("includes the current region in v2 and reuses only the original for a text ed const plain = await prepareCorrection(api,{...input,idempotencyKey:"plain-edit",selection:undefined}); expect(plain.referenceIds).toHaveLength(1); }); + +it("keeps the original GIF's references in its next version, skipping deleted ones", async () => { + const store = new MemoryStorage(); + const api = new ImageService(store); + const project = await api.createProject("Test"); + const png = await sharp({ create: { width: 256, height: 256, channels: 3, background: "white" } }).png().toBuffer(); + const { job } = await api.importImage("image.png", "image/png", png, project.id); + const character = await api.addReference(project.id, "cat.png", "image/png", png); + await store.put("jobs", job.id, { ...job, imported: false, source: "api" as const, provider: "openai" as const, model: "gpt-image-2.6-sunburst", + prompt: "The cat hides under a blanket", outputFormat: "gif" as const, frameCount: 12, width: 816, height: 816, + referenceIds: [character.id, "00000000-0000-4000-8000-000000000000"] }); + await store.put("settings", "provider-openai", { id: "provider-openai" }); + const key = vi.spyOn(await import("../src/core/settings"), "readKey").mockResolvedValue("test-key"); + await addNote(store, { imageId: job.id, text: "Roll out to the left" }); + const next = await prepareCorrection(api, { imageId: job.id, idempotencyKey: "cat-v2" }); + expect(next).toMatchObject({ referenceIds: [character.id], outputFormat: "gif", frameCount: 12 }); + key.mockRestore(); +}); diff --git a/tests/providers.test.ts b/tests/providers.test.ts index 623d843..5bc7c84 100644 --- a/tests/providers.test.ts +++ b/tests/providers.test.ts @@ -526,3 +526,34 @@ it.each([null, { data: "private-catalog-value" }, { data: [null] }, { models: [{ await expect(discoverModels("openai", "key")).rejects.toThrow("The provider returned an unreadable model list. Try again later."); }, ); + +it("sends a GIF with reference images to the edits endpoint with its frame settings", async () => { + const gif = new TextEncoder().encode("GIF89a-animation"); + vi.mocked(imageSize).mockImplementation(bytes => bytes[0] === 0x47 + ? { width: 768, height: 768, type: "gif" } + : { width: 1024, height: 1024, type: "png" }); + const fetch = vi.fn(async () => ({ + ok: true, + status: 200, + json: async () => ({ data: [{ b64_json: Buffer.from(gif).toString("base64") }], usage: { input_tokens: 10, output_tokens: 20, total_tokens: 30 } }), + })); + vi.stubGlobal("fetch", fetch); + vi.mocked(generateImage).mockClear(); + const result = await generate({ + provider: "openai", model: "gpt-image-2.6-sunburst", prompt: "The cat hides under a blanket", + width: 768, height: 768, transparent: false, outputFormat: "gif", frameCount: 12, frameDurationMs: 150, quality: "medium", + } as Job, "key", [new Uint8Array([1, 2]), new Uint8Array([3, 4])]); + expect(generateImage).not.toHaveBeenCalled(); + const [url, init] = fetch.mock.calls[0] as unknown as [string, { body: FormData; headers: Record }]; + expect(url).toBe("https://api.openai.com/v1/images/edits"); + expect(init.headers).toEqual({ Authorization: "Bearer key" }); + const form = init.body; + expect(Object.fromEntries(["model", "prompt", "n", "size", "output_format", "frame_count", "frame_duration_ms", "quality"].map(key => [key, form.get(key)]))).toEqual({ + model: "gpt-image-2.6-sunburst", prompt: "The cat hides under a blanket", n: "1", size: "768x768", + output_format: "gif", frame_count: "12", frame_duration_ms: "150", quality: "medium", + }); + const images = form.getAll("image[]") as File[]; + expect(images.map(image => [image.name, image.type])).toEqual([["reference-1.png", "image/png"], ["reference-2.png", "image/png"]]); + expect(result).toMatchObject({ mime: "image/gif", width: 768, height: 768, usage: { inputTokens: 10, outputTokens: 20, totalTokens: 30 } }); + expect(result.adaptationError).toBeUndefined(); +}); diff --git a/tests/workspace.test.tsx b/tests/workspace.test.tsx index 9cc64fa..2f8d6ae 100644 --- a/tests/workspace.test.tsx +++ b/tests/workspace.test.tsx @@ -3166,8 +3166,9 @@ it("offers API quality, complexity, format and count, and blocks conflicting for fireEvent.click(screen.getByRole("checkbox", { name: "Transparent" })); fireEvent.click(screen.getByRole("button", { name: "Attach image reference" })); fireEvent.click(await screen.findByRole("button", { name: "panda.png" })); - expect(formatOption("gif").disabled).toBe(true); - expect(screen.getByText(/GIF output with reference images is not supported/)).toBeTruthy(); + expect(formatOption("gif").disabled).toBe(false); + expect(formatOption("svg").disabled).toBe(true); + expect(screen.getByText("SVG output cannot be combined with reference images.")).toBeTruthy(); fireEvent.click(screen.getByRole("button", { name: "panda.png" })); fireEvent.click(screen.getByRole("button", { name: "Close" })); fireEvent.change(screen.getByLabelText("Quality"), { target: { value: "xhigh" } }); diff --git a/wrangler.jsonc b/wrangler.jsonc index 528a62d..e3bfc35 100644 --- a/wrangler.jsonc +++ b/wrangler.jsonc @@ -37,7 +37,7 @@ "max_batch_size": 1, "max_batch_timeout": 0, "max_retries": 0, - "max_concurrency": 4 + "max_concurrency": 20 }] }, "images": {