diff --git a/internal/gateway/claude_subscription.go b/internal/gateway/claude_subscription.go index 02905b690..ee2432b74 100644 --- a/internal/gateway/claude_subscription.go +++ b/internal/gateway/claude_subscription.go @@ -266,8 +266,11 @@ type subscriptionRun struct { behindTurn string // behindLine is the session line the conversation at behindKey ends // at: the interactive mode, which can't be taken back, is branched - // off its session there (resume) + // off its session there (resume). behindMsg is the id of the reply + // that line is of: the cut goes after that reply's last line, which + // the interactive mode may tell after the turn ended (cutReply) behindLine string + behindMsg string // endWhy is why magpie ended it, as the log of a turn that finds it // gone says (abortFor); results are the calls whose results it was // last handed (continueWith) @@ -374,9 +377,16 @@ type subscriptionRun struct { parkedSeq int // lastLine is the session line of the reply it wrote last, and // backLine lastLine as the turn it was resumed for began: the - // conversation at backKey ends there. Under mu. + // conversation at backKey ends there. lastMsg is the id of the reply + // heard last, and backMsg lastMsg as the turn began: the interactive + // mode streams a reply first and tells its session lines after, read + // from the file it writes, so a client that asks its next turn (a + // prompt suggestion) at once finds lastLine still a line before that + // reply (sleepy_shibe: the call before its result). Under mu. lastLine string backLine string + lastMsg string + backMsg string } // callLine is the session line of an assistant message block calling a @@ -1747,14 +1757,14 @@ func (b *subscriptionBridge) resume(req *Request, owner string) (*subscriptionRu } b.mu.Lock() run := b.idle[key] - back, at := "", "" // the turn the run is taken back from first, and the line before it + back, at, atMsg := "", "", "" // the turn the run is taken back from first, the line before it and its reply if run == nil { // the run went on with a turn this one doesn't follow: Claude // Code's side question, asked as the conversation so far and a // message more (#1638). It goes back to before that turn. for _, r := range b.idle { if r.behindKey == key && r.behindTurn != "" { - run, back, at = r, r.behindTurn, r.behindLine + run, back, at, atMsg = r, r.behindTurn, r.behindLine, r.behindMsg break } } @@ -1771,7 +1781,7 @@ func (b *subscriptionBridge) resume(req *Request, owner string) (*subscriptionRu if run != nil { delete(b.idle, run.idleKey) run.idleKey = "" - run.behindKey, run.behindTurn, run.behindLine = "", "", "" + run.behindKey, run.behindTurn, run.behindLine, run.behindMsg = "", "", "", "" } b.mu.Unlock() if run == nil { @@ -1790,7 +1800,7 @@ func (b *subscriptionBridge) resume(req *Request, owner string) (*subscriptionRu // a branch does, told only the turn. Let go, a new Claude Code was // told the whole conversation each turn Claude Code asked its // prompt suggestion after (bbfatx on X). - req.branch = run.branchAt(at, owner, since) + req.branch = run.branchAt(at, atMsg, owner, since) } if run.tui && (back != "" || urlImages(since) > 0) { // the interactive mode can't be taken back, nor pasted an image @@ -1841,7 +1851,7 @@ func (b *subscriptionBridge) resume(req *Request, owner string) (*subscriptionRu ch := make(chan Event, 64) run.segment = ch run.active = time.Now() - run.turnUUID, run.backKey, run.backLine = turn, key, run.lastLine + run.turnUUID, run.backKey, run.backLine, run.backMsg = turn, key, run.lastLine, run.lastMsg run.allowed = allowedTools(req) run.mu.Unlock() run.endIn(runTimeout) @@ -2148,9 +2158,9 @@ func (r *subscriptionRun) ended(req *Request, said, stop string, ok bool) { // the client's next request, its results sent again or the next turn, // found no run and a new one was told the whole conversation. r.mu.Lock() - turn, back, backLine := r.turnUUID, r.backKey, r.backLine + turn, back, backLine, backMsg := r.turnUUID, r.backKey, r.backLine, r.backMsg if !ok || stop != "tool" { - r.turnUUID, r.backKey, r.backLine = "", "", "" + r.turnUUID, r.backKey, r.backLine, r.backMsg = "", "", "", "" } if ok && stop == "stop" { r.replied = true @@ -2195,7 +2205,7 @@ func (r *subscriptionRun) ended(req *Request, said, stop string, ok bool) { // the conversation before this turn, when the run was resumed for // it: a side question Claude Code asked of it is taken back from // there when the conversation's own next turn comes (resume) - r.behindKey, r.behindTurn, r.behindLine = back, turn, backLine + r.behindKey, r.behindTurn, r.behindLine, r.behindMsg = back, turn, backLine, backMsg // the boundary before conv's: the conversation as the client has it, // when this turn was a side question of it, whose exchange the // client's own next turn leaves out @@ -2306,9 +2316,11 @@ type savedSession struct { // before the side question's own message, behindTurn, that a -p run // was told under magpie's uuid, or, for the interactive mode, which // names its messages itself, after behindLine, the reply before it + // (as far as that reply's last line, behindMsg) behind string behindTurn string behindLine string + behindMsg string loose *looseTurn tools map[string]bool // the tools its agent was told of at time.Time // since when it waits @@ -2345,7 +2357,7 @@ func (b *subscriptionBridge) shelve(run *subscriptionRun) { key := run.idleKey s := &savedSession{session: sid, sessions: sessions, owner: run.owned(), conv: run.convKey, key: key, behind: run.behindKey, loose: run.loose, tools: tools, at: run.idleAt, cachePrefix: run.cachePrefix, appended: run.appended} if run.tui { - s.behindLine = run.behindLine + s.behindLine, s.behindMsg = run.behindLine, run.behindMsg } else { s.behindTurn = run.behindTurn } @@ -2438,7 +2450,7 @@ func (s *savedSession) cutBehind() bool { var cut string var err error if s.behindLine != "" { - cut, err = cutSession(s.sessions, s.session, s.behindLine) + cut, err = cutReply(s.sessions, s.session, s.behindLine, s.behindMsg) } else { cut, err = cutSessionBefore(s.sessions, s.session, s.behindTurn) } @@ -2456,13 +2468,17 @@ func (s *savedSession) cutBehind() bool { // noteLines keeps where in the run's session a line calling the client's // tools ids was written: uuid, as Claude Code's output tells it. Claude // Code's own lines () are no reply's. -func (r *subscriptionRun) noteLines(uuid, model string, ids []string) { +// msg is the line's message id, when it wasn't streamed (replyBegun says so). +func (r *subscriptionRun) noteLines(uuid, model, msg string, ids []string) { if uuid == "" || model == "" { return } r.mu.Lock() defer r.mu.Unlock() r.lastLine = uuid + if msg != "" { + r.lastMsg = msg + } if len(ids) == 0 { return } @@ -2564,18 +2580,30 @@ func (b *subscriptionBridge) branch(req *Request, owner string) *savedSession { return nil } -// branchAt is a branch of the run's session cut after its line at, 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. -func (r *subscriptionRun) branchAt(at, owner string, since []Message) *savedSession { +// replyBegun notes a reply message as it begins: its lines in the session +// come later (lastMsg). +func (r *subscriptionRun) replyBegun(msg string) { + if msg == "" { + return + } + r.mu.Lock() + r.lastMsg = msg + r.mu.Unlock() +} + +// 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. +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 { return nil } - cut, err := cutSession(sessions, sid, at) + cut, err := cutReply(sessions, sid, at, msg) if err != nil { log.Printf("claude: the interactive run's session couldn't be cut before its side question (%v)", err) return nil @@ -2600,6 +2628,57 @@ func cutSession(dirs []string, sid, uuid string) (string, error) { return cutSessionAt(dirs, sid, uuid, cutAfter) } +// 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 +// mode tells a reply's lines only after its stream ended, so the line the +// 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. +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 { + if end := cutAfterReply(b, msg); end > 0 { + return end + } + return cutAfter(b, mark, uuid) + }) +} + +// cutAfterReply is where in a session's lines b the last whole assistant +// line of message msg ends, -1 when none is there. +func cutAfterReply(b []byte, msg string) int { + mark := []byte(`"id":"` + msg + `"`) + end := -1 + for at := 0; at < len(b); { + nl := bytes.IndexByte(b[at:], '\n') + if nl < 0 { + break + } + line := b[at : at+nl] + at += nl + 1 + if !bytes.Contains(line, mark) { + continue + } + var l struct { + Type string `json:"type"` + IsSidechain bool `json:"isSidechain"` + Message struct { + ID string `json:"id"` + } `json:"message"` + } + if json.Unmarshal(line, &l) == nil && l.Type == "assistant" && !l.IsSidechain && l.Message.ID == msg { + end = at + } + } + return end +} + // cutSessionBefore is cutSession as far as the line before uuid's: the // session as it stood before that message was told. func cutSessionBefore(dirs []string, sid, uuid string) (string, error) { @@ -3642,7 +3721,11 @@ func (r *subscriptionRun) readOutput(rd io.Reader) { ids = append(ids, c.ID) } } - r.noteLines(envelope.UUID, whole.Model, ids) + msg := "" + if !streamed[whole.ID] { + msg = whole.ID + } + r.noteLines(envelope.UUID, whole.Model, msg, ids) } // a message not streamed is told by its id: a streamed one's // whole messages come after its stream's events, under its id; @@ -3882,6 +3965,7 @@ func (r *subscriptionRun) readOutput(rd io.Reader) { switch e.Type { case "message_start": streamed[e.Message.ID] = true + r.replyBegun(e.Message.ID) begin(e.Message.ID, e.Message.Model, e.Message.Usage) case "content_block_start": switch e.ContentBlock.Type { diff --git a/internal/gateway/claude_subscription_prefix_test.go b/internal/gateway/claude_subscription_prefix_test.go index 9f10d9c14..82756c161 100644 --- a/internal/gateway/claude_subscription_prefix_test.go +++ b/internal/gateway/claude_subscription_prefix_test.go @@ -10,6 +10,7 @@ import ( "path/filepath" "regexp" "runtime" + "strconv" "strings" "testing" "time" @@ -27,6 +28,9 @@ import ( // T": H the lines its session had as it started (a branch's copy, or a // resumed session), T the turns it was told. A turn that says CALLTOOL // calls the client's read tool first and says what the call was answered. +// With a file "late" in its log folder, it tells each reply's message +// with its uuid a while after the reply's stream ended, as the +// interactive mode reads it from the session it wrote. type prefixHarness struct { t *testing.T s *Server @@ -79,7 +83,8 @@ say() { echo '{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"'"$1"'"}}}' echo '{"type":"stream_event","event":{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":1}}}' echo '{"type":"stream_event","event":{"type":"message_stop"}}' - echo '{"type":"assistant","uuid":"a'$$'-'$m'","sessionId":"'$sid'","message":{"role":"assistant","content":[{"type":"text","text":"'"$1"'"}]}}' >> "$f" + echo '{"type":"assistant","uuid":"a'$$'-'$m'","sessionId":"'$sid'","message":{"id":"m'$$'-'$m'","role":"assistant","content":[{"type":"text","text":"'"$1"'"}]}}' >> "$f" + if [ -f `+logs+`/late ]; then sleep 1; fi echo '{"type":"assistant","uuid":"a'$$'-'$m'","message":{"id":"m'$$'-'$m'","model":"claude-opus-5-5","content":[{"type":"text","text":"'"$1"'"}]}}' echo '{"type":"result","subtype":"success","is_error":false,"result":""}' } @@ -100,10 +105,14 @@ while read -r line; do echo '{"type":"stream_event","event":{"type":"content_block_stop","index":0}}' echo '{"type":"stream_event","event":{"type":"message_delta","delta":{"stop_reason":"tool_use"},"usage":{"output_tokens":3}}}' echo '{"type":"stream_event","event":{"type":"message_stop"}}' - echo '{"type":"assistant","uuid":"a'$$'-'$m'","sessionId":"'$sid'","message":{"role":"assistant","content":[{"type":"tool_use","id":"toolu_R'$$'_'$n'","name":"mcp__magpie__read","input":{}}]}}' >> "$f" + echo '{"type":"assistant","uuid":"a'$$'-'$m'","sessionId":"'$sid'","message":{"id":"m'$$'-'$m'","role":"assistant","content":[{"type":"tool_use","id":"toolu_R'$$'_'$n'","name":"mcp__magpie__read","input":{}}]}}' >> "$f" echo '{"type":"assistant","uuid":"a'$$'-'$m'","message":{"id":"m'$$'-'$m'","model":"claude-opus-5-5","content":[{"type":"tool_use","id":"toolu_R'$$'_'$n'","name":"mcp__magpie__read","input":{}}]}}' - got=$(curl --noproxy '*' -s -m 20 -X POST -H 'Content-Type: application/json' --data '{"tool_call_id":"toolu_R'$$'_'$n'","name":"read","arguments":{}}' "$cb") + # the call's id outside the command substitution: macOS's sh (bash + # 3.2) reads '$$' in one as $'…' and leaves the pid out + call='{"tool_call_id":"toolu_R'$$'_'$n'","name":"read","arguments":{}}' + got=$(curl --noproxy '*' -s -m 20 -X POST -H 'Content-Type: application/json' --data "$call" "$cb") case "$got" in *"No tool can be used"*) got=refused ;; *) got=answered ;; esac + echo '{"type":"user","uuid":"r'$$'-'$n'","sessionId":"'$sid'","message":{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_R'$$'_'$n'","content":"x"}]}}' >> "$f" say "pid $$ had $had turn $n call $got" continue ;; esac @@ -346,3 +355,122 @@ func TestClaudeInteractiveSideQuestionBranchesBeforeIt(t *testing.T) { t.Fatalf("the turn after: %q", got) } } + +// sleepy_shibe (magpie 0.1.2906, Claude Code 2.1.318): the interactive +// mode streams a reply and tells its session lines after, read from the +// file Claude Code writes. Claude Code asks its prompt suggestion the +// moment a turn's reply ends, so the run began the suggestion with the +// line it had heard last still the turn's tool call: the branch the next +// turn went on in was cut there, before the call's result and the reply, +// and Claude Code resumed it as U1, the call, "Tool call interrupted" +// and a reply. The branch goes as far as the reply's last +// line: the conversation the client has, the suggestion left out. +func TestClaudeInteractiveSideQuestionAfterACallKeepsTheReply(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", "read it. CALLTOOL") + _, body := h.ask(tools, `[`+u1+`]`) + id := regexp.MustCompile(`toolu_R\d+_\d+`).FindString(body) + if id == "" || !strings.Contains(body, `"tool_use"`) { + t.Fatalf("the first turn made no call: %.800s", body) + } + // the client runs the tool while Claude Code's call waits on it + eventually(t, "the run's call waits on the client", func() bool { + h.s.subscription.mu.Lock() + runs := make([]*subscriptionRun, 0, len(h.s.subscription.runs)) + for _, run := range h.s.subscription.runs { + runs = append(runs, run) + } + h.s.subscription.mu.Unlock() + for _, run := range runs { + run.mu.Lock() + _, waits := run.pending[id] + run.mu.Unlock() + if waits { + return true + } + } + return false + }) + call := `{"role":"assistant","content":[{"type":"tool_use","id":"` + id + `","name":"read","input":{}}]}` + result := `{"role":"user","content":[{"type":"tool_result","tool_use_id":"` + id + `","content":"package main"}]}` + conv := u1 + `,` + call + `,` + result + first, _ := h.ask(tools, `[`+conv+`]`) + pid := answerPID(t, first) + if first != "pid "+pid+" had 0 turn 1 call answered" { + t.Fatalf("the reply after the call's result: %q", first) + } + conv += `,` + 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, its call, the call's result and the reply: the + // suggestion's two lines left out + if branch == pid || next != "pid "+branch+" had 4 turn 1" { + t.Fatalf("the turn after the suggestion: %q (the conversation's run was %s, its session's turn has 4 lines before the suggestion)\n%s", next, pid, h.log(branch)) + } + log := h.log(branch) + if told := log[strings.Index(log, "\ntold "):]; strings.Contains(told, "CALLTOOL") || strings.Contains(told, "SUGGESTION") || !strings.Contains(told, "now commit it") { + t.Fatalf("the branch was told %.600s, want the new turn only", told) + } +} + +// 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 +// far as the reply's last line, past the call's result, and leaves the +// prompt suggestion and its answer out; a sub-agent's line of the same +// id (isSidechain) is no line of the reply. +func TestClaudeCutReplyKeepsTheWholeReply(t *testing.T) { + was := cutWait + cutWait = 50 * time.Millisecond + t.Cleanup(func() { cutWait = was }) + dir := t.TempDir() + // the shape of a Claude Code 2.1.318 session, trimmed + rows := []string{ + `{"parentUuid":null,"isSidechain":false,"userType":"external","cwd":"/w","sessionId":"S","version":"2.1.318","type":"user","message":{"role":"user","content":"read main.go"},"uuid":"u1","timestamp":"2026-11-03T10:00:00.000Z"}`, + `{"parentUuid":"u1","isSidechain":false,"userType":"external","cwd":"/w","sessionId":"S","version":"2.1.318","message":{"id":"msg_01A","type":"message","role":"assistant","model":"claude-opus-5-5","content":[{"type":"tool_use","id":"toolu_01","name":"mcp__magpie__read","input":{"path":"main.go"}}],"stop_reason":null},"requestId":"req_1","type":"assistant","uuid":"a1","timestamp":"2026-11-03T10:00:02.000Z"}`, + `{"parentUuid":"a1","isSidechain":false,"userType":"external","cwd":"/w","sessionId":"S","version":"2.1.318","type":"user","message":{"role":"user","content":[{"tool_use_id":"toolu_01","type":"tool_result","content":[{"type":"text","text":"package main"}]}]},"uuid":"r1","timestamp":"2026-11-03T10:00:05.000Z","toolUseResult":[{"type":"text","text":"package main"}]}`, + `{"parentUuid":"r1","isSidechain":false,"userType":"external","cwd":"/w","sessionId":"S","version":"2.1.318","message":{"id":"msg_01B","type":"message","role":"assistant","model":"claude-opus-5-5","content":[{"type":"thinking","thinking":"short file","signature":"sig"}],"stop_reason":null},"requestId":"req_2","type":"assistant","uuid":"a2","timestamp":"2026-11-03T10:00:06.000Z"}`, + `{"parentUuid":"a2","isSidechain":true,"userType":"external","cwd":"/w","sessionId":"S","version":"2.1.318","message":{"id":"msg_01B","type":"message","role":"assistant","model":"claude-opus-5-5","content":[{"type":"text","text":"a sub-agent's"}]},"type":"assistant","uuid":"x1","timestamp":"2026-11-03T10:00:06.500Z"}`, + `{"parentUuid":"a2","isSidechain":false,"userType":"external","cwd":"/w","sessionId":"S","version":"2.1.318","message":{"id":"msg_01B","type":"message","role":"assistant","model":"claude-opus-5-5","content":[{"type":"text","text":"It is a main package."}],"stop_reason":"end_turn"},"requestId":"req_2","type":"assistant","uuid":"a3","timestamp":"2026-11-03T10:00:07.000Z"}`, + `{"parentUuid":"a3","isSidechain":false,"userType":"external","cwd":"/w","sessionId":"S","version":"2.1.318","type":"system","subtype":"turn_duration","durationMs":7000,"uuid":"d1","timestamp":"2026-11-03T10:00:07.100Z"}`, + `{"parentUuid":"d1","isSidechain":false,"userType":"external","cwd":"/w","sessionId":"S","version":"2.1.318","type":"user","message":{"role":"user","content":` + strconv.Quote(suggestionMode) + `},"uuid":"u2","timestamp":"2026-11-03T10:00:07.300Z"}`, + `{"parentUuid":"u2","isSidechain":false,"userType":"external","cwd":"/w","sessionId":"S","version":"2.1.318","message":{"id":"msg_01C","type":"message","role":"assistant","model":"claude-opus-5-5","content":[{"type":"text","text":"run the tests"}],"stop_reason":"end_turn"},"requestId":"req_3","type":"assistant","uuid":"a4","timestamp":"2026-11-03T10:00:08.000Z"}`, + } + lines := strings.Join(rows, "\n") + "\n" + if err := os.WriteFile(filepath.Join(dir, "S.jsonl"), []byte(lines), 0o600); err != nil { + t.Fatal(err) + } + upTo := func(n int) string { + return strings.ReplaceAll(strings.Join(rows[:n], "\n")+"\n", `"sessionId":"S"`, `"sessionId":"ID"`) + } + for _, c := range []struct { + name, line, msg string + want int + }{ + {"the call heard last", "a1", "msg_01B", 6}, + {"the reply's first block heard last", "a2", "msg_01B", 6}, + {"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}, + } { + id, err := cutReply([]string{dir}, "S", c.line, c.msg) + if err != nil { + t.Fatalf("%s: %v", c.name, err) + } + got, _ := os.ReadFile(filepath.Join(dir, id+".jsonl")) + if want := strings.ReplaceAll(upTo(c.want), `"sessionId":"ID"`, `"sessionId":"`+id+`"`); string(got) != want { + t.Errorf("%s: copy\n%s\nwant\n%s", c.name, got, want) + } + } + 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) + } +}