claude: a summary request branches before its call's line is read (#6128, recih on X)

park() marks a streamed call with the conversation it answered while its
callLine.uuid is still empty. branch()'s no-call path only took lines with a
uuid, so it skipped the call and logged "no run waits on a reply to this
conversation". Claude Code can write the call's transcript line late, after
the tool has run, so waiting for the uuid never helps.

branch() now also takes pending lines with no uuid whose conversation
matches, records their tool-call ids in savedSession.cutCalls, and
cutSessionBeforeCalls cuts the session before the first assistant line
holding one of them. It asks again until cutWait; if the line never appears
the session as it stands on disk is already the conversation before the call.
A line whose uuid is known still wins. The match is still on the conversation
before the reply and on the run's own account.

Run (through mote-run): go vet for darwin, windows and linux; gofmt -l clean;
go test -count=1 -timeout 45m ./internal/gateway: one red,
TestKeyLimitReservationsStayInTheirWindow total/tokens and total/cost, which
is red at base 7a606eecd without this change and is #6165.
TestClaudeBranchForSummaryBeforeTheCallLineIsRead covers a parked call with
no uuid, a call line written 60ms into the cut, and a line that never comes.
Broke it by hand (len(unread) ignored): red with recih's message.

Not tried: a real TUI run. Other code that needs a uuid (noteLines, cutSessionAt)
was read: they guard lines noted from Claude Code's output and are not
reached by this path.
This commit is contained in:
yetone
2026-11-11 23:02:04 +08:00
parent 12cd456f2c
commit b587eb3069
2 changed files with 130 additions and 5 deletions
+72 -5
View File
@@ -1100,7 +1100,7 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model,
log.Printf("claude: a branch of a claude -p run's session goes to a new interactive Claude Code, told the whole conversation")
from, req.branch = nil, nil
}
if from != nil && from.cut != "" {
if from != nil && (from.cut != "" || len(from.cutCalls) > 0) {
// a branch is a copy of the run's session as far as the reply
// that made the calls, a session of its own: Claude Code's
// interactive mode doesn't take --resume-session-at, and resumes
@@ -1111,14 +1111,20 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model,
if from.cutBefore {
cutter, how = cutSessionBefore, "a side request that sends the conversation whole, without the calls its run still waits on, goes on in a branch of that run's session, cut before them"
}
sid, err := cutter(from.sessions, from.session, from.cut)
var sid string
var err error
if from.cut == "" {
sid, err = cutSessionBeforeCalls(from.sessions, from.session, from.cutCalls)
} else {
sid, err = cutter(from.sessions, from.session, from.cut)
}
if err != nil {
log.Printf("claude: a branch of a run's session couldn't be cut (%v); a new Claude Code is told the whole conversation", err)
from, req.branch = nil, nil
} else {
log.Printf("claude: %s (%d messages)", how, len(from.since))
from.mu.Lock()
from.session, from.cut, from.cutBefore, from.gone = sid, "", false, false
from.session, from.cut, from.cutCalls, from.cutBefore, from.gone = sid, "", nil, false, false
from.mu.Unlock()
}
}
@@ -2530,6 +2536,9 @@ type savedSession struct {
// cutBefore: cut before that line, not after it: the reply's words
// stay and its calls go (a side request that dropped them, #6128)
cutBefore bool
// cutCalls: the cut is before the line of these tool calls, found by
// their ids, when the line's uuid isn't known yet (#6128).
cutCalls []string
// tui: the session was made by Claude Code's interactive mode; a
// branch of it is too, where it can be (claudePrint)
tui bool
@@ -2774,10 +2783,27 @@ func (b *subscriptionBridge) branch(req *Request, owner string) (*savedSession,
}
run.mu.Lock()
at, seq, said := "", 0, ""
var unread []string // pending calls whose line isn't read yet
if pending {
for id, l := range run.lines {
switch {
case l.told != told:
case l.uuid == "":
unread = append(unread, id)
if seq == 0 || l.seq < seq {
seq, said = l.seq, l.told
}
}
}
// A reply is parked on once its calls were streamed; its
// session line may not be read yet, nor on disk (#6128): the
// calls are found in the session by their ids, and a line
// already read is a surer place.
slices.Sort(unread)
for _, l := range run.lines {
if l.uuid != "" && l.told == told && (at == "" || l.seq < seq) {
at, seq, said = l.uuid, l.seq, l.told
unread = nil
}
}
} else {
@@ -2790,7 +2816,7 @@ 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))
run.mu.Unlock()
if at == "" {
if at == "" && len(unread) == 0 {
continue
}
switch {
@@ -2804,7 +2830,7 @@ func (b *subscriptionBridge) branch(req *Request, owner string) (*savedSession,
if pending && found != nil && seq <= foundSeq {
continue
}
found, foundSeq = &savedSession{session: sid, sessions: sessions, owner: owner, at: time.Now(), since: msgs[i:], cut: at, cutBefore: pending, tui: run.tui, appended: run.appended, cachePrefix: prefix, gone: true}, seq
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
}
if !pending {
break
@@ -3007,6 +3033,47 @@ func cutSessionBefore(dirs []string, sid, uuid string) (string, error) {
return cutSessionAt(dirs, sid, uuid, cutBefore)
}
// cutSessionBeforeCalls is cutSession as far as the line before the first
// assistant line that calls one of ids, the calls a run's reply made that
// its line uuid isn't known for (#6128). Claude Code writes that line late,
// after its tool ran: asked again until cutWait is over, then, with the
// line not there, the session as it stands is what came before the calls.
func cutSessionBeforeCalls(dirs []string, sid string, ids []string) (string, error) {
if len(ids) == 0 {
return "", errors.New("no session to cut")
}
return cutSessionWhere(dirs, sid, "calls "+strings.Join(ids, ","), func(b []byte, last bool) int {
if end := cutBeforeCalls(b, ids); end >= 0 {
return end
}
if last {
return len(b)
}
return -1
})
}
// cutBeforeCalls is where in a session's lines b the first whole assistant
// line calling one of ids begins, -1 when none is there; a line with no
// newline yet is not whole.
func cutBeforeCalls(b []byte, ids []string) int {
for at := 0; at < len(b); {
nl := bytes.IndexByte(b[at:], '\n')
if nl < 0 {
break
}
line := b[at : at+nl]
start := at
at += nl + 1
for _, id := range ids {
if bytes.Contains(line, []byte(`"id":"`+id+`"`)) {
return start
}
}
}
return -1
}
// cutSessionWhere copies session sid as far as the place at finds in its
// lines (> 0), asked again until cutWait is over; last is the final ask.
// what is what it looks for, as an error says.
@@ -5,6 +5,7 @@ import (
"path/filepath"
"strings"
"testing"
"time"
)
// recih on X (#6128): Claude Code's AgentSummary sends the sub-agent's
@@ -70,3 +71,60 @@ func TestClaudeBranchForSummaryWithoutThePendingCall(t *testing.T) {
t.Fatalf("closed run: %v %q", got, why)
}
}
// #6128 (recih, v0.1.3757): the run parks on a call it streamed before the
// call's session line is read or written (Claude Code writes it after the
// tool ran), so the line has no uuid. The summary is found by the history
// the call answered, and the branch is cut before the call by its id,
// whether the line is on disk by then or not.
func TestClaudeBranchForSummaryBeforeTheCallLineIsRead(t *testing.T) {
was := cutWait
cutWait = 300 * time.Millisecond
t.Cleanup(func() { cutWait = was })
dir := t.TempDir()
const sid = "lead-session"
path := filepath.Join(dir, sid+".jsonl")
head := `{"uuid":"u1","sessionId":"` + sid + `","type":"user"}` + "\n" + `{"uuid":"a-words","sessionId":"` + sid + `","type":"assistant"}` + "\n"
if err := os.WriteFile(path, []byte(head), 0o600); err != nil {
t.Fatal(err)
}
user := func(s string) Message { return Message{Role: "user", Parts: []Part{{Kind: Text, Text: s}}} }
words := Message{Role: "assistant", Parts: []Part{{Kind: Text, Text: "I will run the tests."}}}
history := []Message{user("task")}
b := newSubscriptionBridge()
run := &subscriptionRun{sessionID: sid, sessions: []string{dir}, tui: true}
own := "claude\x00u"
run.owner.Store(&own)
run.lines = map[string]callLine{"toolu_1": {seq: 1, told: historyKey(history)}} // parked, no uuid yet
b.runs["r"] = run
req := &Request{Messages: append(append(append([]Message{}, history...), words), user("Describe your progress in 3-5 words."))}
got, why := b.branch(req, own)
if got == nil {
t.Fatalf("no branch while the call's line is unread: %s", why)
}
if !got.cutBefore || len(got.cutCalls) != 1 || got.cutCalls[0] != "toolu_1" {
t.Fatalf("branch = %+v, want cut before the call toolu_1", got)
}
// the line is written while the cut waits for it: the cut is before it
go func() {
time.Sleep(60 * time.Millisecond)
f, _ := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0o600)
defer f.Close()
f.WriteString(`{"uuid":"a-call","sessionId":"` + sid + `","type":"assistant","message":{"content":[{"type":"tool_use","id":"toolu_1"}]}}` + "\n")
}()
id, err := cutSessionBeforeCalls(got.sessions, got.session, got.cutCalls)
if err != nil {
t.Fatal(err)
}
if s, _ := os.ReadFile(filepath.Join(dir, id+".jsonl")); !strings.Contains(string(s), "a-words") || strings.Contains(string(s), "a-call") {
t.Fatalf("branch keeps %q, want the words and not the call", s)
}
// the line never comes: what is on disk is what came before the call
id, err = cutSessionBeforeCalls(got.sessions, got.session, []string{"toolu_9"})
if err != nil {
t.Fatal(err)
}
if s, _ := os.ReadFile(filepath.Join(dir, id+".jsonl")); !strings.Contains(string(s), "a-words") {
t.Fatalf("branch keeps %q, want the words", s)
}
}