GeezerVison is showing github.com — compaction: background summary + recent-context drops unconsumed tool-result images, causing repeated image reads · Issue #66826 · anomalyco/opencode
compaction: background summary + recent-context drops unconsumed tool-result images, causing repeated image reads #66826DescriptionDescription
When auto-compaction swaps in a background precomputed summary (default-on since #64290, PRECOMPUTE_LEAD = 60_000 in #60049), messages in [keepID, compaction) are serialized into <recent-context> as plain text by SessionRecentText.messageToText.
This silently drops both tool-result image payloads (serializeToolContent replaces them with [Attached image/png: ...]) and assistant reasoning parts (recent-text.ts:45):
- If the turn right before compaction calls
read on images (and IMAGE_TOKEN_ESTIMATE = 1_500 pushes the prompt past the compaction ceiling), compaction runs before the next LLM step ever sees those images. Since the precomputed summary was anchored at an earlier keepID, those images are neither in <summary> nor kept as media in <recent-context>.
- For multimodal reasoning models (e.g. DeepSeek / Claude) that write visual findings in
reasoning and immediately issue the next tool call without visible text, every image-reading step between keepID and compaction loses both its pixels and its observations at once.
In a real v2.4.1 session inspecting a 24-page PDF, auto-compaction triggered right after read on 4 page PNGs (keepID was 20 steps earlier). On the next step the model noted:
"I read pages 4,5,6,7 in the last calls but results were just images. I don't have the visual assessment recorded. Let me re-check..."
and re-read all 24 pages from scratch.
Verified still present on dev (31a291bd03):
packages/core/src/session/compaction.ts (usePrecomputed, L434–L464): swaps in the held summary without checking for unconsumed media in the tail.
packages/core/src/session/history.ts (withRecentText, L246–L280) & packages/core/src/session/recent-text.ts (L45, L87–L92): strips reasoning and replaces tool-result file media with [Attached <mime>: <name>].
Related to #60511 (which covers dropped user text attachments on sync trim), except here default-on background compaction drops unconsumed tool-result images during normal auto-compaction without any overflow shrink.
Possible fixes (without exposing raw provider reasoning):
- Keep real media parts (under the existing
boundImages 25 MiB cap) in the checkpoint/tail for tool-result images that have no subsequent assistant text turn consuming them; or
- In
usePrecomputed, skip swapping a stale background summary when [keepID, compaction) contains unconsumed media tool results (or keep the trailing turn outside <recent-context>).
Plugins
none required (reproduces in core SessionRecentText / SessionCompaction)
OpenCode version
v2.4.1 (verified on dev @ 31a291b)
Steps to reproduce
- Run a multimodal model with auto + background compaction enabled (default on
dev / v2.4.1).
- Read images via
read near the compaction threshold so auto-compaction swaps in an earlier background summary (metadata.keepID anchored several steps back).
- Observe
<recent-context> drops both the image/* payload and any reasoning notes, forcing the model to re-read the images.
Minimal code repro from packages/core:
bun -e '
import { SessionRecentText } from "./src/session/recent-text.js"
const msg = {
id: "msg_test_1",
type: "assistant",
time: { created: Date.now() },
agent: "general",
model: { providerID: "test", id: "test-vlm" },
content: [
{ type: "reasoning", text: "Page 4 shows table 2 overflowing the right margin." },
{
type: "tool",
id: "call_1",
name: "read",
state: {
status: "completed",
input: { path: "/tmp/pages/p-04.png" },
content: [
{ type: "text", text: "Image read successfully" },
{ type: "file", mime: "image/png", name: "/tmp/pages/p-04.png", uri: "data:image/png;base64,iVBORw0KGgo=" },
],
},
},
],
}
console.log(SessionRecentText.messageToText(msg as any))
'
Output (both pixels and reasoning gone):
[Assistant tool call]: read({"path":"/tmp/pages/p-04.png"})
[Tool result]: Image read successfully
[Attached image/png: /tmp/pages/p-04.png]
Screenshot
No response
Operating System
Linux (Docker sandbox) / macOS
Terminal
N/A (headless opencode server) Activityopencodejr commented on Nov 27, 2026 Seen with a simulated model or a mock server, not a real provider; a maintainer should confirm.
Thanks for the detailed report and the analysis. I reproduced this with the v2.4.1 CLI driven by a simulated model. It still happens on the latest dev (8815bc9d4).
Setup:
- A simulated model that accepts images, with a 100k context.
- Its reported prompt-token usage puts the session near the compaction ceiling, so a background summary is precomputed.
- The model then calls
read on a PNG, which pushes the context past the ceiling.
On the next step the held summary is swapped in. The request the model gets is the conversation checkpoint only, and its <recent-context> contains:
[Assistant tool call]: read({"path":"pages/p-04.png"})
[Tool result]: Image read successfully
[Attached image/png: pages/p-04.png]
There is no image part, so the model never sees the image it just read. The comment on usePrecomputed says the tail after the held summary is kept verbatim, so dropping the image looks unintended. Dropping reasoning parts there is deliberate (the code comment explains why), so I've treated only the image loss as the bug.
The model responses, the token usage and the model's limits were simulated; the script below reproduces it. Closely related: #60511, which is the same label-only rewrite, in the synchronous compaction path and for user text attachments. I've passed this on to the maintainers.
Reproduction script (drive.ts)
// Repro for #66826: a background (precomputed) compaction summary swapped in right after a `read`
// of an image turns that unconsumed tool-result image into a text label in <recent-context>.
import { Effect, Stream } from "effect"
import { Llm, OpenCodeDriver } from "opencode-drive"
// 1x1 PNG
const PNG = Uint8Array.from(Buffer.from(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==", "base64"))
const usage = (prompt: number) =>
Llm.raw({ choices: [], usage: { prompt_tokens: prompt, completion_tokens: 10, total_tokens: prompt + 10 } })
const describe = (body: any) => {
const s = JSON.stringify(body)
return {
hasImagePart: /"type":"image_url"|data:image\/png;base64/.test(s),
hasLabel: s.includes("[Attached image/png"),
hasRecentContext: s.includes("<recent-context>"),
isSummaryRequest: s.includes("<template>") || s.includes("summar"),
}
}
export default OpenCodeDriver.use(
{
...(process.env.OC_DEV ? { opencode: { dev: process.env.OC_DEV } } : {}),
project: { git: true, files: { "pages/p-04.png": PNG } },
config: {
providers: {
simulation: {
models: {
"gpt-sim-model": {
capabilities: { tools: true, input: ["text", "image"], output: ["text"] },
limit: { context: 100_000, output: 16_000 },
},
},
},
},
} as any,
},
({ ui, llm }) =>
Effect.gen(function* () {
let step = 0
yield* llm.serve((request: any, index) => {
const body = request?.request?.body ?? request?.body ?? request
const info = describe(body)
console.log(`REQUEST ${index}: ${JSON.stringify(info)}`)
const text = JSON.stringify(body)
const roles = (body?.messages ?? []).map((m: any) => m.role).join(",")
console.log(`REQUEST ${index} roles=${roles}`)
const rc = text.indexOf("<recent-context>")
if (rc >= 0) console.log(`REQUEST ${index} recent-context: ${text.slice(rc, rc + 1500)}`)
const last = body?.messages?.at(-1)
// A summary request asks for the summary template in its final user message.
if (last?.role === "user" && JSON.stringify(last).includes("<template>")) {
console.log(`REQUEST ${index} -> summary request`)
return Stream.make(Llm.text("## Objective\n- Inspect pages"), usage(1000), Llm.finish("stop"))
}
step++
if (step === 1) return Stream.make(Llm.text("First answer."), usage(1_000), Llm.finish("stop"))
if (step === 2) return Stream.make(Llm.text("Second answer."), usage(50_000), Llm.finish("stop"))
if (step === 3)
return Stream.make(
Llm.toolCall({ index: 0, id: "call_img", name: "read", input: { path: "pages/p-04.png" } }),
usage(83_000),
Llm.finish("tool-calls"),
)
return Stream.make(Llm.text("Done looking."), usage(5_000), Llm.finish("stop"))
})
yield* ui.submit("First message")
yield* ui.waitFor("First answer.")
yield* ui.submit("Second message")
yield* ui.waitFor("Second answer.")
yield* Effect.sleep("3 seconds")
yield* ui.submit("Read pages/p-04.png and assess it")
yield* ui.waitFor("Done looking.", { timeout: 60_000 } as any)
yield* ui.screenshot("after")
}),
)
Run it with opencode-drive: opencode-drive run ./drive.ts. It drives opencode from your PATH; set OC_DEV to the path of an OpenCode checkout to run that from source instead.
m4r1glen commented on Nov 27, 2026 I'd like to work on this issue, focusing on preserving unconsumed tool-result images during background compaction while respecting existing media and context limits.
Could you assign it to me if nobody is currently working on it? Guembri01 commented on Nov 27, 2026 I tried the second fix in the report — skip swapping a stale background summary when [keepID, compaction) holds media — and it is not sufficient. Recording why, because it narrows the choice.
I instrumented SessionCompaction with a test history whose last turn is a read that returned an image, a held background summary anchored earlier, and automatic compaction due. Skipping the swap worked: usePrecomputed returned undefined and summarize ran. But the fresh summary request contained only the prefix — 4 messages, ending at the anchor — and not the image.
The reason is summarize's shrink input:
history: withoutTail(prepared.request, keepID),
and deliver picks shrink.history (or flattenAndDropOldest(shrink.history, …)) whenever the whole request does not fit. The tail is excluded because a checkpoint keeps it beside the summary. That is true for a fresh compaction too, not just a swapped one: the tail becomes <recent-context> text either way, and SessionRecentText renders media as [Attached image/png: …].
So the loss is in the checkpoint's tail, not only in the stale summary. Consequences for the two options in the report:
- Skip the stale swap does not help on its own; the fresh summary drops the same tail.
- Keep real media in the checkpoint tail (option a) fixes it at the point of loss, under the existing
boundImages cap.
- A third, smaller variant: when the tail holds media, pass the full request to the summarizer (
history: prepared.request, letting deliver fit or flatten it) instead of withoutTail, so the observations are written into the summary text. It costs the tail's tokens on the summary call and changes nothing about how checkpoints are stored.
I have not opened a patch: all three change compaction's cost or checkpoint format, which is a maintainer call. Happy to implement whichever is preferred; the test above (image in the tail, held summary, assert the summarizer's request carries it) is the guard either way. supercoderhawk commented on Nov 28, 2026 Thanks @opencodejr for the repro and @Guembri01 for catching the withoutTail path on synchronous compaction too — that narrows the root cause down nicely.
From a real multimodal workflow perspective, Option A (keeping unconsumed tool-result media in the retained tail under boundImages) is strongly preferable over passing the tail into the summarizer:
agents.compaction.model may be configured as a text-only model (and flattenAndDropOldest already replaces media with [image/... omitted] when shrinking), so the summarizer cannot reliably inspect images.
- For pixel-level visual inspection tasks (rendered PDF pages, charts, or UI screenshots), a terse
<summary> bullet cannot replace actually seeing the newly read image — the agent still has to re-read it.
Sharing a sanitized excerpt from the real 200k-context multimodal session below as confirmation beyond the simulated repro. Happy to wait on maintainers' preference.
Real-session trace excerpt (sanitized, v2.4.1, 200k-context multimodal reasoning model)
sequenceDiagram
participant Agent as Multimodal Agent (200k ctx)
participant OC as OpenCode Compaction (v2.4.1)
Note over Agent,OC: Step 30 (ctx 105.3k): background summary starts (keepID = step 30)
Agent->>OC: Steps 35-48: 23 PNG read() calls (ctx 145.8k -> 164.5k)
Agent->>OC: Step 49 (ctx 165.6k): read(p-04.png .. p-07.png) [+4x1,500 est >= 170k ceiling]
OC-->>OC: Step 50: Auto-compaction swaps in stale summary (keepID = step 30)
Note over OC: recent-context drops reasoning & rewrites images to "[Attached image/png: ...]"
OC->>Agent: Step 51 (ctx 52.3k): Checkpoint only - zero image payloads from steps 35-49
Note over Agent: Reasoning: "I read pages 4,5,6,7 in the last calls but results were just images.<br/>I don't have the visual assessment recorded. Let me re-check..."
Agent->>OC: Steps 51-70: Re-reads all 24 pages (25 redundant PNG read() calls)
Loading
| Step |
Event |
Prompt ctx (measured) |
Effect |
#30 |
Pre-export milestone |
105,315 |
Anchored as metadata.keepID for background summary |
#35–#48 |
First visual pass (23 PNG reads) |
145,767 → 164,526 |
Visual findings recorded in reasoning parts |
#49 |
read(p-04.png .. p-07.png) |
165,600 |
+4 × 1,500 image estimate crosses 170k auto-compaction ceiling |
#50 |
Auto-compaction (reason: auto) |
105,458 |
Swaps held summary (keepID = #30); <recent-context> turns all PNGs into [Attached image/png: ...] labels |
#51 |
Next assistant step |
52,330 |
Model never sees p-04..p-07.png, notes "results were just images. I don't have the visual assessment recorded" |
#51–#70 |
Full re-inspection |
52,330 → 72,940 |
Re-reads 21 pages (25 redundant read calls) |
MetadataMetadataDevelopmentNo branches or pull requestsIssue actions
|