Compare commits

..

6 commits
v2.1.2 ... main

Author SHA1 Message Date
Drew Smirnoff
585149e50e
fix: drain terminal query replies before releasing the terminal (#1894)
Signed-off-by: Drew Smirnoff <drew@charm.land>
2026-11-20 19:01:53 +04:00
Meng Yan
b681f23559
fix(renderer): flush queued view before insert above (#1741)
Co-authored-by: Drew Smirnoff <drew@charm.land>
Signed-off-by: Meng Yan <yanmxa@gmail.com>
Signed-off-by: Drew Smirnoff <drew@charm.land>
2026-11-20 18:56:54 +04:00
jane michelle arc
9c6598361d
fix: return write errors from Program.Run (#1879)
Co-authored-by: Drew Smirnoff <drew@charm.land>
Signed-off-by: Drew Smirnoff <drew@charm.land>
2026-11-20 18:52:39 +04:00
Johnny Chen
bc55190481
fix: synchronize canceled input cleanup (#1876)
AI-assisted-by: Codex (GPT 6.1 sol)
Co-authored-by: Drew Smirnoff <drew@charm.land>
Signed-off-by: Drew Smirnoff <drew@charm.land>
2026-11-20 18:44:32 +04:00
draw me an elephant
7dd9c4c46e
fix: keep signal subscription alive through shutdown (#1853)
Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-authored-by: Drew Smirnoff <drew@charm.land>
Signed-off-by: Drew Smirnoff <drew@charm.land>
2026-11-20 18:38:53 +04:00
draw me an elephant
7ab4335dac
fix: don't panic on uncomparable color.Color values (#1852)
Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
Co-authored-by: Drew Smirnoff <drew@charm.land>
Signed-off-by: Drew Smirnoff <drew@charm.land>
2026-11-20 18:33:00 +04:00
8 changed files with 1106 additions and 51 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()
@ -303,6 +312,11 @@ func (s *cursedRenderer) flush(closing bool) (bool, error) {
s.mu.Lock()
defer s.mu.Unlock()
return s.flushLocked(closing)
}
// flushLocked is [cursedRenderer.flush] for callers that hold s.mu.
func (s *cursedRenderer) flushLocked(closing bool) (bool, error) {
if !closing && s.viewStale {
return false, nil
}
@ -462,7 +476,7 @@ func (s *cursedRenderer) flush(closing bool) (bool, error) {
}
if !closing {
// Request keyboard enhancements when they change
_, _ = s.scr.WriteString(ansi.RequestKittyKeyboard)
s.query(ansi.RequestKittyKeyboard)
}
}
@ -491,7 +505,7 @@ func (s *cursedRenderer) flush(closing bool) (bool, error) {
{newColor: view.ForegroundColor, oldColor: lfg, reset: ansi.ResetForegroundColor, setter: ansi.SetForegroundColor},
{newColor: view.BackgroundColor, oldColor: lbg, reset: ansi.ResetBackgroundColor, setter: ansi.SetBackgroundColor},
} {
if c.newColor != c.oldColor {
if !colorEqual(c.newColor, c.oldColor) {
if c.newColor == nil {
// Reset the color if it was set to nil.
_, _ = s.scr.WriteString(c.reset)
@ -809,6 +823,20 @@ func (s *cursedRenderer) insertAbove(str string) error {
return nil
}
// render only queues the latest view; the frame ticker draws it later, so
// a print can arrive before the view the program just returned is on the
// terminal. Draw that view first, so the lines go above what is actually
// on screen: scrolling with the old frame's geometry can move rows of the
// old frame into the scrollback, and a view that leaves the alt screen
// hasn't left it yet, so the lines would be printed on the alt screen and
// lost. A view that enters the alt screen is left for later: until then,
// the lines are still printed on the normal screen, where they persist.
if !s.view.AltScreen {
if _, err := s.flushLocked(false); err != nil {
return fmt.Errorf("bubbletea: error flushing before insert above: %w", err)
}
}
var sb strings.Builder
w, h := s.cellbuf.Width(), s.cellbuf.Height()
_, y := s.scr.Position()
@ -928,6 +956,20 @@ func setProgramStatus(s *cursedRenderer, prev, cur *ProgramStatus) {
}
}
// colorEqual reports whether two colors are equal. Colors are compared by
// their RGBA values, which is all the terminal ever sees, rather than with ==,
// which panics on [color.Color] implementations whose dynamic type is
// uncomparable (e.g. a struct containing a slice). A nil color stays distinct
// from any other color so that resetting a color still works.
func colorEqual(a, b color.Color) bool {
if a == nil || b == nil {
return a == nil && b == nil
}
ar, ag, ab, aa := a.RGBA()
br, bg, bb, ba := b.RGBA()
return ar == br && ag == bg && ab == bb && aa == ba
}
func viewEquals(a, b *View) bool {
if a == nil || b == nil {
return false
@ -943,8 +985,8 @@ func viewEquals(a, b *View) bool {
a.ReportFocus != b.ReportFocus ||
a.MouseMode != b.MouseMode ||
a.WindowTitle != b.WindowTitle ||
a.ForegroundColor != b.ForegroundColor ||
a.BackgroundColor != b.BackgroundColor ||
!colorEqual(a.ForegroundColor, b.ForegroundColor) ||
!colorEqual(a.BackgroundColor, b.BackgroundColor) ||
a.KeyboardEnhancements != b.KeyboardEnhancements {
return false
}
@ -957,7 +999,7 @@ func viewEquals(a, b *View) bool {
a.Cursor.Y != b.Cursor.Y ||
a.Cursor.Shape != b.Cursor.Shape ||
a.Cursor.Blink != b.Cursor.Blink ||
a.Cursor.Color != b.Cursor.Color {
!colorEqual(a.Cursor.Color, b.Cursor.Color) {
return false
}
}

View file

@ -3,6 +3,7 @@ package tea
import (
"bytes"
"fmt"
"image/color"
"io"
"strings"
"testing"
@ -227,6 +228,103 @@ func TestCursedRenderer_mouseVsFlush(t *testing.T) {
}
}
// uncomparableColor is a color.Color implementation whose dynamic type is
// uncomparable (it contains a slice), so comparing two values with == panics.
type uncomparableColor struct {
rgba color.RGBA
pad []int
}
func (c uncomparableColor) RGBA() (r, g, b, a uint32) {
return c.rgba.RGBA()
}
// Fixes: https://github.com/charmbracelet/bubbletea/issues/1848
func TestCursedRenderer_uncomparableViewColors(t *testing.T) {
t.Parallel()
var out bytes.Buffer
r := newCursedRenderer(&out, []string{"TERM=xterm-256color"}, 80, 24)
r.start()
red := color.RGBA{R: 0xff, A: 0xff}
view := NewView("hello")
view.AltScreen = true
view.ForegroundColor = uncomparableColor{rgba: red, pad: []int{1}}
view.BackgroundColor = uncomparableColor{rgba: red, pad: []int{2}}
view.Cursor = &Cursor{Color: uncomparableColor{rgba: red, pad: []int{3}}}
// Render the same view twice. The second flush takes the viewEquals
// early-return path, which compares the color.Color interface values.
for range 2 {
r.render(view)
if _, err := r.flush(false); err != nil {
t.Fatal(err)
}
}
}
// Colors are compared by value: the same color, whatever its type, doesn't
// redraw the view, while a different color or a reset does.
func TestCursedRenderer_viewColorChanges(t *testing.T) {
t.Parallel()
red := color.RGBA{R: 0xff, A: 0xff}
blue := color.RGBA{B: 0xff, A: 0xff}
for _, tt := range []struct {
name string
set func(*View, color.Color)
code string
reset string
}{
{"foreground", func(v *View, c color.Color) { v.ForegroundColor = c }, "10", "110"},
{"background", func(v *View, c color.Color) { v.BackgroundColor = c }, "11", "111"},
{"cursor", func(v *View, c color.Color) { v.Cursor = NewCursor(0, 0); v.Cursor.Color = c }, "12", "112"},
} {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
var out bytes.Buffer
r := newCursedRenderer(&out, []string{"TERM=xterm-256color"}, 80, 24)
render := func(c color.Color) bool {
t.Helper()
view := NewView("hello")
tt.set(&view, c)
r.render(view)
drew, err := r.flush(false)
if err != nil {
t.Fatal(err)
}
return drew
}
render(uncomparableColor{rgba: red, pad: []int{1}})
if want := "\x1b]" + tt.code + ";#ff0000\a"; !strings.Contains(out.String(), want) {
t.Fatalf("missing red color sequence %q in %q", want, out.String())
}
out.Reset()
if render(uncomparableColor{rgba: red, pad: []int{2}}) || out.Len() != 0 {
t.Fatalf("unchanged color redrew the view: %q", out.String())
}
if render(red) || out.Len() != 0 {
t.Fatalf("the same color of another type redrew the view: %q", out.String())
}
render(uncomparableColor{rgba: blue})
if want := "\x1b]" + tt.code + ";#0000ff\a"; !strings.Contains(out.String(), want) {
t.Fatalf("missing blue color sequence %q in %q", want, out.String())
}
out.Reset()
render(nil)
if want := "\x1b]" + tt.reset + "\a"; !strings.Contains(out.String(), want) {
t.Fatalf("missing color reset %q in %q", want, out.String())
}
})
}
}
func assertInOrder(t *testing.T, got string, wants ...string) {
t.Helper()
rest := got
@ -357,10 +455,14 @@ func TestCursedRenderer_insertAboveBeforeFirstFlush(t *testing.T) {
t.Fatal(err)
}
want := "\r\n" + ansi.CursorUp(1) +
// The one-line view is drawn first, then the line is inserted above it,
// making room for one line rather than for the terminal's height.
got := output.String()
frame := "\r" + ansi.EraseScreenBelow + "footer"
insert := "\r\n" + ansi.CursorUp(1) +
ansi.InsertLine(1) + ansi.EraseLineRight + "startup" + "\r\n"
if got := output.String(); got != want {
t.Fatalf("unexpected insertAbove output:\nwant: %q\n got: %q", want, got)
if !strings.HasSuffix(got, frame+insert) {
t.Fatalf("unexpected insertAbove output:\nwant suffix: %q\n got: %q", frame+insert, got)
}
}
@ -476,6 +578,10 @@ func TestCursedRenderer_insertAboveLineBoundaries(t *testing.T) {
var out bytes.Buffer
r := newCursedRenderer(&out, []string{"TERM=xterm-256color"}, width, 2)
r.render(NewView("view\nview"))
if _, err := r.flush(false); err != nil {
t.Fatal(err)
}
out.Reset()
r.scr.SetPosition(0, 0)
if err := r.insertAbove(tt.line); err != nil {
t.Fatal(err)
@ -494,3 +600,94 @@ func TestCursedRenderer_insertAboveLineBoundaries(t *testing.T) {
})
}
}
func TestCursedRenderer_insertAboveFlushesQueuedView(t *testing.T) {
var output bytes.Buffer
r := newCursedRenderer(
&output,
[]string{"TERM=xterm-256color", "TERM_PROGRAM=Apple_Terminal"},
80,
24,
)
r.render(NewView("stale frame\nstale row"))
if _, err := r.flush(false); err != nil {
t.Fatalf("flush initial view: %v", err)
}
output.Reset()
r.render(NewView("current frame"))
if err := r.insertAbove("committed block"); err != nil {
t.Fatalf("insert above: %v", err)
}
if r.lastView == nil || r.lastView.Content != "current frame" {
t.Fatalf("insertAbove did not flush the queued view: %#v", r.lastView)
}
written := output.String()
currentAt := strings.Index(written, "current frame")
committedAt := strings.Index(written, "committed block")
if currentAt < 0 || committedAt < 0 {
t.Fatalf("output missing markers (current=%d, committed=%d): %q", currentAt, committedAt, written)
}
if currentAt > committedAt {
t.Fatalf("inserted scrollback before flushing current frame: %q", written)
}
}
// Fixes: https://github.com/charmbracelet/bubbletea/issues/1881
func TestCursedRenderer_insertAboveAfterLeavingAltScreen(t *testing.T) {
t.Parallel()
var out bytes.Buffer
r := newCursedRenderer(&out, []string{"TERM=xterm-256color"}, 80, 24)
alt := NewView("alt screen view")
alt.AltScreen = true
r.render(alt)
if _, err := r.flush(false); err != nil {
t.Fatal(err)
}
// The update leaves the alt screen and prints a line before the next
// frame is drawn. The line must be printed on the normal screen, after
// leaving the alt screen, or it is lost with it.
r.render(NewView("inline view"))
if err := r.insertAbove("printed line"); err != nil {
t.Fatal(err)
}
if _, err := r.flush(false); err != nil {
t.Fatal(err)
}
got := out.String()
assertInOrder(t, got, ansi.SetModeAltScreenSaveCursor, ansi.ResetModeAltScreenSaveCursor, "inline view", "printed line")
if n := strings.Count(got, "printed line"); n != 1 {
t.Fatalf("expected the line to be printed once, got %d times in %q", n, got)
}
}
func TestCursedRenderer_insertAboveBeforeEnteringAltScreen(t *testing.T) {
t.Parallel()
var out bytes.Buffer
r := newCursedRenderer(&out, []string{"TERM=xterm-256color"}, 80, 24)
r.render(NewView("inline view"))
if _, err := r.flush(false); err != nil {
t.Fatal(err)
}
// The update enters the alt screen and prints a line before the next
// frame is drawn. The line is printed on the normal screen, before
// entering the alt screen, so it's still there after leaving it.
alt := NewView("alt screen view")
alt.AltScreen = true
r.render(alt)
if err := r.insertAbove("printed line"); err != nil {
t.Fatal(err)
}
if _, err := r.flush(false); err != nil {
t.Fatal(err)
}
assertInOrder(t, out.String(), "inline view", "printed line", ansi.SetModeAltScreenSaveCursor, "alt screen view")
}

227
shutdown_input_test.go Normal file
View file

@ -0,0 +1,227 @@
package tea
import (
"context"
"errors"
"io"
"os"
"strings"
"testing"
"testing/synctest"
"time"
)
type shutdownInputReader struct {
cancelable bool
cancels int
closes int
}
func (*shutdownInputReader) Read([]byte) (int, error) { return 0, io.EOF }
func (r *shutdownInputReader) Cancel() bool { r.cancels++; return r.cancelable }
func (r *shutdownInputReader) Close() error { r.closes++; return nil }
func TestShutdownWaitsForCancelableInput(t *testing.T) {
for _, kill := range []bool{false, true} {
name := "quit"
if kill {
name = "kill"
}
t.Run(name, func(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
p := NewProgram(&testModel{}, WithOutput(io.Discard))
r := &shutdownInputReader{cancelable: true}
p.cancelReader = r
p.readLoopDone = make(chan struct{})
stopped := make(chan struct{})
go func() { p.shutdown(kill); close(stopped) }()
synctest.Wait()
if r.cancels != 1 || r.closes != 0 {
t.Errorf("before read loop completion: cancel=%d close=%d", r.cancels, r.closes)
}
select {
case <-stopped:
t.Error("shutdown returned before the input loop finished")
default:
}
close(p.readLoopDone)
synctest.Wait()
<-stopped
if r.closes != 1 {
t.Errorf("close calls after input completion: got %d, want 1", r.closes)
}
p.shutdown(kill)
if r.cancels != 1 || r.closes != 1 {
t.Errorf("repeated shutdown: cancel=%d close=%d", r.cancels, r.closes)
}
})
})
}
}
func TestShutdownDefersCloseAfterInputTimeout(t *testing.T) {
for _, kill := range []bool{false, true} {
name := "quit"
if kill {
name = "kill"
}
t.Run(name, func(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
p := NewProgram(&testModel{}, WithOutput(io.Discard))
r := &shutdownInputReader{cancelable: true}
p.cancelReader = r
done := make(chan struct{})
p.readLoopDone = done
stopped := make(chan struct{})
go func() { p.shutdown(kill); close(stopped) }()
synctest.Wait()
time.Sleep(time.Second)
synctest.Wait()
select {
case <-stopped:
default:
t.Error("shutdown did not retain its bounded wait")
}
if r.closes != 0 {
t.Errorf("reader closed while its input loop was still active: %d", r.closes)
}
// Cleanup must retain this reader, not follow a later field assignment.
replacement := &shutdownInputReader{}
p.cancelReader = replacement
p.readLoopDone = make(chan struct{})
close(done)
synctest.Wait()
if r.closes != 1 || replacement.closes != 0 {
t.Errorf("close calls: original=%d replacement=%d", r.closes, replacement.closes)
}
<-stopped
})
})
}
}
// A reader that shutdown closed must not be closed again when a later run
// replaces it: closing a cancel reader closes raw file descriptors, so a
// second close can close an unrelated file that reused the number.
func TestShutdownClosesInputOnce(t *testing.T) {
p := NewProgram(&testModel{}, WithInput(strings.NewReader("")), WithOutput(io.Discard))
r := &shutdownInputReader{cancelable: true}
p.cancelReader = r
p.readLoopDone = make(chan struct{})
close(p.readLoopDone)
p.shutdown(false)
if r.closes != 1 {
t.Fatalf("shutdown closed the reader %d times, want 1", r.closes)
}
// The next run starts a new reader in place of the closed one.
if err := p.initInputReader(false); err != nil {
t.Fatal(err)
}
if r.closes != 1 {
t.Errorf("starting a new reader closed the old one again: %d closes", r.closes)
}
p.shutdownInput()
}
func TestShutdownInputFallbacks(t *testing.T) {
for _, tc := range []struct {
name string
reader bool
cancelable bool
loop bool
finished bool
}{
{name: "no reader"},
{name: "uncancelable", reader: true, loop: true},
{name: "no input loop", reader: true, cancelable: true},
{name: "finished loop", reader: true, cancelable: true, loop: true, finished: true},
} {
t.Run(tc.name, func(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
p := NewProgram(&testModel{}, WithOutput(io.Discard))
r := &shutdownInputReader{cancelable: tc.cancelable}
if tc.reader {
p.cancelReader = r
}
if tc.loop {
p.readLoopDone = make(chan struct{})
if tc.finished {
close(p.readLoopDone)
}
}
start := time.Now()
p.shutdown(true)
if time.Since(start) != 0 {
t.Error("input fallback unexpectedly waited")
}
if tc.reader && (r.cancels != 1 || r.closes != 1) {
t.Errorf("fallback cleanup: cancel=%d close=%d", r.cancels, r.closes)
}
})
})
}
}
type (
inputStartedMsg struct{}
inputShutdownModel struct{ ready chan struct{} }
)
func (m inputShutdownModel) Init() Cmd { return func() Msg { return inputStartedMsg{} } }
func (m inputShutdownModel) Update(msg Msg) (Model, Cmd) {
if _, ok := msg.(inputStartedMsg); ok {
close(m.ready)
}
return m, nil
}
func (inputShutdownModel) View() View { return NewView("ready") }
func TestProgramCanceledInput(t *testing.T) {
for _, kill := range []bool{false, true} {
name := "context"
if kill {
name = "kill"
}
t.Run(name, func(t *testing.T) {
// A real file exercises the native cancelreader rather than its no-op fallback.
reader, writer, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
defer reader.Close()
defer writer.Close()
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
ready := make(chan struct{})
p := NewProgram(inputShutdownModel{ready}, WithContext(ctx), WithInput(reader), WithOutput(io.Discard), WithWindowSize(80, 24), WithoutSignalHandler())
result := make(chan error, 1)
go func() { _, err := p.Run(); result <- err }()
select {
case <-ready:
case <-time.After(5 * time.Second):
t.Fatal("event loop did not start")
}
if kill {
p.Kill()
} else {
cancel()
}
select {
case err = <-result:
case <-time.After(5 * time.Second):
t.Fatal("program did not stop")
}
if !errors.Is(err, ErrProgramKilled) {
t.Fatalf("unexpected error: %v", err)
}
if !kill && !errors.Is(err, context.Canceled) {
t.Fatalf("missing external cancellation: %v", err)
}
if _, err := reader.Stat(); err != nil {
t.Fatalf("borrowed input was closed: %v", err)
}
})
}
}

View file

@ -55,3 +55,69 @@ func TestHandleSignalsReturnsAfterContextCancelDuringPendingSend(t *testing.T) {
t.Fatal("handleSignals did not return after context cancel: signal goroutine is deadlocked")
}
}
// TestHandleSignalsCatchesSecondSignalDuringShutdown is a regression test for
// https://github.com/charmbracelet/bubbletea/issues/1849: after a quit
// message is forwarded, the signal subscription must stay alive until the
// program finishes, so a second SIGINT during shutdown is caught instead of
// taking the runtime's default path and killing the process.
func TestHandleSignalsCatchesSecondSignalDuringShutdown(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Register our own handler first so a SIGINT can never take down the
// test process, whether or not handleSignals is catching it.
ours := make(chan os.Signal, 2)
signal.Notify(ours, syscall.SIGINT)
defer signal.Stop(ours)
finished := make(chan struct{})
defer close(finished)
p := &Program{
ctx: ctx,
msgs: make(chan Msg),
finished: finished,
}
done := p.handleSignals()
time.Sleep(100 * time.Millisecond) // let the handler register its signal.Notify
// While the program runs, every signal is forwarded as an interrupt
// message, so a program that doesn't quit on the first one (for example
// because a filter dropped it) still gets the next one.
for i := range 2 {
if err := syscall.Kill(os.Getpid(), syscall.SIGINT); err != nil {
t.Fatalf("failed to send SIGINT: %v", err)
}
<-ours
select {
case msg := <-p.msgs:
if _, ok := msg.(InterruptMsg); !ok {
t.Fatalf("expected InterruptMsg, got %T", msg)
}
case <-time.After(5 * time.Second):
t.Fatalf("SIGINT %d was not forwarded", i+1)
}
}
// Context cancellation (the start of shutdown) ends the handler.
cancel()
select {
case <-done:
case <-time.After(5 * time.Second):
t.Fatal("handleSignals did not finish after context cancel")
}
// Release our own watcher so that whether SIGINT is still caught depends
// solely on the program's subscription. A second SIGINT during the
// shutdown window must still be caught (and dropped); if the program had
// already released its subscription it would take the runtime's default
// path and terminate this test process — so surviving is the assertion.
signal.Stop(ours)
if err := syscall.Kill(os.Getpid(), syscall.SIGINT); err != nil {
t.Fatalf("failed to send second SIGINT: %v", err)
}
time.Sleep(200 * time.Millisecond)
}

159
tea.go
View file

@ -522,6 +522,8 @@ type Program struct {
msgs chan Msg
errs chan error
writeErr error // first error writing to the output; guarded by writeErrMu
writeErrMu sync.Mutex
finished chan struct{}
runMu sync.Mutex
shutdownOnce sync.Once
@ -557,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
@ -672,6 +679,11 @@ func NewProgram(model Model, opts ...ProgramOption) *Program {
func (p *Program) handleSignals() chan struct{} {
ch := make(chan struct{})
// Run sets finished before it starts the handlers. Read it here, not in
// the goroutine below, which may still be running when Run is called
// again and replaces it.
finished := p.finished
// Listen for SIGINT and SIGTERM.
//
// In most cases ^C will not send an interrupt because the terminal will be
@ -683,27 +695,34 @@ func (p *Program) handleSignals() chan struct{} {
go func() {
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
defer func() {
signal.Stop(sig)
close(ch)
}()
defer signal.Stop(sig)
for {
select {
case <-p.ctx.Done():
// The program is shutting down: report the handler done so
// shutdown can proceed, but keep the signal subscription
// alive until Run returns. A second SIGINT/SIGTERM arriving
// while the terminal is being restored is then caught and
// dropped instead of taking the runtime's default path,
// which kills the process before the terminal is restored.
close(ch)
if finished != nil {
<-finished
}
return
case s := <-sig:
if atomic.LoadUint32(&p.ignoreSignals) == 0 {
var msg Msg = QuitMsg{}
if s == syscall.SIGINT {
msg = InterruptMsg{}
}
select {
case p.msgs <- msg:
case <-p.ctx.Done():
}
return
if atomic.LoadUint32(&p.ignoreSignals) != 0 {
continue
}
var msg Msg = QuitMsg{}
if s == syscall.SIGINT {
msg = InterruptMsg{}
}
select {
case p.msgs <- msg:
case <-p.ctx.Done():
}
}
}
@ -897,7 +916,7 @@ func (p *Program) eventLoop(model Model, cmds chan Cmd) (Model, error) {
p.execute(fmt.Sprint(msg.Msg))
case printLineMessage:
p.renderer.insertAbove(msg.messageBody) //nolint:errcheck,gosec
p.keepWriteErr(p.renderer.insertAbove(msg.messageBody))
case clearScreenMsg:
p.renderer.clearScreen()
@ -1074,6 +1093,9 @@ func (p *Program) Run() (returnModel Model, returnErr error) {
p.ctx, p.cancel = context.WithCancel(p.externalCtx)
p.errs = make(chan error, 1)
p.shutdownOnce = sync.Once{}
p.writeErrMu.Lock()
p.writeErr = nil
p.writeErrMu.Unlock()
}
p.ranOnce = true
@ -1166,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
}
}
@ -1267,6 +1290,11 @@ func (p *Program) Run() (returnModel Model, returnErr error) {
// Restore terminal state.
p.shutdown(killed)
if err == nil {
// Report a failure to write to the output, if there was one.
err = p.firstWriteErr()
}
return model, err
}
@ -1340,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()
@ -1362,6 +1398,27 @@ func (p *Program) flush() error {
return nil
}
// keepWriteErr remembers err as the error to return from [Program.Run] if it
// is the first error writing to the output. Later errors are dropped so they
// do not hide the first one.
func (p *Program) keepWriteErr(err error) {
if err == nil {
return
}
p.writeErrMu.Lock()
defer p.writeErrMu.Unlock()
if p.writeErr == nil {
p.writeErr = err
}
}
// firstWriteErr returns the first error kept by keepWriteErr.
func (p *Program) firstWriteErr() error {
p.writeErrMu.Lock()
defer p.writeErrMu.Unlock()
return p.writeErr
}
// shutdown performs operations to free up resources and restore the terminal
// to its original state.
func (p *Program) shutdown(kill bool) {
@ -1371,21 +1428,17 @@ func (p *Program) shutdown(kill bool) {
// Wait for all handlers to finish.
p.handlers.shutdown()
// Check if the cancel reader has been setup before waiting and closing.
if p.cancelReader != nil {
// Wait for input loop to finish.
if p.cancelReader.Cancel() {
if !kill {
p.waitForReadLoop()
}
}
_ = p.cancelReader.Close()
}
p.shutdownInput()
if p.renderer != nil {
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()
})
}
@ -1418,6 +1471,13 @@ func (p *Program) recoverFromPanic(r interface{}) {
// recoverFromGoPanic recovers from a goroutine panic, prints a stack trace,
// restores the terminal to a usable state, and signals the program to be killed.
func (p *Program) recoverFromGoPanic(r interface{}) {
p.recoverFromGoPanicWithStack(r, debug.Stack())
}
// recoverFromGoPanicWithStack is [Program.recoverFromGoPanic] with the stack
// captured at the panic site. The renderer ticker goroutine uses this because
// it must not block in [Program.shutdown].
func (p *Program) recoverFromGoPanicWithStack(r interface{}, trace []byte) {
select {
case p.errs <- ErrProgramPanic:
default:
@ -1427,7 +1487,7 @@ func (p *Program) recoverFromGoPanic(r interface{}) {
// terminal does not work or when raw mode is still active.
rec := strings.ReplaceAll(fmt.Sprintf("%s", r), "\n", "\r\n")
fmt.Fprintf(os.Stderr, "Caught panic:\r\n\r\n%s\r\n\r\nRestoring terminal...\r\n\r\n", rec)
stack := strings.ReplaceAll(fmt.Sprintf("%s\n", debug.Stack()), "\n", "\r\n")
stack := strings.ReplaceAll(fmt.Sprintf("%s\n", trace), "\n", "\r\n")
fmt.Fprint(os.Stderr, stack)
if v, err := strconv.ParseBool(os.Getenv("TEA_DEBUG")); err == nil && v {
f, err := os.Create(fmt.Sprintf("bubbletea-panic-%d.log", time.Now().Unix()))
@ -1460,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()
}
@ -1561,8 +1633,14 @@ func (p *Program) startRenderer() {
realign = false
ticker.Reset(framerate)
}
_ = p.flush()
if drew, _ := p.renderer.flush(false); drew {
drew, ok := p.flushFrame()
if !ok {
// The renderer panicked and the program is shutting
// down. Stop drawing and wait for stopRenderer.
<-p.rendererDone
return
}
if drew {
idle = 0
} else if idle++; idle >= idleFrames {
// Nothing is changing. Stop waking up every frame until
@ -1575,6 +1653,26 @@ func (p *Program) startRenderer() {
}()
}
// flushFrame writes the queued output and the current frame, and reports
// whether a frame was drawn. If the renderer panics, ok is false and the panic
// is recovered so the terminal still gets restored. The recovery runs on
// another goroutine: shutting down sends on rendererDone, which only the
// renderer goroutine calling flushFrame receives.
func (p *Program) flushFrame() (drew, ok bool) {
if !p.disableCatchPanics {
defer func() {
if r := recover(); r != nil {
ok = false
go p.recoverFromGoPanicWithStack(r, debug.Stack())
}
}()
}
p.keepWriteErr(p.flush())
drew, err := p.renderer.flush(false)
p.keepWriteErr(err)
return drew, true
}
// stopRenderer stops the renderer.
// If kill is true, the renderer will be stopped immediately without flushing
// the last frame.
@ -1586,8 +1684,9 @@ func (p *Program) stopRenderer(kill bool) {
if !kill {
// flush locks the mutex
_, _ = p.renderer.flush(true)
_, err := p.renderer.flush(true)
p.keepWriteErr(err)
}
_ = p.renderer.close()
p.keepWriteErr(p.renderer.close())
}

View file

@ -775,6 +775,44 @@ func TestTeaGoroutinePanic(t *testing.T) {
}
}
// flushPanicRenderer panics on every non-closing flush, simulating a renderer
// crash inside the ticker goroutine started by startRenderer.
type flushPanicRenderer struct {
nilRenderer
}
func (flushPanicRenderer) flush(closing bool) (bool, error) {
if !closing {
panic("flushPanicRenderer")
}
return false, nil
}
// Fixes: https://github.com/charmbracelet/bubbletea/issues/1848
func TestTeaRendererFlushPanic(t *testing.T) {
t.Parallel()
var buf bytes.Buffer
var in bytes.Buffer
m := &testModel{}
p := NewProgram(m,
WithInput(&in),
WithOutput(&buf),
WithoutSignals(),
)
p.renderer = flushPanicRenderer{}
_, err := p.Run()
if !errors.Is(err, ErrProgramPanic) {
t.Fatalf("Expected %v, got %v", ErrProgramPanic, err)
}
if !errors.Is(err, ErrProgramKilled) {
t.Fatalf("Expected %v, got %v", ErrProgramKilled, err)
}
}
type benchModel struct {
t testing.TB
}
@ -1005,3 +1043,79 @@ func TestProgressBarStateStringOutOfRange(t *testing.T) {
}
}
}
type failWriter struct{}
func (failWriter) Write([]byte) (int, error) { return 0, errors.New("disk full") }
func TestTeaRunReturnsWriteError(t *testing.T) {
t.Parallel()
var in bytes.Buffer
in.Write([]byte("q"))
ctx, cancel := context.WithTimeout(t.Context(), 3*time.Second)
defer cancel()
p := NewProgram(&testModel{},
WithContext(ctx),
WithInput(&in),
WithOutput(failWriter{}),
)
_, err := p.Run()
if err == nil {
t.Fatal("Run returned nil although every write to the output failed")
}
if !strings.Contains(err.Error(), "disk full") {
t.Fatalf("Run error does not wrap the write error: %v", err)
}
if errors.Is(err, ErrProgramKilled) {
t.Fatalf("a write error alone should not report a killed program: %v", err)
}
}
// helloQuitModel draws a line and quits as soon as it starts.
type helloQuitModel struct{ init Cmd }
func (m helloQuitModel) Init() Cmd { return m.init }
func (m helloQuitModel) Update(Msg) (Model, Cmd) { return m, nil }
func (helloQuitModel) View() View { return NewView("hello") }
// A write error belongs to the run it happened in: running the program again
// with a working output returns no error.
func TestTeaRunWriteErrorDoesNotCarryOver(t *testing.T) {
t.Parallel()
var buf bytes.Buffer
p := NewProgram(helloQuitModel{init: Quit}, WithInput(nil), WithOutput(&buf), WithWindowSize(80, 24))
// Pretend an earlier run failed to write.
p.ranOnce = true
p.keepWriteErr(errors.New("disk full"))
if _, err := p.Run(); err != nil {
t.Fatalf("expected no error, got %v", err)
}
if !strings.Contains(buf.String(), "hello") {
t.Fatalf("expected the view to be written, got %q", buf.String())
}
}
// printFailWriter fails the writes that print a line above the program.
type printFailWriter struct{}
func (printFailWriter) Write(b []byte) (int, error) {
if bytes.Contains(b, []byte("printed line")) {
return 0, errors.New("broken pipe")
}
return len(b), nil
}
// Failing to print a line above the program is a write error too.
func TestTeaRunReturnsPrintWriteError(t *testing.T) {
t.Parallel()
m := helloQuitModel{init: Sequence(Println("printed line"), Quit)}
_, err := NewProgram(m, WithInput(nil), WithOutput(printFailWriter{})).Run()
if err == nil || !strings.Contains(err.Error(), "broken pipe") {
t.Fatalf("expected the print's write error, got %v", err)
}
}

129
tty.go
View file

@ -1,12 +1,14 @@
package tea
import (
"context"
"fmt"
"os"
"strconv"
"time"
uv "github.com/charmbracelet/ultraviolet"
"github.com/charmbracelet/x/ansi"
"github.com/charmbracelet/x/term"
)
@ -33,7 +35,7 @@ func (p *Program) initTerminal() error {
// Bubble Tea program.
func (p *Program) restoreTerminalState() error {
// Flush queued commands.
_ = p.flush()
p.keepWriteErr(p.flush())
return p.restoreInput()
}
@ -89,34 +91,145 @@ func (p *Program) initInputReader(cancel bool) error {
p.inputScanner = drv
p.readLoopDone = make(chan struct{})
go p.readLoop()
go p.readLoop(p.ctx, drv, p.readLoopDone, p.errs)
return nil
}
func (p *Program) readLoop() {
defer close(p.readLoopDone)
// readLoop streams input events to the program until ctx is done or reading
// fails. It takes the per-run state it uses as arguments rather than reading
// it from p: the loop can outlive [Program.shutdown], see
// [Program.shutdownInput], and must not race with a later run replacing it.
func (p *Program) readLoop(ctx context.Context, scanner *uv.TerminalReader, done chan struct{}, errs chan error) {
defer close(done)
if err := p.inputScanner.StreamEvents(p.ctx, p.msgs); err != nil {
if err := scanner.StreamEvents(ctx, p.msgs); err != nil {
select {
case <-p.ctx.Done():
case <-ctx.Done():
return
case p.errs <- err:
case errs <- err:
}
}
}
const inputReadLoopTimeout = 500 * time.Millisecond
// shutdownInput cancels input before closing the reader's resources. Keep the
// bounded shutdown for slow readers, but retain ownership of a reader that is
// still in use until its input loop has actually finished.
func (p *Program) shutdownInput() {
reader := p.cancelReader
if reader == nil {
return
}
// The reader is closed below, or later once its input loop finishes.
// Forget it so that a later run doesn't close it again: closing it closes
// raw file descriptors, and closing one twice can close an unrelated file
// that has since reused the number.
p.cancelReader = nil
if reader.Cancel() && p.readLoopDone != nil {
done := p.readLoopDone
timer := time.NewTimer(inputReadLoopTimeout)
defer timer.Stop()
select {
case <-done:
case <-timer.C:
go func() {
<-done
_ = reader.Close()
}()
return
}
}
_ = reader.Close()
}
// waitForReadLoop waits for the cancelReader to finish its read loop.
func (p *Program) waitForReadLoop() {
select {
case <-p.readLoopDone:
case <-time.After(500 * time.Millisecond): //nolint:mnd
case <-time.After(inputReadLoopTimeout):
// The read loop hangs, which means the input
// cancelReader's cancel function has returned true even
// though it was not able to cancel the read.
}
}
// 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)
}
}