claude: /usage is read in the interactive mode, typed in it, not through -p
With the interactive mode on, the plan's allowance (the Claude account's
usage card) was still read by `claude -p /usage`, the one -p run left
beside a request. Claude Code 2.1.316's -p /usage also tells only the
session's cost, no window. Now claudeUsage, with claudeTUIOn, runs the
interactive mode's helper (claudeUsageTUI) and gives it a line
{"type":"command","command":"/usage"}. The helper types /usage, waits for
the panel to settle (a "N% used" and a second without change, or three
seconds of anything else, 20s at most), closes it with Esc, and tells
what was drawn as -p's lines say it (usageText: "Current session: 0% used
· resets 5am (Asia/Shanghai)"), so parseClaudeUsage reads it unchanged.
No model is asked. The helper types no other command. The machine
reasons a request is refused for (no shim, OS, missing, off) refuse the
read the same way. Turned off, -p runs it as before.
Run (mote, at this tree on origin/main a25d3d081):
- gofmt clean; go vet internal/gateway and internal/claudetui for darwin,
windows, and linux with -tags nogui: ok.
- go test -run 'Usage|Claude|Command' ./internal/gateway
./internal/claudetui ./internal/provider: ok (59.9s, 4.1s, 25.2s).
- New tests: TestShimReadsUsage, which uses the bytes Claude Code 2.1.316
drew for the panel (testdata/usage-2.1.316.bin), TestShimRunsNoOtherCommand,
TestUsageText and TestClaudeUsageTUIOn.
Real run (this Mac, sandbox HOME, Claude Code 2.1.316, the test account):
the built helper with claudeTUIUsageArgs and the /usage line answered in
6.1s with local_command "usage" and "Current session: 0% used · resets
5am (Asia/Shanghai)" / "Current week (all models): 98% used · resets Nov
4 at 6am (Asia/Shanghai)". Exit 0.
Broken by hand: with claudeUsage's claudeTUIOn branch off,
TestClaudeUsageTUIOn read "Total cost: $0.0000" from -p and went red.
With usageText's reset dropped, TestShimReadsUsage and TestUsageText went
red.
Not tried: a plan with overages on, or a Team/Enterprise plan's panel;
both are read through the overages line and the "no window" fallback
only. Not run on Windows or in WSL. No GUI file changed. Not run: the
full gateway suite.
This commit is contained in:
@@ -344,8 +344,15 @@ The gateway's log says which (`claude: not the interactive mode: …`).
|
||||
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`) asks
|
||||
no model and is still `claude -p /usage`.
|
||||
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
|
||||
panel's windows ("NN% used", `commandSettle` still) and closes it with
|
||||
Esc. 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.
|
||||
|
||||
The Claude Code provider editor's "Claude Code runs as" row
|
||||
(`claudeModeRow` in app.js, drawn by claudemode.js, which it loads with
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
(B[?2004h[?1000h[?1002h[?1003h[?1006h[H␍[2C[16B[38;5;153m❯ /add-dir Add a new working directory␍[2C[1B[38;5;246m /artifacts Browse your published and shared artifacts␍[2C[1B /auto-mode-setup Teach auto mode about your environment, plus␍[32C[1Boptional rule tweaks[61G[39m[K␍[2C[2B/[7m ␍[38C[2B[27m[K[24;1H[22;4H[H␍[5C[16B[38;5;153m[1mu[22msage [33GShow session cost, plan [1mu[22msage, and activity␍[2C[1B[39m [38;5;153mstats[39m[K␍[5C[1B[1mu[22m[38;5;246mpgrade [33G[39m[1mU[22m[38;5;246mpgrade [44GMax for higher rate limits and more␍[32C[1BO[35G[39m[1mu[22m[38;5;246ms[39m[K␍[3C[2Bu[7m [27m[24;1H[22;5H[H␍[6C[16B[38;5;153m[1ms[58Gs␍[5C[2B[22m[38;5;246mfoc[39m[1mus[22m[38;5;246m [33GTo[36Ggle foc[39m[1mus[22m[38;5;246m view:[52Gjust your prompt, summary,[39m[K␍[32C[1B[38;5;246mand response␍[4C[2B[39ms[7m [27m[24;1H[22;6H[H␍[2C[15B[38;5;153m❯ /[1musa[22mge Show session cost, plan [1musa[22mge, and activity␍[2C[1B[39m [38;5;153mstats[39m[K␍[2C[1B[38;5;246m /claude-api Build and debug apps that use the Claude API␍[5C[1Bc[8Gntext[33GVisualize current context [39m[1musa[22m[38;5;246mge as a[70Gcolored[39m[K␍[32C[1B[38;5;246mgrid[39m[K␍[5C[2Ba[7m [27m[24;1H[22;7H[H␍[8C[15B[38;5;153m[1mg[60Gg␍[6C[2B[22m[38;5;246montext [33GVisualize[43Gcurrent con[55Gex[59G[39m[1musag[22m[38;5;246me as a colored␍[2C[1B[39m [38;5;246mgrid[39m[K␍[2C[1B[38;5;246m /effort Set effort level for model [39m[1musag[22m[38;5;246me␍[6C[2B[39mg[7m [27m[24;1H[22;8H[H␍[9C[15B[38;5;153m[1me[61Ge␍[62C[2B[39me␍[63C[2Be␍[2C[2B[22m[38;5;153m/usage[39m[7m [27m[24;1H[22;9H[H[38;5;174m▎[3G[38;5;246mthe ones it assesses as lower-risk, and blocks the rest.␍[1B[38;5;174m▎[39m [38;5;246mhttps://code.claude.com/docs/en/permission-modes␍[1B[38;5;153m▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔[61G[38;5;246m◐ medium · /effort[38;5;153m ▔␍[1B[39m [38;5;153m[1mSettings[22m[39m Status Config [48;5;153m[38;5;16m[1m Usage [22m[39m[49m Stats[K␍[2B [3G [1mSessi[10Gn[22m[K␍[1B[K␍[1B [3G [38;5;246mTotal cost: [18G [22G $0.0000[39m[K␍[1B [3G [38;5;246mTotal duration (API): [27G0s[39m[K␍[1B [3G [38;5;246mTotal duration (wall): 10s[39m[K␍[3C[1B[38;5;246mTotal code changes: 0 lines added, 0 lines removed␍[3C[1BUsage: 0 input, 0 output, 0 cache read, 0 cache write␍[3C[2B[39m[1mCurrent session␍[3C[1B[22m[48;5;102m[38;5;153m [55G[39m[49m0%[58Gused␍[2C[1B [38;5;246mResets 12am (Asia/Shanghai)[39m[K␍[32C[1B[K␍[2C[1B [1mCurrent week (all models)[22m[K␍[3C[1B[48;5;102m[38;5;153m████████████████████████████████████████▌ [55G[39m[49m81%[59Gused␍[2C[1B [38;5;246mResets Nov[15G4[17Gat[20G6am[24G(Asia/Shanghai)[39m[K␍[1B[K␍[1B [1mWhat's contributing to your usage?␍[1B[22m [38;5;246mApproximate · sessions on this machine only[39m[K␍[2C[1B [79G[38;5;246m↓[39m[24;1H[4;32H[H␍[3C[13B[38;5;246mEsc to cancel[39m[K␍[3C[1B[K␍[3C[1B[K␍[3C[2B[K␍[3C[1B[K␍[3C[1B[K␍[3C[2B[K␍[3C[1B[K[24;1H[4;32H[H␍[78C[23B[K[24;1H[4;32H[H␍[3C[2B [38;5;220mYou've used 81% of your weekly limit · resets Nov 4 at 6am (Asia/Shanghai)[39m[24;1H[4;32H
|
||||
@@ -473,6 +473,7 @@ func (s *shim) input(r io.Reader) error {
|
||||
Message struct {
|
||||
Content json.RawMessage `json:"content"`
|
||||
} `json:"message"`
|
||||
Command string `json:"command"`
|
||||
}
|
||||
if json.Unmarshal(sc.Bytes(), &m) != nil {
|
||||
continue
|
||||
@@ -485,6 +486,10 @@ func (s *shim) input(r io.Reader) error {
|
||||
"error": "Claude Code's interactive mode takes no " + m.Request.Subtype + " request"}
|
||||
}
|
||||
s.emit(map[string]any{"type": "control_response", "response": resp})
|
||||
case "command":
|
||||
if err := s.command(m.Command); err != nil {
|
||||
return err
|
||||
}
|
||||
case "user":
|
||||
pieces, err := s.userPieces(m.Message.Content)
|
||||
if err != nil {
|
||||
@@ -505,6 +510,109 @@ func (s *shim) input(r io.Reader) error {
|
||||
return sc.Err()
|
||||
}
|
||||
|
||||
// how long a command's panel may take to be drawn, and how long it stays
|
||||
// as it is before it is taken as drawn whole
|
||||
var (
|
||||
commandWait = 20 * time.Second
|
||||
commandSettle = time.Second
|
||||
)
|
||||
|
||||
// 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).
|
||||
func (s *shim) command(name string) error {
|
||||
if name != "/usage" {
|
||||
s.emit(map[string]any{"type": "result", "subtype": "error_during_execution", "is_error": true, "session_id": s.sid,
|
||||
"result": "the helper types no " + name + " in Claude Code's interactive mode"})
|
||||
return nil
|
||||
}
|
||||
for _, c := range name {
|
||||
if _, err := io.WriteString(s.pty, string(c)); err != nil {
|
||||
return err
|
||||
}
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
// the command menu drawn as it was typed settles, and is left out of
|
||||
// what is read
|
||||
time.Sleep(commandSettle)
|
||||
s.clearScreen()
|
||||
if _, err := io.WriteString(s.pty, "\r"); err != nil {
|
||||
return err
|
||||
}
|
||||
by := time.After(commandWait)
|
||||
last, quiet := "", time.Now()
|
||||
for waiting := true; waiting; {
|
||||
p := s.plain()
|
||||
if p != last {
|
||||
last, quiet = p, time.Now()
|
||||
}
|
||||
// drawn: its windows, and the panel still a moment; or anything
|
||||
// else (an error, a plan with no allowance) still for longer
|
||||
still := time.Since(quiet)
|
||||
if strings.TrimSpace(p) != "" && (usageUsed.MatchString(p) && still >= commandSettle || still >= 3*commandSettle) {
|
||||
break
|
||||
}
|
||||
select {
|
||||
case <-s.changed:
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
case <-by:
|
||||
waiting = false
|
||||
case <-s.exited:
|
||||
return fmt.Errorf("Claude Code ended (%v): %s", s.exit, s.lastScreen())
|
||||
}
|
||||
}
|
||||
_, _ = io.WriteString(s.pty, "\x1b")
|
||||
s.emit(map[string]any{"type": "result", "subtype": "success", "is_error": false, "session_id": s.sid,
|
||||
"local_command": "usage", "result": usageText(last)})
|
||||
return nil
|
||||
}
|
||||
|
||||
var (
|
||||
usageName = regexp.MustCompile(`^(session|week(?: \([^)]*\))?)`)
|
||||
usageUsed = regexp.MustCompile(`([0-9.]+)%\s+used`)
|
||||
usageReset = regexp.MustCompile(`Resets (.*?\))`)
|
||||
)
|
||||
|
||||
// usageText is the plan's allowance as /usage's panel shows it, each
|
||||
// window a bar ("Current session ███▌ 99% used", then "Resets 7pm
|
||||
// (Asia/Shanghai)" below), said as -p's lines say it: "Current session:
|
||||
// 99% used · resets 7pm (Asia/Shanghai)", a window drawn again told as
|
||||
// drawn last. Overages are said as /usage says them. A panel with no
|
||||
// window is told as drawn, for its words to say why.
|
||||
func usageText(screen string) string {
|
||||
t := strings.Join(strings.Fields(screen), " ")
|
||||
var names []string
|
||||
said := map[string]string{}
|
||||
for _, chunk := range strings.Split(t, "Current ")[1:] {
|
||||
name, used := usageName.FindString(chunk), usageUsed.FindStringSubmatch(chunk)
|
||||
if name == "" || used == nil {
|
||||
continue
|
||||
}
|
||||
line := "Current " + name + ": " + used[1] + "% used"
|
||||
if r := usageReset.FindStringSubmatch(chunk[strings.Index(chunk, used[0]):]); r != nil {
|
||||
line += " · resets " + r[1]
|
||||
}
|
||||
if _, ok := said[name]; !ok {
|
||||
names = append(names, name)
|
||||
}
|
||||
said[name] = line
|
||||
}
|
||||
var lines []string
|
||||
for _, n := range names {
|
||||
lines = append(lines, said[n])
|
||||
}
|
||||
if strings.Contains(t, "using your overages") {
|
||||
lines = append(lines, "You are currently using your overages to power your Claude Code usage.")
|
||||
}
|
||||
if len(lines) == 0 {
|
||||
return t
|
||||
}
|
||||
return strings.Join(lines, "\n")
|
||||
}
|
||||
|
||||
// piece is a part of a user message as it is pasted: words, or the path
|
||||
// of an image file, which Claude Code's prompt takes as that image
|
||||
// ("[Image #1]") when it is pasted alone.
|
||||
|
||||
@@ -214,6 +214,12 @@ func fakeClaude(args []string) {
|
||||
}
|
||||
_, _ = fmt.Fprintf(tapped, `{"s":%d,"end":"done"}`+"\n", n)
|
||||
}
|
||||
if line == "/usage" {
|
||||
// its panel, as Claude Code 2.1.316 drew it
|
||||
b, _ := os.ReadFile(os.Getenv("FAKE_USAGE"))
|
||||
_, _ = os.Stdout.Write(b)
|
||||
continue
|
||||
}
|
||||
f, _ := os.OpenFile(filepath.Join(dir, sid+".jsonl"), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600)
|
||||
rows := []any{
|
||||
map[string]any{"type": "user", "message": map[string]any{"role": "user", "content": line}},
|
||||
@@ -258,6 +264,11 @@ func runShim(t *testing.T, env []string, pargs []string, lines []string, want in
|
||||
})
|
||||
t.Setenv("MAGPIE_TUI_TEST_CFG", cfg)
|
||||
for _, l := range lines {
|
||||
// a line after "raw:" is said as it is
|
||||
if raw, ok := strings.CutPrefix(l, "raw:"); ok {
|
||||
_, _ = io.WriteString(stdin, raw+"\n")
|
||||
continue
|
||||
}
|
||||
// a line that is JSON is the message's content blocks
|
||||
var content any = l
|
||||
if json.Valid([]byte(l)) {
|
||||
@@ -628,6 +639,51 @@ func TestShimInWSL(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// /usage is typed, and the windows its panel shows are told as -p's
|
||||
// /usage lines say them, in a result naming its local command; the
|
||||
// panel is the bytes Claude Code 2.1.316 drew, a bar, then "81%", then
|
||||
// "used", each placed by a move of the cursor.
|
||||
func TestShimReadsUsage(t *testing.T) {
|
||||
panel, _ := filepath.Abs(filepath.Join("testdata", "usage-2.1.316.bin"))
|
||||
out := runShim(t, []string{"FAKE_USAGE=" + panel}, append([]string{fakePath(t)}, pArgs...), []string{`raw:{"type":"command","command":"/usage"}`}, 2)
|
||||
want := "Current session: 0% used · resets 12am (Asia/Shanghai)\nCurrent week (all models): 81% used · resets Nov 4 at 6am (Asia/Shanghai)"
|
||||
if r := out[1]; r["type"] != "result" || r["is_error"] != false || r["local_command"] != "usage" || r["result"] != want {
|
||||
t.Fatalf("told %v", r)
|
||||
}
|
||||
}
|
||||
|
||||
// A command other than /usage is told as an error, and none is typed.
|
||||
func TestShimRunsNoOtherCommand(t *testing.T) {
|
||||
out := runShim(t, nil, append([]string{fakePath(t)}, pArgs...), []string{`raw:{"type":"command","command":"/login"}`}, 2)
|
||||
if r := out[1]; r["type"] != "result" || r["is_error"] != true || !strings.Contains(r["result"].(string), "/login") {
|
||||
t.Fatalf("told %v", r)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUsageText(t *testing.T) {
|
||||
b, err := os.ReadFile(filepath.Join("testdata", "usage-2.1.316.bin"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := "Current session: 0% used · resets 12am (Asia/Shanghai)\nCurrent week (all models): 81% used · resets Nov 4 at 6am (Asia/Shanghai)"
|
||||
if got := usageText(ansi.ReplaceAllString(string(b), " ")); got != want {
|
||||
t.Fatalf("usageText = %q, want %q", got, want)
|
||||
}
|
||||
for screen, want := range map[string]string{
|
||||
// a window drawn again is told as drawn last, the Sonnet week its own
|
||||
"Current session ██ 10% used Resets 7pm (Asia/Shanghai) Current session ███ 12% used Resets 7pm (Asia/Shanghai) Current week (Sonnet only) █ 4% used Resets Nov 4 at 6am (UTC)": "Current session: 12% used · resets 7pm (Asia/Shanghai)\nCurrent week (Sonnet only): 4% used · resets Nov 4 at 6am (UTC)",
|
||||
// with no reset drawn
|
||||
"Current session 0% used": "Current session: 0% used",
|
||||
"Current session ████ 100% used Resets 7pm (UTC) You are using your overages": "Current session: 100% used · resets 7pm (UTC)\nYou are currently using your overages to power your Claude Code usage.",
|
||||
// no window: told as drawn, for its words to say why
|
||||
"Settings Usage /usage is only available for subscription plans.": "Settings Usage /usage is only available for subscription plans.",
|
||||
} {
|
||||
if got := usageText(screen); got != want {
|
||||
t.Errorf("usageText(%q) = %q, want %q", screen, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A long paste is waited for as long as Claude Code takes it in: a real
|
||||
// 3MB one showed "[Pasted text" after 35s, where pasteWait alone would
|
||||
// press Enter while the paste was still being taken in.
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"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)
|
||||
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)"
|
||||
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)"}'
|
||||
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)
|
||||
}
|
||||
b, _ := os.ReadFile(log)
|
||||
for _, want := range []string{"[-p][--output-format][stream-json][--input-format][stream-json]", "[--tools][]", "[--setting-sources][]",
|
||||
"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)
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"slices"
|
||||
@@ -172,6 +173,9 @@ func claudeUsage(ctx context.Context, configDir string) (string, error) {
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if claudeTUIOn() {
|
||||
return claudeUsageTUI(ctx, binary, configDir)
|
||||
}
|
||||
tmp, err := os.MkdirTemp("", "magpie-claude-")
|
||||
if err != nil {
|
||||
return "", err
|
||||
@@ -180,17 +184,7 @@ func claudeUsage(ctx context.Context, configDir string) (string, error) {
|
||||
cmd := binary.command(ctx, claudeUsageArgs()...)
|
||||
cmd.Dir = tmp
|
||||
cmd.Stdin = strings.NewReader("")
|
||||
// CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC makes /usage skip its request
|
||||
// and print only a reading another run left in the last hour, so it stays
|
||||
// only when the user set it.
|
||||
env := cleanClaudeEnv(os.Environ())
|
||||
if os.Getenv("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC") == "" {
|
||||
env = slices.DeleteFunc(env, func(e string) bool {
|
||||
return strings.HasPrefix(e, "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=")
|
||||
})
|
||||
}
|
||||
env = append(env, "DISABLE_TELEMETRY=1", "DISABLE_ERROR_REPORTING=1", "DISABLE_AUTOUPDATER=1")
|
||||
env, err = binary.proxied(ctx, env)
|
||||
env, err := binary.proxied(ctx, claudeUsageEnv())
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
@@ -218,6 +212,74 @@ func claudeUsage(ctx context.Context, configDir string) (string, error) {
|
||||
return "", errors.New("Claude Code: " + clip(msg))
|
||||
}
|
||||
|
||||
// claudeUsageEnv is the environment a /usage read runs Claude Code in:
|
||||
// CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC makes /usage skip its request
|
||||
// and show only a reading another run left in the last hour, so it stays
|
||||
// only when the user set it.
|
||||
func claudeUsageEnv() []string {
|
||||
env := cleanClaudeEnv(os.Environ())
|
||||
if os.Getenv("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC") == "" {
|
||||
env = slices.DeleteFunc(env, func(e string) bool {
|
||||
return strings.HasPrefix(e, "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=")
|
||||
})
|
||||
}
|
||||
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)
|
||||
}
|
||||
tmp, err := os.MkdirTemp("", "magpie-claude-")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer os.RemoveAll(tmp)
|
||||
cmd, err := binary.tuiCommand(ctx, claudeTUIUsageArgs()...)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
cmd.Dir = tmp
|
||||
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")
|
||||
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")
|
||||
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
|
||||
}
|
||||
if msg := strings.TrimSpace(stderr.String()); msg != "" {
|
||||
return "", errors.New("Claude Code: " + clip(msg))
|
||||
}
|
||||
if runErr != nil {
|
||||
return "", runErr
|
||||
}
|
||||
return "", errors.New("Claude Code ended with no answer")
|
||||
}
|
||||
|
||||
// runClaudeTree runs a one-off Claude Code (a test, a /usage) and ends,
|
||||
// with it, whatever it started: its context ending kills only the
|
||||
// process magpie started, and on Windows that is cmd.exe running npm's
|
||||
@@ -272,6 +334,13 @@ func claudeUsageArgs() []string {
|
||||
"--tools", "", "--strict-mcp-config", "--setting-sources", "", "--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", ""}
|
||||
}
|
||||
|
||||
func claudeWarmArgs(model string) []string {
|
||||
return []string{"-p", "--output-format", "json", "--model", model,
|
||||
"--tools", "", "--strict-mcp-config", "--setting-sources", "", "--no-session-persistence"}
|
||||
|
||||
Reference in New Issue
Block a user