diff --git a/docs/subsystems/claude-subscription-bridge.md b/docs/subsystems/claude-subscription-bridge.md index f39460be2..30df28369 100644 --- a/docs/subsystems/claude-subscription-bridge.md +++ b/docs/subsystems/claude-subscription-bridge.md @@ -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 diff --git a/internal/claudetui/testdata/usage-2.1.316.bin b/internal/claudetui/testdata/usage-2.1.316.bin new file mode 100644 index 000000000..5b276ea8d --- /dev/null +++ b/internal/claudetui/testdata/usage-2.1.316.bin @@ -0,0 +1 @@ +(B[?2004h[?1000h[?1002h[?1003h[?1006h ❯ /add-dir Add a new working directory  /artifacts Browse your published and shared artifacts  /auto-mode-setup Teach auto mode about your environment, plus optional rule tweaks /  usage Show session cost, plan usage, and activity  stats upgrade Upgrade Max for higher rate limits and more Ous u  ss focus Togle focus view:just your prompt, summary, and response s  ❯ /usage Show session cost, plan usage, and activity  stats  /claude-api Build and debug apps that use the Claude API cntextVisualize current context usage as acolored grid a  gg ontext Visualizecurrent conexusage as a colored  grid  /effort Set effort level for model usage g  ee e e /usage ▎the ones it assesses as lower-risk, and blocks the rest. ▎ https://code.claude.com/docs/en/permission-modes ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔◐ medium · /effort ▔  Settings Status Config  Usage  Stats   Sessin    Total cost:   $0.0000   Total duration (API): 0s   Total duration (wall): 10s Total code changes: 0 lines added, 0 lines removed Usage: 0 input, 0 output, 0 cache read, 0 cache write Current session  0%used  Resets 12am (Asia/Shanghai)   Current week (all models) ████████████████████████████████████████▌ 81%used  Resets Nov4at6am(Asia/Shanghai)   What's contributing to your usage?  Approximate · sessions on this machine only  ↓ Esc to cancel          You've used 81% of your weekly limit · resets Nov 4 at 6am (Asia/Shanghai) \ No newline at end of file diff --git a/internal/claudetui/tui.go b/internal/claudetui/tui.go index b902df0e0..a9293fc60 100644 --- a/internal/claudetui/tui.go +++ b/internal/claudetui/tui.go @@ -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. diff --git a/internal/claudetui/tui_test.go b/internal/claudetui/tui_test.go index 2093a9530..6d79b59f6 100644 --- a/internal/claudetui/tui_test.go +++ b/internal/claudetui/tui_test.go @@ -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. diff --git a/internal/gateway/claude_tui_usage_test.go b/internal/gateway/claude_tui_usage_test.go new file mode 100644 index 000000000..72365e06f --- /dev/null +++ b/internal/gateway/claude_tui_usage_test.go @@ -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) + } +} diff --git a/internal/gateway/claude_warmup.go b/internal/gateway/claude_warmup.go index 2b6a3edbd..3ba222e45 100644 --- a/internal/gateway/claude_warmup.go +++ b/internal/gateway/claude_warmup.go @@ -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"}