From 6ba549b8708445d7d1f570d21d365e280bacad55 Mon Sep 17 00:00:00 2001 From: Andrej Antas Date: Wed, 25 Nov 2026 10:05:07 +0100 Subject: [PATCH] [FIX] Freezing on CPU loads --- cmd/margin-gui/agent.go | 28 +++++------- cmd/margin-gui/coalesce.go | 60 +++++++++++++++++++++++++ cmd/margin-gui/coalesce_test.go | 79 +++++++++++++++++++++++++++++++++ 3 files changed, 151 insertions(+), 16 deletions(-) create mode 100644 cmd/margin-gui/coalesce.go create mode 100644 cmd/margin-gui/coalesce_test.go diff --git a/cmd/margin-gui/agent.go b/cmd/margin-gui/agent.go index a225aa9..b8d2e97 100644 --- a/cmd/margin-gui/agent.go +++ b/cmd/margin-gui/agent.go @@ -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() diff --git a/cmd/margin-gui/coalesce.go b/cmd/margin-gui/coalesce.go new file mode 100644 index 0000000..7b11c69 --- /dev/null +++ b/cmd/margin-gui/coalesce.go @@ -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) + } +} diff --git a/cmd/margin-gui/coalesce_test.go b/cmd/margin-gui/coalesce_test.go new file mode 100644 index 0000000..792e807 --- /dev/null +++ b/cmd/margin-gui/coalesce_test.go @@ -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() +}