From 2c91e4fdcb6fa88a4e12f47091880f54c9843e0d Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Tue, 25 Aug 2026 14:46:07 +0300 Subject: [PATCH 1/5] fix(tray): address the 16 findings of the macOS tray UX + settings-parity audit Menu-bar icon now badges server severity and is labelled for VoiceOver; per-server actions report failure instead of closing silently; a "Needs Attention" row navigates and its remediation lives under its own verb. Agent Tokens and a new global Tools search reach the sidebar, the Servers submenu groups by state, and the settings catalogue regains the three web-only fields behind a full key-coverage parity gate. --- .../MCPProxy/MCPProxy/API/APIClient.swift | 29 +- .../macos/MCPProxy/MCPProxy/API/Models.swift | 6 + .../macos/MCPProxy/MCPProxy/MCPProxyApp.swift | 495 +++++++++++++----- .../MCPProxy/MCPProxy/Menu/TrayIcon.swift | 57 -- .../MCPProxy/Menu/TrayPresentation.swift | 221 ++++++++ .../Settings/ConfigSettingsView.swift | 96 +++- .../MCPProxy/Settings/SettingsCatalog.swift | 57 +- .../MCPProxy/MCPProxy/State/AppState.swift | 43 +- .../MCPProxy/Views/ActivityView.swift | 52 ++ .../MCPProxy/MCPProxy/Views/MainWindow.swift | 14 + .../MCPProxy/Views/SettingsView.swift | 26 +- .../MCPProxy/MCPProxy/Views/ToolsView.swift | 222 ++++++++ .../MCPProxyTests/TrayAuditMenuTests.swift | 340 ++++++++++++ .../MCPProxyTests/TrayPresentationTests.swift | 165 ++++++ scripts/check-settings-parity.py | 168 ++++-- 15 files changed, 1691 insertions(+), 300 deletions(-) delete mode 100644 native/macos/MCPProxy/MCPProxy/Menu/TrayIcon.swift create mode 100644 native/macos/MCPProxy/MCPProxy/Menu/TrayPresentation.swift create mode 100644 native/macos/MCPProxy/MCPProxy/Views/ToolsView.swift create mode 100644 native/macos/MCPProxy/MCPProxyTests/TrayAuditMenuTests.swift create mode 100644 native/macos/MCPProxy/MCPProxyTests/TrayPresentationTests.swift diff --git a/native/macos/MCPProxy/MCPProxy/API/APIClient.swift b/native/macos/MCPProxy/MCPProxy/API/APIClient.swift index 8a3ff0837..0bb9e994a 100644 --- a/native/macos/MCPProxy/MCPProxy/API/APIClient.swift +++ b/native/macos/MCPProxy/MCPProxy/API/APIClient.swift @@ -772,10 +772,18 @@ actor APIClient { // MARK: - Tool Search - /// Search tools across all servers via `GET /api/v1/tools`. - func searchTools(query: String, limit: Int = 20) async throws -> [SearchResult] { + /// BM25 search across every upstream tool via `GET /api/v1/index/search`. + /// + /// This used to call `GET /api/v1/tools?q=…`, which has no `q` parameter: + /// it returns the full catalogue under `tools`, while this function reads + /// `results` — so every call returned an empty array. Nothing consumed it, + /// which is how it stayed broken; `ToolsView` (F16) is the first caller. + /// + /// Note the REST contract (#871): `tool.name` here is the BARE tool name + /// with `server_name` alongside — callers assemble `server:tool` themselves. + func searchTools(query: String, limit: Int = 50) async throws -> [SearchResult] { let encoded = query.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? query - let data = try await fetchRaw(path: "/api/v1/tools?q=\(encoded)&limit=\(limit)") + let data = try await fetchRaw(path: "/api/v1/index/search?q=\(encoded)&limit=\(limit)") let decoder = JSONDecoder() if let wrapper = try? decoder.decode(APIResponse.self, from: data), let payload = wrapper.data { @@ -787,6 +795,21 @@ actor APIClient { return [] } + /// The whole tool catalogue via `GET /api/v1/tools` — what the Tools view + /// shows before anything is typed. + func allTools() async throws -> [SearchTool] { + let data = try await fetchRaw(path: "/api/v1/tools") + let decoder = JSONDecoder() + if let wrapper = try? decoder.decode(APIResponse.self, from: data), + let payload = wrapper.data { + return payload.tools ?? [] + } + if let direct = try? decoder.decode(SearchToolsResponse.self, from: data) { + return direct.tools ?? [] + } + return [] + } + // MARK: - Tool Quarantine /// Fetch tool diff (old vs new description/schema) for a pending/changed tool. diff --git a/native/macos/MCPProxy/MCPProxy/API/Models.swift b/native/macos/MCPProxy/MCPProxy/API/Models.swift index fbae11dbb..5c80f72f5 100644 --- a/native/macos/MCPProxy/MCPProxy/API/Models.swift +++ b/native/macos/MCPProxy/MCPProxy/API/Models.swift @@ -796,6 +796,11 @@ struct StatusResponse: Codable { let routingMode: String? let upstreamStats: UpstreamStats? let timestamp: Int64? + /// MCP-2176: the core's built-in default MCP instructions, rendered as the + /// placeholder of the Settings → Advanced instructions field so the shown + /// default never drifts from `resolveInstructions("")`. Optional — a core + /// older than the field simply omits it. + let defaultInstructions: String? enum CodingKeys: String, CodingKey { case running @@ -804,6 +809,7 @@ struct StatusResponse: Codable { case routingMode = "routing_mode" case upstreamStats = "upstream_stats" case timestamp + case defaultInstructions = "default_instructions" } } diff --git a/native/macos/MCPProxy/MCPProxy/MCPProxyApp.swift b/native/macos/MCPProxy/MCPProxy/MCPProxyApp.swift index ff9470b81..940f8a38f 100644 --- a/native/macos/MCPProxy/MCPProxy/MCPProxyApp.swift +++ b/native/macos/MCPProxy/MCPProxy/MCPProxyApp.swift @@ -895,11 +895,21 @@ final class AppController: NSObject, NSApplicationDelegate, NSWindowDelegate, NS // MARK: - Status Icon /// Update the status bar icon based on app state. - /// Always draws the MCPProxy base icon, with a small colored overlay badge - /// in the bottom-right corner for stopped or error states. - /// - Running OK: plain MCPProxy icon (no overlay) - /// - Stopped: small orange stop badge overlay - /// - Error: small red exclamation badge overlay + /// + /// 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. + /// + /// - Running OK: plain MCPProxy icon, no glyph + /// - 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) + /// + /// F2: every pass also publishes the state as text — accessibility + /// description, accessibility label and tooltip — so a screen-reader user + /// hears more than "status menu" and the glyphs have a text alternative. private func updateStatusIcon() { guard let button = statusItem?.button else { return } @@ -915,20 +925,42 @@ final class AppController: NSObject, NSApplicationDelegate, NSWindowDelegate, NS let isStopped = appState.isStopped let hasError: Bool if case .error = appState.coreState { hasError = true } else { hasError = false } + let badge = TrayStatusIcon.badge( + isStopped: isStopped, + hasCoreError: hasError, + worstDiagnosticSeverity: appState.worstDiagnosticSeverity + ) + let label = TrayStatusIcon.accessibilityLabel( + for: badge, + summary: appState.statusSummary, + attentionCount: appState.serversWithDiagnostic.count + ) // Always use template icon (pure black, adapts to light/dark menu bar) base.isTemplate = true base.size = NSSize(width: 18, height: 18) + base.accessibilityDescription = label button.image = base // Show state indicator as text next to icon (keeps icon as pure template) - if isStopped { - button.title = "⏹" - } else if hasError { - button.title = "⚠" - } else { + 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.toolTip = label + button.setAccessibilityLabel(label) } // MARK: - Menu Building (AppKit NSMenu — no SwiftUI) @@ -1068,14 +1100,50 @@ final class AppController: NSObject, NSApplicationDelegate, NSWindowDelegate, NS // The full text stays in the tooltip. let title = GlanceFormatting.tailTruncated( fullTitle, limit: GlanceFormatting.reasonBudget) - let item = NSMenuItem(title: title, action: #selector(handleAttentionAction(_:)), keyEquivalent: "") - item.target = self - item.representedObject = server + + // F4: these rows used to run `health.action` on click — a row + // reading "demo-filesystem — failed to connect" silently + // RESTARTED the server, and an `enable`-actioned row enabled + // one. Nothing in the label said so, nothing confirmed it and + // (F3) nothing reported failure. A row that reads as + // disclosure now navigates and nothing else; the action moves + // into a submenu under its own verb, matching the explicit + // verbs already used under `Servers ▸`. + let item = NSMenuItem(title: title, action: nil, keyEquivalent: "") item.toolTip = fullTitle // Truncated on screen, spoken in full — tooltips are not read // by VoiceOver (same FR-025 discipline as the glance rows). item.setAccessibilityLabel(fullTitle) item.image = NSImage(systemSymbolName: icon, accessibilityDescription: action) + + if let verb = TrayServerAction.fromHealthAction(action) { + let rowMenu = NSMenu(title: server.name) + + let act = NSMenuItem(title: verb.menuTitle, + action: #selector(performAttentionAction(_:)), + keyEquivalent: "") + act.target = self + act.representedObject = server + act.image = NSImage(systemSymbolName: actionIcon(for: action), + accessibilityDescription: action) + rowMenu.addItem(act) + rowMenu.addItem(.separator()) + + let details = NSMenuItem(title: "Open Server Details", + action: #selector(showServerDetailFromMenu(_:)), + keyEquivalent: "") + details.target = self + details.representedObject = server.name + rowMenu.addItem(details) + + item.submenu = rowMenu + } else { + // Nothing to run — quarantine review, a missing secret, a + // configuration problem. Straight to the detail view. + item.action = #selector(showServerDetailFromMenu(_:)) + item.target = self + item.representedObject = server.name + } submenu.addItem(item) } parent.submenu = submenu @@ -1103,79 +1171,42 @@ final class AppController: NSObject, NSApplicationDelegate, NSWindowDelegate, NS serversSubmenu.addItem(makeAddServerItem()) serversSubmenu.addItem(.separator()) + // F15: 29 flat alphabetical entries — 13 of them disabled, 3 + // quarantined, interleaved and told apart only by dot colour — + // made a submenu taller than the screen. Attention first, then the + // servers that are working, then the disabled tail behind one row. + let attentionNames = Set(attentionServers.map(\.name)) + var grouped: [TrayServerGroup: [ServerStatus]] = [:] for server in appState.servers { - let item = NSMenuItem(title: server.name, action: nil, keyEquivalent: "") - - // Status icon: colored dot. The OAuth login-required state is a - // calm, actionable affordance (MCP-1822) — `menuStatusNSColor` - // gives it the system accent tint instead of the red error dot + - // red lock badge that previously framed sign-in as a hard failure. - let needsAuth = server.isOAuthLoginRequired - let dotColor = server.menuStatusNSColor - - let iconSize = NSSize(width: 16, height: 16) - let icon = NSImage(size: iconSize, flipped: false) { _ in - // Draw health dot - let dotRect = NSRect(x: 2, y: 4, width: 8, height: 8) - dotColor.setFill() - NSBezierPath(ovalIn: dotRect).fill() - return true - } - item.image = icon - - // Per-server submenu with actions - let sub = NSMenu() - let statusText = server.health?.summary ?? (server.connected ? "Connected" : server.enabled ? "Disconnected" : "Disabled") - let statusLine = NSMenuItem(title: statusText, action: nil, keyEquivalent: "") - statusLine.isEnabled = false - sub.addItem(statusLine) - - // Protocol info - let protoLine = NSMenuItem(title: "Protocol: \(server.protocol)", action: nil, keyEquivalent: "") - protoLine.isEnabled = false - sub.addItem(protoLine) - - sub.addItem(.separator()) - - // OAuth sign-in — calm, actionable affordance shown first when - // login is required (MCP-1822), not error framing. - if needsAuth { - let login = NSMenuItem(title: "Sign in", action: #selector(loginServer(_:)), keyEquivalent: "") - login.target = self - login.representedObject = server.name - login.image = NSImage(systemSymbolName: "person.badge.key", accessibilityDescription: "sign in") - sub.addItem(login) - sub.addItem(.separator()) - } + let group = TrayServerGrouping.group( + enabled: server.enabled, + needsAttention: attentionNames.contains(server.name)) + grouped[group, default: []].append(server) + } + + for server in (grouped[.needsAttention] ?? []) + (grouped[.active] ?? []) { + serversSubmenu.addItem(makeServerMenuItem(server)) + } - if server.enabled { - let disableLabel = server.protocol == "stdio" ? "Stop" : "Disable" - let disable = NSMenuItem(title: disableLabel, action: #selector(disableServer(_:)), keyEquivalent: "") - disable.target = self - disable.representedObject = server.name - sub.addItem(disable) + let disabledServers = grouped[.disabled] ?? [] + if !disabledServers.isEmpty { + if disabledServers.count >= TrayServerGrouping.disabledFoldThreshold { + let fold = NSMenuItem(title: "Disabled (\(disabledServers.count))", + action: nil, keyEquivalent: "") + let foldMenu = NSMenu(title: "Disabled") + for server in disabledServers { + foldMenu.addItem(makeServerMenuItem(server)) + } + fold.submenu = foldMenu + serversSubmenu.addItem(.separator()) + serversSubmenu.addItem(fold) } else { - let enableLabel = server.protocol == "stdio" ? "Start" : "Enable" - let enable = NSMenuItem(title: enableLabel, action: #selector(enableServer(_:)), keyEquivalent: "") - enable.target = self - enable.representedObject = server.name - sub.addItem(enable) + // Below the fold threshold the extra click costs more than + // the rows it saves. + for server in disabledServers { + serversSubmenu.addItem(makeServerMenuItem(server)) + } } - - let restart = NSMenuItem(title: "Restart", action: #selector(restartServer(_:)), keyEquivalent: "") - restart.target = self - restart.representedObject = server.name - sub.addItem(restart) - - sub.addItem(.separator()) - - let logs = NSMenuItem(title: "View Logs", action: #selector(viewServerLogs(_:)), keyEquivalent: "") - logs.target = self - logs.representedObject = server.name - sub.addItem(logs) - - item.submenu = sub - serversSubmenu.addItem(item) } serversMenuItem.submenu = serversSubmenu @@ -1201,12 +1232,25 @@ final class AppController: NSObject, NSApplicationDelegate, NSWindowDelegate, NS profileSubmenu.addItem(allItem) profileSubmenu.addItem(.separator()) + // F11: the tray showed only a tool count, so a profile whose + // servers are not in the config read as "empty" rather than + // "switching to this scopes every agent to nothing". + let knownServers = Set(appState.servers.map(\.name)) for profile in appState.profiles { - let item = NSMenuItem(title: "\(profile.name) (\(profile.toolCount) tools)", + let title = TrayProfileDisplay.label( + name: profile.name, + servers: profile.servers, + toolCount: profile.toolCount, + knownServers: knownServers) + let item = NSMenuItem(title: title, action: #selector(switchProfile(_:)), keyEquivalent: "") item.target = self item.representedObject = profile.name item.state = profile.name == appState.activeProfile ? .on : .off + if profile.servers.filter({ knownServers.contains($0) }).isEmpty { + item.toolTip = "None of this profile’s servers (\(profile.servers.joined(separator: ", "))) " + + "are in the configuration. Switching to it would leave agents with no tools." + } profileSubmenu.addItem(item) } @@ -1230,7 +1274,9 @@ final class AppController: NSObject, NSApplicationDelegate, NSWindowDelegate, NS // together (a nil target would make it silently do nothing). menu.addItem(ConnectClientMenuRouter.shared.makeMenuItem()) - let openApp = NSMenuItem(title: "Open MCPProxy...", action: #selector(openMainWindow), keyEquivalent: "") + // F9: "Open MCPProxy..." and "Open Web UI" never said that one is a + // native window and the other a browser tab. + let openApp = NSMenuItem(title: "Open MCPProxy Window", action: #selector(openMainWindow), keyEquivalent: "") openApp.target = self menu.addItem(openApp) @@ -1238,16 +1284,22 @@ final class AppController: NSObject, NSApplicationDelegate, NSWindowDelegate, NS settingsItem.target = self menu.addItem(settingsItem) - let webUI = NSMenuItem(title: "Open Web UI", action: #selector(openWebUI), keyEquivalent: "") + let webUI = NSMenuItem(title: "Open Web UI in Browser", action: #selector(openWebUI), keyEquivalent: "") webUI.target = self menu.addItem(webUI) menu.addItem(.separator()) - // Settings - let autoStart = NSMenuItem(title: "Run at Startup", action: #selector(toggleAutoStart(_:)), keyEquivalent: "") + // F9: the same AutoStartService setting is called "Launch MCPProxy at + // login" in Settings → App. One setting, one name — and a tooltip that + // separates it from "Start MCPProxy Core when the app opens", the + // genuinely confusable neighbour one row from "Start/Stop MCPProxy + // Core" (which means *now*, not at launch). + let autoStart = NSMenuItem(title: "Launch at Login", action: #selector(toggleAutoStart(_:)), keyEquivalent: "") autoStart.target = self autoStart.state = appState.autoStartEnabled ? .on : .off + autoStart.toolTip = "Starts the MCPProxy app when you log in. Whether it also starts the core is " + + "“Start MCPProxy Core when the app opens” in Settings → App." menu.addItem(autoStart) let checkUpdates = NSMenuItem(title: "Check for Updates", action: #selector(checkForUpdates), keyEquivalent: "") @@ -1371,6 +1423,109 @@ final class AppController: NSObject, NSApplicationDelegate, NSWindowDelegate, NS } + /// One row of the Servers submenu: the server's name, a health dot, and a + /// submenu of the actions that apply to it. + /// + /// Internal so the menu tests can build a row without walking the whole + /// menu, and because F15's grouping calls it from three places. + @MainActor + func makeServerMenuItem(_ server: ServerStatus) -> NSMenuItem { + let item = NSMenuItem(title: server.name, action: nil, keyEquivalent: "") + + // Status icon: colored dot. The OAuth login-required state is a + // calm, actionable affordance (MCP-1822) — `menuStatusNSColor` + // gives it the system accent tint instead of the red error dot + + // red lock badge that previously framed sign-in as a hard failure. + let needsAuth = server.isOAuthLoginRequired + let dotColor = server.menuStatusNSColor + + let iconSize = NSSize(width: 16, height: 16) + let icon = NSImage(size: iconSize, flipped: false) { _ in + // Draw health dot + let dotRect = NSRect(x: 2, y: 4, width: 8, height: 8) + dotColor.setFill() + NSBezierPath(ovalIn: dotRect).fill() + return true + } + item.image = icon + + // Per-server submenu with actions + let sub = NSMenu() + let statusText = server.health?.summary ?? (server.connected ? "Connected" : server.enabled ? "Disconnected" : "Disabled") + let statusLine = NSMenuItem(title: statusText, action: nil, keyEquivalent: "") + statusLine.isEnabled = false + sub.addItem(statusLine) + + // Protocol info — display-normalised (F12). `streamable-http` beside + // `http` and `sse` is three wire spellings of one transport family. + let protoLine = NSMenuItem(title: "Protocol: \(TrayProtocolDisplay.label(for: server.protocol))", + action: nil, keyEquivalent: "") + protoLine.isEnabled = false + sub.addItem(protoLine) + + sub.addItem(.separator()) + + // OAuth sign-in — calm, actionable affordance shown first when + // login is required (MCP-1822), not error framing. + if needsAuth { + let login = NSMenuItem(title: TrayServerAction.login.menuTitle, + action: #selector(loginServer(_:)), keyEquivalent: "") + login.target = self + login.representedObject = server.name + login.image = NSImage(systemSymbolName: "person.badge.key", accessibilityDescription: "sign in") + sub.addItem(login) + sub.addItem(.separator()) + } + + // F8(a): a quarantined server offered only Disable · Restart · View + // Logs — the one thing it needs is a review, and the menu had no path + // to it at all. Deep-links to Server Detail, which opens on Tools with + // the quarantine banner. + if server.quarantined { + let review = NSMenuItem(title: TrayServerAction.approve.menuTitle, + action: #selector(showServerDetailFromMenu(_:)), keyEquivalent: "") + review.target = self + review.representedObject = server.name + review.image = NSImage(systemSymbolName: "checkmark.shield", accessibilityDescription: "review quarantine") + sub.addItem(review) + sub.addItem(.separator()) + } + + // F7: one config write, one verb pair. `Stop`/`Start` for stdio and + // `Disable`/`Enable` for everything else put two mental models — + // transient process control vs. persistent admin state — on the same + // `enabled` flag, and left submenus reading "Disabled … Start". + if server.enabled { + let disable = NSMenuItem(title: TrayServerAction.disable.menuTitle, + action: #selector(disableServer(_:)), keyEquivalent: "") + disable.target = self + disable.representedObject = server.name + sub.addItem(disable) + } else { + let enable = NSMenuItem(title: TrayServerAction.enable.menuTitle, + action: #selector(enableServer(_:)), keyEquivalent: "") + enable.target = self + enable.representedObject = server.name + sub.addItem(enable) + } + + let restart = NSMenuItem(title: TrayServerAction.restart.menuTitle, + action: #selector(restartServer(_:)), keyEquivalent: "") + restart.target = self + restart.representedObject = server.name + sub.addItem(restart) + + sub.addItem(.separator()) + + let logs = NSMenuItem(title: "View Logs", action: #selector(viewServerLogs(_:)), keyEquivalent: "") + logs.target = self + logs.representedObject = server.name + sub.addItem(logs) + + item.submenu = sub + return item + } + // MARK: - Menu Actions @objc private func retryCore() { @@ -1542,43 +1697,115 @@ final class AppController: NSObject, NSApplicationDelegate, NSWindowDelegate, NS alert.runModal() } - @objc private func handleAttentionAction(_ sender: NSMenuItem) { - guard let server = sender.representedObject as? ServerStatus else { return } - let action = server.health?.action ?? "" + /// Run the remediation a "Needs Attention" row offers — from the row's own + /// submenu, under its own verb, never as a side effect of clicking the row + /// (F4). + @MainActor + @objc private func performAttentionAction(_ sender: NSMenuItem) { + guard let server = sender.representedObject as? ServerStatus, + let verb = TrayServerAction.fromHealthAction(server.health?.action ?? "") else { return } + perform(verb, on: server.name, id: server.id) + } + + /// Navigate to a server's detail page. The represented object is the + /// server NAME (what `.showServerDetail` matches on). + @objc private func showServerDetailFromMenu(_ sender: NSMenuItem) { + guard let name = sender.representedObject as? String else { return } + showMainWindow() + NotificationCenter.default.post(name: .switchToServers, object: nil) + DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { + NotificationCenter.default.post(name: .showServerDetail, object: name) + } + } - // Perform the API action silently (if any) - if !action.isEmpty { - Task { + /// F3: the one place a per-server menu action is dispatched. + /// + /// Every one of these used to be `try? await …`, so a restart that 500s + /// was indistinguishable from one that worked — the menu simply closed. + /// The Web UI raises a toast and Server Detail shows an inline error; the + /// tray was the only surface that lied by omission. Failures are now + /// user-visible, and the alert is presented only on failure so the happy + /// path stays silent. + @MainActor + private func perform(_ action: TrayServerAction, on name: String, id: String) { + guard let client = appState.apiClient else { + presentServerActionFailure(action, server: name, error: TrayActionError.noCore) + return + } + Task { [weak self] in + do { switch action { - case "login": try? await appState.apiClient?.loginServer(server.id) - case "restart": try? await appState.apiClient?.restartServer(server.id) - case "enable": try? await appState.apiClient?.enableServer(server.id) - default: break + case .enable: try await client.enableServer(id) + case .disable: try await client.disableServer(id) + case .restart: try await client.restartServer(id) + case .login: try await client.loginServer(id) + case .approve: return // review is a human decision — never dispatched + } + NSLog("[MCPProxy] %@ %@: ok", action.rawValue, name) + } catch { + NSLog("[MCPProxy] %@ %@ failed: %@", action.rawValue, name, error.localizedDescription) + await MainActor.run { + self?.presentServerActionFailure(action, server: name, error: error) } } } + } - // Always navigate to the server's detail page - showMainWindow() - NotificationCenter.default.post(name: .switchToServers, object: nil) - DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { - NotificationCenter.default.post(name: .showServerDetail, object: server.name) + /// A failed menu action, said out loud. Modal because the user just asked + /// for this and is still looking at the menu bar — and because a + /// UNUserNotification can be silenced by Focus, which would put us back + /// where F3 started. + @MainActor + private func presentServerActionFailure(_ action: TrayServerAction, server: String, error: Error) { + let alert = NSAlert() + alert.messageText = TrayServerActionFailure.title(action: action, server: server) + alert.informativeText = TrayServerActionFailure.message(action: action, server: server, error: error) + alert.alertStyle = .warning + alert.addButton(withTitle: "Open Server Details") + alert.addButton(withTitle: "Report an Issue") + alert.addButton(withTitle: "Dismiss") + NSApp.activate(ignoringOtherApps: true) + switch alert.runModal() { + case .alertFirstButtonReturn: + showMainWindow() + NotificationCenter.default.post(name: .switchToServers, object: nil) + DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { + NotificationCenter.default.post(name: .showServerDetail, object: server) + } + case .alertSecondButtonReturn: + NSWorkspace.shared.open(ProjectLinks.issues) + default: + break } } + /// Failure modes the tray itself knows about, before any request is made. + enum TrayActionError: LocalizedError { + case noCore + var errorDescription: String? { + switch self { + case .noCore: + return "MCPProxy is not connected to a running core." + } + } + } + + @MainActor @objc private func enableServer(_ sender: NSMenuItem) { guard let id = sender.representedObject as? String else { return } - Task { try? await appState.apiClient?.enableServer(id) } + perform(.enable, on: id, id: id) } + @MainActor @objc private func disableServer(_ sender: NSMenuItem) { guard let id = sender.representedObject as? String else { return } - Task { try? await appState.apiClient?.disableServer(id) } + perform(.disable, on: id, id: id) } + @MainActor @objc private func restartServer(_ sender: NSMenuItem) { guard let id = sender.representedObject as? String else { return } - Task { try? await appState.apiClient?.restartServer(id) } + perform(.restart, on: id, id: id) } /// Switch the server-level default active profile (Profiles v2 T5). The @@ -1593,25 +1820,14 @@ final class AppController: NSObject, NSApplicationDelegate, NSWindowDelegate, NS } } + @MainActor @objc private func loginServer(_ sender: NSMenuItem) { guard let id = sender.representedObject as? String else { NSLog("[MCPProxy] loginServer: no server ID in representedObject") return } NSLog("[MCPProxy] loginServer: triggering login for %@", id) - // Use appState.apiClient directly (already on main thread, no async needed) - if let client = appState.apiClient { - Task { - do { - try await client.loginServer(id) - NSLog("[MCPProxy] loginServer: API call succeeded for %@", id) - } catch { - NSLog("[MCPProxy] loginServer: API call failed: %@", error.localizedDescription) - } - } - } else { - NSLog("[MCPProxy] loginServer: no apiClient available") - } + perform(.login, on: id, id: id) } @objc private func viewServerLogs(_ sender: NSMenuItem) { @@ -1638,25 +1854,37 @@ final class AppController: NSObject, NSApplicationDelegate, NSWindowDelegate, NS } } - /// Open the Web UI activity log filtered by a glance row's session. + /// Open the native activity log filtered to a glance row's session. /// /// Opens the app's own window at the Activity section — the activity log /// has a native home, and a tray click should not context-switch the user - /// into a browser (the Web UI stays reachable via "Open Web UI"). The - /// row's session id (representedObject) stays on the item because the - /// glance in-place update reads it as row identity; the native log - /// currently opens unfiltered. + /// into a browser (the Web UI stays reachable via "Open Web UI in + /// Browser"). + /// + /// F10: the row's session id (representedObject) used to be thrown away, + /// so a click on one client's run opened the whole unfiltered log. The id + /// now rides along on `.activityFilter` and seeds ActivityView's session + /// filter, which is what makes a glance row parent↔child navigable. @objc private func openActivityForSession(_ sender: NSMenuItem) { + let sessionId = sender.representedObject as? String showMainWindow(tab: Self.glanceActivityDestination) + guard let sessionId, !sessionId.isEmpty else { return } + // After the tab switch: a window created for this click seeds its own + // selection at init, and the filter must land on the view that exists. + DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { + NotificationCenter.default.post(name: .activityFilter, object: sessionId) + } } /// Where a glance row click lands. A constant so tests can pin the /// destination without instantiating the app delegate. static let glanceActivityDestination: SidebarItem = .activity - @objc private func openConfigFile() { - NSWorkspace.shared.open(InstancePaths.configFileURL) - } + // `openConfigFile()` used to live here: an @objc selector nothing + // referenced, for a file the tray deliberately never reads or writes (all + // config goes through REST). Deleted by the 2026-08 UX audit (F14) rather + // than wired to a menu row that would contradict the REST-only contract — + // the effective configuration is in Settings → Raw. // MARK: - Project links (discussion #948) @@ -1683,6 +1911,16 @@ final class AppController: NSObject, NSApplicationDelegate, NSWindowDelegate, NS appendLink(to: credits, label: "GitHub", url: ProjectLinks.github) credits.append(NSAttributedString(string: " ", attributes: body)) appendLink(to: credits, label: "Documentation", url: ProjectLinks.docs) + // F14: the tray — the surface a Homebrew user actually sees — had no + // way to report anything, while `ProjectLinks.issues`/`.discussions` + // sat declared and unused. They land here and in Settings → App + // rather than as new top-level rows: the menu was deliberately cut to + // stop it scrolling (#1023, pinned by MenuStructureTests), and this + // costs no row. + credits.append(NSAttributedString(string: " ", attributes: body)) + appendLink(to: credits, label: "Report an Issue", url: ProjectLinks.issues) + credits.append(NSAttributedString(string: " ", attributes: body)) + appendLink(to: credits, label: "Discussions", url: ProjectLinks.discussions) NSApp.orderFrontStandardAboutPanel(options: [ .credits: credits @@ -1802,6 +2040,11 @@ extension Notification.Name { /// Posted by `showMainWindow(tab:)` to select a sidebar section in an /// already-open main window (object = SidebarItem raw value string). static let switchToSidebarTab = Notification.Name("MCPProxy.switchToSidebarTab") + /// Posted by a tray glance row to scope the Activity Log to the session it + /// came from (object = MCP session id string). F10 — a glance row that + /// opened the whole unfiltered log was the one place the "parent↔child + /// navigable" rule was not honoured. + static let activityFilter = Notification.Name("MCPProxy.activityFilter") } @main diff --git a/native/macos/MCPProxy/MCPProxy/Menu/TrayIcon.swift b/native/macos/MCPProxy/MCPProxy/Menu/TrayIcon.swift deleted file mode 100644 index a1ced50cf..000000000 --- a/native/macos/MCPProxy/MCPProxy/Menu/TrayIcon.swift +++ /dev/null @@ -1,57 +0,0 @@ -// TrayIcon.swift -// MCPProxy -// -// The label view for the MenuBarExtra. Renders a template icon in the -// menu bar that reflects the aggregate health level of the proxy. -// Spec 044 adds a small dot overlay keyed off the worst classified -// diagnostic severity across enabled servers — red for error, orange -// for warn — so users see attention-worthy failures at a glance. - -import SwiftUI - -struct TrayIcon: View { - @ObservedObject var appState: AppState - - var body: some View { - ZStack(alignment: .topTrailing) { - Image(systemName: iconName) - .symbolRenderingMode(.hierarchical) - if let badge = diagnosticBadgeColor { - Circle() - .fill(badge) - .frame(width: 5, height: 5) - .offset(x: 2, y: -2) - .accessibilityLabel( - appState.worstDiagnosticSeverity == "error" - ? "Server errors present" - : "Server warnings present" - ) - } - } - } - - /// SF Symbol name based on current health indicator. - private var iconName: String { - switch appState.healthLevel { - case .healthy: - return "server.rack" - case .degraded: - return "exclamationmark.triangle" - case .unhealthy: - return "xmark.circle" - case .disconnected: - return "antenna.radiowaves.left.and.right.slash" - } - } - - /// Spec 044 — colour the badge dot based on the worst classified - /// diagnostic severity. Returns nil when no diagnostics are attached, - /// which keeps the plain monochrome icon for healthy users. - private var diagnosticBadgeColor: Color? { - switch appState.worstDiagnosticSeverity { - case "error": return .red - case "warn": return .orange - default: return nil - } - } -} diff --git a/native/macos/MCPProxy/MCPProxy/Menu/TrayPresentation.swift b/native/macos/MCPProxy/MCPProxy/Menu/TrayPresentation.swift new file mode 100644 index 000000000..5215af69e --- /dev/null +++ b/native/macos/MCPProxy/MCPProxy/Menu/TrayPresentation.swift @@ -0,0 +1,221 @@ +// TrayPresentation.swift +// MCPProxy +// +// Pure presentation rules for the status-bar menu. Everything here is a value +// -> value function so the menu's *decisions* can be tested without AppKit, +// leaving `rebuildMenu()` to do nothing but hang the results on NSMenuItems. +// +// Introduced by the 2026-08 macOS tray UX audit (F1, F3, F11, F12, F15). + +import Foundation + +// MARK: - F1 · What the menu-bar icon says + +/// The one badge the status-bar button carries, in priority order. +/// +/// Before the audit the icon badged only *core stopped* and *core error*: with +/// five servers needing attention the menu bar looked exactly like all-healthy, +/// which defeats the point of a status item. `severity` restores the Spec 044 +/// red/orange dot that `TrayIcon.swift` was written for and never delivered +/// (that view was never instantiated). +enum TrayIconBadge: Equatable { + /// Everything is fine — the plain template icon, nothing beside it. + case none + /// The core is not running. + case stopped + /// The core reported an error. + case coreError + /// At least one enabled server has an attached warn/error diagnostic. + case severity(TrayIconSeverity) +} + +enum TrayIconSeverity: String, Equatable { + case warn + case error +} + +enum TrayStatusIcon { + /// Decide the badge from the three inputs the app delegate already has. + /// + /// Core state wins over server severity: a stopped or erroring core makes + /// every server verdict stale, so showing an amber server dot on top of it + /// would be a second, quieter story about the same outage. + static func badge(isStopped: Bool, hasCoreError: Bool, worstDiagnosticSeverity: String?) -> TrayIconBadge { + if isStopped { return .stopped } + if hasCoreError { return .coreError } + switch worstDiagnosticSeverity { + case "error": return .severity(.error) + case "warn": return .severity(.warn) + default: return .none + } + } + + /// The glyph drawn beside the template icon. Empty for `.none`. + /// + /// 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. + static func glyph(for badge: TrayIconBadge) -> String { + switch badge { + case .none: return "" + case .stopped: return "⏹" + case .coreError: return "⚠" + case .severity: return "●" + } + } + + /// 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 { + var parts = ["MCPProxy"] + if !summary.isEmpty { parts.append(summary) } + switch badge { + case .none: + break + case .stopped: + parts.append("core stopped") + case .coreError: + parts.append("core error") + case .severity(let severity): + let noun = severity == .error ? "error" : "warning" + parts.append(attentionCount == 1 + ? "1 server \(noun)" + : "\(attentionCount) server \(noun)s") + } + return parts.joined(separator: " — ") + } +} + +// MARK: - F12 · Transport names users recognise + +enum TrayProtocolDisplay { + /// `Protocol: streamable-http` beside `Protocol: http` and `Protocol: sse` + /// exposed three wire spellings of what users experience as one transport + /// family. Normalise for display only — the config value is untouched. + static func label(for raw: String) -> String { + switch raw.lowercased() { + case "stdio": return "stdio" + case "http": return "HTTP" + case "streamable-http", "streamable_http", "http-stream": return "HTTP (streamable)" + case "sse": return "HTTP (SSE)" + case "auto", "": return "auto-detect" + default: return raw + } + } +} + +// MARK: - F11 · Profiles that would scope agents to nothing + +enum TrayProfileDisplay { + /// The Web UI's ProfileSwitcher shows "N servers · M tools"; the tray showed + /// only the tool count, so a profile whose servers are not in the config + /// ("research (0 tools)") read as merely empty rather than broken. Switching + /// to it scopes every agent to zero servers. + /// + /// `knownServers` is the set of configured server names; a profile + /// referencing none of them is called out by name. + static func label(name: String, servers: [String], toolCount: Int, knownServers: Set) -> String { + let effective = servers.filter { knownServers.contains($0) }.count + if effective == 0 { + return "\(name) — no servers" + } + let serverWord = effective == 1 ? "server" : "servers" + return "\(name) (\(effective) \(serverWord) · \(toolCount) tools)" + } +} + +// MARK: - F15 · A Servers submenu that fits on screen + +/// How one server is filed in the Servers submenu. +enum TrayServerGroup: Equatable { + /// Something is wrong or waiting: sign-in, connection error, quarantine. + case needsAttention + /// Enabled and behaving. + case active + /// Switched off on purpose — the long tail, folded away. + case disabled +} + +enum TrayServerGrouping { + /// The audit found 29 flat alphabetical entries with 13 disabled and 3 + /// quarantined interleaved, distinguishable only by dot colour, in a + /// submenu taller than the screen. Attention first, then the working + /// servers, then the disabled ones behind one row. + /// + /// Generic over anything that can answer the three questions, so the + /// ordering is testable without building `ServerStatus` fixtures. + static func group(enabled: Bool, needsAttention: Bool) -> TrayServerGroup { + if !enabled { return .disabled } + return needsAttention ? .needsAttention : .active + } + + /// Below this many disabled servers, folding them costs a click and saves + /// nothing. At or above it the fold is the point. + static let disabledFoldThreshold = 3 +} + +// MARK: - F3 · Server actions that fail out loud + +/// The five per-server menu actions used to be fired as `try? await …`: a +/// restart that 500s was indistinguishable from one that worked, because the +/// menu simply closed. The Web UI raises a toast and Server Detail shows an +/// inline error, so the tray was the only surface that lied by omission. +enum TrayServerAction: String, Equatable { + case enable + case disable + case restart + case login + case approve + + /// Present tense, for the failure title: "Couldn't restart github". + var verb: String { + switch self { + case .enable: return "enable" + case .disable: return "disable" + case .restart: return "restart" + case .login: return "sign in to" + case .approve: return "approve" + } + } + + /// Imperative, for a menu row: the user must be told what a click does. + var menuTitle: String { + switch self { + case .enable: return "Enable" + case .disable: return "Disable" + case .restart: return "Restart" + case .login: return "Sign in" + case .approve: return "Review quarantine…" + } + } + + /// Maps the `health.action` string the core sends to the action the tray + /// would perform. `approve` is deliberately absent: a quarantine review is + /// a human decision, never something a menu click does on the user's + /// behalf. + static func fromHealthAction(_ action: String) -> TrayServerAction? { + switch action { + case "login": return .login + case "restart": return .restart + case "enable": return .enable + default: return nil + } + } +} + +enum TrayServerActionFailure { + static func title(action: TrayServerAction, server: String) -> String { + "Couldn’t \(action.verb) \(server)" + } + + /// The error as the user can act on it, with the one thing the tray knows + /// they can do next. Never empty — an alert with no body reads as a bug. + static func message(action: TrayServerAction, server: String, error: Error) -> String { + let detail = (error as? LocalizedError)?.errorDescription ?? error.localizedDescription + let body = detail.trimmingCharacters(in: .whitespacesAndNewlines) + let reason = body.isEmpty ? "The core did not say why." : body + return "\(reason)\n\nOpen \(server) in MCPProxy to see its logs, or try again." + } +} diff --git a/native/macos/MCPProxy/MCPProxy/Settings/ConfigSettingsView.swift b/native/macos/MCPProxy/MCPProxy/Settings/ConfigSettingsView.swift index 555123067..60185d790 100644 --- a/native/macos/MCPProxy/MCPProxy/Settings/ConfigSettingsView.swift +++ b/native/macos/MCPProxy/MCPProxy/Settings/ConfigSettingsView.swift @@ -21,6 +21,11 @@ final class ConfigStore: ObservableObject { @Published var loadError: String? /// Bumped on every mutation so SwiftUI re-evaluates dirty state. @Published var revision = 0 + /// The core's built-in MCP `instructions` text (MCP-2176), shown as the + /// placeholder of the instructions field so a blank box reads as "the + /// default is this" instead of "nothing". Fetched, never hardcoded — the + /// Web UI does the same and the two must not drift. + @Published var defaultInstructions: String? private var original: [String: Any] = [:] private let appState: AppState @@ -43,6 +48,11 @@ final class ConfigStore: ObservableObject { } catch { loadError = (error as? APIClientError)?.errorDescription ?? error.localizedDescription } + // Best-effort: an older core without the field just leaves the generic + // placeholder in place, so this never fails the settings load. + if let status = try? await api.status(), let text = status.defaultInstructions, !text.isEmpty { + defaultInstructions = text + } loading = false } @@ -304,32 +314,47 @@ struct ConfigFieldRow: View { private var validationError: String? { dirty ? validateConfigField(field, store.value(field.key)) : nil } var body: some View { - HStack(alignment: .top) { - VStack(alignment: .leading, spacing: 2) { - HStack(spacing: 6) { - Text(field.label).fontWeight(.medium) - if dirty { Circle().fill(Color.orange).frame(width: 6, height: 6) } - if field.restart { - Text("restart").font(.caption2).padding(.horizontal, 5).padding(.vertical, 1) - .background(Color.orange.opacity(0.25)).cornerRadius(4) - } - if let docs = field.docs, let url = URL(string: SettingsCatalog.docsBase + docs) { - Link("docs ↗", destination: url).font(.caption) - } - } - if let help = field.help { - Text(help).font(.caption).foregroundColor(.secondary).fixedSize(horizontal: false, vertical: true) + Group { + // A textarea cannot share a row with its label — 240pt of trailing + // column is not a place to edit a paragraph. It stacks instead. + if field.control == .textarea { + VStack(alignment: .leading, spacing: 6) { + labelBlock + control.frame(maxWidth: .infinity, alignment: .leading) } - if let err = validationError { - Text(err).font(.caption).foregroundColor(.red) + } else { + HStack(alignment: .top) { + labelBlock + Spacer(minLength: 16) + control.frame(maxWidth: 240, alignment: .trailing) } } - Spacer(minLength: 16) - control.frame(maxWidth: 240, alignment: .trailing) } .padding(.vertical, 8) } + private var labelBlock: some View { + VStack(alignment: .leading, spacing: 2) { + HStack(spacing: 6) { + Text(field.label).fontWeight(.medium) + if dirty { Circle().fill(Color.orange).frame(width: 6, height: 6) } + if field.restart { + Text("restart").font(.caption2).padding(.horizontal, 5).padding(.vertical, 1) + .background(Color.orange.opacity(0.25)).cornerRadius(4) + } + if let docs = field.docs, let url = URL(string: SettingsCatalog.docsBase + docs) { + Link("docs ↗", destination: url).font(.caption) + } + } + if let help = field.help { + Text(help).font(.caption).foregroundColor(.secondary).fixedSize(horizontal: false, vertical: true) + } + if let err = validationError { + Text(err).font(.caption).foregroundColor(.red) + } + } + } + @ViewBuilder private var control: some View { switch field.control { case .toggle: @@ -340,9 +365,36 @@ struct ConfigFieldRow: View { } .labelsHidden().frame(maxWidth: 220) case .number: - TextField("", value: store.doubleBinding(field.key), format: .number) - .multilineTextAlignment(.trailing).frame(width: 100) - .textFieldStyle(.roundedBorder) + HStack(spacing: 4) { + TextField("", value: store.doubleBinding(field.key), format: .number) + .multilineTextAlignment(.trailing).frame(width: 100) + .textFieldStyle(.roundedBorder) + // F13: fields.ts gives entropy_threshold step 0.1 and + // oauth_expiry_warning_hours step 0.5; without a stepper the + // native form could only be typed into. + if let step = field.step { + Stepper("", value: store.doubleBinding(field.key), + in: (field.min ?? -.greatestFiniteMagnitude)...(field.max ?? .greatestFiniteMagnitude), + step: step) + .labelsHidden() + } + } + case .textarea: + // The instructions field: multi-line, and its placeholder is the + // live built-in default rather than an example. + ZStack(alignment: .topLeading) { + TextEditor(text: store.optionalStringBinding(field.key)) + .font(.system(.callout, design: .monospaced)) + .frame(minHeight: 120) + .overlay(RoundedRectangle(cornerRadius: 6).stroke(Color(nsColor: .separatorColor))) + if coerceString(store.value(field.key)).isEmpty { + Text(store.defaultInstructions ?? field.placeholder ?? "") + .font(.system(.caption, design: .monospaced)) + .foregroundColor(.secondary) + .padding(.horizontal, 6).padding(.vertical, 10) + .allowsHitTesting(false) + } + } case .text, .duration: // Duration fields are tri-state: an optional one stores a blank // value as "unset" (reset to default) via optionalStringBinding. diff --git a/native/macos/MCPProxy/MCPProxy/Settings/SettingsCatalog.swift b/native/macos/MCPProxy/MCPProxy/Settings/SettingsCatalog.swift index 7f2e8a114..094c506bd 100644 --- a/native/macos/MCPProxy/MCPProxy/Settings/SettingsCatalog.swift +++ b/native/macos/MCPProxy/MCPProxy/Settings/SettingsCatalog.swift @@ -9,7 +9,7 @@ import Foundation // MARK: - Pinned types (view layer depends on these — do not rename) -enum ConfigControl { case toggle, select, number, text, secret, duration, multiselect } +enum ConfigControl { case toggle, select, number, text, textarea, secret, duration, multiselect } enum ConfigValueKind { case hostport, bytesize, cpu, hostname, url, secretkey } struct ConfigOption: Identifiable { let value: String; let label: String; var id: String { value } } @@ -22,6 +22,10 @@ struct ConfigField: Identifiable { var options: [ConfigOption] = [] var min: Double? = nil var max: Double? = nil + // Increment for a `.number` stepper. Mirrors `step` in fields.ts — without + // it a fractional field (entropy 4.5, OAuth warning 1.5h) can only be typed, + // never nudged (F13). + var step: Double? = nil var restart: Bool = false var docs: String? = nil // doc path on docs.mcpproxy.app var valueKind: ConfigValueKind? = nil @@ -66,7 +70,8 @@ enum SettingsCatalog { control: .secret, restart: true, valueKind: .secretkey, - optional: true + optional: true, + placeholder: "\u{2022}\u{2022}\u{2022}\u{2022}\u{2022}\u{2022}\u{2022}\u{2022} (unchanged \u{2014} type to replace)" ), ConfigField( key: "require_mcp_auth", @@ -83,6 +88,16 @@ enum SettingsCatalog { dangerMessage: "Disabling quarantine removes Tool Poisoning Attack protection — new servers and changed tools will run without your approval. Continue?", dangerConfirmValue: false ), + // Spec 088 US4 / FR-018 — the deep-scan layer was reachable only by + // hand-editing this key, and the tray's Raw tab is read-only, so it was + // unreachable from the tray entirely (F6). + ConfigField( + key: "security.deep_scan.enabled", + label: "Deep scan (Docker scanners)", + help: "The deterministic offline baseline scan is always on and needs no setup. Turning this on adds the opt-in Docker-based deep scanners (source-level analysis of the server\u{2019}s published package) on top of it. Requires Docker; a deep-scan failure is informational and never changes the baseline verdict.", + control: .toggle, + docs: "/features/security-scanner-plugins" + ), ConfigField( key: "docker_isolation.enabled", label: "Run stdio servers in Docker", @@ -125,6 +140,7 @@ enum SettingsCatalog { control: .text, restart: true, valueKind: .hostport, + placeholder: "127.0.0.1:8080", dangerMessage: "Binding to a non-loopback address (e.g. 0.0.0.0) exposes mcpproxy to your network. Make sure \u{201C}Require API key for MCP clients\u{201D} is enabled. Continue?" ), ] @@ -175,10 +191,10 @@ enum SettingsCatalog { ConfigField( key: "telemetry.enabled", label: "Anonymous usage telemetry", - help: "Sends anonymous usage counts (never tool arguments, content, or identities). Opt-out at any time.", + help: "Sends anonymous usage counts (never tool arguments, content, or identities). Opt-out at any time. Disabling sends a single anonymous opt-out signal, then stops all telemetry.", control: .toggle, docs: "/features/telemetry", - dangerMessage: "Anonymous telemetry is how we see which features matter and catch problems — it never includes your tool arguments, content, or any identifying info. Turning it off removes that signal. Turn it off anyway?", + dangerMessage: "Anonymous telemetry is how we see which features matter and catch problems — it never includes your tool arguments, content, or any identifying info. Turning it off removes that signal, and sends a single anonymous opt-out signal before all telemetry stops. Turn it off anyway?", dangerConfirmValue: false, dangerInfoTone: true ), @@ -192,6 +208,27 @@ enum SettingsCatalog { // ---- Section 3: Advanced (subsystem accordions) ---- static let advanced: [ConfigSection] = [ + // The whole accordion was missing from the tray (F6): the one setting + // that changes what every connected AI client is told about the proxy + // could not be edited outside the Web UI. + ConfigSection( + id: "mcp", + title: "MCP server instructions", + help: "Text sent to AI clients in the MCP initialize response, guiding how to use the proxy. Power-user, set-once option.", + fields: [ + ConfigField( + key: "instructions", + label: "Server instructions", + // Empty saves "" — Go maps that back to the built-in + // default, fetched live into the placeholder (see + // ConfigStore.defaultInstructions) so it never drifts. + help: "Leave blank to use the built-in default (shown greyed-out). Applied on the next client connect, not to already-connected sessions.", + control: .textarea, + optional: true, + placeholder: "Loading built-in default…" + ), + ] + ), ConfigSection( id: "code-execution", title: "Code execution", @@ -201,6 +238,8 @@ enum SettingsCatalog { ConfigField(key: "code_execution_timeout_ms", label: "Max run time per execution (ms)", control: .number, min: 1, max: 600000), ConfigField(key: "code_execution_max_tool_calls", label: "Max tool calls per execution", help: "0 = unlimited.", control: .number, min: 0), ConfigField(key: "code_execution_pool_size", label: "JavaScript runtime pool size", help: "How many sandboxes run concurrently.", control: .number, min: 1, max: 100), + // Spec 096 field, added web-side only (F6). + ConfigField(key: "code_execution_max_parallel", label: "Parallel calls per call_tools() batch", help: "Default concurrency for batched tool calls; a script can override it per call (1-32).", control: .number, min: 1, max: 32), ] ), ConfigSection( @@ -210,9 +249,9 @@ enum SettingsCatalog { docs: "/features/docker-isolation", fields: [ ConfigField(key: "docker_isolation.network_mode", label: "Container network", help: "none = no network (most secure), bridge = NAT, host = share host network.", control: .select, options: ["bridge", "none", "host"].map { ConfigOption(value: $0, label: $0) }), - ConfigField(key: "docker_isolation.memory_limit", label: "Memory limit per container", control: .text, valueKind: .bytesize, optional: true), - ConfigField(key: "docker_isolation.cpu_limit", label: "CPU limit per container", control: .text, valueKind: .cpu, optional: true), - ConfigField(key: "docker_isolation.registry", label: "Container image registry", control: .text, valueKind: .hostname, optional: true), + ConfigField(key: "docker_isolation.memory_limit", label: "Memory limit per container", control: .text, valueKind: .bytesize, optional: true, placeholder: "512m"), + ConfigField(key: "docker_isolation.cpu_limit", label: "CPU limit per container", control: .text, valueKind: .cpu, optional: true, placeholder: "1.0"), + ConfigField(key: "docker_isolation.registry", label: "Container image registry", control: .text, valueKind: .hostname, optional: true, placeholder: "docker.io"), ConfigField(key: "docker_isolation.enable_cache_volume", label: "Share a package cache volume", help: "Speeds up repeated npm/uvx installs by caching across containers.", control: .toggle), ] ), @@ -225,7 +264,7 @@ enum SettingsCatalog { ConfigField(key: "sensitive_data_detection.scan_requests", label: "Scan tool arguments", control: .toggle), ConfigField(key: "sensitive_data_detection.scan_responses", label: "Scan tool responses", control: .toggle), ConfigField(key: "sensitive_data_detection.max_payload_size_kb", label: "Max payload scanned (KB)", help: "Larger payloads are scanned only up to this size.", control: .number, min: 1), - ConfigField(key: "sensitive_data_detection.entropy_threshold", label: "Randomness threshold", help: "Higher = fewer false positives when flagging random-looking strings (default 4.5).", control: .number, min: 0, max: 8), + ConfigField(key: "sensitive_data_detection.entropy_threshold", label: "Randomness threshold", help: "Higher = fewer false positives when flagging random-looking strings (default 4.5).", control: .number, min: 0, max: 8, step: 0.1), ] ), ConfigSection( @@ -298,7 +337,7 @@ enum SettingsCatalog { title: "Other", fields: [ ConfigField(key: "max_result_size_chars", label: "Max inline response to the client (characters)", help: "Hard ceiling on a single response sent inline. 0 = no ceiling.", control: .number, min: 0), - ConfigField(key: "oauth_expiry_warning_hours", label: "Warn before OAuth token expires (hours)", help: "How early a server is shown as \u{201C}degraded\u{201D} before its OAuth token expires.", control: .number, min: 0), + ConfigField(key: "oauth_expiry_warning_hours", label: "Warn before OAuth token expires (hours)", help: "How early a server is shown as \u{201C}degraded\u{201D} before its OAuth token expires.", control: .number, min: 0, step: 0.5), ConfigField(key: "disable_management", label: "Block agents from managing servers", help: "Prevents agents from using the upstream_servers management tool.", control: .toggle, dangerMessage: "This prevents agents from adding or removing servers via the management tool. Continue?", dangerConfirmValue: true), ConfigField(key: "allow_server_add", label: "Let agents add servers", control: .toggle), ConfigField(key: "allow_server_remove", label: "Let agents remove servers", control: .toggle), diff --git a/native/macos/MCPProxy/MCPProxy/State/AppState.swift b/native/macos/MCPProxy/MCPProxy/State/AppState.swift index 1f6d7b40e..0ef374939 100644 --- a/native/macos/MCPProxy/MCPProxy/State/AppState.swift +++ b/native/macos/MCPProxy/MCPProxy/State/AppState.swift @@ -11,15 +11,11 @@ import Foundation import Combine -// MARK: - Health Indicator (tray icon badge) - -/// Tray icon badge level, derived from aggregated server health. -enum HealthIndicator: String, Sendable { - case healthy - case degraded - case unhealthy - case disconnected -} +// The former `HealthIndicator` enum and `AppState.healthLevel` lived here to +// feed `Menu/TrayIcon.swift` — a SwiftUI menu-bar label that was never +// instantiated, so both were dead from the day they were written (found by the +// 2026-08 tray UX audit, F1). The status item is AppKit and now badges server +// severity itself; see `TrayStatusIcon` in Menu/TrayPresentation.swift. // MARK: - App State @@ -327,35 +323,6 @@ final class AppState: ObservableObject { return sawWarn ? "warn" : nil } - /// Aggregate health indicator for the tray icon badge. - /// Only considers ENABLED servers. Disabled servers are intentional — don't flag them. - /// Uses majority-based logic: green if most are healthy, yellow if some degraded, - /// red only if the majority are unhealthy. - var healthLevel: HealthIndicator { - guard coreState == .connected else { - return .disconnected - } - - let enabled = servers.filter { $0.enabled } - if enabled.isEmpty { - return .healthy - } - - let unhealthyCount = enabled.filter { $0.health?.level == "unhealthy" }.count - let degradedCount = enabled.filter { $0.health?.level == "degraded" }.count - let total = enabled.count - - // Red only if more than half of enabled servers are unhealthy - if unhealthyCount > total / 2 { - return .unhealthy - } - // Yellow if any degraded or unhealthy (but not majority) - if unhealthyCount > 0 || degradedCount > 0 { - return .degraded - } - return .healthy - } - /// Whether the tray is connected to a running core. var isConnected: Bool { coreState == .connected diff --git a/native/macos/MCPProxy/MCPProxy/Views/ActivityView.swift b/native/macos/MCPProxy/MCPProxy/Views/ActivityView.swift index 8d3477974..7a78acc2b 100644 --- a/native/macos/MCPProxy/MCPProxy/Views/ActivityView.swift +++ b/native/macos/MCPProxy/MCPProxy/Views/ActivityView.swift @@ -32,6 +32,11 @@ struct ActivityView: View { /// (records whose parent_id equals it). Set by "View sub-calls" in the /// detail panel; cleared by the filter chip or "View parent call". @State private var filterParentId: String? + /// When set, the list shows only the records of one MCP session. Seeded by + /// a tray glance row (`.activityFilter`) so a click on "github:search ×12" + /// lands on that client's calls instead of the whole log (F10); cleared by + /// its own chip. + @State private var filterSessionId: String? /// Monotonic ticket for loadActivities: only the NEWEST in-flight load may /// publish its results, so a slow unfiltered fetch can never overwrite the /// sub-call view the user just asked for (or vice versa). @@ -94,9 +99,21 @@ struct ActivityView: View { if let parentId = filterParentId, !parentId.isEmpty { parts.append("parent_id=\(parentId)") } + if let sessionId = filterSessionId, !sessionId.isEmpty, + let encoded = sessionId.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) { + parts.append("session_id=\(encoded)") + } return parts.joined(separator: "&") } + /// Scope the list to one MCP session (a tray glance row's hand-off). + private func showSession(_ sessionId: String) { + filterSessionId = sessionId + filterParentId = nil + selectedActivityID = nil + Task { await loadActivities() } + } + // MARK: - Parent/child navigation (code_execution sub-calls) /// Filter the list down to the children of one code_execution call. @@ -226,6 +243,11 @@ struct ActivityView: View { await loadActivities() } } + // F10: a tray glance row hands over the session it was derived from. + .onReceive(NotificationCenter.default.publisher(for: .activityFilter)) { note in + guard let sessionId = note.object as? String, !sessionId.isEmpty else { return } + showSession(sessionId) + } } // MARK: - Table Header @@ -410,6 +432,36 @@ struct ActivityView: View { .clipShape(Capsule()) .accessibilityIdentifier("activity-parent-filter-chip") } + + // Session filter chip (F10): says which client's calls are on + // screen, and how to get back to everything. + if let sessionId = filterSessionId { + HStack(spacing: 6) { + Image(systemName: "person.crop.circle") + .font(.scaled(.caption, scale: fontScale)) + Text("Session \(Self.shortCorrelationId(sessionId))") + .font(.scaled(.caption, scale: fontScale)) + .lineLimit(1) + .truncationMode(.middle) + Button { + filterSessionId = nil + Task { await loadActivities() } + } label: { + Image(systemName: "xmark.circle.fill") + .foregroundStyle(.secondary) + } + .buttonStyle(.borderless) + .help("Show all activity") + .accessibilityLabel("Clear session filter") + .accessibilityIdentifier("activity-clear-session-filter") + Spacer() + } + .padding(.horizontal, 10) + .padding(.vertical, 5) + .background(Color.accentColor.opacity(0.12)) + .clipShape(Capsule()) + .accessibilityIdentifier("activity-session-filter-chip") + } } .padding(.horizontal) .padding(.bottom, 8) diff --git a/native/macos/MCPProxy/MCPProxy/Views/MainWindow.swift b/native/macos/MCPProxy/MCPProxy/Views/MainWindow.swift index bf0520c3c..062c92f97 100644 --- a/native/macos/MCPProxy/MCPProxy/Views/MainWindow.swift +++ b/native/macos/MCPProxy/MCPProxy/Views/MainWindow.swift @@ -6,9 +6,17 @@ import SwiftUI enum SidebarItem: String, CaseIterable, Identifiable { case dashboard = "Dashboard" case servers = "Servers" + // F16: BM25 tool discovery is the product's headline feature and had no + // native home — a tray-first user could not answer "which of my 942 tools + // does X?" without opening a browser. + case tools = "Tools" case registries = "Registries" case activity = "Activity Log" case secrets = "Secrets" + // F5: TokensView was a complete, API-complete create/list/revoke UI that + // nothing instantiated — a headline security feature reachable from the + // Web UI and the CLI but not from the app the user has open. + case tokens = "Agent Tokens" var id: String { rawValue } @@ -16,9 +24,11 @@ enum SidebarItem: String, CaseIterable, Identifiable { switch self { case .dashboard: return "rectangle.3.group" case .servers: return "server.rack" + case .tools: return "wrench.and.screwdriver" case .registries: return "books.vertical" case .activity: return "clock.arrow.circlepath" case .secrets: return "key.fill" + case .tokens: return "key.horizontal" } } @@ -70,12 +80,16 @@ struct MainWindow: View { DashboardView(appState: appState) case .servers: ServersView(appState: appState) + case .tools: + ToolsView(appState: appState) case .registries: RegistriesView(appState: appState) case .activity: ActivityView(appState: appState) case .secrets: SecretsView(appState: appState) + case .tokens: + TokensView(appState: appState) } } .frame(maxWidth: .infinity, maxHeight: .infinity) diff --git a/native/macos/MCPProxy/MCPProxy/Views/SettingsView.swift b/native/macos/MCPProxy/MCPProxy/Views/SettingsView.swift index 0288da878..59591750e 100644 --- a/native/macos/MCPProxy/MCPProxy/Views/SettingsView.swift +++ b/native/macos/MCPProxy/MCPProxy/Views/SettingsView.swift @@ -59,8 +59,12 @@ private struct AppPrefsTab: View { var body: some View { Form { Section { - Toggle("Launch MCPProxy at login", isOn: $launchAtLogin) + // F9: the tray menu calls this same AutoStartService setting + // "Launch at Login" — one setting, one name. + Toggle("Launch at Login", isOn: $launchAtLogin) .onChange(of: launchAtLogin) { applyLaunchAtLogin($0) } + Text("Starts the MCPProxy app when you log in. Also shown as “Launch at Login” in the menu-bar menu.") + .font(.callout).foregroundColor(.secondary) if let launchError { Text(launchError).font(.callout).foregroundColor(.red) } @@ -78,7 +82,13 @@ private struct AppPrefsTab: View { Text("MCPProxy will not start the core. It still connects to a core you start yourself, and you can start one from the menu at any time.") .font(.callout).foregroundColor(.secondary) } - } header: { Text("Startup") } + } header: { Text("Startup") } footer: { + // F9: these two and the menu's "Start/Stop MCPProxy Core" are a + // genuinely confusable trio — one is at login, one is at app + // launch, one is right now — and nothing said so. + Text("These settings act at login and at app launch. To start or stop the core right now, use “Start/Stop MCPProxy Core” in the menu-bar menu.") + .font(.callout).foregroundColor(.secondary) + } Section { HStack { @@ -98,6 +108,18 @@ private struct AppPrefsTab: View { Text(appState.isConnected ? "Connected" : "Not connected") } } + // F14: the tray had no feedback path at all while the Web UI + // has /feedback and the CLI has `mcpproxy feedback`. A + // Homebrew user who never sees the repo now has one here and + // in the About panel — without spending a menu row. + LabeledContent("Help") { + HStack(spacing: 12) { + Link("Documentation", destination: ProjectLinks.docs) + Link("Report an Issue", destination: ProjectLinks.issues) + Link("Discussions", destination: ProjectLinks.discussions) + } + .font(.callout) + } } header: { Text("About") } footer: { Text("All server configuration is managed in the Security, General and Advanced tabs.") .font(.callout).foregroundColor(.secondary) diff --git a/native/macos/MCPProxy/MCPProxy/Views/ToolsView.swift b/native/macos/MCPProxy/MCPProxy/Views/ToolsView.swift new file mode 100644 index 000000000..ffc903496 --- /dev/null +++ b/native/macos/MCPProxy/MCPProxy/Views/ToolsView.swift @@ -0,0 +1,222 @@ +// ToolsView.swift +// MCPProxy +// +// F16 (2026-08 tray UX audit): BM25 tool discovery is the product's headline +// feature and the tray had no native equivalent of the Web UI's /search and +// /tools — per-server tools were visible only inside Server Detail, so a +// tray-first user could not answer "which of my 942 tools does X?" without +// opening a browser. +// +// Empty query -> the whole catalogue (GET /api/v1/tools), grouped by server. +// Typed query -> BM25 ranking (GET /api/v1/index/search), best match first. +// +// Both REST surfaces return the BARE tool name with `server_name` alongside +// (#871); `server:tool` is assembled here, never taken from `name`. + +import SwiftUI + +struct ToolsView: View { + @ObservedObject var appState: AppState + @Environment(\.fontScale) var fontScale + + @State private var query = "" + @State private var rows: [ToolRow] = [] + @State private var isLoading = false + @State private var errorMessage: String? + /// Only the newest in-flight load may publish, so a slow catalogue fetch + /// cannot overwrite the search results the user just asked for. + @State private var loadGeneration = 0 + @State private var selectedID: String? + + private var apiClient: APIClient? { appState.apiClient } + + /// One row of the list: a tool, its server, and (for a search) its rank. + struct ToolRow: Identifiable, Equatable { + let server: String + let name: String + let description: String + let score: Double? + + /// The canonical MCP identity — what an agent would actually call. + var qualified: String { server.isEmpty ? name : "\(server):\(name)" } + var id: String { qualified } + } + + var body: some View { + VStack(alignment: .leading, spacing: 0) { + header + searchBar + Divider() + content + } + .task { await load() } + .onChange(of: appState.totalTools) { _ in + // The index rebuilt (a server connected, tools re-discovered). + if query.isEmpty { Task { await load() } } + } + } + + // MARK: - Header + + private var header: some View { + HStack { + Text("Tools") + .font(.scaled(.title2, scale: fontScale).bold()) + Spacer() + if isLoading { ProgressView().controlSize(.small) } + Text(countLabel) + .font(.scaled(.caption, scale: fontScale)) + .foregroundStyle(.secondary) + } + .padding(.horizontal) + .padding(.top, 12) + .padding(.bottom, 6) + } + + private var countLabel: String { + if rows.isEmpty { return "" } + let noun = rows.count == 1 ? "tool" : "tools" + return query.isEmpty + ? "\(rows.count) \(noun)" + : "\(rows.count) \(noun) matched" + } + + private var searchBar: some View { + HStack(spacing: 6) { + Image(systemName: "magnifyingglass").foregroundStyle(.secondary) + TextField("Search all tools — the same BM25 ranking agents get", text: $query) + .textFieldStyle(.plain) + .accessibilityIdentifier("tools-search-field") + .onSubmit { Task { await load() } } + .onChange(of: query) { _ in Task { await load() } } + if !query.isEmpty { + Button { + query = "" + } label: { + Image(systemName: "xmark.circle.fill").foregroundStyle(.secondary) + } + .buttonStyle(.borderless) + .accessibilityLabel("Clear search") + } + } + .padding(.horizontal) + .padding(.bottom, 10) + } + + // MARK: - Content + + @ViewBuilder + private var content: some View { + if let errorMessage { + VStack(spacing: 8) { + Image(systemName: "exclamationmark.triangle").font(.title2).foregroundStyle(.orange) + Text("Couldn’t load tools").font(.scaled(.headline, scale: fontScale)) + Text(errorMessage).font(.scaled(.caption, scale: fontScale)).foregroundStyle(.secondary) + Button("Retry") { Task { await load() } } + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + } else if rows.isEmpty && !isLoading { + VStack(spacing: 8) { + Image(systemName: "wrench.and.screwdriver").font(.title2).foregroundStyle(.secondary) + Text(query.isEmpty ? "No tools indexed yet" : "No tool matches “\(query)”") + .font(.scaled(.headline, scale: fontScale)) + Text(query.isEmpty + ? "Connect a server and its tools appear here." + : "Try fewer or more general words — this is the same search agents run.") + .font(.scaled(.caption, scale: fontScale)) + .foregroundStyle(.secondary) + } + .frame(maxWidth: .infinity, maxHeight: .infinity) + } else { + List(rows, selection: $selectedID) { row in + toolRow(row) + .contextMenu { + Button("Copy Tool Name") { + NSPasteboard.general.clearContents() + NSPasteboard.general.setString(row.qualified, forType: .string) + } + Button("Open \(row.server)") { openServer(row.server) } + .disabled(row.server.isEmpty) + } + } + .listStyle(.inset) + .accessibilityIdentifier("tools-list") + } + } + + private func toolRow(_ row: ToolRow) -> some View { + VStack(alignment: .leading, spacing: 2) { + HStack(spacing: 6) { + Text(row.name) + .font(.scaled(.body, scale: fontScale).weight(.medium)) + .textSelection(.enabled) + Text(row.server) + .font(.scaled(.caption2, scale: fontScale)) + .padding(.horizontal, 5).padding(.vertical, 1) + .background(Color.accentColor.opacity(0.15)) + .clipShape(Capsule()) + Spacer() + if let score = row.score { + Text(String(format: "%.2f", score)) + .font(.scaled(.caption2, scale: fontScale).monospacedDigit()) + .foregroundStyle(.secondary) + .help("BM25 relevance score") + } + } + if !row.description.isEmpty { + Text(row.description) + .font(.scaled(.caption, scale: fontScale)) + .foregroundStyle(.secondary) + .lineLimit(2) + } + } + .padding(.vertical, 3) + .accessibilityElement(children: .combine) + .accessibilityLabel("\(row.qualified). \(row.description)") + } + + private func openServer(_ server: String) { + guard !server.isEmpty else { return } + NotificationCenter.default.post(name: .switchToServers, object: nil) + DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { + NotificationCenter.default.post(name: .showServerDetail, object: server) + } + } + + // MARK: - Loading + + private func load() async { + guard let client = apiClient else { + rows = [] + errorMessage = "MCPProxy is not connected to a running core." + return + } + loadGeneration += 1 + let generation = loadGeneration + let term = query.trimmingCharacters(in: .whitespacesAndNewlines) + isLoading = true + defer { if generation == loadGeneration { isLoading = false } } + + do { + let fetched: [ToolRow] + if term.isEmpty { + fetched = try await client.allTools().map { + ToolRow(server: $0.serverName ?? "", name: $0.name, + description: $0.description ?? "", score: nil) + } + } else { + fetched = try await client.searchTools(query: term).map { + ToolRow(server: $0.tool.serverName ?? "", name: $0.tool.name, + description: $0.tool.description ?? "", score: $0.score) + } + } + guard generation == loadGeneration else { return } + rows = fetched + errorMessage = nil + } catch { + guard generation == loadGeneration else { return } + rows = [] + errorMessage = error.localizedDescription + } + } +} diff --git a/native/macos/MCPProxy/MCPProxyTests/TrayAuditMenuTests.swift b/native/macos/MCPProxy/MCPProxyTests/TrayAuditMenuTests.swift new file mode 100644 index 000000000..64c809d60 --- /dev/null +++ b/native/macos/MCPProxy/MCPProxyTests/TrayAuditMenuTests.swift @@ -0,0 +1,340 @@ +// TrayAuditMenuTests.swift +// MCPProxyTests +// +// Drives the real `rebuildMenu()` and pins the menu-shaped fixes from the +// 2026-08 macOS tray UX audit: +// +// F4 a "Needs Attention" row no longer runs an API action on a click that +// reads as navigation — the verb has its own row +// F7 one operation, one verb pair (Enable/Disable), stdio included +// F8a a quarantined server offers a review path +// F9 the login item is called the same thing here and in Settings; the two +// "open" rows say where they open +// F11 a profile that resolves to no servers says so +// F12 transports are display-normalised +// F15 the Servers submenu groups by state and folds the disabled tail +// +// Same seams as MenuStructureTests / SupersedeMenuTests, so a regression fails +// here rather than shipping. + +import XCTest +import AppKit +@testable import MCPProxy + +@MainActor +final class TrayAuditMenuTests: XCTestCase { + + private final class TestMenuHost: TrayMenuHost { + var menu: NSMenu? + } + + private func makeController(servers: [ServerStatus] = [], + profiles: [ProfileSummary] = []) -> (AppController, TestMenuHost) { + let host = TestMenuHost() + let controller = AppController( + glanceDataSource: CountingGlanceDataSource(), menuHost: host + ) + controller.appState.coreState = .connected + controller.appState.servers = servers + controller.appState.profiles = profiles + return (controller, host) + } + + private func topLevelTitles(_ host: TestMenuHost) -> [String] { + (host.menu?.items ?? []).map(\.title) + } + + private func submenu(_ host: TestMenuHost, startingWith prefix: String) throws -> NSMenu { + let parent = try XCTUnwrap( + (host.menu?.items ?? []).first { $0.title.hasPrefix(prefix) }, + "expected a top-level item starting with \(prefix); got \(topLevelTitles(host))") + return try XCTUnwrap(parent.submenu) + } + + private func serverSubmenu(_ host: TestMenuHost, named name: String) throws -> NSMenu { + let servers = try submenu(host, startingWith: "Servers (") + let item = try XCTUnwrap(servers.items.first { $0.title == name }, + "no row for \(name) in \(servers.items.map(\.title))") + return try XCTUnwrap(item.submenu) + } + + // MARK: - F7 · One verb pair + + /// The audit's Appendix A: four rows, identical admin state, four different + /// verbs — and a stdio submenu reading "Disabled … Start". + func testStdioAndHTTPServersUseTheSameEnableDisableVerbs() throws { + let (controller, host) = makeController(servers: [ + Self.server(name: "stdio-on", proto: "stdio", enabled: true), + Self.server(name: "http-on", proto: "http", enabled: true), + Self.server(name: "stdio-off", proto: "stdio", enabled: false), + Self.server(name: "http-off", proto: "http", enabled: false), + ]) + controller.rebuildMenu() + + for name in ["stdio-on", "http-on"] { + let titles = try serverSubmenu(host, named: name).items.map(\.title) + XCTAssertTrue(titles.contains("Disable"), "\(name): \(titles)") + XCTAssertFalse(titles.contains("Stop"), "process-control verbs are a different mental model") + } + // Disabled servers are folded (F15) — reach them through the fold when + // there are enough of them, or inline when there are not. + for name in ["stdio-off", "http-off"] { + let titles = try Self.disabledServerSubmenu(host, named: name).items.map(\.title) + XCTAssertTrue(titles.contains("Enable"), "\(name): \(titles)") + XCTAssertFalse(titles.contains("Start")) + } + } + + // MARK: - F12 · Transport names + + func testTheProtocolLineIsDisplayNormalised() throws { + let (controller, host) = makeController(servers: [ + Self.server(name: "everything", proto: "streamable-http", enabled: true) + ]) + controller.rebuildMenu() + + let titles = try serverSubmenu(host, named: "everything").items.map(\.title) + XCTAssertTrue(titles.contains("Protocol: HTTP (streamable)"), "\(titles)") + XCTAssertFalse(titles.contains("Protocol: streamable-http")) + } + + // MARK: - F8a · A path to the quarantine review + + func testAQuarantinedServerOffersAReview() throws { + let (controller, host) = makeController(servers: [ + Self.server(name: "everything", proto: "http", enabled: true, quarantined: true) + ]) + controller.rebuildMenu() + + let items = try serverSubmenu(host, named: "everything").items + let review = try XCTUnwrap(items.first { $0.title.hasPrefix("Review quarantine") }, + "quarantined server offered only \(items.map(\.title))") + XCTAssertNotNil(review.action, "a review row with no action is the F14 dead link again") + XCTAssertTrue(review.target === controller) + XCTAssertEqual(review.representedObject as? String, "everything") + } + + func testAHealthyServerHasNoReviewRow() throws { + let (controller, host) = makeController(servers: [ + Self.server(name: "github", proto: "http", enabled: true) + ]) + controller.rebuildMenu() + let titles = try serverSubmenu(host, named: "github").items.map(\.title) + XCTAssertFalse(titles.contains { $0.hasPrefix("Review quarantine") }) + } + + // MARK: - F4 · Attention rows do not mutate on a navigation click + + func testAnAttentionRowDoesNotFireItsActionOnClick() throws { + let (controller, host) = makeController(servers: [ + Self.server(name: "cloudflare", proto: "http", enabled: true, + health: ("degraded", "Sign-in required", "login")) + ]) + controller.rebuildMenu() + + let attention = try submenu(host, startingWith: "Needs Attention") + let row = try XCTUnwrap(attention.items.first) + // An item that owns a submenu is wired by AppKit to its own + // `submenuAction:` (and targeted at the submenu). What matters is that + // the row no longer carries the ServerStatus payload the old handler + // acted on, so no API call is reachable by clicking the row. + XCTAssertEqual(row.action, NSSelectorFromString("submenuAction:"), + "the row itself must do nothing — clicking it used to sign in / restart / ENABLE a server") + XCTAssertNil(row.representedObject as? ServerStatus) + let rowMenu = try XCTUnwrap(row.submenu, "the action needs somewhere explicit to live") + XCTAssertEqual(rowMenu.items.first?.title, "Sign in") + XCTAssertNotNil(rowMenu.items.first?.action) + XCTAssertTrue(rowMenu.items.first?.target === controller) + XCTAssertTrue(rowMenu.items.map(\.title).contains("Open Server Details")) + } + + /// The security case the audit calls out by name: enabling a server is a + /// state change and must never be an unlabelled side effect. + /// + /// A disabled server is intentional, so it is not in Needs Attention at + /// all (`AppState.serversNeedingAttention` drops `enable`) — the only way + /// to enable one from the tray is the explicitly named row under + /// `Servers ▸ ▸ Enable`. + func testEnablingAServerIsOnlyEverAnExplicitlyNamedRow() throws { + let (controller, host) = makeController(servers: [ + Self.server(name: "demo", proto: "stdio", enabled: false, + health: ("degraded", "Disabled", "enable")) + ]) + controller.rebuildMenu() + + XCTAssertFalse(topLevelTitles(host).contains { $0.hasPrefix("Needs Attention") }, + "a server the user switched off is not an alert") + let items = try Self.disabledServerSubmenu(host, named: "demo").items + let enable = try XCTUnwrap(items.first { $0.title == "Enable" }) + XCTAssertTrue(enable.target === controller) + } + + /// A row with nothing to run (quarantine, missing secret) stays a plain + /// clickable disclosure — no submenu for a menu of one navigation. + func testARowWithNoActionNavigatesDirectly() throws { + let (controller, host) = makeController(servers: [ + Self.server(name: "everything", proto: "http", enabled: true, quarantined: true, + health: ("degraded", "Quarantined for review", "approve")) + ]) + controller.rebuildMenu() + + let attention = try submenu(host, startingWith: "Needs Attention") + let row = try XCTUnwrap(attention.items.first) + XCTAssertNil(row.submenu) + XCTAssertNotNil(row.action) + XCTAssertEqual(row.representedObject as? String, "everything", + "navigation keys off the server NAME, which is what .showServerDetail matches") + } + + // MARK: - F15 · A Servers submenu that fits + + func testDisabledServersFoldIntoTheirOwnSubmenu() throws { + var servers = [ + Self.server(name: "alive-1", proto: "http", enabled: true), + Self.server(name: "alive-2", proto: "http", enabled: true), + ] + for i in 1...4 { + servers.append(Self.server(name: "off-\(i)", proto: "http", enabled: false)) + } + let (controller, host) = makeController(servers: servers) + controller.rebuildMenu() + + let menu = try submenu(host, startingWith: "Servers (") + let titles = menu.items.map(\.title).filter { !$0.isEmpty } + XCTAssertEqual(titles, ["Add Server...", "alive-1", "alive-2", "Disabled (4)"]) + let fold = try XCTUnwrap(menu.items.first { $0.title == "Disabled (4)" }?.submenu) + XCTAssertEqual(fold.items.map(\.title), ["off-1", "off-2", "off-3", "off-4"]) + } + + func testAFewDisabledServersStayInline() throws { + let (controller, host) = makeController(servers: [ + Self.server(name: "alive", proto: "http", enabled: true), + Self.server(name: "off", proto: "http", enabled: false), + ]) + controller.rebuildMenu() + + let titles = try submenu(host, startingWith: "Servers (").items.map(\.title).filter { !$0.isEmpty } + XCTAssertEqual(titles, ["Add Server...", "alive", "off"], + "one disabled server behind a fold costs a click and saves nothing") + } + + func testServersNeedingAttentionSortFirst() throws { + let (controller, host) = makeController(servers: [ + Self.server(name: "aaa-fine", proto: "http", enabled: true), + Self.server(name: "zzz-broken", proto: "http", enabled: true, + health: ("unhealthy", "failed to connect", "restart")), + ]) + controller.rebuildMenu() + + let titles = try submenu(host, startingWith: "Servers (").items.map(\.title).filter { !$0.isEmpty } + XCTAssertEqual(titles, ["Add Server...", "zzz-broken", "aaa-fine"], + "alphabetical order buried the servers that need something") + } + + // MARK: - F11 · Empty profiles + + func testAProfileWithNoConfiguredServersIsFlaggedInTheMenu() throws { + let (controller, host) = makeController( + servers: [Self.server(name: "everything", proto: "http", enabled: true)], + profiles: [ + Self.profile(name: "research", servers: ["github", "gitlab"], toolCount: 0), + Self.profile(name: "live", servers: ["everything"], toolCount: 12), + ]) + controller.rebuildMenu() + + let titles = try submenu(host, startingWith: "Profile:").items.map(\.title) + XCTAssertTrue(titles.contains("research — no servers"), "\(titles)") + XCTAssertTrue(titles.contains("live (1 server · 12 tools)"), "\(titles)") + } + + // MARK: - F9 · Names that say what happens + + func testTheOpenRowsSayWhereTheyOpen() { + let (controller, host) = makeController(servers: [Self.server(name: "github", proto: "http", enabled: true)]) + controller.rebuildMenu() + + let titles = topLevelTitles(host) + XCTAssertTrue(titles.contains("Open MCPProxy Window"), "\(titles)") + XCTAssertTrue(titles.contains("Open Web UI in Browser"), "\(titles)") + } + + /// The same AutoStartService setting is "Launch at Login" in Settings → App. + func testTheLoginItemHasOneName() { + let (controller, host) = makeController(servers: [Self.server(name: "github", proto: "http", enabled: true)]) + controller.rebuildMenu() + + let titles = topLevelTitles(host) + XCTAssertTrue(titles.contains("Launch at Login"), "\(titles)") + XCTAssertFalse(titles.contains("Run at Startup")) + } + + // MARK: - F5 / F16 · The unreachable views + + func testAgentTokensAndToolsAreReachableFromTheSidebar() { + let items = SidebarItem.allCases.map(\.rawValue) + XCTAssertTrue(items.contains("Agent Tokens"), + "TokensView was 444 lines of finished UI that nothing instantiated") + XCTAssertTrue(items.contains("Tools"), + "BM25 discovery is the headline feature and had no native home") + } + + func testEverySidebarItemHasAnIcon() { + for item in SidebarItem.allCases { + XCTAssertFalse(item.icon.isEmpty, "\(item.rawValue) has no symbol") + } + } + + // MARK: - Helpers + + /// Find a disabled server's submenu whether or not it landed behind the fold. + private static func disabledServerSubmenu(_ host: TestMenuHost, named name: String) throws -> NSMenu { + let parent = try XCTUnwrap( + (host.menu?.items ?? []).first { $0.title.hasPrefix("Servers (") }?.submenu) + if let direct = parent.items.first(where: { $0.title == name })?.submenu { + return direct + } + let fold = try XCTUnwrap( + parent.items.first { $0.title.hasPrefix("Disabled (") }?.submenu, + "\(name) is neither inline nor folded: \(parent.items.map(\.title))") + return try XCTUnwrap(fold.items.first { $0.title == name }?.submenu) + } + + /// Built through the canonical Codable path so fixtures survive future + /// field additions on `ServerStatus`. + private static func server(name: String, + proto: String = "http", + enabled: Bool = true, + quarantined: Bool = false, + health: (level: String, summary: String, action: String)? = nil) -> ServerStatus { + var healthJSON = "" + if let health { + healthJSON = """ + , "health": {"level": "\(health.level)", "admin_state": "enabled", + "summary": "\(health.summary)", "action": "\(health.action)"} + """ + } + let json = """ + { + "id": "\(name)", + "name": "\(name)", + "protocol": "\(proto)", + "enabled": \(enabled), + "connected": \(enabled && health == nil), + "quarantined": \(quarantined), + "tool_count": 4 + \(healthJSON) + } + """.data(using: .utf8)! + // swiftlint:disable:next force_try + return try! JSONDecoder().decode(ServerStatus.self, from: json) + } + + private static func profile(name: String, servers: [String], toolCount: Int) -> ProfileSummary { + let list = servers.map { "\"\($0)\"" }.joined(separator: ",") + let json = """ + {"name": "\(name)", "servers": [\(list)], "tool_count": \(toolCount)} + """.data(using: .utf8)! + // swiftlint:disable:next force_try + return try! JSONDecoder().decode(ProfileSummary.self, from: json) + } +} diff --git a/native/macos/MCPProxy/MCPProxyTests/TrayPresentationTests.swift b/native/macos/MCPProxy/MCPProxyTests/TrayPresentationTests.swift new file mode 100644 index 000000000..80959bdff --- /dev/null +++ b/native/macos/MCPProxy/MCPProxyTests/TrayPresentationTests.swift @@ -0,0 +1,165 @@ +// TrayPresentationTests.swift +// MCPProxyTests +// +// The decision half of the 2026-08 tray UX audit fixes: what the menu-bar icon +// says (F1/F2), how a transport is named (F12), how a profile that resolves to +// nothing is labelled (F11), how servers are filed in the submenu (F15), and +// what a failed action tells the user (F3). + +import XCTest +@testable import MCPProxy + +final class TrayPresentationTests: XCTestCase { + + // MARK: - F1 · The icon shows server health + + /// The finding itself: five servers needing attention left the menu bar + /// looking exactly like all-healthy. + func testServerDiagnosticsBadgeTheMenuBarIcon() { + XCTAssertEqual( + TrayStatusIcon.badge(isStopped: false, hasCoreError: false, worstDiagnosticSeverity: "error"), + .severity(.error)) + XCTAssertEqual( + TrayStatusIcon.badge(isStopped: false, hasCoreError: false, worstDiagnosticSeverity: "warn"), + .severity(.warn)) + } + + func testAHealthyProxyKeepsThePlainIcon() { + XCTAssertEqual( + TrayStatusIcon.badge(isStopped: false, hasCoreError: false, worstDiagnosticSeverity: nil), + .none) + XCTAssertEqual(TrayStatusIcon.glyph(for: .none), "") + } + + /// A stopped or erroring core makes every server verdict stale — it must + /// not be told twice, more quietly, by an amber dot. + func testCoreStateOutranksServerSeverity() { + XCTAssertEqual( + TrayStatusIcon.badge(isStopped: true, hasCoreError: false, worstDiagnosticSeverity: "error"), + .stopped) + XCTAssertEqual( + TrayStatusIcon.badge(isStopped: false, hasCoreError: true, worstDiagnosticSeverity: "warn"), + .coreError) + } + + func testEveryBadgeHasItsOwnGlyph() { + let glyphs = [TrayIconBadge.stopped, .coreError, .severity(.warn)].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") + } + + // MARK: - F2 · Spoken, not just drawn + + func testTheStatusItemSaysWhatIsWrongInWords() { + let label = TrayStatusIcon.accessibilityLabel( + for: .severity(.error), summary: "13/29 servers, 942 tools", attentionCount: 5) + XCTAssertTrue(label.hasPrefix("MCPProxy")) + XCTAssertTrue(label.contains("13/29 servers")) + XCTAssertTrue(label.contains("5 server errors"), "got: \(label)") + } + + func testOneFailingServerIsNotPluralised() { + let label = TrayStatusIcon.accessibilityLabel( + for: .severity(.warn), summary: "1/1 servers, 4 tools", attentionCount: 1) + XCTAssertTrue(label.contains("1 server warning"), "got: \(label)") + XCTAssertFalse(label.contains("warnings")) + } + + func testAStoppedCoreIsNamedNotJustGlyphed() { + let label = TrayStatusIcon.accessibilityLabel(for: .stopped, summary: "Stopped", attentionCount: 0) + XCTAssertTrue(label.contains("core stopped"), "got: \(label)") + } + + // MARK: - F12 · Transport names + + func testTheThreeHTTPSpellingsReadAsOneFamily() { + XCTAssertEqual(TrayProtocolDisplay.label(for: "streamable-http"), "HTTP (streamable)") + XCTAssertEqual(TrayProtocolDisplay.label(for: "sse"), "HTTP (SSE)") + XCTAssertEqual(TrayProtocolDisplay.label(for: "http"), "HTTP") + XCTAssertEqual(TrayProtocolDisplay.label(for: "stdio"), "stdio") + } + + /// An unknown transport must survive verbatim rather than be swallowed — + /// a blank protocol line is worse than an ugly one. + func testAnUnknownProtocolIsShownAsGiven() { + XCTAssertEqual(TrayProtocolDisplay.label(for: "websocket"), "websocket") + } + + // MARK: - F11 · Profiles that resolve to nothing + + func testAProfileWhoseServersAreNotConfiguredSaysSo() { + let label = TrayProfileDisplay.label( + name: "research", servers: ["github", "gitlab"], toolCount: 0, + knownServers: ["everything", "ElevenLabs"]) + XCTAssertEqual(label, "research — no servers") + } + + func testAWorkingProfileShowsServersAndTools() { + let label = TrayProfileDisplay.label( + name: "deploy", servers: ["github", "k8s"], toolCount: 27, + knownServers: ["github", "k8s", "jira"]) + XCTAssertEqual(label, "deploy (2 servers · 27 tools)") + } + + /// The count is the EFFECTIVE one: a profile listing three servers of which + /// one exists scopes agents to one server, and must say one. + func testOnlyConfiguredServersCount() { + let label = TrayProfileDisplay.label( + name: "solo", servers: ["github", "ghost", "phantom"], toolCount: 4, + knownServers: ["github"]) + XCTAssertEqual(label, "solo (1 server · 4 tools)") + } + + // MARK: - F15 · Filing the Servers submenu + + func testDisabledServersAreFiledAwayFromWorkingOnes() { + XCTAssertEqual(TrayServerGrouping.group(enabled: false, needsAttention: false), .disabled) + XCTAssertEqual(TrayServerGrouping.group(enabled: true, needsAttention: true), .needsAttention) + XCTAssertEqual(TrayServerGrouping.group(enabled: true, needsAttention: false), .active) + } + + /// A disabled server that also has a health action is still disabled: the + /// admin state is the user's own decision and outranks the symptom. + func testDisabledWinsOverAttention() { + XCTAssertEqual(TrayServerGrouping.group(enabled: false, needsAttention: true), .disabled) + } + + // MARK: - F3 · Failures that say something + + func testAFailedActionNamesTheServerAndTheVerb() { + let title = TrayServerActionFailure.title(action: .restart, server: "github") + XCTAssertEqual(title, "Couldn’t restart github") + } + + func testTheMessageCarriesTheErrorAndAWayForward() { + struct Boom: LocalizedError { var errorDescription: String? { "500 upstream refused" } } + let message = TrayServerActionFailure.message(action: .enable, server: "jira", error: Boom()) + XCTAssertTrue(message.contains("500 upstream refused")) + XCTAssertTrue(message.contains("jira")) + } + + /// An alert body that is empty (or just whitespace from a bare error) reads + /// as a bug in the tray rather than a failure of the action. + func testAnErrorWithNothingToSayStillProducesABody() { + struct Silent: LocalizedError { var errorDescription: String? { " " } } + let message = TrayServerActionFailure.message(action: .login, server: "cloudflare", error: Silent()) + XCTAssertTrue(message.contains("did not say why"), "got: \(message)") + } + + // MARK: - F4/F7 · One verb per operation + + func testHealthActionsMapToTheVerbsTheMenuShows() { + XCTAssertEqual(TrayServerAction.fromHealthAction("login"), .login) + XCTAssertEqual(TrayServerAction.fromHealthAction("restart"), .restart) + XCTAssertEqual(TrayServerAction.fromHealthAction("enable"), .enable) + } + + /// Quarantine approval is a human decision. If it ever became a dispatchable + /// action, a Needs Attention row would approve a quarantined server on a + /// click that reads as navigation — exactly the F4 failure mode. + func testQuarantineApprovalIsNeverDispatched() { + XCTAssertNil(TrayServerAction.fromHealthAction("approve")) + XCTAssertNil(TrayServerAction.fromHealthAction("set_secret")) + XCTAssertNil(TrayServerAction.fromHealthAction("")) + } +} diff --git a/scripts/check-settings-parity.py b/scripts/check-settings-parity.py index e988c46df..b918cbfdb 100755 --- a/scripts/check-settings-parity.py +++ b/scripts/check-settings-parity.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Web <-> native settings catalog parity canary. +"""Web <-> native settings catalog parity gate. The native macOS tray Settings form (native/macos/.../Settings/SettingsCatalog.swift) is a HAND-PORT of the Web UI catalog (frontend/src/views/settings/fields.ts). @@ -8,15 +8,24 @@ "2m" placeholder on macOS while the web form had the correct 30s / 5m (see MCP-1214). -This canary pins parity for *duration* fields (the demonstrated risk class): -for every duration field it compares `optional` and `placeholder` across the -two files and fails loudly on any mismatch -- or if a duration field is missing -its placeholder on either side. Run in CI as a required merge check. +Originally this canary pinned only *duration* fields. The 2026-08 macOS tray UX +audit (finding F6) found the bigger hole the narrow check could not see: three +non-deprecated Web UI settings -- security.deep_scan.enabled, instructions and +code_execution_max_parallel -- were simply ABSENT from the native catalogue, +while its header claimed to mirror fields.ts 1:1. The tray's Raw tab is +read-only, so those settings were not editable from the tray at all. -It is intentionally line-oriented and conservative: each duration field is -declared on a single line in both catalogs today. If that format changes, the -parser will stop finding attributes and FAIL, forcing this script to be updated -in lockstep rather than silently passing. +So the gate now checks, for every field: + + 1. KEY COVERAGE -- the two catalogues describe the same set of config keys + (minus the documented exclusions below). This is what stops the next + web-first field from drifting. + 2. ATTRIBUTE PARITY -- placeholder / optional / step / min / max agree + wherever both sides declare the field. + +It is intentionally line-oriented and conservative. If either catalogue's +format changes so that keys stop being parseable, the script FAILS rather than +silently passing, forcing it to be updated in lockstep. """ from __future__ import annotations import re @@ -27,22 +36,64 @@ TS = ROOT / "frontend/src/views/settings/fields.ts" SWIFT = ROOT / "native/macos/MCPProxy/MCPProxy/Settings/SettingsCatalog.swift" +# Keys that legitimately live on one side only. +# +# server_edition.* -- the server edition is not shipped in the personal tray, +# so the native app has no business editing it. +WEB_ONLY_PREFIXES = ("server_edition.",) +WEB_ONLY_KEYS: set[str] = set() +NATIVE_ONLY_KEYS: set[str] = set() + +# Minimum number of fields we expect to parse on each side. A parser that +# silently stops matching would otherwise report perfect parity over zero +# fields. +MIN_FIELDS = 40 + + +def _num(raw: str | None) -> float | None: + if raw is None: + return None + try: + return float(raw) + except ValueError: + sys.exit(f"[parity] unparseable numeric attribute: {raw!r}") + def parse_ts(text: str) -> dict[str, dict]: - """Extract {key: {optional, placeholder}} for `control: 'duration'` fields.""" + """Extract {key: attrs} for every field object in fields.ts. + + Fields are written either on one line or as a multi-line object literal; + both start with a `key:` line, so the scan is anchored there and reads + forward to the end of that object (tracked by brace depth).""" out: dict[str, dict] = {} - for line in text.splitlines(): - if "control: 'duration'" not in line and 'control: "duration"' not in line: - continue - m = re.search(r"key:\s*['\"]([^'\"]+)['\"]", line) - if not m: - sys.exit(f"[parity] TS duration field with no parseable key:\n {line.strip()}") + for m in re.finditer(r"\bkey:\s*['\"]([^'\"]+)['\"]", text): key = m.group(1) - ph = re.search(r"placeholder:\s*['\"]([^'\"]*)['\"]", line) - opt = re.search(r"optional:\s*(true|false)", line) + # The field is the object literal containing this key: walk back to the + # nearest `{` and forward until the braces balance. + open_idx = text.rfind("{", 0, m.start()) + if open_idx == -1: + sys.exit(f"[parity] TS field {key!r} is not inside an object literal") + depth = 0 + end = len(text) + for i in range(open_idx, len(text)): + if text[i] == "{": + depth += 1 + elif text[i] == "}": + depth -= 1 + if depth == 0: + end = i + 1 + break + blob = text[open_idx:end] + ph = re.search(r"placeholder:\s*['\"]([^'\"]*)['\"]", blob) + opt = re.search(r"optional:\s*(true|false)", blob) + control = re.search(r"control:\s*['\"]([^'\"]+)['\"]", blob) out[key] = { "placeholder": ph.group(1) if ph else None, "optional": (opt.group(1) == "true") if opt else False, + "control": control.group(1) if control else None, + "step": _num(m2.group(1)) if (m2 := re.search(r"\bstep:\s*([\d.]+)", blob)) else None, + "min": _num(m3.group(1)) if (m3 := re.search(r"\bmin:\s*(-?[\d.]+)", blob)) else None, + "max": _num(m4.group(1)) if (m4 := re.search(r"\bmax:\s*(-?[\d.]+)", blob)) else None, } return out @@ -95,21 +146,38 @@ def _swift_configfield_blocks(text: str) -> list[str]: return blocks +def _swift_placeholder(block: str) -> str | None: + """Swift placeholders may be written with \\u{...} escapes; decode them so + they compare equal to the TS literal.""" + m = re.search(r'placeholder:\s*"((?:[^"\\]|\\.)*)"', block) + if not m: + return None + raw = m.group(1) + return re.sub(r"\\u\{([0-9a-fA-F]+)\}", lambda h: chr(int(h.group(1), 16)), raw) + + def parse_swift(text: str) -> dict[str, dict]: - """Extract {key: {optional, placeholder}} for `control: .duration` fields.""" + """Extract {key: attrs} for every ConfigField in SettingsCatalog.swift.""" out: dict[str, dict] = {} for block in _swift_configfield_blocks(text): - if "control: .duration" not in block: - continue m = re.search(r'key:\s*"([^"]+)"', block) if not m: - sys.exit(f"[parity] Swift duration ConfigField with no parseable key:\n {block.strip()[:120]}") + # `ConfigField` also appears as a parameter TYPE (e.g. + # `validateConfigField(_ field: ConfigField, …)`); those blocks + # carry no `key:` and are not catalogue entries. + if re.search(r"^\s*_?\s*\w+\s*:\s*ConfigField", block): + continue + sys.exit(f"[parity] Swift ConfigField with no parseable key:\n {block.strip()[:120]}") key = m.group(1) - ph = re.search(r'placeholder:\s*"([^"]*)"', block) opt = re.search(r"optional:\s*(true|false)", block) + control = re.search(r"control:\s*\.(\w+)", block) out[key] = { - "placeholder": ph.group(1) if ph else None, + "placeholder": _swift_placeholder(block), "optional": (opt.group(1) == "true") if opt else False, + "control": control.group(1) if control else None, + "step": _num(m2.group(1)) if (m2 := re.search(r"\bstep:\s*([\d.]+)", block)) else None, + "min": _num(m3.group(1)) if (m3 := re.search(r"\bmin:\s*(-?[\d.]+)", block)) else None, + "max": _num(m4.group(1)) if (m4 := re.search(r"\bmax:\s*(-?[\d.]+)", block)) else None, } return out @@ -120,27 +188,39 @@ def main() -> int: errors: list[str] = [] - if not web or not native: - errors.append(f"parsed 0 duration fields (web={len(web)}, native={len(native)}) " - "-- catalog format may have changed; update this script") + if len(web) < MIN_FIELDS or len(native) < MIN_FIELDS: + errors.append( + f"parsed too few fields (web={len(web)}, native={len(native)}, expected >= {MIN_FIELDS}) " + "-- catalog format may have changed; update this script" + ) + + comparable_web = { + k for k in web + if not k.startswith(WEB_ONLY_PREFIXES) and k not in WEB_ONLY_KEYS + } + comparable_native = {k for k in native if k not in NATIVE_ONLY_KEYS} - only_web = sorted(set(web) - set(native)) - only_native = sorted(set(native) - set(web)) + only_web = sorted(comparable_web - comparable_native) + only_native = sorted(comparable_native - comparable_web) if only_web: - errors.append(f"duration field(s) only in web fields.ts: {only_web}") + errors.append( + "setting(s) in the Web UI but NOT editable in the macOS tray: " + f"{only_web} -- add them to SettingsCatalog.swift (the tray's Raw tab is read-only, " + "so a missing field is unreachable there, not merely inconvenient)" + ) if only_native: - errors.append(f"duration field(s) only in native SettingsCatalog.swift: {only_native}") + errors.append(f"setting(s) only in native SettingsCatalog.swift: {only_native}") - for key in sorted(set(web) & set(native)): + for key in sorted(comparable_web & comparable_native): w, n = web[key], native[key] - if w["placeholder"] is None: - errors.append(f"{key}: web has no placeholder (must show the real default, e.g. 30s)") - if n["placeholder"] is None: - errors.append(f"{key}: native has no placeholder (must show the real default, e.g. 30s)") - if w["placeholder"] != n["placeholder"]: - errors.append(f"{key}: placeholder mismatch web={w['placeholder']!r} native={n['placeholder']!r}") - if w["optional"] != n["optional"]: - errors.append(f"{key}: optional mismatch web={w['optional']} native={n['optional']}") + for attr in ("placeholder", "optional", "step", "min", "max"): + if w[attr] != n[attr]: + errors.append(f"{key}: {attr} mismatch web={w[attr]!r} native={n[attr]!r}") + if w["control"] == "duration": + if w["placeholder"] is None: + errors.append(f"{key}: web duration field has no placeholder (must show the real default, e.g. 30s)") + if n["placeholder"] is None: + errors.append(f"{key}: native duration field has no placeholder (must show the real default, e.g. 30s)") if errors: print("Settings parity check FAILED:", file=sys.stderr) @@ -148,9 +228,11 @@ def main() -> int: print(f" - {e}", file=sys.stderr) return 1 - print(f"Settings parity OK: {len(web)} duration field(s) consistent across web + native:") - for key in sorted(web): - print(f" - {key}: placeholder={web[key]['placeholder']!r} optional={web[key]['optional']}") + shared = comparable_web & comparable_native + print(f"Settings parity OK: {len(shared)} setting(s) consistent across web + native.") + excluded = sorted(set(web) - comparable_web) + if excluded: + print(f" (excluded by design: {excluded})") return 0 From 6c6ed7b6a1fc4f9fe5327c0f920651b0740a984a Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Tue, 25 Aug 2026 15:02:54 +0300 Subject: [PATCH 2/5] test(tray): pin the window- and settings-side audit fixes --- .../macos/MCPProxy/MCPProxy/MCPProxyApp.swift | 19 +-- .../MCPProxy/MCPProxy/ProjectLinks.swift | 22 ++++ .../TrayAuditSurfacesTests.swift | 124 ++++++++++++++++++ 3 files changed, 150 insertions(+), 15 deletions(-) create mode 100644 native/macos/MCPProxy/MCPProxyTests/TrayAuditSurfacesTests.swift diff --git a/native/macos/MCPProxy/MCPProxy/MCPProxyApp.swift b/native/macos/MCPProxy/MCPProxy/MCPProxyApp.swift index 940f8a38f..2d761d700 100644 --- a/native/macos/MCPProxy/MCPProxy/MCPProxyApp.swift +++ b/native/macos/MCPProxy/MCPProxy/MCPProxyApp.swift @@ -1906,21 +1906,10 @@ final class AppController: NSObject, NSApplicationDelegate, NSWindowDelegate, NS credits.append(NSAttributedString( string: "Smart MCP proxy — intelligent tool discovery, token savings, and security quarantine.\n\n", attributes: body)) - appendLink(to: credits, label: "Homepage", url: ProjectLinks.homepage) - credits.append(NSAttributedString(string: " ", attributes: body)) - appendLink(to: credits, label: "GitHub", url: ProjectLinks.github) - credits.append(NSAttributedString(string: " ", attributes: body)) - appendLink(to: credits, label: "Documentation", url: ProjectLinks.docs) - // F14: the tray — the surface a Homebrew user actually sees — had no - // way to report anything, while `ProjectLinks.issues`/`.discussions` - // sat declared and unused. They land here and in Settings → App - // rather than as new top-level rows: the menu was deliberately cut to - // stop it scrolling (#1023, pinned by MenuStructureTests), and this - // costs no row. - credits.append(NSAttributedString(string: " ", attributes: body)) - appendLink(to: credits, label: "Report an Issue", url: ProjectLinks.issues) - credits.append(NSAttributedString(string: " ", attributes: body)) - appendLink(to: credits, label: "Discussions", url: ProjectLinks.discussions) + for (index, link) in AboutPanelLinks.all.enumerated() { + if index > 0 { credits.append(NSAttributedString(string: " ", attributes: body)) } + appendLink(to: credits, label: link.label, url: link.url) + } NSApp.orderFrontStandardAboutPanel(options: [ .credits: credits diff --git a/native/macos/MCPProxy/MCPProxy/ProjectLinks.swift b/native/macos/MCPProxy/MCPProxy/ProjectLinks.swift index a3a721699..988b71979 100644 --- a/native/macos/MCPProxy/MCPProxy/ProjectLinks.swift +++ b/native/macos/MCPProxy/MCPProxy/ProjectLinks.swift @@ -13,3 +13,25 @@ enum ProjectLinks { static let issues = URL(string: "https://github.com/smart-mcp-proxy/mcpproxy-go/issues")! static let discussions = URL(string: "https://github.com/smart-mcp-proxy/mcpproxy-go/discussions")! } + +/// The credits block of the standard About panel. +/// +/// A value rather than inline construction so the one property that matters — +/// that a running app carries a way to REPORT something, not just to read the +/// docs — is testable. Before the 2026-08 UX audit (F14) `ProjectLinks.issues` +/// and `.discussions` were declared and never used anywhere in the app, while +/// the Web UI had /feedback and the CLI had `mcpproxy feedback`. +enum AboutPanelLinks { + struct Link: Equatable { + let label: String + let url: URL + } + + static let all: [Link] = [ + Link(label: "Homepage", url: ProjectLinks.homepage), + Link(label: "GitHub", url: ProjectLinks.github), + Link(label: "Documentation", url: ProjectLinks.docs), + Link(label: "Report an Issue", url: ProjectLinks.issues), + Link(label: "Discussions", url: ProjectLinks.discussions), + ] +} diff --git a/native/macos/MCPProxy/MCPProxyTests/TrayAuditSurfacesTests.swift b/native/macos/MCPProxy/MCPProxyTests/TrayAuditSurfacesTests.swift new file mode 100644 index 000000000..1f81a940a --- /dev/null +++ b/native/macos/MCPProxy/MCPProxyTests/TrayAuditSurfacesTests.swift @@ -0,0 +1,124 @@ +// TrayAuditSurfacesTests.swift +// MCPProxyTests +// +// The window- and settings-side fixes from the 2026-08 macOS tray UX audit. +// These surfaces cannot be walked by `mcpproxy-ui-test` (it reads the status +// bar menu, and window-level accessibility is unavailable while the screen is +// locked), so their contracts are pinned here instead: +// +// F5 Agent Tokens is reachable +// F6 the three Web-UI-only settings are in the native catalogue +// F13 placeholders and steps match the Web UI +// F14 the About panel carries a way to report something +// F16 the Tools view assembles server:tool from the bare REST name + +import XCTest +@testable import MCPProxy + +final class TrayAuditSurfacesTests: XCTestCase { + + private var allFields: [ConfigField] { + SettingsCatalog.security + + SettingsCatalog.general + + SettingsCatalog.advanced.flatMap(\.fields) + } + + private func field(_ key: String) throws -> ConfigField { + try XCTUnwrap(allFields.first { $0.key == key }, + "\(key) is not in SettingsCatalog — it is unreachable from the tray, " + + "whose Raw tab is read-only") + } + + // MARK: - F6 · The settings that were web-only + + func testDeepScanIsEditableFromTheTray() throws { + let deepScan = try field("security.deep_scan.enabled") + XCTAssertEqual(deepScan.control, .toggle) + XCTAssertNotNil(deepScan.docs, "the Docker-scanner opt-in needs its doc link") + } + + func testServerInstructionsAreEditableFromTheTray() throws { + let instructions = try field("instructions") + XCTAssertEqual(instructions.control, .textarea, "a paragraph is not a 240pt trailing field") + XCTAssertTrue(instructions.optional, "blank means: use the built-in default") + XCTAssertNotNil(instructions.placeholder) + } + + func testCodeExecutionParallelismIsEditableFromTheTray() throws { + let parallel = try field("code_execution_max_parallel") + XCTAssertEqual(parallel.control, .number) + XCTAssertEqual(parallel.min, 1) + XCTAssertEqual(parallel.max, 32) + } + + /// The catalogue's own header claims it mirrors fields.ts 1:1 — this is the + /// in-suite half of that claim (scripts/check-settings-parity.py is the + /// cross-file gate). + func testNoFieldIsDeclaredTwice() { + let keys = allFields.map(\.key) + XCTAssertEqual(Set(keys).count, keys.count, + "duplicate key(s): \(keys.filter { k in keys.filter { $0 == k }.count > 1 })") + } + + // MARK: - F13 · Copy and control drift + + func testDockerFieldsCarryTheirExampleValues() throws { + XCTAssertEqual(try field("docker_isolation.memory_limit").placeholder, "512m") + XCTAssertEqual(try field("docker_isolation.cpu_limit").placeholder, "1.0") + XCTAssertEqual(try field("docker_isolation.registry").placeholder, "docker.io") + } + + /// Both are fractional in practice (entropy 4.5, "warn 1.5h before"), and + /// without a step they could only be typed, never nudged. + func testFractionalNumbersHaveAStep() throws { + XCTAssertEqual(try field("sensitive_data_detection.entropy_threshold").step, 0.1) + XCTAssertEqual(try field("oauth_expiry_warning_hours").step, 0.5) + } + + func testTelemetryCopyMatchesTheWebUIRevision() throws { + let telemetry = try field("telemetry.enabled") + XCTAssertTrue(telemetry.help?.contains("single anonymous opt-out signal") == true, + "the tray's wording was a revision behind: \(telemetry.help ?? "nil")") + XCTAssertTrue(telemetry.dangerMessage?.contains("opt-out signal") == true) + } + + // MARK: - F14 · A way to report something + + func testTheAboutPanelOffersTheIssueTracker() { + let labels = AboutPanelLinks.all.map(\.label) + XCTAssertTrue(labels.contains("Report an Issue"), "\(labels)") + XCTAssertTrue(labels.contains("Discussions")) + XCTAssertEqual(AboutPanelLinks.all.first { $0.label == "Report an Issue" }?.url, + ProjectLinks.issues) + } + + func testEveryAboutLinkIsDistinct() { + let urls = AboutPanelLinks.all.map(\.url) + XCTAssertEqual(Set(urls).count, urls.count) + } + + // MARK: - F16 · Tool identity in the Tools view + + /// REST `/index/search` returns the BARE name plus `server_name` (#871). + /// The view must assemble the canonical id rather than trust `name`. + func testToolRowAssemblesTheCanonicalIdentity() { + let row = ToolsView.ToolRow(server: "github", name: "create_issue", + description: "Open an issue", score: 4.2) + XCTAssertEqual(row.qualified, "github:create_issue") + XCTAssertEqual(row.id, "github:create_issue") + } + + func testAToolWithNoServerStillHasAUsableIdentity() { + let row = ToolsView.ToolRow(server: "", name: "retrieve_tools", + description: "", score: nil) + XCTAssertEqual(row.qualified, "retrieve_tools", + "a leading colon is not an identity") + } + + // MARK: - F10 · The glance hand-off has its own channel + + func testTheActivityFilterNotificationIsItsOwnChannel() { + XCTAssertNotEqual(Notification.Name.activityFilter, .switchToActivity) + XCTAssertNotEqual(Notification.Name.activityFilter, .switchToSidebarTab) + } +} From 7a9ce4edee140e8387742b50ce5e96079261a217 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Tue, 25 Aug 2026 15:16:57 +0300 Subject: [PATCH 3/5] fix(tray): tighten query encoding, export filters and the parity gate Cross-model review round 1: escape query values (urlQueryAllowed lets &/=/+ through), carry the sub-call and session filters into the activity export, count only the badged severity in the status-item label, treat a newline-only optional field as unset, and widen the settings parity gate to control/restart/options with comment stripping and duplicate detection. --- .../MCPProxy/MCPProxy/API/APIClient.swift | 14 ++- .../macos/MCPProxy/MCPProxy/MCPProxyApp.swift | 10 ++- .../MCPProxy/Settings/SettingsCatalog.swift | 6 +- .../MCPProxy/MCPProxy/State/AppState.swift | 12 +++ .../MCPProxy/Views/ActivityView.swift | 36 +++++--- .../TrayAuditSurfacesTests.swift | 13 +++ .../MCPProxyTests/TrayPresentationTests.swift | 34 +++++++ scripts/check-settings-parity.py | 89 ++++++++++++++++++- 8 files changed, 194 insertions(+), 20 deletions(-) diff --git a/native/macos/MCPProxy/MCPProxy/API/APIClient.swift b/native/macos/MCPProxy/MCPProxy/API/APIClient.swift index 0bb9e994a..6eb3d5318 100644 --- a/native/macos/MCPProxy/MCPProxy/API/APIClient.swift +++ b/native/macos/MCPProxy/MCPProxy/API/APIClient.swift @@ -772,6 +772,18 @@ actor APIClient { // MARK: - Tool Search + /// Percent-encode one query-string VALUE. + /// + /// `.urlQueryAllowed` is the wrong set for a value: it deliberately leaves + /// `&`, `=`, `+` and `?` intact, so a tool search for "a&limit=1" would + /// silently become two parameters, and a `+` in a session id would decode + /// as a space. Only unreserved characters survive here. + static func escapeQueryValue(_ value: String) -> String { + let unreserved = CharacterSet( + charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~") + return value.addingPercentEncoding(withAllowedCharacters: unreserved) ?? "" + } + /// BM25 search across every upstream tool via `GET /api/v1/index/search`. /// /// This used to call `GET /api/v1/tools?q=…`, which has no `q` parameter: @@ -782,7 +794,7 @@ actor APIClient { /// Note the REST contract (#871): `tool.name` here is the BARE tool name /// with `server_name` alongside — callers assemble `server:tool` themselves. func searchTools(query: String, limit: Int = 50) async throws -> [SearchResult] { - let encoded = query.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? query + let encoded = Self.escapeQueryValue(query) let data = try await fetchRaw(path: "/api/v1/index/search?q=\(encoded)&limit=\(limit)") let decoder = JSONDecoder() if let wrapper = try? decoder.decode(APIResponse.self, from: data), diff --git a/native/macos/MCPProxy/MCPProxy/MCPProxyApp.swift b/native/macos/MCPProxy/MCPProxy/MCPProxyApp.swift index 2d761d700..05f2a364f 100644 --- a/native/macos/MCPProxy/MCPProxy/MCPProxyApp.swift +++ b/native/macos/MCPProxy/MCPProxy/MCPProxyApp.swift @@ -930,10 +930,18 @@ final class AppController: NSObject, NSApplicationDelegate, NSWindowDelegate, NS hasCoreError: hasError, worstDiagnosticSeverity: appState.worstDiagnosticSeverity ) + // The count must be of the severity being badged, over the same + // (enabled, non-OAuth) set `worstDiagnosticSeverity` considers. + let badgedCount: Int + if case .severity(let severity) = badge { + badgedCount = appState.diagnosticCount(severity: severity.rawValue) + } else { + badgedCount = 0 + } let label = TrayStatusIcon.accessibilityLabel( for: badge, summary: appState.statusSummary, - attentionCount: appState.serversWithDiagnostic.count + attentionCount: badgedCount ) // Always use template icon (pure black, adapts to light/dark menu bar) diff --git a/native/macos/MCPProxy/MCPProxy/Settings/SettingsCatalog.swift b/native/macos/MCPProxy/MCPProxy/Settings/SettingsCatalog.swift index 094c506bd..bb1c72f20 100644 --- a/native/macos/MCPProxy/MCPProxy/Settings/SettingsCatalog.swift +++ b/native/macos/MCPProxy/MCPProxy/Settings/SettingsCatalog.swift @@ -388,8 +388,12 @@ func configSet(_ obj: inout [String: Any], _ path: String, _ value: Any?) { /// stored verbatim. This keeps a blank optional field from being sent as "" /// (which the backend can't parse as a duration) and from reading as dirty /// against an absent key. +/// Whitespace here means newlines too: the textarea (`instructions`) shares +/// this binding, and a box holding nothing but a stray newline must read as +/// "unset" — otherwise the user thinks they cleared it back to the default and +/// silently saved a blank line as their custom instructions. func optionalScalarStored(_ s: String) -> Any? { - s.trimmingCharacters(in: .whitespaces).isEmpty ? nil : s + s.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? nil : s } /// Assembles a nested object containing ONLY the given dot-path keys, read from diff --git a/native/macos/MCPProxy/MCPProxy/State/AppState.swift b/native/macos/MCPProxy/MCPProxy/State/AppState.swift index 0ef374939..ee2646882 100644 --- a/native/macos/MCPProxy/MCPProxy/State/AppState.swift +++ b/native/macos/MCPProxy/MCPProxy/State/AppState.swift @@ -307,6 +307,18 @@ final class AppState: ObservableObject { servers.filter { $0.hasAttentionDiagnostic && !$0.isOAuthLoginRequired } } + /// 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. + func diagnosticCount(severity: String) -> Int { + servers.filter { + $0.enabled && !$0.isOAuthLoginRequired && $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. /// diff --git a/native/macos/MCPProxy/MCPProxy/Views/ActivityView.swift b/native/macos/MCPProxy/MCPProxy/Views/ActivityView.swift index 7a78acc2b..b3819af45 100644 --- a/native/macos/MCPProxy/MCPProxy/Views/ActivityView.swift +++ b/native/macos/MCPProxy/MCPProxy/Views/ActivityView.swift @@ -92,18 +92,28 @@ struct ActivityView: View { /// Build query string from current filter state. private var filterQueryString: String { - var parts: [String] = ["limit=100"] - if filterType != "all" { parts.append("type=\(filterType)") } - if filterServer != "all" { parts.append("server=\(filterServer)") } - if filterStatus != "all" { parts.append("status=\(filterStatus)") } + (["limit=100"] + activeFilterParams).joined(separator: "&") + } + + /// The filters currently in force, as encoded `key=value` pairs. + /// + /// Shared with the export so a filtered view and its export can never + /// disagree — "Export with current filters" used to drop the sub-call and + /// session scopes and hand back the whole log. Values are escaped: a + /// server name with a space or `&` is otherwise a broken (or extra) query + /// parameter. + private var activeFilterParams: [String] { + var parts: [String] = [] + if filterType != "all" { parts.append("type=\(APIClient.escapeQueryValue(filterType))") } + if filterServer != "all" { parts.append("server=\(APIClient.escapeQueryValue(filterServer))") } + if filterStatus != "all" { parts.append("status=\(APIClient.escapeQueryValue(filterStatus))") } if let parentId = filterParentId, !parentId.isEmpty { - parts.append("parent_id=\(parentId)") + parts.append("parent_id=\(APIClient.escapeQueryValue(parentId))") } - if let sessionId = filterSessionId, !sessionId.isEmpty, - let encoded = sessionId.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) { - parts.append("session_id=\(encoded)") + if let sessionId = filterSessionId, !sessionId.isEmpty { + parts.append("session_id=\(APIClient.escapeQueryValue(sessionId))") } - return parts.joined(separator: "&") + return parts } /// Scope the list to one MCP session (a tray glance row's hand-off). @@ -569,11 +579,9 @@ struct ActivityView: View { defer { isExporting = false } guard let client = apiClient else { return } do { - // Build export query with current filters - var exportQuery = "format=\(format)" - if filterType != "all" { exportQuery += "&type=\(filterType)" } - if filterServer != "all" { exportQuery += "&server=\(filterServer)" } - if filterStatus != "all" { exportQuery += "&status=\(filterStatus)" } + // Build export query with current filters — every one of + // them, from the same source the list uses. + let exportQuery = (["format=\(format)"] + activeFilterParams).joined(separator: "&") let data = try await client.fetchRaw(path: "/api/v1/activity/export?\(exportQuery)") try data.write(to: url) NSWorkspace.shared.activateFileViewerSelecting([url]) diff --git a/native/macos/MCPProxy/MCPProxyTests/TrayAuditSurfacesTests.swift b/native/macos/MCPProxy/MCPProxyTests/TrayAuditSurfacesTests.swift index 1f81a940a..e22e0615e 100644 --- a/native/macos/MCPProxy/MCPProxyTests/TrayAuditSurfacesTests.swift +++ b/native/macos/MCPProxy/MCPProxyTests/TrayAuditSurfacesTests.swift @@ -115,6 +115,19 @@ final class TrayAuditSurfacesTests: XCTestCase { "a leading colon is not an identity") } + // MARK: - Query encoding (cross-model review, round 1) + + /// `.urlQueryAllowed` — the obvious choice, and the one this code used — + /// deliberately permits `&`, `=`, `+` and `?`, so a search for + /// "a&limit=1" would have become a second parameter. + func testQueryValuesEscapeParameterDelimiters() { + XCTAssertEqual(APIClient.escapeQueryValue("a&limit=1"), "a%26limit%3D1") + XCTAssertEqual(APIClient.escapeQueryValue("git hub"), "git%20hub") + XCTAssertEqual(APIClient.escapeQueryValue("a+b"), "a%2Bb", "a raw + decodes as a space") + XCTAssertEqual(APIClient.escapeQueryValue("sess-1_a.b~c"), "sess-1_a.b~c", + "unreserved characters must survive untouched") + } + // MARK: - F10 · The glance hand-off has its own channel func testTheActivityFilterNotificationIsItsOwnChannel() { diff --git a/native/macos/MCPProxy/MCPProxyTests/TrayPresentationTests.swift b/native/macos/MCPProxy/MCPProxyTests/TrayPresentationTests.swift index 80959bdff..342aac745 100644 --- a/native/macos/MCPProxy/MCPProxyTests/TrayPresentationTests.swift +++ b/native/macos/MCPProxy/MCPProxyTests/TrayPresentationTests.swift @@ -65,6 +65,40 @@ final class TrayPresentationTests: XCTestCase { XCTAssertFalse(label.contains("warnings")) } + /// The spoken count must be of the severity being badged, over the same + /// enabled, non-OAuth set `worstDiagnosticSeverity` uses — otherwise the + /// status item says "4 server errors" over a badge that counted three + /// (cross-model review, round 1). + @MainActor + func testTheSpokenCountMatchesTheBadgedSeverity() { + let state = AppState() + state.servers = [ + Self.diagnosingServer(name: "a", enabled: true, severity: "error"), + Self.diagnosingServer(name: "b", enabled: true, severity: "error"), + Self.diagnosingServer(name: "c", enabled: true, severity: "warn"), + Self.diagnosingServer(name: "d", enabled: false, severity: "error"), + ] + XCTAssertEqual(state.worstDiagnosticSeverity, "error") + XCTAssertEqual(state.diagnosticCount(severity: "error"), 2, + "the disabled server is not part of the badge") + XCTAssertEqual(state.diagnosticCount(severity: "warn"), 1) + XCTAssertEqual(state.serversWithDiagnostic.count, 4, + "the old input counted every diagnostic, enabled or not") + } + + private static func diagnosingServer(name: String, enabled: Bool, severity: String) -> ServerStatus { + let json = """ + { + "id": "\(name)", "name": "\(name)", "protocol": "http", + "enabled": \(enabled), "connected": false, "quarantined": false, "tool_count": 0, + "error_code": "MCPX_TEST", + "diagnostic": {"code": "MCPX_TEST", "severity": "\(severity)", "summary": "boom"} + } + """.data(using: .utf8)! + // swiftlint:disable:next force_try + return try! JSONDecoder().decode(ServerStatus.self, from: json) + } + func testAStoppedCoreIsNamedNotJustGlyphed() { let label = TrayStatusIcon.accessibilityLabel(for: .stopped, summary: "Stopped", attentionCount: 0) XCTAssertTrue(label.contains("core stopped"), "got: \(label)") diff --git a/scripts/check-settings-parity.py b/scripts/check-settings-parity.py index b918cbfdb..af0fa779d 100755 --- a/scripts/check-settings-parity.py +++ b/scripts/check-settings-parity.py @@ -20,8 +20,15 @@ 1. KEY COVERAGE -- the two catalogues describe the same set of config keys (minus the documented exclusions below). This is what stops the next web-first field from drifting. - 2. ATTRIBUTE PARITY -- placeholder / optional / step / min / max agree - wherever both sides declare the field. + 2. ATTRIBUTE PARITY -- control / placeholder / optional / step / min / max / + restart / select options agree wherever both sides declare the field. A + control that drifts (number -> toggle) or a select option that disappears + changes what the tray can SET while leaving key coverage intact. + +Both parsers strip comments first: a commented-out ConfigField would otherwise +be counted as editable, which is precisely the drift this gate exists to catch. +A key declared twice on either side is a hard failure -- one definition would +silently win. It is intentionally line-oriented and conservative. If either catalogue's format changes so that keys stop being parseable, the script FAILS rather than @@ -50,6 +57,72 @@ MIN_FIELDS = 40 +def strip_comments(text: str, block_comments: bool) -> str: + """Blank out `//` (and optionally `/* */`) comments, string-aware. + + Without this the parsers happily read a COMMENTED-OUT field and report it + as editable — a false negative in a gate whose whole job is to notice a + field going missing. Characters are replaced with spaces rather than + deleted so no line/offset shifts.""" + out = list(text) + i, n = 0, len(text) + quote: str | None = None + while i < n: + c = text[i] + if quote: + if c == "\\": + i += 2 + continue + if c == quote: + quote = None + i += 1 + continue + if c in "\"'`": + quote = c + i += 1 + continue + if c == "/" and i + 1 < n and text[i + 1] == "/": + while i < n and text[i] != "\n": + out[i] = " " + i += 1 + continue + if block_comments and c == "/" and i + 1 < n and text[i + 1] == "*": + while i < n and not (text[i] == "*" and i + 1 < n and text[i + 1] == "/"): + if text[i] != "\n": + out[i] = " " + i += 1 + for _ in range(2): + if i < n: + out[i] = " " + i += 1 + continue + i += 1 + return "".join(out) + + +def _ts_options(blob: str) -> list[str] | None: + """The selectable VALUES of a select/multiselect, in order. Dropping one + silently narrows what the tray can set, which no key-coverage check sees.""" + m = re.search(r"options:\s*\[(.*?)\]", blob, re.S) + if not m: + return None + return re.findall(r"value:\s*['\"]([^'\"]+)['\"]", m.group(1)) or \ + re.findall(r"['\"]([^'\"]+)['\"]", m.group(1)) + + +def _swift_options(block: str) -> list[str] | None: + """Swift writes options either as explicit ConfigOption(value:label:) pairs + or as `["a","b"].map { ConfigOption(value: $0, label: $0) }`.""" + m = re.search(r"options:\s*\[(.*?)\]", block, re.S) + if not m: + return None + inner = m.group(1) + explicit = re.findall(r'value:\s*"([^"]+)"', inner) + if explicit: + return explicit + return re.findall(r'"([^"]+)"', inner) + + def _num(raw: str | None) -> float | None: if raw is None: return None @@ -66,8 +139,11 @@ def parse_ts(text: str) -> dict[str, dict]: both start with a `key:` line, so the scan is anchored there and reads forward to the end of that object (tracked by brace depth).""" out: dict[str, dict] = {} + text = strip_comments(text, block_comments=True) for m in re.finditer(r"\bkey:\s*['\"]([^'\"]+)['\"]", text): key = m.group(1) + if key in out: + sys.exit(f"[parity] TS declares {key!r} twice — one definition silently wins") # The field is the object literal containing this key: walk back to the # nearest `{` and forward until the braces balance. open_idx = text.rfind("{", 0, m.start()) @@ -94,6 +170,8 @@ def parse_ts(text: str) -> dict[str, dict]: "step": _num(m2.group(1)) if (m2 := re.search(r"\bstep:\s*([\d.]+)", blob)) else None, "min": _num(m3.group(1)) if (m3 := re.search(r"\bmin:\s*(-?[\d.]+)", blob)) else None, "max": _num(m4.group(1)) if (m4 := re.search(r"\bmax:\s*(-?[\d.]+)", blob)) else None, + "restart": bool(re.search(r"\brestart:\s*true", blob)), + "options": _ts_options(blob), } return out @@ -159,6 +237,7 @@ def _swift_placeholder(block: str) -> str | None: def parse_swift(text: str) -> dict[str, dict]: """Extract {key: attrs} for every ConfigField in SettingsCatalog.swift.""" out: dict[str, dict] = {} + text = strip_comments(text, block_comments=True) for block in _swift_configfield_blocks(text): m = re.search(r'key:\s*"([^"]+)"', block) if not m: @@ -169,6 +248,8 @@ def parse_swift(text: str) -> dict[str, dict]: continue sys.exit(f"[parity] Swift ConfigField with no parseable key:\n {block.strip()[:120]}") key = m.group(1) + if key in out: + sys.exit(f"[parity] SettingsCatalog declares {key!r} twice — one definition silently wins") opt = re.search(r"optional:\s*(true|false)", block) control = re.search(r"control:\s*\.(\w+)", block) out[key] = { @@ -178,6 +259,8 @@ def parse_swift(text: str) -> dict[str, dict]: "step": _num(m2.group(1)) if (m2 := re.search(r"\bstep:\s*([\d.]+)", block)) else None, "min": _num(m3.group(1)) if (m3 := re.search(r"\bmin:\s*(-?[\d.]+)", block)) else None, "max": _num(m4.group(1)) if (m4 := re.search(r"\bmax:\s*(-?[\d.]+)", block)) else None, + "restart": bool(re.search(r"\brestart:\s*true", block)), + "options": _swift_options(block), } return out @@ -213,7 +296,7 @@ def main() -> int: for key in sorted(comparable_web & comparable_native): w, n = web[key], native[key] - for attr in ("placeholder", "optional", "step", "min", "max"): + for attr in ("control", "placeholder", "optional", "step", "min", "max", "restart", "options"): if w[attr] != n[attr]: errors.append(f"{key}: {attr} mismatch web={w[attr]!r} native={n[attr]!r}") if w["control"] == "duration": From 9ef7ece3aa4c29d901703cbfe51973b8eff83117 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Tue, 25 Aug 2026 15:22:20 +0300 Subject: [PATCH 4/5] fix(tray): percent-encode server names in API paths Cross-model review round 2: server names are only validated against ':', so 'my/server' would split the /servers/{id}/... path the menu's enable, disable, restart and sign-in actions all post to. --- .../MCPProxy/MCPProxy/API/APIClient.swift | 21 +++++++++++++++---- .../TrayAuditSurfacesTests.swift | 10 +++++++++ 2 files changed, 27 insertions(+), 4 deletions(-) diff --git a/native/macos/MCPProxy/MCPProxy/API/APIClient.swift b/native/macos/MCPProxy/MCPProxy/API/APIClient.swift index 6eb3d5318..09bd31eb8 100644 --- a/native/macos/MCPProxy/MCPProxy/API/APIClient.swift +++ b/native/macos/MCPProxy/MCPProxy/API/APIClient.swift @@ -190,24 +190,37 @@ actor APIClient { return response.servers } + /// Percent-encode one PATH segment. + /// + /// Server names are only validated against `:` (see + /// `internal/config/server_name_validation_test.go`), so `my/server` or + /// `my server` are legal names that would otherwise split the path into + /// extra segments and 404 — or, worse, address a different route. Every + /// `/servers/{id}/…` action the tray menu can fire goes through this. + static func escapePathComponent(_ value: String) -> String { + let unreserved = CharacterSet( + charactersIn: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~") + return value.addingPercentEncoding(withAllowedCharacters: unreserved) ?? "" + } + /// Enable a server via `POST /api/v1/servers/{id}/enable`. func enableServer(_ id: String) async throws { - try await postAction(path: "/api/v1/servers/\(id)/enable") + try await postAction(path: "/api/v1/servers/\(Self.escapePathComponent(id))/enable") } /// Disable a server via `POST /api/v1/servers/{id}/disable`. func disableServer(_ id: String) async throws { - try await postAction(path: "/api/v1/servers/\(id)/disable") + try await postAction(path: "/api/v1/servers/\(Self.escapePathComponent(id))/disable") } /// Restart a server via `POST /api/v1/servers/{id}/restart`. func restartServer(_ id: String) async throws { - try await postAction(path: "/api/v1/servers/\(id)/restart") + try await postAction(path: "/api/v1/servers/\(Self.escapePathComponent(id))/restart") } /// Trigger OAuth login for a server via `POST /api/v1/servers/{id}/login`. func loginServer(_ id: String) async throws { - try await postAction(path: "/api/v1/servers/\(id)/login") + try await postAction(path: "/api/v1/servers/\(Self.escapePathComponent(id))/login") } // MARK: - Profiles (Profiles v2 T5) diff --git a/native/macos/MCPProxy/MCPProxyTests/TrayAuditSurfacesTests.swift b/native/macos/MCPProxy/MCPProxyTests/TrayAuditSurfacesTests.swift index e22e0615e..051334ff2 100644 --- a/native/macos/MCPProxy/MCPProxyTests/TrayAuditSurfacesTests.swift +++ b/native/macos/MCPProxy/MCPProxyTests/TrayAuditSurfacesTests.swift @@ -128,6 +128,16 @@ final class TrayAuditSurfacesTests: XCTestCase { "unreserved characters must survive untouched") } + /// Server names are validated only against `:`, so `my/server` is a legal + /// name that would split a `/servers/{id}/restart` path into extra + /// segments — every menu action goes through those routes (cross-model + /// review, round 2). + func testServerNamesAreSafeAsPathSegments() { + XCTAssertEqual(APIClient.escapePathComponent("my/server"), "my%2Fserver") + XCTAssertEqual(APIClient.escapePathComponent("my server"), "my%20server") + XCTAssertEqual(APIClient.escapePathComponent("github"), "github") + } + // MARK: - F10 · The glance hand-off has its own channel func testTheActivityFilterNotificationIsItsOwnChannel() { From c173342b955f40fcb13a698c90042f38656053a3 Mon Sep 17 00:00:00 2001 From: Algis Dumbris Date: Tue, 25 Aug 2026 15:31:47 +0300 Subject: [PATCH 5/5] fix(tray): hand the glance session filter over without a timing race Cross-model review round 3: publish the pending session on AppState so a window created by the click picks it up on appear (a delayed notification lands before ActivityView subscribes), and make the parity gate refuse a non-string-literal field key instead of silently skipping it. --- native/macos/MCPProxy/MCPProxy/MCPProxyApp.swift | 14 +++++++++----- .../macos/MCPProxy/MCPProxy/State/AppState.swift | 11 +++++++++++ .../MCPProxy/MCPProxy/Views/ActivityView.swift | 10 ++++++++++ scripts/check-settings-parity.py | 12 ++++++++++++ 4 files changed, 42 insertions(+), 5 deletions(-) diff --git a/native/macos/MCPProxy/MCPProxy/MCPProxyApp.swift b/native/macos/MCPProxy/MCPProxy/MCPProxyApp.swift index 05f2a364f..68dd59f19 100644 --- a/native/macos/MCPProxy/MCPProxy/MCPProxyApp.swift +++ b/native/macos/MCPProxy/MCPProxy/MCPProxyApp.swift @@ -1875,13 +1875,17 @@ final class AppController: NSObject, NSApplicationDelegate, NSWindowDelegate, NS /// filter, which is what makes a glance row parent↔child navigable. @objc private func openActivityForSession(_ sender: NSMenuItem) { let sessionId = sender.representedObject as? String + // Published BEFORE the window is built, so a view created by this very + // click picks the filter up on appear. A delayed notification would be + // a race: too early and nothing is subscribed, too late and the user + // has already read an unfiltered log. + if let sessionId, !sessionId.isEmpty { + appState.pendingActivitySessionFilter = sessionId + } showMainWindow(tab: Self.glanceActivityDestination) guard let sessionId, !sessionId.isEmpty else { return } - // After the tab switch: a window created for this click seeds its own - // selection at init, and the filter must land on the view that exists. - DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { - NotificationCenter.default.post(name: .activityFilter, object: sessionId) - } + // Covers the already-open window, whose observers are live now. + NotificationCenter.default.post(name: .activityFilter, object: sessionId) } /// Where a glance row click lands. A constant so tests can pin the diff --git a/native/macos/MCPProxy/MCPProxy/State/AppState.swift b/native/macos/MCPProxy/MCPProxy/State/AppState.swift index ee2646882..9ad9e6491 100644 --- a/native/macos/MCPProxy/MCPProxy/State/AppState.swift +++ b/native/macos/MCPProxy/MCPProxy/State/AppState.swift @@ -78,6 +78,17 @@ final class AppState: ObservableObject { // MARK: - Profiles (Profiles v2 T5) /// Configured profiles for the tray profile switcher. @Published var profiles: [ProfileSummary] = [] + + /// A session the Activity Log should scope itself to as soon as it exists + /// (F10 — a tray glance row's hand-off). + /// + /// A notification alone cannot carry this: a window created BY the click + /// subscribes its `onReceive` observers only once the view appears, so a + /// post made now lands on the floor — the same trap `showMainWindow(tab:)` + /// documents for the sidebar tab. ActivityView consumes and clears this on + /// appear; the notification still covers the already-open window, and + /// whichever arrives first clears it for the other. + @Published var pendingActivitySessionFilter: String? /// Server-level default active profile slug; empty means "all servers". @Published var activeProfile: String = "" diff --git a/native/macos/MCPProxy/MCPProxy/Views/ActivityView.swift b/native/macos/MCPProxy/MCPProxy/Views/ActivityView.swift index b3819af45..d9cc08cf5 100644 --- a/native/macos/MCPProxy/MCPProxy/Views/ActivityView.swift +++ b/native/macos/MCPProxy/MCPProxy/Views/ActivityView.swift @@ -243,6 +243,13 @@ struct ActivityView: View { } } .task { + // A glance row that opened this window left its session here (F10); + // consume it before the first load so the list is never briefly + // unfiltered. + if let pending = appState.pendingActivitySessionFilter, !pending.isEmpty { + appState.pendingActivitySessionFilter = nil + filterSessionId = pending + } await loadSummary() await loadActivities() } @@ -256,6 +263,9 @@ struct ActivityView: View { // F10: a tray glance row hands over the session it was derived from. .onReceive(NotificationCenter.default.publisher(for: .activityFilter)) { note in guard let sessionId = note.object as? String, !sessionId.isEmpty else { return } + // This view is live, so the hand-off is settled here — clear the + // pending value so a later-appearing view does not re-apply it. + appState.pendingActivitySessionFilter = nil showSession(sessionId) } } diff --git a/scripts/check-settings-parity.py b/scripts/check-settings-parity.py index af0fa779d..13cda776f 100755 --- a/scripts/check-settings-parity.py +++ b/scripts/check-settings-parity.py @@ -140,6 +140,18 @@ def parse_ts(text: str) -> dict[str, dict]: forward to the end of that object (tracked by brace depth).""" out: dict[str, dict] = {} text = strip_comments(text, block_comments=True) + # A `key:` whose value is not a string literal (a constant, a template + # literal, a computed name) is invisible to the scan below — the field + # would go missing from BOTH sides of the comparison and the gate would + # pass while the tray could not edit it. Refuse rather than skip. + for stray in re.finditer(r"\bkey:\s*(?!['\"])(\S+)", text): + token = stray.group(1) + # `key: string` in the SettingsField interface is a TYPE position, not a + # field declaration. + if re.fullmatch(r"(string|number|boolean|any|unknown)[;,)]?", token): + continue + sys.exit(f"[parity] TS field key is not a string literal: key: {token} " + "-- this parser cannot see it; either inline the literal or teach this script") for m in re.finditer(r"\bkey:\s*['\"]([^'\"]+)['\"]", text): key = m.group(1) if key in out: