gui: the Mac's menu bar icon keeps the place the user gave it across a quit (nb5p)

nb5p on Discord (macOS 26, Ice): after every update, and after a plain
quit and reopen, magpie's icon went back into Ice's hidden section however
often it was moved out. Alma has the same. Other apps keep their place.

Cause: AppKit keeps where a status item sits in the app's defaults by its
autosave name ("NSStatusItem Preferred Position Item-0"), and
-[NSStatusBar removeStatusItem:] deletes that key. Wails' cleanup removes
every tray as the app quits (application.go cleanup -> systray.destroy ->
systemTrayDestroy -> removeStatusItem:), so each quit forgot the place and
the next magpie's item started at the default spot, left of the others,
which in Ice is the hidden section. Apps that just exit keep the key.
(Electron's Tray, Alma's, removes its item the same way.) The autosave
name itself is stable: magpie makes one item, so it is Item-0 every
launch, under the same bundle id; it was never the identity that changed.

Fix: a shutdown task (h.app.OnShutdown, which Wails runs before it
removes trays) renames each of the app's status items to "magpie quitting
N" first, so the removal deletes a key nobody keeps and Item-0's place
stays. The items are found by their button's target, Wails'
StatusItemController, whose statusItem property is the item. Windows and
Linux get a no-op (trayshown_other.go). The handover's old magpie quits
through the same path, so a restart to update keeps the place too.

Evidence, on mote (macOS 27.2) with a 40-line Cocoa probe under its own
defaults domain: position seeded at 400, exit without removing -> key kept;
removeStatusItem on quit -> key gone, next launch has none; a fixed
autosave name "magpie" -> also gone on removal (so a fixed name alone
would not help); autosaveName changed just before removeStatusItem ->
key kept, next launch reads 400, and no key is written for the throwaway
name.

Run: gofmt -l internal/gui (clean); on mote at this head go vet
./internal/gui, GOOS=linux go vet -tags nogui, GOOS=windows go vet,
go build ./..., GOOS=windows go build ./..., GOOS=linux go build -tags
nogui ./... : ok. go test ./internal/gui on mote skipping the runAppKit
tests: everything passes except TestSettingsSaveKeepsWhatItDoesNotSend
(SearchAll, red on main, #4514) and TestMainWindowCorners (AppKit, killed:
mote has no Aqua session).

New test: TestQuitKeepsTheMenuBarIconsPlace (trayplace_darwin_test.go)
runs a Wails app twice under a sandboxed defaults home: Item-0's place
seeded, then tray.Destroy(), the call Wails' cleanup makes. Without
keepTrayPlace it must read "forgotten" (the cause), with it "kept".

Not tried: the new test and TestHandoverLeaves... hang over ssh on mote
(its console sits at the login window: no gui/501 launchd domain, no
Finder or Dock), and this Mac is the user's live one, so the AppKit test
has not run anywhere yet; macOS CI runs it. No real two-launch check with
the built app and Ice, for the same reason. The full suite was not run
(two other sessions' gateway suites were on mote).
This commit is contained in:
yetone
2026-10-31 16:53:00 +08:00
parent 4d6bd346ce
commit 6893cfbe34
4 changed files with 172 additions and 0 deletions
+3
View File
@@ -573,6 +573,9 @@ func Run(version string, showMain bool, link string) error {
}
h.tray.SetMenu(menu)
h.tray.AttachWindow(h.panel).WindowOffset(6)
// before Wails removes the item as the app quits, which would forget
// where the user put the icon (trayshown_darwin.go; nothing elsewhere)
h.app.OnShutdown(func() { keepTrayPlace() })
// a Mac that handed the gateway to the new version (handover.go)
// leaves the menu bar to it while it finishes its requests: one bird
if runtime.GOOS == "darwin" {
+91
View File
@@ -0,0 +1,91 @@
//go:build darwin && cgo && !nogui
package gui
import (
"fmt"
"net/http"
"os"
"strings"
"testing"
"time"
"github.com/wailsapp/wails/v3/pkg/application"
"github.com/wailsapp/wails/v3/pkg/events"
)
// nb5p on Discord (macOS 26): Ice put magpie's menu bar icon back in its
// hidden section after every update, and after a plain quit and reopen,
// however often it was moved out. AppKit keeps where the item sits by its
// autosave name ("NSStatusItem Preferred Position Item-0"), and Wails
// removes the item as the app quits, which forgets it: the next magpie's
// item started at the default spot. Renamed first, the removal forgets
// nothing kept.
func TestQuitKeepsTheMenuBarIconsPlace(t *testing.T) {
for _, c := range []struct{ keep, want string }{
{"0", "tray place: forgotten"}, // the cause, without the fix
{"1", "tray place: kept"},
} {
out, err := runAppKit(t, 30*time.Second, []string{"MAGPIE_TEST_TRAY_PLACE=" + c.keep})
if err != nil || !strings.Contains(string(out), c.want) {
t.Fatalf("keep %s: want %q: %v\n%s", c.keep, c.want, err, out)
}
}
}
func init() {
keep := os.Getenv("MAGPIE_TEST_TRAY_PLACE")
if keep == "" {
return
}
fail := func(format string, a ...any) {
fmt.Printf("tray place: "+format+"\n", a...)
os.Exit(1)
}
// where the user put it, the launch before
setTrayPlace("Item-0", 400)
app := application.New(application.Options{
Name: "magpie tray place regression",
Mac: application.MacOptions{ActivationPolicy: application.ActivationPolicyAccessory},
Assets: application.AssetOptions{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html")
fmt.Fprint(w, `<p>magpie</p>`)
})},
})
tray := app.SystemTray.New()
tray.SetTemplateIcon(trayIcon)
app.Event.OnApplicationEvent(events.Common.ApplicationStarted, func(*application.ApplicationEvent) {
go func() {
for deadline := time.Now().Add(5 * time.Second); trayItems() == 0; {
if time.Now().After(deadline) {
fail("no status item came up")
}
time.Sleep(50 * time.Millisecond)
}
// AppKit may move it to where the item really is; kept is
// what counts
if _, ok := trayPlace("Item-0"); !ok {
fail("the place set before the start is gone")
}
// what the app's shutdown does: magpie's task, then Wails'
// removal of every tray
if keep == "1" {
if n := keepTrayPlace(); n != 1 {
fail("kept the place of %d items, not 1", n)
}
}
tray.Destroy()
mainSettled()
if x, ok := trayPlace("Item-0"); ok {
fmt.Printf("tray place: kept (%v)\n", x)
} else {
fmt.Println("tray place: forgotten")
}
os.Exit(0)
}()
})
if err := app.Run(); err != nil {
fail("run: %v", err)
}
os.Exit(1)
}
+77
View File
@@ -56,6 +56,60 @@ static void mpSetFlag(const char *k) {
[d synchronize];
}
// AppKit keeps where a status item sits ("NSStatusItem Preferred Position
// Item-0", where the user or a menu bar manager like Ice put it) by its
// autosave name, and removeStatusItem: forgets it. Wails removes the item
// as the app quits, so every quit, and every restart to update, put the
// icon back at the default spot, left of the others: in Ice's hidden
// section (nb5p). Under a name of its own the removal forgets nothing that
// is kept. Every item of this app's, by its Wails controller (the button's
// target); how many there are, renamed if rename.
static int mpTrayItemsNow(int rename) {
int n = 0;
for (NSWindow *w in NSApp.windows) {
NSMutableArray *views = [NSMutableArray arrayWithObject:w.contentView ?: [NSNull null]];
while (views.count) {
id v = views.lastObject;
[views removeLastObject];
if (![v isKindOfClass:[NSView class]]) continue;
[views addObjectsFromArray:[v subviews]];
if (![v isKindOfClass:[NSStatusBarButton class]]) continue;
id t = [(NSStatusBarButton *)v target];
if (![t respondsToSelector:@selector(statusItem)]) continue;
id it = [t performSelector:@selector(statusItem)];
if (![it isKindOfClass:[NSStatusItem class]]) continue;
if (rename) ((NSStatusItem *)it).autosaveName = [NSString stringWithFormat:@"magpie quitting %d", n];
n++;
}
}
return n;
}
static int mpTrayItems(int rename) {
if ([NSThread isMainThread]) return mpTrayItemsNow(rename);
__block int n = 0;
dispatch_sync(dispatch_get_main_queue(), ^{ n = mpTrayItemsNow(rename); });
return n;
}
static NSString *mpPlaceKey(const char *name) {
return [@"NSStatusItem Preferred Position " stringByAppendingString:[NSString stringWithUTF8String:name]];
}
// Where AppKit keeps the item named name, -1 for nowhere.
static double mpTrayPlace(const char *name) {
NSUserDefaults *d = [NSUserDefaults standardUserDefaults];
[d synchronize];
id v = [[d persistentDomainForName:[[NSBundle mainBundle] bundleIdentifier] ?: [[NSProcessInfo processInfo] processName]] objectForKey:mpPlaceKey(name)];
return [v respondsToSelector:@selector(doubleValue)] ? [v doubleValue] : -1;
}
static void mpSetTrayPlace(const char *name, double x) {
NSUserDefaults *d = [NSUserDefaults standardUserDefaults];
[d setDouble:x forKey:mpPlaceKey(name)];
[d synchronize];
}
// Waits, off the main thread, for what is queued on it to have run.
static void mpMainSettled(void) {
dispatch_sync(dispatch_get_main_queue(), ^{});
@@ -76,6 +130,29 @@ func forgetTrayHidden() int { return int(C.mpForgetHidden()) }
// what is queued on it, the tray's Hide among them.
func forgetTrayHiddenLater() { C.mpForgetHiddenLater() }
// keepTrayPlace has the menu bar icon's place outlive this magpie: run as
// the app quits, before Wails removes the item, which would forget where
// the user put it (mpKeepTrayPlaceNow). How many items it kept the place of.
func keepTrayPlace() int { return int(C.mpTrayItems(1)) }
// trayItems is how many status items this app has up.
func trayItems() int { return int(C.mpTrayItems(0)) }
// trayPlace is where AppKit keeps the status item named name ("Item-0"),
// and whether it keeps one.
func trayPlace(name string) (float64, bool) {
k := C.CString(name)
defer C.free(unsafe.Pointer(k))
x := float64(C.mpTrayPlace(k))
return x, x >= 0
}
func setTrayPlace(name string, x float64) {
k := C.CString(name)
defer C.free(unsafe.Pointer(k))
C.mpSetTrayPlace(k, C.double(x))
}
// mainSettled waits for the main thread to run what is queued on it. Not
// on the main thread.
func mainSettled() { C.mpMainSettled() }
+1
View File
@@ -6,3 +6,4 @@ package gui
func forgetTrayHidden() int { return 0 }
func forgetTrayHiddenLater() {}
func bringTrayBack() (stillHidden bool) { return false }
func keepTrayPlace() int { return 0 }