Files
magpie/internal/gateway/responses_hidden_thinking_test.go
T
yetone 79c8667c92 gateway: Codex gives Claude its signed thinking back through encrypted_content
Codex calling a Claude model through magpie (mysterious_dove_96933 on
Discord): a reply's reasoning items carried only the summary, so Claude's
thinking signature and a redacted_thinking block's data were gone. On
the next request of a tool loop magpie sent Anthropic the turn as
[tool_use] alone, with thinking on, which Anthropic documents as a 400
("final assistant message must start with a thinking block"), and the
model lost its reasoning across calls either way.

Now the Anthropic decoders name a signature as Claude's (KSig with
sealAnthropic, Part.SignedBy). The Responses encoder and renderResponses
give each thinking block a reasoning item whose encrypted_content is
"magpie-claude1:" and the block's JSON in base64 (internal/claudeseal):
its summary beside it, an empty summary for a block signed with no
text, and redacted_thinking as an item of its own. parseResponses reads
it back into the block as Claude wrote it, in order, so anthropicBody
sends it as before for an Anthropic client. A Gemini thought's
signature isn't named and isn't sealed.

The envelope never reaches a Responses API: withoutClaudeSeals in
passthrough and forwardOnce (the item keeps its summary, one with none
goes), codexInputAs leaves such an item out for Codex's own models, and
codexUpstreamOn takes it out before the ChatGPT backend. OpenAI's own
encrypted_content is untouched. sessions.PortCodexRollouts writes such
an item as its summary, so a thread resumed against OpenAI itself isn't
refused. redact.MaskJSON already keeps a reasoning item's seal whole
(no change); TestMaskJSONKeepsClaudeBlocks holds that.

Run, at 5e3dd1d52 plus this change:
- go test -count=1 -timeout 45m ./internal/gateway/ ./internal/sessions/
  ./internal/redact/ ./internal/claudeseal/: sessions, redact,
  claudeseal ok; gateway ok but for TestResponsesStreamToolThenHiddenThinking
  (#1786), whose hidden cases wanted no reasoning item, the loss this
  fixes. They now want one item carrying the sealed block with an empty
  summary, and its guarantee (a whole stream, no panic) is unchanged;
  re-run green.
- gofmt -l clean; go vet (darwin) on the touched packages, GOOS=linux
  go vet -tags nogui ./internal/..., GOOS=windows go vet on the touched
  packages: clean.
- TestCodexToolLoopGivesClaudeItsThinkingBack (a fake Anthropic: signed
  thinking, redacted_thinking, a text-less signed block, tool_use; a
  Codex-shaped request with store false and the encrypted_content
  include; then the follow-up) fails on 5e3dd1d52: "stream=true:
  Anthropic was sent 1 assistant blocks, want 4". Passes now, streamed
  and not.
- Real: a sandbox HOME with only OpenRouter's key (Anthropic endpoint,
  anthropic/claude-opus-5.5, served by Claude Platform on AWS), magpie
  serve on its own port, a Codex-shaped two-turn tool loop at effort
  high, streamed and not: turn 1 gave a reasoning item with
  magpie-claude1: (3.1KB), turn 2 was 200 through /v1/responses →
  /v1/messages and answered from the tool output.

Broken by hand:
- withoutClaudeSeals a no-op: TestClaudeBlocksNeverGoToAResponsesAPI
  red, the relay sent magpie-claude1: items.
- codexInputAs not leaving them out: red, "ChatGPT backend would be
  sent …".
- sealing any signature (no sealAnthropic check):
  TestGeminiSignatureIsNotSealedAsClaudes red.
- portValue's reasoning branch off: TestPortLineDropsClaudeBlocks red.

Not tried: the 400 itself. Through OpenRouter, Opus 5.5 answered turn 2
with the envelope stripped too (the old shape), so this route shows
only the lost reasoning, not the refusal. Not tried on api.anthropic.com
directly, Bedrock or Vertex keys, or Claude's subscription (whose tool
loop stays inside Claude Code's run). Codex resuming a ported thread
against OpenAI with such items wasn't run.
2026-10-27 11:26:54 +08:00

109 lines
5.9 KiB
Go

package gateway
import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/yetone/magpie/internal/claudeseal"
"github.com/yetone/magpie/internal/provider"
)
// A Claude turn that calls a tool and then thinks without showing it, a
// redacted_thinking block or a thinking block signed with no text, is a
// whole Responses stream for Codex: the call, then response.completed. The
// encoder read the open call from the collector's last part, which by then
// was the thinking, and panicked, so the client got a chunked body cut short
// ("unexpected EOF", "stream disconnected before completion", #1786).
func TestResponsesStreamToolThenHiddenThinking(t *testing.T) {
const head = "event: message_start\ndata: {\"type\":\"message_start\",\"message\":{\"id\":\"msg_01\",\"type\":\"message\",\"role\":\"assistant\",\"model\":\"claude-opus-4-6\",\"content\":[],\"stop_reason\":null,\"usage\":{\"input_tokens\":12,\"output_tokens\":1}}}\n\n" +
"event: content_block_start\ndata: {\"type\":\"content_block_start\",\"index\":0,\"content_block\":{\"type\":\"tool_use\",\"id\":\"toolu_01\",\"name\":\"shell\",\"input\":{}}}\n\n" +
"event: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":0,\"delta\":{\"type\":\"input_json_delta\",\"partial_json\":\"{\\\"command\\\":[\\\"ls\\\"]}\"}}\n\n" +
"event: content_block_stop\ndata: {\"type\":\"content_block_stop\",\"index\":0}\n\n"
const tail = "event: message_delta\ndata: {\"type\":\"message_delta\",\"delta\":{\"stop_reason\":\"tool_use\",\"stop_sequence\":null},\"usage\":{\"output_tokens\":30}}\n\n" +
"event: message_stop\ndata: {\"type\":\"message_stop\"}\n\n"
for _, c := range []struct {
name, block string
visible bool
}{
{"redacted_thinking", "event: content_block_start\ndata: {\"type\":\"content_block_start\",\"index\":1,\"content_block\":{\"type\":\"redacted_thinking\",\"data\":\"EmwKAhgBEgy3va3pzix\"}}\n\n" +
"event: content_block_stop\ndata: {\"type\":\"content_block_stop\",\"index\":1}\n\n", false},
{"empty thinking, signed at its start", "event: content_block_start\ndata: {\"type\":\"content_block_start\",\"index\":1,\"content_block\":{\"type\":\"thinking\",\"thinking\":\"\",\"signature\":\"fixture\"}}\n\n" +
"event: content_block_stop\ndata: {\"type\":\"content_block_stop\",\"index\":1}\n\n", false},
{"empty thinking, signed in a delta", "event: content_block_start\ndata: {\"type\":\"content_block_start\",\"index\":1,\"content_block\":{\"type\":\"thinking\",\"thinking\":\"\",\"signature\":\"\"}}\n\n" +
"event: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":1,\"delta\":{\"type\":\"signature_delta\",\"signature\":\"fixture\"}}\n\n" +
"event: content_block_stop\ndata: {\"type\":\"content_block_stop\",\"index\":1}\n\n", false},
{"visible thinking", "event: content_block_start\ndata: {\"type\":\"content_block_start\",\"index\":1,\"content_block\":{\"type\":\"thinking\",\"thinking\":\"\",\"signature\":\"\"}}\n\n" +
"event: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":1,\"delta\":{\"type\":\"thinking_delta\",\"thinking\":\"Now list it.\"}}\n\n" +
"event: content_block_delta\ndata: {\"type\":\"content_block_delta\",\"index\":1,\"delta\":{\"type\":\"signature_delta\",\"signature\":\"fixture\"}}\n\n" +
"event: content_block_stop\ndata: {\"type\":\"content_block_stop\",\"index\":1}\n\n", true},
} {
t.Run(c.name, func(t *testing.T) {
fresh(t)
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.Copy(io.Discard, r.Body)
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, head+c.block+tail)
}))
defer up.Close()
if err := provider.Save(provider.Provider{ID: "anth", Name: "Anth", Key: "k", Anthropic: up.URL, Models: []string{"claude-opus-4-6"}}); err != nil {
t.Fatal(err)
}
gw := httptest.NewServer(New().Handler())
defer gw.Close()
resp, err := http.Post(gw.URL+"/v1/responses", "application/json", strings.NewReader(
`{"model":"anth/claude-opus-4-6","stream":true,"input":"list the files","reasoning":{"effort":"high"},`+
`"tools":[{"type":"function","name":"shell","parameters":{"type":"object","properties":{"command":{"type":"array","items":{"type":"string"}}}}}]}`))
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("status %d, the stream was cut short: %v\n%s", resp.StatusCode, err, body)
}
var completed map[string]any
var call map[string]any
var reasoning []map[string]any
for _, ev := range events(string(body)) {
switch ev["type"] {
case "response.completed":
completed = ev
case "response.output_item.done":
item, _ := ev["item"].(map[string]any)
switch item["type"] {
case "function_call":
call = item
case "reasoning":
reasoning = append(reasoning, item)
}
}
}
if completed == nil {
t.Fatalf("no response.completed:\n%s", body)
}
if call == nil || call["call_id"] != "toolu_01" || call["name"] != "shell" || call["arguments"] != `{"command":["ls"]}` {
b, _ := json.Marshal(call)
t.Fatalf("function_call = %s, want toolu_01 shell {\"command\":[\"ls\"]}\n%s", b, body)
}
// Thinking Claude didn't show is still given back to it on the
// next request (mysterious_dove_96933 on Discord): one reasoning
// item carrying the block, its summary empty unless shown.
if len(reasoning) != 1 {
t.Fatalf("%d reasoning items, want 1\n%s", len(reasoning), body)
}
enc, _ := reasoning[0]["encrypted_content"].(string)
if !claudeseal.Is(enc) {
t.Errorf("reasoning item's encrypted_content = %q, want Claude's block sealed", enc)
}
summary, _ := reasoning[0]["summary"].([]any)
if shown := len(summary) > 0; shown != c.visible {
t.Errorf("reasoning summary = %v, want shown %v", summary, c.visible)
}
})
}
}