diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md index 82cf2e545..ab477f6ae 100644 --- a/docs/subsystems/agent-wiring.md +++ b/docs/subsystems/agent-wiring.md @@ -20,6 +20,7 @@ something else shows up as drift. | What came before | The stash (`stash.json`) remembers what the config said before magpie pointed it at the gateway, so Disconnect restores it rather than guessing. | [`stash.go`](../../internal/agent/stash.go) | | Disconnect and preview | `Disconnect` runs `Unwire`, then returns each field still on magpie to its default. Last it runs `Restore`: Pi and its kin (`piLike`: Pi, OmO, Prime Agent; and MothX, its one `settings.json`) copy `settings.json` and `models.json` aside (`*.before-magpie`, `beforeMagpie`) before magpie's first write, and put that copy back byte for byte where what Disconnect left is the same JSON; a file that wasn't there goes again when only empty objects are left in it. `DisconnectPreview` runs the real Disconnect on a copy under a temporary home, in a subprocess (`DryRunArg`), and diffs the files. The preview is never a second account of what Disconnect does. | [`applied.go`](../../internal/agent/applied.go), [`preview.go`](../../internal/agent/preview.go) | | Keeping configs current | `Reseat` moves agents off a model magpie no longer serves (#200). `OnGateway` and `Rewire` write the new gateway address into every connected agent when the port changes. `Source` and `Stale` say what an unconnected agent runs on, and whether running copies still use the old list. | [`reseat.go`](../../internal/agent/reseat.go), [`rewire.go`](../../internal/agent/rewire.go), [`connectinfo.go`](../../internal/agent/connectinfo.go) | +| Codex background compaction | Settings › Long conversations' Codex background compaction (`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`. 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`, an inline or dotted table is the user's as written. | [`codex_async.go`](../../internal/agent/codex_async.go) | | Named omp profiles | omp keeps a profile's settings under `~/.omp/profiles/` (or under `PI_CONFIG_DIR`), each with its own `config.yml` and `models.yml`. Every such profile is an agent of its own — `omp#` on Windows, `omp#@wsl:` 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) | | WSL twins | On Windows each running distro is probed once, without starting a stopped one. The `wslKinds` agents found there become agents of their own, `@wsl:`, edited through `\\wsl.localhost\`. A kind is found by its folder under the distro's home or by its command there (not one on a Windows drive). Where another tool shares one of them, the kind leaves it out: Gemini CLI is found by its command alone, because Antigravity keeps `~/.gemini` too. Goose is found by its folder alone, because a `goose` command can be pressly's migration tool. Reasonix also needs the version its command gives (`accept`), because the old npm client is named `reasonix` too. The gateway address and key follow the distro's networking: mirrored or NAT (`place`, `keyAt`). `ListsFor` keeps a twin's model picks under the Windows twin's id (#927). | [`wsl.go`](../../internal/agent/wsl.go), [`gatewaykey.go`](../../internal/agent/gatewaykey.go) | | Settings tuned from use | Usage › Context's "Tuned for you" advises, per agent, the settings that would have spent the fewest tokens on the user's own calls of the range, and puts one in on a click. Package `tune` replays the calls `sessions.Calls` reads from the agents' session files under each candidate value (`Compact`, `CacheTTL`); `tuneOf` picks the agents and models (Claude Code per model, Codex pooled). `TuneRead`, `TuneApply` and `TuneUndo` know where each setting lives: Claude Code's `modelSettings..autoCompactWindow` (where its `/autocompact` saves), `promptCacheTtl` and `subagentPromptCacheTtl` in `~/.claude/settings.json`; Codex's top-level `model_auto_compact_token_limit`. The advice is weighed by tokens alone: it is labelled "Fewest tokens", and a compaction window it would change says it doesn't measure how well the agent keeps the task after a compaction, and that a lower window compacts more often (#1854, `context-tune.test.cjs`). A compaction row's "Other window…" opens the app menu with every value of the curve, each with its estimated extra tokens over the fewest and about how many compactions it would have made (`Point.compacts`, from the same replay), and puts the one picked in like Use (#1860). An agent whose files time its compactions also has their wait weighed (HirotaNagai on X): Claude Code's `compact_boundary` line says `compactMetadata.durationMs`, which `sessions` puts on the first call after it, and Codex compacts by a call of its own (the record a `compacted` line names, in rollouts since 2026-09), whose time is the compaction's (`Call.Compact`; an older rollout's compaction has no call and stays untimed). With 3 or more timed for a model (`minTimed`), `Facts.took` is their median seconds, each window says its wait (`Point.wait`, its compactions × `took`), and the row says what a compaction took, the wait at the advice against the window now, and the cheaper window the advice passed over for waiting longer (`Compaction.cheapest`, `wait_cheapest`) when it saves 3% or more; the advice is labelled "Tokens + wait", its caveat says tokens and waiting only, and the picker says each window's wait with "Fewest tokens" on the cheapest (`context-tune.test.cjs`). An agent or model with fewer timed reads and is advised as before. | [`internal/tune`](../../internal/tune/tune.go), [`tune.go`](../../internal/agent/tune.go), [`internal/gui/tune.go`](../../internal/gui/tune.go) | diff --git a/internal/agent/codex.go b/internal/agent/codex.go index 96d019059..9be854a69 100644 --- a/internal/agent/codex.go +++ b/internal/agent/codex.go @@ -386,12 +386,18 @@ func codexIn(at place) *Agent { return dropSubEffort() } // magpie as a provider Codex can name; its threads started on magpie do + // Codex's background compaction, as Settings has it (#2490): written + // where Codex is routed through magpie, taken back where it isn't + asyncCompaction := func(routed bool) error { + s := settings.Load() + return codexAsyncSync(path, at.key("codex.async"), routed, s.CodexAsyncCompact, s.CodexAsyncCompactPercent) + } putProvider := func() error { - return edit.SetTOMLTable(path, "model_providers."+magpieID, - edit.KV{Path: "name", Value: "magpie"}, - edit.KV{Path: "base_url", Value: at.v1()}, - edit.KV{Path: "wire_api", Value: "responses"}, - edit.KV{Path: "experimental_bearer_token", Value: at.gwKey()}, + kvs := []edit.KV{ + {Path: "name", Value: "magpie"}, + {Path: "base_url", Value: at.v1()}, + {Path: "wire_api", Value: "responses"}, + {Path: "experimental_bearer_token", Value: at.gwKey()}, // Codex offers its built-in image tool (image_gen.imagegen) and // the other OpenAI-provider tools only to a provider it reads as // the OpenAI actor: one that does not require OpenAI auth but @@ -404,8 +410,17 @@ func codexIn(at place) *Agent { // gets the header set there, the user's others kept; written // inline beside that table it defined http_headers twice and // every model switch failed (wztlink1013 on Discord). - edit.KV{Path: "http_headers", Value: edit.Inline{{Path: "x-openai-actor-authorization", Value: "magpie"}}}, - ) + {Path: "http_headers", Value: edit.Inline{{Path: "x-openai-actor-authorization", Value: "magpie"}}}, + } + // the table's capabilities, the user's or the background + // compaction's, aren't lost as it is written again + if caps := codexProviderCaps(path); caps != nil { + kvs = append(kvs, edit.KV{Path: "capabilities", Value: caps}) + } + if err := edit.SetTOMLTable(path, "model_providers."+magpieID, kvs...); err != nil { + return err + } + return asyncCompaction(true) } hasProvider := func() bool { t, err := edit.GetTOMLTable(path, "model_providers."+magpieID) @@ -1143,6 +1158,9 @@ func codexIn(at place) *Agent { }, OwnVia: codexOwnViaMagpie, Sync: func() error { + if err := asyncCompaction(routed()); err != nil { + return err + } // model_provider = "magpie" left with its table gone (taken by // another tool, or a hand edit), which keeps Codex from loading // its config at all, connected to magpie or not (Tystem on diff --git a/internal/agent/codex_async.go b/internal/agent/codex_async.go new file mode 100644 index 000000000..e4092467d --- /dev/null +++ b/internal/agent/codex_async.go @@ -0,0 +1,190 @@ +package agent + +// Codex's background compaction (0.163 on, #2490): with +// [features.async_compaction] enabled, Codex sends a compaction_trigger of +// its own while a turn goes on, once the conversation is past +// model_async_compact_threshold_percent of the model's window (in that +// table; one at the top level is not read), and takes the summary in at the +// turn's next step. It starts one only on a provider whose +// capabilities.remote_compaction is "v2", which Codex gives OpenAI's own and +// Azure alone: on magpie's [model_providers.magpie] it never ran until that +// was written there too. magpie's gateway answers the trigger as it does +// Codex's own compaction (codexCompact, or the provider's native one). +// +// What magpie writes is kept in the stash, so a value the user set there +// (by hand, or a value they changed since) is theirs: never written over, +// and left when the setting is turned off. + +import ( + "encoding/json" + "errors" + + "github.com/pelletier/go-toml/v2" + + "github.com/yetone/magpie/internal/edit" +) + +const ( + codexAsyncTable = "features.async_compaction" + codexAsyncPercent = "model_async_compact_threshold_percent" +) + +// codexAsyncStash is what magpie wrote. +type codexAsyncStash struct { + Enabled bool `json:"enabled,omitempty"` // enabled = true + Percent int `json:"percent,omitempty"` // the threshold + Cap bool `json:"cap,omitempty"` // capabilities = { remote_compaction = "v2" } +} + +// codexAsyncNow is how the config has them: the async_compaction value +// (nil, a bool, or a table) and magpie's provider table, nil when absent. +func codexAsyncNow(path string) (feature any, provider map[string]any, err error) { + raw, err := edit.Read(path) + if err != nil || raw == nil { + return nil, nil, err + } + var doc map[string]any + if err := toml.Unmarshal(raw, &doc); err != nil { + return nil, nil, err + } + features, _ := doc["features"].(map[string]any) + providers, _ := doc["model_providers"].(map[string]any) + p, _ := providers[magpieID].(map[string]any) + return features["async_compaction"], p, nil +} + +// codexAsyncSync puts the setting into the Codex config at path, where +// Codex is routed through magpie or not: on is the setting, percent its +// threshold (0 leaves Codex's own). key is the stash's. The capability is +// written for a feature the user turned on in the config themselves too: +// on magpie's provider it would never run without it (#2493). +func codexAsyncSync(path, key string, routed, on bool, percent int) error { + feature, provider, err := codexAsyncNow(path) + var bad *toml.DecodeError + if errors.As(err, &bad) { + return nil // one that doesn't parse is told by Check, and written to by nothing + } + if err != nil { + return err + } + var st codexAsyncStash + if raw := stashLoad()[key]; raw != "" { + json.Unmarshal([]byte(raw), &st) + } + was := st + want := routed && on + if !want { + percent = 0 + } + + // [features.async_compaction]: written only as that table, which a + // config without the feature, or with the table, has. The bare + // async_compaction = true, or the table spelled inline or as dotted + // keys, is the user's, as written. + table, _ := feature.(map[string]any) + asTable := feature == nil + if table != nil { + t, err := edit.GetTOMLTable(path, codexAsyncTable) + if err != nil { + return err + } + asTable = t != nil + } + if asTable { + enabled, hasEnabled := table["enabled"].(bool) + if table["enabled"] != nil && !(hasEnabled && st.Enabled && enabled) { + st.Enabled = false // set, or changed since, by the user + } + switch { + case want && !hasEnabled && table["enabled"] == nil: + if err := edit.SetTOMLKey(path, codexAsyncTable, "enabled", true); err != nil { + return err + } + st.Enabled = true + case !want && st.Enabled: + if err := edit.DelTOMLKey(path, codexAsyncTable, "enabled"); err != nil { + return err + } + st.Enabled = false + } + cur, hasPercent := table[codexAsyncPercent].(int64) + if table[codexAsyncPercent] != nil && !(hasPercent && int64(st.Percent) == cur) { + st.Percent = 0 + } + switch { + case percent > 0 && (table[codexAsyncPercent] == nil || st.Percent != 0): + if st.Percent != percent { + if err := edit.SetTOMLKey(path, codexAsyncTable, codexAsyncPercent, percent); err != nil { + return err + } + } + st.Percent = percent + case percent == 0 && st.Percent != 0: + if err := edit.DelTOMLKey(path, codexAsyncTable, codexAsyncPercent); err != nil { + return err + } + st.Percent = 0 + } + } else { + st.Enabled, st.Percent = false, 0 + } + + // capabilities on magpie's provider table, when there is one: one the + // user gave it, whatever it says, stays as it is + if feature, _, err = codexAsyncNow(path); err != nil { + return err + } + table, _ = feature.(map[string]any) + if feature == true || table["enabled"] == true { + want = routed + } + if provider == nil { + st.Cap = false + } else { + caps, has := provider["capabilities"].(map[string]any) + if has && !(st.Cap && len(caps) == 1 && caps["remote_compaction"] == "v2") { + st.Cap = false + } + switch { + case want && provider["capabilities"] == nil: + if err := edit.SetTOMLKey(path, "model_providers."+magpieID, "capabilities", edit.Inline{{Path: "remote_compaction", Value: "v2"}}); err != nil { + return err + } + st.Cap = true + case !want && st.Cap: + if err := edit.DelTOMLKey(path, "model_providers."+magpieID, "capabilities"); err != nil { + return err + } + st.Cap = false + } + } + + if st != was { + if st == (codexAsyncStash{}) { + forget(key) + } else { + b, _ := json.Marshal(st) + stash(map[string]string{key: string(b)}) + } + } + return nil +} + +// codexProviderCaps is the capabilities magpie's provider table has, as an +// Inline to write it back with when the table is written again: one the +// user gave it, or magpie's for the background compaction, isn't lost. +func codexProviderCaps(path string) edit.Inline { + _, provider, err := codexAsyncNow(path) + if err != nil { + return nil + } + caps, _ := provider["capabilities"].(map[string]any) + var out edit.Inline + for _, k := range sortedKeys(caps) { + switch v := caps[k].(type) { + case string, bool, int64, float64: + out = append(out, edit.KV{Path: k, Value: v}) + } + } + return out +} diff --git a/internal/agent/codex_async_test.go b/internal/agent/codex_async_test.go new file mode 100644 index 000000000..0d39f84c2 --- /dev/null +++ b/internal/agent/codex_async_test.go @@ -0,0 +1,167 @@ +package agent + +import ( + "strings" + "testing" + + "github.com/pelletier/go-toml/v2" + + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/settings" +) + +// setAsyncCompact sets Codex's background compaction as the Settings row +// does, put back when the test ends. +func setAsyncCompact(t *testing.T, on bool, percent int) { + t.Helper() + was := settings.Load() + t.Cleanup(func() { + s := settings.Load() + s.CodexAsyncCompact, s.CodexAsyncCompactPercent = was.CodexAsyncCompact, was.CodexAsyncCompactPercent + if err := settings.Save(s); err != nil { + t.Errorf("restoring settings: %v", err) + } + }) + s := settings.Load() + s.CodexAsyncCompact, s.CodexAsyncCompactPercent = on, percent + if err := settings.Save(s); err != nil { + t.Fatal(err) + } +} + +// asyncOf is the config's async_compaction value and the capability on +// magpie's provider table. +func asyncOf(t *testing.T, config string) (feature any, capability any) { + t.Helper() + var doc map[string]any + if err := toml.Unmarshal([]byte(config), &doc); err != nil { + t.Fatalf("%v:\n%s", err, config) + } + features, _ := doc["features"].(map[string]any) + providers, _ := doc["model_providers"].(map[string]any) + p, _ := providers[magpieID].(map[string]any) + caps, _ := p["capabilities"].(map[string]any) + return features["async_compaction"], caps["remote_compaction"] +} + +// The switch on, Codex routed through magpie as its provider (no ChatGPT +// sign-in) gets [features.async_compaction] with the threshold in that +// table, where Codex 0.163 reads it, and remote_compaction = "v2" on +// magpie's provider table: without it Codex never starts a background +// compaction on a provider other than OpenAI's (tried with Codex 0.163: +// none in a whole turn past the threshold; with it, one per step, its +// summary taken in). A model switch writing the table again keeps it, and +// the switch off takes all of it out again. +func TestCodexAsyncCompactionWritten(t *testing.T) { + quietCodex(t, false, provider.CodexDaemonCheck{}) + home, read := codexHome(t, "", "model = \"gpt-5.5\"\n") + setAsyncCompact(t, true, 70) + cx := codex(home) + route(t, cx, read) + feature, capability := asyncOf(t, read()) + table, _ := feature.(map[string]any) + if table["enabled"] != true || table["model_async_compact_threshold_percent"] != int64(70) { + t.Fatalf("async_compaction = %v:\n%s", feature, read()) + } + if capability != "v2" { + t.Fatalf("no remote_compaction = \"v2\" on magpie's provider:\n%s", read()) + } + // a model switch writes magpie's provider table again + if err := cx.Fields[0].Set("fake/m1"); err != nil { + t.Fatal(err) + } + if err := cx.Sync(); err != nil { + t.Fatal(err) + } + if _, capability := asyncOf(t, read()); capability != "v2" { + t.Fatalf("the capability went as the table was written again:\n%s", read()) + } + if strings.Count(read(), "capabilities") != 1 || strings.Count(read(), "[features.async_compaction]") != 1 { + t.Fatalf("written twice:\n%s", read()) + } + // another threshold + setAsyncCompact(t, true, 80) + if err := cx.Sync(); err != nil { + t.Fatal(err) + } + if feature, _ := asyncOf(t, read()); feature.(map[string]any)["model_async_compact_threshold_percent"] != int64(80) { + t.Fatalf("threshold not moved to 80:\n%s", read()) + } + setAsyncCompact(t, false, 80) + if err := cx.Sync(); err != nil { + t.Fatal(err) + } + if feature, capability := asyncOf(t, read()); feature != nil || capability != nil { + t.Fatalf("left behind with the switch off: %v %v\n%s", feature, capability, read()) + } + if _, ok := stashLoad()["codex.async"]; ok { + t.Fatal("the stash still claims what magpie wrote") + } +} + +// A value the user set is theirs: on, it is never written over; off, it +// stays. The feature the user turned on by hand gets the capability it +// needs on magpie's provider, the switch on or not (#2493). +func TestCodexAsyncCompactionKeepsTheUsers(t *testing.T) { + for _, tc := range []struct { + name, config string + on bool + want string // the config holds this after + capability any // on magpie's provider once routed + }{ + {"enabled false, threshold", "[features.async_compaction]\nenabled = false\nmodel_async_compact_threshold_percent = 50\n", true, + "[features.async_compaction]\nenabled = false\nmodel_async_compact_threshold_percent = 50\n", "v2"}, + {"bare true", "[features]\nasync_compaction = true\n", false, "[features]\nasync_compaction = true\n", "v2"}, + {"bare false", "[features]\nasync_compaction = false\n", true, "[features]\nasync_compaction = false\n", "v2"}, + {"inline", "[features]\nasync_compaction = { enabled = true }\n", false, "async_compaction = { enabled = true }\n", "v2"}, + {"bare true, switch on", "[features]\nasync_compaction = true\n", true, "[features]\nasync_compaction = true\n", "v2"}, + } { + t.Run(tc.name, func(t *testing.T) { + quietCodex(t, false, provider.CodexDaemonCheck{}) + home, read := codexHome(t, "", "model = \"gpt-5.5\"\n\n"+tc.config) + setAsyncCompact(t, tc.on, 70) + cx := codex(home) + route(t, cx, read) + if !strings.Contains(read(), tc.want) || strings.Contains(read(), "= 70") { + t.Fatalf("the user's value was written over:\n%s", read()) + } + if _, capability := asyncOf(t, read()); capability != tc.capability { + t.Fatalf("capability %v, want %v:\n%s", capability, tc.capability, read()) + } + setAsyncCompact(t, false, 0) + if err := cx.Sync(); err != nil { + t.Fatal(err) + } + if !strings.Contains(read(), tc.want) { + t.Fatalf("the user's value went with the switch off:\n%s", read()) + } + }) + } +} + +// A capability the user gave magpie's provider stays as they wrote it. +func TestCodexAsyncCompactionKeepsUsersCapability(t *testing.T) { + quietCodex(t, false, provider.CodexDaemonCheck{}) + home, read := codexHome(t, "", "model = \"gpt-5.5\"\n") + cx := codex(home) + route(t, cx, read) + b := strings.Replace(read(), "wire_api = \"responses\"\n", "wire_api = \"responses\"\ncapabilities = { remote_compaction = \"unsupported\" }\n", 1) + writeFile(t, cx.Path, b) + setAsyncCompact(t, true, 0) + if err := cx.Fields[0].Set("fake/m1"); err != nil { + t.Fatal(err) + } + if err := cx.Sync(); err != nil { + t.Fatal(err) + } + if _, capability := asyncOf(t, read()); capability != "unsupported" { + t.Fatalf("the user's capability was written over:\n%s", read()) + } + setAsyncCompact(t, false, 0) + if err := cx.Sync(); err != nil { + t.Fatal(err) + } + if _, capability := asyncOf(t, read()); capability != "unsupported" { + t.Fatalf("the user's capability went:\n%s", read()) + } +} diff --git a/internal/gui/api.go b/internal/gui/api.go index 6d4a6da75..2f6194904 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -1219,6 +1219,8 @@ func Handler(w Windows, gw *gateway.Server) http.Handler { in.CodexAgentsV1 = cur.CodexAgentsV1 in.FullContext = cur.FullContext // set on its own (full-context below) in.CompactAt = cur.CompactAt // and so is the threshold + // Codex's background compaction, set on its own (codex-async-compact below) + in.CodexAsyncCompact, in.CodexAsyncCompactPercent = cur.CodexAsyncCompact, cur.CodexAsyncCompactPercent // Claude Desktop's list, set in its row on the Agents page in.DesktopLongest = cur.DesktopLongest // and the Get started card put away, from the card itself @@ -1498,6 +1500,28 @@ func Handler(w Windows, gw *gateway.Server) http.Handler { } writeJSON(rw, settingsState()) }) + // Codex's background compaction (#2490): on or off, and the share of + // a model's window it starts at (0: Codex's own, 65), written into the + // config Codex is routed through + mux.HandleFunc("POST /api/settings/codex-async-compact", func(rw http.ResponseWriter, r *http.Request) { + var in struct { + On bool + Percent *int + } + if err := json.NewDecoder(r.Body).Decode(&in); err != nil { + fail(rw, err) + return + } + pct := settings.Load().CodexAsyncCompactPercent + if in.Percent != nil { + pct = *in.Percent + } + if err := provider.SetCodexAsyncCompact(in.On, pct); err != nil { + fail(rw, err) + return + } + writeJSON(rw, settingsState()) + }) // where Codex's request for a thread's description goes: "" as Codex // sends it, or a model's id. It is separate from the title setting. mux.HandleFunc("POST /api/settings/codex-descriptions", func(rw http.ResponseWriter, r *http.Request) { diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 09ab05d8b..f8d1402cc 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -19170,7 +19170,7 @@ function renderSettings() { row(t("Community"), t("questions, ideas and feedback, on Discord or GitHub"), "", join, repo); // gateway mode leaves out what is written into this computer's agents' // files, and the alerts its desktop would show - for (const r of [$("#plainNamesSegs").parentElement, $("#codexAgentsV1Segs").parentElement, $("#fullContextSegs").parentElement, + for (const r of [$("#plainNamesSegs").parentElement, $("#codexAgentsV1Segs").parentElement, $("#fullContextSegs").parentElement, $("#codexAsyncRow"), $("#codexTitlesRow"), $("#codexDescriptionsRow"), $("#codexPredictionsRow"), $("#codexAutoReviewRow"), $("#usageAlertRow"), $("#balanceAlertRow"), $("#resetReminderRow"), $("#turnDoneRow")]) r.hidden = gatewayMode; // the parts' tabs, one gone whose rows are all hidden here setSetTab(setTab); @@ -19842,6 +19842,24 @@ function renderTrayUsage(s, keep) { const compactRow = el("div", "compact-at"); compactRow.append(compactSegs, compactNum); $("#fullContextSegs").replaceChildren(compactRow); + // Codex's background compaction (#2490): [features.async_compaction] and + // its threshold, written where magpie routes Codex (codex_async.go) + const setAsync = (body) => writingPrefs(api("settings/codex-async-compact", body)).then((ns) => { prefs = ns; renderSettings(); }).catch((e) => { status(t(e.message), "err"); renderSettings(); }); + const asyncSegs = segs([["off", t("Off")], ["on", t("On")]], s.codexAsyncCompact ? "on" : "off", (v) => setAsync({ on: v === "on" })); + const asyncNum = input(s.codexAsyncCompactPercent ? s.codexAsyncCompactPercent + "%" : "", "65%"); + asyncNum.className = "words compact-num"; + asyncNum.hidden = !s.codexAsyncCompact; + asyncNum.title = t("Background compaction at"); + asyncNum.setAttribute("aria-label", t("Background compaction at")); + asyncNum.onchange = () => { + const v = asyncNum.value.trim().replace(/\s*%$/, ""); + const n = v === "" ? 0 : Number(v); + if (!Number.isInteger(n) || n < 0 || n > 100) return status(t("Background compaction at: {v} is not a percent from 1 to 100", { v: asyncNum.value.trim() }), "err"); + setAsync({ on: true, percent: n }); + }; + const asyncRow = el("div", "compact-at"); + asyncRow.append(asyncSegs, asyncNum); + $("#codexAsyncSegs").replaceChildren(asyncRow); renderCodexTitles(s); renderCodexDescriptions(s); renderCodexPredictions(s); diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 5ed88c0e6..956630bd6 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -1005,6 +1005,10 @@ const I18N = { "Codex subagents on any model": "Codex 子代理可用任意模型", "Long conversations": "长对话", "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%);它配置里自己设的值不动", + "Background compaction at": "后台压缩阈值", + "Background compaction at: {v} is not a percent from 1 to 100": "后台压缩阈值:{v} 不是 1 到 100 的百分比", "Codex and Claude Code compact at 272K (non-Claude [1m] too) or the size typed; full window: slower, costlier": "Codex 和 Claude Code 在 272K(非 Claude 的 [1m] 模型也是)或这里填的大小时压缩;完整窗口每轮更慢更贵", "Compact at {n}": "{n} 时压缩", "Codex thread titles": "Codex 会话标题", @@ -4696,6 +4700,10 @@ const I18N = { "Codex subagents on any model": "Codex 子代理可用任意模型", "Long conversations": "長對話", "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%);它設定裡自己設的值不動", + "Background compaction at": "背景壓縮閾值", + "Background compaction at: {v} is not a percent from 1 to 100": "背景壓縮閾值:{v} 不是 1 到 100 的百分比", "Codex and Claude Code compact at 272K (non-Claude [1m] too) or the size typed; full window: slower, costlier": "Codex 和 Claude Code 在 272K(非 Claude 的 [1m] 模型也是)或這裡填的大小時壓縮;完整視窗每輪更慢更貴", "Compact at {n}": "{n} 時壓縮", "Codex thread titles": "Codex 會話標題", @@ -8349,6 +8357,10 @@ const I18N = { "Codex subagents on any model": "Codex のサブエージェントで任意のモデル", "Long conversations": "長い会話", "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%)。設定ファイルで自分で設定した値はそのまま", + "Background compaction at": "バックグラウンド圧縮のしきい値", + "Background compaction at: {v} is not a percent from 1 to 100": "バックグラウンド圧縮のしきい値:{v} は 1〜100 のパーセントではありません", "Codex and Claude Code compact at 272K (non-Claude [1m] too) or the size typed; full window: slower, costlier": "Codex と Claude Code は 272K(Claude 以外の [1m] モデルも)か入力したサイズで圧縮。ウィンドウ全体は遅く高価", "Compact at {n}": "{n} で圧縮", "Codex thread titles": "Codex のスレッドタイトル", @@ -12036,6 +12048,10 @@ const I18N = { "Codex subagents on any model": "Codex-Subagenten auf jedem Modell", "Long conversations": "Lange Unterhaltungen", "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", + "Background compaction at": "Hintergrundkomprimierung ab", + "Background compaction at: {v} is not a percent from 1 to 100": "Hintergrundkomprimierung ab: {v} ist kein Prozentwert von 1 bis 100", "Codex and Claude Code compact at 272K (non-Claude [1m] too) or the size typed; full window: slower, costlier": "Codex/Claude Code komprimieren bei 272K (auch [1m] außer Claude) oder hier; volles Fenster: teurer", "Compact at {n}": "Bei {n} komprimieren", "Codex thread titles": "Codex-Thread-Titel", diff --git a/internal/gui/assets/index.html b/internal/gui/assets/index.html index f01a919b8..a5b5f984d 100644 --- a/internal/gui/assets/index.html +++ b/internal/gui/assets/index.html @@ -199,6 +199,10 @@
Long conversations
Codex and Claude Code compact at 272K (non-Claude [1m] too) or the size typed; full window: slower, costlier
+
+
Codex background compaction
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 thread titles
diff --git a/internal/gui/settings_keep_test.go b/internal/gui/settings_keep_test.go index 9d850b3f1..937c581a7 100644 --- a/internal/gui/settings_keep_test.go +++ b/internal/gui/settings_keep_test.go @@ -179,6 +179,7 @@ func TestSettingsSaveKeepsWhatItDoesNotSend(t *testing.T) { NoAccountDiscovery: true, } was.DesktopSubagentEffort = "high" + was.CodexAsyncCompact, was.CodexAsyncCompactPercent = true, 70 if err := settings.Save(was); err != nil { t.Fatal(err) } diff --git a/internal/gui/tests/codex-async-compact.test.cjs b/internal/gui/tests/codex-async-compact.test.cjs new file mode 100644 index 000000000..da18a3647 --- /dev/null +++ b/internal/gui/tests/codex-async-compact.test.cjs @@ -0,0 +1,103 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// Settings → Long conversations' Codex background compaction (#2490): Off / +// On, and with it on the share of the window Codex starts at, typed as a +// percent (empty: Codex's own 65%). Each posts settings/codex-async-compact +// on its own, a value that isn't 0 to 100 is refused before anything is +// sent, and nothing scrolls the page. Every language, Chromium and WebKit; +// 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 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 }; + const models = ["deepseek-v4-flash", "deepseek-v4-pro"].map((id) => ({ id, name: id, on: true, context: 1000000 })); + const provider = { id: "deepseek", name: "DeepSeek", icon: "generic", chat: "https://api.deepseek.example/v1", responses: "", anthropic: "", models, agents: [], key: { set: true, masked: "sk-…1234" }, ready: true, compacts: { "*": 500000, "deepseek-v4-flash": 272000 } }; + const providers = { providers: [provider], presets: [], excluded: [], gateway: { running: true, window: true } }; + 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: [], profiles: [], settings: { lang, theme: "light" } }); + if (url.pathname === "/api/providers") return json(providers); + if (url.pathname === "/api/groups") return json({ groups: [], models: [] }); + if (url.pathname.startsWith("/api/provider/")) { + posts.push({ path: url.pathname, body: req.postDataJSON() }); + return json(providers); + } + if (url.pathname === "/api/settings/codex-async-compact") { + const body = req.postDataJSON(); + posts.push({ path: url.pathname, body }); + settings = { ...settings, codexAsyncCompact: body.on, ...(body.percent !== undefined ? { codexAsyncCompactPercent: body.percent } : {}) }; + 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: "Codex background compaction", field: "Background compaction at", bad: "Background compaction at: 150 is not a percent from 1 to 100", off: "Off", on: "On" }, + zh: { name: "Codex 后台压缩", field: "后台压缩阈值", bad: "后台压缩阈值:150 不是 1 到 100 的百分比", off: "关闭", on: "开启" }, + "zh-TW": { name: "Codex 背景壓縮", field: "背景壓縮閾值", bad: "背景壓縮閾值:150 不是 1 到 100 的百分比", off: "關閉", on: "開啟" }, + ja: { name: "Codex のバックグラウンド圧縮", field: "バックグラウンド圧縮のしきい値", bad: "バックグラウンド圧縮のしきい値:150 は 1〜100 のパーセントではありません", off: "オフ", on: "オン" }, + de: { name: "Codex-Hintergrundkomprimierung", field: "Hintergrundkomprimierung ab", bad: "Hintergrundkomprimierung ab: 150 ist kein Prozentwert von 1 bis 100", off: "Aus", on: "An" }, +}; + +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}: Codex background compaction is turned on with a threshold`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: process.env.PLAYWRIGHT_CHANNEL || "chromium" })); + t.after(() => browser.close()); + const page = await (await browser.newContext({ viewport: { width: 900, height: 720 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + const errors = [], posts = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang, posts)); + await page.goto("http://magpie.test/?view=settings"); + const row = page.locator("#codexAsyncRow"); + await row.getByText(w.name, { exact: true }).waitFor(); + assert.equal(await row.locator("select").count(), 0, "no native select"); + const num = row.locator("input.compact-num"); + assert(await num.isHidden(), "no threshold while off"); + const view = () => page.locator("#view-settings").evaluate((v) => v.scrollTop); + const before = await view(); + await row.getByText(w.on, { exact: true }).click(); + await page.waitForFunction(() => document.querySelector("#codexAsyncRow input.compact-num")?.hidden === false); + assert.deepEqual(posts.map((p) => [p.path, p.body]), [["/api/settings/codex-async-compact", { on: true }]]); + assert.equal(await num.getAttribute("aria-label"), w.field); + assert.equal(await num.getAttribute("placeholder"), "65%"); + await num.fill("150"); + await num.press("Enter"); + await page.getByText(w.bad).waitFor(); + assert.equal(posts.length, 1, "a bad percent is not sent"); + await num.fill("70%"); + await num.press("Enter"); + await page.waitForFunction(() => document.querySelector("#codexAsyncRow input.compact-num")?.value === "70%"); + assert.deepEqual(posts.at(-1), { path: "/api/settings/codex-async-compact", body: { on: true, percent: 70 } }); + await row.getByText(w.off, { exact: true }).click(); + await page.waitForFunction(() => document.querySelector("#codexAsyncRow input.compact-num")?.hidden); + assert.deepEqual(posts.at(-1).body, { on: false }); + 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"); + assert.deepEqual(errors, []); + }); + } +} diff --git a/internal/provider/modelprefs.go b/internal/provider/modelprefs.go index 3178aead5..5ce37e1b7 100644 --- a/internal/provider/modelprefs.go +++ b/internal/provider/modelprefs.go @@ -819,6 +819,25 @@ func SetCodexAutoReview(id string) error { return nil } +// SetCodexAsyncCompact sets Codex's background compaction +// (settings.CodexAsyncCompact) and the share of a model's window it starts +// at, 1–100 or 0 for Codex's own, and has Codex's config written again. +func SetCodexAsyncCompact(on bool, percent int) error { + if percent < 0 || percent > 100 { + return fmt.Errorf("Codex compacts in the background past 1 to 100%% of a model's window, not %d%%", percent) + } + s := settings.Load() + if s.CodexAsyncCompact == on && s.CodexAsyncCompactPercent == percent { + return nil + } + s.CodexAsyncCompact, s.CodexAsyncCompactPercent = on, percent + if err := settings.Save(s); err != nil { + return err + } + catalog.Touched() + return nil +} + // SetFullContext turns settings.FullContext on or off: Codex and Claude // Code are told a model's whole window, or the working one, again. func SetFullContext(on bool) error { diff --git a/internal/settings/settings.go b/internal/settings/settings.go index 1b6be1166..74666b887 100644 --- a/internal/settings/settings.go +++ b/internal/settings/settings.go @@ -484,6 +484,17 @@ 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"` + // 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 + // on Discord): [features.async_compaction] enabled in the config Codex + // is routed through, and capabilities.remote_compaction = "v2" on + // magpie's provider table, without which Codex never starts one on a + // provider other than OpenAI's. A value the user set there is theirs + // and stays (internal/agent/codex_async.go). + CodexAsyncCompact bool `json:"codexAsyncCompact,omitempty"` + // CodexAsyncCompactPercent is that share, 1–100; 0 is Codex's own, 65. + CodexAsyncCompactPercent int `json:"codexAsyncCompactPercent,omitempty"` // ChinaMirror is the Plugins page's 「国内镜像」 switch: the plugin list, // npm (the plugins' packages and what npm says of them) and Bun's // downloads are asked of mirrors in China first, and of their official