Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 12 additions & 16 deletions cmd/margin-gui/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -317,24 +317,20 @@ func (a *Agents) session(reviewPath string) *session {
}

func (a *Agents) pump(reviewPath string, s *session) {
buf := make([]byte, 32<<10)
for {
n, err := s.pty.Read(buf)
if n > 0 {
s.mu.Lock()
s.buf = append(s.buf, buf[:n]...)
if over := len(s.buf) - scrollback; over > 0 {
s.buf = s.buf[over:]
}
s.mu.Unlock()
if a.app != nil {
a.app.Event.Emit("agent:data", AgentData{Review: reviewPath, Data: base64.StdEncoding.EncodeToString(buf[:n])})
}
// Output goes to the window in batches, not one event per read: every event is run on the UI
// thread, and an agent redrawing its screen can read faster than a busy machine runs them,
// which leaves the window no time to handle input.
coalesce(s.pty, agentFrame, agentPending, func(chunk []byte) {
s.mu.Lock()
s.buf = append(s.buf, chunk...)
if over := len(s.buf) - scrollback; over > 0 {
s.buf = s.buf[over:]
}
if err != nil {
break
s.mu.Unlock()
if a.app != nil {
a.app.Event.Emit("agent:data", AgentData{Review: reviewPath, Data: base64.StdEncoding.EncodeToString(chunk)})
}
}
})
waitErr := s.cmd.Wait()
_ = s.pty.Close()
a.mu.Lock()
Expand Down
60 changes: 60 additions & 0 deletions cmd/margin-gui/coalesce.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package main

import (
"io"
"sync"
"time"
)

const (
// agentFrame is the shortest gap between two batches of agent output sent to the window.
agentFrame = 33 * time.Millisecond
// agentPending is how much unsent output may wait before reading from the agent pauses.
agentPending = 1 << 20
)

// coalesce reads r until it fails and hands what it read to flush in batches: the first bytes
// after a quiet spell at once, then whatever arrived meanwhile at most once per every. Reading
// pauses while limit bytes wait to be flushed. Everything read is flushed before coalesce returns.
func coalesce(r io.Reader, every time.Duration, limit int, flush func([]byte)) {
var (
mu sync.Mutex
cond = sync.NewCond(&mu)
pending []byte
done bool
)
go func() {
buf := make([]byte, 32<<10)
for {
n, err := r.Read(buf)
mu.Lock()
for len(pending) >= limit {
cond.Wait()
}
pending = append(pending, buf[:n]...)
done = err != nil
cond.Broadcast()
mu.Unlock()
if err != nil {
return
}
}
}()
for {
mu.Lock()
for len(pending) == 0 && !done {
cond.Wait()
}
chunk, finished := pending, done
pending = nil
cond.Broadcast()
mu.Unlock()
if len(chunk) > 0 {
flush(chunk)
}
if finished {
return
}
time.Sleep(every)
}
}
79 changes: 79 additions & 0 deletions cmd/margin-gui/coalesce_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
package main

import (
"bytes"
"io"
"testing"
"time"
)

// A producer writing many small pieces reaches the window in a few batches, in order and complete.
func TestCoalesceBatchesSmallWrites(t *testing.T) {
pr, pw := io.Pipe()
var want bytes.Buffer
go func() {
for i := 0; i < 2000; i++ {
piece := []byte{byte('a' + i%26)}
want.Write(piece)
pw.Write(piece)
if i%100 == 0 {
time.Sleep(time.Millisecond)
}
}
pw.Close()
}()
var got bytes.Buffer
flushes := 0
coalesce(pr, 20*time.Millisecond, 1<<20, func(b []byte) {
flushes++
got.Write(b)
})
if !bytes.Equal(got.Bytes(), want.Bytes()) {
t.Fatalf("got %d bytes, want %d, or out of order", got.Len(), want.Len())
}
if flushes > 50 {
t.Fatalf("2000 writes took %d flushes; they should be batched", flushes)
}
}

// After a quiet spell, output (an echoed key) is not held back.
func TestCoalesceFlushesFirstBytesAtOnce(t *testing.T) {
pr, pw := io.Pipe()
got := make(chan time.Time, 4)
go coalesce(pr, time.Hour, 1<<20, func([]byte) { got <- time.Now() })
start := time.Now()
pw.Write([]byte("x"))
select {
case at := <-got:
if d := at.Sub(start); d > 100*time.Millisecond {
t.Fatalf("first bytes took %v", d)
}
case <-time.After(time.Second):
t.Fatal("first bytes never flushed")
}
pw.Close()
}

// A slow window makes reading pause instead of buffering without bound.
func TestCoalescePausesReadingWhenWindowIsBehind(t *testing.T) {
pr, pw := io.Pipe()
release := make(chan struct{})
go coalesce(pr, 0, 8, func([]byte) { <-release })
pw.Write(make([]byte, 8)) // flushed, flush blocks
pw.Write(make([]byte, 8)) // pending reaches limit
pw.Write(make([]byte, 8)) // read, but held until there is room
wrote := make(chan struct{})
go func() { pw.Write(make([]byte, 8)); close(wrote) }()
select {
case <-wrote:
t.Fatal("reading went on while the window was behind")
case <-time.After(100 * time.Millisecond):
}
close(release)
select {
case <-wrote:
case <-time.After(time.Second):
t.Fatal("reading did not resume")
}
pw.Close()
}
Loading