claudetui: an image goes into the interactive mode on Windows 10 as a long paste, not -p (ok123now on X, #5061)

ok123now (magpie v0.1.3901, Windows 10 LTSC 21H2, Claude Code 2.1.316,
Claude Desktop): text worked, one 64x64 PNG was a 502 every try, and the
client asked again without end.

Cause: the helper pastes an image as its file's path in bracketed-paste
marks. Windows 10's conhost (10.0.19041) drops the marks on the way in
(the reporter's lead; #5061 and #5205 measured it on 19044 and 19045),
so Claude Code got the path as typed words, the helper waited out
pasteWait and exited 1, and the gateway answered 502.

Fix:
- claudetui: Claude Code reads its console as VT input (mode 0x208, read
  from a real claude.exe 2.1.316) and takes one read of over 800
  characters as a paste with or without the marks ($X=800 in 2.1.316,
  q6=800 in 2.1.281), a path with spaces after it as the image alone. On
  Windows the path is sent padded with spaces to 900 characters, no
  marks: over 800, and under the 1024-byte blocks the same conhost loses
  of a longer write (#5205). Elsewhere it stays bracketed.
- If the interactive mode still doesn't take a message (an image, or a
  block it can't paste), the helper ends the turn with an error result
  beginning claudetui.Unpastable instead of exiting, the gateway asks it
  once as claude -p with the image itself, and remembers that for 12
  hours. A redo that can't run is a 400, not a 502, so no client loops.
- The reporter asked to keep images interactive: -p counts at about
  twice the plan quota and has none of the interactive run's cache. The
  -p reason (Routing chip, all four locales, and the log line) says so.

Run, at this head (rebased on 925bc7188):
- win-run (Windows 11 26200): ./internal/claudetui; every test passes
  but TestShimFirstMessageWaitsForTools, red on the old code too (#4810).
  TestShimPaddedImageTakenWithoutMarks 3 of 3, TestImagePasteWindowsLength.
- The helper on a real claude.exe 2.1.316 in a ConPTY (sandbox
  CLAUDE_CONFIG_DIR, ANTHROPIC_BASE_URL to a closed port): padded and
  bracketed, the image reached the transcript as an image. A direct
  probe: bracketed and padded paths shown as [Image #1], a bare path
  stays words.
- wsl-run: ./internal/claudetui ok; go vet of claudetui and gateway on
  Linux and Windows.
- GUI: routing-entry, routing-intent-entry, claude-mode,
  claude-tui-setting, i18n-keys, i18n-en-no-cjk in Chromium and WebKit
  (Linux), 112/112.
- Full suite, wsl-run (Linux), go test -tags nogui -timeout 45m ./...:
  every package ok (gateway 883s, claudetui 164s) but internal/usage's
  TestRequestStateKeptAcrossACatalogFetchedAgain, a catalog CacheKey red
  already filed as #6572 and untouched here. The mote suite stayed queued
  behind other sessions' runs, so the suite ran on Linux.

Broken by hand: TestShimPaddedImageTakenWithoutMarks on the old code
(bracketed paste, fake console dropping the marks) is red: the shim
wrote 1 line of 3 in 30s. Its bracketed half is the old behaviour and
ends in an Unpastable error result, not an exit.

Not tried: a real Windows 10 21H2 console (no such box here); the -p
redo with a real Claude subscription. Long pasted text on Windows 10
still loses 1 KB blocks (#5205); this doesn't change that.
This commit is contained in:
yetone
2026-11-14 10:48:55 +08:00
parent 925bc7188b
commit 8ed2ae030c
10 changed files with 414 additions and 36 deletions
+46 -2
View File
@@ -407,7 +407,7 @@ path or isn't macOS, Linux or Windows. Nothing a request asks is refused
any more (`claudePrint` keeps an image known by its URL, which
`serveClaudeSubscription` has downloaded before any run, below).
The one exception to "nothing runs as `-p`" with it On is a turn Anthropic
The first exception to "nothing runs as `-p`" with it On is a turn Anthropic
refuses in the interactive mode as a third-party app's: a 400 "Third-party
apps now draw from your extra usage" (#4503), or on a Team or
Enterprise workspace "draw from extra usage" with no "your" (#5645; both
@@ -428,6 +428,49 @@ turn whose reply had begun, and Off are never asked again
(`thirdPartyRefused` says why). Settings' own value is not changed.
`claude_tui_refusal_test.go` holds each case.
A second exception is a turn whose message the interactive mode didn't
take (ok123now on X: magpie v0.1.3901, Windows 10 LTSC 21H2, Claude Code
2.1.316; text worked, a 64×64 PNG was a 502 every try, and the client
asked again and again). The helper pastes an image as its file's path,
and Claude Code takes it as an image only when the paste reaches it as a
paste; a console that passes it on as typing leaves the path as words,
and the helper waited out `pasteWait` and ended. The reporter's lead was
a console that drops the bracketed-paste marks. Claude Code on Windows
reads its console as VT input (`ENABLE_VIRTUAL_TERMINAL_INPUT`; mode
0x208 read from a real claude.exe 2.1.316), and it takes one read of over
800 characters as a paste with or without the marks (`$X=800` in 2.1.316,
`q6=800` in 2.1.281), a path with spaces after it as the image alone.
Windows 10's conhost (10.0.19041) does drop the marks on the way in
(#5061, #5205, measured on 19044 and 19045), and it loses 1024-byte
blocks of a longer write (#5205). So on Windows the helper sends the
path with spaces after it up to 900 characters, over Claude Code's 800
and under 1024 bytes, and no marks (`imagePad`, `imagePaste`,
`TestImagePasteWindowsLength`); elsewhere it stays bracketed. With a
real claude.exe 2.1.316 in a ConPTY on Windows 11 26200, the bracketed
path and the padded one were each taken as `[Image #1]`, and the bare
path with no marks stayed words, as the reporter saw; the helper itself
on that claude.exe, padded and bracketed, put the image in the
transcript. Windows 10 itself is not tried; the padded path doesn't
need the marks. Long pasted text there still loses blocks (#5205),
which this doesn't change. If the interactive mode still doesn't take the image, the
turn goes to `-p` as below, which the plan counts at about twice the
interactive mode's and which starts without the interactive run's
cache; the Routing chip's reason says so. Then the helper answers such a
turn with an error result beginning `claudetui.Unpastable` (the words
`claudetui.ImageNotTaken` for the image; a block it can't paste begins
the same), and the helper ends. With nothing of the reply said, `relay`
hands it back as `redoAsPrint` and the turn is asked again once as `-p`,
which is sent the image itself (`unpastedSaid`, `Request.unpasted`,
`claudePrint` code `unpasted`). An image not taken is kept on the bridge
for 12 hours (`subscriptionBridge.unpasted`, `unpastedFor`): this
machine's turns with an image anywhere in their messages start as `-p`
then, and text alone is still the interactive mode's. When the redo can't
run (Off meanwhile, the client gone) the failure is a 400, not a 502
(`bridgeFailed`), so neither the client nor the fallback asks it again.
`claude_tui_unpasted_test.go` holds each case, and
`TestShimPaddedImageTakenWithoutMarks` the padded paste on a console that
drops the marks.
The other exception is Claude Code's auto mode classifier when its own
cache marks keep a long transcript (#5585, #5655; `keptByPrint`,
`claudePrint` code `cache-marks`). The classifier is asked afresh each
@@ -2044,7 +2087,8 @@ Each request the bridge answers notes how its run started: `startRun` calls
last mode and so says nothing of one request. The note rides the request's
context (`withEntry`, `claude_entry.go`) and `serve` copies it onto the try
(`Try.Entry` "tui" or "print", `Try.EntryWhy` the `claudePrint` code that
chose -p: off, os, missing, no-shim, image, third-party, cache-marks). The
chose -p: off, os, missing, no-shim, image, third-party, unpasted,
cache-marks). The
Routing page's request row shows a TUI or -p chip with the reason in its
title (`entryNote` in the routing plugin's client.js), so the plan cost of
a request can be told from how it ran (Anotiaww on X,
+3
View File
@@ -67,3 +67,6 @@ func (s *shim) stop() {
_ = syscall.Kill(-s.cmd.Process.Pid, syscall.SIGKILL)
}
}
// imagePadOS: a terminal here passes the bracketed-paste marks (imagePad).
const imagePadOS = 0
+6
View File
@@ -169,3 +169,9 @@ func (s *shim) stop() {
_ = windows.TerminateProcess(s.proc, 1)
}
}
// imagePadOS: a pseudo console may drop the bracketed-paste marks, so an
// image's path is sent as a read long enough to be a paste, over 800
// characters and under the 1024 bytes Windows 10's conhost can lose
// (imagePad).
const imagePadOS = 900
+53 -3
View File
@@ -763,11 +763,19 @@ func (s *shim) input(r io.Reader) error {
pieces, err := s.userPieces(m.Message.Content)
if err != nil {
s.emit(map[string]any{"type": "result", "subtype": "error_during_execution", "is_error": true, "session_id": s.sid,
"result": "this message can't be pasted into Claude Code's interactive mode: " + err.Error()})
"result": Unpastable + err.Error()})
continue
}
err = s.send(pieces)
s.dropImages()
var unpasted *imageUnpasted
if errors.As(err, &unpasted) {
// the prompt holds the path as words: the turn is told
// it failed, for the bridge to ask it as claude -p, and
// this Claude Code ends with it
s.emit(map[string]any{"type": "result", "subtype": "error_during_execution", "is_error": true, "session_id": s.sid,
"result": Unpastable + err.Error()})
}
if err != nil {
return err
}
@@ -1362,7 +1370,7 @@ func (s *shim) path(path string) string {
// returns the number shown.
func (s *shim) pasteImage(path string, after int) (int, error) {
s.clearScreen()
if _, err := io.WriteString(s.pty, "\x1b[200~"+path+"\x1b[201~"); err != nil {
if _, err := io.WriteString(s.pty, imagePaste(path, imagePad)); err != nil {
return 0, err
}
by := time.After(pasteWait)
@@ -1374,13 +1382,55 @@ func (s *shim) pasteImage(path string, after int) (int, error) {
case <-s.changed:
case <-time.After(100 * time.Millisecond):
case <-by:
return 0, fmt.Errorf("Claude Code did not take an image pasted as its path: %s", s.lastScreen())
return 0, &imageUnpasted{s.lastScreen()}
case <-s.exited:
return 0, fmt.Errorf("Claude Code ended (%v): %s", s.exit, s.lastScreen())
}
}
}
// imagePad is how long an image's pasted path is made with spaces after
// it, sent with no bracketed-paste marks: 0 brackets it. Claude Code takes
// one read of over 800 characters as a paste with or without the marks
// (2.1.281 and 2.1.316), and a path with spaces after it as the image
// alone. On Windows Claude Code reads its console as VT input
// (ENABLE_VIRTUAL_TERMINAL_INPUT, mode 0x208), and Windows 10's conhost
// (10.0.19041) drops the marks on the way in, leaving the path as words
// (ok123now on X, Windows 10 LTSC 21H2; #5061, #5205), so there it is sent
// padded. The same conhost loses 1024-byte blocks of a longer write
// (#5205), so the padded path stays under that.
var imagePad = imagePadOS
// imagePaste is what is written to paste an image's path: bracketed, or
// with spaces after it up to pad characters, one at least.
func imagePaste(path string, pad int) string {
if pad == 0 {
return "\x1b[200~" + path + "\x1b[201~"
}
return path + strings.Repeat(" ", max(1, pad-utf8.RuneCountInString(path)))
}
// Unpastable begins the error a turn ends in when its message can't be
// pasted into the interactive mode: a block it doesn't take, or an image
// whose path Claude Code didn't take as an image (imageUnpasted). The
// bridge asks such a turn again as claude -p, which is sent the image
// itself (ok123now on X: a 64x64 PNG on Windows 10 LTSC 21H2 was answered
// 502, and the client asked again and again).
const Unpastable = "this message can't be pasted into Claude Code's interactive mode: "
// imageUnpasted is an image's path pasted that the prompt never showed
// taken as an image within pasteWait: left as words, as a console whose
// pasting Claude Code can't tell from typing leaves it.
type imageUnpasted struct{ screen string }
// ImageNotTaken begins imageUnpasted's words: what the bridge keeps, for
// the machine's next turns with images to run as claude -p.
const ImageNotTaken = "Claude Code did not take an image pasted as its path"
func (e *imageUnpasted) Error() string {
return ImageNotTaken + ": " + e.screen
}
// imageTaken is the number of the image the prompt shows taken, numbered
// past after: drawn since the paste, or ending the prompt as the screen
// shows it (prompt). 0 while it shows none.
+100 -20
View File
@@ -18,6 +18,7 @@ import (
"syscall"
"testing"
"time"
"unicode/utf8"
)
// The test binary is also the shim (MAGPIE_TUI_TEST=shim) and a fake
@@ -27,6 +28,10 @@ import (
func TestMain(m *testing.M) {
switch os.Getenv("MAGPIE_TUI_TEST") {
case "shim":
// FAKE_IMAGE_PAD: imagePad, as another system's
if pad := os.Getenv("FAKE_IMAGE_PAD"); pad != "" {
imagePad, _ = strconv.Atoi(pad)
}
if err := Run(os.Args[1:]); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
@@ -349,6 +354,31 @@ func fakeClaude(args []string) {
}
take(p, draw)
}
// pasteEnded takes in a paste that has ended
pasteEnded := func(p string) {
mu.Lock()
taking = true
fmt.Print("\r❯ " + drawn.String())
mu.Unlock()
// FAKE_NO_IMAGE: an image's path pasted stays words, as a
// console whose pastes Claude Code can't tell from typing
// leaves it (ok123now on X, Windows 10 LTSC 21H2)
if b, err := os.ReadFile(strings.TrimSpace(p)); err == nil && strings.HasPrefix(filepath.Base(strings.TrimSpace(p)), "image-") && os.Getenv("FAKE_NO_IMAGE") != "1" {
go func() {
time.Sleep(200 * time.Millisecond)
mu.Lock()
defer mu.Unlock()
pasted++
take(fmt.Sprintf("[Image #%d:%s]", pasted, b), fmt.Sprintf("[Image #%d]", pasted))
}()
return
}
if namesImage.MatchString(p) {
time.AfterFunc(nameWait, func() { takeText(p) })
return
}
takeText(p)
}
// retry is what an "r" draws while /usage's panel says it couldn't
// load the figures, nil when it says nothing of the kind
var retry []byte
@@ -363,35 +393,28 @@ func fakeClaude(args []string) {
if _, err := io.ReadFull(r, seq); err != nil {
return
}
// FAKE_DROP_MARKS: the console drops the bracketed-paste
// marks, as ok123now's Windows 10 LTSC 21H2 is thought to
if os.Getenv("FAKE_DROP_MARKS") == "1" {
continue
}
pasting = string(seq) == "[200~"
if pasting {
paste.Reset()
continue
}
p := paste.String()
mu.Lock()
taking = true
fmt.Print("\r❯ " + drawn.String())
mu.Unlock()
if b, err := os.ReadFile(p); err == nil && strings.HasPrefix(filepath.Base(p), "image-") {
go func() {
time.Sleep(200 * time.Millisecond)
mu.Lock()
defer mu.Unlock()
pasted++
take(fmt.Sprintf("[Image #%d:%s]", pasted, b), fmt.Sprintf("[Image #%d]", pasted))
}()
continue
}
if namesImage.MatchString(p) {
time.AfterFunc(nameWait, func() { takeText(p) })
continue
}
takeText(p)
pasteEnded(paste.String())
continue
case pasting:
paste.WriteByte(c)
continue
case c != '\r' && c != 0x1b && r.Buffered() >= 800:
// a read of over 800 characters is a paste, marked or not, as
// Claude Code takes one
b := make([]byte, r.Buffered())
_, _ = io.ReadFull(r, b)
pasteEnded(string(c) + string(b))
continue
case c == 'r' && retry != nil:
fakeFrames(retry)
retry = nil
@@ -682,6 +705,63 @@ func TestShimPastesImages(t *testing.T) {
}
}
// An image whose path Claude Code leaves as words ends the turn in an
// error that begins Unpastable, which the bridge asks again as claude -p
// (ok123now on X): it was an exit with no result, a 502 the client asked
// again and again. The helper ends with it, the prompt holding the path.
func TestShimImageNotTakenIsUnpastable(t *testing.T) {
img := `[{"type":"text","text":"what colour?"},{"type":"image","source":{"type":"base64","media_type":"image/png","data":"` +
base64.StdEncoding.EncodeToString([]byte("red")) + `"}}]`
out := runShim(t, []string{"FAKE_NO_IMAGE=1"}, append([]string{fakePath(t)}, pArgs...), []string{img}, 2)
if out[1]["type"] != "result" || out[1]["is_error"] != true || !strings.HasPrefix(fmt.Sprint(out[1]["result"]), Unpastable+ImageNotTaken) {
t.Fatalf("the turn ended %v, want an error beginning %q", out[1], Unpastable+ImageNotTaken)
}
}
// An image's path sent padded, with no bracketed-paste marks, is taken as
// the image on a console that drops the marks, as Claude Code takes a read
// of over 800 characters as a paste; bracketed, it stays words there
// (ok123now on X, Windows 10 LTSC 21H2). Windows sends it padded.
func TestShimPaddedImageTakenWithoutMarks(t *testing.T) {
img := `[{"type":"text","text":"what colour?"},{"type":"image","source":{"type":"base64","media_type":"image/png","data":"` +
base64.StdEncoding.EncodeToString([]byte("red")) + `"}}]`
out := runShim(t, []string{"FAKE_DROP_MARKS=1", "FAKE_IMAGE_PAD=900"}, append([]string{fakePath(t)}, pArgs...), []string{img}, 3)
var said string
for _, m := range out[1:] {
if m["type"] == "assistant" {
b, _ := json.Marshal(m["message"])
said = string(b)
}
}
if !strings.Contains(said, `[Image #1:red]`) || strings.Contains(said, imagesPrefix) {
t.Fatalf("Claude Code was sent %s, want the image taken: %v", said, out)
}
bracketed := runShim(t, []string{"FAKE_DROP_MARKS=1", "FAKE_IMAGE_PAD=0"}, append([]string{fakePath(t)}, pArgs...), []string{img}, 2)
if r := bracketed[1]; r["type"] != "result" || r["is_error"] != true || !strings.HasPrefix(fmt.Sprint(r["result"]), Unpastable+ImageNotTaken) {
t.Fatalf("a bracketed path on a console that drops the marks ended %v, want %q", r, Unpastable+ImageNotTaken)
}
}
// Windows' padded path is one read of over 800 characters, which Claude
// Code takes as a paste, and under the 1024-byte blocks Windows 10's
// conhost loses of a longer write (#5205), for a short path, a long one and
// one with a user name in Chinese.
func TestImagePasteWindowsLength(t *testing.T) {
for _, path := range []string{
`C:\x\image-1.png`,
`C:\Users\administrator\AppData\Local\Temp\magpie-claude-images-123456-987654321\image-12.png`,
`C:\Users\张三丰\AppData\Local\Temp\magpie-claude-images-123456-987654321\image-1.png`,
} {
w := imagePaste(path, 900)
if n := utf8.RuneCountInString(w); n <= 800 || len(w) >= 1024 || strings.TrimRight(w, " ") != path || strings.Contains(w, "\x1b") {
t.Errorf("%s padded to %d characters, %d bytes: %q", path, n, len(w), w)
}
}
if w := imagePaste(`C:\x\image-1.png`, 0); w != "\x1b[200~C:\\x\\image-1.png\x1b[201~" {
t.Errorf("unpadded = %q, want the path bracketed", w)
}
}
// Words with a line that names an image file ("foo.png" in an ls) are
// taken in a moment after they are pasted, and an image pasted meanwhile
// that is taken in first lets Enter send the message without them. Each
+72 -11
View File
@@ -102,6 +102,10 @@ type subscriptionBridge struct {
// refused in the interactive mode as a third-party app's, and when:
// their turns run as claude -p until thirdPartyFor has passed (#4503)
thirdParty sync.Map
// unpasted is when, in unix nanoseconds, this machine's interactive
// Claude Code last didn't take an image pasted into it: turns with
// images run as claude -p until unpastedFor has passed (ok123now)
unpasted atomic.Int64
}
// untrustedFor is how long a caller's folder Claude Code asked to trust
@@ -1210,7 +1214,7 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model,
// runs them interactively. A run it can't take is refused, never made
// -p: a refused request never ran, and isn't the last run
tui, code := claudeTUI(req, binary)
if !tui && code != "off" && code != "no-shim" && code != thirdPartyCode && code != cacheMarksCode {
if !tui && code != "off" && code != "no-shim" && code != thirdPartyCode && code != unpastedCode && code != cacheMarksCode {
cleanup()
return nil, nil, &tuiRefusal{claudeTUIErr(claudeNotTUIWhy(req, binary))}
}
@@ -1524,6 +1528,7 @@ func claudePrint(req *Request, binary claudeCLI) (code, why string) {
}{
{urlImages(req.Messages) > 0, "image", "an image known by its URL"},
{req.tuiRefused, thirdPartyCode, "Anthropic refused this agent's system prompt in the interactive mode as a third-party app's"},
{req.unpasted, unpastedCode, "Claude Code's interactive mode here didn't take this message, or an image pasted into it; the plan counts a -p run at about twice the interactive mode's, and it starts without the interactive run's cache"},
{req.clientCache.keptAsPrint(), cacheMarksCode, fmt.Sprintf("the client's cache marks keep %dKB of history, which a fresh interactive run writes again each call", markedHistory(req)>>10)},
} {
if c.is {
@@ -1833,7 +1838,7 @@ func claudeTUIOn() bool {
// A -p run made for such a prompt goes on with its turns, as a -p run
// from before the interactive mode was turned on doesn't.
func wantTUI(req *Request) bool {
return claudeTUIOn() && !req.tuiRefused && !req.clientCache.keptAsPrint()
return claudeTUIOn() && !req.tuiRefused && !req.unpasted && !req.clientCache.keptAsPrint()
}
// claudeNotTUIWhy is why a run isn't the interactive mode.
@@ -7072,14 +7077,15 @@ var ratelimitWindows = map[string]string{
// on them.
func (s *Server) serveSubscription(w http.ResponseWriter, r *http.Request, from provider.Protocol, name, model, owner string, body []byte, usage *Usage,
start func(ctx context.Context, req *Request) (*subscriptionRun, <-chan Event, error)) (int, string) {
return s.serveSubscriptionAs(w, r, from, name, model, owner, body, usage, start, false)
return s.serveSubscriptionAs(w, r, from, name, model, owner, body, usage, start, "")
}
// serveSubscriptionAs is serveSubscription, asPrint for the turn asked
// again as claude -p after the interactive mode's run was refused as a
// third-party app's with nothing of the reply said (redoAsPrint).
// serveSubscriptionAs is serveSubscription, redo the code of a turn asked
// again as claude -p after the interactive mode's run failed with nothing
// of the reply said (redoAsPrint): thirdPartyCode, refused as a
// third-party app's, or unpastedCode, its message not taken there.
func (s *Server) serveSubscriptionAs(w http.ResponseWriter, r *http.Request, from provider.Protocol, name, model, owner string, body []byte, usage *Usage,
start func(ctx context.Context, req *Request) (*subscriptionRun, <-chan Event, error), asPrint bool) (int, string) {
start func(ctx context.Context, req *Request) (*subscriptionRun, <-chan Event, error), redo string) (int, string) {
var req *Request
var err error
if name == "Claude Code" && wantsClientCache(r, from) {
@@ -7142,13 +7148,25 @@ func (s *Server) serveSubscriptionAs(w http.ResponseWriter, r *http.Request, fro
// interactive mode as a third-party app's runs as claude -p, which is
// served it: asked again after the refusal, or of a prompt refused
// within thirdPartyFor (#4503)
if name == "Claude Code" && claudeTUIOn() && (asPrint || s.subscription.tuiRefused(req)) {
if name == "Claude Code" && claudeTUIOn() && (redo == thirdPartyCode || s.subscription.tuiRefused(req)) {
req.tuiRefused = true
if req.clientCache != nil {
req.clientCache.print = true
}
}
if name == "Claude Code" && claudeTUIOn() && !req.tuiRefused && keptByPrint(req) {
// a turn whose message the interactive mode didn't take runs as
// claude -p, which is sent it whole: asked again after that failure,
// or, with images, on a machine whose interactive Claude Code didn't
// take an image pasted into it within unpastedFor (ok123now on X:
// Windows 10 LTSC, every image turn a 502 the client asked again)
if name == "Claude Code" && claudeTUIOn() && !req.tuiRefused &&
(redo == unpastedCode || countImages(req.Messages) > 0 && s.subscription.imagesUnpasted()) {
req.unpasted = true
if req.clientCache != nil {
req.clientCache.print = true
}
}
if name == "Claude Code" && claudeTUIOn() && !req.tuiRefused && !req.unpasted && keptByPrint(req) {
// the classifier's marks keep more than its fresh interactive
// run would write again each call: claude -p keeps them
req.clientCache.print, req.clientCache.kept = true, true
@@ -7375,10 +7393,18 @@ func (s *Server) serveSubscriptionAs(w http.ResponseWriter, r *http.Request, fro
if req.interactive && thirdPartyIn(msg) {
s.subscription.refusedTUI(req)
}
if req.interactive && strings.Contains(msg, claudetui.ImageNotTaken) {
s.subscription.unpasted.Store(time.Now().UnixNano())
}
if code == redoAsPrint && unpastedSaid(name, msg) {
gone()
log.Printf("claude: the interactive mode didn't take a turn's message on %s, with nothing of the reply said: asked again as claude -p, which the plan counts at about twice the interactive mode's, with none of its cache (%.200s)", req.Model, msg)
return s.serveSubscriptionAs(w, r, from, name, model, owner, body, usage, start, unpastedCode)
}
if code == redoAsPrint {
gone()
log.Printf("claude: Anthropic refused an interactive-mode turn on %s as a third-party app's, with nothing of the reply said: asked again as claude -p (#4503)", req.Model)
return s.serveSubscriptionAs(w, r, from, name, model, owner, body, usage, start, true)
return s.serveSubscriptionAs(w, r, from, name, model, owner, body, usage, start, thirdPartyCode)
}
return code, msg
}
@@ -7410,6 +7436,10 @@ func bridgeFailed(name, msg string, status int) (int, string) {
return status, msg
case quotaSaid(msg):
return 429, msg
case unpastedSaid(name, msg):
// the same message fails the same way on every account and on
// every try: a 502 was asked again and again (ok123now on X)
return 400, msg
case name == "Claude Code" && tooLong(400, msg):
return 400, msg + " (Claude Code's own check, before Anthropic was asked: it holds a conversation to its own limit for the account, " +
"200K once Anthropic has said the account needs extra usage for long context. " +
@@ -7497,8 +7527,39 @@ const redoAsPrint = -4503
// code and msg, back as redoAsPrint: Anthropic's third-party refusal, the
// user's interactive mode still on (Off, every run is -p already), and the
// client still waiting.
//
// So is a message the interactive mode didn't take (unpastedSaid): an
// image whose pasted path Claude Code left as words, as a console that
// doesn't pass pasting through leaves it, or a block it doesn't paste.
// claude -p is sent the message whole.
func redoable(r *http.Request, name string, req *Request, code int, msg string) bool {
return req.interactive && !req.tuiRefused && thirdPartySaid(name, code, msg) && claudeTUIOn() && r.Context().Err() == nil
return req.interactive && !req.tuiRefused && !req.unpasted && (thirdPartySaid(name, code, msg) || unpastedSaid(name, msg)) &&
claudeTUIOn() && r.Context().Err() == nil
}
// unpastedSaid is whether a Claude Code run's failure is the interactive
// mode's helper not getting the turn's message into Claude Code
// (claudetui.Unpastable).
func unpastedSaid(name, msg string) bool {
return name == "Claude Code" && strings.Contains(msg, claudetui.Unpastable)
}
// unpastedCode is claudePrint's code for a run that is claude -p because
// the interactive mode didn't take its message, or, with images, an image
// on this machine within unpastedFor.
const unpastedCode = "unpasted"
// unpastedFor is how long turns with images run as claude -p after this
// machine's interactive Claude Code didn't take an image pasted into it:
// a console that doesn't pass pasting through stays so, and each try
// costs a Claude Code's start and pasteWait.
const unpastedFor = 12 * time.Hour
// imagesUnpasted is whether this machine's interactive Claude Code didn't
// take an image pasted into it within unpastedFor.
func (b *subscriptionBridge) imagesUnpasted() bool {
at := b.unpasted.Load()
return at != 0 && time.Since(time.Unix(0, at)) < unpastedFor
}
// thirdPartyFor is how long an agent's system prompt Anthropic refused in
@@ -0,0 +1,124 @@
package gateway
import (
"encoding/base64"
"net/http/httptest"
"strings"
"testing"
"github.com/yetone/magpie/internal/claudetui"
"github.com/yetone/magpie/internal/provider"
)
// tuiUnpastedResult is what the interactive mode's helper answers a turn
// whose image Claude Code left as words (ok123now on X: Windows 10 LTSC
// 21H2, a 64x64 PNG). Its path has no backslash: macOS's sh echoes one
// as an escape.
var tuiUnpastedResult = `{"type":"result","subtype":"error_during_execution","is_error":true,"result":"` +
claudetui.Unpastable + claudetui.ImageNotTaken + `: > C:/Users/me/AppData/Local/Temp/image-1.png"}`
// unpastedHarness is tuiThirdPartyHarness whose interactive Claude Code
// fails every turn as one whose image it didn't take.
func unpastedHarness(t *testing.T) (*resumeHarness, string) {
t.Helper()
tuiThirdPartyText = strings.ReplaceAll(tuiUnpastedResult, "'", `'"'"'`)
t.Cleanup(func() { tuiThirdPartyText = tuiThirdPartyRefusal })
return tuiThirdPartyHarness(t, "", "")
}
// askImage asks h's Claude subscription a first turn with one PNG, or
// with text alone.
func askImage(t *testing.T, h *resumeHarness, image, stream bool) (int, string, string, Usage) {
t.Helper()
content := `"what is it?"`
if image {
content = `[{"type":"image","source":{"type":"base64","media_type":"image/png","data":"` +
base64.StdEncoding.EncodeToString([]byte("\x89PNG\r\n\x1a\nred")) + `"}},{"type":"text","text":"what colour?"}]`
}
s := ""
if stream {
s = `"stream":true,`
}
body := `{"model":"claude-sonnet-5","max_tokens":100,` + s + `"messages":[{"role":"user","content":` + content + `}]}`
rec := httptest.NewRecorder()
var u Usage
code, msg := h.s.serveClaudeSubscription(rec, httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body)), provider.Anthropic, h.p, "claude-sonnet-5", []byte(body), &u)
return code, msg, rec.Body.String(), u
}
// An image turn the interactive mode didn't take, nothing of its reply
// said, is asked again once as claude -p, which is sent the image, and the
// client has its answer (ok123now on X). Before, it had a 502, asked
// again, and had it again, and the conversation went no further.
func TestClaudeTUIUnpastedImageRedoneAsPrint(t *testing.T) {
for _, stream := range []bool{false, true} {
t.Run(map[bool]string{false: "whole", true: "stream"}[stream], func(t *testing.T) {
h, started := unpastedHarness(t)
code, msg, body, u := askImage(t, h, true, stream)
if code != 200 || !strings.Contains(body, "ok") || strings.Contains(body, claudetui.Unpastable) || u.ErrType != "" {
t.Fatalf("%d %.300s %.400s %q", code, msg, body, u.ErrType)
}
if n := helperStarts(started); n != 1 {
t.Fatalf("the interactive mode started %d times, want once", n)
}
runs := h.runs()
if len(runs) != 2 {
t.Fatalf("%d runs, want two: the interactive mode's, then claude -p", len(runs))
}
sent := 0
for _, log := range runs {
if strings.Contains(log, `"type":"image"`) {
sent++
}
}
// the interactive mode's fake logs nothing of what it was told
if sent != 1 {
t.Fatalf("the image went to %d runs, want claude -p's: %v", sent, runs)
}
})
}
}
// Once this machine's interactive Claude Code didn't take an image, the
// next turns with images, of any conversation, run as claude -p from the
// start; a turn of text alone is still the interactive mode's.
func TestClaudeTUIUnpastedImagesRunAsPrint(t *testing.T) {
h, started := unpastedHarness(t)
if code, msg, body, _ := askImage(t, h, true, false); code != 200 {
t.Fatalf("%d %.300s %.300s", code, msg, body)
}
if code, msg, body, _ := askImage(t, h, true, true); code != 200 || !strings.Contains(body, "ok") {
t.Fatalf("%d %.300s %.300s", code, msg, body)
}
if n := helperStarts(started); n != 1 {
t.Fatalf("the interactive mode started %d times, want once: images run as -p here now", n)
}
if runs := len(h.runs()); runs != 3 {
t.Fatalf("%d runs, want 3", runs)
}
askImage(t, h, false, false)
if n := helperStarts(started); n != 2 {
t.Fatalf("the interactive mode started %d times, want twice: text is still tried there", n)
}
}
// A failure to paste the message that does reach the client is a 400 no
// account rests for and the client doesn't ask again, never a 502: the
// same message fails the same way every try.
func TestClaudeUnpastableIsNoRetried502(t *testing.T) {
code, _ := bridgeFailed("Claude Code", claudetui.Unpastable+claudetui.ImageNotTaken+": >", 0)
if code != 400 {
t.Fatalf("%d, want 400", code)
}
body := []byte(`{"type":"error","error":{"type":"invalid_request_error","message":"Claude Code: ` + claudetui.ImageNotTaken + `"}}`)
if retryable(code, body) {
t.Fatal("asked of the next account")
}
switch f := failure(code, body); f {
case failCredit, failQuota, failRate, failAuth:
t.Fatalf("reads as the account's (%s)", f)
}
if code, _ := bridgeFailed("Claude Code", "Claude Code ended without an answer", 0); code != 502 {
t.Fatalf("%d: another failure is still a 502", code)
}
}
+5
View File
@@ -244,6 +244,11 @@ type Request struct {
// such prompts, with the interactive mode on all the same
// (thirdPartyPrint)
tuiRefused bool
// unpasted, for the Claude bridge, is a request whose message Claude
// Code's interactive mode didn't take, or one with images on a
// machine where it didn't take an image (ok123now on X): its run is
// claude -p, with the interactive mode on all the same
unpasted bool
// hourMarks has the cache marks magpie adds on Anthropic's Messages
// (anthropicBody) last an hour: a Responses client's (Codex's), whose
// turns are often more than five minutes apart and whose own vendor
@@ -1503,6 +1503,7 @@ function routingPage(part) {
missing: "Claude Code isn't installed on this computer",
image: "the request has an image known by its URL, which only claude -p takes",
"third-party": "the interactive mode was turned away over this agent's system prompt",
unpasted: "the interactive mode here didn't take the message, or an image pasted into it; the plan counts claude -p at about twice the interactive mode's, and it starts without the interactive run's cache",
"cache-marks": "the client's cache marks keep history that a fresh interactive run would write again",
};
// entryNote: what a try's entry point chip says (Try.Entry)
@@ -16,6 +16,7 @@ magpie.strings({
"Claude Code ran this request as claude -p": "Claude Code 以 claude -p 运行了这个请求",
"the request has an image known by its URL, which only claude -p takes": "请求里有按 URL 引用的图片,只有 claude -p 能处理",
"the interactive mode was turned away over this agent's system prompt": "Anthropic 在交互模式下拒绝了这个 Agent 的系统提示词",
"the interactive mode here didn't take the message, or an image pasted into it; the plan counts claude -p at about twice the interactive mode's, and it starts without the interactive run's cache": "这台电脑上的交互模式没有接收这条消息,或粘贴进去的图片;套餐对 claude -p 的计量约为交互模式的两倍,且用不上交互运行已有的缓存",
"the client's cache marks keep history that a fresh interactive run would write again": "客户端的缓存标记保留了历史,新开的交互运行会把它再写一遍",
"magpie is masking this request before routing it (Settings › Privacy), so who takes it isn't picked yet.": "magpie 正在给这个请求脱敏(设置 › 隐私),脱敏完才路由,所以还没选出由谁处理。",
"This request waits for the turn before it on an account near its usage cap, so it goes out when that one is done.": "该请求在等同一账号上前一个请求结束,该账号已接近用量上限,前一个结束后即发出。",
@@ -766,6 +767,7 @@ magpie.strings({
"Claude Code ran this request as claude -p": "Claude Code 以 claude -p 執行了這個請求",
"the request has an image known by its URL, which only claude -p takes": "請求裡有按 URL 引用的圖片,只有 claude -p 能處理",
"the interactive mode was turned away over this agent's system prompt": "Anthropic 在互動模式下拒絕了這個 Agent 的系統提示詞",
"the interactive mode here didn't take the message, or an image pasted into it; the plan counts claude -p at about twice the interactive mode's, and it starts without the interactive run's cache": "這台電腦上的互動模式沒有接收這則訊息,或貼上去的圖片;方案對 claude -p 的計量約為互動模式的兩倍,且用不上互動執行已有的快取",
"the client's cache marks keep history that a fresh interactive run would write again": "用戶端的快取標記保留了歷史,新開的互動執行會把它再寫一遍",
"magpie is masking this request before routing it (Settings › Privacy), so who takes it isn't picked yet.": "magpie 正在為這個請求脫敏(設定 › 隱私),脫敏完才路由,所以還沒選出由誰處理。",
"This request waits for the turn before it on an account near its usage cap, so it goes out when that one is done.": "該請求在等同一帳號上前一個請求結束,該帳號已接近用量上限,前一個結束後即送出。",
@@ -1516,6 +1518,7 @@ magpie.strings({
"Claude Code ran this request as claude -p": "Claude Code はこのリクエストを claude -p で実行しました",
"the request has an image known by its URL, which only claude -p takes": "リクエストに URL で参照する画像があり、claude -p だけが扱えます",
"the interactive mode was turned away over this agent's system prompt": "Anthropic が対話モードでこのエージェントのシステムプロンプトを拒否しました",
"the interactive mode here didn't take the message, or an image pasted into it; the plan counts claude -p at about twice the interactive mode's, and it starts without the interactive run's cache": "このコンピューターの対話モードがこのメッセージ、または貼り付けた画像を受け取りませんでした。プランは claude -p を対話モードの約 2 倍として数え、対話実行のキャッシュも使えません",
"the client's cache marks keep history that a fresh interactive run would write again": "クライアントのキャッシュマークが履歴を保持しており、新しい対話実行ではそれをもう一度書き込むことになります",
"magpie is masking this request before routing it (Settings › Privacy), so who takes it isn't picked yet.": "magpie はルーティングの前にこのリクエストをマスクしています(設定 › プライバシー)。誰が処理するかはまだ決まっていません。",
"This request waits for the turn before it on an account near its usage cap, so it goes out when that one is done.": "このリクエストは、使用量の上限に近いアカウントで前のリクエストが終わるのを待っており、終わり次第送信されます。",
@@ -2266,6 +2269,7 @@ magpie.strings({
"Claude Code ran this request as claude -p": "Claude Code hat diese Anfrage als claude -p ausgeführt",
"the request has an image known by its URL, which only claude -p takes": "die Anfrage enthält ein Bild, das per URL angegeben ist und nur von claude -p verarbeitet wird",
"the interactive mode was turned away over this agent's system prompt": "Anthropic hat den Systemprompt dieses Agents im interaktiven Modus abgelehnt",
"the interactive mode here didn't take the message, or an image pasted into it; the plan counts claude -p at about twice the interactive mode's, and it starts without the interactive run's cache": "der interaktive Modus hat auf diesem Computer die Nachricht oder ein eingefügtes Bild nicht angenommen; der Plan zählt claude -p etwa doppelt so hoch wie den interaktiven Modus, und der Cache des interaktiven Laufs fehlt ihm",
"the client's cache marks keep history that a fresh interactive run would write again": "die Cache-Markierungen des Clients behalten einen Verlauf, den ein frischer interaktiver Lauf erneut schreiben würde",
"magpie is masking this request before routing it (Settings › Privacy), so who takes it isn't picked yet.": "magpie maskiert diese Anfrage vor der Weiterleitung (Einstellungen › Datenschutz), daher steht noch nicht fest, wer sie übernimmt.",
"This request waits for the turn before it on an account near its usage cap, so it goes out when that one is done.": "Diese Anfrage wartet bei einem Konto nahe seinem Nutzungslimit auf die vorherige und geht danach hinaus.",