gateway: a Claude subscription run is told the user's words after a tool result as theirs, not the tool's (#1878)

JinJieBeWater found that Claude Code's AgentSummary label request ("Describe
your most recent action in 3-5 words. Do not use tools.", sent as a text
block after the sub-agent's last tool_result) reached the inner Claude as
tool output, so it went on with the task instead of answering the label.

Two paths had it:

- renderParts (a run started anew, or a resumed turn) wrote the text right
  after the tool's last line. A text or file part after a tool result in the
  same message now closes it with "[end of tool result id=…]" and is marked
  "[user message]". A result followed by nothing or by another result is
  told as before, so existing prompts and their cache prefix don't change.
- match folded the text into the last result, and continueWith handed it to
  Claude Code as the MCP result. It no longer folds; saidWithResults takes
  the words, and continueWith writes them to Claude Code's stdin as a user
  message before handing the results over, waiting for Claude Code's
  command_lifecycle "queued" for that uuid (2s at most). Claude Code then
  tells its model the message with the result as one the user sent while it
  worked, in the same turn.

Going on in the run, rather than starting a new one for such requests, keeps
the cache prefix (#1716/#1717) and #872's mid-turn messages, which use the
same shape. #872's text is now queued as the user's instead of appended to
the result. Words in a message that holds images (pi-ai's "Attached
image(s) from tool result:" captions) still fold into the result, decided by
the message's parts, not its text. A tool whose output says "Do not use
tools." keeps it inside its result. The fork test's fake Claude now models
mid-turn absorption the way Claude Code does.

Run: gofmt -l; go vet on darwin, linux (-tags nogui), windows for
./internal/gateway; go test -tags nogui ./internal/gateway/ -count=1 green;
-race -count=3 on the new tests. Broken by hand, each red: no end marker;
an end marker after every result; the words not passed to continueWith; the
old fold into the result; the words queued after the result is handed over.
Real Claude Code 2.1.296 driven through the gateway in a sandbox HOME
against a local mock of Anthropic: on continuation the next request's
tool_result holds "SOURCE_LAST_LINE" then the "user sent a new message
while you were working" reminder with the label request; on a new run the
prompt holds the closed result and "[user message]".

Not run: the owner's real Claude subscription (its credentials are in the
Keychain, off-limits here), so the real model's answer to the label isn't
seen; Windows tests; the full ./... suite.
This commit is contained in:
yetone
2026-10-13 07:44:34 +08:00
parent f230fa23b0
commit 5b14ebf49a
7 changed files with 450 additions and 55 deletions
+45 -1
View File
@@ -308,6 +308,50 @@ there and gets a run started anew (`answeredElsewhere` in the log). It is
never refused: Claude Code doesn't retry a 409, and the agent that sent it
stops (ylorn on Discord).
## The user's words beside tool results (#872, #1878)
A user message can hold tool results and, after them, text blocks of the
user's: Claude Code's AgentSummary asks for its sub-agent's progress label
that way ("Describe your most recent action in 3-5 words. Do not use
tools.", JinJieBeWater), a fork its directive, and an older Claude Code a
message sent while a tool ran (#872). The words are the user's, and both
ways a run is told them keep them apart from the tool's output:
- **A run told the messages as text** (`renderParts`, for a run started
anew and for a resumed turn): a text or file part after a tool result in
the same message closes the result, `[end of tool result id=…]`, and is
marked `[user message]`. Before, it ran on after the tool's last line
(`SOURCE_LAST_LINEDescribe your…`), and the model read it as tool output
and went on with the task. A result followed by nothing, or by another
result, is told as before.
- **Results that go on in their run** (`match`, `continueWith`): `match`
no longer adds the words to the last result's text, which made them part
of the MCP result. `saidWithResults` takes them, and `continueWith`
writes them to Claude Code's input as a user message (`queue`) before it
hands the results over, and waits for Claude Code's `command_lifecycle`
"queued" for that message's uuid (at most `queuedWait`, 2s; a version
that doesn't say goes on after it). Claude Code then tells its model the
message with the result, as one the user sent while it worked ("The user
sent a new message while you were working: …"), within the turn. Tried
with the real Claude Code 2.1.296 against a local mock of Anthropic: the
next request holds the tool's output, then that reminder, and the turn
ends with one `result`. Handed over after the results, a message could
come after the model's reply and start a turn of its own.
Where the result ends is said by the message's parts alone. A tool whose
output says "Do not use tools." has it told as its output, inside the
result. The words of a message that holds images (pi-ai's "Attached
image(s) from tool result:" over Chat, #1382) still go with the result
before them, with the images.
A request with words beside the results still takes the run waiting on
the calls when it comes first (`claimResume`). An AgentSummary that does
is answered in the sub-agent's run, and the sub-agent's own next request
then gets a run started anew, as any request after another answered the
calls does. Starting such a request anew instead would tell the whole
conversation to a new run, a prefix the cache has never seen (#1716,
#1717), for every message sent mid-turn.
## The account's allowance on the reply (#1257)
Claude Code tells a run's account allowance in its stream-json
@@ -333,7 +377,7 @@ carries none.
```sh
go test -tags nogui ./internal/claudecode/ -count=1
go test -tags nogui ./internal/gateway/ -run 'ClaudeSubscriptionRunsTheDownloaded|ClaudeSubscriptionWithoutClaudeCode|ClaudeRewritten|LostMedia|ImagesTakenOut|RunLetGoWhenTheClientRewrote|ClaudeSessionTempFiles|ClaudeLetGo|ClaudeSessionFiles|ClaudeOldSessions|ClaudeSubscriptionReplySaysTheAllowance|ClaudeAllowanceHeaders|ClaudeForksAnsweringTheLeadsCalls|ClaudeTurnGivenUpOn|ClaudeToolResultsGivenUpOn|ClaudePromptMarksEarlierTurns|ClaudeUnloadableSession|ClaudeEndedRunSaysWhy|ClaudeIdle|ClaudeSideQuestion|ClaudeNoRunSaysWhy|ClaudeToolResultsNoRunSaysWhy' -count=1
go test -tags nogui ./internal/gateway/ -run 'ClaudeSubscriptionRunsTheDownloaded|ClaudeSubscriptionWithoutClaudeCode|ClaudeRewritten|LostMedia|ImagesTakenOut|RunLetGoWhenTheClientRewrote|ClaudeSessionTempFiles|ClaudeLetGo|ClaudeSessionFiles|ClaudeOldSessions|ClaudeSubscriptionReplySaysTheAllowance|ClaudeAllowanceHeaders|ClaudeForksAnsweringTheLeadsCalls|ClaudeTurnGivenUpOn|ClaudeToolResultsGivenUpOn|ClaudePromptMarksEarlierTurns|ClaudeUnloadableSession|ClaudeEndedRunSaysWhy|ClaudeIdle|ClaudeSideQuestion|ClaudeNoRunSaysWhy|ClaudeToolResultsNoRunSaysWhy|ClaudePromptToldUserText|ClaudePromptKeepsInstructions|ClaudeToolResultsGoOnWithTheUsersWords|ClaudeToolResultsKeepInstructions|ToolResultKeepsUserTextSentMidTurn' -count=1
```
`claude_rewritten_test.go` has a case for each relaxation and one for each
+1 -1
View File
@@ -733,7 +733,7 @@ func TestClaudeBridgeSafeguardConcurrentHandoff(t *testing.T) {
}
blocked("a")
waiter := run.pending["a"]
segment, err := run.continueWith(results, nil)
segment, err := run.continueWith(results, "", nil)
if err != nil || (<-waiter).Content[0]["text"] != "A" {
t.Fatalf("first handoff: %v", err)
}
+127 -7
View File
@@ -252,6 +252,13 @@ type subscriptionRun struct {
// result, while the client ran both and sent both results back at once.
early map[string]mcpToolResult
// queued is the user's words sent with tool results, written to Claude
// Code's input as a message of their own while it waits on the calls,
// by the message's uuid: closed once Claude Code says it queued it
// (its command_lifecycle), so it is in hand before the results are
// (continueWith, #1878)
queued map[string]chan struct{}
// asked is the client's tools its reply called, and parkedAt when it
// began waiting on them
asked []string
@@ -2112,6 +2119,10 @@ func (r *subscriptionRun) readOutput(rd io.Reader) {
RateLimitInfo json.RawMessage `json:"rate_limit_info"`
// Claude Code's answer to a control request (rewind)
Response json.RawMessage `json:"response"`
// a user message it took from its input, by the uuid it was
// given, and where it is: queued, started, completed
CommandUUID string `json:"command_uuid"`
State string `json:"state"`
// an assistant message, one of its blocks at a time; raw, as
// a user message's content may be a string
Message json.RawMessage `json:"message"`
@@ -2177,6 +2188,15 @@ func (r *subscriptionRun) readOutput(rd io.Reader) {
r.answered(envelope.Response)
return
}
if envelope.Type == "command_lifecycle" {
r.mu.Lock()
if ch := r.queued[envelope.CommandUUID]; ch != nil {
close(ch)
delete(r.queued, envelope.CommandUUID)
}
r.mu.Unlock()
return
}
if envelope.Type == "system" && envelope.Subtype == "init" && envelope.SessionID != "" {
r.mu.Lock()
r.sessionID = envelope.SessionID
@@ -2598,8 +2618,20 @@ func renderClaudeTurn(msgs []Message, tools []Tool) []map[string]any {
// renderParts writes the parts as text, a call of one of the offered tools
// under the name the run can call it by (bridgeName). A call of a tool the
// caller doesn't offer (its framework's own) keeps its name.
//
// The user's words after a tool result in the same message (Claude Code's
// AgentSummary asks for its label that way) are the user's, not the tool's:
// the result is closed and the words marked as the user's. Run on after the
// tool's last line, the model read them as tool output and went on with the
// task (#1878). Only the message's parts say where the result ends; what the
// tool wrote stays inside it, whatever it says.
func renderParts(blocks []map[string]any, text *strings.Builder, parts []Part, offered map[string]bool) []map[string]any {
open := "" // the tool result told last, not closed yet
for _, p := range parts {
if open != "" && (p.Kind == Text || p.Kind == File) {
fmt.Fprintf(text, "\n[end of tool result id=%s]\n\n[user message]\n", open)
open = ""
}
switch p.Kind {
case Text:
text.WriteString(p.Text)
@@ -2615,6 +2647,7 @@ func renderParts(blocks []map[string]any, text *strings.Builder, parts []Part, o
fmt.Fprintf(text, "\n[tool call %s id=%s args=%s]", name, p.ID, argsString(p))
case ToolResult:
fmt.Fprintf(text, "\n[tool result id=%s%s]\n%s", p.CallID, map[bool]string{true: " error"}[p.IsError], p.Text)
open = p.CallID
// the images the tool returned follow its text
for _, im := range p.Images {
blocks = imageBlocks(blocks, text, im)
@@ -2685,16 +2718,19 @@ func (b *subscriptionBridge) match(req *Request) (*subscriptionRun, []Part, stri
}
var fresh, loose []Part
for _, m := range req.Messages[i:] {
captions := withImages(m)
for _, p := range m.Parts {
switch {
case p.Kind == ToolResult:
p.Images = slices.Clone(p.Images)
fresh = append(fresh, p)
case p.Kind == Text && len(fresh) > 0:
// Claude Code puts a message the user sends while a tool is
// running beside that tool_result (usually as a system reminder).
// A resumed subscription run only receives its MCP result, so keep
// the adjacent text with it instead of silently dropping the turn.
case p.Kind == Text && len(fresh) > 0 && captions:
// the words of a message of the results' images, which go
// with the result before them: pi-ai's "Attached image(s)
// from tool result:" over Chat. The user's own words, in a
// message with no images, are not the tool's: continueWith
// tells them as a message of the user's (saidWithResults,
// #872, #1878).
last := &fresh[len(fresh)-1]
if last.Text != "" && p.Text != "" {
last.Text += "\n\n"
@@ -2876,13 +2912,67 @@ func (r *subscriptionRun) offers(tools []Tool) bool {
return true
}
// saidWithResults is the user's words after tool results in the messages
// since the last reply: a message the user sent while a tool ran (#872),
// or what a request forked from the conversation asks (Claude Code's
// AgentSummary, #1878). The words of a message with images go with the
// results (match), as before. "" when there are no results, or no words.
func saidWithResults(msgs []Message) string {
i := len(msgs)
for i > 0 && msgs[i-1].Role != "assistant" {
i--
}
var said []string
results := false
for _, m := range msgs[i:] {
captions := withImages(m)
for _, p := range m.Parts {
switch {
case p.Kind == ToolResult:
results = true
case p.Kind == Text && results && !captions && strings.TrimSpace(p.Text) != "":
said = append(said, p.Text)
}
}
}
if !results {
return ""
}
return strings.Join(said, "\n\n")
}
// withImages says m has an image of its own, not in a tool result.
func withImages(m Message) bool {
return slices.ContainsFunc(m.Parts, func(p Part) bool { return p.Kind == Image })
}
// queuedWait is how long continueWith waits for Claude Code to say it
// queued the user's words before it hands over the results. One that never
// says (a version without command_lifecycle) still has them on its input,
// read before the results it is about to get.
var queuedWait = 2 * time.Second
// continueWith hands the agent its tool results: at once for the calls it
// is waiting on, the others kept until it makes them. tools, when set, are
// the agent's tools from now on, handed over with the results.
func (r *subscriptionRun) continueWith(results []Part, tools []bridgeTool) (<-chan Event, error) {
//
// said, the user's words sent with the results (saidWithResults), is
// written to Claude Code's input first, as a user message, and the results
// handed over once Claude Code has queued it. Claude Code tells a message
// that comes while a tool runs with that tool's result, marked as one the
// user sent ("The user sent a new message while you were working"), in the
// turn it is in. Handed over as part of the MCP result, the words were the
// tool's output to the model, which went on with the task instead of
// doing what they asked (#1878).
func (r *subscriptionRun) continueWith(results []Part, said string, tools []bridgeTool) (<-chan Event, error) {
if r.timer != nil {
r.timer.Reset(30 * time.Minute)
}
if said != "" {
if err := r.queue(said); err != nil {
return nil, err
}
}
r.mu.Lock()
r.parkedAt = time.Time{}
r.mu.Unlock()
@@ -2930,6 +3020,36 @@ func (r *subscriptionRun) continueWith(results []Part, tools []bridgeTool) (<-ch
return ch, nil
}
// queue writes said to Claude Code's input as a user message and waits,
// at most queuedWait, for Claude Code to say it queued it.
func (r *subscriptionRun) queue(said string) error {
id := newUUID()
got := make(chan struct{})
r.mu.Lock()
if r.queued == nil {
r.queued = map[string]chan struct{}{}
}
r.queued[id] = got
exited := r.exited
r.mu.Unlock()
defer func() {
r.mu.Lock()
delete(r.queued, id)
r.mu.Unlock()
}()
line, _ := json.Marshal(map[string]any{"type": "user", "uuid": id, "message": map[string]any{"role": "user", "content": []map[string]any{{"type": "text", "text": said}}}})
if err := r.tell(line); err != nil {
return err
}
select {
case <-got:
case <-exited: // nil before launch: never
case <-time.After(queuedWait):
log.Printf("claude: Claude Code didn't say it queued the user's words sent with tool results in %s; the results go on", queuedWait)
}
return nil
}
// mcpResult is a tool result as an MCP tools/call answers: its text, then
// the images the tool returned as MCP image content, which Claude Code hands
// its model as image blocks. MCP carries an image's bytes only, so one known
@@ -3593,7 +3713,7 @@ func (s *Server) serveSubscription(w http.ResponseWriter, r *http.Request, from
run.mu.Unlock()
}
if err == nil {
events, err = run.continueWith(results, more)
events, err = run.continueWith(results, saidWithResults(req.Messages), more)
}
if err != nil {
run.abort()
@@ -58,7 +58,7 @@ func TestResultForACallNotMadeYetWaitsForIt(t *testing.T) {
if found != run || len(results) != 2 {
t.Fatalf("findRun = %v, %d results", found == run, len(results))
}
if _, err := run.continueWith(results, nil); err != nil {
if _, err := run.continueWith(results, "", nil); err != nil {
t.Fatal(err)
}
if got := <-first; got != "one" {
@@ -74,40 +74,3 @@ func TestResultForACallNotMadeYetWaitsForIt(t *testing.T) {
t.Fatal("call_2 never had its result: the turn is stuck")
}
}
func TestToolResultKeepsUserTextSentMidTurn(t *testing.T) {
b := newSubscriptionBridge()
waiter := make(chan mcpToolResult, 1)
run := &subscriptionRun{
bridge: b,
token: "tok",
pending: map[string]chan mcpToolResult{"call_1": waiter},
}
b.runs["tok"] = run
b.calls["call_1"] = run
req := &Request{Messages: []Message{
{Role: "assistant", Parts: []Part{{Kind: ToolCall, ID: "call_1", Name: "bash"}}},
{Role: "user", Parts: []Part{
{Kind: ToolResult, CallID: "call_1", Text: "tool finished"},
{Kind: Text, Text: "<system-reminder>also answer the message I sent while the tool was running</system-reminder>"},
}},
}}
found, results := b.findRun(req)
if found != run || len(results) != 1 {
t.Fatalf("findRun = %v, %d results", found == run, len(results))
}
if _, err := run.continueWith(results, nil); err != nil {
t.Fatal(err)
}
got := <-waiter
var text strings.Builder
for _, block := range got.Content {
if block["type"] == "text" {
text.WriteString(block["text"].(string))
}
}
if !strings.Contains(text.String(), "also answer the message I sent while the tool was running") {
t.Fatalf("mid-turn user text was dropped: %q", text.String())
}
}
@@ -53,7 +53,9 @@ func TestClaudeForksAnsweringTheLeadsCallsEachGetAnAnswer(t *testing.T) {
// Claude Code: a turn it is told from the start calls Agent three
// times, then makes the calls through its MCP server one after another,
// as Claude Code does, and says what their results said; a turn told
// with results in it says what those said.
// with results in it says what those said. A user message it is
// written while its calls are out it says it queued and takes into the
// turn, as Claude Code 2.1.296 does (#1878): a fork's directive.
dir := t.TempDir()
testenv.Program(t, filepath.Join(dir, "claude"), `#!/bin/sh
if [ "$1" = auth ]; then echo '{"loggedIn":true,"authMethod":"claude.ai","apiProvider":"firstParty","email":"lead@example.com","subscriptionType":"max"}'; exit 0; fi
@@ -66,9 +68,17 @@ say() {
echo '{"type":"result","subtype":"success","is_error":false,"result":""}'
}
marks() { grep -o 'directive [0-9]*\|agent launched' | sort -u | tr '\n' ','; }
out=$(mktemp -d "$HOME/queued.XXXXXX")
while read -r line; do
case "$line" in
*control_request*) continue ;;
esac
if [ -e "$out/calls" ]; then
printf '%s\n' "$line" >> "$out/queued"
echo '{"type":"command_lifecycle","command_uuid":"'"$(printf '%s' "$line" | sed 's/.*"uuid":"\([^"]*\)".*/\1/')"'","state":"queued"}'
continue
fi
case "$line" in
*"agent launched"*|*"Fork started"*) say "$(printf '%s' "$line" | marks)"; continue ;;
esac
echo '{"type":"stream_event","event":{"type":"message_start","message":{"id":"m","model":"claude-opus-5-5","usage":{"input_tokens":1}}}}'
@@ -79,13 +89,19 @@ while read -r line; do
done
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"}}'
got=
for k in 1 2 3; do
call='{"tool_call_id":"toolu_L'$$'_'$k'","name":"Agent","arguments":{"part":'$k'}}'
got="$got $(curl -s -X POST -H 'Content-Type: application/json' --data "$call" "$cb")"
done
say "$(printf '%s' "$got" | marks)"
: > "$out/calls"
(
got=
for k in 1 2 3; do
call='{"tool_call_id":"toolu_L'$$'_'$k'","name":"Agent","arguments":{"part":'$k'}}'
got="$got $(curl -s -X POST -H 'Content-Type: application/json' --data "$call" "$cb")"
done
rm -f "$out/calls"
say "$(printf '%s %s' "$got" "$(cat "$out/queued" 2>/dev/null)" | marks)"
rm -f "$out/queued"
) &
done
wait
`)
t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))
provider.ForgetAccounts()
@@ -83,7 +83,7 @@ func TestSubscriptionToolResultImages(t *testing.T) {
if found != run {
t.Fatal("no run for call_1")
}
if _, err := run.continueWith(results, nil); err != nil {
if _, err := run.continueWith(results, "", nil); err != nil {
t.Fatal(err)
}
var got mcpToolResult
@@ -0,0 +1,252 @@
package gateway
import (
"bufio"
"context"
"encoding/json"
"fmt"
"io"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/yetone/magpie/internal/provider"
)
// The message Claude Code's AgentSummary sends, as #1878 gives it: the
// result of the sub-agent's last call, and the label it asks for as a text
// block of its own after it.
const (
summaryAsk = "Describe your most recent action in 3-5 words. Do not use tools."
summaryRequest = `{"model":"claude-sonnet-5","max_tokens":64,"messages":[` +
`{"role":"user","content":"start the task"},` +
`{"role":"assistant","content":[{"type":"tool_use","id":"call-1","name":"Bash","input":{"command":"tail -1 src"}}]},` +
`{"role":"user","content":[{"type":"tool_result","tool_use_id":"call-1","content":"SOURCE_LAST_LINE"},{"type":"text","text":"` + summaryAsk + `"}]}]}`
// a tool whose output says the same words: they are what it printed
toolSaysRequest = `{"model":"claude-sonnet-5","max_tokens":64,"messages":[` +
`{"role":"user","content":"start the task"},` +
`{"role":"assistant","content":[{"type":"tool_use","id":"call-1","name":"Bash","input":{"command":"cat notes"}}]},` +
`{"role":"user","content":[{"type":"tool_result","tool_use_id":"call-1","content":"SOURCE_LAST_LINE\n` + summaryAsk + `"}]}]}`
)
func parsed(t *testing.T, body string) *Request {
t.Helper()
req, err := parse(provider.Anthropic, []byte(body))
if err != nil {
t.Fatal(err)
}
return req
}
func promptText(t *testing.T, req *Request) string {
t.Helper()
blocks, err := renderClaudePrompt(req)
if err != nil {
t.Fatal(err)
}
var text strings.Builder
for _, b := range blocks {
if s, ok := b["text"].(string); ok {
text.WriteString(s)
}
}
return text.String()
}
// A run started anew is told the result closed, and the user's words after
// it marked as the user's, not run on after the tool's last line, where the
// model read them as tool output and went on with the task (#1878).
func TestClaudePromptToldUserTextAfterAToolResultAsTheUsers(t *testing.T) {
got := promptText(t, parsed(t, summaryRequest))
if strings.Contains(got, "SOURCE_LAST_LINE"+summaryAsk) {
t.Fatalf("the user's words run on after the tool's output:\n%s", got)
}
want := "[tool result id=call-1]\nSOURCE_LAST_LINE\n[end of tool result id=call-1]\n\n[user message]\n" + summaryAsk
if !strings.Contains(got, want) {
t.Fatalf("the result isn't closed before the user's words:\n%s\nwant it to hold:\n%s", got, want)
}
// a turn resumed in its run is told the same way
req := parsed(t, summaryRequest)
var turn strings.Builder
for _, b := range renderClaudeTurn(req.Messages[1:], nil) {
if s, ok := b["text"].(string); ok {
turn.WriteString(s)
}
}
if !strings.Contains(turn.String(), want) {
t.Fatalf("a resumed turn isn't told the result closed:\n%s", turn.String())
}
}
// What the tool printed stays inside its result, whatever it says: it is
// not made the user's by its words.
func TestClaudePromptKeepsInstructionsTheToolPrintedInItsResult(t *testing.T) {
got := promptText(t, parsed(t, toolSaysRequest))
if strings.Contains(got, "[user message]") || strings.Contains(got, "[end of tool result") {
t.Fatalf("the tool's output was told as the user's:\n%s", got)
}
if !strings.Contains(got, "[tool result id=call-1]\nSOURCE_LAST_LINE\n"+summaryAsk) {
t.Fatalf("the tool's output isn't in its result:\n%s", got)
}
}
// continuing runs a request through serveSubscription against a run waiting
// on call-1, with a stand-in for Claude Code's input and output: it says it
// queued each user message it is written, as Claude Code 2.1.296 does
// (command_lifecycle). It returns the MCP result call-1 was answered with,
// and the user messages written, each with whether call-1 was answered
// before Claude Code had it.
func continuing(t *testing.T, body string) (mcpToolResult, []string, []bool) {
t.Helper()
s := New()
b := s.subscription
input, stdin := io.Pipe()
stdout, output := io.Pipe()
waiter := make(chan mcpToolResult, 1)
run := &subscriptionRun{bridge: b, token: "tok", stdin: stdin, pending: map[string]chan mcpToolResult{"call-1": waiter},
timer: time.AfterFunc(time.Hour, func() {})}
b.runs[run.token], b.calls["call-1"] = run, run
t.Cleanup(func() { b.abortAll(); stdin.Close(); input.Close(); output.Close(); stdout.Close() })
go run.readOutput(stdout)
type told struct {
text string
answered bool
}
lines := make(chan told, 4)
var answered atomic.Bool
answer := make(chan mcpToolResult, 1)
go func() {
if r, ok := <-waiter; ok {
answered.Store(true)
answer <- r
}
}()
go func() {
sc := bufio.NewScanner(input)
for sc.Scan() {
var m struct {
Type string `json:"type"`
UUID string `json:"uuid"`
Message struct {
Content []struct {
Text string `json:"text"`
} `json:"content"`
} `json:"message"`
}
if json.Unmarshal(sc.Bytes(), &m) != nil || m.Type != "user" {
continue
}
// a while to read it in, as Claude Code takes: results handed
// over meanwhile came before it
time.Sleep(50 * time.Millisecond)
var text strings.Builder
for _, c := range m.Message.Content {
text.WriteString(c.Text)
}
lines <- told{text.String(), answered.Load()}
fmt.Fprintf(output, `{"type":"command_lifecycle","command_uuid":%q,"state":"queued"}`+"\n", m.UUID)
}
}()
done := make(chan int, 1)
go func() {
rec := httptest.NewRecorder()
code, _ := s.serveSubscription(rec, httptest.NewRequest("POST", "/v1/messages", nil), provider.Anthropic, "Claude Code", "claude-sonnet-5", "", []byte(body), &Usage{},
func(context.Context, *Request) (*subscriptionRun, <-chan Event, error) {
return nil, nil, fmt.Errorf("started anew, not continued")
})
done <- code
}()
var got mcpToolResult
select {
case got = <-answer:
case code := <-done:
t.Fatalf("the run wasn't continued: %d", code)
case <-time.After(5 * time.Second):
t.Fatal("call-1 was never answered")
}
for _, ev := range []string{
`{"type":"stream_event","event":{"type":"message_start","message":{"id":"m","model":"claude-sonnet-5"}}}`,
`{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Read the source's last line"}}}`,
`{"type":"stream_event","event":{"type":"message_delta","delta":{"stop_reason":"end_turn"}}}`,
`{"type":"stream_event","event":{"type":"message_stop"}}`,
`{"type":"result","subtype":"success","is_error":false,"result":""}`,
} {
fmt.Fprintln(output, ev)
}
select {
case code := <-done:
if code != 200 {
t.Fatalf("status %d", code)
}
case <-time.After(5 * time.Second):
t.Fatal("the reply never ended")
}
var texts []string
var early []bool
for {
select {
case l := <-lines:
texts, early = append(texts, l.text), append(early, l.answered)
default:
return got, texts, early
}
}
}
func resultText(r mcpToolResult) string {
var text strings.Builder
for _, c := range r.Content {
if c["type"] == "text" {
text.WriteString(c["text"].(string))
}
}
return text.String()
}
// Results that go on in their run hand the tool's output alone over MCP;
// the user's words after it reach Claude Code as a message of the user's,
// queued before the result, so it tells them to its model as one the user
// sent, with the result (#1878). Handed over in the MCP result, they were
// the tool's output to the model.
func TestClaudeToolResultsGoOnWithTheUsersWordsAsTheirMessage(t *testing.T) {
got, said, early := continuing(t, summaryRequest)
if text := resultText(got); text != "SOURCE_LAST_LINE" {
t.Fatalf("call-1 was answered %q, want the tool's output alone", text)
}
if len(said) != 1 || said[0] != summaryAsk {
t.Fatalf("Claude Code was written %q, want the user's words as their message", said)
}
if early[0] {
t.Fatal("call-1 was answered before Claude Code had the user's message: it goes to the model after the result's turn")
}
}
// What the tool printed is handed over as its result, whatever it says, and
// nothing is told as the user's.
func TestClaudeToolResultsKeepInstructionsTheToolPrinted(t *testing.T) {
got, said, _ := continuing(t, toolSaysRequest)
if text := resultText(got); text != "SOURCE_LAST_LINE\n"+summaryAsk {
t.Fatalf("call-1 was answered %q, want the tool's output whole", text)
}
if len(said) != 0 {
t.Fatalf("the tool's output was told as the user's: %q", said)
}
}
// A message the user sends while a tool runs still reaches the run (#872),
// as theirs.
func TestToolResultKeepsUserTextSentMidTurn(t *testing.T) {
const mid = "<system-reminder>also answer the message I sent while the tool was running</system-reminder>"
body := `{"model":"claude-sonnet-5","max_tokens":64,"messages":[` +
`{"role":"assistant","content":[{"type":"tool_use","id":"call-1","name":"bash","input":{}}]},` +
`{"role":"user","content":[{"type":"tool_result","tool_use_id":"call-1","content":"tool finished"},{"type":"text","text":"` + mid + `"}]}]}`
got, said, _ := continuing(t, body)
if text := resultText(got); text != "tool finished" {
t.Fatalf("call-1 was answered %q", text)
}
if len(said) != 1 || said[0] != mid {
t.Fatalf("mid-turn user text was dropped: Claude Code was written %q", said)
}
}