From f6a538ece908bbd4a4f2afa632b409032e999f86 Mon Sep 17 00:00:00 2001 From: yetone Date: Wed, 18 Nov 2026 23:05:00 +0800 Subject: [PATCH] images: a resolution tier, 1K, 2K or 4K, in Settings and the image MCP (skingstyle48487 on X) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Asking the image MCP for 4K through a relay came back at 2K: nothing told the model how large to draw. Settings › Models › Images now has Image resolution (Automatic, 1K, 2K, 4K; an app menu, saved as imageResolution), and generate_image takes a resolution argument. The agent's own resolution or WIDTHxHEIGHT size wins over the setting. The images API takes `resolution` (or a tier given as size, "4K"), and each vendor gets it in its own field: - Gemini: imageConfig.imageSize (3.x image models; 2.x draws at 1K); - chat image models (Gemini's): image_config.image_size; - OpenRouter /images: resolution; - Grok Imagine: resolution 1k or 2k (its largest); - Seedream (Ark): the size tier the model has, or its pixels for a ratio; - MiniMax H3: area; - GPT Image 2 and other WxH images APIs: pixels at the ratio, within GPT Image 2's limits (edge 3840, 655,360 to 8,294,400 pixels, /16); - gpt-image-1, DALL·E and SenseNova keep their own sizes. A vendor that answers 400 or 422 to a tier is asked once more without it. An unknown resolution is a 400. Both MCPs now say what size each image came back at, and when that is under the tier asked. The row is drawn by videogen.js, after Video generation's, so app.js keeps its budget (it was at 1,088,641 to the byte); the server keeps imageResolution when a save doesn't send it (TestSettingsImageResolution), so prefsKeep doesn't carry it. The menu has no notes: "The model's own" was a plugin's key already. Run (magpie-desktop WSL on xiaomi-gpu; mote was over load 18 all day): - gofmt -l: clean; go vet -tags nogui ./... and GOOS=windows go vet ./...: ok. - go test ./internal/gateway -count=1 (1995s), ./internal/imagemcp, ./internal/settings, ./internal/settingsapi: ok; at this head go vet -tags nogui of gui, gateway and settingsapi, and gateway -run "Tier|ImagesAPIResolution|ImageMCP|Draw|Image", settingsapi and imagemcp: ok. - New: draw_tier_test.go (each protocol's field, a fake upstream for the images API and the image MCP, the 400 retry, the precedence). - At this head (on 88b65d758): go test -tags nogui ./internal/gui -run "Budget|I18n|SettingsImage": ok; node --test i18n-keys, image-resolution (22 of 22: chromium and webkit, en zh zh-TW ja de, 1100 and 420 wide), video-gen-pick and old-webkit: 62 of 64. The 2 reds are old-webkit's "compat.js is the first..." (guideback.js) and "the styles hold up in Safari 15.0" (app.css :has()), the same on a clean copy of origin/main 88b65d758: #6570. - Broken by hand: imagesAPISize returning the size as given, the retry off, chat image_size and OpenRouter resolution dropped, the image MCP ignoring the setting, the server's keep of imageResolution removed, a zh string removed: each turned its test red. Not run yet: the full go test ./... and the whole GUI suite (WSL's one suite slot was taken by another session); they run after this push. Not tried against a real vendor. --- docs/subsystems/gateway-routing.md | 2 +- internal/gateway/draw.go | 112 +++-- internal/gateway/draw_minimax.go | 3 + internal/gateway/draw_tier.go | 421 +++++++++++++++++++ internal/gateway/draw_tier_test.go | 295 +++++++++++++ internal/gateway/draw_volcengine.go | 5 +- internal/gateway/image_mcp.go | 16 +- internal/gateway/image_mcp_memory_test.go | 2 +- internal/gui/api_settings_test.go | 30 ++ internal/gui/assets/app.js | 3 +- internal/gui/assets/i18n.js | 8 + internal/gui/assets/videogen.js | 24 ++ internal/gui/tests/image-resolution.test.cjs | 136 ++++++ internal/imagemcp/imagemcp.go | 13 +- internal/settings/settings.go | 10 + internal/settingsapi/settingsapi.go | 37 +- 16 files changed, 1063 insertions(+), 54 deletions(-) create mode 100644 internal/gateway/draw_tier.go create mode 100644 internal/gateway/draw_tier_test.go create mode 100644 internal/gui/tests/image-resolution.test.cjs diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 95ecc7d7e..ffb9d6a74 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -60,7 +60,7 @@ another for the conversation instead of listing every id | Accounts at once | A provider's `MaxAccounts` (01huadalang on Discord: three ZCode accounts used at once got the exit address refused with a 405, two didn't; the ZCode plugin declared two from 0.1.40 to 0.1.67, and since 0.1.68 declares none and holds its Start Plan to six requests in flight from the address itself, since a user's other accounts sat unused, mathfournity on X) is how many of its keys or accounts take requests at the same time: `provider.AtOnce()` is the user's own value, else what its plugin declares (`maxAccounts` on the auth hook or in package.json's `magpie`, read by host.js `atOnceOf`; zcode says 2), else no limit; the user's 0 is no limit over the plugin's. `perKeyBarred` keeps the first N in the user's own order (`rank`, so a dragged list counts), preferring ones not resting, and hands the rest to `keepAtOnce`'s reserves: they go after everything else as asides with `candidate.reserve` set (`Weighed.Reserve`), so whatever the routing mode, a reserve is asked only once the kept ones failed or rest, and a kept one that rests gives its seat to the first reserve on the next request. Three guards keep a reserve from being reached for anything else: `laneMate` never spills a full lane onto one, a full queue (`laneErr`) drops the provider's reserves before passing on (`dropReserves`), so the request is turned away with the 429 instead, and session affinity keeps no conversation on a reserve once the kept ones can take it (`affine`'s "reserve"; Strict still holds). Leak known: a failure that rests nobody (a 5xx on one try) still passes that one request to the reserve, as it does to any next candidate. Set in the provider editor's Advanced (Accounts at once, beside Concurrency) or with `magpie provider at-once`; Routing's row says "in reserve · {n} at once" (`TestAtOnceKeepsFirstInUserOrder`, `TestAtOnceFullLaneWaitsForTheKept`, `TestAtOnceReserveTakesOverAndGivesBack`, `provider-at-once.test.cjs`). | [`fallback.go`](../../internal/gateway/fallback.go), [`concurrency.go`](../../internal/gateway/concurrency.go), [`internal/provider/concurrency.go`](../../internal/provider/concurrency.go) | | Sink | With `Sink` on, a key or account that answers 429 while it still has quota goes to the back, behind every one not rate limited since. Held in memory until restart, or until its rest is lifted by hand (Try now, `Unrest` calls `unsink`, `UnrestAll` `unsinkAll` for the key and each of its models), which puts it back in its place (`TestTryNowPutsASunkAccountBack`, `TestUnrestAllUnsinksTheModels`). Another magpie's model rate limited there, whose rest is the model's alone (`remoteModelRest`), sinks alone too (`restID`), and `sunkAt` reads a candidate's model before its key, so the remote's other models keep their place (#2167, ggbdpq; `TestRemoteMagpieRateLimitSinksTheModel`, `TestMagpieAddedByHandRateLimitSinksTheModel`). A group in a group sinks by its own Sink, within its own order (`sinkOwn`, #2255), and the group asked for then sinks the whole by its own; `TestNestedGroupSinksItsOwnOrder`. | [`sink.go`](../../internal/gateway/sink.go) | | Group defaults | What a group does when a member is rate limited (Sink), slow to start (FirstToken) or every member is busy (Patience) is set once for every group in settings (`groupSink`, `groupFirstToken`, `groupPatience`; `settings.SetGroupDefaults`, POST `/api/groups/defaults`, the Routing groups page's Settings card; jiezhengj on Discord). A group follows the default for each it leaves unset, and its own value wins: `Sinks()` is `Sink`, or the default unless `NoSink` (Keeps its place); `FirstTokenOr()` is its own `FirstToken` (`FirstTokenWait`, -1, is its own Wait), else the default; `Waits()` reads the default when `Patience` is 0 (60 is its own 1 min). The group editor's rows open on Default for a group that sets none, the hint naming the value it follows. Groups saved before kept 0 and no `NoSink`, so they follow the default, which starts at magpie's own (keep its place, wait, 60s). `TestGroupDefaultsUnlessItsOwn`, `TestGroupFirstTokenFollowsTheDefault`, `TestGroupSinkFollowsTheDefault`, `TestGroupDefaultsSaved`, `group-defaults.test.cjs`. | [`group.go`](../../internal/provider/group.go), [`groups.go`](../../internal/gui/groups.go) | -| Image generation | `/v1/images/generations` and `/v1/images/edits` are translated to the selected model's image API. OpenRouter image-only models use its `/images` endpoint and send reference images as `input_references`; OpenRouter models that return images through chat stay on Chat Completions. Volcengine Ark (`isArk`: an `ark.*.volces.com` base, the preset's plans or one added by hand) is asked at `/images/generations` only, as its doc (https://www.volcengine.com/docs/82379/1541523) takes it (`drawArk`): `watermark: false`, since it marks every image otherwise; reference images as JSON `image` (a URL or data URL, an array for several), never a multipart edit; no `n`, so one request per image (`eachDrawing`); no ratio as `size`, so a ratio its doc lists is sent as that ratio's 2K size and any other is a 400 that says to put it in the prompt; no mask, no quality (JL on Discord, `TestArkDrawsWithoutWatermarkOncePerImage`). DashScope (`dashScope`: Qwen's, Bailian's and Qwen Cloud's presets, or one of their hosts) draws its Qwen-Image and Wan 2.7 image models (`dashScopeDraws`) on its own API, `/api/v1/services/aigc/multimodal-generation/generation` (`drawDashScope`), as docs.qwencloud.com gives it: the prompt as the user message's `text` part after an edit's images as `image` parts (a URL or data URL), `n`, `size` as `W*H` (a ratio is a 400 that says to give WxH), `watermark: false`, no mask; the images are read from every `output.choices[].message.content[].image` (`readDashScopeAnswer`), and a refusal says its `message` and `code`. A Token Plan's host serves no OpenAI images API, so the drawing went on to chat completions and "drew nothing" (judi0713 on Discord, `TestDashScopeDrawsOnItsOwnAPI`). A MiniMax API key (`filmsMiniMax`: the `minimax` and `minimax-cn` presets, or any provider at api.minimax.io, api.minimaxi.com or api.minimax.cn) lists `image-01` and `image-01-live` among its drawers (`minimaxDrawers`) and draws them on MiniMax's own `/v1/image_generation` (`drawMiniMax`), as platform.minimax.io gives it: `aspect_ratio` from `size` (one MiniMax lists, or the size it draws for one; else for image-01 a `width`/`height` in 512 to 2048 by 8; else the nearest ratio), `n`, `response_format: base64`, an edit's images as `subject_reference` (`type: character`), and the caller's `seed`, `prompt_optimizer`, `aigc_watermark` and `style`; no mask. The images are read from `data.image_base64` (or `image_urls`), and a `base_resp` failure in a 200 is told by its code (1004/2049 key, 1008 balance, 1026 content, 1002 rate) with its status (`readMiniMaxDrawing`). It went to chat completions before and was answered "unknown model 'image-01' (2013)" (rocbomb123 on X, `TestMiniMaxDrawsOnImageGeneration`). A routing group named for a drawing or a video (`drawingGroup`: `group/`, or a bare id the group goes by that resolved to one of its members) is tried member by member in the order its routing plans for a chat (`drawingTries` over `planGroup`), each member over its own keys or accounts (`drawOnAccounts`, `startVideo`); the next member is asked while one fails as a chat's would move on (`retryable`: its vendor 5xx, out of quota, the model not served), never for a refusal of the request itself, and the call's `Fallback` names those tried first (#2005, tianxia3111: a group of two relays answered the first one's 502). A group with chat models beside its image or video ones is tried on those alone (`drawingTries`' `makes`: `drawsModel`, or `servesKind` for video), so a drawing never goes to a chat member, on its provider's images API or as a chat asked for an image (changqiu4890 on Discord: a group of three relay chat models, a DeepSeek one and the relay's gpt-image-2.5 drew on its first chat model; `TestMixedGroupDrawsOnItsImageMemberOnly`, `TestMixedGroupMakesVideoOnItsVideoMemberOnly`). Codex's image tool draws on the routing group its turn asked for when that group has an image member (`codexDrawingProvider` gives the turn's group, `GroupDraws`, then `resolveDrawing`), and only otherwise on the provider that served the turn or Settings' pick (`TestCodexDrawingTakesItsGroupsImageMember`). Pause rules and a gateway key's group hold apply as for a chat. A failed drawing rests no member and no key. An account out of quota for the image model (`failure` reads `failQuota`) rests that model on it alone (`restDrawer`, keyed by `restID`), until the reset its refusal names (`resetsAt`: Antigravity's "Your quota will reset after 3h19m30s.") or `quotaRest`, so the next drawing asks the accounts that still have it first (`restLast`), and the account's text models stay in. Antigravity also tells a model's quota used up as a 200 whose stream is the error; `drawCodeAssist` gives such an error the status its words stand for (`saidStatus`: quota or rate 429, credit 402, else 502), as the images API's 200 with no image does, so a spent account hands the drawing to the next one as its 429 does (01huadalang on Discord: a 502 ended the drawing on the spent account; `TestAntigravityDrawingOutOfQuotaInsideTheReplyGoesOn`, `TestAntigravityDrawingQuotaRestsTheImageModel`). `TestImageGroupMovesOnToTheNextMember`, `TestVideoGroupMovesOnToTheNextMember`. Such a group may be Settings → Models → Images → Image generation's pick (7up6666 on X): the list offers each routing group with a member among its provider's `Drawers` (`GroupDraws`), so a request naming no model, the Magpie Image MCP's included, draws on the group; a picked group none of whose members draws any more is `DrawerMissing` (`drawerMissing`), the row says so and Automatic draws in its place. `TestImageGroupPickedInSettingsDraws`, `TestImageGenOffersDrawingGroups`. A group's Add a model picker offers each provider's image models, `/api/groups`' `drawers` (`gateway.Drawers` less hidden ones, apart from the chat `models`), said as such and with no reasoning level (jzw690 on X); such a member draws whether or not its provider's picks name it, as picks are of chat models (`provider.FindDrawingGroup`, used by `GroupDraws`, `resolveDrawing` and the image group's turns), and the group is no model agents are offered. A group named on `/v1/embeddings`, `/v1/rerank`, `/v1/audio/speech`, `/v1/audio/transcriptions` (and translations) or `/v1/videos` keeps the same way a member its provider's chat list doesn't have (`mediaMembers`: `provider.FindGroupAlso` with `offChatList`), and is tried from its first such member (`mediaGroupFirst`), so a hand-made group of embedding or speech models of providers with picks is served, not a 404 (XYenon on Discord); a chat model the user unticked stays out. `TestMediaGroupOfProvidersWithChatPicks`, `TestVideoGroupOfProvidersWithChatPicks`. The same models need no group made by hand (#5339): a fetched list keeps its models made for another API, each marked with it (`catalog.Model.Serves`, from the id: `catalog.ServesOf`; `LiveServing`), out of the chat models (`catalog.Chat`), so agents' lists, gateway keys and Routing's chat pickers never offer them, and a moderation model is still dropped. A model of one kind that more than one provider serves under exactly the same id (no other case, no other version) is a group of that kind made per request on its route (`provider.KindGroup`, `mediaMembers` and `servesKind` in [`media_group.go`](../../internal/gateway/media_group.go)): asked by the bare id there, or by `group/auto-:` (`KindGroupID`; a chat model's found group's id has no `:`), never on another kind's route, its members in the Providers order, none switched off and none the model is disabled on. It is in no list of groups (`Groups`), so no agent, key or picker offers it. Video is the kind `video` (`Videomakers`); images keep their own groups. A list saved before this is fetched again once a run, schedule or none (`refreshDueLists`, `catalog.LiveKinded`). Another magpie's list (`X-Magpie-Drawers`) is not marked; its models are found by their id (`ServesOf`). `TestKindGroupsServeEachAPIByRoute`, `TestVideoKindGroupByTheModelsID`, `TestKindGroupHoldsTheExactModel`, `TestKindlessListFetchedOnce`, `TestFetchKeepsModelsOfOtherAPIs`. `TestImageGroupOfUnpickedImageModelsDraws`, `TestGroupEditorOffersImageModels`, `group-pick-drawers.test.cjs`. An account's own list of models (#474) never bars a ChatGPT account's GPT Image, a Grok subscription's Grok Imagine or a WorkBuddy plan's image models (`listsCantName`): the list is picked from the editor's chat models, which they are never among, so a list kept for some chat models had every drawing refused as "set not to be served by any account" (heyiwei5 on X). A key's list, picked from models that include its image ones, still bars them. `TestCodexDrawsPastAccountModelLists`. A drawing is given Settings → Models → Images → Image generation timeout (`imageTimeout`, 1 to 60 minutes, 5 when unset; neighbads on X: a slow image endpoint needed more) as its context's deadline (`drawTimeout`, `drawWithin`), and so is downloading an image answered as a link (`imageLongest`, never under `ImageLongest`). A drawing's request goes through a transport with no `ResponseHeaderTimeout` (`drawsApart`), since an images API sends its headers only once it has drawn, and every other request keeps `upstreamHeaderWait` (10 minutes). A video's submit, status and download calls keep 5 minutes each (`videoTimeout`). The `magpie mcp image` process, which may not read these settings (WSL), waits on a call up to `callLongest` (two hours and a minute), so it never cuts one the gateway still waits on. `TestLongImageTimeoutLetsASlowVendorFinish`, `TestImageTimeoutSettingReachesTheVendor`, `TestOnlyDrawingsWaitPastTheHeaderWait`. | [`draw.go`](../../internal/gateway/draw.go), [`draw_volcengine.go`](../../internal/gateway/draw_volcengine.go), [`draw_dashscope.go`](../../internal/gateway/draw_dashscope.go), [`video.go`](../../internal/gateway/video.go), [`catalog.go`](../../internal/catalog/catalog.go) | +| Image generation | `/v1/images/generations` and `/v1/images/edits` are translated to the selected model's image API. OpenRouter image-only models use its `/images` endpoint and send reference images as `input_references`; OpenRouter models that return images through chat stay on Chat Completions. Volcengine Ark (`isArk`: an `ark.*.volces.com` base, the preset's plans or one added by hand) is asked at `/images/generations` only, as its doc (https://www.volcengine.com/docs/82379/1541523) takes it (`drawArk`): `watermark: false`, since it marks every image otherwise; reference images as JSON `image` (a URL or data URL, an array for several), never a multipart edit; no `n`, so one request per image (`eachDrawing`); no ratio as `size`, so a ratio its doc lists is sent as that ratio's 2K size and any other is a 400 that says to put it in the prompt; no mask, no quality (JL on Discord, `TestArkDrawsWithoutWatermarkOncePerImage`). DashScope (`dashScope`: Qwen's, Bailian's and Qwen Cloud's presets, or one of their hosts) draws its Qwen-Image and Wan 2.7 image models (`dashScopeDraws`) on its own API, `/api/v1/services/aigc/multimodal-generation/generation` (`drawDashScope`), as docs.qwencloud.com gives it: the prompt as the user message's `text` part after an edit's images as `image` parts (a URL or data URL), `n`, `size` as `W*H` (a ratio is a 400 that says to give WxH), `watermark: false`, no mask; the images are read from every `output.choices[].message.content[].image` (`readDashScopeAnswer`), and a refusal says its `message` and `code`. A Token Plan's host serves no OpenAI images API, so the drawing went on to chat completions and "drew nothing" (judi0713 on Discord, `TestDashScopeDrawsOnItsOwnAPI`). A MiniMax API key (`filmsMiniMax`: the `minimax` and `minimax-cn` presets, or any provider at api.minimax.io, api.minimaxi.com or api.minimax.cn) lists `image-01` and `image-01-live` among its drawers (`minimaxDrawers`) and draws them on MiniMax's own `/v1/image_generation` (`drawMiniMax`), as platform.minimax.io gives it: `aspect_ratio` from `size` (one MiniMax lists, or the size it draws for one; else for image-01 a `width`/`height` in 512 to 2048 by 8; else the nearest ratio), `n`, `response_format: base64`, an edit's images as `subject_reference` (`type: character`), and the caller's `seed`, `prompt_optimizer`, `aigc_watermark` and `style`; no mask. The images are read from `data.image_base64` (or `image_urls`), and a `base_resp` failure in a 200 is told by its code (1004/2049 key, 1008 balance, 1026 content, 1002 rate) with its status (`readMiniMaxDrawing`). It went to chat completions before and was answered "unknown model 'image-01' (2013)" (rocbomb123 on X, `TestMiniMaxDrawsOnImageGeneration`). A routing group named for a drawing or a video (`drawingGroup`: `group/`, or a bare id the group goes by that resolved to one of its members) is tried member by member in the order its routing plans for a chat (`drawingTries` over `planGroup`), each member over its own keys or accounts (`drawOnAccounts`, `startVideo`); the next member is asked while one fails as a chat's would move on (`retryable`: its vendor 5xx, out of quota, the model not served), never for a refusal of the request itself, and the call's `Fallback` names those tried first (#2005, tianxia3111: a group of two relays answered the first one's 502). A group with chat models beside its image or video ones is tried on those alone (`drawingTries`' `makes`: `drawsModel`, or `servesKind` for video), so a drawing never goes to a chat member, on its provider's images API or as a chat asked for an image (changqiu4890 on Discord: a group of three relay chat models, a DeepSeek one and the relay's gpt-image-2.5 drew on its first chat model; `TestMixedGroupDrawsOnItsImageMemberOnly`, `TestMixedGroupMakesVideoOnItsVideoMemberOnly`). Codex's image tool draws on the routing group its turn asked for when that group has an image member (`codexDrawingProvider` gives the turn's group, `GroupDraws`, then `resolveDrawing`), and only otherwise on the provider that served the turn or Settings' pick (`TestCodexDrawingTakesItsGroupsImageMember`). Pause rules and a gateway key's group hold apply as for a chat. A failed drawing rests no member and no key. An account out of quota for the image model (`failure` reads `failQuota`) rests that model on it alone (`restDrawer`, keyed by `restID`), until the reset its refusal names (`resetsAt`: Antigravity's "Your quota will reset after 3h19m30s.") or `quotaRest`, so the next drawing asks the accounts that still have it first (`restLast`), and the account's text models stay in. Antigravity also tells a model's quota used up as a 200 whose stream is the error; `drawCodeAssist` gives such an error the status its words stand for (`saidStatus`: quota or rate 429, credit 402, else 502), as the images API's 200 with no image does, so a spent account hands the drawing to the next one as its 429 does (01huadalang on Discord: a 502 ended the drawing on the spent account; `TestAntigravityDrawingOutOfQuotaInsideTheReplyGoesOn`, `TestAntigravityDrawingQuotaRestsTheImageModel`). `TestImageGroupMovesOnToTheNextMember`, `TestVideoGroupMovesOnToTheNextMember`. Such a group may be Settings → Models → Images → Image generation's pick (7up6666 on X): the list offers each routing group with a member among its provider's `Drawers` (`GroupDraws`), so a request naming no model, the Magpie Image MCP's included, draws on the group; a picked group none of whose members draws any more is `DrawerMissing` (`drawerMissing`), the row says so and Automatic draws in its place. `TestImageGroupPickedInSettingsDraws`, `TestImageGenOffersDrawingGroups`. A group's Add a model picker offers each provider's image models, `/api/groups`' `drawers` (`gateway.Drawers` less hidden ones, apart from the chat `models`), said as such and with no reasoning level (jzw690 on X); such a member draws whether or not its provider's picks name it, as picks are of chat models (`provider.FindDrawingGroup`, used by `GroupDraws`, `resolveDrawing` and the image group's turns), and the group is no model agents are offered. A group named on `/v1/embeddings`, `/v1/rerank`, `/v1/audio/speech`, `/v1/audio/transcriptions` (and translations) or `/v1/videos` keeps the same way a member its provider's chat list doesn't have (`mediaMembers`: `provider.FindGroupAlso` with `offChatList`), and is tried from its first such member (`mediaGroupFirst`), so a hand-made group of embedding or speech models of providers with picks is served, not a 404 (XYenon on Discord); a chat model the user unticked stays out. `TestMediaGroupOfProvidersWithChatPicks`, `TestVideoGroupOfProvidersWithChatPicks`. The same models need no group made by hand (#5339): a fetched list keeps its models made for another API, each marked with it (`catalog.Model.Serves`, from the id: `catalog.ServesOf`; `LiveServing`), out of the chat models (`catalog.Chat`), so agents' lists, gateway keys and Routing's chat pickers never offer them, and a moderation model is still dropped. A model of one kind that more than one provider serves under exactly the same id (no other case, no other version) is a group of that kind made per request on its route (`provider.KindGroup`, `mediaMembers` and `servesKind` in [`media_group.go`](../../internal/gateway/media_group.go)): asked by the bare id there, or by `group/auto-:` (`KindGroupID`; a chat model's found group's id has no `:`), never on another kind's route, its members in the Providers order, none switched off and none the model is disabled on. It is in no list of groups (`Groups`), so no agent, key or picker offers it. Video is the kind `video` (`Videomakers`); images keep their own groups. A list saved before this is fetched again once a run, schedule or none (`refreshDueLists`, `catalog.LiveKinded`). Another magpie's list (`X-Magpie-Drawers`) is not marked; its models are found by their id (`ServesOf`). `TestKindGroupsServeEachAPIByRoute`, `TestVideoKindGroupByTheModelsID`, `TestKindGroupHoldsTheExactModel`, `TestKindlessListFetchedOnce`, `TestFetchKeepsModelsOfOtherAPIs`. `TestImageGroupOfUnpickedImageModelsDraws`, `TestGroupEditorOffersImageModels`, `group-pick-drawers.test.cjs`. An account's own list of models (#474) never bars a ChatGPT account's GPT Image, a Grok subscription's Grok Imagine or a WorkBuddy plan's image models (`listsCantName`): the list is picked from the editor's chat models, which they are never among, so a list kept for some chat models had every drawing refused as "set not to be served by any account" (heyiwei5 on X). A key's list, picked from models that include its image ones, still bars them. `TestCodexDrawsPastAccountModelLists`. A drawing is given Settings → Models → Images → Image generation timeout (`imageTimeout`, 1 to 60 minutes, 5 when unset; neighbads on X: a slow image endpoint needed more) as its context's deadline (`drawTimeout`, `drawWithin`), and so is downloading an image answered as a link (`imageLongest`, never under `ImageLongest`). A drawing's request goes through a transport with no `ResponseHeaderTimeout` (`drawsApart`), since an images API sends its headers only once it has drawn, and every other request keeps `upstreamHeaderWait` (10 minutes). A video's submit, status and download calls keep 5 minutes each (`videoTimeout`). The `magpie mcp image` process, which may not read these settings (WSL), waits on a call up to `callLongest` (two hours and a minute), so it never cuts one the gateway still waits on. `TestLongImageTimeoutLetsASlowVendorFinish`, `TestImageTimeoutSettingReachesTheVendor`, `TestOnlyDrawingsWaitPastTheHeaderWait`. A drawing's resolution tier, 1K, 2K or 4K (`resolution`, or a `size` that is one; `tierOf`, `settleTier` in [`draw_tier.go`](../../internal/gateway/draw_tier.go)), is asked of each vendor in its own field: Gemini's `imageConfig.imageSize`, a chat image model's `image_config.image_size`, OpenRouter's `resolution`, Grok's `resolution` (1k or 2k), Ark Seedream's `size` (a tier or its pixels), MiniMax's `area`, and gpt-image-2 and later as `WxH` pixels in their limits (`imagesAPISize`); gpt-image-1, DALL·E and SenseNova get none. A request whose tier its vendor answers with a 400 or 422 is asked once more without it (`tierRefused`). The Magpie Image MCP asks Settings → Models → Images → Image resolution (`imageResolution`, unset is the model's own; skingstyle48487 on X) when the agent names neither size nor resolution, and says the pixels drawn when they are under the tier asked (`ImageTier`, `PixelsSaid`); the row is drawn by `videogen.js` beside Video generation. `TestTierReachesEachProtocol`, `TestImageTierPrecedence`, `TestImagesAPIResolution`, `TestImageMCPAsksTheSetResolution`, `image-resolution.test.cjs`. | [`draw.go`](../../internal/gateway/draw.go), [`draw_volcengine.go`](../../internal/gateway/draw_volcengine.go), [`draw_dashscope.go`](../../internal/gateway/draw_dashscope.go), [`video.go`](../../internal/gateway/video.go), [`catalog.go`](../../internal/catalog/catalog.go) | | Decisions | `POST /v1/decisions` (and `/decisions`) is OpenAI's Decisions API, checked against openai-python's `decisions.create` (`DecisionCreateParams`, `Decision`): `model` (gpt-6-luna), `input` (a string, or messages and items whose parts are `input_text`, `input_image` with a data or http(s) URL, JSON), `questions` (1 to 400 predicate, choice or score questions), and `prompt_cache_key`, `prompt_cache_options`, `safety_identifier`. The answer is `{answers, model, usage}`, never streamed. `decide` passes the body through `serveRetrieval` as embeddings' is, with only `model` changed, so model resolution, a disabled model, a key's models, accounts and spent limits, pause rules, the provider's keys or accounts, masking (a data URL's image is left as it is) and the Routing page hold as on every route. It goes only to a provider `canDecide` takes: an OpenAI API key on `api.openai.com`, Azure OpenAI (`IsAzure`, at its v1 API's `/openai/v1/decisions`, the model in the body as the deployment's name), or another magpie, which routes it on. Any other, a relay, a plugin or a ChatGPT sign-in whatever its list says, is never sent it: the try is refused 400 with who serves it (`decisionRequest.refuses`, next to the no-OpenAI-API check), and a group moves on to its next member. A bare `gpt-6-luna` is the kind group `decision` (`servesDecision`: a provider `canDecide` takes that lists the model, or an OpenAI key, as the API takes it without it on the key's chat list), so a relay listing the same id is never its member. Usage is recorded as `decisions` from the answer's `usage` (`decisionRequest.counted`): `input_tokens` less `input_tokens_details`' `cached_tokens` and `cache_write_tokens` as input, those two as cache read and write, and no output, as OpenAI bills none, so gpt-6-luna's own rates price it. `native_endpoints` is about the chat APIs a model is relayed on, and stays chat/completions and responses. A model that answers System One (`systemOneTargets`: a decision group's members, else `provider.RouteDecider`'s, none of them a provider `canDecide` takes, so another magpie still gets the Decisions body) is asked there instead (wudi_boy on Discord: Qwen's decision-model-preview on Decisions was refused): `decisionsAsSystemOne` turns predicate into `noul`, choice into a criteria map (a boolean value as "true"/"false"), score into a criteria list of `label: description` least first, an unnamed question into `question_N` answered with a null name, and `input` into the state (a string, or `{"messages":[{role, content, refusal}]}` with `input_json` as its JSON text); `serveSystemOneBody` serves it, and `systemOneAsDecision` gives the Decisions answer (a choice's value typed back, a score's probabilities by index or label, a missing answer a `refusal`, usage input and output with no cache split). The prompt-cache hints and `safety_identifier` change no answer and are left out; anything else with no counterpart is a 400 naming it before a vendor is asked (`untranslated`: an image unless every target is a Clef or another magpie, an http image, a function or custom tool call or its output, an image or refusal in a question, any other field or question type). The reverse: `/v1/systemone` whose `RouteDecider` finds no System One provider (its 404) but `resolveRetrievalModel` resolves the model is `systemOneByDecisions`, sent through `serveRetrieval` as above (`systemOneAsDecisions`, `decisionAsSystemOne`). A vendor's error passes through as it was said. `TestDecisionsAskSystemOne`, `TestDecisionsMessagesAsSystemOneState`, `TestDecisionsUntranslatableRefused`, `TestDecisionsImagesToClef`, `TestSystemOneAsksDecisions`. `TestDecisionsReachOpenAIAndAzure`, `TestDecisionsRefusedWhereNotServed`, `TestCanDecide`, `TestDecisionsThroughAnotherMagpie`, `TestDecisionsHeldByKeysAndRules`. | [`decisions.go`](../../internal/gateway/decisions.go), [`decisions_systemone.go`](../../internal/gateway/decisions_systemone.go), [`embeddings.go`](../../internal/gateway/embeddings.go), [`media_group.go`](../../internal/gateway/media_group.go) | | Affinity | A conversation stays with the key or account that answered it, so the vendor's prompt cache is read again. Modes: auto (""), `session`, `turn`, `off`, `strict`. Stored in `affinity.json` next to `providers.json`. A conversation is kept by its id (`affinityID`, in `stickKey` and `ruleKey`): the agent's session header, else the caller's `X-Magpie-Session` (#5242: requests that each named a session of their own, and opened alike, were taken for one conversation and kept together; `TestMagpieSessionIsTheConversation`), else (`conversationID`, which is what Kilo and a plugin are sent as the conversation, so `X-Magpie-Session` never goes upstream) a hash of how the conversation opens, which every later turn repeats: its first user message, or, when the agent wrote that one alone (`userWords`: an `` block, Reasonix's ``, an instruction file), the user messages from it through the first that holds the user's own words, an image, a file or a recording (`conversationOpening`, `userOpens`). A system or developer message between them is passed over; a reply, a call or a tool's result ends the opening, and with none of the user's before it the first message is hashed alone. One message is hashed as the request has it; several are hashed without their cache marks and with a content of one text part read as that text (`writeOpening`), since an agent moves its mark on to each turn's newest message, some spelling a marked message as one part and an unmarked one as a string (`TestCacheMarkMovingOnKeepsTheID`). Before, the first message was always hashed alone, and every conversation an agent opened on the same message in one folder was one: kept under `session` on the account that answered the first, and never moved on by rotate (keeyangyy, #3938, `TestConversationsOnOneEnvironmentMessageAreApart`, `TestReasonixConversationsInOneWorkspaceAreApart`, `TestNewConversationsInOneFolderAreRoutedApart`). A conversation whose first user message is the user's own keeps the id it had, which the Context page and the Routing page's requests find dsh's sessions by (`dshConvs`, `routeOwners`, `routeSessions`): dsh's pi-ai routes send no session header. A dsh fork repeats its source's opening, so a finished request is named by the id of the reply its client was given (`Route.ResponseID`, set from `clientResponseID` as the route is marked done), which dsh writes down on that reply (`replayState.response.responseId`, read into `Session.ResponseIDs`: a fork's own replies after its `session/end-seed` only). Vendors' reply ids can repeat, so a reply's id names a session over the opening only when the opening is that session's own or that of a session it was forked from (`ForkOf`, from the fork's `parentSession`; `ownerOf`), and Routing reads the sessions again for a reply id it has not found only up to a minute after the request ended (`looseKeys`): a title call's id is never written down (#5491, Flandern1211). A request still running or failed, and one logged before Route had the id, keeps the opening's session. A Claude Code subagent's is kept apart from its lead's by `x-claude-code-agent-id` (`stickKey`): Claude Code sends the session's id with its subagents' requests too, and a subagent's answer took the lead's stick over, so the lead's next turn was judged by the subagent's cache and moved to another account, where its whole conversation was written again (slkassinthehood on X, `TestClaudeConversationKeepsItsAccountsCache`). Behind a remote magpie, the key or account is the remote's key and the provider there that serves the model, its id's first part (`remoteUpstream`, `candidate.vendor`, `sameVendor`): the remote is one key here, but each of its providers keeps its own cache and seals, so a conversation is kept, held strictly, told its seals were refused and given its native compaction's reader by that pair, as the same group on the remote does (fremontdango on Discord: a group of one model from two of the remote's providers kept a conversation on the second as the same account when the first was gone, and a strict one failed over to it; `TestRemoteMagpieStrictKeepsTheRemotesProvider`, `TestRemoteMagpieOtherProviderIsNotTheSameAccount`). A remote's group is one vendor by its whole id, its own routing deciding inside it; a model named without a provider is the key alone. Lanes and requests a minute still go by the key here, the limits the user set on it. | [`affinity.go`](../../internal/gateway/affinity.go) | | One try | `attempt` sends one candidate the request. It goes through the proxy of the account or key it uses, else the provider's (`p.Via`, `ProxyChoice`: `AccountProxies` holds an account's by its name, a key's by its `KeyID`). A request magpie makes for one provider while serving another's (a web search, an image description, a classifier call) takes its own provider's proxy or the global one, never the outer one: `netproxy.With` replaces a choice the context already names, "" too, and `webSearch` starts from none, so the search APIs follow the global proxy (#1522). A provider of the user's set not to check its certificate (`InsecureTLS`, #2383) has it skipped for its own base URLs' hosts alone, through `p.Via` ([Providers and accounts](providers-accounts.md)), and one held to HTTP/1.1 (`HTTP1`) is spoken it at those hosts alone. A TLS record error read on an HTTP/2 connection ("bad record MAC", "received record with version …": the bytes under the TLS were mangled, by the far side or a box between) drops that connection, as Go's transport does, and `netproxy.Dispatch` sends the requests to that host:port over HTTP/1.1 for 6 hours after (`markH2Broken`, `h2BrokenFor`; kepner_53726: a company gateway failed 124 turns in 3 days so, each a 200 with no output, until a restart; `TestH2RecordErrorMovesHostToHTTP1`). Every request to one vendor's host shares one HTTP/2 connection (`upstreamTransport`); one silent for 10s (no HEADERS or DATA from the vendor since the last request) is pinged, and dropped when no answer comes within 10s, so a connection gone silent without closing (a proxy's way out died, a NAT forgot the flow) fails the requests on it, which move on as a 502 does, and the next request dials a new one. A live vendor answers a ping whatever its streams are doing, so a long wait for a first byte is not cut by it (#2843: a group's requests hung with no first byte until a restart; `TestGroupMovesOnFromSilentHTTP2Connection`). A silence answered is pinged again only 5 minutes on (`netproxy.CalmHTTP2`, `PingAgain`): Go's own health check pings it every 10s, its ping's answer restarting its clock, and Google's front end, holding clients to gRPC's ping policy (a ping within 5 minutes of the last with nothing sent between is a strike, and the third ends the connection), ended a turn of gemini thinking through Antigravity at ~235s with GOAWAY ENHANCE_YOUR_CALM "too_many_pings" (zdevoz on Discord; `TestLongSilenceIsNotPingedIntoGoaway`, `TestCalmFindsAPathDeadLaterInTheSilence`). The try after a GOAWAY goes on a new connection (`TestTryAfterGoawayDialsAnew`). `http.DefaultTransport`, whose requests are short, keeps Go's (`netproxy.HTTP2Health`). A large body (64KB or more, or of no stated length) is pinged too, as a silent connection takes a body that fits its send buffer, but its ping's answer is queued behind the body's own DATA, so on a slow uplink a working connection loses it (#3909: a ~680KB turn on a 2-10KB/s uplink failed every try). Such a body whose connection was dropped for a lost ping is sent once more, through `GetBody`, on a new connection that is not pinged and is given up on when a write moves no bytes for a minute (`uploadTransport`); for 30 minutes after, large bodies go there at once (`drawsApart.slow`; `TestUploadStillUnderwayIsNotCutByHealthPing`, `TestSlowUplinkSkipsTheLostTry`, `TestLargeBodyOnSilentConnectionIsSentAgain`). A subscription with its own client is served specially, such as Claude through the genuine Claude Code. The request is relayed as is (`passthrough`) when the model is usable on the agent's API, except that a Claude model where the provider has an Anthropic URL is translated to Messages from Chat or Responses too (`OnMessages`: OpenCode speaks Chat for every model, and a relay drops cache_control there), unless the user set the model's API or the vendor's list names its APIs. An account that only streams (`Account.Stream`: a plugin's, and most subscriptions magpie signs in to) has a request that asked for one body translated, which magpie always asks streamed, except a plugin's on Responses (`gathers`): that is relayed all the same, asked with `stream:true`, and the client given the `response` of the stream's `response.completed` (or `response.incomplete`) as one JSON body (`gathered` in [`gathered.go`](../../internal/gateway/gathered.go); its `output` filled from the stream's `response.output_item.done` items, or else its text, when that event's is empty). So the tools the vendor runs itself, and its response's `tools` and usage details, reach the client (plugins#112: a translation dropped Grok's `x_search`, and Grok answered without searching; `TestGrokPluginNonStreamKeepsHostedTools`). A stream that fails or ends before that event is a 502 (`TestGrokPluginNonStreamEndedShort`), never an empty 200. A Messages request is still translated, its stream having no event that holds the whole reply, and so is a subscription magpie signs in to itself (the ChatGPT backend's, Qoder's): its own code fits its requests. A request offering web search to a provider that doesn't search by itself is translated too, so magpie can search for it (`search.go`; a provider that searches for some of its models only, Command Code's Provider API, lists them in `searchModels` by API, and none count under its `x-cmd-zdr` header, #1590), but on the agent's own API where the provider serves it and no `ResponsesFirst`/`MessagesFirst` rule prefers another: Codex offers web_search on every turn, and each went out as Chat (#997). Otherwise it is translated (`translate`) to the first API `usable` gives: Chat, except Responses for OpenAI's models where their maker serves them (`ResponsesFirst`), Responses for every model at ModelScope, whose Chat API reports neither the tokens its cache answered nor reasoning while its Responses API reports both (`ResponsesTellsCache`, #1578; a 404 there sends the model to Chat, and only there), and Anthropic's Messages for a Claude model where the provider has an Anthropic URL (`MessagesFirst`, which keeps its cache breakpoints, #997). An API that answers the model is not served there (`wrongEndpoint`, `catalog.WrongEndpoint`: the English wordings and AgentRouter's Chinese one, #3766, read escaped too; a model's test reads them as well, see [Providers and accounts](providers-accounts.md)) is remembered in `unfit` until magpie restarts. A Chat API that refuses function tools with reasoning, with no other API to take them to, is asked once more with `reasoning_effort` `none` (#176), unless `none` is known refused (`turnedAway`); `none` refused naming the levels, the tools refusal is the answer, not a retry at the lowest level (#2670). When every API has turned the model away, the API the user picked for it (`ModelAPI`) is asked again, and without a pick each API the provider has a URL for (`Speaks`), Chat first. `Provider.Native`, the API agents with a per-model API (Pi, omp, droid) are wired to ask on, follows the same order. A custom provider with a Gemini URL (#1346) has Gemini last among the APIs it speaks: a Gemini client's request is relayed there, and any other is translated to it when it has no other, or when the user set Gemini as the model's API (`SetModelAPI` takes chat, responses, anthropic or gemini, each only where the provider has its URL, from the editor's Save or `magpie model api`; a model set to Gemini has no `Native`, so those agents ask it on their own API and it is translated). Upstream it is always asked `models/{model}:streamGenerateContent?alt=sse` under the base (`upstreamPath`), the model only in the path (`forwardOnce` drops the body's), so a Gemini client that asked for one JSON body is translated, as for Factory's generate route. It goes to the first API `usable` gives, Chat where the provider has a Chat URL too, except one that asks an image's size or shape (`generationConfig.imageConfig`), which only a Gemini API takes: that one is translated on the Gemini URL (#3820, `TestGeminiImageConfigGoesToTheGeminiAPIBesideChat`). | [`gateway.go`](../../internal/gateway/gateway.go) | diff --git a/internal/gateway/draw.go b/internal/gateway/draw.go index 4392dda6b..ecdecc3ca 100644 --- a/internal/gateway/draw.go +++ b/internal/gateway/draw.go @@ -661,10 +661,23 @@ type drawing struct { // text. Extra map[string]any Form bool + // Tier is the resolution asked (1K, 2K, 4K; draw_tier.go): the + // request's resolution, or a tier given as size. "" for the model's own, + // as with a WIDTHxHEIGHT size, which is the size asked + Tier string +} + +// shape is d's size without a tier given as size: a ratio, WIDTHxHEIGHT, +// or "". +func (d drawing) shape() string { + if tierOf(d.Size) != "" { + return "" + } + return d.Size } // drawingRead are the fields of an images request magpie reads itself. -var drawingRead = []string{"model", "prompt", "size", "quality", "complexity", "background", "output_format", "response_format", "n", "image", "image[]", "images", "mask", "markup", "user"} +var drawingRead = []string{"model", "prompt", "size", "quality", "complexity", "background", "output_format", "response_format", "n", "image", "image[]", "images", "mask", "markup", "user", "resolution"} // extraOf keeps v as one of d's Extra under k, unless magpie reads k. func (d *drawing) extraOf(k string, v any) { @@ -978,6 +991,7 @@ func vendorSaid(text string) string { // edits take. func readDrawing(r *http.Request) (drawing, error) { var d drawing + var resolution string ct, _, _ := mime.ParseMediaType(r.Header.Get("Content-Type")) if ct == "multipart/form-data" { if err := r.ParseMultipartForm(64 << 20); err != nil { @@ -994,6 +1008,7 @@ func readDrawing(r *http.Request) (drawing, error) { d.N, _ = strconv.Atoi(get("n")) d.Complexity = get("complexity") d.Form = true + resolution = get("resolution") for k := range f.Value { d.extraOf(k, get(k)) } @@ -1039,11 +1054,15 @@ func readDrawing(r *http.Request) (drawing, error) { Mask json.RawMessage `json:"mask"` Markup json.RawMessage `json:"markup"` ResponseFormat string `json:"response_format"` + Resolution any `json:"resolution"` } if err := json.Unmarshal(body, &in); err != nil { return d, fmt.Errorf("the request isn't JSON: %v", err) } d = drawing{Model: in.Model, Prompt: in.Prompt, Size: in.Size, Quality: in.Quality, Complexity: strings.TrimSpace(in.Complexity), Background: in.Background, Format: in.Format, Want: strings.TrimSpace(in.ResponseFormat), N: in.N} + if in.Resolution != nil { + resolution = fmt.Sprint(in.Resolution) + } var all map[string]any json.Unmarshal(body, &all) for k, v := range all { @@ -1082,6 +1101,9 @@ func readDrawing(r *http.Request) (drawing, error) { if strings.TrimSpace(d.Prompt) == "" && (d.Extra["layer_decomposition"] == nil || len(d.Images) == 0) { return d, errors.New("say what to draw in prompt") } + if err := d.settleTier(resolution); err != nil { + return d, err + } if d.N <= 0 { d.N = 1 } @@ -1401,8 +1423,24 @@ func accountRefusedDrawing(code int) bool { } // draw asks the provider for d's images, on the API model draws on there, -// and on the other when that one isn't served. +// and on the other when that one isn't served. A drawing asked at a tier +// the vendor turns away is asked once more at the model's own size +// (draw_tier.go), so a resolution set in Settings never keeps an image +// from being drawn. func (s *Server) draw(ctx context.Context, p provider.Provider, model string, d drawing) (drawn, int, error) { + out, code, err := s.drawAsked(ctx, p, model, d) + if tierRefused(d, code, err) && ctx.Err() == nil { + plain := d + plain.Tier = "" + plain.Size = d.shape() + if o, c, e := s.drawAsked(ctx, p, model, plain); e == nil { + return o, c, e + } + } + return out, code, err +} + +func (s *Server) drawAsked(ctx context.Context, p provider.Provider, model string, d drawing) (drawn, int, error) { // the headers the user gave the image model ctx = provider.WithModel(ctx, p.ID, model) if drawsWorkBuddy(p) { @@ -1666,12 +1704,10 @@ func (s *Server) drawImages(ctx context.Context, p provider.Provider, model stri var body []byte var ct, url string m := strings.ToLower(model) + size := imagesAPISize(p, model, d) if drawsGrok(p) { // Grok's Imagine API takes an aspect ratio, not a size or a quality - req := map[string]any{"model": model, "prompt": d.Prompt, "n": d.N, "response_format": "b64_json"} - if ar := aspectAmong(d.Size, grokAspects); ar != "" { - req["aspect_ratio"] = ar - } + req := grokImagesReq(model, d) if len(d.Images) > 0 { var imgs []map[string]string for _, pic := range d.Images { @@ -1685,13 +1721,17 @@ func (s *Server) drawImages(ctx context.Context, p provider.Provider, model stri body, _ = json.Marshal(req) } else if len(d.Images) == 0 { req := map[string]any{"model": model, "prompt": d.Prompt, "n": d.N} - fields := map[string]string{"size": d.Size, "quality": d.Quality, "background": d.Background, "output_format": d.Format} + fields := map[string]string{"size": size, "quality": d.Quality, "background": d.Background, "output_format": d.Format} if drawsCopilot(p) { // Copilot CLI sends model, prompt, size and quality - fields = map[string]string{"size": d.Size, "quality": d.Quality} + fields = map[string]string{"size": size, "quality": d.Quality} } else if !drawsCodex(p) { fields["complexity"] = d.Complexity } + if p.IsRemoteMagpie() { + // the other magpie sends it on in its vendor's own field + fields["resolution"] = d.Tier + } for k, v := range fields { if v != "" { req[k] = v @@ -1711,7 +1751,7 @@ func (s *Server) drawImages(ctx context.Context, p provider.Provider, model stri if senseNovaDrawer(m) { req["response_format"] = "b64_json" } - for k, v := range map[string]string{"size": d.Size, "quality": d.Quality, "background": d.Background, "output_format": d.Format} { + for k, v := range map[string]string{"size": size, "quality": d.Quality, "background": d.Background, "output_format": d.Format} { if v != "" { req[k] = v } @@ -1732,7 +1772,7 @@ func (s *Server) drawImages(ctx context.Context, p provider.Provider, model stri } else { var buf bytes.Buffer mw := multipart.NewWriter(&buf) - for k, v := range map[string]string{"model": model, "prompt": d.Prompt, "n": strconv.Itoa(d.N), "size": d.Size, "quality": d.Quality, "complexity": d.Complexity, "background": d.Background, "output_format": d.Format} { + for k, v := range map[string]string{"model": model, "prompt": d.Prompt, "n": strconv.Itoa(d.N), "size": size, "quality": d.Quality, "complexity": d.Complexity, "background": d.Background, "output_format": d.Format} { if v != "" { mw.WriteField(k, v) } @@ -1740,6 +1780,9 @@ func (s *Server) drawImages(ctx context.Context, p provider.Provider, model stri if strings.Contains(m, "dall-e") { mw.WriteField("response_format", "b64_json") } + if p.IsRemoteMagpie() && d.Tier != "" { + mw.WriteField("resolution", d.Tier) + } field := "image" if len(d.Images) > 1 { field = "image[]" @@ -1797,13 +1840,29 @@ func (s *Server) drawOpenRouterImages(ctx context.Context, p provider.Provider, if d.Markup != nil { return drawn{}, http.StatusBadRequest, errors.New("OpenRouter's images API does not support a markup layer") } + body, _ := json.Marshal(openRouterImagesReq(model, d)) + url := strings.TrimRight(p.Base(provider.Chat), "/") + "/images" + b, code, err := s.send(ctx, p, url, "application/json", body, true) + if err != nil { + return drawn{}, code, err + } + return readImagesAnswer(p, url, b, code) +} + +// openRouterImagesReq is d as OpenRouter's Image API takes it. +func openRouterImagesReq(model string, d drawing) map[string]any { req := map[string]any{"model": model, "prompt": d.Prompt, "n": d.N} for k, v := range map[string]string{"quality": d.Quality, "background": d.Background, "output_format": d.Format} { if v != "" { req[k] = v } } - openRouterSize(req, model, d.Size) + openRouterSize(req, model, d.shape()) + if d.Tier != "" && takesImageSize(model) { + // OpenRouter's own field for it (512 to 4K); a model that draws at + // 1K alone is asked at its own + req["resolution"] = d.Tier + } if len(d.Images) > 0 { refs := make([]map[string]any, 0, len(d.Images)) for _, pic := range d.Images { @@ -1811,13 +1870,7 @@ func (s *Server) drawOpenRouterImages(ctx context.Context, p provider.Provider, } req["input_references"] = refs } - body, _ := json.Marshal(req) - url := strings.TrimRight(p.Base(provider.Chat), "/") + "/images" - b, code, err := s.send(ctx, p, url, "application/json", body, true) - if err != nil { - return drawn{}, code, err - } - return readImagesAnswer(p, url, b, code) + return req } // openRouterSize puts an images API size into req as OpenRouter's Image API @@ -2032,7 +2085,7 @@ func extOf(mimeType string) string { func drawPrompt(d drawing) string { var b strings.Builder b.WriteString(d.Prompt) - if r := aspectOf(d.Size); r != "" { + if r := aspectOf(d.shape()); r != "" { fmt.Fprintf(&b, "\n\nAspect ratio: %s.", r) } if d.Background == "transparent" { @@ -2050,8 +2103,8 @@ func (s *Server) drawChat(ctx context.Context, p provider.Provider, model string } req := map[string]any{"model": model, "stream": false, "modalities": []string{"image", "text"}, "messages": []map[string]any{{"role": "user", "content": content}}} - if r := aspectOf(d.Size); r != "" { - req["image_config"] = map[string]string{"aspect_ratio": r} + if c := chatImageConfig(model, d); c != nil { + req["image_config"] = c } body, _ := json.Marshal(req) url := strings.TrimRight(p.Base(provider.Chat), "/") + "/chat/completions" @@ -2148,7 +2201,7 @@ func (s *Server) drawGemini(ctx context.Context, p provider.Provider, model stri parts = append(parts, map[string]any{"inlineData": map[string]string{"mimeType": pic.Mime, "data": base64.StdEncoding.EncodeToString(pic.Data)}}) } cfg := map[string]any{"responseModalities": []string{"TEXT", "IMAGE"}} - if c := imageConfigOf(model, d.Size); c != nil { + if c := imageConfigOf(model, d.shape(), d.Tier); c != nil { cfg["imageConfig"] = c } body, _ := json.Marshal(map[string]any{"contents": []map[string]any{{"role": "user", "parts": parts}}, "generationConfig": cfg}) @@ -2225,7 +2278,7 @@ func (s *Server) drawCodeAssist(ctx context.Context, p provider.Provider, model parts = append(parts, Part{Kind: Image, MediaType: pic.Mime, Data: base64.StdEncoding.EncodeToString(pic.Data)}) } req := &Request{Messages: []Message{{Role: "user", Parts: parts}}, draws: true} - if c := imageConfigOf(model, d.Size); c != nil { + if c := imageConfigOf(model, d.shape(), d.Tier); c != nil { // the size and shape the images API asked, in the field a Gemini // client's own imageConfig arrives in, which buildCodeAssistSent // puts in generationConfig @@ -2342,15 +2395,18 @@ func imageSizeOf(size string) string { // imageConfigOf is the imageConfig an images API size asks a Gemini image // model to draw at: the ratio the size is nearest, with the imageSize -// beside it when the size asks past the model's 1K default and the model -// takes one (takesImageSize). nil for none. -func imageConfigOf(model, size string) map[string]string { +// beside it when a tier is asked, or the size asks past the model's 1K +// default, and the model takes one (takesImageSize). nil for none. +func imageConfigOf(model, size, tier string) map[string]string { c := map[string]string{} if r := aspectOf(size); r != "" { c["aspectRatio"] = r } - if s := imageSizeOf(size); s != "" && takesImageSize(model) { - c["imageSize"] = s + if tier == "" { + tier = imageSizeOf(size) + } + if tier != "" && takesImageSize(model) { + c["imageSize"] = tier } if len(c) == 0 { return nil diff --git a/internal/gateway/draw_minimax.go b/internal/gateway/draw_minimax.go index f43e7ce78..8c9c1e82f 100644 --- a/internal/gateway/draw_minimax.go +++ b/internal/gateway/draw_minimax.go @@ -131,6 +131,9 @@ func minimaxH3Body(model string, d drawing) ([]byte, string, error) { } req := map[string]any{"model": model, "prompt": d.Prompt, "n": min(max(d.N, 1), 10)} minimaxH3Size(req, d.Size) + if _, px := req["size"]; d.Tier != "" && !px { + req["area"] = d.Tier + } switch f := strings.ToLower(d.Format); f { case "png", "jpeg", "jpg", "webp": req["output_format"] = f diff --git a/internal/gateway/draw_tier.go b/internal/gateway/draw_tier.go new file mode 100644 index 000000000..258166e2f --- /dev/null +++ b/internal/gateway/draw_tier.go @@ -0,0 +1,421 @@ +package gateway + +// A resolution tier (1K, 2K, 4K) is how large an image is asked to be +// drawn, apart from its shape (skingstyle48487 on X: a 4K asked through the +// image MCP came back at 2K). Settings › Images › Resolution sets the one +// the image MCP asks when the agent names none (settings.ImageResolution), +// and an agent can name one in generate_image's resolution, or in size +// ("4K"). The images API takes it as resolution, OpenRouter's name for it, +// and each vendor is asked for it in its own field: +// +// - Gemini's generateContent: imageConfig.imageSize "1K", "2K" or "4K" +// (the Gemini 3 image models; a 2.x or Lite one draws at 1K alone); +// - chat completions (OpenRouter, a relay's Gemini): image_config's +// image_size beside its aspect_ratio, for a Gemini image model; +// - OpenRouter's Image API: resolution; +// - Ark's Seedream: size as the tier, or the doc's WIDTHxHEIGHT for the +// ratio asked at that tier (each model takes the tiers its doc lists: +// https://docs.volcengine.com/docs/82379/1541523); +// - xAI's Imagine: resolution "1k" or "2k", its largest; +// - MiniMax's H3-Image: area; +// - an OpenAI-shaped images API (GPT Image 2 and later, a relay's +// models): size as the WIDTHxHEIGHT the tier is at the ratio asked, +// within GPT Image 2's 3840px edge and 8,294,400 pixels. +// +// A model whose sizes stop short of a tier (GPT Image 1, DALL·E, a 2.x +// Gemini) is asked at its own size; and a vendor that turns the tier away +// with a 400 is asked once more without it (drawTiered), so a tier set in +// Settings never stops an image being drawn. An explicit WIDTHxHEIGHT from +// the agent is the size, over any tier. + +import ( + "bytes" + "fmt" + "image" + "math" + "slices" + "strconv" + "strings" + + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/settings" +) + +// tierOf is s as a resolution tier, "1K", "2K" or "4K", in any case; "" for +// anything else. +func tierOf(s string) string { + switch t := strings.ToUpper(strings.TrimSpace(s)); t { + case "1K", "2K", "4K": + return t + } + return "" +} + +// isPixels is whether size is WIDTHxHEIGHT. +func isPixels(size string) bool { + w, h, ok := strings.Cut(strings.ToLower(strings.TrimSpace(size)), "x") + if !ok { + return false + } + x, err1 := strconv.Atoi(strings.TrimSpace(w)) + y, err2 := strconv.Atoi(strings.TrimSpace(h)) + return err1 == nil && err2 == nil && x > 0 && y > 0 +} + +// settleTier reads a drawing's tier: resolution as given, or a tier given +// as size ("4K"; d.shape() leaves it out where the tier is sent). A +// WIDTHxHEIGHT size is the size asked, and no tier goes beside it. A +// resolution that isn't a tier (or auto) is an error. +func (d *drawing) settleTier(resolution string) error { + resolution = strings.TrimSpace(resolution) + t := tierOf(resolution) + if t == "" && resolution != "" && !strings.EqualFold(resolution, "auto") { + return fmt.Errorf("resolution is 1K, 2K or 4K (or auto for the model's own), not %q", resolution) + } + if st := tierOf(d.Size); st != "" && t == "" && !strings.EqualFold(resolution, "auto") { + t = st + } + if isPixels(d.Size) { + t = "" + } + d.Tier = t + return nil +} + +// ImageTier is the resolution the image MCP asks the images API for: the +// one the agent named (arg: 1K, 2K, 4K, or auto for none), else, unless +// the agent gave a size of its own (WIDTHxHEIGHT, or a tier as size), +// Settings › Images › Resolution's. "" asks for none. +func ImageTier(arg, size string) (string, error) { + arg = strings.TrimSpace(arg) + switch { + case strings.EqualFold(arg, "auto"): + return "", nil + case tierOf(arg) != "": + return tierOf(arg), nil + case arg != "": + return "", fmt.Errorf("resolution is 1K, 2K or 4K (or auto for the model's own), not %q", arg) + } + if size = strings.TrimSpace(size); size != "" && !strings.EqualFold(size, "auto") && !strings.Contains(size, ":") { + return "", nil + } + return tierOf(settings.Load().ImageResolution), nil +} + +// tierEdge is the long side, in pixels, a tier names. +func tierEdge(t string) int { + switch t { + case "1K": + return 1024 + case "2K": + return 2048 + case "4K": + return 4096 + } + return 0 +} + +// bareModel is a model id as its maker names it: without models/ or a +// relay's vendor/ before it, in lower case. +func bareModel(model string) string { + m := strings.ToLower(strings.TrimSpace(model)) + if i := strings.LastIndex(m, "/"); i >= 0 { + m = m[i+1:] + } + return m +} + +// geminiImage is whether model is a Gemini image model (Nano Banana) that +// takes an imageSize past 1K. +func geminiImage(model string) bool { + m := bareModel(model) + return (strings.HasPrefix(m, "gemini-") || strings.HasPrefix(m, "nano-banana")) && takesImageSize(model) +} + +// fixedSizes is whether model draws only at sizes of its own, none of +// them past 1536px: DALL·E's and GPT Image 1's (1, 1.5, mini). +func fixedSizes(model string) bool { + m := bareModel(model) + return strings.HasPrefix(m, "dall-e") || strings.HasPrefix(m, "gpt-image-1") || strings.HasPrefix(m, "chatgpt-image") +} + +// gptImageAny is whether model is GPT Image 2 or later, which draws at any +// WIDTHxHEIGHT within its limits. +func gptImageAny(model string) bool { + m := bareModel(model) + rest, ok := strings.CutPrefix(m, "gpt-image-") + if !ok { + return false + } + n := strings.IndexFunc(rest, func(r rune) bool { return r < '0' || r > '9' }) + if n < 0 { + n = len(rest) + } + v, err := strconv.Atoi(rest[:n]) + return err == nil && v >= 2 +} + +// ratioParts is a ratio "16:9" as its two sides; 1:1 for none. +func ratioParts(r string) (float64, float64) { + a, b, ok := strings.Cut(strings.ReplaceAll(r, " ", ""), ":") + x, err1 := strconv.ParseFloat(a, 64) + y, err2 := strconv.ParseFloat(b, 64) + if !ok || err1 != nil || err2 != nil || x <= 0 || y <= 0 { + return 1, 1 + } + return x, y +} + +// tierPixels is WIDTHxHEIGHT for tier t at ratio r (1:1 for none): its long +// side the tier's, each side a multiple of 16. gpt holds it to GPT Image +// 2's limits: an edge of 3840 at most, 655,360 to 8,294,400 pixels. +func tierPixels(t, r string, gpt bool) string { + a, b := ratioParts(r) + edge := float64(tierEdge(t)) + if gpt { + edge = min(edge, 3840) + } + w, h := edge, edge*b/a + if b > a { + w, h = edge*a/b, edge + } + round := math.Round + if gpt { + const most, least = 8294400, 655360 + if area := w * h; area > most { + f := math.Sqrt(most / area) + w, h, round = w*f, h*f, math.Floor + } else if area < least { + f := math.Sqrt(least / area) + w, h, round = w*f, h*f, math.Ceil + } + } + px := func(v float64) int { return max(16, int(round(v/16))*16) } + return fmt.Sprintf("%dx%d", px(w), px(h)) +} + +// seedreamTiers are the tiers each Seedream model's size takes, as Ark's +// doc lists them, and arkTierSizes the WIDTHxHEIGHT its tables give each +// ratio at a tier: Seedream 4.0's for 1K, 4.0, 4.5 and 5.0 lite's for 2K +// and 4K, and 5.x pro and flash's own. +var ( + seedream40Tiers = []string{"1K", "2K", "4K"} + seedream45Tiers = []string{"2K", "4K"} + seedream5LiteTier = []string{"2K", "3K", "4K"} + seedream5Tiers = []string{"1K", "1.5K", "2K"} +) + +var arkTierSizes = map[string]map[string]string{ + "1K": {"1:1": "1024x1024", "4:3": "1152x864", "3:4": "864x1152", "16:9": "1280x720", "9:16": "720x1280", "3:2": "1248x832", "2:3": "832x1248", "21:9": "1512x648"}, + "2K": arkRatioSizes, + "4K": {"1:1": "4096x4096", "4:3": "4704x3520", "3:4": "3520x4704", "16:9": "5504x3040", "9:16": "3040x5504", "3:2": "4992x3328", "2:3": "3328x4992", "21:9": "6240x2656"}, +} + +// seedream5Sizes are Seedream 5.x pro and flash's sizes (5.5's too). +var seedream5Sizes = map[string]map[string]string{ + "1K": {"1:1": "1024x1024", "4:3": "1152x864", "3:4": "864x1152", "16:9": "1424x800", "9:16": "800x1424", "3:2": "1248x832", "2:3": "832x1248", "21:9": "1568x672"}, + "2K": {"1:1": "2048x2048", "4:3": "2368x1776", "3:4": "1776x2368", "16:9": "2816x1584", "9:16": "1584x2816", "3:2": "2496x1664", "2:3": "1664x2496", "21:9": "3136x1344"}, +} + +// seedreamTiersOf is the tiers a Seedream model takes; nil for one magpie +// doesn't know, which is asked the tier as given. +func seedreamTiersOf(model string) []string { + m := strings.ReplaceAll(bareModel(model), ".", "-") + switch { + case !strings.Contains(m, "seedream"): + return nil + case strings.Contains(m, "seedream-4-5"): + return seedream45Tiers + case strings.Contains(m, "seedream-4"): + return seedream40Tiers + case strings.Contains(m, "seedream-5-0-lite") || strings.Contains(m, "seedream-5-lite"): + return seedream5LiteTier + case strings.Contains(m, "seedream-5"): + return seedream5Tiers + } + return nil +} + +// tierValue is a tier's size in K, for nearest. +func tierValue(t string) float64 { + v, _ := strconv.ParseFloat(strings.TrimSuffix(t, "K"), 64) + return v +} + +// nearestTier is the largest of tiers at or under t, else the smallest. +func nearestTier(t string, tiers []string) string { + if len(tiers) == 0 || slices.Contains(tiers, t) { + return t + } + best := "" + for _, x := range tiers { + if tierValue(x) <= tierValue(t) && (best == "" || tierValue(x) > tierValue(best)) { + best = x + } + } + if best == "" { + best = tiers[0] + } + return best +} + +// isSeedream is whether model is a Seedream. +func isSeedream(model string) bool { + return strings.Contains(bareModel(model), "seedream") +} + +// seedreamSize is size and tier t as a Seedream model takes size: the tier +// it takes nearest t, as the tier with no ratio asked, or as the doc's +// WIDTHxHEIGHT for the ratio at that tier. size alone is arkSize's. +func seedreamSize(model, size, t string) (string, error) { + if t == "" { + return arkSize(size) + } + t = nearestTier(t, seedreamTiersOf(model)) + size = strings.ReplaceAll(strings.TrimSpace(size), " ", "") + if size == "" || strings.EqualFold(size, "auto") || !strings.Contains(size, ":") { + return t, nil + } + table := arkTierSizes + if slices.Equal(seedreamTiersOf(model), seedream5Tiers) { + table = seedream5Sizes + } + if px, ok := table[t][size]; ok { + return px, nil + } + if _, ok := table["2K"][size]; ok { + // a tier with no table of its own (1.5K, 3K): asked as the tier, + // the ratio in the prompt as the doc says + return t, nil + } + return arkSize(size) +} + +// imagesAPISize is the size an OpenAI-shaped images API is sent for d: +// d's own, or with a tier, the WIDTHxHEIGHT the tier is at d's ratio +// for a model that takes it. +func imagesAPISize(p provider.Provider, model string, d drawing) string { + if d.Tier == "" || p.IsRemoteMagpie() { + return d.Size + } + m := strings.ToLower(model) + switch { + case isSeedream(model): + if s, err := seedreamSize(model, d.shape(), d.Tier); err == nil { + return s + } + return d.shape() + case fixedSizes(model) || senseNovaDrawer(m): + return d.shape() + } + r := aspectOf(d.shape()) + return tierPixels(d.Tier, r, gptImageAny(model) || drawsCodex(p) || drawsCopilot(p)) +} + +// grokImagesReq is d as xAI's Imagine API takes it, but its images: an +// aspect ratio and a resolution, not a size or a quality. +func grokImagesReq(model string, d drawing) map[string]any { + req := map[string]any{"model": model, "prompt": d.Prompt, "n": d.N, "response_format": "b64_json"} + if ar := aspectAmong(d.shape(), grokAspects); ar != "" { + req["aspect_ratio"] = ar + } + if t := grokResolution(d.Tier); t != "" { + req["resolution"] = t + } + return req +} + +// grokResolution is tier t as xAI's Imagine takes resolution: 1k or 2k, +// its largest; "" for none. +func grokResolution(t string) string { + switch t { + case "1K": + return "1k" + case "2K", "4K": + return "2k" + } + return "" +} + +// chatImageConfig is the image_config a chat model is asked to draw with: +// the ratio, and for a Gemini image model the image_size (a tier, or what +// a pixel size asks past 1K), as OpenRouter's and relays' chat completions +// take them. nil for none. +func chatImageConfig(model string, d drawing) map[string]string { + c := map[string]string{} + if r := aspectOf(d.shape()); r != "" { + c["aspect_ratio"] = r + } + t := d.Tier + if t == "" { + t = imageSizeOf(d.Size) + } + if t != "" && geminiImage(model) { + c["image_size"] = t + } + if len(c) == 0 { + return nil + } + return c +} + +// tierRefused is whether a vendor's refusal of a drawing asked at a tier +// may be of the tier: a 400 or 422, which is asked once more at the +// model's own size. +func tierRefused(d drawing, code int, err error) bool { + return d.Tier != "" && err != nil && (code == 400 || code == 422) +} + +// PixelsOf is an image's WIDTHxHEIGHT, read from its header; "" when it +// can't be read. +func PixelsOf(img []byte) string { + cfg, _, err := image.DecodeConfig(bytes.NewReader(img)) + if err != nil || cfg.Width <= 0 || cfg.Height <= 0 { + return "" + } + return fmt.Sprintf("%dx%d", cfg.Width, cfg.Height) +} + +// PixelsSaid is the line a tool result says the images' sizes in, so what +// came back can be checked against the resolution asked (tier): which +// sizes, and when one is well under the tier, that the model drew it at +// its own. "" for no sizes. +func PixelsSaid(sizes []string, tier string) string { + var known []string + small := false + for _, px := range sizes { + if px == "" { + continue + } + known = append(known, px) + w, h, _ := strings.Cut(px, "x") + x, _ := strconv.Atoi(w) + y, _ := strconv.Atoi(h) + if e := tierEdge(tier); e > 0 && max(x, y) < e*3/4 { + small = true + } + } + if len(known) == 0 { + return "" + } + what := "The image is" + if len(sizes) > 1 { + what = "The images are" + } + line := fmt.Sprintf("%s %s pixels", what, strings.Join(known, ", ")) + if small { + line += fmt.Sprintf(", under the %s asked: the model drew at the largest size it gives", tier) + } else if tier != "" { + line += fmt.Sprintf(" (%s asked)", tier) + } + return line + ".\n" +} + +// AskedTier is the tier an image MCP asks a drawing at, for PixelsSaid: +// the one sent as resolution, else one given as size ("4K"). +func AskedTier(tier, size string) string { + if tier != "" { + return tier + } + return tierOf(size) +} diff --git a/internal/gateway/draw_tier_test.go b/internal/gateway/draw_tier_test.go new file mode 100644 index 000000000..e0b39c5b5 --- /dev/null +++ b/internal/gateway/draw_tier_test.go @@ -0,0 +1,295 @@ +package gateway + +import ( + "bytes" + "encoding/base64" + "encoding/json" + "image" + "image/png" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/settings" +) + +// A resolution tier goes to each vendor in its own field (skingstyle48487 +// on X: a 4K asked through the image MCP came back at 2K). +func TestTierReachesEachProtocol(t *testing.T) { + t.Run("gemini", func(t *testing.T) { + c := imageConfigOf("gemini-3-pro-image-preview", "16:9", "4K") + if c["imageSize"] != "4K" || c["aspectRatio"] != "16:9" { + t.Fatalf("imageConfig %v", c) + } + // a model that draws at 1K alone is asked the ratio only + if c := imageConfigOf("gemini-2.5-flash-image", "16:9", "4K"); c["imageSize"] != "" { + t.Fatalf("2.x imageConfig %v", c) + } + }) + t.Run("chat", func(t *testing.T) { + c := chatImageConfig("google/gemini-3-pro-image-preview", drawing{Size: "16:9", Tier: "4K"}) + if c["image_size"] != "4K" || c["aspect_ratio"] != "16:9" { + t.Fatalf("image_config %v", c) + } + // a pixel size over 1K asked in chat is its tier, not dropped + if c := chatImageConfig("gemini-3-pro-image-preview", drawing{Size: "2048x2048"}); c["image_size"] != "2K" || c["aspect_ratio"] != "1:1" { + t.Fatalf("pixels' image_config %v", c) + } + if c := chatImageConfig("some-painter", drawing{Tier: "4K"}); c != nil { + t.Fatalf("a model not Gemini's is sent %v", c) + } + }) + t.Run("openrouter", func(t *testing.T) { + req := openRouterImagesReq("google/gemini-3-pro-image-preview", drawing{Prompt: "p", N: 1, Size: "16:9", Tier: "4K"}) + if req["resolution"] != "4K" || req["aspect_ratio"] != "16:9" || req["size"] != nil { + t.Fatalf("sent %v", req) + } + // a tier as size goes as resolution, not as size + d := drawing{Prompt: "p", N: 1, Size: "2k"} + d.settleTier("") + if req := openRouterImagesReq("google/gemini-3-pro-image-preview", d); req["resolution"] != "2K" || req["size"] != nil { + t.Fatalf("tier as size: sent %v", req) + } + }) + t.Run("grok", func(t *testing.T) { + if req := grokImagesReq("grok-imagine-image", drawing{Tier: "4K", Size: "16:9"}); req["resolution"] != "2k" || req["aspect_ratio"] != "16:9" { + t.Fatalf("4K: sent %v", req) + } + if req := grokImagesReq("grok-imagine-image", drawing{Tier: "1K"}); req["resolution"] != "1k" { + t.Fatalf("1K: sent %v", req) + } + }) + t.Run("ark", func(t *testing.T) { + for _, c := range []struct{ model, size, tier, want string }{ + {"doubao-seedream-4-5-251128", "", "4K", "4K"}, + {"doubao-seedream-4-5-251128", "16:9", "4K", "5504x3040"}, + {"doubao-seedream-4-5-251128", "", "1K", "2K"}, // 4.5 draws at 2K at the least + {"doubao-seedream-4-0-250828", "", "1K", "1K"}, + {"doubao-seedream-4-0-250828", "9:16", "1K", "720x1280"}, + {"doubao-seedream-5-0-pro-260628", "", "4K", "2K"}, // 5.0 pro's largest + {"doubao-seedream-5-0-pro-260628", "16:9", "1K", "1424x800"}, + {"doubao-seedream-5-0-lite-20260812", "", "4K", "4K"}, + {"doubao-seedream-4-5-251128", "1536x1024", "", "1536x1024"}, + } { + b, err := arkBody(c.model, drawing{Prompt: "p", N: 1, Size: c.size, Tier: c.tier}) + if err != nil { + t.Fatal(err) + } + var m map[string]any + json.Unmarshal(b, &m) + if m["size"] != c.want { + t.Errorf("%s %q at %s: size %v, want %s", c.model, c.size, c.tier, m["size"], c.want) + } + } + }) + t.Run("minimax", func(t *testing.T) { + b, _, err := minimaxH3Body("MiniMax-H3-Image", drawing{Prompt: "p", N: 1, Size: "16:9", Tier: "2K"}) + if err != nil { + t.Fatal(err) + } + var m map[string]any + json.Unmarshal(b, &m) + if m["area"] != "2K" || m["aspect_ratio"] != "16:9" || m["size"] != nil { + t.Fatalf("sent %v", m) + } + }) + t.Run("images API", func(t *testing.T) { + p := provider.Provider{ID: "relay", Chat: "http://relay.test/v1"} + for _, c := range []struct{ model, size, tier, want string }{ + {"gpt-image-2", "16:9", "4K", "3840x2160"}, + {"gpt-image-2", "", "4K", "2880x2880"}, // within 8,294,400 pixels + {"gpt-image-2.5", "9:16", "2K", "1152x2048"}, + {"gpt-image-2", "21:9", "1K", "1248x544"}, // at least 655,360 pixels + {"gpt-image-1", "16:9", "4K", "16:9"}, // its own sizes: the ratio as asked + {"gpt-image-1.5", "4K", "4K", ""}, + {"dall-e-3", "", "2K", ""}, + {"painter", "3:2", "2K", "2048x1360"}, + {"painter", "1024x1024", "", "1024x1024"}, + {"doubao-seedream-4-5-251128", "", "4K", "4K"}, + } { + if got := imagesAPISize(p, c.model, drawing{Size: c.size, Tier: c.tier}); got != c.want { + t.Errorf("%s %q at %s: size %q, want %q", c.model, c.size, c.tier, got, c.want) + } + } + }) +} + +// A tier is read from resolution, or from a tier given as size; a +// WIDTHxHEIGHT size is the size, and an unknown resolution is refused. +func TestSettleTier(t *testing.T) { + for _, c := range []struct{ size, resolution, want string }{ + {"", "4k", "4K"}, + {"16:9", "2K", "2K"}, + {"4K", "", "4K"}, + {"4K", "auto", ""}, + {"1024x1024", "4K", ""}, + {"", "", ""}, + } { + d := drawing{Size: c.size} + if err := d.settleTier(c.resolution); err != nil || d.Tier != c.want { + t.Errorf("size %q resolution %q: tier %q (%v), want %q", c.size, c.resolution, d.Tier, err, c.want) + } + } + d := drawing{} + if err := d.settleTier("8K"); err == nil { + t.Fatal("8K taken") + } +} + +// The image MCP asks the tier the agent names, else Settings' unless the +// agent gave a size of its own. +func TestImageTierPrecedence(t *testing.T) { + fresh(t) + st := settings.Load() + st.ImageResolution = "2K" + if err := settings.Save(st); err != nil { + t.Fatal(err) + } + for _, c := range []struct{ arg, size, want string }{ + {"", "", "2K"}, + {"", "16:9", "2K"}, + {"", "1024x1024", ""}, + {"", "4K", ""}, // the size's own tier, read by the gateway + {"4K", "", "4K"}, + {"auto", "", ""}, + } { + if got, err := ImageTier(c.arg, c.size); err != nil || got != c.want { + t.Errorf("resolution %q size %q: %q (%v), want %q", c.arg, c.size, got, err, c.want) + } + } + if _, err := ImageTier("8K", ""); err == nil { + t.Fatal("8K taken") + } + st.ImageResolution = "8K" + if err := settings.Save(st); err == nil { + t.Fatal("settings took 8K") + } +} + +// pngOf is a real PNG of w by h. +func pngOf(w, h int) []byte { + var b bytes.Buffer + png.Encode(&b, image.NewGray(image.Rect(0, 0, w, h))) + return b.Bytes() +} + +// tierEasel is a relay's images API that turns size away when refuse says +// so, and draws a picture of px pixels otherwise. +type tierEasel struct { + mu sync.Mutex + bodies []map[string]any + refuse func(map[string]any) bool + img []byte +} + +func (e *tierEasel) ServeHTTP(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + var m map[string]any + json.Unmarshal(b, &m) + e.mu.Lock() + e.bodies = append(e.bodies, m) + refuse := e.refuse != nil && e.refuse(m) + e.mu.Unlock() + w.Header().Set("Content-Type", "application/json") + if refuse { + w.WriteHeader(400) + io.WriteString(w, `{"error":{"message":"Invalid size"}}`) + return + } + io.WriteString(w, `{"created":1,"data":[{"b64_json":"`+base64.StdEncoding.EncodeToString(e.img)+`"}]}`) +} + +func (e *tierEasel) sent() []map[string]any { + e.mu.Lock() + defer e.mu.Unlock() + return append([]map[string]any(nil), e.bodies...) +} + +func tierEaseled(t *testing.T, img []byte) (*Server, *tierEasel) { + t.Helper() + fresh(t) + e := &tierEasel{img: img} + up := httptest.NewServer(e) + t.Cleanup(up.Close) + if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Chat: up.URL + "/v1", Key: "key", Models: []string{"gpt-image-2", "gpt-image-1"}}); err != nil { + t.Fatal(err) + } + return New(), e +} + +// The images API takes resolution: GPT Image 2 is asked the pixels the +// tier is at the ratio, GPT Image 1 its own size; a vendor that turns the +// tier away is asked once more without it; and an unknown tier is a 400. +func TestImagesAPIResolution(t *testing.T) { + s, e := tierEaseled(t, pngBytes) + if code, _, raw := postImages(t, s, "/v1/images/generations", "application/json", `{"model":"relay/gpt-image-2","prompt":"a magpie","size":"16:9","resolution":"4K"}`); code != 200 { + t.Fatalf("%d %s", code, raw) + } + if m := e.sent()[0]; m["size"] != "3840x2160" || m["resolution"] != nil { + t.Fatalf("gpt-image-2 was sent %v", m) + } + if code, _, raw := postImages(t, s, "/v1/images/generations", "application/json", `{"model":"relay/gpt-image-1","prompt":"a magpie","size":"4K"}`); code != 200 { + t.Fatalf("%d %s", code, raw) + } + if m := e.sent()[1]; m["size"] != nil { + t.Fatalf("gpt-image-1 was sent %v", m) + } + + e.refuse = func(m map[string]any) bool { return m["size"] != nil } + code, _, raw := postImages(t, s, "/v1/images/generations", "application/json", `{"model":"relay/gpt-image-2","prompt":"a magpie","resolution":"4K"}`) + if code != 200 { + t.Fatalf("refused tier: %d %s", code, raw) + } + if sent := e.sent(); len(sent) != 4 || sent[2]["size"] != "2880x2880" || sent[3]["size"] != nil { + t.Fatalf("sent %v", sent) + } + // a size the caller gave is not asked again without it + code, _, _ = postImages(t, s, "/v1/images/generations", "application/json", `{"model":"relay/gpt-image-2","prompt":"a magpie","size":"1536x1024"}`) + if code != 400 || len(e.sent()) != 5 { + t.Fatalf("%d, sent %d", code, len(e.sent())) + } + + if code, _, raw := postImages(t, s, "/v1/images/generations", "application/json", `{"model":"relay/gpt-image-2","prompt":"a magpie","resolution":"8K"}`); code != 400 || !strings.Contains(raw, "1K, 2K or 4K") { + t.Fatalf("8K: %d %s", code, raw) + } +} + +// generate_image asks Settings' resolution when the agent names no size, +// and says what size each image came back at, and when that is under the +// tier asked. +func TestImageMCPAsksTheSetResolution(t *testing.T) { + s, e := tierEaseled(t, pngOf(2048, 1152)) + t.Setenv("MAGPIE_PUBLIC_URL", "") + t.Cleanup(s.imageStore.running.Wait) + st := settings.Load() + st.ImageResolution = "4K" + if err := settings.Save(st); err != nil { + t.Fatal(err) + } + h := lanGuard(s.Handler()) + m := readImageReply(t, imagePost(h, "127.0.0.1:5000", imageToolCall(GenerateImageTool, map[string]any{"prompt": "a magpie", "model": "relay/gpt-image-2", "size": "16:9"}))) + if m.Result.IsError { + t.Fatalf("drawn: %+v", m) + } + if got := e.sent()[0]["size"]; got != "3840x2160" { + t.Fatalf("sent size %v", got) + } + if text := m.Result.Content[0].Text; !strings.Contains(text, "2048x1152 pixels, under the 4K asked") { + t.Fatalf("said %q", text) + } + + // a size of the agent's own is the size: no tier goes beside it + readImageReply(t, imagePost(h, "127.0.0.1:5000", imageToolCall(GenerateImageTool, map[string]any{"prompt": "a magpie", "model": "relay/gpt-image-2", "size": "1536x1024"}))) + if got := e.sent()[1]["size"]; got != "1536x1024" { + t.Fatalf("sent size %v", got) + } + // and so is one the agent names in resolution + readImageReply(t, imagePost(h, "127.0.0.1:5000", imageToolCall(GenerateImageTool, map[string]any{"prompt": "a magpie", "model": "relay/gpt-image-2", "resolution": "1K"}))) + if got := e.sent()[2]["size"]; got != "1024x1024" { + t.Fatalf("sent size %v", got) + } +} diff --git a/internal/gateway/draw_volcengine.go b/internal/gateway/draw_volcengine.go index ffbd8f5e3..a4037ed97 100644 --- a/internal/gateway/draw_volcengine.go +++ b/internal/gateway/draw_volcengine.go @@ -84,7 +84,10 @@ func arkBody(model string, d drawing) ([]byte, error) { if d.Markup != nil { return nil, errors.New("Volcengine's images API takes no markup layer: say in the prompt what to change") } - size, err := arkSize(d.Size) + size, err := seedreamSize(model, d.shape(), d.Tier) + if d.Tier == "" { + size, err = arkSize(d.Size) + } if err != nil { return nil, err } diff --git a/internal/gateway/image_mcp.go b/internal/gateway/image_mcp.go index d1fed1d32..85828aada 100644 --- a/internal/gateway/image_mcp.go +++ b/internal/gateway/image_mcp.go @@ -88,6 +88,7 @@ func ImageToolProps(images string) map[string]any { "quality": map[string]any{"type": "string", "description": "low, medium, high, xhigh, max or auto, for models that take it (xhigh and max: GPT Image 2.5 and later)."}, "complexity": map[string]any{"type": "string", "description": "low, medium or high: how much detail GPT Image 2.6 and later put in (default high)."}, "background": map[string]any{"type": "string", "description": "transparent, opaque or auto, for models that take it."}, + "resolution": map[string]any{"type": "string", "enum": []string{"1K", "2K", "4K", "auto"}, "description": "How large to draw: 1K, 2K or 4K on the long side, with size's aspect ratio, for models that take it; auto for the model's own. Default: the user's setting."}, } } @@ -297,6 +298,7 @@ func (s *Server) imageMCPDraw(r *http.Request, raw json.RawMessage) map[string]a Quality string `json:"quality"` Complexity string `json:"complexity"` Background string `json:"background"` + Resolution string `json:"resolution"` } if err := json.Unmarshal(raw, &a); err != nil { return toolResult("invalid arguments: "+err.Error(), true) @@ -304,6 +306,10 @@ func (s *Server) imageMCPDraw(r *http.Request, raw json.RawMessage) map[string]a if strings.TrimSpace(a.Prompt) == "" { return toolResult(GenerateImageTool+" needs a prompt", true) } + tier, err := ImageTier(a.Resolution, a.Size) + if err != nil { + return toolResult(err.Error(), true) + } req := map[string]any{"prompt": a.Prompt, "n": max(1, min(a.N, maxDrawings)), "response_format": "b64_json"} // a model named goes to the images API named, so a gateway key's // models hold it there (#882) @@ -314,7 +320,7 @@ func (s *Server) imageMCPDraw(r *http.Request, raw json.RawMessage) map[string]a } req["model"] = ref } - for k, v := range map[string]string{"size": a.Size, "quality": a.Quality, "complexity": a.Complexity, "background": a.Background} { + for k, v := range map[string]string{"size": a.Size, "quality": a.Quality, "complexity": a.Complexity, "background": a.Background, "resolution": tier} { if v != "" { req[k] = v } @@ -353,14 +359,14 @@ func (s *Server) imageMCPDraw(r *http.Request, raw json.RawMessage) map[string]a defer cancel() rec := &replyRecorder{header: http.Header{}} s.images(edit)(rec, in.WithContext(ctx)) - return s.imageMCPDrawn(rec, who.KeyID, base) + return s.imageMCPDrawn(rec, who.KeyID, base, AskedTier(tier, a.Size)) }) return s.imageMCPAwait(r, j) } // imageMCPDrawn is the tool result of the images API's answer: each image // in it and at its URL. -func (s *Server) imageMCPDrawn(rec *replyRecorder, key, base string) map[string]any { +func (s *Server) imageMCPDrawn(rec *replyRecorder, key, base, tier string) map[string]any { var out struct { Model string `json:"model"` Data []struct { @@ -382,7 +388,7 @@ func (s *Server) imageMCPDrawn(rec *replyRecorder, key, base string) map[string] return toolResult("no image came back", true) } var content []any - var urls, lost, revised []string + var urls, lost, revised, pixels []string var files []MadeFile for i, d := range out.Data { var img []byte @@ -413,6 +419,7 @@ func (s *Server) imageMCPDrawn(rec *replyRecorder, key, base string) map[string] if !strings.HasPrefix(mt, "image/") { mt = "image/png" } + pixels = append(pixels, PixelsOf(img)) urls = append(urls, base+ImageMCPFiles+s.imageMCPKeepFile(img, mt, key)) inline := len(img) <= imageMCPInline if inline { @@ -435,6 +442,7 @@ func (s *Server) imageMCPDrawn(rec *replyRecorder, key, base string) map[string] for _, u := range urls { fmt.Fprintf(&b, "- %s\n", u) } + b.WriteString(PixelsSaid(pixels, tier)) if len(content) < len(urls) { fmt.Fprintf(&b, "Images over %d MB are only at their URL.\n", imageMCPInline>>20) } diff --git a/internal/gateway/image_mcp_memory_test.go b/internal/gateway/image_mcp_memory_test.go index 457c773a6..802d077d4 100644 --- a/internal/gateway/image_mcp_memory_test.go +++ b/internal/gateway/image_mcp_memory_test.go @@ -40,7 +40,7 @@ func TestImageMCPKeepsDrawingsOffTheHeap(t *testing.T) { for range 3 { rec := &replyRecorder{header: http.Header{}} rec.body.Write(body) - res := s.imageMCPDrawn(rec, "", "http://127.0.0.1:3425") + res := s.imageMCPDrawn(rec, "", "http://127.0.0.1:3425", "") if res["isError"] == true { t.Fatalf("%v", res) } diff --git a/internal/gui/api_settings_test.go b/internal/gui/api_settings_test.go index 8c4d42213..7c2b592ae 100644 --- a/internal/gui/api_settings_test.go +++ b/internal/gui/api_settings_test.go @@ -231,6 +231,36 @@ func TestSettingsImageTimeout(t *testing.T) { } } +// The resolution an image is drawn at (skingstyle48487 on X) is set by +// the Settings page, "" for the model's own, kept by a save that doesn't +// send it (the page's other saves don't), and refused when not a tier. +func TestSettingsImageResolution(t *testing.T) { + h := t.TempDir() + t.Setenv("HOME", h) + t.Setenv("USERPROFILE", h) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config")) + handler := Handler(nil, nil) + for _, x := range []struct { + body string + code int + want string + }{ + {`{"theme":"dark","imageResolution":"4K"}`, http.StatusOK, "4K"}, + {`{"theme":"light"}`, http.StatusOK, "4K"}, + {`{"theme":"light","imageResolution":"8K"}`, http.StatusBadRequest, "4K"}, + {`{"theme":"light","imageResolution":""}`, http.StatusOK, ""}, + } { + rec := httptest.NewRecorder() + handler.ServeHTTP(rec, httptest.NewRequest("POST", "/api/settings", strings.NewReader(x.body))) + if rec.Code != x.code { + t.Fatalf("%s: %d %s", x.body, rec.Code, rec.Body) + } + if got := settings.Load().ImageResolution; got != x.want { + t.Fatalf("%s: imageResolution %q", x.body, got) + } + } +} + // How long a routing group's classifier is given (#2934) is set by the // Settings page, 0 for the default 8 seconds, kept by a save from a page // that doesn't send it, and refused past 60 with the saved value kept. diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 37e1e49ea..a63a5e6df 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -21770,7 +21770,8 @@ function renderImageGen(s, keep, box) { val.append(b); r.append(who, val); box.append(r); - // Video generation's row (#1399), drawn by videogen.js + // Video generation's row (#1399), drawn by videogen.js, and Image + // resolution's after it (skingstyle48487 on X) if (v !== "off") { const vr = el("div", "row pref"); box.append(vr); diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index cb6d0ad8b..66c5ad204 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -1350,6 +1350,8 @@ const I18N = { "{model}, picked here, no longer makes videos: its provider was removed or turned off, or the model isn't marked a video model any more. No other model makes videos. Pick another model here.": "这里选的 {model} 已不能生成视频:它的服务商被删除或关闭了,或者这个模型不再标记为视频模型。也没有其他能生成视频的模型。请在这里另选一个模型。", "Intent classifier timeout": "意图判断超时", "How long a routing group's classifier is given to say which intent a turn is. The turn waits for it before it goes anywhere, and past it goes on without its answer. A slow classifier may need longer": "路由组的意图判断模型判断这一轮属于哪种意图可用的时间。这一轮要等它判断完才会发出,超过则不等它的回答直接继续。较慢的判断模型可能需要更长时间", + "Image resolution": "生图分辨率", + "How large images are drawn when the agent names no size. A model that can't draw that large draws at its own": "智能体没指定尺寸时生成图片的大小。画不了这么大的模型按它自己的尺寸生成", "Image generation timeout": "生图超时", "How long a provider is given to draw an image and send it, before the request is given up. A slow image endpoint may need longer": "提供商生成并返回一张图可用的时间,超过即放弃这次请求。较慢的生图接口可能需要更长", "The model the Image generation MCP server below draws with, for the agents that add it; images come back in their answer": "下方生图 MCP 服务器所用的模型,供添加了它的智能体使用;图片随回答返回", @@ -6843,6 +6845,8 @@ const I18N = { "{model}, picked here, no longer makes videos: its provider was removed or turned off, or the model isn't marked a video model any more. No other model makes videos. Pick another model here.": "這裡選的 {model} 已無法生成影片:它的服務商被刪除或關閉了,或者這個模型不再標記為影片模型。也沒有其他能生成影片的模型。請在這裡另選一個模型。", "Intent classifier timeout": "意圖判斷逾時", "How long a routing group's classifier is given to say which intent a turn is. The turn waits for it before it goes anywhere, and past it goes on without its answer. A slow classifier may need longer": "路由組的意圖判斷模型判斷這一輪屬於哪種意圖可用的時間。這一輪要等它判斷完才會送出,超過則不等它的回答直接繼續。較慢的判斷模型可能需要更長時間", + "Image resolution": "生圖解析度", + "How large images are drawn when the agent names no size. A model that can't draw that large draws at its own": "代理沒指定尺寸時生成圖片的大小。畫不了這麼大的模型按它自己的尺寸生成", "Image generation timeout": "生圖逾時", "How long a provider is given to draw an image and send it, before the request is given up. A slow image endpoint may need longer": "提供者生成並傳回一張圖可用的時間,超過即放棄這次請求。較慢的生圖端點可能需要更長", "The model the Image generation MCP server below draws with, for the agents that add it; images come back in their answer": "下方生圖 MCP 伺服器所用的模型,供新增了它的智慧體使用;圖片隨回答傳回", @@ -12302,6 +12306,8 @@ const I18N = { "{model}, picked here, no longer makes videos: its provider was removed or turned off, or the model isn't marked a video model any more. No other model makes videos. Pick another model here.": "ここで選んだ {model} は動画を生成できなくなっています。プロバイダーが削除またはオフにされたか、このモデルが動画モデルとしてマークされなくなりました。動画を生成できるモデルが他にありません。ここで別のモデルを選んでください。", "Intent classifier timeout": "インテント判定のタイムアウト", "How long a routing group's classifier is given to say which intent a turn is. The turn waits for it before it goes anywhere, and past it goes on without its answer. A slow classifier may need longer": "ルーティンググループの分類モデルが、このターンがどのインテントかを答えるまで待つ時間。ターンは答えを待ってから送られ、過ぎると答えなしで進みます。遅い分類モデルではもっと長く必要なことがあります", + "Image resolution": "画像の解像度", + "How large images are drawn when the agent names no size. A model that can't draw that large draws at its own": "エージェントがサイズを指定しないときに生成する画像の大きさ。そこまで大きく描けないモデルは自身のサイズで描きます", "Image generation timeout": "画像生成のタイムアウト", "How long a provider is given to draw an image and send it, before the request is given up. A slow image endpoint may need longer": "プロバイダーが画像を生成して送るまで待つ時間。過ぎるとリクエストは打ち切られます。遅い画像エンドポイントにはより長い時間が必要なことがあります", "The model the Image generation MCP server below draws with, for the agents that add it; images come back in their answer": "下の画像生成 MCP サーバーが使うモデルです(追加したエージェント向け)。画像は回答で返されます", @@ -17778,6 +17784,8 @@ const I18N = { "{model}, picked here, no longer makes videos: its provider was removed or turned off, or the model isn't marked a video model any more. No other model makes videos. Pick another model here.": "{model}, hier gewählt, erzeugt keine Videos mehr: Sein Anbieter wurde entfernt oder ausgeschaltet, oder das Modell ist nicht mehr als Videomodell markiert. Kein anderes Modell erzeugt Videos. Wähle hier ein anderes Modell.", "Intent classifier timeout": "Zeitlimit für den Absicht-Klassifikator", "How long a routing group's classifier is given to say which intent a turn is. The turn waits for it before it goes anywhere, and past it goes on without its answer. A slow classifier may need longer": "Wie lange der Klassifikator einer Routing-Gruppe Zeit hat zu sagen, welche Absicht eine Runde hat. Die Runde wartet darauf, bevor sie irgendwohin geht, und danach geht sie ohne seine Antwort weiter. Ein langsamer Klassifikator braucht vielleicht länger", + "Image resolution": "Bildauflösung", + "How large images are drawn when the agent names no size. A model that can't draw that large draws at its own": "Wie groß Bilder erzeugt werden, wenn der Agent keine Größe nennt. Ein Modell, das nicht so groß zeichnen kann, zeichnet in seiner eigenen", "Image generation timeout": "Zeitlimit für Bilderzeugung", "How long a provider is given to draw an image and send it, before the request is given up. A slow image endpoint may need longer": "Wie lange ein Anbieter Zeit hat, ein Bild zu zeichnen und zu senden, bevor die Anfrage aufgegeben wird. Ein langsamer Bild-Endpunkt braucht unter Umständen länger", "The model the Image generation MCP server below draws with, for the agents that add it; images come back in their answer": "Das Modell, mit dem der MCP-Server der Bilderzeugung unten für die Agenten zeichnet, die ihn hinzufügen; Bilder kommen in ihrer Antwort zurück", diff --git a/internal/gui/assets/videogen.js b/internal/gui/assets/videogen.js index 49ec60b36..f5a194362 100644 --- a/internal/gui/assets/videogen.js +++ b/internal/gui/assets/videogen.js @@ -43,4 +43,28 @@ window.videoGenFill = function (r, s, keep) { const val = el("div", "val"); val.append(b); r.append(who, val); + r.after(imageResRow(s, keep)); }; + +// imageResRow draws Image resolution, put after Video generation's row: +// how large Magpie Image asks an image to be drawn when the agent names +// no size (skingstyle48487 on X), the model's own, 1K, 2K or 4K, which +// the gateway asks each vendor for in its own field +function imageResRow(s, keep) { + const r = el("div", "row pref"), tiers = [["", "Automatic"], ["1K", "1K"], ["2K", "2K"], ["4K", "4K"]], who = el("div", "who"), val = el("div", "val"), n = t("Image resolution"); + r.id = "imageResolutionRow"; + who.append(el("div", "name", n), el("div", "sub wraps", t("How large images are drawn when the agent names no size. A model that can't draw that large draws at its own"))); + const cur = tiers.find(([v]) => v === (s.imageResolution || "")) || tiers[0], b = el("button", "sess-pick image-resolution"); + b.type = "button"; + b.title = n; + menuOpener(b); + b.append(el("span", "", t(cur[1])), svg(CHEV, 11, 1.6)); + b.onclick = (e) => { + e.stopPropagation(); + if (b.classList.contains("open")) return closeProtoMenu(); + openProtoMenu(b, tiers.map(([v, name]) => ({ v, name, note: "", literalName: !!v })), cur[0], (v) => v !== cur[0] && savePrefs({ ...keep, imageResolution: v }), "Image resolution", "sess-menu", "right"); + }; + val.append(b); + r.append(who, val); + return r; +} diff --git a/internal/gui/tests/image-resolution.test.cjs b/internal/gui/tests/image-resolution.test.cjs new file mode 100644 index 000000000..63be76f2c --- /dev/null +++ b/internal/gui/tests/image-resolution.test.cjs @@ -0,0 +1,136 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// Settings › Models › Images (skingstyle48487 on X: a 4K image asked through +// the image MCP came back at 2K): Image resolution is Automatic at first, a +// menu of the app's own (no native select) of Automatic, 1K, 2K and 4K; +// 4K saves imageResolution "4K" with the rest of the settings kept, and +// Automatic saves "". It is gone with image generation off, and another +// row's save keeps it. In English, Chinese, Traditional Chinese, Japanese +// and German, 1100 and 420 wide. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); +const { reach, watchSettingsReads, settingsDrawn } = require("./reader.cjs"); + +const assets = path.resolve(__dirname, "../assets"); +const words = { + en: { name: "Image resolution", auto: "Automatic", sub: "when the agent names no size" }, + zh: { name: "生图分辨率", auto: "自动", sub: "智能体没指定尺寸时" }, + "zh-TW": { name: "生圖解析度", auto: "自動", sub: "代理沒指定尺寸時" }, + ja: { name: "画像の解像度", auto: "自動", sub: "サイズを指定しないとき" }, + de: { name: "Bildauflösung", auto: "Automatisch", sub: "keine Größe nennt" }, +}; + +function serve(lang, saved, own) { + const settings = { lang, theme: "light", redact: true, imageGen: "", imageGenAuto: "codex/gpt-image-2", + imageGenModels: [{ id: "codex/gpt-image-2", name: "GPT Image 2", provider: "codex", providerName: "Codex", icon: "openai" }], ...own }; + const state = { agents: [], profiles: [], settings }; + return async (r) => { + const url = new URL(r.request().url()); + const json = (data) => r.fulfill({ json: data }); + if (url.pathname === "/boot.js") return r.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return r.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json(state); + if (url.pathname === "/api/settings") { + if (r.request().method() === "POST") { + saved.push(JSON.parse(r.request().postData())); + Object.assign(settings, saved.at(-1)); + } + return json(settings); + } + if (url.pathname === "/api/groups") return json({ models: [], groups: [], pools: [] }); + if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true, url: "http://127.0.0.1:3999" } }); + if (url.pathname.startsWith("/api/")) return json({}); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + try { await r.fulfill({ body: await fs.readFile(file), contentType }); } catch { await r.fulfill({ status: 404, body: "" }); } + }; +} + +async function open(engine, lang, width, saved, own, t) { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await (await browser.newContext({ viewport: { width, height: 900 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang, saved, own)); + await watchSettingsReads(page); + await page.goto("http://magpie.test/?view=settings&tab=models"); + await settingsDrawn(page); // rows found are the ones that stay (#1659) + await page.locator("#imagesList #imageTimeoutRow").waitFor(); + return { page, errors }; +} + +const waitSaved = async (page, saved, n) => { + for (let i = 0; i < 200 && saved.length < n; i++) await page.waitForTimeout(50); +}; + +async function pick(page, name) { + const b = page.locator("#imageResolutionRow .sess-pick"); + await reach(page, b); + await b.click(); + const menu = page.locator(".proto-menu"); + await menu.waitFor(); + const item = menu.locator(".pm-item", { has: page.locator(".pm-name", { hasText: new RegExp(`^${name}$`) }) }); + await item.click(); +} + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of Object.keys(words)) for (const width of [1100, 420]) { + const w = words[lang]; + test(`${engine} ${lang} ${width}: how large an image is drawn`, async (t) => { + const saved = []; + const { page, errors } = await open(engine, lang, width, saved, {}, t); + const row = page.locator("#imagesList #imageResolutionRow"); + await row.waitFor(); + assert.equal(await row.locator(".name").textContent(), w.name); + assert((await row.locator(".sub").textContent()).includes(w.sub)); + assert.equal(await row.evaluate((r) => r.nextElementSibling?.id), "imageTimeoutRow", "above the timeout"); + assert.equal(await row.locator("select").count(), 0, "no native select"); + assert.equal((await row.locator(".sess-pick").textContent()).trim(), w.auto, "Automatic at first"); + const fit = await row.locator(".sess-pick").evaluate((e) => e.getBoundingClientRect().right <= innerWidth + 1); + assert(fit, `the picker fits at ${width}`); + + const b = row.locator(".sess-pick"); + await reach(page, b); + await b.click(); + const menu = page.locator(".proto-menu"); + await menu.waitFor(); + assert.deepEqual(await menu.locator(".pm-name").allTextContents(), [w.auto, "1K", "2K", "4K"]); + assert.deepEqual(await menu.locator(".pm-item .pm-note").allTextContents(), ["", "", "", ""], "no notes, the names say it"); + assert.equal(await menu.locator(".pm-item[aria-checked=true] .pm-name").textContent(), w.auto); + const inside = await menu.evaluate((m) => { const r = m.getBoundingClientRect(); return r.left >= -1 && r.right <= innerWidth + 1; }); + assert(inside, `the menu fits at ${width}`); + await menu.locator(".pm-item", { has: page.locator(".pm-name", { hasText: /^4K$/ }) }).click(); + await waitSaved(page, saved, 1); + assert.equal(saved.length, 1, "saved once"); + assert.equal(saved[0].imageResolution, "4K"); + assert.equal(saved[0].redact, true, "the rest kept"); + assert.equal(saved[0].lang, lang); + await page.waitForFunction(() => document.querySelector("#imageResolutionRow .sess-pick")?.textContent.trim() === "4K", null, { timeout: 10000 }); + + await pick(page, w.auto); + await waitSaved(page, saved, 2); + assert.equal(saved.length, 2, JSON.stringify(saved)); + assert.equal(saved[1].imageResolution, ""); + assert(await page.evaluate(() => document.scrollingElement.scrollWidth <= innerWidth + 1), `no sideways scroll at ${width}px`); + assert.deepEqual(errors, []); + }); + } + test(`${engine}: other saves leave the tier set alone, and the row goes with image generation off`, async (t) => { + const saved = []; + const { page, errors } = await open(engine, "en", 1100, saved, { imageResolution: "2K" }, t); + assert.equal((await page.locator("#imageResolutionRow .sess-pick").textContent()).trim(), "2K"); + await page.evaluate(() => savePrefs({ ...prefsKeep(prefs), redact: false })); + await waitSaved(page, saved, 1); + // the server keeps what a save doesn't send (TestSettingsImageResolution) + assert(!("imageResolution" in saved[0]), JSON.stringify(saved)); + const off = []; + const o = await open(engine, "en", 1100, off, { imageGen: "off" }, t); + assert.equal(await o.page.locator("#imageResolutionRow").count(), 0); + assert.deepEqual([...errors, ...o.errors], []); + }); +} diff --git a/internal/imagemcp/imagemcp.go b/internal/imagemcp/imagemcp.go index 2011ed0e0..ff29e9fd7 100644 --- a/internal/imagemcp/imagemcp.go +++ b/internal/imagemcp/imagemcp.go @@ -444,6 +444,7 @@ type args struct { Quality string `json:"quality"` Complexity string `json:"complexity"` Background string `json:"background"` + Resolution string `json:"resolution"` } // generate asks the gateway for the images and saves them; what it says is @@ -458,6 +459,12 @@ func (s *server) generate(raw json.RawMessage, used *string, c caller) (string, return "", errors.New("prompt is required") } a.N = max(1, min(a.N, 4)) + // the resolution the agent asks, else Settings › Images' unless the + // agent gave a size of its own + tier, err := gateway.ImageTier(a.Resolution, a.Size) + if err != nil { + return "", err + } project := s.project(c) // the images themselves, not URLs to fetch: the gateway fetches one a // vendor keeps through the vendor's own proxy, the way it just reached @@ -470,7 +477,7 @@ func (s *server) generate(raw json.RawMessage, used *string, c caller) (string, } req["model"] = m } - for k, v := range map[string]string{"size": a.Size, "quality": a.Quality, "complexity": a.Complexity, "background": a.Background} { + for k, v := range map[string]string{"size": a.Size, "quality": a.Quality, "complexity": a.Complexity, "background": a.Background, "resolution": tier} { if v != "" { req[k] = v } @@ -532,7 +539,7 @@ func (s *server) generate(raw json.RawMessage, used *string, c caller) (string, // an image that was drawn, and paid for, is never dropped unsaid: one // that can't be had is answered by where the vendor keeps it, beside // those saved (#1576) - var saved, revised, lost []string + var saved, revised, lost, pixels []string for i, d := range out.Data { img, mt := []byte(nil), d.Mime switch { @@ -566,6 +573,7 @@ func (s *server) generate(raw json.RawMessage, used *string, c caller) (string, return "", err } saved = append(saved, path) + pixels = append(pixels, gateway.PixelsOf(img)) if d.Revised != "" { revised = append(revised, d.Revised) } @@ -578,6 +586,7 @@ func (s *server) generate(raw json.RawMessage, used *string, c caller) (string, for _, p := range saved { fmt.Fprintf(&b, "- %s\n", shownPath(p)) } + b.WriteString(gateway.PixelsSaid(pixels, gateway.AskedTier(tier, a.Size))) for _, l := range lost { fmt.Fprintf(&b, "Not saved: %s\n", l) } diff --git a/internal/settings/settings.go b/internal/settings/settings.go index 6d440f03a..72a0d7a2b 100644 --- a/internal/settings/settings.go +++ b/internal/settings/settings.go @@ -637,6 +637,11 @@ type Settings struct { // than 5): from 1 to ImageTimeoutMost, 0 for ImageTimeoutDefault. // ImageWait reads it. ImageTimeout int `json:"imageTimeout,omitempty"` + // ImageResolution is the resolution the image MCP asks an image to be + // drawn at when the agent names no size of its own (skingstyle48487 on + // X): one of ImageResolutions, "" for the model's own. The gateway + // asks each vendor for it in its own field (gateway's draw_tier.go). + ImageResolution string `json:"imageResolution,omitempty"` // ClassifyTimeout is how long, in seconds, a routing group's classifier // is given to say which intent a turn is (#2934: a Kiro subscription's // haiku needed more than 8, the default then): from 1 to ClassifyTimeoutMost, 0 for @@ -1612,6 +1617,8 @@ var ( // UpdateChannels are UpdateChannel's values: every version, Daily, // Stable. UpdateChannels = []string{"", UpdateDaily, UpdateStable} + // ImageResolutions are ImageResolution's values; "" is the model's own + ImageResolutions = []string{"", "1K", "2K", "4K"} // UpdateEveries are UpdateEvery's values, in minutes. UpdateEveries = []int{30, 60, 360, 1440} // TextSizes are TextSize's values, in percent. None is under 100: the @@ -2671,6 +2678,9 @@ func saveOwn(s Settings, recording, reads bool) error { if s.ImageTimeout < 0 || s.ImageTimeout > ImageTimeoutMost { return fmt.Errorf("image generation is given from 1 to %d minutes, or 0 for %d, not %d", ImageTimeoutMost, ImageTimeoutDefault, s.ImageTimeout) } + if !slices.Contains(ImageResolutions, s.ImageResolution) { + return fmt.Errorf("an image is drawn at 1K, 2K, 4K or the model's own resolution (empty), not %q", s.ImageResolution) + } if s.ClassifyTimeout < 0 || s.ClassifyTimeout > ClassifyTimeoutMost { return fmt.Errorf("a routing group's classifier is given from 1 to %d seconds, or 0 for %d, not %d", ClassifyTimeoutMost, ClassifyTimeoutDefault, s.ClassifyTimeout) } diff --git a/internal/settingsapi/settingsapi.go b/internal/settingsapi/settingsapi.go index 039d81d0a..9bf15f7cf 100644 --- a/internal/settingsapi/settingsapi.go +++ b/internal/settingsapi/settingsapi.go @@ -46,7 +46,7 @@ var Keys = []string{ "workbuddyCheckin", "traeCheckin", "minimaxCheckin", "qoderCheckin", "checkinAt", // models: replies, vision, images, search "replyModel", "noLoopGuard", "claudeLeanPrompt", "claudeNoExtraUsage", "claudePrintMode", "refusalRetries", "retryAfterCap", - "vision", "visionEffort", "imageGen", "videoGen", "imageTimeout", "classifyTimeout", + "vision", "visionEffort", "imageGen", "videoGen", "imageTimeout", "imageResolution", "classifyTimeout", // what every routing group does that says nothing of its own "groupSink", "groupFirstToken", "groupPatience", "searcher", "searcherThen", "searcherEffort", "searchFirst", @@ -59,21 +59,22 @@ var Keys = []string{ // checks a saved value against (a value outside them is refused there, // from the window as from the CLI). A setting's "" is its default. var Choices = map[string][]string{ - "theme": settings.Themes, - "lang": settings.Langs, - "tray": settings.Trays, - "currency": settings.Currencies, - "totalCurrency": settings.TotalCurrencies, - "trayCurrency": settings.TotalCurrencies, - "codexWarmup": {"off", "week", "all"}, - "claudeWarmup": {"off", "week", "all"}, - "trayUsageEvery": ints(settings.TrayEvery), - "dayStart": {"0", "1", "2", "3", "4", "5", "6"}, - "updateChannel": {settings.UpdateStable, settings.UpdateDaily}, - "updateSource": {settings.UpdateSourceSite, settings.UpdateSourceGitHub}, - "updateEvery": ints(settings.UpdateEveries), - "searchFirst": {settings.SearchFirstModel, settings.SearchFirstAPI}, - "replyModel": settings.ReplyModels, + "theme": settings.Themes, + "lang": settings.Langs, + "tray": settings.Trays, + "currency": settings.Currencies, + "totalCurrency": settings.TotalCurrencies, + "trayCurrency": settings.TotalCurrencies, + "codexWarmup": {"off", "week", "all"}, + "claudeWarmup": {"off", "week", "all"}, + "trayUsageEvery": ints(settings.TrayEvery), + "dayStart": {"0", "1", "2", "3", "4", "5", "6"}, + "updateChannel": {settings.UpdateStable, settings.UpdateDaily}, + "updateSource": {settings.UpdateSourceSite, settings.UpdateSourceGitHub}, + "updateEvery": ints(settings.UpdateEveries), + "searchFirst": {settings.SearchFirstModel, settings.SearchFirstAPI}, + "replyModel": settings.ReplyModels, + "imageResolution": {"1K", "2K", "4K"}, } func ints(v []int) []string { @@ -217,6 +218,10 @@ func Merge(body []byte, cur settings.Settings, web bool) (settings.Settings, err if _, sent := fields["imageTimeout"]; !sent { in.ImageTimeout = cur.ImageTimeout } + // nor the resolution an image is drawn at + if _, sent := fields["imageResolution"]; !sent { + in.ImageResolution = cur.ImageResolution + } // nor how long a routing group's classifier is given (#2934) if _, sent := fields["classifyTimeout"]; !sent { in.ClassifyTimeout = cur.ClassifyTimeout