[BUG] Viewing image evicts almost all conversation history messages
๐ What happened?
For background, I was working on some visualization work in Agent mode, which is essentially a long loop: the agent reads the data and the code, writes the processing and plotting code,renders a figure, views it, adjusts, renders again โ until the figure looks right. The data-processing half of that is substantial on its own (reading inputs, inspecting intermediate outputs, etc; about 100~300k tokens of context), and the figure-review half adds many large images over the session.
The problem: after a handful of figure views the agent stops acting on what it has already built. It announces work it already did as if it were new ("let me first look at the data and code"), re-reads files it had already processed, re-writes processing steps it had already validated, and renders again. Each further figure triggers it again. From the user's side the session silently restarts and never converges on the last few percent of the figure.
Nothing in the UI explains when or why this happens, and the chat transcript still shows the full history, so the restart looks like the model's fault.
Spoiler: the history trimmer being too aggressive is the root cause.
๐ Steps to reproduce
- Agent mode with
deepseek-v4.1-flash. - Ask for a visualization built from scratch: read the dirty data, process it, plot it, then look at the rendered figure and refine it.
- Wait for the agent running a normal number of refinement cycles. The data-processing and code-editing history reaches a few hundred thousand tokens; the figures are large and there are several of them.
- After a few figure views, the agent re-reads what it already read and redoes work it already did.
- Keep going: the same reset recurs on following figures, and it gets worse, not better โ the very act of re-reading adds back the history that is dropped next time.
โ What did you expect?
- Once the agent has read the data and built the pipeline, it should keep that work for the rest of the task.
- In history trimmer, looking at a figure should cost roughly what looking at a file costs โ it should not consume a large share of the conversation.
- If context genuinely has to be reduced, the session should degrade in a way the user can see and act on (e.g. manual compaction), not silently rewind to the start of the task.
๐ฅ๏ธ Environment
- Extension version: 0.8.1
- VS Code version: 1.147.0
- Provider: OpenCode Go
- Model: deepseek-v4.1-flash
๐ธ Logs or screenshots (optional)
Condensed from VSCode Output panel โ OpenCode, 2026-11-19. prompt / cached are the provider's counts; promptEstimate is the extension's own:
02:34:43 usage: prompt=258376 completion=163 cached=257920 cacheHit=99.8% finishReason=tool_calls
02:36:49 [history-trim] Replaced 1 old image(s) with placeholder text (kept most recent 2).
02:36:49 Request: messages=453 promptEstimate=498070 maxOutputTokens=384000
02:36:49 [request] payloadBytes=1624972
02:36:55 usage: prompt=258592 completion=181 cached=258304 cacheHit=99.9% finishReason=tool_calls
02:38:57 [history-trim] Replaced 1 old image(s) with placeholder text (kept most recent 2).
02:38:57 Request: messages=455 promptEstimate=498256 maxOutputTokens=384000
02:38:57 [request] payloadBytes=1625646
02:39:02 usage: prompt=258808 completion=86 cached=258560 cacheHit=99.9% finishReason=tool_calls
02:39:12 [history-trim] Replaced 2 old image(s) with placeholder text (kept most recent 2).
02:39:12 [history-trim] Dropped 291 old message(s) to fit context window
(budget=613952 tokens, maxBytes=2762784);
estimated payload now ~538239 tokens / 257952 bytes.
02:39:12 Request: messages=168 promptEstimate=538239 maxOutputTokens=384000
02:39:12 [request] payloadBytes=1889241
02:39:42 usage: prompt=91033 completion=280 cached=29696 cacheHit=32.6% finishReason=tool_calls
02:39:50 [history-trim] Replaced 2 old image(s) with placeholder text (kept most recent 2).
02:39:50 [history-trim] Dropped 291 old message(s) ... estimated payload now ~539058 tokens
02:39:50 [request] payloadBytes=1891003
02:39:50 usage: prompt=91033 ... (same shape, repeated)
| Observation | Value |
|---|---|
| Real prompt before the trim | 258,808 tokens |
| Extension's estimate for that same request | 498,256 (1.9ร too high) |
| What tipped it over | two more figures added between 02:38:57 and 02:39:12 |
| Messages dropped in one request | 291 (455 โ 168) |
| Real prompt after the trim | 91,033 โ 65 % of the work gone |
| Extension's estimate after the trim | 538,239 (5.9ร too high) |
| Serialized payload before โ after | 1,625,646 โ 1,889,241 bytes (it grew) |
| Of those bytes, image data | 1,631,289 (text-only estimate: 257,952) |
| Prompt cache | 99.9 % โ 32.6 %; the next request took ~30 s |
Four things stand out:
- The trim was triggered while the real prompt was at 258,808 tokens โ a quarter of the window โ and it left 91,033.
- Dropping 291 messages made the request bigger. The remaining figures weigh far more than the text that was removed.
- The extension's estimate is 1.9ร too high before the trim and 5.9ร too high after it, while the provider's own counts say the request is small.
- The same trim, with the same count, fires again 38 s later โ it is recomputed from the full history each request, so the cut never settles and every turn re-pays a cold prefix (99.9 % โ 32.6 % cache hit).
๐ Root cause
src/tokenEstimate.ts โ estimatePromptTokenCount() measures the whole prompt as estimateTokenCount(JSON.stringify(prompt)), which is ceil(chars / 4) ร 1.1. Image parts are already base64 data URLs, so a screenshot's raw bytes are counted as if they were prose:
| Figure PNG | base64 chars | charged by the estimator | real (measured) | over-charge |
|---|---|---|---|---|
| 150 KB | 204,800 | 56,320 | hundreds | ~150ร |
| 300 KB | 409,600 | 112,640 | hundreds | ~300ร |
| 1 MB | 1,430,872 | 393,490 | 244โ486 | ~1,000ร |
In the log above that is exact: the image bytes (1,631,289) re-measured at 1,631,289 รท 3.636 = 448,650 โ the phantom 447,206 tokens, i.e. 83 % of the 538,239-token estimate is base64 image data. This is why the estimate runs 5.9ร ahead of the provider's count, and why adding one more figure is enough to cross the budget.
Two consequences in the loop:
- The wrong history is dropped. The trim keeps
messages[0](the anchor) and the newest message (the current prompt or latest tool result) and drops the oldest middle in one block. In an agentic loop the just-viewed figure is the newest message, so what gets dropped is precisely the data-processing work that produced the figure โ the expensive, hard-to-recompute part. - The notice makes it self-sustaining. #274's
[Context notice]tells the model to "re-read files or ask the user". The model re-reads, which adds history back; the next figure inflates the estimate again; the trim fires again. Nothing bounds this โdetectBeamToolLoop()only applies tobeam-*model ids.
Why the byte cap didn't catch this. #173 deliberately stopped counting image data toward MAX_REQUEST_PAYLOAD_BYTES via stripImageData(), on the grounds that image weight "is already bounded by the dedicated image-history trimmer โ the byte ceiling exists to bound text growth" (docs/issues/75-20260821-issue173-vision-byte-cap.md). The token budget exists to bound text growth for exactly the same reason, but it still charges base64. This is the token-side half of that asymmetry โ and the log shows it directly: the byte check passed (257,952 estimated bytes โช 2,762,784) while the token check failed at 538,239.
Secondary effect worth noting. finalTokens also feeds calculateModelLimits(), whose remainingContext = contextWindow โ (prompt ร 1.12), and src/request/openai.ts sends max_tokens from it. On this model max_tokens reaches 1 once the estimated prompt passes ~889K, which two large figures plus a long session can reach โ the same collapse reported in #83 (prompt: 754,773 completion: 1 finishReason: length,
docs/issues/37-20260724-estimate-token-count-overflow.md). It did not happen in the session above (maxOutputTokens=384000 throughout), so treat it as arithmetic-reachable rather than observed.
Two internal inconsistencies make this hard to notice from the UI: tokens.ts charges IMAGE_TOKEN_ESTIMATE = 1024 for the same image the trimmer charges 393,490 (so VS Code believes the payload is small and never compacts), and nothing surfaces the trim except a line in the Output channel.
๐ Measured: the limits being enforced do not exist (at least on DS, GLM and Qwen)
TL;DR: OpenCode Go actually accepts requests with much higher number of tokens or request body size.
I ran several direct POST /zen/go/v1/chat/completions calls using a script, with thinking: disabled, temperature: 0. To make "HTTP 200" mean "answered correctly" rather than "accepted and silently truncated", a needle (ZX-4471-QP) is planted at ~50 % depth of the prompt and must be echoed back.
A. Prompts larger than the budget the extension trims to
The extension's budget for this model is min(โ1M ร 0.7โ, 1M โ 384K โ 2048) = 613,952 tokens; maxBytes = 2,762,784.
| model | prompt tokens | ร budget | body | HTTP | needle | max_tokens | latency |
|---|---|---|---|---|---|---|---|
| deepseek-v4.1-flash | 661,694 | 1.08ร | 1.71 MB | 200 | OK | 64 | 32.4 s |
| deepseek-v4.1-flash | 853,854 | 1.39ร | 2.21 MB | 200 | OK | 64 | 28.1 s |
| deepseek-v4.1-flash | 853,854 | 1.39ร | 2.21 MB | 200 | OK | 131,072 | 7.1 s |
| deepseek-v4.1-flash | ~879,000 | 1.43ร | 2.28 MB | 400 | โ | 64 | 6.0 s |
| deepseek-v4.1-flash | ~907,000 | 1.48ร | 2.35 MB | 400 | โ | 64 | 5.0 s |
| deepseek-v4.1-flash | ~960,000 | 1.56ร | 2.49 MB | 400 | โ | 64 | 4.9 s |
| glm-5.3-flash | 763,479 | 1.24ร | 2.01 MB | 200 | OK | 64 | 33.7 s |
| qwen3.8-flash | 746,754 | 1.22ร | 1.58 MB | 200 | OK | 64 | 42.9 s |
Failures were all {"type":"invalid_request_error","code":"context_length_exceeded"} โ the token axis, never bytes. Real ceiling: >853,854 and <879,000 prompt tokens (~86โ88 % of the nominal 1M window).
The row that matters most is the third: 853,854 input tokens plus a 131,072-token output request (total โ 985K) still returns 200 with a correct
answer. So the ceiling is not the constraint at 614K, and the 0.7 ratio is not what binds โ the 384K output reservation is (613,952 < 700,000).
B. Large bodies from many images
Images are the clean byte probe: base64 inflates the body while real token cost stays small. Each image is a 590ร590 incompressible PNG (1 MB binary โ 1.33 MB base64). Text-only baseline with the same filler: 5,335 tokens (deepseek) / 5,385 (glm).
| model | images | body | ร byte cap | prompt tokens | tokens/image | HTTP | needle | latency |
|---|---|---|---|---|---|---|---|---|
| deepseek-v4.1-flash | 8 | 10.68 MB | 3.9ร | 7,285 | 244 | 200 | OK | 25.8 s |
| deepseek-v4.1-flash | 16 | 21.35 MB | 7.7ร | 9,237 | 244 | 200 | OK | 34.8 s |
| glm-5.3-flash | 8 | 10.68 MB | 3.9ร | 9,273 | 486 | 200 | OK | 10.2 s |
What this establishes
- A figure costs hundreds of tokens, not hundreds of thousands. 244โ486 per 1 MB image measured; a full-size figure is larger but in the low thousands. The estimator charges ~1,000ร that, which is the entire bug.
- The numbers the trimmer is defending do not exist. This model answered correctly at 1.39ร the token budget and at 7.7ร the byte cap.
- Neither the image count nor the byte cap is a real upstream limit here โ 16 images (8ร
MAX_HISTORY_IMAGES_KEPT) and 21.35 MB were accepted. A per-model wall does exist elsewhere (mimo-v2.5400s above ~32 MB), so a universal cap is still worth having โ just not at 2.76 MB. - Therefore the trim in the log above removed 291 messages and 167K real tokens for no benefit: the request it protected against was 91K tokens and succeeded.
Ideas for fixing the issue
I'm not sure which is the best for this issue, and I leave them here:
- Detect the input type in the trimmer instead of fixing the estimate โ the byte cap can special-case images safely because it is only a safety bound; the token budget also drives
max_tokensand reported usage, so it needs the correct number, not an exception. - Turn history trimming off / make it opt-in by an option โ hides the miscalculation and still sends
max_tokensderived from a bogus prompt size; it also re-opens #109. - Allowlist models that tolerate large bodies โ the accounting error is model-independent, and all three cheap models tested tolerate 1.2โ1.4ร the budget, so such a list would cover almost everything. A per-model budget override is the useful version of this idea.
- Raise
MAX_HISTORY_IMAGES_KEPT/ make it into an tunable option โ allowing model to compare multiple figures at once.