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.
This commit is contained in:
yetone
2026-10-14 20:03:53 +08:00
parent b7a2e73761
commit e1dcd1e1d7
9 changed files with 466 additions and 22 deletions
+3 -2
View File
@@ -22,7 +22,7 @@ something else shows up as drift.
| Keeping configs current | `Reseat` moves agents off a model magpie no longer serves (#200). `OnGateway` and `Rewire` write the new gateway address into every connected agent when the port changes. `Source` and `Stale` say what an unconnected agent runs on, and whether running copies still use the old list. | [`reseat.go`](../../internal/agent/reseat.go), [`rewire.go`](../../internal/agent/rewire.go), [`connectinfo.go`](../../internal/agent/connectinfo.go) |
| Named omp profiles | omp keeps a profile's settings under `~/.omp/profiles/<name>` (or under `PI_CONFIG_DIR`), each with its own `config.yml` and `models.yml`. Every such profile is an agent of its own — `omp#<name>` on Windows, `omp#<name>@wsl:<distro>` in a distro — so each can be connected, drifted and disconnected on its own. They share omp's model lists (`ListsFor`), and the default `omp` row is the folder `ompDir`/`ompIn` already pick, so an `OMP_PROFILE` that row is already pointed at is not listed twice. A name omp refuses is not a row: `default`, a trailing dot, or a Windows reserved device name (`aux`, `nul`, `com1`, `lpt9.x`, `con.work`), on every platform (`ompProfileOK`). A distro's profile names come from its probe and are kept in `wsl.json`; a stopped distro is never started to list them, its profile rows showing what was last seen (`asleep`). | [`omp.go`](../../internal/agent/omp.go), [`wsl.go`](../../internal/agent/wsl.go) |
| WSL twins | On Windows each running distro is probed once, without starting a stopped one. The `wslKinds` agents found there become agents of their own, `<id>@wsl:<distro>`, edited through `\\wsl.localhost\<distro>`. A kind is found by its folder under the distro's home or by its command there (not one on a Windows drive). Where another tool shares one of them, the kind leaves it out: Gemini CLI is found by its command alone, because Antigravity keeps `~/.gemini` too. Goose is found by its folder alone, because a `goose` command can be pressly's migration tool. Reasonix also needs the version its command gives (`accept`), because the old npm client is named `reasonix` too. The gateway address and key follow the distro's networking: mirrored or NAT (`place`, `keyAt`). `ListsFor` keeps a twin's model picks under the Windows twin's id (#927). | [`wsl.go`](../../internal/agent/wsl.go), [`gatewaykey.go`](../../internal/agent/gatewaykey.go) |
| Settings tuned from use | Usage › Context's "Tuned for you" advises, per agent, the settings that would have spent the fewest tokens on the user's own calls of the range, and puts one in on a click. Package `tune` replays the calls `sessions.Calls` reads from the agents' session files under each candidate value (`Compact`, `CacheTTL`); `tuneOf` picks the agents and models (Claude Code per model, Codex pooled). `TuneRead`, `TuneApply` and `TuneUndo` know where each setting lives: Claude Code's `modelSettings.<model>.autoCompactWindow` (where its `/autocompact` saves), `promptCacheTtl` and `subagentPromptCacheTtl` in `~/.claude/settings.json`; Codex's top-level `model_auto_compact_token_limit`. The advice is weighed by tokens alone: it is labelled "Fewest tokens", and a compaction window it would change says it doesn't measure how well the agent keeps the task after a compaction, and that a lower window compacts more often (#1854, `context-tune.test.cjs`). A compaction row's "Other window…" opens the app menu with every value of the curve, each with its estimated extra tokens over the fewest and about how many compactions it would have made (`Point.compacts`, from the same replay), and puts the one picked in like Use (#1860). | [`internal/tune`](../../internal/tune/tune.go), [`tune.go`](../../internal/agent/tune.go), [`internal/gui/tune.go`](../../internal/gui/tune.go) |
| Settings tuned from use | Usage › Context's "Tuned for you" advises, per agent, the settings that would have spent the fewest tokens on the user's own calls of the range, and puts one in on a click. Package `tune` replays the calls `sessions.Calls` reads from the agents' session files under each candidate value (`Compact`, `CacheTTL`); `tuneOf` picks the agents and models (Claude Code per model, Codex pooled). `TuneRead`, `TuneApply` and `TuneUndo` know where each setting lives: Claude Code's `modelSettings.<model>.autoCompactWindow` (where its `/autocompact` saves), `promptCacheTtl` and `subagentPromptCacheTtl` in `~/.claude/settings.json`; Codex's top-level `model_auto_compact_token_limit`. The advice is weighed by tokens alone: it is labelled "Fewest tokens", and a compaction window it would change says it doesn't measure how well the agent keeps the task after a compaction, and that a lower window compacts more often (#1854, `context-tune.test.cjs`). A compaction row's "Other window…" opens the app menu with every value of the curve, each with its estimated extra tokens over the fewest and about how many compactions it would have made (`Point.compacts`, from the same replay), and puts the one picked in like Use (#1860). An agent whose files time its compactions also has their wait weighed (HirotaNagai on X): Claude Code's `compact_boundary` line says `compactMetadata.durationMs`, which `sessions` puts on the first call after it, and Codex compacts by a call of its own (the record a `compacted` line names, in rollouts since 2026-09), whose time is the compaction's (`Call.Compact`; an older rollout's compaction has no call and stays untimed). With 3 or more timed for a model (`minTimed`), `Facts.took` is their median seconds, each window says its wait (`Point.wait`, its compactions × `took`), and the row says what a compaction took, the wait at the advice against the window now, and the cheaper window the advice passed over for waiting longer (`Compaction.cheapest`, `wait_cheapest`) when it saves 3% or more; the advice is labelled "Tokens + wait", its caveat says tokens and waiting only, and the picker says each window's wait with "Fewest tokens" on the cheapest (`context-tune.test.cjs`). An agent or model with fewer timed reads and is advised as before. | [`internal/tune`](../../internal/tune/tune.go), [`tune.go`](../../internal/agent/tune.go), [`internal/gui/tune.go`](../../internal/gui/tune.go) |
| Agents a plugin adds | A plugin's `magpie.agent` module (or a `*.agent.js` file) says where an agent magpie has no setup of its own keeps its model (`config`, `format`, `model`, `prefix`), and its `connect` returns the other keys to write. `agentplug` compiles each in moejs (via `jsmod`, as gateway middleware is), reloads it when plugins.json or the file changes, and keeps why one didn't load. `plugged` makes each an `Agent` with `Plugin` set, listed after magpie's own; an id one of magpie's own agents has is refused (`PluginErrors`). | [`agentplug.go`](../../internal/agentplug/agentplug.go), [`plugged.go`](../../internal/agent/plugged.go) |
| Environment-only agents | Agents that read the gateway only from the environment get a `Launch` command. Cursor Private Inference instead gets user-level variables (`cursorLocalOn`, `KeepCursorLocalEnv`), and magpie writes none of Cursor's own files. It is found by its product.json in the apps folders, in the folder Windows' list of installed programs names (`cursorLocalInstalls`, any folder picked in its installer), or as its Linux AppImage (`Cursor_Private_Inference-…AppImage`) in the folders downloads are kept in (#1254). Its effort field is kept in magpie (`provider.AgentEffort`) and asked by the gateway, its levels those of the models it lists (`cursorLocalEfforts`, #1003). | [`cursorlocal.go`](../../internal/agent/cursorlocal.go) |
@@ -87,7 +87,7 @@ something else shows up as drift.
- Codex signed in to ChatGPT and not connected still gets `openai_base_url` while more of its ChatGPT accounts are on in magpie (`failover`, stash `codex.failover`; with a CC Switch mirror as its provider, the mirror's `base_url` and `codex.mirror_failover`), so a turn its own account has no allowance for goes on to the next. That Codex is `FailingOver`: not `Wired`, yet its requests go through magpie. The Agents row says so and what turns it off (`FailoverSaid` in the CLI and TUI, `failover` in `/api/state`, a button to Providers › Codex in the GUI), and the gateway hands it only its own models from `/backend-api/codex/models` (`CodexOwnOnly`, set on `gateway.CodexOwnOnly` by main; its ETag carries `provider.CodexOwnListTag`, and Sync ages a `models_cache.json` without it). A connected WSL Codex shares the gateway path, so while one is connected every Codex gets magpie's models (#1385). A base URL the user wrote by hand (#856) isn't failover's and stays a plain not-connected row. A Codex the user disconnected gets no failover till they connect it again. The app serving the gateway takes failover out as it quits (`EndFailover`, `EndCodexFailover` in `OnShutdown`), so a Codex left on its own goes straight to OpenAI rather than retrying a gateway that's gone (Leon920717 on X); the next start's Sync writes it again. Codex's app-server read the old base URL as it started and keeps it, and `KeepCodexDaemonCurrent` ends with magpie, so `EndCodexFailover` restarts it there when no codex session is on it (`codexDaemonCheck`); with one on it, it stays on the gone gateway until the user restarts it (thisisvainxx on X: "several restarts"). A connected Codex keeps magpie as it quits: its model is one of magpie's, and Disconnect is what puts its own config back. A magpie that ends without quitting (killed, a crash, `magpie serve`) leaves failover in place.
- A Codex thread keeps the provider it was started on. While a magpie model is on, CC Switch's provider tables go through magpie too (`takeTables`), and get their own base URL back when Codex steps off magpie (`giveTables`, stash `codex.tables`). CC Switch's OpenAI mirror (a table of another id, `name = "OpenAI"`, `requires_openai_auth`, no `base_url`) isn't reached by `openai_base_url`, which takes only the built-in provider to magpie: a thread started on it and reopened went straight to ChatGPT, which refused the magpie model picked in it, and magpie never saw the request (#1796). While Codex goes to magpie by the base URL, `takeMirrors` gives each such mirror magpie's ChatGPT backend as its `base_url` (stash `codex.mirrors`), and `giveMirrors` takes it off again; a mirror a profile names, or one whose `base_url` was changed since, stays as it is. Moving the threads onto another provider is the Sessions page's Move (#887).
- An agent's config is written in the form the installed version reads, taken from what that version declares, not the latest one. VSCodium has no Copilot Chat of its own, and the Marketplace's last one (0.48.1) has no Custom Endpoint provider, only OpenAI Compatible (`customoai`, #1014). magpie reads the provider list in the package.json of the `github.copilot-chat` installed under `~/.vscode-oss/extensions` (`vscodeChatOf`). It writes its group for `customendpoint` when that is declared, for `customoai` when only that is, with each model's window as `maxInputTokens` + `maxOutputTokens` and the token as `x-api-key` (that version drops an Authorization in `requestHeaders`). A missing or unreadable extension keeps `customendpoint`. Sync rewrites a group written for the other provider, and Check reports it, as it does a Copilot Chat declaring neither. That Copilot Chat registers its providers only while signed in to GitHub with a personal Copilot plan, which the Notice says.
- Tuned settings are written only on the user's click, never by Sync or Connect. The value there before is stashed once (`tune.<agent>.<knob>[.<model>]` in `stash.json`), so Undo puts it back, or takes the key out (and a `modelSettings` entry left empty). A value the user changed after the click is theirs: Undo then only forgets the stash. A variable that comes before the setting (`CLAUDE_CODE_AUTO_COMPACT_WINDOW`, `FORCE_PROMPT_CACHING_5M`, `CLAUDE_CODE_PROMPT_CACHE_TTL`, `CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL`, in settings.json's `env` or magpie's own) is shown as `locked` and Apply refuses, since the setting would change nothing. Claude Code compacts at the smaller of the window set and the model's own (its `/autocompact` says "capped to 200k by model"), so advice starts from that, and a model that isn't Claude's has no window here (magpie's own compact wiring serves it). Advice changes a value only when the replay saves 3% or more, and of the windows within 1% of the cheapest takes the largest. Tokens are weighed as billed: cache reads 0.1, 5-minute writes 1.25, hour writes 2, output 5 for Claude; reads 0.1, writes 1, output 8 otherwise.
- Tuned settings are written only on the user's click, never by Sync or Connect. The value there before is stashed once (`tune.<agent>.<knob>[.<model>]` in `stash.json`), so Undo puts it back, or takes the key out (and a `modelSettings` entry left empty). A value the user changed after the click is theirs: Undo then only forgets the stash. A variable that comes before the setting (`CLAUDE_CODE_AUTO_COMPACT_WINDOW`, `FORCE_PROMPT_CACHING_5M`, `CLAUDE_CODE_PROMPT_CACHE_TTL`, `CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL`, in settings.json's `env` or magpie's own) is shown as `locked` and Apply refuses, since the setting would change nothing. Claude Code compacts at the smaller of the window set and the model's own (its `/autocompact` says "capped to 200k by model"), so advice starts from that, and a model that isn't Claude's has no window here (magpie's own compact wiring serves it). Advice changes a value only when the replay saves 3% or more, and of the windows within 1% of the cheapest takes the largest; with the compactions timed, it never advises a window that compacts more often than the one now, so never a longer wait: of the windows that compact no more often it takes the cheapest, and of those within 3% of that (`sameCost`, the same bar as changing at all) the one that compacts least, the larger of two that compact as often. Tokens and seconds share no unit the files measure, so the advice doesn't trade one for the other at a guessed rate; a cheaper window that waits longer is said with its wait in the row and the picker, for the user to choose. The wait per compaction is taken as the same at every window: the files time compactions only near the window the user ran with, too narrow to fit how it grows with the prompt. Tokens are weighed as billed: cache reads 0.1, 5-minute writes 1.25, hour writes 2, output 5 for Claude; reads 0.1, writes 1, output 8 otherwise.
- A plugin's agent writes each key in place (JSON, YAML or env), the user's comments and other keys kept. An object or array `connect` returns is taken as its JSON text (`agentplug.keys`), so it is written in the order the plugin gave it, not sorted as a Go map would be: Kilo lists its effort variants in key order (#1890, `TestPluggedKeepsPluginOrder`). What each key held before the first write is stashed under `plugin:<id>:<path>`, typed, and its own model or Disconnect puts every key back and takes out the ones that weren't there; the file is never written whole. A `connect` that throws or takes over a second writes nothing and says why. Its gateway key is `magpie-<id>` (`agentKeyAt`), and usage names its requests by that key or by its `ua` words (`usage.PluginAgents`). Its `agent.library` (instructions, `mcp` with `mcpFormat`, skills) gives it the Library's three as well, written by `internal/library` as any agent's are ([library](library.md)); a `mcpFormat` outside `agentplug.MCPFormats`, or an `mcp` without one, keeps the plugin from loading.
- StepCode config root resolves to the parent of an absolute `STEP_CODING_AGENT_DIR` (agent resources directory differs from config root; relative values ignored), or `STEPCODE_CONFIG_DIR` under home when native, defaulting to `~/.stepcode` ([`stepcode.go`](../../internal/agent/stepcode.go)). Project configs override global configs in StepCode, but magpie manages global configuration only (`config.toml` and `models.json`). Detection is strictly directory-only via `agentDir`, avoiding collision with Smallstep's bare `step` command on `PATH`. Wiring performs an atomic two-file edit (`models.json` provider block and `config.toml` top-level defaults/scope) backed by `stash.json`. Custom fields within `providers.magpie` are preserved during sync, and the original provider block is restored on disconnect. A renamed provider's `magpie/<old>/` entries in `enabledModels` follow it, a glob or a thinking level included, and the scope remembered for disconnect follows too; the user's other entries stay. Disconnect restores original defaults, preserves user native changes and custom scope edits, and removes newly created files only when empty.
- An agent is detected by its config file, its folder, or its command on magpie's PATH (`Detected`). That PATH is the login shell's plus the folders users' tools go in (`proc.UserPath`: `~/.local/bin`, npm's prefixes, the Node nvm's default alias resolves to (the highest installed when it names none), bun, Homebrew, ...), so a CLI a terminal doesn't find can still be found and listed: an npm install under a Node the terminal no longer uses. `/api/agents/cli` then gives where it is (`path`) and `offPath` when the login shell's PATH (`proc.LoginPath`) lacks its folder, and the Agents row says "Not on your terminal's PATH", its tip naming the file (悠悠哥 on Discord: Codex 0.162.1 listed with no codex on PATH and no `~/.codex`). An unknown login PATH says nothing. A folder another tool writes too doesn't count (`dirShared`): Pi's for omp, `~/.copilot` for the Copilot CLI, which GitHub Copilot's JetBrains and VS Code plugins also write, and Qoder's and Qoder CN's, which Qoder's JetBrains plugin fills. A config file another tool writes first counts only when `pathOwn` says it is the agent's: Qoder's `settings.json` holding `enabledPlugins` alone is the plugin's (`qoderPluginOnly`; #1495, `TestCopilotFolderFromAnIDEPluginIsNotTheCLI`, `TestQoderSettingsFromAnIDEPluginIsNotTheCLI`). The Qoder app (the desktop app, which runs Qoder's CLI as its agent with the same folder) is found by the `.qoder-app-status.json` it writes there (`sign`, `qoderApp`; #2138, `TestQoderAppIsQoder`), as its `settings.json` can be its bundled plugin's `enabledPlugins` alone. Only the GUI and `daemon install` widen the PATH so; `magpie serve`, `web`, `tui` and the CLI keep the one they were started with, so an agent's CLI (`cliBin`, which its version and `omp`'s max effort are read from) is looked for in those folders (`proc.FindTool`) on every system when it isn't on the PATH, not only on Windows (whqtian on Discord: omp under `~/.bun/bin` on Ubuntu read as no version and offered xhigh in place of max; `TestOmpVersionOffPath`).
@@ -111,6 +111,7 @@ go test -tags nogui ./internal/agent -run '^TestPlugged'
go test -tags nogui ./internal/agent -run 'TestCodexFailoverOnlyKeepsOwnModels|TestCodexOwnModelThroughMagpieWhileAccountsOn|TestCodexHandWrittenBaseURLStays|TestCodexProxyFor|TestRealProxyProbe|TestCodexEnvTakesLoginShell|TestCodexFailoverHeldWhileProxyDoesNotPassOn|TestCodexProxiedDrift|TestCodexFailoverEndsWithMagpie|TestCodexMirrorFailoverHeldAndEndsWithMagpie'
go test -tags nogui ./internal/agent -run 'TestDisconnectStaysThroughSync|TestCodexDisconnectStaysWithAccountsOn|TestCodexAPIDisconnectStays'
go test -tags nogui ./internal/tune ./internal/agent -run 'TestCompact|TestCacheTTL|TestTune'
go test -tags nogui ./internal/sessions -run 'CompactTook'
node --test internal/gui/tests/context-tune.test.cjs
node --test internal/gui/tests/agent-connect.test.cjs internal/gui/tests/agent-disconnect-preview.test.cjs internal/gui/tests/claude-signin.test.cjs internal/gui/tests/agent-failover.test.cjs internal/gui/tests/agent-proxied.test.cjs internal/gui/tests/plugin-agent.test.cjs
```
+36 -12
View File
@@ -923,15 +923,17 @@
// how far apart, as a share of the axis, two of its labels must sit: a
// label is about 30px wide, the narrowest card's axis about 280px
const TICK_GAP = 0.16;
function chart(pts, current, best, show) {
function chart(pts, current, best, show, timed) {
if (pts.length < 2) return null;
const near = (v) => pts.reduce((a, p) => Math.abs(p.value - v) < Math.abs(a.value - v) ? p : a, pts[0]);
const now = typeof current === "number" ? near(current) : pts.find((p) => p.value === current);
const top = typeof best === "number" ? near(best) : pts.find((p) => p.value === best);
if (!top) return null;
// measured from the advice, not the cheapest point: tune takes the
// largest window within 1% of it, and those cost nothing more here
const low = top.cost;
// largest window within 1% of it, and those cost nothing more here.
// Timed, the advice may pass a cheaper window that waits longer, so
// each is said against the cheapest
const low = timed ? Math.min(...pts.map((p) => p.cost)) : top.cost;
const extra = (p) => Math.max(0, p.cost - low);
const most = Math.max(...pts.map(extra));
if (!(most > 0)) return null;
@@ -971,7 +973,8 @@
dot.append(tag);
}
dot.dataset.tt = p === top
? t("{value}: the fewest tokens for how you work", { value: show(p.value) })
? timed ? t("{value}: the fewest tokens without waiting longer on compactions", { value: show(p.value) })
: t("{value}: the fewest tokens for how you work", { value: show(p.value) })
: 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);
};
@@ -991,7 +994,7 @@
tagged.push(p);
return label;
};
const bestTag = tag(top, t("Leanest"));
const bestTag = tag(top, timed ? t("Tokens + wait") : t("Leanest"));
const nowTag = now && now !== top ? tag(now, "+" + pct(extra(now) / low)) : "";
const worstTag = worst !== now && worst !== top ? tag(worst, "+" + pct(extra(worst) / low)) : "";
if (worst !== now && worst !== top) at(worst, "worst", worstTag);
@@ -1037,11 +1040,13 @@
return f;
};
vals.append(val("Now", cur, "now"));
// named for what it is measured by, tokens alone, not "best" (#1854)
if (!same) vals.append(el("span", "ctx-tune-arrow", "→"), val("Fewest tokens", best, "best"));
// named for what it is measured by, tokens alone, not "best" (#1854);
// with the agent's compactions timed, tokens and the wait on them
const timed = !!(a.compact && (r.facts || {}).took > 0);
if (!same) vals.append(el("span", "ctx-tune-arrow", "→"), val(timed ? "Tokens + wait" : "Fewest tokens", best, "best"));
row.append(vals);
const c = a.compact
? chart(a.compact.curve || [], r.current, r.best, show)
? chart(a.compact.curve || [], r.current, r.best, show, timed)
: chart([{ value: "5m", cost: r.short }, { value: "1h", cost: r.hour }], r.current, r.best, show);
if (c) row.append(c);
@@ -1051,13 +1056,28 @@
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) });
// how long the agent's own compactions took, from its files: what a
// window that compacts more often would have kept the reader waiting
if (timed) {
const secs = f.took < 120 ? t("{n}s", { n: f.took }) : fmtDur(f.took);
why.textContent += " " + (same
? t("Each compaction kept you waiting about {secs} ({n} timed). Over the range that's about {wait} at {value}.", { secs, n: f.timed, wait: fmtDur(r.wait || 0), value: show(cur) })
: t("Each compaction kept you waiting about {secs} ({n} timed). Over the range that's about {wait} at {best}, against {now} at {value}.", { secs, n: f.timed, wait: fmtDur(r.wait_best || 0), best: show(best), now: fmtDur(r.wait || 0), value: show(cur) }));
// the cheaper window the advice passed over, for waiting longer
const cheap = (a.compact.curve || []).find((p) => p.value === r.cheapest);
const adv = same ? r.cost : r.low;
if (cheap && r.cheapest !== best && adv > 0 && (adv - cheap.cost) / adv >= 0.03 && (r.wait_cheapest || 0) > (same ? r.wait || 0 : r.wait_best || 0))
why.textContent += " " + t("{value} would spend {pct} fewer tokens, but wait about {wait}.", { value: show(r.cheapest), pct: pct((adv - cheap.cost) / adv), wait: fmtDur(r.wait_cheapest) });
}
} else {
why.textContent = t("{quick} of your calls came within 5 minutes of the one before, {pause} after a pause of 5 to 60 minutes.", { quick: pct(f.quick || 0), pause: pct(f.pause || 0) });
}
row.append(why);
// a window advised is weighed by tokens alone: what a compaction loses of
// the task isn't measured, and a smaller one compacts more often (#1854)
if (a.compact && !same) row.append(el("p", "ctx-tune-caveat", t("A token estimate only: it doesn't measure how well the agent keeps the task after a compaction. The lower the window, the more often it compacts.")));
if (a.compact && !same) row.append(el("p", "ctx-tune-caveat", timed
? t("Tokens and waiting only: it doesn't measure how well the agent keeps the task after a compaction. The lower the window, the more often it compacts.")
: t("A token estimate only: it doesn't measure how well the agent keeps the task after a compaction. The lower the window, the more often it compacts.")));
const foot = el("div", "ctx-tune-foot");
const verdict = same || applied
@@ -1113,16 +1133,20 @@
other.setAttribute("aria-expanded", "false");
other.onclick = (e) => {
e.stopPropagation();
const base = (pts.find((p) => p.value === best) || {}).cost ?? r.low;
// timed, the advice may spend over the cheapest to wait no
// longer, so each value is said against the cheapest
const cheapest = pts.reduce((x, p) => p.cost < x.cost ? p : x, pts[0]);
const base = timed ? cheapest.cost : (pts.find((p) => p.value === best) || {}).cost ?? r.low;
const now = set.ours && set.value != null ? +set.value : cur;
const near = pts.reduce((x, p) => Math.abs(p.value - now) < Math.abs(x.value - now) ? p : x, pts[0]);
const opts = pts.map((p) => {
const extra = Math.max(0, p.cost - base);
const spend = p.value === best ? t("Fewest tokens")
const spend = p.value === (timed ? cheapest.value : best) ? t("Fewest tokens")
: base > 0 && extra / base < 0.005 ? t("As few tokens")
: t("+{tokens} tokens (+{pct})", { tokens: fmtK(extra), pct: pct(base > 0 ? extra / base : 0) });
const often = p.compacts == null ? "" : p.compacts ? count(p.compacts, "about 1 compaction", "about {n} compactions") : t("no compaction");
return { v: String(p.value), name: show(p.value), literalName: true, note: [spend, often].filter(Boolean).join(" · ") };
const wait = timed && p.compacts ? t("about {d} waiting", { d: fmtDur(p.wait || 0) }) : "";
return { v: String(p.value), name: show(p.value), literalName: true, note: [spend, often, wait].filter(Boolean).join(" · ") };
});
openProtoMenu(other, opts, String(near.value), (v) => {
if (v !== String(now)) send("apply", v);
+28
View File
@@ -106,6 +106,13 @@ const I18N = {
"about {n} compactions": "约压缩 {n} 次",
"no compaction": "不会压缩",
"A token estimate only: it doesn't measure how well the agent keeps the task after a compaction. The lower the window, the more often it compacts.": "只是 Token 估算:没有衡量压缩后 Agent 还能多好地接着做任务。阈值越低,压缩越频繁。",
"Tokens + wait": "Token + 等待",
"{value}: the fewest tokens without waiting longer on compactions": "{value}:不多等压缩的前提下,Token 最省",
"{value} would spend {pct} fewer tokens, but wait about {wait}.": "{value} 能少花 {pct} Token,但要等约 {wait}。",
"Each compaction kept you waiting about {secs} ({n} timed). Over the range that's about {wait} at {value}.": "每次压缩让你等了约 {secs}(计时 {n} 次)。这段时间里,{value} 下约等 {wait}。",
"Each compaction kept you waiting about {secs} ({n} timed). Over the range that's about {wait} at {best}, against {now} at {value}.": "每次压缩让你等了约 {secs}(计时 {n} 次)。这段时间里,{best} 下约等 {wait},{value} 下约等 {now}。",
"Tokens and waiting only: it doesn't measure how well the agent keeps the task after a compaction. The lower the window, the more often it compacts.": "只算了 Token 和等待:没有衡量压缩后 Agent 还能多好地接着做任务。阈值越低,压缩越频繁。",
"about {d} waiting": "约等 {d}",
"Your conversations grow {growth} a call; a compaction leaves {after}, and reading back what it dropped costs {rework}. {n} compactions in the range.": "你的对话每次调用增长 {growth};压缩后剩 {after},把丢掉的内容再读回来要花 {rework}。这段时间共压缩 {n} 次。",
"Your conversations grow {growth} a call, and none was compacted in the range.": "你的对话每次调用增长 {growth},这段时间没有一次压缩。",
"{quick} of your calls came within 5 minutes of the one before, {pause} after a pause of 5 to 60 minutes.": "你 {quick} 的调用距上一次不到 5 分钟,{pause} 在停顿 5 到 60 分钟之后。",
@@ -4314,6 +4321,13 @@ const I18N = {
"about {n} compactions": "約壓縮 {n} 次",
"no compaction": "不會壓縮",
"A token estimate only: it doesn't measure how well the agent keeps the task after a compaction. The lower the window, the more often it compacts.": "只是 Token 估算:沒有衡量壓縮後 Agent 還能多好地接著做任務。閾值越低,壓縮越頻繁。",
"Tokens + wait": "Token + 等待",
"{value}: the fewest tokens without waiting longer on compactions": "{value}:不多等壓縮的前提下,Token 最省",
"{value} would spend {pct} fewer tokens, but wait about {wait}.": "{value} 能少花 {pct} Token,但要等約 {wait}。",
"Each compaction kept you waiting about {secs} ({n} timed). Over the range that's about {wait} at {value}.": "每次壓縮讓你等了約 {secs}(計時 {n} 次)。這段時間裡,{value} 下約等 {wait}。",
"Each compaction kept you waiting about {secs} ({n} timed). Over the range that's about {wait} at {best}, against {now} at {value}.": "每次壓縮讓你等了約 {secs}(計時 {n} 次)。這段時間裡,{best} 下約等 {wait},{value} 下約等 {now}。",
"Tokens and waiting only: it doesn't measure how well the agent keeps the task after a compaction. The lower the window, the more often it compacts.": "只算了 Token 和等待:沒有衡量壓縮後 Agent 還能多好地接著做任務。閾值越低,壓縮越頻繁。",
"about {d} waiting": "約等 {d}",
"Your conversations grow {growth} a call; a compaction leaves {after}, and reading back what it dropped costs {rework}. {n} compactions in the range.": "你的對話每次呼叫增長 {growth};壓縮後剩 {after},把丟掉的內容再讀回來要花 {rework}。這段時間共壓縮 {n} 次。",
"Your conversations grow {growth} a call, and none was compacted in the range.": "你的對話每次呼叫增長 {growth},這段時間沒有一次壓縮。",
"{quick} of your calls came within 5 minutes of the one before, {pause} after a pause of 5 to 60 minutes.": "你 {quick} 的呼叫距上一次不到 5 分鐘,{pause} 在停頓 5 到 60 分鐘之後。",
@@ -8495,6 +8509,13 @@ const I18N = {
"about {n} compactions": "コンパクト約 {n} 回",
"no compaction": "コンパクトなし",
"A token estimate only: it doesn't measure how well the agent keeps the task after a compaction. The lower the window, the more often it compacts.": "トークンの見積もりだけです。コンパクトのあとエージェントが作業をどれだけ保てるかは測っていません。しきい値が低いほどコンパクトの回数は増えます。",
"Tokens + wait": "トークン + 待ち時間",
"{value}: the fewest tokens without waiting longer on compactions": "{value}: コンパクトの待ち時間を増やさずに、トークンが最も少ない",
"{value} would spend {pct} fewer tokens, but wait about {wait}.": "{value} ならトークンは {pct} 減りますが、約 {wait}待ちます。",
"Each compaction kept you waiting about {secs} ({n} timed). Over the range that's about {wait} at {value}.": "コンパクト 1 回の待ち時間は約 {secs}({n} 回を計測)。この期間では {value} で約 {wait}待ちます。",
"Each compaction kept you waiting about {secs} ({n} timed). Over the range that's about {wait} at {best}, against {now} at {value}.": "コンパクト 1 回の待ち時間は約 {secs}({n} 回を計測)。この期間では {best} で約 {wait}、{value} では約 {now}待ちます。",
"Tokens and waiting only: it doesn't measure how well the agent keeps the task after a compaction. The lower the window, the more often it compacts.": "トークンと待ち時間だけの見積もりです。コンパクトのあとエージェントが作業をどれだけ保てるかは測っていません。しきい値が低いほどコンパクトの回数は増えます。",
"about {d} waiting": "待ち約 {d}",
"Your conversations grow {growth} a call; a compaction leaves {after}, and reading back what it dropped costs {rework}. {n} compactions in the range.": "会話は 1 回の呼び出しごとに {growth} 増えます。コンパクト後は {after} が残り、落とした内容を読み直すのに {rework} かかります。この期間のコンパクトは {n} 回。",
"Your conversations grow {growth} a call, and none was compacted in the range.": "会話は 1 回の呼び出しごとに {growth} 増え、この期間にコンパクトはありませんでした。",
"{quick} of your calls came within 5 minutes of the one before, {pause} after a pause of 5 to 60 minutes.": "呼び出しの {quick} は前回から 5 分以内、{pause} は 5〜60 分の間を置いた後でした。",
@@ -12684,6 +12705,13 @@ const I18N = {
"about {n} compactions": "etwa {n} Kompaktierungen",
"no compaction": "keine Kompaktierung",
"A token estimate only: it doesn't measure how well the agent keeps the task after a compaction. The lower the window, the more often it compacts.": "Nur eine Token-Schätzung: Wie gut der Agent die Aufgabe nach einer Kompaktierung behält, misst sie nicht. Je niedriger die Schwelle, desto öfter wird kompaktiert.",
"Tokens + wait": "Tokens + Wartezeit",
"{value}: the fewest tokens without waiting longer on compactions": "{value}: die wenigsten Tokens, ohne länger auf Kompaktierungen zu warten",
"{value} would spend {pct} fewer tokens, but wait about {wait}.": "{value} würde {pct} weniger Tokens verbrauchen, aber etwa {wait} warten lassen.",
"Each compaction kept you waiting about {secs} ({n} timed). Over the range that's about {wait} at {value}.": "Jede Kompaktierung ließ dich etwa {secs} warten ({n} gemessen). Im Zeitraum sind das bei {value} etwa {wait}.",
"Each compaction kept you waiting about {secs} ({n} timed). Over the range that's about {wait} at {best}, against {now} at {value}.": "Jede Kompaktierung ließ dich etwa {secs} warten ({n} gemessen). Im Zeitraum sind das bei {best} etwa {wait}, gegenüber {now} bei {value}.",
"Tokens and waiting only: it doesn't measure how well the agent keeps the task after a compaction. The lower the window, the more often it compacts.": "Nur Tokens und Wartezeit: Wie gut der Agent die Aufgabe nach einer Kompaktierung behält, misst das nicht. Je niedriger die Schwelle, desto öfter wird kompaktiert.",
"about {d} waiting": "etwa {d} Wartezeit",
"Your conversations grow {growth} a call; a compaction leaves {after}, and reading back what it dropped costs {rework}. {n} compactions in the range.": "Deine Unterhaltungen wachsen um {growth} pro Aufruf; eine Kompaktierung lässt {after} übrig, und das Zurücklesen des Entfernten kostet {rework}. {n} Kompaktierungen im Zeitraum.",
"Your conversations grow {growth} a call, and none was compacted in the range.": "Deine Unterhaltungen wachsen um {growth} pro Aufruf, und im Zeitraum wurde keine kompaktiert.",
"{quick} of your calls came within 5 minutes of the one before, {pause} after a pause of 5 to 60 minutes.": "{quick} deiner Aufrufe kamen innerhalb von 5 Minuten nach dem vorigen, {pause} nach einer Pause von 5 bis 60 Minuten.",
+103
View File
@@ -341,3 +341,106 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
}
});
}
// An agent whose files time its compactions (HirotaNagai on X, a Codex
// user: a window that compacts more often keeps you waiting more): the
// advice is named for tokens and the wait, the why says how long a
// compaction took, the wait at the advice against the window now, and the
// cheaper window it passed over for waiting longer; the caveat no longer
// says tokens only, and each window in the picker says its wait beside its
// tokens, "Fewest tokens" on the cheapest one, not the advice. A row whose
// compactions aren't timed reads as before. In both engines, every
// language, a phone's width and a desk's.
const timedCurve = () => {
const pts = [];
for (let v = 100000; v <= 400000; v += 10000) {
const compacts = Math.round(9e6 / v);
// 100K the cheapest, but it compacts more often than the window now
pts.push({ value: v, cost: v === 100000 ? 0.95e9 : 1e9 + Math.abs(v - 200000) * 500, compacts, wait: compacts * 76 });
}
return pts;
};
const timedTune = {
days: 7,
agents: [{ agent: "codex", calls: 5200, advice: [
{ knob: "compact", setting: { value: "120000", source: "config" },
compact: { model: "gpt-6-astra", current: 120000, window: 272000, best: 240000, cost: 1.3e9, low: 1.02e9, curve: timedCurve(), wait: 5700, wait_best: 2888, cheapest: 100000, wait_cheapest: 6840, facts: { ...facts, took: 76, timed: 14 } } },
] }],
};
const waitBest = { en: "Tokens + wait", zh: "Token + 等待", "zh-TW": "Token + 等待", ja: "トークン + 待ち時間", de: "Tokens + Wartezeit" };
const waitWhy = {
en: "Each compaction kept you waiting about 76s (14 timed). Over the range that's about 48m at 240K, against 1h 35m at 120K. 100K would spend 7% fewer tokens, but wait about 1h 54m.",
zh: "每次压缩让你等了约 76 秒(计时 14 次)。这段时间里,240K 下约等 48 分钟,120K 下约等 1 小时 35 分。 100K 能少花 7% Token,但要等约 1 小时 54 分。",
"zh-TW": "每次壓縮讓你等了約 76 秒(計時 14 次)。這段時間裡,240K 下約等 48 分鐘,120K 下約等 1 小時 35 分。 100K 能少花 7% Token,但要等約 1 小時 54 分。",
ja: "コンパクト 1 回の待ち時間は約 76 秒(14 回を計測)。この期間では 240K で約 48 分、120K では約 1 時間 35 分待ちます。 100K ならトークンは 7% 減りますが、約 1 時間 54 分待ちます。",
de: "Jede Kompaktierung ließ dich etwa 76 s warten (14 gemessen). Im Zeitraum sind das bei 240K etwa 48 Min., gegenüber 1 Std. 35 Min. bei 120K. 100K würde 7% weniger Tokens verbrauchen, aber etwa 1 Std. 54 Min. warten lassen.",
};
const waitTip = {
en: "240K: the fewest tokens without waiting longer on compactions",
zh: "240K:不多等压缩的前提下,Token 最省",
"zh-TW": "240K:不多等壓縮的前提下,Token 最省",
ja: "240K: コンパクトの待ち時間を増やさずに、トークンが最も少ない",
de: "240K: die wenigsten Tokens, ohne länger auf Kompaktierungen zu warten",
};
const waitCaveat = {
en: "Tokens and waiting only: it doesn't measure how well the agent keeps the task after a compaction. The lower the window, the more often it compacts.",
zh: "只算了 Token 和等待:没有衡量压缩后 Agent 还能多好地接着做任务。阈值越低,压缩越频繁。",
"zh-TW": "只算了 Token 和等待:沒有衡量壓縮後 Agent 還能多好地接著做任務。閾值越低,壓縮越頻繁。",
ja: "トークンと待ち時間だけの見積もりです。コンパクトのあとエージェントが作業をどれだけ保てるかは測っていません。しきい値が低いほどコンパクトの回数は増えます。",
de: "Nur Tokens und Wartezeit: Wie gut der Agent die Aufgabe nach einer Kompaktierung behält, misst das nicht. Je niedriger die Schwelle, desto öfter wird kompaktiert.",
};
const waitNote100 = { en: "Fewest tokens · about 90 compactions · about 1h 54m waiting", zh: "最省 Token · 约压缩 90 次 · 约等 1 小时 54 分", "zh-TW": "最省 Token · 約壓縮 90 次 · 約等 1 小時 54 分", ja: "トークン最少 · コンパクト約 90 回 · 待ち約 1 時間 54 分", de: "Wenigste Tokens · etwa 90 Kompaktierungen · etwa 1 Std. 54 Min. Wartezeit" };
const waitNote240 = { en: "+70M tokens (+7%) · about 38 compactions · about 48m waiting", zh: "多花 70M Token(+7%) · 约压缩 38 次 · 约等 48 分钟", "zh-TW": "多花 70M Token(+7%) · 約壓縮 38 次 · 約等 48 分鐘", ja: "70M トークン多い(+7%) · コンパクト約 38 回 · 待ち約 48 分", de: "+70M Tokens (+7%) · etwa 38 Kompaktierungen · etwa 48 Min. Wartezeit" };
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(`${engine}: timed compactions put their wait beside the tokens`, 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.on("pageerror", (e) => errors.push(e.message));
const base = serve(lang, []);
await page.route("**/*", (r) => new URL(r.request().url()).pathname === "/api/tune" ? r.fulfill({ json: timedTune }) : base(r));
await page.goto("http://magpie.test/?view=usage");
const row = page.locator(".ctx-tune-row").nth(0);
await row.locator(".ctx-tune-pick").waitFor();
await page.locator(".ctx-none").waitFor();
assert.equal(await row.locator(".ctx-tune-val.best .ctx-k").textContent(), waitBest[lang]);
assert.equal(await row.locator(".ctx-tc-dot.best .ctx-tc-tag").innerText(), waitBest[lang]);
assert.equal(await row.locator(".ctx-tc-dot.best").getAttribute("data-tt"), waitTip[lang]);
const why = await row.locator(".ctx-tune-why").innerText();
assert.ok(why.endsWith(" " + waitWhy[lang]), `${lang}: ${why}`);
assert.equal(await row.locator(".ctx-tune-caveat").innerText(), waitCaveat[lang]);
const over = await page.evaluate(() => {
const out = [];
const view = document.querySelector("#view-usage");
if (view.scrollWidth > view.clientWidth + 1) out.push("page " + view.scrollWidth + ">" + view.clientWidth);
for (const c of document.querySelectorAll(".ctx-tune")) {
const b = c.getBoundingClientRect();
for (const e of c.querySelectorAll("*")) {
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(over, []);
await row.locator(".ctx-tune-pick").evaluate((b) => b.click());
const menu = page.locator(".proto-menu.ctx-tune-menu");
await menu.waitFor();
const item = (v) => menu.locator(".pm-item", { has: page.locator(".pm-name", { hasText: new RegExp("^" + v + "$") }) });
assert.equal(await item("100K").locator(".pm-note").innerText(), waitNote100[lang]);
assert.equal(await item("240K").locator(".pm-note").innerText(), waitNote240[lang]);
const box = await menu.boundingBox();
assert.ok(box.x >= 0 && box.x + box.width <= width + 1, `the menu is inside the window: ${JSON.stringify(box)}`);
await page.keyboard.press("Escape");
await ctx.close();
});
}
assert.deepEqual(errors, []);
});
}
+4 -1
View File
@@ -33,10 +33,13 @@ import (
// one is.
// v12: a ZCode call's input leaves out the cache, and its output the
// reasoning counted twice, as its session's summary does (#1947).
// v13: a call after a compaction carries how long the compaction took
// (Compact): Claude Code's compact_boundary durationMs, Codex's compaction
// call's own time.
// What each version names is what a cache of the one before it cannot serve:
// the version is part of the directory's name, so a cache written by an older
// one is never read (pruneCalls).
const callCacheVersion = "calls-v12"
const callCacheVersion = "calls-v13"
const maxKeptCalls = 131072
const maxKeptFiles = 64
+34 -2
View File
@@ -44,8 +44,12 @@ type Call struct {
// Millis: how long the call took. Codex's, of a turn that made this call alone, is what
// it says; the rest are told from the file's times, the call's last line less the line
// that asked for it (a prompt, a tool's result), and so a little more or less than it was
Millis int64 `json:"ms,omitempty"`
Cwd string `json:"cwd,omitempty"`
Millis int64 `json:"ms,omitempty"`
// Compact: how long a compaction of the context kept the agent waiting, in ms.
// Codex's is on the compaction's own call (its Millis); Claude Code's is the
// durationMs its compact_boundary line says, on the first call after it
Compact int64 `json:"compact_ms,omitempty"`
Cwd string `json:"cwd,omitempty"`
// Where the call is in its file, for reading what was said in it (ContentOf): the file,
// from where what it was asked began — after the reply before it — to where it ended,
// and for Claude Code the id of its message
@@ -82,6 +86,8 @@ type callFile struct {
Requested string
LastUser, LastAsst time.Time
Began map[string]time.Time
// how long a compaction its file told of took, for the call after it
CompactMs int64
// Codex
CX *cxRun
}
@@ -480,6 +486,16 @@ func claudeCallLine(st *callFile, b []byte) {
if json.Unmarshal(b, &n) == nil && n.Attachment.Identity.ModelID != "" {
st.Requested = st.str(n.Attachment.Identity.ModelID)
}
case bytes.Contains(b, ccCompact):
// {"type":"system","subtype":"compact_boundary","compactMetadata":{"durationMs":48913,…}}
var n struct {
Meta struct {
DurationMs int64 `json:"durationMs"`
} `json:"compactMetadata"`
}
if json.Unmarshal(b, &n) == nil && n.Meta.DurationMs > 0 {
st.CompactMs = n.Meta.DurationMs
}
case bytes.Contains(b, ccUserLine):
// what a reply is asked by: a prompt, or a tool's result
if at := tsAt(b, true); !at.IsZero() {
@@ -623,6 +639,9 @@ func claudeCallLine(st *callFile, b []byte) {
}
st.Msgs[c.Msg], st.Began[c.Msg] = m.Call, asked
}
if c.Error == "" {
c.Compact, st.CompactMs = st.CompactMs, 0
}
st.Calls = append(st.Calls, c)
}
@@ -637,6 +656,7 @@ func firstChars(s string, n int) string {
var (
ccIdentity = []byte(`"identity":{"modelId":"`)
ccUserLine = []byte(`"type":"user"`)
ccCompact = []byte(`"subtype":"compact_boundary"`)
cxToolOut = []byte(`"type":"function_call_output"`)
cxCustomOut = []byte(`"type":"custom_tool_call_output"`)
cxStarted = []byte(`"type":"task_started"`)
@@ -773,6 +793,7 @@ func codexCallLine(st *callFile, b []byte) {
r.Turns[p.TurnID] = turn
if turn.N == 1 {
st.Calls[turn.First].TTFT, st.Calls[turn.First].Millis = p.FirstToken, p.Duration
st.codexCompact(turn.First)
st.markCall(turn.First)
}
case l.Type == "compacted":
@@ -897,10 +918,21 @@ func (st *callFile) codexTiming(i int) {
if turn.N == 1 && turn.Complete {
c.Millis, c.TTFT = turn.Duration, turn.FirstToken
}
st.codexCompact(i)
st.markCall(i)
}
// codexCompact notes a compaction's call's time as the wait it made: Codex
// compacts by a call of its own to the model.
func (st *callFile) codexCompact(i int) {
c := &st.Calls[i]
c.Compact = 0
if e := st.CX.Usage.Entries; i < len(e) && e[i].Compaction {
c.Compact = c.Millis
}
}
func hashHead(head string) string { return fmt.Sprintf("%x", sha256.Sum256([]byte(head))) }
func sameHead(head, hash string, size int) bool {
return size >= 0 && len(head) >= size && hashHead(head[:size]) == hash
+65
View File
@@ -595,6 +595,71 @@ func TestCallsCodexTimedFromTheAsk(t *testing.T) {
}
}
// A Claude Code compaction is no call of the file's, but its compact_boundary
// line says how long it took (shape from a real 2026-10 transcript): the
// first call after it carries that, an API error between them does not take
// it, and a call with no compaction before it carries none.
func TestCallsClaudeCompactTook(t *testing.T) {
d := setupCalls(t)
boundary := func(sec, ms int) string {
return fmt.Sprintf(`{"parentUuid":null,"logicalParentUuid":"p","isSidechain":false,"type":"system","subtype":"compact_boundary","content":"Conversation compacted","isMeta":false,"timestamp":"%s","uuid":"b%d","level":"info","compactMetadata":{"trigger":"auto","preTokens":169492,"postTokens":7669,"durationMs":%d},"sessionId":"sess1","cwd":"/work/app"}`, stamp(sec), sec, ms)
}
summary := func(sec int) string {
return fmt.Sprintf(`{"type":"user","timestamp":"%s","message":{"role":"user","content":"This session is being continued"},"isCompactSummary":true,"sessionId":"sess1"}`, stamp(sec))
}
writeLines(t, filepath.Join(d.claude, "projects", "-work-app", "sess1.jsonl"),
claudeMsg("a", "claude-opus-5-5", 1, 1, 160000, 0, 10),
boundary(60, 48913),
summary(60),
claudeSynthetic("API Error: overloaded", 61, `,"isApiErrorMessage":true`),
claudeMsg("b", "claude-opus-5-5", 1, 1, 0, 9000, 70),
claudeMsg("c", "claude-opus-5-5", 1, 1, 9000, 0, 80),
)
got := map[string]int64{}
check := func() {
t.Helper()
clear(got)
for _, c := range Calls(time.Time{}) {
got[c.RequestID+c.Error] += c.Compact
}
if got["req_a"] != 0 || got["req_b"] != 48913 || got["req_c"] != 0 || got["unknown"] != 0 {
t.Fatalf("compact: %v", got)
}
}
check()
Reset() // read again from the call cache
check()
}
// Codex compacts by a call of its own (a token_usage_record the compacted
// line names): that call's time is the compaction's (real fixture: asked at
// task_started 01:41:35.120, answered 01:44:20.576). Other calls carry none.
func TestCallsCodexCompactTook(t *testing.T) {
data, err := os.ReadFile(filepath.Join("testdata", "codex-native-compaction.jsonl"))
if err != nil {
t.Fatal(err)
}
codexUsageLog(t, strings.Split(strings.TrimSpace(string(data)), "\n"))
check := func() {
t.Helper()
got := map[string]int64{}
for _, c := range Calls(time.Time{}) {
got[c.ResponseID] = c.Compact
}
for id, ms := range got {
if want := map[bool]int64{true: 165456}[id == "resp_4"]; ms != want {
t.Fatalf("compact %v", got)
}
}
if _, ok := got["resp_4"]; !ok {
t.Fatalf("no compaction call: %v", got)
}
}
check()
Reset()
check()
}
// bare is a call without where it is in its file, which a test of what the
// calls are has no want of.
func bare(c Call) Call {
+79 -5
View File
@@ -34,6 +34,9 @@ type Call struct {
Out int
Wrote int // of Prompt, written to the cache
Wrote1 int // of Wrote, kept an hour
// Compact is how long a compaction kept the agent waiting, in ms, on the
// call its file tells it with; 0 when none or the agent doesn't say
Compact int64
}
// FromCalls makes tune's calls of an agent's calls read from its files,
@@ -60,6 +63,7 @@ func FromCalls(cs []sessions.Call) []Call {
Time: c.Time, Stream: stream, Model: strings.ToLower(m), Long: long,
Sub: strings.Contains(filepath.ToSlash(c.File), "/subagents/"),
Prompt: p, Out: c.Output, Wrote: c.CacheWrite, Wrote1: c.CacheWrite1h,
Compact: c.Compact,
})
}
return out
@@ -83,11 +87,14 @@ func WeightsFor(model string) Weights {
// Point is one setting tried and what the period would have cost with it,
// and how many compactions it would have made there: what a window over
// the leanest buys, said beside what it costs (#1860).
// the leanest buys, said beside what it costs (#1860). Wait is the seconds
// those compactions would have kept the user waiting, when the agent's
// files time them (Facts.Took).
type Point struct {
Value int `json:"value"`
Cost float64 `json:"cost"`
Compacts int `json:"compacts"`
Wait int `json:"wait,omitempty"`
}
// Facts are what a replay found of the user's habits, said beside the
@@ -106,6 +113,10 @@ type Facts struct {
Away float64 `json:"away,omitempty"` // over an hour
Hour float64 `json:"hour,omitempty"` // of the cache writes, the share kept an hour
Sessions int `json:"sessions,omitempty"` // streams that reached a compaction
// Took is the median seconds a compaction kept the agent waiting, of
// Timed compactions its files timed; 0 when fewer than minTimed were
Took int `json:"took,omitempty"`
Timed int `json:"timed,omitempty"`
}
// Compaction is the window advised for one model of an agent.
@@ -118,6 +129,14 @@ type Compaction struct {
Low float64 `json:"low"` // with Best
Curve []Point `json:"curve"`
Facts Facts `json:"facts"`
// with compactions timed, the seconds they would have waited: with
// Current, and with Best
Wait int `json:"wait,omitempty"`
WaitBest int `json:"wait_best,omitempty"`
// with compactions timed, the cheapest window and its wait, which
// the advice passes over when it would wait longer than now
Cheapest int `json:"cheapest,omitempty"`
WaitCheapest int `json:"wait_cheapest,omitempty"`
}
// CompactOpts says how an agent compacts: the windows it takes, and how
@@ -143,8 +162,30 @@ const (
dropFrom = 20000
// the calls after a compaction its rework is counted over
reworkCalls = 10
// the compactions that must be timed before their time is weighed
minTimed = 3
// windows within this share of the cheapest cost the same: the least
// that is worth changing a setting for (Compact keeps the current one
// unless it saves this much), and so, with compactions timed, the band
// the one that compacts least is taken from
sameCost = 0.03
)
// took is the median seconds a compaction took of those the calls time,
// and how many that is; 0 when fewer than minTimed are.
func took(cs []Call) (int, int) {
var ms []int
for _, c := range cs {
if c.Compact > 0 {
ms = append(ms, int(c.Compact))
}
}
if len(ms) < minTimed {
return 0, len(ms)
}
return (median(ms) + 500) / 1000, len(ms)
}
// streams groups calls by the conversation they are in, each oldest first.
func streams(cs []Call) [][]Call {
by := map[string][]Call{}
@@ -321,12 +362,17 @@ func Compact(cs []Call, o CompactOpts) *Compaction {
// over: it keeps at least half the summary's size, or twenty calls'
// growth, free over it
floor := max(o.Min, roundUp(after+max(after/2, 20*f.Growth)+o.Reserve, o.Step))
f.Took, f.Timed = took(cs)
if f.Took == 0 {
f.Timed = 0
}
r := &Compaction{Model: model, Current: cur, Window: o.Window, Facts: f}
run := func(v int) Point {
c, n, _ := replayCompact(ss, max(after+1, v-o.Reserve), after, b, rework, w, write)
return Point{Value: v, Cost: c, Compacts: n}
return Point{Value: v, Cost: c, Compacts: n, Wait: n * f.Took}
}
r.Cost = run(cur).Cost
now := run(cur)
r.Cost = now.Cost
for v := floor; v <= top; v += o.Step {
r.Curve = append(r.Curve, run(v))
}
@@ -342,10 +388,38 @@ func Compact(cs []Call, o CompactOpts) *Compaction {
best = p
}
}
// with the agent's compactions timed, the advice never makes the user
// wait longer than the window now does: tokens and seconds share no
// unit the files measure, so it doesn't trade one for the other on a
// guessed rate. Of the windows that compact no more often than now,
// the cheapest; of those within sameCost of it, the one that waits
// least (the fewest compactions, the larger of two that make as
// many). A cheaper window that waits longer stays on the curve with
// its wait, for the reader to pick.
if f.Took > 0 {
var calm []Point
for _, p := range r.Curve {
if p.Compacts <= now.Compacts {
calm = append(calm, p)
}
}
best = now
if len(calm) > 0 {
cl := slices.MinFunc(calm, func(a, b Point) int { return cmpF(a.Cost, b.Cost) })
best = cl
for _, p := range calm {
if p.Cost <= cl.Cost*(1+sameCost) && (p.Compacts < best.Compacts || p.Compacts == best.Compacts && p.Value > best.Value) {
best = p
}
}
}
r.Cheapest, r.WaitCheapest = low.Value, low.Wait
}
r.Best, r.Low = best.Value, best.Cost
r.Wait, r.WaitBest = now.Wait, best.Wait
// it only says to change what would save 3% or more
if r.Cost <= 0 || (r.Cost-r.Low)/r.Cost < 0.03 {
r.Best, r.Low = cur, r.Cost
if r.Cost <= 0 || (r.Cost-r.Low)/r.Cost < sameCost {
r.Best, r.Low, r.WaitBest = cur, r.Cost, r.Wait
}
_, _, over := replayCompact(ss, max(after+1, r.Best-o.Reserve), after, b, rework, w, write)
f.Long = float64(over) / float64(max(1, f.Calls))
+114
View File
@@ -151,3 +151,117 @@ func TestCompactCurveCountsCompactions(t *testing.T) {
t.Fatalf("%d compactions replayed at %d, %d seen in the files", last.Compacts, last.Value, r.Facts.Compacts)
}
}
// timed marks the first ms compactions of cs (the call after each drop) as
// having kept the agent waiting ms milliseconds, as its files would say.
func timed(cs []Call, n int, ms int64) []Call {
out := append([]Call(nil), cs...)
for i := 1; i < len(out) && n > 0; i++ {
if out[i].Stream == out[i-1].Stream && compacted(out[i-1].Prompt, out[i].Prompt) {
out[i].Compact = ms
n--
}
}
return out
}
// With the agent's compactions timed, the advice never waits longer than
// the window now does: of the windows that compact no more often, the
// cheapest, and of those within 3% of it the fewest compactions. The
// cheaper window untimed advice takes, which compacts more often, is said
// with its wait instead. Each window says the seconds its compactions
// would have waited.
func TestCompactTimedWaitsLeast(t *testing.T) {
cs := many(4, func(id string, t0 time.Time) []Call {
return session(id, t0, 400, 30000, 4000, 967000, 60000, 30*time.Second, false)
})
for _, cur := range []int{1000000, 600000, 150000} {
o := claudeOpts
o.Window, o.Current = 1000000, cur
plain := Compact(cs, o)
r := Compact(timed(cs, 4, 61400), o)
if plain == nil || r == nil {
t.Fatal("no advice")
}
if r.Facts.Took != 61 || r.Facts.Timed != 4 {
t.Fatalf("took %ds of %d timed, want 61s of 4", r.Facts.Took, r.Facts.Timed)
}
nowN := r.Wait / 61 // the window now may sit under the curve
low := r.Curve[0]
for _, p := range r.Curve {
if p.Cost < low.Cost {
low = p
}
}
var best Point
for _, p := range r.Curve {
if p.Wait != p.Compacts*61 {
t.Fatalf("%d waits %ds for %d compactions", p.Value, p.Wait, p.Compacts)
}
if p.Value == r.Best {
best = p
}
}
if best.Compacts > nowN {
t.Fatalf("at %d: advised %d makes %d compactions, more than %d now", cur, r.Best, best.Compacts, nowN)
}
for _, p := range r.Curve {
if p.Compacts <= nowN && p.Cost*(1+sameCost) < best.Cost {
t.Fatalf("at %d: %d waits no longer than now and costs %.0f, over 3%% under %.0f at %d", cur, p.Value, p.Cost, best.Cost, r.Best)
}
}
if r.Cheapest != low.Value || r.WaitCheapest != low.Wait {
t.Fatalf("at %d: cheapest said %d (%ds), want %d (%ds)", cur, r.Cheapest, r.WaitCheapest, low.Value, low.Wait)
}
if r.WaitBest != best.Wait {
t.Fatalf("at %d: wait %ds now, %ds advised", cur, r.Wait, r.WaitBest)
}
t.Logf("at %d (%d compactions): untimed %d (%d), timed %d (%d), cheapest %d (%d)", cur, nowN, plain.Best, compactsAt(plain, plain.Best), r.Best, best.Compacts, low.Value, low.Compacts)
}
// from 1M, untimed advice goes to 260000 and compacts far more often;
// timed, it stays where the wait doesn't grow
o := claudeOpts
o.Window, o.Current = 1000000, 1000000
plain, r := Compact(cs, o), Compact(timed(cs, 4, 61400), o)
if compactsAt(plain, plain.Best) <= compactsAt(r, 1000000) {
t.Fatalf("fixture: untimed %d makes %d compactions, no more than %d now", plain.Best, compactsAt(plain, plain.Best), compactsAt(r, 1000000))
}
if r.Best == plain.Best {
t.Fatalf("timed advice %d is untimed's, which waits longer than now", r.Best)
}
}
func compactsAt(r *Compaction, v int) int {
for _, p := range r.Curve {
if p.Value == v {
return p.Compacts
}
}
return -1
}
// Too few compactions timed, or none, and the advice is what it was without
// their time: the same window, no wait said.
func TestCompactUntimedUnchanged(t *testing.T) {
cs := many(4, func(id string, t0 time.Time) []Call {
return session(id, t0, 400, 30000, 4000, 967000, 60000, 30*time.Second, false)
})
o := claudeOpts
o.Window, o.Current = 1000000, 1000000
plain := Compact(cs, o)
few := Compact(timed(cs, 2, 61400), o)
if plain == nil || few == nil {
t.Fatal("no advice")
}
if plain.Best != 260000 || few.Best != plain.Best {
t.Fatalf("best %d untimed, %d with 2 timed; want 260000 both", plain.Best, few.Best)
}
if few.Facts.Took != 0 || few.Facts.Timed != 0 || few.Wait != 0 || few.WaitBest != 0 || few.Cheapest != 0 || few.WaitCheapest != 0 {
t.Fatalf("wait said from 2 timed: %+v", few)
}
for _, p := range few.Curve {
if p.Wait != 0 {
t.Fatalf("%d waits %ds", p.Value, p.Wait)
}
}
}