codex icon indicating copy to clipboard operation
codex copied to clipboard

Codex should not resend large base64 image tool outputs in subsequent context

Open wang1970 opened this issue 5 months ago • 29 comments

Summary

When a user submits an image to Codex, sending the image in the immediate request is expected. However, after that turn is processed, Codex appears to persist the full base64 image payload in conversation/tool history and resends it in later /v1/responses requests.

This causes unbounded context growth. In one observed case, a later request included multiple base64 image payloads in tool messages, producing an upstream Chat request of about 8.34 MB and about 5.7 million prompt tokens. Several OpenAI-compatible upstream providers then failed with 502/524 or HTTP 200 streams with no valid output.

Expected behavior

  • User-submitted images can be included in the current request.
  • After the image has been processed, Codex should not keep resending the full data:image/*;base64,... payload as ordinary conversation context.
  • Large image payloads should be replaced by a compact reference, digest, placeholder, or omitted from subsequent context unless explicitly required again.
  • Tool outputs containing large binary/base64 data should be aggressively pruned or summarized before being stored in long-lived conversation history.

Actual behavior observed

A later Codex request contained full base64 images inside historical tool messages. The largest tool message was a PNG data URL of about 7.68 million characters. Another JPEG data URL was about 426k characters.

The request shape after being converted to OpenAI Chat format was approximately:

messages = 77
roles:
  system    4
  user      9
  assistant 39
  tool      25
tools = 10
upstream_body ~= 8,343,294 bytes
prompt_tokens ~= 5,722,717
completion_tokens = 0

Largest historical message contents:

tool message[36] ~= 7,681,241 chars
  [{"type":"input_image","image_url":"data:image/png;base64,..."}]

tool message[23] ~= 426,314 chars
  [{"type":"input_image","image_url":"data:image/jpeg;base64,..."}]

This was not caused by the proxy duplicating request data. The actual upstream request body did not include the proxy diagnostic raw request field; the large payload was already present in the conversation messages submitted by Codex.

Failure mode

Observed downstream/upstream behavior included:

I-智枢云桥/gpt-5.5 -> 502 after about 203s
https://vsllm.com/gpt-5.5 -> HTTP 200 stream, first token after about 84.8s, then dropped
prompt_tokens = 5,722,717
completion_tokens = 0

Other OpenAI-compatible providers also failed for similar Codex /v1/responses requests with large historical context, usually as 502/524 or stream dropped/no valid output.

Why this matters

This makes long-running Codex sessions unstable after image/tool interactions:

  • Context can grow by several MB from a single image.
  • The same large image data can be resent repeatedly in later turns.
  • Prompt token counts can explode into millions.
  • Upstream providers may fail, timeout, or return incomplete streams.
  • The failure is confusing because the user is not submitting a new image in the later turn.

Suggested fix

Codex should treat large image/base64 payloads as ephemeral request data rather than durable text/tool history.

Possible mitigations:

  1. Strip or replace data:image/*;base64,... payloads from historical messages after the turn that consumes them.
  2. Store a compact placeholder such as [image omitted: sha256=..., bytes=...] in later context.
  3. Apply max-size limits to tool outputs before persisting them into conversation history.
  4. Avoid serializing image payloads into tool messages that are replayed to the model in subsequent requests.
  5. Add diagnostics/warnings when a request context contains very large base64 payloads.

The key point: submitting an image in the current user turn is fine, but resending the full base64 image in all later turns should be avoided.

wang1970 avatar Jun 15 '26 13:06 wang1970

Potential duplicates detected. Please review them and close your issue if it is a duplicate.

  • #28150

Powered by Codex Action

github-actions[bot] avatar Jun 15 '26 13:06 github-actions[bot]

Thanks for the duplicate detection. I reviewed #28150. This issue is related, but I do not think it is an exact duplicate.

#28150 focuses mainly on Codex Desktop thread persistence/recovery problems: large rollout JSONL, screenshots/appshots/local_images poisoning compaction, Electron crash loops, and safe-resume/repair-thread behavior.

This issue focuses on a different downstream effect of the same underlying image/tool-output lifecycle problem: large historical image payloads are being replayed into subsequent model requests. In the observed case, a previous image/tool result was resent inside later /v1/responses context as data:image/*;base64,..., producing an actual upstream request of about 8.34 MB and about 5.7 million prompt tokens. That caused provider-side 502/524 failures or HTTP 200 streams with no valid output.

So the overlap is:

  • image/tool outputs should not be persisted/replayed indefinitely;
  • large image payloads should be stored out-of-line, summarized, or replaced with lightweight references.

The distinction is:

  • #28150: image history poisons Desktop thread persistence / compaction / recovery.
  • This issue: image history leaks into later model request context and causes prompt-token explosion / upstream API failures.

I think keeping this open is useful because it provides concrete evidence that the problem affects not only local session recovery, but also the actual request payload sent to the model in later turns.

wang1970 avatar Jun 15 '26 13:06 wang1970

I checked current main for the request-growth path described here. The issue still looks plausible from the current code, and the risky boundary seems to be long-lived history/replay of FunctionCallOutputContentItem::InputImage, not logging.

Relevant code paths I found:

  • codex-rs/core/src/tools/handlers/view_image.rs: ViewImageOutput::log_preview() correctly omits the data URL for logs, but to_response_item() returns FunctionCallOutputContentItem::InputImage { image_url: self.image_url.clone(), ... }. So the model-visible response item still carries the full data URL.
  • codex-rs/core/src/session/mod.rs: record_conversation_items() records the response items into history and persists the same items to the rollout before sending raw response items.
  • codex-rs/utils/output-truncation/src/lib.rs: truncate_function_output_items_with_policy() applies the byte/token budget to text items, but InputImage { image_url, detail } is pushed through unchanged. formatted_truncate_text_content_items_with_policy() also preserves images after text truncation.
  • codex-rs/core/src/context_manager/history.rs: for_prompt() only strips images when the target model does not support image input. For an image-capable target model, historical image content can remain model-visible.
  • codex-rs/core/src/session/turn.rs: replace_last_turn_images("Invalid image") exists, but it is only used as an error recovery path for CodexErr::InvalidImageRequest, not as normal post-turn history pruning.
  • codex-rs/core/src/session/mod.rs: rollout reconstruction can call prepare_response_items() only behind Feature::ResizeAllImages, and the comment explicitly says persisted rollouts are kept unchanged. That does not appear to provide an unconditional sanitizer for historical data:image/*;base64,... payloads.

So I think the minimal fix should be separate from log redaction and separate from current-turn image submission. The safer owner boundary is the durable-history / replay path: after an image has been consumed for the current turn, historical tool-output images should be replaced with a compact placeholder or digest before they can be persisted/replayed into later prompts. Current-turn user images can still be sent normally.

Suggested regression test shape:

  1. Build conversation history containing a FunctionCallOutput content item with InputImage { image_url: "data:image/png;base64,...large..." }.
  2. Submit a later text-only turn to an image-capable model.
  3. Assert the prompt/request items for that later turn do not contain data:image/ and instead contain a bounded placeholder/reference.
  4. Also assert text truncation remains unchanged, because the existing truncation helper already handles text separately.

This is high impact because a single historical image can bypass the existing output truncation budget and be resent repeatedly, which matches the multi-MB / million-token request shape reported above.

wgu9 avatar Jun 15 '26 15:06 wgu9

I published a diagnostics branch that should help quantify this class of image/tool-output replay without changing persisted history yet:

Compare: https://github.com/openai/codex/compare/main...100yenadmin:codex/resume-payload-diagnostics?expand=1 Commit: 0e980ef9588d6dfb3619f31b0a112c193660451a

I could not open the upstream PR directly because GitHub returned GraphQL: 100yenadmin does not have the correct permissions to execute CreatePullRequest, but the branch is pushed to 100yenadmin/codex.

Scope note: this is not the durable-history sanitizer proposed above. It intentionally does not mutate persisted rollout/history or strip model-visible image payloads. It only logs non-content resume payload diagnostics for cold/running thread/resume: turn/item counts, estimated item payload bytes, item class distribution, user-image/image-item counts, MCP/dynamic-tool output counts, command-output counts, and token-usage replay timing.

Why it is relevant here: the active Desktop lockups in #28867 now include small active threads, so image-heavy/full-history replay is a stress signal rather than a proven sole cause. These diagnostics should let maintainers correlate future stalls with whether the resume payload actually contains image/tool-output heavy history, and then decide whether the next guardrail belongs in resume transport, Desktop rendering, token-usage replay, or durable-history image redaction.

100yenadmin avatar Jun 18 '26 08:06 100yenadmin

@tibo-openai

100yenadmin avatar Jun 18 '26 08:06 100yenadmin

After first use, large image payloads should be replaced by digest-backed references in replay history.

Persist media type, byte count, hash, producer turn/tool id, and an optional retained blob pointer. Later context assembly can include a compact placeholder plus token/byte diagnostics, instead of resending base64 bodies that already served their turn.


Generated with ax.

Necmttn avatar Jun 21 '26 10:06 Necmttn

any update?

aweiu avatar Jul 01 '26 10:07 aweiu

Repro / confirmation: view_image → persistent base64 in session → later turns 400 context_length_exceeded

Environment

  • macOS
  • Codex Desktop 26.707.72221 (CLI 0.144.2)
  • Custom provider through local proxy (CC Switch 3.17.0):
    • client: wire_api = "responses", base http://127.0.0.1:15721/v1
    • model: gpt-5.6-sol, model_reasoning_effort = "xhigh"
  • Model catalog marks gpt-5.6-sol as context_window = 128000 / max_context_window = 128000

What happens

  1. Thread uses built-in view_image (and/or browser screenshots).
  2. Rollout JSONL stores full data:image/...;base64,... under image / tool-related items (input_image counts grow).
  3. Later turns (even when the user is not attaching a new image) send multi‑hundred‑KB to multi‑MB request bodies and fail with:
HTTP 400
Your input exceeds the context window of this model. Please adjust your input and try again.

User-facing (via local proxy) often becomes: local proxy failed while handling Codex endpoint /responses + the same cause string.

Measured (redacted)

Artifact Observation
Session JSONL 26–43 MB after image-heavy work
view_image / input_image present; e.g. input_image=26 with 135 data:image markers in one session
Largest single base64 chunk commonly ~400–660KB (chars), sometimes larger
Failing request body size (gateway) often ~0.95MB, also ~1.5MB → 400 context exceeded
Successful text-ish request ~100KB → 200
Compact does not reliably recover once history is image-bloated (consistent with other compact+image issues)

This matches the core claim of this issue: images are expected on the turn they are viewed, but full base64 tool/image payloads appear to remain in history and get re-sent, causing unbounded context growth and permanent thread death.

Cross-links

  • farion1231/cc-switch#4465 — responses-wire/local proxy may further mishandle image parts as text (token inflation); measurements also posted there
  • #30441, #32128, #23257, #29812 — same family (image history / compact duplication / rollout explosion)

Ask / expected behavior

  1. After an image has been consumed for a turn, subsequent requests should not resend full base64 by default (reference path / hash / short placeholder, or hard-drop old images).
  2. Auto-compact / /compact should strip or externalize inline images; otherwise compact itself 400s.
  3. UI error should mention image history size, not only generic context-window / proxy failure.

I can share additional redacted counters (image count vs body_bytes over time) if helpful. No secrets/payloads attached.

hertzhzzz avatar Jul 15 '26 10:07 hertzhzzz

Windows Desktop reproduction: resumed image-heavy history causes later text-only turns to fail with HTTP 403

I can reproduce the same underlying replay problem on Windows with Codex Desktop.

Observed behavior

  1. A project thread accumulated browser/tool image outputs stored as inline data:image/png;base64,... values.
  2. Opening/taking over/resuming that project thread causes the historical image payloads to be replayed into later requests.
  3. A later user message as short as continue then consistently fails with unexpected status 403 Forbidden.
  4. The same workspace directory succeeds in a fresh, ephemeral, text-only Codex invocation that is explicitly instructed not to read any files or call tools. This rules out the workspace files themselves as the startup trigger.

Sanitized local measurements

  • At least 12 historical tool/image outputs contained inline data:image/png;base64,... payloads.
  • Largest individual serialized payloads were approximately 3.51 MB, 3.41 MB, 3.28 MB, 2.36 MB, 2.25 MB, and 1.84 MB.
  • Those six records alone total about 16.6 MB, before other image records and history duplication.
  • The failing resumed/handoff requests inherited the image-heavy history even though the new user message was text-only.

Expected behavior

Historical tool-output images should not be replayed as raw data URLs on later text-only turns. They should be pruned, bounded, externalized, or replaced with a compact reference/placeholder before durable history is replayed. A poisoned image-heavy thread should also have a supported repair path rather than causing every subsequent short request to fail.

No raw images, prompts, paths, session IDs details are included here for privacy.

Cooper-X-Oak avatar Jul 28 '26 10:07 Cooper-X-Oak

Additional data point: this replay costs ~55 GB of upstream traffic in a single working day

The reports above focus on functional failures (context_length_exceeded, 403/502). The same replay path also has a large and easily quantified network cost, which I don't think has been measured yet.

Environment

  • macOS (Apple Silicon)
  • Codex desktop app, which bundles codex-cli 0.146.0-alpha.9.2 at ChatGPT.app/Contents/Resources/codex; standalone codex-cli 0.145.0 also installed
  • Numbers below come from per-process connection accounting on the host, counting only the process named codex (the Electron/app processes are accounted separately)
  • Workload: ordinary development with browser/screenshot tool use

One working day (2026-07-31), process codex

connections 3,486 (3,377 to chatgpt.com)
uploaded 54.63 GB
downloaded 1.56 GB

An upload/download ratio of roughly 35:1.

Per-request upload size

upload size requests total
30–50 MB 973 39.49 GB
10–30 MB 991 12.10 GB
50–100 MB 25 1.38 GB
> 100 MB 7 0.97 GB
1–10 MB 237 0.63 GB
< 1 MB 1,253 0.05 GB

Across the 2,212 requests above 1 MB: median 13.3 MB, max 211 MB.

Two observations pointing at replay rather than organic context growth

  1. Resumed sessions start the day already at full payload. The first requests of the working day (07:00) had a median upload of 38.2 MB with no ramp-up whatsoever. A session resumed from history immediately pays for everything accumulated on previous days.

  2. Cost is strictly per-turn, and images dominate the session. Scanning rollout JSONL files for inline data:image/*;base64, payloads:

session size inline images image bytes share
opened 07-26, still in use 07-31 2000 MB / 27,189 lines 1,938 1,883 MB 94%
opened same day 322 MB 245 257 MB 80%
opened same day 140 MB 88 89 MB 64%

The average retained image is ≈1 MB, which lines up with the 30–50 MB request bucket at roughly 30–40 retained images per request.

Overnight, with those same session files on disk but no prompts submitted, codex made 87 connections and uploaded 0.22 MB over 7 hours. So there is no background cost — it is entirely per-turn replay.

Code path

Consistent with the analysis @wgu9 posted earlier. In codex-rs/utils/output-truncation/src/lib.rs, truncate_function_output_items_with_policy():

  • InputText computes a cost, decrements remaining_budget, and falls back to truncate_text when over budget
  • InputAudio computes a cost via estimate_audio_token_count and checks it against the budget
  • InputImage is pushed with image_url.clone() unconditionally — no cost computed, no budget decremented, no truncation

formatted_truncate_text_content_items_with_policy() behaves the same way: images are filtered out of the text merge and then re-appended verbatim. Callers include codex-rs/core/src/context_manager/history.rs.

A practical consequence: tool_output_token_limit cannot bound this today, because images never participate in the truncation policy. That may be worth documenting even ahead of a fix, since it is a natural thing for users to reach for.

InputAudio in the same match arm is a ready-made template for whichever bound is chosen (budgeted retention, or keeping the last N images and replacing older ones with a placeholder as @Necmttn suggested).

Happy to re-measure with a patch applied if that would be useful.

suharvest avatar Aug 01 '26 00:08 suharvest

Additional macOS Desktop evidence: direct view_image tool outputs dominate session storage

I can confirm the same underlying issue on a current macOS Codex Desktop installation. In this case, the largest source of persistent image data is ordinary image-viewing tool output, not compaction alone.

Environment

  • Codex Desktop: 26.818.61809 (build 7019)
  • Codex CLI: 0.149.0
  • macOS 15.5 (24F74), Apple Silicon
  • Workload: image-heavy local media review using view_image, including contact sheets, QA images, and screenshots

Privacy-safe store-level measurements

A streaming scan was performed without printing or uploading prompts, image contents, project paths, credentials, or raw JSONL records.

  • Rollout JSONL files: 1,247
  • Total ~/.codex/sessions size: 16.076 GiB
  • Inline data:image/*;base64 payload occurrences: 14,683
  • Base64 image payload size: 11.307 GiB
  • Image payloads account for approximately 70.3% of the entire session store
  • Rollouts larger than 100 MiB: 36
  • Largest rollout: approximately 594 MiB
  • In that rollout, approximately 502 MiB consisted of Base64 image payloads

Breakdown of the 11.307 GiB of image payloads:

  • custom_tool_call_output: 9.073 GiB — 80.2%
  • other image-bearing records: 2.049 GiB — 18.1%
  • user/message images: 0.157 GiB — 1.4%
  • compacted records: 0.028 GiB — 0.2%

Representative persisted structure:

{
  "type": "response_item",
  "payload": {
    "type": "custom_tool_call_output",
    "output": [
      {
        "type": "input_image",
        "image_url": "data:image/png;base64,<redacted>",
        "detail": "original"
      }
    ]
  }
}

Repeatedly viewing the same local image creates another full inline payload. A clipboard screenshot of approximately 304 KB, for example, produced approximately 396 KiB of Base64 data in the rollout, consistent with Base64 expansion.

Why this is distinct and important

Existing reports correctly identify compaction and full-history forks as major amplification paths. This dataset shows that even without compaction being the dominant contributor, normal view_image usage can steadily grow the persistent store because full image bytes are written into ordinary tool-output records.

This makes image-heavy review workflows accumulate many gigabytes even when the original images already exist as local files.

Requested product behavior

  1. Store image bytes once in a content-addressed media/blob store.
  2. Persist only a stable reference, MIME type, byte size, and digest in rollout history.
  3. Deduplicate identical images across repeated views, compaction checkpoints, resume, and forks.
  4. After the consuming turn, replace model-history image bytes with a compact reference or placeholder unless the image is explicitly requested again.
  5. Preserve and expose the original local path when available, with “Open in Finder”, “Copy path”, and “Export” actions.
  6. Add per-thread and profile-wide media budgets, disk-pressure warnings, and safe admission limits.
  7. Provide a first-party storage manager and migration/vacuum path for existing image-heavy rollouts.

Related storage reports include #23257, #34337, and #40111. The current experimental cold-rollout compression path may reduce some physical storage, but compression alone does not address repeated tool-output persistence, content deduplication, active sessions, image discoverability, or safe garbage collection.

No raw rollout files are attached because they contain private screenshots, prompts, local paths, and project information.

bigbugneil avatar Aug 26 '26 11:08 bigbugneil

macOS confirmation: sharp post-tool latency cliff after active view_image history reached ~90 MB

I can add a current macOS Desktop reproduction where ordinary view_image tool outputs correlate with a severe per-model-step latency cliff on the official OpenAI backend.

Environment

  • macOS 26.6.1, Apple Silicon (arm64)
  • Codex Desktop 26.825.31414 (build 7287)
  • Desktop-bundled runtime: codex-cli 0.150.0-alpha.12.2
  • Model: gpt-5.6-sol
  • Reasoning effort: max
  • Fast mode was active; thread settings recorded service_tier: priority

The separately installed codex-cli 0.150.1 was not used by this Desktop task.

Privacy-safe rollout measurements

At the captured point:

  • Rollout JSONL size: 110.4 MB
  • Inline images retained in custom_tool_call_output: 31
  • Total serialized input_image.image_url characters: 109.3 MB
  • Image-bearing tool results: 10
  • Largest single view_image result: 19.2 MB across four images
  • Context compactions: 0
  • Model context window: 258,400 tokens

No prompts, image contents, local paths, credentials, raw rollout records, or task IDs are included here.

Latency transition

Before the active inline-image history reached approximately 72.6 MB, observed post-tool model-boundary delays were generally 16–48 seconds.

A later view_image result added 17.5 MB across four images, bringing the active retained image history to approximately 90.2 MB. The next model event arrived 474 seconds later.

After that point, repeated model-boundary gaps were:

217s, 206s, 207s, 210s, 211s, 221s

Another four-image view_image result added 19.2 MB, bringing active retained image history to approximately 109.3 MB. The next observed gaps were 276s and 269s.

The latency cliff began at approximately 158,227 / 258,400 input tokens, well before the nominal context limit. The 474-second gap followed a request reporting approximately 99% cached input; most later long gaps also reported roughly 93.6–99.3% cached input. A prompt-cache miss is therefore not required for the slowdown.

In the captured interval, local tool calls themselves completed in at most 15 seconds. The multi-minute gaps occurred after tool output and token_count were persisted, before the next reasoning/tool/final-response event. Desktop logs showed no approval wait, rate-limit event, timeout, or stream error for those gaps.

Historical controls on the same machine/account

  • A prior gpt-5.6-sol + max session using bundled CLI 0.150.0-alpha.8 reached 231,409 input tokens, compacted six times, and had a maximum comparable post-tool boundary gap of 16s above 150k input tokens.
  • Older image-heavy sessions retained 53–189 MB of inline images over their full append-only history, but compaction kept the maximum active image payload between checkpoints to approximately 23–37 MB. None showed a 180s+ comparable boundary gap above 150k input tokens.

This does not prove the exact request body resent to the service; request-level telemetry would be needed for that. It does show a strong correlation between un-compacted inline view_image payload growth and a sudden, persistent latency increase that ordinary token accounting did not predict.

Suggested diagnostics/fix

  • Include InputImage byte cost in history truncation and compaction thresholds.
  • Externalize or content-address view_image bytes and retain lightweight references instead of replayable data URLs.
  • Deduplicate repeated local-image views.
  • Expose privacy-safe per-request payload bytes plus dispatch/upload/preprocessing/first-event timing.
  • Add a fail-soft warning or automatic pruning path before active inline-image history becomes large enough to poison subsequent turns.

A separate UI symptom occurred in the same period: the Desktop log emitted 1,222 ResizeObserver loop completed with undelivered notifications errors in roughly one hour. That may explain additional renderer sluggishness and appears related to #33996, but it does not explain the multi-minute absence of new rollout events by itself.

HyperHe-dev avatar Aug 28 '26 12:08 HyperHe-dev

Updated for v0.11.2 (2026-11-15). I'm the author of Context Attachment Manager, a local, MIT-licensed plugin built after I ran into repeated reconnects with roughly 44 MB of accumulated image history.

For recognized image blocks on supported Codex desktop routes, it can leave earlier images out of the next outgoing request while keeping numbered references. The model can retrieve an original image through MCP when needed. Auto-select, pinning, and manual selection are available; original conversation records and image files remain read-only.

In the current release this is on by default: earlier images go out as placeholders without any selecting, and the model can still fetch an original by its ID after the chat is compacted. A placeholder is written once and then stays the same, so the earlier chat is still read from the prompt cache (how it is designed).

This may help with the repeated image payload described here, but it does not fix arbitrary base64 embedded in ordinary text, change a provider's conversion behavior, or establish that all reconnects share this cause. Request bytes and billed tokens are different measurements.

The old default-endpoint-only limitation in my original reply is outdated: v0.9.0 preserves each route's configured upstream and supports compatible custom endpoints. They must support the client's native API format, images, and tool calls; there is no protocol conversion. Live third-party gateway model calls have not been tested by me.

Installation and current scope · v0.9.0 release · v0.11.2 release

chipfighter avatar Sep 28 '26 14:09 chipfighter

Another affected macOS user here. This is particularly disruptive during multi-round image generation: old image payloads accumulate, reconnect attempts reach 5/5, and HTTP/SSE fallback is followed by repeated large image uploads that greatly reduce conversation efficiency.

I am also affected on macOS while iterating on image generation across multiple turns. After reconnect attempts reach 5/5, the transport falls back to HTTP/SSE. Continuing the same conversation then causes repeated large image uploads, heavy bandwidth use, and substantial delays between turns. This severely affects Codex conversation efficiency and makes iterative design work difficult, including ordinary follow-up messages after image generation.

Please correlate this with #38846 (WebSocket close code 1009 / message too big), #24550 (large inline-image history causing WebSocket fallback), and #23665 (recovery from HTTP fallback). A 1009 close and the subsequent HTTP/SSE fallback are different stages of the failure: an oversized WebSocket message can trigger the disconnect, and fallback can then expose the repeated full-history upload cost. I have not captured the close code from my own session, so I am reporting the retry/fallback and bandwidth symptoms rather than claiming a confirmed 1009 reproduction.

Please treat historical-image byte size as a separate constraint from model token usage. Stable file references or bounded image retention would prevent small follow-up turns from repeatedly transferring large historical payloads. Please also provide a recovery action that preserves the text conversation, since starting over repeatedly interrupts design work.

xiao-do-do avatar Oct 02 '26 09:10 xiao-do-do

Adding feedback about the repeated historical-image uploads described in this issue and #43015. Old images reportedly get retransmitted on later requests, including text-only turns that do not need those images. The resulting bandwidth usage and waiting time make extended conversations difficult to use.

Could maintainers please confirm the current status and the responsible team? If a fix has shipped, please identify the versions that include it. If it remains unresolved, please provide an official workaround and a supported way to remove historical images from an existing conversation while preserving its useful text context.

Please also consider bounding aggregate image/request bytes and replacing unnecessary historical image payloads with references, so small follow-up requests do not repeatedly pay the full upload cost.

This comment conveys user feedback; it is not a new locally measured reproduction. No private images or session logs are attached.

lyouroboros109 avatar Oct 12 '26 02:10 lyouroboros109

Additional Windows Desktop data point: retained screenshot history and pre-header delay

Environment: Codex Desktop OpenAI.Codex_26.1013.4894.0, bundled codex-cli 0.163.0-alpha.10.2, Windows x64, ChatGPT authentication, gpt-6-luna / Max.

In one long-running Blender MCP session, nine consecutive requests between 2026-10-17 23:09 and 23:56 China Standard Time used responses_http. The logged request body sizes ranged from 27,520,969 to 27,812,863 bytes before compression, and 18,406,444 to 18,598,692 bytes after compression. The rollout already contained 33 inline PNG input_image blocks at the first request (32 distinct hashes; one exact duplicate).

There was a strong body-growth correlation when new screenshots were added later in the same session:

  • At 00:22:40 on Oct 18, the next prepared body grew by about 7.18 MB; three newly recorded screenshot data URIs totalled about 7.17 MB.
  • At 00:36:54, the body grew by about 2.110 MB; one preceding screenshot data URI was about 2.107 MB.
  • At 00:50:49, the body grew by about 2.353 MB; one preceding screenshot data URI was about 2.350 MB.

For the requests in the primary window, request-body preparation to HTTP response headers took 193–558 seconds. The first recorded model output then followed the headers by about 2–7 seconds. Two attempts logged a generic Request failed before a later HTTP 200; the exact retry count is not available.

Limits: These measurements show large prepared HTTP bodies and a close correlation between new screenshot data and later body growth. They do not prove that every historical image is resent byte-for-byte or that the full prepared body was transmitted. The local logs have no upload-complete timestamp, so preparation-to-headers must not be read as upload duration. The affected requests were responses_http; no matching WebSocket 300-second idle-timeout event was present. I did not find a timestamp-matched Clash upstream error for these requests.

This may be useful alongside the pre-response-header timeout report and the Windows image-heavy HTTP reports / #54668. Raw rollouts, prompts, request IDs, local paths, and image contents are intentionally omitted.

matith avatar Oct 18 '26 06:10 matith

Follow-up: tool-only image accumulation, full-context HTTP replay, and a counterexample to a universal 16 MiB WS limit

Verified on October 19, 2026. Windows Codex Desktop 26.1013.4894.0, bundled runtime 0.163.0-alpha.10.2, built-in OpenAI provider, ChatGPT authentication.

This update separates production observations from independent synthetic tests. Our latest experiment does not support a universal 16 MiB limit on the uncompressed WebSocket message. Please correlate with #24550, #38846 and #23665.

Production observations

A newly created text-only handoff thread received no user-uploaded images. Tool activity subsequently added screenshots and generated-image outputs. At the inspected snapshot, its working context had accumulated 21 inline image blocks since compaction, containing 55,929,954 bytes of Data URLs:

  • 11 function_call_output image blocks: 33,215,346 bytes.
  • 10 custom_tool_call_output image blocks: 22,714,608 bytes.

These are reconstructed local working-context measurements, not captured WS message sizes. Logged prepared HTTP request bodies reached 57,447,827 bytes before compression and 42,296,198 bytes after zstd. Large-context submissions occurred during ordinary continuations, not only failed-request retries. Prepared-body sizes do not establish completed network transfer or VPN-billed traffic.

The retained log window lacked this thread's initial WS failure; its original close code and cause remain unknown.

What is established about compaction and recovery

Across three inspected threads and 46 compaction records, we found specific successful compactions that removed tool images. In one checkpoint, 11 function-output generated images and 13 custom-output viewed images were absent from the replacement window. Separate comparisons removed screenshots while retaining user images with unchanged hashes. This is evidence for these item forms/checkpoints, not a guarantee about every image type or compaction.

The observed chain is:

  1. Inline image bytes accumulate between compactions, potentially while the token-based trigger has not fired.
  2. Compaction may remove tool images; retained user images can still leave a large window. Successful compaction does not guarantee a small serialized request.
  3. When the incremental baseline is unavailable, the required working context is sent again—not necessarily the entire conversation archive.
  4. In a separate affected thread, an explicit 60-minute connection-limit error was followed by successful new WS handshakes and full-baseline requests, then early closures and HTTP fallback. The old closures' codes were not preserved.
  5. In the inspected runtime, HTTP fallback sets disable_websockets=true on the live client. A later successful compaction reduced that thread's reconstructed window to approximately 7.78 MB, but subsequent requests stayed HTTP; no fresh WS attempt was recorded.
  6. The inspected ordinary streaming branch discards peer Close details and reports the generic “websocket closed by server before response.completed” error.

Sources: version-pinned client, version-pinned WS endpoint.

There are already serialized soft-budget changes such as #47758/#47957 that shed optional metadata/observations. Our concern is the remaining ordinary inline-image payload and full-baseline replay; we are not claiming there is no byte-aware logic anywhere in Codex.

Native-path single-image controls

Isolated native tool-image tests used a valid 2,200,000-byte padded PNG, a 2,710,712-byte high-entropy synthetic PNG, and a 1,596,345-byte same-source JPEG. Persisted image bytes/hashes and dimensions matched the files; no resizing/reencoding was observed. Answers matched the synthetic content, and exact task/turn-correlated logs contained transport=responses_websocket labels. This does not support a universal 2 MB PNG cutoff on that tested path. Final serialized WS messages and compressed frames were not captured.

Independent controlled boundary test

The following used an existing standalone diagnostic executable with official authentication and TLS verification, not the unmodified desktop's native request-construction path. Four independent connections, one request each, no retries:

Payload construction Complete UTF-8 message bytes Result
Small PNG + trailing whitespace 16,777,215 response.completed, 2.137 s
Same small PNG + two more spaces 16,777,217 response.completed, 2.043 s
Same-pixel PNG with random ancillary padding 16,777,215 response.completed, 6.733 s
Same padded PNG + two more spaces 16,777,217 Peer Close 1009, empty reason, 6.913 s

All four handshakes returned 101, negotiated permessage-deflate, and reported successful send completion. This failure was after handshake, not a handshake failure.

Offline checks confirmed:

  • Each pair differs strictly by two trailing ASCII spaces; image fields and parsed JSON values within the pair are identical.
  • The sender transmits original text, without trimming or reserialization.
  • Across groups only image_url differs. PNG IDAT bytes and decoded pixels are identical; the random ancillary chunk is structurally valid.
  • Small-image Data URL: 7,142 bytes; padded-image Data URL: 16,776,762 bytes.
  • 1009 was received in a peer Close frame, not raised as a local capacity exception.

Limits: Actual compressed WS payload bytes were not captured. Groups were run in separate process executions, so batch/routing differences remain possible. Response IDs were not retained for additional correlation. These are new synthetic samples, not identical replays of older failures. Offline DEFLATE estimates are not wire measurements. The diagnostic build's source-to-binary correspondence was not independently reproduced.

The successful 16,777,217-byte request contradicts “every uncompressed message above 16 MiB fails.” The padded-image pair shows size-associated peer rejection in this experiment, but does not establish a universal threshold, the enforcement layer, or a compressed-byte limit. It cannot retrospectively assign 1009 to every production closure.

Requested maintainer guidance

  • Preserve peer Close code/reason and privacy-safe serialized/compressed-message size diagnostics, plus full-versus-incremental status.
  • Clarify what is constrained: serialized message, compressed payload, decoded image, aggregate media, or another layer.
  • Bound ordinary image/request bytes before full-baseline rebuilds, including reconnect and compaction.
  • Avoid repeated unchanged requests after a deterministically oversized-message rejection.
  • Provide supported recovery preserving the original thread and image files while reducing transmitted working context.
  • Allow controlled WS recovery after context reduction rather than leaving a live client indefinitely in HTTP fallback.
  • Identify any tracked fix or release addressing these mechanisms.

No private images, conversation contents, credentials, local paths or session identifiers are attached. No production history or client configuration was modified for these tests.

pamelagrainsn-cmyk avatar Oct 19 '26 14:10 pamelagrainsn-cmyk

Same problem here: screenshot-heavy threads grow by megabytes per image while barely growing in tokens. In one 0.162 thread, prompt tokens rose by only 34.7K while the request body rose by 16.8 MB. Token-based auto-compaction never fired, and the body reached 48 MB.

Two causes in 0.162:

  • High-detail images keep their source bytes up to 2048 px. A 1920×1080 PNG passes through unchanged, at roughly 1–3 MB (utils/image/src/lib.rs, HIGH_DETAIL and can_preserve_source_bytes).
  • app-server wires passthrough_image_store() (message_processor.rs). Although ImageReference::File and AttachmentStore exist, every request re-sends every historical image as base64, and there is no configuration to change that.

Until there is a native fix, we carry two small patches that follow how our reference desktop agent handles images:

  • Image caps (https://github.com/claymorelab/codex/commit/3f4fde7b68ca4e534035ec099ba88111a66e7341): high-detail and resize-to-fit images are capped at 1024 px on the long side (1280 px for WebP) and at 1 MB, shrinking by 0.8 until both hold. Original-detail requests are unchanged.
  • Image-count compaction (https://github.com/claymorelab/codex/commit/3d7fab76128c505ba45bdfdc6568fc527d4ddffa): auto-compaction also triggers once the history carries 24 images. The compaction summary keeps only the latest image, behind a short "[Latest screenshot]" note, so the model keeps the last visual state.

What would make these patches unnecessary:

  • a configurable AttachmentStore in app-server, so images are sent by reference, or
  • compaction that takes image bytes into account, not only tokens.

Related: #30441 (the 413 dead end) and #16033 (the accounting bug that stops recovery).

lywaterman avatar Oct 20 '26 06:10 lywaterman

One update to my earlier workaround, since custom endpoints came up here: v0.9.0 now preserves the original upstream per client route instead of assuming the default OpenAI endpoint. Automatic image retrieval and pinning are also available. I've updated my earlier comment with the current scope and limitations.

I'm the project's author. This only applies to recognized image blocks on supported desktop routes with compatible native APIs, images, and tools; it doesn't fix a gateway's image-to-text conversion or arbitrary base64 in ordinary tool text. Live third-party gateway model calls remain untested by me.

chipfighter avatar Oct 23 '26 09:10 chipfighter

I ran into the same problem. This is how I worked around it: https://github.com/Chuncheng95/Codex-DeepSeek-HTTP-413-Recovery

我也遇到了这个问题,这是我的解决方法: https://github.com/Chuncheng95/Codex-DeepSeek-HTTP-413-Recovery

Chuncheng95 avatar Oct 28 '26 04:10 Chuncheng95