claude: /usage and "hi" reads run in magpie's work folder and say why they ended (#4830)
mydosu's Claude Code quota reads on Windows failed for both accounts
with "exit status 1" alone. Two things were behind it:
- Each one-off interactive run (claudeUsageTUI, askClaudeTUI) started in
a new magpie-claude-<n> temp folder, which the helper trusted, so each
read wrote one more trusted projects entry into the config's state file.
The reporter had 67 in ~/.claude.json.
- The caller's budget (subscriptionTimeout, 20s) is shorter than the
helper's own waits (45s for the prompt, 20s for a panel). The context's
kill came first, and that is TerminateProcess on Windows, so Wait said
"exit status 1" with an empty stderr. On Unix the same kill says
"signal: killed".
What changed:
- One-off TUI runs work in claudeWorkDir (oneOffDir). That is the
owner-checked folder the bridge's own runs already use, so each config
directory holds one trusted entry instead of one per read. A temp
folder is made only when that folder can't be.
- The run's session file there is removed by the session_id the helper's
init line names (dropOneOff). It is not removed under WSL.
- The helper is told its caller's deadline (claudetui.DeadlineEnv, the
context's deadline less min(3s, a quarter of what is left)). At that
time it ends on its own, saying what Claude Code hadn't done and its
last screen, e.g. "Claude Code hadn't drawn /usage's panel in the
2.9s its caller waits for it: ...".
- A run that still says nothing reads "Claude Code's interactive mode
said nothing before magpie stopped waiting for it (...)" (oneOffErr),
not an exit code.
- quotaError says these reasons on the card as "Allowance unavailable:
{why}" (an existing key in every language). The full text stays in
the tooltip. Nearby comments were cut so the core script budget holds
without a raise.
- No -p fallback was added. The -p asks keep their own temp folder,
since -p asks nothing about trust.
- The entries older magpies left in ~/.claude.json are left alone:
magpie never writes that file.
Run at this head (after the rebase on c875e66c2), on mote:
- go test -count=1 ./internal/claudetui: ok.
- go test -count=1 -run 'Claude|TUI|Usage|Warm|Ask' ./internal/gateway: ok.
- go test ./internal/gui -run 'Budget|I18n|Script': ok.
- node --test claude-quota-onboarding (chromium and webkit, en, zh,
zh-TW, ja and de, 440px) and i18n-keys: 14 of 14.
- GOOS=linux and GOOS=windows go vet of claudetui and gateway: clean.
- gofmt -l: clean.
On xiaomi-gpu (Windows 11, win-run):
- TestShimEndsAtItsCallersDeadline passes through ConPTY.
- TestShimFirstMessageWaitsForTools and TestShimReadsUsage are red the
same way on origin/main c875e66c2. They are filed as #4810 and #4820.
- The real Claude Code 2.1.316 ran under a sandbox HOME and
CLAUDE_CONFIG_DIR, with fake credentials and a rebuilt magpie.exe.
Before the change, each run left a new trusted temp entry. With
MAGPIE_CLAUDE_TUI_BY 3s out, the helper now exits saying "Claude Code
hadn't drawn /usage's panel in the 2.9s its caller waits for it: <its
screen>". Untrusted, it says the trust reason.
Broken by hand (each went red):
- The helper ignores DeadlineEnv: claudetui's deadline test.
- oneOffDir never uses claudeWorkDir: two different pwds and sessions
left.
- removeSession dropped: "session was left".
- oneOffErr's context branch removed: got "signal: killed".
- helperDeadline not passed: "helper was told by:" empty.
- quotaError's new lines removed: the onboarding GUI test shows
"Allowance unavailable" alone.
Not tried:
- A real signed-in Claude account on Windows. So which step is slow on
the reporter's machine (start-up, the prompt or the panel) is not
known. The card now names it.
- Unrelated, seen while breaking it: with no deadline, a /usage whose
panel is never drawn ends after 20s as a success with an empty result.
Reported by mydosu (myduso_27930 on Discord).
This commit is contained in:
@@ -356,6 +356,27 @@ 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.
|
||||
|
||||
These one-off interactive runs (`askClaudeTUI`, `claudeUsageTUI`) 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
|
||||
a new `magpie-claude-<n>` entry each read (#4830, mydosu): 67 had piled up
|
||||
in one `~/.claude.json`. Entries left by older magpies stay; magpie
|
||||
doesn't write that file. The run's own session file in that folder is
|
||||
removed by the `session_id` the helper's init line names (`dropOneOff`),
|
||||
so the folder's project doesn't fill with "hi"s. The helper is told when
|
||||
its caller stops waiting (`claudetui.DeadlineEnv`, the context's deadline
|
||||
less `oneOffMargin`, at most a quarter of what is left) and ends then on
|
||||
its own, saying what Claude Code hadn't done and its last screen ("Claude
|
||||
Code hadn't drawn /usage's panel in the 16.9s its caller waits for it:
|
||||
…"). Killed at the deadline instead, it said nothing, and on Windows the
|
||||
reading's error was "exit status 1" alone. A run that still says nothing
|
||||
is "Claude Code's interactive mode said nothing before magpie stopped
|
||||
waiting for it" (`oneOffErr`), and the card says the reason
|
||||
(`quotaError`'s "Allowance unavailable: {why}"), its full text kept for the
|
||||
tooltip. The `-p` asks keep a temp folder each, which they remove: `-p`
|
||||
asks nothing about trust.
|
||||
|
||||
The Claude Code provider editor's "Claude Code runs as" row
|
||||
(`claudeModeRow` in app.js, drawn by claudemode.js, which it loads with
|
||||
its first read) is a switch between Interactive mode (TUI) and claude
|
||||
|
||||
@@ -10,6 +10,14 @@ const Command = "claude-tui-helper"
|
||||
// answer in their own Claude Code, and the run ends, saying so.
|
||||
const TrustEnv = "MAGPIE_CLAUDE_TUI_TRUST"
|
||||
|
||||
// DeadlineEnv holds, in Unix milliseconds, when a one-off run's caller
|
||||
// (a /usage read, a test's "hi") stops waiting for it. The helper ends
|
||||
// then on its own, saying on its stderr what Claude Code hadn't done and
|
||||
// what it last drew. Killed at the caller's deadline instead, it said
|
||||
// nothing, and the reading's error was its exit code alone, "exit status
|
||||
// 1" on Windows (#4830).
|
||||
const DeadlineEnv = "MAGPIE_CLAUDE_TUI_BY"
|
||||
|
||||
// Untrusted begins what the helper says, on its stderr, as it ends over a
|
||||
// folder it wasn't told to trust: the bridge then runs the turn in a
|
||||
// folder of magpie's.
|
||||
|
||||
@@ -34,6 +34,7 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/appdir"
|
||||
@@ -105,6 +106,10 @@ type shim struct {
|
||||
// listed is the file magpie's tool server writes once Claude Code has
|
||||
// listed its tools (mcpListed), "" for a run without it
|
||||
listed string
|
||||
|
||||
// doing is what Claude Code is being waited on for, as late says it
|
||||
// once its caller stops waiting (DeadlineEnv)
|
||||
doing atomic.Value
|
||||
}
|
||||
|
||||
// Run runs Claude Code at path, args being the bridge's `claude -p` ones,
|
||||
@@ -188,6 +193,18 @@ func Run(args []string) error {
|
||||
s.tap.drop()
|
||||
os.Exit(1)
|
||||
}()
|
||||
if by, ok := deadline(os.Getenv(DeadlineEnv)); ok {
|
||||
started := time.Now()
|
||||
t := time.AfterFunc(time.Until(by), func() {
|
||||
fmt.Fprintf(os.Stderr, "claude-tui: %s\n", s.late(time.Since(started)))
|
||||
s.stop()
|
||||
s.dropImages()
|
||||
s.tap.drop()
|
||||
os.Exit(1)
|
||||
})
|
||||
defer t.Stop()
|
||||
}
|
||||
s.doing.Store("showed no prompt")
|
||||
if err := s.ready(); err != nil {
|
||||
signal.Reset()
|
||||
s.stop()
|
||||
@@ -324,6 +341,26 @@ func lastAt(re *regexp.Regexp, p string) int {
|
||||
return m[len(m)-1][0]
|
||||
}
|
||||
|
||||
// deadline reads DeadlineEnv's value: when the caller stops waiting.
|
||||
func deadline(v string) (time.Time, bool) {
|
||||
ms, err := strconv.ParseInt(strings.TrimSpace(v), 10, 64)
|
||||
if err != nil || ms <= 0 {
|
||||
return time.Time{}, false
|
||||
}
|
||||
return time.UnixMilli(ms), true
|
||||
}
|
||||
|
||||
// late is why the run ends at its caller's deadline (DeadlineEnv), d
|
||||
// after it started: what Claude Code hadn't done by then, and what it
|
||||
// last drew.
|
||||
func (s *shim) late(d time.Duration) string {
|
||||
doing, _ := s.doing.Load().(string)
|
||||
if doing == "" {
|
||||
doing = "showed no prompt"
|
||||
}
|
||||
return fmt.Sprintf("Claude Code %s in the %s its caller waits for it: %s", doing, d.Round(100*time.Millisecond), s.lastScreen())
|
||||
}
|
||||
|
||||
var errUntrusted = errors.New(Untrusted + ", which only its user answers")
|
||||
|
||||
// signIn is what Claude Code's interactive mode shows where it is not
|
||||
@@ -533,6 +570,7 @@ func (s *shim) input(r io.Reader) error {
|
||||
return err
|
||||
}
|
||||
case "user":
|
||||
s.doing.Store("hadn't answered")
|
||||
pieces, err := s.userPieces(m.Message.Content)
|
||||
if err != nil {
|
||||
s.emit(map[string]any{"type": "result", "subtype": "error_during_execution", "is_error": true, "session_id": s.sid,
|
||||
@@ -566,6 +604,7 @@ var (
|
||||
// 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 {
|
||||
s.doing.Store("hadn't drawn " + name + "'s panel")
|
||||
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"})
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
@@ -148,6 +149,12 @@ func fakeClaude(args []string) {
|
||||
fmt.Print("something went wrong\n")
|
||||
os.Exit(3)
|
||||
}
|
||||
if os.Getenv("FAKE_STALL") == "1" {
|
||||
// drawn, but no prompt ever comes
|
||||
fmt.Print("\r\nStarting up…\r\n")
|
||||
time.Sleep(time.Minute)
|
||||
os.Exit(0)
|
||||
}
|
||||
if os.Getenv("FAKE_LOGIN") == "1" {
|
||||
// signed in for -p alone: the interactive mode asks how to sign in
|
||||
fmt.Print("\r\nSelect login method:\r\n\r\n ❯ 1. Claude account with subscription\r\n 2. Anthropic Console account\r\n")
|
||||
@@ -476,6 +483,13 @@ func TestDropLeft(t *testing.T) {
|
||||
// runEnds runs the shim in home, told "hello", until it
|
||||
// exits or answers: what it wrote, its stderr, and how it ended.
|
||||
func runEnds(t *testing.T, home string, env []string) (out, stderr string, err error) {
|
||||
t.Helper()
|
||||
b, _ := json.Marshal(map[string]any{"type": "user", "message": map[string]any{"role": "user", "content": "hello"}})
|
||||
return runEndsTold(t, home, env, string(b))
|
||||
}
|
||||
|
||||
// runEndsTold is runEnds told line, a stream-json line, for "hello".
|
||||
func runEndsTold(t *testing.T, home string, env []string, line string) (out, stderr string, err error) {
|
||||
t.Helper()
|
||||
exe, _ := os.Executable()
|
||||
cfg := filepath.Join(home, "claude")
|
||||
@@ -496,8 +510,7 @@ func runEnds(t *testing.T, home string, env []string) (out, stderr string, err e
|
||||
_ = cmd.Process.Kill()
|
||||
_ = cmd.Wait()
|
||||
})
|
||||
b, _ := json.Marshal(map[string]any{"type": "user", "message": map[string]any{"role": "user", "content": "hello"}})
|
||||
_, _ = stdin.Write(append(b, '\n'))
|
||||
_, _ = io.WriteString(stdin, line+"\n")
|
||||
done := make(chan string, 1)
|
||||
go func() {
|
||||
var all strings.Builder
|
||||
@@ -602,6 +615,40 @@ func TestShimGoesThroughOnboarding(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A one-off run's caller (a /usage read, a test's "hi") tells the helper
|
||||
// when it stops waiting (DeadlineEnv), and the helper ends then on its
|
||||
// own, saying what Claude Code hadn't done and what it last drew. Killed
|
||||
// at the caller's deadline instead, it said nothing, and the reading's
|
||||
// error was "exit status 1" (#4830, mydosu, Windows).
|
||||
func TestShimEndsAtItsCallersDeadline(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
name, line, why, screen string
|
||||
env []string
|
||||
}{
|
||||
{"no prompt", `{"type":"user","message":{"role":"user","content":"hello"}}`, "showed no prompt in the", "Starting up", []string{"FAKE_STALL=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")}},
|
||||
} {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
start := time.Now()
|
||||
by := start.Add(3 * time.Second).UnixMilli()
|
||||
out, stderr, err := runEndsTold(t, t.TempDir(), append(c.env, DeadlineEnv+"="+strconv.FormatInt(by, 10)), c.line)
|
||||
d := time.Since(start)
|
||||
if err == nil || strings.Contains(out, `"type":"result"`) {
|
||||
t.Fatalf("ended %v, wrote %q", err, out)
|
||||
}
|
||||
if !strings.Contains(stderr, "claude-tui: Claude Code "+c.why) || !strings.Contains(stderr, c.screen) {
|
||||
t.Fatalf("stderr %q", stderr)
|
||||
}
|
||||
// at the deadline, with room for a slow machine to start it,
|
||||
// and well before the helper's own waits (20s, 45s)
|
||||
if d < 2500*time.Millisecond || d > 15*time.Second {
|
||||
t.Fatalf("ended after %s, the deadline 3s", d)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestShimTrustsWhenTold(t *testing.T) {
|
||||
out := runShim(t, []string{"FAKE_TRUST=1", TrustEnv + "=1"}, append([]string{fakePath(t)}, pArgs...), []string{"hello"}, 3)
|
||||
if out[0]["subtype"] != "init" || out[1]["type"] != "assistant" {
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -63,3 +64,92 @@ cat > /dev/null
|
||||
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 {
|
||||
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)
|
||||
}
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
for _, f := range left {
|
||||
if _, err := os.Stat(f); !os.IsNotExist(err) {
|
||||
t.Errorf("the run's session %s was left", f)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,11 +5,14 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/claudetui"
|
||||
"github.com/yetone/magpie/internal/netproxy"
|
||||
@@ -87,22 +90,23 @@ func askClaudeTUI(ctx context.Context, binary claudeCLI, configDir, model string
|
||||
if _, why := claudeMachineWhy(binary); why != "" {
|
||||
return claudeTUIErr(why)
|
||||
}
|
||||
tmp, err := os.MkdirTemp("", "magpie-claude-")
|
||||
work, done, err := oneOffDir()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.RemoveAll(tmp)
|
||||
defer done()
|
||||
cmd, err := binary.tuiCommand(ctx, claudeTUIWarmArgs(model)...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cmd.Dir = tmp
|
||||
cmd.Dir = work
|
||||
env, err := binary.proxied(ctx, cleanClaudeEnv(os.Environ()))
|
||||
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, helperDeadline(ctx)...)
|
||||
cmd.Env = binary.tuiEnv(binary.env(binary.asRoot(env), configDir), configDir)
|
||||
stdin, err := cmd.StdinPipe()
|
||||
if err != nil {
|
||||
@@ -115,19 +119,14 @@ func askClaudeTUI(ctx context.Context, binary claudeCLI, configDir, model string
|
||||
var stderr bytes.Buffer
|
||||
cmd.Stdout, cmd.Stderr = out, &stderr
|
||||
runErr := runClaudeTree(ctx, cmd, "a Claude Code test on "+model)
|
||||
dropOneOff(binary, configDir, work, out.sid)
|
||||
if out.res != nil {
|
||||
if out.res.IsError {
|
||||
return errors.New("Claude Code: " + clip(out.res.Result))
|
||||
}
|
||||
return 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")
|
||||
return oneOffErr(ctx, stderr.String(), runErr)
|
||||
}
|
||||
|
||||
// resultLines reads the helper's stream-json for its first result, and
|
||||
@@ -136,6 +135,8 @@ type resultLines struct {
|
||||
buf []byte
|
||||
res *claudeRun
|
||||
done func()
|
||||
// sid is the session the helper said it runs (its init's session_id)
|
||||
sid string
|
||||
}
|
||||
|
||||
func (w *resultLines) Write(p []byte) (int, error) {
|
||||
@@ -149,9 +150,14 @@ func (w *resultLines) Write(p []byte) (int, error) {
|
||||
break
|
||||
}
|
||||
var r claudeRun
|
||||
if json.Unmarshal(w.buf[:i], &r) == nil && r.Type == "result" {
|
||||
w.res = &r
|
||||
w.done()
|
||||
if json.Unmarshal(w.buf[:i], &r) == nil {
|
||||
if r.SessionID != "" {
|
||||
w.sid = r.SessionID
|
||||
}
|
||||
if r.Type == "result" {
|
||||
w.res = &r
|
||||
w.done()
|
||||
}
|
||||
}
|
||||
w.buf = w.buf[i+1:]
|
||||
}
|
||||
@@ -235,22 +241,23 @@ func claudeUsageTUI(ctx context.Context, binary claudeCLI, configDir string) (st
|
||||
if _, why := claudeMachineWhy(binary); why != "" {
|
||||
return "", claudeTUIErr(why)
|
||||
}
|
||||
tmp, err := os.MkdirTemp("", "magpie-claude-")
|
||||
work, done, err := oneOffDir()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer os.RemoveAll(tmp)
|
||||
defer done()
|
||||
cmd, err := binary.tuiCommand(ctx, claudeTUIUsageArgs()...)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
cmd.Dir = tmp
|
||||
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, helperDeadline(ctx)...)
|
||||
cmd.Env = binary.tuiEnv(binary.env(binary.asRoot(env), configDir), configDir)
|
||||
stdin, err := cmd.StdinPipe()
|
||||
if err != nil {
|
||||
@@ -261,6 +268,7 @@ func claudeUsageTUI(ctx context.Context, binary claudeCLI, configDir string) (st
|
||||
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
|
||||
@@ -271,13 +279,68 @@ func claudeUsageTUI(ctx context.Context, binary claudeCLI, configDir string) (st
|
||||
}
|
||||
return out.res.Result, nil
|
||||
}
|
||||
if msg := strings.TrimSpace(stderr.String()); msg != "" {
|
||||
return "", errors.New("Claude Code: " + clip(msg))
|
||||
return "", oneOffErr(ctx, stderr.String(), runErr)
|
||||
}
|
||||
|
||||
// oneOffDir is the folder a one-off interactive run (a test, a /usage)
|
||||
// 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
|
||||
// run's own was asked again every time, and left one more trusted
|
||||
// project in the state file each time (#4830, mydosu: 67 of them). done
|
||||
// removes a folder of the run's own, made only when magpie's can't be
|
||||
// used.
|
||||
func oneOffDir() (dir string, done func(), err error) {
|
||||
if dir, err := claudeWorkDir(); err == nil {
|
||||
return dir, func() {}, nil
|
||||
}
|
||||
tmp, err := os.MkdirTemp("", "magpie-claude-")
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
return tmp, func() { _ = os.RemoveAll(tmp) }, nil
|
||||
}
|
||||
|
||||
// dropOneOff removes the session a one-off interactive run left in
|
||||
// magpie's folder, by its id (sid, "" when it told none): a test's "hi"
|
||||
// keeps its transcript there. A folder of the run's own goes whole.
|
||||
func dropOneOff(binary claudeCLI, configDir, work, sid string) {
|
||||
if binary.wsl != nil || sid == "" {
|
||||
return
|
||||
}
|
||||
removeSession(claudeSessions(configDir, work), sid)
|
||||
}
|
||||
|
||||
// oneOffMargin is how long before its caller's deadline a one-off
|
||||
// interactive run's helper ends on its own (claudetui.DeadlineEnv), for
|
||||
// what it says to be read before the run is killed.
|
||||
const oneOffMargin = 3 * time.Second
|
||||
|
||||
// helperDeadline tells the helper when ctx ends, oneOffMargin early (a
|
||||
// quarter of what is left, when that is less), nothing when it doesn't.
|
||||
func helperDeadline(ctx context.Context) []string {
|
||||
dl, ok := ctx.Deadline()
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
margin := min(oneOffMargin, time.Until(dl)/4)
|
||||
return []string{claudetui.DeadlineEnv + "=" + strconv.FormatInt(dl.Add(-margin).UnixMilli(), 10)}
|
||||
}
|
||||
|
||||
// oneOffErr is why a one-off interactive run ended with no result: what
|
||||
// its helper said, else that its caller stopped waiting, never only the
|
||||
// exit status its kill left (on Windows "exit status 1", #4830).
|
||||
func oneOffErr(ctx context.Context, stderr string, runErr error) error {
|
||||
if msg := strings.TrimSpace(stderr); msg != "" {
|
||||
return errors.New("Claude Code: " + clip(msg))
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return fmt.Errorf("Claude Code's interactive mode said nothing before magpie stopped waiting for it (%v)", ctx.Err())
|
||||
}
|
||||
if runErr != nil {
|
||||
return "", runErr
|
||||
return runErr
|
||||
}
|
||||
return "", errors.New("Claude Code ended with no answer")
|
||||
return errors.New("Claude Code ended with no answer")
|
||||
}
|
||||
|
||||
// runClaudeTree runs a one-off Claude Code (a test, a /usage) and ends,
|
||||
@@ -306,6 +369,8 @@ type claudeRun struct {
|
||||
Type string `json:"type"`
|
||||
IsError bool `json:"is_error"`
|
||||
Result string `json:"result"`
|
||||
// SessionID is the session the run said it is (stream-json's lines)
|
||||
SessionID string `json:"session_id"`
|
||||
}
|
||||
|
||||
// claudeResult reads the result from what claude -p --output-format json
|
||||
|
||||
@@ -13548,10 +13548,12 @@ const SIGN_IN_GONE = /sign-in has (expired|lapsed)|sign in again/i;
|
||||
function quotaError(err, q) {
|
||||
// first-run screens the helper can't pass (#4817)
|
||||
if (/^Claude Code: claude-tui: .{0,40}(stays on its first-run screens|shows its first-run notes)/.test(err)) return t("Finish Claude Code's first-run setup, then refresh. Run magpie claude-code to find its executable.");
|
||||
// the /usage helper's other reasons, on the card (#4830)
|
||||
const tui = /^Claude Code: claude-tui: (.+?)(?:: |$)/m.exec(err) || /^(Claude Code's interactive mode said nothing[^(]*?) \(/.exec(err);
|
||||
if (tui) return t("Allowance unavailable: {why}", { why: tui[1].slice(0, 160) });
|
||||
// signed in again in place from the row's Sign in again (blue12345655)
|
||||
if (/sign-in has expired/.test(err)) return t("Signed out — choose Sign in again on this account under Providers");
|
||||
// a Copilot account GitHub refused the token of (copilot_lapsed.go), as
|
||||
// its row says it, in English or already in the user's language
|
||||
// Copilot's refused token (copilot_lapsed.go), in either language
|
||||
const copilotLapsed = "GitHub refused this Copilot sign-in; sign in again";
|
||||
if (err === copilotLapsed || err === t(copilotLapsed)) return t(copilotLapsed);
|
||||
// an account whose sign-in its vendor revoked (signin_revoked.go, #1793)
|
||||
@@ -13562,12 +13564,10 @@ function quotaError(err, q) {
|
||||
if (/violation of Terms of Service/i.test(err)) return t("Google has suspended this account — hover for details");
|
||||
if (/access token is invalid or expired|didn't take the access token/.test(err)) return t("AiHubMix didn't take the access token — paste a new one in the provider's settings");
|
||||
if (/this key has no limit/.test(err)) return t("This key has no limit — add the account's access token in the provider's settings to see its balance");
|
||||
// a Volcengine or Tencent plan whose provider has no access key to read
|
||||
// it with (accessKeyCard, #1821): the card used to be left out unsaid
|
||||
// a Volcengine or Tencent plan with no access key (#1821)
|
||||
if (/^this plan's usage is read with the account's access key: give its SecretId/.test(err)) return t("This plan's usage needs the account's SecretId and SecretKey — give them in the provider's settings");
|
||||
if (/^this plan's usage is read with the account's access key/.test(err)) return t("This plan's usage needs the account's AccessKey ID and Secret — give them in the provider's settings");
|
||||
// ZCode with no plan left: nothing to spend, not a failed read (#1001);
|
||||
// the plugin's card names no way out. Whole sentence, so others pass.
|
||||
// ZCode with no plan left, not a failed read (#1001)
|
||||
if (/^this account has no GLM Coding Plan, and ZCode's Start Plan has ended or was never started$/.test(err)) return t("ZCode: no GLM Coding Plan, and no free Start Plan — subscribe to a GLM Coding Plan to use this account");
|
||||
// an OpenCode Go key's windows (planquota.go): only the subscribing
|
||||
// member's key reads them; said with the way out
|
||||
|
||||
@@ -101,6 +101,22 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
for (const text of Object.values(siblings)) assert.ok(text.includes(want), text);
|
||||
assert.equal(await page.evaluate(() => quotaError("network is unreachable")), await page.evaluate(() => t("Allowance unavailable")), "unrelated errors keep their classification");
|
||||
assert.equal(await page.evaluate(e => quotaError(e), olderError), want, "an older magpie's words are read too");
|
||||
// any other reason the helper gave, and a run that said none before
|
||||
// magpie stopped waiting, are said on the card, not "unavailable"
|
||||
// alone (#4830); the last screen after the reason stays for the
|
||||
// tooltip
|
||||
for (const [err, why] of [
|
||||
["Claude Code: claude-tui: Claude Code showed no prompt in the 16.9s its caller waits for it: Do you trust this folder? ❯ No, exit",
|
||||
"Claude Code showed no prompt in the 16.9s its caller waits for it"],
|
||||
["Claude Code: claude-tui: Claude Code asks whether to trust the folder, which only its user answers\nmagpie: Claude Code's interactive mode didn't run: Claude Code asks whether to trust the folder, which only its user answers",
|
||||
"Claude Code asks whether to trust the folder, which only its user answers"],
|
||||
["Claude Code's interactive mode said nothing before magpie stopped waiting for it (context deadline exceeded)",
|
||||
"Claude Code's interactive mode said nothing before magpie stopped waiting for it"],
|
||||
]) {
|
||||
const said = await page.evaluate(([e, w]) => [quotaError(e), t("Allowance unavailable: {why}", { why: w })], [err, why]);
|
||||
assert.equal(said[0], said[1], err);
|
||||
if (lang !== "en") assert.ok(!said[0].startsWith("Allowance unavailable"), said[0]);
|
||||
}
|
||||
|
||||
await page.waitForFunction(() => !quotaRefreshing.size);
|
||||
// Simulate the next read after the user completes setup. Another
|
||||
|
||||
Reference in New Issue
Block a user