From 9c6598361dc9d09f6116f0c67d5de781bfe36a16 Mon Sep 17 00:00:00 2001 From: jane michelle arc Date: Fri, 20 Nov 2026 15:52:39 +0100 Subject: [PATCH] fix: return write errors from Program.Run (#1879) Co-authored-by: Drew Smirnoff Signed-off-by: Drew Smirnoff --- tea.go | 43 ++++++++++++++++++++++++++---- tea_test.go | 76 +++++++++++++++++++++++++++++++++++++++++++++++++++++ tty.go | 2 +- 3 files changed, 115 insertions(+), 6 deletions(-) diff --git a/tea.go b/tea.go index ff8a1317..a7e0312f 100644 --- a/tea.go +++ b/tea.go @@ -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()) } diff --git a/tea_test.go b/tea_test.go index c9375ea6..ae20a508 100644 --- a/tea_test.go +++ b/tea_test.go @@ -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) + } +} diff --git a/tty.go b/tty.go index 7c7ec62e..d8db5974 100644 --- a/tty.go +++ b/tty.go @@ -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() }