diff --git a/go.mod b/go.mod index c2d4adb5a..c916dc051 100644 --- a/go.mod +++ b/go.mod @@ -41,6 +41,7 @@ require ( github.com/clipperhouse/stringish v0.1.1 // indirect github.com/dustin/go-humanize v1.0.1 // indirect github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect + github.com/gen2brain/h265 v0.2.4 // indirect github.com/lucasb-eyer/go-colorful v1.3.0 // indirect github.com/mattn/go-colorable v0.1.14 // indirect github.com/mattn/go-isatty v0.0.20 // indirect diff --git a/go.sum b/go.sum index cc6b4dea9..f39547790 100644 --- a/go.sum +++ b/go.sum @@ -36,6 +36,8 @@ github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6 github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM= github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k= github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= +github.com/gen2brain/h265 v0.2.4 h1:JUSbGkRAYZpd7ucCL192yx4ViEo75ZO6OEdm1TQt9qM= +github.com/gen2brain/h265 v0.2.4/go.mod h1:kefpLxLhGpNCUG/q/aabJcD6GqB9Nhet3fNi9xX9Wzw= github.com/go-json-experiment/json v0.0.0-20251027170946-4849db3c2f7e h1:Lf/gRkoycfOBPa42vU2bbgPurFong6zXeFtPoxholzU= github.com/go-json-experiment/json v0.0.0-20251027170946-4849db3c2f7e/go.mod h1:uNVvRXArCGbZ508SxYYTC5v1JWoz2voff5pm25jU1Ok= github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE= diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 830e95b6a..305fa12b4 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -1517,6 +1517,8 @@ func (s *Server) countTokens(w http.ResponseWriter, r *http.Request) { if !ok { return } + // counted as the HEIC photos in it will be sent (heic.go) + body = heicAsJPEG(provider.Anthropic, body) var err error var model string body, model, err = requestModel(body) @@ -1889,6 +1891,9 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro // a client's "off" is magpie's none, for every route and check below // that reads the body's effort (plugins#334) body = offAsNone(from, body) + // a HEIC photo goes as JPEG (or PNG), which every vendor takes, on + // every route below (heic.go) + body = heicAsJPEG(from, body) // the upstream names in force for this request, read once here rather // than once per place a name is looked up below r = withWires(r) diff --git a/internal/gateway/heic.go b/internal/gateway/heic.go new file mode 100644 index 000000000..d52a4fc39 --- /dev/null +++ b/internal/gateway/heic.go @@ -0,0 +1,305 @@ +package gateway + +import ( + "bytes" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "image/jpeg" + "image/png" + "runtime/debug" + "strings" + "sync" + "time" + + "github.com/gen2brain/h265/heic" + + "github.com/yetone/magpie/internal/provider" +) + +// An iPhone's photos are HEIC, and an agent sends one dragged in as it is +// (Pi, Pi Desktop). Most vendors take JPEG, PNG, GIF and WebP only, and +// turn the request away: DeepSeek on WorkBuddy did (qikamatata on X). +// heicAsJPEG writes each HEIC image of a request again as JPEG, or as PNG +// when it has transparency, before anything reads the body, so every +// route has it so: a provider's own, a plugin's fetch, a describer, the +// count of its tokens. It goes by the bytes, not the type the request +// gives them: a HEIC sent as image/jpeg is one too. +// +// The decoder is gen2brain/h265's, pure Go (magpie is built without cgo +// for every system), so it is the same on every computer, and no system +// converter need be there. +// +// A request with no HEIC in it is not walked: mayHoldHEIC is a scan of +// its bytes. An image that can't be read, is too big, or takes too long +// goes as it came, and the vendor says what it says of it. + +// heicBrands are the ftyp brands of an HEVC still (ISO/IEC 23008-12), as +// the decoder registers them. +var heicBrands = []string{"heic", "heix", "heim", "heis", "hevc", "hevx", "hevm", "hevs", "mif1", "msf1"} + +// heicMarks are the base64 of "yp" and a brand: the file's bytes 6 to 11, +// "ftyp" ending at 8, are its base64's characters 8 to 15 wherever the +// file's base64 starts. All begin "eXB". +var heicMarks = func() map[string]bool { + m := map[string]bool{} + for _, b := range heicBrands { + m[base64.StdEncoding.EncodeToString([]byte("yp"+b))] = true + } + return m +}() + +const ( + // a HEIC larger than this goes as it came + heicMaxBase64 = 48 << 20 + // nor is one decoded with more pixels than a 48 MP iPhone photo + heicMaxPixels = 50_000_000 + // past this many pixels, what a conversion held is given back at once + heicFreeAbove = 16_000_000 + // the longest side written: no vendor reads more, and a 24 or 48 MP + // photo written whole would be a JPEG of tens of megabytes + heicMaxSide = 4096 + // what the cache of converted images holds at most + heicCacheBytes = 64 << 20 + heicCacheEntries = 32 +) + +// heicWait is how long a request waits for its image; one not converted +// by then goes as it came, and its conversion, finished, serves the +// request's next turn. +var heicWait = 30 * time.Second + +// heicEncode writes a HEIC image again; a var for tests. +var heicEncode = encodeHEIC + +// mayHoldHEIC is whether the body may have a HEIC in it: an image/heic or +// image/heif type, or the base64 of an HEVC still's ftyp. +func mayHoldHEIC(body []byte) bool { + if bytes.Contains(body, []byte("image/hei")) || bytes.Contains(body, []byte(`image\/hei`)) { + return true + } + for rest := body; ; { + i := bytes.Index(rest, []byte("eXB")) + if i < 0 { + return false + } + if i+8 <= len(rest) && heicMarks[string(rest[i:i+8])] { + return true + } + rest = rest[i+3:] + } +} + +// heicAsJPEG is the body with each HEIC image in it written as JPEG (PNG +// with transparency); the body as it came when there is none. +func heicAsJPEG(proto provider.Protocol, body []byte) []byte { + if !mayHoldHEIC(body) { + return body + } + out, err := walkImages(proto, body, func(im imageAt) (json.RawMessage, error) { + raw := heicOf(im.Src) + if raw == nil { + return nil, nil + } + mime, data := heicConverted(raw) + if data == nil { + return nil, nil + } + return withImageData(proto, im.Block, mime, base64.StdEncoding.EncodeToString(data)), nil + }) + if err != nil { + return body + } + return out +} + +// heicOf is the bytes of a data: URL's image when they are a HEIC's. +func heicOf(src string) []byte { + rest, ok := strings.CutPrefix(src, "data:") + if !ok { + return nil + } + head, b64, ok := strings.Cut(rest, ",") + if !ok || !strings.HasSuffix(head, ";base64") || len(b64) < 16 || len(b64) > heicMaxBase64 { + return nil + } + sniff, err := base64.StdEncoding.DecodeString(b64[:16]) + if err != nil || !isHEIC(sniff) { + return nil + } + raw, err := base64.RawStdEncoding.DecodeString(strings.TrimRight(b64, "=")) + if err != nil { + return nil + } + return raw +} + +// isHEIC is whether b starts as an HEVC still's file does. +func isHEIC(b []byte) bool { + if len(b) < 12 || string(b[4:8]) != "ftyp" { + return false + } + for _, brand := range heicBrands { + if string(b[8:12]) == brand { + return true + } + } + return false +} + +type heicResult struct { + mime string + data []byte // nil: it goes as it came +} + +var heicCache struct { + sync.Mutex + m map[[32]byte]heicResult + order [][32]byte + size int +} + +// heicSlots is how many images are decoded at once: a 48 MP photo holds +// a few hundred megabytes while it is. +var heicSlots = make(chan struct{}, 1) + +// heicConverted is the HEIC raw written again, from the cache when it was +// before: an agent sends its conversation's images on every turn. +func heicConverted(raw []byte) (string, []byte) { + k := sha256.Sum256(raw) + heicCache.Lock() + r, ok := heicCache.m[k] + heicCache.Unlock() + if ok { + return r.mime, r.data + } + done := make(chan heicResult, 1) + go func() { + heicSlots <- struct{}{} + defer func() { <-heicSlots }() + var r heicResult + func() { + defer func() { + if recover() != nil { + r = heicResult{} // the decoder's fault on a bad file + } + }() + r.mime, r.data = heicEncode(raw) + }() + heicKeep(k, r) + done <- r + }() + timer := time.NewTimer(heicWait) + defer timer.Stop() + select { + case r := <-done: + return r.mime, r.data + case <-timer.C: + return "", nil + } +} + +// heicKeep caches r, dropping the oldest past the cache's bounds. +func heicKeep(k [32]byte, r heicResult) { + heicCache.Lock() + defer heicCache.Unlock() + if heicCache.m == nil { + heicCache.m = map[[32]byte]heicResult{} + } + if _, ok := heicCache.m[k]; ok || len(r.data) > heicCacheBytes { + return + } + heicCache.m[k] = r + heicCache.order = append(heicCache.order, k) + heicCache.size += len(r.data) + for len(heicCache.order) > heicCacheEntries || heicCache.size > heicCacheBytes { + old := heicCache.order[0] + heicCache.order = heicCache.order[1:] + heicCache.size -= len(heicCache.m[old].data) + delete(heicCache.m, old) + } +} + +// encodeHEIC decodes a HEIC, turned as it says it is shown, and writes it +// as JPEG, or as PNG when it has transparency; "", nil when it can't. +func encodeHEIC(raw []byte) (string, []byte) { + cfg, err := heic.DecodeConfig(bytes.NewReader(raw)) + if err != nil || cfg.Width <= 0 || cfg.Height <= 0 || int64(cfg.Width)*int64(cfg.Height) > heicMaxPixels { + return "", nil + } + img, err := heic.Decode(bytes.NewReader(raw), heic.Options{AutoRotate: true, FrameSizeLimit: heicMaxPixels}) + if err != nil { + return "", nil + } + if cfg.Width*cfg.Height > heicFreeAbove { + // a 48 MP photo held about a gigabyte while it was written + // again (1.6s on an M5 Pro); what it held goes back to the system + // now, not minutes later + defer debug.FreeOSMemory() + } + if b := img.Bounds(); max(b.Dx(), b.Dy()) > heicMaxSide { + w, h := heicMaxSide, max(1, b.Dy()*heicMaxSide/b.Dx()) + if b.Dy() > b.Dx() { + w, h = max(1, b.Dx()*heicMaxSide/b.Dy()), heicMaxSide + } + img = triangleResize(img, w, h) + } + var out bytes.Buffer + if o, ok := img.(interface{ Opaque() bool }); ok && !o.Opaque() { + if png.Encode(&out, img) != nil { + return "", nil + } + return "image/png", out.Bytes() + } + if jpeg.Encode(&out, img, &jpeg.Options{Quality: 90}) != nil { + return "", nil + } + return "image/jpeg", out.Bytes() +} + +// withImageData is an image block with its data replaced by b64 of mime, +// its other fields as they were; nil when the block can't be read. +func withImageData(proto provider.Protocol, block json.RawMessage, mime, b64 string) json.RawMessage { + var m map[string]json.RawMessage + if decodeJSON(block, &m) != nil { + return nil + } + set := func(field string, values map[string]string) bool { + inner := map[string]json.RawMessage{} + if len(m[field]) > 0 && decodeJSON(m[field], &inner) != nil { + return false + } + for k, v := range values { + inner[k], _ = json.Marshal(v) + } + m[field], _ = json.Marshal(inner) + return true + } + url := "data:" + mime + ";base64," + b64 + switch proto { + case provider.Chat: + var s string + if decodeJSON(m["image_url"], &s) == nil { + m["image_url"], _ = json.Marshal(url) + } else if !set("image_url", map[string]string{"url": url}) { + return nil + } + case provider.Responses: + m["image_url"], _ = json.Marshal(url) + case provider.Anthropic: + if !set("source", map[string]string{"type": "base64", "media_type": mime, "data": b64}) { + return nil + } + case provider.Gemini: + if !set("inlineData", map[string]string{"mimeType": mime, "data": b64}) { + return nil + } + default: + return nil + } + out, err := json.Marshal(m) + if err != nil { + return nil + } + return out +} diff --git a/internal/gateway/heic_test.go b/internal/gateway/heic_test.go new file mode 100644 index 000000000..f515d7090 --- /dev/null +++ b/internal/gateway/heic_test.go @@ -0,0 +1,307 @@ +package gateway + +import ( + "bytes" + "encoding/base64" + "encoding/json" + "image" + "image/jpeg" + "image/png" + "io" + "net/http" + "net/http/httptest" + "os" + "strings" + "sync" + "testing" + "time" + + "github.com/tidwall/gjson" + + "github.com/yetone/magpie/internal/provider" +) + +// testdata/opaque.heic (32x24) and alpha.heic (24x24, transparent around +// an icon) were written by macOS's own encoder, sips -s format heic, as an +// iPhone writes its photos. +func heicFixture(t *testing.T, name string) string { + t.Helper() + b, err := os.ReadFile("testdata/" + name) + if err != nil { + t.Fatal(err) + } + if !isHEIC(b) { + t.Fatalf("%s is not a HEIC", name) + } + return base64.StdEncoding.EncodeToString(b) +} + +// sentImage reads the image a data: URL or bare base64 holds, its type as +// the request says it and as its bytes are. +func sentImage(t *testing.T, mime, b64 string) (image.Image, string) { + t.Helper() + if rest, ok := strings.CutPrefix(b64, "data:"); ok { + head, data, _ := strings.Cut(rest, ",") + mime, b64 = strings.TrimSuffix(head, ";base64"), data + } + raw, err := base64.StdEncoding.DecodeString(b64) + if err != nil { + t.Fatalf("not base64: %v", err) + } + img, format, err := image.Decode(bytes.NewReader(raw)) + if err != nil { + t.Fatalf("sent as %s, not an image: %v", mime, err) + } + if "image/"+format != mime { + t.Fatalf("sent as %s, its bytes are %s", mime, format) + } + return img, mime +} + +// A HEIC goes as JPEG in every request shape that carries an image, its +// block's other fields kept, whatever type the request gave it; one with +// transparency goes as PNG. +func TestHEICGoesAsJPEG(t *testing.T) { + opaque, alpha := heicFixture(t, "opaque.heic"), heicFixture(t, "alpha.heic") + cases := []struct { + name string + proto provider.Protocol + body string + path string // gjson path of the image's base64 or data: URL + mime string // gjson path of its type, when apart from it + kept string // gjson path of a field that must be kept + want string + }{ + {"chat url string", provider.Chat, `{"model":"m","messages":[{"role":"user","content":[{"type":"text","text":"what is it"},{"type":"image_url","image_url":"data:image/heic;base64,` + opaque + `"}]}]}`, + "messages.0.content.1.image_url", "", "messages.0.content.0.text", "image/jpeg"}, + {"chat url object", provider.Chat, `{"model":"m","messages":[{"role":"user","content":[{"type":"image_url","image_url":{"url":"data:image/heic;base64,` + opaque + `","detail":"high"}}]}]}`, + "messages.0.content.0.image_url.url", "", "messages.0.content.0.image_url.detail", "image/jpeg"}, + {"chat heic named jpeg", provider.Chat, `{"model":"m","messages":[{"role":"user","content":[{"type":"image_url","image_url":{"url":"data:image/jpeg;base64,` + opaque + `"}}]}]}`, + "messages.0.content.0.image_url.url", "", "model", "image/jpeg"}, + {"chat tool image", provider.Chat, `{"model":"m","messages":[{"role":"user","content":"look"},{"role":"tool","tool_call_id":"c","content":[{"type":"image_url","image_url":{"url":"data:image/heif;base64,` + opaque + `"}}]}]}`, + "messages.1.content.0.image_url.url", "", "messages.1.tool_call_id", "image/jpeg"}, + {"chat transparent", provider.Chat, `{"model":"m","messages":[{"role":"user","content":[{"type":"image_url","image_url":{"url":"data:image/heic;base64,` + alpha + `"}}]}]}`, + "messages.0.content.0.image_url.url", "", "model", "image/png"}, + {"responses", provider.Responses, `{"model":"m","input":[{"role":"user","content":[{"type":"input_image","image_url":"data:image/heic;base64,` + opaque + `","detail":"auto"}]}]}`, + "input.0.content.0.image_url", "", "input.0.content.0.detail", "image/jpeg"}, + {"responses tool output", provider.Responses, `{"model":"m","input":[{"type":"function_call_output","call_id":"c","output":[{"type":"input_image","image_url":"data:image/heic;base64,` + opaque + `"}]}]}`, + "input.0.output.0.image_url", "", "input.0.call_id", "image/jpeg"}, + {"messages", provider.Anthropic, `{"model":"m","max_tokens":9,"messages":[{"role":"user","content":[{"type":"image","source":{"type":"base64","media_type":"image/heic","data":"` + opaque + `"},"cache_control":{"type":"ephemeral"}}]}]}`, + "messages.0.content.0.source.data", "messages.0.content.0.source.media_type", "messages.0.content.0.cache_control.type", "image/jpeg"}, + {"messages named png", provider.Anthropic, `{"model":"m","max_tokens":9,"messages":[{"role":"user","content":[{"type":"image","source":{"type":"base64","media_type":"image/png","data":"` + opaque + `"}}]}]}`, + "messages.0.content.0.source.data", "messages.0.content.0.source.media_type", "max_tokens", "image/jpeg"}, + {"messages tool_result", provider.Anthropic, `{"model":"m","max_tokens":9,"messages":[{"role":"user","content":[{"type":"tool_result","tool_use_id":"t","content":[{"type":"image","source":{"type":"base64","media_type":"image/heic","data":"` + alpha + `"}}]}]}]}`, + "messages.0.content.0.content.0.source.data", "messages.0.content.0.content.0.source.media_type", "messages.0.content.0.tool_use_id", "image/png"}, + {"gemini", provider.Gemini, `{"contents":[{"role":"user","parts":[{"text":"what"},{"inlineData":{"mimeType":"image/heic","data":"` + opaque + `"}}]}]}`, + "contents.0.parts.1.inlineData.data", "contents.0.parts.1.inlineData.mimeType", "contents.0.parts.0.text", "image/jpeg"}, + {"gemini function response", provider.Gemini, `{"contents":[{"role":"user","parts":[{"functionResponse":{"name":"shot","response":{},"parts":[{"inlineData":{"mimeType":"image/heic","data":"` + opaque + `"}}]}}]}]}`, + "contents.0.parts.0.functionResponse.parts.0.inlineData.data", "contents.0.parts.0.functionResponse.parts.0.inlineData.mimeType", "contents.0.parts.0.functionResponse.name", "image/jpeg"}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + if !mayHoldHEIC([]byte(c.body)) { + t.Fatal("the scan missed the HEIC") + } + out := heicAsJPEG(c.proto, []byte(c.body)) + if !json.Valid(out) { + t.Fatalf("not JSON: %.200s", out) + } + before, after := gjson.Get(c.body, c.kept), gjson.GetBytes(out, c.kept) + if !before.Exists() || before.Raw != after.Raw { + t.Fatalf("%s was %s, is %s", c.kept, before.Raw, after.Raw) + } + mime := "" + if c.mime != "" { + mime = gjson.GetBytes(out, c.mime).Str + } + img, got := sentImage(t, mime, gjson.GetBytes(out, c.path).Str) + if got != c.want { + t.Fatalf("sent as %s, want %s", got, c.want) + } + b := img.Bounds() + if c.want == "image/jpeg" && (b.Dx() != 32 || b.Dy() != 24) { + t.Fatalf("%dx%d, want 32x24", b.Dx(), b.Dy()) + } + if c.want == "image/png" { + if b.Dx() != 24 || b.Dy() != 24 { + t.Fatalf("%dx%d, want 24x24", b.Dx(), b.Dy()) + } + // HEVC's alpha is lossy: near 0, not 0 + if _, _, _, a := img.At(0, 0).RGBA(); a > 0x1000 { + t.Fatalf("the corner's alpha is %#x, want transparent", a) + } + } + if mayHoldHEIC(out) { + t.Fatalf("a HEIC is still in it") + } + }) + } +} + +// What the JPEG shows is the photo: its colours come through the decoder, +// not a blank of the right size. +func TestHEICPixelsKept(t *testing.T) { + out := heicAsJPEG(provider.Chat, []byte(`{"messages":[{"role":"user","content":[{"type":"image_url","image_url":"data:image/heic;base64,`+heicFixture(t, "opaque.heic")+`"}]}]}`)) + img, _ := sentImage(t, "", gjson.GetBytes(out, "messages.0.content.0.image_url").Str) + var lo, hi uint32 = 1 << 16, 0 + for y := 0; y < 24; y++ { + for x := 0; x < 32; x++ { + r, g, b, _ := img.At(x, y).RGBA() + lo, hi = min(lo, r, g, b), max(hi, r, g, b) + } + } + if hi-lo < 1<<12 { + t.Fatalf("the image is flat (%d..%d): nothing was decoded", lo, hi) + } +} + +// A request with no HEIC goes byte for byte as it came: a PNG, a JPEG, an +// image/heic whose bytes are not one, a URL. +func TestNonHEICImageUnchanged(t *testing.T) { + var p, j bytes.Buffer + img := image.NewNRGBA(image.Rect(0, 0, 8, 8)) + png.Encode(&p, img) + jpeg.Encode(&j, img, nil) + pb, jb := base64.StdEncoding.EncodeToString(p.Bytes()), base64.StdEncoding.EncodeToString(j.Bytes()) + for _, c := range []struct { + proto provider.Protocol + body string + }{ + {provider.Chat, `{"model":"m", "messages":[{"role":"user","content":[{"type":"image_url","image_url":"data:image/png;base64,` + pb + `"}]}]}`}, + {provider.Chat, `{"model":"m","messages":[{"role":"user","content":[{"type":"image_url","image_url":{"url":"data:image/heic;base64,` + jb + `"}}]}]}`}, + {provider.Chat, `{"model":"m","messages":[{"role":"user","content":[{"type":"image_url","image_url":{"url":"https://example.com/a.heic"}}]}]}`}, + {provider.Responses, `{"input":[{"role":"user","content":[{"type":"input_image","image_url":"data:image/jpeg;base64,` + jb + `"}]}]}`}, + {provider.Anthropic, `{"messages":[{"role":"user","content":[{"type":"image","source":{"type":"base64","media_type":"image/heic","data":"` + pb + `"}}]}]}`}, + {provider.Gemini, `{"contents":[{"parts":[{"inlineData":{"mimeType":"image/png","data":"` + pb + `"}}]}]}`}, + // the HEIC's base64 as text a user pasted is not an image + {provider.Chat, `{"messages":[{"role":"user","content":"` + heicFixture(t, "opaque.heic") + `"}]}`}, + } { + if out := heicAsJPEG(c.proto, []byte(c.body)); !bytes.Equal(out, []byte(c.body)) { + t.Errorf("%s changed:\n%.300s\nto\n%.300s", c.proto, c.body, out) + } + } +} + +// One that can't be converted goes as it came: a decoder that panics on +// it, one that takes too long, a file cut short. +func TestHEICUnconvertedGoesAsItCame(t *testing.T) { + opaque := heicFixture(t, "opaque.heic") + body := func(b64 string) []byte { + return []byte(`{"messages":[{"role":"user","content":[{"type":"image_url","image_url":"data:image/heic;base64,` + b64 + `"}]}]}`) + } + reset := func() { + heicCache.Lock() + heicCache.m, heicCache.order, heicCache.size = nil, nil, 0 + heicCache.Unlock() + } + reset() + t.Cleanup(reset) + + cut, _ := base64.StdEncoding.DecodeString(opaque) + short := body(base64.StdEncoding.EncodeToString(cut[:len(cut)/2])) + if out := heicAsJPEG(provider.Chat, short); !bytes.Equal(out, short) { + t.Fatalf("a HEIC cut short changed: %.200s", out) + } + + enc := heicEncode + t.Cleanup(func() { heicEncode = enc }) + heicEncode = func([]byte) (string, []byte) { panic("bad file") } + if out := heicAsJPEG(provider.Chat, body(opaque)); !bytes.Equal(out, body(opaque)) { + t.Fatalf("a decoder's panic changed the body: %.200s", out) + } + reset() + + wait := heicWait + t.Cleanup(func() { heicWait = wait }) + heicWait = 50 * time.Millisecond + release := make(chan struct{}) + finished := make(chan struct{}) + heicEncode = func(raw []byte) (string, []byte) { + defer close(finished) + <-release + return enc(raw) + } + if out := heicAsJPEG(provider.Chat, body(opaque)); !bytes.Equal(out, body(opaque)) { + t.Fatalf("a conversion past its wait changed the body: %.200s", out) + } + // finished later, it serves the next turn from the cache + close(release) + <-finished + heicWait = wait + heicEncode = func([]byte) (string, []byte) { t.Error("converted twice"); return "", nil } + deadline := time.Now().Add(10 * time.Second) + for { + heicCache.Lock() + n := len(heicCache.m) + heicCache.Unlock() + if n == 1 || time.Now().After(deadline) { + break + } + time.Sleep(10 * time.Millisecond) + } + out := heicAsJPEG(provider.Chat, body(opaque)) + if _, mime := sentImage(t, "", gjson.GetBytes(out, "messages.0.content.0.image_url").Str); mime != "image/jpeg" { + t.Fatalf("the next turn sent %s", mime) + } +} + +// The HEIC reaches a plugin's fetch as JPEG (WorkBuddy's DeepSeek is +// served by its plugin): through serve, whether the client's API is the +// plugin's or is translated to it. +func TestHEICReachesPluginAsJPEG(t *testing.T) { + t.Setenv("FAKE_SEES", "1") + var mu sync.Mutex + var seen [][]byte + pid := besideFake(t, "fakeco", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + mu.Lock() + seen = append(seen, b) + mu.Unlock() + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, `data: {"id":"c1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"a bridge"},"finish_reason":null}]}`+"\n\n") + io.WriteString(w, `data: {"id":"c1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}`+"\n\ndata: [DONE]\n\n") + })) + opaque := heicFixture(t, "opaque.heic") + h := New().Handler() + for _, c := range []struct{ path, body string }{ + {"/v1/chat/completions", `{"model":"` + pid + `/fake-sees","stream":true,"messages":[{"role":"user","content":[{"type":"text","text":"what is it"},{"type":"image_url","image_url":{"url":"data:image/heic;base64,` + opaque + `"}}]}]}`}, + {"/v1/messages", `{"model":"` + pid + `/fake-sees","max_tokens":100,"messages":[{"role":"user","content":[{"type":"text","text":"what is it"},{"type":"image","source":{"type":"base64","media_type":"image/heic","data":"` + opaque + `"}}]}]}`}, + } { + mu.Lock() + seen = nil + mu.Unlock() + req := httptest.NewRequest("POST", c.path, strings.NewReader(c.body)) + req.Header.Set("Authorization", "Bearer magpie") + rec := httptest.NewRecorder() + h.ServeHTTP(rec, req) + if rec.Code != 200 { + t.Fatalf("%s: %d %s", c.path, rec.Code, rec.Body.String()) + } + mu.Lock() + if len(seen) != 1 { + mu.Unlock() + t.Fatalf("%s: the plugin's fetch was asked %d times", c.path, len(seen)) + } + sent := seen[0] + mu.Unlock() + if mayHoldHEIC(sent) { + t.Fatalf("%s: the plugin was sent the HEIC", c.path) + } + url := "" + gjson.GetBytes(sent, "messages").ForEach(func(_, m gjson.Result) bool { + m.Get("content").ForEach(func(_, part gjson.Result) bool { + if u := part.Get("image_url.url"); u.Exists() { + url = u.Str + } + return true + }) + return true + }) + if url == "" { + t.Fatalf("%s: no image reached the plugin: %.300s", c.path, sent) + } + if _, mime := sentImage(t, "", url); mime != "image/jpeg" { + t.Fatalf("%s: the plugin got %s", c.path, mime) + } + } +} diff --git a/internal/gateway/image_input.go b/internal/gateway/image_input.go index 71c9c02c9..d49d8d539 100644 --- a/internal/gateway/image_input.go +++ b/internal/gateway/image_input.go @@ -57,6 +57,8 @@ type imageAt struct { Src string // Last is set on one in the latest turn, Tool on one a tool gave back. Last, Tool bool + // Block is the image's block as it is in the body. + Block json.RawMessage } // Current is whether the image is one the user gives the model now, which @@ -237,7 +239,7 @@ func swapImageBlocks(proto provider.Protocol, raw json.RawMessage, last, tool bo decodeJSON(block["type"], &kind) src, isImage := imageSrc(proto, kind, block) if isImage { - out, err := swap(imageAt{Src: src, Last: last, Tool: tool}) + out, err := swap(imageAt{Src: src, Last: last, Tool: tool, Block: rawBlock}) if err != nil { return raw, false, err } diff --git a/internal/gateway/testdata/alpha.heic b/internal/gateway/testdata/alpha.heic new file mode 100644 index 000000000..0c8302c38 Binary files /dev/null and b/internal/gateway/testdata/alpha.heic differ diff --git a/internal/gateway/testdata/opaque.heic b/internal/gateway/testdata/opaque.heic new file mode 100644 index 000000000..5b9a1fe75 Binary files /dev/null and b/internal/gateway/testdata/opaque.heic differ diff --git a/internal/plugin/testdata/fake/index.js b/internal/plugin/testdata/fake/index.js index bea188768..b9d6afbbf 100644 --- a/internal/plugin/testdata/fake/index.js +++ b/internal/plugin/testdata/fake/index.js @@ -112,6 +112,9 @@ export const FakePlugin = async ({ client }) => ({ cfg.provider[ID].models["gemini-3-flash-canvas"] = { ...g, name: "Gemini 3 Flash Canvas", modalities: { input: ["text", "image"], output: ["text", "image"] } } cfg.provider[ID].models["imagen-4.0-generate-001"] = { ...g, name: "Imagen 4", modalities: { input: ["text"], output: ["image"] } } } + // $FAKE_SEES: a model on the provider's openai-compatible that takes + // images, as WorkBuddy's plugin serves its models + if (process.env.FAKE_SEES) cfg.provider[ID].models["fake-sees"] = { name: "Fake Sees", modalities: { input: ["text", "image"], output: ["text"] }, limit: { context: 1000, output: 100 } } // $FAKE_DEEPSEEK: a DeepSeek model, as Cline's cline-pass/deepseek-v4-pro if (process.env.FAKE_DEEPSEEK) cfg.provider[ID].models["deepseek-v4-pro"] = { name: "DeepSeek V4 Pro", limit: { context: 1000, output: 100 } } // $FAKE_GLM: a GLM model, as Cline's cline-pass/glm-5.3