Commit Graph
9 Commits
Author SHA1 Message Date
yetone d614f21721 gateway: a HEIC photo goes to the vendor as JPEG, or PNG with alpha (qikamatata on X)
Pi and Pi Desktop send an iPhone photo dragged in as image/heic, and
DeepSeek flash on WorkBuddy (a plugin's fetch) turned it away; most
vendors take JPEG, PNG, GIF and WebP only.

What: heicAsJPEG (heic.go) runs at the top of Server.serve, after
offAsNone, so every route below sees the converted image: a provider's
own, a plugin's fetch, the describer, every translation. count_tokens
does the same. It walks images through walkImages, the one image walker,
so it covers Chat image_url (string or object), Responses input_image,
Anthropic image blocks and Gemini inlineData, tool results included. It
goes by the bytes (ftyp + an HEVC still's brand), so a HEIC labelled
image/jpeg or image/png is converted too, and a JPEG labelled heic is
left alone. Other fields of the block (detail, cache_control) are kept.
Transparent images go as PNG, opaque ones as JPEG q90.

Cost: a body with no "image/hei" and no base64 ftyp mark ("eXB" + 5
chars, at the same place in any base64 that starts at the file) is not
walked. Caps: 48 MB of base64, 50 MP, the long side written at 4096 px,
one decode at a time, 30 s wait (a late result is cached for the next
turn), a 64 MB / 32 entry cache by sha256, since agents resend a
conversation's images every turn. Any failure, panic included, leaves
the image as it came. Measured on mote (M5 Pro): 12 MP 0.44 s, 24 MP
0.86 s, 48 MP 1.6 s / ~1 GB held, freed at once with FreeOSMemory.

Why gen2brain/h265 v0.2.4: pure Go (release builds are CGO_ENABLED=0),
MIT, no dependencies, SIMD on amd64 and arm64, maintained (latest
2026-10-29). Not chosen: gen2brain/heic (wazero WASM or a libheif dylib
through purego), jdeng/goheif (cgo libde265), OS converters (Windows
needs the paid HEVC extension, Linux tools are often missing).

Tests (heic_test.go, fixtures made on mote with sips, 1.6 KB each):
12 shapes converted with their kept fields, pixels kept, 7 non-HEIC
cases byte-identical, a cut file / a panicking decoder / a timeout go
as they came, and a plugin's fetch (fake plugin, new FAKE_SEES image
model) gets JPEG on /v1/chat/completions and /v1/messages.

Run at this tree (733fac48f + this change), on mote:
- gofmt -l internal: clean
- GOOS=darwin/linux/windows go vet -tags nogui ./internal/gateway
  ./internal/plugin: ok
- CGO_ENABLED=0 go build ./internal/gateway for darwin, linux, windows
  x amd64, arm64: ok
- go test ./internal/gateway ./internal/plugin -count=1 -timeout 45m:
  ok (774s, 134s)
- win-run (Windows amd64) and wsl-run (Linux amd64, AVX2 path):
  go test ./internal/gateway -run HEIC: ok

Broken by hand, each red, then restored:
- no heicAsJPEG call in serve: TestHEICReachesPluginAsJPEG red
- media_type not set for Anthropic: the messages subtests red
- no base64 mark scan: the "labelled jpeg/png" subtests red

Not tried: a real Pi -> WorkBuddy request with a real account; a real
iPhone gridded HEIC (only sips files and Apple's 26 MB wallpaper); a HEIC
behind an http URL (not fetched, goes as it came); Anthropic document
blocks, Responses input_file and images/edits.
2026-11-01 15:04:28 +08:00
yetone fcbf618ebb gateway: a request's turns are looked through for images in place, before any copy (#3725)
walkImages decoded the whole request's top level (a copy of the body)
before it knew whether any turn held an image, and anyImageBlock read
every block whole, so a long agent conversation of text tool_results was
decoded block by block on every request. Now anyImageTurn walks the
turns array in place with eachMember/eachElement and decodes only when
an image is there. A tool_result's content (Anthropic) and a
functionResponse's parts (Gemini) are looked inside, so an image a tool
returned is still found.

Measured:
- hasImage on a 60-turn, 76KB body of text tool_results: 6863
  allocations before, at most 4 now (TestImageWalkReadsToolResultsInPlace,
  red on the old code with "took 6863 allocations").
- BenchmarkZZIO (12x20 catalog, ~31KB body, a local benchmark not
  committed): 620KB/1944 allocs per request before, 520KB/1544 after.

The test's table covers content before type, content given twice, a
tool_result inside a tool_result, an escaped "type" key, a text block
with content, string content, Gemini parts after name, nested fileData
and text-only parts. The existing image tests pass unchanged.

Run at this tree (base e1709ab42): gofmt -l clean; GOOS=linux and
GOOS=windows go vet -tags nogui ./internal/gateway ok; go test -count=1
-timeout 45m ./internal/gateway ok (446.961s).

Rebased onto 92cf0b68d (no internal/gateway change since
e1709ab42; pii, redact and settings changed): go vet -tags nogui
./internal/gateway ok and go test -count=1 -run Image ./internal/gateway
ok (12.011s) at the pushed head. The full gateway package ran at the
base above, not at this head.
2026-10-27 02:17:05 +08:00
yetone 68133754a3 gateway: a request's body is read in place, not copied by every reader (yg6888 on X: ~1 GB)
yg6888 on X: "magpie 占用内存有点高 随时1个g", with a group of 29
accounts and three agents sending at once.

Cause: each reader of a request decodes its turns into json.RawMessage
values (the images walk, the conversation id, the prompt, the edits, the
chat parse), and decodeJSON copied each value it filled, as
encoding/json does. A 1.5 MB conversation allocated ~42.8 MB on its way
through a group. Three agents at once kept the heap in the hundreds of
MB, and the GC ran behind it.

Fix:
- readRequestBody holds the body (holdBody) until the request's context
  ends. A RawMessage decodeJSON fills from inside a held body shares the
  body's bytes, capped so an append can't write into it. The body must
  be at most 16x the value (heldShareMost), so a small value kept past
  its request (a cache entry, a signature) never pins a whole body.
  Anything not held is still copied: a stream's buffer, a scanner line,
  a body built and changed in place. The list is bounded at 64 bodies
  (heldBodiesMost) and each leaves it through context.AfterFunc.
- The ratio leaves a long conversation's many small turns copied, so
  the two readers that run on every request take them in place:
  - conversationID takes the turns with elementsOf, slices of the
    body.
  - walkImages, which runs several times a request, first scans the
    turns without decoding (anyImageBlock/anyImageIn) and returns at
    once when there is no image. Keys and kinds are compared with
    jsonStringIs, so an escaped "type", a duplicate key, a tool
    result, a Responses function_call_output and Gemini's inlineData,
    fileData and functionResponse still count.

Numbers: sandbox gateway, fresh process each run, 150 requests of a
1.5 MB conversation, 3 at once through a group, machine load ~250:

                    peak RSS  HeapSys  GCs  allocated   bytes.Clone
  before            273 MB    222 MB   117  6416 MB     3635 MB
  held bodies       233 MB    186 MB    74  3379 MB     1480 MB
  + id/image scan   223 MB    174 MB    64  2853 MB      927 MB

That is ~42.8 MB allocated per request before and ~19 MB after. What is
still copied comes from the translators (stringOrText, editMessages,
parseChat, responsesContent), unquoteJSON (~670 MB), io.ReadAll
(~480 MB) and rewriteModel (~225 MB). None of these is changed here.

Tests:
- TestRequestBodyRawValuesShareIt, TestDecodeJSONCopiesWhatIsNotHeld and
  TestHeldBodiesBounded (fastjson_held_test.go).
- TestImageWalkReadsTextOnlyTurnsInPlace: a 938 KB text-only
  conversation allocates under len/8 per walk plus id, and eight image
  shapes are still found.

Broken by hand, each red:
- no share cap
- no ratio
- no bound
- no release
- pre-scan removed (8,780,204 B per iteration)
- tool_result skipped (case not found)
- id decoding each turn (1,044,859 B over the 117,265 limit)
- kind compared as raw bytes (the escaped case is not found)

No subsystem page covers decodeJSON.

Run record, the three commits on origin/main d9c6a60d8 (machine load
~270-480, with other sessions' GUI suites running):
- gofmt -l: clean. go vet ./... on darwin, GOOS=windows and
  GOOS=linux -tags nogui: exit 0.
- go test ./... -count=1 -timeout 45m (sandbox HOME, 11:02-11:34): 64
  ok, 1 FAIL: internal/gui TestCoreScriptBudget, app.js 155 bytes over
  from the first ledNum. ledNum was made smaller (1,268,907 of
  1,269,000 bytes), then internal/gui -count=1 alone: ok (329 s).
- Before the rebase (723f40778 on 9588501c0): internal/gateway ok
  (2064 s), internal/agent ok at -timeout 120m (it timed out at 45m
  at load ~700, #2869), internal/gui red only in
  TestSetAnswersWhileDevinAndProvidersHang (#1375).
- GUI suite, all 140 files, Chromium and WebKit, every language, at
  load 400-840 on 723f40778. Every red was run alone against
  9588501c0, and none comes from this change: routing-bodies
  (#2559/#2658), routing-keys-fold and routing-model-rest (#2658),
  routing-mode-goes WebKit (#2151, head 2/20 vs base 3/20),
  routing-request-metrics (#2571), routing-wb-restricted (#1905),
  usage-agents-hide (#2276/#2399), usage-fold (#2399), usage-checkin
  WebKit Qoder (#2549), usage-refresh (#2184). 5 s first waits under
  load were added to #2900. The usage-ledger route-callback race at
  page close was filed as #3001.
- After the rebase, each alone in both engines: routing-busy-frames,
  routing-intent-entry, routing-key-windows, routing-pause and
  usage-ledger were green.
- After the smaller ledNum, each alone, both engines, all languages:
  routing-busy-frames 6/0 (one later run lost Chromium's launch at
  180 s twice; Chromium alone right after: 3/3), usage-ledger
  Chromium 16/16 and WebKit 17/0. usage-ledger-leave and
  routing-request-metrics were red in browser launch and 5 s waits on
  this head and on d9c6a60d8 alike (#2900, #2571). Added to #2900:
  a WebKit zh usage-ledger run hung after a 5 s timeout.
2026-10-20 13:26:05 +08:00
yetone 5feadabef6 gateway: a long conversation's request costs about a third of the CPU it did, with the same bytes sent on (#1532, #1654)
The gateway reads one request's body a dozen times or more on its way:
modelOf, streamOf, conversationID, requestEffort, bodyEffort,
walkImages and swapImageBlocks (more than once through a group), turnOf's
parse, promptOf, chatToolNames, thinkingOffUnlessAsked, decodeRequest,
and for Responses pairToolItems, orphanedToolOutputs,
hasSealedAgentMessage and askedTier. Each read took a field or two with
json.Unmarshal, which checks the whole input and then steps through every
byte of every string one call at a time, so each read cost as much as
decoding the whole conversation: 74-77% of a request's CPU in pprof, most
of it checkValid and stateInString.

decodeJSON (fastjson.go) is json.Unmarshal for these reads. It checks the
body once with its own validator (json.Valid's grammar and 10000 depth,
8 string bytes at a time), splits objects and arrays at their members
without decoding them, and decodes only what dst has a place for:
strings, booleans, json.RawMessage (copied, as encoding/json does),
structs, pointers, slices and string-keyed maps by their parts, and
everything else (numbers, interfaces, types that decode themselves) by
encoding/json itself. Whatever it doesn't take on exactly as
json.Unmarshal would goes to json.Unmarshal with dst zeroed: invalid
input, a dst already holding something, an embedded field, a ",string"
option, two fields of one name, a key given twice, a value of the wrong
type. A list or object where dst takes a string (a "string or parts"
read) is answered by json.Unmarshal of its opening and close, which gives
the same error at the same offset without reading the rest. The request
paths' json.Unmarshal calls in gateway.go, decide.go, affinity.go,
image_input.go, textcalls.go, anthropic.go, ir.go, prompt.go, chat.go,
chattidy.go and responses.go, and hasSealedAgentMessage and askedTier,
now call it. Nothing that writes a body changed.

Numbers, M4 Pro under load 10-20 from other sessions, BenchmarkLargeRequest
(new: a 2 MB agent conversation with 30 tools, tool calls and results,
through a fake vendor), 20 requests each:

                    CPU in the request's handler    time per request
                    (pprof, per request)            (ns/op)
  anthropic         154ms -> 45ms                   208-212ms -> 52ms
  anthropic, group  178ms -> 51ms                   249-262ms -> 65-67ms
  chat              122ms -> 35ms                   167-254ms -> 50-54ms
  responses         215ms -> 56ms                   294-452ms -> 70ms

TestLargeRequestEndpoints (64 MB padded bodies): 16.8-17.6s -> 2.9-4.8s
(skipping runs of spaces 8 bytes at a time took its last ~5s).

Tests:
- TestUpstreamBodiesUnchanged sends 18 requests (Anthropic, Chat and
  Responses; direct, through a group, translated to each other protocol,
  with images, thinking, escapes, odd spacing, a repeated key, and four
  2 MB conversations) and compares what the vendor gets with
  testdata/upstream_bodies, recorded on the code before this change
  (all 18 identical; three runs agreed). Breaking decodeJSON's \n
  unescape by hand turns the three translated cases holding one red.
- TestDecodeJSONIsUnmarshal / FuzzDecodeJSON compare decodeJSON with
  json.Unmarshal (dst DeepEqual, error nil-ness) for 19 types shaped like
  the gateway's, and jsonValid with json.Valid, over seeds, every cut
  and a changed byte at every place of each seed, and 2.5 minutes of
  fuzzing (~1.75M inputs). Breaking the validator's control-byte check
  by hand turns it red.
- go test -tags nogui -timeout 40m ./... on this commit rebased onto
  origin/main 498b77fbc, with #1667's fix below it: all 48 packages ok
  (gateway 394s).
gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui
./internal/gateway clean.

Not tried: real vendor traffic; Windows and Linux runs (vet only).
2026-10-12 03:28:16 +08:00
yetone da1fd6cb0c gateway: a Gemini functionResponse's own parts reach the upstream — the image agy's view_file read (#1038, handong66: agy via magpie can't see images, the model makes up what they show)
agy sends the image a tool read inside the function response, as Gemini 3's
multimodal function responses carry it: functionResponse.parts[].inlineData
(under role "model", as agy sends tool results). parseGemini read only id,
name and response, so the parts were dropped before any translation: the
reporter's prompt was 96 tokens instead of 1115 and the model invented the
watermark and subtitle, with a 200 / STOP the client couldn't tell apart.

parseGemini now reads functionResponse.parts (camelCase, and snake_case
through geminiCamel): an image (inlineData or fileData) becomes the tool
result's Images, which every builder already carries — Antigravity/Code
Assist and Factory's Gemini as inlineData right after the functionResponse
in the same turn (the shape top-level images already work in), Anthropic as
tool_result image blocks, Responses as function_call_output input_image,
Chat as the image message after the tool's. A non-image file (a PDF) can't
sit in a tool result, so it follows the result in the same turn instead of
being lost. walkImages now looks inside a Gemini functionResponse's parts
too, so a model that can't see is sent the request with the tool's image
replaced by the omitted note, as for every other surface's tool images.

Tests from the reporter's literal request shape (view_file, call_462432,
response.output + parts[].inlineData; role model and user; camelCase and
snake_case): TestGeminiFunctionResponseImage (parse + Code Assist, Anthropic,
Chat, Responses bodies), TestGeminiFunctionResponseImageReachesUpstream
(/v1beta to a Chat upstream through the gateway), TestGeminiFunctionResponseFile
and TestGeminiFunctionResponseImageIsATools. All four fail without the change
("Images:[]", "the tool's image was not seen"). Not run against a real agy
or Antigravity account.
2026-10-07 00:23:34 +08:00
Charan Rathore 3b6ea8b589 gateway: clear 400 for Responses images named by file_id on translated routes (#166)
* gateway: 400 on translated Responses images named by file_id

Add error handling for unportable current image in translate function.

* gateway: keep native file_id passthrough, reject on translation

Added hasUnportableCurrentImage function to check for images without a portable source.

* gateway: test Responses file_id image handling
2026-09-29 03:38:54 +08:00
yetone d00d9ffe6f gateway: a model that can't see images is given what a model that can says of them (让Magpie支持配置图像识别模型) — until now an image sent to a model the catalog knows takes text only was turned away in the latest turn and left out of older turns and tool results, so an agent on DeepSeek, GLM or any text-only model couldn't be shown a screenshot at all. Now each image in such a request is described once by the vision model and the description goes in its place, in every protocol (Chat, Responses, Anthropic, Gemini), current turn, older turns and tool results alike: "[Image, as <model> describes it for this model, which can't see images:] … [End of the image's description]". The describer is asked through the gateway itself (User-Agent magpie-vision/1, recorded as agent magpie), with a system prompt to transcribe text, code, errors and UI state exactly and not to answer or guess; images are described four at a time, and a description is kept (256, by model+image) since an agent sends a conversation's images again every turn, a failure not kept. An image of the latest turn that can't be described is a 502 saying why; one in an older turn is left out as before. Settings → Images → Image recognition picks the model: Automatic (a small model that sees — a Claude account's, a Codex account's, the cheapest of an API key's, another account's), Off (images turned away as before), or any model or group that sees; an id that doesn't resolve is refused. In a routing group the description is made only when a text-only member is actually tried, so a rule that routes images to a member that sees costs nothing; a member whose image can't be described is skipped for the next, the last one answers 502. The describer's own request is never described again, so a Vision set to a text-only model is turned away, not looped. Checked in a sandbox HOME against a local vendor: an image sent over Chat and over Anthropic to a text-only model reached it as the description, the describer was asked once per image, and the Settings row and its picker in light and dark. 2026-09-29 01:20:31 +08:00
e136cf9a27 gateway: Gemini PDF and audio files kept on text-only routes (#95)
* gateway: keep Gemini document and audio file data on text-only routes

* fix(gateway): avoid translating Gemini files as images

* fix(gateway): preserve Gemini files for Code Assist while translating safely

* fix(gateway): retain Gemini file placeholder for Claude subscriptions

---------

Co-authored-by: Instinct Agent <agent@instinct.com>
Co-authored-by: Charan Rathore <charan-rathore@users.noreply.github.com>
2026-09-27 04:24:03 +08:00
herrkaefer b5d47ca5e7 gateway: an image sent to a model that can't see is dealt with before it goes out, and one a tool returned no longer ends the chat (#56)
A model's image input is taken from models.dev and the provider's own list, and a group's from its members: only a model known to be text-only is refused an image — one whose support is unknown still gets it, and Codex, OpenCode and Pi are told which models take images. An image the user attaches for a text-only model answers 400 in the client's own format before the upstream is asked; an image earlier in the chat, or one a tool returned (Claude Code's Read, Codex's view_image, a Chat tool message), becomes a short text note, so a chat that met a picture carries on after a switch to a text-only model. Thanks @herrkaefer.
2026-09-25 15:39:56 +08:00