fix: drain terminal query replies before releasing the terminal (#1894)

Signed-off-by: Drew Smirnoff <drew@charm.land>
This commit is contained in:
Drew Smirnoff 2026-11-20 19:01:53 +04:00 committed by GitHub
parent b681f23559
commit 585149e50e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 316 additions and 6 deletions

View file

@ -31,11 +31,12 @@ type cursedRenderer struct {
hardTabs bool // whether to use hard tabs to optimize cursor movements
backspace bool // whether to use backspace to optimize cursor movements
mapnl bool
syncdUpdates bool // whether to use synchronized output mode for updates
starting bool // indicates whether the renderer is starting after being stopped
pendingErase bool // an scr.Erase() is pending and hasn't been drained by flush yet
viewStale bool // a resize occurred and we are waiting for render() to supply the new View
noInput bool // whether input is disabled, in which case keyboard enhancement queries are pointless
syncdUpdates bool // whether to use synchronized output mode for updates
starting bool // indicates whether the renderer is starting after being stopped
pendingErase bool // an scr.Erase() is pending and hasn't been drained by flush yet
viewStale bool // a resize occurred and we are waiting for render() to supply the new View
noInput bool // whether input is disabled, in which case keyboard enhancement queries are pointless
onQuery func() // called when a terminal query is written, see [Program.noteQuery]
}
var _ renderer = &cursedRenderer{}
@ -290,6 +291,14 @@ func (s *cursedRenderer) close() (err error) {
return nil
}
// query writes a terminal query and reports it to onQuery.
func (s *cursedRenderer) query(seq string) {
_, _ = s.scr.WriteString(seq)
if s.onQuery != nil {
s.onQuery()
}
}
// writeString implements renderer.
func (s *cursedRenderer) writeString(str string) (int, error) {
s.mu.Lock()
@ -467,7 +476,7 @@ func (s *cursedRenderer) flushLocked(closing bool) (bool, error) {
}
if !closing {
// Request keyboard enhancements when they change
_, _ = s.scr.WriteString(ansi.RequestKittyKeyboard)
s.query(ansi.RequestKittyKeyboard)
}
}

31
tea.go
View file

@ -559,6 +559,11 @@ type Program struct {
inputScanner *uv.TerminalReader
readLoopDone chan struct{}
// lastQuery is when a terminal query was last written, in Unix
// nanoseconds, or 0 once its reply has been read. See
// [Program.drainQueryReplies].
lastQuery atomic.Int64
// modes keeps track of terminal modes that have been enabled or disabled.
ignoreSignals uint32
@ -1183,6 +1188,7 @@ func (p *Program) Run() (returnModel Model, returnErr error) {
// raw mode. See issue #1572.
mapNl := runtime.GOOS != "windows" && p.ttyInput == nil
r.setOptimizations(p.useHardTabs, p.useBackspace, mapNl)
r.onQuery = p.noteQuery
p.renderer = r
}
}
@ -1362,9 +1368,17 @@ func (p *Program) executeQuery(seq string) {
if p.disableInput {
return
}
p.noteQuery()
p.execute(seq)
}
// noteQuery records that a terminal query is about to be written, so its
// reply can be read before the terminal is handed back. See
// [Program.drainQueryReplies].
func (p *Program) noteQuery() {
p.lastQuery.Store(time.Now().UnixNano())
}
// flush flushes the output buffer to the program output.
func (p *Program) flush() error {
p.mu.Lock()
@ -1420,6 +1434,11 @@ func (p *Program) shutdown(kill bool) {
p.stopRenderer(kill)
}
// Read the replies to queries that are still in flight, so they don't
// end up in the shell as typed input once the program exits. The
// program's context is already canceled, so give the drain its own.
_ = p.drainQueryReplies(context.Background())
_ = p.restoreTerminalState()
})
}
@ -1501,6 +1520,18 @@ func (p *Program) releaseTerminal(reset bool) error {
}
}
// Replies to queries we sent may still be in flight. Read them now, while
// the terminal is still in raw mode, so they don't end up as input for
// whoever gets the terminal next, e.g. an exec'd process. The program gets
// them once its event loop resumes.
if events := p.drainQueryReplies(p.ctx); len(events) > 0 {
go func() {
for _, ev := range events {
p.Send(ev)
}
}()
}
return p.restoreTerminalState()
}

73
tty.go
View file

@ -8,6 +8,7 @@ import (
"time"
uv "github.com/charmbracelet/ultraviolet"
"github.com/charmbracelet/x/ansi"
"github.com/charmbracelet/x/term"
)
@ -157,6 +158,78 @@ func (p *Program) waitForReadLoop() {
}
}
// queryDrainTimeout bounds how long [Program.drainQueryReplies] waits for the
// terminal to answer.
const queryDrainTimeout = 500 * time.Millisecond
// queryReplyWindow is how long after a query its reply may still be on its
// way. The input reader reads replies that arrive later than that.
const queryReplyWindow = time.Second
// drainQueryReplies reads the replies to terminal queries that may still be in
// flight after the input reader has stopped, and returns them. Otherwise they
// stay in the tty input queue for the next reader: a process started with
// [ExecProcess], or the shell once the program exits (#1590).
//
// It sends a Primary Device Attributes (DA1) request and reads input until
// the terminal answers it. Terminals answer requests in order, so by then
// every earlier reply has been read. Nothing is drained when the last query
// was sent long enough ago for its reply to have been read already.
func (p *Program) drainQueryReplies(ctx context.Context) []Msg {
last := p.lastQuery.Swap(0)
if last == 0 || time.Since(time.Unix(0, last)) > queryReplyWindow ||
p.ttyInput == nil || p.ttyOutput == nil || p.input == nil {
return nil
}
// Make sure the pending queries themselves have been written, followed by
// the DA1 request that marks the end of their replies.
p.mu.Lock()
_, _ = p.outputBuf.WriteString(ansi.RequestPrimaryDeviceAttributes)
p.mu.Unlock()
if err := p.flush(); err != nil {
p.keepWriteErr(err)
return nil
}
cr, err := uv.NewCancelReader(p.input)
if err != nil {
return nil
}
defer cr.Close() //nolint:errcheck
// Stop reading once the DA1 reply arrives, the timeout expires, or ctx is
// done.
ctx, cancel := context.WithTimeout(ctx, queryDrainTimeout)
defer cancel()
context.AfterFunc(ctx, func() { cr.Cancel() })
drv := uv.NewTerminalReader(cr, p.environ.Getenv("TERM"))
drv.SetLogger(p.logger)
eventc := make(chan uv.Event)
done := make(chan struct{})
go func() {
defer close(done)
_ = drv.StreamEvents(ctx, eventc)
}()
var events []Msg
for {
select {
case ev := <-eventc:
if _, ok := ev.(uv.PrimaryDeviceAttributesEvent); ok {
// Every earlier reply has been read.
cancel()
continue
}
events = append(events, ev)
case <-done:
return events
}
}
}
const (
defaultWidth = 80
defaultHeight = 24

197
tty_drain_test.go Normal file
View file

@ -0,0 +1,197 @@
//go:build !windows
// +build !windows
package tea
import (
"bytes"
"io"
"os"
"sync"
"testing"
"time"
uv "github.com/charmbracelet/ultraviolet"
"github.com/charmbracelet/x/ansi"
)
// fakeTerminal answers terminal queries written to it by writing the replies
// to the program's input, like a real terminal would.
type fakeTerminal struct {
mu sync.Mutex
out bytes.Buffer
input io.Writer
}
func (f *fakeTerminal) Write(b []byte) (int, error) {
f.mu.Lock()
defer f.mu.Unlock()
f.out.Write(b)
if bytes.Contains(b, []byte(ansi.RequestModeSynchronizedOutput)) {
_, _ = io.WriteString(f.input, "\x1b[?2026;2$y")
}
if bytes.Contains(b, []byte(ansi.RequestPrimaryDeviceAttributes)) {
_, _ = io.WriteString(f.input, "\x1b[?62;22c")
}
return len(b), nil
}
func (f *fakeTerminal) String() string {
f.mu.Lock()
defer f.mu.Unlock()
return f.out.String()
}
func newDrainTestProgram(t *testing.T) (*Program, *os.File, *fakeTerminal) {
t.Helper()
r, w, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
_ = r.Close()
_ = w.Close()
})
ft := &fakeTerminal{input: w}
p := NewProgram(nil, WithInput(r), WithOutput(ft))
// Pretend input and output are a terminal; drainQueryReplies only runs
// for TTYs.
p.ttyInput = r
p.ttyOutput = w
return p, w, ft
}
// readAvailable returns what can be read from r within d.
func readAvailable(t *testing.T, r io.Reader, d time.Duration) string {
t.Helper()
ch := make(chan string, 1)
go func() {
buf := make([]byte, 256)
n, _ := r.Read(buf)
ch <- string(buf[:n])
}()
select {
case s := <-ch:
return s
case <-time.After(d):
return ""
}
}
// Replies to queries that arrive after the input reader is canceled must not
// be left in the tty input for the next reader, such as an exec'd process.
func TestDrainQueryReplies(t *testing.T) {
p, w, ft := newDrainTestProgram(t)
// The query is still buffered, as it is when ExecProcess is returned from
// Init before the renderer has flushed.
p.executeQuery(ansi.RequestModeSynchronizedOutput)
start := time.Now()
events := p.drainQueryReplies(t.Context())
if elapsed := time.Since(start); elapsed >= queryDrainTimeout {
t.Fatalf("drain did not stop at the DA1 reply, took %v", elapsed)
}
if !bytes.Contains([]byte(ft.String()), []byte(ansi.RequestPrimaryDeviceAttributes)) {
t.Fatalf("expected a DA1 request to be written, got %q", ft.String())
}
// The reply is returned, the DA1 reply is not.
if len(events) != 1 {
t.Fatalf("expected one reply, got %#v", events)
}
if ev, ok := events[0].(uv.ModeReportEvent); !ok || ev.Mode != ansi.ModeSynchronizedOutput {
t.Fatalf("expected a synchronized output mode report, got %#v", events[0])
}
// Nothing but what is typed afterwards is left for the next reader.
if _, err := io.WriteString(w, "abc"); err != nil {
t.Fatal(err)
}
if got := readAvailable(t, p.input, time.Second); got != "abc" {
t.Fatalf("expected next reader to get %q, got %q", "abc", got)
}
}
// Releasing the terminal hands the replies it read to the program.
func TestReleaseTerminalDeliversQueryReplies(t *testing.T) {
p, _, _ := newDrainTestProgram(t)
p.executeQuery(ansi.RequestModeSynchronizedOutput)
if err := p.releaseTerminal(false); err != nil {
t.Fatal(err)
}
select {
case msg := <-p.msgs:
if ev, ok := msg.(uv.ModeReportEvent); !ok || ev.Mode != ansi.ModeSynchronizedOutput {
t.Fatalf("expected a synchronized output mode report, got %#v", msg)
}
case <-time.After(time.Second):
t.Fatal("mode report was not delivered to the program")
}
}
// A program that quits right after it starts sends its queries during
// shutdown. Their replies must be read before the terminal is handed back to
// the shell, or the shell reads them as typed input.
//
// Fixes: https://github.com/charmbracelet/bubbletea/issues/1590
func TestShutdownDrainsQueryReplies(t *testing.T) {
p, w, ft := newDrainTestProgram(t)
p.executeQuery(ansi.RequestModeSynchronizedOutput)
p.shutdown(false)
if !bytes.Contains([]byte(ft.String()), []byte(ansi.RequestPrimaryDeviceAttributes)) {
t.Fatalf("expected a DA1 request to be written, got %q", ft.String())
}
if _, err := io.WriteString(w, "abc"); err != nil {
t.Fatal(err)
}
if got := readAvailable(t, p.input, time.Second); got != "abc" {
t.Fatalf("expected the shell to get %q, got %q", "abc", got)
}
}
// Without outstanding queries there is nothing to drain, and no DA1 request
// is sent.
func TestDrainQueryRepliesNoPendingQuery(t *testing.T) {
p, _, ft := newDrainTestProgram(t)
p.drainQueryReplies(t.Context())
if out := ft.String(); out != "" {
t.Fatalf("expected no output, got %q", out)
}
}
// The reply to a query sent long ago has been read by the input reader
// already, so there's nothing to drain.
func TestDrainQueryRepliesOldQuery(t *testing.T) {
p, _, ft := newDrainTestProgram(t)
p.lastQuery.Store(time.Now().Add(-2 * queryReplyWindow).UnixNano())
p.drainQueryReplies(t.Context())
if out := ft.String(); out != "" {
t.Fatalf("expected no output, got %q", out)
}
}
// The renderer's keyboard enhancements query counts as a query.
func TestCursedRendererReportsQueries(t *testing.T) {
var out bytes.Buffer
r := newCursedRenderer(&out, []string{"TERM=xterm-256color"}, 80, 24)
var queries int
r.onQuery = func() { queries++ }
r.render(NewView("hello"))
if _, err := r.flush(false); err != nil {
t.Fatal(err)
}
if !bytes.Contains(out.Bytes(), []byte(ansi.RequestKittyKeyboard)) {
t.Fatalf("expected a keyboard enhancements query, got %q", out.String())
}
if queries != 1 {
t.Fatalf("expected the query to be reported once, got %d", queries)
}
}