diff --git a/docs/subsystems/claude-subscription-bridge.md b/docs/subsystems/claude-subscription-bridge.md index d86db4c5a..a51874f64 100644 --- a/docs/subsystems/claude-subscription-bridge.md +++ b/docs/subsystems/claude-subscription-bridge.md @@ -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.` (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 `/projects/*/.jsonl` and tells each row as `-p` would (`translator`): assistant messages whole, a tool's result, a `` 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 diff --git a/internal/claudetui/tui.go b/internal/claudetui/tui.go index ad8954816..3b1d18df9 100644 --- a/internal/claudetui/tui.go +++ b/internal/claudetui/tui.go @@ -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 #" 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. diff --git a/internal/claudetui/tui_test.go b/internal/claudetui/tui_test.go index 4869f0529..ad9afc887 100644 --- a/internal/claudetui/tui_test.go +++ b/internal/claudetui/tui_test.go @@ -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 #:]" 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 # + // + lines]", numbered with the images. An image file's path + // pasted alone is read a moment later and becomes "[Image #:]" 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) {