diff --git a/internal/gateway/codex_images.go b/internal/gateway/codex_images.go index c2e0554ce..e7c2e844b 100644 --- a/internal/gateway/codex_images.go +++ b/internal/gateway/codex_images.go @@ -2,17 +2,23 @@ package gateway import ( "bytes" + "container/list" "crypto/sha256" "encoding/base64" - "fmt" + "encoding/binary" "image" "image/draw" "image/gif" "image/jpeg" "image/png" + "io" "math" + "runtime" + "slices" "strings" "sync" + "sync/atomic" + "time" "github.com/tidwall/gjson" @@ -37,61 +43,153 @@ func codexImagesFit(p provider.Provider, to provider.Protocol, body []byte) []by if p.Account == nil || p.Account.Agent != "codex" || to != provider.Responses || !bytes.Contains(body, []byte(`input_image`)) { return body } - type swap struct { - at, end int - with string - } - var swaps []swap - var with []int // the input items with an image in them - i := 0 + // One walk of the body: each input item, and the parts of the items + // with an image in them, read where they sit. Looking each part up + // again by its path from the top read the body from its start for + // every image: in a Computer Use turn of 160 screenshots, gigabytes of + // JSON read for one request (fflake33, Discord). + var jobs []fitJob gjson.GetBytes(body, "input").ForEach(func(_, item gjson.Result) bool { - if strings.Contains(item.Raw, "input_image") { - with = append(with, i) + if !strings.Contains(item.Raw, "input_image") { + return true } - i++ + item.ForEach(func(key, parts gjson.Result) bool { + if key.Str != "content" && key.Str != "output" || !parts.IsArray() { + return true + } + parts.ForEach(func(_, part gjson.Result) bool { + // the part's members read once, not once for each + var kind, detail, url gjson.Result + part.ForEach(func(k, v gjson.Result) bool { + // the first of a key given twice, as Get reads it + switch { + case k.Str == "type" && !kind.Exists(): + kind = v + case k.Str == "detail" && !detail.Exists(): + detail = v + case k.Str == "image_url" && !url.Exists(): + url = v + } + return true + }) + if kind.String() != "input_image" { + return true + } + end := url.Index + len(url.Raw) + if url.Type != gjson.String || url.Index <= 0 || end > len(body) || string(body[url.Index:end]) != url.Raw || !strings.HasPrefix(url.Str, "data:") { + return true + } + if limits, ok := codexImageLimits(detail.String()); ok { + jobs = append(jobs, fitJob{at: url.Index, end: end, url: url.Str, l: limits}) + } + return true + }) + return true + }) return true }) - for _, i := range with { - for _, key := range []string{"content", "output"} { - parts := gjson.GetBytes(body, fmt.Sprintf("input.%d.%s", i, key)) - if !parts.IsArray() { - continue - } - for j := range parts.Array() { - part := gjson.GetBytes(body, fmt.Sprintf("input.%d.%s.%d", i, key, j)) - if part.Get("type").String() != "input_image" { - continue - } - url := gjson.GetBytes(body, fmt.Sprintf("input.%d.%s.%d.image_url", i, key, j)) - if url.Type != gjson.String || url.Index <= 0 || !strings.HasPrefix(url.Str, "data:") { - continue - } - limits, ok := codexImageLimits(part.Get("detail").String()) - if !ok { - continue - } - if fit, ok := codexImageFit(url.Str, limits); ok { - swaps = append(swaps, swap{url.Index, url.Index + len(url.Raw), `"` + fit + `"`}) - } - } - } - } - if len(swaps) == 0 { + if len(jobs) == 0 { return body } + fitAll(jobs) + slices.SortFunc(jobs, func(a, b fitJob) int { return a.at - b.at }) // the rest of the request goes byte for byte as it came, for the // prompt cache var out bytes.Buffer - last := 0 - for _, s := range swaps { - out.Write(body[last:s.at]) - out.WriteString(s.with) - last = s.end + last, swapped := 0, false + for _, j := range jobs { + if !j.changed || j.at < last { + continue + } + if !swapped { + out.Grow(len(body)) + swapped = true + } + out.Write(body[last:j.at]) + out.WriteByte('"') + out.WriteString(j.with) + out.WriteByte('"') + last = j.end + } + if !swapped { + return body } out.Write(body[last:]) return out.Bytes() } +// fitJob is one image of a request: where its data URL's JSON string +// sits, the URL, the limits it is fitted to, and what it is sent as. +type fitJob struct { + at, end int + url string + l imageLimits + key [32]byte + with string + changed bool +} + +// fitWorkers is how many images of a request are made again at once: +// each holds a decoded screenshot and its resize, near 100 MB for a +// Retina one. +const fitWorkers = 4 + +// fitAll fits each job's image: as it was kept (fitted), or else made +// again, the images not kept made side by side. +func fitAll(jobs []fitJob) { + fitted.letGo() + var todo []int + for i := range jobs { + j := &jobs[i] + comma := strings.IndexByte(j.url, ',') + if comma < 0 || !strings.HasSuffix(j.url[:comma], ";base64") { + continue + } + j.key = fitKey(j.url, j.l) + if e, ok := fitted.get(j.key); ok { + j.with, j.changed = e.url(), e.data != nil + continue + } + todo = append(todo, i) + } + if len(todo) == 0 { + return + } + // the same screenshot twice in a request is made once + made := map[[32]byte]*fitEntry{} + var order []int + for _, i := range todo { + if _, ok := made[jobs[i].key]; !ok { + made[jobs[i].key] = &fitEntry{} + order = append(order, i) + } + } + next := make(chan int) + var wg sync.WaitGroup + for range min(fitWorkers, runtime.GOMAXPROCS(0), len(order)) { + wg.Add(1) + go func() { + defer wg.Done() + for i := range next { + j := jobs[i] + *made[j.key] = codexImageRefit(j.url[strings.IndexByte(j.url, ',')+1:], j.l) + } + }() + } + for _, i := range order { + next <- i + } + close(next) + wg.Wait() + for _, i := range order { + fitted.put(jobs[i].key, *made[jobs[i].key]) + } + for _, i := range todo { + e := made[jobs[i].key] + jobs[i].with, jobs[i].changed = e.url(), e.data != nil + } +} + type imageLimits struct{ side, patches int } // codexPatch is the patch a Responses model reads an image in. @@ -138,52 +236,130 @@ func (l imageLimits) size(w, h int) (int, int) { // to hold: one past it goes as it came. const codexImageMaxPixels = 80 << 20 -// fitted holds what codexImageFit made of the images a conversation -// sends again on every turn. -var fitted = struct { - sync.Mutex - m map[[32]byte]string -}{m: map[[32]byte]string{}} - -// codexImageFit is a data URL's image as Codex's client would send it, -// and whether that differs from what came. -func codexImageFit(url string, l imageLimits) (string, bool) { - comma := strings.IndexByte(url, ',') - if comma < 0 || !strings.HasSuffix(url[:comma], ";base64") { - return "", false - } - key := sha256.Sum256([]byte(fmt.Sprint(l.side, l.patches, url))) - fitted.Lock() - got, ok := fitted.m[key] - fitted.Unlock() - if ok { - return got, got != "" - } - got = codexImageRefit(url[comma+1:], l) - fitted.Lock() - if len(fitted.m) >= 64 { - clear(fitted.m) - } - fitted.m[key] = got - fitted.Unlock() - return got, got != "" +// fitEntry is what an image is sent as: data in mime, or, with no data, +// the image as it came. +type fitEntry struct { + mime string + data []byte } -// codexImageRefit is the data URL of an image's base64 resized and -// written again, or "" when it goes as it came. -func codexImageRefit(b64 string, l imageLimits) string { +// url is the entry's data URL, or "" for the image as it came. +func (e fitEntry) url() string { + if e.data == nil { + return "" + } + return "data:" + e.mime + ";base64," + base64.StdEncoding.EncodeToString(e.data) +} + +// fitKey names an image's data URL fitted to l. +func fitKey(url string, l imageLimits) [32]byte { + h := sha256.New() + var n [16]byte + binary.LittleEndian.PutUint64(n[:8], uint64(l.side)) + binary.LittleEndian.PutUint64(n[8:], uint64(l.patches)) + h.Write(n[:]) + io.WriteString(h, url) + var k [32]byte + h.Sum(k[:0]) + return k +} + +// fitted holds what codexImageRefit made of the images a conversation +// sends again on every turn, so that a past screenshot is decoded, resized +// and encoded once, not on each turn. It is bounded by the bytes it holds +// (fittedBudget), dropping the least recently used first, and drops what +// no request has sent for fittedIdle. The 64-entry map it replaces was +// cleared when full, so past 64 screenshots every turn made each of them +// again (fflake33, Discord). +// +// A request looks up all its images before it keeps any it made, so a +// conversation larger than the budget still finds the images kept since +// its last turn, rather than dropping each just before it is sent again. +var fitted = &fitCache{m: map[[32]byte]*list.Element{}} + +// fittedBudget is how many bytes of fitted images are kept, and +// fittedIdle how long one is kept unsent. fittedMost bounds the entries, +// as most images go as they came and hold no bytes. +var ( + fittedBudget = 256 << 20 + fittedIdle = time.Hour + fittedMost = 8192 +) + +type fitCache struct { + sync.Mutex + m map[[32]byte]*list.Element + order list.List // of *fitItem, the most recently used first + bytes int +} + +type fitItem struct { + key [32]byte + e fitEntry + used time.Time +} + +// letGo drops what has gone unsent for fittedIdle. +func (c *fitCache) letGo() { + c.Lock() + defer c.Unlock() + now := time.Now() + for back := c.order.Back(); back != nil && now.Sub(back.Value.(*fitItem).used) > fittedIdle; back = c.order.Back() { + c.drop(back) + } +} + +func (c *fitCache) get(k [32]byte) (fitEntry, bool) { + c.Lock() + defer c.Unlock() + el, ok := c.m[k] + if !ok { + return fitEntry{}, false + } + it := el.Value.(*fitItem) + it.used = time.Now() + c.order.MoveToFront(el) + return it.e, true +} + +func (c *fitCache) put(k [32]byte, e fitEntry) { + c.Lock() + defer c.Unlock() + if _, ok := c.m[k]; ok || len(e.data) > fittedBudget { + return + } + for c.bytes+len(e.data) > fittedBudget || len(c.m) >= fittedMost { + c.drop(c.order.Back()) + } + c.m[k] = c.order.PushFront(&fitItem{key: k, e: e, used: time.Now()}) + c.bytes += len(e.data) +} + +func (c *fitCache) drop(el *list.Element) { + it := c.order.Remove(el).(*fitItem) + delete(c.m, it.key) + c.bytes -= len(it.e.data) +} + +// refits counts the images codexImageRefit decodes and writes again. +var refits atomic.Int64 + +// codexImageRefit is an image's base64 resized and written again, or an +// entry with no data when it goes as it came. +func codexImageRefit(b64 string, l imageLimits) fitEntry { raw, err := base64.StdEncoding.DecodeString(b64) if err != nil { - return "" + return fitEntry{} } cfg, format, err := image.DecodeConfig(bytes.NewReader(raw)) if err != nil || cfg.Width*cfg.Height > codexImageMaxPixels { - return "" + return fitEntry{} } w, h := l.size(cfg.Width, cfg.Height) if w == cfg.Width && h == cfg.Height && format != "gif" { - return "" + return fitEntry{} } + refits.Add(1) var src image.Image switch format { case "png": @@ -193,10 +369,10 @@ func codexImageRefit(b64 string, l imageLimits) string { case "gif": src, err = gif.Decode(bytes.NewReader(raw)) default: - return "" + return fitEntry{} } if err != nil { - return "" + return fitEntry{} } if w != cfg.Width || h != cfg.Height { src = triangleResize(src, w, h) @@ -210,9 +386,9 @@ func codexImageRefit(b64 string, l imageLimits) string { err = png.Encode(&out, src) } if err != nil { - return "" + return fitEntry{} } - return "data:" + mime + ";base64," + base64.StdEncoding.EncodeToString(out.Bytes()) + return fitEntry{mime: mime, data: out.Bytes()} } // triangleResize scales src to w by h with a triangle (linear) filter diff --git a/internal/gateway/codex_images_test.go b/internal/gateway/codex_images_test.go index 47b381868..4c0e815cf 100644 --- a/internal/gateway/codex_images_test.go +++ b/internal/gateway/codex_images_test.go @@ -2,8 +2,10 @@ package gateway import ( "bytes" + "container/list" "encoding/base64" "encoding/json" + "fmt" "image" "image/color" "image/jpeg" @@ -14,6 +16,7 @@ import ( "net/http/httptest" "strings" "testing" + "time" "github.com/tidwall/gjson" @@ -265,3 +268,133 @@ func TestCodexAccountGetsScreenshotAtCodexSize(t *testing.T) { } t.Logf("%d bytes from the agent, %d to ChatGPT", len(body), len(got)) } + +// freshFitted gives a test a cache of fitted images of its own, with +// budget bytes, and counts the images made again from here. +func freshFitted(t *testing.T, budget int) func() int64 { + t.Helper() + was, wasBudget := fitted, fittedBudget + fitted, fittedBudget = &fitCache{m: map[[32]byte]*list.Element{}}, budget + t.Cleanup(func() { fitted, fittedBudget = was, wasBudget }) + from := refits.Load() + return func() int64 { return refits.Load() - from } +} + +// computerUseRequest is a Responses turn with each of shots as a +// Computer Use tool's screenshot, as Codex sends a conversation's every +// past screenshot again on each turn. +func computerUseRequest(shots []string) []byte { + var input []any + for i, shot := range shots { + id := fmt.Sprintf("call_%d", i) + input = append(input, + map[string]any{"type": "function_call", "call_id": id, "name": "computer", "arguments": `{"action":"screenshot"}`}, + map[string]any{"type": "function_call_output", "call_id": id, "output": []any{ + map[string]any{"type": "input_image", "image_url": shot}}}) + } + b, _ := json.Marshal(map[string]any{"model": "gpt-5.5", "stream": true, "input": input}) + return b +} + +// wideShots are n distinct PNGs wider than Codex sends, each made +// smaller once it is fitted: cheap to make, as a test needs. +func wideShots(t *testing.T, n int) []string { + t.Helper() + out := make([]string, n) + for i := range out { + m := image.NewRGBA(image.Rect(0, 0, 2100, 4)) + for x := 0; x < 2100; x++ { + m.SetRGBA(x, i%4, color.RGBA{byte(i), byte(i >> 8), byte(x), 255}) + } + out[i] = shotURL(t, m, "png") + } + return out +} + +// A long Computer Use conversation (fflake33, Discord: hundreds of +// screenshots) sends every past screenshot again on each turn. Each is +// decoded, resized and written again once; the next turn makes only its +// new one, past the 64 images the cache held, and sends the others as the +// same bytes as before, which the prompt cache needs. +func TestCodexScreenshotsAreNotFittedAgainEachTurn(t *testing.T) { + made := freshFitted(t, fittedBudget) + shots := wideShots(t, 101) + first := codexImagesFit(codexAccount(), provider.Responses, computerUseRequest(shots[:100])) + if n := made(); n != 100 { + t.Fatalf("the first turn made %d images, want 100", n) + } + next := codexImagesFit(codexAccount(), provider.Responses, computerUseRequest(shots)) + if n := made() - 100; n != 1 { + t.Errorf("the next turn made %d images again, want only its new one", n) + } + for i := range 100 { + path := fmt.Sprintf("input.%d.output.0.image_url", 2*i+1) + was, now := gjson.GetBytes(first, path).String(), gjson.GetBytes(next, path).String() + if was == shots[i] || now != was { + t.Fatalf("screenshot %d: not the same fitted bytes on the next turn", i) + } + } + m, _ := shotDecode(t, gjson.GetBytes(next, "input.201.output.0.image_url").String()) + if m.Bounds().Dx() != 2048 { + t.Errorf("the new screenshot went at %v", m.Bounds()) + } +} + +// Past what the cache may hold, each turn still finds the screenshots kept +// since the last and makes only the rest again. Keeping each image as it +// is made, in a conversation whose images come in the same order each +// turn, would drop each one just before it is sent again and find none. +// What is held stays within the budget. +func TestCodexFittedImagesPastTheBudget(t *testing.T) { + shots := wideShots(t, 30) + one := len(fitKeyEntry(t, shots[0]).data) + made := freshFitted(t, 10*one+one/2) + body := computerUseRequest(shots) + was := int64(0) + for turn := 1; turn <= 3; turn++ { + codexImagesFit(codexAccount(), provider.Responses, body) + n := made() - was + was += n + if turn == 1 && n != 30 || turn > 1 && n != 20 { + t.Errorf("turn %d made %d of 30 images, with 10 kept", turn, n) + } + fitted.Lock() + held := fitted.bytes + fitted.Unlock() + if held > fittedBudget { + t.Errorf("turn %d: %d bytes held, past the budget of %d", turn, held, fittedBudget) + } + } +} + +// fitKeyEntry is shot fitted to Codex's high limits, made directly. +func fitKeyEntry(t *testing.T, shot string) fitEntry { + t.Helper() + e := codexImageRefit(shot[strings.IndexByte(shot, ',')+1:], imageLimits{2048, 2500}) + if e.data == nil { + t.Fatal("the screenshot fits as it came") + } + return e +} + +// What no request has sent for fittedIdle is let go. +func TestCodexFittedImagesLetGoWhenIdle(t *testing.T) { + made := freshFitted(t, fittedBudget) + shots := wideShots(t, 2) + codexImagesFit(codexAccount(), provider.Responses, computerUseRequest(shots[:1])) + fitted.Lock() + for el := fitted.order.Front(); el != nil; el = el.Next() { + el.Value.(*fitItem).used = time.Now().Add(-fittedIdle - time.Minute) + } + fitted.Unlock() + codexImagesFit(codexAccount(), provider.Responses, computerUseRequest(shots[1:])) + fitted.Lock() + n, held := len(fitted.m), fitted.bytes + fitted.Unlock() + if n != 1 || made() != 2 { + t.Errorf("%d kept after the first went idle, %d made", n, made()) + } + if want := len(fitKeyEntry(t, shots[1]).data); held != want { + t.Errorf("%d bytes held, want %d", held, want) + } +} diff --git a/internal/gateway/codex_images_timing_test.go b/internal/gateway/codex_images_timing_test.go new file mode 100644 index 000000000..1d08b5f62 --- /dev/null +++ b/internal/gateway/codex_images_timing_test.go @@ -0,0 +1,203 @@ +package gateway + +import ( + "bytes" + "context" + "encoding/base64" + "encoding/json" + "fmt" + "image" + "image/jpeg" + "io" + "math/rand/v2" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "runtime/pprof" + "strings" + "sync" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// computerUseShots are n distinct w×h JPEG screenshots as data URLs: a +// desktop with noise along its top, so each is as large as a real one, +// and a stamp that makes each its own. +func computerUseShots(n, w, h int) []string { + base := shotImage(w, h) + noise := rand.New(rand.NewPCG(3, 4)) + for i := 0; i < 200*base.Stride; i++ { + if i%4 != 3 { + base.Pix[i] = byte(noise.Uint32()) + } + } + out := make([]string, n) + var wg sync.WaitGroup + sem := make(chan struct{}, 8) + for i := range n { + wg.Add(1) + sem <- struct{}{} + go func() { + defer wg.Done() + defer func() { <-sem }() + m := image.NewRGBA(base.Rect) + copy(m.Pix, base.Pix) + for y := 300; y < 364; y++ { + for x := 0; x < 64; x++ { + o := y*m.Stride + (x+(i%40)*64)*4 + m.Pix[o], m.Pix[o+1], m.Pix[o+2] = byte(i), byte(i*7), byte(i*13) + } + } + var b bytes.Buffer + jpeg.Encode(&b, m, &jpeg.Options{Quality: 85}) + out[i] = "data:image/jpeg;base64," + base64.StdEncoding.EncodeToString(b.Bytes()) + }() + } + wg.Wait() + return out +} + +// computerUseTurn is a long Computer Use conversation as Codex sends it on +// the Responses API: each step a user or assistant message, a tool call +// and the tool's output with its screenshot. +func computerUseTurn(model string, shots []string) []byte { + para := strings.Repeat("Clicked the button in the toolbar, waited for the sheet and read what it says. ", 30) + var input []any + for i, shot := range shots { + id := fmt.Sprintf("call_%04d", i) + input = append(input, + map[string]any{"type": "message", "role": "user", "content": []any{map[string]any{"type": "input_text", "text": para}}}, + map[string]any{"type": "message", "role": "assistant", "content": []any{map[string]any{"type": "output_text", "text": para}}}, + map[string]any{"type": "function_call", "call_id": id, "name": "computer", "arguments": `{"action":"screenshot"}`}, + map[string]any{"type": "function_call_output", "call_id": id, "output": []any{ + map[string]any{"type": "input_text", "text": "screenshot taken"}, + map[string]any{"type": "input_image", "image_url": shot}}}, + ) + } + input = append(input, map[string]any{"type": "message", "role": "user", "content": []any{map[string]any{"type": "input_text", "text": "go on"}}}) + b, _ := json.Marshal(map[string]any{"model": model, "stream": true, "instructions": para, "input": input}) + return b +} + +// turnTimer stands in for an upstream that answers at once, and notes when +// each request reached it: the time from the agent's request to then is +// magpie's own work on it, the upload to a local server aside. +type turnTimer struct { + mu sync.Mutex + arrived time.Time +} + +func (tt *turnTimer) handler(w http.ResponseWriter, r *http.Request) { + tt.mu.Lock() + tt.arrived = time.Now() + tt.mu.Unlock() + io.Copy(io.Discard, r.Body) + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, sse( + `data: {"type":"response.created","response":{"id":"r1","model":"gpt-6.1-sol"}}`, + `data: {"type":"response.output_text.delta","delta":"ok"}`, + `data: {"type":"response.completed","response":{"id":"r1","status":"completed","output":[],"usage":{"input_tokens":7,"output_tokens":2}}}`)) +} + +// turn sends body to s and says how long magpie took before the upstream +// had it, and in all. Its CPU profile samples carry the label turn=name, +// for pprof's -tagfocus: on a loaded machine the time a turn's work took +// says more than how long it waited. +func (tt *turnTimer) turn(t *testing.T, s *Server, body []byte, name string) (local, all time.Duration) { + t.Helper() + start := time.Now() + rec := httptest.NewRecorder() + pprof.Do(context.Background(), pprof.Labels("turn", name), func(context.Context) { + s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/responses", bytes.NewReader(body))) + }) + all = time.Since(start) + if rec.Code != 200 { + t.Fatalf("status %d: %.300s", rec.Code, rec.Body.String()) + } + tt.mu.Lock() + defer tt.mu.Unlock() + return tt.arrived.Sub(start), all +} + +// TestComputerUseTurnTiming times magpie's own work on a long Computer +// Use turn to a ChatGPT account, as fflake33's (Discord): the first turn, +// and the next, which sends every past screenshot again. Run it with +// MAGPIE_TURN_TIMING=1 (and -cpuprofile/-memprofile to see where). +func TestComputerUseTurnTiming(t *testing.T) { + if os.Getenv("MAGPIE_TURN_TIMING") == "" { + t.Skip("MAGPIE_TURN_TIMING=1 times a long Computer Use turn") + } + codexSignedIn(t) + tt := &turnTimer{} + up := httptest.NewServer(http.HandlerFunc(tt.handler)) + t.Cleanup(up.Close) + was := provider.CodexBase + provider.CodexBase = up.URL + "/backend-api/codex" + t.Cleanup(func() { provider.CodexBase = was }) + + n := 160 + fmt.Sscan(os.Getenv("MAGPIE_TURN_SHOTS"), &n) + start := time.Now() + shots := computerUseShots(n+3, 2940, 1912) + t.Logf("%d screenshots made in %v", n+3, time.Since(start)) + s := New() + for turn := 1; turn <= 4; turn++ { + // each turn adds a screenshot to those sent before + body := computerUseTurn("codex/gpt-5.5", shots[:n+turn-1]) + local, all := tt.turn(t, s, body, fmt.Sprint(turn)) + t.Logf("turn %d: %d images, %d MB: magpie %v before the upstream had it, %v in all", turn, n+turn-1, len(body)>>20, local, all) + } +} + +// TestCopilotLongTurnTiming times magpie's own work on a long Codex turn +// with no images to a Copilot account (echo_ts, Discord). Run it with +// MAGPIE_TURN_TIMING=1. +func TestCopilotLongTurnTiming(t *testing.T) { + if os.Getenv("MAGPIE_TURN_TIMING") == "" { + t.Skip("MAGPIE_TURN_TIMING=1 times a long Copilot turn") + } + fresh(t) + cfg := os.Getenv("XDG_CONFIG_HOME") + os.MkdirAll(filepath.Join(cfg, "github-copilot"), 0o755) + os.WriteFile(filepath.Join(cfg, "github-copilot", "apps.json"), mustJSON(map[string]any{ + "github.com:Iv1.x": map[string]any{"user": "echo", "oauth_token": "gho_timing"}, + }), 0o600) + tt := &turnTimer{} + api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/models" { + io.WriteString(w, `{"data":[{"id":"gpt-6.1-sol","name":"GPT-6.1 Sol","model_picker_enabled":true,"policy":{"state":"enabled"},"supported_endpoints":["/responses"],"capabilities":{"type":"chat","supports":{"reasoning_effort":["low","medium","high"]}}}]}`) + return + } + tt.handler(w, r) + })) + t.Cleanup(api.Close) + gh := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.HasSuffix(r.URL.Path, "/token") { + json.NewEncoder(w).Encode(map[string]any{"token": "sess", "expires_at": time.Now().Add(time.Hour).Unix(), "endpoints": map[string]string{"api": api.URL}}) + return + } + io.WriteString(w, `{"copilot_plan":"individual","access_type_sku":"monthly_subscriber_quota"}`) + })) + t.Cleanup(gh.Close) + oldTok, oldUser := provider.CopilotTokenURL, provider.CopilotUserURL + provider.CopilotTokenURL, provider.CopilotUserURL = gh.URL+"/token", gh.URL+"/user" + t.Cleanup(func() { provider.CopilotTokenURL, provider.CopilotUserURL = oldTok, oldUser }) + p, err := provider.Find("copilot") + if err != nil { + t.Fatal(err) + } + if _, err := p.Fetch(context.Background()); err != nil { + t.Fatal(err) + } + s := New() + for _, words := range []int{2_000, 30_000, 150_000} { + body := largeConversation(provider.Responses, "copilot/gpt-6.1-sol", words) + for turn := 1; turn <= 3; turn++ { + local, all := tt.turn(t, s, body, fmt.Sprintf("%dk-%d", words/1000, turn)) + t.Logf("%d KB, turn %d: magpie %v before the upstream had it, %v in all", len(body)>>10, turn, local, all) + } + } +} diff --git a/internal/gateway/vision.go b/internal/gateway/vision.go index c3a4b8b53..cefc225d7 100644 --- a/internal/gateway/vision.go +++ b/internal/gateway/vision.go @@ -9,6 +9,7 @@ import ( "fmt" "net/http" "net/http/httptest" + "slices" "strings" "sync" "time" @@ -46,9 +47,11 @@ var visionTimeout, visionWaitMost = 3 * time.Minute, 10 * time.Minute // visionParallel is how many images of a request are described at once. const visionParallel = 4 -// sightsKept is how many descriptions are kept: an agent sends a -// conversation's images again every turn. -const sightsKept = 256 +// sightsKept is how many descriptions are kept, the least recently used +// dropped first: an agent sends a conversation's images again every turn, +// and a long Computer Use one holds hundreds of screenshots (fflake33). +// A description is a few kilobytes. +const sightsKept = 2048 const visionSystem = `You describe images for an AI model that cannot see them. It will answer the user from your description alone, so leave nothing out that it may need. - Transcribe all text exactly as written, keeping its layout: code, terminal output, error messages, logs, UI labels, menus, file names, numbers. @@ -292,6 +295,12 @@ func (s *Server) describe(ctx context.Context, model, src string) (string, error key := hex.EncodeToString(sum[:]) s.sightMu.Lock() if e, ok := s.sights[key]; ok { + // used again, so the last to go: a long conversation's first + // images, still sent every turn, outlast those of conversations + // that have ended + if i := slices.Index(s.sightOrder, key); i >= 0 { + s.sightOrder = append(append(s.sightOrder[:i:i], s.sightOrder[i+1:]...), key) + } s.sightMu.Unlock() select { case <-e.done: diff --git a/internal/gateway/vision_test.go b/internal/gateway/vision_test.go index 0f2a55490..427244f99 100644 --- a/internal/gateway/vision_test.go +++ b/internal/gateway/vision_test.go @@ -1,6 +1,8 @@ package gateway import ( + "encoding/base64" + "fmt" "io" "net/http" "net/http/httptest" @@ -211,3 +213,27 @@ func TestSeerPicksAModelThatSees(t *testing.T) { t.Fatal("seer with vision off") } } + +// A long conversation sends every past screenshot again on each turn +// (fflake33, Discord: hundreds of them). Each is described once, not again +// on the next turn once there are more than 256. +func TestManyImagesDescribedOnce(t *testing.T) { + s, u := eyed(t) + const n = 300 + var parts []string + for i := range n { + img := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("screenshot %d", i))) + parts = append(parts, `{"type":"input_image","image_url":"data:image/png;base64,`+img+`"}`) + } + body := `{"model":"probe/text","input":[{"role":"user","content":[{"type":"input_text","text":"read"},` + strings.Join(parts, ",") + `]}]}` + for turn := 1; turn <= 2; turn++ { + rec := httptest.NewRecorder() + s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/responses", strings.NewReader(body))) + if rec.Code != 200 { + t.Fatalf("turn %d: %d %.300s", turn, rec.Code, rec.Body.String()) + } + } + if got := len(u.sent("eye")); got != n { + t.Fatalf("%d images described %d times over two turns, want each once", n, got) + } +}