claudetui: a turn's images are pasted as files, not sent to claude -p
A request with images ran claude -p, and a turn with one ended the interactive run. The helper now writes each base64 image to image-N.<ext> (0600) in a magpie-claude-images-* temp folder and pastes its path alone, which Claude Code 2.1.314 reads into the message as [Image #N]; a path inside other words stays words. Claude Code reads the file after the paste returns, so the helper waits for [Image #N] past the last one before pasting the next piece. The folder is removed when the helper ends. Only an image known by its URL still goes to -p (urlImages), and tuiPromptMost counts words without images. Run: go test ./internal/claudetui ./internal/cli on mote and in WSL magpie-desktop, ok; go test -run 'TestClaudeTUI|TestSubscription| TestClaudePrint' ./internal/gateway on mote, ok; go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./..., go build, gofmt -l, ok. Real account (Claude Code 2.1.314, haiku, sandbox HOME) through the sandbox gateway with tools: a red then a blue square in two turns, 3 of 3 answered red, blue; the transcript has image blocks in both user rows, entrypoint cli, and the second turn went on in the same run. Broken by hand: without the wait for [Image #N], TestShimPastesImages loses the second image. Not tried: an image over Claude Code's size limit; Linux with a real account.
This commit is contained in:
@@ -110,6 +110,19 @@ talks to it as it talks to `-p`: stream-json in and out. The helper:
|
||||
- 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`);
|
||||
- pastes a message's images as files (`userPieces`, `writeImage`): each
|
||||
base64 image is written to `image-N.<ext>` (0600) in a
|
||||
`magpie-claude-images-*` temp folder, and its path is pasted alone,
|
||||
which Claude Code reads into the message as `[Image #N]` (a path inside
|
||||
other words stays words). Claude Code reads the file after the paste
|
||||
returns, so the helper waits for `[Image #N]` with N past the last
|
||||
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:
|
||||
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;
|
||||
- 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
|
||||
@@ -147,17 +160,18 @@ 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.
|
||||
- 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),
|
||||
which a paste can't carry as `-p` does.
|
||||
|
||||
The gateway's log says which (`claude: this run is -p: …`,
|
||||
`claudePrintWhy`), and the helper's own line when it becomes `-p` (below)
|
||||
is logged from the run's stderr (`lockedWriter`).
|
||||
|
||||
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
|
||||
anew: a turn with an image known by its URL, 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
|
||||
|
||||
+206
-70
@@ -20,15 +20,18 @@ import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
@@ -73,6 +76,11 @@ type shim struct {
|
||||
|
||||
exited chan struct{}
|
||||
exit error
|
||||
|
||||
// images is where a message's images are written for their paths to
|
||||
// be pasted, made with the first; images counts them
|
||||
images string
|
||||
nimages int
|
||||
}
|
||||
|
||||
// Run runs Claude Code at path, args being the bridge's `claude -p` ones,
|
||||
@@ -118,11 +126,13 @@ func Run(args []string) error {
|
||||
return printMode(path, pargs)
|
||||
}
|
||||
defer s.stop()
|
||||
defer s.dropImages()
|
||||
sigs := make(chan os.Signal, 1)
|
||||
signal.Notify(sigs, syscall.SIGTERM, syscall.SIGINT, syscall.SIGHUP)
|
||||
go func() {
|
||||
<-sigs
|
||||
s.stop()
|
||||
s.dropImages()
|
||||
os.Exit(1)
|
||||
}()
|
||||
if err := s.ready(); err != nil {
|
||||
@@ -391,13 +401,13 @@ func (s *shim) input(r io.Reader) error {
|
||||
}
|
||||
s.emit(map[string]any{"type": "control_response", "response": resp})
|
||||
case "user":
|
||||
text, ok := userText(m.Message.Content)
|
||||
if !ok {
|
||||
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": "an image can't be pasted into Claude Code's interactive mode"})
|
||||
"result": "this message can't be pasted into Claude Code's interactive mode: " + err.Error()})
|
||||
continue
|
||||
}
|
||||
if err := s.send(text); err != nil {
|
||||
if err := s.send(pieces); err != nil {
|
||||
return err
|
||||
}
|
||||
if m.UUID != "" {
|
||||
@@ -408,34 +418,99 @@ func (s *shim) input(r io.Reader) error {
|
||||
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
|
||||
// piece is a part of a user message as it is pasted: words, or the path
|
||||
// of an image file, which Claude Code's prompt takes as that image
|
||||
// ("[Image #1]") when it is pasted alone.
|
||||
type piece struct{ text, image string }
|
||||
|
||||
// imageTypes are the images Claude Code's prompt takes, by their file's
|
||||
// extension.
|
||||
var imageTypes = map[string]string{"image/png": ".png", "image/jpeg": ".jpg", "image/gif": ".gif", "image/webp": ".webp"}
|
||||
|
||||
// userPieces is a user message as it is pasted: its text blocks one after
|
||||
// another, an image block written to a file of its own.
|
||||
func (s *shim) userPieces(raw json.RawMessage) ([]piece, error) {
|
||||
var str string
|
||||
if json.Unmarshal(raw, &str) == nil {
|
||||
return []piece{{text: str}}, nil
|
||||
}
|
||||
var blocks []struct {
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text"`
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text"`
|
||||
Source struct {
|
||||
Type string `json:"type"`
|
||||
MediaType string `json:"media_type"`
|
||||
Data string `json:"data"`
|
||||
} `json:"source"`
|
||||
}
|
||||
if json.Unmarshal(raw, &blocks) != nil {
|
||||
return "", false
|
||||
if err := json.Unmarshal(raw, &blocks); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var out []piece
|
||||
var b strings.Builder
|
||||
for _, bl := range blocks {
|
||||
if bl.Type != "text" {
|
||||
return "", false
|
||||
switch bl.Type {
|
||||
case "text":
|
||||
if bl.Text == "" {
|
||||
continue
|
||||
}
|
||||
if b.Len() > 0 || len(out) > 0 {
|
||||
b.WriteString("\n\n")
|
||||
}
|
||||
b.WriteString(bl.Text)
|
||||
case "image":
|
||||
path, err := s.writeImage(bl.Source.Type, bl.Source.MediaType, bl.Source.Data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if b.Len() > 0 {
|
||||
b.WriteString("\n\n")
|
||||
out = append(out, piece{text: b.String()})
|
||||
b.Reset()
|
||||
}
|
||||
out = append(out, piece{image: path})
|
||||
default:
|
||||
return nil, fmt.Errorf("a %s block", bl.Type)
|
||||
}
|
||||
if bl.Text == "" {
|
||||
continue
|
||||
}
|
||||
if b.Len() > 0 {
|
||||
b.WriteString("\n\n")
|
||||
}
|
||||
b.WriteString(bl.Text)
|
||||
}
|
||||
return b.String(), true
|
||||
if b.Len() > 0 || len(out) == 0 {
|
||||
out = append(out, piece{text: b.String()})
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// writeImage writes an image block's bytes to a file of its own, named
|
||||
// for its type, and returns its path.
|
||||
func (s *shim) writeImage(source, mediaType, data string) (string, error) {
|
||||
if source != "base64" {
|
||||
return "", fmt.Errorf("an image by %s", source)
|
||||
}
|
||||
b, err := base64.StdEncoding.DecodeString(data)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("an image's data: %w", err)
|
||||
}
|
||||
if mediaType == "" {
|
||||
mediaType = http.DetectContentType(b)
|
||||
}
|
||||
ext, ok := imageTypes[mediaType]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("a %s image", mediaType)
|
||||
}
|
||||
if s.images == "" {
|
||||
if s.images, err = os.MkdirTemp("", "magpie-claude-images-"); err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
s.nimages++
|
||||
path := filepath.Join(s.images, fmt.Sprintf("image-%d%s", s.nimages, ext))
|
||||
return path, os.WriteFile(path, b, 0o600)
|
||||
}
|
||||
|
||||
// dropImages removes the images pasted, once Claude Code has ended.
|
||||
func (s *shim) dropImages() {
|
||||
if s.images != "" {
|
||||
_ = os.RemoveAll(s.images)
|
||||
}
|
||||
}
|
||||
|
||||
// pasteable is text as a paste can carry it: no escape that would end the
|
||||
@@ -444,18 +519,7 @@ func userText(raw json.RawMessage) (string, bool) {
|
||||
// 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)
|
||||
text = pasteClean(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
|
||||
@@ -471,46 +535,58 @@ func pasteable(text string, busy bool) string {
|
||||
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 {
|
||||
// pasteClean is text without an escape that would end a paste early, nor
|
||||
// other control characters, its lines ended by \n.
|
||||
func pasteClean(text string) string {
|
||||
text = strings.ReplaceAll(text, "\r\n", "\n")
|
||||
return 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)
|
||||
}
|
||||
|
||||
// send pastes a message's pieces into Claude Code's prompt, each image
|
||||
// once the prompt shows the one before (its file is read as it is pasted,
|
||||
// and words pasted meanwhile would come before it), 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(pieces []piece) error {
|
||||
s.rowsMu.Lock()
|
||||
before, busy := s.rows, s.busy
|
||||
s.rowsMu.Unlock()
|
||||
text = pasteable(text, busy)
|
||||
if strings.TrimSpace(text) == "" {
|
||||
text = "."
|
||||
text, image := "", 0
|
||||
for i, p := range pieces {
|
||||
if p.image != "" {
|
||||
var err error
|
||||
if image, err = s.pasteImage(p.image, image); err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
if i == 0 {
|
||||
p.text = pasteable(p.text, busy)
|
||||
} else {
|
||||
p.text = pasteClean(p.text)
|
||||
}
|
||||
if i == 0 && len(pieces) == 1 && strings.TrimSpace(p.text) == "" {
|
||||
p.text = "."
|
||||
}
|
||||
s.clearScreen()
|
||||
if _, err := s.pty.WriteString("\x1b[200~" + p.text + "\x1b[201~"); err != nil {
|
||||
return err
|
||||
}
|
||||
text = p.text
|
||||
}
|
||||
s.clearScreen()
|
||||
if _, err := s.pty.WriteString("\x1b[200~" + text + "\x1b[201~"); err != nil {
|
||||
if err := s.shown(text); 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 {
|
||||
@@ -537,6 +613,66 @@ shown:
|
||||
return fmt.Errorf("Claude Code did not take the message: %s", s.lastScreen())
|
||||
}
|
||||
|
||||
var imageShown = regexp.MustCompile(`\[Image #(\d+)\]`)
|
||||
|
||||
// pasteImage pastes an image file's path, and waits for the prompt to show
|
||||
// it taken as an image: one numbered past after, the message's image
|
||||
// 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 {
|
||||
return 0, err
|
||||
}
|
||||
by := time.After(pasteWait)
|
||||
for {
|
||||
for _, m := range imageShown.FindAllStringSubmatch(s.plain(), -1) {
|
||||
if n, _ := strconv.Atoi(m[1]); n > after {
|
||||
return n, nil
|
||||
}
|
||||
}
|
||||
select {
|
||||
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())
|
||||
case <-s.exited:
|
||||
return 0, fmt.Errorf("Claude Code ended (%v): %s", s.exit, s.lastScreen())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// shown waits for the prompt to show pasted text: its last words, or
|
||||
// Claude Code's "[Pasted text" for a long one. Text "" waits for nothing.
|
||||
func (s *shim) shown(text string) error {
|
||||
if text == "" {
|
||||
return nil
|
||||
}
|
||||
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())
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// 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"))
|
||||
|
||||
@@ -4,6 +4,7 @@ package claudetui
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
@@ -115,8 +116,12 @@ func fakeClaude(args []string) {
|
||||
// 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)
|
||||
fmt.Print("\r\n❯ ")
|
||||
var typed strings.Builder
|
||||
pasting := false
|
||||
// the prompt's words; an image file's path pasted alone is read a
|
||||
// moment later and becomes "[Image #<n>:<its bytes>]" where the
|
||||
// prompt's words end then
|
||||
var mu sync.Mutex
|
||||
var typed, paste strings.Builder
|
||||
pasting, images := false, 0
|
||||
for {
|
||||
c, err := r.ReadByte()
|
||||
if err != nil {
|
||||
@@ -129,14 +134,42 @@ func fakeClaude(args []string) {
|
||||
return
|
||||
}
|
||||
pasting = string(seq) == "[200~"
|
||||
if pasting {
|
||||
paste.Reset()
|
||||
continue
|
||||
}
|
||||
p := paste.String()
|
||||
if b, err := os.ReadFile(p); err == nil && strings.HasPrefix(filepath.Base(p), "image-") {
|
||||
images++
|
||||
n := images
|
||||
go func() {
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
typed.WriteString(fmt.Sprintf("[Image #%d:%s]", n, b))
|
||||
fmt.Printf("[Image #%d]", n)
|
||||
}()
|
||||
continue
|
||||
}
|
||||
mu.Lock()
|
||||
typed.WriteString(p)
|
||||
mu.Unlock()
|
||||
fmt.Print(p) // drawn in the prompt
|
||||
continue
|
||||
case c != '\r' || pasting:
|
||||
case pasting:
|
||||
paste.WriteByte(c)
|
||||
continue
|
||||
case c != '\r':
|
||||
mu.Lock()
|
||||
typed.WriteByte(c)
|
||||
fmt.Printf("%c", c) // drawn in the prompt
|
||||
mu.Unlock()
|
||||
fmt.Printf("%c", c)
|
||||
continue
|
||||
}
|
||||
mu.Lock()
|
||||
line := typed.String()
|
||||
typed.Reset()
|
||||
mu.Unlock()
|
||||
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}},
|
||||
@@ -178,7 +211,12 @@ func runShim(t *testing.T, env []string, pargs []string, lines []string, want in
|
||||
})
|
||||
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}})
|
||||
// a line that is JSON is the message's content blocks
|
||||
var content any = l
|
||||
if json.Valid([]byte(l)) {
|
||||
content = json.RawMessage(l)
|
||||
}
|
||||
b, _ := json.Marshal(map[string]any{"type": "user", "message": map[string]any{"role": "user", "content": content}})
|
||||
_, _ = stdin.Write(append(b, '\n'))
|
||||
}
|
||||
got := make(chan map[string]any)
|
||||
@@ -257,6 +295,34 @@ func TestShimTurnsInteractive(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A message's images are pasted as their files' paths, each alone and
|
||||
// after the prompt shows the one before: the words and images reach
|
||||
// Claude Code in their order. One it can't take as a file is an error.
|
||||
func TestShimPastesImages(t *testing.T) {
|
||||
b64 := func(s string) string { return base64.StdEncoding.EncodeToString([]byte(s)) }
|
||||
msg := `[{"type":"text","text":"look:"},{"type":"image","source":{"type":"base64","media_type":"image/png","data":"` + b64("red") + `"}},` +
|
||||
`{"type":"text","text":"and"},{"type":"image","source":{"type":"base64","media_type":"image/gif","data":"` + b64("blue") + `"}},{"type":"text","text":"now"}]`
|
||||
byURL := `[{"type":"text","text":"see"},{"type":"image","source":{"type":"url","url":"https://example.com/a.png"}}]`
|
||||
out := runShim(t, nil, append([]string{fakePath(t)}, pArgs...), []string{msg, byURL}, 4)
|
||||
var said string
|
||||
var failed bool
|
||||
for _, m := range out[1:] {
|
||||
switch m["type"] {
|
||||
case "assistant":
|
||||
b, _ := json.Marshal(m["message"])
|
||||
said = string(b)
|
||||
case "result":
|
||||
failed = failed || m["is_error"] == true && strings.Contains(fmt.Sprint(m["result"]), "an image by url")
|
||||
}
|
||||
}
|
||||
if want := `echo: look:\n\n[Image #1:red]\n\nand\n\n[Image #2:blue]\n\nnow"`; !strings.Contains(said, want) {
|
||||
t.Fatalf("Claude Code was sent %s, want %s", said, want)
|
||||
}
|
||||
if !failed {
|
||||
t.Fatalf("an image by its URL wasn't an error: %v", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestShimFallsBackToPrint(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
name string
|
||||
|
||||
@@ -947,7 +947,8 @@ func (b *subscriptionBridge) startRun(ctx context.Context, req *Request, model,
|
||||
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.
|
||||
// interactive mode is pasted, its words without its images (each pasted
|
||||
// as its file's path); 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
|
||||
@@ -968,7 +969,13 @@ func claudeTUI(req *Request, binary claudeCLI, prompt []map[string]any) bool {
|
||||
|
||||
// claudePrintWhy is why a run is -p, "" when it is the interactive mode.
|
||||
func claudePrintWhy(req *Request, binary claudeCLI, prompt []map[string]any) string {
|
||||
b, _ := json.Marshal(prompt)
|
||||
var words []map[string]any
|
||||
for _, bl := range prompt {
|
||||
if bl["type"] != "image" {
|
||||
words = append(words, bl)
|
||||
}
|
||||
}
|
||||
b, _ := json.Marshal(words)
|
||||
for _, c := range []struct {
|
||||
is bool
|
||||
why string
|
||||
@@ -980,7 +987,7 @@ func claudePrintWhy(req *Request, binary claudeCLI, prompt []map[string]any) str
|
||||
{len(req.Safeguards) > 0, "safeguards"},
|
||||
{req.clientCache != nil, "the client's cache marks"},
|
||||
{len(req.Format.schema()) > 0, "a JSON schema"},
|
||||
{countImages(req.Messages) > 0, "images"},
|
||||
{urlImages(req.Messages) > 0, "an image known by its URL"},
|
||||
{settings.Load().ClaudePrintMode, "the interactive mode is turned off"},
|
||||
{len(b) > tuiPromptMost, "a first message over 400KB"},
|
||||
} {
|
||||
@@ -1131,8 +1138,9 @@ func (b *subscriptionBridge) resume(req *Request, owner string) (*subscriptionRu
|
||||
return nil, nil
|
||||
}
|
||||
req.clientCache.selected(false)
|
||||
if run.tui && (back != "" || countImages(since) > 0) {
|
||||
if run.tui && (back != "" || urlImages(since) > 0) {
|
||||
// the interactive mode can't be taken back, nor pasted an image
|
||||
// it has no bytes of
|
||||
run.abortFor("the interactive Claude Code can't go on with this turn")
|
||||
return nil, nil
|
||||
}
|
||||
@@ -3182,6 +3190,25 @@ func countImages(msgs []Message) int {
|
||||
return n
|
||||
}
|
||||
|
||||
// urlImages counts msgs' images known by their URL alone, which Claude
|
||||
// Code's interactive mode can't be pasted: it takes an image as a file.
|
||||
func urlImages(msgs []Message) int {
|
||||
n := 0
|
||||
for _, m := range msgs {
|
||||
for _, p := range m.Parts {
|
||||
if p.Kind == Image && p.Data == "" {
|
||||
n++
|
||||
}
|
||||
for _, im := range p.Images {
|
||||
if im.Data == "" {
|
||||
n++
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// historyEnd is where the turn to answer begins in msgs: the message after
|
||||
// the last reply that calls no tool. 0 when there is no such reply, or
|
||||
// nothing after it, and the messages are told as one turn.
|
||||
|
||||
@@ -41,7 +41,10 @@ func TestClaudeTUIChosen(t *testing.T) {
|
||||
{"safeguards", &Request{Messages: text("hi"), Safeguards: json.RawMessage(`{"a":1}`)}, here, prompt, false, false, "safeguards"},
|
||||
{"client cache marks", &Request{Messages: text("hi"), clientCache: &clientCache{}}, here, prompt, false, false, "the client's cache marks"},
|
||||
{"a schema", &Request{Messages: text("hi"), Format: &Format{Type: "json_schema", Schema: json.RawMessage(`{"type":"object"}`)}}, here, prompt, false, false, "a JSON schema"},
|
||||
{"an image", &Request{Messages: []Message{{Role: "user", Parts: []Part{{Kind: Image, MediaType: "image/png", Data: "AA=="}}}}}, here, prompt, false, false, "images"},
|
||||
{"an image", &Request{Messages: []Message{{Role: "user", Parts: []Part{{Kind: Image, MediaType: "image/png", Data: "AA=="}}}}}, here, prompt, false, on, ""},
|
||||
{"an image by its URL", &Request{Messages: []Message{{Role: "user", Parts: []Part{{Kind: Image, URL: "https://example.com/a.png"}}}}}, here, prompt, false, false, "an image known by its URL"},
|
||||
{"a tool's image by its URL", &Request{Messages: []Message{{Role: "user", Parts: []Part{{Kind: ToolResult, Images: []Part{{Kind: Image, URL: "https://example.com/a.png"}}}}}}}, here, prompt, false, false, "an image known by its URL"},
|
||||
{"a large image", &Request{Messages: text("hi")}, here, []map[string]any{{"type": "text", "text": "hi"}, {"type": "image", "source": map[string]any{"type": "base64", "data": strings.Repeat("A", tuiPromptMost)}}}, false, on, ""},
|
||||
{"a long first message", &Request{Messages: text("hi")}, here, []map[string]any{{"type": "text", "text": strings.Repeat("x", tuiPromptMost)}}, false, false, "a first message over 400KB"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
|
||||
Reference in New Issue
Block a user