fix: return write errors from Program.Run (#1879)

Co-authored-by: Drew Smirnoff <drew@charm.land>
Signed-off-by: Drew Smirnoff <drew@charm.land>
This commit is contained in:
jane michelle arc 2026-11-20 15:52:39 +01:00 committed by GitHub
parent bc55190481
commit 9c6598361d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 115 additions and 6 deletions

43
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
@ -909,7 +911,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()
@ -1086,6 +1088,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
@ -1279,6 +1284,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
}
@ -1374,6 +1384,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) {
@ -1605,8 +1636,9 @@ func (p *Program) flushFrame() (drew, ok bool) {
}
}()
}
_ = p.flush()
drew, _ = p.renderer.flush(false)
p.keepWriteErr(p.flush())
drew, err := p.renderer.flush(false)
p.keepWriteErr(err)
return drew, true
}
@ -1621,8 +1653,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

@ -1043,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)
}
}

2
tty.go
View file

@ -34,7 +34,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()
}