[PR #1027] [MERGED] fix(image-gen): harden OpenRouter image response parsing #4893

Closed
opened 2026-10-22 04:11:30 +07:00 by bsakaguchi · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/Pasta-Devs/Marinara-Engine/pull/1027
Author: @etherious1804
Created: 5/20/2026
Status: ✅ Merged
Merged: 5/20/2026
Merged by: @cha1latte

Base: staging ← Head: fix/openrouter-image-response-parsing


📝 Commits (1)

  • c787fc9 fix(image-gen): harden OpenRouter image response parsing

📊 Changes

1 file changed (+47 additions, -3 deletions)

View changed files

📝 packages/server/src/services/image/image-generation.ts (+47 -3)

📄 Description

Linked issue

Closes #1026

Why this change

OpenRouter's image-generation endpoint surfaces several response shapes depending on the underlying provider and the model's `modalities` config, and Marinara's current parser only handles the chat-completions JSON envelope cleanly. Two real failure modes today:

  1. Raw image bytes. Some OpenRouter image models (raw provider passthrough) return PNG / JPEG / GIF / WEBP bytes directly with an `image/*` content-type instead of a JSON envelope. The current `await resp.json()` throws `SyntaxError: Unexpected token ... is not valid JSON` and the user sees a JSON-parse crash instead of an image.
  2. JSON envelope with no image (model refusal, text-only response, etc.). The existing "no image" error message is just `No image data in OpenRouter response: <first 200 chars>` with no `finish_reason`, no shape hint, and no log line. There is no way to tell from this error whether the issue is a wrong API key, a model that doesn't support image output, a prompt that was refused, or a misconfigured `modalities` setting.
  3. Gzipped responses. OpenRouter sometimes returns `Content-Encoding: gzip` from upstream providers. The shared `imageFetch` helper does not set `decodeCompressedResponse: true`, so those buffers fail the JSON-parse path even when the underlying payload is a valid envelope.

This PR is the split-out half of #970 that the reviewer asked to move into its own change.

What changed

`packages/server/src/services/image/image-generation.ts`:

  • `generateOpenRouter`: read the response into a `Buffer` first, then sniff the content-type and magic bytes. If it looks like an image, base64-encode it and return directly via the existing `detectImageMimeType` / `imageExtensionFromMimeType` helpers.
  • Otherwise parse as JSON. If the parse fails, throw an error that includes the content-type and the first 80 bytes (hex) so the user can immediately tell what shape they actually received.
  • If the JSON has a top-level `error` field, surface it verbatim (truncated to 400 chars).
  • If JSON parses but no image URL is extractable, log the full message shape via `logger.warn` (model, `finish_reason`, first 800 chars of the message body) and throw an error that includes `finish_reason` and the message-object keys.
  • Enable `decodeCompressedResponse: true` on the shared `imageFetch` helper so gzipped responses are decoded transparently. The other image-related callers already work on decoded buffers, so this is a no-op for them.
  • Add the missing `import { logger }` referenced by the new `logger.warn` call.

No behavior change for OpenRouter responses that were already producing images successfully — the new path only branches on the response shape.

Validation

  • `pnpm check` passes locally
  • Container (Docker / Podman) built and ran without issue
  • Ran the app, clicked through the changes manually
  • Checked edge cases (light + dark mode, mobile viewport, empty states, error paths)
  • Above manual verification completed (describe below)
  • Read and followed `CONTRIBUTING.md`

Only ticking `pnpm check` because it is a deterministic command result that this agent ran on the final commit. The manual-verification boxes are intentionally left unchecked per the AI-Generated PR guidance — those are a to-do list for the human contributor and reviewer, not evidence that work is done. The work I actually exercised is described below as prose.

What I ran locally (prose, for reviewer reference)

  • `pnpm check` green on the final commit (`tsc -b` + ESLint across shared/server/client; server tsc-noemit; client build).
  • Triggered the raw-image-bytes path by pointing the OpenRouter connection at a model that returns a direct PNG response. Without the patch the call crashed with a JSON SyntaxError; with the patch the image was returned and displayed in chat.
  • Triggered the "JSON envelope with no extractable image" path by sending a refusal-likely prompt; the error message now reports `finish_reason` and the message-object keys, and a `logger.warn` line is written with the full shape.

Manual verification a reviewer should still do (these are paths I could not easily fixture locally):

  • Verify a gzipped OpenRouter response still parses correctly end-to-end — I enabled `decodeCompressedResponse: true` but did not have a gzipped fixture handy. Worth running one OpenRouter call through a debug proxy that forces `Content-Encoding: gzip`.
  • Sanity-check that no other image-flow caller (Stability AI, Pollinations, custom OpenAI-compatible, NovelAI, ComfyUI, AUTOMATIC1111, etc.) regresses with `decodeCompressedResponse: true` on the shared helper. Those callers already work on decoded buffers, but the flag is shared, so worth a smoke test in CI.

Docs and release impact

  • No docs changes needed
  • Updated docs (README / CONTRIBUTING / android/README / CHANGELOG) as needed
  • Version/release files updated (only if this PR includes a version bump)

Purely a server-side parser hardening. No docs or release-metadata changes.

UI evidence (if applicable)

No UI surface touched.

Note on relationship to #970

#970 (Draw Things) was originally a single combined PR with these OpenRouter parsing improvements bundled in. Per the reviewer's call to split unrelated work, those OpenRouter changes have been pulled out into this PR; #970 now only contains Draw Things support.

🤖 Generated with Claude Code


🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.

## 📋 Pull Request Information **Original PR:** https://github.com/Pasta-Devs/Marinara-Engine/pull/1027 **Author:** [@etherious1804](https://github.com/etherious1804) **Created:** 5/20/2026 **Status:** ✅ Merged **Merged:** 5/20/2026 **Merged by:** [@cha1latte](https://github.com/cha1latte) **Base:** `staging` ← **Head:** `fix/openrouter-image-response-parsing` --- ### 📝 Commits (1) - [`c787fc9`](https://github.com/Pasta-Devs/Marinara-Engine/commit/c787fc904a39fcf3636e9e6e241e3545a0367f66) fix(image-gen): harden OpenRouter image response parsing ### 📊 Changes **1 file changed** (+47 additions, -3 deletions) <details> <summary>View changed files</summary> 📝 `packages/server/src/services/image/image-generation.ts` (+47 -3) </details> ### 📄 Description ## Linked issue Closes #1026 ## Why this change OpenRouter's image-generation endpoint surfaces several response shapes depending on the underlying provider and the model's \`modalities\` config, and Marinara's current parser only handles the chat-completions JSON envelope cleanly. Two real failure modes today: 1. **Raw image bytes.** Some OpenRouter image models (raw provider passthrough) return PNG / JPEG / GIF / WEBP bytes directly with an \`image/*\` content-type instead of a JSON envelope. The current \`await resp.json()\` throws \`SyntaxError: Unexpected token ... is not valid JSON\` and the user sees a JSON-parse crash instead of an image. 2. **JSON envelope with no image (model refusal, text-only response, etc.).** The existing \"no image\" error message is just \`No image data in OpenRouter response: <first 200 chars>\` with no \`finish_reason\`, no shape hint, and no log line. There is no way to tell from this error whether the issue is a wrong API key, a model that doesn't support image output, a prompt that was refused, or a misconfigured \`modalities\` setting. 3. **Gzipped responses.** OpenRouter sometimes returns \`Content-Encoding: gzip\` from upstream providers. The shared \`imageFetch\` helper does not set \`decodeCompressedResponse: true\`, so those buffers fail the JSON-parse path even when the underlying payload is a valid envelope. This PR is the split-out half of #970 that the reviewer asked to move into its own change. ## What changed \`packages/server/src/services/image/image-generation.ts\`: - \`generateOpenRouter\`: read the response into a \`Buffer\` first, then sniff the content-type and magic bytes. If it looks like an image, base64-encode it and return directly via the existing \`detectImageMimeType\` / \`imageExtensionFromMimeType\` helpers. - Otherwise parse as JSON. If the parse fails, throw an error that includes the content-type and the first 80 bytes (hex) so the user can immediately tell what shape they actually received. - If the JSON has a top-level \`error\` field, surface it verbatim (truncated to 400 chars). - If JSON parses but no image URL is extractable, log the full message shape via \`logger.warn\` (model, \`finish_reason\`, first 800 chars of the message body) and throw an error that includes \`finish_reason\` and the message-object keys. - Enable \`decodeCompressedResponse: true\` on the shared \`imageFetch\` helper so gzipped responses are decoded transparently. The other image-related callers already work on decoded buffers, so this is a no-op for them. - Add the missing \`import { logger }\` referenced by the new \`logger.warn\` call. No behavior change for OpenRouter responses that were already producing images successfully — the new path only branches on the response shape. ## Validation - [x] \`pnpm check\` passes locally - [ ] Container (Docker / Podman) built and ran without issue - [ ] Ran the app, clicked through the changes manually - [ ] Checked edge cases (light + dark mode, mobile viewport, empty states, error paths) - [ ] Above manual verification completed (describe below) - [ ] Read and followed \`CONTRIBUTING.md\` > Only ticking \`pnpm check\` because it is a deterministic command result that this agent ran on the final commit. The manual-verification boxes are intentionally left unchecked per the AI-Generated PR guidance — those are a to-do list for the human contributor and reviewer, not evidence that work is done. The work I actually exercised is described below as prose. ### What I ran locally (prose, for reviewer reference) - \`pnpm check\` green on the final commit (\`tsc -b\` + ESLint across shared/server/client; server tsc-noemit; client build). - Triggered the raw-image-bytes path by pointing the OpenRouter connection at a model that returns a direct PNG response. Without the patch the call crashed with a JSON SyntaxError; with the patch the image was returned and displayed in chat. - Triggered the \"JSON envelope with no extractable image\" path by sending a refusal-likely prompt; the error message now reports \`finish_reason\` and the message-object keys, and a \`logger.warn\` line is written with the full shape. **Manual verification a reviewer should still do** (these are paths I could not easily fixture locally): - Verify a gzipped OpenRouter response still parses correctly end-to-end — I enabled \`decodeCompressedResponse: true\` but did not have a gzipped fixture handy. Worth running one OpenRouter call through a debug proxy that forces \`Content-Encoding: gzip\`. - Sanity-check that no other image-flow caller (Stability AI, Pollinations, custom OpenAI-compatible, NovelAI, ComfyUI, AUTOMATIC1111, etc.) regresses with \`decodeCompressedResponse: true\` on the shared helper. Those callers already work on decoded buffers, but the flag is shared, so worth a smoke test in CI. ## Docs and release impact - [ ] No docs changes needed - [ ] Updated docs (README / CONTRIBUTING / android/README / CHANGELOG) as needed - [ ] Version/release files updated (only if this PR includes a version bump) Purely a server-side parser hardening. No docs or release-metadata changes. ## UI evidence (if applicable) No UI surface touched. ## Note on relationship to #970 #970 (Draw Things) was originally a single combined PR with these OpenRouter parsing improvements bundled in. Per the reviewer's call to split unrelated work, those OpenRouter changes have been pulled out into this PR; #970 now only contains Draw Things support. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
bsakaguchi 2026-10-22 04:11:30 +07:00
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
Pasta-Devs/Marinara-Engine#4893
No description provided.