Skip to content

feat(tray): add "Start Core when the app opens" preference (#410) - #847

Merged
Dumbris merged 3 commits into
mainfrom
fix/410-tray-core-autostart
Jul 14, 2026
Merged

Dumbris merged 3 commits into
mainfrom
fix/410-tray-core-autostart

Conversation

@Dumbris

@Dumbris Dumbris commented Jul 13, 2026

Copy link
Copy Markdown
Member

Implements discussion #410 (jagaliano), open and unanswered since 2026-04-25.

The report

The macOS tray starts the Core unconditionally in applicationDidFinishLaunching, and nothing can stop it: the existing Stop action only sets an in-memory isStopped, so the choice never survives a relaunch. Keeping MCPProxy in the menu bar therefore means keeping the Core — and its whole tree of upstream MCP server processes — alive. ~1.8 GB RSS in the reporter's setup, with no AI client open.

The requester read our Swift and proposed the implementation himself; his analysis checks out. What he did not know: the Go tray has had MCPPROXY_TRAY_SKIP_CORE for this all along (cmd/mcpproxy-tray/main.go, documented in docs/architecture.md). The Swift app we actually ship never got it. So this is closing a parity gap, not inventing a concept.

Design — where the state lives

The tray and Core are decoupled (socket / HTTP only), so this setting cannot live in the Core's config: its entire purpose is to be read when no Core is running, so there is nothing to ask. It is tray-local (UserDefaults), alongside fontScale and firstRunCompleted.

This does not make the tray stateful about the Core. It never remembers whether a Core is running — that is discovered live from the socket on every launch. The one bit it remembers is its own permission to spawn one:

attach to a running core  — always allowed, never gated
spawn a new core          — gated by the preference

With the preference off and no Core up, the tray idles and polls, so a Core started later (CLI, launchd, brew services) is picked up without a tray restart. An explicit "Start MCPProxy Core" from the menu always spawns.

Stop stays session-only by design: the persistent choice is the toggle. Stopping the Core to debug something must not silently leave the tray dead after the next reboot.

Two ownership bugs fixed alongside

Both are real today; idle mode makes them far more reachable.

  1. Swift: "Stop MCPProxy Core" lied on an attached Core. It killed managedProcess — nil in .externalAttached — so it tore down our own clients, displayed "Stopped", and left the Core running. We hold no PID for it and the Core exposes no shutdown endpoint. It is now "Disconnect from Core" and says so. shutdown() checks ownership explicitly instead of relying on process incidentally being nil.
  2. Go tray killed Cores it never started. coreOwnershipExternalManaged ("a Core was already running, so I attached") still fell through to shutdownExternalCoreFallback() + ensureCoreTermination(), which look the PID up from /status and even pgrep -f "mcpproxy serve" for stragglers. Run a Core under launchd, open the Go tray, quit it — your Core died. Only a tray-spawned Core is terminated now.

Tests

7 new: CoreLaunchPolicyTests (default-ON back-compat, round-trip, env override precedence), CoreOwnershipTests (only-kill-what-you-spawned, honest labels), Go TestShouldTerminateCore. Swift suite 276 → 283 tests, failure count unchanged at 7 — those 7 are pre-existing on clean main (SSE parser, UserDefaults suite pollution), not from this change. go build ./... + golangci-lint v2 clean.

Not yet driven end-to-end in the real .app — the wiring (idle mode, attach-watch, menu labels) is proven by construction and unit tests only.

The macOS tray started the core unconditionally in applicationDidFinishLaunching,
and nothing could stop it: the existing Stop action only sets an in-memory
isStopped, so the choice never survived a relaunch. Keeping MCPProxy in the menu
bar therefore meant keeping the core — and its whole tree of upstream MCP server
processes — alive, ~1.8 GB RSS in the reporter's setup, even with no AI client
open. The Go tray has had MCPPROXY_TRAY_SKIP_CORE for this since forever; the
Swift app we actually ship never got it.

Add a persisted "Start MCPProxy Core when the app opens" preference
(CoreLaunchPolicy, UserDefaults, default ON so existing installs are unchanged),
honouring MCPPROXY_TRAY_SKIP_CORE for parity with the Go tray.

The setting is tray-local, and has to be: its purpose is to be read when NO core
is running, so there is nothing to ask over the socket. This does not make the
tray stateful about the core — it never remembers whether a core is running, it
discovers that live from the socket on every launch. The one bit it remembers is
its own permission to SPAWN one:

  attach to a running core — always allowed, never gated
  spawn a new core        — gated by the preference

With the preference off and no core up, the tray idles and polls for a core to
appear, so one started later (CLI, launchd, brew services) is picked up without
a restart. An explicit "Start MCPProxy Core" from the menu always spawns.

Also fix two ownership bugs this makes reachable:

- Swift: "Stop MCPProxy Core" on a core we merely ATTACHED to tore down our own
  clients, displayed "Stopped", and left the core running — we hold no PID for
  it and the core exposes no shutdown endpoint. The item is now "Disconnect from
  Core" and says so. Shutdown checks ownership explicitly instead of relying on
  `process` happening to be nil for an attached core.
- Go tray: coreOwnershipExternalManaged ("a core was already running, so I
  attached") was still terminated on quit, via the PID from /status plus a
  `pgrep -f "mcpproxy serve"` sweep. Running a core under launchd and opening
  the tray meant quitting the tray killed your core. Only a core the tray
  launched is terminated now.
@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Jul 13, 2026 •

Copy link
Copy Markdown

Deploying mcpproxy-docs with  Cloudflare Pages  Cloudflare Pages

Latest commit: 9610425
Status: ✅  Deploy successful!
Preview URL: https://482da673.mcpproxy-docs.pages.dev
Branch Preview URL: https://fix-410-tray-core-autostart.mcpproxy-docs.pages.dev

View logs

@codecov-commenter

Copy link
Copy Markdown

⚠️ Please install the 'codecov app svg image' to ensure uploads and comments are reliably processed by Codecov.

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

Cross-model review (Codex) on PR #847 turned up two ways idle mode could hand
the tray a core it then mislabels or spawns against the user's wishes.

1. Stale attach-watch could race an explicit Start and corrupt ownership.
   "Start MCPProxy Core" builds a FRESH CoreProcessManager and drops the old
   one, but in idle mode the old manager is still polling for a core to attach
   to. It could observe the socket the NEW manager's core had just created and
   publish ownership = .externalAttached for a core the tray itself spawned —
   after which the menu offers "Disconnect", Stop refuses to signal it, and quit
   leaks the process. A superseded manager now never touches AppState again, and
   the app retires the outgoing manager before swapping in its replacement.

2. retry() was a back door around the launch policy. With autostart off, an
   attached external core that exits leaves the tray in an error state whose
   menu offers "Retry" — which called launchAndConnect() unconditionally and
   spawned a tray-managed core the user had asked us not to start. Retry now
   re-runs the normal start path with a spawn decision derived from ownership
   and policy (CoreLaunchPolicy.retryMaySpawn): a core we own is relaunched; an
   external one is re-attached, or we go back to idle and wait for it.

Also: startCore() no longer re-assigns appState.startCoreOnLaunch. AppState
already initializes it from CoreLaunchPolicy, and its didSet writes through to
UserDefaults — so the redundant sync materialized the key on every launch, even
for users who only ever set MCPPROXY_TRAY_SKIP_CORE.
@github-actions

github-actions Bot commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

📦 Build Artifacts

Workflow Run: View Run
Branch: fix/410-tray-core-autostart

Available Artifacts

  • archive-darwin-amd64 (28 MB)
  • archive-darwin-arm64 (25 MB)
  • archive-linux-amd64 (16 MB)
  • archive-linux-arm64 (15 MB)
  • archive-windows-amd64 (28 MB)
  • archive-windows-arm64 (25 MB)
  • frontend-dist-pr (0 MB)
  • installer-dmg-darwin-amd64 (22 MB)
  • installer-dmg-darwin-arm64 (19 MB)

How to Download

Option 1: GitHub Web UI (easiest)

  1. Go to the workflow run page linked above
  2. Scroll to the bottom "Artifacts" section
  3. Click on the artifact you want to download

Option 2: GitHub CLI

gh run download 29274703626 --repo smart-mcp-proxy/mcpproxy-go

Note: Artifacts expire in 14 days.

Found by running the real app: with core autostart off, the tray idled, saw an
external core appear, tried to attach — and landed in

  Error: Failed to connect to external core: cancelled

while a perfectly healthy core was running on the socket.

attachToExternalCore() opened with cancelAttachWatch(), but the attach is
normally running INSIDE the watch task (that is how the core was noticed in the
first place). Cancelling there cancels the very task performing the attach, so
the connectToCore() it goes on to await throws CancellationError. Self-inflicted,
and invisible to unit tests: it needs a real socket, a real core appearing while
idle, and the actor's task tree.

attachToExternalCore now drops the task reference without cancelling — the watch
loop exits by itself the moment attachIfCoreIsRunning() reports success. The
remaining cancelAttachWatch() callers (shutdown, supersede) are all OUTSIDE the
task, where cancelling is correct, and the function now documents that constraint.

Verified end-to-end in the real macOS app (dev bundle, mcpproxy-ui-test):
- no stored preference => core auto-starts, and the key is NOT materialized
- Settings > Startup shows "Start MCPProxy Core when the app opens" (ON)
- preference OFF => no core spawned; menu offers "Start MCPProxy Core"
- an external core started later => tray attaches; menu reads "Disconnect from Core"
- quitting the tray leaves that external core RUNNING
- explicit "Start MCPProxy Core" spawns one anyway, labelled "Stop MCPProxy Core"
  (tray-owned), and leaves the preference off
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants