diff --git a/docs/subsystems/claude-subscription-bridge.md b/docs/subsystems/claude-subscription-bridge.md index 281dd5e0a..2bc7376d7 100644 --- a/docs/subsystems/claude-subscription-bridge.md +++ b/docs/subsystems/claude-subscription-bridge.md @@ -373,6 +373,26 @@ 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 helper reads the screen as a terminal shows it (`grid`, +[`screen.go`](../../internal/claudetui/screen.go), 200 by 50 on Windows +as its pseudo console is made, 80 by 24 elsewhere), beside the stream: +Windows' pseudo console sends only the cells that changed, skipping one +that holds the same letter ("Settin\x1b[1Cs"), and a window drawn only +for a moment is kept as it looked (`panel`). The panel is drawn before +its figures, "Loading usage data…" while Claude Code asks for them: the +helper waits that out (to `commandWait`), presses "r" once on "Error: +Failed to load usage data", and a panel that still has no figure is an +error result, "/usage couldn't load the plan's usage: …". Before, 3s +still on "Loading usage data…" was taken as drawn, and the panel's frame +was told as the figures, which the card read as an account with no +allowance (Seagull fries, Windows 11; `TestShimWaitsForUsageFigures`, on +the bytes the pseudo console passed on for a real 2.1.316, +`testdata/usage-loading-win-2.1.316.bin`, `usage-failed-win-2.1.316.bin`). +The provider keeps the account's last reading on that error +(`claudeUsageUnknown`, as for Claude Code's own "temporarily +unavailable"), and a panel with no figure otherwise is "Claude Code's +/usage showed no usage figures: …", never "told no allowance", which is +kept for an account Claude Code refuses (`claudeUsageDenied`). These one-off interactive runs (`askClaudeTUI`, `claudeUsageTUI`) work in magpie's shared work folder (`oneOffDir`: `claudeWorkDir`, a fresh temp diff --git a/internal/claudetui/screen.go b/internal/claudetui/screen.go new file mode 100644 index 000000000..144d6e0b6 --- /dev/null +++ b/internal/claudetui/screen.go @@ -0,0 +1,257 @@ +package claudetui + +import ( + "strconv" + "strings" + "unicode/utf8" + + "golang.org/x/text/width" +) + +// grid is Claude Code's screen as a terminal shows it: what it draws is +// put in its cells, where the cursor is moved to. Read as a stream, with +// its escapes taken out (plain), a screen drawn again only where it +// changed is misread: Windows' pseudo console sends only the cells that +// changed, a cell left as it was skipped by a move of the cursor +// ("Settin\x1b[1Cs" for "Settings", whose g was there already), and a +// number redrawn in place is a digit or two after the old one, which the +// stream still holds. The grid holds the screen as it is. +type grid struct { + cells [][]rune + cols, rows int + row, col int + // pending is the start of an escape or a character a read ended in + // the middle of + pending []byte +} + +func newGrid(cols, rows int) *grid { + g := &grid{cols: cols, rows: rows} + g.cells = make([][]rune, rows) + for i := range g.cells { + g.cells[i] = blankRow(cols) + } + return g +} + +func blankRow(cols int) []rune { + r := make([]rune, cols) + for i := range r { + r[i] = ' ' + } + return r +} + +// text is the screen, a line a row, each without its trailing spaces. +func (g *grid) text() string { + var b strings.Builder + for i, r := range g.cells { + if i > 0 { + b.WriteByte('\n') + } + var line []rune + for _, c := range r { + if c != 0 { // the second cell of a wide character + line = append(line, c) + } + } + b.WriteString(strings.TrimRight(string(line), " ")) + } + return b.String() +} + +func (g *grid) clamp() { + g.row = min(max(g.row, 0), g.rows-1) + g.col = min(max(g.col, 0), g.cols) +} + +func (g *grid) lineFeed() { + if g.row < g.rows-1 { + g.row++ + return + } + copy(g.cells, g.cells[1:]) + g.cells[g.rows-1] = blankRow(g.cols) +} + +func (g *grid) put(r rune) { + w := 1 + if k := width.LookupRune(r).Kind(); k == width.EastAsianWide || k == width.EastAsianFullwidth { + w = 2 + } + if g.col+w > g.cols { + g.col = 0 + g.lineFeed() + } + g.cells[g.row][g.col] = r + if w == 2 && g.col+1 < g.cols { + g.cells[g.row][g.col+1] = 0 + } + g.col += w +} + +// erase blanks the cells from..to (not included) of row. +func (g *grid) erase(row, from, to int) { + for i := max(from, 0); i < min(to, g.cols); i++ { + g.cells[row][i] = ' ' + } +} + +// write draws b. An escape or character cut off at its end is kept for +// the next write. +func (g *grid) write(b []byte) { + if len(g.pending) > 0 { + b = append(g.pending, b...) + g.pending = nil + } + for i := 0; i < len(b); { + c := b[i] + switch { + case c == 0x1b: + n := g.escape(b[i:]) + if n == 0 { // cut off + if len(b)-i < 4096 { + g.pending = append([]byte(nil), b[i:]...) + } + return + } + i += n + continue + case c == '\r': + g.col = 0 + case c == '\n', c == '\v', c == '\f': + g.lineFeed() + case c == '\b': + g.col = max(g.col-1, 0) + case c == '\t': + g.col = min((g.col/8+1)*8, g.cols-1) + case c < 0x20 || c == 0x7f: + default: + if !utf8.FullRune(b[i:]) { + g.pending = append([]byte(nil), b[i:]...) + return + } + r, n := utf8.DecodeRune(b[i:]) + g.put(r) + i += n + continue + } + i++ + } +} + +// escape acts on the escape at the start of b and is its length, 0 when +// b ends before it does. +func (g *grid) escape(b []byte) int { + if len(b) < 2 { + return 0 + } + switch b[1] { + case '[': + i := 2 + for i < len(b) && b[i] >= 0x20 && b[i] <= 0x3f { + i++ + } + params := string(b[2:i]) + for i < len(b) && b[i] >= 0x20 && b[i] <= 0x2f { + i++ + } + if i >= len(b) { + return 0 + } + g.csi(params, b[i]) + return i + 1 + case ']', 'P', '^', '_': + // a string, ended by BEL (an OSC's) or ST + for i := 2; i < len(b); i++ { + if b[i] == 0x07 && b[1] == ']' { + return i + 1 + } + if b[i] == 0x1b && i+1 < len(b) && b[i+1] == '\\' { + return i + 2 + } + } + return 0 + case '(', ')', '*', '+', '#', '%': + if len(b) < 3 { + return 0 + } + return 3 + case 'D': + g.lineFeed() + case 'E': + g.col = 0 + g.lineFeed() + case 'M': + g.row = max(g.row-1, 0) + } + return 2 +} + +func (g *grid) csi(params string, final byte) { + if strings.HasPrefix(params, "?") || strings.HasPrefix(params, ">") || strings.HasPrefix(params, "<") || strings.HasPrefix(params, "=") { + return // modes, keyboard protocols: nothing drawn + } + var ps []int + for _, p := range strings.Split(params, ";") { + n, _ := strconv.Atoi(p) + ps = append(ps, n) + } + arg := func(i, def int) int { + if i < len(ps) && ps[i] > 0 { + return ps[i] + } + return def + } + switch final { + case 'A': + g.row -= arg(0, 1) + case 'B', 'e': + g.row += arg(0, 1) + case 'C', 'a': + g.col += arg(0, 1) + case 'D': + g.col -= arg(0, 1) + case 'E': + g.row, g.col = g.row+arg(0, 1), 0 + case 'F': + g.row, g.col = g.row-arg(0, 1), 0 + case 'G', '`': + g.col = arg(0, 1) - 1 + case 'd': + g.row = arg(0, 1) - 1 + case 'H', 'f': + g.row, g.col = arg(0, 1)-1, arg(1, 1)-1 + case 'K': + if g.row >= 0 && g.row < g.rows { + switch arg(0, 0) { + case 0: + g.erase(g.row, g.col, g.cols) + case 1: + g.erase(g.row, 0, g.col+1) + case 2: + g.erase(g.row, 0, g.cols) + } + } + case 'J': + switch arg(0, 0) { + case 0: + g.erase(g.row, g.col, g.cols) + for r := g.row + 1; r < g.rows; r++ { + g.erase(r, 0, g.cols) + } + case 1: + for r := 0; r < g.row; r++ { + g.erase(r, 0, g.cols) + } + g.erase(g.row, 0, g.col+1) + case 2, 3: + for r := range g.rows { + g.erase(r, 0, g.cols) + } + } + case 'X': + g.erase(g.row, g.col, g.col+arg(0, 1)) + } + g.clamp() +} diff --git a/internal/claudetui/screen_test.go b/internal/claudetui/screen_test.go new file mode 100644 index 000000000..75bba76bf --- /dev/null +++ b/internal/claudetui/screen_test.go @@ -0,0 +1,61 @@ +package claudetui + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +// The screen is read as a terminal shows it: a cell Windows' pseudo +// console skips because it holds the same letter ("Settin\x1b[1Cs") is +// still that letter, and a figure redrawn in place reads as redrawn, where +// the stream had both ("10% used" then "2"). +func TestGridDrawsInPlace(t *testing.T) { + g := newGrid(200, 50) + g.write([]byte("\x1b[10;3HSettings Status\x1b[12;3HCurrent session \x1b[38;2;1;2;3m██\x1b[m 10% used")) + g.write([]byte("\x1b[10;3HSettin\x1b[1Cs\x1b[m Status")) + g.write([]byte("\x1b[12;23H2")) + // an escape and a character cut off between two reads + g.write([]byte("\x1b[13;3HResets 7pm \x1b[3")) + g.write([]byte("8;2;1;2;3m(Asia/Shanghai) \xe2\x96")) + g.write([]byte("\x88")) + text := g.text() + for _, want := range []string{"\n Settings Status\n", "\n Current session ██ 12% used\n", "\n Resets 7pm (Asia/Shanghai) █\n"} { + if !strings.Contains(text, want) { + t.Fatalf("screen lacks %q:\n%s", want, text) + } + } + if got := usageText(text); got != "Current session: 12% used · resets 7pm (Asia/Shanghai)" { + t.Fatalf("usageText = %q", got) + } + // erased: to the end of the line, characters (ECH), the screen + g.write([]byte("\x1b[12;19H\x1b[K\x1b[10;3H\x1b[3X")) + if text := g.text(); !strings.Contains(text, "\n Current session\n") || !strings.Contains(text, "\n tings Status\n") { + t.Fatalf("erased:\n%s", text) + } + g.write([]byte("\x1b[2J")) + if strings.TrimSpace(g.text()) != "" { + t.Fatalf("cleared:\n%s", g.text()) + } +} + +// What the pseudo console passed on for a real Claude Code 2.1.316's +// /usage panel, loading its figures and failing to, reads as that panel. +func TestGridReadsConPTYPanel(t *testing.T) { + for file, want := range map[string]string{ + "usage-loading-win-2.1.316.bin": "Loading usage data…", + "usage-failed-win-2.1.316.bin": "Error: Failed to load usage data", + } { + b, err := os.ReadFile(filepath.Join("testdata", file)) + if err != nil { + t.Fatal(err) + } + g := newGrid(200, 50) + g.write(b) + text := g.text() + if !strings.Contains(text, want) || !strings.Contains(text, "❯ /usage") || usageUsed.MatchString(text) { + t.Fatalf("%s:\n%s", file, text) + } + } +} diff --git a/internal/claudetui/testdata/.gitattributes b/internal/claudetui/testdata/.gitattributes new file mode 100644 index 000000000..08e4e0349 --- /dev/null +++ b/internal/claudetui/testdata/.gitattributes @@ -0,0 +1,2 @@ +# the bytes Claude Code drew, through a pty or Windows' pseudo console, CRLF and all +*.bin -text diff --git a/internal/claudetui/testdata/usage-failed-win-2.1.316.bin b/internal/claudetui/testdata/usage-failed-win-2.1.316.bin new file mode 100644 index 000000000..a658a7f28 --- /dev/null +++ b/internal/claudetui/testdata/usage-failed-win-2.1.316.bin @@ -0,0 +1,5 @@ +❯ /usage  + +────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────Settins Status Config  Usage  Stats +Session +Total cost:$0.0000Total duration (API):0sTotal duration (wall): 1sTotal code changes: 0 lines added, 0 lines removedUsage: 0 input, 0 output, 0 cache read, 0 cache writeLoading usage data…Esc to cancelError: Failed to load usage datar to retry · Esc to cancel \ No newline at end of file diff --git a/internal/claudetui/testdata/usage-loading-win-2.1.316.bin b/internal/claudetui/testdata/usage-loading-win-2.1.316.bin new file mode 100644 index 000000000..e8d857cdb --- /dev/null +++ b/internal/claudetui/testdata/usage-loading-win-2.1.316.bin @@ -0,0 +1,5 @@ +❯ /usage  + +────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────Settins Status Config  Usage  Stats +Session +Total cost:$0.0000Total duration (API):0sTotal duration (wall): 1sTotal code changes: 0 lines added, 0 lines removedUsage: 0 input, 0 output, 0 cache read, 0 cache writeLoading usage data…Esc to cancel \ No newline at end of file diff --git a/internal/claudetui/tui.go b/internal/claudetui/tui.go index fae3ac911..b1cdea92c 100644 --- a/internal/claudetui/tui.go +++ b/internal/claudetui/tui.go @@ -30,6 +30,7 @@ import ( "os/signal" "path/filepath" "regexp" + "runtime" "slices" "strconv" "strings" @@ -75,6 +76,12 @@ type shim struct { screenMu sync.Mutex screen []byte changed chan struct{} + // grid is the screen as a terminal shows it (screen.go), drawn from + // the start; panel is how it looked last while a /usage read was + // going (watch) and showed a window, "" once the screen is cleared + grid *grid + watch bool + panel string // rows ticks when a user message (or one queued mid-turn) reaches the // transcript: a pasted message was sent @@ -287,6 +294,18 @@ func (s *shim) read() { if len(s.screen) > 256<<10 { s.screen = append([]byte(nil), s.screen[len(s.screen)-128<<10:]...) } + if s.grid == nil { + s.grid = newGrid(screenSize()) + } + s.grid.write(d) + if s.watch { + // a panel can be drawn only for a moment (Claude Code + // 2.1.316 draws /usage's windows, then the panel again + // without them), so each look of it is kept + if t := s.grid.text(); usageUsed.MatchString(t) { + s.panel = t + } + } s.screenMu.Unlock() select { case s.changed <- struct{}{}: @@ -313,9 +332,31 @@ func (s *shim) plain() string { func (s *shim) clearScreen() { s.screenMu.Lock() s.screen = s.screen[:0] + s.panel = "" s.screenMu.Unlock() } +// screenSize is the size of Claude Code's terminal: Windows' pseudo +// console is made 200 by 50 (child_windows.go); a pty here is given no +// size, and Claude Code draws in 80 by 24. +func screenSize() (cols, rows int) { + if runtime.GOOS == "windows" { + return 200, 50 + } + return 80, 24 +} + +// looks is the screen as it is now, and the last look of it with a +// usage window since it was cleared, while watched. +func (s *shim) looks() (now, panel string) { + s.screenMu.Lock() + defer s.screenMu.Unlock() + if s.grid != nil { + now = s.grid.text() + } + return now, s.panel +} + // lastScreen is the end of what Claude Code drew, for an error to say. func (s *shim) lastScreen() string { p := strings.Join(strings.Fields(s.plain()), " ") @@ -637,23 +678,56 @@ func (s *shim) command(name string) error { if _, err := io.WriteString(s.pty, "\r"); err != nil { return err } + s.screenMu.Lock() + s.watch = true + s.screenMu.Unlock() + defer func() { + s.screenMu.Lock() + s.watch = false + s.screenMu.Unlock() + }() by := time.After(commandWait) - last, quiet, drawn := "", time.Now(), false + last, quiet, drawn, retried := "", time.Now(), false, false + var now, panel string for waiting := true; waiting; { p := s.plain() - if p != last { - last, quiet = p, time.Now() + now, panel = s.looks() + if p+now != last { + last, quiet = p+now, time.Now() } - // 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 usageUsed.MatchString(p) && still >= commandSettle || usageDrawn(p) && still >= 3*commandSettle { + loading, failed := usageLoading.MatchString(now), usageFailed.MatchString(now) + figures := panel != "" || usageUsed.MatchString(p) + switch { + case loading: + // the panel is drawn before its figures, which Claude Code + // asks Anthropic for: a slow answer kept "Loading usage + // data…" on screen past the 3s below, and the panel's + // frame was told as the figures (Seagull fries) + s.doing.Store("was still loading " + name + "'s figures") + if figures && still >= 3*commandSettle { + drawn = true + } + case failed && !figures && !retried && still >= commandSettle: + // "Error: Failed to load usage data", "r to retry" + s.doing.Store("couldn't load " + name + "'s figures") + if _, err := io.WriteString(s.pty, "r"); err != nil { + return err + } + retried, quiet = true, time.Now() + // drawn: its windows, and the panel still a moment; or the + // panel's words with no window (a failure, 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. + case figures && still >= commandSettle, + (failed || usageDrawn(p) || usageDrawn(now)) && still >= 3*commandSettle: drawn = true + } + if drawn { break } select { @@ -666,13 +740,25 @@ func (s *shim) command(name string) error { } } _, _ = io.WriteString(s.pty, "\x1b") - if !drawn { + p := s.plain() + text := usageText(panel) + if panel == "" { + text = usageText(p) + } + switch { + case !usageUsed.MatchString(panel+p) && (usageLoading.MatchString(now) || usageFailed.MatchString(now)): + // no figures, the panel still loading them or saying it + // couldn't: unknown, not a plan with no allowance + s.emit(map[string]any{"type": "result", "subtype": "error_during_execution", "is_error": true, "session_id": s.sid, + "result": name + " couldn't load the plan's usage: " + strings.Join(strings.Fields(now), " ")}) + return nil + case !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)}) + "local_command": "usage", "result": text}) return nil } @@ -684,6 +770,9 @@ func usageDrawn(screen string) bool { return usagePanel.MatchString(t) && !usageLoading.MatchString(t) } +// /usage's panel once its figures failed to load (Claude Code 2.1.316) +var usageFailed = regexp.MustCompile(`Failed to load usage data`) + var ( usageName = regexp.MustCompile(`^(session|week(?: \([^)]*\))?)`) usageUsed = regexp.MustCompile(`([0-9.]+)%\s+used`) diff --git a/internal/claudetui/tui_test.go b/internal/claudetui/tui_test.go index 08b6e43c1..a83327f4e 100644 --- a/internal/claudetui/tui_test.go +++ b/internal/claudetui/tui_test.go @@ -2,6 +2,7 @@ package claudetui import ( "bufio" + "bytes" "encoding/base64" "encoding/json" "fmt" @@ -211,6 +212,9 @@ func fakeClaude(args []string) { var mu sync.Mutex var typed, paste strings.Builder pasting, images := false, 0 + // retry is what an "r" draws while /usage's panel says it couldn't + // load the figures, nil when it says nothing of the kind + var retry []byte for { c, err := r.ReadByte() if err != nil { @@ -248,6 +252,10 @@ func fakeClaude(args []string) { case pasting: paste.WriteByte(c) continue + case c == 'r' && retry != nil: + fakeFrames(retry) + retry = nil + continue case c != '\r': mu.Lock() typed.WriteByte(c) @@ -292,7 +300,26 @@ func fakeClaude(args []string) { } // its panel, as Claude Code 2.1.316 drew it b, _ := os.ReadFile(os.Getenv("FAKE_USAGE")) - _, _ = os.Stdout.Write(b) + // FAKE_USAGE_FIRST: drawn before it, as Windows' pseudo + // console passed on 2.1.316's panel loading its figures, or + // failing to; FAKE_USAGE_THEN says what comes after: the + // figures 4s later ("slow"), or on an "r" ("retry"), or the + // failure again on an "r" ("retry-fails") + if first := os.Getenv("FAKE_USAGE_FIRST"); first != "" { + f, _ := os.ReadFile(first) + _, _ = os.Stdout.Write(f) + switch os.Getenv("FAKE_USAGE_THEN") { + case "slow": + time.Sleep(4 * time.Second) + case "retry": + retry = b + continue + case "retry-fails": + retry = f + continue + } + } + fakeFrames(b) continue } f, _ := os.OpenFile(filepath.Join(dir, sid+".jsonl"), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600) @@ -311,6 +338,25 @@ func fakeClaude(args []string) { } } +// fakeFrames draws b a frame at a time, as Claude Code does: each frame +// ends parking the cursor at the screen's foot (ESC[24;1H), and the next +// comes a moment later. A terminal that renders what it is given (Windows' +// pseudo console) passes on each frame, not only how the last one left +// the screen. +func fakeFrames(b []byte) { + park := []byte("\x1b[24;1H") + for len(b) > 0 { + i := bytes.Index(b, park) + if i < 0 { + _, _ = os.Stdout.Write(b) + return + } + _, _ = os.Stdout.Write(b[:i+len(park)]) + b = b[i+len(park):] + time.Sleep(50 * time.Millisecond) + } +} + // shim runs the shim on the fake Claude Code with pargs, says lines on its // input and returns what it wrote, once it wrote want lines. func runShim(t *testing.T, env []string, pargs []string, lines []string, want int) []map[string]any { @@ -831,6 +877,44 @@ func TestUsageDrawn(t *testing.T) { } } +// Windows' pseudo console (Seagull fries, Claude Code 2.1.316 on Windows +// 11): /usage's panel is drawn "Loading usage data…" while Claude Code +// asks for the figures, and an answer slower than 3s had the panel's +// frame told as the figures ("❯ /usage ─── Settin s Status Config Usage +// …"), which the card read as an account with no allowance. A panel that +// failed to load ("Error: Failed to load usage data", "r to retry") was +// told the same way. The figures are waited for, a failure retried once, +// and a panel still with no figures told as an error. The first frames +// are the bytes the pseudo console passed on for a real 2.1.316 in a +// sandbox (testdata/usage-*-win-2.1.316.bin). +func TestShimWaitsForUsageFigures(t *testing.T) { + panel, _ := filepath.Abs(filepath.Join("testdata", "usage-2.1.316.bin")) + loading, _ := filepath.Abs(filepath.Join("testdata", "usage-loading-win-2.1.316.bin")) + failed, _ := filepath.Abs(filepath.Join("testdata", "usage-failed-win-2.1.316.bin")) + want := "Current session: 0% used · resets 12am (Asia/Shanghai)\nCurrent week (all models): 81% used · resets Nov 4 at 6am (Asia/Shanghai)" + for _, c := range []struct{ name, first, then, err string }{ + {"slow", loading, "slow", ""}, + {"retried", failed, "retry", ""}, + {"failed again", failed, "retry-fails", "/usage couldn't load the plan's usage: "}, + } { + t.Run(c.name, func(t *testing.T) { + out := runShim(t, []string{"FAKE_USAGE=" + panel, "FAKE_USAGE_FIRST=" + c.first, "FAKE_USAGE_THEN=" + c.then}, + append([]string{fakePath(t)}, pArgs...), []string{`raw:{"type":"command","command":"/usage"}`}, 2) + r := out[1] + if c.err == "" { + if r["type"] != "result" || r["is_error"] != false || r["result"] != want { + t.Fatalf("told %v", r) + } + return + } + got, _ := r["result"].(string) + if r["type"] != "result" || r["is_error"] != true || !strings.HasPrefix(got, c.err) || !strings.Contains(got, "Failed to load usage data") { + 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) diff --git a/internal/provider/claude_usage_cli.go b/internal/provider/claude_usage_cli.go index 904541c4d..9fe29402c 100644 --- a/internal/provider/claude_usage_cli.go +++ b/internal/provider/claude_usage_cli.go @@ -66,6 +66,16 @@ var claudeUsageLineRE = regexp.MustCompile(`^Current (session|week(?: \(([^)]+)\ // without an allowance. This says nothing about the account's limits. var errClaudeUsageUnavailable = errors.New("Claude Code's /usage is temporarily unavailable") +// claudeUsageUnknown is a /usage read that told nothing of the account, +// for a reason that passes: Claude Code's own "temporarily unavailable", +// or a panel that couldn't load its figures (the helper's "/usage +// couldn't load the plan's usage": still "Loading usage data…", or +// "Failed to load usage data" after a retry). The card keeps the +// account's last reading. Windows' pseudo console showed 2.1.316's panel +// while it still loaded, and the card said the account had no allowance +// (Seagull fries). +var claudeUsageUnknown = regexp.MustCompile(`^(?:Claude Code: )?(?:` + regexp.QuoteMeta(errClaudeUsageUnavailable.Error()) + `|/usage couldn't load the plan's usage)`) + var errClaudeCannotRun = errors.New("Claude Code can't be run from here") // An account error stays visible even when it also mentions a timeout or @@ -153,8 +163,10 @@ func parseClaudeUsage(text string, now time.Time) ([]QuotaWindow, error) { }) { return out, errClaudeUsageUnavailable } + // a panel with no figure says nothing of the account's allowance: + // unknown, its words told first, _, _ := strings.Cut(text, "\n") - return out, errors.New("Claude Code's /usage told no allowance: " + clipLine(first)) + return out, errors.New("Claude Code's /usage showed no usage figures: " + clipLine(first)) } return out, nil } diff --git a/internal/provider/claude_usage_fallback_test.go b/internal/provider/claude_usage_fallback_test.go index 3a4a5bf8d..1f8f0e29b 100644 --- a/internal/provider/claude_usage_fallback_test.go +++ b/internal/provider/claude_usage_fallback_test.go @@ -3,6 +3,7 @@ package provider import ( "context" "encoding/json" + "errors" "os" "path/filepath" "strings" @@ -316,3 +317,37 @@ func TestClaudeUsageUnavailableRecovers(t *testing.T) { t.Fatalf("next failure should keep the recovered reading: %+v", q) } } + +// A /usage read that showed no figures is unknown, never an account with +// no allowance. Seagull fries' Claude Code 2.1.316 on Windows told /usage's +// panel while it still loaded its figures, and the card said "/usage told +// no allowance". The helper now says when the panel couldn't load them, +// and the card keeps the account's last reading then, as for Claude +// Code's own "temporarily unavailable"; any other panel with no figures +// is told as what it showed. +func TestClaudeUsageWithoutFiguresIsUnknown(t *testing.T) { + at := time.Now().Add(-10 * time.Minute).Truncate(time.Second) + reset := time.Now().Add(time.Hour).Truncate(time.Second) + snapshot := lastQuota{At: at, Q: SubscriptionQuota{Provider: "claude", Plan: "pro", Windows: []QuotaWindow{ + {Name: "5 hours", Used: 40, ResetsAt: &reset}, + }}} + // the result the helper gave for the panel as the pseudo console drew it + chrome := "❯ /usage ──────────── Settin s Status Config Usage Stats Session Total cost: $0.0000 Total duration (API): 0s Total duration (wall): 1s Total code changes: 0 lines added, 0 lines removed Usage: 0 input, 0 output, 0 cache read, 0 cache write Loading usage data… Esc to cancel" + _, card := claudeUsageCards(t, chrome, nil) + if q := card(); !strings.HasPrefix(q.Error, "Claude Code's /usage showed no usage figures: ❯ /usage") || len(q.Windows) != 0 { + t.Fatalf("the panel's frame read as %+v", q) + } + for _, err := range []string{ + "Claude Code: /usage couldn't load the plan's usage: ❯ /usage Error: Failed to load usage data r to retry · Esc to cancel", + "Claude Code: /usage couldn't load the plan's usage: ❯ /usage Loading usage data… Esc to cancel", + } { + t.Run(err, func(t *testing.T) { + _, card := claudeUsageCards(t, "", &snapshot) + UsageClaudeVia(func(context.Context, string) (string, error) { return "", errors.New(err) }) + q := card() + if q.Error != "" || q.AsOf == nil || !q.AsOf.Equal(at) || len(q.Windows) != 1 || q.Windows[0].Used != 40 { + t.Fatalf("a panel that couldn't load its figures should keep this account's reading: %+v", q) + } + }) + } +} diff --git a/internal/provider/quota_last.go b/internal/provider/quota_last.go index af4f0f4b3..2ff1d358d 100644 --- a/internal/provider/quota_last.go +++ b/internal/provider/quota_last.go @@ -100,7 +100,7 @@ func keepLast(q SubscriptionQuota, user string) SubscriptionQuota { if q.Provider == "claude" && claudeUsageDenied.MatchString(q.Error) { return q } - claudeUnavailable := q.Provider == "claude" && q.Error == errClaudeUsageUnavailable.Error() + claudeUnavailable := q.Provider == "claude" && claudeUsageUnknown.MatchString(q.Error) if !claudeUnavailable && !passing.MatchString(q.Error) { return q }