diff --git a/docs/subsystems/claude-subscription-bridge.md b/docs/subsystems/claude-subscription-bridge.md index 95bc1fd44..594727e7d 100644 --- a/docs/subsystems/claude-subscription-bridge.md +++ b/docs/subsystems/claude-subscription-bridge.md @@ -85,6 +85,65 @@ is judged as any other. Without it the call was refused 401, never reached the run, and every turn with tool results found no run waiting and started a new Claude Code told the whole conversation (#1546). +## Claude Code's interactive mode (`claudePrintMode`) + +By default a run on macOS and Linux is Claude Code's interactive mode, not +`claude -p`. Anthropic counts a request by its entrypoint, and a `-p` +run's `sdk-cli` costs about twice the plan's allowance of the interactive +mode's `cli` (anthropics/claude-code#97074). The run is the real +interactive Claude Code: nothing sets `CLAUDE_CODE_ENTRYPOINT`. + +The bridge starts `magpie claude-tui-helper ` +(`internal/claudetui`) in place of `claude` when `claudeTUI` says so, and +talks to it as it talks to `-p`: stream-json in and out. The helper: + +- turns the arguments into the interactive mode's (`interactiveArgs`): + `-p`, the stream-json formats, `--verbose`, + `--include-partial-messages`, `--thinking-display`, + `--dangerously-skip-permissions` and `--no-session-persistence` go; + `--permission-mode default --allowedTools mcp__magpie[,WebSearch] + --no-chrome` come. Permissions are not skipped: only magpie's MCP tools + (and the web search `-p` was given) are allowed, and nothing else is + offered (`--tools ""`). A new session is given `--session-id`; +- starts Claude Code in a pseudo-terminal of its own (200x50, its own + session), no tmux, and answers what it asks of the terminal; +- pastes each user message into the prompt (bracketed paste) and presses + Enter. A message opening with `/`, `!`, `#` or `&` is pasted after a + line break, so it is words, not a command (`pasteable`); +- tails `/projects/*/.jsonl` and tells each + row as `-p` would (`translator`): assistant messages whole (no partial + stream), a tool's result, a `` API error as the turn's error + result with its `rate_limit_info`, and `turn_duration` as the result. + +The user's own `~/.claude.json` and `~/.claude` are never written. Claude +Code asks whether to trust a folder it has not run in; the helper answers +yes only when the bridge sets `MAGPIE_CLAUDE_TUI_TRUST=1`, which it does +for magpie's own working folder or a saved account's config directory, +both magpie's. In the caller's folder under the account Claude Code is +signed in to, the question is the user's: a folder the user has not +trusted makes that run `-p`. + +A run is `-p`, as before, when (`claudeTUI`): + +- Settings › Models › Replies › Claude Code's interactive mode is Off + (`claudePrintMode`); +- it is Windows, or Claude Code in WSL; +- the request has safeguards, client cache marks, a JSON schema or images, + or a prompt over 400KB (`tuiPromptMost`), which a paste can't carry as + `-p` does. + +A turn the interactive mode can't take ends the run, and the next starts +anew: a turn with images, one that takes earlier turns back, an effort +change. A run given up on (`letGo`) is not taken back, since the +interactive mode can't answer a control request to stop a turn. + +If the interactive Claude Code doesn't start or show its prompt within 45 +seconds, the helper becomes `claude -p` with the same arguments +(`printMode`, `exec` on the same pid, its input still unread), so the +turn is answered all the same, and it writes +`/magpie/claude-tui-broken`: for 30 minutes after, every run goes +to `-p` at once. A folder not trusted goes to `-p` without the mark. + ## Why turns go on in one run A run started anew is told the whole conversation in one user message @@ -808,6 +867,8 @@ and the next turn starts a run in the new one, as after any restart. ```sh go test -tags nogui ./internal/gateway/ -run '^TestClaudeClientCache' -count=1 go test -tags nogui ./internal/gateway/ -run '^TestClaudeLeanPrompt' -count=1 +go test -tags nogui ./internal/gateway/ -run '^TestClaudeTUIChosen$' -count=1 +go test ./internal/claudetui/ -count=1 go test -tags nogui ./internal/claudecode/ -count=1 go test -tags nogui ./internal/gateway/ -run '^TestClaudeCodeGivenTheBridgeForASOCKSProxy$' -count=1 go test -tags nogui ./internal/provider/ -run '^TestClaudeSignInBridgesASOCKSProxy$' -count=1 diff --git a/internal/claudetui/command.go b/internal/claudetui/command.go new file mode 100644 index 000000000..6744f4678 --- /dev/null +++ b/internal/claudetui/command.go @@ -0,0 +1,11 @@ +package claudetui + +// Command is the hidden subcommand that runs it. +const Command = "claude-tui-helper" + +// TrustEnv, "1", has the shim tell Claude Code yes when it asks whether +// to trust the folder it runs in: the bridge sets it for magpie's own +// folder, and for a caller's in an account folder of magpie's, whose +// Claude Code no one else runs. Otherwise the question is the user's to +// answer in their own Claude Code, and the run is -p. +const TrustEnv = "MAGPIE_CLAUDE_TUI_TRUST" diff --git a/internal/claudetui/pty_darwin.go b/internal/claudetui/pty_darwin.go new file mode 100644 index 000000000..096d157c0 --- /dev/null +++ b/internal/claudetui/pty_darwin.go @@ -0,0 +1,40 @@ +package claudetui + +import ( + "os" + "syscall" + "unsafe" + + "golang.org/x/sys/unix" +) + +// openPTY opens a pseudo-terminal: its master, and the name of its slave. +func openPTY() (*os.File, string, error) { + m, err := os.OpenFile("/dev/ptmx", os.O_RDWR|syscall.O_NOCTTY, 0) + if err != nil { + return nil, "", err + } + fd := int(m.Fd()) + if err := unix.IoctlSetInt(fd, unix.TIOCPTYGRANT, 0); err != nil { + m.Close() + return nil, "", err + } + if err := unix.IoctlSetInt(fd, unix.TIOCPTYUNLK, 0); err != nil { + m.Close() + return nil, "", err + } + var name [128]byte + if _, _, e := syscall.Syscall(syscall.SYS_IOCTL, uintptr(fd), uintptr(unix.TIOCPTYGNAME), uintptr(unsafe.Pointer(&name[0]))); e != 0 { + m.Close() + return nil, "", e + } + n := 0 + for n < len(name) && name[n] != 0 { + n++ + } + return m, string(name[:n]), nil +} + +// the requests that read and set a terminal's modes (the tests' fake +// Claude Code sets its own raw, as the real one does) +const ioctlGetTermios, ioctlSetTermios = unix.TIOCGETA, unix.TIOCSETA diff --git a/internal/claudetui/pty_linux.go b/internal/claudetui/pty_linux.go new file mode 100644 index 000000000..7a4f6846a --- /dev/null +++ b/internal/claudetui/pty_linux.go @@ -0,0 +1,32 @@ +package claudetui + +import ( + "os" + "strconv" + "syscall" + + "golang.org/x/sys/unix" +) + +// openPTY opens a pseudo-terminal: its master, and the name of its slave. +func openPTY() (*os.File, string, error) { + m, err := os.OpenFile("/dev/ptmx", os.O_RDWR|syscall.O_NOCTTY, 0) + if err != nil { + return nil, "", err + } + fd := int(m.Fd()) + if err := unix.IoctlSetPointerInt(fd, unix.TIOCSPTLCK, 0); err != nil { + m.Close() + return nil, "", err + } + n, err := unix.IoctlGetInt(fd, unix.TIOCGPTN) + if err != nil { + m.Close() + return nil, "", err + } + return m, "/dev/pts/" + strconv.Itoa(n), nil +} + +// the requests that read and set a terminal's modes (the tests' fake +// Claude Code sets its own raw, as the real one does) +const ioctlGetTermios, ioctlSetTermios = unix.TCGETS, unix.TCSETS diff --git a/internal/claudetui/transcript.go b/internal/claudetui/transcript.go new file mode 100644 index 000000000..82a9f5afd --- /dev/null +++ b/internal/claudetui/transcript.go @@ -0,0 +1,137 @@ +package claudetui + +import ( + "encoding/json" +) + +// emitter is where a translator's lines go. +type emitter interface { + emit(v any) + // a message the user sent reached the transcript, and a turn ended + sawRow() + turnOver() +} + +// translator tells the bridge, as `claude -p`'s stream-json, what the +// session's transcript says. Claude Code writes a row a content block of an +// assistant message, under the message's id, as -p tells one not streamed: +// each goes on as it is. An API error is a message whose text +// is the error, and a turn's end a turn_duration row: they become the +// turn's result, as -p ends a turn. +type translator struct { + out emitter + // the turn failed: its row's result is told, and the + // turn_duration after it says nothing more + failed bool +} + +func newTranslator(out emitter) *translator { return &translator{out: out} } + +// quiet and flush are for a translator that holds rows back; this one +// tells each as it comes. +func (t *translator) quiet() {} +func (t *translator) flush() {} + +func (t *translator) row(b []byte) { + var r struct { + Type string `json:"type"` + Subtype string `json:"subtype"` + IsSidechain bool `json:"isSidechain"` + IsMeta bool `json:"isMeta"` + RequestID string `json:"requestId"` + Error json.RawMessage `json:"error"` + IsAPIError bool `json:"isApiErrorMessage"` + APIStatus int `json:"apiErrorStatus"` + ToolUseResult json.RawMessage `json:"toolUseResult"` + Operation string `json:"operation"` + APIParams struct { + RateLimitInfo json.RawMessage `json:"rate_limit_info"` + } `json:"apiErrorParams"` + Message json.RawMessage `json:"message"` + } + if json.Unmarshal(b, &r) != nil || r.IsSidechain { + return + } + switch r.Type { + case "queue-operation": + // a message sent mid-turn waits in Claude Code's queue + if r.Operation == "enqueue" { + t.out.sawRow() + } + case "user": + if !r.IsMeta && isPrompt(r.Message) { + t.failed = false + t.out.sawRow() + } + if len(r.ToolUseResult) > 0 && r.ToolUseResult[0] == '{' { + t.out.emit(map[string]any{"type": "user", "tool_use_result": r.ToolUseResult}) + } + case "assistant": + var m struct { + Model string `json:"model"` + Content []struct { + Type string `json:"type"` + Text string `json:"text"` + } `json:"content"` + } + _ = json.Unmarshal(r.Message, &m) + line := map[string]any{"type": "assistant", "message": r.Message} + if r.RequestID != "" { + line["request_id"] = r.RequestID + } + if len(r.Error) > 0 { + line["error"] = r.Error + } + t.out.emit(line) + if m.Model != "" || !r.IsAPIError { + return + } + text := "" + for _, c := range m.Content { + if c.Type == "text" { + text += c.Text + } + } + if len(r.APIParams.RateLimitInfo) > 0 && string(r.APIParams.RateLimitInfo) != "null" { + t.out.emit(map[string]any{"type": "rate_limit_event", "rate_limit_info": r.APIParams.RateLimitInfo}) + } + t.failed = true + t.out.turnOver() + t.out.emit(map[string]any{"type": "result", "subtype": "error_during_execution", "is_error": true, + "result": text, "api_error_status": r.APIStatus}) + case "system": + if r.Subtype == "turn_duration" && !t.failed { + t.out.emit(map[string]any{"type": "result", "subtype": "success", "is_error": false}) + } + if r.Subtype == "turn_duration" { + t.failed = false + t.out.turnOver() + } + } +} + +// isPrompt says whether a user row's message is one typed in: text, not a +// tool's result. +func isPrompt(raw json.RawMessage) bool { + var m struct { + Content json.RawMessage `json:"content"` + } + if json.Unmarshal(raw, &m) != nil || len(m.Content) == 0 { + return false + } + if m.Content[0] == '"' { + return true + } + var blocks []struct { + Type string `json:"type"` + } + if json.Unmarshal(m.Content, &blocks) != nil { + return false + } + for _, b := range blocks { + if b.Type == "tool_result" { + return false + } + } + return len(blocks) > 0 +} diff --git a/internal/claudetui/tui.go b/internal/claudetui/tui.go new file mode 100644 index 000000000..a9d5cde2c --- /dev/null +++ b/internal/claudetui/tui.go @@ -0,0 +1,678 @@ +//go:build darwin || linux + +// Package claudetui runs Claude Code's interactive mode for magpie's Claude +// subscription bridge, as `magpie claude-tui-helper`: the bridge talks to +// it as it talks to `claude -p --input-format stream-json --output-format +// stream-json`, and it runs the real interactive Claude Code in a +// pseudo-terminal of its own. A user message is pasted into Claude Code's +// prompt and sent with Enter, as a person does; what Claude Code answers is +// read from the session's transcript, which Claude Code writes as it goes, +// and told back as stream-json, one whole message at a time. +// +// Anthropic counts a request by its entrypoint: the interactive mode's +// "cli", where -p's is "sdk-cli", and an sdk-cli request costs about +// twice as much of the plan's allowance (anthropics/claude-code#97074). +// The run is the real interactive Claude Code: nothing sets its +// entrypoint. +package claudetui + +import ( + "bufio" + "bytes" + "crypto/rand" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "os/exec" + "os/signal" + "path/filepath" + "regexp" + "strings" + "sync" + "syscall" + "time" + + "golang.org/x/sys/unix" +) + +// how long Claude Code may take to show its prompt, a pasted message to +// show in it, and a sent one to reach its transcript +var ( + readyWait = 45 * time.Second + pasteWait = 10 * time.Second + sentWait = 3 * time.Second + // rows of one message are written together: a message is whole once + // none of its rows came for this long, or anything else did + messageQuiet = 150 * time.Millisecond +) + +type shim struct { + outMu sync.Mutex + out io.Writer + + pty *os.File + cmd *exec.Cmd + sid string + // projects is Claude Code's projects folder, where it keeps the + // session's transcript (//.jsonl) + projects string + + screenMu sync.Mutex + screen []byte + changed chan struct{} + + // rows ticks when a user message (or one queued mid-turn) reaches the + // transcript: a pasted message was sent + rowsMu sync.Mutex + rows int + rowsCh chan struct{} + // a turn is going: from a message's row to the turn's end + busy bool + + exited chan struct{} + exit error +} + +// Run runs Claude Code at path, args being the bridge's `claude -p` ones, +// with stream-json on standard input and output: interactive, with the +// same model, tools and settings (interactiveArgs). One that doesn't come +// up becomes the -p run it stands for (printMode), reading the input +// still unread. +func Run(args []string) error { + if len(args) < 1 { + return errors.New("usage: magpie " + Command + " [claude -p's arguments]") + } + path, pargs := args[0], args[1:] + if since, ok := brokenSince(); ok { + fmt.Fprintf(os.Stderr, "claude-tui: Claude Code's interactive mode failed to start %s ago; this run is -p\n", time.Since(since).Round(time.Second)) + return printMode(path, pargs) + } + args = interactiveArgs(pargs) + s := &shim{out: os.Stdout, changed: make(chan struct{}, 1), rowsCh: make(chan struct{}, 1), exited: make(chan struct{})} + resume := "" + for i, a := range args { + if a == "--resume" && i+1 < len(args) { + resume = args[i+1] + } + } + if resume != "" { + s.sid = resume + } else { + s.sid = newUUID() + args = append(args, "--session-id", s.sid) + } + s.projects = filepath.Join(configDir(), "projects") + // a resumed session's file has its earlier turns: only what is + // written after the start is read + var from int64 + if p := s.transcript(); p != "" { + if fi, err := os.Stat(p); err == nil { + from = fi.Size() + } + } + if err := s.start(path, args); err != nil { + markBroken() + fmt.Fprintf(os.Stderr, "claude-tui: Claude Code's interactive mode could not start (%v); this run is -p\n", err) + return printMode(path, pargs) + } + defer s.stop() + sigs := make(chan os.Signal, 1) + signal.Notify(sigs, syscall.SIGTERM, syscall.SIGINT, syscall.SIGHUP) + go func() { + <-sigs + s.stop() + os.Exit(1) + }() + if err := s.ready(); err != nil { + if !errors.Is(err, errUntrusted) { + markBroken() + } + signal.Reset() + s.stop() + fmt.Fprintf(os.Stderr, "claude-tui: %v; this run is -p\n", err) + return printMode(path, pargs) + } + s.emit(map[string]any{"type": "system", "subtype": "init", "session_id": s.sid}) + go s.tail(from) + return s.input(os.Stdin) +} + +// configDir is the folder Claude Code keeps its state in. +func configDir() string { + if d := os.Getenv("CLAUDE_CONFIG_DIR"); d != "" { + return d + } + home, _ := os.UserHomeDir() + return filepath.Join(home, ".claude") +} + +// childEnv is the environment for Claude Code: the shim's, without what a +// Claude Code above it marks its own children with (one started from a +// Claude Code session keeps no transcript, "inherited +// CLAUDE_CODE_CHILD_SESSION marker"), in a terminal it can draw in. +func childEnv() []string { + var env []string + for _, e := range os.Environ() { + k, _, _ := strings.Cut(e, "=") + switch { + case k == "CLAUDECODE", k == "CLAUDE_CODE_ENTRYPOINT", k == "CLAUDE_CODE_CHILD_SESSION", + k == "CLAUDE_CODE_SESSION_ID", k == "CLAUDE_CODE_SESSION_ATTENDED", k == "CLAUDE_CODE_EXECPATH", + k == "CLAUDE_PID", k == "CLAUDE_EFFORT", k == "TERM", k == "COLUMNS", k == "LINES", + strings.HasPrefix(k, "CLAUDE_CODE_MESSAGING_"): + continue + } + env = append(env, e) + } + return append(env, "TERM=xterm-256color") +} + +func (s *shim) start(path string, args []string) error { + m, name, err := openPTY() + if err != nil { + return err + } + tty, err := os.OpenFile(name, os.O_RDWR|syscall.O_NOCTTY, 0) + if err != nil { + m.Close() + return err + } + // wide, so a line of Claude Code's screen is a line + _ = unix.IoctlSetWinsize(int(tty.Fd()), unix.TIOCSWINSZ, &unix.Winsize{Row: 50, Col: 200}) + cmd := exec.Command(path, args...) + cmd.Env = childEnv() + cmd.Stdin, cmd.Stdout, cmd.Stderr = tty, tty, tty + // its own session, the terminal its controlling one: the shim ending + // closes the terminal, and Claude Code is hung up on with it + cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true, Setctty: true} + if err := cmd.Start(); err != nil { + m.Close() + tty.Close() + return err + } + tty.Close() + s.pty, s.cmd = m, cmd + go func() { + err := cmd.Wait() + s.exit = err + close(s.exited) + }() + go s.read() + return nil +} + +// stop ends Claude Code: asked, then made to. +func (s *shim) stop() { + if s.cmd == nil || s.cmd.Process == nil { + return + } + select { + case <-s.exited: + return + default: + } + _ = s.cmd.Process.Signal(syscall.SIGTERM) + select { + case <-s.exited: + case <-time.After(3 * time.Second): + _ = syscall.Kill(-s.cmd.Process.Pid, syscall.SIGKILL) + } +} + +// read keeps the tail of what Claude Code draws, and answers what it asks +// of the terminal: where the cursor is, and what terminal it is. +func (s *shim) read() { + buf := make([]byte, 64<<10) + for { + n, err := s.pty.Read(buf) + if n > 0 { + d := buf[:n] + if bytes.Contains(d, []byte("\x1b[6n")) { + _, _ = s.pty.Write([]byte("\x1b[1;1R")) + } + if bytes.Contains(d, []byte("\x1b[c")) || bytes.Contains(d, []byte("\x1b[0c")) { + _, _ = s.pty.Write([]byte("\x1b[?62;c")) + } + s.screenMu.Lock() + s.screen = append(s.screen, d...) + if len(s.screen) > 256<<10 { + s.screen = append([]byte(nil), s.screen[len(s.screen)-128<<10:]...) + } + s.screenMu.Unlock() + select { + case s.changed <- struct{}{}: + default: + } + } + if err != nil { + return + } + } +} + +var ansi = regexp.MustCompile(`\x1b\[[0-9;?<>=]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[P^_][^\x1b]*\x1b\\|\x1b.`) + +// plain is what Claude Code drew since the screen was last cleared +// (clearScreen), its escapes taken out. +func (s *shim) plain() string { + s.screenMu.Lock() + b := string(s.screen) + s.screenMu.Unlock() + return ansi.ReplaceAllString(b, " ") +} + +func (s *shim) clearScreen() { + s.screenMu.Lock() + s.screen = s.screen[:0] + s.screenMu.Unlock() +} + +// 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()), " ") + if len(p) > 600 { + p = p[len(p)-600:] + } + return p +} + +var ( + trustNo = regexp.MustCompile(`❯\s*No,\s*exit`) + trustYes = regexp.MustCompile(`❯\s*Yes,\s*I trust`) +) + +var errUntrusted = errors.New("Claude Code asks whether to trust the folder, which only its user answers") + +// ready waits for Claude Code's prompt. Asked whether to trust the folder +// it runs in, it is told yes, as a person would, when TrustEnv says so. +func (s *shim) ready() error { + deadline := time.After(readyWait) + answered := 0 + for { + p := s.plain() + switch { + case strings.Contains(p, "trust this folder") && os.Getenv(TrustEnv) != "1": + return errUntrusted + case strings.Contains(p, "trust this folder") && answered < 3: + keys := "" + switch { + case trustNo.MatchString(p): + keys = "\x1b[B" + case trustYes.MatchString(p): + default: + goto wait + } + answered++ + s.clearScreen() + if keys != "" { + _, _ = s.pty.WriteString(keys) + time.Sleep(300 * time.Millisecond) + } + _, _ = s.pty.WriteString("\r") + case strings.Contains(p, "keep browser tools off"): + // Claude in Chrome found: kept off, as the bridge runs it + // --no-chrome + s.clearScreen() + _, _ = s.pty.WriteString("\x1b") + case strings.Contains(p, "Choose the text style"): + s.clearScreen() + _, _ = s.pty.WriteString("\r") + case strings.Contains(p, "❯ "): + // drawn: a moment for its input to be listened to + time.Sleep(300 * time.Millisecond) + return nil + } + wait: + select { + case <-s.changed: + case <-time.After(200 * time.Millisecond): + case <-s.exited: + return fmt.Errorf("Claude Code ended before it showed its prompt (%v): %s", s.exit, s.lastScreen()) + case <-deadline: + return fmt.Errorf("Claude Code showed no prompt in %s: %s", readyWait, s.lastScreen()) + } + } +} + +func (s *shim) emit(v any) { + b, _ := json.Marshal(v) + s.outMu.Lock() + defer s.outMu.Unlock() + _, _ = s.out.Write(append(b, '\n')) +} + +// input reads the bridge's stream-json: user messages, sent to Claude Code, +// and control requests, of which interactive mode takes none but initialize. +func (s *shim) input(r io.Reader) error { + sc := bufio.NewScanner(r) + sc.Buffer(make([]byte, 64<<10), 64<<20) + for sc.Scan() { + var m struct { + Type string `json:"type"` + UUID string `json:"uuid"` + RequestID string `json:"request_id"` + Request struct { + Subtype string `json:"subtype"` + } `json:"request"` + Message struct { + Content json.RawMessage `json:"content"` + } `json:"message"` + } + if json.Unmarshal(sc.Bytes(), &m) != nil { + continue + } + switch m.Type { + case "control_request": + resp := map[string]any{"subtype": "success", "request_id": m.RequestID, "response": map[string]any{}} + if m.Request.Subtype != "initialize" { + resp = map[string]any{"subtype": "error", "request_id": m.RequestID, + "error": "Claude Code's interactive mode takes no " + m.Request.Subtype + " request"} + } + s.emit(map[string]any{"type": "control_response", "response": resp}) + case "user": + text, ok := userText(m.Message.Content) + if !ok { + s.emit(map[string]any{"type": "result", "subtype": "error_during_execution", "is_error": true, "session_id": s.sid, + "result": "an image can't be pasted into Claude Code's interactive mode"}) + continue + } + if err := s.send(text); err != nil { + return err + } + if m.UUID != "" { + s.emit(map[string]any{"type": "command_lifecycle", "command_uuid": m.UUID, "state": "queued"}) + } + } + } + return sc.Err() +} + +// userText is a user message's text, its blocks one after another; false +// for one with anything but text. +func userText(raw json.RawMessage) (string, bool) { + var s string + if json.Unmarshal(raw, &s) == nil { + return s, true + } + var blocks []struct { + Type string `json:"type"` + Text string `json:"text"` + } + if json.Unmarshal(raw, &blocks) != nil { + return "", false + } + var b strings.Builder + for _, bl := range blocks { + if bl.Type != "text" { + return "", false + } + if bl.Text == "" { + continue + } + if b.Len() > 0 { + b.WriteString("\n\n") + } + b.WriteString(bl.Text) + } + return b.String(), true +} + +// pasteable is text as a paste can carry it: no escape that would end the +// paste early, nor other control characters, its lines ended by \n; and +// not opening with what Claude Code's prompt takes as a command (/) or a +// shell line (!), a memory (#) or a background task (&). busy is for a +// message sent while a turn is going, which Claude Code queues. +func pasteable(text string, busy bool) string { + text = strings.ReplaceAll(text, "\r\n", "\n") + text = strings.Map(func(r rune) rune { + switch { + case r == '\r': + return '\n' + case r == '\n', r == '\t': + return r + case r < 0x20, r == 0x7f: + return -1 + } + return r + }, text) + // After a line break the prompt takes it as words: a space before it + // is trimmed, and a zero-width one taken out of the paste. Claude Code + // trims a queued message, though, and runs one opening with / as a + // command even so, or drops it: that one is marked as the user's + // words, as the bridge marks them after a tool's result. + if t := strings.TrimLeft(text, " \t\n"); t != "" && strings.ContainsRune("/!#&", rune(t[0])) { + if busy { + text = userMark + t + } else { + text = "\n" + t + } + } + return text +} + +// send pastes text into Claude Code's prompt and presses Enter, again +// while the message hasn't reached the transcript: an Enter that lands +// while the paste is still being taken in is part of it. +func (s *shim) send(text string) error { + s.rowsMu.Lock() + before, busy := s.rows, s.busy + s.rowsMu.Unlock() + text = pasteable(text, busy) + if strings.TrimSpace(text) == "" { + text = "." + } + s.clearScreen() + if _, err := s.pty.WriteString("\x1b[200~" + text + "\x1b[201~"); err != nil { + return err + } + // shown in the prompt: its last words, or Claude Code's "[Pasted text" + // for a long one + tail := strings.TrimSpace(text) + if i := strings.LastIndexByte(tail, '\n'); i >= 0 { + tail = strings.TrimSpace(tail[i+1:]) + } + if r := []rune(tail); len(r) > 16 { + tail = string(r[len(r)-16:]) + } + shownBy := time.After(pasteWait) +shown: + for { + p := s.plain() + if strings.Contains(p, "Pasted text") || tail != "" && strings.Contains(strings.Join(strings.Fields(p), " "), strings.Join(strings.Fields(tail), " ")) { + break + } + select { + case <-s.changed: + case <-time.After(100 * time.Millisecond): + case <-shownBy: + break shown + case <-s.exited: + return fmt.Errorf("Claude Code ended (%v): %s", s.exit, s.lastScreen()) + } + } + time.Sleep(150 * time.Millisecond) + for try := 0; try < 4; try++ { + if _, err := s.pty.WriteString("\r"); err != nil { + return err + } + by := time.After(sentWait) + for { + s.rowsMu.Lock() + sent := s.rows > before + s.rowsMu.Unlock() + if sent { + return nil + } + select { + case <-s.rowsCh: + continue + case <-by: + case <-s.exited: + return fmt.Errorf("Claude Code ended (%v): %s", s.exit, s.lastScreen()) + } + break + } + } + return fmt.Errorf("Claude Code did not take the message: %s", s.lastScreen()) +} + +// transcript is the session's transcript, "" before Claude Code writes it. +func (s *shim) transcript() string { + m, _ := filepath.Glob(filepath.Join(s.projects, "*", s.sid+".jsonl")) + if len(m) == 0 { + return "" + } + return m[0] +} + +// userMark is what the bridge marks the user's words with after a tool's +// result (renderParts). +const userMark = "[user message]\n" + +func (s *shim) sawRow() { + s.rowsMu.Lock() + s.rows++ + s.busy = true + s.rowsMu.Unlock() + select { + case s.rowsCh <- struct{}{}: + default: + } +} + +// tail reads the transcript from offset from on, as Claude Code writes it, +// and tells the bridge what it says. +func (s *shim) tail(from int64) { + var path string + for path == "" { + if path = s.transcript(); path == "" { + select { + case <-s.exited: + return + case <-time.After(100 * time.Millisecond): + } + } + } + f, err := os.Open(path) + if err != nil { + return + } + defer f.Close() + if _, err := f.Seek(from, io.SeekStart); err != nil { + return + } + t := newTranslator(s) + rd := bufio.NewReaderSize(f, 1<<20) + var part []byte + for { + line, err := rd.ReadBytes('\n') + if len(line) > 0 { + part = append(part, line...) + if part[len(part)-1] == '\n' { + t.row(part) + part = nil + } + continue + } + if err != nil && err != io.EOF { + return + } + t.quiet() + select { + case <-s.exited: + // what it wrote last + if line, _ := rd.ReadBytes('\n'); len(line) > 0 { + t.row(append(part, line...)) + } + t.flush() + return + case <-time.After(50 * time.Millisecond): + } + } +} + +func (s *shim) turnOver() { + s.rowsMu.Lock() + s.busy = false + s.rowsMu.Unlock() +} + +func newUUID() string { + var b [16]byte + _, _ = rand.Read(b[:]) + b[6] = b[6]&0x0f | 0x40 + b[8] = b[8]&0x3f | 0x80 + return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:]) +} + +// interactiveArgs are `claude -p` arguments made the interactive mode's: +// the same model, tools, MCP servers, settings, effort, system prompt and +// session, without what only -p takes; its permission prompts kept, and +// magpie's MCP tools (and the web search -p was given) allowed without +// one, where -p skipped them all. +func interactiveArgs(pargs []string) []string { + var out []string + allowed := []string{"mcp__magpie"} + for i := 0; i < len(pargs); i++ { + a := pargs[i] + switch a { + case "-p", "--print", "--verbose", "--include-partial-messages", "--dangerously-skip-permissions", + "--no-session-persistence", "--replay-user-messages": + continue + case "--output-format", "--input-format", "--thinking-display", "--json-schema", "--permission-mode": + i++ + continue + case "--tools": + if i+1 < len(pargs) { + for _, t := range strings.FieldsFunc(pargs[i+1], func(r rune) bool { return r == ',' || r == ' ' }) { + allowed = append(allowed, t) + } + } + } + out = append(out, a) + } + return append(out, "--permission-mode", "default", "--allowedTools", strings.Join(allowed, ","), "--no-chrome") +} + +// printMode becomes Claude Code at path, run with the -p arguments pargs: +// the same process, so the bridge's input, output and process tree go on +// as they were. +func printMode(path string, pargs []string) error { + return unix.Exec(path, append([]string{path}, pargs...), os.Environ()) +} + +// broken is where a failed start is kept: for brokenFor after it, runs go +// straight to -p, rather than each waiting out readyWait. +func broken() string { + dir, err := os.UserCacheDir() + if err != nil { + return "" + } + return filepath.Join(dir, "magpie", "claude-tui-broken") +} + +const brokenFor = 30 * time.Minute + +func brokenSince() (time.Time, bool) { + p := broken() + if p == "" { + return time.Time{}, false + } + fi, err := os.Stat(p) + if err != nil || time.Since(fi.ModTime()) > brokenFor { + return time.Time{}, false + } + return fi.ModTime(), true +} + +func markBroken() { + p := broken() + if p == "" { + return + } + _ = os.MkdirAll(filepath.Dir(p), 0o700) + _ = os.WriteFile(p, nil, 0o600) + now := time.Now() + _ = os.Chtimes(p, now, now) +} diff --git a/internal/claudetui/tui_other.go b/internal/claudetui/tui_other.go new file mode 100644 index 000000000..570a992bc --- /dev/null +++ b/internal/claudetui/tui_other.go @@ -0,0 +1,11 @@ +//go:build !darwin && !linux + +package claudetui + +import "errors" + +// Run has no pseudo-terminal to run Claude Code in here: the bridge runs +// `claude -p` on this system. +func Run(args []string) error { + return errors.New("Claude Code's interactive mode isn't run by magpie on this system") +} diff --git a/internal/claudetui/tui_test.go b/internal/claudetui/tui_test.go new file mode 100644 index 000000000..60bb7e96a --- /dev/null +++ b/internal/claudetui/tui_test.go @@ -0,0 +1,303 @@ +//go:build darwin || linux + +package claudetui + +import ( + "bufio" + "encoding/json" + "fmt" + "io" + "os" + "os/exec" + "path/filepath" + "slices" + "strings" + "testing" + "time" + + "golang.org/x/sys/unix" +) + +// The test binary is also the shim (MAGPIE_TUI_TEST=shim) and a fake +// Claude Code (MAGPIE_TUI_TEST=claude): interactive, it shows a prompt, +// writes each line typed into its transcript as a turn answered "echo: +// "; with -p it answers each stream-json line with a -p result. +func TestMain(m *testing.M) { + switch os.Getenv("MAGPIE_TUI_TEST") { + case "shim": + if err := Run(os.Args[1:]); err != nil { + fmt.Fprintln(os.Stderr, err) + os.Exit(1) + } + os.Exit(0) + case "claude": + fakeClaude(os.Args[1:]) + os.Exit(0) + } + os.Exit(m.Run()) +} + +func fakeClaude(args []string) { + if slices.Contains(args, "-p") { + sc := bufio.NewScanner(os.Stdin) + for sc.Scan() { + fmt.Printf(`{"type":"result","subtype":"success","is_error":false,"result":"print mode"}` + "\n") + } + return + } + if os.Getenv("FAKE_FAIL") == "1" { + fmt.Print("something went wrong\n") + os.Exit(3) + } + sid := "" + if i := slices.Index(args, "--session-id"); i >= 0 { + sid = args[i+1] + } + dir := filepath.Join(os.Getenv("CLAUDE_CONFIG_DIR"), "projects", "work") + _ = os.MkdirAll(dir, 0o700) + if os.Getenv("FAKE_TRUST") == "1" { + fmt.Print("Do you trust this folder?\r\n ❯ Yes, I trust this folder\r\n No, exit\r\n") + r := bufio.NewReader(os.Stdin) + if _, err := r.ReadString('\n'); err != nil { + return + } + } + // what it was started with, for the test to read + _ = os.WriteFile(filepath.Join(os.Getenv("CLAUDE_CONFIG_DIR"), "args"), []byte(strings.Join(args, "\n")), 0o600) + // raw, as Claude Code's terminal is: a paste is taken whole, and Enter + // outside one sends it + if tio, err := unix.IoctlGetTermios(0, ioctlGetTermios); err == nil { + tio.Lflag &^= unix.ECHO | unix.ICANON + tio.Iflag &^= unix.ICRNL + _ = unix.IoctlSetTermios(0, ioctlSetTermios, tio) + } + fmt.Print("\r\n❯ ") + r := bufio.NewReader(os.Stdin) + var typed strings.Builder + pasting := false + for { + c, err := r.ReadByte() + if err != nil { + return + } + switch { + case c == 0x1b: + seq := make([]byte, 5) + if _, err := io.ReadFull(r, seq); err != nil { + return + } + pasting = string(seq) == "[200~" + continue + case c != '\r' || pasting: + typed.WriteByte(c) + fmt.Printf("%c", c) // drawn in the prompt + continue + } + line := typed.String() + typed.Reset() + 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}}, + map[string]any{"type": "assistant", "requestId": "req_1", "message": map[string]any{"id": "msg_1", "model": "claude-haiku", "role": "assistant", + "content": []any{map[string]any{"type": "text", "text": "echo: " + line}}}}, + map[string]any{"type": "system", "subtype": "turn_duration"}, + } + for _, row := range rows { + b, _ := json.Marshal(row) + _, _ = f.Write(append(b, '\n')) + } + f.Close() + fmt.Print("\r\n❯ ") + } +} + +// 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 { + t.Helper() + exe, err := os.Executable() + if err != nil { + t.Fatal(err) + } + home := t.TempDir() + cfg := filepath.Join(home, "claude") + cmd := exec.Command(exe, pargs...) + cmd.Env = append(os.Environ(), "MAGPIE_TUI_TEST=shim", "HOME="+home, "XDG_CACHE_HOME="+filepath.Join(home, "cache"), "CLAUDE_CONFIG_DIR="+cfg) + cmd.Env = append(cmd.Env, env...) + stdin, _ := cmd.StdinPipe() + stdout, _ := cmd.StdoutPipe() + cmd.Stderr = os.Stderr + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + _ = cmd.Process.Kill() + _ = cmd.Wait() + }) + t.Setenv("MAGPIE_TUI_TEST_CFG", cfg) + for _, l := range lines { + b, _ := json.Marshal(map[string]any{"type": "user", "message": map[string]any{"role": "user", "content": l}}) + _, _ = stdin.Write(append(b, '\n')) + } + got := make(chan map[string]any) + go func() { + sc := bufio.NewScanner(stdout) + for sc.Scan() { + var m map[string]any + _ = json.Unmarshal(sc.Bytes(), &m) + got <- m + } + }() + var out []map[string]any + by := time.After(30 * time.Second) + for len(out) < want { + select { + case m := <-got: + out = append(out, m) + case <-by: + t.Fatalf("the shim wrote %d lines of %d in 30s: %v", len(out), want, out) + } + } + return out +} + +func fakePath(t *testing.T) string { + t.Helper() + exe, _ := os.Executable() + // the fake is the test binary, told so by its environment: a script + // beside it starts it so + p := filepath.Join(t.TempDir(), "claude") + if err := os.WriteFile(p, []byte("#!/bin/sh\nMAGPIE_TUI_TEST=claude exec '"+exe+"' \"$@\"\n"), 0o700); err != nil { + t.Fatal(err) + } + return p +} + +var pArgs = []string{"-p", "--output-format", "stream-json", "--input-format", "stream-json", "--include-partial-messages", "--verbose", + "--model", "haiku", "--tools", "WebSearch", "--strict-mcp-config", "--mcp-config", "{}", "--setting-sources", "", + "--dangerously-skip-permissions", "--effort", "high", "--thinking-display", "summarized"} + +func TestShimTurnsInteractive(t *testing.T) { + out := runShim(t, nil, append([]string{fakePath(t)}, pArgs...), []string{"hello", "/help"}, 5) + if out[0]["type"] != "system" || out[0]["subtype"] != "init" || out[0]["session_id"] == "" { + t.Fatalf("first line %v, want the init", out[0]) + } + var texts []string + results := 0 + for _, m := range out[1:] { + switch m["type"] { + case "assistant": + b, _ := json.Marshal(m["message"]) + texts = append(texts, string(b)) + case "result": + results++ + } + } + if len(texts) != 2 || !strings.Contains(texts[0], "echo: hello") || results != 2 { + t.Fatalf("got %v", out) + } + // a slash opening the message is pasted after a line break: words, + // not a command + if !strings.Contains(texts[1], `\n/help"`) { + t.Fatalf("the second turn said %s", texts[1]) + } + args, _ := os.ReadFile(filepath.Join(os.Getenv("MAGPIE_TUI_TEST_CFG"), "args")) + got := strings.Split(string(args), "\n") + for _, no := range []string{"-p", "--dangerously-skip-permissions", "--output-format", "--verbose", "--thinking-display"} { + if slices.Contains(got, no) { + t.Errorf("the interactive Claude Code was given %s: %q", no, got) + } + } + for _, yes := range []string{"--no-chrome", "mcp__magpie,WebSearch", "--session-id", "high"} { + if !slices.Contains(got, yes) { + t.Errorf("the interactive Claude Code wasn't given %s: %q", yes, got) + } + } +} + +func TestShimFallsBackToPrint(t *testing.T) { + for _, c := range []struct { + name string + env []string + broken bool + }{ + {"failed start", []string{"FAKE_FAIL=1"}, true}, + {"untrusted folder", []string{"FAKE_TRUST=1"}, false}, + } { + t.Run(c.name, func(t *testing.T) { + out := runShim(t, c.env, append([]string{fakePath(t)}, pArgs...), []string{"hello"}, 1) + if out[0]["result"] != "print mode" { + t.Fatalf("got %v, want the -p run's answer", out) + } + home := filepath.Dir(os.Getenv("MAGPIE_TUI_TEST_CFG")) + m, _ := filepath.Glob(filepath.Join(home, "*", "*", "magpie", "claude-tui-broken")) + m2, _ := filepath.Glob(filepath.Join(home, "*", "magpie", "claude-tui-broken")) + if got := len(m)+len(m2) > 0; got != c.broken { + t.Fatalf("marked broken: %v, want %v", got, c.broken) + } + }) + } +} + +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" { + t.Fatalf("got %v, want an interactive turn", out) + } +} + +func TestPasteable(t *testing.T) { + for _, c := range []struct { + in string + busy bool + want string + }{ + {"hello", false, "hello"}, + {"/help", false, "\n/help"}, + {" !ls", false, "\n!ls"}, + {"# note", true, userMark + "# note"}, + {"a\r\nb\x1b[201~c", false, "a\nb[201~c"}, + {"x / y", true, "x / y"}, + } { + if got := pasteable(c.in, c.busy); got != c.want { + t.Errorf("pasteable(%q, %v) = %q, want %q", c.in, c.busy, got, c.want) + } + } +} + +type lines struct { + out []map[string]any + rows, overed int +} + +func (l *lines) emit(v any) { + b, _ := json.Marshal(v) + var m map[string]any + _ = json.Unmarshal(b, &m) + l.out = append(l.out, m) +} +func (l *lines) sawRow() { l.rows++ } +func (l *lines) turnOver() { l.overed++ } + +func TestTranslatorAPIError(t *testing.T) { + l := &lines{} + tr := newTranslator(l) + for _, row := range []string{ + `{"type":"user","message":{"role":"user","content":"hi"}}`, + `{"type":"assistant","isApiErrorMessage":true,"apiErrorStatus":429,"apiErrorParams":{"rate_limit_info":{"status":"rejected"}},"message":{"id":"x","model":"","content":[{"type":"text","text":"You've hit your limit"}]}}`, + `{"type":"system","subtype":"turn_duration"}`, + `{"type":"user","isSidechain":true,"message":{"role":"user","content":"agent"}}`, + } { + tr.row([]byte(row)) + } + kinds := []string{} + for _, m := range l.out { + kinds = append(kinds, m["type"].(string)) + } + if !slices.Equal(kinds, []string{"assistant", "rate_limit_event", "result"}) || l.rows != 1 || l.overed != 2 { + t.Fatalf("got %v (rows %d, over %d)", l.out, l.rows, l.overed) + } + if r := l.out[2]; r["is_error"] != true || r["result"] != "You've hit your limit" || r["api_error_status"] != float64(429) { + t.Fatalf("result %v", r) + } +} diff --git a/internal/cli/main.go b/internal/cli/main.go index cd00979bf..e6cc9708d 100644 --- a/internal/cli/main.go +++ b/internal/cli/main.go @@ -17,6 +17,7 @@ import ( "github.com/yetone/magpie/internal/appdir" "github.com/yetone/magpie/internal/catalog" "github.com/yetone/magpie/internal/claudebridge" + "github.com/yetone/magpie/internal/claudetui" "github.com/yetone/magpie/internal/codexrelay" "github.com/yetone/magpie/internal/davsync" "github.com/yetone/magpie/internal/gateway" @@ -321,6 +322,8 @@ func run(args []string) error { return imagemcp.Run(args[1:]) case "claude-mcp-helper": // internal: stdio MCP subprocess spawned by Claude Code return claudebridge.RunMCP(args[1:]) + case claudetui.Command: // internal: Claude Code's interactive mode for the bridge + return claudetui.Run(args[1:]) case "statusline": return statuslineCmd(args) case "tools": diff --git a/internal/gateway/claude_subscription.go b/internal/gateway/claude_subscription.go index eeebbec35..1bea82b21 100644 --- a/internal/gateway/claude_subscription.go +++ b/internal/gateway/claude_subscription.go @@ -61,6 +61,7 @@ import ( "github.com/yetone/magpie/internal/appdir" "github.com/yetone/magpie/internal/claudecode" + "github.com/yetone/magpie/internal/claudetui" "github.com/yetone/magpie/internal/netproxy" "github.com/yetone/magpie/internal/proc" "github.com/yetone/magpie/internal/provider" @@ -174,6 +175,7 @@ type subscriptionRun struct { safeguardBeta string clientMarks bool lean bool // started with leanSystem as its system prompt + tui bool // Claude Code's interactive mode (claudeTUI) cacheTail string cachePrefix cachePrefix timer *time.Timer @@ -814,7 +816,16 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model, prefix = promptCachePrefix(prompt) } } - cmd := binary.command(context.Background(), args...) + // Claude Code's interactive mode, where a run allows it (claudeTUI): + // the shim (claudetui) is handed the -p arguments, and becomes that -p + // run when the interactive one doesn't start + tui := claudeTUI(req, binary, prompt) + var cmd *exec.Cmd + if tui { + cmd = proc.CommandContext(context.Background(), exe, append([]string{claudetui.Command, binary.path}, args...)...) + } else { + cmd = binary.command(context.Background(), args...) + } cmd.Dir = work env, err := binary.proxied(ctx, cleanClaudeEnv(os.Environ())) if err != nil { @@ -827,6 +838,13 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model, if len(req.Safeguards) > 0 { env = append(env, "ANTHROPIC_BETAS="+req.SafeguardBeta) } + if tui && (!client || configDir != "") { + // a folder of magpie's, or an account folder of magpie's whose + // Claude Code no one else runs: asked whether to trust it, the + // shim says yes; in the user's own account a caller's folder is + // theirs to answer for, and the run is -p + env = append(env, claudetui.TrustEnv+"=1") + } cmd.Env = binary.env(binary.asRoot(env), configDir) stdin, err := cmd.StdinPipe() if err != nil { @@ -856,6 +874,7 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model, run.safeguardBeta = req.SafeguardBeta run.clientMarks = req.clientCache != nil run.lean = req.leanPrompt + run.tui = tui run.cachePrefix = prefix if user, _ := ownerAccount(owner); user != "" { run.loginVersion = provider.ClaudeLoginVersion(user) @@ -891,7 +910,7 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model, run.readOutput(stdout) }() - if len(req.Safeguards) > 0 || from != nil || run.clientMarks { + if len(req.Safeguards) > 0 || from != nil || run.clientMarks || tui { // Initialize the SDK before applying settings. Send the potentially // large context over stdin rather than an environment entry. A // Claude Code resumed from a saved session answers it only once @@ -923,6 +942,32 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model, return run, segment, nil } +// claudeTUIRuns is false where magpie's executable has no shim to run: +// the gateway's tests, whose fake Claude Codes are -p ones. +var claudeTUIRuns = true + +// tuiPromptMost is the longest first message a run in Claude Code's +// interactive mode is pasted; a longer one is a -p run's. +const tuiPromptMost = 400 << 10 + +// claudeTUI says whether a run is Claude Code's interactive mode, as a +// person runs it (claudetui), rather than -p: the plan counts a -p +// request, its entrypoint sdk-cli, at about twice the interactive mode's +// (anthropics/claude-code#97074). On unless the user turned it off +// (ClaudePrintMode), on macOS and Linux, for a run whose Claude Code is +// this machine's; not for what only -p takes: safeguards and a client's +// cache marks (control requests and an extra body), a JSON schema, and +// images. prompt is the run's first message. +func claudeTUI(req *Request, binary claudeCLI, prompt []map[string]any) bool { + if !claudeTUIRuns || runtime.GOOS != "darwin" && runtime.GOOS != "linux" || binary.wsl != nil || binary.path == "" || + len(req.Safeguards) > 0 || req.clientCache != nil || len(req.Format.schema()) > 0 || + countImages(req.Messages) > 0 || settings.Load().ClaudePrintMode { + return false + } + b, _ := json.Marshal(prompt) + return len(b) <= tuiPromptMost +} + // safeguardBody is the safety-only form of the run's extra body. func safeguardBody(raw json.RawMessage) string { return claudeExtraBody(raw, "") @@ -1063,6 +1108,11 @@ func (b *subscriptionBridge) resume(req *Request, owner string) (*subscriptionRu return nil, nil } req.clientCache.selected(false) + if run.tui && (back != "" || countImages(since) > 0) { + // the interactive mode can't be taken back, nor pasted an image + run.abortFor("the interactive Claude Code can't go on with this turn") + return nil, nil + } if back != "" { if err := run.rewind(back); err != nil { log.Printf("claude: a run that went on with a side question could not be taken back to the conversation's turn, let go: %v", err) @@ -1114,6 +1164,12 @@ func (b *subscriptionBridge) resume(req *Request, owner string) (*subscriptionRu // untouched, where a run started anew is told it in one message, a // prefix the cache has never seen if req.Effort != run.effort { + if run.tui { + // the interactive mode takes its effort at its start only: + // the run is let go, and one at the new effort started + run.abortFor("its effort is set at its start, and the next turn asks another") + return nil, nil + } if err := run.setEffort(req.Effort); err != nil { run.abortFor("it could not be told the next turn's effort: " + err.Error()) return nil, nil @@ -1774,7 +1830,8 @@ type controlReply struct { func (r *subscriptionRun) letGo() { r.mu.Lock() turn, back := r.turnUUID, r.backKey - can := !r.closed && r.stdin != nil && r.bridge != nil && r.timer != nil && + // the interactive mode (claudeTUI) can't be taken back + can := !r.closed && !r.tui && r.stdin != nil && r.bridge != nil && r.timer != nil && turn != "" && back != "" && len(r.pending) == 0 && r.rewinding == nil done := make(chan struct{}) if can { diff --git a/internal/gateway/claude_tui_test.go b/internal/gateway/claude_tui_test.go new file mode 100644 index 000000000..db5ea0836 --- /dev/null +++ b/internal/gateway/claude_tui_test.go @@ -0,0 +1,54 @@ +package gateway + +import ( + "encoding/json" + "runtime" + "strings" + "testing" + + "github.com/yetone/magpie/internal/settings" + "github.com/yetone/magpie/internal/wslrun" +) + +// A Claude run is Claude Code's interactive mode on macOS and Linux, for +// this machine's Claude Code, unless the user turned it off or the run +// needs what only -p takes. +func TestClaudeTUIChosen(t *testing.T) { + was := settings.Load() + t.Cleanup(func() { _ = settings.Save(was) }) + claudeTUIRuns = true + t.Cleanup(func() { claudeTUIRuns = false }) + here := claudeCLI{path: "/usr/local/bin/claude"} + text := func(s string) []Message { + return []Message{{Role: "user", Parts: []Part{{Kind: Text, Text: s}}}} + } + prompt := []map[string]any{{"type": "text", "text": "hi"}} + on := runtime.GOOS == "darwin" || runtime.GOOS == "linux" + cases := []struct { + name string + req *Request + binary claudeCLI + prompt []map[string]any + print bool + want bool + }{ + {"a plain turn", &Request{Messages: text("hi")}, here, prompt, false, on}, + {"turned off", &Request{Messages: text("hi")}, here, prompt, true, false}, + {"in WSL", &Request{Messages: text("hi")}, claudeCLI{path: "claude", wsl: &wslrun.Tool{}}, prompt, false, false}, + {"safeguards", &Request{Messages: text("hi"), Safeguards: json.RawMessage(`{"a":1}`)}, here, prompt, false, false}, + {"client cache marks", &Request{Messages: text("hi"), clientCache: &clientCache{}}, here, prompt, false, false}, + {"a schema", &Request{Messages: text("hi"), Format: &Format{Type: "json_schema", Schema: json.RawMessage(`{"type":"object"}`)}}, here, prompt, false, false}, + {"an image", &Request{Messages: []Message{{Role: "user", Parts: []Part{{Kind: Image, MediaType: "image/png", Data: "AA=="}}}}}, here, prompt, false, false}, + {"a long first message", &Request{Messages: text("hi")}, here, []map[string]any{{"type": "text", "text": strings.Repeat("x", tuiPromptMost)}}, false, false}, + } + for _, c := range cases { + st := settings.Load() + st.ClaudePrintMode = c.print + if err := settings.Save(st); err != nil { + t.Fatal(err) + } + if got := claudeTUI(c.req, c.binary, c.prompt); got != c.want { + t.Errorf("%s: claudeTUI = %v, want %v", c.name, got, c.want) + } + } +} diff --git a/internal/gateway/main_test.go b/internal/gateway/main_test.go index fc2801fe1..8feade50b 100644 --- a/internal/gateway/main_test.go +++ b/internal/gateway/main_test.go @@ -29,6 +29,8 @@ func TestMain(m *testing.M) { serveMiddleware() searchOn = gwtool.Serve(gwtool.WebSearch) limitsOn = gwbudget.Limit(budget.Limiter{}) + // the test binary is no magpie: it runs no claude-tui-helper + claudeTUIRuns = false code, err := isolatedTests(m) if err != nil { fmt.Fprintln(os.Stderr, err) diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index acea22bdf..8916e6b02 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -21759,7 +21759,18 @@ function renderReplies(s, keep) { cval.append(segs([["off", t("Off")], ["on", t("On")]], s.claudeLeanPrompt ? "on" : "off", (v) => savePrefs({ ...keep, claudeLeanPrompt: v === "on" }))); c.append(cwho, cval); - box.append(r, l, f, k, c); + // a Claude run as Claude Code's interactive mode, -p when turned off + // (on unless off: the plan counts a -p request at about twice) + const u = el("div", "row pref"); + u.id = "claudeTuiRow"; + const uwho = el("div", "who"); + uwho.append(el("div", "name", t("Claude Code's interactive mode")), + el("div", "sub wraps", t("A Claude subscription runs Claude Code as a person does, in its interactive mode, where the plan counts a request at about half of what -p uses. Off runs it as claude -p, as Windows always does"))); + const uval = el("div", "val"); + uval.append(segs([["off", t("Off")], ["on", t("On")]], s.claudePrintMode ? "off" : "on", + (v) => savePrefs({ ...keep, claudePrintMode: v === "off" }))); + u.append(uwho, uval); + box.append(r, l, f, k, c, u); } // renderDisabledModels: the models the user turned off for every request @@ -22767,7 +22778,7 @@ function prefsKeep(s) { redact: !!s.redact, redactPersonal: !!s.redactPersonal, redactKinds: s.redactKinds || {}, redactWords: s.redactWords || [], redactWordsAnyCase: !!s.redactWordsAnyCase, redactWordsWhole: !!s.redactWordsWhole, redactShape: !!s.redactShape, codexWarmup: s.codexWarmup || "", claudeWarmup: s.claudeWarmup || "", codexWarmAt: s.codexWarmAt || "", claudeWarmAt: s.claudeWarmAt || "", codexWarmAts: warmTimes(s.codexWarmAts, s.codexWarmAt), claudeWarmAts: warmTimes(s.claudeWarmAts, s.claudeWarmAt), workbuddyCheckin: !!s.workbuddyCheckin, traeCheckin: !!s.traeCheckin, minimaxCheckin: !!s.minimaxCheckin, qoderCheckin: !!s.qoderCheckin, noStats: !!s.noStats, noUsageStats: !!s.noUsageStats, signInLinkOnly: !!s.signInLinkOnly, - memberModel: !!s.memberModel, noLoopGuard: !!s.noLoopGuard, claudeLeanPrompt: !!s.claudeLeanPrompt, refusalRetries: s.refusalRetries ?? null, + memberModel: !!s.memberModel, noLoopGuard: !!s.noLoopGuard, claudeLeanPrompt: !!s.claudeLeanPrompt, claudePrintMode: !!s.claudePrintMode, refusalRetries: s.refusalRetries ?? null, noUpdatePill: !!s.noUpdatePill, noAutoUpdate: !!s.noAutoUpdate, updateEvery: s.updateEvery || 360, autoRestart: !!s.autoRestart, noAutoDownload: !!s.noAutoDownload, updateChannel: s.updateChannel || "", trayUsage: s.trayUsage || "", trayUsageEvery: s.trayUsageEvery || 3, trayNoLogos: !!s.trayNoLogos, trayNoBird: !!s.trayNoBird, trayPace: !!s.trayPace, trayNoCost: !!s.trayNoCost, trayWindows: s.trayWindows || {}, vision: s.vision || "", visionEffort: s.visionEffort || "", searcherEffort: s.searcherEffort || "", imageGen: s.imageGen || "", imageTimeout: s.imageTimeout || 0, classifyTimeout: s.classifyTimeout || 0, searcher: s.searcher || "", searchFirst: s.searchFirst || "", currency: s.currency || "usd", chineseUnits: !!s.chineseUnits, usageAlert: s.usageAlert || 0, balanceAlert: s.balanceAlert || 0, resetReminder: s.resetReminder || 0, diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 4d990e6b3..309243b89 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -331,6 +331,8 @@ const I18N = { "Name the member in replies": "回复里写明成员", "Stop looping replies": "停止循环的回复", "Short Claude system prompt": "精简 Claude 系统提示词", + "Claude Code's interactive mode": "Claude Code 交互模式", + "A Claude subscription runs Claude Code as a person does, in its interactive mode, where the plan counts a request at about half of what -p uses. Off runs it as claude -p, as Windows always does": "Claude 订阅像人一样以交互模式运行 Claude Code,套餐对每次请求的计量约为 -p 的一半。关闭则以 claude -p 运行,Windows 上始终如此", "A Claude subscription answers with the agent's own instructions as its system prompt, in place of Claude Code's, about 1K fewer tokens each request. Still the real Claude Code, but its requests look less like Claude Code's own, which can put the account more at risk": "Claude 订阅以智能体自己的指令作为系统提示词,代替 Claude Code 的,每次请求约少 1K token。仍是真正的 Claude Code,但请求不再那么像 Claude Code 自己发出的,账号风险可能更高", "Ask again after a refusal": "被拒答后再问", "When a vendor's safety filter refuses a request before anything is said, how many more accounts or routing group members are asked. Never ask again hands the refusal straight back: Claude Code then switches to its own fallback model, as it does on Anthropic's API": "供应商的安全过滤在还没说出任何内容前拒绝请求时,再换多少个账号或路由组成员去问。选“不再问”会直接把拒答交回:Claude Code 随后会像直连 Anthropic API 时一样,自己换到它的备用模型", @@ -4559,6 +4561,8 @@ const I18N = { "Name the member in replies": "回覆裡寫明成員", "Stop looping replies": "停止循環的回覆", "Short Claude system prompt": "精簡 Claude 系統提示詞", + "Claude Code's interactive mode": "Claude Code 互動模式", + "A Claude subscription runs Claude Code as a person does, in its interactive mode, where the plan counts a request at about half of what -p uses. Off runs it as claude -p, as Windows always does": "Claude 訂閱像人一樣以互動模式執行 Claude Code,方案對每次請求的計量約為 -p 的一半。關閉則以 claude -p 執行,Windows 上始終如此", "A Claude subscription answers with the agent's own instructions as its system prompt, in place of Claude Code's, about 1K fewer tokens each request. Still the real Claude Code, but its requests look less like Claude Code's own, which can put the account more at risk": "Claude 訂閱以代理自己的指令作為系統提示詞,取代 Claude Code 的,每次請求約少 1K token。仍是真正的 Claude Code,但請求不再那麼像 Claude Code 自己發出的,帳號風險可能更高", "Ask again after a refusal": "被拒答後再問", "When a vendor's safety filter refuses a request before anything is said, how many more accounts or routing group members are asked. Never ask again hands the refusal straight back: Claude Code then switches to its own fallback model, as it does on Anthropic's API": "供應商的安全過濾在還沒說出任何內容前拒絕請求時,再換多少個帳號或路由組成員去問。選「不再問」會直接把拒答交回:Claude Code 隨後會像直連 Anthropic API 時一樣,自己換到它的備用模型", @@ -8756,6 +8760,8 @@ const I18N = { "Name the member in replies": "応答にメンバー名を記す", "Stop looping replies": "ループする応答を止める", "Short Claude system prompt": "Claude のシステムプロンプトを短く", + "Claude Code's interactive mode": "Claude Code の対話モード", + "A Claude subscription runs Claude Code as a person does, in its interactive mode, where the plan counts a request at about half of what -p uses. Off runs it as claude -p, as Windows always does": "Claude サブスクリプションは人と同じように Claude Code を対話モードで実行し、プランはリクエストを -p の約半分として数えます。オフにすると claude -p で実行します(Windows では常にこちら)", "A Claude subscription answers with the agent's own instructions as its system prompt, in place of Claude Code's, about 1K fewer tokens each request. Still the real Claude Code, but its requests look less like Claude Code's own, which can put the account more at risk": "Claude サブスクリプションは Claude Code のものの代わりにエージェント自身の指示をシステムプロンプトとして応答し、リクエストごとに約 1K トークン少なくなります。本物の Claude Code のままですが、リクエストが Claude Code 自身のものらしくなくなるため、アカウントのリスクが高まる可能性があります", "Ask again after a refusal": "拒否のあと聞き直す", "When a vendor's safety filter refuses a request before anything is said, how many more accounts or routing group members are asked. Never ask again hands the refusal straight back: Claude Code then switches to its own fallback model, as it does on Anthropic's API": "ベンダーの安全フィルターが何も言わないうちにリクエストを拒否したとき、ほかのアカウントやルーティンググループのメンバーにあと何回聞くか。「聞き直さない」は拒否をそのまま返します。Claude Code は Anthropic の API のときと同じく、自分のフォールバックモデルに切り替えます", @@ -12963,6 +12969,8 @@ const I18N = { "Name the member in replies": "Mitglied in Antworten nennen", "Stop looping replies": "Schleifende Antworten beenden", "Short Claude system prompt": "Kurzer Claude-Systemprompt", + "Claude Code's interactive mode": "Interaktiver Modus von Claude Code", + "A Claude subscription runs Claude Code as a person does, in its interactive mode, where the plan counts a request at about half of what -p uses. Off runs it as claude -p, as Windows always does": "Ein Claude-Abo führt Claude Code wie ein Mensch im interaktiven Modus aus, wo der Plan eine Anfrage mit etwa der Hälfte von -p anrechnet. Aus führt es als claude -p aus, wie unter Windows immer", "A Claude subscription answers with the agent's own instructions as its system prompt, in place of Claude Code's, about 1K fewer tokens each request. Still the real Claude Code, but its requests look less like Claude Code's own, which can put the account more at risk": "Ein Claude-Abo antwortet mit den eigenen Anweisungen des Agenten als Systemprompt statt mit dem von Claude Code, etwa 1K Token weniger pro Anfrage. Weiterhin das echte Claude Code, aber seine Anfragen sehen Claude Codes eigenen weniger ähnlich, was das Konto stärker gefährden kann", "Ask again after a refusal": "Nach einer Ablehnung erneut fragen", "When a vendor's safety filter refuses a request before anything is said, how many more accounts or routing group members are asked. Never ask again hands the refusal straight back: Claude Code then switches to its own fallback model, as it does on Anthropic's API": "Lehnt der Sicherheitsfilter eines Anbieters eine Anfrage ab, bevor etwas gesagt wurde: wie viele weitere Konten oder Mitglieder der Routing-Gruppe gefragt werden. Nie gibt die Ablehnung direkt zurück: Claude Code wechselt dann selbst zu seinem Ausweichmodell, wie bei Anthropics API", diff --git a/internal/gui/core_budget_test.go b/internal/gui/core_budget_test.go index f8ebdc65a..018851790 100644 --- a/internal/gui/core_budget_test.go +++ b/internal/gui/core_budget_test.go @@ -16,7 +16,7 @@ import ( // raises them and says why in its commit. const ( appScriptBudget = 1_315_316 // app.js: 1,198,239 after Usage left (P2); 1,218,098 with the 10-15 fixes to pages still in the core; 1,232,466 with the provider editor's Advanced fold and every dialog holding its place, the core's own (10-16); 1,250,533 with the quota refresh kept through redraws, the core's own since the tray panel draws it too, plus 1.5% (#2397); 1,269,083 with Free first's option in the provider editor's ROUTINGS, which the Routing page reads too, plus 1.5%; 1,272,726 with the Providers page drawing its last list at once (#1519), the core's page, and the Routing trace's account names read without Object.entries (#1481), plus 1.5%; a dialog growing out of the row that opened it and folding back into it, the core's own since every page's dialogs open through it (10-20); Codex's and Claude Code's own settings moved from Settings into the agent's row on the Agents page, the core's own since the tray panel and the window both draw them (10-20); 1,314,432 with Settings › Privacy's record of what was masked (its summary, the records view and the local model's controls), which belongs to Settings, the core's own, plus 1.5%; 1,336,481 with a provider's Names & levels saying Provider in model names is Settings' and opening it there (joe), and Settings' Image recognition saying where a custom provider's model is marked (nexnull), both in the core's own pages, with no room added (10-23); 1,337,633 with Settings › Models › Replies' Intent classifier timeout (#2934, reyoung), Settings' own row, drawn by waitRow, which the Image generation timeout's row now shares, with no room added; 1,337,735 with the provider editor's link naming a partner's page by its own host (siteHost) instead of usemagpie.ai's /go link, the core's own editor, with no room added (10-23); 1,338,084 with Check in now saying what the press came to (claimed +credits, already today, not available yet) where it said "refreshed" (#3326), the check-in row the tray panel draws too, the core's own, with no room added (10-23); 1,338,929 with a new partner's tile keeping a small dot until it is opened, in the add sheet, the core's own, with no room added (10-23); 1,343,324 with the sidebar's open-page row marked by one shape that moves on a spring (navTopGo), the window's own shell, which every page sits beside, with no room added (10-23); 1,343,465 with a dialog kept centred while its content comes in, until it is pressed (holdModal, every page's dialogs), the core's own, with no room added (10-24); 1,317,486 with what masking did moved out to Insights › Masking (plugins/redact), the budget lowered to it (10-24); 1,321,336 with Codex's one subagent model, its card's square saying plainly what each choice does and a row with a name in its sheet, where two squares read alike (the owner), the Agents page's, which the tray panel draws too, the core's own, with no room added (10-24); 1,321,424 with Settings › Models' Image generation MCP server row beside Image recognition's (JonahFu on X), the two drawn by one helper (mcpRow), Settings' own, with no room added (10-25); 1,321,994 with a provider of the user's set never to rest for a limit (zoecats), the provider editor's Advanced row, the core's own editor, with no room added (10-25); 1,322,289 with Settings › Privacy's Keep a key's form under Mask secrets (Charles Cao on X), Settings' own row, with no room added (10-25); 1,322,537 with no Codex squares beside its named settings rows (the owner), with no room added (10-25); 1,323,401 with the tray panel drawing its last allowances at once and asking for them beside the state (#3160, #3134), the tray panel's, the core's own, and the 4 bytes 84c50f032 added, with no room added (10-25); 1,326,105 with many releases' notes merged into one list by kind, each line with its version (the owner), in the update sheet and What's new, with no room added (10-25); 1,321,319 with Settings › Observability moved out to its plugin (plugins/otel/page.js) and its Langfuse setup there (an X user), the budget lowered to it (10-26); a quota card whose window is used but names no reset no longer saying "Not used yet" (windy on Discord) raised it to 1,321,347, and back to 1,321,319 with Settings' model pickers sharing one row helper (modelOpt) where six kept their own copy, no raise (10-26); 1,325,845 with every slow page's skeletons getting magpie's bird hopping bar to bar (skelBird, the owner after the Plugins page's README), one bird for the window over whatever page or dialog is loading, the core's own, with no room added (10-26); 1,310,129 with Settings › Network and sharing's gateway rows (its port, bare ids, local network, allowed addresses, web pages) moved out to the gateway plugin (plugins/gateway/settings.js), the budget lowered to it (10-27); 1,310,269 with Test models naming the first model that failed and its error in the status line, where it said only how many (ysm119 on Discord), the provider editor's, the core's own, with no room added (10-27); 1,310,460 with Settings › About's Website row linking usemagpie.ai (the owner), Settings' own row, with no room added (10-27); 1,309,669 with a pool's Stop at the caps and Check usage near a cap ticks under a provider's accounts (plugins#349), the core's own editor, its account rows' Remove and add rows each drawn by one helper (forgetOf, addRow), with no room added (10-28); 1,311,681 with Install another agent on the Agents page naming the agents Plugins has (More in Plugins) and opening Plugins at its Agents (the owner), the Agents page's, the core's own, with no room added (10-28); 1,311,735 with More in Plugins in sight while Install another agent is folded (the owner), with no room added (10-29); 1,313,704 with a window whose WebKit scrolls under wheels it never tells of (macOS 13) remembered once seen, a scroll at rest then waiting 120ms for a second the same way within 80ms before it is put back, kept for a late wheel to give back (waitsBack), and a load landing under the wheel keeping the reader's way (backAfterLoad, issennknight), the window's own scroll guard, with no room added (10-29); back to 1,311,735 with Settings › Models › Web search's rows (renderSearch, renderSearcher, the search APIs' keys) moved out to the search plugin (plugins/search/settings.js), app.js 1,292,527 after it, not lowered further since what is left plus 1.5% is over it (#4133, 10-29); 1,315,316 with the Agents row of a Claude Code or Codex not connected saying the account it is signed in to and switching it to another (Switch accounts only, the owner on X), in place of the failover line's ChatGPT accounts button, the Agents page's, the core's own, its comments cut down, with no room added (10-30); 1,317,705 with a Claude account added from a setup-token (sfss5362 on X): the sign-in's Use a setup-token instead…, its sheet, and its account row's magpie only, the provider editor's account rows, the core's own editor, its comments cut down, with no room added (10-30); back to 1,315,316 with the setup-token sheet and Copilot's GHE.com one moved out to signsheets.js, loaded when one is asked for (signAsk, 10-30) - coreScriptBudget = 1_536_631 // every core script: 1,358,034 after Usage left; 1,380,003 with them; 1,405,937 with the fold; 1,426,102 with 10-16's core work (the GitHub list loading, the move to plugins, Settings › Long conversations), plus 1.5% (#2612); 1,447,368 with loadBack, the window's one state read per return, which every page needs and so is the core's own (1,446,845 before it, 155 bytes under), plus 1.5%; OpenCode Zen's card saying OpenCode tells no key its balance adds ~390 bytes inside it; 1,472,589 with the dialog that grows out of its row and the agents' own settings in their rows, on main's 10-20 core work (the Providers page's last list, the Routing trace's names), plus 1.5% (10-20); 1,506,192 with Settings › Privacy's record of what was masked, plus 1.5%; 1,529,393 with the Intent classifier timeout row (#2934), with no room added; 1,529,495 with the editor's partner link host, with no room added; 1,529,844 with Check in now's press summary (#3326), with no room added; 1,530,689 with the new partner tile's dot, with no room added; 1,535,084 with the sidebar's spring, with no room added; 1,549,478 with the context window card's map (tiles by tokens, the default look, the block grid a switch away) and its text view showing an inline image, in context.js, which the Routing page draws as well as Usage, so the core's own, with no room added (10-24); 1,550,768 with a usage card's refresh opening after its text (#840's card, which the tray panel draws too), the Add key spinner, and a dialog kept centred while its content comes in, with no room added (10-24); 1,524,789 with what masking did moved out to Insights › Masking, lowered to it; 1,528,525 with Codex's one subagent model, with no room added (10-24); 1,528,972 with the Image generation MCP server row (JonahFu on X), with no room added (10-25); 1,529,542 with the limit-rest row (zoecats), with no room added (10-25); 1,529,837 with Keep a key's form (Charles Cao on X), with no room added (10-25); 1,530,050 with no Codex squares beside its named settings rows (the owner), with no room added (10-25); 1,530,631 with a plugin's page growing to its README on the dialog's spring instead of in one jump (the owner), the Plugins page's, in plugins.js, with no room added (10-25); 1,533,445 with the context map counting its tokens on as a live request grows, a tile pointed at keeping its tip, a tool's gathered results saying how many and the small files their folder (the owner, after flohoeller's map on X), in context.js, which the Routing page draws as well as Usage, and the 4 bytes 84c50f032 added to app.js (Settings' Version row) without a raise, with no room added (10-25); 1,534,312 with the tray panel's last allowances drawn at once (#3160, #3134), with no room added (10-25); 1,537,016 with many releases' notes merged into one list by kind (the owner), in app.js, with no room added (10-25); 1,542,244 with a plugin's README loading under magpie's bird bouncing down its lines instead of pulsing bars (the owner), the Plugins page's, in plugins.js, with no room added (10-26); 1,542,418 with a page plugin's sidebar tab coming and going as it is installed, switched on or off, or removed, instead of on the Plugins page's next load (the owner), in plugins.js, with no room added (10-26); 1,537,645 with Settings › Observability moved out to plugins/otel, lowered to it (10-26); 1,537,673 with a used window with no reset not "Not used yet" (windy on Discord), and back to 1,537,645 with Settings' model pickers sharing modelOpt (10-26); 1,541,967 with every slow page's skeletons getting magpie's bird (skelBird, the owner), in app.js, the README's bird sharing its drawing and styles, with no room added (10-26); 1,526,251 with Settings' gateway rows moved out to plugins/gateway/settings.js, lowered to it (10-27); 1,526,391 with Test models naming the first failed model and its error (ysm119 on Discord), in app.js, with no room added (10-27); 1,526,556 with About's Website row (the owner), in app.js, with no room added (10-27); 1,526,500 with a pool's cap ticks (plugins#349), in app.js, with no room added (10-28); 1,527,245 with About's Open-source licenses row and dialog (the owner), in app.js, with no room added (10-28); 1,528,076 with the Partners heading's light (the owner), in app.js, with no room added (10-28); 1,530,449 with Install another agent's More in Plugins row (the owner), in app.js, and Plugins opening at its Agents, in plugins.js, with no room added (10-28); 1,530,807 with layout.js measuring the scrollbar into --bar, which every page's right padding takes off so its sides match (the owner), the window's own shell, with no room added (10-28); 1,530,861 with More in Plugins in sight while Install another agent is folded (the owner), in app.js, with no room added (10-29); 1,532,830 with waitsBack and backAfterLoad (issennknight, macOS 13), the window's own scroll guard, in app.js, with no room added (10-29); the context map's tile wording (a4e929212) and Cindy's Add magpie (628ac36fc) had taken the core over it, and Web search's rows moved out to plugins/search/settings.js brought it back to 1,530,861 (#4133, 10-29); 1,532,459 with a provider editor's account rows on one line each, First or Make first at its right end and the settings that aren't set under ⋯ (the owner), the core's own editor, in app.js, which stays in its budget with its comments cut down, with no room added (10-29); 1,532,602 with a plugin's README waiting for its bird to land on three lines before it goes in, however soon it came (the owner, 10-30), in plugins.js, with no room added; 1,536,357 with Switch accounts only on the Agents row (the owner on X), in app.js, with no room added (10-30); 1,537,034 with a plugin's README read once shown at once, with no bird, when its page opens again and read again behind it, the last 20 kept (the owner), in plugins.js, with no room added (10-30); 1,539,423 with a Claude account added from a setup-token (sfss5362 on X), in app.js, with no room added (10-30); 1,538,975 with purposes.js written as compact JSON by genpurposes and the MCP tool purpose in it, 448 bytes less in all (ferock on Discord), lowered to it (10-30); 1,536,586 with the setup-token sheet and Copilot's GHE.com one moved out to signsheets.js, lowered by the 2,389 the setup-token raised it (10-30); 1,536,631 with the 45 bytes b62fa332f added to app.js (Send requests unmasked for subscriptions and plugin providers too) without a raise, with no room added (10-31) + coreScriptBudget = 1_537_356 // every core script: 1,358,034 after Usage left; 1,380,003 with them; 1,405,937 with the fold; 1,426,102 with 10-16's core work (the GitHub list loading, the move to plugins, Settings › Long conversations), plus 1.5% (#2612); 1,447,368 with loadBack, the window's one state read per return, which every page needs and so is the core's own (1,446,845 before it, 155 bytes under), plus 1.5%; OpenCode Zen's card saying OpenCode tells no key its balance adds ~390 bytes inside it; 1,472,589 with the dialog that grows out of its row and the agents' own settings in their rows, on main's 10-20 core work (the Providers page's last list, the Routing trace's names), plus 1.5% (10-20); 1,506,192 with Settings › Privacy's record of what was masked, plus 1.5%; 1,529,393 with the Intent classifier timeout row (#2934), with no room added; 1,529,495 with the editor's partner link host, with no room added; 1,529,844 with Check in now's press summary (#3326), with no room added; 1,530,689 with the new partner tile's dot, with no room added; 1,535,084 with the sidebar's spring, with no room added; 1,549,478 with the context window card's map (tiles by tokens, the default look, the block grid a switch away) and its text view showing an inline image, in context.js, which the Routing page draws as well as Usage, so the core's own, with no room added (10-24); 1,550,768 with a usage card's refresh opening after its text (#840's card, which the tray panel draws too), the Add key spinner, and a dialog kept centred while its content comes in, with no room added (10-24); 1,524,789 with what masking did moved out to Insights › Masking, lowered to it; 1,528,525 with Codex's one subagent model, with no room added (10-24); 1,528,972 with the Image generation MCP server row (JonahFu on X), with no room added (10-25); 1,529,542 with the limit-rest row (zoecats), with no room added (10-25); 1,529,837 with Keep a key's form (Charles Cao on X), with no room added (10-25); 1,530,050 with no Codex squares beside its named settings rows (the owner), with no room added (10-25); 1,530,631 with a plugin's page growing to its README on the dialog's spring instead of in one jump (the owner), the Plugins page's, in plugins.js, with no room added (10-25); 1,533,445 with the context map counting its tokens on as a live request grows, a tile pointed at keeping its tip, a tool's gathered results saying how many and the small files their folder (the owner, after flohoeller's map on X), in context.js, which the Routing page draws as well as Usage, and the 4 bytes 84c50f032 added to app.js (Settings' Version row) without a raise, with no room added (10-25); 1,534,312 with the tray panel's last allowances drawn at once (#3160, #3134), with no room added (10-25); 1,537,016 with many releases' notes merged into one list by kind (the owner), in app.js, with no room added (10-25); 1,542,244 with a plugin's README loading under magpie's bird bouncing down its lines instead of pulsing bars (the owner), the Plugins page's, in plugins.js, with no room added (10-26); 1,542,418 with a page plugin's sidebar tab coming and going as it is installed, switched on or off, or removed, instead of on the Plugins page's next load (the owner), in plugins.js, with no room added (10-26); 1,537,645 with Settings › Observability moved out to plugins/otel, lowered to it (10-26); 1,537,673 with a used window with no reset not "Not used yet" (windy on Discord), and back to 1,537,645 with Settings' model pickers sharing modelOpt (10-26); 1,541,967 with every slow page's skeletons getting magpie's bird (skelBird, the owner), in app.js, the README's bird sharing its drawing and styles, with no room added (10-26); 1,526,251 with Settings' gateway rows moved out to plugins/gateway/settings.js, lowered to it (10-27); 1,526,391 with Test models naming the first failed model and its error (ysm119 on Discord), in app.js, with no room added (10-27); 1,526,556 with About's Website row (the owner), in app.js, with no room added (10-27); 1,526,500 with a pool's cap ticks (plugins#349), in app.js, with no room added (10-28); 1,527,245 with About's Open-source licenses row and dialog (the owner), in app.js, with no room added (10-28); 1,528,076 with the Partners heading's light (the owner), in app.js, with no room added (10-28); 1,530,449 with Install another agent's More in Plugins row (the owner), in app.js, and Plugins opening at its Agents, in plugins.js, with no room added (10-28); 1,530,807 with layout.js measuring the scrollbar into --bar, which every page's right padding takes off so its sides match (the owner), the window's own shell, with no room added (10-28); 1,530,861 with More in Plugins in sight while Install another agent is folded (the owner), in app.js, with no room added (10-29); 1,532,830 with waitsBack and backAfterLoad (issennknight, macOS 13), the window's own scroll guard, in app.js, with no room added (10-29); the context map's tile wording (a4e929212) and Cindy's Add magpie (628ac36fc) had taken the core over it, and Web search's rows moved out to plugins/search/settings.js brought it back to 1,530,861 (#4133, 10-29); 1,532,459 with a provider editor's account rows on one line each, First or Make first at its right end and the settings that aren't set under ⋯ (the owner), the core's own editor, in app.js, which stays in its budget with its comments cut down, with no room added (10-29); 1,532,602 with a plugin's README waiting for its bird to land on three lines before it goes in, however soon it came (the owner, 10-30), in plugins.js, with no room added; 1,536,357 with Switch accounts only on the Agents row (the owner on X), in app.js, with no room added (10-30); 1,537,034 with a plugin's README read once shown at once, with no bird, when its page opens again and read again behind it, the last 20 kept (the owner), in plugins.js, with no room added (10-30); 1,539,423 with a Claude account added from a setup-token (sfss5362 on X), in app.js, with no room added (10-30); 1,538,975 with purposes.js written as compact JSON by genpurposes and the MCP tool purpose in it, 448 bytes less in all (ferock on Discord), lowered to it (10-30); 1,536,586 with the setup-token sheet and Copilot's GHE.com one moved out to signsheets.js, lowered by the 2,389 the setup-token raised it (10-30); 1,536,631 with the 45 bytes b62fa332f added to app.js (Send requests unmasked for subscriptions and plugin providers too) without a raise, with no room added (10-31); 1,537,356 with Settings › Models › Replies › Claude Code's interactive mode, a row beside Short Claude system prompt (the owner), in app.js, with no room added (10-31) ) func TestCoreScriptBudget(t *testing.T) { diff --git a/internal/gui/tests/claude-tui-setting.test.cjs b/internal/gui/tests/claude-tui-setting.test.cjs new file mode 100644 index 000000000..2f7926847 --- /dev/null +++ b/internal/gui/tests/claude-tui-setting.test.cjs @@ -0,0 +1,101 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// Settings › Models › Replies: Claude Code's interactive mode is On, says +// what it saves and that Off is -p, and Off saves claudePrintMode with the +// rest of the settings kept, the page not moved by the click. In English, +// Chinese, Japanese and German, 1100 and 420 wide. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); +const { watchSettingsReads, settingsDrawn } = require("./reader.cjs"); + +const assets = path.resolve(__dirname, "../assets"); +const words = { + en: { name: "Claude Code's interactive mode", head: "Replies", off: "Off", on: "On", sub: "about half", risk: "claude -p" }, + zh: { name: "Claude Code 交互模式", head: "回复", off: "关闭", on: "开启", sub: "约为 -p 的一半", risk: "claude -p" }, + ja: { name: "Claude Code の対話モード", head: "応答", off: "オフ", on: "オン", sub: "-p の約半分", risk: "claude -p" }, + de: { name: "Interaktiver Modus von Claude Code", head: "Antworten", off: "Aus", on: "An", sub: "Hälfte von -p", risk: "claude -p" }, +}; + +function serve(lang, saved) { + const settings = { lang, theme: "light", redact: true }; + const state = { agents: [], profiles: [], settings }; + return async (r) => { + const url = new URL(r.request().url()); + const json = (data) => r.fulfill({ json: data }); + if (url.pathname === "/boot.js") return r.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return r.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json(state); + if (url.pathname === "/api/settings") { + if (r.request().method() === "POST") { + saved.push(JSON.parse(r.request().postData())); + Object.assign(settings, saved.at(-1)); + } + return json(settings); + } + if (url.pathname === "/api/groups") return json({ models: [], groups: [], pools: [] }); + if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true, url: "http://127.0.0.1:3999" } }); + if (url.pathname.startsWith("/api/")) return json({}); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + await r.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh", "ja", "de"]) for (const width of [1100, 420]) { + const w = words[lang]; + test(`${engine} ${lang} ${width}: Claude Code's interactive mode can be turned off`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await (await browser.newContext({ viewport: { width, height: 900 } })).newPage(); + page.setDefaultTimeout(5000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + const saved = []; + await page.route("**/*", serve(lang, saved)); + await watchSettingsReads(page); + await page.goto("http://magpie.test/?view=settings&tab=models"); + await settingsDrawn(page); // rows found are the ones that stay (#1659) + const row = page.locator("#replyList #claudeTuiRow"); + await row.waitFor(); + // scrolled to as a reader does, with the wheel: WebKit at 420 put + // back a scroll made from script + await page.mouse.move(width / 2, 450); + for (let i = 0; i < 40; i++) { + const box = await row.boundingBox(); + if (box && box.y >= 0 && box.y + box.height <= 900) break; + await page.mouse.wheel(0, 120); + await page.waitForTimeout(50); + } + assert.equal(await row.locator(".name").textContent(), w.name); + const sub = await row.locator(".sub").textContent(); + assert(sub.includes(w.sub) && sub.includes(w.risk), sub); + for (const part of [".name", ".sub", ".segs"]) { + const fit = await row.locator(part).first().evaluate((e) => { + const r = e.getBoundingClientRect(); + return e.scrollWidth <= e.clientWidth + 1 && r.width > 0 && r.right <= innerWidth + 1; + }); + assert(fit, `${part} fits at ${width}`); + } + assert.equal(await page.locator("#replyList").evaluate((l) => l.previousElementSibling.textContent.trim()), w.head); + const on = row.locator(".segs button", { hasText: w.on }); + const off = row.locator(".segs button", { hasText: w.off }); + assert.equal(await on.getAttribute("aria-pressed"), "true", "On at first"); + + const before = await page.evaluate(() => [scrollX, scrollY, document.scrollingElement.scrollTop]); + const b = await off.boundingBox(); + await page.mouse.click(b.x + b.width / 2, b.y + b.height / 2); + await page.waitForFunction(() => document.querySelector("#claudeTuiRow")); + for (let i = 0; i < 50 && !saved.length; i++) await page.waitForTimeout(50); + assert.equal(saved.length, 1, "saved once"); + assert.equal(saved[0].claudePrintMode, true); + assert.equal(saved[0].claudeLeanPrompt, false, "the row beside it kept"); + assert.equal(saved[0].redact, true, "the rest kept"); + assert.equal(saved[0].lang, lang); + assert.deepEqual(await page.evaluate(() => [scrollX, scrollY, document.scrollingElement.scrollTop]), before, "the click moved nothing"); + assert.deepEqual(errors, []); + }); + } +} diff --git a/internal/gui/tests/mobile-web.test.cjs b/internal/gui/tests/mobile-web.test.cjs index cb563966f..7a17c86b4 100644 --- a/internal/gui/tests/mobile-web.test.cjs +++ b/internal/gui/tests/mobile-web.test.cjs @@ -371,6 +371,13 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await current.locator("#claudeLeanRow").evaluate((r) => r.remove()); await current.waitForTimeout(350); } + // Replies' Claude Code's interactive mode row is new: until + // BASE_REF has it, the page is compared with the row taken + // out; claude-tui-setting.test.cjs covers the row. + if (view === "settings" && !baselineFile("app.js").includes("claudeTuiRow")) { + await current.locator("#claudeTuiRow").evaluate((r) => r.remove()); + await current.waitForTimeout(350); + } // A setting row's line wraps whole (arculongus on Discord): // until BASE_REF has that, the page is compared with the lines // held to one line as they were; settings-lines-wrap.test.cjs diff --git a/internal/settings/settings.go b/internal/settings/settings.go index 9ee34754d..4f3acf831 100644 --- a/internal/settings/settings.go +++ b/internal/settings/settings.go @@ -349,6 +349,12 @@ type Settings struct { // real Claude Code, its billing line and identity line kept; off, as by // default, the run is the shape every Claude Code run has. ClaudeLeanPrompt bool `json:"claudeLeanPrompt,omitempty"` + // ClaudePrintMode runs a Claude subscription's Claude Code as `claude + // -p` always. Off, as by default, a run is Claude Code's interactive + // mode, as a person runs it, where it can be (macOS and Linux, no + // images, safeguards or client cache marks): the plan counts a -p + // request at about twice an interactive one. + ClaudePrintMode bool `json:"claudePrintMode,omitempty"` // ClaudeRunsMost is how many Claude Code processes a Claude // subscription may have running at once: conversations' runs, those // waiting for a next turn or on tool results, and one-off tests and