diff --git a/internal/gui/api.go b/internal/gui/api.go index 0839ec3ce..97891acad 100644 --- a/internal/gui/api.go +++ b/internal/gui/api.go @@ -2746,8 +2746,15 @@ func writeJSON(rw http.ResponseWriter, v any) { // WebView2 is sent no If-None-Match, and Wails turns its 304 into a 505. // It returns the tag, or "" when v could not be written. func writeJSONSame(rw http.ResponseWriter, r *http.Request, v any) string { - var b bytes.Buffer - if err := json.NewEncoder(&b).Encode(v); err != nil { + return writeSame(rw, r, func(b *bytes.Buffer) error { return json.NewEncoder(b).Encode(v) }) +} + +// writeSame is writeJSONSame of the answer write puts in b, a kept buffer +// (answerBuffer). +func writeSame(rw http.ResponseWriter, r *http.Request, write func(b *bytes.Buffer) error) string { + b := answerBuffer() + defer keepAnswer(b) + if err := write(b); err != nil { fail(rw, err) return "" } @@ -2775,6 +2782,52 @@ var sentRows struct { const sentRowsKept = 4 +// answerBuffers are the buffers a long answer is written in, kept between +// polls: grown from nothing for each, the Sessions tab's list and its +// stats, ~6 MB each, were ~110 MB of 90 s of polls while an agent worked +// (#2278). They go answerLinger after the last answer. +var answerBuffers struct { + sync.Mutex + free []*bytes.Buffer + t *time.Timer +} + +const answerBuffersKept = 2 + +var answerLinger = 30 * time.Second + +// answerBuffer is a kept buffer, empty, or a new one +func answerBuffer() *bytes.Buffer { + answerBuffers.Lock() + defer answerBuffers.Unlock() + if n := len(answerBuffers.free); n > 0 { + b := answerBuffers.free[n-1] + answerBuffers.free = answerBuffers.free[:n-1] + return b + } + return new(bytes.Buffer) +} + +// keepAnswer puts b back once its answer is written: nothing reads it +// after, a ResponseWriter copies what it is given. +func keepAnswer(b *bytes.Buffer) { + b.Reset() + answerBuffers.Lock() + defer answerBuffers.Unlock() + if len(answerBuffers.free) < answerBuffersKept { + answerBuffers.free = append(answerBuffers.free, b) + } + if answerBuffers.t == nil { + answerBuffers.t = time.AfterFunc(answerLinger, func() { + answerBuffers.Lock() + answerBuffers.free = nil + answerBuffers.Unlock() + }) + return + } + answerBuffers.t.Reset(answerLinger) +} + // rowsSize is the size of the last answer writeJSONRows wrote of each key, // what the next one's buffer is made for. var rowsSize sync.Map @@ -2796,14 +2849,15 @@ func writeJSONRows[T any](rw http.ResponseWriter, r *http.Request, key string, r // the rows are written once, into the answer itself: each row's // Marshal, their Join and the answer's buffer were three copies of the // ~8 MB list a poll, and the buffer grew to it from nothing - var whole bytes.Buffer + whole := answerBuffer() + defer keepAnswer(whole) if n, ok := rowsSize.Load(key); ok { whole.Grow(n.(int) + n.(int)/8) } whole.WriteByte('{') whole.Write(k) whole.WriteString(":[") - enc := json.NewEncoder(&whole) + enc := json.NewEncoder(whole) ends := make([]int, len(rows)+1) ends[0] = whole.Len() for i := range rows { @@ -2828,7 +2882,7 @@ func writeJSONRows[T any](rw http.ResponseWriter, r *http.Request, key string, r } b.WriteByte('\n') } - end(&whole) + end(whole) rowsSize.Store(key, whole.Len()) all := whole.Bytes() raw := make([][]byte, len(rows)) diff --git a/internal/gui/sessions.go b/internal/gui/sessions.go index 45f3fa359..113a8bd44 100644 --- a/internal/gui/sessions.go +++ b/internal/gui/sessions.go @@ -189,10 +189,7 @@ func sessionRoutes(mux *http.ServeMux, w Windows) { rw.WriteHeader(http.StatusOK) return } - tag := writeJSONSame(rw, r, struct { - sessions.Stats - Agents map[string]string `json:"agents"` - }{st, agents}) + tag := writeSame(rw, r, func(b *bytes.Buffer) error { return statsAnswer(b, st, agents) }) if tag != "" { statsTags.Lock() if statsTags.m == nil || len(statsTags.m) >= statsMemoMost { @@ -789,3 +786,53 @@ func viaOf(x usage.ViaIndex, s sessions.Session) []usage.Via { } return nil } + +// statsAnswer writes the stats answer into b as an Encoder of +// struct{ sessions.Stats; Agents } does, its days one at a time: encoded +// whole, the Encoder's own buffer grew to the ~6 MB answer from nothing +// after each collection, ~200 MB of 90 s of polls while an agent worked +// (#2278). +func statsAnswer(b *bytes.Buffer, st sessions.Stats, agents map[string]string) error { + enc := json.NewEncoder(b) + // v as Marshal writes it: Encode ends it with a newline + put := func(v any) error { + if err := enc.Encode(v); err != nil { + return err + } + b.Truncate(b.Len() - 1) + return nil + } + b.WriteString(`{"from":`) + if err := put(st.From); err != nil { + return err + } + b.WriteString(`,"to":`) + if err := put(st.To); err != nil { + return err + } + b.WriteString(`,"days":`) + if st.Days == nil { + b.WriteString("null") + } else { + b.WriteByte('[') + for i := range st.Days { + if i > 0 { + b.WriteByte(',') + } + if err := put(&st.Days[i]); err != nil { + return err + } + } + b.WriteByte(']') + } + b.WriteString(`,"keys":`) + if err := put(st.Keys); err != nil { + return err + } + b.WriteString(`,"agents":`) + if err := put(agents); err != nil { + return err + } + b.WriteString("}\n") + return nil +} diff --git a/internal/gui/stats_answer_test.go b/internal/gui/stats_answer_test.go new file mode 100644 index 000000000..23b4b0ac1 --- /dev/null +++ b/internal/gui/stats_answer_test.go @@ -0,0 +1,74 @@ +package gui + +import ( + "bytes" + "encoding/json" + "net/http/httptest" + "testing" + + "github.com/yetone/magpie/internal/sessions" +) + +// statsAnswer writes the stats answer a day at a time, and the answer is +// byte for byte what the Encoder of the whole gave: the page's tag rests +// on those bytes. A field added to Stats shows here as a difference. +func TestStatsAnswerWritesWhatEncodeDid(t *testing.T) { + day := func(date string) sessions.Day { + return sessions.Day{Date: date, + Usage: []sessions.Usage{{Agent: "codex", Cwd: "/a&c", Model: "gpt
x", Tokens: sessions.Tokens{Input: 3, CacheWrite1h: 1}, Cost: 1e21, Priced: true}}, + Active: []sessions.Active{{Agent: "claude", Cwd: "引号\"", Seconds: 61, Hours: []int64{1, 2}}}} + } + for _, c := range []struct { + st sessions.Stats + agents map[string]string + }{ + {sessions.Stats{}, nil}, + {sessions.Stats{From: "2026-10-01", To: "2026-10-30", Days: []sessions.Day{}, Keys: []string{}}, map[string]string{}}, + {sessions.Stats{From: "<", To: "&", Days: []sessions.Day{day("2026-10-29"), {Date: "2026-10-30"}, day("x")}, Keys: []string{"codex:1", "a"}}, + } { + var want bytes.Buffer + if err := json.NewEncoder(&want).Encode(struct { + sessions.Stats + Agents map[string]string `json:"agents"` + }{c.st, c.agents}); err != nil { + t.Fatal(err) + } + var got bytes.Buffer + if err := statsAnswer(&got, c.st, c.agents); err != nil { + t.Fatal(err) + } + if !bytes.Equal(got.Bytes(), want.Bytes()) { + t.Fatalf("\n got %s\nwant %s", got.Bytes(), want.Bytes()) + } + } +} + +// A long answer is written into a buffer kept from the last, not one grown +// from nothing each poll. +func TestAnswerBufferKeptForTheNext(t *testing.T) { + answerBuffers.Lock() + answerBuffers.free = nil + answerBuffers.Unlock() + big := bytes.Repeat([]byte("x"), 1<<20) + w := httptest.NewRecorder() + writeSame(w, httptest.NewRequest("GET", "/x", nil), func(b *bytes.Buffer) error { + b.Write(big) + return nil + }) + if !bytes.Equal(w.Body.Bytes(), big) { + t.Fatalf("answer of %d bytes, want %d", w.Body.Len(), len(big)) + } + b := answerBuffer() + if b.Len() != 0 || b.Cap() < len(big) { + t.Fatalf("next buffer holds %d, room for %d: not the last answer's", b.Len(), b.Cap()) + } + keepAnswer(b) + rows := []rowsBufRow{{Name: string(big)}} + writeJSONRows(httptest.NewRecorder(), httptest.NewRequest("GET", "/x", nil), "kept-test", rows, struct{}{}) + answerBuffers.Lock() + n := len(answerBuffers.free) + answerBuffers.Unlock() + if n == 0 { + t.Fatal("writeJSONRows kept no buffer for the next answer") + } +}