claude: a subscription's run is Claude Code's interactive mode, -p only as the fallback
The owner (10-31): a Claude subscription ran `claude -p`, whose
requests Anthropic labels sdk-cli and counts at about twice the
interactive mode's cli (anthropics/claude-code#97074). Running the real
interactive Claude Code is what its terms describe and uses the plan as
a person does. Wanted inside magpie, on by default, with a way off.
`magpie claude-tui-helper <claude> <-p args>` (internal/claudetui)
stands where `claude -p` stood and speaks the same stream-json. It
turns the -p arguments into the interactive mode's (no -p, no
--dangerously-skip-permissions: --permission-mode default with only
mcp__magpie, and the WebSearch -p was given, allowed; --no-chrome;
--session-id or the --resume given), starts Claude Code in a
pseudo-terminal of its own (no tmux), pastes each message into its
prompt and presses Enter, and tells the session's transcript back as
-p's lines: whole assistant messages, an API error as the turn's error
result with its rate_limit_info, turn_duration as the result. Nothing
sets CLAUDE_CODE_ENTRYPOINT, and the user's ~/.claude and
~/.claude.json are never written. The folder-trust question is
answered only for magpie's own folder or a saved account's config
directory (MAGPIE_CLAUDE_TUI_TRUST).
A Claude Code that doesn't start or show its prompt in 45s becomes
`claude -p` on the same pid, its input still unread, so the turn is
answered all the same; that is remembered for 30 minutes
(<cache>/magpie/claude-tui-broken). An untrusted folder goes to -p
without the mark.
claudeTUI keeps -p for Windows and WSL, Settings › Models › Replies ›
Claude Code's interactive mode Off (claudePrintMode), safeguards,
client cache marks, a JSON schema, images and a first message over
400KB. A TUI run ends instead of taking an image turn, a rewind or an
effort change, and letGo doesn't take one back. The gateway's tests
run with claudeTUIRuns off: their binary has no claude-tui-helper.
docs/subsystems/claude-subscription-bridge.md has the section.
The core's scripts grow 725 bytes with the setting's row;
coreScriptBudget is raised to the exact size, 1,537,356, with no room
added.
Run (rebased on f2eb56c6b and its budget fix):
- mote: go vet of claudetui, gateway, cli, settings on darwin;
GOOS=windows of claudetui, gateway, cli; GOOS=linux of claudetui,
gateway; gofmt -l clean.
- mote: go test ./internal/claudetui: TestShimTurnsInteractive (a fake
interactive Claude Code in the PTY: two turns, a /help pasted as
words, the arguments it was given), TestShimFallsBackToPrint (failed
start marks broken; untrusted folder doesn't), TestShimTrustsWhenTold,
TestPasteable, TestTranslatorAPIError.
- mote: go test ./internal/gateway -run TestClaudeTUIChosen (plain,
off, WSL, safeguards, cache marks, schema, image, long prompt),
TestClaudeLean*, TestCleanClaudeEnv.
- mote: go test -timeout 45m ./internal/claudetui ./internal/cli
./internal/settings ./internal/gateway: all ok (gateway 524s).
go test -run Budget ./internal/gui: ok after the raise below.
- Linux (magpie-desktop): go test ./internal/claudetui ok natively,
the PTY's Linux ioctls among it. GOOS=linux go vet -tags nogui of
cli, gateway, claudetui, settings ok.
- Linux box, Playwright 1.62, chromium and webkit: claude-tui-setting
16/16, claude-lean-prompt-setting 16/16, i18n-keys 4/4, mobile-web
30/30 against 74f1df869's tree. mote's WebKit didn't launch (other
sessions' GUI suites, running 11-16h, held ~108 WebKit processes),
so the GUI ran there instead.
- Real Claude Code 2.1.314 on a real Claude account's magpie config dir,
haiku, through the built helper with the bridge's exact -p arguments
(an MCP server named magpie with one tool, --tools "",
--system-prompt-file, --thinking disabled, --effort low,
--thinking-display): the tool was called without a permission prompt
and its answer used; the system prompt's end token in every reply;
a second turn on the same run; a later run with --resume remembered
the first. All 18 transcript rows say "entrypoint":"cli". Startup to
init 0.7–1.5s, a haiku turn 1.4–4s. Two messages sent at once are
one turn, as Claude Code queues them.
Broken by hand:
- each claudeTUI condition taken out in turn (WSL, safeguards, cache
marks, schema, images, the setting, the 400KB bound): its case red.
The WSL case first passed with the check gone (its claudeCLI had no
path); given one, it is red without it.
- the trust check taken out of ready(): TestShimTrustsWhenTold red
(the run went to -p).
Not tried: a turn through a running gateway into the helper on a real
account (a sandbox HOME would copy the sign-in into a new keychain item
and refresh it apart from the live one); a ~400KB paste; Linux with a
real Claude Code; an API error from the real service (the translator
is tested on its rows). The full go test ./... did not run (mote was held by those suites);
the four packages this touches ran whole.
This commit is contained in:
@@ -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 <claude> <the -p arguments>`
|
||||
(`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 `<CLAUDE_CONFIG_DIR>/projects/*/<session>.jsonl` and tells each
|
||||
row as `-p` would (`translator`): assistant messages whole (no partial
|
||||
stream), a tool's result, a `<synthetic>` 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
|
||||
`<cache>/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
|
||||
|
||||
@@ -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"
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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 <synthetic> 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 <synthetic> 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 != "<synthetic>" || !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
|
||||
}
|
||||
@@ -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 (<projects>/<folder>/<sid>.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> [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)
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
@@ -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:
|
||||
// <line>"; 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":"<synthetic>","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)
|
||||
}
|
||||
}
|
||||
@@ -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":
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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",
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -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, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user