diff --git a/docs/subsystems/claude-subscription-bridge.md b/docs/subsystems/claude-subscription-bridge.md index 21ffe01cf..281dd5e0a 100644 --- a/docs/subsystems/claude-subscription-bridge.md +++ b/docs/subsystems/claude-subscription-bridge.md @@ -362,7 +362,13 @@ 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 +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 +for three `commandSettle`s: Claude Code draws its banner and folder again +first, which stays still while a slow /usage loads, and taken as the +panel it was read as an allowance's error (ikunbots on X, v0.1.2738). +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` diff --git a/internal/claudetui/tui.go b/internal/claudetui/tui.go index c163194d8..fae3ac911 100644 --- a/internal/claudetui/tui.go +++ b/internal/claudetui/tui.go @@ -638,7 +638,7 @@ func (s *shim) command(name string) error { return err } by := time.After(commandWait) - last, quiet := "", time.Now() + last, quiet, drawn := "", time.Now(), false for waiting := true; waiting; { p := s.plain() if p != last { @@ -646,8 +646,14 @@ func (s *shim) command(name string) error { } // drawn: its windows, and the panel still a moment; or anything // else (an error, a plan with no allowance) still for longer + // Claude Code draws itself again first (its banner, the folder, + // the prompt's rules), which stays still while a slow /usage + // loads: told as the panel, its banner was read as an allowance + // (ikunbots on X, v0.1.2738). Anything else is waited for only + // once the panel's tabs are drawn, and not loading. still := time.Since(quiet) - if strings.TrimSpace(p) != "" && (usageUsed.MatchString(p) && still >= commandSettle || still >= 3*commandSettle) { + if usageUsed.MatchString(p) && still >= commandSettle || usageDrawn(p) && still >= 3*commandSettle { + drawn = true break } select { @@ -660,15 +666,30 @@ func (s *shim) command(name string) error { } } _, _ = io.WriteString(s.pty, "\x1b") + if !drawn { + s.emit(map[string]any{"type": "result", "subtype": "error_during_execution", "is_error": true, "session_id": s.sid, + "result": fmt.Sprintf("Claude Code hadn't drawn /usage's panel in %s: %s", commandWait, s.lastScreen())}) + return nil + } s.emit(map[string]any{"type": "result", "subtype": "success", "is_error": false, "session_id": s.sid, "local_command": "usage", "result": usageText(last)}) return nil } +// usageDrawn is /usage's panel drawn and loaded: the tabs of the Settings +// it opens in ("Settings Status Config Usage Stats", Claude Code +// 2.1.316), with nothing still loading. +func usageDrawn(screen string) bool { + t := strings.Join(strings.Fields(screen), " ") + return usagePanel.MatchString(t) && !usageLoading.MatchString(t) +} + var ( - usageName = regexp.MustCompile(`^(session|week(?: \([^)]*\))?)`) - usageUsed = regexp.MustCompile(`([0-9.]+)%\s+used`) - usageReset = regexp.MustCompile(`Resets (.*?\))`) + usageName = regexp.MustCompile(`^(session|week(?: \([^)]*\))?)`) + usageUsed = regexp.MustCompile(`([0-9.]+)%\s+used`) + usageReset = regexp.MustCompile(`Resets (.*?\))`) + usagePanel = regexp.MustCompile(`\bSettings\b.*\bUsage\b`) + usageLoading = regexp.MustCompile(`(?i)\bloading\b`) ) // usageText is the plan's allowance as /usage's panel shows it, each diff --git a/internal/claudetui/tui_test.go b/internal/claudetui/tui_test.go index 383898b6c..08b6e43c1 100644 --- a/internal/claudetui/tui_test.go +++ b/internal/claudetui/tui_test.go @@ -279,6 +279,17 @@ func fakeClaude(args []string) { _, _ = fmt.Fprintf(tapped, `{"s":%d,"end":"done"}`+"\n", n) } if line == "/usage" { + // Claude Code drawn again before a slow /usage's panel: its + // banner and folder, as ikunbots' read told them (v0.1.2738) + if after := os.Getenv("FAKE_USAGE_BANNER"); after != "" { + fmt.Print("\x1b[2J\x1b[H ▐▛███▜▌ Claude Code v2.1.316\r\n▝▜█████▛▘ Opus 4.8 · Claude Pro\r\n ▘▘ ▝▝ /private/var/folders/3d/qhyx6qps/T/magpie-claude-work-501\r\n\r\n" + + strings.Repeat("─", 80) + "\r\n❯ \r\n" + strings.Repeat("─", 80) + "\r\n") + ms, err := strconv.Atoi(after) + if err != nil { + continue + } + time.Sleep(time.Duration(ms) * time.Millisecond) + } // its panel, as Claude Code 2.1.316 drew it b, _ := os.ReadFile(os.Getenv("FAKE_USAGE")) _, _ = os.Stdout.Write(b) @@ -637,6 +648,8 @@ func TestShimEndsAtItsCallersDeadline(t *testing.T) { {"trust unanswered", `{"type":"user","message":{"role":"user","content":"hello"}}`, "asked whether to trust " + wd + ", not answered in the", "trust this folder", []string{"FAKE_TRUST=deaf", TrustEnv + "=1"}}, // FAKE_USAGE names no panel: nothing is drawn for /usage {"no /usage panel", `{"type":"command","command":"/usage"}`, "hadn't drawn /usage's panel in the", "", []string{"FAKE_USAGE=" + filepath.Join(t.TempDir(), "none")}}, + // the banner drawn again and no panel after it: never told as one + {"banner, no /usage panel", `{"type":"command","command":"/usage"}`, "hadn't drawn /usage's panel in the", "magpie-claude-work-501", []string{"FAKE_USAGE_BANNER=never"}}, } { t.Run(c.name, func(t *testing.T) { start := time.Now() @@ -786,6 +799,38 @@ func TestShimReadsUsage(t *testing.T) { } } +// Claude Code draws its banner again before /usage's panel, and a slow +// /usage leaves it still for seconds. It is waited past, never told as the +// panel: read as one, the banner was an allowance's error (ikunbots on X, +// v0.1.2738, "/usage told no allowance: ▘▘ ▝▝ /private/var/folders/…"). +func TestShimWaitsPastTheBanner(t *testing.T) { + panel, _ := filepath.Abs(filepath.Join("testdata", "usage-2.1.316.bin")) + out := runShim(t, []string{"FAKE_USAGE=" + panel, "FAKE_USAGE_BANNER=4500"}, 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["result"] != want { + t.Fatalf("told %v", r) + } +} + +func TestUsageDrawn(t *testing.T) { + b, err := os.ReadFile(filepath.Join("testdata", "usage-2.1.316.bin")) + if err != nil { + t.Fatal(err) + } + if !usageDrawn(ansi.ReplaceAllString(string(b), " ")) { + t.Fatal("2.1.316's panel isn't taken as drawn") + } + for screen, want := range map[string]bool{ + "▐▛███▜▌ Claude Code v2.1.316 ▘▘ ▝▝ /private/var/folders/3d/x/T/magpie-claude-work-501 ──── ❯ ────": false, + "Settings Status Config Usage Stats Loading usage…": false, + "Settings Usage /usage is only available for subscription plans.": true, + } { + if got := usageDrawn(screen); got != want { + t.Errorf("usageDrawn(%q) = %v, want %v", screen, got, want) + } + } +} + // 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)