qoder: thinking turned off reaches Qoder as off, a refused usage sign-in no longer lapses the account, only a gone sign-in is a 401, and a tool's images are sent (#162 review follow-ups)

- Chat reasoning_effort "none" (and Responses reasoning.effort "none") was read as low by effortOf before qoderEffort saw it, so a model that can stop thinking (qfmodel) was sent enable_thinking true at low, and an Anthropic request with thinking disabled got the model's default (max on an always-thinking one). The request now carries ThinkOff beside Effort — set for effort "none" and for Anthropic thinking {"type":"disabled"} — and Qoder reads it as none: off where the model can stop, its lowest effort where it can't. effortOf and Effort are unchanged, so every other vendor gets what it did.
- The device token serves only Qoder's account pages (usage); chat runs on the job token. A refused device-token refresh marked the whole account "sign-in has expired" though chat still worked. Now only a refused job-token refresh lapses the account; a refused device one leaves usage unavailable with that reason ("Qoder refused the account-page sign-in (chat still works) — sign in again to see usage").
- askQoder answered 401 for any credential error, so a refresh that timed out made Claude Code ask to log in again. Errors that mean the sign-in is gone (not signed in, no such account, unreadable, no refresh token, a refused job refresh) now wrap provider.ErrQoderSignIn and are 401; anything else (a timeout, the network) is 502.
- Images a tool returned were dropped. Qoder's tool turns hold text, but its user turns take image_url blocks, so the images now follow the tool turns in a user turn — "[From the result of <tool> (tool call <id>):]" then the images — joined to the start of the user's own next turn, and the tool turn notes that they follow, the way buildChat does for Chat upstreams.

Tested: TestQoderThinkingOff (Chat, Responses, Anthropic off on qfmodel and on an always-thinking model; other vendors' Effort still low; thinking unmentioned keeps the default), TestQoderCredentialStatus (timeout and network 502, a gone sign-in 401), TestQoderToolResultImages, TestQoderRefusedRefreshLapses (device refused: not lapsed, usage reason; job refused: lapsed, ErrQoderSignIn) and TestQoderRefreshNetworkErrorNotSignIn — each of the first four fails on main. go build (darwin, GOOS=windows) and go test -tags nogui ./... pass
This commit is contained in:
yetone
2026-09-29 17:03:45 +08:00
parent 2ed6dd0520
commit 3efba14ed5
9 changed files with 232 additions and 34 deletions
+3 -1
View File
@@ -147,7 +147,9 @@ func parseAnthropic(body []byte) (*Request, error) {
// output_config's effort sets how hard the model thinks only when it
// was asked to think: Claude Code's title requests carry effort but no
// thinking, and reasoning_effort would turn it on upstream
if th := a.Thinking; th != nil && (th.Type == "enabled" || th.Type == "adaptive") {
if th := a.Thinking; th != nil && th.Type == "disabled" {
r.ThinkOff = true
} else if th != nil && (th.Type == "enabled" || th.Type == "adaptive") {
r.Thinking = true
r.Effort = effortOfBudget(th.BudgetTokens)
if oc := a.OutputConfig; oc != nil {
+1
View File
@@ -64,6 +64,7 @@ func parseChat(body []byte) (*Request, error) {
if r.Effort != "" {
r.Thinking = true
}
r.ThinkOff = strings.EqualFold(strings.TrimSpace(c.ReasoningEffort), "none")
var stop string
if json.Unmarshal(c.Stop, &stop) == nil && stop != "" {
r.Stop = []string{stop}
+7 -3
View File
@@ -96,9 +96,13 @@ type Request struct {
Stream bool
Effort string // low | medium | high | xhigh | max, when the client asked
Thinking bool // the client asked for visible reasoning
Parallel *bool // parallel tool calls allowed
WebSearch bool // the client offered its provider's own web search
Fast bool // the client asked for priority processing: service_tier priority (Codex's Fast mode)
// ThinkOff is the client turning reasoning off: effort "none" (which
// Effort reads as low, for vendors with no way to turn it off) or an
// Anthropic request with thinking disabled.
ThinkOff bool
Parallel *bool // parallel tool calls allowed
WebSearch bool // the client offered its provider's own web search
Fast bool // the client asked for priority processing: service_tier priority (Codex's Fast mode)
// CacheKey is the client's prompt_cache_key (Codex sends its thread's
// id), which OpenAI, and relays in front of it, route a conversation by
// to where its prompt is cached.
+71 -10
View File
@@ -2,8 +2,10 @@ package gateway
import (
"bufio"
"cmp"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
@@ -151,7 +153,13 @@ func (s *Server) askQoder(model, user string) round {
return func(ctx context.Context, req *Request) (<-chan Event, int, string) {
cred, err := qoderAuth(ctx, user)
if err != nil {
return nil, 401, "Qoder: " + err.Error()
// only a sign-in that is gone asks the agent to log in again;
// a refresh that timed out or never reached Qoder may pass
status := 502
if errors.Is(err, provider.ErrQoderSignIn) {
status = 401
}
return nil, status, "Qoder: " + err.Error()
}
config, err := qoderModel(ctx, user, model)
if err != nil {
@@ -234,7 +242,11 @@ func qoderChatBody(req *Request, model qoder.ModelInfo) ([]byte, error) {
sys := map[string]any{"type": "text", "text": qoderSysText(req)}
all := []any{map[string]any{"role": "system", "content": []any{sys}}}
thinking, effort := qoderEffort(req.Effort, model)
asked := req.Effort
if req.ThinkOff {
asked = "none" // Effort reads none as low
}
thinking, effort := qoderEffort(asked, model)
maxTok := int64(32000)
if req.MaxTokens > 0 {
maxTok = int64(req.MaxTokens)
@@ -269,13 +281,55 @@ func qoderChatBody(req *Request, model qoder.ModelInfo) ([]byte, error) {
// qoderMessages renders magpie's turns as OpenAI turns, the format Qoder's
// chat endpoint takes: an assistant's tool calls as tool_calls and their
// results as tool turns named by tool_call_id, so a result is paired with
// its call and not by order.
// its call and not by order. A tool turn holds text only, so the images a
// tool returned go after the tool turns in a user turn — as the start of
// the user's own turn when one comes next — the way buildChat sends them.
func qoderMessages(ms []Message) []any {
var out []any
names := map[string]string{}
var seen []any
seeLater := func(p Part) int {
var ims []any
for _, im := range p.Images {
if im.Data != "" {
ims = append(ims, map[string]any{"type": "image_url",
"image_url": map[string]any{"url": "data:" + im.MediaType + ";base64," + im.Data}})
}
}
if len(ims) == 0 {
return 0
}
of := "tool call " + p.CallID
if name := cmp.Or(names[p.CallID], p.Name); name != "" {
of = name + " (" + of + ")"
}
seen = append(seen, map[string]any{"type": "text", "text": "[From the result of " + of + ":]"})
seen = append(seen, ims...)
return len(ims)
}
showSeen := func() {
if len(seen) > 0 {
out = append(out, map[string]any{"role": "user", "content": seen})
seen = nil
}
}
for _, m := range ms {
var blocks []any
var calls []map[string]any
var text string
flush := func() {
if len(blocks) == 0 {
return
}
if m.Role == "user" && len(seen) > 0 {
blocks, seen = append(seen, blocks...), nil
}
out = append(out, map[string]any{"role": m.Role, "content": blocks})
blocks = nil
}
if m.Role != "user" {
showSeen()
}
for _, p := range m.Parts {
switch p.Kind {
case Text:
@@ -296,17 +350,25 @@ func qoderMessages(ms []Message) []any {
if id == "" {
id = "call_" + qoder.NewID()
}
names[id] = p.Name
calls = append(calls, map[string]any{"id": id, "type": "function",
"function": map[string]any{"name": p.Name, "arguments": string(argsOf(p))}})
case ToolResult:
if len(blocks) > 0 {
out = append(out, map[string]any{"role": m.Role, "content": blocks})
blocks = nil
}
flush()
txt := p.Text
if p.IsError {
txt = "Error: " + txt
}
if n := seeLater(p); n > 0 {
note := fmt.Sprintf("[The tool returned %d images; they follow in the next message.]", n)
if n == 1 {
note = "[The tool returned an image; it follows in the next message.]"
}
if strings.TrimSpace(txt) != "" {
txt += "\n\n"
}
txt += note
}
out = append(out, map[string]any{"role": "tool", "tool_call_id": p.CallID, "content": txt})
}
}
@@ -314,10 +376,9 @@ func qoderMessages(ms []Message) []any {
out = append(out, map[string]any{"role": "assistant", "content": text, "tool_calls": calls})
continue
}
if len(blocks) > 0 {
out = append(out, map[string]any{"role": m.Role, "content": blocks})
}
flush()
}
showSeen()
return out
}
+97
View File
@@ -432,3 +432,100 @@ func TestServeQoder(t *testing.T) {
}
}
}
// Thinking turned off reaches Qoder as off: reasoning_effort "none", which
// Effort reads as low for other vendors, and Anthropic's thinking disabled.
func TestQoderThinkingOff(t *testing.T) {
model := testQoderModel(t)
always, err := qoder.ModelConfigs([]byte(`{"chat":[{"key":"gf","enable":true,"is_reasoning":true,"thinking_config":{"enabled":{"is_default":true,"efforts":{"max":{"is_default":true},"high":{},"low":{}}}}}]}`))
if err != nil {
t.Fatal(err)
}
for _, tt := range []struct {
from provider.Protocol
body string
}{
{provider.Chat, `{"model":"m","reasoning_effort":"none","messages":[{"role":"user","content":"hi"}]}`},
{provider.Responses, `{"model":"m","reasoning":{"effort":"none"},"input":"hi"}`},
{provider.Anthropic, `{"model":"m","max_tokens":100,"thinking":{"type":"disabled"},"messages":[{"role":"user","content":"hi"}]}`},
} {
req, err := parse(tt.from, []byte(tt.body))
if err != nil {
t.Fatal(err)
}
if tt.from != provider.Anthropic && req.Effort != "low" {
t.Errorf("%s: other vendors' effort changed: %q", tt.from, req.Effort)
}
b, _ := qoderChatBody(req, model)
if gjson.GetBytes(b, "parameters.enable_thinking").Bool() || gjson.GetBytes(b, "parameters.reasoning_effort").Exists() {
t.Errorf("%s: thinking off on a model that can stop: %s", tt.from, gjson.GetBytes(b, "parameters").Raw)
}
b, _ = qoderChatBody(req, always[0])
if !gjson.GetBytes(b, "parameters.enable_thinking").Bool() || gjson.GetBytes(b, "parameters.reasoning_effort").String() != "low" {
t.Errorf("%s: thinking off on an always-thinking model: %s", tt.from, gjson.GetBytes(b, "parameters").Raw)
}
}
// thinking not mentioned is the model's own default, as before
req, _ := parse(provider.Anthropic, []byte(`{"model":"m","max_tokens":100,"messages":[{"role":"user","content":"hi"}]}`))
b, _ := qoderChatBody(req, always[0])
if gjson.GetBytes(b, "parameters.reasoning_effort").String() != "max" {
t.Errorf("unmentioned thinking: %s", gjson.GetBytes(b, "parameters").Raw)
}
}
// Only a sign-in that is gone is a 401 (the agent asks to log in again); a
// refresh that timed out or failed on the network is a 502.
func TestQoderCredentialStatus(t *testing.T) {
done := qoderUpstream(t, nil)
defer done()
s := New()
for _, tt := range []struct {
err error
want int
}{
{fmt.Errorf("Qoder: refresh: %w", context.DeadlineExceeded), 502},
{errors.New("dial tcp: connection refused"), 502},
{fmt.Errorf("one@x's Qoder sign-in has expired — sign in again (%w)", provider.ErrQoderSignIn), 401},
} {
qoderAuth = func(context.Context, string) (*qoder.Credential, error) { return nil, tt.err }
ch, status, _ := s.askQoder("qfmodel", "one@x")(context.Background(), &Request{Model: "qfmodel"})
if ch != nil || status != tt.want {
t.Errorf("%v: status %d, want %d", tt.err, status, tt.want)
}
}
}
// A tool turn holds text only, so a tool's images follow in a user turn,
// joined to the user's own next turn.
func TestQoderToolResultImages(t *testing.T) {
png := Part{Kind: Image, MediaType: "image/png", Data: "iVBOR"}
msgs := qoderMessages([]Message{
{Role: "user", Parts: []Part{{Kind: Text, Text: "look"}}},
{Role: "assistant", Parts: []Part{{Kind: ToolCall, ID: "call_A", Name: "screenshot", Args: json.RawMessage(`{}`)}}},
{Role: "user", Parts: []Part{
{Kind: ToolResult, CallID: "call_A", Text: "shot taken", Images: []Part{png}},
{Kind: Text, Text: "what do you see?"}}},
{Role: "assistant", Parts: []Part{{Kind: ToolCall, ID: "call_B", Name: "screenshot", Args: json.RawMessage(`{}`)}}},
{Role: "user", Parts: []Part{{Kind: ToolResult, CallID: "call_B", Images: []Part{png, png}}}},
})
b, _ := json.Marshal(msgs)
got := gjson.ParseBytes(b)
if len(msgs) != 7 {
t.Fatalf("turns %s", b)
}
if got.Get("2.role").String() != "tool" || !strings.Contains(got.Get("2.content").String(), "shot taken") ||
!strings.Contains(got.Get("2.content").String(), "an image; it follows") {
t.Fatalf("tool turn %s", got.Get("2").Raw)
}
u := got.Get("3")
if u.Get("role").String() != "user" || !strings.Contains(u.Get("content.0.text").String(), "screenshot (tool call call_A)") ||
u.Get("content.1.image_url.url").String() != "data:image/png;base64,iVBOR" || u.Get("content.2.text").String() != "what do you see?" {
t.Fatalf("images with the user's turn %s", u.Raw)
}
if got.Get("5.role").String() != "tool" || !strings.Contains(got.Get("5.content").String(), "2 images") {
t.Fatalf("second tool turn %s", got.Get("5").Raw)
}
if got.Get("6.role").String() != "user" || got.Get("6.content.#").Int() != 3 {
t.Fatalf("trailing images %s", got.Get("6").Raw)
}
}
+1
View File
@@ -90,6 +90,7 @@ func parseResponses(body []byte) (*Request, error) {
if q.Reasoning != nil {
r.Effort = effortOf(q.Reasoning.Effort)
r.Thinking = true
r.ThinkOff = strings.EqualFold(strings.TrimSpace(q.Reasoning.Effort), "none")
}
var s string
if json.Unmarshal(q.Input, &s) == nil {
+16 -16
View File
@@ -92,20 +92,17 @@ func qoderPersist(l savedLogin, c qoder.Credential, renewed bool) error {
return nil
}
// qoderRefreshFailed marks the account lapsed when Qoder refused its refresh
// token: that sign-in is gone and has to be made again. A refresh that never
// got an answer marks nothing.
// ErrQoderSignIn is under every error that says the Qoder sign-in itself is
// gone — not signed in, unreadable, or its refresh refused — as against a
// refresh that timed out or never reached Qoder, which may pass.
var ErrQoderSignIn = errors.New("Qoder sign-in")
// qoderRefreshFailed marks the account lapsed when Qoder refused its job
// refresh token: that sign-in is gone and has to be made again. A refresh
// that never got an answer marks nothing.
func qoderRefreshFailed(user string, err error) error {
var job *qoder.JobTokenRefreshHTTPError
var device *qoder.DeviceTokenRefreshHTTPError
status := 0
switch {
case errors.As(err, &job):
status = job.StatusCode
case errors.As(err, &device):
status = device.StatusCode
}
if status != http.StatusUnauthorized && status != http.StatusForbidden {
if !errors.As(err, &job) || job.StatusCode != http.StatusUnauthorized && job.StatusCode != http.StatusForbidden {
return err
}
msg := user + "'s Qoder sign-in has expired — sign in again"
@@ -118,7 +115,7 @@ func qoderRefreshFailed(user string, err error) error {
}
}
_ = writeLogins(ls)
return fmt.Errorf("%s (%w)", msg, err)
return fmt.Errorf("%s (%w)", msg, errors.Join(ErrQoderSignIn, err))
}
func qoderWho(c qoder.Credential) string { return firstNonEmpty(c.Email, c.UID) }
@@ -204,7 +201,7 @@ func QoderCredential(ctx context.Context, user string) (*qoder.Credential, error
if user == "" {
ls := qoderLogins()
if len(ls) == 0 {
return nil, fmt.Errorf("Qoder: not signed in")
return nil, fmt.Errorf("Qoder: not signed in (%w)", ErrQoderSignIn)
}
user = ls[0].User
}
@@ -215,11 +212,11 @@ func QoderCredential(ctx context.Context, user string) (*qoder.Credential, error
}
l, found := qoderLookup(user)
if !found {
return nil, fmt.Errorf("no Qoder account %q", user)
return nil, fmt.Errorf("no Qoder account %q (%w)", user, ErrQoderSignIn)
}
c, ok, changed := qoderCurrent(l)
if !ok {
return nil, fmt.Errorf("Qoder: unreadable sign-in")
return nil, fmt.Errorf("Qoder: unreadable sign-in (%w)", ErrQoderSignIn)
}
if c.MachineID == "" {
c.MachineID = qoder.NewMachineID()
@@ -231,6 +228,9 @@ func QoderCredential(ctx context.Context, user string) (*qoder.Credential, error
fresh, err := c.Refresh(rctx, qoderClient)
cancel()
if err != nil {
if c.RefreshToken == "" { // nothing to refresh with: sign in again
err = errors.Join(ErrQoderSignIn, err)
}
return nil, qoderRefreshFailed(l.User, err)
}
c, changed, renewed = fresh, true, true
+28 -3
View File
@@ -194,14 +194,39 @@ func TestQoderRefusedRefreshLapses(t *testing.T) {
}
return ""
}
if _, err := qoderRefreshDevice(context.Background(), "one@x", c.DeviceToken); err == nil || lapsed() == "" {
// the device token serves only usage: chat still works, so the
// account isn't lapsed and usage says why it is missing
if _, err := qoderRefreshDevice(context.Background(), "one@x", c.DeviceToken); err == nil || lapsed() != "" ||
!strings.Contains(err.Error(), "usage is unavailable") || errors.Is(err, ErrQoderSignIn) {
t.Fatalf("device refresh refused: %v lapsed %q", err, lapsed())
}
if _, err := QoderCredential(context.Background(), "one@x"); err == nil || lapsed() == "" || !errors.Is(err, ErrQoderSignIn) {
t.Fatalf("job refresh refused: %v lapsed %q", err, lapsed())
}
if err := qoderSave(c); err != nil || lapsed() != "" {
t.Fatalf("sign-in again keeps lapsed: %v", err)
}
if _, err := QoderCredential(context.Background(), "one@x"); err == nil || lapsed() == "" {
t.Fatalf("job refresh refused: %v lapsed %q", err, lapsed())
}
// A job refresh that never got an answer is no refused sign-in.
func TestQoderRefreshNetworkErrorNotSignIn(t *testing.T) {
signIn(t)
qoderTestClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
panic(http.ErrAbortHandler)
}))
c := qoderTestCredential("one")
c.ExpiresAt = time.Now().Add(time.Minute).UnixMilli()
if err := qoderSave(c); err != nil {
t.Fatal(err)
}
_, err := QoderCredential(context.Background(), "one@x")
if err == nil || errors.Is(err, ErrQoderSignIn) {
t.Fatalf("network failure read as a lapsed sign-in: %v", err)
}
for _, l := range Logins("qoder") {
if l.Lapsed != "" {
t.Fatalf("lapsed on a network failure: %q", l.Lapsed)
}
}
}
+8 -1
View File
@@ -5,6 +5,7 @@ import (
"encoding/json"
"errors"
"fmt"
"net/http"
"github.com/yetone/magpie/internal/qoder"
)
@@ -61,7 +62,13 @@ func qoderRefreshDevice(ctx context.Context, user, attempted string) (string, er
dt, err := qoder.RefreshDeviceToken(rctx, qoderClient, "", c.DeviceRefresh)
cancel()
if err != nil {
return "", qoderRefreshFailed(l.User, err)
// The device token serves only the account pages (usage); chat
// runs on the job token, so a refused one doesn't lapse the account.
var refused *qoder.DeviceTokenRefreshHTTPError
if errors.As(err, &refused) && (refused.StatusCode == http.StatusUnauthorized || refused.StatusCode == http.StatusForbidden) {
return "", fmt.Errorf("Qoder usage is unavailable: Qoder refused the account-page sign-in (chat still works) — sign in again to see usage (%w)", err)
}
return "", err
}
c.DeviceToken, c.DeviceRefresh = dt.Token, dt.RefreshToken
if err := qoderPersist(l, c, false); err != nil {