agents: Claude Code's prompt cache lifetime is picked in its settings
Linka (Discord) asked to set Claude Code's prompt cache TTL from magpie. Until now only Usage › Context's "Tuned for you" card wrote it, and that card offers nothing when the value is already the cheapest it found. Claude Code's opened row and settings sheet now have two rows under its own Long conversations: "Prompt cache · main conversation" and "Prompt cache · subagents". Each opens the app menu with Claude Code's default, 5 min and 1 hour. They write the keys the card writes, promptCacheTtl and subagentPromptCacheTtl in Claude Code's settings.json (agent.ClaudeCacheSet, POST /api/settings/claude-cache). Default takes the key out. A pick is the user's own: it forgets the card's stash, so the card's Undo leaves it. A variable that comes before the setting (FORCE_PROMPT_CACHING_5M, CLAUDE_CODE_PROMPT_CACHE_TTL, CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL, in settings.json's env or magpie's own) disables the row and names the variable, and the route refuses it, so a value the user set by hand is never written over. The names were checked in Claude Code 2.1.316's binary. Its resolver checks FORCE_PROMPT_CACHING_5M, then the env var, then the setting (enum "5m"/"1h"), then an agent's experimental.cacheTtl, then ENABLE_PROMPT_CACHING_1H. With nothing set, the main conversation gets 1h on a subscription within its limits and subagents get 5m. Run (mote, at this tree on2ce44dc28): - go test -count=1 -run 'TestClaudeCache|TestTune' ./internal/agent ./internal/gui: ok; go test ./internal/cli: ok (route parity). - node --test claude-cache.test.cjs: 8/8 (Chromium and WebKit, en and zh, 900 and 420px), with agent-compact, i18n-*, gui-ja/zh-tw/de, old-webkit, agent-details-ready and context-tune: ok. - Whole GUI suite on the Linux VM (wsl-run, concurrency 4), still running at commit: 74 files red there, mostly WebKitGTK. Of those only codex-memories-settings reaches Claude Code's settings: it counted Claude Code's rows as Long conversations alone, and now leaves out the two cache rows and checks they are there (18/18 on mote). desktop-subagent-model, account-eye, allow-ips and builtins pass alone on mote. codex-auto-reset (webkit de, #4790) and i18n-keys (#5327, #5332, #5426, #5482) fail the same way at origin/mainf0620db63on mote. - go test ./internal/gui ./internal/agent ./internal/tune: agent and tune ok; gui red only in TestMainWindowCorners/macOS_26_SDK (#3949). - gofmt -l: clean; go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./..., go build ./...: ok. Broken by hand: - Without forget, TestClaudeCacheSet fails ("the pick is the user's, not the card's"). - Without the lock check, it fails ("set under CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL"). - With default leaving the key, TestClaudeCacheSet and TestClaudeCacheRoute fail. - Without the rows in agentcompact.js, claude-cache.test.cjs fails 8/8. Without the same-pick check, it fails on the extra post. - The first GUI run was red in WebKit at 420px: Playwright's own scroll to an off-screen button was taken as the page scrolling. The test now wheels the rows into sight as a reader does, and checks they came into view. Not tried: a real Claude Code session reading the picked value (only the settings.json it reads was checked); the live ~/.claude was never touched. Reported-by: Linka
This commit is contained in:
@@ -25,6 +25,7 @@ something else shows up as drift.
|
||||
| Codex background compaction | Long conversations' Codex background compaction, in Codex's opened row on the Agents page (`CodexAsyncCompact`, `CodexAsyncCompactPercent`, #2490) writes `[features.async_compaction]` `enabled = true` and `model_async_compact_threshold_percent` (Codex 0.163 reads it only in that table) into each Codex config magpie routes, on every `Sync`. The table is written only when every Codex that reads the config is 0.163.0-alpha.8 or later (`codexReaders`: the CLI on PATH, the Mac app's bundled `codex-cli/codex-package.json`, the Windows Store app and an editor's `openai.chatgpt` extension, whose versions aren't known, a WSL distro's CLI): an older Codex takes every unknown `[features]` entry for a bool and won't load a config with the table ("invalid type: map, expected a boolean"). Otherwise, or with no Codex found, magpie writes the bare `[features]` `async_compaction = true`, which every Codex loads, and no threshold; a table magpie wrote before is taken out on the next `Sync`, and Settings' row names the Codex that held it (`CodexAsyncHeld`). Codex starts a background compaction only on a provider whose `capabilities.remote_compaction` is `"v2"`, which it gives OpenAI and Azure alone, so `[model_providers.magpie]` gets `capabilities = { remote_compaction = "v2" }` too, also when the user turned the feature on by hand (#2493); `putProvider` carries the table's capabilities over when it writes it again. What magpie wrote is in the stash under `codex.async`: a value the user set, or changed since, is never written over and stays when the switch goes off; a bare `async_compaction = true` the stash doesn't name as magpie's (`bool`), an inline or dotted table is the user's as written. | [`codex_async.go`](../../internal/agent/codex_async.go) |
|
||||
| Codex windows | Each magpie model's entry in Codex's catalog (`codexcat.entriesAt`, and `listedEntry` for a relay's own entry) says the model's whole window as `context_window`, which Codex shows (95% of it) as the conversation's context. Where Codex compacts goes in the entry's `auto_compact_token_limit`: the threshold set on the model or its provider, else Long conversations' (`settings.Working`, 272K by default), only when that is below the window; Full window writes none. A model whose window magpie doesn't know (a relay listing none, one models.dev lacks) gets no `context_window` and still the threshold as `auto_compact_token_limit` (Long conversations' Compact at, 272K by default; a relay's own entry only a user-set one, under its own window and limit): Codex compacts at no point on an entry with neither, and after the vendor's "too long" every turn errors again until a manual /compact (jiangguochao666 on X, 11-01; reproduced with real Codex 0.165 and a relay refusing past 100K, compacted at 80K after the fix). `TestCodexCompactsWithNoKnownWindow`. A vendor that lists a larger window than it takes is not caught: Codex compacts on that window's 90%, or the threshold. Codex 0.165 compacts at the lesser of it and 90% of the window, and a `model_auto_compact_token_limit` the user put in config.toml comes before it, as a `model_context_window` there replaces every model's window (Codex then compacts at 90% of it). Long conversations' row in Codex's opened card names either one, top-level or in the profile config.toml picks (`agent.CodexCompactHeld`, sent to the page as one line by `codexKeysText`), and Take it out deletes them (`DropCodexCompactHolds`); magpie never deletes them on its own, as the value is the user's (zgjfjfl on Discord, 10-31: 128000 there, 544K in Long conversations). No threshold above a model's window moves Codex either, which then compacts at 90% of it: the row names the model Codex's config runs (`agent.CodexModel`, the picked profile's first) and the window magpie tells Codex for it, when Long conversations doesn't come below it and no threshold is set on the model or its provider (`codexWindowUnder` in internal/gui/api.go; the reporter's model was a relay's gpt-6-A). `TestCodexCompactHeldNamedAndTakenOut`, `TestCodexWindowUnderLongConversations`, codex-compact-held.test.cjs. Until 10-30 the threshold went in `context_window` with the window as `max_context_window`, so a 1M model showed 258K in Codex (01huadalang on Discord); `max_context_window` stays a field magpie owns so `Keep` doesn't carry an old catalog's over. Codex's own models (`codex/`) keep their entry's window. `Tag` carries `catalogFormat`, so a Codex holding a list in the old shape asks again. `TestCodexCatalogCompactAt`, `TestCodexWindowShownCompactApart`. | [`codexcat.go`](../../internal/codexcat/codexcat.go) |
|
||||
| An agent's own Long conversations | Codex, Claude Code and Grok Build (`settings.CompactAgents`) can each have a Long conversations of their own over the one for every agent (molianyin4227 on Discord: models differ, so one size fits none): `settings.AgentCompacts[agent]` holds Compact at (`At`, 0 for the working window) or Full window (`Full`), and `Settings.ForAgent(agent)` lays it over `CompactAt`/`FullContext` for that agent's readers alone (`codexcat.entriesAt`, `codexListed`, `claudeIn`'s `writeCompact` and `desktopPlan`, `grokModelTables`, the route list's `buildModels`, Codex's window line and Tuned for you). A threshold set on a model or its provider still comes first. An agent with none follows the value for every agent, so an agent without the key (any agent outside the three) gets nothing new written. Set by `provider.SetAgentCompact` (`POST /api/settings/agent-compact` `{agent, own, full, at}`; `own` false takes it away), shown as a row under Long conversations in the agent's opened row and its sheet ("Long conversations in <agent>": Every agent, Compact at, Full window), drawn by `agentcompact.js`, which app.js imports when the agent's settings hold Long conversations. Tuned for you's Use on an agent with its own value changes that one and stashes it under `tune.long.compact.<agent>`. In a terminal, `magpie model compact <codex|claude|grok> [every|off|<size>]` (`agentCompact`, `TestModelCompactAgentCmd`). Not covered: t3code's route list reads the value for every agent. `TestSetAgentCompact`, `TestCodexCatalogCompactAt`, `TestGrokWindowFollowsLongConversations`, `TestClaudeCompactAt`, `TestTuneAgentOwnLong`, agent-compact.test.cjs. | [`settings.go`](../../internal/settings/settings.go), [`compact.go`](../../internal/provider/compact.go), [`agentcompact.js`](../../internal/gui/assets/agentcompact.js) |
|
||||
| Claude Code's prompt cache | Claude Code's opened row and sheet have, under its Long conversations, "Prompt cache · main conversation" and "Prompt cache · subagents" (Linka on Discord), each Claude Code's default, 5 min or 1 hour in the app menu (`claudeCacheRows` in `agentcompact.js`). They write the keys Tuned for you writes, `promptCacheTtl` and `subagentPromptCacheTtl` in Claude Code's settings.json (`agent.ClaudeCacheSet`, `POST /api/settings/claude-cache` `{knob, value}`; the values read back as `claudeCache` in `/api/settings`). Default takes the key out. A pick is the user's: it forgets the card's stash, so Undo leaves it. A variable that comes first (`FORCE_PROMPT_CACHING_5M`, `CLAUDE_CODE_PROMPT_CACHE_TTL`, `CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL`) disables the row and names it, and the route refuses. Claude Code 2.1.316 reads them in that order, then the setting, then an agent's `experimental.cacheTtl`, then `ENABLE_PROMPT_CACHING_1H`; unset, the main conversation takes 1 hour on a subscription within its limits and subagents 5 minutes. `TestClaudeCacheSet`, `TestClaudeCacheRoute`, claude-cache.test.cjs. | [`tune.go`](../../internal/agent/tune.go), [`agentcompact.js`](../../internal/gui/assets/agentcompact.js) |
|
||||
| Codex instructions | Each magpie model's entry in Codex's catalog carries the instructions official Codex sends that model, Codex's own text word for word; magpie writes none of its own and never changes the identity line (`codexcat.officialFor`). The model's slug (the id's last path segment, lowercased) is matched as Codex matches one, by the longest prefix of an official slug (`longestPrefix`; `auto/gpt-6.1-sol` takes gpt-6.1-sol's, `s2a/openai/gpt-6-luna-2026-09-14` gpt-6-luna's): first against the entries the user's ChatGPT account handed this Codex (`CacheEntries`, models_cache.json), whose `base_instructions` (else `model_messages.instructions_template`) and `model_messages` go over as sent; then against Codex's bundled catalog (`codex_instructions.json`, each model's `instructions_template` from openai/codex rust-v0.166.0's models-manager/models.json), the text only, as an older Codex may not read that release's `model_messages`. Any other model, and a routing group (`group/`), which may hand a turn to any model, takes Codex's prompt for a model it doesn't know (`Prompt`, models-manager/prompt.md), which is what official Codex sends it (`model_info_from_slug`). An entry Codex was handed with no `base_instructions` (`ownEntry`) takes its `model_messages.instructions_template`, else `Official`, and magpie's own ChatGPT-backend requests fall back to `Official` too (`codexInstructions` in internal/provider). Until 11-01 every third-party model was handed gpt-5.2-codex_prompt.md ("You are Codex, based on GPT-5"), so a magpie GPT-6 model ran on a GPT-5.2-era prompt (#3759, #4008, #4783). The Codex files are in testdata (`testdata/codex-rust-v0.166.0`), and `TestBundledIsCodexOwn` fails when the embedded copies differ from them; on a new Codex release copy its two files there and rebuild `codex_instructions.json`. Real Codex 0.166 against a capturing gateway sends the official text as its first developer message for a GPT-6 model and prompt.md for DeepSeek. `TestThirdPartyModelsTakeCodexOwnInstructions`, `TestThirdPartyModelsTakeCachedEntry`, `TestOwnEntryInstructions`. Not read: the bundled catalog inside the user's installed Codex binary. | [`codexcat.go`](../../internal/codexcat/codexcat.go) |
|
||||
| Codex: DeepSeek models | A DeepSeek model's entry (`codexcat.deepSeek`: deepseek-v4*, -flash, -pro, -chat, -reasoner after any provider or relay prefix; not a routing group, not a distill) takes what DeepSeek's own Codex setup (cdn.deepseek.com/api-docs/codex-deepseek-setup-en.sh, its models.json) says of its models: `shell_type` `shell_command` (Codex 0.165 reads it as `unified_exec`, its only shell; older Codex had a one-shot `shell_command` tool), `support_verbosity` with `default_verbosity` low, `default_reasoning_summary` none (no `reasoning.summary` sent), `multi_agent_version` v2, and `supports_image_detail_original` on a model whose entry takes images. Not taken: its `base_instructions`/`model_messages` (magpie never rewrites a Codex prompt), its `auto_compact_token_limit` null (magpie's 272K default stays, from e950eb080's DeepSeek latency report; Full window or the model's Compact at gives the whole window), `supports_search_tool` false on v4-pro (#258), its reasoning levels (the provider's). `default_reasoning_summary` is tagged `keep:"unset"`, so a value the user put in another model's entry stays (`Keep`). Other vendors' entries are unchanged. `TestCodexCatalogDeepSeekAsDeepSeekSays`, `TestCodexCatalogKeepsUsersSummary`. | [`codexcat.go`](../../internal/codexcat/codexcat.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) |
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
package agent
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestClaudeCacheSet (Linka on Discord): Claude Code's prompt cache picked
|
||||
// in its settings goes where the Usage card writes it, the user's other
|
||||
// settings kept; Claude Code's default takes the key out; a value the card
|
||||
// stashed is forgotten, so its Undo never puts an older one back over the
|
||||
// pick; a variable Claude Code reads first leaves the file alone.
|
||||
func TestClaudeCacheSet(t *testing.T) {
|
||||
home := tuneSandbox(t)
|
||||
path := filepath.Join(home, ".claude", "settings.json")
|
||||
flat := func() string { return strings.Join(strings.Fields(tuneFile(t, path)), "") }
|
||||
tuneWrite(t, path, `{"theme": "dark", "promptCacheTtl": "1h"}`)
|
||||
if s, _ := TuneRead(home, "claude", TuneCache, ""); s.Value != "1h" || s.Source != "settings" {
|
||||
t.Fatalf("read %+v; want the user's own 1h", s)
|
||||
}
|
||||
if err := ClaudeCacheSet(home, TuneCache, "5m"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := flat(); got != `{"theme":"dark","promptCacheTtl":"5m"}` {
|
||||
t.Fatalf("after 5m: %s", got)
|
||||
}
|
||||
if err := ClaudeCacheSet(home, TuneSubCache, "1h"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s, _ := TuneRead(home, "claude", TuneSubCache, ""); s.Value != "1h" {
|
||||
t.Fatalf("subagents %+v; want 1h", s)
|
||||
}
|
||||
for _, knob := range []string{TuneCache, TuneSubCache} {
|
||||
if err := ClaudeCacheSet(home, knob, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if got := flat(); got != `{"theme":"dark"}` {
|
||||
t.Fatalf("Claude Code's default left a key: %s", got)
|
||||
}
|
||||
if err := ClaudeCacheSet(home, TuneCache, ""); err != nil {
|
||||
t.Fatalf("default again: %v", err)
|
||||
}
|
||||
|
||||
// the card put 1h in over the user's 5m; picking 5m in the settings is
|
||||
// theirs, and the card's Undo has nothing left to put back
|
||||
tuneWrite(t, path, `{"promptCacheTtl": "5m"}`)
|
||||
if err := TuneApply(home, "claude", TuneCache, "", "1h"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := ClaudeCacheSet(home, TuneCache, "1h"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s, _ := TuneRead(home, "claude", TuneCache, ""); s.Ours {
|
||||
t.Fatalf("read %+v; the pick is the user's, not the card's", s)
|
||||
}
|
||||
if err := TuneUndo(home, "claude", TuneCache, ""); err == nil {
|
||||
t.Fatal("the card could still undo the user's pick")
|
||||
}
|
||||
if got := flat(); got != `{"promptCacheTtl":"1h"}` {
|
||||
t.Fatalf("after Undo: %s", got)
|
||||
}
|
||||
|
||||
for _, bad := range [][2]string{{TuneCache, "2h"}, {TuneCompact, "5m"}, {"cache", "5m"}} {
|
||||
if err := ClaudeCacheSet(home, bad[0], bad[1]); err == nil {
|
||||
t.Errorf("took %s=%q", bad[0], bad[1])
|
||||
}
|
||||
}
|
||||
|
||||
// a variable Claude Code reads before the setting: nothing written
|
||||
tuneWrite(t, path, `{"env": {"CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL": "1h"}}`)
|
||||
if err := ClaudeCacheSet(home, TuneSubCache, "5m"); err == nil {
|
||||
t.Fatal("set under CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL")
|
||||
}
|
||||
if err := ClaudeCacheSet(home, TuneSubCache, ""); err == nil {
|
||||
t.Fatal("cleared under CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL")
|
||||
}
|
||||
t.Setenv("FORCE_PROMPT_CACHING_5M", "1")
|
||||
if err := ClaudeCacheSet(home, TuneCache, "1h"); err == nil {
|
||||
t.Fatal("set under FORCE_PROMPT_CACHING_5M")
|
||||
}
|
||||
if got := flat(); got != `{"env":{"CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL":"1h"}}` {
|
||||
t.Fatalf("wrote under a variable: %s", got)
|
||||
}
|
||||
}
|
||||
+39
-3
@@ -420,9 +420,10 @@ type TuneKnob struct {
|
||||
// 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
|
||||
// card 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). The cache lifetimes are also picked in Claude Code's own
|
||||
// settings (ClaudeCacheSet), which makes them the user's. 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 {
|
||||
@@ -636,3 +637,38 @@ func asyncUndo() error {
|
||||
}
|
||||
return provider.SetCodexAsyncCompact(st.On, st.Percent)
|
||||
}
|
||||
|
||||
// ClaudeCacheSet is one of Claude Code's prompt-cache lifetimes as the
|
||||
// user picks it in Claude Code's settings, beside its compaction (Linka on
|
||||
// Discord: the card offers no way to change a lifetime that is already
|
||||
// the cheapest): "5m" or "1h", written where the card writes it
|
||||
// (promptCacheTtl, subagentPromptCacheTtl in settings.json), or "" taking
|
||||
// the key out, so Claude Code's own default holds. Claude Code reads the
|
||||
// variables before the setting (FORCE_PROMPT_CACHING_5M, then
|
||||
// CLAUDE_CODE_PROMPT_CACHE_TTL or CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL),
|
||||
// so with one set nothing is written. The pick is the user's own: a value
|
||||
// the card stashed is forgotten, so its Undo never puts an older one back
|
||||
// over it.
|
||||
func ClaudeCacheSet(home, knob, value string) error {
|
||||
if knob != TuneCache && knob != TuneSubCache {
|
||||
return fmt.Errorf("Claude Code has no prompt cache %q", knob)
|
||||
}
|
||||
if value != "" && value != "5m" && value != "1h" {
|
||||
return fmt.Errorf("the cache is kept 5m or 1h, not %q", value)
|
||||
}
|
||||
p, err := tuneWhere(home, "claude", knob, "")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if cur, _ := TuneRead(home, "claude", knob, ""); cur.Locked != "" {
|
||||
return fmt.Errorf("%s=%s is set and comes before the setting: take it out first", cur.Locked, cur.Value)
|
||||
}
|
||||
forget(tuneKey("claude", knob, ""))
|
||||
if value == "" {
|
||||
if _, ok := p.get(); !ok {
|
||||
return nil
|
||||
}
|
||||
return edit.DelJSON(p.path, p.key)
|
||||
}
|
||||
return edit.SetJSON(p.path, edit.KV{Path: p.key, Value: value})
|
||||
}
|
||||
|
||||
@@ -194,6 +194,7 @@ var notYet = map[string]string{
|
||||
"POST /api/settings/bare-ids": S2, // api.go
|
||||
"POST /api/settings/busy-load": S2, // api.go
|
||||
"POST /api/settings/checkin-account": S2, // api.go
|
||||
"POST /api/settings/claude-cache": S2, // tune.go
|
||||
"POST /api/settings/codex-agents-v1": S2, // api.go
|
||||
"POST /api/settings/codex-async-compact": S2, // api.go
|
||||
"POST /api/settings/codex-auto-reset": S2, // api.go
|
||||
|
||||
@@ -544,6 +544,9 @@ type settingsJSON struct {
|
||||
// model_auto_compact_token_limit; agent.CodexCompactHeld), written
|
||||
// as the row names them: "[profiles.p] key = value, ..."
|
||||
CodexCompactKeys string `json:"codexCompactKeys,omitempty"`
|
||||
// Claude Code's two prompt-cache lifetimes as it reads them
|
||||
// (agent.TuneRead): the rows beside its compaction in its settings
|
||||
ClaudeCache []claudeCacheJSON `json:"claudeCache,omitempty"`
|
||||
// the magpie model Codex's config runs, when its own window is no
|
||||
// larger than Long conversations' threshold: Codex compacts it at 90%
|
||||
// of that window (codexWindowUnder)
|
||||
@@ -810,6 +813,7 @@ func settingsState() settingsJSON {
|
||||
s.CodexUsers, s.ClaudeUsers = loginUsers("codex"), loginUsers("claude")
|
||||
s.CodexAsyncHeld = agent.CodexAsyncHeld()
|
||||
s.CodexCompactKeys = codexKeysText(agent.CodexCompactHeld(""))
|
||||
s.ClaudeCache = claudeCacheState()
|
||||
s.CodexWindow = codexWindowUnder(s.Settings.ForAgent("codex"), agent.CodexModel(""))
|
||||
s.WorkBuddy, s.WorkBuddyCheckins = provider.HasWorkBuddy(), provider.WorkBuddyCheckins()
|
||||
s.Trae, s.TraeCheckins = provider.HasTrae(), provider.TraeCheckins()
|
||||
|
||||
@@ -42,11 +42,63 @@ window.agentCompactFill = function (list, a) {
|
||||
};
|
||||
draw();
|
||||
list.querySelector(".agent-compact")?.remove();
|
||||
list.querySelectorAll(".claude-cache").forEach((r) => r.remove());
|
||||
const above = list.querySelector("#fullContextRow");
|
||||
above ? above.after(row) : list.append(row);
|
||||
if (kind === "claude") row.after(...claudeCacheRows(list));
|
||||
// every agent's size, in its label, changes when the row above is drawn
|
||||
const seen = new MutationObserver(() => row.isConnected ? draw() : seen.disconnect());
|
||||
// Details can build this list before attaching it to the page.
|
||||
const segsBox = list.querySelector("#fullContextSegs");
|
||||
if (segsBox) seen.observe(segsBox, { childList: true });
|
||||
};
|
||||
|
||||
// Claude Code's prompt cache, beside its compaction (Linka on Discord: the
|
||||
// Usage card offers no way to change one that is already the cheapest):
|
||||
// the main conversation's and the subagents', each 5 min, 1 hour or
|
||||
// Claude Code's own default, which takes the key out of its settings.json
|
||||
// (agent.ClaudeCacheSet). One a variable sets shows it, unchangeable here.
|
||||
function claudeCacheRows(list) {
|
||||
const KNOBS = [["cache_ttl", "Prompt cache · main conversation"], ["subagent_cache_ttl", "Prompt cache · subagents"]];
|
||||
const OPTS = [["", "Claude Code's default"], ["5m", "5 min"], ["1h", "1 hour"]];
|
||||
return KNOBS.map(([knob, label]) => {
|
||||
const row = el("div", "row pref claude-cache");
|
||||
row.dataset.knob = knob;
|
||||
const who = el("div", "who"), val = el("div", "val");
|
||||
who.append(el("div", "name", t(label)));
|
||||
row.append(who, val);
|
||||
let drawn;
|
||||
const draw = () => {
|
||||
const c = ((prefs || {}).claudeCache || []).find((x) => x.knob === knob) || {};
|
||||
const key = JSON.stringify(c);
|
||||
if (key === drawn) return;
|
||||
drawn = key;
|
||||
const cur = c.value || "", known = OPTS.find(([v]) => v === cur);
|
||||
const b = el("button", "sess-pick");
|
||||
b.type = "button";
|
||||
b.setAttribute("aria-label", t(label));
|
||||
b.setAttribute("aria-haspopup", "menu");
|
||||
b.setAttribute("aria-expanded", "false");
|
||||
b.append(el("span", "", known ? t(known[1]) : cur), svg(CHEV, 11, 1.6));
|
||||
b.disabled = !!c.locked;
|
||||
b.onclick = (e) => {
|
||||
e.stopPropagation();
|
||||
if (b.classList.contains("open")) return closeProtoMenu();
|
||||
openProtoMenu(b, OPTS.map(([v, name]) => ({ v, name, note: "" })), cur, (v) => {
|
||||
if (v === cur) return;
|
||||
writingPrefs(api("settings/claude-cache", { knob, value: v }))
|
||||
.then((ns) => { prefs = ns; renderSettings(); if (row.isConnected) draw(); }).catch(settingsErr);
|
||||
}, label, "sess-menu", "right");
|
||||
};
|
||||
val.replaceChildren(b);
|
||||
who.querySelector(".sub")?.remove();
|
||||
if (c.locked) who.append(el("div", "sub", t("{name} is set and comes first", { name: c.locked })));
|
||||
};
|
||||
draw();
|
||||
// drawn again when the settings are read again
|
||||
const seen = new MutationObserver(() => row.isConnected ? draw() : seen.disconnect());
|
||||
const box = list.querySelector("#fullContextSegs");
|
||||
if (box) seen.observe(box, { childList: true });
|
||||
return row;
|
||||
});
|
||||
}
|
||||
|
||||
@@ -3897,6 +3897,7 @@ const I18N = {
|
||||
"auto mode": "自动模式",
|
||||
"Auto mode": "自动模式",
|
||||
"Claude Code's own pick": "由 Claude Code 自己挑选",
|
||||
"Claude Code's default": "Claude Code 默认",
|
||||
"the model that checks each action in auto mode": "自动模式下检查每个操作的模型",
|
||||
"the model {agent} picks for its auto mode classifier": "{agent} 为自动模式分类器挑选的模型",
|
||||
"no ChatGPT account is on in magpie": "magpie 中没有启用的 ChatGPT 账号",
|
||||
@@ -8531,6 +8532,7 @@ const I18N = {
|
||||
"auto mode": "自動模式",
|
||||
"Auto mode": "自動模式",
|
||||
"Claude Code's own pick": "由 Claude Code 自己挑選",
|
||||
"Claude Code's default": "Claude Code 預設",
|
||||
"the model that checks each action in auto mode": "自動模式下檢查每個操作的模型",
|
||||
"the model {agent} picks for its auto mode classifier": "{agent} 為自動模式分類器挑選的模型",
|
||||
"no ChatGPT account is on in magpie": "magpie 中沒有啟用的 ChatGPT 帳號",
|
||||
@@ -13182,6 +13184,7 @@ const I18N = {
|
||||
"auto mode": "自動モード",
|
||||
"Auto mode": "自動モード",
|
||||
"Claude Code's own pick": "Claude Code が自分で選ぶ",
|
||||
"Claude Code's default": "Claude Code の既定",
|
||||
"the model that checks each action in auto mode": "自動モードで各操作をチェックするモデル",
|
||||
"the model {agent} picks for its auto mode classifier": "{agent} が自動モードの分類器に選ぶモデル",
|
||||
"no ChatGPT account is on in magpie": "magpie で有効な ChatGPT アカウントがありません",
|
||||
@@ -17842,6 +17845,7 @@ const I18N = {
|
||||
"auto mode": "Auto-Modus",
|
||||
"Auto mode": "Auto-Modus",
|
||||
"Claude Code's own pick": "wählt Claude Code selbst",
|
||||
"Claude Code's default": "Standard von Claude Code",
|
||||
"the model that checks each action in auto mode": "das Modell, das im Auto-Modus jede Aktion prüft",
|
||||
"the model {agent} picks for its auto mode classifier": "das Modell, das {agent} für den Klassifikator des Auto-Modus wählt",
|
||||
"no ChatGPT account is on in magpie": "in magpie ist kein ChatGPT-Konto eingeschaltet",
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
package gui
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/agent"
|
||||
)
|
||||
|
||||
// Linka on Discord: Claude Code's prompt cache is set in its settings,
|
||||
// beside its compaction. Reading the settings shows the user's own value
|
||||
// and writes nothing; a pick goes through POST /api/settings/claude-cache,
|
||||
// and Claude Code's default ("") takes the key out.
|
||||
func TestClaudeCacheRoute(t *testing.T) {
|
||||
h := sandboxHome(t)
|
||||
path := filepath.Join(h, ".claude", "settings.json")
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
own := []byte(`{"theme": "dark", "promptCacheTtl": "1h"}`)
|
||||
if err := os.WriteFile(path, own, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := claudeCacheState()
|
||||
want := []claudeCacheJSON{{Knob: agent.TuneCache, Value: "1h"}, {Knob: agent.TuneSubCache}}
|
||||
if len(got) != 2 || got[0] != want[0] || got[1] != want[1] {
|
||||
t.Fatalf("read %+v; want %+v", got, want)
|
||||
}
|
||||
if b, _ := os.ReadFile(path); !bytes.Equal(b, own) {
|
||||
t.Fatalf("reading wrote the user's file:\n%s", b)
|
||||
}
|
||||
mux := http.NewServeMux()
|
||||
tuneRoutes(mux)
|
||||
post := func(knob, value string) int {
|
||||
body, _ := json.Marshal(map[string]string{"knob": knob, "value": value})
|
||||
rec := httptest.NewRecorder()
|
||||
mux.ServeHTTP(rec, httptest.NewRequest("POST", "/api/settings/claude-cache", bytes.NewReader(body)))
|
||||
return rec.Code
|
||||
}
|
||||
if c := post(agent.TuneSubCache, "5m"); c != 200 {
|
||||
t.Fatalf("5m for subagents: %d", c)
|
||||
}
|
||||
if c := post(agent.TuneCache, ""); c != 200 {
|
||||
t.Fatalf("default: %d", c)
|
||||
}
|
||||
got = claudeCacheState()
|
||||
if got[0].Value != "" || got[1].Value != "5m" {
|
||||
t.Fatalf("after the picks %+v; want default and 5m", got)
|
||||
}
|
||||
if b, _ := os.ReadFile(path); bytes.Contains(b, []byte(`"promptCacheTtl"`)) || !bytes.Contains(b, []byte(`"theme"`)) {
|
||||
t.Fatalf("default left the key, or lost the user's theme:\n%s", b)
|
||||
}
|
||||
if c := post(agent.TuneCache, "2h"); c == 200 {
|
||||
t.Fatal("took 2h")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// Claude Code's prompt cache in its own settings, beside its compaction
|
||||
// (Linka on Discord: Usage › Context's card offered no way to change a
|
||||
// lifetime that was already the cheapest). Under "Long conversations in
|
||||
// Claude Code" are the main conversation's and the subagents', each a
|
||||
// button opening the app's menu (no native select): Claude Code's default,
|
||||
// 5 min or 1 hour, posting settings/claude-cache. One a variable sets is
|
||||
// shown and can't be picked. Codex's sheet has none. Nothing scrolls, the
|
||||
// rows fit a narrow window. English and Chinese, Chromium and WebKit, wide
|
||||
// and narrow; no backend, the API is faked here.
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs/promises");
|
||||
const path = require("node:path");
|
||||
const { test } = require("node:test");
|
||||
const { chromium, webkit } = require("playwright");
|
||||
const { watchSettingsReads, agentRow, openAgentSettings, pickItem } = require("./reader.cjs");
|
||||
|
||||
const assets = path.resolve(__dirname, "../assets");
|
||||
|
||||
function serve(lang, posts) {
|
||||
let settings = {
|
||||
theme: "light", lang, tray: "panel", currency: "usd", version: "0.1.900", dir: "~/.config/magpie", gateway: "http://127.0.0.1:3425", proxyNow: "none", proxySource: "none", visionModels: [], imageGenModels: [], titleModels: [], workbuddyCheckins: [], lanURLs: [], redactWords: [], trayUsageEvery: 3, compactAt: 400000,
|
||||
claudeCache: [{ knob: "cache_ttl", value: "1h" }, { knob: "subagent_cache_ttl", value: "1h", locked: "CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL" }],
|
||||
};
|
||||
return async (route) => {
|
||||
const req = route.request(), url = new URL(req.url());
|
||||
const json = (data) => route.fulfill({ json: data });
|
||||
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:${JSON.stringify(lang)},theme:"light",web:true};` });
|
||||
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
|
||||
if (url.pathname === "/api/state") return json({ agents: [agentRow("claude", "Claude Code"), agentRow("codex", "Codex")], profiles: [], settings: { lang, theme: "light" } });
|
||||
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true } });
|
||||
if (url.pathname === "/api/groups") return json({ groups: [], models: [] });
|
||||
if (url.pathname === "/api/settings/claude-cache") {
|
||||
const body = req.postDataJSON();
|
||||
posts.push({ path: url.pathname, body });
|
||||
settings = { ...settings, claudeCache: settings.claudeCache.map((c) => c.knob === body.knob ? { knob: c.knob, ...(body.value ? { value: body.value } : {}) } : c) };
|
||||
return json(settings);
|
||||
}
|
||||
if (url.pathname === "/api/settings") {
|
||||
if (req.method() === "POST") posts.push({ path: url.pathname, body: req.postDataJSON() });
|
||||
return json(settings);
|
||||
}
|
||||
if (url.pathname === "/api/plugins") return json({ plugins: [] });
|
||||
if (url.pathname === "/api/usage/quotas") return json([]);
|
||||
if (url.pathname.startsWith("/api/")) return json({});
|
||||
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
|
||||
try {
|
||||
await route.fulfill({ body: await fs.readFile(file), contentType: { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)] });
|
||||
} catch {
|
||||
await route.fulfill({ status: 404, body: "" });
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const words = {
|
||||
en: { main: "Prompt cache · main conversation", sub: "Prompt cache · subagents", dflt: "Claude Code's default", m5: "5 min", h1: "1 hour", held: "CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL is set and comes first" },
|
||||
zh: { main: "提示缓存 · 主对话", sub: "提示缓存 · 子代理", dflt: "Claude Code 默认", m5: "5 分钟", h1: "1 小时", held: "已设置 CLAUDE_CODE_SUBAGENT_PROMPT_CACHE_TTL,它优先" },
|
||||
};
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
for (const lang of ["en", "zh"]) {
|
||||
for (const width of [900, 420]) {
|
||||
const w = words[lang];
|
||||
test(`${engine} ${lang} ${width}px: Claude Code's prompt cache is set beside its compaction`, async (t) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: process.env.PLAYWRIGHT_CHANNEL || "chromium" }));
|
||||
t.after(() => browser.close());
|
||||
const page = await (await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" })).newPage();
|
||||
page.setDefaultTimeout(5000);
|
||||
page.setDefaultNavigationTimeout(60000);
|
||||
const errors = [], posts = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await page.route("**/*", serve(lang, posts));
|
||||
await watchSettingsReads(page);
|
||||
await page.goto("http://magpie.test/?view=agents");
|
||||
await openAgentSettings(page, "claude");
|
||||
const main = page.locator('.ag-prefs .claude-cache[data-knob="cache_ttl"]');
|
||||
const sub = page.locator('.ag-prefs .claude-cache[data-knob="subagent_cache_ttl"]');
|
||||
await main.waitFor();
|
||||
// right under Claude Code's own Long conversations, main first
|
||||
assert.equal(await main.evaluate((r) => r.previousElementSibling?.classList.contains("agent-compact")), true);
|
||||
assert.equal(await sub.evaluate((r) => r.previousElementSibling?.dataset.knob), "cache_ttl");
|
||||
assert.equal(await main.locator(".name").textContent(), w.main);
|
||||
assert.equal(await sub.locator(".name").textContent(), w.sub);
|
||||
assert.equal(await page.locator(".ag-prefs select").count(), 0, "no native select");
|
||||
assert.equal(await main.locator(".sub").count(), 0, "no description");
|
||||
const btn = main.locator("button.sess-pick");
|
||||
assert.equal((await btn.textContent()).trim(), w.h1);
|
||||
const view = () => page.locator("#view-agents").evaluate((v) => v.scrollTop);
|
||||
// the reader wheels the rows into sight, as one does at 420px
|
||||
const sb0 = sub.locator("button.sess-pick");
|
||||
await page.mouse.move(width / 2, 400);
|
||||
for (let i = 0; i < 40; i++) {
|
||||
const r = await sb0.boundingBox();
|
||||
if (r && r.y > 120 && r.y + r.height < 700) break;
|
||||
await page.mouse.wheel(0, 120);
|
||||
await page.waitForTimeout(30);
|
||||
}
|
||||
await page.waitForTimeout(300);
|
||||
const seen = await sb0.boundingBox();
|
||||
assert(seen && seen.y + seen.height < 760, "the rows came into sight");
|
||||
const before = await view();
|
||||
// 5 min, then Claude Code's default, each from the app's menu
|
||||
await btn.click();
|
||||
const menu = page.locator(".proto-menu");
|
||||
await menu.waitFor();
|
||||
assert.deepEqual((await menu.locator(".pm-name").allTextContents()), [w.dflt, w.m5, w.h1]);
|
||||
await pickItem(page, menu.locator(".pm-item", { hasText: w.m5 }));
|
||||
await page.waitForFunction((v) => document.querySelector('.ag-prefs .claude-cache[data-knob="cache_ttl"] button')?.textContent.trim() === v, w.m5);
|
||||
assert.deepEqual(posts.map((p) => [p.path, p.body]), [["/api/settings/claude-cache", { knob: "cache_ttl", value: "5m" }]]);
|
||||
await btn.click();
|
||||
await menu.waitFor();
|
||||
await pickItem(page, menu.locator(".pm-item", { hasText: w.dflt }));
|
||||
await page.waitForFunction((v) => document.querySelector('.ag-prefs .claude-cache[data-knob="cache_ttl"] button')?.textContent.trim() === v, w.dflt);
|
||||
assert.deepEqual(posts.at(-1).body, { knob: "cache_ttl", value: "" });
|
||||
// the same pick again sends nothing
|
||||
await btn.click();
|
||||
await menu.waitFor();
|
||||
const sent = posts.length;
|
||||
await pickItem(page, menu.locator(".pm-item", { hasText: w.dflt }));
|
||||
await menu.waitFor({ state: "detached" });
|
||||
assert.equal(posts.length, sent);
|
||||
// the subagents' is a variable's: shown, said, not pickable
|
||||
const sb = sub.locator("button.sess-pick");
|
||||
assert.equal((await sb.textContent()).trim(), w.h1);
|
||||
assert(await sb.isDisabled());
|
||||
assert.equal(await sub.locator(".sub").textContent(), w.held);
|
||||
assert.equal(await view(), before, "a pick scrolled the page");
|
||||
assert(!posts.some((p) => p.path === "/api/settings"), "set on its own, not with the other preferences");
|
||||
for (const r of [main, sub]) {
|
||||
const over = await r.evaluate((x) => x.scrollWidth - x.clientWidth);
|
||||
assert(over <= 1, `the row overflows by ${over}px`);
|
||||
}
|
||||
// Codex's sheet has no Claude Code cache
|
||||
await page.keyboard.press("Escape");
|
||||
const codexLink = page.locator('.row.agent[data-id="codex"] .ag-link');
|
||||
await codexLink.click();
|
||||
await page.locator('.row.agent[data-id="codex"] .ag-prefs').waitFor();
|
||||
assert.equal(await page.locator('.row.agent[data-id="codex"] .claude-cache').count(), 0);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -175,9 +175,10 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
await page.goto("http://magpie.test/?view=agents");
|
||||
await openAgentSettings(page, "claude");
|
||||
await page.locator('.row.agent[data-id="claude"] .ag-prefs #fullContextRow').waitFor();
|
||||
// Long conversations, and Claude Code's own size under it
|
||||
// Long conversations, Claude Code's own size and its prompt cache under it
|
||||
await page.locator('.row.agent[data-id="claude"] .ag-prefs .agent-compact').waitFor();
|
||||
assert.equal(await page.locator(".ag-prefs .row.pref:not(.agent-compact)").count(), 1, "Claude Code's settings are Long conversations alone");
|
||||
assert.equal(await page.locator(".ag-prefs .row.pref:not(.agent-compact):not(.claude-cache)").count(), 1, "Claude Code's settings are Long conversations and its own");
|
||||
assert.equal(await page.locator(".ag-prefs .row.pref.claude-cache").count(), 2);
|
||||
assert.equal(await page.locator("#codexMemoriesRow").isHidden(), true);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
@@ -350,6 +350,21 @@ func tuneRoutes(mux *http.ServeMux) {
|
||||
s, _ := agent.TuneRead("", in.Agent, in.Knob, in.Model)
|
||||
writeJSON(rw, s)
|
||||
})
|
||||
// Claude Code's prompt cache picked in its settings: "5m", "1h", or ""
|
||||
// for Claude Code's own default (agent.ClaudeCacheSet)
|
||||
mux.HandleFunc("POST /api/settings/claude-cache", func(rw http.ResponseWriter, r *http.Request) {
|
||||
var in struct{ Knob, Value string }
|
||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
if err := agent.ClaudeCacheSet("", in.Knob, in.Value); err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
tuneForget()
|
||||
writeJSON(rw, settingsState())
|
||||
})
|
||||
mux.HandleFunc("POST /api/tune/undo", func(rw http.ResponseWriter, r *http.Request) {
|
||||
var in change
|
||||
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
|
||||
@@ -496,3 +511,24 @@ func tuneCallsSince(since time.Time) map[string][]tune.Call {
|
||||
}
|
||||
return by
|
||||
}
|
||||
|
||||
// claudeCacheJSON is one of Claude Code's prompt-cache lifetimes: its
|
||||
// knob (agent.TuneCache, agent.TuneSubCache), the value it runs at ("" for
|
||||
// Claude Code's own default), and the variable that sets it, when one does.
|
||||
type claudeCacheJSON struct {
|
||||
Knob string `json:"knob"`
|
||||
Value string `json:"value,omitempty"`
|
||||
Locked string `json:"locked,omitempty"`
|
||||
}
|
||||
|
||||
func claudeCacheState() []claudeCacheJSON {
|
||||
var out []claudeCacheJSON
|
||||
for _, knob := range []string{agent.TuneCache, agent.TuneSubCache} {
|
||||
s, err := agent.TuneRead("", "claude", knob, "")
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
out = append(out, claudeCacheJSON{Knob: knob, Value: s.Value, Locked: s.Locked})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user