diff --git a/internal/agent/codex_async.go b/internal/agent/codex_async.go index 54c03b402..ced2f27fa 100644 --- a/internal/agent/codex_async.go +++ b/internal/agent/codex_async.go @@ -356,3 +356,54 @@ func codexProviderCaps(path string) edit.Inline { } return out } + +// CodexAsyncHeldHere is the Codexes on this machine that would keep the +// background compaction's threshold out of its config (one before +// codexAsyncTableFrom, or of no known version), asked now rather than at +// the last sync, which asks only while the setting is on. +func CodexAsyncHeldHere(home string) []CodexReader { + return codexAsyncBlocked(codexReaders(here(tuneHome(home)))) +} + +// codexAsyncOwn names what the user has in Codex's config.toml that +// comes before magpie's background compaction threshold, as codexAsyncSync +// leaves it: the feature as a bare key of theirs (true at Codex's own 65%, +// or false), their table spelled inline or as dotted keys, enabled = false +// in it, or a threshold of their own. "" when magpie's threshold is what +// Codex would read. +func codexAsyncOwn(home string) string { + at := here(tuneHome(home)) + path := filepath.Join(at.codexHome(), "config.toml") + feature, _, err := codexAsyncNow(path) + if err != nil || feature == nil { + return "" + } + var st codexAsyncStash + if raw := stashLoad()[at.key("codex.async")]; raw != "" { + json.Unmarshal([]byte(raw), &st) + } + bare := "features.async_compaction" + switch f := feature.(type) { + case bool: + if f && st.Bool { + return "" + } + return bare + case map[string]any: + if t, err := edit.GetTOMLTable(path, codexAsyncTable); err != nil || t == nil { + return bare + } + if e, has := f["enabled"]; has { + if on, _ := e.(bool); !on { + return codexAsyncTable + ".enabled" + } + } + if p, has := f[codexAsyncPercent]; has { + if n, _ := p.(int64); st.Percent == 0 || int64(st.Percent) != n { + return codexAsyncTable + "." + codexAsyncPercent + } + } + return "" + } + return bare +} diff --git a/internal/agent/tune.go b/internal/agent/tune.go index add388858..da942930b 100644 --- a/internal/agent/tune.go +++ b/internal/agent/tune.go @@ -33,6 +33,10 @@ const ( TuneCompact = "compact" // when the agent compacts its conversation, in tokens TuneCache = "cache_ttl" // Claude Code: the main conversation's cache, 5m or 1h TuneSubCache = "subagent_cache_ttl" // Claude Code: its subagents', workflows' and helpers' + // Codex (0.163 on): the share of a model's window past which it + // compacts in the background while the turn goes on, 1–100; its + // foreground limit stays where it is, as the backstop + TuneAsync = "async_compact" ) // TuneSetting is one of those settings as an agent has it now. @@ -233,6 +237,9 @@ func (p tunePlace) envOf(k string) string { // TuneRead is how an agent has a setting tune advises now. func TuneRead(home, agent, knob, model string) (TuneSetting, error) { + if agent == "codex" && knob == TuneAsync { + return asyncRead(home), nil + } p, err := tuneWhere(home, agent, knob, model) if err != nil { return TuneSetting{}, err @@ -328,6 +335,9 @@ func tuneStashed(agent, knob, model string) (tuneStash, bool) { // was there before is kept, the first time only, for TuneUndo. A variable // that takes precedence is an error: the setting would change nothing. func TuneApply(home, agent, knob, model, value string) error { + if agent == "codex" && knob == TuneAsync { + return asyncApply(home, value) + } p, err := tuneWhere(home, agent, knob, model) if err != nil { return err @@ -379,6 +389,9 @@ func TuneApply(home, agent, knob, model, value string) error { // TuneUndo puts back what a setting was before tune put one in, unless // 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() + } p, err := tuneWhere(home, agent, knob, model) if err != nil { return err @@ -436,3 +449,94 @@ func tomlRaw(raw string) any { } return strings.Trim(raw, `"'`) } + +// Codex's background compaction, as tune puts the advice in it (herman_hong +// on Discord: a foreground compaction kept them waiting, so they set 384K +// by hand; the advice's 120K is wanted in the background, the 384K kept as +// the backstop). It is Settings' Background compaction +// (settings.CodexAsyncCompact, CodexAsyncCompactPercent), which Sync writes +// into Codex's config.toml as [features.async_compaction] enabled and +// model_async_compact_threshold_percent: a share of the model's window, +// not tokens (codex-rs core/src/config, 1 to 100, Codex's own 65). The +// foreground limit, the user's model_auto_compact_token_limit or Long +// conversations, isn't touched. What Settings had before is stashed, so +// Undo puts it back unless the user changed it since. + +// TuneAsyncSource is the Source of the background compaction's share. +const TuneAsyncSource = "async" + +const tuneAsyncKey = "tune.codex." + TuneAsync + +type tuneAsyncStash struct { + On bool `json:"on"` + Percent int `json:"percent"` + Set int `json:"set"` +} + +func asyncStashed() (tuneAsyncStash, bool) { + raw := stashLoad()[tuneAsyncKey] + var st tuneAsyncStash + if raw == "" || json.Unmarshal([]byte(raw), &st) != nil { + return tuneAsyncStash{}, false + } + return st, true +} + +func asyncOurs(s settings.Settings) bool { + st, ok := asyncStashed() + return ok && s.CodexAsyncCompact && s.CodexAsyncCompactPercent == st.Set +} + +// asyncRead is the share Codex compacts in the background at: "" when it +// is off, 65 for Codex's own. One the user has in config.toml comes first +// (codexAsyncOwn), and is Locked. +func asyncRead(home string) TuneSetting { + out := TuneSetting{Source: TuneAsyncSource} + if own := codexAsyncOwn(home); own != "" { + out.Locked = own + return out + } + s := settings.Load() + if s.CodexAsyncCompact { + p := s.CodexAsyncCompactPercent + if p == 0 { + p = 65 + } + out.Value = strconv.Itoa(p) + } + out.Ours = asyncOurs(s) + return out +} + +func asyncApply(home, value string) error { + n, err := strconv.Atoi(value) + if err != nil || n < 1 || n > 100 { + return fmt.Errorf("Codex compacts in the background past 1 to 100%% of a model's window, not %q", value) + } + if own := codexAsyncOwn(home); own != "" { + return fmt.Errorf("Codex's config.toml sets %s, which comes before magpie's: take it out first", own) + } + s := settings.Load() + st, ok := asyncStashed() + if !ok { + st = tuneAsyncStash{On: s.CodexAsyncCompact, Percent: s.CodexAsyncCompactPercent} + } + st.Set = n + b, _ := json.Marshal(st) + stash(map[string]string{tuneAsyncKey: string(b)}) + return provider.SetCodexAsyncCompact(true, n) +} + +// 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 { + st, ok := asyncStashed() + if !ok { + return fmt.Errorf("magpie didn't set Codex's background compaction") + } + defer forget(tuneAsyncKey) + if !asyncOurs(settings.Load()) { + return nil + } + return provider.SetCodexAsyncCompact(st.On, st.Percent) +} diff --git a/internal/agent/tune_test.go b/internal/agent/tune_test.go index a44365a27..c3712c7ff 100644 --- a/internal/agent/tune_test.go +++ b/internal/agent/tune_test.go @@ -380,3 +380,113 @@ func TestTuneCodexMigrateOnSync(t *testing.T) { t.Fatalf("Long conversations %d, want tune's 150000", got.CompactAt) } } + +// TestTuneCodexAsync: the advice goes into Background compaction as a +// share of the window; the foreground limit, the user's own in +// config.toml or Long conversations, stays where it is (herman_hong's 384K +// backstop), and Undo puts Background compaction back as it was. +func TestTuneCodexAsync(t *testing.T) { + home := tuneSandbox(t) + path := filepath.Join(home, ".codex", "config.toml") + tuneWrite(t, path, "model_auto_compact_token_limit = 384000\n") + if err := provider.SetCompactAt(200000); err != nil { + t.Fatal(err) + } + setAsyncCompact(t, false, 0) + if s := asyncRead(home); s.Value != "" || s.Locked != "" || s.Ours || s.Source != TuneAsyncSource { + t.Fatalf("read %+v: want off", s) + } + for _, bad := range []string{"0", "101", "120000", "x"} { + if err := TuneApply(home, "codex", TuneAsync, "", bad); err == nil { + t.Fatalf("applied %q", bad) + } + } + if err := TuneApply(home, "codex", TuneAsync, "", "30"); err != nil { + t.Fatal(err) + } + if got := settings.Load(); !got.CodexAsyncCompact || got.CodexAsyncCompactPercent != 30 || got.CompactAt != 200000 { + t.Fatalf("after apply: async=%v %d%% compactAt=%d", got.CodexAsyncCompact, got.CodexAsyncCompactPercent, got.CompactAt) + } + if got := tuneFile(t, path); !strings.Contains(got, "model_auto_compact_token_limit = 384000") { + t.Fatalf("the foreground limit moved:\n%s", got) + } + if s, _ := TuneRead(home, "codex", TuneAsync, ""); s.Value != "30" || !s.Ours { + t.Fatalf("read after apply %+v", s) + } + // applying again keeps what was there before tune + if err := TuneApply(home, "codex", TuneAsync, "", "25"); err != nil { + t.Fatal(err) + } + if err := TuneUndo(home, "codex", TuneAsync, ""); err != nil { + t.Fatal(err) + } + if got := settings.Load(); got.CodexAsyncCompact || got.CodexAsyncCompactPercent != 0 { + t.Fatalf("after undo: async=%v %d%%, want off", got.CodexAsyncCompact, got.CodexAsyncCompactPercent) + } + if err := TuneUndo(home, "codex", TuneAsync, ""); err == nil { + t.Fatal("undid twice") + } + // Codex's own 65 reads as 65; a share the user picks in Settings after + // Use is theirs, and Undo leaves it + setAsyncCompact(t, true, 0) + if s := asyncRead(home); s.Value != "65" || s.Ours { + t.Fatalf("read at Codex's own %+v", s) + } + if err := TuneApply(home, "codex", TuneAsync, "", "30"); err != nil { + t.Fatal(err) + } + if err := provider.SetCodexAsyncCompact(true, 50); err != nil { + t.Fatal(err) + } + if s := asyncRead(home); s.Value != "50" || s.Ours { + t.Fatalf("read after the user's 50 %+v", s) + } + if err := TuneUndo(home, "codex", TuneAsync, ""); err != nil { + t.Fatal(err) + } + if got := settings.Load(); !got.CodexAsyncCompact || got.CodexAsyncCompactPercent != 50 { + t.Fatalf("undo wrote over the user's 50: %v %d", got.CodexAsyncCompact, got.CodexAsyncCompactPercent) + } +} + +// TestTuneCodexAsyncOwn: background compaction the user set in Codex's +// config.toml comes before magpie's, so the card says so and Use changes +// nothing; a table magpie wrote itself is not the user's. +func TestTuneCodexAsyncOwn(t *testing.T) { + for _, c := range []struct{ name, file, key string }{ + {"own share", "[features.async_compaction]\nenabled = true\nmodel_async_compact_threshold_percent = 80\n", codexAsyncTable + "." + codexAsyncPercent}, + {"turned off", "[features.async_compaction]\nenabled = false\n", codexAsyncTable + ".enabled"}, + {"bare off", "[features]\nasync_compaction = false\n", "features.async_compaction"}, + {"bare on", "[features]\nasync_compaction = true\n", "features.async_compaction"}, + } { + t.Run(c.name, func(t *testing.T) { + home := tuneSandbox(t) + path := filepath.Join(home, ".codex", "config.toml") + tuneWrite(t, path, c.file) + setAsyncCompact(t, false, 0) + if s := asyncRead(home); s.Locked != c.key || s.Value != "" { + t.Fatalf("read %+v, want locked by %s", s, c.key) + } + if err := TuneApply(home, "codex", TuneAsync, "", "30"); err == nil { + t.Fatal("applied under the user's own") + } + if got := settings.Load(); got.CodexAsyncCompact { + t.Fatal("Background compaction turned on") + } + if got := tuneFile(t, path); got != c.file { + t.Fatalf("config.toml changed:\n%s", got) + } + }) + } + t.Run("magpie's own table", func(t *testing.T) { + home := tuneSandbox(t) + path := filepath.Join(home, ".codex", "config.toml") + tuneWrite(t, path, "[features.async_compaction]\nenabled = true\nmodel_async_compact_threshold_percent = 40\n") + b, _ := json.Marshal(codexAsyncStash{Enabled: true, Percent: 40}) + stash(map[string]string{here(tuneHome(home)).key("codex.async"): string(b)}) + setAsyncCompact(t, true, 40) + if s := asyncRead(home); s.Locked != "" || s.Value != "40" { + t.Fatalf("read %+v: magpie's own table counted as the user's", s) + } + }) +} diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 1e111d79f..17a992949 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -21389,7 +21389,7 @@ function renderAgentPrefs() { // a Codex here before 0.163, or of no known version (codexAsyncHeld) const held = s.codexAsyncCompact && s.codexAsyncHeld || [], box = el("div"); box.append(asyncRow); - if (held.length) box.append(el("div", "hint codex-async-held", t("{who}: the share needs Codex 0.163 or later; until it's updated magpie writes only async_compaction = true, at 65%", { who: held.map((r) => t({ app: "Codex app", ide: "Codex editor extension", wsl: "Codex in WSL" }[r.kind] || "Codex CLI") + (r.version ? " " + r.version : "")).join(", ") }))); + if (held.length) box.append(el("div", "hint codex-async-held", codexHeld(held))); $("#codexAsyncSegs").replaceChildren(box); renderCodexTitles(s); renderCodexDescriptions(s); diff --git a/internal/gui/assets/context.js b/internal/gui/assets/context.js index 71094f8ac..8eea033d8 100644 --- a/internal/gui/assets/context.js +++ b/internal/gui/assets/context.js @@ -23,6 +23,8 @@ }; const CELLS = 400; const partName = (k) => t(PART_NAMES[k] || k); + // the Codexes here before 0.163 or of no known version (app.js too) + const codexHeld = window.codexHeld = (held) => t("{who}: the share needs Codex 0.163 or later; until it's updated magpie writes only async_compaction = true, at 65%", { who: held.map((r) => t({ app: "Codex app", ide: "Codex editor extension", wsl: "Codex in WSL" }[r.kind] || "Codex CLI") + (r.version ? " " + r.version : "")).join(", ") }); const fmtK = (n) => { n = Math.max(0, Math.round(n || 0)); @@ -1506,11 +1508,11 @@ else if (set.value) note.textContent = t("You set {value}", { value: show(set.value) }); else note.textContent = t("The agent's default"); const key = [agent, a.knob, a.model || ""].join("\x00"); - const send = async (path, value) => { + const send = async (path, value, knob = a.knob) => { tuneBusy = key; renderContext(); try { - await api("tune/" + path, { agent, knob: a.knob, model: a.model || "", value: String(value ?? "") }); + 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"); } catch (e) { statusErr(e); @@ -1575,6 +1577,22 @@ }; foot.append(other); } + // Codex's background compaction at the advice, the limit kept (herman_hong) + const as = a.async, aset = as?.setting || {}, cav = (s) => row.append(el("p", "ctx-tune-caveat ctx-tune-async", s)); + const btn = (label, go, c = "") => { + const b = el("button", "text" + c, label); + b.type = "button"; + b.disabled = tuneBusy === key; + b.onclick = go; + return foot.appendChild(b); + }; + 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) }); row.append(foot); return row; } diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index ebb4387b2..858122e23 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -142,6 +142,11 @@ const I18N = { "The agent's default": "Agent 的默认值", "Saved: {agent} reads it from its next session": "已保存:{agent} 从下一个会话开始使用", "Put back": "已恢复", + "Use {value} in the background": "在后台用 {value}", + "Undo background": "撤销后台压缩", + "In the background at {value}": "后台压缩于 {value}", + "Background compaction: Codex's config.toml sets {key}, which comes first": "后台压缩:Codex 的 config.toml 设了 {key},以它为准", + "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}({window} 中约 {value})时,Codex 在后台压缩,当前回合照常进行;{now} 仍是前台压缩阈值,后台压缩没完成时兜底。这是 Codex 仍在开发中的功能,需要 0.163 或更新。", "Use {value}": "使用 {value}", "Replaces your {value}; Undo puts it back": "会替换你的 {value};撤销可恢复", "Long conversations, shared by Codex, Claude Code and Grok Build": "「长对话」,Codex、Claude Code 和 Grok Build 共用", @@ -4397,6 +4402,11 @@ const I18N = { "The agent's default": "Agent 的預設值", "Saved: {agent} reads it from its next session": "已儲存:{agent} 從下一個工作階段開始使用", "Put back": "已復原", + "Use {value} in the background": "在背景用 {value}", + "Undo background": "復原背景壓縮", + "In the background at {value}": "背景壓縮於 {value}", + "Background compaction: Codex's config.toml sets {key}, which comes first": "背景壓縮:Codex 的 config.toml 設了 {key},以它為準", + "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}({window} 中約 {value})時,Codex 在背景壓縮,目前回合照常進行;{now} 仍是前景壓縮閾值,背景壓縮沒完成時兜底。這是 Codex 仍在開發中的功能,需要 0.163 或更新。", "Use {value}": "使用 {value}", "Replaces your {value}; Undo puts it back": "會取代你的 {value};復原可還原", "Long conversations, shared by Codex, Claude Code and Grok Build": "「長對話」,Codex、Claude Code 與 Grok Build 共用", @@ -8627,6 +8637,11 @@ const I18N = { "The agent's default": "エージェントの既定値", "Saved: {agent} reads it from its next session": "保存しました:{agent} は次のセッションから使います", "Put back": "元に戻しました", + "Use {value} in the background": "バックグラウンドで {value} を使う", + "Undo background": "バックグラウンドを取り消す", + "In the background at {value}": "バックグラウンドで {value}", + "Background compaction: Codex's config.toml sets {key}, which comes first": "バックグラウンド圧縮: Codex の config.toml が {key} を設定しており、そちらが優先されます", + "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}({window} のうち約 {value})を超えると、Codex はターンを続けたままバックグラウンドで圧縮します。{now} はフォアグラウンドのしきい値として残り、バックグラウンドの圧縮が間に合わないときに使われます。Codex でまだ開発中の機能で、0.163 以降が必要です。", "Use {value}": "{value} にする", "Replaces your {value}; Undo puts it back": "あなたの {value} を置き換えます。取り消すと戻ります", "Long conversations, shared by Codex, Claude Code and Grok Build": "「長い会話」。Codex、Claude Code、Grok Build で共通", @@ -12864,6 +12879,11 @@ const I18N = { "The agent's default": "Standard des Agenten", "Saved: {agent} reads it from its next session": "Gespeichert: {agent} liest es ab der nächsten Sitzung", "Put back": "Zurückgesetzt", + "Use {value} in the background": "{value} im Hintergrund nutzen", + "Undo background": "Hintergrund rückgängig", + "In the background at {value}": "Im Hintergrund bei {value}", + "Background compaction: Codex's config.toml sets {key}, which comes first": "Hintergrundkomprimierung: Codex' config.toml setzt {key}, das hat Vorrang", + "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.": "Ab {pct} des Modellfensters, etwa {value} von {window}, komprimiert Codex im Hintergrund, während der Zug weiterläuft; {now} bleibt die Schwelle im Vordergrund, falls die im Hintergrund nicht fertig ist. Eine Codex-Funktion, die noch in Entwicklung ist, ab 0.163.", "Use {value}": "{value} verwenden", "Replaces your {value}; Undo puts it back": "Ersetzt dein {value}; Rückgängig stellt es wieder her", "Long conversations, shared by Codex, Claude Code and Grok Build": "„Lange Unterhaltungen“, die Codex, Claude Code und Grok Build teilen", diff --git a/internal/gui/core_budget_test.go b/internal/gui/core_budget_test.go index 7428dc21d..014de12c1 100644 --- a/internal/gui/core_budget_test.go +++ b/internal/gui/core_budget_test.go @@ -16,7 +16,7 @@ import ( // raises them and says why in its commit. const ( appScriptBudget = 1_316_781 // app.js: 1,198,239 after Usage left (P2); 1,218,098 with the 10-15 fixes to pages still in the core; 1,232,466 with the provider editor's Advanced fold and every dialog holding its place, the core's own (10-16); 1,250,533 with the quota refresh kept through redraws, the core's own since the tray panel draws it too, plus 1.5% (#2397); 1,269,083 with Free first's option in the provider editor's ROUTINGS, which the Routing page reads too, plus 1.5%; 1,272,726 with the Providers page drawing its last list at once (#1519), the core's page, and the Routing trace's account names read without Object.entries (#1481), plus 1.5%; a dialog growing out of the row that opened it and folding back into it, the core's own since every page's dialogs open through it (10-20); Codex's and Claude Code's own settings moved from Settings into the agent's row on the Agents page, the core's own since the tray panel and the window both draw them (10-20); 1,314,432 with Settings › Privacy's record of what was masked (its summary, the records view and the local model's controls), which belongs to Settings, the core's own, plus 1.5%; 1,336,481 with a provider's Names & levels saying Provider in model names is Settings' and opening it there (joe), and Settings' Image recognition saying where a custom provider's model is marked (nexnull), both in the core's own pages, with no room added (10-23); 1,337,633 with Settings › Models › Replies' Intent classifier timeout (#2934, reyoung), Settings' own row, drawn by waitRow, which the Image generation timeout's row now shares, with no room added; 1,337,735 with the provider editor's link naming a partner's page by its own host (siteHost) instead of usemagpie.ai's /go link, the core's own editor, with no room added (10-23); 1,338,084 with Check in now saying what the press came to (claimed +credits, already today, not available yet) where it said "refreshed" (#3326), the check-in row the tray panel draws too, the core's own, with no room added (10-23); 1,338,929 with a new partner's tile keeping a small dot until it is opened, in the add sheet, the core's own, with no room added (10-23); 1,343,324 with the sidebar's open-page row marked by one shape that moves on a spring (navTopGo), the window's own shell, which every page sits beside, with no room added (10-23); 1,343,465 with a dialog kept centred while its content comes in, until it is pressed (holdModal, every page's dialogs), the core's own, with no room added (10-24); 1,317,486 with what masking did moved out to Insights › Masking (plugins/redact), the budget lowered to it (10-24); 1,321,336 with Codex's one subagent model, its card's square saying plainly what each choice does and a row with a name in its sheet, where two squares read alike (the owner), the Agents page's, which the tray panel draws too, the core's own, with no room added (10-24); 1,321,424 with Settings › Models' Image generation MCP server row beside Image recognition's (JonahFu on X), the two drawn by one helper (mcpRow), Settings' own, with no room added (10-25); 1,321,994 with a provider of the user's set never to rest for a limit (zoecats), the provider editor's Advanced row, the core's own editor, with no room added (10-25); 1,322,289 with Settings › Privacy's Keep a key's form under Mask secrets (Charles Cao on X), Settings' own row, with no room added (10-25); 1,322,537 with no Codex squares beside its named settings rows (the owner), with no room added (10-25); 1,323,401 with the tray panel drawing its last allowances at once and asking for them beside the state (#3160, #3134), the tray panel's, the core's own, and the 4 bytes 84c50f032 added, with no room added (10-25); 1,326,105 with many releases' notes merged into one list by kind, each line with its version (the owner), in the update sheet and What's new, with no room added (10-25); 1,321,319 with Settings › Observability moved out to its plugin (plugins/otel/page.js) and its Langfuse setup there (an X user), the budget lowered to it (10-26); a quota card whose window is used but names no reset no longer saying "Not used yet" (windy on Discord) raised it to 1,321,347, and back to 1,321,319 with Settings' model pickers sharing one row helper (modelOpt) where six kept their own copy, no raise (10-26); 1,325,845 with every slow page's skeletons getting magpie's bird hopping bar to bar (skelBird, the owner after the Plugins page's README), one bird for the window over whatever page or dialog is loading, the core's own, with no room added (10-26); 1,310,129 with Settings › Network and sharing's gateway rows (its port, bare ids, local network, allowed addresses, web pages) moved out to the gateway plugin (plugins/gateway/settings.js), the budget lowered to it (10-27); 1,310,269 with Test models naming the first model that failed and its error in the status line, where it said only how many (ysm119 on Discord), the provider editor's, the core's own, with no room added (10-27); 1,310,460 with Settings › About's Website row linking usemagpie.ai (the owner), Settings' own row, with no room added (10-27); 1,309,669 with a pool's Stop at the caps and Check usage near a cap ticks under a provider's accounts (plugins#349), the core's own editor, its account rows' Remove and add rows each drawn by one helper (forgetOf, addRow), with no room added (10-28); 1,311,681 with Install another agent on the Agents page naming the agents Plugins has (More in Plugins) and opening Plugins at its Agents (the owner), the Agents page's, the core's own, with no room added (10-28); 1,311,735 with More in Plugins in sight while Install another agent is folded (the owner), with no room added (10-29); 1,313,704 with a window whose WebKit scrolls under wheels it never tells of (macOS 13) remembered once seen, a scroll at rest then waiting 120ms for a second the same way within 80ms before it is put back, kept for a late wheel to give back (waitsBack), and a load landing under the wheel keeping the reader's way (backAfterLoad, issennknight), the window's own scroll guard, with no room added (10-29); back to 1,311,735 with Settings › Models › Web search's rows (renderSearch, renderSearcher, the search APIs' keys) moved out to the search plugin (plugins/search/settings.js), app.js 1,292,527 after it, not lowered further since what is left plus 1.5% is over it (#4133, 10-29); 1,315,316 with the Agents row of a Claude Code or Codex not connected saying the account it is signed in to and switching it to another (Switch accounts only, the owner on X), in place of the failover line's ChatGPT accounts button, the Agents page's, the core's own, its comments cut down, with no room added (10-30); 1,317,705 with a Claude account added from a setup-token (sfss5362 on X): the sign-in's Use a setup-token instead…, its sheet, and its account row's magpie only, the provider editor's account rows, the core's own editor, its comments cut down, with no room added (10-30); back to 1,315,316 with the setup-token sheet and Copilot's GHE.com one moved out to signsheets.js, loaded when one is asked for (signAsk, 10-30); 1,315,479 with the provider editor lining its Advanced up with its fields (the owner: 高级这个折叠按钮为什么在一个前不着村后不着店的位置?) and a refresh on each of its accounts (在这里也要加上手动刷新用量的按钮), the core's own editor, with no room added (10-31); 1,315,603 with About's Log row, the path of the log the app writes and an Open for its folder (rayem1w on X), in app.js, its comment cut to one line, with no room added (10-31); 1,316,781 with a provider's model listed by an id of the user's (zeewell on X), the provider editor's Names & levels Listed as box beside Same as, the core's own editor, with no room added (10-31) - coreScriptBudget = 1_539_856 // every core script: 1,358,034 after Usage left; 1,380,003 with them; 1,405,937 with the fold; 1,426,102 with 10-16's core work (the GitHub list loading, the move to plugins, Settings › Long conversations), plus 1.5% (#2612); 1,447,368 with loadBack, the window's one state read per return, which every page needs and so is the core's own (1,446,845 before it, 155 bytes under), plus 1.5%; OpenCode Zen's card saying OpenCode tells no key its balance adds ~390 bytes inside it; 1,472,589 with the dialog that grows out of its row and the agents' own settings in their rows, on main's 10-20 core work (the Providers page's last list, the Routing trace's names), plus 1.5% (10-20); 1,506,192 with Settings › Privacy's record of what was masked, plus 1.5%; 1,529,393 with the Intent classifier timeout row (#2934), with no room added; 1,529,495 with the editor's partner link host, with no room added; 1,529,844 with Check in now's press summary (#3326), with no room added; 1,530,689 with the new partner tile's dot, with no room added; 1,535,084 with the sidebar's spring, with no room added; 1,549,478 with the context window card's map (tiles by tokens, the default look, the block grid a switch away) and its text view showing an inline image, in context.js, which the Routing page draws as well as Usage, so the core's own, with no room added (10-24); 1,550,768 with a usage card's refresh opening after its text (#840's card, which the tray panel draws too), the Add key spinner, and a dialog kept centred while its content comes in, with no room added (10-24); 1,524,789 with what masking did moved out to Insights › Masking, lowered to it; 1,528,525 with Codex's one subagent model, with no room added (10-24); 1,528,972 with the Image generation MCP server row (JonahFu on X), with no room added (10-25); 1,529,542 with the limit-rest row (zoecats), with no room added (10-25); 1,529,837 with Keep a key's form (Charles Cao on X), with no room added (10-25); 1,530,050 with no Codex squares beside its named settings rows (the owner), with no room added (10-25); 1,530,631 with a plugin's page growing to its README on the dialog's spring instead of in one jump (the owner), the Plugins page's, in plugins.js, with no room added (10-25); 1,533,445 with the context map counting its tokens on as a live request grows, a tile pointed at keeping its tip, a tool's gathered results saying how many and the small files their folder (the owner, after flohoeller's map on X), in context.js, which the Routing page draws as well as Usage, and the 4 bytes 84c50f032 added to app.js (Settings' Version row) without a raise, with no room added (10-25); 1,534,312 with the tray panel's last allowances drawn at once (#3160, #3134), with no room added (10-25); 1,537,016 with many releases' notes merged into one list by kind (the owner), in app.js, with no room added (10-25); 1,542,244 with a plugin's README loading under magpie's bird bouncing down its lines instead of pulsing bars (the owner), the Plugins page's, in plugins.js, with no room added (10-26); 1,542,418 with a page plugin's sidebar tab coming and going as it is installed, switched on or off, or removed, instead of on the Plugins page's next load (the owner), in plugins.js, with no room added (10-26); 1,537,645 with Settings › Observability moved out to plugins/otel, lowered to it (10-26); 1,537,673 with a used window with no reset not "Not used yet" (windy on Discord), and back to 1,537,645 with Settings' model pickers sharing modelOpt (10-26); 1,541,967 with every slow page's skeletons getting magpie's bird (skelBird, the owner), in app.js, the README's bird sharing its drawing and styles, with no room added (10-26); 1,526,251 with Settings' gateway rows moved out to plugins/gateway/settings.js, lowered to it (10-27); 1,526,391 with Test models naming the first failed model and its error (ysm119 on Discord), in app.js, with no room added (10-27); 1,526,556 with About's Website row (the owner), in app.js, with no room added (10-27); 1,526,500 with a pool's cap ticks (plugins#349), in app.js, with no room added (10-28); 1,527,245 with About's Open-source licenses row and dialog (the owner), in app.js, with no room added (10-28); 1,528,076 with the Partners heading's light (the owner), in app.js, with no room added (10-28); 1,530,449 with Install another agent's More in Plugins row (the owner), in app.js, and Plugins opening at its Agents, in plugins.js, with no room added (10-28); 1,530,807 with layout.js measuring the scrollbar into --bar, which every page's right padding takes off so its sides match (the owner), the window's own shell, with no room added (10-28); 1,530,861 with More in Plugins in sight while Install another agent is folded (the owner), in app.js, with no room added (10-29); 1,532,830 with waitsBack and backAfterLoad (issennknight, macOS 13), the window's own scroll guard, in app.js, with no room added (10-29); the context map's tile wording (a4e929212) and Cindy's Add magpie (628ac36fc) had taken the core over it, and Web search's rows moved out to plugins/search/settings.js brought it back to 1,530,861 (#4133, 10-29); 1,532,459 with a provider editor's account rows on one line each, First or Make first at its right end and the settings that aren't set under ⋯ (the owner), the core's own editor, in app.js, which stays in its budget with its comments cut down, with no room added (10-29); 1,532,602 with a plugin's README waiting for its bird to land on three lines before it goes in, however soon it came (the owner, 10-30), in plugins.js, with no room added; 1,536,357 with Switch accounts only on the Agents row (the owner on X), in app.js, with no room added (10-30); 1,537,034 with a plugin's README read once shown at once, with no bird, when its page opens again and read again behind it, the last 20 kept (the owner), in plugins.js, with no room added (10-30); 1,539,423 with a Claude account added from a setup-token (sfss5362 on X), in app.js, with no room added (10-30); 1,538,975 with purposes.js written as compact JSON by genpurposes and the MCP tool purpose in it, 448 bytes less in all (ferock on Discord), lowered to it (10-30); 1,536,586 with the setup-token sheet and Copilot's GHE.com one moved out to signsheets.js, lowered by the 2,389 the setup-token raised it (10-30); 1,536,631 with the 45 bytes b62fa332f added to app.js (Send requests unmasked for subscriptions and plugin providers too) without a raise, with no room added (10-31); 1,537,356 with Settings › Models › Replies › Claude Code's interactive mode, a row beside Short Claude system prompt (the owner), in app.js, with no room added (10-31); Long conversations in Codex's row naming the config.toml keys Codex reads before it, with Take it out, and the window magpie tells Codex for the model it runs (zgjfjfl on Discord) raised it to 1,537,669, and it is back under 1,537,356 with the key list and the window's size written by the server (codexKeysText, tokensSize) and the row's words cut, no raise (10-31); 1,538,554 with the same two, with no room added (10-31); 1,538,678 with About's Log row (rayem1w on X), with no room added (10-31); 1,539,856 with a model's Listed as id (zeewell on X), in app.js, with no room added (10-31) + coreScriptBudget = 1_541_427 // every core script: 1,358,034 after Usage left; 1,380,003 with them; 1,405,937 with the fold; 1,426,102 with 10-16's core work (the GitHub list loading, the move to plugins, Settings › Long conversations), plus 1.5% (#2612); 1,447,368 with loadBack, the window's one state read per return, which every page needs and so is the core's own (1,446,845 before it, 155 bytes under), plus 1.5%; OpenCode Zen's card saying OpenCode tells no key its balance adds ~390 bytes inside it; 1,472,589 with the dialog that grows out of its row and the agents' own settings in their rows, on main's 10-20 core work (the Providers page's last list, the Routing trace's names), plus 1.5% (10-20); 1,506,192 with Settings › Privacy's record of what was masked, plus 1.5%; 1,529,393 with the Intent classifier timeout row (#2934), with no room added; 1,529,495 with the editor's partner link host, with no room added; 1,529,844 with Check in now's press summary (#3326), with no room added; 1,530,689 with the new partner tile's dot, with no room added; 1,535,084 with the sidebar's spring, with no room added; 1,549,478 with the context window card's map (tiles by tokens, the default look, the block grid a switch away) and its text view showing an inline image, in context.js, which the Routing page draws as well as Usage, so the core's own, with no room added (10-24); 1,550,768 with a usage card's refresh opening after its text (#840's card, which the tray panel draws too), the Add key spinner, and a dialog kept centred while its content comes in, with no room added (10-24); 1,524,789 with what masking did moved out to Insights › Masking, lowered to it; 1,528,525 with Codex's one subagent model, with no room added (10-24); 1,528,972 with the Image generation MCP server row (JonahFu on X), with no room added (10-25); 1,529,542 with the limit-rest row (zoecats), with no room added (10-25); 1,529,837 with Keep a key's form (Charles Cao on X), with no room added (10-25); 1,530,050 with no Codex squares beside its named settings rows (the owner), with no room added (10-25); 1,530,631 with a plugin's page growing to its README on the dialog's spring instead of in one jump (the owner), the Plugins page's, in plugins.js, with no room added (10-25); 1,533,445 with the context map counting its tokens on as a live request grows, a tile pointed at keeping its tip, a tool's gathered results saying how many and the small files their folder (the owner, after flohoeller's map on X), in context.js, which the Routing page draws as well as Usage, and the 4 bytes 84c50f032 added to app.js (Settings' Version row) without a raise, with no room added (10-25); 1,534,312 with the tray panel's last allowances drawn at once (#3160, #3134), with no room added (10-25); 1,537,016 with many releases' notes merged into one list by kind (the owner), in app.js, with no room added (10-25); 1,542,244 with a plugin's README loading under magpie's bird bouncing down its lines instead of pulsing bars (the owner), the Plugins page's, in plugins.js, with no room added (10-26); 1,542,418 with a page plugin's sidebar tab coming and going as it is installed, switched on or off, or removed, instead of on the Plugins page's next load (the owner), in plugins.js, with no room added (10-26); 1,537,645 with Settings › Observability moved out to plugins/otel, lowered to it (10-26); 1,537,673 with a used window with no reset not "Not used yet" (windy on Discord), and back to 1,537,645 with Settings' model pickers sharing modelOpt (10-26); 1,541,967 with every slow page's skeletons getting magpie's bird (skelBird, the owner), in app.js, the README's bird sharing its drawing and styles, with no room added (10-26); 1,526,251 with Settings' gateway rows moved out to plugins/gateway/settings.js, lowered to it (10-27); 1,526,391 with Test models naming the first failed model and its error (ysm119 on Discord), in app.js, with no room added (10-27); 1,526,556 with About's Website row (the owner), in app.js, with no room added (10-27); 1,526,500 with a pool's cap ticks (plugins#349), in app.js, with no room added (10-28); 1,527,245 with About's Open-source licenses row and dialog (the owner), in app.js, with no room added (10-28); 1,528,076 with the Partners heading's light (the owner), in app.js, with no room added (10-28); 1,530,449 with Install another agent's More in Plugins row (the owner), in app.js, and Plugins opening at its Agents, in plugins.js, with no room added (10-28); 1,530,807 with layout.js measuring the scrollbar into --bar, which every page's right padding takes off so its sides match (the owner), the window's own shell, with no room added (10-28); 1,530,861 with More in Plugins in sight while Install another agent is folded (the owner), in app.js, with no room added (10-29); 1,532,830 with waitsBack and backAfterLoad (issennknight, macOS 13), the window's own scroll guard, in app.js, with no room added (10-29); the context map's tile wording (a4e929212) and Cindy's Add magpie (628ac36fc) had taken the core over it, and Web search's rows moved out to plugins/search/settings.js brought it back to 1,530,861 (#4133, 10-29); 1,532,459 with a provider editor's account rows on one line each, First or Make first at its right end and the settings that aren't set under ⋯ (the owner), the core's own editor, in app.js, which stays in its budget with its comments cut down, with no room added (10-29); 1,532,602 with a plugin's README waiting for its bird to land on three lines before it goes in, however soon it came (the owner, 10-30), in plugins.js, with no room added; 1,536,357 with Switch accounts only on the Agents row (the owner on X), in app.js, with no room added (10-30); 1,537,034 with a plugin's README read once shown at once, with no bird, when its page opens again and read again behind it, the last 20 kept (the owner), in plugins.js, with no room added (10-30); 1,539,423 with a Claude account added from a setup-token (sfss5362 on X), in app.js, with no room added (10-30); 1,538,975 with purposes.js written as compact JSON by genpurposes and the MCP tool purpose in it, 448 bytes less in all (ferock on Discord), lowered to it (10-30); 1,536,586 with the setup-token sheet and Copilot's GHE.com one moved out to signsheets.js, lowered by the 2,389 the setup-token raised it (10-30); 1,536,631 with the 45 bytes b62fa332f added to app.js (Send requests unmasked for subscriptions and plugin providers too) without a raise, with no room added (10-31); 1,537,356 with Settings › Models › Replies › Claude Code's interactive mode, a row beside Short Claude system prompt (the owner), in app.js, with no room added (10-31); Long conversations in Codex's row naming the config.toml keys Codex reads before it, with Take it out, and the window magpie tells Codex for the model it runs (zgjfjfl on Discord) raised it to 1,537,669, and it is back under 1,537,356 with the key list and the window's size written by the server (codexKeysText, tokensSize) and the row's words cut, no raise (10-31); 1,538,554 with the same two, with no room added (10-31); 1,538,678 with About's Log row (rayem1w on X), with no room added (10-31); 1,539,856 with a model's Listed as id (zeewell on X), in app.js, with no room added (10-31); 1,541,427 with Tuned for you's Codex row offering the advice to background compaction, its foreground limit kept (herman_hong on Discord), in context.js, which Usage and Routing draw, the Codex-too-old line shared with Settings' row (codexHeld, app.js 278 bytes less), with no room added (10-31) ) func TestCoreScriptBudget(t *testing.T) { diff --git a/internal/gui/tests/context-tune.test.cjs b/internal/gui/tests/context-tune.test.cjs index 636828679..c87036fe0 100644 --- a/internal/gui/tests/context-tune.test.cjs +++ b/internal/gui/tests/context-tune.test.cjs @@ -627,3 +627,112 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", assert.deepEqual(errors, []); }); } + +// Codex's background compaction at the advice (herman_hong on Discord: a +// foreground compaction kept them waiting, so they set 384K in config.toml +// by hand; the advice's 120K is wanted in the background, the 384K kept). +// The row offers it beside the foreground limit, which it never changes: +// the click puts 30% (of a 400K window) in Background compaction, then a +// chip says so and Undo puts it back. Codex's config.toml setting its own +// share, or a Codex too old for one, says why and offers nothing. In both +// engines, every language, a phone's width and a desk's. +const asyncTune = (as) => ({ + days: 7, + agents: [{ agent: "codex", calls: 2808, advice: [ + { knob: "compact", setting: { value: "384000", source: "config", locked: "model_auto_compact_token_limit" }, + compact: { model: "gpt-5.5", current: 384000, window: 400000, best: 120000, cost: 1.4e9, low: 1.02e9, curve: curve(90000, 400000, 120000), facts }, + async: { percent: 30, value: 120000, window: 400000, setting: { source: "async", ...as.setting }, ...(as.held ? { held: as.held } : {}) } }, + ] }], +}); +const asyncUse = { en: "Use 120K in the background", zh: "在后台用 120K", "zh-TW": "在背景用 120K", ja: "バックグラウンドで 120K を使う", de: "120K im Hintergrund nutzen" }; +const asyncOn = { en: "In the background at 120K", zh: "后台压缩于 120K", "zh-TW": "背景壓縮於 120K", ja: "バックグラウンドで 120K", de: "Im Hintergrund bei 120K" }; +const asyncUndo = { en: "Undo background", zh: "撤销后台压缩", "zh-TW": "復原背景壓縮", ja: "バックグラウンドを取り消す", de: "Hintergrund rückgängig" }; +const asyncTip = { + en: "Codex compacts in the background past 30% of the model's window, about 120K of 400K, while the turn goes on; 384K stays as the foreground limit, for when the background one isn't ready. A Codex feature still under development, 0.163 or later.", + zh: "对话超过模型窗口的 30%(400K 中约 120K)时,Codex 在后台压缩,当前回合照常进行;384K 仍是前台压缩阈值,后台压缩没完成时兜底。这是 Codex 仍在开发中的功能,需要 0.163 或更新。", +}; +const asyncLocked = { + en: "Background compaction: Codex's config.toml sets features.async_compaction.enabled, which comes first", + zh: "后台压缩:Codex 的 config.toml 设了 features.async_compaction.enabled,以它为准", + "zh-TW": "背景壓縮:Codex 的 config.toml 設了 features.async_compaction.enabled,以它為準", + ja: "バックグラウンド圧縮: Codex の config.toml が features.async_compaction.enabled を設定しており、そちらが優先されます", + de: "Hintergrundkomprimierung: Codex' config.toml setzt features.async_compaction.enabled, das hat Vorrang", +}; +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(`${engine}: Codex takes the advice in the background, its own limit kept`, 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 as = { setting: {} }; + const base = serve(lang, []); + await page.route("**/*", (r) => { + const p = new URL(r.request().url()).pathname; + if (p === "/api/tune") return r.fulfill({ json: asyncTune(as) }); + if (p === "/api/tune/apply" || p === "/api/tune/undo") { + const b = JSON.parse(r.request().postData()); + posts.push({ path: p, ...b }); + as = { setting: p.endsWith("apply") ? { value: b.value, ours: true } : { value: "65" } }; + 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 go = row.locator(".ctx-tune-foot button.ctx-tune-async"); + await go.waitFor(); + assert.equal(await go.innerText(), asyncUse[lang]); + if (asyncTip[lang]) assert.equal(await go.getAttribute("data-tt"), asyncTip[lang]); + // the foreground limit is the user's own: still no Use for it + assert.equal(await row.locator(".ctx-tune-foot button.primary").count(), 0); + assert.equal(await page.locator(".ctx-tune select, .ctx-tune-row .ctx-chip.ctx-tune-async").count(), 0); + const over = () => page.evaluate(() => { + const view = document.querySelector("#view-usage"); + const out = view.scrollWidth > view.clientWidth + 1 ? ["page " + view.scrollWidth + ">" + view.clientWidth] : []; + const b = document.querySelector(".ctx-tune").getBoundingClientRect(); + for (const e of document.querySelectorAll(".ctx-tune *")) { + const r = e.getBoundingClientRect(); + if (r.width && (r.right > b.right + 1 || r.left < b.left - 1)) out.push((e.className.baseVal ?? e.className) + " " + Math.round(r.left) + "–" + Math.round(r.right)); + } + return out; + }); + assert.deepEqual(await over(), []); + await go.click(); + const chip = row.locator(".ctx-chip.good.ctx-tune-async"); + await chip.waitFor(); + assert.deepEqual(posts, [{ path: "/api/tune/apply", agent: "codex", knob: "async_compact", model: "", value: "30" }]); + assert.equal(await chip.innerText(), asyncOn[lang]); + assert.equal(await go.count(), 0); + const undo = row.locator(".ctx-tune-foot button.text", { hasText: asyncUndo[lang] }); + assert.equal(await undo.count(), 1); + assert.deepEqual(await over(), []); + await undo.click(); + await go.waitFor(); + assert.deepEqual(posts[1], { path: "/api/tune/undo", agent: "codex", knob: "async_compact", model: "", value: "" }); + assert.equal(await chip.count(), 0); + // the user's own in config.toml, then a Codex too old for a share: + // each says why, and there's nothing to click + as = { setting: { locked: "features.async_compaction.enabled" } }; + await page.evaluate(() => window.loadContext()); + await row.locator(".ctx-tune-caveat.ctx-tune-async").waitFor(); + assert.equal(await row.locator(".ctx-tune-caveat.ctx-tune-async").innerText(), asyncLocked[lang]); + assert.equal(await go.count(), 0); + as = { setting: {}, held: [{ kind: "cli", version: "0.162.1" }] }; + await page.evaluate(() => window.loadContext()); + await row.locator(".ctx-tune-caveat.ctx-tune-async", { hasText: "0.162.1" }).waitFor(); + assert.equal(await go.count(), 0); + assert.deepEqual(await over(), []); + await ctx.close(); + }); + } + assert.deepEqual(errors, []); + }); +} diff --git a/internal/gui/tune.go b/internal/gui/tune.go index 2b89cab92..27c728740 100644 --- a/internal/gui/tune.go +++ b/internal/gui/tune.go @@ -34,6 +34,44 @@ type tuneAdvice struct { // window in Long conversations doesn't move it (hoobnn on Discord: a // card said "In use" for 170K beside "Now 430K") Own *tuneOwn `json:"own,omitempty"` + // Async is Codex's background compaction at the advice, its foreground + // limit kept as the backstop; nil where it can't help + Async *tuneAsync `json:"async,omitempty"` +} + +// tuneAsync is the advice as Codex's background compaction takes it: a +// share of the model's window (Percent), about Value tokens of Window. +// Held are the Codexes here too old for the share, or of no known version. +type tuneAsync struct { + Percent int `json:"percent"` + Value int `json:"value"` + Window int `json:"window"` + Setting agent.TuneSetting `json:"setting"` + Held []agent.CodexReader `json:"held,omitempty"` +} + +// codexAsyncAt is the advice r as a share of the window Codex's +// background compaction starts at: the fewest tokens (a compaction in the +// background keeps no one waiting, so the wait the advice weighs doesn't +// count), rounded down, so it starts no later than that. ok is false +// where it would start no sooner than the foreground does, at the lesser +// of the limit now and 90% of the window (codex-rs ModelInfo +// auto_compact_token_limit), and where the window isn't known. +func codexAsyncAt(r *tune.Compaction) (percent, value int, ok bool) { + if r == nil || r.Window <= 0 { + return 0, 0, false + } + v := r.Best + if r.Cheapest > 0 && r.Facts.Took > 0 { + v = r.Cheapest + } + percent = max(1, min(100, v*100/r.Window)) + value = r.Window * percent / 100 + fg := r.Window * 9 / 10 + if r.Current > 0 { + fg = min(fg, r.Current) + } + return percent, value, value < fg } type tuneOwn struct { @@ -140,6 +178,10 @@ func adviseOf(by map[string][]tune.Call, days int, home string) tuneState { if own != "" && s.Source == agent.TuneLong && r.Current == told { ad.Own = &tuneOwn{Model: own, Value: told} } + if pct, v, ok := codexAsyncAt(r); ok { + as, _ := agent.TuneRead(home, name, agent.TuneAsync, "") + ad.Async = &tuneAsync{Percent: pct, Value: v, Window: r.Window, Setting: as, Held: agent.CodexAsyncHeldHere(home)} + } ta.Advice = append(ta.Advice, ad) } } diff --git a/internal/gui/tune_async_test.go b/internal/gui/tune_async_test.go new file mode 100644 index 000000000..2852e42ee --- /dev/null +++ b/internal/gui/tune_async_test.go @@ -0,0 +1,36 @@ +package gui + +import ( + "testing" + + "github.com/yetone/magpie/internal/tune" +) + +// TestCodexAsyncAt: the advice as a share of the window Codex's background +// compaction starts at, rounded down; none where it would start no sooner +// than the foreground limit (the lesser of the limit now and 90% of the +// window) or the window isn't known. Timed compactions take the cheapest +// window, since one in the background keeps no one waiting. +func TestCodexAsyncAt(t *testing.T) { + for _, c := range []struct { + name string + r *tune.Compaction + pct, value int + ok bool + }{ + {"herman_hong's", &tune.Compaction{Current: 384000, Window: 400000, Best: 120000}, 30, 120000, true}, + {"rounded down", &tune.Compaction{Current: 384000, Window: 400000, Best: 123000}, 30, 120000, true}, + {"timed takes the cheapest", &tune.Compaction{Current: 384000, Window: 400000, Best: 200000, Cheapest: 100000, Facts: tune.Facts{Took: 3}}, 25, 100000, true}, + {"untimed keeps the advice", &tune.Compaction{Current: 384000, Window: 400000, Best: 200000, Cheapest: 100000}, 50, 200000, true}, + {"not before the foreground", &tune.Compaction{Current: 120000, Window: 400000, Best: 120000}, 30, 120000, false}, + {"not past 90%", &tune.Compaction{Window: 400000, Best: 380000}, 95, 380000, false}, + {"at least 1%", &tune.Compaction{Current: 900000, Window: 1000000, Best: 5000}, 1, 10000, true}, + {"no window", &tune.Compaction{Current: 384000, Best: 120000}, 0, 0, false}, + {"none", nil, 0, 0, false}, + } { + pct, v, ok := codexAsyncAt(c.r) + if ok != c.ok || (ok && (pct != c.pct || v != c.value)) || (!ok && c.pct == 0 && (pct != 0 || v != 0)) { + t.Errorf("%s: %d%% %d %v, want %d%% %d %v", c.name, pct, v, ok, c.pct, c.value, c.ok) + } + } +}