From fe6533ad8bf797ce9dfc6a9297a997fa4661d7fc Mon Sep 17 00:00:00 2001 From: yetone Date: Thu, 5 Nov 2026 04:51:45 +0800 Subject: [PATCH] claudetui: Claude Code's exit is recorded once its last words are read (#5283) The shim closed `exited` as soon as cmd.Wait returned, which can be before the PTY reader has read what Claude Code wrote just before it ended. Every "Claude Code ended ..." error then carried an empty screen in place of the reason it gave, which is what TestShimNeverPrints/ failed_start saw on a loaded ubuntu CI runner (run 41899504898): "ended before it showed its prompt (exit status 3): " with no "something went wrong". The shim's own stderr line is meant; the test checks the reason is in it. Now the exit goes through shim.ended: on Unix it waits for read to end (the master reads EIO once the last slave writer is gone), on Windows, whose pseudo console stays open, until reading has gone quiet for 250ms after its first bytes; two seconds at most either way, for a terminal a child of Claude Code keeps open. Run: - Red before: with a 200ms sleep injected at the top of read(), the old code failed failed_start 5 of 5 on Linux (wsl-run, magpie-desktop) with CI's exact message; with the fix and the same injection, 50 of 50 green. Without injection the old code passed 300 of 300 there (an idle machine never loses the race). - New TestShimEndedAfterLastWordsRead (a reader given the last words 300ms late, terminal ending and staying open). Broken by hand (ended records at once): red on both subtests; restored: green 20 of 20 with TestShimNeverPrints on Linux. - internal/claudetui: Linux (wsl-run) -count=3 ok; macOS (mote-run) -race -count=2 ok; Windows (win-run) -count=2: only TestShimFirstMessageWaitsForTools red, the same at origin/main 49e382735 without this change (#4810, commented). - go vet ./internal/claudetui with GOOS darwin, linux, windows (mote). - gofmt -l clean. Not tried: a real Claude Code ending before its prompt (only the fake); the Windows quiet rule on a really slow ConPTY reader. --- internal/claudetui/child_unix.go | 4 +-- internal/claudetui/child_windows.go | 7 +++--- internal/claudetui/tui.go | 39 ++++++++++++++++++++++++++++- internal/claudetui/tui_test.go | 36 ++++++++++++++++++++++++++ 4 files changed, 79 insertions(+), 7 deletions(-) diff --git a/internal/claudetui/child_unix.go b/internal/claudetui/child_unix.go index 15610912c..140c1c1b9 100644 --- a/internal/claudetui/child_unix.go +++ b/internal/claudetui/child_unix.go @@ -44,9 +44,7 @@ func (s *shim) start(path string, args []string) error { tty.Close() s.pty, s.cmd = m, cmd go func() { - err := cmd.Wait() - s.exit = err - close(s.exited) + s.ended(cmd.Wait(), false) }() go s.read() return nil diff --git a/internal/claudetui/child_windows.go b/internal/claudetui/child_windows.go index f89e24e1e..ea2ce1dd5 100644 --- a/internal/claudetui/child_windows.go +++ b/internal/claudetui/child_windows.go @@ -77,12 +77,13 @@ func (s *shim) start(path string, args []string) error { go func() { _, _ = windows.WaitForSingleObject(h, windows.INFINITE) var code uint32 + var exit error if err := windows.GetExitCodeProcess(h, &code); err != nil { - s.exit = err + exit = err } else if code != 0 { - s.exit = fmt.Errorf("exit status %d", code) + exit = fmt.Errorf("exit status %d", code) } - close(s.exited) + s.ended(exit, true) }() go s.read() return nil diff --git a/internal/claudetui/tui.go b/internal/claudetui/tui.go index 3ea693d12..269731af4 100644 --- a/internal/claudetui/tui.go +++ b/internal/claudetui/tui.go @@ -92,6 +92,9 @@ type shim struct { exited chan struct{} exit error + // readDone closes as read ends; nread counts the bytes it has read + readDone chan struct{} + nread atomic.Int64 // images is where a message's images are written for their paths to // be pasted, made with the first; images counts them @@ -143,7 +146,7 @@ func Run(args []string) error { return fmt.Errorf("Claude Code's interactive mode didn't run: %s", why) } args = interactiveArgs(pargs[len(wslArgs(wsl)):]) - s := &shim{out: os.Stdout, changed: make(chan struct{}, 1), rowsCh: make(chan struct{}, 1), exited: make(chan struct{}), wsl: wsl, listed: mcpListed(args)} + s := &shim{out: os.Stdout, changed: make(chan struct{}, 1), rowsCh: make(chan struct{}, 1), exited: make(chan struct{}), readDone: make(chan struct{}), wsl: wsl, listed: mcpListed(args)} resume := "" for i, a := range args { if a == "--resume" && i+1 < len(args) { @@ -274,13 +277,47 @@ func childEnv(extra ...string) []string { return append(append(env, extra...), "TERM=xterm-256color") } +// ended records how Claude Code ended, err, once read has what it drew +// before it ended: its exit can be seen before the bytes it wrote just +// before are read, and the error said then carried an empty screen, not +// the reason it gave (#5283, a loaded Linux CI runner). A terminal that +// ends with its last writer (Unix) is read to its end; a pseudo console +// that stays open (Windows, open) is read until it has gone quiet after +// its first bytes. Two seconds at most, for a terminal a child of Claude +// Code keeps open. +func (s *shim) ended(err error, open bool) { + if s.readDone != nil { + limit := time.After(2 * time.Second) + for last := int64(0); ; { + var tick <-chan time.Time + if open { + tick = time.After(250 * time.Millisecond) + } + select { + case <-s.readDone: + case <-limit: + case <-tick: + if n := s.nread.Load(); n == 0 || n != last { + last = n + continue + } + } + break + } + } + s.exit = err + close(s.exited) +} + // read keeps the tail of what Claude Code draws, and answers what it asks // of the terminal: where the cursor is, and what terminal it is. func (s *shim) read() { + defer close(s.readDone) buf := make([]byte, 64<<10) for { n, err := s.pty.Read(buf) if n > 0 { + s.nread.Add(int64(n)) d := buf[:n] if bytes.Contains(d, []byte("\x1b[6n")) { _, _ = io.WriteString(s.pty, "\x1b[1;1R") diff --git a/internal/claudetui/tui_test.go b/internal/claudetui/tui_test.go index 85d455168..f0f9810f1 100644 --- a/internal/claudetui/tui_test.go +++ b/internal/claudetui/tui_test.go @@ -1038,3 +1038,39 @@ func TestShownWaitGrowsWithThePaste(t *testing.T) { t.Fatalf("a 3MB paste waits %v", got) } } + +// Claude Code's exit is seen only once what it wrote before it is read: +// seen first, the reason it gave was left out of the error, which had an +// empty screen (#5283, ubuntu CI). Here the reader is given the last +// words late, as a loaded machine schedules it, on a terminal that ends +// (Unix) and on one that stays open (Windows' pseudo console). +func TestShimEndedAfterLastWordsRead(t *testing.T) { + for _, closes := range []bool{true, false} { + t.Run(fmt.Sprintf("terminal ends %v", closes), func(t *testing.T) { + r, w := io.Pipe() + t.Cleanup(func() { _ = w.Close() }) + s := &shim{changed: make(chan struct{}, 1), exited: make(chan struct{}), readDone: make(chan struct{}), + pty: struct { + io.Reader + io.Writer + }{r, io.Discard}} + go s.read() + go s.ended(fmt.Errorf("exit status 3"), !closes) + go func() { + time.Sleep(300 * time.Millisecond) + _, _ = io.WriteString(w, "something went wrong\r\n") + if closes { + _ = w.Close() + } + }() + select { + case <-s.exited: + case <-time.After(10 * time.Second): + t.Fatal("the exit was never recorded") + } + if got := s.lastScreen(); !strings.Contains(got, "something went wrong") { + t.Fatalf("the exit was recorded with the screen %q", got) + } + }) + } +}