gateway: a </think> inside code no longer ends a reply's thinking; a plugin's text keeps its <think> (#2634)

Kane-Kuroneko's Qoder replies through Codex began mid-sentence at a
backtick: the Chat decoder took any reply whose text began with <think>
as inline thinking up to the first literal </think>, even one inside an
inline-code example ("使用 `<think>...</think>` 标签"), for every Chat
upstream.

- The close is looked for only outside Markdown code (mdCode in
  chat.go): an inline span (taken to end with its line, so a stray
  backtick can't swallow the answer) or a fenced block. Backtick runs and
  a close split across chunks are held, as the tag tail was.
- A plugin's Chat reply is read as OpenCode reads it, its text as it came
  (decoderFor, used by streamTranslated, the continuation path and the
  search path): the plugin knows its vendor and gives reasoning apart.
  Qoder's plugin sends reasoning_content and has no splitter of its own.
- A reply that already gave thinking in reasoning_content/reasoning has
  no leading-tag lookup in its text.
- The line breaks after a close are left out however they're chunked:
  one character a delta used to leave "\n" at the head of the answer.
- Codex titles/descriptions/predictions (codex_titles.go) strip a leading
  block with the same close rule (afterThought), the sibling cut.
MiniMax (2ab69d0f) and Gemini's <thought> keep working: their existing
tests pass unchanged.

Tests use the reporter's literal bytes, whole, a character a delta and a
byte a delta: TestChatThinkCloseInCode, TestThinkExampleReachesClientsWhole
(Codex /v1/responses and Claude Code /v1/messages against a fake Chat
upstream), TestChatThinkTagAfterReasoningField, TestPluginThinkTagIsText
(the fake plugin as qoder, through Bun, with #2634's historical
boundary), TestAfterThoughtCloseInCode.

Broken by hand, each watched go red: close matched inside code ->
TestChatThinkCloseInCode, TestThinkExampleReachesClientsWhole,
TestAfterThoughtCloseInCode; reasoning-field rule off ->
TestChatThinkTagAfterReasoningField; plugin scope off ->
TestPluginThinkTagIsText; newline trim off -> TestChatThinkCloseInCode,
TestThinkExampleReachesClientsWhole, plus the existing MiniMax tests.

Run: gofmt -l clean; go vet ./... (darwin), GOOS=linux and GOOS=windows
go vet -tags nogui ./... clean; go test -timeout 45m ./... on this change plus the next
commit's library edit (the worktree held both while it ran): 64
packages ok, internal/gateway ok (524s), internal/library ok; internal/gui's
real-window darwin tests were killed at their 30s bar under a load
average of ~295, and internal/provider failed to link on a GOCACHE file
another run trimmed. Rerun alone: internal/provider ok (206s),
internal/gui ok (165s). No GUI files touched. Not tried
against real Qoder or MiniMax accounts.

Not changed: the plugins repo's think-tags middleware
(packages/think-tags) also ends a block at the first indexOf("</think>")
when a user turns it on.
This commit is contained in:
yetone
2026-10-17 08:49:42 +08:00
parent c1e95f919b
commit d4a1b9baa7
6 changed files with 329 additions and 30 deletions
+99 -12
View File
@@ -997,7 +997,14 @@ type chatDecoder struct {
lead string
thought bool
thoughtClose string
past bool // the reply's text has begun; no tag is looked for now
// code is where the thinking is in Markdown code, where a close tag is
// an example written out, not the close (#2634: "使用 `<think>…</think>`
// 标签" cut the reply at the example's close)
code mdCode
past bool // the reply's text has begun; no tag is looked for now
// trim is a thinking block just closed: the line breaks after its
// close are left out of the answer, in whatever chunk they come
trim bool
}
// thoughtTags are the tags a leading block of thinking comes between in a
@@ -1033,21 +1040,15 @@ func (d *chatDecoder) text(s string, emit func(Event)) {
if d.thought {
s = d.lead + s
d.lead = ""
if i := strings.Index(s, thoughtClose); i >= 0 {
if i, keep := d.code.find(s, thoughtClose, false); i >= 0 {
if i > 0 {
emit(Event{Kind: KThink, Text: s[:i]})
}
d.thought, d.past = false, true
s = strings.TrimLeft(s[i+len(thoughtClose):], "\n")
d.thought, d.past, d.trim = false, true, true
s = s[i+len(thoughtClose):]
} else {
// the end of it may be the close tag begun
keep := 0
for n := min(len(thoughtClose)-1, len(s)); n > 0; n-- {
if strings.HasSuffix(s, thoughtClose[:n]) {
keep = n
break
}
}
// the end of it may be the close tag, or a run of backticks,
// begun
if t := s[:len(s)-keep]; t != "" {
emit(Event{Kind: KThink, Text: t})
}
@@ -1055,11 +1056,91 @@ func (d *chatDecoder) text(s string, emit func(Event)) {
return
}
}
if d.trim {
if s = strings.TrimLeft(s, "\n"); s != "" {
d.trim = false
}
}
if s != "" {
emit(Event{Kind: KText, Text: s})
}
}
// mdCode follows whether text read piece by piece is in Markdown code: an
// inline span, taken to end with its line, or a fenced block.
type mdCode struct {
span int // the backticks the open inline span began with; 0 for none
fence int // the backticks the open fenced block began with; 0 for none
mid bool // past the line's leading spaces
}
// find gives where close is first outside code in s, read on from the
// pieces before, or -1 and how many bytes at the end of s are held back
// for the next piece: a close tag or a run of backticks that may go on
// there. Unless last, that is; then nothing is held.
func (m *mdCode) find(s, close string, last bool) (at, hold int) {
for j := 0; j < len(s); {
switch c := s[j]; {
case c == '`':
k := j
for k < len(s) && s[k] == '`' {
k++
}
if k == len(s) && !last {
return -1, len(s) - j
}
switch n := k - j; {
case m.fence > 0:
if !m.mid && n >= m.fence {
m.fence = 0
}
case m.span > 0:
if n == m.span {
m.span = 0
}
case !m.mid && n >= 3:
m.fence = n
default:
m.span = n
}
m.mid = true
j = k
case c == '\n':
m.span, m.mid = 0, false
j++
case c == ' ' || c == '\t':
j++
case c == '<' && m.span == 0 && m.fence == 0:
if strings.HasPrefix(s[j:], close) {
return j, 0
}
if !last && strings.HasPrefix(close, s[j:]) {
return -1, len(s) - j
}
m.mid = true
j++
default:
m.mid = true
j++
}
}
return -1, 0
}
// afterThought is t without a leading <think>…</think> block, a whole
// reply's thinking where its API leaves it in the text; t when it has none.
func afterThought(t string) string {
rest, ok := strings.CutPrefix(t, "<think>")
if !ok {
return t
}
var m mdCode
if i, _ := m.find(rest, "</think>", true); i >= 0 {
return strings.TrimSpace(rest[i+len("</think>"):])
}
return t
}
// markedThought sends a piece of text Gemini marked as a thought
// (extra_content.google.thought) as thinking. AI Studio's OpenAI-compatible
// API may still wrap it in <thought> tags, and mark only the chunk with the
@@ -1184,6 +1265,12 @@ func (d *chatDecoder) decode(data string, emit func(Event)) error {
}
if t != "" {
emit(Event{Kind: KThink, Text: t})
if !d.thought && d.lead == "" {
// a reply whose thinking has a field of its own doesn't
// also give it in its text: a <think> there is the
// model's words (#2634)
d.past = true
}
}
if c.Delta.ExtraContent.Google.Thought {
d.markedThought(content, emit)
+3 -15
View File
@@ -278,11 +278,7 @@ func noPrediction(said string) string {
// or unusable answer is no prediction.
func predictionJSON(said string) (string, bool) {
t := strings.TrimSpace(said)
if rest, ok := strings.CutPrefix(t, "<think>"); ok {
if _, after, ok := strings.Cut(rest, "</think>"); ok {
t = strings.TrimSpace(after)
}
}
t = afterThought(t)
if strings.HasPrefix(t, "```") {
t = strings.TrimPrefix(t, "```")
if i := strings.IndexByte(t, '\n'); i >= 0 && !strings.Contains(t[:i], "{") {
@@ -324,11 +320,7 @@ func noDescription(said string) string {
// object Codex asks for. An unusable answer returns an empty string.
func descriptionJSON(said string) string {
t := strings.TrimSpace(said)
if rest, ok := strings.CutPrefix(t, "<think>"); ok {
if _, after, ok := strings.Cut(rest, "</think>"); ok {
t = strings.TrimSpace(after)
}
}
t = afterThought(t)
if strings.HasPrefix(t, "```") {
t = strings.TrimPrefix(t, "```")
if i := strings.IndexByte(t, '\n'); i >= 0 && !strings.Contains(t[:i], "{") {
@@ -492,11 +484,7 @@ func titleShapeOf(body []byte) titleShape {
func titleJSON(said string, shape titleShape) string {
t := strings.TrimSpace(said)
// a reasoning model's thoughts, where its API leaves them in the text
if rest, ok := strings.CutPrefix(t, "<think>"); ok {
if _, after, ok := strings.Cut(rest, "</think>"); ok {
t = strings.TrimSpace(after)
}
}
t = afterThought(t)
if strings.HasPrefix(t, "```") {
t = strings.TrimPrefix(t, "```")
if i := strings.IndexByte(t, '\n'); i >= 0 && !strings.Contains(t[:i], "{") {
+1 -1
View File
@@ -523,7 +523,7 @@ func (s *Server) streamTranslated(w http.ResponseWriter, r *http.Request, p prov
return writeError(w, from, 502, failed), failed
}
} else {
dec := decoder(actual)
dec := decoderFor(p, actual)
attemptSee := see
if names := textCallNames(request.Tools); names != nil {
t := &textCallSee{names: names, see: see}
+13 -1
View File
@@ -5542,7 +5542,7 @@ func (s *Server) translate(w http.ResponseWriter, r *http.Request, p provider.Pr
}
return writeVendorError(w, from, res.StatusCode, msg, b), msg
}
dec := decoder(actual)
dec := decoderFor(p, actual)
rd, sse := eventStream(res)
if !sse {
// the provider ignored stream:true; read the whole reply as one
@@ -5787,6 +5787,18 @@ func build(proto provider.Protocol, r *Request, model, host string, rejectTemp b
return out, nil
}
// decoderFor is decoder for p's replies. A plugin's Chat text is read as
// OpenCode reads it, as it came: the plugin knows its vendor and gives its
// reasoning apart, so a <think> at the head of its text is the model's
// words, not a block of thinking to take out (Qoder's, #2634).
func decoderFor(p provider.Provider, proto provider.Protocol) func(data string, emit func(Event)) error {
if proto == provider.Chat && p.IsPlugin() {
d := &chatDecoder{past: true}
return d.decode
}
return decoder(proto)
}
func decoder(proto provider.Protocol) func(data string, emit func(Event)) error {
switch proto {
case provider.Chat:
+1 -1
View File
@@ -1085,7 +1085,7 @@ func (s *Server) askTranslated(p provider.Provider, to provider.Protocol, model
go func() {
defer close(events)
defer res.Body.Close()
dec := decoder(actual)
dec := decoderFor(p, actual)
send := func(ev Event) error {
select {
case events <- ev:
+212
View File
@@ -0,0 +1,212 @@
package gateway
import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// The reply in Kane-Kuroneko's #2634, as its bytes were: thinking that
// writes the close tag out as an inline-code example, then the answer.
const exampleClose = "<think>开始分析。使用 `<think>...</think>` 标签。\n继续分析。</think>\n最终正文。"
// The boundary #2634 saw from Qoder's plugin: the answer began at the
// backtick after the first </think>, and the reasoning was "...\n".
const qoderBoundary = "<think>...\n</think>` 标签或 JSON 格式,Qoder 插件将其转为 OpenAI `tool_calls`"
// chatChunks is a Chat stream giving text one Unicode character a delta,
// each reasoning piece before it in reasoning_content.
func chatChunks(text string, reasoning ...string) string {
var lines []string
add := func(delta map[string]any, finish any) {
b, _ := json.Marshal(map[string]any{"id": "c1", "object": "chat.completion.chunk", "model": "m1",
"choices": []any{map[string]any{"index": 0, "delta": delta, "finish_reason": finish}}})
lines = append(lines, "data: "+string(b))
}
for _, r := range reasoning {
add(map[string]any{"role": "assistant", "reasoning_content": r}, nil)
}
for _, r := range text {
add(map[string]any{"role": "assistant", "content": string(r)}, nil)
}
add(map[string]any{}, "stop")
lines = append(lines, `data: {"id":"c1","object":"chat.completion.chunk","choices":[],"usage":{"prompt_tokens":5,"completion_tokens":5}}`, "data: [DONE]")
return sse(lines...)
}
// A <think> example written in Markdown code, inline or fenced, is the
// thinking's words; only the close outside code ends it, however the text
// falls across chunks.
func TestChatThinkCloseInCode(t *testing.T) {
run := func(parts ...string) (think, text string) {
var d chatDecoder
for i, p := range parts {
ch := map[string]any{"index": 0, "delta": map[string]any{"content": p}}
if i == len(parts)-1 {
ch["finish_reason"] = "stop"
}
b, _ := json.Marshal(map[string]any{"id": "x", "choices": []any{ch}})
d.decode(string(b), func(ev Event) {
switch ev.Kind {
case KThink:
think += ev.Text
case KText:
text += ev.Text
}
})
}
return
}
runes := func(s string) []string {
var out []string
for _, r := range s {
out = append(out, string(r))
}
return out
}
want := "开始分析。使用 `<think>...</think>` 标签。\n继续分析。"
for _, c := range []struct {
name string
parts []string
think, text string
}{
{"#2634 whole", []string{exampleClose}, want, "最终正文。"},
{"#2634 a character a chunk", runes(exampleClose), want, "最终正文。"},
{"#2634 a byte a chunk", strings.Split(exampleClose, ""), want, "最终正文。"},
{"a double-backtick span", []string{"<think>a ``x`</think>`` b</think>c"}, "a ``x`</think>`` b", "c"},
{"a fenced block", runes("<think>like\n```xml\n</think>\n```\nso</think>\nok"), "like\n```xml\n</think>\n```\nso", "ok"},
{"a span ends with its line", []string{"<think>a `b\n</think>\nok"}, "a `b\n", "ok"},
{"backticks after the close", runes("<think>a</think>\n`x` y"), "a", "`x` y"},
{"a close tag split by a chunk", []string{"<think>a `", "x` b</th", "ink>c"}, "a `x` b", "c"},
{"backticks held at the end", []string{"<think>a ``"}, "a ``", ""},
} {
t.Run(c.name, func(t *testing.T) {
if think, text := run(c.parts...); think != c.think || text != c.text {
t.Errorf("think %q text %q, want %q %q", think, text, c.think, c.text)
}
})
}
}
// A reply whose thinking came in reasoning_content gives none in its text:
// a <think> there is what the model said (#2634).
func TestChatThinkTagAfterReasoningField(t *testing.T) {
var d chatDecoder
var think, text string
readSSE(strings.NewReader(chatChunks(qoderBoundary, "先想一想。")), func(_, data string) error {
return d.decode(data, func(ev Event) {
switch ev.Kind {
case KThink:
think += ev.Text
case KText:
text += ev.Text
}
})
})
if think != "先想一想。" || text != qoderBoundary {
t.Errorf("think %q text %q, want the reasoning field's and the text as it came", think, text)
}
}
// #2634 through each route that reads a built-in Chat upstream's text:
// Codex's Responses and Claude Code's Messages get the example's close in
// the reasoning and the answer whole.
func TestThinkExampleReachesClientsWhole(t *testing.T) {
f := &fake{t: t, reply: chatChunks(exampleClose)}
setup(t, provider.Chat, f)
code, body := post(t, "/v1/responses", `{"model":"fake/m1","stream":true,"input":[{"role":"user","content":"hi"}]}`)
if code != 200 {
t.Fatalf("responses: %d %s", code, body)
}
reasoning, text := thinkAndText(body)
if !strings.Contains(reasoning, "`<think>...</think>` 标签。\n继续分析。") || text != "最终正文。" {
t.Errorf("responses: reasoning %q, message %q", reasoning, text)
}
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", "/v1/messages", strings.NewReader(`{"model":"fake/m1","stream":true,"max_tokens":100,"messages":[{"role":"user","content":"hi"}]}`))
req.Header.Set("anthropic-version", "2023-06-01")
New().Handler().ServeHTTP(rec, req)
if rec.Code != 200 {
t.Fatalf("messages: %d %s", rec.Code, rec.Body)
}
var thinking, said string
for _, ev := range events(rec.Body.String()) {
if ev["type"] != "content_block_delta" {
continue
}
d, _ := ev["delta"].(map[string]any)
if s, ok := d["thinking"].(string); ok {
thinking += s
}
if s, ok := d["text"].(string); ok {
said += s
}
}
if !strings.Contains(thinking, "`<think>...</think>` 标签。\n继续分析。") || said != "最终正文。" {
t.Errorf("messages: thinking %q, text %q", thinking, said)
}
}
// thinkAndText is a Responses stream's reasoning summary and message
// text, from its finished items.
func thinkAndText(body string) (reasoning, text string) {
for _, ev := range events(body) {
if ev["type"] != "response.output_item.done" {
continue
}
item, _ := ev["item"].(map[string]any)
key, parts := "text", item["content"]
if item["type"] == "reasoning" {
parts = item["summary"]
}
list, _ := parts.([]any)
for _, p := range list {
m, _ := p.(map[string]any)
s, _ := m[key].(string)
if item["type"] == "reasoning" {
reasoning += s
} else {
text += s
}
}
}
return
}
// A plugin's Chat reply reaches Codex as OpenCode would show it: Qoder's
// plugin gives its reasoning apart, so text that begins with <think> is
// the answer, all of it, never cut at the first </think> (#2634).
func TestPluginThinkTagIsText(t *testing.T) {
pid := besideFake(t, "qoder", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.ReadAll(r.Body)
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, chatChunks(qoderBoundary))
}))
code, body := post(t, "/v1/responses", `{"model":"`+pid+`/fake-1","stream":true,"input":[{"role":"user","content":"hi"}]}`)
if code != 200 {
t.Fatalf("%d %s", code, body)
}
if reasoning, text := thinkAndText(body); reasoning != "" || text != qoderBoundary {
t.Errorf("reasoning %q, message %q; want the text as the plugin gave it", reasoning, text)
}
}
// A title, description or prediction Codex asked for loses a leading
// thinking block the same way: up to the close outside code.
func TestAfterThoughtCloseInCode(t *testing.T) {
if got := afterThought(exampleClose); got != "最终正文。" {
t.Errorf("afterThought = %q", got)
}
if got := descriptionJSON("<think>`</think>` is a tag</think>\nFix the parser"); !strings.Contains(got, "Fix the parser") || strings.Contains(got, "is a tag") {
t.Errorf("descriptionJSON = %q", got)
}
if got := afterThought("<think>never closed"); got != "<think>never closed" {
t.Errorf("afterThought of an open block = %q", got)
}
}