diff --git a/.github/swift-file-length-budget.tsv b/.github/swift-file-length-budget.tsv index 68977f89ba36..9bfe42cf8fb6 100644 --- a/.github/swift-file-length-budget.tsv +++ b/.github/swift-file-length-budget.tsv @@ -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 @@ -205,7 +205,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/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..a532beb1a4b7 --- /dev/null +++ b/Packages/macOS/CmuxSettings/Sources/CmuxSettings/Values/BrowserWebExtensionEntry.swift @@ -0,0 +1,136 @@ +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 + /// 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. + /// - 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 + } + + /// 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) + .resolvingSymlinksInPath() + .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) + .resolvingSymlinksInPath() + .standardizedFileURL + guard url.pathExtension == "appex" else { return url.path } + return url + .appendingPathComponent("Contents/Resources", isDirectory: true) + .resolvingSymlinksInPath() + .standardizedFileURL + .path + } +} + +// 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/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 de3704f836f7..baa7027af719 100644 --- a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Bindings/JSONValueModel.swift +++ b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Bindings/JSONValueModel.swift @@ -23,13 +23,25 @@ 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 + /// 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. @@ -87,7 +99,10 @@ 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.observationRevision &+= 1 + self.current = value + self.hasObservedValue = true } } @@ -96,35 +111,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 { self?.lastWriteError = nil } + await MainActor.run { + guard let self else { return } + self.finishWrite(requestID: requestID, error: nil) + } } catch { await MainActor.run { - self?.lastWriteError = error - self?.errorLog.record(error, keyID: keyID) + guard let self else { return } + 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 { self?.lastWriteError = nil } + await MainActor.run { + guard let self else { return } + self.finishWrite(requestID: requestID, error: nil) + } } catch { await MainActor.run { - self?.lastWriteError = error - self?.errorLog.record(error, keyID: keyID) + guard let self else { return } + 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/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..8edf850bf71e 100644 --- a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Environment/SettingsHostActions.swift +++ b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Environment/SettingsHostActions.swift @@ -171,6 +171,17 @@ 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 + + /// A live map of configured extension IDs to host-side load failures. + func browserWebExtensionLoadErrorUpdates() -> AsyncStream<[String: String]> } public extension SettingsHostActions { @@ -183,6 +194,19 @@ 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 } + + /// 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/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..3ad92b7d605f 100644 --- a/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserSection.swift +++ b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserSection.swift @@ -39,15 +39,24 @@ public struct BrowserSection: View { @State private var httpAllowlistSyncedValue: String = "" @State private var httpAllowlistLoaded: Bool = false + @State private var webExtensions: JSONValueModel<[BrowserWebExtensionEntry]> + 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 +82,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 +98,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..a4bd9ec3dbe3 --- /dev/null +++ b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCard.swift @@ -0,0 +1,360 @@ +import AppKit +import CmuxSettings +import SwiftUI +import UniformTypeIdentifiers + +/// **Extensions** card in the Browser section. +/// +/// 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]> + let hostActions: SettingsHostActions + + @State private var cardState = BrowserWebExtensionsCardState() + @State private var loadErrorsByEntryID: [String: String] = [:] + + var body: some View { + let entries = cardState.effectiveEntries(observed: model.current) + let enabledByID = effectiveEnabledByID(for: entries) + SettingsCard { + headerRow + if supported { + ForEach(entries) { entry in + SettingsCardDivider() + entryRow(entry, isEnabled: enabledByID[entry.id] ?? entry.enabled) + } + if cardState.shouldShowEmptyState( + entries: entries, + hasObservedValue: model.hasObservedValue + ) { + SettingsCardDivider() + emptyRow + } + } + } + .task { + model.startObserving() + let discovered = await hostActions.discoverBrowserWebExtensions() + guard !Task.isCancelled else { return } + cardState.completeDiscovery(discovered) + } + .task { + for await loadErrors in hostActions.browserWebExtensionLoadErrorUpdates() { + loadErrorsByEntryID = loadErrors + } + } + .onChange(of: model.current) { _, current in + cardState.reconcileObservedEntries( + current, + observationRevision: model.observationRevision + ) + } + .onChange(of: model.writeResultRevision) { _, _ in + cardState.reconcileWriteResult( + completedWriteID: model.lastCompletedWriteID, + failed: model.lastWriteError != nil + ) + } + } + + private var supported: Bool { + hostActions.browserWebExtensionsSupported() + } + + private var effectiveEntries: [BrowserWebExtensionEntry] { + cardState.effectiveEntries(observed: model.current) + } + + /// Discovered Safari extensions not yet added, offered by the Import menu. + private var importableExtensions: [SettingsDiscoveredBrowserExtension] { + 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 cardState.discovered.filter { candidate in + !addedIDs.contains(candidate.id) + && !addedResourcePaths.contains(standardizedSafariAppExtensionResourcePath(candidate.path)) + } + } + + private var headerRow: some View { + return SettingsCardRow( + configurationReview: .json("browser.webExtensions"), + searchAnchorID: "setting:browser:web-extensions", + String(localized: "settings.browser.webExtensions", defaultValue: "Extensions"), + subtitle: headerSubtitle + ) { + HStack(spacing: 8) { + importMenu + Button(String( + localized: "settings.browser.webExtensions.addUnpacked", + defaultValue: "Add Unpacked…" + )) { + addUnpackedExtension() + } + .controlSize(.small) + .disabled(!supported || !model.hasObservedValue) + .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) + .fixedSize() + .disabled(!cardState.canUseImportMenu( + supported: supported, + hasObservedValue: model.hasObservedValue + )) + .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, + String( + localized: "settings.browser.webExtensions.noneAdded", + defaultValue: "No extensions added" + ), + subtitle: String( + 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 entryRow(_ entry: BrowserWebExtensionEntry, isEnabled: Bool) -> some View { + 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: subtitle + ) { + HStack(spacing: 8) { + Toggle("", isOn: Binding( + get: { isEnabled }, + set: { setEnabled($0, id: entry.id) } + )) + .labelsHidden() + .controlSize(.small) + .accessibilityIdentifier("BrowserWebExtensionToggle-\(entry.id)") + Button(String( + localized: "settings.browser.webExtensions.remove", + defaultValue: "Remove" + )) { + remove(id: entry.id) + } + .controlSize(.small) + } + } + } + + private func setEnabled(_ enabled: Bool, id: String) { + 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 + } + } + + private func add(_ entry: BrowserWebExtensionEntry) { + guard model.hasObservedValue else { return } + var entries = effectiveEntries + guard !entries.contains(where: { $0.id == entry.id }) else { + presentDuplicateExtensionAlert(for: entry) + return + } + let entryResourcePath = standardizedResourcePath(for: entry) + guard !entries.contains(where: { standardizedResourcePath(for: $0) == entryResourcePath }) else { + presentDuplicateExtensionAlert(for: entry) + return + } + entries.append(entry) + 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 } + var entries = effectiveEntries + guard update(&entries) else { return } + commitEntries(entries) + } + + private func commitEntries(_ entries: [BrowserWebExtensionEntry]) { + cardState.beginWrite( + entries: entries, + writeID: model.set(entries), + observationRevision: model.observationRevision + ) + } + + 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 + 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 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, + path: url.path, + enabled: true, + 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.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." + ), + url.lastPathComponent + ) + alert.addButton(withTitle: String(localized: "common.ok", defaultValue: "OK")) + 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.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() + } + + private func effectiveEnabledByID(for entries: [BrowserWebExtensionEntry]) -> [String: Bool] { + var seenEnabledPaths = Set() + var result: [String: Bool] = [:] + for entry in entries { + let path = standardizedResourcePath(for: entry) + let isFirstEnabledEntryForPath = entry.enabled && seenEnabledPaths.insert(path).inserted + result[entry.id] = isFirstEnabledEntryForPath + } + return result + } + + private func standardizedPath(_ path: String) -> String { + BrowserWebExtensionEntry.standardizedPath(path) + } + + private func standardizedResourcePath(for entry: BrowserWebExtensionEntry) -> String { + switch entry.kind { + case .safariAppExtension: + return BrowserWebExtensionEntry.standardizedSafariAppExtensionResourceRootPath(entry.path) + case .unpackedDirectory: + return standardizedPath(entry.path) + } + } + + private func standardizedSafariAppExtensionResourcePath(_ path: String) -> String { + BrowserWebExtensionEntry.standardizedSafariAppExtensionResourceRootPath(path) + } +} 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..d1357a8e9eda --- /dev/null +++ b/Packages/macOS/CmuxSettingsUI/Sources/CmuxSettingsUI/Sections/BrowserWebExtensionsCardState.swift @@ -0,0 +1,79 @@ +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 + private var pendingStartObservationRevision: UInt64 = 0 + private var matchingObservationRevision: UInt64? + private var completedWriteSucceeded = false + + func effectiveEntries(observed: [BrowserWebExtensionEntry]) -> [BrowserWebExtensionEntry] { + pendingEntries ?? observed + } + + func canUseImportMenu(supported: Bool, hasObservedValue: Bool) -> Bool { + 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 + } + + 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], + 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 + matchingObservationRevision = nil + hasWriteError = false + } +} diff --git a/Packages/macOS/CmuxSettingsUI/Tests/CmuxSettingsUITests/BrowserWebExtensionsCardStateTests.swift b/Packages/macOS/CmuxSettingsUI/Tests/CmuxSettingsUITests/BrowserWebExtensionsCardStateTests.swift new file mode 100644 index 000000000000..5ac308a78120 --- /dev/null +++ b/Packages/macOS/CmuxSettingsUI/Tests/CmuxSettingsUITests/BrowserWebExtensionsCardStateTests.swift @@ -0,0 +1,120 @@ +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 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")] + 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) + + let externallyUpdated = [entry(id: "external")] + state.reconcileObservedEntries(externallyUpdated) + #expect(state.hasWriteError) + + state.beginWrite(entries: pending, writeID: 3) + #expect(!state.hasWriteError) + } + + + @Test + func successfulWriteWaitsForMatchingObservation() { + let observed = [entry(id: "existing")] + let pending = observed + [entry(id: "new")] + var state = BrowserWebExtensionsCardState() + state.beginWrite(entries: pending, writeID: 1, observationRevision: 4) + + state.reconcileWriteResult(completedWriteID: 1, failed: false) + #expect(state.pendingWriteID == 1) + #expect(state.effectiveEntries(observed: observed) == pending) + + state.reconcileObservedEntries(pending, observationRevision: 5) + #expect(state.pendingWriteID == nil) + #expect(state.effectiveEntries(observed: pending) == pending) + } + + @Test + func observationBeforeCompletionKeepsOptimisticValueUntilSuccess() { + let observed = [entry(id: "existing")] + let pending = observed + [entry(id: "new")] + var state = BrowserWebExtensionsCardState() + 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) + } + + @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 successfulWriteDoesNotClearNewerPendingWrite() { + let first = [entry(id: "first")] + let second = [entry(id: "second")] + var state = BrowserWebExtensionsCardState() + 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) + #expect(state.effectiveEntries(observed: []) == second) + } + + private func entry(id: String) -> BrowserWebExtensionEntry { + BrowserWebExtensionEntry( + id: id, + kind: .unpackedDirectory, + path: "/Extensions/\(id)", + enabled: true + ) + } +} diff --git a/Packages/macOS/CmuxSettingsUI/Tests/CmuxSettingsUITests/JSONValueModelLifecycleTests.swift b/Packages/macOS/CmuxSettingsUI/Tests/CmuxSettingsUITests/JSONValueModelLifecycleTests.swift index 77f024e15633..972f1cb8a5b2 100644 --- a/Packages/macOS/CmuxSettingsUI/Tests/CmuxSettingsUITests/JSONValueModelLifecycleTests.swift +++ b/Packages/macOS/CmuxSettingsUI/Tests/CmuxSettingsUITests/JSONValueModelLifecycleTests.swift @@ -81,4 +81,59 @@ 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) + } + + @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/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/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index d82597428f6e..516fea290969 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -30613,6 +30613,131 @@ } } }, + "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": "延伸功能" + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "ផ្នែកបន្ថែម" + } + } + } + }, "canvas.commandScrollHint": { "extractionState": "manual", "localizations": { @@ -44813,359 +44938,3234 @@ } } }, - "settings.search.alias.setting.app.loading-spinner-position": { + "settings.browser.webExtension.permissionPrompt.allow": { "extractionState": "manual", "localizations": { "ar": { "stringUnit": { "state": "translated", - "value": "sidebar.loadingSpinnerPosition loading spinner position left right leading trailing side workspace تحميل مؤشر يسار يمين موضع" + "value": "سماح" } }, "bs": { "stringUnit": { "state": "translated", - "value": "sidebar.loadingSpinnerPosition loading spinner position left right leading trailing side workspace učitavanje indikator lijevo desno pozicija" + "value": "Dozvoli" } }, "da": { "stringUnit": { "state": "translated", - "value": "sidebar.loadingSpinnerPosition loading spinner position left right leading trailing side workspace indlæsning indikator venstre højre placering" + "value": "Tillad" } }, "de": { "stringUnit": { "state": "translated", - "value": "sidebar.loadingSpinnerPosition loading spinner position left right leading trailing side workspace laden Indikator links rechts Position" + "value": "Erlauben" } }, "en": { "stringUnit": { "state": "translated", - "value": "sidebar.loadingSpinnerPosition loading spinner position left right leading trailing side workspace" + "value": "Allow" } }, "es": { "stringUnit": { "state": "translated", - "value": "sidebar.loadingSpinnerPosition loading spinner position left right leading trailing side workspace carga indicador izquierda derecha posición" + "value": "Permitir" } }, "fr": { "stringUnit": { "state": "translated", - "value": "sidebar.loadingSpinnerPosition loading spinner position left right leading trailing side workspace chargement indicateur gauche droite position" + "value": "Autoriser" } }, "it": { "stringUnit": { "state": "translated", - "value": "sidebar.loadingSpinnerPosition loading spinner position left right leading trailing side workspace caricamento indicatore sinistra destra posizione" + "value": "Consenti" } }, "ja": { "stringUnit": { "state": "translated", - "value": "sidebar.loadingSpinnerPosition loading spinner position left right leading trailing side workspace 読み込み スピナー 位置 左 右 サイド" + "value": "許可" + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "អនុញ្ញាត" } }, "ko": { "stringUnit": { "state": "translated", - "value": "sidebar.loadingSpinnerPosition loading spinner position left right leading trailing side workspace 로딩 스피너 왼쪽 오른쪽 위치" + "value": "허용" } }, "nb": { "stringUnit": { "state": "translated", - "value": "sidebar.loadingSpinnerPosition loading spinner position left right leading trailing side workspace lasting indikator venstre høyre plassering" + "value": "Tillat" } }, "pl": { "stringUnit": { "state": "translated", - "value": "sidebar.loadingSpinnerPosition loading spinner position left right leading trailing side workspace ładowanie wskaźnik lewo prawo pozycja" + "value": "Zezwól" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "sidebar.loadingSpinnerPosition loading spinner position left right leading trailing side workspace carregamento indicador esquerda direita posição" + "value": "Permitir" } }, "ru": { "stringUnit": { "state": "translated", - "value": "sidebar.loadingSpinnerPosition loading spinner position left right leading trailing side workspace загрузка индикатор слева справа положение" + "value": "Разрешить" } }, "th": { "stringUnit": { "state": "translated", - "value": "sidebar.loadingSpinnerPosition loading spinner position left right leading trailing side workspace โหลด ตัวบ่งชี้ ซ้าย ขวา ตำแหน่ง" + "value": "อนุญาต" } }, "tr": { "stringUnit": { "state": "translated", - "value": "sidebar.loadingSpinnerPosition loading spinner position left right leading trailing side workspace yükleme gösterge sol sağ konum" + "value": "İzin Ver" } }, "uk": { "stringUnit": { "state": "translated", - "value": "sidebar.loadingSpinnerPosition loading spinner position left right leading trailing side workspace завантаження індикатор ліворуч праворуч розташування" + "value": "Дозволити" } }, "zh-Hans": { "stringUnit": { "state": "translated", - "value": "sidebar.loadingSpinnerPosition loading spinner position left right leading trailing side workspace 加载 指示器 左 右 位置" + "value": "允许" } }, "zh-Hant": { "stringUnit": { "state": "translated", - "value": "sidebar.loadingSpinnerPosition loading spinner position left right leading trailing side workspace 載入 指示器 左 右 位置" + "value": "允許" } } } }, - "settings.search.alias.setting.app.notification-badge-position": { + "settings.browser.webExtension.permissionPrompt.deny": { "extractionState": "manual", "localizations": { "ar": { "stringUnit": { "state": "translated", - "value": "sidebar.notificationBadgePosition notification unread badge position left right leading trailing side workspace تحميل مؤشر يسار يمين موضع" + "value": "رفض" } }, "bs": { "stringUnit": { "state": "translated", - "value": "sidebar.notificationBadgePosition notification unread badge position left right leading trailing side workspace učitavanje indikator lijevo desno pozicija" + "value": "Odbij" } }, "da": { "stringUnit": { "state": "translated", - "value": "sidebar.notificationBadgePosition notification unread badge position left right leading trailing side workspace indlæsning indikator venstre højre placering" + "value": "Afvis" } }, "de": { "stringUnit": { "state": "translated", - "value": "sidebar.notificationBadgePosition notification unread badge position left right leading trailing side workspace laden Indikator links rechts Position" + "value": "Ablehnen" } }, "en": { "stringUnit": { "state": "translated", - "value": "sidebar.notificationBadgePosition notification unread badge position left right leading trailing side workspace" + "value": "Deny" } }, "es": { "stringUnit": { "state": "translated", - "value": "sidebar.notificationBadgePosition notification unread badge position left right leading trailing side workspace carga indicador izquierda derecha posición" + "value": "Denegar" } }, "fr": { "stringUnit": { "state": "translated", - "value": "sidebar.notificationBadgePosition notification unread badge position left right leading trailing side workspace chargement indicateur gauche droite position" + "value": "Refuser" } }, "it": { "stringUnit": { "state": "translated", - "value": "sidebar.notificationBadgePosition notification unread badge position left right leading trailing side workspace caricamento indicatore sinistra destra posizione" + "value": "Nega" } }, "ja": { "stringUnit": { "state": "translated", - "value": "sidebar.notificationBadgePosition notification unread badge position left right leading trailing side workspace 通知 未読 バッジ 位置 左 右 サイド" + "value": "拒否" + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "បដិសេធ" } }, "ko": { "stringUnit": { "state": "translated", - "value": "sidebar.notificationBadgePosition notification unread badge position left right leading trailing side workspace 로딩 스피너 왼쪽 오른쪽 위치" + "value": "거부" } }, "nb": { "stringUnit": { "state": "translated", - "value": "sidebar.notificationBadgePosition notification unread badge position left right leading trailing side workspace lasting indikator venstre høyre plassering" + "value": "Avslå" } }, "pl": { "stringUnit": { "state": "translated", - "value": "sidebar.notificationBadgePosition notification unread badge position left right leading trailing side workspace ładowanie wskaźnik lewo prawo pozycja" + "value": "Odmów" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "sidebar.notificationBadgePosition notification unread badge position left right leading trailing side workspace carregamento indicador esquerda direita posição" + "value": "Negar" } }, "ru": { "stringUnit": { "state": "translated", - "value": "sidebar.notificationBadgePosition notification unread badge position left right leading trailing side workspace загрузка индикатор слева справа положение" + "value": "Запретить" } }, "th": { "stringUnit": { "state": "translated", - "value": "sidebar.notificationBadgePosition notification unread badge position left right leading trailing side workspace โหลด ตัวบ่งชี้ ซ้าย ขวา ตำแหน่ง" + "value": "ปฏิเสธ" } }, "tr": { "stringUnit": { "state": "translated", - "value": "sidebar.notificationBadgePosition notification unread badge position left right leading trailing side workspace yükleme gösterge sol sağ konum" + "value": "Reddet" } }, "uk": { "stringUnit": { "state": "translated", - "value": "sidebar.notificationBadgePosition notification unread badge position left right leading trailing side workspace завантаження індикатор ліворуч праворуч розташування" + "value": "Заборонити" } }, "zh-Hans": { "stringUnit": { "state": "translated", - "value": "sidebar.notificationBadgePosition notification unread badge position left right leading trailing side workspace 加载 指示器 左 右 位置" + "value": "拒绝" } }, "zh-Hant": { "stringUnit": { "state": "translated", - "value": "sidebar.notificationBadgePosition notification unread badge position left right leading trailing side workspace 載入 指示器 左 右 位置" + "value": "拒絕" } } } }, - "settings.search.alias.setting.app.show-agent-activity": { + "settings.browser.webExtension.permissionPrompt.matchPatterns.message": { "extractionState": "manual", "localizations": { "ar": { "stringUnit": { "state": "translated", - "value": "sidebar.showAgentActivity loading spinner active coding agent agents running activity تحميل مؤشر يسار يمين موضع" + "value": "يريد الامتداد “%@” الوصول إلى الصفحات المطابقة:\n\n%@" } }, "bs": { "stringUnit": { "state": "translated", - "value": "sidebar.showAgentActivity loading spinner active coding agent agents running activity učitavanje indikator lijevo desno pozicija" + "value": "Ekstenzija “%@” traži pristup odgovarajućim stranicama:\n\n%@" } }, "da": { "stringUnit": { "state": "translated", - "value": "sidebar.showAgentActivity loading spinner active coding agent agents running activity indlæsning indikator venstre højre placering" + "value": "Udvidelsen “%@” anmoder om adgang til matchende sider:\n\n%@" } }, "de": { "stringUnit": { "state": "translated", - "value": "sidebar.showAgentActivity loading spinner active coding agent agents running activity laden Indikator links rechts Position" + "value": "Die Erweiterung „%@“ möchte auf übereinstimmende Seiten zugreifen:\n\n%@" } }, "en": { "stringUnit": { "state": "translated", - "value": "sidebar.showAgentActivity loading spinner active coding agent agents running activity" + "value": "The extension “%@” wants access to matching pages:\n\n%@" } }, "es": { "stringUnit": { "state": "translated", - "value": "sidebar.showAgentActivity loading spinner active coding agent agents running activity carga indicador izquierda derecha posición" + "value": "La extensión “%@” solicita acceso a páginas coincidentes:\n\n%@" } }, "fr": { "stringUnit": { "state": "translated", - "value": "sidebar.showAgentActivity loading spinner active coding agent agents running activity chargement indicateur gauche droite position" + "value": "L’extension « %@ » souhaite accéder aux pages correspondantes :\n\n%@" } }, "it": { "stringUnit": { "state": "translated", - "value": "sidebar.showAgentActivity loading spinner active coding agent agents running activity caricamento indicatore sinistra destra posizione" + "value": "L’estensione “%@” vuole accedere alle pagine corrispondenti:\n\n%@" } }, "ja": { "stringUnit": { "state": "translated", - "value": "sidebar.showAgentActivity loading spinner active coding agent agents running activity 読み込み スピナー アクティブ コーディング エージェント 実行中 アクティビティ" + "value": "機能拡張“%@”が一致するページへのアクセスを求めています:\n\n%@" + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "ផ្នែកបន្ថែម “%@” ចង់ចូលប្រើទំព័រដែលត្រូវគ្នា៖\n\n%@" } }, "ko": { "stringUnit": { "state": "translated", - "value": "sidebar.showAgentActivity loading spinner active coding agent agents running activity 로딩 스피너 왼쪽 오른쪽 위치" + "value": "확장 프로그램 “%@”에서 일치하는 페이지에 대한 접근 권한을 요청합니다:\n\n%@" } }, "nb": { "stringUnit": { "state": "translated", - "value": "sidebar.showAgentActivity loading spinner active coding agent agents running activity lasting indikator venstre høyre plassering" + "value": "Utvidelsen «%@» ber om tilgang til samsvarende sider:\n\n%@" } }, "pl": { "stringUnit": { "state": "translated", - "value": "sidebar.showAgentActivity loading spinner active coding agent agents running activity ładowanie wskaźnik lewo prawo pozycja" + "value": "Rozszerzenie „%@” prosi o dostęp do pasujących stron:\n\n%@" } }, "pt-BR": { "stringUnit": { "state": "translated", - "value": "sidebar.showAgentActivity loading spinner active coding agent agents running activity carregamento indicador esquerda direita posição" + "value": "A extensão “%@” solicita acesso a páginas correspondentes:\n\n%@" } }, "ru": { "stringUnit": { "state": "translated", - "value": "sidebar.showAgentActivity loading spinner active coding agent agents running activity загрузка индикатор слева справа положение" + "value": "Расширение «%@» запрашивает доступ к соответствующим страницам:\n\n%@" } }, "th": { "stringUnit": { "state": "translated", - "value": "sidebar.showAgentActivity loading spinner active coding agent agents running activity โหลด ตัวบ่งชี้ ซ้าย ขวา ตำแหน่ง" + "value": "ส่วนขยาย “%@” ต้องการเข้าถึงหน้าที่ตรงกัน:\n\n%@" } }, "tr": { "stringUnit": { "state": "translated", - "value": "sidebar.showAgentActivity loading spinner active coding agent agents running activity yükleme gösterge sol sağ konum" + "value": "“%@” uzantısı eşleşen sayfalara erişmek istiyor:\n\n%@" } }, "uk": { "stringUnit": { "state": "translated", - "value": "sidebar.showAgentActivity loading spinner active coding agent agents running activity завантаження індикатор ліворуч праворуч розташування" + "value": "Розширення «%@» запитує доступ до відповідних сторінок:\n\n%@" } }, "zh-Hans": { "stringUnit": { "state": "translated", - "value": "sidebar.showAgentActivity loading spinner active coding agent agents running activity 加载 指示器 左 右 位置" + "value": "扩展程序“%@”请求访问匹配的页面:\n\n%@" } }, "zh-Hant": { "stringUnit": { "state": "translated", - "value": "sidebar.showAgentActivity loading spinner active coding agent agents running activity 載入 指示器 左 右 位置" + "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": { + "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": "延伸功能" + } + }, + "km": { + "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": "加入未封裝…" + } + }, + "km": { + "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)。" + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "ជ្រើសថតដែលមានផ្នែកបន្ថែមវេបមិនបានខ្ចប់ (manifest.json នៅកម្រិតដើម)។" + } + } + } + }, + "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": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "استيراد ملحق Safari" + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "Uvezi Safari ekstenziju" + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "Importér Safari-udvidelse" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Safari-Erweiterung importieren" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Import Safari Extension" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Importar extensión de Safari" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Importer une extension Safari" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Importa estensione Safari" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "Safari 機能拡張を読み込む" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "Safari 확장 프로그램 가져오기" + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "Importer Safari-utvidelse" + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "Importuj rozszerzenie Safari" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Importar extensão do Safari" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Импортировать расширение Safari" + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "นำเข้าส่วนขยาย Safari" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Safari Uzantısını İçe Aktar" + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "Імпортувати розширення Safari" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "导入 Safari 扩展" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "輸入 Safari 延伸功能" + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "នាំចូលផ្នែកបន្ថែម Safari" + } + } + } + }, + "settings.browser.webExtensions.importSafari.none": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "لم يتم العثور على ملحقات قابلة للاستيراد" + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "Nema ekstenzija za uvoz" + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "Ingen udvidelser at importere" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Keine importierbaren Erweiterungen gefunden" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "No Importable Extensions Found" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "No hay extensiones para importar" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Aucune extension à importer" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Nessuna estensione da importare" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "読み込める機能拡張が見つかりません" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "가져올 수 있는 확장 프로그램 없음" + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "Ingen utvidelser å importere" + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "Brak rozszerzeń do zaimportowania" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Nenhuma extensão para importar" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Нет расширений для импорта" + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "ไม่พบส่วนขยายที่นำเข้าได้" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "İçe Aktarılabilir Uzantı Bulunamadı" + } + }, + "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.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": "未加入延伸功能" + } + }, + "km": { + "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 網頁延伸功能,或加入未封裝的延伸功能檔案夾。" + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "នាំចូលផ្នែកបន្ថែម Safari ពីកម្មវិធីដែលបានដំឡើង ឬបន្ថែមថតផ្នែកបន្ថែមមិនបានខ្ចប់។" + } + } + } + }, + "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.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": { + "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": "移除" + } + }, + "km": { + "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 網頁延伸功能,或未封裝的延伸功能檔案夾。" + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "ផ្នែកបន្ថែម 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 或以上版本。" + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "ផ្នែកបន្ថែមវេបទាមទារ macOS 15.4 ឬថ្មីជាងនេះ។" + } + } + } + }, + "settings.search.alias.setting.app.loading-spinner-position": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "sidebar.loadingSpinnerPosition loading spinner position left right leading trailing side workspace تحميل مؤشر يسار يمين موضع" + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "sidebar.loadingSpinnerPosition loading spinner position left right leading trailing side workspace učitavanje indikator lijevo desno pozicija" + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "sidebar.loadingSpinnerPosition loading spinner position left right leading trailing side workspace indlæsning indikator venstre højre placering" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "sidebar.loadingSpinnerPosition loading spinner position left right leading trailing side workspace laden Indikator links rechts Position" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "sidebar.loadingSpinnerPosition loading spinner position left right leading trailing side workspace" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "sidebar.loadingSpinnerPosition loading spinner position left right leading trailing side workspace carga indicador izquierda derecha posición" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "sidebar.loadingSpinnerPosition loading spinner position left right leading trailing side workspace chargement indicateur gauche droite position" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "sidebar.loadingSpinnerPosition loading spinner position left right leading trailing side workspace caricamento indicatore sinistra destra posizione" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "sidebar.loadingSpinnerPosition loading spinner position left right leading trailing side workspace 読み込み スピナー 位置 左 右 サイド" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "sidebar.loadingSpinnerPosition loading spinner position left right leading trailing side workspace 로딩 스피너 왼쪽 오른쪽 위치" + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "sidebar.loadingSpinnerPosition loading spinner position left right leading trailing side workspace lasting indikator venstre høyre plassering" + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "sidebar.loadingSpinnerPosition loading spinner position left right leading trailing side workspace ładowanie wskaźnik lewo prawo pozycja" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "sidebar.loadingSpinnerPosition loading spinner position left right leading trailing side workspace carregamento indicador esquerda direita posição" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "sidebar.loadingSpinnerPosition loading spinner position left right leading trailing side workspace загрузка индикатор слева справа положение" + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "sidebar.loadingSpinnerPosition loading spinner position left right leading trailing side workspace โหลด ตัวบ่งชี้ ซ้าย ขวา ตำแหน่ง" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "sidebar.loadingSpinnerPosition loading spinner position left right leading trailing side workspace yükleme gösterge sol sağ konum" + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "sidebar.loadingSpinnerPosition loading spinner position left right leading trailing side workspace завантаження індикатор ліворуч праворуч розташування" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "sidebar.loadingSpinnerPosition loading spinner position left right leading trailing side workspace 加载 指示器 左 右 位置" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "sidebar.loadingSpinnerPosition loading spinner position left right leading trailing side workspace 載入 指示器 左 右 位置" + } + } + } + }, + "settings.search.alias.setting.app.notification-badge-position": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "sidebar.notificationBadgePosition notification unread badge position left right leading trailing side workspace تحميل مؤشر يسار يمين موضع" + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "sidebar.notificationBadgePosition notification unread badge position left right leading trailing side workspace učitavanje indikator lijevo desno pozicija" + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "sidebar.notificationBadgePosition notification unread badge position left right leading trailing side workspace indlæsning indikator venstre højre placering" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "sidebar.notificationBadgePosition notification unread badge position left right leading trailing side workspace laden Indikator links rechts Position" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "sidebar.notificationBadgePosition notification unread badge position left right leading trailing side workspace" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "sidebar.notificationBadgePosition notification unread badge position left right leading trailing side workspace carga indicador izquierda derecha posición" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "sidebar.notificationBadgePosition notification unread badge position left right leading trailing side workspace chargement indicateur gauche droite position" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "sidebar.notificationBadgePosition notification unread badge position left right leading trailing side workspace caricamento indicatore sinistra destra posizione" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "sidebar.notificationBadgePosition notification unread badge position left right leading trailing side workspace 通知 未読 バッジ 位置 左 右 サイド" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "sidebar.notificationBadgePosition notification unread badge position left right leading trailing side workspace 로딩 스피너 왼쪽 오른쪽 위치" + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "sidebar.notificationBadgePosition notification unread badge position left right leading trailing side workspace lasting indikator venstre høyre plassering" + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "sidebar.notificationBadgePosition notification unread badge position left right leading trailing side workspace ładowanie wskaźnik lewo prawo pozycja" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "sidebar.notificationBadgePosition notification unread badge position left right leading trailing side workspace carregamento indicador esquerda direita posição" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "sidebar.notificationBadgePosition notification unread badge position left right leading trailing side workspace загрузка индикатор слева справа положение" + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "sidebar.notificationBadgePosition notification unread badge position left right leading trailing side workspace โหลด ตัวบ่งชี้ ซ้าย ขวา ตำแหน่ง" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "sidebar.notificationBadgePosition notification unread badge position left right leading trailing side workspace yükleme gösterge sol sağ konum" + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "sidebar.notificationBadgePosition notification unread badge position left right leading trailing side workspace завантаження індикатор ліворуч праворуч розташування" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "sidebar.notificationBadgePosition notification unread badge position left right leading trailing side workspace 加载 指示器 左 右 位置" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "sidebar.notificationBadgePosition notification unread badge position left right leading trailing side workspace 載入 指示器 左 右 位置" + } + } + } + }, + "settings.search.alias.setting.app.show-agent-activity": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "sidebar.showAgentActivity loading spinner active coding agent agents running activity تحميل مؤشر يسار يمين موضع" + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "sidebar.showAgentActivity loading spinner active coding agent agents running activity učitavanje indikator lijevo desno pozicija" + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "sidebar.showAgentActivity loading spinner active coding agent agents running activity indlæsning indikator venstre højre placering" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "sidebar.showAgentActivity loading spinner active coding agent agents running activity laden Indikator links rechts Position" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "sidebar.showAgentActivity loading spinner active coding agent agents running activity" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "sidebar.showAgentActivity loading spinner active coding agent agents running activity carga indicador izquierda derecha posición" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "sidebar.showAgentActivity loading spinner active coding agent agents running activity chargement indicateur gauche droite position" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "sidebar.showAgentActivity loading spinner active coding agent agents running activity caricamento indicatore sinistra destra posizione" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "sidebar.showAgentActivity loading spinner active coding agent agents running activity 読み込み スピナー アクティブ コーディング エージェント 実行中 アクティビティ" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "sidebar.showAgentActivity loading spinner active coding agent agents running activity 로딩 스피너 왼쪽 오른쪽 위치" + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "sidebar.showAgentActivity loading spinner active coding agent agents running activity lasting indikator venstre høyre plassering" + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "sidebar.showAgentActivity loading spinner active coding agent agents running activity ładowanie wskaźnik lewo prawo pozycja" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "sidebar.showAgentActivity loading spinner active coding agent agents running activity carregamento indicador esquerda direita posição" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "sidebar.showAgentActivity loading spinner active coding agent agents running activity загрузка индикатор слева справа положение" + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "sidebar.showAgentActivity loading spinner active coding agent agents running activity โหลด ตัวบ่งชี้ ซ้าย ขวา ตำแหน่ง" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "sidebar.showAgentActivity loading spinner active coding agent agents running activity yükleme gösterge sol sağ konum" + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "sidebar.showAgentActivity loading spinner active coding agent agents running activity завантаження індикатор ліворуч праворуч розташування" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "sidebar.showAgentActivity loading spinner active coding agent agents running activity 加载 指示器 左 右 位置" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "sidebar.showAgentActivity loading spinner active coding agent agents running activity 載入 指示器 左 右 位置" + } + } + } + }, + "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" + } + }, + "km": { + "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" } } } 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/AppDelegate+BrowserWebExtensionShortcutRouting.swift b/Sources/AppDelegate+BrowserWebExtensionShortcutRouting.swift new file mode 100644 index 000000000000..6d09f252d2e6 --- /dev/null +++ b/Sources/AppDelegate+BrowserWebExtensionShortcutRouting.swift @@ -0,0 +1,133 @@ +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 { + let flags = event.modifierFlags.intersection(.deviceIndependentFlagsMask) + guard !flags.intersection([.command, .control, .option]).isEmpty else { + return false + } + return 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. + guard !flags.intersection([.command, .control, .option]).isEmpty else { + 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, + 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+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 88294bcefb4b..42202a0a72a8 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 @@ -15087,19 +15087,6 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent return false } - private 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)) @@ -15130,7 +15117,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent } } - private func numberedConfiguredShortcutDigit( + func numberedConfiguredShortcutDigit( event: NSEvent, action: KeyboardShortcutSettings.Action ) -> Int? { @@ -16063,7 +16050,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 @@ -16534,6 +16521,9 @@ private extension NSApplication { let responder = event.window?.firstResponder ?? AppDelegate.shared?.shortcutRoutingKeyWindow?.firstResponder ?? mainWindow?.firstResponder + if cmuxRouteWebExtensionCommandForStaleMenuShortcut(event, responder: responder) { + return + } if let ghosttyView = cmuxOwningGhosttyView(for: responder) { ghosttyView.keyDown(with: event) #if DEBUG 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/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 b64cbe615030..c5f94b1f508f 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 { @@ -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 @@ -258,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, allowWebExtensionInitialNavigationConfiguration: Bool = true ) -> UUID? { ensureLoaded() guard let panel = makePanel( @@ -270,7 +273,7 @@ final class DockSplitStore: BonsplitDelegate { workingDirectory: workingDirectory ?? currentBaseDirectory(), tmuxStartCommand: tmuxStartCommand, preferredProfileID: preferredProfileID, - bypassInsecureHTTPHostOnce: bypassInsecureHTTPHostOnce + 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 { @@ -389,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) @@ -440,7 +444,7 @@ final class DockSplitStore: BonsplitDelegate { workingDirectory: String, tmuxStartCommand: String? = nil, preferredProfileID: UUID? = nil, - bypassInsecureHTTPHostOnce: String? = nil + bypassInsecureHTTPHostOnce: String? = nil, webViewConfiguration: WKWebViewConfiguration? = nil, allowWebExtensionInitialNavigationConfiguration: Bool = true ) -> (any Panel)? { switch kind { case .terminal: @@ -462,7 +466,7 @@ final class DockSplitStore: BonsplitDelegate { url: url, initialRequest: initialRequest, preferredProfileID: preferredProfileID, - bypassInsecureHTTPHostOnce: bypassInsecureHTTPHostOnce + bypassInsecureHTTPHostOnce: bypassInsecureHTTPHostOnce, webViewConfiguration: webViewConfiguration, allowWebExtensionInitialNavigationConfiguration: allowWebExtensionInitialNavigationConfiguration ) } } @@ -556,22 +560,21 @@ 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 } - // 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. + browser.browserWebExtensionHost?.noteTabMetadataChanged(panelID: browser.id) + // 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/HostSettingsActions.swift b/Sources/HostSettingsActions.swift index e21003b4914f..948314527068 100644 --- a/Sources/HostSettingsActions.swift +++ b/Sources/HostSettingsActions.swift @@ -19,6 +19,33 @@ 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 + ) + } + } + + 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/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/BrowserNavigationDelegate.swift b/Sources/Panels/BrowserNavigationDelegate.swift index 86c10b9c8a99..b1eb76d263fe 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, + shouldRouteWebExtensionNavigationInCurrentTab?(url) == true, + shouldRouteWebExtensionNavigationAsCurrentTab(navigationAction, shouldOpenInNewTab: shouldOpenInNewTab) { + 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/BrowserNavigationPopupPolicy.swift b/Sources/Panels/BrowserNavigationPopupPolicy.swift index e5d491a475c0..5dc575bb0ac1 100644 --- a/Sources/Panels/BrowserNavigationPopupPolicy.swift +++ b/Sources/Panels/BrowserNavigationPopupPolicy.swift @@ -63,6 +63,27 @@ func browserNavigationShouldFallbackNilTargetToNewTab( navigationType != .other } +extension BrowserNavigationDelegate { + func shouldRouteWebExtensionNavigationAsCurrentTab( + targetFrameIsMainFrame: Bool?, + shouldOpenInNewTab: Bool, + navigationType _: WKNavigationType + ) -> Bool { + targetFrameIsMainFrame == true && !shouldOpenInNewTab + } + + 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/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 82686c11c543..8bb67a8f514a 100644 --- a/Sources/Panels/BrowserPanel.swift +++ b/Sources/Panels/BrowserPanel.swift @@ -983,71 +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", -] - -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) @@ -1213,7 +1148,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 +2681,9 @@ final class BrowserPanel: Panel, ObservableObject { /// The underlying web view private(set) var webView: WKWebView private var websiteDataStore: WKWebsiteDataStore + let browserWebExtensionHost: (any BrowserWebExtensionHosting)? + private(set) var webExtensionPageContextIdentifier: ObjectIdentifier? + var isRegisteredForWebExtensions = false var webViewDidRequestClose: (() -> Void)? /// Monotonic identity for the current WKWebView instance. @@ -3098,6 +3037,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 @@ -3321,12 +3261,13 @@ final class BrowserPanel: Panel, ObservableObject { let replacement = Self.makeWebView( profileID: profileID, - websiteDataStore: websiteDataStore + websiteDataStore: websiteDataStore, + browserWebExtensionHost: browserWebExtensionHost ) 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 @@ -3536,13 +3477,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, + webViewConfiguration: WKWebViewConfiguration? = nil ) -> CmuxWebView { - let config = WKWebViewConfiguration() - configureWebViewConfiguration( - config, - websiteDataStore: websiteDataStore ?? BrowserProfileStore.shared.websiteDataStore(for: profileID) - ) + 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 @@ -3560,12 +3502,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 + browserWebExtensionHost?.attach(to: configuration) if configuration.urlSchemeHandler(forURLScheme: CmuxDiffViewerURLSchemeHandler.scheme) == nil { configuration.setURLSchemeHandler( CmuxDiffViewerURLSchemeHandler.shared, @@ -3945,7 +3889,9 @@ final class BrowserPanel: Panel, ObservableObject { proxyEndpoint: BrowserProxyEndpoint? = nil, bypassRemoteProxy: Bool = false, isRemoteWorkspace: Bool = false, - remoteWebsiteDataStoreIdentifier: UUID? = nil + remoteWebsiteDataStoreIdentifier: UUID? = nil, + browserWebExtensionHost: (any BrowserWebExtensionHosting)? = 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. @@ -3967,25 +3913,34 @@ final class BrowserPanel: Panel, ObservableObject { ? WKWebsiteDataStore(forIdentifier: remoteWebsiteDataStoreIdentifier ?? workspaceId) : BrowserProfileStore.shared.websiteDataStore(for: resolvedProfileID) self.websiteDataStore = websiteDataStore + self.browserWebExtensionHost = browserWebExtensionHost + 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 var adoptedPrewarmedWebView = false - if let prewarmed = Self.claimedPrewarmedWebView( + if initialWebViewConfiguration == nil, let prewarmed = Self.claimedPrewarmedWebView( isRemoteWorkspace: isRemoteWorkspace, initialRequest: initialRequest, renderInitialNavigation: renderInitialNavigation, initialURL: initialURL, profileID: resolvedProfileID, - websiteDataStore: websiteDataStore + websiteDataStore: websiteDataStore, + browserWebExtensionHost: browserWebExtensionHost ) { webView = prewarmed adoptedPrewarmedWebView = true } else { webView = Self.makeWebView( profileID: resolvedProfileID, - websiteDataStore: websiteDataStore + websiteDataStore: websiteDataStore, + browserWebExtensionHost: browserWebExtensionHost, + webViewConfiguration: initialWebViewConfiguration ) } self.webView = webView + webExtensionPageContextIdentifier = initialExtensionNavigationConfiguration?.contextIdentifier self.insecureHTTPAlertFactory = { NSAlert() } hiddenWebViewDiscardManager.delegate = self applyProxyConfigurationIfAvailable() @@ -4008,6 +3963,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 @@ -4195,10 +4152,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) @@ -4213,7 +4167,7 @@ final class BrowserPanel: Panel, ObservableObject { hasCommittedDocumentSinceWebViewReplacement = true refreshBackgroundAppearance() } else { - navigate(to: url) + navigate(to: url, allowWebExtensionContext: initialExtensionNavigationConfiguration != nil) } } } @@ -4622,13 +4576,14 @@ final class BrowserPanel: Panel, ObservableObject { let replacement = Self.makeWebView( profileID: resolvedProfileID, - websiteDataStore: websiteDataStore + websiteDataStore: websiteDataStore, + browserWebExtensionHost: browserWebExtensionHost ) replacement.pageZoom = desiredZoom webViewInstanceID = UUID() hasCommittedDocumentSinceWebViewReplacement = false; userStoppedLoadSinceWebViewReplacement = false resetWebViewLifecycleMetadata(resetVisibility: false) - webView = replacement + webExtensionPageContextIdentifier = nil; webView = replacement currentURL = restoreURL shouldRenderWebView = wasRenderable refreshWebViewLifecycleState() @@ -5131,13 +5086,14 @@ final class BrowserPanel: Panel, ObservableObject { let replacement = Self.makeWebView( profileID: profileID, - websiteDataStore: websiteDataStore + websiteDataStore: websiteDataStore, + browserWebExtensionHost: browserWebExtensionHost ) replacement.pageZoom = desiredZoom webViewInstanceID = UUID() hasCommittedDocumentSinceWebViewReplacement = false; userStoppedLoadSinceWebViewReplacement = false resetWebViewLifecycleMetadata(resetVisibility: false) - webView = replacement + webExtensionPageContextIdentifier = nil; webView = replacement shouldRenderWebView = wasRenderable refreshWebViewLifecycleState() @@ -5295,6 +5251,7 @@ final class BrowserPanel: Panel, ObservableObject { } func close() { + unregisterWebExtensionIfNeeded() cancelHiddenWebViewDiscard() isClosingWebViewLifecycle = true refreshWebViewLifecycleState() @@ -5680,13 +5637,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( @@ -5706,15 +5663,15 @@ 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 } + guard let url = request.url, !shouldBlockWebExtensionNavigation(to: url, allowWebExtensionContext: allowWebExtensionContext) else { return } cancelHiddenWebViewDiscard() if usesRemoteWorkspaceProxy, remoteProxyEndpoint == nil { pendingRemoteNavigation = PendingRemoteNavigation( request: request, recordTypedNavigation: recordTypedNavigation, - preserveRestoredSessionHistory: preserveRestoredSessionHistory + preserveRestoredSessionHistory: preserveRestoredSessionHistory, allowWebExtensionContext: allowWebExtensionContext ) hiddenWebViewDiscardManager.updateRestoredSessionRenderIntent(nil) currentURL = Self.remoteProxyDisplayURL(for: url) ?? url @@ -5727,7 +5684,7 @@ final class BrowserPanel: Panel, ObservableObject { request: request, originalURL: url, recordTypedNavigation: recordTypedNavigation, - preserveRestoredSessionHistory: preserveRestoredSessionHistory + preserveRestoredSessionHistory: preserveRestoredSessionHistory, allowWebExtensionContext: allowWebExtensionContext ) } @@ -5747,7 +5704,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 } @@ -5756,7 +5713,7 @@ final class BrowserPanel: Panel, ObservableObject { request: URLRequest, originalURL: URL, recordTypedNavigation: Bool, - preserveRestoredSessionHistory: Bool + preserveRestoredSessionHistory: Bool, allowWebExtensionContext: Bool ) { cancelHiddenWebViewDiscard() clearWebContentTerminationRecovery() @@ -5764,6 +5721,7 @@ final class BrowserPanel: Panel, ObservableObject { abandonRestoredSessionHistoryIfNeeded() } let effectiveRequest = remoteProxyPreparedRequest(from: request, logScope: "rewrite") + 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) @@ -5787,6 +5745,93 @@ final class BrowserPanel: Panel, ObservableObject { } } + private func ensureWebExtensionNavigationConfiguration(for url: URL, allowWebExtensionContext: Bool) { + let targetConfiguration = browserWebExtensionHost?.webViewConfiguration(forNavigatingTo: url) + let targetContextIdentifier = targetConfiguration?.contextIdentifier + guard targetContextIdentifier != webExtensionPageContextIdentifier else { return } + 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 + if contextIdentifier != webExtensionPageContextIdentifier { + replaceWebViewForWebExtensionNavigation( + webViewConfiguration: webViewConfiguration, + contextIdentifier: contextIdentifier + ) + } + } + navigate(to: url) + } + + 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" + let restoreDeveloperTools = preferredDeveloperToolsVisible || isDeveloperToolsVisible() + +#if DEBUG + cmuxDebugLog( + "browser.webext.webviewSwap panel=\(id.uuidString.prefix(5)) " + + "reason=\(reason)" + ) +#endif + + prepareDeveloperToolsForWebViewReplacement(preserveVisibleIntent: restoreDeveloperTools) + 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() + if restoreDeveloperTools { + requestDeveloperToolsRefreshAfterNextAttach(reason: reason) + } + } + private func remoteProxyPreparedRequest(from request: URLRequest, logScope: String) -> URLRequest { guard remoteProxyEndpoint != nil else { return request } guard let url = request.url else { return request } @@ -5876,7 +5921,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) } @@ -6142,11 +6187,12 @@ extension BrowserPanel { let replacement = Self.makeWebView( profileID: profileID, - websiteDataStore: websiteDataStore + websiteDataStore: websiteDataStore, + browserWebExtensionHost: browserWebExtensionHost ) webViewInstanceID = UUID() hasCommittedDocumentSinceWebViewReplacement = false; userStoppedLoadSinceWebViewReplacement = false - webView = replacement + webExtensionPageContextIdentifier = nil; webView = replacement shouldRenderWebView = false refreshWebViewLifecycleState() bindWebView(replacement) @@ -6317,70 +6363,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 - ) 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/BrowserPanelView.swift b/Sources/Panels/BrowserPanelView.swift index a68d6b2f4462..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" @@ -1348,6 +1273,15 @@ struct BrowserPanelView: View { onClear: { panel.clearRecentDownloads() } ) } + + if #available(macOS 15.4, *), let support = panel.browserWebExtensionSupport { + BrowserWebExtensionToolbarButtons( + support: support, + panel: panel, + iconPointSize: chromeMetrics.navigationIconFontSize, + hitSize: addressBarButtonHitSize + ) + } } } 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/Panels/BrowserWebExtensionActionSnapshot.swift b/Sources/Panels/BrowserWebExtensionActionSnapshot.swift new file mode 100644 index 000000000000..13aee9c13899 --- /dev/null +++ b/Sources/Panels/BrowserWebExtensionActionSnapshot.swift @@ -0,0 +1,19 @@ +import AppKit + +@available(macOS 15.4, *) +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 + character.isLetter || character.isNumber ? character : "-" + } + .reduce(into: "") { $0.append($1) } + return "BrowserWebExtensionActionButton-\(safeID)" + } +} 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/BrowserWebExtensionDiscoveryService.swift b/Sources/Panels/BrowserWebExtensionDiscoveryService.swift new file mode 100644 index 000000000000..127fdf82c36b --- /dev/null +++ b/Sources/Panels/BrowserWebExtensionDiscoveryService.swift @@ -0,0 +1,179 @@ +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") + 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? + + func discoverInstalledSafariExtensions() async -> [BrowserWebExtensionCandidate] { + let output: String + do { + output = try await runPluginkit() + } catch { + return [] + } + return Self.parse(pluginkitOutput: output) + } + + /// 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] { + var seen = Set() + var candidates: [BrowserWebExtensionCandidate] = [] + for line in pluginkitOutput.split(separator: "\n") { + let rawLine = String(line).trimmingCharacters(in: .whitespaces) + guard let pathRange = Self.appexPathRange(in: rawLine) else { continue } + let path = String(rawLine[pathRange]) + let prefix = String(rawLine[.. 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? { + 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 { + 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 = Self.pluginkitArguments + let stdout = Pipe() + process.standardOutput = stdout + // 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() + 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"). + for try await byte in stdout.fileHandleForReading.bytes { + data.append(byte) + } + 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/BrowserWebExtensionHosting.swift b/Sources/Panels/BrowserWebExtensionHosting.swift new file mode 100644 index 000000000000..4532b5968d5a --- /dev/null +++ b/Sources/Panels/BrowserWebExtensionHosting.swift @@ -0,0 +1,13 @@ +import AppKit +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) + func noteTabMetadataChanged(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..bc2c2fd900d6 --- /dev/null +++ b/Sources/Panels/BrowserWebExtensionLoadedRecord.swift @@ -0,0 +1,11 @@ +import CmuxSettings +import WebKit + +@available(macOS 15.4, *) +struct BrowserWebExtensionLoadedRecord { + let entry: BrowserWebExtensionEntry + let standardizedPath: String + let context: WKWebExtensionContext + + var entryID: String { entry.id } +} diff --git a/Sources/Panels/BrowserWebExtensionNavigationConfiguration.swift b/Sources/Panels/BrowserWebExtensionNavigationConfiguration.swift new file mode 100644 index 000000000000..bc9679ff2942 --- /dev/null +++ b/Sources/Panels/BrowserWebExtensionNavigationConfiguration.swift @@ -0,0 +1,128 @@ +import AppKit +import WebKit + +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 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/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..abf2bb91755f --- /dev/null +++ b/Sources/Panels/BrowserWebExtensionPermissionStateStore.swift @@ -0,0 +1,53 @@ +import Foundation + +@available(macOS 15.4, *) +struct BrowserWebExtensionPermissionStateStore { + private static let storageKey = "browser.webExtensionPermissionStates.v2" + + private let defaults: UserDefaults + + init(defaults: UserDefaults = .standard) { + self.defaults = defaults + } + + func state(for entryID: String, standardizedPath: String) -> BrowserWebExtensionPermissionState? { + allStates()[storageIdentity(entryID: entryID, standardizedPath: standardizedPath)] + } + + func save(_ state: BrowserWebExtensionPermissionState, for entryID: String, standardizedPath: String) { + var states = allStates() + states[storageIdentity(entryID: entryID, standardizedPath: standardizedPath)] = state + saveAllStates(states) + } + + func removeState(for entryID: String, standardizedPath: String) { + var states = allStates() + 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( + [String: BrowserWebExtensionPermissionState].self, + from: data + ) else { + return [:] + } + return states + } + + 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 new file mode 100644 index 000000000000..0e1f02c1f358 --- /dev/null +++ b/Sources/Panels/BrowserWebExtensionPopoutWindowController.swift @@ -0,0 +1,201 @@ +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(set) 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) +#if DEBUG + webView.isInspectable = true +#endif + + 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], + 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 usesFallbackFrame { + window.center() + } + + super.init() + window.delegate = self + window.title = context.webExtension.displayName ?? String( + localized: "browser.webExtension.action.help", + defaultValue: "Extension" + ) + + if let url = configuration.tabURLs.first, + support.canOpenExtensionPopupURL(url, for: context) { + webView.load(URLRequest(url: url)) + } + if configuration.shouldBeFocused { + NSApp.activate() + 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) { + NSApp.activate() + window.makeKeyAndOrderFront(nil) + completionHandler(nil) + } + + func close(for context: WKWebExtensionContext, completionHandler: @escaping (Error?) -> Void) { + closeFromExtensionOrUser() + completionHandler(nil) + } + + func canLoadExtensionRequestedURL(_ url: URL) -> Bool { + guard let extensionContext else { return false } + return support?.canOpenExtensionPopupURL(url, for: extensionContext) == true + } + + // 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) { + guard let controller, + controller.canLoadExtensionRequestedURL(url) else { + completionHandler(NSError(domain: "cmux.webExtension.popup", code: 1)) + return + } + 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/BrowserWebExtensionReconciliationPlanner.swift b/Sources/Panels/BrowserWebExtensionReconciliationPlanner.swift new file mode 100644 index 000000000000..3f119f1a560e --- /dev/null +++ b/Sources/Panels/BrowserWebExtensionReconciliationPlanner.swift @@ -0,0 +1,140 @@ +import CmuxSettings +import Foundation + +struct BrowserWebExtensionReconciliationPlanner { + struct LoadedEntry: Equatable { + let id: String + let standardizedPath: String + } + + struct UnloadEntry: Equatable { + let id: String + let preservePermissionState: Bool + } + + struct Plan: Equatable { + let desiredEntries: [BrowserWebExtensionEntry] + let unloadEntries: [UnloadEntry] + let loadEntries: [BrowserWebExtensionEntry] + + var unloadEntryIDs: [String] { + unloadEntries.map(\.id) + } + } + + 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) }) + var configuredResourceRootByID: [String: String] = [:] + for entry in settingsEntries { + configuredResourceRootByID[entry.id] = Self.standardizedResourceRootPath(for: entry) + } + + let unloadEntries = loadedEntries + .filter { loaded in + guard let desired = desiredByID[loaded.id] else { return true } + return Self.standardizedResourceRootPath(for: desired) != loaded.standardizedPath + } + .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 } + return loaded.standardizedPath != Self.standardizedResourceRootPath(for: entry) + } + + return Plan( + desiredEntries: desiredEntries, + unloadEntries: unloadEntries, + loadEntries: loadEntries + ) + } + + 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) + } + + static func standardizedResourceRootPath(for entry: BrowserWebExtensionEntry) -> String { + entry.standardizedResourceRootPath + } + + 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) + return URL(fileURLWithPath: standardizedPath).pathExtension == "appex" + ? .safariAppExtension + : .unpackedDirectory + } + + private func desired( + settingsEntries: [BrowserWebExtensionEntry], + environmentPaths: [String] + ) -> [BrowserWebExtensionEntry] { + 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.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.standardizedResourceRootPath(forEnvironmentPath: 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: Self.kind(forEnvironmentPath: path), + 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..0d5693e1ee78 --- /dev/null +++ b/Sources/Panels/BrowserWebExtensionSupport+Loading.swift @@ -0,0 +1,355 @@ +import CmuxSettings +import CryptoKit +import Foundation +import WebKit + +@available(macOS 15.4, *) +extension BrowserWebExtensionSupport { + var loadedRecordsInOrder: [BrowserWebExtensionLoadedRecord] { + loadedEntryIDsInOrder.compactMap { loadedByEntryID[$0] } + } + + 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, + environmentPaths: Self.environmentExtensionPaths(), + loadedEntries: loadedByEntryID.values.map { + BrowserWebExtensionReconciliationPlanner.LoadedEntry( + id: $0.entryID, + standardizedPath: $0.standardizedPath + ) + } + ) + + var failedUnloadEntries: [BrowserWebExtensionEntry] = [] + for entry in plan.unloadEntries { + 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 } + for entry in plan.loadEntries where loadedByEntryID[entry.id] == nil { + 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 } + return actionSnapshot(for: record, tabAdapter: tabAdapter) + } + } + + func rebuildActionSnapshots() { + actionSnapshotIDs = loadedRecordsInOrder.map(\.entryID) + refreshAllActionSnapshots() + } + + func refreshActionSnapshot(for context: WKWebExtensionContext) { + guard actionSnapshotIDs.contains(where: { loadedByEntryID[$0]?.context === context }) else { + rebuildActionSnapshots() + return + } + 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 + } + + func refreshActionSnapshots(for panelID: UUID?) { + guard let panelID, + let invalidation = actionSnapshotInvalidationsByPanelID[panelID] else { return } + invalidation.refresh() + } + + func extensionPagePanels(usingContextIdentifier contextIdentifier: ObjectIdentifier) -> [BrowserPanel] { + tabAdapters.values.compactMap(\.panel).filter { + $0.webExtensionPageContextIdentifier == contextIdentifier + } + } + + 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( + 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 + ) + } + + @discardableResult + private func unload( + entryID: String, + preservePermissionState: Bool = true + ) -> BrowserWebExtensionEntry? { + guard let record = loadedByEntryID[entryID] else { return nil } + let extensionPagePanels = extensionPagePanels( + usingContextIdentifier: ObjectIdentifier(record.context) + ) + if preservePermissionState { + persistPermissionState( + entryID: entryID, + standardizedPath: record.standardizedPath, + context: record.context + ) + } + do { + try controller.unload(record.context) + } catch { + recordLoadError(entryID: entryID) +#if DEBUG + cmuxDebugLog(BrowserWebExtensionDiagnostics.failure(operation: .unload, error: error)) +#endif + return record.entry + } + + removePermissionStateObservers(entryID: entryID) + if !preservePermissionState { + removePermissionState(entryID: entryID, standardizedPath: record.standardizedPath) + } + loadedByEntryID[entryID] = nil + loadedEntryIDsInOrder.removeAll { $0 == entryID } + 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() + } +#if DEBUG + cmuxDebugLog(BrowserWebExtensionDiagnostics.success(operation: .unload)) +#endif + return nil + } + + @discardableResult + func unloadAllWebExtensions() -> Bool { + var didUnloadEveryExtension = true + for entryID in Array(loadedEntryIDsInOrder) { + if unload(entryID: entryID) != nil { + didUnloadEveryExtension = false + } + } + 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 { + do { + let webExtension = try await makeWebExtension(for: entry) + guard canApplyWebExtensionLoad(generation: generation) else { return } + let standardizedPath = BrowserWebExtensionReconciliationPlanner.standardizedResourceRootPath(for: entry) + let context = try load(webExtension, entryID: entry.id, standardizedPath: standardizedPath) + loadedByEntryID[entry.id] = BrowserWebExtensionLoadedRecord( + entry: entry, + standardizedPath: standardizedPath, + context: context + ) + if !loadedEntryIDsInOrder.contains(entry.id) { + loadedEntryIDsInOrder.append(entry.id) + } + loadErrorsByEntryID.removeValue(forKey: entry.id) + refreshLoadErrors() +#if DEBUG + cmuxDebugLog(BrowserWebExtensionDiagnostics.success(operation: .load)) +#endif + } catch { + guard canApplyWebExtensionLoad(generation: generation) else { return } + recordLoadError(entryID: entry.id) +#if DEBUG + cmuxDebugLog(BrowserWebExtensionDiagnostics.failure(operation: .load, error: error)) +#endif + } + } + + 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(entryID: entry.id) + } +#if DEBUG + 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" { + 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, + entryID: String, + standardizedPath: String + ) throws -> WKWebExtensionContext { + let context = WKWebExtensionContext(for: webExtension) + configureStableContextIdentity(context, entryID: entryID, standardizedPath: standardizedPath) +#if DEBUG + context.isInspectable = true +#endif + restorePermissionState(for: context, entryID: entryID, standardizedPath: standardizedPath) + installPermissionStateObservers( + for: context, + entryID: entryID, + standardizedPath: standardizedPath + ) + do { + try controller.load(context) + } catch { + removePermissionStateObservers(entryID: entryID) + throw error + } + 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))" + } + + func recordLoadError(entryID: String) { + loadErrorsByEntryID[entryID] = BrowserWebExtensionDiagnostics.genericFailureMessage + refreshLoadErrors() + } + + private func refreshLoadErrors() { + loadErrors = loadErrorsByEntryID + .sorted { $0.key < $1.key } + .map(\.value) + for continuation in loadErrorUpdateContinuations.values { + continuation.yield(loadErrorsByEntryID) + } + } +} + +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/BrowserWebExtensionSupport+Permissions.swift b/Sources/Panels/BrowserWebExtensionSupport+Permissions.swift new file mode 100644 index 000000000000..be96ebf7b4d9 --- /dev/null +++ b/Sources/Panels/BrowserWebExtensionSupport+Permissions.swift @@ -0,0 +1,87 @@ +import Foundation +import WebKit + +@available(macOS 15.4, *) +extension BrowserWebExtensionSupport { + func restorePermissionState(for context: WKWebExtensionContext, entryID: String, standardizedPath: String) { + permissionStateStore.state(for: entryID, standardizedPath: standardizedPath)?.apply(to: context) + } + + func persistPermissionState(entryID: String, standardizedPath: String, context: WKWebExtensionContext) { + permissionStateStore.save( + BrowserWebExtensionPermissionState(context: context), + for: entryID, + standardizedPath: standardizedPath + ) + } + + 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, + standardizedPath: record.standardizedPath, + 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, + standardizedPath: 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, + standardizedPath: standardizedPath, + 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 new file mode 100644 index 000000000000..5c45928e45f5 --- /dev/null +++ b/Sources/Panels/BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift @@ -0,0 +1,464 @@ +import AppKit +import WebKit + +@available(macOS 15.4, *) +extension BrowserWebExtensionSupport: WKWebExtensionControllerDelegate { + func webExtensionController( + _ controller: WKWebExtensionController, + openWindowsFor extensionContext: WKWebExtensionContext + ) -> [any WKWebExtensionWindow] { + let openWindows: [any WKWebExtensionWindow] = [windowAdapter] + popouts(for: extensionContext) + guard let focusedWindow = focusedWebExtensionWindow(for: NSApp.keyWindow, among: openWindows) else { + return openWindows + } + let focusedID = ObjectIdentifier(focusedWindow as AnyObject) + return [focusedWindow] + openWindows.filter { + ObjectIdentifier($0 as AnyObject) != focusedID + } + } + + func webExtensionController( + _ controller: WKWebExtensionController, + focusedWindowFor extensionContext: WKWebExtensionContext + ) -> (any WKWebExtensionWindow)? { + let openWindows: [any WKWebExtensionWindow] = [windowAdapter] + popouts(for: extensionContext) + return focusedWebExtensionWindow(for: NSApp.keyWindow, among: openWindows) + } + + private func popouts(for extensionContext: WKWebExtensionContext) -> [BrowserWebExtensionPopoutWindowController] { + popouts.filter { $0.extensionContext === extensionContext } + } + + 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 + guard !configuration.shouldBePrivate else { + completionHandler(nil, openTabsUnsupportedError()) + return + } + guard configuration.windowType == .popup else { + guard configuration.windowType == .normal, + let window = openNormalBrowserWindow(using: configuration, for: extensionContext) else { + completionHandler(nil, openTabsUnsupportedError()) + return + } + completionHandler(window, nil) + return + } + guard configuration.tabURLs.allSatisfy({ canOpenExtensionPopupURL($0, for: extensionContext) }) else { + completionHandler(nil, openTabsUnsupportedError()) + return + } + let popout = BrowserWebExtensionPopoutWindowController( + configuration: configuration, + context: extensionContext, + support: self + ) + popouts.append(popout) + controller.didOpenWindow(popout) + controller.didOpenTab(popout.tab) + if popout.isKeyWindow { + controller.didFocusWindow(popout) + } + completionHandler(popout, nil) + } + + private func openNormalBrowserWindow( + using configuration: WKWebExtension.WindowConfiguration, + for extensionContext: WKWebExtensionContext + ) -> (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 } + } + + 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 let adapter = openBrowserTab( + url: requestedTab.url, + shouldActivate: shouldActivate, + webViewConfiguration: requestedTab.webViewConfiguration + ), let panel = adapter.panel else { + openedPanels.reversed().forEach(closeOpenedBrowserTab) + return nil + } + openedPanels.append(panel) + } + return windowAdapter + } + + 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, + 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, + !canOpenExtensionRequestedBrowserURL(url, for: extensionContext) { + completionHandler(nil, openTabsUnsupportedError()) + return + } + + guard let adapter = openBrowserTab( + url: configuration.url, + shouldActivate: configuration.shouldBeActive, + webViewConfiguration: configuration.url.flatMap { webViewConfigurationForExtensionRequestedBrowserURL($0, for: extensionContext) } + ) else { + completionHandler(nil, openTabsUnsupportedError()) + return + } + completionHandler(adapter, nil) + } + + func openBrowserTab( + url: URL?, + shouldActivate: Bool, + webViewConfiguration: WKWebViewConfiguration? + ) -> BrowserWebExtensionTabAdapter? { + 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 + ) + } + + 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) + } + guard let panel = workspace.newBrowserSurface( + inPane: paneID, + url: url, + focus: shouldActivate, + preferredProfileID: workspace.preferredBrowserProfileID, + webViewConfiguration: webViewConfiguration + ) else { return nil } + return tabAdapterForOpenedPanel(panel, shouldActivate: shouldActivate) + } + + 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 } + 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 + } + + 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) } + } + + 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, for extensionContext: WKWebExtensionContext) -> WKWebViewConfiguration? { + guard controller.extensionContext(for: url) === extensionContext else { return nil } + return extensionContext.webViewConfiguration + } + + 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", + code: 2, + userInfo: [NSLocalizedDescriptionKey: String( + localized: "browser.webExtension.error.openTabsUnsupported", + defaultValue: "Opening extension tabs is not supported yet." + )] + ) + } + + func webExtensionController( + _ controller: WKWebExtensionController, + didUpdate action: WKWebExtension.Action, + forExtensionContext context: WKWebExtensionContext + ) { + refreshActionSnapshot(for: action, context: context) + } + + 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, + 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) + persistPermissionStateSoon(for: extensionContext) + } + + 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) + persistPermissionStateSoon(for: extensionContext) + } + + 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) + persistPermissionStateSoon(for: extensionContext) + } + + private func permissionMessage( + extensionContext: WKWebExtensionContext, + details: String, + key: StaticString, + defaultValue: String.LocalizationValue + ) -> String { + let extensionName = extensionContext.webExtension.displayName ?? String( + localized: "browser.webExtension.action.help", + defaultValue: "Extension" + ) + return String.localizedStringWithFormat( + 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 new file mode 100644 index 000000000000..387e5b4b661e --- /dev/null +++ b/Sources/Panels/BrowserWebExtensionSupport.swift @@ -0,0 +1,438 @@ +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+). +/// +/// 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 +@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")! + + @ObservationIgnored + let controller: WKWebExtensionController + @ObservationIgnored + let permissionStateStore = BrowserWebExtensionPermissionStateStore() + + var actionSnapshotIDs: [String] = [] + var actionSnapshotRevision = 0 + var loadErrors: [String] = [] + + @ObservationIgnored + var settingsObservationTask: Task? + @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] = [] + @ObservationIgnored + var loadErrorsByEntryID: [String: String] = [:] + @ObservationIgnored + var loadErrorUpdateContinuations: [UUID: AsyncStream<[String: String]>.Continuation] = [:] + @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]] = [:] + @ObservationIgnored + var orderedPanelIDs: [UUID] = [] + @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] = [] + + /// Anchor for the next action popup presentation, set by the toolbar button + /// immediately before calling `performAction(context:panel:anchorView:)`. + @ObservationIgnored + weak var pendingPopupAnchorView: NSView? + + 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 = BrowserUserAgentSettings.safariApplicationNameForUserAgent + configuration.webViewConfiguration = webViewConfiguration + 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 { + settingsObservationTask?.cancel() + tabMetadataFlushTask?.cancel() + 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 + // with self. (Calling the @MainActor removal helper from nonisolated + // deinit does not compile.) + } + + // MARK: - Configuration attachment + + /// Attaches the shared extension controller to a browser web view configuration. + func attach(to configuration: WKWebViewConfiguration) { + 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 + /// 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) { + settingsStore = jsonStore + settingsKey = catalog.browser.webExtensions + 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 } + 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, generation: self.settingsLoadGeneration) + } + } + } + + private func stopSettingsObservationAndUnload() { + settingsLoadGeneration &+= 1 + settingsObservationTask?.cancel() + settingsObservationTask = nil + if !unloadAllWebExtensions() { + BrowserAvailabilitySettings.setDisabled(false) + } + } + + 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 } + } + + // 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 + tabMetadataSnapshotsByPanelID[panel.id] = TabMetadataSnapshot(panel: panel) + 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 } + tabMetadataSnapshotsByPanelID.removeValue(forKey: panelID) + pendingTabMetadataPanelIDs.remove(panelID) + orderedPanelIDs.removeAll { $0 == panelID } + activePanelIDsByWindow = activePanelIDsByWindow.filter { $0.value != panelID } + actionSnapshotInvalidationsByPanelID.removeValue(forKey: panelID) + 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) + refreshActionSnapshots(for: successor.panel?.id) + } + } + } + + func noteActivated(panelID: UUID) { + guard tabAdapters[panelID] != nil else { return } + rememberActivePanel(panelID) + guard activePanelID != panelID else { return } + let previousPanelID = activePanelID + let previous = previousPanelID.flatMap { tabAdapters[$0] } + activePanelID = panelID + if let adapter = tabAdapters[panelID] { + controller.didActivateTab(adapter, previousActiveTab: previous) + } + refreshActionSnapshots(for: previousPanelID) + refreshActionSnapshots(for: panelID) + } + + func noteWindowBecameKey(_ window: NSWindow) { + 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 + } + + func focusedWebExtensionWindow(for keyWindow: NSWindow?) -> (any WKWebExtensionWindow)? { + guard let keyWindow else { return nil } + 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 + } + + 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 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? { + 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 record in loadedRecordsInOrder where record.context.performCommand(for: event) { +#if DEBUG + cmuxDebugLog("browser.webext.command handled name=\(record.context.webExtension.displayName ?? "?")") +#endif + return true + } + 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) + } +} + + +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 new file mode 100644 index 000000000000..747c3fd2a811 --- /dev/null +++ b/Sources/Panels/BrowserWebExtensionTabAdapter.swift @@ -0,0 +1,128 @@ +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 isMuted(for context: WKWebExtensionContext) -> Bool { + panel?.isMuted ?? false + } + + func isSelected(for context: WKWebExtensionContext) -> Bool { + support?.activePanelID == panelID + } + + func activate(for context: WKWebExtensionContext, completionHandler: @escaping (Error?) -> Void) { + 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 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, + support.canOpenExtensionRequestedBrowserURL(url, for: context) else { + completionHandler(webExtensionTabError(code: 4)) + return + } + panel.navigateFromWebExtension( + to: url, + webViewConfiguration: support.webViewConfigurationForExtensionRequestedBrowserURL(url, for: context) + ) + completionHandler(nil) + } + + func reload(fromOrigin: Bool, for context: WKWebExtensionContext, completionHandler: @escaping (Error?) -> Void) { + guard let webView = panel?.webView else { + completionHandler(webExtensionTabError(code: 3)) + return + } + if fromOrigin { + webView.reloadFromOrigin() + } else { + webView.reload() + } + completionHandler(nil) + } + + func goBack(for context: WKWebExtensionContext, completionHandler: @escaping (Error?) -> Void) { + guard let webView = panel?.webView else { + completionHandler(webExtensionTabError(code: 3)) + return + } + webView.goBack() + completionHandler(nil) + } + + func goForward(for context: WKWebExtensionContext, completionHandler: @escaping (Error?) -> Void) { + guard let webView = panel?.webView else { + completionHandler(webExtensionTabError(code: 3)) + return + } + webView.goForward() + completionHandler(nil) + } + + private func focusOwningCmuxTab() -> Bool { + guard let panel else { return false } + return support?.focusOwningCmuxTab(panelID: panelID, workspaceId: panel.workspaceId) ?? false + } + + private func webExtensionTabError(code: Int) -> NSError { + NSError(domain: "cmux.webExtension.tab", code: code) + } +} diff --git a/Sources/Panels/BrowserWebExtensionToolbarButtons.swift b/Sources/Panels/BrowserWebExtensionToolbarButtons.swift new file mode 100644 index 000000000000..134e17b3d76e --- /dev/null +++ b/Sources/Panels/BrowserWebExtensionToolbarButtons.swift @@ -0,0 +1,111 @@ +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 { + let support: BrowserWebExtensionSupport + let panel: BrowserPanel + let iconPointSize: CGFloat + let hitSize: CGFloat + + var body: some View { + ForEach(support.actionSnapshots(for: panel.id)) { snapshot in + BrowserWebExtensionActionButton( + snapshot: snapshot, + panel: panel, + iconPointSize: iconPointSize, + hitSize: hitSize, + performAction: { anchorView in + guard let context = support.context(forActionID: snapshot.id) else { return } + support.performAction(context: context, panel: panel, anchorView: anchorView) + } + ) + } + } +} + +@available(macOS 15.4, *) +private struct BrowserWebExtensionActionButton: View { + let snapshot: BrowserWebExtensionActionSnapshot + let panel: BrowserPanel + let iconPointSize: CGFloat + let hitSize: CGFloat + let performAction: (NSView?) -> Void + + @State private var anchorViewHolder = BrowserWebExtensionAnchorViewHolder() + + var body: some View { + Button(action: { +#if DEBUG + cmuxDebugLog(BrowserWebExtensionDiagnostics.success(operation: .action)) +#endif + performAction(anchorViewHolder.view) + }) { + actionIcon + .frame(width: hitSize, height: hitSize, alignment: .center) + .contentShape(Rectangle()) + } + .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 { + 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) + } + } + } +} + +/// 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..7ddaa1fa8d90 --- /dev/null +++ b/Sources/Panels/BrowserWebExtensionWindowAdapter.swift @@ -0,0 +1,67 @@ +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) { + 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() + hostWindow.makeKeyAndOrderFront(nil) + completionHandler(nil) + } + + private var hostWindow: NSWindow? { + support?.activeTabAdapter?.panel?.webView.window + } +} diff --git a/Sources/Panels/CmuxWebView.swift b/Sources/Panels/CmuxWebView.swift index d251881fa2c2..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) @@ -665,34 +659,21 @@ 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 { return finish(AppDelegate.shared?.handleBrowserSurfaceKeyEquivalent(event) == true) } + if cmuxPerformBrowserWebExtensionCommandKeyEquivalent(event) { + 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 { 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/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/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..88ff45fbe825 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) @@ -6154,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+DockBrowserLookup.swift b/Sources/Workspace+DockBrowserLookup.swift index 17beb6e87d7e..0f0fd06ae35a 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? { @@ -38,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, @@ -47,11 +52,16 @@ extension Workspace { initialRequest: seed.initialRequest, focus: true, preferredProfileID: panel.profileID, - bypassInsecureHTTPHostOnce: seed.bypassInsecureHTTPHostOnce + bypassInsecureHTTPHostOnce: seed.bypassInsecureHTTPHostOnce, + 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, @@ -63,12 +73,17 @@ extension Workspace { initialRequest: seed.initialRequest, focus: true, preferredProfileID: panel.profileID, - bypassInsecureHTTPHostOnce: seed.bypassInsecureHTTPHostOnce + bypassInsecureHTTPHostOnce: seed.bypassInsecureHTTPHostOnce, + 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 + ) } } @@ -97,7 +112,9 @@ extension DockSplitStore { url: URL?, initialRequest: URLRequest? = nil, preferredProfileID: UUID? = nil, - bypassInsecureHTTPHostOnce: String? = nil + bypassInsecureHTTPHostOnce: String? = nil, + webViewConfiguration: WKWebViewConfiguration? = nil, + allowWebExtensionInitialNavigationConfiguration: Bool = true ) -> BrowserPanel { let settings = currentRemoteBrowserSettings() let panel = BrowserPanel( @@ -109,7 +126,10 @@ extension DockSplitStore { proxyEndpoint: settings.proxyEndpoint, bypassRemoteProxy: settings.bypassRemoteProxy, isRemoteWorkspace: settings.isRemoteWorkspace, - remoteWebsiteDataStoreIdentifier: settings.remoteWebsiteDataStoreIdentifier + remoteWebsiteDataStoreIdentifier: settings.remoteWebsiteDataStoreIdentifier, + browserWebExtensionHost: browserWebExtensionHost, + webViewConfiguration: webViewConfiguration, + allowWebExtensionInitialNavigationConfiguration: allowWebExtensionInitialNavigationConfiguration ) panel.setRemoteWorkspaceStatus(settings.remoteStatus) panel.webViewDidRequestClose = { [weak self, weak panel] in 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 e6a2068b0d57..490fa3a4ef60 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 { @@ -39,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 @@ -1815,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 @@ -1997,6 +1898,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 +1928,8 @@ final class Workspace: Identifiable, ObservableObject { remoteWebsiteDataStoreIdentifier: self.isRemoteWorkspace ? self.id : nil, remoteStatus: self.browserRemoteWorkspaceStatusSnapshot() ) - } + }, + browserWebExtensionHost: browserWebExtensionHost ) _dockSplit = store return store @@ -2365,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 @@ -2859,6 +2762,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 +2774,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 +2846,8 @@ final class Workspace: Identifiable, ObservableObject { profileID: resolvedNewBrowserProfileID(), initialURL: initialBrowserURL, omnibarVisible: initialBrowserOmnibarVisible, - transparentBackground: initialBrowserTransparentBackground + transparentBackground: initialBrowserTransparentBackground, + browserWebExtensionHost: browserWebExtensionHost ) configureBrowserPanel(browserPanel) panels[browserPanel.id] = browserPanel @@ -2965,8 +2871,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 @@ -3579,6 +3489,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 }) @@ -3591,6 +3505,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 @@ -7956,7 +7871,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 @@ -7984,6 +7900,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) @@ -8029,7 +7946,9 @@ final class Workspace: Identifiable, ObservableObject { creationPolicy: BrowserPanelCreationPolicy = .userInitiated, omnibarVisible: Bool = true, transparentBackground: Bool = false, - bypassRemoteProxy: Bool = false + bypassRemoteProxy: Bool = false, + 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 @@ -8065,7 +7984,10 @@ final class Workspace: Identifiable, ObservableObject { proxyEndpoint: remoteProxyEndpoint, bypassRemoteProxy: bypassRemoteProxy, isRemoteWorkspace: isRemoteWorkspace, - remoteWebsiteDataStoreIdentifier: isRemoteWorkspace && !bypassRemoteProxy ? id : nil + remoteWebsiteDataStoreIdentifier: isRemoteWorkspace && !bypassRemoteProxy ? id : nil, + browserWebExtensionHost: browserWebExtensionHost, + webViewConfiguration: webViewConfiguration, + allowWebExtensionInitialNavigationConfiguration: allowWebExtensionInitialNavigationConfiguration ) configureBrowserPanel(browserPanel) panels[browserPanel.id] = browserPanel @@ -8084,6 +8006,7 @@ final class Workspace: Identifiable, ObservableObject { ) else { panels.removeValue(forKey: browserPanel.id) panelTitles.removeValue(forKey: browserPanel.id) + browserPanel.close() return nil } @@ -9540,6 +9463,9 @@ final class Workspace: Identifiable, ObservableObject { ) { guard !remoteTmuxMirrorMutations.suppressesFocusActivation else { return } markExplicitFocusIntent(on: panelId) + if let browserPanel = panels[panelId] as? BrowserPanel { + browserPanel.noteWebExtensionActivated() + } #if DEBUG let pane = bonsplitController.focusedPaneId?.id.uuidString.prefix(5) ?? "nil" let triggerLabel = trigger == .terminalFirstResponder ? "firstResponder" : "standard" @@ -11613,6 +11539,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/Sources/cmuxApp.swift b/Sources/cmuxApp.swift index b389b39df611..c3df3cea318c 100644 --- a/Sources/cmuxApp.swift +++ b/Sources/cmuxApp.swift @@ -187,7 +187,11 @@ struct cmuxApp: App { KeyboardShortcutSettings.settingsFileStore.applyDeferredManagedDefaultSideEffects() StartupBreadcrumbLog.append("app.init.keyboardShortcuts.sideEffectsApplied") StartupBreadcrumbLog.append("app.init.tabManager.begin") - _tabManager = StateObject(wrappedValue: TabManager()) + let browserWebExtensionHost = Self.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. if let stored = defaults.string(forKey: SocketControlSettings.appStorageKey) { @@ -226,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) @@ -1445,48 +1461,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", -] - -/// 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 a3f3a30f2daa..a3193241ee27 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 */; }; @@ -170,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 */; }; @@ -189,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 */; }; @@ -201,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 */; }; @@ -310,6 +314,25 @@ 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 */; }; + 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 */; }; + 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 */; }; + 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 */; }; + 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 */; }; 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 */; }; @@ -510,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 */; }; @@ -568,6 +592,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 */; }; @@ -1614,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 */; }; @@ -1865,6 +1891,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 = ""; }; @@ -1930,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 = ""; }; @@ -1948,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 = ""; }; @@ -1960,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 = ""; }; @@ -2069,6 +2099,25 @@ 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 = ""; }; + 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 = ""; }; + 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 = ""; }; + 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 = ""; }; + 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 = ""; }; 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 = ""; }; @@ -2243,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 = ""; }; @@ -2278,6 +2328,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 = ""; }; @@ -3302,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 = ""; }; @@ -3871,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 */, @@ -3991,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 */, @@ -4180,6 +4235,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 */, @@ -4284,6 +4340,25 @@ 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 */, + B1CFE0070000000000000002 /* BrowserWebExtensionSupport+Loading.swift */, + B1CFE0100000000000000002 /* BrowserWebExtensionSupport+Permissions.swift */, + B1CFE0090000000000000002 /* BrowserWebExtensionSupport+WKWebExtensionControllerDelegate.swift */, + B1CFE0060000000000000002 /* BrowserWebExtensionDiscoveryService.swift */, + B1CFE0050000000000000002 /* BrowserWebExtensionPopoutWindowController.swift */, + B1CFE0080000000000000002 /* BrowserWebExtensionHosting.swift */, + B1CFE00A0000000000000002 /* BrowserWebExtensionActionSnapshot.swift */, + B1CFE0110000000000000002 /* BrowserWebExtensionActionSnapshotInvalidation.swift */, + B1CFE00B0000000000000002 /* BrowserWebExtensionLoadedRecord.swift */, + B1CFE00D0000000000000002 /* BrowserWebExtensionNavigationConfiguration.swift */, + FADE00020000000000000002 /* BrowserExternalNavigationPolicy.swift */, + FADE00030000000000000002 /* BrowserDevToolsIconOptions.swift */, + B1CFE00E0000000000000002 /* BrowserWebExtensionPermissionState.swift */, + B1CFE00F0000000000000002 /* BrowserWebExtensionPermissionStateStore.swift */, + B1CFE00C0000000000000002 /* BrowserWebExtensionReconciliationPlanner.swift */, C67540100000000000000002 /* BrowserNavigationPopupPolicy.swift */, A5001412 /* BrowserPanel.swift */, B1F0C0090000000000000002 /* BrowserPanelDeveloperToolsLifecycle.swift */, @@ -4437,6 +4512,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 */, @@ -4916,6 +4992,8 @@ C0DE71B10000000000000002 /* AppDelegate+AgentChatNotifications.swift */ = {isa = B6585002B6585002B6585002 /* BrowserHiddenWebViewDiscardMemoryPressureTests.swift */, B75040020000000000000002 /* BrowserDiscardedWebViewRestoreRetryTests.swift */, B75040030000000000000002 /* BrowserDiscardRestoreHealPredicateTests.swift */, + B1CFE0200000000000000002 /* BrowserWebExtensionSupportTests.swift */, + B1CFE0210000000000000002 /* BrowserWebExtensionReviewRegressionTests.swift */, B75040040000000000000002 /* BrowserInsecureHTTPAlertTestSupport.swift */, B6585002B6585002B658PW02 /* BrowserPrewarmedWebViewPoolTests.swift */, 58C7B1B978620BE162CC057E /* BrowserPanelTests.swift */, @@ -5700,6 +5778,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 */, @@ -5739,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 */, @@ -5750,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 */, @@ -5759,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 */, @@ -5841,6 +5923,23 @@ 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 */, + B1CFE0110000000000000001 /* BrowserWebExtensionActionSnapshotInvalidation.swift in Sources */, + 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 */, + 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 */, @@ -5885,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 */, @@ -5909,6 +6009,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 */, @@ -6621,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 */, @@ -6892,6 +6994,8 @@ 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 */, 0A0F00560000000000000003 /* CampfireHookNotificationTests.swift in Sources */, 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/BrowserPrewarmedWebViewPoolTests.swift b/cmuxTests/BrowserPrewarmedWebViewPoolTests.swift index fc17786d4daa..05945f12b909 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,29 @@ private final class PrewarmPoolHarness { } } +@MainActor +private final class PrewarmTestWebExtensionHost: BrowserWebExtensionHosting { + private(set) var attachedConfigurationCount = 0 + + func attach(to configuration: WKWebViewConfiguration) { + attachedConfigurationCount += 1 + } + + func webViewConfiguration(forNavigatingTo url: URL) -> BrowserWebExtensionNavigationConfiguration? { + nil + } + + func register(panel: BrowserPanel) {} + + func unregister(panelID: UUID) {} + + func noteActivated(panelID: UUID) {} + + func noteTabMetadataChanged(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 +200,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) diff --git a/cmuxTests/BrowserWebExtensionReviewRegressionTests.swift b/cmuxTests/BrowserWebExtensionReviewRegressionTests.swift new file mode 100644 index 000000000000..e6fd30e2333a --- /dev/null +++ b/cmuxTests/BrowserWebExtensionReviewRegressionTests.swift @@ -0,0 +1,406 @@ +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 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) }) + + let adapter = support.openBrowserTab( + in: tabManager, + url: nil, + shouldActivate: false, + webViewConfiguration: nil + ) + + let panel = try #require(adapter?.panel) + #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 + @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)) + + 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 + 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 { + 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, *) + 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 + @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 + @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 +private final class BrowserWebExtensionReviewTestHost: BrowserWebExtensionHosting { + private let extensionHost: String? + private let contextToken = NSObject() + + 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 } + // 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: WKWebViewConfiguration() + ) + } + + func register(panel: BrowserPanel) {} + func unregister(panelID: UUID) {} + func noteActivated(panelID: UUID) {} + func noteTabMetadataChanged(panelID: UUID) {} + func performCommand(for event: NSEvent) -> Bool { false } +} diff --git a/cmuxTests/BrowserWebExtensionSupportTests.swift b/cmuxTests/BrowserWebExtensionSupportTests.swift new file mode 100644 index 000000000000..280697c35637 --- /dev/null +++ b/cmuxTests/BrowserWebExtensionSupportTests.swift @@ -0,0 +1,499 @@ +import AppKit +import CmuxSettings +import Foundation +import Testing +import WebKit + +#if canImport(cmux_DEV) +@testable import cmux_DEV +#elseif canImport(cmux) +@testable import cmux +#endif + +@Suite(.serialized) +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) + #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: firstWindow, among: [support.windowAdapter]) as AnyObject?) === support.windowAdapter) + #expect(support.focusedWebExtensionWindow(for: firstWindow, among: []) == nil) + } + + @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 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() + 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 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 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() + 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() + 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.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) + } + + @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 { + 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)) + } + + @MainActor + @Test + func extensionExitPreservesNilTargetNewTabIntent() { + let delegate = BrowserNavigationDelegate() + + #expect(!delegate.shouldRouteWebExtensionNavigationAsCurrentTab( + targetFrameIsMainFrame: nil, + shouldOpenInNewTab: false, + navigationType: .linkActivated + )) + #expect(!delegate.shouldRouteWebExtensionNavigationAsCurrentTab( + targetFrameIsMainFrame: nil, + shouldOpenInNewTab: false, + navigationType: .other + )) + #expect(delegate.shouldRouteWebExtensionNavigationAsCurrentTab( + targetFrameIsMainFrame: true, + shouldOpenInNewTab: false, + navigationType: .linkActivated + )) + } + + @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", standardizedPath: "/Extensions/First") + store.save(secondState, for: "com.example.second", standardizedPath: "/Extensions/Second") + + #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 + @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 { + 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", 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", standardizedPath: "/Extensions/First") == nil) + #expect(store.state(for: "com.example.second", standardizedPath: "/Extensions/Second") == secondState) + } + + @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") + } + + @Test + func pluginkitQueriesOnlyTheElectedExtensionVersion() { + #expect(BrowserWebExtensionDiscoveryService.pluginkitArguments == [ + "-m", + "-p", + "com.apple.Safari.web-extension", + "-v", + ]) + } +} + +@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 } +} 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",