Claude subscription: a new turn after a reply its run already went on from (a client-side fork, a turn sent in place of an earlier one) rewrites the whole conversation to the cache
What happens
On the Claude subscription bridge (interactive mode), a new turn that goes on from a reply its run has already gone past starts a new Claude Code that is told the whole conversation. Only Claude Code's own system prompt and tools are read from the cache; everything after is written again at the 1h rate.
Two clients hit this in normal use:
- A client-side fork. DeepSeek Harness's
subagent_forkstarts a sub-agent seeded with the lead's finished turns plus a task of its own, while the lead's run is busy answering the lead's next turn. The fork's last assistant message is the lead's previous final reply (no tool call), followed by the fork's task. - Going back and sending another turn. The user goes back two or more turns, rewrites a message and sends it, while the run waits after its latest reply. (A rewrite of the latest turn is already handled:
resumetakes the run back throughbehindKey, #1638.)
Related: #1429 (rewind to where the history diverges), #5405 (retryBranch), #5663, #3436. None of them covers these two triggers.
Evidence
Magpie 0.1.4273 (Linux, interactive mode, claude-opus-5-5, 1h cache). Cache figures from usage.jsonl, log lines from the journal (structure only).
Fork while the lead is busy (2026-11-17):
| Request | cache_read | cache_write |
|---|---|---|
| lead, the turn that started the fork | 138,234 | 1,042 |
| fork, first request | 21,671 | 113,755 |
| lead, next turn | 139,276 | 4,948 |
| fork, second request on | 135,426 → 197,416 | hundreds to ~17k |
claude: no branch of a run's session for this request: the reply has no call, and no run waits on a reply to this conversation
claude: no run waits for this turn: its run is busy with another request
claude: a new Claude Code goes on with the conversation from a transcript of it (43 messages, 0 images), typed the last turn's 2
The fork's second request reads exactly 21,671 + 113,755 = 135,426, i.e. only the first request of each fork pays, but it pays for the whole prefix.
Going back two turns (2026-11-14, v0.1.4080): a prefix of 318,991 tokens read 21,682 and wrote 297,307 (about $2.43 for that one request; going on in the original structure would have been about $0.13). The original branch had moved on from the same point. The same 1h prefix had been read 21 minutes earlier, so this is not TTL. Log: no branch of a run's session … the reply has no call, no run here has had this conversation, transcript of it (396 messages, 12 images).
Why
branchcuts only at a reply's call line, or before the calls of a reply a run waits on (#6128). The reply these turns follow calls no tool.retryBranchneeds the request to be exactly the busy run's turn (run.told == historyKey(req.Messages)). A fork's task is a different turn.resumeonly finds a run idle at the very point the request goes on from, or (behindKey) one turn back.- The run did have the point: when it was resumed for the turn after that reply,
backLine/backMsgheld exactly where to cut, andretryBranchuses them. But they are overwritten at the next turn, so nothing remembers where earlier turns began.
Proposed fix (branch attached)
Fix branch: https://github.com/yyjsjsjx-png/magpie/tree/claude-turn-branch (one commit, ee3c6e994, on 17da22414; its body carries the verification record). The same change is attached as a patch at the end.
Keep the start of every turn a run is resumed for, and branch off it, the same way retryBranch does for the current turn:
resume, when it hands an idle run its next turn (not when it takes a run back from a side question), appends{key, lastLine, lastMsg}to a bounded per-run list (subscriptionRun.turns, at mostturnsMost= 256) beforebackLine/backMsgare overwritten.keyis theturnKeyresume found the run waiting at (it becomesbackKey).- A new step
turnBranch, afterretryBranchinserveClaudeSubscription'sstart: for a new turn, take the request's own key (nextTurn: the conversation as far as its last reply that calls no tool, under the request's model, settings, system prompt and tools), find a run of the owner, live or ended with its session kept, with a turn start at that key (the latest started run first), and resume a copy of its session cut after that reply (cutReply), typed only the turn's messages. The run it branched from is not disturbed. - The key is resume's, not the conversation's alone: a session holds what it was told besides the conversation (a
-prun's first message carries the client's system prompt), and the branch's run is told only the turn, so a turn under another model, settings, system prompt or tools is told whole, asresumeleaves it. (Matching byconversationKeysalone let a fork under new instructions go on under the old ones.) - Same usability rules as
branch/retryBranch: no client cache marks, not rewound or rewinding, samelean, no-prun under the interactive mode, session on disk. keepablealso keeps an ended run that has only turn starts to cut at (a run ended between turns, e.g. retired), soturnBranchcan use its session like the other branches do.
Docs: docs/subsystems/claude-subscription-bridge.md (the runtime path gets a step 4, the whyNoRun, kept-runs and cache-lifetime paragraphs name turnBranch).
This is a concrete trigger of the direction in #1429. Cutting at the longest common prefix in general, e.g. inside a tool loop where earlier messages changed, also has to deal with calls left dangling by the cut; this branch does not attempt that.
Not covered here
- The caller's environment note. A turn sent from another computer than the run's earlier turns is not told the bridge's note on where tools run (
envUnknownNote):turnKeyhas no caller in it. This isresume's behaviour today for the conversation's own next turn (a run started for a caller on this computer, its next turn sent from another, is resumed and told no note), andturnBranchkeeps it. Fixing it for both, e.g. by telling the run an explicit environment update with the turn, seems better than starting a new Claude Code for every caller change, but is left out of this branch. - A key stricter than the prefix.
turnKeyis the conditionresumeuses, not the longest prefix the cache could read: e.g. atool_choiceofnonechanges the key while the tools the run is told stay the same. Loosening it would apply toresumetoo. - A divergence inside a tool loop (#1429's general case).
Verification
At origin/main 17da22414 plus the branch, all with go1.26.8 (as go.mod and CI): Linux tests on WSL2 Ubuntu 24.04 under a temp HOME with pinned caches; vet and builds on a Windows host.
-
New tests, with the shell stand-in for Claude Code:
TestClaudeForkWhileItsLeadIsBusyBranchesAfterTheReply,TestClaudeTurnSentInPlaceOfAnEarlierOneBranchesAfterTheReplyBeforeandTestClaudeTurnBranchCopiesTheSessionAsFarAsTheReply(print and interactive; the last holds each copied session file to the run's session as it stood after the matched reply, byte for byte, plus the branch's own turn and nothing else, then checks that the original run goes on with its fifth turn);TestClaudeTurnUnderOtherInstructionsIsNotBranched(print, where the instructions are in the session's first message);- without a process, also on Windows:
TestClaudeTurnBranchCutsAfterTheReplyTheTurnFollows(incl. another system prompt and another model) andTestClaudeTurnBranchGoesOnFromAnEndedRunsSession.
-
Red before, green after (each break restored before the next):
- both production files at
origin/main, 2. turn starts never recorded, 3. theturnBranchcall taken out ofstart: the fork, rewritten-turn and copy tests FAIL ("0 runs branched, 2 started anew", "0 runs branched, want one", "went on from no copy of its own" / "lost that reply from its copy"); the instructions test passes there (the turn is told whole); keepablewithout theturnscondition:TestClaudeTurnBranchGoesOnFromAnEndedRunsSessionFAILs ("a run with only its turns' starts to cut at isn't kept");- turn starts matched by the conversation alone:
TestClaudeTurnUnderOtherInstructionsIsNotBranchedFAILs ("never told the new instructions"); - every turn start pointed at the run's latest reply, and 7. the first turn start cut before its reply:
TestClaudeTurnBranchCopiesTheSessionAsFarAsTheReplyFAILs in both modes ("want the run's session as it stood after that reply, then the fork's own turn").
- both production files at
-
Neighbours still pass:
TestClaudeTurnSentAgainWhileItsRunIsBusyBranchesOffItsSession,TestClaudeTurnPastABusyRunsTurnIsNotBranchedOffIt(a turn past the busy one is still told whole),TestClaudeForkBranchesOffTheLeadsSession,TestClaudeBranchForSummary*. -
gofmt -lclean;go vet ./...,GOOS=linux go vet -tags nogui ./...,GOOS=windows go vet ./...,go build,GOOS=linux go build -tags nogui,GOOS=windows go buildall exit 0 (Windows and Linux only; macOS neither built nor run). -
Full suite, as CI's Test step (every package but the gateway with
-timeout 30m, the gateway's binary throughbuild/race-shards.shwith-test.timeout=20m): every package passes, and 136 of the gateway's 137 chunks (4371 tests), except three tests that fail the same at17da22414without the change:TestClaudeSilentTurnFails: its 18 streamed cases answer 200 (the stream begins with a keepalive before the 502), also when run alone, about 14s a case;TestFreedHeapLeavesFootprint(build/darwin): its nestedgo build -overlayexits 1, as the downloaded toolchain sits inGOMODCACHE, whose runtime files-overlaymay not replace;TestRequestStateKeptAcrossACatalogFetchedAgain(internal/usage): fails in 2 or 3 of 3 runs on either.
These are reds of their own on main (or of this environment), not caused by this branch.
With a real Claude Code (2.1.325, interactive mode, claude-haiku-5-5, a Claude subscription account; a gateway of its own on loopback with its own HOME and config and a copy of the sign-in, the live gateway untouched): three turns on a first message of ~45K tokens, then a fork at the first reply, each binary on its own random first message.
| Fork request | cache_read | cache_write | Log |
|---|---|---|---|
| with the branch | 48,614 | 959 | a new turn after a reply its run went on from with another goes on in a branch of its session, cut after that reply |
17da22414 |
2,955 | 41,830 | a new Claude Code goes on with the conversation from a transcript of it (2 messages, 0 images) |
The fork read exactly what the second turn had read (the prefix through the first reply), so a copy cut after a reply with no call is read from the cache as one cut at a call line is. The run's own fourth turn read 49,298 (with the branch) and 44,793 after the fork, so the fork left it as it was. All five answers were the words asked for.
Not run:
-race(no C toolchain in that WSL). The change starts no goroutine or timer;turnBranchtakesb.muthen eachrun.muin turn, asretryBranchdoes.- The busy-lead fork and a turn sent in place of an earlier one with a real Claude Code (only the fork at an earlier reply of an idle run was).
- macOS.
Patch against 17da22414 (git apply)
``diff
diff --git a/docs/subsystems/claude-subscription-bridge.md b/docs/subsystems/claude-subscription-bridge.md
index 70328f624..ebfc1cccc 100644
--- a/docs/subsystems/claude-subscription-bridge.md
+++ b/docs/subsystems/claude-subscription-bridge.md
@@ -985,11 +985,12 @@ is an hour's). Until 11-07 every run was given 1h whatever the pick
(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
+again while its run is busy (retryBranch), a new turn after a reply its
+run went on from with another (turnBranch) 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.
+branches then made carried none, and their runs went back to an hour
+under a 5m pick (linkaww); everyRunKept5m in the fork, busy-retry, turn
+branch and side question tests.
branch also takes a side request that sends the conversation whole with the
calls its run still waits on dropped, and the words before them kept: Claude
@@ -1209,7 +1210,7 @@ history to the 1h cache at 2×.
sent initialize first, which Claude Code answers only once it has
loaded the session; one that can't load it exits 1 ("No conversation
found with session ID") without answering. start then lets the
- session go and goes on to step 4 in the same request, logged "Claude
- session go and goes on to step 5 in the same request, logged "Claude
Code could not go on from the conversation's saved session". Before,
the turn got 502 "Claude Code ended" with the safety context set, and
an empty reply without it.
@@ -1229,7 +1230,48 @@ history to the 1h cache at 2×.
backLine), the session can't be copied, the client places its own cache marks, or the run was taken back or is being taken back — the turn told whole, as before. -4.retire, then a new run. In the interactive mode, a conversation +4.subscriptionBridge.turnBranchwhen none of those did: a new turn - after a reply that a run of the account began a turn at, and went on
- from with that turn. The client forked the conversation there —
- DeepSeek Harness's
subagent_forkstarts a sub-agent on the lead's - finished turns and a task of its own while the lead's run answers its
- next turn — or took a turn back and sent another in its place after the
- run had answered it (a turn further back than the last, which
resume - takes back to through
behindKey). The last reply calls no tool, so branchfinds no call line; the turn is no retry of the busy one, soretryBranchtakes none; a new Claude Code was told the whole- conversation, its own system prompt and tools the only part read from
- the cache (11-17: a fork whose prefix was 135,426 tokens read 21,671 and
- wrote 113,755).
resumekeeps, as it hands a run its next turn - (no side question to take back), where the turn began
- (
subscriptionRun.turns, at mostturnsMost): the key it found the - run waiting at (
turnKey, which becomesbackKey) and the line and - reply it ended at (
lastLine,lastMsg, which becomebackLine, backMsg).turnBranchfinds the run, live or ended with its session- kept, with a turn start at the request's own key — the conversation as
- far as its last reply that calls no tool, under the request's model,
- settings, system prompt and tools (
nextTurn) — the latest started run - first, and resumes a copy of its session cut after that reply
- (
cutReply), typed only the turn's messages. The key is resume's, not - the conversation's alone (
conversationKeys): a session holds what it - was told besides the conversation (a
-prun's first message carries - the client's system prompt), and the branch's run is told only the
- turn, so a fork under other instructions would have gone on under the
- old ones; it is told whole, as resume would leave such a turn. The run
- it branched from is not disturbed, and keeps waiting or answering where
- it was.
nilwhen no such run is found, or it was taken back or is - being taken back, is of another mode or prompt (
lean, a-prun - under the interactive mode), the client places its own cache marks, or
- the session can't be copied — the turn told whole, as before. A turn
- whose run waits after the very reply it follows still goes on in that
- run (
resume), and tool results for a reply's calls are no new turn - (
nextTurn).TestClaudeForkWhileItsLeadIsBusyBranchesAfterTheReply, TestClaudeTurnSentInPlaceOfAnEarlierOneBranchesAfterTheReplyBefore,TestClaudeTurnBranchCopiesTheSessionAsFarAsTheReply,TestClaudeTurnUnderOtherInstructionsIsNotBranched,TestClaudeTurnBranchCutsAfterTheReplyTheTurnFollowsandTestClaudeTurnBranchGoesOnFromAnEndedRunsSessionhold it. +5.retire, then a new run. In the interactive mode, a conversation with a reply that calls no tool is given to the new Claude Code as its own transcript (replaySession, inclaude_replay.go): a session file of two lines, a user line holding the conversation before that @@ -1403,7 +1445,8 @@ with a turn this one doesn't follow, waits under another key (the model, settings, system prompt or tools differ), waits at an earlier turn, is busy with another request (a turn whose run is busy answering the very turn sent again goes on from a copy of its session instead, -retryBranch, so this line is not logged for one), ended (how long ago, +retryBranch, and so does a new turn after a reply a run began a turn +at,turnBranch, so this line is not logged for either), ended (how long ago, and why:endWhy, set byabortFor, kept inb.lostby conversation), or no run here has had the conversation. Tool results that find no run waiting add what became of @@ -1968,8 +2011,9 @@ in the sameb.musection that takes it out ofruns, 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,backLineand -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 +backMsg, the starts of the turns it was resumed for (turns), and its +mode, owner and prompt flags. Kept: a session on disk with a call line, a +turn start or an earlier turn's 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 @@ -1981,12 +2025,14 @@ 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
+closed; turnBranch looks at both, the latest started run first. 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
+(backLine/backMsg) and told the turn; a new turn after a reply the
+run began a turn at is cut after that reply (turns) 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
diff --git a/internal/gateway/claude_ended.go b/internal/gateway/claude_ended.go
index 41e008c55..f08e5030e 100644
--- a/internal/gateway/claude_ended.go
+++ b/internal/gateway/claude_ended.go
@@ -13,8 +13,8 @@ import (
// 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
+// answered, is what a branch is cut from (branch, retryBranch, turnBranch)
+// 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.
//
@@ -33,15 +33,16 @@ type endedRun struct {
}
// 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. +// branch to be cut from: a session on disk with a line, a turn or a turn's +// start (turns, turnBranch) 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 != "")
-
(len(r.lines) > 0 || r.backLine != "" || r.backMsg != "" || len(r.turns) > 0)
}
// keepEnded keeps the session of a run that just ended (keepable) for a diff --git a/internal/gateway/claude_subscription.go b/internal/gateway/claude_subscription.go index 173286e28..5300f041a 100644 --- a/internal/gateway/claude_subscription.go +++ b/internal/gateway/claude_subscription.go @@ -429,8 +429,27 @@ type subscriptionRun struct { backLine string lastMsg string backMsg string
- // turns is where each turn it was resumed for began, oldest first, at
- // most turnsMost: the key it waited at (backKey) and the line and reply
- // it ended at (backLine, backMsg), kept past the turn. A new turn that
- // goes on from one of those replies after the run went on from it with
- // another (a fork of the conversation, a turn taken back and sent
- // anew) branches off the session there (turnBranch). Under mu.
- turns []turnStart }
+// turnStart is where in a run's session a turn it was resumed for began: +// key is what resume found the run waiting at (turnKey: the conversation +// before the turn, and the model, settings, system prompt and tools it was +// asked under), and line and msg are the session line and the reply it +// ended at, as cutReply takes them. +type turnStart struct {
- key, line, msg string +}
+// turnsMost is how many turn starts a run keeps (turns). +const turnsMost = 256 + // callLine is the session line of an assistant message block calling a // client's tool: its uuid, its place among the run's lines, and the // conversation the reply answered (historyKey), set as the run parks on @@ -2125,6 +2144,17 @@ func (b *subscriptionBridge) resume(req *Request, owner string) (*subscriptionRu run.segment = ch run.active = time.Now() run.turnUUID, run.backKey, run.backLine, run.backMsg = turn, key, run.lastLine, run.lastMsg
- if back == "" && (run.lastLine != "" || run.lastMsg != "") {
-
// kept past the turn: a fork of the conversation at its last -
// reply, or a turn sent in place of this one, comes after the run -
// went on, and branches off its session here (turnBranch). A run -
// taken back from a side question has lines past the turn's start -
// (back), and keeps none. -
run.turns = append(run.turns, turnStart{key: key, line: run.lastLine, msg: run.lastMsg}) -
if len(run.turns) > turnsMost { -
run.turns = slices.Delete(run.turns, 0, len(run.turns)-turnsMost) -
} - } run.fromLen = 0 // it answered a turn since it started: its lines say where the conversation stood run.allowed = allowedTools(req) run.mu.Unlock() @@ -3086,6 +3116,99 @@ func (b *subscriptionBridge) retryBranch(req *Request, owner string) *savedSessi return found }
+// turnBranch is where a new turn goes on from a copy of a run's session, +// cut after the reply the turn follows, when the run went on from that +// reply with another turn: the client forked its conversation there +// (DeepSeek Harness's subagent_fork starts a sub-agent on the lead's +// finished turns and a task, while the lead's run answers its next turn), +// or took a turn back and sent another in its place (an edit, a retry +// with other words) after the run had answered it. Its last reply calls +// no tool, so branch finds no call line to cut at, and the request is no +// retry of the busy run's turn: a new Claude Code was told the whole +// conversation, only its own system prompt and tools read from the cache. +// The run kept where each turn it was resumed for began (turns); the copy +// is the conversation as Claude Code asked it of Anthropic, so the +// branch's run reads the history from the cache and is told only the +// turn, as a turn after an unshelve is. A turn start is found by the key +// resume found the run waiting at (turnKey), as resume would find a run +// waiting there now: a session holds what the request it was told under +// said besides the conversation — the client's system prompt, which a +// -p run's first message carries — and the branch's run is told only the +// turn, so a request asked under another model, settings, system prompt +// or tools, which resume wouldn't give the run, is told whole as before. +// nil when no run of the owner, live or ended with its session kept, +// began a turn there, or the copy can't be made: a client's own cache +// marks, a session taken back or being taken back, another mode, or no +// session on disk. +func (b *subscriptionBridge) turnBranch(req *Request, owner string) *savedSession {
- if req.clientCache != nil {
-
return nil - }
- key, since := nextTurn(req, owner)
- if key == "" {
-
return nil - }
- b.mu.Lock()
- runs := make([]*subscriptionRun, 0, len(b.runs)+len(b.ended))
- for _, run := range b.runs {
-
if run.owned() == owner { -
runs = append(runs, run) -
} - }
- ended := b.endedRuns()
- for run := range ended {
-
if run.owned() == owner { -
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() -
usable := (gone || !run.closed) && run.rewinding == nil && !run.rewound && run.lean == req.leanPrompt && -
!run.clientMarks && (run.tui || !wantTUI(req)) -
var start turnStart -
for _, t := range run.turns { -
if t.key == key { -
start = t // the latest -
} -
} -
sid, sessions, appended, tui, prefix, started := run.sessionID, slices.Clone(run.sessions), run.appended, run.tui, run.cachePrefix, run.started -
run.mu.Unlock() -
if !usable || start.key == "" || sid == "" || len(sessions) == 0 { -
continue -
} -
if found != nil && !started.After(at) { -
continue -
} -
cut, err := cutReply(sessions, sid, start.line, start.msg) -
if err != nil { -
log.Printf("claude: a run's session couldn't be cut after the reply a new turn follows (%v)", err) -
continue -
} -
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, cachePrefix: prefix}, started -
foundEnded = nil -
if gone { -
foundEnded = run -
} - }
- if found == nil {
-
return nil - }
- if foundEnded != nil {
-
log.Printf("claude: a new turn after a reply its run went on from with another (it ended %s ago: %s) goes on in a branch of the session kept, cut after that reply", time.Since(ended[foundEnded]).Round(time.Second), foundEnded.whyLost()) -
return found - }
- log.Printf("claude: a new turn after a reply its run went on from with another goes on in a branch of its session, cut after that reply")
- return found +}
// replyBegun notes a reply message as it begins: its lines in the session // come later (lastMsg). func (r *subscriptionRun) replyBegun(msg string) { @@ -7137,6 +7260,13 @@ func (s *Server) serveClaudeSubscription(w http.ResponseWriter, r *http.Request, // the cache, told only the turn from = s.subscription.retryBranch(req, owner) }
-
if from == nil { -
// a new turn after a reply its run went on from with another -
// (a fork of the conversation, a turn sent in place of one): -
// the run goes on from a copy of that run's session, cut -
// after the reply, told only the turn -
from = s.subscription.turnBranch(req, owner) -
} if from == nil { if why := s.subscription.whyNoRun(req, owner); why != "" { log.Printf("claude: no run waits for this turn: %s", why)
diff --git a/internal/gateway/claude_subscription_busy_retry_test.go b/internal/gateway/claude_subscription_busy_retry_test.go
index 838ff2bcd..45a892120 100644
--- a/internal/gateway/claude_subscription_busy_retry_test.go
+++ b/internal/gateway/claude_subscription_busy_retry_test.go
@@ -20,8 +20,9 @@ import (
// a user line and an assistant line of its own written to the session's
// file, and answered with its pid and turn. A run resumed from a session
// answers at once; the second turn of a run started anew holds mid-reply,
-// as one whose client went away without magpie hearing of it does (#5405).
-// It says where the per-run logs are, and the log of what it was told.
+// as one whose client went away without magpie hearing of it does (#5405),
+// unless a file named nohold is beside the told log. It says where the
+// per-run logs are, and the log of what it was told.
func busyRetryClaude(t *testing.T) (string, string) {
t.Helper()
if runtime.GOOS == "windows" {
@@ -59,7 +60,7 @@ while read -r line; do
echo "told $line" >> $log
echo "told $line" >> + told +
n=$((n+1))
- if [ -z "$resumed" ] && [ $n = 2 ]; then
- if [ -z "$resumed" ] && [ $n = 2 ] && [ ! -f
+ dir +/nohold ]; then sleep 60 continue fi diff --git a/internal/gateway/claude_turn_branch_cut_test.go b/internal/gateway/claude_turn_branch_cut_test.go new file mode 100644 index 000000000..868c552c1 --- /dev/null +++ b/internal/gateway/claude_turn_branch_cut_test.go @@ -0,0 +1,159 @@ +package gateway
+import (
- "os"
- "path/filepath"
- "strings"
- "testing"
- "time" +)
+// turnBranchFixture is a bridge with one interactive run of own whose +// session on disk holds two turns, and which began its second turn after +// the first reply (line-1, m1): the conversation before that turn is before. +func turnBranchFixture(t *testing.T) (b *subscriptionBridge, run *subscriptionRun, own string, before []Message) {
- t.Helper()
- dir := t.TempDir()
- const sid = "lead-session"
- lines := []string{
-
`{"type":"user","uuid":"ask-1","sessionId":"` + sid + `"}`, -
`{"type":"assistant","uuid":"line-1","sessionId":"` + sid + `","message":{"id":"m1","model":"claude-sonnet-5"}}`, -
`{"type":"user","uuid":"ask-2","sessionId":"` + sid + `"}`, -
`{"type":"assistant","uuid":"line-2","sessionId":"` + sid + `","message":{"id":"m2","model":"claude-sonnet-5"}}`, - }
- if err := os.WriteFile(filepath.Join(dir, sid+".jsonl"), []byte(strings.Join(lines, "\n")+"\n"), 0o600); err != nil {
-
t.Fatal(err) - }
- before = []Message{tbUser("fix the bug"), tbSaid("fixed")}
- own = "claude\x00u"
- b = newSubscriptionBridge()
- run = &subscriptionRun{sessionID: sid, sessions: []string{dir}, tui: true, started: time.Now()}
- run.owner.Store(&own)
- // the key resume found the run waiting at, for a request of these settings
- run.turns = []turnStart{{key: turnKey(own, tbRequest(before), before), line: "line-1", msg: "m1"}}
- b.runs["r"] = run
- return b, run, own, before +}
+// tbRequest is a request of the fixture's settings with msgs. +func tbRequest(msgs []Message) *Request {
- return &Request{Model: "claude-sonnet-5", System: "be brief", Messages: msgs} +}
+func tbUser(s string) Message { return Message{Role: "user", Parts: []Part{{Kind: Text, Text: s}}} } +func tbSaid(s string) Message {
- return Message{Role: "assistant", Parts: []Part{{Kind: Text, Text: s}}} +}
+// cutAsFarAsTheFirstReply checks that s is a copy of the fixture's session +// of its own, cut after the first reply, told the turn alone. +func cutAsFarAsTheFirstReply(t *testing.T, run *subscriptionRun, s *savedSession) {
- t.Helper()
- if s.session == run.sessionID || len(s.since) != 1 || !s.tui {
-
t.Fatalf("branch = session %q, %d messages told, tui %v; want a copy of its own, told the turn alone, interactive", s.session, len(s.since), s.tui) - }
- copied, _ := os.ReadFile(filepath.Join(run.sessions[0], s.session+".jsonl"))
- if c := string(copied); !strings.Contains(c, "line-1") || strings.Contains(c, "ask-2") || strings.Contains(c, "line-2") {
-
t.Fatalf("the copy keeps %q, want the session as far as the first reply", c) - } +}
+// turnBranch cuts the session of the run that began a turn where the +// request goes on from, after the reply it ended at, and takes none where +// that isn't the case: another account's run, a conversation no turn began +// at, the same conversation under another system prompt or model (resume +// wouldn't give the run that turn either), tool results for a call a reply +// made, a run taken back, or a -p run while the interactive mode is on. +func TestClaudeTurnBranchCutsAfterTheReplyTheTurnFollows(t *testing.T) {
- b, run, own, before := turnBranchFixture(t)
- fork := tbRequest(append(append([]Message{}, before...), tbUser("update the docs")))
- got := b.turnBranch(fork, own)
- if got == nil {
-
t.Fatal("no branch for a turn after the reply a turn of the run began at") - }
- t.Cleanup(got.discard)
- cutAsFarAsTheFirstReply(t, run, got)
- if got := b.turnBranch(fork, "claude\x00v"); got != nil {
-
got.discard() -
t.Error("a run of another account was branched") - }
- later := tbRequest(append(append([]Message{}, before...), tbUser("and run the tests"), tbSaid("they pass"), tbUser("commit")))
- if got := b.turnBranch(later, own); got != nil {
-
got.discard() -
t.Error("a turn after a reply no turn began at was branched") - }
- other := tbRequest(fork.Messages)
- other.System = "answer in French"
- if got := b.turnBranch(other, own); got != nil {
-
got.discard() -
t.Error("a turn under another system prompt was branched off a session told the old one") - }
- other = tbRequest(fork.Messages)
- other.Model = "claude-opus-5"
- if got := b.turnBranch(other, own); got != nil {
-
got.discard() -
t.Error("a turn asked of another model was branched") - }
- // the results of a call its run's reply made go on with that run, or
- // branch at the call (branch): no new turn
- results := tbRequest([]Message{tbUser("fix the bug"),
-
{Role: "assistant", Parts: []Part{{Kind: ToolCall, ID: "toolu_1", Name: "read", Args: []byte(`{}`)}}}, -
{Role: "user", Parts: []Part{{Kind: ToolResult, CallID: "toolu_1", Text: "ok"}}}}) - if got := b.turnBranch(results, own); got != nil {
-
got.discard() -
t.Error("tool results were branched as a new turn") - }
- claudeTUIRuns = true
- t.Cleanup(func() { claudeTUIRuns = false })
- run.mu.Lock()
- run.tui = false
- run.mu.Unlock()
- if got := b.turnBranch(fork, own); got != nil {
-
got.discard() -
t.Error("a -p run's session was branched while the interactive mode is on") - }
- run.mu.Lock()
- run.tui, run.rewound = true, true
- run.mu.Unlock()
- if got := b.turnBranch(fork, own); got != nil {
-
got.discard() -
t.Error("a run taken back was branched") - } +}
+// A run that ended between turns — its conversation told to a new run +// (retire), its reply ended by a refusal — has no call line and no turn +// under way, only the starts of the turns it answered: its session is kept +// for those (keepable), and a fork at one of them branches off it as off a +// live run's. +func TestClaudeTurnBranchGoesOnFromAnEndedRunsSession(t *testing.T) {
- b, run, own, before := turnBranchFixture(t)
- t.Cleanup(b.dropAllEnded)
- delete(b.runs, "r")
- run.mu.Lock()
- run.closed = true
- run.mu.Unlock()
- if !run.keepable() {
-
t.Fatal("a run with only its turns' starts to cut at isn't kept") - }
- b.mu.Lock()
- b.keepEnded(run)
- b.mu.Unlock()
- fork := tbRequest(append(append([]Message{}, before...), tbUser("update the docs")))
- got := b.turnBranch(fork, own)
- if got == nil {
-
t.Fatal("no branch off the kept session of an ended run") - }
- t.Cleanup(got.discard)
- cutAsFarAsTheFirstReply(t, run, got)
- // with no turn start either, there is nothing to cut at
- run.mu.Lock()
- run.turns = nil
- run.mu.Unlock()
- if run.keepable() {
-
t.Error("a run with nothing to cut at is kept") - } +} diff --git a/internal/gateway/claude_turn_branch_test.go b/internal/gateway/claude_turn_branch_test.go new file mode 100644 index 000000000..67c2f2be8 --- /dev/null +++ b/internal/gateway/claude_turn_branch_test.go @@ -0,0 +1,295 @@ +package gateway
+import (
- "encoding/json"
- "fmt"
- "net/http/httptest"
- "os"
- "path/filepath"
- "slices"
- "strings"
- "testing"
- "time"
- "github.com/yetone/magpie/internal/provider" +)
+// A fork of a conversation at its last finished turn goes on in a branch of +// the lead's session, cut after the reply it follows. DeepSeek Harness's +// subagent_fork starts a sub-agent on the lead's finished turns and a task +// of its own, while the lead's run answers the lead's next turn: the fork's +// last reply calls no tool, so branch found no call line, and the fork is +// no retry of the busy turn, so retryBranch took none either. A new Claude +// Code was told the whole conversation, and on 11-17 a fork whose prefix +// was 135,426 tokens read 21,671 (Claude Code's system prompt and tools) +// and wrote 113,755 to the cache. +func TestClaudeForkWhileItsLeadIsBusyBranchesAfterTheReply(t *testing.T) {
- for _, mode := range []string{"print", "interactive"} {
-
t.Run(mode, func(t *testing.T) { forkWhileLeadBusy(t, mode) }) - } +}
+func forkWhileLeadBusy(t *testing.T, mode string) {
- h := newBusyRetryHarness(t, mode)
- pickFiveMinutes(t)
- logs := keepLog(t)
- task := rmsg("user", "the conversation so far, told at length. fix the bug")
- first := h.ask(
[+ task +]) - if !strings.Contains(first, "turn 1") {
-
t.Fatalf("the first turn: %q", first) - }
- reply := rmsg("assistant", first)
- // the lead's next turn: its run holds mid-reply, busy
- firstTold := h.heard()
- done := h.send(
[+ task +,+ reply +,+ rmsg("user", "and run the tests") +]) - t.Cleanup(func() {
-
h.s.subscription.abortAll() // the lead's turn holds to the end: stop it -
<-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 lead's run was never told its turn:\n%s\nmagpie log:\n%s", h.read(), logs.String()) -
} -
time.Sleep(10 * time.Millisecond) - }
- // the fork: the lead's finished turns, and a task of its own
- if got := h.ask(
[+ task +,+ reply +,+ rmsg("user", "update the docs for the fix") +]); got == "" { -
t.Fatal("the fork 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 fork's run %s was told the whole conversation:\n%.600s", name, told) -
} -
if !strings.Contains(told, "update the docs for the fix") || strings.Contains(told, "and run the tests") { -
t.Errorf("the fork's run %s was told, want its task and not the lead's turn:\n%.600s", name, told) -
} -
// a copy of the lead's session (lead<pid>), never the lead's own -
i := strings.Index(told, "--resume ") -
if sid := told[i+9:]; strings.HasPrefix(sid, "lead") { -
t.Errorf("the fork's run resumed the lead's session %.30s, want a copy of its own", sid) -
} - }
- if branch != 1 || lead != 1 {
-
t.Fatalf("%d runs branched, %d started anew, want one of each; told log:\n%s\nmagpie log:\n%s", branch, lead, h.read(), logs.String()) - }
- if want := "cut after that reply"; !strings.Contains(logs.String(), want) {
-
t.Errorf("the log says:\n%s", logs.String()) - }
- for _, whole := range []string{"a new Claude Code is told the whole conversation: 3 messages", "from a transcript of it"} {
-
if strings.Contains(logs.String(), whole) { -
t.Errorf("the fork told a new Claude Code the whole conversation:\n%s", logs.String()) -
} - }
- // the branch keeps the 5m cache the lead's run had
- everyRunKept5m(t, h.logs) +}
+// A turn sent in place of one answered two turns back goes on in a branch +// of the run's session, cut after the reply before it: the user went back +// in the conversation, rewrote a message, and sent it, while the run waits +// after its latest reply. A rewrite of the latest turn is taken back to +// before it in its run (behindKey, #1638); one further back found no run, +// and a new Claude Code was told the whole conversation (on 11-14 a +// prefix of 318,991 tokens read 21,682 and wrote 297,307). The run keeps +// waiting after its latest reply. +func TestClaudeTurnSentInPlaceOfAnEarlierOneBranchesAfterTheReplyBefore(t *testing.T) {
- for _, mode := range []string{"print", "interactive"} {
-
t.Run(mode, func(t *testing.T) { earlierTurnSentAnew(t, mode) }) - } +}
+func earlierTurnSentAnew(t *testing.T, mode string) {
- h := newBusyRetryHarness(t, mode)
- t.Cleanup(h.s.subscription.abortAll)
- if err := os.WriteFile(filepath.Join(filepath.Dir(h.told), "nohold"), nil, 0o600); err != nil {
-
t.Fatal(err) - }
- pickFiveMinutes(t)
- logs := keepLog(t)
- task := rmsg("user", "the conversation so far, told at length. fix the bug")
- first := h.ask(
[+ task +]) - conv :=
[+ task +,+ rmsg("assistant", first) - second := h.ask(conv +
,+ rmsg("user", "and run the tests") +]) - third := h.ask(conv +
,+ rmsg("user", "and run the tests") +,+ rmsg("assistant", second) +,+ rmsg("user", "now commit it") +]) - if !strings.Contains(third, "turn 3") || pidOf(t, third) != pidOf(t, first) {
-
t.Fatalf("the conversation's turns went to more than one run: %q, %q, %q\nmagpie log:\n%s", first, second, third, logs.String()) - }
- // the second turn, rewritten, in place of the second and third
- if got := h.ask(conv +
,+ rmsg("user", "run only the unit tests") +]); got == "" { -
t.Fatal("the rewritten turn was answered nothing") - }
- branch := 0
- for name, told := range h.toldBy() {
-
if !strings.Contains(told, "--resume") { -
continue -
} -
branch++ -
if strings.Contains(told, "the conversation so far") { -
t.Errorf("the rewritten turn's run %s was told the whole conversation:\n%.600s", name, told) -
} -
if !strings.Contains(told, "run only the unit tests") || strings.Contains(told, "and run the tests") || strings.Contains(told, "now commit it") { -
t.Errorf("the rewritten turn's run %s was told, want the rewritten turn alone:\n%.600s", name, told) -
} - }
- if branch != 1 {
-
t.Fatalf("%d runs branched, want one; told log:\n%s\nmagpie log:\n%s", branch, h.read(), logs.String()) - }
- if want := "cut after that reply"; !strings.Contains(logs.String(), want) {
-
t.Errorf("the log says:\n%s", logs.String()) - }
- for _, whole := range []string{"a new Claude Code is told the whole conversation: 3 messages", "from a transcript of it"} {
-
if strings.Contains(logs.String(), whole) { -
t.Errorf("the rewritten turn told a new Claude Code the whole conversation:\n%s", logs.String()) -
} - }
- // the run still waits after its latest reply, for the turn after it
- h.s.subscription.mu.Lock()
- idle := len(h.s.subscription.idle)
- h.s.subscription.mu.Unlock()
- if idle != 2 {
-
t.Errorf("%d runs wait, want the conversation's and the branch's", idle) - }
- everyRunKept5m(t, h.logs) +}
+// A branch's copy holds the run's session as far as the reply the turn +// follows, and no further: a fork at the first reply of four, and one at +// the second, each copy the turns up to their reply alone, and the run +// they branched off goes on with the conversation's own next turn. The +// stand-in Claude Code resumes any session file it finds, so what the new +// turn was told says nothing of where the copy was cut; the copy itself +// is read, and held to the run's session as it stood after that reply, +// byte for byte, with the branch's own turn after it and nothing else: a +// stand-in started anew numbers its lines from 1 again, so its own line-1 +// would pass for the run's first reply in a copy cut before it. Reviews +// that pointed every turn start at the run's latest reply, and one that +// cut the first start before its reply, found the tests before this green. +func TestClaudeTurnBranchCopiesTheSessionAsFarAsTheReply(t *testing.T) {
- for _, mode := range []string{"print", "interactive"} {
-
t.Run(mode, func(t *testing.T) { copiesAsFarAsTheReply(t, mode) }) - } +}
+func copiesAsFarAsTheReply(t *testing.T, mode string) {
- h := newBusyRetryHarness(t, mode)
- t.Cleanup(h.s.subscription.abortAll)
- if err := os.WriteFile(filepath.Join(filepath.Dir(h.told), "nohold"), nil, 0o600); err != nil {
-
t.Fatal(err) - }
- // session reads the file of the session sid, with its id taken out
- session := func(sid string) string {
-
t.Helper() -
var dirs []string -
h.s.subscription.mu.Lock() -
for _, run := range h.s.subscription.runs { -
run.mu.Lock() -
if run.sessionID == sid { -
dirs = slices.Clone(run.sessions) -
} -
run.mu.Unlock() -
} -
h.s.subscription.mu.Unlock() -
for _, dir := range dirs { -
if b, err := os.ReadFile(filepath.Join(dir, sid+".jsonl")); err == nil { -
return strings.ReplaceAll(string(b), `"sessionId":"`+sid+`"`, `"sessionId":"S"`) -
} -
} -
t.Fatalf("no session file %s", sid) -
return "" - }
- conv := "[" + rmsg("user", "fix the bug")
- first := h.ask(conv + "]")
- lead := "lead" + pidOf(t, first) // the stand-in's session of a run started anew
- conv += "," + rmsg("assistant", first)
- prefixes := []string{conv} // the conversation as far as each reply
- stood := []string{session(lead)} // the run's session after each reply
- for n := 2; n <= 4; n++ {
-
conv += "," + rmsg("user", fmt.Sprintf("the conversation's turn %d", n)) -
reply := h.ask(conv + "]") -
if pidOf(t, reply) != pidOf(t, first) { -
t.Fatalf("turn %d went to another run: %q", n, reply) -
} -
conv += "," + rmsg("assistant", reply) -
prefixes = append(prefixes, conv) -
stood = append(stood, session(lead)) - }
- for i := range 2 {
-
task := fmt.Sprintf("the fork's task at reply %d", i+1) -
fork := h.ask(prefixes[i] + "," + rmsg("user", task) + "]") -
sid := "" -
for _, told := range h.toldBy() { -
if strings.Contains(told, "--resume ") && strings.Contains(told, task) { -
sid = strings.Fields(strings.SplitN(told, "--resume ", 2)[1])[0] -
} -
} -
if sid == "" || pidOf(t, fork) == pidOf(t, first) { -
t.Fatalf("the fork at reply %d went on from no copy of its own: %q", i+1, fork) -
} -
copied, want := session(sid), stood[i] -
if !strings.HasPrefix(copied, want) || strings.Count(copied, "\n") != strings.Count(want, "\n")+2 { -
t.Errorf("the fork at reply %d: want the run's session as it stood after that reply, then the fork's own turn\nstood:\n%s\ncopy:\n%s", i+1, want, copied) -
} - }
- fifth := h.ask(conv + "," + rmsg("user", "the conversation's turn 5") + "]")
- if pidOf(t, fifth) != pidOf(t, first) || !strings.Contains(fifth, "turn 5") {
-
t.Errorf("the run the forks branched off didn't go on with its next turn: %q", fifth) - } +}
+// A turn asked under another system prompt is no turn the run's session +// can go on with, and is told whole: a -p run's first message carries the +// client's system prompt, and a branch's run is told only the turn, so a +// fork under new instructions went on under the old ones and never heard +// the new. resume leaves such a turn too (turnKey). A review found it. +func TestClaudeTurnUnderOtherInstructionsIsNotBranched(t *testing.T) {
- h := newBusyRetryHarness(t, "print")
- t.Cleanup(h.s.subscription.abortAll)
- if err := os.WriteFile(filepath.Join(filepath.Dir(h.told), "nohold"), nil, 0o600); err != nil {
-
t.Fatal(err) - }
- task := rmsg("user", "fix the bug")
- first := h.ask(
[+ task +]) - before :=
[+ task +,+ rmsg("assistant", first) - second := h.ask(before +
,+ rmsg("user", "run the tests") +]) - third := h.ask(before +
,+ rmsg("user", "run the tests") +,+ rmsg("assistant", second) +,+ rmsg("user", "commit it") +]) - if pidOf(t, first) != pidOf(t, third) {
-
t.Fatalf("the conversation's turns went to more than one run: %q, %q", first, third) - }
- // the instructions are in the run's first message, not a file of its own
- h.s.subscription.mu.Lock()
- for _, run := range h.s.subscription.runs {
-
if run.lean || run.appended || run.tui { -
h.s.subscription.mu.Unlock() -
t.Fatal("the run doesn't carry the client's instructions in its first message") -
} - }
- h.s.subscription.mu.Unlock()
- const system = "ALWAYSANSWERINFRENCH"
- body := strings.Replace(h.body(before+
,+rmsg("user", "run only the unit tests")+]),"system":"be brief","system":"+system+", 1) - rec := httptest.NewRecorder()
- var u Usage
- if code, why := h.s.serveClaudeSubscription(rec, httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body)), provider.Anthropic, h.p, "claude-sonnet-5", []byte(body), &u); code != 200 {
-
t.Fatalf("%d %s", code, why) - }
- var reply struct {
-
Content []struct{ Text string } `json:"content"` - }
- if err := json.Unmarshal(rec.Body.Bytes(), &reply); err != nil || len(reply.Content) == 0 {
-
t.Fatalf("no answer: %s", rec.Body) - }
- told := h.toldBy()[pidOf(t, reply.Content[0].Text)]
- if !strings.Contains(told, system) {
-
t.Fatalf("the turn's Claude Code was never told the new instructions:\n%.800s", told) - } +}
</details>
Follow-up: the two cases listed as not run with a real Claude Code are now run, the same way as above (2.1.325, interactive mode, claude-haiku-5-5, a gateway of its own on loopback with its own HOME and config and a copy of the sign-in; each binary on its own random first message of ~45K tokens).
A. Fork while the lead's run is busy. The lead's second turn asks the model to call a tool; the gateway hands the call to the client and the run waits on its result — as a DeepSeek Harness lead waits on its subagent_fork call. The fork is sent then, and the lead's tool result after it.
| Request | with the branch: cache_read / write | 17da22414: cache_read / write |
|---|---|---|
| lead, turn 2 (calls the tool, run waits) | 52,235 / 253 | 47,811 / 412 |
| fork while the run waits | 52,235 / 552 | 2,996 / 44,870 |
| lead, tool result sent back | 52,488 / 160 | 48,223 / 160 |
At 17da22414 the fork logs no run waits for this turn: its run is busy with another request and then a new Claude Code goes on with the conversation from a transcript of it, the same as the report above; with the branch it logs … goes on in a branch of its session, cut after that reply. The lead goes on with its tool result in its own run either way.
B. Going back two turns and sending a rewritten message.
| Request | with the branch | 17da22414 |
|---|---|---|
| lead, turn 3 | 47,978 / 48 | 49,679 / 48 |
| turn 2 rewritten and sent again | 47,726 / 544 | 2,996 / 46,291 |
| lead, turn 4 | 48,026 / 47 | 49,727 / 47 |
(B has the same request shape as the fork measured in the issue; it is run again here under its own name.) Every answer was the word asked for, and the model did call the tool in A (stop_reason: tool_use).
Verified the reporter's fix branch on current upstream/main — it applies clean and holds. This is @yyjsjsjx-png's report and @yyjsjsjx-png's own fix; what follows is an independent check of their work, not a second patch.
Root cause
On the Claude subscription bridge, a new turn that goes on from a reply its run has already gone past found no run to continue with: branch (internal/gateway/claude_subscription.go) cuts a run's session only at a reply's call line or before the calls of a reply a run waits on, retryBranch needs the request to be the busy run's own turn (run.told == historyKey(req.Messages)), and resume finds a run only at the very reply it waits at, or one turn on (behindKey). So a fork seeded at a finished turn, or a rewrite sent in place of an earlier turn, started a new Claude Code told the whole conversation — only Claude Code's own system prompt and tools came from the cache, everything after was written again at the 1h rate (the reporter measured it on real runs: a fork whose prefix was 135,426 tokens read 21,671 and wrote 113,755; a turn sent two back read 21,682 of a 318,991 prefix and wrote 297,307).
The fix (entirely the reporter's work)
Branch claude-turn-branch, one commit ee3c6e994 on 17da22414 (the same diff is attached to the issue above). Following the reporter's own analysis: resume keeps where each turn it hands a run began — subscriptionRun.turns, at most turnsMost = 256, the turnKey it found the run waiting at plus the line and reply it ended at — and a new step after retryBranch in serveClaudeSubscription's start, subscriptionBridge.turnBranch, finds a run of the owner (live, or ended with its session kept — keepable now also keeps a run whose only cut point is a turn start) with a turn start at the request's own key (nextTurn), and resumes a copy of its session cut after that reply (cutReply), typed only the turn's messages; the run branched from is not disturbed. The key is resume's, not the conversation's alone (conversationKeys), so a turn under another model, settings, system prompt or tools is told whole, as resume leaves such a turn. docs/subsystems/claude-subscription-bridge.md gets the step (runtime path step 4, whyNoRun, kept runs, cache lifetime), and the doc matches the code on each point I checked (turnsMost, the record condition in resume, the run ordering, the log lines).
What I ran
On upstream/main 6c6d3bc84 plus the patch (Windows 11 amd64 host, go1.27.0). One commit has touched internal/gateway/claude_subscription.go since the branch's base — a2213b1b6's supersede (a run left waiting by a compacted conversation), a different face — and the patch lands past it with shifted context:
| Check | Result |
|---|---|
| Attached patch vs branch commit | byte-identical to git diff ee3c6e994^ ee3c6e994 (SHA-256 first 16: 77a1c3bfb02c6123) |
git apply --check on 6c6d3bc84 |
clean |
Red without the fix (turnBranch body cut, tests kept) |
TestClaudeTurnBranchCutsAfterTheReplyTheTurnFollows FAIL "no branch for a turn after the reply a turn of the run began at"; TestClaudeTurnBranchGoesOnFromAnEndedRunsSession FAIL "no branch off the kept session of an ended run" |
| Green with the fix | both PASS; tree re-checked byte-for-byte against the patch after the restore |
The four stand-in tests (TestClaudeForkWhileItsLeadIsBusyBranchesAfterTheReply, TestClaudeTurnSentInPlaceOfAnEarlierOneBranchesAfterTheReplyBefore, TestClaudeTurnBranchCopiesTheSessionAsFarAsTheReply, TestClaudeTurnUnderOtherInstructionsIsNotBranched) |
skip on Windows ("a shell script stands in for Claude Code"); PASS on the reporter's WSL2 Ubuntu 24.04 (go1.26.8), with their red-before/green-after steps 1–7 in the commit body |
go test ./internal/gateway -count=1 -timeout 45m (24.5 min) |
15 red, none in this change's path and all pre-existing on this Windows host: the known socket-handover ×5, marshal-family, WSL-listener ×2, TestClaudeAsRootEnv, TestSweepBridgeProjects…, TestHubRootsOfACodexThread, TestPluginToldWhereTheAgentWorks, and TestMaskedRecordKeepsSentAndBack — a timing flake of its own here, reproduced 4 of 50 runs of this test alone on this very tree: masking one rule hit takes under a microsecond and rec.Took = h.took.Microseconds() (masked.go:88) truncates it to 0, so the test's r.Took <= 0 assertion fails; it passes alone on both trees. The six new tests add no red |
gofmt -l (changed .go files) |
clean |
go vet ./... (windows native), GOOS=linux go vet -tags nogui ./... |
clean |
GOOS=darwin go vet -tags nogui ./... |
only the pre-existing internal/gui trayImagePNG red (traycolumns_darwin_test.go:38), untouched by this change |
| builds | windows, linux/darwin/windows -tags nogui all exit 0 |
-race |
Not verified (no C toolchain on this box); the change starts no goroutine or timer and takes b.mu then each run's mu in turn, as retryBranch does (the reporter's note — not run there either) |
The reporter's real-device runs stand as the real-use evidence, and they are theirs, not mine to claim: Claude Code 2.1.325, interactive mode, a loopback gateway with its own HOME and config and a copy of the sign-in — the fork while the lead's run waits on a tool call (A) and the turn sent in place of an earlier one (B), each measured with and without the branch (the cache_read/write tables in the issue body and follow-up comment: the fork paid 52,235/552 with the branch against 2,996/44,870 without it; the rewritten turn 47,726/544 against 2,996/46,291), and the lead went on undisturbed either way.
Not verified: a real Claude Code run on this Windows host (no subscription account here — the reporter's A/B runs cover the real surface); -race (no C toolchain here); macOS.
Siblings: the cut points a run's session already has — branch, retryBranch, branchAt — are unchanged and keep their own tests; turnBranch adds the fourth cut, and keepable's new condition is held by TestClaudeTurnBranchGoesOnFromAnEndedRunsSession. The general divergence inside a tool loop (#1429) stays open by design here, as the issue itself says.
Attribution: the fix is entirely @yyjsjsjx-png's — the branch, the commit and the attached patch are their work, and the commit keeps them as author. When applying, please keep the author (yyjsjsjx-png).
Generated-by: GLM-5.3-Flash (ZCode)