Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

autostart, gui: Open at login says when the Mac's own switch for it is off (#2120)

yetone5e30d5b5ae3c
diff --git a/docs/subsystems/gui-shell.md b/docs/subsystems/gui-shell.md
index 563b7412e..4c71707ec 100644
--- a/docs/subsystems/gui-shell.md
+++ b/docs/subsystems/gui-shell.md
@@ -349,7 +349,7 @@ covers it in both engines, every language and a narrow window.
### Shared UI rules
-- Settings → General is laid out as macOS System Settings is (1ooogle on X): a row says its name alone when that says enough (Appearance, Colorblind mode, Language, Text size, the fonts, the tray click, the Codex model rows, Open at login, Show in Dock), and keeps one short line where the setting isn't clear from its name or has a consequence (Long conversations, Lightweight mode, Prevent sleep, Session terminal, Codex subagents). A font row's line shows only while its fonts load or fail; the text size keys are the choices' tooltip, and Colorblind mode's note is its Off/On control's (`#colorblindSegs`). Colorblind mode (`settings.Colorblind`, `data-colorblind="1"` on `:root`, #2073) switches the chart series (`--c1`…`--c7`) in both light and dark themes to an Okabe–Ito palette where adjacent series differ in hue and lightness. On a quota curve each window (`data-series`, its index mod 7, set by `drawQuotaPlot` and `quotaCurve`'s legend only) gets a dash of its own on `path.qc-line`, its legend key shows a sample of that line (`.qc-sample`) for the dot, and the even paces (`line.qc-even`) are dotted; the curve's tooltip says so. The balance curve sets no `data-series` and keeps its solid line, dashed fit and dot. The Context tab's "good" grade, which takes `--c2` as a colour rather than a series, keeps a blue (`--c1`). Language is one menu button showing the language picked, opened in the app's menu (`renderLangPick`). See `settings-general.test.cjs` and `quota-curve.test.cjs`.
+- Settings → General is laid out as macOS System Settings is (1ooogle on X): a row says its name alone when that says enough (Appearance, Colorblind mode, Language, Text size, the fonts, the tray click, the Codex model rows, Open at login, Show in Dock), and keeps one short line where the setting isn't clear from its name or has a consequence (Long conversations, Lightweight mode, Prevent sleep, Session terminal, Codex subagents). A font row's line shows only while its fonts load or fail; the text size keys are the choices' tooltip, and Colorblind mode's note is its Off/On control's (`#colorblindSegs`). Colorblind mode (`settings.Colorblind`, `data-colorblind="1"` on `:root`, #2073) switches the chart series (`--c1`…`--c7`) in both light and dark themes to an Okabe–Ito palette where adjacent series differ in hue and lightness. On a quota curve each window (`data-series`, its index mod 7, set by `drawQuotaPlot` and `quotaCurve`'s legend only) gets a dash of its own on `path.qc-line`, its legend key shows a sample of that line (`.qc-sample`) for the dot, and the even paces (`line.qc-even`) are dotted; the curve's tooltip says so. The balance curve sets no `data-series` and keeps its solid line, dashed fit and dot. The Context tab's "good" grade, which takes `--c2` as a colour rather than a series, keeps a blue (`--c1`). Language is one menu button showing the language picked, opened in the app's menu (`renderLangPick`). See `settings-general.test.cjs` and `quota-curve.test.cjs`. Open at login reads `autostart.Enabled`, which on macOS 13 and later also asks Background Task Management about magpie's launch agent (`SMAppService.statusForLegacyURL:`, matched by the plist's Label, not its path); a record the user switched off in System Settings › General › Login Items reads as needing allowing, and the row keeps On with one line saying so and a button that opens Login Items (`/api/open` allows that one `x-apple.systempreferences` URL). The status read again when the window comes back to the front clears the line. On macOS 12, in a build without cgo, or when the system can't be asked, the plist alone decides, as before (#2120, `login-allow.test.cjs`, `login_allow_test.go`).
- Settings' search-provider picker offers **Off**, saved as `searcher: "off"`. Its help explains API-only search and suppresses provider fallback/own-search hints while off; the search priority row is hidden because no provider competes with the APIs. See [gateway search behavior](gateway-routing.md#turning-provider-search-off), [`renderSearcher`](../../internal/gui/assets/app.js), `TestSettingsSearchProviderOff` and `searcher-pick.test.cjs`.
- Settings' search APIs are asked in their listed order: each API's row (with its keys' row) is dragged as one, or moved with Alt+↑/↓, and has a switch that turns it off without removing its key (#2286). See [the search APIs' order](gateway-routing.md#the-search-apis-order-and-one-switched-off), `searchArrange` in [`app.js`](../../internal/gui/assets/app.js) and `search-order.test.cjs`.
- Settings' Search APIs add row has a base URL field under the key for every API (#1580): the vendor's own address is its placeholder, picking an API already added fills in its saved URL so a new key alone keeps it, and Add with no key changes only the URL. See [a search API's base URL](gateway-routing.md#a-search-apis-base-url), [`renderSearch`](../../internal/gui/assets/app.js) and `search-api.test.cjs`.
diff --git a/internal/autostart/autostart.go b/internal/autostart/autostart.go
index 5cbb147ab..2ca573d95 100644
--- a/internal/autostart/autostart.go
+++ b/internal/autostart/autostart.go
@@ -16,8 +16,37 @@ import (
// Arg is what magpie is started with at login: the tray, no window.
const Arg = "tray"
-// Enabled reports whether magpie opens at login.
-func Enabled() bool { return enabled() }
+// State is whether magpie opens at login, as the system will act on it.
+type State string
+
+const (
+ // Off: no record, so nothing opens magpie at login.
+ Off State = "off"
+ // On: the record is there, and nothing the system says holds it back.
+ On State = "on"
+ // NeedsAllowing: the record is there, but the user switched it off in
+ // the system's own settings (on the Mac, System Settings › General ›
+ // Login Items › Allow in the Background), so it opens nothing until
+ // it is allowed there again; writing the record anew doesn't do that.
+ NeedsAllowing State = "allow"
+)
+
+// LoginItemsURL opens System Settings' Login Items pane, where a record
+// that NeedsAllowing is allowed again.
+const LoginItemsURL = "x-apple.systempreferences:com.apple.LoginItems-Settings.extension"
+
+// Enabled reports whether magpie opens at login. A system that can't be
+// asked, or that answers something else, is not taken for a no: the
+// record's own word stands (On).
+func Enabled() State {
+ if !enabled() {
+ return Off
+ }
+ if heldBack() {
+ return NeedsAllowing
+ }
+ return On
+}
// Set has magpie open at login, or not, as this copy of it.
func Set(on bool) error {
diff --git a/internal/autostart/autostart_android.go b/internal/autostart/autostart_android.go
index 1ea69cfe0..a1aea3c79 100644
--- a/internal/autostart/autostart_android.go
+++ b/internal/autostart/autostart_android.go
@@ -41,3 +41,6 @@ func disable() error {
}
func refresh() error { return nil }
+
+// heldBack: nothing here is switched off apart from the record itself
+func heldBack() bool { return false }
diff --git a/internal/autostart/autostart_android_test.go b/internal/autostart/autostart_android_test.go
index 6c10de4e3..c27110694 100644
--- a/internal/autostart/autostart_android_test.go
+++ b/internal/autostart/autostart_android_test.go
@@ -25,13 +25,13 @@ func TestBootScript(t *testing.T) {
if err := os.Chmod(record(), 0o600); err != nil {
t.Fatal(err)
}
- if Enabled() {
+ if Enabled() != Off {
t.Fatal("non-executable script reported as enabled")
}
if err := enable(exe); err != nil {
t.Fatal(err)
}
- if !Enabled() {
+ if Enabled() == Off {
t.Fatal("enable did not restore executable permission")
}
if err := exec.Command("/system/bin/sh", record()).Run(); err != nil {
diff --git a/internal/autostart/autostart_darwin.go b/internal/autostart/autostart_darwin.go
index 422b0d774..1671afec1 100644
--- a/internal/autostart/autostart_darwin.go
+++ b/internal/autostart/autostart_darwin.go
@@ -28,6 +28,31 @@ func enabled() bool {
return err == nil && ourLabel.Match(b) && program.Match(b)
}
+// What ServiceManagement's statusForLegacyURL: says of a launch agent
+// (SMAppServiceStatus). Background Task Management keeps it, by the
+// plist's Label, wherever the file is: switched off under Login Items ›
+// Allow in the Background, it is requiresApproval, and stays so when the
+// plist is written anew, or removed and written again. launchctl
+// print-disabled doesn't follow that switch (it went on saying enabled,
+// macOS 26.2), so it isn't asked.
+const (
+ smNotRegistered = 0
+ smEnabled = 1
+ smRequiresApproval = 2
+ smNotFound = 3
+ // the system couldn't be asked: before macOS 13, or a build without cgo
+ smUnknown = -1
+)
+
+// legacyStatus asks the system about the launch agent at path. A var for
+// the tests; a build without cgo can't ask.
+var legacyStatus = func(path string) int { return smUnknown }
+
+// heldBack: the system says the user switched the launch agent off. Only
+// requiresApproval says so; not registered yet, not found, or no answer
+// leave the record's own word.
+func heldBack() bool { return legacyStatus(record()) == smRequiresApproval }
+
// a launch agent the system loads at the next login: the app itself, run
// once, not kept alive — quitting magpie quits it until then
func enable(exe string) error {
diff --git a/internal/autostart/autostart_darwin_test.go b/internal/autostart/autostart_darwin_test.go
index c1d9c4eda..495cba573 100644
--- a/internal/autostart/autostart_darwin_test.go
+++ b/internal/autostart/autostart_darwin_test.go
@@ -51,7 +51,7 @@ func TestRefreshOlderLaunchAgent(t *testing.T) {
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("USERPROFILE", home)
- if err := Refresh(); err != nil || Enabled() {
+ if err := Refresh(); err != nil || Enabled() != Off {
t.Fatalf("Refresh turned Open at login on: %v", err)
}
if _, err := os.Stat(filepath.Join(home, "Library")); !os.IsNotExist(err) {
@@ -176,7 +176,7 @@ func TestSetThenTruncatedRecordReadsAsOff(t *testing.T) {
if err := Set(true); err != nil {
t.Fatal(err)
}
- if !Enabled() {
+ if Enabled() == Off {
t.Fatal("not on after Set(true)")
}
p := record()
@@ -190,13 +190,13 @@ func TestSetThenTruncatedRecordReadsAsOff(t *testing.T) {
if err := os.WriteFile(p, head, 0o644); err != nil {
t.Fatal(err)
}
- if Enabled() {
+ if Enabled() != Off {
t.Errorf("a launch agent with no ProgramArguments reads as on:\n%s", head)
}
if err := os.WriteFile(p, nil, 0o644); err != nil {
t.Fatal(err)
}
- if Enabled() {
+ if Enabled() != Off {
t.Error("an empty launch agent reads as on")
}
// a program named as nothing is no program to run either, and launchd
@@ -205,7 +205,93 @@ func TestSetThenTruncatedRecordReadsAsOff(t *testing.T) {
if err := os.WriteFile(p, []byte(empty), 0o644); err != nil {
t.Fatal(err)
}
- if Enabled() {
+ if Enabled() != Off {
t.Errorf("a launch agent with no program reads as on:\n%s", empty)
}
}
+
+// Switched off under System Settings › Login Items › Allow in the
+// Background, the launch agent stays where it was and opens nothing, so
+// Open at login says it needs allowing, not on (#2120). Only the system's
+// requiresApproval says that: no answer, or any other, leaves the record's
+// word, and no record is off whatever the system says.
+func TestEnabledFollowsTheSystemsSwitch(t *testing.T) {
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ t.Setenv("USERPROFILE", home)
+ prev := legacyStatus
+ t.Cleanup(func() { legacyStatus = prev })
+ var asked string
+ status := smRequiresApproval
+ legacyStatus = func(p string) int { asked = p; return status }
+
+ if got := Enabled(); got != Off {
+ t.Fatalf("no launch agent reads %q, want off", got)
+ }
+ if err := Set(true); err != nil {
+ t.Fatal(err)
+ }
+ if got := Enabled(); got != NeedsAllowing {
+ t.Fatalf("switched off in System Settings reads %q, want %q", got, NeedsAllowing)
+ }
+ if asked != record() {
+ t.Fatalf("asked the system about %q, not the launch agent %q", asked, record())
+ }
+ for _, s := range []int{smEnabled, smNotRegistered, smNotFound, smUnknown, 7} {
+ status = s
+ if got := Enabled(); got != On {
+ t.Errorf("the system answering %d reads %q, want on", s, got)
+ }
+ }
+ status = smRequiresApproval
+ if err := Set(false); err != nil {
+ t.Fatal(err)
+ }
+ if got := Enabled(); got != Off {
+ t.Fatalf("turned off reads %q", got)
+ }
+}
+
+// The system's switch is kept by the launch agent's label, wherever its
+// plist is: a test's record under a sandbox home is com.yetone.magpie
+// too, and the system would answer for the user's own. The tests ask a
+// stand-in that knows nothing; askSystem is the real question.
+var askSystem func(string) int
+
+func keepToTheSandbox() {
+ askSystem = legacyStatus
+ legacyStatus = func(string) int { return smUnknown }
+}
+
+// The real question reaches ServiceManagement: a launch agent under a
+// label Background Task Management has never seen is notFound, and a path
+// with no file at all is notRegistered. The user's own label is never
+// asked about.
+func TestLegacyStatusAsksTheSystem(t *testing.T) {
+ out, err := exec.Command("sw_vers", "-productVersion").Output()
+ if err != nil {
+ t.Skip("no sw_vers")
+ }
+ dir := t.TempDir()
+ p := filepath.Join(dir, "com.yetone.magpie-test.plist")
+ b := strings.Replace(string(plist("/usr/bin/true")), "<string>"+label+"</string>", "<string>com.yetone.magpie-test-"+filepath.Base(dir)+"</string>", 1)
+ if err := os.WriteFile(p, []byte(b), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ got := askSystem(p)
+ if major := strings.SplitN(strings.TrimSpace(string(out)), ".", 2)[0]; major == "11" || major == "12" {
+ if got != smUnknown {
+ t.Fatalf("macOS %s answered %d, want unknown", out, got)
+ }
+ return
+ }
+ if !cgoBuilt {
+ t.Skip("built without cgo: the system can't be asked")
+ }
+ if got != smNotFound {
+ t.Errorf("a label BTM never saw answered %d, want notFound (%d)", got, smNotFound)
+ }
+ if got := askSystem(filepath.Join(dir, "none.plist")); got != smNotRegistered {
+ t.Errorf("no file answered %d, want notRegistered (%d)", got, smNotRegistered)
+ }
+}
diff --git a/internal/autostart/autostart_other.go b/internal/autostart/autostart_other.go
index e05d6d5b9..3bf1c5924 100644
--- a/internal/autostart/autostart_other.go
+++ b/internal/autostart/autostart_other.go
@@ -58,3 +58,6 @@ func disable() error {
// refresh: nothing an older magpie wrote here needs writing again
func refresh() error { return nil }
+
+// heldBack: nothing here is switched off apart from the record itself
+func heldBack() bool { return false }
diff --git a/internal/autostart/autostart_other_test.go b/internal/autostart/autostart_other_test.go
index ca6daa6b0..6f48abe6a 100644
--- a/internal/autostart/autostart_other_test.go
+++ b/internal/autostart/autostart_other_test.go
@@ -21,7 +21,7 @@ func TestSetThenTruncatedRecordReadsAsOff(t *testing.T) {
if err := Set(true); err != nil {
t.Fatal(err)
}
- if !Enabled() {
+ if Enabled() == Off {
t.Fatal("not on after Set(true)")
}
p := record()
@@ -35,13 +35,13 @@ func TestSetThenTruncatedRecordReadsAsOff(t *testing.T) {
if err := os.WriteFile(p, head, 0o644); err != nil {
t.Fatal(err)
}
- if Enabled() {
+ if Enabled() != Off {
t.Errorf("a desktop entry with no Exec reads as on:\n%s", head)
}
if err := os.WriteFile(p, nil, 0o644); err != nil {
t.Fatal(err)
}
- if Enabled() {
+ if Enabled() != Off {
t.Error("an empty desktop entry reads as on")
}
// an Exec key with nothing after it names nothing to run either, and the
@@ -49,7 +49,7 @@ func TestSetThenTruncatedRecordReadsAsOff(t *testing.T) {
if err := os.WriteFile(p, []byte("[Desktop Entry]\nType=Application\nName=magpie\nExec=\n"), 0o644); err != nil {
t.Fatal(err)
}
- if Enabled() {
+ if Enabled() != Off {
t.Error("a desktop entry with an empty Exec reads as on")
}
}
diff --git a/internal/autostart/autostart_sm_darwin.go b/internal/autostart/autostart_sm_darwin.go
new file mode 100644
index 000000000..848503ae3
--- /dev/null
+++ b/internal/autostart/autostart_sm_darwin.go
@@ -0,0 +1,33 @@
+//go:build darwin && cgo
+
+package autostart
+
+/*
+#cgo CFLAGS: -x objective-c -fobjc-arc
+#cgo LDFLAGS: -framework Foundation -framework ServiceManagement
+#include <stdlib.h>
+#import <Foundation/Foundation.h>
+#import <ServiceManagement/ServiceManagement.h>
+
+// SMAppService is macOS 13's; before it there is nothing to ask (-1)
+static long magpieLegacyStatus(const char *path) {
+ if (@available(macOS 13.0, *)) {
+ @autoreleasepool {
+ NSURL *u = [NSURL fileURLWithPath:[NSString stringWithUTF8String:path]];
+ return (long)[SMAppService statusForLegacyURL:u];
+ }
+ }
+ return -1;
+}
+*/
+import "C"
+
+import "unsafe"
+
+func init() {
+ legacyStatus = func(path string) int {
+ p := C.CString(path)
+ defer C.free(unsafe.Pointer(p))
+ return int(C.magpieLegacyStatus(p))
+ }
+}
diff --git a/internal/autostart/autostart_test.go b/internal/autostart/autostart_test.go
index 260815687..890602749 100644
--- a/internal/autostart/autostart_test.go
+++ b/internal/autostart/autostart_test.go
@@ -18,13 +18,13 @@ func TestSet(t *testing.T) {
t.Setenv("USERPROFILE", home)
t.Setenv("XDG_CONFIG_HOME", home+"/.config")
t.Setenv("APPIMAGE", "/opt/my apps/magpie.AppImage")
- if Enabled() {
+ if Enabled() != Off {
t.Fatal("on before it was turned on")
}
if err := Set(true); err != nil {
t.Fatal(err)
}
- if !Enabled() {
+ if Enabled() == Off {
t.Fatal("not on after Set(true)")
}
path := record()
@@ -41,7 +41,7 @@ func TestSet(t *testing.T) {
t.Errorf("%s lacks %q:\n%s", path, want, b)
}
}
- if err := Set(false); err != nil || Enabled() {
+ if err := Set(false); err != nil || Enabled() != Off {
t.Fatalf("still on after Set(false): %v", err)
}
if err := Set(false); err != nil {
diff --git a/internal/autostart/autostart_windows.go b/internal/autostart/autostart_windows.go
index a9ae231ff..8b111bdd9 100644
--- a/internal/autostart/autostart_windows.go
+++ b/internal/autostart/autostart_windows.go
@@ -117,3 +117,6 @@ func disable() error {
// refresh: nothing an older magpie wrote here needs writing again
func refresh() error { return nil }
+
+// heldBack: nothing here is switched off apart from the record itself
+func heldBack() bool { return false }
diff --git a/internal/autostart/autostart_windows_test.go b/internal/autostart/autostart_windows_test.go
index a5b6d09dd..d76126369 100644
--- a/internal/autostart/autostart_windows_test.go
+++ b/internal/autostart/autostart_windows_test.go
@@ -44,13 +44,13 @@ func TestEnabledUnreadableKeyIsNotOff(t *testing.T) {
openRunKey = func(registry.Key, string, uint32) (registry.Key, error) {
return 0, windows.ERROR_ACCESS_DENIED
}
- if !Enabled() {
+ if Enabled() == Off {
t.Fatal("a Run key that cannot be read reads as off")
}
openRunKey = func(registry.Key, string, uint32) (registry.Key, error) {
return 0, registry.ErrNotExist
}
- if Enabled() {
+ if Enabled() != Off {
t.Fatal("no Run key reads as on")
}
}
@@ -121,7 +121,7 @@ func TestEnabledWithNoMarkerIsOn(t *testing.T) {
openApprovedKey = func(registry.Key, string, uint32) (registry.Key, error) {
return 0, registry.ErrNotExist
}
- if !Enabled() {
+ if Enabled() == Off {
t.Fatal("a Run value with no Startup apps marker reads as off")
}
}
diff --git a/internal/autostart/cgo_darwin_test.go b/internal/autostart/cgo_darwin_test.go
new file mode 100644
index 000000000..73af65cb3
--- /dev/null
+++ b/internal/autostart/cgo_darwin_test.go
@@ -0,0 +1,6 @@
+//go:build darwin && cgo
+
+package autostart
+
+// cgoBuilt: this build asks ServiceManagement (autostart_sm_darwin.go)
+const cgoBuilt = true
diff --git a/internal/autostart/isolate_other_test.go b/internal/autostart/isolate_other_test.go
new file mode 100644
index 000000000..3a7ea2536
--- /dev/null
+++ b/internal/autostart/isolate_other_test.go
@@ -0,0 +1,6 @@
+//go:build !darwin
+
+package autostart
+
+// keepToTheSandbox: only the Mac's switch is asked of the system
+func keepToTheSandbox() {}
diff --git a/internal/autostart/main_test.go b/internal/autostart/main_test.go
index f3937e852..4f2b3d87d 100644
--- a/internal/autostart/main_test.go
+++ b/internal/autostart/main_test.go
@@ -6,5 +6,9 @@ import (
"github.com/yetone/magpie/internal/testenv"
)
-// The tests run in a home of their own, never the user's real files.
-func TestMain(m *testing.M) { testenv.Main(m) }
+// The tests run in a home of their own, never the user's real files, and
+// never ask the system about the user's own login item.
+func TestMain(m *testing.M) {
+ keepToTheSandbox()
+ testenv.Main(m)
+}
diff --git a/internal/autostart/nocgo_darwin_test.go b/internal/autostart/nocgo_darwin_test.go
new file mode 100644
index 000000000..58d8d331d
--- /dev/null
+++ b/internal/autostart/nocgo_darwin_test.go
@@ -0,0 +1,6 @@
+//go:build darwin && !cgo
+
+package autostart
+
+// cgoBuilt: this build has no way to ask ServiceManagement
+const cgoBuilt = false
diff --git a/internal/cli/autostart_cli.go b/internal/cli/autostart_cli.go
index 1a28dc8ff..e6ee8659c 100644
--- a/internal/cli/autostart_cli.go
+++ b/internal/cli/autostart_cli.go
@@ -22,13 +22,17 @@ func autostartCmd(args []string) error {
return fmt.Errorf("usage: magpie autostart [on|off]")
}
}
- if autostart.Enabled() {
+ switch autostart.Enabled() {
+ case autostart.NeedsAllowing:
+ // the record is there, and Set(true) can't undo the user's switch
+ fmt.Println("magpie is set to open at login, but it is switched off in System Settings › General › Login Items › Allow in the Background: switch it on there")
+ case autostart.On:
if runtime.GOOS == "android" {
fmt.Println(green.Render("✓"), "magpie starts the gateway at boot (requires Termux:Boot)")
} else {
fmt.Println(green.Render("✓"), "magpie opens at login, in the tray")
}
- } else {
+ default:
fmt.Println("magpie doesn't open at login")
}
return nil
diff --git a/internal/daemon/daemon.go b/internal/daemon/daemon.go
index 42eafeb85..fd1613e00 100644
--- a/internal/daemon/daemon.go
+++ b/internal/daemon/daemon.go
@@ -278,8 +278,11 @@ func installed(f func(manager) error) error {
})
}
-// autostartEnabled is a var for the tests.
-var autostartEnabled = autostart.Enabled
+// autostartEnabled: magpie's own record is there, whether or not the
+// user has it switched off in System Settings for now, since switching
+// it back on there opens the app with the service still installed. A
+// var for the tests.
+var autostartEnabled = func() bool { return autostart.Enabled() != autostart.Off }
// self is the program the service runs: this one, by the name on PATH
// when that is this same file, so a package manager's link (Homebrew's
diff --git a/internal/gui/api.go b/internal/gui/api.go
index 1f6e0f8cd..4616434e4 100644
--- a/internal/gui/api.go
+++ b/internal/gui/api.go
@@ -395,8 +395,11 @@ type settingsJSON struct {
// settings, environment, system, off or none
ProxyNow string `json:"proxyNow"`
ProxySource string `json:"proxySource"`
- // whether magpie opens at login: the system's record, not a setting
- Login bool `json:"login"`
+ // whether magpie opens at login: the system's record, not a setting;
+ // LoginAllow, the record is there but the user switched it off in
+ // System Settings › Login Items, which is where it's allowed again
+ Login bool `json:"login"`
+ LoginAllow bool `json:"loginAllow,omitempty"`
// the model that describes images when Vision names none, and those
// that can be named
VisionAuto string `json:"visionAuto,omitempty"`
@@ -583,6 +586,10 @@ type searchFailedJSON struct {
At time.Time `json:"at"`
}
+// loginState is whether magpie opens at login, as the system will act on
+// it. A var for the tests: the real one asks the user's own system.
+var loginState = autostart.Enabled
+
func settingsState() settingsJSON {
s := settingsJSON{Settings: settings.Load(), Version: Version, Dir: tilde(settings.Dir()), Portable: settings.Portable() != "", Gateway: gateway.URL()}
s.AddrEnv = os.Getenv("MAGPIE_ADDR")
@@ -622,7 +629,8 @@ func settingsState() settingsJSON {
s.OTelEnv = true
}
}
- s.Login = autostart.Enabled()
+ login := loginState()
+ s.Login, s.LoginAllow = login != autostart.Off, login == autostart.NeedsAllowing
if s.LAN {
s.LANURLs, s.LANContainer = gateway.LANURLs(), gateway.ContainerAddrs()
}
diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css
index 2ef04d21c..0e15462c6 100644
--- a/internal/gui/assets/app.css
+++ b/internal/gui/assets/app.css
@@ -3341,6 +3341,8 @@ input.words.search-key, input.words.search-url { flex: 1 1 120px; width: auto; m
.warm-at .warm-rm, .warm-at .warm-add { min-width: 24px; height: 27px; padding: 0 6px; font-size: 14px; line-height: 1; }
.row.pref .sub .warn { color: var(--amber); }
.row.pref .sub.wraps { white-space: normal; }
+.row.pref .login-allow-open { font: inherit; color: var(--accent); padding: 0; background: none; border: 0; cursor: pointer; }
+.row.pref .login-allow-open:hover { text-decoration: underline; }
/* the field's clock and picker in the page's own palette */
:root[data-theme="dark"] .warm-at input.at { color-scheme: dark; }
@media (prefers-color-scheme: dark) { :root:not([data-theme="light"]) .warm-at input.at { color-scheme: dark; } }
diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js
index bcaa9562e..1b4ee3611 100644
--- a/internal/gui/assets/app.js
+++ b/internal/gui/assets/app.js
@@ -18794,6 +18794,32 @@ function renderBarIcon() {
.catch((e) => { status(t(e.message), "err"); renderBarIcon(); })));
}
+// renderLoginAllow: Open at login switched off in System Settings, its
+// launch agent still there (#2120, Anoninz). On stays picked, as the record
+// is, and writing it again doesn't undo the user's switch, so the row says
+// it won't open and opens Login Items, where it is allowed again. Coming
+// back to the window reads the settings again (load), so the line goes once
+// it is allowed there.
+const loginItemsURL = "x-apple.systempreferences:com.apple.LoginItems-Settings.extension";
+function renderLoginAllow(s) {
+ const who = $("#loginRow .who");
+ let sub = who.querySelector(".login-allow");
+ if (!s.loginAllow) { sub?.remove(); return; }
+ if (!sub) {
+ sub = document.createElement("div");
+ sub.className = "sub wraps login-allow";
+ who.append(sub);
+ }
+ // the row is hidden on a page served to another computer (web), which
+ // has no System Settings to open
+ const open = document.createElement("button");
+ open.type = "button";
+ open.className = "login-allow-open";
+ open.textContent = t("Open Login Items");
+ open.onclick = () => api("open", { url: loginItemsURL }).catch((e) => status(t(e.message), "err"));
+ sub.replaceChildren(t("Switched off in System Settings’ Login Items, so magpie won’t open at login"), " ", open);
+}
+
async function loadSettings() {
const since = prefsWrites;
if (!web && fontList === null && !fontListError) loadFonts();
@@ -19205,6 +19231,7 @@ function renderSettings() {
// the system's record, set on its own, not with the other choices
$("#loginSegs").replaceChildren(segs([["off", t("Off")], ["on", t("On")]], s.login ? "on" : "off", (v) =>
writingPrefs(api("settings/login", { on: v === "on" })).then((ns) => { prefs = ns; renderSettings(); }).catch((e) => { status(t(e.message), "err"); renderSettings(); })));
+ renderLoginAllow(s);
// Codex's and Claude Code's warm-ups and WorkBuddy's check-in, one tab
// each over one card, the rows' names not saying the service again.
// A ChatGPT account's next window started as soon as the last resets
diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js
index cdb5ef0d8..ebb23ea5e 100644
--- a/internal/gui/assets/i18n.js
+++ b/internal/gui/assets/i18n.js
@@ -858,6 +858,8 @@ const I18N = {
"Guesses your next message for the composer, reading the whole conversation again each time; at Codex’s own, it goes on the thread’s model through its ChatGPT sign-in": "为输入框猜测你的下一条消息,每次都把整段对话重读一遍;选 Codex 自带时用该会话的模型,经它的 ChatGPT 登录",
"Decides an approval in your place when Codex’s approvals are on auto-review; Codex’s own pick is codex-auto-review, else the conversation’s model at low effort": "Codex 的审批设为自动审批时,代你决定是否批准;由 Codex 决定时用 codex-auto-review,没有则用当前对话的模型(低推理)",
"Writes Codex’s memories of past threads, in the background; Codex’s own: gpt-5.6-terra, with gpt-5.6-luna summing up each thread": "在后台把过去的会话整理成 Codex 的记忆;Codex 自带的:整理用 gpt-5.6-terra,总结对话用 gpt-5.6-luna",
+ "Switched off in System Settings’ Login Items, so magpie won’t open at login": "已在系统设置的登录项里关闭,登录时不会打开 magpie",
+ "Open Login Items": "打开登录项",
"Opens in the menu bar with no window. System Settings › General › Login Items lists it under App Background Activity, not Open at Login": "登录后在菜单栏打开,不弹出窗口。系统设置 › 通用 › 登录项 里,它列在「App后台活动」下,而不是「登录时打开」",
"Opens in the tray with no window": "登录后在托盘打开,不弹出窗口",
"With window": "跟随窗口",
@@ -4588,6 +4590,8 @@ const I18N = {
"Guesses your next message for the composer, reading the whole conversation again each time; at Codex’s own, it goes on the thread’s model through its ChatGPT sign-in": "為輸入框猜測你的下一則訊息,每次都把整段對話重讀一遍;選 Codex 自帶時用該會話的模型,經它的 ChatGPT 登入",
"Decides an approval in your place when Codex’s approvals are on auto-review; Codex’s own pick is codex-auto-review, else the conversation’s model at low effort": "Codex 的審批設為自動審批時,代你決定是否批准;由 Codex 決定時用 codex-auto-review,沒有則用目前對話的模型(低推理)",
"Writes Codex’s memories of past threads, in the background; Codex’s own: gpt-5.6-terra, with gpt-5.6-luna summing up each thread": "在背景把過去的會話整理成 Codex 的記憶;Codex 自帶的:整理用 gpt-5.6-terra,總結對話用 gpt-5.6-luna",
+ "Switched off in System Settings’ Login Items, so magpie won’t open at login": "已在系統設定的登入項目裡關閉,登入時不會開啟 magpie",
+ "Open Login Items": "打開登入項目",
"Opens in the menu bar with no window. System Settings › General › Login Items lists it under App Background Activity, not Open at Login": "登入後在選單列開啟,不彈出視窗。系統設定 › 一般 › 登入項目 裡,它列在「App背景活動」下,而不是「在登入時打開」",
"Opens in the tray with no window": "登入後在系統匣開啟,不彈出視窗",
"With window": "跟隨視窗",
@@ -8290,6 +8294,8 @@ const I18N = {
"Guesses your next message for the composer, reading the whole conversation again each time; at Codex’s own, it goes on the thread’s model through its ChatGPT sign-in": "入力欄に次のメッセージを予測し、そのたびに会話全体を読み直します。Codex 自身ならスレッドのモデルで、その ChatGPT サインインで送られます",
"Decides an approval in your place when Codex’s approvals are on auto-review; Codex’s own pick is codex-auto-review, else the conversation’s model at low effort": "Codex の承認が自動レビューのとき、あなたの代わりに承認を判断します。Codex に任せると codex-auto-review、なければ会話のモデル(低い推論)",
"Writes Codex’s memories of past threads, in the background; Codex’s own: gpt-5.6-terra, with gpt-5.6-luna summing up each thread": "過去のスレッドを Codex のメモリにバックグラウンドでまとめます。Codex の初期設定:整理は gpt-5.6-terra、スレッドの要約は gpt-5.6-luna",
+ "Switched off in System Settings’ Login Items, so magpie won’t open at login": "システム設定のログイン項目でオフになっているため、ログイン時に magpie は開きません",
+ "Open Login Items": "ログイン項目を開く",
"Opens in the menu bar with no window. System Settings › General › Login Items lists it under App Background Activity, not Open at Login": "ログイン後、ウィンドウなしでメニューバーに開きます。システム設定 › 一般 › ログイン項目では「ログイン時に開く」ではなく「アプリのバックグラウンドでのアクティビティ」に表示されます",
"Opens in the tray with no window": "ログイン後、ウィンドウなしでトレイに開きます",
"With window": "ウィンドウと連動",
@@ -12006,6 +12012,8 @@ const I18N = {
"Guesses your next message for the composer, reading the whole conversation again each time; at Codex’s own, it goes on the thread’s model through its ChatGPT sign-in": "Errät Ihre nächste Nachricht fürs Eingabefeld und liest dafür jedes Mal das ganze Gespräch neu; bei „Eigene von Codex“ mit dem Modell des Threads über seine ChatGPT-Anmeldung",
"Decides an approval in your place when Codex’s approvals are on auto-review; Codex’s own pick is codex-auto-review, else the conversation’s model at low effort": "Entscheidet eine Freigabe an Ihrer Stelle, wenn Codex’ Freigaben auf Auto-Review stehen; „Wie Codex es wählt“ ist codex-auto-review, sonst das Modell des Gesprächs mit wenig Reasoning",
"Writes Codex’s memories of past threads, in the background; Codex’s own: gpt-5.6-terra, with gpt-5.6-luna summing up each thread": "Schreibt im Hintergrund Codex’ Erinnerungen an frühere Threads; Codex’ eigenes: gpt-5.6-terra, Threads zusammengefasst mit gpt-5.6-luna",
+ "Switched off in System Settings’ Login Items, so magpie won’t open at login": "In den Systemeinstellungen unter „Anmeldeobjekte“ ausgeschaltet, daher öffnet sich magpie bei der Anmeldung nicht",
+ "Open Login Items": "Anmeldeobjekte öffnen",
"Opens in the menu bar with no window. System Settings › General › Login Items lists it under App Background Activity, not Open at Login": "Öffnet sich in der Menüleiste, ohne Fenster. Systemeinstellungen › Allgemein › Anmeldeobjekte führt es unter „App-Hintergrundaktivitäten“, nicht unter „Bei der Anmeldung öffnen“",
"Opens in the tray with no window": "Öffnet sich im Infobereich, ohne Fenster",
"With window": "Mit Fenster",
diff --git a/internal/gui/login_allow_test.go b/internal/gui/login_allow_test.go
new file mode 100644
index 000000000..51570f7ea
--- /dev/null
+++ b/internal/gui/login_allow_test.go
@@ -0,0 +1,47 @@
+package gui
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/yetone/magpie/internal/autostart"
+)
+
+// Open at login switched off in System Settings, its launch agent still
+// there, reads as needing to be allowed, not as on (#2120, Anoninz): the
+// row says so and opens Login Items, the one System Settings pane the page
+// may open.
+func TestLoginNeedsAllowing(t *testing.T) {
+ sandboxHome(t)
+ prev := loginState
+ t.Cleanup(func() { loginState = prev })
+ for _, c := range []struct {
+ st autostart.State
+ login, allow bool
+ }{{autostart.Off, false, false}, {autostart.On, true, false}, {autostart.NeedsAllowing, true, true}} {
+ loginState = func() autostart.State { return c.st }
+ s := settingsState()
+ if s.Login != c.login || s.LoginAllow != c.allow {
+ t.Errorf("%s: login %v, loginAllow %v; want %v, %v", c.st, s.Login, s.LoginAllow, c.login, c.allow)
+ }
+ b, _ := json.Marshal(s)
+ if got := strings.Contains(string(b), `"loginAllow":true`); got != c.allow {
+ t.Errorf("%s: loginAllow in the JSON is %v: %s", c.st, got, b)
+ }
+ }
+
+ w := &importWindows{}
+ mux := http.NewServeMux()
+ providerRoutes(mux, w)
+ for _, link := range []string{autostart.LoginItemsURL, "x-apple.systempreferences:com.apple.preference.security?Privacy_FilesAndFolders", "x-apple.systempreferences:"} {
+ w.opened = ""
+ body, _ := json.Marshal(map[string]string{"url": link})
+ mux.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("POST", "/api/open", strings.NewReader(string(body))))
+ if want := link == autostart.LoginItemsURL; (w.opened == link) != want {
+ t.Errorf("%s: opened %q", link, w.opened)
+ }
+ }
+}
diff --git a/internal/gui/providers.go b/internal/gui/providers.go
index 2c771e35f..263abc938 100644
--- a/internal/gui/providers.go
+++ b/internal/gui/providers.go
@@ -15,6 +15,7 @@ import (
"time"
"github.com/yetone/magpie/internal/agent"
+ "github.com/yetone/magpie/internal/autostart"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/gateway"
"github.com/yetone/magpie/internal/provider"
@@ -2276,7 +2277,9 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
mux.HandleFunc("POST /api/open", func(rw http.ResponseWriter, r *http.Request) {
var in struct{ URL string }
_ = json.NewDecoder(r.Body).Decode(&in)
- if strings.HasPrefix(in.URL, "https://") || strings.HasPrefix(in.URL, "http://") || strings.HasPrefix(in.URL, agent.CindyScheme) || strings.HasPrefix(in.URL, agent.LodyScheme) {
+ // and System Settings' Login Items, where Open at login is allowed
+ // again: that one pane, not System Settings' scheme at large
+ if strings.HasPrefix(in.URL, "https://") || strings.HasPrefix(in.URL, "http://") || strings.HasPrefix(in.URL, agent.CindyScheme) || strings.HasPrefix(in.URL, agent.LodyScheme) || in.URL == autostart.LoginItemsURL {
// Open again on a sign-in says why it didn't open (#2043)
if err := w.OpenURL(in.URL); err != nil {
fail(rw, err)
diff --git a/internal/gui/tests/login-allow.test.cjs b/internal/gui/tests/login-allow.test.cjs
new file mode 100644
index 000000000..ee45e5b74
--- /dev/null
+++ b/internal/gui/tests/login-allow.test.cjs
@@ -0,0 +1,122 @@
+// Run with Node's test runner and Playwright on the module path; see README.md.
+// Anoninz on #2120: magpie's Open at login said On while the Mac's own
+// switch for it, in System Settings › General › Login Items, was off, so
+// magpie never opened at login. Settings now says whether the system will
+// open it: in every language, at 1000px and 440px, in both engines, on a Mac,
+// with the API faked:
+// - a record the system holds switched off shows On with one line under it
+// saying so, and a button that asks magpie to open Login Items (the exact
+// x-apple.systempreferences URL, through /api/open);
+// - the window coming back to the front reads the state again: switched
+// back on there, the line goes;
+// - a page served to another computer (web) has no System Settings to
+// open, and no Open at login row at all.
+const assert = require("node:assert/strict");
+const fs = require("node:fs/promises");
+const path = require("node:path");
+const { test } = require("node:test");
+const { chromium, webkit } = require("playwright");
+const { watchSettingsReads, settingsDrawn } = require("./reader.cjs");
+
+const assets = path.resolve(__dirname, "../assets");
+const loginItems = "x-apple.systempreferences:com.apple.LoginItems-Settings.extension";
+const line = {
+ en: "Switched off in System Settings’ Login Items, so magpie won’t open at login",
+ zh: "已在系统设置的登录项里关闭,登录时不会打开 magpie",
+ "zh-TW": "已在系統設定的登入項目裡關閉,登入時不會開啟 magpie",
+ ja: "システム設定のログイン項目でオフになっているため、ログイン時に magpie は開きません",
+ de: "In den Systemeinstellungen unter „Anmeldeobjekte“ ausgeschaltet, daher öffnet sich magpie bei der Anmeldung nicht",
+};
+const button = { en: "Open Login Items", zh: "打开登录项", "zh-TW": "打開登入項目", ja: "ログイン項目を開く", de: "Anmeldeobjekte öffnen" };
+
+function serve(lang, web, st, opened) {
+ const settings = () => ({ lang, theme: "light", searchVendors: [], searchAPIs: [], ...st });
+ return async (r) => {
+ const url = new URL(r.request().url());
+ const json = (data, status = 200) => r.fulfill({ status, json: data });
+ if (url.pathname === "/boot.js") return r.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:${web}};` });
+ if (url.pathname === "/wails/runtime.js") return r.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
+ if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: settings() });
+ if (url.pathname === "/api/settings") return json(settings());
+ if (url.pathname === "/api/open") {
+ opened.push(JSON.parse(r.request().postData()).url);
+ return json({});
+ }
+ if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true, url: "http://127.0.0.1:3999" } });
+ if (url.pathname === "/api/groups") return json({ models: [], groups: [], pools: [] });
+ if (url.pathname === "/api/plugins") return json({ plugins: [] });
+ if (url.pathname === "/api/usage/quotas") return json([]);
+ if (url.pathname.startsWith("/api/")) return json({});
+ const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
+ const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
+ await r.fulfill({ body: await fs.readFile(file), contentType });
+ };
+}
+
+for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
+ for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) for (const width of [1000, 440]) for (const web of [false, true]) {
+ test(`${engine} ${lang} ${width}px${web ? " web" : ""}: Open at login says when the Mac's own switch for it is off`, async (t) => {
+ const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
+ t.after(() => browser.close());
+ const page = await (await browser.newContext({ viewport: { width, height: 760 } })).newPage();
+ page.setDefaultTimeout(5000);
+ const errors = [];
+ page.on("pageerror", (e) => errors.push(e.message));
+ await page.addInitScript(() => Object.defineProperty(navigator, "platform", { get: () => "MacIntel" }));
+ const st = { login: true, loginAllow: true }, opened = [];
+ await page.route("**/*", serve(lang, web, st, opened));
+ await watchSettingsReads(page);
+ await page.goto("http://magpie.test/?view=settings&tab=general");
+ await settingsDrawn(page);
+ const sub = page.locator("#loginRow .login-allow");
+ if (web) {
+ await page.locator("#loginRow").waitFor({ state: "hidden" });
+ await page.locator("#langPick span").waitFor();
+ assert.equal(await page.locator("#loginRow").isHidden(), true, "a page served to another computer offers Open at login");
+ assert.deepEqual(errors, []);
+ return;
+ }
+ await sub.waitFor();
+
+ const seen = await page.evaluate(() => {
+ const row = document.querySelector("#loginRow"), s = row.querySelector(".login-allow"), r = row.getBoundingClientRect();
+ return {
+ text: s.firstChild.textContent,
+ inside: [...s.getClientRects()].every((x) => x.left >= r.left - 0.5 && x.right <= r.right + 0.5),
+ stripe: parseFloat(getComputedStyle(row).borderLeftWidth) > 1,
+ sideways: document.documentElement.scrollWidth > innerWidth,
+ selects: document.querySelectorAll("#setPage-general select").length,
+ };
+ });
+ assert.equal(seen.text, line[lang]);
+ assert.ok(seen.inside, "the line runs out of its row");
+ assert.equal(seen.stripe, false, "the row has a stripe down its left");
+ assert.equal(seen.sideways, false, "the page scrolls sideways");
+ assert.equal(seen.selects, 0, "no native <select>");
+
+ const open = page.locator("#loginRow .login-allow-open");
+ assert.equal(await open.innerText(), button[lang]);
+ assert.equal(await open.evaluate((b) => b.tagName), "BUTTON");
+ // scrolled to as a reader would, with the wheel, once the page has come
+ // in (it comes in animated: a place read mid-way isn't where it rests)
+ await page.evaluate(() => Promise.all(document.getAnimations().map((a) => a.finished.catch(() => {}))));
+ let b = await open.boundingBox();
+ for (let i = 0; i < 40 && b.y + b.height > page.viewportSize().height; i++) {
+ await page.mouse.move(width / 2, 300);
+ await page.mouse.wheel(0, 200);
+ await page.waitForTimeout(50);
+ b = await open.boundingBox();
+ }
+ await page.mouse.click(b.x + b.width / 2, b.y + b.height / 2);
+ for (let i = 0; i < 50 && !opened.length; i++) await page.waitForTimeout(50);
+ assert.deepEqual(opened, [loginItems]);
+
+ // switched back on in System Settings, then back to magpie: the line goes
+ st.loginAllow = false;
+ await page.evaluate(() => window.dispatchEvent(new Event("focus")));
+ await sub.waitFor({ state: "detached" });
+ assert.equal(await page.locator("#loginRow .sub").filter({ visible: true }).count(), 0, "Open at login says its name alone again");
+ assert.deepEqual(errors, []);
+ });
+ }
+}