claudetui: Claude Code's interactive mode on Windows, in a pseudo console

A Claude run on Windows was always claude -p, the entrypoint the plan
counts at about twice the interactive mode's. The helper now starts
Claude Code in a ConPTY there (child_windows.go): CreatePseudoConsole on
two pipes, CreateProcess with the console attribute and
STARTF_USESTDHANDLES with no handles. Without that flag a child takes
the helper's own standard handles (the bridge's pipes) and draws into
them, not the console. A .cmd claude is quoted by proc.Command as the -p
run's. Ending closes the console, then kills after 3s; the -p fallback
runs Claude Code as a child, as Windows has no exec. The pty code moved
to child_unix.go unchanged, and tui.go has no build tag.

Windows ends a run by killing its job, which no handler hears, so a
turn's images folder is now removed once its message is sent, and a
helper starting removes magpie-claude-images-* folders over an hour old
(dropLeftImages). The gateway's gate lets Windows through (WSL stays
-p), and the setting's text no longer says Windows is always -p
(en, zh, zh-TW, ja, de). Doc updated.

Run:
- go test ./internal/claudetui on macOS (mote), Linux (magpie-desktop
  WSL2) and Windows 11 26200 (xiaomi-gpu): ok. The fake Claude Code on
  Windows is a claude.cmd, its console made raw with SetConsoleMode.
  New: TestDropLeftImages, and TestShimPastesImages checks the folder is
  gone after its message.
- go test -run Claude ./internal/gateway on mote, and the TUI tests on
  Windows: ok.
- i18n-keys and claude-tui-setting (chromium and webkit, en/zh/ja/de,
  1100 and 420): 20 of 20 on the Windows box. On mote chromium passed
  and every webkit case timed out in browserType.launch, beside other
  sessions' GUI suites running for up to 20 hours (load 22).
- go vet -tags nogui of claudetui, gateway and cli for darwin, linux and
  windows; gofmt -l clean.
- Real account on xiaomi-gpu: a sandbox HOME gateway (port 3462) with
  the Claude Max account, real claude.exe 2.1.281, haiku-5-5. One tool
  call, two in one message, text then a call, and two image turns
  (twice): all right answers. 81 transcript rows, every one
  "entrypoint":"cli", no "-p" line in the log. Images noted as
  C:\Users\...\magpie-claude-images-*\image-N.png and no folder left.
  Killing the gateway ended its four resident helpers and claude.exe.
  The token wasn't refreshed; the copied credentials were deleted.
  (This ran before the 1809 check in start was added; the claudetui
  tests on Windows and GOOS=windows vet ran again after it: ok.)

Broken by hand: STARTF_USESTDHANDLES removed, TestShimTurnsInteractive
on Windows red (3 lines of 5 in 30s: the fake's drawing reached the
shim's stdout).

Not tried: an npm claude.cmd install with the real account (only the
fake .cmd), Windows 10 before 1809 (no CreatePseudoConsole: the start
checks for it and falls back to -p), a run ended mid-turn by the client
on Windows.
A stray "The system cannot find the path specified." showed once in the
Windows test output; it wasn't on the shim's stderr, and three reruns
didn't show it.
This commit is contained in:
yetone
2026-10-31 06:10:00 +08:00
parent c8f199695c
commit c59c547c5b
12 changed files with 428 additions and 123 deletions
+22 -8
View File
@@ -87,9 +87,9 @@ 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
By default a run on macOS, Linux and Windows 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`.
@@ -105,8 +105,19 @@ talks to it as it talks to `-p`: stream-json in and out. The helper:
--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;
- starts Claude Code in a pseudo-terminal of its own (200x50), no tmux,
and answers what it asks of the terminal. On macOS and Linux it is a
pty in a session of its own (`child_unix.go`). On Windows it is a
pseudo console (ConPTY, `child_windows.go`): `CreatePseudoConsole` on
two pipes, and `CreateProcess` with the console as an attribute and
`STARTF_USESTDHANDLES` with no handles, since without it a child
took the helper's own standard handles (the bridge's pipes) and drew
into them rather than the console (tried on Windows 11 26200). An npm
install's `claude.cmd` is run by cmd.exe with its arguments quoted as
the `-p` run's (`proc.Command`). Ending, the helper closes the console
(Claude Code is told as a closed window tells it) and kills it after
3s. Its `-p` fallback runs Claude Code as a child, since Windows has no
exec;
- 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`);
@@ -119,10 +130,13 @@ talks to it as it talks to `-p`: stream-json in and out. The helper:
before pasting the next piece; without that wait the second of two
images was lost. The transcript holds real image blocks, and Claude Code
notes each one's path to the model (`[Image: source: …]`). The folder
is removed when the helper ends, on SIGINT, SIGTERM and SIGHUP too:
is removed once its message is sent (Claude Code has read the files
by then), and when the helper ends, on SIGINT, SIGTERM and SIGHUP too:
magpie's own handler (`endProbesOnSignal`) let go of the signals for
this command (`leaveSignals`), since it re-raised SIGTERM and killed the
helper before it could end Claude Code and remove its files;
helper before it could end Claude Code and remove its files. Windows
ends a run by killing its job, which no handler hears, so a helper
starting removes such folders over an hour old (`dropLeftImages`);
- 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
@@ -159,7 +173,7 @@ 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;
- it is Claude Code in WSL;
- the request has safeguards, client cache marks, a JSON schema, an image
known only by its URL (`urlImages`: the helper pastes files, and has no
bytes of it), or words over 400KB (`tuiPromptMost`, images not counted),
+77
View File
@@ -0,0 +1,77 @@
//go:build darwin || linux
package claudetui
import (
"os"
"os/exec"
"syscall"
"time"
"golang.org/x/sys/unix"
)
// child is Claude Code, started in a pseudo-terminal.
type child struct{ cmd *exec.Cmd }
// endSignals are what the helper ends on, its Claude Code with it.
var endSignals = []os.Signal{syscall.SIGTERM, syscall.SIGINT, syscall.SIGHUP}
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)
}
}
// 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())
}
+186
View File
@@ -0,0 +1,186 @@
package claudetui
import (
"errors"
"fmt"
"os"
"os/exec"
"sync"
"syscall"
"time"
"unsafe"
"golang.org/x/sys/windows"
"github.com/yetone/magpie/internal/proc"
)
// child is Claude Code, started in a pseudo console (ConPTY): Windows' own
// terminal for a program that draws, as Windows Terminal runs one in.
type child struct {
proc windows.Handle
console windows.Handle
closeOnce sync.Once
}
// endSignals are what the helper ends on, its Claude Code with it: Ctrl+C,
// and its console closed. The gateway ends a run by killing its job, which
// no handler hears: the images folder is then left for another helper to
// remove (dropLeftImages).
var endSignals = []os.Signal{os.Interrupt, syscall.SIGTERM}
func (s *shim) start(path string, args []string) error {
// Windows 10 before 1809 has none, and x/sys panics calling it there
if err := windows.NewLazySystemDLL("kernel32.dll").NewProc("CreatePseudoConsole").Find(); err != nil {
return fmt.Errorf("no pseudo console on this Windows: %w", err)
}
// a .cmd (npm's shim) is run by cmd.exe, its arguments quoted as
// the -p run's are
cmd := proc.Command(path, args...)
if cmd.Err != nil {
return cmd.Err
}
line := windows.ComposeCommandLine(cmd.Args)
if cmd.SysProcAttr != nil && cmd.SysProcAttr.CmdLine != "" {
line = cmd.SysProcAttr.CmdLine
}
// what is typed goes in at inW, what Claude Code draws comes out at
// outR; the console holds the other ends
var inR, inW, outR, outW windows.Handle
if err := windows.CreatePipe(&inR, &inW, nil, 0); err != nil {
return err
}
if err := windows.CreatePipe(&outR, &outW, nil, 0); err != nil {
windows.CloseHandle(inR)
windows.CloseHandle(inW)
return err
}
var console windows.Handle
// wide, so a line of Claude Code's screen is a line
err := windows.CreatePseudoConsole(windows.Coord{X: 200, Y: 50}, inR, outW, 0, &console)
// the console has its own of these
windows.CloseHandle(inR)
windows.CloseHandle(outW)
in, out := os.NewFile(uintptr(inW), "conpty-in"), os.NewFile(uintptr(outR), "conpty-out")
if err != nil {
in.Close()
out.Close()
return fmt.Errorf("a pseudo console: %w", err)
}
h, err := startIn(console, cmd.Path, line, childEnv())
if err != nil {
windows.ClosePseudoConsole(console)
in.Close()
out.Close()
return err
}
s.pty = conpty{in: in, out: out}
s.proc, s.console = h, console
go func() {
_, _ = windows.WaitForSingleObject(h, windows.INFINITE)
var code uint32
if err := windows.GetExitCodeProcess(h, &code); err != nil {
s.exit = err
} else if code != 0 {
s.exit = fmt.Errorf("exit status %d", code)
}
close(s.exited)
}()
go s.read()
return nil
}
// startIn starts the program at app, with the command line line and the
// environment env, attached to console.
func startIn(console windows.Handle, app, line string, env []string) (windows.Handle, error) {
attrs, err := windows.NewProcThreadAttributeList(1)
if err != nil {
return 0, err
}
defer attrs.Delete()
// the attribute's value is the console's handle itself
if err := attrs.Update(windows.PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE, *(*unsafe.Pointer)(unsafe.Pointer(&console)), unsafe.Sizeof(console)); err != nil {
return 0, err
}
si := &windows.StartupInfoEx{ProcThreadAttributeList: attrs.List()}
si.Cb = uint32(unsafe.Sizeof(*si))
// standard handles of none: without this, the helper's own (the
// bridge's pipes) are Claude Code's, and it draws into them rather
// than the console (microsoft/terminal#11276)
si.Flags = windows.STARTF_USESTDHANDLES
appW, err := windows.UTF16PtrFromString(app)
if err != nil {
return 0, err
}
lineW, err := windows.UTF16PtrFromString(line)
if err != nil {
return 0, err
}
block, err := envBlock(env)
if err != nil {
return 0, err
}
var pi windows.ProcessInformation
if err := windows.CreateProcess(appW, lineW, nil, nil, false,
windows.EXTENDED_STARTUPINFO_PRESENT|windows.CREATE_UNICODE_ENVIRONMENT, block, nil, &si.StartupInfo, &pi); err != nil {
return 0, err
}
windows.CloseHandle(pi.Thread)
return pi.Process, nil
}
// envBlock is env as CreateProcess takes it: each NUL-ended, then a NUL.
func envBlock(env []string) (*uint16, error) {
var b []uint16
for _, e := range env {
u, err := windows.UTF16FromString(e)
if err != nil {
return nil, err
}
b = append(b, u...)
}
b = append(b, 0)
return &b[0], nil
}
// conpty is a pseudo console's two ends as one terminal.
type conpty struct{ in, out *os.File }
func (c conpty) Read(p []byte) (int, error) { return c.out.Read(p) }
func (c conpty) Write(p []byte) (int, error) { return c.in.Write(p) }
// closeConsole closes Claude Code's console, which tells it so, as closing
// a terminal window does (CTRL_CLOSE_EVENT). It returns at once: before
// Windows 11 24H2, ClosePseudoConsole waits for its output to be read.
func (s *shim) closeConsole() {
s.closeOnce.Do(func() {
go windows.ClosePseudoConsole(s.console)
})
}
// stop ends Claude Code: its console closed, then killed.
func (s *shim) stop() {
if s.proc == 0 {
return
}
s.closeConsole()
select {
case <-s.exited:
case <-time.After(3 * time.Second):
_ = windows.TerminateProcess(s.proc, 1)
}
}
// printMode runs Claude Code at path with the -p arguments pargs, on the
// helper's own input and output, and exits as it does: Windows has no
// exec, so the helper stays its parent.
func printMode(path string, pargs []string) error {
cmd := proc.Command(path, pargs...)
cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
err := cmd.Run()
var exit *exec.ExitError
if errors.As(err, &exit) {
os.Exit(exit.ExitCode())
}
return err
}
+21
View File
@@ -0,0 +1,21 @@
//go:build darwin || linux
package claudetui
import "golang.org/x/sys/unix"
// fakeRaw makes the fake Claude Code's terminal raw, as the real one's is: a
// paste is taken whole, and Enter outside one sends it.
func fakeRaw() {
if tio, err := unix.IoctlGetTermios(0, ioctlGetTermios); err == nil {
tio.Lflag &^= unix.ECHO | unix.ICANON
tio.Iflag &^= unix.ICRNL
_ = unix.IoctlSetTermios(0, ioctlSetTermios, tio)
}
}
// fakeScript is a script in dir that runs the test binary exe as the fake
// Claude Code, and its path.
func fakeScript(dir, exe string) (string, string) {
return dir + "/claude", "#!/bin/sh\nMAGPIE_TUI_TEST=claude exec '" + exe + "' \"$@\"\n"
}
+28
View File
@@ -0,0 +1,28 @@
package claudetui
import (
"path/filepath"
"golang.org/x/sys/windows"
)
// fakeRaw makes the fake Claude Code's console raw, as the real one's is:
// keys read as they come, VT sequences in (a paste's brackets) and out.
func fakeRaw() {
in, _ := windows.GetStdHandle(windows.STD_INPUT_HANDLE)
var m uint32
if windows.GetConsoleMode(in, &m) == nil {
m &^= windows.ENABLE_LINE_INPUT | windows.ENABLE_ECHO_INPUT | windows.ENABLE_PROCESSED_INPUT
_ = windows.SetConsoleMode(in, m|windows.ENABLE_VIRTUAL_TERMINAL_INPUT)
}
out, _ := windows.GetStdHandle(windows.STD_OUTPUT_HANDLE)
if windows.GetConsoleMode(out, &m) == nil {
_ = windows.SetConsoleMode(out, m|windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING)
}
}
// fakeScript is a batch file in dir that runs the test binary exe as the
// fake Claude Code, and its text: a .cmd, as npm installs Claude Code.
func fakeScript(dir, exe string) (string, string) {
return filepath.Join(dir, "claude.cmd"), "@set MAGPIE_TUI_TEST=claude\r\n@\"" + exe + "\" %*\r\n"
}
+42 -80
View File
@@ -1,5 +1,3 @@
//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
@@ -27,17 +25,13 @@ import (
"io"
"net/http"
"os"
"os/exec"
"os/signal"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"syscall"
"time"
"golang.org/x/sys/unix"
)
// how long Claude Code may take to show its prompt, a pasted message to
@@ -55,8 +49,10 @@ type shim struct {
outMu sync.Mutex
out io.Writer
pty *os.File
cmd *exec.Cmd
// pty is Claude Code's terminal: what it draws is read from it, and
// what is typed written to it
pty io.ReadWriter
child
sid string
// projects is Claude Code's projects folder, where it keeps the
// session's transcript (<projects>/<folder>/<sid>.jsonl)
@@ -127,8 +123,9 @@ func Run(args []string) error {
}
defer s.stop()
defer s.dropImages()
go dropLeftImages()
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGTERM, syscall.SIGINT, syscall.SIGHUP)
signal.Notify(sigs, endSignals...)
go func() {
<-sigs
s.stop()
@@ -178,58 +175,6 @@ func childEnv() []string {
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() {
@@ -239,10 +184,10 @@ func (s *shim) read() {
if n > 0 {
d := buf[:n]
if bytes.Contains(d, []byte("\x1b[6n")) {
_, _ = s.pty.Write([]byte("\x1b[1;1R"))
_, _ = io.WriteString(s.pty, "\x1b[1;1R")
}
if bytes.Contains(d, []byte("\x1b[c")) || bytes.Contains(d, []byte("\x1b[0c")) {
_, _ = s.pty.Write([]byte("\x1b[?62;c"))
_, _ = io.WriteString(s.pty, "\x1b[?62;c")
}
s.screenMu.Lock()
s.screen = append(s.screen, d...)
@@ -333,22 +278,22 @@ func (s *shim) ready() error {
answered++
yesAt = time.Time{}
s.clearScreen()
_, _ = s.pty.WriteString("\r")
_, _ = io.WriteString(s.pty, "\r")
case no >= 0:
yesAt = time.Time{}
if time.Since(downAt) >= time.Second {
downAt = time.Now()
_, _ = s.pty.WriteString("\x1b[B")
_, _ = io.WriteString(s.pty, "\x1b[B")
}
}
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")
_, _ = io.WriteString(s.pty, "\x1b")
case strings.Contains(p, "Choose the text style"):
s.clearScreen()
_, _ = s.pty.WriteString("\r")
_, _ = io.WriteString(s.pty, "\r")
case strings.Contains(p, "❯ "):
// drawn: a moment for its input to be listened to
time.Sleep(300 * time.Millisecond)
@@ -407,7 +352,9 @@ func (s *shim) input(r io.Reader) error {
"result": "this message can't be pasted into Claude Code's interactive mode: " + err.Error()})
continue
}
if err := s.send(pieces); err != nil {
err = s.send(pieces)
s.dropImages()
if err != nil {
return err
}
if m.UUID != "" {
@@ -497,7 +444,7 @@ func (s *shim) writeImage(source, mediaType, data string) (string, error) {
return "", fmt.Errorf("a %s image", mediaType)
}
if s.images == "" {
if s.images, err = os.MkdirTemp("", "magpie-claude-images-"); err != nil {
if s.images, err = os.MkdirTemp("", imagesPrefix+strconv.Itoa(os.Getpid())+"-"); err != nil {
return "", err
}
}
@@ -506,10 +453,32 @@ func (s *shim) writeImage(source, mediaType, data string) (string, error) {
return path, os.WriteFile(path, b, 0o600)
}
// dropImages removes the images pasted, once Claude Code has ended.
// dropImages removes the images pasted: once their message is in the
// transcript, Claude Code has them, and when the helper ends.
func (s *shim) dropImages() {
if s.images != "" {
_ = os.RemoveAll(s.images)
s.images = ""
}
}
// imagesPrefix names the folders images are written to, the helper's pid
// after it.
const imagesPrefix = "magpie-claude-images-"
// imagesLeft is how long an image folder is left before another helper
// removes it: one killed with its images still in the prompt, as Windows
// ends a run, can't remove its own.
const imagesLeft = time.Hour
// dropLeftImages removes the image folders helpers left, untouched for
// imagesLeft.
func dropLeftImages() {
m, _ := filepath.Glob(filepath.Join(os.TempDir(), imagesPrefix+"*"))
for _, d := range m {
if fi, err := os.Stat(d); err == nil && fi.IsDir() && time.Since(fi.ModTime()) > imagesLeft {
_ = os.RemoveAll(d)
}
}
}
@@ -579,7 +548,7 @@ func (s *shim) send(pieces []piece) error {
p.text = "."
}
s.clearScreen()
if _, err := s.pty.WriteString("\x1b[200~" + p.text + "\x1b[201~"); err != nil {
if _, err := io.WriteString(s.pty, "\x1b[200~"+p.text+"\x1b[201~"); err != nil {
return err
}
text = p.text
@@ -589,7 +558,7 @@ func (s *shim) send(pieces []piece) error {
}
time.Sleep(150 * time.Millisecond)
for try := 0; try < 4; try++ {
if _, err := s.pty.WriteString("\r"); err != nil {
if _, err := io.WriteString(s.pty, "\r"); err != nil {
return err
}
by := time.After(sentWait)
@@ -620,7 +589,7 @@ var imageShown = regexp.MustCompile(`\[Image #(\d+)\]`)
// before it. It returns the number shown.
func (s *shim) pasteImage(path string, after int) (int, error) {
s.clearScreen()
if _, err := s.pty.WriteString("\x1b[200~" + path + "\x1b[201~"); err != nil {
if _, err := io.WriteString(s.pty, "\x1b[200~"+path+"\x1b[201~"); err != nil {
return 0, err
}
by := time.After(pasteWait)
@@ -791,13 +760,6 @@ func interactiveArgs(pargs []string) []string {
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 {
-11
View File
@@ -1,11 +0,0 @@
//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")
}
+40 -12
View File
@@ -1,5 +1,3 @@
//go:build darwin || linux
package claudetui
import (
@@ -16,8 +14,6 @@ import (
"sync"
"testing"
"time"
"golang.org/x/sys/unix"
)
// The test binary is also the shim (MAGPIE_TUI_TEST=shim) and a fake
@@ -104,11 +100,7 @@ func fakeClaude(args []string) {
_ = os.MkdirAll(dir, 0o700)
// 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)
}
fakeRaw()
r := bufio.NewReader(os.Stdin)
if os.Getenv("FAKE_TRUST") == "1" {
fakeTrust(r)
@@ -197,7 +189,10 @@ func runShim(t *testing.T, env []string, pargs []string, lines []string, want in
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)
tmp := filepath.Join(home, "tmp")
_ = os.Mkdir(tmp, 0o700)
cmd.Env = append(os.Environ(), "MAGPIE_TUI_TEST=shim", "HOME="+home, "XDG_CACHE_HOME="+filepath.Join(home, "cache"), "LOCALAPPDATA="+filepath.Join(home, "cache"),
"TMPDIR="+tmp, "TMP="+tmp, "TEMP="+tmp, "CLAUDE_CONFIG_DIR="+cfg)
cmd.Env = append(cmd.Env, env...)
stdin, _ := cmd.StdinPipe()
stdout, _ := cmd.StdoutPipe()
@@ -246,8 +241,8 @@ func fakePath(t *testing.T) string {
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 {
p, script := fakeScript(t.TempDir(), exe)
if err := os.WriteFile(p, []byte(script), 0o700); err != nil {
t.Fatal(err)
}
return p
@@ -321,6 +316,39 @@ func TestShimPastesImages(t *testing.T) {
if !failed {
t.Fatalf("an image by its URL wasn't an error: %v", out)
}
// Claude Code has them once their message is in the transcript: the
// files are gone while the helper goes on
left, _ := filepath.Glob(filepath.Join(filepath.Dir(os.Getenv("MAGPIE_TUI_TEST_CFG")), "tmp", imagesPrefix+"*"))
if len(left) > 0 {
t.Fatalf("the images are left after their message: %v", left)
}
}
// A folder of images a killed helper left is removed by a later one after
// imagesLeft, and one in use isn't.
func TestDropLeftImages(t *testing.T) {
tmp := t.TempDir()
t.Setenv("TMPDIR", tmp)
t.Setenv("TMP", tmp)
t.Setenv("TEMP", tmp)
old, now := filepath.Join(tmp, imagesPrefix+"1-a"), filepath.Join(tmp, imagesPrefix+"2-b")
for _, d := range []string{old, now} {
if err := os.MkdirAll(d, 0o700); err != nil {
t.Fatal(err)
}
_ = os.WriteFile(filepath.Join(d, "image-1.png"), []byte("x"), 0o600)
}
then := time.Now().Add(-imagesLeft - time.Minute)
if err := os.Chtimes(old, then, then); err != nil {
t.Fatal(err)
}
dropLeftImages()
if _, err := os.Stat(old); !os.IsNotExist(err) {
t.Errorf("the folder left %s ago is still there (%v)", imagesLeft, err)
}
if _, err := os.Stat(now); err != nil {
t.Errorf("the folder in use was removed: %v", err)
}
}
func TestShimFallsBackToPrint(t *testing.T) {
+2 -2
View File
@@ -955,7 +955,7 @@ const tuiPromptMost = 400 << 10
// 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
// (ClaudePrintMode), on macOS, Linux and Windows, 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.
@@ -981,7 +981,7 @@ func claudePrintWhy(req *Request, binary claudeCLI, prompt []map[string]any) str
why string
}{
{!claudeTUIRuns, "no shim"},
{runtime.GOOS != "darwin" && runtime.GOOS != "linux", runtime.GOOS},
{runtime.GOOS != "darwin" && runtime.GOOS != "linux" && runtime.GOOS != "windows", runtime.GOOS},
{binary.wsl != nil, "Claude Code in WSL"},
{binary.path == "", "no Claude Code path"},
{len(req.Safeguards) > 0, "safeguards"},
+5 -5
View File
@@ -12,9 +12,9 @@ import (
"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.
// A Claude run is Claude Code's interactive mode on macOS, Linux and
// Windows, 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) })
@@ -25,7 +25,7 @@ func TestClaudeTUIChosen(t *testing.T) {
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"
on := runtime.GOOS == "darwin" || runtime.GOOS == "linux" || runtime.GOOS == "windows"
cases := []struct {
name string
req *Request
@@ -33,7 +33,7 @@ func TestClaudeTUIChosen(t *testing.T) {
prompt []map[string]any
print bool
want bool
why string // what is logged, on macOS and Linux
why string // what is logged, on macOS, Linux and Windows
}{
{"a plain turn", &Request{Messages: text("hi")}, here, prompt, false, on, ""},
{"turned off", &Request{Messages: text("hi")}, here, prompt, true, false, "the interactive mode is turned off"},
+1 -1
View File
@@ -21759,7 +21759,7 @@ function renderReplies(s, keep) {
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")));
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")));
const uval = el("div", "val");
uval.append(segs([["off", t("Off")], ["on", t("On")]], s.claudePrintMode ? "off" : "on",
(v) => savePrefs({ ...keep, claudePrintMode: v === "off" })));
+4 -4
View File
@@ -332,7 +332,7 @@ const I18N = {
"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 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": "Claude 订阅像人一样以交互模式运行 Claude Code,套餐对每次请求的计量约为 -p 的一半。关闭则以 claude -p 运行",
"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 时一样,自己换到它的备用模型",
@@ -4573,7 +4573,7 @@ const I18N = {
"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 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": "Claude 訂閱像人一樣以互動模式執行 Claude Code,方案對每次請求的計量約為 -p 的一半。關閉則以 claude -p 執行",
"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 時一樣,自己換到它的備用模型",
@@ -8783,7 +8783,7 @@ const I18N = {
"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 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": "Claude サブスクリプションは人と同じように Claude Code を対話モードで実行し、プランはリクエストを -p の約半分として数えます。オフにすると claude -p で実行します",
"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 のときと同じく、自分のフォールバックモデルに切り替えます",
@@ -13003,7 +13003,7 @@ const I18N = {
"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 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": "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",
"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",