From 9c740c0d4844cf218a84ef6a294ac2d31a8a2a87 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Fri, 28 Aug 2026 08:29:26 +0300 Subject: [PATCH 1/4] fix(tray): stop the permanent red badge, and shrink it to a corner dot MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The v0.61.0 tray badge (#1055) sat red indefinitely on an install whose only error-severity diagnostics belonged to quarantined servers, and it was drawn as a full-size glyph beside the icon rather than a badge on it. Tray badge — quarantined servers no longer tint it worstDiagnosticSeverity and diagnosticCount excluded OAuth login-required servers but not quarantined ones. mcpproxy still attempts a connection to a quarantined server so the scanner can export its tool definitions, and the failed attempt leaves an error-severity diagnostic behind — while the same payload reports health.level "healthy" / admin_state "quarantined". The menu header drew a calm yellow dot from serversNeedingAttention under a red menu-bar dot from worstDiagnosticSeverity, and the user could not clear it without approving or disabling the server. Both properties now share one ServerStatus.isBadgeExempt predicate so they cannot drift apart, and any future intentional non-connected state has one place to be added. Tray badge — drawn as a corner dot, not a glyph beside the icon The severity badge was a full-size "●" plus a leading space in the button's attributed title, which widened the status item by about a character and read as a second icon. It is now a 6pt dot in the icon's bottom-right corner, as a subview: the status-item image must stay isTemplate to track the light/dark menu bar and to invert while the menu is open, and template rendering forces every pixel monochrome, so a coloured dot composited into the image comes back black. The view is hit-test transparent and ignored by accessibility, since the button already publishes the whole state as its label. ⏹ (core stopped) and ⚠ (core error) keep their full-size glyphs: those mean "nothing is working", which is worth the width and would be lost if collapsed into the same dot. Diagnostics — two of mcpproxy's own messages no longer say "file a bug" `command "npx" has no args` (emitted by our own pre-spawn validation in connection_stdio.go) and the legacy-SSE `4xx for initialize POST` both fell through to MCPX_UNKNOWN_UNCLASSIFIED, whose catalog entry offers a "Report a bug" button. They now classify as MCPX_CONFIG_INVALID_COMMAND and MCPX_HTTP_LEGACY_SSE, with catalog entries and docs pages. The legacy-SSE rule is matched before the generic HTTP status-text fallback, which would otherwise claim it as a bare 403/404 and send the user hunting for a credential problem that does not exist. Logging — one ListTools failure was three ERROR lines core.Client, managed.Client and Manager.discoverTools each logged the same failed list operation at ERROR. On an install with several stdio servers the periodic sweep hit this roughly once a minute per server, indefinitely. The two inner layers drop to Debug; the manager keeps the line at Warn, since it deliberately skips markSwept so the next sweep retries — a failure the code already plans to retry is not an error. Tests - Swift: quarantine/OAuth badge exemption from live /api/v1/servers payload shapes, including that a genuinely broken server still tints red and that the spoken count agrees with the badge. - Swift: corner-dot geometry and colour asserted by rendering the view offscreen and reading pixels back — the status item cannot be screenshotted without a Screen Recording grant, and "it looked right once" is not a regression test. - Go: both new codes classify from the verbatim v0.61.0 error strings, ordinary HTTP statuses are unaffected, and both codes are registered. - Go: one ListTools failure is reported by exactly one layer, not at ERROR, and is still reported at all. --- docs/errors/MCPX_CONFIG_INVALID_COMMAND.md | 82 ++++++++++ docs/errors/MCPX_HTTP_LEGACY_SSE.md | 63 ++++++++ docs/errors/README.md | 2 + internal/diagnostics/classifier.go | 17 ++ .../classifier_selfmessages_test.go | 91 +++++++++++ internal/diagnostics/codes.go | 12 ++ internal/diagnostics/registry.go | 19 +++ internal/upstream/core/client.go | 7 +- internal/upstream/listtools_logging_test.go | 137 ++++++++++++++++ internal/upstream/managed/client.go | 6 +- internal/upstream/manager.go | 7 +- .../macos/MCPProxy/MCPProxy/API/Models.swift | 32 ++++ .../macos/MCPProxy/MCPProxy/MCPProxyApp.swift | 78 ++++++--- .../MCPProxy/Menu/TrayBadgeDotView.swift | 67 ++++++++ .../MCPProxy/Menu/TrayPresentation.swift | 61 ++++++- .../MCPProxy/MCPProxy/State/AppState.swift | 20 +-- .../MCPProxyTests/TrayBadgeDotTests.swift | 106 ++++++++++++ .../TrayBadgeExemptionTests.swift | 153 ++++++++++++++++++ .../MCPProxyTests/TrayPresentationTests.swift | 36 ++++- website/sidebars.js | 2 + 20 files changed, 963 insertions(+), 35 deletions(-) create mode 100644 docs/errors/MCPX_CONFIG_INVALID_COMMAND.md create mode 100644 docs/errors/MCPX_HTTP_LEGACY_SSE.md create mode 100644 internal/diagnostics/classifier_selfmessages_test.go create mode 100644 internal/upstream/listtools_logging_test.go create mode 100644 native/macos/MCPProxy/MCPProxy/Menu/TrayBadgeDotView.swift create mode 100644 native/macos/MCPProxy/MCPProxyTests/TrayBadgeDotTests.swift create mode 100644 native/macos/MCPProxy/MCPProxyTests/TrayBadgeExemptionTests.swift diff --git a/docs/errors/MCPX_CONFIG_INVALID_COMMAND.md b/docs/errors/MCPX_CONFIG_INVALID_COMMAND.md new file mode 100644 index 000000000..3ae1bd993 --- /dev/null +++ b/docs/errors/MCPX_CONFIG_INVALID_COMMAND.md @@ -0,0 +1,82 @@ +--- +id: MCPX_CONFIG_INVALID_COMMAND +title: MCPX_CONFIG_INVALID_COMMAND +sidebar_label: INVALID_COMMAND +description: A stdio server's command and args cannot spawn anything — typically a package runner with no package to run. +--- + +# `MCPX_CONFIG_INVALID_COMMAND` + +**Severity:** error +**Domain:** Config + +## What happened + +The server's `command` / `args` pair cannot start an MCP server. The common case +is a package runner named with nothing to run: + +```jsonc +{ + "name": "demo-filesystem", + "protocol": "stdio", + "command": "npx" // ← no "args", so there is no package to execute +} +``` + +`npx`, `uvx`, `pipx` and `bunx` all take the package to run as their first +argument. Without it they either print usage and exit or drop into an +interactive prompt, and neither speaks MCP — so the connection fails on every +attempt and the server stays permanently unhealthy. + +mcpproxy detects this *before* spawning the process, which is why the failure is +instant rather than a timeout. + +## How to fix + +### Add the package to `args` + +```jsonc +{ + "name": "demo-filesystem", + "protocol": "stdio", + "command": "npx", + "args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/serve"] +} +``` + +`-y` (npm) skips the install prompt, which would otherwise hang the handshake. +The `uvx` equivalent needs no flag: + +```jsonc +{ "command": "uvx", "args": ["mcp-server-time"] } +``` + +### Inspect what is currently configured + +```bash +mcpproxy upstream get -o json +``` + +### Remove the entry if it is a leftover + +An entry that was added for a demo or a test and never completed is worth +deleting rather than fixing — it keeps the tray badge red for a server nobody +uses: + +```bash +mcpproxy upstream remove +``` + +### Apply the change + +The config file is hot-reloaded, so saving `~/.mcpproxy/mcp_config.json` is +enough. To force a retry immediately: + +```bash +mcpproxy upstream restart +``` + +## Related + +- [`MCPX_STDIO_SPAWN_ENOENT`](MCPX_STDIO_SPAWN_ENOENT.md) — the command itself was not found +- [`MCPX_CONFIG_PARSE_ERROR`](MCPX_CONFIG_PARSE_ERROR.md) — the config file is not valid JSON diff --git a/docs/errors/MCPX_HTTP_LEGACY_SSE.md b/docs/errors/MCPX_HTTP_LEGACY_SSE.md new file mode 100644 index 000000000..ff3bc6893 --- /dev/null +++ b/docs/errors/MCPX_HTTP_LEGACY_SSE.md @@ -0,0 +1,63 @@ +--- +id: MCPX_HTTP_LEGACY_SSE +title: MCPX_HTTP_LEGACY_SSE +sidebar_label: LEGACY_SSE +description: The endpoint rejected the streamable-HTTP initialize POST with a 4xx — the signature of a server that only speaks the older SSE transport. +--- + +# `MCPX_HTTP_LEGACY_SSE` + +**Severity:** error +**Domain:** HTTP + +## What happened + +mcpproxy opened the connection with a streamable-HTTP `initialize` POST and the +endpoint answered with a 4xx. That combination is the signature of a server +implementing only the **older SSE transport**, which expects a `GET` to open an +event stream and a separate POST endpoint for messages — so it rejects the +streamable-HTTP handshake outright. + +This is a **transport mismatch, not an authentication or routing failure**. It +is reported separately from `MCPX_HTTP_403` / `MCPX_HTTP_404` precisely because +those send you looking for a credential or URL problem that does not exist. + +## How to fix + +### Set the transport explicitly + +```jsonc +{ + "name": "my-server", + "protocol": "sse", // was "http" or "streamable-http" + "url": "https://example.com/sse" +} +``` + +### Check the URL path + +Legacy SSE servers usually publish the stream on a distinct path. If the +endpoint documents `/sse` and the config points at `/mcp` (or the bare origin), +correct the URL as well as the protocol. + +### Let mcpproxy pick + +Omitting `protocol`, or setting it to `auto`, makes mcpproxy negotiate — useful +when the server supports both and you do not want to pin a choice: + +```jsonc +{ "name": "my-server", "protocol": "auto", "url": "https://example.com/mcp" } +``` + +### Confirm the change + +```bash +mcpproxy upstream restart +mcpproxy upstream logs --follow +``` + +## Related + +- [`MCPX_HTTP_404`](MCPX_HTTP_404.md) — the endpoint genuinely does not exist +- [`MCPX_HTTP_403`](MCPX_HTTP_403.md) — the endpoint exists but refuses the caller +- [`MCPX_HTTP_CONN_REFUSED`](MCPX_HTTP_CONN_REFUSED.md) — nothing is listening at all diff --git a/docs/errors/README.md b/docs/errors/README.md index 10ac5f06d..c1b6305ea 100644 --- a/docs/errors/README.md +++ b/docs/errors/README.md @@ -63,6 +63,7 @@ Run `mcpproxy doctor list-codes` for the machine-readable list. - [`MCPX_HTTP_404`](MCPX_HTTP_404.md) — Not Found - [`MCPX_HTTP_5XX`](MCPX_HTTP_5XX.md) — Server error - [`MCPX_HTTP_CONN_REFUSED`](MCPX_HTTP_CONN_REFUSED.md) — Connection refused +- [`MCPX_HTTP_LEGACY_SSE`](MCPX_HTTP_LEGACY_SSE.md) — endpoint only speaks the legacy SSE transport ## Docker @@ -77,6 +78,7 @@ Run `mcpproxy doctor list-codes` for the machine-readable list. - [`MCPX_CONFIG_DEPRECATED_FIELD`](MCPX_CONFIG_DEPRECATED_FIELD.md) — deprecated field used - [`MCPX_CONFIG_PARSE_ERROR`](MCPX_CONFIG_PARSE_ERROR.md) — invalid JSON - [`MCPX_CONFIG_MISSING_SECRET`](MCPX_CONFIG_MISSING_SECRET.md) — secret reference unresolved +- [`MCPX_CONFIG_INVALID_COMMAND`](MCPX_CONFIG_INVALID_COMMAND.md) — command has nothing to run (e.g. `npx` with no package) ## Quarantine diff --git a/internal/diagnostics/classifier.go b/internal/diagnostics/classifier.go index 2b0245846..ae2a4a302 100644 --- a/internal/diagnostics/classifier.go +++ b/internal/diagnostics/classifier.go @@ -157,6 +157,13 @@ func classifyConfig(err error, _ ClassifierHints) Code { strings.Contains(msg, "secret reference") && (strings.Contains(msg, "not found") || strings.Contains(msg, "unresolved")), strings.Contains(msg, "unresolved secret"): return ConfigMissingSecret + // A package-runner command with nothing to run. This is mcpproxy's OWN + // pre-spawn validation message (internal/upstream/core/connection_stdio.go), + // so leaving it unclassified put a "Please file a bug report" CTA on a + // config typo the user can fix in one line. + case strings.Contains(msg, "has no args"), + strings.Contains(msg, "no args") && strings.Contains(msg, "required"): + return ConfigInvalidCommand } return "" } @@ -346,6 +353,16 @@ func classifyHTTP(err error, hints ClassifierHints) Code { return HTTPTimeout } + // A 4xx on the streamable-HTTP `initialize` POST is the legacy-SSE + // signature, not an auth or routing failure — the upstream layer says so in + // as many words. Matched BEFORE the generic status-text fallback below, + // which would otherwise claim it as a bare MCPX_HTTP_404/403 and send the + // user hunting for a credential problem that does not exist. + if strings.Contains(lmsg, "likely a legacy sse server") || + (strings.Contains(lmsg, "4xx for initialize") && strings.Contains(lmsg, "post")) { + return HTTPLegacySSE + } + // HTTP status text fallback. The upstream layer wraps non-2xx responses // as a plain string ("transport error: request failed with status 504: ..."). // The typed statusError path used by DiagnoseHTTPStatus() never fires for diff --git a/internal/diagnostics/classifier_selfmessages_test.go b/internal/diagnostics/classifier_selfmessages_test.go new file mode 100644 index 000000000..43bd1fa78 --- /dev/null +++ b/internal/diagnostics/classifier_selfmessages_test.go @@ -0,0 +1,91 @@ +package diagnostics + +import ( + "errors" + "testing" +) + +// Both errors below are mcpproxy's OWN wording, produced before or during the +// connect attempt — yet both classified as MCPX_UNKNOWN_UNCLASSIFIED, whose +// catalog entry tells the user to file a bug report against us. The strings are +// copied verbatim from a live v0.61.0 install. +func TestOwnErrorMessagesDoNotClassifyAsUnknown(t *testing.T) { + cases := []struct { + name string + err string + hints ClassifierHints + want Code + }{ + { + name: "package runner with no package to run", + err: `failed to connect: server "demo-filesystem": command "npx" has no args — the npm package to run (e.g. ["-y", "some-mcp-server"]) is required`, + hints: ClassifierHints{Transport: "stdio"}, + want: ConfigInvalidCommand, + }, + { + name: "uvx variant of the same validation failure", + err: `server "x": command "uvx" has no args — the Python package to run is required`, + hints: ClassifierHints{Transport: "stdio"}, + want: ConfigInvalidCommand, + }, + { + name: "streamable-HTTP handshake refused by a legacy SSE server", + err: "failed to connect: MCP initialize failed during no-auth strategy: transport error: server returned 4xx for initialize POST, likely a legacy SSE server", + hints: ClassifierHints{Transport: "http"}, + want: HTTPLegacySSE, + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got := Classify(errors.New(tc.err), tc.hints) + if got != tc.want { + t.Fatalf("Classify() = %q, want %q", got, tc.want) + } + if got == UnknownUnclassified { + t.Fatal("mcpproxy's own error message must never ask the user to file a bug") + } + }) + } +} + +// The legacy-SSE match must win over the generic HTTP status-text fallback: +// reading it as a bare 403/404 sends the user hunting for a credential problem +// that does not exist. +func TestLegacySSEBeatsGenericStatusText(t *testing.T) { + err := errors.New("transport error: request failed with status 404: server returned 4xx for initialize POST, likely a legacy SSE server") + if got := Classify(err, ClassifierHints{Transport: "http"}); got != HTTPLegacySSE { + t.Fatalf("Classify() = %q, want %q", got, HTTPLegacySSE) + } +} + +// Every code the classifier can return must be registered, or the API emits a +// diagnostic with no user message, no fix steps and no docs URL. +func TestNewCodesAreRegistered(t *testing.T) { + for _, c := range []Code{ConfigInvalidCommand, HTTPLegacySSE} { + entry, ok := Get(c) + if !ok { + t.Fatalf("%s is not registered in the catalog", c) + } + if entry.UserMessage == "" { + t.Errorf("%s has no user message", c) + } + if len(entry.FixSteps) == 0 { + t.Errorf("%s has no fix steps", c) + } + for _, step := range entry.FixSteps { + if step.Type == FixStepLink && step.URL == "" { + t.Errorf("%s has a link fix step with no URL", c) + } + } + } +} + +// A genuine 404 with no legacy-SSE marker must still classify as a plain 404 — +// the new rule must not swallow the generic HTTP status path. +func TestOrdinaryHTTPStatusesAreUnaffected(t *testing.T) { + err := errors.New("transport error: request failed with status 404: not found") + if got := Classify(err, ClassifierHints{Transport: "http"}); got != HTTPNotFound { + t.Fatalf("Classify() = %q, want %q", got, HTTPNotFound) + } +} diff --git a/internal/diagnostics/codes.go b/internal/diagnostics/codes.go index fee39d957..c3493c952 100644 --- a/internal/diagnostics/codes.go +++ b/internal/diagnostics/codes.go @@ -48,6 +48,12 @@ const ( HTTPServerErr Code = "MCPX_HTTP_5XX" HTTPConnRefuse Code = "MCPX_HTTP_CONN_REFUSED" HTTPTimeout Code = "MCPX_HTTP_TIMEOUT" + // HTTPLegacySSE: the endpoint rejected the streamable-HTTP `initialize` + // POST with a 4xx. That is the signature of a server that only speaks the + // older SSE transport, so the fix is a transport change in config — not a + // credential or reachability problem, which is why it must not fall through + // to a generic MCPX_HTTP_4xx or to MCPX_UNKNOWN_UNCLASSIFIED. + HTTPLegacySSE Code = "MCPX_HTTP_LEGACY_SSE" ) // DOCKER domain — Docker isolation subsystem failures. @@ -74,6 +80,12 @@ const ( ConfigDeprecatedField Code = "MCPX_CONFIG_DEPRECATED_FIELD" ConfigParseError Code = "MCPX_CONFIG_PARSE_ERROR" ConfigMissingSecret Code = "MCPX_CONFIG_MISSING_SECRET" + // ConfigInvalidCommand: the server's stdio `command`/`args` pair cannot + // spawn anything useful — e.g. a package-runner (`npx`, `uvx`) with no + // package to run. mcpproxy detects this itself before spawning, so the + // message is ours and the user can fix it in mcp_config.json; surfacing it + // as UNKNOWN told them to file a bug against us instead. + ConfigInvalidCommand Code = "MCPX_CONFIG_INVALID_COMMAND" ) // QUARANTINE domain — security quarantine failures. diff --git a/internal/diagnostics/registry.go b/internal/diagnostics/registry.go index 634027816..d77166564 100644 --- a/internal/diagnostics/registry.go +++ b/internal/diagnostics/registry.go @@ -258,6 +258,15 @@ func seedHTTP() { }, DocsURL: docsURL(HTTPTimeout), }) + register(CatalogEntry{ + Code: HTTPLegacySSE, + Severity: SeverityError, + UserMessage: "This endpoint rejected the streamable-HTTP handshake; it looks like a legacy SSE server.", + FixSteps: []FixStep{ + {Type: FixStepLink, Label: "Choosing the right transport", URL: docsURL(HTTPLegacySSE)}, + }, + DocsURL: docsURL(HTTPLegacySSE), + }) } // --- DOCKER -------------------------------------------------------------- @@ -356,6 +365,16 @@ func seedCONFIG() { }, DocsURL: docsURL(ConfigParseError), }) + register(CatalogEntry{ + Code: ConfigInvalidCommand, + Severity: SeverityError, + UserMessage: "This server's command has nothing to run — a package runner like npx or uvx needs the package name in \"args\".", + FixSteps: []FixStep{ + {Type: FixStepCommand, Label: "Show this server's config", Command: "mcpproxy upstream get -o json"}, + {Type: FixStepLink, Label: "Server configuration reference", URL: docsURL(ConfigInvalidCommand)}, + }, + DocsURL: docsURL(ConfigInvalidCommand), + }) register(CatalogEntry{ Code: ConfigMissingSecret, Severity: SeverityError, diff --git a/internal/upstream/core/client.go b/internal/upstream/core/client.go index 2b119adeb..214ee7b7d 100644 --- a/internal/upstream/core/client.go +++ b/internal/upstream/core/client.go @@ -339,7 +339,12 @@ func (c *Client) ListTools(ctx context.Context) ([]*config.ToolMetadata, error) listReq := mcp.ListToolsRequest{} toolsResult, err := client.ListTools(ctx, listReq) if err != nil { - c.logger.Error("Failed to list tools via direct call to upstream server", + // Debug, not Error: both callers above (managed.Client.ListTools and + // upstream.Manager.discoverTools) log this same failure, so logging it + // here made one transient sweep miss cost three ERROR lines. The + // outermost caller is the only layer that knows whether the failure + // matters — a periodic sweep just retries on the next cycle. + c.logger.Debug("Failed to list tools via direct call to upstream server", zap.String("server", c.config.Name), zap.Error(err)) return nil, fmt.Errorf("failed to list tools: %w", err) diff --git a/internal/upstream/listtools_logging_test.go b/internal/upstream/listtools_logging_test.go new file mode 100644 index 000000000..db0c5c527 --- /dev/null +++ b/internal/upstream/listtools_logging_test.go @@ -0,0 +1,137 @@ +package upstream + +import ( + "context" + "strings" + "testing" + "time" + + mcpserver "github.com/mark3labs/mcp-go/server" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "go.uber.org/zap" + "go.uber.org/zap/zapcore" + "go.uber.org/zap/zaptest/observer" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/secret" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/storage" +) + +// newObservedManager is newTestManager with a logger whose entries the test can +// inspect, at Debug so the downgraded sites are visible rather than filtered. +func newObservedManager(t *testing.T) (*Manager, *observer.ObservedLogs) { + t.Helper() + core, logs := observer.New(zapcore.DebugLevel) + tmpDir := t.TempDir() + cfg := &config.Config{DataDir: tmpDir} + storageManager, err := storage.NewBoltDB(tmpDir, zap.NewNop().Sugar()) + require.NoError(t, err) + t.Cleanup(func() { _ = storageManager.Close() }) + + m := NewManager(zap.New(core), cfg, storageManager, secret.NewResolver(), nil) + t.Cleanup(func() { m.DisconnectAll() }) + return m, logs +} + +// One ListTools failure used to be logged at ERROR three times — once each by +// core.Client, managed.Client and Manager.discoverTools. On an install with +// several stdio servers the periodic sweep hit this roughly once a minute per +// server, forever, which is what rotated main.log every couple of hours. +// +// The sweep deliberately does not markSwept on failure so the next cycle +// retries; a failure the code already plans to retry is a Warn at most, and it +// belongs to exactly one layer. +func TestListToolsFailureIsLoggedOnceAndNotAsError(t *testing.T) { + m, logs := newObservedManager(t) + t.Setenv("MCPPROXY_DISABLE_OAUTH", "true") + + upstream := newTestPromptUpstreamServer(t, "greeting") + testServer := mcpserver.NewTestStreamableHTTPServer(upstream) + + require.NoError(t, m.AddServerConfig("srv-a", &config.ServerConfig{ + Name: "server-a", + Protocol: "streamable-http", + URL: testServer.URL, + Enabled: true, + })) + client, ok := m.GetClient("srv-a") + require.True(t, ok) + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + require.NoError(t, client.Connect(ctx)) + + // Kill the upstream out from under a client that still believes it is + // connected — the exact shape of the transport-closed sweep miss. + testServer.Close() + logs.TakeAll() + + _, _ = m.DiscoverTools(context.Background()) + + // The three layers that each reported the SAME failed list operation. A + // state-transition log ("Connection error detected during ListTools, + // updating server state") is a different fact — it fires once when the + // client gives up on the connection — and is deliberately not counted here. + reportsTheListFailure := []string{ + "Failed to list tools via direct call to upstream server", // core.Client + "ListTools operation failed", // managed.Client + "Failed to list tools from client", // Manager.discoverTools + } + + var elevated []string + for _, e := range logs.All() { + if e.Level < zapcore.WarnLevel { + continue + } + for _, msg := range reportsTheListFailure { + if e.Message == msg { + elevated = append(elevated, e.Level.String()+": "+e.Message) + } + } + } + + assert.Len(t, elevated, 1, + "one failed ListTools must be reported by exactly one layer, got: %v", elevated) + for _, entry := range elevated { + assert.False(t, strings.HasPrefix(entry, "error:"), + "a sweep failure the manager retries next cycle must not be ERROR, got: %v", elevated) + } +} + +// The failure must still be visible: silencing all three layers would trade a +// log storm for an invisible outage. +func TestListToolsFailureIsStillReported(t *testing.T) { + m, logs := newObservedManager(t) + t.Setenv("MCPPROXY_DISABLE_OAUTH", "true") + + upstream := newTestPromptUpstreamServer(t, "greeting") + testServer := mcpserver.NewTestStreamableHTTPServer(upstream) + + require.NoError(t, m.AddServerConfig("srv-a", &config.ServerConfig{ + Name: "server-a", + Protocol: "streamable-http", + URL: testServer.URL, + Enabled: true, + })) + client, ok := m.GetClient("srv-a") + require.True(t, ok) + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + require.NoError(t, client.Connect(ctx)) + + testServer.Close() + logs.TakeAll() + + _, _ = m.DiscoverTools(context.Background()) + + found := false + for _, e := range logs.All() { + if e.Level >= zapcore.WarnLevel && strings.Contains(e.Message, "Failed to list tools from client") { + found = true + assert.Equal(t, zapcore.WarnLevel, e.Level, "the surviving log should be Warn") + } + } + assert.True(t, found, "the sweep miss must still be reported at Warn by the manager") +} diff --git a/internal/upstream/managed/client.go b/internal/upstream/managed/client.go index 81fd40b94..ff508a2e8 100644 --- a/internal/upstream/managed/client.go +++ b/internal/upstream/managed/client.go @@ -743,7 +743,11 @@ func (mc *Client) runListToolsAsLeader(listCtx context.Context, release func() b mc.publishListToolsResult(tools, err) if err != nil { - mc.logger.Error("ListTools operation failed", + // Debug for the same reason as the core layer: this is the middle of + // three logs of one failure. A ListTools miss that matters is either + // re-logged by the caller or promoted by the isConnectionError branch + // just below, which raises a Warn AND moves the state machine. + mc.logger.Debug("ListTools operation failed", zap.String("server", mc.GetConfig().Name), zap.Error(err)) diff --git a/internal/upstream/manager.go b/internal/upstream/manager.go index e47a169f7..7bc791ec9 100644 --- a/internal/upstream/manager.go +++ b/internal/upstream/manager.go @@ -1170,7 +1170,12 @@ func (m *Manager) discoverTools(ctx context.Context, dueOnly bool) ([]*config.To tools, err := client.ListTools(ctx) if err != nil { - m.logger.Error("Failed to list tools from client", + // Warn, not Error: markSwept below is deliberately skipped so the + // next sweep retries this server. A failure the code already plans + // to retry is not an error — and on a healthy install with several + // stdio servers this fired ~1x/min each, forever, which is what + // made main.log rotate every couple of hours. + m.logger.Warn("Failed to list tools from client", zap.String("id", snapshot.id), zap.String("server", snapshot.name), zap.Error(err)) diff --git a/native/macos/MCPProxy/MCPProxy/API/Models.swift b/native/macos/MCPProxy/MCPProxy/API/Models.swift index 5c80f72f5..2fd6fa7d5 100644 --- a/native/macos/MCPProxy/MCPProxy/API/Models.swift +++ b/native/macos/MCPProxy/MCPProxy/API/Models.swift @@ -353,6 +353,38 @@ struct ServerStatus: Codable, Identifiable, Equatable { return d.severity == "warn" || d.severity == "error" } + /// True when the server is held for quarantine review — an intentional + /// admin state, not a fault, exactly like `isOAuthLoginRequired`. + /// + /// mcpproxy still *attempts* a connection to a quarantined server so the + /// security scanner can export its tool definitions, and a failed attempt + /// leaves an error-severity diagnostic behind. That diagnostic used to tint + /// the menu-bar badge red while the very same payload reported + /// `health.level == "healthy"` / `admin_state == "quarantined"` — so the + /// menu header drew a calm yellow dot under a red menu-bar dot, and the + /// user could not clear it without approving or disabling the server. + /// + /// Both signals are checked: `quarantined` is the server's own flag and + /// `admin_state` is the cross-surface contract CLI/REST/Web-UI/tray share. + var isQuarantineReview: Bool { + quarantined || health?.adminState == "quarantined" + } + + /// Whether this server's diagnostic is allowed to tint the menu-bar badge. + /// + /// The badge answers "is something broken?", so a server sitting in a state + /// the user chose — or is being asked to act on calmly — must not turn it + /// red. Two such states exist, and both still carry an error-severity + /// diagnostic from the connect attempt that state implies: + /// waiting for sign-in, and held for quarantine review. + /// + /// Any future intentional non-connected state belongs here too, and must be + /// added to BOTH `worstDiagnosticSeverity` and `diagnosticCount` — they + /// share this predicate precisely so they cannot drift apart. + var isBadgeExempt: Bool { + isOAuthLoginRequired || isQuarantineReview + } + /// True when the server is in the OAuth login-required state (MCP-1819/T3). /// `health.action == "login"` is the stable, cross-surface contract that /// CLI/REST/Web-UI/tray all key off. In this state the server needs a calm, diff --git a/native/macos/MCPProxy/MCPProxy/MCPProxyApp.swift b/native/macos/MCPProxy/MCPProxy/MCPProxyApp.swift index 68dd59f19..5ab613481 100644 --- a/native/macos/MCPProxy/MCPProxy/MCPProxyApp.swift +++ b/native/macos/MCPProxy/MCPProxy/MCPProxyApp.swift @@ -42,6 +42,10 @@ final class AppController: NSObject, NSApplicationDelegate, NSWindowDelegate, NS var coreManager: CoreProcessManager? private var statusItem: NSStatusItem? + /// The corner severity dot overlaid on the status item button, when a + /// server severity is being badged. Held so `updateStatusIcon()` can reuse + /// one view across polls instead of rebuilding the button's subviews. + private var badgeDotView: TrayBadgeDotView? /// Where the tray menu lives. Assigned to `statusItem` at launch; injected /// by tests that drive the menu paths without a status bar item. @@ -896,16 +900,19 @@ final class AppController: NSObject, NSApplicationDelegate, NSWindowDelegate, NS /// Update the status bar icon based on app state. /// - /// The icon itself is always the plain MCPProxy template glyph; the state - /// rides beside it as a coloured glyph in the button's attributed title. - /// See `TrayStatusIcon.glyph(for:)` for why the badge cannot be composited - /// into the image. + /// The icon itself is always the plain MCPProxy template glyph. Core states + /// ride beside it as a glyph in the button's attributed title; a server + /// severity rides ON it as a small corner dot. See + /// `TrayStatusIcon.glyph(for:)` for why the badge cannot be composited into + /// the image itself, and `TrayBadgeDotView` for how the dot gets its colour + /// without breaking the template. /// - /// - Running OK: plain MCPProxy icon, no glyph + /// - Running OK: plain MCPProxy icon, nothing else /// - Stopped: ⏹ /// - Core error: ⚠ - /// - Server warn/error diagnostics: an amber/red dot (F1 — before the audit - /// the menu bar looked identical to all-healthy with five servers down) + /// - Server warn/error diagnostics: a small amber/red dot in the icon's + /// bottom-right corner (F1 — before the audit the menu bar looked + /// identical to all-healthy with five servers down) /// /// F2: every pass also publishes the state as text — accessibility /// description, accessibility label and tooltip — so a screen-reader user @@ -931,7 +938,7 @@ final class AppController: NSObject, NSApplicationDelegate, NSWindowDelegate, NS worstDiagnosticSeverity: appState.worstDiagnosticSeverity ) // The count must be of the severity being badged, over the same - // (enabled, non-OAuth) set `worstDiagnosticSeverity` considers. + // (enabled, non-exempt) set `worstDiagnosticSeverity` considers. let badgedCount: Int if case .severity(let severity) = badge { badgedCount = appState.diagnosticCount(severity: severity.rawValue) @@ -950,27 +957,62 @@ final class AppController: NSObject, NSApplicationDelegate, NSWindowDelegate, NS base.accessibilityDescription = label button.image = base - // Show state indicator as text next to icon (keeps icon as pure template) + // Core states stay as text next to the icon (keeps icon a pure + // template). ⏹/⚠ take the menu bar's own label colour so they stay + // legible in both appearances. let glyph = TrayStatusIcon.glyph(for: badge) if glyph.isEmpty { button.attributedTitle = NSAttributedString(string: "") button.title = "" } else { - // Only the severity dot is coloured; ⏹/⚠ keep the menu bar's own - // label colour so they stay legible in both appearances. - var attributes: [NSAttributedString.Key: Any] = [ - .font: NSFont.systemFont(ofSize: 11) - ] - if case .severity(let severity) = badge { - attributes[.foregroundColor] = severity == .error ? NSColor.systemRed : NSColor.systemOrange - } - button.attributedTitle = NSAttributedString(string: " " + glyph, attributes: attributes) + button.attributedTitle = NSAttributedString( + string: " " + glyph, + attributes: [.font: NSFont.systemFont(ofSize: 11)]) } + // Server severity rides ON the icon as a corner dot. + updateBadgeDot(on: button, severity: TrayStatusIcon.dotSeverity(for: badge)) + button.toolTip = label button.setAccessibilityLabel(label) } + /// Attach / update / remove the corner badge dot on the status item button. + /// + /// The dot is a SUBVIEW rather than pixels composited into `button.image` + /// because that image must stay `isTemplate` to track the light/dark menu + /// bar and to invert correctly while the menu is open — and a template + /// image is re-rendered monochrome, so a red dot drawn into it would come + /// back black. A sibling view is the only place a colour survives all three + /// appearances. + /// + /// The view is created once and reused: rebuilding it on every state poll + /// would thrash the button's subview list several times a second. + private func updateBadgeDot(on button: NSStatusBarButton, severity: TrayIconSeverity?) { + guard let severity else { + badgeDotView?.removeFromSuperview() + badgeDotView = nil + return + } + + let dot: TrayBadgeDotView + if let existing = badgeDotView, existing.superview === button { + dot = existing + } else { + badgeDotView?.removeFromSuperview() + dot = TrayBadgeDotView(frame: .zero) + button.addSubview(dot) + badgeDotView = dot + } + + // Bottom-right of the 18x18 icon, which AppKit centres in the button. + // The maths lives in TrayStatusIcon so it can be tested without a live + // menu bar (see TrayBadgeDotTests). + dot.frame = TrayStatusIcon.badgeDotFrame(inButtonSize: button.bounds.size) + dot.autoresizingMask = [.minXMargin, .maxYMargin] + dot.fillColor = severity == .error ? .systemRed : .systemOrange + } + // MARK: - Menu Building (AppKit NSMenu — no SwiftUI) /// Rebuild the entire NSMenu from current appState. diff --git a/native/macos/MCPProxy/MCPProxy/Menu/TrayBadgeDotView.swift b/native/macos/MCPProxy/MCPProxy/Menu/TrayBadgeDotView.swift new file mode 100644 index 000000000..c6b676c26 --- /dev/null +++ b/native/macos/MCPProxy/MCPProxy/Menu/TrayBadgeDotView.swift @@ -0,0 +1,67 @@ +// TrayBadgeDotView.swift +// MCPProxy +// +// The small coloured dot overlaid on the bottom-right corner of the menu-bar +// icon when a server carries a warn/error diagnostic. + +import AppKit + +/// A coloured badge dot drawn over the status item's template icon. +/// +/// Why a subview and not pixels in `button.image`: an `NSStatusItem` image must +/// stay `isTemplate` so AppKit re-tints it for light/dark menu bars and inverts +/// it while the menu is open. Template rendering forces every pixel to the +/// menu-bar's own colour, so a red dot composited into the image comes back +/// black. A sibling view is drawn after the template pass and keeps its colour +/// in all three appearances. +final class TrayBadgeDotView: NSView { + + /// The dot's fill. Setting it redraws; setting it to the same value is a + /// no-op so the status poll does not schedule redundant redraws. + var fillColor: NSColor = .systemRed { + didSet { + guard fillColor != oldValue else { return } + needsDisplay = true + } + } + + override init(frame frameRect: NSRect) { + super.init(frame: frameRect) + wantsLayer = true + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("TrayBadgeDotView is created in code, never from a nib") + } + + /// The dot is decoration on a button. Without this it would swallow the + /// clicks that open the menu wherever it overlaps the icon — a status item + /// with a dead corner. + override func hitTest(_ point: NSPoint) -> NSView? { nil } + + /// Decoration must never take focus or appear as a separate element to + /// VoiceOver: the button already publishes the full state as its + /// accessibility label (`TrayStatusIcon.accessibilityLabel`), and a second, + /// unlabelled element beside it would just be noise. + override func accessibilityIsIgnored() -> Bool { true } + + override func draw(_ dirtyRect: NSRect) { + let rect = bounds.insetBy(dx: 0.5, dy: 0.5) + guard rect.width > 0, rect.height > 0 else { return } + + let path = NSBezierPath(ovalIn: rect) + fillColor.setFill() + path.fill() + + // A darker rim of the fill's own hue, so the dot still reads as a + // distinct shape where it overlaps the icon glyph. Deliberately NOT the + // menu-bar background: that is translucent over the user's wallpaper + // and has no colour this view can name. + if let rim = fillColor.blended(withFraction: 0.35, of: .black) { + rim.setStroke() + path.lineWidth = 1 + path.stroke() + } + } +} diff --git a/native/macos/MCPProxy/MCPProxy/Menu/TrayPresentation.swift b/native/macos/MCPProxy/MCPProxy/Menu/TrayPresentation.swift index 5215af69e..973b95ec3 100644 --- a/native/macos/MCPProxy/MCPProxy/Menu/TrayPresentation.swift +++ b/native/macos/MCPProxy/MCPProxy/Menu/TrayPresentation.swift @@ -50,22 +50,77 @@ enum TrayStatusIcon { } } - /// The glyph drawn beside the template icon. Empty for `.none`. + /// The glyph drawn BESIDE the template icon. Empty for `.none` and for + /// `.severity`, which is drawn as a corner dot instead (see `dotSeverity`). /// /// Deliberately text, not a composited image: an NSStatusItem image must /// stay `isTemplate` to follow the light/dark menu bar, and a template /// image is re-rendered monochrome — a coloured dot drawn into it would /// come back black. The button's attributed title is the one place a - /// colour survives, and the existing ⏹ / ⚠ states already live there. + /// colour survives, and the ⏹ / ⚠ core states live there. + /// + /// `.severity` used to live here too, as a full-size "●" plus a leading + /// space. That widened the status item by roughly a character and read as a + /// second icon rather than a badge on the first. It now rides as a small + /// overlay dot in the icon's bottom-right corner, which is what a badge + /// looks like everywhere else on the platform — so this returns "" for it + /// and `dotSeverity(for:)` is what the button acts on. static func glyph(for badge: TrayIconBadge) -> String { switch badge { case .none: return "" case .stopped: return "⏹" case .coreError: return "⚠" - case .severity: return "●" + case .severity: return "" } } + /// The severity to draw as a corner dot over the icon, or nil for no dot. + /// + /// Only `.severity` badges: a stopped or erroring CORE is about the proxy + /// itself rather than one server, so it keeps its full-size glyph — the + /// distinction is worth the width for a state that means "nothing is + /// working", and collapsing it into the same dot would lose it. + static func dotSeverity(for badge: TrayIconBadge) -> TrayIconSeverity? { + if case .severity(let severity) = badge { return severity } + return nil + } + + /// Every badge must be visible somehow: as a glyph beside the icon, as a + /// corner dot, or both. A badge that is neither is an invisible state. + static func isVisible(_ badge: TrayIconBadge) -> Bool { + if badge == .none { return true } + return !glyph(for: badge).isEmpty || dotSeverity(for: badge) != nil + } + + /// Default geometry for the corner dot. 6pt against an 18pt icon is small + /// enough to read as a badge rather than a second symbol — the complaint + /// that prompted the change was that a full-size "●" beside the icon was + /// simply too big. + static let badgeDotDiameter: CGFloat = 6 + static let statusIconSide: CGFloat = 18 + + /// Where the corner dot sits inside the status item button, in the button's + /// own (bottom-left origin) coordinates. + /// + /// Pure maths so the placement is testable without a live menu bar — this + /// machine cannot screenshot the status item without a Screen Recording + /// grant, and "it looked right once" is not a regression test. + /// + /// AppKit centres the icon in the button, so the dot is anchored to the + /// icon's bottom-right corner rather than the button's: the button is wider + /// than the icon, and hanging the dot off the button's edge would float it + /// away from the glyph it badges. + static func badgeDotFrame(inButtonSize buttonSize: CGSize, + iconSide: CGFloat = statusIconSide, + diameter: CGFloat = badgeDotDiameter) -> CGRect { + let originX = (buttonSize.width - iconSide) / 2 + let originY = (buttonSize.height - iconSide) / 2 + return CGRect(x: originX + iconSide - diameter, + y: originY, + width: diameter, + height: diameter) + } + /// F2 · What VoiceOver and the tooltip say. `summary` is /// `AppState.statusSummary` ("13/29 servers, 942 tools"). static func accessibilityLabel(for badge: TrayIconBadge, summary: String, attentionCount: Int) -> String { diff --git a/native/macos/MCPProxy/MCPProxy/State/AppState.swift b/native/macos/MCPProxy/MCPProxy/State/AppState.swift index 9ad9e6491..7f95e04b1 100644 --- a/native/macos/MCPProxy/MCPProxy/State/AppState.swift +++ b/native/macos/MCPProxy/MCPProxy/State/AppState.swift @@ -320,25 +320,27 @@ final class AppState: ObservableObject { /// How many servers carry the severity the tray icon is currently badging. /// - /// Must agree with `worstDiagnosticSeverity` exactly, or the status item - /// says "4 server errors" over a badge that counted three: that property - /// looks only at ENABLED servers, while `serversWithDiagnostic` includes - /// the disabled ones and both severities. + /// Must agree with `worstDiagnosticSeverity` exactly — including its + /// `isBadgeExempt` filter — or the status item says "4 server errors" over + /// a badge that counted three: that property looks only at ENABLED servers, + /// while `serversWithDiagnostic` includes the disabled ones and both + /// severities. func diagnosticCount(severity: String) -> Int { servers.filter { - $0.enabled && !$0.isOAuthLoginRequired && $0.diagnostic?.severity == severity + $0.enabled && !$0.isBadgeExempt && $0.diagnostic?.severity == severity }.count } /// Highest-severity diagnostic across enabled servers. Returns nil when /// no diagnostics are attached. Used by TrayIcon to colour the badge. /// - /// MCP-1819/T3: OAuth login-required servers are skipped so a server that - /// merely needs sign-in does not tint the tray icon badge red/orange — the - /// calm "Needs Attention / Sign in" path owns that state instead. + /// Servers in an INTENTIONAL non-connected state are skipped (see + /// `ServerStatus.isBadgeExempt`) so neither a pending sign-in nor a + /// quarantine review tints the tray icon badge red/orange — the calm + /// "Needs Attention" path owns those states instead. var worstDiagnosticSeverity: String? { var sawWarn = false - for srv in servers where srv.enabled && !srv.isOAuthLoginRequired { + for srv in servers where srv.enabled && !srv.isBadgeExempt { guard let d = srv.diagnostic else { continue } if d.severity == "error" { return "error" } if d.severity == "warn" { sawWarn = true } diff --git a/native/macos/MCPProxy/MCPProxyTests/TrayBadgeDotTests.swift b/native/macos/MCPProxy/MCPProxyTests/TrayBadgeDotTests.swift new file mode 100644 index 000000000..cfab44966 --- /dev/null +++ b/native/macos/MCPProxy/MCPProxyTests/TrayBadgeDotTests.swift @@ -0,0 +1,106 @@ +// TrayBadgeDotTests.swift +// MCPProxyTests +// +// The severity badge moved from a full-size "● " beside the icon to a small dot +// in the icon's bottom-right corner. These assert the geometry and the drawing, +// because the status item itself cannot be screenshotted without a Screen +// Recording grant — "it looked right once" is not a regression test. + +import AppKit +import XCTest +@testable import MCPProxy + +final class TrayBadgeDotTests: XCTestCase { + + /// A 36x22 button is the size AppKit gives a status item holding an 18pt + /// icon and no title — the shape this actually ships in. + private static let buttonSize = CGSize(width: 36, height: 22) + + // MARK: - Geometry + + func testTheDotSitsInTheBottomRightOfTheIconNotTheButton() { + let frame = TrayStatusIcon.badgeDotFrame(inButtonSize: Self.buttonSize) + let iconOriginX = (Self.buttonSize.width - TrayStatusIcon.statusIconSide) / 2 + let iconOriginY = (Self.buttonSize.height - TrayStatusIcon.statusIconSide) / 2 + + XCTAssertEqual(frame.maxX, iconOriginX + TrayStatusIcon.statusIconSide, accuracy: 0.01, + "the dot's right edge must meet the ICON's right edge") + XCTAssertEqual(frame.minY, iconOriginY, accuracy: 0.01, + "the dot's bottom must meet the icon's bottom") + } + + /// The complaint was that the badge was too big. 6pt on an 18pt icon is a + /// third of its width — a badge, not a second symbol. + func testTheDotIsSmallRelativeToTheIcon() { + let frame = TrayStatusIcon.badgeDotFrame(inButtonSize: Self.buttonSize) + XCTAssertEqual(frame.width, frame.height, "the badge is a circle") + XCTAssertLessThanOrEqual(frame.width, TrayStatusIcon.statusIconSide / 2.5, + "a dot larger than this reads as a second icon") + XCTAssertGreaterThanOrEqual(frame.width, 4, "below this it is invisible on a retina menu bar") + } + + /// It must stay inside the button whatever width AppKit hands us, or it is + /// clipped away on one side and silently invisible. + func testTheDotStaysInsideTheButtonAtAnyWidth() { + for width in [24.0, 30.0, 36.0, 48.0] as [CGFloat] { + let size = CGSize(width: width, height: 22) + let frame = TrayStatusIcon.badgeDotFrame(inButtonSize: size) + XCTAssertGreaterThanOrEqual(frame.minX, 0, "clipped left at width \(width)") + XCTAssertLessThanOrEqual(frame.maxX, width, "clipped right at width \(width)") + XCTAssertGreaterThanOrEqual(frame.minY, 0, "clipped bottom at width \(width)") + XCTAssertLessThanOrEqual(frame.maxY, size.height, "clipped top at width \(width)") + } + } + + // MARK: - Drawing + + /// Renders the view offscreen and reads the centre pixel back. This is the + /// assertion a screenshot would have made. + private func centrePixel(of view: TrayBadgeDotView) -> NSColor? { + guard let rep = view.bitmapImageRepForCachingDisplay(in: view.bounds) else { return nil } + view.cacheDisplay(in: view.bounds, to: rep) + return rep.colorAt(x: Int(view.bounds.midX), y: Int(view.bounds.midY)) + } + + func testAnErrorDrawsARedDot() { + let view = TrayBadgeDotView(frame: NSRect(x: 0, y: 0, width: 12, height: 12)) + view.fillColor = .systemRed + + guard let colour = centrePixel(of: view)?.usingColorSpace(.sRGB) else { + return XCTFail("nothing was drawn") + } + XCTAssertGreaterThan(colour.redComponent, 0.5, "the dot is not red") + XCTAssertGreaterThan(colour.redComponent, colour.greenComponent) + XCTAssertGreaterThan(colour.redComponent, colour.blueComponent) + XCTAssertGreaterThan(colour.alphaComponent, 0.9, "the dot must be opaque") + } + + func testAWarningDrawsAnAmberDotNotARedOne() { + let view = TrayBadgeDotView(frame: NSRect(x: 0, y: 0, width: 12, height: 12)) + view.fillColor = .systemOrange + + guard let colour = centrePixel(of: view)?.usingColorSpace(.sRGB) else { + return XCTFail("nothing was drawn") + } + XCTAssertGreaterThan(colour.greenComponent, 0.25, + "amber must be distinguishable from red at a glance") + XCTAssertGreaterThan(colour.redComponent, colour.blueComponent) + } + + // MARK: - It is decoration, not a control + + /// The dot overlaps the icon. Without hit-test passthrough it would swallow + /// the clicks that open the menu, leaving a dead corner on the status item. + func testTheDotDoesNotSwallowClicks() { + let view = TrayBadgeDotView(frame: NSRect(x: 0, y: 0, width: 12, height: 12)) + XCTAssertNil(view.hitTest(NSPoint(x: 6, y: 6)), + "a click on the badge must reach the button underneath") + } + + /// The button already publishes the whole state as its accessibility label; + /// a second unlabelled element beside it is noise for a VoiceOver user. + func testTheDotIsInvisibleToAccessibility() { + let view = TrayBadgeDotView(frame: NSRect(x: 0, y: 0, width: 12, height: 12)) + XCTAssertTrue(view.accessibilityIsIgnored()) + } +} diff --git a/native/macos/MCPProxy/MCPProxyTests/TrayBadgeExemptionTests.swift b/native/macos/MCPProxy/MCPProxyTests/TrayBadgeExemptionTests.swift new file mode 100644 index 000000000..3eabe0ea5 --- /dev/null +++ b/native/macos/MCPProxy/MCPProxyTests/TrayBadgeExemptionTests.swift @@ -0,0 +1,153 @@ +// TrayBadgeExemptionTests.swift +// MCPProxyTests +// +// A quarantined server used to tint the menu-bar badge red forever. The +// fixtures here are the live v0.61.0 /api/v1/servers payloads that did it. + +import XCTest +@testable import MCPProxy + +final class TrayBadgeExemptionTests: XCTestCase { + + // MARK: - Fixtures (verbatim shapes from a live install) + + /// A quarantined server that mcpproxy connected for scanner inspection and + /// failed to reach. Note the contradiction inside ONE payload: the health + /// block says healthy/quarantined, the diagnostic says error. + private static func quarantinedServer(name: String) -> ServerStatus { + decode(""" + { + "id": "\(name)", "name": "\(name)", "protocol": "http", + "enabled": true, "connected": false, "quarantined": true, "tool_count": 0, + "error_code": "MCPX_UNKNOWN_UNCLASSIFIED", + "diagnostic": {"code": "MCPX_UNKNOWN_UNCLASSIFIED", "severity": "error", "summary": "boom"}, + "health": {"level": "healthy", "admin_state": "quarantined", + "summary": "Quarantined for review", "action": "approve"} + } + """) + } + + private static func loginRequiredServer(name: String) -> ServerStatus { + decode(""" + { + "id": "\(name)", "name": "\(name)", "protocol": "http", + "enabled": true, "connected": false, "quarantined": false, "tool_count": 0, + "error_code": "MCPX_OAUTH_LOGIN_REQUIRED", + "diagnostic": {"code": "MCPX_OAUTH_LOGIN_REQUIRED", "severity": "error", "summary": "sign in"}, + "health": {"level": "degraded", "admin_state": "enabled", + "summary": "Sign-in required", "action": "login"} + } + """) + } + + /// A genuinely broken server: `command: "npx"` with no args. + private static func brokenServer(name: String) -> ServerStatus { + decode(""" + { + "id": "\(name)", "name": "\(name)", "protocol": "stdio", + "enabled": true, "connected": false, "quarantined": false, "tool_count": 0, + "error_code": "MCPX_CONFIG_INVALID_COMMAND", + "diagnostic": {"code": "MCPX_CONFIG_INVALID_COMMAND", "severity": "error", "summary": "no args"}, + "health": {"level": "unhealthy", "admin_state": "enabled", + "summary": "failed to connect", "action": "restart"} + } + """) + } + + private static func decode(_ json: String) -> ServerStatus { + // swiftlint:disable:next force_try + try! JSONDecoder().decode(ServerStatus.self, from: json.data(using: .utf8)!) + } + + // MARK: - The bug + + /// The reported symptom: a red menu-bar dot that nothing the user did could + /// clear, on an install whose only error-severity diagnostics belonged to + /// quarantined servers. + @MainActor + func testAQuarantinedServerDoesNotTintTheBadge() { + let state = AppState() + state.servers = [Self.quarantinedServer(name: "everything")] + + XCTAssertNil(state.worstDiagnosticSeverity, + "a server held for review is an intentional state, not a fault") + XCTAssertEqual(state.diagnosticCount(severity: "error"), 0) + XCTAssertEqual( + TrayStatusIcon.badge(isStopped: false, hasCoreError: false, + worstDiagnosticSeverity: state.worstDiagnosticSeverity), + .none) + } + + /// The same exemption that already existed for sign-in, still working — + /// this is the precedent the quarantine case was missing. + @MainActor + func testALoginRequiredServerStillDoesNotTintTheBadge() { + let state = AppState() + state.servers = [Self.loginRequiredServer(name: "cloudflare-graphql")] + XCTAssertNil(state.worstDiagnosticSeverity) + } + + /// The exemption must not swallow real faults: a misconfigured server is + /// exactly what the badge exists to show. + @MainActor + func testAGenuinelyBrokenServerStillTintsTheBadgeRed() { + let state = AppState() + state.servers = [ + Self.quarantinedServer(name: "everything"), + Self.loginRequiredServer(name: "cloudflare-graphql"), + Self.brokenServer(name: "demo-filesystem"), + ] + XCTAssertEqual(state.worstDiagnosticSeverity, "error") + XCTAssertEqual(state.diagnosticCount(severity: "error"), 1, + "only the misconfigured server counts toward the badge") + } + + /// The two surfaces disagreeing is what made this so confusing to read: the + /// menu header drew a calm yellow dot from `serversNeedingAttention` while + /// the menu-bar badge drew red from `worstDiagnosticSeverity`, off the same + /// payload. Quarantine must still ask for attention — just not in red. + @MainActor + func testQuarantineStillAsksForAttentionJustNotInRed() { + let state = AppState() + state.servers = [Self.quarantinedServer(name: "everything")] + + XCTAssertEqual(state.serversNeedingAttention.count, 1, + "the user still has to approve it — the menu must say so") + XCTAssertNil(state.worstDiagnosticSeverity, + "but the menu bar must not scream about it") + } + + /// `diagnosticCount` and `worstDiagnosticSeverity` must filter identically, + /// or the tooltip says "1 server error" over a badge that is not drawn. + @MainActor + func testTheSpokenCountAgreesWithTheBadgeUnderExemptions() { + let state = AppState() + state.servers = [ + Self.quarantinedServer(name: "q1"), + Self.quarantinedServer(name: "q2"), + Self.loginRequiredServer(name: "l1"), + ] + XCTAssertNil(state.worstDiagnosticSeverity) + XCTAssertEqual(state.diagnosticCount(severity: "error"), 0, + "nothing is badged, so nothing may be counted") + } + + /// `quarantined: true` alone is enough, even if the health block is absent + /// or stale — the two signals are checked independently on purpose. + @MainActor + func testTheQuarantineFlagAloneIsEnough() { + let server = Self.decode(""" + { + "id": "q", "name": "q", "protocol": "http", + "enabled": true, "connected": false, "quarantined": true, "tool_count": 0, + "diagnostic": {"code": "MCPX_TEST", "severity": "error", "summary": "boom"} + } + """) + XCTAssertTrue(server.isQuarantineReview) + XCTAssertTrue(server.isBadgeExempt) + + let state = AppState() + state.servers = [server] + XCTAssertNil(state.worstDiagnosticSeverity) + } +} diff --git a/native/macos/MCPProxy/MCPProxyTests/TrayPresentationTests.swift b/native/macos/MCPProxy/MCPProxyTests/TrayPresentationTests.swift index 342aac745..954299d3c 100644 --- a/native/macos/MCPProxy/MCPProxyTests/TrayPresentationTests.swift +++ b/native/macos/MCPProxy/MCPProxyTests/TrayPresentationTests.swift @@ -42,12 +42,44 @@ final class TrayPresentationTests: XCTestCase { .coreError) } - func testEveryBadgeHasItsOwnGlyph() { - let glyphs = [TrayIconBadge.stopped, .coreError, .severity(.warn)].map(TrayStatusIcon.glyph(for:)) + /// The two CORE states keep distinct full-size glyphs; server severity does + /// not use a glyph at all any more (it is a corner dot), so the uniqueness + /// rule applies to the states that still draw text. + func testEveryCoreBadgeHasItsOwnGlyph() { + let glyphs = [TrayIconBadge.stopped, .coreError].map(TrayStatusIcon.glyph(for:)) XCTAssertEqual(Set(glyphs).count, glyphs.count, "two states drawn identically is no state at all") XCTAssertFalse(glyphs.contains(""), "a badged state with no glyph is invisible") } + /// The whole point of the corner-dot change: a server severity must NOT + /// widen the status item with a full-size "● " beside the icon. + func testServerSeverityDrawsNoGlyphBesideTheIcon() { + XCTAssertEqual(TrayStatusIcon.glyph(for: .severity(.error)), "") + XCTAssertEqual(TrayStatusIcon.glyph(for: .severity(.warn)), "") + } + + func testServerSeverityDrawsACornerDot() { + XCTAssertEqual(TrayStatusIcon.dotSeverity(for: .severity(.error)), .error) + XCTAssertEqual(TrayStatusIcon.dotSeverity(for: .severity(.warn)), .warn) + } + + /// A core outage is about the proxy, not one server — it keeps the wider + /// glyph rather than collapsing into the same dot, which would lose the + /// distinction between "nothing works" and "one server is unhappy". + func testCoreStatesDoNotUseTheCornerDot() { + XCTAssertNil(TrayStatusIcon.dotSeverity(for: .stopped)) + XCTAssertNil(TrayStatusIcon.dotSeverity(for: .coreError)) + XCTAssertNil(TrayStatusIcon.dotSeverity(for: .none)) + } + + /// Moving a state between the glyph and the dot must never drop it: every + /// badge has to be visible through one channel or the other. + func testNoBadgeIsInvisible() { + for badge: TrayIconBadge in [.none, .stopped, .coreError, .severity(.warn), .severity(.error)] { + XCTAssertTrue(TrayStatusIcon.isVisible(badge), "\(badge) is drawn nowhere") + } + } + // MARK: - F2 · Spoken, not just drawn func testTheStatusItemSaysWhatIsWrongInWords() { diff --git a/website/sidebars.js b/website/sidebars.js index 416f855e1..2d3a38e47 100644 --- a/website/sidebars.js +++ b/website/sidebars.js @@ -186,6 +186,7 @@ const sidebars = { 'errors/MCPX_HTTP_404', 'errors/MCPX_HTTP_5XX', 'errors/MCPX_HTTP_CONN_REFUSED', + 'errors/MCPX_HTTP_LEGACY_SSE', ], }, { @@ -206,6 +207,7 @@ const sidebars = { 'errors/MCPX_CONFIG_DEPRECATED_FIELD', 'errors/MCPX_CONFIG_PARSE_ERROR', 'errors/MCPX_CONFIG_MISSING_SECRET', + 'errors/MCPX_CONFIG_INVALID_COMMAND', ], }, { From 5e773a98a18d50ac553e2f53cf80c64ada786e17 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Fri, 28 Aug 2026 08:49:07 +0300 Subject: [PATCH 2/4] fix(tray): anchor the badge dot to the icon, not the button MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Cross-model review (opencode, gpt-5.6-sol) caught a real defect in the corner-dot badge: it was a 6x6 subview positioned from `button.bounds` at update time and pinned with `[.minXMargin, .maxYMargin]`. That anchors to the BUTTON's bottom-right, but the dot belongs to the CENTRED 18pt icon, and it broke in two independent ways. * Rate mismatch. When the status button shrinks by N, a right-pinned subview moves left by N while the centred icon's right edge moves left by only N/2 — the badge slides off the glyph it is badging. * Stale bounds. NSStatusItem is variableLength and resizes asynchronously, so the `button.bounds` read immediately after clearing `attributedTitle` (which updateStatusIcon does, in the same pass) is still the old, wider value. The dot is then laid out against an icon centre that no longer exists. The overlay now fills the button, autoresizes with `[.width, .height]`, and computes the dot inside `draw(_:)` from its own live bounds. Any resize simply repaints in the right place, which removes both failure modes rather than patching either. `hitTest` already returned nil, which is what keeps the now-full-size overlay from swallowing every click. Note `needsDisplayOnBoundsChange` is a CALayer property and does not exist on NSView — the review suggested it and it does not compile. `setFrameSize` is overridden instead. Tests The drawing tests now RENDER the view and scan the bitmap for the pixels it actually painted, converting device pixels to points, rather than sampling one computed point. The earlier version guessed the bitmap's y-flip, read a transparent pixel, and would have reported "the view drew nothing" as a colour failure. Scanning asserts position, colour and restraint together and survives a geometry retune. Added: - the dot tracks the icon across button widths (the regression above) - a resize re-renders it in its new place - only the corner dot is painted, never a wash over the whole icon --- .../macos/MCPProxy/MCPProxy/MCPProxyApp.swift | 13 +- .../MCPProxy/Menu/TrayBadgeDotView.swift | 39 +++++- .../MCPProxyTests/TrayBadgeDotTests.swift | 121 ++++++++++++++++-- 3 files changed, 151 insertions(+), 22 deletions(-) diff --git a/native/macos/MCPProxy/MCPProxy/MCPProxyApp.swift b/native/macos/MCPProxy/MCPProxy/MCPProxyApp.swift index 5ab613481..c59dae110 100644 --- a/native/macos/MCPProxy/MCPProxy/MCPProxyApp.swift +++ b/native/macos/MCPProxy/MCPProxy/MCPProxyApp.swift @@ -1005,11 +1005,14 @@ final class AppController: NSObject, NSApplicationDelegate, NSWindowDelegate, NS badgeDotView = dot } - // Bottom-right of the 18x18 icon, which AppKit centres in the button. - // The maths lives in TrayStatusIcon so it can be tested without a live - // menu bar (see TrayBadgeDotTests). - dot.frame = TrayStatusIcon.badgeDotFrame(inButtonSize: button.bounds.size) - dot.autoresizingMask = [.minXMargin, .maxYMargin] + // The overlay covers the WHOLE button and works out where the dot goes + // at draw time, from its own live bounds. A small subview pinned to the + // corner is wrong here on two counts — the button resizes + // asynchronously (so `bounds` read now can be stale) and the dot is + // anchored to the CENTRED icon, which moves at half the rate of the + // button's right edge. See TrayBadgeDotView's type comment. + dot.frame = button.bounds + dot.autoresizingMask = [.width, .height] dot.fillColor = severity == .error ? .systemRed : .systemOrange } diff --git a/native/macos/MCPProxy/MCPProxy/Menu/TrayBadgeDotView.swift b/native/macos/MCPProxy/MCPProxy/Menu/TrayBadgeDotView.swift index c6b676c26..be3a9576c 100644 --- a/native/macos/MCPProxy/MCPProxy/Menu/TrayBadgeDotView.swift +++ b/native/macos/MCPProxy/MCPProxy/Menu/TrayBadgeDotView.swift @@ -14,6 +14,23 @@ import AppKit /// menu-bar's own colour, so a red dot composited into the image comes back /// black. A sibling view is drawn after the template pass and keeps its colour /// in all three appearances. +/// +/// Why the view fills the WHOLE button rather than being a 6x6 view positioned +/// at the corner: the dot is anchored to the centred 18pt ICON, not to the +/// button, and the button's width changes (it is `variableLength`, and the core +/// -state glyph comes and goes from `attributedTitle`). A small right-pinned +/// subview breaks that anchor twice over — +/// +/// * `[.minXMargin, .maxYMargin]` pins to the BUTTON's bottom-right, so when +/// the button shrinks by N the dot moves left by N while the centred icon's +/// right edge moves left by only N/2; and +/// * `NSStatusItem` resizes asynchronously, so `button.bounds` read straight +/// after clearing `attributedTitle` is still the old, wider value — the dot +/// is laid out against an icon centre that no longer exists. +/// +/// Filling the bounds and computing the dot inside `draw(_:)` from the CURRENT +/// bounds removes both failure modes: any resize just redraws in the right +/// place. (Cross-model review, gpt-5.6-sol.) final class TrayBadgeDotView: NSView { /// The dot's fill. Setting it redraws; setting it to the same value is a @@ -30,14 +47,26 @@ final class TrayBadgeDotView: NSView { wantsLayer = true } + /// The dot's position is derived from `bounds` at draw time, so a resize + /// MUST repaint or the badge is left at the previous geometry. + /// + /// This is the NSView spelling of it. `needsDisplayOnBoundsChange` is a + /// CALayer property and does not exist on NSView — reaching for it here + /// simply fails to compile. + override func setFrameSize(_ newSize: NSSize) { + let changed = newSize != frame.size + super.setFrameSize(newSize) + if changed { needsDisplay = true } + } + @available(*, unavailable) required init?(coder: NSCoder) { fatalError("TrayBadgeDotView is created in code, never from a nib") } - /// The dot is decoration on a button. Without this it would swallow the - /// clicks that open the menu wherever it overlaps the icon — a status item - /// with a dead corner. + /// The view covers the whole button, so this is what keeps the status item + /// clickable at all: without it the badge would swallow every click that + /// opens the menu. override func hitTest(_ point: NSPoint) -> NSView? { nil } /// Decoration must never take focus or appear as a separate element to @@ -47,7 +76,9 @@ final class TrayBadgeDotView: NSView { override func accessibilityIsIgnored() -> Bool { true } override func draw(_ dirtyRect: NSRect) { - let rect = bounds.insetBy(dx: 0.5, dy: 0.5) + // Recomputed every draw from the CURRENT bounds — see the type comment. + let dot = TrayStatusIcon.badgeDotFrame(inButtonSize: bounds.size) + let rect = dot.insetBy(dx: 0.5, dy: 0.5) guard rect.width > 0, rect.height > 0 else { return } let path = NSBezierPath(ovalIn: rect) diff --git a/native/macos/MCPProxy/MCPProxyTests/TrayBadgeDotTests.swift b/native/macos/MCPProxy/MCPProxyTests/TrayBadgeDotTests.swift index cfab44966..9aaf147b2 100644 --- a/native/macos/MCPProxy/MCPProxyTests/TrayBadgeDotTests.swift +++ b/native/macos/MCPProxy/MCPProxyTests/TrayBadgeDotTests.swift @@ -54,39 +54,134 @@ final class TrayBadgeDotTests: XCTestCase { // MARK: - Drawing - /// Renders the view offscreen and reads the centre pixel back. This is the - /// assertion a screenshot would have made. - private func centrePixel(of view: TrayBadgeDotView) -> NSColor? { + /// Every opaque pixel the view painted, plus their bounding box, found by + /// scanning the rendered bitmap. + /// + /// Scanning rather than sampling one computed point: the earlier version of + /// this test guessed at the bitmap's y-flip and read a transparent pixel, + /// which looks exactly like "the view drew nothing". Finding the marks the + /// view actually made asserts position, colour and restraint at once, and + /// keeps working if the geometry is retuned. + private func paintedMarks(of view: TrayBadgeDotView) -> (box: NSRect, opaque: Int, sample: NSColor)? { guard let rep = view.bitmapImageRepForCachingDisplay(in: view.bounds) else { return nil } view.cacheDisplay(in: view.bounds, to: rep) - return rep.colorAt(x: Int(view.bounds.midX), y: Int(view.bounds.midY)) + + var minX = Int.max, minY = Int.max, maxX = Int.min, maxY = Int.min + var count = 0 + var sample: NSColor? + for y in 0.. 0.5 else { continue } + count += 1 + minX = min(minX, x); maxX = max(maxX, x) + minY = min(minY, y); maxY = max(maxY, y) + if sample == nil || c.alphaComponent > 0.95 { sample = c } + } + } + guard count > 0, let sample else { return nil } + // The rep is in DEVICE pixels (2x on retina); report POINTS so the + // assertions can be written against the same units as badgeDotFrame. + let scale = CGFloat(rep.pixelsWide) / view.bounds.width + let box = NSRect(x: CGFloat(minX) / scale, + y: CGFloat(minY) / scale, + width: CGFloat(maxX - minX + 1) / scale, + height: CGFloat(maxY - minY + 1) / scale) + return (box, Int(CGFloat(count) / (scale * scale)), sample) } func testAnErrorDrawsARedDot() { - let view = TrayBadgeDotView(frame: NSRect(x: 0, y: 0, width: 12, height: 12)) + let view = TrayBadgeDotView(frame: NSRect(origin: .zero, size: Self.buttonSize)) view.fillColor = .systemRed - guard let colour = centrePixel(of: view)?.usingColorSpace(.sRGB) else { - return XCTFail("nothing was drawn") - } + guard let marks = paintedMarks(of: view) else { return XCTFail("nothing was drawn") } + guard let colour = marks.sample.usingColorSpace(.sRGB) else { return XCTFail("no colour space") } + XCTAssertGreaterThan(colour.redComponent, 0.5, "the dot is not red") XCTAssertGreaterThan(colour.redComponent, colour.greenComponent) XCTAssertGreaterThan(colour.redComponent, colour.blueComponent) - XCTAssertGreaterThan(colour.alphaComponent, 0.9, "the dot must be opaque") } func testAWarningDrawsAnAmberDotNotARedOne() { - let view = TrayBadgeDotView(frame: NSRect(x: 0, y: 0, width: 12, height: 12)) + let view = TrayBadgeDotView(frame: NSRect(origin: .zero, size: Self.buttonSize)) view.fillColor = .systemOrange - guard let colour = centrePixel(of: view)?.usingColorSpace(.sRGB) else { - return XCTFail("nothing was drawn") - } + guard let marks = paintedMarks(of: view) else { return XCTFail("nothing was drawn") } + guard let colour = marks.sample.usingColorSpace(.sRGB) else { return XCTFail("no colour space") } + XCTAssertGreaterThan(colour.greenComponent, 0.25, "amber must be distinguishable from red at a glance") XCTAssertGreaterThan(colour.redComponent, colour.blueComponent) } + /// What is painted must be the small corner dot — not a wash over the whole + /// icon, which is the way "make the overlay fill the button" goes wrong. + func testOnlyTheCornerDotIsPainted() { + let view = TrayBadgeDotView(frame: NSRect(origin: .zero, size: Self.buttonSize)) + view.fillColor = .systemRed + + guard let marks = paintedMarks(of: view) else { return XCTFail("nothing was drawn") } + let expected = TrayStatusIcon.badgeDotFrame(inButtonSize: Self.buttonSize) + + XCTAssertLessThanOrEqual(marks.box.width, expected.width + 1, + "painted wider than the dot — the overlay is washing the icon") + XCTAssertLessThanOrEqual(marks.box.height, expected.height + 1, + "painted taller than the dot") + + let buttonArea = Self.buttonSize.width * Self.buttonSize.height + XCTAssertLessThan(Double(marks.opaque), Double(buttonArea) * 0.15, + "the badge must cover a small fraction of the button, got \(marks.opaque)px") + + // Right-hand half, lower half: the corner the badge belongs in. + XCTAssertGreaterThan(marks.box.midX, Self.buttonSize.width / 2, "dot is not on the right") + XCTAssertGreaterThan(marks.box.midY, Self.buttonSize.height / 2, + "dot is not low (bitmap y grows downward, so low = large y)") + } + + // MARK: - It survives a resize + + /// The regression cross-model review (gpt-5.6-sol) found: the badge used to + /// be a 6x6 subview pinned with [.minXMargin, .maxYMargin], which anchors to + /// the BUTTON's corner. The icon is CENTRED, so when the button shrinks by N + /// the right-pinned dot moves left by N while the icon's right edge moves + /// left by only N/2 — the badge drifts off the glyph. On top of that, + /// NSStatusItem resizes asynchronously, so the bounds read right after + /// clearing attributedTitle were the old, wider ones. + /// + /// The view now fills the button and derives the dot from its live bounds, + /// so the badge is correct at EVERY width, not just the one it was born at. + func testTheDotTracksTheIconWhenTheButtonResizes() { + let view = TrayBadgeDotView(frame: NSRect(x: 0, y: 0, width: 48, height: 22)) + view.fillColor = .systemRed + + for width in [48.0, 36.0, 30.0, 24.0] as [CGFloat] { + view.frame = NSRect(x: 0, y: 0, width: width, height: 22) + let dot = TrayStatusIcon.badgeDotFrame(inButtonSize: view.bounds.size) + let iconRight = (width - TrayStatusIcon.statusIconSide) / 2 + TrayStatusIcon.statusIconSide + XCTAssertEqual(dot.maxX, iconRight, accuracy: 0.01, + "badge drifted off the icon at button width \(width)") + } + } + + /// A resize must actually re-render the dot at the new position — the + /// point of computing it in `draw(_:)`. Asserting the rendered output + /// rather than the `needsDisplay` flag, which a layer-backed view does not + /// report reliably. (`needsDisplayOnBoundsChange` is a CALayer property and + /// does not exist on NSView at all.) + func testResizingRedrawsTheDotInItsNewPlace() { + let view = TrayBadgeDotView(frame: NSRect(x: 0, y: 0, width: 48, height: 22)) + view.fillColor = .systemRed + guard let wide = paintedMarks(of: view) else { return XCTFail("nothing drawn at 48pt") } + + view.setFrameSize(NSSize(width: 28, height: 22)) + guard let narrow = paintedMarks(of: view) else { return XCTFail("nothing drawn at 28pt") } + + XCTAssertNotEqual(wide.box.midX, narrow.box.midX, + "the dot did not move when the button shrank") + let expected = TrayStatusIcon.badgeDotFrame(inButtonSize: NSSize(width: 28, height: 22)) + XCTAssertEqual(narrow.box.midX, expected.midX, accuracy: 1.5, + "after the resize the dot is not where the icon's corner now is") + } + // MARK: - It is decoration, not a control /// The dot overlaps the icon. Without hit-test passthrough it would swallow From a17e09c4cbbe08833ecd4efc1dfa97a83a551a1d Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Fri, 28 Aug 2026 08:56:30 +0300 Subject: [PATCH 3/4] =?UTF-8?q?fix(tray):=20the=20status=20button=20is=20F?= =?UTF-8?q?LIPPED=20=E2=80=94=20pin=20it,=20test=20it,=20document=20it?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Multi-agent verification found what both I and the cross-model review missed, by compiling against real AppKit rather than reasoning about it: NSView().isFlipped = false NSButton().isFlipped = true NSStatusBarButton.isFlipped = true The first commit in this PR (9c740c0d4) therefore shipped the badge in the icon's TOP-right corner, not the bottom-right its comment and commit message both claimed. `y = 2` in a flipped button is 2pt from the TOP, and `.maxYMargin` pins to the TOP. Rendered inside a real 36x22 status button the dot landed at bitmap rows 4-15 of 44 (top-first). The second commit (5e773a98a) already corrected it — but incidentally, because TrayBadgeDotView is a plain NSView and computes the dot in its own unflipped space. Nothing recorded that the design depends on that, and no test could tell the two apart: every badge test rendered the view standalone, where the flip never enters the picture. * `isFlipped` is now overridden to `false` explicitly. It is load-bearing, not incidental — overriding it to true silently moves the badge back to the top-right. * TrayBadgeDotView's and badgeDotFrame's comments described the OLD bug wrongly (they said the mask pinned bottom-right). Corrected, with the flipped-coordinate trap written down as the reason the design is shaped the way it is. * New TrayBadgeInStatusButtonTests renders the overlay inside a REAL NSStatusBarButton and asserts the dot is in the visual lower-right. Mutation-tested: flipping the overlay fails it with "badge is in the TOP half — the flipped-coordinate bug is back (rows 4...15 of 44)", matching the shipped bug's measured position exactly. Also from the sweep: * The legacy-SSE string is mcp-go's exported `transport.ErrLegacySSEServer`, NOT one of ours as the classifier comment, the test file and the PR body all claimed. Corrected, `errors.Is` added as the primary check (the substring fallback stays, since the upstream layer stringifies the error and breaks the errors.Is chain), and TestLegacySSESentinelStillMatches pins the vendored wording — otherwise a routine mcp-go bump silently regresses MCPX_HTTP_LEGACY_SSE to MCPX_HTTP_404 with the suite green. * `serversWithDiagnostic` was left on the narrower OAuth-only predicate when isBadgeExempt was introduced, breaking the "these filter identically" invariant at birth. Nothing consumes it today, which is precisely why the drift would have surfaced late. Aligned, and pinned by a test. * `isQuarantineReview`'s comment claimed `quarantined` and `admin_state` were two independent signals. They are not — health/calculator.go derives the second from the first. The check is kept as belt-and-braces; the claim is corrected. * Added the composition case nothing covered: servers are quarantined on add, so a newly added npx-with-no-args server is quarantined AND broken. It asks for review rather than raising a red badge — deliberate, now pinned, along with the case that it DOES alarm once released. --- internal/diagnostics/classifier.go | 20 +++- .../classifier_selfmessages_test.go | 47 +++++++- .../macos/MCPProxy/MCPProxy/API/Models.swift | 9 +- .../MCPProxy/Menu/TrayBadgeDotView.swift | 32 +++-- .../MCPProxy/Menu/TrayPresentation.swift | 9 +- .../MCPProxy/MCPProxy/State/AppState.swift | 19 ++- .../TrayBadgeExemptionTests.swift | 59 ++++++++++ .../TrayBadgeInStatusButtonTests.swift | 109 ++++++++++++++++++ 8 files changed, 277 insertions(+), 27 deletions(-) create mode 100644 native/macos/MCPProxy/MCPProxyTests/TrayBadgeInStatusButtonTests.swift diff --git a/internal/diagnostics/classifier.go b/internal/diagnostics/classifier.go index ae2a4a302..09a78c842 100644 --- a/internal/diagnostics/classifier.go +++ b/internal/diagnostics/classifier.go @@ -7,6 +7,8 @@ import ( "os/exec" "strings" "syscall" + + "github.com/mark3labs/mcp-go/client/transport" ) // Classify maps a raw error to a stable Code. It prefers typed-error inspection @@ -354,11 +356,19 @@ func classifyHTTP(err error, hints ClassifierHints) Code { } // A 4xx on the streamable-HTTP `initialize` POST is the legacy-SSE - // signature, not an auth or routing failure — the upstream layer says so in - // as many words. Matched BEFORE the generic status-text fallback below, - // which would otherwise claim it as a bare MCPX_HTTP_404/403 and send the - // user hunting for a credential problem that does not exist. - if strings.Contains(lmsg, "likely a legacy sse server") || + // signature, not an auth or routing failure. Matched BEFORE the generic + // status-text fallback below, which would otherwise claim it as a bare + // MCPX_HTTP_404/403 and send the user hunting for a credential problem that + // does not exist. + // + // The typed check first: this error is mcp-go's exported sentinel, NOT one + // of our own strings, so a library bump can reword it at any time. The + // substring fallback stays because the upstream layer commonly stringifies + // the error before it reaches us, which breaks the errors.Is chain. + // TestLegacySSESentinelStillMatches pins the vendored wording so that bump + // fails a test instead of silently regressing this code to MCPX_HTTP_404. + if errors.Is(err, transport.ErrLegacySSEServer) || + strings.Contains(lmsg, "likely a legacy sse server") || (strings.Contains(lmsg, "4xx for initialize") && strings.Contains(lmsg, "post")) { return HTTPLegacySSE } diff --git a/internal/diagnostics/classifier_selfmessages_test.go b/internal/diagnostics/classifier_selfmessages_test.go index 43bd1fa78..47b87db51 100644 --- a/internal/diagnostics/classifier_selfmessages_test.go +++ b/internal/diagnostics/classifier_selfmessages_test.go @@ -2,13 +2,22 @@ package diagnostics import ( "errors" + "fmt" + "strings" "testing" + + "github.com/mark3labs/mcp-go/client/transport" ) -// Both errors below are mcpproxy's OWN wording, produced before or during the -// connect attempt — yet both classified as MCPX_UNKNOWN_UNCLASSIFIED, whose -// catalog entry tells the user to file a bug report against us. The strings are -// copied verbatim from a live v0.61.0 install. +// Both errors below reached the user as MCPX_UNKNOWN_UNCLASSIFIED, whose catalog +// entry tells them to file a bug report against us — for failures that are +// entirely diagnosable. The strings are copied verbatim from a live v0.61.0 +// install. +// +// Only the first is mcpproxy's own wording (internal/upstream/core/ +// connection_stdio.go). The second is mcp-go's exported `transport +// .ErrLegacySSEServer` sentinel; see TestLegacySSESentinelStillMatches for why +// that distinction needs its own guard. func TestOwnErrorMessagesDoNotClassifyAsUnknown(t *testing.T) { cases := []struct { name string @@ -89,3 +98,33 @@ func TestOrdinaryHTTPStatusesAreUnaffected(t *testing.T) { t.Fatalf("Classify() = %q, want %q", got, HTTPNotFound) } } + +// The legacy-SSE rule matches a string mcp-go owns, not one of ours. Nothing +// else in this repo produces it: +// +// $ grep -rn "legacy SSE" --include="*.go" internal/ | grep -v _test +// internal/diagnostics/classifier.go:... (the matcher itself) +// +// So a routine mcp-go bump that rewords the sentinel would silently regress +// MCPX_HTTP_LEGACY_SSE back to MCPX_HTTP_404 with the whole suite green — the +// user gets sent hunting for a credential problem again. The typed errors.Is +// path in classifyHTTP survives a reword; the substring fallback (needed +// because the upstream layer stringifies the error) does not. This pins it, so +// the bump fails HERE with a clear reason instead of degrading in the field. +func TestLegacySSESentinelStillMatches(t *testing.T) { + msg := strings.ToLower(transport.ErrLegacySSEServer.Error()) + + matchesWording := strings.Contains(msg, "likely a legacy sse server") || + (strings.Contains(msg, "4xx for initialize") && strings.Contains(msg, "post")) + if !matchesWording { + t.Fatalf("mcp-go reworded ErrLegacySSEServer to %q — update the substring fallback "+ + "in classifyHTTP to match, or MCPX_HTTP_LEGACY_SSE silently degrades to MCPX_HTTP_404", + transport.ErrLegacySSEServer.Error()) + } + + // The typed path must work even when nothing about the wording matches. + if got := Classify(fmt.Errorf("connect: %w", transport.ErrLegacySSEServer), + ClassifierHints{Transport: "http"}); got != HTTPLegacySSE { + t.Fatalf("wrapped sentinel classified as %q, want %q", got, HTTPLegacySSE) + } +} diff --git a/native/macos/MCPProxy/MCPProxy/API/Models.swift b/native/macos/MCPProxy/MCPProxy/API/Models.swift index 2fd6fa7d5..79e05e8ee 100644 --- a/native/macos/MCPProxy/MCPProxy/API/Models.swift +++ b/native/macos/MCPProxy/MCPProxy/API/Models.swift @@ -364,8 +364,13 @@ struct ServerStatus: Codable, Identifiable, Equatable { /// menu header drew a calm yellow dot under a red menu-bar dot, and the /// user could not clear it without approving or disabling the server. /// - /// Both signals are checked: `quarantined` is the server's own flag and - /// `admin_state` is the cross-surface contract CLI/REST/Web-UI/tray share. + /// The `admin_state` half is belt-and-braces, not a second independent + /// signal: the backend derives it FROM `quarantined` + /// (`internal/health/calculator.go` returns `AdminState: quarantined` + /// whenever the input is quarantined), so today it cannot be true while + /// `quarantined` is false. It is kept because `admin_state` is the + /// cross-surface contract CLI/REST/Web-UI/tray share, and this stays correct + /// if those two ever decouple. var isQuarantineReview: Bool { quarantined || health?.adminState == "quarantined" } diff --git a/native/macos/MCPProxy/MCPProxy/Menu/TrayBadgeDotView.swift b/native/macos/MCPProxy/MCPProxy/Menu/TrayBadgeDotView.swift index be3a9576c..10a38df6d 100644 --- a/native/macos/MCPProxy/MCPProxy/Menu/TrayBadgeDotView.swift +++ b/native/macos/MCPProxy/MCPProxy/Menu/TrayBadgeDotView.swift @@ -17,20 +17,29 @@ import AppKit /// /// Why the view fills the WHOLE button rather than being a 6x6 view positioned /// at the corner: the dot is anchored to the centred 18pt ICON, not to the -/// button, and the button's width changes (it is `variableLength`, and the core -/// -state glyph comes and goes from `attributedTitle`). A small right-pinned -/// subview breaks that anchor twice over — +/// button, and the button's width changes (it is `variableLength`, and the +/// core-state glyph comes and goes from `attributedTitle`). A small subview +/// pinned into the button's corner breaks three ways — /// -/// * `[.minXMargin, .maxYMargin]` pins to the BUTTON's bottom-right, so when -/// the button shrinks by N the dot moves left by N while the centred icon's -/// right edge moves left by only N/2; and +/// * **`NSStatusBarButton` is FLIPPED.** `NSButton.isFlipped` is `true` (unlike +/// a plain `NSView`), so inside the button y grows DOWNWARD: a frame at +/// `y = 2` is 2pt from the TOP, and `.maxYMargin` pins to the TOP. The first +/// attempt at this badge did exactly that and shipped the dot in the icon's +/// top-right corner while every test passed, because no test rendered it +/// inside a real status button. This is the trap; it is the reason the whole +/// design now lives in `draw(_:)` of an UNFLIPPED view. +/// * `[.minXMargin, …]` pins horizontally to the BUTTON's edge, so when the +/// button shrinks by N the dot moves left by N while the centred icon's +/// right edge moves left by only N/2. /// * `NSStatusItem` resizes asynchronously, so `button.bounds` read straight /// after clearing `attributedTitle` is still the old, wider value — the dot /// is laid out against an icon centre that no longer exists. /// /// Filling the bounds and computing the dot inside `draw(_:)` from the CURRENT -/// bounds removes both failure modes: any resize just redraws in the right -/// place. (Cross-model review, gpt-5.6-sol.) +/// bounds removes all three: the geometry is re-derived every draw, in this +/// view's own bottom-left space, independent of the button's. +/// (Cross-model review, gpt-5.6-sol; flipped-coordinate trap found by the +/// verification sweep.) final class TrayBadgeDotView: NSView { /// The dot's fill. Setting it redraws; setting it to the same value is a @@ -42,6 +51,13 @@ final class TrayBadgeDotView: NSView { } } + /// Load-bearing, and stated explicitly rather than inherited: every + /// coordinate in `draw(_:)` and in `TrayStatusIcon.badgeDotFrame` assumes a + /// bottom-left origin, while this view's SUPERVIEW (`NSStatusBarButton`) is + /// flipped. Overriding it to `true` would silently move the badge to the + /// icon's top-right — which is precisely the bug this design replaced. + override var isFlipped: Bool { false } + override init(frame frameRect: NSRect) { super.init(frame: frameRect) wantsLayer = true diff --git a/native/macos/MCPProxy/MCPProxy/Menu/TrayPresentation.swift b/native/macos/MCPProxy/MCPProxy/Menu/TrayPresentation.swift index 973b95ec3..59a48e147 100644 --- a/native/macos/MCPProxy/MCPProxy/Menu/TrayPresentation.swift +++ b/native/macos/MCPProxy/MCPProxy/Menu/TrayPresentation.swift @@ -99,8 +99,13 @@ enum TrayStatusIcon { static let badgeDotDiameter: CGFloat = 6 static let statusIconSide: CGFloat = 18 - /// Where the corner dot sits inside the status item button, in the button's - /// own (bottom-left origin) coordinates. + /// Where the corner dot sits, in BOTTOM-LEFT-ORIGIN coordinates. + /// + /// Read that twice before reusing this: it is the coordinate space of + /// `TrayBadgeDotView` (a plain, unflipped `NSView`), NOT of the status item + /// button that view sits in. `NSStatusBarButton.isFlipped` is `true`, so + /// applying this rect directly to a subview OF THE BUTTON puts the dot in + /// the icon's TOP-right corner. That bug shipped once already. /// /// Pure maths so the placement is testable without a live menu bar — this /// machine cannot screenshot the status item without a Screen Recording diff --git a/native/macos/MCPProxy/MCPProxy/State/AppState.swift b/native/macos/MCPProxy/MCPProxy/State/AppState.swift index 7f95e04b1..47506655c 100644 --- a/native/macos/MCPProxy/MCPProxy/State/AppState.swift +++ b/native/macos/MCPProxy/MCPProxy/State/AppState.swift @@ -309,13 +309,20 @@ final class AppState: ObservableObject { /// warn/error severity. These drive the "Fix issues" menu group and the /// tray badge tint. /// - /// MCP-1819/T3: OAuth login-required servers are excluded. Pre-T1 the - /// backend classifies that state as an error-severity - /// MCPX_UNKNOWN_UNCLASSIFIED diagnostic, which would otherwise read as a - /// "file a bug" hard error. A server that just needs sign-in is surfaced - /// calmly via `serversNeedingAttention` (the "Sign in" affordance) instead. + /// Servers in an intentional non-connected state are excluded, via the same + /// `isBadgeExempt` predicate the badge uses — it was left on the narrower + /// OAuth-only check when that predicate was introduced, which quietly broke + /// the "these three filter identically" invariant at birth (verification + /// sweep, gap 1). Nothing consumes this today, which is exactly why the + /// drift would have gone unnoticed until something did. + /// + /// MCP-1819/T3, the original reason: the backend classifies OAuth + /// login-required as an error-severity MCPX_UNKNOWN_UNCLASSIFIED diagnostic, + /// which would otherwise read as a "file a bug" hard error. Such a server is + /// surfaced calmly via `serversNeedingAttention` instead — as is a + /// quarantined one, via "Review quarantine…". var serversWithDiagnostic: [ServerStatus] { - servers.filter { $0.hasAttentionDiagnostic && !$0.isOAuthLoginRequired } + servers.filter { $0.hasAttentionDiagnostic && !$0.isBadgeExempt } } /// How many servers carry the severity the tray icon is currently badging. diff --git a/native/macos/MCPProxy/MCPProxyTests/TrayBadgeExemptionTests.swift b/native/macos/MCPProxy/MCPProxyTests/TrayBadgeExemptionTests.swift index 3eabe0ea5..1fe3f4140 100644 --- a/native/macos/MCPProxy/MCPProxyTests/TrayBadgeExemptionTests.swift +++ b/native/macos/MCPProxy/MCPProxyTests/TrayBadgeExemptionTests.swift @@ -132,6 +132,65 @@ final class TrayBadgeExemptionTests: XCTestCase { "nothing is badged, so nothing may be counted") } + /// The composition the whole fix set rests on, and the one shape that was + /// untested: new servers are quarantined by default + /// (`config_load_admission_gate.go` sets `Quarantined = true` on add), so + /// the PR's own live fixture — an `npx`-with-no-args server — arrives + /// quarantined AND misconfigured. The new MCPX_CONFIG_INVALID_COMMAND + /// therefore does NOT tint the badge in the commonest case. + /// + /// That is deliberate, not an oversight: quarantine review is the first + /// thing the user must do, and it is surfaced calmly. But it is worth + /// pinning, because "fix a config error" and "approve this server" are + /// exactly the two states someone might later assume compose differently. + @MainActor + func testANewlyAddedBrokenServerAsksForReviewNotAlarm() { + let broken = Self.decode(""" + { + "id": "demo", "name": "demo", "protocol": "stdio", + "enabled": true, "connected": false, "quarantined": true, "tool_count": 0, + "error_code": "MCPX_CONFIG_INVALID_COMMAND", + "diagnostic": {"code": "MCPX_CONFIG_INVALID_COMMAND", "severity": "error", "summary": "no args"}, + "health": {"level": "healthy", "admin_state": "quarantined", + "summary": "Quarantined for review", "action": "approve"} + } + """) + let state = AppState() + state.servers = [broken] + + XCTAssertNil(state.worstDiagnosticSeverity, + "a server awaiting review must not raise a red badge, even when broken") + XCTAssertEqual(state.serversNeedingAttention.count, 1, + "but it must still be listed — the user has to act on it") + XCTAssertEqual(broken.health?.action, "approve", + "and the action offered is review, not restart") + } + + /// Once reviewed and released from quarantine, the SAME broken server must + /// raise the badge — otherwise the exemption would hide the fault forever. + @MainActor + func testTheSameServerAlarmsOnceItLeavesQuarantine() { + let state = AppState() + state.servers = [Self.brokenServer(name: "demo")] + XCTAssertEqual(state.worstDiagnosticSeverity, "error") + XCTAssertEqual(state.diagnosticCount(severity: "error"), 1) + } + + /// The three filters that must agree. `serversWithDiagnostic` was left on + /// the narrower OAuth-only predicate when `isBadgeExempt` was introduced. + @MainActor + func testAllThreeDiagnosticFiltersAgreeOnExemptions() { + let state = AppState() + state.servers = [ + Self.quarantinedServer(name: "q"), + Self.loginRequiredServer(name: "l"), + ] + XCTAssertNil(state.worstDiagnosticSeverity) + XCTAssertEqual(state.diagnosticCount(severity: "error"), 0) + XCTAssertTrue(state.serversWithDiagnostic.isEmpty, + "serversWithDiagnostic must use the same exemption as the badge") + } + /// `quarantined: true` alone is enough, even if the health block is absent /// or stale — the two signals are checked independently on purpose. @MainActor diff --git a/native/macos/MCPProxy/MCPProxyTests/TrayBadgeInStatusButtonTests.swift b/native/macos/MCPProxy/MCPProxyTests/TrayBadgeInStatusButtonTests.swift new file mode 100644 index 000000000..9c3353246 --- /dev/null +++ b/native/macos/MCPProxy/MCPProxyTests/TrayBadgeInStatusButtonTests.swift @@ -0,0 +1,109 @@ +// TrayBadgeInStatusButtonTests.swift +// MCPProxyTests +// +// The badge, rendered inside a REAL NSStatusBarButton. +// +// Every other badge test renders TrayBadgeDotView standalone. That is exactly +// how a shipped bug hid: `NSStatusBarButton.isFlipped` is `true` (NSButton +// flips; a plain NSView does not), so geometry written for a bottom-left origin +// lands in the icon's TOP-right corner once the view is a child of the button — +// and a standalone render never sees it. This file closes that gap by putting +// the overlay where it actually lives and looking at the pixels. + +import AppKit +import XCTest +@testable import MCPProxy + +final class TrayBadgeInStatusButtonTests: XCTestCase { + + private var statusItem: NSStatusItem? + + override func tearDown() { + if let item = statusItem { NSStatusBar.system.removeStatusItem(item) } + statusItem = nil + super.tearDown() + } + + /// A real status item button, or nil when the environment has no status bar + /// to attach one to. + private func makeStatusButton() -> NSStatusBarButton? { + let item = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength) + statusItem = item + guard let button = item.button else { return nil } + button.setFrameSize(NSSize(width: 36, height: 22)) + return button + } + + /// The assumption the whole design rests on. If this ever changes, the + /// badge silently moves corners — so assert it rather than trusting it. + func testTheStatusButtonIsFlippedButTheOverlayIsNot() throws { + let button = try XCTUnwrap(makeStatusButton(), "no status bar available") + XCTAssertTrue(button.isFlipped, + "NSStatusBarButton is expected to be flipped; the badge geometry depends on knowing that") + + let overlay = TrayBadgeDotView(frame: button.bounds) + XCTAssertFalse(overlay.isFlipped, + "the overlay must stay bottom-left origin — badgeDotFrame is written for that space") + } + + /// The regression itself: with the overlay installed the way the app + /// installs it, the dot must render in the LOWER half of the button as the + /// user sees it. + /// + /// Bitmap rows count from the TOP, so "visually low" means a LARGE row + /// index. The shipped bug put the dot at rows 5-14 of 44; correct is ~29-38. + func testTheDotRendersInTheVisualBottomRightOfTheButton() throws { + let button = try XCTUnwrap(makeStatusButton(), "no status bar available") + + let overlay = TrayBadgeDotView(frame: button.bounds) + overlay.autoresizingMask = [.width, .height] + overlay.fillColor = .systemRed + button.addSubview(overlay) + + let rep = try XCTUnwrap(button.bitmapImageRepForCachingDisplay(in: button.bounds)) + button.cacheDisplay(in: button.bounds, to: rep) + + var minRow = Int.max, maxRow = Int.min, minCol = Int.max, maxCol = Int.min + var found = false + for row in 0.. 0.5, + c.redComponent > 0.5, + c.redComponent > c.greenComponent + 0.2, + c.redComponent > c.blueComponent + 0.2 else { continue } + found = true + minRow = min(minRow, row); maxRow = max(maxRow, row) + minCol = min(minCol, col); maxCol = max(maxCol, col) + } + } + + XCTAssertTrue(found, "the badge did not render inside the status button at all") + + let midRow = Double(minRow + maxRow) / 2 + let midCol = Double(minCol + maxCol) / 2 + XCTAssertGreaterThan(midRow, Double(rep.pixelsHigh) / 2, + "badge is in the TOP half — the flipped-coordinate bug is back " + + "(rows \(minRow)...\(maxRow) of \(rep.pixelsHigh))") + XCTAssertGreaterThan(midCol, Double(rep.pixelsWide) / 2, + "badge is in the LEFT half (cols \(minCol)...\(maxCol) of \(rep.pixelsWide))") + } + + /// The overlay covers the whole button, so the button must still be + /// clickable through it — otherwise the status item stops opening its menu. + func testTheButtonIsStillClickableThroughTheOverlay() throws { + let button = try XCTUnwrap(makeStatusButton(), "no status bar available") + let overlay = TrayBadgeDotView(frame: button.bounds) + overlay.autoresizingMask = [.width, .height] + button.addSubview(overlay) + + // Dead centre, and the dot's own corner: neither may be captured. + for point in [NSPoint(x: button.bounds.midX, y: button.bounds.midY), + NSPoint(x: button.bounds.maxX - 3, y: button.bounds.maxY - 3)] { + let hit = button.hitTest(point) + XCTAssertFalse(hit === overlay, + "the overlay captured the click at \(point) — the menu would not open") + } + } +} From 2a73ca8493997d1d2ddaf527fb23be71c7f7cc6d Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Fri, 28 Aug 2026 08:58:44 +0300 Subject: [PATCH 4/4] test(tray): skip the status-button render test when there is no window server MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit TrayBadgeInStatusButtonTests creates a real NSStatusBar item, which is the whole point — the flipped-coordinate bug is invisible to a standalone render. But `swift test` runs on a macos-latest runner whose window-server state is not guaranteed, and there `item.button` is nil. XCTUnwrap turned that into a FAILURE, so a green local run could have gone red in CI for a reason the test cannot assert there. Throws XCTSkip instead. The assertions are about AppKit geometry inside a real button; with no button there is nothing to assert, and that is a skip, not a defect. --- .../TrayBadgeInStatusButtonTests.swift | 22 +++++++++++++------ 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/native/macos/MCPProxy/MCPProxyTests/TrayBadgeInStatusButtonTests.swift b/native/macos/MCPProxy/MCPProxyTests/TrayBadgeInStatusButtonTests.swift index 9c3353246..972d16ff4 100644 --- a/native/macos/MCPProxy/MCPProxyTests/TrayBadgeInStatusButtonTests.swift +++ b/native/macos/MCPProxy/MCPProxyTests/TrayBadgeInStatusButtonTests.swift @@ -24,12 +24,20 @@ final class TrayBadgeInStatusButtonTests: XCTestCase { super.tearDown() } - /// A real status item button, or nil when the environment has no status bar - /// to attach one to. - private func makeStatusButton() -> NSStatusBarButton? { + /// A real status item button. + /// + /// Throws `XCTSkip` — NOT a failure — when the environment has no status bar + /// to attach one to. `swift test` runs on a `macos-latest` runner whose + /// window-server state is not guaranteed; a headless agent returns a nil + /// `button`, and turning that into a red build would punish CI for + /// something this test cannot assert there. The assertions below are about + /// AppKit geometry, which only means anything with a real button. + private func makeStatusButton() throws -> NSStatusBarButton { let item = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength) statusItem = item - guard let button = item.button else { return nil } + guard let button = item.button else { + throw XCTSkip("no window server / status bar in this environment") + } button.setFrameSize(NSSize(width: 36, height: 22)) return button } @@ -37,7 +45,7 @@ final class TrayBadgeInStatusButtonTests: XCTestCase { /// The assumption the whole design rests on. If this ever changes, the /// badge silently moves corners — so assert it rather than trusting it. func testTheStatusButtonIsFlippedButTheOverlayIsNot() throws { - let button = try XCTUnwrap(makeStatusButton(), "no status bar available") + let button = try makeStatusButton() XCTAssertTrue(button.isFlipped, "NSStatusBarButton is expected to be flipped; the badge geometry depends on knowing that") @@ -53,7 +61,7 @@ final class TrayBadgeInStatusButtonTests: XCTestCase { /// Bitmap rows count from the TOP, so "visually low" means a LARGE row /// index. The shipped bug put the dot at rows 5-14 of 44; correct is ~29-38. func testTheDotRendersInTheVisualBottomRightOfTheButton() throws { - let button = try XCTUnwrap(makeStatusButton(), "no status bar available") + let button = try makeStatusButton() let overlay = TrayBadgeDotView(frame: button.bounds) overlay.autoresizingMask = [.width, .height] @@ -93,7 +101,7 @@ final class TrayBadgeInStatusButtonTests: XCTestCase { /// The overlay covers the whole button, so the button must still be /// clickable through it — otherwise the status item stops opening its menu. func testTheButtonIsStillClickableThroughTheOverlay() throws { - let button = try XCTUnwrap(makeStatusButton(), "no status bar available") + let button = try makeStatusButton() let overlay = TrayBadgeDotView(frame: button.bounds) overlay.autoresizingMask = [.width, .height] button.addSubview(overlay)