tune: a Codex card locked by config.toml's own compact limit hands it to magpie on a click (sufeng1894 on X)

sufeng1894 asked why Codex's compaction threshold can no longer be set by
hand. The card said config.toml's model_auto_compact_token_limit wins, and
the background row said features.async_compaction's
model_async_compact_threshold_percent wins: both locked, and nothing on
the card did anything about it.

Cause. Only the old tune card (9e665491e to f20118304, 10-10 to 10-28)
wrote model_auto_compact_token_limit, stashing the user's own raw value;
the 10-28 migration puts that raw value back, which then locks the card.
So the values on the screen are the user's, or the user's restored by
that migration. A magpie-written value could have lost its stash through
stash.json races (before 270b52573), an unparsable stash (before
58651568b), tuneMigrateCodex forgetting the stash even when its file
write failed, and codexAsyncSync stashing only after every write. The
last two are fixed here: the migration forgets only after the write
succeeds, and codexAsyncSync records its stash in a defer right after
reading the old state, advancing it per successful write.

Change. A locked card shows one button, "Let magpie set it" (zh 交给
magpie 设置, zh-TW, ja, de), only when the user clicks. POST
/api/tune/takeover (TuneTakeOver):
- the file's limit moves into Long conversations by tuneMigrateCodex's
  rule (a lower Long the user has is kept), the key is deleted from
  config.toml with every other key kept, and the file value is stashed
  (tune.codex.compact_file); Undo puts Long back and writes the key back,
  unless the user changed Long since;
- a background threshold of the user's (enabled = true) is adopted as
  magpie's background share with its own Undo, which turns the share off
  and gives back the percent and enabled as they were. enabled = false
  is not taken.
Nothing removes the user's value without that click.

Run:
- internal/agent, internal/gui, internal/cli, internal/tune at the pushed
  head (rebased on ca87ae9c5) on mica: ok. TestCoreScriptBudget raised
  by 189 (the button, its post and Undo background), reason in the file.
- Full Go suite -timeout 45m on mica at the pre-rebase head (2ba62f7f7
  base): every package ok except TestCoreScriptBudget, since fixed.
- Broken by hand, red: migrate forgetting first (TestTuneCodexMigrateKeepsStash),
  asyncGiveBack disabled (TestTuneCodexTakeOverAsync), longUndo in place
  of codexLongUndo (TestTuneCodexTakeOver), and the GUI button disabled
  (context-tune, 11 red).
- context-tune, compact-one-value, codex-async-compact, i18n-keys at the
  pushed head on mica, Chromium and WebKit, every language, 360 and 1100:
  the new test passes; reds are codex-async-compact's zh/zh-TW "kept the
  share out" (4, the same at ca87ae9c5) and i18n-keys' routing plugin
  word (#6877).
- win-run TestTune|TestCodexAsync in agent and gui: ok. wsl-run vet and
  those tests with -tags nogui: ok. GOOS=windows go vet and GOOS=linux
  go vet -tags nogui: ok. gofmt -l: clean.
- make test-ui on mote, pre-rebase head, through header-centre (about a
  third; the rest still running when pushed): reds in 29 files, none a
  tune file. The first 16 (account-arrange to context-cap) were run
  alone at this head and at origin/main ca87ae9c5 on mica: the same
  reds at both (base has 4 more, in agent-own-direct), the #5475 class.
  The next 13 (ctx-session-line to header-centre) were run the same way at the pushed head: 59 red at head, 60 at ca87ae9c5, the same tests (header-centre's halfway case red in one engine at each).

Not tried: a real Codex session after the takeover; codexAsyncSync's
defer has no test with a failing write.
This commit is contained in:
yetone
2026-11-17 06:39:40 +08:00
parent ca87ae9c59
commit ce16633367
10 changed files with 570 additions and 24 deletions
File diff suppressed because one or more lines are too long
+13 -8
View File
@@ -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
}
+226 -12
View File
@@ -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
+226
View File
@@ -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)
}
}
+1
View File
@@ -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
+6 -2
View File
@@ -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;
}
+4
View File
@@ -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",
File diff suppressed because one or more lines are too long
+73
View File
@@ -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
+19
View File
@@ -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