gateway, claudetui: an interactive run asked another effort goes on in its run, the conversation read from the cache

#5584 (Suge8, magpie 0.1.3216, Claude Code 2.1.318, Pi on Opus 5.5,
interactive mode): a turn asking another effort than the one before let
the run go ("its effort is set at its start, and the next turn asks
another"), and a new Claude Code was told the conversation from a
transcript: 72,416 tokens written to the cache on a 108-message
conversation, 178,309 on a 148-message one (first token after 94.4s).

-p runs take a new level by apply_flag_settings (#502). The interactive
mode can't, as measured on the real 2.1.318 (Haiku 5.5, tmux, magpie's
own arguments):
- typing `/effort high` keeps the cache (55,310 read before, 55,400
  after), but saves the level as the default for new sessions:
  modelSettings.<model>.effortLevel in the settings.json of the
  account's folder, the user's own ~/.claude for Claude Code's own
  sign-in, even with --setting-sources ''. Only `max` is session-only.
- a --settings file rewritten (effortLevel, or modelSettings.<model>)
  changes nothing: the request stays at medium, with or without
  --effort. Claude Code pins the file's content as it starts.
- after `/effort max`, the one field of its requests that changes is
  output_config.effort.

Fix:
- Every interactive run has the guard file (guard.json, {} with no
  safeguards); guardBody writes its safeguards and, once the run was
  told another level than its --effort (ownEffort), "effort" beside
  them. setSafeguards and the new setTUIEffort both write it from the
  run's state (tellGuard, under settingsMu).
- tap.js asks each main request (x-claude-code-request-class: main) at
  the file's effort in output_config.effort, and leaves Claude Code's
  other requests as they were; CLAUDE_CODE_EXTRA_BODY gets the file
  without "effort". It writes guard.json.live at the first main request
  as well as the first one carrying safeguards.
- resume: an interactive run asked another effort calls setTUIEffort.
  A run with no .live (no tap), or a turn asking Claude Code's own
  level ("") of a run started at another, is let go as before, the log
  saying which.
- A level the model refuses (real 2.1.318 on claude-haiku-4-5 through
  such a rewrite: "API Error: 400 This model does not support the
  effort parameter.") fails the turn as a run started at it would; the
  existing path (ended, !ok) lets the run go, and the turn asked again
  starts a Claude Code at that --effort.
- docs/subsystems/claude-subscription-bridge.md says so.

Run at this tree (base 9e6687e3):
- New: TestTapAsksTheGuardFilesEffort (bun and node),
  TestClaudeTUIEffortChangeGoesOnInItsRun,
  TestClaudeTUIEffortChangeWithoutTapStartsAnew,
  TestClaudeTUIEffortRefusedStartsAnew: ok; with the guard tests,
  -race -count=3: ok.
- gofmt -l: clean. go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...; go build, GOOS=linux go build -tags nogui,
  GOOS=windows go build: ok.
- go test -tags nogui ./... (Go 1.26.8, go.mod's; sandbox HOME):
  everything ok but TestPluginSOCKSProxy (#2207, Bun 1.4.4 here) and
  TestLaneLimitRoutes (#5150, reads the running gateway; ok alone).
- The built binary, `magpie serve` on 127.0.0.1:34251 in a sandbox HOME,
  XDG dirs and TMPDIR, Claude Code 2.1.318 signed in from a copy of the
  access token (no refresh token), three turns of one conversation on
  claude-haiku-5-5 at medium, high, medium (~20K tokens of history):
  one Claude Code pid for all three, no "its effort is set at its
  start"; the requests as sent (a read-only preload under the tap) asked
  medium, high, medium; usage read/written 795/19,413, 19,869/384,
  20,228/71. ~/.claude/settings.json byte for byte unchanged.

Broken by hand:
- resume's old abortFor back: the three gateway tests red ("started 2
  runs, want one at medium"; the log's reason; the refused turn
  answered 200).
- tap.js not asking the effort: TestTapAsksTheGuardFilesEffort red
  ("request 1 was sent … medium").

Not tried: Opus and Sonnet through the interactive mode (Haiku 5.5
only); whether Anthropic thinks harder at the rewritten level (the
request asks it, the reply doesn't tell); a Claude Code in WSL.
This commit is contained in:
Suge8
2026-11-10 18:57:44 +08:00
committed by yetone
parent 901e641f27
commit 543eb39b94
7 changed files with 406 additions and 51 deletions
+44 -12
View File
@@ -480,17 +480,19 @@ Claude Code reads `CLAUDE_CODE_EXTRA_BODY` from its own environment as
it builds each request, and nothing outside it changes that once it runs
(2.1.316: a later `apply_flag_settings` or a rewritten `--settings` file
changes nothing it sends). `startRun` puts them in its environment, and
writes the same extra body to `guard.json` in the run's temp folder,
named to the helper by `MAGPIE_CLAUDE_GUARD` (`claudetui.GuardEnv`). The
helper hands it to Claude Code as WSL reads it, and takes it out of the
environment otherwise. On each `/v1/messages` request whose body is a
string with a `safeguards` key, `tap.js` reads the file, puts its
`safeguards` there in place of Claude Code's, and sets
`CLAUDE_CODE_EXTRA_BODY` in Claude Code's environment to it, so the
requests after are built with it. A JSON parse and stringify of a
2.1.316 body is byte for byte the same, so the request is what Claude
Code sends with that variable. At the first such request it writes
`guard.json.live`. `setSafeguards` replaces the file (temp file and
writes the same extra body to `guard.json` in the run's temp folder
(`guardBody`; every interactive run has the file, `{}` with no
safeguards), named to the helper by `MAGPIE_CLAUDE_GUARD`
(`claudetui.GuardEnv`). The helper hands it to Claude Code as WSL reads
it, and takes it out of the environment otherwise. On each
`/v1/messages` request whose body is a string with a `safeguards` key,
`tap.js` reads the file, puts its `safeguards` there in place of Claude
Code's, and sets `CLAUDE_CODE_EXTRA_BODY` in Claude Code's environment
to it (the file without its `effort`), so the requests after are built
with it. A JSON parse and stringify of a 2.1.316 body is byte for byte
the same, so the request is what Claude Code sends with that variable.
At the first such request, or the first of the main turn's
(`x-claude-code-request-class: main`), it writes `guard.json.live`. `setSafeguards` replaces the file (temp file and
rename) before the turn or tool results go to the run, and the run goes
on, its cache too: an auto-mode tool loop's classifier context grows by
a `prior_turn_context` entry each batch, and restarting for that began
@@ -500,6 +502,35 @@ the cache again (3 to 10 times the cost;
`TestTapPutsTheGuardFilesSafeguards`). A changed safety beta, or
safeguards appearing or going, still restarts.
A turn asking another effort goes on in its run too (#5584). The `-p`
run is told it by `apply_flag_settings` (`setEffort`, #502). The
interactive mode takes another level only from a person typing
`/effort`, and 2.1.318 saves that as the default for new sessions
(`modelSettings.<model>.effortLevel` in the settings of the account's
folder, the user's own `~/.claude/settings.json` for Claude Code's own
sign-in; only `max` is the session's alone), and reads a `--settings`
file once, as it starts. So `setTUIEffort` writes the level beside the
safeguards in `guard.json` (`tellGuard`, from the run's safeguards and
`effort`; none while it is the `--effort` the run started at,
`ownEffort`), and `tap.js` asks each main request at it in
`output_config.effort`, leaving Claude Code's other requests (titles,
summaries, its classifiers) as they were. That is the one field
Claude Code's own `/effort` changes in its requests: on the real
2.1.318 with Haiku 5.5, the turn after one asked high in place of
medium read the whole conversation from the cache (55,392 tokens read,
41 written; the turn before, 55,308 and 84). The level is the request's
own, as `--effort` takes it, not fitted to the model as Claude Code
fits its own: one the model refuses (claude-haiku-4-5 answers "API
Error: 400 This model does not support the effort parameter.") fails
that turn, which lets the run go (`ended`), and the turn asked again
starts a Claude Code at that `--effort`. A run without a `.live` file,
or a turn asking Claude Code's own level (`""`) of a run started at
another, is let go, the log saying why, and the turn starts a run anew
(`TestClaudeTUIEffortChangeGoesOnInItsRun`,
`TestClaudeTUIEffortChangeWithoutTapStartsAnew`,
`TestClaudeTUIEffortRefusedStartsAnew`,
`TestTapAsksTheGuardFilesEffort`).
A run with no `.live` file (no tap, a Claude Code not on
`FetchSession`, or no request yet) can't be given them. Its classifier
context also carries parts that change on nearly every request, the
@@ -653,7 +684,8 @@ subscription with Only switch serves nothing through magpie and shows no
row.
A turn the interactive mode can't take ends the run, and the next starts
anew: a turn that takes earlier turns back, an effort change. A run given up on
anew: a turn that takes earlier turns back, an effort change its tap
can't ask (see the safeguards above). A run given up on
(`letGo`) is not taken back, since the interactive mode can't answer a
control request to stop a turn.
+5 -3
View File
@@ -37,9 +37,11 @@ const tapEnv = "MAGPIE_CLAUDE_TAP"
// GuardEnv names, to the helper, a file of the bridge's that holds the
// extra body (CLAUDE_CODE_EXTRA_BODY) of the client's latest turn: tap.js
// puts its safeguards in each request Claude Code makes, which reads that
// variable only from an environment nothing outside it can change. The
// bridge rewrites the file as a turn brings new ones, and tap.js writes
// <file>.live once it has seen a request it puts them in.
// variable only from an environment nothing outside it can change, and
// the effort the run was told since it started, which tap.js asks each
// main request at. The bridge rewrites the file as a turn brings new
// ones, and tap.js writes <file>.live once it has seen a request it puts
// them in.
const GuardEnv = "MAGPIE_CLAUDE_GUARD"
// how long a message of the transcript waits for its stream, and a turn's
+45 -16
View File
@@ -16,6 +16,13 @@
// Claude Code would have put them there had the variable said so, and
// the variable is set to it for the requests after. The file says it was
// seen (<file>.live) at the first request it could be put in.
//
// The file's effort, beside the extra body, is the level the run was told
// since it started (#5584): each main request asks it in
// output_config.effort, in place of the --effort Claude Code started
// with. The interactive mode takes another level only from a person
// typing /effort, which saves it as the user's default for new sessions;
// a --settings file is read once, as Claude Code starts.
(() => {
const file = process.env.MAGPIE_CLAUDE_TAP;
const guard = process.env.MAGPIE_CLAUDE_GUARD;
@@ -53,37 +60,58 @@
}
let streams = 0;
let live = false;
// body is a request's body with the guard file's safeguards: the same
// bytes when they are what it has, or when it has none to replace (a
// request Claude Code builds without the extra body)
const guarded = (body) => {
if (!guard || typeof body !== "string" || body.indexOf('"safeguards"') < 0) return body;
let extra, now;
// body is a request's body with the guard file's safeguards and effort:
// the same bytes when they are what it has, or when it has none to
// replace (a request Claude Code builds without the extra body). The
// effort goes in the main turn's requests (main) alone, never in what
// Claude Code asks beside them (titles, summaries, its classifiers).
const guarded = (body, main) => {
if (!guard || typeof body !== "string") return body;
const carries = body.indexOf('"safeguards"') >= 0;
if (!carries && !main) return body;
let text, now;
try {
extra = fs.readFileSync(guard, "utf8");
now = JSON.parse(extra);
text = fs.readFileSync(guard, "utf8");
now = JSON.parse(text);
} catch {
return body;
}
if (!now || typeof now !== "object" || !("safeguards" in now)) return body;
if (!now || typeof now !== "object") return body;
// the file is the extra body Claude Code is to send, and the effort
// beside it, which is no field of a request
const { effort, ...extra } = now;
const level = main && typeof effort === "string" ? effort : "";
const safeguards = carries && "safeguards" in extra;
if (!safeguards && !main) return body;
let req;
try {
req = JSON.parse(body);
} catch {
return body;
}
if (!req || typeof req !== "object" || !("safeguards" in req)) return body;
if (!req || typeof req !== "object") return body;
if (safeguards && !("safeguards" in req)) return body;
if (!live) {
live = true;
try {
fs.writeFileSync(guard + ".live", "");
} catch {}
}
if (process.env.CLAUDE_CODE_EXTRA_BODY !== extra) process.env.CLAUDE_CODE_EXTRA_BODY = extra;
if (JSON.stringify(req.safeguards) === JSON.stringify(now.safeguards)) return body;
req.safeguards = now.safeguards;
put({ guard: "set" });
return JSON.stringify(req);
let changed = false;
if (safeguards) {
const env = effort === undefined ? text : JSON.stringify(extra);
if (process.env.CLAUDE_CODE_EXTRA_BODY !== env) process.env.CLAUDE_CODE_EXTRA_BODY = env;
if (JSON.stringify(req.safeguards) !== JSON.stringify(extra.safeguards)) {
req.safeguards = extra.safeguards;
changed = true;
put({ guard: "set" });
}
}
if (level && !(req.output_config && req.output_config.effort === level)) {
req.output_config = { ...(req.output_config || {}), effort: level };
changed = true;
}
return changed ? JSON.stringify(req) : body;
};
// read tells each event of stream s, then its end: cut when it broke
// off, as a dropped connection or Claude Code's own Esc ends it
@@ -125,7 +153,8 @@
try {
const url = String((input && input.url) || input);
if (init && /\/v1\/messages(\?|$)/.test(url)) {
const body = guarded(init.body);
const headers = new Headers(init.headers || (input && input.headers) || undefined);
const body = guarded(init.body, headers.get("x-claude-code-request-class") === "main");
if (body !== init.body) init = { ...init, body };
}
} catch {}
+96
View File
@@ -119,3 +119,99 @@ func TestTapPutsTheGuardFilesSafeguards(t *testing.T) {
t.Skip("neither Bun nor Node is here to run tap.js")
}
}
// effortMain makes requests as Claude Code does in a run started at
// effort medium, the bridge's guard file rewritten as a turn asks
// another (#5584).
const effortMain = `const fs = require("fs");
const guard = process.argv[process.argv.length - 1];
const url = "https://api.anthropic.com/v1/messages?beta=true";
const main = { "x-claude-code-request-class": "main" };
const body = (extra) => JSON.stringify({ model: "claude-haiku-5-5", messages: [{ role: "user", content: "hi" }], thinking: { type: "adaptive" }, output_config: { effort: "medium" }, ...extra, stream: true });
(async () => {
const s = new Bun.FetchSession();
const ask = (headers, b) => s.fetch(url, { method: "POST", headers, body: b });
// the run's first turn: as Claude Code made it
await ask(main, body({}));
// the next turn asks high
fs.writeFileSync(guard, JSON.stringify({ effort: "high" }));
await ask(main, body({}));
// what Claude Code asks beside the turn keeps its own
await ask({ "x-claude-code-request-class": "title" }, body({}));
// with safeguards beside it, the variable is the extra body alone
fs.writeFileSync(guard, JSON.stringify({ effort: "high", safeguards: [{ c: "b" }] }));
await ask(main, body({ safeguards: [{ c: "a" }] }));
console.log(JSON.stringify({ env: process.env.CLAUDE_CODE_EXTRA_BODY }));
})();
`
// #5584: the interactive mode takes another effort only from a person
// typing /effort, which saves it as the user's default. tap.js asks each
// of the main turn's requests at the guard file's effort, in
// output_config.effort, and leaves Claude Code's other requests, and a
// run whose file has none, as Claude Code made them.
func TestTapAsksTheGuardFilesEffort(t *testing.T) {
ran := false
for _, rt := range []string{"bun", "node"} {
path, err := exec.LookPath(rt)
if err != nil {
continue
}
ran = true
t.Run(rt, func(t *testing.T) {
dir := t.TempDir()
for name, js := range map[string]string{"stub.js": guardStub, "main.js": effortMain, "tap.js": string(tapJS)} {
if err := os.WriteFile(filepath.Join(dir, name), []byte(js), 0o600); err != nil {
t.Fatal(err)
}
}
guard := filepath.Join(dir, "guard.json")
if err := os.WriteFile(guard, []byte(`{}`), 0o600); err != nil {
t.Fatal(err)
}
pre := "--preload"
if rt == "node" {
pre = "-r"
}
cmd := exec.Command(path, pre, filepath.Join(dir, "stub.js"), pre, filepath.Join(dir, "tap.js"), filepath.Join(dir, "main.js"), guard)
cmd.Env = append(os.Environ(), tapEnv+"="+filepath.Join(dir, "tap.jsonl"), GuardEnv+"="+guard)
out, err := cmd.CombinedOutput()
if err != nil {
t.Fatalf("%v: %s", err, out)
}
var got []map[string]any
for _, l := range strings.Split(strings.TrimSpace(string(out)), "\n") {
var m map[string]any
if json.Unmarshal([]byte(l), &m) != nil {
t.Fatalf("not a line of the stub's: %q\n%s", l, out)
}
got = append(got, m)
}
body := func(effort, sg string) string {
b := `{"model":"claude-haiku-5-5","messages":[{"role":"user","content":"hi"}],"thinking":{"type":"adaptive"},"output_config":{"effort":"` + effort + `"}`
if sg != "" {
b += `,"safeguards":` + sg
}
return b + `,"stream":true}`
}
want := []string{body("medium", ""), body("high", ""), body("medium", ""), body("high", `[{"c":"b"}]`)}
if len(got) != len(want)+1 {
t.Fatalf("told %s", out)
}
for i, w := range want {
if got[i]["body"] != w {
t.Fatalf("request %d was sent\n%v\nwant\n%v", i, got[i]["body"], w)
}
}
if env := got[len(got)-1]["env"]; env != `{"safeguards":[{"c":"b"}]}` {
t.Fatalf("Claude Code's extra body after: %v", env)
}
if _, err := os.Stat(guard + ".live"); err != nil {
t.Fatalf("the tap never said it asks them: %v", err)
}
})
}
if !ran {
t.Skip("neither Bun nor Node is here to run tap.js")
}
}
+76 -19
View File
@@ -215,7 +215,7 @@ type subscriptionRun struct {
safeguards json.RawMessage
safeguardBeta string
// guard is the file the interactive mode's tap reads its safeguards
// from on each request (claudetui.GuardEnv); "" with none
// and effort from on each request (claudetui.GuardEnv); "" with none
guard string
clientMarks bool
lean bool // started with leanSystem as its system prompt
@@ -298,8 +298,11 @@ type subscriptionRun struct {
replied bool
// effort is the level its Claude Code thinks at, as it started (its
// --effort) or was told since (setEffort); "" is Claude Code's own
effort string
// --effort) or was told since (setEffort, setTUIEffort); "" is Claude
// Code's own. ownEffort is the one it started at, which an
// interactive run asks at by itself.
effort string
ownEffort string
// loginVersion is the credential the run's account had when it
// started (provider.ClaudeLoginVersion), which a refusal it reports is
@@ -1229,15 +1232,17 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model,
// its own environment, which apply_flag_settings or a --settings file
// rewritten don't reach once it runs: the run is given the safeguards
// here, and a file (guard) its tap puts each later turn's in every
// request from (claudetui.GuardEnv, setSafeguards). A client's cache
// tail isn't added to Claude Code's own marks, which it keeps
// (clientCache.pasted).
tuiBody, guard := "", ""
if tui && len(req.Safeguards) > 0 {
tuiBody = claudeExtraBody(req.Safeguards, "")
env = append(env, "CLAUDE_CODE_EXTRA_BODY="+tuiBody)
// request from (claudetui.GuardEnv, setSafeguards), with the effort a
// later turn asks (setTUIEffort): every run has the file, safeguards
// or not. A client's cache tail isn't added to Claude Code's own
// marks, which it keeps (clientCache.pasted).
guard := ""
if tui {
if len(req.Safeguards) > 0 {
env = append(env, "CLAUDE_CODE_EXTRA_BODY="+claudeExtraBody(req.Safeguards, ""))
}
guard = filepath.Join(tmp, "guard.json")
if writeGuard(guard, tuiBody) == nil {
if writeGuard(guard, guardBody(req.Safeguards, "")) == nil {
env = append(env, claudetui.GuardEnv+"="+guard)
} else {
guard = ""
@@ -1291,10 +1296,11 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model,
run.appended = req.appendPrompt
run.tui = tui
run.cachePrefix = prefix
if tuiBody != "" {
if tui {
run.safeguards = bytes.Clone(req.Safeguards)
run.guard = guard
}
run.ownEffort = req.Effort
run.allowed = allowedTools(req)
if user, _ := ownerAccount(owner); user != "" {
run.loginVersion = provider.ClaudeLoginVersion(user)
@@ -1665,7 +1671,7 @@ func (r *subscriptionRun) setSafeguards(req *Request) error {
// (guardLive): the run goes on, its cache too, and upstream is
// sent this turn's classifier context whole (#4804).
if len(req.Safeguards) > 0 && r.guardLive() {
if err := writeGuard(r.guard, claudeExtraBody(req.Safeguards, "")); err != nil {
if err := r.tellGuard(req.Safeguards, r.effort); err != nil {
return fmt.Errorf("the turn's safeguards could not be handed to Claude Code (%v); restart it", err)
}
r.safeguards = bytes.Clone(req.Safeguards)
@@ -1704,6 +1710,31 @@ func (r *subscriptionRun) guardLive() bool {
return err == nil
}
// guardBody is a guard file: the extra body the run's Claude Code is to
// send (claudeExtraBody: its safeguards), and effort beside it, the level
// the tap asks each main request at in Claude Code's place, "" for the
// one Claude Code started at.
func guardBody(safeguards json.RawMessage, effort string) string {
body := map[string]any{}
if len(safeguards) > 0 {
body["safeguards"] = safeguards
}
if effort != "" {
body["effort"] = effort
}
b, _ := json.Marshal(body)
return string(b)
}
// tellGuard writes the interactive run's guard file for safeguards and
// effort, the run's own once it is written; settingsMu is held.
func (r *subscriptionRun) tellGuard(safeguards json.RawMessage, effort string) error {
if effort == r.ownEffort {
effort = ""
}
return writeGuard(r.guard, guardBody(safeguards, effort))
}
// writeGuard replaces the guard file with body whole: the tap reads it as
// Claude Code makes a request, never half-written.
func writeGuard(path, body string) error {
@@ -1996,12 +2027,11 @@ func (b *subscriptionBridge) resume(req *Request, owner string) (*subscriptionRu
// prefix the cache has never seen
if req.Effort != run.effort {
if run.tui {
// the interactive mode takes its effort at its start only:
// the run is let go, and one at the new effort started
run.abortFor("its effort is set at its start, and the next turn asks another")
return nil, nil
}
if err := run.setEffort(req.Effort); err != nil {
if err := run.setTUIEffort(req.Effort); err != nil {
run.abortFor(err.Error())
return nil, nil
}
} else if err := run.setEffort(req.Effort); err != nil {
run.abortFor("it could not be told the next turn's effort: " + err.Error())
return nil, nil
}
@@ -2224,6 +2254,33 @@ func (r *subscriptionRun) setEffort(effort string) error {
return nil
}
// setTUIEffort has the interactive run think at effort from its next
// turn: its tap asks each main request at it (guardBody), as Claude Code
// itself does after a person types /effort, which the run can't do: that
// saves the level as the user's default for new sessions, in the folder
// of the account the run is signed in to, where only 'max' is the
// session's alone (2.1.318). Claude Code's own level, "", can't be asked
// in place of another, and a Claude Code without the tap (guardLive) is
// asked at its --effort only: such a run is let go, and one at the new
// effort started. On the real 2.1.318 (Haiku 5.5) the turn after one
// asked at high instead of medium read the whole conversation from the
// cache (55,392 tokens read, 41 written).
func (r *subscriptionRun) setTUIEffort(effort string) error {
if effort == "" && r.ownEffort != "" {
return errors.New("its effort is set at its start, and the next turn asks Claude Code's own")
}
if !r.guardLive() {
return errors.New("its effort is set at its start, its Claude Code has no tap to ask another, and the next turn does")
}
r.settingsMu.Lock()
defer r.settingsMu.Unlock()
if err := r.tellGuard(r.safeguards, effort); err != nil {
return fmt.Errorf("the next turn's effort could not be handed to Claude Code: %v", err)
}
r.effort = effort
return nil
}
// retire lets go of the runs left waiting at an earlier point of this
// conversation, which a new run now carries on: its turns since went to
// another model (switched to and back), so none of them comes back to
+132
View File
@@ -0,0 +1,132 @@
package gateway
import (
"encoding/json"
"net/http/httptest"
"os"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// tuiEffortRefusal is what the interactive helper tells of the 400 the
// real 2.1.318 met when its request asked an effort of claude-haiku-4-5,
// which takes none.
const tuiEffortRefusal = `{"type":"result","subtype":"error_during_execution","is_error":true,"result":"API Error: 400 This model does not support the effort parameter.","api_error_status":400}`
// tuiEffortTurn sends the conversation so far asking effort, as Pi does in
// output_config, and returns the status and the reply's text.
func tuiEffortTurn(t *testing.T, s *Server, conv, effort string) (int, string) {
t.Helper()
body := `{"model":"claude-sonnet-5","max_tokens":100,"thinking":{"type":"adaptive"},"output_config":{"effort":"` + effort + `"},"system":"be brief","tools":[{"name":"read","input_schema":{"type":"object"}}],"messages":[` + conv + `]}`
rec := httptest.NewRecorder()
var u Usage
p := provider.Provider{ID: "claude", Account: &provider.Account{Agent: "claude", User: "u"}}
code, msg := s.serveClaudeSubscription(rec, httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body)), provider.Anthropic, p, "claude-sonnet-5", []byte(body), &u)
if code != 200 {
return code, msg
}
_, text := lastContent(t, rec.Body.Bytes())
return code, text
}
// lastContent is a reply's last block: its type and text.
func lastContent(t *testing.T, body []byte) (kind, text string) {
t.Helper()
var res struct {
Content []struct{ Type, Text string } `json:"content"`
}
if err := json.Unmarshal(body, &res); err != nil || len(res.Content) == 0 {
t.Fatalf("no reply: %s", body)
}
last := res.Content[len(res.Content)-1]
return last.Type, last.Text
}
// claudeLog is the fake Claude Code's log: its starts' arguments, and
// the guard file as each request carried it.
func claudeLog(t *testing.T, path string) (starts, sent []string) {
t.Helper()
b, _ := os.ReadFile(path)
for _, l := range strings.Split(string(b), "\n") {
if v, ok := strings.CutPrefix(l, "args "); ok {
starts = append(starts, v)
}
if v, ok := strings.CutPrefix(l, "sent "); ok {
sent = append(sent, v)
}
}
return starts, sent
}
// #5584: a turn of an interactive run asking another effort than the one
// before let the run go, and a new Claude Code was told the whole
// conversation, written to the cache again (72,416 tokens on the
// reporter's 108 messages). Its tap now asks the turn's requests at the
// new level: one Claude Code takes both turns, the second's request at
// high.
func TestClaudeTUIEffortChangeGoesOnInItsRun(t *testing.T) {
log := guardClaude(t)
s := guardServer(t)
conv := rmsg("user", "hi")
code, text := tuiEffortTurn(t, s, conv, "medium")
if code != 200 {
t.Fatalf("%d %s", code, text)
}
conv += "," + rmsg("assistant", text) + "," + rmsg("user", "think harder")
if code, text = tuiEffortTurn(t, s, conv, "high"); code != 200 {
t.Fatalf("%d %s", code, text)
}
starts, sent := claudeLog(t, log)
if len(starts) != 1 || !strings.Contains(starts[0], "--effort medium") {
t.Fatalf("started %d runs, want one at medium:\n%s", len(starts), strings.Join(starts, "\n"))
}
if len(sent) != 2 || sent[0] != `{}` || sent[1] != `{"effort":"high"}` {
t.Fatalf("the turns' requests were asked at %q, want Claude Code's own then high", sent)
}
}
// A Claude Code without the tap is asked at its --effort only: a turn
// asking another starts one at it, and the log says why.
func TestClaudeTUIEffortChangeWithoutTapStartsAnew(t *testing.T) {
log := guardClaude(t)
t.Setenv("FAKE_NO_TAP", "1")
logs := keepLog(t)
s := guardServer(t)
conv := rmsg("user", "hi")
_, text := tuiEffortTurn(t, s, conv, "medium")
conv += "," + rmsg("assistant", text) + "," + rmsg("user", "think harder")
if code, text := tuiEffortTurn(t, s, conv, "high"); code != 200 {
t.Fatalf("%d %s", code, text)
}
starts, _ := claudeLog(t, log)
if len(starts) != 2 || !strings.Contains(starts[1], "--effort high") {
t.Fatalf("started %d runs, want a second at high:\n%s", len(starts), strings.Join(starts, "\n"))
}
if want := "its Claude Code has no tap to ask another"; !strings.Contains(logs.String(), want) {
t.Fatalf("the log doesn't say why the run ended (%q):\n%s", want, logs)
}
}
// A level Anthropic refuses the model fails that turn, as a run started
// at it would, and lets the run go: the turn asked again starts a Claude
// Code at its --effort, which fits the level to the model itself.
func TestClaudeTUIEffortRefusedStartsAnew(t *testing.T) {
log := guardClaude(t)
t.Setenv("FAKE_REFUSE_EFFORT", "1")
s := guardServer(t)
conv := rmsg("user", "hi")
_, text := tuiEffortTurn(t, s, conv, "medium")
conv += "," + rmsg("assistant", text) + "," + rmsg("user", "think harder")
if code, msg := tuiEffortTurn(t, s, conv, "high"); code != 400 || !strings.Contains(msg, "does not support the effort") {
t.Fatalf("the refused turn: %d %s", code, msg)
}
if code, text := tuiEffortTurn(t, s, conv, "high"); code != 200 || !strings.HasPrefix(text, "pid ") {
t.Fatalf("the turn asked again: %d %s", code, text)
}
starts, _ := claudeLog(t, log)
if len(starts) != 2 || !strings.Contains(starts[1], "--effort high") {
t.Fatalf("started %d runs, want a second at high:\n%s", len(starts), strings.Join(starts, "\n"))
}
}
+8 -1
View File
@@ -22,7 +22,9 @@ import (
// it saw a request to put them in (<file>.live) unless FAKE_NO_TAP is
// set, and logs the file as each of its requests would carry it. A turn
// saying CALL3 calls the client's read tool three times, one call a
// request, before it answers. Its log is returned.
// request, before it answers. With FAKE_REFUSE_EFFORT set, a request the
// file asks another effort of is refused as Anthropic refuses an effort
// the model doesn't take. Its log is returned.
func guardClaude(t *testing.T) string {
t.Helper()
if runtime.GOOS == "windows" {
@@ -57,6 +59,11 @@ while read -r line; do
esac
printf 'told %s\n' "$line" >> ` + log + `
if [ -n "$MAGPIE_CLAUDE_GUARD" ] && [ -z "$FAKE_NO_TAP" ]; then : > "$MAGPIE_CLAUDE_GUARD.live"; fi
if [ -n "$FAKE_REFUSE_EFFORT" ] && grep -q '"effort"' "$MAGPIE_CLAUDE_GUARD" 2>/dev/null; then
sent
echo '` + tuiEffortRefusal + `'
continue
fi
case "$line" in *CALL3*) ;; *)
sent; start 0
echo '{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"pid '$me'"}}}'