tune: Codex can take the compaction advice in the background, its own limit kept (herman_hong)
herman_hong on Discord: Tuned for you advises Codex compact at ~120K.
A foreground compaction kept them waiting, so they had set 384K by hand.
Now that Codex compacts in the background, they want the advice there
and the 384K kept as the backstop.
Codex has this since 0.163.0 (checked in codex-rs at rust-v0.166.0, not
in 0.162.1): [features.async_compaction] enabled and
model_async_compact_threshold_percent, an integer share (1 to 100) of
the model's window, 65 by default. It is Stage::UnderDevelopment, runs
only with remote compaction v2 (which magpie already sets on its
provider), and starts none once the foreground limit is reached. magpie
already writes it from Settings' Background compaction (#2490), with
the version gate and the user's own keys kept. This drives that setting
from tune:
- agent: knob TuneAsync ("async_compact") on codex. TuneRead gives the
share, TuneApply turns Background compaction on at it (stashing what
Settings had the first time), and TuneUndo puts that back unless the
user changed it since. The foreground limit (Long conversations, or
the user's model_auto_compact_token_limit) is never touched. Async
keys the user wrote in config.toml come first (codexAsyncOwn): the
row says so and Apply errors. A table magpie wrote itself doesn't
count as the user's.
- gui/tune.go: advice.async holds the advice as a share of the window,
rounded down. With timed compactions it uses the token-cheapest
window, since a background compaction keeps no one waiting. It is
offered only when it would start before the foreground limit (the
lesser of the limit now and 90% of the window). held lists Codexes
too old for a share.
- context.js: the row gets a text button, "Use 120K in the background",
whose tip gives the share and says the foreground limit stays. After
Use a chip says so, with Undo background. A config.toml of the
user's, or a Codex too old, gets a one-line caveat and no button.
The too-old line is shared with Settings' row (codexHeld). No select,
no layout change. zh, zh-TW, ja and de are in i18n.js.
- The core script budget goes up by 1,571 bytes for the row
(core_budget_test.go says why). app.js is 278 bytes smaller.
Run (at this change on origin/main 6893cfbe3; rebased on d0a61b856,
whose new commits touch none of these files, and TestCoreScriptBudget,
TestTune*, TestCodexAsync* run again there: ok):
- gofmt -l: clean.
- mote-run go vet ./internal/agent ./internal/gui, plus GOOS=linux
-tags nogui and GOOS=windows vet of both: ok.
- mote-run go test -count=1 -timeout 45m ./internal/agent
./internal/tune ./internal/provider: ok. ./internal/gui: the new
tests and TestCoreScriptBudget pass. TestSettingsSaveKeepsWhatItDoes
NotSend is red on clean origin/main too (#4514). Eleven AppKit window
tests (TestMainWindowCorners, TestPanelCloseHidesIt, ...) were killed
at their 30-40s on mote at load ~25; this change touches no window
code.
- wsl-run node --test context-tune, codex-async-compact and i18n-keys:
the new test passes in chromium and webkit, in all five languages,
at 360 and 1100. It checks the label, the tip, the POST body
{knob: async_compact, value: "30"}, the chip and Undo, the locked
and held caveats, and no overflow. i18n-keys' "a plugin's words are
its own" is red on main (#4524).
Broken by hand (each went red, then restored):
- codexAsyncOwn always "": TestTuneCodexAsyncOwn red in all 4 cases.
- asyncOurs ignoring the set share: TestTuneCodexAsync red (it would
undo over the user's 50).
- codexAsyncAt keyed on WaitBest, and always ok: TestCodexAsyncAt red
(timed cheapest, foreground, 90%).
- context.js posting without the knob: the GUI test red, knob
"compact" where "async_compact" was wanted.
Not tried: a real Codex 0.163+ turn compacting in the background
through magpie, and a real account's /api/tune. When the models' windows
differ, the share comes from the advice's window, so the tokens are
approximate; the tip shows the share Codex gets.
This commit is contained in:
@@ -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
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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",
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -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, []);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user