diff --git a/.env.example b/.env.example index 718ebbb..d3aa3d0 100644 --- a/.env.example +++ b/.env.example @@ -6,6 +6,7 @@ IMAGE_QUEUE_SETTINGS_SECRET= IMAGE_QUEUE_MCP_TOKEN= IMAGE_QUEUE_CF_ACCESS_TEAM_DOMAIN= IMAGE_QUEUE_CF_ACCESS_AUDIENCE= +IMAGE_QUEUE_ACCESS_ALLOWED_EMAILS= # Platform path separator between allowed reference directories. IMAGE_QUEUE_REFERENCE_ROOTS= IMAGE_QUEUE_OPENAI_API_KEY= diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4fe550a..0da55cd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -17,13 +17,13 @@ jobs: runs-on: ${{ matrix.os }} timeout-minutes: 20 steps: - - uses: actions/checkout@v4 - - uses: pnpm/action-setup@v4 - - uses: actions/setup-node@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - uses: pnpm/action-setup@b906affcce14559ad1aafd4ab0e942779e9f58b1 # v4 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 with: node-version: 24 cache: pnpm - - uses: actions/setup-python@v5 + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5 with: python-version: '3.12' - run: pnpm install --frozen-lockfile diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml index 7780ff7..a652471 100644 --- a/.github/workflows/pages.yml +++ b/.github/workflows/pages.yml @@ -16,8 +16,6 @@ on: permissions: contents: read - pages: write - id-token: write concurrency: group: pages @@ -26,28 +24,34 @@ concurrency: jobs: build: runs-on: ubuntu-latest + permissions: + contents: read + pages: read steps: - - uses: actions/checkout@v4 - - uses: pnpm/action-setup@v4 - - uses: actions/setup-node@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - uses: pnpm/action-setup@b906affcce14559ad1aafd4ab0e942779e9f58b1 # v4 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 with: node-version: 24 cache: pnpm - - uses: actions/configure-pages@v5 + - uses: actions/configure-pages@983d7736d9b0ae728b81ab479565c72886d7745b # v5 id: pages - run: pnpm install --frozen-lockfile - run: pnpm build:website env: WEBSITE_BASE_PATH: ${{ steps.pages.outputs.base_path }} - - uses: actions/upload-pages-artifact@v3 + - uses: actions/upload-pages-artifact@56afc609e74202658d3ffba0e8f6dda462b719fa # v3 with: path: dist/website deploy: needs: build runs-on: ubuntu-latest + permissions: + pages: write + id-token: write environment: name: github-pages url: ${{ steps.deployment.outputs.page_url }} steps: - - uses: actions/deploy-pages@v4 + - uses: actions/deploy-pages@d6db90164ac5ed86f2b6aed7e0febac5b3c0c03e # v4 id: deployment diff --git a/.gitignore b/.gitignore index 213c6ac..3a2ad68 100644 --- a/.gitignore +++ b/.gitignore @@ -16,3 +16,4 @@ dist/ __pycache__/ *.pyc +wrangler.deploy.jsonc diff --git a/CHANGELOG.md b/CHANGELOG.md index 2f7cc5f..cfa493b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,17 @@ # Changelog +## 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). +- Connect the hosted MCP endpoint from Claude on the web, desktop and phone, Claude Code or Codex. Every request needs a Cloudflare Access sign-in from an allowed address; other signed-in accounts get 403, and the local static MCP token is not accepted there. API generation runs from the queue, one attempt per job without automatic retries. +- Hosted deployments generate through the OpenAI API by default. `refresh_models` loads the model list with the server's key, `view_image` returns a finished image, and the inline request, image and gallery views work on the stateless endpoint. Reading tools are marked read-only so hosts can run them without asking. +- Inline views follow the host's font and colours, show a loading state, download the full file and play GIFs as a light animated preview. On a phone a swipe scrolls the conversation and a tap selects a place for a change. The Next version form explains what it does. +- The next version of a generated GIF is generated again from its prompt with the requested changes, keeping its model, size, frame count and frame duration. +- Every OpenAI image model has its own profile: GPT Image 2.6 Sunburst (the new default) and Flare, 2.5 Sunburst and Flare, GPT Image 2, 1.5 and 1 mini, with documented custom sizes, `quality` and, for 2.6, `complexity`. `list_models` and `get_generation_source` report each model's capabilities. +- API requests can ask for PNG, WebP, JPEG, GIF or SVG when the model lists that format. GIF requests set frame count and duration and are checked against the frame sheet the model can render before submission. One submission can create up to 10 jobs. +- A definite provider rejection, including an account with no credits, is stored as failed with the provider's reason. A corrected request may reuse the idempotency key of a failed or cancelled one. +- The sidebar shows the generation source in use and lets you switch it. Connect an agent shows the remote MCP steps on a hosted workspace. Dark theme selects, fields and checkboxes read as one system. + ## 0.1.5 — 2026-11-17 - Send the first prompt directly to Inbox. Opening a project or topic sets the destination for the next image. A paused queue shows its status on mobile before submission. diff --git a/README.md b/README.md index 7f4ce7b..694e49d 100644 --- a/README.md +++ b/README.md @@ -82,6 +82,17 @@ Choose the default for new requests in **Settings → Default source**, or use M The optional [image-queue skill](skills/image-queue/SKILL.md) explains references, source selection and error recovery for agents. Reference images must be PNG, JPEG or WebP; style documents belong in text instructions. Before retrying an uncertain result, inspect the retained output and the recovery details returned by MCP. +### Use it from your phone: deploy to Cloudflare + +You can also run your own private copy on Cloudflare and add it as a remote MCP server in the Claude apps (web, desktop and phone), Claude Code or Codex. Cloudflare Access protects the panel and the MCP endpoint, and generation uses your image API key. It costs 5 USD per month for Workers Paid plus API usage. `pnpm cloudflare:setup --domain app.example.com --email you@example.com` sets everything up; see [Cloudflare deployment](docs/cloudflare.md). + +```sh +claude mcp add --transport http image-queue https://app.example.com/api/mcp +codex mcp add image-queue --url https://app.example.com/api/mcp && codex mcp login image-queue +``` + +In claude.ai or Claude Desktop, add the same URL under **Settings → Connectors → Add custom connector**; it also appears in the Claude mobile app. + ### Set up with an agent Give a local agent terminal access to the folder where you want image-queue, then paste: @@ -121,11 +132,12 @@ The supported deployment is local on macOS (Apple silicon). Cloudflare deploymen - Only models with a verified size profile appear in the model list. - References: PNG, JPEG or WebP, up to 20 MB. - Interrupted paid requests are not retried automatically. +- The Cloudflare deployment runs API generation only; the Codex queue stays local. - Not included yet: multi-machine sync, video, Windows and Linux support. - Some OpenAI accounts need [organization verification](https://developers.openai.com/api/docs/guides/image-generation) before using image models. ## More -[Configuration](docs/configuration.md) · [Codex workers](docs/codex-workers.md) · [Contributing](CONTRIBUTING.md) · [Security](SECURITY.md) +[Configuration](docs/configuration.md) · [Cloudflare deployment](docs/cloudflare.md) · [Codex workers](docs/codex-workers.md) · [Contributing](CONTRIBUTING.md) · [Security](SECURITY.md) Licensed under [Apache 2.0](LICENSE). diff --git a/cloudflare-worker.ts b/cloudflare-worker.ts index ac701bc..8d74e84 100644 --- a/cloudflare-worker.ts +++ b/cloudflare-worker.ts @@ -1,14 +1,50 @@ // @ts-ignore OpenNext generates this module during the Cloudflare build. import handler from "./.open-next/worker.js"; +// @ts-ignore OpenNext generates this module during the Cloudflare build. +import { runWithCloudflareRequestContext } from "./.open-next/cloudflare/init.js"; +import { busyRetryDelaySeconds, maxBusyAttempts } from "./src/core/generation-queue"; import { maintainTrash } from "./src/core/maintenance"; +import { abandonQueuedJob, runQueuedJob } from "./src/core/runtime"; import { CloudflareStorage } from "./src/storage/cloudflare"; type StorageBindings = ConstructorParameters; -type Environment = { DB: StorageBindings[0]; BLOBS: StorageBindings[1] }; +type GenerationQueue = { send(body: GenerationBody, options?: { delaySeconds?: number }): Promise }; +type GenerationBody = { jobId: string; attempt?: number }; +type Environment = { DB: StorageBindings[0]; BLOBS: StorageBindings[1]; GENERATION_QUEUE?: GenerationQueue }; +type ExecutionContext = { waitUntil(promise: Promise): void }; +type GenerationMessage = { body: unknown; ack(): void }; + +/** Internal origin for queue work; it never receives network traffic. */ +const queueOrigin = "https://generation-queue.invalid/"; export default { fetch: handler.fetch, async scheduled(event: { scheduledTime: number }, env: Environment) { await maintainTrash(new CloudflareStorage(env.DB, env.BLOBS), event.scheduledTime); }, + /** + * Runs provider generation outside the request that created the job, so a + * remote MCP client's time limit cannot cut an attempt short. Messages are + * acknowledged after each attempt and never retried: a second delivery + * could charge the provider twice. + */ + async queue(batch: { messages: readonly GenerationMessage[] }, env: Environment, ctx: ExecutionContext) { + for (const message of batch.messages) { + const body = message.body as Partial | null; + if (typeof body?.jobId === "string") { + const jobId = body.jobId; + const attempt = Number.isInteger(body.attempt) ? body.attempt! : 0; + const inContext = (work: () => Promise) => + runWithCloudflareRequestContext(new Request(queueOrigin), env, ctx, work) as Promise; + if ((await inContext(() => runQueuedJob(jobId))) === "busy") { + // Another operation holds the job. Nothing was sent to the provider, + // so offering it again later cannot charge twice. + if (attempt < maxBusyAttempts && env.GENERATION_QUEUE) + await env.GENERATION_QUEUE.send({ jobId, attempt: attempt + 1 }, { delaySeconds: busyRetryDelaySeconds }); + else await inContext(() => abandonQueuedJob(jobId)); + } + } + message.ack(); + } + }, }; diff --git a/docs/cloudflare.md b/docs/cloudflare.md new file mode 100644 index 0000000..60f910a --- /dev/null +++ b/docs/cloudflare.md @@ -0,0 +1,144 @@ +# Run image-queue on Cloudflare and connect it as a remote MCP server + +A Cloudflare deployment gives you your own private image queue on the web. You can request, follow and view images from the Claude apps on the web, desktop and phone, from Claude Code and from Codex, with no computer running at home. Generation uses an image API key that you provide. The Codex file queue stays local-only. + +Everything runs in your own Cloudflare account. Nobody else can reach the panel or the MCP endpoint: Cloudflare Access protects every request, and the application also checks the signed Access identity against your list of allowed e-mail addresses. See [ADR-0020](decisions/0020-remote-mcp-behind-cloudflare-access.md) for the design. + +## What you need + +- A Cloudflare account with a domain (zone) on it. The deployment uses a subdomain, for example `app.example.com`. +- A Workers Paid plan (5 USD per month). The free plan allows 10 ms of CPU time per request, which is not enough for the panel and the MCP server. D1, Queues and the R2 and Images usage of one person fit in the included allowances. +- A Cloudflare Zero Trust organization with an active plan. Zero Trust Free costs nothing and covers up to 50 users, but it has to be chosen once (**Zero Trust → Settings → Plan**); an organization without a plan shows "You need an active plan to continue" and cannot protect applications. +- An OpenAI API key, ideally from a dedicated project, because every image is billed. OpenAI does not offer a spend limit on every project. With prepaid credits and no payment method on the organization, spending stops at the credit balance; with a payment method, set the organization's usage limits. + +| Part | What it does | +|-|-| +| Worker on your subdomain | Panel, API and MCP endpoint at `/api/mcp` | +| D1 database `image-queue` | Projects, jobs and settings | +| R2 bucket `image-queue` | Images, references and thumbnails | +| Queue `image-queue-generation` | Runs each API generation outside the request that created it | +| Cloudflare Access application | Sign-in for the panel, and OAuth for MCP clients through Managed OAuth | + +## Deploy with one command + +1. Sign in to Cloudflare once with `pnpm exec wrangler login`. If your account has no Zero Trust organization yet, or the organization has no plan, open the [Zero Trust dashboard](https://one.dash.cloudflare.com/), choose a team name and the Free plan. +2. Create an API token under **My Profile → API Tokens → Create Custom Token** with two account permissions: **Access: Apps and Policies → Edit** and **Access: Organizations, Identity Providers, and Groups → Edit**. `wrangler login` cannot manage Access. +3. Run: + + ```sh + pnpm cloudflare:setup --domain app.example.com --email you@example.com + ``` + + The script asks for the API token and the OpenAI key without echoing them, unless `CLOUDFLARE_ACCESS_API_TOKEN` and `IMAGE_QUEUE_OPENAI_API_KEY` are set. Neither value is printed or written to disk. It creates or reuses D1, R2 and the queue, applies new migrations, builds and deploys to the custom domain, creates or updates the Access application with Managed OAuth and a One-time PIN login, and sets the Worker secrets. Run it again after an update; every step is repeatable. A rerun writes the Access application and its policy again, so changes made to them in the dashboard are replaced; use `--skip-access` to keep them. Use `--skip-access` to deploy only, `--skip-deploy` to change only Access and secrets, and `--account-id` when your login has several accounts. + +The steps below do the same by hand. + +## Deploy by hand + +1. Create the resources and apply the migrations: + + ```sh + pnpm install + pnpm exec wrangler login + pnpm exec wrangler d1 create image-queue + pnpm exec wrangler r2 bucket create image-queue + pnpm exec wrangler queues create image-queue-generation + ``` + + Put the returned D1 `database_id` into `wrangler.jsonc`, then apply every file in `migrations/` in order: + + ```sh + pnpm exec wrangler d1 execute image-queue --remote --file migrations/0001.sql + pnpm exec wrangler d1 execute image-queue --remote --file migrations/0002.sql + ``` + +2. Add your subdomain to `wrangler.jsonc` as a custom domain: + + ```jsonc + "routes": [{ "pattern": "app.example.com", "custom_domain": true }] + ``` + + The Worker is not served on `workers.dev` or preview URLs. + +3. Create the Access application in the Zero Trust dashboard, under **Access controls → Applications → Add an application → Self-hosted**: + - **Domain:** your subdomain, for example `app.example.com`, with no path. + - **Policy:** Allow, with a rule for the e-mail addresses that may use it. + - **Login method:** One-time PIN, or an identity provider you already use. + - **Advanced settings → Managed OAuth:** on. The redirect allowlist starts empty: under **Allowed redirect URIs** add `https://claude.ai/api/mcp/auth_callback` and `https://claude.com/api/mcp/auth_callback`. Keep **Allow localhost clients** and **Allow loopback clients** on for Claude Code and Codex, which receive the sign-in on a local port. **Grant session duration** decides how long a connected client stays signed in; the default equals the application session (24 hours), so set it longer, for example `336h`, if you do not want to enter a new code every day. + - Copy the application's **Application Audience (AUD) Tag** and your team domain (`.cloudflareaccess.com`). + +4. Build, deploy and set the configuration. Deploy first: until the secrets are set, the Worker rejects every request. + + ```sh + pnpm build:cloudflare + pnpm exec wrangler deploy + pnpm exec wrangler secret put IMAGE_QUEUE_CF_ACCESS_TEAM_DOMAIN + pnpm exec wrangler secret put IMAGE_QUEUE_CF_ACCESS_AUDIENCE + pnpm exec wrangler secret put IMAGE_QUEUE_ACCESS_ALLOWED_EMAILS + pnpm exec wrangler secret put IMAGE_QUEUE_OPENAI_API_KEY + ``` + + `IMAGE_QUEUE_ACCESS_ALLOWED_EMAILS` takes comma-separated addresses. Keep it the same as the Access policy: Access decides who may sign in, and the application refuses any other address with 403. + +5. Connect a client (below) and ask it to run `refresh_models`. It lists the image models your key can use, saves them and returns those with a verified size profile; it generates nothing and is not billed. Run it again after OpenAI releases a model. + +## Connect an MCP client + +The server URL is `https://app.example.com/api/mcp`. The first connection opens the Cloudflare Access sign-in page; after that, the client refreshes its token by itself. + +### Claude on the web, desktop and phone + +Custom connectors are shared across claude.ai, Claude Desktop and the Claude mobile apps. + +1. Open **Settings → Connectors → Add custom connector**. On a Team or Enterprise plan, an owner adds it under organization settings. +2. Enter a name such as `image-queue` and the server URL. Leave the advanced OAuth fields empty; Claude registers itself. +3. Click **Connect** and sign in on the Access page. +4. In a chat, enable the connector and ask for an image, for example: "Use image-queue to make a 1024×1024 image of a lighthouse at dawn with gpt-image-2.6, then show it." + +The model calls `request_image`, which returns at once, follows the job with `wait_for_job` or `get_job`, and shows the result with `view_image`. On Cloudflare a request without `source` uses the API and the preferred model from `list_models`; the local Codex queue is not available there. If `list_models` is empty or a model is missing, ask for `refresh_models`. + +Claude keeps the tool list it read when the connector was connected. After a deployment that adds or changes tools, disconnect and connect the connector again in **Settings → Connectors**, then start a new chat; otherwise new tools such as `refresh_models` are missing and old descriptions stay in use. The hosted endpoint is stateless and cannot notify Claude of the change. + +Reading tools are marked read-only (`readOnlyHint`), so Claude can run them without asking each time. Tools that may bill the API key (`request_image`, `request_images`, `retry_image`, `iterate_image`) and tools that cancel work keep asking until you choose **Always allow** for them. + +The inline request view shows a loading placeholder until the preview arrives, and **Download** hands the full-size file to Claude, which saves it on the device. + +### Claude Code + +```sh +claude mcp add --transport http image-queue https://app.example.com/api/mcp +``` + +Then run `/mcp` in Claude Code, select `image-queue` and authenticate. This needs **Allow localhost clients** and **Allow loopback clients** in the Access application. + +### Codex CLI and the Codex app + +The CLI and the desktop app share `~/.codex/config.toml`. + +```sh +codex mcp add image-queue --url https://app.example.com/api/mcp +codex mcp login image-queue +``` + +`codex mcp login` opens the Access sign-in in a browser. Like Claude Code, it needs localhost and loopback clients allowed in the Access application. A local stdio configuration of image-queue can stay next to the remote one under a different name. + +## Verify a deployment + +- `curl -i https://app.example.com/api/mcp -X POST` without credentials returns `401` from Access with a `WWW-Authenticate` header that points to OAuth metadata. +- The panel without a session redirects to the Access sign-in page. +- After connecting a client, `tools/list` includes `request_image`, `get_job`, `wait_for_job` and `view_image`. + +To test the deployable bundle without a Cloudflare account or a paid provider, run the local acceptance, which uses the real Workers runtime with local D1, R2 and Queues, a synthetic Access key set and a stub image API: + +```sh +pnpm build:cloudflare +pnpm exec wrangler deploy --dry-run --outdir .wrangler/acceptance +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. +- 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 9cda303..a1dc936 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -26,7 +26,7 @@ Open http://127.0.0.1:3215. Connections and worker settings are at `/settings`. Environment keys use `IMAGE_QUEUE_OPENAI_API_KEY`, `IMAGE_QUEUE_GOOGLE_GENERATIVE_AI_API_KEY`, `IMAGE_QUEUE_AI_GATEWAY_API_KEY` and `IMAGE_QUEUE_OPENROUTER_API_KEY`. Legacy unprefixed configuration remains readable. Keep local configuration and credentials out of version control and synchronization. -Provider discovery confirms access to a model, but does not establish its supported dimensions. The composer and MCP `list_models` expose only models with a structurally valid stored size profile. Execution rejects a missing or invalid profile before starting a paid attempt. The release still requires live provider verification and a maintained registry of those verified profiles; connecting a new key alone currently does not create that evidence. See [model verification](model-profiles.md). +Provider discovery confirms access to a model, but does not establish its supported dimensions. The composer and MCP `list_models` expose only models with a structurally valid stored size profile. Execution rejects a missing or invalid profile before starting a paid attempt. Profiles come from a maintained registry backed by live verification receipts; capabilities taken only from provider documentation are listed as `documentedOnly`. Connecting a new key alone does not create a profile. See [model verification](model-profiles.md). The default queue directory is `./image-queue`. Configure `IMAGE_QUEUE_QUEUE_DIR` to attach an existing queue. The panel imports metadata, reads existing artwork and appends new requests using the shared `.queue.lock`. Project assignment stays in panel storage. Submitted queue entries remain worker-owned. No worker is created by this application. @@ -98,19 +98,33 @@ To order an image over stdio, use the ID returned by `create_project` or `list_p For an exact output size, provide `width` and `height` in pixels. Pass the request's returned `id` to `get_job` to read its status and, when done, its local `outputPath`. -HTTP MCP uses `/api/mcp` and requires `Authorization: Bearer `. It is disabled until that secret is configured. A local HTTP client must send the returned `Mcp-Session-Id` on subsequent requests to retain negotiated MCP Apps capabilities. Sessions expire after 30 minutes of inactivity. The Cloudflare HTTP endpoint is stateless and exposes the base MCP tools. +HTTP MCP uses `/api/mcp` and requires `Authorization: Bearer `. It is disabled until that secret is configured. A local HTTP client must send the returned `Mcp-Session-Id` on subsequent requests to retain negotiated MCP Apps capabilities. Sessions expire after 30 minutes of inactivity. A Cloudflare deployment authenticates MCP through Cloudflare Access instead; see below. -API generation records the attempt before contacting a provider and disables SDK retries. Interrupted or ambiguous failures become `uncertain`. Check the provider before submitting another job. A new job is an explicit new request and can incur a new charge. +API generation records the attempt before contacting a provider and disables SDK retries. A definite provider rejection, such as invalid input or no remaining credits, is stored as `failed` with the provider's reason and did not generate an image; interrupted or ambiguous failures stay `uncertain` and need a check before another request, which can incur a new charge. -## Experimental Cloudflare deployment — outside 0.1.0 +## Cloudflare deployment and remote MCP -Version 0.1.0 supports local deployment only. The implementation notes below are experimental groundwork, not a supported deployment guide. Provider-only Cloudflare deployment is planned for a later 0.1.x release after separate validation. +Step-by-step setup and client connection instructions are in [Cloudflare deployment](cloudflare.md). ```sh 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. Before deploying, create the D1 database and R2 bucket, replace the local D1 ID in `wrangler.jsonc`, and apply `migrations/0001.sql`. Configure `IMAGE_QUEUE_STORAGE_DRIVER=cloudflare`, `IMAGE_QUEUE_CF_ACCESS_TEAM_DOMAIN`, `IMAGE_QUEUE_CF_ACCESS_AUDIENCE` and optionally `IMAGE_QUEUE_MCP_TOKEN`. Provider API keys are Cloudflare platform secrets using the prefixed names above. Protect the site with Cloudflare Access. Browser routes verify the Access JWT. HTTP MCP has separate bearer authentication. +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). + +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. + +Protect the custom domain with one self-hosted Cloudflare Access application and turn on its Managed OAuth, with `https://claude.ai/api/mcp/auth_callback` and `https://claude.com/api/mcp/auth_callback` on the redirect allowlist, and localhost and loopback clients allowed for Claude Code and Codex. Access then answers MCP clients with OAuth discovery, dynamic client registration and PKCE, and forwards the same signed assertion for a browser session and for an OAuth token. The application verifies that assertion on every panel, API and MCP request and accepts only allowlisted e-mail addresses; a signed-in address outside the allowlist receives 403. Without team domain, audience or allowlist it rejects every request. Invocation logs are off, so request headers are not stored in Workers Logs. The static `IMAGE_QUEUE_MCP_TOKEN` is local-only and is not accepted by a Cloudflare deployment. + +Add the remote endpoint in Claude as a custom connector with the URL `https:///api/mcp`. The Claude apps on the web, desktop and mobile share connectors. Signing in opens the Access login page. `view_image` returns a preview of a finished image as image content, so it can be shown in a client without MCP Apps views. `refresh_models` rediscovers the image models with the server's key and saves them, because a deployment whose key is a platform secret has no key to enter in Settings. On Cloudflare a request without `source` uses the API and the preferred model; the Codex queue is refused there. The Cloudflare HTTP endpoint is stateless and exposes the base MCP tools. + +`scripts/cloudflare-acceptance.mjs` runs the deployable bundle in the local Workers runtime with D1, R2 and Queues, a synthetic Access key set and a stub provider. No request leaves the machine. + +```sh +pnpm build:cloudflare +pnpm exec wrangler deploy --dry-run --outdir .wrangler/acceptance +node scripts/cloudflare-acceptance.mjs +``` The Codex file queue is local-only. Cloudflare can generate using configured API providers. A cloud-to-local queue bridge is outside this implementation. diff --git a/docs/decisions/0012-model-profiles-with-documented-capabilities.md b/docs/decisions/0012-model-profiles-with-documented-capabilities.md new file mode 100644 index 0000000..f431c65 --- /dev/null +++ b/docs/decisions/0012-model-profiles-with-documented-capabilities.md @@ -0,0 +1,35 @@ +--- +status: accepted +date: 2026-11-19 +--- + +# Keep one model profile registry and mark documented-only capabilities + +## Context and Problem Statement + +API generation uses a static registry of model profiles (`src/core/model-profiles.ts`). Until now an entry could list only what a paid test generation had confirmed. GPT Image 2.6 Flare was therefore limited to opaque 1024 × 1024 images, although OpenAI documents custom sizes from 655,360 to 8,294,400 pixels and transparent backgrounds for it. Game assets need non-square and transparent output. A paid test of every option is not always possible, for example when the API account has no credit. How can agents use a model's real options without the application promising results it never checked? + +## Decision Drivers + +- Agents and the panel must see what the provider accepts, not an outdated subset. +- Unsupported options must be refused before a paid attempt, never silently dropped. +- Users must be able to tell which capabilities a real generation has confirmed. + +## Considered Options + +- Profiles list only generation-verified capabilities +- Profiles list documented capabilities and mark those not yet verified +- Read capabilities from the provider at runtime + +## Decision Outcome + +Chosen option: "Profiles list documented capabilities and mark those not yet verified". Each model ID, including dated snapshots, has its own entry; capabilities are never inherited across a model family. An entry may add capabilities stated by the provider's official documentation; each such capability is named in `documentedOnly` until a receipt covers it. An entry without any generation and reference-edit receipt is allowed only when `documentedOnly` names both "generation" and "reference edit", and it reports `generationVerified: false`. `list_models` and `get_generation_source` return these fields. The first registry entry is the preferred default model. Every request is validated against the profile before submission: sizes, transparency, quality and references. After generation, the application measures the output dimensions and transparency as before, so a provider that ignores an option produces a visible mismatch rather than a silent success. + +Runtime discovery is not used: the OpenAI model list does not return image sizes or options. + +### Consequences + +- Good, because the owner's chosen model can be used for non-square and transparent assets. +- Good, because the evidence level of each capability remains visible. +- Bad, because a model with documentation-only support can be selected and billed before any receipt exists; `generationVerified: false` makes that visible. +- Bad, because a documented option can still fail at the provider. Such a failure is reported on the attempt and is not retried automatically. diff --git a/docs/decisions/0020-remote-mcp-behind-cloudflare-access.md b/docs/decisions/0020-remote-mcp-behind-cloudflare-access.md new file mode 100644 index 0000000..3396177 --- /dev/null +++ b/docs/decisions/0020-remote-mcp-behind-cloudflare-access.md @@ -0,0 +1,77 @@ +--- +status: accepted +date: 2026-11-19 +--- + +# Protect the hosted MCP endpoint with Cloudflare Access and run generation from a queue + +## Context and Problem Statement + +A Cloudflare deployment should be usable as a remote MCP connector from the Claude apps, including the mobile app, so that a user can submit and view image generations away from the computer. The hosted endpoint was protected by a static bearer token, while the panel was protected by Cloudflare Access. API generation ran inside the request that created the job. + +The Claude apps connect to remote MCP servers from Anthropic's cloud. For user-level authorization they support OAuth 2.0 with Dynamic Client Registration or a Client ID Metadata Document, PKCE (S256) and discovery through protected resource metadata. A fixed request header is available only to some organizations as a beta. Remote tool calls can be cut off after about a minute and are limited to a few minutes. An image provider can take longer than that. + +How should the hosted endpoint authenticate the Claude apps, and how should a remote request start a generation without being cut short? + +## Decision Drivers + +- The hosted endpoint must not be open, and must work with the OAuth flow the Claude apps support. +- The application should not implement and operate its own OAuth authorization server if the platform provides one. +- One identity check should protect the panel and MCP. +- A provider attempt must not be cut short by a client time limit, and must never be repeated automatically, because a repeat can be charged again. + +## Considered Options + +- Cloudflare Access with Managed OAuth in front of the whole deployment, with the application verifying the Access assertion, and generation from Cloudflare Queues +- An OAuth provider inside the Worker (`@cloudflare/workers-oauth-provider`) whose sign-in page is protected by Access +- Keep the static bearer token for the hosted endpoint +- Run generation inside the MCP request, or after the response with `waitUntil` + +## Decision Outcome + +Chosen option: "Cloudflare Access with Managed OAuth, and generation from Cloudflare Queues", because Access already protects the panel, Managed OAuth gives MCP clients a standard OAuth 2.1 flow with dynamic client registration and PKCE, and the origin receives the same signed assertion for a browser session and for an OAuth token. + +Rules: + +- One self-hosted Access application covers the deployment's custom domain, with Managed OAuth turned on, Claude's callback URLs on its redirect allowlist, and localhost and loopback clients allowed for Claude Code and Codex. The Worker is not reachable on `workers.dev` or preview URLs. +- The application verifies the `Cf-Access-Jwt-Assertion` signature, issuer, audience and expiry on every panel, API and MCP request, and accepts only identities whose e-mail address is in `IMAGE_QUEUE_ACCESS_ALLOWED_EMAILS`. Without team domain, audience or allowlist, every request is rejected. +- The static MCP bearer token stays a local-only credential. The hosted endpoint does not accept it. +- On Cloudflare, a new API job is sent to the `image-queue-generation` queue and the request returns at once. The consumer runs one job per invocation, without automatic retries, and records an error that happens before the provider attempt as `failed`. A job whose lock is busy is offered again later rather than failed, because nothing was sent to the provider. D1 locks carry a lease longer than the consumer's 15-minute limit. Locally, generation runs as before. +- `view_image` returns a preview of a finished image as image content, so a client without MCP Apps views can show the result. + +### Consequences + +- Good, because no OAuth server code or token storage lives in the application. +- Good, because the panel and MCP share one sign-in and one allowlist. +- Good, because a client time limit no longer interrupts a paid attempt. +- Bad, because a deployment needs a Cloudflare Zero Trust organization, an Access application on a custom domain and, in practice, a Workers Paid plan: the free plan allows 10 ms of CPU time per request, less than the panel and the MCP server need. +- Bad, because Access token lifetimes and the redirect allowlist live in the Cloudflare dashboard, outside the repository. +- Neutral, because the queue consumer is a second entry point that must set up the same runtime context as a request. + +### Confirmation + +- Tests check that the hosted endpoint rejects requests without an assertion, with a forged or expired assertion, with another audience, with an unlisted e-mail address and with the static token. +- Tests check that a Cloudflare API job is queued, that a queue failure is recorded before any provider request, and that the consumer acknowledges each message once. +- `scripts/cloudflare-acceptance.mjs` runs the deployable bundle in the local Workers runtime with D1, R2 and Queues, a synthetic Access key set and a stub provider, and checks discovery, rejection, one generation end to end and a single provider call. + +## Pros and Cons of the Options + +### An OAuth provider inside the Worker + +- Good, because it works without Managed OAuth. +- Bad, because the application would own client registration, token storage, rotation and revocation. +- Bad, because the sign-in page still needs Access or another identity check. + +### Keep the static bearer token + +- Good, because it is simple. +- Bad, because the Claude apps do not offer a fixed header to most users, and a shared static secret cannot be scoped or rotated per client. + +### Generation inside the request or with `waitUntil` + +- Good, because it needs no queue. +- Bad, because a client time limit or the 30-second limit after a response can end the attempt, leaving an uncertain, possibly charged result. + +## More Information + +This record extends [ADR-0004](0004-mcp-is-the-primary-interface-for-agents.md) for the hosted transport and keeps [ADR-0006](0006-one-server-side-key-store.md): the provider key is a Cloudflare platform secret. diff --git a/docs/decisions/ALL-DECISIONS.md b/docs/decisions/ALL-DECISIONS.md index 7f84977..93cc6de 100644 --- a/docs/decisions/ALL-DECISIONS.md +++ b/docs/decisions/ALL-DECISIONS.md @@ -12,6 +12,7 @@ | [0007](0007-sync-between-machines-over-ssh.md) | superseded by ADR-0014 | Sync between a user's machines over SSH, without a shared queue | | [0008](0008-provider-neutral-names.md) | accepted | Use provider-neutral names for the product and its parts | | [0009](0009-optional-mcp-apps-views.md) | proposed | Offer MCP Apps views as an optional layer over the MCP tools | +| [0012](0012-model-profiles-with-documented-capabilities.md) | accepted | Keep one model profile registry and mark documented-only capabilities | | [0013](0013-archive-and-trash-in-panel-metadata.md) | proposed | Keep archive and trash in panel metadata, and never delete files outside the store by default | | [0014](0014-optional-sync-through-an-s3-compatible-bucket.md) | accepted | Optional sync between machines through an S3-compatible bucket | | [0015](0015-portable-identities-without-renaming-worker-requests.md) | accepted | Add portable identities without renaming worker requests | @@ -19,8 +20,9 @@ | [0017](0017-forward-worker-requests-verbatim.md) | accepted | Forward image-worker requests verbatim with explicit reference attachments | | [0018](0018-kernel-locks-for-local-storage.md) | accepted | Use kernel locks for local storage operations | | [0019](0019-coordinate-local-queue-processing.md) | accepted | Coordinate local queue processing per generation source | +| [0020](0020-remote-mcp-behind-cloudflare-access.md) | accepted | Protect the hosted MCP endpoint with Cloudflare Access and run generation from a queue | -0010–0012 remain reserved for idempotency, durable execution and model profiles. Proposed records remain proposals. +0010 and 0011 remain reserved for idempotency and durable execution. Proposed records remain proposals. ## ADR-0016 diff --git a/docs/model-profiles.md b/docs/model-profiles.md index 8b0a947..29ed6d7 100644 --- a/docs/model-profiles.md +++ b/docs/model-profiles.md @@ -13,4 +13,37 @@ For each model: A test against a fake transport proves the request format only. It does not satisfy steps 2–3. Failed or ambiguous paid requests must not be automatically retried. A profile must not promise dimensions or capabilities that were not checked. -GPT Image 2.6 Flare and GPT Image 1.5 have verified 1024 × 1024 profiles: [Flare](verification/gpt-image-2.6-flare.md), [1.5](verification/gpt-image-1.5.md). Cached or discovered size profiles without an exact provider/model match in the verified registry are discarded at the application boundary. They cannot make a model selectable or authorize a generation attempt. +Capabilities stated by the official documentation but not covered by a receipt may be added under `documentedOnly` ([ADR-0012](decisions/0012-model-profiles-with-documented-capabilities.md)). Remove an item from that list only after a receipt covers it. + +Cached or discovered size profiles without an exact provider/model match in the registry are discarded at the application boundary. They cannot make a model selectable or authorize a generation attempt. + +## Current profiles + +Checked against the official documentation on 2026-11-19. Capabilities are stored per model ID, including dated snapshots; nothing is inherited across a family. "Custom" means `WIDTHxHEIGHT` with both sides multiples of 16, longest side at most 3840, ratio 1:3 to 3:1 and 655,360 to 8,294,400 pixels. "Standard" means 1024x1024, 1536x1024 and 1024x1536. Every listed model accepts reference images through the edits endpoint. + +| Model | Sizes | Transparent | Quality | Complexity | Output formats | Receipts | +|-|-|-|-|-|-|-| +| `gpt-image-2.6-sunburst` (default) | Custom | Yes | low, medium, high, xhigh, max, auto | low, medium, high (API default high) | png, webp, jpeg, gif, svg | None: documentation only | +| `gpt-image-2.6-flare` | Custom | Yes | low, medium, high, xhigh, max, auto | low, medium, high (API default high) | png, webp, jpeg, gif, svg | Opaque 1024 × 1024 and a reference edit ([receipt](verification/gpt-image-2.6-flare.md)) | +| `gpt-image-2.5-sunburst`, `-2026-09-08` | Custom; above 2560x1440 experimental | Yes | low, medium, high, xhigh, max, auto | None | png, webp, jpeg | None | +| `gpt-image-2.5-flare`, `-2026-09-08` | Custom; above 2560x1440 experimental | Yes | low, medium, high, xhigh, max, auto | None | png, webp, jpeg | None | +| `gpt-image-2`, `-2026-04-21` (deprecated) | Custom | Preview | low, medium, high, auto | None | png, webp, jpeg | None | +| `gpt-image-1.5` (deprecated) | Standard | Yes | low, medium, high, auto | None | png, webp, jpeg | Square, portrait, transparent and reference edits ([receipt](verification/gpt-image-1.5.md)) | +| `gpt-image-1-mini` (deprecated) | Standard | Yes (not stated per model) | low, medium, high, auto | None | png, webp, jpeg | None | + +`gpt-image-1` was shut down on 2026-10-23 and has no profile. Transparent output requires PNG or WebP. + +Sources: + +- [Image generation guide](https://developers.openai.com/api/docs/guides/image-generation): "GPT-Image-2.6" (complexity levels and default, SVG and GIF output), "Size and quality options" (custom size limits, xhigh and max for 2.5 and 2.6 Sunburst and Flare), transparency, and "Earlier GPT Image models" (GPT Image 2 sizes and qualities). +- [Create image reference](https://developers.openai.com/api/reference/resources/images/methods/generate): `background` (2.5 transparent, GPT Image 2 transparent in preview), `complexity` (low, medium, high), `quality`, `output_format` and `size`; `gpt-image-1` shutdown. +- Model pages: [2.6 Sunburst](https://developers.openai.com/api/docs/models/gpt-image-2.6-sunburst), [2.6 Flare](https://developers.openai.com/api/docs/models/gpt-image-2.6-flare), [2.5 Sunburst](https://developers.openai.com/api/docs/models/gpt-image-2.5-sunburst), [2.5 Flare](https://developers.openai.com/api/docs/models/gpt-image-2.5-flare), [GPT Image 2](https://developers.openai.com/api/docs/models/gpt-image-2), [1.5](https://developers.openai.com/api/docs/models/gpt-image-1.5), [1 mini](https://developers.openai.com/api/docs/models/gpt-image-1-mini) (edits endpoint, snapshots, deprecation). +- `@ai-sdk/openai` 4.0.118, which sends `complexity` and lists custom sizes for 2.5 and 2.6. + +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. + +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. + +`count` from 1 to 10 on an MCP or panel submission creates that many independent jobs with the same parameters. The first keeps the idempotency key; the rest use that key plus `-2` through `-N`. The whole submission is validated before any job is created. Replaying the same key and count returns those jobs. `request_images` counts every expanded job toward its 20-image cap. One job is still one image. diff --git a/migrations/0002.sql b/migrations/0002.sql new file mode 100644 index 0000000..0c159dd --- /dev/null +++ b/migrations/0002.sql @@ -0,0 +1 @@ +ALTER TABLE locks ADD COLUMN expires_at INTEGER; diff --git a/package.json b/package.json index 13dc53e..c95a4eb 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "image-queue", - "version": "0.1.5", + "version": "0.2.0", "description": "Local-first image queue and generation workspace", "scripts": { "dev": "next dev --hostname 127.0.0.1 --port 3215", @@ -12,6 +12,7 @@ "mcp": "node --env-file-if-exists=.env.local --import tsx src/mcp/stdio.ts", "build:cloudflare": "opennextjs-cloudflare build", "preview:cloudflare": "opennextjs-cloudflare preview", + "cloudflare:setup": "tsx scripts/cloudflare-setup.ts", "pool": "node --env-file-if-exists=.env.local --import tsx scripts/pool.ts", "benchmark": "tsx scripts/benchmark.ts", "build:mcp": "pnpm check:boundaries && pnpm build:mcp-views && esbuild src/mcp/stdio.ts --bundle --platform=node --format=esm --packages=external --outfile=dist/mcp.mjs", diff --git a/scripts/build-mcp-views.ts b/scripts/build-mcp-views.ts index b2ff3e7..9e79f16 100644 --- a/scripts/build-mcp-views.ts +++ b/scripts/build-mcp-views.ts @@ -1,4 +1,5 @@ import { build } from "esbuild"; +import { createHash } from "node:crypto"; import { writeFile } from "node:fs/promises"; const viewBudget = 150_000; @@ -8,6 +9,23 @@ function reportViewSize(name: string, html: string) { if (bytes > viewBudget) throw new Error(`MCP ${name} view exceeds the uncompressed size budget`); } +/** Hosts cache a view by its address, so the address changes whenever the view does. */ +const viewVersion = (html: string) => createHash("sha256").update(html).digest("hex").slice(0, 10); + +/** + * Shared look of the inline views. Every value comes from the host's MCP Apps + * style variables (font, sizes, colours, radius), so a view reads as part of + * the app that shows it; the fallbacks follow the system colour scheme. + */ +const secondaryText = "var(--color-text-secondary,color-mix(in srgb,currentColor 70%,transparent))"; +const baseCss = `body{margin:0;padding:16px;font-family:var(--font-sans,ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif);font-size:var(--font-text-md-size,14px);line-height:var(--font-text-md-line-height,1.5);font-weight:var(--font-weight-normal,400);color:var(--color-text-primary,CanvasText);background:var(--color-background-primary,Canvas);-webkit-font-smoothing:antialiased}`; +const buttonCss = (selector: string) => + `${selector}{font:inherit;font-size:var(--font-text-sm-size,13px);font-weight:var(--font-weight-medium,500);min-height:40px;padding:0 14px;border:var(--border-width-regular,1px) solid var(--color-border-primary,color-mix(in srgb,currentColor 25%,transparent));border-radius:var(--border-radius-md,8px);background:transparent;color:var(--color-text-primary,inherit);cursor:pointer}` + + `${selector}:hover:not(:disabled){background:var(--color-background-secondary,color-mix(in srgb,currentColor 8%,transparent))}` + + `${selector}.primary{border-color:transparent;background:var(--color-background-inverse,CanvasText);color:var(--color-text-inverse,Canvas)}` + + `${selector}.primary:hover:not(:disabled){background:var(--color-background-inverse,CanvasText);opacity:.88}` + + `button:focus-visible{outline:2px solid var(--color-ring-primary,Highlight);outline-offset:2px}button:disabled{opacity:.6;cursor:default}`; + const result = await build({ entryPoints: ["src/mcp/views/job.ts"], bundle: true, @@ -17,13 +35,13 @@ const result = await build({ minify: true, }); const script = result.outputFiles[0].text.replaceAll("

Image request

Connecting to image-queue…

`;
+const html = `

Image request

Connecting to image-queue…

`; reportViewSize("job", html); await writeFile( "src/mcp/views/job-html.ts", `// Generated by scripts/build-mcp-views.ts\nexport const jobViewHtml = ${JSON.stringify( html, - )};\n`, + )};\nexport const jobViewVersion = ${JSON.stringify(viewVersion(html))};\n`, ); const galleryBuild = await build({ @@ -31,15 +49,15 @@ const galleryBuild = await build({ format: "iife", platform: "browser", minify: true, }); const galleryScript = galleryBuild.outputFiles[0].text.replaceAll("

Loading images…

`; +const galleryHtml = `

Loading images…

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

Loading image…

    `; +const imageHtml = `

    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)};\n`); +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`); diff --git a/scripts/cloudflare-acceptance.mjs b/scripts/cloudflare-acceptance.mjs new file mode 100644 index 0000000..31c8e58 --- /dev/null +++ b/scripts/cloudflare-acceptance.mjs @@ -0,0 +1,214 @@ +// Local acceptance for the Cloudflare deployment, in the real workerd runtime. +// +// Runs the bundle that `wrangler deploy` would upload with local D1, R2 and +// Queues, and routes every outbound request to a stub: a synthetic Cloudflare +// Access key set and a fake OpenAI image endpoint. No network request leaves +// the machine and no provider is charged. +// +// pnpm build:cloudflare +// pnpm exec wrangler deploy --dry-run --outdir .wrangler/acceptance +// node scripts/cloudflare-acceptance.mjs +import { createRequire } from "node:module"; +import { readdir, readFile } from "node:fs/promises"; +import assert from "node:assert/strict"; +import { exportJWK, generateKeyPair, SignJWT } from "jose"; +import sharp from "sharp"; + +const require = createRequire(require_resolve("wrangler/package.json")); +const { Miniflare, convertV4MiniflareOptions } = require("miniflare"); +function require_resolve(name) { + return createRequire(import.meta.url).resolve(name); +} + +const team = "acceptance.cloudflareaccess.com"; +const audience = "acceptance-audience"; +const owner = "owner@example.com"; +const providerKey = "sk-acceptance-stub-key"; + +const { publicKey, privateKey } = await generateKeyPair("RS256", { extractable: true }); +const jwks = { keys: [{ ...await exportJWK(publicKey), kid: "acceptance", alg: "RS256" }] }; +const foreign = await generateKeyPair("RS256"); +const sign = ({ email = owner, key = privateKey, aud = audience } = {}) => + new SignJWT({ email }).setProtectedHeader({ alg: "RS256", kid: "acceptance" }) + .setIssuer(`https://${team}`).setAudience(aud).setExpirationTime("5m").sign(key); +const png = (await sharp({ create: { width: 1024, height: 1024, channels: 4, background: "#2563eb" } }) + .png().toBuffer()).toString("base64"); + +const stub = ` +const calls = []; +export default { + async fetch(request) { + const url = new URL(request.url); + if (url.hostname === "stub.invalid" && url.pathname === "/calls") return Response.json(calls); + calls.push({ method: request.method, url: url.href, authorization: request.headers.get("authorization") }); + if (url.href === "https://${team}/cdn-cgi/access/certs") return Response.json(${JSON.stringify(jwks)}); + if (url.href === "https://api.openai.com/v1/images/generations" && request.method === "POST") { + calls.at(-1).body = await request.json(); + return Response.json({ created: 1, data: [{ b64_json: "${png}" }], + usage: { input_tokens: 10, output_tokens: 100, total_tokens: 110 } }); + } + return new Response("blocked outbound request", { status: 599 }); + }, +};`; + +const mf = new Miniflare(convertV4MiniflareOptions({ + workers: [ + { + name: "image-queue", + modules: true, + scriptPath: ".wrangler/acceptance/cloudflare-worker.js", + compatibilityDate: "2026-11-14", + compatibilityFlags: ["nodejs_compat"], + bindings: { + IMAGE_QUEUE_STORAGE_DRIVER: "cloudflare", + IMAGE_QUEUE_CF_ACCESS_TEAM_DOMAIN: team, + IMAGE_QUEUE_CF_ACCESS_AUDIENCE: audience, + IMAGE_QUEUE_ACCESS_ALLOWED_EMAILS: owner, + IMAGE_QUEUE_OPENAI_API_KEY: providerKey, + }, + d1Databases: { DB: "acceptance" }, + r2Buckets: { BLOBS: "acceptance" }, + queueProducers: { GENERATION_QUEUE: "image-queue-generation" }, + queueConsumers: { "image-queue-generation": { maxBatchSize: 1, maxBatchTimeout: 0, maxRetries: 0 } }, + assets: { directory: ".open-next/assets", binding: "ASSETS", routerConfig: { has_user_worker: true } }, + images: { binding: "IMAGES" }, + outboundService: "stub", + }, + { name: "stub", modules: true, script: stub }, + ], +})); + +const results = []; +const check = async (name, work) => { + await work(); + results.push(name); + console.log(`ok - ${name}`); +}; + +try { + const db = await mf.getD1Database("DB"); + for (const migration of (await readdir("migrations")).filter(name => name.endsWith(".sql")).sort()) + for (const statement of (await readFile(`migrations/${migration}`, "utf8")).split(";").map(s => s.trim()).filter(Boolean)) + await db.prepare(statement).run(); + await db.prepare("INSERT INTO records(collection,id,value) VALUES(?,?,?)").bind("models", "openai", JSON.stringify([ + { id: "gpt-image-1.5", name: "GPT Image 1.5", provider: "openai", references: true, transparency: true }, + ])).run(); + + const base = "https://images.example.com"; + let id = 0; + const mcp = async (method, params, headers) => { + const response = await mf.dispatchFetch(`${base}/api/mcp`, { + method: "POST", + headers: { accept: "application/json, text/event-stream", "content-type": "application/json", ...headers }, + body: JSON.stringify({ jsonrpc: "2.0", id: ++id, method, ...(params ? { params } : {}) }), + }); + return response; + }; + const access = { "cf-access-jwt-assertion": await sign() }; + const call = async (name, args) => { + const response = await mcp("tools/call", { name, arguments: args }, access); + assert.equal(response.status, 200); + const body = await response.json(); + assert.ok(!body.error && !body.result.isError, JSON.stringify(body)); + return JSON.parse(body.result.content[0].text); + }; + + await check("MCP rejects a request without credentials (401)", async () => { + const response = await mcp("tools/list", undefined, {}); + if (response.status !== 401) console.log("DEBUG", response.status, [...response.headers], (await response.text()).slice(0, 400)); + assert.equal(response.status, 401); + }); + await check("MCP rejects a static bearer token, a forged assertion and another audience (401)", async () => { + for (const headers of [ + { authorization: "Bearer anything" }, + { "cf-access-jwt-assertion": await sign({ key: foreign.privateKey }) }, + { "cf-access-jwt-assertion": await sign({ aud: "another-app" }) }, + ]) assert.equal((await mcp("tools/list", undefined, headers)).status, 401); + }); + await check("MCP refuses a signed-in e-mail outside the allowlist (403)", async () => { + const headers = { "cf-access-jwt-assertion": await sign({ email: "intruder@example.com" }) }; + assert.equal((await mcp("tools/list", undefined, headers)).status, 403); + }); + await check("panel rejects a browser without an Access session (403)", async () => { + const response = await mf.dispatchFetch(`${base}/api/state`); + assert.equal(response.status, 403); + }); + await check("MCP initialize and tools/list work with an allowlisted Access identity", async () => { + const initialize = await mcp("initialize", { + protocolVersion: "2025-11-25", capabilities: {}, clientInfo: { name: "acceptance", version: "1.0" }, + }, access); + assert.equal(initialize.status, 200); + const tools = await (await mcp("tools/list", undefined, access)).json(); + const names = tools.result.tools.map(tool => tool.name); + for (const name of ["request_image", "get_job", "wait_for_job", "view_image", "list_models", "refresh_models", "create_project"]) + assert.ok(names.includes(name), `missing ${name}`); + }); + await check("panel state answers an allowlisted Access identity", async () => { + const response = await mf.dispatchFetch(`${base}/api/state`, { headers: access }); + assert.equal(response.status, 200); + }); + + let job; + await check("request_image returns at once and the generation queue completes the image", async () => { + const project = await call("create_project", { name: "Remote acceptance" }); + const started = Date.now(); + job = await call("request_image", { + projectId: project.id, source: "api", provider: "openai", model: "gpt-image-1.5", + prompt: "A blue square", width: 1024, height: 1024, idempotencyKey: "remote-acceptance-1", + }); + assert.equal(job.status, "queued"); + console.log(` request_image answered in ${Date.now() - started} ms with status ${job.status}`); + for (let attempt = 0; attempt < 60 && ["queued", "running"].includes(job.status); attempt++) { + await new Promise(resolve => setTimeout(resolve, 500)); + job = await call("get_job", { id: job.id }); + } + assert.equal(job.status, "done", JSON.stringify(job)); + assert.ok(job.blobKey, "no stored result"); + const bucket = await mf.getR2Bucket("BLOBS"); + const stored = await bucket.get(job.blobKey); + assert.ok(stored && (await stored.arrayBuffer()).byteLength > 1000, "result missing in R2"); + }); + await check("view_image returns the finished image as inline image content", async () => { + const response = await mcp("tools/call", { name: "view_image", arguments: { id: job.id } }, access); + const body = await response.json(); + assert.ok(!body.error && !body.result.isError, JSON.stringify(body).slice(0, 400)); + const [image] = body.result.content; + assert.equal(image.type, "image"); + assert.match(image.mimeType, /^image\//); + assert.ok(Buffer.from(image.data, "base64").byteLength > 100); + }); + await check("a request without source defaults to the API on Cloudflare", async () => { + const queued = await call("request_image", { + projectId: job.projectId, prompt: "A green circle", width: 1024, height: 1024, idempotencyKey: "remote-acceptance-default", + }); + assert.equal(queued.source, "api"); + assert.equal(queued.model, "gpt-image-1.5"); + let current = queued; + for (let attempt = 0; attempt < 60 && ["queued", "running"].includes(current.status); attempt++) { + await new Promise(resolve => setTimeout(resolve, 500)); + current = await call("get_job", { id: queued.id }); + } + assert.equal(current.status, "done", JSON.stringify(current)); + }); + await check("one provider call per image, authorized with the platform-secret key", async () => { + const calls = await (await (await mf.getWorker("stub")).fetch("https://stub.invalid/calls")).json(); + const generations = calls.filter(entry => entry.url === "https://api.openai.com/v1/images/generations"); + assert.equal(generations.length, 2); + assert.equal(generations[0].authorization, `Bearer ${providerKey}`); + assert.equal(generations[0].body.prompt, "A blue square"); + const blocked = calls.filter(entry => !entry.url.startsWith(`https://${team}/`) && !entry.url.startsWith("https://api.openai.com/")); + assert.deepEqual(blocked, [], "unexpected outbound requests"); + }); + await check("a replayed idempotency key returns the same job without a second provider call", async () => { + const replay = await call("request_image", { + projectId: job.projectId, source: "api", provider: "openai", model: "gpt-image-1.5", + prompt: "A blue square", width: 1024, height: 1024, idempotencyKey: "remote-acceptance-1", + }); + assert.equal(replay.id, job.id); + const calls = await (await (await mf.getWorker("stub")).fetch("https://stub.invalid/calls")).json(); + assert.equal(calls.filter(entry => entry.url.endsWith("/v1/images/generations")).length, 2); + }); + console.log(`\n${results.length} checks passed`); +} finally { + await mf.dispose(); +} diff --git a/scripts/cloudflare-setup-plan.ts b/scripts/cloudflare-setup-plan.ts new file mode 100644 index 0000000..6dfe3c6 --- /dev/null +++ b/scripts/cloudflare-setup-plan.ts @@ -0,0 +1,121 @@ +/** Pure parts of `pnpm cloudflare:setup`, kept separate so they can be tested without Cloudflare. */ + +export const claudeCallbacks = [ + "https://claude.ai/api/mcp/auth_callback", + "https://claude.com/api/mcp/auth_callback", +]; +export const applicationName = "image-queue"; + +export type SetupOptions = { + domain: string; + emails: string[]; + accountId?: string; + skipAccess: boolean; + skipDeploy: boolean; + skipBuild: boolean; +}; + +const hostname = /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/; +const email = /^[^\s@,]+@[^\s@,]+\.[^\s@,]+$/; + +export function parseOptions(argv: readonly string[], env: Record = {}): SetupOptions { + const options: SetupOptions = { domain: "", emails: [], skipAccess: false, skipDeploy: false, skipBuild: false }; + for (let index = 0; index < argv.length; index++) { + const argument = argv[index]!; + const value = () => { + const next = argv[++index]; + if (next === undefined || next.startsWith("--")) throw new Error(`${argument} needs a value`); + return next; + }; + if (argument === "--domain") options.domain = value().trim().toLowerCase(); + else if (argument === "--email") options.emails.push(...value().split(",").map(item => item.trim().toLowerCase()).filter(Boolean)); + else if (argument === "--account-id") options.accountId = value().trim(); + else if (argument === "--skip-access") options.skipAccess = true; + else if (argument === "--skip-deploy") options.skipDeploy = true; + else if (argument === "--skip-build") options.skipBuild = true; + else throw new Error(`Unknown option ${argument}`); + } + options.accountId ??= env.CLOUDFLARE_ACCOUNT_ID; + if (!hostname.test(options.domain)) throw new Error("--domain must be a host name such as app.example.com, without a scheme or path"); + if (!options.skipAccess && options.emails.length === 0) throw new Error("--email is required to set up Cloudflare Access"); + const invalid = options.emails.find(item => !email.test(item)); + if (invalid) throw new Error(`Not an e-mail address: ${invalid}`); + if (options.accountId !== undefined && !/^[0-9a-f]{32}$/.test(options.accountId)) throw new Error("--account-id must be a 32-character Cloudflare account ID"); + options.emails = [...new Set(options.emails)]; + return options; +} + +/** The only account ID in `wrangler whoami` output; several accounts need --account-id. */ +export function accountFromWhoami(output: string) { + const ids = [...new Set(output.match(/\b[0-9a-f]{32}\b/g) ?? [])]; + if (ids.length === 1) return ids[0]!; + throw new Error(ids.length === 0 + ? "Run `pnpm exec wrangler login` first" + : "Several Cloudflare accounts are available. Pass --account-id."); +} + +type WranglerConfig = { + d1_databases?: { binding: string; database_name: string; database_id: string }[]; + routes?: unknown[]; + workers_dev?: boolean; + preview_urls?: boolean; + [key: string]: unknown; +}; + +/** Deployment configuration: the repository's wrangler.jsonc with the real D1 ID and the custom domain. */ +export function deploymentConfig(base: WranglerConfig, databaseId: string, domain: string): WranglerConfig { + if (!/^[0-9a-f-]{36}$/.test(databaseId)) throw new Error("Unexpected D1 database ID"); + return { + ...base, + d1_databases: (base.d1_databases ?? []).map(database => + database.binding === "DB" ? { ...database, database_id: databaseId } : database), + routes: [{ pattern: domain, custom_domain: true }], + workers_dev: false, + preview_urls: false, + }; +} + +/** Migration files not yet recorded, in order. */ +export function pendingMigrations(files: readonly string[], applied: readonly string[]) { + const done = new Set(applied); + return files.filter(name => /^\d{4}[\w-]*\.sql$/.test(name) && !done.has(name)).sort(); +} + +/** The self-hosted Access application, with Managed OAuth for MCP clients. */ +export function accessApplication(domain: string, emails: readonly string[], identityProviderId: string) { + return { + type: "self_hosted", + name: applicationName, + domain, + session_duration: "24h", + allowed_idps: [identityProviderId], + auto_redirect_to_identity: true, + app_launcher_visible: false, + policies: [{ + name: "image-queue owners", + decision: "allow", + include: emails.map(address => ({ email: { email: address } })), + }], + oauth_configuration: { + enabled: true, + dynamic_client_registration: { + enabled: true, + allowed_uris: claudeCallbacks, + // Claude Code and Codex receive the sign-in on a local port. + allow_any_on_localhost: true, + allow_any_on_loopback: true, + }, + grant: { access_token_lifetime: "15m", session_duration: "336h" }, + }, + }; +} + +/** Values the Worker needs; never printed. */ +export function workerSecrets(input: { teamDomain: string; audience: string; emails: readonly string[]; openAiKey?: string }) { + return { + IMAGE_QUEUE_CF_ACCESS_TEAM_DOMAIN: input.teamDomain, + IMAGE_QUEUE_CF_ACCESS_AUDIENCE: input.audience, + IMAGE_QUEUE_ACCESS_ALLOWED_EMAILS: input.emails.join(","), + ...(input.openAiKey ? { IMAGE_QUEUE_OPENAI_API_KEY: input.openAiKey } : {}), + }; +} diff --git a/scripts/cloudflare-setup.ts b/scripts/cloudflare-setup.ts new file mode 100644 index 0000000..e1e18bf --- /dev/null +++ b/scripts/cloudflare-setup.ts @@ -0,0 +1,197 @@ +// Sets up a private image-queue deployment on Cloudflare, or brings an existing one up to date. +// +// pnpm cloudflare:setup --domain app.example.com --email you@example.com +// +// Every step can be repeated. Resources and the deployment use your `wrangler login`. +// Cloudflare Access needs an API token with "Access: Apps and Policies Edit" and +// "Access: Organizations, Identity Providers, and Groups Edit"; the script reads it from +// CLOUDFLARE_ACCESS_API_TOKEN or asks for it without echoing. The OpenAI key is read from +// IMAGE_QUEUE_OPENAI_API_KEY or asked for the same way. Neither is printed or written to disk. +import { execFile, spawn } from "node:child_process"; +import { readdir, readFile, writeFile } from "node:fs/promises"; +import { createInterface } from "node:readline"; +import { Writable } from "node:stream"; +import { promisify } from "node:util"; +import { + accessApplication, accountFromWhoami, applicationName, claudeCallbacks, deploymentConfig, parseOptions, + pendingMigrations, workerSecrets, type SetupOptions, +} from "./cloudflare-setup-plan"; + +const run = promisify(execFile); +const wranglerBin = "node_modules/.bin/wrangler"; +const deployConfigPath = "wrangler.deploy.jsonc"; +const names = { database: "image-queue", bucket: "image-queue", queue: "image-queue-generation" }; + +const step = (text: string) => console.log(`\n▸ ${text}`); + +async function wrangler(args: string[], input?: string) { + if (input === undefined) { + const { stdout } = await run(wranglerBin, args, { maxBuffer: 64 * 1024 * 1024 }); + return stdout; + } + return new Promise((resolve, reject) => { + const child = spawn(wranglerBin, args, { stdio: ["pipe", "pipe", "inherit"] }); + let output = ""; + child.stdout.on("data", chunk => { output += chunk; }); + child.on("error", reject); + child.on("close", code => code === 0 ? resolve(output) : reject(new Error(`wrangler ${args[0]} ${args[1] ?? ""} failed`))); + child.stdin.end(input); + }); +} + +/** Runs a create command and treats "already exists" as success. */ +async function ensure(label: string, args: string[]) { + try { + await wrangler(args); + console.log(` created ${label}`); + } catch (error) { + const text = String((error as { stderr?: string; stdout?: string }).stderr ?? "") + + String((error as { stdout?: string }).stdout ?? ""); + if (!/already exists|already taken|already own/i.test(text)) throw new Error(`Could not create ${label}: ${text.trim().split("\n").at(-1)}`); + console.log(` ${label} already exists`); + } +} + +async function hiddenPrompt(question: string) { + if (!process.stdin.isTTY) return undefined; + let muted = false; + const output = new Writable({ + write(chunk, _encoding, done) { + if (!muted) process.stdout.write(chunk); + done(); + }, + }); + const reader = createInterface({ input: process.stdin, output, terminal: true }); + return new Promise(resolve => { + reader.question(question, answer => { + reader.close(); + process.stdout.write("\n"); + resolve(answer.trim()); + }); + muted = true; + }); +} + +async function cloudflare(token: string, path: string, init: RequestInit = {}) { + const response = await fetch(`https://api.cloudflare.com/client/v4${path}`, { + ...init, + headers: { authorization: `Bearer ${token}`, "content-type": "application/json", ...init.headers }, + }); + const body = await response.json().catch(() => ({})) as { success?: boolean; result?: T; errors?: { message: string }[] }; + if (!response.ok || !body.success) { + const reason = body.errors?.map(error => error.message).join("; ") || `HTTP ${response.status}`; + throw new Error(`Cloudflare API ${init.method ?? "GET"} ${path.replace(/[0-9a-f]{32}/g, "")}: ${reason}`); + } + return body.result as T; +} + +async function resourcesAndDeployment(options: SetupOptions) { + step("Resources"); + const databases = JSON.parse(await wrangler(["d1", "list", "--json"])) as { name: string; uuid: string }[]; + let database = databases.find(entry => entry.name === names.database); + if (!database) { + await wrangler(["d1", "create", names.database, "--no-update-config"]); + database = (JSON.parse(await wrangler(["d1", "list", "--json"])) as { name: string; uuid: string }[]) + .find(entry => entry.name === names.database); + if (!database) throw new Error("The D1 database was not created"); + console.log(` created D1 ${names.database}`); + } else console.log(` D1 ${names.database} already exists`); + await ensure(`R2 bucket ${names.bucket}`, ["r2", "bucket", "create", names.bucket]); + await ensure(`queue ${names.queue}`, ["queues", "create", names.queue]); + + step("Deployment configuration"); + const base = JSON.parse(await readFile("wrangler.jsonc", "utf8")); + await writeFile(deployConfigPath, `${JSON.stringify(deploymentConfig(base, database.uuid, options.domain), null, 2)}\n`); + console.log(` wrote ${deployConfigPath} (not committed)`); + + step("Database migrations"); + const tracking = "CREATE TABLE IF NOT EXISTS image_queue_migrations (name TEXT PRIMARY KEY, applied_at TEXT NOT NULL)"; + await wrangler(["d1", "execute", names.database, "--remote", "-y", "-c", deployConfigPath, "--command", tracking]); + const appliedOutput = JSON.parse(await wrangler(["d1", "execute", names.database, "--remote", "-y", "-c", deployConfigPath, + "--json", "--command", "SELECT name FROM image_queue_migrations"])) as { results: { name: string }[] }[]; + const applied = appliedOutput.flatMap(entry => entry.results.map(row => row.name)); + const pending = pendingMigrations(await readdir("migrations"), applied); + for (const migration of pending) { + await wrangler(["d1", "execute", names.database, "--remote", "-y", "-c", deployConfigPath, "--file", `migrations/${migration}`]); + await wrangler(["d1", "execute", names.database, "--remote", "-y", "-c", deployConfigPath, "--command", + `INSERT INTO image_queue_migrations(name, applied_at) VALUES('${migration}', datetime('now'))`]); + console.log(` applied ${migration}`); + } + if (pending.length === 0) console.log(" up to date"); + + if (!options.skipBuild) { + step("Build"); + await run("pnpm", ["build:cloudflare"], { maxBuffer: 256 * 1024 * 1024 }); + console.log(" built"); + } + step("Deploy"); + await wrangler(["deploy", "-c", deployConfigPath]); + console.log(` deployed to https://${options.domain}`); +} + +async function access(options: SetupOptions, accountId: string) { + step("Cloudflare Access"); + const token = process.env.CLOUDFLARE_ACCESS_API_TOKEN ?? await hiddenPrompt(" Cloudflare API token for Access (input hidden): "); + if (!token) throw new Error("Set CLOUDFLARE_ACCESS_API_TOKEN or run in a terminal to enter it"); + const account = `/accounts/${accountId}/access`; + const organization = await cloudflare<{ auth_domain?: string }>(token, `${account}/organizations`).catch(() => { + throw new Error("No Zero Trust organization. Open https://one.dash.cloudflare.com/, choose a team name and the Free plan, then run this again."); + }); + if (!organization.auth_domain) throw new Error("The Zero Trust organization has no team domain yet"); + + const providers = await cloudflare<{ id: string; type: string }[]>(token, `${account}/identity_providers`); + let pin = providers.find(provider => provider.type === "onetimepin"); + if (!pin) { + pin = await cloudflare<{ id: string; type: string }>(token, `${account}/identity_providers`, { + method: "POST", body: JSON.stringify({ type: "onetimepin", name: "One-time PIN", config: {} }), + }); + console.log(" added the One-time PIN login method"); + } + + const body = JSON.stringify(accessApplication(options.domain, options.emails, pin.id)); + const applications = await cloudflare<{ id: string; domain: string; name: string }[]>(token, `${account}/apps`); + const existing = applications.find(app => app.domain === options.domain); + if (existing && existing.name !== applicationName) + throw new Error(`An Access application named "${existing.name}" already covers ${options.domain}. Rename or remove it first.`); + const application = await (existing + ? cloudflare<{ aud: string }>(token, `${account}/apps/${existing.id}`, { method: "PUT", body }) + : cloudflare<{ aud: string }>(token, `${account}/apps`, { method: "POST", body }) + ).catch(error => { + throw new Error(`${error instanceof Error ? error.message : error}. If the Zero Trust organization has no plan yet, choose Zero Trust Free under Zero Trust → Settings → Plan and run this again.`); + }); + console.log(` ${existing ? "updated" : "created"} the Access application with Managed OAuth`); + console.log(` redirect allowlist: ${claudeCallbacks.join(", ")}, plus localhost and loopback`); + return { teamDomain: organization.auth_domain, audience: application.aud }; +} + +async function main() { + const options = parseOptions(process.argv.slice(2), process.env); + const accountId = options.accountId ?? accountFromWhoami(await wrangler(["whoami"])); + if (!options.skipDeploy) await resourcesAndDeployment(options); + else await readFile(deployConfigPath, "utf8").catch(() => { + throw new Error(`${deployConfigPath} is missing; run once without --skip-deploy`); + }); + + if (options.skipAccess) { + console.log("\nSkipped Cloudflare Access. Until it is set up, the deployment rejects every request."); + return; + } + const accessValues = await access(options, accountId); + const openAiKey = process.env.IMAGE_QUEUE_OPENAI_API_KEY ?? + await hiddenPrompt(" OpenAI API key for this deployment (input hidden, empty to keep the current one): "); + + step("Worker secrets"); + const secrets = workerSecrets({ ...accessValues, emails: options.emails, openAiKey: openAiKey || undefined }); + await wrangler(["secret", "bulk", "-c", deployConfigPath], JSON.stringify(secrets)); + console.log(` set ${Object.keys(secrets).join(", ")}`); + + console.log(` +Done. Add this URL as a custom connector in Claude, or with Claude Code or Codex: + https://${options.domain}/api/mcp +After connecting, ask the client to run refresh_models once to load the image models your key can use.`); +} + +main().catch(error => { + console.error(`\n✗ ${error instanceof Error ? error.message : String(error)}`); + process.exitCode = 1; +}); diff --git a/skills/image-queue/SKILL.md b/skills/image-queue/SKILL.md index 5b3f3c6..ba49b07 100644 --- a/skills/image-queue/SKILL.md +++ b/skills/image-queue/SKILL.md @@ -9,7 +9,7 @@ Use the connected image-queue MCP tools. Tool namespaces may vary; discover the ## Choose the source deliberately -Read `get_generation_source` and `list_models` before the first request when the source or model is not already known in this conversation. +Read `get_generation_source` and `list_models` before the first request when the source or model is not already known in this conversation. If `list_models` is empty or lacks a model the user names, call `refresh_models` once; it generates nothing and is not billed. A hosted (Cloudflare) server always uses source `api`. After a job is `done`, call `view_image` to show it when the client has no inline views. - `queue` means the local Codex runner using the ChatGPT plan. It requires the machine and runner to be available. A queued request is not proof that generation has started. - `api` means a separately billed OpenAI API call using the locally configured key. A working ChatGPT plan does not provide API credit. @@ -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 verified size profile. The final image may be fitted down from a supported provider size; 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 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. 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/actions/index.ts b/src/actions/index.ts index 0a84fe4..8b116c1 100644 --- a/src/actions/index.ts +++ b/src/actions/index.ts @@ -2,7 +2,7 @@ import { generationPreferenceSchema, saveGenerationPreference } from "@/core/generation-preference"; import { UserFacingError, publicErrorMessage } from "@/core/user-facing-error"; import { requireReleaseProvider } from "@/core/release-providers"; -import { applyVerifiedModelProfiles } from "@/core/model-profiles"; +import { applyVerifiedModelProfiles, assertModelOptions } from "@/core/model-profiles"; import { purgeInput } from "@/core/purge-plan"; import { retentionInput } from "@/core/retention"; import { prepareCorrection, workspaceCorrectionSchema } from "@/core/prepare-correction"; @@ -11,13 +11,14 @@ import { pathsSchema, savePaths } from "@/core/paths"; import { revalidatePath } from "next/cache"; import { headers } from "next/headers"; import { changeProcessing, processingInput } from "@/core/processing"; -import { after } from "next/server"; import { createSafeActionClient } from "next-safe-action"; import { z } from "zod"; import { verifyAccess } from "@/core/access"; import { localRequestDenied } from "@/core/local-request"; import { poolSchema, savePoolConfig } from "@/core/pool"; -import { enqueue, retryBlockedQueueJob, retryImageJob, service } from "@/core/runtime"; +import { requestsForCount } from "@/core/request-count"; +import { dispatch, enqueue, retryBlockedQueueJob, retryImageJob, service } from "@/core/runtime"; +import { configuration } from "@/core/config"; import { idSchema, projectSchema, requestSchema, retryImageSchema, settingsSchema, type Job, type Model } from "@/core/schema"; import { saveKey, removeKey, readKey } from "@/core/settings"; import { reservationRecoveryInput, inspectReservedResult } from "@/core/reservation-recovery"; @@ -35,24 +36,12 @@ const action = createSafeActionClient({ await verifyAccess(requestHeaders.get("cf-access-jwt-assertion")); return next(); }); -async function submit(job: Job, api: Awaited>) { - if (job.source === "queue" || (await import("@/core/config")).configuration("STORAGE_DRIVER") !== "cloudflare") return enqueue(job.id); - after(async () => { - try { - await enqueue(job.id); - } catch (error) { - await api.store.lock(job.id, async () => { - const current = await api.store.get("jobs", job.id); - if (current?.status !== "queued") return; - await api.store.put("jobs", job.id, { - ...current, - status: "failed", - error: error instanceof UserFacingError ? error.message : "Generation failed", - updatedAt: new Date().toISOString(), - }); - }); - } - }); +async function submit(job: Job, _api?: Awaited>) { + // Locally a queue job is appended to the worker queue and a provider job leaves + // a durable ticket for the API runner, so both are safe to do in this call. + if (job.source === "queue" || configuration("STORAGE_DRIVER") !== "cloudflare") return enqueue(job.id); + // Cloudflare runs provider jobs from its generation queue. + return dispatch(job.id); } export const createProjectAction = action @@ -78,23 +67,32 @@ export const generationSourceAction = action }); export const requestImageAction = action - .inputSchema(requestSchema) + .inputSchema(requestSchema.extend({ count: z.number().int().min(1).max(10).optional() })) .action(async ({ parsedInput }) => { + const { count, ...request } = parsedInput; + const expanded = requestsForCount(request, count ?? 1).map(item => requestSchema.parse(item)); const api = await service(); - if (parsedInput.source === "api") { - requireReleaseProvider(parsedInput.provider); - const models = applyVerifiedModelProfiles((await api.store.get("models", parsedInput.provider)) ?? []); - const profile = sizeProfileSchema.safeParse(models?.find(model => model.id === parsedInput.model)?.sizeProfile); - if (!profile.success) + if (request.source === "api") { + requireReleaseProvider(request.provider); + const models = applyVerifiedModelProfiles((await api.store.get("models", request.provider)) ?? []); + const model = models.find(entry => entry.id === request.model); + const profile = sizeProfileSchema.safeParse(model?.sizeProfile); + if (!model || !profile.success) throw new UserFacingError("This model has no valid size profile. Choose another model or refresh its configuration."); - resolveModelSize(profile.data, parsedInput); - await readKey(api.store, parsedInput.provider); + assertModelOptions(model, request); + resolveModelSize(profile.data, request); + await readKey(api.store, request.provider); + } + if (request.projectId === "inbox") await api.ensureInbox(); + const jobs = []; + for (const item of expanded) { + const job = await api.create(item); + await submit(job, api); + jobs.push(job); } - if (parsedInput.projectId === "inbox") await api.ensureInbox(); - const job = await api.create(parsedInput); - await submit(job, api); revalidatePath("/"); - return job; + const [first] = jobs; + return (count ?? 1) > 1 ? { ...first, jobs } : first; }); export const retryBlockedQueueAction = action .inputSchema(z.object({ ids: z.array(idSchema).min(1).max(1000) })) diff --git a/src/app/api/asset/route.ts b/src/app/api/asset/route.ts index 3f60352..4adaed3 100644 --- a/src/app/api/asset/route.ts +++ b/src/app/api/asset/route.ts @@ -5,6 +5,17 @@ import { hash, type Job } from "@/core/schema"; import { thumbnail } from "@/sources/thumbnail"; import { storage } from "@/storage"; const pendingThumbnails = new Map>(); +const svgPolicy = "default-src 'none'; style-src 'unsafe-inline'; sandbox"; + +function imageHeaders(mime: string, cacheControl: string, extra?: Record) { + return { + "Content-Type": mime, + "Cache-Control": cacheControl, + "X-Content-Type-Options": "nosniff", + ...(mime === "image/svg+xml" ? { "Content-Security-Policy": svgPolicy } : {}), + ...extra, + }; +} function renderThumbnail(bytes: Uint8Array, size: number, key: string) { if (configuration("STORAGE_DRIVER") === "cloudflare") return thumbnail(bytes, size); @@ -120,17 +131,14 @@ export async function GET(request: Request) { } } return new Response(blob.bytes as BodyInit, { - headers: { - "Content-Type": blob.mime, - ...(blob.mime.startsWith("video/") ? { + headers: imageHeaders( + blob.mime, + params.has("thumb") ? "private, max-age=31536000, immutable" : "private, max-age=86400", + blob.mime.startsWith("video/") ? { "Accept-Ranges": "bytes", "Content-Length": String(blob.bytes.byteLength), - } : {}), - "Cache-Control": params.has("thumb") - ? "private, max-age=31536000, immutable" - : "private, max-age=86400", - "X-Content-Type-Options": "nosniff", - }, + } : undefined, + ), }); } catch { return new Response("Not found", { status: 404 }); diff --git a/src/app/api/mcp/route.ts b/src/app/api/mcp/route.ts index 066a5f6..f779796 100644 --- a/src/app/api/mcp/route.ts +++ b/src/app/api/mcp/route.ts @@ -1,3 +1,4 @@ +import { AccessForbidden, verifyAccess } from "@/core/access"; import { configuration } from "@/core/config"; import { localRequestDenied } from "@/core/local-request"; import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/server"; @@ -10,20 +11,48 @@ const sessions = new Map(); +function sameSecret(actual: string | null, expected: string) { + const encoder = new TextEncoder(); + const left = encoder.encode(actual ?? ""); + const right = encoder.encode(expected); + let difference = left.length ^ right.length; + for (let index = 0; index < right.length; index++) + difference |= (left[index] ?? 0) ^ right[index]!; + return difference === 0; +} + +const unauthorized = () => new Response("Unauthorized", { + status: 401, + headers: { "Cache-Control": "no-store", "WWW-Authenticate": "Bearer" }, +}); + async function handle(request: Request) { if (localRequestDenied(request)) return new Response("Access denied", { status: 403 }); - const token = configuration("MCP_TOKEN"); - if (!token || request.headers.get("authorization") !== `Bearer ${token}`) - return new Response("Unauthorized", { status: 401 }); // Cloudflare requests may be routed to different isolates. if (configuration("STORAGE_DRIVER") === "cloudflare") { + // Cloudflare Access (browser session or Managed OAuth token) is the only + // credential for the hosted endpoint; a static bearer token is local-only. + try { + await verifyAccess(request.headers.get("cf-access-jwt-assertion")); + } catch (error) { + // A signed-in but unlisted identity must not restart OAuth in a loop. + if (error instanceof AccessForbidden) + return new Response("Forbidden", { status: 403, headers: { "Cache-Control": "no-store" } }); + return unauthorized(); + } if (request.method !== "POST") return new Response(null, { status: 405 }); const transport = new WebStandardStreamableHTTPServerTransport({ enableJsonResponse: true }); - await createServer().connect(transport); + // Stateless: a new server per request never sees the host's initialize, so + // the MCP Apps views are always listed (hosts without MCP Apps ignore them). + await createServer({ appViews: "always", panelUrl: new URL(request.url).origin }).connect(transport); return transport.handleRequest(request); } + const token = configuration("MCP_TOKEN"); + if (!token || !sameSecret(request.headers.get("authorization"), `Bearer ${token}`)) + return unauthorized(); + const now = Date.now(); for (const [id, session] of sessions) { if (session.expiresAt > now) continue; diff --git a/src/app/globals.css b/src/app/globals.css index 1f92186..71198e7 100644 --- a/src/app/globals.css +++ b/src/app/globals.css @@ -90,7 +90,8 @@ --stage: #06070a; --border: #272a3a; --border-strong: #3f4459; - --border-input: #72778e; + /* 3.5:1 on --bg and 3.2:1 on --surface-1: the boundary of a text field, no brighter than needed. */ + --border-input: #62677d; --text: #eceef5; --text-soft: #c1c5d4; --text-muted: #989db0; @@ -296,19 +297,22 @@ svg { margin-top: auto; padding-top: 20px; } -.queue-health { - display: flex; - align-items: center; - gap: 9px; - margin: 18px 12px; +/* Sidebar: the generation source in use, its model and its state. */ +.generation-status { + display: grid; + gap: 6px; + margin: 18px 0; font-size: 11px; } -.queue-health div span { - display: block; - color: var(--muted-fg); - font-size: 10px; - margin-top: 4px; -} +.generation-status-label, +.generation-status-value, +.generation-status-note { padding-inline: 12px; } +.generation-status-label { color: var(--muted-fg); } +.generation-status-value { font-size: 12px; font-weight: 500; } +.generation-status-note { color: var(--muted-fg); font-size: 10px; line-height: 1.4; } +/* The trigger text starts on the same edge as the label and the note. */ +.generation-status [data-slot="select-trigger"] { height: 28px; font-size: 11px; min-width: 0; padding-left: 12px; } +.generation-status [data-slot="select-value"] { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .profile { display: flex; @@ -705,10 +709,15 @@ h1 span { max-width: 835px; margin: 9px auto 0; display: flex; + flex-wrap: wrap; justify-content: space-between; font-size: 9px; color: var(--muted-fg); } +.composer-hint > p { + flex-basis: 100%; + margin: 0; +} .composer-hint strong { font-weight: 450; } @@ -985,7 +994,7 @@ dd { .section-label, .project-nav, .add-project, - .queue-health, + .generation-status, .profile > div, .profile > button { display: none; @@ -2086,7 +2095,7 @@ button.composer-restore, .sidebar > :not(.project-nav) { flex-shrink: 0; } @media (min-width: 601px) and (max-height: 800px) { .sidebar .brand { margin-bottom: 20px; } - .sidebar .queue-health { margin-block: 10px; } + .sidebar .generation-status { margin-block: 10px; } .sidebar .sidebar-bottom { padding-top: 8px; } .sidebar .profile { margin-top: 8px; padding-block: 12px; } } @@ -2184,11 +2193,25 @@ button.composer-restore, --color-input: var(--border-input); --color-destructive: var(--danger); } -:root:not([data-theme="light"]) :is([data-slot="input"], [data-slot="textarea"], [data-slot="select-trigger"]) { +/* Text fields are sunken. A select opens a menu, so its trigger reads as a button. */ +:root:not([data-theme="light"]) :is([data-slot="input"], [data-slot="textarea"]) { background: var(--bg); border-color: var(--border-input); color: var(--text); } +:root:not([data-theme="light"]) [data-slot="select-trigger"] { + background: var(--surface-2); + border-color: var(--border-strong); + color: var(--text); +} +:root:not([data-theme="light"]) [data-slot="select-trigger"]:is(:hover, [aria-expanded="true"]):not(:disabled) { + background: var(--surface-3); +} +/* An unchecked box is an empty field: the same sunken fill and 3:1 boundary. */ +:root:not([data-theme="light"]) [data-slot="checkbox"]:not([data-checked], [data-indeterminate]) { + background: var(--bg); + border-color: var(--border-input); +} :root:not([data-theme="light"]) :is(input, textarea)::placeholder, :root:not([data-theme="light"]) [data-slot="select-trigger"][data-placeholder] { color: var(--text-faint); diff --git a/src/app/settings/settings.css b/src/app/settings/settings.css index 8b4c640..b0742ab 100644 --- a/src/app/settings/settings.css +++ b/src/app/settings/settings.css @@ -115,7 +115,7 @@ .settings-list-row { display: flex; flex-wrap: wrap; align-items: center; gap: 12px; padding: 8px 0; font-size: 13px; } .settings-list-row + .settings-list-row { border-top: 1px solid var(--border); } .settings-list-name { font-weight: 500; } -/* The model count and a connection test result share one cell; a result replaces the count in place. */ +/* The model count and a failed connection test share one cell; an error replaces the count in place. */ .settings-list-meta { display: grid; flex: 1 1 0; min-width: min(100%, 12rem); line-height: 1.5; overflow-wrap: anywhere; color: var(--muted-fg); } .settings-meta-text { grid-area: 1 / 1; } .settings-meta-text[data-result] { color: var(--foreground); } @@ -148,9 +148,7 @@ } .settings-card-footer > [data-slot="button"]:last-child { margin-left: auto; } .settings-footer-status { display: grid; gap: 2px; min-width: 0; } -.settings-footer-hint, .provider-connection-status, .provider-success { margin: 0; font-size: 13px; line-height: 1.5; overflow-wrap: anywhere; } -.settings-footer-hint, .provider-connection-status { color: var(--muted-fg); } -.provider-success { color: var(--foreground); } +.settings-footer-hint, .provider-connection-status { margin: 0; font-size: 13px; line-height: 1.5; overflow-wrap: anywhere; color: var(--muted-fg); } /* One control height per card. */ .settings-card :is([data-slot="input"], [data-slot="select-trigger"], [data-slot="button"]) { height: var(--settings-control); } @@ -234,6 +232,8 @@ .config-folder-button { justify-self: start; margin-top: 4px; } +/* Numbered steps inside a settings row: the row's hint size, full-contrast text. */ +.settings-steps { margin: 0; padding-left: 20px; display: grid; gap: 6px; list-style: decimal; font-size: 13px; line-height: 1.5; } .processing-limits { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 10rem), 1fr)); diff --git a/src/app/website/setup-prompt.tsx b/src/app/website/setup-prompt.tsx index 4422b2a..cb99fbf 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.1.5. 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.0. 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/agent-connection.tsx b/src/components/agent-connection.tsx index 07591c8..7cd740e 100644 --- a/src/components/agent-connection.tsx +++ b/src/components/agent-connection.tsx @@ -2,7 +2,7 @@ import { useState } from "react"; import { Toggle, ToggleGroup } from "@ui-sdk/react/toggle"; -import { mcpConfigurations, type McpLaunch } from "@/core/mcp-configuration"; +import { mcpConfigurations, remoteMcpClients, type McpLaunch } from "@/core/mcp-configuration"; import { Button } from "./ui/button"; import { FolderOpen } from "@phosphor-icons/react"; import { openAgentConfigDirectoryAction } from "@/actions"; @@ -13,8 +13,83 @@ const destinations: Record = { "Claude Code": <>Paste into .mcp.json in your project., }; +/** Connect an agent to a hosted deployment: the remote server URL, then the steps or command for each client. */ +function RemoteAgentConnection({ origin, onNotice }: { origin: string; onNotice: (message: string) => void }) { + const { url, clients } = remoteMcpClients(origin); + const [name, setName] = useState(clients[0].name); + const client = clients.find(entry => entry.name === name) ?? clients[0]; + const copyFailed = () => onNotice("Unable to copy. Select and copy the text."); + + return
      +
      +

      Connect an agent

      +

      Add this workspace to Claude, Claude Code or Codex as a remote MCP server, then request and view images from a chat, also on your phone.

      +
      +
      +
      + Server URL + Remote MCP over HTTP. Each client signs in through this workspace's sign-in page; no key is copied into the client. +
      +
      +
      + URL + onNotice("Server URL copied")} onError={copyFailed}> + Copy + +
      +
      {url}
      +
      +
      +
      +
      +
      + Add to your client + {client.note} +
      + { if (values[0]) setName(values[0] as string); }}> + {clients.map(entry => {entry.name})} + +
      + {"steps" in client && client.steps + ? <> +
        {client.steps.map(step =>
      1. {step}
      2. )}
      + {"after" in client && {client.after}} + + : "value" in client &&
      +
      + {client.format} + onNotice(`${client.name} command copied`)} onError={copyFailed}> + Copy + +
      +
      {client.value}
      +
      } +
      +
      +

      + Image requests from a connected agent use this workspace's default generation source and are billed to its provider key. +

      +
      +
      ; +} + /** Connect an agent: server facts, one build step, then the client configuration to paste. */ -export function AgentConnection({ launch, dashboardOrigin, onNotice, platform }: { +export function AgentConnection({ launch, dashboardOrigin, onNotice, platform, remote = false }: { + platform?: string; + launch?: McpLaunch; + dashboardOrigin?: string; + onNotice: (message: string) => void; + /** A hosted deployment has no local stdio server; clients connect to its remote endpoint. */ + remote?: boolean; +}) { + if (remote) return dashboardOrigin ? : null; + return ; +} + +function LocalAgentConnection({ launch, dashboardOrigin, onNotice, platform }: { platform?: string; launch?: McpLaunch; dashboardOrigin?: string; diff --git a/src/components/connected-provider-row.tsx b/src/components/connected-provider-row.tsx index dc8c1a2..bb99e17 100644 --- a/src/components/connected-provider-row.tsx +++ b/src/components/connected-provider-row.tsx @@ -16,19 +16,23 @@ export function connectionWorksMessage(models: number) { /** * One connected provider: its model count, a connection test with the stored key, and disconnect. - * The test result replaces the model count in place. `revision` changes whenever the stored key is - * replaced; a result checked against an older key is never shown. + * A failed test replaces the model count in place. A successful test leaves the count and reports + * its confirmation through `onConfirmed`. `revision` changes whenever the stored key is replaced; + * a result checked against an older key is never shown. */ -export function ConnectedProviderRow({ provider, label, count, revision = 0, onDisconnect }: { +export function ConnectedProviderRow({ provider, label, count, revision = 0, onDisconnect, onConfirmed }: { provider: Provider; label: string; count: number; revision?: number; onDisconnect: () => Promise; + onConfirmed?: (message: string) => void; }) { // Key revision of the test in flight; guards repeated clicks for the same key. const running = useRef(undefined); const nextId = useRef(0); + const revisionNow = useRef(revision); + revisionNow.current = revision; const [testingRevision, setTestingRevision] = useState(); const [result, setResult] = useState(); const testing = testingRevision === revision; @@ -49,20 +53,27 @@ export function ConnectedProviderRow({ provider, label, count, revision = 0, onD if (running.current === started) return; running.current = started; setTestingRevision(started); - let message: string; + let outcome: { ok: true; models: number } | { ok: false; message: string }; try { const response = await testConnectionAction({ provider }); - message = response?.data - ? connectionWorksMessage(response.data.models) - : response?.serverError ?? "The connection could not be checked. Try again."; + outcome = response?.data + ? { ok: true, models: response.data.models } + : { ok: false, message: response?.serverError ?? "The connection could not be checked. Try again." }; } catch { - message = "The connection could not be checked. Try again."; + outcome = { ok: false, message: "The connection could not be checked. Try again." }; } finally { if (running.current === started) running.current = undefined; setTestingRevision(value => value === started ? undefined : value); } - const id = ++nextId.current; // Revisions only grow, so a result for an older key never replaces a newer one. + if (revisionNow.current !== started) return; + if (outcome.ok) { + setResult(undefined); + onConfirmed?.(connectionWorksMessage(outcome.models)); + return; + } + const id = ++nextId.current; + const message = outcome.message; setResult(value => value && value.keyRevision > started ? value : { message, id, keyRevision: started }); } diff --git a/src/components/workspace.tsx b/src/components/workspace.tsx index 083e2ec..f0b6f8a 100644 --- a/src/components/workspace.tsx +++ b/src/components/workspace.tsx @@ -1,4 +1,6 @@ "use client"; +import { extensionForMime, extensionForOutputFormat, referenceFormatError } from "@/core/image-format"; +import type { ImageComplexity, ImageOutputFormat, ImageQuality } from "@/core/model-profiles"; import { isSizeMismatchError } from "@/core/job-recovery"; import { reservationTime } from "@/core/reservation-time"; import { customSizesStorageKey, readCustomSizes, rememberCustomSize } from "@/core/custom-sizes"; @@ -208,6 +210,10 @@ function closestCustomDimensions(width: number, ratio: string, profile?: SizePro } } +const qualityLabels: Record = { auto: "Auto quality", low: "Low quality", medium: "Medium quality", high: "High quality", xhigh: "Extra high quality", max: "Max quality" }; +const complexityLabels: Record = { low: "Low complexity", medium: "Medium complexity", high: "High complexity" }; +const formatLabels: Record = { png: "PNG", webp: "WebP", jpeg: "JPEG", gif: "GIF", svg: "SVG" }; + export function Workspace({ initialProject = "all", initialJob, @@ -348,6 +354,10 @@ export function Workspace({ } }, []); const [variants, setVariants] = useState("1"); + const [quality, setQuality] = useState<"" | ImageQuality>(""); + const [complexity, setComplexity] = useState<"" | ImageComplexity>(""); + const [outputFormat, setOutputFormat] = useState("png"); + const [frameCount, setFrameCount] = useState("9"); const [destination, setDestination] = useState(""); const [searchExpanded, setSearchExpanded] = useState(false); const [search, setSearch] = useState(""); @@ -455,13 +465,22 @@ export function Workspace({ const [busy, setBusy] = useState(false); const [pendingRecovery, setPendingRecovery] = useState<{ jobId: string; action: "retry" | "mark-failed" }>(); const detailPendingRecovery = pendingRecovery?.jobId === detailJob?.id ? pendingRecovery?.action : undefined; - const [notice, setNotice] = useState(""); - const [providerSuccess, setProviderSuccess] = useState(""); + const [notice, setNoticeText] = useState(""); + // Provider confirmations toast on Settings. Other notices there stay in the page banner. + const [noticeToast, setNoticeToast] = useState(false); + const setNotice = useCallback((message: string) => { + setNoticeToast(false); + setNoticeText(message); + }, []); + const showConfirmation = useCallback((message: string) => { + setNoticeToast(true); + setNoticeText(message); + }, []); // Bumps per provider whenever its key is replaced, so a connection test of the old key is dropped. const [keyRevisions, setKeyRevisions] = useState>>({}); useEffect(() => { if (selected) setNotice(""); - }, [selected?.id]); + }, [selected?.id, setNotice]); const [undoHistory, setUndoHistory] = useState([]); const undoId = undoHistory.at(-1); @@ -470,7 +489,7 @@ export function Workspace({ const showRetentionNotice = useCallback((message: string, undoable: boolean) => { setNotice(message); setUndoNotice(undoable ? message : undefined); - }, []); + }, [setNotice]); const undoPending = useRef(false); const [undoBusy, setUndoBusy] = useState(false); const [dark, setDark] = useState(true); @@ -819,6 +838,7 @@ export function Workspace({ }, [measureFilters, queuePage, showFilterRow]); const [reservationReviewId,setReservationReviewId]=useState(); const health = data.localRunner ? (data.localRunner.paused ? "Workers paused" : data.localRunner.blockedReason ? "Local execution needs attention" : data.localRunner.enabled === 0 ? "Workers paused" : data.localRunner.running ? `${data.localRunner.running} generating` : "Ready for requests") : workerHealth(data.pool, data.pulses, healthNow); + const queueNote = (!data.localRunner && !data.pulses.length && !data.jobs.some(job => job.source === "queue")) ? "Not configured" : health; const stoppedJob = data.localRunner?.blockedJobId ? data.jobs.find(job => job.id === data.localRunner?.blockedJobId) : undefined; const workersPaused = data.processing?.paused || (data.processing?.queue.paused ?? data.localRunner?.paused ?? (data.localRunner ? data.localRunner.enabled === 0 : data.pool.workers === 0)); const slotsWithoutHeartbeat = Array.from({ length: data.pool.workers }, (_, index) => index + 1) @@ -842,6 +862,10 @@ export function Workspace({ } }, [data.models, provider, settingsPage]); const models = modelsWithSizeProfiles(data.models).filter((m) => m.provider === "openai"); + // What the sidebar says under the generation controls: the state of the source in use. + const generationNote = source === "queue" ? queueNote + : models.length ? "Billed to your OpenAI key" + : connectedProviders.length ? "No models loaded. Open Settings." : "No provider connected. Open Settings."; useEffect(() => { if (source !== "api") return; const compatible = models.filter(entry => refs.length === 0 || entry.references); @@ -907,18 +931,58 @@ export function Workspace({ }, [sizes, size, customDimensionsSelected, loaded, customSizesLoaded]); const selectedModel = models.find((item) => item.id === model); const correctionNeedsConnection = source === "api" && models.length === 0; - const correctionSourceError = source === "api" - ? !selectedModel ? "Connect OpenAI in Settings and choose an image model." - : !selectedModel.references ? "Choose a model that supports reference images." - : detailJob?.transparent && (!detailJob.imported || detailJob.opacityVerified) && !selectedModel.transparency - ? "This image has transparency. Choose a source that supports transparent images." - : "" - : ""; + const correctionSourceError = referenceFormatError(detailJob?.outputFormat) + ?? (source === "api" + ? !selectedModel ? "Connect OpenAI in Settings and choose an image model." + : !selectedModel.references ? "Choose a model that supports reference images." + : detailJob?.transparent && (!detailJob.imported || detailJob.opacityVerified) && !selectedModel.transparency + ? "This image has transparency. Choose a source that supports transparent images." + : "" + : ""); const transparencyAllowed = source === "queue" || selectedModel?.transparency === true; useEffect(() => { if (!transparencyAllowed) setTransparent(false); }, [transparencyAllowed]); + const qualityOptions = useMemo( + () => (selectedModel?.qualities ?? []).filter(value => value !== "auto"), + [selectedModel], + ); + const complexityOptions = selectedModel?.complexities ?? []; + const orderedFormats = useMemo(() => { + const listed = selectedModel?.outputFormats ?? []; + const unique = listed.filter((value, index) => listed.indexOf(value) === index); + return unique.includes("png") + ? ["png" as const, ...unique.filter(value => value !== "png")] + : unique; + }, [selectedModel]); + const vectorFormats = orderedFormats.some(value => value === "gif" || value === "svg"); + const formatBlocked = (value: string) => (value === "gif" || value === "svg") && (transparent || refs.length > 0); + useEffect(() => { + if (source !== "api" && Number(variants) > 4) setVariants("4"); + }, [source, variants]); + useEffect(() => { + if (source !== "api" || !selectedModel) return; + if (quality && !selectedModel.qualities?.includes(quality)) setQuality(""); + if (complexity && !selectedModel.complexities?.includes(complexity)) setComplexity(""); + if (orderedFormats.length && !orderedFormats.includes(outputFormat)) + setOutputFormat((orderedFormats.includes("png") ? "png" : orderedFormats[0]) as ImageOutputFormat); + if (formatBlocked(outputFormat)) { + const fallback = orderedFormats.find(value => value === "png" || value === "webp" || value === "jpeg") ?? "png"; + setOutputFormat(fallback); + } + if (outputFormat !== "gif" && frameCount !== "9") setFrameCount("9"); + }, [source, selectedModel, quality, complexity, outputFormat, orderedFormats, transparent, refs.length, frameCount]); + const formatConstraint = source !== "api" || !vectorFormats ? "" + : 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 + ? "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." + : ""; const referencesById = useMemo(() => new Map(data.references.map(reference => [reference.id, reference])), [data.references]); const selectedRefs = refs.flatMap(id => { const reference = referencesById.get(id); @@ -1036,28 +1100,50 @@ export function Workspace({ try { const [width, height] = size.split("x").map(Number); const created: string[] = []; - for (let variant = 0; variant < Number(variants); variant++) { + const request = { + ...values, + projectId, + topicId: destinationTopic || undefined, + source, + provider, + model, + resolution: selectedResolution, + exactDimensions: selectedResolution && !customDimensionsSelected ? false : undefined, + aspectRatio: aspectRatios.find(value => { + const [ratioWidth, ratioHeight] = value.split(":").map(Number); + return width * ratioHeight === height * ratioWidth; + }), + width, + height, + transparent, + referenceIds: refs, + }; + const remember = (data: { id: string; jobs?: { id: string }[] } | undefined) => { + if (data?.jobs?.length) created.push(...data.jobs.map(job => job.id)); + else if (data?.id) created.push(data.id); + }; + if (source === "api") { + const count = Number(variants); const result = await requestImageAction({ - ...values, - projectId, - topicId: destinationTopic || undefined, - source, - provider, - model, - resolution: selectedResolution, - exactDimensions: selectedResolution && !customDimensionsSelected ? false : undefined, - aspectRatio: aspectRatios.find(value => { - const [ratioWidth, ratioHeight] = value.split(":").map(Number); - return width * ratioHeight === height * ratioWidth; - }), - width, - height, - transparent, - referenceIds: refs, - idempotencyKey: `${requestKey.current}-${variant}`, + ...request, + idempotencyKey: requestKey.current, + ...(count > 1 ? { count } : {}), + ...(quality ? { quality } : {}), + ...(complexity ? { complexity } : {}), + ...(outputFormat !== "png" ? { outputFormat } : {}), + ...(outputFormat === "gif" && frameCount !== "9" ? { frameCount: Number(frameCount) } : {}), }); showError(result); - if (result?.data?.id) created.push(result.data.id); + remember(result?.data); + } else { + for (let variant = 0; variant < Number(variants); variant++) { + const result = await requestImageAction({ + ...request, + idempotencyKey: `${requestKey.current}-${variant}`, + }); + showError(result); + remember(result?.data); + } } requestKey.current = crypto.randomUUID(); if (form.getValues("prompt") === values.prompt) form.reset(); @@ -1094,7 +1180,8 @@ export function Workspace({ const result = await fetch(asset(job, false)); if (!result.ok) throw new Error("Could not load image reference"); const blob = await result.blob(); - await upload(new File([blob], job.originalName || `${job.id}.png`, { type: blob.type }), undefined, undefined, targetProjectId); + const extension = blob.type ? extensionForMime(blob.type) : extensionForOutputFormat(job.outputFormat); + await upload(new File([blob], job.originalName || `${job.id}.${extension}`, { type: blob.type }), undefined, undefined, targetProjectId); } async function attachReferences(jobs: Job[], files: File[], targetProjectId: string) { @@ -1108,6 +1195,8 @@ export function Workspace({ async function receiveReferences(jobs: Job[], files: File[]) { if (jobs.length + files.length === 0) throw new Error("Select a completed image to add as a reference"); + const blocked = jobs.map(job => referenceFormatError(job.outputFormat)).find(Boolean); + if (blocked) throw new Error(blocked); if (files.some(file => !["image/png", "image/jpeg", "image/webp"].includes(file.type))) throw new Error("References support PNG, JPEG and WebP images"); const referenceCount = refs.length + jobs.length + files.length; @@ -1740,11 +1829,19 @@ export function Workspace({ }} className={`nav-item ${retentionDrop === view ? "bg-accent ring-1 ring-primary" : ""} ${retentionView === view && !settingsPage ? "selected" : ""}`} aria-current={retentionView === view && !settingsPage ? "page" : undefined} onClick={() => {if(settingsPage){router.push(`/?view=${view}`);return;}window.history.replaceState({}, "", `/?view=${view}`);setQueuePage(false);setRetentionView(view);setProject("all");setTopic("");setFilter("all");setSearch("");setTagFilter("");setSelectedIds([]);}}>{view === "archive" ? : }{data.jobs.filter(job => view === "trash" ? job.trashedAt : job.archivedAt && !job.trashedAt).length})}
      -
      -
      - Codex queue - job.source === "queue")) ? "Not configured" : health} /> -
      +
      + Generation + {data.cloud + // The Codex queue needs a local installation, so a hosted workspace has one source. + ? OpenAI API + : void changeDefaultSource(value as typeof source)} + options={[{ value: "api", label: "OpenAI API" }, { value: "queue", label: "Codex queue" }]} />} + {source === "api" && models.length > 0 && { setResolution(""); void changeDefaultSource("api", value); }} + placeholder="Select model" + options={models.map(entry => ({ value: entry.id, label: entry.name, disabled: !entry.sizeProfile }))} />} +
      - +
      ) : ( @@ -2777,7 +2874,7 @@ export function Workspace({ className="compact-select" value={variants} onValueChange={setVariants} - options={[1, 2, 3, 4].map((count) => ({ + options={(source === "api" ? [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] : [1, 2, 3, 4]).map((count) => ({ value: String(count), label: `${count} ${count === 1 ? "image" : "images"}`, }))} @@ -2866,12 +2963,62 @@ export function Workspace({ label: ratioFirstLabel(value), })), ...(supportsCustomSize ? [{value:"custom",label:"Custom size…"}] : [])]} /> + {source === "api" && selectedModel && qualityOptions.length > 0 && ( + setQuality(value as "" | ImageQuality)} + options={[ + { value: "", label: "Auto quality" }, + ...qualityOptions.map(value => ({ value, label: qualityLabels[value] ?? value })), + ]} + /> + )} + {source === "api" && selectedModel && complexityOptions.length > 0 && ( + setComplexity(value as "" | ImageComplexity)} + options={[ + { value: "", label: "Default complexity" }, + ...complexityOptions.map(value => ({ value, label: complexityLabels[value] ?? value })), + ]} + /> + )} + {source === "api" && selectedModel && orderedFormats.length > 0 && ( + setOutputFormat(value as ImageOutputFormat)} + options={orderedFormats.map(value => ({ + value, + label: formatLabels[value] ?? value, + disabled: formatBlocked(value), + }))} + /> + )} + {source === "api" && outputFormat === "gif" && ( + { + const count = String(index + 2); + return { value: count, label: `${count} frames` }; + })} + /> + )}
      - {source === "api" && model && !sizes.length &&

      {unavailableSizeMessage}

      } - {source === "api" && sizeFallback?.after === size && ( -

      - This model does not support {ratioFirstLabel(sizeFallback.before)}. Using {ratioFirstLabel(size)}. -

      - )} - {sizeAdaptation &&

      {sizeAdaptation}

      }
      + {source === "api" && model && !sizes.length &&

      {unavailableSizeMessage}

      } + {source === "api" && sizeFallback?.after === size && ( +

      + This model does not support {ratioFirstLabel(sizeFallback.before)}. Using {ratioFirstLabel(size)}. +

      + )} + {sizeAdaptation &&

      {sizeAdaptation}

      } + {formatConstraint &&

      {formatConstraint}

      } {(source === "queue" ? queueRequestsNotice : apiNotice) && {source === "api" ? "API processing unavailable · requests will wait" : workersPaused ? "Queue paused · requests will wait" : "Queue unavailable · requests will wait"}} {source === "queue" @@ -2933,7 +3081,7 @@ export function Workspace({ {notice && - !(settings || newProject || selected || library) && ( + !(newProject || selected || library || (settings && !noticeToast)) && ( setNotice("")} action={notice === "Connect this provider in Settings first" ? Open settings @@ -3194,7 +3342,7 @@ export function Workspace({

      {detailJob.imported ? "Imported" : detailJob.source === "queue" ? "Codex queue" : providerLabels[detailJob.provider]}{!detailJob.imported && detailJob.model && ` · ${detailJob.model}`}

      -

      {detailJob.width} × {detailJob.height}{(!detailJob.imported || detailJob.opacityVerified) && <> · {detailJob.transparent ? "Transparent" : "Opaque"}} · {new Date(detailJob.createdAt).toLocaleString(undefined, { dateStyle: "medium", timeStyle: "short" })}

      +

      {detailJob.width} × {detailJob.height}{(!detailJob.imported || detailJob.opacityVerified) && <> · {detailJob.transparent ? "Transparent" : "Opaque"}}{(detailJob.outputFormat || (detailJob.source === "api" && !detailJob.imported)) && ` · ${formatLabels[detailJob.outputFormat ?? "png"] ?? "PNG"}`}{detailJob.quality && ` · ${qualityLabels[detailJob.quality] ?? detailJob.quality}`}{detailJob.complexity && ` · ${complexityLabels[detailJob.complexity] ?? detailJob.complexity}`} · {new Date(detailJob.createdAt).toLocaleString(undefined, { dateStyle: "medium", timeStyle: "short" })}

      {detailJob.exactDimensions === false && detailJob.aspectRatio &&

      Requested aspect ratio · {detailJob.aspectRatio}

      } {detailJob.resolution && @@ -3293,6 +3441,8 @@ export function Workspace({ {detailJob.status === "done" && ( )} + {referenceFormatError(detailJob.outputFormat) && {referenceFormatError(detailJob.outputFormat)}} {(detailJob.status === "done" || (detailJob.status === "blocked" && detailJob.blobKey)) && (

      Loading images…

      "; +export const galleryViewHtml = "

      Loading images…

      "; +export const galleryViewVersion = "ef29184889"; diff --git a/src/mcp/views/gallery.ts b/src/mcp/views/gallery.ts index 882ad10..7e5adce 100644 --- a/src/mcp/views/gallery.ts +++ b/src/mcp/views/gallery.ts @@ -1,5 +1,6 @@ import { layout } from "../../core/layout"; -import { CompactApp, applyDocumentTheme, applyHostStyleVariables } from "./compact-app"; +import { CompactApp, applyDocumentTheme, applyHostFonts, applyHostStyleVariables } from "./compact-app"; +import { loadThumbnail } from "./thumbnail"; const app = new CompactApp({ name: "image-queue-gallery", version: "1.0.0" }); const grid = document.querySelector("#gallery")!; @@ -169,15 +170,11 @@ function fetchPreview(id: string) { const pending = pendingPreviews.get(id); if (pending) return pending; const requestGeneration = generation; - const request = app.readServerResource({ uri: `image-queue://thumbnail/${encodeURIComponent(id)}` }) - .then(resource => { + const request = loadThumbnail(app, id, () => disposed) + .then(url => { if (disposed || generation !== requestGeneration) return; - const asset = resource.contents.find(value => "blob" in value); - if (asset && "blob" in asset && asset.mimeType?.startsWith("image/")) { - const url = `data:${asset.mimeType};base64,${asset.blob}`; - rememberPreview(id, url); - return url; - } + rememberPreview(id, url); + return url; }) .finally(() => { if (pendingPreviews.get(id) === request) pendingPreviews.delete(id); @@ -309,6 +306,7 @@ app.onhostcontextchanged = context => { updateDisplayMode(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; generation++; resizeObserver.disconnect(); window.removeEventListener("scroll", positionImages); viewport?.removeEventListener("scroll", positionImages); cardsById.clear(); items.clear(); orderedItems = []; positions.clear(); clearPreviews(); selected.clear(); geometry = undefined; grid.replaceChildren(); return {}; }; app.connect().then(() => { @@ -317,4 +315,5 @@ app.connect().then(() => { if (context) updateDisplayMode(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); }).catch(() => { if (!disposed) status.textContent = "Unable to connect to the host."; }); diff --git a/src/mcp/views/image-html.ts b/src/mcp/views/image-html.ts index 47e9bab..88dbddd 100644 --- a/src/mcp/views/image-html.ts +++ b/src/mcp/views/image-html.ts @@ -1,2 +1,3 @@ // Generated by scripts/build-mcp-views.ts -export const imageViewHtml = "

      Loading image…

        "; +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"; diff --git a/src/mcp/views/image.ts b/src/mcp/views/image.ts index 62bcfc2..50249ba 100644 --- a/src/mcp/views/image.ts +++ b/src/mcp/views/image.ts @@ -1,7 +1,14 @@ import { annotationSelection } from "../../core/annotation"; -import { CompactApp, applyDocumentTheme, applyHostStyleVariables } from "./compact-app"; +import { CompactApp, applyDocumentTheme, applyHostFonts, applyHostStyleVariables } from "./compact-app"; +import { loadPreview } from "./thumbnail"; +import { sourceLabel } from "./source-label"; +import { jobStatusLabels } from "../../core/job-status"; +import type { Job } from "../../core/schema"; +import { isMotionReduced } from "../../lib/motion"; +import { nextVersionMode } from "../../core/image-format"; const app = new CompactApp({ name: "image-queue-image", version: "1.0.0" }); const status = document.querySelector("[role=status]")!; +const source = document.querySelector("#source"); const preview = document.querySelector("#preview")!; const notes = document.querySelector("#notes")!; const pins = document.querySelector("#pins")!; @@ -12,11 +19,22 @@ const saveNote = document.querySelector("#save-note")!; const clearPoint = document.querySelector("#clear-point")!; const draftPoint = document.querySelector("#draft-point")!; const queueButton = document.querySelector("#queue-notes")!; +const saved = document.querySelector(".saved"); +const noCorrections = document.querySelector("#no-corrections"); +const noteHint = document.querySelector("#note-hint"); +const hints = { + edit: "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.", + regenerate: "Describe a change and save it. Request next version then generates the whole animation again from its prompt with your saved changes, so other details can differ too.", +}; +/** "edit" changes the image itself, "regenerate" makes an animation again from its prompt, "none" offers no changes (SVG). */ +let nextVersion: "edit" | "regenerate" | "none" = "edit"; let correctionKey: string | undefined; let canQueue = false; let imageId = ""; let notePoint: { x: number; y: number; w?: number; h?: number } | undefined; -let dragStart: { pointerId: number; x: number; y: number } | undefined; +let dragStart: { pointerId: number; x: number; y: number; touch: boolean; clientX: number; clientY: number } | undefined; +/** A finger that moves further than this is scrolling the conversation, not marking the image. */ +const TAP_SLOP_PX = 10; let previousPoint: typeof notePoint; function updateDraftPoint() { draftPoint.hidden = !notePoint; @@ -50,16 +68,20 @@ function cancelAnnotation(event: KeyboardEvent) { } document.addEventListener("keydown", cancelAnnotation); preview.addEventListener("pointerdown", event => { - if (preview.hidden || disposed || dragStart || event.button !== 0) return; + if (preview.hidden || disposed || dragStart || event.button !== 0 || nextVersion !== "edit") return; const point = pointerPosition(event); if (!point) return; - event.preventDefault(); + const touch = event.pointerType === "touch"; previousPoint = notePoint; - dragStart = { pointerId: event.pointerId, ...point }; + dragStart = { pointerId: event.pointerId, ...point, touch, clientX: event.clientX, clientY: event.clientY }; + // A finger keeps scrolling the conversation; only a tap that stays in place marks a point. + // Mouse and pen drag out an area. + if (touch) return; + event.preventDefault(); preview.setPointerCapture(event.pointerId); }); preview.addEventListener("pointermove", event => { - if (!dragStart || dragStart.pointerId !== event.pointerId) return; + if (!dragStart || dragStart.pointerId !== event.pointerId || dragStart.touch) return; const point = pointerPosition(event); if (!point) return; notePoint = annotationSelection(dragStart, point); @@ -69,11 +91,12 @@ preview.addEventListener("pointerup", event => { if (!dragStart || dragStart.pointerId !== event.pointerId) return; const start = dragStart; dragStart = undefined; + if (start.touch && Math.hypot(event.clientX - start.clientX, event.clientY - start.clientY) > TAP_SLOP_PX) return; const point = pointerPosition(event); if (!point || disposed) return; - notePoint = annotationSelection(start, point); + notePoint = start.touch ? { x: start.x, y: start.y } : annotationSelection(start, point); updateDraftPoint(); - status.textContent = "Area selected. Add a note below."; + status.textContent = notePoint.w ? "Area selected. Describe the change." : "Place selected. Describe the change."; noteText.focus(); }); for (const eventName of ["pointercancel", "lostpointercapture"] as const) { @@ -136,8 +159,22 @@ function render(result: { content?: unknown[] }) { } updateDraftPoint(); imageId = data.image.id; - canQueue = data.image.status === "done" && !data.image.archivedAt && data.notes.some((note: { sentInJobId?: string }) => !note.sentInJobId); + nextVersion = ["edit", "regenerate", "none"].includes(data.image.nextVersion) ? data.image.nextVersion : nextVersionMode(data.image); + const correctable = nextVersion !== "none"; + noteForm.hidden = !correctable; + if (saved) saved.hidden = !correctable; + if (noCorrections) noCorrections.hidden = correctable; + if (noteHint && nextVersion !== "none") noteHint.textContent = hints[nextVersion]; + // Only an edit can be about one place: the place goes to the model marked on a copy of the image. + if (nextVersion !== "edit") { + notePoint = undefined; + dragStart = undefined; + updateDraftPoint(); + } + canQueue = correctable && data.image.status === "done" && !data.image.archivedAt && data.notes.some((note: { sentInJobId?: string }) => !note.sentInJobId); queueButton.disabled = !canQueue; + // With nothing to send the button only adds noise; it appears with the first saved note. + queueButton.hidden = !data.notes.some((note: { sentInJobId?: string }) => !note.sentInJobId); const current = ++generation; if (!keepPreview) { preview.hidden = true; @@ -159,7 +196,7 @@ function render(result: { content?: unknown[] }) { item.value = note.sentInJobId ? 0 : pendingNumber; item.id = `note-${notes.childElementCount + 1}`; notes.append(item); - if (!note.sentInJobId && note.x !== undefined && note.y !== undefined) { + if (nextVersion === "edit" && !note.sentInJobId && note.x !== undefined && note.y !== undefined) { const pin = document.createElement("button"); pin.type = "button"; pin.className = "note-pin"; @@ -194,31 +231,36 @@ function render(result: { content?: unknown[] }) { versions.append(button); } } - status.textContent = data.image.status; + // A single version needs no switcher. + versions.hidden = data.versions.length < 2; + const statusLabel = jobStatusLabels[data.image.status as Job["status"]]; + status.textContent = statusLabel; + if (source) source.textContent = sourceLabel(data.image); if (keepPreview) pins.hidden = false; - if (data.image.status === "done" && !keepPreview) void app.readServerResource({ uri: `image-queue://thumbnail/${encodeURIComponent(data.image.id)}` }).then(resource => { + const animated = data.image.outputFormat === "gif" && !isMotionReduced(); + if (data.image.status === "done" && !keepPreview) void loadPreview(app, data.image.id, () => disposed || generation !== current, { animated }).then(({ url }) => { if (disposed || generation !== current) return; - const image = resource.contents.find(item => "blob" in item); - if (image && "blob" in image && image.mimeType?.startsWith("image/")) { - preview.onload = () => { - if (!disposed && generation === current) pins.hidden = false; - }; - preview.onerror = () => { - if (!disposed && generation === current) { - pins.hidden = true; - status.textContent = "Preview unavailable"; - } - }; - preview.src = `data:${image.mimeType};base64,${image.blob}`; - preview.hidden = false; - } - }).catch(() => { if (!disposed && generation === current) status.textContent = "Preview unavailable"; }); + preview.onload = () => { + if (!disposed && generation === current) pins.hidden = false; + }; + preview.onerror = () => { + if (!disposed && generation === current) { + pins.hidden = true; + status.textContent = "Preview unavailable"; + } + }; + preview.src = url; + preview.hidden = false; + }).catch(() => { + // A late preview failure must not replace a message about the user's own action. + if (!disposed && generation === current && status.textContent === statusLabel) status.textContent = "Preview unavailable"; + }); } catch { status.textContent = "Invalid image response."; } } queueButton.addEventListener("click", async () => { if (disposed || queueButton.disabled || !canQueue || !imageId) return; if (saveNote.disabled || noteText.value.trim()) { - status.textContent = "Save your note before adding the correction to the queue."; + status.textContent = "Save your change first, then request the next version."; noteText.focus(); return; } @@ -242,10 +284,10 @@ queueButton.addEventListener("click", async () => { if (!disposed && generation === request) { correctionKey = undefined; await show(target); - if (!disposed && imageId === target) status.textContent = "Correction added to queue."; + if (!disposed && imageId === target) status.textContent = "Next version requested."; } } catch { - if (!disposed && generation === request) status.textContent = "Could not queue correction. Retry to check the same request."; + if (!disposed && generation === request) status.textContent = "Could not request the next version. Retry to check the same request."; } finally { queueButton.disabled = !canQueue; } @@ -270,7 +312,7 @@ noteForm.addEventListener("submit", async event => { await show(target); } } catch { - if (!disposed && generation === request) status.textContent = "Could not save note. Your text is preserved."; + if (!disposed && generation === request) status.textContent = "Could not save the change. Your text is preserved."; } finally { saveNote.disabled = false; } @@ -279,6 +321,7 @@ app.ontoolresult = render; 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; @@ -291,4 +334,5 @@ 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/mcp/views/job-html.ts b/src/mcp/views/job-html.ts index 2bff337..2802cfe 100644 --- a/src/mcp/views/job-html.ts +++ b/src/mcp/views/job-html.ts @@ -1,2 +1,3 @@ // Generated by scripts/build-mcp-views.ts -export const jobViewHtml = "

          Image request

          Connecting to image-queue…

          ";
          +export const jobViewHtml = "

          Image request

          Connecting to image-queue…

          "; +export const jobViewVersion = "bfdc8012bf"; diff --git a/src/mcp/views/job.ts b/src/mcp/views/job.ts index 73c41ae..92e9463 100644 --- a/src/mcp/views/job.ts +++ b/src/mcp/views/job.ts @@ -5,15 +5,16 @@ import { CompactApp, applyDocumentTheme, applyHostStyleVariables, + applyHostFonts, } from "./compact-app"; +import { loadPreview } from "./thumbnail"; +import { sourceLabel } from "./source-label"; +import { isMotionReduced } from "../../lib/motion"; const app = new CompactApp({ name: "image-queue", version: "1.0.0" }); const status = document.querySelector("[role=status]")!; const workerNotice = document.querySelector("#workers-offline"); if (workerNotice) workerNotice.textContent = workersOfflineMessage; const source = document.querySelector("#source"); -const providerLabels = new Map([ - ["openai", "OpenAI"], ["google", "Google"], ["openrouter", "OpenRouter"], ["gateway", "AI Gateway"], -]); const prompt = document.querySelector("#prompt")!; const path = document.querySelector("#path")!; const copyPath = document.querySelector("#copy-path"); @@ -54,6 +55,71 @@ openApp?.addEventListener("click", async () => { openApp.disabled = false; } }); +const download = document.querySelector("#download"); +download?.addEventListener("click", async () => { + if (disposed || !id || download.disabled) return; + const requestedId = id; + download.disabled = true; + download.textContent = "Preparing…"; + try { + if (app.canDownloadFiles()) { + const result = await app.callServerTool({ name: "read_image_file", arguments: { id: requestedId } }); + const file = result?.isError ? undefined : result?.content?.find(item => item.type === "resource"); + if (file?.type !== "resource" || !("blob" in file.resource) || !file.resource.mimeType) throw new Error(); + const saved = await app.downloadFile({ contents: [{ type: "resource", resource: { + uri: file.resource.uri, mimeType: file.resource.mimeType, blob: file.resource.blob } }] }); + if (saved?.isError) throw new Error(); + } else { + // Hosts without file downloads open the full image in the browser instead. + const base = decodeURIComponent(document.body.dataset.dashboard ?? ""); + const url = new URL(`${base}/api/asset?job=${encodeURIComponent(requestedId)}`); + if (!["http:", "https:"].includes(url.protocol) || url.username || url.password) throw new Error(); + const result = await app.openLink({ url: url.href }); + if (result.isError) throw new Error(); + } + } catch { + if (!disposed && id === requestedId) status.textContent = "Ready. Download unavailable."; + } finally { + download.disabled = false; + download.textContent = "Download"; + } +}); +const play = document.querySelector("#play"); +/** People who asked the system for less motion start a GIF themselves. The view's stylesheet decides the mode. */ +const prefersStill = () => isMotionReduced(); +play?.addEventListener("click", async () => { + if (disposed || !id || play.disabled) return; + const requestedId = id; + const stale = () => disposed || id !== requestedId || previewId !== requestedId; + play.disabled = true; + play.textContent = "Loading…"; + try { + let url: string | undefined; + try { + const preview = await loadPreview(app, requestedId, stale, { animated: true }); + if (preview.animated) url = preview.url; + } catch { + // Fall through to the file itself. + } + if (!url) { + // The preview kept one frame only, so play the full file. + const result = await app.callServerTool({ name: "read_image_file", arguments: { id: requestedId } }); + const file = result?.isError ? undefined : result?.content?.find(item => item.type === "resource"); + if (file?.type !== "resource" || !("blob" in file.resource) || !file.resource.mimeType?.startsWith("image/")) throw new Error(); + url = `data:${file.resource.mimeType};base64,${file.resource.blob}`; + } + if (stale()) return; + const element = document.querySelector("#preview"); + if (!element) return; + element.src = url; + play.hidden = true; + } catch { + if (!stale()) status.textContent = "Ready. The animation cannot be played here. Use Download."; + } finally { + play.disabled = false; + play.textContent = "Play animation"; + } +}); let id = ""; let timer: ReturnType | undefined; let visible = true; @@ -97,6 +163,8 @@ function render(result: { content?: unknown[] }) { previewId = ""; id = ""; if (openApp) openApp.hidden = true; + if (download) download.hidden = true; + if (play) play.hidden = true; if (workerNotice) workerNotice.hidden = true; if (source) source.textContent = ""; prompt.textContent = ""; @@ -125,6 +193,7 @@ function render(result: { content?: unknown[] }) { if (id !== job.id) started = Date.now(); if (id !== job.id || job.trashedAt || job.status !== "done") { previewId = ""; + if (play) play.hidden = true; const element = document.querySelector("#preview"); if (element) { element.hidden = true; @@ -134,6 +203,7 @@ function render(result: { content?: unknown[] }) { const placeholder = document.querySelector("#placeholder"); if (placeholder) { placeholder.hidden = Boolean(job.trashedAt) || !["queued", "running", "done"].includes(job.status) || (job.status === "done" && previewId === job.id && Boolean(document.querySelector("#preview")?.getAttribute("src"))); + placeholder.dataset.label = job.status === "queued" ? "Waiting to start…" : job.status === "running" ? "Generating…" : "Loading preview…"; if (Number.isInteger(job.width) && Number.isInteger(job.height) && job.width > 0 && job.height > 0 && job.width <= 32768 && job.height <= 32768) { placeholder.style.aspectRatio = `${job.width} / ${job.height}`; placeholder.style.width = `min(100%, ${420 * job.width / job.height}px)`; @@ -144,10 +214,15 @@ function render(result: { content?: unknown[] }) { preview.width = job.width; preview.height = job.height; preview.style.aspectRatio = `${job.width} / ${job.height}`; + // Same box as the placeholder, so the image keeps its ratio, its rounded corners and its left edge. + preview.style.width = `min(100%, ${420 * job.width / job.height}px)`; + preview.style.height = "auto"; } const jobChanged = id !== job.id; 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); 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 @@ -160,11 +235,7 @@ function render(result: { content?: unknown[] }) { if (notice) workerNotice.textContent = notice; workerNotice.hidden = job.status !== "queued" || !notice || Boolean(job.trashedAt); } - if (source) { - const provider = providerLabels.get(job.provider) ?? "Provider API"; - const model = typeof job.model === "string" && job.model.length <= 200 ? job.model : ""; - source.textContent = job.source === "queue" ? "Codex queue" : job.source === "api" ? [provider, model].filter(Boolean).join(" · ") : job.source === "import" ? "Imported image" : ""; - } + if (source) source.textContent = sourceLabel(job); prompt.textContent = job.prompt; const outputPath = job.outputPath ?? ""; const pathChanged = path.textContent !== outputPath; @@ -177,20 +248,17 @@ function render(result: { content?: unknown[] }) { if (!job.trashedAt && job.status === "done" && previewId !== id) { previewId = id; const requestedId = id; - void app - .readServerResource({ - uri: `image-queue://thumbnail/${encodeURIComponent(requestedId)}`, - }) - .then((result) => { - const image = result.contents.find((item) => "blob" in item); - if (!image || !("blob" in image) || !image.blob || !image.mimeType?.startsWith("image/")) - throw new Error("Preview unavailable"); + const isGif = job.outputFormat === "gif"; + void loadPreview(app, requestedId, () => disposed || id !== requestedId || previewId !== requestedId, { animated: isGif && !prefersStill() }) + .then((preview) => { if (!disposed && id === requestedId && previewId === requestedId) { const element = document.querySelector("#preview")!; if (!element) return; - element.src = `data:${image.mimeType};base64,${image.blob}`; + element.src = preview.url; element.hidden = false; if (placeholder) placeholder.hidden = true; + // A GIF shown as a still gets Play: by choice (reduced motion) or because the preview lost its frames. + if (play) play.hidden = !isGif || preview.animated; } }) .catch(() => { @@ -235,6 +303,7 @@ 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); }; const observer = new IntersectionObserver((entries) => { visible = entries.some((entry) => entry.isIntersecting); @@ -253,6 +322,7 @@ 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/mcp/views/source-label.ts b/src/mcp/views/source-label.ts new file mode 100644 index 0000000..3b128c4 --- /dev/null +++ b/src/mcp/views/source-label.ts @@ -0,0 +1,10 @@ +const providerLabels = new Map([ + ["openai", "OpenAI"], ["google", "Google"], ["openrouter", "OpenRouter"], ["gateway", "AI Gateway"], +]); + +/** "OpenAI · gpt-image-2.6-sunburst", "Codex queue" or "Imported image": where an image came from, for the inline views. */ +export function sourceLabel(job: { source?: unknown; provider?: unknown; model?: unknown }) { + const provider = (typeof job.provider === "string" && providerLabels.get(job.provider)) || "Provider API"; + const model = typeof job.model === "string" && job.model.length <= 200 ? job.model : ""; + return job.source === "queue" ? "Codex queue" : job.source === "api" ? [provider, model].filter(Boolean).join(" · ") : job.source === "import" ? "Imported image" : ""; +} diff --git a/src/mcp/views/thumbnail.ts b/src/mcp/views/thumbnail.ts new file mode 100644 index 0000000..0900813 --- /dev/null +++ b/src/mcp/views/thumbnail.ts @@ -0,0 +1,40 @@ +import type { CompactApp } from "./compact-app"; + +type PreviewApp = Pick; + +/** + * Load a finished image's preview, or reject when it is unavailable. + * The app-only tool goes first: some hosts proxy a view's tool calls but read only + * the ui:// resource a tool names. The private resource stays as the fallback and is + * skipped once the caller no longer wants the preview. `animated` asks for the + * frames of a GIF and reports whether the preview kept them. + */ +export async function loadPreview(app: PreviewApp, id: string, stale: () => boolean, options: { animated?: boolean } = {}) { + try { + const result = await app.callServerTool({ name: "read_thumbnail", arguments: options.animated ? { id, animated: true } : { id } }); + const image = result?.isError ? undefined : result?.content?.find(item => item.type === "image"); + if (image?.type === "image" && image.data && image.mimeType.startsWith("image/")) { + const note = result?.content?.find(item => item.type === "text"); + let animated = false; + try { + animated = note?.type === "text" && JSON.parse(note.text)?.animated === true; + } catch { + // An older server sends the image alone. + } + return { url: `data:${image.mimeType};base64,${image.data}`, animated }; + } + } catch { + // The host or an older server may not offer the tool. + } + if (stale()) throw new Error("Preview no longer needed"); + const resource = await app.readServerResource({ uri: `image-queue://thumbnail/${encodeURIComponent(id)}` }); + const asset = resource?.contents?.find(item => "blob" in item); + if (asset && "blob" in asset && asset.blob && asset.mimeType?.startsWith("image/")) + return { url: `data:${asset.mimeType};base64,${asset.blob}`, animated: false }; + throw new Error("Preview unavailable"); +} + +/** The still preview as a data URL. */ +export async function loadThumbnail(app: PreviewApp, id: string, stale: () => boolean) { + return (await loadPreview(app, id, stale)).url; +} diff --git a/src/sources/image-fit.ts b/src/sources/image-fit.ts index 8b3e8c4..3030c1b 100644 --- a/src/sources/image-fit.ts +++ b/src/sources/image-fit.ts @@ -1,12 +1,21 @@ +import { outputMime } from "../core/image-format"; import { UserFacingError } from "../core/user-facing-error"; import { imageSize } from "image-size"; import { configuration } from "@/core/config"; import { planImageFit } from "@/core/image-fit"; -export async function fitImage(bytes: Uint8Array, target: { width: number; height: number }) { +type RasterFormat = "png" | "webp" | "jpeg" | "gif"; + +export async function fitImage( + bytes: Uint8Array, + target: { width: number; height: number }, + format: RasterFormat = "png", +) { + if (format === "gif") return fitGif(bytes, target); const dimensions = imageSize(bytes); if (!dimensions.width || !dimensions.height) throw new UserFacingError("Cannot read generated image dimensions"); const plan = planImageFit({ width: dimensions.width, height: dimensions.height }, target); + const mime = outputMime[format]; if (configuration("STORAGE_DRIVER") === "cloudflare") { const { getCloudflareContext } = await import("@opennextjs/cloudflare"); const { env } = await getCloudflareContext({ async: true }); @@ -18,7 +27,7 @@ export async function fitImage(bytes: Uint8Array, target: { width: number; heigh }; } }).IMAGES; const output = await images.input(new Blob([bytes as BlobPart]).stream()) - .transform({ ...target, fit: "cover", gravity: "center" }).output({ format: "image/png" }); + .transform({ ...target, fit: "cover", gravity: "center" }).output({ format: mime }); const response = output.response(); if (!response.ok) throw new Error(`Image transformation failed (HTTP ${response.status})`); const fittedBytes = new Uint8Array(await response.arrayBuffer()); @@ -26,11 +35,33 @@ export async function fitImage(bytes: Uint8Array, target: { width: number; heigh if (fittedDimensions.width !== target.width || fittedDimensions.height !== target.height) { throw new UserFacingError("Image transformation returned unexpected dimensions"); } - return { bytes: fittedBytes, mime: "image/png" }; + return { bytes: fittedBytes, mime }; } const sharp = (await import("sharp")).default; - return { - bytes: new Uint8Array(await sharp(bytes).extract(plan.extract).resize(plan.resize).png().toBuffer()), - mime: "image/png", - }; + const pipeline = sharp(bytes).extract(plan.extract).resize(plan.resize); + const encoded = format === "webp" ? pipeline.webp() : format === "jpeg" ? pipeline.jpeg() : pipeline.png(); + return { bytes: new Uint8Array(await encoded.toBuffer()), mime }; +} + +/** Keep every GIF frame. Refuse an upscale; leave exact fitting failures to the caller. */ +async function fitGif(bytes: Uint8Array, target: { width: number; height: number }) { + const dimensions = imageSize(bytes); + if (!dimensions.width || !dimensions.height) throw new UserFacingError("Cannot read generated image dimensions"); + const plan = planImageFit({ width: dimensions.width, height: dimensions.height }, target); + if (configuration("STORAGE_DRIVER") === "cloudflare") + throw new UserFacingError("The generated GIF could not be fitted to the requested dimensions while keeping the animation."); + const sharp = (await import("sharp")).default; + const before = await sharp(bytes, { animated: true }).metadata(); + const pages = before.pages ?? 1; + let fitted: Buffer; + try { + fitted = await sharp(bytes, { animated: true }).extract(plan.extract).resize(plan.resize).gif().toBuffer(); + } catch { + throw new UserFacingError("The generated GIF could not be fitted to the requested dimensions while keeping the animation."); + } + const after = await sharp(fitted, { animated: true }).metadata(); + const frameHeight = after.pageHeight ?? after.height; + if (after.width !== target.width || frameHeight !== target.height || (after.pages ?? 1) !== pages) + throw new UserFacingError("The generated GIF could not be fitted to the requested dimensions while keeping the animation."); + return { bytes: new Uint8Array(fitted), mime: outputMime.gif }; } diff --git a/src/sources/providers.ts b/src/sources/providers.ts index ae10547..11133ed 100644 --- a/src/sources/providers.ts +++ b/src/sources/providers.ts @@ -1,3 +1,5 @@ +import { ImageRequestError, readProviderError } from "../core/api-rejection"; +import { mimeForDetectedType, outputMime, svgDocument } from "../core/image-format"; import { UserFacingError } from "../core/user-facing-error"; import { createOpenRouter } from "@openrouter/ai-sdk-provider"; import { createGateway } from "@ai-sdk/gateway"; @@ -117,9 +119,24 @@ export async function generate( : job.provider === "google" ? { aspectRatio: `${job.width / gcd(job.width, job.height)}:${job.height / gcd(job.width, job.height)}` } : { size: `${job.width}x${job.height}` }; + if ((job.quality || job.complexity) && job.provider !== "openai") + throw new UserFacingError("Quality and complexity settings require an OpenAI image model"); + if (job.outputFormat === "svg") + return generateSvg(job, key, sizeParameters.size, references.length); + if ((job.outputFormat || job.frameCount !== undefined || job.frameDurationMs !== undefined) && job.provider !== "openai") + throw new UserFacingError("Output format and frame settings require an OpenAI image model"); + const rasterFormat = job.outputFormat; + const openaiOptions = { + ...(job.transparent ? { background: "transparent" as const, outputFormat: rasterFormat ?? "png" as const } : {}), + ...(!job.transparent && rasterFormat ? { outputFormat: rasterFormat } : {}), + ...(job.quality ? { quality: job.quality } : {}), + ...(job.complexity ? { complexity: job.complexity } : {}), + ...(rasterFormat === "gif" && job.frameCount !== undefined ? { frameCount: job.frameCount } : {}), + ...(rasterFormat === "gif" && job.frameDurationMs !== undefined ? { frameDurationMs: job.frameDurationMs } : {}), + }; const providerOptions: Parameters[0]["providerOptions"] = job.resolution && job.provider === "google" ? { google: { imageConfig: { imageSize: job.resolution } } } - : job.transparent ? { openai: { background: "transparent" } } : undefined; + : Object.keys(openaiOptions).length ? { openai: openaiOptions } : undefined; const result = await generateImage({ model, prompt: references.length @@ -132,25 +149,123 @@ export async function generate( providerOptions, }); const generatedDimensions = imageSize(result.image.uint8Array); - let output = { bytes: result.image.uint8Array, mime: result.image.mediaType }; + let bytes = result.image.uint8Array; + let mime = mimeOf(bytes); let adaptationError: string | undefined; - if (sizeProfile && job.exactDimensions !== false && (generatedDimensions.width !== job.width || generatedDimensions.height !== job.height)) { + const needsFit = Boolean(sizeProfile && job.exactDimensions !== false && (generatedDimensions.width !== job.width || generatedDimensions.height !== job.height)); + const fitFailure = (error: unknown) => error instanceof UserFacingError + ? `The generated image was saved. ${error.message}` + : "The generated image was saved, but could not be fitted to the requested dimensions without upscaling."; + if (rasterFormat) { + const requestedMime = outputMime[rasterFormat]; + if (mime !== requestedMime) + adaptationError = `The generated image was saved. The provider returned ${mime} instead of the requested ${rasterFormat} output.`; + else if (needsFit) { + const { fitImage } = await import("./image-fit"); + try { + const fitted = await fitImage(bytes, { width: job.width, height: job.height }, rasterFormat); + bytes = fitted.bytes; + mime = mimeOf(bytes); + if (mime !== requestedMime) + adaptationError = `The generated image was saved. The provider returned ${mime} instead of the requested ${rasterFormat} output.`; + } catch (error) { + adaptationError = fitFailure(error); + } + } + } else if (needsFit) { const { fitImage } = await import("./image-fit"); try { - output = await fitImage(output.bytes, { width: job.width, height: job.height }); + const fitted = await fitImage(bytes, { width: job.width, height: job.height }, "png"); + bytes = fitted.bytes; + mime = outputMime.png; } catch (error) { - adaptationError = error instanceof UserFacingError ? `The generated image was saved. ${error.message}` : "The generated image was saved, but could not be fitted to the requested dimensions without upscaling."; + adaptationError = fitFailure(error); } } return { - ...imageSize(output.bytes), - ...output, + ...imageSize(bytes), + bytes, + mime, generatedDimensions, adaptationError, usage: result.usage, }; } +/** Prefer the bytes over the provider's declared media type. */ +function mimeOf(bytes: Uint8Array) { + let detected: string | undefined; + try { detected = mimeForDetectedType(imageSize(bytes).type); } catch { detected = undefined; } + if (detected) return detected; + if (svgDocument(bytes)) return outputMime.svg; + 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", { + method: "POST", + headers: { Authorization: `Bearer ${key}`, "Content-Type": "application/json" }, + body: JSON.stringify(body), + signal: AbortSignal.timeout(240000), + }).catch(() => { + throw new UserFacingError("Could not reach the provider. Check your connection and try again."); + }); + if (response.status === 401) + throw new ImageRequestError(401, "The provider rejected this API key (401). Check the key and try again."); + if (response.status === 403) + throw new ImageRequestError(403, "This API key cannot generate images (403). Check its permissions."); + if (!response.ok) + throw new ImageRequestError( + response.status, + `The provider rejected image generation (${response.status}).`, + await readProviderError(response), + ); + const payload = await response.json().catch(() => { + throw new UserFacingError("The provider returned an unreadable image. Try again later."); + }); + const parsed = z.object({ + data: z.array(z.object({ b64_json: z.string().min(1) })).min(1), + }).safeParse(payload); + if (!parsed.success) + throw new UserFacingError("The provider returned an unreadable image. Try again later."); + let bytes: Uint8Array; + try { + const binary = atob(parsed.data.data[0].b64_json); + bytes = Uint8Array.from(binary, char => char.charCodeAt(0)); + } catch { + throw new UserFacingError("The provider returned an unreadable image. Try again later."); + } + if (!bytes.length || !svgDocument(bytes)) + throw new UserFacingError("The provider returned an unreadable image. Try again later."); + return { + bytes, + mime: outputMime.svg, + width, + height, + generatedDimensions: { width, height }, + adaptationError: undefined, + usage: undefined, + }; +} + function gcd(a: number, b: number): number { return b === 0 ? a : gcd(b, a % b); } diff --git a/src/sources/thumbnail.ts b/src/sources/thumbnail.ts index f44bdee..05663fc 100644 --- a/src/sources/thumbnail.ts +++ b/src/sources/thumbnail.ts @@ -1,5 +1,16 @@ import { configuration } from "@/core/config"; -export async function thumbnail(bytes: Uint8Array, width: number) { +/** True when WebP bytes carry the animation flag of the extended header. */ +export function isAnimatedWebp(bytes: Uint8Array) { + const tag = (offset: number) => String.fromCharCode(...bytes.subarray(offset, offset + 4)); + return bytes.length > 20 && tag(0) === "RIFF" && tag(8) === "WEBP" && tag(12) === "VP8X" && (bytes[20] & 0x02) !== 0; +} + +/** + * A WebP preview of the given width. With animated set, the frames of an + * animated source are kept; whether they survived is reported as `animated`, + * because the hosted image service decides that for itself. + */ +export async function thumbnail(bytes: Uint8Array, width: number, options: { animated?: boolean } = {}) { if (configuration("STORAGE_DRIVER") === "cloudflare") { const { getCloudflareContext } = await import("@opennextjs/cloudflare"); const { env } = await getCloudflareContext({ async: true }); @@ -8,32 +19,34 @@ export async function thumbnail(bytes: Uint8Array, width: number) { transform(options: { width: number }): { output(options: { format: string; + anim?: boolean; }): Promise<{ response(): Response }>; }; }; }; const images = (env as unknown as { IMAGES: Images }).IMAGES; - const output = await images + const transformed = await images .input(new Blob([bytes as BlobPart]).stream()) .transform({ width }) - .output({ format: "image/webp" }); - const response = output.response(); + .output({ format: "image/webp", ...(options.animated ? { anim: true } : {}) }); + const response = transformed.response(); if (!response.ok) throw new Error(`Thumbnail transformation failed (HTTP ${response.status})`); - return { - bytes: new Uint8Array(await response.arrayBuffer()), - mime: "image/webp", - }; + const output = new Uint8Array(await response.arrayBuffer()); + return { bytes: output, mime: "image/webp", animated: isAnimatedWebp(output) }; } const sharp = (await import("sharp")).default; - const { dominant } = await sharp(bytes).stats(); + // The first page is the GIF frame and a rasterized SVG. Previews stay WebP. + const { dominant } = await sharp(bytes, { pages: 1 }).stats(); + const output = new Uint8Array( + await sharp(bytes, options.animated ? { animated: true } : { pages: 1 }) + .resize({ width, withoutEnlargement: true }) + .webp({ quality: 78 }) + .toBuffer(), + ); return { - bytes: new Uint8Array( - await sharp(bytes) - .resize({ width, withoutEnlargement: true }) - .webp({ quality: 78 }) - .toBuffer(), - ), + bytes: output, mime: "image/webp", + animated: isAnimatedWebp(output), dominantColor: `rgb(${dominant.r} ${dominant.g} ${dominant.b})`, }; } diff --git a/src/storage/cloudflare.ts b/src/storage/cloudflare.ts index 4c74d7f..014f431 100644 --- a/src/storage/cloudflare.ts +++ b/src/storage/cloudflare.ts @@ -1,5 +1,8 @@ import { StorageLockBusy, type Storage, safeKey } from "./types"; +/** Lock lease, longer than the 15-minute queue consumer limit. */ +export const lockLease = 20 * 60 * 1000; + interface Database { prepare(sql: string): { bind(...args: unknown[]): { @@ -54,11 +57,20 @@ export class CloudflareStorage implements Storage { .bind(safeKey(collection), safeKey(id)).run(); } async lock(key: string, work: () => Promise) { + const id = safeKey(key); const token = crypto.randomUUID(); + const now = Date.now(); + // A Worker killed while holding a lock never reaches finally; its lease + // lets the next caller take over. The lease outlasts a queue consumer's + // 15-minute limit, so a live holder never loses its lock. + await this.db + .prepare("DELETE FROM locks WHERE id=? AND expires_at IS NOT NULL AND expires_atconsole.error('Local image execution requires attention.'), + report:error=>console.error('Local image execution requires attention.',error instanceof Error?`${error.name}: ${error.message}`:''), }); stopWatching=watchQueue(paths.queueDirectory,()=>executor?.wake()); paused=paused||await globalPause(store); diff --git a/tests/access-fixture.ts b/tests/access-fixture.ts new file mode 100644 index 0000000..eecc8c1 --- /dev/null +++ b/tests/access-fixture.ts @@ -0,0 +1,35 @@ +import { exportJWK, generateKeyPair, SignJWT } from "jose"; +import { vi } from "vitest"; + +export const accessAudience = "image-queue-audience"; +export const allowedEmail = "owner@example.com"; + +/** + * Configures a synthetic Cloudflare Access deployment and serves its signing + * keys. Each call uses its own team domain, because key sets are cached per + * issuer for the life of the process. + */ +export async function syntheticAccess() { + const accessTeam = `team-${crypto.randomUUID()}.cloudflareaccess.com`; + const accessIssuer = `https://${accessTeam}`; + vi.stubEnv("IMAGE_QUEUE_STORAGE_DRIVER", "cloudflare"); + vi.stubEnv("IMAGE_QUEUE_CF_ACCESS_TEAM_DOMAIN", accessTeam); + vi.stubEnv("IMAGE_QUEUE_CF_ACCESS_AUDIENCE", accessAudience); + vi.stubEnv("IMAGE_QUEUE_ACCESS_ALLOWED_EMAILS", ` Owner@Example.com, second@example.com `); + const { publicKey, privateKey } = await generateKeyPair("RS256", { extractable: true }); + const jwk = { ...await exportJWK(publicKey), kid: "fixture", alg: "RS256" }; + const passThrough = globalThis.fetch; + const fetchKeys = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => + String(input) === `${accessIssuer}/cdn-cgi/access/certs` + ? Response.json({ keys: [jwk] }) + : passThrough(input, init)); + vi.stubGlobal("fetch", fetchKeys); + const sign = (claims: { email?: string; audience?: string; issuer?: string; expiration?: string } = {}) => + new SignJWT(claims.email === undefined ? { email: allowedEmail } : { email: claims.email }) + .setProtectedHeader({ alg: "RS256", kid: "fixture" }) + .setIssuer(claims.issuer ?? accessIssuer) + .setAudience(claims.audience ?? accessAudience) + .setExpirationTime(claims.expiration ?? "5m") + .sign(privateKey); + return { sign, fetchKeys, privateKey, issuer: accessIssuer }; +} diff --git a/tests/access.test.ts b/tests/access.test.ts index ffb882e..d7c1743 100644 --- a/tests/access.test.ts +++ b/tests/access.test.ts @@ -2,12 +2,16 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { exportJWK, generateKeyPair, SignJWT } from "jose"; import { verifyAccess } from "../src/core/access"; +import { AccessForbidden } from "../src/core/access"; +import { accessAudience, syntheticAccess } from "./access-fixture"; afterEach(() => { vi.unstubAllGlobals(); delete process.env.STORAGE_DRIVER; delete process.env.CF_ACCESS_TEAM_DOMAIN; delete process.env.CF_ACCESS_AUDIENCE; + delete process.env.ACCESS_ALLOWED_EMAILS; + vi.unstubAllEnvs(); }); describe("Cloudflare Access", () => { it("allows local requests", async () => { @@ -19,19 +23,39 @@ describe("Cloudflare Access", () => { await expect(verifyAccess("token")).rejects.toThrow("required"); process.env.CF_ACCESS_TEAM_DOMAIN = "example.cloudflareaccess.com"; await expect(verifyAccess("token")).rejects.toThrow("required"); + process.env.CF_ACCESS_AUDIENCE = "aud"; + // Without an e-mail allowlist any Access identity would pass. + await expect(verifyAccess("token")).rejects.toThrow("required"); + process.env.ACCESS_ALLOWED_EMAILS = " , "; + await expect(verifyAccess("token")).rejects.toThrow("required"); + }); + it("accepts only allowlisted e-mail identities", async () => { + const { sign, privateKey, issuer, fetchKeys } = await syntheticAccess(); + await expect(verifyAccess(await sign())).resolves.toBeUndefined(); + await expect(verifyAccess(await sign({ email: "SECOND@example.com" }))).resolves.toBeUndefined(); + await expect(verifyAccess(await sign({ email: "intruder@example.com" }))).rejects.toThrow("not allowed"); + await expect(verifyAccess(await sign({ email: "intruder@example.com" }))).rejects.toBeInstanceOf(AccessForbidden); + await expect(verifyAccess(await sign({ email: "" }))).rejects.toThrow("not allowed"); + const withoutEmail = await new SignJWT({}).setProtectedHeader({ alg: "RS256", kid: "fixture" }) + .setIssuer(issuer).setAudience(accessAudience).setExpirationTime("5m") + .sign(privateKey); + await expect(verifyAccess(withoutEmail)).rejects.toThrow("not allowed"); + // The key set is fetched once and reused for later assertions. + expect(fetchKeys.mock.calls.filter(([url]) => String(url).endsWith("/cdn-cgi/access/certs"))).toHaveLength(1); }); it("verifies signature, issuer and audience against a synthetic key set", async () => { process.env.STORAGE_DRIVER = "cloudflare"; - process.env.CF_ACCESS_TEAM_DOMAIN = "example.cloudflareaccess.com"; + process.env.CF_ACCESS_TEAM_DOMAIN = "verify.cloudflareaccess.com"; process.env.CF_ACCESS_AUDIENCE = "aud"; - const issuer = "https://example.cloudflareaccess.com"; + process.env.ACCESS_ALLOWED_EMAILS = "owner@example.com"; + const issuer = "https://verify.cloudflareaccess.com"; const { publicKey, privateKey } = await generateKeyPair("RS256", { extractable: true }); const other = await generateKeyPair("RS256"); const jwk = { ...await exportJWK(publicKey), kid: "fixture", alg: "RS256" }; const fetchKeys = vi.fn(async (_url: URL) => Response.json({ keys: [jwk] })); vi.stubGlobal("fetch", fetchKeys); const token = (audience: string, origin = issuer, signer = privateKey, expiration = "5m") => - new SignJWT({}).setProtectedHeader({ alg: "RS256", kid: "fixture" }) + new SignJWT({ email: "owner@example.com" }).setProtectedHeader({ alg: "RS256", kid: "fixture" }) .setIssuer(origin).setAudience(audience).setExpirationTime(expiration).sign(signer); await expect(verifyAccess(await token("aud"))).resolves.toBeUndefined(); await expect(verifyAccess(await token("another"))).rejects.toThrow(/aud/); @@ -43,8 +67,21 @@ describe("Cloudflare Access", () => { .setIssuer(issuer).setAudience("aud").sign(privateKey); await expect(verifyAccess(noExpiration)).rejects.toThrow(/exp/); expect(String(fetchKeys.mock.calls[0]?.[0])).toBe(`${issuer}/cdn-cgi/access/certs`); + expect(fetchKeys).toHaveBeenCalledTimes(1); + }); + it("fails while the key set is unavailable and recovers on the next request", async () => { + process.env.STORAGE_DRIVER = "cloudflare"; + process.env.CF_ACCESS_TEAM_DOMAIN = "unavailable.cloudflareaccess.com"; + process.env.CF_ACCESS_AUDIENCE = "aud"; + process.env.ACCESS_ALLOWED_EMAILS = "owner@example.com"; + const { publicKey, privateKey } = await generateKeyPair("RS256", { extractable: true }); + const jwk = { ...await exportJWK(publicKey), kid: "fixture", alg: "RS256" }; + const fetchKeys = vi.fn(async (_url: URL) => Response.json({ keys: [jwk] })); fetchKeys.mockResolvedValueOnce(new Response(null, { status: 503 })); - await expect(verifyAccess(await token("aud"))).rejects.toThrow(/200 OK/); - await expect(verifyAccess(await token("aud"))).resolves.toBeUndefined(); + vi.stubGlobal("fetch", fetchKeys); + const token = await new SignJWT({ email: "owner@example.com" }).setProtectedHeader({ alg: "RS256", kid: "fixture" }) + .setIssuer("https://unavailable.cloudflareaccess.com").setAudience("aud").setExpirationTime("5m").sign(privateKey); + await expect(verifyAccess(token)).rejects.toThrow(/200 OK/); + await expect(verifyAccess(token)).resolves.toBeUndefined(); }); }); diff --git a/tests/actions.test.ts b/tests/actions.test.ts index 4108276..7365313 100644 --- a/tests/actions.test.ts +++ b/tests/actions.test.ts @@ -12,6 +12,7 @@ const mocks = vi.hoisted(() => ({ moveProject: vi.fn(), revalidatePath: vi.fn(), enqueue: vi.fn(), + dispatch: vi.fn(), retryBlocked: vi.fn(), retryImage: vi.fn(), retryImageJob: vi.fn(), @@ -47,6 +48,7 @@ vi.mock("../src/core/runtime", () => ({ }, }), enqueue: mocks.enqueue, + dispatch: mocks.dispatch, retryBlockedQueueJob: mocks.retryBlocked, retryImageJob: mocks.retryImageJob, })); @@ -114,22 +116,38 @@ it("queues Codex images synchronously", async () => { await requestImageAction(request); expect(mocks.enqueue).toHaveBeenCalledWith("IMG-one"); }); -it("on Cloudflare executes API images after returning and preserves failure status", async () => { +it("creates one panel job per count without storing the count", async () => { + mocks.create.mockImplementation(async (input: { idempotencyKey: string; count?: number }) => ({ + id: `IMG-${input.idempotencyKey}`, source: "queue", status: "queued", idempotencyKey: input.idempotencyKey, + })); + const result = await requestImageAction({ ...request, count: 3 }); + expect(mocks.create.mock.calls.map(call => call[0].idempotencyKey)).toEqual(["one", "one-2", "one-3"]); + expect(mocks.create.mock.calls.every(call => call[0].count === undefined)).toBe(true); + expect(result?.data).toMatchObject({ id: "IMG-one" }); + const data = result?.data; + expect(data && "jobs" in data ? data.jobs.map(job => job.id) : []).toEqual(["IMG-one", "IMG-one-2", "IMG-one-3"]); + expect(mocks.enqueue).toHaveBeenCalledTimes(3); +}); +it("leaves a local API image as durable work for the API runner, in the request", async () => { + mocks.create.mockResolvedValue({ id: "IMG-one", source: "api" }); + mocks.get.mockImplementation(async (collection: string) => collection === "models" + ? [{ id: "gpt-image-1.5", provider: "openai", sizeProfile: { mode: "fixed", sizes: [{ width: 1024, height: 1024 }] } }] + : { id: "IMG-one", source: "api", status: "queued" }); + await requestImageAction({ ...request, source: "api", model: "gpt-image-1.5" }); + expect(mocks.enqueue).toHaveBeenCalledExactlyOnceWith("IMG-one"); + expect(mocks.dispatch).not.toHaveBeenCalled(); + expect(mocks.after).not.toHaveBeenCalled(); +}); +it("on Cloudflare hands API images to the generation queue", async () => { vi.stubEnv("IMAGE_QUEUE_STORAGE_DRIVER","cloudflare"); mocks.create.mockResolvedValue({ id: "IMG-one", source: "api" }); - mocks.get.mockResolvedValue({ id: "IMG-one", source: "api", status: "queued" }); mocks.get.mockImplementation(async (collection: string) => collection === "models" ? [{ id: "gpt-image-1.5", provider: "openai", sizeProfile: { mode: "fixed", sizes: [{ width: 1024, height: 1024 }] } }] : { id: "IMG-one", source: "api", status: "queued" }); await requestImageAction({ ...request, source: "api", model: "gpt-image-1.5" }); - await mocks.after.mock.calls[0][0](); - mocks.enqueue.mockRejectedValue(new Error("Authorization: Bearer private-background-key")); - await mocks.after.mock.calls[0][0](); - expect(mocks.put).toHaveBeenCalledWith( - "jobs", - "IMG-one", - expect.objectContaining({ status: "failed", error: "Generation failed" }), - ); + expect(mocks.dispatch).toHaveBeenCalledExactlyOnceWith("IMG-one"); + expect(mocks.enqueue).not.toHaveBeenCalled(); + expect(mocks.after).not.toHaveBeenCalled(); }); it("validates provider models before storing keys", async () => { mocks.discover.mockResolvedValue([]); @@ -208,22 +226,6 @@ it("saves pool configuration with validation", async () => { ).toBeTruthy(); }); -it("maps non-Error Cloudflare background failures", async () => { - vi.stubEnv("IMAGE_QUEUE_STORAGE_DRIVER","cloudflare"); - mocks.create.mockResolvedValue({ id: "IMG-one", source: "api" }); - mocks.get.mockResolvedValue({ id: "IMG-one", source: "api", status: "queued" }); - mocks.get.mockImplementation(async (collection: string) => collection === "models" - ? [{ id: "gpt-image-1.5", provider: "openai", sizeProfile: { mode: "fixed", sizes: [{ width: 1024, height: 1024 }] } }] - : { id: "IMG-one", source: "api", status: "queued" }); - await requestImageAction({ ...request, source: "api", model: "gpt-image-1.5" }); - mocks.enqueue.mockRejectedValue("bad"); - await mocks.after.mock.calls[0][0](); - expect(mocks.put).toHaveBeenCalledWith( - "jobs", - "IMG-one", - expect.objectContaining({ error: "Generation failed" }), - ); -}); it("cancels queued API work without changing the Codex queue", async () => { mocks.get.mockResolvedValue({ id: "IMG-one", @@ -425,21 +427,6 @@ it("does not expose unexpected storage errors through server actions", async () }); -it("preserves the safe missing-connection reason on Cloudflare", async () => { - vi.stubEnv("IMAGE_QUEUE_STORAGE_DRIVER","cloudflare"); - mocks.create.mockResolvedValue({ id: "IMG-one", source: "api" }); - mocks.get.mockImplementation(async (collection: string) => collection === "models" - ? [{ id: "gpt-image-1.5", provider: "openai" }] - : { id: "IMG-one", source: "api", status: "queued" }); - await requestImageAction({ ...request, source: "api", model: "gpt-image-1.5" }); - mocks.enqueue.mockRejectedValue(new UserFacingError("Connect this provider in Settings first")); - await mocks.after.mock.calls[0][0](); - expect(mocks.put).toHaveBeenCalledWith("jobs", "IMG-one", expect.objectContaining({ - status: "failed", error: "Connect this provider in Settings first", - })); -}); - - it("rejects a missing provider connection before creating a request", async () => { mocks.get.mockResolvedValue([{id:"gpt-image-1.5",provider:"openai"}]); mocks.readKey.mockRejectedValueOnce(new UserFacingError("Connect this provider in Settings first")); diff --git a/tests/animated-thumbnail.test.ts b/tests/animated-thumbnail.test.ts new file mode 100644 index 0000000..11666fd --- /dev/null +++ b/tests/animated-thumbnail.test.ts @@ -0,0 +1,72 @@ +import sharp from "sharp"; +import { expect, it } from "vitest"; +import { isAnimatedWebp, thumbnail } from "../src/sources/thumbnail"; + +async function gif(frames: number, side = 96) { + const colours = ["#c0392b", "#27ae60", "#2980b9", "#f1c40f"]; + const pages = await Promise.all(Array.from({ length: frames }, (_, index) => + sharp({ create: { width: side, height: side, channels: 3, background: colours[index % colours.length] } }).png().toBuffer())); + return new Uint8Array(await sharp(pages, { join: { animated: true } }).gif({ delay: 120 }).toBuffer()); +} + +it("keeps every frame of a GIF in an animated preview and resizes them", async () => { + const preview = await thumbnail(await gif(4), 48, { animated: true }); + expect(preview.mime).toBe("image/webp"); + expect(preview.animated).toBe(true); + const meta = await sharp(preview.bytes, { animated: true }).metadata(); + expect(meta.pages).toBe(4); + expect(meta.width).toBe(48); + expect(meta.pageHeight).toBe(48); +}); + +it("still returns the first frame only when animation is not asked for", async () => { + const preview = await thumbnail(await gif(4), 48); + expect(preview.animated).toBe(false); + expect((await sharp(preview.bytes, { animated: true }).metadata()).pages ?? 1).toBe(1); +}); + +it("reports a still source as not animated even when animation is asked for", async () => { + const still = new Uint8Array(await sharp({ create: { width: 64, height: 64, channels: 3, background: "#333" } }).png().toBuffer()); + expect((await thumbnail(still, 48, { animated: true })).animated).toBe(false); + expect(isAnimatedWebp(new Uint8Array([1, 2, 3]))).toBe(false); +}); + +it("serves the animated preview of a GIF job through the app-only tool, and a still for other images", async () => { + const { mkdtemp, rm } = await import("node:fs/promises"); + const os = await import("node:os"); + const path = await import("node:path"); + const { Client } = await import("@modelcontextprotocol/client"); + const { InMemoryTransport } = await import("@modelcontextprotocol/server"); + const root = await mkdtemp(path.join(os.tmpdir(), "animated-preview-")); + process.env.STORAGE_DIR = path.join(root, "store"); + process.env.CODEX_QUEUE_DIR = path.join(root, "queue"); + try { + const { createServer } = await import("../src/mcp/server"); + const { service } = await import("../src/core/runtime"); + const api = await service(); + const project = await api.createProject("Animated preview"); + await api.store.putBlob("results/corgi-gif", await gif(3), "image/gif"); + await api.store.put("jobs", "IMG-corgi-gif", { + id: "IMG-corgi-gif", projectId: project.id, source: "api", status: "done", blobKey: "results/corgi-gif", outputFormat: "gif", + prompt: "A corgi typing", width: 96, height: 96, referenceIds: [], createdAt: "2026-11-20T01:00:00.000Z", updatedAt: "2026-11-20T01:00:00.000Z", + }); + 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); + const read = async (args: Record) => { + const result = await client.callTool({ name: "read_thumbnail", arguments: args }) as { content: { type: string; text?: string; data?: string }[] }; + const bytes = new Uint8Array(Buffer.from(result.content.find(item => item.type === "image")!.data!, "base64")); + return { note: JSON.parse(result.content.find(item => item.type === "text")!.text!), pages: (await sharp(bytes, { animated: true }).metadata()).pages ?? 1 }; + }; + expect(await read({ id: "IMG-corgi-gif", animated: true })).toEqual({ note: { animated: true }, pages: 3 }); + expect(await read({ id: "IMG-corgi-gif" })).toEqual({ note: { animated: false }, pages: 1 }); + await client.close(); + await server.close(); + } finally { + await rm(root, { recursive: true, force: true }); + delete process.env.STORAGE_DIR; + delete process.env.CODEX_QUEUE_DIR; + } +}); diff --git a/tests/cloudflare-setup.test.ts b/tests/cloudflare-setup.test.ts new file mode 100644 index 0000000..369b7c1 --- /dev/null +++ b/tests/cloudflare-setup.test.ts @@ -0,0 +1,78 @@ +import { expect, it } from "vitest"; +import { + accessApplication, accountFromWhoami, claudeCallbacks, deploymentConfig, parseOptions, pendingMigrations, workerSecrets, +} from "../scripts/cloudflare-setup-plan"; + +it("parses and validates setup options", () => { + expect(parseOptions(["--domain", "App.Example.com", "--email", "A@example.com,b@example.com", "--email", "a@example.com"])) + .toEqual({ domain: "app.example.com", emails: ["a@example.com", "b@example.com"], skipAccess: false, skipDeploy: false, skipBuild: false }); + expect(parseOptions(["--domain", "app.example.com", "--skip-access"], { CLOUDFLARE_ACCOUNT_ID: "0".repeat(32) })) + .toMatchObject({ emails: [], skipAccess: true, accountId: "0".repeat(32) }); + for (const [argv, message] of [ + [["--domain", "https://app.example.com", "--email", "a@example.com"], /host name/], + [["--domain", "app.example.com/api", "--email", "a@example.com"], /host name/], + [["--domain", "app.example.com"], /--email is required/], + [["--domain", "app.example.com", "--email", "not-an-address"], /Not an e-mail/], + [["--domain", "app.example.com", "--email", "a@example.com", "--account-id", "abc"], /32-character/], + [["--domain"], /needs a value/], + [["--domain", "app.example.com", "--force"], /Unknown option/], + ] as const) expect(() => parseOptions(argv)).toThrow(message); +}); + +it("reads the single account from wrangler whoami and refuses to guess between several", () => { + const id = "0123456789abcdef0123456789abcdef"; + expect(accountFromWhoami(`│ Someone's Account │ ${id} │`)).toBe(id); + expect(() => accountFromWhoami(`${id}\n${"a".repeat(32)}`)).toThrow(/--account-id/); + expect(() => accountFromWhoami("You are not authenticated")).toThrow(/wrangler login/); +}); + +it("adds the D1 ID and the custom domain without changing the rest of the configuration", () => { + const base = { + name: "image-queue", + d1_databases: [{ binding: "DB", database_name: "image-queue", database_id: "local-image-queue" }], + queues: { producers: [] }, + workers_dev: true, + }; + const id = "6f1c2a8e-0b4d-4c55-9a1e-3f2b7d9e0c11"; + expect(deploymentConfig(base, id, "app.example.com")).toEqual({ + ...base, + d1_databases: [{ binding: "DB", database_name: "image-queue", database_id: id }], + routes: [{ pattern: "app.example.com", custom_domain: true }], + workers_dev: false, + preview_urls: false, + }); + expect(base.d1_databases[0]!.database_id).toBe("local-image-queue"); + expect(() => deploymentConfig(base, "local-image-queue", "app.example.com")).toThrow(/D1/); +}); + +it("applies only unrecorded migration files, in order", () => { + expect(pendingMigrations(["0002.sql", "README.md", "0001.sql", "0003_add_index.sql"], ["0001.sql"])) + .toEqual(["0002.sql", "0003_add_index.sql"]); + expect(pendingMigrations(["0001.sql"], ["0001.sql"])).toEqual([]); +}); + +it("protects the whole domain with one allow policy and Managed OAuth for Claude, Claude Code and Codex", () => { + const application = accessApplication("app.example.com", ["a@example.com"], "pin-id"); + expect(application).toMatchObject({ + type: "self_hosted", + domain: "app.example.com", + allowed_idps: ["pin-id"], + policies: [{ decision: "allow", include: [{ email: { email: "a@example.com" } }] }], + oauth_configuration: { + enabled: true, + dynamic_client_registration: { enabled: true, allowed_uris: claudeCallbacks, allow_any_on_localhost: true, allow_any_on_loopback: true }, + }, + }); + expect(claudeCallbacks).toEqual(["https://claude.ai/api/mcp/auth_callback", "https://claude.com/api/mcp/auth_callback"]); + expect(JSON.stringify(application)).not.toMatch(/everyone|any_valid_service_token|"ip"/); +}); + +it("sets the provider key only when one is given", () => { + const base = { teamDomain: "team.cloudflareaccess.com", audience: "aud", emails: ["a@example.com", "b@example.com"] }; + expect(workerSecrets(base)).toEqual({ + IMAGE_QUEUE_CF_ACCESS_TEAM_DOMAIN: "team.cloudflareaccess.com", + IMAGE_QUEUE_CF_ACCESS_AUDIENCE: "aud", + IMAGE_QUEUE_ACCESS_ALLOWED_EMAILS: "a@example.com,b@example.com", + }); + expect(workerSecrets({ ...base, openAiKey: "sk-test" })).toHaveProperty("IMAGE_QUEUE_OPENAI_API_KEY", "sk-test"); +}); diff --git a/tests/cloudflare-worker.test.ts b/tests/cloudflare-worker.test.ts index 0405a96..0c5b262 100644 --- a/tests/cloudflare-worker.test.ts +++ b/tests/cloudflare-worker.test.ts @@ -1,31 +1,78 @@ import { expect, it, vi } from "vitest"; -const { maintain, fetchHandler, bindings } = vi.hoisted(() => ({ - maintain: vi.fn().mockResolvedValue([]), fetchHandler: vi.fn(), bindings: vi.fn(), +const { maintain, fetchHandler, bindings, runQueuedJob, abandonQueuedJob, runWithContext } = vi.hoisted(() => ({ + maintain: vi.fn().mockResolvedValue([]), + fetchHandler: vi.fn(), + bindings: vi.fn(), + runQueuedJob: vi.fn().mockResolvedValue("finished"), + abandonQueuedJob: vi.fn().mockResolvedValue(undefined), + runWithContext: vi.fn(async (_request: Request, _env: unknown, _ctx: unknown, work: () => Promise) => work()), })); vi.mock("./.open-next/worker.js", () => ({ default: { fetch: fetchHandler } })); +vi.mock("./generated-init-stub", () => ({ runWithCloudflareRequestContext: runWithContext })); vi.mock("../src/core/maintenance", () => ({ maintainTrash: maintain })); +vi.mock("../src/core/runtime", () => ({ runQueuedJob, abandonQueuedJob })); vi.mock("../src/storage/cloudflare", () => ({ CloudflareStorage: class { constructor(db: unknown, blobs: unknown) { bindings(db, blobs); } }, })); import worker from "../cloudflare-worker"; +import { busyRetryDelaySeconds, maxBusyAttempts } from "../src/core/generation-queue"; + +const env = { DB: {}, BLOBS: {} } as Parameters[1]; +const ctx = { waitUntil: vi.fn() }; +const message = (body: unknown) => ({ body, ack: vi.fn() }); it("preserves the app handler and awaits scheduled maintenance with event time", async () => { - const env = { DB: {}, BLOBS: {} } as Parameters[1]; await worker.scheduled({ scheduledTime: 12345 }, env); expect(worker.fetch).toBe(fetchHandler); expect(bindings).toHaveBeenCalledWith(env.DB, env.BLOBS); expect(maintain).toHaveBeenCalledWith(expect.anything(), 12345); }); -it("keeps the hourly trigger and custom entry point in deployment configuration", async () => { +it("keeps the hourly trigger, the queue without retries and no public workers.dev route", async () => { const { readFile } = await import("node:fs/promises"); const config = JSON.parse(await readFile(new URL("../wrangler.jsonc", import.meta.url), "utf8")); expect(config.main).toBe("cloudflare-worker.ts"); expect(config.triggers.crons).toEqual(["0 * * * *"]); + expect(config.workers_dev).toBe(false); + expect(config.preview_urls).toBe(false); + expect(config.queues.producers).toEqual([{ binding: "GENERATION_QUEUE", queue: "image-queue-generation" }]); + expect(config.queues.consumers).toEqual([expect.objectContaining({ + queue: "image-queue-generation", max_batch_size: 1, max_retries: 0, + })]); }); it("propagates maintenance failure to the scheduled invocation", async () => { maintain.mockRejectedValueOnce(new Error("maintenance failed")); - const env = { DB: {}, BLOBS: {} } as Parameters[1]; await expect(worker.scheduled({ scheduledTime: 12345 }, env)).rejects.toThrow("maintenance failed"); }); + +it("runs each queued job inside the Cloudflare context and acknowledges every message once", async () => { + const valid = message({ jobId: "IMG-remote" }); + const malformed = [message(null), message({ jobId: 7 }), message("IMG-remote")]; + await worker.queue({ messages: [valid, ...malformed] }, env, ctx); + expect(runQueuedJob).toHaveBeenCalledTimes(1); + expect(runQueuedJob).toHaveBeenCalledWith("IMG-remote"); + expect(runWithContext).toHaveBeenCalledWith(expect.any(Request), env, ctx, expect.any(Function)); + for (const item of [valid, ...malformed]) expect(item.ack).toHaveBeenCalledTimes(1); +}); + +it("offers a busy job again later and abandons it after the last attempt", async () => { + const send = vi.fn().mockResolvedValue(undefined); + const withQueue = { ...env, GENERATION_QUEUE: { send } }; + runQueuedJob.mockResolvedValue("busy"); + try { + const first = message({ jobId: "IMG-busy" }); + await worker.queue({ messages: [first] }, withQueue, ctx); + expect(send).toHaveBeenCalledExactlyOnceWith({ jobId: "IMG-busy", attempt: 1 }, { delaySeconds: busyRetryDelaySeconds }); + expect(first.ack).toHaveBeenCalledOnce(); + expect(abandonQueuedJob).not.toHaveBeenCalled(); + + const last = message({ jobId: "IMG-busy", attempt: maxBusyAttempts }); + await worker.queue({ messages: [last] }, withQueue, ctx); + expect(send).toHaveBeenCalledOnce(); + expect(abandonQueuedJob).toHaveBeenCalledExactlyOnceWith("IMG-busy"); + expect(last.ack).toHaveBeenCalledOnce(); + } finally { + runQueuedJob.mockResolvedValue("finished"); + } +}); diff --git a/tests/cloudflare.test.ts b/tests/cloudflare.test.ts index 66c2fb2..708f1e4 100644 --- a/tests/cloudflare.test.ts +++ b/tests/cloudflare.test.ts @@ -1,9 +1,9 @@ -import { describe, expect, it } from "vitest"; -import { CloudflareStorage } from "../src/storage/cloudflare"; +import { describe, expect, it, vi } from "vitest"; +import { CloudflareStorage, lockLease } from "../src/storage/cloudflare"; function bindings() { const records = new Map(); - const locks = new Map(); + const locks = new Map(); const blobs = new Map(); const db = { prepare(sql: string) { @@ -26,10 +26,13 @@ function bindings() { records.set(`${args[0]}/${args[1]}`, String(args[2])); if (sql.startsWith("INSERT INTO locks")) { if (locks.has(String(args[0]))) throw new Error("unique"); - locks.set(String(args[0]), String(args[1])); + locks.set(String(args[0]), { token: String(args[1]), expiresAt: args[2] as number | null }); } if (sql.startsWith("DELETE FROM records")) records.delete(`${args[0]}/${args[1]}`); - if (sql.startsWith("DELETE FROM locks")) + if (sql.startsWith("DELETE FROM locks WHERE id=? AND expires_at")) { + const held = locks.get(String(args[0])); + if (held && held.expiresAt !== null && held.expiresAt < Number(args[1])) locks.delete(String(args[0])); + } else if (sql.startsWith("DELETE FROM locks") && locks.get(String(args[0]))?.token === args[1]) locks.delete(String(args[0])); }, }; @@ -56,7 +59,7 @@ function bindings() { : null; }, }; - return new CloudflareStorage(db as never, bucket as never); + return Object.assign(new CloudflareStorage(db as never, bucket as never), { fakeLocks: locks }); } describe("Cloudflare storage contract", () => { it("stores, replaces and lists JSON records", async () => { @@ -88,6 +91,23 @@ describe("Cloudflare storage contract", () => { ).rejects.toThrow("fail"); expect(await s.lock("test", async () => 2)).toBe(2); }); + it("lets a caller take over a lock whose holder died after its lease", async () => { + const s = bindings(); + const start = Date.now(); + s.fakeLocks.set("job", { token: "dead", expiresAt: start + 1000 }); + await expect(s.lock("job", async () => 1)).rejects.toThrow("progress"); + const clock = vi.spyOn(Date, "now").mockReturnValue(start + 2000); + try { + expect(await s.lock("job", async () => s.fakeLocks.get("job")?.expiresAt)).toBe(start + 2000 + lockLease); + expect(s.fakeLocks.has("job")).toBe(false); + // A legacy lock without a lease is never taken over. + s.fakeLocks.set("legacy", { token: "old", expiresAt: null }); + await expect(s.lock("legacy", async () => 1)).rejects.toThrow("progress"); + } finally { + clock.mockRestore(); + } + expect(lockLease).toBeGreaterThan(15 * 60 * 1000); + }); }); it("deletes records and blobs independently and idempotently", async () => { diff --git a/tests/connected-provider-row.test.tsx b/tests/connected-provider-row.test.tsx index 2d22120..1b63bc4 100644 --- a/tests/connected-provider-row.test.tsx +++ b/tests/connected-provider-row.test.tsx @@ -18,8 +18,13 @@ function deferred() { return { promise, resolve }; } -function row(provider: "openai" | "google" = "openai", label = "OpenAI", revision = 0) { - return {}} />; +function row( + provider: "openai" | "google" = "openai", + label = "OpenAI", + revision = 0, + onConfirmed?: (message: string) => void, +) { + return {}} onConfirmed={onConfirmed} />; } function meta(container: HTMLElement) { @@ -41,10 +46,11 @@ it("renders the model count as a status region before the first result", () => { expect(view.container.querySelector(".settings-list-result")).toBeNull(); }); -it("shows Testing… with the progress icon in the same button, ignores repeat clicks and replaces the count with the result", async () => { +it("shows Testing… with the progress icon in the same button, ignores repeat clicks and keeps the count after success", async () => { const pending = deferred<{ data: { models: number } }>(); + const onConfirmed = vi.fn(); testConnectionAction.mockReturnValueOnce(pending.promise); - const view = render(
            {row()}
          ); + const view = render(
            {row("openai", "OpenAI", 0, onConfirmed)}
          ); const status = meta(view.container); const button = screen.getByRole("button", { name: "Test connection" }); @@ -70,64 +76,79 @@ it("shows Testing… with the progress icon in the same button, ignores repeat c expect(button.querySelector("svg.spin")).toBeNull(); expect(screen.getByRole("button", { name: "Test connection" })).toBe(button); expect(meta(view.container)).toBe(status); - expect(shownMeta(view.container)).toBe("Connection works. 12 image models available."); - // The count fades out in the same cell and is not announced again. - const leaving = status.querySelector(".settings-meta-leaving")!; - expect(leaving.textContent).toBe("3 models"); - expect(leaving.getAttribute("aria-hidden")).toBe("true"); - fireEvent.animationEnd(leaving); - expect(status.textContent).toBe("Connection works. 12 image models available."); + expect(shownMeta(view.container)).toBe("3 models"); + expect(status.textContent).toBe("3 models"); + expect(status.querySelector("[data-result]")).toBeNull(); + expect(onConfirmed).toHaveBeenCalledOnce(); + expect(onConfirmed).toHaveBeenCalledWith("Connection works. 12 image models available."); }); -it("replaces the previous result in place with the provider's error", async () => { +it("replaces the count with an error and restores it after a later success", async () => { + const onConfirmed = vi.fn(); testConnectionAction .mockResolvedValueOnce({ data: { models: 1 } }) .mockResolvedValueOnce({ serverError: "The provider rejected this API key (401). Check the key and try again." }) - .mockRejectedValueOnce(new Error("network")); - const view = render(
            {row()}
          ); + .mockRejectedValueOnce(new Error("network")) + .mockResolvedValueOnce({ data: { models: 4 } }); + const view = render(
            {row("openai", "OpenAI", 0, onConfirmed)}
          ); const button = screen.getByRole("button", { name: "Test connection" }); await act(async () => fireEvent.click(button)); const status = meta(view.container); const first = status.firstElementChild; - expect(shownMeta(view.container)).toBe("Connection works. 1 image model available."); + expect(shownMeta(view.container)).toBe("3 models"); + expect(onConfirmed).toHaveBeenCalledWith(connectionWorksMessage(1)); await act(async () => fireEvent.click(button)); expect(meta(view.container)).toBe(status); - // A new element restarts the fade for the replacing sentence; the old one fades out beside it. + // A new element restarts the fade for the replacing sentence; the count fades out beside it. expect(status.firstElementChild).not.toBe(first); expect(shownMeta(view.container)).toBe("The provider rejected this API key (401). Check the key and try again."); expect(status.querySelectorAll(".settings-meta-text")).toHaveLength(2); + const leaving = status.querySelector(".settings-meta-leaving")!; + expect(leaving.textContent).toBe("3 models"); + expect(leaving.getAttribute("aria-hidden")).toBe("true"); + fireEvent.animationEnd(leaving); + expect(status.textContent).toBe("The provider rejected this API key (401). Check the key and try again."); await act(async () => fireEvent.click(button)); expect(shownMeta(view.container)).toBe("The connection could not be checked. Try again."); + + await act(async () => fireEvent.click(button)); + expect(shownMeta(view.container)).toBe("3 models"); + expect(status.querySelector(".settings-meta-text:not(.settings-meta-leaving)")?.hasAttribute("data-result")).toBe(false); + expect(onConfirmed).toHaveBeenLastCalledWith(connectionWorksMessage(4)); }); it("keeps other provider rows usable while one test runs", async () => { const pending = deferred<{ data: { models: number } }>(); + const onConfirmed = vi.fn(); testConnectionAction.mockReturnValueOnce(pending.promise).mockResolvedValueOnce({ data: { models: 2 } }); - render(
            {row("openai", "OpenAI")}{row("google", "Google")}
          ); + render(
            {row("openai", "OpenAI", 0, onConfirmed)}{row("google", "Google", 0, onConfirmed)}
          ); const [openai, google] = screen.getAllByRole("button", { name: "Test connection" }); fireEvent.click(openai); await act(async () => fireEvent.click(google)); expect(testConnectionAction).toHaveBeenNthCalledWith(2, { provider: "google" }); expect(google.getAttribute("aria-busy")).toBeNull(); expect(openai.getAttribute("aria-busy")).toBe("true"); - expect(google.closest("li")!.textContent).toContain(connectionWorksMessage(2)); + expect(google.closest("li")!.textContent).not.toContain("Connection works"); + expect(onConfirmed).toHaveBeenCalledWith(connectionWorksMessage(2)); await act(async () => pending.resolve({ data: { models: 5 } })); - expect(openai.closest("li")!.textContent).toContain(connectionWorksMessage(5)); + expect(openai.closest("li")!.textContent).not.toContain("Connection works"); + expect(onConfirmed).toHaveBeenCalledWith(connectionWorksMessage(5)); }); it("clears the result when the key is replaced and ignores a test of the old key", async () => { + const onConfirmed = vi.fn(); const old = deferred<{ data: { models: number } }>(); - testConnectionAction.mockResolvedValueOnce({ data: { models: 4 } }).mockReturnValueOnce(old.promise); - const view = render(
            {row()}
          ); + testConnectionAction.mockResolvedValueOnce({ serverError: "The provider rejected this API key (401). Check the key and try again." }).mockReturnValueOnce(old.promise); + const view = render(
            {row("openai", "OpenAI", 0, onConfirmed)}
          ); const button = screen.getByRole("button", { name: "Test connection" }); await act(async () => fireEvent.click(button)); - expect(shownMeta(view.container)).toBe(connectionWorksMessage(4)); + expect(shownMeta(view.container)).toBe("The provider rejected this API key (401). Check the key and try again."); fireEvent.click(button); expect(button.getAttribute("aria-busy")).toBe("true"); - view.rerender(
            {row("openai", "OpenAI", 1)}
          ); + view.rerender(
            {row("openai", "OpenAI", 1, onConfirmed)}
          ); // The new key shows the model count again and can be tested at once. expect(shownMeta(view.container)).toBe("3 models"); expect(button.getAttribute("aria-busy")).toBeNull(); @@ -138,9 +159,11 @@ it("clears the result when the key is replaced and ignores a test of the old key await act(async () => old.resolve({ data: { models: 9 } })); expect(shownMeta(view.container)).toBe("3 models"); + expect(onConfirmed).not.toHaveBeenCalled(); expect(button.getAttribute("aria-busy")).toBe("true"); await act(async () => fresh.resolve({ data: { models: 6 } })); - expect(shownMeta(view.container)).toBe(connectionWorksMessage(6)); + expect(shownMeta(view.container)).toBe("3 models"); + expect(onConfirmed).toHaveBeenCalledWith(connectionWorksMessage(6)); expect(button.getAttribute("aria-busy")).toBeNull(); }); @@ -164,15 +187,15 @@ it("cross-fades the meta text with the fast token and ends in the visible state document.documentElement.style.setProperty("--motion-reduced", "1"); try { - const pending = deferred<{ data: { models: number } }>(); + const pending = deferred<{ serverError: string }>(); testConnectionAction.mockReturnValueOnce(pending.promise); const view = render(
            {row()}
          ); const button = screen.getByRole("button", { name: "Test connection" }); fireEvent.click(button); expect(within(button).getByText("Testing…")).toBeTruthy(); - await act(async () => pending.resolve({ data: { models: 4 } })); + await act(async () => pending.resolve({ serverError: "The provider rejected this API key (401). Check the key and try again." })); const sentence = meta(view.container).querySelector(".settings-meta-text:not(.settings-meta-leaving)") as HTMLElement; - expect(sentence.textContent).toBe("Connection works. 4 image models available."); + expect(sentence.textContent).toBe("The provider rejected this API key (401). Check the key and try again."); expect(sentence.getAttribute("style")).toBeNull(); } finally { document.documentElement.style.removeProperty("--motion-reduced"); diff --git a/tests/core.test.ts b/tests/core.test.ts index dfb43ec..aa6e45a 100644 --- a/tests/core.test.ts +++ b/tests/core.test.ts @@ -13,6 +13,8 @@ import { } from "../src/core/schema"; import { ImageService } from "../src/core/service"; import { readKey, saveKey } from "../src/core/settings"; +import { extensionForMime, extensionForOutputFormat, mimeForDetectedType, svgDocument } from "../src/core/image-format"; +import { requestsForCount } from "../src/core/request-count"; import { FileStorage } from "../src/storage/fs"; import { safeKey } from "../src/storage/types"; @@ -57,6 +59,28 @@ describe("image requests", () => { ).rejects.toThrow("Idempotency"); expect(await service.jobs()).toHaveLength(1); }); + it("refuses output format and frame settings for queue requests before creating a job", async () => { + const project = await service.createProject("Formats"); + const input = request(project.id); + await expect(service.create({ ...input, outputFormat: "webp" })).rejects.toThrow("Output format and frame settings apply only to API generation"); + await expect(service.create({ ...input, frameCount: 4 })).rejects.toThrow("Output format and frame settings apply only to API generation"); + 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 () => { + const project = await service.createProject("GIF"); + await service.store.put("models", "openai", [{ + id: "gpt-image-2.6-sunburst", provider: "openai", name: "Sunburst", + references: true, transparency: true, + sizeProfile: { mode: "fixed", sizes: [{ width: 1024, height: 1024 }] }, + }]); + const reference = await service.addReference(project.id, "ref.png", "image/png", png); + 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([]); + }); it("requires a project and model for API requests", async () => { await expect(service.create(request("missing"))).rejects.toThrow("Project"); const p = await service.createProject("One"); @@ -64,6 +88,30 @@ describe("image requests", () => { service.create({ ...request(p.id), source: "api" }), ).rejects.toThrow("model"); }); + it("accepts the documented format and frame bounds", () => { + const base = { ...request("test"), source: "api" as const, model: "gpt-image-2.6-sunburst" }; + expect(requestSchema.safeParse({ ...base, outputFormat: "gif", frameCount: 2, frameDurationMs: 20 }).success).toBe(true); + expect(requestSchema.safeParse({ ...base, outputFormat: "gif", frameCount: 16, frameDurationMs: 2000 }).success).toBe(true); + for (const frameCount of [1, 17]) + expect(requestSchema.safeParse({ ...base, outputFormat: "gif", frameCount }).success).toBe(false); + for (const frameDurationMs of [19, 2001]) + expect(requestSchema.safeParse({ ...base, outputFormat: "gif", frameDurationMs }).success).toBe(false); + expect(requestSchema.safeParse({ ...base, outputFormat: "bmp" }).success).toBe(false); + const counted = requestsForCount({ ...base, idempotencyKey: "k".repeat(96) }, 10); + expect(requestSchema.safeParse(counted[0]).success).toBe(true); + expect(counted[9].idempotencyKey).toBe(`${"k".repeat(96)}-10`); + expect(requestSchema.safeParse(counted[9]).success).toBe(false); + expect(() => requestsForCount(base, 11)).toThrow("1 to 10"); + expect(extensionForOutputFormat("jpeg")).toBe("jpg"); + expect(extensionForOutputFormat()).toBe("png"); + expect(extensionForMime("image/svg+xml")).toBe("svg"); + expect(extensionForMime("image/jpeg; charset=binary")).toBe("jpg"); + expect(extensionForMime("image/gif")).toBe("gif"); + expect(mimeForDetectedType("jpg")).toBe("image/jpeg"); + expect(mimeForDetectedType("bmp")).toBeUndefined(); + expect(svgDocument(new TextEncoder().encode(""))).toBe(true); + expect(svgDocument(new TextEncoder().encode("hello "))).toBe(false); + }); it("rejects queue injection", () => { expect( requestSchema.safeParse({ diff --git a/tests/generated-init-stub.ts b/tests/generated-init-stub.ts new file mode 100644 index 0000000..3fe42c3 --- /dev/null +++ b/tests/generated-init-stub.ts @@ -0,0 +1,3 @@ +export async function runWithCloudflareRequestContext(_request: Request, _env: unknown, _ctx: unknown, work: () => Promise) { + return work(); +} diff --git a/tests/generation-dispatch.test.ts b/tests/generation-dispatch.test.ts new file mode 100644 index 0000000..0f592a0 --- /dev/null +++ b/tests/generation-dispatch.test.ts @@ -0,0 +1,114 @@ +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { MemoryStorage } from "../src/storage/memory"; +import type { Job } from "../src/core/schema"; + +const { state } = vi.hoisted(() => ({ + state: { store: undefined as unknown, env: {} as Record }, +})); +vi.mock("../src/storage", () => ({ storage: async () => state.store })); +vi.mock("@opennextjs/cloudflare", () => ({ getCloudflareContext: async () => ({ env: state.env }) })); +import { abandonQueuedJob, dispatch, runQueuedJob } from "../src/core/runtime"; + +let store: MemoryStorage; +const job = (patch: Partial = {}) => ({ + id: "IMG-remote", + projectId: "project", + source: "api", + provider: "openai", + model: "gpt-image-2", + prompt: "A blue square", + width: 1024, + height: 1024, + referenceIds: [], + status: "queued", + createdAt: "2026-11-19T20:00:00.000Z", + updatedAt: "2026-11-19T20:00:00.000Z", + ...patch, +}) as Job; + +beforeEach(() => { + store = new MemoryStorage(); + state.store = store; + state.env = {}; + vi.stubEnv("IMAGE_QUEUE_STORAGE_DRIVER", "cloudflare"); + vi.stubEnv("IMAGE_QUEUE_OPENAI_API_KEY", ""); + vi.stubEnv("OPENAI_API_KEY", ""); +}); +afterEach(() => vi.unstubAllEnvs()); + +it("hands a Cloudflare provider job to the generation queue without contacting the provider", async () => { + const send = vi.fn().mockResolvedValue(undefined); + state.env = { GENERATION_QUEUE: { send } }; + await store.put("jobs", "IMG-remote", job()); + await dispatch("IMG-remote"); + expect(send).toHaveBeenCalledExactlyOnceWith({ jobId: "IMG-remote" }); + expect((await store.get("jobs", "IMG-remote"))?.status).toBe("queued"); +}); + +it("records a job as failed when the queue cannot accept it, before any provider request", async () => { + for (const env of [{}, { GENERATION_QUEUE: { send: vi.fn().mockRejectedValue(new Error("queue down")) } }]) { + state.env = env; + await store.put("jobs", "IMG-remote", job()); + await dispatch("IMG-remote"); + expect(await store.get("jobs", "IMG-remote")).toMatchObject({ + status: "failed", + error: "Generation could not be started. No provider request was made.", + }); + } +}); + +it("does not queue a job that is no longer waiting", async () => { + const send = vi.fn(); + state.env = { GENERATION_QUEUE: { send } }; + await store.put("jobs", "IMG-remote", job({ status: "done" })); + await dispatch("IMG-remote"); + expect(send).not.toHaveBeenCalled(); +}); + +it("keeps the Codex file queue local-only on Cloudflare", async () => { + const send = vi.fn(); + state.env = { GENERATION_QUEUE: { send } }; + await store.put("jobs", "IMG-remote", job({ source: "queue" })); + await expect(dispatch("IMG-remote")).rejects.toThrow("only in a local installation"); + expect(send).not.toHaveBeenCalled(); +}); + +it("records a queued job that cannot start as failed with its reason", async () => { + await store.put("jobs", "IMG-remote", job()); + await runQueuedJob("IMG-remote"); + expect(await store.get("jobs", "IMG-remote")).toMatchObject({ + status: "failed", + error: "Connect this provider in Settings first", + }); +}); + +it("records unexpected start failures without exposing their details", async () => { + vi.stubEnv("IMAGE_QUEUE_OPENAI_API_KEY", "fixture-key"); + const get = store.get.bind(store); + for (const failure of [new Error("Authorization: Bearer private-background-key"), "bad"]) { + vi.spyOn(store, "get").mockImplementation(async (collection: string, id: string) => { + if (collection === "models") throw failure; + return get(collection, id); + }); + await store.put("jobs", "IMG-remote", job()); + await runQueuedJob("IMG-remote"); + const saved = await get("jobs", "IMG-remote"); + expect(saved).toMatchObject({ status: "failed", error: "Generation failed" }); + expect(JSON.stringify(saved)).not.toContain("private-background-key"); + } +}); + +it("reports a busy job without failing it, and abandons it only when asked", async () => { + await store.put("jobs", "IMG-remote", job()); + await store.lock("IMG-remote", async () => { + expect(await runQueuedJob("IMG-remote")).toBe("busy"); + // Still locked: abandoning must not throw or change anything. + await abandonQueuedJob("IMG-remote"); + }); + expect((await store.get("jobs", "IMG-remote"))?.status).toBe("queued"); + await abandonQueuedJob("IMG-remote"); + expect(await store.get("jobs", "IMG-remote")).toMatchObject({ + status: "failed", + error: "Generation could not start because the request stayed busy. No provider request was made.", + }); +}); diff --git a/tests/generation-preference.test.ts b/tests/generation-preference.test.ts index 9d25585..e8e173c 100644 --- a/tests/generation-preference.test.ts +++ b/tests/generation-preference.test.ts @@ -15,3 +15,25 @@ it('rejects an unconfigured API model and leaves the preference unchanged',async await expect(saveGenerationPreference(store,{source:'api',provider:'openai',model:'unknown'})).rejects.toThrow('configured OpenAI'); expect(await readGenerationPreference(store)).toMatchObject({source:'queue'}); }); + +it('defaults a Cloudflare deployment to the API and the preferred model, and refuses the local queue there', async () => { + const { vi } = await import('vitest'); + vi.stubEnv('IMAGE_QUEUE_STORAGE_DRIVER', 'cloudflare'); + try { + const store = new MemoryStorage(); + expect(await readGenerationPreference(store)).toEqual({ source: 'api', provider: 'openai' }); + await store.put('models', 'openai', [ + { id: 'gpt-image-1.5', name: 'GPT Image 1.5', provider: 'openai' }, + { id: 'gpt-image-2.6-sunburst', name: 'GPT Image 2.6 Sunburst', provider: 'openai' }, + ]); + expect(await readGenerationPreference(store)).toEqual({ source: 'api', provider: 'openai', model: 'gpt-image-2.6-sunburst' }); + // A queue choice saved before the deployment moved to Cloudflare is not used there. + await store.put('settings', 'generation-source', { source: 'queue', provider: 'openai' }); + expect(await readGenerationPreference(store)).toMatchObject({ source: 'api' }); + await expect(saveGenerationPreference(store, { source: 'queue', provider: 'openai' })).rejects.toThrow('only in a local installation'); + expect(await saveGenerationPreference(store, { source: 'api', provider: 'openai', model: 'gpt-image-1.5' })).toMatchObject({ model: 'gpt-image-1.5' }); + expect(await readGenerationPreference(store)).toMatchObject({ source: 'api', model: 'gpt-image-1.5' }); + } finally { + vi.unstubAllEnvs(); + } +}); diff --git a/tests/gif-sheet.test.ts b/tests/gif-sheet.test.ts new file mode 100644 index 0000000..afde828 --- /dev/null +++ b/tests/gif-sheet.test.ts @@ -0,0 +1,37 @@ +import { expect, it } from "vitest"; +import { assertGifSheetFits, gifSheetFits } from "../src/core/gif-sheet"; +import type { SizeProfile } from "../src/core/size-intent"; + +const gptImage26: SizeProfile = { + mode: "dimensions", minSide: 16, maxSide: 3840, multiple: 16, + minPixels: 655360, maxPixels: 8294400, minRatio: 1 / 3, maxRatio: 3, +}; +const square = (side: number) => ({ width: side, height: side }); + +it("rejects every 1024x1024 GIF OpenAI refused: 4, 6 and 8 frames need 4096x2048, 9 need 3072x3072", () => { + for (const count of [2, 4, 6, 8, 9]) expect(gifSheetFits(gptImage26, square(1024), count), String(count)).toBe(false); + expect(gifSheetFits(gptImage26, { width: 1536, height: 1024 }, 9)).toBe(false); + expect(() => assertGifSheetFits(gptImage26, square(1024), 4)) + .toThrow("use 960x960 or smaller for 4 frames. Nothing was sent or billed."); +}); + +it("matches the published square caps: 960 up to 9 frames, 816 up to 12, 720 up to 16", () => { + for (const [count, cap] of [[2, 960], [8, 960], [9, 960], [10, 816], [12, 816], [13, 720], [16, 720]] as const) { + expect(gifSheetFits(gptImage26, square(cap), count), `${count} at ${cap}`).toBe(true); + expect(gifSheetFits(gptImage26, square(cap + 16), count), `${count} at ${cap + 16}`).toBe(false); + } +}); + +it("checks the default of 9 frames when the request names no count", () => { + expect(() => assertGifSheetFits(gptImage26, square(1024), undefined)).toThrow("use 960x960 or smaller for 9 frames"); + expect(() => assertGifSheetFits(gptImage26, square(960), undefined)).not.toThrow(); +}); + +it("offers fewer frames when no model size can hold the count", () => { + // 13 to 16 frames need 720x720, below the smallest size this application sends (816x816). + expect(() => assertGifSheetFits(gptImage26, square(816), 16)).toThrow(": use at most 12 frames at this size. Nothing was sent or billed."); +}); + +it("leaves fixed-size models alone", () => { + expect(gifSheetFits({ mode: "fixed", sizes: [square(1024)] } as SizeProfile, square(1024), 16)).toBe(true); +}); diff --git a/tests/http-secret-boundary.test.ts b/tests/http-secret-boundary.test.ts index 2e6ca73..85dbbd5 100644 --- a/tests/http-secret-boundary.test.ts +++ b/tests/http-secret-boundary.test.ts @@ -72,11 +72,11 @@ it("keeps a stored provider credential out of every HTTP surface and its logs", ["get_queue_processing", {}], ["set_queue_processing", { source: "all", paused: true }], ["get_generation_source", {}], ["set_generation_source", { source: "queue" }], ["list_thumbnails", {}], ["get_image_details", { id: "missing" }], - ["get_job_state", { id: "missing" }], + ["get_job_state", { id: "missing" }], ["read_thumbnail", { id: "missing" }], ["read_image_file", { id: "missing" }], ["add_notes_to_queue", { imageId: "missing", idempotencyKey: "audit-notes" }], - ["list_models", {}], ["list_projects", {}], ["list_jobs", {}], + ["list_models", {}], ["refresh_models", {}], ["list_projects", {}], ["list_jobs", {}], ["create_project", { name: "MCP audit project" }], - ["get_job", { id: "missing" }], ["show_job", { id: "missing" }], + ["get_job", { id: "missing" }], ["show_job", { id: "missing" }], ["view_image", { id: "missing" }], ["show_image", { id: "missing" }], ["show_images", {}], ["wait_for_job", { id: "missing", timeoutSeconds: 0 }], ["cancel_job", { id: "missing" }], ["retry_image", { id: "missing" }], diff --git a/tests/idempotency-after-failure.test.ts b/tests/idempotency-after-failure.test.ts new file mode 100644 index 0000000..ee29808 --- /dev/null +++ b/tests/idempotency-after-failure.test.ts @@ -0,0 +1,36 @@ +import { expect, it } from "vitest"; +import { MemoryStorage } from "../src/storage/memory"; +import { ImageService } from "../src/core/service"; +import type { Job } from "../src/core/schema"; + +async function setup() { + const store = new MemoryStorage(); + const api = new ImageService(store); + const project = await api.createProject("Keys"); + const request = { projectId: project.id, idempotencyKey: "corgi-gif", prompt: "A corgi typing", width: 1024, height: 1024, source: "queue" as const, + provider: "openai" as const, model: "", transparent: false, referenceIds: [] }; + return { store, api, request }; +} + +it("lets a corrected request reuse the key of a request that failed, without creating duplicates", async () => { + const { store, api, request } = await setup(); + const first = await api.create(request); + await store.put("jobs", first.id, { ...first, status: "failed", error: "The provider rejected the image request" }); + + const corrected = await api.create({ ...request, width: 960, height: 960 }); + expect(corrected.id).toMatch(/^IMG-corgi-gif-[A-Za-z0-9]{8}$/); + expect(corrected.status).toBe("queued"); + // Repeating the corrected request returns the same job; repeating the failed one returns the failed job. + expect((await api.create({ ...request, width: 960, height: 960 })).id).toBe(corrected.id); + expect((await api.create(request)).status).toBe("failed"); + expect((await store.list("jobs")).length).toBe(2); +}); + +it("still refuses a different request under the key of a request that is queued, running or done", async () => { + const { store, api, request } = await setup(); + const first = await api.create(request); + await expect(api.create({ ...request, prompt: "A cat typing" })) + .rejects.toThrow(`Idempotency key already belongs to a different request (${first.id}, queued). Use a new idempotencyKey`); + await store.put("jobs", first.id, { ...first, status: "done" }); + await expect(api.create({ ...request, prompt: "A cat typing" })).rejects.toThrow("different request"); +}); diff --git a/tests/image-fit-cloud.test.ts b/tests/image-fit-cloud.test.ts index 4fea449..5925761 100644 --- a/tests/image-fit-cloud.test.ts +++ b/tests/image-fit-cloud.test.ts @@ -19,6 +19,14 @@ it("requests a centered crop and validates returned dimensions", async () => { await expect(fitImage(input, { width: 80, height: 80 })).rejects.toThrow("unexpected dimensions"); }); +it("refuses to fit a GIF on Cloudflare so the animation is not flattened", async () => { + const frame = await sharp({ create: { width: 80, height: 40, channels: 3, background: "red" } }).png().toBuffer(); + const gif = await sharp([frame, frame], { join: { animated: true } }).gif().toBuffer(); + mocks.transform.mockClear(); + await expect(fitImage(gif, { width: 40, height: 20 }, "gif")).rejects.toThrow("keeping the animation"); + expect(mocks.transform).not.toHaveBeenCalled(); +}); + it("rejects a failed Cloudflare transform even when the response contains matching image bytes", async () => { const input = await sharp({ create: { width: 200, height: 100, channels: 4, background: "red" } }).png().toBuffer(); const fitted = new Uint8Array(await sharp(input).resize(80, 80).png().toBuffer()); diff --git a/tests/image-fit-output.test.ts b/tests/image-fit-output.test.ts index 637e233..7bb78d0 100644 --- a/tests/image-fit-output.test.ts +++ b/tests/image-fit-output.test.ts @@ -24,6 +24,25 @@ it("preserves transparency when fitting a PNG", async () => { expect(data[3]).toBe(0); }); +it("fits WebP and JPEG without converting them to PNG", async () => { + const input = await sharp({ create: { width: 200, height: 100, channels: 3, background: "red" } }).png().toBuffer(); + for (const format of ["webp", "jpeg"] as const) { + const result = await fitImage(input, { width: 80, height: 40 }, format); + expect(result.mime).toBe(format === "jpeg" ? "image/jpeg" : "image/webp"); + expect(await sharp(result.bytes).metadata()).toMatchObject({ width: 80, height: 40, format }); + } +}); + +it("fits an animated GIF down without dropping frames or upscaling", async () => { + const red = await sharp({ create: { width: 80, height: 40, channels: 3, background: "red" } }).png().toBuffer(); + const blue = await sharp({ create: { width: 80, height: 40, channels: 3, background: "blue" } }).png().toBuffer(); + const gif = await sharp([red, blue], { join: { animated: true } }).gif().toBuffer(); + const result = await fitImage(gif, { width: 40, height: 20 }, "gif"); + expect(result.mime).toBe("image/gif"); + expect(await sharp(result.bytes, { animated: true }).metadata()).toMatchObject({ width: 40, pageHeight: 20, pages: 2 }); + await expect(fitImage(gif, { width: 160, height: 80 }, "gif")).rejects.toThrow("without upscaling"); +}); + it("crops the center rather than either edge", async () => { const center = await sharp({ create: { width: 100, height: 100, channels: 4, background: "blue" } }).png().toBuffer(); const input = await sharp({ create: { width: 200, height: 100, channels: 4, background: "red" } }) diff --git a/tests/mcp-gallery-view.test.ts b/tests/mcp-gallery-view.test.ts index 193f657..c27b697 100644 --- a/tests/mcp-gallery-view.test.ts +++ b/tests/mcp-gallery-view.test.ts @@ -16,6 +16,10 @@ vi.mock("../src/mcp/views/compact-app", () => ({ applyDocumentTheme: vi.fn(), applyHostStyleVariables: vi.fn(), })); afterEach(() => { document.body.innerHTML = ""; vi.unstubAllGlobals(); }); +// A preview asks the app-only tool first, so the resource fallback starts a few microtasks later. +async function settle() { + for (let turn = 0; turn < 8; turn++) await Promise.resolve(); +} async function open(withViewport = false) { vi.resetModules(); document.body.innerHTML = '

          '; @@ -167,12 +171,42 @@ it("offers only host-supported display modes and follows the confirmed mode", as expect(button.textContent).toBe("Full screen"); }); +it("loads card previews through the app-only tool without reading the resource", async () => { + const app = await open(); + app.callServerTool.mockResolvedValue({ content: [{ type: "image", mimeType: "image/webp", data: "dG9vbA==" }] }); + app.ontoolresult(result([{ id: "one", title: "One", status: "done" }, { id: "two", title: "Two", status: "queued" }])); + await settle(); + expect(app.callServerTool.mock.calls).toEqual([[{ name: "read_thumbnail", arguments: { id: "one" } }]]); + expect(document.querySelector('[data-image-id="one"] img')!.src).toBe("data:image/webp;base64,dG9vbA=="); + expect(app.readServerResource).not.toHaveBeenCalled(); + await app.onteardown(); +}); + +it("falls back to the thumbnail resource and marks a card when both sources fail", async () => { + const app = await open(); + app.callServerTool.mockResolvedValue({ isError: true, content: [{ type: "text", text: "Image is unavailable" }] }); + app.readServerResource.mockImplementation(async ({ uri }: { uri: string }) => { + if (uri.endsWith("/two")) throw new Error("Resource unavailable"); + return { contents: [{ mimeType: "image/webp", blob: "cmVzb3VyY2U=" }] }; + }); + app.ontoolresult(result([{ id: "one", title: "One", status: "done" }, { id: "two", title: "Two", status: "done" }])); + await settle(); + const first = document.querySelector('[data-image-id="one"] img')!; + const second = document.querySelector('[data-image-id="two"] img')!; + expect(first.src).toBe("data:image/webp;base64,cmVzb3VyY2U="); + expect(first.alt).toBe("One"); + expect(second.hasAttribute("src")).toBe(false); + expect(second.alt).toBe("Two — preview unavailable"); + await app.onteardown(); +}); + it("ignores a thumbnail delivered after the gallery was replaced", async () => { const app = await open(); let finish!: (value: unknown) => void; app.readServerResource.mockImplementation(() => new Promise(resolve => { finish = resolve; })); app.ontoolresult(result([{ id: "old", title: "Old", status: "done" }])); const oldImage = document.querySelector("#gallery img")!; + await settle(); app.ontoolresult(result([{ id: "new", title: "New", status: "queued" }])); finish({ contents: [{ mimeType: "image/png", blob: "YWJj" }] }); await Promise.resolve(); @@ -186,6 +220,7 @@ it("ignores a thumbnail failure after teardown", async () => { app.readServerResource.mockImplementation(() => new Promise((_, reject) => { fail = reject; })); app.ontoolresult(result([{ id: "one", title: "One", status: "done" }])); const image = document.querySelector("#gallery img")!; + await settle(); await app.onteardown(); fail(new Error("Disconnected")); await Promise.resolve(); @@ -273,8 +308,8 @@ it.each([false, true])("windows cards and reloads evicted previews (over budget: app.readServerResource.mockResolvedValue({ contents: [{ blob, mimeType: "image/png" }] }); app.ontoolresult(result(Array.from({ length: 100 }, (_, i) => ({ id: `image-${i}`, title: `Image ${i}`, status: "done" })))); expect(grid.querySelectorAll("label").length).toBeLessThan(15); + await settle(); expect(app.readServerResource.mock.calls.length).toBeLessThan(15); - await Promise.resolve(); const first = grid.querySelector("input")!; first.checked = true; first.dispatchEvent(new Event("change")); @@ -369,6 +404,7 @@ it("reuses a pending thumbnail read when a card returns to the viewport", async app.ontoolresult(result(Array.from({ length: 100 }, (_, i) => ({ id: `image-${i}`, title: `Image ${i}`, status: "done", })))); + await settle(); top = -3000; window.dispatchEvent(new Event("scroll")); expect(grid.querySelector('[data-image-id="image-0"]')).toBeNull(); diff --git a/tests/mcp-hosted-views.test.ts b/tests/mcp-hosted-views.test.ts new file mode 100644 index 0000000..fa938e5 --- /dev/null +++ b/tests/mcp-hosted-views.test.ts @@ -0,0 +1,83 @@ +import { GALLERY_VIEW_URI, IMAGE_VIEW_URI, JOB_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"; + +let root: string; +beforeEach(async () => { + root = await mkdtemp(path.join(os.tmpdir(), "mcp-hosted-")); + 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; +}); + +async function tools(appViews?: "always") { + const server = createServer(appViews ? { appViews } : undefined); + // A client without the MCP Apps extension, like a stateless request after initialize. + const client = new Client({ name: "test", version: "1" }); + const [a, b] = InMemoryTransport.createLinkedPair(); + await server.connect(a); + await client.connect(b); + const listed = (await client.listTools()).tools; + const resources = (await client.listResources()).resources.map(resource => resource.uri); + await client.close(); + await server.close(); + return { listed, resources }; +} + +it("lists the MCP Apps views on a stateless hosted server without negotiation", async () => { + const { listed, resources } = await tools("always"); + const byName = Object.fromEntries(listed.map(tool => [tool.name, tool])); + expect(byName.request_image?._meta).toMatchObject({ ui: { resourceUri: JOB_VIEW_URI } }); + expect(byName.show_image?._meta).toMatchObject({ ui: { resourceUri: IMAGE_VIEW_URI } }); + expect(byName.show_images?._meta).toMatchObject({ ui: { resourceUri: GALLERY_VIEW_URI } }); + expect(resources).toEqual(expect.arrayContaining([JOB_VIEW_URI, IMAGE_VIEW_URI, GALLERY_VIEW_URI])); +}); + +it("keeps views off for a host that does not advertise MCP Apps", async () => { + const { listed } = await tools(); + expect(listed.find(tool => tool.name === "request_image")?._meta?.ui).toBeUndefined(); +}); + +it("marks reading tools read-only and billing or cancelling tools as such", async () => { + const { listed } = await tools("always"); + const hints = Object.fromEntries(listed.map(tool => [tool.name, tool.annotations])); + for (const name of ["list_models", "wait_for_job", "get_job", "show_job", "list_projects", "view_image", "get_job_state"]) + expect(hints[name], name).toMatchObject({ readOnlyHint: true, destructiveHint: false }); + for (const name of ["request_image", "retry_image", "create_project", "set_generation_source"]) + expect(hints[name], name).toMatchObject({ readOnlyHint: false }); + expect(hints.request_image).toMatchObject({ openWorldHint: true, destructiveHint: false }); + expect(hints.cancel_job).toMatchObject({ destructiveHint: true }); + // Every listed tool carries an explicit hint. + for (const tool of listed) expect(tool.annotations?.readOnlyHint, tool.name).toBeTypeOf("boolean"); +}); + +it("gives each view an address that changes with its content, so hosts do not show a cached old view", async () => { + const { jobViewHtml, jobViewVersion } = await import("../src/mcp/views/job-html"); + const { createHash } = await import("node:crypto"); + expect(jobViewVersion).toBe(createHash("sha256").update(jobViewHtml).digest("hex").slice(0, 10)); + expect(JOB_VIEW_URI).toBe(`ui://image-queue/job-${jobViewVersion}`); + for (const uri of [GALLERY_VIEW_URI, IMAGE_VIEW_URI]) expect(uri).toMatch(/^ui:\/\/image-queue\/[a-z]+-[0-9a-f]{10}$/); +}); + +it("links the hosted request view to the deployment that served it, not the local default", async () => { + const server = createServer({ appViews: "always", panelUrl: "https://app.example.com" }); + const client = new Client({ name: "test", version: "1" }); + const [a, b] = InMemoryTransport.createLinkedPair(); + await server.connect(a); + await client.connect(b); + const view = await client.readResource({ uri: JOB_VIEW_URI }); + await client.close(); + await server.close(); + const html = "text" in view.contents[0] ? view.contents[0].text : ""; + expect(html).toContain(`data-dashboard="${encodeURIComponent("https://app.example.com")}"`); + expect(html).not.toContain("127.0.0.1"); +}); diff --git a/tests/mcp-http-session.test.ts b/tests/mcp-http-session.test.ts index 6960e7a..90feb81 100644 --- a/tests/mcp-http-session.test.ts +++ b/tests/mcp-http-session.test.ts @@ -1,5 +1,7 @@ +import { GALLERY_VIEW_URI, IMAGE_VIEW_URI, JOB_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"; it("preserves negotiated MCP Apps resources across authenticated HTTP requests", async () => { vi.stubEnv("IMAGE_QUEUE_MCP_TOKEN", "local-test-token"); @@ -30,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(["ui://image-queue/gallery", "ui://image-queue/image", "ui://image-queue/job"]); + .toEqual([GALLERY_VIEW_URI, IMAGE_VIEW_URI, JOB_VIEW_URI]); const unauthorized = await POST(new Request(url, { method: "POST", headers: { "mcp-session-id": session! }, })); @@ -155,54 +157,74 @@ it("evicts the least recently active session when the local session limit is rea }); it("rejects DELETE for the stateless Cloudflare transport", async () => { - vi.stubEnv("IMAGE_QUEUE_MCP_TOKEN", "local-test-token"); - vi.stubEnv("IMAGE_QUEUE_STORAGE_DRIVER", "cloudflare"); + const { sign } = await syntheticAccess(); try { const response = await DELETE(new Request("http://localhost/api/mcp", { method: "DELETE", - headers: { authorization: "Bearer local-test-token" }, + headers: { "cf-access-jwt-assertion": await sign() }, })); expect(response.status).toBe(405); expect(response.headers.has("mcp-session-id")).toBe(false); } finally { vi.unstubAllEnvs(); + vi.unstubAllGlobals(); } }); -it("handles independent authenticated MCP requests in Cloudflare mode", async () => { +it("serves Cloudflare MCP only to an allowlisted Cloudflare Access identity", async () => { + const { sign } = await syntheticAccess(); + // A static token must not open the hosted endpoint, even when configured. vi.stubEnv("IMAGE_QUEUE_MCP_TOKEN", "local-test-token"); - vi.stubEnv("IMAGE_QUEUE_STORAGE_DRIVER", "cloudflare"); try { - const send = (message: object, token = "local-test-token") => POST(new Request("http://localhost/api/mcp", { + const send = (message: object, headers: Record) => POST(new Request("http://localhost/api/mcp", { method: "POST", headers: { - authorization: `Bearer ${token}`, accept: "application/json, text/event-stream", "content-type": "application/json", + ...headers, }, body: JSON.stringify({ jsonrpc: "2.0", ...message }), })); + const owner = { "cf-access-jwt-assertion": await sign() }; const params = { protocolVersion: "2025-11-25", capabilities: {}, clientInfo: { name: "stateless-test", version: "1.0" }, }; - const initialize = await send({ id: 1, method: "initialize", params }); + const initialize = await send({ id: 1, method: "initialize", params }, owner); expect(initialize.status).toBe(200); expect(initialize.headers.has("mcp-session-id")).toBe(false); expect(await initialize.json()).toMatchObject({ id: 1, result: { protocolVersion: "2025-11-25" } }); - const tools = await send({ id: 2, method: "tools/list" }); + const tools = await send({ id: 2, method: "tools/list" }, owner); expect(tools.status).toBe(200); expect(tools.headers.has("mcp-session-id")).toBe(false); expect(await tools.json()).toMatchObject({ id: 2, result: { tools: expect.arrayContaining([expect.objectContaining({ name: "request_image" })]), } }); - expect((await send({ id: 3, method: "tools/list" }, "wrong-token")).status).toBe(401); + const rejected: Record[] = [ + {}, + { authorization: "Bearer local-test-token" }, + { authorization: "Bearer oauth:opaque-managed-token" }, + { "cf-access-jwt-assertion": "not-a-jwt" }, + { "cf-access-jwt-assertion": await sign({ audience: "another-application" }) }, + { "cf-access-jwt-assertion": await sign({ expiration: "5m ago" }) }, + ]; + for (const headers of rejected) { + const response = await send({ id: 3, method: "tools/list" }, headers); + expect(response.status).toBe(401); + expect(response.headers.get("cache-control")).toBe("no-store"); + expect(await response.text()).toBe("Unauthorized"); + } + // A signed-in identity outside the allowlist is refused without restarting OAuth. + const outsider = await send({ id: 4, method: "tools/list" }, { "cf-access-jwt-assertion": await sign({ email: "intruder@example.com" }) }); + expect(outsider.status).toBe(403); + expect(outsider.headers.get("www-authenticate")).toBeNull(); } finally { vi.unstubAllEnvs(); + vi.unstubAllGlobals(); } }); diff --git a/tests/mcp-image-view.test.ts b/tests/mcp-image-view.test.ts index 0e7ed78..cbeb581 100644 --- a/tests/mcp-image-view.test.ts +++ b/tests/mcp-image-view.test.ts @@ -10,6 +10,12 @@ vi.mock("../src/mcp/views/compact-app", () => ({ constructor() { bridge.app = this; } }, applyDocumentTheme: vi.fn(), applyHostStyleVariables: vi.fn(), })); +// A preview asks the app-only tool first, so the resource fallback starts a few microtasks later. +async function settle() { + for (let turn = 0; turn < 8; turn++) await Promise.resolve(); +} +/** Calls a view made for anything other than loading its preview. */ +const actionCalls = () => bridge.app.callServerTool.mock.calls.filter(([request]: [{ name: string }]) => request.name !== "read_thumbnail"); it("renders notes safely and switches versions by record identifier", async () => { document.body.innerHTML = '

            '; await import("../src/mcp/views/image"); @@ -61,13 +67,45 @@ it("positions saved note pins and focuses the matching note", async () => { await bridge.app.onteardown(); }); +it.each([ + { source: "the app-only tool", tool: { content: [{ type: "image", mimeType: "image/webp", data: "dG9vbA==" }] }, src: "data:image/webp;base64,dG9vbA==", reads: 0 }, + { source: "the resource after the tool fails", tool: { isError: true, content: [{ type: "text", text: "Image is unavailable" }] }, src: "data:image/webp;base64,cmVzb3VyY2U=", reads: 1 }, +])("loads the preview from $source", async ({ tool, src, reads }) => { + vi.resetModules(); + document.body.innerHTML = '

              '; + await import("../src/mcp/views/image"); + bridge.app.callServerTool.mockResolvedValue(tool); + bridge.app.readServerResource.mockResolvedValue({ contents: [{ mimeType: "image/webp", blob: "cmVzb3VyY2U=" }] }); + bridge.app.ontoolresult({ content: [{ text: JSON.stringify({ image: { id: "one", status: "done" }, notes: [], versions: [] }) }] }); + await settle(); + expect(bridge.app.callServerTool).toHaveBeenCalledWith({ name: "read_thumbnail", arguments: { id: "one" } }); + expect(document.querySelector("#preview")!.src).toBe(src); + expect(document.querySelector('[role="status"]')?.textContent).toBe("Ready"); + expect(bridge.app.readServerResource).toHaveBeenCalledTimes(reads); + await bridge.app.onteardown(); +}); + +it("reports an unavailable preview only after the tool and the resource both fail", async () => { + vi.resetModules(); + document.body.innerHTML = '

                '; + await import("../src/mcp/views/image"); + bridge.app.callServerTool.mockRejectedValue(new Error("Unknown tool")); + bridge.app.readServerResource.mockRejectedValue(new Error("Resource unavailable")); + bridge.app.ontoolresult({ content: [{ text: JSON.stringify({ image: { id: "one", status: "done" }, notes: [], versions: [] }) }] }); + await settle(); + expect(bridge.app.readServerResource).toHaveBeenCalledTimes(1); + expect(document.querySelector('[role="status"]')?.textContent).toBe("Preview unavailable"); + expect(document.querySelector("#preview")!.hasAttribute("src")).toBe(false); + await bridge.app.onteardown(); +}); + it("shows pins after preview load and hides them on decode failure", async () => { vi.resetModules(); document.body.innerHTML = '

                  '; await import("../src/mcp/views/image"); bridge.app.readServerResource.mockResolvedValue({ contents: [{ mimeType: "image/png", blob: "YWJj" }] }); bridge.app.ontoolresult({ content: [{ text: JSON.stringify({ image: { id: "one", status: "done" }, notes: [{ text: "Change sky", x: 0.2, y: 0.3 }], versions: [] }) }] }); - await Promise.resolve(); + await settle(); const preview = document.querySelector("#preview")!; const pins = document.querySelector("#pins")!; preview.dispatchEvent(new Event("load")); @@ -248,7 +286,7 @@ it("queues corrections only on click and reuses the key after failure", async () document.body.innerHTML = '

                    '; await import("../src/mcp/views/image"); bridge.app.ontoolresult({ content: [{ text: JSON.stringify({ image: { id: "one", status: "done" }, notes: [{ text: "Fix" }], versions: [] }) }] }); - expect(bridge.app.callServerTool).not.toHaveBeenCalled(); + expect(actionCalls()).toEqual([]); bridge.app.callServerTool .mockResolvedValueOnce({ isError: true, content: [{ type: "text", text: "Choose an available image model" }] }) .mockResolvedValueOnce({ isError: true, content: [{ type: "text", text: "Internal file path" }] }); @@ -259,8 +297,8 @@ it("queues corrections only on click and reuses the key after failure", async () expect(status.textContent).toBe("Connect the original image model in Settings, then retry this correction."); button.click(); await Promise.resolve(); - expect(status.textContent).toBe("Could not queue correction. Retry to check the same request."); - const calls = bridge.app.callServerTool.mock.calls; + expect(status.textContent).toBe("Could not request the next version. Retry to check the same request."); + const calls = actionCalls(); expect(calls).toHaveLength(2); expect(calls[0][0].name).toBe("add_notes_to_queue"); expect(calls[0][0].arguments).toEqual(calls[1][0].arguments); @@ -275,10 +313,10 @@ it("keeps an unsaved note when the user requests a correction", async () => { const text = document.querySelector("#note-text")!; text.value = "Unsaved instruction"; document.querySelector("#queue-notes")!.click(); - expect(bridge.app.callServerTool).not.toHaveBeenCalled(); + expect(actionCalls()).toEqual([]); expect(text.value).toBe("Unsaved instruction"); expect(document.activeElement).toBe(text); - expect(document.querySelector('[role="status"]')?.textContent).toContain("Save your note"); + expect(document.querySelector('[role="status"]')?.textContent).toContain("Save your change"); await bridge.app.onteardown(); }); @@ -294,7 +332,7 @@ it.each([ const button = document.querySelector("#queue-notes")!; expect(button.disabled).toBe(true); button.click(); - expect(bridge.app.callServerTool).not.toHaveBeenCalled(); + expect(actionCalls()).toEqual([]); await bridge.app.onteardown(); }); @@ -310,9 +348,9 @@ it("refreshes sent notes and disables resubmission after a successful correction await Promise.resolve(); await Promise.resolve(); await Promise.resolve(); - expect(bridge.app.callServerTool).toHaveBeenLastCalledWith({ name: "get_image_details", arguments: { id: "one" } }); + expect(actionCalls().at(-1)).toEqual([{ name: "get_image_details", arguments: { id: "one" } }]); expect(button.disabled).toBe(true); - expect(document.querySelector('[role="status"]')?.textContent).toBe("Correction added to queue."); + expect(document.querySelector('[role="status"]')?.textContent).toBe("Next version requested."); await bridge.app.onteardown(); }); @@ -368,7 +406,7 @@ it("does not overwrite a newer image with an old correction confirmation", async await Promise.resolve(); await Promise.resolve(); expect(document.querySelector("#notes")?.textContent).toBe("two"); - expect(document.querySelector('[role="status"]')?.textContent).not.toBe("Correction added to queue."); + expect(document.querySelector('[role="status"]')?.textContent).not.toBe("Next version requested."); await bridge.app.onteardown(); }); @@ -405,7 +443,7 @@ it("keeps an unchanged image and notes mounted and reuses pixels after a note ed app.readServerResource.mockResolvedValue({contents:[{blob:"YWJj",mimeType:"image/png"}]}); const data={image:{id:"stable",status:"done",prompt:"Image"},notes:[{text:"First"}],versions:[{id:"stable"}]}; const send=(value:unknown)=>app.ontoolresult({content:[{text:JSON.stringify(value)}]}); - send(data);await Promise.resolve();await Promise.resolve(); + send(data);await settle(); const preview=document.querySelector('#preview')!,note=document.querySelector('#notes li'); const src=preview.src; const version=document.querySelector('#versions button'); @@ -422,3 +460,95 @@ it("keeps an unchanged image and notes mounted and reuses pixels after a note ed expect(document.querySelectorAll('#versions button')).toHaveLength(2); await app.onteardown(); }); + +const phoneBody = '

                      '; + +it("lets a finger scroll across the image without dropping a point, and marks a point on a tap", async () => { + vi.resetModules(); + document.body.innerHTML = phoneBody; + await import("../src/mcp/views/image"); + bridge.app.ontoolresult({ content: [{ text: JSON.stringify({ image: { id: "one", status: "queued" }, notes: [], versions: [] }) }] }); + const preview = document.querySelector("#preview")!; + preview.hidden = false; + preview.getBoundingClientRect = () => ({ left: 0, top: 0, width: 200, height: 200 } as DOMRect); + preview.setPointerCapture = vi.fn(); + const draft = document.querySelector("#draft-point")!; + const down = new PointerEvent("pointerdown", { pointerId: 1, pointerType: "touch", button: 0, clientX: 100, clientY: 150, cancelable: true }); + preview.dispatchEvent(down); + expect(down.defaultPrevented).toBe(false); + expect(preview.setPointerCapture).not.toHaveBeenCalled(); + preview.dispatchEvent(new PointerEvent("pointermove", { pointerId: 1, pointerType: "touch", clientX: 100, clientY: 60 })); + preview.dispatchEvent(new PointerEvent("pointerup", { pointerId: 1, pointerType: "touch", clientX: 100, clientY: 60 })); + expect(draft.hidden).toBe(true); + preview.dispatchEvent(new PointerEvent("pointerdown", { pointerId: 2, pointerType: "touch", button: 0, clientX: 100, clientY: 150 })); + preview.dispatchEvent(new PointerEvent("pointercancel", { pointerId: 2, pointerType: "touch" })); + expect(draft.hidden).toBe(true); + preview.dispatchEvent(new PointerEvent("pointerdown", { pointerId: 3, pointerType: "touch", button: 0, clientX: 50, clientY: 150 })); + preview.dispatchEvent(new PointerEvent("pointerup", { pointerId: 3, pointerType: "touch", clientX: 53, clientY: 152 })); + expect(draft.hidden).toBe(false); + expect(draft.style.left).toBe("25%"); + expect(draft.style.top).toBe("75%"); + await bridge.app.onteardown(); +}); + +it("names the status and source like the request view, plays a GIF and hides controls with nothing to do", async () => { + vi.resetModules(); + document.body.innerHTML = phoneBody; + await import("../src/mcp/views/image"); + bridge.app.callServerTool.mockResolvedValue({ content: [{ type: "image", data: "R0lG", mimeType: "image/webp" }, { type: "text", text: '{"animated":true}' }] }); + bridge.app.ontoolresult({ content: [{ text: JSON.stringify({ image: { id: "one", status: "done", source: "api", provider: "openai", model: "gpt-image-2.6-sunburst", outputFormat: "gif" }, notes: [], versions: [{ id: "one", versionNumber: 1 }] }) }] }); + await settle(); + expect(document.querySelector('[role="status"]')!.textContent).toBe("Ready"); + expect(document.querySelector("#source")!.textContent).toBe("OpenAI · gpt-image-2.6-sunburst"); + expect(bridge.app.callServerTool).toHaveBeenCalledWith({ name: "read_thumbnail", arguments: { id: "one", animated: true } }); + expect(document.querySelector("#versions")!.hidden).toBe(true); + expect(document.querySelector("#queue-notes")!.hidden).toBe(true); + await bridge.app.onteardown(); +}); + +const formBody = phoneBody.replace('
                      ', '

                      ').replace('
                        ', '
                          ') + "
                        "; + +it("offers no changes for an image that has no next version, and brings the form back for one that has", async () => { + vi.resetModules(); + document.body.innerHTML = formBody; + await import("../src/mcp/views/image"); + bridge.app.callServerTool.mockResolvedValue({ content: [{ type: "image", data: "R0lG", mimeType: "image/webp" }] }); + bridge.app.ontoolresult({ content: [{ text: JSON.stringify({ image: { id: "one", status: "done", outputFormat: "svg", nextVersion: "none" }, notes: [{ text: "Earlier note", x: 0.5, y: 0.5 }], versions: [] }) }] }); + await settle(); + expect(document.querySelector("#pins")!.childElementCount).toBe(0); + expect(document.querySelector("#note-form")!.hidden).toBe(true); + expect(document.querySelector(".saved")!.hidden).toBe(true); + expect(document.querySelector("#no-corrections")!.hidden).toBe(false); + document.querySelector("#queue-notes")!.click(); + expect(actionCalls()).toEqual([]); + bridge.app.ontoolresult({ content: [{ text: JSON.stringify({ image: { id: "two", status: "done", outputFormat: "png", nextVersion: "edit" }, notes: [], versions: [] }) }] }); + expect(document.querySelector("#note-form")!.hidden).toBe(false); + expect(document.querySelector("#no-corrections")!.hidden).toBe(true); + expect(document.querySelector("#note-hint")!.textContent).toContain("tap that place on the image"); + await bridge.app.onteardown(); +}); + +it("takes changes for an animation without letting the image be tapped, and requests the next version", async () => { + vi.resetModules(); + document.body.innerHTML = formBody; + await import("../src/mcp/views/image"); + bridge.app.callServerTool.mockResolvedValue({ content: [{ type: "image", data: "R0lG", mimeType: "image/webp" }] }); + bridge.app.ontoolresult({ content: [{ text: JSON.stringify({ image: { id: "one", status: "done", outputFormat: "gif", nextVersion: "regenerate" }, notes: [{ text: "Fluffier tail" }], versions: [] }) }] }); + await settle(); + expect(document.querySelector("#note-form")!.hidden).toBe(false); + expect(document.querySelector("#no-corrections")!.hidden).toBe(true); + expect(document.querySelector("#note-hint")!.textContent).toContain("whole animation again"); + const preview = document.querySelector("#preview")!; + preview.getBoundingClientRect = () => ({ left: 0, top: 0, width: 200, height: 200 } as DOMRect); + preview.setPointerCapture = vi.fn(); + preview.dispatchEvent(new PointerEvent("pointerdown", { pointerId: 1, button: 0, clientX: 50, clientY: 50 })); + preview.dispatchEvent(new PointerEvent("pointerup", { pointerId: 1, clientX: 50, clientY: 50 })); + expect(document.querySelector("#draft-point")!.hidden).toBe(true); + const button = document.querySelector("#queue-notes")!; + expect(button.hidden).toBe(false); + expect(button.disabled).toBe(false); + button.click(); + await Promise.resolve(); + expect(actionCalls()[0][0]).toMatchObject({ name: "add_notes_to_queue", arguments: { imageId: "one" } }); + await bridge.app.onteardown(); +}); diff --git a/tests/mcp-job-view.test.ts b/tests/mcp-job-view.test.ts index b805100..92fdcf1 100644 --- a/tests/mcp-job-view.test.ts +++ b/tests/mcp-job-view.test.ts @@ -8,6 +8,8 @@ vi.mock("../src/mcp/views/compact-app", () => ({ onteardown: any; callServerTool = vi.fn(); openLink = vi.fn(async () => ({})); + downloadFile = vi.fn(async () => ({})); + canDownloadFiles = vi.fn(() => true); readServerResource = vi.fn(async () => ({contents:[]})); connect = vi.fn(async () => {}); getHostContext = vi.fn(() => ({theme:"dark",styles:{variables:{"--color-text-primary":"white"}}})); @@ -23,10 +25,14 @@ afterEach(() => { vi.unstubAllGlobals(); document.body.innerHTML = ""; }); +// The preview asks the app-only tool first, so the resource fallback starts a few microtasks later. +async function settle() { + for (let turn = 0; turn < 8; turn++) await Promise.resolve(); +} async function openView() { vi.resetModules(); document.body.innerHTML = - '

                        ';
                        +    '

                        ';
                           vi.stubGlobal(
                             "IntersectionObserver",
                             class {
                        @@ -76,7 +82,7 @@ it("renders state and polls until completion", async () => {
                           bridge.visibility([{ isIntersecting: false }]);
                           bridge.visibility([{ isIntersecting: true }]);
                           await vi.advanceTimersByTimeAsync(10000);
                        -  expect(app.callServerTool).toHaveBeenCalledTimes(1);
                        +  expect(app.callServerTool.mock.calls.filter(([request]: [{ name: string }]) => request.name === "get_job_state")).toHaveLength(1);
                           await app.onteardown();
                         });
                         it("handles malformed responses and deleted jobs", async () => {
                        @@ -112,9 +118,9 @@ it("retries a failed preview when the same completed job is rendered again", asy
                           app.readServerResource.mockRejectedValueOnce(new Error("temporary"));
                           const result={content:[{type:"text",text:JSON.stringify({id:"one",status:"done",prompt:"Image"})}]};
                           app.ontoolresult(result);
                        -  await Promise.resolve();
                        -  await Promise.resolve();
                        +  await settle();
                           app.ontoolresult(result);
                        +  await settle();
                           expect(app.readServerResource).toHaveBeenCalledTimes(2);
                           await app.onteardown();
                         });
                        @@ -123,14 +129,59 @@ it("reports empty thumbnail responses and permits retry", async () => {
                           const app = await openView();
                           const result={content:[{type:"text",text:JSON.stringify({id:"one",status:"done",prompt:"Image"})}]};
                           app.ontoolresult(result);
                        -  await Promise.resolve();
                        -  await Promise.resolve();
                        +  await settle();
                           expect(document.querySelector('[role="status"]')?.textContent).toBe("Ready. Preview unavailable.");
                           app.ontoolresult(result);
                        +  await settle();
                           expect(app.readServerResource).toHaveBeenCalledTimes(2);
                           await app.onteardown();
                         });
                         
                        +it("shows the preview from the app-only tool without reading the resource", async () => {
                        +  const app = await openView();
                        +  document.body.insertAdjacentHTML("beforeend", '
                        '); + app.callServerTool.mockImplementation(async ({ name }: { name: string }) => name === "read_thumbnail" + ? { content: [{ type: "image", mimeType: "image/webp", data: "dG9vbA==" }] } + : { content: [{ type: "text", text: JSON.stringify({ id: "one", status: "done", prompt: "Image" }) }] }); + app.ontoolresult({ content: [{ type: "text", text: JSON.stringify({ id: "one", status: "done", prompt: "Image" }) }] }); + await settle(); + const preview = document.querySelector("#preview")!; + expect(app.callServerTool).toHaveBeenCalledWith({ name: "read_thumbnail", arguments: { id: "one" } }); + expect(preview.src).toBe("data:image/webp;base64,dG9vbA=="); + expect(preview.hidden).toBe(false); + expect(document.querySelector("#placeholder")!.hidden).toBe(true); + expect(document.querySelector('[role="status"]')?.textContent).toBe("Ready"); + expect(app.readServerResource).not.toHaveBeenCalled(); + await app.onteardown(); +}); + +it("falls back to the thumbnail resource when the tool is refused", async () => { + const app = await openView(); + document.body.insertAdjacentHTML("beforeend", ''); + app.callServerTool.mockRejectedValue(new Error("Unknown tool")); + app.readServerResource.mockResolvedValue({ contents: [{ blob: "cmVzb3VyY2U=", mimeType: "image/webp" }] }); + app.ontoolresult({ content: [{ type: "text", text: JSON.stringify({ id: "one", status: "done", prompt: "Image" }) }] }); + await settle(); + expect(app.readServerResource).toHaveBeenCalledWith({ uri: "image-queue://thumbnail/one" }); + expect(document.querySelector("#preview")!.src).toBe("data:image/webp;base64,cmVzb3VyY2U="); + await app.onteardown(); +}); + +it("reports an unavailable preview only after the tool and the resource both fail", async () => { + const app = await openView(); + document.body.insertAdjacentHTML("beforeend", ''); + const job = { content: [{ type: "text", text: JSON.stringify({ id: "one", status: "done", prompt: "Image" }) }] }; + app.callServerTool.mockImplementation(async ({ name }: { name: string }) => name === "read_thumbnail" + ? { isError: true, content: [{ type: "text", text: "Image is unavailable" }] } : job); + app.readServerResource.mockRejectedValue(new Error("Resource unavailable")); + app.ontoolresult(job); + await settle(); + expect(app.readServerResource).toHaveBeenCalledTimes(1); + expect(document.querySelector('[role="status"]')?.textContent).toBe("Ready. Preview unavailable."); + expect(document.querySelector("#preview")!.hidden).toBe(true); + await app.onteardown(); +}); + it("ignores results after teardown", async () => { const app=await openView(); await app.onteardown(); @@ -155,12 +206,11 @@ it("ignores an old thumbnail response after switching jobs", async () => { app.readServerResource.mockImplementationOnce(() => new Promise(resolve => { resolveOld = resolve; })); app.readServerResource.mockResolvedValueOnce({ contents: [{ blob: "bmV3", mimeType: "image/png" }] }); app.ontoolresult({ content: [{ type: "text", text: JSON.stringify({ id: "old", status: "done", prompt: "Old" }) }] }); + await settle(); app.ontoolresult({ content: [{ type: "text", text: JSON.stringify({ id: "new", status: "done", prompt: "New" }) }] }); - await Promise.resolve(); - await Promise.resolve(); + await settle(); resolveOld({ contents: [{ blob: "b2xk", mimeType: "image/png" }] }); - await Promise.resolve(); - await Promise.resolve(); + await settle(); expect(document.querySelector("#preview")!.src).toBe("data:image/png;base64,bmV3"); expect(document.querySelector("#prompt")?.textContent).toBe("New"); await app.onteardown(); @@ -204,10 +254,10 @@ it("does not restore an in-flight preview after a trash update", async () => { app.readServerResource.mockImplementationOnce(() => new Promise(resolve => { complete = resolve; })); const job = { id: "one", status: "done", prompt: "Image" }; app.ontoolresult({ content: [{ type: "text", text: JSON.stringify(job) }] }); + await settle(); app.ontoolresult({ content: [{ type: "text", text: JSON.stringify({ ...job, trashedAt: "2026-11-14" }) }] }); complete({ contents: [{ blob: "b2xk", mimeType: "image/png" }] }); - await Promise.resolve(); - await Promise.resolve(); + await settle(); const preview = document.querySelector("#preview")!; expect(preview.hidden).toBe(true); expect(preview.hasAttribute("src")).toBe(false); @@ -319,8 +369,7 @@ it("keeps the placeholder hidden on repeated ready updates after preview loading app.readServerResource.mockResolvedValue({ contents: [{ blob: "aGVsbG8=", mimeType: "image/png" }] }); app.callServerTool.mockResolvedValue(response); app.ontoolresult(response); - await Promise.resolve(); - await Promise.resolve(); + await settle(); app.ontoolresult(response); expect(placeholder.hidden).toBe(true); await app.onteardown(); @@ -461,7 +510,7 @@ it("keeps the loaded preview and copy state through an unchanged job refresh", a const job={id:"stable",status:"done",prompt:"Stable image",outputPath:"/output/stable.png"}; const result={content:[{type:"text",text:JSON.stringify(job)}]}; app.ontoolresult(result); - await Promise.resolve();await Promise.resolve(); + await settle(); const preview=document.querySelector('#preview')!; const source=preview.src; const copy=document.querySelector('#copy-path')!; @@ -474,3 +523,100 @@ it("keeps the loaded preview and copy state through an unchanged job refresh", a expect(app.readServerResource).toHaveBeenCalledTimes(1); await app.onteardown(); }); + +it("offers a full-size download for a finished image and hands it to the host", async () => { + const app = await openView(); + const file = { uri: "image-queue://image/one.png", mimeType: "image/png", blob: "UE5H" }; + app.callServerTool.mockImplementation(async ({ name }: { name: string }) => + name === "read_image_file" ? { content: [{ type: "resource", resource: file }] } : { isError: true, content: [] }); + document.body.insertAdjacentHTML("beforeend", ''); + const download = document.querySelector("#download")!; + app.ontoolresult({ content: [{ type: "text", text: JSON.stringify({ id: "one", status: "running", prompt: "A forest" }) }] }); + expect(download.hidden).toBe(true); + expect(document.querySelector("#placeholder")?.dataset.label).toBe("Generating…"); + app.ontoolresult({ content: [{ type: "text", text: JSON.stringify({ id: "one", status: "done", prompt: "A forest" }) }] }); + expect(download.hidden).toBe(false); + expect(document.querySelector("#placeholder")?.dataset.label).toBe("Loading preview…"); + download.click(); + await settle(); + expect(app.callServerTool).toHaveBeenCalledWith({ name: "read_image_file", arguments: { id: "one" } }); + expect(app.downloadFile).toHaveBeenCalledWith({ contents: [{ type: "resource", resource: file }] }); + expect(download.textContent).toBe("Download"); +}); + +it("opens the full image when the host cannot save files", async () => { + const app = await openView(); + app.canDownloadFiles.mockReturnValue(false); + app.callServerTool.mockResolvedValue({ isError: true, content: [] }); + document.body.dataset.dashboard = encodeURIComponent("https://app.example.com"); + app.ontoolresult({ content: [{ type: "text", text: JSON.stringify({ id: "one", status: "done", prompt: "A forest" }) }] }); + document.querySelector("#download")!.click(); + await settle(); + expect(app.openLink).toHaveBeenCalledWith({ url: "https://app.example.com/api/asset?job=one" }); + delete document.body.dataset.dashboard; +}); + +const gifJob = { content: [{ type: "text", text: JSON.stringify({ id: "gif", status: "done", prompt: "A corgi typing", outputFormat: "gif" }) }] }; +function previewResult(data: string, animated: boolean) { + return { content: [{ type: "image", mimeType: "image/webp", data }, { type: "text", text: JSON.stringify({ animated }) }] }; +} +async function openGifView(tool: (call: { name: string; arguments: Record }) => unknown) { + const app = await openView(); + document.body.insertAdjacentHTML("beforeend", ''); + // The view was imported before these elements existed, so load it again with them in place. + vi.resetModules(); + await import("../src/mcp/views/job"); + bridge.app.callServerTool.mockImplementation(async (call: any) => tool(call)); + return bridge.app as typeof app; +} + +it("plays a GIF in the request view through an animated preview", async () => { + const app = await openGifView(({ name }) => name === "read_thumbnail" ? previewResult("YW5pbQ==", true) : { isError: true, content: [] }); + app.ontoolresult(gifJob); + await settle(); + expect(app.callServerTool).toHaveBeenCalledWith({ name: "read_thumbnail", arguments: { id: "gif", animated: true } }); + expect(document.querySelector("#preview")!.src).toBe("data:image/webp;base64,YW5pbQ=="); + expect(document.querySelector("#play")!.hidden).toBe(true); +}); + +it("shows a still with Play under reduced motion and starts the animation on request", async () => { + // The view's stylesheet sets this under the reduced-motion media query. + document.documentElement.style.setProperty("--motion-reduced", "1"); + const app = await openGifView(({ name, arguments: args }) => + name === "read_thumbnail" ? previewResult(args.animated ? "YW5pbQ==" : "c3RpbGw=", Boolean(args.animated)) : { isError: true, content: [] }); + app.ontoolresult(gifJob); + await settle(); + const preview = document.querySelector("#preview")!; + const play = document.querySelector("#play")!; + expect(app.callServerTool).toHaveBeenCalledWith({ name: "read_thumbnail", arguments: { id: "gif" } }); + expect(preview.src).toBe("data:image/webp;base64,c3RpbGw="); + expect(play.hidden).toBe(false); + play.click(); + await settle(); + expect(preview.src).toBe("data:image/webp;base64,YW5pbQ=="); + expect(play.hidden).toBe(true); + document.documentElement.style.removeProperty("--motion-reduced"); +}); + +it("plays the full file when the preview service returned one frame", async () => { + const app = await openGifView(({ name }) => + name === "read_thumbnail" ? previewResult("c3RpbGw=", false) + : name === "read_image_file" ? { content: [{ type: "resource", resource: { uri: "image-queue://image/gif.gif", mimeType: "image/gif", blob: "R0lG" } }] } + : { isError: true, content: [] }); + app.ontoolresult(gifJob); + await settle(); + const play = document.querySelector("#play")!; + expect(play.hidden).toBe(false); + play.click(); + await settle(); + expect(document.querySelector("#preview")!.src).toBe("data:image/gif;base64,R0lG"); + expect(play.hidden).toBe(true); +}); + +it("keeps Play away from images that are not GIFs", async () => { + const app = await openGifView(({ name }) => name === "read_thumbnail" ? previewResult("c3RpbGw=", false) : { isError: true, content: [] }); + app.ontoolresult({ content: [{ type: "text", text: JSON.stringify({ id: "png", status: "done", prompt: "A fox" }) }] }); + await settle(); + expect(app.callServerTool).toHaveBeenCalledWith({ name: "read_thumbnail", arguments: { id: "png" } }); + expect(document.querySelector("#play")!.hidden).toBe(true); +}); diff --git a/tests/mcp-view-thumbnail.test.ts b/tests/mcp-view-thumbnail.test.ts new file mode 100644 index 0000000..bc71976 --- /dev/null +++ b/tests/mcp-view-thumbnail.test.ts @@ -0,0 +1,53 @@ +import { expect, it, vi } from "vitest"; +import { loadThumbnail } from "../src/mcp/views/thumbnail"; + +const resource = { contents: [{ uri: "image-queue://thumbnail/one", mimeType: "image/webp", blob: "cmVzb3VyY2U=" }] }; +function host(tool: () => Promise, read: () => Promise = async () => resource) { + return { callServerTool: vi.fn(tool), readServerResource: vi.fn(read) } as any; +} + +it("loads the preview through the app-only tool without reading the resource", async () => { + const app = host(async () => ({ content: [{ type: "image", mimeType: "image/webp", data: "dG9vbA==" }] })); + await expect(loadThumbnail(app, "one", () => false)).resolves.toBe("data:image/webp;base64,dG9vbA=="); + expect(app.callServerTool).toHaveBeenCalledWith({ name: "read_thumbnail", arguments: { id: "one" } }); + expect(app.readServerResource).not.toHaveBeenCalled(); +}); + +it.each([ + ["a rejected call", async () => { throw new Error("Unknown tool"); }], + ["an error result", async () => ({ isError: true, content: [{ type: "image", mimeType: "image/webp", data: "dG9vbA==" }] })], + ["a result without an image", async () => ({ content: [{ type: "text", text: "{}" }] })], + ["an image of another type", async () => ({ content: [{ type: "image", mimeType: "text/html", data: "dG9vbA==" }] })], + ["no result", async () => undefined], +])("falls back to the private resource after %s", async (_, tool) => { + const app = host(tool); + await expect(loadThumbnail(app, "a b", () => false)).resolves.toBe("data:image/webp;base64,cmVzb3VyY2U="); + expect(app.readServerResource).toHaveBeenCalledWith({ uri: "image-queue://thumbnail/a%20b" }); +}); + +it.each([ + ["rejects", async () => { throw new Error("Resource unavailable"); }], + ["is empty", async () => ({ contents: [] })], + ["is not an image", async () => ({ contents: [{ uri: "ui://image-queue/job", mimeType: "text/html", blob: "PGI+" }] })], +])("reports an unavailable preview when the tool fails and the resource %s", async (_, read) => { + const app = host(async () => ({ isError: true, content: [{ type: "text", text: "Image is unavailable" }] }), read); + await expect(loadThumbnail(app, "one", () => false)).rejects.toThrow(); + expect(app.callServerTool).toHaveBeenCalledTimes(1); + expect(app.readServerResource).toHaveBeenCalledTimes(1); +}); + +it("skips the fallback once the preview is no longer wanted", async () => { + const app = host(async () => { throw new Error("Unknown tool"); }); + await expect(loadThumbnail(app, "one", () => true)).rejects.toThrow(); + expect(app.readServerResource).not.toHaveBeenCalled(); +}); + +it("asks for the frames of a GIF and reports whether the preview kept them", async () => { + const { loadPreview } = await import("../src/mcp/views/thumbnail"); + const app = host(async () => ({ content: [{ type: "image", mimeType: "image/webp", data: "dG9vbA==" }, { type: "text", text: '{"animated":true}' }] })); + await expect(loadPreview(app, "one", () => false, { animated: true })).resolves.toEqual({ url: "data:image/webp;base64,dG9vbA==", animated: true }); + expect(app.callServerTool).toHaveBeenCalledWith({ name: "read_thumbnail", arguments: { id: "one", animated: true } }); + // An older server sends the image alone: treated as a still. + const old = host(async () => ({ content: [{ type: "image", mimeType: "image/webp", data: "dG9vbA==" }] })); + await expect(loadPreview(old, "one", () => false, { animated: true })).resolves.toEqual({ url: "data:image/webp;base64,dG9vbA==", animated: false }); +}); diff --git a/tests/mcp.test.ts b/tests/mcp.test.ts index 416e642..72c7f9a 100644 --- a/tests/mcp.test.ts +++ b/tests/mcp.test.ts @@ -1,3 +1,4 @@ +import { GALLERY_VIEW_URI, IMAGE_VIEW_URI, JOB_VIEW_URI } from "../src/mcp/apps"; import { png, mp4 } from "./fixtures"; import { service } from "../src/core/runtime"; import { mkdtemp, rm, writeFile, mkdir, symlink } from "node:fs/promises"; @@ -46,7 +47,7 @@ async function call(name: string, args: Record = {}) { describe("MCP client/server flow", () => { it("lists tools and manages project, request, result and cancellation", async () => { const tools=(await client.listTools()).tools; - expect(tools).toHaveLength(27); + expect(tools).toHaveLength(29); expect(tools.map(tool=>tool.name)).toEqual(expect.arrayContaining(["get_queue_processing","set_queue_processing"])); const p = await call("create_project", { name: "Agent project" }); expect(await call("list_projects")).toHaveLength(1); @@ -280,7 +281,7 @@ it("registers optional HTML resources only for a capable host", async () => { await new Promise((resolve) => setTimeout(resolve, 0)); const resources = await appClient.listResources(); expect(resources.resources.map((item) => item.uri)).toContain( - "ui://image-queue/job", + JOB_VIEW_URI, ); const appTools = (await appClient.listTools()).tools; expect( @@ -288,14 +289,14 @@ it("registers optional HTML resources only for a capable host", async () => { ).toMatchObject({ ui: { visibility: ["app"] } }); expect( appTools.find((tool) => tool.name === "show_job")?._meta, - ).toMatchObject({ ui: { resourceUri: "ui://image-queue/job" } }); + ).toMatchObject({ ui: { resourceUri: JOB_VIEW_URI } }); expect( (await client.listTools()).tools.some( (tool) => tool.name === "get_job_state", ), ).toBe(false); const resource = await appClient.readResource({ - uri: "ui://image-queue/job", + uri: JOB_VIEW_URI, }); expect(resource.contents[0].mimeType).toBe("text/html;profile=mcp-app"); await expect( @@ -338,6 +339,26 @@ it("registers optional HTML resources only for a capable host", async () => { await expect(appClient.readResource({ uri: "image-queue://thumbnail/trashed-preview", })).rejects.toThrow("unavailable"); + await api.store.put("jobs", "pending-preview", { + id: "pending-preview", status: "queued", source: "api", + blobKey: "results/test-preview", createdAt: "2026-01-01", prompt: "A violet rectangle", + }); + expect(appTools.find(tool => tool.name === "read_thumbnail")?._meta) + .toEqual({ ui: { visibility: ["app"] } }); + expect((await client.listTools()).tools.some(tool => tool.name === "read_thumbnail")).toBe(false); + const toolPreview = await appClient.callTool({ name: "read_thumbnail", arguments: { id: "preview" } }); + expect(toolPreview.isError).toBeFalsy(); + expect(toolPreview.content).toEqual([{ + type: "image", mimeType: "image/webp", data: "blob" in content ? content.blob : undefined, + }, { type: "text", text: JSON.stringify({ animated: false }) }]); + for (const id of ["trashed-preview", "pending-preview", "missing", "../escape"]) { + const refused = await appClient.callTool({ name: "read_thumbnail", arguments: { id } }); + expect(refused.isError, id).toBe(true); + expect(refused.content, id).toEqual([{ type: "text", text: expect.any(String) }]); + expect(JSON.stringify(refused.content), id).not.toContain("results/test-preview"); + } + await expect(appClient.readResource({ uri: "image-queue://thumbnail/pending-preview" })).rejects.toThrow("unavailable"); + await expect(client.callTool({ name: "read_thumbnail", arguments: { id: "preview" } })).rejects.toThrow("not found"); expect(appTools.find(tool => tool.name === "add_notes_to_queue")?._meta) .toMatchObject({ ui: { visibility: ["app"] } }); expect((await client.listTools()).tools.some(tool => tool.name === "add_notes_to_queue")).toBe(false); @@ -345,8 +366,8 @@ it("registers optional HTML resources only for a capable host", async () => { .toMatchObject({ ui: { visibility: ["app"] } }); expect((await client.listTools()).tools.some(tool => tool.name === "get_image_details")).toBe(false); await api.store.put("notes", "preview-note", { id: "preview-note", imageId: "preview", text: "Brighten sky", x: 0.5, y: 0.2 }); - expect(appTools.find(tool => tool.name === "show_image")?._meta).toMatchObject({ ui: { resourceUri: "ui://image-queue/image" } }); - const imageResource = await appClient.readResource({ uri: "ui://image-queue/image" }); + expect(appTools.find(tool => tool.name === "show_image")?._meta).toMatchObject({ ui: { resourceUri: IMAGE_VIEW_URI } }); + const imageResource = await appClient.readResource({ uri: IMAGE_VIEW_URI }); expect(imageResource.contents[0].mimeType).toBe("text/html;profile=mcp-app"); const project = await api.createProject("MCP parity"); for (const request of [ @@ -792,7 +813,7 @@ it("changes only the saved source and lets an omitted source use it",async()=>{ expect(result).toMatchObject({generationStarted:false,existingRequestsChanged:false,preference:{source:'api'}}); expect((await call('get_generation_source')).preference.model).toBe('gpt-image-1.5'); const project=await api.createProject('API default'); - const runtime=await import('../src/core/runtime');const enqueueSpy=vi.spyOn(runtime,'enqueue').mockResolvedValue(undefined); + const runtime=await import('../src/core/runtime');const enqueueSpy=vi.spyOn(runtime,'dispatch').mockResolvedValue(undefined); try { const job=await call('request_image',{projectId:project.id,prompt:'A red square',width:1024,height:1024,idempotencyKey:'saved-default'}); expect(job).toMatchObject({source:'api',model:'gpt-image-1.5',status:'queued'}); @@ -827,6 +848,181 @@ it("replays an identical MCP request after its default and model catalog change" } }); +it("reports and enforces gpt-image-2.6-flare and gpt-image-1.5 capabilities", async () => { + const api = await service(); + await api.store.put("models", "openai", [ + { id: "gpt-image-2.6-flare", name: "GPT Image 2.6 Flare", provider: "openai", references: false, transparency: false }, + { id: "gpt-image-1.5", name: "GPT Image 1.5", provider: "openai", references: true, transparency: true }, + ]); + const models = await call("list_models"); + expect(models.map((model: { id: string }) => model.id)).toEqual(["gpt-image-2.6-flare", "gpt-image-1.5"]); + expect(models[0]).toMatchObject({ + transparency: true, references: true, + sizeProfile: { mode: "dimensions", maxSide: 3840, multiple: 16, minPixels: 655360, maxPixels: 8294400 }, + qualities: ["low", "medium", "high", "xhigh", "max", "auto"], + }); + expect(models[1].sizeProfile.sizes).toContainEqual({ width: 1536, height: 1024 }); + await call("set_generation_source", { source: "api", model: "gpt-image-2.6-flare" }); + expect(await call("get_generation_source")).toMatchObject({ + preference: { source: "api", model: "gpt-image-2.6-flare" }, + model: { id: "gpt-image-2.6-flare", transparency: true }, + }); + const project = await api.createProject("Flare capabilities"); + const runtime = await import("../src/core/runtime"); + const enqueueSpy = vi.spyOn(runtime, "enqueue").mockResolvedValue(undefined); + try { + const wide = await call("request_image", { projectId: project.id, prompt: "A wide red panda forest", aspectRatio: "16:9", transparent: true, quality: "high", idempotencyKey: "flare-wide" }); + expect(wide).toMatchObject({ model: "gpt-image-2.6-flare", width: 2048, height: 1152, transparent: true, quality: "high" }); + const sprite = await call("request_image", { projectId: project.id, prompt: "A red panda sprite", width: 256, height: 256, transparent: true, idempotencyKey: "flare-sprite" }); + expect(sprite).toMatchObject({ width: 256, height: 256, transparent: true }); + await expect(call("request_image", { projectId: project.id, prompt: "Too high quality", model: "gpt-image-1.5", width: 1024, height: 1024, quality: "xhigh", idempotencyKey: "legacy-xhigh" })) + .rejects.toThrow('does not support quality "xhigh"'); + await expect(call("request_images", { requests: [ + { projectId: project.id, prompt: "Fine request", width: 1024, height: 1024, idempotencyKey: "batch-ok" }, + { projectId: project.id, prompt: "Queue with quality", source: "queue", width: 1024, height: 1024, quality: "low", idempotencyKey: "batch-queue-quality" }, + ] })).rejects.toThrow("Quality and complexity apply only to API generation"); + expect((await call("list_jobs", { projectId: project.id })).some((job: { idempotencyKey: string }) => job.idempotencyKey === "batch-ok")).toBe(false); + await expect(call("request_image", { projectId: project.id, prompt: "Beyond the limit", width: 4096, height: 2304, idempotencyKey: "flare-too-wide" })) + .rejects.toThrow("between 16 and 3840 pixels"); + } finally { enqueueSpy.mockRestore(); } +}); + +it("profiles every discovered OpenAI image model per ID and defaults to gpt-image-2.6-sunburst", async () => { + const api = await service(); + const ids = ["gpt-image-1-mini", "gpt-image-1.5", "gpt-image-2", "gpt-image-2-2026-04-21", "gpt-image-2.5-flare", "gpt-image-2.5-flare-2026-09-08", + "gpt-image-2.5-sunburst", "gpt-image-2.5-sunburst-2026-09-08", "gpt-image-2.6-flare", "gpt-image-2.6-sunburst"]; + await api.store.put("models", "openai", ids.map(id => ({ id, name: id, provider: "openai", references: false, transparency: false }))); + const models = await call("list_models"); + expect(models.map((model: { id: string }) => model.id).slice(0, 2)).toEqual(["gpt-image-2.6-sunburst", "gpt-image-2.6-flare"]); + expect(new Set(models.map((model: { id: string }) => model.id))).toEqual(new Set(ids)); + const byId = Object.fromEntries(models.map((model: { id: string }) => [model.id, model])); + expect(byId["gpt-image-2.6-sunburst"]).toMatchObject({ + transparency: true, references: true, complexities: ["low", "medium", "high"], + outputFormats: ["png", "webp", "jpeg", "gif", "svg"], generationVerified: false, + documentedOnly: expect.arrayContaining(["generation", "reference edit"]), + }); + expect(byId["gpt-image-2.5-sunburst"]).toMatchObject({ complexities: [], outputFormats: ["png", "webp", "jpeg"], qualities: expect.arrayContaining(["xhigh", "max"]) }); + expect(byId["gpt-image-2"].qualities).not.toContain("xhigh"); + expect(byId["gpt-image-1-mini"].sizeProfile.mode).toBe("fixed"); + + await call("set_generation_source", { source: "api" }); + expect((await call("get_generation_source")).preference.model).toBe("gpt-image-2.6-sunburst"); + await call("set_generation_source", { source: "api", model: "gpt-image-2.6-sunburst" }); + const project = await api.createProject("Sunburst capabilities"); + const runtime = await import("../src/core/runtime"); + const enqueueSpy = vi.spyOn(runtime, "enqueue").mockResolvedValue(undefined); + try { + const portrait = await call("request_image", { projectId: project.id, prompt: "A tall red panda banner", aspectRatio: "9:16", transparent: true, quality: "max", complexity: "medium", idempotencyKey: "sunburst-portrait" }); + expect(portrait).toMatchObject({ model: "gpt-image-2.6-sunburst", width: 1152, height: 2048, quality: "max", complexity: "medium" }); + await expect(call("request_image", { projectId: project.id, prompt: "No complexity", model: "gpt-image-2.5-sunburst", width: 1024, height: 1024, complexity: "low", idempotencyKey: "25-complexity" })) + .rejects.toThrow('does not support complexity "low". Supported: none.'); + await expect(call("request_image", { projectId: project.id, prompt: "Queue complexity", source: "queue", width: 1024, height: 1024, complexity: "high", idempotencyKey: "queue-complexity" })) + .rejects.toThrow("Quality and complexity apply only to API generation"); + } finally { enqueueSpy.mockRestore(); } +}); + +it("rejects an output format the source or model cannot use before creating any job", async () => { + const api = await service(); + await api.store.put("models", "openai", [ + { id: "gpt-image-2.6-sunburst", name: "Sunburst", provider: "openai", references: true, transparency: true }, + { id: "gpt-image-1.5", name: "GPT Image 1.5", provider: "openai", references: true, transparency: true }, + ]); + await call("set_generation_source", { source: "api", model: "gpt-image-2.6-sunburst" }); + const project = await api.createProject("Formats"); + const runtime = await import("../src/core/runtime"); + const enqueueSpy = vi.spyOn(runtime, "enqueue").mockResolvedValue(undefined); + const base = { projectId: project.id, prompt: "A red panda", width: 1024, height: 1024 }; + try { + await expect(call("request_image", { ...base, source: "queue", outputFormat: "webp", idempotencyKey: "queue-webp" })) + .rejects.toThrow("Output format and frame settings apply only to API generation"); + await expect(call("request_image", { ...base, model: "gpt-image-1.5", outputFormat: "svg", idempotencyKey: "legacy-svg" })) + .rejects.toThrow('does not support output format "svg"'); + await expect(call("request_image", { ...base, outputFormat: "jpeg", transparent: true, idempotencyKey: "jpeg-transparent" })) + .rejects.toThrow("Transparent background requires PNG or WebP"); + 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" })) + .rejects.toThrow("only to GIF"); + await expect(call("request_images", { requests: [ + { ...base, idempotencyKey: "counted-ok", count: 2, outputFormat: "webp" }, + { ...base, idempotencyKey: "counted-bad", outputFormat: "svg", referenceIds: [reference.id] }, + ] })).rejects.toThrow("cannot be combined with reference images"); + expect(await call("list_jobs", { projectId: project.id })).toEqual([]); + } finally { enqueueSpy.mockRestore(); } +}); + +it("expands count into independent jobs, replays them, and caps the expanded batch at 20", async () => { + const api = await service(); + await api.store.put("models", "openai", [ + { id: "gpt-image-2.6-sunburst", name: "Sunburst", provider: "openai", references: true, transparency: true }, + ]); + await call("set_generation_source", { source: "api", model: "gpt-image-2.6-sunburst" }); + const project = await api.createProject("Count"); + const runtime = await import("../src/core/runtime"); + const enqueueSpy = vi.spyOn(runtime, "enqueue").mockResolvedValue(undefined); + const again = { projectId: project.id, prompt: "Three pandas", width: 1024, height: 1024, idempotencyKey: "three", count: 3, outputFormat: "svg" as const }; + try { + const once = await call("request_image", { projectId: project.id, prompt: "A single panda", width: 1024, height: 1024, idempotencyKey: "single", outputFormat: "svg" }); + expect(once.jobs).toBeUndefined(); + expect(once).toMatchObject({ id: "IMG-single", outputFormat: "svg" }); + const created = await call("request_image", again); + expect(created.id).toBe("IMG-three"); + expect(created.count).toBeUndefined(); + expect(created.jobs.map((job: { id: string; outputFormat: string }) => job.id)).toEqual(["IMG-three", "IMG-three-2", "IMG-three-3"]); + expect(created.jobs.every((job: { outputFormat?: string; count?: number }) => job.outputFormat === "svg" && job.count === undefined)).toBe(true); + for (const job of created.jobs) await api.store.put("jobs", job.id, { ...job, status: "done" }); + enqueueSpy.mockClear(); + const replay = await call("request_image", again); + expect(replay.jobs.map((job: { id: string }) => job.id)).toEqual(["IMG-three", "IMG-three-2", "IMG-three-3"]); + expect(enqueueSpy).not.toHaveBeenCalled(); + expect((await call("list_jobs", { projectId: project.id })).filter((job: { idempotencyKey: string }) => job.idempotencyKey.startsWith("three"))).toHaveLength(3); + await expect(call("request_images", { requests: [ + { projectId: project.id, prompt: "A batch panda", width: 1024, height: 1024, idempotencyKey: "cap-a", count: 10 }, + { projectId: project.id, prompt: "Another batch panda", width: 1024, height: 1024, idempotencyKey: "cap-b", count: 10 }, + { projectId: project.id, prompt: "One more panda", width: 1024, height: 1024, idempotencyKey: "cap-c" }, + ] })).rejects.toThrow("at most 20"); + expect((await call("list_jobs", { projectId: project.id })).some((job: { idempotencyKey: string }) => job.idempotencyKey.startsWith("cap-"))).toBe(false); + const batch = await call("request_images", { requests: [ + { projectId: project.id, prompt: "Wide panda", width: 1024, height: 1024, idempotencyKey: "batch-wide", count: 2, outputFormat: "webp" }, + ] }); + expect(batch.map((job: { id: string }) => job.id)).toEqual(["IMG-batch-wide", "IMG-batch-wide-2"]); + } finally { enqueueSpy.mockRestore(); } +}); + +it("writes one queue entry per count and returns the same jobs on replay", async () => { + const project = await call("create_project", { name: "Queue count" }); + const request = { projectId: project.id, prompt: "Two queue pandas", source: "queue" as const, width: 1024, height: 1024, idempotencyKey: "queue-count", count: 2 }; + const first = await call("request_image", request); + expect(first.jobs.map((job: { id: string }) => job.id)).toEqual(["IMG-queue-count", "IMG-queue-count-2"]); + expect(new Set(first.jobs.map((job: { outputPath: string }) => job.outputPath)).size).toBe(2); + const replay = await call("request_image", request); + expect(replay.jobs.map((job: { id: string }) => job.id)).toEqual(first.jobs.map((job: { id: string }) => job.id)); + expect(await call("list_jobs", { projectId: project.id })).toHaveLength(2); +}); + +it("shows a finished image as inline image content and refuses unfinished ones", async () => { + const api = await service(); + const project = await api.createProject("Inline preview"); + const sharp = (await import("sharp")).default; + const png = new Uint8Array(await sharp({ create: { width: 32, height: 32, channels: 4, background: "#2563eb" } }).png().toBuffer()); + await api.store.putBlob("results/inline-preview", png, "image/png"); + await api.store.put("jobs", "IMG-inline-preview", { + id: "IMG-inline-preview", projectId: project.id, source: "api", status: "done", blobKey: "results/inline-preview", + prompt: "Inline", width: 1, height: 1, referenceIds: [], createdAt: "2026-11-19T20:00:00.000Z", updatedAt: "2026-11-19T20:00:00.000Z", + }); + const shown = await client.callTool({ name: "view_image", arguments: { id: "IMG-inline-preview" } }); + expect(shown.isError, JSON.stringify(shown.content)).toBeFalsy(); + expect(shown.content).toEqual([expect.objectContaining({ type: "image", mimeType: expect.stringMatching(/^image\//) })]); + await api.store.put("jobs", "IMG-inline-pending", { id: "IMG-inline-pending", projectId: project.id, source: "api", status: "queued" }); + const pending = await client.callTool({ name: "view_image", arguments: { id: "IMG-inline-pending" } }); + expect(pending.isError).toBe(true); +}); + it("counts external Codex requests before the dashboard imports the gallery", async () => { const queue = path.join(root, "queue"); await mkdir(queue, { recursive: true }); diff --git a/tests/model-options.test.ts b/tests/model-options.test.ts index fdb3b61..04dd89f 100644 --- a/tests/model-options.test.ts +++ b/tests/model-options.test.ts @@ -48,7 +48,7 @@ it("filters dimension and ratio profiles by their declared constraints", () => { expect(modelSizes("openai", "custom", { mode: "dimensions", minSide: 256, maxSide: 1536, multiple: 16, minPixels: 65536, maxPixels: 2000000, minRatio: 0.5, maxRatio: 2, - })).toEqual(["1024x1024", "1536x1024", "1024x1536"]); + })).toEqual(["1024x1024", "1536x1024", "1024x1536", "1472x1104", "1104x1472"]); expect(modelSizes("google", "custom", { mode: "aspect-ratio", ratios: ["1:1", "9:16"], levels: [], })).toEqual(["1024x1024", "1080x1920"]); @@ -63,3 +63,11 @@ it("does not invent standard presets for a custom-only ratio profile", () => { mode: "aspect-ratio", ratios: ["5:4"], levels: [], })).toEqual([]); }); + +it("offers every standard ratio natively for gpt-image-2.6-flare", async () => { + const { verifiedModelProfiles } = await import("../src/core/model-profiles"); + const flare = verifiedModelProfiles.find(entry => entry.model === "gpt-image-2.6-flare")!; + expect(modelSizes("openai", flare.model, flare.sizeProfile)).toEqual([ + "1024x1024", "1536x1024", "1024x1536", "1472x1104", "1104x1472", "2048x1152", "1152x2048", "2688x1152", + ]); +}); diff --git a/tests/model-profiles.test.ts b/tests/model-profiles.test.ts index 44a876b..0d7b602 100644 --- a/tests/model-profiles.test.ts +++ b/tests/model-profiles.test.ts @@ -8,13 +8,14 @@ const profile: VerifiedModelProfile = { provider: "openai", model: model.id, references: true, transparency: false, sizeProfile: { mode: "fixed", sizes: [{ width: 1024, height: 1024 }] }, + qualities: ["low", "high"], complexities: [], outputFormats: ["png"], documentedOnly: [], documentation: "https://developers.openai.com/api/docs/guides/image-generation", verifiedAt: "2026-11-15T12:00:00Z", evidence: { generation: "fixture-generation", referenceEdit: "fixture-edit" }, }; it("adds verified profiles only to exact provider and model matches", () => { const unknown = { ...model, id: "gpt-image-other" }; - expect(applyVerifiedModelProfiles([model, unknown], [profile])).toEqual([{ ...model, sizeProfile: profile.sizeProfile }, unknown]); + expect(applyVerifiedModelProfiles([model, unknown], [profile])).toEqual([{ ...model, sizeProfile: profile.sizeProfile, qualities: ["low", "high"], complexities: [], outputFormats: ["png"], documentedOnly: [], generationVerified: true }, unknown]); expect(model.sizeProfile).toBeUndefined(); expect(applyVerifiedModelProfiles([model], [])).toEqual([model]); }); @@ -31,7 +32,7 @@ it("keeps published profile evidence present with section anchors and image hash expect(verifiedModelProfileSchema.safeParse(profile).success).toBe(true); expect(ids.has(profile.model)).toBe(false); ids.add(profile.model); - for (const [kind, link] of Object.entries(profile.evidence)) { + for (const [kind, link] of Object.entries(profile.evidence ?? {})) { const [file, anchor] = link.split("#"); expect(file).toMatch(/^docs\/verification\/[a-z0-9.-]+\.md$/); const text = await readFile(file, "utf8"); @@ -54,3 +55,70 @@ it("removes cached size profiles without an exact verified registry entry", () = expect(applyVerifiedModelProfiles([otherProvider], [profile])[0].sizeProfile).toBeUndefined(); expect(cached.sizeProfile).toEqual(profile.sizeProfile); }); + +it("publishes the documented gpt-image-2.6-flare and gpt-image-1.5 capabilities", () => { + const flare = verifiedModelProfiles.find(entry => entry.model === "gpt-image-2.6-flare")!; + expect(flare).toMatchObject({ transparency: true, references: true, qualities: expect.arrayContaining(["xhigh", "max"]) }); + expect(flare.sizeProfile).toEqual({ mode: "dimensions", minSide: 16, maxSide: 3840, multiple: 16, minPixels: 655360, maxPixels: 8294400, minRatio: 1 / 3, maxRatio: 3 }); + expect(flare.documentedOnly).toEqual(expect.arrayContaining(["transparent background"])); + const legacy = verifiedModelProfiles.find(entry => entry.model === "gpt-image-1.5")!; + expect(legacy.sizeProfile).toEqual({ mode: "fixed", sizes: [{ width: 1024, height: 1024 }, { width: 1024, height: 1536 }, { width: 1536, height: 1024 }] }); + expect(legacy.qualities).not.toContain("xhigh"); +}); + +it("refuses options a model cannot honour", async () => { + const { assertModelOptions } = await import("../src/core/model-profiles"); + const [withProfile] = applyVerifiedModelProfiles([model], [profile]); + expect(() => assertModelOptions(withProfile, { quality: "high" })).not.toThrow(); + expect(() => assertModelOptions(withProfile, { quality: "max" })).toThrow('does not support quality "max". Supported: low, high.'); + expect(() => assertModelOptions(withProfile, { transparent: true })).toThrow("does not support transparency"); + expect(() => assertModelOptions({ ...withProfile, references: false }, { referenceIds: ["ref-1"] })).toThrow("image references"); + expect(() => assertModelOptions(model, { quality: "low" })).toThrow("Supported: none."); +}); + +it("requires documentation-only entries to name generation and reference edit as unverified", () => { + expect(verifiedModelProfileSchema.safeParse({ ...profile, evidence: null }).success).toBe(false); + expect(verifiedModelProfileSchema.safeParse({ ...profile, evidence: null, documentedOnly: ["generation", "reference edit"] }).success).toBe(true); + for (const entry of verifiedModelProfiles.filter(item => item.evidence === null)) + expect(entry.documentedOnly).toEqual(expect.arrayContaining(["generation", "reference edit"])); +}); + +it("keeps complexity, SVG and GIF to GPT Image 2.6 and xhigh/max to 2.5 and 2.6", () => { + for (const entry of verifiedModelProfiles) { + const is26 = entry.model.startsWith("gpt-image-2.6-"); + const isNew = is26 || entry.model.startsWith("gpt-image-2.5-"); + expect(entry.complexities.length > 0).toBe(is26); + expect(entry.outputFormats.includes("svg")).toBe(is26); + expect(entry.qualities.includes("max")).toBe(isNew); + } + expect(verifiedModelProfiles[0].model).toBe("gpt-image-2.6-sunburst"); +}); + +it("refuses an output format, transparency pairing, SVG combination or frame setting the model cannot honour", async () => { + const { assertModelOptions } = await import("../src/core/model-profiles"); + const [raster] = applyVerifiedModelProfiles([model], [profile]); + const [vector] = applyVerifiedModelProfiles( + [{ ...model, transparency: true }], + [{ ...profile, transparency: true, outputFormats: ["png", "webp", "jpeg", "gif", "svg"] }], + ); + expect(() => assertModelOptions(vector, { outputFormat: "webp" })).not.toThrow(); + expect(() => assertModelOptions(vector, { outputFormat: "svg" })).not.toThrow(); + expect(() => assertModelOptions(raster, { outputFormat: "gif" })).toThrow('does not support output format "gif". Supported: png.'); + expect(() => assertModelOptions(vector, { transparent: true, outputFormat: "jpeg" })).toThrow("Transparent background requires PNG or WebP"); + 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", 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"); + expect(() => assertModelOptions(vector, { frameCount: 2 })).toThrow("only to GIF"); + expect(() => assertModelOptions(vector, { outputFormat: "gif", frameCount: 8, frameDurationMs: 200 })).not.toThrow(); +}); + +it("refuses complexity a model does not offer", async () => { + const { assertModelOptions } = await import("../src/core/model-profiles"); + const [withProfile] = applyVerifiedModelProfiles([model], [{ ...profile, complexities: ["low"] }]); + expect(() => assertModelOptions(withProfile, { complexity: "low" })).not.toThrow(); + expect(() => assertModelOptions(withProfile, { complexity: "high" })).toThrow('does not support complexity "high". Supported: low.'); +}); diff --git a/tests/notes.test.ts b/tests/notes.test.ts index 49e18cb..0859bff 100644 --- a/tests/notes.test.ts +++ b/tests/notes.test.ts @@ -580,8 +580,9 @@ it("rejects unsupported real alpha before persisting an API correction or consum const {job} = await api.importImage("transparent.png","image/png",bytes,project.id); const note = await addNote(store,{imageId:job.id,text:"Change the circle"}); const refs = await Promise.all(["original","notes"].map(name => api.addReference(project.id,name,"image/png",bytes))); - await store.put("models","openai",[{id:"gpt-image-2.6-flare",provider:"openai",references:true,transparency:false}]); - await expect(createCorrection(api,{imageId:job.id,referenceIds:refs.map(ref=>ref.id),idempotencyKey:"alpha-blocked",generation:{source:"api",provider:"openai",model:"gpt-image-2.6-flare"}})).rejects.toThrow("supports transparent images"); + // gpt-image-2.6-flare supports transparency, so use an opaque-only fixture model. + await store.put("models","openai",[{id:"gpt-image-opaque-fixture",provider:"openai",references:true,transparency:false}]); + await expect(createCorrection(api,{imageId:job.id,referenceIds:refs.map(ref=>ref.id),idempotencyKey:"alpha-blocked",generation:{source:"api",provider:"openai",model:"gpt-image-opaque-fixture"}})).rejects.toThrow("supports transparent images"); expect(await store.get("jobs","IMG-alpha-blocked")).toBeUndefined(); expect(await store.get("correction-intents","alpha-blocked")).toBeUndefined(); expect(await store.get("notes",note.id)).not.toHaveProperty("sentInJobId"); diff --git a/tests/organization-actions.test.ts b/tests/organization-actions.test.ts index fed3dca..1f9fc64 100644 --- a/tests/organization-actions.test.ts +++ b/tests/organization-actions.test.ts @@ -3,6 +3,7 @@ import { MemoryStorage } from "../src/storage/memory"; const state = vi.hoisted(() => ({ store: undefined as unknown as MemoryStorage, enqueue: vi.fn(), + dispatch: vi.fn(), after: vi.fn(), configuredQueueRoot: vi.fn(async () => "/tmp/fixture-queue"), })); @@ -19,6 +20,7 @@ vi.mock("../src/core/runtime", async () => { return { service: async () => new ImageService(state.store), enqueue: state.enqueue, + dispatch: state.dispatch, }; }); import * as actions from "../src/actions"; @@ -252,21 +254,10 @@ it.each(["disk", "cloudflare"])("dispatches an API iteration using the %s lifecy expect(state.after).not.toHaveBeenCalled(); return; } + // Cloudflare hands the job to its generation queue; failure recording is covered by the dispatch tests. + expect(state.dispatch).toHaveBeenCalledExactlyOnceWith("IMG-api-iteration"); expect(state.enqueue).not.toHaveBeenCalled(); - expect(state.after).toHaveBeenCalledOnce(); - await state.after.mock.calls[0][0](); - expect(state.enqueue).toHaveBeenCalledExactlyOnceWith("IMG-api-iteration"); - - state.enqueue.mockRejectedValueOnce(new Error("Provider is disconnected")); - await state.after.mock.calls[0][0](); - expect(await state.store.get("jobs", "IMG-api-iteration")).toMatchObject({ - status: "failed", error: "Generation failed", parentVersionId: "one", - }); - const current = await state.store.get>("jobs", "IMG-api-iteration"); - await state.store.put("jobs", "IMG-api-iteration", { ...current, status: "done", error: undefined }); - state.enqueue.mockRejectedValueOnce(new Error("Late failure")); - await state.after.mock.calls[0][0](); - expect(await state.store.get("jobs", "IMG-api-iteration")).toMatchObject({ status: "done" }); + expect(state.after).not.toHaveBeenCalled(); }); it("rejects external-file deletion from Cloudflare before touching any record", async () => { diff --git a/tests/prepare-correction.test.ts b/tests/prepare-correction.test.ts index 9f014f8..6d8c07c 100644 --- a/tests/prepare-correction.test.ts +++ b/tests/prepare-correction.test.ts @@ -20,6 +20,48 @@ it("prepares two references and retries the same correction without duplicate jo expect(await store.list("references")).toHaveLength(2); await expect(prepareCorrection(api, { ...input, instruction: "Different" })).rejects.toThrow("different request"); }); +it("rejects an imported GIF and any SVG, which have no prompt to generate again and cannot be references", 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); + await store.put("jobs", job.id, { ...job, outputFormat: "gif" }); + await addNote(store, { imageId: job.id, text: "Blue sky", x: 0.5, y: 0.5 }); + await expect(prepareCorrection(api, { imageId: job.id, idempotencyKey: "gif" })).rejects.toThrow("cannot be used as references"); + await store.put("jobs", job.id, { ...job, outputFormat: "svg", source: "api", imported: false }); + 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 () => { + 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 gif = { ...job, imported: false, source: "api" as const, provider: "openai" as const, model: "gpt-image-2.6-sunburst", + prompt: "A red panda relaxing on a branch", outputFormat: "gif" as const, frameCount: 8, frameDurationMs: 180, width: 960, height: 960 }; + await store.put("jobs", job.id, gif); + 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: "Make the tail\nfluffier" }); + await new Promise(resolve => setTimeout(resolve, 3)); // Notes are sent in the order they were saved. + await addNote(store, { imageId: job.id, text: "Add falling leaves" }); + const input = { imageId: job.id, idempotencyKey: "panda-v2" }; + const first = await prepareCorrection(api, input); + expect(first.prompt).toBe("A red panda relaxing on a branch\n\nRequested changes:\n1. Make the tail fluffier\n2. Add falling leaves"); + expect(first).toMatchObject({ referenceIds: [], outputFormat: "gif", frameCount: 8, frameDurationMs: 180, width: 960, height: 960, + source: "api", model: "gpt-image-2.6-sunburst", parentVersionId: job.id }); + expect((await prepareCorrection(api, input)).id).toBe(first.id); + expect(await store.list("references")).toEqual([]); + expect((await store.list<{ sentInJobId?: string }>("notes")).every(note => note.sentInJobId === first.id)).toBe(true); + // A third version keeps the earlier changes and continues their numbering. + await store.put("jobs", first.id, { ...(await store.get("jobs", first.id))!, status: "done" }); + await addNote(store, { imageId: first.id, text: "Slower blink" }); + const third = await prepareCorrection(api, { imageId: first.id, idempotencyKey: "panda-v3" }); + expect(third.prompt).toBe(`${first.prompt}\n3. Slower blink`); + key.mockRestore(); +}); it("rejects unavailable images before storing references", async () => { const store = new MemoryStorage(); await expect(prepareCorrection(new ImageService(store), { imageId: "missing", idempotencyKey: "test" })).rejects.toThrow("ready"); diff --git a/tests/providers.test.ts b/tests/providers.test.ts index 2e93487..623d843 100644 --- a/tests/providers.test.ts +++ b/tests/providers.test.ts @@ -1,7 +1,7 @@ import { afterEach, describe, expect, it, vi } from "vitest"; vi.mock("image-size", () => ({ - imageSize: () => ({ width: 1024, height: 1024 }), + imageSize: vi.fn(() => ({ width: 1024, height: 1024, type: "png" })), })); vi.mock("../src/sources/image-fit", () => ({ fitImage: vi.fn(async (bytes) => ({ bytes, mime: "image/png" })) })); vi.mock("ai", () => ({ generateImage: vi.fn() })); @@ -25,6 +25,7 @@ vi.mock("@ai-sdk/gateway", () => ({ })); import { generateImage } from "ai"; +import { imageSize } from "image-size"; import type { Job } from "../src/core/schema"; import { discoverModels, @@ -32,7 +33,19 @@ import { providerModel, } from "../src/sources/providers"; -afterEach(() => vi.unstubAllGlobals()); +afterEach(() => { + vi.unstubAllGlobals(); + vi.mocked(imageSize).mockReset(); + vi.mocked(imageSize).mockReturnValue({ width: 1024, height: 1024, type: "png" }); +}); +async function rejection(promise: Promise) { + try { + await promise; + } catch (error) { + return error as Error; + } + throw new Error("expected the provider call to fail"); +} describe("providers", () => { it("constructs supported providers", () => { for (const provider of ["openai", "google", "gateway"] as const) @@ -117,7 +130,19 @@ describe("providers", () => { prompt: expect.objectContaining({ text: "Panda" }), }), ); + expect(vi.mocked(generateImage).mock.lastCall![0].providerOptions).toEqual({ + openai: { background: "transparent", outputFormat: "png" }, + }); await generate({ ...j, transparent: false }, "key", []); + expect(vi.mocked(generateImage).mock.lastCall![0].providerOptions).toBeUndefined(); + await generate({ ...j, transparent: true, quality: "xhigh" }, "key", []); + expect(vi.mocked(generateImage).mock.lastCall![0].providerOptions).toEqual({ + openai: { background: "transparent", outputFormat: "png", quality: "xhigh" }, + }); + await generate({ ...j, transparent: false, complexity: "low" }, "key", []); + expect(vi.mocked(generateImage).mock.lastCall![0].providerOptions).toEqual({ openai: { complexity: "low" } }); + await expect(generate({ ...j, provider: "google", model: "gemini-image", transparent: false, quality: "low" }, "key", [])) + .rejects.toThrow("Quality and complexity settings require an OpenAI image model"); }); it("rejects unsupported features before calling the model", async () => { const j = { @@ -217,7 +242,7 @@ it("fits profiled provider output when returned dimensions differ", async () => const result = await generate({ provider: "openai", model: "custom", prompt: "panda", width: 800, height: 800, transparent: false } as Job, "key", [], { mode: "fixed", sizes: [{width:1024,height:1024}] }); - expect(fitImage).toHaveBeenCalledWith(new Uint8Array([1]), {width:800,height:800}); + expect(fitImage).toHaveBeenCalledWith(new Uint8Array([1]), {width:800,height:800}, "png"); expect(result.generatedDimensions).toMatchObject({width:1024,height:1024}); }); @@ -310,6 +335,168 @@ it("routes an OpenRouter request with an image reference through its image model expect(result).toMatchObject({ bytes: output, mime: "image/png", width: 1024, height: 1024 }); }); +it("passes WebP, JPEG and GIF frame options and stores the format of the bytes", async () => { + const bytes = new Uint8Array([4, 5, 6]); + vi.mocked(generateImage).mockResolvedValue({ + image: { uint8Array: bytes, mediaType: "image/png" }, usage: {}, + } as never); + vi.mocked(imageSize).mockReturnValue({ width: 1024, height: 1024, type: "webp" }); + const job = { + provider: "openai", model: "gpt-image-2.6-sunburst", prompt: "A panda", + width: 1024, height: 1024, transparent: false, + } as Job; + expect((await generate({ ...job, outputFormat: "webp", quality: "high" }, "key", [])).mime).toBe("image/webp"); + expect(vi.mocked(generateImage).mock.lastCall![0].providerOptions).toEqual({ + openai: { outputFormat: "webp", quality: "high" }, + }); + vi.mocked(imageSize).mockReturnValue({ width: 1024, height: 1024, type: "jpg" }); + expect((await generate({ ...job, outputFormat: "jpeg" }, "key", [])).mime).toBe("image/jpeg"); + expect(vi.mocked(generateImage).mock.lastCall![0].providerOptions).toEqual({ openai: { outputFormat: "jpeg" } }); + await generate({ ...job, outputFormat: "webp", transparent: true }, "key", []); + expect(vi.mocked(generateImage).mock.lastCall![0].providerOptions).toEqual({ + openai: { background: "transparent", outputFormat: "webp" }, + }); + vi.mocked(imageSize).mockReturnValue({ width: 1024, height: 1024, type: "gif" }); + expect((await generate({ + ...job, outputFormat: "gif", frameCount: 4, frameDurationMs: 80, + }, "key", [])).mime).toBe("image/gif"); + expect(vi.mocked(generateImage).mock.lastCall![0].providerOptions).toEqual({ + openai: { outputFormat: "gif", frameCount: 4, frameDurationMs: 80 }, + }); + const { fitImage } = await import("../src/sources/image-fit"); + vi.mocked(fitImage).mockClear(); + vi.mocked(imageSize).mockReturnValue({ width: 1024, height: 1024, type: "webp" }); + await generate({ ...job, width: 800, height: 800, outputFormat: "webp" }, "key", [], { mode: "fixed", sizes: [{ width: 1024, height: 1024 }] }); + expect(fitImage).toHaveBeenCalledWith(bytes, { width: 800, height: 800 }, "webp"); + vi.mocked(imageSize).mockReturnValue({ width: 1024, height: 1024, type: "png" }); + vi.mocked(fitImage).mockClear(); + const mismatched = await generate({ ...job, width: 800, height: 800, outputFormat: "webp" }, "key", [], { mode: "fixed", sizes: [{ width: 1024, height: 1024 }] }); + expect(mismatched.mime).toBe("image/png"); + expect(mismatched.adaptationError).toMatch(/image\/png/); + expect(mismatched.adaptationError).toMatch(/webp/); + expect(fitImage).not.toHaveBeenCalled(); +}); + +it("stores a Google JPEG when the request does not set an output format", async () => { + const bytes = new Uint8Array([9, 9, 9]); + vi.mocked(imageSize).mockReturnValue({ width: 1024, height: 1024, type: "jpg" }); + vi.mocked(generateImage).mockResolvedValue({ + image: { uint8Array: bytes, mediaType: "image/jpeg" }, usage: {}, + } as never); + const { fitImage } = await import("../src/sources/image-fit"); + vi.mocked(fitImage).mockClear(); + const result = await generate({ + provider: "google", model: "gemini-test-image", prompt: "panda", + width: 1024, height: 1024, transparent: false, + } as Job, "key", [], { mode: "fixed", sizes: [{ width: 1024, height: 1024 }] }); + expect(result.mime).toBe("image/jpeg"); + expect(result.adaptationError).toBeUndefined(); + expect(result.bytes).toBe(bytes); + expect(fitImage).not.toHaveBeenCalled(); +}); + +it("fits an unformatted JPEG to PNG without a format mismatch note", async () => { + const bytes = new Uint8Array([8, 8, 8]); + const fitted = new Uint8Array([1, 2, 3]); + vi.mocked(imageSize).mockReturnValue({ width: 1024, height: 1024, type: "jpg" }); + vi.mocked(generateImage).mockResolvedValue({ + image: { uint8Array: bytes, mediaType: "image/jpeg" }, usage: {}, + } as never); + const { fitImage } = await import("../src/sources/image-fit"); + vi.mocked(fitImage).mockResolvedValueOnce({ bytes: fitted, mime: "image/png" }); + const result = await generate({ + provider: "openai", model: "gpt-image-2.6-sunburst", prompt: "panda", + width: 800, height: 800, transparent: false, + } as Job, "key", [], { mode: "fixed", sizes: [{ width: 1024, height: 1024 }] }); + expect(fitImage).toHaveBeenCalledWith(bytes, { width: 800, height: 800 }, "png"); + expect(result.bytes).toBe(fitted); + expect(result.mime).toBe("image/png"); + expect(result.adaptationError).toBeUndefined(); +}); + +it("requests SVG directly with n=1 and never returns the key in an error", async () => { + const secret = "svg-provider-credential-fixture"; + const svg = ``; + const fetch = vi.fn(async () => ({ + ok: true, + status: 200, + json: async () => ({ data: [{ b64_json: Buffer.from(svg).toString("base64") }] }), + })); + vi.stubGlobal("fetch", fetch); + vi.mocked(generateImage).mockClear(); + const job = { + provider: "openai", model: "gpt-image-2.6-sunburst", prompt: "A vector panda", + width: 1024, height: 1024, transparent: false, outputFormat: "svg", + quality: "high", complexity: "low", + } as Job; + const result = await generate(job, secret, []); + expect(generateImage).not.toHaveBeenCalled(); + expect(result).toMatchObject({ mime: "image/svg+xml", width: 1024, height: 1024 }); + expect(new TextDecoder().decode(result.bytes)).toBe(svg); + const [url, init] = fetch.mock.calls[0] as unknown as [string, { body: string; headers: { Authorization: string } }]; + expect(url).toBe("https://api.openai.com/v1/images/generations"); + expect(JSON.parse(init.body)).toEqual({ + model: "gpt-image-2.6-sunburst", prompt: "A vector panda", n: 1, size: "1024x1024", + output_format: "svg", quality: "high", complexity: "low", + }); + expect(init.headers.Authorization).toBe(`Bearer ${secret}`); + await generate({ ...job, transparent: true, quality: undefined, complexity: undefined }, secret, []); + const transparentCall = fetch.mock.calls.at(-1) as unknown as [string, { body: string }]; + expect(JSON.parse(transparentCall[1].body).background).toBe("transparent"); + const leaking = new Error(`Authorization: Bearer ${secret}`); + vi.stubGlobal("fetch", vi.fn(async () => { throw leaking; })); + const transport = await rejection(generate(job, secret, [])); + expect(transport.message).not.toContain(secret); + expect(transport.cause).toBeUndefined(); + expect(transport.message).toMatch(/Could not reach/); + const json = vi.fn(async () => { throw leaking; }); + vi.stubGlobal("fetch", vi.fn(async () => ({ ok: true, status: 200, json }))); + const unreadable = await rejection(generate(job, secret, [])); + expect(unreadable.message).not.toContain(secret); + expect(unreadable.message).toMatch(/unreadable image/); + const body = vi.fn(async () => ({ error: secret })); + vi.stubGlobal("fetch", vi.fn(async () => ({ ok: false, status: 401, json: body }))); + const rejected = await rejection(generate({ ...job, transparent: true }, secret, [])); + expect(body).not.toHaveBeenCalled(); + expect(rejected.message).toContain("401"); + expect(rejected.message).toBe("The provider rejected this API key (401). Check the key and try again."); + expect(rejected).toMatchObject({ statusCode: 401 }); + expect(rejected.message).not.toContain(secret); + await expect(generate(job, secret, [new Uint8Array([1])])).rejects.toThrow("reference images"); + vi.stubGlobal("fetch", vi.fn(async () => ({ + ok: true, status: 200, json: async () => ({ data: [{ b64_json: Buffer.from("not a vector").toString("base64") }] }), + }))); + const plain = await rejection(generate(job, secret, [])); + expect(plain.message).toMatch(/unreadable image/); + expect(plain.message).not.toContain(secret); + await expect(generate({ ...job, provider: "google" }, secret, [])).rejects.toThrow("OpenAI image model"); + await expect(generate({ ...job, outputFormat: "webp", provider: "google" }, secret, [])).rejects.toThrow("OpenAI image model"); + await expect(generate(job, secret, [], { mode: "aspect-ratio", ratios: ["1:1"], levels: [] })).rejects.toThrow("pixel size"); + vi.stubGlobal("fetch", vi.fn(async () => ({ ok: false, status: 403, json: async () => ({ error: secret }) }))); + const forbidden = await rejection(generate(job, secret, [])); + expect(forbidden.message).toBe("This API key cannot generate images (403). Check its permissions."); + expect(forbidden).toMatchObject({ statusCode: 403 }); + expect(forbidden.message).not.toContain(secret); + vi.stubGlobal("fetch", vi.fn(async () => ({ + ok: false, + status: 429, + json: async () => ({ error: { message: "You have no credits remaining", code: "insufficient_quota", type: "insufficient_quota" } }), + }))); + const quota = await rejection(generate(job, secret, [])); + expect(quota.message).toBe("The provider rejected image generation (429)."); + expect(quota).toMatchObject({ statusCode: 429, providerCode: "insufficient_quota", providerMessage: "You have no credits remaining" }); + expect(JSON.stringify(quota)).not.toContain(secret); + vi.stubGlobal("fetch", vi.fn(async () => ({ ok: false, status: 500, json: async () => ({ error: secret }) }))); + const failed = await rejection(generate(job, secret, [])); + expect(failed.message).toBe("The provider rejected image generation (500)."); + expect(failed).toMatchObject({ statusCode: 500 }); + expect(failed.message).not.toContain(secret); + vi.stubGlobal("fetch", vi.fn(async () => ({ ok: true, status: 200, json: async () => ({ data: [{ b64_json: "!!!!" }] }) }))); + const invalid = await rejection(generate(job, secret, [])); + expect(invalid.message).toMatch(/unreadable image/); + expect(invalid.message).not.toContain(secret); +}); + it("reports a credential rejection without reading the provider error body", async () => { const json = vi.fn(async () => ({ error: "fixture-key" })); vi.stubGlobal("fetch", vi.fn(async () => ({ ok: false, status: 403, json }))); diff --git a/tests/refresh-models.test.ts b/tests/refresh-models.test.ts new file mode 100644 index 0000000..51d9c21 --- /dev/null +++ b/tests/refresh-models.test.ts @@ -0,0 +1,42 @@ +import { afterEach, expect, it, vi } from "vitest"; +import { MemoryStorage } from "../src/storage/memory"; +import { refreshModelCatalog } from "../src/core/model-refresh"; +import type { Model } from "../src/core/schema"; + +afterEach(() => { + vi.unstubAllEnvs(); + vi.stubGlobal("fetch", () => { throw new Error("Real network access is disabled in tests. Mock the provider transport."); }); +}); + +it("saves every discovered image model and returns the ones with a verified profile, newest first", async () => { + vi.stubEnv("IMAGE_QUEUE_OPENAI_API_KEY", "server-key-fixture"); + const fetchModels = vi.fn(async (_url: string, init?: RequestInit) => { + expect(new Headers(init?.headers).get("authorization")).toBe("Bearer server-key-fixture"); + return Response.json({ data: [ + { id: "gpt-image-1.5" }, { id: "gpt-image-2.6-flare" }, { id: "gpt-image-2.5-sunburst" }, + { id: "gpt-image-9-preview" }, { id: "gpt-6.1-sol" }, + ] }); + }); + vi.stubGlobal("fetch", fetchModels); + const store = new MemoryStorage(); + await store.put("models", "openai", [{ id: "gpt-image-1.5", name: "old", provider: "openai" }]); + + const usable = await refreshModelCatalog(store, "openai"); + + expect(fetchModels).toHaveBeenCalledOnce(); + expect(String(fetchModels.mock.calls[0]![0])).toBe("https://api.openai.com/v1/models"); + expect(usable.map(model => model.id)).toEqual(["gpt-image-2.6-flare", "gpt-image-2.5-sunburst", "gpt-image-1.5"]); + const saved = await store.get("models", "openai"); + expect(saved?.map(model => model.id).sort()).toEqual(["gpt-image-1.5", "gpt-image-2.5-sunburst", "gpt-image-2.6-flare", "gpt-image-9-preview"]); + expect(JSON.stringify([usable, saved])).not.toContain("server-key-fixture"); +}); + +it("keeps the saved catalog when the key cannot list any image model", async () => { + vi.stubEnv("IMAGE_QUEUE_OPENAI_API_KEY", "server-key-fixture"); + vi.stubGlobal("fetch", vi.fn(async () => Response.json({ data: [{ id: "gpt-6.1-sol" }] }))); + const store = new MemoryStorage(); + const before = [{ id: "gpt-image-1.5", name: "GPT Image 1.5", provider: "openai" }]; + await store.put("models", "openai", before); + await expect(refreshModelCatalog(store, "openai")).rejects.toThrow("no supported image models"); + expect(await store.get("models", "openai")).toEqual(before); +}); diff --git a/tests/remote-agent-connection.test.tsx b/tests/remote-agent-connection.test.tsx new file mode 100644 index 0000000..66d1941 --- /dev/null +++ b/tests/remote-agent-connection.test.tsx @@ -0,0 +1,35 @@ +// @vitest-environment happy-dom +import { cleanup, fireEvent, render, screen } from "@testing-library/react"; +import { afterEach, expect, it, vi } from "vitest"; +import { remoteMcpClients } from "../src/core/mcp-configuration"; + +vi.mock("../src/actions", () => ({ openAgentConfigDirectoryAction: vi.fn() })); +import { AgentConnection } from "../src/components/agent-connection"; + +afterEach(cleanup); + +it("builds remote connection steps from the deployment origin, without keys", () => { + const { url, clients } = remoteMcpClients("https://app.example.com/settings?x=1#agent-connection"); + expect(url).toBe("https://app.example.com/api/mcp"); + expect(clients.map(client => client.name)).toEqual(["Claude", "Claude Code", "Codex"]); + expect(clients[1].value).toBe("claude mcp add --transport http image-queue https://app.example.com/api/mcp"); + expect(clients[2].value).toBe("codex mcp add image-queue --url https://app.example.com/api/mcp\ncodex mcp login image-queue"); + expect(JSON.stringify(clients)).not.toMatch(/token|secret|sk-/i); +}); + +it("shows a hosted workspace how to connect Claude and coding agents to its remote MCP server", () => { + render( {}} />); + expect(screen.getByRole("region", { name: "Server URL" }).textContent).toBe("https://app.example.com/api/mcp"); + // Claude comes first: numbered steps for the connector, not a local stdio configuration. + expect(screen.getByRole("list", { name: "Claude steps" }).querySelectorAll("li").length).toBe(4); + expect(screen.queryByText("pnpm build:mcp")).toBeNull(); + fireEvent.click(screen.getByRole("button", { name: "Claude Code" })); + expect(screen.getByRole("region", { name: "Claude Code command" }).textContent) + .toBe("claude mcp add --transport http image-queue https://app.example.com/api/mcp"); +}); + +it("keeps the local stdio configuration for a local workspace", () => { + render( {}} />); + expect(screen.getByText("pnpm build:mcp")).toBeTruthy(); + expect(screen.queryByRole("region", { name: "Server URL" })).toBeNull(); +}); diff --git a/tests/routes.test.ts b/tests/routes.test.ts index 2eaa81d..9db7547 100644 --- a/tests/routes.test.ts +++ b/tests/routes.test.ts @@ -351,6 +351,20 @@ it("imports images through the same-origin endpoint", async () => { ).toBe(403); }); +it("serves SVG with a locked-down content security policy", async () => { + const svg = ``; + mocks.store.get.mockImplementation(async (collection: string) => collection === "jobs" + ? { id: "vector", status: "done", blobKey: "results/vector", source: "api" } + : undefined); + mocks.store.getBlob.mockResolvedValue({ bytes: new TextEncoder().encode(svg), mime: "image/svg+xml" }); + const response = await asset(new Request("http://localhost/api/asset?job=vector")); + expect(response.status).toBe(200); + expect(response.headers.get("content-type")).toBe("image/svg+xml"); + expect(response.headers.get("content-security-policy")).toBe("default-src 'none'; style-src 'unsafe-inline'; sandbox"); + expect(response.headers.get("x-content-type-options")).toBe("nosniff"); + expect(await response.text()).toBe(svg); +}); + it("serves a retained blocked output and rejects blocked jobs without a file", async () => { mocks.store.get.mockImplementation(async (collection: string) => collection === "jobs" ? { id: "retained", status: "blocked", blobKey: "results/retained" } diff --git a/tests/runtime.test.ts b/tests/runtime.test.ts index cfa0cbd..bcc35a4 100644 --- a/tests/runtime.test.ts +++ b/tests/runtime.test.ts @@ -1,9 +1,11 @@ import { createHash } from "node:crypto"; +import { APICallError } from "ai"; import { png, mp4 } from "./fixtures"; import { mkdir, mkdtemp, readFile, realpath, rm, utimes, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { jobRecovery } from "../src/core/job-recovery"; import { importExistingQueue } from "../src/core/import-queue"; import { executeImageJob, refreshedJobs, retryBlockedQueueJob, retryImageJob, service } from "../src/core/runtime"; import type { Job } from "../src/core/schema"; @@ -19,6 +21,7 @@ vi.mock("../src/core/model-profiles", async (importOriginal) => { actual.applyVerifiedModelProfiles(models.map(model => model.id === "gpt-image-test" ? {...model, provider: "openai" as const} : model), models.filter(model => model.id === "gpt-image-test" && actual.verifiedModelProfileSchema.shape.sizeProfile.safeParse(model.sizeProfile).success).map(model => ({ provider: "openai" as const, model: "gpt-image-test", sizeProfile: model.sizeProfile!, references: model.references, transparency: model.transparency, + qualities: ["low", "medium", "high", "auto"], complexities: [], outputFormats: ["png", "webp", "jpeg", "gif", "svg"], documentedOnly: [], documentation: "https://example.com/fixture", verifiedAt: "2026-11-15T00:00:00Z", evidence: { generation: "fixture", referenceEdit: "fixture" }, }))) @@ -64,6 +67,32 @@ afterEach(async () => { usage: {}, } as never); }); +function apiError(statusCode: number, body: unknown) { + return new APICallError({ + message: "do-not-store-sdk-message-sentinel", + url: "https://api.openai.com/v1/images/generations", + requestBodyValues: { secret: "do-not-store-request-body-sentinel" }, + responseHeaders: { authorization: "Bearer do-not-store-header-sentinel" }, + statusCode, + responseBody: JSON.stringify(body), + }); +} +function hidesSecrets(job: Job) { + const serialized = JSON.stringify(job); + expect(serialized).not.toContain("do-not-store"); + expect(serialized).not.toContain("Bearer"); + expect(serialized).not.toContain("test-key"); +} +async function failApi(error: unknown) { + const job = await make("api"); + process.env.OPENAI_API_KEY = "test-key"; + await store.put("models", "openai", [ + { id: "gpt-image-test", references: false, transparency: false, sizeProfile: { mode: "fixed", sizes: [{ width: 1024, height: 1024 }] } }, + ]); + vi.mocked(generate).mockRejectedValueOnce(error); + await execute(job.id); + return (await store.get("jobs", job.id))!; +} async function make(source: "queue" | "api" = "queue") { const p = await api.createProject("Test"); return api.create({ @@ -203,6 +232,56 @@ describe("runtime", () => { const digest = createHash("sha256").update(bytes).digest("hex"); expect(saved?.blobKey).toBe(`results/${digest}`); expect(await store.getBlob(`results/${digest}`)).toEqual({ bytes, mime: "image/png" }); + expect(JSON.parse(saved!.provenance!).outputFormat).toBe("png"); + }); + it("stores each requested API format and records it in provenance", async () => { + process.env.OPENAI_API_KEY = "test-key"; + await store.put("models", "openai", [{ + id: "gpt-image-test", references: false, transparency: true, + sizeProfile: { mode: "fixed", sizes: [{ width: 1024, height: 1024 }] }, + }]); + const { outputMime, extensionForOutputFormat } = await import("../src/core/image-format"); + for (const format of ["png", "webp", "jpeg", "gif", "svg"] as const) { + const bytes = Uint8Array.of(format.length); + vi.mocked(generate).mockResolvedValueOnce({ bytes, mime: outputMime[format], width: 1024, height: 1024, usage: {} } as never); + const project = await api.createProject(format); + const job = await api.create({ + projectId: project.id, idempotencyKey: format, prompt: "Painted panda", source: "api", + provider: "openai", model: "gpt-image-test", width: 1024, height: 1024, + transparent: false, referenceIds: [], outputFormat: format, + ...(format === "gif" ? { frameCount: 6, frameDurationMs: 100 } : {}), + }); + await execute(job.id); + const saved = await store.get("jobs", job.id); + const provenance = JSON.parse(saved!.provenance!); + expect(saved?.status).toBe("done"); + expect(provenance.outputFormat).toBe(format); + if (format === "gif") expect(provenance).toMatchObject({ frameCount: 6, frameDurationMs: 100 }); + expect(await store.getBlob(saved!.blobKey!)).toEqual({ bytes, mime: outputMime[format] }); + expect(`${job.id}.${extensionForOutputFormat(format)}`).toBe(`${job.id}.${format === "jpeg" ? "jpg" : format}`); + } + }); + it("tells the local runner to stop on a rejected key while the request keeps the provider's reason", async () => { + const { ImageRequestError } = await import("../src/core/api-rejection"); + for (const error of [ + apiError(401, { error: { message: "Incorrect API key provided." } }), + new ImageRequestError(401, "The provider rejected this API key (401). Check the key and try again."), + ]) { + const job = await make("api"); + process.env.OPENAI_API_KEY = "test-key"; + await store.put("models", "openai", [ + { id: "gpt-image-test", references: false, transparency: false, sizeProfile: { mode: "fixed", sizes: [{ width: 1024, height: 1024 }] } }, + ]); + vi.mocked(generate).mockRejectedValueOnce(error); + const failed = vi.fn(async () => {}); + await executeImageJob(job.id, store, { admit: async commit => { await commit(); return true; }, failed }); + expect(failed).toHaveBeenCalledExactlyOnceWith(expect.stringContaining("OpenAI rejected access"), true, undefined); + const saved = (await store.get("jobs", job.id))!; + expect(saved.status).toBe("failed"); + expect(saved.error).toContain("(HTTP 401)"); + expect(saved.error).toContain("No image was generated."); + hidesSecrets(saved); + } }); it("preserves uncertain failures without replaying the request", async () => { const job = await make("api"); @@ -217,6 +296,103 @@ describe("runtime", () => { await execute(job.id); expect(generate).toHaveBeenCalledTimes(1); }); + it("records a definite provider rejection as failed and allows another request", async () => { + const quota = await failApi(apiError(429, { + error: { message: "You exceeded your current quota", type: "insufficient_quota", code: "insufficient_quota" }, + })); + expect(quota.status).toBe("failed"); + expect(quota.error).toContain("https://platform.openai.com/settings/organization/billing"); + expect(quota.error).toMatch(/no credits/i); + expect(quota.error).toContain("HTTP 429"); + expect(quota.error).toContain("No image was generated."); + expect(quota.error).not.toContain("may have been charged"); + expect(jobRecovery(quota)).toMatchObject({ + action: "inspect_error", + automaticRetryAllowed: false, + message: "Read the error and fix its cause before retrying. Do not repeat an unchanged failing request.", + }); + hidesSecrets(quota); + const retried = await retryImageJob(quota.id); + expect(retried.id).not.toBe(quota.id); + expect(retried.status).toBe("queued"); + expect((await store.get("jobs", quota.id))?.status).toBe("failed"); + + const invalid = await failApi(apiError(400, { + error: { message: `Invalid size: 100x100 is not supported. ${"x".repeat(400)}TAIL_SHOULD_BE_OMITTED` }, + })); + expect(invalid.status).toBe("failed"); + expect(invalid.error).toContain("HTTP 400"); + expect(invalid.error).toContain("Invalid size: 100x100 is not supported."); + expect(invalid.error).toContain("No image was generated."); + expect(invalid.error).not.toContain("TAIL_SHOULD_BE_OMITTED"); + expect(invalid.error!.length).toBeLessThanOrEqual(400); + hidesSecrets(invalid); + + const limited = await failApi(apiError(429, { + error: { message: "Rate limit reached for requests.", type: "requests", code: "rate_limit_exceeded" }, + })); + expect(limited.status).toBe("failed"); + expect(limited.error).toContain("Retry later."); + expect(limited.error).toContain("No image was generated."); + expect(limited.error).not.toContain("platform.openai.com"); + hidesSecrets(limited); + }); + it("keeps timeouts, aborts, network failures and server errors uncertain", async () => { + const abort = new Error("The operation was aborted"); + abort.name = "AbortError"; + const uncertain = "Generation did not complete locally. Check the provider before creating another request; it may have been charged."; + for (const error of [ + new DOMException("The operation was aborted due to timeout", "TimeoutError"), + abort, + new APICallError({ + message: "Cannot connect to API: socket hang up", + url: "https://api.openai.com/v1/images/generations", + requestBodyValues: { secret: "do-not-store-request-body-sentinel" }, + }), + apiError(500, { error: { message: "The server had an error while processing your request.", type: "server_error" } }), + ]) { + const saved = await failApi(error); + expect(saved.status).toBe("uncertain"); + expect(saved.error).toBe(uncertain); + expect(JSON.stringify(saved)).not.toContain("do-not-store"); + expect(JSON.stringify(saved)).not.toContain("server had an error"); + } + }); + it("records an SVG provider 429 as failed without keeping the API key", async () => { + const job = await make("api"); + const secret = "svg-quota-key-should-not-appear"; + process.env.OPENAI_API_KEY = secret; + await store.put("models", "openai", [ + { id: "gpt-image-test", references: false, transparency: false, sizeProfile: { mode: "fixed", sizes: [{ width: 1024, height: 1024 }] } }, + ]); + await store.put("jobs", job.id, { ...job, outputFormat: "svg" }); + vi.stubGlobal("fetch", vi.fn(async () => ({ + ok: false, + status: 429, + json: async () => ({ error: { message: "You have no credits remaining to generate images." } }), + }))); + try { + const actual = await vi.importActual("../src/sources/providers"); + vi.mocked(generate).mockImplementationOnce(actual.generate); + await execute(job.id); + } finally { + vi.stubGlobal("fetch", () => { + throw new Error("Real network access is disabled in tests. Mock the provider transport."); + }); + } + const saved = (await store.get("jobs", job.id))!; + expect(saved.status).toBe("failed"); + expect(saved.error).toContain("https://platform.openai.com/settings/organization/billing"); + expect(saved.error).toMatch(/no credits/i); + expect(saved.error).toContain("No image was generated."); + expect(JSON.stringify(saved)).not.toContain(secret); + expect(jobRecovery(saved)).toMatchObject({ action: "inspect_error", automaticRetryAllowed: false }); + const created = await api.create({ + projectId: job.projectId, idempotencyKey: "after-quota", prompt: "Painted panda", source: "api", + provider: "openai", model: "gpt-image-test", width: 1024, height: 1024, transparent: false, referenceIds: [], + }); + expect(created.status).toBe("queued"); + }); it("recovers interrupted API status without calling a provider", async () => { const job = await make("api"); await store.put("jobs", job.id, { @@ -355,7 +531,7 @@ it("rejects cloud queue execution before touching files", async () => { const stub = vi.spyOn(stores, "storage").mockResolvedValue(store); const job = await make(); process.env.STORAGE_DRIVER = "cloudflare"; - await expect(execute(job.id)).rejects.toThrow("local companion"); + await expect(execute(job.id)).rejects.toThrow("only in a local installation"); stub.mockRestore(); }); it("rejects API generation without a discovered model profile", async () => { diff --git a/tests/size-intent.test.ts b/tests/size-intent.test.ts index 2f3ef8e..2765425 100644 --- a/tests/size-intent.test.ts +++ b/tests/size-intent.test.ts @@ -23,7 +23,7 @@ it("validates model dimension and resolution constraints",async()=>{ expect(()=>resolveModelSize({mode:"aspect-ratio",ratios:["1:1"],levels:[]},{aspectRatio:"9:16"})).toThrow(); const profile={mode:"dimensions" as const,minSide:256,maxSide:4096,multiple:16,minPixels:65536,maxPixels:9000000,minRatio:1/3,maxRatio:3}; expect(resolveModelSize(profile,{width:1024,height:1024}).requiresResize).toBe(false); - expect(()=>resolveModelSize(profile,{width:1025,height:1024})).toThrow("limits"); + expect(resolveModelSize(profile,{width:1025,height:1024})).toEqual({target:{width:1025,height:1024},parameters:{size:"1040x1024"},requiresResize:true}); }); it("uses the model native size for ratio-only requests", async () => { @@ -74,8 +74,8 @@ it("checks every dimension boundary with an actionable error", async () => { expect(resolveModelSize(profile, { width: 512, height: 512 }).requiresResize).toBe(false); expect(resolveModelSize(profile, { width: 2048, height: 1024 }).requiresResize).toBe(false); expect(() => resolveModelSize(profile, { width: 2064, height: 1024 })).toThrow("between 256 and 2048 pixels"); - expect(() => resolveModelSize(profile, { width: 1025, height: 1024 })).toThrow("divisible by 16"); - expect(() => resolveModelSize(profile, { width: 256, height: 256 })).toThrow("total pixels"); + expect(resolveModelSize(profile, { width: 1025, height: 1024 }).parameters).toEqual({ size: "1040x1024" }); + expect(resolveModelSize(profile, { width: 256, height: 256 })).toEqual({ target: { width: 256, height: 256 }, parameters: { size: "512x512" }, requiresResize: true }); expect(() => resolveModelSize(profile, { width: 1536, height: 1536 })).toThrow("total pixels"); expect(() => resolveModelSize(profile, { width: 1536, height: 512 })).toThrow("width/height between 0.5 and 2"); }); @@ -105,3 +105,22 @@ it("rejects a native size too small to produce the requested aspect ratio", asyn expect(() => resolveModelSize({ mode: "fixed", sizes: [{ width: 1, height: 1 }] }, { aspectRatio: "21:9" })).toThrow("No native size can represent"); }); + +it("resolves gpt-image-2.6-flare sizes on its 16-pixel grid", async () => { + const { resolveModelSize } = await import("../src/core/size-intent"); + const { verifiedModelProfiles } = await import("../src/core/model-profiles"); + const flare = verifiedModelProfiles.find(entry => entry.model === "gpt-image-2.6-flare")!.sizeProfile; + expect(resolveModelSize(flare, { aspectRatio: "16:9" })).toEqual({ target: { width: 2048, height: 1152 }, parameters: { size: "2048x1152" }, requiresResize: false }); + expect(resolveModelSize(flare, { aspectRatio: "9:16" }).parameters).toEqual({ size: "1152x2048" }); + expect(resolveModelSize(flare, { aspectRatio: "21:9" }).parameters).toEqual({ size: "2688x1152" }); + expect(resolveModelSize(flare, { width: 1536, height: 864 })).toMatchObject({ parameters: { size: "1536x864" }, requiresResize: false }); + expect(resolveModelSize(flare, { width: 3840, height: 2160 })).toMatchObject({ parameters: { size: "3840x2160" }, requiresResize: false }); + // Small sprites are generated at the smallest allowed size and fitted down, never upscaled. + const sprite = resolveModelSize(flare, { width: 256, height: 256 }); + expect(sprite).toEqual({ target: { width: 256, height: 256 }, parameters: { size: "816x816" }, requiresResize: true }); + expect(816 * 816).toBeGreaterThanOrEqual(655360); + expect(resolveModelSize(flare, { width: 1920, height: 1080 })).toEqual({ target: { width: 1920, height: 1080 }, parameters: { size: "1920x1088" }, requiresResize: true }); + expect(() => resolveModelSize(flare, { width: 4096, height: 2304 })).toThrow("between 16 and 3840 pixels"); + expect(() => resolveModelSize(flare, { width: 3200, height: 1024 })).toThrow("width/height between 1/3 and 3"); + expect(() => resolveModelSize(flare, { width: 3840, height: 3840 })).toThrow("total pixels"); +}); diff --git a/tests/storage-contract.test.ts b/tests/storage-contract.test.ts index 58652bc..8692171 100644 --- a/tests/storage-contract.test.ts +++ b/tests/storage-contract.test.ts @@ -40,7 +40,8 @@ for (const driver of ["disk", "memory", "cloudflare"]) { disposables.push(async () => disallowLoopback()); const proxy = await getPlatformProxy({ configPath, persist: false, remoteBindings: false }); disposables.push(() => proxy.dispose()); - await proxy.env.DB.exec((await readFile("migrations/0001.sql", "utf8")).trim()); + for (const migration of ["0001.sql", "0002.sql"]) + await proxy.env.DB.exec((await readFile(`migrations/${migration}`, "utf8")).trim()); return new CloudflareStorage(proxy.env.DB, proxy.env.BUCKET); } it("round-trips records and isolates returned values", async () => { diff --git a/tests/thumbnail.test.ts b/tests/thumbnail.test.ts index 6e45e5b..30a3a08 100644 --- a/tests/thumbnail.test.ts +++ b/tests/thumbnail.test.ts @@ -1,3 +1,4 @@ +import sharp from "sharp"; import { afterEach, expect, it, vi } from "vitest"; const { response } = vi.hoisted(() => ({ response: vi.fn(() => new Response(new Uint8Array([1, 2, 3]))) })); vi.mock("@opennextjs/cloudflare", () => ({ @@ -24,9 +25,23 @@ it("uses the Cloudflare Images binding and returns WebP bytes", async () => { expect(await thumbnail(new Uint8Array([1]), 320)).toEqual({ bytes: new Uint8Array([1, 2, 3]), mime: "image/webp", + animated: false, }); }); +it("rasterizes an SVG and the first GIF frame to WebP", async () => { + const svg = Buffer.from(``); + const preview = await thumbnail(svg, 10); + expect(preview.mime).toBe("image/webp"); + expect(await sharp(preview.bytes).metadata()).toMatchObject({ format: "webp", width: 10 }); + const red = await sharp({ create: { width: 40, height: 20, channels: 3, background: "red" } }).png().toBuffer(); + const blue = await sharp({ create: { width: 40, height: 20, channels: 3, background: "blue" } }).png().toBuffer(); + const gif = await sharp([red, blue], { join: { animated: true } }).gif().toBuffer(); + const frame = await thumbnail(gif, 10); + const { dominant } = await sharp(frame.bytes).stats(); + expect(dominant.r).toBeGreaterThan(dominant.b); +}); + it("rejects a failed Cloudflare transform before returning bytes as WebP", async () => { process.env.STORAGE_DRIVER = "cloudflare"; response.mockReturnValueOnce(new Response("Unavailable", { status: 503 })); diff --git a/tests/workspace.test.tsx b/tests/workspace.test.tsx index 01909c1..9cc64fa 100644 --- a/tests/workspace.test.tsx +++ b/tests/workspace.test.tsx @@ -111,6 +111,7 @@ import { createTopicAction, processingAction, poolConfigAction, + generationSourceAction, requestImageAction, moveJobAction, cancelAction, @@ -535,6 +536,8 @@ describe("workspace edge cases and interactions", () => { ); const error = await screen.findByRole("alert"); expect(error.textContent).toBe("Invalid key"); + expect(error.classList.contains("field-error")).toBe(true); + expect(document.querySelector(".toast")).toBeNull(); const key = screen.getByLabelText("API key"); expect(key.getAttribute("aria-describedby")).toBe(error.id); expect(key.getAttribute("aria-invalid")).toBe("true"); @@ -555,7 +558,11 @@ describe("workspace edge cases and interactions", () => { (screen.getByLabelText("Generation source") as HTMLSelectElement).value, ).toBe("api"), ); - expect(screen.getByText("Local companion required")).toBeTruthy(); + // The sidebar names the source in use instead of a Codex queue that cannot run there. + const status = document.querySelector(".generation-status")!; + expect(status.textContent).toContain("OpenAI API"); + expect(screen.queryByText("Local companion required")).toBeNull(); + expect(screen.queryByLabelText("Active generation source")).toBeNull(); }); }); @@ -579,6 +586,30 @@ it("cancels a queued request and reports cancellation failures", async () => { fireEvent.click(screen.getByRole("button", { name: "Cancel request" })); await screen.findByText("Already claimed"); }); +it("disables using a GIF or SVG result as a reference", async () => { + vi.stubGlobal("fetch", vi.fn(async () => ({ + ok: true, + json: async () => ({ ...structuredClone(state), jobs: [{ ...state.jobs[0], outputFormat: "gif", source: "api" }] }), + }))); + render(); + fireEvent.click(await screen.findByRole("button", { name: "Open IMG-first" })); + expect(screen.getByRole("button", { name: "Use as reference" })).toHaveProperty("disabled", true); + expect(document.getElementById("reference-format-reason")?.textContent).toBe("GIF and SVG results cannot be used as references."); +}); +it("downloads a WebP result with a matching file extension", async () => { + vi.stubGlobal("fetch", vi.fn(async () => ({ + ok: true, + json: async () => ({ ...structuredClone(state), jobs: [{ ...state.jobs[0], outputFormat: "webp", source: "api" }] }), + }))); + const names: string[] = []; + vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(function (this: HTMLAnchorElement) { + names.push(this.download); + }); + render(); + fireEvent.click(await screen.findByRole("button", { name: "Open IMG-first" })); + fireEvent.click(screen.getByRole("button", { name: "Download" })); + expect(names).toEqual(["IMG-first.webp"]); +}); it("downloads and reuses a generated image as a reference", async () => { vi.stubGlobal( "fetch", @@ -727,10 +758,26 @@ it("tests a connected provider beside its disconnect action", async () => { const test = screen.getByRole("button", { name: "Test connection" }); expect(test.parentElement).toBe(screen.getByRole("button", { name: "Disconnect" }).parentElement); fireEvent.click(test); - await screen.findByText("Connection works. 3 image models available."); + const confirmation = await screen.findByText("Connection works. 3 image models available."); + expect(confirmation.closest(".toast")).toBeTruthy(); + expect(document.querySelector(".settings-notice")).toBeNull(); + expect(test.closest("li")?.querySelector(".settings-list-meta")?.textContent).toBe("1 model"); expect(testConnectionAction).toHaveBeenCalledWith({ provider: "openai" }); expect(disconnectAction).not.toHaveBeenCalled(); }); +it("keeps a failed connection test beside the provider", async () => { + const { testConnectionAction } = await import("../src/actions"); + vi.mocked(testConnectionAction).mockResolvedValueOnce({ + serverError: "The provider rejected this API key (401). Check the key and try again.", + } as never); + render(); + await screen.findByLabelText("API key"); + fireEvent.click(screen.getByRole("button", { name: "Test connection" })); + const error = await screen.findByText("The provider rejected this API key (401). Check the key and try again."); + expect(error.closest(".settings-list-meta")).toBeTruthy(); + expect(error.closest(".toast")).toBeNull(); + expect(document.querySelector(".settings-notice")).toBeNull(); +}); it("copies an output path and focuses the prompt", async () => { Object.defineProperty(navigator, "clipboard", { configurable: true, @@ -782,7 +829,9 @@ it("handles settings navigation and provider disconnect errors", async () => { render(); await screen.findByLabelText("API key"); fireEvent.click(screen.getByRole("button", { name: "Disconnect" })); - await screen.findByText("Cannot disconnect"); + const failure = await screen.findByText("Cannot disconnect"); + expect(failure.classList.contains("settings-notice")).toBe(true); + expect(document.querySelector(".toast")).toBeNull(); fireEvent.click(screen.getByRole("button", { name: /^All images/ })); fireEvent.click(screen.getByRole("button", { name: /^Queue/ })); fireEvent.click(screen.getByRole("button", { name: "New project" })); @@ -1514,7 +1563,8 @@ it("keeps custom size open when dimensions violate the model profile", async () fireEvent.change(screen.getByLabelText("Generation source"), { target: { value: "api" } }); fireEvent.change(screen.getByLabelText("Image model"), { target: { value: "gpt-image-test" } }); fireEvent.change(screen.getByLabelText("Image size"), { target: { value: "custom" } }); - fireEvent.change(screen.getByLabelText("Width"), { target: { value: "1025" } }); + // Off-grid sizes are now fitted down from a covering native size; exceeding maxSide is still refused. + fireEvent.change(screen.getByLabelText("Width"), { target: { value: "2064" } }); fireEvent.change(screen.getByLabelText("Height"), { target: { value: "1024" } }); fireEvent.click(screen.getByRole("button", { name: "Apply size" })); expect(screen.getByRole("alert").textContent).toContain("model's limits"); @@ -2188,16 +2238,18 @@ it("updates the same polite live region after workers are paused", async () => { ok: true, json: async () => ({ ...structuredClone(state), + // The sidebar reports the source in use, so the queue must be it. + generationSource: { source: "queue" }, pool: { ...state.pool, workers: vi.mocked(poolConfigAction).mock.calls.length ? 0 : 4 }, }), }))); - const { container } = render(); - const region = container.querySelector('.queue-health [aria-live="polite"]'); - expect(region?.textContent).toBe("Not configured"); + const { container } = render(); + const region = container.querySelector('.generation-status [aria-live="polite"]'); + expect(region?.textContent).toBe("Workers not responding"); fireEvent.change(await screen.findByLabelText("Active workers"), { target: { value: "0" } }); fireEvent.click(screen.getByRole("button", { name: "Save worker settings" })); await waitFor(() => expect(region?.textContent).toBe("Workers paused")); - expect(container.querySelector('.queue-health [aria-live="polite"]')).toBe(region); + expect(container.querySelector('.generation-status [aria-live="polite"]')).toBe(region); }); it("shows a disabled worker finishing its existing reservation", async () => { @@ -2719,10 +2771,26 @@ it("hides discovered models without usable size profiles from the composer", asy }) }))); await ready(); fireEvent.change(screen.getByLabelText("Generation source"), { target: { value: "api" } }); - expect(screen.getByRole("option", { name: "Image test" })).toBeTruthy(); + // The composer and the sidebar both list models; neither offers one without a size profile. + expect(screen.getAllByRole("option", { name: "Image test" }).length).toBe(2); expect(screen.queryByRole("option", { name: "Unprofiled model" })).toBeNull(); }); +it("shows and switches the generation source and model in the sidebar", async () => { + vi.stubGlobal("fetch", vi.fn(async () => ({ ok: true, json: async () => ({ ...structuredClone(state), generationSource: { source: "queue" } }) }))); + render(); + const status = document.querySelector(".generation-status")!; + const sourceSelect = screen.getByLabelText("Active generation source") as HTMLSelectElement; + expect(sourceSelect.value).toBe("queue"); + expect(screen.queryByLabelText("Active image model")).toBeNull(); + fireEvent.change(sourceSelect, { target: { value: "api" } }); + await waitFor(() => expect(generationSourceAction).toHaveBeenCalledWith(expect.objectContaining({ source: "api" }))); + // The composer follows the same setting, and the model becomes switchable beside it. + expect((screen.getByLabelText("Generation source") as HTMLSelectElement).value).toBe("api"); + expect(await screen.findByLabelText("Active image model")).toBeTruthy(); + await waitFor(() => expect(status.textContent).toContain("Billed to your OpenAI key")); +}); + it("updates the provider state from the saved catalog and shows success without error styling", async () => { vi.mocked(connectAction).mockResolvedValueOnce({ data: state.models } as never); @@ -2730,12 +2798,26 @@ it("updates the provider state from the saved catalog and shows success without fireEvent.change(screen.getByLabelText("API key"), { target: { value: "fixture-key-value" } }); fireEvent.click(screen.getByRole("button", { name: "Connect & load models" })); const success = await screen.findByText("Provider connected and image models refreshed"); - expect(success.classList.contains("provider-success")).toBe(true); + expect(success.closest(".toast")).toBeTruthy(); expect(success.classList.contains("field-error")).toBe(false); + expect(document.querySelector(".provider-success")).toBeNull(); + expect(document.querySelector(".settings-notice")).toBeNull(); expect(screen.getByRole("button", { name: "Update key & refresh models" })).toBeTruthy(); expect(screen.getByText("Model catalog saved", { exact: true })).toBeTruthy(); }); +it("toasts when the provider connects but the workspace cannot refresh", async () => { + vi.mocked(connectAction).mockResolvedValueOnce({ data: state.models } as never); + vi.stubGlobal("fetch", vi.fn(async () => { throw new Error("offline"); })); + render(); + fireEvent.change(screen.getByLabelText("API key"), { target: { value: "fixture-key-value" } }); + fireEvent.click(screen.getByRole("button", { name: "Connect & load models" })); + const success = await screen.findByText("Provider connected. Refresh the page to reload the workspace."); + expect(success.closest(".toast")).toBeTruthy(); + expect(document.querySelector(".settings-notice")).toBeNull(); + expect(screen.queryByText("Provider connected and image models refreshed")).toBeNull(); +}); + it("distinguishes a connected provider without a size profile from a missing connection", async () => { const unprofiled = state.models.map(({ sizeProfile: _profile, ...model }) => model); vi.stubGlobal("fetch", vi.fn(async () => ({ ok: true, json: async () => ({ ...structuredClone(state), models: unprofiled }) }))); @@ -3023,6 +3105,9 @@ it("saves the default source in Settings without submitting or resuming work", a render(); fireEvent.change(screen.getByRole('combobox', {name:'Default generation source'}), {target:{value:'api'}}); await waitFor(() => expect(generationSourceAction).toHaveBeenCalledWith({source:'api',provider:'openai'})); + const saved = await screen.findByText("Default source saved. Existing requests keep their source."); + expect(saved.classList.contains("settings-notice")).toBe(true); + expect(document.querySelector(".toast")).toBeNull(); await waitFor(() => expect((screen.getByRole('combobox', {name:'Default generation source'}) as HTMLSelectElement).value).toBe('api')); expect(requestImageAction).not.toHaveBeenCalled(); expect(pauseLocalRunnerAction).not.toHaveBeenCalled(); @@ -3037,6 +3122,110 @@ it("restores the composer source when saving its default fails", async () => { expect((screen.getByRole('combobox', {name:'Generation source'}) as HTMLSelectElement).value).toBe('queue'); }); +const capableModels = [ + { + id: "gpt-image-2.6-sunburst", name: "Sunburst", provider: "openai", transparency: true, references: true, + sizeProfile: { mode: "fixed", sizes: [{ width: 1024, height: 1024 }] }, + qualities: ["low", "medium", "high", "xhigh", "auto"], + complexities: ["low", "medium", "high"], + outputFormats: ["png", "webp", "jpeg", "gif", "svg"], + }, + { + id: "gpt-image-1-mini", name: "Mini", provider: "openai", transparency: true, references: true, + sizeProfile: { mode: "fixed", sizes: [{ width: 1024, height: 1024 }] }, + qualities: ["low", "medium"], complexities: [], outputFormats: ["png", "webp"], + }, +]; + +it("offers API quality, complexity, format and count, and blocks conflicting formats", async () => { + vi.stubGlobal("fetch", vi.fn(async () => ({ + ok: true, + json: async () => ({ ...structuredClone(state), models: capableModels, references: [ + { id: "ref", projectId: "project", name: "panda.png", kind: "image" }, + ] }), + }))); + render(); + await screen.findByRole("button", { name: "Open IMG-first" }); + expect(screen.queryByLabelText("Quality")).toBeNull(); + expect(screen.queryByLabelText("Format")).toBeNull(); + expect(screen.getByLabelText("Image variants").querySelectorAll("option")).toHaveLength(4); + fireEvent.change(screen.getByLabelText("Generation source"), { target: { value: "api" } }); + await waitFor(() => expect(screen.getByLabelText("Quality")).toBeTruthy()); + expect(screen.getByLabelText("Image variants").querySelectorAll("option")).toHaveLength(10); + const quality = screen.getByLabelText("Quality"); + expect(quality.querySelectorAll("option").length).toBe(5); + expect([...quality.querySelectorAll("option")].map(option => option.textContent)).toEqual(["Auto quality", "Low quality", "Medium quality", "High quality", "Extra high quality"]); + expect([...screen.getByLabelText("Complexity").querySelectorAll("option")].map(option => option.textContent)).toEqual(["Default complexity", "Low complexity", "Medium complexity", "High complexity"]); + const formatOption = (name: string) => screen.getByLabelText("Format").querySelector(`option[value="${name}"]`) as HTMLOptionElement; + fireEvent.click(screen.getByRole("checkbox", { name: "Transparent" })); + expect(formatOption("gif").disabled).toBe(true); + expect(formatOption("svg").disabled).toBe(true); + expect(screen.getByText("Transparent background requires PNG or WebP output.")).toBeTruthy(); + fireEvent.change(screen.getByLabelText("Format"), { target: { value: "gif" } }); + await waitFor(() => expect(screen.getByLabelText("Format")).toHaveProperty("value", "png")); + 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(); + fireEvent.click(screen.getByRole("button", { name: "panda.png" })); + fireEvent.click(screen.getByRole("button", { name: "Close" })); + fireEvent.change(screen.getByLabelText("Quality"), { target: { value: "xhigh" } }); + fireEvent.change(screen.getByLabelText("Complexity"), { target: { value: "low" } }); + fireEvent.change(screen.getByLabelText("Format"), { target: { value: "gif" } }); + expect(screen.getByLabelText("Format")).toHaveProperty("value", "gif"); + expect(screen.getByRole("checkbox", { name: "Transparent" }).hasAttribute("data-disabled")).toBe(true); + expect(screen.getByText("Transparent background is available with PNG or WebP output.")).toBeTruthy(); + expect(document.getElementById("format-constraint")?.closest(".composer-hint")).toBeTruthy(); + fireEvent.change(screen.getByLabelText("Frames"), { target: { value: "4" } }); + fireEvent.change(screen.getByLabelText("Image variants"), { target: { value: "2" } }); + fireEvent.change(screen.getByLabelText("Generation source"), { target: { value: "queue" } }); + await waitFor(() => expect(screen.queryByLabelText("Format")).toBeNull()); + expect(screen.getByRole("checkbox", { name: "Transparent" }).hasAttribute("data-disabled")).toBe(false); + fireEvent.change(screen.getByLabelText("Generation source"), { target: { value: "api" } }); + await waitFor(() => expect(screen.getByLabelText("Format")).toHaveProperty("value", "gif")); + fireEvent.change(screen.getByLabelText("Image model"), { target: { value: "gpt-image-1-mini" } }); + await waitFor(() => expect(screen.getByLabelText("Quality")).toHaveProperty("value", "")); + expect(screen.queryByLabelText("Complexity")).toBeNull(); + expect(screen.queryByLabelText("Frames")).toBeNull(); + expect(screen.getByLabelText("Format")).toHaveProperty("value", "png"); + fireEvent.change(screen.getByLabelText("Quality"), { target: { value: "medium" } }); + fireEvent.change(screen.getByLabelText("Format"), { target: { value: "webp" } }); + fireEvent.change(screen.getByLabelText("Image prompt"), { target: { value: "A painted panda" } }); + fireEvent.click(screen.getByRole("button", { name: "Generate image" })); + await waitFor(() => expect(requestImageAction).toHaveBeenCalledTimes(1)); + const payload = vi.mocked(requestImageAction).mock.calls[0][0]; + expect(payload).toMatchObject({ source: "api", quality: "medium", outputFormat: "webp", count: 2 }); + expect(payload).not.toHaveProperty("complexity"); + expect(payload).not.toHaveProperty("frameCount"); + expect(payload).not.toHaveProperty("frameDurationMs"); + fireEvent.change(screen.getByLabelText("Generation source"), { target: { value: "queue" } }); + await waitFor(() => expect(screen.queryByLabelText("Quality")).toBeNull()); + expect(screen.queryByLabelText("Format")).toBeNull(); +}); + +it("shows stored format settings and restores them from the detail view", async () => { + vi.stubGlobal("fetch", vi.fn(async () => ({ + ok: true, + json: async () => ({ + ...structuredClone(state), + models: capableModels, + jobs: [{ ...state.jobs[0], source: "api", model: "gpt-image-2.6-sunburst", outputFormat: "webp", quality: "high", complexity: "low" }], + }), + }))); + render(); + fireEvent.click(await screen.findByRole("button", { name: "Open IMG-first" })); + const metadata = [...document.querySelectorAll(".detail-metadata")].map(node => node.textContent).join(" "); + expect(metadata).toMatch(/WebP/); + expect(metadata).toMatch(/High quality/); + expect(metadata).toMatch(/Low complexity/); + fireEvent.click(screen.getByRole("button", { name: "More" })); + fireEvent.click(await screen.findByRole("menuitem", { name: "Reuse prompt" })); + await waitFor(() => expect(screen.getByLabelText("Format")).toHaveProperty("value", "webp")); + expect(screen.getByLabelText("Quality")).toHaveProperty("value", "high"); + expect(screen.getByLabelText("Complexity")).toHaveProperty("value", "low"); +}); + it("links the processing panel and saves a source pause independently of provider access", async () => { const source = { paused: false, workers: 2, policy: { limit: 0, windowMinutes: 60 }, online: true, running: 0 }; const initialState = { diff --git a/vitest.config.ts b/vitest.config.ts index fa39588..9285f0f 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -4,6 +4,7 @@ export default defineConfig({ resolve: { alias: { "@": fileURLToPath(new URL("./src", import.meta.url)), "./.open-next/worker.js": fileURLToPath(new URL("./tests/generated-worker-stub.ts", import.meta.url)), + "./.open-next/cloudflare/init.js": fileURLToPath(new URL("./tests/generated-init-stub.ts", import.meta.url)), } }, test: { maxWorkers: 4, diff --git a/wrangler.jsonc b/wrangler.jsonc index 04853c6..528a62d 100644 --- a/wrangler.jsonc +++ b/wrangler.jsonc @@ -4,6 +4,9 @@ "main": "cloudflare-worker.ts", "triggers": { "crons": ["0 * * * *"] }, "compatibility_date": "2026-11-14", + "workers_dev": false, + "preview_urls": false, + "observability": { "enabled": true, "logs": { "enabled": true, "invocation_logs": false } }, "compatibility_flags": [ "nodejs_compat" ], @@ -27,6 +30,16 @@ "bucket_name": "image-queue" } ], + "queues": { + "producers": [{ "binding": "GENERATION_QUEUE", "queue": "image-queue-generation" }], + "consumers": [{ + "queue": "image-queue-generation", + "max_batch_size": 1, + "max_batch_timeout": 0, + "max_retries": 0, + "max_concurrency": 4 + }] + }, "images": { "binding": "IMAGES" }