gateway: an image Claude Code is handed in a block is fitted to 2000 px, as it fits its own (sean_80289)

sean_80289 on Discord, through DeepSeek Harness (dsh) to a Claude
subscription: "API Error: an image in the conversation could not be
processed and was removed. Double press esc to edit your message, or
re-read the file if you still need it."

Cause: magpie gives Claude Code the earlier turns' images as image blocks
in the transcript a run resumes (replaySession), and a -p run's
stream-json message carries them the same way. Claude Code sends those as
they are; it fits only an image it reads from a file (2.1.316: 2000 px a
side, 5 MiB of base64), as with the files magpie pastes for the last
turn. dsh passes an image with a long edge up to 8192 px byte for byte
(its 2048x2048 pixel budget and 8192 px edge), and the API refuses one
over 8000 px a side, which Claude Code reports with that message.

Reproduced with a real Claude Code 2.1.316 (claude-tui-helper, sandbox
HOME, a real subscription token), a 400x8192 JPEG:
- in a resumed transcript: sean's exact error, error_during_execution;
- 400x8000 and 2590x1619 in a transcript, and 400x8192 pasted: answered.

Fix: claudeImage (claude_images.go) fits each base64 image in
imageBlocks (replay, -p prompts, typed turns) and in mcpResult (a tool's
images): scaled to 2000 px a side with its shape kept, JPEG again as
JPEG at 85 and anything else as PNG, then JPEG at a lower quality if it
is still over 5 MiB of base64. An image that fits, or can't be read,
goes byte for byte as before. Decoding is bounded by codexImageMaxBytes
and imageHolds, and results are kept in the fitted cache under their own
limits key.

Run on mote at a8d6a861a, one commit (internal/proc only) before the
pushed head: go test ./internal/gateway ./internal/tui
./internal/cli: tui ok; the new tests and the existing replay and Codex
image tests pass. Two reds, both filed and red apart from this change:
gateway TestCodexPoolSaysTheClientsVersion (#4807, another test's Codex
identity in a full package run) and cli TestEveryRouteHasACommandOrIsNamed
(#4826). go vet for darwin, linux (-tags nogui) and windows; gofmt -l
clean; go build -tags nogui ok. Then a real Claude Code 2.1.316 with the
image claudeImage made of the 400x8192 JPEG (98x2000 JPEG) in a resumed
transcript answered ("Blue and red."); the raw image beside it gave the
error again.

At the pushed head after the rebase: go build ./... ok, go test
./internal/tui ./internal/proc ok, and the new and replay tests in
internal/gateway ok.

Broken by hand: with claudeImage returning its input,
TestClaudeReplayFitsATallImage (the transcript's image 400x8192) and
TestClaudeImagePNGAndToolResults (3000x1000) went red.

Not tried: dsh itself; a WebP over the side (Go can't write WebP, so no
fixture; decoding goes through x/image/webp); more than 20 images over
2000 px in one request, which the API refuses with another message and
this fit covers too.
This commit is contained in:
yetone
2026-11-02 16:01:44 +08:00
parent 5ef19d0073
commit 4b407bb79f
3 changed files with 286 additions and 2 deletions
+131
View File
@@ -0,0 +1,131 @@
package gateway
import (
"bytes"
"encoding/base64"
"image"
"image/color"
"image/draw"
"image/gif"
"image/jpeg"
"image/png"
"math"
"strings"
"golang.org/x/image/webp"
)
// Claude Code fits an image it reads from a file before it sends one
// (Claude Code 2.1.316: 2000 px a side and 5 MiB of base64 at most), as it
// does with the files magpie pastes into its prompt. An image magpie hands
// it as an image block is sent as it is: the earlier turns' images in a
// transcript a run resumes (replaySession), a -p run's stream-json
// message, and, fitted here too, a tool's images in its MCP result. The API refuses an image over 8000 px a side, and Claude Code
// then says "API Error: an image in the conversation could not be
// processed and was removed" and the turn fails. DeepSeek Harness (dsh)
// sends images up to 8192 px a side (its normalizedImageMaxDimension, the
// long edge after a 2048x2048 pixel budget), so a tall screenshot of
// 400x8192 went through dsh and the -anthropic route to a Claude
// subscription and was refused (sean_80289 on Discord). Claude Code took
// the same image pasted, fitted to 2000 px. The API also holds every image
// of a request with more than 20 to 2000 px, which dsh's 2048 budget
// passes too.
//
// claudeImage gives an image block what Claude Code would have made of
// the image: scaled to fit 2000 px a side, a JPEG written again as JPEG at
// quality 85 and any other as PNG, then as JPEG at a lower quality if that
// is still over the base64 limit. An image that fits goes as it came, byte
// for byte, and so does one that can't be read.
const (
claudeImageSide = 2000
claudeImageBase64 = 5 << 20
)
// claudeImageLimits keys the images claudeImage made in fitted, apart
// from Codex's.
var claudeImageLimits = imageLimits{side: claudeImageSide, patches: -1}
// claudeImage is the media type and base64 an inline image is sent to
// Claude Code with.
func claudeImage(mediaType, data string) (string, string) {
if data == "" || len(data) > codexImageMaxBytes {
return mediaType, data
}
cfg, _, err := image.DecodeConfig(base64.NewDecoder(base64.StdEncoding, strings.NewReader(data)))
if err != nil {
return mediaType, data
}
if cfg.Width <= claudeImageSide && cfg.Height <= claudeImageSide && len(data) <= claudeImageBase64 {
return mediaType, data
}
key := fitKey(mediaType+";"+data, claudeImageLimits)
e, ok := fitted.get(key)
if !ok {
e = claudeImageRefit(data)
fitted.put(key, e)
}
if e.data == nil {
return mediaType, data
}
return e.mime, base64.StdEncoding.EncodeToString(e.data)
}
// claudeImageRefit is the image scaled and written again, or an entry
// with no data when it goes as it came.
func claudeImageRefit(data string) fitEntry {
raw, err := base64.StdEncoding.DecodeString(data)
if err != nil {
return fitEntry{}
}
cfg, format, err := image.DecodeConfig(bytes.NewReader(raw))
if err != nil {
return fitEntry{}
}
holds, ok := imageHolds(cfg, format)
if !ok || len(raw)+holds > codexImageMaxBytes {
return fitEntry{}
}
var src image.Image
switch format {
case "png":
src, err = png.Decode(bytes.NewReader(raw))
case "jpeg":
src, err = jpeg.Decode(bytes.NewReader(raw))
case "gif":
src, err = gif.Decode(bytes.NewReader(raw))
case "webp":
src, err = webp.Decode(bytes.NewReader(raw))
default:
return fitEntry{}
}
if err != nil {
return fitEntry{}
}
w, h := cfg.Width, cfg.Height
if scale := math.Min(float64(claudeImageSide)/float64(max(w, h)), 1); scale < 1 {
w = max(int(math.Round(float64(w)*scale)), 1)
h = max(int(math.Round(float64(h)*scale)), 1)
src = triangleResize(src, w, h)
}
fits := func(b []byte) bool { return base64.StdEncoding.EncodedLen(len(b)) <= claudeImageBase64 }
var out bytes.Buffer
if format == "jpeg" {
err = jpeg.Encode(&out, src, &jpeg.Options{Quality: 85})
if err == nil && fits(out.Bytes()) {
return fitEntry{mime: "image/jpeg", data: out.Bytes()}
}
} else if err = png.Encode(&out, src); err == nil && fits(out.Bytes()) {
return fitEntry{mime: "image/png", data: out.Bytes()}
}
// still over the limit: JPEG, on white where it was clear
flat := image.NewRGBA(src.Bounds())
draw.Draw(flat, flat.Rect, image.NewUniform(color.White), image.Point{}, draw.Src)
draw.Draw(flat, flat.Rect, src, src.Bounds().Min, draw.Over)
for _, q := range []int{75, 60, 40} {
out.Reset()
if jpeg.Encode(&out, flat, &jpeg.Options{Quality: q}) == nil && fits(out.Bytes()) {
return fitEntry{mime: "image/jpeg", data: out.Bytes()}
}
}
return fitEntry{}
}
+151
View File
@@ -0,0 +1,151 @@
package gateway
import (
"bufio"
"bytes"
"encoding/base64"
"encoding/json"
"image"
"image/color"
"image/jpeg"
"image/png"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// tallShot is a screenshot as DeepSeek Harness sends one: a JPEG 400 px
// wide and 8192 tall, within dsh's 2048x2048 pixel budget and 8192 px
// long edge, so dsh passes it byte for byte (sean_80289's case).
func tallShot(t *testing.T, w, h int) string {
t.Helper()
m := image.NewRGBA(image.Rect(0, 0, w, h))
for y := 0; y < h; y++ {
for x := 0; x < w; x++ {
m.Set(x, y, color.RGBA{uint8(x), uint8(y), uint8(x ^ y), 255})
}
}
var b bytes.Buffer
if err := jpeg.Encode(&b, m, &jpeg.Options{Quality: 85}); err != nil {
t.Fatal(err)
}
return base64.StdEncoding.EncodeToString(b.Bytes())
}
func imageSize(t *testing.T, b64 string) (image.Config, string) {
t.Helper()
cfg, format, err := image.DecodeConfig(base64.NewDecoder(base64.StdEncoding, strings.NewReader(b64)))
if err != nil {
t.Fatalf("the image sent can't be read: %v", err)
}
return cfg, format
}
// An earlier turn's image over 8000 px a side went into the transcript a
// run resumes as it came, and the API refused the turn: "API Error: an
// image in the conversation could not be processed and was removed"
// (sean_80289, through DeepSeek Harness). It goes fitted to 2000 px a
// side, as Claude Code fits its own.
func TestClaudeReplayFitsATallImage(t *testing.T) {
h := tuiScriptHarness(t, `[ -f "$file" ] && cp "$file" "$file.seen"`)
img := tallShot(t, 400, 8192)
body := `{"model":"claude-sonnet-5","max_tokens":100,"messages":[` +
`{"role":"user","content":[{"type":"image","source":{"type":"base64","media_type":"image/jpeg","data":"` + img + `"}},{"type":"text","text":"what is it"}]},` +
`{"role":"assistant","content":[{"type":"text","text":"a long page"}]},` +
`{"role":"user","content":"and its title?"}]}`
var u Usage
if code, msg := h.s.serveClaudeSubscription(httptest.NewRecorder(), httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body)), provider.Anthropic, h.p, "claude-sonnet-5", []byte(body), &u); code != 200 {
t.Fatalf("%d %s", code, msg)
}
var run string
for _, l := range h.runs() {
run = l
}
args, _, _ := strings.Cut(run, "\n")
_, sid, ok := strings.Cut(args, "--resume ")
if !ok {
t.Fatalf("the run wasn't given a transcript: %s", args)
}
sid, _, _ = strings.Cut(sid, " ")
seen, _ := filepath.Glob(filepath.Join(h.config, "projects", "*", sid+".jsonl.seen"))
if len(seen) != 1 {
t.Fatalf("no transcript %s", sid)
}
b, err := os.ReadFile(seen[0])
if err != nil {
t.Fatal(err)
}
images := 0
sc := bufio.NewScanner(bytes.NewReader(b))
sc.Buffer(nil, 16<<20)
for sc.Scan() {
var l struct {
Message struct {
Content []struct {
Type string `json:"type"`
Source struct {
MediaType string `json:"media_type"`
Data string `json:"data"`
} `json:"source"`
} `json:"content"`
} `json:"message"`
}
if json.Unmarshal(sc.Bytes(), &l) != nil {
continue
}
for _, c := range l.Message.Content {
if c.Type != "image" {
continue
}
images++
cfg, format := imageSize(t, c.Source.Data)
if cfg.Width > claudeImageSide || cfg.Height > claudeImageSide {
t.Fatalf("the transcript's image is %dx%d, over Claude Code's %d px", cfg.Width, cfg.Height, claudeImageSide)
}
if cfg.Height != 2000 || cfg.Width != 98 {
t.Fatalf("the image wasn't scaled to its own shape: %dx%d", cfg.Width, cfg.Height)
}
if c.Source.MediaType != "image/"+format {
t.Fatalf("media_type %q for a %s", c.Source.MediaType, format)
}
}
}
if images != 1 {
t.Fatalf("%d images in the transcript", images)
}
}
// An image that fits goes as it came, byte for byte; one that can't be
// read goes as it came too.
func TestClaudeImageThatFitsGoesAsItCame(t *testing.T) {
small := tallShot(t, 400, 2000)
if mt, d := claudeImage("image/jpeg", small); mt != "image/jpeg" || d != small {
t.Fatal("an image within 2000 px was written again")
}
if mt, d := claudeImage("image/png", "bm90IGFuIGltYWdl"); mt != "image/png" || d != "bm90IGFuIGltYWdl" {
t.Fatal("bytes that aren't an image were changed")
}
}
// A PNG over the side is scaled and stays a PNG; a tool's image in an MCP
// result is fitted as a message's is.
func TestClaudeImagePNGAndToolResults(t *testing.T) {
m := image.NewNRGBA(image.Rect(0, 0, 3000, 1000))
var b bytes.Buffer
if err := png.Encode(&b, m); err != nil {
t.Fatal(err)
}
wide := base64.StdEncoding.EncodeToString(b.Bytes())
res := mcpResult(Part{Text: "shot", Images: []Part{{MediaType: "image/png", Data: wide}}})
if len(res.Content) != 2 {
t.Fatalf("%d contents", len(res.Content))
}
cfg, format := imageSize(t, res.Content[1]["data"].(string))
if cfg.Width != 2000 || cfg.Height != 667 || format != "png" || res.Content[1]["mimeType"] != "image/png" {
t.Fatalf("the tool's image went as %dx%d %s (%v)", cfg.Width, cfg.Height, format, res.Content[1]["mimeType"])
}
}
+4 -2
View File
@@ -4268,7 +4268,8 @@ func imageBlocks(blocks []map[string]any, text *strings.Builder, p Part) []map[s
}
switch {
case p.Data != "":
blocks = append(blocks, map[string]any{"type": "image", "source": map[string]any{"type": "base64", "media_type": p.MediaType, "data": p.Data}})
mediaType, data := claudeImage(p.MediaType, p.Data)
blocks = append(blocks, map[string]any{"type": "image", "source": map[string]any{"type": "base64", "media_type": mediaType, "data": data}})
case p.URL != "":
blocks = append(blocks, map[string]any{"type": "image", "source": map[string]any{"type": "url", "url": p.URL}})
}
@@ -4813,7 +4814,8 @@ func mcpResult(p Part) mcpToolResult {
for _, im := range p.Images {
switch {
case im.Data != "":
content = append(content, map[string]any{"type": "image", "data": im.Data, "mimeType": imageMediaType(im)})
mimeType, data := claudeImage(imageMediaType(im), im.Data)
content = append(content, map[string]any{"type": "image", "data": data, "mimeType": mimeType})
case im.URL != "":
content = append(content, map[string]any{"type": "text", "text": "[image: " + im.URL + "]"})
}