Skip to content

Commit 8bbc86a

Browse files
Agentclaude
andcommitted
Fix readline EOF: tcflush stdin before each Readline() call (#334)
Root cause (confirmed by research): ergochat/readline sends \033[6n (cursor position query) before each prompt. During long LLM calls, the terminal response \033[row;colR arrives late and sits in stdin. On the next Readline(), these stale bytes cause io.EOF. Same bug exists in Node.js readline (nodejs/node#57602) and Ruby reline (ruby/reline#674). Fix: call POSIX tcflush(TCIFLUSH) via TIOCFLUSH ioctl after each agent Run() completes, before the next Readline(). Discards any stale cursor position responses from stdin. Also kept EOF retry as safety net (1 retry with 300ms pause). Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
1 parent 6e4f3e0 commit 8bbc86a

2 files changed

Lines changed: 34 additions & 0 deletions

File tree

‎internal/agent/coderepl.go‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -296,6 +296,12 @@ func (cr *CodeREPL) Run(ctx context.Context) error {
296296
cr.renderer.writeContent("")
297297
cr.renderer.mu.Unlock()
298298
}
299+
300+
// Flush stale cursor position responses from stdin before next Readline().
301+
// readline sends \033[6n (cursor position query) on every prompt.
302+
// During long LLM calls, the response \033[row;colR arrives late and
303+
// causes Readline() to return io.EOF. tcflush discards these stale bytes.
304+
flushStdin()
299305
}
300306
}
301307

‎internal/agent/flush_unix.go‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
//go:build !windows
2+
3+
package agent
4+
5+
import (
6+
"os"
7+
"syscall"
8+
"unsafe"
9+
)
10+
11+
// flushStdin discards any data received on stdin but not yet read.
12+
// Prevents stale cursor position responses (\033[row;colR) from
13+
// readline's \033[6n queries from causing Readline() to return io.EOF.
14+
//
15+
// Uses POSIX tcflush(TCIFLUSH) via ioctl. Works on macOS and Linux.
16+
func flushStdin() {
17+
fd := os.Stdin.Fd()
18+
19+
// TCIFLUSH = 1 (flush data received but not read)
20+
// On macOS: TIOCFLUSH with FREAD flag
21+
// On Linux: TCFLSH ioctl with TCIFLUSH arg
22+
//
23+
// Use the portable approach: TIOCFLUSH exists on both platforms.
24+
// TIOCFLUSH (0x80047410 on macOS) flushes the specified queues.
25+
// Pass FREAD (1) to flush input only.
26+
fread := int32(1) // FREAD = flush input queue
27+
syscall.Syscall(syscall.SYS_IOCTL, fd, 0x80047410, uintptr(unsafe.Pointer(&fread)))
28+
}

0 commit comments

Comments
 (0)