From 45ae4b76a57fa6817f89b4e63754679c55b10aa4 Mon Sep 17 00:00:00 2001 From: liyujun Date: Sun, 15 Nov 2026 20:57:50 +0800 Subject: [PATCH] fix(ui): stop mouse movement from typing escape codes into a focused agent A terminal can deliver one mouse report across two reads. When a read ends inside a report, Bubble Tea parses its ESC[ head as alt+'[' and the rest of the bytes as text, and focus forwards both into the agent's input. Its canHaveMoreData guard covers a buffer holding nothing but ESC and one rune, so a partial SGR report of any length is misread this way. Wrap stdin on Unix with a reader that frames input without waiting on a CSI: each read performs at most one terminal read, except a bounded wait for an SS3 head or half a UTF-8 character, and keeps a partial sequence for the next one. A broken SGR report ends at the first byte that cannot belong to it, so a typed key is delivered instead of swallowed. A lone ESC stays a key press unless the rest of its sequence is already queued, when it is joined to it. While a bracketed paste is open, bytes pass through as they arrive and the last five are remembered, so an end marker split across reads still closes the paste; broken CSI heads and undecidable bytes before a paste are removed so the paste keeps its bytes. A reset that lands during a read is applied by the read loop, so a length computed before it is never used to slice a cleared buffer. An SS3 head after a completed prefix, and an Escape or SS3 head after a paste, are resolved before returning; otherwise the cancel reader would wait for the next keystroke and merge it into the old head. The wait reads only the remaining output room, so it cannot take bytes it has no room to return. CSI parameter and intermediate bytes follow ECMA-48, so a mode report such as ESC[?2026;1$y stays whole instead of becoming text. Exec resets retained input after Bubble Tea stops its reader and before the child reads, and again after the child, clearing a canonical-mode EOF. It pins stdin to the terminal only when stdin is one, so ssh attach and editors keep a TTY. Known limits: a read that ends after ESC with the rest not yet queued treats it as the Escape key at a short-read boundary (a full buffer or a paste may hold it until the next read), so a report or paste marker split there remains uncovered; a partial generic CSI is held without a timeout and can consume a later byte as its final; known four-byte sequences (ESC[Oa, ESC[[A, ESC ESC [A) split inside the sequence read as their shorter forms, as they do in Bubble Tea at a read boundary; a 256-byte read of text is held by Bubble Tea itself until the next read, and a trailing ESC at a full buffer is held for the next read; stdin that is not a terminal keeps Bubble Tea's own /dev/tty reader; a paste whose end marker never arrives stays open; an undecidable byte immediately before a paste is dropped to keep the paste; reset drops bytes the guard already holds, not bytes still in the terminal or queued in Bubble Tea. Windows keeps Bubble Tea's native reader, whose console input is not an ANSI byte stream. --- internal/inputguard/guard.go | 91 ++ internal/inputguard/guard_bubbletea_test.go | 951 ++++++++++++++++++++ internal/inputguard/guard_frame_test.go | 37 + internal/inputguard/guard_test.go | 806 +++++++++++++++++ internal/inputguard/guard_unix.go | 539 +++++++++++ internal/inputguard/wait_unix.go | 25 + internal/inputguard/wait_unix_test.go | 46 + internal/ui/terminal/exec.go | 25 +- internal/ui/terminal/exec_test.go | 66 +- main.go | 1 + main_input_other.go | 9 + main_input_unix.go | 24 + 12 files changed, 2614 insertions(+), 6 deletions(-) create mode 100644 internal/inputguard/guard.go create mode 100644 internal/inputguard/guard_bubbletea_test.go create mode 100644 internal/inputguard/guard_frame_test.go create mode 100644 internal/inputguard/guard_test.go create mode 100644 internal/inputguard/guard_unix.go create mode 100644 internal/inputguard/wait_unix.go create mode 100644 internal/inputguard/wait_unix_test.go create mode 100644 main_input_other.go create mode 100644 main_input_unix.go diff --git a/internal/inputguard/guard.go b/internal/inputguard/guard.go new file mode 100644 index 00000000..129dd71e --- /dev/null +++ b/internal/inputguard/guard.go @@ -0,0 +1,91 @@ +// Package inputguard frames terminal input for Bubble Tea. Complete messages +// are handed over whole; a broken SGR report is cut at the byte that cannot +// belong to it, a CSI keeps its intermediate bytes, and a short SS3 key or +// half a UTF-8 character waits briefly for its remaining bytes. +package inputguard + +import "unicode/utf8" + +const esc = 0x1b + +// completeLen is the length of the longest prefix that ends on a message +// boundary: after a whole escape sequence or rune. A tail inside a sequence is +// left for the next read. +func completeLen(b []byte) int { + i, done := 0, 0 + for i < len(b) { + if b[i] != esc { + _, size := utf8.DecodeRune(b[i:]) + if size == 1 && !utf8.FullRune(b[i:]) { + return done + } + i += size + done = i + continue + } + end := escapeEnd(b, i) + if end < 0 { + return done + } + i, done = end, end + } + return done +} + +// escapeEnd returns the index just past the escape sequence starting at i, or +// -1 while the bytes seen so far could still grow into one. CSI parameter and +// intermediate bytes are kept, so mode reports such as ?2026;1$y stay whole. +// Anything else is an ESC-prefixed key, which is how Bubble Tea reads it too. +func escapeEnd(b []byte, i int) int { + if i+1 >= len(b) { + return -1 + } + switch b[i+1] { + case '[': + sgr := i+2 < len(b) && b[i+2] == '<' + j := i + 2 + for j < len(b) && b[j] >= 0x30 && b[j] <= 0x3f { + j++ + } + for j < len(b) && b[j] >= 0x20 && b[j] <= 0x2f { + if b[j] == '$' && j > i+2 { + // urxvt ends its Shift+Home/End reports on '$' with no final. + if params := string(b[i+2 : j]); params == "7" || params == "8" { + return j + 1 + } + } + j++ + } + if j >= len(b) { + return -1 + } + if b[j] < 0x40 || b[j] > 0x7e { + return -1 + } + if sgr && b[j] != 'M' && b[j] != 'm' { + // An SGR report ends only on M or m; anything else is a break + // the caller turns into a key press. + return -1 + } + if b[j] == 'M' && j == i+2 { + // X10 mouse: the final byte carries three more. + if j+4 > len(b) { + return -1 + } + return j + 4 + } + return j + 1 + case 'O': + // SS3 carries one more byte. + if i+2 >= len(b) { + return -1 + } + return i + 3 + } + // An escape marking alt carries one rune. + if !utf8.FullRune(b[i+1:]) { + return -1 + } + _, size := utf8.DecodeRune(b[i+1:]) + return i + 1 + size +} diff --git a/internal/inputguard/guard_bubbletea_test.go b/internal/inputguard/guard_bubbletea_test.go new file mode 100644 index 00000000..c439b454 --- /dev/null +++ b/internal/inputguard/guard_bubbletea_test.go @@ -0,0 +1,951 @@ +//go:build unix + +package inputguard + +import ( + "io" + "os" + "strings" + "sync" + "testing" + "time" + + tea "github.com/charmbracelet/bubbletea" +) + +type msgRecorder struct { + msgs chan tea.Msg + started chan struct{} +} + +func (m *msgRecorder) Init() tea.Cmd { + return func() tea.Msg { + if m.started != nil { + close(m.started) + } + return nil + } +} + +func (m *msgRecorder) Update(msg tea.Msg) (tea.Model, tea.Cmd) { + select { + case m.msgs <- msg: + default: + } + return m, nil +} + +func (m *msgRecorder) View() string { return "" } + +type slowRecorder struct { + msgs chan tea.Msg + delay time.Duration + once sync.Once +} + +func (m *slowRecorder) Init() tea.Cmd { return nil } + +func (m *slowRecorder) Update(msg tea.Msg) (tea.Model, tea.Cmd) { + m.once.Do(func() { time.Sleep(m.delay) }) + m.msgs <- msg + return m, nil +} + +func (m *slowRecorder) View() string { return "" } + +// pipeInput returns the two ends of a pipe. Only the write end is closed in +// cleanup: Bubble Tea's kill path abandons its read loop, and closing the +// read end underneath it races with the cancel reader's own Fd call. +func pipeInput(t *testing.T) (*os.File, *os.File) { + t.Helper() + read, write, err := os.Pipe() + if err != nil { + t.Fatalf("pipe: %v", err) + } + t.Cleanup(func() { _ = write.Close() }) + return read, write +} + +// TestBubbleTeaNeverTurnsAMouseBurstIntoText is the regression for the leak +// seen in focus: a burst longer than Bubble Tea's read buffer leaves the rest +// of a report in the guard, and the next read can return nothing. Bubble Tea +// must not flush that remainder as alt+[ and plain text. +func TestBubbleTeaNeverTurnsAMouseBurstIntoText(t *testing.T) { + read, write := pipeInput(t) + recorder := &msgRecorder{msgs: make(chan tea.Msg, 256)} + program := tea.NewProgram(recorder, + tea.WithInput(New(read)), + tea.WithoutRenderer(), + tea.WithMouseCellMotion(), + ) + t.Cleanup(program.Kill) + go func() { _, _ = program.Run() }() + + burst := strings.Repeat("\x1b[<35;40;12M", 24) + if _, err := write.WriteString(burst); err != nil { + t.Fatalf("write burst: %v", err) + } + if _, err := write.WriteString("\x1b[<35;40"); err != nil { + t.Fatalf("write partial report: %v", err) + } + time.Sleep(20 * time.Millisecond) + if _, err := write.WriteString(";13M"); err != nil { + t.Fatalf("write report tail: %v", err) + } + + deadline := time.After(2 * time.Second) + mice := 0 + for mice < 25 { + select { + case msg := <-recorder.msgs: + switch msg := msg.(type) { + case tea.MouseMsg: + mice++ + case tea.KeyMsg: + t.Fatalf("Bubble Tea parsed input as %+v, want only mouse events", msg) + } + case <-deadline: + t.Fatalf("saw %d mouse events, want 25", mice) + } + } +} + +// TestBubbleTeaDeliversABurstLongerThanItsBuffer sends one burst with no +// follow-up write. The guard must not drain the terminal into its own buffer, +// or the rest of the burst waits for a keystroke the test never sends. +func TestBubbleTeaDeliversABurstLongerThanItsBuffer(t *testing.T) { + read, write := pipeInput(t) + const perEvent = 64 + recorder := &msgRecorder{msgs: make(chan tea.Msg, perEvent+8)} + program := tea.NewProgram(recorder, + tea.WithInput(New(read)), + tea.WithoutRenderer(), + tea.WithMouseCellMotion(), + ) + t.Cleanup(program.Kill) + go func() { _, _ = program.Run() }() + + if _, err := write.WriteString(strings.Repeat("\x1b[<35;40;12M", perEvent)); err != nil { + t.Fatalf("write burst: %v", err) + } + + deadline := time.After(3 * time.Second) + mice := 0 + for mice < perEvent { + select { + case msg := <-recorder.msgs: + switch msg := msg.(type) { + case tea.MouseMsg: + mice++ + case tea.KeyMsg: + t.Fatalf("Bubble Tea parsed input as %+v, want only mouse events", msg) + } + case <-deadline: + t.Fatalf("saw %d of %d mouse events; the burst stalled in the guard", mice, perEvent) + } + } +} + +// TestBubbleTeaKeepsASplitCharacterWhole pins that a character split across +// reads reaches the program as one rune, not a replacement and a fragment. +func TestBubbleTeaKeepsASplitCharacterWhole(t *testing.T) { + read, write := pipeInput(t) + recorder := &msgRecorder{msgs: make(chan tea.Msg, 8)} + program := tea.NewProgram(recorder, + tea.WithInput(New(read)), + tea.WithoutRenderer(), + ) + t.Cleanup(program.Kill) + go func() { _, _ = program.Run() }() + + if _, err := write.WriteString("a" + "中"[:1]); err != nil { + t.Fatalf("write: %v", err) + } + time.Sleep(5 * time.Millisecond) + if _, err := write.WriteString("中"[1:]); err != nil { + t.Fatalf("write: %v", err) + } + + deadline := time.After(2 * time.Second) + text := "" + for text != "a中" { + select { + case msg := <-recorder.msgs: + key, ok := msg.(tea.KeyMsg) + if !ok { + continue + } + text += string(key.Runes) + case <-deadline: + t.Fatalf("typed %q so far, want the whole character", text) + } + } +} + +// TestBubbleTeaKeepsASplitEscCharacterWhole covers an Alt-modified character +// split inside its UTF-8 bytes. +func TestBubbleTeaKeepsASplitEscCharacterWhole(t *testing.T) { + read, write := pipeInput(t) + recorder := &msgRecorder{msgs: make(chan tea.Msg, 8)} + program := tea.NewProgram(recorder, + tea.WithInput(New(read)), + tea.WithoutRenderer(), + ) + t.Cleanup(program.Kill) + go func() { _, _ = program.Run() }() + + if _, err := write.WriteString("\x1b" + "中"[:1]); err != nil { + t.Fatalf("write: %v", err) + } + time.Sleep(5 * time.Millisecond) + if _, err := write.WriteString("中"[1:]); err != nil { + t.Fatalf("write rest: %v", err) + } + + deadline := time.After(2 * time.Second) + for { + select { + case msg := <-recorder.msgs: + key, ok := msg.(tea.KeyMsg) + if ok && key.Alt && string(key.Runes) == "中" { + return + } + if ok { + t.Fatalf("parsed %+v, want Alt+中", key) + } + case <-deadline: + t.Fatal("Alt+中 did not arrive") + } + } +} + +// TestBubbleTeaKeepsASplitEscCharacterAfterText covers the same split after a +// complete text message. +func TestBubbleTeaKeepsASplitEscCharacterAfterText(t *testing.T) { + read, write := pipeInput(t) + recorder := &msgRecorder{msgs: make(chan tea.Msg, 8)} + program := tea.NewProgram(recorder, + tea.WithInput(New(read)), + tea.WithoutRenderer(), + ) + t.Cleanup(program.Kill) + go func() { _, _ = program.Run() }() + + if _, err := write.WriteString("a\x1b" + "中"[:1]); err != nil { + t.Fatalf("write: %v", err) + } + time.Sleep(5 * time.Millisecond) + if _, err := write.WriteString("中"[1:]); err != nil { + t.Fatalf("write rest: %v", err) + } + + deadline := time.After(2 * time.Second) + sawText, sawAlt := false, false + for !sawText || !sawAlt { + select { + case msg := <-recorder.msgs: + key, ok := msg.(tea.KeyMsg) + if !ok { + continue + } + if !key.Alt && string(key.Runes) == "a" { + sawText = true + continue + } + if key.Alt && string(key.Runes) == "中" { + sawAlt = true + continue + } + t.Fatalf("parsed %+v, want a and Alt+中", key) + case <-deadline: + t.Fatalf("text=%t alt=%t; want both", sawText, sawAlt) + } + } +} + +// TestBubbleTeaKeepsAReportCutAtTheBufferLimit pins the 256-byte case: when +// the caller's buffer ends exactly after a report's ESC, the rest must still +// arrive as a mouse event and never as an Escape key plus text. +func TestBubbleTeaKeepsAReportCutAtTheBufferLimit(t *testing.T) { + read, write := pipeInput(t) + recorder := &msgRecorder{msgs: make(chan tea.Msg, 8)} + program := tea.NewProgram(recorder, + tea.WithInput(New(read)), + tea.WithoutRenderer(), + tea.WithMouseCellMotion(), + ) + t.Cleanup(program.Kill) + go func() { _, _ = program.Run() }() + + const report = "\x1b[<35;40;12M" + if _, err := write.WriteString(strings.Repeat("a", 255) + report); err != nil { + t.Fatalf("write: %v", err) + } + deadline := time.After(2 * time.Second) + mice := 0 + for mice == 0 { + select { + case msg := <-recorder.msgs: + switch msg := msg.(type) { + case tea.MouseMsg: + mice++ + case tea.KeyMsg: + if msg.Type == tea.KeyEsc { + t.Fatal("the cut report became an Escape key") + } + } + case <-deadline: + t.Fatal("Bubble Tea did not receive the report") + } + } +} + +// TestSlowConsumerDoesNotTurnAReportIntoText pins that a stalled event loop +// does not make a later read treat a report already on its way as typing. +func TestSlowConsumerDoesNotTurnAReportIntoText(t *testing.T) { + read, write := pipeInput(t) + recorder := &slowRecorder{msgs: make(chan tea.Msg, 8), delay: 200 * time.Millisecond} + program := tea.NewProgram(recorder, + tea.WithInput(New(read)), + tea.WithoutRenderer(), + tea.WithMouseCellMotion(), + ) + t.Cleanup(program.Kill) + go func() { _, _ = program.Run() }() + + if _, err := write.WriteString("z"); err != nil { + t.Fatalf("write blocker: %v", err) + } + time.Sleep(20 * time.Millisecond) + if _, err := write.WriteString(strings.Repeat("a", 254) + "\x1b[<35;40;12M"); err != nil { + t.Fatalf("write report: %v", err) + } + deadline := time.After(3 * time.Second) + for { + select { + case msg := <-recorder.msgs: + switch msg := msg.(type) { + case tea.MouseMsg: + return + case tea.KeyMsg: + if msg.Type == tea.KeyEsc { + t.Fatal("the report became an Escape key") + } + } + case <-deadline: + t.Fatal("the report never arrived as a mouse event") + } + } +} + +// TestBubbleTeaPasteStartAtTheBufferLimit pins that a paste whose start +// marker lands on the 256-byte boundary still becomes one paste. +func TestBubbleTeaPasteStartAtTheBufferLimit(t *testing.T) { + read, write := pipeInput(t) + recorder := &msgRecorder{msgs: make(chan tea.Msg, 8)} + program := tea.NewProgram(recorder, + tea.WithInput(New(read)), + tea.WithoutRenderer(), + ) + t.Cleanup(program.Kill) + go func() { _, _ = program.Run() }() + + const text = "hello" + paste := strings.Repeat("a", 250) + "\x1b[200~" + text + "\x1b[201~" + if _, err := write.WriteString(paste); err != nil { + t.Fatalf("write: %v", err) + } + deadline := time.After(2 * time.Second) + for { + select { + case msg := <-recorder.msgs: + key, ok := msg.(tea.KeyMsg) + if ok && key.Paste { + if string(key.Runes) != text { + t.Fatalf("paste %q, want %q", string(key.Runes), text) + } + return + } + if ok && strings.ContainsRune(string(key.Runes), '[') { + t.Fatalf("parsed the paste marker as text: %q", string(key.Runes)) + } + case <-deadline: + t.Fatal("Bubble Tea did not deliver the paste") + } + } +} + +func TestBubbleTeaPasteThenEnter(t *testing.T) { + read, write := pipeInput(t) + recorder := &msgRecorder{msgs: make(chan tea.Msg, 8)} + program := tea.NewProgram(recorder, + tea.WithInput(New(read)), + tea.WithoutRenderer(), + ) + t.Cleanup(program.Kill) + go func() { _, _ = program.Run() }() + + paste := "\x1b[200~hello\x1b[201~" + if _, err := write.WriteString(paste + "\r"); err != nil { + t.Fatalf("write: %v", err) + } + deadline := time.After(2 * time.Second) + sawPaste, sawEnter := false, false + for !sawPaste || !sawEnter { + select { + case msg := <-recorder.msgs: + key, ok := msg.(tea.KeyMsg) + if !ok { + continue + } + if key.Paste { + sawPaste = true + } + if key.Type == tea.KeyEnter { + sawEnter = true + } + case <-deadline: + t.Fatalf("paste=%t enter=%t; want both", sawPaste, sawEnter) + } + } +} + +func TestBubbleTeaPasteThenSecondPaste(t *testing.T) { + read, write := pipeInput(t) + recorder := &msgRecorder{msgs: make(chan tea.Msg, 8)} + program := tea.NewProgram(recorder, + tea.WithInput(New(read)), + tea.WithoutRenderer(), + ) + t.Cleanup(program.Kill) + go func() { _, _ = program.Run() }() + + first, second := "one", "x\x1b[<35;中" + input := "\x1b[200~" + first + "\x1b[201~\x1b[200~" + second + "\x1b[201~" + if _, err := write.WriteString(input); err != nil { + t.Fatalf("write: %v", err) + } + deadline := time.After(2 * time.Second) + pastes := []string{} + for len(pastes) < 2 { + select { + case msg := <-recorder.msgs: + key, ok := msg.(tea.KeyMsg) + if ok && key.Paste { + pastes = append(pastes, string(key.Runes)) + } + case <-deadline: + t.Fatalf("pastes %q, want both", pastes) + } + } + if pastes[0] != first || pastes[1] != second { + t.Fatalf("pastes %q, want %q and %q", pastes, first, second) + } +} + +func TestBubbleTeaSecondPasteSplitAcrossReads(t *testing.T) { + read, write := pipeInput(t) + recorder := &msgRecorder{msgs: make(chan tea.Msg, 8)} + program := tea.NewProgram(recorder, + tea.WithInput(New(read)), + tea.WithoutRenderer(), + ) + t.Cleanup(program.Kill) + go func() { _, _ = program.Run() }() + + first, second := "one", "x\x1b[<35;中" + if _, err := write.WriteString("\x1b[200~" + first + "\x1b[201~\x1b[200~" + second[:4]); err != nil { + t.Fatalf("write: %v", err) + } + time.Sleep(20 * time.Millisecond) + if _, err := write.WriteString(second[4:] + "\x1b[201~"); err != nil { + t.Fatalf("write tail: %v", err) + } + deadline := time.After(2 * time.Second) + pastes := []string{} + for len(pastes) < 2 { + select { + case msg := <-recorder.msgs: + key, ok := msg.(tea.KeyMsg) + if ok && key.Paste { + pastes = append(pastes, string(key.Runes)) + } + case <-deadline: + t.Fatalf("pastes %q, want both", pastes) + } + } + if pastes[0] != first || pastes[1] != second { + t.Fatalf("pastes %q, want %q and %q", pastes, first, second) + } +} + +func TestBubbleTeaPasteAfterLoneESC(t *testing.T) { + read, write := pipeInput(t) + recorder := &msgRecorder{msgs: make(chan tea.Msg, 8)} + program := tea.NewProgram(recorder, + tea.WithInput(New(read)), + tea.WithoutRenderer(), + ) + t.Cleanup(program.Kill) + go func() { _, _ = program.Run() }() + + input := "\x1b[200~one\x1b[201~\x1b\x1b[200~two\x1b[201~" + if _, err := write.WriteString(input); err != nil { + t.Fatalf("write: %v", err) + } + deadline := time.After(2 * time.Second) + pastes := []string{} + for len(pastes) < 2 { + select { + case msg := <-recorder.msgs: + key, ok := msg.(tea.KeyMsg) + if !ok { + continue + } + if !key.Paste { + t.Fatalf("parsed %+v, want only pastes", msg) + } + pastes = append(pastes, string(key.Runes)) + case <-deadline: + t.Fatalf("pastes %q, want both", pastes) + } + } + if pastes[0] != "one" || pastes[1] != "two" { + t.Fatalf("pastes %q, want one and two", pastes) + } +} + +func TestBubbleTeaPasteEndWithAPartialReport(t *testing.T) { + read, write := pipeInput(t) + recorder := &msgRecorder{msgs: make(chan tea.Msg, 16)} + program := tea.NewProgram(recorder, + tea.WithInput(New(read)), + tea.WithoutRenderer(), + tea.WithMouseCellMotion(), + ) + t.Cleanup(program.Kill) + go func() { _, _ = program.Run() }() + + if _, err := write.WriteString("\x1b[200~hello"); err != nil { + t.Fatalf("write: %v", err) + } + time.Sleep(20 * time.Millisecond) + if _, err := write.WriteString("\x1b[201~\x1b[<35;4"); err != nil { + t.Fatalf("write tail: %v", err) + } + time.Sleep(20 * time.Millisecond) + if _, err := write.WriteString("0;12M"); err != nil { + t.Fatalf("write report tail: %v", err) + } + + deadline := time.After(2 * time.Second) + sawPaste, sawMouse := false, false + for !sawPaste || !sawMouse { + select { + case msg := <-recorder.msgs: + switch msg := msg.(type) { + case tea.KeyMsg: + if msg.Paste { + sawPaste = true + continue + } + t.Fatalf("parsed %+v, want no keys around the paste", msg) + case tea.MouseMsg: + sawMouse = true + } + case <-deadline: + t.Fatalf("paste=%t mouse=%t; want both", sawPaste, sawMouse) + } + } +} + +func TestBubbleTeaAltOAloneResolves(t *testing.T) { + read, write := pipeInput(t) + recorder := &msgRecorder{msgs: make(chan tea.Msg, 8)} + program := tea.NewProgram(recorder, + tea.WithInput(New(read)), + tea.WithoutRenderer(), + ) + t.Cleanup(program.Kill) + go func() { _, _ = program.Run() }() + + if _, err := write.WriteString("\x1bO"); err != nil { + t.Fatalf("write: %v", err) + } + deadline := time.After(2 * time.Second) + for { + select { + case msg := <-recorder.msgs: + key, ok := msg.(tea.KeyMsg) + if ok && key.Alt && string(key.Runes) == "O" { + return + } + case <-deadline: + t.Fatal("Alt+O did not resolve without another write") + } + } +} + +func TestBubbleTeaSS3TailAfterText(t *testing.T) { + read, write := pipeInput(t) + recorder := &msgRecorder{msgs: make(chan tea.Msg, 8)} + program := tea.NewProgram(recorder, + tea.WithInput(New(read)), + tea.WithoutRenderer(), + ) + t.Cleanup(program.Kill) + go func() { _, _ = program.Run() }() + + if _, err := write.WriteString("a\x1bO"); err != nil { + t.Fatalf("write: %v", err) + } + deadline := time.After(2 * time.Second) + sawA, sawAltO := false, false + for !sawA || !sawAltO { + select { + case msg := <-recorder.msgs: + key, ok := msg.(tea.KeyMsg) + if !ok { + continue + } + if key.Alt && string(key.Runes) == "O" { + sawAltO = true + continue + } + if !key.Alt && string(key.Runes) == "a" { + sawA = true + continue + } + t.Fatalf("parsed %+v, want a and Alt+O", key) + case <-deadline: + t.Fatalf("a=%t alt+O=%t; want both", sawA, sawAltO) + } + } +} + +func TestBubbleTeaSS3TailAfterTextKeepsNextKey(t *testing.T) { + read, write := pipeInput(t) + recorder := &msgRecorder{msgs: make(chan tea.Msg, 8)} + program := tea.NewProgram(recorder, + tea.WithInput(New(read)), + tea.WithoutRenderer(), + ) + t.Cleanup(program.Kill) + go func() { _, _ = program.Run() }() + + if _, err := write.WriteString("a\x1bO"); err != nil { + t.Fatalf("write: %v", err) + } + deadline := time.After(2 * time.Second) + sawAltO := false + for !sawAltO { + select { + case msg := <-recorder.msgs: + key, ok := msg.(tea.KeyMsg) + if ok && key.Alt && string(key.Runes) == "O" { + sawAltO = true + } + case <-deadline: + t.Fatal("Alt+O did not resolve before the next key") + } + } + if _, err := write.WriteString("P"); err != nil { + t.Fatalf("write next key: %v", err) + } + deadline = time.After(2 * time.Second) + for { + select { + case msg := <-recorder.msgs: + key, ok := msg.(tea.KeyMsg) + if !ok { + continue + } + if !key.Alt && string(key.Runes) == "P" { + return + } + t.Fatalf("parsed %+v, want the next key as P", key) + case <-deadline: + t.Fatal("P did not arrive") + } + } +} + +type chunkReader struct { + chunks [][]byte +} + +func (r *chunkReader) Read(p []byte) (int, error) { + if len(r.chunks) == 0 { + return 0, io.EOF + } + chunk := r.chunks[0] + r.chunks = r.chunks[1:] + return copy(p, chunk), nil +} + +// TestBubbleTeaPlainReaderPasteThenEscapeBaseline is a control: it bypasses +// Guard and only proves Bubble Tea's own reader handles this sequence. It is +// not a regression test for the manager's input path. +func TestBubbleTeaPlainReaderPasteThenEscapeBaseline(t *testing.T) { + recorder := &msgRecorder{msgs: make(chan tea.Msg, 8)} + program := tea.NewProgram(recorder, + tea.WithInput(&chunkReader{chunks: [][]byte{ + []byte("\x1b[200~hi\x1b[201~"), + []byte("\x1b"), + }}), + tea.WithoutRenderer(), + ) + t.Cleanup(program.Kill) + go func() { _, _ = program.Run() }() + + deadline := time.After(2 * time.Second) + sawPaste, sawEsc := false, false + for !sawPaste || !sawEsc { + select { + case msg := <-recorder.msgs: + key, ok := msg.(tea.KeyMsg) + if !ok { + continue + } + if key.Paste { + sawPaste = true + continue + } + if key.Type == tea.KeyEsc { + sawEsc = true + continue + } + t.Fatalf("parsed %+v, want the paste and Escape", key) + case <-deadline: + t.Fatalf("paste=%t escape=%t; want both", sawPaste, sawEsc) + } + } +} + +func TestBubbleTeaPasteThenEscape(t *testing.T) { + read, write := pipeInput(t) + recorder := &msgRecorder{msgs: make(chan tea.Msg, 8)} + program := tea.NewProgram(recorder, + tea.WithInput(New(read)), + tea.WithoutRenderer(), + ) + t.Cleanup(program.Kill) + go func() { _, _ = program.Run() }() + + if _, err := write.WriteString("\x1b[200~hi\x1b[201~\x1b"); err != nil { + t.Fatalf("write: %v", err) + } + deadline := time.After(2 * time.Second) + sawPaste, sawEsc := false, false + for !sawPaste || !sawEsc { + select { + case msg := <-recorder.msgs: + key, ok := msg.(tea.KeyMsg) + if !ok { + continue + } + if key.Paste { + sawPaste = true + continue + } + if key.Type == tea.KeyEsc { + sawEsc = true + continue + } + t.Fatalf("parsed %+v, want the paste and Escape", key) + case <-deadline: + t.Fatalf("paste=%t escape=%t; want both", sawPaste, sawEsc) + } + } +} + +func TestBubbleTeaPasteThenSS3(t *testing.T) { + read, write := pipeInput(t) + recorder := &msgRecorder{msgs: make(chan tea.Msg, 8)} + program := tea.NewProgram(recorder, + tea.WithInput(New(read)), + tea.WithoutRenderer(), + ) + t.Cleanup(program.Kill) + go func() { _, _ = program.Run() }() + + if _, err := write.WriteString("\x1b[200~hi\x1b[201~\x1bO"); err != nil { + t.Fatalf("write: %v", err) + } + deadline := time.After(2 * time.Second) + sawPaste, sawAltO := false, false + for !sawPaste || !sawAltO { + select { + case msg := <-recorder.msgs: + key, ok := msg.(tea.KeyMsg) + if !ok { + continue + } + if key.Paste { + sawPaste = true + continue + } + if key.Alt && string(key.Runes) == "O" { + sawAltO = true + continue + } + t.Fatalf("parsed %+v, want the paste and Alt+O", key) + case <-deadline: + t.Fatalf("paste=%t alt+O=%t; want both", sawPaste, sawAltO) + } + } +} + +func TestBubbleTeaModeReportIsNotTyped(t *testing.T) { + for _, input := range []string{"\x1b[?2026;1$y", "\x1b[1 q"} { + t.Run(input, func(t *testing.T) { + read, write := pipeInput(t) + recorder := &msgRecorder{msgs: make(chan tea.Msg, 8)} + program := tea.NewProgram(recorder, + tea.WithInput(New(read)), + tea.WithoutRenderer(), + ) + t.Cleanup(program.Kill) + go func() { _, _ = program.Run() }() + + if _, err := write.WriteString(input); err != nil { + t.Fatalf("write report: %v", err) + } + time.Sleep(20 * time.Millisecond) + if _, err := write.WriteString("z"); err != nil { + t.Fatalf("write key: %v", err) + } + deadline := time.After(2 * time.Second) + for { + select { + case msg := <-recorder.msgs: + key, ok := msg.(tea.KeyMsg) + if !ok { + continue + } + if !key.Alt && string(key.Runes) == "z" { + return + } + t.Fatalf("parsed %+v, want the report to stay out of the keys", key) + case <-deadline: + t.Fatal("the key after the report did not arrive") + } + } + }) + } +} + +// TestBubbleTeaKeepsTypedTextAfterAHalfReport pins that a broken report head +// does not turn the following character into text behind alt+'['. +func TestBubbleTeaKeepsTypedTextAfterAHalfReport(t *testing.T) { + read, write := pipeInput(t) + recorder := &msgRecorder{msgs: make(chan tea.Msg, 8)} + program := tea.NewProgram(recorder, + tea.WithInput(New(read)), + tea.WithoutRenderer(), + ) + t.Cleanup(program.Kill) + go func() { _, _ = program.Run() }() + + if _, err := write.WriteString("a\x1b[<35;中"); err != nil { + t.Fatalf("write: %v", err) + } + deadline := time.After(2 * time.Second) + text := "" + for text != "a中" { + select { + case msg := <-recorder.msgs: + key, ok := msg.(tea.KeyMsg) + if !ok { + continue + } + if key.Alt || strings.ContainsRune(string(key.Runes), '[') { + t.Fatalf("parsed %+v, want only the typed text", msg) + } + text += string(key.Runes) + case <-deadline: + t.Fatalf("typed %q so far, want a and the character", text) + } + } +} + +// TestReleaseTerminalKeepsTheTerminalFree pins the release contract: a +// partial CSI must not block ReleaseTerminal, and keys typed while a child +// owns the terminal must not be read by the manager. +func TestReleaseTerminalKeepsTheTerminalFree(t *testing.T) { + read, write := pipeInput(t) + started := make(chan struct{}) + recorder := &msgRecorder{msgs: make(chan tea.Msg, 8), started: started} + program := tea.NewProgram(recorder, + tea.WithInput(New(read)), + tea.WithoutRenderer(), + ) + go func() { _, _ = program.Run() }() + t.Cleanup(program.Kill) + select { + case <-started: + case <-time.After(2 * time.Second): + t.Fatal("program did not start") + } + + if _, err := write.WriteString("\x1b[<35;"); err != nil { + t.Fatalf("write partial CSI: %v", err) + } + time.Sleep(30 * time.Millisecond) + + ResetActive() + released := time.Now() + if err := program.ReleaseTerminal(); err != nil { + t.Fatalf("release terminal: %v", err) + } + if waited := time.Since(released); waited > 200*time.Millisecond { + t.Fatalf("ReleaseTerminal waited %v for a partial CSI", waited) + } + + if _, err := write.WriteString("q"); err != nil { + t.Fatalf("write during release: %v", err) + } + select { + case msg := <-recorder.msgs: + if key, ok := msg.(tea.KeyMsg); ok && string(key.Runes) == "q" { + t.Fatal("a key typed during the release reached the program") + } + case <-time.After(150 * time.Millisecond): + } + + if err := program.RestoreTerminal(); err != nil { + t.Fatalf("restore terminal: %v", err) + } +} + +func TestBubbleTeaPasteKeepsItsLinefeeds(t *testing.T) { + read, write := pipeInput(t) + recorder := &msgRecorder{msgs: make(chan tea.Msg, 8)} + program := tea.NewProgram(recorder, + tea.WithInput(New(read)), + tea.WithoutRenderer(), + ) + t.Cleanup(program.Kill) + go func() { _, _ = program.Run() }() + + const text = "paste-one\npaste-two\npaste-three\n" + paste := "\x1b[200~" + text + "\x1b[201~" + if _, err := write.WriteString(paste); err != nil { + t.Fatalf("write: %v", err) + } + deadline := time.After(2 * time.Second) + for { + select { + case msg := <-recorder.msgs: + key, ok := msg.(tea.KeyMsg) + if ok && key.Paste { + if string(key.Runes) != text { + t.Fatalf("paste %q, want %q", string(key.Runes), text) + } + return + } + case <-deadline: + t.Fatal("Bubble Tea did not deliver the paste") + } + } +} diff --git a/internal/inputguard/guard_frame_test.go b/internal/inputguard/guard_frame_test.go new file mode 100644 index 00000000..bc572fc7 --- /dev/null +++ b/internal/inputguard/guard_frame_test.go @@ -0,0 +1,37 @@ +package inputguard + +import ( + "testing" +) + +func TestCompleteLen(t *testing.T) { + cases := []struct { + input string + want int + }{ + {"", 0}, + {"a", 1}, + {"\x1b", 0}, + {"\x1b[", 0}, + {"\x1b[<35;1;2", 0}, + {"\x1b[<35;\xe4\xb8\xad", 0}, + {"\x1b[<35;\x7f", 0}, + {"\x1b[7$", 4}, + {"\x1b[8$", 4}, + {"\x1b[1 q", 5}, + {"\x1b[?2026;1$y", 11}, + {"\x1b[?2004;1$y", 11}, + {"\x1b[<35;1;2M", 10}, + {"\x1b[A", 3}, + {"\x1b[200~", 6}, + {"\x1b[Mabc", 6}, + {"\x1b]x", 3}, + {"\xe4\xb8", 0}, + {"中", 3}, + } + for _, test := range cases { + if got := completeLen([]byte(test.input)); got != test.want { + t.Errorf("completeLen(%q) = %d, want %d", test.input, got, test.want) + } + } +} diff --git a/internal/inputguard/guard_test.go b/internal/inputguard/guard_test.go new file mode 100644 index 00000000..cdaf57ac --- /dev/null +++ b/internal/inputguard/guard_test.go @@ -0,0 +1,806 @@ +//go:build unix + +package inputguard + +import ( + "io" + "os" + "strings" + "testing" + "time" +) + +func guardFor(t *testing.T) (*Guard, *os.File) { + t.Helper() + read, write, err := os.Pipe() + if err != nil { + t.Fatalf("pipe: %v", err) + } + t.Cleanup(func() { _ = read.Close(); _ = write.Close() }) + return New(read), write +} + +func writeAfter(t *testing.T, w *os.File, first, second string, delay time.Duration) { + t.Helper() + if _, err := w.WriteString(first); err != nil { + t.Fatalf("write first chunk: %v", err) + } + go func() { + time.Sleep(delay) + _, _ = w.WriteString(second) + }() +} + +// readEvent reads until at least one byte arrives, failing on a deadline so a +// reader that blocks cannot hang the package. A zero-length read means the +// guard is holding a partial sequence, which is expected. +func readEvent(t *testing.T, g *Guard) string { + t.Helper() + deadline := time.Now().Add(2 * time.Second) + buf := make([]byte, 256) + for time.Now().Before(deadline) { + type result struct { + text string + err error + } + done := make(chan result, 1) + go func() { + n, err := g.Read(buf) + done <- result{string(buf[:n]), err} + }() + select { + case got := <-done: + if got.err != nil { + t.Fatalf("read: %v", got.err) + } + if got.text != "" { + if !g.paste { + if left := completeLen(g.pending); left > 0 { + t.Fatalf("read left %d bytes of a complete message behind", left) + } + } + return got.text + } + case <-time.After(time.Second): + t.Fatal("read did not return") + } + } + t.Fatal("read did not produce a whole message") + return "" +} + +// A split after the first byte is not covered: a short read holding only +// ESC is the Escape key, as Bubble Tea reads it. +func TestSplitMouseReportAtEveryByte(t *testing.T) { + const report = "\x1b[<35;163;38M" + for split := 2; split < len(report); split++ { + t.Run(strings.ReplaceAll(report[:split], "\x1b", "ESC"), func(t *testing.T) { + g, w := guardFor(t) + writeAfter(t, w, report[:split], report[split:], 2*time.Millisecond) + if got := readEvent(t, g); got != report { + t.Fatalf("read %q, want %q", got, report) + } + }) + } +} + +type resetOnRead struct { + file *os.File + firstBytes int + resetAt int + reads int + reset bool +} + +func (r *resetOnRead) Read(p []byte) (int, error) { + r.reads++ + if r.reads == 1 && len(p) > r.firstBytes { + p = p[:r.firstBytes] + } + if r.reads == r.resetAt { + var one [1]byte + _, _ = r.file.Read(one[:]) + if !r.reset { + r.reset = true + ResetActive() + } + return 0, nil + } + return r.file.Read(p) +} + +func TestPasteThenEscapeKeepsBoth(t *testing.T) { + g, w := guardFor(t) + if _, err := w.WriteString("\x1b[200~hi\x1b[201~\x1b"); err != nil { + t.Fatalf("write: %v", err) + } + if got := readEvent(t, g); got != "\x1b[200~hi\x1b[201~\x1b" { + t.Fatalf("read %q, want the paste and the Escape", got) + } +} + +func TestModeReportKeepsItsBytes(t *testing.T) { + for _, input := range []string{"\x1b[?2026;1$y", "\x1b[?2004;1$y", "\x1b[1 q", "a\x1b[?2026;1$y", "a\x1b[1 q"} { + g, w := guardFor(t) + if _, err := w.WriteString(input); err != nil { + t.Fatalf("write: %v", err) + } + if got := readEvent(t, g); got != input { + t.Fatalf("read %q, want %q", got, input) + } + } +} + +func TestSS3TailAfterTextResolves(t *testing.T) { + g, w := guardFor(t) + if _, err := w.WriteString("a\x1bO"); err != nil { + t.Fatalf("write: %v", err) + } + if got := readEvent(t, g); got != "a\x1bO" { + t.Fatalf("read %q, want the text and the SS3 head", got) + } +} + +func TestResetDuringPeekDoesNotPanic(t *testing.T) { + cases := []struct { + name string + input string + first int + }{ + {"text then escape", "a\x1b[", 2}, + {"escape only", "\x1b[", 1}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + g, w := guardFor(t) + if _, err := w.WriteString(tc.input); err != nil { + t.Fatalf("write: %v", err) + } + rr := &resetOnRead{file: g.file, firstBytes: tc.first, resetAt: 2} + g.reader = rr + done := make(chan struct{}) + var n int + var err error + go func() { + n, err = g.Read(make([]byte, 256)) + close(done) + }() + select { + case <-done: + case <-time.After(time.Second): + t.Fatal("Read blocked") + } + if err != nil { + t.Fatalf("Read: %v", err) + } + if n != 0 { + t.Fatalf("Read = %d, want no output", n) + } + if !rr.reset { + t.Fatal("reset hook did not run") + } + if len(g.pending) != 0 { + t.Fatalf("pending = %q, want empty after reset", g.pending) + } + if g.paste { + t.Fatal("paste still true after reset") + } + if _, err := w.WriteString("y"); err != nil { + t.Fatalf("write after reset: %v", err) + } + if got := readEvent(t, g); got != "y" { + t.Fatalf("read after reset = %q, want y", got) + } + }) + } +} + +func TestBrokenSGRKeepsALaterKey(t *testing.T) { + g, w := guardFor(t) + if _, err := w.WriteString("\x1b[<35;"); err != nil { + t.Fatalf("write head: %v", err) + } + buf := make([]byte, 256) + if n, err := g.Read(buf); err != nil || n != 0 { + t.Fatalf("first read = %d, %v; want no output", n, err) + } + time.Sleep(50 * time.Millisecond) + if _, err := w.WriteString("a"); err != nil { + t.Fatalf("write key: %v", err) + } + if got := readEvent(t, g); got != "a" { + t.Fatalf("read %q, want the typed key", got) + } +} +func TestChunksNeverEndInsideAMessage(t *testing.T) { + const report = "\x1b[<35;40;12M" + want := strings.Repeat(report, 40) + g, w := guardFor(t) + if _, err := w.WriteString(want + "\x1b[<35;4"); err != nil { + t.Fatalf("write burst: %v", err) + } + var got strings.Builder + for got.Len() < len(want) { + buf := make([]byte, 256) + n, err := g.Read(buf) + if err != nil { + t.Fatalf("read: %v", err) + } + if n > 0 && completeLen(buf[:n]) != n { + t.Fatalf("chunk %q ends inside a message", buf[:n]) + } + got.Write(buf[:n]) + } + if got.String() != want { + t.Fatalf("read %d bytes, want the 40 whole reports", got.Len()) + } +} + +func TestIncompleteMouseReportDoesNotConsumeCtrlC(t *testing.T) { + g, w := guardFor(t) + if _, err := w.WriteString("\x1b[<35;"); err != nil { + t.Fatalf("write mouse prefix: %v", err) + } + if _, err := w.Write([]byte{0x03}); err != nil { + t.Fatalf("write Ctrl+C: %v", err) + } + if got := readEvent(t, g); got != string([]byte{0x03}) { + t.Fatalf("read %q, want Ctrl+C", got) + } +} + +func TestStandaloneEscapeIsDeliveredAtOnce(t *testing.T) { + g, w := guardFor(t) + if _, err := w.Write([]byte{esc}); err != nil { + t.Fatalf("write Escape: %v", err) + } + start := time.Now() + if got := readEvent(t, g); got != string([]byte{esc}) { + t.Fatalf("read %q, want Escape", got) + } + if waited := time.Since(start); waited > 80*time.Millisecond { + t.Fatalf("Escape waited %v", waited) + } +} + +func TestOrdinaryInputDoesNotWait(t *testing.T) { + g, w := guardFor(t) + if _, err := w.WriteString("hello\r"); err != nil { + t.Fatalf("write: %v", err) + } + start := time.Now() + if got := readEvent(t, g); got != "hello\r" { + t.Fatalf("read %q", got) + } + if waited := time.Since(start); waited > 80*time.Millisecond { + t.Fatalf("ordinary input waited %v", waited) + } +} + +func TestLoneEscapeAfterAWholeMessageIsNotStranded(t *testing.T) { + g, w := guardFor(t) + if _, err := w.WriteString("a\x1b"); err != nil { + t.Fatalf("write: %v", err) + } + start := time.Now() + if got := readEvent(t, g); got != "a\x1b" { + t.Fatalf("read %q, want the key and the Escape", got) + } + if waited := time.Since(start); waited > 80*time.Millisecond { + t.Fatalf("Escape waited %v", waited) + } +} + +func TestRetainedCSIDoesNotEatThePrefix(t *testing.T) { + g, w := guardFor(t) + if _, err := w.WriteString("hello\x1b[<35;"); err != nil { + t.Fatalf("write: %v", err) + } + if got := readEvent(t, g); got != "hello" { + t.Fatalf("read %q, want the text before the broken report", got) + } + if _, err := w.Write([]byte{0x03}); err != nil { + t.Fatalf("write Ctrl+C: %v", err) + } + if got := readEvent(t, g); got != "\x03" { + t.Fatalf("read %q, want Ctrl+C after the skipped report", got) + } +} + +func TestSkipKeepsEnter(t *testing.T) { + g, w := guardFor(t) + if _, err := w.WriteString("x\x1b[<35;"); err != nil { + t.Fatalf("write: %v", err) + } + if got := readEvent(t, g); got != "x" { + t.Fatalf("read %q, want the text before the broken report", got) + } + if _, err := w.Write([]byte{'\r'}); err != nil { + t.Fatalf("write Enter: %v", err) + } + if got := readEvent(t, g); got != "\r" { + t.Fatalf("read %q, want Enter", got) + } +} + +func TestIncompleteArrowCSIKeepsCtrlC(t *testing.T) { + g, w := guardFor(t) + if _, err := w.WriteString("\x1b[1;2\x03"); err != nil { + t.Fatalf("write: %v", err) + } + if got := readEvent(t, g); got != "\x03" { + t.Fatalf("read %q, want Ctrl+C", got) + } +} + +func TestEndOfInputWithAHalfReportDoesNotSpin(t *testing.T) { + g, w := guardFor(t) + if _, err := w.WriteString("a\x1b[<35;"); err != nil { + t.Fatalf("write: %v", err) + } + if err := w.Close(); err != nil { + t.Fatalf("close: %v", err) + } + start := time.Now() + if got := readEvent(t, g); got != "a" { + t.Fatalf("read %q, want the whole byte before the broken report", got) + } + buf := make([]byte, 256) + if _, err := g.Read(buf); err == nil { + t.Fatal("read after end of input returned no error") + } + if waited := time.Since(start); waited > 2*time.Second { + t.Fatalf("end of input took %v", waited) + } +} + +func TestHalfCSIFollowedByTypedTextKeepsTheText(t *testing.T) { + for _, typed := range []string{"中", "\x7f"} { + g, w := guardFor(t) + if _, err := w.WriteString("a\x1b[<35;" + typed); err != nil { + t.Fatalf("write: %v", err) + } + if got := readEvent(t, g); got != "a"+typed { + t.Fatalf("read %q, want the text around the broken report", got) + } + } +} + +func TestSkipKeepsANonASCIICharacter(t *testing.T) { + g, w := guardFor(t) + if _, err := w.WriteString("x\x1b[<35;"); err != nil { + t.Fatalf("write: %v", err) + } + if got := readEvent(t, g); got != "x" { + t.Fatalf("read %q, want the text before the broken report", got) + } + if _, err := w.WriteString("中\x03"); err != nil { + t.Fatalf("write: %v", err) + } + if got := readEvent(t, g); got != "中\x03" { + t.Fatalf("read %q, want the character and Ctrl+C", got) + } +} + +func TestSplitRuneWaitsForItsRemainingBytes(t *testing.T) { + g, w := guardFor(t) + writeAfter(t, w, "中"[:1], "中"[1:], 2*time.Millisecond) + if got := readEvent(t, g); got != "中" { + t.Fatalf("read %q, want the whole character", got) + } +} + +func TestSplitEscRuneWaitsForItsRemainingBytes(t *testing.T) { + g, w := guardFor(t) + writeAfter(t, w, "\x1b"+"中"[:1], "中"[1:], 2*time.Millisecond) + if got := readEvent(t, g); got != "\x1b中" { + t.Fatalf("read %q, want ESC and the whole character", got) + } +} + +func TestSplitEscRuneAfterCompleteMessage(t *testing.T) { + g, w := guardFor(t) + writeAfter(t, w, "a\x1b"+"中"[:1], "中"[1:], 2*time.Millisecond) + var got strings.Builder + for got.String() != "a\x1b中" { + got.WriteString(readEvent(t, g)) + } +} + +func TestFullBufferKeepsTheCSITail(t *testing.T) { + g, w := guardFor(t) + prefix := strings.Repeat("a", 254) + "\x1b[" + if _, err := w.WriteString(prefix); err != nil { + t.Fatalf("write: %v", err) + } + if got := readEvent(t, g); len(got) != 254 { + t.Fatalf("read %d bytes, want the text before the tail", len(got)) + } + if _, err := w.WriteString("201~"); err != nil { + t.Fatalf("write tail: %v", err) + } + if got := readEvent(t, g); got != "\x1b[201~" { + t.Fatalf("read %q, want the whole sequence", got) + } +} + +func TestSplitSS3WaitsForItsFinalByte(t *testing.T) { + g, w := guardFor(t) + writeAfter(t, w, "\x1bO", "P", 2*time.Millisecond) + if got := readEvent(t, g); got != "\x1bOP" { + t.Fatalf("read %q, want the whole SS3 key", got) + } +} + +func TestFullBufferKeepsTheSS3Tail(t *testing.T) { + g, w := guardFor(t) + if _, err := w.WriteString(strings.Repeat("a", 254) + "\x1bO"); err != nil { + t.Fatalf("write: %v", err) + } + if got := readEvent(t, g); len(got) != 254 { + t.Fatalf("read %d bytes, want the text before the tail", len(got)) + } + if _, err := w.WriteString("P"); err != nil { + t.Fatalf("write tail: %v", err) + } + if got := readEvent(t, g); got != "\x1bOP" { + t.Fatalf("read %q, want the whole SS3 key", got) + } +} + +func TestFullBufferESCWaitsForItsReport(t *testing.T) { + g, w := guardFor(t) + const report = "\x1b[<35;40;12M" + if _, err := w.WriteString(strings.Repeat("a", 255) + report); err != nil { + t.Fatalf("write: %v", err) + } + if got := readEvent(t, g); len(got) != 255 { + t.Fatalf("read %d bytes, want the text before the report", len(got)) + } + if got := readEvent(t, g); got != report { + t.Fatalf("read %q, want the whole report", got) + } +} + +func TestBrokenSGRKeepsTheTypedKey(t *testing.T) { + g, w := guardFor(t) + if _, err := w.WriteString("\x1b[<35;a"); err != nil { + t.Fatalf("write: %v", err) + } + if got := readEvent(t, g); got != "a" { + t.Fatalf("read %q, want the typed key", got) + } +} + +func TestPasteKeepsLiteralSequences(t *testing.T) { + const paste = "\x1b[200~a\x1b[\nb\x1b[201~" + g, w := guardFor(t) + if _, err := w.WriteString(paste); err != nil { + t.Fatalf("write: %v", err) + } + var got strings.Builder + for !strings.HasSuffix(got.String(), "\x1b[201~") { + got.WriteString(readEvent(t, g)) + } + if got.String() != paste { + t.Fatalf("read %q, want the literal paste", got.String()) + } +} + +func TestPasteStraddlesTheCallerBuffer(t *testing.T) { + content := strings.Repeat("x", 251) + paste := "\x1b[200~" + content + "\x1b[201~" + g, w := guardFor(t) + if _, err := w.WriteString(paste); err != nil { + t.Fatalf("write: %v", err) + } + var got strings.Builder + for !strings.HasSuffix(got.String(), "\x1b[201~") { + got.WriteString(readEvent(t, g)) + } + if got.String() != paste { + t.Fatalf("read %d bytes, want the whole paste", got.Len()) + } + if g.paste { + t.Fatal("guard still in paste mode after the end marker") + } +} + +func TestResetDropsAPartialSequence(t *testing.T) { + g, w := guardFor(t) + if _, err := w.WriteString("\x1b[<35;"); err != nil { + t.Fatalf("write: %v", err) + } + buf := make([]byte, 256) + if n, err := g.Read(buf); err != nil || n != 0 { + t.Fatalf("first read = %d, %v; want no output", n, err) + } + ResetActive() + if _, err := w.WriteString("a"); err != nil { + t.Fatalf("write: %v", err) + } + if got := readEvent(t, g); got != "a" { + t.Fatalf("read %q, want the typed key", got) + } +} + +func TestPartialCSIDoesNotBlockTheReader(t *testing.T) { + g, w := guardFor(t) + if _, err := w.WriteString("\x1b[<35;"); err != nil { + t.Fatalf("write: %v", err) + } + done := make(chan struct{}) + go func() { + buf := make([]byte, 256) + if n, err := g.Read(buf); err != nil || n != 0 { + t.Errorf("read = %d, %v; want no output", n, err) + } + close(done) + }() + select { + case <-done: + case <-time.After(200 * time.Millisecond): + t.Fatal("a partial CSI blocked the reader") + } +} + +func TestPasteStartMarkerArrivesWhole(t *testing.T) { + for _, extra := range []string{"", "x", "\x1b["} { + g, w := guardFor(t) + if _, err := w.WriteString("\x1b[200~" + extra); err != nil { + t.Fatalf("write: %v", err) + } + var got strings.Builder + got.WriteString(readEvent(t, g)) + if !strings.HasPrefix(got.String(), "\x1b[200~") { + t.Fatalf("first chunk %q, want the start marker unsplit", got.String()) + } + if _, err := w.WriteString("hello\x1b[201~"); err != nil { + t.Fatalf("write rest: %v", err) + } + for !strings.HasSuffix(got.String(), "\x1b[201~") { + got.WriteString(readEvent(t, g)) + } + if want := "\x1b[200~" + extra + "hello\x1b[201~"; got.String() != want { + t.Fatalf("read %q, want %q", got.String(), want) + } + } +} +func TestPasteStartAtTheBufferLimit(t *testing.T) { + g, w := guardFor(t) + paste := strings.Repeat("a", 250) + "\x1b[200~hello\x1b[201~" + if _, err := w.WriteString(paste); err != nil { + t.Fatalf("write: %v", err) + } + var got strings.Builder + for !strings.HasSuffix(got.String(), "\x1b[201~") { + got.WriteString(readEvent(t, g)) + } + if got.String() != paste { + t.Fatalf("read %d bytes, want the whole paste", got.Len()) + } + if g.paste { + t.Fatal("guard still in paste mode after the end marker") + } +} + +func TestURXVTShiftHomeAndEndPassThrough(t *testing.T) { + g, w := guardFor(t) + if _, err := w.WriteString("\x1b[7$\x1b[8$"); err != nil { + t.Fatalf("write: %v", err) + } + if got := readEvent(t, g); got != "\x1b[7$\x1b[8$" { + t.Fatalf("read %q, want both urxvt sequences", got) + } +} + +func TestResetClearsAStoredEOF(t *testing.T) { + g, w := guardFor(t) + g.err = io.EOF + ResetActive() + if _, err := w.WriteString("a"); err != nil { + t.Fatalf("write: %v", err) + } + if got := readEvent(t, g); got != "a" { + t.Fatalf("read %q, want the key typed after the reset", got) + } +} + +func TestCompletePasteWithLeadingTextArrivesTogether(t *testing.T) { + const paste = "\x1b[200~hello\x1b[201~" + g, w := guardFor(t) + if _, err := w.WriteString("a" + paste); err != nil { + t.Fatalf("write: %v", err) + } + got := readEvent(t, g) + if got != "a"+paste { + t.Fatalf("read %q, want the text and the whole paste", got) + } +} + +func TestTextAndEnterAfterAPasteArriveTogether(t *testing.T) { + for _, tail := range []string{"a", "\r"} { + g, w := guardFor(t) + paste := "\x1b[200~hello\x1b[201~" + if _, err := w.WriteString(paste + tail); err != nil { + t.Fatalf("write: %v", err) + } + if got := readEvent(t, g); got != paste+tail { + t.Fatalf("read %q, want the paste and %q", got, tail) + } + } +} + +func TestTwoPastesInOneRead(t *testing.T) { + g, w := guardFor(t) + both := "\x1b[200~one\x1b[201~\x1b[200~two\x1b[201~" + if _, err := w.WriteString(both); err != nil { + t.Fatalf("write: %v", err) + } + if got := readEvent(t, g); got != both { + t.Fatalf("read %q, want both pastes", got) + } +} + +func TestSecondPasteKeepsItsBytes(t *testing.T) { + const both = "\x1b[200~one\x1b[201~\x1b[200~x\x1b[<35;中\x1b[201~" + g, w := guardFor(t) + if _, err := w.WriteString(both); err != nil { + t.Fatalf("write: %v", err) + } + got := readEvent(t, g) + if got != both { + t.Fatalf("read %q, want both pastes verbatim", got) + } +} + +func TestPasteAfterABrokenCSIPrefixKeepsItsBytes(t *testing.T) { + both := "\x1b[200~one\x1b[201~\x1b[<35;\x1b[200~two\x1b[201~" + g, w := guardFor(t) + if _, err := w.WriteString(both); err != nil { + t.Fatalf("write: %v", err) + } + got := readEvent(t, g) + if !strings.Contains(got, "two") || strings.Contains(got, "<35;") { + t.Fatalf("read %q, want the second paste without the broken head", got) + } +} + +func TestPasteAfterALoneESCDoesNotWaitForAKey(t *testing.T) { + input := "\x1b[200~one\x1b[201~\x1b\x1b[200~two\x1b[201~" + g, w := guardFor(t) + if _, err := w.WriteString(input); err != nil { + t.Fatalf("write: %v", err) + } + want := "\x1b[200~one\x1b[201~\x1b[200~two\x1b[201~" + if got := readEvent(t, g); got != want { + t.Fatalf("read %q, want both pastes", got) + } +} + +func TestPasteEndWithAPartialReportKeepsItWhole(t *testing.T) { + g, w := guardFor(t) + if _, err := w.WriteString("\x1b[200~hello"); err != nil { + t.Fatalf("write: %v", err) + } + if got := readEvent(t, g); got != "\x1b[200~hello" { + t.Fatalf("read %q, want the open paste", got) + } + if _, err := w.WriteString("\x1b[201~\x1b[<35;4"); err != nil { + t.Fatalf("write tail: %v", err) + } + if got := readEvent(t, g); got != "\x1b[201~" { + t.Fatalf("read %q, want the paste end only", got) + } + if _, err := w.WriteString("0;12M"); err != nil { + t.Fatalf("write report tail: %v", err) + } + if got := readEvent(t, g); got != "\x1b[<35;40;12M" { + t.Fatalf("read %q, want the whole report", got) + } +} + +func TestPasteWithTextBeforeItKeepsItsBytes(t *testing.T) { + paste := "x\x1b[200~a\x1b[\nb\x1b[201~" + g, w := guardFor(t) + if _, err := w.WriteString(paste); err != nil { + t.Fatalf("write: %v", err) + } + if got := readEvent(t, g); got != paste { + t.Fatalf("read %q, want the text and the literal paste", got) + } +} + +func TestLongPasteWithTheEndOnTheBufferBoundary(t *testing.T) { + g, w := guardFor(t) + content := strings.Repeat("a", 245) + paste := "\x1b[200~" + content + "\x1b[201~" + if _, err := w.WriteString(paste); err != nil { + t.Fatalf("write: %v", err) + } + var got strings.Builder + for !strings.HasSuffix(got.String(), "\x1b[201~") { + got.WriteString(readEvent(t, g)) + } + if got.String() != paste { + t.Fatalf("read %d bytes, want the whole paste", got.Len()) + } + if g.paste { + t.Fatal("guard still in paste mode after the end marker") + } +} + +func TestPasteEndSplitAtEveryByte(t *testing.T) { + end := "\x1b[201~" + for split := 1; split < len(end); split++ { + g, w := guardFor(t) + paste := "\x1b[200~hello" + end + if _, err := w.WriteString(paste[:6+5+split]); err != nil { + t.Fatalf("write: %v", err) + } + var got strings.Builder + got.WriteString(readEvent(t, g)) + if _, err := w.WriteString(paste[6+5+split:]); err != nil { + t.Fatalf("write rest: %v", err) + } + for !strings.HasSuffix(got.String(), end) { + got.WriteString(readEvent(t, g)) + } + if got.String() != paste { + t.Fatalf("split %d: read %q, want %q", split, got.String(), paste) + } + if g.paste { + t.Fatalf("split %d: guard still in paste mode", split) + } + } +} + +// firstReadLimit models the real 256-byte reader receiving a short first read +// followed by already-queued bytes. It makes the OS read boundary deterministic. +type firstReadLimit struct { + file *os.File + limit int + first bool +} + +func (r *firstReadLimit) Read(p []byte) (int, error) { + if !r.first { + r.first = true + if len(p) > r.limit { + p = p[:r.limit] + } + } + return r.file.Read(p) +} + +func TestPasteTailReadRespectsRemainingOutputRoom(t *testing.T) { + paste := "\x1b[200~" + strings.Repeat("a", 241) + "\x1b[201~" + for _, tc := range []struct { + name string + first string + after string + want string + }{ + {name: "SS3 tail", first: paste + "\x1bO", after: "PQ", want: paste + "\x1bOP"}, + {name: "CSI tail", first: paste + "\x1b", after: "[AP", want: paste + "\x1b[A"}, + } { + t.Run(tc.name, func(t *testing.T) { + g, w := guardFor(t) + g.reader = &firstReadLimit{file: g.file, limit: len(tc.first)} + if _, err := w.WriteString(tc.first + tc.after); err != nil { + t.Fatal(err) + } + buf := make([]byte, 256) + n, err := g.Read(buf) + if err != nil { + t.Fatal(err) + } + if got := string(buf[:n]); got != tc.want { + t.Fatalf("Read returned %q, want %q", got, tc.want) + } + if complete := completeLen(g.pending); complete > 0 { + t.Fatalf("%d complete bytes stranded in guard pending: %q", complete, g.pending) + } + }) + } +} diff --git a/internal/inputguard/guard_unix.go b/internal/inputguard/guard_unix.go new file mode 100644 index 00000000..0e0cceb2 --- /dev/null +++ b/internal/inputguard/guard_unix.go @@ -0,0 +1,539 @@ +//go:build unix + +package inputguard + +import ( + "bytes" + "io" + "os" + "sync/atomic" + "time" + "unicode/utf8" +) + +const ( + // briefTimeout is how long a short read waits for the rest of an SS3 key + // or half a UTF-8 character. It stays well under Bubble Tea's 500ms + // ReleaseTerminal budget, so the read loop cannot outlive a release. + briefTimeout = 50 * time.Millisecond + readSize = 1024 +) + +var ( + pasteStart = []byte("\x1b[200~") + pasteEnd = []byte("\x1b[201~") +) + +// Guard wraps terminal input for Bubble Tea. It hands over whole messages and +// never blocks on a sequence that may not arrive: only an SS3 head or half a +// UTF-8 character waits, briefly, because a terminal writes those together. +type Guard struct { + file *os.File + // reader is the file in production. Tests replace it to land a reset + // inside a read and pin the stale-length path. + reader io.Reader + fd int + pending []byte + // paste passes everything literally until the bracketed paste end marker. + paste bool + // lookBehind keeps the last few delivered bytes while a paste is open, so + // an end marker split across reads is still recognised. + lookBehind []byte + // filled records that the last read used the caller's room (when that room + // is below the scratch size), so a trailing ESC may have been cut by the + // read rather than typed. + filled bool + // reset is bumped by ResetActive. The read loop compares it and drops + // what it holds, so reset never touches the reader's state directly. + reset atomic.Uint64 + gen uint64 + err error + scratch [readSize]byte +} + +// New wraps a terminal file and makes it the guard ResetActive resets. One +// reader must use it at a time. +func New(file *os.File) *Guard { + g := &Guard{file: file, reader: file, fd: int(file.Fd())} + current.Store(g) + return g +} + +var current atomic.Pointer[Guard] + +// ResetActive asks the active guard to drop bytes it is holding, so a command +// handed the terminal (an editor, ssh attach) starts from a clean boundary. +// The read loop performs the drop, because it is the only owner of that state. +func ResetActive() { + if g := current.Load(); g != nil { + g.reset.Add(1) + } +} + +// resetSeen reports a reset that the read loop has not applied yet. Only the +// read loop clears state, so a read that raced a reset cannot hand a caller a +// length computed before the clear. +func (g *Guard) resetSeen() bool { + return g.reset.Load() != g.gen +} + +// Read returns whole messages only. A partial sequence stays in pending and +// is completed by a later read; a broken SGR report is cut at the first byte +// that cannot belong to it. Returning (0, nil) is safe because the bytes it +// holds are not yet a complete message; an SS3 head is handed over as Alt+key +// after its brief wait. A reset is applied only by the read loop, so a read +// that raced one never slices a buffer the reset already cleared. +func (g *Guard) Read(p []byte) (int, error) { + if len(p) == 0 { + return 0, nil + } + didRead := false + for { + if gen := g.reset.Load(); gen != g.gen { + g.gen = gen + g.pending = nil + g.paste = false + g.lookBehind = nil + g.filled = false + g.err = nil + continue + } + if g.err != nil { + if complete := completeLen(g.pending); complete > 0 { + return g.emit(p, complete), nil + } + g.pending = nil + return 0, g.err + } + if g.paste { + if len(g.pending) > 0 { + combined := append(append([]byte(nil), g.lookBehind...), g.pending...) + if idx := bytes.Index(combined, pasteEnd); idx >= 0 { + markerEnd := idx + len(pasteEnd) + take := markerEnd - len(g.lookBehind) + out := append([]byte(nil), g.pending[:take]...) + rest, tail, pasting := sanitizePaste(g.pending[take:]) + out = append(out, rest...) + g.pending = tail + g.paste = pasting + g.lookBehind = nil + if pasting { + g.lookBehind = tailBytes(out, len(pasteEnd)-1) + } else { + out = g.extendTail(p, out) + if g.resetSeen() { + continue + } + } + return g.emitBytes(p, out), nil + } + // Not finished: deliver what arrived and remember the tail. + g.lookBehind = tailBytes(combined, len(pasteEnd)-1) + return g.emit(p, len(g.pending)), nil + } + if didRead { + return 0, nil + } + didRead = true + g.readOnce(len(p) - len(g.pending)) + continue + } + + if trimmed := abortedCSI(g.pending); len(trimmed) != len(g.pending) { + g.replace(trimmed) + continue + } + if bytes.Contains(g.pending, pasteStart) { + out, tail, pasting := sanitizePaste(g.pending) + g.pending = tail + g.paste = pasting + if pasting { + g.lookBehind = tailBytes(out, len(pasteEnd)-1) + } else { + out = g.extendTail(p, out) + if g.resetSeen() { + continue + } + } + if len(out) > 0 { + return g.emitBytes(p, out), nil + } + } + complete := completeLen(g.pending) + if complete > 0 { + if trimmed := abortedCSI(g.pending[complete:]); len(trimmed) != len(g.pending)-complete { + g.pending = append(g.pending[:complete:complete], trimmed...) + continue + } + tail := g.pending[complete:] + if len(tail) == 1 && tail[0] == esc { + if g.filled { + // The limit cut a sequence after its ESC; keep it, as + // Bubble Tea itself does at a full buffer. + return g.emit(p, complete), nil + } + if g.peek(p) { + continue + } + if g.resetSeen() { + continue + } + // A standalone Escape is a key: hand it over with the prefix + // instead of leaving it for the next keystroke. + return g.emit(p, complete+1), nil + } + if isSS3(tail) && !g.filled { + // The tail is a complete Alt+key now, but it may still become + // an SS3 key. Wait once, then hand the prefix and the head + // over together; otherwise Alt+O waits for the next keystroke. + if g.waitBriefly(p) { + continue + } + if g.resetSeen() { + continue + } + return g.emit(p, len(g.pending)), nil + } + return g.emit(p, complete), nil + } + + if len(g.pending) == 0 { + if didRead { + return 0, nil + } + didRead = true + g.readOnce(len(p)) + continue + } + if len(g.pending) == 1 && g.pending[0] == esc { + if g.filled { + // The limit cut a sequence after its ESC. Read the rest; if + // none is queued, hold the byte for the next read as Bubble + // Tea does at a full buffer. + if didRead { + return 0, nil + } + didRead = true + g.readOnce(len(p) - 1) + continue + } + if g.peek(p) { + continue + } + if g.resetSeen() { + continue + } + return g.emit(p, 1), nil + } + if isSS3(g.pending) || isPartialRune(g.pending) || isEscPartialRune(g.pending) { + // Poll even after the read above: this branch may have arrived in + // that same read, and the cancel reader only wakes on a new fd + // event. A bare Alt+O must resolve without another keystroke. + didRead = true + if g.waitBriefly(p) { + continue + } + if g.resetSeen() { + continue + } + return g.emit(p, len(g.pending)), nil + } + + room := len(p) - len(g.pending) + if room <= 0 { + // A sequence larger than the caller's buffer cannot be delivered; + // drop its head and let the rest be parsed on its own. + g.pending = nil + continue + } + if didRead { + return 0, nil + } + didRead = true + g.readOnce(room) + } +} + +// sanitizePaste copies complete input and pastes, dropping broken CSI heads +// and undecidable prefixes that would otherwise strand a paste behind an +// empty fd. The returned tail is an incomplete non-paste sequence to keep. +func sanitizePaste(b []byte) (out, tail []byte, pasting bool) { + i := 0 + for i < len(b) { + if b[i] == esc && bytes.HasPrefix(b[i+1:], pasteStart) { + // A lone Escape glued to a paste start would turn the marker into + // Alt+Esc plus text; keep the paste. + i++ + continue + } + if isCSI(b[i:]) { + if trimmed := abortedCSI(b[i:]); len(trimmed) < len(b[i:]) { + // Drop the broken head; its offending byte is parsed next. + i += len(b[i:]) - len(trimmed) + continue + } + } + j := bytes.Index(b[i:], pasteStart) + if j == 0 { + rest := b[i+len(pasteStart):] + if end := bytes.Index(rest, pasteEnd); end >= 0 { + at := i + len(pasteStart) + end + len(pasteEnd) + out = append(out, b[i:at]...) + i = at + continue + } + return append(out, b[i:]...), nil, true + } + if j > 0 { + prefix := b[i : i+j] + complete := completeLen(prefix) + if complete == 0 { + // An undecidable prefix before a paste: drop it, keep the + // paste rather than strand it behind an empty fd. + i += j + continue + } + out = append(out, prefix[:complete]...) + i += complete + continue + } + complete := completeLen(b[i:]) + if complete == 0 { + return out, append([]byte(nil), b[i:]...), false + } + out = append(out, b[i:i+complete]...) + i += complete + } + return out, nil, false +} + +// tailBytes copies at most n trailing bytes of b. +func tailBytes(b []byte, n int) []byte { + if n <= 0 || len(b) == 0 { + return nil + } + if len(b) > n { + b = b[len(b)-n:] + } + return append([]byte(nil), b...) +} + +// extendTail resolves an Escape or SS3 head that follows bytes ready to +// return. A complete key must not stay in pending: the cancel reader only +// calls Read again when the fd has data, so the next keystroke would be the +// only thing that wakes it. +func (g *Guard) extendTail(p []byte, out []byte) []byte { + for !g.filled { + if len(out)+len(g.pending) > len(p) { + return out + } + if bytes.Contains(g.pending, pasteStart) { + rest, tail, pasting := sanitizePaste(g.pending) + if len(out)+len(rest) > len(p) { + return out + } + out = append(out, rest...) + g.pending = tail + g.paste = pasting + if pasting { + g.lookBehind = tailBytes(out, len(pasteEnd)-1) + return out + } + continue + } + switch { + case len(g.pending) == 1 && g.pending[0] == esc: + if !g.peek(p[len(out):]) { + if g.resetSeen() { + return out + } + if len(out)+len(g.pending) > len(p) { + return out + } + out = append(out, g.pending...) + g.pending = nil + return out + } + case isSS3(g.pending): + if !g.waitBriefly(p[len(out):]) { + if g.resetSeen() { + return out + } + if len(out)+len(g.pending) > len(p) { + return out + } + out = append(out, g.pending...) + g.pending = nil + return out + } + default: + return out + } + if g.resetSeen() { + return out + } + if complete := completeLen(g.pending); complete > 0 { + if len(out)+complete > len(p) { + return out + } + out = append(out, g.pending[:complete]...) + g.pending = g.pending[complete:] + return out + } + } + return out +} + +// emitBytes copies already-compacted bytes out. +func (g *Guard) emitBytes(p, b []byte) int { + return copy(p, b) +} + +// abortedCSI drops the head of a broken CSI when a byte that cannot belong to +// it arrives, keeping that byte. SGR reports accept only their parameters and +// M/m; other CSI accept parameter and intermediate bytes and one final byte. +// A letter in an SGR report, a control byte or a non-ASCII byte therefore ends +// the sequence instead of being swallowed. +func abortedCSI(b []byte) []byte { + if !isCSI(b) { + return b + } + if len(b) > 2 && b[2] == '<' { + for i := 3; i < len(b); i++ { + switch c := b[i]; { + case c == 'M' || c == 'm': + return b + case c >= '0' && c <= '9', c == ';', c == ':': + default: + return b[i:] + } + } + return b + } + intermediate := false + for i := 2; i < len(b); i++ { + c := b[i] + if !intermediate { + switch { + case c >= 0x30 && c <= 0x3f: + continue + case c == '$' && i == 3 && (b[2] == '7' || b[2] == '8'): + // urxvt Shift+Home/End end on $, which Bubble Tea maps. + return b + case c >= 0x20 && c <= 0x2f: + intermediate = true + continue + case c >= 0x40 && c <= 0x7e: + return b + } + return b[i:] + } + switch { + case c >= 0x20 && c <= 0x2f: + continue + case c >= 0x40 && c <= 0x7e: + return b + default: + return b[i:] + } + } + return b +} + +func isCSI(b []byte) bool { + return len(b) >= 2 && b[0] == esc && b[1] == '[' +} + +// isSS3 reports whether b is the head of an SS3 key sequence. +func isSS3(b []byte) bool { + return len(b) == 2 && b[0] == esc && b[1] == 'O' +} + +// isPartialRune reports whether b is the beginning of a multi-byte UTF-8 +// character whose remaining bytes have not arrived yet. +func isPartialRune(b []byte) bool { + return len(b) > 0 && b[0] >= 0x80 && !utf8.FullRune(b) +} + +// isEscPartialRune covers an Alt-modified character cut inside its UTF-8 +// bytes: ESC followed by a partial rune. +func isEscPartialRune(b []byte) bool { + return len(b) >= 2 && b[0] == esc && b[1] >= 0x80 && !utf8.FullRune(b[1:]) +} + +// waitBriefly reads for the rest of an SS3 key or a split character. +func (g *Guard) waitBriefly(p []byte) bool { + return g.waitFor(p, briefTimeout) +} + +// peek reads only bytes already queued. A bare Escape stays a key unless the +// rest of its sequence is waiting at this moment, which is crossterm's rule. +func (g *Guard) peek(p []byte) bool { + return g.waitFor(p, 0) +} + +// waitFor reads for up to timeout, reporting whether new bytes arrived. +func (g *Guard) waitFor(p []byte, timeout time.Duration) bool { + room := len(p) - len(g.pending) + if room <= 0 { + return false + } + ready, err := waitInput(g.fd, timeout) + if err != nil { + g.err = err + return true + } + if !ready { + return false + } + return g.readOnce(room) +} + +// readOnce performs at most one terminal read, bounded by the caller's room. +func (g *Guard) readOnce(limit int) bool { + if limit > readSize { + limit = readSize + } + if limit <= 0 { + return false + } + gen := g.reset.Load() + n, err := g.reader.Read(g.scratch[:limit]) + if g.reset.Load() != gen { + // A reset landed while this read was in flight; the bytes belong to + // the command that asked for the handoff, not to the manager. The + // read loop applies the reset, so a caller that computed a length + // before this read cannot slice a buffer that is already cleared. + return false + } + if n > 0 { + g.pending = append(g.pending, g.scratch[:n]...) + g.filled = n == limit && limit < readSize + } + if err != nil { + g.err = err + } + return n > 0 +} + +func (g *Guard) emit(p []byte, n int) int { + copied := copy(p, g.pending[:n]) + g.pending = g.pending[copied:] + if len(g.pending) == 0 { + g.pending = nil + } + return copied +} + +func (g *Guard) replace(b []byte) { + g.pending = append(g.pending[:0], b...) +} + +// Write, Close, Fd and Name keep the wrapped input recognizable as a terminal +// file to Bubble Tea and its cancel reader. +func (g *Guard) Write(p []byte) (int, error) { return g.file.Write(p) } +func (g *Guard) Close() error { return g.file.Close() } +func (g *Guard) Fd() uintptr { return uintptr(g.fd) } +func (g *Guard) Name() string { return g.file.Name() } + +var _ io.ReadWriteCloser = (*Guard)(nil) diff --git a/internal/inputguard/wait_unix.go b/internal/inputguard/wait_unix.go new file mode 100644 index 00000000..885b56de --- /dev/null +++ b/internal/inputguard/wait_unix.go @@ -0,0 +1,25 @@ +//go:build unix + +package inputguard + +import ( + "errors" + "time" + + "golang.org/x/sys/unix" +) + +func waitInput(fd int, timeout time.Duration) (bool, error) { + ms := int((timeout + time.Millisecond - 1) / time.Millisecond) + for { + fds := []unix.PollFd{{Fd: int32(fd), Events: unix.POLLIN}} + ready, err := unix.Poll(fds, ms) + if errors.Is(err, unix.EINTR) { + continue + } + if err != nil { + return false, err + } + return ready > 0, nil + } +} diff --git a/internal/inputguard/wait_unix_test.go b/internal/inputguard/wait_unix_test.go new file mode 100644 index 00000000..17bca949 --- /dev/null +++ b/internal/inputguard/wait_unix_test.go @@ -0,0 +1,46 @@ +//go:build unix + +package inputguard + +import ( + "os" + "testing" + "time" +) + +func TestWaitInputReady(t *testing.T) { + read, write, err := os.Pipe() + if err != nil { + t.Fatalf("pipe: %v", err) + } + t.Cleanup(func() { _ = read.Close(); _ = write.Close() }) + if _, err := write.WriteString("x"); err != nil { + t.Fatalf("write: %v", err) + } + ready, err := waitInput(int(read.Fd()), time.Second) + if err != nil { + t.Fatalf("waitInput: %v", err) + } + if !ready { + t.Fatal("waitInput = false, want ready") + } + var buf [1]byte + if _, err := read.Read(buf[:]); err != nil { + t.Fatalf("read queued byte: %v", err) + } +} + +func TestWaitInputTimeout(t *testing.T) { + read, write, err := os.Pipe() + if err != nil { + t.Fatalf("pipe: %v", err) + } + t.Cleanup(func() { _ = read.Close(); _ = write.Close() }) + ready, err := waitInput(int(read.Fd()), 20*time.Millisecond) + if err != nil { + t.Fatalf("waitInput: %v", err) + } + if ready { + t.Fatal("waitInput = true, want timeout") + } +} diff --git a/internal/ui/terminal/exec.go b/internal/ui/terminal/exec.go index 5ca3ae55..27beb925 100644 --- a/internal/ui/terminal/exec.go +++ b/internal/ui/terminal/exec.go @@ -7,19 +7,35 @@ import ( "os/exec" tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/x/term" ) // ExecProcess hands the terminal to cmd for the length of its run. // -// Bubble Tea's program output is wrapped for IME cursor placement, but -// os/exec only gives a child a TTY when Stdout is the actual *os.File. +// Bubble Tea's program input and output are wrapped (input by the guard that +// keeps escape sequences whole, output for IME cursor placement), but os/exec +// only gives a child a TTY when both ends are the actual *os.File. func ExecProcess(cmd *exec.Cmd, fn tea.ExecCallback) tea.Cmd { + pinStdin(cmd, os.Stdin, term.IsTerminal(os.Stdin.Fd())) if cmd.Stdout == nil { cmd.Stdout = os.Stdout } return Exec(processCommand{cmd}, fn) } +// ResetInput drops input the program read but has not parsed, so a child that +// takes over the terminal starts from a message boundary. The manager sets it +// to the active guard; it is a hook so this package stays free of the guard. +var ResetInput = func() {} + +// pinStdin hands the child the terminal only when that is where the manager +// reads input; a redirected stdin stays unset, so Bubble Tea's /dev/tty wins. +func pinStdin(cmd *exec.Cmd, stdin *os.File, terminal bool) { + if cmd.Stdin == nil && terminal { + cmd.Stdin = stdin + } +} + // Exec hands the terminal to c with scheme reports off: Bubble Tea releases // only the modes it set, so a flip would otherwise reach the child as typed // input. The callback runs once the terminal is restored and asks for the @@ -37,6 +53,11 @@ func Exec(c tea.ExecCommand, fn tea.ExecCallback) tea.Cmd { type schemeReportsPaused struct{ tea.ExecCommand } func (c schemeReportsPaused) Run() error { + // Bubble Tea has stopped its reader and released the terminal by the time + // Run is called. Drop anything read before that boundary, and again after + // the child, which may leave an EOF from its own reads. + ResetInput() + defer ResetInput() if err := DisableSchemeReports(); err != nil { return err } diff --git a/internal/ui/terminal/exec_test.go b/internal/ui/terminal/exec_test.go index 04be1b04..6642813a 100644 --- a/internal/ui/terminal/exec_test.go +++ b/internal/ui/terminal/exec_test.go @@ -20,11 +20,19 @@ import ( "github.com/charmbracelet/x/ansi" ) -func TestExecProcessKeepsChildStdoutOnTheTerminal(t *testing.T) { +func TestExecProcessKeepsChildOnTheTerminal(t *testing.T) { cmd := exec.CommandContext(context.Background(), "sh", "-c", "true") - ExecProcess(cmd, nil) - if cmd.Stdout != os.Stdout { - t.Fatal("interactive child stdout was not pinned to the terminal") + pinStdin(cmd, os.Stdin, true) + if cmd.Stdin != os.Stdin { + t.Fatal("interactive child stdin was not pinned to the terminal") + } +} + +func TestPinStdinLeavesARedirectedStreamAlone(t *testing.T) { + cmd := exec.CommandContext(context.Background(), "sh", "-c", "true") + pinStdin(cmd, os.Stdin, false) + if cmd.Stdin != nil { + t.Fatal("redirected stdin was replaced with the process stdin") } } @@ -236,3 +244,53 @@ func TestExecPausesSchemeReportsAroundChild(t *testing.T) { }) } } + +// quietCommand takes the terminal and does nothing, so the reset boundaries +// around it can be observed without a real child. +type quietCommand struct{ run func() } + +func (c quietCommand) Run() error { + if c.run != nil { + c.run() + } + return nil +} +func (quietCommand) SetStdin(io.Reader) {} +func (quietCommand) SetStdout(io.Writer) {} +func (quietCommand) SetStderr(io.Writer) {} + +func TestExecResetsInputAroundChild(t *testing.T) { + original := ResetInput + t.Cleanup(func() { ResetInput = original }) + calls := 0 + ResetInput = func() { calls++ } + devNull, err := os.OpenFile(os.DevNull, os.O_WRONLY, 0) + if err != nil { + t.Fatalf("open dev null: %v", err) + } + saved := os.Stdout + os.Stdout = devNull + t.Cleanup(func() { + os.Stdout = saved + _ = devNull.Close() + }) + beforeChild := -1 + err = (schemeReportsPaused{quietCommand{run: func() { beforeChild = calls }}}).Run() + if err != nil { + t.Fatalf("run: %v", err) + } + if beforeChild != 1 { + t.Fatalf("reset ran %d times before the child, want once", beforeChild) + } + if calls != 2 { + t.Fatalf("reset ran %d times, want before and after the child", calls) + } +} + +func TestExecProcessPinsStdout(t *testing.T) { + cmd := exec.CommandContext(context.Background(), "sh", "-c", "true") + ExecProcess(cmd, nil) + if cmd.Stdout != os.Stdout { + t.Fatal("ExecProcess did not pin stdout to the terminal") + } +} diff --git a/main.go b/main.go index b6e106aa..0dc1095e 100644 --- a/main.go +++ b/main.go @@ -364,6 +364,7 @@ func run() (resultErr error) { tea.WithMouseCellMotion(), tea.WithOutput(model.CursorOutput(os.Stdout)), tea.WithFilter(programFilter), + inputOption(), ) if err := ui.DisableAlternateScroll(); err != nil { return err diff --git a/main_input_other.go b/main_input_other.go new file mode 100644 index 00000000..3d4c9b18 --- /dev/null +++ b/main_input_other.go @@ -0,0 +1,9 @@ +//go:build !unix + +package main + +import tea "github.com/charmbracelet/bubbletea" + +// inputOption keeps Bubble Tea's native reader on platforms whose console +// input has no wait primitive this package can share. +func inputOption() tea.ProgramOption { return func(*tea.Program) {} } diff --git a/main_input_unix.go b/main_input_unix.go new file mode 100644 index 00000000..f6097b20 --- /dev/null +++ b/main_input_unix.go @@ -0,0 +1,24 @@ +//go:build unix + +package main + +import ( + "os" + + "github.com/YoanWai/agent-manager/internal/inputguard" + "github.com/YoanWai/agent-manager/internal/ui/terminal" + tea "github.com/charmbracelet/bubbletea" + "github.com/charmbracelet/x/term" +) + +func init() { terminal.ResetInput = inputguard.ResetActive } + +// inputOption hands the TUI whole escape sequences when stdin is a terminal, +// so a short read cannot split a mouse report into keys and text. Input that +// is not a terminal keeps Bubble Tea's own reader. +func inputOption() tea.ProgramOption { + if !term.IsTerminal(os.Stdin.Fd()) { + return func(*tea.Program) {} + } + return tea.WithInput(inputguard.New(os.Stdin)) +}