claude: a reply that writes its tool calls as "[tool call …]" text makes them for real instead of showing the lines (Zhenzhen on Discord)

Claude Desktop 3.1623.0 on a Claude subscription ("Fable 5.1 High",
magpie 0.1.1327) showed replies holding lines like
  [tool call mcp__magpie__mcp__ccd_turn__update_plan id=toolu_0Validate args={"advance":true}]
  [tool call mcp__magpie__Bash id=toolu_0Validate bash args={"command":"cd /Users/... && git diff --check ..."}]
and nothing ran. That is the form renderCachedParts gives past calls when
a run is told the conversation as text (renderClaudePrompt for a run
started anew, renderClaudeTurn for a turn with the client's own calls).
The model copied it: Claude Code had no call to make, the turn ended
end_turn, and the client showed the lines as words.

- readOutput holds a reply's words back from the first line that opens
  with "[tool call " (textCalls); words before it, and lines that only
  start like it, go on as they come. A reply that ends there with
  end_turn and calls none of the client's tools isn't ended: once the
  turn's result is in, the run is told textCallsAsk as a user message on
  its input, and the reply goes on in the next message (one
  message_start, as after Claude Code's own call). The client gets the
  real tool_use, registered by mcpCall, so its results go on in the run.
  Asked once per reply; written as text again, the words reach the
  client as before. No input (a run that ends by itself) or a reply that
  also called a client tool: not asked.
- A prompt that tells past calls as text ends with pastCallsNote: the
  lines record earlier calls, and writing one calls nothing. Placed after
  the messages (before </current_turn>), so the history chunks and their
  cache marks are unchanged. A prompt with no call is told as before.
- Neither text names magpie, Claude or Anthropic (checked in the test).
  Claude Code's own prompt and identity are untouched.

docs/subsystems/claude-subscription-bridge.md: new section "Tool calls
written as text", tests added to Verification.

Run at base 34ad18ed8 (origin/main) + this change, sandbox HOME with
pinned caches:
- New tests in claude_text_calls_test.go, built from the report's lines.
  With claude_subscription.go put back to 34ad18ed8 (claude_text_calls.go
  kept so it builds): TestClaudeTextToolCallsAreMadeForReal FAILs "the
  client was shown the calls written as text" (the raw [tool call …]
  deltas in the stream), TestClaudeTextToolCallsAskedOnce FAILs (reply
  ended end_turn after the first text call, run never asked),
  TestClaudeTextToolCallsUnstreamed and
  TestClaudePromptSaysPastCallsAreARecord fail too. Restored: all pass,
  also -race -count=3.
- gofmt -l: nothing. go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: ok.
- go test -tags nogui -timeout 45m -count=1 ./internal/gateway/ (log
  teed): ok 515.4s. The first such run failed
  TestClaudeTurnWithItsImagesTakenOutGoesOnInItsRun (passes at
  34ad18ed8): push built each line from string(byte), which turns
  UTF-8 into Latin-1 runes, so "一只猫" reached the client garbled. Now
  s[i:i+1]; TestClaudeTextCallsHoldsOnlyTheLine has a CJK case that
  fails with string(ch) put back (shown "ä\xb8\x80只猫…") and passes
  without.
- Rebased on origin/main 8ef9fc578 (it changed internal/gateway's
  redact paths), then again at the pushed head: gofmt, the three vets
  ok, go test -tags nogui -timeout 45m -count=1 ./internal/gateway/:
  ok 385.4s. Rebased once more on 3b8bcc365 (Codex sign-in refresh,
  internal/gateway's signin_revoked.go): go vet of gateway and
  provider, and -run 'Claude|CodexRefresh' ./internal/gateway/: ok
  39.9s; the whole package not run again at that head.
- Full suite: not run; another session's go test ./... (pid 72083) was
  running on this machine.

Not tried: a real Claude Code or a real Claude subscription. Writing a
user message to an idle run after its result is the path resume already
takes for each next turn; that the model then makes the call it wrote
as text is not shown on a real model. Not tried with Claude Desktop.
This commit is contained in:
yetone
2026-10-23 18:19:59 +08:00
parent 3b8bcc3654
commit 0815c91864
4 changed files with 388 additions and 10 deletions
+27 -1
View File
@@ -568,6 +568,32 @@ 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.
## Tool calls written as text
A run told the conversation as text (`renderClaudePrompt`, and
`renderClaudeTurn` with the client's own calls in the turn) is shown each
past call as a `[tool call <name> id=… args=…]` line and each result as
`[tool result id=…]`. The model can copy that form and write its calls as
text: Claude Code has no call to make, the turn ends with end_turn, and the
client shows the lines as the reply's words while nothing runs (Zhenzhen on
Discord: Claude Desktop on Fable 5.1 got
`[tool call mcp__magpie__Bash id=toolu_0Validate bash args={…}]`).
- Such a prompt ends with a note (`pastCallsNote`) that the lines record
earlier calls and that writing one calls nothing. A prompt with no call in
it is told as before.
- `readOutput` holds back a reply's words from the first line that opens
with `[tool call ` (`textCalls`); words before it, and lines that only
start like it, go on as they come. A reply that ends there with end_turn
and calls none of the client's tools isn't ended: once its turn's
`result` is in, the run is told `textCallsAsk` as a user message, and the
reply goes on in the next message (one `message_start`, as after Claude
Code's own call), so the client gets the real `tool_use` and its results
go on in the run. It is asked once per reply: written as text again, the
words reach the client as written. A run with no input to write to, or a
reply that called the client's tools too (the text is left out), is
not asked.
## The account's allowance on the reply (#1257)
Claude Code tells a run's account allowance in its stream-json
@@ -602,7 +628,7 @@ go test -tags nogui ./internal/gateway/ -run '^TestClaudeToolNamesComeBackAsDecl
go test -tags nogui ./internal/gateway/ -run 'TestClaudeRunsHeldToTheRoom|TestClaudeRoom|TestClaudeOneOffsTakeRoom|TestClaudeMemRuns|TestClaudeRunsMost|TestClaudeNoRoom' -count=1
go test -tags nogui ./internal/cli/ -run '^TestClaudeCodeRunsSetsTheUsersOwn$' -count=1
go test -tags nogui ./internal/settings/ -run '^TestClaudeRunsMostIsMachineLocal$' -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|ClaudeHistoryCachedAcrossNewRuns|ClaudeUnloadableSession|ClaudeEndedRunSaysWhy|ClaudeIdle|ClaudeSideQuestion|ClaudeNoRunSaysWhy|ClaudeToolResultsNoRunSaysWhy|ClaudePromptToldUserText|ClaudePromptKeepsInstructions|ClaudeToolResultsGoOnWithTheUsersWords|ClaudeToolResultsKeepInstructions|ToolResultKeepsUserTextSentMidTurn' -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|ClaudeHistoryCachedAcrossNewRuns|ClaudeUnloadableSession|ClaudeEndedRunSaysWhy|ClaudeIdle|ClaudeSideQuestion|ClaudeNoRunSaysWhy|ClaudeToolResultsNoRunSaysWhy|ClaudePromptToldUserText|ClaudePromptKeepsInstructions|ClaudeToolResultsGoOnWithTheUsersWords|ClaudeToolResultsKeepInstructions|ToolResultKeepsUserTextSentMidTurn|ClaudeTextToolCalls|ClaudeTextCallsHoldsOnlyTheLine|ClaudePromptSaysPastCallsAreARecord' -count=1
```
`claude_rewritten_test.go` has a case for each relaxation and one for each
+56 -9
View File
@@ -2109,13 +2109,44 @@ func (r *subscriptionRun) readOutput(rd io.Reader) {
// unstreamedQuiet, as when Claude Code goes on to call the client's
// tools and waits on them
unstreamed, unstreamedStop, blocks := "", "", 0
// The reply's tool calls written as text (textCalls), held back from
// the client. A reply that ends with them and calls none of the
// client's tools goes on: once its turn's result is in, the run is
// told to make them (textCallsAsk), and the reply goes on in its next
// message, as after Claude Code's own call. Only once a reply: told
// again, the words go to the client as written.
var calls textCalls
retell := false // the run is told to make its calls once this turn's result is in
retold := false // this reply was told so
var pmu sync.Mutex // held for each line, and by quiet's settle
var quiet *time.Timer
text := func(s string) {
if s != "" && !r.schema {
shown = true
r.emit(Event{Kind: KText, Text: s})
}
}
said := func(s string) { text(calls.push(s)) }
// what each message's end does, once its stop is known
end := func(why string) {
if goesOn := why != "" && r.schema && !theirs || why == "tool_use" && len(own) > 0 && !theirs; goesOn {
inside = true // the answer is the next message's, or the result's
} else if why != "" {
held, seen := calls.end()
switch {
case seen && !theirs && why == "end_turn" && !retold && r.stdin != nil:
retell, retold, inside = true, true, true
log.Printf("claude: a reply wrote its tool calls as text (%d bytes held back); its run is told to make them", len(held))
return
case seen && theirs:
// it called the client's tools too: those are the reply's
log.Printf("claude: a reply wrote tool calls as text beside real ones; the text (%d bytes) is left out", len(held))
case seen:
log.Printf("claude: a reply wrote its tool calls as text again; the client is told the words as written")
text(held)
default:
text(held)
}
r.emit(Event{Kind: KStop, Stop: stopFromAnthropic(why)})
}
}
@@ -2158,12 +2189,6 @@ func (r *subscriptionRun) readOutput(rd io.Reader) {
r.mu.Unlock()
return name, true
}
text := func(s string) {
if s != "" && !r.schema {
shown = true
r.emit(Event{Kind: KText, Text: s})
}
}
// begin starts a message: the reply's first, or one it goes on in,
// after Claude Code's own call or an attempt cut short
begin := func(id, model string, u cliUsage) {
@@ -2175,6 +2200,7 @@ func (r *subscriptionRun) readOutput(rd io.Reader) {
return
}
before, this = Usage{}, Usage{}
calls, retold = textCalls{}, false
r.mu.Lock()
r.asked = nil
r.mu.Unlock()
@@ -2305,7 +2331,22 @@ func (r *subscriptionRun) readOutput(rd io.Reader) {
}
return
}
if envelope.Type == "result" && retell && !envelope.IsError {
// the turn whose reply wrote its calls as text is over: the run
// is told to make them, and the reply goes on in its answer
retell = false
calls = textCalls{}
ask, _ := json.Marshal(map[string]any{"type": "user", "uuid": newUUID(), "message": map[string]any{"role": "user",
"content": []map[string]any{{"type": "text", "text": textCallsAsk}}}})
if err := r.tell(ask); err != nil {
inside = false
r.emit(Event{Kind: KError, Text: "Claude Code could not be told to make the tool calls its reply wrote as text: " + err.Error(), Status: http.StatusBadGateway, RequestID: reqID})
r.endSegment()
}
return
}
if envelope.Type == "result" {
retell = false
// a turn that failed — out of quota, rate limited — ends with
// this and no message_stop, the CLI waiting on its next input:
// the reply ends here, or it would wait with it (#177)
@@ -2385,7 +2426,7 @@ func (r *subscriptionRun) readOutput(rd io.Reader) {
r.emit(Event{Kind: KSig, Text: c.Signature})
}
case "text":
text(c.Text)
said(c.Text)
case "tool_use":
name, theirs := toolStart(index, c.Name)
if !theirs {
@@ -2440,7 +2481,7 @@ func (r *subscriptionRun) readOutput(rd io.Reader) {
r.emit(Event{Kind: KToolStart, ID: e.ContentBlock.ID, Name: name})
}
case "text":
text(e.ContentBlock.Text)
said(e.ContentBlock.Text)
case "thinking":
// a block of its own, signed with no text or not (#1445)
r.emit(Event{Kind: KThinkStart})
@@ -2457,7 +2498,7 @@ func (r *subscriptionRun) readOutput(rd io.Reader) {
case "content_block_delta":
switch e.Delta.Type {
case "text_delta":
text(e.Delta.Text)
said(e.Delta.Text)
case "thinking_delta":
r.emit(Event{Kind: KThink, Text: e.Delta.Thinking})
case "signature_delta":
@@ -2675,6 +2716,9 @@ func renderClaudePrompt(req *Request) ([]map[string]any, error) {
chunk = len(blocks) - 1
}
}
if slices.ContainsFunc(req.Messages, callsTool) {
text.WriteString(pastCallsNote + "\n\n")
}
if split > 0 {
text.WriteString("</current_turn>")
}
@@ -2902,6 +2946,9 @@ func renderClaudeTurn(msgs []Message, tools []Tool) []map[string]any {
}
blocks = renderParts(blocks, &text, m.Parts, offered)
}
if slices.ContainsFunc(msgs, callsTool) {
text.WriteString("\n\n" + pastCallsNote)
}
return closeBlocks(blocks, &text)
}
+75
View File
@@ -0,0 +1,75 @@
package gateway
import "strings"
// A run started anew, or a turn that goes on with the client's own calls in
// it, is told the conversation as text, each past call a "[tool call …]"
// line (renderCachedParts). The model can take that for how it calls a
// tool and write such lines itself: Claude Code then has no call to make,
// the turn ends, and the client shows the lines as the reply's words
// (Zhenzhen on Discord, Claude Desktop on Fable 5.1).
const textCallOpen = "[tool call "
// textCallsAsk is what a run whose reply wrote its calls as text is told,
// once, so it makes them (readOutput).
const textCallsAsk = `Your last message wrote tool calls out as text ("[tool call …]" lines). ` +
`Text like that runs nothing: no tool ran, and the user doesn't see those lines. Make the calls with your tools now.`
// pastCallsNote ends a prompt that tells past calls as text: the lines
// record them, and writing one calls nothing.
const pastCallsNote = "(The \"[tool call …]\" and \"[tool result …]\" lines above record calls made earlier. " +
"Writing such a line calls nothing: call a tool only with the tool itself.)"
// textCalls holds back a reply's words from the first line that opens as a
// call told in text (textCallOpen), so the client isn't shown it. Words up
// to that line go on as they come; a line is held only while it could
// still open so.
type textCalls struct {
mid bool // the words so far end inside a line that can't be one
line string // the start of a line that may open as one
seen bool // a line opened as one: the rest is held
held strings.Builder
}
// push takes the next of the reply's words and says which go to the client
// now.
func (c *textCalls) push(s string) string {
if c.seen {
c.held.WriteString(s)
return ""
}
var out strings.Builder
for i := 0; i < len(s); i++ {
ch := s[i]
if c.mid {
out.WriteByte(ch)
c.mid = ch != '\n'
continue
}
line := c.line + s[i:i+1] // a byte, as a UTF-8 rune may be cut across chunks
open := strings.TrimLeft(line, " \t")
switch {
case strings.HasPrefix(open, textCallOpen):
c.seen, c.line = true, ""
c.held.WriteString(line)
c.held.WriteString(s[i+1:])
return out.String()
case strings.HasPrefix(textCallOpen, open):
c.line = line
default:
out.WriteString(line)
c.line, c.mid = "", ch != '\n'
}
}
return out.String()
}
// end is what was held at the reply's end: the words from the call told in
// text on when seen, else a line's start that never became one.
func (c *textCalls) end() (held string, seen bool) {
if !c.seen {
held, c.line = c.line, ""
return held, false
}
return c.held.String(), true
}
+230
View File
@@ -0,0 +1,230 @@
package gateway
import (
"bufio"
"encoding/json"
"io"
"strings"
"sync"
"testing"
)
// The report's lines (Zhenzhen on Discord, Claude Desktop 3.1623.0 on
// "Fable 5.1 High", magpie 0.1.1327): the model wrote its calls in the
// form a conversation told as text gives past calls, ids made up.
const (
reportedPlanCall = `[tool call mcp__magpie__mcp__ccd_turn__update_plan id=toolu_0Validate args={"advance":true}]`
reportedBashCall = `[tool call mcp__magpie__Bash id=toolu_0Validate bash args={"command":"cd /Users/... && git diff --check ..."}]`
)
// textCallTurn is a streamed reply whose words are chunks, ended as Claude
// Code ends a turn: end_turn and its result.
func textCallTurn(id string, chunks ...string) []string {
lines := []string{
`{"type":"stream_event","event":{"type":"message_start","message":{"id":"` + id + `","model":"claude-fable-5-1","usage":{"input_tokens":3,"output_tokens":1}}}}`,
`{"type":"stream_event","event":{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}}`,
}
for _, c := range chunks {
b, _ := json.Marshal(c)
lines = append(lines, `{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":`+string(b)+`}}}`)
}
return append(lines,
`{"type":"stream_event","event":{"type":"content_block_stop","index":0}}`,
`{"type":"stream_event","event":{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":40}}}`,
`{"type":"stream_event","event":{"type":"message_stop"}}`,
`{"type":"result","subtype":"success","is_error":false,"result":"done"}`,
)
}
// realCallTurn is a streamed reply that calls the client's update_plan
// through the run's MCP helper, as Claude Code tells it.
var realCallTurn = []string{
`{"type":"stream_event","event":{"type":"message_start","message":{"id":"msg_real","model":"claude-fable-5-1","usage":{"input_tokens":3,"output_tokens":1}}}}`,
`{"type":"stream_event","event":{"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"toolu_01RealCall","name":"mcp__magpie__mcp__ccd_turn__update_plan","input":{}}}}`,
`{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"{\"advance\":true}"}}}`,
`{"type":"stream_event","event":{"type":"content_block_stop","index":0}}`,
`{"type":"stream_event","event":{"type":"message_delta","delta":{"stop_reason":"tool_use"},"usage":{"output_tokens":20}}}`,
`{"type":"stream_event","event":{"type":"message_stop"}}`,
}
// stdinOf gives run an input that records each line it is told.
func stdinOf(t *testing.T, run *subscriptionRun) func() []string {
t.Helper()
pr, pw := io.Pipe()
run.stdin = pw
var mu sync.Mutex
var told []string
done := make(chan struct{})
go func() {
defer close(done)
s := bufio.NewScanner(pr)
s.Buffer(make([]byte, 64<<10), 1<<20)
for s.Scan() {
mu.Lock()
told = append(told, s.Text())
mu.Unlock()
}
}()
t.Cleanup(func() { pw.Close(); pr.Close(); <-done })
return func() []string {
mu.Lock()
defer mu.Unlock()
return append([]string(nil), told...)
}
}
// A reply that writes its tool calls as "[tool call …]" text shows the
// client none of it: the run is told to make the calls, and the client gets
// the real call, the words before the text calls kept. Before, the client
// showed the lines as the reply's words and nothing ran.
func TestClaudeTextToolCallsAreMadeForReal(t *testing.T) {
run := &subscriptionRun{}
told := stdinOf(t, run)
lines := append(textCallTurn("msg_text",
"Plan advanced; now validating.\n",
"[tool", " call mcp__magpie__mcp__ccd_turn__update_plan id=toolu_0Valid",
strings.TrimPrefix(reportedPlanCall, "[tool call mcp__magpie__mcp__ccd_turn__update_plan id=toolu_0Valid")+"\n",
reportedBashCall+"\n[tool result id=toolu_0Validate]\nok"),
realCallTurn...)
text, stop, _, _, raw, ended, ok := claudeReply(t, run, lines, true)
if strings.Contains(raw, "[tool call") || strings.Contains(raw, "tool result id=") {
t.Fatalf("the client was shown the calls written as text:\n%s", raw)
}
if text != "Plan advanced; now validating.\n[mcp__ccd_turn__update_plan]" || stop != "tool_use" || ended != "tool" || !ok {
t.Fatalf("reply %q stop %q, run ended %q %v:\n%s", text, stop, ended, ok, raw)
}
if strings.Count(raw, `"type":"message_start"`) != 1 {
t.Fatalf("the reply didn't go on as one message:\n%s", raw)
}
asks := told()
if len(asks) != 1 {
t.Fatalf("the run was told %d lines, want the one ask: %q", len(asks), asks)
}
var ask struct {
Type string `json:"type"`
Message struct {
Role string `json:"role"`
Content []struct {
Text string `json:"text"`
} `json:"content"`
} `json:"message"`
}
if json.Unmarshal([]byte(asks[0]), &ask) != nil || ask.Type != "user" || ask.Message.Role != "user" ||
len(ask.Message.Content) != 1 || ask.Message.Content[0].Text != textCallsAsk {
t.Fatalf("the run was told %s", asks[0])
}
// the ask names neither magpie nor the vendor
for _, w := range []string{"magpie", "Claude", "Anthropic"} {
if strings.Contains(textCallsAsk, w) || strings.Contains(pastCallsNote, w) {
t.Fatalf("the text magpie adds names %s", w)
}
}
}
// Told once, a reply that writes its calls as text again reaches the
// client as written: the run isn't asked over and over.
func TestClaudeTextToolCallsAskedOnce(t *testing.T) {
run := &subscriptionRun{}
told := stdinOf(t, run)
lines := append(textCallTurn("msg_text", reportedPlanCall), textCallTurn("msg_again", "Calling it: \n"+reportedBashCall)...)
text, stop, _, _, raw, ended, ok := claudeReply(t, run, lines, true)
if text != "Calling it: \n"+reportedBashCall || stop != "end_turn" || ended != "stop" || !ok {
t.Fatalf("reply %q stop %q, run ended %q %v:\n%s", text, stop, ended, ok, raw)
}
if n := len(told()); n != 1 {
t.Fatalf("the run was asked %d times", n)
}
}
// A run with no input to tell (one that ends by itself) gives the client the
// words as written, as before.
func TestClaudeTextToolCallsWithoutInput(t *testing.T) {
text, stop, _, _, raw, _, _ := claudeReply(t, &subscriptionRun{}, textCallTurn("msg_text", "a\n"+reportedPlanCall), true)
if text != "a\n"+reportedPlanCall || stop != "end_turn" {
t.Fatalf("reply %q stop %q:\n%s", text, stop, raw)
}
}
// Words that only look like the start of such a line, or name it mid-line,
// go to the client whole, however they are cut into chunks.
func TestClaudeTextCallsHoldsOnlyTheLine(t *testing.T) {
for _, words := range []string{
"[tooling] fixed\n[tool]\n [tool calls] are made with tools",
"see [tool call x id=1 args={}] in the log\nok",
"",
"\n\n[tool ca",
"一只猫\n [工具] 调用 …\n[tool callé]",
} {
for size := 1; size <= len(words)+1; size++ {
var c textCalls
var out strings.Builder
for i := 0; i < len(words); i += size {
out.WriteString(c.push(words[i:min(i+size, len(words))]))
}
held, seen := c.end()
if seen || out.String()+held != words {
t.Fatalf("%q in chunks of %d: shown %q, held %q (%v)", words, size, out.String(), held, seen)
}
}
}
var c textCalls
shown := c.push("ok\n ") + c.push(reportedPlanCall[:3]) + c.push(reportedPlanCall[3:]+"\nmore")
if held, seen := c.end(); shown != "ok\n" || !seen || held != " "+reportedPlanCall+"\nmore" {
t.Fatalf("shown %q, held %q (%v)", shown, held, seen)
}
}
// A conversation told as text says its "[tool call …]" lines are a
// record, and that writing one calls nothing: for a run started anew and
// for a turn told with the client's own calls. One with no calls is told
// as before.
func TestClaudePromptSaysPastCallsAreARecord(t *testing.T) {
msgs := []Message{
{Role: "user", Parts: []Part{{Kind: Text, Text: "check the diff"}}},
{Role: "assistant", Parts: []Part{{Kind: ToolCall, ID: "toolu_01", Name: "Bash", Args: json.RawMessage(`{"command":"git diff --check"}`)}}},
{Role: "user", Parts: []Part{{Kind: ToolResult, CallID: "toolu_01", Text: "clean"}}},
{Role: "assistant", Parts: []Part{{Kind: Text, Text: "clean"}}},
{Role: "user", Parts: []Part{{Kind: Text, Text: "go on"}}},
}
tools := []Tool{{Name: "Bash"}}
all := func(blocks []map[string]any) string {
var s strings.Builder
for _, b := range blocks {
t, _ := b["text"].(string)
s.WriteString(t)
}
return s.String()
}
blocks, err := renderClaudePrompt(&Request{Messages: msgs, Tools: tools})
if err != nil {
t.Fatal(err)
}
if got := all(blocks); !strings.HasSuffix(got, pastCallsNote+"\n\n</current_turn>") || !strings.Contains(got, "[tool call mcp__magpie__Bash id=toolu_01") {
t.Fatalf("started anew:\n%s", got)
}
if got := all(renderClaudeTurn(msgs[1:3], tools)); !strings.HasSuffix(got, "\n\n"+pastCallsNote) {
t.Fatalf("the turn since:\n%s", got)
}
for _, m := range [][]Message{{msgs[0]}, {msgs[0], msgs[3], msgs[4]}} {
blocks, _ := renderClaudePrompt(&Request{Messages: m, Tools: tools})
if got := all(blocks) + all(renderClaudeTurn(m, tools)); strings.Contains(got, pastCallsNote) {
t.Fatalf("no calls, yet told:\n%s", got)
}
}
}
// The same told in whole messages, as Claude Code tells an answer it asked
// for again without a stream.
func TestClaudeTextToolCallsUnstreamed(t *testing.T) {
run := &subscriptionRun{}
told := stdinOf(t, run)
words, _ := json.Marshal("Validating.\n" + reportedBashCall)
lines := append([]string{
`{"type":"assistant","message":{"id":"msg_whole","model":"claude-fable-5-1","role":"assistant","content":[{"type":"text","text":` + string(words) + `}],"stop_reason":"end_turn","usage":{"input_tokens":3,"output_tokens":40}}}`,
`{"type":"result","subtype":"success","is_error":false,"result":"done"}`,
}, realCallTurn...)
text, stop, _, _, raw, ended, ok := claudeReply(t, run, lines, true)
if text != "Validating.\n[mcp__ccd_turn__update_plan]" || stop != "tool_use" || ended != "tool" || !ok || len(told()) != 1 {
t.Fatalf("reply %q stop %q, run ended %q %v, told %q:\n%s", text, stop, ended, ok, told(), raw)
}
}