GeezerVison is showing github.com — feat(google): enable Gemini inline image output by tizerluo · Pull Request #355 · lidge-jun/opencodex
Conversation
tizerluo
commented
Jul 23, 2026
•
edited by coderabbitai
Bot
Loading
Uh oh!
There was an error while loading. Please reload this page.
Summary
- Enable Gemini image generation through Cloud Code Assist (Antigravity) with two complementary paths:
/v1/images/generations fallback (primary): When no OpenAI upstream is configured, Codex's built-in image_gen skill now falls back to CCA's dedicated image model (gemini-3.1-flash-image). This is the standard Codex workflow — the model calls the tool, codex-rs POSTs to the Images API, and the proxy serves it via CCA.
- Inline
inlineData parsing: For users who select gemini-3.1-flash-image directly as their chat model, inlineData parts in the response are materialized to ~/.opencodex/artifacts/ and emitted as markdown.
- Add
responseModalities: ["TEXT", "IMAGE"] to generationConfig for non-thinking Gemini models.
- Add
gemini-3.1-flash-image to the CCA model catalog (from FetchAvailableModels.imageGenerationModelIds).
- Automatically omit
responseModalities when a thinking level is active (thinking models reject IMAGE modality).
How it works (Codex workflow)
User: "draw me a cat"
→ Chat model calls image_gen.imagegen tool
→ codex-rs POSTs /v1/images/generations {prompt: "a cat", model: "gpt-image-1"}
→ OpenCodex: no OpenAI upstream? → CCA fallback
→ Calls gemini-3.1-flash-image via v1internal:generateContent
→ Returns {created, data: [{b64_json: "..."}]}
→ codex-rs renders the image
No model switching required. Works with just a CCA login (ocx login google-antigravity).
Verification
bun run typecheck — clean
bun test tests/images/gemini-inline.test.ts — 8/8 pass
bun test tests/google-adapter.test.ts tests/google-vertex-stream.test.ts — 17/17 pass
bun run privacy:scan — passed
- E2E (Images API):
POST /v1/images/generations {"prompt":"A cute green frog on a lily pad"} → 2MB JPEG returned in standard {created, data:[{b64_json}]} format
- E2E (inline):
POST /v1/chat/completions with model gemini-3.1-flash-image →  markdown with materialized 515KB JPEG
Note: bun run test (full suite) has 24 pre-existing failures on dev in catalog/discovery tests, unrelated to this change.
Checklist
- Scope stays focused and avoids unrelated cleanup.
- Docs or release notes were updated when needed.
- Security-sensitive changes were reviewed for secrets, auth, and unsafe defaults.
Summary by CodeRabbit
- New Features
- Added support for Gemini image-capable models, including the new
gemini-3.1-flash-image model.
- Inline images are saved as local artifacts and displayed through Markdown image links.
- Added Google Antigravity fallback support for image generation requests.
- Bug Fixes
- Added validation and size limits for generated image data.
- Improved Markdown path escaping for image links.
- Documentation
- Documented native Gemini image generation, artifact handling, and image size limits.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
This comment was marked as outdated.
This comment was marked as duplicate.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
This comment was marked as duplicate.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
This comment was marked as duplicate.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
This comment was marked as duplicate.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
This comment was marked as resolved.
This comment was marked as resolved.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
This comment was marked as outdated.
This comment was marked as outdated.
This comment was marked as outdated.
This comment was marked as outdated.
This comment was marked as outdated.
This comment was marked as outdated.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
This comment was marked as outdated.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
This comment was marked as outdated.
This comment was marked as outdated.
- Emit file: URI instead of ~/ for artifact paths (resolvable + privacy)
- Remove imagen-4.0-generate-001 from IMAGE_CAPABLE_MODELS (wrong API)
- Try CCA fallback when OpenAI candidate exists but auth fails
- Return 502 on OAuth refresh failure (not misleading 400 'none configured')
- Reuse ANTIGRAVITY_REQUEST_UA instead of hard-coded UA
- Wrap fetch+body-read in try/finally for linkedSignal.cleanup()
- Catch body-read timeout/abort → 504/499
- Preserve CCA 4xx statuses instead of collapsing to 502
- Add UUID collision retry on exclusive-create (flag: wx)
- pruneOldArtifacts() caps artifacts/ to 200 files, deleting oldest by mtime
- Runs after each successful write in materializeInlineImage + downloadImageToArtifact
- Best-effort: errors caught and warned, never fails the write
- Use pathToFileURL for standard file: URIs (Windows + RFC8089 compliant)
- Validate CCA envelope: Array.isArray(parts) + per-part object check
- Map OAuthLoginRequiredError → 401 (login required), not 502 (refresh failed)
- Fix body-read timeout: check linkedSignal.signal.aborted before parent signal
- Remove Imagen from adapters.md docs
- Document CCA fallback also fires after OpenAI auth failure (+ locales)
- Document artifacts emitted as file: URIs
R4 findings fixed:
1. Body-read client cancellation now reports 499 (not 504):
signalWithTimeout propagates parent abort into the linked signal,
so both are aborted on client cancel. Check parent signal first
in the body-read catch block.
2. OAuth preflight now runs inside the image deadline:
Move signalWithTimeout creation before getValidAccessToken so token
refresh and project discovery are bounded by timeoutMs and can be
cancelled by client abort. Add 499/504 checks after OAuth preflight.
4. PNG magic bytes: validate complete 8-byte signature
(89 50 4E 47 0D 0A 1A 0A) instead of just the first 4 bytes.
5. Inline payload size pre-check: reject oversized base64 strings
in the adapter before normalization copies them, preventing large
allocations before the decoded-size guard runs.
Finding 3 (file: URL for remote clients) is a design discussion,
not a code bug — addressed in PR review response.
R5 findings fixed:
2. OAuth preflight signal propagation: wrap getValidAccessToken in
abortableRace against linkedSignal.signal so client abort / timeout
during token refresh surfaces as 499/504 instead of hanging.
5. HTTP-layer payload limit: add Content-Length pre-check in
parseResponse before response.json() buffers the body.
Codex P2-1: Reject malformed CCA inlineData.data (non-string types
were forwarded as fake b64_json).
Codex P2-2: Fix duplicate 'neither' bullet in JA/KO/RU/ZH locale docs.
Codex P2-3: Exempt gemini-*-image chat models from routed catalog
media-generation filter (shouldExposeRoutedModel).
Codex P2-4: Map CCA safety blocks (finishReason SAFETY/BLOCKLIST/etc)
to non-retryable 400 instead of retried 502.
Finding 3 (file: URL local-only) addressed in review response as a
design positioning decision, not a code bug.
… takeover
Address remaining Wibias blockers: admission bearer allows CCA/keyed without
forwarding the secret, CCA n=1 + RECITATION + validated base64, explicit image
model allowlists, authenticated opaque artifact HTTP route, and size caps with
focused regressions.
Maintainer takeover
Rebased onto latest dev and applied the remaining Wibias R5 blockers plus CodeRabbit/Codex hardening:
- Admission bearer authenticates the caller for CCA/keyed image paths without being forwarded upstream
- CCA rejects
n !== 1, treats RECITATION as blocking, and validates base64 + image magic before b64_json
- Explicit Gemini image-capable allowlists (catalog + Google adapter) instead of broad
/gemini/ && /image/ matching
- Markdown emits authenticated opaque
/v1/opencodex/artifacts/<id> URLs (no file: / host paths)
- Pre-parse size caps for non-stream bodies and SSE frames
- Focused regressions for the above
Waiting on fresh CI + bot review before squash-merge. Author @tizerluo will be credited on merge.
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
💡 Codex Review
|
buffer += decoder.decode(value, { stream: true }); |
Cap SSE frames before waiting for a newline
When a compromised or stalled Google upstream sends one very large data: frame without a newline, this append grows buffer without limit because MAX_SSE_FRAME_BYTES is checked only later in handleDataLine(), after split("\n") produces a complete line. Fresh evidence after the earlier buffering finding is that the new frame-size check remains unreachable for an unterminated frame; enforce the cap while accumulating bytes/chars and add a no-newline regression.
AGENTS.md reference: AGENTS.md:L93-L95
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
|
|
if (!ARTIFACT_ID_RE.test(name)) {
|
|
|
throw new Error("artifact filename is not a valid opaque id");
|
|
|
}
|
|
|
return `${ARTIFACT_HTTP_PREFIX}/${name}`;
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Include the proxy origin in artifact links
When Codex CLI/App receives this Markdown outside a document served by the proxy, the root-relative /v1/opencodex/artifacts/... URL resolves against the client's own UI/current context rather than the OpenCodex server, so the newly added HTTP route still cannot render the generated image, especially for remote or containerized proxies. Fresh evidence beyond the earlier remote-client comment is that the replacement now emits only a path with no scheme or authority; construct a client-resolvable URL using the proxy's externally reachable origin.
Useful? React with 👍 / 👎.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Comment on lines
+83
to
+87
|
|
`gemini-2.0-flash-preview-image-generation`, or any model id matching both `gemini` and `image`),
|
|
|
the adapter sends `responseModalities: ["TEXT", "IMAGE"]`. Returned `inlineData` parts are
|
|
|
materialized to the `artifacts/` subdirectory of the configured OpenCodex config directory and
|
|
|
surfaced to the client as a markdown image link referencing a `file:` URI
|
|
|
(``). Each image is capped at 50 MB and each response at 100 MB of decoded
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Synchronize inline-image docs with the runtime
The documented behavior no longer matches this change: the adapter now uses an exact three-model allowlist rather than accepting any ID containing gemini and image, and emitted links now target /v1/opencodex/artifacts/... rather than a file: URI. Users following this reference may select unsupported models and will troubleshoot the wrong artifact mechanism; update the model list and link description to match the implementation.
AGENTS.md reference: AGENTS.md:L96-L97
Useful? React with 👍 / 👎.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
|
|
export function readArtifactBytes(id: string): { bytes: Buffer; contentType: string } | null {
|
|
|
const path = resolveArtifactPath(id);
|
|
|
if (!path) return null;
|
|
|
const bytes = readFileSync(path);
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Stream artifact files instead of synchronously copying them
When a client retrieves an artifact near the supported 50 MiB limit, readFileSync() blocks Bun's JavaScript event loop while loading the entire file, and the route then copies that buffer again with new Uint8Array(artifact.bytes). A few concurrent image views can therefore retain roughly twice the artifact size per request and stall unrelated proxy traffic; serve the file through an asynchronous or streaming body such as Bun.file instead of materializing two in-memory copies.
Useful? React with 👍 / 👎.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
|
|
}
|
|
|
return formatErrorResponse(502, "upstream_error", "CCA image generation failed: OAuth token refresh failed");
|
|
|
}
|
|
|
const project = getOAuthCredentialProjectId("google-antigravity");
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Resolve the OAuth token and project from one account snapshot
When the active Google Antigravity account is switched while token refresh is in progress, getValidAccessToken() can return account A's token and this later lookup can reload account B's project ID. The request then combines credentials from different accounts, producing authorization failures or charging/selecting the wrong project when account A can access it; extend the account-scoped access snapshot to carry the matching project ID and use both values atomically.
AGENTS.md reference: AGENTS.md:L83-L89
Useful? React with 👍 / 👎.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Comment on lines
+593
to
+594
|
|
if (Number.isFinite(contentLength) && contentLength > MAX_RESPONSE_BYTES) {
|
|
|
return [{ type: "error", message: `google response too large (content-length ${contentLength} exceeds ${MAX_RESPONSE_BYTES} bytes)` }];
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Cancel oversized non-streaming responses on the header path
When Google declares a Content-Length above the cap, this early return leaves response.body uncancelled. A large or indefinitely streaming upstream body can therefore keep its fetch connection and buffers alive until garbage collection even though the client has already received an adapter error, allowing repeated oversized responses to exhaust upstream connection slots; explicitly cancel the body before returning and add a cancellation regression for this header-only rejection path.
AGENTS.md reference: AGENTS.md:L93-L95
Useful? React with 👍 / 👎.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Include gemini-3.1-flash-image in the OAuth preset migration assertion so
Cross-platform CI matches the Antigravity picker seed.
When Antigravity is logged in but has no Cloud Code Assist project id,
surface a project-discovery 400 instead of falling through to the generic
provider-not-configured message.
Cancel oversized non-stream bodies on the Content-Length path, cap SSE
accumulation before a newline, stream artifacts via Bun.file, and sync the
adapters reference docs with the explicit allowlist and opaque HTTP route.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Maintainer review @ 379cb3c9
Verdict: approve.
All Wibias R5 blockers are addressed on tip (rebased onto latest dev):
- Admission bearer allows CCA/keyed Images without forwarding the proxy secret
- CCA rejects
n !== 1
RECITATION is a non-retryable content filter
- Strict base64 + magic validation before CCA
b64_json
- Explicit Gemini image-capable allowlists (catalog + adapter); media-gen IDs stay filtered
- Authenticated opaque
/v1/opencodex/artifacts/<id> route (no file: / host paths)
- Pre-parse size caps for non-stream bodies + SSE accumulation/frames
Tip also includes focused regressions, docs sync, Bun.file artifact streaming, Content-Length cancel, and a clear CCA project-discovery error.
Security review
No medium/high/critical findings in the changed image/artifact/auth paths. Admission non-forwarding, artifact path containment, base64/magic validation, and allowlist gating look solid.
Process
- Cross-platform CI green on exact tip
- CodeRabbit completed; tip Codex P2s from the takeover batch addressed
- Remaining Codex notes (absolute artifact origin, OAuth snapshot atomicity) are non-blocking follow-ups
Ready to squash-merge with credit to @tizerluo.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Merged — thank you @tizerluo!
Huge thanks for this PR. Gemini inline image output is a meaningful capability for Codex users, and you carried it through a long review loop with a ton of care (CCA Images fallback, artifacts, catalog wiring, and many hardening passes). That work is genuinely appreciated.
Squash-merged to dev as 65e3fee1 with you credited as the commit author (plus Co-authored-by). The history will keep your name on this feature.
Welcome contribution — looking forward to more from you if you feel like it.
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Wibias
added a commit
that referenced
this pull request
Jul 27, 2026
Credit: @tizerluo for the original feature on #424.
Folds stacked #528 hardening and maintainer review/security follow-ups.
Reconciled with #355 artifact helpers on latest dev.
Closes #424
Closes #528
This was referenced Aug 2, 2026
This was referenced Aug 13, 2026
agentHits
pushed a commit
to agentHits/opencodex
that referenced
this pull request
Sep 17, 2026
…MERGE_AND_IMPROVE recorded
Uh oh!
There was an error while loading. Please reload this page.
Assignees
No one assigned
Milestone
No milestone
Development
Successfully merging this pull request may close these issues.
Uh oh!
There was an error while loading. Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
|