diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md index 255065b2e..a6f440d8e 100644 --- a/docs/subsystems/agent-wiring.md +++ b/docs/subsystems/agent-wiring.md @@ -223,7 +223,7 @@ something else shows up as drift. - Codex on a magpie model the user has since unchecked in its provider's model list (`provider.Unpicked`: the provider has picks, its served models lack it, and it is not a decision model) moves to that provider's first model magpie lists for Codex (`pickedInstead`, [`model_unpicked.go`](../../internal/agent/model_unpicked.go)), in each wiring: Codex's Sync puts it through `set`, as picking it does, and the profile's Sync through `put` (JNDliuliuM on X: Codex CLI, restarted, still started on the old model; `Resolve` still serves it). A provider with no picks, whose list is the vendor's, keeps a model it lacks (#2642), and one with none of its models listed leaves Codex where it is. Other agents' model fields, and Codex's subagent and compaction models, are not moved yet (#6504). - 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). Codex 0.166 refuses to resume a thread whose provider isn't the one configured ("This chat uses openai, but your current provider is magpie", openai/codex#58865; 毅 on Discord), and for a legacy thread the rollout's `session_meta` wins over the state DB row. So when magpie becomes the provider, bringOver relabels plain rollouts in place and also moves legacy threads Codex packed to `.jsonl.zst` that were updated in the last 30 days, up to 128 MB a sync, newest first, each with a copy kept in the trash (`sessions.MovePackedCodexThreads`, `TestCodexThreadsFollowMagpieIn`, `TestMovePackedCodexThreads`); bringBack moves them back. A paginated thread (`history_mode = 'paginated'` in the row, every thread Codex 0.166 starts) is listed and resumed on the provider its row names, never its files' (codex-rs thread-store `read_thread`: "Paginated history may contain only a suffix, so its display metadata lives in SQLite"), so the 30 days and the budget left an API-key user's older OpenAI threads refused in the Codex app (Parry_Moody and Cyrus on Discord). Every one now moves by its row alone, of any age, packed or not, an id of any length, its files neither written nor copied (`sessions.RetagPagedCodexThreads`, after the in-place relabel), in bringOver, bringBack, bringOfficial, bringBeside and giveBeside (`RetagPagedCodexThreadIDs`); one a Codex has open (its writer lock, which would write its provider back) or wrote to in the last minute waits for the next sync. The Sessions page lists a paginated thread on its row's provider (`codexPagedProviders`, read again when the database or its WAL changes). Tried with the real codex 0.166.0 (`codex exec resume`): refused on magpie with the row on openai, resumed after the retag, and back on OpenAI after the reverse (`TestCodexPagedThreadsFollowByRow`, `TestRetagPagedCodexThreads`). Codex rebuilds a row from the rollout when a search listing or a missing row reconciles it, which would put a retagged thread back on its file's provider until the next sync. A thread a move leaves where it was because it was written to in the last minute or a Codex holds it open gets one more Sync once it is quiet and let go (`sessions.CodexThreadsBusyOn`: a recent rollout, or its writer lock held, tried under Codex's coordination lock; `codexThreadsLater` looks every 15s for up to 12h, one wait per home and provider): no other Sync may come for hours. bringBack's (the thread a turn ran in during the takeover, as the account came back) otherwise stayed on magpie, and the Codex app couldn't resume it on OpenAI, so Retry failed each time and its model read unavailable (nb5p on Discord, `TestCodexTakeoverThreadComesBackOnceQuiet`). bringOver's and lendOwn's are the chats the Codex app had loaded as magpie became Codex's provider: the app holds every loaded thread's lock however long ago it was written (tried with codex 0.165's app-server), checks a loaded thread's provider against config.toml at each turn, and refuses it ("This chat uses OpenAI, but your current provider is magpie", crypto0xfish on Discord) until it lets the thread go; resumed after that, it was refused again on its row's `openai` until something else synced (`TestCodexOpenThreadFollowsMagpieOnceLetGo`). The chat open at the switch is moved by its row (a legacy one in place, at equal id length) just before the Codex app's app-server is ended for the route change (`provider.CodexBeforeAppEnd`, `codexRetagOpenThreads`, `sessions.RetagLoadedCodexThreads`): the app holds its lock, but the end is a clean SIGTERM that writes nothing back, and the next app-server resumes it on the new provider, in both directions (tried with the real codex 0.167.1 app-server: refused with `modelProviderMismatch` openai to magpie and `modelProviderNotConfigured` magpie to openai without the retag, resumed with it; hubo31377762 on X; `TestCodexOpenThreadsMoveBeforeAppServerEnds`, `TestCodexRouteChangeMovesOpenChatsFirst`). The resumed thread's sandbox falls back to config.toml's default whatever the provider (#6028, a separate bug). That is done for the provider Codex was on before magpie (stash `codex.provider`, `openai` when none), a provider of the user's own too: a relay's table or CC Switch's `custom`, whose threads the Codex app listed and refused to open on magpie ("This chat uses custom, but your current provider is magpie", hxy920830 on X). An id of magpie's length (`custom`) is relabelled in place; any other (`myrelay`) is rewritten with a copy kept, the threads of the last 30 days, 128 MB a sync, newest first (`sessions.MoveRecentCodexThreads`), and none moves of a provider a profile names. OpenAI's threads come to magpie too, since the Codex app lists them and refuses each one there as it did on that provider ("此聊天使用的是 OpenAI,但你当前的提供商是 magpie", Lice9735 on X, Codex on its own `openai-http` table before). They are recorded in stash `codex.lent` with the user's provider as `to`, as `lendOwn` records its own below: the Disconnect gives every thread on magpie to that provider, where Codex resumes them, and `giveLent` gives these back to OpenAI once Codex is on it again. None moves while a profile names `openai` (`TestCodexOpenAIThreadsFollowMagpieFromOwnProvider`). Before, they stayed on OpenAI there. The Disconnect puts the user's `model_provider` back and bringBack returns the threads to it; so does CC Switch switching back to that provider (`TestCodexThreadsFollowMagpieIn`, `TestMoveRecentCodexThreads`). A thread started on `cc-switch-official`, the id CC Switch 3.17 to 3.20 gave the official account, is moved to `openai` (or `magpie`, whichever Codex is on) while magpie wires Codex, as CC Switch 4 does itself (#7948 there), unless the user's own top-level `model_provider` or a profile names that id (`bringOfficial`, AcMilan on Discord, `TestCodexMovesCCSwitchOfficialThreads`). CC Switch's OpenAI mirror is the ChatGPT account's as much, and the Codex app names a provider by its table's `name`, so a thread on the mirror with Codex on `openai`, or the other way round, was refused as "This chat uses OpenAI, but your current provider is OpenAI" (Chris on Discord; codex 0.167 `exec resume` refuses both by id, 0.168 drops the check). Its threads move the same way: `bringOfficial` takes every mirror table's that isn't at the top, named by a profile, or the provider magpie took down (stash `codex.provider`, whose threads `bringBeside` and `bringOver` move with a record and give back at the Disconnect), and a mirror at the top takes OpenAI's through `lendOwn` (`TestCodexMirrorThreadsFollowOpenAI`, `TestCodexMirrorAtTopJoinsWithItsThreads`, `TestCodexMirrorAtTopTakesOpenAIThreads`). Before #4347 (v0.1.2652) the beside wiring took a provider of the user's (CC Switch's `custom`) down and kept it in stash `codex.provider`, leaving Codex on OpenAI by the base URL with every thread of that provider refused ("This chat uses custom, but your current provider is openai", yikelizi9438 on Discord). While Codex stays so (routed by `openai_base_url`, no top-level `model_provider`), `bringBeside` moves that provider's threads to `openai` the same way (in place at OpenAI's length, the last 30 days rewritten otherwise) and records them in stash `codex.brought`; the Disconnect puts the provider back and `giveBeside` returns exactly those threads to it (`sessions.MoveCodexThreadIDs`), and if magpie becomes Codex's provider instead they go on to `magpie` (`followBeside`), where bringBack returns them at the Disconnect (`TestCodexBesideBringsTakenProvidersThreads`). The other way round, Codex on a provider of the user's at the top (CC Switch's `custom`, kept since #4347, CC Switch's OpenAI mirror too; not magpie, `openai` or `cc-switch-official`) could not continue a thread started on OpenAI before ("This chat uses openai, but your current provider is custom. Switch to openai to continue", harris on Discord, after CC Switch). Each Sync moves OpenAI's threads to that provider the same way (`lendOwn`: in place at OpenAI's length, by the row for a paginated one, the last 30 days rewritten otherwise) and records them in stash `codex.lent`; once Codex is on OpenAI again `giveLent` returns exactly those (`sessions.MoveCodexThreadIDs`, `RetagPagedCodexThreadIDs`), the record kept while Codex is on that provider or on magpie and dropped on any other. None moves while a profile names `openai`, after the user disconnected Codex, or from a distro's Codex (`TestCodexOwnProviderTakesOpenAIThreads`, `TestCodexOwnProviderLeavesOpenAIThreads`). Each rewrite (`codexOnto`, shared by bringOver, bringBeside and lendOwn) goes `packedBudget` bytes a sync, newest first; when the budget stops it with threads left (`MovePackedCodexThreads` and `MoveRecentCodexThreads` say `more`), it asks for the next sync at once (`codexThreadsAgain`) instead of leaving them refused until something else syncs, which may be hours away (`TestCodexThreadsLeftByTheBudgetAskAgain`). Threads on any other provider, and ones older than 30 days that can't be relabelled in place, stay put: the Sessions page's Move or Resume takes them over. - 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. 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..[.]` 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 the window Codex's catalog gives them (`codexcat.OwnWindow`, else 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 locked card offers one action, Let magpie set it (`take`, `POST /api/tune/takeover`, `TuneTakeOver`; sufeng1894 on X: the card had no way to adjust it), and nothing moves without that click: the limit goes into Long conversations by `tuneMigrateCodex`'s rule (at magpie's default or Full window it is taken; a Compact at the user typed takes it only when lower), is taken out of config.toml, and its text is stashed (`tune.codex.compact_file`), so Undo puts Long conversations back and writes the limit in again unless the user changed either since. Background compaction's `model_async_compact_threshold_percent` of the user's (with `enabled = true` or none) is taken the same way: Settings' Background compaction takes it on, at that share, and the `codex.async` stash names the file's value magpie's, so the file is unchanged and the card adjusts it; Undo turns Background compaction back and gives the value back as the user's, written again if a later share replaced it. `tuneMigrateCodex` forgets an older tune's stash only once the limit is out of the file, and `codexAsyncSync` stashes what it wrote even when a later write fails, so a value magpie wrote never reads as the user's and locks the card (`TestTuneCodexTakeOver`, `TestTuneCodexTakeOverAsync`, `TestTuneCodexMigrateKeepsStash`, context-tune.test.cjs). 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..[.]` 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 the window Codex's catalog gives them (`codexcat.OwnWindow`, else 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::`, 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-` (`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 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 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//` 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. diff --git a/internal/agent/codex_async.go b/internal/agent/codex_async.go index d8a9550d3..ed60cc13f 100644 --- a/internal/agent/codex_async.go +++ b/internal/agent/codex_async.go @@ -251,7 +251,20 @@ func codexAsyncSync(path, key string, routed, on bool, percent int, tableOK bool if raw := stashShared()[key]; raw != "" { json.Unmarshal([]byte(raw), &st) } + // what was written is stashed however the sync ends: a write after + // it that fails never leaves magpie's threshold or table in the file + // unstashed, where it would read as the user's and lock the setting was := st + defer func() { + if st != was { + if st == (codexAsyncStash{}) { + forget(key) + } else { + b, _ := json.Marshal(st) + stash(map[string]string{key: string(b)}) + } + } + }() want := routed && on useTable := want && tableOK if !useTable { @@ -373,14 +386,6 @@ func codexAsyncSync(path, key string, routed, on bool, percent int, tableOK bool } } - if st != was { - if st == (codexAsyncStash{}) { - forget(key) - } else { - b, _ := json.Marshal(st) - stash(map[string]string{key: string(b)}) - } - } return nil } diff --git a/internal/agent/tune.go b/internal/agent/tune.go index 886b31226..90d7a3b94 100644 --- a/internal/agent/tune.go +++ b/internal/agent/tune.go @@ -54,6 +54,9 @@ type TuneSetting struct { Locked string `json:"locked,omitempty"` // Ours: tune put Value in, and Undo puts back what was there Ours bool `json:"ours,omitempty"` + // Take: what is Locked is one magpie can take over on the user's say + // (TuneTakeOver) + Take bool `json:"take,omitempty"` } // TuneLong is the Source of a window that is magpie's Long conversations, @@ -163,24 +166,122 @@ func tuneMigrateCodex(home string) { 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 { + forget(tuneKey("codex", TuneCompact, "")) return } + // the stash goes only once the limit is out of the file: one that + // couldn't be moved is still magpie's, and tried again at the next + // read, never left in the file as if the user had written it if n, err := strconv.Atoi(st.Set); err == nil && n > 0 { - s := settings.Load().ForAgent("codex") - if s.CompactAt == 0 || s.FullContext || n < s.Compact() { - if err := longApply("codex", n); err != nil { - return - } + if err := longApply("codex", codexLongTakes(n)); err != nil { + return } } + var err error if st.Had { - _ = edit.SetTOMLTop(p.path, edit.KV{Path: p.key, Value: tomlRaw(st.Raw)}) - return + err = edit.SetTOMLTop(p.path, edit.KV{Path: p.key, Value: tomlRaw(st.Raw)}) + } else { + err = edit.DelTOMLTop(p.path, p.key) } - _ = edit.DelTOMLTop(p.path, p.key) + if err == nil { + forget(tuneKey("codex", TuneCompact, "")) + } +} + +// codexLongTakes is the window Long conversations for Codex has once a +// limit n from Codex's config.toml is moved into it: n, where Long +// conversations is at magpie's default or Full window; else the lesser of +// the two, where Codex compacted with both (it stops at the lesser of the +// limit and the window it is told), so nothing changes for the user. +func codexLongTakes(n int) int { + s := settings.Load().ForAgent("codex") + if s.CompactAt == 0 || s.FullContext { + return n + } + return min(n, s.Compact()) +} + +// tuneFileKey stashes the limit the user had in Codex's config.toml when +// they let magpie set it (TuneTakeOver), as the file had it: Undo writes +// it back. +const tuneFileKey = "tune.codex.compact_file" + +// TuneTakeOver is the user's say that magpie sets what Codex's config.toml +// sets before it, the Locked of TuneRead (sufeng1894 on X: the Usage +// page's Codex card was locked by a model_auto_compact_token_limit, with +// no way to adjust it from magpie). The limit moves into Long +// conversations for Codex (codexLongTakes, as tuneMigrateCodex moves +// tune's own) and out of the file; a background compaction threshold of +// the user's in [features.async_compaction] becomes Background +// compaction's, in Settings, and stays in the file as magpie's. Undo puts +// both back as they were. Nothing of the user's is taken without this. +func TuneTakeOver(home, agent string) error { + if agent != "codex" { + return fmt.Errorf("%s has nothing in its config that magpie can take over", agent) + } + _, limit := codexOwnLimit(home) + _, _, async := asyncTakeable(home) + if !limit && !async { + return fmt.Errorf("Codex's config.toml sets nothing magpie can take over") + } + if limit { + if err := compactTakeOver(home); err != nil { + return err + } + } + if async { + return asyncTakeOver(home) + } + return nil +} + +// codexOwnLimit is the model_auto_compact_token_limit Codex's config.toml +// has at its top, as a token count: ok when there is one magpie can take. +func codexOwnLimit(home string) (int, bool) { + p := tunePlace{path: filepath.Join(here(tuneHome(home)).codexHome(), "config.toml"), key: codexCompactKey, toml: true} + v, has := p.get() + if !has { + return 0, false + } + n, err := strconv.Atoi(compactValue(strings.Trim(v, `"'`))) + return n, err == nil && n > 0 +} + +func compactTakeOver(home string) error { + p := tunePlace{path: filepath.Join(here(tuneHome(home)).codexHome(), "config.toml"), key: codexCompactKey, toml: true} + raw, _ := p.get() + n, ok := codexOwnLimit(home) + if !ok { + return fmt.Errorf("%s = %s is no token count", codexCompactKey, raw) + } + if err := longApply("codex", codexLongTakes(n)); err != nil { + return err + } + // kept before the key goes, so a write cut short loses nothing + stash(map[string]string{tuneFileKey: raw}) + return edit.DelTOMLTop(p.path, p.key) +} + +// codexLongUndo is Undo on Codex's window in Long conversations: Long +// conversations as it was, and the limit the user let magpie take +// (tuneFileKey) back in config.toml, unless either changed since. +func codexLongUndo(home string) error { + ours := longOurs(settings.Load(), "codex") + raw := stashShared()[tuneFileKey] + if err := longUndo("codex"); err != nil { + return err + } + if raw == "" { + return nil + } + defer forget(tuneFileKey) + p := tunePlace{path: filepath.Join(here(tuneHome(home)).codexHome(), "config.toml"), key: codexCompactKey, toml: true} + if _, has := p.get(); !ours || has { + return nil + } + return edit.SetTOMLTop(p.path, edit.KV{Path: p.key, Value: tomlRaw(compactValue(strings.Trim(raw, `"'`)))}) } // tuneStash is what a setting was before tune put one in. @@ -275,6 +376,7 @@ func TuneRead(home, agent, knob, model string) (TuneSetting, error) { // 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 + _, s.Take = codexOwnLimit(home) return s, nil } st := settings.Load() @@ -487,13 +589,16 @@ func TuneCacheHere(home string) []TuneKnob { // the user has changed it since: then it is theirs, and only forgotten. func TuneUndo(home, agent, knob, model string) error { if agent == "codex" && knob == TuneAsync { - return asyncUndo() + return asyncUndo(home) } p, err := tuneWhere(home, agent, knob, model) if err != nil { return err } if cur, _ := TuneRead(home, agent, knob, model); cur.Source == TuneLong { + if agent == "codex" { + return codexLongUndo(home) + } return longUndo(agent) } st, ok := tuneStashed(agent, knob, model) @@ -568,6 +673,10 @@ type tuneAsyncStash struct { On bool `json:"on"` Percent int `json:"percent"` Set int `json:"set"` + // the threshold, and enabled = true, the user had in config.toml when + // they let magpie take it over (asyncTakeOver), which Undo gives back + Own int `json:"own,omitempty"` + OwnEnabled bool `json:"ownEnabled,omitempty"` } func asyncStashed() (tuneAsyncStash, bool) { @@ -591,6 +700,7 @@ func asyncRead(home string) TuneSetting { out := TuneSetting{Source: TuneAsyncSource} if own := codexAsyncOwn(home); own != "" { out.Locked = own + _, _, out.Take = asyncTakeable(home) return out } s := settings.Load() @@ -626,7 +736,7 @@ func asyncApply(home, value string) error { // asyncUndo puts Background compaction back as it was before tune, unless // the user changed it since: then it is theirs, and only forgotten. -func asyncUndo() error { +func asyncUndo(home string) error { st, ok := asyncStashed() if !ok { return fmt.Errorf("magpie didn't set Codex's background compaction") @@ -635,7 +745,111 @@ func asyncUndo() error { if !asyncOurs(settings.Load()) { return nil } - return provider.SetCodexAsyncCompact(st.On, st.Percent) + if err := provider.SetCodexAsyncCompact(st.On, st.Percent); err != nil { + return err + } + if st.Own > 0 { + return asyncGiveBack(home, st) + } + return nil +} + +// asyncTakeable is the background compaction threshold of the user's that +// Codex's config.toml has in its [features.async_compaction] table, the +// one thing there that keeps magpie's from being read: ok when magpie can +// take it over (asyncTakeOver). enabled: the table's enabled = true is the +// user's too. +func asyncTakeable(home string) (n int, enabled, ok bool) { + if codexAsyncOwn(home) != codexAsyncTable+"."+codexAsyncPercent { + return 0, false, false + } + at := here(tuneHome(home)) + feature, _, err := codexAsyncNow(filepath.Join(at.codexHome(), "config.toml")) + t, _ := feature.(map[string]any) + p, isInt := t[codexAsyncPercent].(int64) + if err != nil || !isInt || p < 1 || p > 100 { + return 0, false, false + } + var cs codexAsyncStash + if raw := stashShared()[at.key("codex.async")]; raw != "" { + json.Unmarshal([]byte(raw), &cs) + } + e, _ := t["enabled"].(bool) + return int(p), e && !cs.Enabled, true +} + +// asyncTakeOver makes the user's threshold Background compaction's: the +// setting takes its value, and the config's key is counted as the one +// magpie wrote (codexAsyncSync's stash), so it is changed and taken out +// with the setting from now on. Nothing in the file changes. +func asyncTakeOver(home string) error { + n, enabled, ok := asyncTakeable(home) + if !ok { + return fmt.Errorf("Codex's config.toml sets no background compaction threshold magpie can take over") + } + s := settings.Load() + st, had := asyncStashed() + if !had { + st = tuneAsyncStash{On: s.CodexAsyncCompact, Percent: s.CodexAsyncCompactPercent} + } + st.Set, st.Own, st.OwnEnabled = n, n, enabled + b, _ := json.Marshal(st) + stash(map[string]string{tuneAsyncKey: string(b)}) + key := here(tuneHome(home)).key("codex.async") + var cs codexAsyncStash + if raw := stashShared()[key]; raw != "" { + json.Unmarshal([]byte(raw), &cs) + } + cs.Percent = n + if enabled { + cs.Enabled = true + } + b, _ = json.Marshal(cs) + stash(map[string]string{key: string(b)}) + return provider.SetCodexAsyncCompact(true, n) +} + +// asyncGiveBack puts the threshold (and enabled = true) the user let magpie +// take back in config.toml as theirs, unless they changed the file since. +func asyncGiveBack(home string, st tuneAsyncStash) error { + at := here(tuneHome(home)) + path, key := filepath.Join(at.codexHome(), "config.toml"), at.key("codex.async") + var cs codexAsyncStash + if raw := stashShared()[key]; raw != "" { + json.Unmarshal([]byte(raw), &cs) + } + feature, _, err := codexAsyncNow(path) + if err != nil { + return err + } + if feature != nil { + if _, isTable := feature.(map[string]any); !isTable { + return nil // the user's own spelling of it since + } + } + t, _ := feature.(map[string]any) + if cur, has := t[codexAsyncPercent]; has && (cs.Percent == 0 || cur != int64(cs.Percent)) { + return nil // a threshold the user wrote since + } + if err := edit.SetTOMLKey(path, codexAsyncTable, codexAsyncPercent, st.Own); err != nil { + return err + } + cs.Percent = 0 + if st.OwnEnabled { + if t["enabled"] == nil { + if err := edit.SetTOMLKey(path, codexAsyncTable, "enabled", true); err != nil { + return err + } + } + cs.Enabled = false + } + if cs == (codexAsyncStash{}) { + forget(key) + return nil + } + b, _ := json.Marshal(cs) + stash(map[string]string{key: string(b)}) + return nil } // ClaudeCacheSet is one of Claude Code's prompt-cache lifetimes as the diff --git a/internal/agent/tune_takeover_test.go b/internal/agent/tune_takeover_test.go new file mode 100644 index 000000000..149d969ed --- /dev/null +++ b/internal/agent/tune_takeover_test.go @@ -0,0 +1,226 @@ +package agent + +import ( + "encoding/json" + "os" + "path/filepath" + "runtime" + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/settings" +) + +// TestTuneCodexTakeOver: a model_auto_compact_token_limit of the user's +// locks the Codex card (sufeng1894 on X), and the card's one action lets +// magpie set it: the limit moves into Long conversations (the rule +// tuneMigrateCodex moves tune's own by) and out of config.toml, the card +// adjusts it from then on, and Undo puts both back. Nothing of the user's +// moves without that say. +func TestTuneCodexTakeOver(t *testing.T) { + t.Run("default Long conversations takes the limit", func(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 = 140_000\n\n[features]\nx = true\n") + s, _ := TuneRead(home, "codex", TuneCompact, "") + if s.Locked != codexCompactKey || !s.Take { + t.Fatalf("read %+v: want locked, and takeable", s) + } + if err := TuneApply(home, "codex", TuneCompact, "", "100000"); err == nil { + t.Fatal("applied over the user's own limit without their say") + } + if got := tuneFile(t, path); !strings.Contains(got, "140_000") { + t.Fatalf("config.toml changed without the say:\n%s", got) + } + if err := TuneTakeOver(home, "codex"); err != nil { + t.Fatal(err) + } + if got := settings.Load(); got.CompactAt != 140000 || got.FullContext { + t.Fatalf("Long conversations %d full=%v, want the file's 140000", got.CompactAt, got.FullContext) + } + if got := tuneFile(t, path); strings.Contains(got, codexCompactKey) || !strings.Contains(got, "gpt-5.5") || !strings.Contains(got, "x = true") { + t.Fatalf("config.toml after the take-over:\n%s", got) + } + s, _ = TuneRead(home, "codex", TuneCompact, "") + if s.Locked != "" || s.Take || s.Source != TuneLong || s.Value != "140000" || !s.Ours { + t.Fatalf("read after the take-over %+v", s) + } + // adjusted from the card now + if err := TuneApply(home, "codex", TuneCompact, "", "100000"); err != nil { + t.Fatal(err) + } + if got := settings.Load(); got.CompactAt != 100000 { + t.Fatalf("Long conversations %d after apply", got.CompactAt) + } + if err := TuneUndo(home, "codex", TuneCompact, ""); err != nil { + t.Fatal(err) + } + if got := settings.Load(); got.CompactAt != 0 || got.FullContext { + t.Fatalf("Long conversations %d after undo, want magpie's default", got.CompactAt) + } + if got := tuneFile(t, path); !strings.Contains(got, "model_auto_compact_token_limit = 140000") || !strings.Contains(got, "x = true") { + t.Fatalf("undo didn't put the user's limit back:\n%s", got) + } + if s, _ := TuneRead(home, "codex", TuneCompact, ""); s.Locked != codexCompactKey || s.Value != "140000" { + t.Fatalf("read after undo %+v", s) + } + if _, ok := stashShared()[tuneFileKey]; ok { + t.Fatal("the file's stash stayed after undo") + } + }) + t.Run("a lower Long conversations stays where Codex compacted", func(t *testing.T) { + home := tuneSandbox(t) + path := filepath.Join(home, ".codex", "config.toml") + if err := provider.SetCompactAt(120000); err != nil { + t.Fatal(err) + } + tuneWrite(t, path, "model_auto_compact_token_limit = 180000\n") + if err := TuneTakeOver(home, "codex"); err != nil { + t.Fatal(err) + } + if got := settings.Load(); got.CompactAt != 120000 { + t.Fatalf("Long conversations %d, want 120000 kept", got.CompactAt) + } + s, _ := TuneRead(home, "codex", TuneCompact, "") + if s.Locked != "" || !s.Ours { + t.Fatalf("read %+v: Undo must be offered", s) + } + if err := TuneUndo(home, "codex", TuneCompact, ""); err != nil { + t.Fatal(err) + } + if got := tuneFile(t, path); !strings.Contains(got, "= 180000") { + t.Fatalf("undo didn't put the user's limit back:\n%s", got) + } + if got := settings.Load(); got.CompactAt != 120000 { + t.Fatalf("Long conversations %d after undo", got.CompactAt) + } + }) + t.Run("Long conversations changed since is the user's", func(t *testing.T) { + home := tuneSandbox(t) + path := filepath.Join(home, ".codex", "config.toml") + tuneWrite(t, path, "model_auto_compact_token_limit = 180000\n") + if err := TuneTakeOver(home, "codex"); 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 { + t.Fatalf("undo wrote over the user's 250000: %d", got.CompactAt) + } + if got := tuneFile(t, path); strings.Contains(got, codexCompactKey) { + t.Fatalf("undo put a limit back over the user's later choice:\n%s", got) + } + }) + t.Run("nothing to take", func(t *testing.T) { + home := tuneSandbox(t) + tuneWrite(t, filepath.Join(home, ".codex", "config.toml"), "model = \"gpt-5.5\"\n") + if err := TuneTakeOver(home, "codex"); err == nil { + t.Fatal("took over nothing") + } + if err := TuneTakeOver(home, "claude"); err == nil { + t.Fatal("took over Claude Code") + } + }) +} + +// TestTuneCodexTakeOverAsync: a background compaction threshold of the +// user's in config.toml (the screenshot's second lock) becomes Background +// compaction's on the same say: Settings takes its share, the file keeps +// it as magpie's, a sync leaves it, and Undo gives it back as the user's. +func TestTuneCodexTakeOverAsync(t *testing.T) { + home := tuneSandbox(t) + path := filepath.Join(home, ".codex", "config.toml") + file := "[features.async_compaction]\nenabled = true\nmodel_async_compact_threshold_percent = 80\n" + tuneWrite(t, path, file) + setAsyncCompact(t, false, 0) + key := here(tuneHome(home)).key("codex.async") + sync := func() { + t.Helper() + s := settings.Load() + if err := codexAsyncSync(path, key, true, s.CodexAsyncCompact, s.CodexAsyncCompactPercent, true); err != nil { + t.Fatal(err) + } + } + if s := asyncRead(home); s.Locked != codexAsyncTable+"."+codexAsyncPercent || !s.Take { + t.Fatalf("read %+v: want locked by the threshold, takeable", s) + } + if err := TuneTakeOver(home, "codex"); err != nil { + t.Fatal(err) + } + if got := settings.Load(); !got.CodexAsyncCompact || got.CodexAsyncCompactPercent != 80 { + t.Fatalf("Background compaction %v %d%%, want on at the file's 80", got.CodexAsyncCompact, got.CodexAsyncCompactPercent) + } + sync() + if got := tuneFile(t, path); got != file { + t.Fatalf("config.toml changed by the take-over and a sync:\n%s", got) + } + if s := asyncRead(home); s.Locked != "" || s.Value != "80" || !s.Ours { + t.Fatalf("read after the take-over %+v", s) + } + // adjusted from the card now: a sync writes the new share + if err := TuneApply(home, "codex", TuneAsync, "", "30"); err != nil { + t.Fatal(err) + } + sync() + if got := tuneFile(t, path); !strings.Contains(got, codexAsyncPercent+" = 30") { + t.Fatalf("config.toml after apply:\n%s", got) + } + if err := TuneUndo(home, "codex", TuneAsync, ""); err != nil { + t.Fatal(err) + } + sync() + if got := settings.Load(); got.CodexAsyncCompact || got.CodexAsyncCompactPercent != 0 { + t.Fatalf("Background compaction %v %d%% after undo, want off as before", got.CodexAsyncCompact, got.CodexAsyncCompactPercent) + } + if got := tuneFile(t, path); !strings.Contains(got, codexAsyncPercent+" = 80") || !strings.Contains(got, "enabled = true") { + t.Fatalf("undo didn't give the user's threshold back:\n%s", got) + } + if s := asyncRead(home); s.Locked != codexAsyncTable+"."+codexAsyncPercent { + t.Fatalf("read after undo %+v: the threshold is the user's again", s) + } + + // enabled = false is no threshold to take: still locked, nothing taken + tuneWrite(t, path, "[features.async_compaction]\nenabled = false\n") + if s := asyncRead(home); s.Take { + t.Fatalf("read %+v: enabled = false offered for taking", s) + } +} + +// TestTuneCodexMigrateKeepsStash: a limit an older tune wrote that can't +// be moved out of config.toml yet stays stashed as magpie's and is moved +// at a later read; before, the stash went first, and the limit was left +// in the file as if the user had written it, locking the card. +func TestTuneCodexMigrateKeepsStash(t *testing.T) { + if runtime.GOOS == "windows" || os.Geteuid() == 0 { + t.Skip("a folder made read-only still takes writes here") + } + home := tuneSandbox(t) + dir := filepath.Join(home, ".codex") + path := filepath.Join(dir, "config.toml") + tuneWrite(t, path, "model_auto_compact_token_limit = 150000\n") + b, _ := json.Marshal(tuneStash{Set: "150000"}) + stash(map[string]string{tuneKey("codex", TuneCompact, ""): string(b)}) + if err := os.Chmod(dir, 0o555); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { os.Chmod(dir, 0o755) }) + TuneRead(home, "codex", TuneCompact, "") + if _, ok := tuneStashed("codex", TuneCompact, ""); !ok { + t.Fatal("tune's stash went with its limit still in config.toml") + } + if err := os.Chmod(dir, 0o755); err != nil { + t.Fatal(err) + } + s, _ := TuneRead(home, "codex", TuneCompact, "") + if s.Locked != "" || s.Source != TuneLong || s.Value != "150000" { + t.Fatalf("read after the file could be written %+v", s) + } + if got := tuneFile(t, path); strings.Contains(got, codexCompactKey) { + t.Fatalf("config.toml:\n%s", got) + } +} diff --git a/internal/cli/settings_parity_test.go b/internal/cli/settings_parity_test.go index 3c3e2686b..0f39964e6 100644 --- a/internal/cli/settings_parity_test.go +++ b/internal/cli/settings_parity_test.go @@ -527,6 +527,7 @@ var notYet = map[string]string{ "POST /api/gateway/unrest": U, // trace.go "GET /api/tune": U, // tune.go "POST /api/tune/apply": U, // tune.go + "POST /api/tune/takeover": U, // tune.go "POST /api/tune/undo": U, // tune.go "POST /api/uninstall/finish": A, // uninstall.go "GET /api/usage/checkins/off": U, // usage.go: the Usage page's switched-off check-ins; `magpie accounts checkin` does every account diff --git a/internal/gui/assets/context.js b/internal/gui/assets/context.js index 171b576e8..e8623e74b 100644 --- a/internal/gui/assets/context.js +++ b/internal/gui/assets/context.js @@ -1379,7 +1379,7 @@ renderContext(); try { await api("tune/" + path, { agent, knob, model: a.model || "", value: String(value ?? "") }); - status(path === "apply" ? t("Saved: {agent} reads it from its next session", { agent: agentLabel(agent) }) : t("Put back"), "ok"); + status(path != "undo" ? t("Saved: {agent} reads it from its next session", { agent: agentLabel(agent) }) : t("Put back"), "ok"); } catch (e) { statusErr(e); } @@ -1449,13 +1449,17 @@ b.onclick = go; return foot.appendChild(b); }; + // what Codex's config.toml sets before magpie, taken over on the + // reader's click (sufeng1894 on X: locked, with no way to adjust it) + if (set.take || aset.take) btn(t("Let magpie set it"), () => send("takeover"), " primary ctx-tune-take"); if (!as) {} else if (aset.locked) cav(t("Background compaction: Codex's config.toml sets {key}, which comes first", { key: aset.locked })); else if (as.held?.length) cav(codexHeld(as.held)); else if (aset.ours && +aset.value === as.percent) { verdict.after(el("span", "ctx-chip good ctx-tune-async", t("In the background at {value}", { value: fmtK(as.value) }))); verdict.nextSibling.prepend(el("i")); btn(t("Undo background"), () => send("undo", "", "async_compact")); - } else btn(t("Use {value} in the background", { value: fmtK(as.value) }), () => send("apply", as.percent, "async_compact"), " ctx-tune-async").dataset.tt = t("Codex compacts in the background past {pct} of the model's window, about {value} of {window}, while the turn goes on; {now} stays as the foreground limit, for when the background one isn't ready. A Codex feature still under development, 0.163 or later.", { pct: as.percent + "%", value: fmtK(as.value), window: fmtK(as.window), now: show(cur) }); + // after it, Undo for a share taken over from config.toml + } else btn(t("Use {value} in the background", { value: fmtK(as.value) }), () => send("apply", as.percent, "async_compact"), " ctx-tune-async").dataset.tt = t("Codex compacts in the background past {pct} of the model's window, about {value} of {window}, while the turn goes on; {now} stays as the foreground limit, for when the background one isn't ready. A Codex feature still under development, 0.163 or later.", { pct: as.percent + "%", value: fmtK(as.value), window: fmtK(as.window), now: show(cur) }), aset.ours && btn(t("Undo background"), () => send("undo", "", "async_compact")); row.append(foot); return row; } diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 02abb928f..e29316534 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -334,6 +334,7 @@ const I18N = { "Fewer tokens, but more compactions to wait on": "Token 更少,但要多等几次压缩", "{pct} fewer tokens · {tokens} over the range": "少 {pct} Token · 这段时间省 {tokens}", "{name} is set and comes first": "已设置 {name},它优先", + "Let magpie set it": "交给 magpie 设置", "{model} compacts at its own {value}, which comes first": "{model} 有自己的压缩阈值 {value},它优先", "{model} compacts at its own {value}, which this doesn't move": "{model} 有自己的压缩阈值 {value},这里不会改动它", "Set by magpie": "由 magpie 设置", @@ -5705,6 +5706,7 @@ const I18N = { "Fewer tokens, but more compactions to wait on": "Token 更少,但要多等幾次壓縮", "{pct} fewer tokens · {tokens} over the range": "少 {pct} Token · 這段時間省 {tokens}", "{name} is set and comes first": "已設定 {name},它優先", + "Let magpie set it": "交給 magpie 設定", "{model} compacts at its own {value}, which comes first": "{model} 有自己的壓縮閾值 {value},它優先", "{model} compacts at its own {value}, which this doesn't move": "{model} 有自己的壓縮閾值 {value},這裡不會改動它", "Set by magpie": "由 magpie 設定", @@ -11046,6 +11048,7 @@ const I18N = { "Fewer tokens, but more compactions to wait on": "トークンは減りますが、コンパクトの待ちが増えます", "{pct} fewer tokens · {tokens} over the range": "トークン {pct} 減 · この期間で {tokens}", "{name} is set and comes first": "{name} が設定されていて優先されます", + "Let magpie set it": "magpie に任せる", "{model} compacts at its own {value}, which comes first": "{model} には独自の圧縮しきい値 {value} があり、そちらが優先されます", "{model} compacts at its own {value}, which this doesn't move": "{model} には独自の圧縮しきい値 {value} があり、ここでは変わりません", "Set by magpie": "magpie が設定", @@ -16396,6 +16399,7 @@ const I18N = { "Fewer tokens, but more compactions to wait on": "Weniger Tokens, aber mehr Kompaktierungen, auf die du wartest", "{pct} fewer tokens · {tokens} over the range": "{pct} weniger Tokens · {tokens} im Zeitraum", "{name} is set and comes first": "{name} ist gesetzt und hat Vorrang", + "Let magpie set it": "magpie festlegen lassen", "{model} compacts at its own {value}, which comes first": "{model} hat ein eigenes „Komprimieren ab“ ({value}), das Vorrang hat", "{model} compacts at its own {value}, which this doesn't move": "{model} hat ein eigenes „Komprimieren ab“ ({value}), das sich hier nicht ändert", "Set by magpie": "Von magpie gesetzt", diff --git a/internal/gui/core_budget_test.go b/internal/gui/core_budget_test.go index d4e3fa412..0a1563bab 100644 --- a/internal/gui/core_budget_test.go +++ b/internal/gui/core_budget_test.go @@ -18,7 +18,7 @@ import ( // `git log -L` of this file. const ( appScriptBudget = 1_087_447 // app.js: 1,080,614 at 8016205e3, with the 5,653 of room it had; +123 for a sidebar list folded from its page's row (hkwok06 on X), its chevron and fold in navicons.js, imported with the first list; +57 for each account of a provider's Usage card in a card of its own (normalcoder_ on X), past the 24 of room left; +17 for an allowance card's wallet line under its rings (apple_test_src on X), the one filter shared with its text line; +338 for the Daily update channel (fishmagic80 on X): its segment, its line under Update channel and the version row's two Up to date on Daily words, packed to the shortest form (one t() per choice); Settings › About and renderUpdate draw them on every window, so there is no page to move them to; +35 for Baidu Qianfan's Token Plan sign-in (yuushabu_buyinn on X, #5860): its field in qianfanplan.js, imported when such a provider's editor opens, drawn by renderStepPlan now told whose sign-in it brings, and what is left is the import and two quotaError lines, past the room there was; quotaError reads every card's error, so there is no page to move it to; +27 for Windows' title bar (258a14 on X): the caption buttons, their clicks, the bar's double click and what keeps them over a dialog in wincap.js, imported in Windows' window alone, the header's room for them in app.css, and what is left is the one line that imports it, past the 29 of room there was; that window's frame is drawn on every start, so there is no page to move it to; +107 for the pages in the reader's own order (chet030714 on X): the order, the sidebar and tab bar put in it, and the menu's drag and keys in navorder.js and navpages.js, imported once an order is kept or Settings draws, and what is left is the one line in navHides that imports it; navHides runs on every start, so there is no page to move it to; +275 for the grants Alibaba's Token Plan asks of a RAM user's AccessKey in the reader's language (MetalHqa on X): one string (ALI_RAM) shown under the editor's AccessKey ID and on the card that names them, less the 48 of the wrong "a RAM user that may use Model Studio is enough" it replaces; the editor and quotaError draw them on every window, so there is no page to move them to; +135 for a model test its vendor queued shown queued and not green (sufeng1894 on X): queuedSaid, one string shared by the chip's title, Test models' and Test this model's status, and the chip's amber dot; renderModels draws the provider editor's chips, so there is no page to move it to; +66 for AstrLink Guard's row saying an x64 magpie runs it under Windows on Arm's emulation until the next update installs the Arm build (EV_John_Liu on X), the Rosetta line's sibling, one line in pmSub; the Privacy rows draw it, so there is no page to move it to - coreScriptBudget = 1_271_537 // every core script at 8016205e3, the old measure 682 over its cap there (#5918); +367 for the model test on a chosen account (tmr11235), no page left to move it to; +151 for the provider menu's "Only on this device" item and its four translations; +458 for Settings › About's Report a problem row and its translations; +113 for withScheme, the one rule every typed address goes through (eachg0 on X), cut to the shortest form that keeps it whole; +10 for the kept whole's tooltip (Musikrv77852 on X), the past-cycle line reused for it, no page left to move it to; +1,112 for Codex's Open button and its Open Codex with menu (Yink88564391 on X), packed to the shortest form, no page left to move them to; +168 for Discover's long lists drawn in part (the owner, 11-13), after the rest of its hook moved into plugingrid.js, imported when Plugins first draws; +296 for the cap toggle and Smart sentences that say what they do and the Sign in on another computer row (Wing8Aqua on X), packed to the shortest form, no page left to move them to; +333 for In turn's figure in a provider's editor and its words naming the message that goes round (Wing8Aqua on X), the figure itself in rotfig.js, imported when In turn is first shown, the hook packed to the shortest form; +236 for a lone capped Codex account's row saying its turns go to the fallbacks when Codex is connected (not_4O4 on X), the two helpers inlined, no page left to move it to; +717 for omp's advisor (Awad_Yoo on X, #6408): its three rows moved into ompadvisor.js, imported when an omp's settings show, and what is left is the import, the role's " · off" and the Settings line's name, packed to the shortest form; +468 for a plugin's own file import (auth.import) in the import sheet, in the plugin's words (marchen_cc on X), packed to one statement; importSay is read as the Providers rows draw, so it has no lazy page to go to, and nothing else was moved out; +180 for Claude Magpie's own Claude Code folder (xMopf7RF on X, #6459): its Advanced fold in claudemagpie.js, imported when it first shows, and what is left is the import and the fold's place in the Separate app line, 216 bytes packed to the shortest form, less the 36 of room there was; +81 for the Use Claude Magpie button on Claude Desktop's row (xMopf7RF on X), drawn by claudemagpie.js too, what is left the one line that places it (#2710); +225 for the Hermes row's Other profiles lines (Norethcy on X), which 1d60b165c took out while each profile had a row and c96f33d65 left with no place at all, packed to the shortest form; the dead hermes# Default note went with it, and the Agents rows draw it, so there is no page to move it to; +397 for a key's own price rate (tnt12231 on X): its lines, check and placeholder in keyrates.js, imported when a provider with two or more keys opens, and what is left is the import, the draft's copy, Advanced opening for it, the save's one line and proxyLines drawing another kind of line; +316 for an image or video model's chip saying what it makes from its right-click (iceloon on X): the chat chip's Makes… now shared with it, and the media chip's Copy model ID left out, packed to the shortest form; the provider's editor draws it, so there is no page to move it to; +67 for the Claude Code · Claude Magpie row saying it is on magpie through Claude Magpie (xMopf7RF on X), one line in connectLine with the shortest words that say it; the Agents rows draw it, so there is no page to move it to; +12 for AIGoCode's logo in pngIcons (MindfulReturn on X), the list every drawn icon is looked up in; +491 for each cost in the tray panel's and Requests' chart and ranking in its own provider's currency (onkashiko on X): ledProv and the provider passed through, packed to the shortest form; drawLedColumns and drawLedRank are shared by the panel, so there is no page to move it to; +326 for the Qwen AI platform's Token Plan sign-in (imthe99galaxy on X): its field, sign-in and wait in qianwenplan.js, imported when such a provider's editor opens, and what is left is the import and one quotaError line for its two refusals, packed to the shortest form; quotaError reads every card's error, so there is no page to move it to; +72 for Copy all keys (emilochen on X): its row in keyrates.js, imported when a provider with two or more keys opens through keyRateField, now told which of its parts to draw, and what is left is the one line that places it; +83 for the page saying it has gone from view, so what its Sessions and Usage pages keep goes in 30 s and not 7 minutes (P0 memory): folded into the visibilitychange listener every window has, packed to the shortest form, so there is no page to move it to; +270 for Providers' Select, to remove several at once (eiyuuzaki2333 on X): its rows, bar, removal and keys in pvpick.js, imported when Select is first clicked, and what is left is pvSel, the button's click and two lines in renderProviders, which draws the list, so there is no page to move it to; +81 for each account of a provider's Usage card in a card of its own (normalcoder_ on X): one line that makes the box, its brief look left to CSS, and renderQuotas, which draws every card, so there is no page to move it to; +17 for Kimi Code's booster balance under an allowance card's rings in the tray panel (apple_test_src on X): the card's text line and the wallet line share one filter, packed to the shortest form; panelQuotaCard draws every card, so there is no page to move it to; +51 for what a failed plugin install left in plugins/, listed under Installed with a Remove (CHENGJIAHEGOXIS on X): its section in plugininstalled.js as pmLeftovers, imported when Plugins first draws, and what is left is the one call after drawInstalled; draw is what draws the page, so there is no page to move it to; +123 for a sidebar list folded from its page's row (hkwok06 on X): the chevron, its click and the fold kept per page in navicons.js, imported with the first list, and what is left is the folded list read beside the hidden pages' (navList, which navMine now shares) and the two rows' clicks asking navFold first; navSubs draws every list, so there is no page to move it to; +338 for the Daily update channel (fishmagic80 on X): its segment, its line under Update channel and the version row's two Up to date on Daily words, packed to the shortest form (one t() per choice); Settings › About and renderUpdate draw them on every window, so there is no page to move them to; +35 for Baidu Qianfan's Token Plan sign-in (yuushabu_buyinn on X, #5860): its field in qianfanplan.js, imported when such a provider's editor opens, drawn by renderStepPlan now told whose sign-in it brings, and what is left is the import and two quotaError lines, past the room there was; quotaError reads every card's error, so there is no page to move it to; +27 for Windows' title bar (258a14 on X): the caption buttons, their clicks, the bar's double click and what keeps them over a dialog in wincap.js, imported in Windows' window alone, the header's room for them in app.css, and what is left is the one line that imports it, past the 29 of room there was; that window's frame is drawn on every start, so there is no page to move it to; +107 for the pages in the reader's own order (chet030714 on X): the order, the sidebar and tab bar put in it, and the menu's drag and keys in navorder.js and navpages.js, imported once an order is kept or Settings draws, and what is left is the one line in navHides that imports it; navHides runs on every start, so there is no page to move it to; +275 for the grants Alibaba's Token Plan asks of a RAM user's AccessKey in the reader's language (MetalHqa on X): one string (ALI_RAM) shown under the editor's AccessKey ID and on the card that names them, less the 48 of the wrong "a RAM user that may use Model Studio is enough" it replaces; the editor and quotaError draw them on every window, so there is no page to move them to; +135 for a model test its vendor queued shown queued and not green (sufeng1894 on X): queuedSaid, one string shared by the chip's title, Test models' and Test this model's status, and the chip's amber dot; renderModels draws the provider editor's chips, so there is no page to move it to; +66 for AstrLink Guard's row saying an x64 magpie runs it under Windows on Arm's emulation until the next update installs the Arm build (EV_John_Liu on X), the Rosetta line's sibling, one line in pmSub; the Privacy rows draw it, so there is no page to move it to + coreScriptBudget = 1_271_726 // every core script at 8016205e3, the old measure 682 over its cap there (#5918); +367 for the model test on a chosen account (tmr11235), no page left to move it to; +151 for the provider menu's "Only on this device" item and its four translations; +458 for Settings › About's Report a problem row and its translations; +113 for withScheme, the one rule every typed address goes through (eachg0 on X), cut to the shortest form that keeps it whole; +10 for the kept whole's tooltip (Musikrv77852 on X), the past-cycle line reused for it, no page left to move it to; +1,112 for Codex's Open button and its Open Codex with menu (Yink88564391 on X), packed to the shortest form, no page left to move them to; +168 for Discover's long lists drawn in part (the owner, 11-13), after the rest of its hook moved into plugingrid.js, imported when Plugins first draws; +296 for the cap toggle and Smart sentences that say what they do and the Sign in on another computer row (Wing8Aqua on X), packed to the shortest form, no page left to move them to; +333 for In turn's figure in a provider's editor and its words naming the message that goes round (Wing8Aqua on X), the figure itself in rotfig.js, imported when In turn is first shown, the hook packed to the shortest form; +236 for a lone capped Codex account's row saying its turns go to the fallbacks when Codex is connected (not_4O4 on X), the two helpers inlined, no page left to move it to; +717 for omp's advisor (Awad_Yoo on X, #6408): its three rows moved into ompadvisor.js, imported when an omp's settings show, and what is left is the import, the role's " · off" and the Settings line's name, packed to the shortest form; +468 for a plugin's own file import (auth.import) in the import sheet, in the plugin's words (marchen_cc on X), packed to one statement; importSay is read as the Providers rows draw, so it has no lazy page to go to, and nothing else was moved out; +180 for Claude Magpie's own Claude Code folder (xMopf7RF on X, #6459): its Advanced fold in claudemagpie.js, imported when it first shows, and what is left is the import and the fold's place in the Separate app line, 216 bytes packed to the shortest form, less the 36 of room there was; +81 for the Use Claude Magpie button on Claude Desktop's row (xMopf7RF on X), drawn by claudemagpie.js too, what is left the one line that places it (#2710); +225 for the Hermes row's Other profiles lines (Norethcy on X), which 1d60b165c took out while each profile had a row and c96f33d65 left with no place at all, packed to the shortest form; the dead hermes# Default note went with it, and the Agents rows draw it, so there is no page to move it to; +397 for a key's own price rate (tnt12231 on X): its lines, check and placeholder in keyrates.js, imported when a provider with two or more keys opens, and what is left is the import, the draft's copy, Advanced opening for it, the save's one line and proxyLines drawing another kind of line; +316 for an image or video model's chip saying what it makes from its right-click (iceloon on X): the chat chip's Makes… now shared with it, and the media chip's Copy model ID left out, packed to the shortest form; the provider's editor draws it, so there is no page to move it to; +67 for the Claude Code · Claude Magpie row saying it is on magpie through Claude Magpie (xMopf7RF on X), one line in connectLine with the shortest words that say it; the Agents rows draw it, so there is no page to move it to; +12 for AIGoCode's logo in pngIcons (MindfulReturn on X), the list every drawn icon is looked up in; +491 for each cost in the tray panel's and Requests' chart and ranking in its own provider's currency (onkashiko on X): ledProv and the provider passed through, packed to the shortest form; drawLedColumns and drawLedRank are shared by the panel, so there is no page to move it to; +326 for the Qwen AI platform's Token Plan sign-in (imthe99galaxy on X): its field, sign-in and wait in qianwenplan.js, imported when such a provider's editor opens, and what is left is the import and one quotaError line for its two refusals, packed to the shortest form; quotaError reads every card's error, so there is no page to move it to; +72 for Copy all keys (emilochen on X): its row in keyrates.js, imported when a provider with two or more keys opens through keyRateField, now told which of its parts to draw, and what is left is the one line that places it; +83 for the page saying it has gone from view, so what its Sessions and Usage pages keep goes in 30 s and not 7 minutes (P0 memory): folded into the visibilitychange listener every window has, packed to the shortest form, so there is no page to move it to; +270 for Providers' Select, to remove several at once (eiyuuzaki2333 on X): its rows, bar, removal and keys in pvpick.js, imported when Select is first clicked, and what is left is pvSel, the button's click and two lines in renderProviders, which draws the list, so there is no page to move it to; +81 for each account of a provider's Usage card in a card of its own (normalcoder_ on X): one line that makes the box, its brief look left to CSS, and renderQuotas, which draws every card, so there is no page to move it to; +17 for Kimi Code's booster balance under an allowance card's rings in the tray panel (apple_test_src on X): the card's text line and the wallet line share one filter, packed to the shortest form; panelQuotaCard draws every card, so there is no page to move it to; +51 for what a failed plugin install left in plugins/, listed under Installed with a Remove (CHENGJIAHEGOXIS on X): its section in plugininstalled.js as pmLeftovers, imported when Plugins first draws, and what is left is the one call after drawInstalled; draw is what draws the page, so there is no page to move it to; +123 for a sidebar list folded from its page's row (hkwok06 on X): the chevron, its click and the fold kept per page in navicons.js, imported with the first list, and what is left is the folded list read beside the hidden pages' (navList, which navMine now shares) and the two rows' clicks asking navFold first; navSubs draws every list, so there is no page to move it to; +338 for the Daily update channel (fishmagic80 on X): its segment, its line under Update channel and the version row's two Up to date on Daily words, packed to the shortest form (one t() per choice); Settings › About and renderUpdate draw them on every window, so there is no page to move them to; +35 for Baidu Qianfan's Token Plan sign-in (yuushabu_buyinn on X, #5860): its field in qianfanplan.js, imported when such a provider's editor opens, drawn by renderStepPlan now told whose sign-in it brings, and what is left is the import and two quotaError lines, past the room there was; quotaError reads every card's error, so there is no page to move it to; +27 for Windows' title bar (258a14 on X): the caption buttons, their clicks, the bar's double click and what keeps them over a dialog in wincap.js, imported in Windows' window alone, the header's room for them in app.css, and what is left is the one line that imports it, past the 29 of room there was; that window's frame is drawn on every start, so there is no page to move it to; +107 for the pages in the reader's own order (chet030714 on X): the order, the sidebar and tab bar put in it, and the menu's drag and keys in navorder.js and navpages.js, imported once an order is kept or Settings draws, and what is left is the one line in navHides that imports it; navHides runs on every start, so there is no page to move it to; +275 for the grants Alibaba's Token Plan asks of a RAM user's AccessKey in the reader's language (MetalHqa on X): one string (ALI_RAM) shown under the editor's AccessKey ID and on the card that names them, less the 48 of the wrong "a RAM user that may use Model Studio is enough" it replaces; the editor and quotaError draw them on every window, so there is no page to move them to; +135 for a model test its vendor queued shown queued and not green (sufeng1894 on X): queuedSaid, one string shared by the chip's title, Test models' and Test this model's status, and the chip's amber dot; renderModels draws the provider editor's chips, so there is no page to move it to; +66 for AstrLink Guard's row saying an x64 magpie runs it under Windows on Arm's emulation until the next update installs the Arm build (EV_John_Liu on X), the Rosetta line's sibling, one line in pmSub; the Privacy rows draw it, so there is no page to move it to; +189 for Let magpie set it on a Codex card locked by config.toml's own compact limit or background threshold (sufeng1894 on X), and Undo for a background share taken over: the shared send posts it, packed to the shortest form; adviceRow draws every card, so there is no page to move it to ) // codeBytes is how many bytes of b are code: its blank lines, its lines diff --git a/internal/gui/tests/context-tune.test.cjs b/internal/gui/tests/context-tune.test.cjs index c947eaadb..8f6e9dc14 100644 --- a/internal/gui/tests/context-tune.test.cjs +++ b/internal/gui/tests/context-tune.test.cjs @@ -750,6 +750,79 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", }); } +// sufeng1894 on X: "怎么codex不能手工调整压缩阈值了?" Codex's own +// model_auto_compact_token_limit (and its background threshold) in +// config.toml locked the card, and nothing on it said what to do. A lock +// magpie can take over now has one action, Let magpie set it: the click +// asks /api/tune/takeover, and the card then adjusts the limit with Use and +// Undo. A lock with nothing to take (take unset) offers nothing. In both +// engines, every language, a phone's width and a desk's. +const takeLabel = { en: "Let magpie set it", zh: "交给 magpie 设置", "zh-TW": "交給 magpie 設定", ja: "magpie に任せる", de: "magpie festlegen lassen" }; +const takeTune = (taken, take) => ({ + days: 7, + agents: [{ agent: "codex", calls: 2808, advice: [ + { knob: "compact", setting: taken ? { value: "140000", source: "long", ours: true } : { value: "140000", source: "config", locked: "model_auto_compact_token_limit", ...(take ? { take: true } : {}) }, + compact: { model: "gpt-5.5", current: 140000, window: 400000, best: 85000, cost: 1.4e9, low: 1.02e9, curve: curve(70000, 400000, 85000), facts }, + async: { percent: 30, value: 120000, window: 400000, setting: taken ? { value: "80", source: "async", ours: true } : { source: "async", locked: "features.async_compaction.model_async_compact_threshold_percent", ...(take ? { take: true } : {}) } } }, + ] }], +}); +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(`${engine}: Codex's own limit in config.toml is handed to magpie on a click`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + const errors = []; + t.after(() => browser.close()); + for (const lang of Object.keys(heading)) for (const [width, height] of [[360, 760], [1100, 760]]) { + await t.test(`${lang}, ${width}x${height}`, async () => { + const ctx = await browser.newContext({ viewport: { width, height }, reducedMotion: "reduce" }); + await ctx.addInitScript(() => { try { localStorage.setItem("magpie.usageTab", "context"); } catch {} }); + const page = await ctx.newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + page.on("pageerror", (e) => errors.push(e.message)); + const posts = []; + let taken = false, take = false; + const base = serve(lang, []); + await page.route("**/*", (r) => { + const p = new URL(r.request().url()).pathname; + if (p === "/api/tune") return r.fulfill({ json: takeTune(taken, take) }); + if (p.startsWith("/api/tune/")) { + posts.push({ path: p, ...JSON.parse(r.request().postData()) }); + if (p === "/api/tune/takeover") taken = true; + return r.fulfill({ json: {} }); + } + return base(r); + }); + await page.goto("http://magpie.test/?view=usage"); + const row = page.locator(".ctx-tune-row").nth(0); + const btn = row.locator(".ctx-tune-foot button.ctx-tune-take"); + // nothing magpie can take: no action + await row.locator(".ctx-tune-caveat").first().waitFor(); + assert.equal(await btn.count(), 0); + assert.equal(await row.locator(".ctx-tune-foot button.primary").count(), 0); + take = true; + await page.evaluate(() => window.loadContext()); + await btn.waitFor(); + // one action for both locks + assert.equal(await btn.count(), 1); + assert.equal(await btn.innerText(), takeLabel[lang]); + const over = await page.evaluate(() => { + const view = document.querySelector("#view-usage"); + return view.scrollWidth > view.clientWidth + 1 ? view.scrollWidth + ">" + view.clientWidth : ""; + }); + assert.equal(over, ""); + assert.deepEqual(posts, []); + await btn.click(); + await btn.waitFor({ state: "detached" }); + assert.deepEqual(posts, [{ path: "/api/tune/takeover", agent: "codex", knob: "compact", model: "", value: "" }]); + assert.equal(await btn.count(), 0); + assert.equal(await row.locator(".ctx-tune-caveat.ctx-tune-async").count(), 0); + await ctx.close(); + }); + } + assert.deepEqual(errors, []); + }); +} + // hoobnn on Discord (11-01): over 7 or 30 days, Use on Codex's window did // nothing. Those ranges held a model with a Compact at of its own (430K), // which "Now" was read from, so a Use moved Codex's other models and the diff --git a/internal/gui/tune.go b/internal/gui/tune.go index e52556776..072340559 100644 --- a/internal/gui/tune.go +++ b/internal/gui/tune.go @@ -405,6 +405,25 @@ func tuneRoutes(mux *http.ServeMux) { } writeJSON(rw, settingsState()) }) + // what Codex's config.toml sets before magpie, taken over on the + // user's click (agent.TuneTakeOver): Undo puts it back + mux.HandleFunc("POST /api/tune/takeover", func(rw http.ResponseWriter, r *http.Request) { + if gatewayRefused(rw) { + return + } + var in change + if err := json.NewDecoder(r.Body).Decode(&in); err != nil { + fail(rw, err) + return + } + if err := agent.TuneTakeOver("", in.Agent); err != nil { + fail(rw, err) + return + } + tuneForget() + s, _ := agent.TuneRead("", in.Agent, agent.TuneCompact, "") + writeJSON(rw, s) + }) mux.HandleFunc("POST /api/tune/undo", func(rw http.ResponseWriter, r *http.Request) { if gatewayRefused(rw) { return