settings: one longest context for every model (WJaunita45604 on X)

Settings > Models > Routing has a Longest context field (magpie model
context-cap [<size>|off], POST /api/settings/context-cap). It lowers every
model's window to it, so a user need not set each model. A window the user
set on a model, or on its provider with "*", wins and is not capped; a model
whose window is unknown stays unknown.

It is applied where the window is derived, provider.windowIn, so /v1/models,
every agent's catalog, group windows and the compaction thresholds that
follow the window all agree. Codex's own models take it through
CodexNativeWindow, CodexWindow and codexcat.Cap on the list the gateway
serves; the list's ETag carries the cap so Codex asks again. The provider
editor's Listed value stays the vendor's.

Run (mote): provider, codexcat, cli, settings, settingsapi, gateway tests;
GUI context-cap, model-load, settings-places, i18n-keys, settings-general in
chromium and webkit (en, zh); TestCoreScriptBudget; gofmt; vet on darwin,
linux nogui and windows. Broken by hand: windowIn without the cap turns
TestContextCapHoldsEveryModelButTheOnesTheUserSet and TestModelsListContextCap
red.
Not tried: the whole GUI suite (one row added to an existing list, no new API
read on page load), a real Codex reading the capped list, Windows run.
Not covered: Claude Code's own [1m] choice (claudeRunName) and agent/claude.go's
fallback when a ref has no window.
This commit is contained in:
yetone
2026-11-11 11:07:57 +08:00
parent eb56de0b59
commit 7476328901
20 changed files with 443 additions and 8 deletions
+1
View File
@@ -26,6 +26,7 @@ something else shows up as drift.
| Codex background compaction | Long conversations' Codex background compaction, in Codex's opened row on the Agents page (`CodexAsyncCompact`, `CodexAsyncCompactPercent`, #2490) writes `[features.async_compaction]` `enabled = true` and `model_async_compact_threshold_percent` (Codex 0.163 reads it only in that table) into each Codex config magpie routes, on every `Sync`. The table is written only when every Codex that reads the config is 0.163.0-alpha.8 or later (`codexReaders`: the CLI on PATH, the Mac app's bundled `codex-cli/codex-package.json`, the Windows Store app and an editor's `openai.chatgpt` extension, whose versions aren't known, a WSL distro's CLI): an older Codex takes every unknown `[features]` entry for a bool and won't load a config with the table ("invalid type: map, expected a boolean"). Otherwise, or with no Codex found, magpie writes the bare `[features]` `async_compaction = true`, which every Codex loads, and no threshold; a table magpie wrote before is taken out on the next `Sync`, and Settings' row names the Codex that held it (`CodexAsyncHeld`). Codex starts a background compaction only on a provider whose `capabilities.remote_compaction` is `"v2"`, which it gives OpenAI and Azure alone, so `[model_providers.magpie]` gets `capabilities = { remote_compaction = "v2" }` too, also when the user turned the feature on by hand (#2493); `putProvider` carries the table's capabilities over when it writes it again. What magpie wrote is in the stash under `codex.async`: a value the user set, or changed since, is never written over and stays when the switch goes off; a bare `async_compaction = true` the stash doesn't name as magpie's (`bool`), an inline or dotted table is the user's as written. | [`codex_async.go`](../../internal/agent/codex_async.go) |
| Codex windows | Each magpie model's entry in Codex's catalog (`codexcat.entriesAt`, and `listedEntry` for a relay's own entry) says the model's whole window as `context_window`, which Codex shows (95% of it) as the conversation's context. Where Codex compacts goes in the entry's `auto_compact_token_limit`: the threshold set on the model or its provider, else Long conversations' (`settings.Working`, 272K by default), only when that is below the window; Full window writes none. A model whose window magpie doesn't know (a relay listing none, one models.dev lacks) gets no `context_window` and still the threshold as `auto_compact_token_limit` (Long conversations' Compact at, 272K by default; a relay's own entry only a user-set one, under its own window and limit): Codex compacts at no point on an entry with neither, and after the vendor's "too long" every turn errors again until a manual /compact (jiangguochao666 on X, 11-01; reproduced with real Codex 0.165 and a relay refusing past 100K, compacted at 80K after the fix). `TestCodexCompactsWithNoKnownWindow`. A vendor that lists a larger window than it takes is not caught: Codex compacts on that window's 90%, or the threshold. Codex 0.165 compacts at the lesser of it and 90% of the window, and a `model_auto_compact_token_limit` the user put in config.toml comes before it, as a `model_context_window` there replaces every model's window (Codex then compacts at 90% of it). Long conversations' row in Codex's opened card names either one, top-level or in the profile config.toml picks (`agent.CodexCompactHeld`, sent to the page as one line by `codexKeysText`), and Take it out deletes them (`DropCodexCompactHolds`); magpie never deletes them on its own, as the value is the user's (zgjfjfl on Discord, 10-31: 128000 there, 544K in Long conversations). No threshold above a model's window moves Codex either, which then compacts at 90% of it: the row names the model Codex's config runs (`agent.CodexModel`, the picked profile's first) and the window magpie tells Codex for it, when Long conversations doesn't come below it and no threshold is set on the model or its provider (`codexWindowUnder` in internal/gui/api.go; the reporter's model was a relay's gpt-6-A). `TestCodexCompactHeldNamedAndTakenOut`, `TestCodexWindowUnderLongConversations`, codex-compact-held.test.cjs. Until 10-30 the threshold went in `context_window` with the window as `max_context_window`, so a 1M model showed 258K in Codex (01huadalang on Discord); `max_context_window` stays a field magpie owns so `Keep` doesn't carry an old catalog's over. Codex's own models (`codex/`) keep their entry's window. `Tag` carries `catalogFormat`, so a Codex holding a list in the old shape asks again. `TestCodexCatalogCompactAt`, `TestCodexWindowShownCompactApart`. | [`codexcat.go`](../../internal/codexcat/codexcat.go) |
| An agent's own Long conversations | Codex, Claude Code and Grok Build (`settings.CompactAgents`) can each have a Long conversations of their own over the one for every agent (molianyin4227 on Discord: models differ, so one size fits none): `settings.AgentCompacts[agent]` holds Compact at (`At`, 0 for the working window) or Full window (`Full`), and `Settings.ForAgent(agent)` lays it over `CompactAt`/`FullContext` for that agent's readers alone (`codexcat.entriesAt`, `codexListed`, `claudeIn`'s `writeCompact` and `desktopPlan`, `grokModelTables`, the route list's `buildModels`, Codex's window line and Tuned for you). A threshold set on a model or its provider still comes first. An agent with none follows the value for every agent, so an agent without the key (any agent outside the three) gets nothing new written. Set by `provider.SetAgentCompact` (`POST /api/settings/agent-compact` `{agent, own, full, at}`; `own` false takes it away), shown as a row under Long conversations in the agent's opened row and its sheet ("Long conversations in <agent>": Every agent, Compact at, Full window), drawn by `agentcompact.js`, which app.js imports when the agent's settings hold Long conversations. Tuned for you's Use on an agent with its own value changes that one and stashes it under `tune.long.compact.<agent>`. In a terminal, `magpie model compact <codex|claude|grok> [every|off|<size>]` (`agentCompact`, `TestModelCompactAgentCmd`). Not covered: t3code's route list reads the value for every agent. `TestSetAgentCompact`, `TestCodexCatalogCompactAt`, `TestGrokWindowFollowsLongConversations`, `TestClaudeCompactAt`, `TestTuneAgentOwnLong`, agent-compact.test.cjs. | [`settings.go`](../../internal/settings/settings.go), [`compact.go`](../../internal/provider/compact.go), [`agentcompact.js`](../../internal/gui/assets/agentcompact.js) |
| Longest context | One cap on every model's window (`settings.ContextCap`, WJaunita45604 on X), in Settings › Models › Routing as Longest context (`renderContextCap`), `POST /api/settings/context-cap` `{at}` (0 takes it away), `magpie model context-cap [<size>\|off]`. It is a `min` against the vendor's listed window: `provider.windowIn` (`WindowOf`, `entryFor`, so /v1/models, every agent's catalog, group windows and the compaction thresholds derived from them) and, for Codex's own models, `CodexNativeWindow`, `CodexWindow` and `codexcat.Cap` on the list the gateway serves (`codexWindowsTag` carries the cap, so Codex asks again). A window the user set on a model, or `*` on its provider (`Contexts`), comes first and is not capped; a model whose window is unknown stays unknown. `Listed` in the provider editor is still the vendor's. Not covered: Claude Code's own `[1m]` choice (`claudeRunName`) and `agent/claude.go`'s fallback when a ref has no window. `TestContextCapHoldsEveryModelButTheOnesTheUserSet`, `TestModelsListContextCap`, `TestCapHoldsAnEntry`, `TestModelContextCapCmd`, context-cap.test.cjs. | [`settings.go`](../../internal/settings/settings.go), [`models.go`](../../internal/provider/models.go) |
| Claude Code's prompt cache | Claude Code's opened row and sheet have, under its Long conversations, "Prompt cache · main conversation" and "Prompt cache · subagents" (Linka on Discord), each Claude Code's default, 5 min or 1 hour in the app menu (`claudeCacheRows` in `agentcompact.js`). They write the keys Tuned for you writes, `promptCacheTtl` and `subagentPromptCacheTtl` in Claude Code's settings.json (`agent.ClaudeCacheSet`, `POST /api/settings/claude-cache` `{knob, value}`; the values read back as `claudeCache` in `/api/settings`). Default takes the key out. A pick is the user's: it forgets the card's stash, so Undo leaves it. A variable that comes first (`FORCE_PROMPT_CACHING_5M`, `CLAUDE_CODE_PROMPT_CACHE_TTL`, `CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL`) disables the row and names it, and the route refuses. Claude Code 2.1.316 reads them in that order, then the setting, then an agent's `experimental.cacheTtl`, then `ENABLE_PROMPT_CACHING_1H`; unset, the main conversation takes 1 hour on a subscription within its limits and subagents 5 minutes. `TestClaudeCacheSet`, `TestClaudeCacheRoute`, claude-cache.test.cjs. | [`tune.go`](../../internal/agent/tune.go), [`agentcompact.js`](../../internal/gui/assets/agentcompact.js) |
| Codex instructions | Each magpie model's entry in Codex's catalog carries the instructions official Codex sends that model, Codex's own text word for word; magpie writes none of its own and never changes the identity line (`codexcat.officialFor`). The model's slug (the id's last path segment, lowercased) is matched as Codex matches one, by the longest prefix of an official slug (`longestPrefix`; `auto/gpt-6.1-sol` takes gpt-6.1-sol's, `s2a/openai/gpt-6-luna-2026-09-14` gpt-6-luna's): first against the entries the user's ChatGPT account handed this Codex (`CacheEntries`, models_cache.json), whose `base_instructions` (else `model_messages.instructions_template`) and `model_messages` go over as sent; then against Codex's bundled catalog (`codex_instructions.json`, each model's `instructions_template` from openai/codex rust-v0.166.0's models-manager/models.json), the text only, as an older Codex may not read that release's `model_messages`. Any other model, and a routing group (`group/`), which may hand a turn to any model, takes Codex's prompt for a model it doesn't know (`Prompt`, models-manager/prompt.md), which is what official Codex sends it (`model_info_from_slug`). An entry Codex was handed with no `base_instructions` (`ownEntry`) takes its `model_messages.instructions_template`, else `Official`, and magpie's own ChatGPT-backend requests fall back to `Official` too (`codexInstructions` in internal/provider). Until 11-01 every third-party model was handed gpt-5.2-codex_prompt.md ("You are Codex, based on GPT-5"), so a magpie GPT-6 model ran on a GPT-5.2-era prompt (#3759, #4008, #4783). The Codex files are in testdata (`testdata/codex-rust-v0.166.0`), and `TestBundledIsCodexOwn` fails when the embedded copies differ from them; on a new Codex release copy its two files there and rebuild `codex_instructions.json`. Real Codex 0.166 against a capturing gateway sends the official text as its first developer message for a GPT-6 model and prompt.md for DeepSeek. `TestThirdPartyModelsTakeCodexOwnInstructions`, `TestThirdPartyModelsTakeCachedEntry`, `TestOwnEntryInstructions`. Not read: the bundled catalog inside the user's installed Codex binary. | [`codexcat.go`](../../internal/codexcat/codexcat.go) |
| Codex: DeepSeek models | A DeepSeek model's entry (`codexcat.deepSeek`: deepseek-v4*, -flash, -pro, -chat, -reasoner after any provider or relay prefix; not a routing group, not a distill) takes what DeepSeek's own Codex setup (cdn.deepseek.com/api-docs/codex-deepseek-setup-en.sh, its models.json) says of its models: `shell_type` `shell_command` (Codex 0.165 reads it as `unified_exec`, its only shell; older Codex had a one-shot `shell_command` tool), `support_verbosity` with `default_verbosity` low, `default_reasoning_summary` none (no `reasoning.summary` sent), `multi_agent_version` v2, and `supports_image_detail_original` on a model whose entry takes images. Not taken: its `base_instructions`/`model_messages` (magpie never rewrites a Codex prompt), its `auto_compact_token_limit` null (magpie's 272K default stays, from e950eb080's DeepSeek latency report; Full window or the model's Compact at gives the whole window), `supports_search_tool` false on v4-pro (#258), its reasoning levels (the provider's). `default_reasoning_summary` is tagged `keep:"unset"`, so a value the user put in another model's entry stays (`Keep`). Other vendors' entries are unchanged. `TestCodexCatalogDeepSeekAsDeepSeekSays`, `TestCodexCatalogKeepsUsersSummary`. | [`codexcat.go`](../../internal/codexcat/codexcat.go) |
+37
View File
@@ -108,6 +108,10 @@ const modelUsage = `usage:
settings on the Agents page,
is the same switch; a provider's own Compact at (its
editor) comes before it
magpie model context-cap [<size>|off] the longest context window any model is told, such as 200k:
agents' lists and /v1/models say no more for every model
that has no window of its own (magpie model context); a
shorter or unknown window stays as it is. off takes it away
magpie model compact <agent> [every|off|<size>] codex, claude or grok's own Long conversations: every
follows the one above; off runs to the whole window; a
size compacts there
@@ -149,6 +153,8 @@ func modelCmd(args []string) error {
return modelSuffix(args[1:])
case "compact", "full-context":
return modelCompact(args[1:])
case "context-cap", "ctx-cap":
return modelContextCap(args[1:])
case "context", "ctx":
return modelContext(args[1:])
case "output", "max-output":
@@ -790,6 +796,37 @@ func modelCompact(args []string) error {
return nil
}
// modelContextCap says or sets the longest context window any model is told
// (settings.ContextCap).
func modelContextCap(args []string) error {
if len(args) == 0 {
if n := settings.Load().ContextCap; n > 0 {
fmt.Println(bold.Render(tokenCount(n)), muted.Render("· no model is told a longer window, unless you set one for it or its provider · magpie model context-cap off"))
} else {
fmt.Println("off", muted.Render("· every model takes its own window · magpie model context-cap <size>"))
}
return nil
}
var n int
switch v := strings.ToLower(args[0]); v {
case "off", "no", "none", "0":
default:
var err error
if n, err = provider.ParseTokens(v); err != nil || n <= 0 {
return fmt.Errorf("magpie model context-cap <size such as 200k>|off, not %q", args[0])
}
}
if err := provider.SetContextCap(n); err != nil {
return err
}
if n == 0 {
fmt.Println(green.Render("✓"), "every model takes its own window again")
} else {
fmt.Println(green.Render("✓"), "no model is told a window longer than", tokenCount(n), muted.Render("· one you set for a model or a provider stays"))
}
return nil
}
// agentCompact says or sets an agent's own Long conversations
// (settings.AgentCompacts): every follows the one above for every agent,
// off runs to the whole window, a size compacts there.
@@ -0,0 +1,30 @@
package cli
import (
"testing"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/settings"
)
// magpie model context-cap 200k holds every model's window to 200K, off
// takes it away, and a value that is not a length is refused with the cap
// as it was (WJaunita45604 on X).
func TestModelContextCapCmd(t *testing.T) {
groupsHome(t)
catalog.Changed = nil // no agent's files are rewritten here
if err := modelCmd([]string{"context-cap", "200k"}); err != nil || settings.Load().ContextCap != 200000 {
t.Fatal(err, settings.Load().ContextCap)
}
if err := modelCmd([]string{"context-cap"}); err != nil {
t.Fatal(err)
}
for _, bad := range []string{"maybe", "-5", "0k"} {
if err := modelCmd([]string{"context-cap", bad}); err == nil || settings.Load().ContextCap != 200000 {
t.Fatalf("took %q: %v, cap %d", bad, err, settings.Load().ContextCap)
}
}
if err := modelCmd([]string{"context-cap", "off"}); err != nil || settings.Load().ContextCap != 0 {
t.Fatal(err, settings.Load().ContextCap)
}
}
+22
View File
@@ -1211,6 +1211,28 @@ func Window(e map[string]any, n, most int) {
}
}
// Cap holds one of Codex's own entries to a window of at most n tokens
// (settings.ContextCap), where the user set none for it: its window, the
// most it may be raised to and the threshold it compacts at come down to n
// when they are above it, and nothing else changes.
func Cap(e map[string]any, n int) {
if n <= 0 {
return
}
for _, k := range []string{"context_window", "max_context_window", "auto_compact_token_limit"} {
switch v := e[k].(type) {
case float64:
if int(v) > n {
e[k] = n
}
case int:
if v > n {
e[k] = n
}
}
}
}
// Codex keeps the model list it was handed in models_cache.json, with the
// list's ETag, and asks again only once the cache has aged (minutes) — or
// when a reply's X-Models-Etag differs from it; the same one only makes the
+24
View File
@@ -0,0 +1,24 @@
package codexcat
import "testing"
// Cap holds one of Codex's own entries to a window, with the most it may be
// raised to and the threshold it compacts at, and touches nothing else.
func TestCapHoldsAnEntry(t *testing.T) {
e := map[string]any{"slug": "gpt-5.5", "context_window": float64(272000), "max_context_window": float64(872000), "auto_compact_token_limit": float64(244800)}
Cap(e, 200000)
for _, k := range []string{"context_window", "max_context_window", "auto_compact_token_limit"} {
if got, _ := e[k].(int); got != 200000 {
t.Errorf("%s: %v, want 200000", k, e[k])
}
}
short := map[string]any{"context_window": float64(128000)}
Cap(short, 200000)
if short["context_window"] != float64(128000) {
t.Errorf("a shorter window changed: %v", short)
}
Cap(short, 0)
if short["context_window"] != float64(128000) {
t.Errorf("no cap changed it: %v", short)
}
}
+5 -1
View File
@@ -2432,12 +2432,16 @@ func codexMerged(own []any, cached bool) []any {
// the windows the user set on the codex provider, as /v1/models says
// them (#674); a cached entry, which keeps what magpie handed Codex
// last, takes the account's own list's back when none is set
window := provider.CodexNativeWindow(cached)
window, capAt := provider.CodexNativeWindow(cached), settings.Shared().ContextCap
for _, m := range own {
if o, ok := m.(map[string]any); ok {
slug, _ := o["slug"].(string)
if n, most, ok := window(slug); ok {
codexcat.Window(o, n, most)
} else {
// none the user set: the longest context for every model
// holds (settings.ContextCap)
codexcat.Cap(o, capAt)
}
}
}
+55
View File
@@ -1060,6 +1060,61 @@ func TestModelsListContext(t *testing.T) {
t.Fatalf("no group/big: %s", rec.Body.String())
}
// One longest context for every model (WJaunita45604 on X): /v1/models
// says no window above it for a model the user set none for, and a model's
// own value stays.
func TestModelsListContextCap(t *testing.T) {
setup(t, provider.Chat, &fake{t: t})
p, err := provider.Find("fake")
if err != nil {
t.Fatal(err)
}
p.Models = []string{"m1", "m2"}
p.Contexts = map[string]int{"m2": 900000}
if err := provider.Save(*p); err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(filepath.Dir(catalog.CachePath()), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(catalog.CachePath(), []byte(`{"x":{"models":{"m1":{"id":"m1","limit":{"context":1000000}},"m2":{"id":"m2","limit":{"context":1000000}}}}}`), 0o644); err != nil {
t.Fatal(err)
}
catalog.Reset()
t.Cleanup(catalog.Reset)
windows := func() map[string]float64 {
rec := httptest.NewRecorder()
New().Handler().ServeHTTP(rec, httptest.NewRequest("GET", "/v1/models", nil))
var out struct {
Data []map[string]any `json:"data"`
}
json.Unmarshal(rec.Body.Bytes(), &out)
got := map[string]float64{}
for _, m := range out.Data {
id, _ := m["id"].(string)
for _, k := range []string{"context_window", "context_length", "max_input_tokens"} {
if n, ok := m[k].(float64); ok {
if prev, seen := got[id]; seen && prev != n {
t.Fatalf("%s says two windows: %v", id, m)
}
got[id] = n
}
}
}
return got
}
if got := windows(); got["fake/m1"] != 1000000 || got["fake/m2"] != 900000 {
t.Fatalf("before the cap: %v", got)
}
if err := provider.SetContextCap(200000); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { provider.SetContextCap(0) })
if got := windows(); got["fake/m1"] != 200000 || got["fake/m2"] != 900000 {
t.Fatalf("under a 200K cap: %v, want m1 200000 and m2's own 900000", got)
}
}
func TestModelsListReasoning(t *testing.T) {
fresh(t)
if err := os.MkdirAll(filepath.Dir(catalog.CachePath()), 0o755); err != nil {
+14
View File
@@ -1884,6 +1884,20 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
}
writeJSON(rw, settingsState())
})
// the longest context window any model is told (settings.ContextCap):
// At 0 takes the cap away; a model's or provider's own window stays
mux.HandleFunc("POST /api/settings/context-cap", func(rw http.ResponseWriter, r *http.Request) {
var in struct{ At int }
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
fail(rw, err)
return
}
if err := provider.SetContextCap(in.At); err != nil {
fail(rw, err)
return
}
writeJSON(rw, settingsState())
})
// an agent's own Long conversations (settings.AgentCompacts): Own
// false follows the one for every agent again
mux.HandleFunc("POST /api/settings/agent-compact", func(rw http.ResponseWriter, r *http.Request) {
+1 -1
View File
@@ -21715,7 +21715,7 @@ function renderReplies(s, keep) {
// a Claude run's, in its provider's editor (PROV_PREFS)
$("#claudeRunList").replaceChildren(c, u);
$("#claudeRunList").classList.toggle("gw", gatewayMode);
$("#routeList").replaceChildren(f, a, k, $("#busyLoadRow"));
$("#routeList").replaceChildren(f, a, k, $("#busyLoadRow"), $("#contextCapRow"));
}
// renderDisabledModels: models turned off for every request (#1867), a row per
+8
View File
@@ -1987,6 +1987,8 @@ const I18N = {
"The most a reply may hold, told to the agents as their max tokens and sent as max_tokens on Anthropic's API when the agent names none; empty leaves it to the vendor and models.dev": "单次回复的最大 token 数,作为 max tokens 告知 Agent,Agent 没给时也作为 max_tokens 发给 Anthropic 的 API;留空则按厂商和 models.dev",
"Max output: {v} is not a number of tokens like 32k": "最大输出:{v} 不是 32k 这样的 token 数",
"Compact at": "压缩阈值",
"Longest context": "最长上下文",
"Longest context: {v} is not a number of tokens like 272k": "最长上下文:{v} 不是 272k 这样的 token 数",
"e.g. 500k · or deepseek-v4-flash=272k, comma separated": "如 500k · 或 deepseek-v4-flash=272k,逗号分隔",
"Where Codex, Claude Code and Grok Build compact a long conversation on these models; empty follows Long conversations, in their settings on the Agents page (else in Settings), and a size at or above a model's window runs it to its whole window": "Codex、Claude Code 和 Grok Build 在这些模型上压缩长对话的位置;留空按 Agent 页里它们设置中的「长对话」(否则在「设置」里),大于等于模型窗口则用完整窗口",
"Compact at: {v} is not a number of tokens like 272k": "压缩阈值:{v} 不是 272k 这样的 token 数",
@@ -6990,6 +6992,8 @@ const I18N = {
"The most a reply may hold, told to the agents as their max tokens and sent as max_tokens on Anthropic's API when the agent names none; empty leaves it to the vendor and models.dev": "單次回覆的最大 token 數,作為 max tokens 告知 Agent,Agent 沒給時也作為 max_tokens 發給 Anthropic 的 API;留空則按廠商和 models.dev",
"Max output: {v} is not a number of tokens like 32k": "最大輸出:{v} 不是 32k 這樣的 token 數",
"Compact at": "壓縮閾值",
"Longest context": "最長上下文",
"Longest context: {v} is not a number of tokens like 272k": "最長上下文:{v} 不是 272k 這樣的 token 數",
"e.g. 500k · or deepseek-v4-flash=272k, comma separated": "如 500k · 或 deepseek-v4-flash=272k,逗號分隔",
"Where Codex, Claude Code and Grok Build compact a long conversation on these models; empty follows Long conversations, in their settings on the Agents page (else in Settings), and a size at or above a model's window runs it to its whole window": "Codex、Claude Code 和 Grok Build 在這些模型上壓縮長對話的位置;留空按 Agent 頁裡它們設定中的「長對話」(否則在「設定」裡),大於等於模型視窗則用完整視窗",
"Compact at: {v} is not a number of tokens like 272k": "壓縮閾值:{v} 不是 272k 這樣的 token 數",
@@ -11969,6 +11973,8 @@ const I18N = {
"The most a reply may hold, told to the agents as their max tokens and sent as max_tokens on Anthropic's API when the agent names none; empty leaves it to the vendor and models.dev": "1 回の返答の最大トークン数で、max tokens としてエージェントに伝えられ、エージェントが指定しない場合は Anthropic の API に max_tokens として送られます。空欄の場合はベンダーと models.dev に従います",
"Max output: {v} is not a number of tokens like 32k": "最大出力:{v} は 32k のようなトークン数ではありません",
"Compact at": "圧縮しきい値",
"Longest context": "最長コンテキスト",
"Longest context: {v} is not a number of tokens like 272k": "最長コンテキスト:{v} は 272k のようなトークン数ではありません",
"e.g. 500k · or deepseek-v4-flash=272k, comma separated": "例:500k · または deepseek-v4-flash=272k(カンマ区切り)",
"Where Codex, Claude Code and Grok Build compact a long conversation on these models; empty follows Long conversations, in their settings on the Agents page (else in Settings), and a size at or above a model's window runs it to its whole window": "Codex、Claude Code、Grok Build がこれらのモデルで長い会話を圧縮する位置です。空欄ならエージェントページのそれぞれの設定にある「長い会話」(なければ「設定」)に従い、モデルのウィンドウ以上ならウィンドウ全体を使います",
"Compact at: {v} is not a number of tokens like 272k": "圧縮しきい値:{v} は 272k のようなトークン数ではありません",
@@ -16979,6 +16985,8 @@ const I18N = {
"The most a reply may hold, told to the agents as their max tokens and sent as max_tokens on Anthropic's API when the agent names none; empty leaves it to the vendor and models.dev": "Höchstzahl an Token einer Antwort, den Agenten als max tokens mitgeteilt und an Anthropics API als max_tokens gesendet, wenn der Agent keine nennt; leer überlässt es dem Anbieter und models.dev",
"Max output: {v} is not a number of tokens like 32k": "Max. Ausgabe: {v} ist keine Token-Zahl wie 32k",
"Compact at": "Komprimieren ab",
"Longest context": "Längster Kontext",
"Longest context: {v} is not a number of tokens like 272k": "Längster Kontext: {v} ist keine Token-Zahl wie 272k",
"e.g. 500k · or deepseek-v4-flash=272k, comma separated": "z. B. 500k · oder deepseek-v4-flash=272k, durch Kommas getrennt",
"Where Codex, Claude Code and Grok Build compact a long conversation on these models; empty follows Long conversations, in their settings on the Agents page (else in Settings), and a size at or above a model's window runs it to its whole window": "Wo Codex, Claude Code und Grok Build eine lange Unterhaltung bei diesen Modellen komprimieren; leer folgt Lange Unterhaltungen in ihren Einstellungen auf der Seite Agenten (sonst unter Einstellungen), ein Wert ab dem Fenster des Modells nutzt das ganze Fenster",
"Compact at: {v} is not a number of tokens like 272k": "Komprimieren ab: {v} ist keine Token-Zahl wie 272k",
+4
View File
@@ -391,6 +391,10 @@
<div class="who"><div class="name" data-t>Busy models last</div><div class="sub" data-t>A model its plugin says is busier than this goes after the others a request could go to, as its vendor makes it wait. One with no load reported in the last 5 minutes keeps its place</div></div>
<div id="busyLoadSegs"></div>
</div>
<div class="row pref" id="contextCapRow">
<div class="who"><div class="name" data-t>Longest context</div></div>
<div class="val" id="contextCapVal"></div>
</div>
</div>
<div class="row-head"><span class="label" data-t>Disabled models</span></div>
<div class="list prefs" id="disabledModelsList"></div>
@@ -80,6 +80,7 @@ function renderPort(s) {
// codex/gpt-5.6-sol. Posted on its own; off by default.
function renderBareIds(s) {
renderBusyLoad(s); // Models › Routing's row
renderContextCap(s);
$("#bareIdsSegs").replaceChildren(segs([[false, t("Off")], [true, t("On")]], !!s.bareModelIDs, (on) =>
writingPrefs(api("settings/bare-ids", { on })).then((ns) => { prefs = state.settings = ns; renderSettings(); })
.catch((e) => { status(t(e.message), "err"); renderSettings(); })));
@@ -131,6 +132,31 @@ function renderBusyLoad(s) {
}));
}
// renderContextCap: one longest context for every model (settings.ContextCap,
// WJaunita45604 on X). A window a model or its provider has set itself wins;
// empty or "off" takes the cap away.
function renderContextCap(s) {
const field = input(s.contextCap ? contextsText({ "*": s.contextCap }) : "", t("None"));
field.className = "words context-cap";
field.style.cssText = "width:96px;flex:none";
field.setAttribute("aria-label", t("Longest context"));
const save = () => {
const v = field.value.trim().toLowerCase();
let at = 0;
if (v && v !== "off") {
const r = parseContexts(v);
if (r.error || !r.map["*"]) { status(t("Longest context: {v} is not a number of tokens like 272k", { v: field.value }), "err"); return renderContextCap(s); }
at = r.map["*"];
}
if (at === (s.contextCap || 0)) return renderContextCap(s);
writingPrefs(api("settings/context-cap", { at })).then((ns) => { prefs = state.settings = ns; renderSettings(); })
.catch((e) => { status(t(e.message), "err"); renderSettings(); });
};
field.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Enter") field.blur(); if (e.key === "Escape") { field.value = s.contextCap ? contextsText({ "*": s.contextCap }) : ""; field.blur(); } };
field.onchange = save;
$("#contextCapVal").replaceChildren(field);
}
// renderCORS: the web pages whose scripts may call the gateway from a
// browser (#1051), by origin — a row to add one, and one row each to take
// it away. A page listed calls with a gateway key; none listed, no page
+1 -1
View File
@@ -1037,7 +1037,7 @@ func providerInfoWith(p provider.Provider, ls provider.Listing, agents []agentUs
if imageSet {
images = said
}
window := p.WindowOf(m)
window := p.WindowIn(m, set)
j := modelJSON{ID: m.ID, Name: m.Name, Efforts: provider.EffortsOf(m), On: on, Context: window, Output: provider.OutputWithin(window, p.ReplyLimitIn(m, set)), Listed: provider.ListedWindow(m), ListedOutput: provider.OutputWithin(provider.ListedWindow(m), p.ReplyLimitIn(m, settings.Settings{})), Max: m.MaxContext, Free: m.Free, Rate: m.Rate, RateWas: m.RateWas, Images: images, ImageSet: imageSet, Own: own, Best: newest[m.ID]}
list, listed, free := pricer.Prices(set, m.ID)
j.Zero = !m.Free && free
+96
View File
@@ -0,0 +1,96 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// One longest context for every model (settings.contextCap, WJaunita45604
// on X): Settings > Models > Routing has a Longest context field, empty
// ("None") by default, no secondary text. A size typed (272k, 1m) and
// committed with Enter posts settings/context-cap on its own and shows as
// set; empty or "off" posts 0; something that is not a number of tokens is
// refused with nothing posted; no typing scrolls the page.
// English and Chinese, Chromium and WebKit; no backend, the API is faked.
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 { watchSettingsReads, settingsDrawn, wheelTo } = require("./reader.cjs");
const assets = path.resolve(__dirname, "../assets");
function server(lang, posted) {
let cur = { theme: "light", lang, tray: "panel", currency: "usd", version: "0.1.900", dir: "~/.config/magpie", gateway: "http://127.0.0.1:3425", proxyNow: "none", proxySource: "none", visionModels: [], imageGenModels: [], titleModels: [], workbuddyCheckins: [], lanURLs: [], redactWords: [], trayUsageEvery: 3, fx: { rate: 7.2, at: new Date().toISOString(), stale: false } };
return async (route) => {
const req = route.request(), url = new URL(req.url());
const json = (data) => route.fulfill({ json: data });
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" }, fx: cur.fx });
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true } });
if (url.pathname === "/api/settings/context-cap") {
const body = req.postDataJSON();
posted.push(["context-cap", body]);
cur = { ...cur, contextCap: body.at || undefined };
return json(cur);
}
if (url.pathname === "/api/settings") {
if (req.method() === "POST") posted.push(["settings", req.postDataJSON()]);
return json(cur);
}
if (url.pathname === "/api/plugins") return json({ plugins: [] });
if (url.pathname === "/api/usage/quotas") return json([]);
if (url.pathname === "/api/agents/cli") return json({ agents: {}, pending: false });
if (url.pathname === "/api/groups") return json({ groups: [], models: [] });
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 route.fulfill({ body: await fs.readFile(file), contentType });
};
}
const want = {
en: { name: "Longest context", none: "None", bad: "Longest context: lots is not a number of tokens like 272k" },
zh: { name: "最长上下文", none: "无", bad: "最长上下文:lots 不是 272k 这样的 token 数" },
};
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of Object.keys(want)) {
const w = want[lang];
test(`${engine} ${lang}: one longest context for every model`, async (t) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: process.env.PLAYWRIGHT_CHANNEL || "chromium" }));
t.after(() => browser.close());
const page = await (await browser.newContext({ viewport: { width: 900, height: 420 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
const errors = [], posted = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", server(lang, posted));
await watchSettingsReads(page);
await page.goto("http://magpie.test/?view=settings&tab=models");
await settingsDrawn(page);
const row = page.locator("#contextCapRow"), field = row.locator("input.context-cap");
await field.waitFor();
assert.equal((await row.locator(".name").textContent()).trim(), w.name);
assert.equal(await row.locator(".sub").count(), 0, "no secondary text");
assert.equal(await field.getAttribute("placeholder"), w.none);
assert.equal(await field.inputValue(), "");
assert.equal(await row.locator("select").count(), 0, "no native select");
const view = () => page.locator("#view-settings").evaluate((v) => v.scrollTop);
await wheelTo(page, field, 160); // in sight first, so Playwright's own scrolling isn't counted
const before = await view();
await field.fill("lots");
await field.press("Enter");
await page.getByText(w.bad).waitFor();
assert.deepEqual(posted, []);
await row.locator("input.context-cap").fill("272k");
await row.locator("input.context-cap").press("Enter");
await page.waitForFunction(() => document.querySelector("#contextCapRow input")?.value === "272k" && !document.querySelector("#contextCapRow input:focus"));
assert.deepEqual(posted, [["context-cap", { at: 272000 }]]);
await row.locator("input.context-cap").fill("off");
await row.locator("input.context-cap").press("Enter");
await page.waitForFunction(() => document.querySelector("#contextCapRow input")?.value === "");
assert.deepEqual(posted.at(-1), ["context-cap", { at: 0 }]);
assert(!posted.some((p) => p[0] === "settings"), "set on its own, not with the other preferences");
assert.equal(await view(), before, "typing scrolled the page");
assert(await row.boundingBox().then((b) => b.height < 80), "the row stays one line");
assert.deepEqual(errors, []);
});
}
}
+7 -2
View File
@@ -837,6 +837,7 @@ func CodexNativePicked() (map[string]bool, bool) {
func CodexNativeWindow(restore bool) func(slug string) (n, most int, ok bool) {
p, _ := find(All(), "codex")
live, _, _ := catalog.Live("codex")
capped := settings.Shared()
return func(slug string) (int, int, bool) {
if n := p.ContextOf(slug); n > 0 {
return n, 0, true
@@ -849,7 +850,7 @@ func CodexNativeWindow(restore bool) func(slug string) (n, most int, ok bool) {
// a list without the max (saved before magpie kept
// it) leaves the cache's own; Window still raises it to
// the window when it's below
return m.Context, m.MaxContext, true
return capped.Capped(m.Context), capped.Capped(m.MaxContext), true
}
}
return 0, 0, false
@@ -870,6 +871,7 @@ func CodexWindow(user, slug string) int {
if n := p.ContextOf(slug); n > 0 {
return n
}
capped := settings.Shared()
var lists [][]catalog.Model
if user != "" {
if live, _, ok := catalog.Live(accountModels("codex", user)); ok {
@@ -883,7 +885,7 @@ func CodexWindow(user, slug string) int {
for _, ms := range lists {
for _, m := range ms {
if n := catalog.Window(m.Context); m.ID == slug && n > 0 {
return n
return capped.Capped(n)
}
}
}
@@ -896,6 +898,9 @@ func CodexWindow(user, slug string) int {
func codexWindowsTag() []catalog.Model {
p, _ := find(All(), "codex")
var out []catalog.Model
if n := settings.Shared().ContextCap; n > 0 {
out = append(out, catalog.Model{ID: "~cap", Context: n})
}
for _, k := range slices.Sorted(maps.Keys(p.Contexts)) {
out = append(out, catalog.Model{ID: "=" + k, Context: p.Contexts[k]})
}
+19
View File
@@ -284,3 +284,22 @@ func SetCompactAt(n int) error {
catalog.Touched()
return nil
}
// SetContextCap holds every model's window to n tokens at most
// (settings.ContextCap), where the user set none for the model or its
// provider; 0 takes the cap away. Agents' lists are written again.
func SetContextCap(n int) error {
if n < 0 {
return errorf("a context cap is a number of tokens, not %d", n)
}
s := settings.Load()
if s.ContextCap == n {
return nil
}
s.ContextCap = n
if err := settings.Save(s); err != nil {
return err
}
catalog.Touched()
return nil
}
+65
View File
@@ -0,0 +1,65 @@
package provider
import (
"path/filepath"
"testing"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/settings"
)
// One longest context for every model (WJaunita45604 on X): a window above
// it is told as the cap, a shorter or unknown one as it was, and one the
// user typed for the model or for all the provider's models is theirs.
func TestContextCapHoldsEveryModelButTheOnesTheUserSet(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("USERPROFILE", home)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
catalog.Changed = nil
long := catalog.Model{ID: "long", Context: 1_000_000}
short := catalog.Model{ID: "short", Context: 128_000}
none := catalog.Model{ID: "no-window-anywhere-xyz"}
plain := Provider{ID: "a"}
win := func(p Provider, m catalog.Model) int { return p.WindowOf(m) }
if got := win(plain, long); got != 1_000_000 {
t.Fatalf("no cap: %d", got)
}
if err := SetContextCap(200_000); err != nil {
t.Fatal(err)
}
for _, tc := range []struct {
name string
p Provider
m catalog.Model
want int
}{
{"longer comes down", plain, long, 200_000},
{"shorter stays", plain, short, 128_000},
{"unknown stays unknown", plain, none, 0},
{"the model's own wins", Provider{ID: "a", Contexts: map[string]int{"long": 500_000}}, long, 500_000},
{"its provider's own wins", Provider{ID: "a", Contexts: map[string]int{"*": 400_000}}, long, 400_000},
{"another model of that provider is capped", Provider{ID: "a", Contexts: map[string]int{"other": 500_000}}, long, 200_000},
} {
if got := win(tc.p, tc.m); got != tc.want {
t.Errorf("%s: %d, want %d", tc.name, got, tc.want)
}
// the catalog's entry says what the page does
if got := entryFor(tc.p, tc.m, settings.Load()).Context; got != tc.want {
t.Errorf("%s: entry %d, want %d", tc.name, got, tc.want)
}
}
if ListedWindow(long) != 1_000_000 {
t.Errorf("the vendor's own window changed: %d", ListedWindow(long))
}
if err := SetContextCap(-1); err == nil {
t.Error("took a negative cap")
}
if err := SetContextCap(0); err != nil {
t.Fatal(err)
}
if got := win(plain, long); got != 1_000_000 {
t.Fatalf("cap off: %d", got)
}
}
+12 -3
View File
@@ -3456,7 +3456,7 @@ func entriesOf(of func(Provider) bool, off func(pid, model string) bool) []Entry
// window and the reply limit a request on it is routed and metered against,
// with what the user set taken over the vendor's list and models.dev.
func entryFor(p Provider, m catalog.Model, s settings.Settings) Entry {
ctx := p.WindowOf(m)
ctx := p.windowIn(m, s)
output := p.replyLimit(m, s)
images := m.Images || catalog.SeesImages(m.ID)
if m.ImageInput != nil {
@@ -3717,7 +3717,16 @@ func ListedWindow(m catalog.Model) int {
// is the user's word on it, larger or not. The catalog's entries and the
// Providers page's model lists both read it, so the page shows the window
// agents are told.
func (p Provider) WindowOf(m catalog.Model) int {
func (p Provider) WindowOf(m catalog.Model) int { return p.windowIn(m, settings.Shared()) }
// WindowIn is WindowOf with the settings s already read.
func (p Provider) WindowIn(m catalog.Model, s settings.Settings) int { return p.windowIn(m, s) }
// windowIn is WindowOf under settings s: a window the user typed, for the
// model or for all the provider's (which is no larger than the model's own
// where it says), is theirs as it is; any other is held to the longest
// context the user set for every model (settings.ContextCap).
func (p Provider) windowIn(m catalog.Model, s settings.Settings) int {
if n := p.Contexts[m.ID]; n > 0 {
return n
}
@@ -3727,7 +3736,7 @@ func (p Provider) WindowOf(m catalog.Model) int {
}
return n
}
return ListedWindow(m)
return s.Capped(ListedWindow(m))
}
// ContextOf is the context the user set for the provider's model: its own,
+15
View File
@@ -854,6 +854,12 @@ type Settings struct {
// off, in tokens: 0 is WorkingWindow (#876: 272K was the only one).
// A provider's or a model's own (ModelCompacts) comes before it.
CompactAt int `json:"compactAt,omitempty"`
// ContextCap is the longest context window any model is told, in
// tokens, for every model that has no window of its own set by the user
// (a model's, or its provider's "*"): the one cap that replaces setting
// each model's (WJaunita45604 on X). 0 is no cap. It only lowers: a
// model whose window is shorter, or not known, is told what it was.
ContextCap int `json:"contextCap,omitempty"`
// AgentCompacts is Long conversations of an agent's own, by its kind
// (CompactAgents), over CompactAt and FullContext for that agent alone
// (molianyin4227 on Discord: models differ, so one size for every
@@ -1480,6 +1486,15 @@ const WorkingWindow = 272000
// waited for the page to load again.
func (s Settings) LightweightOn() bool { return s.Lightweight != nil && *s.Lightweight }
// Capped is a model's window n under ContextCap: no longer than it, and
// as it was when the cap is off, is longer than n, or n is not known (0).
func (s Settings) Capped(n int) int {
if s.ContextCap > 0 && n > s.ContextCap {
return s.ContextCap
}
return n
}
// Working is the context window an agent is told for a model with one of
// n tokens (see FullContext).
func (s Settings) Working(n int) int {
+1
View File
@@ -341,6 +341,7 @@ func Merge(body []byte, cur settings.Settings, web bool) (settings.Settings, err
in.FullContext = cur.FullContext // set on its own (full-context)
in.CompactAt = cur.CompactAt // and so is the threshold
in.AgentCompacts = cur.AgentCompacts // and each agent's own (agent-compact)
in.ContextCap = cur.ContextCap // and the longest window of every model (context-cap)
// Codex's background compaction, set on its own (codex-async-compact)
in.CodexAsyncCompact, in.CodexAsyncCompactPercent = cur.CodexAsyncCompact, cur.CodexAsyncCompactPercent
// Claude Desktop's list, set in its row on the Agents page