claude: a side question after a run's first reply of words branches by the reply's id
sleepy_shibe (Discord #feedback, magpie 0.1.2948, Claude Code 2.1.318,
claude-opus-5-5, macOS, interactive mode): when the last turn's reply
was words only, the turn after a prompt suggestion found no run
("claude: no run waits for this turn: its run ended 0s ago: the
interactive Claude Code can't go on with this turn") and a new Claude
Code was told the whole conversation as a transcript. With a tool call
in the turn it branched. 3 sessions, 7 times.
Cause (the reporter's reading, checked in a test): the interactive mode
streams a reply and the bridge hears its session line only later, from
the file. resume saves run.lastLine as the turn's backLine. A run's
first reply of words has no line heard yet, so backLine, behindLine and
the shelf's behindLine were empty while behindMsg (from message_start)
held the reply's id. branchAt returned nil at `at == ""` with no log,
and the run was let go. With a tool call, the run waited on the call and
heard the call's line first, so there was a line to cut at (8ac5f98e).
A run after a branch is a new run, so every first reply of words after
one hit it.
Fix, every path that cuts behind a side question:
- branchAt cuts with the reply's id alone when no line was heard.
- cutReply takes an empty uuid with a msg and cuts after the reply's
last main-thread line; cutSessionAt's empty-uuid check moves to its
uuid callers (cutSessionWhere does the polling).
- unshelve's search for a session behind a side question accepts a
behindMsg alone, and cutBehind cuts by cutReply when either is set.
- cutReply waits for the reply's lines up to cutWait before falling
back to the uuid's line. Before, a run that had heard an earlier
turn's line cut after it at once when the new reply's lines weren't
written yet, dropping the last turn.
Tests:
- TestClaudeInteractiveSideQuestionAfterAFirstReplyOfWordsKeepsTheReply:
the fake writes the reply's line late; first turn words only, the
suggestion, then "now commit it". The next turn must resume a copy of
the run's own session (U1 and A1), told only the new turn. On
origin/main ed7aeb052 it is red and logs the reporter's exact line.
- TestClaudeShelvedSideQuestionAfterAFirstReplyOfWordsKeepsTheReply:
the same run let go past idleMost; the shelved session (behindLine
empty, behindMsg set) is found and cut.
- TestClaudeCutReplyWaitsForTheReplysLines, and two id-only cases plus
two error cases in TestClaudeCutReplyKeepsTheWholeReply.
Broken by hand, each red then restored: branchAt's old guard (the
interactive test), unshelve's old condition and cutBehind's old route
(the shelved test each), cutReply falling back to the uuid without
waiting (the wait test).
Run (mote, at this tree on origin/main ed7aeb052):
- go test -tags nogui -count=3 -run 'TestClaudeCutReply|TestClaudeShelved...|
TestClaudeInteractiveSideQuestion|TestClaudeCutSession' ./internal/gateway/: ok
- go test -tags nogui -count=1 -timeout 45m ./...: ok, 87 packages, no
FAIL (gateway 770s, claudetui 75s); log kept whole.
- go vet -tags nogui ./internal/gateway/, GOOS=linux go vet -tags nogui
./..., GOOS=windows go vet ./..., go build ./..., GOOS=linux go build
-tags nogui ./..., GOOS=windows go build ./...: ok
- gofmt -l: clean
Not tried: a real interactive Claude Code 2.1.318 with a real account;
the fake reproduces the timing (the reply's row heard after the stream
ended), not the real TUI. A reply split into several rows whose later
rows are not yet written when the cut runs would still be cut short
(as before this change); not seen.
This commit is contained in:
@@ -850,9 +850,23 @@ before the run is let go and its file removed (`branchAt`, a cut copy as
|
||||
in [Tool results another request answers first](#tool-results-another-request-answers-first)),
|
||||
and a new interactive run resumes the copy, told only the turn's
|
||||
messages. Before, every turn after a suggestion was told whole to a new
|
||||
run (bbfatx on X). There is no cut with a client's own cache marks, or for a run with no session or no line;
|
||||
then the turn is told whole, as before.
|
||||
`TestClaudeInteractiveSideQuestionBranchesBeforeIt` holds it.
|
||||
run (bbfatx on X). The interactive mode streams a reply first and tells
|
||||
its session lines after, read from the file, so as a suggestion begins
|
||||
`lastLine` may be a line before the reply (its tool call) or, in a run's
|
||||
first reply, empty. The run also keeps the reply's message id (`lastMsg`
|
||||
from `replyBegun`, then `backMsg`, `behindMsg` and the shelf's
|
||||
`behindMsg`), and `cutReply` cuts after that reply's last main-thread
|
||||
line: by the id alone when no line was heard, waiting up to `cutWait` for
|
||||
the reply's lines before it falls back to the line (sleepy_shibe, twice).
|
||||
The shelf (`unshelve`, `cutBehind`) takes a session behind a side
|
||||
question by either. There is no cut with a client's own cache marks, or
|
||||
for a run with no session, or neither a line nor a reply; then the turn
|
||||
is told whole, as before.
|
||||
`TestClaudeInteractiveSideQuestionBranchesBeforeIt`,
|
||||
`TestClaudeInteractiveSideQuestionAfterACallKeepsTheReply`,
|
||||
`TestClaudeInteractiveSideQuestionAfterAFirstReplyOfWordsKeepsTheReply`,
|
||||
`TestClaudeShelvedSideQuestionAfterAFirstReplyOfWordsKeepsTheReply` and
|
||||
`TestClaudeCutReplyWaitsForTheReplysLines` hold it.
|
||||
|
||||
A turn after a reply that starts a new run logs why none waited
|
||||
(`whyNoRun`, "claude: no run waits for this turn: …"): its run went on
|
||||
|
||||
@@ -2432,7 +2432,7 @@ func (b *subscriptionBridge) unshelve(req *Request, owner string) *savedSession
|
||||
// where that turn put it, not where the conversation's own next
|
||||
// turn comes by (#4914)
|
||||
for _, e := range b.shelf {
|
||||
if e.behind == key && (e.behindTurn != "" || e.behindLine != "") && (s == nil || e.at.After(s.at)) {
|
||||
if e.behind == key && (e.behindTurn != "" || e.behindLine != "" || e.behindMsg != "") && (s == nil || e.at.After(s.at)) {
|
||||
s = e
|
||||
}
|
||||
}
|
||||
@@ -2467,7 +2467,7 @@ func (b *subscriptionBridge) unshelve(req *Request, owner string) *savedSession
|
||||
func (s *savedSession) cutBehind() bool {
|
||||
var cut string
|
||||
var err error
|
||||
if s.behindLine != "" {
|
||||
if s.behindLine != "" || s.behindMsg != "" {
|
||||
cut, err = cutReply(s.sessions, s.session, s.behindLine, s.behindMsg)
|
||||
} else {
|
||||
cut, err = cutSessionBefore(s.sessions, s.session, s.behindTurn)
|
||||
@@ -2612,13 +2612,15 @@ func (r *subscriptionRun) replyBegun(msg string) {
|
||||
// branchAt is a branch of the run's session cut after its line at, as far
|
||||
// as the last line of its reply msg (cutReply), for a turn of its
|
||||
// conversation told since: the copy is made now, before the run is let go
|
||||
// with its file, and is the branch's own. nil when there is no line or
|
||||
// session, or the copy can't be made.
|
||||
// with its file, and is the branch's own. A run whose reply was its first
|
||||
// may have heard no line of its own as the side question began, only the
|
||||
// reply's id, and is cut by that alone (sleepy_shibe). nil when there is
|
||||
// neither a line nor a reply, no session, or the copy can't be made.
|
||||
func (r *subscriptionRun) branchAt(at, msg, owner string, since []Message) *savedSession {
|
||||
r.mu.Lock()
|
||||
sid, sessions, marks := r.sessionID, slices.Clone(r.sessions), r.clientMarks
|
||||
r.mu.Unlock()
|
||||
if at == "" || sid == "" || len(sessions) == 0 || marks {
|
||||
if at == "" && msg == "" || sid == "" || len(sessions) == 0 || marks {
|
||||
return nil
|
||||
}
|
||||
cut, err := cutReply(sessions, sid, at, msg)
|
||||
@@ -2646,6 +2648,16 @@ func cutSession(dirs []string, sid, uuid string) (string, error) {
|
||||
return cutSessionAt(dirs, sid, uuid, cutAfter)
|
||||
}
|
||||
|
||||
// cutSessionAt is cutSession as far as where at says in the session's
|
||||
// lines, uuid's line found by mark.
|
||||
func cutSessionAt(dirs []string, sid, uuid string, at func(b, mark []byte, uuid string) int) (string, error) {
|
||||
if uuid == "" {
|
||||
return "", errors.New("no session to cut")
|
||||
}
|
||||
mark := []byte(`"uuid":"` + uuid + `"`)
|
||||
return cutSessionWhere(dirs, sid, "line "+uuid, func(b []byte, _ bool) int { return at(b, mark, uuid) })
|
||||
}
|
||||
|
||||
// cutReply is cutSession as far as the last line of the reply msg, the
|
||||
// message whose line uuid is or one after it: the conversation as it
|
||||
// stood before the side question asked after that reply. The interactive
|
||||
@@ -2653,17 +2665,24 @@ func cutSession(dirs []string, sid, uuid string) (string, error) {
|
||||
// run had heard last as the side question began may be one before the
|
||||
// reply (its tool call, before the result and the reply's words): cut
|
||||
// there, the conversation went on with a call Claude Code took as
|
||||
// interrupted (sleepy_shibe). Lines of msg come before the side
|
||||
// question's, which the run was told after the reply; with no msg, or
|
||||
// none of its lines in the session, the cut is after uuid's line.
|
||||
// interrupted (sleepy_shibe). A run's first reply may have no line heard
|
||||
// at all, uuid empty, and is cut by msg alone. Lines of msg come before
|
||||
// the side question's, which the run was told after the reply; they are
|
||||
// waited for as long as a line is (cutWait), as an earlier line found
|
||||
// first would cut the reply off. With no msg, or none of its lines in the
|
||||
// session by then, the cut is after uuid's line.
|
||||
func cutReply(dirs []string, sid, uuid, msg string) (string, error) {
|
||||
if msg == "" {
|
||||
return cutSession(dirs, sid, uuid)
|
||||
}
|
||||
return cutSessionAt(dirs, sid, uuid, func(b, mark []byte, uuid string) int {
|
||||
mark := []byte(`"uuid":"` + uuid + `"`)
|
||||
return cutSessionWhere(dirs, sid, "reply "+msg, func(b []byte, last bool) int {
|
||||
if end := cutAfterReply(b, msg); end > 0 {
|
||||
return end
|
||||
}
|
||||
if !last || uuid == "" {
|
||||
return -1
|
||||
}
|
||||
return cutAfter(b, mark, uuid)
|
||||
})
|
||||
}
|
||||
@@ -2703,18 +2722,21 @@ func cutSessionBefore(dirs []string, sid, uuid string) (string, error) {
|
||||
return cutSessionAt(dirs, sid, uuid, cutBefore)
|
||||
}
|
||||
|
||||
func cutSessionAt(dirs []string, sid, uuid string, at func(b, mark []byte, uuid string) int) (string, error) {
|
||||
if sid == "" || uuid == "" || strings.ContainsAny(sid, `/\`) || strings.Contains(sid, "..") {
|
||||
// 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.
|
||||
func cutSessionWhere(dirs []string, sid, what string, at func(b []byte, last bool) int) (string, error) {
|
||||
if sid == "" || strings.ContainsAny(sid, `/\`) || strings.Contains(sid, "..") {
|
||||
return "", errors.New("no session to cut")
|
||||
}
|
||||
mark := []byte(`"uuid":"` + uuid + `"`)
|
||||
for deadline := time.Now().Add(cutWait); ; time.Sleep(20 * time.Millisecond) {
|
||||
last := time.Now().After(deadline)
|
||||
for _, dir := range dirs {
|
||||
b, err := os.ReadFile(filepath.Join(dir, sid+".jsonl"))
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
end := at(b, mark, uuid)
|
||||
end := at(b, last)
|
||||
if end <= 0 {
|
||||
continue
|
||||
}
|
||||
@@ -2728,8 +2750,8 @@ func cutSessionAt(dirs []string, sid, uuid string, at func(b, mark []byte, uuid
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
return "", fmt.Errorf("line %s isn't in session %s", uuid, sid)
|
||||
if last {
|
||||
return "", fmt.Errorf("%s isn't in session %s", what, sid)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -421,6 +421,145 @@ func TestClaudeInteractiveSideQuestionAfterACallKeepsTheReply(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// sleepy_shibe (magpie 0.1.2948, Claude Code 2.1.318): a run's first
|
||||
// reply, words only, streamed and over before Claude Code's prompt
|
||||
// suggestion began, while the reply's line, read from the session file,
|
||||
// came after. The run had heard no line of its own yet, only the reply's
|
||||
// message id, so the branch for the next turn had nowhere to be cut, and
|
||||
// a new Claude Code was told the whole conversation ("no run waits for
|
||||
// this turn ... can't go on with this turn"). The branch is cut by the
|
||||
// reply's id alone: U1 and A1, the suggestion left out.
|
||||
func TestClaudeInteractiveSideQuestionAfterAFirstReplyOfWordsKeepsTheReply(t *testing.T) {
|
||||
h := newPrefixHarness(t)
|
||||
h.interactive()
|
||||
if err := os.WriteFile(filepath.Join(h.logs, "late"), nil, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tools := `"tools":` + prefixTools + `,`
|
||||
u1 := rmsg("user", "what does main.go do")
|
||||
first, _ := h.ask(tools, `[`+u1+`]`)
|
||||
pid := answerPID(t, first)
|
||||
if first != "pid "+pid+" had 0 turn 1" {
|
||||
t.Fatalf("the first turn: %q", first)
|
||||
}
|
||||
conv := u1 + `,` + rmsg("assistant", first)
|
||||
if got, _ := h.ask(tools, `[`+conv+`,`+rmsg("user", suggestionMode)+`]`); got != "pid "+pid+" had 0 turn 2" {
|
||||
t.Fatalf("the suggestion: %q", got)
|
||||
}
|
||||
next, _ := h.ask(tools, `[`+conv+`,`+rmsg("user", "now commit it")+`]`)
|
||||
branch := answerPID(t, next)
|
||||
// the turn's message and the reply: the suggestion's two lines left out
|
||||
if branch == pid || next != "pid "+branch+" had 2 turn 1" {
|
||||
t.Fatalf("the turn after the suggestion: %q (the conversation's run was %s, its session's turn has 2 lines before the suggestion)\n%s", next, pid, h.log(branch))
|
||||
}
|
||||
log := h.log(branch)
|
||||
// resumed from a copy of the run's own session, not a transcript of
|
||||
// the conversation a new Claude Code is given
|
||||
sid := regexp.MustCompile(`--resume (\S+)`).FindStringSubmatch(log)
|
||||
if sid == nil {
|
||||
t.Fatalf("the branch resumed no session: %.600s", log)
|
||||
}
|
||||
copied, _ := filepath.Glob(filepath.Join(h.config, "projects", "*", sid[1]+".jsonl"))
|
||||
if len(copied) != 1 {
|
||||
t.Fatalf("the branch's session %s: %v", sid[1], copied)
|
||||
}
|
||||
if b, _ := os.ReadFile(copied[0]); !strings.Contains(string(b), `"uuid":"u`+pid+`-1"`) || !strings.Contains(string(b), `"uuid":"a`+pid+`-1"`) {
|
||||
t.Fatalf("the branch's session isn't a copy of the run's U1 and A1:\n%s", b)
|
||||
}
|
||||
if told := log[strings.Index(log, "\ntold "):]; strings.Contains(told, "main.go") || strings.Contains(told, "SUGGESTION") || !strings.Contains(told, "now commit it") {
|
||||
t.Fatalf("the branch was told %.600s, want the new turn only", told)
|
||||
}
|
||||
}
|
||||
|
||||
// The same run let go past idleMost after the suggestion: its session is
|
||||
// shelved where the suggestion put it, and the conversation's next turn
|
||||
// finds it by the reply's id alone and resumes a copy cut before the
|
||||
// suggestion (#4914), not a transcript of the whole conversation.
|
||||
func TestClaudeShelvedSideQuestionAfterAFirstReplyOfWordsKeepsTheReply(t *testing.T) {
|
||||
h := newPrefixHarness(t)
|
||||
h.interactive()
|
||||
if err := os.WriteFile(filepath.Join(h.logs, "late"), nil, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tools := `"tools":` + prefixTools + `,`
|
||||
u1 := rmsg("user", "what does main.go do")
|
||||
first, _ := h.ask(tools, `[`+u1+`]`)
|
||||
pid := answerPID(t, first)
|
||||
conv := u1 + `,` + rmsg("assistant", first)
|
||||
if got, _ := h.ask(tools, `[`+conv+`,`+rmsg("user", suggestionMode)+`]`); got != "pid "+pid+" had 0 turn 2" {
|
||||
t.Fatalf("the suggestion: %q", got)
|
||||
}
|
||||
for i := range idleMost {
|
||||
h.ask(tools, `[`+rmsg("user", "other conversation "+strconv.Itoa(i))+`]`)
|
||||
}
|
||||
h.s.subscription.mu.Lock()
|
||||
var behindLine, behindMsg string
|
||||
for _, e := range h.s.subscription.shelf {
|
||||
if e.session == "s"+pid {
|
||||
behindLine, behindMsg = e.behindLine, e.behindMsg
|
||||
}
|
||||
}
|
||||
h.s.subscription.mu.Unlock()
|
||||
if behindMsg == "" || behindLine != "" {
|
||||
t.Fatalf("the shelved session is behind line %q, reply %q: want the reply's id alone, its line heard late", behindLine, behindMsg)
|
||||
}
|
||||
next, _ := h.ask(tools, `[`+conv+`,`+rmsg("user", "now commit it")+`]`)
|
||||
resumed := answerPID(t, next)
|
||||
if next != "pid "+resumed+" had 2 turn 1" {
|
||||
t.Fatalf("the turn after the suggestion: %q\n%s", next, h.log(resumed))
|
||||
}
|
||||
log := h.log(resumed)
|
||||
sid := regexp.MustCompile(`--resume (\S+)`).FindStringSubmatch(log)
|
||||
if sid == nil || sid[1] == "s"+pid {
|
||||
t.Fatalf("the next turn resumed no copy of the shelved session: %.600s", log)
|
||||
}
|
||||
copied, _ := filepath.Glob(filepath.Join(h.config, "projects", "*", sid[1]+".jsonl"))
|
||||
if len(copied) != 1 {
|
||||
t.Fatalf("the resumed session %s: %v", sid[1], copied)
|
||||
}
|
||||
if b, _ := os.ReadFile(copied[0]); !strings.Contains(string(b), `"uuid":"u`+pid+`-1"`) || !strings.Contains(string(b), `"uuid":"a`+pid+`-1"`) || strings.Contains(string(b), `"uuid":"a`+pid+`-2"`) {
|
||||
t.Fatalf("the resumed session isn't the run's U1 and A1 alone:\n%s", b)
|
||||
}
|
||||
if told := log[strings.Index(log, "\ntold "):]; strings.Contains(told, "main.go") || !strings.Contains(told, "now commit it") {
|
||||
t.Fatalf("the resumed run was told %.600s, want the new turn only", told)
|
||||
}
|
||||
}
|
||||
|
||||
// A run that heard a line of an earlier turn last, its new reply's lines
|
||||
// not yet in the session as the next turn comes: cutReply waits for the
|
||||
// reply's lines, as it would for the line, before it cuts after the
|
||||
// earlier line, which would leave the last turn out.
|
||||
func TestClaudeCutReplyWaitsForTheReplysLines(t *testing.T) {
|
||||
was := cutWait
|
||||
cutWait = 5 * time.Second
|
||||
t.Cleanup(func() { cutWait = was })
|
||||
dir := t.TempDir()
|
||||
f := filepath.Join(dir, "S.jsonl")
|
||||
early := `{"type":"user","uuid":"u1","sessionId":"S","message":{"role":"user","content":"hi"}}` + "\n" +
|
||||
`{"type":"assistant","uuid":"a1","sessionId":"S","message":{"id":"msg_1","role":"assistant","content":[{"type":"text","text":"hello"}]}}` + "\n" +
|
||||
`{"type":"user","uuid":"u2","sessionId":"S","message":{"role":"user","content":"and now"}}` + "\n"
|
||||
late := `{"type":"assistant","uuid":"a2","sessionId":"S","message":{"id":"msg_2","role":"assistant","content":[{"type":"text","text":"done"}]}}` + "\n"
|
||||
if err := os.WriteFile(f, []byte(early), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
written := make(chan struct{})
|
||||
go func() {
|
||||
defer close(written)
|
||||
// the cut is looking by now: it found a1 and no line of msg_2
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
os.WriteFile(f, []byte(early+late), 0o600)
|
||||
}()
|
||||
id, err := cutReply([]string{dir}, "S", "a1", "msg_2")
|
||||
<-written
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, _ := os.ReadFile(filepath.Join(dir, id+".jsonl"))
|
||||
if want := strings.ReplaceAll(early+late, `"sessionId":"S"`, `"sessionId":"`+id+`"`); string(got) != want {
|
||||
t.Errorf("copy\n%s\nwant\n%s", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
// cutReply keeps a reply whole: Claude Code writes a line a content
|
||||
// block, each under the message's id, and the line the run heard last as
|
||||
// the side question began may be the turn's tool call. The copy goes as
|
||||
@@ -460,6 +599,8 @@ func TestClaudeCutReplyKeepsTheWholeReply(t *testing.T) {
|
||||
{"the reply's last line heard", "a3", "msg_01B", 6},
|
||||
{"no reply known", "a1", "", 2},
|
||||
{"the reply's lines not in the session", "a1", "msg_none", 2},
|
||||
{"no line heard, the reply's id only", "", "msg_01B", 6},
|
||||
{"no line heard, the call's reply", "", "msg_01A", 2},
|
||||
} {
|
||||
id, err := cutReply([]string{dir}, "S", c.line, c.msg)
|
||||
if err != nil {
|
||||
@@ -473,4 +614,10 @@ func TestClaudeCutReplyKeepsTheWholeReply(t *testing.T) {
|
||||
if id, err := cutReply([]string{dir}, "S", "zz", "msg_none"); err == nil {
|
||||
t.Errorf("a cut at no line nor reply: %s, want an error", id)
|
||||
}
|
||||
if id, err := cutReply([]string{dir}, "S", "", "msg_none"); err == nil {
|
||||
t.Errorf("a cut at no line and a reply not in the session: %s, want an error", id)
|
||||
}
|
||||
if id, err := cutReply([]string{dir}, "S", "", ""); err == nil {
|
||||
t.Errorf("a cut at neither a line nor a reply: %s, want an error", id)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user