diff --git a/docs/subsystems/claude-subscription-bridge.md b/docs/subsystems/claude-subscription-bridge.md index 93657c7fd..ba636294a 100644 --- a/docs/subsystems/claude-subscription-bridge.md +++ b/docs/subsystems/claude-subscription-bridge.md @@ -712,8 +712,16 @@ history to the 1h cache at 2×. file of two lines, a user line holding the conversation before that reply as below (its images as image blocks, client cache marks taken out) and an assistant line holding the reply's words (thinking left - out). The run starts with `--resume` on it and is typed only the turns - after the reply, as a saved session's run is (the session is + out). The user line tells every message before the reply inside + ``, with no `` + (`renderClaudePromptAt` with the split at the end): the reply answers + the last of them, and the turn to answer is the one typed after it. + Before 11-04 the user line was rendered as a first message, so the + turn the reply answers was marked ``, "the turn to answer + now", and a resumed run answered an old question again or said its + tool calls had no results (愛睏柴犬阿茶 on Discord, + `TestClaudeTUIReplayMarksNoEarlierTurnCurrent`). The run starts with + `--resume` on it and is typed only the turns after the reply, as a saved session's run is (the session is discarded if the run doesn't take it). The file goes in the project folder of the work folder with its links followed, which is the one Claude Code reads (on a Mac `/var` is `/private/var`). Before 11-01 diff --git a/internal/gateway/claude_replay.go b/internal/gateway/claude_replay.go index d23f4abf4..89c89212b 100644 --- a/internal/gateway/claude_replay.go +++ b/internal/gateway/claude_replay.go @@ -22,12 +22,13 @@ import ( // // The session is two lines, the ones a run started at the reply's turn // would have written: the user's, the conversation before the reply as -// renderClaudePrompt tells it (the reply's turn marked as the one to -// answer; the caller's instructions not in it when the run has them after -// Claude Code's system prompt, req.appendPrompt), and the assistant's, the -// reply's words. nil when there is no -// such reply (none that calls no tool, or one with no words), or the file -// can't be written; the run is then told the conversation whole. +// renderClaudePrompt tells it, every turn of it as history (none marked as +// the one to answer: that is the turn typed after the reply; the caller's +// instructions not in it when the run has them after Claude Code's system +// prompt, req.appendPrompt), and the assistant's, the reply's words. nil +// when there is no such reply (none that calls no tool, or one with no +// words), or the file can't be written; the run is then told the +// conversation whole. func replaySession(dirs []string, work, model string, req *Request) *savedSession { split := historyEnd(req.Messages) if split < 2 || len(dirs) == 0 { @@ -41,7 +42,13 @@ func replaySession(dirs []string, work, model string, req *Request) *savedSessio before.Messages = req.Messages[:split-1] // Claude Code puts its own marks on what it sends before.clientCache = nil - blocks, err := renderClaudePrompt(&before) + // every turn before the reply is history, the last of them the one the + // reply answers: none is the turn to answer, which is typed after it. + // Rendered as a first message (renderClaudePrompt's own split), the + // turn the reply answers was marked , "the turn to answer + // now", and the resumed run answered it again, or said its tool calls + // had no results (愛睏柴犬阿茶 on Discord) + blocks, err := renderClaudePromptAt(&before, len(before.Messages)) if err != nil { return nil } diff --git a/internal/gateway/claude_subscription.go b/internal/gateway/claude_subscription.go index ebb5c43c3..02905b690 100644 --- a/internal/gateway/claude_subscription.go +++ b/internal/gateway/claude_subscription.go @@ -4077,6 +4077,15 @@ func (u cliUsage) gateway() Usage { } func renderClaudePrompt(req *Request) ([]map[string]any, error) { + return renderClaudePromptAt(req, historyEnd(req.Messages)) +} + +// renderClaudePromptAt is renderClaudePrompt with the turn to answer +// beginning at split. split == len(req.Messages) tells every message as +// history, with no turn to answer: a transcript's user line before its +// reply (replaySession), which answers the last of them, while the turn to +// answer is typed after it. +func renderClaudePromptAt(req *Request, split int) ([]map[string]any, error) { var blocks []map[string]any var text strings.Builder // a lean run has them as its system prompt (leanSystem), an appending @@ -4125,7 +4134,7 @@ func renderClaudePrompt(req *Request) ([]map[string]any, error) { // after the last reply that calls no tool, as nextTurn splits it). Told // as one stretch of Human:/Assistant: text, the images of earlier turns // read as just sent, and the model answered them again (#1365). - split := historyEnd(req.Messages) + whole := split > 0 && split == len(req.Messages) // The history is told in chunks, each a block of its own (historyChunk). // A conversation with no reply that calls no tool, as a sub-agent's // loop of tool calls (Claude Code's AgentSummary asks a summary of one @@ -4163,7 +4172,10 @@ func renderClaudePrompt(req *Request) ([]map[string]any, error) { if slices.ContainsFunc(req.Messages, callsTool) { text.WriteString(pastCallsNote + "\n\n") } - if split > 0 { + switch { + case whole: + text.WriteString("") + case split > 0: text.WriteString("") } // The one mark a run's first message may have (Claude Code keeps three diff --git a/internal/gateway/claude_tui_replay_test.go b/internal/gateway/claude_tui_replay_test.go index 5fde47aab..1d8e73735 100644 --- a/internal/gateway/claude_tui_replay_test.go +++ b/internal/gateway/claude_tui_replay_test.go @@ -116,3 +116,101 @@ func TestClaudeTUIReplayOnlyWithAReply(t *testing.T) { } } } + +// A transcript's user line is the turns before its reply, all of them +// told as history: the reply answers the last of them, and the turn the +// run is to answer is the one typed after it. Rendered as a first +// message, the user line marked the turn its reply answers as the +// , "the turn to answer now", so a run resumed on +// U0 A0 U1 A1 and typed U2 saw U1, answered already, as the one to +// answer: the model answered an old question again, or said earlier tool +// calls had no results (愛睏柴犬阿茶 on Discord). +func TestClaudeTUIReplayMarksNoEarlierTurnCurrent(t *testing.T) { + user := func(s string) Message { return Message{Role: "user", Parts: []Part{{Kind: Text, Text: s}}} } + reply := func(s string) Message { return Message{Role: "assistant", Parts: []Part{{Kind: Text, Text: s}}} } + call := func(id string) Message { + return Message{Role: "assistant", Parts: []Part{{Kind: ToolCall, ID: id, Name: "read", Args: json.RawMessage(`{}`)}}} + } + result := func(id, s string) Message { + return Message{Role: "user", Parts: []Part{{Kind: ToolResult, CallID: id, Text: s}}} + } + for _, tc := range []struct { + name string + msgs []Message + told []string // in the transcript's user line + reply string // its assistant line + typed int // messages typed after it + }{ + {"two turns", []Message{user("U1 first ask"), reply("A1 answer"), user("U2 newest ask")}, + []string{"U1 first ask"}, "A1 answer", 1}, + {"three turns", []Message{user("U0 first ask"), reply("A0 answer"), user("U1 second ask"), reply("A1 answer"), user("U2 newest ask")}, + []string{"U0 first ask", "A0 answer", "U1 second ask"}, "A1 answer", 1}, + {"tool results", []Message{ + user("U0 first ask"), call("c0"), result("c0", "R0 result"), reply("A0 answer"), + user("U1 second ask"), call("c1"), result("c1", "R1 result"), reply("A1 answer"), + user("U2 newest ask")}, + []string{"U0 first ask", "R0 result", "A0 answer", "U1 second ask", "R1 result"}, "A1 answer", 1}, + {"tool results only before the reply", []Message{ + user("U1 first ask"), call("c1"), result("c1", "R1 result"), reply("A1 answer"), user("U2 newest ask")}, + []string{"U1 first ask", "R1 result"}, "A1 answer", 1}, + {"the client's calls after the reply", []Message{ + user("U0 first ask"), reply("A0 answer"), user("U1 second ask"), reply("A1 answer"), + user("U2 newest ask"), call("c2"), result("c2", "R2 result")}, + []string{"U0 first ask", "A0 answer", "U1 second ask"}, "A1 answer", 3}, + } { + t.Run(tc.name, func(t *testing.T) { + dir := t.TempDir() + req := &Request{System: "rules", Tools: []Tool{{Name: "read"}}, Messages: tc.msgs} + s := replaySession([]string{dir}, dir, "claude-sonnet-5", req) + if s == nil { + t.Fatal("no transcript") + } + b, err := os.ReadFile(filepath.Join(dir, s.session+".jsonl")) + s.discard() + if err != nil { + t.Fatal(err) + } + if len(s.since) != tc.typed { + t.Fatalf("typed %d messages, want %d", len(s.since), tc.typed) + } + if got := s.since[0].Parts[0].Text; got != "U2 newest ask" { + t.Fatalf("typed %q first, want the newest ask", got) + } + lines := strings.Split(strings.TrimSpace(string(b)), "\n") + if len(lines) != 2 { + t.Fatalf("the transcript:\n%s", b) + } + var first, second struct { + Message struct { + Content []map[string]any `json:"content"` + } `json:"message"` + } + if json.Unmarshal([]byte(lines[0]), &first) != nil || json.Unmarshal([]byte(lines[1]), &second) != nil { + t.Fatalf("the transcript:\n%s", b) + } + var told strings.Builder + for _, c := range first.Message.Content { + s, _ := c["text"].(string) + told.WriteString(s) + } + text := told.String() + if strings.Contains(text, "current_turn") || strings.Contains(text, "turn to answer now") { + t.Fatalf("the transcript marks a turn its reply answers as the one to answer now:\n%s", text) + } + if open := strings.Index(text, historyOpen); open < 0 || open > strings.Index(text, tc.told[0]) || !strings.HasSuffix(strings.TrimSpace(text), "") { + t.Fatalf("the transcript's turns aren't told as history:\n%s", text) + } + for _, w := range tc.told { + if !strings.Contains(text, w) { + t.Fatalf("the transcript's user line doesn't have %q:\n%s", w, text) + } + } + if strings.Contains(text, "newest ask") || strings.Contains(text, tc.reply) { + t.Fatalf("the transcript's user line has the reply or the turn after it:\n%s", text) + } + if got, _ := second.Message.Content[0]["text"].(string); got != tc.reply { + t.Fatalf("the transcript's reply is %q, want %q", got, tc.reply) + } + }) + } +}