diff --git a/docs/subsystems/claude-subscription-bridge.md b/docs/subsystems/claude-subscription-bridge.md index 3c95f1aa3..4a609e75b 100644 --- a/docs/subsystems/claude-subscription-bridge.md +++ b/docs/subsystems/claude-subscription-bridge.md @@ -702,7 +702,14 @@ mark in the first message is as long (`Request.runMark`), since Anthropic refuses a 1h mark after a 5m one. A session a run goes on from keeps the lifetime it started with (`cachePrefix.ttl`; one saved before it was kept is an hour's). Until 11-07 every run was given 1h whatever the pick -(linkaww). `TestClaudeRunKeepsTheUsersCacheTTL`. +(linkaww). `TestClaudeRunKeepsTheUsersCacheTTL`. Every `savedSession` +carries its run's `cachePrefix`: the shelf's (`shelve`), and the branches +cut from a live run's session for a fork's turn (`branch`), a turn sent +again while its run is busy (`retryBranch`) and the turn after the +interactive mode's side question (`branchAt`). Up to v0.1.3266 the three +branches carried none, and their runs went back to an hour under a 5m +pick (linkaww); `everyRunKept5m` in the fork, busy-retry and side +question tests. A new run (and one started from a transcript, `replaySession`) picks its lifetime with `runTTLFor`: `FORCE_PROMPT_CACHING_5M` on this computer diff --git a/internal/gateway/claude_prompt_cache_test.go b/internal/gateway/claude_prompt_cache_test.go index d0312ae48..75765ab5c 100644 --- a/internal/gateway/claude_prompt_cache_test.go +++ b/internal/gateway/claude_prompt_cache_test.go @@ -301,3 +301,48 @@ func mustRender(t *testing.T, req *Request) []map[string]any { } return blocks } + +// pickFiveMinutes sets the test's Claude Code (CLAUDE_CONFIG_DIR) to a 5m +// prompt cache for its main conversation, as the Agents page writes it. +func pickFiveMinutes(t *testing.T) { + t.Helper() + dir := os.Getenv("CLAUDE_CONFIG_DIR") + if dir == "" { + t.Fatal("no CLAUDE_CONFIG_DIR") + } + if err := os.MkdirAll(dir, 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "settings.json"), []byte(`{"promptCacheTtl":"5m"}`), 0o600); err != nil { + t.Fatal(err) + } +} + +// everyRunKept5m checks that each run whose log is in logs (a stand-in +// Claude Code's, "ttl " on a line) and whose +// arguments resume a session was given a 5m cache, and that there was +// one. A run that goes on from a branch of a session keeps its parent's +// lifetime: the branches the side question, a fork and a turn sent again +// make were given none, and an hour came back under a 5m pick (linkaww). +func everyRunKept5m(t *testing.T, logs string) { + t.Helper() + entries, _ := os.ReadDir(logs) + resumed := 0 + for _, e := range entries { + if strings.Contains(e.Name(), ".") { + continue + } + b, _ := os.ReadFile(filepath.Join(logs, e.Name())) + log := string(b) + if !strings.Contains(log, "--resume ") { + continue + } + resumed++ + if !strings.Contains(log, "\nttl 5m\n") { + t.Errorf("a branch's run, want a 5m cache as its parent's:\n%.400s", log) + } + } + if resumed == 0 { + t.Error("no run went on from a session") + } +} diff --git a/internal/gateway/claude_subscription.go b/internal/gateway/claude_subscription.go index 7b1c0188f..f28abe4cb 100644 --- a/internal/gateway/claude_subscription.go +++ b/internal/gateway/claude_subscription.go @@ -2471,6 +2471,10 @@ type savedSession struct { // run that resumes it is given them so again appended bool + // cachePrefix is the marks, and the cache lifetime, of the run whose + // session this is: the run that goes on from it keeps both. Every + // savedSession is given its run's, a branch's too: one without it ran + // an hour's cache under a 5m pick (linkaww) cachePrefix cachePrefix mu sync.Mutex @@ -2698,7 +2702,7 @@ func (b *subscriptionBridge) branch(req *Request, owner string) *savedSession { at, seq, said = l.uuid, l.seq, l.told } } - sid, sessions := run.sessionID, slices.Clone(run.sessions) + sid, sessions, prefix := run.sessionID, slices.Clone(run.sessions), run.cachePrefix usable := !run.closed && !run.rewound && run.lean == req.leanPrompt && !run.clientMarks && (run.tui || !wantTUI(req)) run.mu.Unlock() if at == "" { @@ -2710,7 +2714,7 @@ func (b *subscriptionBridge) branch(req *Request, owner string) *savedSession { if !usable || sid == "" || len(sessions) == 0 || said != told { return nil } - return &savedSession{session: sid, sessions: sessions, owner: owner, at: time.Now(), since: msgs[i:], cut: at, tui: run.tui, appended: run.appended, gone: true} + return &savedSession{session: sid, sessions: sessions, owner: owner, at: time.Now(), since: msgs[i:], cut: at, tui: run.tui, appended: run.appended, cachePrefix: prefix, gone: true} } return nil } @@ -2756,7 +2760,7 @@ func (b *subscriptionBridge) retryBranch(req *Request, owner string) *savedSessi // whose reply the client has is no retry of it busy := !run.closed && run.rewinding == nil && !run.rewound && run.lean == req.leanPrompt && !run.clientMarks && (run.tui || !wantTUI(req)) && run.told == want - sid, sessions, backLine, backMsg, appended, tui := run.sessionID, slices.Clone(run.sessions), run.backLine, run.backMsg, run.appended, run.tui + sid, sessions, backLine, backMsg, appended, tui, prefix := run.sessionID, slices.Clone(run.sessions), run.backLine, run.backMsg, run.appended, run.tui, run.cachePrefix started := run.started run.mu.Unlock() if !busy || sid == "" || backLine == "" && backMsg == "" || len(sessions) == 0 { @@ -2773,7 +2777,7 @@ func (b *subscriptionBridge) retryBranch(req *Request, owner string) *savedSessi if found != nil { found.discard() // a newer run's copy is taken: the older one's goes } - found, at = &savedSession{session: cut, sessions: sessions, owner: owner, at: time.Now(), since: since, tui: tui, appended: appended}, started + found, at = &savedSession{session: cut, sessions: sessions, owner: owner, at: time.Now(), since: since, tui: tui, appended: appended, cachePrefix: prefix}, started } if found == nil { return nil @@ -2813,7 +2817,7 @@ func (r *subscriptionRun) branchAt(at, msg, owner string, since []Message) *save return nil } log.Printf("claude: the conversation's next turn goes on in a branch of its interactive run's session, cut before the side question it answered since") - return &savedSession{session: cut, sessions: sessions, owner: owner, at: time.Now(), since: since, tui: true, appended: r.appended} + return &savedSession{session: cut, sessions: sessions, owner: owner, at: time.Now(), since: since, tui: true, appended: r.appended, cachePrefix: r.cachePrefix} } // cutWait is how long cutSession waits for the line it cuts after to be diff --git a/internal/gateway/claude_subscription_busy_retry_test.go b/internal/gateway/claude_subscription_busy_retry_test.go index 215fddea9..838ff2bcd 100644 --- a/internal/gateway/claude_subscription_busy_retry_test.go +++ b/internal/gateway/claude_subscription_busy_retry_test.go @@ -33,6 +33,7 @@ func busyRetryClaude(t *testing.T) (string, string) { if [ "$1" = auth ]; then echo '{"loggedIn":true,"authMethod":"claude.ai","apiProvider":"firstParty","email":"u@example.com","subscriptionType":"max"}'; exit 0; fi log=` + logs + `/$$ echo "args $*" > $log +echo "ttl ${CLAUDE_CODE_PROMPT_CACHE_TTL-unset}" >> $log echo "mode ${FAKE_TUI:-print}" >> $log echo "args $*" >> ` + told + ` sid=lead$$; resumed=; prev= @@ -169,6 +170,7 @@ func TestClaudeTurnSentAgainWhileItsRunIsBusyBranchesOffItsSession(t *testing.T) func busyRetryBranches(t *testing.T, mode string) { h := newBusyRetryHarness(t, mode) + pickFiveMinutes(t) logs := keepLog(t) first := h.ask(`[` + rmsg("user", "the conversation so far, told at length. fix the bug") + `]`) if !strings.Contains(first, "turn 1") { @@ -238,6 +240,8 @@ func busyRetryBranches(t *testing.T, mode string) { if strings.Contains(logs.String(), "a new Claude Code is told the whole conversation: 3 messages") { t.Errorf("the retry told a new Claude Code the whole conversation:\n%s", logs.String()) } + // the retry's branch keeps the 5m cache the busy run had + everyRunKept5m(t, h.logs) } // A turn that goes on past the one a busy run answers is no retry of it: diff --git a/internal/gateway/claude_subscription_fork_test.go b/internal/gateway/claude_subscription_fork_test.go index 9662abe51..8b67e3290 100644 --- a/internal/gateway/claude_subscription_fork_test.go +++ b/internal/gateway/claude_subscription_fork_test.go @@ -239,6 +239,7 @@ func forkBranches(t *testing.T, mode string) { config := filepath.Join(home, ".claude") t.Setenv("CLAUDE_CONFIG_DIR", config) os.MkdirAll(config, 0o755) + pickFiveMinutes(t) os.WriteFile(filepath.Join(config, ".credentials.json"), mustJSON(map[string]any{"claudeAiOauth": map[string]any{ "accessToken": "tok-lead", "refreshToken": "r-lead", "expiresAt": time.Now().Add(24 * time.Hour).UnixMilli(), "subscriptionType": "max"}}), 0o600) os.WriteFile(filepath.Join(home, ".claude.json"), mustJSON(map[string]any{ @@ -259,6 +260,7 @@ func forkBranches(t *testing.T, mode string) { if [ "$1" = auth ]; then echo '{"loggedIn":true,"authMethod":"claude.ai","apiProvider":"firstParty","email":"lead@example.com","subscriptionType":"max"}'; exit 0; fi log=`+logs+`/$$ echo "args $*" > $log +echo "ttl ${CLAUDE_CODE_PROMPT_CACHE_TTL-unset}" >> $log echo "mode ${FAKE_TUI:-print}" >> $log cb=$(cat "$(printf '%s\n' "$@" | grep -o '"claude-mcp-helper","[^"]*"' | head -1 | sed 's/.*","//; s/"$//')") sid=lead$$; resumed=; at=; fork=; prev= @@ -424,4 +426,6 @@ FAKE_TUI=interactive exec "$claude" "$@" if files, _ := filepath.Glob(filepath.Join(config, "projects", "*", "lead"+pid+".jsonl")); len(files) == 0 { t.Error("the lead's session file is gone") } + // the fork's branch keeps the 5m cache its lead had + everyRunKept5m(t, logs) } diff --git a/internal/gateway/claude_subscription_prefix_test.go b/internal/gateway/claude_subscription_prefix_test.go index 713888224..326f1957d 100644 --- a/internal/gateway/claude_subscription_prefix_test.go +++ b/internal/gateway/claude_subscription_prefix_test.go @@ -63,6 +63,7 @@ func newPrefixHarness(t *testing.T) *prefixHarness { if [ "$1" = auth ]; then echo '{"loggedIn":true,"authMethod":"claude.ai","apiProvider":"firstParty","email":"lead@example.com","subscriptionType":"max"}'; exit 0; fi log=`+logs+`/$$ echo "args $*" > $log +echo "ttl ${CLAUDE_CODE_PROMPT_CACHE_TTL-unset}" >> $log helper=$(printf '%s\n' "$@" | grep -o '"claude-mcp-helper","[^"]*","[^"]*"' | head -1) cb=$(cat "$(printf '%s' "$helper" | sed 's/^"claude-mcp-helper","//; s/",".*//')") cp "$(printf '%s' "$helper" | sed 's/.*","//; s/"$//')" `+logs+`/$$.tools @@ -327,6 +328,7 @@ exec "$claude" "$@" func TestClaudeInteractiveSideQuestionBranchesBeforeIt(t *testing.T) { h := newPrefixHarness(t) h.interactive() + pickFiveMinutes(t) tools := `"tools":` + prefixTools + `,` first, _ := h.ask(tools, `[`+rmsg("user", "fix the bug")+`]`) pid := answerPID(t, first) @@ -354,6 +356,8 @@ func TestClaudeInteractiveSideQuestionBranchesBeforeIt(t *testing.T) { if got, _ := h.ask(tools, `[`+conv+`,`+rmsg("user", "push it")+`]`); got != "pid "+branch+" had 4 turn 2" { t.Fatalf("the turn after: %q", got) } + // the branch keeps the 5m cache its run had (everyRunKept5m) + everyRunKept5m(t, h.logs) } // sleepy_shibe (magpie 0.1.2906, Claude Code 2.1.318): the interactive