Files
magpie/internal/gateway/claude_tui_usage_test.go
T
yetone 82403f9f6d claude: /usage is read through -p, never the interactive mode, which opened idle accounts' 5-hour window (#5582)
Since v0.1.2635 (ccd746e03), when the interactive mode is on (the
default), magpie read the plan's allowance by starting the interactive
Claude Code in its helper and typing /usage there (claudeUsageTUI). The
interactive Claude Code 2.1.316 sends a model request as it starts,
before anything is typed. That is probeQuotaStatus: haiku, max_tokens 1,
content "quota". It sends it unless CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC
is set, and that variable also keeps /usage from loading. The request
counts, so on an account with no 5-hour window it started one. The
reporter's reads came at magpie's start and when a window ended, and
each opened a window with warm-up off. Their counterexample (11-01,
v0.1.2433, before ccd746e03) read /usage through -p and opened nothing.

Recorded (sandbox HOME and CLAUDE_CONFIG_DIR, a fake sign-in, the real
Claude Code 2.1.316 behind a recording proxy that answers everything
itself, so no account was spent):
- magpie's interactive args and env, in a pty. At start, before /usage
  was typed:
  POST api.anthropic.com /v1/messages?beta=true
  {"model":"claude-haiku-4-5-20251001","max_tokens":1,
   "messages":[{"role":"user","content":"quota"}],...}
  then GET /api/oauth/usage once /usage was typed.
- The same with CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1: no POST, but
  no /api/oauth/usage either, and the panel says "Failed to load usage
  data". This can't be the fix.
- `claude -p /usage` with claudeUsageArgs and claudeUsageEnv: no
  /v1/messages at all, only GET /api/oauth/usage (plus profile and
  bootstrap GETs). It printed "You are currently using your subscription
  to power your Claude Code usage" / "Current session: 13% used · resets
  Nov 7 at 4pm (Asia/Shanghai)" / "Current week (all models): 4% used ·
  ...". ccd746e03 said -p's /usage tells only the session's cost. In
  2.1.316's source that is only for a sign-in without a subscription or
  the user:profile scope, such as a setup-token, which provider never
  reads (errClaudeSetupToken), or an API key.

Fix: claudeUsage always runs `claude -p /usage`, with the interactive
mode on or off. claudeUsageTUI and claudeTUIUsageArgs are gone. This is
the one choke point (provider.UsageClaudeVia -> runClaudeUsage) for
every magpie read of Claude usage: the signed-in account's card,
saved accounts (readSavedClaudeUsage), the 8-day keep-alive, the
used-up switch's spare reads and refreshes. The other interactive
starts are the bridge's turns, the warm-up and the model test. Each one
sends a model request the user asked for, and each runs with
cleanClaudeEnv's CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1, so the
startup probe isn't added there. Not changed: claudetui still takes a
typed /usage, and magpie no longer sends it.

Docs: docs/subsystems/claude-subscription-bridge.md says why and
removes the wrong -p claim. The comments in claude_warmup.go, tui.go
and claude_usage_cli.go are updated to match.

Tests: TestClaudeUsageStartsNoInteractiveRun replaces
TestClaudeUsageTUIOn, TestClaudeUsageTUIWorksInMagpiesFolder and
TestClaudeUsageTUISaysItsDeadline. With the interactive mode on, it
checks that a read of the signed-in account and of a saved one starts
no helper, runs -p /usage, and leaves the traffic variable off. The
"usage" rows of TestClaudeOneOffTrustsMagpiesFolder and
TestClaudeOneOffFailureLogged are removed, since a /usage read is no
longer an interactive one-off run. Their "test" rows stay.

Run (mote, at this tree on origin/main 665b9aff1; after the rebase on 9e6687e3a, vet and claudetui plus gateway's ClaudeUsage|OneOff|Trust|TUI tests again: ok):
- gofmt -l internal/gateway internal/provider internal/claudetui: clean.
- go vet for darwin, and for linux and windows with -tags nogui:
  ./internal/gateway ./internal/provider ./internal/claudetui ok.
- On mote: go test -count=1 -timeout 45m ./internal/provider ./internal/claudetui: ok (114s, 110s);
  go test -run 'Claude|Usage|Warm|Trust|OneOff|TUI|Shim|Guard|Loop|Budget' ./internal/gateway: ok (89s).

Broken by hand: with HEAD's claude_warmup.go (its claudeTUIOn branch
back) and the new test, TestClaudeUsageStartsNoInteractiveRun went red:
"a /usage read started the interactive Claude Code: claude-tui-helper
.../claude -p --output-format stream-json --input-format stream-json ...".

Not tried: a real account's -p /usage on this build. The windows output
above comes from the recorder's fake usage reply, and the reporter's
v0.1.2433 readings came from -p. Not tried: an Enterprise account whose
usage reply leaves the windows out. -p then prints only the
subscription line, which reads as "temporarily unavailable" and keeps
the last reading, where the interactive panel had said no window has
started. Not run on Windows or in WSL. The -p read there is the same code
(claudeUsage); the interactive read had run on Windows too.
Not run: the full ./... suite (mote's suite.lock had four full runs
queued).
2026-11-07 11:52:30 +08:00

60 lines
2.1 KiB
Go

package gateway
import (
"context"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/testenv"
)
// A /usage read never starts the interactive Claude Code, the
// interactive mode on (#5582): as it starts, before /usage is typed, it
// sends a counted model request ("quota", haiku, max_tokens 1; recorded
// from Claude Code 2.1.316), which opened the five-hour window of an
// idle account with warm-up off. The read runs as -p, which sends none,
// for the signed-in account and a saved one, and keeps
// CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC off, without which /usage
// loads nothing.
func TestClaudeUsageStartsNoInteractiveRun(t *testing.T) {
text := "Current session: 13% used · resets 4pm (Asia/Shanghai)"
plog := fakeWarmClaude(t, `{"type":"result","is_error":false,"result":"`+text+`"}`, 0)
claudeTUIRuns = true
t.Cleanup(func() { claudeTUIRuns = false })
t.Setenv("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC", "1")
os.Unsetenv("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC")
started := filepath.Join(t.TempDir(), "started")
helper := filepath.Join(t.TempDir(), "magpie")
testenv.Program(t, helper, `#!/bin/sh
echo "$@" >> '`+started+`'
printf '%s\n' '{"type":"result","subtype":"success","is_error":false,"local_command":"usage","result":"`+text+`"}'
cat > /dev/null
`)
claudeTUIHelper = helper
t.Cleanup(func() { claudeTUIHelper = "" })
if !claudeTUIOn() {
t.Fatal("the interactive mode isn't on")
}
for _, cfg := range []string{"", t.TempDir()} {
os.Remove(plog)
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
got, err := claudeUsage(ctx, cfg)
cancel()
if err != nil || got != text {
t.Fatalf("account %q: usage %q %v", cfg, got, err)
}
if b, err := os.ReadFile(started); err == nil {
t.Fatalf("account %q: a /usage read started the interactive Claude Code:\n%s", cfg, b)
}
b, _ := os.ReadFile(plog)
for _, want := range []string{"[-p][/usage][--output-format][json]", "traffic:\n", "telemetry:1\n"} {
if !strings.Contains(string(b), want) {
t.Errorf("account %q: the -p read lacks %q:\n%s", cfg, want, b)
}
}
}
}