From 83f40be8c94d024213e6ccb28a3b42faa13c81d2 Mon Sep 17 00:00:00 2001 From: StuBehan Date: Wed, 25 Nov 2026 07:49:31 +0000 Subject: [PATCH] feat(settings): an MCP category, with setup for each client, and the version in the footer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit MCP gets its own category after Extensions. Set up for… opens a page with Claude Code, Claude Desktop and Codex: ⏎ copies what adds stack-nudge to each, and a tick shows once its config has it, read from the default and any extra config dirs. Claude Code's command is now user scope. The writes switch moves with it, in the registry too. The version leaves the bottom of the sidebar for the left of Settings' footer, and shows a nightly's build number. --- .../ExtensionSettingsPageTests.swift | 2 +- .../MCPClientsTests.swift | 109 ++++++++++++++ .../SettingsCategoryTests.swift | 4 +- docs/design/local-mcp.md | 8 +- docs/panel.md | 5 +- panel/Components.swift | 11 ++ panel/MCPClients.swift | 133 ++++++++++++++++++ panel/Panel.swift | 2 + panel/PanelNav.swift | 86 +++++++---- panel/ScreenshotRenderer.swift | 20 ++- panel/Settings.swift | 66 +++++++-- panel/SettingsRegistry.swift | 7 +- panel/SettingsRegistryWrites.swift | 2 +- 13 files changed, 406 insertions(+), 49 deletions(-) create mode 100644 Tests/StackNudgePanelCoreTests/MCPClientsTests.swift create mode 100644 panel/MCPClients.swift diff --git a/Tests/StackNudgePanelCoreTests/ExtensionSettingsPageTests.swift b/Tests/StackNudgePanelCoreTests/ExtensionSettingsPageTests.swift index d9d7811..d1e46ab 100644 --- a/Tests/StackNudgePanelCoreTests/ExtensionSettingsPageTests.swift +++ b/Tests/StackNudgePanelCoreTests/ExtensionSettingsPageTests.swift @@ -187,7 +187,7 @@ final class ExtensionSettingsPageTests: XCTestCase { XCTAssertEqual(nav.label(for: .extensionPage("away")), "Away") XCTAssertEqual(nav.selectedRow, .extensionSetting("away", "STACKNUDGE_EXT_A"), "lands on the first row") nav.selectNextCategory() - XCTAssertEqual(nav.settingsCategory, .panel) + XCTAssertEqual(nav.settingsCategory, .mcp) } // Settings, then the app's lock row, then Update when there is one, then diff --git a/Tests/StackNudgePanelCoreTests/MCPClientsTests.swift b/Tests/StackNudgePanelCoreTests/MCPClientsTests.swift new file mode 100644 index 0000000..b9a3272 --- /dev/null +++ b/Tests/StackNudgePanelCoreTests/MCPClientsTests.swift @@ -0,0 +1,109 @@ +import XCTest + +@testable import StackNudgePanelCore + +// Settings → MCP → Set up for…: what each client's setup copies, and whether +// its config already has stack-nudge. +final class MCPClientsTests: XCTestCase { + + private let binary = "/Users/me/Applications/StackNudge.app/Contents/MacOS/stack-nudge" + + func testEachSetupPointsAtTheAppsOwnBinary() { + XCTAssertEqual(MCPClient.claudeCode.setup(binary: binary), + "claude mcp add --scope user stack-nudge -- \(binary) --mcp") + XCTAssertEqual(MCPClient.codex.setup(binary: binary), "codex mcp add stack-nudge -- \(binary) --mcp") + XCTAssertEqual(MCPClient.claudeDesktop.setup(binary: binary), + #""stack-nudge": {"command": "\#(binary)", "args": ["--mcp"]}"#) + } + + // What Desktop gets pasted into its JSON has to stay JSON. + func testDesktopsEntryParsesInsideMCPServers() throws { + let entry = MCPClient.claudeDesktop.setup(binary: "/Users/a \"b\"/stack-nudge") + let config = "{\"mcpServers\": {\(entry)}}" + XCTAssertTrue(MCPClient.claudeDesktop.hasBridge(in: config)) + } + + func testAPathWithASpaceIsQuotedForTheShell() { + XCTAssertEqual(MCPClient.codex.setup(binary: "/Apps/Stack Nudge/stack-nudge"), + "codex mcp add stack-nudge -- '/Apps/Stack Nudge/stack-nudge' --mcp") + } + + func testClaudeCodeIsFoundAtUserOrProjectScope() { + let user = #"{"mcpServers": {"nudge": {"type": "stdio", "command": "\#(binary)", "args": ["--mcp"]}}}"# + let project = #"{"projects": {"/r": {"mcpServers": {"stack-nudge": {"command": "\#(binary)", "args": ["--mcp"]}}}}}"# + XCTAssertTrue(MCPClient.claudeCode.hasBridge(in: user), "found whatever it was named") + XCTAssertTrue(MCPClient.claudeCode.hasBridge(in: project)) + } + + func testOtherServersAndTheAppWithoutTheFlagDontCount() { + let other = #"{"mcpServers": {"x": {"command": "npx", "args": ["stack-nudge", "--mcp"]}}}"# + let noFlag = #"{"mcpServers": {"x": {"command": "\#(binary)", "args": []}}}"# + XCTAssertFalse(MCPClient.claudeDesktop.hasBridge(in: other)) + XCTAssertFalse(MCPClient.claudeDesktop.hasBridge(in: noFlag)) + XCTAssertFalse(MCPClient.claudeDesktop.hasBridge(in: "not json")) + } + + func testCodexsTableIsFound() { + let config = """ + model = "gpt-5" + + [mcp_servers.other] + command = "npx" + args = ["-y", "thing"] + + [mcp_servers.stack-nudge] + command = "\(binary)" + args = [ + "--mcp", + ] + """ + XCTAssertTrue(MCPClient.codex.hasBridge(in: config)) + XCTAssertFalse(MCPClient.codex.hasBridge(in: "[mcp_servers.other]\ncommand = \"npx\"\nargs = [\"--mcp\"]")) + XCTAssertFalse(MCPClient.codex.hasBridge(in: "[profiles.x]\ncommand = \"\(binary)\"\nargs = [\"--mcp\"]")) + } + + // Extra Claude config dirs and Codex homes count as much as the defaults. + func testAClientIsTickedFromAnyOfItsConfigs() { + let codexEntry = "[mcp_servers.n]\ncommand = \"\(binary)\"\nargs = [\"--mcp\"]" + let files = ["/work/.claude/.claude.json": #"{"mcpServers": {"n": {"command": "\#(binary)", "args": ["--mcp"]}}}"#, + "/h/.codex/config.toml": codexEntry] + let configured = MCPClient.configured(home: "/h", claudeDirs: ["/work/.claude"], codexHomes: [], + read: { files[$0] }) + XCTAssertEqual(configured, [.claudeCode, .codex]) + } +} + +// The MCP category and the page below it, reached and left as an integration +// page is. +@MainActor +final class MCPSettingsTests: XCTestCase { + + func testTheCategoryHoldsTheDoorAndTheWritesSwitch() { + let nav = PanelNav() + XCTAssertEqual(nav.rows(in: .mcp), [.mcpSetupClients, .mcpWrites]) + XCTAssertEqual(nav.rows(in: .mcpSetupPage), MCPClient.allCases.map { .mcpClient($0) }) + XCTAssertFalse(nav.rows(in: .actions).contains(.mcpWrites)) + XCTAssertEqual(SettingsCategory.allCases.firstIndex(of: .mcp), + SettingsCategory.allCases.firstIndex(of: .extensions).map { $0 + 1 }) + } + + func testThePageOpensFromItsRowAndGoesBackToIt() { + let nav = PanelNav() + nav.settingsCategory = .mcp + nav.settingsDetailFocused = true + nav.selectFirstCategoryRow() + XCTAssertEqual(nav.selectedRow, .mcpSetupClients) + XCTAssertTrue(nav.selectedRowOpensOnRight) + nav.openMCPSetupPage() + XCTAssertEqual(nav.settingsCategory, .mcpSetupPage) + XCTAssertEqual(nav.sidebarCategory, .mcp, "MCP stays lit while its page is open") + XCTAssertEqual(nav.settingsBackLabel, "MCP") + nav.settingsBack() + XCTAssertEqual(nav.settingsCategory, .mcp) + XCTAssertEqual(nav.selectedRow, .mcpSetupClients) + } + + func testTheWritesSwitchIsListedUnderMCP() { + XCTAssertEqual(SettingsRegistry.spec("STACKNUDGE_MCP_WRITES")?.category, "mcp") + } +} diff --git a/Tests/StackNudgePanelCoreTests/SettingsCategoryTests.swift b/Tests/StackNudgePanelCoreTests/SettingsCategoryTests.swift index 220605f..21486f7 100644 --- a/Tests/StackNudgePanelCoreTests/SettingsCategoryTests.swift +++ b/Tests/StackNudgePanelCoreTests/SettingsCategoryTests.swift @@ -13,7 +13,7 @@ final class SettingsCategoryTests: XCTestCase { func testEveryCategoryRowIsReachableAndUnique() { let nav = PanelNav() var seen: [SettingsRow] = [] - for category in SettingsCategory.allCases + Integration.allCases.map({ .integrationPage($0) }) { + for category in SettingsCategory.allCases + Integration.allCases.map({ .integrationPage($0) }) + [.mcpSetupPage] { seen += nav.rows(in: category) } XCTAssertEqual(Set(seen).count, seen.count, "a row appears in two categories") @@ -60,7 +60,7 @@ final class SettingsCategoryTests: XCTestCase { // GitHub page swaps Connect for Disconnect on signing in; every branch // is reachable, so every one counts as a home. let pages: [SettingsCategory] = Integration.allCases.map { .integrationPage($0) } - + [.extensionPage(SettingsRow.representativeExtensionID)] + + [.extensionPage(SettingsRow.representativeExtensionID), .mcpSetupPage] for cached in [true, false] { for signedIn in [true, false] { nav.voiceModelCached = cached diff --git a/docs/design/local-mcp.md b/docs/design/local-mcp.md index 038f7c7..662f183 100644 --- a/docs/design/local-mcp.md +++ b/docs/design/local-mcp.md @@ -183,10 +183,12 @@ anything else (Settings, the config file) is credited to `stack-nudge`. ## Writes Settings writes are the main use, so v1 has them. One switch governs them, -Settings → Actions → **MCP clients can change settings** (`STACKNUDGE_MCP_WRITES`), +Settings → MCP → **MCP clients can change settings** (`STACKNUDGE_MCP_WRITES`), on by default. It is a client-side opt-in already: nothing reaches stack-nudge -until you add the server, and **Copy MCP setup for Claude Code** on the same -page copies the line that does it, pointing at the installed app. +until you add the server, and **Set up for…** on the same page lists Claude +Code, Claude Desktop and Codex, copies what adds it to each, pointing at the +installed app, and ticks the ones whose config already has it. stack-nudge +reads those configs and never writes them. Any process running as you could already change these by editing the config file, so writes aren't a new privilege. What's new is an agent doing it in one diff --git a/docs/panel.md b/docs/panel.md index 26e358c..510fea9 100644 --- a/docs/panel.md +++ b/docs/panel.md @@ -158,11 +158,14 @@ Reachable from the tab strip, `Cmd+,`, or the last `Cmd`-number. A sidebar of ca | **Usage** | Quota tracking, Quota alerts, Alert threshold, Poll frequency, Context alert, Show remaining, and the two pi budgets | | **Integrations** | A card each for Slack and GitHub, with where it stands on the right; `→` or `⏎` opens its page. Slack's: paste setup, detected user, test message, on/off, idle threshold, message text, finished turns. GitHub's: PR links, GitHub activity, Hide shipped, Connect GitHub (or Disconnect once signed in). Each page's first line says what it's doing or what's wrong | | **Extensions** | What's installed, then **Browse extensions** (see [Extensions](#extensions)) | +| **MCP** | **Set up for…**, whose page has a card each for Claude Code, Claude Desktop and Codex: `⏎` copies what adds stack-nudge to it, and a tick shows once its config has it. Then MCP clients can change settings. See [the local MCP server](design/local-mcp.md) | | **Panel** | Hotkey, Pin panel, Keep open when empty, Launch at login, Name from tab titles | | **Events** | History per session, Event history, Clear event history | -| **Actions** | Edit phrases, Check permissions, Open config file, View release notes, Update channel (Stable or Nightly, see [Nightly builds](setup.md#nightly-builds)), Check for updates, Copy MCP setup for Claude Code and MCP clients can change settings (see [the local MCP server](design/local-mcp.md)), Uninstall, Quit | +| **Actions** | Edit phrases, Check permissions, Open config file, View release notes, Update channel (Stable or Nightly, see [Nightly builds](setup.md#nightly-builds)), Check for updates, Uninstall, Quit | | **About** | The version and hook-script status, and a link to this repo | +The version, nightly build number included, is on the left of the footer on every Settings page. + An extension that asks for a Settings page gets one under Extensions. A pending update, an extension update, a missing permission, or an agent whose hooks aren't wired yet shows as a row above every category. An app or extension update also puts a dot on the Settings tab. | Key | Action | diff --git a/panel/Components.swift b/panel/Components.swift index a895287..d5e9953 100644 --- a/panel/Components.swift +++ b/panel/Components.swift @@ -270,6 +270,9 @@ extension EnvironmentValues { // and "Hide" otherwise. struct PageFooter: View { + // A quiet line on the left, such as Settings' version. Hints keep the + // right. + var leading: String? = nil @ViewBuilder var hints: () -> Hints @Environment(\.escapeCancels) private var escapeCancels @@ -277,6 +280,14 @@ struct PageFooter: View { var body: some View { HStack(spacing: 0) { + if let leading { + Text(leading) + .font(.caption2.monospacedDigit()) + .foregroundStyle(.tertiary) + .lineLimit(1) + .fixedSize() + .padding(.trailing, 12) + } ShedToFitLayout { hints() } diff --git a/panel/MCPClients.swift b/panel/MCPClients.swift new file mode 100644 index 0000000..d9c09bd --- /dev/null +++ b/panel/MCPClients.swift @@ -0,0 +1,133 @@ +import Foundation + +// The MCP clients Settings → MCP → Set up for… can add stack-nudge to, and +// whether each already has it. A client's config is read, never written: +// setting one up copies what to run or paste, so stack-nudge never edits a +// file another app owns. Pure, for tests. +enum MCPClient: CaseIterable, Hashable { + case claudeCode, claudeDesktop, codex + + var name: String { + switch self { + case .claudeCode: return "Claude Code" + case .claudeDesktop: return "Claude Desktop" + case .codex: return "Codex" + } + } + + // The card's second line: what ⏎ copies. + var summary: String { + switch self { + case .claudeCode: return "Copies the claude mcp add command, for every project" + case .claudeDesktop: return "Copies the entry for mcpServers in its config file" + case .codex: return "Copies the codex mcp add command" + } + } + + var symbol: String { + switch self { + case .claudeCode: return "terminal.fill" + case .claudeDesktop: return "macwindow" + case .codex: return "chevron.left.forwardslash.chevron.right" + } + } + + // What to run or paste, pointing at `binary`, this app's own, so it's + // right wherever the app is installed. Claude Desktop doesn't expand ~, so + // its path is always written out in full. + func setup(binary: String) -> String { + let quoted = binary.contains(" ") ? "'\(binary)'" : binary + switch self { + case .claudeCode: + return "claude mcp add --scope user stack-nudge -- \(quoted) \(MCPBridge.flag)" + case .codex: + return "codex mcp add stack-nudge -- \(quoted) \(MCPBridge.flag)" + case .claudeDesktop: + return "\"stack-nudge\": {\"command\": \(Self.jsonString(binary)), \"args\": [\"\(MCPBridge.flag)\"]}" + } + } + + // The files a client keeps its servers in. Claude Code and Codex can each + // run from more than one config dir; the extra ones are the logins the + // Usage tab already found (ClaudeConfigDirs, CodexHomes). + func configFiles(home: String, claudeDirs: [String], codexHomes: [String]) -> [String] { + switch self { + case .claudeCode: + return ["\(home)/.claude.json"] + claudeDirs.map { "\($0)/.claude.json" } + case .claudeDesktop: + return ["\(home)/Library/Application Support/Claude/claude_desktop_config.json"] + case .codex: + return ["\(home)/.codex/config.toml"] + codexHomes.map { "\($0)/config.toml" } + } + } + + // The clients with stack-nudge in any of their config files. + static func configured(home: String = NSHomeDirectory(), claudeDirs: [String] = [], codexHomes: [String] = [], + read: (String) -> String? = { try? String(contentsOfFile: $0, encoding: .utf8) }) + -> Set { + Set(allCases.filter { client in + client.configFiles(home: home, claudeDirs: claudeDirs, codexHomes: codexHomes) + .contains { path in read(path).map(client.hasBridge) ?? false } + }) + } + + // Whether one config file's text has a server running stack-nudge's + // bridge, whatever it was named. + func hasBridge(in text: String) -> Bool { + switch self { + case .claudeCode, .claudeDesktop: return Self.jsonHasBridge(text) + case .codex: return Self.tomlHasBridge(text) + } + } + + // A server is stack-nudge's when it runs the app's binary with --mcp. + static func isBridge(command: String?, args: [String]) -> Bool { + guard let command else { return false } + return (command as NSString).lastPathComponent == "stack-nudge" && args.contains(MCPBridge.flag) + } + + // mcpServers at the top, as Desktop and Claude Code's user scope keep + // them, and under each project, as Claude Code's local scope does. + private static func jsonHasBridge(_ text: String) -> Bool { + guard let data = text.data(using: .utf8), + let root = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] + else { return false } + let projects = (root["projects"] as? [String: Any] ?? [:]).values.compactMap { $0 as? [String: Any] } + let servers = ([root] + projects).flatMap { ($0["mcpServers"] as? [String: Any] ?? [:]).values } + return servers.contains { server in + guard let server = server as? [String: Any] else { return false } + return isBridge(command: server["command"] as? String, args: server["args"] as? [String] ?? []) + } + } + + // Codex's servers are `[mcp_servers.]` tables. Read line by line + // rather than as TOML: only the table's command and args matter here. + private static func tomlHasBridge(_ text: String) -> Bool { + let tables = text.components(separatedBy: "\n").reduce(into: [[String]]()) { tables, raw in + let line = raw.trimmingCharacters(in: .whitespaces) + if line.hasPrefix("[") { + tables.append(line.hasPrefix("[mcp_servers.") ? [] : ["skip"]) + } else if !tables.isEmpty { + tables[tables.count - 1].append(line) + } + } + return tables.filter { $0.first != "skip" }.contains { lines in + let command = lines.first { $0.hasPrefix("command") }.flatMap(quoted) + let args = lines.drop { !$0.hasPrefix("args") }.joined(separator: " ") + return isBridge(command: command, args: args.contains("\"\(MCPBridge.flag)\"") ? [MCPBridge.flag] : []) + } + } + + // The first double-quoted string on a line. + private static func quoted(_ line: String) -> String? { + let parts = line.components(separatedBy: "\"") + return parts.count >= 3 ? parts[1] : nil + } + + private static func jsonString(_ value: String) -> String { + guard let data = try? JSONSerialization.data(withJSONObject: [value], options: [.withoutEscapingSlashes]), + let array = String(data: data, encoding: .utf8) + else { return "\"\(value)\"" } + return String(array.dropFirst().dropLast()) + } +} diff --git a/panel/Panel.swift b/panel/Panel.swift index 931a5a4..95044ea 100644 --- a/panel/Panel.swift +++ b/panel/Panel.swift @@ -1570,6 +1570,8 @@ final class PanelController: NSObject, NSApplicationDelegate, PanelKeyDelegate, .removeDuplicates() .sink { [weak self] category in if case .extensionPage(let id) = category { self?.extensions.tabAppeared(id) } + // Counted on the MCP row, so read as the category opens. + if category == .mcp { self?.nav.refreshMCPClients() } } .store(in: &cancellables) } diff --git a/panel/PanelNav.swift b/panel/PanelNav.swift index db621b0..20acf09 100644 --- a/panel/PanelNav.swift +++ b/panel/PanelNav.swift @@ -217,9 +217,12 @@ enum SettingsRow: Hashable { case githubLinks, githubActivity, hideShipped, connectGithub, disconnectGithub case historyPerSession case editPhrases, checkPermissions, openConfig, releaseNotes, updateChannel, checkUpdates, uninstall, quit - // The local MCP server: whether clients may change settings, and the line - // that adds the server to Claude Code (docs/design/local-mcp.md). - case mcpWrites, mcpSetup + // The local MCP server (docs/design/local-mcp.md): the door to the page of + // clients it can be added to, and whether clients may change settings. + case mcpSetupClients, mcpWrites + // One per client on that page, drawn as a card with a tick once the + // client has stack-nudge. + case mcpClient(MCPClient) case browseExtensions, extensionSources case openRepo // One per built-in integration on the Integrations list, drawn as a card @@ -276,9 +279,9 @@ extension SettingsRow: CaseIterable { .historyPerSession, .editPhrases, .checkPermissions, .openConfig, .releaseNotes, .updateChannel, .checkUpdates, .uninstall, .quit, - .mcpWrites, .mcpSetup, + .mcpSetupClients, .mcpWrites, .browseExtensions, .extensionSources, .openRepo, - ] + Integration.allCases.map { .integration($0) } + ] + Integration.allCases.map { .integration($0) } + MCPClient.allCases.map { .mcpClient($0) } } struct SettingsActions { @@ -1714,6 +1717,10 @@ final class PanelNav: ObservableObject { // somewhere to sign in from, not only to sign out. case .integrationPage(.github): return [.githubLinks, .githubActivity, .hideShipped, githubSignedIn ? .disconnectGithub : .connectGithub] + case .mcp: + return [.mcpSetupClients, .mcpWrites] + case .mcpSetupPage: + return MCPClient.allCases.map { .mcpClient($0) } // Its own category rather than a row under Actions: extensions declare // STACKNUDGE_EXT_ keys, so per-extension configuration needs somewhere // to live, and it should not arrive by growing an unrelated category. @@ -1733,7 +1740,7 @@ final class PanelNav: ObservableObject { return [.historyPerSession, .eventHistory, .clearHistory] case .actions: return [.editPhrases, .checkPermissions, .openConfig, - .releaseNotes, .updateChannel, .checkUpdates, .mcpSetup, .mcpWrites, .uninstall, .quit] + .releaseNotes, .updateChannel, .checkUpdates, .uninstall, .quit] // Version and hook-script freshness render above this row as a plain // note, not as rows: they are readouts with nothing to activate, and a // keyboard-selectable row that ignores Enter reads as broken. @@ -1792,7 +1799,7 @@ final class PanelNav: ObservableObject { // selected category, so anything reaching for a row by identity has to land // on its category first. func category(containing row: SettingsRow) -> SettingsCategory? { - (settingsCategories + Integration.allCases.map { .integrationPage($0) } + (settingsCategories + Integration.allCases.map { .integrationPage($0) } + [.mcpSetupPage] + installedExtensions.map { .extensionPage($0.id) }) .first { rows(in: $0).contains(row) } } @@ -1807,6 +1814,7 @@ final class PanelNav: ObservableObject { switch settingsCategory { case .extensionPage: return .extensions case .integrationPage: return .integrations + case .mcpSetupPage: return .mcp default: return settingsCategory } } @@ -1816,6 +1824,7 @@ final class PanelNav: ObservableObject { switch settingsCategory { case .extensionPage: return "Extensions" case .integrationPage: return "Integrations" + case .mcpSetupPage: return "MCP" default: return "Categories" } } @@ -1835,6 +1844,15 @@ final class PanelNav: ObservableObject { selectFirstCategoryRow() } + // ⏎ on Set up for… opens the page of clients, each ticked or not as its + // config says now. + func openMCPSetupPage() { + refreshMCPClients() + settingsCategory = .mcpSetupPage + settingsDetailFocused = true + selectFirstCategoryRow() + } + // ← in a category's rows. From a page it goes back to the list it was // opened from, on the row that opened it; anywhere else, out to the // sidebar. @@ -1844,6 +1862,8 @@ final class PanelNav: ObservableObject { settingsBack(to: .extensions, on: .installedExtension(id)) case .integrationPage(let integration): settingsBack(to: .integrations, on: .integration(integration)) + case .mcpSetupPage: + settingsBack(to: .mcp, on: .mcpSetupClients) default: settingsDetailFocused = false } @@ -1860,8 +1880,8 @@ final class PanelNav: ObservableObject { // being picked. var selectedRowOpensOnRight: Bool { switch selectedRow { - case .installedExtension, .browseExtensions, .extensionSources, .integration: return true - default: return false + case .installedExtension, .browseExtensions, .extensionSources, .integration, .mcpSetupClients: return true + default: return false } } @@ -2274,7 +2294,8 @@ final class PanelNav: ObservableObject { // the model download. if voiceModelDownloading { cancelVoiceModelDownload() } else { startVoiceModelDownload() } case .connectGithub: connectGithub() - case .mcpSetup: copyMCPSetupCommand() + case .mcpSetupClients: openMCPSetupPage() + case .mcpClient(let client): copyMCPSetup(for: client) case .disconnectGithub: disconnectGithub() case .editPhrases: actions?.editPhrases() case .browseExtensions: actions?.browseExtensions() @@ -2333,7 +2354,7 @@ final class PanelNav: ObservableObject { switch selectedRow { case .wireAgents, .dismissAgents, .connectGithub, .disconnectGithub, .editPhrases, .browseExtensions, .extensionSources, - .installedExtension, .integration, .mcpSetup, + .installedExtension, .integration, .mcpSetupClients, .mcpClient, .checkPermissions, .openConfig, .releaseNotes, .checkUpdates, .uninstall, .quit, .clearHistory, .slackPaste, .slackIdentity, .slackTest, .openRepo, .companionResetPosition, .companionTurnOn, .none: @@ -2459,21 +2480,31 @@ final class PanelNav: ObservableObject { if githubSignedIn != signedIn { githubSignedIn = signedIn } } - // What adds stack-nudge to Claude Code as an MCP server, pointing at this - // app's own binary so it's right wherever the app is installed. - static var mcpSetupCommand: String { - let binary = Bundle.main.executablePath ?? "~/Applications/StackNudge.app/Contents/MacOS/stack-nudge" - let quoted = binary.contains(" ") ? "'\(binary)'" : binary - return "claude mcp add stack-nudge -- \(quoted) \(MCPBridge.flag)" + // This app's own binary, which every client's setup points at. + static var mcpBinaryPath: String { + Bundle.main.executablePath ?? "\(NSHomeDirectory())/Applications/StackNudge.app/Contents/MacOS/stack-nudge" } - @Published var mcpSetupCopied = false + // The clients whose config has stack-nudge, as last read, and the one + // whose setup was just copied. + @Published var mcpConfiguredClients: Set = [] + @Published var mcpCopiedClient: MCPClient? - func copyMCPSetupCommand() { + // A few small file reads, done when the MCP pages are shown, so a client + // set up since (by pasting what was copied) is ticked on the way back. + func refreshMCPClients() { + let configured = MCPClient.configured(claudeDirs: claudeLogins.map(\.configDir), + codexHomes: codexLogins.map(\.codexHome)) + if configured != mcpConfiguredClients { mcpConfiguredClients = configured } + } + + func copyMCPSetup(for client: MCPClient) { NSPasteboard.general.clearContents() - NSPasteboard.general.setString(Self.mcpSetupCommand, forType: .string) - mcpSetupCopied = true - DispatchQueue.main.asyncAfter(deadline: .now() + 3) { [weak self] in self?.mcpSetupCopied = false } + NSPasteboard.general.setString(client.setup(binary: Self.mcpBinaryPath), forType: .string) + mcpCopiedClient = client + DispatchQueue.main.asyncAfter(deadline: .now() + 3) { [weak self] in + if self?.mcpCopiedClient == client { self?.mcpCopiedClient = nil } + } } func setUpdateChannel(_ channel: UpdateChannel) { @@ -2721,7 +2752,7 @@ final class PanelNav: ObservableObject { case .wireAgents, .dismissAgents, .permissions, .update, .extensionUpdates, .hotkey, .speakHotkey, .downloadVoiceModel, .connectGithub, .disconnectGithub, .editPhrases, .browseExtensions, .extensionSources, - .installedExtension, .integration, .mcpSetup, + .installedExtension, .integration, .mcpSetupClients, .mcpClient, .checkPermissions, .openConfig, .releaseNotes, .checkUpdates, .uninstall, .quit, .clearHistory, .slackPaste, .slackIdentity, .slackTest, .openRepo, .companionResetPosition, .companionTurnOn, .none: @@ -2978,16 +3009,19 @@ struct ExtensionTab: Equatable, Identifiable { // one, in install order, and are listed by PanelNav.settingsCategories, since // only nav knows what is installed. `allCases` is the built-in ones alone. enum SettingsCategory: Hashable, CaseIterable { - case notifications, voice, appearance, companion, usage, integrations, extensions, panel, events, + case notifications, voice, appearance, companion, usage, integrations, extensions, mcp, panel, events, actions, about // One extension's page, a level below Extensions. Not in the sidebar. case extensionPage(String) // One integration's page, a level below Integrations. Not in the sidebar. case integrationPage(Integration) + // The clients stack-nudge's MCP server can be added to, a level below MCP. + // Not in the sidebar. + case mcpSetupPage static let allCases: [SettingsCategory] = [ .notifications, .voice, .appearance, .companion, .usage, .integrations, .extensions, - .panel, .events, .actions, .about, + .mcp, .panel, .events, .actions, .about, ] // Kept short: the sidebar is ~120pt. An extension's page is titled by its @@ -3001,6 +3035,8 @@ enum SettingsCategory: Hashable, CaseIterable { case .usage: return "Usage" case .integrations: return "Integrations" case .extensions: return "Extensions" + case .mcp: return "MCP" + case .mcpSetupPage: return "Set up for" case .panel: return "Panel" case .events: return "Events" case .actions: return "Actions" diff --git a/panel/ScreenshotRenderer.swift b/panel/ScreenshotRenderer.swift index 54a18f0..250364b 100644 --- a/panel/ScreenshotRenderer.swift +++ b/panel/ScreenshotRenderer.swift @@ -290,16 +290,26 @@ enum ScreenshotRenderer { // MARK: - MCP - // Settings → Actions with the MCP rows, tall enough to show every row, and - // an MCP client's nudge selected in Events. + // Settings → MCP, the page of clients it can be added to (two of them + // ticked), and an MCP client's nudge selected in Events. private static let mcpScenarios: [Scenario] = [ - Scenario(name: "mcp-settings-actions", set: "mcp", height: 420) { + Scenario(name: "mcp-settings", set: "mcp", height: panelHeight) { let f = PanelFixture(mode: .settings) + f.nav.mcpConfiguredClients = [.claudeCode, .codex] return (f.view, { - f.nav.settingsCategory = .actions + f.nav.settingsCategory = .mcp + f.nav.settingsDetailFocused = true + f.nav.selectFirstCategoryRow() + }) + }, + Scenario(name: "mcp-setup-page", set: "mcp", height: panelHeight) { + let f = PanelFixture(mode: .settings) + f.nav.mcpConfiguredClients = [.claudeCode, .codex] + return (f.view, { + f.nav.settingsCategory = .mcpSetupPage f.nav.settingsDetailFocused = true f.nav.selectedSettingIndex = f.nav.settingsAttentionRows.count - + (f.nav.rows(in: .actions).firstIndex(of: .mcpSetup) ?? 0) + + (f.nav.rows(in: .mcpSetupPage).firstIndex(of: .mcpClient(.claudeDesktop)) ?? 0) }) }, // An extension that offers tools and events to MCP clients, as its diff --git a/panel/Settings.swift b/panel/Settings.swift index 0455bf1..b367b80 100644 --- a/panel/Settings.swift +++ b/panel/Settings.swift @@ -38,7 +38,8 @@ struct SettingsView: View { VStack(alignment: .leading, spacing: 0) { categorySplit - PageFooter { + // The build, nightly and all, on the left of Settings' footer only. + PageFooter(leading: "v\(buildVersion)") { if nav.recordingHotkey || nav.recordingSpeakHotkey { // Esc cancels it too; PageFooter shows that as its last hint. FooterHint(label: "Press a combo with ⌘ / ⇧ / ⌥ / ⌃", keys: [], primary: true) @@ -623,6 +624,58 @@ struct SettingsView: View { .padding(.bottom, 4) } + // The head of the MCP clients page, drawn as an integration page's is. + private var mcpSetupPageHeader: some View { + HStack(alignment: .firstTextBaseline, spacing: 8) { + Text("Set up for").font(.subheadline.weight(.semibold)) + Text("Ticked once stack-nudge is in that app's config").font(.caption).foregroundStyle(.secondary) + .lineLimit(1) + } + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.horizontal, 10) + .padding(.bottom, 4) + } + + // A client on that page, as an integration's card is drawn: what ⏎ copies + // underneath, and on the right a tick when it already has stack-nudge. + private func mcpClientCard(_ client: MCPClient) -> some View { + let row = SettingsRow.mcpClient(client) + let selected = nav.settingsDetailFocused && nav.selectedSettingIndex == nav.index(of: row) + let added = nav.mcpConfiguredClients.contains(client) + return HStack(spacing: 10) { + Image(systemName: client.symbol) + .font(.system(size: 13)) + .foregroundStyle(Color.accentColor) + .frame(width: 18) + VStack(alignment: .leading, spacing: 1) { + Text(client.name).font(.subheadline).lineLimit(1) + Text(client.summary).font(.caption).foregroundStyle(.secondary).lineLimit(1) + } + Spacer(minLength: 8) + if nav.mcpCopiedClient == client { + Text("Copied").font(.caption).foregroundStyle(.secondary) + } else if added { + Label("Added", systemImage: "checkmark.circle.fill") + .font(.caption) + .foregroundStyle(.green) + } else { + Text("Copy").font(.caption).foregroundStyle(.secondary) + } + } + .padding(.horizontal, 10) + .padding(.vertical, 7) + .background(RoundedRectangle(cornerRadius: 8, style: .continuous) + .fill(Color.accentColor.opacity(selected ? 0.22 : 0))) + .contentShape(Rectangle()) + .onTapGesture { + nav.selectedSettingIndex = nav.index(of: row) + nav.activate() + } + .accessibilityElement(children: .combine) + .accessibilityAddTraits(selected ? [.isSelected] : []) + .id(nav.index(of: row)) + } + // Read-only lines under a page's rows: what it was allowed, in plain // words, and where else it appears. private func extensionPageTrailer(_ id: String) -> some View { @@ -954,8 +1007,9 @@ struct SettingsView: View { case .openConfig: row(.openConfig, label: "Open config file…", kind: .action, value: "") case .releaseNotes: row(.releaseNotes, label: "View release notes…", kind: .action, value: "") case .updateChannel: row(.updateChannel, label: "Update channel", kind: .cycle, value: nav.updateChannel.label) - case .mcpSetup: row(.mcpSetup, label: "Copy MCP setup for Claude Code", kind: .action, - value: nav.mcpSetupCopied ? "Copied" : "") + case .mcpSetupClients: row(.mcpSetupClients, label: "Set up for\u{2026}", kind: .action, + value: nav.mcpConfiguredClients.isEmpty ? "" : "\(nav.mcpConfiguredClients.count) added") + case .mcpClient(let client): mcpClientCard(client) case .mcpWrites: row(.mcpWrites, label: "MCP clients can change settings", kind: .toggle, value: nav.mcpWritesEnabled ? "On" : "Off") case .checkUpdates: row(.checkUpdates, label: "Check for updates…", kind: .action, value: checkForUpdatesStatus) @@ -1038,11 +1092,6 @@ struct SettingsView: View { } } } - - Text("v\(appVersion)") - .font(.caption2.monospacedDigit()) - .foregroundStyle(.tertiary) - .padding(.horizontal, 8) } .frame(width: 124) .padding(.vertical, 10) @@ -1077,6 +1126,7 @@ struct SettingsView: View { if case .integrationPage(let integration) = nav.settingsCategory { integrationPageHeader(integration) } + if nav.settingsCategory == .mcpSetupPage { mcpSetupPageHeader } detailRows } .padding(.horizontal, 14) diff --git a/panel/SettingsRegistry.swift b/panel/SettingsRegistry.swift index 4f4fe70..f3fd6f1 100644 --- a/panel/SettingsRegistry.swift +++ b/panel/SettingsRegistry.swift @@ -198,11 +198,12 @@ enum SettingsRegistry { // Extensions SettingSpec(key: "STACKNUDGE_AWAY_LOCK", label: "Lock screen when away", category: "extensions", kind: .toggle, read: { .bool($0.awayLock) }, readOnlyReason: protectsLock), + // MCP + SettingSpec(key: "STACKNUDGE_MCP_WRITES", label: "MCP clients can change settings", category: "mcp", + kind: .toggle, read: { .bool($0.mcpWritesEnabled) }, + readOnlyReason: "Only you can decide what MCP clients may change. Change it in Settings → MCP."), // Actions SettingSpec(key: UpdateChannel.configKey, label: "Update channel", category: "actions", kind: .choice(UpdateChannel.allCases.map(\.rawValue)), read: { .string($0.updateChannel.rawValue) }), - SettingSpec(key: "STACKNUDGE_MCP_WRITES", label: "MCP clients can change settings", category: "actions", - kind: .toggle, read: { .bool($0.mcpWritesEnabled) }, - readOnlyReason: "Only you can decide what MCP clients may change. Change it in Settings → Actions."), ] } diff --git a/panel/SettingsRegistryWrites.swift b/panel/SettingsRegistryWrites.swift index c711c8c..d07070e 100644 --- a/panel/SettingsRegistryWrites.swift +++ b/panel/SettingsRegistryWrites.swift @@ -20,7 +20,7 @@ extension SettingsRegistry { case .readOnly(let reason): return reason case .writesOff: - return "Changing settings from MCP is off. Turn on Settings → Actions → MCP clients can change settings." + return "Changing settings from MCP is off. Turn on Settings → MCP → MCP clients can change settings." case .invalidValue(let message): return message }