Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
tune: the compact window is Long conversations, one value for both agents
yetonef201183047a1
diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.mdindex 982fd91a6..749291232 100644--- a/docs/subsystems/agent-wiring.md+++ b/docs/subsystems/agent-wiring.md@@ -24,7 +24,7 @@ something else shows up as drift.| Codex background compaction | Long conversations' Codex background compaction, in Codex's opened row on the Agents page (`CodexAsyncCompact`, `CodexAsyncCompactPercent`, #2490) writes `[features.async_compaction]` `enabled = true` and `model_async_compact_threshold_percent` (Codex 0.163 reads it only in that table) into each Codex config magpie routes, on every `Sync`. The table is written only when every Codex that reads the config is 0.163.0-alpha.8 or later (`codexReaders`: the CLI on PATH, the Mac app's bundled `codex-cli/codex-package.json`, the Windows Store app and an editor's `openai.chatgpt` extension, whose versions aren't known, a WSL distro's CLI): an older Codex takes every unknown `[features]` entry for a bool and won't load a config with the table ("invalid type: map, expected a boolean"). Otherwise, or with no Codex found, magpie writes the bare `[features]` `async_compaction = true`, which every Codex loads, and no threshold; a table magpie wrote before is taken out on the next `Sync`, and Settings' row names the Codex that held it (`CodexAsyncHeld`). Codex starts a background compaction only on a provider whose `capabilities.remote_compaction` is `"v2"`, which it gives OpenAI and Azure alone, so `[model_providers.magpie]` gets `capabilities = { remote_compaction = "v2" }` too, also when the user turned the feature on by hand (#2493); `putProvider` carries the table's capabilities over when it writes it again. What magpie wrote is in the stash under `codex.async`: a value the user set, or changed since, is never written over and stays when the switch goes off; a bare `async_compaction = true` the stash doesn't name as magpie's (`bool`), an inline or dotted table is the user's as written. | [`codex_async.go`](../../internal/agent/codex_async.go) || 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) || 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, `<id>@wsl:<distro>`, edited through `\\wsl.localhost\<distro>`. 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. Antigravity CLI is found by its own `~/.gemini/antigravity-cli` or its `agy` command (mimi001234 on Discord). 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`). Under NAT the key is the gateway's WSL key (`gateway.WSLKey`, `-<agent>` after it where the agent's key names it), sharing on or off; the gateway listens at that address itself (gateway-routing's WSL under NAT). `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.<model>.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) |+| 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.<model>.autoCompactWindow` (where its `/autocompact` saves), `promptCacheTtl` and `subagentPromptCacheTtl` in `~/.claude/settings.json`. Where Codex compacts, and Claude Code wherever magpie's own window is what it runs at, is one value with Long conversations in the agents' settings sheet (`settings.CompactAt`/`FullContext`, source `long`; 7eleven on Discord): the card reads it, Use sets it through `provider.SetCompactAt`, and Sync writes it into each agent's config as it does for the sheet; the note says it is Long conversations, shared by Codex and Claude Code (`compact-one-value.test.cjs`). 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) || Agents a plugin adds | A plugin's `magpie.agent` module (or a `*.agent.js` file) says where an agent magpie has no setup of its own keeps its model (`config`, `format`, `model`, `prefix`), and its `connect` returns the other keys to write. One with no `model` is connect only (#2374): its one field is `provider`, magpie or nothing, as an app whose one setting is magpie as its provider; `connect` is called without a model, must return keys, and is called again on a catalog change (`Sync`); `ListsModels` is set, so its list is the models picked for it. `agentplug` compiles each in moejs (via `jsmod`, as gateway middleware is), reloads it when plugins.json or the file changes, and keeps why one didn't load. `plugged` makes each an `Agent` with `Plugin` set, listed after magpie's own; an id one of magpie's own agents has is refused (`PluginErrors`). `connect` is given each model as `magpieModels` builds it, with `/v1/models`' `native_endpoints` (`provider.NativeEndpoints`, carried as `catalog.Model.Endpoints`) and `pricing` (`catalog.OpenRouterPricing` of the same `EntryPricer` price), each left out when not known ([`plugged_connect_facts_test.go`](../../internal/agent/plugged_connect_facts_test.go)). | [`agentplug.go`](../../internal/agentplug/agentplug.go), [`plugged.go`](../../internal/agent/plugged.go) || Environment-only agents | Agents that read the gateway only from the environment get a `Launch` command. Antigravity CLI (agy) also gets a function `agy` in each shell's profile while it is on one of magpie's models, so typing `agy` in a new terminal starts it on magpie (bestony on Discord). The function runs `magpie agy run`, which starts the agy on PATH with `GEMINI_API_KEY`, `GOOGLE_GEMINI_BASE_URL` and `--model` (no `--model` when the user gives one) while settings.json's model is still magpie's, and unchanged otherwise. PowerShell's asks `magpie agy env` for them, since the Windows app is a GUI program PowerShell doesn't wait for. `Typed` says the function is there; the row then says plain `agy` works in a new terminal, and the `Launch` command is for a terminal open before. agy has no settings-only route: 1.4.7 refuses to start without `GEMINI_API_KEY` in the environment even with a key on the custom model. Cursor Private Inference instead gets user-level variables (`cursorLocalOn`, `KeepCursorLocalEnv`), and magpie writes none of Cursor's own files. It is found by its product.json in the apps folders, in the folder Windows' list of installed programs names (`cursorLocalInstalls`, any folder picked in its installer), or as its Linux AppImage (`Cursor_Private_Inference-…AppImage`) in the folders downloads are kept in (#1254). Its effort field is kept in magpie (`provider.AgentEffort`) and asked by the gateway, its levels those of the models it lists (`cursorLocalEfforts`, #1003). | [`cursorlocal.go`](../../internal/agent/cursorlocal.go) || Claude Science | Its daemon (`claude-science`) reads the API's address only from its environment's `ANTHROPIC_BASE_URL` and has no setting for it. Connect restarts the daemon with that variable set to the gateway (`scienceOn`: `stop`, then `serve --detached --no-browser` on the port `status` said it was on) and notes the daemon in `claude-science.json` (url, pid, port); Disconnect restarts it without the variable, one in magpie's own environment taken out too. No variable is set for the user and no file of the app's is written. Setting it again while magpie's daemon runs on this gateway does nothing (`Pick` sets the field after `connect`). `KeepClaudeScience` starts it again on the gateway, on its port, when it isn't running (a restart of the computer), each minute while magpie serves; it never stops one running. `Check` reads the daemon's `operon.lock`, not `status` (seconds for a 130 MB Bun program), and calls a daemon with another pid drift: the app's window, opened while none ran, starts its own without the variable. It is found in the Mac app's bundle (`Claude Science.app/Contents/Resources/bin`), `%LOCALAPPDATA%\Programs\ClaudeScience` on Windows, `~/.local/bin`, else on PATH. The app still needs its own Claude sign-in; the gateway never passes it on (see gateway-routing). | [`claudescience.go`](../../internal/agent/claudescience.go), [`science.go`](../../internal/gateway/science.go) |@@ -120,7 +120,7 @@ something else shows up as drift.- Codex signed in to ChatGPT and not connected still gets `openai_base_url` while more of its ChatGPT accounts are on in magpie (`failover`, stash `codex.failover`; with a CC Switch mirror as its provider, the mirror's `base_url` and `codex.mirror_failover`), so a turn its own account has no allowance for goes on to the next — never for a Codex that reaches the gateway from another machine, where that path takes a named key alone and the failed-over turn came back a 401 (#2145, `TestCodexFailoverBeyondLoopbackNotWritten`); Sync takes one it wrote before off again. That Codex is `FailingOver`: not `Wired`, yet its requests go through magpie. The Agents row says so and what turns it off (`FailoverSaid` in the CLI and TUI, `failover` in `/api/state`, a button to Providers › Codex in the GUI), and the gateway hands it only its own models from `/backend-api/codex/models` (`CodexOwnOnly`, set on `gateway.CodexOwnOnly` by main; its ETag carries `provider.CodexOwnListTag`, and Sync ages a `models_cache.json` without it). A connected WSL Codex shares the gateway path, so while one is connected every Codex gets magpie's models (#1385). A base URL the user wrote by hand (#856) isn't failover's and stays a plain not-connected row. A Codex the user disconnected gets no failover till they connect it again. The app serving the gateway takes failover out as it quits (`EndFailover`, `EndCodexFailover` in `OnShutdown`), so a Codex left on its own goes straight to OpenAI rather than retrying a gateway that's gone (Leon920717 on X); the next start's Sync writes it again. Codex's app-server read the old base URL as it started and keeps it, and `KeepCodexDaemonCurrent` ends with magpie, so `EndCodexFailover` restarts it there when no codex session is on it (`codexDaemonCheck`); with one on it, it stays on the gone gateway until the user restarts it (thisisvainxx on X: "several restarts"). Every restart magpie makes runs `codex app-server daemon restart` as its own responsible process on macOS (`proc.CombinedOutputOwn`, a disclaimed `posix_spawn`): the daemon works in the folder of each codex attached to it, and as magpie's child the first codex in ~/Desktop had macOS ask for the Desktop folder in magpie's name (reformed9448 on Discord; `TestRestartedCodexDaemonIsNotMagpies`). A magpie built without cgo (the CLI) still restarts it as its own child. A connected Codex keeps magpie as it quits: its model is one of magpie's, and Disconnect is what puts its own config back. A magpie that ends without quitting (killed, a crash, `magpie serve`) leaves failover in place.- A Codex thread keeps the provider it was started on. While a magpie model is on, CC Switch's provider tables go through magpie too (`takeTables`), and get their own base URL back when Codex steps off magpie (`giveTables`, stash `codex.tables`). CC Switch's OpenAI mirror (a table of another id, `name = "OpenAI"`, `requires_openai_auth`, no `base_url`) isn't reached by `openai_base_url`, which takes only the built-in provider to magpie: a thread started on it and reopened went straight to ChatGPT, which refused the magpie model picked in it, and magpie never saw the request (#1796). While Codex goes to magpie by the base URL, `takeMirrors` gives each such mirror magpie's ChatGPT backend as its `base_url` (stash `codex.mirrors`), and `giveMirrors` takes it off again; a mirror a profile names, or one whose `base_url` was changed since, stays as it is. Moving the threads onto another provider is the Sessions page's Move (#887).- An agent's config is written in the form the installed version reads, taken from what that version declares, not the latest one. VSCodium has no Copilot Chat of its own, and the Marketplace's last one (0.48.1) has no Custom Endpoint provider, only OpenAI Compatible (`customoai`, #1014). magpie reads the provider list in the package.json of the `github.copilot-chat` installed under `~/.vscode-oss/extensions` (`vscodeChatOf`). It writes its group for `customendpoint` when that is declared, for `customoai` when only that is, with each model's window as `maxInputTokens` + `maxOutputTokens` and the token as `x-api-key` (that version drops an Authorization in `requestHeaders`). A missing or unreadable extension keeps `customendpoint`. Sync rewrites a group written for the other provider, and Check reports it, as it does a Copilot Chat declaring neither. That Copilot Chat registers its providers only while signed in to GitHub with a personal Copilot plan, which the Notice says.-- Tuned settings are written only on the user's click, never by Sync or Connect. The value there before is stashed once (`tune.<agent>.<knob>[.<model>]` in `stash.json`), so Undo puts it back, or takes the key out (and a `modelSettings` entry left empty). A value the user changed after the click is theirs: Undo then only forgets the stash. A variable that comes before the setting (`CLAUDE_CODE_AUTO_COMPACT_WINDOW`, `FORCE_PROMPT_CACHING_5M`, `CLAUDE_CODE_PROMPT_CACHE_TTL`, `CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL`, in settings.json's `env` or magpie's own) is shown as `locked` and Apply refuses, since the setting would change nothing. Claude Code compacts at the smaller of the window set and the model's own (its `/autocompact` says "capped to 200k by model"), so advice starts from that, and a model that isn't Claude's has no window here (magpie's own compact wiring serves it). Codex's window is the one magpie's catalog lists for each model it ran (typed, or the vendor's), and with none in config.toml it runs now at what magpie tells Codex (`provider.CompactFor`, else Long conversations in the agent's opened row, as `codexcat` writes it); a model of magpie's whose window isn't known caps nothing short of 1M (or the user's own larger value), never the largest prompt seen (zhemu on Discord: a 1M model at 750K was offered up to 410K), and only Codex's own models, outside the catalog, keep 272K or the largest prompt (`codexWindow`, `TestTuneWindowsAreTheUsers`). Advice changes a value only when the replay saves 3% or more, and of the windows within 1% of the cheapest takes the largest; with the compactions timed, it never advises a window that compacts more often than the one now, so never a longer wait: of the windows that compact no more often it takes the cheapest, and of those within 3% of that (`sameCost`, the same bar as changing at all) the one that compacts least, the larger of two that compact as often. Tokens and seconds share no unit the files measure, so the advice doesn't trade one for the other at a guessed rate; a cheaper window that waits longer is said with its wait in the row and the picker, for the user to choose. The wait per compaction is taken as the same at every window: the files time compactions only near the window the user ran with, too narrow to fit how it grows with the prompt. Tokens are weighed as billed: cache reads 0.1, 5-minute writes 1.25, hour writes 2, output 5 for Claude; reads 0.1, writes 1, output 8 otherwise.+- Tuned settings are written only on the user's click, never by Sync or Connect. A window that is Long conversations (`TuneLong`) is stashed once as Long conversations was (`tune.long.compact`, one stash for both agents, as the value is one), and Undo puts it back, Full window included, unless the user changed it since. Codex's card is always Long conversations, unless config.toml has a `model_auto_compact_token_limit` of the user's, which Codex stops at first: that one is `locked`. A limit an older magpie's tune wrote there (`tune.codex.compact`) is moved by `tuneMigrateCodex`, from Codex's Sync and from the card: Long conversations at magpie's default, or under Full window, takes it as the user's own choice; one the user typed takes it only when it is lower, where Codex compacted; the file gets back what it had; and a limit the user changed after the click is theirs and stays. Claude Code's `CLAUDE_CODE_AUTO_COMPACT_WINDOW` is Long conversations when magpie wrote it from that value (`claude.compact_long` beside `claude.compact_window`, set by `writeCompact`), and its top-level `autoCompactWindow` when magpie wrote it (`claude.compact_default`) and it equals Long conversations; a window from a provider's Compact at, or the user's own, stays `locked`. A Claude model's own `modelSettings` window, under no such variable, is still per model, since Long conversations doesn't reach Claude models. The value there before is stashed once (`tune.<agent>.<knob>[.<model>]` in `stash.json`), so Undo puts it back, or takes the key out (and a `modelSettings` entry left empty). A value the user changed after the click is theirs: Undo then only forgets the stash. A variable that comes before the setting (`CLAUDE_CODE_AUTO_COMPACT_WINDOW`, `FORCE_PROMPT_CACHING_5M`, `CLAUDE_CODE_PROMPT_CACHE_TTL`, `CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL`, in settings.json's `env` or magpie's own) is shown as `locked` and Apply refuses, since the setting would change nothing. Claude Code compacts at the smaller of the window set and the model's own (its `/autocompact` says "capped to 200k by model"), so advice starts from that, and a model that isn't Claude's has no window here (magpie's own compact wiring serves it). Codex's window is the one magpie's catalog lists for each model it ran (typed, or the vendor's), and with none in config.toml it runs now at what magpie tells Codex (`provider.CompactFor`, else Long conversations in the agent's opened row, as `codexcat` writes it); a model of magpie's whose window isn't known caps nothing short of 1M (or the user's own larger value), never the largest prompt seen (zhemu on Discord: a 1M model at 750K was offered up to 410K), and only Codex's own models, outside the catalog, keep 272K or the largest prompt (`codexWindow`, `TestTuneWindowsAreTheUsers`). Advice changes a value only when the replay saves 3% or more, and of the windows within 1% of the cheapest takes the largest; with the compactions timed, it never advises a window that compacts more often than the one now, so never a longer wait: of the windows that compact no more often it takes the cheapest, and of those within 3% of that (`sameCost`, the same bar as changing at all) the one that compacts least, the larger of two that compact as often. Tokens and seconds share no unit the files measure, so the advice doesn't trade one for the other at a guessed rate; a cheaper window that waits longer is said with its wait in the row and the picker, for the user to choose. The wait per compaction is taken as the same at every window: the files time compactions only near the window the user ran with, too narrow to fit how it grows with the prompt. Tokens are weighed as billed: cache reads 0.1, 5-minute writes 1.25, hour writes 2, output 5 for Claude; reads 0.1, writes 1, output 8 otherwise.- A plugin's agent writes each key in place (JSON, YAML or env), the user's comments and other keys kept. An object or array `connect` returns is taken as its JSON text (`agentplug.keys`), so it is written in the order the plugin gave it, not sorted as a Go map would be: Kilo lists its effort variants in key order (#1890, `TestPluggedKeepsPluginOrder`). What each key held before the first write is stashed under `plugin:<id>:<path>`, typed, and its own model or Disconnect puts every key back and takes out the ones that weren't there; the file is never written whole. A `connect` that throws or takes over a second writes nothing and says why. Its gateway key is `magpie-<id>` (`agentKeyAt`), and usage names its requests by that key or by its `ua` words (`usage.PluginAgents`). Its `agent.library` (instructions, `mcp` with `mcpFormat`, skills) gives it the Library's three as well, written by `internal/library` as any agent's are ([library](library.md)); a `mcpFormat` outside `agentplug.MCPFormats`, or an `mcp` without one, keeps the plugin from loading. Turning the plugin off or removing it (`provider.SetPluginOff`, `provider.RemovePlugin`, from the CLI or the Plugins page) first disconnects its agent as `magpie <agent> default` does (`provider.PluginAgentGoing`, set to `agent.UnwirePlugin` in [`plugged_gone.go`](../../internal/agent/plugged_gone.go)), since without the plugin magpie no longer knows the agent (#3810); a plugin already off is read from its module as it is, and one whose module is gone puts back each file whose stash names its spec. A failure keeps the plugin as it was. On again, the agent stays as the user had it, and connecting it puts back the model it was on (Disconnect's `.reconnect`). The stash records the plugin's spec and the file's format, so `magpie <id> default` for the agent of a plugin deleted on disk puts the file back from the stash alone (`agent.RestoreGone`; an older stash's format is its file's name, `agentplug.FormatOf`); a file that no longer holds the gateway's key is the user's and left alone, and one that can't be read is put back over by nothing; with the plugin only switched off, it says the agent is off magpie already, not "unknown agent" (`TestPluginOffPutsItsAgentBack`, `TestRestoreGoneAgent`, `TestGoneAgentDefault`).- StepCode config root resolves to the parent of an absolute `STEP_CODING_AGENT_DIR` (agent resources directory differs from config root; relative values ignored), or `STEPCODE_CONFIG_DIR` under home when native, defaulting to `~/.stepcode` ([`stepcode.go`](../../internal/agent/stepcode.go)). Project configs override global configs in StepCode, but magpie manages global configuration only (`config.toml` and `models.json`). Detection is strictly directory-only via `agentDir`, avoiding collision with Smallstep's bare `step` command on `PATH`. Wiring performs an atomic two-file edit (`models.json` provider block and `config.toml` top-level defaults/scope) backed by `stash.json`. Custom fields within `providers.magpie` are preserved during sync, and the original provider block is restored on disconnect. A renamed provider's `magpie/<old>/` entries in `enabledModels` follow it, a glob or a thinking level included, and the scope remembered for disconnect follows too; the user's other entries stay. Disconnect restores original defaults, preserves user native changes and custom scope edits, and removes newly created files only when empty.- MothX's folder is `$MOTHX_DIR` as it is (no `~`), else `%APPDATA%\mothx` on Windows, else `~/.mothx`; a WSL distro's is its `~/.mothx` ([`mothx.go`](../../internal/agent/mothx.go)). Its `thinkingFormat` is `openai` unless the user set one: with it empty, MothX picks Qwen's `enable_thinking`, DeepSeek's `thinking` or Doubao's levels by the model id, which for magpie's ids says nothing of the vendor that serves them. MothX's `/model` and `/statusline … global` rewrite the whole file, so Disconnect after one takes out magpie's provider, the pick and a `providers` left empty (MothX omits an empty one), and keeps the rest.@@ -163,7 +163,7 @@ go test -tags nogui ./internal/agent -run 'TestCodexFailoverOnlyKeepsOwnModels|Tgo test -tags nogui ./internal/agent -run 'TestDisconnectStaysThroughSync|TestCodexDisconnectStaysWithAccountsOn|TestCodexAPIDisconnectStays'go test -tags nogui ./internal/tune ./internal/agent -run 'TestCompact|TestCacheTTL|TestTune'go test -tags nogui ./internal/sessions -run 'CompactTook'-node --test internal/gui/tests/context-tune.test.cjs+node --test internal/gui/tests/context-tune.test.cjs internal/gui/tests/compact-one-value.test.cjsnode --test internal/gui/tests/agent-connect.test.cjs internal/gui/tests/agent-disconnect-preview.test.cjs internal/gui/tests/claude-signin.test.cjs internal/gui/tests/agent-failover.test.cjs internal/gui/tests/agent-proxied.test.cjs internal/gui/tests/plugin-agent.test.cjs```diff --git a/internal/agent/claude.go b/internal/agent/claude.goindex a240d5317..6f6b3a21b 100644--- a/internal/agent/claude.go+++ b/internal/agent/claude.go@@ -879,8 +879,11 @@ func claudeIn(at place) *Agent {cur := env(claudeCompactEnv)return cur != "" && cur == stashLoad()[compactKey]}+ // set while the window magpie wrote is Long conversations' (not a+ // provider's Compact at): tune's card reads it as that one value+ compactLongKey := at.key("claude.compact_long")dropCompact := func() error {- defer forget(compactKey)+ defer forget(compactKey, compactLongKey)if compactOurs() {return edit.DelJSON(path, "env."+claudeCompactEnv)}@@ -909,8 +912,9 @@ func claudeIn(at place) *Agent {// model (settings.Compact), none under Full windowmain := mainModel()n := provider.CompactSet(main)+ long := falseif s := settings.Load(); n == 0 && !claudeModel(main) && !provider.ClaudeGroup(main) {- n = s.Compact()+ 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// would take precedence over; one typed in magpie doesn't (#876).@@ -927,6 +931,11 @@ func claudeIn(at place) *Agent {}w := strconv.Itoa(n)stash(map[string]string{compactKey: w})+ if long {+ stash(map[string]string{compactLongKey: "1"})+ } else {+ forget(compactLongKey)+ }if env(claudeCompactEnv) == w {return nil}diff --git a/internal/agent/claude_compact_test.go b/internal/agent/claude_compact_test.goindex f3345084c..79e86e6d2 100644--- a/internal/agent/claude_compact_test.go+++ b/internal/agent/claude_compact_test.go@@ -122,9 +122,23 @@ func TestClaudeCompactAt(t *testing.T) {must(provider.SetCompactAt(400000))must(a.Field("model").Set("v/big"))expect("every model at 400K", "400000")+ // the Usage page's card reads that as Long conversations, one value+ // with the agent's settings sheet (7eleven); a provider's own is not it+ tuned := func() TuneSetting {+ t.Helper()+ s, err := TuneRead(home, "claude", TuneCompact, "claude-opus-5-5")+ must(err)+ return s+ }+ if s := tuned(); s.Value != "400000" || s.Source != TuneLong || s.Locked != "" {+ t.Fatalf("tune reads magpie's 400K as %+v", s)+ }must(provider.SetModelCompacts("v", map[string]int{"*": 600000, "flash": 200000}))must(a.Sync())expect("the provider's", "600000")+ if s := tuned(); s.Locked != claudeCompactEnv || s.Value != "600000" {+ t.Fatalf("tune reads the provider's 600K as %+v", s)+ }must(a.Field("model").Set("v/flash[1m]"))expect("the model's own", "200000")must(a.Field("model").Set("v/claude-opus-5-5[1m]"))diff --git a/internal/agent/codex.go b/internal/agent/codex.goindex 16f21914c..4be12e0b2 100644--- a/internal/agent/codex.go+++ b/internal/agent/codex.go@@ -543,6 +543,11 @@ func codexIn(at place) *Agent {// Codex's background compaction, as Settings has it (#2490): written// where Codex is routed through magpie, taken back where it isn'tasyncCompaction := func(routed bool) error {+ // a compact limit tune wrote here before goes to Long+ // conversations, the one window magpie keeps (7eleven)+ if at.id == "" && at.spell == nil {+ tuneMigrateCodex(at.home)+ }s := settings.Load()on := s.CodexAsyncCompact && routedreturn codexAsyncSync(path, at.key("codex.async"), routed, s.CodexAsyncCompact, s.CodexAsyncCompactPercent, on && codexAsyncTableOK(at))diff --git a/internal/agent/codex_home_env_test.go b/internal/agent/codex_home_env_test.goindex cb22ad22e..6d9288f2d 100644--- a/internal/agent/codex_home_env_test.go+++ b/internal/agent/codex_home_env_test.go@@ -42,12 +42,13 @@ func TestCodexHomeEnvTakesThePick(t *testing.T) {if m := StandIn("codex", "gpt-5"); m != "fake/m1" {t.Fatalf("the gateway's stand-in for Codex is %q, read from somewhere else", m)}- if err := TuneApply(home, "codex", TuneCompact, "", "200000"); err != nil {+ // tune reads a compact limit of the user's from $CODEX_HOME's config,+ // which comes before magpie's window, and writes none of its own+ if err := os.WriteFile(filepath.Join(ch, "config.toml"), append([]byte("model_auto_compact_token_limit = 180000\n"), b...), 0o644); err != nil {t.Fatal(err)}- b, _ = os.ReadFile(filepath.Join(ch, "config.toml"))- if !strings.Contains(string(b), "model_auto_compact_token_limit = 200000") {- t.Fatalf("tune didn't write $CODEX_HOME/config.toml:\n%s", b)+ if s, _ := TuneRead(home, "codex", TuneCompact, ""); s.Locked != codexCompactKey || s.Value != "180000" {+ t.Fatalf("tune didn't read $CODEX_HOME/config.toml: %+v", s)}if _, err := os.Stat(filepath.Join(home, ".codex")); !os.IsNotExist(err) {var names []stringdiff --git a/internal/agent/tune.go b/internal/agent/tune.goindex 677e88e3c..add388858 100644--- a/internal/agent/tune.go+++ b/internal/agent/tune.go@@ -2,9 +2,18 @@ package agent// The settings tune advises (internal/tune), as each agent's config has// them, and putting one in on the user's say: Claude Code's auto-compact-// window for a model and its cache lifetimes, Codex's auto-compact limit.-// What was there before is stashed, so Undo puts it back; a variable that-// takes precedence over the setting is told of, never written over.+// window for a model and its cache lifetimes, and where Codex and Claude+// Code compact. What was there before is stashed, so Undo puts it back; a+// variable that takes precedence over the setting is told of, never+// written over.+//+// Where Codex compacts, and Claude Code wherever magpie's own window is+// what it runs at, is one value: Long conversations (settings.CompactAt,+// FullContext), which Sync writes into each agent's config. Tune reads and+// 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.import ("encoding/json"@@ -15,6 +24,8 @@ import ("strings""github.com/yetone/magpie/internal/edit"+ "github.com/yetone/magpie/internal/provider"+ "github.com/yetone/magpie/internal/settings")// The settings tune knows.@@ -28,7 +39,8 @@ const (type TuneSetting struct {Value string `json:"value,omitempty"` // "" when nothing sets it// Where Value comes from: settings (the agent's own config file),- // model (Claude Code's modelSettings for the model), env+ // model (Claude Code's modelSettings for the model), env, or long+ // (TuneLong: magpie's Long conversations, "" under Full window)Source string `json:"source,omitempty"`// Locked names the variable that takes precedence over the setting,// which tune leaves as it is: putting the advice in would change nothing@@ -37,6 +49,112 @@ type TuneSetting struct {Ours bool `json:"ours,omitempty"`}+// TuneLong is the Source of a window that is magpie's Long conversations,+// which Apply and Undo change in magpie's settings, not in the agent's file.+const TuneLong = "long"++// codexCompactKey is the key tune wrote Codex's window to before it went+// to Long conversations; one the user wrote comes before magpie's window.+const codexCompactKey = "model_auto_compact_token_limit"++// tuneLongKey is the stash of Long conversations as it was before tune+// put a window in it, shared by every agent's card, as the value is.+const tuneLongKey = "tune.long.compact"++type tuneLong struct {+ CompactAt int `json:"compactAt"`+ Full bool `json:"full"`+ Set int `json:"set"`+}++func tuneLongStashed() (tuneLong, bool) {+ raw := stashLoad()[tuneLongKey]+ var st tuneLong+ if raw == "" || json.Unmarshal([]byte(raw), &st) != nil {+ return tuneLong{}, false+ }+ return st, true+}++// longValue is Long conversations' window as the setting reads: "" under+// Full window, each model's whole one.+func longValue(s settings.Settings) string {+ if n := s.Compact(); n > 0 {+ return strconv.Itoa(n)+ }+ 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+}++// 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 {+ s := settings.Load()+ st, ok := tuneLongStashed()+ if !ok {+ st = tuneLong{CompactAt: s.CompactAt, Full: s.FullContext}+ }+ st.Set = n+ b, _ := json.Marshal(st)+ stash(map[string]string{tuneLongKey: string(b)})+ 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()+ if !ok {+ return fmt.Errorf("magpie didn't set Long conversations")+ }+ defer forget(tuneLongKey)+ if !longOurs(settings.Load()) {+ return nil+ }+ if st.Full {+ return provider.SetFullContext(true)+ }+ return provider.SetCompactAt(st.CompactAt)+}++// tuneMigrateCodex moves a model_auto_compact_token_limit tune wrote into+// Codex's config.toml before (tune.codex.compact) into Long conversations,+// and puts back what the file had. Long conversations at magpie's default+// takes it, as the user's own choice; one the user set takes it only when+// it is lower, which is where Codex compacted (it stops at the lesser of+// the limit and the window it is told), so nothing changes for them. A+// limit the user changed after tune wrote it is theirs and stays.+func tuneMigrateCodex(home string) {+ st, ok := tuneStashed("codex", TuneCompact, "")+ if !ok {+ return+ }+ p := tunePlace{path: filepath.Join(here(home).codexHome(), "config.toml"), key: codexCompactKey, toml: true}+ defer forget(tuneKey("codex", TuneCompact, ""))+ v, has := p.get()+ if !has || strings.Trim(v, `"'`) != st.Set {+ return+ }+ if n, err := strconv.Atoi(st.Set); err == nil && n > 0 {+ s := settings.Load()+ if s.CompactAt == 0 || s.FullContext || n < s.Compact() {+ if err := longApply(n); err != nil {+ return+ }+ }+ }+ if st.Had {+ _ = edit.SetTOMLTop(p.path, edit.KV{Path: p.key, Value: tomlRaw(st.Raw)})+ return+ }+ _ = edit.DelTOMLTop(p.path, p.key)+}+// tuneStash is what a setting was before tune put one in.type tuneStash struct {Had bool `json:"had"`@@ -89,7 +207,9 @@ func tuneWhere(home, agent, knob, model string) (tunePlace, error) {}case "codex":if knob == TuneCompact {- return tunePlace{path: filepath.Join(here(home).codexHome(), "config.toml"), key: "model_auto_compact_token_limit", toml: true, number: true}, nil+ // the user's own limit in config.toml, which comes before Long+ // conversations; tune itself writes only the latter+ return tunePlace{path: filepath.Join(here(home).codexHome(), "config.toml"), key: codexCompactKey, toml: true, number: true}, nil}}return tunePlace{}, fmt.Errorf("%s has no setting %q tune can put in", agent, knob)@@ -117,9 +237,26 @@ func TuneRead(home, agent, knob, model string) (TuneSetting, error) {if err != nil {return TuneSetting{}, err}+ if agent == "codex" && knob == TuneCompact {+ tuneMigrateCodex(home)+ var s TuneSetting+ if v, ok := p.get(); ok {+ // the user's own limit: Codex stops at it before the window+ // magpie tells it+ s.Value, s.Source, s.Locked = strings.Trim(v, `"'`), "settings", codexCompactKey+ return s, nil+ }+ st := settings.Load()+ return TuneSetting{Value: longValue(st), Source: TuneLong, Ours: longOurs(st)}, nil+ }var s TuneSettingfor _, k := range p.env {if v := p.envOf(k); v != "" && v != "0" && v != "false" {+ 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+ }s.Locked = ks.Value, s.Source = v, "env"if k == "FORCE_PROMPT_CACHING_5M" {@@ -135,8 +272,13 @@ func TuneRead(home, agent, knob, model string) (TuneSetting, error) {s.Source = "model"}} else if agent == "claude" && knob == TuneCompact {- // the top-level window serves every model with none of its own+ // the top-level window serves every model with none of its+ // own: magpie's Long conversations where magpie wrote itif 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+ }s.Value, s.Source = v, "settings"}}@@ -148,6 +290,28 @@ func TuneRead(home, agent, knob, model string) (TuneSetting, error) {return s, nil}+// claudeLongEnv says the CLAUDE_CODE_AUTO_COMPACT_WINDOW Claude Code has+// is the one magpie wrote in settings.json from Long conversations+// (writeCompact), not a provider's Compact at for the main model or the+// user's own.+func claudeLongEnv(path, v string) bool {+ in, ok := edit.GetJSON(path, "env."+claudeCompactEnv)+ m := stashLoad()+ return ok && in == v && v == m["claude.compact_window"] && m["claude.compact_long"] == "1"+}++// claudeLongWindow says the window at key in Claude Code's settings.json+// is the one magpie wrote there (its stash under stashKey) from Long+// conversations, not a provider's Compact at for the main model or the+// user's own.+func claudeLongWindow(path, key, stashKey string) bool {+ v, ok := edit.GetJSON(path, key)+ if !ok || v == "" || v != stashLoad()[stashKey] {+ return false+ }+ return v == longValue(settings.Load())+}+func tuneStashed(agent, knob, model string) (tuneStash, bool) {raw := stashLoad()[tuneKey(agent, knob, model)]if raw == "" {@@ -172,6 +336,16 @@ func TuneApply(home, agent, knob, model, value string) error {if cur.Locked != "" {return fmt.Errorf("%s=%s is set and comes before the setting: take it out first", cur.Locked, cur.Value)}+ if cur.Source == TuneLong {+ n, err := strconv.Atoi(value)+ if err != nil || n <= 0 {+ return fmt.Errorf("%q is no token count", value)+ }+ 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)+ }var v any = valueif p.number {n, err := strconv.Atoi(value)@@ -209,6 +383,9 @@ func TuneUndo(home, agent, knob, model string) error {if err != nil {return err}+ if cur, _ := TuneRead(home, agent, knob, model); cur.Source == TuneLong {+ return longUndo()+ }st, ok := tuneStashed(agent, knob, model)if !ok {return fmt.Errorf("magpie didn't set %s", p.key)diff --git a/internal/agent/tune_test.go b/internal/agent/tune_test.goindex 4bc0e5cdf..a44365a27 100644--- a/internal/agent/tune_test.go+++ b/internal/agent/tune_test.go@@ -1,10 +1,14 @@package agentimport (+ "encoding/json""os""path/filepath""strings""testing"++ "github.com/yetone/magpie/internal/provider"+ "github.com/yetone/magpie/internal/settings")func tuneSandbox(t *testing.T) string {@@ -131,23 +135,248 @@ func TestTuneLockedByEnv(t *testing.T) {}}-// TestTuneCodexCompact: Codex's limit goes at the top of config.toml, the-// tables after it kept, and Undo puts the user's back.+// TestTuneCodexCompact: where Codex compacts is Long conversations, one+// value with the agents' settings sheet (7eleven): the card reads it, Use+// sets it and writes no limit of tune's own beside it into config.toml,+// and Undo puts Long conversations back as it was.func TestTuneCodexCompact(t *testing.T) {home := tuneSandbox(t)path := filepath.Join(home, ".codex", "config.toml")- tuneWrite(t, path, "model = \"gpt-5.5\"\nmodel_auto_compact_token_limit = 200000\n\n[features]\nx = true\n")+ tuneWrite(t, path, "model = \"gpt-5.5\"\n\n[features]\nx = true\n")+ if err := provider.SetCompactAt(200000); err != nil {+ t.Fatal(err)+ }+ s, err := TuneRead(home, "codex", TuneCompact, "")+ if err != nil || s.Value != "200000" || s.Source != TuneLong || s.Locked != "" || s.Ours {+ t.Fatalf("read %+v %v: want Long conversations' 200000", s, err)+ }if err := TuneApply(home, "codex", TuneCompact, "", "150000"); err != nil {t.Fatal(err)}- got := tuneFile(t, path)- if !strings.Contains(got, "model_auto_compact_token_limit = 150000") || strings.Index(got, "150000") > strings.Index(got, "[features]") || !strings.Contains(got, "x = true") {+ if got := settings.Load(); got.CompactAt != 150000 || got.FullContext {+ t.Fatalf("Long conversations after apply: %d full=%v, want 150000", got.CompactAt, got.FullContext)+ }+ if got := tuneFile(t, path); strings.Contains(got, codexCompactKey) || !strings.Contains(got, "x = true") {t.Fatalf("config.toml after apply:\n%s", got)}+ s, _ = TuneRead(home, "codex", TuneCompact, "")+ if s.Value != "150000" || s.Source != TuneLong || !s.Ours {+ t.Fatalf("read after apply %+v", s)+ }+ // the Claude Code card reads the same value where magpie's window is+ // what Claude Code runs at+ if err := TuneUndo(home, "codex", TuneCompact, ""); err != nil {+ t.Fatal(err)+ }+ if got := settings.Load(); got.CompactAt != 200000 {+ t.Fatalf("Long conversations after undo: %d, want 200000", got.CompactAt)+ }+ // Full window comes back as Full window+ if err := provider.SetFullContext(true); err != nil {+ t.Fatal(err)+ }+ if s, _ := TuneRead(home, "codex", TuneCompact, ""); s.Value != "" || s.Source != TuneLong {+ t.Fatalf("read under Full window %+v", s)+ }+ if err := TuneApply(home, "codex", TuneCompact, "", "400000"); err != nil {+ t.Fatal(err)+ }+ if got := settings.Load(); got.CompactAt != 400000 || got.FullContext {+ t.Fatalf("after apply under Full window: %+v", got.CompactAt)+ }if err := TuneUndo(home, "codex", TuneCompact, ""); err != nil {t.Fatal(err)}- if got := tuneFile(t, path); !strings.Contains(got, "model_auto_compact_token_limit = 200000") {- t.Fatalf("config.toml after undo:\n%s", got)+ if got := settings.Load(); !got.FullContext {+ t.Fatal("undo didn't put Full window back")+ }+ // a value the user set in the sheet after Use is theirs: Undo leaves it+ if err := TuneApply(home, "codex", TuneCompact, "", "300000"); err != nil {+ t.Fatal(err)+ }+ if err := provider.SetCompactAt(250000); err != nil {+ t.Fatal(err)+ }+ if err := TuneUndo(home, "codex", TuneCompact, ""); err != nil {+ t.Fatal(err)+ }+ if got := settings.Load(); got.CompactAt != 250000 || got.FullContext {+ t.Fatalf("undo wrote over the user's 250000: %d full=%v", got.CompactAt, got.FullContext)+ }+}++// TestTuneCodexOwnLimit: a model_auto_compact_token_limit the user wrote+// in config.toml stops Codex before magpie's window, so the card says so+// and Use changes nothing.+func TestTuneCodexOwnLimit(t *testing.T) {+ home := tuneSandbox(t)+ path := filepath.Join(home, ".codex", "config.toml")+ tuneWrite(t, path, "model_auto_compact_token_limit = 180000\n")+ s, _ := TuneRead(home, "codex", TuneCompact, "")+ if s.Locked != codexCompactKey || s.Value != "180000" {+ t.Fatalf("read %+v", s)+ }+ if err := TuneApply(home, "codex", TuneCompact, "", "150000"); err == nil {+ t.Fatal("applied under the user's own limit")+ }+ if got := tuneFile(t, path); !strings.Contains(got, "= 180000") {+ t.Fatalf("config.toml:\n%s", got)+ }+ if got := settings.Load(); got.CompactAt != 0 {+ t.Fatalf("Long conversations changed to %d", got.CompactAt)+ }+}++// TestTuneCodexMigrate: a limit an older magpie's tune wrote into+// config.toml goes into Long conversations and the file gets back what+// it had; one the user set in the sheet is kept unless tune's was lower,+// and a limit the user changed since is theirs and stays.+func TestTuneCodexMigrate(t *testing.T) {+ old := func(t *testing.T, home, file, set string, had bool, raw string) string {+ path := filepath.Join(home, ".codex", "config.toml")+ tuneWrite(t, path, file)+ b, _ := json.Marshal(tuneStash{Had: had, Raw: raw, Set: set})+ stash(map[string]string{tuneKey("codex", TuneCompact, ""): string(b)})+ return path+ }+ t.Run("default takes tune's", func(t *testing.T) {+ home := tuneSandbox(t)+ path := old(t, home, "model = \"gpt-5.5\"\nmodel_auto_compact_token_limit = 150000\n", "150000", false, "")+ s, _ := TuneRead(home, "codex", TuneCompact, "")+ if s.Value != "150000" || s.Source != TuneLong || !s.Ours {+ t.Fatalf("read %+v", s)+ }+ if got := settings.Load(); got.CompactAt != 150000 {+ t.Fatalf("Long conversations %d, want tune's 150000", got.CompactAt)+ }+ if got := tuneFile(t, path); strings.Contains(got, codexCompactKey) || !strings.Contains(got, "gpt-5.5") {+ t.Fatalf("config.toml:\n%s", got)+ }+ if _, ok := tuneStashed("codex", TuneCompact, ""); ok {+ t.Fatal("the old stash stayed")+ }+ // Undo still goes back to before tune+ if err := TuneUndo(home, "codex", TuneCompact, ""); err != nil {+ t.Fatal(err)+ }+ if got := settings.Load(); got.CompactAt != 0 || got.FullContext {+ t.Fatalf("after undo %d", got.CompactAt)+ }+ })+ t.Run("user's lower value kept", func(t *testing.T) {+ home := tuneSandbox(t)+ if err := provider.SetCompactAt(120000); err != nil {+ t.Fatal(err)+ }+ path := old(t, home, "model_auto_compact_token_limit = 150000\n", "150000", true, "200000")+ TuneRead(home, "codex", TuneCompact, "")+ if got := settings.Load(); got.CompactAt != 120000 {+ t.Fatalf("Long conversations %d, want the user's 120000", got.CompactAt)+ }+ if got := tuneFile(t, path); !strings.Contains(got, "= 200000") {+ t.Fatalf("config.toml didn't get the user's limit back:\n%s", got)+ }+ })+ t.Run("user's higher value gives way to where Codex compacted", func(t *testing.T) {+ home := tuneSandbox(t)+ if err := provider.SetCompactAt(400000); err != nil {+ t.Fatal(err)+ }+ old(t, home, "model_auto_compact_token_limit = 150000\n", "150000", false, "")+ TuneRead(home, "codex", TuneCompact, "")+ if got := settings.Load(); got.CompactAt != 150000 {+ t.Fatalf("Long conversations %d, want 150000", got.CompactAt)+ }+ })+ t.Run("limit the user changed stays", func(t *testing.T) {+ home := tuneSandbox(t)+ path := old(t, home, "model_auto_compact_token_limit = 170000\n", "150000", false, "")+ s, _ := TuneRead(home, "codex", TuneCompact, "")+ if s.Locked != codexCompactKey || s.Value != "170000" {+ t.Fatalf("read %+v", s)+ }+ if got := settings.Load(); got.CompactAt != 0 {+ t.Fatalf("Long conversations %d", got.CompactAt)+ }+ if got := tuneFile(t, path); !strings.Contains(got, "= 170000") {+ t.Fatalf("config.toml:\n%s", got)+ }+ })+}++// TestTuneClaudeLong: the window magpie wrote into Claude Code's env from+// Long conversations is that value, not a variable that locks the card:+// Use sets Long conversations; a window the user wrote there, or one+// from a provider's Compact at, still locks it.+func TestTuneClaudeLong(t *testing.T) {+ home := tuneSandbox(t)+ path := filepath.Join(home, ".claude", "settings.json")+ tuneWrite(t, path, `{"env": {"CLAUDE_CODE_AUTO_COMPACT_WINDOW": "272000"}}`)+ stash(map[string]string{"claude.compact_window": "272000", "claude.compact_long": "1"})+ s, err := TuneRead(home, "claude", TuneCompact, "claude-opus-5-5")+ if err != nil || s.Value != "272000" || s.Source != TuneLong || s.Locked != "" {+ t.Fatalf("read %+v %v: want Long conversations' 272000", s, err)+ }+ if err := TuneApply(home, "claude", TuneCompact, "claude-opus-5-5", "50000"); err == nil {+ t.Fatal("took a window under Claude Code's 100000")+ }+ if err := TuneApply(home, "claude", TuneCompact, "claude-opus-5-5", "400000"); err != nil {+ t.Fatal(err)+ }+ if got := settings.Load(); got.CompactAt != 400000 {+ t.Fatalf("Long conversations %d, want 400000", got.CompactAt)+ }+ if got := tuneFile(t, path); strings.Contains(got, "modelSettings") {+ t.Fatalf("wrote a model's own window beside Long conversations:\n%s", got)+ }+ // before Sync writes the env again the card says the new value, not+ // the old one as the user's+ if s, _ := TuneRead(home, "claude", TuneCompact, "claude-opus-5-5"); s.Value != "400000" || s.Source != TuneLong || s.Locked != "" {+ t.Fatalf("read before Sync %+v", s)+ }+ // Sync writes the env again; then the Codex card shows the same+ tuneWrite(t, path, `{"env": {"CLAUDE_CODE_AUTO_COMPACT_WINDOW": "400000"}}`)+ stash(map[string]string{"claude.compact_window": "400000"})+ if s, _ := TuneRead(home, "claude", TuneCompact, "claude-opus-5-5"); s.Value != "400000" || s.Source != TuneLong || !s.Ours {+ t.Fatalf("read after apply %+v", s)+ }+ if s, _ := TuneRead(home, "codex", TuneCompact, ""); s.Value != "400000" || s.Source != TuneLong || !s.Ours {+ t.Fatalf("codex read after the Claude card's apply %+v", s)+ }+ if err := TuneUndo(home, "claude", TuneCompact, "claude-opus-5-5"); err != nil {+ t.Fatal(err)+ }+ if got := settings.Load(); got.CompactAt != 0 {+ t.Fatalf("after undo %d", got.CompactAt)+ }+ // the user's own env value+ tuneWrite(t, path, `{"env": {"CLAUDE_CODE_AUTO_COMPACT_WINDOW": "272000"}}`)+ forget("claude.compact_window", "claude.compact_long")+ if s, _ := TuneRead(home, "claude", TuneCompact, "claude-opus-5-5"); s.Locked != "CLAUDE_CODE_AUTO_COMPACT_WINDOW" {+ t.Fatalf("the user's env read %+v", s)+ }+ // magpie's, from a provider's Compact at, not Long conversations+ tuneWrite(t, path, `{"env": {"CLAUDE_CODE_AUTO_COMPACT_WINDOW": "150000"}}`)+ stash(map[string]string{"claude.compact_window": "150000"})+ forget("claude.compact_long")+ if s, _ := TuneRead(home, "claude", TuneCompact, "claude-opus-5-5"); s.Locked != "CLAUDE_CODE_AUTO_COMPACT_WINDOW" {+ t.Fatalf("a provider's window read %+v", s)+ }+}++// TestTuneCodexMigrateOnSync: the move happens when magpie writes Codex's+// config, without the Usage page opened, so Codex runs at the one window.+func TestTuneCodexMigrateOnSync(t *testing.T) {+ home, read := codexHome(t, "", "model_auto_compact_token_limit = 150000\n")+ b, _ := json.Marshal(tuneStash{Set: "150000"})+ stash(map[string]string{tuneKey("codex", TuneCompact, ""): string(b)})+ if err := codex(home).Fields[0].Set("fake/m1"); err != nil {+ t.Fatal(err)+ }+ if cfg := read(); strings.Contains(cfg, codexCompactKey) || !strings.Contains(cfg, `model = "fake/m1"`) {+ t.Fatalf("config.toml after a sync:\n%s", cfg)+ }+ if got := settings.Load(); got.CompactAt != 150000 {+ t.Fatalf("Long conversations %d, want tune's 150000", got.CompactAt)}}diff --git a/internal/gui/assets/context.js b/internal/gui/assets/context.jsindex 325777723..d0362f9f0 100644--- a/internal/gui/assets/context.js+++ b/internal/gui/assets/context.js@@ -1484,6 +1484,7 @@const note = el("div", "ctx-tune-src");title.after(note);if (set.locked) note.textContent = t("{name} is set and comes first", { name: set.locked });+ else if (set.source == "long") note.textContent = t("Long conversations, shared by Codex and Claude Code");else if (set.ours) note.textContent = t("Set by magpie");else if (set.value && a.compact && +set.value > a.compact.window && a.compact.window) note.textContent = t("You set {value}; the model's {window} comes first", { value: show(set.value), window: fmtK(a.compact.window) });else if (set.value) note.textContent = t("You set {value}", { value: show(set.value) });@@ -1526,10 +1527,8 @@go.onclick = () => send("apply", lean.value);foot.append(go);}- // a window of the reader's own (#1860): one who would spend some tokens- // for fewer compactions picks it from the same replay the advice comes- // from, each value with what it spends past the leanest and how often- // it would have compacted in the range, both estimates+ // a window of the reader's own (#1860), from the same replay: each+ // value's tokens past the leanest and compactions, both estimatesconst pts = (a.compact && a.compact.curve) || [];if (pts.length > 1 && !set.locked) {const other = el("button", "text ctx-tune-pick", t("Other window…"));diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.jsindex 549a27383..8be2f299d 100644--- a/internal/gui/assets/i18n.js+++ b/internal/gui/assets/i18n.js@@ -141,6 +141,7 @@ const I18N = {"Put back": "已恢复","Use {value}": "使用 {value}","Replaces your {value}; Undo puts it back": "会替换你的 {value};撤销可恢复",+ "Long conversations, shared by Codex and Claude Code": "「长对话」,Codex 和 Claude Code 共用","1 call": "1 次调用","Up to {pct} fewer": "最多少 {pct}","Not enough calls in this range to tune on": "这段时间的调用太少,还算不出建议",@@ -4186,6 +4187,7 @@ const I18N = {"Put back": "已復原","Use {value}": "使用 {value}","Replaces your {value}; Undo puts it back": "會取代你的 {value};復原可還原",+ "Long conversations, shared by Codex and Claude Code": "「長對話」,Codex 與 Claude Code 共用","1 call": "1 次呼叫","Up to {pct} fewer": "最多少 {pct}","Not enough calls in this range to tune on": "這段時間的呼叫太少,還算不出建議",@@ -8206,6 +8208,7 @@ const I18N = {"Put back": "元に戻しました","Use {value}": "{value} にする","Replaces your {value}; Undo puts it back": "あなたの {value} を置き換えます。取り消すと戻ります",+ "Long conversations, shared by Codex and Claude Code": "「長い会話」。Codex と Claude Code で共通","1 call": "1 回の呼び出し","Up to {pct} fewer": "最大 {pct} 減","Not enough calls in this range to tune on": "この期間は呼び出しが少なく、まだ調整できません",@@ -12233,6 +12236,7 @@ const I18N = {"Put back": "Zurückgesetzt","Use {value}": "{value} verwenden","Replaces your {value}; Undo puts it back": "Ersetzt dein {value}; Rückgängig stellt es wieder her",+ "Long conversations, shared by Codex and Claude Code": "„Lange Unterhaltungen“, die Codex und Claude Code teilen","1 call": "1 Aufruf","Up to {pct} fewer": "Bis zu {pct} weniger","Not enough calls in this range to tune on": "Zu wenige Aufrufe in diesem Zeitraum zum Abstimmen",diff --git a/internal/gui/tests/compact-one-value.test.cjs b/internal/gui/tests/compact-one-value.test.cjsnew file mode 100644index 000000000..03dc432e0--- /dev/null+++ b/internal/gui/tests/compact-one-value.test.cjs@@ -0,0 +1,137 @@+// Run with Node's test runner and Playwright on the module path; see README.md.+// Where Codex compacts is one value (7eleven on Discord): the Usage page's+// Tuned for you card and Long conversations in Codex's settings on the+// Agents page. The card says it is Long conversations, shared by Codex and+// Claude Code, and keeps saying so after Use, with Undo; after Use, the Agents+// page's sheet shows the window Use put in, with no reload. A window typed+// in the sheet is the one the card shows as Now when the Usage page comes+// back. Chromium and WebKit, in every language; the API is faked here and+// keeps the one value as the gateway does (settings.CompactAt).+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");+const curve = (lo, hi, best) => {+ const pts = [];+ for (let v = lo; v <= hi; v += 10000) pts.push({ value: v, cost: 1e9 + Math.abs(v - best) * 3000, compacts: Math.round(9e6 / v) });+ return pts;+};+const facts = { calls: 900, streams: 20, compacts: 40, peak: 380000, after: 57000, growth: 4000, rework: 4700 };++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: 0, fullContext: false };+ let ours = 0; // the window tune put in, as the gateway's stash keeps it+ const window = () => settings.fullContext ? 0 : settings.compactAt || 272000;+ const tune = () => {+ const now = window();+ return {+ days: 7,+ agents: [{ agent: "codex", calls: 900, advice: [{+ knob: "compact",+ setting: { value: now ? String(now) : "", source: "long", ours: ours > 0 && ours === now },+ compact: { current: now || 1000000, best: 400000, cost: 1.9e9, low: 1.5e9, window: 1000000, curve: curve(200000, 600000, 400000), facts },+ }] }],+ };+ };+ 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("codex", "Codex")], profiles: [], settings: { lang, theme: "light" } });+ if (url.pathname === "/api/tune") return json(tune());+ if (url.pathname === "/api/tune/apply" || url.pathname === "/api/tune/undo") {+ const b = req.postDataJSON();+ posts.push({ path: url.pathname, body: b });+ if (url.pathname.endsWith("apply")) {+ ours = +b.value;+ settings = { ...settings, compactAt: ours, fullContext: false };+ }+ return json({});+ }+ 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") return json(settings);+ if (url.pathname === "/api/context") return json({ days: 7, agents: [], sessions: [] });+ if (url.pathname === "/api/gateway/trace") {+ if (url.searchParams.get("wait")) return new Promise(() => {});+ return json({ mine: true, now: new Date().toISOString(), seq: 0, totals: { requests: 0, rerouted: 0, errors: 0 }, routes: [] });+ }+ if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true, url: "http://127.0.0.1:3999" } });+ if (url.pathname === "/api/usage/quotas") return json([]);+ if (url.pathname === "/api/groups") return json({ groups: [], models: [] });+ if (url.pathname === "/api/plugins") return json({ plugins: [] });+ 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: { long: "Long conversations, shared by Codex and Claude Code", undo: "Undo" },+ zh: { long: "「长对话」,Codex 和 Claude Code 共用", undo: "撤销" },+ "zh-TW": { long: "「長對話」,Codex 與 Claude Code 共用", undo: "復原" },+ ja: { long: "「長い会話」。Codex と Claude Code で共通", undo: "取り消す" },+ de: { long: "„Lange Unterhaltungen“, die Codex und Claude Code teilen", undo: "Rückgängig" },+};++for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {+ test(`${engine}: Tuned for you and Long conversations are one window`, async (t) => {+ const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: process.env.PLAYWRIGHT_CHANNEL || "chromium" }));+ t.after(() => browser.close());+ for (const [lang, w] of Object.entries(words)) {+ await t.test(lang, async () => {+ const ctx = await browser.newContext({ viewport: { width: 1100, height: 760 }, reducedMotion: "reduce" });+ await ctx.addInitScript(() => { try { localStorage.setItem("magpie.usageTab", "context"); } catch {} });+ const page = await ctx.newPage();+ page.setDefaultTimeout(5000);+ 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=usage");+ const row = page.locator(".ctx-tune-row").first();+ await row.waitFor();+ // the card says where its window is kept+ assert.equal(await row.locator(".ctx-tune-src").innerText(), w.long);+ await row.locator("button.primary").click();+ // put in by magpie: Undo, and still the one value+ await row.getByRole("button", { name: w.undo, exact: true }).waitFor();+ assert.equal(await row.locator(".ctx-tune-src").innerText(), w.long);+ assert.deepEqual(posts.map((p) => [p.path, p.body.agent, p.body.value]), [["/api/tune/apply", "codex", "400000"]]);++ // the Agents page's sheet shows the window Use put in+ await page.locator('#nav button[data-view="agents"]').click();+ await openAgentSettings(page, "codex");+ const num = page.locator("#fullContextSegs input.compact-num");+ await num.waitFor();+ assert.equal(await num.inputValue(), "400k", "Long conversations after Use on the Usage page");++ // a window typed there is the card's Now when Usage is back+ await num.fill("300k");+ await num.press("Enter");+ await page.waitForFunction(() => document.querySelector("#fullContextSegs input.compact-num")?.value === "300k");+ assert.deepEqual(posts.at(-1), { path: "/api/settings/full-context", body: { on: false, at: 300000 } });+ await page.locator('#nav button[data-view="usage"]').click();+ await page.locator(".ctx-tune-row .ctx-tune-val.now b").filter({ hasText: "300K" }).waitFor();+ // no longer the window tune put in: no Undo, and still the one value+ assert.equal(await page.locator(".ctx-tune-row").first().getByRole("button", { name: w.undo, exact: true }).count(), 0);+ assert.equal(await page.locator(".ctx-tune-row .ctx-tune-src").first().innerText(), w.long);+ assert.deepEqual(errors, []);+ await ctx.close();+ });+ }+ });+}diff --git a/internal/gui/tune.go b/internal/gui/tune.goindex a3b2780b6..2d36b4f96 100644--- a/internal/gui/tune.go+++ b/internal/gui/tune.go@@ -108,8 +108,11 @@ func tuneOf(cs []sessions.Call, days int, home string) tuneState {}st := settings.Load()window, told := 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+ // windows, a provider's own Compact at)cur, _ := strconv.Atoi(s.Value)- if cur == 0 {+ if cur == 0 || s.Source == agent.TuneLong {cur = told}// a value the user chose is never past the last one offered