images: a resolution tier, 1K, 2K or 4K, in Settings and the image MCP (skingstyle48487 on X)

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.
This commit is contained in:
yetone
2026-11-19 00:27:58 +08:00
parent 88b65d7584
commit f6a538ece9
16 changed files with 1063 additions and 54 deletions
File diff suppressed because one or more lines are too long
+84 -28
View File
@@ -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
+3
View File
@@ -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
+421
View File
@@ -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)
}
+295
View File
@@ -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)
}
}
+4 -1
View File
@@ -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
}
+12 -4
View File
@@ -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)
}
+1 -1
View File
@@ -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)
}
+30
View File
@@ -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.
+2 -1
View File
@@ -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);
+8
View File
@@ -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",
+24
View File
@@ -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;
}
@@ -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], []);
});
}
+11 -2
View File
@@ -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)
}
+10
View File
@@ -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)
}
+21 -16
View File
@@ -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