agent: /api/state lists running agents once in 3s, not with a pgrep each call

/api/state asks StaleCopies for every wired agent, and each pattern
started `pgrep -lf`, which walks every process's arguments. On a Mac
with ~1000 processes that was most of a state call: 45ms each, on every
page switch, save and GUI poll, with a pgrep child seen in 25 of 40
samples.

StaleCopies now reads runningLately: a pattern's listing is kept for
3s, with each process's start (not its age), so an age read later is
still right. A fresh listing (a restart waiting for its app to end)
replaces what was kept, so the look that finds the app gone is what the
next poll sees. A test that fakes running is asked each time. The
waits in apprestart still list now.

Run (mote, this tree):
- go vet ./internal/agent ./internal/gui; GOOS=linux and GOOS=windows
  go vet ./internal/agent: ok.
- TestRunningListedOnceInAWhile, TestRunningNeedsNoPs: ok.
  Broken by hand (every call lists): red, "listed 6 times in a row,
  want 1".
- go test ./internal/agent ./internal/provider: ok. ./internal/gui:
  only TestSettingsSaveKeepsWhatItDoesNotSend (#4514) and
  TestMainWindowCorners/macOS_26_SDK (#3949), both red on main too.

Real accounts (sandbox HOME from a copy of the live accounts, on this
Mac with its real Codex app, daemons and CLI running):
- /api/state, 10 calls after 200: v0.1.2519 43-60ms, this 8.4-21ms
  (twice each, alternating). pgrep children in 40 samples: 26 and 24
  before, 1 and 1 after.
- Each wired agent's stale copies (Codex: app, two daemons, cli, each
  with its start) are the same from both binaries, read twice 4s apart.

Not run: the full ./... suite; Linux and Windows runs of the agent
package (vet only).

Picked onto 9be72c948 (origin/main at push); not run again there.
This commit is contained in:
yetone
2026-11-01 10:32:21 +08:00
parent 9be72c9480
commit da0005df81
5 changed files with 131 additions and 5 deletions
+1 -1
View File
@@ -311,7 +311,7 @@ func (a *Agent) StaleCopies() []StaleCopy {
var out []StaleCopy
apps := map[string]int{}
for _, pat := range pats {
for _, p := range running(pat) {
for _, p := range runningLately(pat) {
if strings.Contains(p.cmd, others) && !strings.Contains(p.cmd, dir+"/") {
continue
}
+2 -2
View File
@@ -10,12 +10,12 @@ import (
"github.com/yetone/magpie/internal/proc"
)
// listRunning lists the processes a pgrep -f pattern matches, each with
// listRunningNow lists the processes a pgrep -f pattern matches, each with
// its command line from pgrep -lf and its start from the kernel. ps isn't
// run: on a Mac with a thousand processes and a busy CPU, ps -p over the
// 25 copies of claude a user keeps open took 1-2s, on every /api/state
// (#1962, #2341), where pgrep took 0.06s and a sysctl takes microseconds.
func listRunning(pat string) []runningProc {
func listRunningNow(pat string) []runningProc {
out, _ := proc.Command("pgrep", "-lf", pat).Output()
var ps []runningProc
now := time.Now()
+2 -2
View File
@@ -8,9 +8,9 @@ import (
"github.com/yetone/magpie/internal/proc"
)
// listRunning lists the processes a pgrep -f pattern matches, with how
// listRunningNow lists the processes a pgrep -f pattern matches, with how
// long each has run and its command line, from ps.
func listRunning(pat string) []runningProc {
func listRunningNow(pat string) []runningProc {
out, _ := proc.Command("pgrep", "-f", pat).Output()
pids := strings.Fields(string(out))
if len(pids) == 0 {
+76
View File
@@ -0,0 +1,76 @@
package agent
import (
"reflect"
"sync"
syncatomic "sync/atomic"
"time"
)
// listRunning lists the processes a pattern matches as they are now, for
// a caller that waits on them (a restart waiting for the app to end).
// What it finds replaces what runningLately kept, so a restart's last
// look, the one that finds the app gone, is what the next poll sees.
func listRunning(pat string) []runningProc {
ps := listRunningNow(pat)
lately.put(pat, time.Now(), ps)
return ps
}
// runningLately is running(pat) as it was up to runningFor ago.
// /api/state asks StaleCopies for every wired agent, and each pattern
// started a pgrep that walks every process's arguments: most of a state
// call's 45ms (9ms without it), on every page switch, save and poll.
// Each process's start is kept, not its age, so an age read later is
// still right.
const runningFor = 3 * time.Second
// listRuns counts the listings runningLately made (a test reads it).
var listRuns syncatomic.Uint64
var lately runningKept
type runningKept struct {
sync.Mutex
by map[string]keptRun
}
type keptRun struct {
at time.Time
start []time.Time
cmd []string
}
func (k *runningKept) put(pat string, now time.Time, ps []runningProc) {
r := keptRun{at: now}
for _, p := range ps {
r.start = append(r.start, now.Add(-p.up))
r.cmd = append(r.cmd, p.cmd)
}
k.Lock()
if k.by == nil {
k.by = map[string]keptRun{}
}
k.by[pat] = r
k.Unlock()
}
func runningLately(pat string) []runningProc {
// a test's own running is asked each time
if reflect.ValueOf(running).Pointer() != reflect.ValueOf(listRunning).Pointer() {
return running(pat)
}
now := time.Now()
lately.Lock()
r, ok := lately.by[pat]
lately.Unlock()
if !ok || now.Sub(r.at) >= runningFor || now.Before(r.at) {
listRuns.Add(1)
return listRunning(pat)
}
ps := make([]runningProc, len(r.cmd))
for i := range r.cmd {
ps[i] = runningProc{now.Sub(r.start[i]), r.cmd[i]}
}
return ps
}
+50
View File
@@ -0,0 +1,50 @@
package agent
import (
"testing"
"time"
)
// TestRunningListedOnceInAWhile: /api/state asked pgrep again on every
// call; a pattern asked again within runningFor is not listed again, an
// age read later has grown, a restart's own look replaces what was kept,
// and a test's fake is asked each time.
func TestRunningListedOnceInAWhile(t *testing.T) {
pat := `no-such-process-[0-9]{9}-lately`
runs := listRuns.Load()
for range 6 {
if ps := runningLately(pat); len(ps) != 0 {
t.Fatalf("found %+v", ps)
}
}
if n := listRuns.Load() - runs; n != 1 {
t.Fatalf("listed %d times in a row, want 1", n)
}
lately.put(pat, time.Now(), []runningProc{{10 * time.Second, "codex app-server"}})
ps := runningLately(pat)
if len(ps) != 1 || ps[0].cmd != "codex app-server" || ps[0].up < 10*time.Second || ps[0].up > 12*time.Second {
t.Fatalf("kept copy read back as %+v", ps)
}
// a restart waiting for the app to end looks now, and finds it gone
runs = listRuns.Load()
listRunning(pat)
if ps := runningLately(pat); len(ps) != 0 || listRuns.Load() != runs {
t.Fatalf("after a fresh look: %+v, %d listings", ps, listRuns.Load()-runs)
}
lately.put(pat, time.Now().Add(-runningFor-time.Second), []runningProc{{time.Second, "codex"}})
if ps := runningLately(pat); len(ps) != 0 || listRuns.Load() != runs+1 {
t.Fatalf("an old listing was used: %+v, %d listings", ps, listRuns.Load()-runs)
}
defer func(r func(string) []runningProc) { running = r }(running)
asked := 0
running = func(string) []runningProc { asked++; return nil }
runningLately(pat)
runningLately(pat)
if asked != 2 {
t.Fatalf("a test's running asked %d times, want 2", asked)
}
}