Compare commits

...

2 commits

Author SHA1 Message Date
Ayman Bagabas
3dc93803f9
Merge branch 'nested-seqmsg' into v2-exp-nested-seqmsg 2025-08-07 11:33:28 -04:00
Ayman Bagabas
2a50aab42d
fix: handle nested SequenceMsg in event loop and use sync.WaitGroup for BatchMsg
This simplifies the handling of nested BatchMsg within sequenceMsg and ensures
that all commands in a BatchMsg are executed before proceeding.
It also replaces errgroup with sync.WaitGroup for better clarity and performance
when waiting for multiple goroutines to finish.

Fixes: https://github.com/charmbracelet/bubbletea/issues/680
Supersedes: https://github.com/charmbracelet/bubbletea/pull/843
2025-08-07 11:30:33 -04:00
2 changed files with 39 additions and 13 deletions

31
tea.go
View file

@ -32,7 +32,6 @@ import (
"github.com/charmbracelet/x/ansi"
"github.com/charmbracelet/x/term"
"github.com/lucasb-eyer/go-colorful"
"golang.org/x/sync/errgroup"
)
// ErrProgramPanic is returned by [Program.Run] when the program recovers from a panic.
@ -763,11 +762,10 @@ func (p *Program) eventLoop(model Model, cmds chan Cmd) (Model, error) {
case BatchMsg:
for _, cmd := range msg {
select {
case <-p.ctx.Done():
return model, nil
case cmds <- cmd:
if cmd == nil {
continue
}
go p.Send(cmd())
}
continue
@ -779,20 +777,27 @@ func (p *Program) eventLoop(model Model, cmds chan Cmd) (Model, error) {
continue
}
switch msg := cmd().(type) {
msg := cmd()
switch msg := msg.(type) {
case BatchMsg:
g, _ := errgroup.WithContext(p.ctx)
var wg sync.WaitGroup
for _, cmd := range msg {
g.Go(func() error {
if cmd == nil {
continue
}
wg.Add(1)
cmd := cmd
go func() {
defer wg.Done()
p.Send(cmd())
return nil
})
}()
}
_ = g.Wait() // wait for all commands from batch msg to finish
continue
wg.Wait()
case sequenceMsg:
for _, cmd := range msg {
if cmd == nil {
continue
}
p.Send(cmd())
}
default:

View file

@ -424,6 +424,27 @@ func TestTeaSequenceMsgWithBatchMsg(t *testing.T) {
}
}
func TestTeaNestedSequenceMsg(t *testing.T) {
var buf bytes.Buffer
var in bytes.Buffer
inc := func() Msg {
return incrementMsg{}
}
m := &testModel{}
p := NewProgram(m, WithInput(&in), WithOutput(&buf))
go p.Send(sequenceMsg{inc, Sequence(inc, inc), Quit})
if _, err := p.Run(); err != nil {
t.Fatal(err)
}
if m.counter.Load() != 3 {
t.Fatalf("counter should be 3, got %d", m.counter.Load())
}
}
func TestTeaSend(t *testing.T) {
var buf bytes.Buffer
var in bytes.Buffer