settings: Codex, Claude Code and Grok Build each take a Long conversations of their own (molianyin4227 on Discord)

molianyin4227 (Discord #help): models differ, so one compaction size
for every agent fits none; they asked for Codex, Claude Code and Grok
Build to each have their own, falling back to the shared one.

- settings.AgentCompacts[agent] {At, Full} for the agents that write a
  compaction window (CompactAgents: codex, claude, grok); Settings.
  ForAgent(agent) lays it over CompactAt/FullContext for that agent's
  readers only: codexcat.entriesAt, provider codexListed, Claude Code's
  writeCompact and desktopPlan, grokModelTables, the route list's
  buildModels, Codex's window line (api.go) and Tuned for you
  (gui/tune.go, agent/tune.go). A model's or provider's own Compact at
  still comes first. An agent with none follows the shared value, so
  nothing new is written for it, and an agent outside the three has no
  such key and is refused (provider.SetAgentCompact).
- POST /api/settings/agent-compact {agent, own, full, at}; own false
  takes the agent's value away. settingsapi.Merge keeps the map.
- GUI: a row "Long conversations in <agent>" under Long conversations,
  in the agent's opened row and its sheet: Every agent / Compact at N /
  Full window (segs, no select), a size box when Compact at. It lives in
  agentcompact.js, imported when the agent's settings hold Long
  conversations, then put in synchronously (an async put-in after a
  redraw moved the page in chromium: codex-memories-settings' scroll
  check). It draws again only when its own values change. i18n in
  zh, zh-TW, ja, de.
- Tuned for you's Use on an agent with its own value changes that one,
  stashed under tune.long.compact.<agent>; Undo puts it back.
- codex-memories-settings' "no Codex" check counts Long conversations
  alone again (:not(.agent-compact)) and waits for the new row.
- docs/subsystems/agent-wiring.md: a row for it.

Core size: app.js 1,311,919 bytes, 109 under origin/main 0ee424e3e
(1,312,028): the two calls are paid for by four comments cut. The core
total is 1,534,045, still over its budget as on main (#5139), 109 less
than main's 1,534,154. No budget raised.

Run at this tree (based on origin/main 0ee424e3e, fetched just before
the commit), all on mote via mote-run:
- go test settings, settingsapi, codexcat; provider/agent/gui with
  -run "Compact|Tune|Grok|SettingsSave|CodexWindow|Long": ok.
- New tests broken by hand, each red: ForAgent taken out of codexcat
  (TestCodexCatalogCompactAt), grok.go (TestGrokWindowFollowsLong
  Conversations), claude.go (TestClaudeCompactAt); tune's per-agent key
  turned off (TestTuneAgentOwnLong: "after apply: codex {At:0
  Full:true}"); the row's import call taken out of app.js
  (agent-compact.test.cjs 4 of 4 red in chromium).
- GUI, chromium + webkit (en/zh/zh-TW/ja/de as each file has, narrow
  and wide): agent-compact, agent-prefs, compact-at, compact-one-value,
  settings-general, codex-async-compact, codex-compact-held,
  codex-memories-settings, context-tune, segs-glide, i18n-keys,
  old-webkit: 432 of 432 ok.
- gofmt -l clean; go vet darwin and GOOS=windows on mote, linux with
  -tags gtk3 on magpie-desktop (wsl-run): ok.
- TestCoreScriptBudget: red, 1,534,045 > 1,533,802, as on main (#5139),
  109 bytes lower than main.

Not tried: real Codex, Claude Code or Grok Build reading the values
(the config writers are unit-tested); the full go test ./... (after
the push). `magpie model compact` has no per-agent flag, and t3code's
route list reads the shared value.
This commit is contained in:
yetone
2026-11-04 16:17:47 +08:00
parent 0ee424e3ee
commit 3eb2bda4f2
24 changed files with 506 additions and 49 deletions
+1
View File
@@ -24,6 +24,7 @@ something else shows up as drift.
| Restarting a desktop app | Claude Desktop and WorkBuddy (WorkBuddy AI on macOS) read magpie's settings only as they start (微雨南山 and stones on Discord). `AppBehind` names one running here that started more than a second before magpie last changed what it reads (`changedAt`, which puts a change no file's time shows, such as Claude Desktop's gateway model list, at when it is first seen); only for an agent connected in magpie or disconnected in it. The row's Restart asks first in magpie's own dialog (`confirmRestart`), then `POST /api/agents/restart/{id}` runs `RestartApp`. On macOS (`restartApps`, the bundle found by id under `appFolders`, its `CFBundleExecutable` matched in `pgrep`) it quits as ⌘Q does and waits for every process of the bundle (`reopenBundle`), but a script run on the app's own executable (`runsScript`: a `.js` argument or an absolute path as its first argument), which the running check skips too. WorkBuddy starts its sidecar (`sidecar-entry.js`) and its `codebuddy` CLIs that way, detached; the sidecar outlives a quit, so counting it kept the row behind after every restart and made Restart wait it out and never open the app (Northes on Discord, 11-04, #3700). On Windows the same check reads each process's command line (`proc.CommandLine`); one still open after `appQuitWait` (a "Save?" question) is left as it is and not opened again (`noticeRestartStillOpen`). On Windows (`claude.exe` under `AnthropicClaude` or its Store package, `WorkBuddy.exe` outside the WorkBuddy AI folder) its processes are asked to close (`taskkill` without `/F`); one that has hidden every window and still runs after `appTrayGrace` (1s) is in the tray and has its tree ended at once (`waitClosed`, `winShown`: Claude Desktop hides its window in ~0.6s and keeps all its processes, so waiting the whole `appCloseWait` made a Restart ~12s where quitting by hand takes ~2s, CyberCaius on Discord, 10-29); one still showing a window (a question) gets `appCloseWait` before it is ended, and it is opened again through its Store id or Squirrel's stub. The Codex app's own Restart (`ReopenCodexApp`) asks first too, then ends only the app-server that app runs for itself (`provider.RestartCodexApp`: under its bundle, never a `--listen` one), as a switch does; the app starts another and keeps its window. Quitting and opening it, as before, opened a new window (yoshi037070 on Discord, 10-27). Codex on Windows, WorkBuddy AI on Windows and Linux aren't restarted: their process names aren't known. | [`apprestart.go`](../../internal/agent/apprestart.go), [`apprestart_windows.go`](../../internal/agent/apprestart_windows.go), [`connectinfo.go`](../../internal/agent/connectinfo.go) |
| 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>`. Not covered: `magpie model compact` sets only the value for every agent, and t3code's route list reads that one. `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) |
| 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) |
| Named omp profiles | omp keeps a profile's settings under `~/.omp/profiles/<name>` (or under `PI_CONFIG_DIR`), each with its own `config.yml` and `models.yml`. Every such profile is an agent of its own — `omp#<name>` on Windows, `omp#<name>@wsl:<distro>` in a distro — so each can be connected, drifted and disconnected on its own. They share omp's model lists (`ListsFor`), and the default `omp` row is the folder `ompDir`/`ompIn` already pick, so an `OMP_PROFILE` that row is already pointed at is not listed twice. A name omp refuses is not a row: `default`, a trailing dot, or a Windows reserved device name (`aux`, `nul`, `com1`, `lpt9.x`, `con.work`), on every platform (`ompProfileOK`). A distro's profile names come from its probe and are kept in `wsl.json`; a stopped distro is never started to list them, its profile rows showing what was last seen (`asleep`). | [`omp.go`](../../internal/agent/omp.go), [`wsl.go`](../../internal/agent/wsl.go) |
+2 -2
View File
@@ -934,7 +934,7 @@ func claudeIn(at place) *Agent {
main := mainModel()
n := provider.CompactSet(main)
long := false
if s := settings.Load(); n == 0 && !claudeModel(main) && !provider.ClaudeGroup(main) {
if s := settings.Load().ForAgent("claude"); n == 0 && !claudeModel(main) && !provider.ClaudeGroup(main) {
n, long = s.Compact(), true
// magpie's default gives way to an autoCompactWindow the user
// set in Claude Code (/autocompact, its settings), which the env
@@ -1210,7 +1210,7 @@ func claudeIn(at place) *Agent {
// model's, tiers' and those /model offers (pickerRefs), each with its
// own window under the largest. A model Claude Code knows as Claude's has its own window.
desktopPlan := func(main string, tiers map[string]string) (top, def int, entries map[string]int) {
s := settings.Load()
s := settings.Load().ForAgent("claude")
// the user's own top-level autoCompactWindow
cur, userTop := edit.GetJSON(path, "autoCompactWindow")
userTop = userTop && !defaultOurs()
+17
View File
@@ -151,6 +151,23 @@ func TestClaudeCompactAt(t *testing.T) {
expect("full window, the model's own", "200000")
must(a.Field("model").Set("v/big"))
expect("full window", "")
// Claude Code's own Long conversations (molianyin4227) over every
// agent's Full window; Codex's own is not Claude Code's
must(provider.SetAgentCompact("codex", &settings.AgentCompact{At: 700000}))
must(a.Sync())
expect("codex's own", "")
must(provider.SetAgentCompact("claude", &settings.AgentCompact{At: 300000}))
must(a.Sync())
expect("claude's own 300K", "300000")
if s := tuned(); s.Value != "300000" || s.Source != TuneLong {
t.Fatalf("tune reads claude's own 300K as %+v", s)
}
must(a.Field("model").Set("v/flash"))
expect("claude's own, the model's first", "200000")
must(a.Field("model").Set("v/big"))
must(provider.SetAgentCompact("claude", nil))
must(a.Sync())
expect("back to every agent's full window", "")
}
// An auto-compact window the user set in Claude Code (autoCompactWindow,
+1 -1
View File
@@ -49,7 +49,7 @@ var grokModelTable = `model."` + magpieID + "/"
// as they set it.
func grokModelTables(v1 string, had, wrote map[string]int) ([]edit.Table, map[string]int) {
var out []edit.Table
st, gave := settings.Load(), map[string]int{}
st, gave := settings.Load().ForAgent("grok"), map[string]int{}
for _, m := range sharedModels("grok") {
kvs := []edit.KV{
{Path: "model", Value: m.ID},
+17
View File
@@ -432,4 +432,21 @@ func TestGrokWindowFollowsLongConversations(t *testing.T) {
if pro, flash := grokWindows(t, path); pro != 400000 || flash != 200000 {
t.Fatalf("pro's own threshold: pro %d, flash %d", pro, flash)
}
// Grok Build's own Long conversations (molianyin4227) over every
// agent's, a model's own still first; another agent's is not Grok's
set(func(s *settings.Settings) {
s.ModelCompacts, s.CompactAt = nil, 300000
s.AgentCompacts = map[string]settings.AgentCompact{"grok": {At: 500000}, "codex": {At: 250000}}
})
if pro, flash := grokWindows(t, path); pro != 500000 || flash != 200000 {
t.Fatalf("grok's own 500K: pro %d, flash %d", pro, flash)
}
set(func(s *settings.Settings) { s.AgentCompacts = map[string]settings.AgentCompact{"grok": {Full: true}} })
if pro, flash := grokWindows(t, path); pro != 1000000 || flash != 200000 {
t.Fatalf("grok's own full window: pro %d, flash %d", pro, flash)
}
set(func(s *settings.Settings) { s.AgentCompacts = map[string]settings.AgentCompact{"codex": {Full: true}} })
if pro, flash := grokWindows(t, path); pro != 300000 || flash != 200000 {
t.Fatalf("codex's full window reached grok: pro %d, flash %d", pro, flash)
}
}
+2 -1
View File
@@ -341,7 +341,8 @@ func buildModels(agent string) []catalog.Model {
labels := provider.Labels(shown)
// a model magpie describes images to takes them (provider.Described)
seen := describedNow()
st, find := settings.Load(), provider.GroupFinder()
// the agent's own Long conversations, if it has one (ForAgent)
st, find := settings.Load().ForAgent(agent), provider.GroupFinder()
priceOf := provider.AgentPricer(st, find)
members := func(id string) []provider.Member {
_, ms, _ := find(id)
+45 -24
View File
@@ -13,7 +13,8 @@ package agent
// sets that value, so the Usage page and the agents' settings never show
// two numbers (7eleven on Discord). Before, tune wrote Codex's
// model_auto_compact_token_limit beside it; tuneMigrateCodex moves such a
// value into Long conversations.
// value into Long conversations. An agent with a Long conversations of
// its own (settings.AgentCompacts) has tune read and set that one.
import (
"encoding/json"
@@ -71,8 +72,18 @@ type tuneLong struct {
Set int `json:"set"`
}
func tuneLongStashed() (tuneLong, bool) {
raw := stashShared()[tuneLongKey]
// longKey is where Long conversations as agent reads it is stashed: the
// one for every agent, or the agent's own (settings.AgentCompacts), which
// a Use puts the advice in instead.
func longKey(s settings.Settings, agent string) string {
if _, own := s.AgentCompacts[agent]; own {
return tuneLongKey + "." + agent
}
return tuneLongKey
}
func tuneLongStashed(key string) (tuneLong, bool) {
raw := stashShared()[key]
var st tuneLong
if raw == "" || json.Unmarshal([]byte(raw), &st) != nil {
return tuneLong{}, false
@@ -89,37 +100,48 @@ func longValue(s settings.Settings) string {
return ""
}
// longOurs says Long conversations still holds the window tune put in.
func longOurs(s settings.Settings) bool {
st, ok := tuneLongStashed()
return ok && !s.FullContext && s.Compact() == st.Set
// longOurs says Long conversations, as agent reads it, still holds the
// window tune put in.
func longOurs(s settings.Settings, agent string) bool {
st, ok := tuneLongStashed(longKey(s, agent))
a := s.ForAgent(agent)
return ok && !a.FullContext && a.Compact() == st.Set
}
// longApply puts n in Long conversations, what it was kept the first time
// for Undo. Sync then writes it into every agent magpie routes.
func longApply(n int) error {
func longApply(agent string, n int) error {
s := settings.Load()
st, ok := tuneLongStashed()
key, a := longKey(s, agent), s.ForAgent(agent)
st, ok := tuneLongStashed(key)
if !ok {
st = tuneLong{CompactAt: s.CompactAt, Full: s.FullContext}
st = tuneLong{CompactAt: a.CompactAt, Full: a.FullContext}
}
st.Set = n
b, _ := json.Marshal(st)
stash(map[string]string{tuneLongKey: string(b)})
stash(map[string]string{key: string(b)})
if key != tuneLongKey {
return provider.SetAgentCompact(agent, &settings.AgentCompact{At: n})
}
return provider.SetCompactAt(n) // Full window off too
}
// longUndo puts Long conversations back as it was before tune, unless the
// user changed it since: then it is theirs, and only forgotten.
func longUndo() error {
st, ok := tuneLongStashed()
func longUndo(agent string) error {
s := settings.Load()
key := longKey(s, agent)
st, ok := tuneLongStashed(key)
if !ok {
return fmt.Errorf("magpie didn't set Long conversations")
}
defer forget(tuneLongKey)
if !longOurs(settings.Load()) {
defer forget(key)
if !longOurs(s, agent) {
return nil
}
if key != tuneLongKey {
return provider.SetAgentCompact(agent, &settings.AgentCompact{At: st.CompactAt, Full: st.Full})
}
if st.Full {
return provider.SetFullContext(true)
}
@@ -145,9 +167,9 @@ func tuneMigrateCodex(home string) {
return
}
if n, err := strconv.Atoi(st.Set); err == nil && n > 0 {
s := settings.Load()
s := settings.Load().ForAgent("codex")
if s.CompactAt == 0 || s.FullContext || n < s.Compact() {
if err := longApply(n); err != nil {
if err := longApply("codex", n); err != nil {
return
}
}
@@ -254,7 +276,7 @@ func TuneRead(home, agent, knob, model string) (TuneSetting, error) {
return s, nil
}
st := settings.Load()
return TuneSetting{Value: longValue(st), Source: TuneLong, Ours: longOurs(st)}, nil
return TuneSetting{Value: longValue(st.ForAgent(agent)), Source: TuneLong, Ours: longOurs(st, agent)}, nil
}
var s TuneSetting
for _, k := range p.env {
@@ -262,7 +284,7 @@ func TuneRead(home, agent, knob, model string) (TuneSetting, error) {
if k == claudeCompactEnv && claudeLongEnv(p.path, v) {
// as Long conversations has it now, which Sync is writing
st := settings.Load()
return TuneSetting{Value: longValue(st), Source: TuneLong, Ours: longOurs(st)}, nil
return TuneSetting{Value: longValue(st.ForAgent(agent)), Source: TuneLong, Ours: longOurs(st, agent)}, nil
}
s.Locked = k
s.Value, s.Source = v, "env"
@@ -283,8 +305,7 @@ func TuneRead(home, agent, knob, model string) (TuneSetting, error) {
// own: magpie's Long conversations where magpie wrote it
if v, ok := edit.GetJSON(p.path, "autoCompactWindow"); ok && v != "auto" {
if claudeLongWindow(p.path, "autoCompactWindow", "claude.compact_default") {
st := settings.Load()
return TuneSetting{Value: v, Source: TuneLong, Ours: longOurs(st)}, nil
return TuneSetting{Value: v, Source: TuneLong, Ours: longOurs(settings.Load(), agent)}, nil
}
s.Value, s.Source = v, "settings"
}
@@ -316,7 +337,7 @@ func claudeLongWindow(path, key, stashKey string) bool {
if !ok || v == "" || v != stashShared()[stashKey] {
return false
}
return v == longValue(settings.Load())
return v == longValue(settings.Load().ForAgent("claude"))
}
func tuneStashed(agent, knob, model string) (tuneStash, bool) {
@@ -354,7 +375,7 @@ func TuneApply(home, agent, knob, model, value string) error {
if agent == "claude" && (n < 100000 || n > 1000000) {
return fmt.Errorf("Claude Code takes a window of 100000 to 1000000 tokens, not %d", n)
}
return longApply(n)
return longApply(agent, n)
}
var v any = value
if p.number {
@@ -397,7 +418,7 @@ func TuneUndo(home, agent, knob, model string) error {
return err
}
if cur, _ := TuneRead(home, agent, knob, model); cur.Source == TuneLong {
return longUndo()
return longUndo(agent)
}
st, ok := tuneStashed(agent, knob, model)
if !ok {
+34
View File
@@ -490,3 +490,37 @@ func TestTuneCodexAsyncOwn(t *testing.T) {
}
})
}
// TestTuneAgentOwnLong: where an agent has its own Long conversations
// (molianyin4227), its Usage card reads and sets that one, every other
// agent's left as it was, and Undo puts the agent's own back.
func TestTuneAgentOwnLong(t *testing.T) {
home := tuneSandbox(t)
tuneWrite(t, filepath.Join(home, ".codex", "config.toml"), "model = \"gpt-5.5\"\n")
if err := provider.SetCompactAt(200000); err != nil {
t.Fatal(err)
}
if err := provider.SetAgentCompact("codex", &settings.AgentCompact{Full: true}); err != nil {
t.Fatal(err)
}
if s, _ := TuneRead(home, "codex", TuneCompact, ""); s.Value != "" || s.Source != TuneLong {
t.Fatalf("read codex's own full window %+v", s)
}
if err := TuneApply(home, "codex", TuneCompact, "", "350000"); err != nil {
t.Fatal(err)
}
got := settings.Load()
if c := got.AgentCompacts["codex"]; c.At != 350000 || c.Full || got.CompactAt != 200000 || got.FullContext {
t.Fatalf("after apply: codex %+v, every agent's %d full=%v", c, got.CompactAt, got.FullContext)
}
if s, _ := TuneRead(home, "codex", TuneCompact, ""); s.Value != "350000" || !s.Ours {
t.Fatalf("read after apply %+v", s)
}
if err := TuneUndo(home, "codex", TuneCompact, ""); err != nil {
t.Fatal(err)
}
got = settings.Load()
if c, ok := got.AgentCompacts["codex"]; !ok || !c.Full || got.CompactAt != 200000 {
t.Fatalf("after undo: codex %+v %v, every agent's %d", c, ok, got.CompactAt)
}
}
+1 -1
View File
@@ -352,7 +352,7 @@ func Entries(ms []catalog.Model, after int) []any {
func entriesAt(ms []catalog.Model, after int, effort string) []any {
own := CacheEntries()
v1 := V1()
work := settings.Load()
work := settings.Load().ForAgent("codex")
autoReview := AutoReviewModel()
var entries []any
for i, m := range ms {
+21
View File
@@ -67,6 +67,27 @@ func TestCodexCatalogCompactAt(t *testing.T) {
"d/flash": {float64(1000000), float64(500000)},
"x/big": {float64(1000000), nil},
})
// Codex's own Long conversations (molianyin4227) over every agent's;
// another agent's is not Codex's
if err := settings.Save(settings.Settings{CompactAt: 400000, AgentCompacts: map[string]settings.AgentCompact{"codex": {At: 700000}, "claude": {At: 150000}}}); err != nil {
t.Fatal(err)
}
check("codex's own 700K", map[string][2]any{
"d/flash": {float64(1000000), float64(500000)},
"x/big": {float64(1000000), float64(700000)},
})
if err := settings.Save(settings.Settings{CompactAt: 400000, AgentCompacts: map[string]settings.AgentCompact{"codex": {Full: true}}}); err != nil {
t.Fatal(err)
}
check("codex's own full window", map[string][2]any{
"x/big": {float64(1000000), nil},
})
if err := settings.Save(settings.Settings{FullContext: true, AgentCompacts: map[string]settings.AgentCompact{"claude": {At: 150000}}}); err != nil {
t.Fatal(err)
}
check("claude's own, codex follows every agent's full window", map[string][2]any{
"x/big": {float64(1000000), nil},
})
}
// Codex shows a model's context_window (95% of it) as the conversation's
+23 -1
View File
@@ -781,7 +781,7 @@ func settingsState() settingsJSON {
s.CodexUsers, s.ClaudeUsers = loginUsers("codex"), loginUsers("claude")
s.CodexAsyncHeld = agent.CodexAsyncHeld()
s.CodexCompactKeys = codexKeysText(agent.CodexCompactHeld(""))
s.CodexWindow = codexWindowUnder(s.Settings, agent.CodexModel(""))
s.CodexWindow = codexWindowUnder(s.Settings.ForAgent("codex"), agent.CodexModel(""))
s.WorkBuddy, s.WorkBuddyCheckins = provider.HasWorkBuddy(), provider.WorkBuddyCheckins()
s.Trae, s.TraeCheckins = provider.HasTrae(), provider.TraeCheckins()
s.MiniMax, s.MiniMaxCheckins = provider.HasMiniMax(), provider.MiniMaxCheckins()
@@ -1663,6 +1663,28 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
}
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) {
var in struct {
Agent string
Own, Full bool
At int
}
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
fail(rw, err)
return
}
var c *settings.AgentCompact
if in.Own {
c = &settings.AgentCompact{At: in.At, Full: in.Full}
}
if err := provider.SetAgentCompact(in.Agent, c); err != nil {
fail(rw, err)
return
}
writeJSON(rw, settingsState())
})
// takes out of Codex's config the keys it reads before Long
// conversations (agent.CodexCompactHeld), on the user's click
mux.HandleFunc("POST /api/settings/codex-compact-held/drop", func(rw http.ResponseWriter, r *http.Request) {
+51
View File
@@ -0,0 +1,51 @@
// An agent's own Long conversations (molianyin4227 on Discord: models
// differ, so one size for every agent fits none): Every agent follows the
// 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 kind = kindOf(a);
const row = el("div", "row pref agent-compact");
row.dataset.agent = kind;
const who = el("div", "who"), box = el("div");
who.append(el("div", "name", t("Long conversations in {agent}", { agent: a.name })), el("div", "sub", t("Its own size, for models that differ; Every agent follows Long conversations above")));
row.append(who, box);
let drawn;
const draw = () => {
// the opened row is built before the settings are read; drawn again then,
// and only when its own values changed, so the page under it holds still
const s = prefs || {}, own = (s.agentCompacts || {})[kind];
const key = JSON.stringify([own, s.compactAt]);
if (key === drawn) return;
drawn = key;
const mode = !own ? "all" : own.full ? "full" : "at";
// a size of its own starts from the one every agent has
const at = own ? own.at || 0 : s.compactAt || 0;
const set = (body) => writingPrefs(api("settings/agent-compact", { agent: kind, ...body }))
.then((ns) => { prefs = ns; renderSettings(); if (row.isConnected) draw(); }).catch(settingsErr);
const size = contextsText({ "*": at || 272000 });
const sg = segs([["all", t("Every agent")], ["at", t("Compact at {n}", { n: size.toUpperCase() })], ["full", t("Full window")]], mode,
(v) => set(v === "all" ? { own: false } : { own: true, full: v === "full", at }));
const num = input(at && own ? size : "", "272k");
num.className = "words compact-num";
num.hidden = mode !== "at";
num.title = t("Compact at");
num.setAttribute("aria-label", t("Compact at"));
num.onchange = () => {
const r = parseContexts(num.value);
if (r.error || Object.keys(r.map).some((k) => k !== "*")) return status(t("Compact at: {v} is not a number of tokens like 272k", { v: num.value.trim() }), "err");
set({ own: true, full: false, at: r.map["*"] || 0 });
};
const line = el("div", "compact-at");
line.append(sg, num);
box.replaceChildren(line);
};
draw();
list.querySelector(".agent-compact")?.remove();
const above = list.querySelector("#fullContextRow");
above ? above.after(row) : list.append(row);
// every agent's size, in its label, changes when the row above is drawn
const seen = new MutationObserver(() => row.isConnected ? draw() : seen.disconnect());
const segsBox = document.getElementById("fullContextSegs");
if (segsBox) seen.observe(segsBox, { childList: true });
};
+8 -11
View File
@@ -2230,23 +2230,21 @@ function connectPanel(a, { fields, fieldBtn }) {
const f = a.fields.find((x) => x.key === b.dataset.key);
if (f && !b.querySelector(":scope > .k")) b.prepend(el("span", "k", t(f.label)));
}
// Cursor Private Inference's are magpie's own, its effort asked on
// every request it sends from then on, not what a new session starts
// with (#1003)
// Cursor Private Inference's are magpie's own (#1003)
kv(t(a.id === "cursor-local" ? "Settings" : "New sessions"), line(fields));
}
if (a.native) for (const [key, detail] of Object.entries(a.native.fields || {})) {
if (detail.detail) { const f = a.fields.find((x) => x.key === key); kv(t(f?.label || key), line(t(detail.detail))); }
}
if (CONNECT_COST[kindOf(a)]) kv(t("Once connected"), line(t(CONNECT_COST[kindOf(a)])));
// its own settings, the rows Settings had (agentPrefRows), here where
// the agent is; shown once they are read, so none opens on a default
// its own settings (agentPrefRows), shown once read
const own = agentPrefsOf(a);
if (own) {
const list = el("div", "list prefs ag-prefs");
homeAgentPrefRows();
list.append(...own.map((id) => $("#" + id)));
kv(t("Settings"), list);
agentCompactIn(list, own, a);
if (!prefs) {
list.hidden = true;
loadSettings().then(() => { list.hidden = false; }, statusErr);
@@ -21112,8 +21110,9 @@ const AGENT_PREFS = {
const agentPrefsOf = (a) => gatewayMode ? null : AGENT_PREFS[kindOf(a)];
const PREFS_GLYPH = "M2.75 4.75h10.5M2.75 11.25h10.5M5.75 3.25v3M10.25 9.75v3";
let agentPrefRowEls = null;
// homeAgentPrefRows puts back the rows a sheet took with it when another
// dialog replaced it, so every row is in the page to be drawn
// 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), () => {}));
// homeAgentPrefRows: the rows a sheet took back in the page
function homeAgentPrefRows() {
const box = $("#agentPrefRows");
agentPrefRowEls ||= [...box.children];
@@ -21132,6 +21131,7 @@ async function openAgentPrefs(a) {
head.append(el("b", "", t("{agent} settings", { agent: a.name })));
const list = el("div", "list prefs");
for (const id of ids) list.append($("#" + id));
agentCompactIn(list, ids, a);
const bar = el("div", "bar");
const done = el("button", "primary", t("Done"));
done.type = "button";
@@ -21173,10 +21173,7 @@ function renderAgentPrefs() {
v1Warn.textContent = s.notice ? tNotice(s.notice) : "";
$("#codexAgentsV1Segs").replaceChildren(segs([["off", t("Off")], ["on", t("On")]], s.codexAgentsV1 ? "on" : "off", (v) =>
writingPrefs(api("settings/codex-agents-v1", { on: v === "on" })).then((ns) => { prefs = ns; renderSettings(); if (ns.notice) status(tNotice(ns.notice), "warn", 9000); }).catch(settingsErr)));
// a 1M model's whole window, or compacting at the working one (X: Chen,
// 70–90s to a first token at 550K)
// at a size the user types too, not 272K alone (#876); a provider's own
// Compact at comes before either
// Long conversations (X: Chen; #876)
const setCompact = (body) => prefWrite(api("settings/full-context", body));
const at = contextsText({ "*": s.compactAt || 272000 });
const compactSegs = segs([["off", t("Compact at {n}", { n: at.toUpperCase() })], ["on", t("Full window")]], s.fullContext ? "on" : "off", (v) => setCompact({ on: v === "on" }));
+8
View File
@@ -1212,6 +1212,8 @@ const I18N = {
"Changes nothing in {agents}: magpie’s names don’t reach their model lists": "对 {agents} 不起作用:它们的模型列表里没有 magpie 给的名称",
"Codex subagents on any model": "Codex 子代理可用任意模型",
"Long conversations": "长对话",
"Long conversations in {agent}": "{agent} 的长对话",
"Its own size, for models that differ; Every agent follows Long conversations above": "自有大小,给窗口不同的模型;选「所有智能体」则跟随上面的长对话",
"Full window": "完整窗口",
"Codex background compaction": "Codex 后台压缩",
"Codex 0.163 and later summarise while a turn goes on, past the share of the window typed (65% when empty); a value set in its own config stays": "Codex 0.163 起在一轮进行中就在后台总结,超过这里填的窗口占比时开始(留空为 65%);它配置里自己设的值不动",
@@ -5783,6 +5785,8 @@ const I18N = {
"Changes nothing in {agents}: magpie’s names don’t reach their model lists": "對 {agents} 不起作用:它們的模型列表裡沒有 magpie 給的名稱",
"Codex subagents on any model": "Codex 子代理可用任意模型",
"Long conversations": "長對話",
"Long conversations in {agent}": "{agent} 的長對話",
"Its own size, for models that differ; Every agent follows Long conversations above": "自有大小,給視窗不同的模型;選「所有智慧體」則跟隨上面的長對話",
"Full window": "完整視窗",
"Codex background compaction": "Codex 背景壓縮",
"Codex 0.163 and later summarise while a turn goes on, past the share of the window typed (65% when empty); a value set in its own config stays": "Codex 0.163 起在一輪進行中就在背景總結,超過這裡填的視窗占比時開始(留空為 65%);它設定裡自己設的值不動",
@@ -10315,6 +10319,8 @@ const I18N = {
"Changes nothing in {agents}: magpie’s names don’t reach their model lists": "{agents} には効きません:そのモデル一覧には magpie の名前が出ません",
"Codex subagents on any model": "Codex のサブエージェントで任意のモデル",
"Long conversations": "長い会話",
"Long conversations in {agent}": "{agent} の長い会話",
"Its own size, for models that differ; Every agent follows Long conversations above": "モデルごとに窓が違うときの独自の大きさ。「すべてのエージェント」なら上の長い会話に従います",
"Full window": "ウィンドウ全体",
"Codex background compaction": "Codex のバックグラウンド圧縮",
"Codex 0.163 and later summarise while a turn goes on, past the share of the window typed (65% when empty); a value set in its own config stays": "Codex 0.163 以降はターンの途中で要約し、入力したウィンドウの割合を超えると始まる(空欄で 65%)。設定ファイルで自分で設定した値はそのまま",
@@ -14882,6 +14888,8 @@ const I18N = {
"Changes nothing in {agents}: magpie’s names don’t reach their model lists": "Wirkt nicht in {agents}: deren Modelllisten zeigen magpies Namen nicht",
"Codex subagents on any model": "Codex-Subagenten auf jedem Modell",
"Long conversations": "Lange Unterhaltungen",
"Long conversations in {agent}": "Lange Unterhaltungen in {agent}",
"Its own size, for models that differ; Every agent follows Long conversations above": "Eine eigene Größe für Modelle mit anderem Fenster; Jeder Agent folgt Lange Unterhaltungen oben",
"Full window": "Volles Fenster",
"Codex background compaction": "Codex-Hintergrundkomprimierung",
"Codex 0.163 and later summarise while a turn goes on, past the share of the window typed (65% when empty); a value set in its own config stays": "Codex ab 0.163 fasst während eines Zugs zusammen, ab dem eingegebenen Anteil des Fensters (leer: 65 %); ein in seiner Konfiguration gesetzter Wert bleibt",
+1
View File
@@ -130,6 +130,7 @@ func TestSettingsSaveKeepsWhatItDoesNotSend(t *testing.T) {
ModelOutputs: map[string]int{"p/m": 131072},
ModelCompacts: map[string]int{"p/*": 500000},
CompactAt: 400000,
AgentCompacts: map[string]settings.AgentCompact{"claude": {At: 600000}},
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"},
+134
View File
@@ -0,0 +1,134 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// An agent's own Long conversations (molianyin4227 on Discord: models
// differ, so one size for every agent fits none). Under Long conversations
// in Claude Code's and Codex's sheets, "Long conversations in <agent>"
// follows Every agent until it is given its own: Compact at a size
// (starting from every agent's) or Full window, each posting
// settings/agent-compact for that agent alone; Every agent again takes
// its own away. Its label follows every agent's size when that row
// changes, no click or typing scrolls the page, there is no native select.
// English and Chinese, Chromium and WebKit, wide and narrow; no backend,
// the API is faked here.
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("claude", "Claude Code"), 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-compact") {
const body = req.postDataJSON();
posts.push({ path: url.pathname, body });
const own = { ...(settings.agentCompacts || {}) };
if (body.own) own[body.agent] = { ...(body.at && body.at !== 272000 ? { at: body.at } : {}), ...(body.full ? { full: true } : {}) };
else delete own[body.agent];
settings = { ...settings, agentCompacts: own };
return json(settings);
}
if (url.pathname === "/api/settings/full-context") {
const body = req.postDataJSON();
posts.push({ path: url.pathname, body });
settings = { ...settings, fullContext: body.on, ...(body.at !== undefined ? { compactAt: body.at === 272000 ? 0 : body.at } : {}) };
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) => `Long conversations in ${a}`, all: "Every agent", at: (n) => `Compact at ${n}`, full: "Full window", bad: "Compact at: lots is not a number of tokens like 272k" },
zh: { name: (a) => `${a} 的长对话`, all: "所有智能体", at: (n) => `${n} 时压缩`, full: "完整窗口", bad: "压缩阈值:lots 不是 272k 这样的 token 数" },
};
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of ["en", "zh"]) {
for (const width of [900, 420]) {
const w = words[lang];
test(`${engine} ${lang} ${width}px: an agent sets its own Long conversations`, 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, "claude");
const row = page.locator('.agent-compact[data-agent="claude"]');
await row.waitFor();
assert.equal(await row.locator(".name").textContent(), w.name("Claude Code"));
assert.equal(await row.locator("select").count(), 0, "no native select");
// right under Long conversations
assert.equal(await row.evaluate((r) => r.previousElementSibling?.id), "fullContextRow");
const seg = (label) => row.getByText(label, { exact: true });
const on = (label) => seg(label).evaluate((b) => b.classList.contains("on") || b.getAttribute("aria-pressed") === "true" || b.getAttribute("aria-checked") === "true");
assert(await on(w.all), "follows every agent until set");
assert(await seg(w.at("400K")).isVisible(), "every agent's size is the start");
const num = row.locator("input.compact-num");
assert(await num.isHidden(), "no size while it follows every agent");
const view = () => page.locator("#view-agents").evaluate((v) => v.scrollTop);
const before = await view();
await seg(w.at("400K")).click();
await page.waitForFunction(() => document.querySelector(".agent-compact input.compact-num")?.hidden === false);
assert.deepEqual(posts.map((p) => [p.path, p.body]), [["/api/settings/agent-compact", { agent: "claude", own: true, full: false, at: 400000 }]]);
await num.fill("150k");
await num.press("Enter");
await seg(w.at("150K")).waitFor();
assert.deepEqual(posts.at(-1).body, { agent: "claude", own: true, full: false, at: 150000 });
await seg(w.full).click();
await page.waitForFunction(() => document.querySelector(".agent-compact input.compact-num")?.hidden);
assert.deepEqual(posts.at(-1).body, { agent: "claude", own: true, full: true, at: 150000 });
// every agent's row is untouched by it, and its own change shows here
assert(!posts.some((p) => p.path === "/api/settings/full-context"), "every agent's Long conversations was not sent");
await seg(w.all).click();
await page.waitForFunction(() => document.querySelector(".agent-compact input.compact-num")?.hidden);
assert.deepEqual(posts.at(-1).body, { agent: "claude", own: false });
const every = page.locator("#fullContextSegs input.compact-num");
await every.fill("500k");
await every.press("Enter");
await seg(w.at("500K")).waitFor();
assert(await on(w.all));
assert.equal(await view(), before, "the row scrolled the page");
assert(!posts.some((p) => p.path === "/api/settings"), "set on its own, not with the other preferences");
// a size that isn't one is refused, nothing sent
await seg(w.at("500K")).click();
await page.waitForFunction(() => document.querySelector(".agent-compact input.compact-num")?.hidden === false);
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");
// it fits a narrow window
const over = await row.evaluate((r) => r.scrollWidth - r.clientWidth);
assert(over <= 1, `the row overflows by ${over}px`);
assert.deepEqual(errors, []);
});
}
}
}
@@ -175,7 +175,9 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
await page.goto("http://magpie.test/?view=agents");
await openAgentSettings(page, "claude");
await page.locator('.row.agent[data-id="claude"] .ag-prefs #fullContextRow').waitFor();
assert.equal(await page.locator(".ag-prefs .row.pref").count(), 1, "Claude Code's settings are Long conversations alone");
// Long conversations, and Claude Code's own size under it
await page.locator('.row.agent[data-id="claude"] .ag-prefs .agent-compact').waitFor();
assert.equal(await page.locator(".ag-prefs .row.pref:not(.agent-compact)").count(), 1, "Claude Code's settings are Long conversations alone");
assert.equal(await page.locator("#codexMemoriesRow").isHidden(), true);
assert.deepEqual(errors, []);
});
+3 -2
View File
@@ -156,9 +156,10 @@ test("compat.js is the first of the page's own scripts", async () => {
// Sync, scrollends.js on the window's first scroll, profilerename.js
// when a saved profile's Rename is pressed, keyspend.js when the
// provider editor draws a key's row, syncfiles.js when Sync's Export or
// Import opens; the checks above
// Import opens, agentcompact.js when an agent sheet holds Long
// conversations; 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", "quitask.js", "checkinnow.js", "autobackup.js", "scrollends.js", "profilerename.js", "settingshints.js", "keyspend.js", "syncfiles.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", "quitask.js", "checkinnow.js", "autobackup.js", "scrollends.js", "profilerename.js", "settingshints.js", "keyspend.js", "syncfiles.js", "agentcompact.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html");
});
test("the styles hold up in Safari 15.0", async () => {
+1 -1
View File
@@ -166,7 +166,7 @@ func adviseOf(by map[string][]tune.Call, days int, home string) tuneState {
if err != nil {
continue
}
st := settings.Load()
st := settings.Load().ForAgent("codex")
window, told, own, apart := codexWindow(calls, st, provider.Catalog(), provider.GroupFinder())
// Long conversations' value is the setting; where Codex runs
// now is that as magpie tells it for these models (their
+2 -2
View File
@@ -624,7 +624,7 @@ func buildCodexListTag(kind string) string {
ms = append(ms, codexWindowsTag()...)
// and where a model with no threshold of its own is compacted, when
// that isn't the working window
if n := settings.Load().Compact(); n != settings.WorkingWindow {
if n := settings.Load().ForAgent("codex").Compact(); n != settings.WorkingWindow {
ms = append(ms, catalog.Model{ID: "~compact", Context: n})
}
// and the model Codex's auto-review runs on (#938)
@@ -764,7 +764,7 @@ func codexListed(shown []Entry, members func(id string) []Member, own bool) []ca
// are in Codex's picker beside these
labels := Labels(shown)
seen := described()
s := settings.Load()
s := settings.Load().ForAgent("codex")
find := func(id string) (Group, []Member, bool) { return Group{}, members(id), true }
listed := func(e Entry) bool { return own || !CodexOwn(e) }
apart := codexApart(shown, labels, listed)
+41
View File
@@ -1,6 +1,8 @@
package provider
import (
"maps"
"slices"
"strings"
"github.com/yetone/magpie/internal/catalog"
@@ -222,6 +224,45 @@ func SetModelCompacts(providerID string, cs map[string]int) error {
return nil
}
// SetAgentCompact gives an agent of CompactAgents a Long conversations of
// its own, c, over the one for every agent; nil takes it away, and the
// agent follows that one again.
func SetAgentCompact(agent string, c *settings.AgentCompact) error {
if !slices.Contains(settings.CompactAgents, agent) {
return errorf("%q writes no compaction window magpie sets", agent)
}
if c != nil && c.At < 0 {
return errorf("a compaction threshold is a number of tokens, not %d", c.At)
}
s := settings.Load()
cur, had := s.AgentCompacts[agent]
if c == nil {
if !had {
return nil
}
s.AgentCompacts = maps.Clone(s.AgentCompacts)
delete(s.AgentCompacts, agent)
} else {
n := *c
if n.At == settings.WorkingWindow {
n.At = 0
}
if had && cur == n {
return nil
}
s.AgentCompacts = maps.Clone(s.AgentCompacts)
if s.AgentCompacts == nil {
s.AgentCompacts = map[string]settings.AgentCompact{}
}
s.AgentCompacts[agent] = n
}
if err := settings.Save(s); err != nil {
return err
}
catalog.Touched()
return nil
}
// SetCompactAt has every model without a threshold of its own compacted at
// n tokens, Full window turned off; 0 is the working window again
// (settings.WorkingWindow).
+59
View File
@@ -139,3 +139,62 @@ func TestOwnModelsSwitchTellsTheAgents(t *testing.T) {
t.Fatalf("shown: told %d times, hidden=%v; want twice, false", told, OwnModelsHidden("claude"))
}
}
// An agent sets its own Long conversations (molianyin4227 on Discord: one
// size for every agent fits none when their models differ): Codex, Claude
// Code and Grok Build take one over the one every agent has, another
// agent has no window magpie writes and is refused, nil goes back to
// every agent's, and the agent's 272K is kept as magpie's default.
func TestSetAgentCompact(t *testing.T) {
limitsHome(t)
told := 0
catalog.Changed = func() { told++ }
t.Cleanup(func() { catalog.Changed = nil })
if err := SetCompactAt(400000); err != nil {
t.Fatal(err)
}
told = 0
if err := SetAgentCompact("codex", &settings.AgentCompact{At: 600000}); err != nil {
t.Fatal(err)
}
if err := SetAgentCompact("claude", &settings.AgentCompact{Full: true}); err != nil {
t.Fatal(err)
}
s := settings.Load()
if c, cl, g := s.ForAgent("codex"), s.ForAgent("claude"), s.ForAgent("grok"); c.Compact() != 600000 || cl.Compact() != 0 || g.Compact() != 400000 {
t.Fatalf("codex %d, claude %d, grok %d; want 600000, 0 (full), 400000", c.Compact(), cl.Compact(), g.Compact())
}
if s.CompactAt != 400000 || s.FullContext {
t.Fatalf("every agent's changed: %d full=%v", s.CompactAt, s.FullContext)
}
if told != 2 {
t.Fatalf("told the agents %d times; want 2", told)
}
if err := SetAgentCompact("codex", &settings.AgentCompact{At: 600000}); err != nil || told != 2 {
t.Fatalf("the same value again: %v, told %d", err, told)
}
if err := SetAgentCompact("codex", &settings.AgentCompact{At: settings.WorkingWindow}); err != nil {
t.Fatal(err)
}
if c, ok := settings.Load().AgentCompacts["codex"]; !ok || c.At != 0 || settings.Load().ForAgent("codex").Compact() != settings.WorkingWindow {
t.Fatalf("codex at 272K: %+v %v", c, ok)
}
for _, bad := range []string{"opencode", "", "codex@wsl:Ubuntu"} {
if err := SetAgentCompact(bad, &settings.AgentCompact{At: 300000}); err == nil {
t.Errorf("%q took a window", bad)
}
}
if err := SetAgentCompact("grok", &settings.AgentCompact{At: -1}); err == nil {
t.Error("a negative size was accepted")
}
if err := SetAgentCompact("claude", nil); err != nil {
t.Fatal(err)
}
s = settings.Load()
if _, ok := s.AgentCompacts["claude"]; ok || s.ForAgent("claude").Compact() != 400000 {
t.Fatalf("claude back to every agent's: %+v", s.AgentCompacts)
}
if len(s.AgentCompacts) != 1 {
t.Fatalf("others left: %+v", s.AgentCompacts)
}
}
+28
View File
@@ -732,6 +732,11 @@ 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"`
// 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
// agent fits none). An agent with none follows those two (ForAgent).
AgentCompacts map[string]AgentCompact `json:"agentCompacts,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
@@ -1324,6 +1329,29 @@ func (s Settings) Working(n int) int {
return n
}
// AgentCompact is one agent's Long conversations: Full its FullContext,
// At its CompactAt (0 is WorkingWindow).
type AgentCompact struct {
At int `json:"at,omitempty"`
Full bool `json:"full,omitempty"`
}
// CompactAgents are the agents whose configs magpie writes a compaction
// window into, by the key each reads: Codex's model catalog
// (auto_compact_token_limit), Claude Code's settings.json
// (CLAUDE_CODE_AUTO_COMPACT_WINDOW, autoCompactWindow) and Grok Build's
// model tables (context_window). Only these take an AgentCompact.
var CompactAgents = []string{"codex", "claude", "grok"}
// ForAgent is s as the agent of that kind reads Long conversations: its
// own AgentCompact in CompactAt and FullContext, when it has one.
func (s Settings) ForAgent(kind string) Settings {
if c, ok := s.AgentCompacts[kind]; ok {
s.CompactAt, s.FullContext = c.At, c.Full
}
return s
}
// Compact is where a conversation on a longer window is compacted when
// neither its model nor its provider says (ModelCompacts): CompactAt,
// else WorkingWindow, and 0 under FullContext, the model's whole window.
+3 -2
View File
@@ -307,8 +307,9 @@ func Merge(body []byte, cur settings.Settings, web bool) (settings.Settings, err
in.BareModelIDs = cur.BareModelIDs // set on its own (bare-ids)
in.BusyLoad = cur.BusyLoad // and so is this (busy-load)
in.CodexAgentsV1 = cur.CodexAgentsV1
in.FullContext = cur.FullContext // set on its own (full-context)
in.CompactAt = cur.CompactAt // and so is the threshold
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)
// 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