Commit Graph
6 Commits
Author SHA1 Message Date
yetoneandmdwsk88 ff2a06c349 gui, tune: Tuned for you weighs a model magpie routes at its provider's price, not by its name (#3435)
Tune weighed a call's tokens by its model's name alone (tune.WeightsFor):
an id starting "claude" at Anthropic's ratios (read 0.1, write 1.25, an
hour's write 2), any other at generic ones (an hour's write at a
5-minute one's price). Claude Code is given magpie's models as
provider/model ids (copilot/claude-opus-5-5, anthropic/claude-opus-5-5),
which the name rule took for no Claude model. So a Claude model on an
Anthropic-billed provider was weighed with its hour costing no more than
5 minutes, and none was weighed at the price the usage pages count.

The replay now takes its weights from a tune.Weigh (CompactOpts.Weigh,
and CacheTTL's third argument), per stream; nil weighs as before. Tuned
for you passes pricedWeights: an id with a provider resolves as the
gateway resolves it (provider.Resolve after ClaudeRead) and is weighed
at that provider's EffectivePriceIn, so a Claude model on Copilot has
its hour at the 5-minute write Copilot bills (the previous commit) and
one on Anthropic at 2x. A model Claude Code named itself keeps its
maker's weights, as does a price with no cache read or write. The
compaction advice is weighed the same way. docs/subsystems/agent-wiring.md
says so.

Run on mote (go1.26.8, macOS) at 400b66ec3 plus the previous commit and
this one:
- go test ./internal/tune, and ./internal/gui -run Tune: ok.
- With pricedWeights weighing by the name alone (by hand),
  TestTuneWeighsRoutedCallsAtTheirProvidersPrice is red:
  "relay/claude-opus-5-5 weighs {Read:0.1 Write:1 Write1h:1 Out:8};
  want its price's" and "cache advice ... {Current:1h Best:1h ...};
  want 1h -> 5m".
Not tried: the Context tab in the app; the advice's numbers change, not
its layout or text. Claude Desktop's Code tab is still left out of Tuned
for you, though #3435 names it.

Reported-by: mdwsk88 (dawei on Discord)
Co-authored-by: mdwsk88 <11055210+mdwsk88@users.noreply.github.com>
2026-11-07 04:03:01 +08:00
yetone fbeed7e7f7 usage: the Context tab reads each day and each session file once, not at every refresh (Yayoi_no_yume on X)
A user running magpie on a 1-core, 962 MB server opened Usage › Context.
CPU went to 100%, memory to 91%, and the server went down.

Cause: the tab asks /api/context and /api/tune at every refresh of the
Usage page (every 5s by default). Each ask:
- /api/context read up to 7 days of routing history again, as whole
  gateway.Route values (prompt items, order, tries). A gzipped day not yet
  counted was parsed whole, every route of it, before being cut to its
  latest 2000 (gateway.History).
- /api/tune read every Claude Code and Codex session file in the range
  again, whole, into []sessions.Call, then worked the advice out of all of
  them.

Now:
- gateway.History counts a .gz day's lines first and then parses only its
  latest historyMax+historySlack routes, as it already did for .jsonl.
- /api/context keeps each day's routes slimmed (ctxRec: the parts' tokens
  without their items; the whole prompt only on the routes that can be a
  session's latest), keyed by the size and mtime of the day's files. A
  day is read again only when its files change. The answer is given again
  while its days and the trace are unchanged, for at most a minute.
- /api/tune keeps each file's calls as tune.Call (~100 B each), keyed by
  size, mtime and agent, read one file at a time through
  sessions.ReadCallSource. A message copied into a resumed session is
  still counted once (the earlier file owns it, as in sessions.Calls). The
  advice stands for a minute, and apply or undo lets it go at once.
- tune's stable sorts use slices.SortStableFunc instead of
  sort.SliceStable, which was most of the CPU over 300k calls.

Measured on mote with a generated fixture: 8 days of 20,000 routes each
(7 gzipped, built from a real 2.2 KB route), and 200 Claude Code files of
1,500 calls each (300k calls). The scratch bench was not committed. mote
was at load 130-170 from other suites, so wall times are noisy; CPU time
is from rusage and peak heap is sampled every 2 ms.
  /api/context  before: 1st ask 4.2s CPU, 158 MB peak heap, 202 MB RSS;
                        every refresh 0.63s CPU, 111-121 MB peak heap
                after:  1st ask 0.84s CPU, 48-55 MB, 90-93 MB RSS;
                        every refresh 3-5 ms CPU, 21-34 MB
  /api/tune     before: 1st ask 4.3s CPU, 498 MB peak heap, 717 MB RSS;
                        every refresh 1.0s CPU, 370-494 MB peak heap
                after:  1st ask 0.83s CPU, 373 MB, 409 MB RSS;
                        within a minute 0 CPU, nothing read;
                        after a minute with a file changed, that file is
                        read and the advice worked out again (~0.5s CPU)

Tests:
- TestContextReadsADayOnce: a day whose files are unchanged is not read
  again; a grown day is, and only that day; each session's latest prompt
  keeps its items; the kept answer equals contextOf over every route.
- TestTuneReadsAFileOnce: an unchanged file is not read again; a grown
  one is; a copied message counts once; the call count matches
  tuneOf(sessions.Calls(...)); within a minute nothing is read.
- TestHistoryParsesOnlyAGzDaysLatest: a 5,200-route gz day parses at
  most 2,200 routes.
Broken by hand: always re-read the day, skip tune's file check, drop
History's count-first block. All three tests went red (days read 4
times, files read 5 times, 5,200 routes parsed), then green again once
restored.

Run on mote at this tree:
- gofmt -l: clean.
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows
  go vet ./..., go build ./...: all ok.
- go test ./internal/gui ./internal/gateway ./internal/tune
  ./internal/sessions: tune and sessions ok. gui is red only on
  TestMainWindowCorners/macOS_26_SDK (#3949, macOS 27 on mote). gateway
  is red only on the Antigravity turned-away tests and
  TestCodexSpentGrokFailingIsTold, which are red on main (#4362). This
  change touches neither.
- GUI (node --test, Chromium and WebKit): context-*.test.cjs,
  compact-one-value, usage-refresh, usage-refresh-flight and
  usage-stale-answer: 270 of 273 pass. The 3 reds are context-map's
  "two tiles overlap" in WebKit at 420px (en, ja, de), the overlap
  #3488 has under load (mote at load ~160). No .js changed, so app.js's budget is
  untouched.

Not tried:
- A real 1-core, 1 GB box.
- Codex rollouts in the fixture: Codex files take the same path.
- internal/usage's codexCalls, which still uses sessions.AgentCalls
  (Codex only, on the Usage identity path) and is unchanged.
- tune's first ask, and each ask after a minute with a file changed,
  still works over the range's calls at once: ~30 MB kept per 300k calls,
  and a few hundred MB peak while the advice is worked out. It is bounded
  by the calls in the range, not by a fixed size.
2026-10-30 13:23:19 +08:00
yetone 035c259a6d tune: Codex's compaction windows run to the model's own window or 1M, not the largest prompt seen (zhemu on Discord)
zhemu: Codex Desktop on a CLIProxyAPI provider's 1M GPT model, Settings ›
Long conversations at 750K; Usage › Context › "Other window…" stopped at
~412K. tuneOf took Codex's window as max(272K, the largest prompt seen),
so tune.Compact capped both the offered windows and the user's own value
at the largest prompt (~412K), whatever the model's window or the
user's setting.

Now codexWindow reads the window from magpie's catalog: a model with a
known window (typed or catalog) is offered up to it, and "now" is the
window magpie tells Codex (Settings' long-conversation value or the
model's own compaction, as codexcat writes it), 750K for zhemu. A model
whose window magpie doesn't know caps nothing short of 1M, and a mix
with one unknown is unknown. Codex's own models keep 272K or the
largest prompt. Claude Code is unchanged: only Claude models get the
advice, and other vendors' models use magpie's own window.

Run:
- TestTuneWindowsAreTheUsers (internal/gui), a custom provider with an
  unknown window, 1M and 400K, on Codex and Claude Code. Old code:
  "Codex on cpa/gpt-cpa-open: windows offered up to 410000; want
  1000000" (and for 1m). Broken by hand: told dropped → "now 0, want
  750000"; window=0 for unknown dropped → the mixed case fails.
- TestCompactUnknownWindowCapsNothing (internal/tune): old code "no advice".
- gofmt -l clean; go vet ./... and -tags nogui for GOOS=darwin, linux,
  windows clean.
- context-tune.test.cjs (Chromium + WebKit): 70/70 pass.
- go test ./internal/tune ./internal/gui ./internal/settings ./internal/davsync
  green at this head, rebased on origin/main 95e7c6bcc.

Full suite: SUITE_LINE
2026-10-15 23:08:00 +08:00
yetone e1dcd1e1d7 tune: a compaction window advised never makes you wait longer on compactions, and says the wait (HirotaNagai on X)
Tuned for you advised the compaction window by tokens alone, so a smaller
window that compacts far more often could be advised however long each
compaction keeps the user waiting.

What changed
- sessions: a call now carries how long a compaction took (Call.Compact).
  Claude Code's compact_boundary line gives compactMetadata.durationMs,
  which goes on the first call after it that isn't an error. Codex compacts
  by a call of its own (the token_usage_record a compacted line names), and
  that call's own time is the compaction's. Older rollouts with no such
  record stay untimed. callCacheVersion is now calls-v13.
- tune: with 3 or more compactions timed for a model (minTimed), Facts.took
  is their median in seconds, and each window's Point.wait is its
  compactions x took. When compactions are timed, the advice never takes a
  window that compacts more often than the current one. Of the windows that
  don't, it takes the cheapest, and of those within 3% of that (sameCost)
  the one that compacts least. Tokens and seconds share no unit the files
  measure, so magpie doesn't trade one for the other at a guessed rate. The
  token-cheapest window is reported (cheapest, wait_cheapest) so the user
  can pick it. A model with fewer than 3 timed compactions is advised as
  before, with no wait shown.
- GUI (Usage > Context): when timed, the advice is labelled
  "Tokens + wait". The explanation says what a compaction took, the wait at
  the advice against the window now, and the cheaper window that would wait
  longer (if it saves 3% or more). The caveat says tokens and waiting only.
  The picker shows each window's wait, with "Fewest tokens" on the
  cheapest. Untimed rows are unchanged. The new strings are in zh, zh-TW,
  ja and de.
- docs/subsystems/agent-wiring.md describes the timing sources and the
  rule.

What was run
- go test -tags nogui ./internal/sessions ./internal/tune ./internal/gui
  ./internal/agent pass.
  - internal/agent ran before the rebase. It took 1416s under a load
    average of 120-300 and passed with -timeout 40m (the default 10m timed
    out mid-suite). Its Tune/Compact/CacheTTL tests pass on their own.
  - sessions, tune and gui ran again after rebasing on origin/main
    331c27703. fcd6f3519, the head this was pushed onto, touches none of
    these files.
  - internal/gui's TestProviderListReadsSettingsOnce failed 1 of 3 runs
    under load (7.0s against its 2s bar). It passed 6 of 6 on this branch
    and 9 of 9 on origin/main 4048ead7f, and it doesn't touch this code.
    Filed as #2185.
  - TestCallsClaudeCompactTook and TestCallsCodexCompactTook check the
    timings, also after Reset.
  - TestCompactTimedWaitsLeast checks the advice from 1M, 600K and 150K.
    With the timed rule disabled it fails ("advised 260000 makes 36
    compactions, more than 4 now").
  - TestCompactUntimedUnchanged checks that 2 timed compactions give the
    same advice as none, with no wait.
- GUI: context-tune, i18n-keys and context-window pass, 97/97 in Chromium
  and WebKit, in en/zh/zh-TW/ja/de at 360 and 1100 px. The new timed test
  fails against the old assets ("Fewest tokens" where "Tokens + wait" is
  expected).
- gofmt -l is clean. go vet ./..., GOOS=linux go vet -tags nogui ./... and
  GOOS=windows go vet ./... are clean.
- Real data, from copies of the owner's 4 Codex rollouts and 8 Claude
  transcripts in a sandbox HOME:
  - Compactions took 28-46s (opus-5-5), 85-139s (fable-5-1) and 52-121s
    (Codex gpt-5.6-sol).
  - gpt-5.6-sol keeps 230K. Before this change it was advised 70K: 44%
    fewer tokens, but about 3.5h of waiting against 30m.
  - opus-5 moves 200K to 190K, with 6% fewer tokens and the same wait.
  - Untimed models are unchanged.

Not tried: the live app with real accounts. The replay assumes a
compaction takes the same time at every window, since the files only time
compactions near the window the user ran with.
2026-10-14 20:03:53 +08:00
yetone 0102915fe0 gui: Tuned for you lets a compaction window be picked, each with its estimated extra tokens and compactions (#1860)
MrMengJ applied the advised 200K auto-compaction window and wanted 250K or
300K instead, seeing what each costs against the cheapest. A compaction
row now has "Other window…", which opens the app menu (never a native
select) with every value of the curve the card already replays. Each says
its estimated extra tokens over the fewest (or "Fewest tokens" / "As few
tokens") and about how many compactions it would have made over the range.
The head says it is estimated from the reader's calls. The one picked is put
in through /api/tune/apply like Use, with Undo.

tune.Point gains compacts, counted by the same replayCompact that prices
the point, so tokens and compactions come from one model.

Run: go test ./internal/tune ./internal/gui; TestCompactCurveCountsCompactions
(compactions fall as the window grows; the last point is close to
Facts.Compacts). gofmt -l; go vet internal/tune on darwin, linux -tags
nogui, windows. GUI: context-*, gui-zh-tw/ja/de, compact-at, click-scroll,
i18n-keys in chromium and webkit, 144 pass. The new context-tune test covers
5 languages at 360 and 1100px: menu inside the window, 300K ticked, notes
for 250K and 160K, picking 250K posts apply with no page scroll, Escape
posts nothing. On HEAD~ assets context-tune fails 22 of 23.
Not run: against a real Claude Code settings.json (the apply path is
unchanged from Use).
2026-10-13 04:31:07 +08:00
yetone 9e665491ec context: Tuned for you — each agent's settings worked out from the user's own calls, for the fewest tokens, put in on a click and undone on another
The Context tab now replays the period's calls of each agent against the
settings that decide what they cost, and shows, per agent and per model,
the value that would have used the fewest tokens for how this user works:
Claude Code's auto-compact window per model (modelSettings.<model>.
autoCompactWindow), its main and subagent prompt cache lifetimes
(promptCacheTtl, subagentPromptCacheTtl: 5m or 1h), and Codex's
model_auto_compact_token_limit. Each row says where the value comes from
now (the agent's default, the user's own setting, one magpie set, or a
variable that comes first and locks it), why (how fast conversations grow,
what a compaction leaves, how long the user pauses), the cost curve, and
the saving. Nothing is written until "Use …" is clicked; what was there is
stashed and Undo puts it back, unless the user changed it since. A window
the user set past the model's own is shown capped, as Claude Code caps it
(min(setting, model window)), so no saving is claimed that wouldn't happen.
Advice under a 3% saving is "already the leanest".

On the owner's 7 days (88K Claude Code calls, 956 Codex): opus keeps 200K
(their 500K is capped to it), fable 5.1 200K → 160K saves 5% (2.56M
tokens), both cache lifetimes and Codex's 272K are already the leanest.

Run: go vet ./... and go test ./... pass (internal/tune, internal/agent
TestTune*: user-set values kept, env locks, undo after a user edit, TOML
key order). context-tune.test.cjs passes in Chromium and WebKit, en/zh/
zh-TW/ja/de, at 360 and 1100px (22); context-window, context-scroll-end
pass. Full GUI suite: library-servers-bulk and market-have failed once
under load and pass alone; market-have fails on origin/main 494dedcf too
(1 of 8 runs). Claude Code 2.1.296 in a sandbox config dir shows
"Auto-compact window for Fable 5.1: 160k tokens (from settings)" for the
written modelSettings key. The real-data advice was read from the owner's
own ~/.claude and ~/.codex, nothing written.
2026-10-10 15:05:53 +08:00