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, beforeccd746e03) 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 · ...".ccd746e03said -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 on9e6687e3a, 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).
This commit is contained in:
@@ -467,8 +467,25 @@ A refused request never ran, so it isn't the editor's last request
|
||||
(`noteClaudeRun`). The model test's and warm-up's "hi" (`askClaude`) goes
|
||||
through the helper too (`askClaudeTUI`), in stream-json, and its stdin is
|
||||
closed at the first result. Reading the plan's allowance (`/usage`,
|
||||
`claudeUsageTUI`) types `/usage` in the interactive mode too: the helper
|
||||
is told `{"type":"command","command":"/usage"}`, types it, waits for the
|
||||
`claudeUsage`) never starts the interactive mode, on or off: it runs
|
||||
`claude -p /usage` (`claudeUsageArgs`, #5582). The interactive Claude
|
||||
Code 2.1.316 sends a model request as it starts, before anything is
|
||||
typed (`probeQuotaStatus`: haiku, `max_tokens` 1, content "quota"),
|
||||
unless `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` is set, which also
|
||||
keeps `/usage` from loading ("Failed to load usage data"). That request
|
||||
counts, so on an idle account it started the five-hour window: from
|
||||
v0.1.2635 to the fix, magpie's reads at its start and as a window ended
|
||||
opened the user's window with warm-up off (recorded behind a proxy that
|
||||
answers everything itself). `-p` sends that request only when
|
||||
interactive, so its `/usage` asks the usage endpoint alone
|
||||
(`/api/oauth/usage`), and for a subscription's sign-in (the
|
||||
`user:profile` scope) prints the plan's windows as the lines
|
||||
`provider.parseClaudeUsage` reads. Only a sign-in without that scope (a
|
||||
setup-token, which magpie never reads, or an API key) gets the session's
|
||||
cost instead. `TestClaudeUsageStartsNoInteractiveRun` holds it.
|
||||
|
||||
The helper still takes a typed `/usage`, and nothing of magpie's sends it
|
||||
now: it is told `{"type":"command","command":"/usage"}`, types it, waits for the
|
||||
panel's windows ("NN% used", `commandSettle` still) and closes it with
|
||||
Esc. A panel with no window (its words saying why) is taken as drawn only
|
||||
once its Settings tabs show and nothing is loading (`usageDrawn`), still
|
||||
@@ -479,8 +496,7 @@ With no panel by `commandWait`, the result is an error saying what was
|
||||
last drawn (`TestShimWaitsPastTheBanner`, `TestUsageDrawn`). Its result (`local_command: "usage"`) says each window as -p's lines
|
||||
do, "Current session: 99% used · resets 7pm (Asia/Shanghai)" (`usageText`,
|
||||
tested on the bytes Claude Code 2.1.316 drew, `testdata/usage-2.1.316.bin`),
|
||||
for `provider.parseClaudeUsage`. Claude Code 2.1.316's `-p /usage`
|
||||
printed only the session's cost there, no window, in a real run.
|
||||
for `provider.parseClaudeUsage`.
|
||||
The helper reads the screen as a terminal shows it (`grid`,
|
||||
[`screen.go`](../../internal/claudetui/screen.go), 200 by 50, the size
|
||||
the pseudo-terminal and Windows' pseudo console are made, from one
|
||||
@@ -518,7 +534,7 @@ koohoko5924 on Discord, a Claude Enterprise account, on panels built from
|
||||
until …") are failures as "Failed to load usage data" is
|
||||
(`TestShimToldWhyUsageFailed`).
|
||||
|
||||
These one-off interactive runs (`askClaudeTUI`, `claudeUsageTUI`) work in
|
||||
These one-off interactive runs (`askClaudeTUI`) work in
|
||||
magpie's shared work folder (`oneOffDir`: `claudeWorkDir`, a fresh temp
|
||||
folder only when it can't be made), where the helper may answer the trust
|
||||
question, so a config directory holds one trusted entry for it instead of
|
||||
@@ -551,7 +567,7 @@ waiting for it" (`oneOffErr`), and the card says the reason
|
||||
tooltip. A question about trust left unanswered at the deadline is named
|
||||
with its folder ("Claude Code asked whether to trust <folder>, not answered
|
||||
in the 16.8s …"), where it said "showed no prompt" before (#4830). A failed
|
||||
run also goes to app.log (`logOneOff`: "claude: a /usage read of saved
|
||||
run also goes to app.log (`logOneOff`: "claude: a test on haiku of saved
|
||||
account <dir> failed: …"), with the helper's whole reason, which the card
|
||||
clips to 300 bytes, on one line: the home folder and any
|
||||
`/Users/<name>` or `C:\Users\<name>` become `~`, secrets go through
|
||||
|
||||
@@ -764,9 +764,11 @@ var (
|
||||
// command runs /usage, which Claude Code answers itself, asking no model:
|
||||
// it is typed, and what Claude Code shows for it is told as the result -p's
|
||||
// /usage gives (usageText), its local_command named. The panel is closed
|
||||
// after. It is the one command a line {"type":"command"} runs: the plan's
|
||||
// allowance read in the interactive mode, where -p's /usage tells no
|
||||
// window of it (Claude Code 2.1.316).
|
||||
// after. It is the one command a line {"type":"command"} runs. magpie's
|
||||
// own /usage reads no longer send it (#5582): the interactive Claude Code
|
||||
// (2.1.316) sends a counted model request as it starts, which opened an
|
||||
// idle account's five-hour window, so the gateway reads /usage through -p,
|
||||
// which prints the plan's windows for a subscription's sign-in.
|
||||
func (s *shim) command(name string) error {
|
||||
s.doing.Store("hadn't drawn " + name + "'s panel")
|
||||
if name != "/usage" {
|
||||
|
||||
@@ -22,7 +22,6 @@ func TestClaudeOneOffFailureLogged(t *testing.T) {
|
||||
name, what string
|
||||
run func(ctx context.Context, cfg string) error
|
||||
}{
|
||||
{"usage", "a /usage read", func(ctx context.Context, cfg string) error { _, err := claudeUsage(ctx, cfg); return err }},
|
||||
{"test", "a test on haiku", func(ctx context.Context, cfg string) error { return askClaude(ctx, cfg, "haiku") }},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
|
||||
@@ -63,7 +63,8 @@ func claudeKey(work string) string { return filepath.ToSlash(evalSymlinks(work))
|
||||
|
||||
// mydosu's saved account (#4830, Windows, Claude Code 2.1.316) was asked
|
||||
// whether to trust magpie's folder on every /usage read and every test,
|
||||
// and each waited out its caller's time on the question. Before either
|
||||
// and each waited out its caller's time on the question (a /usage read
|
||||
// runs as -p now, #5582, which asks nothing about trust). Before a test
|
||||
// runs, the account's .claude.json says the folder is trusted, under the
|
||||
// path Claude Code runs in, which a Mac's getcwd gives with its links
|
||||
// resolved (/private/var/… for /var/…).
|
||||
@@ -73,7 +74,6 @@ func TestClaudeOneOffTrustsMagpiesFolder(t *testing.T) {
|
||||
run func(ctx context.Context, cfg string) error
|
||||
say string
|
||||
}{
|
||||
{"usage", func(ctx context.Context, cfg string) error { _, err := claudeUsage(ctx, cfg); return err }, `"local_command":"usage","result":"Current session: 1% used"`},
|
||||
{"test", func(ctx context.Context, cfg string) error { return askClaude(ctx, cfg, "haiku") }, `"result":"Hi!"`},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
|
||||
@@ -4,153 +4,56 @@ import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/claudetui"
|
||||
"github.com/yetone/magpie/internal/testenv"
|
||||
)
|
||||
|
||||
// With the interactive mode on, /usage is typed in it, through its
|
||||
// helper, where -p's /usage tells no window of the plan (Claude Code
|
||||
// 2.1.316): the helper is told the command, and what it tells is the
|
||||
// reading. No claude -p runs. Turned off, it runs as -p.
|
||||
func TestClaudeUsageTUIOn(t *testing.T) {
|
||||
plog := fakeWarmClaude(t, `{"type":"result","is_error":false,"result":"Total cost: $0.0000"}`, 0)
|
||||
// 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")
|
||||
log := filepath.Join(t.TempDir(), "log")
|
||||
text := "Current session: 99% used · resets 7pm (Asia/Shanghai)\nCurrent week (all models): 81% used · resets Nov 4 at 6am (Asia/Shanghai)"
|
||||
started := filepath.Join(t.TempDir(), "started")
|
||||
helper := filepath.Join(t.TempDir(), "magpie")
|
||||
testenv.Program(t, helper, `#!/bin/sh
|
||||
[ "$1" = "`+claudetui.Command+`" ] || exit 9
|
||||
shift 2
|
||||
{ printf 'args:'; for a in "$@"; do printf '[%s]' "$a"; done; echo
|
||||
echo "trust:$`+claudetui.TrustEnv+`"; echo "traffic:$CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC"; echo "telemetry:$DISABLE_TELEMETRY"
|
||||
IFS= read -r line; echo "told:$line"; } > '`+log+`'
|
||||
printf '%s\n' '{"type":"result","subtype":"success","is_error":false,"local_command":"usage","result":"Current session: 99% used · resets 7pm (Asia/Shanghai)\nCurrent week (all models): 81% used · resets Nov 4 at 6am (Asia/Shanghai)"}'
|
||||
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 = "" })
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
got, err := claudeUsage(ctx, "")
|
||||
if err != nil || got != text {
|
||||
t.Fatalf("usage %q %v", got, err)
|
||||
if !claudeTUIOn() {
|
||||
t.Fatal("the interactive mode isn't on")
|
||||
}
|
||||
b, _ := os.ReadFile(log)
|
||||
for _, want := range []string{"[-p][--output-format][stream-json][--input-format][stream-json]", "[--tools][]", "[--setting-sources][]",
|
||||
`[--settings][{"disableDeepLinkRegistration":"disable"}]`,
|
||||
"trust:1\n", "traffic:\n", "telemetry:1\n", `told:{"type":"command","command":"/usage"}`} {
|
||||
if !strings.Contains(string(b), want) {
|
||||
t.Errorf("the helper's run lacks %q:\n%s", want, b)
|
||||
}
|
||||
}
|
||||
if strings.Contains(string(b), "/usage]") {
|
||||
t.Errorf("/usage was given as an argument, not typed:\n%s", b)
|
||||
}
|
||||
if _, err := os.Stat(plog); err == nil {
|
||||
t.Fatal("claude -p ran with the interactive mode on")
|
||||
}
|
||||
printMode(t, true)
|
||||
if _, err := claudeUsage(ctx, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if b, _ := os.ReadFile(plog); !strings.Contains(string(b), "[-p][/usage]") {
|
||||
t.Fatalf("turned off, /usage didn't run as -p:\n%s", b)
|
||||
}
|
||||
}
|
||||
|
||||
// A /usage read in the interactive mode works in magpie's own folder
|
||||
// (claudeWorkDir), every time the same: Claude Code asks whether to trust
|
||||
// a folder once for each state file, and a folder of each read's own was
|
||||
// asked again each time and left one more trusted project in the account's
|
||||
// state file (#4830, mydosu: 67 of them). A session the run told is
|
||||
// removed after it.
|
||||
func TestClaudeUsageTUIWorksInMagpiesFolder(t *testing.T) {
|
||||
fakeWarmClaude(t, `{}`, 0)
|
||||
claudeTUIRuns = true
|
||||
t.Cleanup(func() { claudeTUIRuns = false })
|
||||
cfg := t.TempDir()
|
||||
work, err := claudeWorkDir()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sid := "4830aaaa-0000-4000-8000-000000000000"
|
||||
var left []string
|
||||
for _, d := range claudeSessions(cfg, work) {
|
||||
_ = os.MkdirAll(d, 0o700)
|
||||
_ = os.WriteFile(filepath.Join(d, sid+".jsonl"), []byte("{}\n"), 0o600)
|
||||
left = append(left, filepath.Join(d, sid+".jsonl"))
|
||||
}
|
||||
log := filepath.Join(t.TempDir(), "log")
|
||||
helper := filepath.Join(t.TempDir(), "magpie")
|
||||
testenv.Program(t, helper, `#!/bin/sh
|
||||
echo "pwd:$(pwd)" >> '`+log+`'
|
||||
printf '%s\n' '{"type":"system","subtype":"init","session_id":"`+sid+`"}'
|
||||
printf '%s\n' '{"type":"result","subtype":"success","is_error":false,"local_command":"usage","session_id":"`+sid+`","result":"Current session: 1% used"}'
|
||||
cat > /dev/null
|
||||
`)
|
||||
claudeTUIHelper = helper
|
||||
t.Cleanup(func() { claudeTUIHelper = "" })
|
||||
for range 2 {
|
||||
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 != "Current session: 1% used" {
|
||||
t.Fatalf("usage %q %v", got, err)
|
||||
if err != nil || got != text {
|
||||
t.Fatalf("account %q: usage %q %v", cfg, got, err)
|
||||
}
|
||||
}
|
||||
b, _ := os.ReadFile(log)
|
||||
real, _ := filepath.EvalSymlinks(work)
|
||||
for _, l := range strings.Split(strings.TrimSpace(string(b)), "\n") {
|
||||
if d := strings.TrimPrefix(l, "pwd:"); d != work && d != real {
|
||||
t.Errorf("a read worked in %s, not magpie's folder %s:\n%s", d, work, b)
|
||||
if b, err := os.ReadFile(started); err == nil {
|
||||
t.Fatalf("account %q: a /usage read started the interactive Claude Code:\n%s", cfg, b)
|
||||
}
|
||||
}
|
||||
for _, f := range left {
|
||||
if _, err := os.Stat(f); !os.IsNotExist(err) {
|
||||
t.Errorf("the run's session %s was left", f)
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A read whose helper is killed at its caller's deadline says so, never
|
||||
// only the exit status the kill left ("exit status 1" on Windows, #4830);
|
||||
// and the helper is told the deadline, a margin before it, to end then on
|
||||
// its own, saying why (claudetui.DeadlineEnv).
|
||||
func TestClaudeUsageTUISaysItsDeadline(t *testing.T) {
|
||||
fakeWarmClaude(t, `{}`, 0)
|
||||
claudeTUIRuns = true
|
||||
t.Cleanup(func() { claudeTUIRuns = false })
|
||||
log := filepath.Join(t.TempDir(), "log")
|
||||
helper := filepath.Join(t.TempDir(), "magpie")
|
||||
// a helper that heeds no deadline and says nothing
|
||||
testenv.Program(t, helper, `#!/bin/sh
|
||||
echo "by:$`+claudetui.DeadlineEnv+`" > '`+log+`'
|
||||
exec sleep 30
|
||||
`)
|
||||
claudeTUIHelper = helper
|
||||
t.Cleanup(func() { claudeTUIHelper = "" })
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer cancel()
|
||||
dl, _ := ctx.Deadline()
|
||||
_, err := claudeUsage(ctx, t.TempDir())
|
||||
if err == nil || !strings.Contains(err.Error(), "said nothing before magpie stopped waiting") {
|
||||
t.Fatalf("got %v", err)
|
||||
}
|
||||
b, _ := os.ReadFile(log)
|
||||
ms, perr := strconv.ParseInt(strings.TrimSpace(strings.TrimPrefix(string(b), "by:")), 10, 64)
|
||||
if perr != nil {
|
||||
t.Fatalf("the helper was told %q", b)
|
||||
}
|
||||
// a quarter of the 2s left, the margin less than its 3s
|
||||
if by := time.UnixMilli(ms); !by.Before(dl) || by.Before(dl.Add(-time.Second)) {
|
||||
t.Fatalf("the helper was told %s, the deadline %s", by, dl)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,6 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"os"
|
||||
"os/exec"
|
||||
@@ -183,16 +182,24 @@ func init() {
|
||||
}
|
||||
|
||||
// claudeUsage is what Claude Code's /usage prints for the account in
|
||||
// configDir (empty for its own): a command asking no model, run as
|
||||
// askClaude runs it, with nothing of the user's settings and nothing kept.
|
||||
// configDir (empty for its own), run as askClaude runs it, with nothing of
|
||||
// the user's settings and nothing kept. It always runs as -p, the
|
||||
// interactive mode on or off (#5582): an interactive Claude Code (2.1.316)
|
||||
// sends a model request as it starts, before anything is typed
|
||||
// (probeQuotaStatus: haiku, max_tokens 1, "quota"), unless
|
||||
// CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC is set, which also keeps
|
||||
// /usage from loading. That request is counted, so on an account with no
|
||||
// five-hour window open it started one: magpie's reads, at its start and
|
||||
// as a window ended, opened the user's window with warm-up off. -p skips
|
||||
// that request (it is sent only when interactive) and its /usage asks
|
||||
// only the usage endpoint, and prints the plan's windows for a Claude
|
||||
// subscription's sign-in (one with the user:profile scope; a setup-token
|
||||
// account has none, and provider never reads one).
|
||||
func claudeUsage(ctx context.Context, configDir string) (string, error) {
|
||||
binary, err := claudeBinary()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if claudeTUIOn() {
|
||||
return claudeUsageTUI(ctx, binary, configDir)
|
||||
}
|
||||
tmp, err := os.MkdirTemp("", "magpie-claude-")
|
||||
if err != nil {
|
||||
return "", err
|
||||
@@ -243,61 +250,7 @@ func claudeUsageEnv() []string {
|
||||
return append(env, "DISABLE_TELEMETRY=1", "DISABLE_ERROR_REPORTING=1", "DISABLE_AUTOUPDATER=1")
|
||||
}
|
||||
|
||||
// claudeUsageTUI is claudeUsage with the interactive mode on
|
||||
// (claudeTUIOn): /usage is typed in it, through its helper, which tells
|
||||
// the plan's windows its panel shows as -p's /usage lines say them
|
||||
// (claudetui's usageText). -p's /usage tells only the session's cost
|
||||
// there (Claude Code 2.1.316), so the plan's allowance is read only so.
|
||||
func claudeUsageTUI(ctx context.Context, binary claudeCLI, configDir string) (string, error) {
|
||||
if _, why := claudeMachineWhy(binary); why != "" {
|
||||
return "", claudeTUIErr(why)
|
||||
}
|
||||
work, done, err := oneOffDir()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer done()
|
||||
trustWork(binary, configDir, work)
|
||||
cmd, err := binary.tuiCommand(ctx, claudeTUIUsageArgs()...)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
cmd.Dir = work
|
||||
env, err := binary.proxied(ctx, claudeUsageEnv())
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
// the folder is magpie's own: asked whether to trust it, say yes
|
||||
env = append(env, claudetui.TrustEnv+"=1")
|
||||
env = append(env, claudeBypassEnv(true, configDir)...)
|
||||
env = append(env, helperDeadline(ctx)...)
|
||||
cmd.Env = binary.tuiEnv(binary.env(binary.asRoot(env), configDir), configDir)
|
||||
stdin, err := cmd.StdinPipe()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
go func() { _, _ = io.WriteString(stdin, `{"type":"command","command":"/usage"}`+"\n") }()
|
||||
out := &resultLines{done: func() { _ = stdin.Close() }}
|
||||
var stderr bytes.Buffer
|
||||
cmd.Stdout, cmd.Stderr = out, &stderr
|
||||
runErr := runClaudeTree(ctx, cmd, "a Claude Code /usage read")
|
||||
dropOneOff(binary, configDir, work, out.sid)
|
||||
var full *claudeFull
|
||||
if errors.As(runErr, &full) {
|
||||
return "", runErr
|
||||
}
|
||||
if out.res != nil {
|
||||
if out.res.IsError {
|
||||
return "", errors.New("Claude Code: " + clip(out.res.Result))
|
||||
}
|
||||
return out.res.Result, nil
|
||||
}
|
||||
err = oneOffErr(ctx, stderr.String(), runErr)
|
||||
logOneOff("a /usage read", configDir, stderr.String(), err)
|
||||
return "", err
|
||||
}
|
||||
|
||||
// oneOffDir is the folder a one-off interactive run (a test, a /usage)
|
||||
// oneOffDir is the folder a one-off interactive run (a test, a warm-up)
|
||||
// works in: magpie's own, the one the bridge's runs work in
|
||||
// (claudeWorkDir). Claude Code asks whether to trust a folder once for
|
||||
// each of its state files, and keeps the answer there: a folder of each
|
||||
@@ -521,13 +474,6 @@ func claudeUsageArgs() []string {
|
||||
"--tools", "", "--strict-mcp-config", "--setting-sources", "", "--settings", disableDeepLinkSettings, "--no-session-persistence"}
|
||||
}
|
||||
|
||||
// claudeTUIUsageArgs are claudeUsageArgs for the interactive mode's
|
||||
// helper, /usage typed in it rather than given.
|
||||
func claudeTUIUsageArgs() []string {
|
||||
return []string{"-p", "--output-format", "stream-json", "--input-format", "stream-json", "--verbose",
|
||||
"--tools", "", "--strict-mcp-config", "--setting-sources", "", "--settings", disableDeepLinkSettings}
|
||||
}
|
||||
|
||||
func claudeWarmArgs(model string) []string {
|
||||
return []string{"-p", "--output-format", "json", "--model", model,
|
||||
"--tools", "", "--strict-mcp-config", "--setting-sources", "", "--settings", disableDeepLinkSettings, "--no-session-persistence"}
|
||||
|
||||
@@ -212,7 +212,8 @@ func parseClaudeUsage(text string, now time.Time) ([]QuotaWindow, error) {
|
||||
}
|
||||
|
||||
// claudeNoWindow is the helper's word for an interactive /usage panel that
|
||||
// loaded with no window drawn (claudetui.NoUsageWindow).
|
||||
// loaded with no window drawn (claudetui.NoUsageWindow). The gateway reads
|
||||
// /usage through -p since #5582, which says no such thing.
|
||||
const claudeNoWindow = "No usage window has started"
|
||||
|
||||
func clipLine(s string) string {
|
||||
|
||||
Reference in New Issue
Block a user