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.
This commit is contained in:
yetone
2026-11-13 21:31:01 +08:00
parent 459d668b35
commit bda69db0ee
5 changed files with 106 additions and 0 deletions
+15
View File
@@ -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")
}
+44
View File
@@ -0,0 +1,44 @@
//go:build darwin && cgo
package awake
/*
#cgo CFLAGS: -x objective-c
#cgo LDFLAGS: -framework Foundation
#import <Foundation/Foundation.h>
#include <stdlib.h>
// 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) }) }
}
+37
View File
@@ -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
}
+8
View File
@@ -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() {} }
+2
View File
@@ -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(); {