From bda69db0eed6fd3ac2b2589ade010a434ef5ba58 Mon Sep 17 00:00:00 2001 From: yetone Date: Fri, 13 Nov 2026 21:09:38 +0800 Subject: [PATCH] awake: the gateway's process keeps macOS from App Napping it (#6261) ChasLui (#6261, and on X): with the screen locked, every request after a quiet while got the 30s pre-routing 504 from the menu-bar app (160 in one night). The app serves the gateway in its own process, and a locked screen leaves it a background app, which macOS App Naps: priority band 4, timers throttled, so parsing the 6MB catalog took ~800ms instead of 50ms and requests queued behind it past unroutedUnknown. Keep-awake (caffeinate) holds sleep off, not App Nap. ListenAndServe now holds an NSProcessInfo activity for as long as it serves (awake.NoNap): NSActivityUserInitiatedAllowingIdleSystemSleep, Apple's App Nap opt-out without the idle-sleep hold. Held for the whole life of the gateway, not only while a request is in flight: the request that suffered is the first one after an idle stretch, which arrives at an already napped process. NSActivityLatencyCritical is left out: it is timer precision for audio/video, at an energy cost, and App Nap's throttling is what the reporter measured. Sleep is still Keep's alone, only while the user turned keep-awake on. The command-line magpie is built without cgo and runs from a terminal or launchd, where App Nap doesn't reach it; there NoNap does nothing. Run: - Real App Nap on mote (macOS 27.2): two copies of a throwaway AppKit .app (regular policy, launched hidden with open -j -g), one holding NoNap. Without it: runningboardd "Set AppNap state: active:Y priority:Y timer:Tier5" and ps pri=4 (42 of 42 samples once napped). With it: "active:N socket:N priority:N timer:Tier0" and pri=20, never 4. pmset -g assertions listed nothing for either pid. - TestNoNapLetsTheMacSleep (darwin+cgo): holds NoNap, reads pmset -g assertions, fails on a Prevent* assertion of its own pid. Broken by hand with NSActivityUserInitiated: red ("PreventUserIdleSystemSleep named: magpie serves the gateway ..."); green with the shipped option. - go vet (darwin), GOOS=linux and GOOS=windows go vet -tags nogui of awake, daemon, cli, gateway; CGO_ENABLED=0 nogui build; gofmt -l. - go test -count=1 -timeout 45m . ./internal/{awake,daemon,cli,gateway, proc,update,masking,plugin} on mote: all ok (gateway 908s, plugin 159s, cli 52s) at base 7eecbcc56; at the pushed head (rebased on 459d668b3, which touches none of these files) build, gofmt, linux and windows vet, and awake, daemon, cli tests ok again Not tried: the real magpie.app with a real screen lock. mote and mica were running other sessions' AppKit and simulator tests, which a lock would break; the hidden-app case above is the same App Nap path (runningboardd's AppNap state), reached without the lock. The full suite: both machines' suite.lock queues were hours deep. --- internal/awake/awake.go | 15 +++++++++++ internal/awake/nap_darwin.go | 44 +++++++++++++++++++++++++++++++ internal/awake/nap_darwin_test.go | 37 ++++++++++++++++++++++++++ internal/awake/nap_other.go | 8 ++++++ internal/gateway/gateway.go | 2 ++ 5 files changed, 106 insertions(+) create mode 100644 internal/awake/nap_darwin.go create mode 100644 internal/awake/nap_darwin_test.go create mode 100644 internal/awake/nap_other.go diff --git a/internal/awake/awake.go b/internal/awake/awake.go index 61688ebc3..566c1427c 100644 --- a/internal/awake/awake.go +++ b/internal/awake/awake.go @@ -114,3 +114,18 @@ func Keep(ctx context.Context, level func() Level, state func() State) { } } } + +// NoNap keeps macOS from App Napping the magpie serving the gateway until +// the release it returns is called (#6261, ChasLui). The menu-bar app +// serves it in its own process, and with the screen locked macOS naps the +// app as one in the background: its priority falls to 4 and its timers +// wait, so the first request after a quiet while spent its 30 seconds +// before routing and got a 504. An agent waiting on the gateway is the +// user's work, so the activity says it is user initiated, as Apple's App +// Nap opt-out does. It lets the system sleep when idle, as it did: holding +// that off is Keep's, and only while the user asked for it. Nor does it +// ask for NSActivityLatencyCritical's timer precision, which is for audio +// and video; a request needs the process run, not run to the millisecond. +func NoNap() func() { + return napOff("magpie serves the gateway agents send their requests to") +} diff --git a/internal/awake/nap_darwin.go b/internal/awake/nap_darwin.go new file mode 100644 index 000000000..af696b68c --- /dev/null +++ b/internal/awake/nap_darwin.go @@ -0,0 +1,44 @@ +//go:build darwin && cgo + +package awake + +/* +#cgo CFLAGS: -x objective-c +#cgo LDFLAGS: -framework Foundation +#import +#include + +// magpie_nap_off begins an activity that keeps App Nap off and lets the +// system sleep when idle; it returns the activity, retained, for +// magpie_nap_on to end. +static void *magpie_nap_off(const char *reason) { + @autoreleasepool { + id a = [[NSProcessInfo processInfo] + beginActivityWithOptions:NSActivityUserInitiatedAllowingIdleSystemSleep + reason:[NSString stringWithUTF8String:reason]]; + return (void *)[a retain]; + } +} + +static void magpie_nap_on(void *a) { + @autoreleasepool { + [[NSProcessInfo processInfo] endActivity:(id)a]; + [(id)a release]; + } +} +*/ +import "C" + +import ( + "sync" + "unsafe" +) + +// napOff begins the activity; the release it returns ends it, once. +func napOff(reason string) func() { + r := C.CString(reason) + defer C.free(unsafe.Pointer(r)) + a := C.magpie_nap_off(r) + var once sync.Once + return func() { once.Do(func() { C.magpie_nap_on(a) }) } +} diff --git a/internal/awake/nap_darwin_test.go b/internal/awake/nap_darwin_test.go new file mode 100644 index 000000000..d9c216d99 --- /dev/null +++ b/internal/awake/nap_darwin_test.go @@ -0,0 +1,37 @@ +//go:build darwin && cgo + +package awake + +import ( + "fmt" + "os" + "os/exec" + "strings" + "testing" +) + +// TestNoNapLetsTheMacSleep holds NoNap and reads the system's power +// assertions: none of this process's may hold sleep off, which is Keep's to +// do and only while the user asked for it (#6261). +func TestNoNapLetsTheMacSleep(t *testing.T) { + if _, err := os.Stat("/usr/bin/pmset"); err != nil { + t.Skip("no pmset:", err) + } + release := NoNap() + defer release() + out, err := exec.Command("/usr/bin/pmset", "-g", "assertions").CombinedOutput() + if err != nil { + t.Fatalf("pmset: %v\n%s", err, out) + } + mine := fmt.Sprintf("pid %d(", os.Getpid()) + for _, l := range strings.Split(string(out), "\n") { + if strings.Contains(l, mine) { + t.Logf("held: %s", strings.TrimSpace(l)) + if strings.Contains(l, "Prevent") { + t.Errorf("NoNap holds sleep off: %s", strings.TrimSpace(l)) + } + } + } + release() + release() // a second release does nothing +} diff --git a/internal/awake/nap_other.go b/internal/awake/nap_other.go new file mode 100644 index 000000000..d3cc97939 --- /dev/null +++ b/internal/awake/nap_other.go @@ -0,0 +1,8 @@ +//go:build !darwin || !cgo + +package awake + +// napOff does nothing: App Nap is a Mac's, and a Mac build without cgo is +// the command-line magpie, which runs under launchd or a terminal, where +// App Nap doesn't reach it. +func napOff(string) func() { return func() {} } diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index c687c0478..88eb862b0 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -914,6 +914,8 @@ func (s *Server) ListenAndServe(ctx context.Context) error { // and keeps the community's plugins up to date, noting others' updates, and the Bun they run on go plugin.KeepUpdated(ctx) go plugin.KeepBunUpdated(ctx) + // and keeps macOS from App Napping the process the agents wait on (#6261) + defer awake.NoNap()() // and, when settings say to, keeps the computer awake while agents work go awake.Keep(ctx, func() awake.Level { switch set := settings.Load(); {