diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md index f93fda3cf..abd5ff53b 100644 --- a/docs/subsystems/agent-wiring.md +++ b/docs/subsystems/agent-wiring.md @@ -27,6 +27,8 @@ 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 ": 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.`. In a terminal, `magpie model compact [every|off|]` (`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) | +| An agent's own context window | Any agent with a model list can be told a window of its own for a model (ul3140773077392 on X: dsh compacts earlier than Codex at the same window, so one window fits some and has others compact too early). `settings.AgentContexts[agent]` (the agent's `ListsFor` id) maps `provider/model`, `group/`, `provider/*`, a bare model id or `*` to a window; the most specific wins, and `*` only shortens a known window. `provider.CatalogFor` lays it over the entries last (`withAgentWindows`, `agentwindow.go`) and marks them `WindowSet`, so every writer of that agent's list (dsh's `contextWindow`, Pi, OpenCode, the gateway's /models) and `CompactFor` (Codex, Claude Code compact at the whole window unless a size was typed) follow it; other agents keep the model's own. Set by `provider.SetAgentContexts` (`POST /api/settings/agent-contexts` `{agent, contexts}`; none takes them away), shown as "Context window in " in the agent's sheet (`agentwindow.js`, any agent with fields), and `magpie model window [=…\|off]`. `TestAgentOwnContextWindow`, `TestDshOwnContextWindow`, `TestModelAgentWindowCmd`, `TestSettingsSaveKeepsWhatItDoesNotSend`, agent-window.test.cjs. Not tried against a live dsh. | [`agentwindow.go`](../../internal/provider/agentwindow.go), [`agentwindow.js`](../../internal/gui/assets/agentwindow.js) | +| A group's own Compact at | A routing group can carry where agents compact on it (`Group.Compact`, NovaStudiosss on X: no need to set a context size and a compaction size on each provider model). `compactSet` returns it before the smallest of its members' sizes, so Codex and Claude Code are told it; 0 is none. Set in the group's editor, Advanced, "Compact at" (beside "Context", which is the window agents are told), by `magpie group set compact=\|off`, and carried by every other save of the group. `TestGroupOwnCompactAt`, group-compact.test.cjs. | [`compact.go`](../../internal/provider/compact.go), [`group.go`](../../internal/provider/group.go) | | 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 [\|off\|all\|own]`, and a menu beside it (`settings.ContextCapAll`, `POST /api/settings/context-cap-mode` `{all}`) for which windows it holds. 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 in the default mode (own: the user's word wins, longer or not); with `ContextCapAll` (`Settings.CappedOwn`) it is held to the cap too, so the shorter of the two is told in both modes; 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`, `TestContextCapAllHoldsTheUsersOwnWindowsToo`, `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) | | Claude Code's commit signature | Claude Code's opened row and sheet have "Commit signature (Co-Authored-By)", On or Off in the app menu (9_bishi on X), under its prompt cache rows (`claudeAttributionRow` in `agentcompact.js`). Off writes `attribution.commit = ""` in Claude Code's settings.json, which hides the trailer (`agent.ClaudeAttributionSet`, `POST /api/settings/claude-attribution` `{on}`; read back as `claudeAttribution`: `on`, `off` or `custom`). On takes out what hides it: an empty `attribution.commit`, `attribution: false` and the deprecated `includeCoAuthoredBy: false`, which Claude Code ignores once `attribution.commit` is set. Trailer text the user wrote is `custom`: shown, never written over. `attribution.pr` is left alone. `TestClaudeAttributionSet`, claude-attribution.test.cjs. | [`claude_attribution.go`](../../internal/agent/claude_attribution.go) | diff --git a/internal/agent/dsh_agent_window_test.go b/internal/agent/dsh_agent_window_test.go new file mode 100644 index 000000000..663515c55 --- /dev/null +++ b/internal/agent/dsh_agent_window_test.go @@ -0,0 +1,43 @@ +package agent + +import ( + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// dsh can be told a window of its own for a model (ul3140773077392 on X: +// it compacts earlier than Codex at the same window). The list written +// for dsh carries it as contextWindow, the one written for Codex and the +// model's own stay as they were. +func TestDshOwnContextWindow(t *testing.T) { + syncHome(t) + window := func(agent string) int { + t.Helper() + for _, m := range magpieModels(agent) { + if m.ID == "relay/glm-4.6" { + return m.Context + } + } + t.Fatalf("%s: no relay/glm-4.6", agent) + return 0 + } + if window("dsh") != 204800 { + t.Fatalf("to begin with: %d", window("dsh")) + } + if err := provider.SetAgentContexts("dsh", map[string]int{"relay/glm-4.6": 400000}); err != nil { + t.Fatal(err) + } + if got := window("dsh"); got != 400000 { + t.Errorf("dsh is told %d; want 400000", got) + } + if got := window("codex"); got != 204800 { + t.Errorf("codex is told %d; want the model's own, 204800", got) + } + if err := provider.SetAgentContexts("dsh", nil); err != nil { + t.Fatal(err) + } + if got := window("dsh"); got != 204800 { + t.Errorf("taken away: %d", got) + } +} diff --git a/internal/cli/groups_cli.go b/internal/cli/groups_cli.go index c023e29e1..a99942cda 100644 --- a/internal/cli/groups_cli.go +++ b/internal/cli/groups_cli.go @@ -28,7 +28,9 @@ const groupUsage = `usage: models (the whole list, in order, patterns too), models+=[,m2…] (append), models-=[,m2…] (drop), routing, stays, context (how long a request agents are told it takes: 272k; smallest - is its smallest model's; empty is its largest model's), levels (the reasoning levels agents are offered: + is its smallest model's; empty is its largest model's), + compact (where Codex and Claude Code compact a conversation on it: 200k; + empty leaves it to its models' and Long conversations), levels (the reasoning levels agents are offered: levels=none,low,medium,high,xhigh,max; empty is those every model has — a model without the one asked is sent its nearest), family (a tag: magpie visible shows agents families, not each group), @@ -517,6 +519,15 @@ func applyGroupPairs(g *provider.Group, pairs []string, resolve func(string) (st default: g.Context, err = parseTokens(v) } + case "compact", "compact-at": + // where Codex and Claude Code compact a conversation on the + // group; empty or 0 leaves it to its members' and Settings' + switch strings.ToLower(strings.TrimSpace(v)) { + case "", "default", "off": + g.Compact = 0 + default: + g.Compact, err = parseTokens(v) + } case "levels", "level": // the reasoning levels agents are offered; empty is those every // member has again diff --git a/internal/cli/groups_cli_test.go b/internal/cli/groups_cli_test.go index e7cece759..cd3f25bf4 100644 --- a/internal/cli/groups_cli_test.go +++ b/internal/cli/groups_cli_test.go @@ -137,6 +137,18 @@ func TestApplyGroupPairs(t *testing.T) { t.Errorf("context=%s: %d %v", c.v, g.Context, err) } } + // compact=: where agents compact on the group (NovaStudiosss on X) + for _, c := range []struct { + v string + want int + }{{"160k", 160000}, {"1m", 1000000}, {"off", 0}, {"", 0}} { + if err := applyGroupPairs(&g, []string{"compact=" + c.v}, resolve, false); err != nil || g.Compact != c.want { + t.Errorf("compact=%s: %d %v", c.v, g.Compact, err) + } + } + if err := applyGroupPairs(&g, []string{"compact=lots"}, resolve, false); err == nil { + t.Error("compact=lots was accepted") + } // listed=no: its models offered through the group alone (#1783) if err := applyGroupPairs(&g, []string{"listed=no"}, resolve, false); err != nil || !g.Unlists { t.Fatalf("listed=no: %v %v", g.Unlists, err) diff --git a/internal/cli/model_cli.go b/internal/cli/model_cli.go index 696b279f7..a1b76ccad 100644 --- a/internal/cli/model_cli.go +++ b/internal/cli/model_cli.go @@ -117,6 +117,12 @@ const modelUsage = `usage: shorter or unknown window stays as it is. off takes it away; all also holds a window you set for a model or its provider (the shorter is told), own leaves those alone + magpie model window [=…|off] + the context window one agent is told for a model, apart from + every other agent's (dsh compacts earlier than Codex at the + same window): is provider/model, group/, + provider/*, a bare model id or * (which only shortens); + off takes them away. No pairs shows them magpie model compact [every|off|] codex, claude or grok's own Long conversations: every follows the one above; off runs to the whole window; a size compacts there @@ -158,6 +164,8 @@ func modelCmd(args []string) error { return modelSuffix(args[1:]) case "compact", "full-context": return modelCompact(args[1:]) + case "window", "agent-context": + return modelAgentWindow(args[1:]) case "context-cap", "ctx-cap": return modelContextCap(args[1:]) case "context", "ctx": @@ -884,6 +892,53 @@ func agentCompact(agent string, args []string) error { return nil } +// modelAgentWindow says or sets the windows one agent is told +// (settings.AgentContexts): model=size pairs replace those it had, off +// takes them away. +func modelAgentWindow(args []string) error { + if len(args) == 0 { + return fmt.Errorf("magpie model window [=…|off]") + } + a, err := agent.Find(args[0]) + if err != nil { + return err + } + id := a.ListsFor() + if len(args) == 1 { + cur := provider.AgentContexts(id) + if len(cur) == 0 { + fmt.Println(muted.Render(fmt.Sprintf("%s is told each model's own window · magpie model window %s =", a.ID, a.ID))) + return nil + } + for _, k := range slices.Sorted(maps.Keys(cur)) { + fmt.Println(k, tokenCount(cur[k])) + } + return nil + } + cs := map[string]int{} + if v := strings.ToLower(args[1]); len(args) == 2 && (v == "off" || v == "every" || v == "default") { + cs = nil + } else { + for _, w := range args[1:] { + k, v, ok := strings.Cut(w, "=") + n, perr := provider.ParseTokens(v) + if !ok || perr != nil || n <= 0 { + return fmt.Errorf("magpie model window %s =|off, not %q", a.ID, w) + } + cs[k] = n + } + } + if err := provider.SetAgentContexts(id, cs); err != nil { + return err + } + if len(cs) == 0 { + fmt.Println(green.Render("✓"), a.ID, "is told each model's own window again") + return nil + } + fmt.Println(green.Render("✓"), a.ID, "is told", len(cs), "window(s) of its own", muted.Render("· takes effect when it next starts")) + return nil +} + func compactWords(s settings.Settings) string { if s.FullContext { return "the model's whole window" diff --git a/internal/cli/model_compact_cli_test.go b/internal/cli/model_compact_cli_test.go index f2e7da08e..5c22001c1 100644 --- a/internal/cli/model_compact_cli_test.go +++ b/internal/cli/model_compact_cli_test.go @@ -66,3 +66,33 @@ func TestModelCompactAgentCmd(t *testing.T) { t.Fatal(settings.Load().AgentCompacts) } } + +// magpie model window dsh deepseek-v4-flash=500k gives dsh a window of its +// own for that model (ul3140773077392 on X); a size alone is for every +// model, off takes them away, and a size that is not one is refused. +func TestModelAgentWindowCmd(t *testing.T) { + groupsHome(t) + catalog.Changed = nil + if err := modelCmd([]string{"window", "dsh", "a/m=500k", "*=256k"}); err != nil { + t.Fatal(err) + } + want := map[string]int{"a/m": 500000, "*": 256000} + if got := settings.Load().AgentContexts["dsh"]; len(got) != 2 || got["a/m"] != want["a/m"] || got["*"] != want["*"] { + t.Fatalf("dsh: %v", got) + } + if err := modelCmd([]string{"window", "dsh"}); err != nil { + t.Fatal(err) + } + if err := modelCmd([]string{"window", "dsh", "lots"}); err == nil { + t.Fatal("took lots") + } + if len(settings.Load().AgentContexts["dsh"]) != 2 { + t.Fatal("a refused size changed them", settings.Load().AgentContexts) + } + if err := modelCmd([]string{"window", "dsh", "off"}); err != nil { + t.Fatal(err) + } + if got := settings.Load().AgentContexts; len(got) != 0 { + t.Fatal(got) + } +} diff --git a/internal/cli/settings_parity_test.go b/internal/cli/settings_parity_test.go index 67a9a687c..a71258127 100644 --- a/internal/cli/settings_parity_test.go +++ b/internal/cli/settings_parity_test.go @@ -229,6 +229,7 @@ var cliForRoute = map[string]string{ "GET /api/update": "magpie update check", "POST /api/update/check": "magpie update check", "POST /api/settings/agent-compact": "magpie model compact", + "POST /api/settings/agent-contexts": "magpie model window", "POST /api/settings/agent-suffix": "magpie model suffix", "POST /api/settings/context-cap": "magpie model context-cap", "POST /api/settings/context-cap-mode": "magpie model context-cap", diff --git a/internal/gui/api.go b/internal/gui/api.go index 627e0a83e..aca3027dc 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -1969,6 +1969,28 @@ func Handler(w Windows, gw *gateway.Server) http.Handler { } writeJSON(rw, settingsState()) }) + // the windows one agent is told, apart from every other's + // (settings.AgentContexts): Contexts replaces them, none takes them away + mux.HandleFunc("POST /api/settings/agent-contexts", func(rw http.ResponseWriter, r *http.Request) { + var in struct { + Agent string + Contexts map[string]int + } + if err := json.NewDecoder(r.Body).Decode(&in); err != nil { + fail(rw, err) + return + } + a, err := agent.Find(in.Agent) + if err != nil { + fail(rw, err) + return + } + if err := provider.SetAgentContexts(a.ListsFor(), in.Contexts); err != nil { + fail(rw, err) + return + } + writeJSON(rw, settingsState()) + }) // an agent's own Provider in model names (settings.AgentSuffix): Mode // "" follows the one for every agent again mux.HandleFunc("POST /api/settings/agent-suffix", func(rw http.ResponseWriter, r *http.Request) { diff --git a/internal/gui/assets/agentcompact.js b/internal/gui/assets/agentcompact.js index f974313ce..ee3e766e8 100644 --- a/internal/gui/assets/agentcompact.js +++ b/internal/gui/assets/agentcompact.js @@ -3,7 +3,7 @@ // row above, else this agent compacts at its own size or runs to the whole // window (settings.AgentCompacts). app.js imports this when an agent's // sheet holds Long conversations, so it weighs nothing on the core. -window.agentCompactFill = function (list, a) { +const compactFill = function (list, a) { const kind = kindOf(a); const row = el("div", "row pref agent-compact"); row.dataset.agent = kind; @@ -142,3 +142,9 @@ function claudeAttributionRow(list) { if (box) seen.observe(box, { childList: true }); return row; } + +// Its own context windows come in the same sheet, last (agentwindow.js). +window.agentCompactFill = function (list, a, ids) { + if (ids.includes("fullContextRow")) compactFill(list, a); + if (a.fields.length) import("./agentwindow.js").then(() => agentWindowFill(list, a), () => {}); +}; diff --git a/internal/gui/assets/agentwindow.js b/internal/gui/assets/agentwindow.js new file mode 100644 index 000000000..fc6cbc029 --- /dev/null +++ b/internal/gui/assets/agentwindow.js @@ -0,0 +1,31 @@ +// An agent's own context windows (ul3140773077392 on X: dsh compacts +// earlier than Codex at the same window, so its window wants setting +// apart from every other agent's). One line in the agent's sheet, model=size +// pairs or one size for all: the model as the catalog has it +// (provider/model, group/), provider/*, a bare model id or *. Empty is +// each model's own window (settings.AgentContexts). app.js imports this when +// an agent's sheet opens, so it weighs nothing on the core. +window.agentWindowFill = function (list, a) { + const kind = kindOf(a).split("#")[0]; + const row = el("div", "row pref agent-window"); + row.dataset.agent = kind; + const who = el("div", "who"), box = el("div"); + who.append(el("div", "name", t("Context window"))); + const own = () => ((prefs || {}).agentContexts || {})[kind] || {}; + const num = input(contextsText(own()), t("e.g. 128k · or gpt-6=1m, comma separated")); + num.className = "words window-in"; + num.spellcheck = false; + num.setAttribute("aria-label", t("Context window")); + const shown = () => { if (document.activeElement !== num) num.value = contextsText(own()); }; + num.onchange = () => { + const r = parseContexts(num.value); + if (r.error) return status(t("Context window: {v} is not a length like 128k or 1m", { v: r.error }), "err"); + writingPrefs(api("settings/agent-contexts", { agent: kind, contexts: r.map })) + .then((ns) => { prefs = ns; renderSettings(); shown(); status(t("Takes effect when {agent} next starts", { agent: a.name }), "ok"); }).catch(settingsErr); + }; + num.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Enter") num.blur(); }; + box.append(num); + row.append(who, box); + list.querySelector(".agent-window")?.remove(); + list.append(row); +}; diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index dff131c8b..0e3c9f411 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -21179,7 +21179,7 @@ const AGENT_PREFS = { claude: ["fullContextRow"], grok: ["fullContextRow"], }; -const agentPrefsOf = (a) => gatewayMode ? null : AGENT_PREFS[kindOf(a)] || (a.telemetry ? [] : null); +const agentPrefsOf = (a) => gatewayMode ? null : AGENT_PREFS[kindOf(a)] || (a.telemetry || a.fields.length ? [] : null); // telemetryRow: the agent's own telemetry off in its config (OipsAnthony on X) function telemetryRow(a) { @@ -21211,7 +21211,7 @@ function telemetryRow(a) { const PREFS_GLYPH = "M2.75 4.75h10.5M2.75 11.25h10.5M5.75 3.25v3M10.25 9.75v3"; let agentPrefRowEls = null; // an agent's own Long conversations, under every agent's (agentcompact.js) -const agentCompactIn = (list, ids, a) => ids.includes("fullContextRow") && (window.agentCompactFill ? agentCompactFill(list, a) : import("./agentcompact.js").then(() => agentCompactFill(list, a), () => {})); +const agentCompactIn = (list, ids, a) => window.agentCompactFill ? agentCompactFill(list, a, ids) : import("./agentcompact.js").then(() => agentCompactFill(list, a, ids), () => {}); // homeAgentPrefRows: the rows a sheet took back in the page function homeAgentPrefRows() { const box = $("#agentPrefRows"); diff --git a/internal/gui/assets/plugins/routing/client.js b/internal/gui/assets/plugins/routing/client.js index 27ad6d55b..d6f4451a8 100644 --- a/internal/gui/assets/plugins/routing/client.js +++ b/internal/gui/assets/plugins/routing/client.js @@ -6232,7 +6232,7 @@ function routingPage(part) { // there, rather than leaving the slot empty. const openGroupEditor = async (g) => { if (groupDirty() && !(await confirmDiscard())) return false; - gEdit = { id: g.id, draft: { name: g.name, note: g.note || "", members: [...g.members], match: [...(g.match || [])], matched: [...(g.matched || [])], fast: [...(g.fast || [])], ultra: [...(g.ultra || [])], off: [...(g.off || [])], weights: { ...(g.weights || {}) }, effortMaps: Object.fromEntries(Object.entries(g.effortMaps || {}).map(([id, m]) => [id, { ...m }])), accounts: [...(g.accounts || [])], keys: [...(g.keys || [])], redact: g.redact || "", routing: g.routing || "", pick: g.pick || "", affinity: g.affinity || "", sink: sinkModeOf(g), unlists: !!g.unlists, firstToken: g.firstToken || 0, patience: g.patience || 0, context: g.context || 0, classifier: g.classifier || "", intentSure: g.intentSure ?? null, effort: g.effort || "", levels: [...(g.levels || [])], rules: (g.rules || []).map((r) => ({ ...r, ...(r.more?.length ? { more: [...r.more] } : {}), intent: r.intent || "", agents: [...(r.agents || [])], folders: [...(r.folders || [])], exceptFolders: [...(r.exceptFolders || [])], where: (r.where || []).map((c) => ({ ...c })), time: r.time ? { ...r.time, days: [...(r.time.days || [])] } : null })) } }; + gEdit = { id: g.id, draft: { name: g.name, note: g.note || "", members: [...g.members], match: [...(g.match || [])], matched: [...(g.matched || [])], fast: [...(g.fast || [])], ultra: [...(g.ultra || [])], off: [...(g.off || [])], weights: { ...(g.weights || {}) }, effortMaps: Object.fromEntries(Object.entries(g.effortMaps || {}).map(([id, m]) => [id, { ...m }])), accounts: [...(g.accounts || [])], keys: [...(g.keys || [])], redact: g.redact || "", routing: g.routing || "", pick: g.pick || "", affinity: g.affinity || "", sink: sinkModeOf(g), unlists: !!g.unlists, firstToken: g.firstToken || 0, patience: g.patience || 0, context: g.context || 0, compact: g.compact || 0, classifier: g.classifier || "", intentSure: g.intentSure ?? null, effort: g.effort || "", levels: [...(g.levels || [])], rules: (g.rules || []).map((r) => ({ ...r, ...(r.more?.length ? { more: [...r.more] } : {}), intent: r.intent || "", agents: [...(r.agents || [])], folders: [...(r.folders || [])], exceptFolders: [...(r.exceptFolders || [])], where: (r.where || []).map((c) => ({ ...c })), time: r.time ? { ...r.time, days: [...(r.time.days || [])] } : null })) } }; renderGroups(); return true; }; @@ -7063,7 +7063,7 @@ function routingPage(part) { closeProtoMenu(); if (v === cur || (groupDirty() && !(await confirmDiscard()))) return b.focus({ preventScroll: true }); const n = opts.find(([id]) => id === v)?.[1] || v; - await groupAction("save", { id: g.id, name: g.name, note: g.note || "", members: namedOf(g), match: g.match || [], routing: v, pick: g.pick || "", affinity: g.affinity || "", sink: !!g.sink && sinkable(v), noSink: !!g.noSink, firstToken: g.firstToken || 0, patience: g.patience || 0, rules: g.rules || [], effort: g.effort || "", classifier: g.classifier || "", intentSure: g.intentSure ?? null, context: g.context || 0, levels: g.levels || [], family: g.family || "", fast: g.fast || [], ultra: g.ultra || [], off: g.off || [], weights: g.weights || {}, effortMaps: g.effortMaps || {}, accounts: g.accounts || [], unlists: !!g.unlists }, + await groupAction("save", { id: g.id, name: g.name, note: g.note || "", members: namedOf(g), match: g.match || [], routing: v, pick: g.pick || "", affinity: g.affinity || "", sink: !!g.sink && sinkable(v), noSink: !!g.noSink, firstToken: g.firstToken || 0, patience: g.patience || 0, rules: g.rules || [], effort: g.effort || "", classifier: g.classifier || "", intentSure: g.intentSure ?? null, context: g.context || 0, compact: g.compact || 0, levels: g.levels || [], family: g.family || "", fast: g.fast || [], ultra: g.ultra || [], off: g.off || [], weights: g.weights || {}, effortMaps: g.effortMaps || {}, accounts: g.accounts || [], unlists: !!g.unlists }, t("{name}: {routing}", { name: g.name, routing: t(n) })); // the rows were drawn anew: the keyboard stays on this one's routing gList.querySelector(`.rt-group[data-id="${CSS.escape(g.id)}"] .rt-groute`)?.focus({ preventScroll: true }); @@ -7199,7 +7199,7 @@ function routingPage(part) { b.onclick = (e) => { e.stopPropagation(); // the card opens the editor; this picks if (on) return; - groupAction("save", { id: g.id, name: g.name, note: g.note || "", members: namedOf(g), match: g.match || [], routing: "manual", pick: id, affinity: g.affinity || "", sink: !!g.sink, noSink: !!g.noSink, firstToken: g.firstToken || 0, patience: g.patience || 0, rules: g.rules || [], effort: g.effort || "", classifier: g.classifier || "", intentSure: g.intentSure ?? null, context: g.context || 0, levels: g.levels || [], family: g.family || "", fast: g.fast || [], ultra: g.ultra || [], off: g.off || [], weights: g.weights || {}, effortMaps: g.effortMaps || {}, accounts: g.accounts || [], unlists: !!g.unlists }, + groupAction("save", { id: g.id, name: g.name, note: g.note || "", members: namedOf(g), match: g.match || [], routing: "manual", pick: id, affinity: g.affinity || "", sink: !!g.sink, noSink: !!g.noSink, firstToken: g.firstToken || 0, patience: g.patience || 0, rules: g.rules || [], effort: g.effort || "", classifier: g.classifier || "", intentSure: g.intentSure ?? null, context: g.context || 0, compact: g.compact || 0, levels: g.levels || [], family: g.family || "", fast: g.fast || [], ultra: g.ultra || [], off: g.off || [], weights: g.weights || {}, effortMaps: g.effortMaps || {}, accounts: g.accounts || [], unlists: !!g.unlists }, t("{name}: every request to {model}", { name: g.name, model: memberName(id) })); }; box.append(b); @@ -7821,7 +7821,7 @@ function routingPage(part) { // owner: the form was too much at once). Open when one of them is set, // or as it was left while this group is being edited const adv = edAligned(el("details", "more advanced rt-gadv")); - adv.open = gEdit.adv ?? !!(d.match.length || d.unlists || d.routing || d.sink === "sink" || d.sink === "" || d.firstToken || d.patience || d.context || d.affinity || d.effort || d.levels?.length); + adv.open = gEdit.adv ?? !!(d.match.length || d.unlists || d.routing || d.sink === "sink" || d.sink === "" || d.firstToken || d.patience || d.context || d.compact || d.affinity || d.effort || d.levels?.length); const advOf = gEdit; adv.onfold = (open) => { advOf.adv = open; }; adv.append(el("summary", "", t("Advanced"))); @@ -7955,6 +7955,19 @@ function routingPage(part) { }; advIn.append(el("label", "", t("Context")), ctxW); drawCtx(); + // where agents compact in this group (NovaStudiosss on X): the size + // here, else the smallest member's, as a provider's model sets it + const cmpIn = keys(input(d.compact > 0 ? ctxShort(d.compact).toLowerCase() : "", t("Default"))); + cmpIn.classList.add("cmp-in"); + cmpIn.setAttribute("aria-label", t("Compact at")); + cmpIn.oninput = () => { + const v = cmpIn.value.trim().toLowerCase().replace(/_/g, ""), m = v.match(/^(\d+(?:\.\d+)?)\s*([km]?)$/); + const n = m ? Math.round(+m[1] * (m[2] === "k" ? 1e3 : m[2] === "m" ? 1e6 : 1)) : 0; + cmpIn.setAttribute("aria-invalid", String(!!v && !(n > 0))); + if (!v) d.compact = 0; + else if (n > 0) d.compact = n; + }; + advIn.append(el("label", "", t("Compact at")), cmpIn); const aHint = el("div", "hint", t(AFF_HINT[d.affinity] || AFF_HINT[""])); const aw = el("div"); aw.append(segs(AFF_OPTS.map(([id, n]) => [id, t(n)]), d.affinity, (v) => { d.affinity = v; aHint.textContent = t(AFF_HINT[v] || AFF_HINT[""]); }), aHint); @@ -8826,7 +8839,7 @@ function routingPage(part) { if (own && !d.levels.length) return status(t("Pick a level to offer, or leave them to its models"), "warn"); saveBtn.classList.add("busy"); // refused, Add can be pressed again (busy, it takes no clicks) - groupAction("save", { id: idOf(), from: g?.id, name: d.name.trim() || idOf(), note: (d.note || "").trim(), members: namedOf(d), placed: d.members, match: d.match, routing: d.routing, pick: d.pick || "", affinity: d.affinity, sink: d.sink === "sink" && sinkable(d.routing), noSink: d.sink === "", firstToken: d.firstToken || 0, patience: d.patience || 0, rules: d.rules, effort: d.effort, classifier: d.rules.some((r) => r.intent) || d.effort === "auto" ? d.classifier : "", intentSure: d.intentSure ?? null, context: d.context || 0, levels: own ? d.levels : [], family: g?.family || "", fast: d.fast.filter((x) => d.members.includes(x)), ultra: d.ultra.filter((x) => d.fast.includes(x) && d.members.includes(x)), off: d.off.filter((x) => d.members.includes(x)), weights: Object.fromEntries(Object.entries(d.weights).filter(([x, n]) => d.members.includes(x) && n > 1)), effortMaps: Object.fromEntries(Object.entries(d.effortMaps).filter(([x, m]) => d.members.includes(x) && Object.keys(m).length)), accounts: d.accounts.filter((a) => accountPids().includes(a.slice(0, a.indexOf("/")))), keys: d.keys, redact: d.redact || "follow", unlists: !!d.unlists }, t(g ? "{name} saved" : "{name} added", { name: d.name.trim() || idOf() })) + groupAction("save", { id: idOf(), from: g?.id, name: d.name.trim() || idOf(), note: (d.note || "").trim(), members: namedOf(d), placed: d.members, match: d.match, routing: d.routing, pick: d.pick || "", affinity: d.affinity, sink: d.sink === "sink" && sinkable(d.routing), noSink: d.sink === "", firstToken: d.firstToken || 0, patience: d.patience || 0, rules: d.rules, effort: d.effort, classifier: d.rules.some((r) => r.intent) || d.effort === "auto" ? d.classifier : "", intentSure: d.intentSure ?? null, context: d.context || 0, compact: d.compact || 0, levels: own ? d.levels : [], family: g?.family || "", fast: d.fast.filter((x) => d.members.includes(x)), ultra: d.ultra.filter((x) => d.fast.includes(x) && d.members.includes(x)), off: d.off.filter((x) => d.members.includes(x)), weights: Object.fromEntries(Object.entries(d.weights).filter(([x, n]) => d.members.includes(x) && n > 1)), effortMaps: Object.fromEntries(Object.entries(d.effortMaps).filter(([x, m]) => d.members.includes(x) && Object.keys(m).length)), accounts: d.accounts.filter((a) => accountPids().includes(a.slice(0, a.indexOf("/")))), keys: d.keys, redact: d.redact || "follow", unlists: !!d.unlists }, t(g ? "{name} saved" : "{name} added", { name: d.name.trim() || idOf() })) .then(() => saveBtn.classList.remove("busy")); }; // what goes wrong is said where it is seen, never a click that does nothing diff --git a/internal/gui/assets/plugins/routing/routing.css b/internal/gui/assets/plugins/routing/routing.css index 5bbbf672c..9f686e304 100644 --- a/internal/gui/assets/plugins/routing/routing.css +++ b/internal/gui/assets/plugins/routing/routing.css @@ -718,6 +718,7 @@ body.window .rt-gedit > .bar { --vfoot: 8px; } .rt-gedit .gsuffix { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 8px; } .rt-gedit .gsuffix .hint { overflow-wrap: anywhere; } .rt-gedit .ctx-wrap input.ctx-in { width: 96px; flex: none; } +.rt-gedit input.cmp-in { width: 96px; flex: none; } .rt-gedit .ctx-wrap input.first-in { width: 64px; } .rt-gedit .ctx-wrap .first-unit { margin-left: -2px; color: var(--muted); font-size: 12px; } .rt-gedit .ctx-wrap .first-unit[hidden] { display: none; } diff --git a/internal/gui/settings_keep_test.go b/internal/gui/settings_keep_test.go index 92ec7420d..d0648358e 100644 --- a/internal/gui/settings_keep_test.go +++ b/internal/gui/settings_keep_test.go @@ -131,6 +131,7 @@ func TestSettingsSaveKeepsWhatItDoesNotSend(t *testing.T) { ModelCompacts: map[string]int{"p/*": 500000}, CompactAt: 400000, AgentCompacts: map[string]settings.AgentCompact{"claude": {At: 600000}}, + AgentContexts: map[string]map[string]int{"dsh": {"p/m": 400000}}, ModelPrices: map[string]settings.ModelPrice{"p/m": {Input: &one, Output: &two}}, ModelWires: map[string]string{"p/m": "vendor-c/m"}, ModelAPIs: map[string]string{"p/m": "anthropic"}, diff --git a/internal/gui/tests/agent-prefs.test.cjs b/internal/gui/tests/agent-prefs.test.cjs index 2ae0c64c3..30335b201 100644 --- a/internal/gui/tests/agent-prefs.test.cjs +++ b/internal/gui/tests/agent-prefs.test.cjs @@ -178,7 +178,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", const line = page.locator('.row.agent[data-id="codex"] .agent-prefs-open'); await line.waitFor(); assert.equal(await line.getAttribute("aria-label"), w.sheet); - assert.equal(await page.locator('.row.agent[data-id="pi"] .agent-prefs-open').count(), 0, "Pi has none"); + assert.equal(await page.locator('.row.agent[data-id="pi"] .agent-prefs-open').count(), 1, "Pi has one, for its own context window only"); await noSideScroll(page, `${lang} panel`); await line.click(); await sheet(page).waitFor(); diff --git a/internal/gui/tests/agent-window.test.cjs b/internal/gui/tests/agent-window.test.cjs new file mode 100644 index 000000000..21efa2220 --- /dev/null +++ b/internal/gui/tests/agent-window.test.cjs @@ -0,0 +1,114 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// An agent's own context windows (ul3140773077392 on X: dsh compacts earlier +// than the other agents at the same window). Any agent with models has, in +// its sheet, "Context window": empty follows each model's own +// window; a size or model=size pairs post settings/agent-contexts for that +// agent alone, never the general preferences. A bad size is refused and +// sends nothing, the row fits a narrow window, there is no native select. +// Chromium and WebKit, every language, wide and narrow; 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, agentRow, openAgentSettings } = require("./reader.cjs"); + +const assets = path.resolve(__dirname, "../assets"); + +function serve(lang, posts) { + let settings = { 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, compactAt: 400000 }; + 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:${JSON.stringify(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: [agentRow("dsh", "Dsh"), agentRow("codex", "Codex")], profiles: [], settings: { lang, theme: "light" } }); + if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true } }); + if (url.pathname === "/api/groups") return json({ groups: [], models: [] }); + if (url.pathname === "/api/settings/agent-contexts") { + const body = req.postDataJSON(); + posts.push({ path: url.pathname, body }); + const own = { ...(settings.agentContexts || {}) }; + if (Object.keys(body.contexts).length) own[body.agent] = body.contexts; + else delete own[body.agent]; + settings = { ...settings, agentContexts: own }; + return json(settings); + } + if (url.pathname === "/api/settings") { + if (req.method() === "POST") posts.push({ path: url.pathname, body: req.postDataJSON() }); + return json(settings); + } + if (url.pathname === "/api/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/usage/quotas") return json([]); + if (url.pathname.startsWith("/api/")) return json({}); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + try { + await route.fulfill({ body: await fs.readFile(file), contentType: { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)] }); + } catch { + await route.fulfill({ status: 404, body: "" }); + } + }; +} + +const words = { + en: { name: (a) => "Context window", bad: "Context window: lots is not a length like 128k or 1m" }, + zh: { name: (a) => "上下文窗口", bad: "上下文窗口:lots 不是 128k、1m 这样的长度" }, + "zh-TW": { name: (a) => "上下文視窗", bad: "上下文視窗:lots 不是 128k、1m 這樣的長度" }, + ja: { name: (a) => "コンテキストウィンドウ", bad: "コンテキストウィンドウ:lots は 128k や 1m のような長さではありません" }, + de: { name: (a) => "Kontextfenster", bad: "Kontextfenster: lots ist keine Länge wie 128k oder 1m" }, +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of Object.keys(words)) { + for (const width of [900, 420]) { + const w = words[lang]; + test(`${engine} ${lang} ${width}px: an agent sets its own context window`, 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, height: 760 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = [], posts = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang, posts)); + await watchSettingsReads(page); + await page.goto("http://magpie.test/?view=agents"); + await openAgentSettings(page, "dsh"); + const row = page.locator('.agent-window[data-agent="dsh"]'); + await row.waitFor(); + assert.equal(await row.locator(".name").textContent(), w.name("Dsh")); + assert.equal(await row.locator("select").count(), 0, "no native select"); + const num = row.locator("input.window-in"); + assert.equal(await num.inputValue(), "", "empty while it follows each model's own window"); + const view = () => page.locator("#view-agents").evaluate((v) => v.scrollTop); + const before = await view(); + await num.fill("500k"); + await num.press("Enter"); + await page.waitForFunction(() => document.querySelector(".agent-window input")?.value === "500k"); + assert.deepEqual(posts.map((p) => [p.path, p.body]), [["/api/settings/agent-contexts", { agent: "dsh", contexts: { "*": 500000 } }]]); + await num.fill("relay/m1=1m, 300k"); + await num.press("Enter"); + await page.waitForFunction(() => document.querySelector(".agent-window input")?.value.includes("relay/m1")); + assert.deepEqual(posts.at(-1).body, { agent: "dsh", contexts: { "relay/m1": 1000000, "*": 300000 } }); + assert(!posts.some((p) => p.path === "/api/settings"), "set on its own, not with the other preferences"); + assert.equal(await view(), before, "the row scrolled the page"); + // a size that isn't one is refused, nothing sent + const sent = posts.length; + await num.fill("lots"); + await num.press("Enter"); + await page.getByText(w.bad).waitFor(); + assert.equal(posts.length, sent, "a bad size sent nothing"); + // emptied, the agent follows each model's window again + await num.fill(""); + await num.press("Enter"); + await page.waitForFunction(() => document.querySelector(".agent-window input")?.value === ""); + assert.deepEqual(posts.at(-1).body, { agent: "dsh", contexts: {} }); + // every agent has one, its own + await page.locator('.row.agent[data-id="codex"] .ag-link').scrollIntoViewIfNeeded(); + const over = await row.evaluate((r) => r.scrollWidth - r.clientWidth); + assert(over <= 1, `the row overflows by ${over}px`); + assert.deepEqual(errors, []); + }); + } + } +} diff --git a/internal/gui/tests/group-compact.test.cjs b/internal/gui/tests/group-compact.test.cjs new file mode 100644 index 000000000..5af960243 --- /dev/null +++ b/internal/gui/tests/group-compact.test.cjs @@ -0,0 +1,122 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A routing group carries its own auto-compaction size (NovaStudiosss on X: +// no need to set a context size and a compaction size on each provider +// model). The group editor's Advanced "Compact at" box takes 160k or 1m; +// empty is none (0, the members' own). It is saved with the group and a +// bad length is marked as it is typed. English, Chinese, Traditional +// Chinese, Japanese and German, Chromium and WebKit. +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"); +// the rows a group's editor folds under Advanced, opened +const openAdvanced = async (page) => { + const d = page.locator(".rt-gedit .rt-gadv"); + await d.waitFor({ state: "attached" }); + if (!(await d.evaluate((e) => e.open))) await d.locator(":scope > summary").click(); +}; + +const assets = path.resolve(__dirname, "../assets"); +const models = [ + { id: "oa/gpt-6.1-sol", name: "gpt-6.1-sol", providerName: "OpenAI", icon: "generic", context: 1000000 }, + { id: "an/claude-opus-5-5", name: "claude-opus-5-5", providerName: "Anthropic", icon: "generic", context: 200000 }, + { id: "ds/deepseek-flash", name: "deepseek-flash", providerName: "DeepSeek", icon: "generic", context: 128000 }, +]; +const members = models.map((m) => m.id); +const saved = { context: 0, compact: 0 }; +const groups = () => ({ + models, pools: [], + groups: [{ id: "sol", name: "Sol", members, routing: "order", ready: true, context: saved.context, compact: saved.compact, + memberInfo: members.map((id) => ({ id, ready: true })) }], +}); + +const words = { + en: { edit: "Edit", save: "Save", label: "Compact at" }, + zh: { edit: "编辑", save: "保存", label: "压缩阈值" }, + "zh-TW": { edit: "編輯", save: "儲存", label: "壓縮閾值" }, + ja: { edit: "編集", save: "保存", label: "圧縮しきい値" }, + de: { edit: "Bearbeiten", save: "Speichern", label: "Komprimieren ab" }, +}; + +function serve(lang, posts) { + const state = { agents: [{ id: "codex", name: "Codex", path: "/test/codex", fields: [] }], profiles: [], settings: { lang, theme: "light" } }; + 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/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/gateway/trace") { + if (url.searchParams.get("wait")) return new Promise(() => {}); + return json({ mine: true, now: new Date().toISOString(), seq: 1, totals: { requests: 0, rerouted: 0, errors: 0 }, routes: [] }); + } + if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] }); + if (url.pathname === "/api/groups") return json(groups()); + if (url.pathname.startsWith("/api/groups/")) { + const body = JSON.parse(r.request().postData() || "{}"); + posts.push({ path: url.pathname, body }); + saved.context = body.context || 0; + saved.compact = body.compact || 0; + return json(groups()); + } + 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 }); + }; +} + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of Object.keys(words)) { + const w = words[lang]; + test(`${engine} ${lang}: a group carries its own Compact at`, async (t) => { + saved.context = 0; + saved.compact = 0; + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + const page = await (await browser.newContext({ viewport: { width: 1100, height: 2000 }, reducedMotion: "reduce" })).newPage(); + t.after(() => browser.close()); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = [], posts = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang, posts)); + await page.goto("http://magpie.test/?view=groups"); + const card = page.locator(".rt-group", { hasText: "Sol" }); + await card.waitFor(); + const ed = page.locator(".rt-gedit"); + const box = ed.locator("input.cmp-in"); + const save = async () => { + await ed.locator("button.primary", { hasText: w.save }).click(); + await page.waitForFunction(() => !document.querySelector(".rt-gedit")); + return posts.filter((p) => p.path === "/api/groups/save").at(-1).body; + }; + const open = async () => { await card.locator("button", { hasText: w.edit }).click(); await openAdvanced(page); await box.waitFor(); }; + + await open(); + assert.equal(await box.getAttribute("aria-label"), w.label); + assert.equal(await box.inputValue(), "", "none until set"); + assert.equal((await save()).compact, 0); + + await open(); + await box.fill("abc"); + assert.equal(await box.getAttribute("aria-invalid"), "true"); + await box.fill("160k"); + assert.equal(await box.getAttribute("aria-invalid"), "false"); + assert.equal((await save()).compact, 160000); + + await card.locator("button", { hasText: w.edit }).click(); + await box.waitFor(); + assert.equal(await box.inputValue(), "160k", "the editor opens at what was saved"); + assert(await ed.locator(".rt-gadv").evaluate((e) => e.open), "a set size opens Advanced"); + await box.fill(""); + assert.equal((await save()).compact, 0, "emptied, the group has none"); + + const missing = await page.evaluate(() => ["Compact at", "Default"].filter((k) => !I18N.zh[k])); + assert.deepEqual(missing, [], "every string has its Chinese"); + assert.deepEqual(errors, []); + }); + } +} diff --git a/internal/gui/tests/old-webkit.test.cjs b/internal/gui/tests/old-webkit.test.cjs index 99b4e26d1..25ff4bce9 100644 --- a/internal/gui/tests/old-webkit.test.cjs +++ b/internal/gui/tests/old-webkit.test.cjs @@ -178,7 +178,7 @@ test("compat.js is the first of the page's own scripts", async () => { // pipecheck.js when Settings draws Models; // the checks above // still read them - for (const f of await scripts()) if (!["webfonts.js", "cfgblocked.js", "signsheets.js", "ruleedit.js", "ratewindows.js", "traywindows.js", "autoresetown.js", "registry.js", "navlamp.js", "whatsnew.js", "claudemode.js", "ctxtext.js", "resetask.js", "quotaall.js", "quotatable.js", "quitask.js", "checkinnow.js", "proxies.js", "autobackup.js", "scrollends.js", "profilerename.js", "settingshints.js", "keyspend.js", "syncfiles.js", "agentcompact.js", "balfound.js", "passerrors.js", "tlscerts.js", "keybalance.js", "modellimits.js", "notices.js", "videogen.js", "provlinks.js", "setfeats.js", "pageshare.js", "panelfirst.js", "panelarrange.js", "modelfind.js", "agentsmanager.js", "agentsuffix.js", "phonetabs.js", "pluginmd.js", "bark.js", "acctexport.js", "plugincounts.js", "navicons.js", "autoswitchtip.js", "codexprojects.js", "pipecheck.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html"); + for (const f of await scripts()) if (!["webfonts.js", "cfgblocked.js", "signsheets.js", "ruleedit.js", "ratewindows.js", "traywindows.js", "autoresetown.js", "registry.js", "navlamp.js", "whatsnew.js", "claudemode.js", "ctxtext.js", "resetask.js", "quotaall.js", "quotatable.js", "quitask.js", "checkinnow.js", "proxies.js", "autobackup.js", "scrollends.js", "profilerename.js", "settingshints.js", "keyspend.js", "syncfiles.js", "agentcompact.js", "agentwindow.js", "balfound.js", "passerrors.js", "tlscerts.js", "keybalance.js", "modellimits.js", "notices.js", "videogen.js", "provlinks.js", "setfeats.js", "pageshare.js", "panelfirst.js", "panelarrange.js", "modelfind.js", "agentsmanager.js", "agentsuffix.js", "phonetabs.js", "pluginmd.js", "bark.js", "acctexport.js", "plugincounts.js", "navicons.js", "autoswitchtip.js", "codexprojects.js", "pipecheck.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html"); }); test("the styles hold up in Safari 15.0", async () => { diff --git a/internal/provider/agentwindow.go b/internal/provider/agentwindow.go new file mode 100644 index 000000000..abf0d7a45 --- /dev/null +++ b/internal/provider/agentwindow.go @@ -0,0 +1,115 @@ +package provider + +import ( + "errors" + "maps" + "slices" + "strings" + + "github.com/yetone/magpie/internal/catalog" + "github.com/yetone/magpie/internal/settings" +) + +// The window an agent is told for a model, when it is not the model's own +// for every agent (settings.AgentContexts, ul3140773077392 on X): agents +// compact by different rules (dsh at the smaller of 80% of the window and +// window - max tokens - 64K, Codex at its 272K), so one window fits some +// and has others compact too early. An agent's entry comes before the +// provider's and the group's own size, and is a window the user typed +// (Entry.WindowSet): Codex and Claude Code are then told it whole. + +// agentKey is the id an agent's windows are kept under. +func agentKey(agent string) string { return strings.ToLower(strings.TrimSpace(agent)) } + +// agentWindow is the window agent was given for e, and whether it has one. +// The most specific key wins: the model as the catalog has it, its +// provider's "*", the bare model id, then "*" for all, which only shortens +// a window that is known (as a provider's "*" does). +func agentWindow(own map[string]int, e Entry) (int, bool) { + if len(own) == 0 { + return 0, false + } + if n := own[e.ID]; n > 0 { + return n, true + } + if e.Group == "" { + if n := own[e.Provider.ID+"/*"]; n > 0 { + return n, true + } + if n := own[e.Model]; n > 0 { + return n, true + } + } + if n := own["*"]; n > 0 && e.Context > 0 && n < e.Context { + return n, true + } + return 0, false +} + +// withAgentWindows gives the entries the windows agent was set. +func withAgentWindows(s settings.Settings, agent string, es []Entry) []Entry { + own := s.AgentContexts[agentKey(agent)] + if len(own) == 0 { + return es + } + // copied: the list may be the catalog's own, which other agents read + es = slices.Clone(es) + for i := range es { + if n, ok := agentWindow(own, es[i]); ok { + es[i].Context, es[i].WindowSet = n, true + } + } + return es +} + +// AgentContexts are the windows agent (its list id, Agent.ListsFor) was set. +func AgentContexts(agent string) map[string]int { + return maps.Clone(settings.Load().AgentContexts[agentKey(agent)]) +} + +// SetAgentContexts gives agent the windows in cs, replacing those it had; +// none takes them away, and it is told each model's own again. A key is a +// model as the catalog has it ("provider/model", "group/"), a provider's +// "provider/*", a bare model id or "*". The agents are told when it changes. +func SetAgentContexts(agent string, cs map[string]int) error { + agent = agentKey(agent) + if agent == "" { + return errors.New("no agent") + } + clean := map[string]int{} + for k, n := range cs { + k = strings.TrimPrefix(strings.TrimSpace(k), "magpie/") + switch { + case n < 0: + return errorf("a context window is a number of tokens, not %d", n) + case n == 0: + case k == "": + return errors.New("a context window needs a model, provider/* or * to hold for") + default: + clean[k] = n + } + } + s := settings.Load() + if maps.Equal(s.AgentContexts[agent], clean) || len(clean) == 0 && len(s.AgentContexts[agent]) == 0 { + return nil + } + s.AgentContexts = maps.Clone(s.AgentContexts) + if len(clean) == 0 { + delete(s.AgentContexts, agent) + } else { + if s.AgentContexts == nil { + s.AgentContexts = map[string]map[string]int{} + } + s.AgentContexts[agent] = clean + } + if err := settings.Save(s); err != nil { + return err + } + catalog.Touched() + return nil +} + +// AgentContextAgents are the agents that have a window of their own, sorted. +func AgentContextAgents() []string { + return slices.Sorted(maps.Keys(settings.Load().AgentContexts)) +} diff --git a/internal/provider/agentwindow_test.go b/internal/provider/agentwindow_test.go new file mode 100644 index 000000000..94e602de1 --- /dev/null +++ b/internal/provider/agentwindow_test.go @@ -0,0 +1,137 @@ +package provider + +import ( + "testing" + + "github.com/yetone/magpie/internal/settings" +) + +// The window an agent is told for a model can be its own (ul3140773077392 +// on X: dsh compacts earlier than the other agents at the same window). +// An agent's entry comes before the provider's own window, is a window the +// user typed (so Codex compacts at all of it), leaves every other agent +// alone, "*" only shortens a window that is known, and taking it away +// gives the model's own again. +func TestAgentOwnContextWindow(t *testing.T) { + isolate(t) + limitsHome(t) + if err := Save(Provider{ID: "relay", Name: "Relay", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"m1", "m2"}, Contexts: map[string]int{"m1": 200000, "m2": 100000}}); err != nil { + t.Fatal(err) + } + if err := SetAutoGroups(false); err != nil { + t.Fatal(err) + } + if err := SaveGroup(Group{ID: "mix", Name: "mix", Members: []string{"relay/m1", "relay/m2"}}); err != nil { + t.Fatal(err) + } + window := func(agent, id string) (int, bool) { + shown, _ := CatalogFor(agent) + for _, e := range shown { + if e.ID == id { + return e.Context, e.WindowSet + } + } + t.Fatalf("%s: no %s in %v", agent, id, ids(shown)) + return 0, false + } + if n, set := window("dsh", "relay/m1"); n != 200000 || !set { + t.Fatalf("to begin with: %d %v", n, set) + } + if err := SetAgentContexts("dsh", map[string]int{"relay/m1": 500000, "*": 150000}); err != nil { + t.Fatal(err) + } + for _, c := range []struct { + agent, id string + n int + set bool + }{ + {"dsh", "relay/m1", 500000, true}, // its own entry, even past the model's + {"dsh", "relay/m2", 100000, true}, // "*" only shortens: m2's 100K is shorter than 150K + {"codex", "relay/m1", 200000, true}, // the others keep what the provider says + {"pi", "relay/m2", 100000, true}, + } { + if n, set := window(c.agent, c.id); n != c.n || set != c.set { + t.Errorf("%s %s: %d %v; want %d %v", c.agent, c.id, n, set, c.n, c.set) + } + } + // "*" shortens a window that is longer than it + if err := SetAgentContexts("dsh", map[string]int{"*": 150000}); err != nil { + t.Fatal(err) + } + if n, set := window("dsh", "relay/m1"); n != 150000 || !set { + t.Errorf("* on a longer window: %d %v", n, set) + } + // a provider's, and a group's own entry + if err := SetAgentContexts("dsh", map[string]int{"relay/*": 64000, "group/mix": 90000}); err != nil { + t.Fatal(err) + } + if n, _ := window("dsh", "relay/m2"); n != 64000 { + t.Errorf("provider/*: %d", n) + } + if n, set := window("dsh", "group/mix"); n != 90000 || !set { + t.Errorf("the group: %d %v", n, set) + } + // the window typed is what Codex-style readers compact at + shown, _ := CatalogFor("dsh") + s := settings.Load() + for _, e := range shown { + if e.ID == "relay/m1" { + if got := CompactFor(s, e, GroupFinder()); got != 64000 { + t.Errorf("compacts at %d; want the whole window, 64000", got) + } + } + } + if err := SetAgentContexts("dsh", map[string]int{"relay/m1": -1}); err == nil { + t.Error("a negative window was accepted") + } + if err := SetAgentContexts("dsh", nil); err != nil { + t.Fatal(err) + } + if n, set := window("dsh", "relay/m1"); n != 200000 || !set { + t.Errorf("taken away: %d %v", n, set) + } + if got := settings.Load().AgentContexts; len(got) != 0 { + t.Errorf("kept %v", got) + } +} + +// A routing group carries its own compaction size (NovaStudiosss on X): it +// is where agents compact on the group, before the smallest its members +// say, and with none set nothing changes. +func TestGroupOwnCompactAt(t *testing.T) { + isolate(t) + limitsHome(t) + if err := Save(Provider{ID: "relay", Name: "Relay", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"m1", "m2"}}); err != nil { + t.Fatal(err) + } + if err := SetModelCompacts("relay", map[string]int{"m1": 250000, "m2": 300000}); err != nil { + t.Fatal(err) + } + if err := SetAutoGroups(false); err != nil { + t.Fatal(err) + } + if err := SaveGroup(Group{ID: "mix", Name: "mix", Members: []string{"relay/m1", "relay/m2"}}); err != nil { + t.Fatal(err) + } + if got := CompactSet("group/mix"); got != 250000 { + t.Errorf("none of its own: %d; want its smallest member's", got) + } + if err := SaveGroup(Group{ID: "mix", Name: "mix", Members: []string{"relay/m1", "relay/m2"}, Compact: 160000}); err != nil { + t.Fatal(err) + } + if got := CompactSet("group/mix"); got != 160000 { + t.Errorf("its own: %d", got) + } + if err := SetModelCompacts("relay", nil); err != nil { + t.Fatal(err) + } + if got := CompactSet("group/mix"); got != 160000 { + t.Errorf("its own with no model set: %d", got) + } + if err := SaveGroup(Group{ID: "mix", Name: "mix", Members: []string{"relay/m1"}, Compact: -5}); err != nil { + t.Fatal(err) + } + if g, _, ok := FindGroup(GroupPrefix + "mix"); !ok || g.Compact != 0 { + t.Errorf("a negative size was kept: %+v", g) + } +} diff --git a/internal/provider/compact.go b/internal/provider/compact.go index cbbc3813f..1bd9d22d1 100644 --- a/internal/provider/compact.go +++ b/internal/provider/compact.go @@ -129,12 +129,16 @@ func catalogID(id string) string { } func compactSet(s settings.Settings, id string, find func(string) (Group, []Member, bool)) int { - if len(s.ModelCompacts) == 0 { - return 0 - } id = catalogID(id) if strings.HasPrefix(id, GroupPrefix) { - _, ms, _ := find(id) + g, ms, _ := find(id) + // the group's own, before what its members say + if g.Compact > 0 { + return g.Compact + } + if len(s.ModelCompacts) == 0 { + return 0 + } least := 0 for _, m := range ms { if n := compactOf(s, m.Provider.ID, entryModel(m)); n > 0 && (least == 0 || n < least) { @@ -143,6 +147,9 @@ func compactSet(s settings.Settings, id string, find func(string) (Group, []Memb } return least } + if len(s.ModelCompacts) == 0 { + return 0 + } pid, model, ok := strings.Cut(id, "/") if !ok { return 0 diff --git a/internal/provider/group.go b/internal/provider/group.go index 2890c860b..16b1ac11f 100644 --- a/internal/provider/group.go +++ b/internal/provider/group.go @@ -284,6 +284,12 @@ type Group struct { // as the members change (Mikan on Discord), so the agent compacts // before any member would turn the conversation away. Context int `json:"context,omitempty"` + // Compact is where Codex and Claude Code compact a conversation on the + // group, in tokens (NovaStudiosss on X): over what its members' own + // thresholds (settings.ModelCompacts) and Long conversations say, so a + // group carries both its window (Context) and its compaction and no + // provider needs either set for it. 0 leaves it to those. + Compact int `json:"compact,omitempty"` // Levels are the reasoning levels agents are offered for the group, // lowest first, when the user names them (#295): rather than those // every member has, so that a member with few doesn't take the rest @@ -1813,6 +1819,7 @@ func SaveGroup(g Group) error { if g.Context < 0 { g.Context = ContextSmallest } + g.Compact = max(g.Compact, 0) // the members it names and its patterns, without what the patterns // matched when it was read: those are found again below, and stored // never diff --git a/internal/provider/visible.go b/internal/provider/visible.go index 123ebaff3..c00032ac3 100644 --- a/internal/provider/visible.go +++ b/internal/provider/visible.go @@ -99,6 +99,8 @@ func catalogFor(agent string) (shown, hidden []Entry) { shown = append(shown, e) } } + // the windows the user set for this agent alone (settings.AgentContexts) + shown = withAgentWindows(heldSettings(), agent, shown) return shown, hidden } diff --git a/internal/settings/settings.go b/internal/settings/settings.go index 39c830360..786eff3c5 100644 --- a/internal/settings/settings.go +++ b/internal/settings/settings.go @@ -915,6 +915,16 @@ type Settings struct { // (molianyin4227 on Discord: models differ, so one size for every // agent fits none). An agent with none follows those two (ForAgent). AgentCompacts map[string]AgentCompact `json:"agentCompacts,omitempty"` + // AgentContexts is the context window an agent is told for a model, when + // it is not the one every agent is told (ul3140773077392 on X: dsh + // compacts earlier than Codex does at the same window, so its window + // wants setting apart). By the agent's list id (Agent.ListsFor), then + // the model as the catalog has it ("provider/model", or "group/"), + // "provider/*" for every model of a provider, a bare model id for that + // model at any provider, and "*" for all of them (which only shortens a + // window, as a provider's "*" does). An agent with none is told the + // model's own, or a group's. + AgentContexts map[string]map[string]int `json:"agentContexts,omitempty"` // CodexAsyncCompact has Codex (0.163 on) compact a long conversation // in the background, while its turn goes on, once it is past // CodexAsyncCompactPercent of the model's window (#2490, lantern2077 diff --git a/internal/settingsapi/settingsapi.go b/internal/settingsapi/settingsapi.go index 2cdc8792c..c262505ed 100644 --- a/internal/settingsapi/settingsapi.go +++ b/internal/settingsapi/settingsapi.go @@ -351,6 +351,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.AgentContexts = cur.AgentContexts // and the windows each is told (agent-contexts) in.ContextCap = cur.ContextCap // and the longest window of every model (context-cap) in.ContextCapAll = cur.ContextCapAll // and whether it holds the user's own windows // Codex's background compaction, set on its own (codex-async-compact)