From 6e2b45850870efdeec9f3d978879fef8f20997e6 Mon Sep 17 00:00:00 2001 From: Kylo Jorgensen Date: Wed, 8 Jul 2026 21:53:40 -0600 Subject: [PATCH 01/51] feat(browser): host web extensions via WKWebExtension (Bitwarden support) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds native web-extension support to the built-in browser using WebKit's WKWebExtension API, availability-gated to macOS 15.4+ (deployment target unchanged). Extensions are discovered from the Bitwarden desktop app's bundled Safari web extension and from unpacked directories listed in the CMUX_BROWSER_EXTENSIONS environment variable. - BrowserWebExtensionSupport owns a persistent WKWebExtensionController attached to every browser WKWebViewConfiguration, auto-grants manifest permissions, and implements the controller delegate (action popups, permission prompts, window/tab creation, native messaging). - Tab/window adapters expose browser panels to extensions as tabs of one virtual window; Workspace.focusPanel drives tab-activation events. - Popout window controller implements windows.create for extension pages (Bitwarden passkey confirmation, unlock, and 2FA popouts). - Toolbar action button per loaded extension anchors the extension popup. - Extension keyboard commands (e.g. Bitwarden autofill ⌘⇧L) are offered from CmuxWebView.performKeyEquivalent, and from the stale-menu-shortcut suppression path in sendEvent so a remapped-away cmux default (⌘⇧L is Open Browser's default) stays usable by extensions. Notable behaviors learned the hard way, encoded in comments: - Extension web views must present a Safari UA (applicationNameForUserAgent); Bitwarden's UI crashes at boot on WebKit's default UA. - Native-messaging requests are parked unresolved instead of erroring; Bitwarden retry-loops without backoff on error replies. Verified with Bitwarden 2026.2.0: vault login, popup UI, content-script autofill, ⌘⇧L autofill command, and passkey sign-in via popout. Closes-Discussion: manaflow-ai/cmux#2001 Co-Authored-By: Claude Fable 5 --- Resources/Localizable.xcstrings | 119 +++++ Sources/App/ShortcutRoutingSupport.swift | 18 + Sources/AppDelegate.swift | 10 + Sources/Panels/BrowserPanel.swift | 9 + Sources/Panels/BrowserPanelView.swift | 9 + ...erWebExtensionPopoutWindowController.swift | 172 +++++++ .../Panels/BrowserWebExtensionSupport.swift | 484 ++++++++++++++++++ .../BrowserWebExtensionTabAdapter.swift | 78 +++ .../BrowserWebExtensionToolbarButtons.swift | 98 ++++ .../BrowserWebExtensionWindowAdapter.swift | 54 ++ Sources/Panels/CmuxWebView.swift | 7 + Sources/Workspace.swift | 3 + cmux.xcodeproj/project.pbxproj | 20 + 13 files changed, 1081 insertions(+) create mode 100644 Sources/Panels/BrowserWebExtensionPopoutWindowController.swift create mode 100644 Sources/Panels/BrowserWebExtensionSupport.swift create mode 100644 Sources/Panels/BrowserWebExtensionTabAdapter.swift create mode 100644 Sources/Panels/BrowserWebExtensionToolbarButtons.swift create mode 100644 Sources/Panels/BrowserWebExtensionWindowAdapter.swift diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index d82597428f6e..118fc58f644b 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -30613,6 +30613,125 @@ } } }, + "browser.webExtension.action.help": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "ملحق" + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "Ekstenzija" + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "Udvidelse" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Erweiterung" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Extension" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Extensión" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Extension" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Estensione" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "拡張機能" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "확장 프로그램" + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "Utvidelse" + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "Rozszerzenie" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Extensão" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Расширение" + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "ส่วนขยาย" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Uzantı" + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "Розширення" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "扩展" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "延伸功能" + } + } + } + }, "canvas.commandScrollHint": { "extractionState": "manual", "localizations": { diff --git a/Sources/App/ShortcutRoutingSupport.swift b/Sources/App/ShortcutRoutingSupport.swift index 9c43c05e70ef..6fd50443ec04 100644 --- a/Sources/App/ShortcutRoutingSupport.swift +++ b/Sources/App/ShortcutRoutingSupport.swift @@ -795,6 +795,24 @@ func cmuxOwningGhosttyView(for responder: NSResponder?) -> GhosttyNSView? { return nil } +/// Whether the responder chain passes through a browser web view, so +/// web-extension shortcut commands (e.g. Bitwarden autofill) may claim the event. +func cmuxRespondersContainBrowserWebView(_ responder: NSResponder?) -> Bool { + var current: NSResponder? = responder + while let next = current { + if next is CmuxWebView { return true } + if let view = next as? NSView { + var ancestor: NSView? = view.superview + while let candidate = ancestor { + if candidate is CmuxWebView { return true } + ancestor = candidate.superview + } + } + current = next.nextResponder + } + return false +} + func cmuxFieldEditorOwnerView(_ editor: NSTextView) -> NSView? { guard editor.isFieldEditor else { return nil } if let owner = cmuxTrackedFindFieldEditorOwner(editor) { return owner } diff --git a/Sources/AppDelegate.swift b/Sources/AppDelegate.swift index 88294bcefb4b..91b1f11fb311 100644 --- a/Sources/AppDelegate.swift +++ b/Sources/AppDelegate.swift @@ -16534,6 +16534,16 @@ private extension NSApplication { let responder = event.window?.firstResponder ?? AppDelegate.shared?.shortcutRoutingKeyWindow?.firstResponder ?? mainWindow?.firstResponder + // A stale default (e.g. ⌘⇧L after Open Browser is remapped) is free for + // web-extension commands like Bitwarden autofill while a browser web + // view has focus; otherwise the suppression below would eat it. + if #available(macOS 15.4, *), cmuxRespondersContainBrowserWebView(responder), + BrowserWebExtensionSupport.shared.performCommand(for: event) { +#if DEBUG + cmuxDebugLog("app.sendEvent routed web-extension command before stale cmux menu shortcut") +#endif + return + } if let ghosttyView = cmuxOwningGhosttyView(for: responder) { ghosttyView.keyDown(with: event) #if DEBUG diff --git a/Sources/Panels/BrowserPanel.swift b/Sources/Panels/BrowserPanel.swift index 82686c11c543..bd2752b09ecd 100644 --- a/Sources/Panels/BrowserPanel.swift +++ b/Sources/Panels/BrowserPanel.swift @@ -3566,6 +3566,9 @@ final class BrowserPanel: Panel, ObservableObject { // Ensure browser cookies/storage persist across navigations and launches. // This reduces repeated consent/bot-challenge flows on sites like Google. configuration.websiteDataStore = websiteDataStore + if #available(macOS 15.4, *) { + BrowserWebExtensionSupport.shared.attach(to: configuration) + } if configuration.urlSchemeHandler(forURLScheme: CmuxDiffViewerURLSchemeHandler.scheme) == nil { configuration.setURLSchemeHandler( CmuxDiffViewerURLSchemeHandler.shared, @@ -3990,6 +3993,9 @@ final class BrowserPanel: Panel, ObservableObject { hiddenWebViewDiscardManager.delegate = self applyProxyConfigurationIfAvailable() BrowserProfileStore.shared.noteUsed(resolvedProfileID) + if #available(macOS 15.4, *) { + BrowserWebExtensionSupport.shared.register(panel: self) + } // Set up navigation delegate let navDelegate = BrowserNavigationDelegate() @@ -5295,6 +5301,9 @@ final class BrowserPanel: Panel, ObservableObject { } func close() { + if #available(macOS 15.4, *) { + BrowserWebExtensionSupport.shared.unregister(panelID: id) + } cancelHiddenWebViewDiscard() isClosingWebViewLifecycle = true refreshWebViewLifecycleState() diff --git a/Sources/Panels/BrowserPanelView.swift b/Sources/Panels/BrowserPanelView.swift index a68d6b2f4462..e29908949476 100644 --- a/Sources/Panels/BrowserPanelView.swift +++ b/Sources/Panels/BrowserPanelView.swift @@ -1348,6 +1348,15 @@ struct BrowserPanelView: View { onClear: { panel.clearRecentDownloads() } ) } + + if #available(macOS 15.4, *) { + BrowserWebExtensionToolbarButtons( + support: BrowserWebExtensionSupport.shared, + panel: panel, + iconPointSize: chromeMetrics.navigationIconFontSize, + hitSize: addressBarButtonHitSize + ) + } } } diff --git a/Sources/Panels/BrowserWebExtensionPopoutWindowController.swift b/Sources/Panels/BrowserWebExtensionPopoutWindowController.swift new file mode 100644 index 000000000000..7f6d44d7d00f --- /dev/null +++ b/Sources/Panels/BrowserWebExtensionPopoutWindowController.swift @@ -0,0 +1,172 @@ +import AppKit +import WebKit + +/// Hosts a `windows.create({type: "popup"})` window opened by a web extension — +/// e.g. Bitwarden's passkey-confirmation, unlock, and 2FA popouts. +/// +/// The controller is both the `WKWebExtensionWindow` and the owner of the native +/// `NSWindow` + extension-page `WKWebView`; its single tab is a nested adapter. +@available(macOS 15.4, *) +@MainActor +final class BrowserWebExtensionPopoutWindowController: NSObject, WKWebExtensionWindow, NSWindowDelegate { + private static let defaultSize = CGSize(width: 400, height: 600) + + let window: NSWindow + let webView: WKWebView + private(set) lazy var tab = Tab(controller: self) + private weak var support: BrowserWebExtensionSupport? + private weak var extensionContext: WKWebExtensionContext? + + init( + configuration: WKWebExtension.WindowConfiguration, + context: WKWebExtensionContext, + support: BrowserWebExtensionSupport + ) { + self.support = support + self.extensionContext = context + + let webViewConfiguration = context.webViewConfiguration ?? WKWebViewConfiguration() + webView = WKWebView(frame: .zero, configuration: webViewConfiguration) + webView.isInspectable = true + + var frame = configuration.frame + if frame.isNull || frame.isEmpty || frame.width < 50 || frame.height < 50 { + frame = CGRect(origin: .zero, size: Self.defaultSize) + } + window = NSWindow( + contentRect: frame, + styleMask: [.titled, .closable, .resizable], + backing: .buffered, + defer: false + ) + window.isReleasedWhenClosed = false + window.level = .floating + window.contentView = webView + if configuration.frame.isNull || configuration.frame.isEmpty { + window.center() + } + + super.init() + window.delegate = self + window.title = context.webExtension.displayName ?? "Extension" + + if let url = configuration.tabURLs.first { + webView.load(URLRequest(url: url)) + } + if configuration.shouldBeFocused { + NSApp.activate(ignoringOtherApps: false) + window.makeKeyAndOrderFront(nil) + } else { + window.orderFront(nil) + } + } + + var isKeyWindow: Bool { + window.isKeyWindow + } + + func closeFromExtensionOrUser() { + guard window.delegate === self else { return } + window.delegate = nil + support?.popoutDidClose(self) + window.close() + } + + // MARK: - NSWindowDelegate + + func windowWillClose(_ notification: Notification) { + window.delegate = nil + support?.popoutDidClose(self) + } + + // MARK: - WKWebExtensionWindow + + func tabs(for context: WKWebExtensionContext) -> [any WKWebExtensionTab] { + [tab] + } + + func activeTab(for context: WKWebExtensionContext) -> (any WKWebExtensionTab)? { + tab + } + + func windowType(for context: WKWebExtensionContext) -> WKWebExtension.WindowType { + .popup + } + + func windowState(for context: WKWebExtensionContext) -> WKWebExtension.WindowState { + .normal + } + + func isPrivate(for context: WKWebExtensionContext) -> Bool { + false + } + + func frame(for context: WKWebExtensionContext) -> CGRect { + window.frame + } + + func screenFrame(for context: WKWebExtensionContext) -> CGRect { + window.screen?.frame ?? NSScreen.main?.frame ?? .null + } + + func focus(for context: WKWebExtensionContext, completionHandler: @escaping (Error?) -> Void) { + window.makeKeyAndOrderFront(nil) + completionHandler(nil) + } + + func close(for context: WKWebExtensionContext, completionHandler: @escaping (Error?) -> Void) { + closeFromExtensionOrUser() + completionHandler(nil) + } + + // MARK: - Tab + + /// The popout window's single extension-page tab. + @MainActor + final class Tab: NSObject, WKWebExtensionTab { + private weak var controller: BrowserWebExtensionPopoutWindowController? + + init(controller: BrowserWebExtensionPopoutWindowController) { + self.controller = controller + } + + func window(for context: WKWebExtensionContext) -> (any WKWebExtensionWindow)? { + controller + } + + func indexInWindow(for context: WKWebExtensionContext) -> Int { + 0 + } + + func webView(for context: WKWebExtensionContext) -> WKWebView? { + controller?.webView + } + + func url(for context: WKWebExtensionContext) -> URL? { + controller?.webView.url + } + + func title(for context: WKWebExtensionContext) -> String? { + controller?.webView.title + } + + func isSelected(for context: WKWebExtensionContext) -> Bool { + true + } + + func isLoadingComplete(for context: WKWebExtensionContext) -> Bool { + guard let webView = controller?.webView else { return true } + return !webView.isLoading + } + + func loadURL(_ url: URL, for context: WKWebExtensionContext, completionHandler: @escaping (Error?) -> Void) { + controller?.webView.load(URLRequest(url: url)) + completionHandler(nil) + } + + func close(for context: WKWebExtensionContext, completionHandler: @escaping (Error?) -> Void) { + controller?.closeFromExtensionOrUser() + completionHandler(nil) + } + } +} diff --git a/Sources/Panels/BrowserWebExtensionSupport.swift b/Sources/Panels/BrowserWebExtensionSupport.swift new file mode 100644 index 000000000000..1a6e5bf51904 --- /dev/null +++ b/Sources/Panels/BrowserWebExtensionSupport.swift @@ -0,0 +1,484 @@ +import AppKit +import SwiftUI +import WebKit + +/// Hosts Chrome/Safari-style web extensions in the built-in browser via WebKit's +/// native `WKWebExtensionController` API (macOS 15.4+). +/// +/// One shared controller (persistent storage keyed by a fixed identifier) is attached +/// to every browser `WKWebViewConfiguration`. Extensions are discovered from: +/// - directories listed in the `CMUX_BROWSER_EXTENSIONS` environment variable +/// (colon-separated paths to unpacked extensions or `.appex` bundles), and +/// - the Bitwarden desktop app's bundled Safari web extension, when installed. +@available(macOS 15.4, *) +@MainActor +final class BrowserWebExtensionSupport: NSObject, ObservableObject { + static let shared = BrowserWebExtensionSupport() + + /// Fixed identifier so extension storage (e.g. the Bitwarden vault cache) + /// persists across app launches. + private static let controllerIdentifier = UUID(uuidString: "8C0FDE2B-6EFD-4E8C-9E70-8E7D0A4C51B7")! + + /// Bundled Safari web extension inside the Bitwarden desktop app. + private static let bitwardenAppexURL = URL( + fileURLWithPath: "/Applications/Bitwarden.app/Contents/PlugIns/safari.appex" + ) + + let controller: WKWebExtensionController + + @Published private(set) var contexts: [WKWebExtensionContext] = [] + @Published private(set) var loadErrors: [String] = [] + + private var didStartLoading = false + private var tabAdapters: [UUID: BrowserWebExtensionTabAdapter] = [:] + private var orderedPanelIDs: [UUID] = [] + private(set) var activePanelID: UUID? + private(set) lazy var windowAdapter = BrowserWebExtensionWindowAdapter(support: self) + private var popouts: [BrowserWebExtensionPopoutWindowController] = [] + + /// Anchor for the next action popup presentation, set by the toolbar button + /// immediately before calling `performAction(context:panel:anchorView:)`. + private weak var pendingPopupAnchorView: NSView? + + private var nativeMessageDropCount = 0 + + private override init() { + let configuration = WKWebExtensionController.Configuration(identifier: Self.controllerIdentifier) + // Extension-owned web views (background page, action popup) get WebKit's + // default user agent, which lacks the " Safari/" token. Extensions like + // Bitwarden classify the browser from the UA and crash on an unknown one, + // so present the same Safari application identity the browser panels use. + let webViewConfiguration = configuration.webViewConfiguration ?? WKWebViewConfiguration() + webViewConfiguration.applicationNameForUserAgent = "Version/26.2 Safari/605.1.15" + configuration.webViewConfiguration = webViewConfiguration + controller = WKWebExtensionController(configuration: configuration) + super.init() + controller.delegate = self + } + + // MARK: - Configuration attachment + + /// Attaches the shared extension controller to a browser web view configuration + /// and kicks off extension discovery on first use. + func attach(to configuration: WKWebViewConfiguration) { + configuration.webExtensionController = controller + loadInstalledExtensionsIfNeeded() + } + + private func loadInstalledExtensionsIfNeeded() { + guard !didStartLoading else { return } + didStartLoading = true + Task { await loadInstalledExtensions() } + } + + private func loadInstalledExtensions() async { + for url in Self.candidateExtensionURLs() { + do { + let webExtension: WKWebExtension + if url.pathExtension == "appex" { + if let bundle = Bundle(url: url) { + webExtension = try await WKWebExtension(appExtensionBundle: bundle) + } else { + // Fall back to reading the appex's web-extension resources directly. + let resources = url.appendingPathComponent("Contents/Resources", isDirectory: true) + webExtension = try await WKWebExtension(resourceBaseURL: resources) + } + } else { + webExtension = try await WKWebExtension(resourceBaseURL: url) + } + try load(webExtension) +#if DEBUG + cmuxDebugLog( + "browser.webext.loaded name=\(webExtension.displayName ?? "?") " + + "version=\(webExtension.displayVersion ?? "?") url=\(url.path)" + ) +#endif + } catch { + loadErrors.append("\(url.lastPathComponent): \(error.localizedDescription)") +#if DEBUG + cmuxDebugLog("browser.webext.loadFailed url=\(url.path) error=\(error.localizedDescription)") +#endif + } + } + } + + private func load(_ webExtension: WKWebExtension) throws { + let context = WKWebExtensionContext(for: webExtension) + // Grant everything the manifest requests up front; interactive permission + // prompting can come later. Repeat grants are also answered by the + // prompt delegate methods below. + for permission in webExtension.requestedPermissions { + context.setPermissionStatus(.grantedExplicitly, for: permission) + } + for pattern in webExtension.allRequestedMatchPatterns { + context.setPermissionStatus(.grantedExplicitly, for: pattern) + } +#if DEBUG + context.isInspectable = true +#endif + try controller.load(context) + contexts.append(context) +#if DEBUG + logDiagnostics(for: context, label: "postLoad") + Task { @MainActor [weak self] in + try? await Task.sleep(for: .seconds(5)) + self?.logDiagnostics(for: context, label: "postLoad+5s") + } + if ProcessInfo.processInfo.environment["CMUX_WEBEXT_AUTOPROBE"] == "1" { + Task { @MainActor [weak self] in + try? await Task.sleep(for: .seconds(8)) + guard let self else { return } + cmuxDebugLog("browser.webext.autoprobe performAction") + context.performAction(for: self.activeTabAdapter) + } + } +#endif + } + +#if DEBUG + private func logDiagnostics(for context: WKWebExtensionContext, label: String) { + let ext = context.webExtension + cmuxDebugLog( + "browser.webext.diag(\(label)) name=\(ext.displayName ?? "?") " + + "loaded=\(context.isLoaded ? 1 : 0) " + + "injected=\(ext.hasInjectedContent ? 1 : 0) " + + "background=\(ext.hasBackgroundContent ? 1 : 0) " + + "allURLs=\(context.hasAccessToAllURLs ? 1 : 0) " + + "perms=\(context.currentPermissions.count) " + + "patterns=\(context.currentPermissionMatchPatterns.count) " + + "openTabs=\(context.openTabs.count) " + + "ctxErrors=\(context.errors.map(\.localizedDescription).joined(separator: " | ")) " + + "extErrors=\(ext.errors.map(\.localizedDescription).joined(separator: " | "))" + ) + for command in context.commands { + cmuxDebugLog( + "browser.webext.command registered id=\(command.id) " + + "key=\(command.activationKey ?? "nil") mods=\(command.modifierFlags.rawValue) " + + "title=\(command.title)" + ) + } + } +#endif + + /// Extension bundles/directories to try loading, in order. + private static func candidateExtensionURLs() -> [URL] { + var urls: [URL] = [] + if let env = ProcessInfo.processInfo.environment["CMUX_BROWSER_EXTENSIONS"] { + for path in env.split(separator: ":") where !path.isEmpty { + urls.append(URL(fileURLWithPath: String(path))) + } + } + if FileManager.default.fileExists(atPath: bitwardenAppexURL.path) { + urls.append(bitwardenAppexURL) + } + return urls + } + + // MARK: - Tab lifecycle (called from BrowserPanel) + + func register(panel: BrowserPanel) { + guard tabAdapters[panel.id] == nil else { return } + let adapter = BrowserWebExtensionTabAdapter(panel: panel, support: self) + tabAdapters[panel.id] = adapter + orderedPanelIDs.append(panel.id) + if activePanelID == nil { activePanelID = panel.id } + controller.didOpenTab(adapter) + } + + func unregister(panelID: UUID) { + guard let adapter = tabAdapters.removeValue(forKey: panelID) else { return } + orderedPanelIDs.removeAll { $0 == panelID } + if activePanelID == panelID { activePanelID = orderedPanelIDs.last } + controller.didCloseTab(adapter, windowIsClosing: false) + } + + func noteActivated(panelID: UUID) { + guard tabAdapters[panelID] != nil, activePanelID != panelID else { return } + let previous = activePanelID.flatMap { tabAdapters[$0] } + activePanelID = panelID + if let adapter = tabAdapters[panelID] { + controller.didActivateTab(adapter, previousActiveTab: previous) + } + } + + func tabAdapter(for panelID: UUID) -> BrowserWebExtensionTabAdapter? { + tabAdapters[panelID] + } + + var orderedTabAdapters: [BrowserWebExtensionTabAdapter] { + orderedPanelIDs.compactMap { tabAdapters[$0] } + } + + var activeTabAdapter: BrowserWebExtensionTabAdapter? { + activePanelID.flatMap { tabAdapters[$0] } + } + + func indexInWindow(of panelID: UUID) -> Int { + orderedPanelIDs.firstIndex(of: panelID) ?? 0 + } + + // MARK: - Action popup + + /// Performs the extension's toolbar action for `panel`, anchoring any popup + /// the extension presents to `anchorView`. + func performAction(context: WKWebExtensionContext, panel: BrowserPanel, anchorView: NSView?) { + noteActivated(panelID: panel.id) + pendingPopupAnchorView = anchorView + context.performAction(for: tabAdapter(for: panel.id)) + } + + // MARK: - Keyboard commands + + /// Offers a key equivalent to loaded extensions' declared commands + /// (e.g. Bitwarden's ⌘⇧L autofill). Returns true when one handled it. + func performCommand(for event: NSEvent) -> Bool { + for context in contexts where context.performCommand(for: event) { +#if DEBUG + cmuxDebugLog("browser.webext.command handled name=\(context.webExtension.displayName ?? "?")") +#endif + return true + } +#if DEBUG + if !contexts.isEmpty { + cmuxDebugLog( + "browser.webext.command unmatched key=\(event.charactersIgnoringModifiers ?? "?") " + + "mods=\(event.modifierFlags.intersection(.deviceIndependentFlagsMask).rawValue)" + ) + } +#endif + return false + } + + // MARK: - Popout windows + + func popoutDidClose(_ popout: BrowserWebExtensionPopoutWindowController) { + guard popouts.contains(where: { $0 === popout }) else { return } + popouts.removeAll { $0 === popout } + controller.didCloseTab(popout.tab, windowIsClosing: true) + controller.didCloseWindow(popout) + } +} + +// MARK: - WKWebExtensionControllerDelegate + +@available(macOS 15.4, *) +extension BrowserWebExtensionSupport: WKWebExtensionControllerDelegate { + func webExtensionController( + _ controller: WKWebExtensionController, + openWindowsFor extensionContext: WKWebExtensionContext + ) -> [any WKWebExtensionWindow] { + [windowAdapter] + popouts + } + + func webExtensionController( + _ controller: WKWebExtensionController, + focusedWindowFor extensionContext: WKWebExtensionContext + ) -> (any WKWebExtensionWindow)? { + popouts.first(where: \.isKeyWindow) ?? windowAdapter + } + + func webExtensionController( + _ controller: WKWebExtensionController, + openNewWindowUsing configuration: WKWebExtension.WindowConfiguration, + for extensionContext: WKWebExtensionContext, + completionHandler: @escaping ((any WKWebExtensionWindow)?, Error?) -> Void + ) { +#if DEBUG + cmuxDebugLog( + "browser.webext.openWindow type=\(configuration.windowType.rawValue) " + + "urls=\(configuration.tabURLs.count) focused=\(configuration.shouldBeFocused ? 1 : 0)" + ) +#endif + let popout = BrowserWebExtensionPopoutWindowController( + configuration: configuration, + context: extensionContext, + support: self + ) + popouts.append(popout) + controller.didOpenWindow(popout) + controller.didOpenTab(popout.tab) + completionHandler(popout, nil) + } + + func webExtensionController( + _ controller: WKWebExtensionController, + openNewTabUsing configuration: WKWebExtension.TabConfiguration, + for extensionContext: WKWebExtensionContext, + completionHandler: @escaping ((any WKWebExtensionTab)?, Error?) -> Void + ) { +#if DEBUG + cmuxDebugLog("browser.webext.openTab url=\(configuration.url?.absoluteString.prefix(80) ?? "nil")") +#endif + // External pages go to the user's default browser context inside cmux + // panels eventually; for now open http(s) URLs via the system and host + // extension pages in a popout window. + if let url = configuration.url, url.scheme == "https" || url.scheme == "http" { + NSWorkspace.shared.open(url) + completionHandler(nil, nil) + return + } + completionHandler(nil, NSError( + domain: "cmux.webExtension", code: 2, + userInfo: [NSLocalizedDescriptionKey: "Opening extension tabs is not supported yet"] + )) + } + + func webExtensionController( + _ controller: WKWebExtensionController, + presentActionPopup action: WKWebExtension.Action, + for context: WKWebExtensionContext, + completionHandler: @escaping (Error?) -> Void + ) { + guard let popover = action.popupPopover else { + completionHandler(nil) + return + } + let candidates: [NSView?] = [ + pendingPopupAnchorView, + activeTabAdapter?.panel?.webView, + orderedTabAdapters.first(where: { $0.panel?.webView.window != nil })?.panel?.webView, + NSApp.keyWindow?.contentView ?? NSApp.mainWindow?.contentView, + ] + pendingPopupAnchorView = nil + guard let anchor = candidates.compactMap({ $0 }).first(where: { $0.window != nil }) else { +#if DEBUG + cmuxDebugLog("browser.webext.actionPopup no window-attached anchor; dropping popup") +#endif + completionHandler(nil) + return + } + popover.behavior = .transient + popover.show(relativeTo: anchor.bounds, of: anchor, preferredEdge: .maxY) +#if DEBUG + if ProcessInfo.processInfo.environment["CMUX_WEBEXT_AUTOPROBE"] == "1", + let popupWebView = action.popupWebView { + probePopup(popupWebView) + } +#endif + completionHandler(nil) + } + +#if DEBUG + /// Evaluates a WebExtension-API probe inside the action popup so tab/window + /// adapter behavior is observable from the extension's point of view. + /// Installs an error-capture hook and reloads the popup first so boot-time + /// console errors and unhandled rejections are observable. + private func probePopup(_ popupWebView: WKWebView) { + Task { @MainActor in + let hookSource = """ + window.__errs = []; + window.addEventListener("error", (e) => window.__errs.push("E:" + e.message + "@" + (e.filename || "") + ":" + (e.lineno || 0))); + window.addEventListener("unhandledrejection", (e) => window.__errs.push("R:" + ((e.reason && (e.reason.stack || e.reason.message)) || e.reason))); + const ce = console.error.bind(console); + console.error = (...a) => { window.__errs.push("C:" + a.map(String).join(" ").slice(0, 300)); ce(...a); }; + """ + popupWebView.configuration.userContentController.addUserScript( + WKUserScript(source: hookSource, injectionTime: .atDocumentStart, forMainFrameOnly: false) + ) + popupWebView.reload() + try? await Task.sleep(for: .seconds(5)) + let script = """ + try { + const api = globalThis.browser || globalThis.chrome; + const tabs = await api.tabs.query({ active: true, currentWindow: true }); + const wins = await api.windows.getAll(); + const win = await api.windows.getCurrent().catch((e) => 'ERR:' + e.message); + let popoutTest = "skipped"; + try { + const w = await api.windows.create({ url: "popup/index.html", type: "popup", width: 380, height: 500, focused: false }); + popoutTest = w ? "created:" + w.id + ":tabs=" + (w.tabs ? w.tabs.length : "?") : "null"; + if (w) { await new Promise(r => setTimeout(r, 1500)); await api.windows.remove(w.id); popoutTest += ":removed"; } + } catch (e) { popoutTest = "ERR:" + (e && e.message); } + return JSON.stringify({ + ready: document.readyState, + bodyChildren: document.body ? document.body.children.length : -1, + tabCount: tabs.length, + tab0: tabs[0] ? `${tabs[0].id}:${tabs[0].url || "nourl"}:${tabs[0].title || "notitle"}` : "none", + winCount: wins.length, + currentWin: typeof win === "string" ? win : (win ? win.id : "none"), + text: (document.body ? document.body.innerText : "").replace(/\\s+/g, " ").slice(0, 160), + html: (document.body ? document.body.innerHTML : "").replace(/\\s+/g, " ").slice(0, 240), + errs: (window.__errs || []).slice(0, 8), + popoutTest + }); + } catch (e) { return "ERR:" + (e && e.message); } + """ + popupWebView.callAsyncJavaScript(script, arguments: [:], in: nil, in: .page) { result in + switch result { + case .success(let value): + cmuxDebugLog("browser.webext.popupProbe \(value ?? "nil")") + case .failure(let error): + cmuxDebugLog("browser.webext.popupProbe error=\(error.localizedDescription)") + } + } + } + } +#endif + + func webExtensionController( + _ controller: WKWebExtensionController, + sendMessage message: Any, + toApplicationWithIdentifier applicationIdentifier: String?, + for extensionContext: WKWebExtensionContext, + replyHandler: @escaping (Any?, Error?) -> Void + ) { + // Native messaging (e.g. Bitwarden's desktop-app biometrics IPC) is not + // bridged. Never resolve the reply: an error reply sends Bitwarden into + // an unthrottled reconnect loop (observed ~175k messages/sec), while an + // unresolved promise parks the caller harmlessly. + nativeMessageDropCount += 1 + if nativeMessageDropCount <= 5 { +#if DEBUG + cmuxDebugLog( + "browser.webext.nativeMessage dropped app=\(applicationIdentifier ?? "nil") " + + "count=\(nativeMessageDropCount)" + ) +#endif + } + _ = replyHandler + } + + func webExtensionController( + _ controller: WKWebExtensionController, + connectUsing port: WKWebExtension.MessagePort, + for extensionContext: WKWebExtensionContext, + completionHandler: @escaping (Error?) -> Void + ) { + // See sendMessage above: leave the native port unresolved rather than + // erroring, so extensions do not retry-loop. +#if DEBUG + cmuxDebugLog("browser.webext.nativeConnect dropped app=\(port.applicationIdentifier ?? "nil")") +#endif + _ = completionHandler + } + + func webExtensionController( + _ controller: WKWebExtensionController, + promptForPermissions permissions: Set, + in tab: (any WKWebExtensionTab)?, + for extensionContext: WKWebExtensionContext, + completionHandler: @escaping (Set, Date?) -> Void + ) { + completionHandler(permissions, nil) + } + + func webExtensionController( + _ controller: WKWebExtensionController, + promptForPermissionToAccess urls: Set, + in tab: (any WKWebExtensionTab)?, + for extensionContext: WKWebExtensionContext, + completionHandler: @escaping (Set, Date?) -> Void + ) { + completionHandler(urls, nil) + } + + func webExtensionController( + _ controller: WKWebExtensionController, + promptForPermissionMatchPatterns matchPatterns: Set, + in tab: (any WKWebExtensionTab)?, + for extensionContext: WKWebExtensionContext, + completionHandler: @escaping (Set, Date?) -> Void + ) { + completionHandler(matchPatterns, nil) + } +} diff --git a/Sources/Panels/BrowserWebExtensionTabAdapter.swift b/Sources/Panels/BrowserWebExtensionTabAdapter.swift new file mode 100644 index 000000000000..579ec07e3c1e --- /dev/null +++ b/Sources/Panels/BrowserWebExtensionTabAdapter.swift @@ -0,0 +1,78 @@ +import AppKit +import WebKit + +/// Presents one `BrowserPanel` to web extensions as a browser tab. +/// +/// All `WKWebExtensionTab` requirements are optional; this implements the subset +/// extensions like Bitwarden need to identify, read, and navigate the active tab. +@available(macOS 15.4, *) +@MainActor +final class BrowserWebExtensionTabAdapter: NSObject, WKWebExtensionTab { + private(set) weak var panel: BrowserPanel? + private weak var support: BrowserWebExtensionSupport? + private let panelID: UUID + + init(panel: BrowserPanel, support: BrowserWebExtensionSupport) { + self.panel = panel + self.support = support + self.panelID = panel.id + } + + func window(for context: WKWebExtensionContext) -> (any WKWebExtensionWindow)? { + support?.windowAdapter + } + + func indexInWindow(for context: WKWebExtensionContext) -> Int { + support?.indexInWindow(of: panelID) ?? 0 + } + + func webView(for context: WKWebExtensionContext) -> WKWebView? { + panel?.webView + } + + func url(for context: WKWebExtensionContext) -> URL? { + panel?.webView.url + } + + func title(for context: WKWebExtensionContext) -> String? { + panel?.webView.title + } + + func isLoadingComplete(for context: WKWebExtensionContext) -> Bool { + guard let webView = panel?.webView else { return true } + return !webView.isLoading + } + + func isSelected(for context: WKWebExtensionContext) -> Bool { + support?.activePanelID == panelID + } + + func activate(for context: WKWebExtensionContext, completionHandler: @escaping (Error?) -> Void) { + support?.noteActivated(panelID: panelID) + completionHandler(nil) + } + + func loadURL(_ url: URL, for context: WKWebExtensionContext, completionHandler: @escaping (Error?) -> Void) { + panel?.webView.load(URLRequest(url: url)) + completionHandler(nil) + } + + func reload(fromOrigin: Bool, for context: WKWebExtensionContext, completionHandler: @escaping (Error?) -> Void) { + if fromOrigin { + panel?.webView.reloadFromOrigin() + } else { + panel?.webView.reload() + } + completionHandler(nil) + } + + func goBack(for context: WKWebExtensionContext, completionHandler: @escaping (Error?) -> Void) { + panel?.webView.goBack() + completionHandler(nil) + } + + func goForward(for context: WKWebExtensionContext, completionHandler: @escaping (Error?) -> Void) { + panel?.webView.goForward() + completionHandler(nil) + } +} diff --git a/Sources/Panels/BrowserWebExtensionToolbarButtons.swift b/Sources/Panels/BrowserWebExtensionToolbarButtons.swift new file mode 100644 index 000000000000..528dc0eef0a1 --- /dev/null +++ b/Sources/Panels/BrowserWebExtensionToolbarButtons.swift @@ -0,0 +1,98 @@ +import AppKit +import SwiftUI +import WebKit + +/// Toolbar buttons for loaded web extensions: one button per extension action, +/// anchored so the extension's popup (e.g. the Bitwarden vault) opens beneath it. +@available(macOS 15.4, *) +struct BrowserWebExtensionToolbarButtons: View { + @ObservedObject var support: BrowserWebExtensionSupport + let panel: BrowserPanel + let iconPointSize: CGFloat + let hitSize: CGFloat + + var body: some View { + ForEach(Array(support.contexts.enumerated()), id: \.offset) { _, context in + BrowserWebExtensionActionButton( + support: support, + context: context, + panel: panel, + iconPointSize: iconPointSize, + hitSize: hitSize + ) + } + } +} + +@available(macOS 15.4, *) +private struct BrowserWebExtensionActionButton: View { + let support: BrowserWebExtensionSupport + let context: WKWebExtensionContext + let panel: BrowserPanel + let iconPointSize: CGFloat + let hitSize: CGFloat + + @State private var anchorViewHolder = BrowserWebExtensionAnchorViewHolder() + + var body: some View { + Button(action: { +#if DEBUG + cmuxDebugLog( + "browser.webext.action panel=\(panel.id.uuidString.prefix(5)) " + + "name=\(context.webExtension.displayName ?? "?")" + ) +#endif + support.performAction(context: context, panel: panel, anchorView: anchorViewHolder.view) + }) { + actionIcon + .frame(width: hitSize, height: hitSize, alignment: .center) + .contentShape(Rectangle()) + } + .buttonStyle(OmnibarAddressButtonStyle()) + .background(BrowserWebExtensionAnchorViewReader(holder: anchorViewHolder)) + .safeHelp(context.webExtension.displayName ?? String( + localized: "browser.webExtension.action.help", + defaultValue: "Extension" + )) + .accessibilityIdentifier("BrowserWebExtensionActionButton") + } + + @ViewBuilder + private var actionIcon: some View { + if let icon = context.webExtension.icon(for: CGSize(width: 32, height: 32)) { + Image(nsImage: icon) + .resizable() + .aspectRatio(contentMode: .fit) + .frame(width: iconPointSize + 3, height: iconPointSize + 3) + } else { + CmuxSystemSymbolImage( + systemName: "puzzlepiece.extension", + pointSize: iconPointSize, + weight: .medium + ) + } + } +} + +/// Captures the hosting `NSView` behind a SwiftUI button so an `NSPopover` +/// (the extension action popup) can anchor to it. +@available(macOS 15.4, *) +@MainActor +private final class BrowserWebExtensionAnchorViewHolder { + weak var view: NSView? +} + +@available(macOS 15.4, *) +private struct BrowserWebExtensionAnchorViewReader: NSViewRepresentable { + let holder: BrowserWebExtensionAnchorViewHolder + + func makeNSView(context: Context) -> NSView { + let view = NSView() + holder.view = view + return view + } + + func updateNSView(_ nsView: NSView, context: Context) { + holder.view = nsView + } +} diff --git a/Sources/Panels/BrowserWebExtensionWindowAdapter.swift b/Sources/Panels/BrowserWebExtensionWindowAdapter.swift new file mode 100644 index 000000000000..ebe4eb324031 --- /dev/null +++ b/Sources/Panels/BrowserWebExtensionWindowAdapter.swift @@ -0,0 +1,54 @@ +import AppKit +import WebKit + +/// Presents cmux's browser panels to web extensions as a single browser window. +/// +/// cmux has no traditional tab strip — browser panels live in panes across +/// workspaces — so all live panels are exposed as tabs of one focused window, +/// which is the topology extensions like Bitwarden expect for +/// `tabs.query({active: true, currentWindow: true})`. +@available(macOS 15.4, *) +@MainActor +final class BrowserWebExtensionWindowAdapter: NSObject, WKWebExtensionWindow { + private weak var support: BrowserWebExtensionSupport? + + init(support: BrowserWebExtensionSupport) { + self.support = support + } + + func tabs(for context: WKWebExtensionContext) -> [any WKWebExtensionTab] { + support?.orderedTabAdapters ?? [] + } + + func activeTab(for context: WKWebExtensionContext) -> (any WKWebExtensionTab)? { + support?.activeTabAdapter + } + + func windowType(for context: WKWebExtensionContext) -> WKWebExtension.WindowType { + .normal + } + + func windowState(for context: WKWebExtensionContext) -> WKWebExtension.WindowState { + .normal + } + + func isPrivate(for context: WKWebExtensionContext) -> Bool { + false + } + + func frame(for context: WKWebExtensionContext) -> CGRect { + hostWindow?.frame ?? .null + } + + func screenFrame(for context: WKWebExtensionContext) -> CGRect { + hostWindow?.screen?.frame ?? NSScreen.main?.frame ?? .null + } + + func focus(for context: WKWebExtensionContext, completionHandler: @escaping (Error?) -> Void) { + completionHandler(nil) + } + + private var hostWindow: NSWindow? { + support?.activeTabAdapter?.panel?.webView.window ?? NSApp.keyWindow + } +} diff --git a/Sources/Panels/CmuxWebView.swift b/Sources/Panels/CmuxWebView.swift index d251881fa2c2..9a235539a9da 100644 --- a/Sources/Panels/CmuxWebView.swift +++ b/Sources/Panels/CmuxWebView.swift @@ -699,6 +699,13 @@ final class CmuxWebView: WKWebView { return finish(super.performKeyEquivalent(with: event)) } + // Web-extension commands (e.g. Bitwarden's ⌘⇧L autofill) match only + // shortcuts the extension manifest declares; everything else falls through. + if #available(macOS 15.4, *), + BrowserWebExtensionSupport.shared.performCommand(for: event) { + return finish(true) + } + if Self.isPasteAsPlainTextCommandEquivalent(event) { if event.timestamp > 0 { lastPasteAsPlainTextPerformKeyEventTimestamp = event.timestamp diff --git a/Sources/Workspace.swift b/Sources/Workspace.swift index e6a2068b0d57..06e8ff1f61b8 100644 --- a/Sources/Workspace.swift +++ b/Sources/Workspace.swift @@ -9540,6 +9540,9 @@ final class Workspace: Identifiable, ObservableObject { ) { guard !remoteTmuxMirrorMutations.suppressesFocusActivation else { return } markExplicitFocusIntent(on: panelId) + if #available(macOS 15.4, *), panels[panelId] is BrowserPanel { + BrowserWebExtensionSupport.shared.noteActivated(panelID: panelId) + } #if DEBUG let pane = bonsplitController.focusedPaneId?.id.uuidString.prefix(5) ?? "nil" let triggerLabel = trigger == .terminalFirstResponder ? "firstResponder" : "standard" diff --git a/cmux.xcodeproj/project.pbxproj b/cmux.xcodeproj/project.pbxproj index a3f3a30f2daa..7c1c3035be70 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -310,6 +310,11 @@ C0DE71B10000000000000001 /* AppDelegate+AgentChatNotifications.swift in Sources A50100000000000000000020 /* BrowserWebAuthnTransportSummary.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5010000000000000000001F /* BrowserWebAuthnTransportSummary.swift */; }; A50100000000000000000022 /* BrowserWebAuthnUserDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = A50100000000000000000021 /* BrowserWebAuthnUserDescriptor.swift */; }; C0DE49870000000000000001 /* BrowserWebContentProcessTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE49870000000000000002 /* BrowserWebContentProcessTests.swift */; }; + B1CFE0050000000000000001 /* BrowserWebExtensionPopoutWindowController.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1CFE0050000000000000002 /* BrowserWebExtensionPopoutWindowController.swift */; }; + B1CFE0010000000000000001 /* BrowserWebExtensionSupport.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1CFE0010000000000000002 /* BrowserWebExtensionSupport.swift */; }; + B1CFE0020000000000000001 /* BrowserWebExtensionTabAdapter.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1CFE0020000000000000002 /* BrowserWebExtensionTabAdapter.swift */; }; + B1CFE0040000000000000001 /* BrowserWebExtensionToolbarButtons.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1CFE0040000000000000002 /* BrowserWebExtensionToolbarButtons.swift */; }; + B1CFE0030000000000000001 /* BrowserWebExtensionWindowAdapter.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1CFE0030000000000000002 /* BrowserWebExtensionWindowAdapter.swift */; }; C0DE58990000000000000003 /* BrowserWebKitKeyDownDispatch.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE58990000000000000001 /* BrowserWebKitKeyDownDispatch.swift */; }; A5001534 /* BrowserWindowPortal.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5001533 /* BrowserWindowPortal.swift */; }; B1F0C00A0000000000000001 /* BrowserWindowPortalInspectorLayout.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1F0C00A0000000000000002 /* BrowserWindowPortalInspectorLayout.swift */; }; @@ -2069,6 +2074,11 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = A5010000000000000000001F /* BrowserWebAuthnTransportSummary.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/BrowserWebAuthnTransportSummary.swift; sourceTree = ""; }; A50100000000000000000021 /* BrowserWebAuthnUserDescriptor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/BrowserWebAuthnUserDescriptor.swift; sourceTree = ""; }; C0DE49870000000000000002 /* BrowserWebContentProcessTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BrowserWebContentProcessTests.swift; sourceTree = ""; }; + B1CFE0050000000000000002 /* BrowserWebExtensionPopoutWindowController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/BrowserWebExtensionPopoutWindowController.swift; sourceTree = ""; }; + B1CFE0010000000000000002 /* BrowserWebExtensionSupport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/BrowserWebExtensionSupport.swift; sourceTree = ""; }; + B1CFE0020000000000000002 /* BrowserWebExtensionTabAdapter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/BrowserWebExtensionTabAdapter.swift; sourceTree = ""; }; + B1CFE0040000000000000002 /* BrowserWebExtensionToolbarButtons.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/BrowserWebExtensionToolbarButtons.swift; sourceTree = ""; }; + B1CFE0030000000000000002 /* BrowserWebExtensionWindowAdapter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/BrowserWebExtensionWindowAdapter.swift; sourceTree = ""; }; C0DE58990000000000000001 /* BrowserWebKitKeyDownDispatch.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/BrowserWebKitKeyDownDispatch.swift; sourceTree = ""; }; A5001533 /* BrowserWindowPortal.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BrowserWindowPortal.swift; sourceTree = ""; }; B1F0C00A0000000000000002 /* BrowserWindowPortalInspectorLayout.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BrowserWindowPortalInspectorLayout.swift; sourceTree = ""; }; @@ -4284,6 +4294,11 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = C67540080000000000000002 /* BrowserNavigationDebugURL.swift */, C67540110000000000000002 /* BrowserDownloadRecord.swift */, C67540120000000000000002 /* BrowserDownloadsToolbarButton.swift */, + B1CFE0040000000000000002 /* BrowserWebExtensionToolbarButtons.swift */, + B1CFE0030000000000000002 /* BrowserWebExtensionWindowAdapter.swift */, + B1CFE0020000000000000002 /* BrowserWebExtensionTabAdapter.swift */, + B1CFE0010000000000000002 /* BrowserWebExtensionSupport.swift */, + B1CFE0050000000000000002 /* BrowserWebExtensionPopoutWindowController.swift */, C67540100000000000000002 /* BrowserNavigationPopupPolicy.swift */, A5001412 /* BrowserPanel.swift */, B1F0C0090000000000000002 /* BrowserPanelDeveloperToolsLifecycle.swift */, @@ -5841,6 +5856,11 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = A5010000000000000000001E /* BrowserWebAuthnTransport.swift in Sources */, A50100000000000000000020 /* BrowserWebAuthnTransportSummary.swift in Sources */, A50100000000000000000022 /* BrowserWebAuthnUserDescriptor.swift in Sources */, + B1CFE0050000000000000001 /* BrowserWebExtensionPopoutWindowController.swift in Sources */, + B1CFE0010000000000000001 /* BrowserWebExtensionSupport.swift in Sources */, + B1CFE0020000000000000001 /* BrowserWebExtensionTabAdapter.swift in Sources */, + B1CFE0040000000000000001 /* BrowserWebExtensionToolbarButtons.swift in Sources */, + B1CFE0030000000000000001 /* BrowserWebExtensionWindowAdapter.swift in Sources */, C0DE58990000000000000003 /* BrowserWebKitKeyDownDispatch.swift in Sources */, A5001534 /* BrowserWindowPortal.swift in Sources */, B1F0C00A0000000000000001 /* BrowserWindowPortalInspectorLayout.swift in Sources */, From f6bd395e9be9e35ff3b91c4673822b27f7774609 Mon Sep 17 00:00:00 2001 From: Kylo Jorgensen Date: Wed, 8 Jul 2026 22:45:48 -0600 Subject: [PATCH 02/51] fix(browser): address review findings on web-extension support MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Fire didActivateTab for the successor tab when the active browser panel closes, so extensions don't keep acting on the closed tab. - Register the extension popout window as a cmux auxiliary window (stable cmux.webExtensionPopout identifier) so ⌘W and the shared close-shortcut routing target it instead of workspace panels. - Center the popout whenever the fallback size is applied, not only for null/empty frames (small non-empty frames previously landed at 0,0). - Localize the popout window's fallback title. - Remove the timing-based debug probes (popup API probe, autoprobe, delayed re-diagnostic, per-keystroke unmatched-command log); the one-shot post-load diagnostic remains. Co-Authored-By: Claude Fable 5 --- ...erWebExtensionPopoutWindowController.swift | 13 ++- .../Panels/BrowserWebExtensionSupport.swift | 92 ++----------------- Sources/cmuxApp.swift | 1 + 3 files changed, 19 insertions(+), 87 deletions(-) diff --git a/Sources/Panels/BrowserWebExtensionPopoutWindowController.swift b/Sources/Panels/BrowserWebExtensionPopoutWindowController.swift index 7f6d44d7d00f..ee0dbf5153aa 100644 --- a/Sources/Panels/BrowserWebExtensionPopoutWindowController.swift +++ b/Sources/Panels/BrowserWebExtensionPopoutWindowController.swift @@ -30,7 +30,8 @@ final class BrowserWebExtensionPopoutWindowController: NSObject, WKWebExtensionW webView.isInspectable = true var frame = configuration.frame - if frame.isNull || frame.isEmpty || frame.width < 50 || frame.height < 50 { + let usesFallbackFrame = frame.isNull || frame.isEmpty || frame.width < 50 || frame.height < 50 + if usesFallbackFrame { frame = CGRect(origin: .zero, size: Self.defaultSize) } window = NSWindow( @@ -39,16 +40,22 @@ final class BrowserWebExtensionPopoutWindowController: NSObject, WKWebExtensionW backing: .buffered, defer: false ) + // Standalone closable window: the stable identifier opts it into the + // shared close-shortcut routing (cmuxWindowShouldOwnCloseShortcut). + window.identifier = NSUserInterfaceItemIdentifier("cmux.webExtensionPopout") window.isReleasedWhenClosed = false window.level = .floating window.contentView = webView - if configuration.frame.isNull || configuration.frame.isEmpty { + if usesFallbackFrame { window.center() } super.init() window.delegate = self - window.title = context.webExtension.displayName ?? "Extension" + window.title = context.webExtension.displayName ?? String( + localized: "browser.webExtension.action.help", + defaultValue: "Extension" + ) if let url = configuration.tabURLs.first { webView.load(URLRequest(url: url)) diff --git a/Sources/Panels/BrowserWebExtensionSupport.swift b/Sources/Panels/BrowserWebExtensionSupport.swift index 1a6e5bf51904..6d79e00fd5bc 100644 --- a/Sources/Panels/BrowserWebExtensionSupport.swift +++ b/Sources/Panels/BrowserWebExtensionSupport.swift @@ -120,18 +120,6 @@ final class BrowserWebExtensionSupport: NSObject, ObservableObject { contexts.append(context) #if DEBUG logDiagnostics(for: context, label: "postLoad") - Task { @MainActor [weak self] in - try? await Task.sleep(for: .seconds(5)) - self?.logDiagnostics(for: context, label: "postLoad+5s") - } - if ProcessInfo.processInfo.environment["CMUX_WEBEXT_AUTOPROBE"] == "1" { - Task { @MainActor [weak self] in - try? await Task.sleep(for: .seconds(8)) - guard let self else { return } - cmuxDebugLog("browser.webext.autoprobe performAction") - context.performAction(for: self.activeTabAdapter) - } - } #endif } @@ -188,8 +176,15 @@ final class BrowserWebExtensionSupport: NSObject, ObservableObject { func unregister(panelID: UUID) { guard let adapter = tabAdapters.removeValue(forKey: panelID) else { return } orderedPanelIDs.removeAll { $0 == panelID } - if activePanelID == panelID { activePanelID = orderedPanelIDs.last } controller.didCloseTab(adapter, windowIsClosing: false) + if activePanelID == panelID { + activePanelID = orderedPanelIDs.last + // Tell extensions which tab is active now, or they keep acting on + // the closed one until the next focus change. + if let successor = activePanelID.flatMap({ tabAdapters[$0] }) { + controller.didActivateTab(successor, previousActiveTab: adapter) + } + } } func noteActivated(panelID: UUID) { @@ -238,14 +233,6 @@ final class BrowserWebExtensionSupport: NSObject, ObservableObject { #endif return true } -#if DEBUG - if !contexts.isEmpty { - cmuxDebugLog( - "browser.webext.command unmatched key=\(event.charactersIgnoringModifiers ?? "?") " + - "mods=\(event.modifierFlags.intersection(.deviceIndependentFlagsMask).rawValue)" - ) - } -#endif return false } @@ -349,72 +336,9 @@ extension BrowserWebExtensionSupport: WKWebExtensionControllerDelegate { } popover.behavior = .transient popover.show(relativeTo: anchor.bounds, of: anchor, preferredEdge: .maxY) -#if DEBUG - if ProcessInfo.processInfo.environment["CMUX_WEBEXT_AUTOPROBE"] == "1", - let popupWebView = action.popupWebView { - probePopup(popupWebView) - } -#endif completionHandler(nil) } -#if DEBUG - /// Evaluates a WebExtension-API probe inside the action popup so tab/window - /// adapter behavior is observable from the extension's point of view. - /// Installs an error-capture hook and reloads the popup first so boot-time - /// console errors and unhandled rejections are observable. - private func probePopup(_ popupWebView: WKWebView) { - Task { @MainActor in - let hookSource = """ - window.__errs = []; - window.addEventListener("error", (e) => window.__errs.push("E:" + e.message + "@" + (e.filename || "") + ":" + (e.lineno || 0))); - window.addEventListener("unhandledrejection", (e) => window.__errs.push("R:" + ((e.reason && (e.reason.stack || e.reason.message)) || e.reason))); - const ce = console.error.bind(console); - console.error = (...a) => { window.__errs.push("C:" + a.map(String).join(" ").slice(0, 300)); ce(...a); }; - """ - popupWebView.configuration.userContentController.addUserScript( - WKUserScript(source: hookSource, injectionTime: .atDocumentStart, forMainFrameOnly: false) - ) - popupWebView.reload() - try? await Task.sleep(for: .seconds(5)) - let script = """ - try { - const api = globalThis.browser || globalThis.chrome; - const tabs = await api.tabs.query({ active: true, currentWindow: true }); - const wins = await api.windows.getAll(); - const win = await api.windows.getCurrent().catch((e) => 'ERR:' + e.message); - let popoutTest = "skipped"; - try { - const w = await api.windows.create({ url: "popup/index.html", type: "popup", width: 380, height: 500, focused: false }); - popoutTest = w ? "created:" + w.id + ":tabs=" + (w.tabs ? w.tabs.length : "?") : "null"; - if (w) { await new Promise(r => setTimeout(r, 1500)); await api.windows.remove(w.id); popoutTest += ":removed"; } - } catch (e) { popoutTest = "ERR:" + (e && e.message); } - return JSON.stringify({ - ready: document.readyState, - bodyChildren: document.body ? document.body.children.length : -1, - tabCount: tabs.length, - tab0: tabs[0] ? `${tabs[0].id}:${tabs[0].url || "nourl"}:${tabs[0].title || "notitle"}` : "none", - winCount: wins.length, - currentWin: typeof win === "string" ? win : (win ? win.id : "none"), - text: (document.body ? document.body.innerText : "").replace(/\\s+/g, " ").slice(0, 160), - html: (document.body ? document.body.innerHTML : "").replace(/\\s+/g, " ").slice(0, 240), - errs: (window.__errs || []).slice(0, 8), - popoutTest - }); - } catch (e) { return "ERR:" + (e && e.message); } - """ - popupWebView.callAsyncJavaScript(script, arguments: [:], in: nil, in: .page) { result in - switch result { - case .success(let value): - cmuxDebugLog("browser.webext.popupProbe \(value ?? "nil")") - case .failure(let error): - cmuxDebugLog("browser.webext.popupProbe error=\(error.localizedDescription)") - } - } - } - } -#endif - func webExtensionController( _ controller: WKWebExtensionController, sendMessage message: Any, diff --git a/Sources/cmuxApp.swift b/Sources/cmuxApp.swift index b389b39df611..4953c500ab83 100644 --- a/Sources/cmuxApp.swift +++ b/Sources/cmuxApp.swift @@ -1477,6 +1477,7 @@ private let cmuxAuxiliaryWindowIdentifiers: Set = [ "cmux.titlebarLayoutDebug", "cmux.devWindowDisplay", "cmux.mobilePairingWindow", + "cmux.webExtensionPopout", ] /// Returns whether the given window should handle the standard close shortcut From 8aa903082e992baab0e05a47d5743cd18b9f5e68 Mon Sep 17 00:00:00 2001 From: Kylo Jorgensen Date: Wed, 8 Jul 2026 22:15:38 -0600 Subject: [PATCH 03/51] feat(settings): browser extension management in Settings > Browser MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replaces the hardcoded Bitwarden path with a persisted, user-managed extension registry: - New browser.webExtensions JSONKey ([BrowserWebExtensionEntry]) in the CmuxSettings catalog; entries carry id/kind/path/enabled and fail closed on malformed config. - Extensions card in the Browser settings section: every Safari web extension installed on the Mac (discovered via pluginkit, the registry Safari itself consults) with an enable toggle, unpacked-directory entries with remove buttons, and an "Add Unpacked…" folder picker. - BrowserWebExtensionSupport now observes the JSON key from app startup and diffs desired vs. loaded: enabling loads live, disabling unloads live, and extensions begin loading before the first browser page navigates (shrinking the session-restore content-script race). - One-time migration seeds the Bitwarden entry when the desktop app is installed and no extensions were ever configured, so existing setups keep working; CMUX_BROWSER_EXTENSIONS env paths still merge in. - Curated settings-search entry ("extensions", "bitwarden", "addons") and localized strings for all 19 languages. Verified live: seeding wrote browser.webExtensions to cmux.json on first launch, Bitwarden loaded at startup, toggling enabled=false unloaded the extension within seconds and re-enabling reloaded it. Co-Authored-By: Claude Fable 5 --- .../Keys/BrowserCatalogSection.swift | 7 + .../Values/BrowserWebExtensionEntry.swift | 79 ++ .../SettingsDiscoveredBrowserExtension.swift | 30 + .../Environment/SettingsHostActions.swift | 14 + .../CuratedSettingEntry+Default.swift | 7 + .../Scene/SettingsWindowScene.swift | 2 + .../Sections/BrowserSection.swift | 15 + .../Sections/BrowserWebExtensionsCard.swift | 166 +++ Resources/Localizable.xcstrings | 1071 +++++++++++++++++ Sources/HostSettingsActions.swift | 18 + .../BrowserWebExtensionDiscoveryService.swift | 106 ++ .../Panels/BrowserWebExtensionSupport.swift | 124 +- Sources/cmuxApp.swift | 9 +- cmux.xcodeproj/project.pbxproj | 4 + 14 files changed, 1621 insertions(+), 31 deletions(-) create mode 100644 Packages/macOS/CmuxSettings/Sources/CmuxSettings/Values/BrowserWebExtensionEntry.swift create mode 100644 Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Environment/SettingsDiscoveredBrowserExtension.swift create mode 100644 Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift create mode 100644 Sources/Panels/BrowserWebExtensionDiscoveryService.swift diff --git a/Packages/macOS/CmuxSettings/Sources/CmuxSettings/Keys/BrowserCatalogSection.swift b/Packages/macOS/CmuxSettings/Sources/CmuxSettings/Keys/BrowserCatalogSection.swift index 353dbfb0e080..52b45d5a32fd 100644 --- a/Packages/macOS/CmuxSettings/Sources/CmuxSettings/Keys/BrowserCatalogSection.swift +++ b/Packages/macOS/CmuxSettings/Sources/CmuxSettings/Keys/BrowserCatalogSection.swift @@ -116,5 +116,12 @@ public struct BrowserCatalogSection: SettingCatalogSection { userDefaultsKey: "browserImportHintDismissed" ) + /// Web extensions configured for the built-in browser (macOS 15.4+). + /// See ``BrowserWebExtensionEntry``; only `enabled` entries load. + public let webExtensions = JSONKey<[BrowserWebExtensionEntry]>( + id: "browser.webExtensions", + defaultValue: [] + ) + public init() {} } diff --git a/Packages/macOS/CmuxSettings/Sources/CmuxSettings/Values/BrowserWebExtensionEntry.swift b/Packages/macOS/CmuxSettings/Sources/CmuxSettings/Values/BrowserWebExtensionEntry.swift new file mode 100644 index 000000000000..0647d703dd34 --- /dev/null +++ b/Packages/macOS/CmuxSettings/Sources/CmuxSettings/Values/BrowserWebExtensionEntry.swift @@ -0,0 +1,79 @@ +import Foundation + +/// One web extension the user has configured for the built-in browser, stored +/// under `browser.webExtensions` in `cmux.json`. +/// +/// Extensions come from two places: Safari web extensions installed on this +/// Mac inside another app's bundle (discovered automatically), and unpacked +/// WebExtension directories the user added by hand. Only entries with +/// ``enabled`` set actually load; discovered-but-untouched extensions have no +/// entry at all. +/// +/// ```swift +/// BrowserWebExtensionEntry( +/// id: "com.bitwarden.desktop.safari", +/// kind: .safariAppExtension, +/// path: "/Applications/Bitwarden.app/Contents/PlugIns/safari.appex", +/// enabled: true +/// ) +/// ``` +public struct BrowserWebExtensionEntry: Codable, Sendable, Equatable, Hashable, Identifiable { + /// Where the extension's resources come from. + public enum Kind: String, Codable, Sendable { + /// A Safari web extension `.appex` bundled inside an installed app. + case safariAppExtension + /// A directory containing an unpacked WebExtension (`manifest.json` at + /// its root), Chrome/Firefox load-unpacked style. + case unpackedDirectory + } + + /// Stable identity: the appex plug-in identifier for Safari extensions, or + /// the directory path for unpacked ones. + public var id: String + /// Where the extension's resources come from. + public var kind: Kind + /// Absolute path to the `.appex` bundle or unpacked directory. + public var path: String + /// Whether the extension loads into the browser. + public var enabled: Bool + + /// - Parameters: + /// - id: Stable identity (appex plug-in identifier, or directory path). + /// - kind: Where the extension's resources come from. + /// - path: Absolute path to the `.appex` bundle or unpacked directory. + /// - enabled: Whether the extension loads into the browser. + public init(id: String, kind: Kind, path: String, enabled: Bool) { + self.id = id + self.kind = kind + self.path = path + self.enabled = enabled + } +} + +// MARK: - SettingCodable + +/// Stored as a nested JSON object; a malformed entry is rejected (decodes to +/// `nil`) rather than partially applied, so bad config fails closed. +extension BrowserWebExtensionEntry: SettingCodable { + public static func decodeFromUserDefaults(_ raw: Any?) -> BrowserWebExtensionEntry? { + decodeFromJSON(raw) + } + + public func encodeForUserDefaults() -> Any { + encodeForJSON() + } + + public static func decodeFromJSON(_ raw: Any?) -> BrowserWebExtensionEntry? { + guard let object = raw as? [String: Any] else { return nil } + guard let data = try? JSONSerialization.data(withJSONObject: object) else { return nil } + return try? JSONDecoder().decode(BrowserWebExtensionEntry.self, from: data) + } + + public func encodeForJSON() -> Any { + guard let data = try? JSONEncoder().encode(self), + let object = try? JSONSerialization.jsonObject(with: data) else { + return NSNull() + } + return object + } +} diff --git a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Environment/SettingsDiscoveredBrowserExtension.swift b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Environment/SettingsDiscoveredBrowserExtension.swift new file mode 100644 index 000000000000..063a60e5bb7c --- /dev/null +++ b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Environment/SettingsDiscoveredBrowserExtension.swift @@ -0,0 +1,30 @@ +import Foundation + +/// A Safari web extension found installed on this Mac, as reported by the +/// host through ``SettingsHostActions/discoverBrowserWebExtensions()``. +/// +/// This is display metadata only; the persisted setting is +/// `BrowserWebExtensionEntry` in the catalog. `id` matches the entry's `id` +/// (the appex plug-in identifier) so the Browser section can join the two. +public struct SettingsDiscoveredBrowserExtension: Sendable, Identifiable, Equatable { + /// The appex plug-in identifier (e.g. `com.bitwarden.desktop.safari`). + public let id: String + /// Human-readable name resolved from the extension bundle, if available. + public let displayName: String? + /// The extension's version string, if available. + public let version: String? + /// Absolute path to the `.appex` bundle. + public let path: String + + /// - Parameters: + /// - id: The appex plug-in identifier. + /// - displayName: Human-readable name from the extension bundle. + /// - version: The extension's version string. + /// - path: Absolute path to the `.appex` bundle. + public init(id: String, displayName: String?, version: String?, path: String) { + self.id = id + self.displayName = displayName + self.version = version + self.path = path + } +} diff --git a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Environment/SettingsHostActions.swift b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Environment/SettingsHostActions.swift index 3b8e3be3dae4..ab6cc52904bb 100644 --- a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Environment/SettingsHostActions.swift +++ b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Environment/SettingsHostActions.swift @@ -171,6 +171,14 @@ public protocol SettingsHostActions: AnyObject { /// Applies the host-side OS `AppleLanguages` override for a changed app /// language selection. func applyLanguageOverride(_ language: AppLanguage) + + /// Lists Safari web extensions installed on this Mac (the same registry + /// Safari consults), for the Browser section's extensions list. The host + /// applies `browser.webExtensions` changes itself by observing the key. + func discoverBrowserWebExtensions() async -> [SettingsDiscoveredBrowserExtension] + + /// Whether the host can load web extensions at all (requires macOS 15.4+). + func browserWebExtensionsSupported() -> Bool } public extension SettingsHostActions { @@ -183,6 +191,12 @@ public extension SettingsHostActions { /// Default no-op for package previews and tests without app-language ownership. func applyLanguageOverride(_ language: AppLanguage) {} + /// Default: nothing discovered, for previews/tests with no live host. + func discoverBrowserWebExtensions() async -> [SettingsDiscoveredBrowserExtension] { [] } + + /// Default: unsupported, for previews/tests with no live host. + func browserWebExtensionsSupported() -> Bool { false } + func openMobilePairingWindow() {} /// Default no-op preview action for hosts without a Sleepy Mode overlay. diff --git a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Navigation/CuratedSettingEntry+Default.swift b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Navigation/CuratedSettingEntry+Default.swift index 678fbf75b66d..7eb9430d72b5 100644 --- a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Navigation/CuratedSettingEntry+Default.swift +++ b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Navigation/CuratedSettingEntry+Default.swift @@ -243,6 +243,13 @@ extension Array where Element == CuratedSettingEntry { .init(section: .browser, id: "http-allowlist", title: "HTTP Hosts Allowed in Embedded Browser", synonyms: "browser.insecureHttpHostsAllowedInEmbeddedBrowser insecure http allowlist localhost localtest non-https warning"), .init(section: .browser, id: "react-grab", title: "React Grab Version", synonyms: "browser.reactGrabVersion react grab npm version toolbar cmd-shift-g inspect component"), .init(section: .browser, id: "history", title: "Browsing History", synonyms: "browsing history clear visited pages omnibar suggestions delete"), + .init( + section: .browser, + id: "web-extensions", + title: String(localized: "settings.browser.webExtensions", defaultValue: "Extensions"), + detailText: String(localized: "settings.browser.webExtensions.subtitle", defaultValue: "Safari web extensions from installed apps, or unpacked extension folders."), + synonyms: String(localized: "settings.search.alias.setting.browser.web-extensions", defaultValue: "browser.webExtensions extensions addons plugins bitwarden 1password adguard password manager safari web extension unpacked load") + ), // Browser import .init(section: .browserImport, id: "import-data", title: "Import Browser Data", synonyms: "chrome safari firefox brave edge arc bookmarks history cookies profiles migration"), diff --git a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Scene/SettingsWindowScene.swift b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Scene/SettingsWindowScene.swift index eead0c7f036d..00091e442887 100644 --- a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Scene/SettingsWindowScene.swift +++ b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Scene/SettingsWindowScene.swift @@ -473,8 +473,10 @@ public struct SettingsWindowRoot: View { BrowserSection( defaultsStore: defaultsStore, + jsonStore: jsonStore, catalog: catalog, hostActions: hostActions, + errorLog: runtime.errorLog, importAnchorID: anchorID(for: .browserImport) ) .id(anchorID(for: .browser)) diff --git a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserSection.swift b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserSection.swift index 9c38b72bbe78..2cb2b61dcc47 100644 --- a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserSection.swift +++ b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserSection.swift @@ -39,15 +39,25 @@ public struct BrowserSection: View { @State private var httpAllowlistSyncedValue: String = "" @State private var httpAllowlistLoaded: Bool = false + @State private var webExtensions: JSONValueModel<[BrowserWebExtensionEntry]> + @State private var discoveredWebExtensions: [SettingsDiscoveredBrowserExtension] = [] + public init( defaultsStore: UserDefaultsSettingsStore, + jsonStore: JSONConfigStore, catalog: SettingCatalog, hostActions: SettingsHostActions, + errorLog: SettingsErrorLog, importAnchorID: String? = nil ) { self.catalog = catalog self.hostActions = hostActions self.importAnchorID = importAnchorID + _webExtensions = State(initialValue: JSONValueModel( + store: jsonStore, + key: catalog.browser.webExtensions, + errorLog: errorLog + )) _disabled = State(initialValue: DefaultsValueModel(store: defaultsStore, key: catalog.browser.disabled)) _engine = State(initialValue: DefaultsValueModel(store: defaultsStore, key: catalog.browser.defaultSearchEngine)) _customName = State(initialValue: DefaultsValueModel(store: defaultsStore, key: catalog.browser.customSearchEngineName)) @@ -73,6 +83,7 @@ public struct BrowserSection: View { SettingsSectionHeader(String(localized: "settings.section.browser", defaultValue: "Browser"), section: .browser) .accessibilityIdentifier("SettingsBrowserSection") mainCard + webExtensionsCard } .confirmationDialog( String(localized: "settings.browser.history.clearDialog.title", defaultValue: "Clear browser history?"), @@ -88,6 +99,10 @@ public struct BrowserSection: View { }.task { startSettingsObservation([disabled, engine, customName, customURL, suggestions, theme, discardEnabled, discardDelay, askWhereToSaveDownloads, openTermLinks, interceptOpen, hosts, external, httpAllowlist, importHint, reactGrab]) } } + private var webExtensionsCard: some View { + BrowserWebExtensionsCard(model: webExtensions, hostActions: hostActions) + } + @ViewBuilder private var mainCard: some View { SettingsCard { diff --git a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift new file mode 100644 index 000000000000..d327c53dca36 --- /dev/null +++ b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift @@ -0,0 +1,166 @@ +import AppKit +import CmuxSettings +import SwiftUI +import UniformTypeIdentifiers + +/// **Extensions** card in the Browser section. +/// +/// Lists Safari web extensions installed on this Mac (discovered through the +/// host) and unpacked WebExtension directories the user added, each with an +/// enable toggle. State persists under `browser.webExtensions`; the host +/// observes that key and loads/unloads extensions live. +@MainActor +struct BrowserWebExtensionsCard: View { + let model: JSONValueModel<[BrowserWebExtensionEntry]> + let hostActions: SettingsHostActions + + @State private var discovered: [SettingsDiscoveredBrowserExtension] = [] + + var body: some View { + SettingsCard { + headerRow + if supported { + ForEach(discovered) { candidate in + SettingsCardDivider() + discoveredRow(candidate) + } + ForEach(unpackedEntries) { entry in + SettingsCardDivider() + unpackedRow(entry) + } + if discovered.isEmpty && unpackedEntries.isEmpty { + SettingsCardDivider() + emptyRow + } + } + } + .task { + model.startObserving() + discovered = await hostActions.discoverBrowserWebExtensions() + } + } + + private var supported: Bool { + hostActions.browserWebExtensionsSupported() + } + + private var unpackedEntries: [BrowserWebExtensionEntry] { + model.current.filter { $0.kind == .unpackedDirectory } + } + + private var headerRow: some View { + SettingsCardRow( + configurationReview: .json("browser.webExtensions"), + searchAnchorID: "setting:browser:web-extensions", + String(localized: "settings.browser.webExtensions", defaultValue: "Extensions"), + subtitle: supported + ? String( + localized: "settings.browser.webExtensions.subtitle", + defaultValue: "Safari web extensions from installed apps, or unpacked extension folders." + ) + : String( + localized: "settings.browser.webExtensions.unsupported", + defaultValue: "Web extensions require macOS 15.4 or later." + ) + ) { + Button(String( + localized: "settings.browser.webExtensions.addUnpacked", + defaultValue: "Add Unpacked…" + )) { + addUnpackedExtension() + } + .controlSize(.small) + .disabled(!supported) + .accessibilityIdentifier("BrowserWebExtensionsAddUnpackedButton") + } + } + + private var emptyRow: some View { + SettingsCardRow( + configurationReview: .settingsOnly, + String( + localized: "settings.browser.webExtensions.empty", + defaultValue: "No Safari web extensions found on this Mac" + ), + subtitle: String( + localized: "settings.browser.webExtensions.empty.subtitle", + defaultValue: "Install an app that bundles one (Bitwarden, AdGuard, …) or add an unpacked extension folder." + ) + ) { + EmptyView() + } + } + + private func discoveredRow(_ candidate: SettingsDiscoveredBrowserExtension) -> some View { + SettingsCardRow( + configurationReview: .json("browser.webExtensions"), + candidate.displayName ?? candidate.id, + subtitle: candidate.version.map { "\(candidate.id) · \($0)" } ?? candidate.id + ) { + Toggle("", isOn: Binding( + get: { isEnabled(candidate.id) }, + set: { setEnabled($0, id: candidate.id, kind: .safariAppExtension, path: candidate.path) } + )) + .labelsHidden() + .controlSize(.small) + .accessibilityIdentifier("BrowserWebExtensionToggle-\(candidate.id)") + } + } + + private func unpackedRow(_ entry: BrowserWebExtensionEntry) -> some View { + SettingsCardRow( + configurationReview: .json("browser.webExtensions"), + (entry.path as NSString).lastPathComponent, + subtitle: entry.path + ) { + HStack(spacing: 8) { + Toggle("", isOn: Binding( + get: { isEnabled(entry.id) }, + set: { setEnabled($0, id: entry.id, kind: .unpackedDirectory, path: entry.path) } + )) + .labelsHidden() + .controlSize(.small) + Button(String( + localized: "settings.browser.webExtensions.remove", + defaultValue: "Remove" + )) { + remove(id: entry.id) + } + .controlSize(.small) + } + } + } + + private func isEnabled(_ id: String) -> Bool { + model.current.first { $0.id == id }?.enabled ?? false + } + + private func setEnabled(_ enabled: Bool, id: String, kind: BrowserWebExtensionEntry.Kind, path: String) { + var entries = model.current + if let index = entries.firstIndex(where: { $0.id == id }) { + entries[index].enabled = enabled + entries[index].path = path + } else { + entries.append(BrowserWebExtensionEntry(id: id, kind: kind, path: path, enabled: enabled)) + } + model.set(entries) + } + + private func remove(id: String) { + model.set(model.current.filter { $0.id != id }) + } + + private func addUnpackedExtension() { + let panel = NSOpenPanel() + panel.canChooseFiles = false + panel.canChooseDirectories = true + panel.allowsMultipleSelection = false + panel.message = String( + localized: "settings.browser.webExtensions.addUnpacked.message", + defaultValue: "Choose a folder containing an unpacked web extension (manifest.json at its root)." + ) + guard panel.runModal() == .OK, let url = panel.url else { return } + let path = url.path + setEnabled(true, id: path, kind: .unpackedDirectory, path: path) + } +} diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index 118fc58f644b..18c0b8f497f6 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -44932,6 +44932,958 @@ } } }, + "settings.browser.webExtensions": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "الملحقات" + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "Ekstenzije" + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "Udvidelser" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Erweiterungen" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Extensions" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Extensiones" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Extensions" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Estensioni" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "拡張機能" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "확장 프로그램" + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "Utvidelser" + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "Rozszerzenia" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Extensões" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Расширения" + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "ส่วนขยาย" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Uzantılar" + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "Розширення" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "扩展" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "延伸功能" + } + } + } + }, + "settings.browser.webExtensions.addUnpacked": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "إضافة غير مضغوط…" + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "Dodaj raspakovano…" + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "Tilføj udpakket…" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Entpackte hinzufügen…" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Add Unpacked…" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Añadir descomprimida…" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Ajouter décompressée…" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Aggiungi non pacchettizzata…" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "展開済みを追加…" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "압축 해제된 항목 추가…" + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "Legg til utpakket…" + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "Dodaj rozpakowane…" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Adicionar descompactada…" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Добавить распакованное…" + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "เพิ่มที่แตกไฟล์แล้ว…" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Paketten Çıkarılmış Ekle…" + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "Додати розпаковане…" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "添加未打包扩展…" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "加入未封裝…" + } + } + } + }, + "settings.browser.webExtensions.addUnpacked.message": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "اختر مجلدًا يحتوي على ملحق ويب غير مضغوط (manifest.json في جذره)." + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "Odaberite fasciklu koja sadrži raspakovanu web ekstenziju (manifest.json u korijenu)." + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "Vælg en mappe, der indeholder en udpakket webudvidelse (manifest.json i roden)." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Wähle einen Ordner mit einer entpackten Weberweiterung (manifest.json im Wurzelverzeichnis)." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Choose a folder containing an unpacked web extension (manifest.json at its root)." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Elige una carpeta que contenga una extensión web descomprimida (manifest.json en su raíz)." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Choisissez un dossier contenant une extension web décompressée (manifest.json à sa racine)." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Scegli una cartella contenente un'estensione web non pacchettizzata (manifest.json nella radice)." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "展開済みの Web 拡張機能を含むフォルダを選択してください(ルートに manifest.json)。" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "압축 해제된 웹 확장 프로그램이 있는 폴더를 선택하세요(루트에 manifest.json)." + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "Velg en mappe som inneholder en utpakket nettutvidelse (manifest.json i roten)." + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "Wybierz folder zawierający rozpakowane rozszerzenie internetowe (manifest.json w katalogu głównym)." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Escolha uma pasta contendo uma extensão web descompactada (manifest.json na raiz)." + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Выберите папку с распакованным веб-расширением (manifest.json в корне)." + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "เลือกโฟลเดอร์ที่มีส่วนขยายเว็บที่แตกไฟล์แล้ว (manifest.json อยู่ที่ราก)" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Paketten çıkarılmış bir web uzantısı içeren klasör seçin (kökünde manifest.json)." + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "Виберіть теку з розпакованим веброзширенням (manifest.json у корені)." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "选择包含未打包网页扩展的文件夹(根目录有 manifest.json)。" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "選擇包含未封裝網頁延伸功能的檔案夾(根目錄有 manifest.json)。" + } + } + } + }, + "settings.browser.webExtensions.empty": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "لم يتم العثور على ملحقات ويب Safari على هذا الـ Mac" + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "Na ovom Macu nisu pronađene Safari web ekstenzije" + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "Ingen Safari-webudvidelser fundet på denne Mac" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Keine Safari-Weberweiterungen auf diesem Mac gefunden" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "No Safari web extensions found on this Mac" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "No se encontraron extensiones web de Safari en este Mac" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Aucune extension web Safari trouvée sur ce Mac" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Nessuna estensione web di Safari trovata su questo Mac" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "この Mac に Safari 機能拡張が見つかりません" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "이 Mac에서 Safari 웹 확장 프로그램을 찾을 수 없음" + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "Ingen Safari-nettutvidelser funnet på denne Macen" + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "Nie znaleziono rozszerzeń internetowych Safari na tym Macu" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Nenhuma extensão web do Safari encontrada neste Mac" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "На этом Mac не найдено веб-расширений Safari" + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "ไม่พบส่วนขยายเว็บ Safari บน Mac เครื่องนี้" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Bu Mac'te Safari web uzantısı bulunamadı" + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "На цьому Mac не знайдено веброзширень Safari" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "在这台 Mac 上未找到 Safari 网页扩展" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "在這部 Mac 上找不到 Safari 網頁延伸功能" + } + } + } + }, + "settings.browser.webExtensions.empty.subtitle": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "ثبّت تطبيقًا يتضمن ملحقًا (Bitwarden، AdGuard، …) أو أضف مجلد ملحق غير مضغوط." + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "Instalirajte aplikaciju koja sadrži ekstenziju (Bitwarden, AdGuard, …) ili dodajte raspakovanu fasciklu ekstenzije." + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "Installer en app, der indeholder en (Bitwarden, AdGuard, …), eller tilføj en udpakket udvidelsesmappe." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Installiere eine App, die eine enthält (Bitwarden, AdGuard, …), oder füge einen entpackten Erweiterungsordner hinzu." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Install an app that bundles one (Bitwarden, AdGuard, …) or add an unpacked extension folder." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Instala una app que incluya una (Bitwarden, AdGuard, …) o añade una carpeta de extensión descomprimida." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Installez une app qui en inclut une (Bitwarden, AdGuard, …) ou ajoutez un dossier d'extension décompressé." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Installa un'app che ne include una (Bitwarden, AdGuard, …) o aggiungi una cartella di estensione non pacchettizzata." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "拡張機能を含むアプリ(Bitwarden、AdGuard など)をインストールするか、展開済みの拡張機能フォルダを追加してください。" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "확장 프로그램이 포함된 앱(Bitwarden, AdGuard 등)을 설치하거나 압축 해제된 확장 폴더를 추가하세요." + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "Installer en app som inkluderer en (Bitwarden, AdGuard, …), eller legg til en utpakket utvidelsesmappe." + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "Zainstaluj aplikację zawierającą rozszerzenie (Bitwarden, AdGuard, …) lub dodaj rozpakowany folder rozszerzenia." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Instale um app que inclua uma (Bitwarden, AdGuard, …) ou adicione uma pasta de extensão descompactada." + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Установите приложение с расширением (Bitwarden, AdGuard, …) или добавьте распакованную папку расширения." + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "ติดตั้งแอปที่มีส่วนขยาย (Bitwarden, AdGuard, …) หรือเพิ่มโฟลเดอร์ส่วนขยายที่แตกไฟล์แล้ว" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Uzantı içeren bir uygulama yükleyin (Bitwarden, AdGuard, …) veya paketten çıkarılmış bir uzantı klasörü ekleyin." + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "Установіть застосунок із розширенням (Bitwarden, AdGuard, …) або додайте розпаковану теку розширення." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "安装包含扩展的应用(Bitwarden、AdGuard 等),或添加未打包的扩展文件夹。" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "安裝包含延伸功能的 App(Bitwarden、AdGuard 等),或加入未封裝的延伸功能檔案夾。" + } + } + } + }, + "settings.browser.webExtensions.remove": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "إزالة" + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "Ukloni" + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "Fjern" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Entfernen" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Remove" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Eliminar" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Supprimer" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Rimuovi" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "削除" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "제거" + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "Fjern" + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "Usuń" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Remover" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Удалить" + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "เอาออก" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Kaldır" + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "Видалити" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "移除" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "移除" + } + } + } + }, + "settings.browser.webExtensions.subtitle": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "ملحقات ويب Safari من التطبيقات المثبتة، أو مجلدات ملحقات غير مضغوطة." + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "Safari web ekstenzije iz instaliranih aplikacija ili raspakovane fascikle ekstenzija." + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "Safari-webudvidelser fra installerede apps, eller udpakkede udvidelsesmapper." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Safari-Weberweiterungen aus installierten Apps oder entpackte Erweiterungsordner." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Safari web extensions from installed apps, or unpacked extension folders." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Extensiones web de Safari de apps instaladas, o carpetas de extensiones descomprimidas." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Extensions web Safari des apps installées, ou dossiers d'extensions décompressés." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Estensioni web di Safari dalle app installate, o cartelle di estensioni non pacchettizzate." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "インストール済みアプリの Safari 機能拡張、または展開済みの拡張機能フォルダ。" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "설치된 앱의 Safari 웹 확장 프로그램 또는 압축 해제된 확장 폴더." + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "Safari-nettutvidelser fra installerte apper, eller utpakkede utvidelsesmapper." + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "Rozszerzenia internetowe Safari z zainstalowanych aplikacji lub rozpakowane foldery rozszerzeń." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Extensões web do Safari de apps instalados, ou pastas de extensões descompactadas." + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Веб-расширения Safari из установленных приложений или распакованные папки расширений." + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "ส่วนขยายเว็บ Safari จากแอปที่ติดตั้ง หรือโฟลเดอร์ส่วนขยายที่แตกไฟล์แล้ว" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Yüklü uygulamalardan Safari web uzantıları veya paketten çıkarılmış uzantı klasörleri." + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "Веброзширення Safari зі встановлених застосунків або розпаковані теки розширень." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "来自已安装应用的 Safari 网页扩展,或未打包的扩展文件夹。" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "來自已安裝 App 的 Safari 網頁延伸功能,或未封裝的延伸功能檔案夾。" + } + } + } + }, + "settings.browser.webExtensions.unsupported": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "تتطلب ملحقات الويب نظام macOS 15.4 أو أحدث." + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "Web ekstenzije zahtijevaju macOS 15.4 ili noviji." + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "Webudvidelser kræver macOS 15.4 eller nyere." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Weberweiterungen erfordern macOS 15.4 oder neuer." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Web extensions require macOS 15.4 or later." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Las extensiones web requieren macOS 15.4 o posterior." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Les extensions web nécessitent macOS 15.4 ou ultérieur." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Le estensioni web richiedono macOS 15.4 o successivo." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "Web 拡張機能には macOS 15.4 以降が必要です。" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "웹 확장 프로그램은 macOS 15.4 이상이 필요합니다." + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "Nettutvidelser krever macOS 15.4 eller nyere." + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "Rozszerzenia internetowe wymagają systemu macOS 15.4 lub nowszego." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Extensões web exigem macOS 15.4 ou posterior." + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Для веб-расширений требуется macOS 15.4 или новее." + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "ส่วนขยายเว็บต้องใช้ macOS 15.4 ขึ้นไป" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Web uzantıları macOS 15.4 veya sonrasını gerektirir." + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "Веброзширення потребують macOS 15.4 або новішої версії." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "网页扩展需要 macOS 15.4 或更高版本。" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "網頁延伸功能需要 macOS 15.4 或以上版本。" + } + } + } + }, "settings.search.alias.setting.app.loading-spinner-position": { "extractionState": "manual", "localizations": { @@ -45289,6 +46241,125 @@ } } }, + "settings.search.alias.setting.browser.web-extensions": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "browser.webExtensions extensions addons plugins bitwarden 1password adguard password manager safari web extension unpacked load" + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "browser.webExtensions extensions addons plugins bitwarden 1password adguard password manager safari web extension unpacked load" + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "browser.webExtensions extensions addons plugins bitwarden 1password adguard password manager safari web extension unpacked load" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "browser.webExtensions extensions addons plugins bitwarden 1password adguard password manager safari web extension unpacked load" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "browser.webExtensions extensions addons plugins bitwarden 1password adguard password manager safari web extension unpacked load" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "browser.webExtensions extensions addons plugins bitwarden 1password adguard password manager safari web extension unpacked load" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "browser.webExtensions extensions addons plugins bitwarden 1password adguard password manager safari web extension unpacked load" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "browser.webExtensions extensions addons plugins bitwarden 1password adguard password manager safari web extension unpacked load" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "browser.webExtensions extensions addons plugins bitwarden 1password adguard password manager safari web extension unpacked load" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "browser.webExtensions extensions addons plugins bitwarden 1password adguard password manager safari web extension unpacked load" + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "browser.webExtensions extensions addons plugins bitwarden 1password adguard password manager safari web extension unpacked load" + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "browser.webExtensions extensions addons plugins bitwarden 1password adguard password manager safari web extension unpacked load" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "browser.webExtensions extensions addons plugins bitwarden 1password adguard password manager safari web extension unpacked load" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "browser.webExtensions extensions addons plugins bitwarden 1password adguard password manager safari web extension unpacked load" + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "browser.webExtensions extensions addons plugins bitwarden 1password adguard password manager safari web extension unpacked load" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "browser.webExtensions extensions addons plugins bitwarden 1password adguard password manager safari web extension unpacked load" + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "browser.webExtensions extensions addons plugins bitwarden 1password adguard password manager safari web extension unpacked load" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "browser.webExtensions extensions addons plugins bitwarden 1password adguard password manager safari web extension unpacked load" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "browser.webExtensions extensions addons plugins bitwarden 1password adguard password manager safari web extension unpacked load" + } + } + } + }, "sidebar.agentActivity.tooltip.many": { "extractionState": "manual", "localizations": { diff --git a/Sources/HostSettingsActions.swift b/Sources/HostSettingsActions.swift index e21003b4914f..6683d14cf4a0 100644 --- a/Sources/HostSettingsActions.swift +++ b/Sources/HostSettingsActions.swift @@ -19,6 +19,24 @@ private let hostSettingsLogger = Logger(subsystem: "com.cmuxterm.app", category: final class HostSettingsActions: SettingsHostActions { private let configFileURL: URL + func browserWebExtensionsSupported() -> Bool { + if #available(macOS 15.4, *) { return true } + return false + } + + func discoverBrowserWebExtensions() async -> [SettingsDiscoveredBrowserExtension] { + guard browserWebExtensionsSupported() else { return [] } + let candidates = await BrowserWebExtensionDiscoveryService().discoverInstalledSafariExtensions() + return candidates.map { candidate in + SettingsDiscoveredBrowserExtension( + id: candidate.id, + displayName: candidate.displayName, + version: candidate.version, + path: candidate.path + ) + } + } + /// Serializes font-size config writes so rapid slider saves persist in order. private let fontConfigWriter = FontConfigWriter() diff --git a/Sources/Panels/BrowserWebExtensionDiscoveryService.swift b/Sources/Panels/BrowserWebExtensionDiscoveryService.swift new file mode 100644 index 000000000000..01c758734650 --- /dev/null +++ b/Sources/Panels/BrowserWebExtensionDiscoveryService.swift @@ -0,0 +1,106 @@ +import Foundation + +/// One web extension that can be loaded into the browser: either a Safari web +/// extension installed on this Mac (inside some app's `.appex`) or a directory +/// containing an unpacked WebExtension the user added manually. +struct BrowserWebExtensionCandidate: Identifiable, Hashable, Sendable { + enum Kind: String, Sendable { + case safariAppExtension + case unpackedDirectory + } + + /// Stable identity used for the enabled-set in settings: the appex plugin + /// identifier for Safari extensions, or the directory path for unpacked ones. + let id: String + let kind: Kind + let path: String + let version: String? + let displayName: String? +} + +/// Discovers Safari web extensions registered with the system. +/// +/// Uses `pluginkit -m -p com.apple.Safari.web-extension` — the same registry +/// Safari itself consults — so anything the user installed via an app bundle +/// (Bitwarden, 1Password, AdGuard, …) is found without configuration. +actor BrowserWebExtensionDiscoveryService { + private static let pluginkitURL = URL(fileURLWithPath: "/usr/bin/pluginkit") + + func discoverInstalledSafariExtensions() async -> [BrowserWebExtensionCandidate] { + let output: String + do { + output = try await runPluginkit() + } catch { + return [] + } + return Self.parse(pluginkitOutput: output) + } + + /// Parses `pluginkit -m -A -v` machine listing: one plug-in per line, + /// tab-separated `identifier(version)`, UUID, timestamp, absolute path. + static func parse(pluginkitOutput: String) -> [BrowserWebExtensionCandidate] { + var seen = Set() + var candidates: [BrowserWebExtensionCandidate] = [] + for line in pluginkitOutput.split(separator: "\n") { + let columns = line.split(separator: "\t").map { + $0.trimmingCharacters(in: .whitespaces) + } + guard let first = columns.first, columns.count >= 2 else { continue } + guard let path = columns.last, path.hasSuffix(".appex") else { continue } + + // `identifier(version)` — a leading `+`/`-`/`?` marks election state. + var identifierField = first + while let head = identifierField.first, ["+", "-", "?", "!"].contains(String(head)) { + identifierField = String(identifierField.dropFirst()).trimmingCharacters(in: .whitespaces) + } + var identifier = identifierField + var version: String? + if let open = identifierField.lastIndex(of: "("), identifierField.hasSuffix(")") { + identifier = String(identifierField[.. String? { + let appexURL = URL(fileURLWithPath: path) + // …/SomeApp.app/Contents/PlugIns/foo.appex → SomeApp.app + let containingApp = appexURL.deletingLastPathComponent() + .deletingLastPathComponent().deletingLastPathComponent() + if containingApp.pathExtension == "app" { + return containingApp.deletingPathExtension().lastPathComponent + } + guard let bundle = Bundle(url: appexURL) else { return nil } + return (bundle.infoDictionary?["CFBundleDisplayName"] as? String) + ?? (bundle.infoDictionary?["CFBundleName"] as? String) + } + + private func runPluginkit() async throws -> String { + let process = Process() + process.executableURL = Self.pluginkitURL + process.arguments = ["-m", "-p", "com.apple.Safari.web-extension", "-A", "-v"] + let stdout = Pipe() + process.standardOutput = stdout + process.standardError = Pipe() + try process.run() + + var data = Data() + // EOF on stdout is the completion signal; pluginkit's exit status is + // uninteresting (an empty listing and a failure both mean "none found"). + for try await byte in stdout.fileHandleForReading.bytes { + data.append(byte) + } + return String(data: data, encoding: .utf8) ?? "" + } +} diff --git a/Sources/Panels/BrowserWebExtensionSupport.swift b/Sources/Panels/BrowserWebExtensionSupport.swift index 6d79e00fd5bc..978ac88430fa 100644 --- a/Sources/Panels/BrowserWebExtensionSupport.swift +++ b/Sources/Panels/BrowserWebExtensionSupport.swift @@ -1,4 +1,5 @@ import AppKit +import CmuxSettings import SwiftUI import WebKit @@ -29,7 +30,8 @@ final class BrowserWebExtensionSupport: NSObject, ObservableObject { @Published private(set) var contexts: [WKWebExtensionContext] = [] @Published private(set) var loadErrors: [String] = [] - private var didStartLoading = false + private var settingsObservationTask: Task? + private var loadedByEntryID: [String: WKWebExtensionContext] = [:] private var tabAdapters: [UUID: BrowserWebExtensionTabAdapter] = [:] private var orderedPanelIDs: [UUID] = [] private(set) var activePanelID: UUID? @@ -58,24 +60,92 @@ final class BrowserWebExtensionSupport: NSObject, ObservableObject { // MARK: - Configuration attachment - /// Attaches the shared extension controller to a browser web view configuration - /// and kicks off extension discovery on first use. + /// Attaches the shared extension controller to a browser web view configuration. func attach(to configuration: WKWebViewConfiguration) { configuration.webExtensionController = controller - loadInstalledExtensionsIfNeeded() } - private func loadInstalledExtensionsIfNeeded() { - guard !didStartLoading else { return } - didStartLoading = true - Task { await loadInstalledExtensions() } + // MARK: - Settings-driven loading + + private static let didSeedDefaultsKey = "browserWebExtensionsDidSeedDefaults" + + /// Starts observing `browser.webExtensions` and keeps loaded extensions in + /// sync: newly enabled entries load, disabled/removed entries unload. + /// Called once from app startup so extensions begin loading before the + /// first browser page navigates. + func configure(jsonStore: JSONConfigStore, catalog: SettingCatalog) { + guard settingsObservationTask == nil else { return } + let key = catalog.browser.webExtensions + settingsObservationTask = Task { @MainActor [weak self] in + var isFirstValue = true + for await entries in jsonStore.values(for: key) { + guard let self else { return } + if isFirstValue { + isFirstValue = false + if await self.seedDefaultsIfNeeded(current: entries, store: jsonStore, key: key) { + continue // the seeded value arrives as the next stream element + } + } + await self.apply(entries: entries) + } + } + } + + /// Grandfathers the pre-settings behavior exactly once: if the user has + /// never configured extensions and the Bitwarden desktop app is installed, + /// enable its Safari extension so an existing setup keeps working. + private func seedDefaultsIfNeeded( + current: [BrowserWebExtensionEntry], + store: JSONConfigStore, + key: JSONKey<[BrowserWebExtensionEntry]> + ) async -> Bool { + let defaults = UserDefaults.standard + guard !defaults.bool(forKey: Self.didSeedDefaultsKey) else { return false } + defaults.set(true, forKey: Self.didSeedDefaultsKey) + guard current.isEmpty, + FileManager.default.fileExists(atPath: Self.bitwardenAppexURL.path) else { return false } + let seeded = BrowserWebExtensionEntry( + id: "com.bitwarden.desktop.safari", + kind: .safariAppExtension, + path: Self.bitwardenAppexURL.path, + enabled: true + ) + do { + try await store.set([seeded], for: key) + return true + } catch { + return false + } } - private func loadInstalledExtensions() async { - for url in Self.candidateExtensionURLs() { + private func apply(entries: [BrowserWebExtensionEntry]) async { + var desired: [String: BrowserWebExtensionEntry] = [:] + for entry in entries where entry.enabled { + desired[entry.id] = entry + } + for path in Self.environmentExtensionPaths() where desired[path] == nil { + desired[path] = BrowserWebExtensionEntry( + id: path, + kind: path.hasSuffix(".appex") ? .safariAppExtension : .unpackedDirectory, + path: path, + enabled: true + ) + } + + for (entryID, context) in loadedByEntryID where desired[entryID] == nil { + try? controller.unload(context) + loadedByEntryID[entryID] = nil + contexts.removeAll { $0 === context } +#if DEBUG + cmuxDebugLog("browser.webext.unloaded id=\(entryID)") +#endif + } + + for (entryID, entry) in desired where loadedByEntryID[entryID] == nil { do { + let url = URL(fileURLWithPath: entry.path) let webExtension: WKWebExtension - if url.pathExtension == "appex" { + if entry.kind == .safariAppExtension, url.pathExtension == "appex" { if let bundle = Bundle(url: url) { webExtension = try await WKWebExtension(appExtensionBundle: bundle) } else { @@ -86,23 +156,30 @@ final class BrowserWebExtensionSupport: NSObject, ObservableObject { } else { webExtension = try await WKWebExtension(resourceBaseURL: url) } - try load(webExtension) + let context = try load(webExtension) + loadedByEntryID[entryID] = context #if DEBUG cmuxDebugLog( "browser.webext.loaded name=\(webExtension.displayName ?? "?") " + - "version=\(webExtension.displayVersion ?? "?") url=\(url.path)" + "version=\(webExtension.displayVersion ?? "?") url=\(entry.path)" ) #endif } catch { - loadErrors.append("\(url.lastPathComponent): \(error.localizedDescription)") + loadErrors.append("\(entry.id): \(error.localizedDescription)") #if DEBUG - cmuxDebugLog("browser.webext.loadFailed url=\(url.path) error=\(error.localizedDescription)") + cmuxDebugLog("browser.webext.loadFailed url=\(entry.path) error=\(error.localizedDescription)") #endif } } } - private func load(_ webExtension: WKWebExtension) throws { + private static func environmentExtensionPaths() -> [String] { + guard let env = ProcessInfo.processInfo.environment["CMUX_BROWSER_EXTENSIONS"] else { return [] } + return env.split(separator: ":").map(String.init).filter { !$0.isEmpty } + } + + @discardableResult + private func load(_ webExtension: WKWebExtension) throws -> WKWebExtensionContext { let context = WKWebExtensionContext(for: webExtension) // Grant everything the manifest requests up front; interactive permission // prompting can come later. Repeat grants are also answered by the @@ -121,6 +198,7 @@ final class BrowserWebExtensionSupport: NSObject, ObservableObject { #if DEBUG logDiagnostics(for: context, label: "postLoad") #endif + return context } #if DEBUG @@ -148,20 +226,6 @@ final class BrowserWebExtensionSupport: NSObject, ObservableObject { } #endif - /// Extension bundles/directories to try loading, in order. - private static func candidateExtensionURLs() -> [URL] { - var urls: [URL] = [] - if let env = ProcessInfo.processInfo.environment["CMUX_BROWSER_EXTENSIONS"] { - for path in env.split(separator: ":") where !path.isEmpty { - urls.append(URL(fileURLWithPath: String(path))) - } - } - if FileManager.default.fileExists(atPath: bitwardenAppexURL.path) { - urls.append(bitwardenAppexURL) - } - return urls - } - // MARK: - Tab lifecycle (called from BrowserPanel) func register(panel: BrowserPanel) { diff --git a/Sources/cmuxApp.swift b/Sources/cmuxApp.swift index 4953c500ab83..688732a081a8 100644 --- a/Sources/cmuxApp.swift +++ b/Sources/cmuxApp.swift @@ -159,13 +159,14 @@ struct cmuxApp: App { // Reconcile saved language preference before any UI loads LanguageSettingsStore(defaults: .standard).reconcileLanguageOverrideAtLaunch() StartupBreadcrumbLog.append("app.init.language.applied") + let settingsJSONStore = JSONConfigStore(fileURL: configFileURL) self.settingsRuntime = SettingsRuntime( catalog: settingsCatalog, userDefaultsStore: UserDefaultsSettingsStore( defaults: .standard, migrating: settingsCatalog.all ), - jsonStore: JSONConfigStore(fileURL: configFileURL), + jsonStore: settingsJSONStore, secretStore: secretStore, errorLog: SettingsErrorLog(), accountFlow: HostAccountFlow( @@ -175,6 +176,12 @@ struct cmuxApp: App { hostActions: HostSettingsActions(configFileURL: configFileURL) ) StartupBreadcrumbLog.append("app.init.settingsRuntime.created") + if #available(macOS 15.4, *) { + BrowserWebExtensionSupport.shared.configure( + jsonStore: settingsJSONStore, + catalog: settingsCatalog + ) + } let startupAppearance = AppearanceSettings.resolvedMode() Self.applyAppearance(startupAppearance, duringLaunch: true) diff --git a/cmux.xcodeproj/project.pbxproj b/cmux.xcodeproj/project.pbxproj index 7c1c3035be70..7be3c39186fe 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -310,6 +310,7 @@ C0DE71B10000000000000001 /* AppDelegate+AgentChatNotifications.swift in Sources A50100000000000000000020 /* BrowserWebAuthnTransportSummary.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5010000000000000000001F /* BrowserWebAuthnTransportSummary.swift */; }; A50100000000000000000022 /* BrowserWebAuthnUserDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = A50100000000000000000021 /* BrowserWebAuthnUserDescriptor.swift */; }; C0DE49870000000000000001 /* BrowserWebContentProcessTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE49870000000000000002 /* BrowserWebContentProcessTests.swift */; }; + B1CFE0060000000000000001 /* BrowserWebExtensionDiscoveryService.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1CFE0060000000000000002 /* BrowserWebExtensionDiscoveryService.swift */; }; B1CFE0050000000000000001 /* BrowserWebExtensionPopoutWindowController.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1CFE0050000000000000002 /* BrowserWebExtensionPopoutWindowController.swift */; }; B1CFE0010000000000000001 /* BrowserWebExtensionSupport.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1CFE0010000000000000002 /* BrowserWebExtensionSupport.swift */; }; B1CFE0020000000000000001 /* BrowserWebExtensionTabAdapter.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1CFE0020000000000000002 /* BrowserWebExtensionTabAdapter.swift */; }; @@ -2074,6 +2075,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = A5010000000000000000001F /* BrowserWebAuthnTransportSummary.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/BrowserWebAuthnTransportSummary.swift; sourceTree = ""; }; A50100000000000000000021 /* BrowserWebAuthnUserDescriptor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/BrowserWebAuthnUserDescriptor.swift; sourceTree = ""; }; C0DE49870000000000000002 /* BrowserWebContentProcessTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BrowserWebContentProcessTests.swift; sourceTree = ""; }; + B1CFE0060000000000000002 /* BrowserWebExtensionDiscoveryService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/BrowserWebExtensionDiscoveryService.swift; sourceTree = ""; }; B1CFE0050000000000000002 /* BrowserWebExtensionPopoutWindowController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/BrowserWebExtensionPopoutWindowController.swift; sourceTree = ""; }; B1CFE0010000000000000002 /* BrowserWebExtensionSupport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/BrowserWebExtensionSupport.swift; sourceTree = ""; }; B1CFE0020000000000000002 /* BrowserWebExtensionTabAdapter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/BrowserWebExtensionTabAdapter.swift; sourceTree = ""; }; @@ -4298,6 +4300,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = B1CFE0030000000000000002 /* BrowserWebExtensionWindowAdapter.swift */, B1CFE0020000000000000002 /* BrowserWebExtensionTabAdapter.swift */, B1CFE0010000000000000002 /* BrowserWebExtensionSupport.swift */, + B1CFE0060000000000000002 /* BrowserWebExtensionDiscoveryService.swift */, B1CFE0050000000000000002 /* BrowserWebExtensionPopoutWindowController.swift */, C67540100000000000000002 /* BrowserNavigationPopupPolicy.swift */, A5001412 /* BrowserPanel.swift */, @@ -5856,6 +5859,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = A5010000000000000000001E /* BrowserWebAuthnTransport.swift in Sources */, A50100000000000000000020 /* BrowserWebAuthnTransportSummary.swift in Sources */, A50100000000000000000022 /* BrowserWebAuthnUserDescriptor.swift in Sources */, + B1CFE0060000000000000001 /* BrowserWebExtensionDiscoveryService.swift in Sources */, B1CFE0050000000000000001 /* BrowserWebExtensionPopoutWindowController.swift in Sources */, B1CFE0010000000000000001 /* BrowserWebExtensionSupport.swift in Sources */, B1CFE0020000000000000001 /* BrowserWebExtensionTabAdapter.swift in Sources */, From a18a5f4f2931070f61b814d6701b7d758a01b5cf Mon Sep 17 00:00:00 2001 From: Kylo Jorgensen Date: Wed, 8 Jul 2026 22:26:03 -0600 Subject: [PATCH 04/51] feat(settings): import-based extension list instead of auto-discovery MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Extensions card now shows only extensions the user explicitly added. Discovered Safari web extensions move behind an "Import Safari Extension" menu (listing installed-but-not-added extensions); imported entries capture a display name so rows stay readable across launches. Unpacked folders keep the Add Unpacked… picker. Every row has a Remove button. Co-Authored-By: Claude Fable 5 --- .../Values/BrowserWebExtensionEntry.swift | 7 +- .../Sections/BrowserWebExtensionsCard.swift | 137 +++++--- Resources/Localizable.xcstrings | 318 +++++++++++++++--- .../Panels/BrowserWebExtensionSupport.swift | 3 +- 4 files changed, 369 insertions(+), 96 deletions(-) diff --git a/Packages/macOS/CmuxSettings/Sources/CmuxSettings/Values/BrowserWebExtensionEntry.swift b/Packages/macOS/CmuxSettings/Sources/CmuxSettings/Values/BrowserWebExtensionEntry.swift index 0647d703dd34..f0af90ff0ec0 100644 --- a/Packages/macOS/CmuxSettings/Sources/CmuxSettings/Values/BrowserWebExtensionEntry.swift +++ b/Packages/macOS/CmuxSettings/Sources/CmuxSettings/Values/BrowserWebExtensionEntry.swift @@ -36,17 +36,22 @@ public struct BrowserWebExtensionEntry: Codable, Sendable, Equatable, Hashable, public var path: String /// Whether the extension loads into the browser. public var enabled: Bool + /// Human-readable name captured when the extension was imported + /// (e.g. the containing app's name), shown in the settings list. + public var displayName: String? /// - Parameters: /// - id: Stable identity (appex plug-in identifier, or directory path). /// - kind: Where the extension's resources come from. /// - path: Absolute path to the `.appex` bundle or unpacked directory. /// - enabled: Whether the extension loads into the browser. - public init(id: String, kind: Kind, path: String, enabled: Bool) { + /// - displayName: Human-readable name captured at import time. + public init(id: String, kind: Kind, path: String, enabled: Bool, displayName: String? = nil) { self.id = id self.kind = kind self.path = path self.enabled = enabled + self.displayName = displayName } } diff --git a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift index d327c53dca36..fa120e9acc33 100644 --- a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift +++ b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift @@ -5,10 +5,11 @@ import UniformTypeIdentifiers /// **Extensions** card in the Browser section. /// -/// Lists Safari web extensions installed on this Mac (discovered through the -/// host) and unpacked WebExtension directories the user added, each with an -/// enable toggle. State persists under `browser.webExtensions`; the host -/// observes that key and loads/unloads extensions live. +/// Shows only extensions the user has added: Safari web extensions imported +/// from apps installed on this Mac (the Import menu lists what the host +/// discovers) and unpacked WebExtension directories. Each row has an enable +/// toggle and a Remove button. State persists under `browser.webExtensions`; +/// the host observes that key and loads/unloads extensions live. @MainActor struct BrowserWebExtensionsCard: View { let model: JSONValueModel<[BrowserWebExtensionEntry]> @@ -20,15 +21,11 @@ struct BrowserWebExtensionsCard: View { SettingsCard { headerRow if supported { - ForEach(discovered) { candidate in + ForEach(model.current) { entry in SettingsCardDivider() - discoveredRow(candidate) + entryRow(entry) } - ForEach(unpackedEntries) { entry in - SettingsCardDivider() - unpackedRow(entry) - } - if discovered.isEmpty && unpackedEntries.isEmpty { + if model.current.isEmpty { SettingsCardDivider() emptyRow } @@ -44,8 +41,10 @@ struct BrowserWebExtensionsCard: View { hostActions.browserWebExtensionsSupported() } - private var unpackedEntries: [BrowserWebExtensionEntry] { - model.current.filter { $0.kind == .unpackedDirectory } + /// Discovered Safari extensions not yet added, offered by the Import menu. + private var importableExtensions: [SettingsDiscoveredBrowserExtension] { + let addedIDs = Set(model.current.map(\.id)) + return discovered.filter { !addedIDs.contains($0.id) } } private var headerRow: some View { @@ -63,63 +62,75 @@ struct BrowserWebExtensionsCard: View { defaultValue: "Web extensions require macOS 15.4 or later." ) ) { - Button(String( - localized: "settings.browser.webExtensions.addUnpacked", - defaultValue: "Add Unpacked…" - )) { - addUnpackedExtension() + HStack(spacing: 8) { + importMenu + Button(String( + localized: "settings.browser.webExtensions.addUnpacked", + defaultValue: "Add Unpacked…" + )) { + addUnpackedExtension() + } + .controlSize(.small) + .disabled(!supported) + .accessibilityIdentifier("BrowserWebExtensionsAddUnpackedButton") + } + } + } + + private var importMenu: some View { + Menu(String( + localized: "settings.browser.webExtensions.importSafari", + defaultValue: "Import Safari Extension" + )) { + if importableExtensions.isEmpty { + Button(String( + localized: "settings.browser.webExtensions.importSafari.none", + defaultValue: "No Importable Extensions Found" + )) {} + .disabled(true) + } + ForEach(importableExtensions) { candidate in + Button(candidate.displayName ?? candidate.id) { + importSafariExtension(candidate) + } } - .controlSize(.small) - .disabled(!supported) - .accessibilityIdentifier("BrowserWebExtensionsAddUnpackedButton") } + .controlSize(.small) + .fixedSize() + .disabled(!supported) + .accessibilityIdentifier("BrowserWebExtensionsImportMenu") } private var emptyRow: some View { SettingsCardRow( configurationReview: .settingsOnly, String( - localized: "settings.browser.webExtensions.empty", - defaultValue: "No Safari web extensions found on this Mac" + localized: "settings.browser.webExtensions.noneAdded", + defaultValue: "No extensions added" ), subtitle: String( - localized: "settings.browser.webExtensions.empty.subtitle", - defaultValue: "Install an app that bundles one (Bitwarden, AdGuard, …) or add an unpacked extension folder." + localized: "settings.browser.webExtensions.noneAdded.subtitle", + defaultValue: "Import a Safari web extension from an installed app, or add an unpacked extension folder." ) ) { EmptyView() } } - private func discoveredRow(_ candidate: SettingsDiscoveredBrowserExtension) -> some View { + private func entryRow(_ entry: BrowserWebExtensionEntry) -> some View { SettingsCardRow( configurationReview: .json("browser.webExtensions"), - candidate.displayName ?? candidate.id, - subtitle: candidate.version.map { "\(candidate.id) · \($0)" } ?? candidate.id - ) { - Toggle("", isOn: Binding( - get: { isEnabled(candidate.id) }, - set: { setEnabled($0, id: candidate.id, kind: .safariAppExtension, path: candidate.path) } - )) - .labelsHidden() - .controlSize(.small) - .accessibilityIdentifier("BrowserWebExtensionToggle-\(candidate.id)") - } - } - - private func unpackedRow(_ entry: BrowserWebExtensionEntry) -> some View { - SettingsCardRow( - configurationReview: .json("browser.webExtensions"), - (entry.path as NSString).lastPathComponent, - subtitle: entry.path + entry.displayName ?? (entry.path as NSString).lastPathComponent, + subtitle: entry.kind == .safariAppExtension ? entry.id : entry.path ) { HStack(spacing: 8) { Toggle("", isOn: Binding( get: { isEnabled(entry.id) }, - set: { setEnabled($0, id: entry.id, kind: .unpackedDirectory, path: entry.path) } + set: { setEnabled($0, id: entry.id) } )) .labelsHidden() .controlSize(.small) + .accessibilityIdentifier("BrowserWebExtensionToggle-\(entry.id)") Button(String( localized: "settings.browser.webExtensions.remove", defaultValue: "Remove" @@ -135,14 +146,17 @@ struct BrowserWebExtensionsCard: View { model.current.first { $0.id == id }?.enabled ?? false } - private func setEnabled(_ enabled: Bool, id: String, kind: BrowserWebExtensionEntry.Kind, path: String) { + private func setEnabled(_ enabled: Bool, id: String) { var entries = model.current - if let index = entries.firstIndex(where: { $0.id == id }) { - entries[index].enabled = enabled - entries[index].path = path - } else { - entries.append(BrowserWebExtensionEntry(id: id, kind: kind, path: path, enabled: enabled)) - } + guard let index = entries.firstIndex(where: { $0.id == id }) else { return } + entries[index].enabled = enabled + model.set(entries) + } + + private func add(_ entry: BrowserWebExtensionEntry) { + var entries = model.current + guard !entries.contains(where: { $0.id == entry.id }) else { return } + entries.append(entry) model.set(entries) } @@ -150,6 +164,16 @@ struct BrowserWebExtensionsCard: View { model.set(model.current.filter { $0.id != id }) } + private func importSafariExtension(_ candidate: SettingsDiscoveredBrowserExtension) { + add(BrowserWebExtensionEntry( + id: candidate.id, + kind: .safariAppExtension, + path: candidate.path, + enabled: true, + displayName: candidate.displayName + )) + } + private func addUnpackedExtension() { let panel = NSOpenPanel() panel.canChooseFiles = false @@ -160,7 +184,12 @@ struct BrowserWebExtensionsCard: View { defaultValue: "Choose a folder containing an unpacked web extension (manifest.json at its root)." ) guard panel.runModal() == .OK, let url = panel.url else { return } - let path = url.path - setEnabled(true, id: path, kind: .unpackedDirectory, path: path) + add(BrowserWebExtensionEntry( + id: url.path, + kind: .unpackedDirectory, + path: url.path, + enabled: true, + displayName: url.lastPathComponent + )) } } diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index 18c0b8f497f6..1a19df4be9c5 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -45289,240 +45289,478 @@ } } }, - "settings.browser.webExtensions.empty": { + "settings.browser.webExtensions.importSafari": { "extractionState": "manual", "localizations": { "ar": { "stringUnit": { "state": "translated", - "value": "لم يتم العثور على ملحقات ويب Safari على هذا الـ Mac" + "value": "استيراد ملحق Safari" } }, "bs": { "stringUnit": { "state": "translated", - "value": "Na ovom Macu nisu pronađene Safari web ekstenzije" + "value": "Uvezi Safari ekstenziju" } }, "da": { "stringUnit": { "state": "translated", - "value": "Ingen Safari-webudvidelser fundet på denne Mac" + "value": "Importér Safari-udvidelse" } }, "de": { "stringUnit": { "state": "translated", - "value": "Keine Safari-Weberweiterungen auf diesem Mac gefunden" + "value": "Safari-Erweiterung importieren" } }, "en": { "stringUnit": { "state": "translated", - "value": "No Safari web extensions found on this Mac" + "value": "Import Safari Extension" } }, "es": { "stringUnit": { "state": "translated", - "value": "No se encontraron extensiones web de Safari en este Mac" + "value": "Importar extensión de Safari" } }, "fr": { "stringUnit": { "state": "translated", - "value": "Aucune extension web Safari trouvée sur ce Mac" + "value": "Importer une extension Safari" } }, "it": { "stringUnit": { "state": "translated", - "value": "Nessuna estensione web di Safari trovata su questo Mac" + "value": "Importa estensione Safari" } }, "ja": { "stringUnit": { "state": "translated", - "value": "この Mac に Safari 機能拡張が見つかりません" + "value": "Safari 機能拡張を読み込む" } }, "ko": { "stringUnit": { "state": "translated", - "value": "이 Mac에서 Safari 웹 확장 프로그램을 찾을 수 없음" + "value": "Safari 확장 프로그램 가져오기" } }, "nb": { "stringUnit": { "state": "translated", - "value": "Ingen Safari-nettutvidelser funnet på denne Macen" + "value": "Importer Safari-utvidelse" } }, "pl": { "stringUnit": { "state": "translated", - "value": "Nie znaleziono rozszerzeń internetowych Safari na tym Macu" + "value": "Importuj rozszerzenie Safari" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Nenhuma extensão web do Safari encontrada neste Mac" + "value": "Importar extensão do Safari" } }, "ru": { "stringUnit": { "state": "translated", - "value": "На этом Mac не найдено веб-расширений Safari" + "value": "Импортировать расширение Safari" } }, "th": { "stringUnit": { "state": "translated", - "value": "ไม่พบส่วนขยายเว็บ Safari บน Mac เครื่องนี้" + "value": "นำเข้าส่วนขยาย Safari" } }, "tr": { "stringUnit": { "state": "translated", - "value": "Bu Mac'te Safari web uzantısı bulunamadı" + "value": "Safari Uzantısını İçe Aktar" } }, "uk": { "stringUnit": { "state": "translated", - "value": "На цьому Mac не знайдено веброзширень Safari" + "value": "Імпортувати розширення Safari" } }, "zh-Hans": { "stringUnit": { "state": "translated", - "value": "在这台 Mac 上未找到 Safari 网页扩展" + "value": "导入 Safari 扩展" } }, "zh-Hant": { "stringUnit": { "state": "translated", - "value": "在這部 Mac 上找不到 Safari 網頁延伸功能" + "value": "輸入 Safari 延伸功能" } } } }, - "settings.browser.webExtensions.empty.subtitle": { + "settings.browser.webExtensions.importSafari.none": { "extractionState": "manual", "localizations": { "ar": { "stringUnit": { "state": "translated", - "value": "ثبّت تطبيقًا يتضمن ملحقًا (Bitwarden، AdGuard، …) أو أضف مجلد ملحق غير مضغوط." + "value": "لم يتم العثور على ملحقات قابلة للاستيراد" } }, "bs": { "stringUnit": { "state": "translated", - "value": "Instalirajte aplikaciju koja sadrži ekstenziju (Bitwarden, AdGuard, …) ili dodajte raspakovanu fasciklu ekstenzije." + "value": "Nema ekstenzija za uvoz" } }, "da": { "stringUnit": { "state": "translated", - "value": "Installer en app, der indeholder en (Bitwarden, AdGuard, …), eller tilføj en udpakket udvidelsesmappe." + "value": "Ingen udvidelser at importere" } }, "de": { "stringUnit": { "state": "translated", - "value": "Installiere eine App, die eine enthält (Bitwarden, AdGuard, …), oder füge einen entpackten Erweiterungsordner hinzu." + "value": "Keine importierbaren Erweiterungen gefunden" } }, "en": { "stringUnit": { "state": "translated", - "value": "Install an app that bundles one (Bitwarden, AdGuard, …) or add an unpacked extension folder." + "value": "No Importable Extensions Found" } }, "es": { "stringUnit": { "state": "translated", - "value": "Instala una app que incluya una (Bitwarden, AdGuard, …) o añade una carpeta de extensión descomprimida." + "value": "No hay extensiones para importar" } }, "fr": { "stringUnit": { "state": "translated", - "value": "Installez une app qui en inclut une (Bitwarden, AdGuard, …) ou ajoutez un dossier d'extension décompressé." + "value": "Aucune extension à importer" } }, "it": { "stringUnit": { "state": "translated", - "value": "Installa un'app che ne include una (Bitwarden, AdGuard, …) o aggiungi una cartella di estensione non pacchettizzata." + "value": "Nessuna estensione da importare" } }, "ja": { "stringUnit": { "state": "translated", - "value": "拡張機能を含むアプリ(Bitwarden、AdGuard など)をインストールするか、展開済みの拡張機能フォルダを追加してください。" + "value": "読み込める機能拡張が見つかりません" } }, "ko": { "stringUnit": { "state": "translated", - "value": "확장 프로그램이 포함된 앱(Bitwarden, AdGuard 등)을 설치하거나 압축 해제된 확장 폴더를 추가하세요." + "value": "가져올 수 있는 확장 프로그램 없음" } }, "nb": { "stringUnit": { "state": "translated", - "value": "Installer en app som inkluderer en (Bitwarden, AdGuard, …), eller legg til en utpakket utvidelsesmappe." + "value": "Ingen utvidelser å importere" } }, "pl": { "stringUnit": { "state": "translated", - "value": "Zainstaluj aplikację zawierającą rozszerzenie (Bitwarden, AdGuard, …) lub dodaj rozpakowany folder rozszerzenia." + "value": "Brak rozszerzeń do zaimportowania" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "Instale um app que inclua uma (Bitwarden, AdGuard, …) ou adicione uma pasta de extensão descompactada." + "value": "Nenhuma extensão para importar" } }, "ru": { "stringUnit": { "state": "translated", - "value": "Установите приложение с расширением (Bitwarden, AdGuard, …) или добавьте распакованную папку расширения." + "value": "Нет расширений для импорта" } }, "th": { "stringUnit": { "state": "translated", - "value": "ติดตั้งแอปที่มีส่วนขยาย (Bitwarden, AdGuard, …) หรือเพิ่มโฟลเดอร์ส่วนขยายที่แตกไฟล์แล้ว" + "value": "ไม่พบส่วนขยายที่นำเข้าได้" } }, "tr": { "stringUnit": { "state": "translated", - "value": "Uzantı içeren bir uygulama yükleyin (Bitwarden, AdGuard, …) veya paketten çıkarılmış bir uzantı klasörü ekleyin." + "value": "İçe Aktarılabilir Uzantı Bulunamadı" } }, "uk": { "stringUnit": { "state": "translated", - "value": "Установіть застосунок із розширенням (Bitwarden, AdGuard, …) або додайте розпаковану теку розширення." + "value": "Немає розширень для імпорту" } }, "zh-Hans": { "stringUnit": { "state": "translated", - "value": "安装包含扩展的应用(Bitwarden、AdGuard 等),或添加未打包的扩展文件夹。" + "value": "未找到可导入的扩展" } }, "zh-Hant": { "stringUnit": { "state": "translated", - "value": "安裝包含延伸功能的 App(Bitwarden、AdGuard 等),或加入未封裝的延伸功能檔案夾。" + "value": "找不到可輸入的延伸功能" + } + } + } + }, + "settings.browser.webExtensions.noneAdded": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "لم تتم إضافة ملحقات" + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "Nema dodanih ekstenzija" + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "Ingen udvidelser tilføjet" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Keine Erweiterungen hinzugefügt" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "No extensions added" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "No se han añadido extensiones" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Aucune extension ajoutée" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Nessuna estensione aggiunta" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "拡張機能は追加されていません" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "추가된 확장 프로그램 없음" + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "Ingen utvidelser lagt til" + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "Nie dodano rozszerzeń" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Nenhuma extensão adicionada" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Расширения не добавлены" + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "ยังไม่ได้เพิ่มส่วนขยาย" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Uzantı eklenmedi" + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "Розширення не додано" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "未添加扩展" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "未加入延伸功能" + } + } + } + }, + "settings.browser.webExtensions.noneAdded.subtitle": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "استورد ملحق ويب Safari من تطبيق مثبت، أو أضف مجلد ملحق غير مضغوط." + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "Uvezite Safari web ekstenziju iz instalirane aplikacije ili dodajte raspakovanu fasciklu ekstenzije." + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "Importér en Safari-webudvidelse fra en installeret app, eller tilføj en udpakket udvidelsesmappe." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Importiere eine Safari-Weberweiterung aus einer installierten App oder füge einen entpackten Erweiterungsordner hinzu." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Import a Safari web extension from an installed app, or add an unpacked extension folder." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Importa una extensión web de Safari desde una app instalada, o añade una carpeta de extensión descomprimida." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Importez une extension web Safari depuis une app installée, ou ajoutez un dossier d'extension décompressé." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Importa un'estensione web di Safari da un'app installata, o aggiungi una cartella di estensione non pacchettizzata." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "インストール済みアプリから Safari 機能拡張を読み込むか、展開済みの拡張機能フォルダを追加してください。" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "설치된 앱에서 Safari 웹 확장 프로그램을 가져오거나 압축 해제된 확장 폴더를 추가하세요." + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "Importer en Safari-nettutvidelse fra en installert app, eller legg til en utpakket utvidelsesmappe." + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "Zaimportuj rozszerzenie internetowe Safari z zainstalowanej aplikacji lub dodaj rozpakowany folder rozszerzenia." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Importe uma extensão web do Safari de um app instalado, ou adicione uma pasta de extensão descompactada." + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Импортируйте веб-расширение Safari из установленного приложения или добавьте распакованную папку расширения." + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "นำเข้าส่วนขยายเว็บ Safari จากแอปที่ติดตั้ง หรือเพิ่มโฟลเดอร์ส่วนขยายที่แตกไฟล์แล้ว" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Yüklü bir uygulamadan Safari web uzantısı içe aktarın veya paketten çıkarılmış bir uzantı klasörü ekleyin." + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "Імпортуйте веброзширення Safari зі встановленого застосунку або додайте розпаковану теку розширення." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "从已安装的应用导入 Safari 网页扩展,或添加未打包的扩展文件夹。" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "從已安裝的 App 輸入 Safari 網頁延伸功能,或加入未封裝的延伸功能檔案夾。" } } } diff --git a/Sources/Panels/BrowserWebExtensionSupport.swift b/Sources/Panels/BrowserWebExtensionSupport.swift index 978ac88430fa..68d58e2d3801 100644 --- a/Sources/Panels/BrowserWebExtensionSupport.swift +++ b/Sources/Panels/BrowserWebExtensionSupport.swift @@ -108,7 +108,8 @@ final class BrowserWebExtensionSupport: NSObject, ObservableObject { id: "com.bitwarden.desktop.safari", kind: .safariAppExtension, path: Self.bitwardenAppexURL.path, - enabled: true + enabled: true, + displayName: "Bitwarden" ) do { try await store.set([seeded], for: key) From 775753c4f5a8d118badb5f3072b30cd091aa0597 Mon Sep 17 00:00:00 2001 From: Kylo Jorgensen Date: Wed, 8 Jul 2026 22:31:01 -0600 Subject: [PATCH 05/51] refactor(browser): drop Bitwarden auto-seed; settings are the only source Extensions now load exclusively from browser.webExtensions entries (plus the CMUX_BROWSER_EXTENSIONS env override). The one-time Bitwarden grandfather-seed made sense while the path was hardcoded; with the import-based settings UI, nothing is added without an explicit user action. Bitwarden remains only in comments, doc examples, and settings- search keywords. Co-Authored-By: Claude Fable 5 --- .../Panels/BrowserWebExtensionSupport.swift | 49 ++----------------- 1 file changed, 4 insertions(+), 45 deletions(-) diff --git a/Sources/Panels/BrowserWebExtensionSupport.swift b/Sources/Panels/BrowserWebExtensionSupport.swift index 68d58e2d3801..210fa1365b18 100644 --- a/Sources/Panels/BrowserWebExtensionSupport.swift +++ b/Sources/Panels/BrowserWebExtensionSupport.swift @@ -7,10 +7,11 @@ import WebKit /// native `WKWebExtensionController` API (macOS 15.4+). /// /// One shared controller (persistent storage keyed by a fixed identifier) is attached -/// to every browser `WKWebViewConfiguration`. Extensions are discovered from: +/// to every browser `WKWebViewConfiguration`. Extensions come from: +/// - the `browser.webExtensions` entries in cmux settings (managed in +/// Settings → Browser → Extensions), and /// - directories listed in the `CMUX_BROWSER_EXTENSIONS` environment variable -/// (colon-separated paths to unpacked extensions or `.appex` bundles), and -/// - the Bitwarden desktop app's bundled Safari web extension, when installed. +/// (colon-separated paths to unpacked extensions or `.appex` bundles). @available(macOS 15.4, *) @MainActor final class BrowserWebExtensionSupport: NSObject, ObservableObject { @@ -20,11 +21,6 @@ final class BrowserWebExtensionSupport: NSObject, ObservableObject { /// persists across app launches. private static let controllerIdentifier = UUID(uuidString: "8C0FDE2B-6EFD-4E8C-9E70-8E7D0A4C51B7")! - /// Bundled Safari web extension inside the Bitwarden desktop app. - private static let bitwardenAppexURL = URL( - fileURLWithPath: "/Applications/Bitwarden.app/Contents/PlugIns/safari.appex" - ) - let controller: WKWebExtensionController @Published private(set) var contexts: [WKWebExtensionContext] = [] @@ -67,8 +63,6 @@ final class BrowserWebExtensionSupport: NSObject, ObservableObject { // MARK: - Settings-driven loading - private static let didSeedDefaultsKey = "browserWebExtensionsDidSeedDefaults" - /// Starts observing `browser.webExtensions` and keeps loaded extensions in /// sync: newly enabled entries load, disabled/removed entries unload. /// Called once from app startup so extensions begin loading before the @@ -77,48 +71,13 @@ final class BrowserWebExtensionSupport: NSObject, ObservableObject { guard settingsObservationTask == nil else { return } let key = catalog.browser.webExtensions settingsObservationTask = Task { @MainActor [weak self] in - var isFirstValue = true for await entries in jsonStore.values(for: key) { guard let self else { return } - if isFirstValue { - isFirstValue = false - if await self.seedDefaultsIfNeeded(current: entries, store: jsonStore, key: key) { - continue // the seeded value arrives as the next stream element - } - } await self.apply(entries: entries) } } } - /// Grandfathers the pre-settings behavior exactly once: if the user has - /// never configured extensions and the Bitwarden desktop app is installed, - /// enable its Safari extension so an existing setup keeps working. - private func seedDefaultsIfNeeded( - current: [BrowserWebExtensionEntry], - store: JSONConfigStore, - key: JSONKey<[BrowserWebExtensionEntry]> - ) async -> Bool { - let defaults = UserDefaults.standard - guard !defaults.bool(forKey: Self.didSeedDefaultsKey) else { return false } - defaults.set(true, forKey: Self.didSeedDefaultsKey) - guard current.isEmpty, - FileManager.default.fileExists(atPath: Self.bitwardenAppexURL.path) else { return false } - let seeded = BrowserWebExtensionEntry( - id: "com.bitwarden.desktop.safari", - kind: .safariAppExtension, - path: Self.bitwardenAppexURL.path, - enabled: true, - displayName: "Bitwarden" - ) - do { - try await store.set([seeded], for: key) - return true - } catch { - return false - } - } - private func apply(entries: [BrowserWebExtensionEntry]) async { var desired: [String: BrowserWebExtensionEntry] = [:] for entry in entries where entry.enabled { From 591415e29cd2409409fe95916af3491efebe4605 Mon Sep 17 00:00:00 2001 From: Kylo Jorgensen Date: Wed, 8 Jul 2026 22:51:01 -0600 Subject: [PATCH 06/51] fix(browser): address review findings on extension management - Settings entries win over CMUX_BROWSER_EXTENSIONS for the same path (standardized-path comparison), so a disabled toggle sticks and the same extension can't load twice under two ids. - Unloading an extension closes its open popout windows instead of leaving orphaned extension web views. - Discard pluginkit stderr instead of piping it undrained, which could block the child process and hang discovery. - Drop unused discoveredWebExtensions state from BrowserSection. Co-Authored-By: Claude Fable 5 --- .../CmuxSettingsUI/Sections/BrowserSection.swift | 1 - .../BrowserWebExtensionDiscoveryService.swift | 4 +++- .../BrowserWebExtensionPopoutWindowController.swift | 2 +- Sources/Panels/BrowserWebExtensionSupport.swift | 13 ++++++++++++- 4 files changed, 16 insertions(+), 4 deletions(-) diff --git a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserSection.swift b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserSection.swift index 2cb2b61dcc47..3ad92b7d605f 100644 --- a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserSection.swift +++ b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserSection.swift @@ -40,7 +40,6 @@ public struct BrowserSection: View { @State private var httpAllowlistLoaded: Bool = false @State private var webExtensions: JSONValueModel<[BrowserWebExtensionEntry]> - @State private var discoveredWebExtensions: [SettingsDiscoveredBrowserExtension] = [] public init( defaultsStore: UserDefaultsSettingsStore, diff --git a/Sources/Panels/BrowserWebExtensionDiscoveryService.swift b/Sources/Panels/BrowserWebExtensionDiscoveryService.swift index 01c758734650..974143521500 100644 --- a/Sources/Panels/BrowserWebExtensionDiscoveryService.swift +++ b/Sources/Panels/BrowserWebExtensionDiscoveryService.swift @@ -92,7 +92,9 @@ actor BrowserWebExtensionDiscoveryService { process.arguments = ["-m", "-p", "com.apple.Safari.web-extension", "-A", "-v"] let stdout = Pipe() process.standardOutput = stdout - process.standardError = Pipe() + // Discard rather than pipe stderr: an undrained pipe could block the + // child if it wrote enough diagnostics, hanging discovery. + process.standardError = FileHandle.nullDevice try process.run() var data = Data() diff --git a/Sources/Panels/BrowserWebExtensionPopoutWindowController.swift b/Sources/Panels/BrowserWebExtensionPopoutWindowController.swift index ee0dbf5153aa..1c2775573f97 100644 --- a/Sources/Panels/BrowserWebExtensionPopoutWindowController.swift +++ b/Sources/Panels/BrowserWebExtensionPopoutWindowController.swift @@ -15,7 +15,7 @@ final class BrowserWebExtensionPopoutWindowController: NSObject, WKWebExtensionW let webView: WKWebView private(set) lazy var tab = Tab(controller: self) private weak var support: BrowserWebExtensionSupport? - private weak var extensionContext: WKWebExtensionContext? + private(set) weak var extensionContext: WKWebExtensionContext? init( configuration: WKWebExtension.WindowConfiguration, diff --git a/Sources/Panels/BrowserWebExtensionSupport.swift b/Sources/Panels/BrowserWebExtensionSupport.swift index 210fa1365b18..84421f93433b 100644 --- a/Sources/Panels/BrowserWebExtensionSupport.swift +++ b/Sources/Panels/BrowserWebExtensionSupport.swift @@ -83,7 +83,13 @@ final class BrowserWebExtensionSupport: NSObject, ObservableObject { for entry in entries where entry.enabled { desired[entry.id] = entry } - for path in Self.environmentExtensionPaths() where desired[path] == nil { + // A settings entry for the same path — enabled or not — always wins + // over the env override, so a user's "disabled" toggle sticks and the + // same extension never loads twice under two different ids. + let standardizedSettingsPaths = Set(entries.map { URL(fileURLWithPath: $0.path).standardizedFileURL.path }) + for path in Self.environmentExtensionPaths() { + let standardized = URL(fileURLWithPath: path).standardizedFileURL.path + guard desired[path] == nil, !standardizedSettingsPaths.contains(standardized) else { continue } desired[path] = BrowserWebExtensionEntry( id: path, kind: path.hasSuffix(".appex") ? .safariAppExtension : .unpackedDirectory, @@ -96,6 +102,11 @@ final class BrowserWebExtensionSupport: NSObject, ObservableObject { try? controller.unload(context) loadedByEntryID[entryID] = nil contexts.removeAll { $0 === context } + // Close any popout windows the now-unloaded extension had open + // (e.g. a Bitwarden unlock popout) instead of leaving orphans. + for popout in popouts where popout.extensionContext === context { + popout.closeFromExtensionOrUser() + } #if DEBUG cmuxDebugLog("browser.webext.unloaded id=\(entryID)") #endif From e8b1dbbd245228323268b421fa55b1504ab5ee43 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 03:08:57 -0700 Subject: [PATCH 07/51] Address browser extension review feedback --- .github/swift-file-length-budget.tsv | 10 +- .../Sections/BrowserWebExtensionsCard.swift | 33 +- Resources/Localizable.xcstrings | 66 ++++ Sources/AppDelegate+WindowDock.swift | 3 +- Sources/AppDelegate.swift | 2 +- Sources/DockSplitStore.swift | 5 +- Sources/Panels/BrowserPanel.swift | 59 ++-- Sources/Panels/BrowserPanelView.swift | 4 +- .../BrowserWebExtensionActionSnapshot.swift | 16 + .../BrowserWebExtensionDiscoveryService.swift | 57 ++- .../Panels/BrowserWebExtensionHosting.swift | 11 + .../BrowserWebExtensionLoadedRecord.swift | 8 + ...erWebExtensionPopoutWindowController.swift | 2 + ...serWebExtensionReconciliationPlanner.swift | 80 +++++ .../BrowserWebExtensionSupport+Loading.swift | 138 ++++++++ ...ort+WKWebExtensionControllerDelegate.swift | 234 +++++++++++++ .../Panels/BrowserWebExtensionSupport.swift | 330 ++---------------- .../BrowserWebExtensionToolbarButtons.swift | 30 +- .../BrowserWebExtensionWindowAdapter.swift | 13 + Sources/Panels/CmuxWebView.swift | 2 +- Sources/TabManager+DetachedWorkspace.swift | 1 + Sources/TabManager.swift | 12 +- Sources/Workspace+DockBrowserLookup.swift | 3 +- Sources/Workspace.swift | 19 +- Sources/cmuxApp.swift | 11 +- cmux.xcodeproj/project.pbxproj | 28 ++ .../BrowserWebExtensionSupportTests.swift | 101 ++++++ 27 files changed, 902 insertions(+), 376 deletions(-) create mode 100644 Sources/Panels/BrowserWebExtensionActionSnapshot.swift create mode 100644 Sources/Panels/BrowserWebExtensionHosting.swift create mode 100644 Sources/Panels/BrowserWebExtensionLoadedRecord.swift create mode 100644 Sources/Panels/BrowserWebExtensionReconciliationPlanner.swift create mode 100644 Sources/Panels/BrowserWebExtensionSupport+Loading.swift create mode 100644 Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift create mode 100644 cmuxTests/BrowserWebExtensionSupportTests.swift diff --git a/.github/swift-file-length-budget.tsv b/.github/swift-file-length-budget.tsv index 68977f89ba36..531483235df8 100644 --- a/.github/swift-file-length-budget.tsv +++ b/.github/swift-file-length-budget.tsv @@ -36,7 +36,7 @@ 2876 cmuxTests/CMUXOpenCommandTests.swift 2875 Sources/SessionIndexView.swift 2611 Sources/KeyboardShortcutSettings.swift -2562 Sources/Panels/CmuxWebView.swift +2569 Sources/Panels/CmuxWebView.swift 2546 cmuxTests/WorkspaceManualUnreadTests.swift 2524 cmuxTests/CommandPaletteSearchEngineTests.swift 2403 Sources/Mobile/MobileHostService.swift @@ -98,7 +98,7 @@ 982 Packages/Shared/CmuxAgentChat/Tests/CmuxAgentChatTests/ChatConversationStoreTests.swift 951 Packages/macOS/CmuxControlSocket/Sources/CmuxControlSocket/Coordinator/Workspace/ControlCommandCoordinator+Workspace.swift 951 Sources/App/TerminalDirectoryOpenSupport.swift -948 Sources/App/ShortcutRoutingSupport.swift +966 Sources/App/ShortcutRoutingSupport.swift 947 Sources/TerminalNotificationPolicy.swift 945 Sources/SessionIndexRegisteredAgents.swift 944 Sources/CommandPalette/CommandPaletteSettingsToggle.swift @@ -112,6 +112,7 @@ 897 Sources/DockSplitStore.swift 896 Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/AppSection.swift 885 cmuxTests/SidebarWorkspaceDropPlannerTests.swift + 871 cmuxTests/ClaudeHookSurfaceResolutionSwiftTests.swift 868 Sources/Panels/BrowserScreenshotSnapshotter.swift 864 Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Store/ChatConversationStore.swift @@ -147,6 +148,7 @@ 706 CLI/CMUXCLI+Config.swift 699 cmuxTests/TerminalNotificationClearAllTests.swift 698 cmuxTests/RestorableAgentHookProviderResumeTests.swift + 696 cmuxTests/KeyboardShortcutContextTests.swift 691 Sources/NotificationSoundSettings.swift 691 cmuxTests/TaskManagerResourcesTests.swift @@ -172,6 +174,7 @@ 650 Packages/macOS/CmuxBrowser/Sources/CmuxBrowser/Import/Detection/BrowserInstalledBrowserDetector.swift 650 Sources/Panels/MarkdownRemoteImageLoader.swift 648 cmuxTests/TerminalNotificationQueueTests.swift + 644 Packages/macOS/CMUXAgentLaunch/Tests/CMUXAgentLaunchTests/AgentLaunchSanitizerTests.swift 641 cmuxTests/CommandPaletteNucleoFFITests.swift 638 cmuxTests/RemoteTmuxControlParserTests.swift @@ -181,6 +184,7 @@ 630 Packages/macOS/CmuxSettings/Sources/CmuxSettings/Values/ShortcutWhenClause.swift 624 Sources/SettingsNavigation.swift 623 Packages/macOS/CmuxControlSocket/Sources/CmuxControlSocket/Coordinator/Surface/ControlCommandCoordinator+Surface.swift + 620 cmuxTests/FinderFileDropRegressionTests.swift 608 Sources/TextBoxSubmitActions.swift 608 cmuxUITests/FeedSidebarUITests.swift @@ -205,7 +209,7 @@ 576 Packages/Shared/CMUXMobileCore/Sources/CMUXMobileCore/MobileTerminalRenderGrid.swift 575 Packages/macOS/CmuxWorkspaces/Sources/CmuxWorkspaces/Coordinators/WorkspaceGroupCoordinator.swift 572 Sources/Feed/FeedTextEditorDebugWindowController.swift -567 Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserSection.swift +581 Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserSection.swift 567 Packages/macOS/CmuxTerminalCore/Sources/CmuxTerminalCore/ConfigDiscovery/GhosttyConfigDiscovery.swift 562 cmuxTests/AgentExecutableResolverTests.swift 561 cmuxTests/GhosttyConfigPathResolverTests.swift diff --git a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift index fa120e9acc33..52adab66db8a 100644 --- a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift +++ b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift @@ -23,7 +23,7 @@ struct BrowserWebExtensionsCard: View { if supported { ForEach(model.current) { entry in SettingsCardDivider() - entryRow(entry) + entryRow(entry, isEnabled: entry.enabled) } if model.current.isEmpty { SettingsCardDivider() @@ -117,7 +117,7 @@ struct BrowserWebExtensionsCard: View { } } - private func entryRow(_ entry: BrowserWebExtensionEntry) -> some View { + private func entryRow(_ entry: BrowserWebExtensionEntry, isEnabled: Bool) -> some View { SettingsCardRow( configurationReview: .json("browser.webExtensions"), entry.displayName ?? (entry.path as NSString).lastPathComponent, @@ -125,7 +125,7 @@ struct BrowserWebExtensionsCard: View { ) { HStack(spacing: 8) { Toggle("", isOn: Binding( - get: { isEnabled(entry.id) }, + get: { isEnabled }, set: { setEnabled($0, id: entry.id) } )) .labelsHidden() @@ -142,10 +142,6 @@ struct BrowserWebExtensionsCard: View { } } - private func isEnabled(_ id: String) -> Bool { - model.current.first { $0.id == id }?.enabled ?? false - } - private func setEnabled(_ enabled: Bool, id: String) { var entries = model.current guard let index = entries.firstIndex(where: { $0.id == id }) else { return } @@ -184,6 +180,11 @@ struct BrowserWebExtensionsCard: View { defaultValue: "Choose a folder containing an unpacked web extension (manifest.json at its root)." ) guard panel.runModal() == .OK, let url = panel.url else { return } + let manifestURL = url.appendingPathComponent("manifest.json", isDirectory: false) + guard FileManager.default.fileExists(atPath: manifestURL.path) else { + presentMissingManifestAlert(for: url) + return + } add(BrowserWebExtensionEntry( id: url.path, kind: .unpackedDirectory, @@ -192,4 +193,22 @@ struct BrowserWebExtensionsCard: View { displayName: url.lastPathComponent )) } + + private func presentMissingManifestAlert(for url: URL) { + let alert = NSAlert() + alert.alertStyle = .warning + alert.messageText = String( + localized: "settings.browser.webExtensions.addUnpacked.missingManifest.title", + defaultValue: "Missing manifest.json" + ) + alert.informativeText = String( + format: String( + localized: "settings.browser.webExtensions.addUnpacked.missingManifest.message", + defaultValue: "“%@” is not an unpacked web extension. Choose a folder with manifest.json at its root." + ), + url.lastPathComponent + ) + alert.addButton(withTitle: String(localized: "common.ok", defaultValue: "OK")) + alert.runModal() + } } diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index 1a19df4be9c5..b88663a40b79 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -30729,6 +30729,12 @@ "state": "translated", "value": "延伸功能" } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "ផ្នែកបន្ថែម" + } } } }, @@ -45048,6 +45054,12 @@ "state": "translated", "value": "延伸功能" } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "ផ្នែកបន្ថែម" + } } } }, @@ -45167,6 +45179,12 @@ "state": "translated", "value": "加入未封裝…" } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "បន្ថែមថតមិនបានខ្ចប់…" + } } } }, @@ -45286,6 +45304,12 @@ "state": "translated", "value": "選擇包含未封裝網頁延伸功能的檔案夾(根目錄有 manifest.json)。" } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "ជ្រើសថតដែលមានផ្នែកបន្ថែមវេបមិនបានខ្ចប់ (manifest.json នៅកម្រិតដើម)។" + } } } }, @@ -45405,6 +45429,12 @@ "state": "translated", "value": "輸入 Safari 延伸功能" } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "នាំចូលផ្នែកបន្ថែម Safari" + } } } }, @@ -45524,6 +45554,12 @@ "state": "translated", "value": "找不到可輸入的延伸功能" } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "រកមិនឃើញផ្នែកបន្ថែមដែលអាចនាំចូលបាន" + } } } }, @@ -45643,6 +45679,12 @@ "state": "translated", "value": "未加入延伸功能" } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "មិនទាន់បានបន្ថែមផ្នែកបន្ថែម" + } } } }, @@ -45762,6 +45804,12 @@ "state": "translated", "value": "從已安裝的 App 輸入 Safari 網頁延伸功能,或加入未封裝的延伸功能檔案夾。" } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "នាំចូលផ្នែកបន្ថែម Safari ពីកម្មវិធីដែលបានដំឡើង ឬបន្ថែមថតផ្នែកបន្ថែមមិនបានខ្ចប់។" + } } } }, @@ -45881,6 +45929,12 @@ "state": "translated", "value": "移除" } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "ដកចេញ" + } } } }, @@ -46000,6 +46054,12 @@ "state": "translated", "value": "來自已安裝 App 的 Safari 網頁延伸功能,或未封裝的延伸功能檔案夾。" } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "ផ្នែកបន្ថែម Safari ពីកម្មវិធីដែលបានដំឡើង ឬថតផ្នែកបន្ថែមមិនបានខ្ចប់។" + } } } }, @@ -46119,6 +46179,12 @@ "state": "translated", "value": "網頁延伸功能需要 macOS 15.4 或以上版本。" } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "ផ្នែកបន្ថែមវេបទាមទារ macOS 15.4 ឬថ្មីជាងនេះ។" + } } } }, diff --git a/Sources/AppDelegate+WindowDock.swift b/Sources/AppDelegate+WindowDock.swift index 0e286fc414d4..5bc263a7157b 100644 --- a/Sources/AppDelegate+WindowDock.swift +++ b/Sources/AppDelegate+WindowDock.swift @@ -11,7 +11,8 @@ extension AppDelegate.MainWindowContext { workspaceId: windowId, scope: .global, baseDirectoryProvider: { nil }, - remoteBrowserSettingsProvider: { .local } + remoteBrowserSettingsProvider: { .local }, + browserWebExtensionHost: tabManager.browserWebExtensionHost ) windowDock = store return store diff --git a/Sources/AppDelegate.swift b/Sources/AppDelegate.swift index 91b1f11fb311..d58ce214ef6f 100644 --- a/Sources/AppDelegate.swift +++ b/Sources/AppDelegate.swift @@ -16538,7 +16538,7 @@ private extension NSApplication { // web-extension commands like Bitwarden autofill while a browser web // view has focus; otherwise the suppression below would eat it. if #available(macOS 15.4, *), cmuxRespondersContainBrowserWebView(responder), - BrowserWebExtensionSupport.shared.performCommand(for: event) { + shortcutEventBrowserPanel(event)?.performWebExtensionCommand(for: event) == true { #if DEBUG cmuxDebugLog("app.sendEvent routed web-extension command before stale cmux menu shortcut") #endif diff --git a/Sources/DockSplitStore.swift b/Sources/DockSplitStore.swift index b64cbe615030..57d13d523103 100644 --- a/Sources/DockSplitStore.swift +++ b/Sources/DockSplitStore.swift @@ -32,6 +32,7 @@ final class DockSplitStore: BonsplitDelegate { private let baseDirectoryProvider: () -> String? private let remoteBrowserSettingsProvider: () -> DockRemoteBrowserSettings private let browserAvailabilityProvider: () -> Bool + let browserWebExtensionHost: (any BrowserWebExtensionHosting)? // Internal so cross-container transfers can move live panels without tearing them down. var panels: [UUID: any Panel] = [:] var surfaceIdToPanelId: [TabID: UUID] = [:] @@ -78,13 +79,15 @@ final class DockSplitStore: BonsplitDelegate { scope: DockScope = .workspace, baseDirectoryProvider: @escaping () -> String?, remoteBrowserSettingsProvider: @escaping () -> DockRemoteBrowserSettings = { .local }, - browserAvailabilityProvider: @escaping () -> Bool = { BrowserAvailabilitySettings.isEnabled() } + browserAvailabilityProvider: @escaping () -> Bool = { BrowserAvailabilitySettings.isEnabled() }, + browserWebExtensionHost: (any BrowserWebExtensionHosting)? = nil ) { self.workspaceId = workspaceId self.scope = scope self.baseDirectoryProvider = baseDirectoryProvider self.remoteBrowserSettingsProvider = remoteBrowserSettingsProvider self.browserAvailabilityProvider = browserAvailabilityProvider + self.browserWebExtensionHost = browserWebExtensionHost self.bonsplitController = BonsplitController(configuration: Self.makeConfiguration()) self.sourceLabel = String(localized: "dock.source.title", defaultValue: "Dock") self.bonsplitController.delegate = self diff --git a/Sources/Panels/BrowserPanel.swift b/Sources/Panels/BrowserPanel.swift index bd2752b09ecd..1488a607a4dd 100644 --- a/Sources/Panels/BrowserPanel.swift +++ b/Sources/Panels/BrowserPanel.swift @@ -1213,7 +1213,8 @@ enum BrowserUserAgentSettings { // Force a Safari UA. Some WebKit builds return a minimal UA without Version/Safari tokens, // and some installs may have legacy Chrome UA overrides. Both can cause Google to serve // fallback/old UIs or trigger bot checks. - static let safariUserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.2 Safari/605.1.15" + static let safariApplicationNameForUserAgent = "Version/26.2 Safari/605.1.15" + static let safariUserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) \(safariApplicationNameForUserAgent)" } func normalizedBrowserHistoryNamespace(bundleIdentifier: String) -> String { @@ -2745,6 +2746,7 @@ final class BrowserPanel: Panel, ObservableObject { /// The underlying web view private(set) var webView: WKWebView private var websiteDataStore: WKWebsiteDataStore + let browserWebExtensionHost: (any BrowserWebExtensionHosting)? var webViewDidRequestClose: (() -> Void)? /// Monotonic identity for the current WKWebView instance. @@ -3321,7 +3323,8 @@ final class BrowserPanel: Panel, ObservableObject { let replacement = Self.makeWebView( profileID: profileID, - websiteDataStore: websiteDataStore + websiteDataStore: websiteDataStore, + browserWebExtensionHost: browserWebExtensionHost ) replacement.pageZoom = desiredZoom webViewInstanceID = UUID() @@ -3536,12 +3539,14 @@ final class BrowserPanel: Panel, ObservableObject { // identical configuration, making adoption a drop-in swap. static func makeWebView( profileID: UUID, - websiteDataStore: WKWebsiteDataStore? = nil + websiteDataStore: WKWebsiteDataStore? = nil, + browserWebExtensionHost: (any BrowserWebExtensionHosting)? = nil ) -> CmuxWebView { let config = WKWebViewConfiguration() configureWebViewConfiguration( config, - websiteDataStore: websiteDataStore ?? BrowserProfileStore.shared.websiteDataStore(for: profileID) + websiteDataStore: websiteDataStore ?? BrowserProfileStore.shared.websiteDataStore(for: profileID), + browserWebExtensionHost: browserWebExtensionHost ) let webView = CmuxWebView(frame: .zero, configuration: config) @@ -3560,15 +3565,14 @@ final class BrowserPanel: Panel, ObservableObject { static func configureWebViewConfiguration( _ configuration: WKWebViewConfiguration, - websiteDataStore: WKWebsiteDataStore + websiteDataStore: WKWebsiteDataStore, + browserWebExtensionHost: (any BrowserWebExtensionHosting)? = nil ) { configuration.mediaTypesRequiringUserActionForPlayback = [] // Ensure browser cookies/storage persist across navigations and launches. // This reduces repeated consent/bot-challenge flows on sites like Google. configuration.websiteDataStore = websiteDataStore - if #available(macOS 15.4, *) { - BrowserWebExtensionSupport.shared.attach(to: configuration) - } + browserWebExtensionHost?.attach(to: configuration) if configuration.urlSchemeHandler(forURLScheme: CmuxDiffViewerURLSchemeHandler.scheme) == nil { configuration.setURLSchemeHandler( CmuxDiffViewerURLSchemeHandler.shared, @@ -3948,7 +3952,8 @@ final class BrowserPanel: Panel, ObservableObject { proxyEndpoint: BrowserProxyEndpoint? = nil, bypassRemoteProxy: Bool = false, isRemoteWorkspace: Bool = false, - remoteWebsiteDataStoreIdentifier: UUID? = nil + remoteWebsiteDataStoreIdentifier: UUID? = nil, + browserWebExtensionHost: (any BrowserWebExtensionHosting)? = nil ) { // Register fallback defaults and normalize legacy/out-of-range settings once // per process, before any setting is read below or by the SwiftUI view. @@ -3970,9 +3975,10 @@ final class BrowserPanel: Panel, ObservableObject { ? WKWebsiteDataStore(forIdentifier: remoteWebsiteDataStoreIdentifier ?? workspaceId) : BrowserProfileStore.shared.websiteDataStore(for: resolvedProfileID) self.websiteDataStore = websiteDataStore + self.browserWebExtensionHost = browserWebExtensionHost let webView: CmuxWebView var adoptedPrewarmedWebView = false - if let prewarmed = Self.claimedPrewarmedWebView( + if browserWebExtensionHost == nil, let prewarmed = Self.claimedPrewarmedWebView( isRemoteWorkspace: isRemoteWorkspace, initialRequest: initialRequest, renderInitialNavigation: renderInitialNavigation, @@ -3985,7 +3991,8 @@ final class BrowserPanel: Panel, ObservableObject { } else { webView = Self.makeWebView( profileID: resolvedProfileID, - websiteDataStore: websiteDataStore + websiteDataStore: websiteDataStore, + browserWebExtensionHost: browserWebExtensionHost ) } self.webView = webView @@ -3993,9 +4000,7 @@ final class BrowserPanel: Panel, ObservableObject { hiddenWebViewDiscardManager.delegate = self applyProxyConfigurationIfAvailable() BrowserProfileStore.shared.noteUsed(resolvedProfileID) - if #available(macOS 15.4, *) { - BrowserWebExtensionSupport.shared.register(panel: self) - } + browserWebExtensionHost?.register(panel: self) // Set up navigation delegate let navDelegate = BrowserNavigationDelegate() @@ -4628,7 +4633,8 @@ final class BrowserPanel: Panel, ObservableObject { let replacement = Self.makeWebView( profileID: resolvedProfileID, - websiteDataStore: websiteDataStore + websiteDataStore: websiteDataStore, + browserWebExtensionHost: browserWebExtensionHost ) replacement.pageZoom = desiredZoom webViewInstanceID = UUID() @@ -5137,7 +5143,8 @@ final class BrowserPanel: Panel, ObservableObject { let replacement = Self.makeWebView( profileID: profileID, - websiteDataStore: websiteDataStore + websiteDataStore: websiteDataStore, + browserWebExtensionHost: browserWebExtensionHost ) replacement.pageZoom = desiredZoom webViewInstanceID = UUID() @@ -5300,10 +5307,21 @@ final class BrowserPanel: Panel, ObservableObject { } } + func noteWebExtensionActivated() { + browserWebExtensionHost?.noteActivated(panelID: id) + } + + func performWebExtensionCommand(for event: NSEvent) -> Bool { + browserWebExtensionHost?.performCommand(for: event) ?? false + } + + @available(macOS 15.4, *) + var browserWebExtensionSupport: BrowserWebExtensionSupport? { + browserWebExtensionHost as? BrowserWebExtensionSupport + } + func close() { - if #available(macOS 15.4, *) { - BrowserWebExtensionSupport.shared.unregister(panelID: id) - } + browserWebExtensionHost?.unregister(panelID: id) cancelHiddenWebViewDiscard() isClosingWebViewLifecycle = true refreshWebViewLifecycleState() @@ -6151,7 +6169,8 @@ extension BrowserPanel { let replacement = Self.makeWebView( profileID: profileID, - websiteDataStore: websiteDataStore + websiteDataStore: websiteDataStore, + browserWebExtensionHost: browserWebExtensionHost ) webViewInstanceID = UUID() hasCommittedDocumentSinceWebViewReplacement = false; userStoppedLoadSinceWebViewReplacement = false diff --git a/Sources/Panels/BrowserPanelView.swift b/Sources/Panels/BrowserPanelView.swift index e29908949476..a2f6e4f27f36 100644 --- a/Sources/Panels/BrowserPanelView.swift +++ b/Sources/Panels/BrowserPanelView.swift @@ -1349,9 +1349,9 @@ struct BrowserPanelView: View { ) } - if #available(macOS 15.4, *) { + if #available(macOS 15.4, *), let support = panel.browserWebExtensionSupport { BrowserWebExtensionToolbarButtons( - support: BrowserWebExtensionSupport.shared, + support: support, panel: panel, iconPointSize: chromeMetrics.navigationIconFontSize, hitSize: addressBarButtonHitSize diff --git a/Sources/Panels/BrowserWebExtensionActionSnapshot.swift b/Sources/Panels/BrowserWebExtensionActionSnapshot.swift new file mode 100644 index 000000000000..db5ab718dc99 --- /dev/null +++ b/Sources/Panels/BrowserWebExtensionActionSnapshot.swift @@ -0,0 +1,16 @@ +import AppKit + +@available(macOS 15.4, *) +struct BrowserWebExtensionActionSnapshot: Identifiable { + let id: String + let displayName: String + let icon: NSImage? + + var accessibilityIdentifier: String { + let safeID = id.map { character in + character.isLetter || character.isNumber ? character : "-" + } + .reduce(into: "") { $0.append($1) } + return "BrowserWebExtensionActionButton-\(safeID)" + } +} diff --git a/Sources/Panels/BrowserWebExtensionDiscoveryService.swift b/Sources/Panels/BrowserWebExtensionDiscoveryService.swift index 974143521500..58e343cb5d25 100644 --- a/Sources/Panels/BrowserWebExtensionDiscoveryService.swift +++ b/Sources/Panels/BrowserWebExtensionDiscoveryService.swift @@ -36,29 +36,20 @@ actor BrowserWebExtensionDiscoveryService { return Self.parse(pluginkitOutput: output) } - /// Parses `pluginkit -m -A -v` machine listing: one plug-in per line, - /// tab-separated `identifier(version)`, UUID, timestamp, absolute path. + /// Parses `pluginkit -m -A -v` output. The tool is human-readable rather + /// than a documented TSV format, so each line is parsed by extracting the + /// `.appex` path first, then reading the leading identifier/version field. static func parse(pluginkitOutput: String) -> [BrowserWebExtensionCandidate] { var seen = Set() var candidates: [BrowserWebExtensionCandidate] = [] for line in pluginkitOutput.split(separator: "\n") { - let columns = line.split(separator: "\t").map { - $0.trimmingCharacters(in: .whitespaces) - } - guard let first = columns.first, columns.count >= 2 else { continue } - guard let path = columns.last, path.hasSuffix(".appex") else { continue } - - // `identifier(version)` — a leading `+`/`-`/`?` marks election state. - var identifierField = first - while let head = identifierField.first, ["+", "-", "?", "!"].contains(String(head)) { - identifierField = String(identifierField.dropFirst()).trimmingCharacters(in: .whitespaces) - } - var identifier = identifierField - var version: String? - if let open = identifierField.lastIndex(of: "("), identifierField.hasSuffix(")") { - identifier = String(identifierField[.. Range? { + guard let start = line.firstIndex(of: "/") else { return nil } + guard let end = line.range(of: ".appex", range: start.. (identifier: String, version: String?)? { + let normalizedPrefix = prefix + .split(separator: "\t") + .first + .map(String.init) ?? prefix + let trimmedPrefix = normalizedPrefix.trimmingCharacters(in: .whitespaces) + let pattern = #"^[+\-!?=\s]*([A-Za-z0-9][A-Za-z0-9._-]*\.[A-Za-z0-9._-]+)(?:\(([^)]*)\))?"# + guard let regex = try? NSRegularExpression(pattern: pattern) else { return nil } + let range = NSRange(trimmedPrefix.startIndex.. String? { diff --git a/Sources/Panels/BrowserWebExtensionHosting.swift b/Sources/Panels/BrowserWebExtensionHosting.swift new file mode 100644 index 000000000000..f58d513a1340 --- /dev/null +++ b/Sources/Panels/BrowserWebExtensionHosting.swift @@ -0,0 +1,11 @@ +import AppKit +import WebKit + +@MainActor +protocol BrowserWebExtensionHosting: AnyObject { + func attach(to configuration: WKWebViewConfiguration) + func register(panel: BrowserPanel) + func unregister(panelID: UUID) + func noteActivated(panelID: UUID) + func performCommand(for event: NSEvent) -> Bool +} diff --git a/Sources/Panels/BrowserWebExtensionLoadedRecord.swift b/Sources/Panels/BrowserWebExtensionLoadedRecord.swift new file mode 100644 index 000000000000..86f98d90ca29 --- /dev/null +++ b/Sources/Panels/BrowserWebExtensionLoadedRecord.swift @@ -0,0 +1,8 @@ +import WebKit + +@available(macOS 15.4, *) +struct BrowserWebExtensionLoadedRecord { + let entryID: String + let standardizedPath: String + let context: WKWebExtensionContext +} diff --git a/Sources/Panels/BrowserWebExtensionPopoutWindowController.swift b/Sources/Panels/BrowserWebExtensionPopoutWindowController.swift index 1c2775573f97..8f2fe74d2c98 100644 --- a/Sources/Panels/BrowserWebExtensionPopoutWindowController.swift +++ b/Sources/Panels/BrowserWebExtensionPopoutWindowController.swift @@ -27,7 +27,9 @@ final class BrowserWebExtensionPopoutWindowController: NSObject, WKWebExtensionW let webViewConfiguration = context.webViewConfiguration ?? WKWebViewConfiguration() webView = WKWebView(frame: .zero, configuration: webViewConfiguration) +#if DEBUG webView.isInspectable = true +#endif var frame = configuration.frame let usesFallbackFrame = frame.isNull || frame.isEmpty || frame.width < 50 || frame.height < 50 diff --git a/Sources/Panels/BrowserWebExtensionReconciliationPlanner.swift b/Sources/Panels/BrowserWebExtensionReconciliationPlanner.swift new file mode 100644 index 000000000000..03ca340c58f7 --- /dev/null +++ b/Sources/Panels/BrowserWebExtensionReconciliationPlanner.swift @@ -0,0 +1,80 @@ +import CmuxSettings +import Foundation + +struct BrowserWebExtensionReconciliationPlanner { + struct LoadedEntry: Equatable { + let id: String + let standardizedPath: String + } + + struct Plan: Equatable { + let desiredEntries: [BrowserWebExtensionEntry] + let unloadEntryIDs: [String] + let loadEntries: [BrowserWebExtensionEntry] + } + + func plan( + settingsEntries: [BrowserWebExtensionEntry], + environmentPaths: [String], + loadedEntries: [LoadedEntry] + ) -> Plan { + let loadedByID = Dictionary(uniqueKeysWithValues: loadedEntries.map { ($0.id, $0) }) + let desiredEntries = desired(settingsEntries: settingsEntries, environmentPaths: environmentPaths) + let desiredByID = Dictionary(uniqueKeysWithValues: desiredEntries.map { ($0.id, $0) }) + + let unloadEntryIDs = loadedEntries + .filter { loaded in + guard let desired = desiredByID[loaded.id] else { return true } + return Self.standardizedPath(desired.path) != loaded.standardizedPath + } + .map(\.id) + .sorted() + + let loadEntries = desiredEntries.filter { entry in + guard let loaded = loadedByID[entry.id] else { return true } + return loaded.standardizedPath != Self.standardizedPath(entry.path) + } + + return Plan( + desiredEntries: desiredEntries, + unloadEntryIDs: unloadEntryIDs, + loadEntries: loadEntries + ) + } + + static func standardizedPath(_ path: String) -> String { + URL(fileURLWithPath: path).standardizedFileURL.path + } + + private func desired( + settingsEntries: [BrowserWebExtensionEntry], + environmentPaths: [String] + ) -> [BrowserWebExtensionEntry] { + let settingsPaths = Set(settingsEntries.map { Self.standardizedPath($0.path) }) + var seenDesiredPaths = Set() + var desired: [BrowserWebExtensionEntry] = [] + var desiredIDs = Set() + + for entry in settingsEntries where entry.enabled { + let standardizedPath = Self.standardizedPath(entry.path) + guard seenDesiredPaths.insert(standardizedPath).inserted else { continue } + guard desiredIDs.insert(entry.id).inserted else { continue } + desired.append(entry) + } + + for path in environmentPaths { + let standardizedPath = Self.standardizedPath(path) + guard !settingsPaths.contains(standardizedPath) else { continue } + guard seenDesiredPaths.insert(standardizedPath).inserted else { continue } + guard desiredIDs.insert(path).inserted else { continue } + desired.append(BrowserWebExtensionEntry( + id: path, + kind: path.hasSuffix(".appex") ? .safariAppExtension : .unpackedDirectory, + path: path, + enabled: true + )) + } + + return desired + } +} diff --git a/Sources/Panels/BrowserWebExtensionSupport+Loading.swift b/Sources/Panels/BrowserWebExtensionSupport+Loading.swift new file mode 100644 index 000000000000..c4803a8d55ea --- /dev/null +++ b/Sources/Panels/BrowserWebExtensionSupport+Loading.swift @@ -0,0 +1,138 @@ +import CmuxSettings +import WebKit + +@available(macOS 15.4, *) +extension BrowserWebExtensionSupport { + var loadedRecordsInOrder: [BrowserWebExtensionLoadedRecord] { + loadedEntryIDsInOrder.compactMap { loadedByEntryID[$0] } + } + + func apply(entries: [BrowserWebExtensionEntry]) async { + let planner = BrowserWebExtensionReconciliationPlanner() + let plan = planner.plan( + settingsEntries: entries, + environmentPaths: Self.environmentExtensionPaths(), + loadedEntries: loadedByEntryID.values.map { + BrowserWebExtensionReconciliationPlanner.LoadedEntry( + id: $0.entryID, + standardizedPath: $0.standardizedPath + ) + } + ) + + for entryID in plan.unloadEntryIDs { + unload(entryID: entryID) + } + + for entry in plan.loadEntries where loadedByEntryID[entry.id] == nil { + await load(entry: entry) + } + + rebuildActionSnapshots() + } + + func context(forActionID actionID: String) -> WKWebExtensionContext? { + loadedByEntryID[actionID]?.context + } + + func rebuildActionSnapshots() { + actionSnapshots = loadedRecordsInOrder.map { record in + BrowserWebExtensionActionSnapshot( + id: record.entryID, + displayName: record.context.webExtension.displayName ?? String( + localized: "browser.webExtension.action.help", + defaultValue: "Extension" + ), + icon: record.context.webExtension.icon(for: CGSize(width: 32, height: 32)) + ) + } + } + + private func unload(entryID: String) { + guard let record = loadedByEntryID[entryID] else { return } + do { + try controller.unload(record.context) + } catch { + recordLoadError(error.localizedDescription, entryID: entryID) +#if DEBUG + cmuxDebugLog("browser.webext.unloadFailed id=\(entryID) error=\(error.localizedDescription)") +#endif + return + } + + loadedByEntryID[entryID] = nil + loadedEntryIDsInOrder.removeAll { $0 == entryID } + loadErrorsByEntryID.removeValue(forKey: entryID) + refreshLoadErrors() + + let closingPopouts = popouts.filter { $0.extensionContext === record.context } + for popout in closingPopouts { + popout.closeFromExtensionOrUser() + } +#if DEBUG + cmuxDebugLog("browser.webext.unloaded id=\(entryID)") +#endif + } + + private func load(entry: BrowserWebExtensionEntry) async { + do { + let webExtension = try await makeWebExtension(for: entry) + let context = try load(webExtension) + let standardizedPath = BrowserWebExtensionReconciliationPlanner.standardizedPath(entry.path) + loadedByEntryID[entry.id] = BrowserWebExtensionLoadedRecord( + entryID: entry.id, + standardizedPath: standardizedPath, + context: context + ) + if !loadedEntryIDsInOrder.contains(entry.id) { + loadedEntryIDsInOrder.append(entry.id) + } + loadErrorsByEntryID.removeValue(forKey: entry.id) + refreshLoadErrors() +#if DEBUG + cmuxDebugLog( + "browser.webext.loaded name=\(webExtension.displayName ?? "?") " + + "version=\(webExtension.displayVersion ?? "?") url=\(entry.path)" + ) +#endif + } catch { + recordLoadError(error.localizedDescription, entryID: entry.id) +#if DEBUG + cmuxDebugLog("browser.webext.loadFailed url=\(entry.path) error=\(error.localizedDescription)") +#endif + } + } + + private func makeWebExtension(for entry: BrowserWebExtensionEntry) async throws -> WKWebExtension { + let url = URL(fileURLWithPath: entry.path) + if entry.kind == .safariAppExtension, url.pathExtension == "appex" { + if let bundle = Bundle(url: url) { + return try await WKWebExtension(appExtensionBundle: bundle) + } + let resources = url.appendingPathComponent("Contents/Resources", isDirectory: true) + return try await WKWebExtension(resourceBaseURL: resources) + } + return try await WKWebExtension(resourceBaseURL: url) + } + + @discardableResult + private func load(_ webExtension: WKWebExtension) throws -> WKWebExtensionContext { + let context = WKWebExtensionContext(for: webExtension) +#if DEBUG + context.isInspectable = true +#endif + try controller.load(context) + return context + } + + private func recordLoadError(_ message: String, entryID: String) { + loadErrorsByEntryID[entryID] = "\(entryID): \(message)" + refreshLoadErrors() + } + + private func refreshLoadErrors() { + loadErrors = loadErrorsByEntryID + .sorted { $0.key < $1.key } + .map(\.value) + } +} diff --git a/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift b/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift new file mode 100644 index 000000000000..186a0ca96eac --- /dev/null +++ b/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift @@ -0,0 +1,234 @@ +import AppKit +import WebKit + +@available(macOS 15.4, *) +extension BrowserWebExtensionSupport: WKWebExtensionControllerDelegate { + func webExtensionController( + _ controller: WKWebExtensionController, + openWindowsFor extensionContext: WKWebExtensionContext + ) -> [any WKWebExtensionWindow] { + [windowAdapter] + popouts + } + + func webExtensionController( + _ controller: WKWebExtensionController, + focusedWindowFor extensionContext: WKWebExtensionContext + ) -> (any WKWebExtensionWindow)? { + popouts.first(where: \.isKeyWindow) ?? windowAdapter + } + + func webExtensionController( + _ controller: WKWebExtensionController, + openNewWindowUsing configuration: WKWebExtension.WindowConfiguration, + for extensionContext: WKWebExtensionContext, + completionHandler: @escaping ((any WKWebExtensionWindow)?, Error?) -> Void + ) { +#if DEBUG + cmuxDebugLog( + "browser.webext.openWindow type=\(configuration.windowType.rawValue) " + + "urls=\(configuration.tabURLs.count) focused=\(configuration.shouldBeFocused ? 1 : 0)" + ) +#endif + let popout = BrowserWebExtensionPopoutWindowController( + configuration: configuration, + context: extensionContext, + support: self + ) + popouts.append(popout) + controller.didOpenWindow(popout) + controller.didOpenTab(popout.tab) + completionHandler(popout, nil) + } + + func webExtensionController( + _ controller: WKWebExtensionController, + openNewTabUsing configuration: WKWebExtension.TabConfiguration, + for extensionContext: WKWebExtensionContext, + completionHandler: @escaping ((any WKWebExtensionTab)?, Error?) -> Void + ) { +#if DEBUG + cmuxDebugLog("browser.webext.openTab url=\(configuration.url?.absoluteString.prefix(80) ?? "nil")") +#endif + if let url = configuration.url, url.scheme == "https" || url.scheme == "http" { + NSWorkspace.shared.open(url) + completionHandler(nil, nil) + return + } + completionHandler(nil, NSError( + domain: "cmux.webExtension", + code: 2, + userInfo: [NSLocalizedDescriptionKey: String( + localized: "browser.webExtension.error.openTabsUnsupported", + defaultValue: "Opening extension tabs is not supported yet." + )] + )) + } + + func webExtensionController( + _ controller: WKWebExtensionController, + presentActionPopup action: WKWebExtension.Action, + for context: WKWebExtensionContext, + completionHandler: @escaping (Error?) -> Void + ) { + guard let popover = action.popupPopover else { + completionHandler(nil) + return + } + let candidates: [NSView?] = [ + pendingPopupAnchorView, + activeTabAdapter?.panel?.webView, + orderedTabAdapters.first(where: { $0.panel?.webView.window != nil })?.panel?.webView, + NSApp.keyWindow?.contentView ?? NSApp.mainWindow?.contentView, + ] + pendingPopupAnchorView = nil + guard let anchor = candidates.compactMap({ $0 }).first(where: { $0.window != nil }) else { +#if DEBUG + cmuxDebugLog("browser.webext.actionPopup no window-attached anchor; dropping popup") +#endif + completionHandler(nil) + return + } + popover.behavior = .transient + popover.show(relativeTo: anchor.bounds, of: anchor, preferredEdge: .maxY) + completionHandler(nil) + } + + func webExtensionController( + _ controller: WKWebExtensionController, + sendMessage message: Any, + toApplicationWithIdentifier applicationIdentifier: String?, + for extensionContext: WKWebExtensionContext, + replyHandler: @escaping (Any?, Error?) -> Void + ) { + // Native messaging (e.g. Bitwarden's desktop-app biometrics IPC) is not + // bridged. Never resolve the reply: an error reply sends Bitwarden into + // an unthrottled reconnect loop (observed ~175k messages/sec), while an + // unresolved promise parks the caller harmlessly. + nativeMessageDropCount += 1 + if nativeMessageDropCount <= 5 { +#if DEBUG + cmuxDebugLog( + "browser.webext.nativeMessage dropped app=\(applicationIdentifier ?? "nil") " + + "count=\(nativeMessageDropCount)" + ) +#endif + } + _ = replyHandler + } + + func webExtensionController( + _ controller: WKWebExtensionController, + connectUsing port: WKWebExtension.MessagePort, + for extensionContext: WKWebExtensionContext, + completionHandler: @escaping (Error?) -> Void + ) { + // See sendMessage above: leave the native port unresolved rather than + // erroring, so extensions do not retry-loop. +#if DEBUG + cmuxDebugLog("browser.webext.nativeConnect dropped app=\(port.applicationIdentifier ?? "nil")") +#endif + _ = completionHandler + } + + func webExtensionController( + _ controller: WKWebExtensionController, + promptForPermissions permissions: Set, + in tab: (any WKWebExtensionTab)?, + for extensionContext: WKWebExtensionContext, + completionHandler: @escaping (Set, Date?) -> Void + ) { + let requested = permissions + .map { String(describing: $0) } + .sorted() + .joined(separator: "\n") + let allowed = confirmPermissionRequest( + informativeText: permissionMessage( + extensionContext: extensionContext, + details: requested, + key: "browser.webExtension.permissionPrompt.permissions.message", + defaultValue: "The extension “%@” wants these browser permissions:\n\n%@" + ) + ) + completionHandler(allowed ? permissions : [], nil) + } + + func webExtensionController( + _ controller: WKWebExtensionController, + promptForPermissionToAccess urls: Set, + in tab: (any WKWebExtensionTab)?, + for extensionContext: WKWebExtensionContext, + completionHandler: @escaping (Set, Date?) -> Void + ) { + let requested = urls + .map(\.absoluteString) + .sorted() + .joined(separator: "\n") + let allowed = confirmPermissionRequest( + informativeText: permissionMessage( + extensionContext: extensionContext, + details: requested, + key: "browser.webExtension.permissionPrompt.urls.message", + defaultValue: "The extension “%@” wants access to these pages:\n\n%@" + ) + ) + completionHandler(allowed ? urls : [], nil) + } + + func webExtensionController( + _ controller: WKWebExtensionController, + promptForPermissionMatchPatterns matchPatterns: Set, + in tab: (any WKWebExtensionTab)?, + for extensionContext: WKWebExtensionContext, + completionHandler: @escaping (Set, Date?) -> Void + ) { + let requested = matchPatterns + .map { String(describing: $0) } + .sorted() + .joined(separator: "\n") + let allowed = confirmPermissionRequest( + informativeText: permissionMessage( + extensionContext: extensionContext, + details: requested, + key: "browser.webExtension.permissionPrompt.matchPatterns.message", + defaultValue: "The extension “%@” wants access to matching pages:\n\n%@" + ) + ) + completionHandler(allowed ? matchPatterns : [], nil) + } + + private func permissionMessage( + extensionContext: WKWebExtensionContext, + details: String, + key: String.LocalizationValue, + defaultValue: String.LocalizationValue + ) -> String { + let extensionName = extensionContext.webExtension.displayName ?? String( + localized: "browser.webExtension.action.help", + defaultValue: "Extension" + ) + return String( + format: String(localized: key, defaultValue: defaultValue), + extensionName, + details + ) + } + + private func confirmPermissionRequest(informativeText: String) -> Bool { + let alert = NSAlert() + alert.alertStyle = .warning + alert.messageText = String( + localized: "browser.webExtension.permissionPrompt.title", + defaultValue: "Allow Extension Access?" + ) + alert.informativeText = informativeText + alert.addButton(withTitle: String( + localized: "browser.webExtension.permissionPrompt.allow", + defaultValue: "Allow" + )) + alert.addButton(withTitle: String( + localized: "browser.webExtension.permissionPrompt.deny", + defaultValue: "Deny" + )) + return alert.runModal() == .alertFirstButtonReturn + } +} diff --git a/Sources/Panels/BrowserWebExtensionSupport.swift b/Sources/Panels/BrowserWebExtensionSupport.swift index 84421f93433b..d0da8c1c9ca9 100644 --- a/Sources/Panels/BrowserWebExtensionSupport.swift +++ b/Sources/Panels/BrowserWebExtensionSupport.swift @@ -1,53 +1,68 @@ import AppKit import CmuxSettings +import Observation import SwiftUI import WebKit /// Hosts Chrome/Safari-style web extensions in the built-in browser via WebKit's /// native `WKWebExtensionController` API (macOS 15.4+). /// -/// One shared controller (persistent storage keyed by a fixed identifier) is attached -/// to every browser `WKWebViewConfiguration`. Extensions come from: +/// The app composition root owns one instance and injects it into browser panels. +/// Its persistent controller identifier keeps extension storage stable across app +/// launches. Extensions come from: /// - the `browser.webExtensions` entries in cmux settings (managed in /// Settings → Browser → Extensions), and /// - directories listed in the `CMUX_BROWSER_EXTENSIONS` environment variable /// (colon-separated paths to unpacked extensions or `.appex` bundles). @available(macOS 15.4, *) @MainActor -final class BrowserWebExtensionSupport: NSObject, ObservableObject { - static let shared = BrowserWebExtensionSupport() - +@Observable +final class BrowserWebExtensionSupport: NSObject, BrowserWebExtensionHosting { /// Fixed identifier so extension storage (e.g. the Bitwarden vault cache) /// persists across app launches. private static let controllerIdentifier = UUID(uuidString: "8C0FDE2B-6EFD-4E8C-9E70-8E7D0A4C51B7")! + @ObservationIgnored let controller: WKWebExtensionController - @Published private(set) var contexts: [WKWebExtensionContext] = [] - @Published private(set) var loadErrors: [String] = [] - - private var settingsObservationTask: Task? - private var loadedByEntryID: [String: WKWebExtensionContext] = [:] - private var tabAdapters: [UUID: BrowserWebExtensionTabAdapter] = [:] - private var orderedPanelIDs: [UUID] = [] + var actionSnapshots: [BrowserWebExtensionActionSnapshot] = [] + var loadErrors: [String] = [] + + @ObservationIgnored + var settingsObservationTask: Task? + @ObservationIgnored + var loadedByEntryID: [String: BrowserWebExtensionLoadedRecord] = [:] + @ObservationIgnored + var loadedEntryIDsInOrder: [String] = [] + @ObservationIgnored + var loadErrorsByEntryID: [String: String] = [:] + @ObservationIgnored + var tabAdapters: [UUID: BrowserWebExtensionTabAdapter] = [:] + @ObservationIgnored + var orderedPanelIDs: [UUID] = [] + @ObservationIgnored private(set) var activePanelID: UUID? + @ObservationIgnored private(set) lazy var windowAdapter = BrowserWebExtensionWindowAdapter(support: self) - private var popouts: [BrowserWebExtensionPopoutWindowController] = [] + @ObservationIgnored + var popouts: [BrowserWebExtensionPopoutWindowController] = [] /// Anchor for the next action popup presentation, set by the toolbar button /// immediately before calling `performAction(context:panel:anchorView:)`. - private weak var pendingPopupAnchorView: NSView? + @ObservationIgnored + weak var pendingPopupAnchorView: NSView? - private var nativeMessageDropCount = 0 + @ObservationIgnored + var nativeMessageDropCount = 0 - private override init() { + override init() { let configuration = WKWebExtensionController.Configuration(identifier: Self.controllerIdentifier) // Extension-owned web views (background page, action popup) get WebKit's // default user agent, which lacks the " Safari/" token. Extensions like // Bitwarden classify the browser from the UA and crash on an unknown one, // so present the same Safari application identity the browser panels use. let webViewConfiguration = configuration.webViewConfiguration ?? WKWebViewConfiguration() - webViewConfiguration.applicationNameForUserAgent = "Version/26.2 Safari/605.1.15" + webViewConfiguration.applicationNameForUserAgent = BrowserUserAgentSettings.safariApplicationNameForUserAgent configuration.webViewConfiguration = webViewConfiguration controller = WKWebExtensionController(configuration: configuration) super.init() @@ -78,125 +93,11 @@ final class BrowserWebExtensionSupport: NSObject, ObservableObject { } } - private func apply(entries: [BrowserWebExtensionEntry]) async { - var desired: [String: BrowserWebExtensionEntry] = [:] - for entry in entries where entry.enabled { - desired[entry.id] = entry - } - // A settings entry for the same path — enabled or not — always wins - // over the env override, so a user's "disabled" toggle sticks and the - // same extension never loads twice under two different ids. - let standardizedSettingsPaths = Set(entries.map { URL(fileURLWithPath: $0.path).standardizedFileURL.path }) - for path in Self.environmentExtensionPaths() { - let standardized = URL(fileURLWithPath: path).standardizedFileURL.path - guard desired[path] == nil, !standardizedSettingsPaths.contains(standardized) else { continue } - desired[path] = BrowserWebExtensionEntry( - id: path, - kind: path.hasSuffix(".appex") ? .safariAppExtension : .unpackedDirectory, - path: path, - enabled: true - ) - } - - for (entryID, context) in loadedByEntryID where desired[entryID] == nil { - try? controller.unload(context) - loadedByEntryID[entryID] = nil - contexts.removeAll { $0 === context } - // Close any popout windows the now-unloaded extension had open - // (e.g. a Bitwarden unlock popout) instead of leaving orphans. - for popout in popouts where popout.extensionContext === context { - popout.closeFromExtensionOrUser() - } -#if DEBUG - cmuxDebugLog("browser.webext.unloaded id=\(entryID)") -#endif - } - - for (entryID, entry) in desired where loadedByEntryID[entryID] == nil { - do { - let url = URL(fileURLWithPath: entry.path) - let webExtension: WKWebExtension - if entry.kind == .safariAppExtension, url.pathExtension == "appex" { - if let bundle = Bundle(url: url) { - webExtension = try await WKWebExtension(appExtensionBundle: bundle) - } else { - // Fall back to reading the appex's web-extension resources directly. - let resources = url.appendingPathComponent("Contents/Resources", isDirectory: true) - webExtension = try await WKWebExtension(resourceBaseURL: resources) - } - } else { - webExtension = try await WKWebExtension(resourceBaseURL: url) - } - let context = try load(webExtension) - loadedByEntryID[entryID] = context -#if DEBUG - cmuxDebugLog( - "browser.webext.loaded name=\(webExtension.displayName ?? "?") " + - "version=\(webExtension.displayVersion ?? "?") url=\(entry.path)" - ) -#endif - } catch { - loadErrors.append("\(entry.id): \(error.localizedDescription)") -#if DEBUG - cmuxDebugLog("browser.webext.loadFailed url=\(entry.path) error=\(error.localizedDescription)") -#endif - } - } - } - - private static func environmentExtensionPaths() -> [String] { + static func environmentExtensionPaths() -> [String] { guard let env = ProcessInfo.processInfo.environment["CMUX_BROWSER_EXTENSIONS"] else { return [] } return env.split(separator: ":").map(String.init).filter { !$0.isEmpty } } - @discardableResult - private func load(_ webExtension: WKWebExtension) throws -> WKWebExtensionContext { - let context = WKWebExtensionContext(for: webExtension) - // Grant everything the manifest requests up front; interactive permission - // prompting can come later. Repeat grants are also answered by the - // prompt delegate methods below. - for permission in webExtension.requestedPermissions { - context.setPermissionStatus(.grantedExplicitly, for: permission) - } - for pattern in webExtension.allRequestedMatchPatterns { - context.setPermissionStatus(.grantedExplicitly, for: pattern) - } -#if DEBUG - context.isInspectable = true -#endif - try controller.load(context) - contexts.append(context) -#if DEBUG - logDiagnostics(for: context, label: "postLoad") -#endif - return context - } - -#if DEBUG - private func logDiagnostics(for context: WKWebExtensionContext, label: String) { - let ext = context.webExtension - cmuxDebugLog( - "browser.webext.diag(\(label)) name=\(ext.displayName ?? "?") " + - "loaded=\(context.isLoaded ? 1 : 0) " + - "injected=\(ext.hasInjectedContent ? 1 : 0) " + - "background=\(ext.hasBackgroundContent ? 1 : 0) " + - "allURLs=\(context.hasAccessToAllURLs ? 1 : 0) " + - "perms=\(context.currentPermissions.count) " + - "patterns=\(context.currentPermissionMatchPatterns.count) " + - "openTabs=\(context.openTabs.count) " + - "ctxErrors=\(context.errors.map(\.localizedDescription).joined(separator: " | ")) " + - "extErrors=\(ext.errors.map(\.localizedDescription).joined(separator: " | "))" - ) - for command in context.commands { - cmuxDebugLog( - "browser.webext.command registered id=\(command.id) " + - "key=\(command.activationKey ?? "nil") mods=\(command.modifierFlags.rawValue) " + - "title=\(command.title)" - ) - } - } -#endif - // MARK: - Tab lifecycle (called from BrowserPanel) func register(panel: BrowserPanel) { @@ -262,9 +163,9 @@ final class BrowserWebExtensionSupport: NSObject, ObservableObject { /// Offers a key equivalent to loaded extensions' declared commands /// (e.g. Bitwarden's ⌘⇧L autofill). Returns true when one handled it. func performCommand(for event: NSEvent) -> Bool { - for context in contexts where context.performCommand(for: event) { + for record in loadedRecordsInOrder where record.context.performCommand(for: event) { #if DEBUG - cmuxDebugLog("browser.webext.command handled name=\(context.webExtension.displayName ?? "?")") + cmuxDebugLog("browser.webext.command handled name=\(record.context.webExtension.displayName ?? "?")") #endif return true } @@ -280,164 +181,3 @@ final class BrowserWebExtensionSupport: NSObject, ObservableObject { controller.didCloseWindow(popout) } } - -// MARK: - WKWebExtensionControllerDelegate - -@available(macOS 15.4, *) -extension BrowserWebExtensionSupport: WKWebExtensionControllerDelegate { - func webExtensionController( - _ controller: WKWebExtensionController, - openWindowsFor extensionContext: WKWebExtensionContext - ) -> [any WKWebExtensionWindow] { - [windowAdapter] + popouts - } - - func webExtensionController( - _ controller: WKWebExtensionController, - focusedWindowFor extensionContext: WKWebExtensionContext - ) -> (any WKWebExtensionWindow)? { - popouts.first(where: \.isKeyWindow) ?? windowAdapter - } - - func webExtensionController( - _ controller: WKWebExtensionController, - openNewWindowUsing configuration: WKWebExtension.WindowConfiguration, - for extensionContext: WKWebExtensionContext, - completionHandler: @escaping ((any WKWebExtensionWindow)?, Error?) -> Void - ) { -#if DEBUG - cmuxDebugLog( - "browser.webext.openWindow type=\(configuration.windowType.rawValue) " + - "urls=\(configuration.tabURLs.count) focused=\(configuration.shouldBeFocused ? 1 : 0)" - ) -#endif - let popout = BrowserWebExtensionPopoutWindowController( - configuration: configuration, - context: extensionContext, - support: self - ) - popouts.append(popout) - controller.didOpenWindow(popout) - controller.didOpenTab(popout.tab) - completionHandler(popout, nil) - } - - func webExtensionController( - _ controller: WKWebExtensionController, - openNewTabUsing configuration: WKWebExtension.TabConfiguration, - for extensionContext: WKWebExtensionContext, - completionHandler: @escaping ((any WKWebExtensionTab)?, Error?) -> Void - ) { -#if DEBUG - cmuxDebugLog("browser.webext.openTab url=\(configuration.url?.absoluteString.prefix(80) ?? "nil")") -#endif - // External pages go to the user's default browser context inside cmux - // panels eventually; for now open http(s) URLs via the system and host - // extension pages in a popout window. - if let url = configuration.url, url.scheme == "https" || url.scheme == "http" { - NSWorkspace.shared.open(url) - completionHandler(nil, nil) - return - } - completionHandler(nil, NSError( - domain: "cmux.webExtension", code: 2, - userInfo: [NSLocalizedDescriptionKey: "Opening extension tabs is not supported yet"] - )) - } - - func webExtensionController( - _ controller: WKWebExtensionController, - presentActionPopup action: WKWebExtension.Action, - for context: WKWebExtensionContext, - completionHandler: @escaping (Error?) -> Void - ) { - guard let popover = action.popupPopover else { - completionHandler(nil) - return - } - let candidates: [NSView?] = [ - pendingPopupAnchorView, - activeTabAdapter?.panel?.webView, - orderedTabAdapters.first(where: { $0.panel?.webView.window != nil })?.panel?.webView, - NSApp.keyWindow?.contentView ?? NSApp.mainWindow?.contentView, - ] - pendingPopupAnchorView = nil - guard let anchor = candidates.compactMap({ $0 }).first(where: { $0.window != nil }) else { -#if DEBUG - cmuxDebugLog("browser.webext.actionPopup no window-attached anchor; dropping popup") -#endif - completionHandler(nil) - return - } - popover.behavior = .transient - popover.show(relativeTo: anchor.bounds, of: anchor, preferredEdge: .maxY) - completionHandler(nil) - } - - func webExtensionController( - _ controller: WKWebExtensionController, - sendMessage message: Any, - toApplicationWithIdentifier applicationIdentifier: String?, - for extensionContext: WKWebExtensionContext, - replyHandler: @escaping (Any?, Error?) -> Void - ) { - // Native messaging (e.g. Bitwarden's desktop-app biometrics IPC) is not - // bridged. Never resolve the reply: an error reply sends Bitwarden into - // an unthrottled reconnect loop (observed ~175k messages/sec), while an - // unresolved promise parks the caller harmlessly. - nativeMessageDropCount += 1 - if nativeMessageDropCount <= 5 { -#if DEBUG - cmuxDebugLog( - "browser.webext.nativeMessage dropped app=\(applicationIdentifier ?? "nil") " + - "count=\(nativeMessageDropCount)" - ) -#endif - } - _ = replyHandler - } - - func webExtensionController( - _ controller: WKWebExtensionController, - connectUsing port: WKWebExtension.MessagePort, - for extensionContext: WKWebExtensionContext, - completionHandler: @escaping (Error?) -> Void - ) { - // See sendMessage above: leave the native port unresolved rather than - // erroring, so extensions do not retry-loop. -#if DEBUG - cmuxDebugLog("browser.webext.nativeConnect dropped app=\(port.applicationIdentifier ?? "nil")") -#endif - _ = completionHandler - } - - func webExtensionController( - _ controller: WKWebExtensionController, - promptForPermissions permissions: Set, - in tab: (any WKWebExtensionTab)?, - for extensionContext: WKWebExtensionContext, - completionHandler: @escaping (Set, Date?) -> Void - ) { - completionHandler(permissions, nil) - } - - func webExtensionController( - _ controller: WKWebExtensionController, - promptForPermissionToAccess urls: Set, - in tab: (any WKWebExtensionTab)?, - for extensionContext: WKWebExtensionContext, - completionHandler: @escaping (Set, Date?) -> Void - ) { - completionHandler(urls, nil) - } - - func webExtensionController( - _ controller: WKWebExtensionController, - promptForPermissionMatchPatterns matchPatterns: Set, - in tab: (any WKWebExtensionTab)?, - for extensionContext: WKWebExtensionContext, - completionHandler: @escaping (Set, Date?) -> Void - ) { - completionHandler(matchPatterns, nil) - } -} diff --git a/Sources/Panels/BrowserWebExtensionToolbarButtons.swift b/Sources/Panels/BrowserWebExtensionToolbarButtons.swift index 528dc0eef0a1..03ca93b5c23d 100644 --- a/Sources/Panels/BrowserWebExtensionToolbarButtons.swift +++ b/Sources/Panels/BrowserWebExtensionToolbarButtons.swift @@ -6,19 +6,22 @@ import WebKit /// anchored so the extension's popup (e.g. the Bitwarden vault) opens beneath it. @available(macOS 15.4, *) struct BrowserWebExtensionToolbarButtons: View { - @ObservedObject var support: BrowserWebExtensionSupport + let support: BrowserWebExtensionSupport let panel: BrowserPanel let iconPointSize: CGFloat let hitSize: CGFloat var body: some View { - ForEach(Array(support.contexts.enumerated()), id: \.offset) { _, context in + ForEach(support.actionSnapshots) { snapshot in BrowserWebExtensionActionButton( - support: support, - context: context, + snapshot: snapshot, panel: panel, iconPointSize: iconPointSize, - hitSize: hitSize + hitSize: hitSize, + performAction: { anchorView in + guard let context = support.context(forActionID: snapshot.id) else { return } + support.performAction(context: context, panel: panel, anchorView: anchorView) + } ) } } @@ -26,11 +29,11 @@ struct BrowserWebExtensionToolbarButtons: View { @available(macOS 15.4, *) private struct BrowserWebExtensionActionButton: View { - let support: BrowserWebExtensionSupport - let context: WKWebExtensionContext + let snapshot: BrowserWebExtensionActionSnapshot let panel: BrowserPanel let iconPointSize: CGFloat let hitSize: CGFloat + let performAction: (NSView?) -> Void @State private var anchorViewHolder = BrowserWebExtensionAnchorViewHolder() @@ -39,10 +42,10 @@ private struct BrowserWebExtensionActionButton: View { #if DEBUG cmuxDebugLog( "browser.webext.action panel=\(panel.id.uuidString.prefix(5)) " + - "name=\(context.webExtension.displayName ?? "?")" + "name=\(snapshot.displayName)" ) #endif - support.performAction(context: context, panel: panel, anchorView: anchorViewHolder.view) + performAction(anchorViewHolder.view) }) { actionIcon .frame(width: hitSize, height: hitSize, alignment: .center) @@ -50,16 +53,13 @@ private struct BrowserWebExtensionActionButton: View { } .buttonStyle(OmnibarAddressButtonStyle()) .background(BrowserWebExtensionAnchorViewReader(holder: anchorViewHolder)) - .safeHelp(context.webExtension.displayName ?? String( - localized: "browser.webExtension.action.help", - defaultValue: "Extension" - )) - .accessibilityIdentifier("BrowserWebExtensionActionButton") + .safeHelp(snapshot.displayName) + .accessibilityIdentifier(snapshot.accessibilityIdentifier) } @ViewBuilder private var actionIcon: some View { - if let icon = context.webExtension.icon(for: CGSize(width: 32, height: 32)) { + if let icon = snapshot.icon { Image(nsImage: icon) .resizable() .aspectRatio(contentMode: .fit) diff --git a/Sources/Panels/BrowserWebExtensionWindowAdapter.swift b/Sources/Panels/BrowserWebExtensionWindowAdapter.swift index ebe4eb324031..0b3af2122fbd 100644 --- a/Sources/Panels/BrowserWebExtensionWindowAdapter.swift +++ b/Sources/Panels/BrowserWebExtensionWindowAdapter.swift @@ -45,6 +45,19 @@ final class BrowserWebExtensionWindowAdapter: NSObject, WKWebExtensionWindow { } func focus(for context: WKWebExtensionContext, completionHandler: @escaping (Error?) -> Void) { + guard let hostWindow else { + completionHandler(NSError( + domain: "cmux.webExtension", + code: 3, + userInfo: [NSLocalizedDescriptionKey: String( + localized: "browser.webExtension.error.noBrowserWindow", + defaultValue: "No browser window is available." + )] + )) + return + } + NSApp.activate(ignoringOtherApps: false) + hostWindow.makeKeyAndOrderFront(nil) completionHandler(nil) } diff --git a/Sources/Panels/CmuxWebView.swift b/Sources/Panels/CmuxWebView.swift index 9a235539a9da..2f2233dcbb3b 100644 --- a/Sources/Panels/CmuxWebView.swift +++ b/Sources/Panels/CmuxWebView.swift @@ -702,7 +702,7 @@ final class CmuxWebView: WKWebView { // Web-extension commands (e.g. Bitwarden's ⌘⇧L autofill) match only // shortcuts the extension manifest declares; everything else falls through. if #available(macOS 15.4, *), - BrowserWebExtensionSupport.shared.performCommand(for: event) { + AppDelegate.shared?.shortcutEventBrowserPanel(event)?.performWebExtensionCommand(for: event) == true { return finish(true) } diff --git a/Sources/TabManager+DetachedWorkspace.swift b/Sources/TabManager+DetachedWorkspace.swift index 430f24b01541..44a8d85f8f72 100644 --- a/Sources/TabManager+DetachedWorkspace.swift +++ b/Sources/TabManager+DetachedWorkspace.swift @@ -65,6 +65,7 @@ extension TabManager { workingDirectory: normalizedWorkingDirectory(detached.directory) ?? snapshot.preferredWorkingDirectory, portOrdinal: ordinal, configTemplate: inheritedConfig, + browserWebExtensionHost: browserWebExtensionHost, initialDetachedSurface: detached ) guard newWorkspace.panels[detached.panelId] != nil, diff --git a/Sources/TabManager.swift b/Sources/TabManager.swift index 48c4fb9dae83..3da97c9a8f33 100644 --- a/Sources/TabManager.swift +++ b/Sources/TabManager.swift @@ -391,6 +391,7 @@ class TabManager: ObservableObject { /// Typed synchronous settings access (CmuxSettings). private let settings: any SettingsWriting private let settingsCatalog = SettingCatalog() + let browserWebExtensionHost: (any BrowserWebExtensionHosting)? @Published private(set) var focusHistoryRevision: UInt64 = 0 { didSet { @@ -469,9 +470,11 @@ class TabManager: ObservableObject { gitProbeLimiter: WorkspaceGitMetadataProbeLimiter? = nil, panelTitleUpdateCoalescer: NotificationBurstCoalescer? = nil, settings: any SettingsWriting = UserDefaultsSettingsClient(defaults: .standard), + browserWebExtensionHost: (any BrowserWebExtensionHosting)? = nil, closeTabWarningDefaults: UserDefaults = .standard ) { self.settings = settings + self.browserWebExtensionHost = browserWebExtensionHost self.panelTitleUpdateCoalescer = panelTitleUpdateCoalescer ?? NotificationBurstCoalescer() self.closeTabWarningDefaults = closeTabWarningDefaults workspaceReordering = WorkspaceReorderCoordinator(model: workspaces) @@ -950,6 +953,7 @@ class TabManager: ObservableObject { initialBrowserTransparentBackground: initialBrowserTransparentBackground, workspaceEnvironment: workspaceEnvironment, allowTextBoxFocusDefault: allowTextBoxFocusDefault, + browserWebExtensionHost: browserWebExtensionHost, closeTabWarningDefaults: closeTabWarningDefaults ) } @@ -5981,6 +5985,7 @@ extension TabManager { title: workspaceSnapshot.processTitle, workingDirectory: workspaceSnapshot.currentDirectory, portOrdinal: ordinal, + browserWebExtensionHost: browserWebExtensionHost, closeTabWarningDefaults: closeTabWarningDefaults ) workspace.owningTabManager = self @@ -5994,7 +5999,12 @@ extension TabManager { if newTabs.isEmpty { let ordinal = Self.nextPortOrdinal Self.nextPortOrdinal += 1 - let fallback = Workspace(title: "Terminal 1", portOrdinal: ordinal, closeTabWarningDefaults: closeTabWarningDefaults) + let fallback = Workspace( + title: "Terminal 1", + portOrdinal: ordinal, + browserWebExtensionHost: browserWebExtensionHost, + closeTabWarningDefaults: closeTabWarningDefaults + ) fallback.owningTabManager = self wireClosedBrowserTracking(for: fallback) newTabs.append(fallback) diff --git a/Sources/Workspace+DockBrowserLookup.swift b/Sources/Workspace+DockBrowserLookup.swift index 17beb6e87d7e..7dd3a75fcf79 100644 --- a/Sources/Workspace+DockBrowserLookup.swift +++ b/Sources/Workspace+DockBrowserLookup.swift @@ -109,7 +109,8 @@ extension DockSplitStore { proxyEndpoint: settings.proxyEndpoint, bypassRemoteProxy: settings.bypassRemoteProxy, isRemoteWorkspace: settings.isRemoteWorkspace, - remoteWebsiteDataStoreIdentifier: settings.remoteWebsiteDataStoreIdentifier + remoteWebsiteDataStoreIdentifier: settings.remoteWebsiteDataStoreIdentifier, + browserWebExtensionHost: browserWebExtensionHost ) panel.setRemoteWorkspaceStatus(settings.remoteStatus) panel.webViewDidRequestClose = { [weak self, weak panel] in diff --git a/Sources/Workspace.swift b/Sources/Workspace.swift index 06e8ff1f61b8..fb9ffa1133a2 100644 --- a/Sources/Workspace.swift +++ b/Sources/Workspace.swift @@ -1997,6 +1997,7 @@ final class Workspace: Identifiable, ObservableObject { @Published private(set) var surfaceTabBarDirectory: String? private(set) var preferredBrowserProfileID: UUID? let closeTabWarningDefaults, agentSessionAutoResumeDefaults: UserDefaults + let browserWebExtensionHost: (any BrowserWebExtensionHosting)? /// Ordinal for CMUX_PORT range assignment (monotonically increasing per app session) var portOrdinal: Int = 0 @@ -2026,7 +2027,8 @@ final class Workspace: Identifiable, ObservableObject { remoteWebsiteDataStoreIdentifier: self.isRemoteWorkspace ? self.id : nil, remoteStatus: self.browserRemoteWorkspaceStatusSnapshot() ) - } + }, + browserWebExtensionHost: browserWebExtensionHost ) _dockSplit = store return store @@ -2859,6 +2861,7 @@ final class Workspace: Identifiable, ObservableObject { initialBrowserTransparentBackground: Bool = false, workspaceEnvironment: [String: String] = [:], allowTextBoxFocusDefault: Bool = true, + browserWebExtensionHost: (any BrowserWebExtensionHosting)? = nil, closeTabWarningDefaults: UserDefaults = .standard, agentSessionAutoResumeDefaults: UserDefaults = .standard, initialDetachedSurface: DetachedSurfaceTransfer? = nil, @@ -2870,6 +2873,7 @@ final class Workspace: Identifiable, ObservableObject { self.sidebarProcessTitleObservation = sidebarProcessTitleObservation ?? WorkspaceSidebarProcessTitleObservationModel() self.closeTabWarningDefaults = closeTabWarningDefaults self.agentSessionAutoResumeDefaults = agentSessionAutoResumeDefaults + self.browserWebExtensionHost = browserWebExtensionHost let sanitizedWorkspaceEnvironment = Self.sanitizedWorkspaceEnvironment(workspaceEnvironment) self.workspaceEnvironment = sanitizedWorkspaceEnvironment self.portOrdinal = portOrdinal @@ -2941,7 +2945,8 @@ final class Workspace: Identifiable, ObservableObject { profileID: resolvedNewBrowserProfileID(), initialURL: initialBrowserURL, omnibarVisible: initialBrowserOmnibarVisible, - transparentBackground: initialBrowserTransparentBackground + transparentBackground: initialBrowserTransparentBackground, + browserWebExtensionHost: browserWebExtensionHost ) configureBrowserPanel(browserPanel) panels[browserPanel.id] = browserPanel @@ -7956,7 +7961,8 @@ final class Workspace: Identifiable, ObservableObject { proxyEndpoint: remoteProxyEndpoint, bypassRemoteProxy: bypassRemoteProxy, isRemoteWorkspace: isRemoteWorkspace, - remoteWebsiteDataStoreIdentifier: isRemoteWorkspace && !bypassRemoteProxy ? id : nil + remoteWebsiteDataStoreIdentifier: isRemoteWorkspace && !bypassRemoteProxy ? id : nil, + browserWebExtensionHost: browserWebExtensionHost ) configureBrowserPanel(browserPanel) panels[browserPanel.id] = browserPanel @@ -8065,7 +8071,8 @@ final class Workspace: Identifiable, ObservableObject { proxyEndpoint: remoteProxyEndpoint, bypassRemoteProxy: bypassRemoteProxy, isRemoteWorkspace: isRemoteWorkspace, - remoteWebsiteDataStoreIdentifier: isRemoteWorkspace && !bypassRemoteProxy ? id : nil + remoteWebsiteDataStoreIdentifier: isRemoteWorkspace && !bypassRemoteProxy ? id : nil, + browserWebExtensionHost: browserWebExtensionHost ) configureBrowserPanel(browserPanel) panels[browserPanel.id] = browserPanel @@ -9540,8 +9547,8 @@ final class Workspace: Identifiable, ObservableObject { ) { guard !remoteTmuxMirrorMutations.suppressesFocusActivation else { return } markExplicitFocusIntent(on: panelId) - if #available(macOS 15.4, *), panels[panelId] is BrowserPanel { - BrowserWebExtensionSupport.shared.noteActivated(panelID: panelId) + if let browserPanel = panels[panelId] as? BrowserPanel { + browserPanel.noteWebExtensionActivated() } #if DEBUG let pane = bonsplitController.focusedPaneId?.id.uuidString.prefix(5) ?? "nil" diff --git a/Sources/cmuxApp.swift b/Sources/cmuxApp.swift index 688732a081a8..9d051007d8c9 100644 --- a/Sources/cmuxApp.swift +++ b/Sources/cmuxApp.swift @@ -176,13 +176,18 @@ struct cmuxApp: App { hostActions: HostSettingsActions(configFileURL: configFileURL) ) StartupBreadcrumbLog.append("app.init.settingsRuntime.created") + let browserWebExtensionHost: (any BrowserWebExtensionHosting)? if #available(macOS 15.4, *) { - BrowserWebExtensionSupport.shared.configure( + let support = BrowserWebExtensionSupport() + support.configure( jsonStore: settingsJSONStore, catalog: settingsCatalog ) + browserWebExtensionHost = support + StartupBreadcrumbLog.append("app.init.browserWebExtensions.configured") + } else { + browserWebExtensionHost = nil } - let startupAppearance = AppearanceSettings.resolvedMode() Self.applyAppearance(startupAppearance, duringLaunch: true) StartupBreadcrumbLog.append("app.init.appearance.applied", fields: ["mode": startupAppearance.rawValue]) @@ -194,7 +199,7 @@ struct cmuxApp: App { KeyboardShortcutSettings.settingsFileStore.applyDeferredManagedDefaultSideEffects() StartupBreadcrumbLog.append("app.init.keyboardShortcuts.sideEffectsApplied") StartupBreadcrumbLog.append("app.init.tabManager.begin") - _tabManager = StateObject(wrappedValue: TabManager()) + _tabManager = StateObject(wrappedValue: TabManager(browserWebExtensionHost: browserWebExtensionHost)) StartupBreadcrumbLog.append("app.init.tabManager.complete") // Migrate legacy and old-format socket mode values to the new enum. if let stored = defaults.string(forKey: SocketControlSettings.appStorageKey) { diff --git a/cmux.xcodeproj/project.pbxproj b/cmux.xcodeproj/project.pbxproj index 7be3c39186fe..771c0c065c59 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -310,9 +310,16 @@ C0DE71B10000000000000001 /* AppDelegate+AgentChatNotifications.swift in Sources A50100000000000000000020 /* BrowserWebAuthnTransportSummary.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5010000000000000000001F /* BrowserWebAuthnTransportSummary.swift */; }; A50100000000000000000022 /* BrowserWebAuthnUserDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = A50100000000000000000021 /* BrowserWebAuthnUserDescriptor.swift */; }; C0DE49870000000000000001 /* BrowserWebContentProcessTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE49870000000000000002 /* BrowserWebContentProcessTests.swift */; }; + B1CFE00A0000000000000001 /* BrowserWebExtensionActionSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1CFE00A0000000000000002 /* BrowserWebExtensionActionSnapshot.swift */; }; B1CFE0060000000000000001 /* BrowserWebExtensionDiscoveryService.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1CFE0060000000000000002 /* BrowserWebExtensionDiscoveryService.swift */; }; + B1CFE0080000000000000001 /* BrowserWebExtensionHosting.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1CFE0080000000000000002 /* BrowserWebExtensionHosting.swift */; }; + B1CFE00B0000000000000001 /* BrowserWebExtensionLoadedRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1CFE00B0000000000000002 /* BrowserWebExtensionLoadedRecord.swift */; }; B1CFE0050000000000000001 /* BrowserWebExtensionPopoutWindowController.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1CFE0050000000000000002 /* BrowserWebExtensionPopoutWindowController.swift */; }; + B1CFE00C0000000000000001 /* BrowserWebExtensionReconciliationPlanner.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1CFE00C0000000000000002 /* BrowserWebExtensionReconciliationPlanner.swift */; }; + B1CFE0070000000000000001 /* BrowserWebExtensionSupport+Loading.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1CFE0070000000000000002 /* BrowserWebExtensionSupport+Loading.swift */; }; + B1CFE0090000000000000001 /* BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1CFE0090000000000000002 /* BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift */; }; B1CFE0010000000000000001 /* BrowserWebExtensionSupport.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1CFE0010000000000000002 /* BrowserWebExtensionSupport.swift */; }; + B1CFE0200000000000000001 /* BrowserWebExtensionSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1CFE0200000000000000002 /* BrowserWebExtensionSupportTests.swift */; }; B1CFE0020000000000000001 /* BrowserWebExtensionTabAdapter.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1CFE0020000000000000002 /* BrowserWebExtensionTabAdapter.swift */; }; B1CFE0040000000000000001 /* BrowserWebExtensionToolbarButtons.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1CFE0040000000000000002 /* BrowserWebExtensionToolbarButtons.swift */; }; B1CFE0030000000000000001 /* BrowserWebExtensionWindowAdapter.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1CFE0030000000000000002 /* BrowserWebExtensionWindowAdapter.swift */; }; @@ -2075,9 +2082,16 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = A5010000000000000000001F /* BrowserWebAuthnTransportSummary.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/BrowserWebAuthnTransportSummary.swift; sourceTree = ""; }; A50100000000000000000021 /* BrowserWebAuthnUserDescriptor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/BrowserWebAuthnUserDescriptor.swift; sourceTree = ""; }; C0DE49870000000000000002 /* BrowserWebContentProcessTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BrowserWebContentProcessTests.swift; sourceTree = ""; }; + B1CFE00A0000000000000002 /* BrowserWebExtensionActionSnapshot.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/BrowserWebExtensionActionSnapshot.swift; sourceTree = ""; }; B1CFE0060000000000000002 /* BrowserWebExtensionDiscoveryService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/BrowserWebExtensionDiscoveryService.swift; sourceTree = ""; }; + B1CFE0080000000000000002 /* BrowserWebExtensionHosting.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/BrowserWebExtensionHosting.swift; sourceTree = ""; }; + B1CFE00B0000000000000002 /* BrowserWebExtensionLoadedRecord.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/BrowserWebExtensionLoadedRecord.swift; sourceTree = ""; }; B1CFE0050000000000000002 /* BrowserWebExtensionPopoutWindowController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/BrowserWebExtensionPopoutWindowController.swift; sourceTree = ""; }; + B1CFE00C0000000000000002 /* BrowserWebExtensionReconciliationPlanner.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/BrowserWebExtensionReconciliationPlanner.swift; sourceTree = ""; }; + B1CFE0070000000000000002 /* BrowserWebExtensionSupport+Loading.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Panels/BrowserWebExtensionSupport+Loading.swift"; sourceTree = ""; }; + B1CFE0090000000000000002 /* BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift"; sourceTree = ""; }; B1CFE0010000000000000002 /* BrowserWebExtensionSupport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/BrowserWebExtensionSupport.swift; sourceTree = ""; }; + B1CFE0200000000000000002 /* BrowserWebExtensionSupportTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BrowserWebExtensionSupportTests.swift; sourceTree = ""; }; B1CFE0020000000000000002 /* BrowserWebExtensionTabAdapter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/BrowserWebExtensionTabAdapter.swift; sourceTree = ""; }; B1CFE0040000000000000002 /* BrowserWebExtensionToolbarButtons.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/BrowserWebExtensionToolbarButtons.swift; sourceTree = ""; }; B1CFE0030000000000000002 /* BrowserWebExtensionWindowAdapter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/BrowserWebExtensionWindowAdapter.swift; sourceTree = ""; }; @@ -4300,8 +4314,14 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = B1CFE0030000000000000002 /* BrowserWebExtensionWindowAdapter.swift */, B1CFE0020000000000000002 /* BrowserWebExtensionTabAdapter.swift */, B1CFE0010000000000000002 /* BrowserWebExtensionSupport.swift */, + B1CFE0070000000000000002 /* BrowserWebExtensionSupport+Loading.swift */, + B1CFE0090000000000000002 /* BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift */, B1CFE0060000000000000002 /* BrowserWebExtensionDiscoveryService.swift */, B1CFE0050000000000000002 /* BrowserWebExtensionPopoutWindowController.swift */, + B1CFE0080000000000000002 /* BrowserWebExtensionHosting.swift */, + B1CFE00A0000000000000002 /* BrowserWebExtensionActionSnapshot.swift */, + B1CFE00B0000000000000002 /* BrowserWebExtensionLoadedRecord.swift */, + B1CFE00C0000000000000002 /* BrowserWebExtensionReconciliationPlanner.swift */, C67540100000000000000002 /* BrowserNavigationPopupPolicy.swift */, A5001412 /* BrowserPanel.swift */, B1F0C0090000000000000002 /* BrowserPanelDeveloperToolsLifecycle.swift */, @@ -4934,6 +4954,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = B6585002B6585002B6585002 /* BrowserHiddenWebViewDiscardMemoryPressureTests.swift */, B75040020000000000000002 /* BrowserDiscardedWebViewRestoreRetryTests.swift */, B75040030000000000000002 /* BrowserDiscardRestoreHealPredicateTests.swift */, + B1CFE0200000000000000002 /* BrowserWebExtensionSupportTests.swift */, B75040040000000000000002 /* BrowserInsecureHTTPAlertTestSupport.swift */, B6585002B6585002B658PW02 /* BrowserPrewarmedWebViewPoolTests.swift */, 58C7B1B978620BE162CC057E /* BrowserPanelTests.swift */, @@ -5859,8 +5880,14 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = A5010000000000000000001E /* BrowserWebAuthnTransport.swift in Sources */, A50100000000000000000020 /* BrowserWebAuthnTransportSummary.swift in Sources */, A50100000000000000000022 /* BrowserWebAuthnUserDescriptor.swift in Sources */, + B1CFE00A0000000000000001 /* BrowserWebExtensionActionSnapshot.swift in Sources */, B1CFE0060000000000000001 /* BrowserWebExtensionDiscoveryService.swift in Sources */, + B1CFE0080000000000000001 /* BrowserWebExtensionHosting.swift in Sources */, + B1CFE00B0000000000000001 /* BrowserWebExtensionLoadedRecord.swift in Sources */, B1CFE0050000000000000001 /* BrowserWebExtensionPopoutWindowController.swift in Sources */, + B1CFE00C0000000000000001 /* BrowserWebExtensionReconciliationPlanner.swift in Sources */, + B1CFE0070000000000000001 /* BrowserWebExtensionSupport+Loading.swift in Sources */, + B1CFE0090000000000000001 /* BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift in Sources */, B1CFE0010000000000000001 /* BrowserWebExtensionSupport.swift in Sources */, B1CFE0020000000000000001 /* BrowserWebExtensionTabAdapter.swift in Sources */, B1CFE0040000000000000001 /* BrowserWebExtensionToolbarButtons.swift in Sources */, @@ -6916,6 +6943,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = C2035A060000000000000001 /* BrowserSSLTrustBypassStateTests.swift in Sources */, C7B800062D4202A13C962D2D /* BrowserSystemProxyMirrorTests.swift in Sources */, C0DE49870000000000000001 /* BrowserWebContentProcessTests.swift in Sources */, + B1CFE0200000000000000001 /* BrowserWebExtensionSupportTests.swift in Sources */, C0DE62600000000000000001 /* BrowserWindowPortalRegistryNotificationTests.swift in Sources */, C0DE35530000000000000101 /* BundledCLILinkageTests.swift in Sources */, 0A0F00560000000000000003 /* CampfireHookNotificationTests.swift in Sources */, diff --git a/cmuxTests/BrowserWebExtensionSupportTests.swift b/cmuxTests/BrowserWebExtensionSupportTests.swift new file mode 100644 index 000000000000..02d56ca744ff --- /dev/null +++ b/cmuxTests/BrowserWebExtensionSupportTests.swift @@ -0,0 +1,101 @@ +import CmuxSettings +import Foundation +import Testing + +#if canImport(cmux_DEV) +@testable import cmux_DEV +#elseif canImport(cmux) +@testable import cmux +#endif + +@Suite +struct BrowserWebExtensionSupportTests { + @Test + func reconciliationSkipsEnvPathWhenSettingsEntryIsDisabled() { + let planner = BrowserWebExtensionReconciliationPlanner() + let appexPath = "/Applications/Bitwarden.app/Contents/PlugIns/safari.appex" + let plan = planner.plan( + settingsEntries: [ + BrowserWebExtensionEntry( + id: "com.bitwarden.desktop.safari", + kind: .safariAppExtension, + path: appexPath, + enabled: false + ), + ], + environmentPaths: [appexPath], + loadedEntries: [] + ) + + #expect(plan.desiredEntries.isEmpty) + #expect(plan.loadEntries.isEmpty) + #expect(plan.unloadEntryIDs.isEmpty) + } + + @Test + func reconciliationDoesNotLoadSamePathTwice() { + let planner = BrowserWebExtensionReconciliationPlanner() + let appexPath = "/Applications/Bitwarden.app/Contents/PlugIns/safari.appex" + let plan = planner.plan( + settingsEntries: [ + BrowserWebExtensionEntry( + id: "com.bitwarden.desktop.safari", + kind: .safariAppExtension, + path: appexPath, + enabled: true + ), + ], + environmentPaths: [appexPath], + loadedEntries: [] + ) + + #expect(plan.desiredEntries.map(\.id) == ["com.bitwarden.desktop.safari"]) + #expect(plan.loadEntries.map(\.id) == ["com.bitwarden.desktop.safari"]) + } + + @Test + func reconciliationReloadsWhenPathChangesForSameEntryID() { + let planner = BrowserWebExtensionReconciliationPlanner() + let oldPath = "/Applications/Bitwarden.app/Contents/PlugIns/safari.appex" + let newPath = "/Applications/Bitwarden Beta.app/Contents/PlugIns/safari.appex" + let plan = planner.plan( + settingsEntries: [ + BrowserWebExtensionEntry( + id: "com.bitwarden.desktop.safari", + kind: .safariAppExtension, + path: newPath, + enabled: true + ), + ], + environmentPaths: [], + loadedEntries: [ + BrowserWebExtensionReconciliationPlanner.LoadedEntry( + id: "com.bitwarden.desktop.safari", + standardizedPath: BrowserWebExtensionReconciliationPlanner.standardizedPath(oldPath) + ), + ] + ) + + #expect(plan.unloadEntryIDs == ["com.bitwarden.desktop.safari"]) + #expect(plan.loadEntries.map(\.path) == [newPath]) + } + + @Test + func pluginkitParserHandlesVerboseSpaceSeparatedOutput() { + let output = """ + + com.bitwarden.desktop.safari(2026.7.0) 01234567-89AB-CDEF-0123-456789ABCDEF 2026-07-09 03:21:09 +0000 /Applications/Bitwarden.app/Contents/PlugIns/safari.appex + - com.example.disabled(1.2.3)\tAAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE\t2026-07-09 03:22:09 +0000\t/Applications/Example App.app/Contents/PlugIns/Example Extension.appex + """ + + let candidates = BrowserWebExtensionDiscoveryService.parse(pluginkitOutput: output) + + #expect(candidates.map(\.id) == [ + "com.bitwarden.desktop.safari", + "com.example.disabled", + ]) + #expect(candidates.first?.version == "2026.7.0") + #expect(candidates.first?.path == "/Applications/Bitwarden.app/Contents/PlugIns/safari.appex") + #expect(candidates.last?.version == "1.2.3") + #expect(candidates.last?.path == "/Applications/Example App.app/Contents/PlugIns/Example Extension.appex") + } +} From beb4209b695a618a27abe7dd7ddfc3e5d7d8b687 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 03:15:16 -0700 Subject: [PATCH 08/51] Fix web extension unload and duplicate path state --- .../Sections/BrowserWebExtensionsCard.swift | 27 ++++++++++++++++++- .../BrowserWebExtensionSupport+Loading.swift | 11 +++++--- 2 files changed, 34 insertions(+), 4 deletions(-) diff --git a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift index 52adab66db8a..e2da25399788 100644 --- a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift +++ b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift @@ -18,12 +18,13 @@ struct BrowserWebExtensionsCard: View { @State private var discovered: [SettingsDiscoveredBrowserExtension] = [] var body: some View { + let enabledByID = effectiveEnabledByID() SettingsCard { headerRow if supported { ForEach(model.current) { entry in SettingsCardDivider() - entryRow(entry, isEnabled: entry.enabled) + entryRow(entry, isEnabled: enabledByID[entry.id] ?? entry.enabled) } if model.current.isEmpty { SettingsCardDivider() @@ -146,12 +147,21 @@ struct BrowserWebExtensionsCard: View { var entries = model.current guard let index = entries.firstIndex(where: { $0.id == id }) else { return } entries[index].enabled = enabled + if enabled { + let targetPath = standardizedPath(entries[index].path) + for candidateIndex in entries.indices where candidateIndex != index { + if standardizedPath(entries[candidateIndex].path) == targetPath { + entries[candidateIndex].enabled = false + } + } + } model.set(entries) } private func add(_ entry: BrowserWebExtensionEntry) { var entries = model.current guard !entries.contains(where: { $0.id == entry.id }) else { return } + guard !entries.contains(where: { standardizedPath($0.path) == standardizedPath(entry.path) }) else { return } entries.append(entry) model.set(entries) } @@ -211,4 +221,19 @@ struct BrowserWebExtensionsCard: View { alert.addButton(withTitle: String(localized: "common.ok", defaultValue: "OK")) alert.runModal() } + + private func effectiveEnabledByID() -> [String: Bool] { + var seenEnabledPaths = Set() + var result: [String: Bool] = [:] + for entry in model.current { + let path = standardizedPath(entry.path) + let isFirstEnabledEntryForPath = entry.enabled && seenEnabledPaths.insert(path).inserted + result[entry.id] = isFirstEnabledEntryForPath + } + return result + } + + private func standardizedPath(_ path: String) -> String { + URL(fileURLWithPath: path).standardizedFileURL.path + } } diff --git a/Sources/Panels/BrowserWebExtensionSupport+Loading.swift b/Sources/Panels/BrowserWebExtensionSupport+Loading.swift index c4803a8d55ea..c486c8d35be8 100644 --- a/Sources/Panels/BrowserWebExtensionSupport+Loading.swift +++ b/Sources/Panels/BrowserWebExtensionSupport+Loading.swift @@ -50,19 +50,22 @@ extension BrowserWebExtensionSupport { private func unload(entryID: String) { guard let record = loadedByEntryID[entryID] else { return } + var didUnload = true do { try controller.unload(record.context) } catch { + didUnload = false recordLoadError(error.localizedDescription, entryID: entryID) #if DEBUG cmuxDebugLog("browser.webext.unloadFailed id=\(entryID) error=\(error.localizedDescription)") #endif - return } loadedByEntryID[entryID] = nil loadedEntryIDsInOrder.removeAll { $0 == entryID } - loadErrorsByEntryID.removeValue(forKey: entryID) + if didUnload { + loadErrorsByEntryID.removeValue(forKey: entryID) + } refreshLoadErrors() let closingPopouts = popouts.filter { $0.extensionContext === record.context } @@ -70,7 +73,9 @@ extension BrowserWebExtensionSupport { popout.closeFromExtensionOrUser() } #if DEBUG - cmuxDebugLog("browser.webext.unloaded id=\(entryID)") + if didUnload { + cmuxDebugLog("browser.webext.unloaded id=\(entryID)") + } #endif } From d4d537e914fec33c9a924ff2fd28125d0fb318ed Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 03:21:07 -0700 Subject: [PATCH 09/51] Show duplicate web extension add feedback --- .../Sections/BrowserWebExtensionsCard.swift | 29 +- Resources/Localizable.xcstrings | 250 ++++++++++++++++++ 2 files changed, 277 insertions(+), 2 deletions(-) diff --git a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift index e2da25399788..ea276af3b1aa 100644 --- a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift +++ b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift @@ -160,8 +160,14 @@ struct BrowserWebExtensionsCard: View { private func add(_ entry: BrowserWebExtensionEntry) { var entries = model.current - guard !entries.contains(where: { $0.id == entry.id }) else { return } - guard !entries.contains(where: { standardizedPath($0.path) == standardizedPath(entry.path) }) else { return } + guard !entries.contains(where: { $0.id == entry.id }) else { + presentDuplicateExtensionAlert(for: entry) + return + } + guard !entries.contains(where: { standardizedPath($0.path) == standardizedPath(entry.path) }) else { + presentDuplicateExtensionAlert(for: entry) + return + } entries.append(entry) model.set(entries) } @@ -222,6 +228,25 @@ struct BrowserWebExtensionsCard: View { alert.runModal() } + private func presentDuplicateExtensionAlert(for entry: BrowserWebExtensionEntry) { + let alert = NSAlert() + alert.alertStyle = .informational + alert.messageText = String( + localized: "settings.browser.webExtensions.duplicate.title", + defaultValue: "Extension Already Added" + ) + let displayName = entry.displayName ?? (entry.path as NSString).lastPathComponent + alert.informativeText = String( + format: String( + localized: "settings.browser.webExtensions.duplicate.message", + defaultValue: "“%@” is already in the extensions list." + ), + displayName + ) + alert.addButton(withTitle: String(localized: "common.ok", defaultValue: "OK")) + alert.runModal() + } + private func effectiveEnabledByID() -> [String: Bool] { var seenEnabledPaths = Set() var result: [String: Bool] = [:] diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index b88663a40b79..68473f5809f0 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -235201,6 +235201,256 @@ } } } + }, + "settings.browser.webExtensions.duplicate.title": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "تمت إضافة الإضافة بالفعل" + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "Ekstenzija je već dodana" + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "Udvidelsen er allerede tilføjet" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Erweiterung bereits hinzugefügt" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Extension Already Added" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "La extensión ya se agregó" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Extension déjà ajoutée" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Estensione già aggiunta" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "拡張機能はすでに追加されています" + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "បានបន្ថែមផ្នែកបន្ថែមរួចហើយ" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "확장 프로그램이 이미 추가됨" + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "Utvidelsen er allerede lagt til" + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "Rozszerzenie już dodane" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Extensão já adicionada" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Расширение уже добавлено" + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "เพิ่มส่วนขยายนี้แล้ว" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Uzantı Zaten Eklendi" + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "Розширення вже додано" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "扩展已添加" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "延伸功能已加入" + } + } + } + }, + "settings.browser.webExtensions.duplicate.message": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "“%@” موجودة بالفعل في قائمة الإضافات." + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "“%@” je već na listi ekstenzija." + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "“%@” findes allerede på listen over udvidelser." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "„%@“ ist bereits in der Erweiterungsliste." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "“%@” is already in the extensions list." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "“%@” ya está en la lista de extensiones." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "« %@ » figure déjà dans la liste des extensions." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "“%@” è già nell’elenco delle estensioni." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "「%@」はすでに拡張機能リストにあります。" + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "“%@” មានរួចហើយនៅក្នុងបញ្ជីផ្នែកបន្ថែម។" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "“%@”은(는) 이미 확장 프로그램 목록에 있습니다." + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "«%@» finnes allerede i utvidelseslisten." + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "„%@” jest już na liście rozszerzeń." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "“%@” já está na lista de extensões." + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "«%@» уже есть в списке расширений." + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "“%@” อยู่ในรายการส่วนขยายแล้ว" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "“%@” uzantılar listesinde zaten var." + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "«%@» уже є в списку розширень." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "“%@”已在扩展列表中。" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "「%@」已在延伸功能列表中。" + } + } + } } }, "version": "1.0" From bda49757e086d2288948f7b8846d73378e07dc28 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 03:36:10 -0700 Subject: [PATCH 10/51] Fix browser extension panel lifecycle --- Sources/DockSplitStore.swift | 10 +-- ...rowserPanel+PrewarmedWebViewAdoption.swift | 6 +- Sources/Panels/BrowserPanel.swift | 25 +++++-- .../Panels/BrowserPrewarmedWebViewPool.swift | 51 +++++++++---- Sources/PricingPlansScreen.swift | 6 +- Sources/Workspace.swift | 9 ++- .../BrowserPrewarmedWebViewPoolTests.swift | 74 ++++++++++++++++++- 7 files changed, 149 insertions(+), 32 deletions(-) diff --git a/Sources/DockSplitStore.swift b/Sources/DockSplitStore.swift index 57d13d523103..bd7b25cc5465 100644 --- a/Sources/DockSplitStore.swift +++ b/Sources/DockSplitStore.swift @@ -559,6 +559,7 @@ final class DockSplitStore: BonsplitDelegate { func installSubscription(for panel: any Panel, tracksTerminalTitle: Bool) { if let browser = panel as? BrowserPanel { + browser.registerWebExtensionIfNeeded() let cancellable = Publishers.CombineLatest4( browser.$pageTitle.removeDuplicates(), browser.$isLoading.removeDuplicates(), @@ -569,12 +570,9 @@ final class DockSplitStore: BonsplitDelegate { .sink { [weak self, weak browser] _ in guard let self, let browser, let tabId = self.surfaceId(forPanelId: browser.id), let existing = self.bonsplitController.tab(tabId) else { return } - // Only push fields that actually changed. CombineLatest4 fires on - // ANY of the four publishers, so an `isLoading` flicker during a - // page load would otherwise re-publish the (unchanged) title and - // favicon, mutating the @Observable BonsplitController and - // re-rendering the Dock tree for nothing. Mirrors the main area's - // guarded path in Workspace.installBrowserPanelSubscription. + // Only push fields that actually changed; otherwise unchanged metadata + // would mutate Bonsplit and re-render the Dock tree for nothing. + // Mirrors the main area's guarded path in Workspace.installBrowserPanelSubscription. let resolvedTitle = browser.displayTitle let favicon = browser.faviconPNGData let titleUpdate: String? = existing.title == resolvedTitle ? nil : resolvedTitle diff --git a/Sources/Panels/BrowserPanel+PrewarmedWebViewAdoption.swift b/Sources/Panels/BrowserPanel+PrewarmedWebViewAdoption.swift index e291d013a8ba..678bfee36cbd 100644 --- a/Sources/Panels/BrowserPanel+PrewarmedWebViewAdoption.swift +++ b/Sources/Panels/BrowserPanel+PrewarmedWebViewAdoption.swift @@ -24,7 +24,8 @@ extension BrowserPanel { renderInitialNavigation: Bool, initialURL: URL?, profileID: UUID, - websiteDataStore: WKWebsiteDataStore + websiteDataStore: WKWebsiteDataStore, + browserWebExtensionHost: (any BrowserWebExtensionHosting)? ) -> CmuxWebView? { guard !isRemoteWorkspace, initialRequest == nil, @@ -35,7 +36,8 @@ extension BrowserPanel { return BrowserPrewarmedWebViewPool.shared.claim( url: initialURL, profileID: profileID, - websiteDataStore: websiteDataStore + websiteDataStore: websiteDataStore, + browserWebExtensionHost: browserWebExtensionHost ) } } diff --git a/Sources/Panels/BrowserPanel.swift b/Sources/Panels/BrowserPanel.swift index 1488a607a4dd..f8b0080e2653 100644 --- a/Sources/Panels/BrowserPanel.swift +++ b/Sources/Panels/BrowserPanel.swift @@ -2747,6 +2747,7 @@ final class BrowserPanel: Panel, ObservableObject { private(set) var webView: WKWebView private var websiteDataStore: WKWebsiteDataStore let browserWebExtensionHost: (any BrowserWebExtensionHosting)? + private var isRegisteredForWebExtensions = false var webViewDidRequestClose: (() -> Void)? /// Monotonic identity for the current WKWebView instance. @@ -3978,13 +3979,14 @@ final class BrowserPanel: Panel, ObservableObject { self.browserWebExtensionHost = browserWebExtensionHost let webView: CmuxWebView var adoptedPrewarmedWebView = false - if browserWebExtensionHost == nil, let prewarmed = Self.claimedPrewarmedWebView( + if let prewarmed = Self.claimedPrewarmedWebView( isRemoteWorkspace: isRemoteWorkspace, initialRequest: initialRequest, renderInitialNavigation: renderInitialNavigation, initialURL: initialURL, profileID: resolvedProfileID, - websiteDataStore: websiteDataStore + websiteDataStore: websiteDataStore, + browserWebExtensionHost: browserWebExtensionHost ) { webView = prewarmed adoptedPrewarmedWebView = true @@ -4000,7 +4002,6 @@ final class BrowserPanel: Panel, ObservableObject { hiddenWebViewDiscardManager.delegate = self applyProxyConfigurationIfAvailable() BrowserProfileStore.shared.noteUsed(resolvedProfileID) - browserWebExtensionHost?.register(panel: self) // Set up navigation delegate let navDelegate = BrowserNavigationDelegate() @@ -5312,7 +5313,21 @@ final class BrowserPanel: Panel, ObservableObject { } func performWebExtensionCommand(for event: NSEvent) -> Bool { - browserWebExtensionHost?.performCommand(for: event) ?? false + guard let browserWebExtensionHost else { return false } + noteWebExtensionActivated() + return browserWebExtensionHost.performCommand(for: event) + } + + func registerWebExtensionIfNeeded() { + guard !isRegisteredForWebExtensions, let browserWebExtensionHost else { return } + isRegisteredForWebExtensions = true + browserWebExtensionHost.register(panel: self) + } + + private func unregisterWebExtensionIfNeeded() { + guard isRegisteredForWebExtensions else { return } + isRegisteredForWebExtensions = false + browserWebExtensionHost?.unregister(panelID: id) } @available(macOS 15.4, *) @@ -5321,7 +5336,7 @@ final class BrowserPanel: Panel, ObservableObject { } func close() { - browserWebExtensionHost?.unregister(panelID: id) + unregisterWebExtensionIfNeeded() cancelHiddenWebViewDiscard() isClosingWebViewLifecycle = true refreshWebViewLifecycleState() diff --git a/Sources/Panels/BrowserPrewarmedWebViewPool.swift b/Sources/Panels/BrowserPrewarmedWebViewPool.swift index 5c00ca983567..27fbdf28bee9 100644 --- a/Sources/Panels/BrowserPrewarmedWebViewPool.swift +++ b/Sources/Panels/BrowserPrewarmedWebViewPool.swift @@ -4,12 +4,12 @@ import WebKit /// Single-slot pool of a hidden, pre-navigated browser webview. /// -/// Upgrade entrypoints call ``prewarm(url:profileID:)`` on hover so the +/// Upgrade entrypoints call ``prewarm(url:profileID:browserWebExtensionHost:)`` on hover so the /// pricing page is already loaded by the time the user clicks. The /// ``BrowserPanel`` initializer claims a matching entry via -/// ``claim(url:profileID:websiteDataStore:)`` and adopts the webview instead -/// of starting a cold WebKit process launch plus network load, so the panel -/// shows the finished page immediately. +/// ``claim(url:profileID:websiteDataStore:browserWebExtensionHost:)`` and adopts the webview +/// instead of starting a cold WebKit process launch plus network load, so the +/// panel shows the finished page immediately. /// /// The pool never renders on screen: the webview lives in an offscreen, /// non-activating borderless window (the same hosting recipe as @@ -31,6 +31,7 @@ final class BrowserPrewarmedWebViewPool: NSObject { let webView: CmuxWebView let url: URL let profileID: UUID + let browserWebExtensionHostID: ObjectIdentifier? let hostWindow: NSWindow var loadState: LoadState } @@ -38,14 +39,14 @@ final class BrowserPrewarmedWebViewPool: NSObject { private var entry: Entry? private var expiryTask: Task? private let timeToLive: Duration - private let makeWebView: @MainActor (UUID) -> CmuxWebView + private let makeWebView: @MainActor (UUID, (any BrowserWebExtensionHosting)?) -> CmuxWebView private let startLoad: @MainActor (CmuxWebView, URLRequest) -> Void private let expirySleep: @Sendable (Duration) async throws -> Void init( timeToLive: Duration = .seconds(180), - makeWebView: @escaping @MainActor (UUID) -> CmuxWebView = { profileID in - BrowserPanel.makeWebView(profileID: profileID) + makeWebView: @escaping @MainActor (UUID, (any BrowserWebExtensionHosting)?) -> CmuxWebView = { profileID, browserWebExtensionHost in + BrowserPanel.makeWebView(profileID: profileID, browserWebExtensionHost: browserWebExtensionHost) }, startLoad: @escaping @MainActor (CmuxWebView, URLRequest) -> Void = { webView, request in webView.load(request) @@ -62,9 +63,15 @@ final class BrowserPrewarmedWebViewPool: NSObject { /// Whether a live entry exists for the URL + profile, regardless of load /// state. Used to make repeat hovers cheap no-ops. - func hasEntry(url: URL, profileID: UUID) -> Bool { + func hasEntry( + url: URL, + profileID: UUID, + browserWebExtensionHost: (any BrowserWebExtensionHosting)? = nil + ) -> Bool { guard let entry else { return false } - return entry.url.absoluteString == url.absoluteString && entry.profileID == profileID + return entry.url.absoluteString == url.absoluteString + && entry.profileID == profileID + && entry.browserWebExtensionHostID == Self.hostID(browserWebExtensionHost) } /// Starts (or keeps) a hidden webview loading `url`. Replaces any entry @@ -74,25 +81,30 @@ final class BrowserPrewarmedWebViewPool: NSObject { /// would intercept: the hidden load runs without the panel's navigation /// delegate, so no prompt could be shown here. Sharing the panel's /// allowlist policy keeps http://localhost dev origins prewarmable. - func prewarm(url: URL, profileID: UUID) { + func prewarm( + url: URL, + profileID: UUID, + browserWebExtensionHost: (any BrowserWebExtensionHosting)? = nil + ) { guard let scheme = url.scheme?.lowercased(), scheme == "https" || scheme == "http", !browserShouldBlockInsecureHTTPURL(url) else { return } - if hasEntry(url: url, profileID: profileID) { + if hasEntry(url: url, profileID: profileID, browserWebExtensionHost: browserWebExtensionHost) { scheduleExpiry() return } discard(reason: "replaced") - let webView = makeWebView(profileID) + let webView = makeWebView(profileID, browserWebExtensionHost) webView.navigationDelegate = self let hostWindow = Self.makeHiddenHostWindow(for: webView) entry = Entry( webView: webView, url: url, profileID: profileID, + browserWebExtensionHostID: Self.hostID(browserWebExtensionHost), hostWindow: hostWindow, loadState: .loading ) @@ -107,10 +119,16 @@ final class BrowserPrewarmedWebViewPool: NSObject { /// navigation, or returns nil for a normal cold load. The entry is /// consumed either way: once a matching panel is being created, a /// still-loading or failed entry is useless and would otherwise linger. - func claim(url: URL, profileID: UUID, websiteDataStore: WKWebsiteDataStore) -> CmuxWebView? { + func claim( + url: URL, + profileID: UUID, + websiteDataStore: WKWebsiteDataStore, + browserWebExtensionHost: (any BrowserWebExtensionHosting)? = nil + ) -> CmuxWebView? { guard let entry, entry.url.absoluteString == url.absoluteString, - entry.profileID == profileID else { + entry.profileID == profileID, + entry.browserWebExtensionHostID == Self.hostID(browserWebExtensionHost) else { return nil } guard entry.loadState == .finished, @@ -200,6 +218,11 @@ final class BrowserPrewarmedWebViewPool: NSObject { entry.loadState = state self.entry = entry } + + private static func hostID(_ host: (any BrowserWebExtensionHosting)?) -> ObjectIdentifier? { + guard let host else { return nil } + return ObjectIdentifier(host as AnyObject) + } } extension BrowserPrewarmedWebViewPool: WKNavigationDelegate { diff --git a/Sources/PricingPlansScreen.swift b/Sources/PricingPlansScreen.swift index c1df5cc9c2a4..515e826f5059 100644 --- a/Sources/PricingPlansScreen.swift +++ b/Sources/PricingPlansScreen.swift @@ -23,8 +23,7 @@ enum ProUpgradePresenter { @MainActor static func prefetch() { guard BrowserAvailabilitySettings.isEnabled() else { return } - // When an upgrade workspace already exists, present() refocuses it and - // navigates its existing panel, so a prewarmed webview would go unused. + // Skip prewarm when present() will refocus and navigate an existing upgrade workspace. if let workspaceId = workspaceReuseState.workspaceId, let appDelegate = AppDelegate.shared, appDelegate.proUpgradeWorkspaceExists(workspaceId: workspaceId) { @@ -32,7 +31,8 @@ enum ProUpgradePresenter { } BrowserPrewarmedWebViewPool.shared.prewarm( url: appPricingURLForCurrentAppearance(), - profileID: BrowserPanel.resolvedProfileID(requested: nil) + profileID: BrowserPanel.resolvedProfileID(requested: nil), + browserWebExtensionHost: AppDelegate.shared?.tabManager?.browserWebExtensionHost ) } diff --git a/Sources/Workspace.swift b/Sources/Workspace.swift index fb9ffa1133a2..50f337910e97 100644 --- a/Sources/Workspace.swift +++ b/Sources/Workspace.swift @@ -2970,8 +2970,12 @@ final class Workspace: Identifiable, ObservableObject { ) { bindSurface(tabId, toPanelId: browserPanel.id) initialTabId = tabId + installBrowserPanelSubscription(browserPanel) + } else { + panels.removeValue(forKey: browserPanel.id) + panelTitles.removeValue(forKey: browserPanel.id) + browserPanel.close() } - installBrowserPanelSubscription(browserPanel) } else if initialSurface == .cloudVMLoading { let loadingPanel = CloudVMLoadingPanel(workspaceId: id) panels[loadingPanel.id] = loadingPanel @@ -3584,6 +3588,7 @@ final class Workspace: Identifiable, ObservableObject { } private func installBrowserPanelSubscription(_ browserPanel: BrowserPanel) { + browserPanel.registerWebExtensionIfNeeded() let browserTabState = Publishers.CombineLatest4( browserPanel.$pageTitle.removeDuplicates(), browserPanel.$currentURL.removeDuplicates(), browserPanel.$isLoading.removeDuplicates(), browserPanel.$faviconPNGData.removeDuplicates(by: { $0 == $1 }) @@ -7990,6 +7995,7 @@ final class Workspace: Identifiable, ObservableObject { removeSurfaceMapping(forSurfaceId: newTab.id) panels.removeValue(forKey: browserPanel.id) panelTitles.removeValue(forKey: browserPanel.id) + browserPanel.close() return nil } applyInitialSplitDividerPosition(initialDividerPosition, sourcePaneId: paneId, newPaneId: newPaneId) @@ -8091,6 +8097,7 @@ final class Workspace: Identifiable, ObservableObject { ) else { panels.removeValue(forKey: browserPanel.id) panelTitles.removeValue(forKey: browserPanel.id) + browserPanel.close() return nil } diff --git a/cmuxTests/BrowserPrewarmedWebViewPoolTests.swift b/cmuxTests/BrowserPrewarmedWebViewPoolTests.swift index fc17786d4daa..e59bbdfb7c70 100644 --- a/cmuxTests/BrowserPrewarmedWebViewPoolTests.swift +++ b/cmuxTests/BrowserPrewarmedWebViewPoolTests.swift @@ -1,3 +1,4 @@ +import AppKit import Foundation import Testing import WebKit @@ -25,9 +26,10 @@ private final class PrewarmPoolHarness { var recordRequest: (@MainActor (URLRequest) -> Void)! let dataStore = dataStore pool = BrowserPrewarmedWebViewPool( - makeWebView: { _ in + makeWebView: { _, browserWebExtensionHost in let configuration = WKWebViewConfiguration() configuration.websiteDataStore = dataStore + browserWebExtensionHost?.attach(to: configuration) let webView = CmuxWebView(frame: .zero, configuration: configuration) recordWebView(webView) return webView @@ -42,6 +44,23 @@ private final class PrewarmPoolHarness { } } +@MainActor +private final class PrewarmTestWebExtensionHost: BrowserWebExtensionHosting { + private(set) var attachedConfigurationCount = 0 + + func attach(to configuration: WKWebViewConfiguration) { + attachedConfigurationCount += 1 + } + + func register(panel: BrowserPanel) {} + + func unregister(panelID: UUID) {} + + func noteActivated(panelID: UUID) {} + + func performCommand(for event: NSEvent) -> Bool { false } +} + private let pricingURL = URL(string: "https://cmux.com/app-pricing?appearance=dark")! private let otherURL = URL(string: "https://cmux.com/docs")! private let profileID = UUID() @@ -175,6 +194,59 @@ struct BrowserPrewarmedWebViewPoolTests { #expect(!harness.pool.hasEntry(url: pricingURL, profileID: profileID)) } + @Test func prewarmEntriesAreScopedToWebExtensionHost() { + let harness = PrewarmPoolHarness() + let firstHost = PrewarmTestWebExtensionHost() + let secondHost = PrewarmTestWebExtensionHost() + harness.pool.prewarm( + url: pricingURL, + profileID: profileID, + browserWebExtensionHost: firstHost + ) + + #expect(firstHost.attachedConfigurationCount == 1) + #expect(harness.pool.hasEntry( + url: pricingURL, + profileID: profileID, + browserWebExtensionHost: firstHost + )) + #expect(!harness.pool.hasEntry( + url: pricingURL, + profileID: profileID, + browserWebExtensionHost: secondHost + )) + + harness.pool.prewarm( + url: pricingURL, + profileID: profileID, + browserWebExtensionHost: secondHost + ) + #expect(secondHost.attachedConfigurationCount == 1) + #expect(harness.madeWebViews.count == 2) + harness.pool.webView(harness.madeWebViews[1], didFinish: nil) + + let mismatch = harness.pool.claim( + url: pricingURL, + profileID: profileID, + websiteDataStore: harness.dataStore, + browserWebExtensionHost: firstHost + ) + #expect(mismatch == nil) + #expect(harness.pool.hasEntry( + url: pricingURL, + profileID: profileID, + browserWebExtensionHost: secondHost + )) + + let match = harness.pool.claim( + url: pricingURL, + profileID: profileID, + websiteDataStore: harness.dataStore, + browserWebExtensionHost: secondHost + ) + #expect(match === harness.madeWebViews[1]) + } + @Test func provisionalLoadFailureDiscardsEntry() { let harness = PrewarmPoolHarness() harness.pool.prewarm(url: pricingURL, profileID: profileID) From 5afd75886d16d143b7cfe9c67937b9f557f73fb1 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 03:38:38 -0700 Subject: [PATCH 11/51] Address web extension review comments --- .../Sections/BrowserWebExtensionsCard.swift | 17 ++++++---------- .../BrowserWebExtensionSupport+Loading.swift | 11 +++------- ...ort+WKWebExtensionControllerDelegate.swift | 4 ++-- .../BrowserWebExtensionSupportTests.swift | 20 +++++++++++++++++++ 4 files changed, 31 insertions(+), 21 deletions(-) diff --git a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift index ea276af3b1aa..366fcb187aa4 100644 --- a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift +++ b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift @@ -146,13 +146,11 @@ struct BrowserWebExtensionsCard: View { private func setEnabled(_ enabled: Bool, id: String) { var entries = model.current guard let index = entries.firstIndex(where: { $0.id == id }) else { return } + let targetPath = standardizedPath(entries[index].path) entries[index].enabled = enabled - if enabled { - let targetPath = standardizedPath(entries[index].path) - for candidateIndex in entries.indices where candidateIndex != index { - if standardizedPath(entries[candidateIndex].path) == targetPath { - entries[candidateIndex].enabled = false - } + for candidateIndex in entries.indices where candidateIndex != index { + if standardizedPath(entries[candidateIndex].path) == targetPath { + entries[candidateIndex].enabled = false } } model.set(entries) @@ -237,11 +235,8 @@ struct BrowserWebExtensionsCard: View { ) let displayName = entry.displayName ?? (entry.path as NSString).lastPathComponent alert.informativeText = String( - format: String( - localized: "settings.browser.webExtensions.duplicate.message", - defaultValue: "“%@” is already in the extensions list." - ), - displayName + localized: "settings.browser.webExtensions.duplicate.message", + defaultValue: "“\(displayName)” is already in the extensions list." ) alert.addButton(withTitle: String(localized: "common.ok", defaultValue: "OK")) alert.runModal() diff --git a/Sources/Panels/BrowserWebExtensionSupport+Loading.swift b/Sources/Panels/BrowserWebExtensionSupport+Loading.swift index c486c8d35be8..c4803a8d55ea 100644 --- a/Sources/Panels/BrowserWebExtensionSupport+Loading.swift +++ b/Sources/Panels/BrowserWebExtensionSupport+Loading.swift @@ -50,22 +50,19 @@ extension BrowserWebExtensionSupport { private func unload(entryID: String) { guard let record = loadedByEntryID[entryID] else { return } - var didUnload = true do { try controller.unload(record.context) } catch { - didUnload = false recordLoadError(error.localizedDescription, entryID: entryID) #if DEBUG cmuxDebugLog("browser.webext.unloadFailed id=\(entryID) error=\(error.localizedDescription)") #endif + return } loadedByEntryID[entryID] = nil loadedEntryIDsInOrder.removeAll { $0 == entryID } - if didUnload { - loadErrorsByEntryID.removeValue(forKey: entryID) - } + loadErrorsByEntryID.removeValue(forKey: entryID) refreshLoadErrors() let closingPopouts = popouts.filter { $0.extensionContext === record.context } @@ -73,9 +70,7 @@ extension BrowserWebExtensionSupport { popout.closeFromExtensionOrUser() } #if DEBUG - if didUnload { - cmuxDebugLog("browser.webext.unloaded id=\(entryID)") - } + cmuxDebugLog("browser.webext.unloaded id=\(entryID)") #endif } diff --git a/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift b/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift index 186a0ca96eac..bb6d51e34ff1 100644 --- a/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift +++ b/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift @@ -206,8 +206,8 @@ extension BrowserWebExtensionSupport: WKWebExtensionControllerDelegate { localized: "browser.webExtension.action.help", defaultValue: "Extension" ) - return String( - format: String(localized: key, defaultValue: defaultValue), + return String.localizedStringWithFormat( + String(localized: key, defaultValue: defaultValue), extensionName, details ) diff --git a/cmuxTests/BrowserWebExtensionSupportTests.swift b/cmuxTests/BrowserWebExtensionSupportTests.swift index 02d56ca744ff..e1c30ae1c7e7 100644 --- a/cmuxTests/BrowserWebExtensionSupportTests.swift +++ b/cmuxTests/BrowserWebExtensionSupportTests.swift @@ -53,6 +53,26 @@ struct BrowserWebExtensionSupportTests { #expect(plan.loadEntries.map(\.id) == ["com.bitwarden.desktop.safari"]) } + @Test + func reconciliationDeduplicatesRepeatedEnvironmentPaths() { + let planner = BrowserWebExtensionReconciliationPlanner() + let extensionPath = "/tmp/cmux-web-extensions/../cmux-web-extensions/Example" + let standardizedPath = BrowserWebExtensionReconciliationPlanner.standardizedPath(extensionPath) + let plan = planner.plan( + settingsEntries: [], + environmentPaths: [ + extensionPath, + standardizedPath, + ], + loadedEntries: [] + ) + + #expect(plan.desiredEntries.map(\.id) == [extensionPath]) + #expect(plan.desiredEntries.map(\.path) == [extensionPath]) + #expect(plan.loadEntries.map(\.id) == [extensionPath]) + #expect(plan.unloadEntryIDs.isEmpty) + } + @Test func reconciliationReloadsWhenPathChangesForSameEntryID() { let planner = BrowserWebExtensionReconciliationPlanner() From 223a38af72c92426cda7fb1f4d3b571faabf065a Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 03:47:18 -0700 Subject: [PATCH 12/51] Order focused web extension window first --- ...tensionSupport+WKWebExtensionControllerDelegate.swift | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift b/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift index bb6d51e34ff1..35920b1285ea 100644 --- a/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift +++ b/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift @@ -7,7 +7,14 @@ extension BrowserWebExtensionSupport: WKWebExtensionControllerDelegate { _ controller: WKWebExtensionController, openWindowsFor extensionContext: WKWebExtensionContext ) -> [any WKWebExtensionWindow] { - [windowAdapter] + popouts + let openWindows: [any WKWebExtensionWindow] = [windowAdapter] + popouts + guard let focusedWindow = webExtensionController(controller, focusedWindowFor: extensionContext) else { + return openWindows + } + let focusedID = ObjectIdentifier(focusedWindow as AnyObject) + return [focusedWindow] + openWindows.filter { + ObjectIdentifier($0 as AnyObject) != focusedID + } } func webExtensionController( From 5ba4f0d791dfaa7acd29d9cb9d14e4557c93f7ed Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 03:49:54 -0700 Subject: [PATCH 13/51] Use localized format for duplicate extension alert --- .../Sections/BrowserWebExtensionsCard.swift | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift index 366fcb187aa4..c0f628eafdba 100644 --- a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift +++ b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift @@ -234,9 +234,12 @@ struct BrowserWebExtensionsCard: View { defaultValue: "Extension Already Added" ) let displayName = entry.displayName ?? (entry.path as NSString).lastPathComponent - alert.informativeText = String( - localized: "settings.browser.webExtensions.duplicate.message", - defaultValue: "“\(displayName)” is already in the extensions list." + alert.informativeText = String.localizedStringWithFormat( + String( + localized: "settings.browser.webExtensions.duplicate.message", + defaultValue: "“%@” is already in the extensions list." + ), + displayName ) alert.addButton(withTitle: String(localized: "common.ok", defaultValue: "OK")) alert.runModal() From 87a0707e5f8cb5bb90e739b22e3ce6985a3a96c9 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 03:57:42 -0700 Subject: [PATCH 14/51] Fix web extension popout and window host wiring --- Sources/AppDelegate.swift | 4 ++-- ...serWebExtensionPopoutWindowController.swift | 18 +++++++++++++----- 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/Sources/AppDelegate.swift b/Sources/AppDelegate.swift index d58ce214ef6f..99011a405cd8 100644 --- a/Sources/AppDelegate.swift +++ b/Sources/AppDelegate.swift @@ -8630,7 +8630,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent initialWorkspaceTitle: initialWorkspaceTitle, initialWorkingDirectory: initialWorkingDirectory, initialTerminalInput: initialTerminalInput, - autoWelcomeIfNeeded: initialTerminalInput == nil + autoWelcomeIfNeeded: initialTerminalInput == nil, + browserWebExtensionHost: self.tabManager?.browserWebExtensionHost ) tabManager.windowId = windowId if let sessionWindowSnapshot { @@ -8649,7 +8650,6 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent } restoredSessionSnapshotHandler?(restoredPanelIdsByWorkspaceIndex, tabManager) } - let sidebarWidth = sessionWindowSnapshot?.sidebar.width .map { SessionPersistencePolicy.sanitizedSidebarWidth($0) } ?? SessionPersistencePolicy.defaultSidebarWidth diff --git a/Sources/Panels/BrowserWebExtensionPopoutWindowController.swift b/Sources/Panels/BrowserWebExtensionPopoutWindowController.swift index 8f2fe74d2c98..6aa0608b8bdb 100644 --- a/Sources/Panels/BrowserWebExtensionPopoutWindowController.swift +++ b/Sources/Panels/BrowserWebExtensionPopoutWindowController.swift @@ -31,11 +31,19 @@ final class BrowserWebExtensionPopoutWindowController: NSObject, WKWebExtensionW webView.isInspectable = true #endif - var frame = configuration.frame - let usesFallbackFrame = frame.isNull || frame.isEmpty || frame.width < 50 || frame.height < 50 - if usesFallbackFrame { - frame = CGRect(origin: .zero, size: Self.defaultSize) - } + let requestedFrame = configuration.frame + let hasUsableOrigin = requestedFrame.origin.x.isFinite && requestedFrame.origin.y.isFinite + let width = requestedFrame.width.isFinite && requestedFrame.width >= 50 ? requestedFrame.width : Self.defaultSize.width + let height = requestedFrame.height.isFinite && requestedFrame.height >= 50 ? requestedFrame.height : Self.defaultSize.height + let frame = CGRect( + origin: hasUsableOrigin ? requestedFrame.origin : .zero, + size: CGSize(width: width, height: height) + ) + let usesFallbackFrame = !hasUsableOrigin + || !requestedFrame.width.isFinite + || !requestedFrame.height.isFinite + || requestedFrame.width < 50 + || requestedFrame.height < 50 window = NSWindow( contentRect: frame, styleMask: [.titled, .closable, .resizable], From f8849d51de8c7bf72fdce24889230df6633a60a6 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 04:05:44 -0700 Subject: [PATCH 15/51] Use localized format for manifest alert --- .../CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift index c0f628eafdba..d45b1047ac36 100644 --- a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift +++ b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift @@ -215,8 +215,8 @@ struct BrowserWebExtensionsCard: View { localized: "settings.browser.webExtensions.addUnpacked.missingManifest.title", defaultValue: "Missing manifest.json" ) - alert.informativeText = String( - format: String( + alert.informativeText = String.localizedStringWithFormat( + String( localized: "settings.browser.webExtensions.addUnpacked.missingManifest.message", defaultValue: "“%@” is not an unpacked web extension. Choose a folder with manifest.json at its root." ), From 677411c44205473b6003cb91a08e9ce863774abf Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 04:07:19 -0700 Subject: [PATCH 16/51] Allow WebKit native messaging bridge --- ...ort+WKWebExtensionControllerDelegate.swift | 37 ------------------- .../Panels/BrowserWebExtensionSupport.swift | 3 -- 2 files changed, 40 deletions(-) diff --git a/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift b/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift index 35920b1285ea..42ced54a7bb8 100644 --- a/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift +++ b/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift @@ -100,43 +100,6 @@ extension BrowserWebExtensionSupport: WKWebExtensionControllerDelegate { completionHandler(nil) } - func webExtensionController( - _ controller: WKWebExtensionController, - sendMessage message: Any, - toApplicationWithIdentifier applicationIdentifier: String?, - for extensionContext: WKWebExtensionContext, - replyHandler: @escaping (Any?, Error?) -> Void - ) { - // Native messaging (e.g. Bitwarden's desktop-app biometrics IPC) is not - // bridged. Never resolve the reply: an error reply sends Bitwarden into - // an unthrottled reconnect loop (observed ~175k messages/sec), while an - // unresolved promise parks the caller harmlessly. - nativeMessageDropCount += 1 - if nativeMessageDropCount <= 5 { -#if DEBUG - cmuxDebugLog( - "browser.webext.nativeMessage dropped app=\(applicationIdentifier ?? "nil") " + - "count=\(nativeMessageDropCount)" - ) -#endif - } - _ = replyHandler - } - - func webExtensionController( - _ controller: WKWebExtensionController, - connectUsing port: WKWebExtension.MessagePort, - for extensionContext: WKWebExtensionContext, - completionHandler: @escaping (Error?) -> Void - ) { - // See sendMessage above: leave the native port unresolved rather than - // erroring, so extensions do not retry-loop. -#if DEBUG - cmuxDebugLog("browser.webext.nativeConnect dropped app=\(port.applicationIdentifier ?? "nil")") -#endif - _ = completionHandler - } - func webExtensionController( _ controller: WKWebExtensionController, promptForPermissions permissions: Set, diff --git a/Sources/Panels/BrowserWebExtensionSupport.swift b/Sources/Panels/BrowserWebExtensionSupport.swift index d0da8c1c9ca9..e8827cf51cd2 100644 --- a/Sources/Panels/BrowserWebExtensionSupport.swift +++ b/Sources/Panels/BrowserWebExtensionSupport.swift @@ -52,9 +52,6 @@ final class BrowserWebExtensionSupport: NSObject, BrowserWebExtensionHosting { @ObservationIgnored weak var pendingPopupAnchorView: NSView? - @ObservationIgnored - var nativeMessageDropCount = 0 - override init() { let configuration = WKWebExtensionController.Configuration(identifier: Self.controllerIdentifier) // Extension-owned web views (background page, action popup) get WebKit's From 908140a508f8f02409ccbeb8c491010b80f7bf83 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 04:17:41 -0700 Subject: [PATCH 17/51] Forward web extension tab lifecycle --- Sources/DockSplitStore.swift | 2 + .../Panels/BrowserWebExtensionHosting.swift | 1 + ...ort+WKWebExtensionControllerDelegate.swift | 41 ++++++++++++++++--- .../Panels/BrowserWebExtensionSupport.swift | 5 +++ Sources/Workspace.swift | 1 + .../BrowserPrewarmedWebViewPoolTests.swift | 2 + 6 files changed, 47 insertions(+), 5 deletions(-) diff --git a/Sources/DockSplitStore.swift b/Sources/DockSplitStore.swift index bd7b25cc5465..75d96db08cce 100644 --- a/Sources/DockSplitStore.swift +++ b/Sources/DockSplitStore.swift @@ -392,6 +392,7 @@ final class DockSplitStore: BonsplitDelegate { func focusPanel(_ panelId: UUID) { guard let paneId = paneId(forPanelId: panelId), let tabId = surfaceId(forPanelId: panelId) else { return } + (panels[panelId] as? BrowserPanel)?.browserWebExtensionHost?.noteActivated(panelID: panelId) bonsplitController.focusPane(paneId) bonsplitController.selectTab(tabId) applyDockSelection(tabId: tabId, inPane: paneId) @@ -570,6 +571,7 @@ final class DockSplitStore: BonsplitDelegate { .sink { [weak self, weak browser] _ in guard let self, let browser, let tabId = self.surfaceId(forPanelId: browser.id), let existing = self.bonsplitController.tab(tabId) else { return } + browser.browserWebExtensionHost?.noteTabMetadataChanged(panelID: browser.id) // Only push fields that actually changed; otherwise unchanged metadata // would mutate Bonsplit and re-render the Dock tree for nothing. // Mirrors the main area's guarded path in Workspace.installBrowserPanelSubscription. diff --git a/Sources/Panels/BrowserWebExtensionHosting.swift b/Sources/Panels/BrowserWebExtensionHosting.swift index f58d513a1340..b0466edbeb40 100644 --- a/Sources/Panels/BrowserWebExtensionHosting.swift +++ b/Sources/Panels/BrowserWebExtensionHosting.swift @@ -7,5 +7,6 @@ protocol BrowserWebExtensionHosting: AnyObject { func register(panel: BrowserPanel) func unregister(panelID: UUID) func noteActivated(panelID: UUID) + func noteTabMetadataChanged(panelID: UUID) func performCommand(for event: NSEvent) -> Bool } diff --git a/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift b/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift index 42ced54a7bb8..af5b9828239b 100644 --- a/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift +++ b/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift @@ -56,19 +56,50 @@ extension BrowserWebExtensionSupport: WKWebExtensionControllerDelegate { #if DEBUG cmuxDebugLog("browser.webext.openTab url=\(configuration.url?.absoluteString.prefix(80) ?? "nil")") #endif - if let url = configuration.url, url.scheme == "https" || url.scheme == "http" { - NSWorkspace.shared.open(url) - completionHandler(nil, nil) + if let url = configuration.url, + let scheme = url.scheme?.lowercased(), + scheme != "https" && scheme != "http" { + completionHandler(nil, openTabsUnsupportedError()) return } - completionHandler(nil, NSError( + + guard let adapter = openBrowserTab(url: configuration.url, shouldActivate: configuration.shouldBeActive) else { + completionHandler(nil, openTabsUnsupportedError()) + return + } + completionHandler(adapter, nil) + } + + private func openBrowserTab(url: URL?, shouldActivate: Bool) -> BrowserWebExtensionTabAdapter? { + guard let sourcePanel = activeTabAdapter?.panel, + let workspace = AppDelegate.shared?.workspaceContainingPanel( + panelId: sourcePanel.id, + preferredWorkspaceId: sourcePanel.workspaceId + )?.workspace, + let paneId = workspace.paneId(forPanelId: sourcePanel.id), + let panel = workspace.newBrowserSurface( + inPane: paneId, + url: url, + focus: shouldActivate, + preferredProfileID: sourcePanel.profileID + ) else { + return nil + } + if shouldActivate { + noteActivated(panelID: panel.id) + } + return tabAdapter(for: panel.id) + } + + private func openTabsUnsupportedError() -> NSError { + NSError( domain: "cmux.webExtension", code: 2, userInfo: [NSLocalizedDescriptionKey: String( localized: "browser.webExtension.error.openTabsUnsupported", defaultValue: "Opening extension tabs is not supported yet." )] - )) + ) } func webExtensionController( diff --git a/Sources/Panels/BrowserWebExtensionSupport.swift b/Sources/Panels/BrowserWebExtensionSupport.swift index e8827cf51cd2..8fe4a760d1ed 100644 --- a/Sources/Panels/BrowserWebExtensionSupport.swift +++ b/Sources/Panels/BrowserWebExtensionSupport.swift @@ -129,6 +129,11 @@ final class BrowserWebExtensionSupport: NSObject, BrowserWebExtensionHosting { } } + func noteTabMetadataChanged(panelID: UUID) { + guard let adapter = tabAdapters[panelID] else { return } + controller.didChangeTabProperties([.title, .URL, .loading, .muted], for: adapter) + } + func tabAdapter(for panelID: UUID) -> BrowserWebExtensionTabAdapter? { tabAdapters[panelID] } diff --git a/Sources/Workspace.swift b/Sources/Workspace.swift index 50f337910e97..45ee132482b8 100644 --- a/Sources/Workspace.swift +++ b/Sources/Workspace.swift @@ -3601,6 +3601,7 @@ final class Workspace: Identifiable, ObservableObject { guard let self = self, let browserPanel = browserPanel, let tabId = self.surfaceIdFromPanelId(browserPanel.id) else { return } + browserPanel.browserWebExtensionHost?.noteTabMetadataChanged(panelID: browserPanel.id) self.publishBrowserOpenTabSuggestion(for: browserPanel) guard let existing = self.bonsplitController.tab(tabId) else { return } let nextTitle = browserPanel.displayTitle diff --git a/cmuxTests/BrowserPrewarmedWebViewPoolTests.swift b/cmuxTests/BrowserPrewarmedWebViewPoolTests.swift index e59bbdfb7c70..83971ea2de0a 100644 --- a/cmuxTests/BrowserPrewarmedWebViewPoolTests.swift +++ b/cmuxTests/BrowserPrewarmedWebViewPoolTests.swift @@ -58,6 +58,8 @@ private final class PrewarmTestWebExtensionHost: BrowserWebExtensionHosting { func noteActivated(panelID: UUID) {} + func noteTabMetadataChanged(panelID: UUID) {} + func performCommand(for event: NSEvent) -> Bool { false } } From c3a9f1b92f1336b8203fd2744c7e6a4c4cf1e19f Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 04:26:59 -0700 Subject: [PATCH 18/51] Hide imported extension paths from import menu --- .../CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift index d45b1047ac36..9eae19f112a1 100644 --- a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift +++ b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift @@ -45,7 +45,11 @@ struct BrowserWebExtensionsCard: View { /// Discovered Safari extensions not yet added, offered by the Import menu. private var importableExtensions: [SettingsDiscoveredBrowserExtension] { let addedIDs = Set(model.current.map(\.id)) - return discovered.filter { !addedIDs.contains($0.id) } + let addedPaths = Set(model.current.map { standardizedPath($0.path) }) + return discovered.filter { candidate in + !addedIDs.contains(candidate.id) + && !addedPaths.contains(standardizedPath(candidate.path)) + } } private var headerRow: some View { From e685c71ce68afca6cffb908dc1aa9ed7ae14b54a Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 04:39:05 -0700 Subject: [PATCH 19/51] Support extension tabs and action updates --- Sources/Panels/BrowserPanel.swift | 21 +++++----- .../BrowserWebExtensionActionSnapshot.swift | 3 ++ .../BrowserWebExtensionSupport+Loading.swift | 36 +++++++++++++----- ...ort+WKWebExtensionControllerDelegate.swift | 32 +++++++++++++--- .../Panels/BrowserWebExtensionSupport.swift | 1 + .../BrowserWebExtensionToolbarButtons.swift | 38 +++++++++++++------ Sources/Workspace.swift | 7 +++- 7 files changed, 101 insertions(+), 37 deletions(-) diff --git a/Sources/Panels/BrowserPanel.swift b/Sources/Panels/BrowserPanel.swift index f8b0080e2653..45d120a1615d 100644 --- a/Sources/Panels/BrowserPanel.swift +++ b/Sources/Panels/BrowserPanel.swift @@ -3541,14 +3541,13 @@ final class BrowserPanel: Panel, ObservableObject { static func makeWebView( profileID: UUID, websiteDataStore: WKWebsiteDataStore? = nil, - browserWebExtensionHost: (any BrowserWebExtensionHosting)? = nil + browserWebExtensionHost: (any BrowserWebExtensionHosting)? = nil, + webViewConfiguration: WKWebViewConfiguration? = nil ) -> CmuxWebView { - let config = WKWebViewConfiguration() - configureWebViewConfiguration( - config, - websiteDataStore: websiteDataStore ?? BrowserProfileStore.shared.websiteDataStore(for: profileID), - browserWebExtensionHost: browserWebExtensionHost - ) + let config = webViewConfiguration ?? WKWebViewConfiguration() + if webViewConfiguration == nil { + configureWebViewConfiguration(config, websiteDataStore: websiteDataStore ?? BrowserProfileStore.shared.websiteDataStore(for: profileID), browserWebExtensionHost: browserWebExtensionHost) + } let webView = CmuxWebView(frame: .zero, configuration: config) webView.allowsBackForwardNavigationGestures = true @@ -3954,7 +3953,8 @@ final class BrowserPanel: Panel, ObservableObject { bypassRemoteProxy: Bool = false, isRemoteWorkspace: Bool = false, remoteWebsiteDataStoreIdentifier: UUID? = nil, - browserWebExtensionHost: (any BrowserWebExtensionHosting)? = nil + browserWebExtensionHost: (any BrowserWebExtensionHosting)? = nil, + webViewConfiguration: WKWebViewConfiguration? = nil ) { // Register fallback defaults and normalize legacy/out-of-range settings once // per process, before any setting is read below or by the SwiftUI view. @@ -3979,7 +3979,7 @@ final class BrowserPanel: Panel, ObservableObject { self.browserWebExtensionHost = browserWebExtensionHost let webView: CmuxWebView var adoptedPrewarmedWebView = false - if let prewarmed = Self.claimedPrewarmedWebView( + if webViewConfiguration == nil, let prewarmed = Self.claimedPrewarmedWebView( isRemoteWorkspace: isRemoteWorkspace, initialRequest: initialRequest, renderInitialNavigation: renderInitialNavigation, @@ -3994,7 +3994,8 @@ final class BrowserPanel: Panel, ObservableObject { webView = Self.makeWebView( profileID: resolvedProfileID, websiteDataStore: websiteDataStore, - browserWebExtensionHost: browserWebExtensionHost + browserWebExtensionHost: browserWebExtensionHost, + webViewConfiguration: webViewConfiguration ) } self.webView = webView diff --git a/Sources/Panels/BrowserWebExtensionActionSnapshot.swift b/Sources/Panels/BrowserWebExtensionActionSnapshot.swift index db5ab718dc99..13aee9c13899 100644 --- a/Sources/Panels/BrowserWebExtensionActionSnapshot.swift +++ b/Sources/Panels/BrowserWebExtensionActionSnapshot.swift @@ -5,6 +5,9 @@ struct BrowserWebExtensionActionSnapshot: Identifiable { let id: String let displayName: String let icon: NSImage? + let isEnabled: Bool + let badgeText: String + let hasUnreadBadgeText: Bool var accessibilityIdentifier: String { let safeID = id.map { character in diff --git a/Sources/Panels/BrowserWebExtensionSupport+Loading.swift b/Sources/Panels/BrowserWebExtensionSupport+Loading.swift index c4803a8d55ea..2b40ee738ad2 100644 --- a/Sources/Panels/BrowserWebExtensionSupport+Loading.swift +++ b/Sources/Panels/BrowserWebExtensionSupport+Loading.swift @@ -36,16 +36,34 @@ extension BrowserWebExtensionSupport { } func rebuildActionSnapshots() { - actionSnapshots = loadedRecordsInOrder.map { record in - BrowserWebExtensionActionSnapshot( - id: record.entryID, - displayName: record.context.webExtension.displayName ?? String( - localized: "browser.webExtension.action.help", - defaultValue: "Extension" - ), - icon: record.context.webExtension.icon(for: CGSize(width: 32, height: 32)) - ) + actionSnapshots = loadedRecordsInOrder.map { actionSnapshot(for: $0) } + } + + func refreshActionSnapshot(for context: WKWebExtensionContext) { + guard let record = loadedRecordsInOrder.first(where: { $0.context === context }) else { return } + var snapshots = actionSnapshots + guard let index = snapshots.firstIndex(where: { $0.id == record.entryID }) else { + rebuildActionSnapshots() + return } + snapshots[index] = actionSnapshot(for: record) + actionSnapshots = snapshots + } + + private func actionSnapshot(for record: BrowserWebExtensionLoadedRecord) -> BrowserWebExtensionActionSnapshot { + let action = record.context.action(for: activeTabAdapter) + return BrowserWebExtensionActionSnapshot( + id: record.entryID, + displayName: action?.label ?? record.context.webExtension.displayName ?? String( + localized: "browser.webExtension.action.help", + defaultValue: "Extension" + ), + icon: action?.icon(for: CGSize(width: 32, height: 32)) + ?? record.context.webExtension.icon(for: CGSize(width: 32, height: 32)), + isEnabled: action?.isEnabled ?? true, + badgeText: action?.badgeText ?? "", + hasUnreadBadgeText: action?.hasUnreadBadgeText ?? false + ) } private func unload(entryID: String) { diff --git a/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift b/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift index af5b9828239b..5eefde64220d 100644 --- a/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift +++ b/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift @@ -57,20 +57,28 @@ extension BrowserWebExtensionSupport: WKWebExtensionControllerDelegate { cmuxDebugLog("browser.webext.openTab url=\(configuration.url?.absoluteString.prefix(80) ?? "nil")") #endif if let url = configuration.url, - let scheme = url.scheme?.lowercased(), - scheme != "https" && scheme != "http" { + !canOpenInRegularBrowserTab(url), + controller.extensionContext(for: url) == nil { completionHandler(nil, openTabsUnsupportedError()) return } - guard let adapter = openBrowserTab(url: configuration.url, shouldActivate: configuration.shouldBeActive) else { + guard let adapter = openBrowserTab( + url: configuration.url, + shouldActivate: configuration.shouldBeActive, + webViewConfiguration: configuration.url.flatMap { controller.extensionContext(for: $0)?.webViewConfiguration } + ) else { completionHandler(nil, openTabsUnsupportedError()) return } completionHandler(adapter, nil) } - private func openBrowserTab(url: URL?, shouldActivate: Bool) -> BrowserWebExtensionTabAdapter? { + private func openBrowserTab( + url: URL?, + shouldActivate: Bool, + webViewConfiguration: WKWebViewConfiguration? + ) -> BrowserWebExtensionTabAdapter? { guard let sourcePanel = activeTabAdapter?.panel, let workspace = AppDelegate.shared?.workspaceContainingPanel( panelId: sourcePanel.id, @@ -81,7 +89,8 @@ extension BrowserWebExtensionSupport: WKWebExtensionControllerDelegate { inPane: paneId, url: url, focus: shouldActivate, - preferredProfileID: sourcePanel.profileID + preferredProfileID: sourcePanel.profileID, + webViewConfiguration: webViewConfiguration ) else { return nil } @@ -91,6 +100,11 @@ extension BrowserWebExtensionSupport: WKWebExtensionControllerDelegate { return tabAdapter(for: panel.id) } + private func canOpenInRegularBrowserTab(_ url: URL) -> Bool { + guard let scheme = url.scheme?.lowercased() else { return true } + return scheme == "http" || scheme == "https" || scheme == "about" + } + private func openTabsUnsupportedError() -> NSError { NSError( domain: "cmux.webExtension", @@ -102,6 +116,14 @@ extension BrowserWebExtensionSupport: WKWebExtensionControllerDelegate { ) } + func webExtensionController( + _ controller: WKWebExtensionController, + didUpdate action: WKWebExtension.Action, + forExtensionContext context: WKWebExtensionContext + ) { + refreshActionSnapshot(for: context) + } + func webExtensionController( _ controller: WKWebExtensionController, presentActionPopup action: WKWebExtension.Action, diff --git a/Sources/Panels/BrowserWebExtensionSupport.swift b/Sources/Panels/BrowserWebExtensionSupport.swift index 8fe4a760d1ed..24aae240789b 100644 --- a/Sources/Panels/BrowserWebExtensionSupport.swift +++ b/Sources/Panels/BrowserWebExtensionSupport.swift @@ -127,6 +127,7 @@ final class BrowserWebExtensionSupport: NSObject, BrowserWebExtensionHosting { if let adapter = tabAdapters[panelID] { controller.didActivateTab(adapter, previousActiveTab: previous) } + rebuildActionSnapshots() } func noteTabMetadataChanged(panelID: UUID) { diff --git a/Sources/Panels/BrowserWebExtensionToolbarButtons.swift b/Sources/Panels/BrowserWebExtensionToolbarButtons.swift index 03ca93b5c23d..fd065e3bec46 100644 --- a/Sources/Panels/BrowserWebExtensionToolbarButtons.swift +++ b/Sources/Panels/BrowserWebExtensionToolbarButtons.swift @@ -53,23 +53,39 @@ private struct BrowserWebExtensionActionButton: View { } .buttonStyle(OmnibarAddressButtonStyle()) .background(BrowserWebExtensionAnchorViewReader(holder: anchorViewHolder)) + .disabled(!snapshot.isEnabled) + .opacity(snapshot.isEnabled ? 1 : 0.45) .safeHelp(snapshot.displayName) .accessibilityIdentifier(snapshot.accessibilityIdentifier) } @ViewBuilder private var actionIcon: some View { - if let icon = snapshot.icon { - Image(nsImage: icon) - .resizable() - .aspectRatio(contentMode: .fit) - .frame(width: iconPointSize + 3, height: iconPointSize + 3) - } else { - CmuxSystemSymbolImage( - systemName: "puzzlepiece.extension", - pointSize: iconPointSize, - weight: .medium - ) + ZStack(alignment: .topTrailing) { + if let icon = snapshot.icon { + Image(nsImage: icon) + .resizable() + .aspectRatio(contentMode: .fit) + .frame(width: iconPointSize + 3, height: iconPointSize + 3) + } else { + CmuxSystemSymbolImage( + systemName: "puzzlepiece.extension", + pointSize: iconPointSize, + weight: .medium + ) + } + if !snapshot.badgeText.isEmpty { + Text(snapshot.badgeText) + .font(.system(size: 8, weight: snapshot.hasUnreadBadgeText ? .bold : .semibold)) + .lineLimit(1) + .truncationMode(.tail) + .minimumScaleFactor(0.65) + .padding(.horizontal, 3) + .frame(minWidth: 10, maxWidth: 20, minHeight: 10) + .background(Capsule().fill(Color.accentColor)) + .foregroundStyle(.white) + .offset(x: 5, y: -4) + } } } } diff --git a/Sources/Workspace.swift b/Sources/Workspace.swift index 45ee132482b8..e17f79b61ea8 100644 --- a/Sources/Workspace.swift +++ b/Sources/Workspace.swift @@ -23,6 +23,7 @@ import CryptoKit import Darwin import Network import CoreText +import WebKit #if DEBUG func debugWorkspaceDescriptionPreview(_ text: String?, limit: Int = 120) -> String { @@ -8042,7 +8043,8 @@ final class Workspace: Identifiable, ObservableObject { creationPolicy: BrowserPanelCreationPolicy = .userInitiated, omnibarVisible: Bool = true, transparentBackground: Bool = false, - bypassRemoteProxy: Bool = false + bypassRemoteProxy: Bool = false, + webViewConfiguration: WKWebViewConfiguration? = nil ) -> BrowserPanel? { // A remote tmux mirror workspace is a 1:1 view of a tmux session (which // has no browser concept). A local browser tab here would be an orphan @@ -8079,7 +8081,8 @@ final class Workspace: Identifiable, ObservableObject { bypassRemoteProxy: bypassRemoteProxy, isRemoteWorkspace: isRemoteWorkspace, remoteWebsiteDataStoreIdentifier: isRemoteWorkspace && !bypassRemoteProxy ? id : nil, - browserWebExtensionHost: browserWebExtensionHost + browserWebExtensionHost: browserWebExtensionHost, + webViewConfiguration: webViewConfiguration ) configureBrowserPanel(browserPanel) panels[browserPanel.id] = browserPanel From cc43b8114f5ef82453c62b499199dc98b92a67f4 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 04:50:29 -0700 Subject: [PATCH 20/51] Align web extension tab lifecycle with cmux focus --- .../BrowserWebExtensionTabAdapter.swift | 31 +++++++++++++++++-- Sources/Workspace.swift | 2 +- 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/Sources/Panels/BrowserWebExtensionTabAdapter.swift b/Sources/Panels/BrowserWebExtensionTabAdapter.swift index 579ec07e3c1e..1f961b4cc47c 100644 --- a/Sources/Panels/BrowserWebExtensionTabAdapter.swift +++ b/Sources/Panels/BrowserWebExtensionTabAdapter.swift @@ -48,12 +48,23 @@ final class BrowserWebExtensionTabAdapter: NSObject, WKWebExtensionTab { } func activate(for context: WKWebExtensionContext, completionHandler: @escaping (Error?) -> Void) { - support?.noteActivated(panelID: panelID) - completionHandler(nil) + completionHandler(focusOwningCmuxTab() ? nil : webExtensionTabError(code: 3)) + } + + func setSelected(_ selected: Bool, for context: WKWebExtensionContext, completionHandler: @escaping (Error?) -> Void) { + guard selected else { + completionHandler(nil) + return + } + completionHandler(focusOwningCmuxTab() ? nil : webExtensionTabError(code: 3)) } func loadURL(_ url: URL, for context: WKWebExtensionContext, completionHandler: @escaping (Error?) -> Void) { - panel?.webView.load(URLRequest(url: url)) + guard let panel else { + completionHandler(webExtensionTabError(code: 4)) + return + } + panel.navigate(to: url) completionHandler(nil) } @@ -75,4 +86,18 @@ final class BrowserWebExtensionTabAdapter: NSObject, WKWebExtensionTab { panel?.webView.goForward() completionHandler(nil) } + + private func focusOwningCmuxTab() -> Bool { + guard let panel else { return false } + guard let workspace = AppDelegate.shared?.workspaceContainingPanel( + panelId: panelID, + preferredWorkspaceId: panel.workspaceId + )?.workspace else { return false } + workspace.focusPanel(panelID) + return true + } + + private func webExtensionTabError(code: Int) -> NSError { + NSError(domain: "cmux.webExtension.tab", code: code) + } } diff --git a/Sources/Workspace.swift b/Sources/Workspace.swift index e17f79b61ea8..979258e7eab5 100644 --- a/Sources/Workspace.swift +++ b/Sources/Workspace.swift @@ -3536,6 +3536,7 @@ final class Workspace: Identifiable, ObservableObject { } private func configureBrowserPanel(_ browserPanel: BrowserPanel) { + browserPanel.registerWebExtensionIfNeeded() browserPanel.webViewDidRequestClose = { [weak self, weak browserPanel] in guard let self, let browserPanel else { return } guard self.panels[browserPanel.id] is BrowserPanel else { return } @@ -3589,7 +3590,6 @@ final class Workspace: Identifiable, ObservableObject { } private func installBrowserPanelSubscription(_ browserPanel: BrowserPanel) { - browserPanel.registerWebExtensionIfNeeded() let browserTabState = Publishers.CombineLatest4( browserPanel.$pageTitle.removeDuplicates(), browserPanel.$currentURL.removeDuplicates(), browserPanel.$isLoading.removeDuplicates(), browserPanel.$faviconPNGData.removeDuplicates(by: { $0 == $1 }) From b6bda5b79c59e387ff8b2561fffc4ec5333f7feb Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 04:55:11 -0700 Subject: [PATCH 21/51] Deduplicate Safari extension resource paths --- .../Sections/BrowserWebExtensionsCard.swift | 25 ++++++++++++++++--- 1 file changed, 22 insertions(+), 3 deletions(-) diff --git a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift index 9eae19f112a1..46381d74b5d9 100644 --- a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift +++ b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift @@ -45,10 +45,10 @@ struct BrowserWebExtensionsCard: View { /// Discovered Safari extensions not yet added, offered by the Import menu. private var importableExtensions: [SettingsDiscoveredBrowserExtension] { let addedIDs = Set(model.current.map(\.id)) - let addedPaths = Set(model.current.map { standardizedPath($0.path) }) + let addedResourcePaths = Set(model.current.map { standardizedResourcePath(for: $0) }) return discovered.filter { candidate in !addedIDs.contains(candidate.id) - && !addedPaths.contains(standardizedPath(candidate.path)) + && !addedResourcePaths.contains(standardizedSafariAppExtensionResourcePath(candidate.path)) } } @@ -166,7 +166,8 @@ struct BrowserWebExtensionsCard: View { presentDuplicateExtensionAlert(for: entry) return } - guard !entries.contains(where: { standardizedPath($0.path) == standardizedPath(entry.path) }) else { + let entryResourcePath = standardizedResourcePath(for: entry) + guard !entries.contains(where: { standardizedResourcePath(for: $0) == entryResourcePath }) else { presentDuplicateExtensionAlert(for: entry) return } @@ -263,4 +264,22 @@ struct BrowserWebExtensionsCard: View { private func standardizedPath(_ path: String) -> String { URL(fileURLWithPath: path).standardizedFileURL.path } + + private func standardizedResourcePath(for entry: BrowserWebExtensionEntry) -> String { + switch entry.kind { + case .safariAppExtension: + return standardizedSafariAppExtensionResourcePath(entry.path) + case .unpackedDirectory: + return standardizedPath(entry.path) + } + } + + private func standardizedSafariAppExtensionResourcePath(_ path: String) -> String { + let url = URL(fileURLWithPath: path) + guard url.pathExtension == "appex" else { return standardizedPath(path) } + return url + .appendingPathComponent("Contents/Resources", isDirectory: true) + .standardizedFileURL + .path + } } From c2bb853be9ed7f5c358ced1e3c3998447c7721ca Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 05:15:41 -0700 Subject: [PATCH 22/51] Persist web extension navigation state --- .../Panels/BrowserNavigationDelegate.swift | 16 ++++ Sources/Panels/BrowserPanel.swift | 93 ++++++++++++++++++- .../Panels/BrowserWebExtensionHosting.swift | 1 + ...rWebExtensionNavigationConfiguration.swift | 6 ++ .../BrowserWebExtensionPermissionState.swift | 81 ++++++++++++++++ ...wserWebExtensionPermissionStateStore.swift | 38 ++++++++ .../BrowserWebExtensionSupport+Loading.swift | 15 ++- ...owserWebExtensionSupport+Permissions.swift | 67 +++++++++++++ ...ort+WKWebExtensionControllerDelegate.swift | 5 +- .../Panels/BrowserWebExtensionSupport.swift | 20 ++++ cmux.xcodeproj/project.pbxproj | 16 ++++ .../BrowserWebExtensionSupportTests.swift | 34 +++++++ 12 files changed, 386 insertions(+), 6 deletions(-) create mode 100644 Sources/Panels/BrowserWebExtensionNavigationConfiguration.swift create mode 100644 Sources/Panels/BrowserWebExtensionPermissionState.swift create mode 100644 Sources/Panels/BrowserWebExtensionPermissionStateStore.swift create mode 100644 Sources/Panels/BrowserWebExtensionSupport+Permissions.swift diff --git a/Sources/Panels/BrowserNavigationDelegate.swift b/Sources/Panels/BrowserNavigationDelegate.swift index 86c10b9c8a99..bfd1b7e66369 100644 --- a/Sources/Panels/BrowserNavigationDelegate.swift +++ b/Sources/Panels/BrowserNavigationDelegate.swift @@ -21,6 +21,7 @@ import WebKit var shouldBlockInsecureHTTPSubframeDownload: ((URL) -> Bool)? var handleBlockedInsecureHTTPNavigation: ((URLRequest, BrowserInsecureHTTPNavigationIntent) -> Void)? var handleDroppedFileNavigation: (([URL]) -> Bool)? + var shouldReissueNavigationForWebExtensionConfiguration: ((URLRequest) -> Bool)? var currentRestoreAttemptID: (() -> UUID?)? var terminalPolicyCancellationReporter: ((WKNavigationAction, WKWebView) -> () -> Void)? var didRenderPDFDocument: ((URL, Bool) -> Void)? @@ -329,6 +330,21 @@ import WebKit return } + if navigationAction.targetFrame?.isMainFrame == true, + !shouldOpenInNewTab, + shouldReissueNavigationForWebExtensionConfiguration?(navigationAction.request) == true, + let requestNavigation { +#if DEBUG + cmuxDebugLog( + "browser.nav.decidePolicy.action kind=webExtensionConfigurationSwap " + + "url=\(browserNavigationDebugURL(navigationAction.request.url))" + ) +#endif + requestNavigation(navigationAction.request, .currentTab) + decisionHandler(.cancel) + return + } + if let url = navigationAction.request.url, browserShouldRouteExternalNavigation(url) { clearAttemptedRequest(discardPendingBypasses: true) diff --git a/Sources/Panels/BrowserPanel.swift b/Sources/Panels/BrowserPanel.swift index 45d120a1615d..2239cfbe3c10 100644 --- a/Sources/Panels/BrowserPanel.swift +++ b/Sources/Panels/BrowserPanel.swift @@ -993,6 +993,7 @@ private let browserEmbeddedNavigationSchemes: Set = [ "http", "https", "javascript", + "webkit-extension", ] func browserShouldOpenURLExternally(_ url: URL) -> Bool { @@ -2747,6 +2748,7 @@ final class BrowserPanel: Panel, ObservableObject { private(set) var webView: WKWebView private var websiteDataStore: WKWebsiteDataStore let browserWebExtensionHost: (any BrowserWebExtensionHosting)? + private var webExtensionPageContextIdentifier: ObjectIdentifier? private var isRegisteredForWebExtensions = false var webViewDidRequestClose: (() -> Void)? @@ -3977,9 +3979,14 @@ final class BrowserPanel: Panel, ObservableObject { : BrowserProfileStore.shared.websiteDataStore(for: resolvedProfileID) self.websiteDataStore = websiteDataStore self.browserWebExtensionHost = browserWebExtensionHost + let initialExtensionNavigationConfiguration = (initialRequest?.url ?? initialURL).flatMap { + browserWebExtensionHost?.webViewConfiguration(forNavigatingTo: $0) + } + let initialWebViewConfiguration = webViewConfiguration + ?? initialExtensionNavigationConfiguration?.webViewConfiguration let webView: CmuxWebView var adoptedPrewarmedWebView = false - if webViewConfiguration == nil, let prewarmed = Self.claimedPrewarmedWebView( + if initialWebViewConfiguration == nil, let prewarmed = Self.claimedPrewarmedWebView( isRemoteWorkspace: isRemoteWorkspace, initialRequest: initialRequest, renderInitialNavigation: renderInitialNavigation, @@ -3995,10 +4002,11 @@ final class BrowserPanel: Panel, ObservableObject { profileID: resolvedProfileID, websiteDataStore: websiteDataStore, browserWebExtensionHost: browserWebExtensionHost, - webViewConfiguration: webViewConfiguration + webViewConfiguration: initialWebViewConfiguration ) } self.webView = webView + webExtensionPageContextIdentifier = initialExtensionNavigationConfiguration?.contextIdentifier self.insecureHTTPAlertFactory = { NSAlert() } hiddenWebViewDiscardManager.delegate = self applyProxyConfigurationIfAvailable() @@ -4012,6 +4020,9 @@ final class BrowserPanel: Panel, ObservableObject { navDelegate.requestNavigation = { [weak self] request, intent in self?.requestNavigation(request, intent: intent) } + navDelegate.shouldReissueNavigationForWebExtensionConfiguration = { [weak self] request in + self?.needsWebExtensionNavigationConfigurationSwap(for: request) ?? false + } navDelegate.presentAlert = { [weak self] alert, webView, completion, cancel in guard let self else { cancel() @@ -5807,6 +5818,7 @@ final class BrowserPanel: Panel, ObservableObject { abandonRestoredSessionHistoryIfNeeded() } let effectiveRequest = remoteProxyPreparedRequest(from: request, logScope: "rewrite") + ensureWebExtensionNavigationConfiguration(for: originalURL) // Some installs can end up with a legacy Chrome UA override; keep this pinned. webView.customUserAgent = BrowserUserAgentSettings.safariUserAgent hiddenWebViewDiscardManager.updateRestoredSessionRenderIntent(nil) @@ -5830,6 +5842,83 @@ final class BrowserPanel: Panel, ObservableObject { } } + private func needsWebExtensionNavigationConfigurationSwap(for request: URLRequest) -> Bool { + guard let url = request.url else { return false } + let targetContextIdentifier = browserWebExtensionHost? + .webViewConfiguration(forNavigatingTo: url)? + .contextIdentifier + return targetContextIdentifier != webExtensionPageContextIdentifier + } + + private func ensureWebExtensionNavigationConfiguration(for url: URL) { + let targetConfiguration = browserWebExtensionHost?.webViewConfiguration(forNavigatingTo: url) + let targetContextIdentifier = targetConfiguration?.contextIdentifier + guard targetContextIdentifier != webExtensionPageContextIdentifier else { return } + replaceWebViewForWebExtensionNavigation( + webViewConfiguration: targetConfiguration?.webViewConfiguration, + contextIdentifier: targetContextIdentifier + ) + } + + private func replaceWebViewForWebExtensionNavigation( + webViewConfiguration: WKWebViewConfiguration?, + contextIdentifier: ObjectIdentifier? + ) { + let oldWebView = webView + let desiredZoom = max(minPageZoom, min(maxPageZoom, oldWebView.pageZoom)) + let reason = contextIdentifier == nil ? "webExtensionNavigation.leave" : "webExtensionNavigation.enter" + +#if DEBUG + cmuxDebugLog( + "browser.webext.webviewSwap panel=\(id.uuidString.prefix(5)) " + + "reason=\(reason)" + ) +#endif + + detachWebViewObservers() + clearBrowserFocusMode(reason: reason) + faviconTask?.cancel() + faviconTask = nil + faviconRefreshGeneration &+= 1 + loadingGeneration &+= 1 + loadingEndWorkItem?.cancel() + loadingEndWorkItem = nil + isLoading = false + estimatedProgress = 0 + cancelPendingInteractiveBrowserPrompts(reason: reason) + closeBackgroundPreloadHost(reason: reason) + BrowserWindowPortalRegistry.detach(webView: oldWebView) + webAuthnCoordinator.tearDown(from: oldWebView) + oldWebView.stopLoading() + isMainFrameProvisionalNavigationActive = false + oldWebView.navigationDelegate = nil + oldWebView.uiDelegate = nil + if let oldCmuxWebView = oldWebView as? CmuxWebView { + oldCmuxWebView.clearBrowserDownloadCallbacks() + } + + let replacement = Self.makeWebView( + profileID: profileID, + websiteDataStore: websiteDataStore, + browserWebExtensionHost: browserWebExtensionHost, + webViewConfiguration: webViewConfiguration + ) + replacement.pageZoom = desiredZoom + webViewInstanceID = UUID() + hasCommittedDocumentSinceWebViewReplacement = false + userStoppedLoadSinceWebViewReplacement = false + resetWebViewLifecycleMetadata(resetVisibility: false) + webView = replacement + webExtensionPageContextIdentifier = contextIdentifier + nativeCanGoBack = false + nativeCanGoForward = false + refreshWebViewLifecycleState() + bindWebView(replacement) + applyProxyConfigurationIfAvailable() + applyBrowserThemeModeIfNeeded() + refreshNavigationAvailability() + } + private func remoteProxyPreparedRequest(from request: URLRequest, logScope: String) -> URLRequest { guard remoteProxyEndpoint != nil else { return request } guard let url = request.url else { return request } diff --git a/Sources/Panels/BrowserWebExtensionHosting.swift b/Sources/Panels/BrowserWebExtensionHosting.swift index b0466edbeb40..4532b5968d5a 100644 --- a/Sources/Panels/BrowserWebExtensionHosting.swift +++ b/Sources/Panels/BrowserWebExtensionHosting.swift @@ -4,6 +4,7 @@ import WebKit @MainActor protocol BrowserWebExtensionHosting: AnyObject { func attach(to configuration: WKWebViewConfiguration) + func webViewConfiguration(forNavigatingTo url: URL) -> BrowserWebExtensionNavigationConfiguration? func register(panel: BrowserPanel) func unregister(panelID: UUID) func noteActivated(panelID: UUID) diff --git a/Sources/Panels/BrowserWebExtensionNavigationConfiguration.swift b/Sources/Panels/BrowserWebExtensionNavigationConfiguration.swift new file mode 100644 index 000000000000..eef7246a1d2a --- /dev/null +++ b/Sources/Panels/BrowserWebExtensionNavigationConfiguration.swift @@ -0,0 +1,6 @@ +import WebKit + +struct BrowserWebExtensionNavigationConfiguration { + let contextIdentifier: ObjectIdentifier + let webViewConfiguration: WKWebViewConfiguration +} diff --git a/Sources/Panels/BrowserWebExtensionPermissionState.swift b/Sources/Panels/BrowserWebExtensionPermissionState.swift new file mode 100644 index 000000000000..4385328c5f1a --- /dev/null +++ b/Sources/Panels/BrowserWebExtensionPermissionState.swift @@ -0,0 +1,81 @@ +import Foundation +import WebKit + +@available(macOS 15.4, *) +struct BrowserWebExtensionPermissionState: Codable, Equatable { + var grantedPermissions: [String: Date] = [:] + var deniedPermissions: [String: Date] = [:] + var grantedPermissionMatchPatterns: [String: Date] = [:] + var deniedPermissionMatchPatterns: [String: Date] = [:] + var hasRequestedOptionalAccessToAllHosts = false + var hasAccessToPrivateData = false + + init( + grantedPermissions: [String: Date] = [:], + deniedPermissions: [String: Date] = [:], + grantedPermissionMatchPatterns: [String: Date] = [:], + deniedPermissionMatchPatterns: [String: Date] = [:], + hasRequestedOptionalAccessToAllHosts: Bool = false, + hasAccessToPrivateData: Bool = false + ) { + self.grantedPermissions = grantedPermissions + self.deniedPermissions = deniedPermissions + self.grantedPermissionMatchPatterns = grantedPermissionMatchPatterns + self.deniedPermissionMatchPatterns = deniedPermissionMatchPatterns + self.hasRequestedOptionalAccessToAllHosts = hasRequestedOptionalAccessToAllHosts + self.hasAccessToPrivateData = hasAccessToPrivateData + } + + init(context: WKWebExtensionContext) { + grantedPermissions = Self.permissionState(context.grantedPermissions) + deniedPermissions = Self.permissionState(context.deniedPermissions) + grantedPermissionMatchPatterns = Self.matchPatternState(context.grantedPermissionMatchPatterns) + deniedPermissionMatchPatterns = Self.matchPatternState(context.deniedPermissionMatchPatterns) + hasRequestedOptionalAccessToAllHosts = context.hasRequestedOptionalAccessToAllHosts + hasAccessToPrivateData = context.hasAccessToPrivateData + } + + func apply(to context: WKWebExtensionContext) { + context.grantedPermissions = Self.permissionDictionary(grantedPermissions) + context.deniedPermissions = Self.permissionDictionary(deniedPermissions) + context.grantedPermissionMatchPatterns = Self.matchPatternDictionary(grantedPermissionMatchPatterns) + context.deniedPermissionMatchPatterns = Self.matchPatternDictionary(deniedPermissionMatchPatterns) + context.hasRequestedOptionalAccessToAllHosts = hasRequestedOptionalAccessToAllHosts + context.hasAccessToPrivateData = hasAccessToPrivateData + } + + private static func permissionState(_ values: [WKWebExtension.Permission: Date]) -> [String: Date] { + var state: [String: Date] = [:] + for (permission, expirationDate) in values { + state[permission.rawValue] = expirationDate + } + return state + } + + private static func matchPatternState(_ values: [WKWebExtension.MatchPattern: Date]) -> [String: Date] { + var state: [String: Date] = [:] + for (matchPattern, expirationDate) in values { + state[matchPattern.string] = expirationDate + } + return state + } + + private static func permissionDictionary(_ values: [String: Date]) -> [WKWebExtension.Permission: Date] { + let now = Date() + return Dictionary(uniqueKeysWithValues: values.compactMap { rawValue, expirationDate in + guard expirationDate > now else { return nil } + return (WKWebExtension.Permission(rawValue: rawValue), expirationDate) + }) + } + + private static func matchPatternDictionary(_ values: [String: Date]) -> [WKWebExtension.MatchPattern: Date] { + let now = Date() + return Dictionary(uniqueKeysWithValues: values.compactMap { rawValue, expirationDate in + guard expirationDate > now, + let matchPattern = try? WKWebExtension.MatchPattern(string: rawValue) else { + return nil + } + return (matchPattern, expirationDate) + }) + } +} diff --git a/Sources/Panels/BrowserWebExtensionPermissionStateStore.swift b/Sources/Panels/BrowserWebExtensionPermissionStateStore.swift new file mode 100644 index 000000000000..02fa70554e6d --- /dev/null +++ b/Sources/Panels/BrowserWebExtensionPermissionStateStore.swift @@ -0,0 +1,38 @@ +import Foundation + +@available(macOS 15.4, *) +struct BrowserWebExtensionPermissionStateStore { + private static let storageKey = "browser.webExtensionPermissionStates.v1" + + private let defaults: UserDefaults + + init(defaults: UserDefaults = .standard) { + self.defaults = defaults + } + + func state(for entryID: String) -> BrowserWebExtensionPermissionState? { + allStates()[entryID] + } + + func save(_ state: BrowserWebExtensionPermissionState, for entryID: String) { + var states = allStates() + states[entryID] = state + saveAllStates(states) + } + + private func allStates() -> [String: BrowserWebExtensionPermissionState] { + guard let data = defaults.data(forKey: Self.storageKey), + let states = try? PropertyListDecoder().decode( + [String: BrowserWebExtensionPermissionState].self, + from: data + ) else { + return [:] + } + return states + } + + private func saveAllStates(_ states: [String: BrowserWebExtensionPermissionState]) { + guard let data = try? PropertyListEncoder().encode(states) else { return } + defaults.set(data, forKey: Self.storageKey) + } +} diff --git a/Sources/Panels/BrowserWebExtensionSupport+Loading.swift b/Sources/Panels/BrowserWebExtensionSupport+Loading.swift index 2b40ee738ad2..49d5e8fe18a5 100644 --- a/Sources/Panels/BrowserWebExtensionSupport+Loading.swift +++ b/Sources/Panels/BrowserWebExtensionSupport+Loading.swift @@ -68,6 +68,7 @@ extension BrowserWebExtensionSupport { private func unload(entryID: String) { guard let record = loadedByEntryID[entryID] else { return } + persistPermissionState(entryID: entryID, context: record.context) do { try controller.unload(record.context) } catch { @@ -78,6 +79,7 @@ extension BrowserWebExtensionSupport { return } + removePermissionStateObservers(entryID: entryID) loadedByEntryID[entryID] = nil loadedEntryIDsInOrder.removeAll { $0 == entryID } loadErrorsByEntryID.removeValue(forKey: entryID) @@ -95,7 +97,7 @@ extension BrowserWebExtensionSupport { private func load(entry: BrowserWebExtensionEntry) async { do { let webExtension = try await makeWebExtension(for: entry) - let context = try load(webExtension) + let context = try load(webExtension, entryID: entry.id) let standardizedPath = BrowserWebExtensionReconciliationPlanner.standardizedPath(entry.path) loadedByEntryID[entry.id] = BrowserWebExtensionLoadedRecord( entryID: entry.id, @@ -134,12 +136,19 @@ extension BrowserWebExtensionSupport { } @discardableResult - private func load(_ webExtension: WKWebExtension) throws -> WKWebExtensionContext { + private func load(_ webExtension: WKWebExtension, entryID: String) throws -> WKWebExtensionContext { let context = WKWebExtensionContext(for: webExtension) #if DEBUG context.isInspectable = true #endif - try controller.load(context) + restorePermissionState(for: context, entryID: entryID) + installPermissionStateObservers(for: context, entryID: entryID) + do { + try controller.load(context) + } catch { + removePermissionStateObservers(entryID: entryID) + throw error + } return context } diff --git a/Sources/Panels/BrowserWebExtensionSupport+Permissions.swift b/Sources/Panels/BrowserWebExtensionSupport+Permissions.swift new file mode 100644 index 000000000000..98eb2652b2dd --- /dev/null +++ b/Sources/Panels/BrowserWebExtensionSupport+Permissions.swift @@ -0,0 +1,67 @@ +import Foundation +import WebKit + +@available(macOS 15.4, *) +extension BrowserWebExtensionSupport { + func restorePermissionState(for context: WKWebExtensionContext, entryID: String) { + permissionStateStore.state(for: entryID)?.apply(to: context) + } + + func persistPermissionState(entryID: String, context: WKWebExtensionContext) { + permissionStateStore.save(BrowserWebExtensionPermissionState(context: context), for: entryID) + } + + func persistPermissionState(for context: WKWebExtensionContext) { + guard let record = loadedRecordsInOrder.first(where: { $0.context === context }) else { return } + persistPermissionState(entryID: record.entryID, context: context) + } + + func persistPermissionStateSoon(for context: WKWebExtensionContext) { + Task { @MainActor [weak self, weak context] in + guard let self, let context else { return } + self.persistPermissionState(for: context) + } + } + + func installPermissionStateObservers(for context: WKWebExtensionContext, entryID: String) { + removePermissionStateObservers(entryID: entryID) + permissionObserverTokensByEntryID[entryID] = permissionStateNotificationNames.map { name in + NotificationCenter.default.addObserver( + forName: name, + object: context, + queue: .main + ) { [weak self, weak context] _ in + guard let self, let context else { return } + MainActor.assumeIsolated { + self.persistPermissionState(entryID: entryID, context: context) + } + } + } + } + + func removePermissionStateObservers(entryID: String) { + guard let tokens = permissionObserverTokensByEntryID.removeValue(forKey: entryID) else { return } + for token in tokens { + NotificationCenter.default.removeObserver(token) + } + } + + func removeAllPermissionStateObservers() { + for entryID in Array(permissionObserverTokensByEntryID.keys) { + removePermissionStateObservers(entryID: entryID) + } + } + + private var permissionStateNotificationNames: [Notification.Name] { + [ + WKWebExtensionContext.permissionsWereGrantedNotification, + WKWebExtensionContext.permissionsWereDeniedNotification, + WKWebExtensionContext.grantedPermissionsWereRemovedNotification, + WKWebExtensionContext.deniedPermissionsWereRemovedNotification, + WKWebExtensionContext.permissionMatchPatternsWereGrantedNotification, + WKWebExtensionContext.permissionMatchPatternsWereDeniedNotification, + WKWebExtensionContext.grantedPermissionMatchPatternsWereRemovedNotification, + WKWebExtensionContext.deniedPermissionMatchPatternsWereRemovedNotification, + ] + } +} diff --git a/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift b/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift index 5eefde64220d..74ef6e10cb0a 100644 --- a/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift +++ b/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift @@ -66,7 +66,7 @@ extension BrowserWebExtensionSupport: WKWebExtensionControllerDelegate { guard let adapter = openBrowserTab( url: configuration.url, shouldActivate: configuration.shouldBeActive, - webViewConfiguration: configuration.url.flatMap { controller.extensionContext(for: $0)?.webViewConfiguration } + webViewConfiguration: nil ) else { completionHandler(nil, openTabsUnsupportedError()) return @@ -173,6 +173,7 @@ extension BrowserWebExtensionSupport: WKWebExtensionControllerDelegate { ) ) completionHandler(allowed ? permissions : [], nil) + persistPermissionStateSoon(for: extensionContext) } func webExtensionController( @@ -195,6 +196,7 @@ extension BrowserWebExtensionSupport: WKWebExtensionControllerDelegate { ) ) completionHandler(allowed ? urls : [], nil) + persistPermissionStateSoon(for: extensionContext) } func webExtensionController( @@ -217,6 +219,7 @@ extension BrowserWebExtensionSupport: WKWebExtensionControllerDelegate { ) ) completionHandler(allowed ? matchPatterns : [], nil) + persistPermissionStateSoon(for: extensionContext) } private func permissionMessage( diff --git a/Sources/Panels/BrowserWebExtensionSupport.swift b/Sources/Panels/BrowserWebExtensionSupport.swift index 24aae240789b..05946fad10a9 100644 --- a/Sources/Panels/BrowserWebExtensionSupport.swift +++ b/Sources/Panels/BrowserWebExtensionSupport.swift @@ -24,6 +24,8 @@ final class BrowserWebExtensionSupport: NSObject, BrowserWebExtensionHosting { @ObservationIgnored let controller: WKWebExtensionController + @ObservationIgnored + let permissionStateStore = BrowserWebExtensionPermissionStateStore() var actionSnapshots: [BrowserWebExtensionActionSnapshot] = [] var loadErrors: [String] = [] @@ -39,6 +41,8 @@ final class BrowserWebExtensionSupport: NSObject, BrowserWebExtensionHosting { @ObservationIgnored var tabAdapters: [UUID: BrowserWebExtensionTabAdapter] = [:] @ObservationIgnored + var permissionObserverTokensByEntryID: [String: [NSObjectProtocol]] = [:] + @ObservationIgnored var orderedPanelIDs: [UUID] = [] @ObservationIgnored private(set) var activePanelID: UUID? @@ -66,6 +70,11 @@ final class BrowserWebExtensionSupport: NSObject, BrowserWebExtensionHosting { controller.delegate = self } + deinit { + settingsObservationTask?.cancel() + removeAllPermissionStateObservers() + } + // MARK: - Configuration attachment /// Attaches the shared extension controller to a browser web view configuration. @@ -73,6 +82,17 @@ final class BrowserWebExtensionSupport: NSObject, BrowserWebExtensionHosting { configuration.webExtensionController = controller } + func webViewConfiguration(forNavigatingTo url: URL) -> BrowserWebExtensionNavigationConfiguration? { + guard let context = controller.extensionContext(for: url), + let webViewConfiguration = context.webViewConfiguration else { + return nil + } + return BrowserWebExtensionNavigationConfiguration( + contextIdentifier: ObjectIdentifier(context), + webViewConfiguration: webViewConfiguration + ) + } + // MARK: - Settings-driven loading /// Starts observing `browser.webExtensions` and keeps loaded extensions in diff --git a/cmux.xcodeproj/project.pbxproj b/cmux.xcodeproj/project.pbxproj index 771c0c065c59..c0f6d3220f62 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -314,9 +314,13 @@ C0DE71B10000000000000001 /* AppDelegate+AgentChatNotifications.swift in Sources B1CFE0060000000000000001 /* BrowserWebExtensionDiscoveryService.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1CFE0060000000000000002 /* BrowserWebExtensionDiscoveryService.swift */; }; B1CFE0080000000000000001 /* BrowserWebExtensionHosting.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1CFE0080000000000000002 /* BrowserWebExtensionHosting.swift */; }; B1CFE00B0000000000000001 /* BrowserWebExtensionLoadedRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1CFE00B0000000000000002 /* BrowserWebExtensionLoadedRecord.swift */; }; + B1CFE00D0000000000000001 /* BrowserWebExtensionNavigationConfiguration.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1CFE00D0000000000000002 /* BrowserWebExtensionNavigationConfiguration.swift */; }; + B1CFE00E0000000000000001 /* BrowserWebExtensionPermissionState.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1CFE00E0000000000000002 /* BrowserWebExtensionPermissionState.swift */; }; + B1CFE00F0000000000000001 /* BrowserWebExtensionPermissionStateStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1CFE00F0000000000000002 /* BrowserWebExtensionPermissionStateStore.swift */; }; B1CFE0050000000000000001 /* BrowserWebExtensionPopoutWindowController.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1CFE0050000000000000002 /* BrowserWebExtensionPopoutWindowController.swift */; }; B1CFE00C0000000000000001 /* BrowserWebExtensionReconciliationPlanner.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1CFE00C0000000000000002 /* BrowserWebExtensionReconciliationPlanner.swift */; }; B1CFE0070000000000000001 /* BrowserWebExtensionSupport+Loading.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1CFE0070000000000000002 /* BrowserWebExtensionSupport+Loading.swift */; }; + B1CFE0100000000000000001 /* BrowserWebExtensionSupport+Permissions.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1CFE0100000000000000002 /* BrowserWebExtensionSupport+Permissions.swift */; }; B1CFE0090000000000000001 /* BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1CFE0090000000000000002 /* BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift */; }; B1CFE0010000000000000001 /* BrowserWebExtensionSupport.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1CFE0010000000000000002 /* BrowserWebExtensionSupport.swift */; }; B1CFE0200000000000000001 /* BrowserWebExtensionSupportTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1CFE0200000000000000002 /* BrowserWebExtensionSupportTests.swift */; }; @@ -2086,9 +2090,13 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = B1CFE0060000000000000002 /* BrowserWebExtensionDiscoveryService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/BrowserWebExtensionDiscoveryService.swift; sourceTree = ""; }; B1CFE0080000000000000002 /* BrowserWebExtensionHosting.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/BrowserWebExtensionHosting.swift; sourceTree = ""; }; B1CFE00B0000000000000002 /* BrowserWebExtensionLoadedRecord.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/BrowserWebExtensionLoadedRecord.swift; sourceTree = ""; }; + B1CFE00D0000000000000002 /* BrowserWebExtensionNavigationConfiguration.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/BrowserWebExtensionNavigationConfiguration.swift; sourceTree = ""; }; + B1CFE00E0000000000000002 /* BrowserWebExtensionPermissionState.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/BrowserWebExtensionPermissionState.swift; sourceTree = ""; }; + B1CFE00F0000000000000002 /* BrowserWebExtensionPermissionStateStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/BrowserWebExtensionPermissionStateStore.swift; sourceTree = ""; }; B1CFE0050000000000000002 /* BrowserWebExtensionPopoutWindowController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/BrowserWebExtensionPopoutWindowController.swift; sourceTree = ""; }; B1CFE00C0000000000000002 /* BrowserWebExtensionReconciliationPlanner.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/BrowserWebExtensionReconciliationPlanner.swift; sourceTree = ""; }; B1CFE0070000000000000002 /* BrowserWebExtensionSupport+Loading.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Panels/BrowserWebExtensionSupport+Loading.swift"; sourceTree = ""; }; + B1CFE0100000000000000002 /* BrowserWebExtensionSupport+Permissions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Panels/BrowserWebExtensionSupport+Permissions.swift"; sourceTree = ""; }; B1CFE0090000000000000002 /* BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift"; sourceTree = ""; }; B1CFE0010000000000000002 /* BrowserWebExtensionSupport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/BrowserWebExtensionSupport.swift; sourceTree = ""; }; B1CFE0200000000000000002 /* BrowserWebExtensionSupportTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BrowserWebExtensionSupportTests.swift; sourceTree = ""; }; @@ -4315,12 +4323,16 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = B1CFE0020000000000000002 /* BrowserWebExtensionTabAdapter.swift */, B1CFE0010000000000000002 /* BrowserWebExtensionSupport.swift */, B1CFE0070000000000000002 /* BrowserWebExtensionSupport+Loading.swift */, + B1CFE0100000000000000002 /* BrowserWebExtensionSupport+Permissions.swift */, B1CFE0090000000000000002 /* BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift */, B1CFE0060000000000000002 /* BrowserWebExtensionDiscoveryService.swift */, B1CFE0050000000000000002 /* BrowserWebExtensionPopoutWindowController.swift */, B1CFE0080000000000000002 /* BrowserWebExtensionHosting.swift */, B1CFE00A0000000000000002 /* BrowserWebExtensionActionSnapshot.swift */, B1CFE00B0000000000000002 /* BrowserWebExtensionLoadedRecord.swift */, + B1CFE00D0000000000000002 /* BrowserWebExtensionNavigationConfiguration.swift */, + B1CFE00E0000000000000002 /* BrowserWebExtensionPermissionState.swift */, + B1CFE00F0000000000000002 /* BrowserWebExtensionPermissionStateStore.swift */, B1CFE00C0000000000000002 /* BrowserWebExtensionReconciliationPlanner.swift */, C67540100000000000000002 /* BrowserNavigationPopupPolicy.swift */, A5001412 /* BrowserPanel.swift */, @@ -5884,9 +5896,13 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = B1CFE0060000000000000001 /* BrowserWebExtensionDiscoveryService.swift in Sources */, B1CFE0080000000000000001 /* BrowserWebExtensionHosting.swift in Sources */, B1CFE00B0000000000000001 /* BrowserWebExtensionLoadedRecord.swift in Sources */, + B1CFE00D0000000000000001 /* BrowserWebExtensionNavigationConfiguration.swift in Sources */, + B1CFE00E0000000000000001 /* BrowserWebExtensionPermissionState.swift in Sources */, + B1CFE00F0000000000000001 /* BrowserWebExtensionPermissionStateStore.swift in Sources */, B1CFE0050000000000000001 /* BrowserWebExtensionPopoutWindowController.swift in Sources */, B1CFE00C0000000000000001 /* BrowserWebExtensionReconciliationPlanner.swift in Sources */, B1CFE0070000000000000001 /* BrowserWebExtensionSupport+Loading.swift in Sources */, + B1CFE0100000000000000001 /* BrowserWebExtensionSupport+Permissions.swift in Sources */, B1CFE0090000000000000001 /* BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift in Sources */, B1CFE0010000000000000001 /* BrowserWebExtensionSupport.swift in Sources */, B1CFE0020000000000000001 /* BrowserWebExtensionTabAdapter.swift in Sources */, diff --git a/cmuxTests/BrowserWebExtensionSupportTests.swift b/cmuxTests/BrowserWebExtensionSupportTests.swift index e1c30ae1c7e7..ce613e19db49 100644 --- a/cmuxTests/BrowserWebExtensionSupportTests.swift +++ b/cmuxTests/BrowserWebExtensionSupportTests.swift @@ -100,6 +100,40 @@ struct BrowserWebExtensionSupportTests { #expect(plan.loadEntries.map(\.path) == [newPath]) } + @Test + @available(macOS 15.4, *) + func permissionStateStorePersistsEntryStatesIndependently() throws { + let suiteName = "cmux-web-extension-permissions-\(UUID().uuidString)" + let defaults = try #require(UserDefaults(suiteName: suiteName)) + defer { defaults.removePersistentDomain(forName: suiteName) } + + let store = BrowserWebExtensionPermissionStateStore(defaults: defaults) + let expiration = Date(timeIntervalSince1970: 1_800_000_000) + let firstState = BrowserWebExtensionPermissionState( + grantedPermissions: ["tabs": expiration], + deniedPermissions: ["cookies": expiration], + grantedPermissionMatchPatterns: ["https://example.com/*": expiration], + deniedPermissionMatchPatterns: ["https://denied.example/*": expiration], + hasRequestedOptionalAccessToAllHosts: true, + hasAccessToPrivateData: false + ) + let secondState = BrowserWebExtensionPermissionState( + grantedPermissions: ["storage": expiration], + deniedPermissions: [:], + grantedPermissionMatchPatterns: [:], + deniedPermissionMatchPatterns: [:], + hasRequestedOptionalAccessToAllHosts: false, + hasAccessToPrivateData: true + ) + + store.save(firstState, for: "com.example.first") + store.save(secondState, for: "com.example.second") + + #expect(store.state(for: "com.example.first") == firstState) + #expect(store.state(for: "com.example.second") == secondState) + #expect(store.state(for: "missing") == nil) + } + @Test func pluginkitParserHandlesVerboseSpaceSeparatedOutput() { let output = """ From 77747707188543a8dc99e54cb7c59cc8fb6f8ed1 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 05:25:34 -0700 Subject: [PATCH 23/51] Guard web extension imports until settings load --- .../Bindings/JSONValueModel.swift | 7 ++++- .../Sections/BrowserWebExtensionsCard.swift | 8 +++-- .../JSONValueModelLifecycleTests.swift | 31 +++++++++++++++++++ 3 files changed, 43 insertions(+), 3 deletions(-) diff --git a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Bindings/JSONValueModel.swift b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Bindings/JSONValueModel.swift index de3704f836f7..eb0d4e5b80c5 100644 --- a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Bindings/JSONValueModel.swift +++ b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Bindings/JSONValueModel.swift @@ -23,6 +23,9 @@ public final class JSONValueModel { /// watcher. public private(set) var current: Value + /// Whether the JSON change stream has yielded at least once. + public private(set) var hasObservedValue = false + /// Error from the most recent set/reset attempt, or `nil`. public private(set) var lastWriteError: Error? @@ -87,7 +90,9 @@ public final class JSONValueModel { /// lifecycle hook such as `.task`, not from their initializer. public func startObserving() { observation.activate(makeStream) { [weak self] value in - self?.current = value + guard let self else { return } + self.current = value + self.hasObservedValue = true } } diff --git a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift index 46381d74b5d9..74ad2cfc459f 100644 --- a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift +++ b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift @@ -44,6 +44,7 @@ struct BrowserWebExtensionsCard: View { /// Discovered Safari extensions not yet added, offered by the Import menu. private var importableExtensions: [SettingsDiscoveredBrowserExtension] { + guard model.hasObservedValue else { return [] } let addedIDs = Set(model.current.map(\.id)) let addedResourcePaths = Set(model.current.map { standardizedResourcePath(for: $0) }) return discovered.filter { candidate in @@ -76,7 +77,7 @@ struct BrowserWebExtensionsCard: View { addUnpackedExtension() } .controlSize(.small) - .disabled(!supported) + .disabled(!supported || !model.hasObservedValue) .accessibilityIdentifier("BrowserWebExtensionsAddUnpackedButton") } } @@ -102,7 +103,7 @@ struct BrowserWebExtensionsCard: View { } .controlSize(.small) .fixedSize() - .disabled(!supported) + .disabled(!supported || !model.hasObservedValue) .accessibilityIdentifier("BrowserWebExtensionsImportMenu") } @@ -148,6 +149,7 @@ struct BrowserWebExtensionsCard: View { } private func setEnabled(_ enabled: Bool, id: String) { + guard model.hasObservedValue else { return } var entries = model.current guard let index = entries.firstIndex(where: { $0.id == id }) else { return } let targetPath = standardizedPath(entries[index].path) @@ -161,6 +163,7 @@ struct BrowserWebExtensionsCard: View { } private func add(_ entry: BrowserWebExtensionEntry) { + guard model.hasObservedValue else { return } var entries = model.current guard !entries.contains(where: { $0.id == entry.id }) else { presentDuplicateExtensionAlert(for: entry) @@ -176,6 +179,7 @@ struct BrowserWebExtensionsCard: View { } private func remove(id: String) { + guard model.hasObservedValue else { return } model.set(model.current.filter { $0.id != id }) } diff --git a/Packages/macOS/CmuxSettingsUI/Tests/CmuxSettingsUITests/JSONValueModelLifecycleTests.swift b/Packages/macOS/CmuxSettingsUI/Tests/CmuxSettingsUITests/JSONValueModelLifecycleTests.swift index 77f024e15633..223b7dfa47be 100644 --- a/Packages/macOS/CmuxSettingsUI/Tests/CmuxSettingsUITests/JSONValueModelLifecycleTests.swift +++ b/Packages/macOS/CmuxSettingsUI/Tests/CmuxSettingsUITests/JSONValueModelLifecycleTests.swift @@ -81,4 +81,35 @@ import Testing #expect(streamCreations == 0) } + + @Test func hasObservedValueTracksFirstStreamValue() async { + let tempDir = FileManager.default.temporaryDirectory + .appendingPathComponent("json-value-model-observed-flag-\(UUID().uuidString)", isDirectory: true) + defer { try? FileManager.default.removeItem(at: tempDir) } + + let store = JSONConfigStore(fileURL: tempDir.appendingPathComponent("cmux.json")) + let key = JSONKey(id: "automation.socketPassword", defaultValue: "") + let errorLog = SettingsErrorLog() + let (stream, continuation) = AsyncStream.makeStream() + let model = JSONValueModel( + store: store, + key: key, + errorLog: errorLog, + makeStream: { stream } + ) + + #expect(model.hasObservedValue == false) + model.startObserving() + #expect(model.hasObservedValue == false) + + continuation.yield("observed") + var settleSpins = 0 + while !model.hasObservedValue, settleSpins < 100_000 { + await Task.yield() + settleSpins += 1 + } + + #expect(model.current == "observed") + #expect(model.hasObservedValue) + } } From c134130bc0fcce865768e6d08a28ea7ad0e72951 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 05:34:46 -0700 Subject: [PATCH 24/51] Fix web extension review findings --- Sources/Panels/BrowserPanel.swift | 8 ++--- .../BrowserWebExtensionSupport+Loading.swift | 30 ++++++++++++++----- .../Panels/BrowserWebExtensionSupport.swift | 4 ++- .../BrowserWebExtensionToolbarButtons.swift | 2 +- .../BrowserPrewarmedWebViewPoolTests.swift | 4 +++ 5 files changed, 34 insertions(+), 14 deletions(-) diff --git a/Sources/Panels/BrowserPanel.swift b/Sources/Panels/BrowserPanel.swift index 2239cfbe3c10..19257960c710 100644 --- a/Sources/Panels/BrowserPanel.swift +++ b/Sources/Panels/BrowserPanel.swift @@ -3332,7 +3332,7 @@ final class BrowserPanel: Panel, ObservableObject { replacement.pageZoom = desiredZoom webViewInstanceID = UUID() hasCommittedDocumentSinceWebViewReplacement = false; userStoppedLoadSinceWebViewReplacement = false - webView = replacement + webExtensionPageContextIdentifier = nil; webView = replacement hiddenWebViewDiscardManager.markDiscarded(reason: reason, now: now) currentURL = restoreURL shouldRenderWebView = false @@ -4653,7 +4653,7 @@ final class BrowserPanel: Panel, ObservableObject { webViewInstanceID = UUID() hasCommittedDocumentSinceWebViewReplacement = false; userStoppedLoadSinceWebViewReplacement = false resetWebViewLifecycleMetadata(resetVisibility: false) - webView = replacement + webExtensionPageContextIdentifier = nil; webView = replacement currentURL = restoreURL shouldRenderWebView = wasRenderable refreshWebViewLifecycleState() @@ -5163,7 +5163,7 @@ final class BrowserPanel: Panel, ObservableObject { webViewInstanceID = UUID() hasCommittedDocumentSinceWebViewReplacement = false; userStoppedLoadSinceWebViewReplacement = false resetWebViewLifecycleMetadata(resetVisibility: false) - webView = replacement + webExtensionPageContextIdentifier = nil; webView = replacement shouldRenderWebView = wasRenderable refreshWebViewLifecycleState() @@ -6279,7 +6279,7 @@ extension BrowserPanel { ) webViewInstanceID = UUID() hasCommittedDocumentSinceWebViewReplacement = false; userStoppedLoadSinceWebViewReplacement = false - webView = replacement + webExtensionPageContextIdentifier = nil; webView = replacement shouldRenderWebView = false refreshWebViewLifecycleState() bindWebView(replacement) diff --git a/Sources/Panels/BrowserWebExtensionSupport+Loading.swift b/Sources/Panels/BrowserWebExtensionSupport+Loading.swift index 49d5e8fe18a5..2684b8504f80 100644 --- a/Sources/Panels/BrowserWebExtensionSupport+Loading.swift +++ b/Sources/Panels/BrowserWebExtensionSupport+Loading.swift @@ -35,23 +35,37 @@ extension BrowserWebExtensionSupport { loadedByEntryID[actionID]?.context } + func actionSnapshots(for panelID: UUID) -> [BrowserWebExtensionActionSnapshot] { + _ = actionSnapshotRevision + let tabAdapter = tabAdapters[panelID] + return actionSnapshotIDs.compactMap { entryID in + guard let record = loadedByEntryID[entryID] else { return nil } + return actionSnapshot(for: record, tabAdapter: tabAdapter) + } + } + func rebuildActionSnapshots() { - actionSnapshots = loadedRecordsInOrder.map { actionSnapshot(for: $0) } + actionSnapshotIDs = loadedRecordsInOrder.map(\.entryID) + refreshActionSnapshots() } func refreshActionSnapshot(for context: WKWebExtensionContext) { - guard let record = loadedRecordsInOrder.first(where: { $0.context === context }) else { return } - var snapshots = actionSnapshots - guard let index = snapshots.firstIndex(where: { $0.id == record.entryID }) else { + guard actionSnapshotIDs.contains(where: { loadedByEntryID[$0]?.context === context }) else { rebuildActionSnapshots() return } - snapshots[index] = actionSnapshot(for: record) - actionSnapshots = snapshots + refreshActionSnapshots() + } + + func refreshActionSnapshots() { + actionSnapshotRevision &+= 1 } - private func actionSnapshot(for record: BrowserWebExtensionLoadedRecord) -> BrowserWebExtensionActionSnapshot { - let action = record.context.action(for: activeTabAdapter) + private func actionSnapshot( + for record: BrowserWebExtensionLoadedRecord, + tabAdapter: BrowserWebExtensionTabAdapter? + ) -> BrowserWebExtensionActionSnapshot { + let action = record.context.action(for: tabAdapter) return BrowserWebExtensionActionSnapshot( id: record.entryID, displayName: action?.label ?? record.context.webExtension.displayName ?? String( diff --git a/Sources/Panels/BrowserWebExtensionSupport.swift b/Sources/Panels/BrowserWebExtensionSupport.swift index 05946fad10a9..9fae8dfa7008 100644 --- a/Sources/Panels/BrowserWebExtensionSupport.swift +++ b/Sources/Panels/BrowserWebExtensionSupport.swift @@ -27,7 +27,8 @@ final class BrowserWebExtensionSupport: NSObject, BrowserWebExtensionHosting { @ObservationIgnored let permissionStateStore = BrowserWebExtensionPermissionStateStore() - var actionSnapshots: [BrowserWebExtensionActionSnapshot] = [] + var actionSnapshotIDs: [String] = [] + var actionSnapshotRevision = 0 var loadErrors: [String] = [] @ObservationIgnored @@ -153,6 +154,7 @@ final class BrowserWebExtensionSupport: NSObject, BrowserWebExtensionHosting { func noteTabMetadataChanged(panelID: UUID) { guard let adapter = tabAdapters[panelID] else { return } controller.didChangeTabProperties([.title, .URL, .loading, .muted], for: adapter) + refreshActionSnapshots() } func tabAdapter(for panelID: UUID) -> BrowserWebExtensionTabAdapter? { diff --git a/Sources/Panels/BrowserWebExtensionToolbarButtons.swift b/Sources/Panels/BrowserWebExtensionToolbarButtons.swift index fd065e3bec46..b70992335d7c 100644 --- a/Sources/Panels/BrowserWebExtensionToolbarButtons.swift +++ b/Sources/Panels/BrowserWebExtensionToolbarButtons.swift @@ -12,7 +12,7 @@ struct BrowserWebExtensionToolbarButtons: View { let hitSize: CGFloat var body: some View { - ForEach(support.actionSnapshots) { snapshot in + ForEach(support.actionSnapshots(for: panel.id)) { snapshot in BrowserWebExtensionActionButton( snapshot: snapshot, panel: panel, diff --git a/cmuxTests/BrowserPrewarmedWebViewPoolTests.swift b/cmuxTests/BrowserPrewarmedWebViewPoolTests.swift index 83971ea2de0a..05945f12b909 100644 --- a/cmuxTests/BrowserPrewarmedWebViewPoolTests.swift +++ b/cmuxTests/BrowserPrewarmedWebViewPoolTests.swift @@ -52,6 +52,10 @@ private final class PrewarmTestWebExtensionHost: BrowserWebExtensionHosting { attachedConfigurationCount += 1 } + func webViewConfiguration(forNavigatingTo url: URL) -> BrowserWebExtensionNavigationConfiguration? { + nil + } + func register(panel: BrowserPanel) {} func unregister(panelID: UUID) {} From c515a142a1845e2c79e93b735b2893a116bc7840 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 05:49:41 -0700 Subject: [PATCH 25/51] Harden web extension loading gates --- .../Values/BrowserWebExtensionEntry.swift | 46 +++++++++++++++++ .../Sections/BrowserWebExtensionsCard.swift | 17 +++---- Resources/Localizable.xcstrings | 6 +++ ...serWebExtensionReconciliationPlanner.swift | 20 ++++++-- .../BrowserWebExtensionSupport+Loading.swift | 11 +++- ...ort+WKWebExtensionControllerDelegate.swift | 8 ++- .../Panels/BrowserWebExtensionSupport.swift | 41 ++++++++++++++- .../BrowserWebExtensionSupportTests.swift | 51 +++++++++++++++++++ 8 files changed, 181 insertions(+), 19 deletions(-) diff --git a/Packages/macOS/CmuxSettings/Sources/CmuxSettings/Values/BrowserWebExtensionEntry.swift b/Packages/macOS/CmuxSettings/Sources/CmuxSettings/Values/BrowserWebExtensionEntry.swift index f0af90ff0ec0..f1580d1205a1 100644 --- a/Packages/macOS/CmuxSettings/Sources/CmuxSettings/Values/BrowserWebExtensionEntry.swift +++ b/Packages/macOS/CmuxSettings/Sources/CmuxSettings/Values/BrowserWebExtensionEntry.swift @@ -53,6 +53,52 @@ public struct BrowserWebExtensionEntry: Codable, Sendable, Equatable, Hashable, self.enabled = enabled self.displayName = displayName } + + /// Absolute, standardized path used to identify the effective extension + /// resource root for duplicate detection and reconciliation. + public var standardizedResourceRootPath: String { + Self.standardizedResourceRootPath(for: kind, path: path) + } + + /// Returns a standardized filesystem path. + /// + /// - Parameter path: The path to normalize. + /// - Returns: The standardized file URL path. + public static func standardizedPath(_ path: String) -> String { + URL(fileURLWithPath: path).standardizedFileURL.path + } + + /// Returns the effective resource root for a configured extension path. + /// + /// Safari app extensions load from `Contents/Resources` inside the `.appex` + /// bundle, so the bundle path and its resource directory compare equal. + /// + /// - Parameters: + /// - kind: The configured extension kind. + /// - path: The `.appex` bundle path or unpacked extension directory. + /// - Returns: The standardized effective resource-root path. + public static func standardizedResourceRootPath(for kind: Kind, path: String) -> String { + switch kind { + case .safariAppExtension: + return standardizedSafariAppExtensionResourceRootPath(path) + case .unpackedDirectory: + return standardizedPath(path) + } + } + + /// Returns the resource root WebKit uses for a Safari app extension. + /// + /// - Parameter path: The `.appex` bundle path. + /// - Returns: `Contents/Resources` inside the bundle when `path` points at + /// an `.appex`, otherwise the standardized original path. + public static func standardizedSafariAppExtensionResourceRootPath(_ path: String) -> String { + let url = URL(fileURLWithPath: path).standardizedFileURL + guard url.pathExtension == "appex" else { return url.path } + return url + .appendingPathComponent("Contents/Resources", isDirectory: true) + .standardizedFileURL + .path + } } // MARK: - SettingCodable diff --git a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift index 74ad2cfc459f..75cafadaf1e4 100644 --- a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift +++ b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift @@ -152,10 +152,10 @@ struct BrowserWebExtensionsCard: View { guard model.hasObservedValue else { return } var entries = model.current guard let index = entries.firstIndex(where: { $0.id == id }) else { return } - let targetPath = standardizedPath(entries[index].path) + let targetPath = standardizedResourcePath(for: entries[index]) entries[index].enabled = enabled for candidateIndex in entries.indices where candidateIndex != index { - if standardizedPath(entries[candidateIndex].path) == targetPath { + if standardizedResourcePath(for: entries[candidateIndex]) == targetPath { entries[candidateIndex].enabled = false } } @@ -258,7 +258,7 @@ struct BrowserWebExtensionsCard: View { var seenEnabledPaths = Set() var result: [String: Bool] = [:] for entry in model.current { - let path = standardizedPath(entry.path) + let path = standardizedResourcePath(for: entry) let isFirstEnabledEntryForPath = entry.enabled && seenEnabledPaths.insert(path).inserted result[entry.id] = isFirstEnabledEntryForPath } @@ -266,24 +266,19 @@ struct BrowserWebExtensionsCard: View { } private func standardizedPath(_ path: String) -> String { - URL(fileURLWithPath: path).standardizedFileURL.path + BrowserWebExtensionEntry.standardizedPath(path) } private func standardizedResourcePath(for entry: BrowserWebExtensionEntry) -> String { switch entry.kind { case .safariAppExtension: - return standardizedSafariAppExtensionResourcePath(entry.path) + return BrowserWebExtensionEntry.standardizedSafariAppExtensionResourceRootPath(entry.path) case .unpackedDirectory: return standardizedPath(entry.path) } } private func standardizedSafariAppExtensionResourcePath(_ path: String) -> String { - let url = URL(fileURLWithPath: path) - guard url.pathExtension == "appex" else { return standardizedPath(path) } - return url - .appendingPathComponent("Contents/Resources", isDirectory: true) - .standardizedFileURL - .path + BrowserWebExtensionEntry.standardizedSafariAppExtensionResourceRootPath(path) } } diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index 68473f5809f0..2dc94b499295 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -46602,6 +46602,12 @@ "value": "browser.webExtensions extensions addons plugins bitwarden 1password adguard password manager safari web extension unpacked load" } }, + "km": { + "stringUnit": { + "state": "translated", + "value": "browser.webExtensions extensions addons plugins bitwarden 1password adguard password manager safari web extension unpacked load" + } + }, "ko": { "stringUnit": { "state": "translated", diff --git a/Sources/Panels/BrowserWebExtensionReconciliationPlanner.swift b/Sources/Panels/BrowserWebExtensionReconciliationPlanner.swift index 03ca340c58f7..133e3ce86e16 100644 --- a/Sources/Panels/BrowserWebExtensionReconciliationPlanner.swift +++ b/Sources/Panels/BrowserWebExtensionReconciliationPlanner.swift @@ -43,27 +43,39 @@ struct BrowserWebExtensionReconciliationPlanner { } static func standardizedPath(_ path: String) -> String { - URL(fileURLWithPath: path).standardizedFileURL.path + BrowserWebExtensionEntry.standardizedPath(path) + } + + static func standardizedResourceRootPath(for entry: BrowserWebExtensionEntry) -> String { + entry.standardizedResourceRootPath + } + + static func standardizedResourceRootPath(forEnvironmentPath path: String) -> String { + let standardizedPath = BrowserWebExtensionEntry.standardizedPath(path) + let kind: BrowserWebExtensionEntry.Kind = URL(fileURLWithPath: standardizedPath).pathExtension == "appex" + ? .safariAppExtension + : .unpackedDirectory + return BrowserWebExtensionEntry.standardizedResourceRootPath(for: kind, path: path) } private func desired( settingsEntries: [BrowserWebExtensionEntry], environmentPaths: [String] ) -> [BrowserWebExtensionEntry] { - let settingsPaths = Set(settingsEntries.map { Self.standardizedPath($0.path) }) + let settingsPaths = Set(settingsEntries.map { Self.standardizedResourceRootPath(for: $0) }) var seenDesiredPaths = Set() var desired: [BrowserWebExtensionEntry] = [] var desiredIDs = Set() for entry in settingsEntries where entry.enabled { - let standardizedPath = Self.standardizedPath(entry.path) + let standardizedPath = Self.standardizedResourceRootPath(for: entry) guard seenDesiredPaths.insert(standardizedPath).inserted else { continue } guard desiredIDs.insert(entry.id).inserted else { continue } desired.append(entry) } for path in environmentPaths { - let standardizedPath = Self.standardizedPath(path) + let standardizedPath = Self.standardizedResourceRootPath(forEnvironmentPath: path) guard !settingsPaths.contains(standardizedPath) else { continue } guard seenDesiredPaths.insert(standardizedPath).inserted else { continue } guard desiredIDs.insert(path).inserted else { continue } diff --git a/Sources/Panels/BrowserWebExtensionSupport+Loading.swift b/Sources/Panels/BrowserWebExtensionSupport+Loading.swift index 2684b8504f80..4768bfd5379d 100644 --- a/Sources/Panels/BrowserWebExtensionSupport+Loading.swift +++ b/Sources/Panels/BrowserWebExtensionSupport+Loading.swift @@ -108,11 +108,20 @@ extension BrowserWebExtensionSupport { #endif } + func unloadAllWebExtensions() { + for entryID in Array(loadedEntryIDsInOrder) { + unload(entryID: entryID) + } + loadErrorsByEntryID.removeAll() + refreshLoadErrors() + rebuildActionSnapshots() + } + private func load(entry: BrowserWebExtensionEntry) async { do { let webExtension = try await makeWebExtension(for: entry) let context = try load(webExtension, entryID: entry.id) - let standardizedPath = BrowserWebExtensionReconciliationPlanner.standardizedPath(entry.path) + let standardizedPath = BrowserWebExtensionReconciliationPlanner.standardizedResourceRootPath(for: entry) loadedByEntryID[entry.id] = BrowserWebExtensionLoadedRecord( entryID: entry.id, standardizedPath: standardizedPath, diff --git a/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift b/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift index 74ef6e10cb0a..957fb0e8901c 100644 --- a/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift +++ b/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift @@ -7,7 +7,7 @@ extension BrowserWebExtensionSupport: WKWebExtensionControllerDelegate { _ controller: WKWebExtensionController, openWindowsFor extensionContext: WKWebExtensionContext ) -> [any WKWebExtensionWindow] { - let openWindows: [any WKWebExtensionWindow] = [windowAdapter] + popouts + let openWindows: [any WKWebExtensionWindow] = [windowAdapter] + popouts(for: extensionContext) guard let focusedWindow = webExtensionController(controller, focusedWindowFor: extensionContext) else { return openWindows } @@ -21,7 +21,11 @@ extension BrowserWebExtensionSupport: WKWebExtensionControllerDelegate { _ controller: WKWebExtensionController, focusedWindowFor extensionContext: WKWebExtensionContext ) -> (any WKWebExtensionWindow)? { - popouts.first(where: \.isKeyWindow) ?? windowAdapter + popouts(for: extensionContext).first(where: \.isKeyWindow) ?? windowAdapter + } + + private func popouts(for extensionContext: WKWebExtensionContext) -> [BrowserWebExtensionPopoutWindowController] { + popouts.filter { $0.extensionContext === extensionContext } } func webExtensionController( diff --git a/Sources/Panels/BrowserWebExtensionSupport.swift b/Sources/Panels/BrowserWebExtensionSupport.swift index 9fae8dfa7008..1ceea9f6131c 100644 --- a/Sources/Panels/BrowserWebExtensionSupport.swift +++ b/Sources/Panels/BrowserWebExtensionSupport.swift @@ -34,6 +34,8 @@ final class BrowserWebExtensionSupport: NSObject, BrowserWebExtensionHosting { @ObservationIgnored var settingsObservationTask: Task? @ObservationIgnored + var browserAvailabilityObserverToken: NSObjectProtocol? + @ObservationIgnored var loadedByEntryID: [String: BrowserWebExtensionLoadedRecord] = [:] @ObservationIgnored var loadedEntryIDsInOrder: [String] = [] @@ -73,6 +75,9 @@ final class BrowserWebExtensionSupport: NSObject, BrowserWebExtensionHosting { deinit { settingsObservationTask?.cancel() + if let browserAvailabilityObserverToken { + NotificationCenter.default.removeObserver(browserAvailabilityObserverToken) + } removeAllPermissionStateObservers() } @@ -101,8 +106,36 @@ final class BrowserWebExtensionSupport: NSObject, BrowserWebExtensionHosting { /// Called once from app startup so extensions begin loading before the /// first browser page navigates. func configure(jsonStore: JSONConfigStore, catalog: SettingCatalog) { - guard settingsObservationTask == nil else { return } + guard browserAvailabilityObserverToken == nil else { return } let key = catalog.browser.webExtensions + browserAvailabilityObserverToken = NotificationCenter.default.addObserver( + forName: BrowserAvailabilitySettings.didChangeNotification, + object: nil, + queue: .main + ) { [weak self, jsonStore] _ in + Task { @MainActor in + self?.reconcileBrowserAvailability(jsonStore: jsonStore, key: key) + } + } + reconcileBrowserAvailability(jsonStore: jsonStore, key: key) + } + + private func reconcileBrowserAvailability( + jsonStore: JSONConfigStore, + key: JSONKey<[BrowserWebExtensionEntry]> + ) { + if BrowserAvailabilitySettings.isEnabled() { + startSettingsObservation(jsonStore: jsonStore, key: key) + } else { + stopSettingsObservationAndUnload() + } + } + + private func startSettingsObservation( + jsonStore: JSONConfigStore, + key: JSONKey<[BrowserWebExtensionEntry]> + ) { + guard settingsObservationTask == nil else { return } settingsObservationTask = Task { @MainActor [weak self] in for await entries in jsonStore.values(for: key) { guard let self else { return } @@ -111,6 +144,12 @@ final class BrowserWebExtensionSupport: NSObject, BrowserWebExtensionHosting { } } + private func stopSettingsObservationAndUnload() { + settingsObservationTask?.cancel() + settingsObservationTask = nil + unloadAllWebExtensions() + } + static func environmentExtensionPaths() -> [String] { guard let env = ProcessInfo.processInfo.environment["CMUX_BROWSER_EXTENSIONS"] else { return [] } return env.split(separator: ":").map(String.init).filter { !$0.isEmpty } diff --git a/cmuxTests/BrowserWebExtensionSupportTests.swift b/cmuxTests/BrowserWebExtensionSupportTests.swift index ce613e19db49..0dd415e0bfbd 100644 --- a/cmuxTests/BrowserWebExtensionSupportTests.swift +++ b/cmuxTests/BrowserWebExtensionSupportTests.swift @@ -32,6 +32,29 @@ struct BrowserWebExtensionSupportTests { #expect(plan.unloadEntryIDs.isEmpty) } + @Test + func reconciliationSkipsEnvResourceRootWhenSettingsEntryIsDisabled() { + let planner = BrowserWebExtensionReconciliationPlanner() + let appexPath = "/Applications/Bitwarden.app/Contents/PlugIns/safari.appex" + let resourcePath = "\(appexPath)/Contents/Resources" + let plan = planner.plan( + settingsEntries: [ + BrowserWebExtensionEntry( + id: "com.bitwarden.desktop.safari", + kind: .safariAppExtension, + path: appexPath, + enabled: false + ), + ], + environmentPaths: [resourcePath], + loadedEntries: [] + ) + + #expect(plan.desiredEntries.isEmpty) + #expect(plan.loadEntries.isEmpty) + #expect(plan.unloadEntryIDs.isEmpty) + } + @Test func reconciliationDoesNotLoadSamePathTwice() { let planner = BrowserWebExtensionReconciliationPlanner() @@ -53,6 +76,34 @@ struct BrowserWebExtensionSupportTests { #expect(plan.loadEntries.map(\.id) == ["com.bitwarden.desktop.safari"]) } + @Test + func reconciliationDoesNotLoadBundleAndResourceRootTwice() { + let planner = BrowserWebExtensionReconciliationPlanner() + let appexPath = "/Applications/Bitwarden.app/Contents/PlugIns/safari.appex" + let resourcePath = "\(appexPath)/Contents/Resources" + let plan = planner.plan( + settingsEntries: [ + BrowserWebExtensionEntry( + id: "com.bitwarden.desktop.safari", + kind: .safariAppExtension, + path: appexPath, + enabled: true + ), + BrowserWebExtensionEntry( + id: resourcePath, + kind: .unpackedDirectory, + path: resourcePath, + enabled: true + ), + ], + environmentPaths: [], + loadedEntries: [] + ) + + #expect(plan.desiredEntries.map(\.id) == ["com.bitwarden.desktop.safari"]) + #expect(plan.loadEntries.map(\.id) == ["com.bitwarden.desktop.safari"]) + } + @Test func reconciliationDeduplicatesRepeatedEnvironmentPaths() { let planner = BrowserWebExtensionReconciliationPlanner() From 622e5d1b571dd9a5d906d8cd5272e0ea50082fab Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 06:02:45 -0700 Subject: [PATCH 26/51] Avoid redundant Safari extension reloads --- ...serWebExtensionReconciliationPlanner.swift | 13 +++++---- .../BrowserWebExtensionSupportTests.swift | 27 +++++++++++++++++++ 2 files changed, 35 insertions(+), 5 deletions(-) diff --git a/Sources/Panels/BrowserWebExtensionReconciliationPlanner.swift b/Sources/Panels/BrowserWebExtensionReconciliationPlanner.swift index 133e3ce86e16..8328b14f561b 100644 --- a/Sources/Panels/BrowserWebExtensionReconciliationPlanner.swift +++ b/Sources/Panels/BrowserWebExtensionReconciliationPlanner.swift @@ -25,14 +25,14 @@ struct BrowserWebExtensionReconciliationPlanner { let unloadEntryIDs = loadedEntries .filter { loaded in guard let desired = desiredByID[loaded.id] else { return true } - return Self.standardizedPath(desired.path) != loaded.standardizedPath + return Self.standardizedResourceRootPath(for: desired) != loaded.standardizedPath } .map(\.id) .sorted() let loadEntries = desiredEntries.filter { entry in guard let loaded = loadedByID[entry.id] else { return true } - return loaded.standardizedPath != Self.standardizedPath(entry.path) + return loaded.standardizedPath != Self.standardizedResourceRootPath(for: entry) } return Plan( @@ -51,11 +51,14 @@ struct BrowserWebExtensionReconciliationPlanner { } static func standardizedResourceRootPath(forEnvironmentPath path: String) -> String { + BrowserWebExtensionEntry.standardizedResourceRootPath(for: kind(forEnvironmentPath: path), path: path) + } + + private static func kind(forEnvironmentPath path: String) -> BrowserWebExtensionEntry.Kind { let standardizedPath = BrowserWebExtensionEntry.standardizedPath(path) - let kind: BrowserWebExtensionEntry.Kind = URL(fileURLWithPath: standardizedPath).pathExtension == "appex" + return URL(fileURLWithPath: standardizedPath).pathExtension == "appex" ? .safariAppExtension : .unpackedDirectory - return BrowserWebExtensionEntry.standardizedResourceRootPath(for: kind, path: path) } private func desired( @@ -81,7 +84,7 @@ struct BrowserWebExtensionReconciliationPlanner { guard desiredIDs.insert(path).inserted else { continue } desired.append(BrowserWebExtensionEntry( id: path, - kind: path.hasSuffix(".appex") ? .safariAppExtension : .unpackedDirectory, + kind: Self.kind(forEnvironmentPath: path), path: path, enabled: true )) diff --git a/cmuxTests/BrowserWebExtensionSupportTests.swift b/cmuxTests/BrowserWebExtensionSupportTests.swift index 0dd415e0bfbd..c47d76a74b9f 100644 --- a/cmuxTests/BrowserWebExtensionSupportTests.swift +++ b/cmuxTests/BrowserWebExtensionSupportTests.swift @@ -104,6 +104,33 @@ struct BrowserWebExtensionSupportTests { #expect(plan.loadEntries.map(\.id) == ["com.bitwarden.desktop.safari"]) } + @Test + func reconciliationKeepsLoadedSafariExtensionWhenResourceRootMatches() { + let planner = BrowserWebExtensionReconciliationPlanner() + let appexPath = "/Applications/Bitwarden.app/Contents/PlugIns/safari.appex" + let resourcePath = BrowserWebExtensionEntry.standardizedSafariAppExtensionResourceRootPath(appexPath) + let plan = planner.plan( + settingsEntries: [ + BrowserWebExtensionEntry( + id: "com.bitwarden.desktop.safari", + kind: .safariAppExtension, + path: appexPath, + enabled: true + ), + ], + environmentPaths: [], + loadedEntries: [ + BrowserWebExtensionReconciliationPlanner.LoadedEntry( + id: "com.bitwarden.desktop.safari", + standardizedPath: resourcePath + ), + ] + ) + + #expect(plan.unloadEntryIDs.isEmpty) + #expect(plan.loadEntries.isEmpty) + } + @Test func reconciliationDeduplicatesRepeatedEnvironmentPaths() { let planner = BrowserWebExtensionReconciliationPlanner() From 8ac7905a649226e584265f89b38f99d953d7963d Mon Sep 17 00:00:00 2001 From: Kylo Jorgensen Date: Thu, 9 Jul 2026 07:12:29 -0600 Subject: [PATCH 27/51] fix(browser): repair three compile errors on the extension branch MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - sendEvent's web-extension command routing runs in the swizzled NSApplication method, where AppDelegate's shortcutEventBrowserPanel helper is out of scope — call through AppDelegate.shared. - BrowserWebExtensionSupport.deinit called the @MainActor permission- observer removal helper from a nonisolated context; block-based NotificationCenter tokens auto-unregister on dealloc, so drop the call. - permissionMessage's key parameter must be StaticString to match the String(localized:defaultValue:) overload. Verified: cmux and cmux-unit schemes both build. Co-Authored-By: Claude Fable 5 --- Sources/AppDelegate.swift | 2 +- ...bExtensionSupport+WKWebExtensionControllerDelegate.swift | 2 +- Sources/Panels/BrowserWebExtensionSupport.swift | 6 +++++- 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/Sources/AppDelegate.swift b/Sources/AppDelegate.swift index 99011a405cd8..3a7515d5b818 100644 --- a/Sources/AppDelegate.swift +++ b/Sources/AppDelegate.swift @@ -16538,7 +16538,7 @@ private extension NSApplication { // web-extension commands like Bitwarden autofill while a browser web // view has focus; otherwise the suppression below would eat it. if #available(macOS 15.4, *), cmuxRespondersContainBrowserWebView(responder), - shortcutEventBrowserPanel(event)?.performWebExtensionCommand(for: event) == true { + AppDelegate.shared?.shortcutEventBrowserPanel(event)?.performWebExtensionCommand(for: event) == true { #if DEBUG cmuxDebugLog("app.sendEvent routed web-extension command before stale cmux menu shortcut") #endif diff --git a/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift b/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift index 957fb0e8901c..c066d60b1ba1 100644 --- a/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift +++ b/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift @@ -229,7 +229,7 @@ extension BrowserWebExtensionSupport: WKWebExtensionControllerDelegate { private func permissionMessage( extensionContext: WKWebExtensionContext, details: String, - key: String.LocalizationValue, + key: StaticString, defaultValue: String.LocalizationValue ) -> String { let extensionName = extensionContext.webExtension.displayName ?? String( diff --git a/Sources/Panels/BrowserWebExtensionSupport.swift b/Sources/Panels/BrowserWebExtensionSupport.swift index 1ceea9f6131c..8cc0ea55acfb 100644 --- a/Sources/Panels/BrowserWebExtensionSupport.swift +++ b/Sources/Panels/BrowserWebExtensionSupport.swift @@ -78,7 +78,11 @@ final class BrowserWebExtensionSupport: NSObject, BrowserWebExtensionHosting { if let browserAvailabilityObserverToken { NotificationCenter.default.removeObserver(browserAvailabilityObserverToken) } - removeAllPermissionStateObservers() + // Permission-state observer tokens need no explicit removal here: the + // block-based NotificationCenter tokens auto-unregister when they + // deallocate, which happens as the dictionaries holding them release + // with self. (Calling the @MainActor removal helper from nonisolated + // deinit does not compile.) } // MARK: - Configuration attachment From cb2171e8e34c685615caa6ad8da8f1fdaad44c18 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 06:18:55 -0700 Subject: [PATCH 28/51] Route web extension tabs from dock panels --- Sources/DockSplitStore.swift | 10 +-- ...ort+WKWebExtensionControllerDelegate.swift | 87 ++++++++++++++++--- .../BrowserWebExtensionTabAdapter.swift | 7 +- Sources/Workspace+DockBrowserLookup.swift | 7 +- 4 files changed, 88 insertions(+), 23 deletions(-) diff --git a/Sources/DockSplitStore.swift b/Sources/DockSplitStore.swift index 75d96db08cce..9269c6501975 100644 --- a/Sources/DockSplitStore.swift +++ b/Sources/DockSplitStore.swift @@ -6,7 +6,7 @@ import CmuxCore import CmuxTerminal import Observation import SwiftUI - +import WebKit @MainActor @Observable final class DockSplitStore: BonsplitDelegate { @@ -261,7 +261,7 @@ final class DockSplitStore: BonsplitDelegate { tmuxStartCommand: String? = nil, focus: Bool = true, preferredProfileID: UUID? = nil, - bypassInsecureHTTPHostOnce: String? = nil + bypassInsecureHTTPHostOnce: String? = nil, webViewConfiguration: WKWebViewConfiguration? = nil ) -> UUID? { ensureLoaded() guard let panel = makePanel( @@ -273,7 +273,7 @@ final class DockSplitStore: BonsplitDelegate { workingDirectory: workingDirectory ?? currentBaseDirectory(), tmuxStartCommand: tmuxStartCommand, preferredProfileID: preferredProfileID, - bypassInsecureHTTPHostOnce: bypassInsecureHTTPHostOnce + bypassInsecureHTTPHostOnce: bypassInsecureHTTPHostOnce, webViewConfiguration: webViewConfiguration ) else { return nil } let previousFocus = focus ? nil : focusedDockPaneSelection() guard let tabId = attachPanelAsTab(panel, kind: kind, title: panel.displayTitle, inPane: paneId, tracksTerminalTitle: true) else { @@ -444,7 +444,7 @@ final class DockSplitStore: BonsplitDelegate { workingDirectory: String, tmuxStartCommand: String? = nil, preferredProfileID: UUID? = nil, - bypassInsecureHTTPHostOnce: String? = nil + bypassInsecureHTTPHostOnce: String? = nil, webViewConfiguration: WKWebViewConfiguration? = nil ) -> (any Panel)? { switch kind { case .terminal: @@ -466,7 +466,7 @@ final class DockSplitStore: BonsplitDelegate { url: url, initialRequest: initialRequest, preferredProfileID: preferredProfileID, - bypassInsecureHTTPHostOnce: bypassInsecureHTTPHostOnce + bypassInsecureHTTPHostOnce: bypassInsecureHTTPHostOnce, webViewConfiguration: webViewConfiguration ) } } diff --git a/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift b/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift index c066d60b1ba1..f4f259d66c32 100644 --- a/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift +++ b/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift @@ -83,27 +83,94 @@ extension BrowserWebExtensionSupport: WKWebExtensionControllerDelegate { shouldActivate: Bool, webViewConfiguration: WKWebViewConfiguration? ) -> BrowserWebExtensionTabAdapter? { - guard let sourcePanel = activeTabAdapter?.panel, - let workspace = AppDelegate.shared?.workspaceContainingPanel( - panelId: sourcePanel.id, - preferredWorkspaceId: sourcePanel.workspaceId - )?.workspace, - let paneId = workspace.paneId(forPanelId: sourcePanel.id), - let panel = workspace.newBrowserSurface( + guard let sourcePanel = activeTabAdapter?.panel else { return nil } + if let panel = openWorkspaceBrowserTab( + sourcePanel: sourcePanel, + url: url, + shouldActivate: shouldActivate, + webViewConfiguration: webViewConfiguration + ) { + return tabAdapterForOpenedPanel(panel, shouldActivate: shouldActivate) + } + if let panel = openDockBrowserTab( + sourcePanel: sourcePanel, + url: url, + shouldActivate: shouldActivate, + webViewConfiguration: webViewConfiguration + ) { + return tabAdapterForOpenedPanel(panel, shouldActivate: shouldActivate) + } + return nil + } + + private func openWorkspaceBrowserTab( + sourcePanel: BrowserPanel, + url: URL?, + shouldActivate: Bool, + webViewConfiguration: WKWebViewConfiguration? + ) -> BrowserPanel? { + guard let workspace = AppDelegate.shared?.workspaceContainingPanel( + panelId: sourcePanel.id, + preferredWorkspaceId: sourcePanel.workspaceId + )?.workspace, + let paneId = workspace.paneId(forPanelId: sourcePanel.id) else { + return nil + } + return workspace.newBrowserSurface( + inPane: paneId, + url: url, + focus: shouldActivate, + preferredProfileID: sourcePanel.profileID, + webViewConfiguration: webViewConfiguration + ) + } + + private func openDockBrowserTab( + sourcePanel: BrowserPanel, + url: URL?, + shouldActivate: Bool, + webViewConfiguration: WKWebViewConfiguration? + ) -> BrowserPanel? { + guard let dock = dockContainingPanel(sourcePanel.id), + let paneId = dock.paneId(forPanelId: sourcePanel.id), + let panelID = dock.newSurface( + kind: .browser, inPane: paneId, url: url, focus: shouldActivate, preferredProfileID: sourcePanel.profileID, webViewConfiguration: webViewConfiguration - ) else { - return nil - } + ) else { return nil } + return dock.browserPanel(for: panelID) + } + + private func tabAdapterForOpenedPanel( + _ panel: BrowserPanel, + shouldActivate: Bool + ) -> BrowserWebExtensionTabAdapter? { if shouldActivate { noteActivated(panelID: panel.id) } return tabAdapter(for: panel.id) } + func focusOwningCmuxTab(panelID: UUID, workspaceId: UUID) -> Bool { + if let workspace = AppDelegate.shared?.workspaceContainingPanel( + panelId: panelID, + preferredWorkspaceId: workspaceId + )?.workspace { + workspace.focusPanel(panelID) + return true + } + guard let dock = dockContainingPanel(panelID) else { return false } + dock.focusPanel(panelID) + return true + } + + private func dockContainingPanel(_ panelID: UUID) -> DockSplitStore? { + DockSplitStore.liveStores.first { $0.containsPanel(panelID) } + } + private func canOpenInRegularBrowserTab(_ url: URL) -> Bool { guard let scheme = url.scheme?.lowercased() else { return true } return scheme == "http" || scheme == "https" || scheme == "about" diff --git a/Sources/Panels/BrowserWebExtensionTabAdapter.swift b/Sources/Panels/BrowserWebExtensionTabAdapter.swift index 1f961b4cc47c..39e3b48099f3 100644 --- a/Sources/Panels/BrowserWebExtensionTabAdapter.swift +++ b/Sources/Panels/BrowserWebExtensionTabAdapter.swift @@ -89,12 +89,7 @@ final class BrowserWebExtensionTabAdapter: NSObject, WKWebExtensionTab { private func focusOwningCmuxTab() -> Bool { guard let panel else { return false } - guard let workspace = AppDelegate.shared?.workspaceContainingPanel( - panelId: panelID, - preferredWorkspaceId: panel.workspaceId - )?.workspace else { return false } - workspace.focusPanel(panelID) - return true + return support?.focusOwningCmuxTab(panelID: panelID, workspaceId: panel.workspaceId) ?? false } private func webExtensionTabError(code: Int) -> NSError { diff --git a/Sources/Workspace+DockBrowserLookup.swift b/Sources/Workspace+DockBrowserLookup.swift index 7dd3a75fcf79..64b3eb7479bf 100644 --- a/Sources/Workspace+DockBrowserLookup.swift +++ b/Sources/Workspace+DockBrowserLookup.swift @@ -1,5 +1,6 @@ import AppKit import CmuxCore +import WebKit extension Workspace { func browserPanelIncludingDock(for panelId: UUID) -> BrowserPanel? { @@ -97,7 +98,8 @@ extension DockSplitStore { url: URL?, initialRequest: URLRequest? = nil, preferredProfileID: UUID? = nil, - bypassInsecureHTTPHostOnce: String? = nil + bypassInsecureHTTPHostOnce: String? = nil, + webViewConfiguration: WKWebViewConfiguration? = nil ) -> BrowserPanel { let settings = currentRemoteBrowserSettings() let panel = BrowserPanel( @@ -110,7 +112,8 @@ extension DockSplitStore { bypassRemoteProxy: settings.bypassRemoteProxy, isRemoteWorkspace: settings.isRemoteWorkspace, remoteWebsiteDataStoreIdentifier: settings.remoteWebsiteDataStoreIdentifier, - browserWebExtensionHost: browserWebExtensionHost + browserWebExtensionHost: browserWebExtensionHost, + webViewConfiguration: webViewConfiguration ) panel.setRemoteWorkspaceStatus(settings.remoteStatus) panel.webViewDidRequestClose = { [weak self, weak panel] in From 39f66d82a45cb719a439132de205db857832665b Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 06:35:55 -0700 Subject: [PATCH 29/51] Fix web extension window and toolbar updates --- Sources/DockSplitStore.swift | 8 +-- .../Panels/BrowserNavigationDelegate.swift | 16 ------ Sources/Panels/BrowserPanel.swift | 56 +++++++++---------- ...bExtensionActionSnapshotInvalidation.swift | 12 ++++ ...erWebExtensionPopoutWindowController.swift | 14 ++++- .../BrowserWebExtensionSupport+Loading.swift | 32 +++++++++-- ...ort+WKWebExtensionControllerDelegate.swift | 52 ++++++++++++++++- .../Panels/BrowserWebExtensionSupport.swift | 19 +++++-- .../BrowserWebExtensionTabAdapter.swift | 9 ++- Sources/Workspace+DockBrowserLookup.swift | 12 ++-- Sources/Workspace.swift | 6 +- cmux.xcodeproj/project.pbxproj | 4 ++ 12 files changed, 170 insertions(+), 70 deletions(-) create mode 100644 Sources/Panels/BrowserWebExtensionActionSnapshotInvalidation.swift diff --git a/Sources/DockSplitStore.swift b/Sources/DockSplitStore.swift index 9269c6501975..7970981ca716 100644 --- a/Sources/DockSplitStore.swift +++ b/Sources/DockSplitStore.swift @@ -261,7 +261,7 @@ final class DockSplitStore: BonsplitDelegate { tmuxStartCommand: String? = nil, focus: Bool = true, preferredProfileID: UUID? = nil, - bypassInsecureHTTPHostOnce: String? = nil, webViewConfiguration: WKWebViewConfiguration? = nil + bypassInsecureHTTPHostOnce: String? = nil, webViewConfiguration: WKWebViewConfiguration? = nil, allowWebExtensionInitialNavigationConfiguration: Bool = true ) -> UUID? { ensureLoaded() guard let panel = makePanel( @@ -273,7 +273,7 @@ final class DockSplitStore: BonsplitDelegate { workingDirectory: workingDirectory ?? currentBaseDirectory(), tmuxStartCommand: tmuxStartCommand, preferredProfileID: preferredProfileID, - bypassInsecureHTTPHostOnce: bypassInsecureHTTPHostOnce, webViewConfiguration: webViewConfiguration + bypassInsecureHTTPHostOnce: bypassInsecureHTTPHostOnce, webViewConfiguration: webViewConfiguration, allowWebExtensionInitialNavigationConfiguration: allowWebExtensionInitialNavigationConfiguration ) else { return nil } let previousFocus = focus ? nil : focusedDockPaneSelection() guard let tabId = attachPanelAsTab(panel, kind: kind, title: panel.displayTitle, inPane: paneId, tracksTerminalTitle: true) else { @@ -444,7 +444,7 @@ final class DockSplitStore: BonsplitDelegate { workingDirectory: String, tmuxStartCommand: String? = nil, preferredProfileID: UUID? = nil, - bypassInsecureHTTPHostOnce: String? = nil, webViewConfiguration: WKWebViewConfiguration? = nil + bypassInsecureHTTPHostOnce: String? = nil, webViewConfiguration: WKWebViewConfiguration? = nil, allowWebExtensionInitialNavigationConfiguration: Bool = true ) -> (any Panel)? { switch kind { case .terminal: @@ -466,7 +466,7 @@ final class DockSplitStore: BonsplitDelegate { url: url, initialRequest: initialRequest, preferredProfileID: preferredProfileID, - bypassInsecureHTTPHostOnce: bypassInsecureHTTPHostOnce, webViewConfiguration: webViewConfiguration + bypassInsecureHTTPHostOnce: bypassInsecureHTTPHostOnce, webViewConfiguration: webViewConfiguration, allowWebExtensionInitialNavigationConfiguration: allowWebExtensionInitialNavigationConfiguration ) } } diff --git a/Sources/Panels/BrowserNavigationDelegate.swift b/Sources/Panels/BrowserNavigationDelegate.swift index bfd1b7e66369..86c10b9c8a99 100644 --- a/Sources/Panels/BrowserNavigationDelegate.swift +++ b/Sources/Panels/BrowserNavigationDelegate.swift @@ -21,7 +21,6 @@ import WebKit var shouldBlockInsecureHTTPSubframeDownload: ((URL) -> Bool)? var handleBlockedInsecureHTTPNavigation: ((URLRequest, BrowserInsecureHTTPNavigationIntent) -> Void)? var handleDroppedFileNavigation: (([URL]) -> Bool)? - var shouldReissueNavigationForWebExtensionConfiguration: ((URLRequest) -> Bool)? var currentRestoreAttemptID: (() -> UUID?)? var terminalPolicyCancellationReporter: ((WKNavigationAction, WKWebView) -> () -> Void)? var didRenderPDFDocument: ((URL, Bool) -> Void)? @@ -330,21 +329,6 @@ import WebKit return } - if navigationAction.targetFrame?.isMainFrame == true, - !shouldOpenInNewTab, - shouldReissueNavigationForWebExtensionConfiguration?(navigationAction.request) == true, - let requestNavigation { -#if DEBUG - cmuxDebugLog( - "browser.nav.decidePolicy.action kind=webExtensionConfigurationSwap " + - "url=\(browserNavigationDebugURL(navigationAction.request.url))" - ) -#endif - requestNavigation(navigationAction.request, .currentTab) - decisionHandler(.cancel) - return - } - if let url = navigationAction.request.url, browserShouldRouteExternalNavigation(url) { clearAttemptedRequest(discardPendingBypasses: true) diff --git a/Sources/Panels/BrowserPanel.swift b/Sources/Panels/BrowserPanel.swift index 19257960c710..6af6b4033937 100644 --- a/Sources/Panels/BrowserPanel.swift +++ b/Sources/Panels/BrowserPanel.swift @@ -3103,6 +3103,7 @@ final class BrowserPanel: Panel, ObservableObject { let request: URLRequest let recordTypedNavigation: Bool let preserveRestoredSessionHistory: Bool + let allowWebExtensionContext: Bool } private var pendingRemoteNavigation: PendingRemoteNavigation? private let bypassesRemoteWorkspaceProxy: Bool @@ -3956,7 +3957,7 @@ final class BrowserPanel: Panel, ObservableObject { isRemoteWorkspace: Bool = false, remoteWebsiteDataStoreIdentifier: UUID? = nil, browserWebExtensionHost: (any BrowserWebExtensionHosting)? = nil, - webViewConfiguration: WKWebViewConfiguration? = nil + webViewConfiguration: WKWebViewConfiguration? = nil, allowWebExtensionInitialNavigationConfiguration: Bool = true ) { // Register fallback defaults and normalize legacy/out-of-range settings once // per process, before any setting is read below or by the SwiftUI view. @@ -3979,9 +3980,8 @@ final class BrowserPanel: Panel, ObservableObject { : BrowserProfileStore.shared.websiteDataStore(for: resolvedProfileID) self.websiteDataStore = websiteDataStore self.browserWebExtensionHost = browserWebExtensionHost - let initialExtensionNavigationConfiguration = (initialRequest?.url ?? initialURL).flatMap { - browserWebExtensionHost?.webViewConfiguration(forNavigatingTo: $0) - } + let canUseInitialExtensionConfiguration = allowWebExtensionInitialNavigationConfiguration || webViewConfiguration != nil + let initialExtensionNavigationConfiguration = canUseInitialExtensionConfiguration ? (initialRequest?.url ?? initialURL).flatMap { browserWebExtensionHost?.webViewConfiguration(forNavigatingTo: $0) } : nil let initialWebViewConfiguration = webViewConfiguration ?? initialExtensionNavigationConfiguration?.webViewConfiguration let webView: CmuxWebView @@ -4020,9 +4020,6 @@ final class BrowserPanel: Panel, ObservableObject { navDelegate.requestNavigation = { [weak self] request, intent in self?.requestNavigation(request, intent: intent) } - navDelegate.shouldReissueNavigationForWebExtensionConfiguration = { [weak self] request in - self?.needsWebExtensionNavigationConfigurationSwap(for: request) ?? false - } navDelegate.presentAlert = { [weak self] alert, webView, completion, cancel in guard let self else { cancel() @@ -5760,7 +5757,7 @@ final class BrowserPanel: Panel, ObservableObject { private func navigateWithoutInsecureHTTPPrompt( request: URLRequest, recordTypedNavigation: Bool, - preserveRestoredSessionHistory: Bool = false + preserveRestoredSessionHistory: Bool = false, allowWebExtensionContext: Bool = true ) { guard let url = request.url else { return } cancelHiddenWebViewDiscard() @@ -5768,7 +5765,7 @@ final class BrowserPanel: Panel, ObservableObject { pendingRemoteNavigation = PendingRemoteNavigation( request: request, recordTypedNavigation: recordTypedNavigation, - preserveRestoredSessionHistory: preserveRestoredSessionHistory + preserveRestoredSessionHistory: preserveRestoredSessionHistory, allowWebExtensionContext: allowWebExtensionContext ) hiddenWebViewDiscardManager.updateRestoredSessionRenderIntent(nil) currentURL = Self.remoteProxyDisplayURL(for: url) ?? url @@ -5781,7 +5778,7 @@ final class BrowserPanel: Panel, ObservableObject { request: request, originalURL: url, recordTypedNavigation: recordTypedNavigation, - preserveRestoredSessionHistory: preserveRestoredSessionHistory + preserveRestoredSessionHistory: preserveRestoredSessionHistory, allowWebExtensionContext: allowWebExtensionContext ) } @@ -5801,7 +5798,7 @@ final class BrowserPanel: Panel, ObservableObject { request: navigation.request, originalURL: originalURL, recordTypedNavigation: navigation.recordTypedNavigation, - preserveRestoredSessionHistory: navigation.preserveRestoredSessionHistory + preserveRestoredSessionHistory: navigation.preserveRestoredSessionHistory, allowWebExtensionContext: navigation.allowWebExtensionContext ) pendingRemoteNavigation = nil } @@ -5810,7 +5807,7 @@ final class BrowserPanel: Panel, ObservableObject { request: URLRequest, originalURL: URL, recordTypedNavigation: Bool, - preserveRestoredSessionHistory: Bool + preserveRestoredSessionHistory: Bool, allowWebExtensionContext: Bool ) { cancelHiddenWebViewDiscard() clearWebContentTerminationRecovery() @@ -5818,7 +5815,7 @@ final class BrowserPanel: Panel, ObservableObject { abandonRestoredSessionHistoryIfNeeded() } let effectiveRequest = remoteProxyPreparedRequest(from: request, logScope: "rewrite") - ensureWebExtensionNavigationConfiguration(for: originalURL) + ensureWebExtensionNavigationConfiguration(for: originalURL, allowWebExtensionContext: allowWebExtensionContext) // Some installs can end up with a legacy Chrome UA override; keep this pinned. webView.customUserAgent = BrowserUserAgentSettings.safariUserAgent hiddenWebViewDiscardManager.updateRestoredSessionRenderIntent(nil) @@ -5842,22 +5839,25 @@ final class BrowserPanel: Panel, ObservableObject { } } - private func needsWebExtensionNavigationConfigurationSwap(for request: URLRequest) -> Bool { - guard let url = request.url else { return false } - let targetContextIdentifier = browserWebExtensionHost? - .webViewConfiguration(forNavigatingTo: url)? - .contextIdentifier - return targetContextIdentifier != webExtensionPageContextIdentifier - } - - private func ensureWebExtensionNavigationConfiguration(for url: URL) { + private func ensureWebExtensionNavigationConfiguration(for url: URL, allowWebExtensionContext: Bool) { let targetConfiguration = browserWebExtensionHost?.webViewConfiguration(forNavigatingTo: url) let targetContextIdentifier = targetConfiguration?.contextIdentifier guard targetContextIdentifier != webExtensionPageContextIdentifier else { return } - replaceWebViewForWebExtensionNavigation( - webViewConfiguration: targetConfiguration?.webViewConfiguration, - contextIdentifier: targetContextIdentifier - ) + guard targetContextIdentifier == nil || allowWebExtensionContext else { return } + replaceWebViewForWebExtensionNavigation(webViewConfiguration: targetConfiguration?.webViewConfiguration, contextIdentifier: targetContextIdentifier) + } + + func navigateFromWebExtension(to url: URL, webViewConfiguration: WKWebViewConfiguration?) { + if let webViewConfiguration { + let contextIdentifier = browserWebExtensionHost? + .webViewConfiguration(forNavigatingTo: url)? + .contextIdentifier + replaceWebViewForWebExtensionNavigation( + webViewConfiguration: webViewConfiguration, + contextIdentifier: contextIdentifier + ) + } + navigate(to: url) } private func replaceWebViewForWebExtensionNavigation( @@ -6008,7 +6008,7 @@ final class BrowserPanel: Panel, ObservableObject { } switch intent { case .currentTab: - navigateWithoutInsecureHTTPPrompt(request: request, recordTypedNavigation: false) + navigateWithoutInsecureHTTPPrompt(request: request, recordTypedNavigation: false, allowWebExtensionContext: false) case .newTab: openLinkInNewTab(request: request) } @@ -6499,7 +6499,7 @@ extension BrowserPanel { initialRequest: seed.initialRequest, focus: true, preferredProfileID: profileID, - bypassInsecureHTTPHostOnce: seed.bypassInsecureHTTPHostOnce + bypassInsecureHTTPHostOnce: seed.bypassInsecureHTTPHostOnce, allowWebExtensionInitialNavigationConfiguration: false ) else { #if DEBUG cmuxDebugLog("browser.newTab.open.abort panel=\(id.uuidString.prefix(5)) reason=newPanelFailed") diff --git a/Sources/Panels/BrowserWebExtensionActionSnapshotInvalidation.swift b/Sources/Panels/BrowserWebExtensionActionSnapshotInvalidation.swift new file mode 100644 index 000000000000..c6c482e7726a --- /dev/null +++ b/Sources/Panels/BrowserWebExtensionActionSnapshotInvalidation.swift @@ -0,0 +1,12 @@ +import Observation + +@available(macOS 15.4, *) +@MainActor +@Observable +final class BrowserWebExtensionActionSnapshotInvalidation { + var revision = 0 + + func refresh() { + revision &+= 1 + } +} diff --git a/Sources/Panels/BrowserWebExtensionPopoutWindowController.swift b/Sources/Panels/BrowserWebExtensionPopoutWindowController.swift index 6aa0608b8bdb..8d6f69599b3d 100644 --- a/Sources/Panels/BrowserWebExtensionPopoutWindowController.swift +++ b/Sources/Panels/BrowserWebExtensionPopoutWindowController.swift @@ -67,7 +67,8 @@ final class BrowserWebExtensionPopoutWindowController: NSObject, WKWebExtensionW defaultValue: "Extension" ) - if let url = configuration.tabURLs.first { + if let url = configuration.tabURLs.first, + support.canOpenExtensionRequestedBrowserURL(url) { webView.load(URLRequest(url: url)) } if configuration.shouldBeFocused { @@ -136,6 +137,10 @@ final class BrowserWebExtensionPopoutWindowController: NSObject, WKWebExtensionW completionHandler(nil) } + func canLoadExtensionRequestedURL(_ url: URL) -> Bool { + support?.canOpenExtensionRequestedBrowserURL(url) == true + } + // MARK: - Tab /// The popout window's single extension-page tab. @@ -177,7 +182,12 @@ final class BrowserWebExtensionPopoutWindowController: NSObject, WKWebExtensionW } func loadURL(_ url: URL, for context: WKWebExtensionContext, completionHandler: @escaping (Error?) -> Void) { - controller?.webView.load(URLRequest(url: url)) + guard let controller, + controller.canLoadExtensionRequestedURL(url) else { + completionHandler(NSError(domain: "cmux.webExtension.popup", code: 1)) + return + } + controller.webView.load(URLRequest(url: url)) completionHandler(nil) } diff --git a/Sources/Panels/BrowserWebExtensionSupport+Loading.swift b/Sources/Panels/BrowserWebExtensionSupport+Loading.swift index 4768bfd5379d..ad5ca847fbac 100644 --- a/Sources/Panels/BrowserWebExtensionSupport+Loading.swift +++ b/Sources/Panels/BrowserWebExtensionSupport+Loading.swift @@ -8,6 +8,11 @@ extension BrowserWebExtensionSupport { } func apply(entries: [BrowserWebExtensionEntry]) async { + await apply(entries: entries, generation: settingsLoadGeneration) + } + + func apply(entries: [BrowserWebExtensionEntry], generation: Int) async { + guard canApplyWebExtensionLoad(generation: generation) else { return } let planner = BrowserWebExtensionReconciliationPlanner() let plan = planner.plan( settingsEntries: entries, @@ -24,19 +29,28 @@ extension BrowserWebExtensionSupport { unload(entryID: entryID) } + guard canApplyWebExtensionLoad(generation: generation) else { return } for entry in plan.loadEntries where loadedByEntryID[entry.id] == nil { - await load(entry: entry) + await load(entry: entry, generation: generation) } + guard canApplyWebExtensionLoad(generation: generation) else { return } rebuildActionSnapshots() } + func canApplyWebExtensionLoad(generation: Int) -> Bool { + generation == settingsLoadGeneration && + !Task.isCancelled && + BrowserAvailabilitySettings.isEnabled() + } + func context(forActionID actionID: String) -> WKWebExtensionContext? { loadedByEntryID[actionID]?.context } func actionSnapshots(for panelID: UUID) -> [BrowserWebExtensionActionSnapshot] { _ = actionSnapshotRevision + _ = actionSnapshotInvalidationsByPanelID[panelID]?.revision let tabAdapter = tabAdapters[panelID] return actionSnapshotIDs.compactMap { entryID in guard let record = loadedByEntryID[entryID] else { return nil } @@ -46,7 +60,7 @@ extension BrowserWebExtensionSupport { func rebuildActionSnapshots() { actionSnapshotIDs = loadedRecordsInOrder.map(\.entryID) - refreshActionSnapshots() + refreshAllActionSnapshots() } func refreshActionSnapshot(for context: WKWebExtensionContext) { @@ -54,13 +68,19 @@ extension BrowserWebExtensionSupport { rebuildActionSnapshots() return } - refreshActionSnapshots() + refreshAllActionSnapshots() } - func refreshActionSnapshots() { + func refreshAllActionSnapshots() { actionSnapshotRevision &+= 1 } + func refreshActionSnapshots(for panelID: UUID?) { + guard let panelID, + let invalidation = actionSnapshotInvalidationsByPanelID[panelID] else { return } + invalidation.refresh() + } + private func actionSnapshot( for record: BrowserWebExtensionLoadedRecord, tabAdapter: BrowserWebExtensionTabAdapter? @@ -117,9 +137,10 @@ extension BrowserWebExtensionSupport { rebuildActionSnapshots() } - private func load(entry: BrowserWebExtensionEntry) async { + private func load(entry: BrowserWebExtensionEntry, generation: Int) async { do { let webExtension = try await makeWebExtension(for: entry) + guard canApplyWebExtensionLoad(generation: generation) else { return } let context = try load(webExtension, entryID: entry.id) let standardizedPath = BrowserWebExtensionReconciliationPlanner.standardizedResourceRootPath(for: entry) loadedByEntryID[entry.id] = BrowserWebExtensionLoadedRecord( @@ -139,6 +160,7 @@ extension BrowserWebExtensionSupport { ) #endif } catch { + guard canApplyWebExtensionLoad(generation: generation) else { return } recordLoadError(error.localizedDescription, entryID: entry.id) #if DEBUG cmuxDebugLog("browser.webext.loadFailed url=\(entry.path) error=\(error.localizedDescription)") diff --git a/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift b/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift index f4f259d66c32..229fd0815269 100644 --- a/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift +++ b/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift @@ -40,6 +40,19 @@ extension BrowserWebExtensionSupport: WKWebExtensionControllerDelegate { "urls=\(configuration.tabURLs.count) focused=\(configuration.shouldBeFocused ? 1 : 0)" ) #endif + guard configuration.windowType == .popup else { + guard configuration.windowType == .normal, + let window = openNormalBrowserWindow(using: configuration) else { + completionHandler(nil, openTabsUnsupportedError()) + return + } + completionHandler(window, nil) + return + } + guard configuration.tabURLs.allSatisfy(canOpenExtensionRequestedBrowserURL) else { + completionHandler(nil, openTabsUnsupportedError()) + return + } let popout = BrowserWebExtensionPopoutWindowController( configuration: configuration, context: extensionContext, @@ -51,6 +64,32 @@ extension BrowserWebExtensionSupport: WKWebExtensionControllerDelegate { completionHandler(popout, nil) } + private func openNormalBrowserWindow( + using configuration: WKWebExtension.WindowConfiguration + ) -> (any WKWebExtensionWindow)? { + guard !configuration.tabURLs.isEmpty else { + guard configuration.tabs.isEmpty else { + return windowAdapter + } + return openBrowserTab( + url: nil, + shouldActivate: configuration.shouldBeFocused, + webViewConfiguration: nil + ).map { _ in windowAdapter } + } + + for (index, url) in configuration.tabURLs.enumerated() { + guard canOpenExtensionRequestedBrowserURL(url) else { return nil } + let shouldActivate = configuration.shouldBeFocused && index == 0 + guard openBrowserTab( + url: url, + shouldActivate: shouldActivate, + webViewConfiguration: webViewConfigurationForExtensionRequestedBrowserURL(url) + ) != nil else { return nil } + } + return windowAdapter + } + func webExtensionController( _ controller: WKWebExtensionController, openNewTabUsing configuration: WKWebExtension.TabConfiguration, @@ -61,8 +100,7 @@ extension BrowserWebExtensionSupport: WKWebExtensionControllerDelegate { cmuxDebugLog("browser.webext.openTab url=\(configuration.url?.absoluteString.prefix(80) ?? "nil")") #endif if let url = configuration.url, - !canOpenInRegularBrowserTab(url), - controller.extensionContext(for: url) == nil { + !canOpenExtensionRequestedBrowserURL(url) { completionHandler(nil, openTabsUnsupportedError()) return } @@ -70,7 +108,7 @@ extension BrowserWebExtensionSupport: WKWebExtensionControllerDelegate { guard let adapter = openBrowserTab( url: configuration.url, shouldActivate: configuration.shouldBeActive, - webViewConfiguration: nil + webViewConfiguration: configuration.url.flatMap(webViewConfigurationForExtensionRequestedBrowserURL) ) else { completionHandler(nil, openTabsUnsupportedError()) return @@ -171,6 +209,14 @@ extension BrowserWebExtensionSupport: WKWebExtensionControllerDelegate { DockSplitStore.liveStores.first { $0.containsPanel(panelID) } } + func canOpenExtensionRequestedBrowserURL(_ url: URL) -> Bool { + canOpenInRegularBrowserTab(url) || controller.extensionContext(for: url) != nil + } + + func webViewConfigurationForExtensionRequestedBrowserURL(_ url: URL) -> WKWebViewConfiguration? { + webViewConfiguration(forNavigatingTo: url)?.webViewConfiguration + } + private func canOpenInRegularBrowserTab(_ url: URL) -> Bool { guard let scheme = url.scheme?.lowercased() else { return true } return scheme == "http" || scheme == "https" || scheme == "about" diff --git a/Sources/Panels/BrowserWebExtensionSupport.swift b/Sources/Panels/BrowserWebExtensionSupport.swift index 8cc0ea55acfb..4a316dc73b9f 100644 --- a/Sources/Panels/BrowserWebExtensionSupport.swift +++ b/Sources/Panels/BrowserWebExtensionSupport.swift @@ -34,6 +34,8 @@ final class BrowserWebExtensionSupport: NSObject, BrowserWebExtensionHosting { @ObservationIgnored var settingsObservationTask: Task? @ObservationIgnored + var settingsLoadGeneration = 0 + @ObservationIgnored var browserAvailabilityObserverToken: NSObjectProtocol? @ObservationIgnored var loadedByEntryID: [String: BrowserWebExtensionLoadedRecord] = [:] @@ -44,6 +46,8 @@ final class BrowserWebExtensionSupport: NSObject, BrowserWebExtensionHosting { @ObservationIgnored var tabAdapters: [UUID: BrowserWebExtensionTabAdapter] = [:] @ObservationIgnored + var actionSnapshotInvalidationsByPanelID: [UUID: BrowserWebExtensionActionSnapshotInvalidation] = [:] + @ObservationIgnored var permissionObserverTokensByEntryID: [String: [NSObjectProtocol]] = [:] @ObservationIgnored var orderedPanelIDs: [UUID] = [] @@ -140,15 +144,17 @@ final class BrowserWebExtensionSupport: NSObject, BrowserWebExtensionHosting { key: JSONKey<[BrowserWebExtensionEntry]> ) { guard settingsObservationTask == nil else { return } + settingsLoadGeneration &+= 1 settingsObservationTask = Task { @MainActor [weak self] in for await entries in jsonStore.values(for: key) { guard let self else { return } - await self.apply(entries: entries) + await self.apply(entries: entries, generation: self.settingsLoadGeneration) } } } private func stopSettingsObservationAndUnload() { + settingsLoadGeneration &+= 1 settingsObservationTask?.cancel() settingsObservationTask = nil unloadAllWebExtensions() @@ -165,6 +171,7 @@ final class BrowserWebExtensionSupport: NSObject, BrowserWebExtensionHosting { guard tabAdapters[panel.id] == nil else { return } let adapter = BrowserWebExtensionTabAdapter(panel: panel, support: self) tabAdapters[panel.id] = adapter + actionSnapshotInvalidationsByPanelID[panel.id] = BrowserWebExtensionActionSnapshotInvalidation() orderedPanelIDs.append(panel.id) if activePanelID == nil { activePanelID = panel.id } controller.didOpenTab(adapter) @@ -173,6 +180,7 @@ final class BrowserWebExtensionSupport: NSObject, BrowserWebExtensionHosting { func unregister(panelID: UUID) { guard let adapter = tabAdapters.removeValue(forKey: panelID) else { return } orderedPanelIDs.removeAll { $0 == panelID } + actionSnapshotInvalidationsByPanelID.removeValue(forKey: panelID) controller.didCloseTab(adapter, windowIsClosing: false) if activePanelID == panelID { activePanelID = orderedPanelIDs.last @@ -180,24 +188,27 @@ final class BrowserWebExtensionSupport: NSObject, BrowserWebExtensionHosting { // the closed one until the next focus change. if let successor = activePanelID.flatMap({ tabAdapters[$0] }) { controller.didActivateTab(successor, previousActiveTab: adapter) + refreshActionSnapshots(for: successor.panel?.id) } } } func noteActivated(panelID: UUID) { guard tabAdapters[panelID] != nil, activePanelID != panelID else { return } - let previous = activePanelID.flatMap { tabAdapters[$0] } + let previousPanelID = activePanelID + let previous = previousPanelID.flatMap { tabAdapters[$0] } activePanelID = panelID if let adapter = tabAdapters[panelID] { controller.didActivateTab(adapter, previousActiveTab: previous) } - rebuildActionSnapshots() + refreshActionSnapshots(for: previousPanelID) + refreshActionSnapshots(for: panelID) } func noteTabMetadataChanged(panelID: UUID) { guard let adapter = tabAdapters[panelID] else { return } controller.didChangeTabProperties([.title, .URL, .loading, .muted], for: adapter) - refreshActionSnapshots() + refreshActionSnapshots(for: panelID) } func tabAdapter(for panelID: UUID) -> BrowserWebExtensionTabAdapter? { diff --git a/Sources/Panels/BrowserWebExtensionTabAdapter.swift b/Sources/Panels/BrowserWebExtensionTabAdapter.swift index 39e3b48099f3..db5aa78a2b13 100644 --- a/Sources/Panels/BrowserWebExtensionTabAdapter.swift +++ b/Sources/Panels/BrowserWebExtensionTabAdapter.swift @@ -60,11 +60,16 @@ final class BrowserWebExtensionTabAdapter: NSObject, WKWebExtensionTab { } func loadURL(_ url: URL, for context: WKWebExtensionContext, completionHandler: @escaping (Error?) -> Void) { - guard let panel else { + guard let panel, + let support, + support.canOpenExtensionRequestedBrowserURL(url) else { completionHandler(webExtensionTabError(code: 4)) return } - panel.navigate(to: url) + panel.navigateFromWebExtension( + to: url, + webViewConfiguration: support.webViewConfigurationForExtensionRequestedBrowserURL(url) + ) completionHandler(nil) } diff --git a/Sources/Workspace+DockBrowserLookup.swift b/Sources/Workspace+DockBrowserLookup.swift index 64b3eb7479bf..ad0c2b4f67c4 100644 --- a/Sources/Workspace+DockBrowserLookup.swift +++ b/Sources/Workspace+DockBrowserLookup.swift @@ -48,7 +48,8 @@ extension Workspace { initialRequest: seed.initialRequest, focus: true, preferredProfileID: panel.profileID, - bypassInsecureHTTPHostOnce: seed.bypassInsecureHTTPHostOnce + bypassInsecureHTTPHostOnce: seed.bypassInsecureHTTPHostOnce, + allowWebExtensionInitialNavigationConfiguration: false ) != nil } @@ -64,7 +65,8 @@ extension Workspace { initialRequest: seed.initialRequest, focus: true, preferredProfileID: panel.profileID, - bypassInsecureHTTPHostOnce: seed.bypassInsecureHTTPHostOnce + bypassInsecureHTTPHostOnce: seed.bypassInsecureHTTPHostOnce, + allowWebExtensionInitialNavigationConfiguration: false ) != nil } guard let manager = app.tabManagerFor(tabId: panel.workspaceId) ?? app.tabManager, @@ -99,7 +101,8 @@ extension DockSplitStore { initialRequest: URLRequest? = nil, preferredProfileID: UUID? = nil, bypassInsecureHTTPHostOnce: String? = nil, - webViewConfiguration: WKWebViewConfiguration? = nil + webViewConfiguration: WKWebViewConfiguration? = nil, + allowWebExtensionInitialNavigationConfiguration: Bool = true ) -> BrowserPanel { let settings = currentRemoteBrowserSettings() let panel = BrowserPanel( @@ -113,7 +116,8 @@ extension DockSplitStore { isRemoteWorkspace: settings.isRemoteWorkspace, remoteWebsiteDataStoreIdentifier: settings.remoteWebsiteDataStoreIdentifier, browserWebExtensionHost: browserWebExtensionHost, - webViewConfiguration: webViewConfiguration + webViewConfiguration: webViewConfiguration, + allowWebExtensionInitialNavigationConfiguration: allowWebExtensionInitialNavigationConfiguration ) panel.setRemoteWorkspaceStatus(settings.remoteStatus) panel.webViewDidRequestClose = { [weak self, weak panel] in diff --git a/Sources/Workspace.swift b/Sources/Workspace.swift index 979258e7eab5..ca144ffeabc4 100644 --- a/Sources/Workspace.swift +++ b/Sources/Workspace.swift @@ -8044,7 +8044,8 @@ final class Workspace: Identifiable, ObservableObject { omnibarVisible: Bool = true, transparentBackground: Bool = false, bypassRemoteProxy: Bool = false, - webViewConfiguration: WKWebViewConfiguration? = nil + webViewConfiguration: WKWebViewConfiguration? = nil, + allowWebExtensionInitialNavigationConfiguration: Bool = true ) -> BrowserPanel? { // A remote tmux mirror workspace is a 1:1 view of a tmux session (which // has no browser concept). A local browser tab here would be an orphan @@ -8082,7 +8083,8 @@ final class Workspace: Identifiable, ObservableObject { isRemoteWorkspace: isRemoteWorkspace, remoteWebsiteDataStoreIdentifier: isRemoteWorkspace && !bypassRemoteProxy ? id : nil, browserWebExtensionHost: browserWebExtensionHost, - webViewConfiguration: webViewConfiguration + webViewConfiguration: webViewConfiguration, + allowWebExtensionInitialNavigationConfiguration: allowWebExtensionInitialNavigationConfiguration ) configureBrowserPanel(browserPanel) panels[browserPanel.id] = browserPanel diff --git a/cmux.xcodeproj/project.pbxproj b/cmux.xcodeproj/project.pbxproj index c0f6d3220f62..897bc9493f79 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -311,6 +311,7 @@ C0DE71B10000000000000001 /* AppDelegate+AgentChatNotifications.swift in Sources A50100000000000000000022 /* BrowserWebAuthnUserDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = A50100000000000000000021 /* BrowserWebAuthnUserDescriptor.swift */; }; C0DE49870000000000000001 /* BrowserWebContentProcessTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE49870000000000000002 /* BrowserWebContentProcessTests.swift */; }; B1CFE00A0000000000000001 /* BrowserWebExtensionActionSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1CFE00A0000000000000002 /* BrowserWebExtensionActionSnapshot.swift */; }; + B1CFE0110000000000000001 /* BrowserWebExtensionActionSnapshotInvalidation.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1CFE0110000000000000002 /* BrowserWebExtensionActionSnapshotInvalidation.swift */; }; B1CFE0060000000000000001 /* BrowserWebExtensionDiscoveryService.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1CFE0060000000000000002 /* BrowserWebExtensionDiscoveryService.swift */; }; B1CFE0080000000000000001 /* BrowserWebExtensionHosting.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1CFE0080000000000000002 /* BrowserWebExtensionHosting.swift */; }; B1CFE00B0000000000000001 /* BrowserWebExtensionLoadedRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1CFE00B0000000000000002 /* BrowserWebExtensionLoadedRecord.swift */; }; @@ -2087,6 +2088,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = A50100000000000000000021 /* BrowserWebAuthnUserDescriptor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/BrowserWebAuthnUserDescriptor.swift; sourceTree = ""; }; C0DE49870000000000000002 /* BrowserWebContentProcessTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BrowserWebContentProcessTests.swift; sourceTree = ""; }; B1CFE00A0000000000000002 /* BrowserWebExtensionActionSnapshot.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/BrowserWebExtensionActionSnapshot.swift; sourceTree = ""; }; + B1CFE0110000000000000002 /* BrowserWebExtensionActionSnapshotInvalidation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/BrowserWebExtensionActionSnapshotInvalidation.swift; sourceTree = ""; }; B1CFE0060000000000000002 /* BrowserWebExtensionDiscoveryService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/BrowserWebExtensionDiscoveryService.swift; sourceTree = ""; }; B1CFE0080000000000000002 /* BrowserWebExtensionHosting.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/BrowserWebExtensionHosting.swift; sourceTree = ""; }; B1CFE00B0000000000000002 /* BrowserWebExtensionLoadedRecord.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/BrowserWebExtensionLoadedRecord.swift; sourceTree = ""; }; @@ -4329,6 +4331,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = B1CFE0050000000000000002 /* BrowserWebExtensionPopoutWindowController.swift */, B1CFE0080000000000000002 /* BrowserWebExtensionHosting.swift */, B1CFE00A0000000000000002 /* BrowserWebExtensionActionSnapshot.swift */, + B1CFE0110000000000000002 /* BrowserWebExtensionActionSnapshotInvalidation.swift */, B1CFE00B0000000000000002 /* BrowserWebExtensionLoadedRecord.swift */, B1CFE00D0000000000000002 /* BrowserWebExtensionNavigationConfiguration.swift */, B1CFE00E0000000000000002 /* BrowserWebExtensionPermissionState.swift */, @@ -5893,6 +5896,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = A50100000000000000000020 /* BrowserWebAuthnTransportSummary.swift in Sources */, A50100000000000000000022 /* BrowserWebAuthnUserDescriptor.swift in Sources */, B1CFE00A0000000000000001 /* BrowserWebExtensionActionSnapshot.swift in Sources */, + B1CFE0110000000000000001 /* BrowserWebExtensionActionSnapshotInvalidation.swift in Sources */, B1CFE0060000000000000001 /* BrowserWebExtensionDiscoveryService.swift in Sources */, B1CFE0080000000000000001 /* BrowserWebExtensionHosting.swift in Sources */, B1CFE00B0000000000000001 /* BrowserWebExtensionLoadedRecord.swift in Sources */, From 1dd14fc3d356d69d03946f06abe82005f95ec5a5 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 07:57:05 -0700 Subject: [PATCH 30/51] Fix web extension private windows and activation --- .../Bindings/JSONValueModel.swift | 25 +++- .../Sections/BrowserWebExtensionsCard.swift | 68 ++++++--- .../SettingsRowAnchorResolutionTests.swift | 1 + Sources/DockSplitStore+PaneFocus.swift | 3 + Sources/DockSplitStore.swift | 12 +- .../Panels/BrowserNavigationDelegate.swift | 15 ++ Sources/Panels/BrowserPanel.swift | 17 +-- .../BrowserWebExtensionDiscoveryService.swift | 51 +++++++ ...rWebExtensionNavigationConfiguration.swift | 39 +++++ ...wserWebExtensionPermissionStateStore.swift | 10 ++ ...erWebExtensionPopoutWindowController.swift | 5 +- ...serWebExtensionReconciliationPlanner.swift | 28 +++- .../BrowserWebExtensionSupport+Loading.swift | 54 ++++++- ...owserWebExtensionSupport+Permissions.swift | 4 + ...ort+WKWebExtensionControllerDelegate.swift | 72 +++++++-- .../BrowserWebExtensionTabAdapter.swift | 4 +- Sources/Workspace.swift | 8 +- .../BrowserWebExtensionSupportTests.swift | 137 ++++++++++++++++++ 18 files changed, 481 insertions(+), 72 deletions(-) diff --git a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Bindings/JSONValueModel.swift b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Bindings/JSONValueModel.swift index eb0d4e5b80c5..3c82c249c92e 100644 --- a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Bindings/JSONValueModel.swift +++ b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Bindings/JSONValueModel.swift @@ -28,6 +28,7 @@ public final class JSONValueModel { /// Error from the most recent set/reset attempt, or `nil`. public private(set) var lastWriteError: Error? + private(set) var writeResultRevision = 0 private let store: JSONConfigStore private let key: JSONKey @@ -106,11 +107,17 @@ public final class JSONValueModel { Task { [weak self, store, key] in do { try await store.set(value, for: key) - await MainActor.run { self?.lastWriteError = nil } + await MainActor.run { + guard let self else { return } + self.lastWriteError = nil + self.writeResultRevision &+= 1 + } } catch { await MainActor.run { - self?.lastWriteError = error - self?.errorLog.record(error, keyID: keyID) + guard let self else { return } + self.lastWriteError = error + self.writeResultRevision &+= 1 + self.errorLog.record(error, keyID: keyID) } } } @@ -123,11 +130,17 @@ public final class JSONValueModel { Task { [weak self, store, key] in do { try await store.reset(key) - await MainActor.run { self?.lastWriteError = nil } + await MainActor.run { + guard let self else { return } + self.lastWriteError = nil + self.writeResultRevision &+= 1 + } } catch { await MainActor.run { - self?.lastWriteError = error - self?.errorLog.record(error, keyID: keyID) + guard let self else { return } + self.lastWriteError = error + self.writeResultRevision &+= 1 + self.errorLog.record(error, keyID: keyID) } } } diff --git a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift index 75cafadaf1e4..36526ccdfc20 100644 --- a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift +++ b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift @@ -16,17 +16,19 @@ struct BrowserWebExtensionsCard: View { let hostActions: SettingsHostActions @State private var discovered: [SettingsDiscoveredBrowserExtension] = [] + @State private var pendingEntries: [BrowserWebExtensionEntry]? var body: some View { - let enabledByID = effectiveEnabledByID() + let entries = effectiveEntries + let enabledByID = effectiveEnabledByID(for: entries) SettingsCard { headerRow if supported { - ForEach(model.current) { entry in + ForEach(entries) { entry in SettingsCardDivider() entryRow(entry, isEnabled: enabledByID[entry.id] ?? entry.enabled) } - if model.current.isEmpty { + if entries.isEmpty { SettingsCardDivider() emptyRow } @@ -36,17 +38,30 @@ struct BrowserWebExtensionsCard: View { model.startObserving() discovered = await hostActions.discoverBrowserWebExtensions() } + .onChange(of: model.current) { _, _ in + pendingEntries = nil + } + .onChange(of: model.writeResultRevision) { _, _ in + if model.lastWriteError != nil { + pendingEntries = nil + } + } } private var supported: Bool { hostActions.browserWebExtensionsSupported() } + private var effectiveEntries: [BrowserWebExtensionEntry] { + pendingEntries ?? model.current + } + /// Discovered Safari extensions not yet added, offered by the Import menu. private var importableExtensions: [SettingsDiscoveredBrowserExtension] { guard model.hasObservedValue else { return [] } - let addedIDs = Set(model.current.map(\.id)) - let addedResourcePaths = Set(model.current.map { standardizedResourcePath(for: $0) }) + let entries = effectiveEntries + let addedIDs = Set(entries.map(\.id)) + let addedResourcePaths = Set(entries.map { standardizedResourcePath(for: $0) }) return discovered.filter { candidate in !addedIDs.contains(candidate.id) && !addedResourcePaths.contains(standardizedSafariAppExtensionResourcePath(candidate.path)) @@ -149,22 +164,22 @@ struct BrowserWebExtensionsCard: View { } private func setEnabled(_ enabled: Bool, id: String) { - guard model.hasObservedValue else { return } - var entries = model.current - guard let index = entries.firstIndex(where: { $0.id == id }) else { return } - let targetPath = standardizedResourcePath(for: entries[index]) - entries[index].enabled = enabled - for candidateIndex in entries.indices where candidateIndex != index { - if standardizedResourcePath(for: entries[candidateIndex]) == targetPath { - entries[candidateIndex].enabled = false + updateEntries { entries in + guard let index = entries.firstIndex(where: { $0.id == id }) else { return false } + let targetPath = standardizedResourcePath(for: entries[index]) + entries[index].enabled = enabled + for candidateIndex in entries.indices where candidateIndex != index { + if standardizedResourcePath(for: entries[candidateIndex]) == targetPath { + entries[candidateIndex].enabled = false + } } + return true } - model.set(entries) } private func add(_ entry: BrowserWebExtensionEntry) { guard model.hasObservedValue else { return } - var entries = model.current + var entries = effectiveEntries guard !entries.contains(where: { $0.id == entry.id }) else { presentDuplicateExtensionAlert(for: entry) return @@ -175,12 +190,27 @@ struct BrowserWebExtensionsCard: View { return } entries.append(entry) - model.set(entries) + commitEntries(entries) } private func remove(id: String) { + updateEntries { entries in + let originalCount = entries.count + entries.removeAll { $0.id == id } + return entries.count != originalCount + } + } + + private func updateEntries(_ update: (inout [BrowserWebExtensionEntry]) -> Bool) { guard model.hasObservedValue else { return } - model.set(model.current.filter { $0.id != id }) + var entries = effectiveEntries + guard update(&entries) else { return } + commitEntries(entries) + } + + private func commitEntries(_ entries: [BrowserWebExtensionEntry]) { + pendingEntries = entries + model.set(entries) } private func importSafariExtension(_ candidate: SettingsDiscoveredBrowserExtension) { @@ -254,10 +284,10 @@ struct BrowserWebExtensionsCard: View { alert.runModal() } - private func effectiveEnabledByID() -> [String: Bool] { + private func effectiveEnabledByID(for entries: [BrowserWebExtensionEntry]) -> [String: Bool] { var seenEnabledPaths = Set() var result: [String: Bool] = [:] - for entry in model.current { + for entry in entries { let path = standardizedResourcePath(for: entry) let isFirstEnabledEntryForPath = entry.enabled && seenEnabledPaths.insert(path).inserted result[entry.id] = isFirstEnabledEntryForPath diff --git a/Packages/macOS/CmuxSettingsUI/Tests/CmuxSettingsUITests/SettingsRowAnchorResolutionTests.swift b/Packages/macOS/CmuxSettingsUI/Tests/CmuxSettingsUITests/SettingsRowAnchorResolutionTests.swift index 6ffeba071c3b..ce157795b3bf 100644 --- a/Packages/macOS/CmuxSettingsUI/Tests/CmuxSettingsUITests/SettingsRowAnchorResolutionTests.swift +++ b/Packages/macOS/CmuxSettingsUI/Tests/CmuxSettingsUITests/SettingsRowAnchorResolutionTests.swift @@ -77,6 +77,7 @@ struct SettingsRowAnchorResolutionTests { "browser.showSearchSuggestions", "browser.theme", "browser.urlsToAlwaysOpenExternally", + "browser.webExtensions", "canvas.paneGap", "canvas.snappingEnabled", "customSidebars.renderer", diff --git a/Sources/DockSplitStore+PaneFocus.swift b/Sources/DockSplitStore+PaneFocus.swift index 453b1f496a00..3e2a2826e3c3 100644 --- a/Sources/DockSplitStore+PaneFocus.swift +++ b/Sources/DockSplitStore+PaneFocus.swift @@ -126,6 +126,9 @@ extension DockSplitStore { let activationIntent = selectedPanel.preferredFocusIntentForActivation() selectedPanel.prepareFocusIntentForActivation(activationIntent) + if let browserPanel = selectedPanel as? BrowserPanel { + browserPanel.noteWebExtensionActivated() + } forEachPanel { panelId, panel in if panelId != selectedPanel.id { panel.unfocus() diff --git a/Sources/DockSplitStore.swift b/Sources/DockSplitStore.swift index 7970981ca716..c5f94b1f508f 100644 --- a/Sources/DockSplitStore.swift +++ b/Sources/DockSplitStore.swift @@ -561,20 +561,20 @@ final class DockSplitStore: BonsplitDelegate { func installSubscription(for panel: any Panel, tracksTerminalTitle: Bool) { if let browser = panel as? BrowserPanel { browser.registerWebExtensionIfNeeded() + if focusedPanelId == browser.id { browser.noteWebExtensionActivated() } let cancellable = Publishers.CombineLatest4( - browser.$pageTitle.removeDuplicates(), + browser.$pageTitle.removeDuplicates(), browser.$currentURL.removeDuplicates(), browser.$isLoading.removeDuplicates(), - browser.$faviconPNGData.removeDuplicates(by: { $0 == $1 }), - browser.$isMuted.removeDuplicates() + browser.$faviconPNGData.removeDuplicates(by: { $0 == $1 }) ) + .combineLatest(browser.$isMuted.removeDuplicates()) .receive(on: DispatchQueue.main) .sink { [weak self, weak browser] _ in guard let self, let browser, let tabId = self.surfaceId(forPanelId: browser.id), let existing = self.bonsplitController.tab(tabId) else { return } browser.browserWebExtensionHost?.noteTabMetadataChanged(panelID: browser.id) - // Only push fields that actually changed; otherwise unchanged metadata - // would mutate Bonsplit and re-render the Dock tree for nothing. - // Mirrors the main area's guarded path in Workspace.installBrowserPanelSubscription. + // Only push changed fields; otherwise unchanged metadata would + // mutate Bonsplit. Mirrors Workspace.installBrowserPanelSubscription. let resolvedTitle = browser.displayTitle let favicon = browser.faviconPNGData let titleUpdate: String? = existing.title == resolvedTitle ? nil : resolvedTitle diff --git a/Sources/Panels/BrowserNavigationDelegate.swift b/Sources/Panels/BrowserNavigationDelegate.swift index 86c10b9c8a99..fd49d0f3206e 100644 --- a/Sources/Panels/BrowserNavigationDelegate.swift +++ b/Sources/Panels/BrowserNavigationDelegate.swift @@ -19,6 +19,7 @@ import WebKit var presentAlert: BrowserAlertPresenter = browserPresentAlert var shouldBlockInsecureHTTPNavigation: ((URL) -> Bool)? var shouldBlockInsecureHTTPSubframeDownload: ((URL) -> Bool)? + var shouldBlockWebExtensionNavigation: ((URL) -> Bool)?; var shouldRouteWebExtensionNavigationInCurrentTab: ((URL) -> Bool)? var handleBlockedInsecureHTTPNavigation: ((URLRequest, BrowserInsecureHTTPNavigationIntent) -> Void)? var handleDroppedFileNavigation: (([URL]) -> Bool)? var currentRestoreAttemptID: (() -> UUID?)? @@ -293,6 +294,12 @@ import WebKit ) #endif + if let url = navigationAction.request.url, + shouldBlockWebExtensionNavigation?(url) == true { + clearAttemptedRequest(discardPendingBypasses: true) + decisionHandler(.cancel); return + } + if let url = navigationAction.request.url, shouldOpenCheckoutInSystemBrowser(navigationAction, url: url) { clearAttemptedRequest(discardPendingBypasses: true) @@ -347,6 +354,14 @@ import WebKit return } + if let url = navigationAction.request.url, + navigationAction.targetFrame?.isMainFrame != false, + shouldRouteWebExtensionNavigationInCurrentTab?(url) == true { + clearAttemptedRequest(discardPendingBypasses: true) + requestNavigation?(navigationAction.request, .currentTab) + decisionHandler(.cancel); return + } + if navigationAction.shouldPerformDownload { if navigationAction.targetFrame?.isMainFrame == false { guard let url = navigationAction.request.url else { diff --git a/Sources/Panels/BrowserPanel.swift b/Sources/Panels/BrowserPanel.swift index 6af6b4033937..583b2bc735fb 100644 --- a/Sources/Panels/BrowserPanel.swift +++ b/Sources/Panels/BrowserPanel.swift @@ -2748,7 +2748,7 @@ final class BrowserPanel: Panel, ObservableObject { private(set) var webView: WKWebView private var websiteDataStore: WKWebsiteDataStore let browserWebExtensionHost: (any BrowserWebExtensionHosting)? - private var webExtensionPageContextIdentifier: ObjectIdentifier? + private(set) var webExtensionPageContextIdentifier: ObjectIdentifier? private var isRegisteredForWebExtensions = false var webViewDidRequestClose: (() -> Void)? @@ -4029,6 +4029,8 @@ final class BrowserPanel: Panel, ObservableObject { } navDelegate.shouldBlockInsecureHTTPNavigation = { [weak self] in self?.shouldBlockInsecureHTTPNavigation(to: $0) ?? false } navDelegate.shouldBlockInsecureHTTPSubframeDownload = { browserShouldBlockInsecureHTTPURL($0) } + navDelegate.shouldBlockWebExtensionNavigation = { [weak self] in self?.shouldBlockPageInitiatedWebExtensionNavigation(to: $0) ?? false } + navDelegate.shouldRouteWebExtensionNavigationInCurrentTab = { [weak self] in self?.shouldRoutePageInitiatedWebExtensionNavigationInCurrentTab(to: $0) ?? false } navDelegate.handleBlockedInsecureHTTPNavigation = { [weak self] request, intent in guard let self else { return } let restoreAttemptID = self.currentDiscardRestoreAttemptID @@ -4216,10 +4218,7 @@ final class BrowserPanel: Panel, ObservableObject { recordTypedNavigation: false ) } else { - navigateWithoutInsecureHTTPPrompt( - request: initialRequest, - recordTypedNavigation: false - ) + navigateWithoutInsecureHTTPPrompt(request: initialRequest, recordTypedNavigation: false, allowWebExtensionContext: initialExtensionNavigationConfiguration != nil) } } else if let url = initialURL { hiddenWebViewDiscardManager.updateRestoredSessionRenderIntent(nil) @@ -4234,7 +4233,7 @@ final class BrowserPanel: Panel, ObservableObject { hasCommittedDocumentSinceWebViewReplacement = true refreshBackgroundAppearance() } else { - navigate(to: url) + navigate(to: url, allowWebExtensionContext: initialExtensionNavigationConfiguration != nil) } } } @@ -5731,13 +5730,13 @@ final class BrowserPanel: Panel, ObservableObject { // MARK: - Navigation /// Navigate to a URL - func navigate(to url: URL, recordTypedNavigation: Bool = false) { + func navigate(to url: URL, recordTypedNavigation: Bool = false, allowWebExtensionContext: Bool = true) { let request = URLRequest(url: url) if shouldBlockInsecureHTTPNavigation(to: url) { presentInsecureHTTPAlert(for: request, intent: .currentTab, recordTypedNavigation: recordTypedNavigation) return } - navigateWithoutInsecureHTTPPrompt(request: request, recordTypedNavigation: recordTypedNavigation) + navigateWithoutInsecureHTTPPrompt(request: request, recordTypedNavigation: recordTypedNavigation, allowWebExtensionContext: allowWebExtensionContext) } func navigateWithoutInsecureHTTPPrompt( @@ -5759,7 +5758,7 @@ final class BrowserPanel: Panel, ObservableObject { recordTypedNavigation: Bool, preserveRestoredSessionHistory: Bool = false, allowWebExtensionContext: Bool = true ) { - guard let url = request.url else { return } + guard let url = request.url, !shouldBlockWebExtensionNavigation(to: url, allowWebExtensionContext: allowWebExtensionContext) else { return } cancelHiddenWebViewDiscard() if usesRemoteWorkspaceProxy, remoteProxyEndpoint == nil { pendingRemoteNavigation = PendingRemoteNavigation( diff --git a/Sources/Panels/BrowserWebExtensionDiscoveryService.swift b/Sources/Panels/BrowserWebExtensionDiscoveryService.swift index 58e343cb5d25..dd1a023b2d74 100644 --- a/Sources/Panels/BrowserWebExtensionDiscoveryService.swift +++ b/Sources/Panels/BrowserWebExtensionDiscoveryService.swift @@ -25,6 +25,9 @@ struct BrowserWebExtensionCandidate: Identifiable, Hashable, Sendable { /// (Bitwarden, 1Password, AdGuard, …) is found without configuration. actor BrowserWebExtensionDiscoveryService { private static let pluginkitURL = URL(fileURLWithPath: "/usr/bin/pluginkit") + private static let pluginkitTimeout: Duration = .seconds(10) + private var activePluginkitProcess: Process? + private var activePluginkitStdout: Pipe? func discoverInstalledSafariExtensions() async -> [BrowserWebExtensionCandidate] { let output: String @@ -106,6 +109,15 @@ actor BrowserWebExtensionDiscoveryService { } private func runPluginkit() async throws -> String { + try await withTaskCancellationHandler { + try startPluginkitProcess() + return try await readActivePluginkitOutputWithTimeout() + } onCancel: { + Task { await self.terminateActivePluginkitProcess() } + } + } + + private func startPluginkitProcess() throws { let process = Process() process.executableURL = Self.pluginkitURL process.arguments = ["-m", "-p", "com.apple.Safari.web-extension", "-A", "-v"] @@ -114,8 +126,34 @@ actor BrowserWebExtensionDiscoveryService { // Discard rather than pipe stderr: an undrained pipe could block the // child if it wrote enough diagnostics, hanging discovery. process.standardError = FileHandle.nullDevice + activePluginkitProcess = process + activePluginkitStdout = stdout try process.run() + } + + private func readActivePluginkitOutputWithTimeout() async throws -> String { + try await withThrowingTaskGroup(of: String.self) { group in + group.addTask { try await self.readActivePluginkitOutput() } + group.addTask { + try await Task.sleep(for: Self.pluginkitTimeout) + await self.terminateActivePluginkitProcess() + throw CancellationError() + } + do { + let output = try await group.next() ?? "" + group.cancelAll() + clearActivePluginkitProcess() + return output + } catch { + group.cancelAll() + await terminateActivePluginkitProcess() + throw error + } + } + } + private func readActivePluginkitOutput() async throws -> String { + guard let stdout = activePluginkitStdout else { return "" } var data = Data() // EOF on stdout is the completion signal; pluginkit's exit status is // uninteresting (an empty listing and a failure both mean "none found"). @@ -124,4 +162,17 @@ actor BrowserWebExtensionDiscoveryService { } return String(data: data, encoding: .utf8) ?? "" } + + private func terminateActivePluginkitProcess() { + if let process = activePluginkitProcess, process.isRunning { + process.terminate() + } + try? activePluginkitStdout?.fileHandleForReading.close() + clearActivePluginkitProcess() + } + + private func clearActivePluginkitProcess() { + activePluginkitProcess = nil + activePluginkitStdout = nil + } } diff --git a/Sources/Panels/BrowserWebExtensionNavigationConfiguration.swift b/Sources/Panels/BrowserWebExtensionNavigationConfiguration.swift index eef7246a1d2a..4818443947e8 100644 --- a/Sources/Panels/BrowserWebExtensionNavigationConfiguration.swift +++ b/Sources/Panels/BrowserWebExtensionNavigationConfiguration.swift @@ -4,3 +4,42 @@ struct BrowserWebExtensionNavigationConfiguration { let contextIdentifier: ObjectIdentifier let webViewConfiguration: WKWebViewConfiguration } + +extension BrowserPanel { + func shouldBlockWebExtensionNavigation(to url: URL, allowWebExtensionContext: Bool) -> Bool { + guard !allowWebExtensionContext else { return false } + if browserWebExtensionHost?.webViewConfiguration(forNavigatingTo: url) != nil { + return true + } + return url.scheme?.lowercased() == "webkit-extension" + } + + func shouldBlockPageInitiatedWebExtensionNavigation(to url: URL) -> Bool { + let targetContextIdentifier = browserWebExtensionHost? + .webViewConfiguration(forNavigatingTo: url)? + .contextIdentifier + if let targetContextIdentifier, + targetContextIdentifier == webExtensionPageContextIdentifier { + return false + } + if webExtensionPageContextIdentifier != nil, + !canOpenPageInitiatedWebExtensionExitURL(url) { + return true + } + return targetContextIdentifier != nil || url.scheme?.lowercased() == "webkit-extension" + } + + func shouldRoutePageInitiatedWebExtensionNavigationInCurrentTab(to url: URL) -> Bool { + guard webExtensionPageContextIdentifier != nil, + canOpenPageInitiatedWebExtensionExitURL(url) else { return false } + let targetContextIdentifier = browserWebExtensionHost? + .webViewConfiguration(forNavigatingTo: url)? + .contextIdentifier + return targetContextIdentifier != webExtensionPageContextIdentifier + } + + func canOpenPageInitiatedWebExtensionExitURL(_ url: URL) -> Bool { + guard let scheme = url.scheme?.lowercased() else { return true } + return scheme == "http" || scheme == "https" || scheme == "about" + } +} diff --git a/Sources/Panels/BrowserWebExtensionPermissionStateStore.swift b/Sources/Panels/BrowserWebExtensionPermissionStateStore.swift index 02fa70554e6d..5b42fa0e74c2 100644 --- a/Sources/Panels/BrowserWebExtensionPermissionStateStore.swift +++ b/Sources/Panels/BrowserWebExtensionPermissionStateStore.swift @@ -20,6 +20,12 @@ struct BrowserWebExtensionPermissionStateStore { saveAllStates(states) } + func removeState(for entryID: String) { + var states = allStates() + guard states.removeValue(forKey: entryID) != nil else { return } + saveAllStates(states) + } + private func allStates() -> [String: BrowserWebExtensionPermissionState] { guard let data = defaults.data(forKey: Self.storageKey), let states = try? PropertyListDecoder().decode( @@ -32,6 +38,10 @@ struct BrowserWebExtensionPermissionStateStore { } private func saveAllStates(_ states: [String: BrowserWebExtensionPermissionState]) { + guard !states.isEmpty else { + defaults.removeObject(forKey: Self.storageKey) + return + } guard let data = try? PropertyListEncoder().encode(states) else { return } defaults.set(data, forKey: Self.storageKey) } diff --git a/Sources/Panels/BrowserWebExtensionPopoutWindowController.swift b/Sources/Panels/BrowserWebExtensionPopoutWindowController.swift index 8d6f69599b3d..094110156672 100644 --- a/Sources/Panels/BrowserWebExtensionPopoutWindowController.swift +++ b/Sources/Panels/BrowserWebExtensionPopoutWindowController.swift @@ -68,7 +68,7 @@ final class BrowserWebExtensionPopoutWindowController: NSObject, WKWebExtensionW ) if let url = configuration.tabURLs.first, - support.canOpenExtensionRequestedBrowserURL(url) { + support.canOpenExtensionPopupURL(url, for: context) { webView.load(URLRequest(url: url)) } if configuration.shouldBeFocused { @@ -138,7 +138,8 @@ final class BrowserWebExtensionPopoutWindowController: NSObject, WKWebExtensionW } func canLoadExtensionRequestedURL(_ url: URL) -> Bool { - support?.canOpenExtensionRequestedBrowserURL(url) == true + guard let extensionContext else { return false } + return support?.canOpenExtensionPopupURL(url, for: extensionContext) == true } // MARK: - Tab diff --git a/Sources/Panels/BrowserWebExtensionReconciliationPlanner.swift b/Sources/Panels/BrowserWebExtensionReconciliationPlanner.swift index 8328b14f561b..ff27b6c7ff34 100644 --- a/Sources/Panels/BrowserWebExtensionReconciliationPlanner.swift +++ b/Sources/Panels/BrowserWebExtensionReconciliationPlanner.swift @@ -7,10 +7,19 @@ struct BrowserWebExtensionReconciliationPlanner { let standardizedPath: String } + struct UnloadEntry: Equatable { + let id: String + let preservePermissionState: Bool + } + struct Plan: Equatable { let desiredEntries: [BrowserWebExtensionEntry] - let unloadEntryIDs: [String] + let unloadEntries: [UnloadEntry] let loadEntries: [BrowserWebExtensionEntry] + + var unloadEntryIDs: [String] { + unloadEntries.map(\.id) + } } func plan( @@ -21,14 +30,23 @@ struct BrowserWebExtensionReconciliationPlanner { let loadedByID = Dictionary(uniqueKeysWithValues: loadedEntries.map { ($0.id, $0) }) let desiredEntries = desired(settingsEntries: settingsEntries, environmentPaths: environmentPaths) let desiredByID = Dictionary(uniqueKeysWithValues: desiredEntries.map { ($0.id, $0) }) + var configuredResourceRootByID: [String: String] = [:] + for entry in settingsEntries { + configuredResourceRootByID[entry.id] = Self.standardizedResourceRootPath(for: entry) + } - let unloadEntryIDs = loadedEntries + let unloadEntries = loadedEntries .filter { loaded in guard let desired = desiredByID[loaded.id] else { return true } return Self.standardizedResourceRootPath(for: desired) != loaded.standardizedPath } - .map(\.id) - .sorted() + .map { loaded in + UnloadEntry( + id: loaded.id, + preservePermissionState: configuredResourceRootByID[loaded.id] == loaded.standardizedPath + ) + } + .sorted { $0.id < $1.id } let loadEntries = desiredEntries.filter { entry in guard let loaded = loadedByID[entry.id] else { return true } @@ -37,7 +55,7 @@ struct BrowserWebExtensionReconciliationPlanner { return Plan( desiredEntries: desiredEntries, - unloadEntryIDs: unloadEntryIDs, + unloadEntries: unloadEntries, loadEntries: loadEntries ) } diff --git a/Sources/Panels/BrowserWebExtensionSupport+Loading.swift b/Sources/Panels/BrowserWebExtensionSupport+Loading.swift index ad5ca847fbac..5a72c7654ec2 100644 --- a/Sources/Panels/BrowserWebExtensionSupport+Loading.swift +++ b/Sources/Panels/BrowserWebExtensionSupport+Loading.swift @@ -1,4 +1,6 @@ import CmuxSettings +import CryptoKit +import Foundation import WebKit @available(macOS 15.4, *) @@ -25,8 +27,8 @@ extension BrowserWebExtensionSupport { } ) - for entryID in plan.unloadEntryIDs { - unload(entryID: entryID) + for entry in plan.unloadEntries { + unload(entryID: entry.id, preservePermissionState: entry.preservePermissionState) } guard canApplyWebExtensionLoad(generation: generation) else { return } @@ -71,6 +73,16 @@ extension BrowserWebExtensionSupport { refreshAllActionSnapshots() } + func refreshActionSnapshot(for action: WKWebExtension.Action, context: WKWebExtensionContext) { + if let adapter = action.associatedTab as? BrowserWebExtensionTabAdapter, + let panelID = adapter.panel?.id, + tabAdapters[panelID] === adapter { + refreshActionSnapshots(for: panelID) + return + } + refreshActionSnapshot(for: context) + } + func refreshAllActionSnapshots() { actionSnapshotRevision &+= 1 } @@ -100,9 +112,11 @@ extension BrowserWebExtensionSupport { ) } - private func unload(entryID: String) { + private func unload(entryID: String, preservePermissionState: Bool = true) { guard let record = loadedByEntryID[entryID] else { return } - persistPermissionState(entryID: entryID, context: record.context) + if preservePermissionState { + persistPermissionState(entryID: entryID, context: record.context) + } do { try controller.unload(record.context) } catch { @@ -114,6 +128,9 @@ extension BrowserWebExtensionSupport { } removePermissionStateObservers(entryID: entryID) + if !preservePermissionState { + removePermissionState(entryID: entryID) + } loadedByEntryID[entryID] = nil loadedEntryIDsInOrder.removeAll { $0 == entryID } loadErrorsByEntryID.removeValue(forKey: entryID) @@ -141,8 +158,8 @@ extension BrowserWebExtensionSupport { do { let webExtension = try await makeWebExtension(for: entry) guard canApplyWebExtensionLoad(generation: generation) else { return } - let context = try load(webExtension, entryID: entry.id) let standardizedPath = BrowserWebExtensionReconciliationPlanner.standardizedResourceRootPath(for: entry) + let context = try load(webExtension, entryID: entry.id, standardizedPath: standardizedPath) loadedByEntryID[entry.id] = BrowserWebExtensionLoadedRecord( entryID: entry.id, standardizedPath: standardizedPath, @@ -181,8 +198,13 @@ extension BrowserWebExtensionSupport { } @discardableResult - private func load(_ webExtension: WKWebExtension, entryID: String) throws -> WKWebExtensionContext { + private func load( + _ webExtension: WKWebExtension, + entryID: String, + standardizedPath: String + ) throws -> WKWebExtensionContext { let context = WKWebExtensionContext(for: webExtension) + configureStableContextIdentity(context, entryID: entryID, standardizedPath: standardizedPath) #if DEBUG context.isInspectable = true #endif @@ -197,6 +219,26 @@ extension BrowserWebExtensionSupport { return context } + private func configureStableContextIdentity( + _ context: WKWebExtensionContext, + entryID: String, + standardizedPath: String + ) { + let identifier = stableContextIdentifier(entryID: entryID, standardizedPath: standardizedPath) + context.uniqueIdentifier = identifier + context.baseURL = URL(string: "webkit-extension://\(identifier)/")! + } + + private func stableContextIdentifier(entryID: String, standardizedPath: String) -> String { + let identity = "\(entryID)\n\(standardizedPath)" + let digest = SHA256.hash(data: Data(identity.utf8)) + let hexDigits = Array("0123456789abcdef".utf8) + let hexBytes = digest.flatMap { byte in + [hexDigits[Int(byte >> 4)], hexDigits[Int(byte & 0x0f)]] + } + return "cmux-\(String(decoding: hexBytes, as: UTF8.self))" + } + private func recordLoadError(_ message: String, entryID: String) { loadErrorsByEntryID[entryID] = "\(entryID): \(message)" refreshLoadErrors() diff --git a/Sources/Panels/BrowserWebExtensionSupport+Permissions.swift b/Sources/Panels/BrowserWebExtensionSupport+Permissions.swift index 98eb2652b2dd..874243292572 100644 --- a/Sources/Panels/BrowserWebExtensionSupport+Permissions.swift +++ b/Sources/Panels/BrowserWebExtensionSupport+Permissions.swift @@ -11,6 +11,10 @@ extension BrowserWebExtensionSupport { permissionStateStore.save(BrowserWebExtensionPermissionState(context: context), for: entryID) } + func removePermissionState(entryID: String) { + permissionStateStore.removeState(for: entryID) + } + func persistPermissionState(for context: WKWebExtensionContext) { guard let record = loadedRecordsInOrder.first(where: { $0.context === context }) else { return } persistPermissionState(entryID: record.entryID, context: context) diff --git a/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift b/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift index 229fd0815269..807c1d730d70 100644 --- a/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift +++ b/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift @@ -40,16 +40,20 @@ extension BrowserWebExtensionSupport: WKWebExtensionControllerDelegate { "urls=\(configuration.tabURLs.count) focused=\(configuration.shouldBeFocused ? 1 : 0)" ) #endif + guard !configuration.shouldBePrivate else { + completionHandler(nil, openTabsUnsupportedError()) + return + } guard configuration.windowType == .popup else { guard configuration.windowType == .normal, - let window = openNormalBrowserWindow(using: configuration) else { + let window = openNormalBrowserWindow(using: configuration, for: extensionContext) else { completionHandler(nil, openTabsUnsupportedError()) return } completionHandler(window, nil) return } - guard configuration.tabURLs.allSatisfy(canOpenExtensionRequestedBrowserURL) else { + guard configuration.tabURLs.allSatisfy({ canOpenExtensionPopupURL($0, for: extensionContext) }) else { completionHandler(nil, openTabsUnsupportedError()) return } @@ -65,7 +69,8 @@ extension BrowserWebExtensionSupport: WKWebExtensionControllerDelegate { } private func openNormalBrowserWindow( - using configuration: WKWebExtension.WindowConfiguration + using configuration: WKWebExtension.WindowConfiguration, + for extensionContext: WKWebExtensionContext ) -> (any WKWebExtensionWindow)? { guard !configuration.tabURLs.isEmpty else { guard configuration.tabs.isEmpty else { @@ -78,18 +83,46 @@ extension BrowserWebExtensionSupport: WKWebExtensionControllerDelegate { ).map { _ in windowAdapter } } - for (index, url) in configuration.tabURLs.enumerated() { - guard canOpenExtensionRequestedBrowserURL(url) else { return nil } + guard activeTabAdapter?.panel != nil else { return nil } + let requestedTabs = configuration.tabURLs.map { url in + (url: url, webViewConfiguration: webViewConfigurationForExtensionRequestedBrowserURL(url, for: extensionContext)) + } + guard requestedTabs.allSatisfy({ canOpenExtensionRequestedBrowserURL($0.url, for: extensionContext) }) else { + return nil + } + + var openedPanels: [BrowserPanel] = [] + for (index, requestedTab) in requestedTabs.enumerated() { let shouldActivate = configuration.shouldBeFocused && index == 0 - guard openBrowserTab( - url: url, + guard let adapter = openBrowserTab( + url: requestedTab.url, shouldActivate: shouldActivate, - webViewConfiguration: webViewConfigurationForExtensionRequestedBrowserURL(url) - ) != nil else { return nil } + webViewConfiguration: requestedTab.webViewConfiguration + ), let panel = adapter.panel else { + openedPanels.reversed().forEach(closeOpenedBrowserTab) + return nil + } + openedPanels.append(panel) } return windowAdapter } + private func closeOpenedBrowserTab(_ panel: BrowserPanel) { + if let workspace = AppDelegate.shared?.workspaceContainingPanel( + panelId: panel.id, + preferredWorkspaceId: panel.workspaceId + )?.workspace { + _ = workspace.closePanel(panel.id, force: true) + return + } + guard let dock = dockContainingPanel(panel.id), + let tabId = dock.surfaceId(forPanelId: panel.id) else { return } + dock.forceCloseDockTabIds.insert(tabId) + if !dock.bonsplitController.closeTab(tabId) { + dock.forceCloseDockTabIds.remove(tabId) + } + } + func webExtensionController( _ controller: WKWebExtensionController, openNewTabUsing configuration: WKWebExtension.TabConfiguration, @@ -100,7 +133,7 @@ extension BrowserWebExtensionSupport: WKWebExtensionControllerDelegate { cmuxDebugLog("browser.webext.openTab url=\(configuration.url?.absoluteString.prefix(80) ?? "nil")") #endif if let url = configuration.url, - !canOpenExtensionRequestedBrowserURL(url) { + !canOpenExtensionRequestedBrowserURL(url, for: extensionContext) { completionHandler(nil, openTabsUnsupportedError()) return } @@ -108,7 +141,7 @@ extension BrowserWebExtensionSupport: WKWebExtensionControllerDelegate { guard let adapter = openBrowserTab( url: configuration.url, shouldActivate: configuration.shouldBeActive, - webViewConfiguration: configuration.url.flatMap(webViewConfigurationForExtensionRequestedBrowserURL) + webViewConfiguration: configuration.url.flatMap { webViewConfigurationForExtensionRequestedBrowserURL($0, for: extensionContext) } ) else { completionHandler(nil, openTabsUnsupportedError()) return @@ -209,12 +242,19 @@ extension BrowserWebExtensionSupport: WKWebExtensionControllerDelegate { DockSplitStore.liveStores.first { $0.containsPanel(panelID) } } - func canOpenExtensionRequestedBrowserURL(_ url: URL) -> Bool { - canOpenInRegularBrowserTab(url) || controller.extensionContext(for: url) != nil + func canOpenExtensionRequestedBrowserURL(_ url: URL, for extensionContext: WKWebExtensionContext) -> Bool { + canOpenInRegularBrowserTab(url) || controller.extensionContext(for: url) === extensionContext + } + + func canOpenExtensionPopupURL(_ url: URL, for extensionContext: WKWebExtensionContext) -> Bool { + // Standalone popout WKWebViews bypass BrowserPanel navigation policy, so + // only extension-owned pages may load here. + controller.extensionContext(for: url) === extensionContext } - func webViewConfigurationForExtensionRequestedBrowserURL(_ url: URL) -> WKWebViewConfiguration? { - webViewConfiguration(forNavigatingTo: url)?.webViewConfiguration + func webViewConfigurationForExtensionRequestedBrowserURL(_ url: URL, for extensionContext: WKWebExtensionContext) -> WKWebViewConfiguration? { + guard controller.extensionContext(for: url) === extensionContext else { return nil } + return extensionContext.webViewConfiguration } private func canOpenInRegularBrowserTab(_ url: URL) -> Bool { @@ -238,7 +278,7 @@ extension BrowserWebExtensionSupport: WKWebExtensionControllerDelegate { didUpdate action: WKWebExtension.Action, forExtensionContext context: WKWebExtensionContext ) { - refreshActionSnapshot(for: context) + refreshActionSnapshot(for: action, context: context) } func webExtensionController( diff --git a/Sources/Panels/BrowserWebExtensionTabAdapter.swift b/Sources/Panels/BrowserWebExtensionTabAdapter.swift index db5aa78a2b13..c9c01e4aa223 100644 --- a/Sources/Panels/BrowserWebExtensionTabAdapter.swift +++ b/Sources/Panels/BrowserWebExtensionTabAdapter.swift @@ -62,13 +62,13 @@ final class BrowserWebExtensionTabAdapter: NSObject, WKWebExtensionTab { func loadURL(_ url: URL, for context: WKWebExtensionContext, completionHandler: @escaping (Error?) -> Void) { guard let panel, let support, - support.canOpenExtensionRequestedBrowserURL(url) else { + support.canOpenExtensionRequestedBrowserURL(url, for: context) else { completionHandler(webExtensionTabError(code: 4)) return } panel.navigateFromWebExtension( to: url, - webViewConfiguration: support.webViewConfigurationForExtensionRequestedBrowserURL(url) + webViewConfiguration: support.webViewConfigurationForExtensionRequestedBrowserURL(url, for: context) ) completionHandler(nil) } diff --git a/Sources/Workspace.swift b/Sources/Workspace.swift index ca144ffeabc4..423e550ca67f 100644 --- a/Sources/Workspace.swift +++ b/Sources/Workspace.swift @@ -3536,7 +3536,6 @@ final class Workspace: Identifiable, ObservableObject { } private func configureBrowserPanel(_ browserPanel: BrowserPanel) { - browserPanel.registerWebExtensionIfNeeded() browserPanel.webViewDidRequestClose = { [weak self, weak browserPanel] in guard let self, let browserPanel else { return } guard self.panels[browserPanel.id] is BrowserPanel else { return } @@ -3590,6 +3589,10 @@ final class Workspace: Identifiable, ObservableObject { } private func installBrowserPanelSubscription(_ browserPanel: BrowserPanel) { + browserPanel.registerWebExtensionIfNeeded() + if focusedPanelId == browserPanel.id { + browserPanel.noteWebExtensionActivated() + } let browserTabState = Publishers.CombineLatest4( browserPanel.$pageTitle.removeDuplicates(), browserPanel.$currentURL.removeDuplicates(), browserPanel.$isLoading.removeDuplicates(), browserPanel.$faviconPNGData.removeDuplicates(by: { $0 == $1 }) @@ -11636,6 +11639,9 @@ extension Workspace: BonsplitDelegate { guard let panel = panels[effectiveFocusedPanelId] else { return } + if let browserPanel = panel as? BrowserPanel { + browserPanel.noteWebExtensionActivated() + } if debugStressPreloadSelectionDepth > 0 { if let terminalPanel = panel as? TerminalPanel { diff --git a/cmuxTests/BrowserWebExtensionSupportTests.swift b/cmuxTests/BrowserWebExtensionSupportTests.swift index c47d76a74b9f..2cb5e3a0c9ad 100644 --- a/cmuxTests/BrowserWebExtensionSupportTests.swift +++ b/cmuxTests/BrowserWebExtensionSupportTests.swift @@ -1,6 +1,8 @@ +import AppKit import CmuxSettings import Foundation import Testing +import WebKit #if canImport(cmux_DEV) @testable import cmux_DEV @@ -175,9 +177,78 @@ struct BrowserWebExtensionSupportTests { ) #expect(plan.unloadEntryIDs == ["com.bitwarden.desktop.safari"]) + #expect(plan.unloadEntries == [ + BrowserWebExtensionReconciliationPlanner.UnloadEntry( + id: "com.bitwarden.desktop.safari", + preservePermissionState: false + ), + ]) #expect(plan.loadEntries.map(\.path) == [newPath]) } + @Test + func reconciliationPreservesPermissionStateWhenConfiguredEntryIsDisabled() { + let planner = BrowserWebExtensionReconciliationPlanner() + let appexPath = "/Applications/Bitwarden.app/Contents/PlugIns/safari.appex" + let resourcePath = BrowserWebExtensionReconciliationPlanner.standardizedResourceRootPath( + for: BrowserWebExtensionEntry( + id: "com.bitwarden.desktop.safari", + kind: .safariAppExtension, + path: appexPath, + enabled: true + ) + ) + let plan = planner.plan( + settingsEntries: [ + BrowserWebExtensionEntry( + id: "com.bitwarden.desktop.safari", + kind: .safariAppExtension, + path: appexPath, + enabled: false + ), + ], + environmentPaths: [], + loadedEntries: [ + BrowserWebExtensionReconciliationPlanner.LoadedEntry( + id: "com.bitwarden.desktop.safari", + standardizedPath: resourcePath + ), + ] + ) + + #expect(plan.unloadEntries == [ + BrowserWebExtensionReconciliationPlanner.UnloadEntry( + id: "com.bitwarden.desktop.safari", + preservePermissionState: true + ), + ]) + #expect(plan.loadEntries.isEmpty) + } + + @MainActor + @Test + func pageInitiatedExtensionNavigationPolicyDistinguishesContextEntryAndExit() throws { + let extensionURL = try #require(URL(string: "webkit-extension://cmux-test/options.html")) + let normalURL = try #require(URL(string: "https://example.com/")) + let unknownExtensionURL = try #require(URL(string: "webkit-extension://other-extension/options.html")) + let fileURL = URL(fileURLWithPath: "/tmp/cmux-extension-test.txt") + let host = BrowserWebExtensionNavigationPolicyTestHost(extensionHost: extensionURL.host) + let panel = BrowserPanel( + workspaceId: UUID(), + initialURL: extensionURL, + renderInitialNavigation: false, + browserWebExtensionHost: host + ) + defer { panel.close() } + + #expect(!panel.shouldBlockPageInitiatedWebExtensionNavigation(to: extensionURL)) + #expect(panel.shouldBlockPageInitiatedWebExtensionNavigation(to: unknownExtensionURL)) + #expect(panel.shouldBlockPageInitiatedWebExtensionNavigation(to: fileURL)) + #expect(!panel.shouldRoutePageInitiatedWebExtensionNavigationInCurrentTab(to: extensionURL)) + #expect(panel.shouldRoutePageInitiatedWebExtensionNavigationInCurrentTab(to: normalURL)) + #expect(!panel.shouldRoutePageInitiatedWebExtensionNavigationInCurrentTab(to: fileURL)) + } + @Test @available(macOS 15.4, *) func permissionStateStorePersistsEntryStatesIndependently() throws { @@ -212,6 +283,40 @@ struct BrowserWebExtensionSupportTests { #expect(store.state(for: "missing") == nil) } + @Test + @available(macOS 15.4, *) + func permissionStateStoreRemovesOnlyTargetEntry() throws { + let suiteName = "cmux-web-extension-permission-removal-\(UUID().uuidString)" + let defaults = try #require(UserDefaults(suiteName: suiteName)) + defer { defaults.removePersistentDomain(forName: suiteName) } + + let store = BrowserWebExtensionPermissionStateStore(defaults: defaults) + let expiration = Date(timeIntervalSince1970: 1_800_000_000) + let firstState = BrowserWebExtensionPermissionState( + grantedPermissions: ["tabs": expiration], + deniedPermissions: [:], + grantedPermissionMatchPatterns: [:], + deniedPermissionMatchPatterns: [:], + hasRequestedOptionalAccessToAllHosts: false, + hasAccessToPrivateData: false + ) + let secondState = BrowserWebExtensionPermissionState( + grantedPermissions: ["storage": expiration], + deniedPermissions: [:], + grantedPermissionMatchPatterns: [:], + deniedPermissionMatchPatterns: [:], + hasRequestedOptionalAccessToAllHosts: false, + hasAccessToPrivateData: false + ) + + store.save(firstState, for: "com.example.first") + store.save(secondState, for: "com.example.second") + store.removeState(for: "com.example.first") + + #expect(store.state(for: "com.example.first") == nil) + #expect(store.state(for: "com.example.second") == secondState) + } + @Test func pluginkitParserHandlesVerboseSpaceSeparatedOutput() { let output = """ @@ -231,3 +336,35 @@ struct BrowserWebExtensionSupportTests { #expect(candidates.last?.path == "/Applications/Example App.app/Contents/PlugIns/Example Extension.appex") } } + +@MainActor +private final class BrowserWebExtensionNavigationPolicyTestHost: BrowserWebExtensionHosting { + private let extensionHost: String? + private let contextToken = NSObject() + private let configuration = WKWebViewConfiguration() + + init(extensionHost: String?) { + self.extensionHost = extensionHost + } + + func attach(to configuration: WKWebViewConfiguration) {} + + func webViewConfiguration(forNavigatingTo url: URL) -> BrowserWebExtensionNavigationConfiguration? { + guard url.scheme?.lowercased() == "webkit-extension", + url.host == extensionHost else { return nil } + return BrowserWebExtensionNavigationConfiguration( + contextIdentifier: ObjectIdentifier(contextToken), + webViewConfiguration: configuration + ) + } + + func register(panel: BrowserPanel) {} + + func unregister(panelID: UUID) {} + + func noteActivated(panelID: UUID) {} + + func noteTabMetadataChanged(panelID: UUID) {} + + func performCommand(for event: NSEvent) -> Bool { false } +} From 2d678da6529db806563efcfe853f67fdbf45f57f Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 11:26:22 -0700 Subject: [PATCH 31/51] test(browser): cover extension review regressions --- .../JSONValueModelLifecycleTests.swift | 24 ++++++ .../BrowserWebExtensionSupportTests.swift | 85 +++++++++++++++++++ 2 files changed, 109 insertions(+) diff --git a/Packages/macOS/CmuxSettingsUI/Tests/CmuxSettingsUITests/JSONValueModelLifecycleTests.swift b/Packages/macOS/CmuxSettingsUI/Tests/CmuxSettingsUITests/JSONValueModelLifecycleTests.swift index 223b7dfa47be..972f1cb8a5b2 100644 --- a/Packages/macOS/CmuxSettingsUI/Tests/CmuxSettingsUITests/JSONValueModelLifecycleTests.swift +++ b/Packages/macOS/CmuxSettingsUI/Tests/CmuxSettingsUITests/JSONValueModelLifecycleTests.swift @@ -112,4 +112,28 @@ import Testing #expect(model.current == "observed") #expect(model.hasObservedValue) } + + @Test func rapidWritesCompleteInRequestOrderAndKeepTheNewestValue() async { + let tempDir = FileManager.default.temporaryDirectory + .appendingPathComponent("json-value-model-ordered-writes-\(UUID().uuidString)", isDirectory: true) + defer { try? FileManager.default.removeItem(at: tempDir) } + + let store = JSONConfigStore(fileURL: tempDir.appendingPathComponent("cmux.json")) + let key = JSONKey(id: "automation.socketPassword", defaultValue: "") + let errorLog = SettingsErrorLog() + let model = JSONValueModel(store: store, key: key, errorLog: errorLog) + + let firstRequestID = model.set("first") + let secondRequestID = model.set("second") + + var spins = 0 + while model.writeResultRevision < 2, spins < 100_000 { + await Task.yield() + spins += 1 + } + + #expect(secondRequestID > firstRequestID) + #expect(model.lastCompletedWriteID == secondRequestID) + #expect(await store.value(for: key) == "second") + } } diff --git a/cmuxTests/BrowserWebExtensionSupportTests.swift b/cmuxTests/BrowserWebExtensionSupportTests.swift index 2cb5e3a0c9ad..b90ca5cc724b 100644 --- a/cmuxTests/BrowserWebExtensionSupportTests.swift +++ b/cmuxTests/BrowserWebExtensionSupportTests.swift @@ -12,6 +12,55 @@ import WebKit @Suite struct BrowserWebExtensionSupportTests { + @MainActor + @Test + @available(macOS 15.4, *) + func keyWindowSwitchRestoresThatWindowsActiveExtensionTab() { + let support = BrowserWebExtensionSupport() + let firstPanel = BrowserPanel( + workspaceId: UUID(), + initialURL: URL(string: "https://first.example"), + renderInitialNavigation: false, + browserWebExtensionHost: support + ) + let secondPanel = BrowserPanel( + workspaceId: UUID(), + initialURL: URL(string: "https://second.example"), + renderInitialNavigation: false, + browserWebExtensionHost: support + ) + let firstWindow = NSWindow( + contentRect: NSRect(x: 0, y: 0, width: 800, height: 600), + styleMask: [.titled], + backing: .buffered, + defer: false + ) + let secondWindow = NSWindow( + contentRect: NSRect(x: 0, y: 0, width: 800, height: 600), + styleMask: [.titled], + backing: .buffered, + defer: false + ) + firstWindow.contentView = firstPanel.webView + secondWindow.contentView = secondPanel.webView + defer { + firstPanel.close() + secondPanel.close() + firstWindow.close() + secondWindow.close() + } + + support.register(panel: firstPanel) + support.register(panel: secondPanel) + support.noteActivated(panelID: firstPanel.id) + support.noteActivated(panelID: secondPanel.id) + #expect(support.activePanelID == secondPanel.id) + + support.noteWindowBecameKey(firstWindow) + + #expect(support.activePanelID == firstPanel.id) + } + @Test func reconciliationSkipsEnvPathWhenSettingsEntryIsDisabled() { let planner = BrowserWebExtensionReconciliationPlanner() @@ -225,6 +274,25 @@ struct BrowserWebExtensionSupportTests { #expect(plan.loadEntries.isEmpty) } + @Test + func failedUnloadRollbackRestoresTheLoadedEntryAsEnabled() { + let planner = BrowserWebExtensionReconciliationPlanner() + let loadedEntry = BrowserWebExtensionEntry( + id: "com.example.extension", + kind: .safariAppExtension, + path: "/Applications/Example.app/Contents/PlugIns/Example.appex", + enabled: true, + displayName: "Example" + ) + + let restored = planner.rollbackEntriesAfterFailedUnloads( + settingsEntries: [], + failedEntries: [loadedEntry] + ) + + #expect(restored == [loadedEntry]) + } + @MainActor @Test func pageInitiatedExtensionNavigationPolicyDistinguishesContextEntryAndExit() throws { @@ -249,6 +317,23 @@ struct BrowserWebExtensionSupportTests { #expect(!panel.shouldRoutePageInitiatedWebExtensionNavigationInCurrentTab(to: fileURL)) } + @MainActor + @Test + func extensionExitPreservesNilTargetNewTabIntent() { + let delegate = BrowserNavigationDelegate() + + #expect(!delegate.shouldRouteWebExtensionNavigationAsCurrentTab( + targetFrameIsMainFrame: nil, + shouldOpenInNewTab: false, + navigationType: .linkActivated + )) + #expect(delegate.shouldRouteWebExtensionNavigationAsCurrentTab( + targetFrameIsMainFrame: true, + shouldOpenInNewTab: false, + navigationType: .linkActivated + )) + } + @Test @available(macOS 15.4, *) func permissionStateStorePersistsEntryStatesIndependently() throws { From 7c9c45538b6759ec0e59f80fb9f610380e79ed82 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 11:46:15 -0700 Subject: [PATCH 32/51] fix(browser): address extension review findings --- .../Bindings/JSONValueModel.swift | 48 ++++++++++++---- .../Sections/BrowserWebExtensionsCard.swift | 14 +++-- .../Panels/BrowserNavigationDelegate.swift | 4 +- .../Panels/BrowserNavigationPopupPolicy.swift | 26 +++++++++ .../BrowserWebExtensionLoadedRecord.swift | 5 +- ...serWebExtensionReconciliationPlanner.swift | 27 +++++++++ .../BrowserWebExtensionSupport+Loading.swift | 54 ++++++++++++++++-- .../Panels/BrowserWebExtensionSupport.swift | 57 ++++++++++++++++++- 8 files changed, 209 insertions(+), 26 deletions(-) diff --git a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Bindings/JSONValueModel.swift b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Bindings/JSONValueModel.swift index 3c82c249c92e..59de16cd7e23 100644 --- a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Bindings/JSONValueModel.swift +++ b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Bindings/JSONValueModel.swift @@ -28,12 +28,16 @@ public final class JSONValueModel { /// Error from the most recent set/reset attempt, or `nil`. public private(set) var lastWriteError: Error? + /// Monotonic identifier of the most recently completed set/reset attempt. + public private(set) var lastCompletedWriteID: UInt64 = 0 private(set) var writeResultRevision = 0 private let store: JSONConfigStore private let key: JSONKey private let errorLog: SettingsErrorLog @ObservationIgnored private let makeStream: () -> AsyncStream + @ObservationIgnored private var nextWriteID: UInt64 = 0 + @ObservationIgnored private var writeTask: Task? /// Owns the change-stream subscription and cancels it when this model /// deallocates. @@ -102,47 +106,67 @@ public final class JSONValueModel { /// yields it back. On failure ``lastWriteError`` is populated and /// recorded in the error log. Synchronous because SwiftUI `Binding` /// setters can't `await`. - public func set(_ value: Value) { + @discardableResult + public func set(_ value: Value) -> UInt64 { let keyID = key.id - Task { [weak self, store, key] in + let requestID = makeWriteRequestID() + let previousWriteTask = writeTask + writeTask = Task { [weak self, store, key] in + await previousWriteTask?.value do { try await store.set(value, for: key) await MainActor.run { guard let self else { return } - self.lastWriteError = nil - self.writeResultRevision &+= 1 + self.finishWrite(requestID: requestID, error: nil) } } catch { await MainActor.run { guard let self else { return } - self.lastWriteError = error - self.writeResultRevision &+= 1 + self.finishWrite(requestID: requestID, error: error) self.errorLog.record(error, keyID: keyID) } } } + return requestID } /// Removes the JSON entry (parents that become empty are pruned). /// ``current`` updates when the stream observes the reset. - public func reset() { + @discardableResult + public func reset() -> UInt64 { let keyID = key.id - Task { [weak self, store, key] in + let requestID = makeWriteRequestID() + let previousWriteTask = writeTask + writeTask = Task { [weak self, store, key] in + await previousWriteTask?.value do { try await store.reset(key) await MainActor.run { guard let self else { return } - self.lastWriteError = nil - self.writeResultRevision &+= 1 + self.finishWrite(requestID: requestID, error: nil) } } catch { await MainActor.run { guard let self else { return } - self.lastWriteError = error - self.writeResultRevision &+= 1 + self.finishWrite(requestID: requestID, error: error) self.errorLog.record(error, keyID: keyID) } } } + return requestID + } + + private func makeWriteRequestID() -> UInt64 { + nextWriteID &+= 1 + return nextWriteID + } + + private func finishWrite(requestID: UInt64, error: Error?) { + lastCompletedWriteID = requestID + lastWriteError = error + writeResultRevision &+= 1 + if requestID == nextWriteID { + writeTask = nil + } } } diff --git a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift index 36526ccdfc20..464aae16f62f 100644 --- a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift +++ b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift @@ -17,6 +17,7 @@ struct BrowserWebExtensionsCard: View { @State private var discovered: [SettingsDiscoveredBrowserExtension] = [] @State private var pendingEntries: [BrowserWebExtensionEntry]? + @State private var pendingWriteID: UInt64? var body: some View { let entries = effectiveEntries @@ -38,13 +39,16 @@ struct BrowserWebExtensionsCard: View { model.startObserving() discovered = await hostActions.discoverBrowserWebExtensions() } - .onChange(of: model.current) { _, _ in + .onChange(of: model.current) { _, current in + guard let expectedEntries = pendingEntries, current == expectedEntries else { return } pendingEntries = nil + pendingWriteID = nil } .onChange(of: model.writeResultRevision) { _, _ in - if model.lastWriteError != nil { - pendingEntries = nil - } + guard model.lastCompletedWriteID == pendingWriteID, + model.lastWriteError != nil else { return } + pendingEntries = nil + pendingWriteID = nil } } @@ -210,7 +214,7 @@ struct BrowserWebExtensionsCard: View { private func commitEntries(_ entries: [BrowserWebExtensionEntry]) { pendingEntries = entries - model.set(entries) + pendingWriteID = model.set(entries) } private func importSafariExtension(_ candidate: SettingsDiscoveredBrowserExtension) { diff --git a/Sources/Panels/BrowserNavigationDelegate.swift b/Sources/Panels/BrowserNavigationDelegate.swift index fd49d0f3206e..b1eb76d263fe 100644 --- a/Sources/Panels/BrowserNavigationDelegate.swift +++ b/Sources/Panels/BrowserNavigationDelegate.swift @@ -355,8 +355,8 @@ import WebKit } if let url = navigationAction.request.url, - navigationAction.targetFrame?.isMainFrame != false, - shouldRouteWebExtensionNavigationInCurrentTab?(url) == true { + shouldRouteWebExtensionNavigationInCurrentTab?(url) == true, + shouldRouteWebExtensionNavigationAsCurrentTab(navigationAction, shouldOpenInNewTab: shouldOpenInNewTab) { clearAttemptedRequest(discardPendingBypasses: true) requestNavigation?(navigationAction.request, .currentTab) decisionHandler(.cancel); return diff --git a/Sources/Panels/BrowserNavigationPopupPolicy.swift b/Sources/Panels/BrowserNavigationPopupPolicy.swift index e5d491a475c0..9fdc5d3d3f2e 100644 --- a/Sources/Panels/BrowserNavigationPopupPolicy.swift +++ b/Sources/Panels/BrowserNavigationPopupPolicy.swift @@ -63,6 +63,32 @@ func browserNavigationShouldFallbackNilTargetToNewTab( navigationType != .other } +extension BrowserNavigationDelegate { + func shouldRouteWebExtensionNavigationAsCurrentTab( + targetFrameIsMainFrame: Bool?, + shouldOpenInNewTab: Bool, + navigationType: WKNavigationType + ) -> Bool { + guard targetFrameIsMainFrame != false, !shouldOpenInNewTab else { return false } + if targetFrameIsMainFrame == nil, + browserNavigationShouldFallbackNilTargetToNewTab(navigationType: navigationType) { + return false + } + return true + } + + func shouldRouteWebExtensionNavigationAsCurrentTab( + _ navigationAction: WKNavigationAction, + shouldOpenInNewTab: Bool + ) -> Bool { + shouldRouteWebExtensionNavigationAsCurrentTab( + targetFrameIsMainFrame: navigationAction.targetFrame?.isMainFrame, + shouldOpenInNewTab: shouldOpenInNewTab, + navigationType: navigationAction.navigationType + ) + } +} + func browserNavigationHasSimpleUserActivation( currentEventType: NSEvent.EventType? = NSApp.currentEvent?.type ) -> Bool { diff --git a/Sources/Panels/BrowserWebExtensionLoadedRecord.swift b/Sources/Panels/BrowserWebExtensionLoadedRecord.swift index 86f98d90ca29..bc2c2fd900d6 100644 --- a/Sources/Panels/BrowserWebExtensionLoadedRecord.swift +++ b/Sources/Panels/BrowserWebExtensionLoadedRecord.swift @@ -1,8 +1,11 @@ +import CmuxSettings import WebKit @available(macOS 15.4, *) struct BrowserWebExtensionLoadedRecord { - let entryID: String + let entry: BrowserWebExtensionEntry let standardizedPath: String let context: WKWebExtensionContext + + var entryID: String { entry.id } } diff --git a/Sources/Panels/BrowserWebExtensionReconciliationPlanner.swift b/Sources/Panels/BrowserWebExtensionReconciliationPlanner.swift index ff27b6c7ff34..3f119f1a560e 100644 --- a/Sources/Panels/BrowserWebExtensionReconciliationPlanner.swift +++ b/Sources/Panels/BrowserWebExtensionReconciliationPlanner.swift @@ -60,6 +60,33 @@ struct BrowserWebExtensionReconciliationPlanner { ) } + func rollbackEntriesAfterFailedUnloads( + settingsEntries: [BrowserWebExtensionEntry], + failedEntries: [BrowserWebExtensionEntry] + ) -> [BrowserWebExtensionEntry] { + var restoredEntries = settingsEntries + + for failedEntry in failedEntries { + var restoredEntry = failedEntry + restoredEntry.enabled = true + let failedResourceRoot = Self.standardizedResourceRootPath(for: restoredEntry) + + for index in restoredEntries.indices + where restoredEntries[index].id != restoredEntry.id + && Self.standardizedResourceRootPath(for: restoredEntries[index]) == failedResourceRoot { + restoredEntries[index].enabled = false + } + + if let existingIndex = restoredEntries.firstIndex(where: { $0.id == restoredEntry.id }) { + restoredEntries[existingIndex] = restoredEntry + } else { + restoredEntries.append(restoredEntry) + } + } + + return restoredEntries + } + static func standardizedPath(_ path: String) -> String { BrowserWebExtensionEntry.standardizedPath(path) } diff --git a/Sources/Panels/BrowserWebExtensionSupport+Loading.swift b/Sources/Panels/BrowserWebExtensionSupport+Loading.swift index 5a72c7654ec2..9b95609f17c6 100644 --- a/Sources/Panels/BrowserWebExtensionSupport+Loading.swift +++ b/Sources/Panels/BrowserWebExtensionSupport+Loading.swift @@ -27,8 +27,24 @@ extension BrowserWebExtensionSupport { } ) + var failedUnloadEntries: [BrowserWebExtensionEntry] = [] for entry in plan.unloadEntries { - unload(entryID: entry.id, preservePermissionState: entry.preservePermissionState) + if let failedEntry = unload( + entryID: entry.id, + preservePermissionState: entry.preservePermissionState + ) { + failedUnloadEntries.append(failedEntry) + } + } + + if !failedUnloadEntries.isEmpty { + guard canApplyWebExtensionLoad(generation: generation) else { return } + await rollbackSettingsAfterFailedUnloads( + failedEntries: failedUnloadEntries, + planner: planner + ) + rebuildActionSnapshots() + return } guard canApplyWebExtensionLoad(generation: generation) else { return } @@ -112,8 +128,12 @@ extension BrowserWebExtensionSupport { ) } - private func unload(entryID: String, preservePermissionState: Bool = true) { - guard let record = loadedByEntryID[entryID] else { return } + @discardableResult + private func unload( + entryID: String, + preservePermissionState: Bool = true + ) -> BrowserWebExtensionEntry? { + guard let record = loadedByEntryID[entryID] else { return nil } if preservePermissionState { persistPermissionState(entryID: entryID, context: record.context) } @@ -124,7 +144,7 @@ extension BrowserWebExtensionSupport { #if DEBUG cmuxDebugLog("browser.webext.unloadFailed id=\(entryID) error=\(error.localizedDescription)") #endif - return + return record.entry } removePermissionStateObservers(entryID: entryID) @@ -143,6 +163,7 @@ extension BrowserWebExtensionSupport { #if DEBUG cmuxDebugLog("browser.webext.unloaded id=\(entryID)") #endif + return nil } func unloadAllWebExtensions() { @@ -161,7 +182,7 @@ extension BrowserWebExtensionSupport { let standardizedPath = BrowserWebExtensionReconciliationPlanner.standardizedResourceRootPath(for: entry) let context = try load(webExtension, entryID: entry.id, standardizedPath: standardizedPath) loadedByEntryID[entry.id] = BrowserWebExtensionLoadedRecord( - entryID: entry.id, + entry: entry, standardizedPath: standardizedPath, context: context ) @@ -185,6 +206,29 @@ extension BrowserWebExtensionSupport { } } + private func rollbackSettingsAfterFailedUnloads( + failedEntries: [BrowserWebExtensionEntry], + planner: BrowserWebExtensionReconciliationPlanner + ) async { + guard let settingsStore, let settingsKey else { return } + let settingsEntries = await settingsStore.value(for: settingsKey) + let restoredEntries = planner.rollbackEntriesAfterFailedUnloads( + settingsEntries: settingsEntries, + failedEntries: failedEntries + ) + guard restoredEntries != settingsEntries else { return } + do { + try await settingsStore.set(restoredEntries, for: settingsKey) + } catch { + for entry in failedEntries { + recordLoadError(error.localizedDescription, entryID: entry.id) + } +#if DEBUG + cmuxDebugLog("browser.webext.rollbackSettingsFailed error=\(error.localizedDescription)") +#endif + } + } + private func makeWebExtension(for entry: BrowserWebExtensionEntry) async throws -> WKWebExtension { let url = URL(fileURLWithPath: entry.path) if entry.kind == .safariAppExtension, url.pathExtension == "appex" { diff --git a/Sources/Panels/BrowserWebExtensionSupport.swift b/Sources/Panels/BrowserWebExtensionSupport.swift index 4a316dc73b9f..bb4e96d5fc36 100644 --- a/Sources/Panels/BrowserWebExtensionSupport.swift +++ b/Sources/Panels/BrowserWebExtensionSupport.swift @@ -36,8 +36,14 @@ final class BrowserWebExtensionSupport: NSObject, BrowserWebExtensionHosting { @ObservationIgnored var settingsLoadGeneration = 0 @ObservationIgnored + var settingsStore: JSONConfigStore? + @ObservationIgnored + var settingsKey: JSONKey<[BrowserWebExtensionEntry]>? + @ObservationIgnored var browserAvailabilityObserverToken: NSObjectProtocol? @ObservationIgnored + var windowFocusObserverToken: NSObjectProtocol? + @ObservationIgnored var loadedByEntryID: [String: BrowserWebExtensionLoadedRecord] = [:] @ObservationIgnored var loadedEntryIDsInOrder: [String] = [] @@ -54,6 +60,8 @@ final class BrowserWebExtensionSupport: NSObject, BrowserWebExtensionHosting { @ObservationIgnored private(set) var activePanelID: UUID? @ObservationIgnored + private var activePanelIDsByWindow: [ObjectIdentifier: UUID] = [:] + @ObservationIgnored private(set) lazy var windowAdapter = BrowserWebExtensionWindowAdapter(support: self) @ObservationIgnored var popouts: [BrowserWebExtensionPopoutWindowController] = [] @@ -75,6 +83,17 @@ final class BrowserWebExtensionSupport: NSObject, BrowserWebExtensionHosting { controller = WKWebExtensionController(configuration: configuration) super.init() controller.delegate = self + windowFocusObserverToken = NotificationCenter.default.addObserver( + forName: NSWindow.didBecomeKeyNotification, + object: nil, + queue: .main + ) { [weak self] notification in + guard let window = notification.object as? NSWindow else { return } + Task { @MainActor [weak self, weak window] in + guard let window else { return } + self?.noteWindowBecameKey(window) + } + } } deinit { @@ -82,6 +101,9 @@ final class BrowserWebExtensionSupport: NSObject, BrowserWebExtensionHosting { if let browserAvailabilityObserverToken { NotificationCenter.default.removeObserver(browserAvailabilityObserverToken) } + if let windowFocusObserverToken { + NotificationCenter.default.removeObserver(windowFocusObserverToken) + } // Permission-state observer tokens need no explicit removal here: the // block-based NotificationCenter tokens auto-unregister when they // deallocate, which happens as the dictionaries holding them release @@ -114,6 +136,8 @@ final class BrowserWebExtensionSupport: NSObject, BrowserWebExtensionHosting { /// Called once from app startup so extensions begin loading before the /// first browser page navigates. func configure(jsonStore: JSONConfigStore, catalog: SettingCatalog) { + settingsStore = jsonStore + settingsKey = catalog.browser.webExtensions guard browserAvailabilityObserverToken == nil else { return } let key = catalog.browser.webExtensions browserAvailabilityObserverToken = NotificationCenter.default.addObserver( @@ -174,12 +198,14 @@ final class BrowserWebExtensionSupport: NSObject, BrowserWebExtensionHosting { actionSnapshotInvalidationsByPanelID[panel.id] = BrowserWebExtensionActionSnapshotInvalidation() orderedPanelIDs.append(panel.id) if activePanelID == nil { activePanelID = panel.id } + rememberActivePanel(panel.id) controller.didOpenTab(adapter) } func unregister(panelID: UUID) { guard let adapter = tabAdapters.removeValue(forKey: panelID) else { return } orderedPanelIDs.removeAll { $0 == panelID } + activePanelIDsByWindow = activePanelIDsByWindow.filter { $0.value != panelID } actionSnapshotInvalidationsByPanelID.removeValue(forKey: panelID) controller.didCloseTab(adapter, windowIsClosing: false) if activePanelID == panelID { @@ -194,7 +220,9 @@ final class BrowserWebExtensionSupport: NSObject, BrowserWebExtensionHosting { } func noteActivated(panelID: UUID) { - guard tabAdapters[panelID] != nil, activePanelID != panelID else { return } + guard tabAdapters[panelID] != nil else { return } + rememberActivePanel(panelID) + guard activePanelID != panelID else { return } let previousPanelID = activePanelID let previous = previousPanelID.flatMap { tabAdapters[$0] } activePanelID = panelID @@ -205,6 +233,33 @@ final class BrowserWebExtensionSupport: NSObject, BrowserWebExtensionHosting { refreshActionSnapshots(for: panelID) } + func noteWindowBecameKey(_ window: NSWindow) { + guard let panelID = activePanelID(in: window) else { return } + noteActivated(panelID: panelID) + controller.didFocusWindow(windowAdapter) + } + + private func rememberActivePanel(_ panelID: UUID) { + guard let window = tabAdapters[panelID]?.panel?.webView.window else { return } + activePanelIDsByWindow[ObjectIdentifier(window)] = panelID + } + + private func activePanelID(in window: NSWindow) -> UUID? { + let windowID = ObjectIdentifier(window) + if let rememberedPanelID = activePanelIDsByWindow[windowID], + tabAdapters[rememberedPanelID]?.panel?.webView.window === window { + return rememberedPanelID + } + guard let fallbackPanelID = orderedPanelIDs.reversed().first(where: { + tabAdapters[$0]?.panel?.webView.window === window + }) else { + activePanelIDsByWindow.removeValue(forKey: windowID) + return nil + } + activePanelIDsByWindow[windowID] = fallbackPanelID + return fallbackPanelID + } + func noteTabMetadataChanged(panelID: UUID) { guard let adapter = tabAdapters[panelID] else { return } controller.didChangeTabProperties([.title, .URL, .loading, .muted], for: adapter) From 9c10d76c52f99d2f02aef5a5934128531cf50702 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 12:05:25 -0700 Subject: [PATCH 33/51] test(browser): cover remaining extension review regressions --- .../BrowserWebExtensionSupportTests.swift | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/cmuxTests/BrowserWebExtensionSupportTests.swift b/cmuxTests/BrowserWebExtensionSupportTests.swift index b90ca5cc724b..6bfce62e0ccb 100644 --- a/cmuxTests/BrowserWebExtensionSupportTests.swift +++ b/cmuxTests/BrowserWebExtensionSupportTests.swift @@ -59,6 +59,9 @@ struct BrowserWebExtensionSupportTests { support.noteWindowBecameKey(firstWindow) #expect(support.activePanelID == firstPanel.id) + #expect((support.webExtensionWindow(for: firstWindow) as AnyObject?) === support.windowAdapter) + let unrelatedWindow = NSWindow() + #expect(support.webExtensionWindow(for: unrelatedWindow) == nil) } @Test @@ -327,6 +330,11 @@ struct BrowserWebExtensionSupportTests { shouldOpenInNewTab: false, navigationType: .linkActivated )) + #expect(!delegate.shouldRouteWebExtensionNavigationAsCurrentTab( + targetFrameIsMainFrame: nil, + shouldOpenInNewTab: false, + navigationType: .other + )) #expect(delegate.shouldRouteWebExtensionNavigationAsCurrentTab( targetFrameIsMainFrame: true, shouldOpenInNewTab: false, @@ -368,6 +376,29 @@ struct BrowserWebExtensionSupportTests { #expect(store.state(for: "missing") == nil) } + @Test + @available(macOS 15.4, *) + func permissionStateDoesNotCrossResourceIdentities() throws { + let suiteName = "cmux-web-extension-permission-identity-\(UUID().uuidString)" + let defaults = try #require(UserDefaults(suiteName: suiteName)) + defer { defaults.removePersistentDomain(forName: suiteName) } + + let store = BrowserWebExtensionPermissionStateStore(defaults: defaults) + let state = BrowserWebExtensionPermissionState( + grantedPermissions: ["tabs": Date(timeIntervalSince1970: 1_800_000_000)], + deniedPermissions: [:], + grantedPermissionMatchPatterns: [:], + deniedPermissionMatchPatterns: [:], + hasRequestedOptionalAccessToAllHosts: false, + hasAccessToPrivateData: false + ) + + store.save(state, for: "com.example.extension", standardizedPath: "/Extensions/Original") + + #expect(store.state(for: "com.example.extension", standardizedPath: "/Extensions/Original") == state) + #expect(store.state(for: "com.example.extension", standardizedPath: "/Extensions/Replacement") == nil) + } + @Test @available(macOS 15.4, *) func permissionStateStoreRemovesOnlyTargetEntry() throws { From 721d77264707321fbd608553d0503b166df9fb65 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 13:39:25 -0700 Subject: [PATCH 34/51] fix(browser): address remaining extension review findings --- .../Environment/SettingsHostActions.swift | 10 ++ .../Sections/BrowserWebExtensionsCard.swift | 24 +++- Resources/Localizable.xcstrings | 125 ++++++++++++++++++ Sources/HostSettingsActions.swift | 9 ++ .../Panels/BrowserNavigationPopupPolicy.swift | 9 +- ...wserWebExtensionPermissionStateStore.swift | 19 ++- .../BrowserWebExtensionSupport+Loading.swift | 45 +++++-- ...owserWebExtensionSupport+Permissions.swift | 34 +++-- ...ort+WKWebExtensionControllerDelegate.swift | 3 + .../Panels/BrowserWebExtensionSupport.swift | 22 ++- Sources/Panels/CmuxWebView.swift | 14 +- .../BrowserWebExtensionSupportTests.swift | 20 +-- 12 files changed, 279 insertions(+), 55 deletions(-) diff --git a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Environment/SettingsHostActions.swift b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Environment/SettingsHostActions.swift index ab6cc52904bb..8edf850bf71e 100644 --- a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Environment/SettingsHostActions.swift +++ b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Environment/SettingsHostActions.swift @@ -179,6 +179,9 @@ public protocol SettingsHostActions: AnyObject { /// Whether the host can load web extensions at all (requires macOS 15.4+). func browserWebExtensionsSupported() -> Bool + + /// A live map of configured extension IDs to host-side load failures. + func browserWebExtensionLoadErrorUpdates() -> AsyncStream<[String: String]> } public extension SettingsHostActions { @@ -197,6 +200,13 @@ public extension SettingsHostActions { /// Default: unsupported, for previews/tests with no live host. func browserWebExtensionsSupported() -> Bool { false } + /// Default: no host-side extension failures. + func browserWebExtensionLoadErrorUpdates() -> AsyncStream<[String: String]> { + AsyncStream { continuation in + continuation.yield([:]) + continuation.finish() + } + } func openMobilePairingWindow() {} /// Default no-op preview action for hosts without a Sleepy Mode overlay. diff --git a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift index 464aae16f62f..8222cf504d3f 100644 --- a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift +++ b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift @@ -16,6 +16,7 @@ struct BrowserWebExtensionsCard: View { let hostActions: SettingsHostActions @State private var discovered: [SettingsDiscoveredBrowserExtension] = [] + @State private var loadErrorsByEntryID: [String: String] = [:] @State private var pendingEntries: [BrowserWebExtensionEntry]? @State private var pendingWriteID: UInt64? @@ -39,6 +40,11 @@ struct BrowserWebExtensionsCard: View { model.startObserving() discovered = await hostActions.discoverBrowserWebExtensions() } + .task { + for await loadErrors in hostActions.browserWebExtensionLoadErrorUpdates() { + loadErrorsByEntryID = loadErrors + } + } .onChange(of: model.current) { _, current in guard let expectedEntries = pendingEntries, current == expectedEntries else { return } pendingEntries = nil @@ -73,7 +79,7 @@ struct BrowserWebExtensionsCard: View { } private var headerRow: some View { - SettingsCardRow( + return SettingsCardRow( configurationReview: .json("browser.webExtensions"), searchAnchorID: "setting:browser:web-extensions", String(localized: "settings.browser.webExtensions", defaultValue: "Extensions"), @@ -143,10 +149,22 @@ struct BrowserWebExtensionsCard: View { } private func entryRow(_ entry: BrowserWebExtensionEntry, isEnabled: Bool) -> some View { - SettingsCardRow( + let detail = entry.kind == .safariAppExtension ? entry.id : entry.path + let subtitle = if loadErrorsByEntryID[entry.id] == nil { + detail + } else { + String.localizedStringWithFormat( + String( + localized: "settings.browser.webExtensions.loadFailed.subtitle", + defaultValue: "%@ — Extension error. Disable and re-enable to retry, or remove it." + ), + detail + ) + } + return SettingsCardRow( configurationReview: .json("browser.webExtensions"), entry.displayName ?? (entry.path as NSString).lastPathComponent, - subtitle: entry.kind == .safariAppExtension ? entry.id : entry.path + subtitle: subtitle ) { HStack(spacing: 8) { Toggle("", isOn: Binding( diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index 2dc94b499295..965ff6ebc8a6 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -45813,6 +45813,131 @@ } } }, + "settings.browser.webExtensions.loadFailed.subtitle": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "%@ — خطأ في الامتداد. عطّله ثم فعّله مجددًا لإعادة المحاولة، أو أزله." + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "%@ — Greška proširenja. Onemogućite ga pa ponovo omogućite za novi pokušaj ili ga uklonite." + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "%@ — Fejl i udvidelsen. Deaktiver og aktiver igen for at prøve igen, eller fjern den." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "%@ — Erweiterungsfehler. Zum erneuten Versuch deaktivieren und wieder aktivieren oder entfernen." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "%@ — Extension error. Disable and re-enable to retry, or remove it." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "%@ — Error de la extensión. Desactívala y vuelve a activarla para reintentar, o elimínala." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "%@ — Erreur d’extension. Désactivez puis réactivez-la pour réessayer, ou supprimez-la." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "%@ — Errore dell’estensione. Disattiva e riattiva per riprovare oppure rimuovila." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "%@ — 拡張機能エラー。再試行するには無効にしてから再度有効にするか、削除してください。" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "%@ — 확장 프로그램 오류. 다시 시도하려면 비활성화했다가 다시 활성화하거나 제거하세요." + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "%@ — Feil i utvidelsen. Deaktiver og aktiver igjen for å prøve på nytt, eller fjern den." + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "%@ — Błąd rozszerzenia. Wyłącz i włącz ponownie, aby spróbować jeszcze raz, albo usuń." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "%@ — Erro na extensão. Desative e reative para tentar novamente ou remova." + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "%@ — Ошибка расширения. Отключите и снова включите, чтобы повторить попытку, или удалите." + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "%@ — ส่วนขยายเกิดข้อผิดพลาด ปิดแล้วเปิดใช้งานอีกครั้งเพื่อลองใหม่ หรือนำออก" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "%@ — Uzantı hatası. Yeniden denemek için devre dışı bırakıp tekrar etkinleştirin veya kaldırın." + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "%@ — Помилка розширення. Вимкніть і знову ввімкніть, щоб повторити спробу, або видаліть." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "%@ — 扩展错误。请停用后重新启用以重试,或将其移除。" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "%@ — 擴充功能錯誤。請停用後重新啟用以重試,或將其移除。" + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "%@ — កំហុសកម្មវិធីបន្ថែម។ បិទហើយបើកឡើងវិញដើម្បីសាកល្បងម្តងទៀត ឬដកវាចេញ។" + } + } + } + }, "settings.browser.webExtensions.remove": { "extractionState": "manual", "localizations": { diff --git a/Sources/HostSettingsActions.swift b/Sources/HostSettingsActions.swift index 6683d14cf4a0..948314527068 100644 --- a/Sources/HostSettingsActions.swift +++ b/Sources/HostSettingsActions.swift @@ -37,6 +37,15 @@ final class HostSettingsActions: SettingsHostActions { } } + func browserWebExtensionLoadErrorUpdates() -> AsyncStream<[String: String]> { + guard #available(macOS 15.4, *), + let support = AppDelegate.shared?.tabManager?.browserWebExtensionHost + as? BrowserWebExtensionSupport else { + return AsyncStream { $0.finish() } + } + return support.loadErrorUpdates() + } + /// Serializes font-size config writes so rapid slider saves persist in order. private let fontConfigWriter = FontConfigWriter() diff --git a/Sources/Panels/BrowserNavigationPopupPolicy.swift b/Sources/Panels/BrowserNavigationPopupPolicy.swift index 9fdc5d3d3f2e..5dc575bb0ac1 100644 --- a/Sources/Panels/BrowserNavigationPopupPolicy.swift +++ b/Sources/Panels/BrowserNavigationPopupPolicy.swift @@ -67,14 +67,9 @@ extension BrowserNavigationDelegate { func shouldRouteWebExtensionNavigationAsCurrentTab( targetFrameIsMainFrame: Bool?, shouldOpenInNewTab: Bool, - navigationType: WKNavigationType + navigationType _: WKNavigationType ) -> Bool { - guard targetFrameIsMainFrame != false, !shouldOpenInNewTab else { return false } - if targetFrameIsMainFrame == nil, - browserNavigationShouldFallbackNilTargetToNewTab(navigationType: navigationType) { - return false - } - return true + targetFrameIsMainFrame == true && !shouldOpenInNewTab } func shouldRouteWebExtensionNavigationAsCurrentTab( diff --git a/Sources/Panels/BrowserWebExtensionPermissionStateStore.swift b/Sources/Panels/BrowserWebExtensionPermissionStateStore.swift index 5b42fa0e74c2..abf2bb91755f 100644 --- a/Sources/Panels/BrowserWebExtensionPermissionStateStore.swift +++ b/Sources/Panels/BrowserWebExtensionPermissionStateStore.swift @@ -2,7 +2,7 @@ import Foundation @available(macOS 15.4, *) struct BrowserWebExtensionPermissionStateStore { - private static let storageKey = "browser.webExtensionPermissionStates.v1" + private static let storageKey = "browser.webExtensionPermissionStates.v2" private let defaults: UserDefaults @@ -10,22 +10,27 @@ struct BrowserWebExtensionPermissionStateStore { self.defaults = defaults } - func state(for entryID: String) -> BrowserWebExtensionPermissionState? { - allStates()[entryID] + func state(for entryID: String, standardizedPath: String) -> BrowserWebExtensionPermissionState? { + allStates()[storageIdentity(entryID: entryID, standardizedPath: standardizedPath)] } - func save(_ state: BrowserWebExtensionPermissionState, for entryID: String) { + func save(_ state: BrowserWebExtensionPermissionState, for entryID: String, standardizedPath: String) { var states = allStates() - states[entryID] = state + states[storageIdentity(entryID: entryID, standardizedPath: standardizedPath)] = state saveAllStates(states) } - func removeState(for entryID: String) { + func removeState(for entryID: String, standardizedPath: String) { var states = allStates() - guard states.removeValue(forKey: entryID) != nil else { return } + let identity = storageIdentity(entryID: entryID, standardizedPath: standardizedPath) + guard states.removeValue(forKey: identity) != nil else { return } saveAllStates(states) } + private func storageIdentity(entryID: String, standardizedPath: String) -> String { + "\(entryID)\n\(standardizedPath)" + } + private func allStates() -> [String: BrowserWebExtensionPermissionState] { guard let data = defaults.data(forKey: Self.storageKey), let states = try? PropertyListDecoder().decode( diff --git a/Sources/Panels/BrowserWebExtensionSupport+Loading.swift b/Sources/Panels/BrowserWebExtensionSupport+Loading.swift index 9b95609f17c6..d4e62c8c34a1 100644 --- a/Sources/Panels/BrowserWebExtensionSupport+Loading.swift +++ b/Sources/Panels/BrowserWebExtensionSupport+Loading.swift @@ -135,7 +135,11 @@ extension BrowserWebExtensionSupport { ) -> BrowserWebExtensionEntry? { guard let record = loadedByEntryID[entryID] else { return nil } if preservePermissionState { - persistPermissionState(entryID: entryID, context: record.context) + persistPermissionState( + entryID: entryID, + standardizedPath: record.standardizedPath, + context: record.context + ) } do { try controller.unload(record.context) @@ -149,7 +153,7 @@ extension BrowserWebExtensionSupport { removePermissionStateObservers(entryID: entryID) if !preservePermissionState { - removePermissionState(entryID: entryID) + removePermissionState(entryID: entryID, standardizedPath: record.standardizedPath) } loadedByEntryID[entryID] = nil loadedEntryIDsInOrder.removeAll { $0 == entryID } @@ -166,13 +170,31 @@ extension BrowserWebExtensionSupport { return nil } - func unloadAllWebExtensions() { + @discardableResult + func unloadAllWebExtensions() -> Bool { + var didUnloadEveryExtension = true for entryID in Array(loadedEntryIDsInOrder) { - unload(entryID: entryID) + if unload(entryID: entryID) != nil { + didUnloadEveryExtension = false + } } - loadErrorsByEntryID.removeAll() - refreshLoadErrors() rebuildActionSnapshots() + return didUnloadEveryExtension + } + + func loadErrorUpdates() -> AsyncStream<[String: String]> { + let id = UUID() + let (stream, continuation) = AsyncStream<[String: String]>.makeStream( + bufferingPolicy: .bufferingNewest(1) + ) + loadErrorUpdateContinuations[id] = continuation + continuation.yield(loadErrorsByEntryID) + continuation.onTermination = { [weak self] _ in + Task { @MainActor in + self?.loadErrorUpdateContinuations.removeValue(forKey: id) + } + } + return stream } private func load(entry: BrowserWebExtensionEntry, generation: Int) async { @@ -252,8 +274,12 @@ extension BrowserWebExtensionSupport { #if DEBUG context.isInspectable = true #endif - restorePermissionState(for: context, entryID: entryID) - installPermissionStateObservers(for: context, entryID: entryID) + restorePermissionState(for: context, entryID: entryID, standardizedPath: standardizedPath) + installPermissionStateObservers( + for: context, + entryID: entryID, + standardizedPath: standardizedPath + ) do { try controller.load(context) } catch { @@ -292,5 +318,8 @@ extension BrowserWebExtensionSupport { loadErrors = loadErrorsByEntryID .sorted { $0.key < $1.key } .map(\.value) + for continuation in loadErrorUpdateContinuations.values { + continuation.yield(loadErrorsByEntryID) + } } } diff --git a/Sources/Panels/BrowserWebExtensionSupport+Permissions.swift b/Sources/Panels/BrowserWebExtensionSupport+Permissions.swift index 874243292572..be96ebf7b4d9 100644 --- a/Sources/Panels/BrowserWebExtensionSupport+Permissions.swift +++ b/Sources/Panels/BrowserWebExtensionSupport+Permissions.swift @@ -3,21 +3,29 @@ import WebKit @available(macOS 15.4, *) extension BrowserWebExtensionSupport { - func restorePermissionState(for context: WKWebExtensionContext, entryID: String) { - permissionStateStore.state(for: entryID)?.apply(to: context) + func restorePermissionState(for context: WKWebExtensionContext, entryID: String, standardizedPath: String) { + permissionStateStore.state(for: entryID, standardizedPath: standardizedPath)?.apply(to: context) } - func persistPermissionState(entryID: String, context: WKWebExtensionContext) { - permissionStateStore.save(BrowserWebExtensionPermissionState(context: context), for: entryID) + func persistPermissionState(entryID: String, standardizedPath: String, context: WKWebExtensionContext) { + permissionStateStore.save( + BrowserWebExtensionPermissionState(context: context), + for: entryID, + standardizedPath: standardizedPath + ) } - func removePermissionState(entryID: String) { - permissionStateStore.removeState(for: entryID) + func removePermissionState(entryID: String, standardizedPath: String) { + permissionStateStore.removeState(for: entryID, standardizedPath: standardizedPath) } func persistPermissionState(for context: WKWebExtensionContext) { guard let record = loadedRecordsInOrder.first(where: { $0.context === context }) else { return } - persistPermissionState(entryID: record.entryID, context: context) + persistPermissionState( + entryID: record.entryID, + standardizedPath: record.standardizedPath, + context: context + ) } func persistPermissionStateSoon(for context: WKWebExtensionContext) { @@ -27,7 +35,11 @@ extension BrowserWebExtensionSupport { } } - func installPermissionStateObservers(for context: WKWebExtensionContext, entryID: String) { + func installPermissionStateObservers( + for context: WKWebExtensionContext, + entryID: String, + standardizedPath: String + ) { removePermissionStateObservers(entryID: entryID) permissionObserverTokensByEntryID[entryID] = permissionStateNotificationNames.map { name in NotificationCenter.default.addObserver( @@ -37,7 +49,11 @@ extension BrowserWebExtensionSupport { ) { [weak self, weak context] _ in guard let self, let context else { return } MainActor.assumeIsolated { - self.persistPermissionState(entryID: entryID, context: context) + self.persistPermissionState( + entryID: entryID, + standardizedPath: standardizedPath, + context: context + ) } } } diff --git a/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift b/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift index 807c1d730d70..1901f8c429f8 100644 --- a/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift +++ b/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift @@ -65,6 +65,9 @@ extension BrowserWebExtensionSupport: WKWebExtensionControllerDelegate { popouts.append(popout) controller.didOpenWindow(popout) controller.didOpenTab(popout.tab) + if popout.isKeyWindow { + controller.didFocusWindow(popout) + } completionHandler(popout, nil) } diff --git a/Sources/Panels/BrowserWebExtensionSupport.swift b/Sources/Panels/BrowserWebExtensionSupport.swift index bb4e96d5fc36..7f0dbaf6c524 100644 --- a/Sources/Panels/BrowserWebExtensionSupport.swift +++ b/Sources/Panels/BrowserWebExtensionSupport.swift @@ -50,6 +50,8 @@ final class BrowserWebExtensionSupport: NSObject, BrowserWebExtensionHosting { @ObservationIgnored var loadErrorsByEntryID: [String: String] = [:] @ObservationIgnored + var loadErrorUpdateContinuations: [UUID: AsyncStream<[String: String]>.Continuation] = [:] + @ObservationIgnored var tabAdapters: [UUID: BrowserWebExtensionTabAdapter] = [:] @ObservationIgnored var actionSnapshotInvalidationsByPanelID: [UUID: BrowserWebExtensionActionSnapshotInvalidation] = [:] @@ -181,7 +183,9 @@ final class BrowserWebExtensionSupport: NSObject, BrowserWebExtensionHosting { settingsLoadGeneration &+= 1 settingsObservationTask?.cancel() settingsObservationTask = nil - unloadAllWebExtensions() + if !unloadAllWebExtensions() { + BrowserAvailabilitySettings.setDisabled(false) + } } static func environmentExtensionPaths() -> [String] { @@ -234,9 +238,19 @@ final class BrowserWebExtensionSupport: NSObject, BrowserWebExtensionHosting { } func noteWindowBecameKey(_ window: NSWindow) { - guard let panelID = activePanelID(in: window) else { return } - noteActivated(panelID: panelID) - controller.didFocusWindow(windowAdapter) + let focusedWindow = webExtensionWindow(for: window) + if (focusedWindow as AnyObject?) === windowAdapter, + let panelID = activePanelID(in: window) { + noteActivated(panelID: panelID) + } + controller.didFocusWindow(focusedWindow) + } + + func webExtensionWindow(for window: NSWindow) -> (any WKWebExtensionWindow)? { + if let popout = popouts.first(where: { $0.window === window }) { + return popout + } + return activePanelID(in: window) == nil ? nil : windowAdapter } private func rememberActivePanel(_ panelID: UUID) { diff --git a/Sources/Panels/CmuxWebView.swift b/Sources/Panels/CmuxWebView.swift index 2f2233dcbb3b..97ee80ded051 100644 --- a/Sources/Panels/CmuxWebView.swift +++ b/Sources/Panels/CmuxWebView.swift @@ -693,19 +693,19 @@ final class CmuxWebView: WKWebView { return finish(AppDelegate.shared?.handleBrowserSurfaceKeyEquivalent(event) == true) } + // Manifest commands may use Control or Option, so dispatch them before + // the Command-only cmux menu-equivalent guard. + if #available(macOS 15.4, *), + AppDelegate.shared?.shortcutEventBrowserPanel(event)?.performWebExtensionCommand(for: event) == true { + return finish(true) + } + // Menu/app shortcut routing is only needed for Command equivalents // (New Tab, Close Tab, tab switching, split commands, etc). guard flags.contains(.command) else { return finish(super.performKeyEquivalent(with: event)) } - // Web-extension commands (e.g. Bitwarden's ⌘⇧L autofill) match only - // shortcuts the extension manifest declares; everything else falls through. - if #available(macOS 15.4, *), - AppDelegate.shared?.shortcutEventBrowserPanel(event)?.performWebExtensionCommand(for: event) == true { - return finish(true) - } - if Self.isPasteAsPlainTextCommandEquivalent(event) { if event.timestamp > 0 { lastPasteAsPlainTextPerformKeyEventTimestamp = event.timestamp diff --git a/cmuxTests/BrowserWebExtensionSupportTests.swift b/cmuxTests/BrowserWebExtensionSupportTests.swift index 6bfce62e0ccb..ec7c4049a2ec 100644 --- a/cmuxTests/BrowserWebExtensionSupportTests.swift +++ b/cmuxTests/BrowserWebExtensionSupportTests.swift @@ -368,12 +368,12 @@ struct BrowserWebExtensionSupportTests { hasAccessToPrivateData: true ) - store.save(firstState, for: "com.example.first") - store.save(secondState, for: "com.example.second") + store.save(firstState, for: "com.example.first", standardizedPath: "/Extensions/First") + store.save(secondState, for: "com.example.second", standardizedPath: "/Extensions/Second") - #expect(store.state(for: "com.example.first") == firstState) - #expect(store.state(for: "com.example.second") == secondState) - #expect(store.state(for: "missing") == nil) + #expect(store.state(for: "com.example.first", standardizedPath: "/Extensions/First") == firstState) + #expect(store.state(for: "com.example.second", standardizedPath: "/Extensions/Second") == secondState) + #expect(store.state(for: "missing", standardizedPath: "/Extensions/Missing") == nil) } @Test @@ -425,12 +425,12 @@ struct BrowserWebExtensionSupportTests { hasAccessToPrivateData: false ) - store.save(firstState, for: "com.example.first") - store.save(secondState, for: "com.example.second") - store.removeState(for: "com.example.first") + store.save(firstState, for: "com.example.first", standardizedPath: "/Extensions/First") + store.save(secondState, for: "com.example.second", standardizedPath: "/Extensions/Second") + store.removeState(for: "com.example.first", standardizedPath: "/Extensions/First") - #expect(store.state(for: "com.example.first") == nil) - #expect(store.state(for: "com.example.second") == secondState) + #expect(store.state(for: "com.example.first", standardizedPath: "/Extensions/First") == nil) + #expect(store.state(for: "com.example.second", standardizedPath: "/Extensions/Second") == secondState) } @Test From c5677dcd633f1a124d927d1ac0e24209afee0d2d Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 14:52:29 -0700 Subject: [PATCH 35/51] Fix browser extension review findings --- .github/swift-file-length-budget.tsv | 4 +- Sources/AppDelegate.swift | 42 ++++++ .../BrowserWebExtensionSupport+Loading.swift | 13 ++ ...ort+WKWebExtensionControllerDelegate.swift | 61 ++++++-- Sources/Panels/CmuxWebView.swift | 4 +- cmux.xcodeproj/project.pbxproj | 4 + ...serWebExtensionReviewRegressionTests.swift | 132 ++++++++++++++++++ 7 files changed, 242 insertions(+), 18 deletions(-) create mode 100644 cmuxTests/BrowserWebExtensionReviewRegressionTests.swift diff --git a/.github/swift-file-length-budget.tsv b/.github/swift-file-length-budget.tsv index 531483235df8..aabb5cc70045 100644 --- a/.github/swift-file-length-budget.tsv +++ b/.github/swift-file-length-budget.tsv @@ -35,8 +35,8 @@ 2882 Sources/Update/UpdateTitlebarAccessory.swift 2876 cmuxTests/CMUXOpenCommandTests.swift 2875 Sources/SessionIndexView.swift -2611 Sources/KeyboardShortcutSettings.swift -2569 Sources/Panels/CmuxWebView.swift +2581 Sources/KeyboardShortcutSettings.swift +2571 Sources/Panels/CmuxWebView.swift 2546 cmuxTests/WorkspaceManualUnreadTests.swift 2524 cmuxTests/CommandPaletteSearchEngineTests.swift 2403 Sources/Mobile/MobileHostService.swift diff --git a/Sources/AppDelegate.swift b/Sources/AppDelegate.swift index 3a7515d5b818..c5adf1e4c0bf 100644 --- a/Sources/AppDelegate.swift +++ b/Sources/AppDelegate.swift @@ -14815,6 +14815,48 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent handleConfiguredShortcutKeyEquivalent(event) } + /// Extension manifest commands run only after configured cmux shortcuts decline the event. + func shouldOfferBrowserWebExtensionCommand(_ event: NSEvent) -> Bool { + let shortcutContext = shortcutEventFocusContext(event).shortcutContext + for action in KeyboardShortcutSettings.Action.allCases { + guard action != .showHideAllWindows, + action != .globalSearch, + !action.isBrowserContentShortcut, + KeyboardShortcutSettings.effectiveWhenClause(for: action).evaluate(shortcutContext) else { + continue + } + if action.usesNumberedDigitMatching { + if numberedConfiguredShortcutDigit(event: event, action: action) != nil { + return false + } + continue + } + if configuredShortcutClaimsWebExtensionCommand( + event: event, + shortcut: KeyboardShortcutSettings.shortcut(for: action) + ) { + return false + } + } + + let context = preferredMainWindowContextForShortcutRouting(event: event) + return !configuredCmuxShortcutActions(for: context).contains { action in + guard let shortcut = action.shortcut else { return false } + return configuredShortcutClaimsWebExtensionCommand(event: event, shortcut: shortcut) + } + } + + private func configuredShortcutClaimsWebExtensionCommand( + event: NSEvent, + shortcut: StoredShortcut + ) -> Bool { + guard !shortcut.isUnbound else { return false } + if activeConfiguredShortcutChordPrefixForCurrentEvent == nil, shortcut.hasChord { + return matchShortcutStroke(event: event, stroke: shortcut.firstStroke) + } + return matchConfiguredShortcut(event: event, shortcut: shortcut) + } + /// Route AppKit key-equivalent fallbacks through the same configured shortcut /// dispatcher as the local key monitor before any stale menu item can run. @discardableResult diff --git a/Sources/Panels/BrowserWebExtensionSupport+Loading.swift b/Sources/Panels/BrowserWebExtensionSupport+Loading.swift index d4e62c8c34a1..df3474926c37 100644 --- a/Sources/Panels/BrowserWebExtensionSupport+Loading.swift +++ b/Sources/Panels/BrowserWebExtensionSupport+Loading.swift @@ -109,6 +109,12 @@ extension BrowserWebExtensionSupport { invalidation.refresh() } + func extensionPagePanels(usingContextIdentifier contextIdentifier: ObjectIdentifier) -> [BrowserPanel] { + tabAdapters.values.compactMap(\.panel).filter { + $0.webExtensionPageContextIdentifier == contextIdentifier + } + } + private func actionSnapshot( for record: BrowserWebExtensionLoadedRecord, tabAdapter: BrowserWebExtensionTabAdapter? @@ -134,6 +140,9 @@ extension BrowserWebExtensionSupport { preservePermissionState: Bool = true ) -> BrowserWebExtensionEntry? { guard let record = loadedByEntryID[entryID] else { return nil } + let extensionPagePanels = extensionPagePanels( + usingContextIdentifier: ObjectIdentifier(record.context) + ) if preservePermissionState { persistPermissionState( entryID: entryID, @@ -160,6 +169,10 @@ extension BrowserWebExtensionSupport { loadErrorsByEntryID.removeValue(forKey: entryID) refreshLoadErrors() + for panel in extensionPagePanels { + closeOpenedBrowserTab(panel) + } + let closingPopouts = popouts.filter { $0.extensionContext === record.context } for popout in closingPopouts { popout.closeFromExtensionOrUser() diff --git a/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift b/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift index 1901f8c429f8..6db2a65c41fa 100644 --- a/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift +++ b/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift @@ -86,7 +86,6 @@ extension BrowserWebExtensionSupport: WKWebExtensionControllerDelegate { ).map { _ in windowAdapter } } - guard activeTabAdapter?.panel != nil else { return nil } let requestedTabs = configuration.tabURLs.map { url in (url: url, webViewConfiguration: webViewConfigurationForExtensionRequestedBrowserURL(url, for: extensionContext)) } @@ -110,7 +109,7 @@ extension BrowserWebExtensionSupport: WKWebExtensionControllerDelegate { return windowAdapter } - private func closeOpenedBrowserTab(_ panel: BrowserPanel) { + func closeOpenedBrowserTab(_ panel: BrowserPanel) { if let workspace = AppDelegate.shared?.workspaceContainingPanel( panelId: panel.id, preferredWorkspaceId: panel.workspaceId @@ -152,29 +151,61 @@ extension BrowserWebExtensionSupport: WKWebExtensionControllerDelegate { completionHandler(adapter, nil) } - private func openBrowserTab( + func openBrowserTab( url: URL?, shouldActivate: Bool, webViewConfiguration: WKWebViewConfiguration? ) -> BrowserWebExtensionTabAdapter? { - guard let sourcePanel = activeTabAdapter?.panel else { return nil } - if let panel = openWorkspaceBrowserTab( - sourcePanel: sourcePanel, + if let sourcePanel = activeTabAdapter?.panel { + if let panel = openWorkspaceBrowserTab( + sourcePanel: sourcePanel, + url: url, + shouldActivate: shouldActivate, + webViewConfiguration: webViewConfiguration + ) { + return tabAdapterForOpenedPanel(panel, shouldActivate: shouldActivate) + } + if let panel = openDockBrowserTab( + sourcePanel: sourcePanel, + url: url, + shouldActivate: shouldActivate, + webViewConfiguration: webViewConfiguration + ) { + return tabAdapterForOpenedPanel(panel, shouldActivate: shouldActivate) + } + } + + guard let tabManager = AppDelegate.shared?.activeTabManagerForCommands( + preferredWindow: NSApp.keyWindow ?? NSApp.mainWindow + ) else { return nil } + return openBrowserTab( + in: tabManager, url: url, shouldActivate: shouldActivate, webViewConfiguration: webViewConfiguration - ) { - return tabAdapterForOpenedPanel(panel, shouldActivate: shouldActivate) + ) + } + + func openBrowserTab( + in tabManager: TabManager, + url: URL?, + shouldActivate: Bool, + webViewConfiguration: WKWebViewConfiguration? + ) -> BrowserWebExtensionTabAdapter? { + guard let workspace = tabManager.selectedWorkspace ?? tabManager.tabs.first, + let paneID = workspace.bonsplitController.focusedPaneId + ?? workspace.bonsplitController.allPaneIds.first else { return nil } + if tabManager.selectedTabId != workspace.id { + tabManager.selectWorkspace(workspace) } - if let panel = openDockBrowserTab( - sourcePanel: sourcePanel, + guard let panel = workspace.newBrowserSurface( + inPane: paneID, url: url, - shouldActivate: shouldActivate, + focus: shouldActivate, + preferredProfileID: workspace.preferredBrowserProfileID, webViewConfiguration: webViewConfiguration - ) { - return tabAdapterForOpenedPanel(panel, shouldActivate: shouldActivate) - } - return nil + ) else { return nil } + return tabAdapterForOpenedPanel(panel, shouldActivate: shouldActivate) } private func openWorkspaceBrowserTab( diff --git a/Sources/Panels/CmuxWebView.swift b/Sources/Panels/CmuxWebView.swift index 97ee80ded051..2b107064f78b 100644 --- a/Sources/Panels/CmuxWebView.swift +++ b/Sources/Panels/CmuxWebView.swift @@ -696,7 +696,9 @@ final class CmuxWebView: WKWebView { // Manifest commands may use Control or Option, so dispatch them before // the Command-only cmux menu-equivalent guard. if #available(macOS 15.4, *), - AppDelegate.shared?.shortcutEventBrowserPanel(event)?.performWebExtensionCommand(for: event) == true { + let appDelegate = AppDelegate.shared, + appDelegate.shouldOfferBrowserWebExtensionCommand(event), + appDelegate.shortcutEventBrowserPanel(event)?.performWebExtensionCommand(for: event) == true { return finish(true) } diff --git a/cmux.xcodeproj/project.pbxproj b/cmux.xcodeproj/project.pbxproj index 897bc9493f79..2bac5f2a3451 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -320,6 +320,7 @@ C0DE71B10000000000000001 /* AppDelegate+AgentChatNotifications.swift in Sources B1CFE00F0000000000000001 /* BrowserWebExtensionPermissionStateStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1CFE00F0000000000000002 /* BrowserWebExtensionPermissionStateStore.swift */; }; B1CFE0050000000000000001 /* BrowserWebExtensionPopoutWindowController.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1CFE0050000000000000002 /* BrowserWebExtensionPopoutWindowController.swift */; }; B1CFE00C0000000000000001 /* BrowserWebExtensionReconciliationPlanner.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1CFE00C0000000000000002 /* BrowserWebExtensionReconciliationPlanner.swift */; }; + B1CFE0210000000000000001 /* BrowserWebExtensionReviewRegressionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1CFE0210000000000000002 /* BrowserWebExtensionReviewRegressionTests.swift */; }; B1CFE0070000000000000001 /* BrowserWebExtensionSupport+Loading.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1CFE0070000000000000002 /* BrowserWebExtensionSupport+Loading.swift */; }; B1CFE0100000000000000001 /* BrowserWebExtensionSupport+Permissions.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1CFE0100000000000000002 /* BrowserWebExtensionSupport+Permissions.swift */; }; B1CFE0090000000000000001 /* BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1CFE0090000000000000002 /* BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift */; }; @@ -2097,6 +2098,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = B1CFE00F0000000000000002 /* BrowserWebExtensionPermissionStateStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/BrowserWebExtensionPermissionStateStore.swift; sourceTree = ""; }; B1CFE0050000000000000002 /* BrowserWebExtensionPopoutWindowController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/BrowserWebExtensionPopoutWindowController.swift; sourceTree = ""; }; B1CFE00C0000000000000002 /* BrowserWebExtensionReconciliationPlanner.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/BrowserWebExtensionReconciliationPlanner.swift; sourceTree = ""; }; + B1CFE0210000000000000002 /* BrowserWebExtensionReviewRegressionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BrowserWebExtensionReviewRegressionTests.swift; sourceTree = ""; }; B1CFE0070000000000000002 /* BrowserWebExtensionSupport+Loading.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Panels/BrowserWebExtensionSupport+Loading.swift"; sourceTree = ""; }; B1CFE0100000000000000002 /* BrowserWebExtensionSupport+Permissions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Panels/BrowserWebExtensionSupport+Permissions.swift"; sourceTree = ""; }; B1CFE0090000000000000002 /* BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift"; sourceTree = ""; }; @@ -4970,6 +4972,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = B75040020000000000000002 /* BrowserDiscardedWebViewRestoreRetryTests.swift */, B75040030000000000000002 /* BrowserDiscardRestoreHealPredicateTests.swift */, B1CFE0200000000000000002 /* BrowserWebExtensionSupportTests.swift */, + B1CFE0210000000000000002 /* BrowserWebExtensionReviewRegressionTests.swift */, B75040040000000000000002 /* BrowserInsecureHTTPAlertTestSupport.swift */, B6585002B6585002B658PW02 /* BrowserPrewarmedWebViewPoolTests.swift */, 58C7B1B978620BE162CC057E /* BrowserPanelTests.swift */, @@ -6963,6 +6966,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = C2035A060000000000000001 /* BrowserSSLTrustBypassStateTests.swift in Sources */, C7B800062D4202A13C962D2D /* BrowserSystemProxyMirrorTests.swift in Sources */, C0DE49870000000000000001 /* BrowserWebContentProcessTests.swift in Sources */, + B1CFE0210000000000000001 /* BrowserWebExtensionReviewRegressionTests.swift in Sources */, B1CFE0200000000000000001 /* BrowserWebExtensionSupportTests.swift in Sources */, C0DE62600000000000000001 /* BrowserWindowPortalRegistryNotificationTests.swift in Sources */, C0DE35530000000000000101 /* BundledCLILinkageTests.swift in Sources */, diff --git a/cmuxTests/BrowserWebExtensionReviewRegressionTests.swift b/cmuxTests/BrowserWebExtensionReviewRegressionTests.swift new file mode 100644 index 000000000000..e75f6b9e82bb --- /dev/null +++ b/cmuxTests/BrowserWebExtensionReviewRegressionTests.swift @@ -0,0 +1,132 @@ +import AppKit +import Foundation +import Testing +import WebKit + +#if canImport(cmux_DEV) +@testable import cmux_DEV +#elseif canImport(cmux) +@testable import cmux +#endif + +@Suite(.serialized) +struct BrowserWebExtensionReviewRegressionTests { + @MainActor + @Test + @available(macOS 15.4, *) + func extensionCreatesFirstBrowserTabInActiveTerminalWindow() throws { + let wasBrowserDisabled = BrowserAvailabilitySettings.isDisabled() + BrowserAvailabilitySettings.setDisabled(false) + defer { BrowserAvailabilitySettings.setDisabled(wasBrowserDisabled) } + + let support = BrowserWebExtensionSupport() + let tabManager = TabManager(browserWebExtensionHost: support) + let workspace = try #require(tabManager.selectedWorkspace) + #expect(workspace.panels.values.allSatisfy { !($0 is BrowserPanel) }) + + let adapter = support.openBrowserTab( + in: tabManager, + url: nil, + shouldActivate: false, + webViewConfiguration: nil + ) + + let panel = try #require(adapter?.panel) + defer { _ = workspace.closePanel(panel.id, force: true) } + #expect(panel.workspaceId == workspace.id) + #expect(workspace.panels[panel.id] === panel) + } + + @MainActor + @Test + func configuredCmuxShortcutTakesPriorityOverExtensionCommand() throws { + let appDelegate = try #require(AppDelegate.shared) + let action = KeyboardShortcutSettings.Action.openBrowser + let hadPersistedShortcut = UserDefaults.standard.object(forKey: action.defaultsKey) != nil + let originalShortcut = KeyboardShortcutSettings.shortcut(for: action) + defer { + if hadPersistedShortcut { + KeyboardShortcutSettings.setShortcut(originalShortcut, for: action) + } else { + KeyboardShortcutSettings.resetShortcut(for: action) + } + } + let event = try #require(NSEvent.keyEvent( + with: .keyDown, + location: .zero, + modifierFlags: [.command, .shift], + timestamp: ProcessInfo.processInfo.systemUptime, + windowNumber: 0, + context: nil, + characters: "L", + charactersIgnoringModifiers: "l", + isARepeat: false, + keyCode: 37 + )) + + KeyboardShortcutSettings.setShortcut(action.defaultShortcut, for: action) + #expect(!appDelegate.shouldOfferBrowserWebExtensionCommand(event)) + + KeyboardShortcutSettings.setShortcut(.unbound, for: action) + #expect(appDelegate.shouldOfferBrowserWebExtensionCommand(event)) + } + + @MainActor + @Test + @available(macOS 15.4, *) + func extensionPagePanelLookupMatchesTheOwningContextOnly() throws { + let extensionURL = try #require(URL(string: "webkit-extension://cmux-test/options.html")) + let host = BrowserWebExtensionReviewTestHost(extensionHost: extensionURL.host) + let panel = BrowserPanel( + workspaceId: UUID(), + initialURL: extensionURL, + renderInitialNavigation: false, + browserWebExtensionHost: host + ) + let support = BrowserWebExtensionSupport() + support.register(panel: panel) + defer { + support.unregister(panelID: panel.id) + panel.close() + } + + #expect( + support.extensionPagePanels(usingContextIdentifier: host.contextIdentifier).map(\.id) == [panel.id] + ) + #expect( + support.extensionPagePanels(usingContextIdentifier: ObjectIdentifier(NSObject())).isEmpty + ) + } +} + +@MainActor +private final class BrowserWebExtensionReviewTestHost: BrowserWebExtensionHosting { + private let extensionHost: String? + private let contextToken = NSObject() + private let configuration = WKWebViewConfiguration() + + init(extensionHost: String?) { + self.extensionHost = extensionHost + } + + var contextIdentifier: ObjectIdentifier { + ObjectIdentifier(contextToken) + } + + func attach(to configuration: WKWebViewConfiguration) {} + + func webViewConfiguration(forNavigatingTo url: URL) -> BrowserWebExtensionNavigationConfiguration? { + guard url.scheme?.lowercased() == "webkit-extension", + url.host == extensionHost else { return nil } + return BrowserWebExtensionNavigationConfiguration( + contextIdentifier: contextIdentifier, + webViewConfiguration: configuration + ) + } + + func register(panel: BrowserPanel) {} + func unregister(panelID: UUID) {} + func noteActivated(panelID: UUID) {} + func noteTabMetadataChanged(panelID: UUID) {} + func performCommand(for event: NSEvent) -> Bool { false } +} From 7c6bb51c51b712a688485033edc3bdd626fa69bd Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 15:41:02 -0700 Subject: [PATCH 36/51] test(browser): cover extension settings feedback --- .../Sections/BrowserWebExtensionsCard.swift | 39 ++++++------ .../BrowserWebExtensionsCardState.swift | 41 ++++++++++++ .../BrowserWebExtensionsCardStateTests.swift | 63 +++++++++++++++++++ 3 files changed, 125 insertions(+), 18 deletions(-) create mode 100644 Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCardState.swift create mode 100644 Packages/macOS/CmuxSettingsUI/Tests/CmuxSettingsUITests/BrowserWebExtensionsCardStateTests.swift diff --git a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift index 8222cf504d3f..eb63d590ee45 100644 --- a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift +++ b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift @@ -15,13 +15,11 @@ struct BrowserWebExtensionsCard: View { let model: JSONValueModel<[BrowserWebExtensionEntry]> let hostActions: SettingsHostActions - @State private var discovered: [SettingsDiscoveredBrowserExtension] = [] + @State private var cardState = BrowserWebExtensionsCardState() @State private var loadErrorsByEntryID: [String: String] = [:] - @State private var pendingEntries: [BrowserWebExtensionEntry]? - @State private var pendingWriteID: UInt64? var body: some View { - let entries = effectiveEntries + let entries = cardState.effectiveEntries(observed: model.current) let enabledByID = effectiveEnabledByID(for: entries) SettingsCard { headerRow @@ -38,7 +36,9 @@ struct BrowserWebExtensionsCard: View { } .task { model.startObserving() - discovered = await hostActions.discoverBrowserWebExtensions() + let discovered = await hostActions.discoverBrowserWebExtensions() + guard !Task.isCancelled else { return } + cardState.completeDiscovery(discovered) } .task { for await loadErrors in hostActions.browserWebExtensionLoadErrorUpdates() { @@ -46,15 +46,13 @@ struct BrowserWebExtensionsCard: View { } } .onChange(of: model.current) { _, current in - guard let expectedEntries = pendingEntries, current == expectedEntries else { return } - pendingEntries = nil - pendingWriteID = nil + cardState.reconcileObservedEntries(current) } .onChange(of: model.writeResultRevision) { _, _ in - guard model.lastCompletedWriteID == pendingWriteID, - model.lastWriteError != nil else { return } - pendingEntries = nil - pendingWriteID = nil + cardState.reconcileWriteResult( + completedWriteID: model.lastCompletedWriteID, + failed: model.lastWriteError != nil + ) } } @@ -63,16 +61,19 @@ struct BrowserWebExtensionsCard: View { } private var effectiveEntries: [BrowserWebExtensionEntry] { - pendingEntries ?? model.current + cardState.effectiveEntries(observed: model.current) } /// Discovered Safari extensions not yet added, offered by the Import menu. private var importableExtensions: [SettingsDiscoveredBrowserExtension] { - guard model.hasObservedValue else { return [] } + guard cardState.canUseImportMenu( + supported: supported, + hasObservedValue: model.hasObservedValue + ) else { return [] } let entries = effectiveEntries let addedIDs = Set(entries.map(\.id)) let addedResourcePaths = Set(entries.map { standardizedResourcePath(for: $0) }) - return discovered.filter { candidate in + return cardState.discovered.filter { candidate in !addedIDs.contains(candidate.id) && !addedResourcePaths.contains(standardizedSafariAppExtensionResourcePath(candidate.path)) } @@ -128,7 +129,10 @@ struct BrowserWebExtensionsCard: View { } .controlSize(.small) .fixedSize() - .disabled(!supported || !model.hasObservedValue) + .disabled(!cardState.canUseImportMenu( + supported: supported, + hasObservedValue: model.hasObservedValue + )) .accessibilityIdentifier("BrowserWebExtensionsImportMenu") } @@ -231,8 +235,7 @@ struct BrowserWebExtensionsCard: View { } private func commitEntries(_ entries: [BrowserWebExtensionEntry]) { - pendingEntries = entries - pendingWriteID = model.set(entries) + cardState.beginWrite(entries: entries, writeID: model.set(entries)) } private func importSafariExtension(_ candidate: SettingsDiscoveredBrowserExtension) { diff --git a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCardState.swift b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCardState.swift new file mode 100644 index 000000000000..ff1acdfc9abc --- /dev/null +++ b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCardState.swift @@ -0,0 +1,41 @@ +import CmuxSettings + +/// Transient discovery, optimistic-write, and error state for the Extensions card. +struct BrowserWebExtensionsCardState { + private(set) var discovered: [SettingsDiscoveredBrowserExtension] = [] + private(set) var isDiscoveryComplete = false + private(set) var pendingEntries: [BrowserWebExtensionEntry]? + private(set) var pendingWriteID: UInt64? + private(set) var hasWriteError = false + + func effectiveEntries(observed: [BrowserWebExtensionEntry]) -> [BrowserWebExtensionEntry] { + pendingEntries ?? observed + } + + func canUseImportMenu(supported: Bool, hasObservedValue: Bool) -> Bool { + supported && hasObservedValue + } + + mutating func completeDiscovery(_ discovered: [SettingsDiscoveredBrowserExtension]) { + self.discovered = discovered + isDiscoveryComplete = true + } + + mutating func beginWrite(entries: [BrowserWebExtensionEntry], writeID: UInt64) { + pendingEntries = entries + pendingWriteID = writeID + hasWriteError = false + } + + mutating func reconcileObservedEntries(_ entries: [BrowserWebExtensionEntry]) { + guard entries == pendingEntries else { return } + pendingEntries = nil + pendingWriteID = nil + } + + mutating func reconcileWriteResult(completedWriteID: UInt64, failed: Bool) { + guard completedWriteID == pendingWriteID, failed else { return } + pendingEntries = nil + pendingWriteID = nil + } +} diff --git a/Packages/macOS/CmuxSettingsUI/Tests/CmuxSettingsUITests/BrowserWebExtensionsCardStateTests.swift b/Packages/macOS/CmuxSettingsUI/Tests/CmuxSettingsUITests/BrowserWebExtensionsCardStateTests.swift new file mode 100644 index 000000000000..7926b9396aeb --- /dev/null +++ b/Packages/macOS/CmuxSettingsUI/Tests/CmuxSettingsUITests/BrowserWebExtensionsCardStateTests.swift @@ -0,0 +1,63 @@ +import CmuxSettings +import Testing + +@testable import CmuxSettingsUI + +@Suite +struct BrowserWebExtensionsCardStateTests { + @Test + func importMenuWaitsForSettingsAndDiscovery() { + var state = BrowserWebExtensionsCardState() + + #expect(!state.canUseImportMenu(supported: true, hasObservedValue: true)) + + state.completeDiscovery([]) + + #expect(!state.canUseImportMenu(supported: true, hasObservedValue: false)) + #expect(!state.canUseImportMenu(supported: false, hasObservedValue: true)) + #expect(state.canUseImportMenu(supported: true, hasObservedValue: true)) + } + + @Test + func matchingWriteFailureRollsBackAndSurfacesError() { + let observed = [entry(id: "existing")] + let pending = observed + [entry(id: "new")] + var state = BrowserWebExtensionsCardState() + state.beginWrite(entries: pending, writeID: 2) + + state.reconcileWriteResult(completedWriteID: 1, failed: true) + #expect(state.effectiveEntries(observed: observed) == pending) + #expect(!state.hasWriteError) + + state.reconcileWriteResult(completedWriteID: 2, failed: true) + #expect(state.effectiveEntries(observed: observed) == observed) + #expect(state.hasWriteError) + + state.beginWrite(entries: pending, writeID: 3) + #expect(!state.hasWriteError) + } + + @Test + func observedPendingValueCompletesOptimisticWrite() { + let observed = [entry(id: "existing")] + let pending = observed + [entry(id: "new")] + var state = BrowserWebExtensionsCardState() + state.beginWrite(entries: pending, writeID: 1) + + state.reconcileObservedEntries(observed) + #expect(state.effectiveEntries(observed: observed) == pending) + + state.reconcileObservedEntries(pending) + #expect(state.effectiveEntries(observed: pending) == pending) + #expect(state.pendingWriteID == nil) + } + + private func entry(id: String) -> BrowserWebExtensionEntry { + BrowserWebExtensionEntry( + id: id, + kind: .unpackedDirectory, + path: "/Extensions/\(id)", + enabled: true + ) + } +} From a9724a530c0f691e5fd4f8635385e85014352df0 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 15:42:41 -0700 Subject: [PATCH 37/51] fix(browser): address remaining extension feedback --- .../Sections/BrowserWebExtensionsCard.swift | 29 ++-- .../BrowserWebExtensionsCardState.swift | 3 +- Resources/Localizable.xcstrings | 125 ++++++++++++++++++ ...e+BrowserWebExtensionShortcutRouting.swift | 45 +++++++ Sources/AppDelegate.swift | 46 +------ ...erWebExtensionPopoutWindowController.swift | 3 +- cmux.xcodeproj/project.pbxproj | 4 + 7 files changed, 200 insertions(+), 55 deletions(-) create mode 100644 Sources/AppDelegate+BrowserWebExtensionShortcutRouting.swift diff --git a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift index eb63d590ee45..d513788a433e 100644 --- a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift +++ b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift @@ -84,15 +84,7 @@ struct BrowserWebExtensionsCard: View { configurationReview: .json("browser.webExtensions"), searchAnchorID: "setting:browser:web-extensions", String(localized: "settings.browser.webExtensions", defaultValue: "Extensions"), - subtitle: supported - ? String( - localized: "settings.browser.webExtensions.subtitle", - defaultValue: "Safari web extensions from installed apps, or unpacked extension folders." - ) - : String( - localized: "settings.browser.webExtensions.unsupported", - defaultValue: "Web extensions require macOS 15.4 or later." - ) + subtitle: headerSubtitle ) { HStack(spacing: 8) { importMenu @@ -136,6 +128,25 @@ struct BrowserWebExtensionsCard: View { .accessibilityIdentifier("BrowserWebExtensionsImportMenu") } + private var headerSubtitle: String { + if !supported { + return String( + localized: "settings.browser.webExtensions.unsupported", + defaultValue: "Web extensions require macOS 15.4 or later." + ) + } + if cardState.hasWriteError { + return String( + localized: "settings.browser.webExtensions.saveFailed.subtitle", + defaultValue: "Couldn’t save extension changes. Check cmux.json and try again." + ) + } + return String( + localized: "settings.browser.webExtensions.subtitle", + defaultValue: "Safari web extensions from installed apps, or unpacked extension folders." + ) + } + private var emptyRow: some View { SettingsCardRow( configurationReview: .settingsOnly, diff --git a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCardState.swift b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCardState.swift index ff1acdfc9abc..0d9708de4bc8 100644 --- a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCardState.swift +++ b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCardState.swift @@ -13,7 +13,7 @@ struct BrowserWebExtensionsCardState { } func canUseImportMenu(supported: Bool, hasObservedValue: Bool) -> Bool { - supported && hasObservedValue + supported && hasObservedValue && isDiscoveryComplete } mutating func completeDiscovery(_ discovered: [SettingsDiscoveredBrowserExtension]) { @@ -37,5 +37,6 @@ struct BrowserWebExtensionsCardState { guard completedWriteID == pendingWriteID, failed else { return } pendingEntries = nil pendingWriteID = nil + hasWriteError = true } } diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index 965ff6ebc8a6..ea0aa7a4d443 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -45938,6 +45938,131 @@ } } }, + "settings.browser.webExtensions.saveFailed.subtitle": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "تعذّر حفظ تغييرات الامتداد. تحقّق من cmux.json وحاول مرة أخرى." + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "Nije moguće sačuvati promjene proširenja. Provjerite cmux.json i pokušajte ponovo." + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "Kunne ikke gemme ændringerne til udvidelsen. Kontrollér cmux.json, og prøv igen." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Die Erweiterungsänderungen konnten nicht gespeichert werden. Prüfe cmux.json und versuche es erneut." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Couldn’t save extension changes. Check cmux.json and try again." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "No se pudieron guardar los cambios de la extensión. Comprueba cmux.json e inténtalo de nuevo." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Impossible d’enregistrer les modifications de l’extension. Vérifiez cmux.json et réessayez." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Impossibile salvare le modifiche dell’estensione. Controlla cmux.json e riprova." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "拡張機能の変更を保存できませんでした。cmux.json を確認して、もう一度お試しください。" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "확장 프로그램 변경 사항을 저장할 수 없습니다. cmux.json을 확인하고 다시 시도하세요." + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "Kunne ikke lagre endringene for utvidelsen. Kontroller cmux.json og prøv igjen." + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "Nie udało się zapisać zmian rozszerzenia. Sprawdź cmux.json i spróbuj ponownie." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Não foi possível salvar as alterações da extensão. Verifique o cmux.json e tente novamente." + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Не удалось сохранить изменения расширения. Проверьте cmux.json и повторите попытку." + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "บันทึกการเปลี่ยนแปลงส่วนขยายไม่ได้ ตรวจสอบ cmux.json แล้วลองอีกครั้ง" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Uzantı değişiklikleri kaydedilemedi. cmux.json dosyasını kontrol edip yeniden deneyin." + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "Не вдалося зберегти зміни розширення. Перевірте cmux.json і повторіть спробу." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "无法保存扩展更改。请检查 cmux.json,然后重试。" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "無法儲存擴充功能變更。請檢查 cmux.json,然後再試一次。" + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "មិនអាចរក្សាទុកការផ្លាស់ប្តូរកម្មវិធីបន្ថែមបានទេ។ សូមពិនិត្យ cmux.json ហើយព្យាយាមម្តងទៀត។" + } + } + } + }, "settings.browser.webExtensions.remove": { "extractionState": "manual", "localizations": { diff --git a/Sources/AppDelegate+BrowserWebExtensionShortcutRouting.swift b/Sources/AppDelegate+BrowserWebExtensionShortcutRouting.swift new file mode 100644 index 000000000000..620767e6cdf2 --- /dev/null +++ b/Sources/AppDelegate+BrowserWebExtensionShortcutRouting.swift @@ -0,0 +1,45 @@ +import AppKit + +extension AppDelegate { + /// Extension manifest commands run only after configured cmux shortcuts decline the event. + func shouldOfferBrowserWebExtensionCommand(_ event: NSEvent) -> Bool { + let shortcutContext = shortcutEventFocusContext(event).shortcutContext + for action in KeyboardShortcutSettings.Action.allCases { + guard action != .showHideAllWindows, + action != .globalSearch, + !action.isBrowserContentShortcut, + KeyboardShortcutSettings.effectiveWhenClause(for: action).evaluate(shortcutContext) else { + continue + } + if action.usesNumberedDigitMatching { + if numberedConfiguredShortcutDigit(event: event, action: action) != nil { + return false + } + continue + } + if configuredShortcutClaimsWebExtensionCommand( + event: event, + shortcut: KeyboardShortcutSettings.shortcut(for: action) + ) { + return false + } + } + + let context = preferredMainWindowContextForShortcutRouting(event: event) + return !configuredCmuxShortcutActions(for: context).contains { action in + guard let shortcut = action.shortcut else { return false } + return configuredShortcutClaimsWebExtensionCommand(event: event, shortcut: shortcut) + } + } + + private func configuredShortcutClaimsWebExtensionCommand( + event: NSEvent, + shortcut: StoredShortcut + ) -> Bool { + guard !shortcut.isUnbound else { return false } + if activeConfiguredShortcutChordPrefixForCurrentEvent == nil, shortcut.hasChord { + return matchShortcutStroke(event: event, stroke: shortcut.firstStroke) + } + return matchConfiguredShortcut(event: event, shortcut: shortcut) + } +} diff --git a/Sources/AppDelegate.swift b/Sources/AppDelegate.swift index c5adf1e4c0bf..3b5971dc0d57 100644 --- a/Sources/AppDelegate.swift +++ b/Sources/AppDelegate.swift @@ -14815,48 +14815,6 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent handleConfiguredShortcutKeyEquivalent(event) } - /// Extension manifest commands run only after configured cmux shortcuts decline the event. - func shouldOfferBrowserWebExtensionCommand(_ event: NSEvent) -> Bool { - let shortcutContext = shortcutEventFocusContext(event).shortcutContext - for action in KeyboardShortcutSettings.Action.allCases { - guard action != .showHideAllWindows, - action != .globalSearch, - !action.isBrowserContentShortcut, - KeyboardShortcutSettings.effectiveWhenClause(for: action).evaluate(shortcutContext) else { - continue - } - if action.usesNumberedDigitMatching { - if numberedConfiguredShortcutDigit(event: event, action: action) != nil { - return false - } - continue - } - if configuredShortcutClaimsWebExtensionCommand( - event: event, - shortcut: KeyboardShortcutSettings.shortcut(for: action) - ) { - return false - } - } - - let context = preferredMainWindowContextForShortcutRouting(event: event) - return !configuredCmuxShortcutActions(for: context).contains { action in - guard let shortcut = action.shortcut else { return false } - return configuredShortcutClaimsWebExtensionCommand(event: event, shortcut: shortcut) - } - } - - private func configuredShortcutClaimsWebExtensionCommand( - event: NSEvent, - shortcut: StoredShortcut - ) -> Bool { - guard !shortcut.isUnbound else { return false } - if activeConfiguredShortcutChordPrefixForCurrentEvent == nil, shortcut.hasChord { - return matchShortcutStroke(event: event, stroke: shortcut.firstStroke) - } - return matchConfiguredShortcut(event: event, shortcut: shortcut) - } - /// Route AppKit key-equivalent fallbacks through the same configured shortcut /// dispatcher as the local key monitor before any stale menu item can run. @discardableResult @@ -15129,7 +15087,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent return false } - private func matchConfiguredShortcut(event: NSEvent, shortcut: StoredShortcut) -> Bool { + func matchConfiguredShortcut(event: NSEvent, shortcut: StoredShortcut) -> Bool { guard !shortcut.isUnbound else { return false } if let prefix = activeConfiguredShortcutChordPrefixForCurrentEvent { guard let secondStroke = shortcut.secondStroke, @@ -15172,7 +15130,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent } } - private func numberedConfiguredShortcutDigit( + func numberedConfiguredShortcutDigit( event: NSEvent, action: KeyboardShortcutSettings.Action ) -> Int? { diff --git a/Sources/Panels/BrowserWebExtensionPopoutWindowController.swift b/Sources/Panels/BrowserWebExtensionPopoutWindowController.swift index 094110156672..0e1f02c1f358 100644 --- a/Sources/Panels/BrowserWebExtensionPopoutWindowController.swift +++ b/Sources/Panels/BrowserWebExtensionPopoutWindowController.swift @@ -72,7 +72,7 @@ final class BrowserWebExtensionPopoutWindowController: NSObject, WKWebExtensionW webView.load(URLRequest(url: url)) } if configuration.shouldBeFocused { - NSApp.activate(ignoringOtherApps: false) + NSApp.activate() window.makeKeyAndOrderFront(nil) } else { window.orderFront(nil) @@ -128,6 +128,7 @@ final class BrowserWebExtensionPopoutWindowController: NSObject, WKWebExtensionW } func focus(for context: WKWebExtensionContext, completionHandler: @escaping (Error?) -> Void) { + NSApp.activate() window.makeKeyAndOrderFront(nil) completionHandler(nil) } diff --git a/cmux.xcodeproj/project.pbxproj b/cmux.xcodeproj/project.pbxproj index 2bac5f2a3451..0825c5c33061 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -106,6 +106,7 @@ F4350A120000000000000001 /* AppBundleIconPersistencePolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = F4350A130000000000000001 /* AppBundleIconPersistencePolicy.swift */; }; C0DE45AC0000000000000001 /* AppDelegate+AgentChat.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE45AC0000000000000002 /* AppDelegate+AgentChat.swift */; }; C0DE71B10000000000000001 /* AppDelegate+AgentChatNotifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */; }; + C0DE76990000000000000001 /* AppDelegate+BrowserWebExtensionShortcutRouting.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE76990000000000000002 /* AppDelegate+BrowserWebExtensionShortcutRouting.swift */; }; C4A570010000000000000001 /* AppDelegate+CanvasShortcutRouting.swift in Sources */ = {isa = PBXBuildFile; fileRef = C4A570010000000000000002 /* AppDelegate+CanvasShortcutRouting.swift */; }; C4160A030000000000000001 /* AppDelegate+ClosedItemHistory.swift in Sources */ = {isa = PBXBuildFile; fileRef = C4160A030000000000000002 /* AppDelegate+ClosedItemHistory.swift */; }; C54860050000000000000001 /* AppDelegate+CmuxNavigationDeepLinks.swift in Sources */ = {isa = PBXBuildFile; fileRef = C54860050000000000000002 /* AppDelegate+CmuxNavigationDeepLinks.swift */; }; @@ -1884,6 +1885,7 @@ C0DE71B10000000000000001 /* AppDelegate+AgentChatNotifications.swift in Sources F4350A130000000000000001 /* AppBundleIconPersistencePolicy.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = App/AppBundleIconPersistencePolicy.swift; sourceTree = ""; }; C0DE45AC0000000000000002 /* AppDelegate+AgentChat.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "AppDelegate+AgentChat.swift"; sourceTree = ""; }; C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "AppDelegate+AgentChatNotifications.swift"; sourceTree = ""; }; + C0DE76990000000000000002 /* AppDelegate+BrowserWebExtensionShortcutRouting.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "AppDelegate+BrowserWebExtensionShortcutRouting.swift"; sourceTree = ""; }; C4A570010000000000000002 /* AppDelegate+CanvasShortcutRouting.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "AppDelegate+CanvasShortcutRouting.swift"; sourceTree = ""; }; C4160A030000000000000002 /* AppDelegate+ClosedItemHistory.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "AppDelegate+ClosedItemHistory.swift"; sourceTree = ""; }; C54860050000000000000002 /* AppDelegate+CmuxNavigationDeepLinks.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "AppDelegate+CmuxNavigationDeepLinks.swift"; sourceTree = ""; }; @@ -4218,6 +4220,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = A5001090 /* AppDelegate.swift */, C0DE45AC0000000000000002 /* AppDelegate+AgentChat.swift */, 7725A0027725A0027725A002 /* AppDelegate+ResolvedIconRendering.swift */, + C0DE76990000000000000002 /* AppDelegate+BrowserWebExtensionShortcutRouting.swift */, C0DE71A00000000000000002 /* AgentChatThemeSync.swift */, C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */, B1F0C0080000000000000002 /* AppDelegateDetachedInspectorClose.swift */, @@ -5757,6 +5760,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = F4350A110000000000000001 /* AppBundleIconPersistencePolicy.swift in Sources */, C0DE45AC0000000000000001 /* AppDelegate+AgentChat.swift in Sources */, C0DE71B10000000000000001 /* AppDelegate+AgentChatNotifications.swift in Sources */, + C0DE76990000000000000001 /* AppDelegate+BrowserWebExtensionShortcutRouting.swift in Sources */, C4A570010000000000000001 /* AppDelegate+CanvasShortcutRouting.swift in Sources */, C4160A030000000000000001 /* AppDelegate+ClosedItemHistory.swift in Sources */, C54860050000000000000001 /* AppDelegate+CmuxNavigationDeepLinks.swift in Sources */, From d56edb2c531586cf5b3cb7760efd7d11d1877ca6 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 16:02:56 -0700 Subject: [PATCH 38/51] test(browser): cover clearing stale extension errors --- .../BrowserWebExtensionsCardStateTests.swift | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Packages/macOS/CmuxSettingsUI/Tests/CmuxSettingsUITests/BrowserWebExtensionsCardStateTests.swift b/Packages/macOS/CmuxSettingsUI/Tests/CmuxSettingsUITests/BrowserWebExtensionsCardStateTests.swift index 7926b9396aeb..015bffbdf984 100644 --- a/Packages/macOS/CmuxSettingsUI/Tests/CmuxSettingsUITests/BrowserWebExtensionsCardStateTests.swift +++ b/Packages/macOS/CmuxSettingsUI/Tests/CmuxSettingsUITests/BrowserWebExtensionsCardStateTests.swift @@ -33,6 +33,10 @@ struct BrowserWebExtensionsCardStateTests { #expect(state.effectiveEntries(observed: observed) == observed) #expect(state.hasWriteError) + let externallyUpdated = [entry(id: "external")] + state.reconcileObservedEntries(externallyUpdated) + #expect(!state.hasWriteError) + state.beginWrite(entries: pending, writeID: 3) #expect(!state.hasWriteError) } From 63fd83a028a2e42393ab6aea3a3d73bd78bc2519 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 16:03:40 -0700 Subject: [PATCH 39/51] fix(browser): reconcile extension feedback state --- .../Sections/BrowserWebExtensionsCardState.swift | 8 +++++--- Sources/Panels/BrowserWebExtensionWindowAdapter.swift | 2 +- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCardState.swift b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCardState.swift index 0d9708de4bc8..81e7d6637835 100644 --- a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCardState.swift +++ b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCardState.swift @@ -28,9 +28,11 @@ struct BrowserWebExtensionsCardState { } mutating func reconcileObservedEntries(_ entries: [BrowserWebExtensionEntry]) { - guard entries == pendingEntries else { return } - pendingEntries = nil - pendingWriteID = nil + if entries == pendingEntries { + pendingEntries = nil + pendingWriteID = nil + } + hasWriteError = false } mutating func reconcileWriteResult(completedWriteID: UInt64, failed: Bool) { diff --git a/Sources/Panels/BrowserWebExtensionWindowAdapter.swift b/Sources/Panels/BrowserWebExtensionWindowAdapter.swift index 0b3af2122fbd..1f1a12a1c3ad 100644 --- a/Sources/Panels/BrowserWebExtensionWindowAdapter.swift +++ b/Sources/Panels/BrowserWebExtensionWindowAdapter.swift @@ -56,7 +56,7 @@ final class BrowserWebExtensionWindowAdapter: NSObject, WKWebExtensionWindow { )) return } - NSApp.activate(ignoringOtherApps: false) + NSApp.activate() hostWindow.makeKeyAndOrderFront(nil) completionHandler(nil) } From 55086070e2c97fc013c99f07fa958c39b18aae69 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 16:48:22 -0700 Subject: [PATCH 40/51] test(browser): cover extension lifecycle review regressions --- .../BrowserDeveloperToolsLifecycleTests.swift | 29 ++++++++ ...serWebExtensionReviewRegressionTests.swift | 72 +++++++++++++++++++ 2 files changed, 101 insertions(+) diff --git a/cmuxTests/BrowserDeveloperToolsLifecycleTests.swift b/cmuxTests/BrowserDeveloperToolsLifecycleTests.swift index 8914a0f548b7..d628790868c7 100644 --- a/cmuxTests/BrowserDeveloperToolsLifecycleTests.swift +++ b/cmuxTests/BrowserDeveloperToolsLifecycleTests.swift @@ -10,6 +10,35 @@ import WebKit @MainActor extension BrowserDeveloperToolsVisibilityPersistenceTests { + func testWebExtensionWebViewReplacementClosesAndRestoresDeveloperTools() throws { + let (panel, inspector) = makePanelWithInspector() + defer { closeBrowserPanel(panel) } + XCTAssertTrue(panel.showDeveloperTools()) + XCTAssertTrue(panel.preferredDeveloperToolsVisible) + let oldWebView = panel.webView + let extensionURL = try XCTUnwrap(URL(string: "webkit-extension://cmux-test/options.html")) + + panel.navigateFromWebExtension( + to: extensionURL, + webViewConfiguration: WKWebViewConfiguration() + ) + + XCTAssertFalse(panel.webView === oldWebView) + XCTAssertEqual( + inspector.closeCount, + 1, + "Replacing the inspected WebView must close its inspector before releasing the old view" + ) + XCTAssertTrue( + panel.preferredDeveloperToolsVisible, + "A live context swap should preserve the user's visible Developer Tools intent" + ) + XCTAssertTrue( + panel.hasPendingDeveloperToolsRefreshAfterAttach(), + "The replacement WebView should restore Developer Tools after it attaches" + ) + } + func testDetachedInspectorWillCloseDuringDockBackAdoptsAttachedInspector() { let (panel, inspector) = makePanelWithInspector() defer { closeBrowserPanel(panel) } diff --git a/cmuxTests/BrowserWebExtensionReviewRegressionTests.swift b/cmuxTests/BrowserWebExtensionReviewRegressionTests.swift index e75f6b9e82bb..2dab0cf89258 100644 --- a/cmuxTests/BrowserWebExtensionReviewRegressionTests.swift +++ b/cmuxTests/BrowserWebExtensionReviewRegressionTests.swift @@ -69,6 +69,78 @@ struct BrowserWebExtensionReviewRegressionTests { KeyboardShortcutSettings.setShortcut(.unbound, for: action) #expect(appDelegate.shouldOfferBrowserWebExtensionCommand(event)) + + let plainTypingEvent = try #require(NSEvent.keyEvent( + with: .keyDown, + location: .zero, + modifierFlags: [], + timestamp: ProcessInfo.processInfo.systemUptime, + windowNumber: 0, + context: nil, + characters: "a", + charactersIgnoringModifiers: "a", + isARepeat: false, + keyCode: 0 + )) + #expect(!appDelegate.shouldOfferBrowserWebExtensionCommand(plainTypingEvent)) + } + + @MainActor + @Test + @available(macOS 15.4, *) + func unchangedMetadataDoesNotInvalidateExtensionActions() async throws { + let support = BrowserWebExtensionSupport() + let panel = BrowserPanel(workspaceId: UUID(), browserWebExtensionHost: support) + support.register(panel: panel) + defer { + support.unregister(panelID: panel.id) + panel.close() + } + let invalidation = try #require(support.actionSnapshotInvalidationsByPanelID[panel.id]) + let initialRevision = invalidation.revision + + support.noteTabMetadataChanged(panelID: panel.id) + await Task.yield() + await Task.yield() + + #expect(invalidation.revision == initialRevision) + } + + @MainActor + @Test + @available(macOS 15.4, *) + func sameExtensionLinkOpensSiblingTabWithOwningContext() throws { + let wasBrowserDisabled = BrowserAvailabilitySettings.isDisabled() + BrowserAvailabilitySettings.setDisabled(false) + defer { BrowserAvailabilitySettings.setDisabled(wasBrowserDisabled) } + + let appDelegate = try #require(AppDelegate.shared) + let previousTabManager = appDelegate.tabManager + let extensionURL = try #require(URL(string: "webkit-extension://cmux-test/options.html")) + let siblingURL = try #require(URL(string: "webkit-extension://cmux-test/vault.html")) + let host = BrowserWebExtensionReviewTestHost(extensionHost: extensionURL.host) + let tabManager = TabManager(browserWebExtensionHost: host) + appDelegate.tabManager = tabManager + defer { appDelegate.tabManager = previousTabManager } + + let workspace = try #require(tabManager.selectedWorkspace) + defer { workspace.teardownAllPanels() } + let paneID = try #require(workspace.bonsplitController.allPaneIds.first) + let sourcePanel = try #require(workspace.newBrowserSurface( + inPane: paneID, + url: extensionURL, + focus: false + )) + #expect(sourcePanel.webExtensionPageContextIdentifier == host.contextIdentifier) + + sourcePanel.openLinkInNewTab(url: siblingURL) + + let siblingPanel = try #require( + workspace.panels.values + .compactMap { $0 as? BrowserPanel } + .first { $0.id != sourcePanel.id } + ) + #expect(siblingPanel.webExtensionPageContextIdentifier == host.contextIdentifier) } @MainActor From 8f0f20f5d851bc7a0e3dd63e91f3570f612ed5b6 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 19:35:47 -0700 Subject: [PATCH 41/51] fix(browser): address extension lifecycle review regressions - Require a primary modifier before scanning all shortcut actions in the web-extension command routing hot path - Preserve developer tools visibility intent across web-extension webview replacements - Propagate the web-extension navigation context to page-initiated new tabs only when the target stays in the same extension context - Coalesce tab metadata change notifications and report only properties that actually changed; surface tab mute state to extension contexts Co-Authored-By: Claude Fable 5 --- ...e+BrowserWebExtensionShortcutRouting.swift | 7 ++ Sources/Panels/BrowserPanel.swift | 69 ++------------- .../BrowserPanelDeveloperToolsLifecycle.swift | 23 +++++ ...rWebExtensionNavigationConfiguration.swift | 83 +++++++++++++++++++ .../Panels/BrowserWebExtensionSupport.swift | 67 ++++++++++++++- .../BrowserWebExtensionTabAdapter.swift | 4 + Sources/Workspace+DockBrowserLookup.swift | 22 +++-- 7 files changed, 203 insertions(+), 72 deletions(-) diff --git a/Sources/AppDelegate+BrowserWebExtensionShortcutRouting.swift b/Sources/AppDelegate+BrowserWebExtensionShortcutRouting.swift index 620767e6cdf2..015178d5c331 100644 --- a/Sources/AppDelegate+BrowserWebExtensionShortcutRouting.swift +++ b/Sources/AppDelegate+BrowserWebExtensionShortcutRouting.swift @@ -3,6 +3,13 @@ import AppKit extension AppDelegate { /// Extension manifest commands run only after configured cmux shortcuts decline the event. func shouldOfferBrowserWebExtensionCommand(_ event: NSEvent) -> Bool { + let flags = event.modifierFlags.intersection(.deviceIndependentFlagsMask) + // Manifest keyboard commands on macOS require a primary modifier. Keep + // ordinary typing off the all-actions conflict scan in this hot path. + guard !flags.intersection([.command, .control, .option]).isEmpty else { + return false + } + let shortcutContext = shortcutEventFocusContext(event).shortcutContext for action in KeyboardShortcutSettings.Action.allCases { guard action != .showHideAllWindows, diff --git a/Sources/Panels/BrowserPanel.swift b/Sources/Panels/BrowserPanel.swift index 583b2bc735fb..d552d2e73a99 100644 --- a/Sources/Panels/BrowserPanel.swift +++ b/Sources/Panels/BrowserPanel.swift @@ -5866,6 +5866,7 @@ final class BrowserPanel: Panel, ObservableObject { let oldWebView = webView let desiredZoom = max(minPageZoom, min(maxPageZoom, oldWebView.pageZoom)) let reason = contextIdentifier == nil ? "webExtensionNavigation.leave" : "webExtensionNavigation.enter" + let restoreDeveloperTools = preferredDeveloperToolsVisible || isDeveloperToolsVisible() #if DEBUG cmuxDebugLog( @@ -5874,6 +5875,7 @@ final class BrowserPanel: Panel, ObservableObject { ) #endif + prepareDeveloperToolsForWebViewReplacement(preserveVisibleIntent: restoreDeveloperTools) detachWebViewObservers() clearBrowserFocusMode(reason: reason) faviconTask?.cancel() @@ -5916,6 +5918,9 @@ final class BrowserPanel: Panel, ObservableObject { applyProxyConfigurationIfAvailable() applyBrowserThemeModeIfNeeded() refreshNavigationAvailability() + if restoreDeveloperTools { + requestDeveloperToolsRefreshAfterNextAttach(reason: reason) + } } private func remoteProxyPreparedRequest(from request: URLRequest, logScope: String) -> URLRequest { @@ -6449,70 +6454,6 @@ extension BrowserPanel { ) } - /// Opens a request in a sibling browser tab without dropping request metadata. - func openLinkInNewTab(request: URLRequest, bypassInsecureHTTPHostOnce: String? = nil) { - guard let seed = browserNewTabNavigationSeed( - from: request, - bypassInsecureHTTPHostOnce: bypassInsecureHTTPHostOnce - ) else { - return - } -#if DEBUG - cmuxDebugLog( - "browser.newTab.open.begin panel=\(id.uuidString.prefix(5)) " + - "workspace=\(workspaceId.uuidString.prefix(5)) url=\(browserNavigationDebugURL(seed.url)) bypass=\(seed.bypassInsecureHTTPHostOnce ?? "nil")" - ) -#endif - guard BrowserAvailabilitySettings.isEnabled() else { - _ = NSWorkspace.shared.open(seed.url) -#if DEBUG - cmuxDebugLog("browser.newTab.open.external panel=\(id.uuidString.prefix(5)) reason=browser_disabled") -#endif - return - } - if Workspace.openDockBrowserLinkInNewTabIfNeeded(panel: self, seed: seed) { return } - guard let app = AppDelegate.shared else { -#if DEBUG - cmuxDebugLog("browser.newTab.open.abort panel=\(id.uuidString.prefix(5)) reason=missingAppDelegate") -#endif - return - } - guard let workspace = app.workspaceContainingPanel( - panelId: id, - preferredWorkspaceId: workspaceId - )?.workspace else { -#if DEBUG - cmuxDebugLog("browser.newTab.open.abort panel=\(id.uuidString.prefix(5)) reason=workspaceMissing") -#endif - return - } - guard let paneId = workspace.paneId(forPanelId: id) else { -#if DEBUG - cmuxDebugLog("browser.newTab.open.abort panel=\(id.uuidString.prefix(5)) reason=paneMissing") -#endif - return - } - guard let _ = workspace.newBrowserSurface( - inPane: paneId, - url: seed.url, - initialRequest: seed.initialRequest, - focus: true, - preferredProfileID: profileID, - bypassInsecureHTTPHostOnce: seed.bypassInsecureHTTPHostOnce, allowWebExtensionInitialNavigationConfiguration: false - ) else { -#if DEBUG - cmuxDebugLog("browser.newTab.open.abort panel=\(id.uuidString.prefix(5)) reason=newPanelFailed") -#endif - return - } -#if DEBUG - cmuxDebugLog( - "browser.newTab.open.done panel=\(id.uuidString.prefix(5)) " + - "workspace=\(workspace.id.uuidString.prefix(5)) pane=\(paneId.id.uuidString.prefix(5))" - ) -#endif - } - var currentURLForTabDuplication: URL? { resolvedCurrentSessionHistoryURL() ?? Self.remoteProxyDisplayURL(for: webView.url) diff --git a/Sources/Panels/BrowserPanelDeveloperToolsLifecycle.swift b/Sources/Panels/BrowserPanelDeveloperToolsLifecycle.swift index e2773dbe87a9..84b0e7b4f97c 100644 --- a/Sources/Panels/BrowserPanelDeveloperToolsLifecycle.swift +++ b/Sources/Panels/BrowserPanelDeveloperToolsLifecycle.swift @@ -2,6 +2,29 @@ import AppKit @MainActor extension BrowserPanel { + func prepareDeveloperToolsForWebViewReplacement(preserveVisibleIntent: Bool) { + developerToolsTransitionSettleWorkItem?.cancel() + developerToolsTransitionSettleWorkItem = nil + pendingDeveloperToolsTransitionTargetVisible = nil + developerToolsTransitionTargetVisible = nil + cancelPendingDeveloperToolsVisibilityLossCheck() + cancelDetachedDeveloperToolsWindowCloseResolution() + cancelDetachedDeveloperToolsWindowDismissal() + developerToolsDockControlNormalizationTask?.cancel() + developerToolsDockControlNormalizationTask = nil + cancelDeveloperToolsRestoreRetry() + + _ = WebViewInspectorTeardown.closeInspector(for: webView) + // WebKit can synchronously post the detached inspector's close while + // tearing down the old view. It must not clear the replacement intent. + cancelDetachedDeveloperToolsWindowCloseResolution() + developerToolsDetachedOpenGraceDeadline = nil + developerToolsLastKnownVisibleAt = nil + developerToolsLastAttachedHostAt = nil + setPreferredDeveloperToolsVisible(preserveVisibleIntent) + developerToolsPreservedVisibleIntentForNextAttach = preserveVisibleIntent + } + func detachedDeveloperToolsWindowsForPanel() -> [NSWindow] { NSApp.windows.filter { ($0.isVisible || $0.isMiniaturized) && detachedDeveloperToolsWindowBelongsToPanel($0) } } diff --git a/Sources/Panels/BrowserWebExtensionNavigationConfiguration.swift b/Sources/Panels/BrowserWebExtensionNavigationConfiguration.swift index 4818443947e8..bc9679ff2942 100644 --- a/Sources/Panels/BrowserWebExtensionNavigationConfiguration.swift +++ b/Sources/Panels/BrowserWebExtensionNavigationConfiguration.swift @@ -1,3 +1,4 @@ +import AppKit import WebKit struct BrowserWebExtensionNavigationConfiguration { @@ -38,6 +39,88 @@ extension BrowserPanel { return targetContextIdentifier != webExtensionPageContextIdentifier } + func allowsWebExtensionContextForPageInitiatedNewTab(to url: URL) -> Bool { + guard let sourceContextIdentifier = webExtensionPageContextIdentifier, + let targetContextIdentifier = browserWebExtensionHost? + .webViewConfiguration(forNavigatingTo: url)? + .contextIdentifier else { + return false + } + return targetContextIdentifier == sourceContextIdentifier + } + + /// Opens a request in a sibling browser tab without dropping request metadata. + func openLinkInNewTab(request: URLRequest, bypassInsecureHTTPHostOnce: String? = nil) { + guard let seed = browserNewTabNavigationSeed( + from: request, + bypassInsecureHTTPHostOnce: bypassInsecureHTTPHostOnce + ) else { + return + } + let allowWebExtensionContext = allowsWebExtensionContextForPageInitiatedNewTab(to: seed.url) +#if DEBUG + cmuxDebugLog( + "browser.newTab.open.begin panel=\(id.uuidString.prefix(5)) " + + "workspace=\(workspaceId.uuidString.prefix(5)) url=\(browserNavigationDebugURL(seed.url)) bypass=\(seed.bypassInsecureHTTPHostOnce ?? "nil")" + ) +#endif + guard BrowserAvailabilitySettings.isEnabled() else { + _ = NSWorkspace.shared.open(seed.url) +#if DEBUG + cmuxDebugLog("browser.newTab.open.external panel=\(id.uuidString.prefix(5)) reason=browser_disabled") +#endif + return + } + if Workspace.openDockBrowserLinkInNewTabIfNeeded( + panel: self, + seed: seed, + allowWebExtensionContext: allowWebExtensionContext + ) { + return + } + guard let app = AppDelegate.shared else { +#if DEBUG + cmuxDebugLog("browser.newTab.open.abort panel=\(id.uuidString.prefix(5)) reason=missingAppDelegate") +#endif + return + } + guard let workspace = app.workspaceContainingPanel( + panelId: id, + preferredWorkspaceId: workspaceId + )?.workspace else { +#if DEBUG + cmuxDebugLog("browser.newTab.open.abort panel=\(id.uuidString.prefix(5)) reason=workspaceMissing") +#endif + return + } + guard let paneId = workspace.paneId(forPanelId: id) else { +#if DEBUG + cmuxDebugLog("browser.newTab.open.abort panel=\(id.uuidString.prefix(5)) reason=paneMissing") +#endif + return + } + guard let _ = workspace.newBrowserSurface( + inPane: paneId, + url: seed.url, + initialRequest: seed.initialRequest, + focus: true, + preferredProfileID: profileID, + bypassInsecureHTTPHostOnce: seed.bypassInsecureHTTPHostOnce, + allowWebExtensionInitialNavigationConfiguration: allowWebExtensionContext + ) else { +#if DEBUG + cmuxDebugLog("browser.newTab.open.abort panel=\(id.uuidString.prefix(5)) reason=newPanelFailed") +#endif + return + } +#if DEBUG + cmuxDebugLog( + "browser.newTab.open.done panel=\(id.uuidString.prefix(5)) " + + "workspace=\(workspace.id.uuidString.prefix(5)) pane=\(paneId.id.uuidString.prefix(5))" + ) +#endif + } + func canOpenPageInitiatedWebExtensionExitURL(_ url: URL) -> Bool { guard let scheme = url.scheme?.lowercased() else { return true } return scheme == "http" || scheme == "https" || scheme == "about" diff --git a/Sources/Panels/BrowserWebExtensionSupport.swift b/Sources/Panels/BrowserWebExtensionSupport.swift index 7f0dbaf6c524..36451b4dcf83 100644 --- a/Sources/Panels/BrowserWebExtensionSupport.swift +++ b/Sources/Panels/BrowserWebExtensionSupport.swift @@ -18,6 +18,32 @@ import WebKit @MainActor @Observable final class BrowserWebExtensionSupport: NSObject, BrowserWebExtensionHosting { + private struct TabMetadataSnapshot: Equatable { + let title: String? + let url: URL? + let isLoading: Bool + let isMuted: Bool + + @MainActor + init(panel: BrowserPanel) { + title = panel.webView.title + url = panel.webView.url + isLoading = panel.webView.isLoading + isMuted = panel.isMuted + } + + func changedProperties( + comparedTo previous: TabMetadataSnapshot + ) -> WKWebExtension.TabChangedProperties { + var properties: WKWebExtension.TabChangedProperties = [] + if title != previous.title { properties.insert(.title) } + if url != previous.url { properties.insert(.URL) } + if isLoading != previous.isLoading { properties.insert(.loading) } + if isMuted != previous.isMuted { properties.insert(.muted) } + return properties + } + } + /// Fixed identifier so extension storage (e.g. the Bitwarden vault cache) /// persists across app launches. private static let controllerIdentifier = UUID(uuidString: "8C0FDE2B-6EFD-4E8C-9E70-8E7D0A4C51B7")! @@ -54,6 +80,12 @@ final class BrowserWebExtensionSupport: NSObject, BrowserWebExtensionHosting { @ObservationIgnored var tabAdapters: [UUID: BrowserWebExtensionTabAdapter] = [:] @ObservationIgnored + private var tabMetadataSnapshotsByPanelID: [UUID: TabMetadataSnapshot] = [:] + @ObservationIgnored + private var pendingTabMetadataPanelIDs: Set = [] + @ObservationIgnored + private var tabMetadataFlushTask: Task? + @ObservationIgnored var actionSnapshotInvalidationsByPanelID: [UUID: BrowserWebExtensionActionSnapshotInvalidation] = [:] @ObservationIgnored var permissionObserverTokensByEntryID: [String: [NSObjectProtocol]] = [:] @@ -100,6 +132,7 @@ final class BrowserWebExtensionSupport: NSObject, BrowserWebExtensionHosting { deinit { settingsObservationTask?.cancel() + tabMetadataFlushTask?.cancel() if let browserAvailabilityObserverToken { NotificationCenter.default.removeObserver(browserAvailabilityObserverToken) } @@ -199,6 +232,7 @@ final class BrowserWebExtensionSupport: NSObject, BrowserWebExtensionHosting { guard tabAdapters[panel.id] == nil else { return } let adapter = BrowserWebExtensionTabAdapter(panel: panel, support: self) tabAdapters[panel.id] = adapter + tabMetadataSnapshotsByPanelID[panel.id] = TabMetadataSnapshot(panel: panel) actionSnapshotInvalidationsByPanelID[panel.id] = BrowserWebExtensionActionSnapshotInvalidation() orderedPanelIDs.append(panel.id) if activePanelID == nil { activePanelID = panel.id } @@ -208,6 +242,8 @@ final class BrowserWebExtensionSupport: NSObject, BrowserWebExtensionHosting { func unregister(panelID: UUID) { guard let adapter = tabAdapters.removeValue(forKey: panelID) else { return } + tabMetadataSnapshotsByPanelID.removeValue(forKey: panelID) + pendingTabMetadataPanelIDs.remove(panelID) orderedPanelIDs.removeAll { $0 == panelID } activePanelIDsByWindow = activePanelIDsByWindow.filter { $0.value != panelID } actionSnapshotInvalidationsByPanelID.removeValue(forKey: panelID) @@ -275,9 +311,34 @@ final class BrowserWebExtensionSupport: NSObject, BrowserWebExtensionHosting { } func noteTabMetadataChanged(panelID: UUID) { - guard let adapter = tabAdapters[panelID] else { return } - controller.didChangeTabProperties([.title, .URL, .loading, .muted], for: adapter) - refreshActionSnapshots(for: panelID) + guard tabAdapters[panelID] != nil else { return } + pendingTabMetadataPanelIDs.insert(panelID) + guard tabMetadataFlushTask == nil else { return } + tabMetadataFlushTask = Task { @MainActor [weak self] in + await Task.yield() + guard !Task.isCancelled, let self else { return } + self.tabMetadataFlushTask = nil + self.flushPendingTabMetadataChanges() + } + } + + private func flushPendingTabMetadataChanges() { + let panelIDs = pendingTabMetadataPanelIDs + pendingTabMetadataPanelIDs.removeAll() + for panelID in panelIDs { + guard let adapter = tabAdapters[panelID], let panel = adapter.panel else { + tabMetadataSnapshotsByPanelID.removeValue(forKey: panelID) + continue + } + let current = TabMetadataSnapshot(panel: panel) + guard let previous = tabMetadataSnapshotsByPanelID.updateValue(current, forKey: panelID) else { + continue + } + let properties = current.changedProperties(comparedTo: previous) + guard !properties.isEmpty else { continue } + controller.didChangeTabProperties(properties, for: adapter) + refreshActionSnapshots(for: panelID) + } } func tabAdapter(for panelID: UUID) -> BrowserWebExtensionTabAdapter? { diff --git a/Sources/Panels/BrowserWebExtensionTabAdapter.swift b/Sources/Panels/BrowserWebExtensionTabAdapter.swift index c9c01e4aa223..a52042089296 100644 --- a/Sources/Panels/BrowserWebExtensionTabAdapter.swift +++ b/Sources/Panels/BrowserWebExtensionTabAdapter.swift @@ -43,6 +43,10 @@ final class BrowserWebExtensionTabAdapter: NSObject, WKWebExtensionTab { return !webView.isLoading } + func isMuted(for context: WKWebExtensionContext) -> Bool { + panel?.isMuted ?? false + } + func isSelected(for context: WKWebExtensionContext) -> Bool { support?.activePanelID == panelID } diff --git a/Sources/Workspace+DockBrowserLookup.swift b/Sources/Workspace+DockBrowserLookup.swift index ad0c2b4f67c4..0f0fd06ae35a 100644 --- a/Sources/Workspace+DockBrowserLookup.swift +++ b/Sources/Workspace+DockBrowserLookup.swift @@ -39,7 +39,11 @@ extension Workspace { return true } - func openDockBrowserLinkInNewTab(panel: BrowserPanel, seed: BrowserNewTabNavigationSeed) -> Bool { + func openDockBrowserLinkInNewTab( + panel: BrowserPanel, + seed: BrowserNewTabNavigationSeed, + allowWebExtensionContext: Bool + ) -> Bool { guard let dock = _dockSplit, let paneId = dock.paneId(forPanelId: panel.id) else { return false } return dock.newSurface( kind: .browser, @@ -49,11 +53,15 @@ extension Workspace { focus: true, preferredProfileID: panel.profileID, bypassInsecureHTTPHostOnce: seed.bypassInsecureHTTPHostOnce, - allowWebExtensionInitialNavigationConfiguration: false + allowWebExtensionInitialNavigationConfiguration: allowWebExtensionContext ) != nil } - static func openDockBrowserLinkInNewTabIfNeeded(panel: BrowserPanel, seed: BrowserNewTabNavigationSeed) -> Bool { + static func openDockBrowserLinkInNewTabIfNeeded( + panel: BrowserPanel, + seed: BrowserNewTabNavigationSeed, + allowWebExtensionContext: Bool + ) -> Bool { guard let app = AppDelegate.shared else { return false } if let dock = app.windowDockContainingPanel(panel.id), dock.browserPanel(for: panel.id) === panel, @@ -66,12 +74,16 @@ extension Workspace { focus: true, preferredProfileID: panel.profileID, bypassInsecureHTTPHostOnce: seed.bypassInsecureHTTPHostOnce, - allowWebExtensionInitialNavigationConfiguration: false + allowWebExtensionInitialNavigationConfiguration: allowWebExtensionContext ) != nil } guard let manager = app.tabManagerFor(tabId: panel.workspaceId) ?? app.tabManager, let workspace = manager.tabs.first(where: { $0.id == panel.workspaceId }) else { return false } - return workspace.openDockBrowserLinkInNewTab(panel: panel, seed: seed) + return workspace.openDockBrowserLinkInNewTab( + panel: panel, + seed: seed, + allowWebExtensionContext: allowWebExtensionContext + ) } } From 4d3ad7356605e27855e5323f704e0a4b88f7ca73 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 21:11:23 -0700 Subject: [PATCH 42/51] fix: hoist web-extension host creation out of StateObject autoclosure StateObject(wrappedValue:) takes an escaping autoclosure, which cannot capture mutating self in the App initializer. Co-Authored-By: Claude Fable 5 --- Sources/cmuxApp.swift | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Sources/cmuxApp.swift b/Sources/cmuxApp.swift index 9d051007d8c9..d43a5968cb13 100644 --- a/Sources/cmuxApp.swift +++ b/Sources/cmuxApp.swift @@ -199,6 +199,10 @@ struct cmuxApp: App { KeyboardShortcutSettings.settingsFileStore.applyDeferredManagedDefaultSideEffects() StartupBreadcrumbLog.append("app.init.keyboardShortcuts.sideEffectsApplied") StartupBreadcrumbLog.append("app.init.tabManager.begin") + let browserWebExtensionHost = makeBrowserWebExtensionHostAtLaunch( + jsonStore: settingsRuntime.jsonStore, + catalog: settingsCatalog + ) _tabManager = StateObject(wrappedValue: TabManager(browserWebExtensionHost: browserWebExtensionHost)) StartupBreadcrumbLog.append("app.init.tabManager.complete") // Migrate legacy and old-format socket mode values to the new enum. From fc8e3367f9cb5d9ed422bb45f5ab7bbdd22c016b Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 21:46:35 -0700 Subject: [PATCH 43/51] test(browser): give each fake extension navigation a fresh configuration MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The fake host returned one shared WKWebViewConfiguration for every extension-page navigation, so the sibling-tab panel re-added fixed-name script message handlers (cmuxReactGrab) to the same user content controller — WebKit throws NSInvalidArgumentException and the app host crashes. Production hands out a configuration per navigation via WKWebExtensionContext.webViewConfiguration; mirror that. Co-Authored-By: Claude Fable 5 --- cmuxTests/BrowserWebExtensionReviewRegressionTests.swift | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/cmuxTests/BrowserWebExtensionReviewRegressionTests.swift b/cmuxTests/BrowserWebExtensionReviewRegressionTests.swift index 2dab0cf89258..ac8e91c6a245 100644 --- a/cmuxTests/BrowserWebExtensionReviewRegressionTests.swift +++ b/cmuxTests/BrowserWebExtensionReviewRegressionTests.swift @@ -175,7 +175,6 @@ struct BrowserWebExtensionReviewRegressionTests { private final class BrowserWebExtensionReviewTestHost: BrowserWebExtensionHosting { private let extensionHost: String? private let contextToken = NSObject() - private let configuration = WKWebViewConfiguration() init(extensionHost: String?) { self.extensionHost = extensionHost @@ -190,9 +189,13 @@ private final class BrowserWebExtensionReviewTestHost: BrowserWebExtensionHostin func webViewConfiguration(forNavigatingTo url: URL) -> BrowserWebExtensionNavigationConfiguration? { guard url.scheme?.lowercased() == "webkit-extension", url.host == extensionHost else { return nil } + // Mirror WKWebExtensionContext.webViewConfiguration: a fresh configuration + // (with its own user content controller) per navigation. A single shared + // instance would make every second extension-page panel re-add fixed-name + // script message handlers to the same controller, which WebKit rejects. return BrowserWebExtensionNavigationConfiguration( contextIdentifier: contextIdentifier, - webViewConfiguration: configuration + webViewConfiguration: WKWebViewConfiguration() ) } From 32a765091f76991e68cf7cd926d441d7ac37b27b Mon Sep 17 00:00:00 2001 From: lawrencecchen Date: Thu, 9 Jul 2026 21:59:20 -0700 Subject: [PATCH 44/51] =?UTF-8?q?Route=20extension=20commands=20(e.g.=20Bi?= =?UTF-8?q?twarden=20=E2=8C=98=E2=87=A7L)=20while=20browser=20focus=20mode?= =?UTF-8?q?=20is=20active?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Focus mode suspends every configured cmux shortcut at the app-level monitor, but the web-extension command offer still declined events those suspended shortcuts claim, and the focus-mode branch of CmuxWebView.performKeyEquivalent force-consumed command equivalents for the page before the offer ran. Net effect: with the default ⌘⇧L Open Browser binding, Bitwarden's autofill command could never fire. Now manifest commands are offered first in the focus-mode forward path (browser-chrome shortcuts outrank page content, as in Safari), and the conflict scan is skipped when focus mode owns the event. Outside focus mode nothing changes: configured cmux shortcuts still win. The focus-mode key-equivalent handling moves to CmuxWebViewFocusModeKeyEquivalent.swift so CmuxWebView.swift stays inside its file-length budget. --- ...e+BrowserWebExtensionShortcutRouting.swift | 19 +++++++ Sources/AppDelegate.swift | 2 +- Sources/Panels/CmuxWebView.swift | 27 ++-------- .../CmuxWebViewFocusModeKeyEquivalent.swift | 44 ++++++++++++++++ cmux.xcodeproj/project.pbxproj | 4 ++ ...serWebExtensionReviewRegressionTests.swift | 50 +++++++++++++++++++ 6 files changed, 123 insertions(+), 23 deletions(-) create mode 100644 Sources/Panels/CmuxWebViewFocusModeKeyEquivalent.swift diff --git a/Sources/AppDelegate+BrowserWebExtensionShortcutRouting.swift b/Sources/AppDelegate+BrowserWebExtensionShortcutRouting.swift index 015178d5c331..d7b7f89787cf 100644 --- a/Sources/AppDelegate+BrowserWebExtensionShortcutRouting.swift +++ b/Sources/AppDelegate+BrowserWebExtensionShortcutRouting.swift @@ -3,6 +3,16 @@ import AppKit extension AppDelegate { /// Extension manifest commands run only after configured cmux shortcuts decline the event. func shouldOfferBrowserWebExtensionCommand(_ event: NSEvent) -> Bool { + shouldOfferBrowserWebExtensionCommand( + event, + browserFocusModeActive: browserFocusModePanelForShortcutEvent(event) != nil + ) + } + + func shouldOfferBrowserWebExtensionCommand( + _ event: NSEvent, + browserFocusModeActive: Bool + ) -> Bool { let flags = event.modifierFlags.intersection(.deviceIndependentFlagsMask) // Manifest keyboard commands on macOS require a primary modifier. Keep // ordinary typing off the all-actions conflict scan in this hot path. @@ -10,6 +20,15 @@ extension AppDelegate { return false } + // Browser focus mode already bypasses every configured cmux shortcut at + // the app-level monitor (the page owns the keyboard), so a binding like + // the default ⌘⇧L Open Browser cannot fire here anyway. Let manifest + // commands (e.g. Bitwarden autofill) claim the stroke instead of running + // a conflict scan against shortcuts that are suspended. + if browserFocusModeActive { + return true + } + let shortcutContext = shortcutEventFocusContext(event).shortcutContext for action in KeyboardShortcutSettings.Action.allCases { guard action != .showHideAllWindows, diff --git a/Sources/AppDelegate.swift b/Sources/AppDelegate.swift index 3b5971dc0d57..014939241266 100644 --- a/Sources/AppDelegate.swift +++ b/Sources/AppDelegate.swift @@ -16063,7 +16063,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent return fr.isDescendant(of: panel.webView) } - private func browserFocusModePanelForShortcutEvent(_ event: NSEvent) -> BrowserPanel? { + func browserFocusModePanelForShortcutEvent(_ event: NSEvent) -> BrowserPanel? { // Resolve the panel from the web view that owns the responder chain (the // same resolver every other browser shortcut uses), not the selected pane: // context-menu / web-view-focus entrypoints can focus a WKWebView without diff --git a/Sources/Panels/CmuxWebView.swift b/Sources/Panels/CmuxWebView.swift index 2b107064f78b..91f425efded7 100644 --- a/Sources/Panels/CmuxWebView.swift +++ b/Sources/Panels/CmuxWebView.swift @@ -665,28 +665,11 @@ final class CmuxWebView: WKWebView { #endif let flags = event.modifierFlags.intersection(.deviceIndependentFlagsMask) let normalizedFlags = flags.subtracting([.numericPad, .function, .capsLock]) - if let decision = AppDelegate.shared?.handleBrowserFocusModeKeyEvent( - event, - webView: self, - source: "web.performKeyEquivalent" - ), decision != .inactive { - switch decision { - case .inactive: - break - case .forwardToWebView: - let isReturnKey = event.keyCode == 36 || event.keyCode == 76 - if (normalizedFlags.isEmpty && event.keyCode == 53) || - (isReturnKey && !normalizedFlags.contains(.command)) { - forwardKeyDownToWebKit(event) - return finish(true) - } - let result = super.performKeyEquivalent(with: event) - // While focus mode is active, the page gets the shortcut once and cmux/main-menu - // fallback must not see unhandled command equivalents. - return finish(result || normalizedFlags.contains(.command)) - case .consume: - return finish(true) - } + if let focusModeHandled = performBrowserFocusModeKeyEquivalent( + with: event, + normalizedFlags: normalizedFlags + ) { + return finish(focusModeHandled) } if event.keyCode == 36 || event.keyCode == 76 { diff --git a/Sources/Panels/CmuxWebViewFocusModeKeyEquivalent.swift b/Sources/Panels/CmuxWebViewFocusModeKeyEquivalent.swift new file mode 100644 index 000000000000..9b8cca03bf78 --- /dev/null +++ b/Sources/Panels/CmuxWebViewFocusModeKeyEquivalent.swift @@ -0,0 +1,44 @@ +import AppKit + +@MainActor +extension CmuxWebView { + /// Focus-mode disposition of a key equivalent: nil when browser focus mode + /// is not driving this event, otherwise whether it was handled. + func performBrowserFocusModeKeyEquivalent( + with event: NSEvent, + normalizedFlags: NSEvent.ModifierFlags + ) -> Bool? { + guard let decision = AppDelegate.shared?.handleBrowserFocusModeKeyEvent( + event, + webView: self, + source: "web.performKeyEquivalent" + ), decision != .inactive else { + return nil + } + switch decision { + case .inactive: + return nil + case .consume: + return true + case .forwardToWebView: + let isReturnKey = event.keyCode == 36 || event.keyCode == 76 + if (normalizedFlags.isEmpty && event.keyCode == 53) || + (isReturnKey && !normalizedFlags.contains(.command)) { + forwardKeyDownToWebKit(event) + return true + } + // Extension manifest commands (e.g. Bitwarden's ⌘⇧L autofill) are + // browser-chrome shortcuts, so they outrank page content the same + // way they do in Safari. Focus mode suspends configured cmux + // shortcuts, which is exactly when a binding like the default ⌘⇧L + // Open Browser frees the stroke for the extension. + if cmuxPerformBrowserWebExtensionCommandKeyEquivalent(event) { + return true + } + let result = super.performKeyEquivalent(with: event) + // While focus mode is active, the page gets the shortcut once and + // cmux/main-menu fallback must not see unhandled command equivalents. + return result || normalizedFlags.contains(.command) + } + } +} diff --git a/cmux.xcodeproj/project.pbxproj b/cmux.xcodeproj/project.pbxproj index 0825c5c33061..685a198f95a6 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -588,6 +588,7 @@ C0DE71B10000000000000001 /* AppDelegate+AgentChatNotifications.swift in Sources A5001500 /* CmuxWebView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5001510 /* CmuxWebView.swift */; }; D7C0DE00000000000000A103 /* CmuxWebViewContextMenuLinkCaptureTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D7C0DE00000000000000A104 /* CmuxWebViewContextMenuLinkCaptureTests.swift */; }; D0B1000CA1B2C3D4E5F60001 /* CmuxWebViewDragRoutingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D0B1000DA1B2C3D4E5F60001 /* CmuxWebViewDragRoutingTests.swift */; }; + C0DE59AB0000000000000002 /* CmuxWebViewFocusModeKeyEquivalent.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE59AB0000000000000001 /* CmuxWebViewFocusModeKeyEquivalent.swift */; }; C0DE58990000000000000004 /* CmuxWebViewKeyDownReentryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE58990000000000000002 /* CmuxWebViewKeyDownReentryTests.swift */; }; 7D5DA4DC51454ECDBF9AC978 /* CmuxWebViewMouseNavigationButtonTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 43F90FAF3FD44F11BF547BE9 /* CmuxWebViewMouseNavigationButtonTests.swift */; }; 5E55200000000000000000B3 /* CmuxWindowing in Frameworks */ = {isa = PBXBuildFile; productRef = 5E55200000000000000000B2 /* CmuxWindowing */; }; @@ -2318,6 +2319,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = A5001510 /* CmuxWebView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/CmuxWebView.swift; sourceTree = ""; }; D7C0DE00000000000000A104 /* CmuxWebViewContextMenuLinkCaptureTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CmuxWebViewContextMenuLinkCaptureTests.swift; sourceTree = ""; }; D0B1000DA1B2C3D4E5F60001 /* CmuxWebViewDragRoutingTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CmuxWebViewDragRoutingTests.swift; sourceTree = ""; }; + C0DE59AB0000000000000001 /* CmuxWebViewFocusModeKeyEquivalent.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/CmuxWebViewFocusModeKeyEquivalent.swift; sourceTree = ""; }; C0DE58990000000000000002 /* CmuxWebViewKeyDownReentryTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CmuxWebViewKeyDownReentryTests.swift; sourceTree = ""; }; 43F90FAF3FD44F11BF547BE9 /* CmuxWebViewMouseNavigationButtonTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CmuxWebViewMouseNavigationButtonTests.swift; sourceTree = ""; }; E30750000000000000000003 /* CmuxWorkspaceDefinition.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CmuxWorkspaceDefinition.swift; sourceTree = ""; }; @@ -4495,6 +4497,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = A5001428 /* FilePreviewPDFViewport.swift */, A5001510 /* CmuxWebView.swift */, C0DE58990000000000000001 /* BrowserWebKitKeyDownDispatch.swift */, + C0DE59AB0000000000000001 /* CmuxWebViewFocusModeKeyEquivalent.swift */, D7AB0000000000000000000A /* CmuxWebView+MoveTabToNewWorkspace.swift */, D7C0DE00000000000000A102 /* CmuxWebView+ContextMenuLinkCapture.swift */, C57B00080000000000000002 /* CustomSidebarPaneDataContextCache.swift */, @@ -5987,6 +5990,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = C6255D010000000000000001 /* CmuxWebView+ScriptedDownloads.swift in Sources */, C67540030000000000000001 /* CmuxWebView+SubframeDownloadIntentScript.swift in Sources */, A5001500 /* CmuxWebView.swift in Sources */, + C0DE59AB0000000000000002 /* CmuxWebViewFocusModeKeyEquivalent.swift in Sources */, E30750000000000000000004 /* CmuxWorkspaceDefinition.swift in Sources */, C0A1E5CE01C0A1E5CE01A001 /* CoalesceLatestPublisher.swift in Sources */, A9F200000000000000000016 /* CodexAppServerQueuedInput.swift in Sources */, diff --git a/cmuxTests/BrowserWebExtensionReviewRegressionTests.swift b/cmuxTests/BrowserWebExtensionReviewRegressionTests.swift index ac8e91c6a245..02a7ccb14a37 100644 --- a/cmuxTests/BrowserWebExtensionReviewRegressionTests.swift +++ b/cmuxTests/BrowserWebExtensionReviewRegressionTests.swift @@ -85,6 +85,56 @@ struct BrowserWebExtensionReviewRegressionTests { #expect(!appDelegate.shouldOfferBrowserWebExtensionCommand(plainTypingEvent)) } + @MainActor + @Test + func browserFocusModeOffersExtensionCommandDespiteConfiguredShortcut() throws { + let appDelegate = try #require(AppDelegate.shared) + let action = KeyboardShortcutSettings.Action.openBrowser + let hadPersistedShortcut = UserDefaults.standard.object(forKey: action.defaultsKey) != nil + let originalShortcut = KeyboardShortcutSettings.shortcut(for: action) + defer { + if hadPersistedShortcut { + KeyboardShortcutSettings.setShortcut(originalShortcut, for: action) + } else { + KeyboardShortcutSettings.resetShortcut(for: action) + } + } + let event = try #require(NSEvent.keyEvent( + with: .keyDown, + location: .zero, + modifierFlags: [.command, .shift], + timestamp: ProcessInfo.processInfo.systemUptime, + windowNumber: 0, + context: nil, + characters: "L", + charactersIgnoringModifiers: "l", + isARepeat: false, + keyCode: 37 + )) + + // With the default ⌘⇧L Open Browser binding, the extension command is + // declined outside focus mode but offered inside it, where the app-level + // monitor has already suspended configured cmux shortcuts. + KeyboardShortcutSettings.setShortcut(action.defaultShortcut, for: action) + #expect(!appDelegate.shouldOfferBrowserWebExtensionCommand(event, browserFocusModeActive: false)) + #expect(appDelegate.shouldOfferBrowserWebExtensionCommand(event, browserFocusModeActive: true)) + + // Focus mode does not turn plain typing into extension commands. + let plainTypingEvent = try #require(NSEvent.keyEvent( + with: .keyDown, + location: .zero, + modifierFlags: [], + timestamp: ProcessInfo.processInfo.systemUptime, + windowNumber: 0, + context: nil, + characters: "a", + charactersIgnoringModifiers: "a", + isARepeat: false, + keyCode: 0 + )) + #expect(!appDelegate.shouldOfferBrowserWebExtensionCommand(plainTypingEvent, browserFocusModeActive: true)) + } + @MainActor @Test @available(macOS 15.4, *) From f75b432341b67a590c4bcf80a4acea7d60a22b7d Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 22:44:02 -0700 Subject: [PATCH 45/51] ci: follow cmuxAuxiliaryWindowIdentifiers to its new file in the close-shortcut lint The identifier owner list moved from cmuxApp.swift to Sources/App/AuxiliaryWindowCloseShortcut.swift in the file-length budget refactor; the lint hardcodes the owner-list path, so workflow-guard-tests (and the linux-preflight/tests/ci-status gates behind it) went red. Co-Authored-By: Claude Fable 5 --- scripts/lint_auxiliary_window_close_shortcuts.py | 2 +- tests/test_ci_auxiliary_window_close_shortcuts.sh | 14 +++++++------- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/scripts/lint_auxiliary_window_close_shortcuts.py b/scripts/lint_auxiliary_window_close_shortcuts.py index 63341df69f39..f4e222a489ee 100755 --- a/scripts/lint_auxiliary_window_close_shortcuts.py +++ b/scripts/lint_auxiliary_window_close_shortcuts.py @@ -10,7 +10,7 @@ DEFAULT_ROOTS = ("Sources",) -OWNER_LIST_PATH = pathlib.Path("Sources/cmuxApp.swift") +OWNER_LIST_PATH = pathlib.Path("Sources/App/AuxiliaryWindowCloseShortcut.swift") OWNER_LIST_NAME = "cmuxAuxiliaryWindowIdentifiers" # Hidden/internal bootstrap windows should not take Cmd+W away from the active diff --git a/tests/test_ci_auxiliary_window_close_shortcuts.sh b/tests/test_ci_auxiliary_window_close_shortcuts.sh index 4aacd128977e..6bf0cf812a16 100755 --- a/tests/test_ci_auxiliary_window_close_shortcuts.sh +++ b/tests/test_ci_auxiliary_window_close_shortcuts.sh @@ -9,9 +9,9 @@ python3 scripts/lint_auxiliary_window_close_shortcuts.py TMP_DIR="$(mktemp -d)" trap 'rm -rf "$TMP_DIR"' EXIT -mkdir -p "$TMP_DIR/Sources" +mkdir -p "$TMP_DIR/Sources/App" -cat > "$TMP_DIR/Sources/cmuxApp.swift" <<'SWIFT' +cat > "$TMP_DIR/Sources/App/AuxiliaryWindowCloseShortcut.swift" <<'SWIFT' private let cmuxAuxiliaryWindowIdentifiers: Set = [ "cmux.settings", ] @@ -38,7 +38,7 @@ fi grep -q "cmux.newWindow" "$TMP_DIR/missing.out" grep -q "Sources/NewWindow.swift:9" "$TMP_DIR/missing.out" -cat > "$TMP_DIR/Sources/cmuxApp.swift" <<'SWIFT' +cat > "$TMP_DIR/Sources/App/AuxiliaryWindowCloseShortcut.swift" <<'SWIFT' private let cmuxAuxiliaryWindowIdentifiers: Set = [ // "cmux.newWindow", /* @@ -54,7 +54,7 @@ if python3 scripts/lint_auxiliary_window_close_shortcuts.py --repo-root "$TMP_DI fi grep -q "cmux.newWindow" "$TMP_DIR/commented-owner.out" -cat > "$TMP_DIR/Sources/cmuxApp.swift" <<'SWIFT' +cat > "$TMP_DIR/Sources/App/AuxiliaryWindowCloseShortcut.swift" <<'SWIFT' private let cmuxAuxiliaryWindowIdentifiers: Set = [ // MARK: - Main Windows [user-closable] // This comment intentionally contains a lone ] bracket. @@ -80,7 +80,7 @@ SWIFT python3 scripts/lint_auxiliary_window_close_shortcuts.py --repo-root "$TMP_DIR" -cat > "$TMP_DIR/Sources/cmuxApp.swift" <<'SWIFT' +cat > "$TMP_DIR/Sources/App/AuxiliaryWindowCloseShortcut.swift" <<'SWIFT' private let cmuxAuxiliaryWindowIdentifiers: Set = [ "cmux.settings", ] @@ -99,7 +99,7 @@ python3 scripts/lint_auxiliary_window_close_shortcuts.py --repo-root "$TMP_DIR" # Identifier assigned through a named constant (the MobilePairingWindowController # pattern) must be resolved and enforced, not silently skipped. -cat > "$TMP_DIR/Sources/cmuxApp.swift" <<'SWIFT' +cat > "$TMP_DIR/Sources/App/AuxiliaryWindowCloseShortcut.swift" <<'SWIFT' private let cmuxAuxiliaryWindowIdentifiers: Set = [ "cmux.settings", ] @@ -125,7 +125,7 @@ fi grep -q "cmux.constantWindow" "$TMP_DIR/constant.out" grep -q "Sources/NewWindow.swift:8" "$TMP_DIR/constant.out" -cat > "$TMP_DIR/Sources/cmuxApp.swift" <<'SWIFT' +cat > "$TMP_DIR/Sources/App/AuxiliaryWindowCloseShortcut.swift" <<'SWIFT' private let cmuxAuxiliaryWindowIdentifiers: Set = [ "cmux.constantWindow", "cmux.settings", From e352be58540411481b678b11f112b7a5c36f7217 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 23:05:51 -0700 Subject: [PATCH 46/51] fix: drop no-op await flagged by the Swift warning budget terminateActivePluginkitProcess() is synchronous and this call site is already actor-isolated, so the await performs no async work and trips the warning budget (tests-build-and-lag). Co-Authored-By: Claude Fable 5 --- Sources/Panels/BrowserWebExtensionDiscoveryService.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/Panels/BrowserWebExtensionDiscoveryService.swift b/Sources/Panels/BrowserWebExtensionDiscoveryService.swift index dd1a023b2d74..dec504b8d4e0 100644 --- a/Sources/Panels/BrowserWebExtensionDiscoveryService.swift +++ b/Sources/Panels/BrowserWebExtensionDiscoveryService.swift @@ -146,7 +146,7 @@ actor BrowserWebExtensionDiscoveryService { return output } catch { group.cancelAll() - await terminateActivePluginkitProcess() + terminateActivePluginkitProcess() throw error } } From 6063f15c90c04f892d03a137549f64c84c9c2cc2 Mon Sep 17 00:00:00 2001 From: austinpower1258 Date: Thu, 9 Jul 2026 23:09:15 -0700 Subject: [PATCH 47/51] fix(settings): don't flash 'no extensions added' before settings load MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Extensions card showed the empty state whenever entries were empty, but before JSONValueModel's stream delivers its first value the entries are only the default [] — configured extensions briefly appeared missing. Gate the empty row on hasObservedValue, matching the Import menu's existing gate, and cover it in BrowserWebExtensionsCardStateTests. Addresses the Cursor Bugbot finding on BrowserWebExtensionsCard.swift. Co-Authored-By: Claude Fable 5 --- .../Sections/BrowserWebExtensionsCard.swift | 5 ++++- .../Sections/BrowserWebExtensionsCardState.swift | 8 ++++++++ .../BrowserWebExtensionsCardStateTests.swift | 11 +++++++++++ 3 files changed, 23 insertions(+), 1 deletion(-) diff --git a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift index d513788a433e..b0d093516ad2 100644 --- a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift +++ b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift @@ -28,7 +28,10 @@ struct BrowserWebExtensionsCard: View { SettingsCardDivider() entryRow(entry, isEnabled: enabledByID[entry.id] ?? entry.enabled) } - if entries.isEmpty { + if cardState.shouldShowEmptyState( + entries: entries, + hasObservedValue: model.hasObservedValue + ) { SettingsCardDivider() emptyRow } diff --git a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCardState.swift b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCardState.swift index 81e7d6637835..b816d40d63c2 100644 --- a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCardState.swift +++ b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCardState.swift @@ -16,6 +16,14 @@ struct BrowserWebExtensionsCardState { supported && hasObservedValue && isDiscoveryComplete } + /// The "no extensions added" empty row must wait for the JSON stream's + /// first value: until then the observed entries are only the default `[]`, + /// not the persisted state, and configured extensions would flash as + /// missing. + func shouldShowEmptyState(entries: [BrowserWebExtensionEntry], hasObservedValue: Bool) -> Bool { + entries.isEmpty && hasObservedValue + } + mutating func completeDiscovery(_ discovered: [SettingsDiscoveredBrowserExtension]) { self.discovered = discovered isDiscoveryComplete = true diff --git a/Packages/macOS/CmuxSettingsUI/Tests/CmuxSettingsUITests/BrowserWebExtensionsCardStateTests.swift b/Packages/macOS/CmuxSettingsUI/Tests/CmuxSettingsUITests/BrowserWebExtensionsCardStateTests.swift index 015bffbdf984..814b7b0853da 100644 --- a/Packages/macOS/CmuxSettingsUI/Tests/CmuxSettingsUITests/BrowserWebExtensionsCardStateTests.swift +++ b/Packages/macOS/CmuxSettingsUI/Tests/CmuxSettingsUITests/BrowserWebExtensionsCardStateTests.swift @@ -18,6 +18,17 @@ struct BrowserWebExtensionsCardStateTests { #expect(state.canUseImportMenu(supported: true, hasObservedValue: true)) } + @Test + func emptyStateWaitsForFirstObservedValue() { + let state = BrowserWebExtensionsCardState() + + // Before the JSON stream delivers a value, empty entries only reflect + // the model default — not "no extensions added". + #expect(!state.shouldShowEmptyState(entries: [], hasObservedValue: false)) + #expect(state.shouldShowEmptyState(entries: [], hasObservedValue: true)) + #expect(!state.shouldShowEmptyState(entries: [entry(id: "existing")], hasObservedValue: true)) + } + @Test func matchingWriteFailureRollsBackAndSurfacesError() { let observed = [entry(id: "existing")] From b5278d258ff359aa116a719714a820686a43491a Mon Sep 17 00:00:00 2001 From: 0xCUB3 Date: Fri, 10 Jul 2026 07:05:12 -0400 Subject: [PATCH 48/51] Complete user-managed browser web extensions --- .github/swift-file-length-budget.tsv | 8 +- .../BrowserWebExtensionsCardState.swift | 11 +- .../BrowserWebExtensionsCardStateTests.swift | 29 +- Resources/Localizable.xcstrings | 500 ++++++++++++++++++ .../App/AuxiliaryWindowCloseShortcut.swift | 44 ++ Sources/App/ShortcutRoutingSupport.swift | 18 - ...e+BrowserWebExtensionShortcutRouting.swift | 58 ++ Sources/AppDelegate.swift | 22 +- Sources/CmuxNotificationNames.swift | 43 ++ Sources/KeyboardShortcutContext.swift | 6 + .../Panels/BrowserDevToolsIconOptions.swift | 77 +++ .../BrowserExternalNavigationPolicy.swift | 67 +++ Sources/Panels/BrowserPanel.swift | 95 +--- Sources/Panels/BrowserPanelView.swift | 75 --- .../BrowserWebExtensionDiscoveryService.swift | 5 +- ...ort+WKWebExtensionControllerDelegate.swift | 14 +- .../Panels/BrowserWebExtensionSupport.swift | 48 ++ .../BrowserWebExtensionTabAdapter.swift | 9 + Sources/Panels/CmuxWebView.swift | 13 +- Sources/TabManager.swift | 42 -- Sources/Workspace+PendingTerminalInput.swift | 103 ++++ Sources/Workspace.swift | 102 +--- Sources/cmuxApp.swift | 59 +-- cmux.xcodeproj/project.pbxproj | 20 + ...serWebExtensionReviewRegressionTests.swift | 7 +- .../BrowserWebExtensionSupportTests.swift | 15 +- 26 files changed, 1052 insertions(+), 438 deletions(-) create mode 100644 Sources/App/AuxiliaryWindowCloseShortcut.swift create mode 100644 Sources/CmuxNotificationNames.swift create mode 100644 Sources/Panels/BrowserDevToolsIconOptions.swift create mode 100644 Sources/Panels/BrowserExternalNavigationPolicy.swift create mode 100644 Sources/Workspace+PendingTerminalInput.swift diff --git a/.github/swift-file-length-budget.tsv b/.github/swift-file-length-budget.tsv index aabb5cc70045..9bfe42cf8fb6 100644 --- a/.github/swift-file-length-budget.tsv +++ b/.github/swift-file-length-budget.tsv @@ -35,8 +35,8 @@ 2882 Sources/Update/UpdateTitlebarAccessory.swift 2876 cmuxTests/CMUXOpenCommandTests.swift 2875 Sources/SessionIndexView.swift -2581 Sources/KeyboardShortcutSettings.swift -2571 Sources/Panels/CmuxWebView.swift +2611 Sources/KeyboardShortcutSettings.swift +2562 Sources/Panels/CmuxWebView.swift 2546 cmuxTests/WorkspaceManualUnreadTests.swift 2524 cmuxTests/CommandPaletteSearchEngineTests.swift 2403 Sources/Mobile/MobileHostService.swift @@ -112,7 +112,6 @@ 897 Sources/DockSplitStore.swift 896 Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/AppSection.swift 885 cmuxTests/SidebarWorkspaceDropPlannerTests.swift - 871 cmuxTests/ClaudeHookSurfaceResolutionSwiftTests.swift 868 Sources/Panels/BrowserScreenshotSnapshotter.swift 864 Packages/Shared/CmuxAgentChat/Sources/CmuxAgentChat/Store/ChatConversationStore.swift @@ -148,7 +147,6 @@ 706 CLI/CMUXCLI+Config.swift 699 cmuxTests/TerminalNotificationClearAllTests.swift 698 cmuxTests/RestorableAgentHookProviderResumeTests.swift - 696 cmuxTests/KeyboardShortcutContextTests.swift 691 Sources/NotificationSoundSettings.swift 691 cmuxTests/TaskManagerResourcesTests.swift @@ -174,7 +172,6 @@ 650 Packages/macOS/CmuxBrowser/Sources/CmuxBrowser/Import/Detection/BrowserInstalledBrowserDetector.swift 650 Sources/Panels/MarkdownRemoteImageLoader.swift 648 cmuxTests/TerminalNotificationQueueTests.swift - 644 Packages/macOS/CMUXAgentLaunch/Tests/CMUXAgentLaunchTests/AgentLaunchSanitizerTests.swift 641 cmuxTests/CommandPaletteNucleoFFITests.swift 638 cmuxTests/RemoteTmuxControlParserTests.swift @@ -184,7 +181,6 @@ 630 Packages/macOS/CmuxSettings/Sources/CmuxSettings/Values/ShortcutWhenClause.swift 624 Sources/SettingsNavigation.swift 623 Packages/macOS/CmuxControlSocket/Sources/CmuxControlSocket/Coordinator/Surface/ControlCommandCoordinator+Surface.swift - 620 cmuxTests/FinderFileDropRegressionTests.swift 608 Sources/TextBoxSubmitActions.swift 608 cmuxUITests/FeedSidebarUITests.swift diff --git a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCardState.swift b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCardState.swift index b816d40d63c2..16acc08b4e71 100644 --- a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCardState.swift +++ b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCardState.swift @@ -36,17 +36,16 @@ struct BrowserWebExtensionsCardState { } mutating func reconcileObservedEntries(_ entries: [BrowserWebExtensionEntry]) { - if entries == pendingEntries { - pendingEntries = nil - pendingWriteID = nil - } + guard entries == pendingEntries else { return } + pendingEntries = nil + pendingWriteID = nil hasWriteError = false } mutating func reconcileWriteResult(completedWriteID: UInt64, failed: Bool) { - guard completedWriteID == pendingWriteID, failed else { return } + guard completedWriteID == pendingWriteID else { return } pendingEntries = nil pendingWriteID = nil - hasWriteError = true + hasWriteError = failed } } diff --git a/Packages/macOS/CmuxSettingsUI/Tests/CmuxSettingsUITests/BrowserWebExtensionsCardStateTests.swift b/Packages/macOS/CmuxSettingsUI/Tests/CmuxSettingsUITests/BrowserWebExtensionsCardStateTests.swift index 814b7b0853da..4eae55dc04d9 100644 --- a/Packages/macOS/CmuxSettingsUI/Tests/CmuxSettingsUITests/BrowserWebExtensionsCardStateTests.swift +++ b/Packages/macOS/CmuxSettingsUI/Tests/CmuxSettingsUITests/BrowserWebExtensionsCardStateTests.swift @@ -46,7 +46,7 @@ struct BrowserWebExtensionsCardStateTests { let externallyUpdated = [entry(id: "external")] state.reconcileObservedEntries(externallyUpdated) - #expect(!state.hasWriteError) + #expect(state.hasWriteError) state.beginWrite(entries: pending, writeID: 3) #expect(!state.hasWriteError) @@ -67,6 +67,33 @@ struct BrowserWebExtensionsCardStateTests { #expect(state.pendingWriteID == nil) } + @Test + func successfulWriteClearsPendingWithoutObservedSignal() { + let observed = [entry(id: "existing")] + let pending = observed + [entry(id: "new")] + var state = BrowserWebExtensionsCardState() + state.beginWrite(entries: pending, writeID: 1) + + state.reconcileWriteResult(completedWriteID: 1, failed: false) + #expect(state.pendingWriteID == nil) + + let externallyUpdated = [entry(id: "external")] + #expect(state.effectiveEntries(observed: externallyUpdated) == externallyUpdated) + } + + @Test + func staleSuccessfulWriteDoesNotClearNewerPendingWrite() { + let first = [entry(id: "first")] + let second = [entry(id: "second")] + var state = BrowserWebExtensionsCardState() + state.beginWrite(entries: first, writeID: 1) + state.beginWrite(entries: second, writeID: 2) + + state.reconcileWriteResult(completedWriteID: 1, failed: false) + #expect(state.pendingWriteID == 2) + #expect(state.effectiveEntries(observed: []) == second) + } + private func entry(id: String) -> BrowserWebExtensionEntry { BrowserWebExtensionEntry( id: id, diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index ea0aa7a4d443..90f7082b7e44 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -45313,6 +45313,506 @@ } } }, + "settings.browser.webExtensions.addUnpacked.missingManifest.message": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "«%@» ليست إضافة ويب غير محزّمة. اختر مجلدًا يحتوي على manifest.json في المستوى الجذر." + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "„%@” nije raspakovana web ekstenzija. Odaberite mapu koja u korijenu sadrži manifest.json." + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "»%@« er ikke en udpakket webudvidelse. Vælg en mappe med manifest.json i roden." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "„%@“ ist keine entpackte Web-Erweiterung. Wähle einen Ordner, der auf oberster Ebene manifest.json enthält." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "“%@” is not an unpacked web extension. Choose a folder with manifest.json at its root." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "«%@» no es una extensión web sin empaquetar. Elige una carpeta con manifest.json en la raíz." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "« %@ » n’est pas une extension web non empaquetée. Choisissez un dossier contenant manifest.json à sa racine." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "«%@» non è un’estensione web non pacchettizzata. Scegli una cartella con manifest.json nella directory principale." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "「%@」はパッケージ化されていないWeb拡張機能ではありません。ルートにmanifest.jsonがあるフォルダを選択してください。" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "‘%@’ 항목은 압축 해제된 웹 확장 프로그램이 아닙니다. 루트에 manifest.json이 있는 폴더를 선택하십시오." + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "«%@» er ikke en upakket webutvidelse. Velg en mappe med manifest.json på øverste nivå." + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "„%@” nie jest rozpakowanym rozszerzeniem internetowym. Wybierz folder zawierający plik manifest.json na najwyższym poziomie." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "“%@” não é uma extensão da web descompactada. Escolha uma pasta com manifest.json na raiz." + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "«%@» не является распакованным веб-расширением. Выберите папку, в корне которой находится manifest.json." + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "“%@” ไม่ใช่ส่วนขยายเว็บแบบไม่แพ็ก เลือกโฟลเดอร์ที่มี manifest.json อยู่ที่ระดับบนสุด" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "“%@” paketlenmemiş bir web uzantısı değil. Kök dizininde manifest.json bulunan bir klasör seçin." + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "«%@» не є розпакованим веброзширенням. Виберіть папку, у корені якої міститься manifest.json." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "“%@”不是已解压的 Web 扩展程序。请选择根目录下有 manifest.json 的文件夹。" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "「%@」不是未封裝的 Web 擴充功能。請選擇根目錄中有 manifest.json 的資料夾。" + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "«%@» មិនមែនជាកម្មវិធីបន្ថែមលើបណ្ដាញដែលមិនបានខ្ចប់ទេ។ ជ្រើសរើសថតដែលមាន manifest.json នៅកម្រិតកំពូល។" + } + } + } + }, + "settings.browser.webExtensions.addUnpacked.missingManifest.title": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "ملف manifest.json مفقود" + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "Nedostaje manifest.json" + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "manifest.json mangler" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "manifest.json fehlt" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Missing manifest.json" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Falta manifest.json" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Fichier manifest.json manquant" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "File manifest.json mancante" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "manifest.jsonが見つかりません" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "manifest.json이 없습니다" + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "manifest.json mangler" + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "Brak pliku manifest.json" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "manifest.json ausente" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Файл manifest.json отсутствует" + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "ไม่พบ manifest.json" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "manifest.json eksik" + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "Файл manifest.json відсутній" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "缺少 manifest.json" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "缺少 manifest.json" + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "បាត់ឯកសារ manifest.json" + } + } + } + }, + "settings.browser.webExtensions.duplicate.message": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "الإضافة «%@» موجودة بالفعل في قائمة الإضافات." + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "„%@” se već nalazi na listi ekstenzija." + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "»%@« findes allerede på listen over udvidelser." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "„%@“ ist bereits in der Liste der Erweiterungen enthalten." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "“%@” is already in the extensions list." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "«%@» ya está en la lista de extensiones." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "« %@ » figure déjà dans la liste des extensions." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "«%@» è già nell’elenco delle estensioni." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "「%@」はすでに拡張機能リストにあります。" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "‘%@’ 항목은 이미 확장 프로그램 목록에 있습니다." + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "«%@» finnes allerede i utvidelseslisten." + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "„%@” znajduje się już na liście rozszerzeń." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "“%@” já está na lista de extensões." + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "«%@» уже есть в списке расширений." + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "“%@” อยู่ในรายการส่วนขยายแล้ว" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "“%@” zaten uzantılar listesinde." + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "«%@» уже є у списку розширень." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "“%@”已在扩展程序列表中。" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "「%@」已在擴充功能清單中。" + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "«%@» មាននៅក្នុងបញ្ជីកម្មវិធីបន្ថែមរួចហើយ។" + } + } + } + }, + "settings.browser.webExtensions.duplicate.title": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "تمت الإضافة بالفعل" + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "Ekstenzija je već dodana" + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "Udvidelsen er allerede tilføjet" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Erweiterung bereits hinzugefügt" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Extension Already Added" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Extensión ya añadida" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Extension déjà ajoutée" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Estensione già aggiunta" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "拡張機能は追加済みです" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "확장 프로그램이 이미 추가됨" + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "Utvidelsen er allerede lagt til" + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "Rozszerzenie zostało już dodane" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Extensão já adicionada" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Расширение уже добавлено" + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "เพิ่มส่วนขยายนี้แล้ว" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Uzantı zaten eklendi" + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "Розширення вже додано" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "扩展已添加" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "擴充功能已加入" + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "បានបន្ថែមកម្មវិធីបន្ថែមរួចហើយ" + } + } + } + }, "settings.browser.webExtensions.importSafari": { "extractionState": "manual", "localizations": { diff --git a/Sources/App/AuxiliaryWindowCloseShortcut.swift b/Sources/App/AuxiliaryWindowCloseShortcut.swift new file mode 100644 index 000000000000..5858ec84a36b --- /dev/null +++ b/Sources/App/AuxiliaryWindowCloseShortcut.swift @@ -0,0 +1,44 @@ +import AppKit + +private let cmuxAuxiliaryWindowIdentifiers: Set = [ + "cmux.settings", + "cmux.about", + "cmux.licenses", + "cmux.browser-popup", + "cmux.browserProfilePopoverDebug", + "cmux.configEditor", + "cmux.defaultTerminalRegistrationError", + "cmux.feedButtonStyleDebug", + "cmux.feedPreview", + "cmux.feedTextEditorDebug", + "cmux.fileExplorerStyleDebug", + "cmux.folderDragIcon", + "cmux.pdfPreviewChromeDebug", + "cmux.proBadgeDebug", + "cmux.recentlyClosedHistory", + "cmux.splitButtonLayoutDebug", + "cmux.tabBarBackdropLab", + "cmux.taskManager", + "cmux.aboutTitlebarDebug", + "cmux.debugWindowControls", + "cmux.browserImportHintDebug", + "cmux.extensionSidebarInspector", + "cmux.sidebarDebug", + "cmux.menubarDebug", + "cmux.spinnerGallery", + "cmux.backgroundDebug", + "cmux.startupAppearanceDebug", + "cmux.bonsplitTabBarDebug", + "cmux.titlebarLayoutDebug", + "cmux.devWindowDisplay", + "cmux.mobilePairingWindow", + "cmux.webExtensionPopout", +] + +/// Returns whether the given window should handle the standard close shortcut +/// as a standalone auxiliary window instead of routing it through workspace or +/// panel-close behavior. +func cmuxWindowShouldOwnCloseShortcut(_ window: NSWindow?) -> Bool { + guard let identifier = window?.identifier?.rawValue else { return false } + return cmuxAuxiliaryWindowIdentifiers.contains(identifier) +} diff --git a/Sources/App/ShortcutRoutingSupport.swift b/Sources/App/ShortcutRoutingSupport.swift index 6fd50443ec04..9c43c05e70ef 100644 --- a/Sources/App/ShortcutRoutingSupport.swift +++ b/Sources/App/ShortcutRoutingSupport.swift @@ -795,24 +795,6 @@ func cmuxOwningGhosttyView(for responder: NSResponder?) -> GhosttyNSView? { return nil } -/// Whether the responder chain passes through a browser web view, so -/// web-extension shortcut commands (e.g. Bitwarden autofill) may claim the event. -func cmuxRespondersContainBrowserWebView(_ responder: NSResponder?) -> Bool { - var current: NSResponder? = responder - while let next = current { - if next is CmuxWebView { return true } - if let view = next as? NSView { - var ancestor: NSView? = view.superview - while let candidate = ancestor { - if candidate is CmuxWebView { return true } - ancestor = candidate.superview - } - } - current = next.nextResponder - } - return false -} - func cmuxFieldEditorOwnerView(_ editor: NSTextView) -> NSView? { guard editor.isFieldEditor else { return nil } if let owner = cmuxTrackedFindFieldEditorOwner(editor) { return owner } diff --git a/Sources/AppDelegate+BrowserWebExtensionShortcutRouting.swift b/Sources/AppDelegate+BrowserWebExtensionShortcutRouting.swift index d7b7f89787cf..f80e125641be 100644 --- a/Sources/AppDelegate+BrowserWebExtensionShortcutRouting.swift +++ b/Sources/AppDelegate+BrowserWebExtensionShortcutRouting.swift @@ -1,6 +1,64 @@ import AppKit +/// Whether the responder chain passes through a browser web view, so +/// web-extension shortcut commands (e.g. Bitwarden autofill) may claim the event. +func cmuxRespondersContainBrowserWebView(_ responder: NSResponder?) -> Bool { + var current: NSResponder? = responder + while let next = current { + if next is CmuxWebView { return true } + if let view = next as? NSView { + var ancestor: NSView? = view.superview + while let candidate = ancestor { + if candidate is CmuxWebView { return true } + ancestor = candidate.superview + } + } + current = next.nextResponder + } + return false +} + +/// A stale default (e.g. ⌘⇧L after Open Browser is remapped) is free for +/// web-extension commands like Bitwarden autofill while a browser web +/// view has focus; otherwise the stale-menu-shortcut suppression would eat it. +@MainActor +func cmuxRouteWebExtensionCommandForStaleMenuShortcut(_ event: NSEvent, responder: NSResponder?) -> Bool { + guard #available(macOS 15.4, *), cmuxRespondersContainBrowserWebView(responder), + AppDelegate.shared?.shortcutEventBrowserPanel(event)?.performWebExtensionCommand(for: event) == true else { + return false + } +#if DEBUG + cmuxDebugLog("app.sendEvent routed web-extension command before stale cmux menu shortcut") +#endif + return true +} + +/// Manifest commands may use Control or Option, so browser key handling +/// dispatches them before the Command-only cmux menu-equivalent guard. +@MainActor +func cmuxPerformBrowserWebExtensionCommandKeyEquivalent(_ event: NSEvent) -> Bool { + guard #available(macOS 15.4, *), + let appDelegate = AppDelegate.shared, + appDelegate.shouldOfferBrowserWebExtensionCommand(event) else { + return false + } + return appDelegate.shortcutEventBrowserPanel(event)?.performWebExtensionCommand(for: event) == true +} + extension AppDelegate { + func matchConfiguredShortcut(event: NSEvent, shortcut: StoredShortcut) -> Bool { + guard !shortcut.isUnbound else { return false } + if let prefix = activeConfiguredShortcutChordPrefixForCurrentEvent { + guard let secondStroke = shortcut.secondStroke, + shortcut.firstStroke == prefix else { + return false + } + return matchShortcutStroke(event: event, stroke: secondStroke) + } + guard !shortcut.hasChord else { return false } + return matchShortcutStroke(event: event, stroke: shortcut.firstStroke) + } + /// Extension manifest commands run only after configured cmux shortcuts decline the event. func shouldOfferBrowserWebExtensionCommand(_ event: NSEvent) -> Bool { shouldOfferBrowserWebExtensionCommand( diff --git a/Sources/AppDelegate.swift b/Sources/AppDelegate.swift index 014939241266..42202a0a72a8 100644 --- a/Sources/AppDelegate.swift +++ b/Sources/AppDelegate.swift @@ -15087,19 +15087,6 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent return false } - func matchConfiguredShortcut(event: NSEvent, shortcut: StoredShortcut) -> Bool { - guard !shortcut.isUnbound else { return false } - if let prefix = activeConfiguredShortcutChordPrefixForCurrentEvent { - guard let secondStroke = shortcut.secondStroke, - shortcut.firstStroke == prefix else { - return false - } - return matchShortcutStroke(event: event, stroke: secondStroke) - } - guard !shortcut.hasChord else { return false } - return matchShortcutStroke(event: event, stroke: shortcut.firstStroke) - } - func matchConfiguredShortcut(event: NSEvent, action: KeyboardShortcutSettings.Action) -> Bool { if !shortcutWhenClauseAllows(action: action, event: event) { return false } return matchConfiguredShortcut(event: event, shortcut: KeyboardShortcutSettings.shortcut(for: action)) @@ -16534,14 +16521,7 @@ private extension NSApplication { let responder = event.window?.firstResponder ?? AppDelegate.shared?.shortcutRoutingKeyWindow?.firstResponder ?? mainWindow?.firstResponder - // A stale default (e.g. ⌘⇧L after Open Browser is remapped) is free for - // web-extension commands like Bitwarden autofill while a browser web - // view has focus; otherwise the suppression below would eat it. - if #available(macOS 15.4, *), cmuxRespondersContainBrowserWebView(responder), - AppDelegate.shared?.shortcutEventBrowserPanel(event)?.performWebExtensionCommand(for: event) == true { -#if DEBUG - cmuxDebugLog("app.sendEvent routed web-extension command before stale cmux menu shortcut") -#endif + if cmuxRouteWebExtensionCommandForStaleMenuShortcut(event, responder: responder) { return } if let ghosttyView = cmuxOwningGhosttyView(for: responder) { diff --git a/Sources/CmuxNotificationNames.swift b/Sources/CmuxNotificationNames.swift new file mode 100644 index 000000000000..e5d4a4596296 --- /dev/null +++ b/Sources/CmuxNotificationNames.swift @@ -0,0 +1,43 @@ +import Foundation + +extension Notification.Name { + // The sidebar multi-selection sync events moved to CmuxSidebar as typed + // SidebarMultiSelectionShouldCollapseEvent / DidHideEvent (same names). + static let commandPaletteToggleRequested = Notification.Name("cmux.commandPaletteToggleRequested") + static let commandPaletteRequested = Notification.Name("cmux.commandPaletteRequested") + static let commandPaletteSwitcherRequested = Notification.Name("cmux.commandPaletteSwitcherRequested") + static let commandPaletteSubmitRequested = Notification.Name("cmux.commandPaletteSubmitRequested") + static let commandPaletteDismissRequested = Notification.Name("cmux.commandPaletteDismissRequested") + static let commandPaletteRenameTabRequested = Notification.Name("cmux.commandPaletteRenameTabRequested") + static let commandPaletteRenameWorkspaceRequested = Notification.Name("cmux.commandPaletteRenameWorkspaceRequested") + static let commandPaletteEditWorkspaceDescriptionRequested = Notification.Name("cmux.commandPaletteEditWorkspaceDescriptionRequested") + static let commandPaletteMoveSelection = Notification.Name("cmux.commandPaletteMoveSelection") + static let commandPaletteRenameInputInteractionRequested = Notification.Name("cmux.commandPaletteRenameInputInteractionRequested") + static let commandPaletteRenameInputDeleteBackwardRequested = Notification.Name("cmux.commandPaletteRenameInputDeleteBackwardRequested") + static let feedbackComposerRequested = Notification.Name("cmux.feedbackComposerRequested") + static let ghosttyDidSetTitle = Notification.Name("ghosttyDidSetTitle") + static let ghosttyDidFocusTab = Notification.Name("ghosttyDidFocusTab") + static let ghosttyDidFocusSurface = Notification.Name("ghosttyDidFocusSurface") + static let ghosttyDidBecomeFirstResponderSurface = Notification.Name("ghosttyDidBecomeFirstResponderSurface") + static let browserDidBecomeFirstResponderWebView = Notification.Name("browserDidBecomeFirstResponderWebView") + static let browserFocusAddressBar = Notification.Name("browserFocusAddressBar") + static let browserMoveOmnibarSelection = Notification.Name("browserMoveOmnibarSelection") + static let browserDidExitAddressBar = Notification.Name("browserDidExitAddressBar") + static let browserDidFocusAddressBar = Notification.Name("browserDidFocusAddressBar") + static let browserDidBlurAddressBar = Notification.Name("browserDidBlurAddressBar") + static let browserFocusModeStateDidChange = Notification.Name("cmux.browserFocusModeStateDidChange") + static let webViewDidReceiveClick = Notification.Name("webViewDidReceiveClick") + static let terminalPortalVisibilityDidChange = Notification.Name("cmux.terminalPortalVisibilityDidChange") + static let browserPortalRegistryDidChange = Notification.Name("cmux.browserPortalRegistryDidChange") + static let workspaceOrderDidChange = Notification.Name("cmux.workspaceOrderDidChange") + static let workspacePaneGeometryDidChange = Notification.Name("cmux.workspacePaneGeometryDidChange") + /// Posted when an existing workspace group's `name` changes (rename). The + /// imperatively-cached window-chrome surfaces (custom title bar in + /// `ContentView`, toolbar command label in `WindowToolbarController`) read + /// a grouped anchor's displayed name from `group.name` and refresh on this. + static let workspaceGroupNameDidChange = Notification.Name("cmux.workspaceGroupNameDidChange") + /// Posted after TabManager has applied a terminal title to workspace state. + static let workspaceTitleDidChange = Notification.Name("cmux.workspaceTitleDidChange") + static let workspaceCurrentDirectoryDidChange = Notification.Name("cmux.workspaceCurrentDirectoryDidChange") + static let tabManagerFocusHistoryRevisionDidChange = Notification.Name("cmux.tabManagerFocusHistoryRevisionDidChange") +} diff --git a/Sources/KeyboardShortcutContext.swift b/Sources/KeyboardShortcutContext.swift index d47ce85a10f1..58db720053af 100644 --- a/Sources/KeyboardShortcutContext.swift +++ b/Sources/KeyboardShortcutContext.swift @@ -2,6 +2,12 @@ import AppKit import CmuxSettings import WebKit +enum BrowserFocusModeKeyDecision: Equatable { + case inactive + case forwardToWebView + case consume +} + struct ShortcutEventFocusContext { let browserPanel: BrowserPanel? let markdownPanel: MarkdownPanel? diff --git a/Sources/Panels/BrowserDevToolsIconOptions.swift b/Sources/Panels/BrowserDevToolsIconOptions.swift new file mode 100644 index 000000000000..7c70189a04bd --- /dev/null +++ b/Sources/Panels/BrowserDevToolsIconOptions.swift @@ -0,0 +1,77 @@ +import AppKit +import SwiftUI + +enum BrowserDevToolsIconOption: String, CaseIterable, Identifiable { + case wrenchAndScrewdriver = "wrench.and.screwdriver" + case wrenchAndScrewdriverFill = "wrench.and.screwdriver.fill" + case curlyBracesSquare = "curlybraces.square" + case curlyBraces = "curlybraces" + case terminalFill = "terminal.fill" + case terminal = "terminal" + case hammer = "hammer" + case hammerCircle = "hammer.circle" + case ladybug = "ladybug" + case ladybugFill = "ladybug.fill" + case scope = "scope" + case codeChevrons = "chevron.left.slash.chevron.right" + case gearshape = "gearshape" + case gearshapeFill = "gearshape.fill" + case globe = "globe" + case globeAmericas = "globe.americas.fill" + + var id: String { rawValue } + + var title: String { + switch self { + case .wrenchAndScrewdriver: return "Wrench + Screwdriver" + case .wrenchAndScrewdriverFill: return "Wrench + Screwdriver (Fill)" + case .curlyBracesSquare: return "Curly Braces" + case .curlyBraces: return "Curly Braces (Plain)" + case .terminalFill: return "Terminal (Fill)" + case .terminal: return "Terminal" + case .hammer: return "Hammer" + case .hammerCircle: return "Hammer Circle" + case .ladybug: return "Bug" + case .ladybugFill: return "Bug (Fill)" + case .scope: return "Scope" + case .codeChevrons: return "Code Chevrons" + case .gearshape: return "Gear" + case .gearshapeFill: return "Gear (Fill)" + case .globe: return "Globe" + case .globeAmericas: return "Globe Americas (Fill)" + } + } +} + +enum BrowserDevToolsIconColorOption: String, CaseIterable, Identifiable { + case bonsplitInactive + case bonsplitActive + case accent + case tertiary + + var id: String { rawValue } + + var title: String { + switch self { + case .bonsplitInactive: return "Bonsplit Inactive (Terminal/Globe)" + case .bonsplitActive: return "Bonsplit Active (Terminal/Globe)" + case .accent: return "Accent" + case .tertiary: return "Tertiary" + } + } + + var color: Color { + switch self { + case .bonsplitInactive: + // Matches Bonsplit tab icon tint for inactive tabs. + return Color(nsColor: .secondaryLabelColor) + case .bonsplitActive: + // Matches Bonsplit tab icon tint for active tabs. + return Color(nsColor: .labelColor) + case .accent: + return cmuxAccentColor() + case .tertiary: + return Color(nsColor: .tertiaryLabelColor) + } + } +} diff --git a/Sources/Panels/BrowserExternalNavigationPolicy.swift b/Sources/Panels/BrowserExternalNavigationPolicy.swift new file mode 100644 index 000000000000..b61160e138b1 --- /dev/null +++ b/Sources/Panels/BrowserExternalNavigationPolicy.swift @@ -0,0 +1,67 @@ +import Foundation + +private let browserEmbeddedNavigationSchemes: Set = [ + "about", + "applewebdata", + "blob", + "cmux-diff-viewer", + "data", + "file", + "http", + "https", + "javascript", + "webkit-extension", +] + +func browserShouldOpenURLExternally(_ url: URL) -> Bool { + guard let scheme = url.scheme?.lowercased(), !scheme.isEmpty else { return false } + return !browserEmbeddedNavigationSchemes.contains(scheme) +} + +enum BrowserExternalNavigationAction: Equatable { + case browserFallback(URL) + case promptToOpenApp(URL) +} + +enum BrowserExternalNavigationHandlingResult: Equatable { + case notHandled + case browserFallback + case externalPrompt +} + +func browserShouldRouteExternalNavigation(_ url: URL) -> Bool { + return browserExternalNavigationAction(for: url) != nil +} + +func browserIntentFallbackURL(for url: URL) -> URL? { + guard url.scheme?.lowercased() == "intent" else { return nil } + guard let intentMarker = url.absoluteString.range(of: "#Intent;") else { return nil } + + let fallbackPrefix = "S.browser_fallback_url=" + let intentBody = url.absoluteString[intentMarker.upperBound...] + for component in intentBody.split(separator: ";", omittingEmptySubsequences: false) { + if component == "end" { break } + guard component.hasPrefix(fallbackPrefix) else { continue } + + let rawFallbackURL = String(component.dropFirst(fallbackPrefix.count)) + guard !rawFallbackURL.isEmpty else { return nil } + + let decodedFallbackURL = rawFallbackURL.removingPercentEncoding ?? rawFallbackURL + guard let fallbackURL = URL(string: decodedFallbackURL), + let fallbackScheme = fallbackURL.scheme?.lowercased(), + fallbackScheme == "http" || fallbackScheme == "https" else { + return nil + } + return fallbackURL + } + + return nil +} + +func browserExternalNavigationAction(for url: URL) -> BrowserExternalNavigationAction? { + if let fallbackURL = browserIntentFallbackURL(for: url) { + return .browserFallback(fallbackURL) + } + guard browserShouldOpenURLExternally(url) else { return nil } + return .promptToOpenApp(url) +} diff --git a/Sources/Panels/BrowserPanel.swift b/Sources/Panels/BrowserPanel.swift index d552d2e73a99..d18ebc0920e6 100644 --- a/Sources/Panels/BrowserPanel.swift +++ b/Sources/Panels/BrowserPanel.swift @@ -983,72 +983,6 @@ func browserLoadRequest(_ request: URLRequest, in webView: WKWebView) -> WKNavig return webView.load(browserPreparedNavigationRequest(request)) } -private let browserEmbeddedNavigationSchemes: Set = [ - "about", - "applewebdata", - "blob", - "cmux-diff-viewer", - "data", - "file", - "http", - "https", - "javascript", - "webkit-extension", -] - -func browserShouldOpenURLExternally(_ url: URL) -> Bool { - guard let scheme = url.scheme?.lowercased(), !scheme.isEmpty else { return false } - return !browserEmbeddedNavigationSchemes.contains(scheme) -} - -enum BrowserExternalNavigationAction: Equatable { - case browserFallback(URL) - case promptToOpenApp(URL) -} - -enum BrowserExternalNavigationHandlingResult: Equatable { - case notHandled - case browserFallback - case externalPrompt -} - -func browserShouldRouteExternalNavigation(_ url: URL) -> Bool { - return browserExternalNavigationAction(for: url) != nil -} - -func browserIntentFallbackURL(for url: URL) -> URL? { - guard url.scheme?.lowercased() == "intent" else { return nil } - guard let intentMarker = url.absoluteString.range(of: "#Intent;") else { return nil } - - let fallbackPrefix = "S.browser_fallback_url=" - let intentBody = url.absoluteString[intentMarker.upperBound...] - for component in intentBody.split(separator: ";", omittingEmptySubsequences: false) { - if component == "end" { break } - guard component.hasPrefix(fallbackPrefix) else { continue } - - let rawFallbackURL = String(component.dropFirst(fallbackPrefix.count)) - guard !rawFallbackURL.isEmpty else { return nil } - - let decodedFallbackURL = rawFallbackURL.removingPercentEncoding ?? rawFallbackURL - guard let fallbackURL = URL(string: decodedFallbackURL), - let fallbackScheme = fallbackURL.scheme?.lowercased(), - fallbackScheme == "http" || fallbackScheme == "https" else { - return nil - } - return fallbackURL - } - - return nil -} - -func browserExternalNavigationAction(for url: URL) -> BrowserExternalNavigationAction? { - if let fallbackURL = browserIntentFallbackURL(for: url) { - return .browserFallback(fallbackURL) - } - guard browserShouldOpenURLExternally(url) else { return nil } - return .promptToOpenApp(url) -} - private func browserCopyExternalNavigationURL(_ url: URL) { NSPasteboard.general.clearContents() NSPasteboard.general.setString(url.absoluteString, forType: .string) @@ -2749,7 +2683,7 @@ final class BrowserPanel: Panel, ObservableObject { private var websiteDataStore: WKWebsiteDataStore let browserWebExtensionHost: (any BrowserWebExtensionHosting)? private(set) var webExtensionPageContextIdentifier: ObjectIdentifier? - private var isRegisteredForWebExtensions = false + var isRegisteredForWebExtensions = false var webViewDidRequestClose: (() -> Void)? /// Monotonic identity for the current WKWebView instance. @@ -5316,33 +5250,6 @@ final class BrowserPanel: Panel, ObservableObject { } } - func noteWebExtensionActivated() { - browserWebExtensionHost?.noteActivated(panelID: id) - } - - func performWebExtensionCommand(for event: NSEvent) -> Bool { - guard let browserWebExtensionHost else { return false } - noteWebExtensionActivated() - return browserWebExtensionHost.performCommand(for: event) - } - - func registerWebExtensionIfNeeded() { - guard !isRegisteredForWebExtensions, let browserWebExtensionHost else { return } - isRegisteredForWebExtensions = true - browserWebExtensionHost.register(panel: self) - } - - private func unregisterWebExtensionIfNeeded() { - guard isRegisteredForWebExtensions else { return } - isRegisteredForWebExtensions = false - browserWebExtensionHost?.unregister(panelID: id) - } - - @available(macOS 15.4, *) - var browserWebExtensionSupport: BrowserWebExtensionSupport? { - browserWebExtensionHost as? BrowserWebExtensionSupport - } - func close() { unregisterWebExtensionIfNeeded() cancelHiddenWebViewDiscard() diff --git a/Sources/Panels/BrowserPanelView.swift b/Sources/Panels/BrowserPanelView.swift index a2f6e4f27f36..092a0a94ff25 100644 --- a/Sources/Panels/BrowserPanelView.swift +++ b/Sources/Panels/BrowserPanelView.swift @@ -138,81 +138,6 @@ private extension WKWebView { } } -enum BrowserDevToolsIconOption: String, CaseIterable, Identifiable { - case wrenchAndScrewdriver = "wrench.and.screwdriver" - case wrenchAndScrewdriverFill = "wrench.and.screwdriver.fill" - case curlyBracesSquare = "curlybraces.square" - case curlyBraces = "curlybraces" - case terminalFill = "terminal.fill" - case terminal = "terminal" - case hammer = "hammer" - case hammerCircle = "hammer.circle" - case ladybug = "ladybug" - case ladybugFill = "ladybug.fill" - case scope = "scope" - case codeChevrons = "chevron.left.slash.chevron.right" - case gearshape = "gearshape" - case gearshapeFill = "gearshape.fill" - case globe = "globe" - case globeAmericas = "globe.americas.fill" - - var id: String { rawValue } - - var title: String { - switch self { - case .wrenchAndScrewdriver: return "Wrench + Screwdriver" - case .wrenchAndScrewdriverFill: return "Wrench + Screwdriver (Fill)" - case .curlyBracesSquare: return "Curly Braces" - case .curlyBraces: return "Curly Braces (Plain)" - case .terminalFill: return "Terminal (Fill)" - case .terminal: return "Terminal" - case .hammer: return "Hammer" - case .hammerCircle: return "Hammer Circle" - case .ladybug: return "Bug" - case .ladybugFill: return "Bug (Fill)" - case .scope: return "Scope" - case .codeChevrons: return "Code Chevrons" - case .gearshape: return "Gear" - case .gearshapeFill: return "Gear (Fill)" - case .globe: return "Globe" - case .globeAmericas: return "Globe Americas (Fill)" - } - } -} - -enum BrowserDevToolsIconColorOption: String, CaseIterable, Identifiable { - case bonsplitInactive - case bonsplitActive - case accent - case tertiary - - var id: String { rawValue } - - var title: String { - switch self { - case .bonsplitInactive: return "Bonsplit Inactive (Terminal/Globe)" - case .bonsplitActive: return "Bonsplit Active (Terminal/Globe)" - case .accent: return "Accent" - case .tertiary: return "Tertiary" - } - } - - var color: Color { - switch self { - case .bonsplitInactive: - // Matches Bonsplit tab icon tint for inactive tabs. - return Color(nsColor: .secondaryLabelColor) - case .bonsplitActive: - // Matches Bonsplit tab icon tint for active tabs. - return Color(nsColor: .labelColor) - case .accent: - return cmuxAccentColor() - case .tertiary: - return Color(nsColor: .tertiaryLabelColor) - } - } -} - enum BrowserDevToolsButtonDebugSettings { static let iconNameKey = "browserDevToolsIconName" static let iconColorKey = "browserDevToolsIconColor" diff --git a/Sources/Panels/BrowserWebExtensionDiscoveryService.swift b/Sources/Panels/BrowserWebExtensionDiscoveryService.swift index dec504b8d4e0..127fdf82c36b 100644 --- a/Sources/Panels/BrowserWebExtensionDiscoveryService.swift +++ b/Sources/Panels/BrowserWebExtensionDiscoveryService.swift @@ -26,6 +26,7 @@ struct BrowserWebExtensionCandidate: Identifiable, Hashable, Sendable { actor BrowserWebExtensionDiscoveryService { private static let pluginkitURL = URL(fileURLWithPath: "/usr/bin/pluginkit") private static let pluginkitTimeout: Duration = .seconds(10) + static let pluginkitArguments = ["-m", "-p", "com.apple.Safari.web-extension", "-v"] private var activePluginkitProcess: Process? private var activePluginkitStdout: Pipe? @@ -39,7 +40,7 @@ actor BrowserWebExtensionDiscoveryService { return Self.parse(pluginkitOutput: output) } - /// Parses `pluginkit -m -A -v` output. The tool is human-readable rather + /// Parses `pluginkit -m -v` output. The tool is human-readable rather /// than a documented TSV format, so each line is parsed by extracting the /// `.appex` path first, then reading the leading identifier/version field. static func parse(pluginkitOutput: String) -> [BrowserWebExtensionCandidate] { @@ -120,7 +121,7 @@ actor BrowserWebExtensionDiscoveryService { private func startPluginkitProcess() throws { let process = Process() process.executableURL = Self.pluginkitURL - process.arguments = ["-m", "-p", "com.apple.Safari.web-extension", "-A", "-v"] + process.arguments = Self.pluginkitArguments let stdout = Pipe() process.standardOutput = stdout // Discard rather than pipe stderr: an undrained pipe could block the diff --git a/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift b/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift index 6db2a65c41fa..444b8db9de5a 100644 --- a/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift +++ b/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift @@ -21,7 +21,7 @@ extension BrowserWebExtensionSupport: WKWebExtensionControllerDelegate { _ controller: WKWebExtensionController, focusedWindowFor extensionContext: WKWebExtensionContext ) -> (any WKWebExtensionWindow)? { - popouts(for: extensionContext).first(where: \.isKeyWindow) ?? windowAdapter + focusedWebExtensionWindow(for: NSApp.keyWindow) } private func popouts(for extensionContext: WKWebExtensionContext) -> [BrowserWebExtensionPopoutWindowController] { @@ -272,6 +272,18 @@ extension BrowserWebExtensionSupport: WKWebExtensionControllerDelegate { return true } + func closeBrowserTab(panelID: UUID, workspaceID: UUID) -> Bool { + if let workspace = AppDelegate.shared?.workspaceContainingPanel( + panelId: panelID, + preferredWorkspaceId: workspaceID + )?.workspace { + workspace.markCloseHistoryEligible(panelId: panelID) + return workspace.closePanel(panelID, force: true) + } + guard let dock = dockContainingPanel(panelID) else { return false } + return dock.closePanel(panelID, force: true) + } + private func dockContainingPanel(_ panelID: UUID) -> DockSplitStore? { DockSplitStore.liveStores.first { $0.containsPanel(panelID) } } diff --git a/Sources/Panels/BrowserWebExtensionSupport.swift b/Sources/Panels/BrowserWebExtensionSupport.swift index 36451b4dcf83..9f643756183e 100644 --- a/Sources/Panels/BrowserWebExtensionSupport.swift +++ b/Sources/Panels/BrowserWebExtensionSupport.swift @@ -289,6 +289,11 @@ final class BrowserWebExtensionSupport: NSObject, BrowserWebExtensionHosting { return activePanelID(in: window) == nil ? nil : windowAdapter } + func focusedWebExtensionWindow(for keyWindow: NSWindow?) -> (any WKWebExtensionWindow)? { + guard let keyWindow else { return nil } + return webExtensionWindow(for: keyWindow) + } + private func rememberActivePanel(_ panelID: UUID) { guard let window = tabAdapters[panelID]?.panel?.webView.window else { return } activePanelIDsByWindow[ObjectIdentifier(window)] = panelID @@ -390,3 +395,46 @@ final class BrowserWebExtensionSupport: NSObject, BrowserWebExtensionHosting { controller.didCloseWindow(popout) } } + +/// Creates the app-wide web-extension host at launch on OS versions that +/// support `WKWebExtensionController`; returns nil elsewhere. +@MainActor +func makeBrowserWebExtensionHostAtLaunch( + jsonStore: JSONConfigStore, + catalog: SettingCatalog +) -> (any BrowserWebExtensionHosting)? { + guard #available(macOS 15.4, *) else { return nil } + let support = BrowserWebExtensionSupport() + support.configure(jsonStore: jsonStore, catalog: catalog) + StartupBreadcrumbLog.append("app.init.browserWebExtensions.configured") + return support +} + +extension BrowserPanel { + func noteWebExtensionActivated() { + browserWebExtensionHost?.noteActivated(panelID: id) + } + + func performWebExtensionCommand(for event: NSEvent) -> Bool { + guard let browserWebExtensionHost else { return false } + noteWebExtensionActivated() + return browserWebExtensionHost.performCommand(for: event) + } + + func registerWebExtensionIfNeeded() { + guard !isRegisteredForWebExtensions, let browserWebExtensionHost else { return } + isRegisteredForWebExtensions = true + browserWebExtensionHost.register(panel: self) + } + + func unregisterWebExtensionIfNeeded() { + guard isRegisteredForWebExtensions else { return } + isRegisteredForWebExtensions = false + browserWebExtensionHost?.unregister(panelID: id) + } + + @available(macOS 15.4, *) + var browserWebExtensionSupport: BrowserWebExtensionSupport? { + browserWebExtensionHost as? BrowserWebExtensionSupport + } +} diff --git a/Sources/Panels/BrowserWebExtensionTabAdapter.swift b/Sources/Panels/BrowserWebExtensionTabAdapter.swift index a52042089296..24959c0e4b33 100644 --- a/Sources/Panels/BrowserWebExtensionTabAdapter.swift +++ b/Sources/Panels/BrowserWebExtensionTabAdapter.swift @@ -63,6 +63,15 @@ final class BrowserWebExtensionTabAdapter: NSObject, WKWebExtensionTab { completionHandler(focusOwningCmuxTab() ? nil : webExtensionTabError(code: 3)) } + func close(for context: WKWebExtensionContext, completionHandler: @escaping (Error?) -> Void) { + guard let panel, + support?.closeBrowserTab(panelID: panelID, workspaceID: panel.workspaceId) == true else { + completionHandler(webExtensionTabError(code: 3)) + return + } + completionHandler(nil) + } + func loadURL(_ url: URL, for context: WKWebExtensionContext, completionHandler: @escaping (Error?) -> Void) { guard let panel, let support, diff --git a/Sources/Panels/CmuxWebView.swift b/Sources/Panels/CmuxWebView.swift index 91f425efded7..19bb0762b17c 100644 --- a/Sources/Panels/CmuxWebView.swift +++ b/Sources/Panels/CmuxWebView.swift @@ -51,12 +51,6 @@ struct BrowserImageCopyPasteboardPayload { let sourceURL: URL? } -enum BrowserFocusModeKeyDecision: Equatable { - case inactive - case forwardToWebView - case consume -} - enum BrowserImageCopyPasteboardBuilder { private static let pngPasteboardType = NSPasteboard.PasteboardType(UTType.png.identifier) private static let tiffPasteboardType = NSPasteboard.PasteboardType(UTType.tiff.identifier) @@ -676,12 +670,7 @@ final class CmuxWebView: WKWebView { return finish(AppDelegate.shared?.handleBrowserSurfaceKeyEquivalent(event) == true) } - // Manifest commands may use Control or Option, so dispatch them before - // the Command-only cmux menu-equivalent guard. - if #available(macOS 15.4, *), - let appDelegate = AppDelegate.shared, - appDelegate.shouldOfferBrowserWebExtensionCommand(event), - appDelegate.shortcutEventBrowserPanel(event)?.performWebExtensionCommand(for: event) == true { + if cmuxPerformBrowserWebExtensionCommandKeyEquivalent(event) { return finish(true) } diff --git a/Sources/TabManager.swift b/Sources/TabManager.swift index 3da97c9a8f33..88ff45fbe825 100644 --- a/Sources/TabManager.swift +++ b/Sources/TabManager.swift @@ -6164,48 +6164,6 @@ extension TabManager: WorkspaceGroupHosting {} // id/groupId/isPinned storage. extension Workspace: WorkspaceTabRepresenting {} -extension Notification.Name { - // The sidebar multi-selection sync events moved to CmuxSidebar as typed - // SidebarMultiSelectionShouldCollapseEvent / DidHideEvent (same names). - static let commandPaletteToggleRequested = Notification.Name("cmux.commandPaletteToggleRequested") - static let commandPaletteRequested = Notification.Name("cmux.commandPaletteRequested") - static let commandPaletteSwitcherRequested = Notification.Name("cmux.commandPaletteSwitcherRequested") - static let commandPaletteSubmitRequested = Notification.Name("cmux.commandPaletteSubmitRequested") - static let commandPaletteDismissRequested = Notification.Name("cmux.commandPaletteDismissRequested") - static let commandPaletteRenameTabRequested = Notification.Name("cmux.commandPaletteRenameTabRequested") - static let commandPaletteRenameWorkspaceRequested = Notification.Name("cmux.commandPaletteRenameWorkspaceRequested") - static let commandPaletteEditWorkspaceDescriptionRequested = Notification.Name("cmux.commandPaletteEditWorkspaceDescriptionRequested") - static let commandPaletteMoveSelection = Notification.Name("cmux.commandPaletteMoveSelection") - static let commandPaletteRenameInputInteractionRequested = Notification.Name("cmux.commandPaletteRenameInputInteractionRequested") - static let commandPaletteRenameInputDeleteBackwardRequested = Notification.Name("cmux.commandPaletteRenameInputDeleteBackwardRequested") - static let feedbackComposerRequested = Notification.Name("cmux.feedbackComposerRequested") - static let ghosttyDidSetTitle = Notification.Name("ghosttyDidSetTitle") - static let ghosttyDidFocusTab = Notification.Name("ghosttyDidFocusTab") - static let ghosttyDidFocusSurface = Notification.Name("ghosttyDidFocusSurface") - static let ghosttyDidBecomeFirstResponderSurface = Notification.Name("ghosttyDidBecomeFirstResponderSurface") - static let browserDidBecomeFirstResponderWebView = Notification.Name("browserDidBecomeFirstResponderWebView") - static let browserFocusAddressBar = Notification.Name("browserFocusAddressBar") - static let browserMoveOmnibarSelection = Notification.Name("browserMoveOmnibarSelection") - static let browserDidExitAddressBar = Notification.Name("browserDidExitAddressBar") - static let browserDidFocusAddressBar = Notification.Name("browserDidFocusAddressBar") - static let browserDidBlurAddressBar = Notification.Name("browserDidBlurAddressBar") - static let browserFocusModeStateDidChange = Notification.Name("cmux.browserFocusModeStateDidChange") - static let webViewDidReceiveClick = Notification.Name("webViewDidReceiveClick") - static let terminalPortalVisibilityDidChange = Notification.Name("cmux.terminalPortalVisibilityDidChange") - static let browserPortalRegistryDidChange = Notification.Name("cmux.browserPortalRegistryDidChange") - static let workspaceOrderDidChange = Notification.Name("cmux.workspaceOrderDidChange") - static let workspacePaneGeometryDidChange = Notification.Name("cmux.workspacePaneGeometryDidChange") - /// Posted when an existing workspace group's `name` changes (rename). The - /// imperatively-cached window-chrome surfaces (custom title bar in - /// `ContentView`, toolbar command label in `WindowToolbarController`) read - /// a grouped anchor's displayed name from `group.name` and refresh on this. - static let workspaceGroupNameDidChange = Notification.Name("cmux.workspaceGroupNameDidChange") - /// Posted after TabManager has applied a terminal title to workspace state. - static let workspaceTitleDidChange = Notification.Name("cmux.workspaceTitleDidChange") - static let workspaceCurrentDirectoryDidChange = Notification.Name("cmux.workspaceCurrentDirectoryDidChange") - static let tabManagerFocusHistoryRevisionDidChange = Notification.Name("cmux.tabManagerFocusHistoryRevisionDidChange") -} - enum BrowserFirstResponderNotificationUserInfoKey { static let pointerInitiated = "pointerInitiated" } diff --git a/Sources/Workspace+PendingTerminalInput.swift b/Sources/Workspace+PendingTerminalInput.swift new file mode 100644 index 000000000000..e3dace3709ac --- /dev/null +++ b/Sources/Workspace+PendingTerminalInput.swift @@ -0,0 +1,103 @@ +import AppKit +import CmuxWorkspaces + +final class WorkspacePendingTerminalInputObserver: @unchecked Sendable { + var observer: NSObjectProtocol? +} + +extension Workspace { + + /// Delivers config-driven startup input (`Workspace+CustomLayout.swift`) once + /// the terminal surface is ready, or immediately when it already is. + func sendInputWhenReady( + _ text: String, + to panel: TerminalPanel, + reason: WorkspacePendingTerminalInputReason = .configurationCommand + ) { + if panel.surface.surface != nil { + panel.sendInput(text) + return + } + + let timeout = reason.timeout + let panelId = panel.id + let registration = WorkspacePendingTerminalInputObserver() + + registration.observer = NotificationCenter.default.addObserver( + forName: .terminalSurfaceDidBecomeReady, + object: panel.surface, + queue: .main + ) { [weak self, registration] _ in + Task { @MainActor [weak self, registration] in + guard + let self, + self.hasPendingTerminalInputObserver(registration, forPanelId: panelId) + else { + return + } + + self.removePendingTerminalInputObserver(registration, forPanelId: panelId) + if let panel = self.panels[panelId] as? TerminalPanel { + panel.sendInput(text) + } + } + } + pendingTerminalInputObserversByPanelId[panelId, default: []].append(registration) + panel.surface.requestBackgroundSurfaceStartIfNeeded() + + guard let timeout else { return } + DispatchQueue.main.asyncAfter(deadline: .now() + timeout) { [weak self, registration] in + Task { @MainActor [weak self, registration] in + guard + let self, + self.hasPendingTerminalInputObserver(registration, forPanelId: panelId) + else { + return + } + + self.removePendingTerminalInputObserver(registration, forPanelId: panelId) + #if DEBUG + NSLog("[CmuxConfig] surface not ready after 3s, dropping command (%d chars)", text.count) + #endif + } + } + } + + private func hasPendingTerminalInputObserver( + _ registration: WorkspacePendingTerminalInputObserver, + forPanelId panelId: UUID + ) -> Bool { + pendingTerminalInputObserversByPanelId[panelId]?.contains { + $0 === registration + } == true + } + + private func removePendingTerminalInputObserver( + _ registration: WorkspacePendingTerminalInputObserver, + forPanelId panelId: UUID + ) { + if let observer = registration.observer { + NotificationCenter.default.removeObserver(observer) + registration.observer = nil + } + pendingTerminalInputObserversByPanelId[panelId]?.removeAll { + $0 === registration + } + if pendingTerminalInputObserversByPanelId[panelId]?.isEmpty == true { + pendingTerminalInputObserversByPanelId.removeValue(forKey: panelId) + } + } + + func removePendingTerminalInputObservers(forPanelId panelId: UUID) { + guard let observers = pendingTerminalInputObserversByPanelId.removeValue(forKey: panelId) else { + return + } + for registration in observers { + if let observer = registration.observer { + NotificationCenter.default.removeObserver(observer) + registration.observer = nil + } + } + } + +} diff --git a/Sources/Workspace.swift b/Sources/Workspace.swift index 423e550ca67f..490fa3a4ef60 100644 --- a/Sources/Workspace.swift +++ b/Sources/Workspace.swift @@ -40,10 +40,6 @@ func debugWorkspaceDescriptionPreview(_ text: String?, limit: Int = 120) -> Stri } #endif -private final class WorkspacePendingTerminalInputObserver: @unchecked Sendable { - var observer: NSObjectProtocol? -} - private struct SessionPaneRestoreEntry { let paneId: PaneID let snapshot: SessionPaneLayoutSnapshot @@ -1816,102 +1812,6 @@ extension Workspace { // MARK: - Config-driven terminal input delivery -extension Workspace { - - /// Delivers config-driven startup input (`Workspace+CustomLayout.swift`) once - /// the terminal surface is ready, or immediately when it already is. - func sendInputWhenReady( - _ text: String, - to panel: TerminalPanel, - reason: WorkspacePendingTerminalInputReason = .configurationCommand - ) { - if panel.surface.surface != nil { - panel.sendInput(text) - return - } - - let timeout = reason.timeout - let panelId = panel.id - let registration = WorkspacePendingTerminalInputObserver() - - registration.observer = NotificationCenter.default.addObserver( - forName: .terminalSurfaceDidBecomeReady, - object: panel.surface, - queue: .main - ) { [weak self, registration] _ in - Task { @MainActor [weak self, registration] in - guard - let self, - self.hasPendingTerminalInputObserver(registration, forPanelId: panelId) - else { - return - } - - self.removePendingTerminalInputObserver(registration, forPanelId: panelId) - if let panel = self.panels[panelId] as? TerminalPanel { - panel.sendInput(text) - } - } - } - pendingTerminalInputObserversByPanelId[panelId, default: []].append(registration) - panel.surface.requestBackgroundSurfaceStartIfNeeded() - - guard let timeout else { return } - DispatchQueue.main.asyncAfter(deadline: .now() + timeout) { [weak self, registration] in - Task { @MainActor [weak self, registration] in - guard - let self, - self.hasPendingTerminalInputObserver(registration, forPanelId: panelId) - else { - return - } - - self.removePendingTerminalInputObserver(registration, forPanelId: panelId) - #if DEBUG - NSLog("[CmuxConfig] surface not ready after 3s, dropping command (%d chars)", text.count) - #endif - } - } - } - - private func hasPendingTerminalInputObserver( - _ registration: WorkspacePendingTerminalInputObserver, - forPanelId panelId: UUID - ) -> Bool { - pendingTerminalInputObserversByPanelId[panelId]?.contains { - $0 === registration - } == true - } - - private func removePendingTerminalInputObserver( - _ registration: WorkspacePendingTerminalInputObserver, - forPanelId panelId: UUID - ) { - if let observer = registration.observer { - NotificationCenter.default.removeObserver(observer) - registration.observer = nil - } - pendingTerminalInputObserversByPanelId[panelId]?.removeAll { - $0 === registration - } - if pendingTerminalInputObserversByPanelId[panelId]?.isEmpty == true { - pendingTerminalInputObserversByPanelId.removeValue(forKey: panelId) - } - } - - func removePendingTerminalInputObservers(forPanelId panelId: UUID) { - guard let observers = pendingTerminalInputObserversByPanelId.removeValue(forKey: panelId) else { - return - } - for registration in observers { - if let observer = registration.observer { - NotificationCenter.default.removeObserver(observer) - registration.observer = nil - } - } - } - -} /// Lifted to `CmuxBrowser.ClosedBrowserPanelRestoreSnapshot` (Workspace @@ -2368,7 +2268,7 @@ final class Workspace: Identifiable, ObservableObject { } var restoredAgentResumeStatesByPanelId: [UUID: RestoredAgentResumeState] = [:] var invalidatedRestoredAgentFingerprintsByPanelId: [UUID: Int] = [:] - private var pendingTerminalInputObserversByPanelId: [UUID: [WorkspacePendingTerminalInputObserver]] = [:] + var pendingTerminalInputObserversByPanelId: [UUID: [WorkspacePendingTerminalInputObserver]] = [:] private let sessionRestorePolicy: WorkspaceSessionRestorePolicyService typealias SurfaceResumeStartupLaunch = WorkspaceSurfaceResumeStartupLaunch diff --git a/Sources/cmuxApp.swift b/Sources/cmuxApp.swift index d43a5968cb13..4712e5c1262b 100644 --- a/Sources/cmuxApp.swift +++ b/Sources/cmuxApp.swift @@ -159,14 +159,13 @@ struct cmuxApp: App { // Reconcile saved language preference before any UI loads LanguageSettingsStore(defaults: .standard).reconcileLanguageOverrideAtLaunch() StartupBreadcrumbLog.append("app.init.language.applied") - let settingsJSONStore = JSONConfigStore(fileURL: configFileURL) self.settingsRuntime = SettingsRuntime( catalog: settingsCatalog, userDefaultsStore: UserDefaultsSettingsStore( defaults: .standard, migrating: settingsCatalog.all ), - jsonStore: settingsJSONStore, + jsonStore: JSONConfigStore(fileURL: configFileURL), secretStore: secretStore, errorLog: SettingsErrorLog(), accountFlow: HostAccountFlow( @@ -176,18 +175,7 @@ struct cmuxApp: App { hostActions: HostSettingsActions(configFileURL: configFileURL) ) StartupBreadcrumbLog.append("app.init.settingsRuntime.created") - let browserWebExtensionHost: (any BrowserWebExtensionHosting)? - if #available(macOS 15.4, *) { - let support = BrowserWebExtensionSupport() - support.configure( - jsonStore: settingsJSONStore, - catalog: settingsCatalog - ) - browserWebExtensionHost = support - StartupBreadcrumbLog.append("app.init.browserWebExtensions.configured") - } else { - browserWebExtensionHost = nil - } + let startupAppearance = AppearanceSettings.resolvedMode() Self.applyAppearance(startupAppearance, duringLaunch: true) StartupBreadcrumbLog.append("app.init.appearance.applied", fields: ["mode": startupAppearance.rawValue]) @@ -1461,49 +1449,6 @@ private struct MainWindowBootstrapView: View { } } -private let cmuxAuxiliaryWindowIdentifiers: Set = [ - "cmux.settings", - "cmux.about", - "cmux.licenses", - "cmux.browser-popup", - "cmux.browserProfilePopoverDebug", - "cmux.configEditor", - "cmux.defaultTerminalRegistrationError", - "cmux.feedButtonStyleDebug", - "cmux.feedPreview", - "cmux.feedTextEditorDebug", - "cmux.fileExplorerStyleDebug", - "cmux.folderDragIcon", - "cmux.pdfPreviewChromeDebug", - "cmux.proBadgeDebug", - "cmux.recentlyClosedHistory", - "cmux.splitButtonLayoutDebug", - "cmux.tabBarBackdropLab", - "cmux.taskManager", - "cmux.aboutTitlebarDebug", - "cmux.debugWindowControls", - "cmux.browserImportHintDebug", - "cmux.extensionSidebarInspector", - "cmux.sidebarDebug", - "cmux.menubarDebug", - "cmux.spinnerGallery", - "cmux.backgroundDebug", - "cmux.startupAppearanceDebug", - "cmux.bonsplitTabBarDebug", - "cmux.titlebarLayoutDebug", - "cmux.devWindowDisplay", - "cmux.mobilePairingWindow", - "cmux.webExtensionPopout", -] - -/// Returns whether the given window should handle the standard close shortcut -/// as a standalone auxiliary window instead of routing it through workspace or -/// panel-close behavior. -func cmuxWindowShouldOwnCloseShortcut(_ window: NSWindow?) -> Bool { - guard let identifier = window?.identifier?.rawValue else { return false } - return cmuxAuxiliaryWindowIdentifiers.contains(identifier) -} - private enum DebugWindowConfigSnapshot { static func copyCombinedToPasteboard(defaults: UserDefaults = .standard) { let pasteboard = NSPasteboard.general diff --git a/cmux.xcodeproj/project.pbxproj b/cmux.xcodeproj/project.pbxproj index 685a198f95a6..a3193241ee27 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -171,6 +171,7 @@ C0DE71B10000000000000001 /* AppDelegate+AgentChatNotifications.swift in Sources 7C592156DCB3419BB95383E5 /* AutoNamingEngineTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7752D68A758642EFA282C208 /* AutoNamingEngineTests.swift */; }; A4ECF22C62724853A72D6BDE /* AutoNamingGrokAdapterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 07EC52007B2144C59C047774 /* AutoNamingGrokAdapterTests.swift */; }; 74AB3F34FE3B4974A3A5D264 /* AutoNamingHookPayloadAdapterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 46792DAA478444ED87B17B31 /* AutoNamingHookPayloadAdapterTests.swift */; }; + FADE00010000000000000001 /* AuxiliaryWindowCloseShortcut.swift in Sources */ = {isa = PBXBuildFile; fileRef = FADE00010000000000000002 /* AuxiliaryWindowCloseShortcut.swift */; }; C0DE35860000000000000001 /* BackgroundWorkspacePrimeCoordinator.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE35860000000000000002 /* BackgroundWorkspacePrimeCoordinator.swift */; }; A50012F1 /* Backport.swift in Sources */ = {isa = PBXBuildFile; fileRef = A50012F0 /* Backport.swift */; }; B057B0017E57B0017E57B001 /* Bonsplit in Frameworks */ = {isa = PBXBuildFile; productRef = A5001262 /* Bonsplit */; }; @@ -190,6 +191,7 @@ C0DE71B10000000000000001 /* AppDelegate+AgentChatNotifications.swift in Sources B1F0C0050000000000000001 /* BrowserDeveloperToolsDockControlNormalizer.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1F0C0050000000000000002 /* BrowserDeveloperToolsDockControlNormalizer.swift */; }; B1F0C0060000000000000001 /* BrowserDeveloperToolsDockControlNormalizerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1F0C0060000000000000002 /* BrowserDeveloperToolsDockControlNormalizerTests.swift */; }; B1F0C0070000000000000001 /* BrowserDeveloperToolsLifecycleTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1F0C0070000000000000002 /* BrowserDeveloperToolsLifecycleTests.swift */; }; + FADE00030000000000000001 /* BrowserDevToolsIconOptions.swift in Sources */ = {isa = PBXBuildFile; fileRef = FADE00030000000000000002 /* BrowserDevToolsIconOptions.swift */; }; B75040020000000000000001 /* BrowserDiscardedWebViewRestoreRetryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B75040020000000000000002 /* BrowserDiscardedWebViewRestoreRetryTests.swift */; }; B75040010000000000000001 /* BrowserDiscardRestoreHeal.swift in Sources */ = {isa = PBXBuildFile; fileRef = B75040010000000000000002 /* BrowserDiscardRestoreHeal.swift */; }; B75040030000000000000001 /* BrowserDiscardRestoreHealPredicateTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = B75040030000000000000002 /* BrowserDiscardRestoreHealPredicateTests.swift */; }; @@ -202,6 +204,7 @@ C0DE71B10000000000000001 /* AppDelegate+AgentChatNotifications.swift in Sources C2035A010000000000000001 /* BrowserErrorPage.swift in Sources */ = {isa = PBXBuildFile; fileRef = C2035A010000000000000002 /* BrowserErrorPage.swift */; }; C2035A020000000000000001 /* BrowserErrorPageContent.swift in Sources */ = {isa = PBXBuildFile; fileRef = C2035A020000000000000002 /* BrowserErrorPageContent.swift */; }; C2035A0C000000000000001 /* BrowserErrorPageRetry.swift in Sources */ = {isa = PBXBuildFile; fileRef = C2035A0C000000000000002 /* BrowserErrorPageRetry.swift */; }; + FADE00020000000000000001 /* BrowserExternalNavigationPolicy.swift in Sources */ = {isa = PBXBuildFile; fileRef = FADE00020000000000000002 /* BrowserExternalNavigationPolicy.swift */; }; D7632A11A1B2C3D4E5F60718 /* BrowserFileDropNavigationGuard.swift in Sources */ = {isa = PBXBuildFile; fileRef = D7632A12A1B2C3D4E5F60718 /* BrowserFileDropNavigationGuard.swift */; }; A5008381 /* BrowserFindJavaScriptTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5008380 /* BrowserFindJavaScriptTests.swift */; }; A5008373 /* BrowserFindWebViewEvaluator.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5008372 /* BrowserFindWebViewEvaluator.swift */; }; @@ -530,6 +533,7 @@ C0DE71B10000000000000001 /* AppDelegate+AgentChatNotifications.swift in Sources C54860010000000000000001 /* CmuxNavigationTargetResolver.swift in Sources */ = {isa = PBXBuildFile; fileRef = C54860010000000000000002 /* CmuxNavigationTargetResolver.swift */; }; C54860030000000000000001 /* CmuxNavigationTargetResolverTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C54860030000000000000002 /* CmuxNavigationTargetResolverTests.swift */; }; C54860130000000000000001 /* CmuxNavigationWorkspaceDescriptor.swift in Sources */ = {isa = PBXBuildFile; fileRef = C54860130000000000000002 /* CmuxNavigationWorkspaceDescriptor.swift */; }; + FADE00040000000000000001 /* CmuxNotificationNames.swift in Sources */ = {isa = PBXBuildFile; fileRef = FADE00040000000000000002 /* CmuxNotificationNames.swift */; }; E3B7A30000000000000000D3 /* CmuxNotifications in Frameworks */ = {isa = PBXBuildFile; productRef = E3B7A30000000000000000D2 /* CmuxNotifications */; }; C0DE31390000000000000101 /* CMUXOpenCommandTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE31390000000000000102 /* CMUXOpenCommandTests.swift */; }; C0DE31390000000000000111 /* CMUXOpenHTMLFocusTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE31390000000000000112 /* CMUXOpenHTMLFocusTests.swift */; }; @@ -1635,6 +1639,7 @@ C0DE71B10000000000000001 /* AppDelegate+AgentChatNotifications.swift in Sources F17F00000000000000000005 /* Workspace+FullWidthTab.swift in Sources */ = {isa = PBXBuildFile; fileRef = F17F00000000000000000006 /* Workspace+FullWidthTab.swift */; }; C0DE1A050000000000000001 /* Workspace+LayoutCapture.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE1A050000000000000002 /* Workspace+LayoutCapture.swift */; }; C3744E010000000000000001 /* Workspace+PanelLifecycle.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3744E020000000000000001 /* Workspace+PanelLifecycle.swift */; }; + FADE00050000000000000001 /* Workspace+PendingTerminalInput.swift in Sources */ = {isa = PBXBuildFile; fileRef = FADE00050000000000000002 /* Workspace+PendingTerminalInput.swift */; }; 7738C0037738C0037738C003 /* Workspace+RemoteTmuxControlTopology.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7738D0037738D0037738D003 /* Workspace+RemoteTmuxControlTopology.swift */; }; D77340010000000000000002 /* Workspace+RemoteTmuxTabOrder.swift in Sources */ = {isa = PBXBuildFile; fileRef = D77340010000000000000001 /* Workspace+RemoteTmuxTabOrder.swift */; }; C548600A000000000000001 /* Workspace+SessionRestoreIdentity.swift in Sources */ = {isa = PBXBuildFile; fileRef = C548600A000000000000002 /* Workspace+SessionRestoreIdentity.swift */; }; @@ -1952,6 +1957,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = 7752D68A758642EFA282C208 /* AutoNamingEngineTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AutoNamingEngineTests.swift; sourceTree = ""; }; 07EC52007B2144C59C047774 /* AutoNamingGrokAdapterTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AutoNamingGrokAdapterTests.swift; sourceTree = ""; }; 46792DAA478444ED87B17B31 /* AutoNamingHookPayloadAdapterTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AutoNamingHookPayloadAdapterTests.swift; sourceTree = ""; }; + FADE00010000000000000002 /* AuxiliaryWindowCloseShortcut.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = App/AuxiliaryWindowCloseShortcut.swift; sourceTree = ""; }; C0DE35860000000000000002 /* BackgroundWorkspacePrimeCoordinator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BackgroundWorkspacePrimeCoordinator.swift; sourceTree = ""; }; A50012F0 /* Backport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Backport.swift; sourceTree = ""; }; 74060000000000000000001A /* BonsplitConfiguration+RemoteTmuxEmbedded.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "BonsplitConfiguration+RemoteTmuxEmbedded.swift"; sourceTree = ""; }; @@ -1970,6 +1976,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = B1F0C0050000000000000002 /* BrowserDeveloperToolsDockControlNormalizer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/BrowserDeveloperToolsDockControlNormalizer.swift; sourceTree = ""; }; B1F0C0060000000000000002 /* BrowserDeveloperToolsDockControlNormalizerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BrowserDeveloperToolsDockControlNormalizerTests.swift; sourceTree = ""; }; B1F0C0070000000000000002 /* BrowserDeveloperToolsLifecycleTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BrowserDeveloperToolsLifecycleTests.swift; sourceTree = ""; }; + FADE00030000000000000002 /* BrowserDevToolsIconOptions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/BrowserDevToolsIconOptions.swift; sourceTree = ""; }; B75040020000000000000002 /* BrowserDiscardedWebViewRestoreRetryTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BrowserDiscardedWebViewRestoreRetryTests.swift; sourceTree = ""; }; B75040010000000000000002 /* BrowserDiscardRestoreHeal.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/BrowserDiscardRestoreHeal.swift; sourceTree = ""; }; B75040030000000000000002 /* BrowserDiscardRestoreHealPredicateTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BrowserDiscardRestoreHealPredicateTests.swift; sourceTree = ""; }; @@ -1982,6 +1989,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = C2035A010000000000000002 /* BrowserErrorPage.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/BrowserErrorPage.swift; sourceTree = ""; }; C2035A020000000000000002 /* BrowserErrorPageContent.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/BrowserErrorPageContent.swift; sourceTree = ""; }; C2035A0C000000000000002 /* BrowserErrorPageRetry.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/BrowserErrorPageRetry.swift; sourceTree = ""; }; + FADE00020000000000000002 /* BrowserExternalNavigationPolicy.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/BrowserExternalNavigationPolicy.swift; sourceTree = ""; }; D7632A12A1B2C3D4E5F60718 /* BrowserFileDropNavigationGuard.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BrowserFileDropNavigationGuard.swift; sourceTree = ""; }; A5008380 /* BrowserFindJavaScriptTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BrowserFindJavaScriptTests.swift; sourceTree = ""; }; A5008372 /* BrowserFindWebViewEvaluator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Find/BrowserFindWebViewEvaluator.swift; sourceTree = ""; }; @@ -2284,6 +2292,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = C54860010000000000000002 /* CmuxNavigationTargetResolver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CmuxNavigationTargetResolver.swift; sourceTree = ""; }; C54860030000000000000002 /* CmuxNavigationTargetResolverTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CmuxNavigationTargetResolverTests.swift; sourceTree = ""; }; C54860130000000000000002 /* CmuxNavigationWorkspaceDescriptor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CmuxNavigationWorkspaceDescriptor.swift; sourceTree = ""; }; + FADE00040000000000000002 /* CmuxNotificationNames.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CmuxNotificationNames.swift; sourceTree = ""; }; C0DE31390000000000000102 /* CMUXOpenCommandTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CMUXOpenCommandTests.swift; sourceTree = ""; }; C0DE31390000000000000112 /* CMUXOpenHTMLFocusTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CMUXOpenHTMLFocusTests.swift; sourceTree = ""; }; A9F100000000000000000005 /* CmuxRuntimeDebugCapture.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CmuxRuntimeDebugCapture.swift; sourceTree = ""; }; @@ -3344,6 +3353,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = F17F00000000000000000006 /* Workspace+FullWidthTab.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Workspace+FullWidthTab.swift"; sourceTree = ""; }; C0DE1A050000000000000002 /* Workspace+LayoutCapture.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Workspace+LayoutCapture.swift"; sourceTree = ""; }; C3744E020000000000000001 /* Workspace+PanelLifecycle.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Workspace+PanelLifecycle.swift"; sourceTree = ""; }; + FADE00050000000000000002 /* Workspace+PendingTerminalInput.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Workspace+PendingTerminalInput.swift"; sourceTree = ""; }; 7738D0037738D0037738D003 /* Workspace+RemoteTmuxControlTopology.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Workspace+RemoteTmuxControlTopology.swift"; sourceTree = ""; }; D77340010000000000000001 /* Workspace+RemoteTmuxTabOrder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Workspace+RemoteTmuxTabOrder.swift"; sourceTree = ""; }; C548600A000000000000002 /* Workspace+SessionRestoreIdentity.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Workspace+SessionRestoreIdentity.swift"; sourceTree = ""; }; @@ -3913,6 +3923,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = 47D5AA7D29C94F5CA865B2BF /* ScreenIdentity.swift */, C1713001C1713001C1713001 /* CommandPaletteShortcutRouting.swift */, B42A82C6AA614E74873D9A5F /* ShortcutRoutingSupport.swift */, + FADE00010000000000000002 /* AuxiliaryWindowCloseShortcut.swift */, 81B8CFAF8FCA4231C702D16A /* WindowKeyDownReplayGuard.swift */, 604500200000000000000002 /* WindowTitleTemplateContext.swift */, 604500100000000000000002 /* WindowTitleTemplate.swift */, @@ -4033,6 +4044,8 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = C7268001000000000000002 /* Workspace+CustomSidebarSnapshot.swift */, C7268002000000000000002 /* Workspace+SidebarDirectories.swift */, DCDC1000000000000000B014 /* Workspace+DockBrowserLookup.swift */, + FADE00040000000000000002 /* CmuxNotificationNames.swift */, + FADE00050000000000000002 /* Workspace+PendingTerminalInput.swift */, E30780000000000000000011 /* SSHPTYAttachStartupCommandBuilder.swift */, EE30D5000000000000000001 /* RemoteDaemonStrings+App.swift */, EE30D5000000000000000003 /* WorkspaceRemoteRelayCommandRewriter.swift */, @@ -4341,6 +4354,8 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = B1CFE0110000000000000002 /* BrowserWebExtensionActionSnapshotInvalidation.swift */, B1CFE00B0000000000000002 /* BrowserWebExtensionLoadedRecord.swift */, B1CFE00D0000000000000002 /* BrowserWebExtensionNavigationConfiguration.swift */, + FADE00020000000000000002 /* BrowserExternalNavigationPolicy.swift */, + FADE00030000000000000002 /* BrowserDevToolsIconOptions.swift */, B1CFE00E0000000000000002 /* BrowserWebExtensionPermissionState.swift */, B1CFE00F0000000000000002 /* BrowserWebExtensionPermissionStateStore.swift */, B1CFE00C0000000000000002 /* BrowserWebExtensionReconciliationPlanner.swift */, @@ -5803,6 +5818,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = A5001A02A1B2C3D4E5F60718 /* AppWindowBackdropControllerDependencies.swift in Sources */, A5001A00A1B2C3D4E5F60718 /* AppWindowChromeComposition.swift in Sources */, D9FEC58D5BACCF76459F1BBE /* AuthEnvironment.swift in Sources */, + FADE00010000000000000001 /* AuxiliaryWindowCloseShortcut.swift in Sources */, C0DE35860000000000000001 /* BackgroundWorkspacePrimeCoordinator.swift in Sources */, A50012F1 /* Backport.swift in Sources */, 74060000000000000000001B /* BonsplitConfiguration+RemoteTmuxEmbedded.swift in Sources */, @@ -5814,6 +5830,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = D7032A020000000000000001 /* BrowserClientCertificateAuthenticationController.swift in Sources */, D7032A050000000000000001 /* BrowserClientCertificateCredentialPicker.swift in Sources */, B1F0C0050000000000000001 /* BrowserDeveloperToolsDockControlNormalizer.swift in Sources */, + FADE00030000000000000001 /* BrowserDevToolsIconOptions.swift in Sources */, B75040010000000000000001 /* BrowserDiscardRestoreHeal.swift in Sources */, C42660030000000000000001 /* BrowserDownloadDelegate+PDFPreviewData.swift in Sources */, C59240010000000000000001 /* BrowserDownloadFilenameResolver.swift in Sources */, @@ -5823,6 +5840,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = C2035A010000000000000001 /* BrowserErrorPage.swift in Sources */, C2035A020000000000000001 /* BrowserErrorPageContent.swift in Sources */, C2035A0C000000000000001 /* BrowserErrorPageRetry.swift in Sources */, + FADE00020000000000000001 /* BrowserExternalNavigationPolicy.swift in Sources */, D7632A11A1B2C3D4E5F60718 /* BrowserFileDropNavigationGuard.swift in Sources */, A5008373 /* BrowserFindWebViewEvaluator.swift in Sources */, B42450030000000000000001 /* BrowserHiddenWebViewDiscardManager.swift in Sources */, @@ -5966,6 +5984,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = C54860120000000000000001 /* CmuxNavigationSurfaceDescriptor.swift in Sources */, C54860010000000000000001 /* CmuxNavigationTargetResolver.swift in Sources */, C54860130000000000000001 /* CmuxNavigationWorkspaceDescriptor.swift in Sources */, + FADE00040000000000000001 /* CmuxNotificationNames.swift in Sources */, A9F200000000000000000005 /* CmuxRuntimeDebugCapture.swift in Sources */, A9F200000000000000000006 /* CmuxRuntimeDebugCaptureConfiguration.swift in Sources */, A9F20000000000000000001A /* CmuxRuntimeDebugCaptureSender.swift in Sources */, @@ -6703,6 +6722,7 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = F17F00000000000000000005 /* Workspace+FullWidthTab.swift in Sources */, C0DE1A050000000000000001 /* Workspace+LayoutCapture.swift in Sources */, C3744E010000000000000001 /* Workspace+PanelLifecycle.swift in Sources */, + FADE00050000000000000001 /* Workspace+PendingTerminalInput.swift in Sources */, 7738C0037738C0037738C003 /* Workspace+RemoteTmuxControlTopology.swift in Sources */, D77340010000000000000002 /* Workspace+RemoteTmuxTabOrder.swift in Sources */, C548600A000000000000001 /* Workspace+SessionRestoreIdentity.swift in Sources */, diff --git a/cmuxTests/BrowserWebExtensionReviewRegressionTests.swift b/cmuxTests/BrowserWebExtensionReviewRegressionTests.swift index 02a7ccb14a37..ff9360b1708c 100644 --- a/cmuxTests/BrowserWebExtensionReviewRegressionTests.swift +++ b/cmuxTests/BrowserWebExtensionReviewRegressionTests.swift @@ -19,8 +19,12 @@ struct BrowserWebExtensionReviewRegressionTests { BrowserAvailabilitySettings.setDisabled(false) defer { BrowserAvailabilitySettings.setDisabled(wasBrowserDisabled) } + let appDelegate = try #require(AppDelegate.shared) + let previousTabManager = appDelegate.tabManager + defer { appDelegate.tabManager = previousTabManager } let support = BrowserWebExtensionSupport() let tabManager = TabManager(browserWebExtensionHost: support) + appDelegate.tabManager = tabManager let workspace = try #require(tabManager.selectedWorkspace) #expect(workspace.panels.values.allSatisfy { !($0 is BrowserPanel) }) @@ -32,9 +36,10 @@ struct BrowserWebExtensionReviewRegressionTests { ) let panel = try #require(adapter?.panel) - defer { _ = workspace.closePanel(panel.id, force: true) } #expect(panel.workspaceId == workspace.id) #expect(workspace.panels[panel.id] === panel) + #expect(support.closeBrowserTab(panelID: panel.id, workspaceID: workspace.id)) + #expect(workspace.panels[panel.id] == nil) } @MainActor diff --git a/cmuxTests/BrowserWebExtensionSupportTests.swift b/cmuxTests/BrowserWebExtensionSupportTests.swift index ec7c4049a2ec..8592bbd42100 100644 --- a/cmuxTests/BrowserWebExtensionSupportTests.swift +++ b/cmuxTests/BrowserWebExtensionSupportTests.swift @@ -10,7 +10,7 @@ import WebKit @testable import cmux #endif -@Suite +@Suite(.serialized) struct BrowserWebExtensionSupportTests { @MainActor @Test @@ -62,6 +62,9 @@ struct BrowserWebExtensionSupportTests { #expect((support.webExtensionWindow(for: firstWindow) as AnyObject?) === support.windowAdapter) let unrelatedWindow = NSWindow() #expect(support.webExtensionWindow(for: unrelatedWindow) == nil) + #expect((support.focusedWebExtensionWindow(for: firstWindow) as AnyObject?) === support.windowAdapter) + #expect(support.focusedWebExtensionWindow(for: unrelatedWindow) == nil) + #expect(support.focusedWebExtensionWindow(for: nil) == nil) } @Test @@ -451,6 +454,16 @@ struct BrowserWebExtensionSupportTests { #expect(candidates.last?.version == "1.2.3") #expect(candidates.last?.path == "/Applications/Example App.app/Contents/PlugIns/Example Extension.appex") } + + @Test + func pluginkitQueriesOnlyTheElectedExtensionVersion() { + #expect(BrowserWebExtensionDiscoveryService.pluginkitArguments == [ + "-m", + "-p", + "com.apple.Safari.web-extension", + "-v", + ]) + } } @MainActor From b0fff2f130847c0ca146cded0b06fd6881a8afc3 Mon Sep 17 00:00:00 2001 From: 0xCUB3 Date: Fri, 10 Jul 2026 07:17:10 -0400 Subject: [PATCH 49/51] Address browser extension review feedback --- Resources/Localizable.xcstrings | 250 ------------------ .../Panels/BrowserWebExtensionSupport.swift | 13 - Sources/cmuxApp.swift | 14 +- 3 files changed, 13 insertions(+), 264 deletions(-) diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index 90f7082b7e44..53adc94951d3 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -235957,256 +235957,6 @@ } } } - }, - "settings.browser.webExtensions.duplicate.title": { - "extractionState": "manual", - "localizations": { - "ar": { - "stringUnit": { - "state": "translated", - "value": "تمت إضافة الإضافة بالفعل" - } - }, - "bs": { - "stringUnit": { - "state": "translated", - "value": "Ekstenzija je već dodana" - } - }, - "da": { - "stringUnit": { - "state": "translated", - "value": "Udvidelsen er allerede tilføjet" - } - }, - "de": { - "stringUnit": { - "state": "translated", - "value": "Erweiterung bereits hinzugefügt" - } - }, - "en": { - "stringUnit": { - "state": "translated", - "value": "Extension Already Added" - } - }, - "es": { - "stringUnit": { - "state": "translated", - "value": "La extensión ya se agregó" - } - }, - "fr": { - "stringUnit": { - "state": "translated", - "value": "Extension déjà ajoutée" - } - }, - "it": { - "stringUnit": { - "state": "translated", - "value": "Estensione già aggiunta" - } - }, - "ja": { - "stringUnit": { - "state": "translated", - "value": "拡張機能はすでに追加されています" - } - }, - "km": { - "stringUnit": { - "state": "translated", - "value": "បានបន្ថែមផ្នែកបន្ថែមរួចហើយ" - } - }, - "ko": { - "stringUnit": { - "state": "translated", - "value": "확장 프로그램이 이미 추가됨" - } - }, - "nb": { - "stringUnit": { - "state": "translated", - "value": "Utvidelsen er allerede lagt til" - } - }, - "pl": { - "stringUnit": { - "state": "translated", - "value": "Rozszerzenie już dodane" - } - }, - "pt-BR": { - "stringUnit": { - "state": "translated", - "value": "Extensão já adicionada" - } - }, - "ru": { - "stringUnit": { - "state": "translated", - "value": "Расширение уже добавлено" - } - }, - "th": { - "stringUnit": { - "state": "translated", - "value": "เพิ่มส่วนขยายนี้แล้ว" - } - }, - "tr": { - "stringUnit": { - "state": "translated", - "value": "Uzantı Zaten Eklendi" - } - }, - "uk": { - "stringUnit": { - "state": "translated", - "value": "Розширення вже додано" - } - }, - "zh-Hans": { - "stringUnit": { - "state": "translated", - "value": "扩展已添加" - } - }, - "zh-Hant": { - "stringUnit": { - "state": "translated", - "value": "延伸功能已加入" - } - } - } - }, - "settings.browser.webExtensions.duplicate.message": { - "extractionState": "manual", - "localizations": { - "ar": { - "stringUnit": { - "state": "translated", - "value": "“%@” موجودة بالفعل في قائمة الإضافات." - } - }, - "bs": { - "stringUnit": { - "state": "translated", - "value": "“%@” je već na listi ekstenzija." - } - }, - "da": { - "stringUnit": { - "state": "translated", - "value": "“%@” findes allerede på listen over udvidelser." - } - }, - "de": { - "stringUnit": { - "state": "translated", - "value": "„%@“ ist bereits in der Erweiterungsliste." - } - }, - "en": { - "stringUnit": { - "state": "translated", - "value": "“%@” is already in the extensions list." - } - }, - "es": { - "stringUnit": { - "state": "translated", - "value": "“%@” ya está en la lista de extensiones." - } - }, - "fr": { - "stringUnit": { - "state": "translated", - "value": "« %@ » figure déjà dans la liste des extensions." - } - }, - "it": { - "stringUnit": { - "state": "translated", - "value": "“%@” è già nell’elenco delle estensioni." - } - }, - "ja": { - "stringUnit": { - "state": "translated", - "value": "「%@」はすでに拡張機能リストにあります。" - } - }, - "km": { - "stringUnit": { - "state": "translated", - "value": "“%@” មានរួចហើយនៅក្នុងបញ្ជីផ្នែកបន្ថែម។" - } - }, - "ko": { - "stringUnit": { - "state": "translated", - "value": "“%@”은(는) 이미 확장 프로그램 목록에 있습니다." - } - }, - "nb": { - "stringUnit": { - "state": "translated", - "value": "«%@» finnes allerede i utvidelseslisten." - } - }, - "pl": { - "stringUnit": { - "state": "translated", - "value": "„%@” jest już na liście rozszerzeń." - } - }, - "pt-BR": { - "stringUnit": { - "state": "translated", - "value": "“%@” já está na lista de extensões." - } - }, - "ru": { - "stringUnit": { - "state": "translated", - "value": "«%@» уже есть в списке расширений." - } - }, - "th": { - "stringUnit": { - "state": "translated", - "value": "“%@” อยู่ในรายการส่วนขยายแล้ว" - } - }, - "tr": { - "stringUnit": { - "state": "translated", - "value": "“%@” uzantılar listesinde zaten var." - } - }, - "uk": { - "stringUnit": { - "state": "translated", - "value": "«%@» уже є в списку розширень." - } - }, - "zh-Hans": { - "stringUnit": { - "state": "translated", - "value": "“%@”已在扩展列表中。" - } - }, - "zh-Hant": { - "stringUnit": { - "state": "translated", - "value": "「%@」已在延伸功能列表中。" - } - } - } } }, "version": "1.0" diff --git a/Sources/Panels/BrowserWebExtensionSupport.swift b/Sources/Panels/BrowserWebExtensionSupport.swift index 9f643756183e..4e1ed9f51a4f 100644 --- a/Sources/Panels/BrowserWebExtensionSupport.swift +++ b/Sources/Panels/BrowserWebExtensionSupport.swift @@ -396,19 +396,6 @@ final class BrowserWebExtensionSupport: NSObject, BrowserWebExtensionHosting { } } -/// Creates the app-wide web-extension host at launch on OS versions that -/// support `WKWebExtensionController`; returns nil elsewhere. -@MainActor -func makeBrowserWebExtensionHostAtLaunch( - jsonStore: JSONConfigStore, - catalog: SettingCatalog -) -> (any BrowserWebExtensionHosting)? { - guard #available(macOS 15.4, *) else { return nil } - let support = BrowserWebExtensionSupport() - support.configure(jsonStore: jsonStore, catalog: catalog) - StartupBreadcrumbLog.append("app.init.browserWebExtensions.configured") - return support -} extension BrowserPanel { func noteWebExtensionActivated() { diff --git a/Sources/cmuxApp.swift b/Sources/cmuxApp.swift index 4712e5c1262b..c3df3cea318c 100644 --- a/Sources/cmuxApp.swift +++ b/Sources/cmuxApp.swift @@ -187,7 +187,7 @@ struct cmuxApp: App { KeyboardShortcutSettings.settingsFileStore.applyDeferredManagedDefaultSideEffects() StartupBreadcrumbLog.append("app.init.keyboardShortcuts.sideEffectsApplied") StartupBreadcrumbLog.append("app.init.tabManager.begin") - let browserWebExtensionHost = makeBrowserWebExtensionHostAtLaunch( + let browserWebExtensionHost = Self.makeBrowserWebExtensionHostAtLaunch( jsonStore: settingsRuntime.jsonStore, catalog: settingsCatalog ) @@ -230,6 +230,18 @@ struct cmuxApp: App { StartupBreadcrumbLog.append("app.init.delegate.configured") } + @MainActor + private static func makeBrowserWebExtensionHostAtLaunch( + jsonStore: JSONConfigStore, + catalog: SettingCatalog + ) -> (any BrowserWebExtensionHosting)? { + guard #available(macOS 15.4, *) else { return nil } + let support = BrowserWebExtensionSupport() + support.configure(jsonStore: jsonStore, catalog: catalog) + StartupBreadcrumbLog.append("app.init.browserWebExtensions.configured") + return support + } + private static func terminateForMissingLaunchTag() -> Never { let message = "error: refusing to launch untagged cmux DEV; start with ./scripts/reload.sh --tag (or set CMUX_TAG for test harnesses)" fputs("\(message)\n", stderr) From 8d0d68df0d396cc32169bf12a93ed2982138d3b7 Mon Sep 17 00:00:00 2001 From: 0xCUB3 Date: Fri, 10 Jul 2026 07:25:20 -0400 Subject: [PATCH 50/51] Address remaining browser extension review feedback --- Resources/Localizable.xcstrings | 750 ++++++++++++++++++ ...ort+WKWebExtensionControllerDelegate.swift | 5 +- .../Panels/BrowserWebExtensionSupport.swift | 11 + .../BrowserWebExtensionSupportTests.swift | 6 + 4 files changed, 770 insertions(+), 2 deletions(-) diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index 53adc94951d3..516fea290969 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -44938,6 +44938,756 @@ } } }, + "settings.browser.webExtension.permissionPrompt.allow": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "سماح" + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "Dozvoli" + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "Tillad" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Erlauben" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Allow" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Permitir" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Autoriser" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Consenti" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "許可" + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "អនុញ្ញាត" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "허용" + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "Tillat" + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "Zezwól" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Permitir" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Разрешить" + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "อนุญาต" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "İzin Ver" + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "Дозволити" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "允许" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "允許" + } + } + } + }, + "settings.browser.webExtension.permissionPrompt.deny": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "رفض" + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "Odbij" + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "Afvis" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Ablehnen" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Deny" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Denegar" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Refuser" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Nega" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "拒否" + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "បដិសេធ" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "거부" + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "Avslå" + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "Odmów" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Negar" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Запретить" + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "ปฏิเสธ" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Reddet" + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "Заборонити" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "拒绝" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "拒絕" + } + } + } + }, + "settings.browser.webExtension.permissionPrompt.matchPatterns.message": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "يريد الامتداد “%@” الوصول إلى الصفحات المطابقة:\n\n%@" + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "Ekstenzija “%@” traži pristup odgovarajućim stranicama:\n\n%@" + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "Udvidelsen “%@” anmoder om adgang til matchende sider:\n\n%@" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Die Erweiterung „%@“ möchte auf übereinstimmende Seiten zugreifen:\n\n%@" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "The extension “%@” wants access to matching pages:\n\n%@" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "La extensión “%@” solicita acceso a páginas coincidentes:\n\n%@" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "L’extension « %@ » souhaite accéder aux pages correspondantes :\n\n%@" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "L’estensione “%@” vuole accedere alle pagine corrispondenti:\n\n%@" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "機能拡張“%@”が一致するページへのアクセスを求めています:\n\n%@" + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "ផ្នែកបន្ថែម “%@” ចង់ចូលប្រើទំព័រដែលត្រូវគ្នា៖\n\n%@" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "확장 프로그램 “%@”에서 일치하는 페이지에 대한 접근 권한을 요청합니다:\n\n%@" + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "Utvidelsen «%@» ber om tilgang til samsvarende sider:\n\n%@" + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "Rozszerzenie „%@” prosi o dostęp do pasujących stron:\n\n%@" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "A extensão “%@” solicita acesso a páginas correspondentes:\n\n%@" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Расширение «%@» запрашивает доступ к соответствующим страницам:\n\n%@" + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "ส่วนขยาย “%@” ต้องการเข้าถึงหน้าที่ตรงกัน:\n\n%@" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "“%@” uzantısı eşleşen sayfalara erişmek istiyor:\n\n%@" + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "Розширення «%@» запитує доступ до відповідних сторінок:\n\n%@" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "扩展程序“%@”请求访问匹配的页面:\n\n%@" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "延伸功能「%@」想要取用符合條件的網頁:\n\n%@" + } + } + } + }, + "settings.browser.webExtension.permissionPrompt.permissions.message": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "يريد الامتداد “%@” أذونات المتصفح التالية:\n\n%@" + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "Ekstenzija “%@” traži sljedeće dozvole preglednika:\n\n%@" + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "Udvidelsen “%@” anmoder om følgende browsertilladelser:\n\n%@" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Die Erweiterung „%@“ möchte folgende Browserberechtigungen:\n\n%@" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "The extension “%@” wants these browser permissions:\n\n%@" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "La extensión “%@” solicita estos permisos del navegador:\n\n%@" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "L’extension « %@ » souhaite obtenir les autorisations de navigateur suivantes :\n\n%@" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "L’estensione “%@” richiede queste autorizzazioni del browser:\n\n%@" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "機能拡張“%@”が次のブラウザアクセス権を求めています:\n\n%@" + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "ផ្នែកបន្ថែម “%@” ចង់បានសិទ្ធិកម្មវិធីរុករកទាំងនេះ៖\n\n%@" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "확장 프로그램 “%@”에서 다음 브라우저 권한을 요청합니다:\n\n%@" + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "Utvidelsen «%@» ber om disse nettlesertillatelsene:\n\n%@" + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "Rozszerzenie „%@” prosi o następujące uprawnienia przeglądarki:\n\n%@" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "A extensão “%@” solicita estas permissões do navegador:\n\n%@" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Расширение «%@» запрашивает следующие разрешения браузера:\n\n%@" + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "ส่วนขยาย “%@” ต้องการสิทธิ์เบราว์เซอร์ต่อไปนี้:\n\n%@" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "“%@” uzantısı şu tarayıcı izinlerini istiyor:\n\n%@" + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "Розширення «%@» запитує такі дозволи браузера:\n\n%@" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "扩展程序“%@”请求获得以下浏览器权限:\n\n%@" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "延伸功能「%@」想要下列瀏覽器權限:\n\n%@" + } + } + } + }, + "settings.browser.webExtension.permissionPrompt.title": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "السماح للامتداد بالوصول؟" + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "Dozvoliti ekstenziji pristup?" + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "Tillad adgang for udvidelsen?" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Zugriff der Erweiterung erlauben?" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Allow Extension Access?" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "¿Permitir el acceso de la extensión?" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Autoriser l’accès de l’extension ?" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Consentire l’accesso dell’estensione?" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "機能拡張のアクセスを許可しますか?" + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "អនុញ្ញាតឱ្យផ្នែកបន្ថែមចូលប្រើឬទេ?" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "확장 프로그램 접근을 허용하시겠습니까?" + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "Vil du gi utvidelsen tilgang?" + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "Zezwolić rozszerzeniu na dostęp?" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Permitir o acesso da extensão?" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Разрешить расширению доступ?" + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "อนุญาตให้ส่วนขยายเข้าถึงหรือไม่" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Uzantı erişimine izin verilsin mi?" + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "Дозволити розширенню доступ?" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "允许扩展程序访问?" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "允許延伸功能取用嗎?" + } + } + } + }, + "settings.browser.webExtension.permissionPrompt.urls.message": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "يريد الامتداد “%@” الوصول إلى هذه الصفحات:\n\n%@" + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "Ekstenzija “%@” traži pristup ovim stranicama:\n\n%@" + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "Udvidelsen “%@” anmoder om adgang til disse sider:\n\n%@" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Die Erweiterung „%@“ möchte auf diese Seiten zugreifen:\n\n%@" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "The extension “%@” wants access to these pages:\n\n%@" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "La extensión “%@” solicita acceso a estas páginas:\n\n%@" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "L’extension « %@ » souhaite accéder à ces pages :\n\n%@" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "L’estensione “%@” vuole accedere a queste pagine:\n\n%@" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "機能拡張“%@”がこれらのページへのアクセスを求めています:\n\n%@" + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "ផ្នែកបន្ថែម “%@” ចង់ចូលប្រើទំព័រទាំងនេះ៖\n\n%@" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "확장 프로그램 “%@”에서 다음 페이지에 대한 접근 권한을 요청합니다:\n\n%@" + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "Utvidelsen «%@» ber om tilgang til disse sidene:\n\n%@" + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "Rozszerzenie „%@” prosi o dostęp do tych stron:\n\n%@" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "A extensão “%@” solicita acesso a estas páginas:\n\n%@" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Расширение «%@» запрашивает доступ к этим страницам:\n\n%@" + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "ส่วนขยาย “%@” ต้องการเข้าถึงหน้าเหล่านี้:\n\n%@" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "“%@” uzantısı bu sayfalara erişmek istiyor:\n\n%@" + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "Розширення «%@» запитує доступ до цих сторінок:\n\n%@" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "扩展程序“%@”请求访问以下页面:\n\n%@" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "延伸功能「%@」想要取用這些網頁:\n\n%@" + } + } + } + }, "settings.browser.webExtensions": { "extractionState": "manual", "localizations": { diff --git a/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift b/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift index 444b8db9de5a..5c45928e45f5 100644 --- a/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift +++ b/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift @@ -8,7 +8,7 @@ extension BrowserWebExtensionSupport: WKWebExtensionControllerDelegate { openWindowsFor extensionContext: WKWebExtensionContext ) -> [any WKWebExtensionWindow] { let openWindows: [any WKWebExtensionWindow] = [windowAdapter] + popouts(for: extensionContext) - guard let focusedWindow = webExtensionController(controller, focusedWindowFor: extensionContext) else { + guard let focusedWindow = focusedWebExtensionWindow(for: NSApp.keyWindow, among: openWindows) else { return openWindows } let focusedID = ObjectIdentifier(focusedWindow as AnyObject) @@ -21,7 +21,8 @@ extension BrowserWebExtensionSupport: WKWebExtensionControllerDelegate { _ controller: WKWebExtensionController, focusedWindowFor extensionContext: WKWebExtensionContext ) -> (any WKWebExtensionWindow)? { - focusedWebExtensionWindow(for: NSApp.keyWindow) + let openWindows: [any WKWebExtensionWindow] = [windowAdapter] + popouts(for: extensionContext) + return focusedWebExtensionWindow(for: NSApp.keyWindow, among: openWindows) } private func popouts(for extensionContext: WKWebExtensionContext) -> [BrowserWebExtensionPopoutWindowController] { diff --git a/Sources/Panels/BrowserWebExtensionSupport.swift b/Sources/Panels/BrowserWebExtensionSupport.swift index 4e1ed9f51a4f..387e5b4b661e 100644 --- a/Sources/Panels/BrowserWebExtensionSupport.swift +++ b/Sources/Panels/BrowserWebExtensionSupport.swift @@ -294,6 +294,17 @@ final class BrowserWebExtensionSupport: NSObject, BrowserWebExtensionHosting { return webExtensionWindow(for: keyWindow) } + func focusedWebExtensionWindow( + for keyWindow: NSWindow?, + among openWindows: [any WKWebExtensionWindow] + ) -> (any WKWebExtensionWindow)? { + guard let focusedWindow = focusedWebExtensionWindow(for: keyWindow) else { return nil } + let focusedID = ObjectIdentifier(focusedWindow as AnyObject) + return openWindows.first { + ObjectIdentifier($0 as AnyObject) == focusedID + } + } + private func rememberActivePanel(_ panelID: UUID) { guard let window = tabAdapters[panelID]?.panel?.webView.window else { return } activePanelIDsByWindow[ObjectIdentifier(window)] = panelID diff --git a/cmuxTests/BrowserWebExtensionSupportTests.swift b/cmuxTests/BrowserWebExtensionSupportTests.swift index 8592bbd42100..6bf6e8b689e2 100644 --- a/cmuxTests/BrowserWebExtensionSupportTests.swift +++ b/cmuxTests/BrowserWebExtensionSupportTests.swift @@ -65,6 +65,12 @@ struct BrowserWebExtensionSupportTests { #expect((support.focusedWebExtensionWindow(for: firstWindow) as AnyObject?) === support.windowAdapter) #expect(support.focusedWebExtensionWindow(for: unrelatedWindow) == nil) #expect(support.focusedWebExtensionWindow(for: nil) == nil) + let allowedWindows: [any WKWebExtensionWindow] = [support.windowAdapter] + #expect( + (support.focusedWebExtensionWindow(for: firstWindow, among: allowedWindows) as AnyObject?) + === support.windowAdapter + ) + #expect(support.focusedWebExtensionWindow(for: firstWindow, among: []) == nil) } @Test From f2e19f1eb8a01e54829ea495079d9a22198eb131 Mon Sep 17 00:00:00 2001 From: 0xCUB3 Date: Fri, 10 Jul 2026 07:51:46 -0400 Subject: [PATCH 51/51] Fix browser extension review regressions --- .../Values/BrowserWebExtensionEntry.swift | 10 +- .../BrowserWebExtensionEntryTests.swift | 53 +++++++ .../Bindings/JSONValueModel.swift | 5 + .../Sections/BrowserWebExtensionsCard.swift | 11 +- .../BrowserWebExtensionsCardState.swift | 42 ++++- .../BrowserWebExtensionsCardStateTests.swift | 39 +++-- ...e+BrowserWebExtensionShortcutRouting.swift | 6 +- Sources/Panels/BrowserPanel.swift | 10 +- .../BrowserWebExtensionSupport+Loading.swift | 43 ++++-- .../BrowserWebExtensionTabAdapter.swift | 20 ++- .../BrowserWebExtensionToolbarButtons.swift | 5 +- .../BrowserWebExtensionWindowAdapter.swift | 2 +- ...serWebExtensionReviewRegressionTests.swift | 144 ++++++++++++++++++ .../BrowserWebExtensionSupportTests.swift | 8 +- 14 files changed, 341 insertions(+), 57 deletions(-) create mode 100644 Packages/macOS/CmuxSettings/Tests/CmuxSettingsTests/BrowserWebExtensionEntryTests.swift diff --git a/Packages/macOS/CmuxSettings/Sources/CmuxSettings/Values/BrowserWebExtensionEntry.swift b/Packages/macOS/CmuxSettings/Sources/CmuxSettings/Values/BrowserWebExtensionEntry.swift index f1580d1205a1..a532beb1a4b7 100644 --- a/Packages/macOS/CmuxSettings/Sources/CmuxSettings/Values/BrowserWebExtensionEntry.swift +++ b/Packages/macOS/CmuxSettings/Sources/CmuxSettings/Values/BrowserWebExtensionEntry.swift @@ -65,7 +65,10 @@ public struct BrowserWebExtensionEntry: Codable, Sendable, Equatable, Hashable, /// - Parameter path: The path to normalize. /// - Returns: The standardized file URL path. public static func standardizedPath(_ path: String) -> String { - URL(fileURLWithPath: path).standardizedFileURL.path + URL(fileURLWithPath: path) + .resolvingSymlinksInPath() + .standardizedFileURL + .path } /// Returns the effective resource root for a configured extension path. @@ -92,10 +95,13 @@ public struct BrowserWebExtensionEntry: Codable, Sendable, Equatable, Hashable, /// - Returns: `Contents/Resources` inside the bundle when `path` points at /// an `.appex`, otherwise the standardized original path. public static func standardizedSafariAppExtensionResourceRootPath(_ path: String) -> String { - let url = URL(fileURLWithPath: path).standardizedFileURL + let url = URL(fileURLWithPath: path) + .resolvingSymlinksInPath() + .standardizedFileURL guard url.pathExtension == "appex" else { return url.path } return url .appendingPathComponent("Contents/Resources", isDirectory: true) + .resolvingSymlinksInPath() .standardizedFileURL .path } diff --git a/Packages/macOS/CmuxSettings/Tests/CmuxSettingsTests/BrowserWebExtensionEntryTests.swift b/Packages/macOS/CmuxSettings/Tests/CmuxSettingsTests/BrowserWebExtensionEntryTests.swift new file mode 100644 index 000000000000..31f64ef7980f --- /dev/null +++ b/Packages/macOS/CmuxSettings/Tests/CmuxSettingsTests/BrowserWebExtensionEntryTests.swift @@ -0,0 +1,53 @@ +import Foundation +import Testing +@testable import CmuxSettings + +@Suite("Browser web extension resource identity") +struct BrowserWebExtensionEntryTests { + @Test + func unpackedDirectorySymlinkAliasSharesResourceIdentity() throws { + let root = FileManager.default.temporaryDirectory + .appendingPathComponent("cmux-web-extension-\(UUID().uuidString)", isDirectory: true) + let realDirectory = root.appendingPathComponent("real", isDirectory: true) + let aliasDirectory = root.appendingPathComponent("alias", isDirectory: true) + try FileManager.default.createDirectory(at: realDirectory, withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink(at: aliasDirectory, withDestinationURL: realDirectory) + defer { try? FileManager.default.removeItem(at: root) } + + let realIdentity = BrowserWebExtensionEntry.standardizedResourceRootPath( + for: .unpackedDirectory, + path: realDirectory.path + ) + let aliasIdentity = BrowserWebExtensionEntry.standardizedResourceRootPath( + for: .unpackedDirectory, + path: aliasDirectory.path + ) + + #expect(realIdentity == realDirectory.standardizedFileURL.path) + #expect(aliasIdentity == realIdentity) + } + + @Test + func safariAppExtensionSymlinkAliasSharesResourcesIdentity() throws { + let root = FileManager.default.temporaryDirectory + .appendingPathComponent("cmux-safari-extension-\(UUID().uuidString)", isDirectory: true) + let realAppExtension = root.appendingPathComponent("Real.appex", isDirectory: true) + let resources = realAppExtension.appendingPathComponent("Contents/Resources", isDirectory: true) + let aliasAppExtension = root.appendingPathComponent("Alias.appex", isDirectory: true) + try FileManager.default.createDirectory(at: resources, withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink(at: aliasAppExtension, withDestinationURL: realAppExtension) + defer { try? FileManager.default.removeItem(at: root) } + + let realIdentity = BrowserWebExtensionEntry.standardizedResourceRootPath( + for: .safariAppExtension, + path: realAppExtension.path + ) + let aliasIdentity = BrowserWebExtensionEntry.standardizedResourceRootPath( + for: .safariAppExtension, + path: aliasAppExtension.path + ) + + #expect(realIdentity == resources.standardizedFileURL.path) + #expect(aliasIdentity == realIdentity) + } +} diff --git a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Bindings/JSONValueModel.swift b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Bindings/JSONValueModel.swift index 59de16cd7e23..baa7027af719 100644 --- a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Bindings/JSONValueModel.swift +++ b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Bindings/JSONValueModel.swift @@ -23,6 +23,10 @@ public final class JSONValueModel { /// watcher. public private(set) var current: Value + /// Monotonic identity for each value delivered by the change stream. + /// Consumers can use this to reject observations captured before a write. + public private(set) var observationRevision: UInt64 = 0 + /// Whether the JSON change stream has yielded at least once. public private(set) var hasObservedValue = false @@ -96,6 +100,7 @@ public final class JSONValueModel { public func startObserving() { observation.activate(makeStream) { [weak self] value in guard let self else { return } + self.observationRevision &+= 1 self.current = value self.hasObservedValue = true } diff --git a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift index b0d093516ad2..a4bd9ec3dbe3 100644 --- a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift +++ b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift @@ -49,7 +49,10 @@ struct BrowserWebExtensionsCard: View { } } .onChange(of: model.current) { _, current in - cardState.reconcileObservedEntries(current) + cardState.reconcileObservedEntries( + current, + observationRevision: model.observationRevision + ) } .onChange(of: model.writeResultRevision) { _, _ in cardState.reconcileWriteResult( @@ -249,7 +252,11 @@ struct BrowserWebExtensionsCard: View { } private func commitEntries(_ entries: [BrowserWebExtensionEntry]) { - cardState.beginWrite(entries: entries, writeID: model.set(entries)) + cardState.beginWrite( + entries: entries, + writeID: model.set(entries), + observationRevision: model.observationRevision + ) } private func importSafariExtension(_ candidate: SettingsDiscoveredBrowserExtension) { diff --git a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCardState.swift b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCardState.swift index 16acc08b4e71..d1357a8e9eda 100644 --- a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCardState.swift +++ b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCardState.swift @@ -7,6 +7,9 @@ struct BrowserWebExtensionsCardState { private(set) var pendingEntries: [BrowserWebExtensionEntry]? private(set) var pendingWriteID: UInt64? private(set) var hasWriteError = false + private var pendingStartObservationRevision: UInt64 = 0 + private var matchingObservationRevision: UInt64? + private var completedWriteSucceeded = false func effectiveEntries(observed: [BrowserWebExtensionEntry]) -> [BrowserWebExtensionEntry] { pendingEntries ?? observed @@ -29,23 +32,48 @@ struct BrowserWebExtensionsCardState { isDiscoveryComplete = true } - mutating func beginWrite(entries: [BrowserWebExtensionEntry], writeID: UInt64) { + mutating func beginWrite( + entries: [BrowserWebExtensionEntry], + writeID: UInt64, + observationRevision: UInt64 = 0 + ) { pendingEntries = entries pendingWriteID = writeID + pendingStartObservationRevision = observationRevision + matchingObservationRevision = nil + completedWriteSucceeded = false hasWriteError = false } - mutating func reconcileObservedEntries(_ entries: [BrowserWebExtensionEntry]) { - guard entries == pendingEntries else { return } - pendingEntries = nil - pendingWriteID = nil - hasWriteError = false + mutating func reconcileObservedEntries( + _ entries: [BrowserWebExtensionEntry], + observationRevision: UInt64 = .max + ) { + guard entries == pendingEntries, + observationRevision > pendingStartObservationRevision + else { return } + matchingObservationRevision = observationRevision + finishIfWriteSucceeded() } mutating func reconcileWriteResult(completedWriteID: UInt64, failed: Bool) { guard completedWriteID == pendingWriteID else { return } + completedWriteSucceeded = !failed + if failed { + pendingEntries = nil + pendingWriteID = nil + matchingObservationRevision = nil + hasWriteError = true + } else { + finishIfWriteSucceeded() + } + } + + private mutating func finishIfWriteSucceeded() { + guard completedWriteSucceeded, matchingObservationRevision != nil else { return } pendingEntries = nil pendingWriteID = nil - hasWriteError = failed + matchingObservationRevision = nil + hasWriteError = false } } diff --git a/Packages/macOS/CmuxSettingsUI/Tests/CmuxSettingsUITests/BrowserWebExtensionsCardStateTests.swift b/Packages/macOS/CmuxSettingsUI/Tests/CmuxSettingsUITests/BrowserWebExtensionsCardStateTests.swift index 4eae55dc04d9..5ac308a78120 100644 --- a/Packages/macOS/CmuxSettingsUI/Tests/CmuxSettingsUITests/BrowserWebExtensionsCardStateTests.swift +++ b/Packages/macOS/CmuxSettingsUI/Tests/CmuxSettingsUITests/BrowserWebExtensionsCardStateTests.swift @@ -52,42 +52,57 @@ struct BrowserWebExtensionsCardStateTests { #expect(!state.hasWriteError) } + @Test - func observedPendingValueCompletesOptimisticWrite() { + func successfulWriteWaitsForMatchingObservation() { let observed = [entry(id: "existing")] let pending = observed + [entry(id: "new")] var state = BrowserWebExtensionsCardState() - state.beginWrite(entries: pending, writeID: 1) + state.beginWrite(entries: pending, writeID: 1, observationRevision: 4) - state.reconcileObservedEntries(observed) + state.reconcileWriteResult(completedWriteID: 1, failed: false) + #expect(state.pendingWriteID == 1) #expect(state.effectiveEntries(observed: observed) == pending) - state.reconcileObservedEntries(pending) - #expect(state.effectiveEntries(observed: pending) == pending) + state.reconcileObservedEntries(pending, observationRevision: 5) #expect(state.pendingWriteID == nil) + #expect(state.effectiveEntries(observed: pending) == pending) } @Test - func successfulWriteClearsPendingWithoutObservedSignal() { + func observationBeforeCompletionKeepsOptimisticValueUntilSuccess() { let observed = [entry(id: "existing")] let pending = observed + [entry(id: "new")] var state = BrowserWebExtensionsCardState() - state.beginWrite(entries: pending, writeID: 1) + state.beginWrite(entries: pending, writeID: 1, observationRevision: 1) + state.reconcileObservedEntries(pending, observationRevision: 2) + #expect(state.pendingWriteID == 1) state.reconcileWriteResult(completedWriteID: 1, failed: false) #expect(state.pendingWriteID == nil) + } - let externallyUpdated = [entry(id: "external")] - #expect(state.effectiveEntries(observed: externallyUpdated) == externallyUpdated) + @Test + func staleEqualObservationCannotAcknowledgeNewestWrite() { + let original = [entry(id: "original")] + let newest = [entry(id: "newest")] + var state = BrowserWebExtensionsCardState() + state.beginWrite(entries: newest, writeID: 2, observationRevision: 10) + + state.reconcileObservedEntries(newest, observationRevision: 9) + state.reconcileWriteResult(completedWriteID: 2, failed: true) + #expect(state.pendingWriteID == nil) + #expect(state.effectiveEntries(observed: original) == original) + #expect(state.hasWriteError) } @Test - func staleSuccessfulWriteDoesNotClearNewerPendingWrite() { + func successfulWriteDoesNotClearNewerPendingWrite() { let first = [entry(id: "first")] let second = [entry(id: "second")] var state = BrowserWebExtensionsCardState() - state.beginWrite(entries: first, writeID: 1) - state.beginWrite(entries: second, writeID: 2) + state.beginWrite(entries: first, writeID: 1, observationRevision: 1) + state.beginWrite(entries: second, writeID: 2, observationRevision: 2) state.reconcileWriteResult(completedWriteID: 1, failed: false) #expect(state.pendingWriteID == 2) diff --git a/Sources/AppDelegate+BrowserWebExtensionShortcutRouting.swift b/Sources/AppDelegate+BrowserWebExtensionShortcutRouting.swift index f80e125641be..6d09f252d2e6 100644 --- a/Sources/AppDelegate+BrowserWebExtensionShortcutRouting.swift +++ b/Sources/AppDelegate+BrowserWebExtensionShortcutRouting.swift @@ -61,7 +61,11 @@ extension AppDelegate { /// Extension manifest commands run only after configured cmux shortcuts decline the event. func shouldOfferBrowserWebExtensionCommand(_ event: NSEvent) -> Bool { - shouldOfferBrowserWebExtensionCommand( + let flags = event.modifierFlags.intersection(.deviceIndependentFlagsMask) + guard !flags.intersection([.command, .control, .option]).isEmpty else { + return false + } + return shouldOfferBrowserWebExtensionCommand( event, browserFocusModeActive: browserFocusModePanelForShortcutEvent(event) != nil ) diff --git a/Sources/Panels/BrowserPanel.swift b/Sources/Panels/BrowserPanel.swift index d18ebc0920e6..8bb67a8f514a 100644 --- a/Sources/Panels/BrowserPanel.swift +++ b/Sources/Panels/BrowserPanel.swift @@ -5758,10 +5758,12 @@ final class BrowserPanel: Panel, ObservableObject { let contextIdentifier = browserWebExtensionHost? .webViewConfiguration(forNavigatingTo: url)? .contextIdentifier - replaceWebViewForWebExtensionNavigation( - webViewConfiguration: webViewConfiguration, - contextIdentifier: contextIdentifier - ) + if contextIdentifier != webExtensionPageContextIdentifier { + replaceWebViewForWebExtensionNavigation( + webViewConfiguration: webViewConfiguration, + contextIdentifier: contextIdentifier + ) + } } navigate(to: url) } diff --git a/Sources/Panels/BrowserWebExtensionSupport+Loading.swift b/Sources/Panels/BrowserWebExtensionSupport+Loading.swift index df3474926c37..0d5693e1ee78 100644 --- a/Sources/Panels/BrowserWebExtensionSupport+Loading.swift +++ b/Sources/Panels/BrowserWebExtensionSupport+Loading.swift @@ -153,9 +153,9 @@ extension BrowserWebExtensionSupport { do { try controller.unload(record.context) } catch { - recordLoadError(error.localizedDescription, entryID: entryID) + recordLoadError(entryID: entryID) #if DEBUG - cmuxDebugLog("browser.webext.unloadFailed id=\(entryID) error=\(error.localizedDescription)") + cmuxDebugLog(BrowserWebExtensionDiagnostics.failure(operation: .unload, error: error)) #endif return record.entry } @@ -178,7 +178,7 @@ extension BrowserWebExtensionSupport { popout.closeFromExtensionOrUser() } #if DEBUG - cmuxDebugLog("browser.webext.unloaded id=\(entryID)") + cmuxDebugLog(BrowserWebExtensionDiagnostics.success(operation: .unload)) #endif return nil } @@ -227,16 +227,13 @@ extension BrowserWebExtensionSupport { loadErrorsByEntryID.removeValue(forKey: entry.id) refreshLoadErrors() #if DEBUG - cmuxDebugLog( - "browser.webext.loaded name=\(webExtension.displayName ?? "?") " + - "version=\(webExtension.displayVersion ?? "?") url=\(entry.path)" - ) + cmuxDebugLog(BrowserWebExtensionDiagnostics.success(operation: .load)) #endif } catch { guard canApplyWebExtensionLoad(generation: generation) else { return } - recordLoadError(error.localizedDescription, entryID: entry.id) + recordLoadError(entryID: entry.id) #if DEBUG - cmuxDebugLog("browser.webext.loadFailed url=\(entry.path) error=\(error.localizedDescription)") + cmuxDebugLog(BrowserWebExtensionDiagnostics.failure(operation: .load, error: error)) #endif } } @@ -256,14 +253,15 @@ extension BrowserWebExtensionSupport { try await settingsStore.set(restoredEntries, for: settingsKey) } catch { for entry in failedEntries { - recordLoadError(error.localizedDescription, entryID: entry.id) + recordLoadError(entryID: entry.id) } #if DEBUG - cmuxDebugLog("browser.webext.rollbackSettingsFailed error=\(error.localizedDescription)") + cmuxDebugLog(BrowserWebExtensionDiagnostics.failure(operation: .rollbackSettings, error: error)) #endif } } + private func makeWebExtension(for entry: BrowserWebExtensionEntry) async throws -> WKWebExtension { let url = URL(fileURLWithPath: entry.path) if entry.kind == .safariAppExtension, url.pathExtension == "appex" { @@ -322,8 +320,8 @@ extension BrowserWebExtensionSupport { return "cmux-\(String(decoding: hexBytes, as: UTF8.self))" } - private func recordLoadError(_ message: String, entryID: String) { - loadErrorsByEntryID[entryID] = "\(entryID): \(message)" + func recordLoadError(entryID: String) { + loadErrorsByEntryID[entryID] = BrowserWebExtensionDiagnostics.genericFailureMessage refreshLoadErrors() } @@ -336,3 +334,22 @@ extension BrowserWebExtensionSupport { } } } + +enum BrowserWebExtensionDiagnostics { + static let genericFailureMessage = "Web extension failed" + enum Operation: String { + case load + case unload + case action + case rollbackSettings + } + + static func success(operation: Operation) -> String { + "browser.webext operation=\(operation.rawValue) result=success" + } + + static func failure(operation: Operation, error: Error) -> String { + "browser.webext operation=\(operation.rawValue) result=failure " + + "errorType=\(String(describing: type(of: error)))" + } +} diff --git a/Sources/Panels/BrowserWebExtensionTabAdapter.swift b/Sources/Panels/BrowserWebExtensionTabAdapter.swift index 24959c0e4b33..747c3fd2a811 100644 --- a/Sources/Panels/BrowserWebExtensionTabAdapter.swift +++ b/Sources/Panels/BrowserWebExtensionTabAdapter.swift @@ -87,21 +87,33 @@ final class BrowserWebExtensionTabAdapter: NSObject, WKWebExtensionTab { } func reload(fromOrigin: Bool, for context: WKWebExtensionContext, completionHandler: @escaping (Error?) -> Void) { + guard let webView = panel?.webView else { + completionHandler(webExtensionTabError(code: 3)) + return + } if fromOrigin { - panel?.webView.reloadFromOrigin() + webView.reloadFromOrigin() } else { - panel?.webView.reload() + webView.reload() } completionHandler(nil) } func goBack(for context: WKWebExtensionContext, completionHandler: @escaping (Error?) -> Void) { - panel?.webView.goBack() + guard let webView = panel?.webView else { + completionHandler(webExtensionTabError(code: 3)) + return + } + webView.goBack() completionHandler(nil) } func goForward(for context: WKWebExtensionContext, completionHandler: @escaping (Error?) -> Void) { - panel?.webView.goForward() + guard let webView = panel?.webView else { + completionHandler(webExtensionTabError(code: 3)) + return + } + webView.goForward() completionHandler(nil) } diff --git a/Sources/Panels/BrowserWebExtensionToolbarButtons.swift b/Sources/Panels/BrowserWebExtensionToolbarButtons.swift index b70992335d7c..134e17b3d76e 100644 --- a/Sources/Panels/BrowserWebExtensionToolbarButtons.swift +++ b/Sources/Panels/BrowserWebExtensionToolbarButtons.swift @@ -40,10 +40,7 @@ private struct BrowserWebExtensionActionButton: View { var body: some View { Button(action: { #if DEBUG - cmuxDebugLog( - "browser.webext.action panel=\(panel.id.uuidString.prefix(5)) " + - "name=\(snapshot.displayName)" - ) + cmuxDebugLog(BrowserWebExtensionDiagnostics.success(operation: .action)) #endif performAction(anchorViewHolder.view) }) { diff --git a/Sources/Panels/BrowserWebExtensionWindowAdapter.swift b/Sources/Panels/BrowserWebExtensionWindowAdapter.swift index 1f1a12a1c3ad..7ddaa1fa8d90 100644 --- a/Sources/Panels/BrowserWebExtensionWindowAdapter.swift +++ b/Sources/Panels/BrowserWebExtensionWindowAdapter.swift @@ -62,6 +62,6 @@ final class BrowserWebExtensionWindowAdapter: NSObject, WKWebExtensionWindow { } private var hostWindow: NSWindow? { - support?.activeTabAdapter?.panel?.webView.window ?? NSApp.keyWindow + support?.activeTabAdapter?.panel?.webView.window } } diff --git a/cmuxTests/BrowserWebExtensionReviewRegressionTests.swift b/cmuxTests/BrowserWebExtensionReviewRegressionTests.swift index ff9360b1708c..e6fd30e2333a 100644 --- a/cmuxTests/BrowserWebExtensionReviewRegressionTests.swift +++ b/cmuxTests/BrowserWebExtensionReviewRegressionTests.swift @@ -90,6 +90,44 @@ struct BrowserWebExtensionReviewRegressionTests { #expect(!appDelegate.shouldOfferBrowserWebExtensionCommand(plainTypingEvent)) } + @MainActor + @Test + func extensionShortcutPreflightSkipsPlainTypingContextResolutionAndKeepsControlOptionEligible() throws { + let appDelegate = try #require(AppDelegate.shared) + + let plainTypingEvent = try #require(NSEvent.keyEvent( + with: .keyDown, + location: .zero, + modifierFlags: [], + timestamp: ProcessInfo.processInfo.systemUptime, + windowNumber: 0, + context: nil, + characters: "a", + charactersIgnoringModifiers: "a", + isARepeat: false, + keyCode: 0 + )) + appDelegate.shortcutEventFocusContextCache = nil + #expect(!appDelegate.shouldOfferBrowserWebExtensionCommand(plainTypingEvent)) + #expect(appDelegate.shortcutEventFocusContextCache == nil) + + for modifierFlags in [NSEvent.ModifierFlags.control, .option] { + let event = try #require(NSEvent.keyEvent( + with: .keyDown, + location: .zero, + modifierFlags: modifierFlags, + timestamp: ProcessInfo.processInfo.systemUptime, + windowNumber: 0, + context: nil, + characters: "z", + charactersIgnoringModifiers: "z", + isARepeat: false, + keyCode: 6 + )) + #expect(appDelegate.shouldOfferBrowserWebExtensionCommand(event, browserFocusModeActive: true)) + } + } + @MainActor @Test func browserFocusModeOffersExtensionCommandDespiteConfiguredShortcut() throws { @@ -224,6 +262,112 @@ struct BrowserWebExtensionReviewRegressionTests { support.extensionPagePanels(usingContextIdentifier: ObjectIdentifier(NSObject())).isEmpty ) } + + @MainActor + @Test + @available(macOS 15.4, *) + func extensionDiagnosticsExcludeControlledValuesAndRawErrors() { + let extensionPath = "/tmp/extension-controlled-path" + let extensionID = "extension-controlled-id" + let manifestName = "Extension Controlled Name" + let rawError = "raw upstream error with secret" + let error = SentinelWebExtensionError(message: rawError) + + let loadLog = BrowserWebExtensionDiagnostics.success(operation: .load) + let actionLog = BrowserWebExtensionDiagnostics.success(operation: .action) + let failureLog = BrowserWebExtensionDiagnostics.failure(operation: .load, error: error) + + #expect(!loadLog.contains(extensionPath)) + #expect(!loadLog.contains(extensionID)) + #expect(!loadLog.contains(manifestName)) + #expect(!failureLog.contains(rawError)) + #expect(!actionLog.contains(manifestName)) + + let support = BrowserWebExtensionSupport() + support.recordLoadError(entryID: extensionID) + #expect(support.loadErrors == [BrowserWebExtensionDiagnostics.genericFailureMessage]) + } + + @MainActor + @Test + @available(macOS 15.4, *) + func sameContextExtensionNavigationPreservesWebViewIdentity() throws { + let extensionURL = try #require(URL(string: "webkit-extension://cmux-test/options.html")) + let siblingURL = try #require(URL(string: "webkit-extension://cmux-test/vault.html")) + let host = BrowserWebExtensionReviewTestHost(extensionHost: extensionURL.host) + let panel = BrowserPanel( + workspaceId: UUID(), + initialURL: extensionURL, + renderInitialNavigation: true, + browserWebExtensionHost: host + ) + defer { panel.close() } + let originalWebView = panel.webView + let originalInstanceID = panel.webViewInstanceID + + panel.navigateFromWebExtension( + to: siblingURL, + webViewConfiguration: WKWebViewConfiguration() + ) + + #expect(panel.webView === originalWebView) + #expect(panel.webViewInstanceID == originalInstanceID) + } + + @MainActor + @Test + @available(macOS 15.4, *) + func staleExtensionTabNavigationCommandsReturnUnavailableTabError() throws { + let support = BrowserWebExtensionSupport() + let adapter: BrowserWebExtensionTabAdapter + do { + let panel = BrowserPanel(workspaceId: UUID(), browserWebExtensionHost: support) + adapter = BrowserWebExtensionTabAdapter(panel: panel, support: support) + } + let context = unsafeBitCast(NSObject(), to: WKWebExtensionContext.self) + + var errors: [NSError?] = [] + adapter.reload(fromOrigin: false, for: context) { errors.append($0 as NSError?) } + adapter.reload(fromOrigin: true, for: context) { errors.append($0 as NSError?) } + adapter.goBack(for: context) { errors.append($0 as NSError?) } + adapter.goForward(for: context) { errors.append($0 as NSError?) } + + #expect(errors.count == 4) + #expect(errors.allSatisfy { $0?.domain == "cmux.webExtension.tab" && $0?.code == 3 }) + } + + @MainActor + @Test + @available(macOS 15.4, *) + func extensionWindowAdapterDoesNotUseUnrelatedKeyWindow() { + let support = BrowserWebExtensionSupport() + let panel = BrowserPanel(workspaceId: UUID(), browserWebExtensionHost: support) + support.register(panel: panel) + support.noteActivated(panelID: panel.id) + let unrelatedWindow = NSWindow( + contentRect: NSRect(x: 40, y: 40, width: 300, height: 200), + styleMask: [.titled], + backing: .buffered, + defer: false + ) + defer { + support.unregister(panelID: panel.id) + panel.close() + unrelatedWindow.close() + } + unrelatedWindow.makeKeyAndOrderFront(nil) + let context = unsafeBitCast(NSObject(), to: WKWebExtensionContext.self) + + #expect(support.windowAdapter.frame(for: context) == .null) + var focusError: Error? + support.windowAdapter.focus(for: context) { focusError = $0 } + #expect((focusError as NSError?)?.code == 3) + #expect(NSApp.keyWindow === unrelatedWindow) + } +} + +private struct SentinelWebExtensionError: Error { + let message: String } @MainActor diff --git a/cmuxTests/BrowserWebExtensionSupportTests.swift b/cmuxTests/BrowserWebExtensionSupportTests.swift index 6bf6e8b689e2..280697c35637 100644 --- a/cmuxTests/BrowserWebExtensionSupportTests.swift +++ b/cmuxTests/BrowserWebExtensionSupportTests.swift @@ -63,13 +63,7 @@ struct BrowserWebExtensionSupportTests { let unrelatedWindow = NSWindow() #expect(support.webExtensionWindow(for: unrelatedWindow) == nil) #expect((support.focusedWebExtensionWindow(for: firstWindow) as AnyObject?) === support.windowAdapter) - #expect(support.focusedWebExtensionWindow(for: unrelatedWindow) == nil) - #expect(support.focusedWebExtensionWindow(for: nil) == nil) - let allowedWindows: [any WKWebExtensionWindow] = [support.windowAdapter] - #expect( - (support.focusedWebExtensionWindow(for: firstWindow, among: allowedWindows) as AnyObject?) - === support.windowAdapter - ) + #expect((support.focusedWebExtensionWindow(for: firstWindow, among: [support.windowAdapter]) as AnyObject?) === support.windowAdapter) #expect(support.focusedWebExtensionWindow(for: firstWindow, among: []) == nil) }