diff --git a/docs/subsystems/claude-subscription-bridge.md b/docs/subsystems/claude-subscription-bridge.md index e1c767b29..d9740e5a5 100644 --- a/docs/subsystems/claude-subscription-bridge.md +++ b/docs/subsystems/claude-subscription-bridge.md @@ -493,8 +493,9 @@ 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 +need the marks. Long pasted text there still loses blocks (#5205); the +whole-message check below catches a message cut so. +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 @@ -513,6 +514,23 @@ run (Off meanwhile, the client gone) the failure is a 400, not a 502 `TestShimPaddedImageTakenWithoutMarks` the padded paste on a console that drops the marks. +The helper checks that a message reached Claude +Code whole (`whole.go`, from 3leg0ocat's patch). It took one as sent once +a row of it reached the transcript, whatever the row held, so a cut +message's tail was answered as the message. Now, while a message just sent +waits for its row, the rows' words (a user row's text, a queued message's) +are compared with the words pasted, white space, Claude Code's +`` tags, `[Image #N]` marks and format characters aside, +in place with no copy; the paths of images Claude Code says it took +(`[Image: source: ]` meta rows) are left out, and the images are +counted. What Claude Code answers meanwhile is held (`hold`) for up to +`wholeWait`. A message that isn't whole ends the turn as `Unpastable` +before any of its reply, so the bridge asks it again as `-p`, as an image +not taken; on Windows 10's own ConPTY the error says a `conpty` folder +fixes it (`cutHint`). `whole_test.go` holds the comparison and the hold, +and `TestShimCutMessageIsUnpastable` a fake Claude Code that loses a long +paste's 1024-byte blocks. + 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 diff --git a/internal/claudetui/child_unix.go b/internal/claudetui/child_unix.go index b1a83d93e..16f2ff14a 100644 --- a/internal/claudetui/child_unix.go +++ b/internal/claudetui/child_unix.go @@ -70,3 +70,7 @@ func (s *shim) stop() { // imagePadOS: a terminal here passes the bracketed-paste marks (imagePad). const imagePadOS = 0 + +// cutHint is what a message Claude Code didn't get whole (whole.go) is +// told of where it was lost: nothing known here. +func cutHint() string { return "" } diff --git a/internal/claudetui/child_windows.go b/internal/claudetui/child_windows.go index 55a94773d..afbe89274 100644 --- a/internal/claudetui/child_windows.go +++ b/internal/claudetui/child_windows.go @@ -35,7 +35,11 @@ var endSignals = []os.Signal{os.Interrupt, syscall.SIGTERM} // ships (conpty.dll, which runs the OpenConsole.exe beside it) keeps them. // dsh-cross: a conpty folder beside magpie's executable holding both is // used first; without it, the system's. -type pseudoConsole struct{ create, close *windows.LazyProc } +type pseudoConsole struct { + create, close *windows.LazyProc + // system: Windows' own, kernel32's + system bool +} var console = sync.OnceValue(func() pseudoConsole { if exe, err := os.Executable(); err == nil { @@ -43,14 +47,25 @@ var console = sync.OnceValue(func() pseudoConsole { if _, err := os.Stat(filepath.Join(dir, "OpenConsole.exe")); err == nil { dll := windows.NewLazyDLL(filepath.Join(dir, "conpty.dll")) if dll.NewProc("CreatePseudoConsole").Find() == nil && dll.NewProc("ClosePseudoConsole").Find() == nil { - return pseudoConsole{dll.NewProc("CreatePseudoConsole"), dll.NewProc("ClosePseudoConsole")} + return pseudoConsole{dll.NewProc("CreatePseudoConsole"), dll.NewProc("ClosePseudoConsole"), false} } } } k := windows.NewLazySystemDLL("kernel32.dll") - return pseudoConsole{k.NewProc("CreatePseudoConsole"), k.NewProc("ClosePseudoConsole")} + return pseudoConsole{k.NewProc("CreatePseudoConsole"), k.NewProc("ClosePseudoConsole"), true} }) +// cutHint is what a message Claude Code didn't get whole (whole.go) is +// told of where it was lost: on Windows 10's own ConPTY, how to use +// another (#5205). +func cutHint() string { + if !console().system || windows.RtlGetVersion().BuildNumber >= 22000 { + return "" + } + // short, for the bridge's log line to hold it whole + return "; on Windows 10, a conpty folder beside magpie.exe fixes it (#5205)" +} + func createPseudoConsole(size windows.Coord, in, out windows.Handle, h *windows.Handle) error { r, _, _ := console().create.Call(uintptr(*(*uint32)(unsafe.Pointer(&size))), uintptr(in), uintptr(out), 0, uintptr(unsafe.Pointer(h))) if r != 0 { diff --git a/internal/claudetui/transcript.go b/internal/claudetui/transcript.go index b73f2c4e0..7c26c4cfd 100644 --- a/internal/claudetui/transcript.go +++ b/internal/claudetui/transcript.go @@ -48,6 +48,7 @@ func (t *translator) row(b []byte) { APIStatus int `json:"apiErrorStatus"` ToolUseResult json.RawMessage `json:"toolUseResult"` Operation string `json:"operation"` + Content string `json:"content"` APIParams struct { RateLimitInfo json.RawMessage `json:"rate_limit_info"` } `json:"apiErrorParams"` @@ -60,13 +61,18 @@ func (t *translator) row(b []byte) { case "queue-operation": // a message sent mid-turn waits in Claude Code's queue if r.Operation == "enqueue" { + t.heard(func() heardRow { return heardRow{r.Content, -1} }) t.out.sawRow() } case "user": if !r.IsMeta && isPrompt(r.Message) { t.failed = false + t.heard(func() heardRow { return promptRow(r.Message) }) t.out.sawRow() } + if r.IsMeta { + t.heardTaken(r.Message) + } if len(r.ToolUseResult) > 0 && r.ToolUseResult[0] == '{' { t.out.emit(map[string]any{"type": "user", "tool_use_result": r.ToolUseResult}) } diff --git a/internal/claudetui/tui.go b/internal/claudetui/tui.go index 16bb14209..72991c1d9 100644 --- a/internal/claudetui/tui.go +++ b/internal/claudetui/tui.go @@ -64,6 +64,8 @@ var ( type shim struct { outMu sync.Mutex out io.Writer + // held takes what is written meanwhile, nil when none (whole.go) + held io.Writer // pty is Claude Code's terminal: what it draws is read from it, and // what is typed written to it @@ -91,6 +93,11 @@ type shim struct { rowsMu sync.Mutex rows int rowsCh chan struct{} + // said is the words of the messages that reached the transcript since + // one was sent, to check it whole (whole.go); nil when none is + said []heardRow + // taken is the image files' paths Claude Code took as images meanwhile + taken []string // a turn is going: from a message's row to the turn's end busy bool @@ -729,6 +736,10 @@ func (s *shim) emit(v any) { b, _ := json.Marshal(v) s.outMu.Lock() defer s.outMu.Unlock() + if s.held != nil { + _, _ = s.held.Write(append(b, '\n')) + return + } _, _ = s.out.Write(append(b, '\n')) } @@ -776,11 +787,12 @@ func (s *shim) input(r io.Reader) error { err = s.send(pieces) s.dropImages() var unpasted *imageUnpasted - if errors.As(err, &unpasted) { + var cut *messageCut + if errors.As(err, &unpasted) || errors.As(err, &cut) { // 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, + s.tell(map[string]any{"type": "result", "subtype": "error_during_execution", "is_error": true, "session_id": s.sid, "result": Unpastable + err.Error()}) } if err != nil { @@ -1258,11 +1270,16 @@ func pasteClean(text string) string { func (s *shim) send(pieces []piece) error { s.rowsMu.Lock() before, busy := s.rows, s.busy + s.said = []heardRow{} // kept from now on (heard), till send returns s.rowsMu.Unlock() + defer s.heardAll() + var pasted strings.Builder // the words pasted, to check them whole + images := 0 marker := 0 for i, p := range pieces { var err error if p.image != "" { + images++ if marker, err = s.pasteImage(s.path(p.image), marker); err != nil { return err } @@ -1276,6 +1293,8 @@ func (s *shim) send(pieces []piece) error { if i == 0 && len(pieces) == 1 && strings.TrimSpace(p.text) == "" { p.text = "." } + pasted.WriteString(p.text) + pasted.WriteByte('\n') s.clearScreen() if _, err := io.WriteString(s.pty, "\x1b[200~"+p.text+"\x1b[201~"); err != nil { return err @@ -1295,7 +1314,7 @@ func (s *shim) send(pieces []piece) error { sent := s.rows > before s.rowsMu.Unlock() if sent { - return nil + return s.checkWhole(pasted.String(), images) } select { case <-s.rowsCh: diff --git a/internal/claudetui/tui_test.go b/internal/claudetui/tui_test.go index eb4553be8..df974fb33 100644 --- a/internal/claudetui/tui_test.go +++ b/internal/claudetui/tui_test.go @@ -236,6 +236,24 @@ func fakeChrome(r *bufio.Reader, how string) { // image file before it takes them in: one that ends naming one. var namesImage = regexp.MustCompile(`(?im)\.(png|jpe?g|gif|webp)[ \t]*$`) +// fakeImage is an image the fake took in, as its prompt holds it. +var fakeImage = regexp.MustCompile(`\[Image #(\d+):([^\]]*)\]`) + +// fakeUserRow is a message's content as Claude Code's transcript records +// it: its words, each image's mark "[Image #]" and, with images, the +// images as blocks after them (whole.go reads it so). +func fakeUserRow(typed string) any { + m := fakeImage.FindAllStringSubmatch(typed, -1) + if len(m) == 0 { + return typed + } + content := []any{map[string]any{"type": "text", "text": fakeImage.ReplaceAllString(typed, "[Image #$1]")}} + for _, img := range m { + content = append(content, map[string]any{"type": "image", "source": map[string]any{"type": "base64", "media_type": "image/png", "data": base64.StdEncoding.EncodeToString([]byte(img[2]))}}) + } + return content +} + // 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 @@ -352,6 +370,11 @@ func fakeClaude(args []string) { takeText := func(p string) { mu.Lock() defer mu.Unlock() + // FAKE_CUT: a paste over 1024 bytes loses its whole blocks, as + // Windows 10's own ConPTY lost them (#5205): the tail is left + if os.Getenv("FAKE_CUT") == "1" && len(p) > 1024 { + p = p[len(p)/1024*1024:] + } draw := p if breaks := strings.Count(p, "\n"); len(p) > 800 || breaks > 2 { pasted++ @@ -438,6 +461,7 @@ func fakeClaude(args []string) { continue } line := typed.String() + asTyped := line // what the transcript records, as Claude Code does (fakeUserRow) typed.Reset() drawn.Reset() mu.Unlock() @@ -513,7 +537,7 @@ func fakeClaude(args []string) { } 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}}, + map[string]any{"type": "user", "message": map[string]any{"role": "user", "content": fakeUserRow(asTyped)}}, map[string]any{"type": "assistant", "requestId": "req_1", "message": map[string]any{"id": "msg_1", "model": "claude-haiku", "role": "assistant", "content": []any{map[string]any{"type": "text", "text": "echo: " + line}}}}, map[string]any{"type": "system", "subtype": "turn_duration"}, @@ -723,6 +747,29 @@ func TestShimImageNotTakenIsUnpastable(t *testing.T) { } } +// A message that reaches Claude Code cut, as Windows 10's own ConPTY cut +// one over 1KB (#5205), ends the turn in an error that begins Unpastable +// before any of its reply, which the bridge asks again as claude -p: it +// was answered as sent, the model given the cut's tail. A short one on the +// same console is answered as before. +func TestShimCutMessageIsUnpastable(t *testing.T) { + long := "K-HEAD " + strings.Repeat("filler words ", 400) + " K-TAIL" + out := runShim(t, []string{"FAKE_CUT=1"}, append([]string{fakePath(t)}, pArgs...), []string{long}, 2) + if r := out[1]; r["type"] != "result" || r["is_error"] != true || !strings.HasPrefix(fmt.Sprint(r["result"]), Unpastable) || + !strings.Contains(fmt.Sprint(r["result"]), "characters") { + t.Fatalf("a cut message ended %v, want an error beginning %q", out, Unpastable) + } + for _, m := range out { + if m["type"] == "assistant" || m["type"] == "stream_event" { + t.Fatalf("a cut message's reply got out: %v", out) + } + } + short := runShim(t, []string{"FAKE_CUT=1"}, append([]string{fakePath(t)}, pArgs...), []string{"hello"}, 3) + if r := short[2]; r["type"] != "result" || r["is_error"] != false { + t.Fatalf("a short message ended %v, want answered", short) + } +} + // 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 diff --git a/internal/claudetui/whole.go b/internal/claudetui/whole.go new file mode 100644 index 000000000..827da48f0 --- /dev/null +++ b/internal/claudetui/whole.go @@ -0,0 +1,481 @@ +package claudetui + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "io" + "slices" + "strings" + "time" + "unicode" + "unicode/utf8" +) + +// A message is checked whole once Claude Code has it: the words its +// transcript holds of it against those pasted. A console that loses part +// of a paste (Windows 10's own ConPTY drops a long paste's marks and some +// of its blocks, #5205) gives Claude Code the rest, or the whole taken as +// many pastes with tags in the middle of its words, and the model answers +// that with nothing said. One that isn't whole ends the turn as +// Unpastable, before any of its reply, so the bridge asks it again as +// claude -p, which is sent the message itself. +// What Claude Code makes of the message once it has it is its own: a +// path it took as an image, as it says, isn't missing (sameWordsBut). + +// wholeWait is how long a message whose words no row holds yet waits for +// another row, in case the one read wasn't its. +const wholeWait = 2 * time.Second + +// words reads a message's words one space apart, as Claude Code keeps what +// is pasted whatever it trims, wraps, numbers or takes out: a run of white +// space, a paste tag or an image mark is a space, none at the ends, and a +// format character (a zero-width space) is nothing. It reads in place, so +// two messages are compared without a copy of either. +type words struct { + s string + i int + began bool // a letter was read + space bool // a space comes before the next letter +} + +// next is the next rune, ' ' for a space, -1 at the end. +func (w *words) next() rune { + for w.i < len(w.s) { + c := w.s[w.i] + if c == '<' || c == '[' { + if n := markAt(w.s[w.i:]); n > 0 { + w.i += n + w.space = w.began + continue + } + } + r, size := rune(c), 1 + if c >= utf8.RuneSelf { + r, size = utf8.DecodeRuneInString(w.s[w.i:]) + } + switch { + case 0x3000 < r && r < 0xfeff: + // CJK and the rest between: no white space, no format + // character (unicode.IsSpace, unicode.Cf) + if w.space { + w.space = false + return ' ' + } + case c < utf8.RuneSelf && asciiSpace[c] || c >= utf8.RuneSelf && unicode.IsSpace(r): + w.i += size + w.space = w.began + continue + case c >= utf8.RuneSelf && unicode.Is(unicode.Cf, r): + w.i += size + continue + case w.space: + w.space = false + return ' ' + } + w.i += size + w.began = true + return r + } + return -1 +} + +// asciiSpace is unicode.IsSpace's white space below 0x80. +var asciiSpace = [utf8.RuneSelf]bool{'\t': true, '\n': true, '\v': true, '\f': true, '\r': true, ' ': true} + +// markAt is the length of the paste tag (, or its +// end) or image mark ([Image #3]) s begins with, 0 for none. +func markAt(s string) int { + if s == "" || s[0] != '<' && s[0] != '[' { + return 0 + } + var head, tail string + var in func(byte) bool + switch { + case strings.HasPrefix(s, ``, isWord + case strings.HasPrefix(s, ``, isWord + case strings.HasPrefix(s, "[Image #"): + head, tail, in = "[Image #", "]", isDigit + default: + return 0 + } + n := len(head) + for n < len(s) && in(s[n]) { + n++ + } + if n == len(head) || !strings.HasPrefix(s[n:], tail) { + return 0 + } + return n + len(tail) +} + +func isDigit(c byte) bool { return '0' <= c && c <= '9' } +func isWord(c byte) bool { return isDigit(c) || c == '_' || 'a' <= c|0x20 && c|0x20 <= 'z' } + +// sameWords is whether a and b have the same words, read as words reads +// them; it stops at the first that differs. +func sameWords(a, b string) bool { + x, y := words{s: a}, words{s: b} + for { + r := x.next() + if r != y.next() { + return false + } + if r < 0 { + return true + } + } +} + +// sameWordsBut is sameWords with any of taken, each once, left out of a +// where b doesn't hold it: an image file's path Claude Code took as the +// image, as it says in a row after the message's (imageSources). n is +// how many were left out. With none taken it is sameWords, no copy made. +func sameWordsBut(a, b string, taken []string) (same bool, n int) { + if len(taken) == 0 { + return sameWords(a, b), 0 + } + used := make([]bool, len(taken)) + x, y := words{s: a}, words{s: b} + for { + if end := takenAt(x, y, taken, used); end > 0 { + x.i, x.space = end, x.began + n++ + continue + } + r := x.next() + if r != y.next() { + return false, n + } + if r < 0 { + return true, n + } + } +} + +// takenAt is where in x's words one of taken not yet used ends, quoted or +// not, when it is x's next word whole and y doesn't go on with it (Claude +// Code left it there): 0 when none is. +func takenAt(x, y words, taken []string, used []bool) int { + at := x + switch r := at.next(); { + case r == ' ': + // at.i is the next word's first byte + case r < 0 || x.began: + return 0 + default: + at.i -= utf8.RuneLen(r) + } + s := x.s[at.i:] + for k, p := range taken { + end := 0 + switch { + case used[k] || p == "": + continue + case strings.HasPrefix(s, p): + end = len(p) + case len(s) > len(p)+1 && (s[0] == '"' || s[0] == '\'') && strings.HasPrefix(s[1:], p) && s[1+len(p)] == s[0]: + end = len(p) + 2 + default: + continue + } + if end < len(s) && !(s[end] < utf8.RuneSelf && asciiSpace[s[end]]) || sameUpTo(x, y, at.i+end) { + continue + } + used[k] = true + return at.i + end + } + return 0 +} + +// sameUpTo is whether y goes on as x does till x has read up to stop. +func sameUpTo(x, y words, stop int) bool { + for x.i < stop { + if r := x.next(); r < 0 || r != y.next() { + return false + } + } + return true +} + +// letters counts s's characters as words reads them, its spaces aside. +func letters(s string) int { + w, n := words{s: s}, 0 + for r := w.next(); r >= 0; r = w.next() { + if r != ' ' { + n++ + } + } + return n +} + +// messageCut is a message Claude Code recorded otherwise than it was +// pasted: got and sent count its characters, white space aside, and +// gotImages and sentImages its images when its words were whole. +type messageCut struct{ got, sent, gotImages, sentImages int } + +func (e *messageCut) Error() string { + switch { + case e.gotImages < e.sentImages: + return fmt.Sprintf("Claude Code recorded %d of the message's %d images%s", e.gotImages, e.sentImages, cutHint()) + case e.got < e.sent: + return fmt.Sprintf("Claude Code recorded %d of the message's %d characters%s", e.got, e.sent, cutHint()) + } + return "Claude Code recorded the message otherwise than it was pasted" + cutHint() +} + +// heardRow is what the transcript recorded of a message: its words, and +// how many images it holds, -1 where a row doesn't say (a queued +// message's, which is its words alone). +type heardRow struct { + words string + images int +} + +// wholeIn is nil when one of the messages the transcript recorded since one +// was sent (said) has the words pasted (sent) and its images, or when it +// recorded none it could read. Claude Code takes a pasted image file's +// path as the image, by rules of its own, and says which it took (taken): +// those are left out of the words, and their images out of the count. +func wholeIn(sent string, images int, said []heardRow, taken []string) error { + if len(said) == 0 { + return nil + } + got, gotImages, whole, unexplained := 0, images, false, false + for _, h := range said { + if extra := h.images - images; extra > 0 && pathsIn(sent, taken) < extra { + unexplained = true + continue + } + same, n := sameWordsBut(sent, h.words, taken) + if !same { + got = max(got, letters(h.words)) + continue + } + if h.images < 0 || h.images-n >= images { + return nil + } + whole, gotImages = true, max(0, h.images-n) + } + if unexplained { + return errUnexplained + } + cut := &messageCut{got: got, sent: letters(sent), gotImages: gotImages, sentImages: images} + if whole { + cut.got = cut.sent + } + return cut +} + +// errUnexplained is a row with more images than were pasted, for which +// Claude Code hasn't said (yet) that it took as many of the paste's +// paths: one it doesn't say, says late or says otherwise (a path it +// made its own) isn't judged, rather than failed each time it is sent. +var errUnexplained = errors.New("Claude Code took words of the message as images it didn't name") + +// pathsIn counts the paths of taken that sent holds. +func pathsIn(sent string, taken []string) int { + n := 0 + for _, p := range taken { + if p != "" && strings.Contains(sent, p) { + n++ + } + } + return n +} + +// checkWhole is wholeIn for a message just sent, given wholeWait for the +// row that is its, and for what Claude Code says it took as images. +func (s *shim) checkWhole(sent string, images int) error { + s.hold() + by := time.After(wholeWait) + for { + s.rowsMu.Lock() + said, taken := slices.Clone(s.said), slices.Clone(s.taken) + s.rowsMu.Unlock() + err := wholeIn(sent, images, said, taken) + if err == nil { + return s.unhold(nil) + } + select { + case <-s.rowsCh: + continue + case <-by: + case <-s.exited: + if !errors.Is(err, errUnexplained) { + err = fmt.Errorf("%w; Claude Code ended (%v): %s", err, s.exit, s.lastScreen()) + } + } + if errors.Is(err, errUnexplained) { + err = nil + } + return s.unhold(err) + } +} + +// heard keeps what a message that reached the transcript holds while one +// sent is checked (said isn't nil from send to checkWhole's end); a row of +// one comes before its sawRow. row is read only then. +func (s *shim) heard(row func() heardRow) { + s.rowsMu.Lock() + checking := s.said != nil + s.rowsMu.Unlock() + if !checking { + return + } + h := row() + if h.words == "" && h.images <= 0 { + return + } + s.rowsMu.Lock() + if s.said != nil { + s.said = append(s.said, h) + } + s.rowsMu.Unlock() +} + +// heardTaken keeps the image files' paths Claude Code says, in a row after +// a message's, it took as the images, while one sent is checked, and has +// it checked again. +func (s *shim) heardTaken(raw json.RawMessage) { + s.rowsMu.Lock() + checking := s.said != nil + s.rowsMu.Unlock() + if !checking { + return + } + paths := imageSources(raw) + if len(paths) == 0 { + return + } + s.rowsMu.Lock() + if s.said != nil { + s.taken = append(s.taken, paths...) + } + s.rowsMu.Unlock() + select { + case s.rowsCh <- struct{}{}: + default: + } +} + +// heardAll ends what heard and heardTaken keep, as send returns. +func (s *shim) heardAll() { + s.rowsMu.Lock() + s.said, s.taken = nil, nil + s.rowsMu.Unlock() +} + +// heardTaken tells an emitter that checks messages whole (shim) of a meta +// row, which may say what Claude Code took as images. +func (t *translator) heardTaken(raw json.RawMessage) { + if h, ok := t.out.(interface{ heardTaken(json.RawMessage) }); ok { + h.heardTaken(raw) + } +} + +// imageSource begins a text block of the meta row Claude Code records +// after a message for each image file's path it took as the image: +// "[Image: source: C:\a\x.png]" (2.1.319). +const imageSource = "[Image: source: " + +// imageSources is the paths a meta row says were taken as images. +func imageSources(raw json.RawMessage) []string { + if !bytes.Contains(raw, []byte(imageSource)) { + return nil + } + var m struct { + Content []struct { + Type string `json:"type"` + Text string `json:"text"` + } `json:"content"` + } + _ = json.Unmarshal(raw, &m) + var paths []string + for _, b := range m.Content { + if p, ok := strings.CutPrefix(b.Text, imageSource); ok && b.Type == "text" && strings.HasSuffix(p, "]") { + paths = append(paths, p[:len(p)-1]) + } + } + return paths +} + +// heard tells an emitter that checks messages whole (shim) what one that +// reached the transcript holds. +func (t *translator) heard(row func() heardRow) { + if h, ok := t.out.(interface{ heard(func() heardRow) }); ok { + h.heard(row) + } +} + +// promptRow is what a user row's message holds: its text, or its text +// blocks one after another, and its image blocks. +func promptRow(raw json.RawMessage) heardRow { + var m struct { + Content json.RawMessage `json:"content"` + } + if json.Unmarshal(raw, &m) != nil { + return heardRow{} + } + var s string + if json.Unmarshal(m.Content, &s) == nil { + return heardRow{words: s} + } + var blocks []struct { + Type string `json:"type"` + Text string `json:"text"` + } + _ = json.Unmarshal(m.Content, &blocks) + var h heardRow + var b strings.Builder + for _, bl := range blocks { + switch bl.Type { + case "text": + b.WriteString(bl.Text) + b.WriteString("\n") + case "image": + h.images++ + } + } + h.words = b.String() + return h +} + +// tell writes v past what is held (hold): a turn's failure. +func (s *shim) tell(v any) { + b, _ := json.Marshal(v) + s.outMu.Lock() + defer s.outMu.Unlock() + _, _ = s.out.Write(append(b, '\n')) +} + +// hold keeps what Claude Code answers while its message is checked: it +// asks Anthropic as soon as it records the message (25ms after), and a +// quick model answered words cut, its result let out, within the time +// waited for the message's other rows (wholeWait): the check's error came +// after the turn had ended (Haiku, 64K on Windows 10's console). +func (s *shim) hold() { + s.outMu.Lock() + s.held = new(bytes.Buffer) + s.outMu.Unlock() +} + +// unhold lets out what was held when the message was whole (err nil), +// and drops it, and all after it, when it wasn't: the turn's failure is +// told past it (tell). +func (s *shim) unhold(err error) error { + s.outMu.Lock() + defer s.outMu.Unlock() + if err != nil { + s.held = io.Discard + return err + } + if b, ok := s.held.(*bytes.Buffer); ok { + _, _ = s.out.Write(b.Bytes()) + } + s.held = nil + return nil +} diff --git a/internal/claudetui/whole_test.go b/internal/claudetui/whole_test.go new file mode 100644 index 000000000..d0d0c149a --- /dev/null +++ b/internal/claudetui/whole_test.go @@ -0,0 +1,227 @@ +package claudetui + +import ( + "encoding/json" + "errors" + "slices" + "strings" + "testing" + "unicode" +) + +// TestWholeIn: the words Claude Code records of a pasted message are taken +// as whole whatever it trims, wraps, numbers or takes out, and a message +// that lost a block of its words is not (#5205, which lost 1 KB blocks), +// nor one that lost an image. +func TestWholeIn(t *testing.T) { + long := strings.Repeat("line of words 中文 ", 400) + cases := []struct { + name string + sent string + said []string + whole bool + images int // sent + rows []heardRow // said, with its images + }{ + {"as sent", "hello there", []string{"hello there"}, true, 0, nil}, + {"trimmed and wrapped", "\n/command and more\n", []string{"/command and more"}, true, 0, nil}, + {"a long paste's tags", long, []string{"\n\n" + long + "\n\n"}, true, 0, nil}, + {"image marks", "look at this\n\n", []string{"[Image #1] look at this"}, true, 0, nil}, + {"a zero-width space taken out", "a\u200bb", []string{"ab"}, true, 0, nil}, + {"tabs as spaces", "a\tb", []string{"a b"}, true, 0, nil}, + {"the user's mark", userMark + "go on", []string{"[user message]\ngo on"}, true, 0, nil}, + {"a later row is its", "the message", []string{"another row", "the message"}, true, 0, nil}, + {"no row read", "the message", nil, true, 0, nil}, + {"a block lost", long, []string{long[:1024] + long[2048:]}, false, 0, nil}, + {"its end lost", long, []string{long[:len(long)/2]}, false, 0, nil}, + {"taken as many pastes", long, []string{"\n" + long[:990] + "\n\n\n" + long[990:] + "\n"}, false, 0, nil}, + {"other words", "the message", []string{"another row"}, false, 0, nil}, + {"its images", "look\n", nil, true, 2, []heardRow{{"[Image #1] [Image #2] look", 2}}}, + {"an image lost", "look\n", nil, false, 2, []heardRow{{"[Image #1] look", 1}}}, + {"an image alone", "", nil, true, 1, []heardRow{{"[Image #1]", 1}}}, + {"a queued row says no images", "look\n", nil, true, 1, []heardRow{{"look", -1}}}, + {"images, but a word lost", "look here\n", nil, false, 1, []heardRow{{"look", 1}}}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + rows := c.rows + for _, w := range c.said { + rows = append(rows, heardRow{w, 0}) + } + err := wholeIn(c.sent, c.images, rows, nil) + if (err == nil) != c.whole { + t.Fatalf("wholeIn = %v, want whole %v", err, c.whole) + } + var cut *messageCut + if err != nil && !errors.As(err, &cut) { + t.Fatalf("wholeIn = %#v, want a messageCut", err) + } + }) + } +} + +// BenchmarkWholeIn: a 256 KB message checked against its record, a long +// paste's, read in place. +func BenchmarkWholeIn(b *testing.B) { + sent := strings.Repeat("line of words 中文 and more\n", 256<<10/30) + said := []heardRow{{"\n\n" + sent + "\n", 0}} + b.SetBytes(int64(len(sent))) + b.ReportAllocs() + for b.Loop() { + if wholeIn(sent, 0, said, nil) != nil { + b.Fatal("not whole") + } + } +} + +// TestWordsSkipRange: words reads U+3001 to U+FEFE as letters without +// asking unicode, as none of them is white space or a format character. +func TestWordsSkipRange(t *testing.T) { + for r := rune(0x3001); r < 0xfeff; r++ { + if unicode.IsSpace(r) || unicode.Is(unicode.Cf, r) { + t.Fatalf("%U is white space or a format character", r) + } + } +} + +// TestHold: what Claude Code answers while its message is checked is let +// out after the check when the message was whole, and never when it +// wasn't, the check's error alone told. +func TestHold(t *testing.T) { + var b strings.Builder + s := &shim{out: &b, sid: "s1"} + s.hold() + s.emit(map[string]any{"type": "stream_event"}) + if b.Len() > 0 { + t.Fatal("an answer got out while its message was checked") + } + if s.unhold(nil) != nil || !strings.Contains(b.String(), "stream_event") { + t.Fatalf("a whole message's answer wasn't let out: %q", b.String()) + } + s.emit(map[string]any{"type": "assistant"}) + if !strings.Contains(b.String(), "assistant") { + t.Fatal("held after the check") + } + b.Reset() + s.hold() + s.emit(map[string]any{"type": "stream_event"}) + err := s.unhold(&messageCut{got: 1, sent: 2}) + s.emit(map[string]any{"type": "result", "subtype": "success"}) + s.tell(map[string]any{"type": "result", "is_error": true, "result": Unpastable + err.Error()}) + if strings.Contains(b.String(), "stream_event") || strings.Contains(b.String(), "success") || + !strings.Contains(b.String(), Unpastable) { + t.Fatalf("a cut message's answer got out: %q", b.String()) + } +} + +// TestWholeInTaken: the image files' paths Claude Code says it took as +// images are left out of the words pasted, where it recorded the message +// without them, and their images out of the count; any other words lost +// still fail it (planner2's screenshots, a worker's summary of them, +// 2.1.319). +func TestWholeInTaken(t *testing.T) { + a, b := `C:\s\a.png`, `C:\s\b.png` + long := strings.Repeat("line of words 中文\n", 400) + cases := []struct { + name string + sent string + images int + row heardRow + taken []string + whole bool + }{ + {"lines taken", "fix this\n" + a + "\nand this\n" + b + "\n", 0, + heardRow{"[Image #1] [Image #2]\n\n\nfix this\nand this\n\n", 2}, []string{a, b}, true}, + {"two on a line", a + " " + b + "\nlook", 0, heardRow{"[Image #1] [Image #2]look", 2}, []string{a, b}, true}, + {"quoted, with a space", `"C:\s b\a.png"` + "\nlook", 0, heardRow{"[Image #1]look", 1}, []string{`C:\s b\a.png`}, true}, + {"one left as words", a + "\n" + `C:\s\missing.png` + "\nmore", 0, heardRow{"[Image #1]" + `C:\s\missing.png` + "\nmore", 1}, []string{a}, true}, + {"more on its line stays", a + "|\n" + a + "\n", 0, heardRow{"[Image #1]" + a + "|", 1}, []string{a}, true}, + {"the same path left in words before", "see " + a + " here\n" + a + "\n", 0, heardRow{"[Image #1]see " + a + " here", 1}, []string{a}, true}, + {"beside an image pasted", "look\n" + a, 1, heardRow{"[Image #1] [Image #2]look", 2}, []string{a}, true}, + {"one pasted as an image, its path not in the words", "look", 1, heardRow{"[Image #1] look", 1}, []string{`C:\tmp\paste.png`}, true}, + {"a long one with paths, whole", long + a + "\n" + long, 0, heardRow{"[Image #1]" + long + long, 1}, []string{a}, true}, + {"paths taken, a word lost", a + "\nlook here\n", 0, heardRow{"[Image #1]look", 1}, []string{a}, false}, + {"a long one with paths, a block lost", long + a + "\n" + long, 0, heardRow{"[Image #1]" + long[:1024] + long[2048:] + long, 1}, []string{a}, false}, + {"a path taken, an image pasted lost", "look\n" + a, 1, heardRow{"[Image #1]look", 1}, []string{a}, false}, + {"a path at the start and the end", a + "\nlook\n" + b, 0, heardRow{"[Image #1] [Image #2]look", 2}, []string{a, b}, true}, + {"one path taken twice", a + "\nlook\n" + a + "\n", 0, heardRow{"[Image #1] [Image #2]look", 2}, []string{a, a}, true}, + {"one path twice, taken once", a + "\nlook\n" + a + "\n", 0, heardRow{"[Image #1]look\n" + a, 1}, []string{a}, true}, + {"after a CJK word", "看图\n" + a + "\n中文", 0, heardRow{"[Image #1]看图\n中文", 1}, []string{a}, true}, + {"cut in the middle of a path", "look\n" + a + "\nmore", 0, heardRow{"[Image #1]look\nC:\\s", 1}, []string{a}, false}, + {"a word lost between paths", a + "\nlook\n" + b + "\nmore", 0, heardRow{"[Image #1] [Image #2]look", 2}, []string{a, b}, false}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + err := wholeIn(c.sent, c.images, []heardRow{c.row}, c.taken) + if (err == nil) != c.whole { + t.Fatalf("wholeIn = %v, want whole %v", err, c.whole) + } + var cut *messageCut + if err != nil && !errors.As(err, &cut) { + t.Fatalf("wholeIn = %#v, want a messageCut", err) + } + }) + } +} + +// TestWholeInUnexplained: a row with more images than were pasted, for +// which Claude Code hasn't said it took as many of the paste's paths +// (not yet, not at all, or a path made its own, as in WSL), is not judged +// rather than failed each time; a cut is still one where it has said. +func TestWholeInUnexplained(t *testing.T) { + a := `C:\s\a.png` + for _, c := range []struct { + name string + sent string + row heardRow + taken []string + }{ + {"not yet said", a + "\nlook", heardRow{"[Image #1]look", 1}, nil}, + {"said otherwise", a + "\nlook", heardRow{"[Image #1]look", 1}, []string{"/mnt/c/s/a.png"}}, + {"fewer said than taken", a + "\n" + `C:\s\b.png` + "\nlook", heardRow{"[Image #1] [Image #2]look", 2}, []string{a}}, + } { + t.Run(c.name, func(t *testing.T) { + if err := wholeIn(c.sent, 0, []heardRow{c.row}, c.taken); !errors.Is(err, errUnexplained) { + t.Fatalf("wholeIn = %v, want errUnexplained", err) + } + }) + } + // a later row of the message, whole, is still taken + if err := wholeIn("look", 0, []heardRow{{"[Image #1]", 1}, {"look", 0}}, nil); err != nil { + t.Fatalf("wholeIn = %v, want whole", err) + } +} + +// TestHeardTaken: the paths Claude Code says it took are kept only while a +// message is checked, have it checked again, and end with it. +func TestHeardTaken(t *testing.T) { + row := json.RawMessage(`{"role":"user","content":[{"type":"text","text":"[Image: source: C:\\s\\a.png]"}]}`) + s := &shim{rowsCh: make(chan struct{}, 1)} + s.heardTaken(row) + if s.taken != nil || len(s.rowsCh) > 0 { + t.Fatal("kept with no message checked") + } + s.said = []heardRow{} + s.heardTaken(row) + if !slices.Equal(s.taken, []string{`C:\s\a.png`}) || len(s.rowsCh) != 1 { + t.Fatalf("taken %q, %d signals", s.taken, len(s.rowsCh)) + } + s.heardAll() + if s.said != nil || s.taken != nil { + t.Fatal("kept after the message") + } +} + +// TestImageSources: the meta row Claude Code records after a message for +// the paths it took as images (2.1.319), and rows that aren't it. +func TestImageSources(t *testing.T) { + row := `{"role":"user","content":[{"type":"text","text":"[Image: source: C:\\s\\red.png]"},{"type":"text","text":"[Image: source: C:\\s b\\blue.png]"}]}` + if got := imageSources(json.RawMessage(row)); !slices.Equal(got, []string{`C:\s\red.png`, `C:\s b\blue.png`}) { + t.Fatalf("imageSources = %q", got) + } + for _, r := range []string{`{"role":"user","content":"[Image: source: C:\\x.png]"}`, `{"role":"user","content":[{"type":"text","text":"caveat"}]}`} { + if got := imageSources(json.RawMessage(r)); got != nil { + t.Fatalf("imageSources(%s) = %q", r, got) + } + } +}