Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

gateway: image generation's timeout is a setting, 1 to 60 minutes

yetone197849ad4d6c
diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md
index 187780162..292a113a4 100644
--- a/docs/subsystems/gateway-routing.md
+++ b/docs/subsystems/gateway-routing.md
@@ -34,7 +34,7 @@ backfilled; see [Gateway Session Aggregation](gateway-sessions.md).
| Order of keys and accounts | `Routing`: smart (""), `order`, `rotate`, `usage` (least used, with an `usageHalfLife` of 1h), `pace` or `weight`. `weighRouted` reads each candidate into a `routes.Seat` and asks the strategy serving its routing (`routes.Find`, the router strategy point of [the plugin runtime](plugin-runtime.md#gateway-extension-points-p3-router-strategy)) for the order: Smart is `routes.Smart`, the core's; the others are `routes.Builtin`, registered by the built-in plugin `rotation`. With it off a routing no strategy serves is tried in its listed order, and `routingOf` treats it as `order` wherever the core asks about a routing (a turn's mark, `goesRound`, `sinks`, a rotate group's sessions, a group's heads). Smart, `usage` and `pace` weigh a subscription by its allowance (`allowances`), and a key by its own usage windows when magpie reads them (`keyAllowance`: a sub2api key given a 5-hour, day or 7-day limit, or a key bought as a plan, such as Kimi Code's or a GLM Coding Plan's); any other key has none. A group routed `weight` (#1910) takes its members, not their keys, by smooth weighted round robin: `planLevel` makes each model member (its keys ordered by its own provider's routing) and each nested group one unit, and `weightedUnits` puts the round's pick (`routes.Round` over `group/<id>`, keyed by the member's spelling, `Group.Weights`, 1 if unset) first and the rest in member order for failover; a unit whose head rests leaves the round, and a kept conversation moves the round's charge to the member that kept it (`wrrSeat`, `routes.MoveRound`). A lone key or account is weighed against nobody, but what it has left is still read into the trace (`weighRouted`), so the Routing page shows it as it does for several (#1016); all but used up, it keeps its conversation rather than being said to move (`affine`). A failure rests a candidate (`failure`, `failureOf`). | [`routing.go`](../../internal/gateway/routing.go), [`weighted.go`](../../internal/gateway/weighted.go), [`internal/routes/`](../../internal/routes), [`internal/provider/routing.go`](../../internal/provider/routing.go) |
| Limits | Each key or account (a candidate's `who()`) has at most `MaxConcurrency` requests out at once (its own `AccountConcurrency` over it); one more waits in its lane's queue, bounded by `QueueLimit` and `QueueWait` and turned away with a 429 past either (`lanes.take`). `MaxRPM` (coeo91 on Discord: OpenRouter's free models take 20 a minute) bounds how many requests it sends the vendor in any rolling 60 seconds (`rpms`), counting each for a second more (`rpmSlack`), since the vendor counts a request when it arrives and the first on a new connection arrives later by its dial: one more waits for room in the minute, in the order they came, after it has its slot and right before it is sent. A wait that would be longer than 2 minutes (or the provider's `QueueWait`, when shorter: `rpmWait`) is turned away at once with a 429 whose `Retry-After` is when the minute has room; nothing rests for it. An agent gone while it waits gives its place back. Every request that reaches the vendor counts: each try of the candidate loop (a retry, the next key, a fallback) waits in `serve`, and the requests a try makes on the way and the gateway's own asks (count_tokens, System One's decisions, embeddings, drawing, Kimi's search) are counted by `rpmTransport` on `s.client` (`metered`, `paidFor`). count_tokens never waits: a candidate with no room is skipped, and the local estimate answers. A full lane or a minute with no room gives way to a ready key or account of the provider or the group (`laneMate`, `ready`); a fallback is never asked for want of either. A plugin's account sends through its own transport, so only its tries are counted, not a plugin's own extra requests. Set in the provider editor (Concurrency, Requests per minute, Queue size, Queue wait) or with `magpie provider account-concurrency`, `queue` and `rpm`; a subscription's are kept with its picks, and every account of it keeps them, those on beside the first as well (`withPicks`, called by `All` and `AlsoOn`; #1899: a second WorkBuddy AI account had none, and queued 62s with the wait set to 1s). | [`concurrency.go`](../../internal/gateway/concurrency.go), [`rpm.go`](../../internal/gateway/rpm.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. 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) |
-| 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`). A routing group named for a drawing or a video (`drawingGroup`: `group/<id>`, 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). Pause rules and a gateway key's group hold apply as for a chat. Nothing rests for a failed drawing. `TestImageGroupMovesOnToTheNextMember`, `TestVideoGroupMovesOnToTheNextMember`. 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`. | [`draw.go`](../../internal/gateway/draw.go), [`draw_volcengine.go`](../../internal/gateway/draw_volcengine.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`). A routing group named for a drawing or a video (`drawingGroup`: `group/<id>`, 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). Pause rules and a gateway key's group hold apply as for a chat. Nothing rests for a failed drawing. `TestImageGroupMovesOnToTheNextMember`, `TestVideoGroupMovesOnToTheNextMember`. 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 → 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), [`video.go`](../../internal/gateway/video.go), [`catalog.go`](../../internal/catalog/catalog.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`. | [`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)). Every request to one vendor's host shares one HTTP/2 connection (`upstreamTransport`); one with no frame for 20s is pinged, and dropped when no answer comes within 10s (`netproxy.HTTP2Health`, on `http.DefaultTransport` too), 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 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`) 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; 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. | [`gateway.go`](../../internal/gateway/gateway.go) |
| Trace | The Routing view's record of each decision, written where the decision is made: candidates, rests, which try answered. `Route.Folder` is the folder the agent says it works in (`workDir`), its last two levels only (`shortFolder`, e.g. `workspace/magpie`), never the full path; a request that says none (a title, a topic check) takes its session's as said last (`trace.sessionFolder`), one without a session id has none (#1068). It is kept in the routing history on disk for as long as the route is (`history.go`: 30 days, 200 MB). The GUI shows it in By session's headings, a request row's tooltip, the stage's agent working in more than one folder, and the tray panel's agent tooltip. | [`trace.go`](../../internal/gateway/trace.go) |
diff --git a/internal/gateway/draw.go b/internal/gateway/draw.go
index 8c3a505a1..59f928fb0 100644
--- a/internal/gateway/draw.go
+++ b/internal/gateway/draw.go
@@ -40,8 +40,43 @@ import (
const DrawAgent = "magpie-image/1"
// drawTimeout is how long a vendor is given to draw: to answer, and to send
-// all of its answer.
-var drawTimeout = 5 * time.Minute
+// all of its answer. It is Settings' Image generation timeout (neighbads on
+// X: a slow image endpoint needs more than the 5 minutes it was fixed at),
+// read as each request comes, in drawUnits.
+func drawTimeout() time.Duration {
+ return settings.Load().ImageWait() / time.Minute * drawUnit
+}
+
+// drawUnit is a minute of drawTimeout: a test makes it shorter, rather than
+// wait the minutes out.
+var drawUnit = time.Minute
+
+// drawWaitKey marks a request's context as a drawing's (or a video's),
+// given the time it holds: the vendor is waited on for that long, past the
+// 10 minutes upstreamTransport gives any other request to begin answering
+// (an images API answers only once it has drawn), and what ran out of time
+// says how long it was given.
+type drawWaitKey struct{}
+
+// drawWithin is ctx with d to draw in: its deadline, and the mark.
+func drawWithin(ctx context.Context, d time.Duration) (context.Context, context.CancelFunc) {
+ return context.WithTimeout(context.WithValue(ctx, drawWaitKey{}, d), d)
+}
+
+// drawWaitOf is the time ctx was given to draw in, if it was.
+func drawWaitOf(ctx context.Context) (time.Duration, bool) {
+ d, ok := ctx.Value(drawWaitKey{}).(time.Duration)
+ return d, ok
+}
+
+// givenTo says how long the drawing in ctx was given, or, for a request
+// that isn't one, how long it ran since start.
+func givenTo(ctx context.Context, start time.Time) time.Duration {
+ if d, ok := drawWaitOf(ctx); ok {
+ return d
+ }
+ return time.Since(start).Round(time.Second)
+}
// maxDrawings is how many images one request may ask for.
const maxDrawings = 4
@@ -440,7 +475,7 @@ func (s *Server) images(edit bool) http.HandlerFunc {
return
}
call.Provider, call.To = p.ID, provider.Chat
- ctx, cancel := context.WithTimeout(r.Context(), drawTimeout)
+ ctx, cancel := drawWithin(r.Context(), drawTimeout())
defer cancel()
// the account that drew, or refused last, is the one recorded
var (
@@ -991,7 +1026,7 @@ func (s *Server) sendWith(ctx context.Context, p provider.Provider, method, url,
res, err := p.Do(s.client, req) // a plugin's through the plugin
if err != nil {
if ctx.Err() != nil {
- return nil, 504, fmt.Errorf("%s didn't answer in %s", p.Name, drawTimeout)
+ return nil, 504, fmt.Errorf("%s didn't answer in %s", p.Name, givenTo(ctx, asked))
}
return nil, 502, err
}
@@ -1003,7 +1038,7 @@ func (s *Server) sendWith(ctx context.Context, p provider.Provider, method, url,
if ctx.Err() != nil {
// not a bare "context deadline exceeded" (#1576): the vendor
// began answering, and its answer is what ran out of time
- return nil, 504, fmt.Errorf("%s began answering after %s (%d %s) but hadn't sent all of its answer in %s: %s", p.Name, answered.Round(time.Second), res.StatusCode, http.StatusText(res.StatusCode), drawTimeout, stalledAt(b, time.Since(rb.last)))
+ return nil, 504, fmt.Errorf("%s began answering after %s (%d %s) but hadn't sent all of its answer in %s: %s", p.Name, answered.Round(time.Second), res.StatusCode, http.StatusText(res.StatusCode), givenTo(ctx, asked), stalledAt(b, time.Since(rb.last)))
}
return nil, 502, err
}
@@ -1312,15 +1347,21 @@ func (s *Server) fetchPicture(ctx context.Context, url string) ([]byte, string,
func inline(format string) bool { return strings.EqualFold(format, "b64_json") }
// ImageStall is how long an image being downloaded may send nothing before
-// the download is given up, and ImageLongest how long it may take in all.
-// A slow download goes on while it moves: a 4K PNG is 10 MB and more, and
-// a cap on the whole of it (generate_image's was 2 minutes) lost one that
-// was still coming (#1576).
+// the download is given up, and ImageLongest how long it may take in all
+// at the least: as long as drawTimeout where Settings gives drawing longer,
+// as a vendor slow to draw can be as slow to hand the image over. A slow
+// download goes on while it moves: a 4K PNG is 10 MB and more, and a cap
+// on the whole of it (generate_image's was 2 minutes) lost one that was
+// still coming (#1576).
var (
ImageStall = time.Minute
ImageLongest = 5 * time.Minute
)
+// imageLongest is how long a download may take in all: ImageLongest, or
+// drawTimeout where that is longer.
+func imageLongest() time.Duration { return max(ImageLongest, drawTimeout()) }
+
// maxImageBytes is the most of an image a download reads.
const maxImageBytes = 64 << 20
@@ -1328,13 +1369,14 @@ var errImageStalled = errors.New("the download stalled")
// FetchImage downloads the image at url with c: its bytes, and its type —
// what the bytes are, over what the server says. It gives up when nothing
-// comes for ImageStall or it has taken ImageLongest, and says which, and
+// comes for ImageStall or it has taken imageLongest, and says which, and
// how much had come.
func FetchImage(ctx context.Context, c *http.Client, url string) ([]byte, string, error) {
if !strings.HasPrefix(url, "http://") && !strings.HasPrefix(url, "https://") {
return nil, "", fmt.Errorf("%q isn't an http(s) URL", url)
}
- ctx, cancel := context.WithTimeout(ctx, ImageLongest)
+ longest := imageLongest()
+ ctx, cancel := context.WithTimeout(ctx, longest)
defer cancel()
ctx, stop := context.WithCancelCause(ctx)
defer stop(nil)
@@ -1349,7 +1391,7 @@ func FetchImage(ctx context.Context, c *http.Client, url string) ([]byte, string
case errImageStalled:
return fmt.Errorf("nothing came for %s, after %s", ImageStall, mb(got))
case context.DeadlineExceeded:
- return fmt.Errorf("only %s came in %s", mb(got), ImageLongest)
+ return fmt.Errorf("only %s came in %s", mb(got), longest)
}
return err
}
diff --git a/internal/gateway/draw_fetch_test.go b/internal/gateway/draw_fetch_test.go
index d71978a3b..5d300dfad 100644
--- a/internal/gateway/draw_fetch_test.go
+++ b/internal/gateway/draw_fetch_test.go
@@ -149,9 +149,9 @@ func TestImageByURLIsFetchedForB64Caller(t *testing.T) {
// #1576's 502s at 300 s said only "context deadline exceeded". A vendor
// that began answering but didn't finish in drawTimeout is said to have.
func TestVendorThatStopsMidAnswerIsSaid(t *testing.T) {
- was := drawTimeout
- drawTimeout = 300 * time.Millisecond
- t.Cleanup(func() { drawTimeout = was })
+ was := drawUnit
+ drawUnit = 60 * time.Millisecond // the 5 minutes, 300ms
+ t.Cleanup(func() { drawUnit = was })
s, _ := relayed(t, func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, `{"created":1,"data":[`)
w.(http.Flusher).Flush()
@@ -170,9 +170,9 @@ func TestVendorThatStopsMidAnswerIsSaid(t *testing.T) {
// b64_json body that took 380 s, and on another with a 416 B url. Which of
// the two stalled is said, with how much had come.
func TestStalledAnswerSaysUrlOrB64(t *testing.T) {
- was := drawTimeout
- drawTimeout = 500 * time.Millisecond
- t.Cleanup(func() { drawTimeout = was })
+ was := drawUnit
+ drawUnit = 100 * time.Millisecond // the 5 minutes, 500ms
+ t.Cleanup(func() { drawUnit = was })
for _, c := range []struct {
name, sent, want string
}{
diff --git a/internal/gateway/draw_modelscope.go b/internal/gateway/draw_modelscope.go
index 2fbf724cf..5c7287a71 100644
--- a/internal/gateway/draw_modelscope.go
+++ b/internal/gateway/draw_modelscope.go
@@ -82,7 +82,7 @@ func (s *Server) modelScopeTask(ctx context.Context, p provider.Provider, base s
}
select {
case <-ctx.Done():
- return nil, 504, fmt.Errorf("%s didn't answer in %s", p.Name, drawTimeout)
+ return nil, 504, fmt.Errorf("%s didn't answer in %s", p.Name, givenTo(ctx, time.Now()))
case <-time.After(modelScopeBusy[i]):
}
}
@@ -107,7 +107,7 @@ func (s *Server) modelScopeTask(ctx context.Context, p provider.Provider, base s
for {
select {
case <-ctx.Done():
- return nil, 504, fmt.Errorf("%s didn't finish drawing in %s", p.Name, drawTimeout)
+ return nil, 504, fmt.Errorf("%s didn't finish drawing in %s", p.Name, givenTo(ctx, time.Now()))
case <-time.After(modelScopePoll):
}
b, code, err := s.sendWith(ctx, p, http.MethodGet, base+"/tasks/"+started.TaskID, "", nil, true, task)
diff --git a/internal/gateway/draw_timeout_test.go b/internal/gateway/draw_timeout_test.go
new file mode 100644
index 000000000..a57aa5c59
--- /dev/null
+++ b/internal/gateway/draw_timeout_test.go
@@ -0,0 +1,160 @@
+package gateway
+
+import (
+ "encoding/base64"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/yetone/magpie/internal/catalog"
+ "github.com/yetone/magpie/internal/provider"
+ "github.com/yetone/magpie/internal/settings"
+)
+
+// slowDrawer is a vendor whose images API answers after wait, as one does
+// only once it has drawn, with Settings' Image generation timeout set to
+// minutes (0 for the default).
+func slowDrawer(t *testing.T, minutes int, wait time.Duration) *Server {
+ t.Helper()
+ fresh(t)
+ for _, k := range []string{"HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy", "ALL_PROXY", "all_proxy", "NO_PROXY", "no_proxy"} {
+ t.Setenv(k, "")
+ }
+ up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ select {
+ case <-r.Context().Done():
+ return
+ case <-time.After(wait):
+ }
+ w.Header().Set("Content-Type", "application/json")
+ w.Write([]byte(`{"created":1,"data":[{"b64_json":"` + base64.StdEncoding.EncodeToString(pngBytes) + `"}]}`))
+ }))
+ t.Cleanup(up.Close)
+ if err := provider.Save(provider.Provider{ID: "slow", Name: "Slow", Chat: up.URL + "/v1", Key: "key", Models: []string{"gpt-image-1"}}); err != nil {
+ t.Fatal(err)
+ }
+ if err := catalog.SaveLive("slow", up.URL+"/v1", []catalog.Model{{ID: "gpt-image-1"}}); err != nil {
+ t.Fatal(err)
+ }
+ if minutes > 0 {
+ s := settings.Load()
+ s.ImageTimeout = minutes
+ if err := settings.Save(s); err != nil {
+ t.Fatal(err)
+ }
+ }
+ return New()
+}
+
+// deadlines records the deadline each request to a vendor goes out with,
+// and whether it went as a drawing, on its way to the real transport.
+type deadlines struct {
+ next http.RoundTripper
+ mu sync.Mutex
+ got []time.Duration
+ draw []bool
+}
+
+func (d *deadlines) RoundTrip(r *http.Request) (*http.Response, error) {
+ dl, _ := r.Context().Deadline()
+ _, drawn := drawWaitOf(r.Context())
+ d.mu.Lock()
+ d.got, d.draw = append(d.got, time.Until(dl)), append(d.draw, drawn)
+ d.mu.Unlock()
+ return d.next.RoundTrip(r)
+}
+
+// neighbads on X: a slow image endpoint needed longer than the 5 minutes
+// drawing was given. Settings' Image generation timeout of 30 minutes
+// is what a drawing's request goes to the vendor with, through the
+// gateway's own transport; with none set it is 5 minutes, as before.
+func TestImageTimeoutSettingReachesTheVendor(t *testing.T) {
+ for _, c := range []struct {
+ minutes int
+ want time.Duration
+ }{{30, 30 * time.Minute}, {0, 5 * time.Minute}, {60, time.Hour}} {
+ s := slowDrawer(t, c.minutes, 0)
+ rec := &deadlines{next: s.client.Transport}
+ s.client = &http.Client{Transport: rec}
+ code, _, raw := postImages(t, s, "/v1/images/generations", "application/json", `{"model":"slow/gpt-image-1","prompt":"a magpie"}`)
+ if code != 200 {
+ t.Fatalf("%d minutes: %d %s", c.minutes, code, raw)
+ }
+ if len(rec.got) != 1 || !rec.draw[0] || rec.got[0] > c.want || rec.got[0] < c.want-time.Minute {
+ t.Fatalf("%d minutes: the vendor was asked with %v left (as a drawing: %v), want %v", c.minutes, rec.got, rec.draw, c.want)
+ }
+ }
+}
+
+// The same, with the minutes made short: a vendor that takes past the
+// default 5 to begin answering, and past the wait any other request is
+// given to begin (upstreamHeaderWait), draws when Settings gives it 30;
+// with the default it is said not to have answered in 5.
+func TestLongImageTimeoutLetsASlowVendorFinish(t *testing.T) {
+ wasUnit, wasHead := drawUnit, upstreamHeaderWait
+ drawUnit, upstreamHeaderWait = 20*time.Millisecond, 100*time.Millisecond // 5 minutes 100ms, 30 600ms, 10 minutes 100ms
+ t.Cleanup(func() { drawUnit, upstreamHeaderWait = wasUnit, wasHead })
+ const slow = 300 * time.Millisecond
+
+ s := slowDrawer(t, 30, slow)
+ code, a, raw := postImages(t, s, "/v1/images/generations", "application/json", `{"model":"slow/gpt-image-1","prompt":"a magpie"}`)
+ if code != 200 || len(a.Data) != 1 {
+ t.Fatalf("given 30: %d %s", code, raw)
+ }
+ if b, _ := base64.StdEncoding.DecodeString(a.Data[0].B64); string(b) != string(pngBytes) {
+ t.Fatalf("image %q", b)
+ }
+
+ s = slowDrawer(t, 0, slow)
+ code, _, raw = postImages(t, s, "/v1/images/generations", "application/json", `{"model":"slow/gpt-image-1","prompt":"a magpie"}`)
+ if code != 504 || !strings.Contains(raw, "Slow didn't answer in 100ms") {
+ t.Fatalf("given the default: %d %s", code, raw)
+ }
+}
+
+// An image a vendor answers with as a link is downloaded within the same
+// minutes: a long setting isn't cut by the 5-minute download cap.
+func TestImageDownloadGetsTheSetMinutes(t *testing.T) {
+ slowDrawer(t, 0, 0)
+ if got := imageLongest(); got != ImageLongest {
+ t.Fatalf("unset: %v", got)
+ }
+ slowDrawer(t, 45, 0)
+ if got := imageLongest(); got != 45*time.Minute {
+ t.Fatalf("given 45: %v", got)
+ }
+}
+
+// A request that isn't a drawing still has upstreamHeaderWait to begin
+// answering: only drawings wait longer.
+func TestOnlyDrawingsWaitPastTheHeaderWait(t *testing.T) {
+ was := upstreamHeaderWait
+ upstreamHeaderWait = 100 * time.Millisecond
+ t.Cleanup(func() { upstreamHeaderWait = was })
+ up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ select {
+ case <-r.Context().Done():
+ case <-time.After(400 * time.Millisecond):
+ }
+ }))
+ t.Cleanup(up.Close)
+ c := &http.Client{Transport: upstreamTransport()}
+ req, _ := http.NewRequest(http.MethodGet, up.URL, nil)
+ if res, err := c.Do(req); err == nil || !strings.Contains(err.Error(), "timeout awaiting response headers") {
+ if res != nil {
+ res.Body.Close()
+ }
+ t.Fatalf("a chat's request waited past the header wait: %v", err)
+ }
+ ctx, cancel := drawWithin(t.Context(), 5*time.Second)
+ defer cancel()
+ req, _ = http.NewRequestWithContext(ctx, http.MethodGet, up.URL, nil)
+ res, err := c.Do(req)
+ if err != nil {
+ t.Fatalf("a drawing's request was cut: %v", err)
+ }
+ res.Body.Close()
+}
diff --git a/internal/gateway/upstream_transport.go b/internal/gateway/upstream_transport.go
index d1cadd3db..8bacd8337 100644
--- a/internal/gateway/upstream_transport.go
+++ b/internal/gateway/upstream_transport.go
@@ -17,18 +17,45 @@ var upstreamTLS *tls.Config
// (#237), and the ChatGPT backend over HTTP/1.1 (netproxy.HTTP1). Every
// other vendor is spoken HTTP/2 to wherever it offers it. A request that
// finds its kept-alive connection dropped is sent again on a new one
-// (replayable).
+// (replayable). A vendor is given upstreamHeaderWait to begin answering,
+// but for a drawing, which an images API answers only once it has drawn:
+// it goes through a transport of its own that waits as long as Settings'
+// Image generation timeout gives it (drawWithin), up to 60 minutes.
func upstreamTransport() http.RoundTripper {
- return replayable{netproxy.Dispatch(&http.Transport{
+ return drawsApart{
+ any: replayable{netproxy.Dispatch(vendorTransport(upstreamHeaderWait))},
+ draws: replayable{netproxy.Dispatch(vendorTransport(0))},
+ }
+}
+
+// upstreamHeaderWait is how long a vendor is given to begin answering a
+// request that isn't a drawing.
+var upstreamHeaderWait = 10 * time.Minute
+
+// vendorTransport is a transport to the vendors that gives one wait to
+// begin answering, none for 0: the request's context then bounds it.
+func vendorTransport(wait time.Duration) *http.Transport {
+ return &http.Transport{
Proxy: netproxy.Func,
- ResponseHeaderTimeout: 10 * time.Minute,
+ ResponseHeaderTimeout: wait,
MaxIdleConnsPerHost: 8,
IdleConnTimeout: 90 * time.Second,
ForceAttemptHTTP2: true,
TLSClientConfig: upstreamTLS,
// a silent HTTP/2 connection is pinged and dropped (#2843)
HTTP2: netproxy.HTTP2Health(),
- })}
+ }
+}
+
+// drawsApart sends a drawing's request (drawWaitOf) through draws, every
+// other through any.
+type drawsApart struct{ any, draws http.RoundTripper }
+
+func (t drawsApart) RoundTrip(r *http.Request) (*http.Response, error) {
+ if _, ok := drawWaitOf(r.Context()); ok {
+ return t.draws.RoundTrip(r)
+ }
+ return t.any.RoundTrip(r)
}
// replayable lets Go's transport send a request again, at once and on a new
diff --git a/internal/gateway/video.go b/internal/gateway/video.go
index 7766b9969..d5ba3f332 100644
--- a/internal/gateway/video.go
+++ b/internal/gateway/video.go
@@ -58,6 +58,11 @@ var grokVideoAspects = []string{"1:1", "16:9", "9:16", "4:3", "3:4", "3:2", "2:3
// maxVideoBytes is the most of a video the gateway passes on.
const maxVideoBytes = 512 << 20
+// videoTimeout is how long a video's vendor is given to answer each of its
+// calls: to take the video on, say how it goes, and send it. A video is
+// made between them, so Settings' Image generation timeout isn't it.
+const videoTimeout = 5 * time.Minute
+
// Videomakers are the models a provider can make videos with: a Grok
// subscription's, another magpie's, a preset plan's models when magpie
// implements that vendor's video API, and those a provider's own model list
@@ -743,7 +748,7 @@ func (s *Server) videosCreate(w http.ResponseWriter, r *http.Request) {
w, done = restoring(w)
defer done()
}
- ctx, cancel := context.WithTimeout(r.Context(), drawTimeout)
+ ctx, cancel := drawWithin(r.Context(), videoTimeout)
defer cancel()
var (
v videoStart
@@ -957,7 +962,7 @@ func (s *Server) videosGet(w http.ResponseWriter, r *http.Request) {
writeError(w, provider.Chat, 403, held)
return
}
- ctx, cancel := context.WithTimeout(r.Context(), drawTimeout)
+ ctx, cancel := drawWithin(r.Context(), videoTimeout)
defer cancel()
if filmsOpenAI(p) {
obj, model, code, err := s.openAIVideo(ctx, p, vendorID, id)
@@ -1001,7 +1006,7 @@ func (s *Server) videosContent(w http.ResponseWriter, r *http.Request) {
writeError(w, provider.Chat, 403, held)
return
}
- ctx, cancel := context.WithTimeout(r.Context(), drawTimeout)
+ ctx, cancel := drawWithin(r.Context(), videoTimeout)
defer cancel()
if filmsOpenAI(p) {
if _, models := keyHolds(r); models {
diff --git a/internal/gui/api.go b/internal/gui/api.go
index 2f6194904..802bf4e71 100644
--- a/internal/gui/api.go
+++ b/internal/gui/api.go
@@ -1171,6 +1171,10 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
if _, sent := fields["noAutoDownload"]; !sent {
in.NoAutoDownload = cur.NoAutoDownload
}
+ // nor how long an image is given to be drawn
+ if _, sent := fields["imageTimeout"]; !sent {
+ in.ImageTimeout = cur.ImageTimeout
+ }
in.AgentOrder, in.AgentsHidden, in.AgentsShown = cur.AgentOrder, cur.AgentsHidden, cur.AgentsShown
in.Window, in.WindowMaximised = cur.Window, cur.WindowMaximised // the window's own, as it was last resized
// and what other pages keep here: which models an agent is shown, and
diff --git a/internal/gui/api_settings_test.go b/internal/gui/api_settings_test.go
index 1883c72a7..e7dfd1351 100644
--- a/internal/gui/api_settings_test.go
+++ b/internal/gui/api_settings_test.go
@@ -201,6 +201,36 @@ func TestSettingsRefusalRetries(t *testing.T) {
}
}
+// How long an image is given to be drawn (neighbads on X) is set by the
+// Settings page, 0 for the default 5 minutes, kept by a save from a page
+// that doesn't send it, and refused past 60 with the saved value kept.
+func TestSettingsImageTimeout(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 int
+ }{
+ {`{"theme":"dark","imageTimeout":30}`, http.StatusOK, 30},
+ {`{"theme":"light"}`, http.StatusOK, 30},
+ {`{"theme":"light","imageTimeout":61}`, http.StatusBadRequest, 30},
+ {`{"theme":"light","imageTimeout":0}`, http.StatusOK, 0},
+ } {
+ 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().ImageTimeout; got != x.want {
+ t.Fatalf("%s: imageTimeout %d", x.body, got)
+ }
+ }
+}
+
func TestSettingsColorblindMode(t *testing.T) {
h := t.TempDir()
t.Setenv("HOME", h)
diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js
index 2f21b3e0f..a79ef1d4c 100644
--- a/internal/gui/assets/app.js
+++ b/internal/gui/assets/app.js
@@ -20799,6 +20799,20 @@ function renderImageGen(s, keep, box) {
val.append(b);
r.append(who, val);
box.append(r);
+ // how long a vendor is given to draw an image and send it: 5 minutes
+ // unless set, as a slow image endpoint needs more (neighbads on X)
+ const w = el("div", "row pref");
+ w.id = "imageTimeoutRow";
+ const wwho = el("div", "who");
+ wwho.append(el("div", "name", t("Image generation timeout")),
+ el("div", "sub wraps", t("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")));
+ const mins = [5, 10, 15, 30, 60].map((n) => [String(n), t("{n} min", { n })]);
+ const m = String(s.imageTimeout > 0 ? s.imageTimeout : 5);
+ if (!mins.some(([id]) => id === m)) mins.push([m, t("{n} min", { n: m })]); // set by hand in settings.json
+ const wval = el("div", "val");
+ wval.append(segs(mins, m, (v) => savePrefs({ ...keep, imageTimeout: Number(v) })));
+ w.append(wwho, wval);
+ box.append(w);
}
// mcpAddress: where one of the gateway's own MCP servers is, at path. A
@@ -22181,7 +22195,7 @@ function prefsKeep(s) {
codexWarmAts: warmTimes(s.codexWarmAts, s.codexWarmAt), claudeWarmAts: warmTimes(s.claudeWarmAts, s.claudeWarmAt), workbuddyCheckin: !!s.workbuddyCheckin, traeCheckin: !!s.traeCheckin, minimaxCheckin: !!s.minimaxCheckin, qoderCheckin: !!s.qoderCheckin, noStats: !!s.noStats, noUsageStats: !!s.noUsageStats,
memberModel: !!s.memberModel, noLoopGuard: !!s.noLoopGuard, claudeLeanPrompt: !!s.claudeLeanPrompt, refusalRetries: s.refusalRetries ?? null,
noUpdatePill: !!s.noUpdatePill, noAutoUpdate: !!s.noAutoUpdate, updateEvery: s.updateEvery || 360, autoRestart: !!s.autoRestart, noAutoDownload: !!s.noAutoDownload,
- trayUsage: s.trayUsage || "", trayUsageEvery: s.trayUsageEvery || 3, trayNoLogos: !!s.trayNoLogos, trayNoBird: !!s.trayNoBird, trayPace: !!s.trayPace, trayNoCost: !!s.trayNoCost, vision: s.vision || "", visionEffort: s.visionEffort || "", searcherEffort: s.searcherEffort || "", imageGen: s.imageGen || "", searcher: s.searcher || "", searchFirst: s.searchFirst || "", currency: s.currency || "usd",
+ trayUsage: s.trayUsage || "", trayUsageEvery: s.trayUsageEvery || 3, trayNoLogos: !!s.trayNoLogos, trayNoBird: !!s.trayNoBird, trayPace: !!s.trayPace, trayNoCost: !!s.trayNoCost, vision: s.vision || "", visionEffort: s.visionEffort || "", searcherEffort: s.searcherEffort || "", imageGen: s.imageGen || "", imageTimeout: s.imageTimeout || 0, searcher: s.searcher || "", searchFirst: s.searchFirst || "", currency: s.currency || "usd",
chineseUnits: !!s.chineseUnits, usageAlert: s.usageAlert || 0, balanceAlert: s.balanceAlert || 0, resetReminder: s.resetReminder || 0,
turnDoneAlert: s.turnDoneAlert || 0 };
}
diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js
index 697981669..307be3923 100644
--- a/internal/gui/assets/i18n.js
+++ b/internal/gui/assets/i18n.js
@@ -894,6 +894,8 @@ const I18N = {
"{model}, picked here, isn't set up any more: its provider was removed or turned off, or no longer has it. No other model draws, so a request that names no model is turned away. Pick another model here.": "这里选的 {model} 已不可用:它的服务商被删除或关闭了,或者不再提供这个模型。也没有其他能生图的模型,所以没指定模型的请求会被拒绝。请在这里另选一个模型。",
"images turned away": "带图的请求被拒绝",
"Image generation": "生图模型",
+ "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 Magpie Image draws with, for the agents given the Magpie Image tool; images are saved in their project": "Magpie Image 生图所用的模型,供添加了 Magpie Image 工具的 Agent 使用;图片保存在其项目目录",
"The model Magpie Image draws with. Agents get the Magpie Image tool from the Library, which is turned off in Plugins › Built-in; images are saved in their project": "Magpie Image 生图所用的模型。Agent 要从资源库添加 Magpie Image 工具,而资源库在「插件 › 内置」中已关闭;图片保存在其项目目录",
"The model Magpie Image draws with. Agents get the Magpie Image tool from the Library; images are saved in their project": "Magpie Image 生图所用的模型。Agent 要从资源库添加 Magpie Image 工具才能生图;图片保存在其项目目录",
@@ -4621,6 +4623,8 @@ const I18N = {
"{model}, picked here, isn't set up any more: its provider was removed or turned off, or no longer has it. No other model draws, so a request that names no model is turned away. Pick another model here.": "這裡選的 {model} 已無法使用:它的服務商被刪除或關閉了,或者不再提供這個模型。也沒有其他能生圖的模型,所以沒指定模型的請求會被拒絕。請在這裡另選一個模型。",
"images turned away": "帶圖的請求被拒絕",
"Image generation": "生圖模型",
+ "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 Magpie Image draws with, for the agents given the Magpie Image tool; images are saved in their project": "Magpie Image 生圖所用的模型,供新增了 Magpie Image 工具的 Agent 使用;圖片儲存在其專案目錄",
"The model Magpie Image draws with. Agents get the Magpie Image tool from the Library, which is turned off in Plugins › Built-in; images are saved in their project": "Magpie Image 生圖所用的模型。Agent 要從資源庫新增 Magpie Image 工具,而資源庫在「外掛 › 內建」中已關閉;圖片儲存在其專案目錄",
"The model Magpie Image draws with. Agents get the Magpie Image tool from the Library; images are saved in their project": "Magpie Image 生圖所用的模型。Agent 要從資源庫新增 Magpie Image 工具才能生圖;圖片儲存在其專案目錄",
@@ -8320,6 +8324,8 @@ const I18N = {
"{model}, picked here, isn't set up any more: its provider was removed or turned off, or no longer has it. No other model draws, so a request that names no model is turned away. Pick another model here.": "ここで選んだ {model} は使えなくなっています。プロバイダーが削除またはオフにされたか、このモデルがなくなりました。画像を生成できるモデルが他にないため、モデルを指定しないリクエストは拒否されます。ここで別のモデルを選んでください。",
"images turned away": "画像付きリクエストは拒否",
"Image generation": "画像生成",
+ "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 Magpie Image draws with, for the agents given the Magpie Image tool; images are saved in their project": "Magpie Image ツールを付与したエージェントが画像生成に使うモデルです。画像はそのプロジェクトに保存されます",
"The model Magpie Image draws with. Agents get the Magpie Image tool from the Library, which is turned off in Plugins › Built-in; images are saved in their project": "Magpie Image が画像生成に使うモデルです。エージェントにはライブラリから Magpie Image ツールを付与しますが、ライブラリは「プラグイン › 内蔵」でオフになっています。画像はそのプロジェクトに保存されます",
"The model Magpie Image draws with. Agents get the Magpie Image tool from the Library; images are saved in their project": "Magpie Image が画像生成に使うモデルです。エージェントにはライブラリから Magpie Image ツールを付与します。画像はそのプロジェクトに保存されます",
@@ -12033,6 +12039,8 @@ const I18N = {
"{model}, picked here, isn't set up any more: its provider was removed or turned off, or no longer has it. No other model draws, so a request that names no model is turned away. Pick another model here.": "{model}, hier gewählt, ist nicht mehr eingerichtet: Sein Anbieter wurde entfernt oder ausgeschaltet, oder er hat das Modell nicht mehr. Kein anderes Modell erzeugt Bilder, daher wird eine Anfrage ohne Modell abgewiesen. Wähle hier ein anderes Modell.",
"images turned away": "Bilder werden abgelehnt",
"Image generation": "Bilderzeugung",
+ "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 Magpie Image draws with, for the agents given the Magpie Image tool; images are saved in their project": "Das Modell, mit dem Magpie Image für Agenten mit dem Magpie-Image-Tool zeichnet; Bilder werden in ihrem Projekt gespeichert",
"The model Magpie Image draws with. Agents get the Magpie Image tool from the Library, which is turned off in Plugins › Built-in; images are saved in their project": "Das Modell, mit dem Magpie Image zeichnet. Agenten bekommen das Magpie-Image-Tool aus der Bibliothek, die unter Erweiterungen › Eingebaut ausgeschaltet ist; Bilder werden in ihrem Projekt gespeichert",
"The model Magpie Image draws with. Agents get the Magpie Image tool from the Library; images are saved in their project": "Das Modell, mit dem Magpie Image zeichnet. Agenten bekommen das Magpie-Image-Tool aus der Bibliothek; Bilder werden in ihrem Projekt gespeichert",
diff --git a/internal/gui/tests/disabled-models.test.cjs b/internal/gui/tests/disabled-models.test.cjs
index 794fa3b47..4d2c6af97 100644
--- a/internal/gui/tests/disabled-models.test.cjs
+++ b/internal/gui/tests/disabled-models.test.cjs
@@ -11,7 +11,7 @@ const fs = require("node:fs/promises");
const path = require("node:path");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
-const { watchSettingsReads, settingsDrawn } = require("./reader.cjs");
+const { watchSettingsReads, settingsDrawn, reach } = require("./reader.cjs");
const assets = path.resolve(__dirname, "../assets");
const words = {
@@ -112,13 +112,10 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
// Enable takes one off, the rest kept
const en = fable.locator("button", { hasText: w.enable });
// wheeled down to it as a reader does: the row *opus* adds, under
- // Replies' rows, puts it past the window's foot at 420 in German
- for (let i = 0; i < 20; i++) {
- const box = await en.boundingBox();
- if (box && box.y >= 0 && box.y + box.height <= 900) break;
- await page.mouse.wheel(0, 120);
- await page.waitForTimeout(50);
- }
+ // Replies' rows, puts it past the window's foot at 420 in German, and
+ // under it at 1100 in Chinese with Image generation timeout drawn
+ // above: reach wheels until nothing is over it
+ await reach(page, en);
const eb = await en.boundingBox();
const at = await page.evaluate(() => [scrollX, scrollY, document.scrollingElement.scrollTop]);
await page.mouse.click(eb.x + eb.width / 2, eb.y + eb.height / 2);
diff --git a/internal/gui/tests/image-timeout-setting.test.cjs b/internal/gui/tests/image-timeout-setting.test.cjs
new file mode 100644
index 000000000..a88617a92
--- /dev/null
+++ b/internal/gui/tests/image-timeout-setting.test.cjs
@@ -0,0 +1,142 @@
+// Run with Node's test runner and Playwright on the module path; see README.md.
+// Settings › Models › Images (neighbads on X: a slow image endpoint needs
+// longer than the 5 minutes drawing was given): Image generation timeout
+// is 5 min at first, 30 min saves imageTimeout 30 with the rest of the
+// settings kept and the page not moved by the click, and 5 min saves 5. A
+// value set by hand in settings.json shows as its own choice, pressed. 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 generation timeout", head: "Images", min: (n) => `${n} min`, sub: "A slow image endpoint may need longer" },
+ zh: { name: "生图超时", head: "图像", min: (n) => `${n} 分钟`, sub: "较慢的生图接口可能需要更长" },
+ "zh-TW": { name: "生圖逾時", head: "影像", min: (n) => `${n} 分鐘`, sub: "較慢的生圖端點可能需要更長" },
+ ja: { name: "画像生成のタイムアウト", head: "画像", min: (n) => `${n} 分`, sub: "遅い画像エンドポイント" },
+ de: { name: "Zeitlimit für Bilderzeugung", head: "Bilder", min: (n) => `${n} min`, sub: "langsamer Bild-Endpunkt" },
+};
+
+function serve(lang, saved, own) {
+ const settings = { lang, theme: "light", redact: true, imageGen: "off", ...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)];
+ await r.fulfill({ body: await fs.readFile(file), contentType });
+ };
+}
+
+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 } })).newPage();
+ page.setDefaultTimeout(5000);
+ 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)
+ const row = page.locator("#imagesList #imageTimeoutRow");
+ await row.waitFor();
+ return { page, row, errors };
+}
+
+for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
+ for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) for (const width of [1100, 420]) {
+ const w = words[lang];
+ test(`${engine} ${lang} ${width}: how long an image is given to be drawn`, async (t) => {
+ const saved = [];
+ const { page, row, errors } = await open(engine, lang, width, saved, {}, t);
+ // scrolled to as a reader does, with the wheel
+ await page.mouse.move(width / 2, 450);
+ for (let i = 0; i < 40; i++) {
+ const box = await row.boundingBox();
+ if (box && box.y >= 0 && box.y + box.height <= 900) break;
+ await page.mouse.wheel(0, 120);
+ await page.waitForTimeout(50);
+ }
+ assert.equal(await row.locator(".name").textContent(), w.name);
+ assert((await row.locator(".sub").textContent()).includes(w.sub));
+ for (const part of [".name", ".sub", ".segs"]) {
+ const fit = await row.locator(part).first().evaluate((e) => {
+ const r = e.getBoundingClientRect();
+ return e.scrollWidth <= e.clientWidth + 1 && r.width > 0 && r.right <= innerWidth + 1;
+ });
+ assert(fit, `${part} fits at ${width}`);
+ }
+ assert.equal(await page.locator("#imagesList").evaluate((l) => l.previousElementSibling.textContent.trim()), w.head);
+ assert.deepEqual(await row.locator(".segs button").allTextContents(), [5, 10, 15, 30, 60].map(w.min));
+ assert.equal(await row.locator(".segs button[aria-pressed=true]").textContent(), w.min(5), "5 min at first");
+
+ const at = () => page.evaluate(() => [scrollX, scrollY, document.querySelector("#imageTimeoutRow").closest(".view").scrollTop]);
+ const moved = [];
+ const click = async (name) => {
+ const button = row.locator(".segs button", { hasText: new RegExp(`^${name}$`) });
+ await reach(page, button);
+ let before = await at();
+ for (let i = 0; i < 40; i++) {
+ await page.waitForTimeout(100);
+ const now = await at();
+ if (JSON.stringify(now) === JSON.stringify(before)) break;
+ before = now;
+ }
+ const b = await button.boundingBox();
+ await page.mouse.click(b.x + b.width / 2, b.y + b.height / 2);
+ await page.waitForTimeout(100);
+ const after = await at();
+ if (JSON.stringify(after) !== JSON.stringify(before)) moved.push(`${name}: ${before} → ${after}`);
+ };
+ await row.evaluate((e) => { e.dataset.before = "1"; });
+ await click(w.min(30));
+ for (let i = 0; i < 200 && !saved.length; i++) await page.waitForTimeout(50);
+ assert.equal(saved.length, 1, "saved once");
+ assert.equal(saved[0].imageTimeout, 30);
+ assert.equal(saved[0].imageGen, "off", "the row above it kept");
+ assert.equal(saved[0].redact, true, "the rest kept");
+ assert.equal(saved[0].lang, lang);
+ await page.waitForFunction((m) => {
+ const r = document.querySelector("#imageTimeoutRow");
+ return r && !r.dataset.before && r.querySelector(".segs button[aria-pressed=true]")?.textContent === m;
+ }, w.min(30), { timeout: 10000 });
+ await click(w.min(5));
+ for (let i = 0; i < 200 && saved.length < 2; i++) await page.waitForTimeout(50);
+ assert.equal(saved.length, 2, `saved again: ${JSON.stringify(saved)}`);
+ assert.equal(saved[1].imageTimeout, 5);
+ assert.deepEqual(moved, [], "the click moved nothing");
+ assert.deepEqual(errors, []);
+ });
+ }
+ test(`${engine}: minutes set by hand show as their own choice, and are sent on with other saves`, async (t) => {
+ const saved = [];
+ const { page, row, errors } = await open(engine, "en", 1100, saved, { imageTimeout: 45 }, t);
+ assert.deepEqual(await row.locator(".segs button").allTextContents(), ["5 min", "10 min", "15 min", "30 min", "60 min", "45 min"]);
+ assert.equal(await row.locator(".segs button[aria-pressed=true]").textContent(), "45 min");
+ // another row's save keeps the minutes
+ await page.evaluate(() => savePrefs({ ...prefsKeep(prefs), redact: false }));
+ for (let i = 0; i < 200 && !saved.length; i++) await page.waitForTimeout(50);
+ assert.equal(saved[0].imageTimeout, 45, JSON.stringify(saved));
+ assert.deepEqual(errors, []);
+ });
+}
diff --git a/internal/gui/tests/refusal-retries-setting.test.cjs b/internal/gui/tests/refusal-retries-setting.test.cjs
index a4e6864b5..83537076f 100644
--- a/internal/gui/tests/refusal-retries-setting.test.cjs
+++ b/internal/gui/tests/refusal-retries-setting.test.cjs
@@ -96,14 +96,25 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
// nothing (reproduced with six runs at once)
const click = async (name) => {
const button = row.locator(".segs button", { hasText: name });
- await reach(page, button);
- // the wheel come to rest: WebKit's went on after reach had the row
- let before = await at();
- for (let i = 0; i < 40; i++) {
- await page.waitForTimeout(100);
- const now = await at();
- if (JSON.stringify(now) === JSON.stringify(before)) break;
- before = now;
+ // the wheel come to rest: WebKit's went on after reach had the row,
+ // and at 420 carried All under the window's foot once Image
+ // generation timeout was drawn above, so it is reached again until
+ // it is still clear when the wheel has stopped
+ let before;
+ for (let tries = 0; tries < 5; tries++) {
+ await reach(page, button);
+ before = await at();
+ for (let i = 0; i < 40; i++) {
+ await page.waitForTimeout(100);
+ const now = await at();
+ if (JSON.stringify(now) === JSON.stringify(before)) break;
+ before = now;
+ }
+ const clear = await button.evaluate((e) => {
+ const b = e.getBoundingClientRect(), hit = document.elementFromPoint(b.left + b.width / 2, b.top + b.height / 2);
+ return !!hit && (e === hit || e.contains(hit));
+ });
+ if (clear) break;
}
const b = await button.boundingBox();
await page.mouse.click(b.x + b.width / 2, b.y + b.height / 2);
diff --git a/internal/gui/tests/search-api.test.cjs b/internal/gui/tests/search-api.test.cjs
index 1731ed9e3..be1169e92 100644
--- a/internal/gui/tests/search-api.test.cjs
+++ b/internal/gui/tests/search-api.test.cjs
@@ -15,7 +15,7 @@ const fs = require("node:fs/promises");
const path = require("node:path");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
-const { watchSettingsReads, settingsDrawn } = require("./reader.cjs");
+const { watchSettingsReads, settingsDrawn, reach } = require("./reader.cjs");
const assets = path.resolve(__dirname, "../assets");
const vendors = [
@@ -115,7 +115,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
const b = await loc.boundingBox();
await page.mouse.click(b.x + b.width / 2, b.y + b.height / 2);
};
- const before = await where();
+ let before = await where();
// SearXNG: its address
await click(head.locator("button.search-vendor"));
await click(page.locator(".proto-menu .pm-item", { hasText: "SearXNG" }));
@@ -177,6 +177,12 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
assert.equal(await list.locator(".row.search-api").nth(1).locator("button.search-eye").count(), 0);
assert.equal(await tavily.locator(".sub").innerText(), "tvly…abcd");
const sent = posted.length;
+ // the clicks so far moved nothing; Image generation timeout, drawn
+ // above, puts the saved keys past the window's foot at 420, so the
+ // reader wheels down to them, and the clicks from there move nothing
+ assert.deepEqual(await where(), before, "the clicks moved nothing");
+ await reach(page, tavily.locator("button.search-eye"));
+ before = await where();
await click(tavily.locator("button.search-eye"));
await page.waitForFunction(() => document.querySelector("#searchList .row.search-api .sub.revealed"));
assert.equal(await tavily.locator(".sub").innerText(), "tvly-dev-0123456789abcd");
diff --git a/internal/gui/tests/searcher-pick.test.cjs b/internal/gui/tests/searcher-pick.test.cjs
index db42ec771..c073a5539 100644
--- a/internal/gui/tests/searcher-pick.test.cjs
+++ b/internal/gui/tests/searcher-pick.test.cjs
@@ -342,6 +342,10 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
await settingsDrawn(page); // rows found are the ones that stay (#1659)
const row = page.locator("#searchList .searcher-row");
await row.waitFor();
+ // no title before the pointer has come over the help: asked here,
+ // as reach's wheel, from the view's middle, can pass over it (with
+ // Image generation timeout drawn above, it does in Japanese)
+ assert.equal(await row.locator(".sub").getAttribute("title"), null);
// under Image recognition's MCP address (6c1c0a747) the row is
// past the window's foot: the reader scrolls down to it
await reach(page, row.locator("button.searcher-pick"));
@@ -369,7 +373,6 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
assert.equal(layout.whiteSpace, "nowrap", "desktop help stays on one line");
assert.equal(layout.textOverflow, "ellipsis");
assert(layout.overflow > 0, "long help is truncated");
- assert.equal(await sub.getAttribute("title"), null);
await sub.hover();
const full = await sub.evaluate((e) => e.textContent.replace(/\s+/g, " ").trim());
assert.equal(await sub.getAttribute("title"), full, "hover exposes the complete updated help");
diff --git a/internal/imagemcp/call_longest_test.go b/internal/imagemcp/call_longest_test.go
new file mode 100644
index 000000000..279a33d25
--- /dev/null
+++ b/internal/imagemcp/call_longest_test.go
@@ -0,0 +1,18 @@
+package imagemcp
+
+import (
+ "testing"
+ "time"
+
+ "github.com/yetone/magpie/internal/settings"
+)
+
+// The gateway gives a drawing up to Settings' most minutes, and a video
+// several calls; this process, which may not read those settings (WSL),
+// waits on a call longer than either, so it never cuts one the gateway is
+// still waiting on.
+func TestCallOutwaitsTheLongestDrawing(t *testing.T) {
+ if got, want := callLongest(), 2*settings.ImageTimeoutMost*time.Minute; got <= want || got < ToolTimeout() {
+ t.Fatalf("a call is given %v, a drawing up to %v, a tool %v", got, want, ToolTimeout())
+ }
+}
diff --git a/internal/imagemcp/imagemcp.go b/internal/imagemcp/imagemcp.go
index 4d91a1776..0499fbf4f 100644
--- a/internal/imagemcp/imagemcp.go
+++ b/internal/imagemcp/imagemcp.go
@@ -28,6 +28,7 @@ import (
"time"
"github.com/yetone/magpie/internal/gateway"
+ "github.com/yetone/magpie/internal/settings"
)
// Folder is where images go in the project when no path is given, and
@@ -209,6 +210,18 @@ func stillGoing(j *job) string {
// (Codex, Goose) are still given it, as a call's ceiling.
func ToolTimeout() time.Duration { return videoWait + time.Minute }
+// callLongest is the most a call of this server to the gateway may take,
+// and how long a job left running is waited for once the agent has gone.
+// The gateway gives a vendor up to Settings' Image generation timeout to
+// draw (settings.ImageTimeoutMost minutes at the most), and may then fetch
+// what it drew for as long again (gateway.FetchImage): a call is cut only
+// past both. The gateway ends it at the user's own timeout; this server
+// may run where the settings aren't (an agent in WSL), so it never cuts a
+// drawing the setting allows (neighbads on X).
+func callLongest() time.Duration {
+ return max(ToolTimeout(), 2*settings.ImageTimeoutMost*time.Minute+time.Minute)
+}
+
// Run serves MCP on stdin/stdout until stdin closes.
func Run(args []string) error {
if len(args) > 0 && args[0] != "image" {
@@ -225,17 +238,14 @@ func Run(args []string) error {
if base == "" {
base = gateway.URL()
}
- // the gateway draws for up to 5 minutes and may then fetch what the
- // vendor drew for up to 5 more (gateway.ImageLongest): a call to it
- // is cut only past both
- s := &server{gateway: base, client: &http.Client{Timeout: ToolTimeout()}, enc: json.NewEncoder(os.Stdout), agent: gateway.DrawAgent, pending: map[string]chan rpc{}}
+ s := &server{gateway: base, client: &http.Client{Timeout: callLongest()}, enc: json.NewEncoder(os.Stdout), agent: gateway.DrawAgent, pending: map[string]chan rpc{}}
err := s.serve(os.Stdin)
// what is still being made is saved, though the agent has gone
done := make(chan struct{})
go func() { s.running.Wait(); close(done) }()
select {
case <-done:
- case <-time.After(ToolTimeout()):
+ case <-time.After(callLongest()):
}
return err
}
diff --git a/internal/settings/image_timeout_test.go b/internal/settings/image_timeout_test.go
new file mode 100644
index 000000000..0b5f5766e
--- /dev/null
+++ b/internal/settings/image_timeout_test.go
@@ -0,0 +1,40 @@
+package settings
+
+import (
+ "testing"
+ "time"
+)
+
+// Settings' Image generation timeout (neighbads on X: a slow image
+// endpoint needs more than 5 minutes) is kept from 1 to 60 minutes, and
+// 0, which is what a settings.json without it reads as, is the 5 drawing
+// was always given.
+func TestImageTimeoutKeptAndBounded(t *testing.T) {
+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())
+ if w := Load().ImageWait(); w != 5*time.Minute {
+ t.Fatalf("unset: %v", w)
+ }
+ for _, m := range []int{1, 30, 60} {
+ if err := Save(Settings{ImageTimeout: m}); err != nil {
+ t.Fatalf("%d: %v", m, err)
+ }
+ if s := Load(); s.ImageTimeout != m || s.ImageWait() != time.Duration(m)*time.Minute {
+ t.Fatalf("%d read back as %d, %v", m, s.ImageTimeout, s.ImageWait())
+ }
+ }
+ for _, m := range []int{-1, 61, 600} {
+ if Save(Settings{ImageTimeout: m}) == nil {
+ t.Fatalf("%d minutes accepted", m)
+ }
+ }
+ if Load().ImageTimeout != 60 {
+ t.Fatal("a refused value overwrote the saved one")
+ }
+ // a settings.json written by hand past the bounds still waits within them
+ if w := (Settings{ImageTimeout: 600}).ImageWait(); w != time.Hour {
+ t.Fatalf("600 waits %v", w)
+ }
+ if w := (Settings{ImageTimeout: -3}).ImageWait(); w != 5*time.Minute {
+ t.Fatalf("-3 waits %v", w)
+ }
+}
diff --git a/internal/settings/settings.go b/internal/settings/settings.go
index c94e91fa7..c104d2a95 100644
--- a/internal/settings/settings.go
+++ b/internal/settings/settings.go
@@ -303,6 +303,11 @@ type Settings struct {
// "off" turns the video a request that names no model gets off too
// (gateway.videomaker).
ImageGen string `json:"imageGen,omitempty"`
+ // ImageTimeout is how long, in minutes, a vendor is given to draw an
+ // image and send it (neighbads on X: a slow image endpoint needs more
+ // than 5): from 1 to ImageTimeoutMost, 0 for ImageTimeoutDefault.
+ // ImageWait reads it.
+ ImageTimeout int `json:"imageTimeout,omitempty"`
// Searcher is the provider that searches the web for a model that
// can't: "<provider>" with the small model magpie picks of it,
// "<provider>/<model>", or empty for the one magpie picks
@@ -818,6 +823,25 @@ func Arrange[T any](s Settings, items []T, id func(T) string) (shown, hidden []T
return shown, hidden
}
+// ImageTimeoutDefault is the minutes an image is given to be drawn when
+// ImageTimeout is 0, and ImageTimeoutMost the most it can be set to.
+const (
+ ImageTimeoutDefault = 5
+ ImageTimeoutMost = 60
+)
+
+// ImageWait is how long a vendor is given to draw an image and send it:
+// ImageTimeout's minutes, ImageTimeoutDefault's when it is 0 (or below),
+// and no more than ImageTimeoutMost's when settings.json was written by
+// hand past it.
+func (s Settings) ImageWait() time.Duration {
+ m := s.ImageTimeout
+ if m < 1 {
+ m = ImageTimeoutDefault
+ }
+ return time.Duration(min(m, ImageTimeoutMost)) * time.Minute
+}
+
// Themes and Langs are the accepted values, in the order the UI offers them.
var (
Themes = []string{"system", "light", "dark"}
@@ -1225,6 +1249,9 @@ func save(s Settings, recording bool) error {
return fmt.Errorf("an update mirror is an http(s) address put before the github.com URL, like https://mirror.example/, not %q", m)
}
}
+ 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 s.UsageAlert < 0 || s.UsageAlert > 100 {
return fmt.Errorf("a usage alert is at a percentage from 1 to 100, or 0 for off, not %d", s.UsageAlert)
}