diff --git a/docs/subsystems/claude-subscription-bridge.md b/docs/subsystems/claude-subscription-bridge.md index 9b22b15d6..1dc98997b 100644 --- a/docs/subsystems/claude-subscription-bridge.md +++ b/docs/subsystems/claude-subscription-bridge.md @@ -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 diff --git a/internal/gateway/claude_subscription.go b/internal/gateway/claude_subscription.go index a767ff068..c6bf3df99 100644 --- a/internal/gateway/claude_subscription.go +++ b/internal/gateway/claude_subscription.go @@ -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) } } } diff --git a/internal/gateway/claude_subscription_prefix_test.go b/internal/gateway/claude_subscription_prefix_test.go index 82756c161..713888224 100644 --- a/internal/gateway/claude_subscription_prefix_test.go +++ b/internal/gateway/claude_subscription_prefix_test.go @@ -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) + } }