diff --git a/docs/subsystems/claude-subscription-bridge.md b/docs/subsystems/claude-subscription-bridge.md index ddf441662..addb6e20b 100644 --- a/docs/subsystems/claude-subscription-bridge.md +++ b/docs/subsystems/claude-subscription-bridge.md @@ -1630,7 +1630,9 @@ there as the user's own sessions do; a sweep can't tell them apart. - Its session: `/projects//.jsonl`, for `--resume` (`claudeSessions`). It is removed when the run ends unless - shelved, and when a saved session is discarded (`removeSession`). + shelved or kept for a branch ([A run that ended during a + turn](#a-run-that-ended-during-a-turn-6528)), and when a saved session + is discarded (`removeSession`). `sweepSessions` removes those a stopped gateway left in magpie's own work folder's project, once older than `idleLongest`; a caller's folder is never swept (`clientWorkDir`). @@ -1714,6 +1716,59 @@ run is told the whole conversation as before. `TestClaudeCutSessionCopiesAsFarAsTheLine` and `TestClaudeForkBranchesOffTheLeadsSession` holds it. +### A run that ended during a turn (#6528) + +A run can end in a turn the client still goes on with. It waited on the +client's AskUserQuestion past `runTimeout` ("it waited as long as it +may"), or its client went away mid-reply in a turn that can't be taken +back (`letGo`: the interactive mode, or calls in the client's hands). +Before, its session went with it (`removeRun`), and what came after found +no run and was told whole to a new Claude Code. recih saw an answer given +two minutes after the timeout write 118K tokens to the cache, and a +tunnel drop's two retried sub-agents and their delayed AgentSummary write +305K. + +Now `removeRun` keeps such a run's session for a branch to be cut from +(`keepEnded`, [`claude_ended.go`](../../internal/gateway/claude_ended.go)), +in the same `b.mu` section that takes it out of `runs`, so no request +between finds it in neither. The run object is kept as it ended: its +session id and folders, the call lines (`lines`, each with the +conversation its reply answered), `told`, `convKey`, `backLine` and +`backMsg`, and its mode, owner and prompt flags. Kept: a session on disk +with a call line or a turn start to cut at (`keepable`). Not kept: a run +on the shelf (its file is the shelf's), one whose turn was taken back +(`rewound`), one with the client's own cache marks, one whose account was +handed over to Claude Code, and every run as the gateway stops +(`abortAll` sets `stopping` and removes the kept ones; they are not +written to `claude-shelf.json`, and `sweepSessions` takes what a crash +left). Each is kept `endedLongest` (`idleLongest`, the cache's hour), and +`endedMost` (16) at most, the oldest let go first; letting one go removes +its files. + +`branch` and `retryBranch` look at the kept runs after the live ones, the +one that ended last first, with the same rules except that a kept run is +closed. Tool results that come after (the late answer, or a retry of a +continuation) are cut after the call's line and told the results; a +delayed AgentSummary on the history before them is cut before the calls +(`cutBefore`); a turn sent again after its run ended answering it (a +retry after a dropped connection) is cut before the turn +(`backLine`/`backMsg`) and told the turn. A kept session is never taken +or written: each branch cuts a copy of its own, so the AgentSummary after +a recovery still branches. The log says the run ended, when, and why +("the run this conversation goes on from ended 2m0s ago (it waited as long +as it may); its session, kept since, is branched"). + +Claude Code 2.1.316 writes a reply's text and `tool_use` lines when the +reply has streamed, before the tool runs, in both modes; killed (SIGTERM) +while an MCP call is held, it adds only `cost-state` lines, no result and +no interrupt marker (tried on 11-13 with a mock Anthropic and an MCP tool +that never answers). So the kept file has the call line, and a cut after +it leaves the reply's call open for the results the branch is told. No +tool is run again: the branch is told the client's results. +`TestClaudeAnswerAfterTheRunEndedBranchesOffItsKeptSession`, +`TestClaudeEndedRunsSessionsAreBounded`, +`TestClaudeTurnSentAgainAfterItsRunEndedBranchesOffItsSession`. + ## The user's words beside tool results (#872, #1878) A user message can hold tool results and, after them, text blocks of the @@ -1974,6 +2029,7 @@ go test -tags nogui ./internal/gateway/ -run '^TestClaudeRunsNamesEachProcess$' go test -tags nogui ./internal/settings/ -run '^TestClaudeRunsMostIsMachineLocal$' -count=1 go test -tags nogui ./internal/gateway/ -run 'ClaudeSubscriptionRunsTheDownloaded|ClaudeSubscriptionWithoutClaudeCode|ClaudeRewritten|LostMedia|ImagesTakenOut|RunLetGoWhenTheClientRewrote|ClaudeSessionTempFiles|ClaudeLetGo|ClaudeSessionFiles|ClaudeOldSessions|ClaudeSubscriptionReplySaysTheAllowance|ClaudeAllowanceHeaders|ClaudeForksAnsweringTheLeadsCalls|ClaudeTurnGivenUpOn|ClaudeToolResultsGivenUpOn|ClaudePromptMarksEarlierTurns|ClaudeHistoryCachedAcrossNewRuns|ClaudeUnloadableSession|ClaudeEndedRunSaysWhy|ClaudeIdle|ClaudeSideQuestion|ClaudeInteractiveSideQuestion|ClaudeCutSession|ClaudeForkBranches|ClaudeToolChoiceNone|ClaudeAside|ClaudeNoRunSaysWhy|ClaudeToolResultsNoRunSaysWhy|ClaudePromptToldUserText|ClaudePromptKeepsInstructions|ClaudeToolResultsGoOnWithTheUsersWords|ClaudeToolResultsKeepInstructions|ToolResultKeepsUserTextSentMidTurn|ClaudeTextToolCalls|ClaudeTextCallsHoldsOnlyTheLine|ClaudePromptSaysPastCallsAreARecord' -count=1 go test -tags nogui ./internal/gateway/ -run 'TestClaudeTaskNotification|TestWithTaskNotices|TestClaudeTurnToldTheTaskNotification' -count=1 +go test -tags nogui ./internal/gateway/ -run 'TestClaudeAnswerAfterTheRunEnded|TestClaudeEndedRuns|TestClaudeTurnSentAgain|TestClaudeBranchFor' -count=1 ``` `claude_rewritten_test.go` has a case for each relaxation and one for each diff --git a/internal/gateway/claude_ended.go b/internal/gateway/claude_ended.go new file mode 100644 index 000000000..41e008c55 --- /dev/null +++ b/internal/gateway/claude_ended.go @@ -0,0 +1,119 @@ +package gateway + +import ( + "time" +) + +// A run that ends during a turn keeps its session on disk a while after +// (#6528): the run waited on the client's AskUserQuestion past runTimeout, +// or its client went away mid-reply and the turn couldn't be taken back +// (letGo). Its Claude Code is gone, and the results or the retry that come +// after found no run: each was told the whole conversation by a new Claude +// Code, writing all of it to the cache again (recih: 118K for an answer +// given two minutes late, 305K for two retried sub-agents and their delayed +// AgentSummary). The session as Claude Code wrote it, with where each call +// of the client's tools is in it (lines) and the conversation each reply +// answered, is what a branch is cut from (branch, retryBranch) as from a +// live run's: each takes a copy of its own, so the file is never written +// again, and a later request on the same history (the AgentSummary that +// comes after the retry) branches off it too. +// +// endedMost is how many ended runs are kept so; endedLongest how long each +// is, as long as Anthropic's cache keeps what it asked (claudeCacheTTL). +// The gateway stopping keeps none (abortAll), and its files are swept at +// the next start (sweepSessions). +const endedMost = 16 + +var endedLongest = idleLongest + +// endedRun is when an ended run was kept, and the timer that lets it go. +type endedRun struct { + at time.Time + timer *time.Timer +} + +// keepable says the session of a run that just ended can be kept for a +// branch to be cut from: a session on disk with a line or a turn to cut +// at, Claude Code's own record of its conversation — not one on the shelf +// already, one whose turn was taken back (rewound, which the file may not +// say), or one the client marks its own cache in. +func (r *subscriptionRun) keepable() bool { + r.mu.Lock() + defer r.mu.Unlock() + return r.sessionID != "" && len(r.sessions) > 0 && !r.shelved && !r.clientMarks && !r.rewound && + (len(r.lines) > 0 || r.backLine != "" || r.backMsg != "") +} + +// keepEnded keeps the session of a run that just ended (keepable) for a +// branch to be cut from, and says whether it did, with the runs let go +// for it past endedMost, whose files the caller removes (b.mu held): not +// as the gateway stops, nor one whose account was handed over to Claude +// Code itself. +func (b *subscriptionBridge) keepEnded(run *subscriptionRun) (bool, []*subscriptionRun) { + if b.stopping || run.handed { + return false, nil + } + if b.ended == nil { + b.ended = map[*subscriptionRun]endedRun{} + } + if e, ok := b.ended[run]; ok { // removed again: kept from now + e.timer.Stop() + delete(b.ended, run) + } + var drop []*subscriptionRun + for len(b.ended) >= endedMost { + var oldest *subscriptionRun + for r, e := range b.ended { + if oldest == nil || e.at.Before(b.ended[oldest].at) { + oldest = r + } + } + b.ended[oldest].timer.Stop() + delete(b.ended, oldest) + drop = append(drop, oldest) + } + b.ended[run] = endedRun{at: time.Now(), timer: time.AfterFunc(endedLongest, func() { b.dropEnded(run) })} + return true, drop +} + +// dropEnded lets an ended run's session go, its time over. +func (b *subscriptionBridge) dropEnded(run *subscriptionRun) { + b.mu.Lock() + e, ok := b.ended[run] + delete(b.ended, run) + b.mu.Unlock() + if ok { + e.timer.Stop() + run.removeFiles() + } +} + +// dropAllEnded lets every ended run's session go, as the gateway stops. +func (b *subscriptionBridge) dropAllEnded() { + b.mu.Lock() + b.stopping = true + ended := b.ended + b.ended = nil + b.mu.Unlock() + for run, e := range ended { + e.timer.Stop() + run.removeFiles() + } +} + +// endedRuns is the ended runs kept, with when each ended (b.mu held). +func (b *subscriptionBridge) endedRuns() map[*subscriptionRun]time.Time { + m := make(map[*subscriptionRun]time.Time, len(b.ended)) + for r, e := range b.ended { + m[r] = e.at + } + return m +} + +// removeFiles removes the run's session. +func (r *subscriptionRun) removeFiles() { + r.mu.Lock() + sid, sessions := r.sessionID, r.sessions + r.mu.Unlock() + removeSession(sessions, sid) +} diff --git a/internal/gateway/claude_ended_test.go b/internal/gateway/claude_ended_test.go new file mode 100644 index 000000000..8af016af2 --- /dev/null +++ b/internal/gateway/claude_ended_test.go @@ -0,0 +1,296 @@ +package gateway + +import ( + "context" + "encoding/json" + "fmt" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// endedFixture is a run of the bridge's that parked on the client's +// AskUserQuestion, its session as Claude Code 2.1.316 leaves it when it is +// killed there: the reply's words, then its call, and no result (a real +// run's file, SIGTERMed while an MCP call was held, gained only cost-state +// lines). +type endedFixture struct { + b *subscriptionBridge + run *subscriptionRun + dir string + sid string + own string + history []Message + reply Message +} + +func newEndedFixture(t *testing.T, b *subscriptionBridge, token string) *endedFixture { + t.Helper() + dir := t.TempDir() + sid := "lead-" + token + lines := []string{ + `{"type":"user","uuid":"u1","sessionId":"` + sid + `"}`, + `{"type":"assistant","uuid":"a-words","sessionId":"` + sid + `","message":{"id":"msg_1","content":[{"type":"text","text":"I will ask."}]}}`, + `{"type":"assistant","uuid":"a-call","sessionId":"` + sid + `","message":{"id":"msg_1","content":[{"type":"tool_use","id":"toolu_ask","name":"mcp__magpie__AskUserQuestion"}]}}`, + `{"type":"cost-state","sessionId":"` + sid + `"}`, + } + if err := os.WriteFile(filepath.Join(dir, sid+".jsonl"), []byte(strings.Join(lines, "\n")+"\n"), 0o600); err != nil { + t.Fatal(err) + } + user := Message{Role: "user", Parts: []Part{{Kind: Text, Text: "the conversation so far, told at length: " + token}}} + reply := Message{Role: "assistant", Parts: []Part{{Kind: Text, Text: "I will ask."}, {Kind: ToolCall, ID: "toolu_ask", Name: "AskUserQuestion", Args: json.RawMessage(`{}`)}}} + own := "claude\x00u" + run := &subscriptionRun{bridge: b, token: token, sessionID: sid, sessions: []string{dir}, tui: true} + run.owner.Store(&own) + run.lines = map[string]callLine{"toolu_ask": {uuid: "a-call", seq: 1, told: historyKey([]Message{user})}} + b.mu.Lock() + b.runs[token] = run + b.mu.Unlock() + return &endedFixture{b: b, run: run, dir: dir, sid: sid, own: own, history: []Message{user}, reply: reply} +} + +// answered is the client's request with the question's answer. +func (f *endedFixture) answered() *Request { + return &Request{Messages: []Message{f.history[0], f.reply, {Role: "user", Parts: []Part{{Kind: ToolResult, CallID: "toolu_ask", Text: "Use the second option"}}}}} +} + +// summary is Claude Code's AgentSummary of the conversation, which leaves +// out the reply's call, its result not in yet when it was asked. +func (f *endedFixture) summary() *Request { + words := Message{Role: "assistant", Parts: []Part{{Kind: Text, Text: "I will ask."}}} + return &Request{Messages: []Message{f.history[0], words, {Role: "user", Parts: []Part{{Kind: Text, Text: "Describe your most recent action in 3-5 words"}}}}} +} + +func (f *endedFixture) saved() bool { + _, err := os.Stat(filepath.Join(f.dir, f.sid+".jsonl")) + return err == nil +} + +// recih (#6528, case 1): the run waited on the client's AskUserQuestion +// past runTimeout and was let go ("it waited as long as it may"); the +// answer came two minutes later. Its session went with it, and a new +// Claude Code was told all 95 messages, 118K tokens written to the cache. +// The session is kept, with where the call is in it, and the answer goes +// on in a branch cut after the call, told only the result. A delayed +// AgentSummary on the history before the answer branches off it too: the +// kept session is never taken, each branch is a copy of its own. +func TestClaudeAnswerAfterTheRunEndedBranchesOffItsKeptSession(t *testing.T) { + logs := keepLog(t) + b := newSubscriptionBridge() + t.Cleanup(b.abortAll) + f := newEndedFixture(t, b, "r1") + + f.run.abortFor("it waited as long as it may") // runTimeout's own call + b.mu.Lock() + left := len(b.runs) + b.mu.Unlock() + if left != 0 { + t.Fatalf("%d runs left, want the ended run gone", left) + } + if !f.saved() { + t.Fatal("the ended run's session was removed with it") + } + + got, why := b.branch(f.answered(), f.own) + if got == nil { + t.Fatalf("the answer found no branch: %s", why) + } + if got.cut != "a-call" || got.cutBefore || len(got.since) != 1 || got.since[0].Parts[0].Kind != ToolResult { + t.Fatalf("branch = cut %q before %v, %d messages told; want cut after a-call, told the result only", got.cut, got.cutBefore, len(got.since)) + } + id, err := cutSession(got.sessions, got.session, got.cut) + if err != nil { + t.Fatal(err) + } + copied, _ := os.ReadFile(filepath.Join(f.dir, id+".jsonl")) + if s := string(copied); !strings.Contains(s, `"uuid":"a-call"`) || strings.Contains(s, "cost-state") || !strings.Contains(s, `"sessionId":"`+id+`"`) { + t.Fatalf("the branch is:\n%s", s) + } + if !strings.Contains(logs.String(), "it waited as long as it may") || !strings.Contains(logs.String(), "kept since, is branched") { + t.Errorf("the log doesn't say the branch is of an ended run's session:\n%s", logs.String()) + } + + // the delayed AgentSummary, on the history before the answer + sum, why := b.branch(f.summary(), f.own) + if sum == nil { + t.Fatalf("the delayed summary found no branch: %s", why) + } + if !sum.cutBefore || sum.cut != "a-call" { + t.Fatalf("summary branch = cut %q before %v, want before a-call", sum.cut, sum.cutBefore) + } + if !f.saved() { + t.Fatal("a branch took the kept session") + } + + // another account's request is not branched off it + if got, _ := b.branch(f.answered(), "claude\x00v"); got != nil { + t.Fatal("another account's request was branched off the kept session") + } +} + +// What is kept is bounded: each ended run's session goes after +// endedLongest, the oldest past endedMost, and every one as the gateway +// stops; a request that comes after finds none. +func TestClaudeEndedRunsSessionsAreBounded(t *testing.T) { + t.Run("time", func(t *testing.T) { + was := endedLongest + endedLongest = 50 * time.Millisecond + t.Cleanup(func() { endedLongest = was }) + b := newSubscriptionBridge() + t.Cleanup(b.abortAll) + f := newEndedFixture(t, b, "r1") + f.run.abortFor("it waited as long as it may") + deadline := time.Now().Add(5 * time.Second) + for f.saved() { + if time.Now().After(deadline) { + t.Fatal("the ended run's session outlived endedLongest") + } + time.Sleep(10 * time.Millisecond) + } + if got, _ := b.branch(f.answered(), f.own); got != nil { + t.Fatal("a branch of a session let go") + } + }) + t.Run("count", func(t *testing.T) { + b := newSubscriptionBridge() + t.Cleanup(b.abortAll) + var fs []*endedFixture + for i := range endedMost + 1 { + f := newEndedFixture(t, b, fmt.Sprintf("r%d", i)) + f.run.abortFor("the client went away during a turn it can't take back") + fs = append(fs, f) + time.Sleep(time.Millisecond) // each ends after the one before + } + if fs[0].saved() { + t.Fatal("the oldest session was kept past endedMost") + } + for _, f := range fs[1:] { + if !f.saved() { + t.Fatalf("session %s went, want the newest %d kept", f.sid, endedMost) + } + } + b.mu.Lock() + n := len(b.ended) + b.mu.Unlock() + if n != endedMost { + t.Fatalf("%d kept, want %d", n, endedMost) + } + }) + t.Run("stop", func(t *testing.T) { + b := newSubscriptionBridge() + f := newEndedFixture(t, b, "r1") + f.run.abortFor("it waited as long as it may") + live := newEndedFixture(t, b, "r2") + b.abortAll() + if f.saved() || live.saved() { + t.Fatalf("sessions left as the gateway stopped: ended %v, live %v", f.saved(), live.saved()) + } + }) + t.Run("unkept", func(t *testing.T) { + b := newSubscriptionBridge() + t.Cleanup(b.abortAll) + // a run whose turn was taken back, or the client marks its own + // cache in, has nothing a branch could be cut from + f := newEndedFixture(t, b, "r1") + f.run.rewound = true + f.run.abortFor("x") + g := newEndedFixture(t, b, "r2") + g.run.clientMarks = true + g.run.abortFor("x") + if f.saved() || g.saved() { + t.Fatalf("kept: rewound %v, client's marks %v", f.saved(), g.saved()) + } + }) +} + +// recih (#6528, case 2): a tunnel dropped mid-reply, magpie heard the +// client go away and ended its interactive run (letGo: the interactive +// mode can't be taken back), and the client's own magpie retried the +// request. The retry was told the whole conversation by a new Claude Code +// (125K written); it goes on in a branch of the ended run's session, cut +// before the turn, told only the turn. +func TestClaudeTurnSentAgainAfterItsRunEndedBranchesOffItsSession(t *testing.T) { + h := newBusyRetryHarness(t, "interactive") + 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") { + t.Fatalf("the first turn: %q", first) + } + conv := `[` + rmsg("user", "the conversation so far, told at length. fix the bug") + `,` + rmsg("assistant", first) + `,` + rmsg("user", "and run the tests") + `]` + + // the turn is sent, its run holds mid-reply, and the client goes away + firstTold := h.heard() + body := h.body(conv) + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + go func() { + defer close(done) + var u Usage + h.s.serveClaudeSubscription(httptest.NewRecorder(), httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body)).WithContext(ctx), provider.Anthropic, h.p, "claude-sonnet-5", []byte(body), &u) + }() + t.Cleanup(func() { + cancel() + h.s.subscription.abortAll() + <-done + }) + deadline := time.Now().Add(10 * time.Second) + for !strings.Contains(h.read(), "and run the tests") || h.heard() == firstTold { + if time.Now().After(deadline) { + t.Fatalf("the run was never told the turn:\n%s\nmagpie log:\n%s", h.read(), logs.String()) + } + time.Sleep(10 * time.Millisecond) + } + cancel() + <-done + // letGo ends the run once the request returned + for { + h.s.subscription.mu.Lock() + n := len(h.s.subscription.runs) + h.s.subscription.mu.Unlock() + if n == 0 { + break + } + if time.Now().After(deadline) { + t.Fatalf("the run given up on was never ended:\n%s", logs.String()) + } + time.Sleep(10 * time.Millisecond) + } + + // the client's magpie sends it again + if again := h.ask(conv); again == "" { + t.Fatal("the retry was answered nothing") + } + branch, lead := 0, 0 + for name, told := range h.toldBy() { + if !strings.Contains(told, "--resume") { + lead++ + continue + } + branch++ + if strings.Contains(told, "the conversation so far") { + t.Errorf("the retry's run %s was told the whole conversation:\n%.600s", name, told) + } + if !strings.Contains(told, "and run the tests") { + t.Errorf("the retry's run %s was not told the turn:\n%.600s", name, told) + } + if i := strings.Index(told, "--resume "); strings.HasPrefix(told[i+9:], "lead") { + t.Errorf("the retry's run resumed the ended run's own session, want a copy") + } + } + if branch != 1 || lead != 1 { + t.Fatalf("%d runs branched, %d started anew, want one of each; magpie log:\n%s", branch, lead, logs.String()) + } + if strings.Contains(logs.String(), "from a transcript of it") { + t.Errorf("the retry's run was told the conversation from a transcript:\n%s", logs.String()) + } + if want := "after its run ended answering it"; !strings.Contains(logs.String(), want) { + t.Errorf("the log says:\n%s", logs.String()) + } + everyRunKept5m(t, h.logs) +} diff --git a/internal/gateway/claude_subscription.go b/internal/gateway/claude_subscription.go index dd963d82a..2de3549a9 100644 --- a/internal/gateway/claude_subscription.go +++ b/internal/gateway/claude_subscription.go @@ -88,6 +88,11 @@ type subscriptionBridge struct { // finds no run lost map[string]lostRun lostCalls map[string]lostRun + // ended are runs that ended during a turn, their sessions kept for a + // branch to be cut from (keepEnded, #6528); stopping says the gateway + // stops, and keeps none + ended map[*subscriptionRun]endedRun + stopping bool // untrusted are callers' folders, by account folder, whose // interactive Claude Code asked whether to trust them, and when: a // run for one goes in magpie's own folder until untrustedFor has @@ -2807,21 +2812,27 @@ func (b *subscriptionBridge) branch(req *Request, owner string) (*savedSession, pending := len(calls) == 0 told := historyKey(msgs[:k]) b.mu.Lock() - runs := make([]*subscriptionRun, 0, len(b.runs)) + runs := make([]*subscriptionRun, 0, len(b.runs)+len(b.ended)) for _, run := range b.runs { runs = append(runs, run) } + // then the runs that ended with their sessions kept (#6528), the + // latest first: a call's results that came after its run ended + ended := b.endedRuns() + runs = append(runs, endedLatestFirst(ended)...) b.mu.Unlock() why := "no run of the account made the calls" if pending { why = "the reply has no call, and no run waits on a reply to this conversation" } var found *savedSession + var foundEnded *subscriptionRun foundSeq := 0 for _, run := range runs { if run.owned() != owner { continue } + _, gone := ended[run] run.mu.Lock() at, seq, said := "", 0, "" var unread []string // pending calls whose line isn't read yet @@ -2855,7 +2866,8 @@ func (b *subscriptionBridge) branch(req *Request, owner string) (*savedSession, } } 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)) + // a run that ended is closed, its session kept as it left it + usable := (gone || !run.closed) && !run.rewound && run.lean == req.leanPrompt && !run.clientMarks && (run.tui || !wantTUI(req)) run.mu.Unlock() if at == "" && len(unread) == 0 { continue @@ -2872,6 +2884,10 @@ func (b *subscriptionBridge) branch(req *Request, owner string) (*savedSession, continue } found, foundSeq = &savedSession{session: sid, sessions: sessions, owner: owner, at: time.Now(), since: msgs[i:], cut: at, cutCalls: unread, cutBefore: pending, tui: run.tui, appended: run.appended, cachePrefix: prefix, gone: true}, seq + foundEnded = nil + if gone { + foundEnded = run + } } if !pending { break @@ -2880,9 +2896,19 @@ func (b *subscriptionBridge) branch(req *Request, owner string) (*savedSession, if found == nil { return nil, why } + if foundEnded != nil { + log.Printf("claude: the run this conversation goes on from ended %s ago (%s); its session, kept since, is branched", time.Since(ended[foundEnded]).Round(time.Second), foundEnded.whyLost()) + } return found, "" } +// endedLatestFirst is the ended runs, the one that ended last first. +func endedLatestFirst(ended map[*subscriptionRun]time.Time) []*subscriptionRun { + runs := slices.Collect(maps.Keys(ended)) + slices.SortFunc(runs, func(a, b *subscriptionRun) int { return ended[b].Compare(ended[a]) }) + return runs +} + // retryBranch is where a turn sent again while its run is busy answering // it goes on from a copy of the run's session, cut before the turn // (#5405): the client's connection dropped mid-reply, its request was @@ -2915,14 +2941,26 @@ func (b *subscriptionBridge) retryBranch(req *Request, owner string) *savedSessi } runs = append(runs, run) } + // a run that ended answering the very turn (#6528): its client went + // away mid-reply, a turn the interactive mode can't take back (letGo), + // and the client's retry comes after; it ended busy, not waiting for a + // next turn (idleKey) + ended := b.endedRuns() + for run := range ended { + if run.owned() == owner && run.idleKey == "" && run.convKey != "" && slices.Contains(keys, run.convKey) { + runs = append(runs, run) + } + } b.mu.Unlock() var found *savedSession + var foundEnded *subscriptionRun var at time.Time for _, run := range runs { + _, gone := ended[run] run.mu.Lock() // the very turn, not one that goes on from it (follows): a turn // whose reply the client has is no retry of it - busy := !run.closed && run.rewinding == nil && !run.rewound && run.lean == req.leanPrompt && + busy := (gone || !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, prefix := run.sessionID, slices.Clone(run.sessions), run.backLine, run.backMsg, run.appended, run.tui, run.cachePrefix started := run.started @@ -2942,10 +2980,18 @@ func (b *subscriptionBridge) retryBranch(req *Request, owner string) *savedSessi 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, cachePrefix: prefix}, started + foundEnded = nil + if gone { + foundEnded = run + } } if found == nil { return nil } + if foundEnded != nil { + log.Printf("claude: a turn sent again after its run ended answering it (%s ago: %s) goes on in a branch of the session kept, cut before the turn", time.Since(ended[foundEnded]).Round(time.Second), foundEnded.whyLost()) + return found + } log.Printf("claude: a turn sent again while its run is busy answering it goes on in a branch of its session, cut before the turn") return found } @@ -6663,6 +6709,8 @@ func (r *subscriptionRun) abortFor(why string) { // to be interrupted with it. func (b *subscriptionBridge) abortAll() { b.keepShelf() // the next gateway resumes what waits for a next turn (#6292) + // the sessions of runs that ended go, and those ending now aren't kept + b.dropAllEnded() b.mu.Lock() runs := make([]*subscriptionRun, 0, len(b.runs)) for _, run := range b.runs { @@ -6728,6 +6776,7 @@ func (b *subscriptionBridge) removeRun(run *subscriptionRun) { results := slices.Clone(run.results) run.mu.Unlock() lost := lostRun{at: time.Now(), why: why} + keep := run.keepable() b.mu.Lock() if b.lost == nil { b.lost, b.lostCalls = map[string]lostRun{}, map[string]lostRun{} @@ -6751,12 +6800,20 @@ func (b *subscriptionBridge) removeRun(run *subscriptionRun) { keepLost(b.lostCalls, id, lost, 4*lostMost) } } + // kept as it leaves the runs, so a request between finds it in one + var drop []*subscriptionRun + if keep { + keep, drop = b.keepEnded(run) + } b.mu.Unlock() + for _, r := range drop { + r.removeFiles() + } _ = os.RemoveAll(run.tmp) run.mu.Lock() sid, sessions, shelved := run.sessionID, run.sessions, run.shelved run.mu.Unlock() - if !shelved { + if !shelved && !keep { removeSession(sessions, sid) } }