claudetui: a replayed history keeps its words when one of its lines names an image file and an image follows (#5548)
#5548, Suge8 (magpie 0.1.3106, Claude Code 2.1.318, macOS, interactive mode, Pi over OpenAI Chat): a compacted Pi conversation told whole to a new Claude Code reached it as its four images and the closing notes only; the history, which had `ls` output naming screenshots (a.jpg, …), came into the next prompt, out of order. Cause: send pasted a message's text piece and, without waiting for it to show, the image after it; only the last text piece was waited for. Claude Code 2.1.318 tries each pasted line ending in .png, .jpg, .jpeg, .gif or .webp as an image file before it takes the words in (for a relative name it asks the clipboard through osascript, about 0.45s), and keeps one "pasting" mark for every paste. The image's read ended first and cleared it, so the Enter after the closing notes sent the prompt without the words. Fix: - send waits for every text piece to show before the next piece, not only the last one. - shown counts a "[Pasted text #N" only with N past the paste before it, else the words' own last line: images and pasted text share Claude Code's numbering, so send keeps one number for both, and the prompt drawn again shows the earlier "[Pasted text #1". An inline paste (800 bytes and 2 line breaks at most) takes no number in 2.1.318, so the number stays exact. A paste not shown within shownWait is still gone past, as before. - Every paste goes through send, the WSL and queued (busy) messages too; a message of an image alone has no text to wait for, and one of text alone was already waited for. Tests: the fake Claude Code now does what 2.1.318 does here: it draws a long paste as "[Pasted text #N +B lines]" numbered with the images, draws the prompt again as a paste starts, takes words naming an image file in after 1s, and keeps one pasting mark (an Enter while it is set is lost). TestShimWaitsForWordsNamingImages sends [words naming foo.png, image, an ls naming bar.png and baz.png, image, closing notes], and the same naming .txt files. TestShimPastesImages now expects its second image as #3: the "and" between two images is 4 line breaks, pasted text as 2.1.318 numbers it. Run, at this tree on9e6687e3, and again after a rebase on30ae0e3f(go vet and go test ./internal/claudetui/ ok, the new test red on its old tui.go): - gofmt -l: clean. go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./..., go build, GOOS=linux go build -tags nogui, GOOS=windows go build: ok. - go test ./internal/claudetui/: ok (115s); with -race: ok (118s); the two image tests -race -count=10: ok. - go test -tags nogui ./...: claudetui and the gateway's Claude tests ok. TestAlmaProvidersSeenDecodeOnce (agent), TestMarshalRawIsEncodingJSON, TestMarshalSizedIsJSONMarshal, FuzzMarshalRaw, TestServeWSLListensBesideLoopback (gateway) and TestPluginSOCKSProxy (plugin) fail on this machine (go1.27.3, HTTPS_PROXY set) at9e6687e3without this change too; not looked into here. - Real Claude Code 2.1.318 (claude-haiku-5-5) through a helper built from this tree, the issue's message driven straight into claude-tui-helper, in a sandbox CLAUDE_CONFIG_DIR: s-png (a line "foo.png") 3/3 and s-txt ("foo.txt") 2/2 recorded the whole prompt, 807 chars, the words first and the image as [Image #2]. The old helper in the same setup, s-png 4/4: the words came after the image and the closing notes ("[Image #1] (The images…" first, imagePasteIds [1]); not lost this time, as the clipboard answered sooner than in the report. Broken by hand: - The old tui.go: TestShimWaitsForWordsNamingImages/.png fails, "Claude Code was sent "echo: [Image #1:red][Image #2:blue]\n\n(The images above are the tool's results.)\nReply with the codeword."", the words missing; /.txt passes. - Each piece waited for, but shown taking any "[Pasted text #": both cases fail: the second image is missing, and with .png the ls too. Taken from Suge8's own branch commit 15b05052 (byte-identical tui.go code to the patch ggbdpq rebased on #5548; this one also carries the subsystem doc and the fake's 2.1.318 numbering). The patch's replay_image_test.go and its FAKE_SLOW_PASTE fake mode are left out: they cover the same case as TestShimWaitsForWordsNamingImages with a second fake. Review run at this tree on origin/main9700dd7cd(wsl-run, magpie-desktop, Go 1.26.8): - gofmt -l internal/claudetui, go vet ./internal/claudetui: clean - go test -count=1 ./internal/claudetui/: ok (119s) - -race -count=3 TestShimWaitsForWordsNamingImages|TestShimPastesImages: ok Broken by hand: main's tui.go: TestShimWaitsForWordsNamingImages/.png red, the words missing ("echo: [Image #1:red][Image #2:blue]..."). Known edge (Suge8's): the words' tail can match early when a piece's last line equals an earlier piece's; it then goes on as before the fix. Reported-by: Suge8 Co-authored-by: Suge8 <nnyless@foxmail.com> Co-authored-by: ggbdpq <ggbdpq@gmail.com>
This commit is contained in:
@@ -181,19 +181,29 @@ talks to it as it talks to `-p`: stream-json in and out. The helper:
|
||||
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 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. Windows
|
||||
ends a run by killing its job, which no handler hears, so a helper
|
||||
starting removes such folders, and the tap's, over an hour old
|
||||
(`dropLeft`);
|
||||
other words stays words). Each piece is pasted once the prompt shows
|
||||
the one before (`send`). Claude Code reads an image's file after the
|
||||
paste returns, so the helper waits for `[Image #N]` with N past the
|
||||
paste before; without that wait the second of two images was lost.
|
||||
Words with a line that ends naming an image file (`a.jpg` in an `ls`)
|
||||
are tried as that file first (2.1.318 asks the clipboard for it, about
|
||||
0.45s) and taken in after, and Claude Code keeps one mark of a paste
|
||||
being taken in for every paste: an image pasted meanwhile cleared it,
|
||||
and Enter sent the message without the words, which came in the next
|
||||
prompt (#5548). So words are waited for too, until their last words
|
||||
show or a `[Pasted text #N` with N past the paste before (`shown`):
|
||||
images and pasted text are numbered together, and the prompt drawn
|
||||
again shows the earlier ones (`TestShimWaitsForWordsNamingImages`,
|
||||
`TestShimPastesImages`). The transcript holds real image blocks, and
|
||||
Claude Code notes each one's path to the model (`[Image: source: …]`).
|
||||
The folder 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. Windows ends a run by killing its job, which no handler hears,
|
||||
so a helper starting removes such folders, and the tap's, over an hour
|
||||
old (`dropLeft`);
|
||||
- tails `<CLAUDE_CONFIG_DIR>/projects/*/<session>.jsonl` and tells each
|
||||
row as `-p` would (`translator`): assistant messages whole, a tool's
|
||||
result, a `<synthetic>` API error as the turn's error result with its
|
||||
@@ -404,7 +414,8 @@ a new Claude Code (one older than its session, or a client's own) can
|
||||
run to megabytes. A real 3MB paste showed `[Pasted text` after 35s, and
|
||||
a real 500KB one was answered with all of it in the transcript, so the
|
||||
helper waits for a paste a second per 64KB longer than `pasteWait`
|
||||
(`shownWait`) before its Enter. Until 11-01 words over 400KB were
|
||||
(`shownWait`) before the next piece or its Enter, and goes on when it
|
||||
still isn't shown. Until 11-01 words over 400KB were
|
||||
refused with a 502 (`big`), a bound no paste had been tried at.
|
||||
|
||||
An image known only by its URL is downloaded first
|
||||
|
||||
+36
-23
@@ -1200,20 +1200,25 @@ func pasteClean(text string) string {
|
||||
}, 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.
|
||||
// send pastes a message's pieces into Claude Code's prompt, each once the
|
||||
// prompt shows the one before, 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. A piece is taken in a moment after
|
||||
// it is pasted where Claude Code reads a file for it: an image's path, and
|
||||
// words with a line that names an image file ("a.jpg" in an ls), which it
|
||||
// tries as one before it takes the words. Claude Code takes any paste
|
||||
// ending as the end of pasting, so a piece pasted meanwhile that is taken
|
||||
// first lets Enter send the message without the words, and they show in
|
||||
// the prompt after it (2.1.318).
|
||||
func (s *shim) send(pieces []piece) error {
|
||||
s.rowsMu.Lock()
|
||||
before, busy := s.rows, s.busy
|
||||
s.rowsMu.Unlock()
|
||||
text, image := "", 0
|
||||
marker := 0
|
||||
for i, p := range pieces {
|
||||
var err error
|
||||
if p.image != "" {
|
||||
var err error
|
||||
if image, err = s.pasteImage(s.path(p.image), image); err != nil {
|
||||
if marker, err = s.pasteImage(s.path(p.image), marker); err != nil {
|
||||
return err
|
||||
}
|
||||
continue
|
||||
@@ -1230,10 +1235,9 @@ func (s *shim) send(pieces []piece) error {
|
||||
if _, err := io.WriteString(s.pty, "\x1b[200~"+p.text+"\x1b[201~"); err != nil {
|
||||
return err
|
||||
}
|
||||
text = p.text
|
||||
}
|
||||
if err := s.shown(text); err != nil {
|
||||
return err
|
||||
if marker, err = s.shown(p.text, marker); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
time.Sleep(150 * time.Millisecond)
|
||||
for try := 0; try < 4; try++ {
|
||||
@@ -1273,8 +1277,9 @@ func (s *shim) path(path string) string {
|
||||
}
|
||||
|
||||
// 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.
|
||||
// it taken as an image: one numbered past after, the message's paste
|
||||
// before it (Claude Code numbers images and long pasted text alike). It
|
||||
// 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 {
|
||||
@@ -1305,11 +1310,16 @@ func shownWait(n int) time.Duration {
|
||||
return pasteWait + time.Duration(n/(64<<10))*time.Second
|
||||
}
|
||||
|
||||
var textShown = regexp.MustCompile(`\[Pasted text #(\d+)`)
|
||||
|
||||
// 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 {
|
||||
// Claude Code's "[Pasted text #<n>" for a long one, numbered past after,
|
||||
// the message's paste before it: the prompt drawn again shows those
|
||||
// before. It returns the number shown, or after where the words show
|
||||
// as themselves. Text "" waits for nothing.
|
||||
func (s *shim) shown(text string, after int) (int, error) {
|
||||
if text == "" {
|
||||
return nil
|
||||
return after, nil
|
||||
}
|
||||
tail := strings.TrimSpace(text)
|
||||
if i := strings.LastIndexByte(tail, '\n'); i >= 0 {
|
||||
@@ -1319,22 +1329,25 @@ func (s *shim) shown(text string) error {
|
||||
tail = string(r[len(r)-16:])
|
||||
}
|
||||
shownBy := time.After(shownWait(len(text)))
|
||||
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
|
||||
for _, m := range textShown.FindAllStringSubmatch(p, -1) {
|
||||
if n, _ := strconv.Atoi(m[1]); n > after {
|
||||
return n, nil
|
||||
}
|
||||
}
|
||||
if tail != "" && strings.Contains(strings.Join(strings.Fields(p), " "), strings.Join(strings.Fields(tail), " ")) {
|
||||
return after, nil
|
||||
}
|
||||
select {
|
||||
case <-s.changed:
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
case <-shownBy:
|
||||
break shown
|
||||
return after, nil
|
||||
case <-s.exited:
|
||||
return fmt.Errorf("Claude Code ended (%v): %s", s.exit, s.lastScreen())
|
||||
return 0, fmt.Errorf("Claude Code ended (%v): %s", s.exit, s.lastScreen())
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// transcript is the session's transcript, "" before Claude Code writes it.
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -225,6 +226,16 @@ func fakeChrome(r *bufio.Reader, how string) {
|
||||
}
|
||||
}
|
||||
|
||||
// namesImage is pasted words with a line Claude Code 2.1.318 tries as an
|
||||
// image file before it takes them in: one that ends naming one.
|
||||
var namesImage = regexp.MustCompile(`(?im)\.(png|jpe?g|gif|webp)[ \t]*$`)
|
||||
|
||||
// nameWait is how long the fake takes words that name an image file to
|
||||
// take in. Claude Code took 0.45s, asking the clipboard for the file; the
|
||||
// fake's is longer than its image's 200ms and the Enter after it, for an
|
||||
// Enter that doesn't wait for the words to come before them.
|
||||
const nameWait = time.Second
|
||||
|
||||
func fakeClaude(args []string) {
|
||||
if slices.Contains(args, "-p") {
|
||||
sc := bufio.NewScanner(os.Stdin)
|
||||
@@ -307,12 +318,36 @@ func fakeClaude(args []string) {
|
||||
}
|
||||
streams := 0
|
||||
fmt.Print("\r\n❯ ")
|
||||
// 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
|
||||
// the prompt's words, and the prompt as drawn, again as a paste
|
||||
// starts and as one is taken in. As Claude Code 2.1.318 does, it draws
|
||||
// a paste of over 800 bytes or 2 line breaks as "[Pasted text #<n>
|
||||
// +<breaks> lines]", numbered with the images. 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; words with a line that
|
||||
// names an image file are tried as one first, and taken in after
|
||||
// nameWait. One mark of a paste being taken in stands for all of them,
|
||||
// and is cleared as any is taken in: an Enter while it is set is lost,
|
||||
// as the one Claude Code holds is when a read ends, and an Enter after
|
||||
// sends the prompt as it stands.
|
||||
var mu sync.Mutex
|
||||
var typed, paste strings.Builder
|
||||
pasting, images := false, 0
|
||||
var typed, drawn, paste strings.Builder
|
||||
pasting, taking, pasted := false, false, 0
|
||||
take := func(text, draw string) {
|
||||
typed.WriteString(text)
|
||||
drawn.WriteString(draw)
|
||||
taking = false
|
||||
fmt.Print("\r❯ " + drawn.String())
|
||||
}
|
||||
takeText := func(p string) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
draw := p
|
||||
if breaks := strings.Count(p, "\n"); len(p) > 800 || breaks > 2 {
|
||||
pasted++
|
||||
draw = fmt.Sprintf("[Pasted text #%d +%d lines]", pasted, breaks)
|
||||
}
|
||||
take(p, draw)
|
||||
}
|
||||
// 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
|
||||
@@ -333,22 +368,25 @@ func fakeClaude(args []string) {
|
||||
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-") {
|
||||
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)
|
||||
pasted++
|
||||
take(fmt.Sprintf("[Image #%d:%s]", pasted, b), fmt.Sprintf("[Image #%d]", pasted))
|
||||
}()
|
||||
continue
|
||||
}
|
||||
mu.Lock()
|
||||
typed.WriteString(p)
|
||||
mu.Unlock()
|
||||
fmt.Print(p) // drawn in the prompt
|
||||
if namesImage.MatchString(p) {
|
||||
time.AfterFunc(nameWait, func() { takeText(p) })
|
||||
continue
|
||||
}
|
||||
takeText(p)
|
||||
continue
|
||||
case pasting:
|
||||
paste.WriteByte(c)
|
||||
@@ -360,13 +398,19 @@ func fakeClaude(args []string) {
|
||||
case c != '\r':
|
||||
mu.Lock()
|
||||
typed.WriteByte(c)
|
||||
drawn.WriteByte(c)
|
||||
mu.Unlock()
|
||||
fmt.Printf("%c", c)
|
||||
continue
|
||||
}
|
||||
mu.Lock()
|
||||
if taking {
|
||||
mu.Unlock()
|
||||
continue
|
||||
}
|
||||
line := typed.String()
|
||||
typed.Reset()
|
||||
drawn.Reset()
|
||||
mu.Unlock()
|
||||
if listed != "" {
|
||||
if _, err := os.Stat(listed); err != nil {
|
||||
@@ -611,7 +655,9 @@ func TestShimPastesImages(t *testing.T) {
|
||||
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) {
|
||||
// "and" between its breaks is drawn as pasted text, numbered with the
|
||||
// images
|
||||
if want := `echo: look:\n\n[Image #1:red]\n\nand\n\n[Image #3:blue]\n\nnow"`; !strings.Contains(said, want) {
|
||||
t.Fatalf("Claude Code was sent %s, want %s", said, want)
|
||||
}
|
||||
if !failed {
|
||||
@@ -625,6 +671,39 @@ func TestShimPastesImages(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
// piece waits for the prompt to show the one before, words as a "[Pasted
|
||||
// text" numbered past the paste before them, not one drawn again: the
|
||||
// message reaches Claude Code whole, as one whose lines name no image
|
||||
// does (#5548).
|
||||
func TestShimWaitsForWordsNamingImages(t *testing.T) {
|
||||
image := func(s string) map[string]any {
|
||||
return map[string]any{"type": "image", "source": map[string]any{"type": "base64", "media_type": "image/png", "data": base64.StdEncoding.EncodeToString([]byte(s))}}
|
||||
}
|
||||
text := func(s string) map[string]any { return map[string]any{"type": "text", "text": s} }
|
||||
for _, ext := range []string{".png", ".txt"} {
|
||||
t.Run(ext, func(t *testing.T) {
|
||||
first := "The codeword is MANGO.\nSome notes.\nfoo" + ext + "\nmore notes."
|
||||
second := "$ ls\nbar" + ext + "\nbaz" + ext + "\nthat is all."
|
||||
last := "(The images above are the tool's results.)\nReply with the codeword."
|
||||
msg, _ := json.Marshal([]any{text(first), image("red"), text(second), image("blue"), text(last)})
|
||||
out := runShim(t, nil, append([]string{fakePath(t)}, pArgs...), []string{string(msg)}, 3)
|
||||
var said string
|
||||
for _, m := range out[1:] {
|
||||
if m["type"] == "assistant" {
|
||||
c, _ := m["message"].(map[string]any)["content"].([]any)
|
||||
said, _ = c[0].(map[string]any)["text"].(string)
|
||||
}
|
||||
}
|
||||
if want := "echo: " + first + "\n\n[Image #2:red]\n\n" + second + "\n\n[Image #4:blue]\n\n" + last; said != want {
|
||||
t.Fatalf("Claude Code was sent %q, want %q", said, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A folder of images or a tap's a killed helper left is removed by a
|
||||
// later one after imagesLeft, and one in use isn't.
|
||||
func TestDropLeft(t *testing.T) {
|
||||
|
||||
Reference in New Issue
Block a user