claude: a reply the client keeps as several text blocks goes on in its run (#5705)
A run is kept idle under a key hashed from the conversation with its
reply as the one text it said (every text event run together). The
Anthropic encoder closes a text block at any other event: a thinking
block, a web search, cited text, an attempt Claude Code asked again. So
the client holds the reply as several text blocks and sends them back
that way. messageWords joined parts with a space, so the client's reply
read "Looking at it: Here" where the run's read "Looking at it:Here".
The keys differed, the loose-turn check failed too, and the next turn
logged "no run waits for this turn: no run here has had this
conversation". It was then told to a new Claude Code from a transcript,
which wrote the whole conversation to the cache again (jerrychoi: ~706K
tokens 56s after a cold rebuild, with the first run still alive).
The words hashed for a message now hold no whitespace. Where the client
spaces or splits its text no longer counts, for the turn key, the
conversation keys and the loose turn alike. lostMedia reads per-part
words (messageParts), which are unchanged.
Run (on mote, through mote-run, at b657a2121 + this change):
- go test -count=1 -timeout 45m ./internal/gateway: ok (890s)
- go test -run TestClaudeReplySplitIntoBlocksGoesOnInItsRun -count=3: ok
- GOOS=linux go vet ./internal/gateway, GOOS=windows go vet
./internal/gateway: clean; gofmt -l: clean
Broken by hand: with the old messageWords, the new test is red with the
reporter's exact line, "claude: no run waits for this turn: no run here
has had this conversation", followed by "a new Claude Code is told the
whole conversation: 3 messages".
Not tried: the reporter's own reply structure is not known. It may have
been thinking between texts, a web search or citation, or a retried
attempt; the issue asks for the block types. No real Claude account was
used. The test skips on Windows (a shell script stands in for Claude
Code). No full ./... run: the change is confined to internal/gateway.
Reported-by: jerrychoi
This commit is contained in:
@@ -0,0 +1,108 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"log"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/testenv"
|
||||
)
|
||||
|
||||
// A reply the client keeps as several text blocks — its words split by a
|
||||
// thinking block, a web search or an attempt Claude Code asked again —
|
||||
// goes on in its run at the next turn (#5705). The run was kept under its
|
||||
// reply as one text, the words run together where the client's blocks
|
||||
// meet ("Looking at it:Here"), and the client sent the same reply back as
|
||||
// two ("Looking at it: Here"): its conversation was none the run had, the
|
||||
// log said "no run here has had this conversation", and a new Claude Code
|
||||
// was told all of it from a transcript, writing ~706K tokens to the cache
|
||||
// again 56s after the turn before had written them (jerrychoi).
|
||||
func TestClaudeReplySplitIntoBlocksGoesOnInItsRun(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("a shell script stands in for Claude Code")
|
||||
}
|
||||
dir := t.TempDir()
|
||||
ev := func(e string) string { return `echo '{"type":"stream_event","event":` + e + `}'` }
|
||||
script := `#!/bin/sh
|
||||
n=0
|
||||
while read -r line; do
|
||||
n=$((n+1))
|
||||
` + ev(`{"type":"message_start","message":{"id":"m'$n'","model":"claude-opus-5-5","usage":{"input_tokens":1}}}`) + `
|
||||
if [ $n = 1 ]; then
|
||||
` + ev(`{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`) + `
|
||||
` + ev(`{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Looking at it:"}}`) + `
|
||||
` + ev(`{"type":"content_block_stop","index":0}`) + `
|
||||
` + ev(`{"type":"content_block_start","index":1,"content_block":{"type":"thinking","thinking":"","signature":""}}`) + `
|
||||
` + ev(`{"type":"content_block_delta","index":1,"delta":{"type":"thinking_delta","thinking":"the rest"}}`) + `
|
||||
` + ev(`{"type":"content_block_delta","index":1,"delta":{"type":"signature_delta","signature":"sig"}}`) + `
|
||||
` + ev(`{"type":"content_block_stop","index":1}`) + `
|
||||
` + ev(`{"type":"content_block_start","index":2,"content_block":{"type":"text","text":""}}`) + `
|
||||
` + ev(`{"type":"content_block_delta","index":2,"delta":{"type":"text_delta","text":"Here is the answer."}}`) + `
|
||||
` + ev(`{"type":"content_block_stop","index":2}`) + `
|
||||
else
|
||||
` + ev(`{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`) + `
|
||||
` + ev(`{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"pid '$$' turn '$n'"}}`) + `
|
||||
` + ev(`{"type":"content_block_stop","index":0}`) + `
|
||||
fi
|
||||
` + ev(`{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":3}}`) + `
|
||||
` + ev(`{"type":"message_stop"}`) + `
|
||||
echo '{"type":"result","subtype":"success","is_error":false,"result":""}'
|
||||
done
|
||||
`
|
||||
testenv.Program(t, filepath.Join(dir, "claude"), script)
|
||||
t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))
|
||||
runsEndWithTest(t, dir)
|
||||
var logs bytes.Buffer
|
||||
log.SetOutput(&logs)
|
||||
t.Cleanup(func() { log.SetOutput(os.Stderr) })
|
||||
|
||||
s := New()
|
||||
t.Cleanup(s.subscription.abortAll)
|
||||
p := provider.Provider{ID: "claude", Account: &provider.Account{Agent: "claude", User: "u"}}
|
||||
ask := func(msgs string) json.RawMessage {
|
||||
t.Helper()
|
||||
body := `{"model":"claude-opus-5-5","max_tokens":100,"system":"be brief","tools":[{"name":"read","input_schema":{"type":"object"}}],"messages":` + msgs + `}`
|
||||
rec := httptest.NewRecorder()
|
||||
var u Usage
|
||||
if code, msg := s.serveClaudeSubscription(rec, httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body)), provider.Anthropic, p, "claude-opus-5-5", []byte(body), &u); code != 200 {
|
||||
t.Fatalf("%d %s", code, msg)
|
||||
}
|
||||
var res struct {
|
||||
Content json.RawMessage `json:"content"`
|
||||
}
|
||||
if json.Unmarshal(rec.Body.Bytes(), &res) != nil || len(res.Content) == 0 {
|
||||
t.Fatalf("no answer: %s", rec.Body)
|
||||
}
|
||||
return res.Content
|
||||
}
|
||||
first := `{"role":"user","content":"hi"}`
|
||||
reply := ask(`[` + first + `]`)
|
||||
// the client is told the reply as Anthropic would have: two text
|
||||
// blocks with the thinking between them
|
||||
var blocks []struct{ Type, Text string }
|
||||
json.Unmarshal(reply, &blocks)
|
||||
var types []string
|
||||
for _, b := range blocks {
|
||||
types = append(types, b.Type)
|
||||
}
|
||||
if strings.Join(types, ",") != "text,thinking,text" {
|
||||
t.Fatalf("the reply's blocks: %s", reply)
|
||||
}
|
||||
// and sends it back as it was told it, with the next turn
|
||||
next := ask(`[` + first + `,{"role":"assistant","content":` + string(reply) + `},{"role":"user","content":"and?"}]`)
|
||||
var got []struct{ Text string }
|
||||
json.Unmarshal(next, &got)
|
||||
if len(got) != 1 || !strings.HasSuffix(got[0].Text, " turn 2") {
|
||||
t.Fatalf("the next turn went to a new Claude Code: %s\n%s", next, logs.String())
|
||||
}
|
||||
if strings.Contains(logs.String(), "no run waits for this turn") {
|
||||
t.Fatalf("log:\n%s", logs.String())
|
||||
}
|
||||
}
|
||||
@@ -3342,8 +3342,8 @@ func (r *subscriptionRun) park() {
|
||||
// turnKey is what a conversation has been so far, for the run that had it
|
||||
// to be found again: whom it runs as, the model, its settings and tools,
|
||||
// and the messages' words, tool calls and results. Whitespace, thinking and
|
||||
// how a reply is split into messages are left out, as clients keep those
|
||||
// differently. Its effort is not in it, only whether it asked for one (or
|
||||
// how a reply is split into messages or text blocks are left out, as
|
||||
// clients keep those differently. Its effort is not in it, only whether it asked for one (or
|
||||
// turned thinking off, which its Claude Code was started with): a
|
||||
// run is told another level as its turn starts (setEffort), where one
|
||||
// started anew would write the whole conversation to the cache again (#502).
|
||||
@@ -3422,6 +3422,15 @@ func (r *subscriptionRun) follows(msgs []Message) bool {
|
||||
// answers, not by their ids: a client may name the calls it was told with
|
||||
// ids of its own, the same in every request after (AmpCode's TU-…), and its
|
||||
// conversation is the same one all the same.
|
||||
//
|
||||
// Its words have no whitespace in them at all (messageWords), so where a
|
||||
// reply's text is split into blocks is left out too: the run keeps its
|
||||
// reply as the one text it said, and the client as Anthropic's stream told
|
||||
// it, a block for each run of words between a thinking block, a web search
|
||||
// or an attempt Claude Code asked again. Read with a space where its blocks
|
||||
// met ("Looking at it: Here" for "Looking at it:Here"), the client's
|
||||
// conversation was none the run had, and the next turn was told to a new
|
||||
// Claude Code, all of it written to the cache again (#5705).
|
||||
func hashMessages(h hash.Hash, msgs []Message, after func(i int)) {
|
||||
role := ""
|
||||
for i, words := range messageWords(msgs) {
|
||||
@@ -3430,7 +3439,7 @@ func hashMessages(h hash.Hash, msgs []Message, after func(i int)) {
|
||||
role = m.Role
|
||||
fmt.Fprintf(h, "\x00%s:", role)
|
||||
}
|
||||
h.Write([]byte(words + " "))
|
||||
h.Write([]byte(words))
|
||||
}
|
||||
if after != nil {
|
||||
after(i)
|
||||
@@ -3439,15 +3448,18 @@ func hashMessages(h hash.Hash, msgs []Message, after func(i int)) {
|
||||
}
|
||||
|
||||
// messageWords is each message's words, tool calls and results, as
|
||||
// hashMessages reads them.
|
||||
// hashMessages reads them: with no whitespace, so neither how the client
|
||||
// spaced them nor where it split them into blocks or messages counts.
|
||||
func messageWords(msgs []Message) []string {
|
||||
out := make([]string, len(msgs))
|
||||
for i, parts := range messageParts(msgs) {
|
||||
words := make([]string, len(parts))
|
||||
for k, p := range parts {
|
||||
words[k] = p.words
|
||||
var b strings.Builder
|
||||
for _, p := range parts {
|
||||
for _, f := range strings.Fields(p.words) {
|
||||
b.WriteString(f)
|
||||
}
|
||||
}
|
||||
out[i] = strings.Join(words, " ")
|
||||
out[i] = b.String()
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user