diff --git a/internal/agent/tune.go b/internal/agent/tune.go index 389407167..1598397dc 100644 --- a/internal/agent/tune.go +++ b/internal/agent/tune.go @@ -17,10 +17,12 @@ package agent // its own (settings.AgentCompacts) has tune read and set that one. import ( + "cmp" "encoding/json" "fmt" "os" "path/filepath" + "slices" "strconv" "strings" @@ -407,6 +409,53 @@ func TuneApply(home, agent, knob, model, value string) error { return edit.SetJSON(p.path, edit.KV{Path: p.key, Value: v}) } +// TuneKnob is one setting of an agent's, the model a window is for, and +// how the agent has it now. +type TuneKnob struct { + Knob string + Model string + Setting TuneSetting +} + +// TuneKept are the settings in agent's own config that tune put in and +// that still hold its value (Ours), so Undo can put back what was there: +// Claude Code's cache lifetimes and per-model windows. The Usage page's +// card is the one place they are changed, and it keeps them there when +// a range has too few calls to advise on (linkaww on Discord: a 1-hour +// cache put in, with no way back to 5 minutes). One in magpie's Long +// conversations or Codex's background compaction is left out: Settings +// shows and changes those. +func TuneKept(home, agent string) []TuneKnob { + prefix := "tune." + agent + "." + var out []TuneKnob + for k := range stashShared() { + rest, ok := strings.CutPrefix(k, prefix) + if !ok { + continue + } + knob, model, _ := strings.Cut(rest, ".") + if knob != TuneCompact && knob != TuneCache && knob != TuneSubCache { + continue + } + s, err := TuneRead(home, agent, knob, model) + if err != nil || !s.Ours || s.Source == TuneLong { + continue + } + out = append(out, TuneKnob{Knob: knob, Model: model, Setting: s}) + } + // the same order in every read: the cache rows, then the windows by model + slices.SortFunc(out, func(a, b TuneKnob) int { + window := func(k TuneKnob) int { + if k.Knob == TuneCompact { + return 1 + } + return 0 + } + return cmp.Or(window(a)-window(b), cmp.Compare(a.Knob, b.Knob), cmp.Compare(a.Model, b.Model)) + }) + return out +} + // 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 { diff --git a/internal/gui/assets/context.js b/internal/gui/assets/context.js index 0cb4abb11..b5cc807ac 100644 --- a/internal/gui/assets/context.js +++ b/internal/gui/assets/context.js @@ -1237,16 +1237,11 @@ : t("{value}: {tokens} more tokens over the range (+{pct})", { value: show(p.value), tokens: fmtK(extra(p)), pct: pct(extra(p) / low) }); plot.append(dot); }; - // the advice's value first, then the setting now, then the range's two - // ends: a value that sits too close to one before it is left off, so two - // labels are never drawn over each other (#1549, Ti800: 170K, the - // leanest, one step from the axis's 160K, read as "1170K") + // the advice's value, the setting now, the range's ends: one too close + // to one before is left off, so labels never overlap (#1549, Ti800) const along = (p) => pts.indexOf(p) / (pts.length - 1); - // the tags over the dots the same way: "Leanest" first, then the setting - // now, then the costliest; one beside a tag that matters more and at - // about its height keeps its dot and tooltip but not its tag, so a - // setting one step from the advice doesn't print its "+3%" over - // "Leanest" (#1549) + // the tags the same way: Leanest, the setting now, the costliest; one + // near a tag that matters more keeps its dot, not its tag (#1549) const tagged = []; const tag = (p, label) => { if (tagged.some((k) => Math.abs(along(k) - along(p)) < TICK_GAP && Math.abs(Y(k) - Y(p)) < 20)) return ""; @@ -1277,8 +1272,9 @@ } function adviceRow(agent, a) { - const r = a.compact || a.ttl; - const ttl = !!a.ttl; + // few: put in by tune, too few calls to advise on; kept for Undo (linkaww) + const r = a.compact || a.ttl || { current: a.setting.value, best: a.setting.value, cost: 0, low: 0 }; + const ttl = a.knob != "compact"; const show = (v) => ttl ? ttlName(v) : fmtK(+v); const cur = ttl ? r.current : r.current, best = r.best; const same = String(cur) === String(best); @@ -1326,7 +1322,8 @@ const why = el("p", "ctx-tune-why"); const f = r.facts || {}; - if (a.compact) { + if (a.few) why.textContent = t("Not enough calls in this range to tune on"); + else if (a.compact) { why.textContent = f.compacts ? t("Your conversations grow {growth} a call; a compaction leaves {after}, and reading back what it dropped costs {rework}. {n} compactions in the range.", { growth: fmtK(f.growth), after: fmtK(f.after), rework: fmtK(f.rework), n: f.compacts }) : t("Your conversations grow {growth} a call, and none was compacted in the range.", { growth: fmtK(f.growth) }); @@ -1476,8 +1473,8 @@ const name = el("div", "ctx-who-box"); name.append(who, el("div", "ctx-who-sub", count(ag.calls, "1 call", "{n} calls"))); head.append(name, el("span", "grow")); - const total = ag.advice.reduce((s, a) => { const r = a.compact || a.ttl; return s + Math.max(0, r.cost - r.low); }, 0); - const all = ag.advice.reduce((s, a) => s + (a.compact || a.ttl).cost, 0); + const total = ag.advice.reduce((s, a) => { const r = a.compact || a.ttl || {}; return s + Math.max(0, r.cost - r.low || 0); }, 0); + const all = ag.advice.reduce((s, a) => s + ((a.compact || a.ttl)?.cost || 0), 0); // a share that rounds to nothing is no promise if (all > 0 && total / all >= 0.01) head.append(el("span", "ctx-tune-total", t("Up to {pct} fewer", { pct: pct(total / all) }))); card.append(head); diff --git a/internal/gui/tests/context-tune.test.cjs b/internal/gui/tests/context-tune.test.cjs index 552e40e6c..975928212 100644 --- a/internal/gui/tests/context-tune.test.cjs +++ b/internal/gui/tests/context-tune.test.cjs @@ -901,3 +901,62 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", assert.deepEqual(errors, []); }); } + +// a setting tune put in stays on the card with its Undo when the range has +// too few calls to advise on, or none (linkaww on Discord: Claude Code's +// cache put at 1 hour, and Today showed no way back to 5 minutes) +const few = { en: "Not enough calls in this range to tune on", zh: "这段时间的调用太少,还算不出建议", "zh-TW": "這段時間的呼叫太少,還算不出建議", ja: "この期間は呼び出しが少なく、まだ調整できません", de: "Zu wenige Aufrufe in diesem Zeitraum zum Abstimmen" }; +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(`${engine}: a setting put in keeps its Undo with too few calls`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + const errors = []; + t.after(async () => { + if (errors.length) console.log(errors); + await browser.close(); + }); + for (const lang of Object.keys(few)) 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 = []; + const base = serve(lang, posts); + let put = true; + await page.route("**/*", async (r) => { + const p = new URL(r.request().url()).pathname; + if (p === "/api/tune/undo") put = false; + if (p !== "/api/tune") return base(r); + const advice = put ? [ + { knob: "cache_ttl", setting: { value: "1h", source: "settings", ours: true }, few: true }, + { knob: "compact", model: "claude-opus-5-5", setting: { value: "300000", source: "model", ours: true }, few: true }, + ] : []; + return r.fulfill({ json: { days: 1, agents: put ? [{ agent: "claude", calls: 3, advice }] : [] } }); + }); + await page.goto("http://magpie.test/?view=usage"); + const rows = page.locator(".ctx-tune-row"); + await rows.first().waitFor(); + assert.equal(await rows.count(), 2); + for (const i of [0, 1]) { + assert.equal(await rows.nth(i).locator(".ctx-tune-why").innerText(), few[lang]); + assert.equal(await rows.nth(i).locator("button").count(), 1, `row ${i}: Undo only`); + assert.equal(await rows.nth(i).locator(".ctx-tune-chart svg").count(), 0, `row ${i}: no curve`); + assert.doesNotMatch(await rows.nth(i).innerText(), /NaN|undefined/); + } + assert.match(await rows.nth(0).innerText(), { en: /1 hour/i, zh: /1 小时/, "zh-TW": /1 小時/, ja: /1 時間/, de: /1 Stunde/ }[lang]); + const over = await page.evaluate(() => { + const view = document.querySelector("#view-usage"); + return view.scrollWidth > view.clientWidth + 1 ? view.scrollWidth + ">" + view.clientWidth : ""; + }); + assert.equal(over, ""); + await rows.nth(0).locator("button").evaluate((b) => b.click()); + await page.waitForFunction(() => document.querySelectorAll(".ctx-tune-row").length == 0); + assert.deepEqual(posts.map((p) => [p.path, p.knob]), [["/api/tune/undo", "cache_ttl"]]); + await ctx.close(); + }); + } + assert.deepEqual(errors, []); + }); +} diff --git a/internal/gui/tune.go b/internal/gui/tune.go index 992bdd17e..46a49175d 100644 --- a/internal/gui/tune.go +++ b/internal/gui/tune.go @@ -41,6 +41,9 @@ type tuneAdvice struct { // 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"` + // Few: a setting tune put in, kept on the card with nothing to advise + // (too few calls in the range), so its Undo is still there + Few bool `json:"few,omitempty"` } // tuneAsync is the advice as Codex's background compaction takes it: a @@ -110,7 +113,8 @@ func adviseOf(by map[string][]tune.Call, days int, home string) tuneState { out := tuneState{Days: days, Agents: []tuneAgent{}} for _, name := range []string{"claude", "codex"} { calls := by[name] - if len(calls) == 0 { + kept := agent.TuneKept(home, name) + if len(calls) == 0 && len(kept) == 0 { continue } ta := tuneAgent{Agent: name, Calls: len(calls), Advice: []tuneAdvice{}} @@ -192,6 +196,13 @@ func adviseOf(by map[string][]tune.Call, days int, home string) tuneState { ta.Advice = append(ta.Advice, ad) } } + // what tune put in stays on the card, Undo with it, when the range + // has too few calls to advise on it (linkaww on Discord) + for _, k := range kept { + if !slices.ContainsFunc(ta.Advice, func(a tuneAdvice) bool { return a.Knob == k.Knob && a.Model == k.Model }) { + ta.Advice = append(ta.Advice, tuneAdvice{Knob: k.Knob, Model: k.Model, Setting: k.Setting, Few: true}) + } + } out.Agents = append(out.Agents, ta) } return out diff --git a/internal/gui/tune_kept_test.go b/internal/gui/tune_kept_test.go new file mode 100644 index 000000000..64928dac4 --- /dev/null +++ b/internal/gui/tune_kept_test.go @@ -0,0 +1,98 @@ +package gui + +import ( + "path/filepath" + "testing" + + "github.com/yetone/magpie/internal/agent" + "github.com/yetone/magpie/internal/edit" + "github.com/yetone/magpie/internal/sessions" +) + +// linkaww on Discord (11-06): Usage › Context put Claude Code's cache at +// 1 hour, and the way back to 5 minutes was gone. The card is the one +// place that setting is changed, and its row, Undo with it, came only +// with 50 calls of the range to advise on: Today, or a quiet week, had +// none. A setting tune put in stays on the card, marked few, with too few +// calls or none at all; one the user wrote themselves, and one put back, +// leave it. +func TestTuneKeepsWhatItPutIn(t *testing.T) { + sandboxHome(t) + home := t.TempDir() + kept := func(cs []sessions.Call) []tuneAdvice { + t.Helper() + var out []tuneAdvice + for _, a := range tuneOf(cs, 1, home).Agents { + if a.Agent != "claude" { + continue + } + for _, ad := range a.Advice { + if ad.Few { + out = append(out, ad) + } + } + } + return out + } + few := tuneCalls("claude", "claude-opus-4-5", 5) + if got := kept(few); len(got) != 0 { + t.Fatalf("nothing put in, yet kept rows: %+v", got) + } + if err := agent.TuneApply(home, "claude", agent.TuneCache, "", "1h"); err != nil { + t.Fatal(err) + } + if err := agent.TuneApply(home, "claude", agent.TuneCompact, "claude-opus-4-5", "300000"); err != nil { + t.Fatal(err) + } + for name, cs := range map[string][]sessions.Call{"few calls": few, "no calls": nil} { + got := kept(cs) + if len(got) != 2 { + t.Fatalf("%s: kept %+v; want the cache and the window", name, got) + } + if c := got[0]; c.Knob != agent.TuneCache || c.Setting.Value != "1h" || !c.Setting.Ours || c.TTL != nil { + t.Errorf("%s: cache row %+v; want cache_ttl at 1h, magpie's", name, c) + } + if w := got[1]; w.Knob != agent.TuneCompact || w.Model != "claude-opus-4-5" || w.Setting.Value != "300000" || !w.Setting.Ours { + t.Errorf("%s: window row %+v; want claude-opus-4-5's 300000, magpie's", name, w) + } + } + // with enough calls the cache has its advice, and no second row + for _, a := range tuneOf(tuneCalls("claude", "claude-opus-4-5", 80), 1, home).Agents { + n := 0 + for _, ad := range a.Advice { + if ad.Knob == agent.TuneCache { + n++ + if ad.Few || ad.TTL == nil { + t.Errorf("80 calls: the cache row %+v; want its advice", ad) + } + } + } + if n != 1 { + t.Errorf("80 calls: %d cache rows; want 1", n) + } + } + + if err := agent.TuneUndo(home, "claude", agent.TuneCache, ""); err != nil { + t.Fatal(err) + } + if err := agent.TuneUndo(home, "claude", agent.TuneCompact, "claude-opus-4-5"); err != nil { + t.Fatal(err) + } + if got := kept(nil); len(got) != 0 { + t.Fatalf("put back, yet kept: %+v", got) + } + if st := tuneOf(nil, 1, home); len(st.Agents) != 0 { + t.Errorf("no calls and nothing put in, yet agents: %+v", st.Agents) + } + + // the user's own 1h is theirs to change in their file: no kept row + if err := edit.SetJSON(filepath.Join(home, ".claude", "settings.json"), edit.KV{Path: "promptCacheTtl", Value: "1h"}); err != nil { + t.Fatal(err) + } + if s, _ := agent.TuneRead(home, "claude", agent.TuneCache, ""); s.Value != "1h" { + t.Fatalf("the user's own 1h reads %+v", s) + } + if got := kept(few); len(got) != 0 { + t.Errorf("the user's own 1h: kept %+v; want none", got) + } +}