From 1cf00714527438ac9e025a718b674796682e75ca Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Fri, 29 May 2026 13:07:32 -0500 Subject: [PATCH 01/44] feat: add sidebar ExtensionKit host --- Packages/CMUXExtensionClient/Package.swift | 30 + Packages/CMUXExtensionClient/README.md | 11 + .../CMUXExtensionClient.swift | 150 ++++ .../CMUXExtensionClientTests.swift | 71 ++ Packages/CmuxExtensionKit/README.md | 68 +- ...swift => CmuxExtensionCompatibility.swift} | 229 +++--- .../CmuxExtensionKit/CmuxExtensionKit.swift | 622 ++++----------- .../CmuxExtensionPathFormatter.swift | 20 - .../CmuxExtensionSidebarReducer.swift | 392 --------- .../CmuxExtensionKitTests.swift | 747 +----------------- Resources/Localizable.xcstrings | 103 +++ Sources/ContentView.swift | 99 ++- cmux.xcodeproj/project.pbxproj | 13 + 13 files changed, 803 insertions(+), 1752 deletions(-) create mode 100644 Packages/CMUXExtensionClient/Package.swift create mode 100644 Packages/CMUXExtensionClient/README.md create mode 100644 Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/CMUXExtensionClient.swift create mode 100644 Packages/CMUXExtensionClient/Tests/CMUXExtensionClientTests/CMUXExtensionClientTests.swift rename Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/{CmuxExtensionSidebarProvider.swift => CmuxExtensionCompatibility.swift} (65%) delete mode 100644 Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CmuxExtensionPathFormatter.swift delete mode 100644 Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CmuxExtensionSidebarReducer.swift diff --git a/Packages/CMUXExtensionClient/Package.swift b/Packages/CMUXExtensionClient/Package.swift new file mode 100644 index 000000000000..ebafc1a7e391 --- /dev/null +++ b/Packages/CMUXExtensionClient/Package.swift @@ -0,0 +1,30 @@ +// swift-tools-version: 6.0 +import PackageDescription + +let package = Package( + name: "CMUXExtensionClient", + platforms: [ + .macOS(.v14), + ], + products: [ + .library( + name: "CMUXExtensionClient", + targets: ["CMUXExtensionClient"] + ), + ], + dependencies: [ + .package(path: "../CmuxExtensionKit"), + ], + targets: [ + .target( + name: "CMUXExtensionClient", + dependencies: [ + .product(name: "CmuxExtensionKit", package: "CmuxExtensionKit"), + ] + ), + .testTarget( + name: "CMUXExtensionClientTests", + dependencies: ["CMUXExtensionClient"] + ), + ] +) diff --git a/Packages/CMUXExtensionClient/README.md b/Packages/CMUXExtensionClient/README.md new file mode 100644 index 000000000000..f5a14fae998b --- /dev/null +++ b/Packages/CMUXExtensionClient/README.md @@ -0,0 +1,11 @@ +# CMUX Extension Client + +`CMUXExtensionClient` is the host-side package for loading and driving CMUX sidebar extensions. + +This first slice contains: + +- manifest validation through `CmuxExtensionKit` +- a registry for available sidebar extensions +- a session actor that fetches snapshots and dispatches sidebar actions + +The package is ready for an ExtensionKit-backed adapter, but this branch keeps the first verified surface focused on the API and host lifecycle. Future work should add the real `EXHostViewController` bridge and third-party extension discovery. diff --git a/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/CMUXExtensionClient.swift b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/CMUXExtensionClient.swift new file mode 100644 index 000000000000..754d767ffc5b --- /dev/null +++ b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/CMUXExtensionClient.swift @@ -0,0 +1,150 @@ +import CmuxExtensionKit +import ExtensionFoundation +import ExtensionKit +import Foundation +import SwiftUI + +public enum CMUXSidebarExtensionPoint { + public static let identifier = "com.manaflow.cmux.sidebar" + public static let defaultSceneID = "sidebar" +} + +public struct CMUXSidebarExtensionRecord: Equatable, Identifiable, Sendable { + public var id: String { manifest.id } + public var manifest: CMUXExtensionManifest + public var isHostProvided: Bool + + public init(manifest: CMUXExtensionManifest, isHostProvided: Bool) { + self.manifest = manifest + self.isHostProvided = isHostProvided + } +} + +public enum CMUXExtensionClientError: Error, Equatable, Sendable { + case duplicateExtensionIdentifier(String) + case extensionNotFound(String) +} + +public struct CMUXSidebarExtensionRegistry: Sendable { + private var recordsByID: [String: CMUXSidebarExtensionRecord] + + public init(records: [CMUXSidebarExtensionRecord] = []) throws { + var recordsByID: [String: CMUXSidebarExtensionRecord] = [:] + for record in records { + try CMUXExtensionValidator.validateSidebarManifest(record.manifest) + if recordsByID[record.id] != nil { + throw CMUXExtensionClientError.duplicateExtensionIdentifier(record.id) + } + recordsByID[record.id] = record + } + self.recordsByID = recordsByID + } + + public var records: [CMUXSidebarExtensionRecord] { + recordsByID.values.sorted { $0.manifest.displayName < $1.manifest.displayName } + } + + public func record(id: String) throws -> CMUXSidebarExtensionRecord { + guard let record = recordsByID[id] else { + throw CMUXExtensionClientError.extensionNotFound(id) + } + return record + } +} + +public actor CMUXSidebarExtensionSession { + private let manifest: CMUXExtensionManifest + private let client: CMUXSidebarHostClient + private var latestSnapshot: CMUXSidebarSnapshot? + + public init(manifest: CMUXExtensionManifest, client: CMUXSidebarHostClient) throws { + try CMUXExtensionValidator.validateSidebarManifest(manifest) + self.manifest = manifest + self.client = client + } + + public func refreshSnapshot() async throws -> CMUXSidebarSnapshot { + let snapshot = try await client.snapshot() + latestSnapshot = snapshot + return snapshot + } + + public func perform(_ action: CMUXSidebarAction) async throws -> CMUXExtensionActionResult { + try await client.dispatch(action) + } + + public var extensionManifest: CMUXExtensionManifest { + manifest + } + + public func cachedSnapshot() -> CMUXSidebarSnapshot? { + latestSnapshot + } +} + +public struct CMUXInstalledSidebarExtension: Identifiable, Equatable, Sendable { + public var id: String { bundleIdentifier } + public var bundleIdentifier: String + public var localizedName: String + public var extensionPointIdentifier: String + + public init( + bundleIdentifier: String, + localizedName: String, + extensionPointIdentifier: String + ) { + self.bundleIdentifier = bundleIdentifier + self.localizedName = localizedName + self.extensionPointIdentifier = extensionPointIdentifier + } +} + +@available(macOS 14.0, *) +public struct CMUXSidebarExtensionDiscovery { + public init() {} + + public func installedExtensions( + extensionPointIdentifier: String = CMUXSidebarExtensionPoint.identifier + ) async throws -> [CMUXInstalledSidebarExtension] { + var identities = try AppExtensionIdentity.matching(appExtensionPointIDs: extensionPointIdentifier) + .makeAsyncIterator() + guard let update = await identities.next() else { return [] } + return update.map { + CMUXInstalledSidebarExtension( + bundleIdentifier: $0.bundleIdentifier, + localizedName: $0.localizedName, + extensionPointIdentifier: $0.extensionPointIdentifier + ) + } + .sorted { $0.localizedName < $1.localizedName } + } +} + +@available(macOS 14.0, *) +public struct CMUXSidebarExtensionHostView: NSViewControllerRepresentable { + public typealias NSViewControllerType = EXHostViewController + + private let identity: AppExtensionIdentity + private let sceneID: String + + public init(identity: AppExtensionIdentity, sceneID: String = CMUXSidebarExtensionPoint.defaultSceneID) { + self.identity = identity + self.sceneID = sceneID + } + + public func makeNSViewController(context: Context) -> EXHostViewController { + let viewController = EXHostViewController() + viewController.configuration = EXHostViewController.Configuration( + appExtension: identity, + sceneID: sceneID + ) + return viewController + } + + public func updateNSViewController(_ viewController: EXHostViewController, context: Context) { + viewController.configuration = EXHostViewController.Configuration( + appExtension: identity, + sceneID: sceneID + ) + } +} diff --git a/Packages/CMUXExtensionClient/Tests/CMUXExtensionClientTests/CMUXExtensionClientTests.swift b/Packages/CMUXExtensionClient/Tests/CMUXExtensionClientTests/CMUXExtensionClientTests.swift new file mode 100644 index 000000000000..7dbb7042d4a1 --- /dev/null +++ b/Packages/CMUXExtensionClient/Tests/CMUXExtensionClientTests/CMUXExtensionClientTests.swift @@ -0,0 +1,71 @@ +import CmuxExtensionKit +import XCTest +@testable import CMUXExtensionClient + +final class CMUXExtensionClientTests: XCTestCase { + func testRegistrySortsAndRejectsDuplicates() throws { + let first = CMUXSidebarExtensionRecord( + manifest: CMUXExtensionManifest(id: "b", displayName: "Browser Stack"), + isHostProvided: false + ) + let second = CMUXSidebarExtensionRecord( + manifest: CMUXExtensionManifest(id: "a", displayName: "Attention Queue"), + isHostProvided: false + ) + + let registry = try CMUXSidebarExtensionRegistry(records: [first, second]) + XCTAssertEqual(registry.records.map(\.id), ["a", "b"]) + + XCTAssertThrowsError(try CMUXSidebarExtensionRegistry(records: [first, first])) { error in + XCTAssertEqual(error as? CMUXExtensionClientError, .duplicateExtensionIdentifier("b")) + } + } + + func testSidebarExtensionPointUsesStablePublicIdentifiers() { + XCTAssertEqual(CMUXSidebarExtensionPoint.identifier, "com.manaflow.cmux.sidebar") + XCTAssertEqual(CMUXSidebarExtensionPoint.defaultSceneID, "sidebar") + } + + func testSessionRefreshesSnapshotAndDispatchesActions() async throws { + let workspaceID = UUID() + let snapshot = CMUXSidebarSnapshot( + sequence: 7, + selectedWorkspaceID: workspaceID, + workspaces: [CMUXSidebarWorkspace(id: workspaceID, title: "One")] + ) + let recorder = ActionRecorder() + let client = CMUXSidebarHostClient( + snapshot: { snapshot }, + dispatch: { action in + await recorder.append(action) + return .accepted + } + ) + let session = try CMUXSidebarExtensionSession( + manifest: CMUXExtensionManifest(id: "dev.example.sidebar", displayName: "Example"), + client: client + ) + + let refreshed = try await session.refreshSnapshot() + let result = try await session.perform(.selectWorkspace(workspaceID)) + + XCTAssertEqual(refreshed, snapshot) + let cached = await session.cachedSnapshot() + let actions = await recorder.actions() + XCTAssertEqual(cached, snapshot) + XCTAssertEqual(result, .accepted) + XCTAssertEqual(actions, [.selectWorkspace(workspaceID)]) + } +} + +private actor ActionRecorder { + private var storage: [CMUXSidebarAction] = [] + + func append(_ action: CMUXSidebarAction) { + storage.append(action) + } + + func actions() -> [CMUXSidebarAction] { + storage + } +} diff --git a/Packages/CmuxExtensionKit/README.md b/Packages/CmuxExtensionKit/README.md index 9afbdfe2cb40..3e03784856c2 100644 --- a/Packages/CmuxExtensionKit/README.md +++ b/Packages/CmuxExtensionKit/README.md @@ -1,64 +1,14 @@ -# CmuxExtensionKit +# CMUX Extension Kit -`CmuxExtensionKit` is the prototype API for custom cmux sidebars. A sidebar -provider is pure Swift code that receives a `CmuxExtensionSidebarSnapshot` and -returns a `CmuxExtensionSidebarRenderModel`. The host owns selection, popovers, -window presentation, and mutation dispatch. +`CmuxExtensionKit` is the zero-dependency public contract for CMUX sidebar extensions. -State sync has two parts: +Version 1 only supports sidebar extensions. The API exposes a stable workspace snapshot and a small action channel: -1. Bootstrap with `extension.sidebar.snapshot`. -2. Subscribe to `cmux events`. -3. If `CmuxExtensionSidebarReducer.requiresSnapshotReplacement(after:)` returns - `true`, fetch a fresh `extension.sidebar.snapshot`. Otherwise reduce frames - with `CmuxExtensionSidebarReducer.reduce(_:event:)`. +- read the current sidebar snapshot +- select a workspace +- close a workspace +- ask CMUX to open a URL -That keeps virtualized rows cheap: rows receive immutable render values and -closures, not workspace stores. +The snapshot intentionally starts small: workspace identity, title, detail text, paths, git branch, unread state, listening ports, and pull request URLs. It does not expose terminal buffers, shell history, environment variables, secrets, or arbitrary filesystem access. -```swift -import CmuxExtensionKit - -struct MySidebar: CmuxExtensionSidebarProvider { - let descriptor = CmuxExtensionSidebarProviderDescriptor( - id: "local.example.sidebar", - title: .init(key: "local.example.sidebar.title", defaultValue: "Example"), - subtitle: .init(key: "local.example.sidebar.subtitle", defaultValue: "Local"), - systemImageName: "folder", - isHostProvided: false - ) - - func render(snapshot: CmuxExtensionSidebarSnapshot) -> CmuxExtensionSidebarRenderModel { - let rows = snapshot.workspaces.map { workspace in - CmuxExtensionSidebarRenderRow( - id: workspace.id, - title: workspace.title, - workspaceId: workspace.id, - accessory: .inspector - ) - } - let section = CmuxExtensionSidebarRenderSection( - id: "workspaces", - treeSection: CmuxExtensionWorkspaceTreeSection( - id: "workspaces", - title: "Workspaces", - subtitle: nil, - systemImageName: "folder", - projectRootPath: nil, - workspaceIds: rows.map(\.workspaceId) - ), - rows: rows - ) - return CmuxExtensionSidebarRenderModel( - providerId: descriptor.id, - snapshotSequence: snapshot.sequence, - sections: [section] - ) - } -} -``` - -Rows can request host actions through `CmuxExtensionSidebarMutation`, including -workspace selection, worktree creation, persistent section reordering, and -opening popovers or windows. Extension-owned grouping state should be persisted -by the extension, for example in `~/.config/cmux/extensions//state.json`. +Host-side lifecycle, discovery, and display belong in `Packages/CMUXExtensionClient`. diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CmuxExtensionSidebarProvider.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CmuxExtensionCompatibility.swift similarity index 65% rename from Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CmuxExtensionSidebarProvider.swift rename to Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CmuxExtensionCompatibility.swift index 6b8d964d4af7..590c8bd13999 100644 --- a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CmuxExtensionSidebarProvider.swift +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CmuxExtensionCompatibility.swift @@ -1,50 +1,10 @@ import Foundation -public enum CmuxExtensionSidebarProviderID { - public static let defaultWorkspaces = "cmux.sidebar.default" -} - public enum CmuxExtensionSidebarPresentation: String, Codable, Equatable, Sendable { case tree case browserStack = "browser-stack" } -public struct CmuxExtensionSidebarProviderDescriptor: Identifiable, Codable, Equatable, Sendable { - public var id: String - public var title: CmuxExtensionLocalizedText - public var subtitle: CmuxExtensionLocalizedText? - public var systemImageName: String - public var isHostProvided: Bool - - public init( - id: String, - title: CmuxExtensionLocalizedText, - subtitle: CmuxExtensionLocalizedText?, - systemImageName: String, - isHostProvided: Bool - ) { - self.id = id - self.title = title - self.subtitle = subtitle - self.systemImageName = systemImageName - self.isHostProvided = isHostProvided - } - - public static let defaultWorkspaces = CmuxExtensionSidebarProviderDescriptor( - id: CmuxExtensionSidebarProviderID.defaultWorkspaces, - title: CmuxExtensionLocalizedText( - key: "sidebar.provider.default.title", - defaultValue: "Default Workspaces" - ), - subtitle: CmuxExtensionLocalizedText( - key: "sidebar.provider.default.subtitle", - defaultValue: "cmux" - ), - systemImageName: "list.bullet", - isHostProvided: true - ) -} - public struct CmuxExtensionWorkspaceTreeSection: Identifiable, Codable, Equatable, Sendable { public var id: String public var title: String @@ -79,38 +39,7 @@ public struct CmuxExtensionWorkspaceTreeSection: Identifiable, Codable, Equatabl public enum CmuxExtensionWorkspacePopoverTab: String, Codable, CaseIterable, Equatable, Sendable { case notes case browser - @available(*, deprecated, message: "Use browser. pullRequest decodes as browser for legacy payloads.") case pullRequest - - public static let allCases: [CmuxExtensionWorkspacePopoverTab] = [.notes, .browser] - - public init(from decoder: Decoder) throws { - let container = try decoder.singleValueContainer() - let value = try container.decode(String.self) - switch value { - case Self.notes.rawValue: - self = .notes - case Self.browser.rawValue, "pullRequest": - self = .browser - default: - throw DecodingError.dataCorruptedError( - in: container, - debugDescription: "Unknown workspace popover tab: \(value)" - ) - } - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.singleValueContainer() - switch self { - case .notes: - try container.encode(Self.notes.rawValue) - case .browser: - try container.encode(Self.browser.rawValue) - default: - try container.encode(Self.browser.rawValue) - } - } } public enum CmuxExtensionWorkspaceRowAccessoryKind: String, Codable, Equatable, Sendable { @@ -246,42 +175,6 @@ public struct CmuxExtensionSidebarRenderModel: Codable, Equatable, Sendable { self.sections = sections self.presentation = presentation } - - private enum CodingKeys: String, CodingKey { - case providerId - case snapshotSequence - case sections - case presentation - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - providerId = try container.decode(String.self, forKey: .providerId) - snapshotSequence = try container.decode(UInt64.self, forKey: .snapshotSequence) - sections = try container.decode([CmuxExtensionSidebarRenderSection].self, forKey: .sections) - presentation = try container.decodeIfPresent( - CmuxExtensionSidebarPresentation.self, - forKey: .presentation - ) ?? .tree - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - try container.encode(providerId, forKey: .providerId) - try container.encode(snapshotSequence, forKey: .snapshotSequence) - try container.encode(sections, forKey: .sections) - try container.encode(presentation, forKey: .presentation) - } -} - -public extension CmuxExtensionSidebarRenderModel { - var relativeTextDates: [Date] { - sections.flatMap { section in - section.rows.flatMap { row in - [row.subtitle?.relativeDate, row.trailingText?.relativeDate].compactMap { $0 } - } - } - } } public enum CmuxExtensionSidebarPresentationRequest: Codable, Equatable, Sendable { @@ -317,22 +210,20 @@ public enum CmuxExtensionSidebarMutation: Codable, Equatable, Sendable { case present(CmuxExtensionSidebarPresentationRequest) } +public struct CmuxExtensionCommandResult: Codable, Equatable, Sendable { + public var ok: Bool + + public init(ok: Bool) { + self.ok = ok + } +} + public struct CmuxExtensionSidebarRenderContext: Codable, Equatable, Sendable { public var now: Date public init(now: Date) { self.now = now } - - public static var current: CmuxExtensionSidebarRenderContext { - CmuxExtensionSidebarRenderContext(now: Date()) - } -} - -public protocol CmuxExtensionSidebarProvider: Sendable { - var descriptor: CmuxExtensionSidebarProviderDescriptor { get } - - func render(snapshot: CmuxExtensionSidebarSnapshot) -> CmuxExtensionSidebarRenderModel } public protocol CmuxExtensionSidebarContextualProvider: CmuxExtensionSidebarProvider { @@ -347,7 +238,109 @@ public protocol CmuxExtensionSidebarMutableProvider: CmuxExtensionSidebarContext } public extension CmuxExtensionSidebarProvider { - func render(snapshot: CmuxExtensionSidebarSnapshot, context: CmuxExtensionSidebarRenderContext) -> CmuxExtensionSidebarRenderModel { + func render(snapshot: CmuxExtensionSidebarSnapshot) -> CmuxExtensionSidebarRenderModel { + CmuxExtensionSidebarRenderModel( + providerId: descriptor.id, + snapshotSequence: snapshot.sequence, + sections: [] + ) + } + + func render( + snapshot: CmuxExtensionSidebarSnapshot, + context: CmuxExtensionSidebarRenderContext + ) -> CmuxExtensionSidebarRenderModel { render(snapshot: snapshot) } } + +public struct CmuxExtensionSidebarSnapshot: Codable, Equatable, Sendable { + public var sequence: UInt64 + public var selectedWorkspaceId: UUID? + public var workspaces: [CmuxExtensionWorkspaceSnapshot] + public var windowId: UUID? + + public init( + sequence: UInt64, + selectedWorkspaceId: UUID?, + workspaces: [CmuxExtensionWorkspaceSnapshot], + windowId: UUID? = nil + ) { + self.sequence = sequence + self.selectedWorkspaceId = selectedWorkspaceId + self.workspaces = workspaces + self.windowId = windowId + } + + public var workspaceIds: [UUID] { + workspaces.map(\.id) + } +} + +public struct CmuxExtensionGitBranchSnapshot: Codable, Equatable, Sendable { + public var branch: String + public var isDirty: Bool + + public init(branch: String, isDirty: Bool) { + self.branch = branch + self.isDirty = isDirty + } +} + +public struct CmuxExtensionWorkspaceSnapshot: Identifiable, Codable, Equatable, Sendable { + public var id: UUID + public var title: String + public var customDescription: String? + public var isPinned: Bool + public var rootPath: String? + public var projectRootPath: String? + public var branchSummary: String? + public var remoteDisplayTarget: String? + public var remoteConnectionState: String? + public var unreadCount: Int + public var latestNotificationText: String? + public var latestSubmittedMessage: String? + public var latestSubmittedAt: Date? + public var listeningPorts: [Int] + public var pullRequestURLs: [String] + public var panelDirectories: [String] + public var gitBranches: [CmuxExtensionGitBranchSnapshot] + + public init( + id: UUID, + title: String, + customDescription: String?, + isPinned: Bool, + rootPath: String?, + projectRootPath: String?, + branchSummary: String?, + remoteDisplayTarget: String?, + remoteConnectionState: String?, + unreadCount: Int, + latestNotificationText: String?, + latestSubmittedMessage: String? = nil, + latestSubmittedAt: Date? = nil, + listeningPorts: [Int], + pullRequestURLs: [String] = [], + panelDirectories: [String] = [], + gitBranches: [CmuxExtensionGitBranchSnapshot] = [] + ) { + self.id = id + self.title = title + self.customDescription = customDescription + self.isPinned = isPinned + self.rootPath = rootPath + self.projectRootPath = projectRootPath + self.branchSummary = branchSummary + self.remoteDisplayTarget = remoteDisplayTarget + self.remoteConnectionState = remoteConnectionState + self.unreadCount = unreadCount + self.latestNotificationText = latestNotificationText + self.latestSubmittedMessage = latestSubmittedMessage + self.latestSubmittedAt = latestSubmittedAt + self.listeningPorts = listeningPorts + self.pullRequestURLs = pullRequestURLs + self.panelDirectories = panelDirectories + self.gitBranches = gitBranches + } +} diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CmuxExtensionKit.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CmuxExtensionKit.swift index 210565d73d3b..9b4f8f97fd56 100644 --- a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CmuxExtensionKit.swift +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CmuxExtensionKit.swift @@ -1,516 +1,232 @@ import Foundation -private enum CmuxExtensionDateCoding { - static func iso8601Date(from string: String) -> Date? { - let fractional = formatter( - key: "cmux.extension.iso8601.fractional", - options: [.withInternetDateTime, .withFractionalSeconds] - ) - if let date = fractional.date(from: string) { - return date - } +public struct CMUXExtensionAPIVersion: Codable, Comparable, Equatable, Sendable { + public var major: Int + public var minor: Int - let plain = formatter( - key: "cmux.extension.iso8601.plain", - options: [.withInternetDateTime] - ) - return plain.date(from: string) + public init(major: Int, minor: Int) { + self.major = major + self.minor = minor } - static func iso8601String(from date: Date) -> String { - formatter( - key: "cmux.extension.iso8601.encode", - options: [.withInternetDateTime, .withFractionalSeconds] - ).string(from: date) - } + public static let sidebarV1 = CMUXExtensionAPIVersion(major: 1, minor: 0) - private static func formatter( - key: String, - options: ISO8601DateFormatter.Options - ) -> ISO8601DateFormatter { - let dictionary = Thread.current.threadDictionary - if let formatter = dictionary[key] as? ISO8601DateFormatter { - return formatter - } - let formatter = ISO8601DateFormatter() - formatter.formatOptions = options - dictionary[key] = formatter - return formatter + public static func < (lhs: CMUXExtensionAPIVersion, rhs: CMUXExtensionAPIVersion) -> Bool { + if lhs.major != rhs.major { return lhs.major < rhs.major } + return lhs.minor < rhs.minor } } -public struct CmuxExtensionLocalizedText: Codable, Equatable, Hashable, Sendable { - public var key: String - public var defaultValue: String - - public init(key: String, defaultValue: String) { - self.key = key - self.defaultValue = defaultValue - } +public enum CMUXExtensionKind: String, Codable, CaseIterable, Equatable, Sendable { + case sidebar } -public struct CmuxExtensionSidebarSnapshot: Codable, Equatable, Sendable { - public var sequence: UInt64 - public var windowId: UUID? - public var selectedWorkspaceId: UUID? - public var workspaces: [CmuxExtensionWorkspaceSnapshot] +public struct CMUXExtensionManifest: Codable, Equatable, Identifiable, Sendable { + public var id: String + public var displayName: String + public var kind: CMUXExtensionKind + public var minimumAPIVersion: CMUXExtensionAPIVersion + public var requestedScopes: [CMUXExtensionScope] public init( - sequence: UInt64, - selectedWorkspaceId: UUID?, - workspaces: [CmuxExtensionWorkspaceSnapshot], - windowId: UUID? = nil + id: String, + displayName: String, + kind: CMUXExtensionKind = .sidebar, + minimumAPIVersion: CMUXExtensionAPIVersion = .sidebarV1, + requestedScopes: [CMUXExtensionScope] = [.workspaceMetadata] ) { - self.sequence = sequence - self.windowId = windowId - self.selectedWorkspaceId = selectedWorkspaceId - self.workspaces = workspaces - } - - public var workspaceIds: [UUID] { - workspaces.map(\.id) - } - - private enum CodingKeys: String, CodingKey { - case sequence - case windowId - case selectedWorkspaceId - case workspaces - } - - private enum SocketCodingKeys: String, CodingKey { - case sequence - case seq - case windowId = "window_id" - case selectedWorkspaceId = "selected_workspace_id" - case workspaces - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - let socketContainer = try decoder.container(keyedBy: SocketCodingKeys.self) - sequence = try container.decodeIfPresent(UInt64.self, forKey: .sequence) - ?? socketContainer.decodeIfPresent(UInt64.self, forKey: .sequence) - ?? socketContainer.decodeIfPresent(UInt64.self, forKey: .seq) - ?? 0 - windowId = try container.decodeIfPresent(UUID.self, forKey: .windowId) - ?? socketContainer.decodeIfPresent(UUID.self, forKey: .windowId) - selectedWorkspaceId = try container.decodeIfPresent(UUID.self, forKey: .selectedWorkspaceId) - ?? socketContainer.decodeIfPresent(UUID.self, forKey: .selectedWorkspaceId) - workspaces = try container.decodeIfPresent([CmuxExtensionWorkspaceSnapshot].self, forKey: .workspaces) - ?? socketContainer.decodeIfPresent([CmuxExtensionWorkspaceSnapshot].self, forKey: .workspaces) - ?? [] - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - try container.encode(sequence, forKey: .sequence) - try container.encodeIfPresent(windowId, forKey: .windowId) - try container.encodeIfPresent(selectedWorkspaceId, forKey: .selectedWorkspaceId) - try container.encode(workspaces, forKey: .workspaces) + self.id = id + self.displayName = displayName + self.kind = kind + self.minimumAPIVersion = minimumAPIVersion + self.requestedScopes = requestedScopes } } -public enum CmuxExtensionJSONValue: Codable, Equatable, Sendable { - case null - case bool(Bool) - case number(Double) - case string(String) - case array([CmuxExtensionJSONValue]) - case object([String: CmuxExtensionJSONValue]) - - public init(from decoder: Decoder) throws { - let container = try decoder.singleValueContainer() - if container.decodeNil() { - self = .null - } else if let value = try? container.decode(Bool.self) { - self = .bool(value) - } else if let value = try? container.decode(Double.self) { - self = .number(value) - } else if let value = try? container.decode(String.self) { - self = .string(value) - } else if let value = try? container.decode([CmuxExtensionJSONValue].self) { - self = .array(value) - } else { - self = .object(try container.decode([String: CmuxExtensionJSONValue].self)) - } - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.singleValueContainer() - switch self { - case .null: - try container.encodeNil() - case .bool(let value): - try container.encode(value) - case .number(let value): - try container.encode(value) - case .string(let value): - try container.encode(value) - case .array(let value): - try container.encode(value) - case .object(let value): - try container.encode(value) - } - } - - public var stringValue: String? { - guard case .string(let value) = self else { return nil } - return value - } - - public var boolValue: Bool? { - guard case .bool(let value) = self else { return nil } - return value - } - - public var intValue: Int? { - switch self { - case .number(let value): - return Int(exactly: value) - case .string(let value): - return Int(value) - default: - return nil - } - } +public enum CMUXExtensionScope: String, Codable, CaseIterable, Equatable, Sendable { + case workspaceMetadata + case workspacePaths + case notifications + case networkPorts + case pullRequests } -public struct CmuxExtensionEventFrame: Codable, Equatable, Sendable { +public struct CMUXSidebarSnapshot: Codable, Equatable, Sendable { + public var apiVersion: CMUXExtensionAPIVersion public var sequence: UInt64 - public var name: String - public var category: String - public var source: String - public var occurredAt: Date - public var workspaceId: UUID? - public var surfaceId: UUID? - public var paneId: UUID? - public var windowId: UUID? - public var payload: [String: CmuxExtensionJSONValue] + public var windowID: UUID? + public var selectedWorkspaceID: UUID? + public var workspaces: [CMUXSidebarWorkspace] public init( + apiVersion: CMUXExtensionAPIVersion = .sidebarV1, sequence: UInt64, - name: String, - category: String, - source: String, - occurredAt: Date, - workspaceId: UUID?, - surfaceId: UUID? = nil, - paneId: UUID? = nil, - windowId: UUID? = nil, - payload: [String: CmuxExtensionJSONValue] = [:] + windowID: UUID? = nil, + selectedWorkspaceID: UUID?, + workspaces: [CMUXSidebarWorkspace] ) { + self.apiVersion = apiVersion self.sequence = sequence - self.name = name - self.category = category - self.source = source - self.occurredAt = occurredAt - self.workspaceId = workspaceId - self.surfaceId = surfaceId - self.paneId = paneId - self.windowId = windowId - self.payload = payload - } - - private enum CodingKeys: String, CodingKey { - case sequence = "seq" - case name - case category - case source - case occurredAt = "occurred_at" - case workspaceId = "workspace_id" - case surfaceId = "surface_id" - case paneId = "pane_id" - case windowId = "window_id" - case payload - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - sequence = try container.decode(UInt64.self, forKey: .sequence) - name = try container.decode(String.self, forKey: .name) - category = try container.decode(String.self, forKey: .category) - source = try container.decode(String.self, forKey: .source) - if let date = try? container.decode(Date.self, forKey: .occurredAt) { - occurredAt = date - } else { - let string = try container.decode(String.self, forKey: .occurredAt) - guard let date = CmuxExtensionDateCoding.iso8601Date(from: string) else { - throw DecodingError.dataCorruptedError( - forKey: .occurredAt, - in: container, - debugDescription: "Invalid ISO-8601 event timestamp." - ) - } - occurredAt = date - } - workspaceId = try container.decodeIfPresent(UUID.self, forKey: .workspaceId) - surfaceId = try container.decodeIfPresent(UUID.self, forKey: .surfaceId) - paneId = try container.decodeIfPresent(UUID.self, forKey: .paneId) - windowId = try container.decodeIfPresent(UUID.self, forKey: .windowId) - payload = try container.decodeIfPresent([String: CmuxExtensionJSONValue].self, forKey: .payload) ?? [:] - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - try container.encode(sequence, forKey: .sequence) - try container.encode(name, forKey: .name) - try container.encode(category, forKey: .category) - try container.encode(source, forKey: .source) - try container.encode(CmuxExtensionDateCoding.iso8601String(from: occurredAt), forKey: .occurredAt) - try container.encodeIfPresent(workspaceId, forKey: .workspaceId) - try container.encodeIfPresent(surfaceId, forKey: .surfaceId) - try container.encodeIfPresent(paneId, forKey: .paneId) - try container.encodeIfPresent(windowId, forKey: .windowId) - try container.encode(payload, forKey: .payload) - } -} - -public struct CmuxExtensionCommandResult: Codable, Equatable, Sendable { - public var ok: Bool - public var payload: [String: CmuxExtensionJSONValue] - - public init(ok: Bool, payload: [String: CmuxExtensionJSONValue] = [:]) { - self.ok = ok - self.payload = payload - } -} - -public struct CmuxClient: Sendable { - public var snapshot: @Sendable () async throws -> CmuxExtensionSidebarSnapshot - public var events: @Sendable (_ afterSequence: UInt64?) -> AsyncThrowingStream - public var dispatch: @Sendable (_ mutation: CmuxExtensionSidebarMutation) async throws -> CmuxExtensionCommandResult - - public init( - snapshot: @escaping @Sendable () async throws -> CmuxExtensionSidebarSnapshot, - events: @escaping @Sendable (_ afterSequence: UInt64?) -> AsyncThrowingStream, - dispatch: @escaping @Sendable (_ mutation: CmuxExtensionSidebarMutation) async throws -> CmuxExtensionCommandResult - ) { - self.snapshot = snapshot - self.events = events - self.dispatch = dispatch - } -} - -public struct CmuxExtensionGitBranchSnapshot: Codable, Equatable, Sendable { - public var branch: String - public var isDirty: Bool - - public init(branch: String, isDirty: Bool) { - self.branch = branch - self.isDirty = isDirty - } - - private enum CodingKeys: String, CodingKey { - case branch - case isDirty - } - - private enum SocketCodingKeys: String, CodingKey { - case branch - case isDirty = "dirty" - } - - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - let socketContainer = try decoder.container(keyedBy: SocketCodingKeys.self) - branch = try container.decodeIfPresent(String.self, forKey: .branch) - ?? socketContainer.decode(String.self, forKey: .branch) - isDirty = try container.decodeIfPresent(Bool.self, forKey: .isDirty) - ?? socketContainer.decodeIfPresent(Bool.self, forKey: .isDirty) - ?? false - } - - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - try container.encode(branch, forKey: .branch) - try container.encode(isDirty, forKey: .isDirty) + self.windowID = windowID + self.selectedWorkspaceID = selectedWorkspaceID + self.workspaces = workspaces } } -public struct CmuxExtensionWorkspaceSnapshot: Identifiable, Codable, Equatable, Sendable { +public struct CMUXSidebarWorkspace: Codable, Equatable, Identifiable, Sendable { public var id: UUID public var title: String - public var customDescription: String? + public var detail: String? public var isPinned: Bool public var rootPath: String? public var projectRootPath: String? - public var branchSummary: String? - public var remoteDisplayTarget: String? - public var remoteConnectionState: String? + public var gitBranch: String? public var unreadCount: Int - public var latestNotificationText: String? - public var latestSubmittedMessage: String? - public var latestSubmittedAt: Date? + public var latestNotification: String? public var listeningPorts: [Int] public var pullRequestURLs: [String] - public var panelDirectories: [String] - public var gitBranches: [CmuxExtensionGitBranchSnapshot] public init( id: UUID, title: String, - customDescription: String?, - isPinned: Bool, - rootPath: String?, - projectRootPath: String?, - branchSummary: String?, - remoteDisplayTarget: String?, - remoteConnectionState: String?, - unreadCount: Int, - latestNotificationText: String?, - latestSubmittedMessage: String? = nil, - latestSubmittedAt: Date? = nil, - listeningPorts: [Int], - pullRequestURLs: [String] = [], - panelDirectories: [String] = [], - gitBranches: [CmuxExtensionGitBranchSnapshot] = [] + detail: String? = nil, + isPinned: Bool = false, + rootPath: String? = nil, + projectRootPath: String? = nil, + gitBranch: String? = nil, + unreadCount: Int = 0, + latestNotification: String? = nil, + listeningPorts: [Int] = [], + pullRequestURLs: [String] = [] ) { self.id = id self.title = title - self.customDescription = customDescription + self.detail = detail self.isPinned = isPinned self.rootPath = rootPath self.projectRootPath = projectRootPath - self.branchSummary = branchSummary - self.remoteDisplayTarget = remoteDisplayTarget - self.remoteConnectionState = remoteConnectionState + self.gitBranch = gitBranch self.unreadCount = unreadCount - self.latestNotificationText = latestNotificationText - self.latestSubmittedMessage = latestSubmittedMessage - self.latestSubmittedAt = latestSubmittedAt + self.latestNotification = latestNotification self.listeningPorts = listeningPorts self.pullRequestURLs = pullRequestURLs - self.panelDirectories = panelDirectories - self.gitBranches = gitBranches } +} - private enum CodingKeys: String, CodingKey { - case id - case title - case customDescription - case isPinned - case rootPath - case projectRootPath - case branchSummary - case remoteDisplayTarget - case remoteConnectionState - case unreadCount - case latestNotificationText - case latestSubmittedMessage - case latestSubmittedAt - case listeningPorts - case pullRequestURLs - case panelDirectories - case gitBranches - } +public enum CMUXSidebarAction: Codable, Equatable, Sendable { + case selectWorkspace(UUID) + case closeWorkspace(UUID) + case openURL(String) +} + +public struct CMUXExtensionActionResult: Codable, Equatable, Sendable { + public var accepted: Bool + public var message: String? - private enum SocketCodingKeys: String, CodingKey { - case id - case title - case customDescription = "description" - case isPinned = "pinned" - case rootPath = "root_path" - case projectRootPath = "project_root_path" - case branchSummary = "branch_summary" - case remoteDisplayTarget = "remote_display_target" - case remoteConnectionState = "remote_connection_state" - case unreadCount = "unread_count" - case latestNotificationText = "latest_notification_text" - case latestSubmittedMessage = "latest_submitted_message" - case latestSubmittedAt = "latest_submitted_at" - case listeningPorts = "listening_ports" - case pullRequestURLs = "pull_request_urls" - case panelDirectories = "panel_directories" - case gitBranches = "git_branches" + public init(accepted: Bool, message: String? = nil) { + self.accepted = accepted + self.message = message } - public init(from decoder: Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - let socketContainer = try decoder.container(keyedBy: SocketCodingKeys.self) + public static let accepted = CMUXExtensionActionResult(accepted: true) +} - id = try container.decodeIfPresent(UUID.self, forKey: .id) - ?? socketContainer.decode(UUID.self, forKey: .id) - title = try container.decodeIfPresent(String.self, forKey: .title) - ?? socketContainer.decode(String.self, forKey: .title) - customDescription = try container.decodeIfPresent(String.self, forKey: .customDescription) - ?? socketContainer.decodeIfPresent(String.self, forKey: .customDescription) - isPinned = try container.decodeIfPresent(Bool.self, forKey: .isPinned) - ?? socketContainer.decodeIfPresent(Bool.self, forKey: .isPinned) - ?? false - rootPath = try container.decodeIfPresent(String.self, forKey: .rootPath) - ?? socketContainer.decodeIfPresent(String.self, forKey: .rootPath) - projectRootPath = try container.decodeIfPresent(String.self, forKey: .projectRootPath) - ?? socketContainer.decodeIfPresent(String.self, forKey: .projectRootPath) - branchSummary = try container.decodeIfPresent(String.self, forKey: .branchSummary) - ?? socketContainer.decodeIfPresent(String.self, forKey: .branchSummary) - remoteDisplayTarget = try container.decodeIfPresent(String.self, forKey: .remoteDisplayTarget) - ?? socketContainer.decodeIfPresent(String.self, forKey: .remoteDisplayTarget) - remoteConnectionState = try container.decodeIfPresent(String.self, forKey: .remoteConnectionState) - ?? socketContainer.decodeIfPresent(String.self, forKey: .remoteConnectionState) - unreadCount = try container.decodeIfPresent(Int.self, forKey: .unreadCount) - ?? socketContainer.decodeIfPresent(Int.self, forKey: .unreadCount) - ?? 0 - latestNotificationText = try container.decodeIfPresent(String.self, forKey: .latestNotificationText) - ?? socketContainer.decodeIfPresent(String.self, forKey: .latestNotificationText) - latestSubmittedMessage = try container.decodeIfPresent(String.self, forKey: .latestSubmittedMessage) - ?? socketContainer.decodeIfPresent(String.self, forKey: .latestSubmittedMessage) - latestSubmittedAt = try Self.decodeDate( - container: container, - camelKey: .latestSubmittedAt, - socketContainer: socketContainer, - socketKey: .latestSubmittedAt - ) - listeningPorts = try container.decodeIfPresent([Int].self, forKey: .listeningPorts) - ?? socketContainer.decodeIfPresent([Int].self, forKey: .listeningPorts) - ?? [] - pullRequestURLs = try container.decodeIfPresent([String].self, forKey: .pullRequestURLs) - ?? socketContainer.decodeIfPresent([String].self, forKey: .pullRequestURLs) - ?? [] - panelDirectories = try container.decodeIfPresent([String].self, forKey: .panelDirectories) - ?? socketContainer.decodeIfPresent([String].self, forKey: .panelDirectories) - ?? [] - gitBranches = try container.decodeIfPresent([CmuxExtensionGitBranchSnapshot].self, forKey: .gitBranches) - ?? socketContainer.decodeIfPresent([CmuxExtensionGitBranchSnapshot].self, forKey: .gitBranches) - ?? [] - } +public protocol CMUXSidebarExtension: Sendable { + var manifest: CMUXExtensionManifest { get } + + func makeInitialSnapshot() async throws -> CMUXSidebarSnapshot + func handle(_ action: CMUXSidebarAction) async throws -> CMUXExtensionActionResult +} - public func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - try container.encode(id, forKey: .id) - try container.encode(title, forKey: .title) - try container.encodeIfPresent(customDescription, forKey: .customDescription) - try container.encode(isPinned, forKey: .isPinned) - try container.encodeIfPresent(rootPath, forKey: .rootPath) - try container.encodeIfPresent(projectRootPath, forKey: .projectRootPath) - try container.encodeIfPresent(branchSummary, forKey: .branchSummary) - try container.encodeIfPresent(remoteDisplayTarget, forKey: .remoteDisplayTarget) - try container.encodeIfPresent(remoteConnectionState, forKey: .remoteConnectionState) - try container.encode(unreadCount, forKey: .unreadCount) - try container.encodeIfPresent(latestNotificationText, forKey: .latestNotificationText) - try container.encodeIfPresent(latestSubmittedMessage, forKey: .latestSubmittedMessage) - try container.encodeIfPresent(latestSubmittedAt, forKey: .latestSubmittedAt) - try container.encode(listeningPorts, forKey: .listeningPorts) - try container.encode(pullRequestURLs, forKey: .pullRequestURLs) - try container.encode(panelDirectories, forKey: .panelDirectories) - try container.encode(gitBranches, forKey: .gitBranches) +public struct CMUXSidebarHostClient: Sendable { + public var snapshot: @Sendable () async throws -> CMUXSidebarSnapshot + public var dispatch: @Sendable (CMUXSidebarAction) async throws -> CMUXExtensionActionResult + + public init( + snapshot: @escaping @Sendable () async throws -> CMUXSidebarSnapshot, + dispatch: @escaping @Sendable (CMUXSidebarAction) async throws -> CMUXExtensionActionResult + ) { + self.snapshot = snapshot + self.dispatch = dispatch } +} - private static func decodeDate( - container: KeyedDecodingContainer, - camelKey: CodingKeys, - socketContainer: KeyedDecodingContainer, - socketKey: SocketCodingKeys - ) throws -> Date? { - if let date = try container.decodeIfPresent(Date.self, forKey: camelKey) { - return date +public enum CMUXExtensionValidationError: Error, Equatable, Sendable { + case unsupportedKind(CMUXExtensionKind) + case unsupportedMajorVersion(requested: Int, supported: Int) + case emptyIdentifier + case emptyDisplayName +} + +public enum CMUXExtensionValidator { + public static func validateSidebarManifest( + _ manifest: CMUXExtensionManifest, + supportedAPIVersion: CMUXExtensionAPIVersion = .sidebarV1 + ) throws { + guard manifest.id.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == false else { + throw CMUXExtensionValidationError.emptyIdentifier + } + guard manifest.displayName.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == false else { + throw CMUXExtensionValidationError.emptyDisplayName } - if let date = try? socketContainer.decodeIfPresent(Date.self, forKey: socketKey) { - return date + guard manifest.kind == .sidebar else { + throw CMUXExtensionValidationError.unsupportedKind(manifest.kind) } - guard let string = try socketContainer.decodeIfPresent(String.self, forKey: socketKey) else { - return nil + guard manifest.minimumAPIVersion.major == supportedAPIVersion.major else { + throw CMUXExtensionValidationError.unsupportedMajorVersion( + requested: manifest.minimumAPIVersion.major, + supported: supportedAPIVersion.major + ) } - return CmuxExtensionDateCoding.iso8601Date(from: string) } } + +// Compatibility names used only by the existing cmux app while the old prototype +// sidebar is removed in smaller follow-up steps. +public enum CmuxExtensionSidebarProviderID { + public static let defaultWorkspaces = "cmux.sidebar.default" +} + +public struct CmuxExtensionLocalizedText: Codable, Equatable, Hashable, Sendable { + public var key: String + public var defaultValue: String + + public init(key: String, defaultValue: String) { + self.key = key + self.defaultValue = defaultValue + } +} + +public struct CmuxExtensionSidebarProviderDescriptor: Identifiable, Codable, Equatable, Sendable { + public var id: String + public var title: CmuxExtensionLocalizedText + public var subtitle: CmuxExtensionLocalizedText? + public var systemImageName: String + public var isHostProvided: Bool + + public init( + id: String, + title: CmuxExtensionLocalizedText, + subtitle: CmuxExtensionLocalizedText? = nil, + systemImageName: String, + isHostProvided: Bool + ) { + self.id = id + self.title = title + self.subtitle = subtitle + self.systemImageName = systemImageName + self.isHostProvided = isHostProvided + } + + public static let defaultWorkspaces = CmuxExtensionSidebarProviderDescriptor( + id: CmuxExtensionSidebarProviderID.defaultWorkspaces, + title: CmuxExtensionLocalizedText(key: "sidebar.provider.default.title", defaultValue: "Default Workspaces"), + subtitle: CmuxExtensionLocalizedText(key: "sidebar.provider.default.subtitle", defaultValue: "cmux"), + systemImageName: "list.bullet", + isHostProvided: true + ) +} + +public protocol CmuxExtensionSidebarProvider: Sendable { + var descriptor: CmuxExtensionSidebarProviderDescriptor { get } +} diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CmuxExtensionPathFormatter.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CmuxExtensionPathFormatter.swift deleted file mode 100644 index 7bd8548d0490..000000000000 --- a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CmuxExtensionPathFormatter.swift +++ /dev/null @@ -1,20 +0,0 @@ -import Foundation - -public enum CmuxExtensionPathFormatter { - public static let homeDirectoryPath: String = FileManager.default.homeDirectoryForCurrentUser.path - - public static func shortenedPath( - _ path: String, - homeDirectoryPath: String = Self.homeDirectoryPath - ) -> String { - let trimmed = path.trimmingCharacters(in: .whitespacesAndNewlines) - guard !trimmed.isEmpty else { return path } - if trimmed == homeDirectoryPath { - return "~" - } - if trimmed.hasPrefix(homeDirectoryPath + "/") { - return "~" + trimmed.dropFirst(homeDirectoryPath.count) - } - return trimmed - } -} diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CmuxExtensionSidebarReducer.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CmuxExtensionSidebarReducer.swift deleted file mode 100644 index 39e3094670c5..000000000000 --- a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CmuxExtensionSidebarReducer.swift +++ /dev/null @@ -1,392 +0,0 @@ -import Foundation - -public enum CmuxExtensionSidebarEvent: Codable, Equatable, Sendable { - case snapshotReplaced(CmuxExtensionSidebarSnapshot) - case workspaceUpserted(CmuxExtensionWorkspaceSnapshot) - case workspaceRemoved(UUID) - case workspacesReordered([UUID]) - case workspaceSelected(UUID?) -} - -public struct CmuxExtensionSidebarReducer { - public static func requiresSnapshotReplacement(after frame: CmuxExtensionEventFrame) -> Bool { - switch frame.name { - case "notification.created": - return redactedFields(from: frame.payload).contains { field in - field == "title" || field == "subtitle" || field == "body" - } - - case "workspace.created", "workspace.moved": - return true - - case "notification.read", "notification.cleared", "notification.removed": - return true - - case "workspace.action": - return true - - default: - return frame.name.hasPrefix("sidebar.") - } - } - - public static func reduce( - _ snapshot: CmuxExtensionSidebarSnapshot, - event: CmuxExtensionSidebarEvent - ) -> CmuxExtensionSidebarSnapshot { - switch event { - case .snapshotReplaced(let replacement): - return replacement - - case .workspaceUpserted(let workspace): - var workspaces = snapshot.workspaces - if let index = workspaces.firstIndex(where: { $0.id == workspace.id }) { - workspaces[index] = workspace - } else { - workspaces.append(workspace) - } - return CmuxExtensionSidebarSnapshot( - sequence: snapshot.sequence + 1, - selectedWorkspaceId: snapshot.selectedWorkspaceId, - workspaces: workspaces, - windowId: snapshot.windowId - ) - - case .workspaceRemoved(let id): - let workspaces = snapshot.workspaces.filter { $0.id != id } - return CmuxExtensionSidebarSnapshot( - sequence: snapshot.sequence + 1, - selectedWorkspaceId: snapshot.selectedWorkspaceId == id ? nil : snapshot.selectedWorkspaceId, - workspaces: workspaces, - windowId: snapshot.windowId - ) - - case .workspacesReordered(let ids): - var orderedIds: [UUID] = [] - var seenIds: Set = [] - for id in ids where seenIds.insert(id).inserted { - orderedIds.append(id) - } - let workspacesById = Dictionary( - snapshot.workspaces.map { ($0.id, $0) }, - uniquingKeysWith: { _, replacement in replacement } - ) - let orderedSet = Set(orderedIds) - var known = orderedIds.compactMap { workspacesById[$0] } - known.append(contentsOf: snapshot.workspaces.filter { !orderedSet.contains($0.id) }) - return CmuxExtensionSidebarSnapshot( - sequence: snapshot.sequence + 1, - selectedWorkspaceId: snapshot.selectedWorkspaceId, - workspaces: known, - windowId: snapshot.windowId - ) - - case .workspaceSelected(let id): - return CmuxExtensionSidebarSnapshot( - sequence: snapshot.sequence + 1, - selectedWorkspaceId: id, - workspaces: snapshot.workspaces, - windowId: snapshot.windowId - ) - } - } - - public static func reduce( - _ snapshot: CmuxExtensionSidebarSnapshot, - event frame: CmuxExtensionEventFrame - ) -> CmuxExtensionSidebarSnapshot { - guard frame.sequence > snapshot.sequence else { return snapshot } - var next = snapshot - next.sequence = frame.sequence - - switch frame.name { - case "workspace.created": - guard let workspaceId = resolvedWorkspaceId(frame), - !next.workspaces.contains(where: { $0.id == workspaceId }) else { - return next - } - let title = frame.payload["title"]?.stringValue - ?? frame.payload["custom_title"]?.stringValue - ?? "Workspace" - let workspace = CmuxExtensionWorkspaceSnapshot( - id: workspaceId, - title: title, - customDescription: nil, - isPinned: false, - rootPath: frame.payload["cwd"]?.stringValue ?? frame.payload["root_path"]?.stringValue, - projectRootPath: frame.payload["project_root_path"]?.stringValue, - branchSummary: nil, - remoteDisplayTarget: nil, - remoteConnectionState: nil, - unreadCount: 0, - latestNotificationText: nil, - listeningPorts: [] - ) - let insertionIndex = min(max(frame.payload["index"]?.intValue ?? next.workspaces.count, 0), next.workspaces.count) - next.workspaces.insert(workspace, at: insertionIndex) - if frame.payload["selected"]?.boolValue == true { - next.selectedWorkspaceId = workspaceId - } - - case "workspace.closed": - guard let workspaceId = resolvedWorkspaceId(frame) else { return next } - next.workspaces.removeAll { $0.id == workspaceId } - if next.selectedWorkspaceId == workspaceId { - next.selectedWorkspaceId = nil - } - - case "workspace.selected": - if let workspaceId = resolvedWorkspaceId(frame) { - guard next.workspaces.contains(where: { $0.id == workspaceId }) else { - return next - } - next.selectedWorkspaceId = workspaceId - } else { - next.selectedWorkspaceId = nil - } - - case "workspace.renamed": - guard let workspaceId = resolvedWorkspaceId(frame), - let index = next.workspaces.firstIndex(where: { $0.id == workspaceId }), - let title = renamedWorkspaceTitle(from: frame.payload) else { - return next - } - next.workspaces[index].title = title - - case "workspace.reordered": - let pinnedIds = reorderedPinnedWorkspaceIds(from: frame.payload) - var didApplyLocalReorder = false - if let order = reorderedWorkspaceIds(from: frame.payload) { - var orderedIds: [UUID] = [] - var seenIds: Set = [] - for id in order where seenIds.insert(id).inserted { - orderedIds.append(id) - } - let workspacesById = Dictionary( - next.workspaces.map { ($0.id, $0) }, - uniquingKeysWith: { _, replacement in replacement } - ) - let orderedSet = Set(orderedIds) - var known: [CmuxExtensionWorkspaceSnapshot] = [] - for id in orderedIds { - guard let workspace = workspacesById[id] else { continue } - didApplyLocalReorder = true - known.append(workspace) - } - known.append(contentsOf: next.workspaces.filter { !orderedSet.contains($0.id) }) - next.workspaces = known - } else if let workspaceId = resolvedWorkspaceId(frame), - let index = reorderedWorkspaceIndex(from: frame.payload), - let workspaces = movingWorkspace(next.workspaces, workspaceId: workspaceId, toIndex: index) { - next.workspaces = workspaces - didApplyLocalReorder = true - } - if let pinnedIds, didApplyLocalReorder { - let pinnedSet = Set(pinnedIds) - for index in next.workspaces.indices { - next.workspaces[index].isPinned = pinnedSet.contains(next.workspaces[index].id) - } - } - - case "workspace.prompt.submitted": - guard let workspaceId = resolvedWorkspaceId(frame), - let index = next.workspaces.firstIndex(where: { $0.id == workspaceId }) else { - return next - } - let message = frame.payload["message_preview"]?.stringValue - ?? frame.payload["prompt"]?.stringValue - ?? frame.payload["message"]?.stringValue - guard let prompt = normalizedPrompt(message) else { return next } - next.workspaces[index].latestSubmittedMessage = prompt - next.workspaces[index].latestSubmittedAt = frame.occurredAt - - case "notification.created": - guard let workspaceId = resolvedWorkspaceId(frame), - let index = next.workspaces.firstIndex(where: { $0.id == workspaceId }) else { - return next - } - let isRead = frame.payload["is_read"]?.boolValue ?? false - if !isRead { - next.workspaces[index].unreadCount += 1 - } - next.workspaces[index].latestNotificationText = notificationText(from: frame.payload) - - case "notification.read", "notification.cleared": - guard let workspaceId = resolvedWorkspaceId(frame), - let index = next.workspaces.firstIndex(where: { $0.id == workspaceId }) else { - return next - } - let nextUnreadCount = max(0, next.workspaces[index].unreadCount - notificationCount(from: frame.payload)) - next.workspaces[index].unreadCount = nextUnreadCount - if nextUnreadCount == 0 { - next.workspaces[index].latestNotificationText = nil - } - - case "notification.removed": - guard let workspaceId = resolvedWorkspaceId(frame), - let index = next.workspaces.firstIndex(where: { $0.id == workspaceId }) else { - return next - } - let wasRead = frame.payload["is_read"]?.boolValue ?? false - if !wasRead { - next.workspaces[index].unreadCount = max(0, next.workspaces[index].unreadCount - 1) - } - if next.workspaces[index].unreadCount == 0 - || notificationText(from: frame.payload) == next.workspaces[index].latestNotificationText { - next.workspaces[index].latestNotificationText = nil - } - - default: - break - } - - return next - } - - private static func resolvedWorkspaceId(_ frame: CmuxExtensionEventFrame) -> UUID? { - frame.workspaceId - ?? frame.payload["workspace_id"]?.uuidValue - ?? frame.payload["id"]?.uuidValue - } - - private static func normalizedPrompt(_ value: String?) -> String? { - guard let value else { return nil } - let collapsed = value - .split(whereSeparator: { $0.isWhitespace }) - .joined(separator: " ") - .trimmingCharacters(in: .whitespacesAndNewlines) - return collapsed.isEmpty ? nil : collapsed - } - - private static func reorderedWorkspaceIds(from payload: [String: CmuxExtensionJSONValue]) -> [UUID]? { - if let ids = payload["workspace_ids"]?.uuidArrayValue - ?? payload["order"]?.uuidArrayValue - ?? payload["ids"]?.uuidArrayValue { - return ids - } - if let result = payload["result"]?.objectValue, - let ids = reorderedWorkspaceIds(from: result) { - return ids - } - if let params = payload["params"]?.objectValue, - let ids = reorderedWorkspaceIds(from: params) { - return ids - } - return nil - } - - private static func reorderedPinnedWorkspaceIds(from payload: [String: CmuxExtensionJSONValue]) -> [UUID]? { - if let ids = payload["pinned_workspace_ids"]?.uuidArrayValue - ?? payload["pinned_ids"]?.uuidArrayValue { - return ids - } - if let result = payload["result"]?.objectValue, - let ids = reorderedPinnedWorkspaceIds(from: result) { - return ids - } - if let params = payload["params"]?.objectValue, - let ids = reorderedPinnedWorkspaceIds(from: params) { - return ids - } - return nil - } - - private static func reorderedWorkspaceIndex(from payload: [String: CmuxExtensionJSONValue]) -> Int? { - if let index = payload["index"]?.intValue { - return index - } - if let result = payload["result"]?.objectValue, - let index = reorderedWorkspaceIndex(from: result) { - return index - } - if let params = payload["params"]?.objectValue, - let index = reorderedWorkspaceIndex(from: params) { - return index - } - return nil - } - - private static func movingWorkspace( - _ workspaces: [CmuxExtensionWorkspaceSnapshot], - workspaceId: UUID, - toIndex index: Int - ) -> [CmuxExtensionWorkspaceSnapshot]? { - var next = workspaces - guard let sourceIndex = next.firstIndex(where: { $0.id == workspaceId }) else { return nil } - let workspace = next.remove(at: sourceIndex) - let insertionIndex = min(max(index, 0), next.count) - next.insert(workspace, at: insertionIndex) - return next - } - - private static func renamedWorkspaceTitle(from payload: [String: CmuxExtensionJSONValue]) -> String? { - if let title = payload["title"]?.stringValue { - return title - } - if let title = payload["custom_title"]?.stringValue { - return title - } - - let result = payload["result"]?.objectValue - if let title = result?["title"]?.stringValue { - return title - } - if let title = result?["custom_title"]?.stringValue { - return title - } - - let params = payload["params"]?.objectValue - if let title = params?["title"]?.stringValue { - return title - } - return params?["custom_title"]?.stringValue - } - - private static func notificationText(from payload: [String: CmuxExtensionJSONValue]) -> String? { - normalizedPrompt(payload["body"]?.stringValue) - ?? normalizedPrompt(payload["title"]?.stringValue) - ?? normalizedPrompt(payload["subtitle"]?.stringValue) - } - - private static func notificationCount(from payload: [String: CmuxExtensionJSONValue]) -> Int { - if let count = payload["count"]?.intValue { - return max(0, count) - } - if let ids = payload["notification_ids"]?.arrayValue { - return ids.count - } - return 1 - } - - private static func redactedFields(from payload: [String: CmuxExtensionJSONValue]) -> Set { - Set(payload["redacted_fields"]?.stringArrayValue ?? []) - } -} - -private extension CmuxExtensionJSONValue { - var objectValue: [String: CmuxExtensionJSONValue]? { - guard case .object(let value) = self else { return nil } - return value - } - - var arrayValue: [CmuxExtensionJSONValue]? { - guard case .array(let value) = self else { return nil } - return value - } - - var stringArrayValue: [String]? { - guard let values = arrayValue else { return nil } - let strings = values.compactMap(\.stringValue) - return strings.count == values.count ? strings : nil - } - - var uuidValue: UUID? { - stringValue.flatMap(UUID.init(uuidString:)) - } - - var uuidArrayValue: [UUID]? { - guard let values = arrayValue else { return nil } - let ids = values.compactMap(\.uuidValue) - return ids.count == values.count ? ids : nil - } -} diff --git a/Packages/CmuxExtensionKit/Tests/CmuxExtensionKitTests/CmuxExtensionKitTests.swift b/Packages/CmuxExtensionKit/Tests/CmuxExtensionKitTests/CmuxExtensionKitTests.swift index 18cf7762da0a..3218bf361a6a 100644 --- a/Packages/CmuxExtensionKit/Tests/CmuxExtensionKitTests/CmuxExtensionKitTests.swift +++ b/Packages/CmuxExtensionKit/Tests/CmuxExtensionKitTests/CmuxExtensionKitTests.swift @@ -1,722 +1,59 @@ import XCTest @testable import CmuxExtensionKit -final class CmuxExtensionKitTests: XCTestCase { - func testDefaultProviderDescriptorIsStable() { - XCTAssertEqual(CmuxExtensionSidebarProviderDescriptor.defaultWorkspaces.id, "cmux.sidebar.default") - XCTAssertEqual(CmuxExtensionSidebarProviderDescriptor.defaultWorkspaces.isHostProvided, true) - } - - func testPresentationRequestCodableRoundTrips() throws { - let workspaceId = UUID() - let request = CmuxExtensionSidebarPresentationRequest.openWorkspaceWindow( - workspaceId: workspaceId, - preferredTab: .browser - ) - - let data = try JSONEncoder().encode(request) - let decoded = try JSONDecoder().decode(CmuxExtensionSidebarPresentationRequest.self, from: data) - - XCTAssertEqual(decoded, request) - } - - func testWorkspacePopoverTabRoundTripsActiveCases() throws { - for tab in [CmuxExtensionWorkspacePopoverTab.notes, .browser] { - let data = try JSONEncoder().encode(tab) - let decoded = try JSONDecoder().decode(CmuxExtensionWorkspacePopoverTab.self, from: data) - - XCTAssertEqual(decoded, tab) - } - } - - func testJSONValueIntValueReturnsNilForOutOfRangeNumber() { - XCTAssertEqual(CmuxExtensionJSONValue.number(42).intValue, 42) - XCTAssertNil(CmuxExtensionJSONValue.number(1.5).intValue) - XCTAssertNil(CmuxExtensionJSONValue.number(Double(Int.max)).intValue) - XCTAssertNil(CmuxExtensionJSONValue.number(Double.greatestFiniteMagnitude).intValue) - } - - func testEventFrameDecodesSocketTimestamp() throws { - let workspaceId = UUID() - let data = Data(""" - { - "seq": 12, - "name": "workspace.selected", - "category": "workspace", - "source": "workspace.lifecycle", - "occurred_at": "2026-05-21T10:00:00.123Z", - "workspace_id": "\(workspaceId.uuidString)", - "payload": {"workspace_id": "\(workspaceId.uuidString)"} - } - """.utf8) - - let event = try JSONDecoder().decode(CmuxExtensionEventFrame.self, from: data) - - XCTAssertEqual(event.sequence, 12) - XCTAssertEqual(event.workspaceId, workspaceId) - XCTAssertEqual(event.payload["workspace_id"]?.stringValue, workspaceId.uuidString) - XCTAssertEqual(event.occurredAt.timeIntervalSince1970, 1_779_357_600.123, accuracy: 0.001) - } - - func testSidebarSnapshotDecodesSocketShape() throws { - let windowId = UUID() - let workspaceId = UUID() - let selectedId = workspaceId.uuidString - let data = Data(""" - { - "seq": 7, - "window_id": "\(windowId.uuidString)", - "selected_workspace_id": "\(selectedId)", - "workspaces": [ - { - "id": "\(workspaceId.uuidString)", - "title": "API", - "description": "Backend workspace", - "pinned": true, - "root_path": "/tmp/cmux/api", - "project_root_path": "/tmp/cmux", - "branch_summary": "main", - "remote_display_target": "devbox", - "remote_connection_state": "connected", - "unread_count": 3, - "latest_notification_text": "done", - "latest_submitted_message": "ship", - "latest_submitted_at": "2026-05-21T10:00:00.000Z", - "listening_ports": [3000], - "pull_request_urls": ["https://github.com/manaflow-ai/cmux/pull/4309"], - "panel_directories": ["/tmp/cmux/api", "/tmp/cmux/web"], - "git_branches": [ - {"branch": "main", "dirty": true}, - {"branch": "feature", "dirty": false} - ] - } - ] - } - """.utf8) - - let snapshot = try JSONDecoder().decode(CmuxExtensionSidebarSnapshot.self, from: data) - let workspace = try XCTUnwrap(snapshot.workspaces.first) - - XCTAssertEqual(snapshot.sequence, 7) - XCTAssertEqual(snapshot.windowId, windowId) - XCTAssertEqual(snapshot.selectedWorkspaceId, workspaceId) - XCTAssertEqual(workspace.id, workspaceId) - XCTAssertEqual(workspace.title, "API") - XCTAssertEqual(workspace.customDescription, "Backend workspace") - XCTAssertEqual(workspace.isPinned, true) - XCTAssertEqual(workspace.rootPath, "/tmp/cmux/api") - XCTAssertEqual(workspace.projectRootPath, "/tmp/cmux") - XCTAssertEqual(workspace.branchSummary, "main") - XCTAssertEqual(workspace.remoteDisplayTarget, "devbox") - XCTAssertEqual(workspace.remoteConnectionState, "connected") - XCTAssertEqual(workspace.unreadCount, 3) - XCTAssertEqual(workspace.latestNotificationText, "done") - XCTAssertEqual(workspace.latestSubmittedMessage, "ship") - XCTAssertNotNil(workspace.latestSubmittedAt) - XCTAssertEqual(workspace.listeningPorts, [3000]) - XCTAssertEqual(workspace.pullRequestURLs, ["https://github.com/manaflow-ai/cmux/pull/4309"]) - XCTAssertEqual(workspace.panelDirectories, ["/tmp/cmux/api", "/tmp/cmux/web"]) - XCTAssertEqual(workspace.gitBranches, [ - CmuxExtensionGitBranchSnapshot(branch: "main", isDirty: true), - CmuxExtensionGitBranchSnapshot(branch: "feature", isDirty: false) - ]) - } - - func testWorkspaceSnapshotDecodesSocketShapeDefaults() throws { - let workspaceId = UUID() - let data = Data(""" - {"id":"\(workspaceId.uuidString)","title":"API"} - """.utf8) - - let workspace = try JSONDecoder().decode(CmuxExtensionWorkspaceSnapshot.self, from: data) - - XCTAssertEqual(workspace.id, workspaceId) - XCTAssertEqual(workspace.title, "API") - XCTAssertFalse(workspace.isPinned) - XCTAssertEqual(workspace.unreadCount, 0) - XCTAssertEqual(workspace.listeningPorts, []) - XCTAssertEqual(workspace.pullRequestURLs, []) - XCTAssertEqual(workspace.panelDirectories, []) - XCTAssertEqual(workspace.gitBranches, []) - } - - func testLegacyPullRequestTabDecodesAsBrowser() throws { - let data = try JSONEncoder().encode("pullRequest") - let decoded = try JSONDecoder().decode(CmuxExtensionWorkspacePopoverTab.self, from: data) - - XCTAssertEqual(decoded, .browser) - } - - func testLegacyRenderModelDecodesWithTreePresentation() throws { - let data = Data(""" - {"providerId":"legacy","snapshotSequence":1,"sections":[]} - """.utf8) - - let decoded = try JSONDecoder().decode(CmuxExtensionSidebarRenderModel.self, from: data) - - XCTAssertEqual(decoded.presentation, .tree) - } - - func testMoveWorkspaceMutationCodableRoundTrips() throws { - let move = CmuxExtensionSidebarWorkspaceMove( - workspaceId: UUID(), - sourceSectionId: "loose", - targetSectionId: "group:research", - targetIndex: 2 - ) - let mutation = CmuxExtensionSidebarMutation.moveWorkspace(move) - - let data = try JSONEncoder().encode(mutation) - let decoded = try JSONDecoder().decode(CmuxExtensionSidebarMutation.self, from: data) - - XCTAssertEqual(decoded, mutation) - } - - func testPromptSubmittedEventUpdatesLastMessageProjection() { - let workspace = workspace(title: "API", rootPath: "/tmp/cmux/api", projectRootPath: "/tmp/cmux") - let date = Date(timeIntervalSinceReferenceDate: 300) - let event = CmuxExtensionEventFrame( - sequence: 11, - name: "workspace.prompt.submitted", - category: "workspace", - source: "workspace.prompt_submit", - occurredAt: date, - workspaceId: workspace.id, - payload: [ - "message": .null, - "message_preview": .string(" ship the events "), - "redacted_fields": .array([.string("message")]) - ] - ) - let snapshot = CmuxExtensionSidebarSnapshot( - sequence: 10, - selectedWorkspaceId: nil, - workspaces: [workspace] - ) - - let updated = CmuxExtensionSidebarReducer.reduce(snapshot, event: event) - - XCTAssertEqual(updated.sequence, 11) - XCTAssertEqual(updated.workspaces[0].latestSubmittedMessage, "ship the events") - XCTAssertEqual(updated.workspaces[0].latestSubmittedAt, date) - } - - func testBlankPromptSubmittedEventDoesNotAdvanceLastMessageProjection() { - let existingDate = Date(timeIntervalSinceReferenceDate: 100) - let workspace = workspace( - title: "API", - rootPath: "/tmp/cmux/api", - projectRootPath: "/tmp/cmux", - latestSubmittedMessage: "existing", - latestSubmittedAt: existingDate - ) - let event = CmuxExtensionEventFrame( - sequence: 11, - name: "workspace.prompt.submitted", - category: "workspace", - source: "workspace.prompt_submit", - occurredAt: Date(timeIntervalSinceReferenceDate: 300), - workspaceId: workspace.id, - payload: [ - "message": .null, - "message_preview": .null, - "redacted_fields": .array([.string("message")]) - ] - ) - let snapshot = CmuxExtensionSidebarSnapshot( - sequence: 10, - selectedWorkspaceId: nil, - workspaces: [workspace] - ) - - let updated = CmuxExtensionSidebarReducer.reduce(snapshot, event: event) - - XCTAssertEqual(updated.sequence, 11) - XCTAssertEqual(updated.workspaces[0].latestSubmittedMessage, "existing") - XCTAssertEqual(updated.workspaces[0].latestSubmittedAt, existingDate) - } - - func testStaleEventFrameDoesNotMutateFreshSnapshot() { - let existingDate = Date(timeIntervalSinceReferenceDate: 200) - var workspace = workspace( - title: "API", - rootPath: "/tmp/cmux/api", - projectRootPath: "/tmp/cmux", - latestSubmittedMessage: "newer", - latestSubmittedAt: existingDate - ) - workspace.unreadCount = 1 - workspace.latestNotificationText = "fresh" - let snapshot = CmuxExtensionSidebarSnapshot( - sequence: 20, - selectedWorkspaceId: workspace.id, - workspaces: [workspace] - ) - let staleNotification = CmuxExtensionEventFrame( - sequence: 20, - name: "notification.created", - category: "notification", - source: "notification.store", - occurredAt: Date(timeIntervalSinceReferenceDate: 100), - workspaceId: workspace.id, - payload: [ - "body": .string("old notification"), - "is_read": .bool(false) - ] - ) - let stalePrompt = CmuxExtensionEventFrame( - sequence: 19, - name: "workspace.prompt.submitted", - category: "workspace", - source: "workspace.prompt_submit", - occurredAt: Date(timeIntervalSinceReferenceDate: 100), - workspaceId: workspace.id, - payload: [ - "message_preview": .string("older prompt") - ] - ) - - let afterNotification = CmuxExtensionSidebarReducer.reduce(snapshot, event: staleNotification) - let afterPrompt = CmuxExtensionSidebarReducer.reduce(snapshot, event: stalePrompt) - - XCTAssertEqual(afterNotification, snapshot) - XCTAssertEqual(afterPrompt, snapshot) - } - - func testWorkspacesReorderedHandlesDuplicatesAndPartialPayload() { - let first = workspace(title: "First", rootPath: nil, projectRootPath: nil) - let second = workspace(title: "Second", rootPath: nil, projectRootPath: nil) - let third = workspace(title: "Third", rootPath: nil, projectRootPath: nil) - let windowId = UUID() - let snapshot = CmuxExtensionSidebarSnapshot( - sequence: 5, - selectedWorkspaceId: second.id, - workspaces: [first, second, third], - windowId: windowId - ) - - let updated = CmuxExtensionSidebarReducer.reduce( - snapshot, - event: .workspacesReordered([third.id, first.id, third.id]) - ) - - XCTAssertEqual(updated.sequence, 6) - XCTAssertEqual(updated.windowId, windowId) - XCTAssertEqual(updated.selectedWorkspaceId, second.id) - XCTAssertEqual(updated.workspaces.map(\.id), [third.id, first.id, second.id]) - } - - func testWorkspacesReorderedToleratesDuplicateWorkspaceSnapshots() { - let first = workspace(title: "First", rootPath: nil, projectRootPath: nil) - var replacement = workspace(title: "Replacement", rootPath: nil, projectRootPath: nil) - replacement.id = first.id - let snapshot = CmuxExtensionSidebarSnapshot( - sequence: 5, - selectedWorkspaceId: first.id, - workspaces: [first, replacement] - ) - - let direct = CmuxExtensionSidebarReducer.reduce( - snapshot, - event: .workspacesReordered([first.id]) - ) - let frame = CmuxExtensionEventFrame( - sequence: 8, - name: "workspace.reordered", - category: "workspace", - source: "workspace.lifecycle", - occurredAt: Date(timeIntervalSinceReferenceDate: 1), - workspaceId: first.id, - payload: [ - "workspace_ids": .array([.string(first.id.uuidString)]) - ] - ) - let eventReduced = CmuxExtensionSidebarReducer.reduce(snapshot, event: frame) - - XCTAssertEqual(direct.workspaces.map(\.title), ["Replacement"]) - XCTAssertEqual(eventReduced.workspaces.map(\.title), ["Replacement"]) - } - - func testSidebarEventReducerPreservesWindowIdAcrossFreshSnapshots() { - let first = workspace(title: "First", rootPath: nil, projectRootPath: nil) - let second = workspace(title: "Second", rootPath: nil, projectRootPath: nil) - let windowId = UUID() - let snapshot = CmuxExtensionSidebarSnapshot( - sequence: 1, - selectedWorkspaceId: first.id, - workspaces: [first], - windowId: windowId - ) - - let upserted = CmuxExtensionSidebarReducer.reduce(snapshot, event: .workspaceUpserted(second)) - let selected = CmuxExtensionSidebarReducer.reduce(upserted, event: .workspaceSelected(second.id)) - let reordered = CmuxExtensionSidebarReducer.reduce(selected, event: .workspacesReordered([second.id, first.id])) - let removed = CmuxExtensionSidebarReducer.reduce(reordered, event: .workspaceRemoved(first.id)) - - XCTAssertEqual(upserted.windowId, windowId) - XCTAssertEqual(selected.windowId, windowId) - XCTAssertEqual(reordered.windowId, windowId) - XCTAssertEqual(removed.windowId, windowId) - XCTAssertEqual(removed.workspaces.map(\.id), [second.id]) - } - - func testWorkspaceReorderedEventPreservesFrameSequence() { - let first = workspace(title: "First", rootPath: nil, projectRootPath: nil) - var second = workspace(title: "Second", rootPath: nil, projectRootPath: nil) - second.isPinned = true - let snapshot = CmuxExtensionSidebarSnapshot( - sequence: 10, - selectedWorkspaceId: first.id, - workspaces: [first, second] - ) - let event = CmuxExtensionEventFrame( - sequence: 12, - name: "workspace.reordered", - category: "workspace", - source: "socket.v2", - occurredAt: Date(timeIntervalSinceReferenceDate: 4), - workspaceId: second.id, - payload: [ - "workspace_ids": .array([.string(second.id.uuidString), .string(first.id.uuidString)]), - "pinned_workspace_ids": .array([.string(first.id.uuidString)]) - ] - ) - - let updated = CmuxExtensionSidebarReducer.reduce(snapshot, event: event) - - XCTAssertEqual(updated.sequence, 12) - XCTAssertEqual(updated.workspaces.map(\.id), [second.id, first.id]) - XCTAssertEqual(updated.workspaces.map(\.isPinned), [false, true]) - } - - func testWorkspaceReorderedEventWithoutLocalOverlapPreservesPinnedState() { - var first = workspace(title: "First", rootPath: nil, projectRootPath: nil) - first.isPinned = true - let second = workspace(title: "Second", rootPath: nil, projectRootPath: nil) - let foreign = UUID() - let snapshot = CmuxExtensionSidebarSnapshot( - sequence: 10, - selectedWorkspaceId: first.id, - workspaces: [first, second], - windowId: UUID() - ) - let event = CmuxExtensionEventFrame( - sequence: 12, - name: "workspace.reordered", - category: "workspace", - source: "workspace.lifecycle", - occurredAt: Date(timeIntervalSinceReferenceDate: 4), - workspaceId: foreign, - payload: [ - "workspace_ids": .array([.string(foreign.uuidString)]), - "pinned_workspace_ids": .array([.string(foreign.uuidString)]) - ] - ) - - let updated = CmuxExtensionSidebarReducer.reduce(snapshot, event: event) - - XCTAssertEqual(updated.sequence, 12) - XCTAssertEqual(updated.workspaces.map(\.id), [first.id, second.id]) - XCTAssertEqual(updated.workspaces.map(\.isPinned), [true, false]) - } - - func testWorkspaceReorderedEventReadsSocketResultIndex() { - let first = workspace(title: "First", rootPath: nil, projectRootPath: nil) - let second = workspace(title: "Second", rootPath: nil, projectRootPath: nil) - let third = workspace(title: "Third", rootPath: nil, projectRootPath: nil) - let snapshot = CmuxExtensionSidebarSnapshot( - sequence: 20, - selectedWorkspaceId: first.id, - workspaces: [first, second, third] - ) - let event = CmuxExtensionEventFrame( - sequence: 21, - name: "workspace.reordered", - category: "workspace", - source: "socket.v2", - occurredAt: Date(timeIntervalSinceReferenceDate: 6), - workspaceId: third.id, - payload: [ - "method": .string("workspace.reorder"), - "params": .object([ - "workspace_id": .string(third.id.uuidString), - "index": .number(0) - ]), - "result": .object([ - "workspace_id": .string(third.id.uuidString), - "index": .number(0) - ]) - ] - ) - - let updated = CmuxExtensionSidebarReducer.reduce(snapshot, event: event) - - XCTAssertEqual(updated.sequence, 21) - XCTAssertEqual(updated.workspaces.map(\.id), [third.id, first.id, second.id]) - } - - func testWorkspaceCreatedEventAddsWorkspaceProjection() { - let first = workspace(title: "First", rootPath: "/tmp/cmux/first", projectRootPath: "/tmp/cmux") - let createdId = UUID() - let snapshot = CmuxExtensionSidebarSnapshot( - sequence: 5, - selectedWorkspaceId: first.id, - workspaces: [first] - ) - let event = CmuxExtensionEventFrame( - sequence: 6, - name: "workspace.created", - category: "workspace", - source: "workspace.lifecycle", - occurredAt: Date(timeIntervalSinceReferenceDate: 2), - workspaceId: createdId, - payload: [ - "workspace_id": .string(createdId.uuidString), - "title": .string("Created"), - "cwd": .string("/tmp/cmux/created"), - "index": .number(0), - "selected": .bool(true) - ] - ) - - XCTAssertTrue(CmuxExtensionSidebarReducer.requiresSnapshotReplacement(after: event)) - - let updated = CmuxExtensionSidebarReducer.reduce(snapshot, event: event) - - XCTAssertEqual(updated.sequence, 6) - XCTAssertEqual(updated.selectedWorkspaceId, createdId) - XCTAssertEqual(updated.workspaces.map(\.id), [createdId, first.id]) - XCTAssertEqual(updated.workspaces[0].title, "Created") - XCTAssertEqual(updated.workspaces[0].rootPath, "/tmp/cmux/created") - } - - func testWorkspaceSelectedEventIgnoresWorkspaceOutsideSnapshotWindow() { - let first = workspace(title: "First", rootPath: "/tmp/cmux/first", projectRootPath: "/tmp/cmux") - let secondWindowWorkspaceId = UUID() - let snapshot = CmuxExtensionSidebarSnapshot( - sequence: 1, - selectedWorkspaceId: first.id, - workspaces: [first], - windowId: UUID() - ) - let event = CmuxExtensionEventFrame( - sequence: 2, - name: "workspace.selected", - category: "workspace", - source: "workspace.lifecycle", - occurredAt: Date(timeIntervalSinceReferenceDate: 1), - workspaceId: secondWindowWorkspaceId - ) - - let updated = CmuxExtensionSidebarReducer.reduce(snapshot, event: event) - - XCTAssertEqual(updated.sequence, 2) - XCTAssertEqual(updated.selectedWorkspaceId, first.id) - } - - func testWorkspaceRenamedEventReadsSocketResultPayload() { - let first = workspace(title: "Before", rootPath: "/tmp/cmux/first", projectRootPath: "/tmp/cmux") - let snapshot = CmuxExtensionSidebarSnapshot( - sequence: 7, - selectedWorkspaceId: first.id, - workspaces: [first] - ) - let event = CmuxExtensionEventFrame( - sequence: 8, - name: "workspace.renamed", - category: "workspace", - source: "socket.v2", - occurredAt: Date(timeIntervalSinceReferenceDate: 5), - workspaceId: first.id, - payload: [ - "method": .string("workspace.rename"), - "result": .object([ - "workspace_id": .string(first.id.uuidString), - "title": .string("After") - ]) - ] - ) - - let updated = CmuxExtensionSidebarReducer.reduce(snapshot, event: event) - - XCTAssertEqual(updated.sequence, 8) - XCTAssertEqual(updated.workspaces[0].title, "After") - } - - func testSelectedAndClosedWorkspaceEventsUpdateProjection() { - let first = workspace(title: "First", rootPath: "/tmp/cmux/first", projectRootPath: "/tmp/cmux") - let second = workspace(title: "Second", rootPath: "/tmp/cmux/second", projectRootPath: "/tmp/cmux") - let snapshot = CmuxExtensionSidebarSnapshot( - sequence: 1, - selectedWorkspaceId: nil, - workspaces: [first, second] - ) - let selected = CmuxExtensionEventFrame( - sequence: 2, - name: "workspace.selected", - category: "workspace", - source: "workspace.lifecycle", - occurredAt: Date(timeIntervalSinceReferenceDate: 1), - workspaceId: second.id - ) - let closed = CmuxExtensionEventFrame( - sequence: 3, - name: "workspace.closed", - category: "workspace", - source: "workspace.lifecycle", - occurredAt: Date(timeIntervalSinceReferenceDate: 2), - workspaceId: second.id - ) - - let selectedSnapshot = CmuxExtensionSidebarReducer.reduce(snapshot, event: selected) - let closedSnapshot = CmuxExtensionSidebarReducer.reduce(selectedSnapshot, event: closed) - - XCTAssertEqual(selectedSnapshot.selectedWorkspaceId, second.id) - XCTAssertEqual(closedSnapshot.selectedWorkspaceId, nil) - XCTAssertEqual(closedSnapshot.workspaces.map(\.id), [first.id]) - } - - func testNotificationCreatedEventUpdatesUnreadProjection() { - let workspace = workspace(title: "API", rootPath: "/tmp/cmux/api", projectRootPath: "/tmp/cmux") - let snapshot = CmuxExtensionSidebarSnapshot( - sequence: 30, - selectedWorkspaceId: workspace.id, - workspaces: [workspace] - ) - let event = CmuxExtensionEventFrame( - sequence: 31, - name: "notification.created", - category: "notification", - source: "notification.store", - occurredAt: Date(timeIntervalSinceReferenceDate: 7), - workspaceId: workspace.id, - payload: [ - "notification_id": .string(UUID().uuidString), - "workspace_id": .string(workspace.id.uuidString), - "title": .string("Done"), - "body": .string(" build passed "), - "is_read": .bool(false) +final class CMUXExtensionKitTests: XCTestCase { + func testSidebarSnapshotRoundTripsStableContract() throws { + let workspaceID = UUID(uuidString: "11111111-1111-1111-1111-111111111111")! + let snapshot = CMUXSidebarSnapshot( + sequence: 42, + windowID: UUID(uuidString: "22222222-2222-2222-2222-222222222222")!, + selectedWorkspaceID: workspaceID, + workspaces: [ + CMUXSidebarWorkspace( + id: workspaceID, + title: "Build", + detail: "main", + isPinned: true, + rootPath: "/repo", + projectRootPath: "/repo", + gitBranch: "main", + unreadCount: 2, + latestNotification: "Tests passed", + listeningPorts: [3000], + pullRequestURLs: ["https://github.com/manaflow-ai/cmux/pull/1"] + ), ] ) - let updated = CmuxExtensionSidebarReducer.reduce(snapshot, event: event) + let encoded = try JSONEncoder().encode(snapshot) + let decoded = try JSONDecoder().decode(CMUXSidebarSnapshot.self, from: encoded) - XCTAssertFalse(CmuxExtensionSidebarReducer.requiresSnapshotReplacement(after: event)) - XCTAssertEqual(updated.sequence, 31) - XCTAssertEqual(updated.workspaces[0].unreadCount, 1) - XCTAssertEqual(updated.workspaces[0].latestNotificationText, "build passed") + XCTAssertEqual(decoded, snapshot) + XCTAssertEqual(decoded.apiVersion, .sidebarV1) } - func testNotificationReadEventUpdatesUnreadProjection() { - var workspace = workspace(title: "API", rootPath: "/tmp/cmux/api", projectRootPath: "/tmp/cmux") - workspace.unreadCount = 2 - workspace.latestNotificationText = "done" - let snapshot = CmuxExtensionSidebarSnapshot( - sequence: 31, - selectedWorkspaceId: workspace.id, - workspaces: [workspace] - ) - let event = CmuxExtensionEventFrame( - sequence: 32, - name: "notification.read", - category: "notification", - source: "notification.store", - occurredAt: Date(timeIntervalSinceReferenceDate: 8), - workspaceId: workspace.id, - payload: [ - "notification_ids": .array([.string(UUID().uuidString), .string(UUID().uuidString)]), - "count": .number(2) - ] + func testManifestValidationAcceptsSidebarV1() throws { + let manifest = CMUXExtensionManifest( + id: "dev.example.sidebar", + displayName: "Example Sidebar", + requestedScopes: [.workspaceMetadata, .workspacePaths] ) - let updated = CmuxExtensionSidebarReducer.reduce(snapshot, event: event) - - XCTAssertTrue(CmuxExtensionSidebarReducer.requiresSnapshotReplacement(after: event)) - XCTAssertEqual(updated.sequence, 32) - XCTAssertEqual(updated.workspaces[0].unreadCount, 0) - XCTAssertNil(updated.workspaces[0].latestNotificationText) + XCTAssertNoThrow(try CMUXExtensionValidator.validateSidebarManifest(manifest)) } - func testRedactedNotificationAndSidebarEventsRequireSnapshotReplacement() { - let workspaceId = UUID() - let redactedNotification = CmuxExtensionEventFrame( - sequence: 40, - name: "notification.created", - category: "notification", - source: "notification.store", - occurredAt: Date(timeIntervalSinceReferenceDate: 9), - workspaceId: workspaceId, - payload: [ - "title": .null, - "body": .null, - "redacted_fields": .array([.string("title"), .string("body")]) - ] - ) - let sidebarMetadata = CmuxExtensionEventFrame( - sequence: 41, - name: "sidebar.metadata.updated", - category: "sidebar", - source: "socket.v1", - occurredAt: Date(timeIntervalSinceReferenceDate: 10), - workspaceId: workspaceId - ) - let promptSubmitted = CmuxExtensionEventFrame( - sequence: 42, - name: "workspace.prompt.submitted", - category: "workspace", - source: "workspace.prompt_submit", - occurredAt: Date(timeIntervalSinceReferenceDate: 11), - workspaceId: workspaceId, - payload: ["message_preview": .string("ship")] - ) - let workspaceAction = CmuxExtensionEventFrame( - sequence: 43, - name: "workspace.action", - category: "workspace", - source: "socket.v2", - occurredAt: Date(timeIntervalSinceReferenceDate: 12), - workspaceId: workspaceId, - payload: ["method": .string("workspace.pin")] - ) - let workspaceMoved = CmuxExtensionEventFrame( - sequence: 44, - name: "workspace.moved", - category: "workspace", - source: "socket.v2", - occurredAt: Date(timeIntervalSinceReferenceDate: 13), - workspaceId: workspaceId, - payload: ["method": .string("workspace.move_to_window")] + func testManifestValidationRejectsUnsupportedMajorVersion() { + let manifest = CMUXExtensionManifest( + id: "dev.example.sidebar", + displayName: "Example Sidebar", + minimumAPIVersion: CMUXExtensionAPIVersion(major: 2, minor: 0) ) - XCTAssertTrue(CmuxExtensionSidebarReducer.requiresSnapshotReplacement(after: redactedNotification)) - XCTAssertTrue(CmuxExtensionSidebarReducer.requiresSnapshotReplacement(after: sidebarMetadata)) - XCTAssertTrue(CmuxExtensionSidebarReducer.requiresSnapshotReplacement(after: workspaceAction)) - XCTAssertTrue(CmuxExtensionSidebarReducer.requiresSnapshotReplacement(after: workspaceMoved)) - XCTAssertFalse(CmuxExtensionSidebarReducer.requiresSnapshotReplacement(after: promptSubmitted)) - } - - private func workspace( - title: String, - rootPath: String?, - projectRootPath: String?, - latestSubmittedMessage: String? = nil, - latestSubmittedAt: Date? = nil - ) -> CmuxExtensionWorkspaceSnapshot { - CmuxExtensionWorkspaceSnapshot( - id: UUID(), - title: title, - customDescription: nil, - isPinned: false, - rootPath: rootPath, - projectRootPath: projectRootPath, - branchSummary: nil, - remoteDisplayTarget: nil, - remoteConnectionState: nil, - unreadCount: 0, - latestNotificationText: nil, - latestSubmittedMessage: latestSubmittedMessage, - latestSubmittedAt: latestSubmittedAt, - listeningPorts: [] - ) + XCTAssertThrowsError(try CMUXExtensionValidator.validateSidebarManifest(manifest)) { error in + XCTAssertEqual( + error as? CMUXExtensionValidationError, + .unsupportedMajorVersion(requested: 2, supported: 1) + ) + } } } diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index b85fe09e2697..cccefb43b548 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -161745,6 +161745,109 @@ } } } + }, + "sidebar.provider.extensions.title": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "CMUX Extensions" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "CMUX拡張機能" + } + } + } + }, + "sidebar.provider.extensions.subtitle": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "ExtensionKit" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "ExtensionKit" + } + } + } + }, + "sidebar.extensions.loading": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Loading sidebar extensions" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "サイドバー拡張機能を読み込み中" + } + } + } + }, + "sidebar.extensions.empty.title": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "No sidebar extension enabled" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "有効なサイドバー拡張機能がありません" + } + } + } + }, + "sidebar.extensions.empty.detail": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Install and enable a CMUX sidebar extension to show it here." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "ここに表示するには、CMUXサイドバー拡張機能をインストールして有効にしてください。" + } + } + } + }, + "sidebar.extensions.error": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "CMUX could not load sidebar extensions." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "CMUXはサイドバー拡張機能を読み込めませんでした。" + } + } + } + } } } diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index 6ddb15314082..f82b0a54288a 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -1,7 +1,9 @@ import AppKit import Bonsplit +import CMUXExtensionClient import Combine import CmuxExtensionKit +import ExtensionFoundation import ImageIO import Observation import SwiftUI @@ -9844,14 +9846,29 @@ private extension String { enum CmuxExtensionSidebarSelection { static let defaultsKey = "cmuxExtensionSidebar.providerId" static let defaultProviderId = CmuxExtensionSidebarProviderID.defaultWorkspaces + static let hostedExtensionsProviderId = "cmux.sidebar.extensions" static var providers: [any CmuxExtensionSidebarProvider] { [] } static var descriptors: [CmuxExtensionSidebarProviderDescriptor] { - [.defaultWorkspaces] + providers.map { $0.descriptor } - } + [.defaultWorkspaces, hostedExtensionsDescriptor] + providers.map { $0.descriptor } + } + + static let hostedExtensionsDescriptor = CmuxExtensionSidebarProviderDescriptor( + id: hostedExtensionsProviderId, + title: CmuxExtensionLocalizedText( + key: "sidebar.provider.extensions.title", + defaultValue: "CMUX Extensions" + ), + subtitle: CmuxExtensionLocalizedText( + key: "sidebar.provider.extensions.subtitle", + defaultValue: "ExtensionKit" + ), + systemImageName: "puzzlepiece.extension", + isHostProvided: true + ) static func descriptor(for providerId: String) -> CmuxExtensionSidebarProviderDescriptor { descriptors.first { $0.id == providerId } ?? .defaultWorkspaces @@ -10594,10 +10611,15 @@ struct VerticalTabsSidebar: View { } } + @ViewBuilder private func extensionSidebarScrollArea(renderContext: WorkspaceListRenderContext) -> some View { - TimelineView(.periodic(from: .now, by: 30)) { timeline in - let model = extensionSidebarRenderModel(renderContext: renderContext, now: timeline.date) - extensionSidebarTimelineContent(renderContext: renderContext, model: model, now: timeline.date) + if selectedExtensionSidebarProviderId == CmuxExtensionSidebarSelection.hostedExtensionsProviderId { + CMUXInstalledExtensionSidebarHostView() + } else { + TimelineView(.periodic(from: .now, by: 30)) { timeline in + let model = extensionSidebarRenderModel(renderContext: renderContext, now: timeline.date) + extensionSidebarTimelineContent(renderContext: renderContext, model: model, now: timeline.date) + } } } @@ -13908,6 +13930,73 @@ private struct ExtensionSidebarBrowserStackEmptyArea: View { } } +private struct CMUXInstalledExtensionSidebarHostView: View { + @State private var identity: AppExtensionIdentity? + @State private var isLoading = true + @State private var errorText: String? + + var body: some View { + Group { + if let identity { + CMUXSidebarExtensionHostView(identity: identity) + .accessibilityIdentifier("CMUXExtensionSidebarHostView") + } else { + VStack(alignment: .leading, spacing: 10) { + if isLoading { + ProgressView() + .controlSize(.small) + Text(String(localized: "sidebar.extensions.loading", defaultValue: "Loading sidebar extensions")) + .font(.system(size: 12)) + .foregroundStyle(.secondary) + } else { + Image(systemName: "puzzlepiece.extension") + .font(.system(size: 22, weight: .regular)) + .foregroundStyle(.secondary) + Text(String(localized: "sidebar.extensions.empty.title", defaultValue: "No sidebar extension enabled")) + .font(.system(size: 13, weight: .medium)) + .foregroundStyle(.primary) + Text(errorText ?? String( + localized: "sidebar.extensions.empty.detail", + defaultValue: "Install and enable a CMUX sidebar extension to show it here." + )) + .font(.system(size: 12)) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + } + .padding(.horizontal, 14) + .padding(.top, SidebarWorkspaceScrollInsets.workspaceList.top + 12) + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) + .accessibilityIdentifier("CMUXExtensionSidebarEmptyState") + } + } + .task { + await loadExtension() + } + } + + private func loadExtension() async { + isLoading = true + errorText = nil + do { + var identities = try AppExtensionIdentity.matching( + appExtensionPointIDs: CMUXSidebarExtensionPoint.identifier + ) + .makeAsyncIterator() + let update = await identities.next() ?? [] + identity = update.sorted { $0.localizedName < $1.localizedName }.first + isLoading = false + } catch { + identity = nil + isLoading = false + errorText = String( + localized: "sidebar.extensions.error", + defaultValue: "CMUX could not load sidebar extensions." + ) + } + } +} + enum SidebarWorkspaceShortcutHintMetrics { private static let measurementFont = NSFont.systemFont(ofSize: 10, weight: .semibold) private static let minimumSlotWidth: CGFloat = 28 diff --git a/cmux.xcodeproj/project.pbxproj b/cmux.xcodeproj/project.pbxproj index 3e25c5fe6f7d..28e2c87fb9e7 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -138,6 +138,7 @@ E7E00000000000000000000D /* CmuxEventLogWriter.swift in Sources */ = {isa = PBXBuildFile; fileRef = E7E00000000000000000000E /* CmuxEventLogWriter.swift */; }; E7E000000000000000000007 /* CmuxEventPublishing.swift in Sources */ = {isa = PBXBuildFile; fileRef = E7E000000000000000000008 /* CmuxEventPublishing.swift */; }; E7E000000000000000000001 /* CmuxEventStream.swift in Sources */ = {isa = PBXBuildFile; fileRef = E7E000000000000000000002 /* CmuxEventStream.swift */; }; + C0DE46000000000000000001 /* CMUXExtensionClient in Frameworks */ = {isa = PBXBuildFile; productRef = C0DE46000000000000000002 /* CMUXExtensionClient */; }; C0DE45000000000000000001 /* CmuxExtensionKit in Frameworks */ = {isa = PBXBuildFile; productRef = C0DE45000000000000000002 /* CmuxExtensionKit */; }; C0DE34020000000000000001 /* CmuxHelpCommands.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE34020000000000000003 /* CmuxHelpCommands.swift */; }; C0DE34020000000000000002 /* CmuxHelpResource.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE34020000000000000004 /* CmuxHelpResource.swift */; }; @@ -1143,6 +1144,7 @@ A5B00003A1B2C3D4E5F60718 /* CMUXAgentLaunch in Frameworks */, F53000A0A1B2C3D4E5F60718 /* CMUXAgentVault in Frameworks */, 5EDB6027B346C46521A93C74 /* CMUXAuthCore in Frameworks */, + C0DE46000000000000000001 /* CMUXExtensionClient in Frameworks */, C0DE45000000000000000001 /* CmuxExtensionKit in Frameworks */, 3069F1D10000000000000005 /* CMUXPasteboardFidelity in Frameworks */, A5354303A5354303A5354303 /* CMUXSocketPathDomain in Frameworks */, @@ -1822,6 +1824,7 @@ A5001291 /* MarkdownUI */, 29813FE5A6CBC1019289A251 /* CMUXAuthCore */, AA11BB22CC33DD44EE550002 /* CMUXWorkstream */, + C0DE46000000000000000002 /* CMUXExtensionClient */, C0DE45000000000000000002 /* CmuxExtensionKit */, 3069F1D10000000000000006 /* CMUXPasteboardFidelity */, F53000A2A1B2C3D4E5F60718 /* CMUXAgentVault */, @@ -1955,6 +1958,7 @@ A5001260 /* XCLocalSwiftPackageReference "bonsplit" */, 40B63BB4A170F0BD2D1DEFD1 /* XCLocalSwiftPackageReference "CMUXAuthCore" */, AA11BB22CC33DD44EE550003 /* XCLocalSwiftPackageReference "CMUXWorkstream" */, + C0DE46000000000000000003 /* XCLocalSwiftPackageReference "CMUXExtensionClient" */, C0DE45000000000000000003 /* XCLocalSwiftPackageReference "CmuxExtensionKit" */, 3069F1D10000000000000007 /* XCLocalSwiftPackageReference "CMUXPasteboardFidelity" */, F53000A1A1B2C3D4E5F60718 /* XCLocalSwiftPackageReference "CMUXAgentVault" */, @@ -3023,6 +3027,10 @@ isa = XCLocalSwiftPackageReference; relativePath = Packages/CmuxExtensionKit; }; + C0DE46000000000000000003 /* XCLocalSwiftPackageReference "CMUXExtensionClient" */ = { + isa = XCLocalSwiftPackageReference; + relativePath = Packages/CMUXExtensionClient; + }; 3069F1D10000000000000007 /* XCLocalSwiftPackageReference "CMUXPasteboardFidelity" */ = { isa = XCLocalSwiftPackageReference; relativePath = Packages/CMUXPasteboardFidelity; @@ -3100,6 +3108,11 @@ package = C0DE45000000000000000003 /* XCLocalSwiftPackageReference "CmuxExtensionKit" */; productName = CmuxExtensionKit; }; + C0DE46000000000000000002 /* CMUXExtensionClient */ = { + isa = XCSwiftPackageProductDependency; + package = C0DE46000000000000000003 /* XCLocalSwiftPackageReference "CMUXExtensionClient" */; + productName = CMUXExtensionClient; + }; 3069F1D10000000000000006 /* CMUXPasteboardFidelity */ = { isa = XCSwiftPackageProductDependency; package = 3069F1D10000000000000007 /* XCLocalSwiftPackageReference "CMUXPasteboardFidelity" */; From f69d418347260d1c91b3389523bf7686daf0bd10 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Fri, 29 May 2026 13:52:55 -0500 Subject: [PATCH 02/44] Address sidebar ExtensionKit review feedback --- Packages/CMUXExtensionClient/README.md | 6 +- .../CMUXExtensionClient.swift | 90 +++ .../CMUXExtensionClientTests.swift | 30 +- .../CmuxExtensionKit/CmuxExtensionKit.swift | 10 +- .../CmuxExtensionKitTests.swift | 32 +- Resources/Localizable.xcstrings | 713 +++++++++++++++++- ...MUXInstalledExtensionSidebarHostView.swift | 72 ++ Sources/ContentView.swift | 69 -- cmux.xcodeproj/project.pbxproj | 4 + 9 files changed, 895 insertions(+), 131 deletions(-) create mode 100644 Sources/CMUXInstalledExtensionSidebarHostView.swift diff --git a/Packages/CMUXExtensionClient/README.md b/Packages/CMUXExtensionClient/README.md index f5a14fae998b..e5b43c2807a2 100644 --- a/Packages/CMUXExtensionClient/README.md +++ b/Packages/CMUXExtensionClient/README.md @@ -2,10 +2,12 @@ `CMUXExtensionClient` is the host-side package for loading and driving CMUX sidebar extensions. -This first slice contains: +This package contains: - manifest validation through `CmuxExtensionKit` - a registry for available sidebar extensions - a session actor that fetches snapshots and dispatches sidebar actions +- third-party sidebar extension discovery for `com.manaflow.cmux.sidebar` +- a SwiftUI `EXHostViewController` bridge for rendering the extension scene -The package is ready for an ExtensionKit-backed adapter, but this branch keeps the first verified surface focused on the API and host lifecycle. Future work should add the real `EXHostViewController` bridge and third-party extension discovery. +The exported surface is intentionally sidebar-only: `CmuxExtensionKit` defines the manifest, snapshot, and action contract, while this package owns host lifecycle, discovery, registry lookup, session dispatch, and the ExtensionKit host view. diff --git a/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/CMUXExtensionClient.swift b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/CMUXExtensionClient.swift index 754d767ffc5b..fddfaf689061 100644 --- a/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/CMUXExtensionClient.swift +++ b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/CMUXExtensionClient.swift @@ -4,30 +4,48 @@ import ExtensionKit import Foundation import SwiftUI +/// Public identifiers for the CMUX sidebar ExtensionKit surface. public enum CMUXSidebarExtensionPoint { + /// Extension point identifier third-party sidebar extensions register against. public static let identifier = "com.manaflow.cmux.sidebar" + /// Default ExtensionKit scene identifier hosted inside the cmux sidebar. public static let defaultSceneID = "sidebar" } +/// A sidebar extension registered with the host. public struct CMUXSidebarExtensionRecord: Equatable, Identifiable, Sendable { + /// Stable extension identifier from the manifest. public var id: String { manifest.id } + /// Manifest describing the extension contract and requested scopes. public var manifest: CMUXExtensionManifest + /// Whether the extension is provided by cmux rather than a third party. public var isHostProvided: Bool + /// Creates a sidebar extension record. + /// - Parameters: + /// - manifest: Manifest describing the extension. + /// - isHostProvided: Whether cmux provides the extension. public init(manifest: CMUXExtensionManifest, isHostProvided: Bool) { self.manifest = manifest self.isHostProvided = isHostProvided } } +/// Errors raised by the sidebar extension host client. public enum CMUXExtensionClientError: Error, Equatable, Sendable { + /// More than one extension used the same manifest identifier. case duplicateExtensionIdentifier(String) + /// No registered extension matched the requested identifier. case extensionNotFound(String) } +/// Validated collection of sidebar extensions available to the host. public struct CMUXSidebarExtensionRegistry: Sendable { private var recordsByID: [String: CMUXSidebarExtensionRecord] + /// Creates a registry from extension records. + /// - Parameter records: Records to validate and store by identifier. + /// - Throws: `CMUXExtensionClientError.duplicateExtensionIdentifier` for duplicate ids, or manifest validation errors. public init(records: [CMUXSidebarExtensionRecord] = []) throws { var recordsByID: [String: CMUXSidebarExtensionRecord] = [:] for record in records { @@ -40,10 +58,15 @@ public struct CMUXSidebarExtensionRegistry: Sendable { self.recordsByID = recordsByID } + /// Records sorted by display name for deterministic presentation. public var records: [CMUXSidebarExtensionRecord] { recordsByID.values.sorted { $0.manifest.displayName < $1.manifest.displayName } } + /// Looks up one extension record. + /// - Parameter id: Manifest identifier to find. + /// - Returns: Matching record. + /// - Throws: `CMUXExtensionClientError.extensionNotFound` when no record exists. public func record(id: String) throws -> CMUXSidebarExtensionRecord { guard let record = recordsByID[id] else { throw CMUXExtensionClientError.extensionNotFound(id) @@ -52,42 +75,68 @@ public struct CMUXSidebarExtensionRegistry: Sendable { } } +/// Host-side session that mediates snapshot refreshes and action dispatch for one sidebar extension. public actor CMUXSidebarExtensionSession { private let manifest: CMUXExtensionManifest private let client: CMUXSidebarHostClient private var latestSnapshot: CMUXSidebarSnapshot? + /// Creates a sidebar extension session. + /// - Parameters: + /// - manifest: Manifest for the extension attached to this session. + /// - client: Host callbacks used to fetch snapshots and dispatch actions. + /// - Throws: Manifest validation errors. public init(manifest: CMUXExtensionManifest, client: CMUXSidebarHostClient) throws { try CMUXExtensionValidator.validateSidebarManifest(manifest) self.manifest = manifest self.client = client } + /// Fetches and caches the latest sidebar snapshot. + /// - Returns: Snapshot returned by the host client. + /// - Throws: Errors thrown by the host snapshot callback. public func refreshSnapshot() async throws -> CMUXSidebarSnapshot { let snapshot = try await client.snapshot() latestSnapshot = snapshot return snapshot } + /// Dispatches an extension action to the host. + /// - Parameter action: Sidebar action requested by the extension UI. + /// - Returns: Host action result. + /// - Throws: Errors thrown by the host dispatch callback. public func perform(_ action: CMUXSidebarAction) async throws -> CMUXExtensionActionResult { try await client.dispatch(action) } + /// Manifest associated with this session. public var extensionManifest: CMUXExtensionManifest { manifest } + /// Last snapshot returned by `refreshSnapshot()`, if any. + /// - Returns: Cached sidebar snapshot. public func cachedSnapshot() -> CMUXSidebarSnapshot? { latestSnapshot } } +/// Installed ExtensionKit sidebar extension discovered on the current Mac. public struct CMUXInstalledSidebarExtension: Identifiable, Equatable, Sendable { + /// Stable bundle identifier used for SwiftUI identity. public var id: String { bundleIdentifier } + /// Extension bundle identifier. public var bundleIdentifier: String + /// Localized extension display name. public var localizedName: String + /// Extension point identifier declared by the extension. public var extensionPointIdentifier: String + /// Creates an installed extension summary. + /// - Parameters: + /// - bundleIdentifier: Extension bundle identifier. + /// - localizedName: Localized extension display name. + /// - extensionPointIdentifier: Extension point identifier declared by the extension. public init( bundleIdentifier: String, localizedName: String, @@ -100,9 +149,15 @@ public struct CMUXInstalledSidebarExtension: Identifiable, Equatable, Sendable { } @available(macOS 14.0, *) +/// Discovers installed sidebar extensions that match CMUX's ExtensionKit point. public struct CMUXSidebarExtensionDiscovery { + /// Creates an extension discovery helper. public init() {} + /// Lists installed sidebar extensions. + /// - Parameter extensionPointIdentifier: Extension point identifier to match. + /// - Returns: Installed extensions sorted by localized name. + /// - Throws: Errors thrown by ExtensionFoundation discovery. public func installedExtensions( extensionPointIdentifier: String = CMUXSidebarExtensionPoint.identifier ) async throws -> [CMUXInstalledSidebarExtension] { @@ -121,19 +176,44 @@ public struct CMUXSidebarExtensionDiscovery { } @available(macOS 14.0, *) +/// SwiftUI bridge that hosts a sidebar extension scene through ExtensionKit. public struct CMUXSidebarExtensionHostView: NSViewControllerRepresentable { public typealias NSViewControllerType = EXHostViewController + /// Tracks the configuration currently installed on the host view controller. + public final class Coordinator { + fileprivate var currentKey: HostConfigurationKey? + } + + fileprivate struct HostConfigurationKey: Equatable { + var bundleIdentifier: String + var sceneID: String + } + private let identity: AppExtensionIdentity private let sceneID: String + /// Creates a sidebar extension host view. + /// - Parameters: + /// - identity: Extension identity to host. + /// - sceneID: ExtensionKit scene identifier to render. public init(identity: AppExtensionIdentity, sceneID: String = CMUXSidebarExtensionPoint.defaultSceneID) { self.identity = identity self.sceneID = sceneID } + /// Creates the configuration-tracking coordinator. + /// - Returns: Coordinator for the hosted extension configuration. + public func makeCoordinator() -> Coordinator { + Coordinator() + } + + /// Creates the ExtensionKit host view controller. + /// - Parameter context: SwiftUI representable context. + /// - Returns: Configured `EXHostViewController`. public func makeNSViewController(context: Context) -> EXHostViewController { let viewController = EXHostViewController() + context.coordinator.currentKey = configurationKey viewController.configuration = EXHostViewController.Configuration( appExtension: identity, sceneID: sceneID @@ -141,10 +221,20 @@ public struct CMUXSidebarExtensionHostView: NSViewControllerRepresentable { return viewController } + /// Updates the host view controller when the hosted extension changes. + /// - Parameters: + /// - viewController: Existing ExtensionKit host view controller. + /// - context: SwiftUI representable context. public func updateNSViewController(_ viewController: EXHostViewController, context: Context) { + guard context.coordinator.currentKey != configurationKey else { return } + context.coordinator.currentKey = configurationKey viewController.configuration = EXHostViewController.Configuration( appExtension: identity, sceneID: sceneID ) } + + private var configurationKey: HostConfigurationKey { + HostConfigurationKey(bundleIdentifier: identity.bundleIdentifier, sceneID: sceneID) + } } diff --git a/Packages/CMUXExtensionClient/Tests/CMUXExtensionClientTests/CMUXExtensionClientTests.swift b/Packages/CMUXExtensionClient/Tests/CMUXExtensionClientTests/CMUXExtensionClientTests.swift index 7dbb7042d4a1..0e54279a5618 100644 --- a/Packages/CMUXExtensionClient/Tests/CMUXExtensionClientTests/CMUXExtensionClientTests.swift +++ b/Packages/CMUXExtensionClient/Tests/CMUXExtensionClientTests/CMUXExtensionClientTests.swift @@ -1,8 +1,11 @@ import CmuxExtensionKit -import XCTest +import Foundation +import Testing @testable import CMUXExtensionClient -final class CMUXExtensionClientTests: XCTestCase { +@Suite +struct CMUXExtensionClientTests { + @Test func testRegistrySortsAndRejectsDuplicates() throws { let first = CMUXSidebarExtensionRecord( manifest: CMUXExtensionManifest(id: "b", displayName: "Browser Stack"), @@ -14,18 +17,23 @@ final class CMUXExtensionClientTests: XCTestCase { ) let registry = try CMUXSidebarExtensionRegistry(records: [first, second]) - XCTAssertEqual(registry.records.map(\.id), ["a", "b"]) + #expect(registry.records.map(\.id) == ["a", "b"]) - XCTAssertThrowsError(try CMUXSidebarExtensionRegistry(records: [first, first])) { error in - XCTAssertEqual(error as? CMUXExtensionClientError, .duplicateExtensionIdentifier("b")) + do { + _ = try CMUXSidebarExtensionRegistry(records: [first, first]) + Issue.record("Expected duplicate extension identifier error") + } catch { + #expect(error as? CMUXExtensionClientError == .duplicateExtensionIdentifier("b")) } } + @Test func testSidebarExtensionPointUsesStablePublicIdentifiers() { - XCTAssertEqual(CMUXSidebarExtensionPoint.identifier, "com.manaflow.cmux.sidebar") - XCTAssertEqual(CMUXSidebarExtensionPoint.defaultSceneID, "sidebar") + #expect(CMUXSidebarExtensionPoint.identifier == "com.manaflow.cmux.sidebar") + #expect(CMUXSidebarExtensionPoint.defaultSceneID == "sidebar") } + @Test func testSessionRefreshesSnapshotAndDispatchesActions() async throws { let workspaceID = UUID() let snapshot = CMUXSidebarSnapshot( @@ -49,12 +57,12 @@ final class CMUXExtensionClientTests: XCTestCase { let refreshed = try await session.refreshSnapshot() let result = try await session.perform(.selectWorkspace(workspaceID)) - XCTAssertEqual(refreshed, snapshot) let cached = await session.cachedSnapshot() let actions = await recorder.actions() - XCTAssertEqual(cached, snapshot) - XCTAssertEqual(result, .accepted) - XCTAssertEqual(actions, [.selectWorkspace(workspaceID)]) + #expect(refreshed == snapshot) + #expect(cached == snapshot) + #expect(result == .accepted) + #expect(actions == [.selectWorkspace(workspaceID)]) } } diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CmuxExtensionKit.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CmuxExtensionKit.swift index 9b4f8f97fd56..34adf0b80baf 100644 --- a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CmuxExtensionKit.swift +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CmuxExtensionKit.swift @@ -153,7 +153,7 @@ public struct CMUXSidebarHostClient: Sendable { public enum CMUXExtensionValidationError: Error, Equatable, Sendable { case unsupportedKind(CMUXExtensionKind) - case unsupportedMajorVersion(requested: Int, supported: Int) + case unsupportedAPIVersion(requested: CMUXExtensionAPIVersion, supported: CMUXExtensionAPIVersion) case emptyIdentifier case emptyDisplayName } @@ -172,10 +172,10 @@ public enum CMUXExtensionValidator { guard manifest.kind == .sidebar else { throw CMUXExtensionValidationError.unsupportedKind(manifest.kind) } - guard manifest.minimumAPIVersion.major == supportedAPIVersion.major else { - throw CMUXExtensionValidationError.unsupportedMajorVersion( - requested: manifest.minimumAPIVersion.major, - supported: supportedAPIVersion.major + guard manifest.minimumAPIVersion <= supportedAPIVersion else { + throw CMUXExtensionValidationError.unsupportedAPIVersion( + requested: manifest.minimumAPIVersion, + supported: supportedAPIVersion ) } } diff --git a/Packages/CmuxExtensionKit/Tests/CmuxExtensionKitTests/CmuxExtensionKitTests.swift b/Packages/CmuxExtensionKit/Tests/CmuxExtensionKitTests/CmuxExtensionKitTests.swift index 3218bf361a6a..13d11e6faa40 100644 --- a/Packages/CmuxExtensionKit/Tests/CmuxExtensionKitTests/CmuxExtensionKitTests.swift +++ b/Packages/CmuxExtensionKit/Tests/CmuxExtensionKitTests/CmuxExtensionKitTests.swift @@ -1,7 +1,10 @@ -import XCTest +import Foundation +import Testing @testable import CmuxExtensionKit -final class CMUXExtensionKitTests: XCTestCase { +@Suite +struct CMUXExtensionKitTests { + @Test func testSidebarSnapshotRoundTripsStableContract() throws { let workspaceID = UUID(uuidString: "11111111-1111-1111-1111-111111111111")! let snapshot = CMUXSidebarSnapshot( @@ -28,10 +31,11 @@ final class CMUXExtensionKitTests: XCTestCase { let encoded = try JSONEncoder().encode(snapshot) let decoded = try JSONDecoder().decode(CMUXSidebarSnapshot.self, from: encoded) - XCTAssertEqual(decoded, snapshot) - XCTAssertEqual(decoded.apiVersion, .sidebarV1) + #expect(decoded == snapshot) + #expect(decoded.apiVersion == CMUXExtensionAPIVersion.sidebarV1) } + @Test func testManifestValidationAcceptsSidebarV1() throws { let manifest = CMUXExtensionManifest( id: "dev.example.sidebar", @@ -39,20 +43,26 @@ final class CMUXExtensionKitTests: XCTestCase { requestedScopes: [.workspaceMetadata, .workspacePaths] ) - XCTAssertNoThrow(try CMUXExtensionValidator.validateSidebarManifest(manifest)) + try CMUXExtensionValidator.validateSidebarManifest(manifest) } - func testManifestValidationRejectsUnsupportedMajorVersion() { + @Test + func testManifestValidationRejectsUnsupportedAPIVersion() { let manifest = CMUXExtensionManifest( id: "dev.example.sidebar", displayName: "Example Sidebar", - minimumAPIVersion: CMUXExtensionAPIVersion(major: 2, minor: 0) + minimumAPIVersion: CMUXExtensionAPIVersion(major: 1, minor: 1) ) - XCTAssertThrowsError(try CMUXExtensionValidator.validateSidebarManifest(manifest)) { error in - XCTAssertEqual( - error as? CMUXExtensionValidationError, - .unsupportedMajorVersion(requested: 2, supported: 1) + do { + try CMUXExtensionValidator.validateSidebarManifest(manifest) + Issue.record("Expected unsupported API version error") + } catch { + #expect( + error as? CMUXExtensionValidationError == .unsupportedAPIVersion( + requested: CMUXExtensionAPIVersion(major: 1, minor: 1), + supported: .sidebarV1 + ) ) } } diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index cccefb43b548..66c98c7954ad 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -161749,105 +161749,752 @@ "sidebar.provider.extensions.title": { "extractionState": "manual", "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "امتدادات CMUX" + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "CMUX ekstenzije" + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "CMUX-udvidelser" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "CMUX-Erweiterungen" + } + }, "en": { "stringUnit": { "state": "translated", "value": "CMUX Extensions" } }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Extensiones de CMUX" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Extensions CMUX" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Estensioni CMUX" + } + }, "ja": { "stringUnit": { "state": "translated", "value": "CMUX拡張機能" } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "ផ្នែកបន្ថែម CMUX" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "CMUX 확장 기능" + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "CMUX-utvidelser" + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "Rozszerzenia CMUX" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Extensões do CMUX" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Расширения CMUX" + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "ส่วนขยาย CMUX" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "CMUX uzantıları" + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "Розширення CMUX" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "CMUX 扩展" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "CMUX 擴充功能" + } } } }, "sidebar.provider.extensions.subtitle": { "extractionState": "manual", "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "ExtensionKit" + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "ExtensionKit" + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "ExtensionKit" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "ExtensionKit" + } + }, "en": { "stringUnit": { "state": "translated", "value": "ExtensionKit" } }, + "es": { + "stringUnit": { + "state": "translated", + "value": "ExtensionKit" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "ExtensionKit" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "ExtensionKit" + } + }, "ja": { "stringUnit": { "state": "translated", "value": "ExtensionKit" } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "ExtensionKit" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "ExtensionKit" + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "ExtensionKit" + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "ExtensionKit" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "ExtensionKit" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "ExtensionKit" + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "ExtensionKit" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "ExtensionKit" + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "ExtensionKit" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "ExtensionKit" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "ExtensionKit" + } } } }, "sidebar.extensions.loading": { "extractionState": "manual", "localizations": { - "en": { + "ar": { "stringUnit": { "state": "translated", - "value": "Loading sidebar extensions" + "value": "جارٍ تحميل امتدادات الشريط الجانبي" } }, - "ja": { + "bs": { "stringUnit": { "state": "translated", - "value": "サイドバー拡張機能を読み込み中" + "value": "Učitavanje ekstenzija bočne trake" } - } - } - }, - "sidebar.extensions.empty.title": { - "extractionState": "manual", - "localizations": { - "en": { + }, + "da": { "stringUnit": { "state": "translated", - "value": "No sidebar extension enabled" + "value": "Indlæser sidebjælkeudvidelser" } }, - "ja": { + "de": { "stringUnit": { "state": "translated", - "value": "有効なサイドバー拡張機能がありません" + "value": "Seitenleisten-Erweiterungen werden geladen" } - } - } - }, - "sidebar.extensions.empty.detail": { - "extractionState": "manual", - "localizations": { + }, "en": { "stringUnit": { "state": "translated", - "value": "Install and enable a CMUX sidebar extension to show it here." + "value": "Loading sidebar extensions" } }, - "ja": { + "es": { "stringUnit": { "state": "translated", - "value": "ここに表示するには、CMUXサイドバー拡張機能をインストールして有効にしてください。" + "value": "Cargando extensiones de la barra lateral" } - } - } - }, - "sidebar.extensions.error": { - "extractionState": "manual", - "localizations": { - "en": { + }, + "fr": { "stringUnit": { "state": "translated", - "value": "CMUX could not load sidebar extensions." + "value": "Chargement des extensions de la barre latérale" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Caricamento delle estensioni della barra laterale" } }, "ja": { "stringUnit": { "state": "translated", - "value": "CMUXはサイドバー拡張機能を読み込めませんでした。" + "value": "サイドバー拡張機能を読み込み中" + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "កំពុងផ្ទុកផ្នែកបន្ថែមរបារចំហៀង" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "사이드바 확장 기능 로드 중" + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "Laster sidefeltutvidelser" + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "Ładowanie rozszerzeń paska bocznego" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Carregando extensões da barra lateral" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Загрузка расширений боковой панели" + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "กำลังโหลดส่วนขยายแถบด้านข้าง" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Kenar çubuğu uzantıları yükleniyor" + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "Завантаження розширень бічної панелі" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "正在加载边栏扩展" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "正在載入側邊欄擴充功能" + } + } + } + }, + "sidebar.extensions.empty.title": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "لا يوجد امتداد شريط جانبي مفعّل" + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "Nijedna ekstenzija bočne trake nije omogućena" + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "Ingen sidebjælkeudvidelse er aktiveret" + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Keine Seitenleisten-Erweiterung aktiviert" + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "No sidebar extension enabled" + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "No hay ninguna extensión de barra lateral activada" + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Aucune extension de barre latérale activée" + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Nessuna estensione della barra laterale abilitata" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "有効なサイドバー拡張機能がありません" + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "មិនមានផ្នែកបន្ថែមរបារចំហៀងបានបើកទេ" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "활성화된 사이드바 확장 기능 없음" + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "Ingen sidefeltutvidelse er aktivert" + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "Brak włączonego rozszerzenia paska bocznego" + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Nenhuma extensão da barra lateral ativada" + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Нет включенного расширения боковой панели" + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "ไม่ได้เปิดใช้ส่วนขยายแถบด้านข้าง" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Etkin kenar çubuğu uzantısı yok" + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "Немає ввімкненого розширення бічної панелі" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "未启用边栏扩展" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "未啟用側邊欄擴充功能" + } + } + } + }, + "sidebar.extensions.empty.detail": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "ثبّت امتداد شريط جانبي لـ CMUX وفعّله لعرضه هنا." + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "Instalirajte i omogućite CMUX ekstenziju bočne trake da bi se prikazala ovdje." + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "Installer og aktivér en CMUX-sidebjælkeudvidelse for at vise den her." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "Installieren und aktivieren Sie eine CMUX-Seitenleisten-Erweiterung, um sie hier anzuzeigen." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "Install and enable a CMUX sidebar extension to show it here." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "Instala y activa una extensión de barra lateral de CMUX para mostrarla aquí." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "Installez et activez une extension de barre latérale CMUX pour l’afficher ici." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "Installa e abilita un’estensione della barra laterale di CMUX per mostrarla qui." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "ここに表示するには、CMUXサイドバー拡張機能をインストールして有効にしてください。" + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "ដំឡើង និងបើកផ្នែកបន្ថែមរបារចំហៀង CMUX ដើម្បីបង្ហាញវានៅទីនេះ។" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "여기에 표시하려면 CMUX 사이드바 확장 기능을 설치하고 활성화하세요." + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "Installer og aktiver en CMUX-sidefeltutvidelse for å vise den her." + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "Zainstaluj i włącz rozszerzenie paska bocznego CMUX, aby wyświetlić je tutaj." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "Instale e ative uma extensão da barra lateral do CMUX para mostrá-la aqui." + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "Установите и включите расширение боковой панели CMUX, чтобы показать его здесь." + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "ติดตั้งและเปิดใช้ส่วนขยายแถบด้านข้าง CMUX เพื่อแสดงที่นี่" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "Burada göstermek için bir CMUX kenar çubuğu uzantısı yükleyip etkinleştirin." + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "Установіть і ввімкніть розширення бічної панелі CMUX, щоб показати його тут." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "安装并启用 CMUX 边栏扩展后,它会显示在这里。" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "安裝並啟用 CMUX 側邊欄擴充功能後,它會顯示在這裡。" + } + } + } + }, + "sidebar.extensions.error": { + "extractionState": "manual", + "localizations": { + "ar": { + "stringUnit": { + "state": "translated", + "value": "تعذر على CMUX تحميل امتدادات الشريط الجانبي." + } + }, + "bs": { + "stringUnit": { + "state": "translated", + "value": "CMUX nije mogao učitati ekstenzije bočne trake." + } + }, + "da": { + "stringUnit": { + "state": "translated", + "value": "CMUX kunne ikke indlæse sidebjælkeudvidelser." + } + }, + "de": { + "stringUnit": { + "state": "translated", + "value": "CMUX konnte Seitenleisten-Erweiterungen nicht laden." + } + }, + "en": { + "stringUnit": { + "state": "translated", + "value": "CMUX could not load sidebar extensions." + } + }, + "es": { + "stringUnit": { + "state": "translated", + "value": "CMUX no pudo cargar las extensiones de la barra lateral." + } + }, + "fr": { + "stringUnit": { + "state": "translated", + "value": "CMUX n’a pas pu charger les extensions de barre latérale." + } + }, + "it": { + "stringUnit": { + "state": "translated", + "value": "CMUX non ha potuto caricare le estensioni della barra laterale." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "CMUXはサイドバー拡張機能を読み込めませんでした。" + } + }, + "km": { + "stringUnit": { + "state": "translated", + "value": "CMUX មិនអាចផ្ទុកផ្នែកបន្ថែមរបារចំហៀងបានទេ។" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "CMUX가 사이드바 확장 기능을 로드할 수 없습니다." + } + }, + "nb": { + "stringUnit": { + "state": "translated", + "value": "CMUX kunne ikke laste sidefeltutvidelser." + } + }, + "pl": { + "stringUnit": { + "state": "translated", + "value": "CMUX nie mógł załadować rozszerzeń paska bocznego." + } + }, + "pt-BR": { + "stringUnit": { + "state": "translated", + "value": "O CMUX não pôde carregar as extensões da barra lateral." + } + }, + "ru": { + "stringUnit": { + "state": "translated", + "value": "CMUX не удалось загрузить расширения боковой панели." + } + }, + "th": { + "stringUnit": { + "state": "translated", + "value": "CMUX ไม่สามารถโหลดส่วนขยายแถบด้านข้างได้" + } + }, + "tr": { + "stringUnit": { + "state": "translated", + "value": "CMUX kenar çubuğu uzantılarını yükleyemedi." + } + }, + "uk": { + "stringUnit": { + "state": "translated", + "value": "CMUX не вдалося завантажити розширення бічної панелі." + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "CMUX 无法加载边栏扩展。" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "CMUX 無法載入側邊欄擴充功能。" } } } - } } } diff --git a/Sources/CMUXInstalledExtensionSidebarHostView.swift b/Sources/CMUXInstalledExtensionSidebarHostView.swift new file mode 100644 index 000000000000..dca9eaeba0d8 --- /dev/null +++ b/Sources/CMUXInstalledExtensionSidebarHostView.swift @@ -0,0 +1,72 @@ +import CMUXExtensionClient +import ExtensionFoundation +import SwiftUI + +struct CMUXInstalledExtensionSidebarHostView: View { + @State private var identity: AppExtensionIdentity? + @State private var isLoading = true + @State private var errorText: String? + + var body: some View { + Group { + if let identity { + CMUXSidebarExtensionHostView(identity: identity) + .accessibilityIdentifier("CMUXExtensionSidebarHostView") + } else { + VStack(alignment: .leading, spacing: 10) { + if isLoading { + ProgressView() + .controlSize(.small) + Text(String(localized: "sidebar.extensions.loading", defaultValue: "Loading sidebar extensions")) + .font(.system(size: 12)) + .foregroundStyle(.secondary) + } else { + Image(systemName: "puzzlepiece.extension") + .font(.system(size: 22, weight: .regular)) + .foregroundStyle(.secondary) + Text(String(localized: "sidebar.extensions.empty.title", defaultValue: "No sidebar extension enabled")) + .font(.system(size: 13, weight: .medium)) + .foregroundStyle(.primary) + Text(errorText ?? String( + localized: "sidebar.extensions.empty.detail", + defaultValue: "Install and enable a CMUX sidebar extension to show it here." + )) + .font(.system(size: 12)) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + } + .padding(.horizontal, 14) + .padding(.top, SidebarWorkspaceScrollInsets.workspaceList.top + 12) + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) + .accessibilityIdentifier("CMUXExtensionSidebarEmptyState") + } + } + .task { + await loadExtension() + } + } + + private func loadExtension() async { + isLoading = true + errorText = nil + do { + let update = try await Task.detached(priority: .userInitiated) { + var identities = try AppExtensionIdentity.matching( + appExtensionPointIDs: CMUXSidebarExtensionPoint.identifier + ) + .makeAsyncIterator() + return await identities.next() ?? [] + }.value + identity = update.sorted { $0.localizedName < $1.localizedName }.first + isLoading = false + } catch { + identity = nil + isLoading = false + errorText = String( + localized: "sidebar.extensions.error", + defaultValue: "CMUX could not load sidebar extensions." + ) + } + } +} diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index f82b0a54288a..d17afd2cb3bc 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -1,9 +1,7 @@ import AppKit import Bonsplit -import CMUXExtensionClient import Combine import CmuxExtensionKit -import ExtensionFoundation import ImageIO import Observation import SwiftUI @@ -13930,73 +13928,6 @@ private struct ExtensionSidebarBrowserStackEmptyArea: View { } } -private struct CMUXInstalledExtensionSidebarHostView: View { - @State private var identity: AppExtensionIdentity? - @State private var isLoading = true - @State private var errorText: String? - - var body: some View { - Group { - if let identity { - CMUXSidebarExtensionHostView(identity: identity) - .accessibilityIdentifier("CMUXExtensionSidebarHostView") - } else { - VStack(alignment: .leading, spacing: 10) { - if isLoading { - ProgressView() - .controlSize(.small) - Text(String(localized: "sidebar.extensions.loading", defaultValue: "Loading sidebar extensions")) - .font(.system(size: 12)) - .foregroundStyle(.secondary) - } else { - Image(systemName: "puzzlepiece.extension") - .font(.system(size: 22, weight: .regular)) - .foregroundStyle(.secondary) - Text(String(localized: "sidebar.extensions.empty.title", defaultValue: "No sidebar extension enabled")) - .font(.system(size: 13, weight: .medium)) - .foregroundStyle(.primary) - Text(errorText ?? String( - localized: "sidebar.extensions.empty.detail", - defaultValue: "Install and enable a CMUX sidebar extension to show it here." - )) - .font(.system(size: 12)) - .foregroundStyle(.secondary) - .fixedSize(horizontal: false, vertical: true) - } - } - .padding(.horizontal, 14) - .padding(.top, SidebarWorkspaceScrollInsets.workspaceList.top + 12) - .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) - .accessibilityIdentifier("CMUXExtensionSidebarEmptyState") - } - } - .task { - await loadExtension() - } - } - - private func loadExtension() async { - isLoading = true - errorText = nil - do { - var identities = try AppExtensionIdentity.matching( - appExtensionPointIDs: CMUXSidebarExtensionPoint.identifier - ) - .makeAsyncIterator() - let update = await identities.next() ?? [] - identity = update.sorted { $0.localizedName < $1.localizedName }.first - isLoading = false - } catch { - identity = nil - isLoading = false - errorText = String( - localized: "sidebar.extensions.error", - defaultValue: "CMUX could not load sidebar extensions." - ) - } - } -} - enum SidebarWorkspaceShortcutHintMetrics { private static let measurementFont = NSFont.systemFont(ofSize: 10, weight: .semibold) private static let minimumSlotWidth: CGFloat = 28 diff --git a/cmux.xcodeproj/project.pbxproj b/cmux.xcodeproj/project.pbxproj index 28e2c87fb9e7..2379a0b71ef6 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -142,6 +142,7 @@ C0DE45000000000000000001 /* CmuxExtensionKit in Frameworks */ = {isa = PBXBuildFile; productRef = C0DE45000000000000000002 /* CmuxExtensionKit */; }; C0DE34020000000000000001 /* CmuxHelpCommands.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE34020000000000000003 /* CmuxHelpCommands.swift */; }; C0DE34020000000000000002 /* CmuxHelpResource.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE34020000000000000004 /* CmuxHelpResource.swift */; }; + C0DE46010000000000000001 /* CMUXInstalledExtensionSidebarHostView.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE46010000000000000002 /* CMUXInstalledExtensionSidebarHostView.swift */; }; E7E00000000000000000000B /* CmuxLifecycleEventPublishing.swift in Sources */ = {isa = PBXBuildFile; fileRef = E7E00000000000000000000C /* CmuxLifecycleEventPublishing.swift */; }; 2F0C07000000000000000002 /* CmuxMainWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F0C07000000000000000001 /* CmuxMainWindow.swift */; }; C0DE31390000000000000101 /* CMUXOpenCommandTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE31390000000000000102 /* CMUXOpenCommandTests.swift */; }; @@ -743,6 +744,7 @@ E7E000000000000000000002 /* CmuxEventStream.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CmuxEventStream.swift; sourceTree = ""; }; C0DE34020000000000000003 /* CmuxHelpCommands.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = App/CmuxHelpCommands.swift; sourceTree = ""; }; C0DE34020000000000000004 /* CmuxHelpResource.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = App/CmuxHelpResource.swift; sourceTree = ""; }; + C0DE46010000000000000002 /* CMUXInstalledExtensionSidebarHostView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CMUXInstalledExtensionSidebarHostView.swift; sourceTree = ""; }; E7E00000000000000000000C /* CmuxLifecycleEventPublishing.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CmuxLifecycleEventPublishing.swift; sourceTree = ""; }; 2F0C07000000000000000001 /* CmuxMainWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = App/CmuxMainWindow.swift; sourceTree = ""; }; C0DE31390000000000000102 /* CMUXOpenCommandTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CMUXOpenCommandTests.swift; sourceTree = ""; }; @@ -1322,6 +1324,7 @@ B37A00000000000000000008 /* SettingsCardNote.swift */, C0DE35860000000000000002 /* BackgroundWorkspacePrimeCoordinator.swift */, A5001012 /* ContentView.swift */, + C0DE46010000000000000002 /* CMUXInstalledExtensionSidebarHostView.swift */, E4C001000000000000000002 /* ExtensionSidebarWorkspaceRowView.swift */, E4C001000000000000000004 /* ExtensionWorktreePrototype.swift */, C0DE36230000000000000002 /* WorkspaceFinderDirectoryResolver.swift */, @@ -2147,6 +2150,7 @@ E7E000000000000000000001 /* CmuxEventStream.swift in Sources */, C0DE34020000000000000001 /* CmuxHelpCommands.swift in Sources */, C0DE34020000000000000002 /* CmuxHelpResource.swift in Sources */, + C0DE46010000000000000001 /* CMUXInstalledExtensionSidebarHostView.swift in Sources */, E7E00000000000000000000B /* CmuxLifecycleEventPublishing.swift in Sources */, 2F0C07000000000000000002 /* CmuxMainWindow.swift in Sources */, D3610C010000000000000001 /* CmuxSettingsJSONPathSupport.swift in Sources */, From 2fc7dd980276f4c8609f7eefb2d42fa2b13f08bb Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Fri, 29 May 2026 15:29:48 -0500 Subject: [PATCH 03/44] Split sidebar ExtensionKit sources --- .../CMUXExtensionClient.swift | 240 ------------------ .../CMUXInstalledSidebarExtension.swift | 28 ++ .../CMUXSidebarExtensionDiscovery.swift | 29 +++ .../CMUXSidebarExtensionHostView.swift | 67 +++++ .../CMUXSidebarExtensionPoint.swift | 7 + .../CMUXSidebarExtensionRecord.swift | 29 +++ .../CMUXSidebarExtensionRegistry.swift | 38 +++ .../CMUXSidebarExtensionSession.swift | 48 ++++ .../CMUXExtensionAPIVersion.swift | 18 ++ .../CMUXExtensionManifest.swift | 35 +++ .../CMUXExtensionValidator.swift | 31 +++ .../CmuxExtensionKit/CMUXSidebarActions.swift | 19 ++ .../CMUXSidebarExtension.swift | 21 ++ .../CMUXSidebarSnapshot.swift | 63 +++++ .../CmuxExtensionKit/CmuxExtensionKit.swift | 232 ----------------- .../CmuxExtensionSidebarProvider.swift | 51 ++++ 16 files changed, 484 insertions(+), 472 deletions(-) delete mode 100644 Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/CMUXExtensionClient.swift create mode 100644 Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/CMUXInstalledSidebarExtension.swift create mode 100644 Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/CMUXSidebarExtensionDiscovery.swift create mode 100644 Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/CMUXSidebarExtensionHostView.swift create mode 100644 Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/CMUXSidebarExtensionPoint.swift create mode 100644 Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/CMUXSidebarExtensionRecord.swift create mode 100644 Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/CMUXSidebarExtensionRegistry.swift create mode 100644 Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/CMUXSidebarExtensionSession.swift create mode 100644 Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CMUXExtensionAPIVersion.swift create mode 100644 Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CMUXExtensionManifest.swift create mode 100644 Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CMUXExtensionValidator.swift create mode 100644 Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CMUXSidebarActions.swift create mode 100644 Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CMUXSidebarExtension.swift create mode 100644 Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CMUXSidebarSnapshot.swift delete mode 100644 Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CmuxExtensionKit.swift create mode 100644 Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CmuxExtensionSidebarProvider.swift diff --git a/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/CMUXExtensionClient.swift b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/CMUXExtensionClient.swift deleted file mode 100644 index fddfaf689061..000000000000 --- a/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/CMUXExtensionClient.swift +++ /dev/null @@ -1,240 +0,0 @@ -import CmuxExtensionKit -import ExtensionFoundation -import ExtensionKit -import Foundation -import SwiftUI - -/// Public identifiers for the CMUX sidebar ExtensionKit surface. -public enum CMUXSidebarExtensionPoint { - /// Extension point identifier third-party sidebar extensions register against. - public static let identifier = "com.manaflow.cmux.sidebar" - /// Default ExtensionKit scene identifier hosted inside the cmux sidebar. - public static let defaultSceneID = "sidebar" -} - -/// A sidebar extension registered with the host. -public struct CMUXSidebarExtensionRecord: Equatable, Identifiable, Sendable { - /// Stable extension identifier from the manifest. - public var id: String { manifest.id } - /// Manifest describing the extension contract and requested scopes. - public var manifest: CMUXExtensionManifest - /// Whether the extension is provided by cmux rather than a third party. - public var isHostProvided: Bool - - /// Creates a sidebar extension record. - /// - Parameters: - /// - manifest: Manifest describing the extension. - /// - isHostProvided: Whether cmux provides the extension. - public init(manifest: CMUXExtensionManifest, isHostProvided: Bool) { - self.manifest = manifest - self.isHostProvided = isHostProvided - } -} - -/// Errors raised by the sidebar extension host client. -public enum CMUXExtensionClientError: Error, Equatable, Sendable { - /// More than one extension used the same manifest identifier. - case duplicateExtensionIdentifier(String) - /// No registered extension matched the requested identifier. - case extensionNotFound(String) -} - -/// Validated collection of sidebar extensions available to the host. -public struct CMUXSidebarExtensionRegistry: Sendable { - private var recordsByID: [String: CMUXSidebarExtensionRecord] - - /// Creates a registry from extension records. - /// - Parameter records: Records to validate and store by identifier. - /// - Throws: `CMUXExtensionClientError.duplicateExtensionIdentifier` for duplicate ids, or manifest validation errors. - public init(records: [CMUXSidebarExtensionRecord] = []) throws { - var recordsByID: [String: CMUXSidebarExtensionRecord] = [:] - for record in records { - try CMUXExtensionValidator.validateSidebarManifest(record.manifest) - if recordsByID[record.id] != nil { - throw CMUXExtensionClientError.duplicateExtensionIdentifier(record.id) - } - recordsByID[record.id] = record - } - self.recordsByID = recordsByID - } - - /// Records sorted by display name for deterministic presentation. - public var records: [CMUXSidebarExtensionRecord] { - recordsByID.values.sorted { $0.manifest.displayName < $1.manifest.displayName } - } - - /// Looks up one extension record. - /// - Parameter id: Manifest identifier to find. - /// - Returns: Matching record. - /// - Throws: `CMUXExtensionClientError.extensionNotFound` when no record exists. - public func record(id: String) throws -> CMUXSidebarExtensionRecord { - guard let record = recordsByID[id] else { - throw CMUXExtensionClientError.extensionNotFound(id) - } - return record - } -} - -/// Host-side session that mediates snapshot refreshes and action dispatch for one sidebar extension. -public actor CMUXSidebarExtensionSession { - private let manifest: CMUXExtensionManifest - private let client: CMUXSidebarHostClient - private var latestSnapshot: CMUXSidebarSnapshot? - - /// Creates a sidebar extension session. - /// - Parameters: - /// - manifest: Manifest for the extension attached to this session. - /// - client: Host callbacks used to fetch snapshots and dispatch actions. - /// - Throws: Manifest validation errors. - public init(manifest: CMUXExtensionManifest, client: CMUXSidebarHostClient) throws { - try CMUXExtensionValidator.validateSidebarManifest(manifest) - self.manifest = manifest - self.client = client - } - - /// Fetches and caches the latest sidebar snapshot. - /// - Returns: Snapshot returned by the host client. - /// - Throws: Errors thrown by the host snapshot callback. - public func refreshSnapshot() async throws -> CMUXSidebarSnapshot { - let snapshot = try await client.snapshot() - latestSnapshot = snapshot - return snapshot - } - - /// Dispatches an extension action to the host. - /// - Parameter action: Sidebar action requested by the extension UI. - /// - Returns: Host action result. - /// - Throws: Errors thrown by the host dispatch callback. - public func perform(_ action: CMUXSidebarAction) async throws -> CMUXExtensionActionResult { - try await client.dispatch(action) - } - - /// Manifest associated with this session. - public var extensionManifest: CMUXExtensionManifest { - manifest - } - - /// Last snapshot returned by `refreshSnapshot()`, if any. - /// - Returns: Cached sidebar snapshot. - public func cachedSnapshot() -> CMUXSidebarSnapshot? { - latestSnapshot - } -} - -/// Installed ExtensionKit sidebar extension discovered on the current Mac. -public struct CMUXInstalledSidebarExtension: Identifiable, Equatable, Sendable { - /// Stable bundle identifier used for SwiftUI identity. - public var id: String { bundleIdentifier } - /// Extension bundle identifier. - public var bundleIdentifier: String - /// Localized extension display name. - public var localizedName: String - /// Extension point identifier declared by the extension. - public var extensionPointIdentifier: String - - /// Creates an installed extension summary. - /// - Parameters: - /// - bundleIdentifier: Extension bundle identifier. - /// - localizedName: Localized extension display name. - /// - extensionPointIdentifier: Extension point identifier declared by the extension. - public init( - bundleIdentifier: String, - localizedName: String, - extensionPointIdentifier: String - ) { - self.bundleIdentifier = bundleIdentifier - self.localizedName = localizedName - self.extensionPointIdentifier = extensionPointIdentifier - } -} - -@available(macOS 14.0, *) -/// Discovers installed sidebar extensions that match CMUX's ExtensionKit point. -public struct CMUXSidebarExtensionDiscovery { - /// Creates an extension discovery helper. - public init() {} - - /// Lists installed sidebar extensions. - /// - Parameter extensionPointIdentifier: Extension point identifier to match. - /// - Returns: Installed extensions sorted by localized name. - /// - Throws: Errors thrown by ExtensionFoundation discovery. - public func installedExtensions( - extensionPointIdentifier: String = CMUXSidebarExtensionPoint.identifier - ) async throws -> [CMUXInstalledSidebarExtension] { - var identities = try AppExtensionIdentity.matching(appExtensionPointIDs: extensionPointIdentifier) - .makeAsyncIterator() - guard let update = await identities.next() else { return [] } - return update.map { - CMUXInstalledSidebarExtension( - bundleIdentifier: $0.bundleIdentifier, - localizedName: $0.localizedName, - extensionPointIdentifier: $0.extensionPointIdentifier - ) - } - .sorted { $0.localizedName < $1.localizedName } - } -} - -@available(macOS 14.0, *) -/// SwiftUI bridge that hosts a sidebar extension scene through ExtensionKit. -public struct CMUXSidebarExtensionHostView: NSViewControllerRepresentable { - public typealias NSViewControllerType = EXHostViewController - - /// Tracks the configuration currently installed on the host view controller. - public final class Coordinator { - fileprivate var currentKey: HostConfigurationKey? - } - - fileprivate struct HostConfigurationKey: Equatable { - var bundleIdentifier: String - var sceneID: String - } - - private let identity: AppExtensionIdentity - private let sceneID: String - - /// Creates a sidebar extension host view. - /// - Parameters: - /// - identity: Extension identity to host. - /// - sceneID: ExtensionKit scene identifier to render. - public init(identity: AppExtensionIdentity, sceneID: String = CMUXSidebarExtensionPoint.defaultSceneID) { - self.identity = identity - self.sceneID = sceneID - } - - /// Creates the configuration-tracking coordinator. - /// - Returns: Coordinator for the hosted extension configuration. - public func makeCoordinator() -> Coordinator { - Coordinator() - } - - /// Creates the ExtensionKit host view controller. - /// - Parameter context: SwiftUI representable context. - /// - Returns: Configured `EXHostViewController`. - public func makeNSViewController(context: Context) -> EXHostViewController { - let viewController = EXHostViewController() - context.coordinator.currentKey = configurationKey - viewController.configuration = EXHostViewController.Configuration( - appExtension: identity, - sceneID: sceneID - ) - return viewController - } - - /// Updates the host view controller when the hosted extension changes. - /// - Parameters: - /// - viewController: Existing ExtensionKit host view controller. - /// - context: SwiftUI representable context. - public func updateNSViewController(_ viewController: EXHostViewController, context: Context) { - guard context.coordinator.currentKey != configurationKey else { return } - context.coordinator.currentKey = configurationKey - viewController.configuration = EXHostViewController.Configuration( - appExtension: identity, - sceneID: sceneID - ) - } - - private var configurationKey: HostConfigurationKey { - HostConfigurationKey(bundleIdentifier: identity.bundleIdentifier, sceneID: sceneID) - } -} diff --git a/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/CMUXInstalledSidebarExtension.swift b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/CMUXInstalledSidebarExtension.swift new file mode 100644 index 000000000000..10d7e9fad5a0 --- /dev/null +++ b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/CMUXInstalledSidebarExtension.swift @@ -0,0 +1,28 @@ +import Foundation + +/// Installed ExtensionKit sidebar extension discovered on the current Mac. +public struct CMUXInstalledSidebarExtension: Identifiable, Equatable, Sendable { + /// Stable bundle identifier used for SwiftUI identity. + public var id: String { bundleIdentifier } + /// Extension bundle identifier. + public var bundleIdentifier: String + /// Localized extension display name. + public var localizedName: String + /// Extension point identifier declared by the extension. + public var extensionPointIdentifier: String + + /// Creates an installed extension summary. + /// - Parameters: + /// - bundleIdentifier: Extension bundle identifier. + /// - localizedName: Localized extension display name. + /// - extensionPointIdentifier: Extension point identifier declared by the extension. + public init( + bundleIdentifier: String, + localizedName: String, + extensionPointIdentifier: String + ) { + self.bundleIdentifier = bundleIdentifier + self.localizedName = localizedName + self.extensionPointIdentifier = extensionPointIdentifier + } +} diff --git a/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/CMUXSidebarExtensionDiscovery.swift b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/CMUXSidebarExtensionDiscovery.swift new file mode 100644 index 000000000000..6b3b651e5f55 --- /dev/null +++ b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/CMUXSidebarExtensionDiscovery.swift @@ -0,0 +1,29 @@ +import ExtensionFoundation +import Foundation + +@available(macOS 14.0, *) +/// Discovers installed sidebar extensions that match CMUX's ExtensionKit point. +public struct CMUXSidebarExtensionDiscovery { + /// Creates an extension discovery helper. + public init() {} + + /// Lists installed sidebar extensions. + /// - Parameter extensionPointIdentifier: Extension point identifier to match. + /// - Returns: Installed extensions sorted by localized name. + /// - Throws: Errors thrown by ExtensionFoundation discovery. + public func installedExtensions( + extensionPointIdentifier: String = CMUXSidebarExtensionPoint.identifier + ) async throws -> [CMUXInstalledSidebarExtension] { + var identities = try AppExtensionIdentity.matching(appExtensionPointIDs: extensionPointIdentifier) + .makeAsyncIterator() + guard let update = await identities.next() else { return [] } + return update.map { + CMUXInstalledSidebarExtension( + bundleIdentifier: $0.bundleIdentifier, + localizedName: $0.localizedName, + extensionPointIdentifier: $0.extensionPointIdentifier + ) + } + .sorted { $0.localizedName < $1.localizedName } + } +} diff --git a/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/CMUXSidebarExtensionHostView.swift b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/CMUXSidebarExtensionHostView.swift new file mode 100644 index 000000000000..de57d4a5f815 --- /dev/null +++ b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/CMUXSidebarExtensionHostView.swift @@ -0,0 +1,67 @@ +import ExtensionFoundation +import ExtensionKit +import SwiftUI + +@available(macOS 14.0, *) +/// SwiftUI bridge that hosts a sidebar extension scene through ExtensionKit. +public struct CMUXSidebarExtensionHostView: NSViewControllerRepresentable { + public typealias NSViewControllerType = EXHostViewController + + /// Tracks the configuration currently installed on the host view controller. + public final class Coordinator { + fileprivate var currentKey: HostConfigurationKey? + } + + fileprivate struct HostConfigurationKey: Equatable { + var bundleIdentifier: String + var sceneID: String + } + + private let identity: AppExtensionIdentity + private let sceneID: String + + /// Creates a sidebar extension host view. + /// - Parameters: + /// - identity: Extension identity to host. + /// - sceneID: ExtensionKit scene identifier to render. + public init(identity: AppExtensionIdentity, sceneID: String = CMUXSidebarExtensionPoint.defaultSceneID) { + self.identity = identity + self.sceneID = sceneID + } + + /// Creates the configuration-tracking coordinator. + /// - Returns: Coordinator for the hosted extension configuration. + public func makeCoordinator() -> Coordinator { + Coordinator() + } + + /// Creates the ExtensionKit host view controller. + /// - Parameter context: SwiftUI representable context. + /// - Returns: Configured `EXHostViewController`. + public func makeNSViewController(context: Context) -> EXHostViewController { + let viewController = EXHostViewController() + context.coordinator.currentKey = configurationKey + viewController.configuration = EXHostViewController.Configuration( + appExtension: identity, + sceneID: sceneID + ) + return viewController + } + + /// Updates the host view controller when the hosted extension changes. + /// - Parameters: + /// - viewController: Existing ExtensionKit host view controller. + /// - context: SwiftUI representable context. + public func updateNSViewController(_ viewController: EXHostViewController, context: Context) { + guard context.coordinator.currentKey != configurationKey else { return } + context.coordinator.currentKey = configurationKey + viewController.configuration = EXHostViewController.Configuration( + appExtension: identity, + sceneID: sceneID + ) + } + + private var configurationKey: HostConfigurationKey { + HostConfigurationKey(bundleIdentifier: identity.bundleIdentifier, sceneID: sceneID) + } +} diff --git a/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/CMUXSidebarExtensionPoint.swift b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/CMUXSidebarExtensionPoint.swift new file mode 100644 index 000000000000..dbb178ac46d6 --- /dev/null +++ b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/CMUXSidebarExtensionPoint.swift @@ -0,0 +1,7 @@ +/// Public identifiers for the CMUX sidebar ExtensionKit surface. +public enum CMUXSidebarExtensionPoint { + /// Extension point identifier third-party sidebar extensions register against. + public static let identifier = "com.manaflow.cmux.sidebar" + /// Default ExtensionKit scene identifier hosted inside the cmux sidebar. + public static let defaultSceneID = "sidebar" +} diff --git a/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/CMUXSidebarExtensionRecord.swift b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/CMUXSidebarExtensionRecord.swift new file mode 100644 index 000000000000..a59c56f8108f --- /dev/null +++ b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/CMUXSidebarExtensionRecord.swift @@ -0,0 +1,29 @@ +import CmuxExtensionKit +import Foundation + +/// A sidebar extension registered with the host. +public struct CMUXSidebarExtensionRecord: Equatable, Identifiable, Sendable { + /// Stable extension identifier from the manifest. + public var id: String { manifest.id } + /// Manifest describing the extension contract and requested scopes. + public var manifest: CMUXExtensionManifest + /// Whether the extension is provided by cmux rather than a third party. + public var isHostProvided: Bool + + /// Creates a sidebar extension record. + /// - Parameters: + /// - manifest: Manifest describing the extension. + /// - isHostProvided: Whether cmux provides the extension. + public init(manifest: CMUXExtensionManifest, isHostProvided: Bool) { + self.manifest = manifest + self.isHostProvided = isHostProvided + } +} + +/// Errors raised by the sidebar extension host client. +public enum CMUXExtensionClientError: Error, Equatable, Sendable { + /// More than one extension used the same manifest identifier. + case duplicateExtensionIdentifier(String) + /// No registered extension matched the requested identifier. + case extensionNotFound(String) +} diff --git a/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/CMUXSidebarExtensionRegistry.swift b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/CMUXSidebarExtensionRegistry.swift new file mode 100644 index 000000000000..ee48a55f9b79 --- /dev/null +++ b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/CMUXSidebarExtensionRegistry.swift @@ -0,0 +1,38 @@ +import CmuxExtensionKit +import Foundation + +/// Validated collection of sidebar extensions available to the host. +public struct CMUXSidebarExtensionRegistry: Sendable { + private var recordsByID: [String: CMUXSidebarExtensionRecord] + + /// Creates a registry from extension records. + /// - Parameter records: Records to validate and store by identifier. + /// - Throws: `CMUXExtensionClientError.duplicateExtensionIdentifier` for duplicate ids, or manifest validation errors. + public init(records: [CMUXSidebarExtensionRecord] = []) throws { + var recordsByID: [String: CMUXSidebarExtensionRecord] = [:] + for record in records { + try CMUXExtensionValidator.validateSidebarManifest(record.manifest) + if recordsByID[record.id] != nil { + throw CMUXExtensionClientError.duplicateExtensionIdentifier(record.id) + } + recordsByID[record.id] = record + } + self.recordsByID = recordsByID + } + + /// Records sorted by display name for deterministic presentation. + public var records: [CMUXSidebarExtensionRecord] { + recordsByID.values.sorted { $0.manifest.displayName < $1.manifest.displayName } + } + + /// Looks up one extension record. + /// - Parameter id: Manifest identifier to find. + /// - Returns: Matching record. + /// - Throws: `CMUXExtensionClientError.extensionNotFound` when no record exists. + public func record(id: String) throws -> CMUXSidebarExtensionRecord { + guard let record = recordsByID[id] else { + throw CMUXExtensionClientError.extensionNotFound(id) + } + return record + } +} diff --git a/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/CMUXSidebarExtensionSession.swift b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/CMUXSidebarExtensionSession.swift new file mode 100644 index 000000000000..e41b57b08301 --- /dev/null +++ b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/CMUXSidebarExtensionSession.swift @@ -0,0 +1,48 @@ +import CmuxExtensionKit +import Foundation + +/// Host-side session that mediates snapshot refreshes and action dispatch for one sidebar extension. +public actor CMUXSidebarExtensionSession { + private let manifest: CMUXExtensionManifest + private let client: CMUXSidebarHostClient + private var latestSnapshot: CMUXSidebarSnapshot? + + /// Creates a sidebar extension session. + /// - Parameters: + /// - manifest: Manifest for the extension attached to this session. + /// - client: Host callbacks used to fetch snapshots and dispatch actions. + /// - Throws: Manifest validation errors. + public init(manifest: CMUXExtensionManifest, client: CMUXSidebarHostClient) throws { + try CMUXExtensionValidator.validateSidebarManifest(manifest) + self.manifest = manifest + self.client = client + } + + /// Fetches and caches the latest sidebar snapshot. + /// - Returns: Snapshot returned by the host client. + /// - Throws: Errors thrown by the host snapshot callback. + public func refreshSnapshot() async throws -> CMUXSidebarSnapshot { + let snapshot = try await client.snapshot() + latestSnapshot = snapshot + return snapshot + } + + /// Dispatches an extension action to the host. + /// - Parameter action: Sidebar action requested by the extension UI. + /// - Returns: Host action result. + /// - Throws: Errors thrown by the host dispatch callback. + public func perform(_ action: CMUXSidebarAction) async throws -> CMUXExtensionActionResult { + try await client.dispatch(action) + } + + /// Manifest associated with this session. + public var extensionManifest: CMUXExtensionManifest { + manifest + } + + /// Last snapshot returned by `refreshSnapshot()`, if any. + /// - Returns: Cached sidebar snapshot. + public func cachedSnapshot() -> CMUXSidebarSnapshot? { + latestSnapshot + } +} diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CMUXExtensionAPIVersion.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CMUXExtensionAPIVersion.swift new file mode 100644 index 000000000000..6f94c25989f5 --- /dev/null +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CMUXExtensionAPIVersion.swift @@ -0,0 +1,18 @@ +import Foundation + +public struct CMUXExtensionAPIVersion: Codable, Comparable, Equatable, Sendable { + public var major: Int + public var minor: Int + + public init(major: Int, minor: Int) { + self.major = major + self.minor = minor + } + + public static let sidebarV1 = CMUXExtensionAPIVersion(major: 1, minor: 0) + + public static func < (lhs: CMUXExtensionAPIVersion, rhs: CMUXExtensionAPIVersion) -> Bool { + if lhs.major != rhs.major { return lhs.major < rhs.major } + return lhs.minor < rhs.minor + } +} diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CMUXExtensionManifest.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CMUXExtensionManifest.swift new file mode 100644 index 000000000000..a02081d79d90 --- /dev/null +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CMUXExtensionManifest.swift @@ -0,0 +1,35 @@ +import Foundation + +public enum CMUXExtensionKind: String, Codable, CaseIterable, Equatable, Sendable { + case sidebar +} + +public struct CMUXExtensionManifest: Codable, Equatable, Identifiable, Sendable { + public var id: String + public var displayName: String + public var kind: CMUXExtensionKind + public var minimumAPIVersion: CMUXExtensionAPIVersion + public var requestedScopes: [CMUXExtensionScope] + + public init( + id: String, + displayName: String, + kind: CMUXExtensionKind = .sidebar, + minimumAPIVersion: CMUXExtensionAPIVersion = .sidebarV1, + requestedScopes: [CMUXExtensionScope] = [.workspaceMetadata] + ) { + self.id = id + self.displayName = displayName + self.kind = kind + self.minimumAPIVersion = minimumAPIVersion + self.requestedScopes = requestedScopes + } +} + +public enum CMUXExtensionScope: String, Codable, CaseIterable, Equatable, Sendable { + case workspaceMetadata + case workspacePaths + case notifications + case networkPorts + case pullRequests +} diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CMUXExtensionValidator.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CMUXExtensionValidator.swift new file mode 100644 index 000000000000..1ebe8caad588 --- /dev/null +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CMUXExtensionValidator.swift @@ -0,0 +1,31 @@ +import Foundation + +public enum CMUXExtensionValidationError: Error, Equatable, Sendable { + case unsupportedKind(CMUXExtensionKind) + case unsupportedAPIVersion(requested: CMUXExtensionAPIVersion, supported: CMUXExtensionAPIVersion) + case emptyIdentifier + case emptyDisplayName +} + +public enum CMUXExtensionValidator { + public static func validateSidebarManifest( + _ manifest: CMUXExtensionManifest, + supportedAPIVersion: CMUXExtensionAPIVersion = .sidebarV1 + ) throws { + guard manifest.id.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == false else { + throw CMUXExtensionValidationError.emptyIdentifier + } + guard manifest.displayName.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == false else { + throw CMUXExtensionValidationError.emptyDisplayName + } + guard manifest.kind == .sidebar else { + throw CMUXExtensionValidationError.unsupportedKind(manifest.kind) + } + guard manifest.minimumAPIVersion <= supportedAPIVersion else { + throw CMUXExtensionValidationError.unsupportedAPIVersion( + requested: manifest.minimumAPIVersion, + supported: supportedAPIVersion + ) + } + } +} diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CMUXSidebarActions.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CMUXSidebarActions.swift new file mode 100644 index 000000000000..d4a5dee92ad1 --- /dev/null +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CMUXSidebarActions.swift @@ -0,0 +1,19 @@ +import Foundation + +public enum CMUXSidebarAction: Codable, Equatable, Sendable { + case selectWorkspace(UUID) + case closeWorkspace(UUID) + case openURL(String) +} + +public struct CMUXExtensionActionResult: Codable, Equatable, Sendable { + public var accepted: Bool + public var message: String? + + public init(accepted: Bool, message: String? = nil) { + self.accepted = accepted + self.message = message + } + + public static let accepted = CMUXExtensionActionResult(accepted: true) +} diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CMUXSidebarExtension.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CMUXSidebarExtension.swift new file mode 100644 index 000000000000..9e7e5b969c6a --- /dev/null +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CMUXSidebarExtension.swift @@ -0,0 +1,21 @@ +import Foundation + +public protocol CMUXSidebarExtension: Sendable { + var manifest: CMUXExtensionManifest { get } + + func makeInitialSnapshot() async throws -> CMUXSidebarSnapshot + func handle(_ action: CMUXSidebarAction) async throws -> CMUXExtensionActionResult +} + +public struct CMUXSidebarHostClient: Sendable { + public var snapshot: @Sendable () async throws -> CMUXSidebarSnapshot + public var dispatch: @Sendable (CMUXSidebarAction) async throws -> CMUXExtensionActionResult + + public init( + snapshot: @escaping @Sendable () async throws -> CMUXSidebarSnapshot, + dispatch: @escaping @Sendable (CMUXSidebarAction) async throws -> CMUXExtensionActionResult + ) { + self.snapshot = snapshot + self.dispatch = dispatch + } +} diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CMUXSidebarSnapshot.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CMUXSidebarSnapshot.swift new file mode 100644 index 000000000000..bfaa68594328 --- /dev/null +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CMUXSidebarSnapshot.swift @@ -0,0 +1,63 @@ +import Foundation + +public struct CMUXSidebarSnapshot: Codable, Equatable, Sendable { + public var apiVersion: CMUXExtensionAPIVersion + public var sequence: UInt64 + public var windowID: UUID? + public var selectedWorkspaceID: UUID? + public var workspaces: [CMUXSidebarWorkspace] + + public init( + apiVersion: CMUXExtensionAPIVersion = .sidebarV1, + sequence: UInt64, + windowID: UUID? = nil, + selectedWorkspaceID: UUID?, + workspaces: [CMUXSidebarWorkspace] + ) { + self.apiVersion = apiVersion + self.sequence = sequence + self.windowID = windowID + self.selectedWorkspaceID = selectedWorkspaceID + self.workspaces = workspaces + } +} + +public struct CMUXSidebarWorkspace: Codable, Equatable, Identifiable, Sendable { + public var id: UUID + public var title: String + public var detail: String? + public var isPinned: Bool + public var rootPath: String? + public var projectRootPath: String? + public var gitBranch: String? + public var unreadCount: Int + public var latestNotification: String? + public var listeningPorts: [Int] + public var pullRequestURLs: [String] + + public init( + id: UUID, + title: String, + detail: String? = nil, + isPinned: Bool = false, + rootPath: String? = nil, + projectRootPath: String? = nil, + gitBranch: String? = nil, + unreadCount: Int = 0, + latestNotification: String? = nil, + listeningPorts: [Int] = [], + pullRequestURLs: [String] = [] + ) { + self.id = id + self.title = title + self.detail = detail + self.isPinned = isPinned + self.rootPath = rootPath + self.projectRootPath = projectRootPath + self.gitBranch = gitBranch + self.unreadCount = unreadCount + self.latestNotification = latestNotification + self.listeningPorts = listeningPorts + self.pullRequestURLs = pullRequestURLs + } +} diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CmuxExtensionKit.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CmuxExtensionKit.swift deleted file mode 100644 index 34adf0b80baf..000000000000 --- a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CmuxExtensionKit.swift +++ /dev/null @@ -1,232 +0,0 @@ -import Foundation - -public struct CMUXExtensionAPIVersion: Codable, Comparable, Equatable, Sendable { - public var major: Int - public var minor: Int - - public init(major: Int, minor: Int) { - self.major = major - self.minor = minor - } - - public static let sidebarV1 = CMUXExtensionAPIVersion(major: 1, minor: 0) - - public static func < (lhs: CMUXExtensionAPIVersion, rhs: CMUXExtensionAPIVersion) -> Bool { - if lhs.major != rhs.major { return lhs.major < rhs.major } - return lhs.minor < rhs.minor - } -} - -public enum CMUXExtensionKind: String, Codable, CaseIterable, Equatable, Sendable { - case sidebar -} - -public struct CMUXExtensionManifest: Codable, Equatable, Identifiable, Sendable { - public var id: String - public var displayName: String - public var kind: CMUXExtensionKind - public var minimumAPIVersion: CMUXExtensionAPIVersion - public var requestedScopes: [CMUXExtensionScope] - - public init( - id: String, - displayName: String, - kind: CMUXExtensionKind = .sidebar, - minimumAPIVersion: CMUXExtensionAPIVersion = .sidebarV1, - requestedScopes: [CMUXExtensionScope] = [.workspaceMetadata] - ) { - self.id = id - self.displayName = displayName - self.kind = kind - self.minimumAPIVersion = minimumAPIVersion - self.requestedScopes = requestedScopes - } -} - -public enum CMUXExtensionScope: String, Codable, CaseIterable, Equatable, Sendable { - case workspaceMetadata - case workspacePaths - case notifications - case networkPorts - case pullRequests -} - -public struct CMUXSidebarSnapshot: Codable, Equatable, Sendable { - public var apiVersion: CMUXExtensionAPIVersion - public var sequence: UInt64 - public var windowID: UUID? - public var selectedWorkspaceID: UUID? - public var workspaces: [CMUXSidebarWorkspace] - - public init( - apiVersion: CMUXExtensionAPIVersion = .sidebarV1, - sequence: UInt64, - windowID: UUID? = nil, - selectedWorkspaceID: UUID?, - workspaces: [CMUXSidebarWorkspace] - ) { - self.apiVersion = apiVersion - self.sequence = sequence - self.windowID = windowID - self.selectedWorkspaceID = selectedWorkspaceID - self.workspaces = workspaces - } -} - -public struct CMUXSidebarWorkspace: Codable, Equatable, Identifiable, Sendable { - public var id: UUID - public var title: String - public var detail: String? - public var isPinned: Bool - public var rootPath: String? - public var projectRootPath: String? - public var gitBranch: String? - public var unreadCount: Int - public var latestNotification: String? - public var listeningPorts: [Int] - public var pullRequestURLs: [String] - - public init( - id: UUID, - title: String, - detail: String? = nil, - isPinned: Bool = false, - rootPath: String? = nil, - projectRootPath: String? = nil, - gitBranch: String? = nil, - unreadCount: Int = 0, - latestNotification: String? = nil, - listeningPorts: [Int] = [], - pullRequestURLs: [String] = [] - ) { - self.id = id - self.title = title - self.detail = detail - self.isPinned = isPinned - self.rootPath = rootPath - self.projectRootPath = projectRootPath - self.gitBranch = gitBranch - self.unreadCount = unreadCount - self.latestNotification = latestNotification - self.listeningPorts = listeningPorts - self.pullRequestURLs = pullRequestURLs - } -} - -public enum CMUXSidebarAction: Codable, Equatable, Sendable { - case selectWorkspace(UUID) - case closeWorkspace(UUID) - case openURL(String) -} - -public struct CMUXExtensionActionResult: Codable, Equatable, Sendable { - public var accepted: Bool - public var message: String? - - public init(accepted: Bool, message: String? = nil) { - self.accepted = accepted - self.message = message - } - - public static let accepted = CMUXExtensionActionResult(accepted: true) -} - -public protocol CMUXSidebarExtension: Sendable { - var manifest: CMUXExtensionManifest { get } - - func makeInitialSnapshot() async throws -> CMUXSidebarSnapshot - func handle(_ action: CMUXSidebarAction) async throws -> CMUXExtensionActionResult -} - -public struct CMUXSidebarHostClient: Sendable { - public var snapshot: @Sendable () async throws -> CMUXSidebarSnapshot - public var dispatch: @Sendable (CMUXSidebarAction) async throws -> CMUXExtensionActionResult - - public init( - snapshot: @escaping @Sendable () async throws -> CMUXSidebarSnapshot, - dispatch: @escaping @Sendable (CMUXSidebarAction) async throws -> CMUXExtensionActionResult - ) { - self.snapshot = snapshot - self.dispatch = dispatch - } -} - -public enum CMUXExtensionValidationError: Error, Equatable, Sendable { - case unsupportedKind(CMUXExtensionKind) - case unsupportedAPIVersion(requested: CMUXExtensionAPIVersion, supported: CMUXExtensionAPIVersion) - case emptyIdentifier - case emptyDisplayName -} - -public enum CMUXExtensionValidator { - public static func validateSidebarManifest( - _ manifest: CMUXExtensionManifest, - supportedAPIVersion: CMUXExtensionAPIVersion = .sidebarV1 - ) throws { - guard manifest.id.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == false else { - throw CMUXExtensionValidationError.emptyIdentifier - } - guard manifest.displayName.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == false else { - throw CMUXExtensionValidationError.emptyDisplayName - } - guard manifest.kind == .sidebar else { - throw CMUXExtensionValidationError.unsupportedKind(manifest.kind) - } - guard manifest.minimumAPIVersion <= supportedAPIVersion else { - throw CMUXExtensionValidationError.unsupportedAPIVersion( - requested: manifest.minimumAPIVersion, - supported: supportedAPIVersion - ) - } - } -} - -// Compatibility names used only by the existing cmux app while the old prototype -// sidebar is removed in smaller follow-up steps. -public enum CmuxExtensionSidebarProviderID { - public static let defaultWorkspaces = "cmux.sidebar.default" -} - -public struct CmuxExtensionLocalizedText: Codable, Equatable, Hashable, Sendable { - public var key: String - public var defaultValue: String - - public init(key: String, defaultValue: String) { - self.key = key - self.defaultValue = defaultValue - } -} - -public struct CmuxExtensionSidebarProviderDescriptor: Identifiable, Codable, Equatable, Sendable { - public var id: String - public var title: CmuxExtensionLocalizedText - public var subtitle: CmuxExtensionLocalizedText? - public var systemImageName: String - public var isHostProvided: Bool - - public init( - id: String, - title: CmuxExtensionLocalizedText, - subtitle: CmuxExtensionLocalizedText? = nil, - systemImageName: String, - isHostProvided: Bool - ) { - self.id = id - self.title = title - self.subtitle = subtitle - self.systemImageName = systemImageName - self.isHostProvided = isHostProvided - } - - public static let defaultWorkspaces = CmuxExtensionSidebarProviderDescriptor( - id: CmuxExtensionSidebarProviderID.defaultWorkspaces, - title: CmuxExtensionLocalizedText(key: "sidebar.provider.default.title", defaultValue: "Default Workspaces"), - subtitle: CmuxExtensionLocalizedText(key: "sidebar.provider.default.subtitle", defaultValue: "cmux"), - systemImageName: "list.bullet", - isHostProvided: true - ) -} - -public protocol CmuxExtensionSidebarProvider: Sendable { - var descriptor: CmuxExtensionSidebarProviderDescriptor { get } -} diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CmuxExtensionSidebarProvider.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CmuxExtensionSidebarProvider.swift new file mode 100644 index 000000000000..2cf41f2f794d --- /dev/null +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CmuxExtensionSidebarProvider.swift @@ -0,0 +1,51 @@ +import Foundation + +// Compatibility names used only by the existing cmux app while the old prototype +// sidebar is removed in smaller follow-up steps. +public enum CmuxExtensionSidebarProviderID { + public static let defaultWorkspaces = "cmux.sidebar.default" +} + +public struct CmuxExtensionLocalizedText: Codable, Equatable, Hashable, Sendable { + public var key: String + public var defaultValue: String + + public init(key: String, defaultValue: String) { + self.key = key + self.defaultValue = defaultValue + } +} + +public struct CmuxExtensionSidebarProviderDescriptor: Identifiable, Codable, Equatable, Sendable { + public var id: String + public var title: CmuxExtensionLocalizedText + public var subtitle: CmuxExtensionLocalizedText? + public var systemImageName: String + public var isHostProvided: Bool + + public init( + id: String, + title: CmuxExtensionLocalizedText, + subtitle: CmuxExtensionLocalizedText? = nil, + systemImageName: String, + isHostProvided: Bool + ) { + self.id = id + self.title = title + self.subtitle = subtitle + self.systemImageName = systemImageName + self.isHostProvided = isHostProvided + } + + public static let defaultWorkspaces = CmuxExtensionSidebarProviderDescriptor( + id: CmuxExtensionSidebarProviderID.defaultWorkspaces, + title: CmuxExtensionLocalizedText(key: "sidebar.provider.default.title", defaultValue: "Default Workspaces"), + subtitle: CmuxExtensionLocalizedText(key: "sidebar.provider.default.subtitle", defaultValue: "cmux"), + systemImageName: "list.bullet", + isHostProvided: true + ) +} + +public protocol CmuxExtensionSidebarProvider: Sendable { + var descriptor: CmuxExtensionSidebarProviderDescriptor { get } +} From 6764a3a20caf3080e950023c853fc061eda3a296 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Fri, 29 May 2026 15:50:01 -0500 Subject: [PATCH 04/44] Organize sidebar extension sources into folders --- .../CMUXInstalledSidebarExtension.swift | 0 .../CMUXSidebarExtensionDiscovery.swift | 0 .../CMUXSidebarExtensionPoint.swift | 0 .../CMUXSidebarExtensionHostView.swift | 0 .../Registry/CMUXExtensionClientError.swift | 9 ++++++++ .../CMUXSidebarExtensionRecord.swift | 8 ------- .../CMUXSidebarExtensionRegistry.swift | 0 .../CMUXSidebarExtensionSession.swift | 0 .../CMUXExtensionAPIVersion.swift | 0 .../CmuxExtensionLocalizedText.swift | 11 +++++++++ .../CmuxExtensionSidebarProvider.swift | 5 ++++ ...xExtensionSidebarProviderDescriptor.swift} | 20 ---------------- .../CmuxExtensionSidebarProviderID.swift | 7 ++++++ .../Manifest/CMUXExtensionKind.swift | 5 ++++ .../CMUXExtensionManifest.swift | 12 ---------- .../Manifest/CMUXExtensionScope.swift | 9 ++++++++ .../CMUXExtensionActionResult.swift} | 6 ----- .../Sidebar/CMUXSidebarAction.swift | 7 ++++++ .../Sidebar/CMUXSidebarExtension.swift | 8 +++++++ .../CMUXSidebarHostClient.swift} | 7 ------ .../Sidebar/CMUXSidebarSnapshot.swift | 23 +++++++++++++++++++ .../CMUXSidebarWorkspace.swift} | 22 ------------------ .../CMUXExtensionValidationError.swift | 8 +++++++ .../CMUXExtensionValidator.swift | 7 ------ 24 files changed, 92 insertions(+), 82 deletions(-) rename Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/{ => Discovery}/CMUXInstalledSidebarExtension.swift (100%) rename Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/{ => Discovery}/CMUXSidebarExtensionDiscovery.swift (100%) rename Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/{ => ExtensionPoint}/CMUXSidebarExtensionPoint.swift (100%) rename Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/{ => Hosting}/CMUXSidebarExtensionHostView.swift (100%) create mode 100644 Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Registry/CMUXExtensionClientError.swift rename Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/{ => Registry}/CMUXSidebarExtensionRecord.swift (71%) rename Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/{ => Registry}/CMUXSidebarExtensionRegistry.swift (100%) rename Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/{ => Session}/CMUXSidebarExtensionSession.swift (100%) rename Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/{ => Common}/CMUXExtensionAPIVersion.swift (100%) create mode 100644 Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/HostCompatibility/CmuxExtensionLocalizedText.swift create mode 100644 Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/HostCompatibility/CmuxExtensionSidebarProvider.swift rename Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/{CmuxExtensionSidebarProvider.swift => HostCompatibility/CmuxExtensionSidebarProviderDescriptor.swift} (64%) create mode 100644 Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/HostCompatibility/CmuxExtensionSidebarProviderID.swift create mode 100644 Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Manifest/CMUXExtensionKind.swift rename Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/{ => Manifest}/CMUXExtensionManifest.swift (70%) create mode 100644 Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Manifest/CMUXExtensionScope.swift rename Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/{CMUXSidebarActions.swift => Sidebar/CMUXExtensionActionResult.swift} (70%) create mode 100644 Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarAction.swift create mode 100644 Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarExtension.swift rename Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/{CMUXSidebarExtension.swift => Sidebar/CMUXSidebarHostClient.swift} (66%) create mode 100644 Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarSnapshot.swift rename Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/{CMUXSidebarSnapshot.swift => Sidebar/CMUXSidebarWorkspace.swift} (64%) create mode 100644 Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Validation/CMUXExtensionValidationError.swift rename Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/{ => Validation}/CMUXExtensionValidator.swift (78%) diff --git a/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/CMUXInstalledSidebarExtension.swift b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Discovery/CMUXInstalledSidebarExtension.swift similarity index 100% rename from Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/CMUXInstalledSidebarExtension.swift rename to Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Discovery/CMUXInstalledSidebarExtension.swift diff --git a/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/CMUXSidebarExtensionDiscovery.swift b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Discovery/CMUXSidebarExtensionDiscovery.swift similarity index 100% rename from Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/CMUXSidebarExtensionDiscovery.swift rename to Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Discovery/CMUXSidebarExtensionDiscovery.swift diff --git a/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/CMUXSidebarExtensionPoint.swift b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/ExtensionPoint/CMUXSidebarExtensionPoint.swift similarity index 100% rename from Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/CMUXSidebarExtensionPoint.swift rename to Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/ExtensionPoint/CMUXSidebarExtensionPoint.swift diff --git a/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/CMUXSidebarExtensionHostView.swift b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Hosting/CMUXSidebarExtensionHostView.swift similarity index 100% rename from Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/CMUXSidebarExtensionHostView.swift rename to Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Hosting/CMUXSidebarExtensionHostView.swift diff --git a/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Registry/CMUXExtensionClientError.swift b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Registry/CMUXExtensionClientError.swift new file mode 100644 index 000000000000..48f4761fd2dd --- /dev/null +++ b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Registry/CMUXExtensionClientError.swift @@ -0,0 +1,9 @@ +import Foundation + +/// Errors raised by the sidebar extension host client. +public enum CMUXExtensionClientError: Error, Equatable, Sendable { + /// More than one extension used the same manifest identifier. + case duplicateExtensionIdentifier(String) + /// No registered extension matched the requested identifier. + case extensionNotFound(String) +} diff --git a/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/CMUXSidebarExtensionRecord.swift b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Registry/CMUXSidebarExtensionRecord.swift similarity index 71% rename from Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/CMUXSidebarExtensionRecord.swift rename to Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Registry/CMUXSidebarExtensionRecord.swift index a59c56f8108f..9c8153805d3e 100644 --- a/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/CMUXSidebarExtensionRecord.swift +++ b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Registry/CMUXSidebarExtensionRecord.swift @@ -19,11 +19,3 @@ public struct CMUXSidebarExtensionRecord: Equatable, Identifiable, Sendable { self.isHostProvided = isHostProvided } } - -/// Errors raised by the sidebar extension host client. -public enum CMUXExtensionClientError: Error, Equatable, Sendable { - /// More than one extension used the same manifest identifier. - case duplicateExtensionIdentifier(String) - /// No registered extension matched the requested identifier. - case extensionNotFound(String) -} diff --git a/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/CMUXSidebarExtensionRegistry.swift b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Registry/CMUXSidebarExtensionRegistry.swift similarity index 100% rename from Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/CMUXSidebarExtensionRegistry.swift rename to Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Registry/CMUXSidebarExtensionRegistry.swift diff --git a/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/CMUXSidebarExtensionSession.swift b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Session/CMUXSidebarExtensionSession.swift similarity index 100% rename from Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/CMUXSidebarExtensionSession.swift rename to Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Session/CMUXSidebarExtensionSession.swift diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CMUXExtensionAPIVersion.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Common/CMUXExtensionAPIVersion.swift similarity index 100% rename from Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CMUXExtensionAPIVersion.swift rename to Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Common/CMUXExtensionAPIVersion.swift diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/HostCompatibility/CmuxExtensionLocalizedText.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/HostCompatibility/CmuxExtensionLocalizedText.swift new file mode 100644 index 000000000000..b09910327a8b --- /dev/null +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/HostCompatibility/CmuxExtensionLocalizedText.swift @@ -0,0 +1,11 @@ +import Foundation + +public struct CmuxExtensionLocalizedText: Codable, Equatable, Hashable, Sendable { + public var key: String + public var defaultValue: String + + public init(key: String, defaultValue: String) { + self.key = key + self.defaultValue = defaultValue + } +} diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/HostCompatibility/CmuxExtensionSidebarProvider.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/HostCompatibility/CmuxExtensionSidebarProvider.swift new file mode 100644 index 000000000000..5d6665e5567d --- /dev/null +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/HostCompatibility/CmuxExtensionSidebarProvider.swift @@ -0,0 +1,5 @@ +import Foundation + +public protocol CmuxExtensionSidebarProvider: Sendable { + var descriptor: CmuxExtensionSidebarProviderDescriptor { get } +} diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CmuxExtensionSidebarProvider.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/HostCompatibility/CmuxExtensionSidebarProviderDescriptor.swift similarity index 64% rename from Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CmuxExtensionSidebarProvider.swift rename to Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/HostCompatibility/CmuxExtensionSidebarProviderDescriptor.swift index 2cf41f2f794d..4b104af75c30 100644 --- a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CmuxExtensionSidebarProvider.swift +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/HostCompatibility/CmuxExtensionSidebarProviderDescriptor.swift @@ -1,21 +1,5 @@ import Foundation -// Compatibility names used only by the existing cmux app while the old prototype -// sidebar is removed in smaller follow-up steps. -public enum CmuxExtensionSidebarProviderID { - public static let defaultWorkspaces = "cmux.sidebar.default" -} - -public struct CmuxExtensionLocalizedText: Codable, Equatable, Hashable, Sendable { - public var key: String - public var defaultValue: String - - public init(key: String, defaultValue: String) { - self.key = key - self.defaultValue = defaultValue - } -} - public struct CmuxExtensionSidebarProviderDescriptor: Identifiable, Codable, Equatable, Sendable { public var id: String public var title: CmuxExtensionLocalizedText @@ -45,7 +29,3 @@ public struct CmuxExtensionSidebarProviderDescriptor: Identifiable, Codable, Equ isHostProvided: true ) } - -public protocol CmuxExtensionSidebarProvider: Sendable { - var descriptor: CmuxExtensionSidebarProviderDescriptor { get } -} diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/HostCompatibility/CmuxExtensionSidebarProviderID.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/HostCompatibility/CmuxExtensionSidebarProviderID.swift new file mode 100644 index 000000000000..3bbb37489f74 --- /dev/null +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/HostCompatibility/CmuxExtensionSidebarProviderID.swift @@ -0,0 +1,7 @@ +import Foundation + +// Compatibility name used only by the existing cmux app while the old prototype +// sidebar is removed in smaller follow-up steps. +public enum CmuxExtensionSidebarProviderID { + public static let defaultWorkspaces = "cmux.sidebar.default" +} diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Manifest/CMUXExtensionKind.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Manifest/CMUXExtensionKind.swift new file mode 100644 index 000000000000..5fbe4cb94ece --- /dev/null +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Manifest/CMUXExtensionKind.swift @@ -0,0 +1,5 @@ +import Foundation + +public enum CMUXExtensionKind: String, Codable, CaseIterable, Equatable, Sendable { + case sidebar +} diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CMUXExtensionManifest.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Manifest/CMUXExtensionManifest.swift similarity index 70% rename from Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CMUXExtensionManifest.swift rename to Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Manifest/CMUXExtensionManifest.swift index a02081d79d90..c1e57fb2fcd3 100644 --- a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CMUXExtensionManifest.swift +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Manifest/CMUXExtensionManifest.swift @@ -1,9 +1,5 @@ import Foundation -public enum CMUXExtensionKind: String, Codable, CaseIterable, Equatable, Sendable { - case sidebar -} - public struct CMUXExtensionManifest: Codable, Equatable, Identifiable, Sendable { public var id: String public var displayName: String @@ -25,11 +21,3 @@ public struct CMUXExtensionManifest: Codable, Equatable, Identifiable, Sendable self.requestedScopes = requestedScopes } } - -public enum CMUXExtensionScope: String, Codable, CaseIterable, Equatable, Sendable { - case workspaceMetadata - case workspacePaths - case notifications - case networkPorts - case pullRequests -} diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Manifest/CMUXExtensionScope.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Manifest/CMUXExtensionScope.swift new file mode 100644 index 000000000000..33fc01f3483b --- /dev/null +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Manifest/CMUXExtensionScope.swift @@ -0,0 +1,9 @@ +import Foundation + +public enum CMUXExtensionScope: String, Codable, CaseIterable, Equatable, Sendable { + case workspaceMetadata + case workspacePaths + case notifications + case networkPorts + case pullRequests +} diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CMUXSidebarActions.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXExtensionActionResult.swift similarity index 70% rename from Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CMUXSidebarActions.swift rename to Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXExtensionActionResult.swift index d4a5dee92ad1..871d005014d8 100644 --- a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CMUXSidebarActions.swift +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXExtensionActionResult.swift @@ -1,11 +1,5 @@ import Foundation -public enum CMUXSidebarAction: Codable, Equatable, Sendable { - case selectWorkspace(UUID) - case closeWorkspace(UUID) - case openURL(String) -} - public struct CMUXExtensionActionResult: Codable, Equatable, Sendable { public var accepted: Bool public var message: String? diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarAction.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarAction.swift new file mode 100644 index 000000000000..7773b7b33e6e --- /dev/null +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarAction.swift @@ -0,0 +1,7 @@ +import Foundation + +public enum CMUXSidebarAction: Codable, Equatable, Sendable { + case selectWorkspace(UUID) + case closeWorkspace(UUID) + case openURL(String) +} diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarExtension.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarExtension.swift new file mode 100644 index 000000000000..2b0592fcdd0d --- /dev/null +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarExtension.swift @@ -0,0 +1,8 @@ +import Foundation + +public protocol CMUXSidebarExtension: Sendable { + var manifest: CMUXExtensionManifest { get } + + func makeInitialSnapshot() async throws -> CMUXSidebarSnapshot + func handle(_ action: CMUXSidebarAction) async throws -> CMUXExtensionActionResult +} diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CMUXSidebarExtension.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarHostClient.swift similarity index 66% rename from Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CMUXSidebarExtension.swift rename to Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarHostClient.swift index 9e7e5b969c6a..3b8e4db02ee6 100644 --- a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CMUXSidebarExtension.swift +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarHostClient.swift @@ -1,12 +1,5 @@ import Foundation -public protocol CMUXSidebarExtension: Sendable { - var manifest: CMUXExtensionManifest { get } - - func makeInitialSnapshot() async throws -> CMUXSidebarSnapshot - func handle(_ action: CMUXSidebarAction) async throws -> CMUXExtensionActionResult -} - public struct CMUXSidebarHostClient: Sendable { public var snapshot: @Sendable () async throws -> CMUXSidebarSnapshot public var dispatch: @Sendable (CMUXSidebarAction) async throws -> CMUXExtensionActionResult diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarSnapshot.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarSnapshot.swift new file mode 100644 index 000000000000..8030f03fb506 --- /dev/null +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarSnapshot.swift @@ -0,0 +1,23 @@ +import Foundation + +public struct CMUXSidebarSnapshot: Codable, Equatable, Sendable { + public var apiVersion: CMUXExtensionAPIVersion + public var sequence: UInt64 + public var windowID: UUID? + public var selectedWorkspaceID: UUID? + public var workspaces: [CMUXSidebarWorkspace] + + public init( + apiVersion: CMUXExtensionAPIVersion = .sidebarV1, + sequence: UInt64, + windowID: UUID? = nil, + selectedWorkspaceID: UUID?, + workspaces: [CMUXSidebarWorkspace] + ) { + self.apiVersion = apiVersion + self.sequence = sequence + self.windowID = windowID + self.selectedWorkspaceID = selectedWorkspaceID + self.workspaces = workspaces + } +} diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CMUXSidebarSnapshot.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarWorkspace.swift similarity index 64% rename from Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CMUXSidebarSnapshot.swift rename to Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarWorkspace.swift index bfaa68594328..ed42bd6a53e6 100644 --- a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CMUXSidebarSnapshot.swift +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarWorkspace.swift @@ -1,27 +1,5 @@ import Foundation -public struct CMUXSidebarSnapshot: Codable, Equatable, Sendable { - public var apiVersion: CMUXExtensionAPIVersion - public var sequence: UInt64 - public var windowID: UUID? - public var selectedWorkspaceID: UUID? - public var workspaces: [CMUXSidebarWorkspace] - - public init( - apiVersion: CMUXExtensionAPIVersion = .sidebarV1, - sequence: UInt64, - windowID: UUID? = nil, - selectedWorkspaceID: UUID?, - workspaces: [CMUXSidebarWorkspace] - ) { - self.apiVersion = apiVersion - self.sequence = sequence - self.windowID = windowID - self.selectedWorkspaceID = selectedWorkspaceID - self.workspaces = workspaces - } -} - public struct CMUXSidebarWorkspace: Codable, Equatable, Identifiable, Sendable { public var id: UUID public var title: String diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Validation/CMUXExtensionValidationError.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Validation/CMUXExtensionValidationError.swift new file mode 100644 index 000000000000..eb28b5bc7e26 --- /dev/null +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Validation/CMUXExtensionValidationError.swift @@ -0,0 +1,8 @@ +import Foundation + +public enum CMUXExtensionValidationError: Error, Equatable, Sendable { + case unsupportedKind(CMUXExtensionKind) + case unsupportedAPIVersion(requested: CMUXExtensionAPIVersion, supported: CMUXExtensionAPIVersion) + case emptyIdentifier + case emptyDisplayName +} diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CMUXExtensionValidator.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Validation/CMUXExtensionValidator.swift similarity index 78% rename from Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CMUXExtensionValidator.swift rename to Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Validation/CMUXExtensionValidator.swift index 1ebe8caad588..5d09f727315c 100644 --- a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/CMUXExtensionValidator.swift +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Validation/CMUXExtensionValidator.swift @@ -1,12 +1,5 @@ import Foundation -public enum CMUXExtensionValidationError: Error, Equatable, Sendable { - case unsupportedKind(CMUXExtensionKind) - case unsupportedAPIVersion(requested: CMUXExtensionAPIVersion, supported: CMUXExtensionAPIVersion) - case emptyIdentifier - case emptyDisplayName -} - public enum CMUXExtensionValidator { public static func validateSidebarManifest( _ manifest: CMUXExtensionManifest, From de4a77e28f42e6590b88600c5664b0bcaa85000f Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Fri, 29 May 2026 16:14:05 -0500 Subject: [PATCH 05/44] Add sample sidebar extension package to workspace --- .../CMUXSampleSidebarExtension/Package.swift | 27 ++++++++ Examples/CMUXSampleSidebarExtension/README.md | 11 ++++ .../CMUXExtensionManifest+Sample.swift | 18 ++++++ .../CMUXSampleSidebarExtension.swift | 33 ++++++++++ .../CMUXSampleSidebarView.swift | 29 +++++++++ .../CMUXSampleWorkspaceRow.swift | 62 +++++++++++++++++++ .../CMUXSidebarSnapshot+Sample.swift | 38 ++++++++++++ .../CMUXSampleSidebarExtensionTests.swift | 38 ++++++++++++ cmux.xcworkspace/contents.xcworkspacedata | 13 ++++ 9 files changed, 269 insertions(+) create mode 100644 Examples/CMUXSampleSidebarExtension/Package.swift create mode 100644 Examples/CMUXSampleSidebarExtension/README.md create mode 100644 Examples/CMUXSampleSidebarExtension/Sources/CMUXSampleSidebarExtension/CMUXExtensionManifest+Sample.swift create mode 100644 Examples/CMUXSampleSidebarExtension/Sources/CMUXSampleSidebarExtension/CMUXSampleSidebarExtension.swift create mode 100644 Examples/CMUXSampleSidebarExtension/Sources/CMUXSampleSidebarExtension/CMUXSampleSidebarView.swift create mode 100644 Examples/CMUXSampleSidebarExtension/Sources/CMUXSampleSidebarExtension/CMUXSampleWorkspaceRow.swift create mode 100644 Examples/CMUXSampleSidebarExtension/Sources/CMUXSampleSidebarExtension/CMUXSidebarSnapshot+Sample.swift create mode 100644 Examples/CMUXSampleSidebarExtension/Tests/CMUXSampleSidebarExtensionTests/CMUXSampleSidebarExtensionTests.swift diff --git a/Examples/CMUXSampleSidebarExtension/Package.swift b/Examples/CMUXSampleSidebarExtension/Package.swift new file mode 100644 index 000000000000..aba3f5798e63 --- /dev/null +++ b/Examples/CMUXSampleSidebarExtension/Package.swift @@ -0,0 +1,27 @@ +// swift-tools-version: 6.0 + +import PackageDescription + +let package = Package( + name: "CMUXSampleSidebarExtension", + platforms: [.macOS(.v14)], + products: [ + .library( + name: "CMUXSampleSidebarExtension", + targets: ["CMUXSampleSidebarExtension"] + ), + ], + dependencies: [ + .package(path: "../../Packages/CmuxExtensionKit"), + ], + targets: [ + .target( + name: "CMUXSampleSidebarExtension", + dependencies: ["CmuxExtensionKit"] + ), + .testTarget( + name: "CMUXSampleSidebarExtensionTests", + dependencies: ["CMUXSampleSidebarExtension"] + ), + ] +) diff --git a/Examples/CMUXSampleSidebarExtension/README.md b/Examples/CMUXSampleSidebarExtension/README.md new file mode 100644 index 000000000000..0c0b102a17ea --- /dev/null +++ b/Examples/CMUXSampleSidebarExtension/README.md @@ -0,0 +1,11 @@ +# CMUX Sample Sidebar Extension + +This package is the minimal sample sidebar extension contract for CMUX. + +It demonstrates: + +- A `CMUXSidebarExtension` implementation. +- A SwiftUI sidebar view that renders a `CMUXSidebarSnapshot`. +- The extension manifest values expected by the host. + +The current CMUX host discovers installed ExtensionKit app extensions with extension point `com.manaflow.cmux.sidebar` and hosts scene `sidebar`. This package is intentionally package-shaped so the contract is visible in the workspace and covered by tests. A follow-up installable `.appex` sample should wrap `CMUXSampleSidebarView` in an ExtensionKit target. diff --git a/Examples/CMUXSampleSidebarExtension/Sources/CMUXSampleSidebarExtension/CMUXExtensionManifest+Sample.swift b/Examples/CMUXSampleSidebarExtension/Sources/CMUXSampleSidebarExtension/CMUXExtensionManifest+Sample.swift new file mode 100644 index 000000000000..1c8860476a9b --- /dev/null +++ b/Examples/CMUXSampleSidebarExtension/Sources/CMUXSampleSidebarExtension/CMUXExtensionManifest+Sample.swift @@ -0,0 +1,18 @@ +import CmuxExtensionKit +import Foundation + +public extension CMUXExtensionManifest { + static let cmuxSampleSidebar = CMUXExtensionManifest( + id: "com.manaflow.cmux.samples.sidebar", + displayName: "CMUX Sample Sidebar", + kind: .sidebar, + minimumAPIVersion: .sidebarV1, + requestedScopes: [ + .workspaceMetadata, + .workspacePaths, + .notifications, + .networkPorts, + .pullRequests, + ] + ) +} diff --git a/Examples/CMUXSampleSidebarExtension/Sources/CMUXSampleSidebarExtension/CMUXSampleSidebarExtension.swift b/Examples/CMUXSampleSidebarExtension/Sources/CMUXSampleSidebarExtension/CMUXSampleSidebarExtension.swift new file mode 100644 index 000000000000..e230e277a382 --- /dev/null +++ b/Examples/CMUXSampleSidebarExtension/Sources/CMUXSampleSidebarExtension/CMUXSampleSidebarExtension.swift @@ -0,0 +1,33 @@ +import CmuxExtensionKit +import Foundation + +public struct CMUXSampleSidebarExtension: CMUXSidebarExtension { + public let manifest: CMUXExtensionManifest + private let snapshotProvider: @Sendable () async throws -> CMUXSidebarSnapshot + + public init( + manifest: CMUXExtensionManifest = .cmuxSampleSidebar, + snapshotProvider: @escaping @Sendable () async throws -> CMUXSidebarSnapshot = { + CMUXSidebarSnapshot.sample + } + ) { + self.manifest = manifest + self.snapshotProvider = snapshotProvider + } + + public func makeInitialSnapshot() async throws -> CMUXSidebarSnapshot { + try await snapshotProvider() + } + + public func handle(_ action: CMUXSidebarAction) async throws -> CMUXExtensionActionResult { + switch action { + case .selectWorkspace, .openURL: + return .accepted + case .closeWorkspace: + return CMUXExtensionActionResult( + accepted: false, + message: "The sample sidebar does not close workspaces." + ) + } + } +} diff --git a/Examples/CMUXSampleSidebarExtension/Sources/CMUXSampleSidebarExtension/CMUXSampleSidebarView.swift b/Examples/CMUXSampleSidebarExtension/Sources/CMUXSampleSidebarExtension/CMUXSampleSidebarView.swift new file mode 100644 index 000000000000..b06f2e6d1364 --- /dev/null +++ b/Examples/CMUXSampleSidebarExtension/Sources/CMUXSampleSidebarExtension/CMUXSampleSidebarView.swift @@ -0,0 +1,29 @@ +import CmuxExtensionKit +import SwiftUI + +public struct CMUXSampleSidebarView: View { + private let snapshot: CMUXSidebarSnapshot + private let onAction: (CMUXSidebarAction) -> Void + + public init( + snapshot: CMUXSidebarSnapshot, + onAction: @escaping (CMUXSidebarAction) -> Void = { _ in } + ) { + self.snapshot = snapshot + self.onAction = onAction + } + + public var body: some View { + List(snapshot.workspaces) { workspace in + CMUXSampleWorkspaceRow( + workspace: workspace, + isSelected: workspace.id == snapshot.selectedWorkspaceID, + onSelect: { + onAction(.selectWorkspace(workspace.id)) + } + ) + } + .listStyle(.sidebar) + .frame(minWidth: 220, idealWidth: 260) + } +} diff --git a/Examples/CMUXSampleSidebarExtension/Sources/CMUXSampleSidebarExtension/CMUXSampleWorkspaceRow.swift b/Examples/CMUXSampleSidebarExtension/Sources/CMUXSampleSidebarExtension/CMUXSampleWorkspaceRow.swift new file mode 100644 index 000000000000..b233edff3ff9 --- /dev/null +++ b/Examples/CMUXSampleSidebarExtension/Sources/CMUXSampleSidebarExtension/CMUXSampleWorkspaceRow.swift @@ -0,0 +1,62 @@ +import CmuxExtensionKit +import SwiftUI + +public struct CMUXSampleWorkspaceRow: View { + private let workspace: CMUXSidebarWorkspace + private let isSelected: Bool + private let onSelect: () -> Void + + public init( + workspace: CMUXSidebarWorkspace, + isSelected: Bool, + onSelect: @escaping () -> Void + ) { + self.workspace = workspace + self.isSelected = isSelected + self.onSelect = onSelect + } + + public var body: some View { + Button(action: onSelect) { + VStack(alignment: .leading, spacing: 4) { + HStack(spacing: 6) { + Text(workspace.title) + .font(.system(size: 13, weight: .medium)) + .lineLimit(1) + if workspace.isPinned { + Image(systemName: "pin.fill") + .font(.system(size: 10, weight: .semibold)) + .foregroundStyle(.secondary) + } + if workspace.unreadCount > 0 { + Text("\(workspace.unreadCount)") + .font(.system(size: 10, weight: .bold)) + .monospacedDigit() + .padding(.horizontal, 5) + .padding(.vertical, 1) + .background(.blue.opacity(0.16), in: Capsule()) + } + } + + if let detail = workspace.detail { + Text(detail) + .font(.system(size: 11)) + .foregroundStyle(.secondary) + .lineLimit(1) + } + + if !workspace.listeningPorts.isEmpty { + Text("Ports \(workspace.listeningPorts.map(String.init).joined(separator: ", "))") + .font(.system(size: 10)) + .foregroundStyle(.secondary) + .lineLimit(1) + } + } + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.vertical, 4) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .listRowBackground(isSelected ? Color.accentColor.opacity(0.18) : Color.clear) + } +} diff --git a/Examples/CMUXSampleSidebarExtension/Sources/CMUXSampleSidebarExtension/CMUXSidebarSnapshot+Sample.swift b/Examples/CMUXSampleSidebarExtension/Sources/CMUXSampleSidebarExtension/CMUXSidebarSnapshot+Sample.swift new file mode 100644 index 000000000000..ae969ed745c5 --- /dev/null +++ b/Examples/CMUXSampleSidebarExtension/Sources/CMUXSampleSidebarExtension/CMUXSidebarSnapshot+Sample.swift @@ -0,0 +1,38 @@ +import CmuxExtensionKit +import Foundation + +public extension CMUXSidebarSnapshot { + static let sample = CMUXSidebarSnapshot( + sequence: 1, + windowID: UUID(uuidString: "00000000-0000-0000-0000-000000000001"), + selectedWorkspaceID: UUID(uuidString: "00000000-0000-0000-0000-000000000101"), + workspaces: [ + CMUXSidebarWorkspace( + id: UUID(uuidString: "00000000-0000-0000-0000-000000000101")!, + title: "ExtensionKit Host", + detail: "feature-sidebar-extension-kit", + isPinned: true, + rootPath: "/Users/example/cmux", + projectRootPath: "/Users/example/cmux", + gitBranch: "feature/sidebar-extension-kit", + unreadCount: 2, + latestNotification: "Tests passed", + listeningPorts: [17320, 9300], + pullRequestURLs: ["https://github.com/manaflow-ai/cmux/pull/4994"] + ), + CMUXSidebarWorkspace( + id: UUID(uuidString: "00000000-0000-0000-0000-000000000102")!, + title: "Sample Consumer", + detail: "Extension workspace data", + isPinned: false, + rootPath: "/Users/example/sample", + projectRootPath: "/Users/example/sample", + gitBranch: "main", + unreadCount: 0, + latestNotification: nil, + listeningPorts: [], + pullRequestURLs: [] + ), + ] + ) +} diff --git a/Examples/CMUXSampleSidebarExtension/Tests/CMUXSampleSidebarExtensionTests/CMUXSampleSidebarExtensionTests.swift b/Examples/CMUXSampleSidebarExtension/Tests/CMUXSampleSidebarExtensionTests/CMUXSampleSidebarExtensionTests.swift new file mode 100644 index 000000000000..fed452f16ee8 --- /dev/null +++ b/Examples/CMUXSampleSidebarExtension/Tests/CMUXSampleSidebarExtensionTests/CMUXSampleSidebarExtensionTests.swift @@ -0,0 +1,38 @@ +import CmuxExtensionKit +import Testing + +@testable import CMUXSampleSidebarExtension + +@Suite +struct CMUXSampleSidebarExtensionTests { + @Test + func testManifestMatchesSidebarContract() throws { + let manifest = CMUXExtensionManifest.cmuxSampleSidebar + + try CMUXExtensionValidator.validateSidebarManifest(manifest) + #expect(manifest.kind == .sidebar) + #expect(manifest.minimumAPIVersion == .sidebarV1) + #expect(manifest.requestedScopes.contains(.workspaceMetadata)) + } + + @Test + func testSampleExtensionReturnsSnapshot() async throws { + let sidebar = CMUXSampleSidebarExtension() + + let snapshot = try await sidebar.makeInitialSnapshot() + + #expect(snapshot.apiVersion == .sidebarV1) + #expect(snapshot.workspaces.count == 2) + #expect(snapshot.selectedWorkspaceID == snapshot.workspaces.first?.id) + } + + @Test + func testSampleExtensionAcceptsSelectWorkspace() async throws { + let sidebar = CMUXSampleSidebarExtension() + let workspaceID = try #require(CMUXSidebarSnapshot.sample.selectedWorkspaceID) + + let result = try await sidebar.handle(.selectWorkspace(workspaceID)) + + #expect(result.accepted) + } +} diff --git a/cmux.xcworkspace/contents.xcworkspacedata b/cmux.xcworkspace/contents.xcworkspacedata index 0b62982d6cee..eb54d885c873 100644 --- a/cmux.xcworkspace/contents.xcworkspacedata +++ b/cmux.xcworkspace/contents.xcworkspacedata @@ -19,6 +19,9 @@ + + @@ -32,4 +35,14 @@ location = "group:CMUXWorkstream"> + + + + + + From 13289adde1d441c2c5410762cded588e203507b1 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Fri, 29 May 2026 16:39:45 -0500 Subject: [PATCH 06/44] Add runnable sample sidebar ExtensionKit app --- .../CMUXSampleSidebarExtension/Package.swift | 27 - Examples/CMUXSampleSidebarExtension/README.md | 11 - .../CMUXExtensionManifest+Sample.swift | 18 - .../CMUXSampleSidebarExtension.swift | 33 - .../CMUXSampleSidebarView.swift | 29 - .../CMUXSampleWorkspaceRow.swift | 62 -- .../CMUXSidebarSnapshot+Sample.swift | 38 - .../CMUXSampleSidebarExtensionTests.swift | 38 - .../Connection/SidebarConnectionModel.swift | 120 +++ .../Extension/SampleSidebarExtension.swift | 26 + .../SampleSidebarExtension/Info.plist | 11 + .../Model/SidebarInsightModel.swift | 76 ++ .../UI/SampleSidebarView.swift | 75 ++ .../UI/SummaryPill.swift | 19 + .../UI/WorkspaceInsightRow.swift | 56 ++ .../project.pbxproj | 777 ++++++++++++++++++ .../AccentColor.colorset/Contents.json | 11 + .../AppIcon.appiconset/Contents.json | 58 ++ .../Assets.xcassets/Contents.json | 6 + .../ContentView.swift | 31 + .../SampleSidebarExtensionAppApp.swift | 17 + .../SampleSidebarExtensionAppTests.swift | 19 + .../SampleSidebarExtensionAppUITests.swift | 43 + ...idebarExtensionAppUITestsLaunchTests.swift | 35 + .../CMUXSidebarExtensionHostView.swift | 40 +- .../Sidebar/CMUXSidebarXPC.swift | 36 + .../CmuxExtensionKitTests.swift | 40 + ...MUXInstalledExtensionSidebarHostView.swift | 137 ++- Sources/ContentView.swift | 90 +- .../Update/MinimalModeSidebarControls.swift | 2 + Sources/Update/UpdateTitlebarAccessory.swift | 67 +- Sources/WindowDecorationsController.swift | 4 + Sources/WindowDragHandleView.swift | 9 +- cmux.xcworkspace/contents.xcworkspacedata | 2 +- 34 files changed, 1787 insertions(+), 276 deletions(-) delete mode 100644 Examples/CMUXSampleSidebarExtension/Package.swift delete mode 100644 Examples/CMUXSampleSidebarExtension/README.md delete mode 100644 Examples/CMUXSampleSidebarExtension/Sources/CMUXSampleSidebarExtension/CMUXExtensionManifest+Sample.swift delete mode 100644 Examples/CMUXSampleSidebarExtension/Sources/CMUXSampleSidebarExtension/CMUXSampleSidebarExtension.swift delete mode 100644 Examples/CMUXSampleSidebarExtension/Sources/CMUXSampleSidebarExtension/CMUXSampleSidebarView.swift delete mode 100644 Examples/CMUXSampleSidebarExtension/Sources/CMUXSampleSidebarExtension/CMUXSampleWorkspaceRow.swift delete mode 100644 Examples/CMUXSampleSidebarExtension/Sources/CMUXSampleSidebarExtension/CMUXSidebarSnapshot+Sample.swift delete mode 100644 Examples/CMUXSampleSidebarExtension/Tests/CMUXSampleSidebarExtensionTests/CMUXSampleSidebarExtensionTests.swift create mode 100644 Examples/SampleSidebarExtensionApp/SampleSidebarExtension/Connection/SidebarConnectionModel.swift create mode 100644 Examples/SampleSidebarExtensionApp/SampleSidebarExtension/Extension/SampleSidebarExtension.swift create mode 100644 Examples/SampleSidebarExtensionApp/SampleSidebarExtension/Info.plist create mode 100644 Examples/SampleSidebarExtensionApp/SampleSidebarExtension/Model/SidebarInsightModel.swift create mode 100644 Examples/SampleSidebarExtensionApp/SampleSidebarExtension/UI/SampleSidebarView.swift create mode 100644 Examples/SampleSidebarExtensionApp/SampleSidebarExtension/UI/SummaryPill.swift create mode 100644 Examples/SampleSidebarExtensionApp/SampleSidebarExtension/UI/WorkspaceInsightRow.swift create mode 100644 Examples/SampleSidebarExtensionApp/SampleSidebarExtensionApp.xcodeproj/project.pbxproj create mode 100644 Examples/SampleSidebarExtensionApp/SampleSidebarExtensionApp/Assets.xcassets/AccentColor.colorset/Contents.json create mode 100644 Examples/SampleSidebarExtensionApp/SampleSidebarExtensionApp/Assets.xcassets/AppIcon.appiconset/Contents.json create mode 100644 Examples/SampleSidebarExtensionApp/SampleSidebarExtensionApp/Assets.xcassets/Contents.json create mode 100644 Examples/SampleSidebarExtensionApp/SampleSidebarExtensionApp/ContentView.swift create mode 100644 Examples/SampleSidebarExtensionApp/SampleSidebarExtensionApp/SampleSidebarExtensionAppApp.swift create mode 100644 Examples/SampleSidebarExtensionApp/SampleSidebarExtensionAppTests/SampleSidebarExtensionAppTests.swift create mode 100644 Examples/SampleSidebarExtensionApp/SampleSidebarExtensionAppUITests/SampleSidebarExtensionAppUITests.swift create mode 100644 Examples/SampleSidebarExtensionApp/SampleSidebarExtensionAppUITests/SampleSidebarExtensionAppUITestsLaunchTests.swift create mode 100644 Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarXPC.swift diff --git a/Examples/CMUXSampleSidebarExtension/Package.swift b/Examples/CMUXSampleSidebarExtension/Package.swift deleted file mode 100644 index aba3f5798e63..000000000000 --- a/Examples/CMUXSampleSidebarExtension/Package.swift +++ /dev/null @@ -1,27 +0,0 @@ -// swift-tools-version: 6.0 - -import PackageDescription - -let package = Package( - name: "CMUXSampleSidebarExtension", - platforms: [.macOS(.v14)], - products: [ - .library( - name: "CMUXSampleSidebarExtension", - targets: ["CMUXSampleSidebarExtension"] - ), - ], - dependencies: [ - .package(path: "../../Packages/CmuxExtensionKit"), - ], - targets: [ - .target( - name: "CMUXSampleSidebarExtension", - dependencies: ["CmuxExtensionKit"] - ), - .testTarget( - name: "CMUXSampleSidebarExtensionTests", - dependencies: ["CMUXSampleSidebarExtension"] - ), - ] -) diff --git a/Examples/CMUXSampleSidebarExtension/README.md b/Examples/CMUXSampleSidebarExtension/README.md deleted file mode 100644 index 0c0b102a17ea..000000000000 --- a/Examples/CMUXSampleSidebarExtension/README.md +++ /dev/null @@ -1,11 +0,0 @@ -# CMUX Sample Sidebar Extension - -This package is the minimal sample sidebar extension contract for CMUX. - -It demonstrates: - -- A `CMUXSidebarExtension` implementation. -- A SwiftUI sidebar view that renders a `CMUXSidebarSnapshot`. -- The extension manifest values expected by the host. - -The current CMUX host discovers installed ExtensionKit app extensions with extension point `com.manaflow.cmux.sidebar` and hosts scene `sidebar`. This package is intentionally package-shaped so the contract is visible in the workspace and covered by tests. A follow-up installable `.appex` sample should wrap `CMUXSampleSidebarView` in an ExtensionKit target. diff --git a/Examples/CMUXSampleSidebarExtension/Sources/CMUXSampleSidebarExtension/CMUXExtensionManifest+Sample.swift b/Examples/CMUXSampleSidebarExtension/Sources/CMUXSampleSidebarExtension/CMUXExtensionManifest+Sample.swift deleted file mode 100644 index 1c8860476a9b..000000000000 --- a/Examples/CMUXSampleSidebarExtension/Sources/CMUXSampleSidebarExtension/CMUXExtensionManifest+Sample.swift +++ /dev/null @@ -1,18 +0,0 @@ -import CmuxExtensionKit -import Foundation - -public extension CMUXExtensionManifest { - static let cmuxSampleSidebar = CMUXExtensionManifest( - id: "com.manaflow.cmux.samples.sidebar", - displayName: "CMUX Sample Sidebar", - kind: .sidebar, - minimumAPIVersion: .sidebarV1, - requestedScopes: [ - .workspaceMetadata, - .workspacePaths, - .notifications, - .networkPorts, - .pullRequests, - ] - ) -} diff --git a/Examples/CMUXSampleSidebarExtension/Sources/CMUXSampleSidebarExtension/CMUXSampleSidebarExtension.swift b/Examples/CMUXSampleSidebarExtension/Sources/CMUXSampleSidebarExtension/CMUXSampleSidebarExtension.swift deleted file mode 100644 index e230e277a382..000000000000 --- a/Examples/CMUXSampleSidebarExtension/Sources/CMUXSampleSidebarExtension/CMUXSampleSidebarExtension.swift +++ /dev/null @@ -1,33 +0,0 @@ -import CmuxExtensionKit -import Foundation - -public struct CMUXSampleSidebarExtension: CMUXSidebarExtension { - public let manifest: CMUXExtensionManifest - private let snapshotProvider: @Sendable () async throws -> CMUXSidebarSnapshot - - public init( - manifest: CMUXExtensionManifest = .cmuxSampleSidebar, - snapshotProvider: @escaping @Sendable () async throws -> CMUXSidebarSnapshot = { - CMUXSidebarSnapshot.sample - } - ) { - self.manifest = manifest - self.snapshotProvider = snapshotProvider - } - - public func makeInitialSnapshot() async throws -> CMUXSidebarSnapshot { - try await snapshotProvider() - } - - public func handle(_ action: CMUXSidebarAction) async throws -> CMUXExtensionActionResult { - switch action { - case .selectWorkspace, .openURL: - return .accepted - case .closeWorkspace: - return CMUXExtensionActionResult( - accepted: false, - message: "The sample sidebar does not close workspaces." - ) - } - } -} diff --git a/Examples/CMUXSampleSidebarExtension/Sources/CMUXSampleSidebarExtension/CMUXSampleSidebarView.swift b/Examples/CMUXSampleSidebarExtension/Sources/CMUXSampleSidebarExtension/CMUXSampleSidebarView.swift deleted file mode 100644 index b06f2e6d1364..000000000000 --- a/Examples/CMUXSampleSidebarExtension/Sources/CMUXSampleSidebarExtension/CMUXSampleSidebarView.swift +++ /dev/null @@ -1,29 +0,0 @@ -import CmuxExtensionKit -import SwiftUI - -public struct CMUXSampleSidebarView: View { - private let snapshot: CMUXSidebarSnapshot - private let onAction: (CMUXSidebarAction) -> Void - - public init( - snapshot: CMUXSidebarSnapshot, - onAction: @escaping (CMUXSidebarAction) -> Void = { _ in } - ) { - self.snapshot = snapshot - self.onAction = onAction - } - - public var body: some View { - List(snapshot.workspaces) { workspace in - CMUXSampleWorkspaceRow( - workspace: workspace, - isSelected: workspace.id == snapshot.selectedWorkspaceID, - onSelect: { - onAction(.selectWorkspace(workspace.id)) - } - ) - } - .listStyle(.sidebar) - .frame(minWidth: 220, idealWidth: 260) - } -} diff --git a/Examples/CMUXSampleSidebarExtension/Sources/CMUXSampleSidebarExtension/CMUXSampleWorkspaceRow.swift b/Examples/CMUXSampleSidebarExtension/Sources/CMUXSampleSidebarExtension/CMUXSampleWorkspaceRow.swift deleted file mode 100644 index b233edff3ff9..000000000000 --- a/Examples/CMUXSampleSidebarExtension/Sources/CMUXSampleSidebarExtension/CMUXSampleWorkspaceRow.swift +++ /dev/null @@ -1,62 +0,0 @@ -import CmuxExtensionKit -import SwiftUI - -public struct CMUXSampleWorkspaceRow: View { - private let workspace: CMUXSidebarWorkspace - private let isSelected: Bool - private let onSelect: () -> Void - - public init( - workspace: CMUXSidebarWorkspace, - isSelected: Bool, - onSelect: @escaping () -> Void - ) { - self.workspace = workspace - self.isSelected = isSelected - self.onSelect = onSelect - } - - public var body: some View { - Button(action: onSelect) { - VStack(alignment: .leading, spacing: 4) { - HStack(spacing: 6) { - Text(workspace.title) - .font(.system(size: 13, weight: .medium)) - .lineLimit(1) - if workspace.isPinned { - Image(systemName: "pin.fill") - .font(.system(size: 10, weight: .semibold)) - .foregroundStyle(.secondary) - } - if workspace.unreadCount > 0 { - Text("\(workspace.unreadCount)") - .font(.system(size: 10, weight: .bold)) - .monospacedDigit() - .padding(.horizontal, 5) - .padding(.vertical, 1) - .background(.blue.opacity(0.16), in: Capsule()) - } - } - - if let detail = workspace.detail { - Text(detail) - .font(.system(size: 11)) - .foregroundStyle(.secondary) - .lineLimit(1) - } - - if !workspace.listeningPorts.isEmpty { - Text("Ports \(workspace.listeningPorts.map(String.init).joined(separator: ", "))") - .font(.system(size: 10)) - .foregroundStyle(.secondary) - .lineLimit(1) - } - } - .frame(maxWidth: .infinity, alignment: .leading) - .padding(.vertical, 4) - .contentShape(Rectangle()) - } - .buttonStyle(.plain) - .listRowBackground(isSelected ? Color.accentColor.opacity(0.18) : Color.clear) - } -} diff --git a/Examples/CMUXSampleSidebarExtension/Sources/CMUXSampleSidebarExtension/CMUXSidebarSnapshot+Sample.swift b/Examples/CMUXSampleSidebarExtension/Sources/CMUXSampleSidebarExtension/CMUXSidebarSnapshot+Sample.swift deleted file mode 100644 index ae969ed745c5..000000000000 --- a/Examples/CMUXSampleSidebarExtension/Sources/CMUXSampleSidebarExtension/CMUXSidebarSnapshot+Sample.swift +++ /dev/null @@ -1,38 +0,0 @@ -import CmuxExtensionKit -import Foundation - -public extension CMUXSidebarSnapshot { - static let sample = CMUXSidebarSnapshot( - sequence: 1, - windowID: UUID(uuidString: "00000000-0000-0000-0000-000000000001"), - selectedWorkspaceID: UUID(uuidString: "00000000-0000-0000-0000-000000000101"), - workspaces: [ - CMUXSidebarWorkspace( - id: UUID(uuidString: "00000000-0000-0000-0000-000000000101")!, - title: "ExtensionKit Host", - detail: "feature-sidebar-extension-kit", - isPinned: true, - rootPath: "/Users/example/cmux", - projectRootPath: "/Users/example/cmux", - gitBranch: "feature/sidebar-extension-kit", - unreadCount: 2, - latestNotification: "Tests passed", - listeningPorts: [17320, 9300], - pullRequestURLs: ["https://github.com/manaflow-ai/cmux/pull/4994"] - ), - CMUXSidebarWorkspace( - id: UUID(uuidString: "00000000-0000-0000-0000-000000000102")!, - title: "Sample Consumer", - detail: "Extension workspace data", - isPinned: false, - rootPath: "/Users/example/sample", - projectRootPath: "/Users/example/sample", - gitBranch: "main", - unreadCount: 0, - latestNotification: nil, - listeningPorts: [], - pullRequestURLs: [] - ), - ] - ) -} diff --git a/Examples/CMUXSampleSidebarExtension/Tests/CMUXSampleSidebarExtensionTests/CMUXSampleSidebarExtensionTests.swift b/Examples/CMUXSampleSidebarExtension/Tests/CMUXSampleSidebarExtensionTests/CMUXSampleSidebarExtensionTests.swift deleted file mode 100644 index fed452f16ee8..000000000000 --- a/Examples/CMUXSampleSidebarExtension/Tests/CMUXSampleSidebarExtensionTests/CMUXSampleSidebarExtensionTests.swift +++ /dev/null @@ -1,38 +0,0 @@ -import CmuxExtensionKit -import Testing - -@testable import CMUXSampleSidebarExtension - -@Suite -struct CMUXSampleSidebarExtensionTests { - @Test - func testManifestMatchesSidebarContract() throws { - let manifest = CMUXExtensionManifest.cmuxSampleSidebar - - try CMUXExtensionValidator.validateSidebarManifest(manifest) - #expect(manifest.kind == .sidebar) - #expect(manifest.minimumAPIVersion == .sidebarV1) - #expect(manifest.requestedScopes.contains(.workspaceMetadata)) - } - - @Test - func testSampleExtensionReturnsSnapshot() async throws { - let sidebar = CMUXSampleSidebarExtension() - - let snapshot = try await sidebar.makeInitialSnapshot() - - #expect(snapshot.apiVersion == .sidebarV1) - #expect(snapshot.workspaces.count == 2) - #expect(snapshot.selectedWorkspaceID == snapshot.workspaces.first?.id) - } - - @Test - func testSampleExtensionAcceptsSelectWorkspace() async throws { - let sidebar = CMUXSampleSidebarExtension() - let workspaceID = try #require(CMUXSidebarSnapshot.sample.selectedWorkspaceID) - - let result = try await sidebar.handle(.selectWorkspace(workspaceID)) - - #expect(result.accepted) - } -} diff --git a/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/Connection/SidebarConnectionModel.swift b/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/Connection/SidebarConnectionModel.swift new file mode 100644 index 000000000000..36a54a61e9d8 --- /dev/null +++ b/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/Connection/SidebarConnectionModel.swift @@ -0,0 +1,120 @@ +import Foundation +import Observation +import SwiftUI +import CmuxExtensionKit + +@Observable +final class SidebarConnectionModel: @unchecked Sendable { + static let shared = SidebarConnectionModel() + + private(set) var snapshot: CMUXSidebarSnapshot? + private(set) var errorText: String? + + @ObservationIgnored + private var host: CMUXSidebarHostXPC? + + private init() {} + + func accept(connection: NSXPCConnection) -> Bool { + connection.exportedInterface = NSXPCInterface(with: CMUXSidebarExtensionXPC.self) + connection.exportedObject = SidebarExtensionXPCReceiver(model: self) + connection.remoteObjectInterface = NSXPCInterface(with: CMUXSidebarHostXPC.self) + host = connection.remoteObjectProxyWithErrorHandler { [weak self] error in + guard let model = self else { return } + let message = error.localizedDescription + Task { @MainActor in + model.errorText = message + } + } as? CMUXSidebarHostXPC + connection.resume() + refreshSnapshot() + return true + } + + var insights: SidebarInsightModel? { + snapshot.map(SidebarInsightModel.init(snapshot:)) + } + + func refreshSnapshot() { + guard let host else { + errorText = String(localized: "sampleSidebar.waitingForHost", defaultValue: "Waiting for cmux") + return + } + host.requestSidebarSnapshot { [weak self] payload, error in + guard let model = self else { return } + let payload = payload.map { $0 as Data } + let error = error.map { String($0) } + Task { @MainActor in + if let error { + model.errorText = error + return + } + guard let payload else { + model.errorText = String(localized: "sampleSidebar.emptySnapshot", defaultValue: "cmux did not send a workspace snapshot") + return + } + do { + model.snapshot = try CMUXSidebarXPCCodec.decodeSnapshot(payload as NSData) + model.errorText = nil + } catch { + model.errorText = error.localizedDescription + } + } + } + } + + func selectWorkspace(_ id: UUID) { + send(.selectWorkspace(id)) + } + + private func send(_ action: CMUXSidebarAction) { + guard let host else { return } + do { + let payload = try CMUXSidebarXPCCodec.encodeAction(action) + host.performSidebarAction(payload) { [weak self] resultPayload, error in + guard let model = self else { return } + let resultPayload = resultPayload.map { $0 as Data } + let error = error.map { String($0) } + Task { @MainActor in + if let error { + model.errorText = error + return + } + if let resultPayload { + let result = try? CMUXSidebarXPCCodec.decodeActionResult(resultPayload as NSData) + if result?.accepted == false { + model.errorText = result?.message + } + } + } + } + } catch { + errorText = error.localizedDescription + } + } + + fileprivate func receive(snapshot payload: Data) { + do { + snapshot = try CMUXSidebarXPCCodec.decodeSnapshot(payload as NSData) + errorText = nil + } catch { + errorText = error.localizedDescription + } + } +} + +private final class SidebarExtensionXPCReceiver: NSObject, CMUXSidebarExtensionXPC { + weak var model: SidebarConnectionModel? + + init(model: SidebarConnectionModel) { + self.model = model + } + + func sidebarSnapshotDidChange(_ payload: NSData) { + let payload = payload as Data + let model = model + Task { @MainActor in + model?.receive(snapshot: payload) + } + } +} diff --git a/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/Extension/SampleSidebarExtension.swift b/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/Extension/SampleSidebarExtension.swift new file mode 100644 index 000000000000..3aa8735b4eb1 --- /dev/null +++ b/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/Extension/SampleSidebarExtension.swift @@ -0,0 +1,26 @@ +import ExtensionFoundation +import ExtensionKit +import SwiftUI +import CmuxExtensionKit + +@main +final class SampleSidebarExtension: AppExtension { + required init() {} + + @AppExtensionPoint.Bind + var boundExtensionPoint: AppExtensionPoint { + AppExtensionPoint.Identifier("com.manaflow.cmux.sidebar") + } + + var configuration: AppExtensionSceneConfiguration { + AppExtensionSceneConfiguration(self.body) + } + + var body: some AppExtensionScene { + PrimitiveAppExtensionScene(id: "sidebar") { + SampleSidebarView(model: SidebarConnectionModel.shared) + } onConnection: { connection in + SidebarConnectionModel.shared.accept(connection: connection) + } + } +} diff --git a/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/Info.plist b/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/Info.plist new file mode 100644 index 000000000000..7d1a05030b30 --- /dev/null +++ b/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/Info.plist @@ -0,0 +1,11 @@ + + + + + EXAppExtensionAttributes + + EXExtensionPointIdentifier + com.manaflow.cmux.sidebar + + + diff --git a/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/Model/SidebarInsightModel.swift b/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/Model/SidebarInsightModel.swift new file mode 100644 index 000000000000..81c6be675cea --- /dev/null +++ b/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/Model/SidebarInsightModel.swift @@ -0,0 +1,76 @@ +import Foundation +import CmuxExtensionKit + +struct SidebarInsightModel { + var sequence: UInt64 + var totalCount: Int + var pinnedCount: Int + var unreadCount: Int + var portCount: Int + var pullRequestCount: Int + var selectedWorkspace: WorkspaceInsight? + var focusQueue: [WorkspaceInsight] + + init(snapshot: CMUXSidebarSnapshot) { + let insights = snapshot.workspaces.map { + WorkspaceInsight(workspace: $0, selectedWorkspaceID: snapshot.selectedWorkspaceID) + } + sequence = snapshot.sequence + totalCount = insights.count + pinnedCount = insights.filter(\.isPinned).count + unreadCount = insights.reduce(0) { $0 + $1.unreadCount } + portCount = insights.reduce(0) { $0 + $1.portCount } + pullRequestCount = insights.reduce(0) { $0 + $1.pullRequestCount } + selectedWorkspace = insights.first(where: \.isSelected) + focusQueue = insights + .filter(\.hasSignal) + .sorted { lhs, rhs in + if lhs.score != rhs.score { return lhs.score > rhs.score } + return lhs.title.localizedCaseInsensitiveCompare(rhs.title) == .orderedAscending + } + } +} + +struct WorkspaceInsight: Identifiable { + var id: UUID + var title: String + var subtitle: String + var isSelected: Bool + var isPinned: Bool + var unreadCount: Int + var portCount: Int + var pullRequestCount: Int + var branch: String? + var latestNotification: String? + + init(workspace: CMUXSidebarWorkspace, selectedWorkspaceID: UUID?) { + id = workspace.id + title = workspace.title + subtitle = workspace.detail ?? workspace.rootPath?.lastPathComponent ?? workspace.projectRootPath?.lastPathComponent ?? "" + isSelected = workspace.id == selectedWorkspaceID + isPinned = workspace.isPinned + unreadCount = max(0, workspace.unreadCount) + portCount = workspace.listeningPorts.count + pullRequestCount = workspace.pullRequestURLs.count + branch = workspace.gitBranch + latestNotification = workspace.latestNotification + } + + var hasSignal: Bool { + isSelected || isPinned || unreadCount > 0 || portCount > 0 || pullRequestCount > 0 || latestNotification != nil + } + + var score: Int { + (isSelected ? 1000 : 0) + + (unreadCount * 100) + + (portCount * 20) + + (pullRequestCount * 10) + + (isPinned ? 5 : 0) + } +} + +private extension String { + var lastPathComponent: String { + (self as NSString).lastPathComponent + } +} diff --git a/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/UI/SampleSidebarView.swift b/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/UI/SampleSidebarView.swift new file mode 100644 index 000000000000..9a04bc7e2de2 --- /dev/null +++ b/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/UI/SampleSidebarView.swift @@ -0,0 +1,75 @@ +import SwiftUI + +struct SampleSidebarView: View { + var model: SidebarConnectionModel + + var body: some View { + VStack(alignment: .leading, spacing: 12) { + if let insights = model.insights { + header(insights) + if let selected = insights.selectedWorkspace { + WorkspaceInsightRow( + insight: selected, + action: { model.selectWorkspace(selected.id) } + ) + } + Divider() + focusQueue(insights) + } else { + waitingState + } + Spacer(minLength: 0) + } + .padding(.horizontal, 12) + .padding(.vertical, 14) + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) + } + + private func header(_ insights: SidebarInsightModel) -> some View { + VStack(alignment: .leading, spacing: 8) { + Text(String(localized: "sampleSidebar.title", defaultValue: "Workspace Signals")) + .font(.system(size: 14, weight: .semibold)) + HStack(spacing: 6) { + SummaryPill(value: "\(insights.unreadCount)", label: String(localized: "sampleSidebar.unread", defaultValue: "Unread")) + SummaryPill(value: "\(insights.portCount)", label: String(localized: "sampleSidebar.ports", defaultValue: "Ports")) + SummaryPill(value: "\(insights.pullRequestCount)", label: String(localized: "sampleSidebar.prs", defaultValue: "PRs")) + } + } + } + + private func focusQueue(_ insights: SidebarInsightModel) -> some View { + VStack(alignment: .leading, spacing: 7) { + Text(String(localized: "sampleSidebar.focusQueue", defaultValue: "Focus Queue")) + .font(.system(size: 11, weight: .medium)) + .foregroundStyle(.secondary) + if insights.focusQueue.isEmpty { + Text(String(localized: "sampleSidebar.noSignals", defaultValue: "No active workspace signals")) + .font(.system(size: 12)) + .foregroundStyle(.secondary) + } else { + ForEach(insights.focusQueue.prefix(8)) { insight in + WorkspaceInsightRow( + insight: insight, + action: { model.selectWorkspace(insight.id) } + ) + } + } + } + } + + private var waitingState: some View { + VStack(alignment: .leading, spacing: 8) { + ProgressView() + .controlSize(.small) + Text(model.errorText ?? String(localized: "sampleSidebar.waitingForHost", defaultValue: "Waiting for cmux")) + .font(.system(size: 12)) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + Button(String(localized: "sampleSidebar.refresh", defaultValue: "Refresh")) { + model.refreshSnapshot() + } + .buttonStyle(.borderless) + .font(.system(size: 12, weight: .medium)) + } + } +} diff --git a/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/UI/SummaryPill.swift b/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/UI/SummaryPill.swift new file mode 100644 index 000000000000..416157d2ad4f --- /dev/null +++ b/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/UI/SummaryPill.swift @@ -0,0 +1,19 @@ +import SwiftUI + +struct SummaryPill: View { + var value: String + var label: String + + var body: some View { + VStack(spacing: 1) { + Text(value) + .font(.system(size: 13, weight: .semibold)) + Text(label) + .font(.system(size: 9, weight: .medium)) + .foregroundStyle(.secondary) + } + .frame(maxWidth: .infinity) + .padding(.vertical, 5) + .background(.quaternary.opacity(0.35), in: RoundedRectangle(cornerRadius: 6, style: .continuous)) + } +} diff --git a/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/UI/WorkspaceInsightRow.swift b/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/UI/WorkspaceInsightRow.swift new file mode 100644 index 000000000000..432749d88893 --- /dev/null +++ b/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/UI/WorkspaceInsightRow.swift @@ -0,0 +1,56 @@ +import SwiftUI + +struct WorkspaceInsightRow: View { + var insight: WorkspaceInsight + var action: () -> Void + + var body: some View { + Button(action: action) { + HStack(spacing: 8) { + Image(systemName: insight.isSelected ? "target" : "terminal") + .font(.system(size: 12, weight: .semibold)) + .frame(width: 16, height: 16) + .foregroundStyle(insight.isSelected ? .blue : .secondary) + VStack(alignment: .leading, spacing: 2) { + Text(insight.title) + .font(.system(size: 12, weight: .semibold)) + .lineLimit(1) + if !insight.subtitle.isEmpty { + Text(insight.subtitle) + .font(.system(size: 10)) + .foregroundStyle(.secondary) + .lineLimit(1) + } + signalLine + } + Spacer(minLength: 0) + } + .padding(.horizontal, 8) + .padding(.vertical, 7) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .background(insight.isSelected ? Color.blue.opacity(0.16) : Color.clear, in: RoundedRectangle(cornerRadius: 6, style: .continuous)) + } + + private var signalLine: some View { + HStack(spacing: 5) { + if insight.unreadCount > 0 { + Label("\(insight.unreadCount)", systemImage: "bell.badge") + } + if insight.portCount > 0 { + Label("\(insight.portCount)", systemImage: "network") + } + if insight.pullRequestCount > 0 { + Label("\(insight.pullRequestCount)", systemImage: "arrow.triangle.pull") + } + if let branch = insight.branch, !branch.isEmpty { + Label(branch, systemImage: "arrow.branch") + .lineLimit(1) + } + } + .font(.system(size: 9, weight: .medium)) + .foregroundStyle(.secondary) + .labelStyle(.titleAndIcon) + } +} diff --git a/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionApp.xcodeproj/project.pbxproj b/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionApp.xcodeproj/project.pbxproj new file mode 100644 index 000000000000..b19c6fa901e2 --- /dev/null +++ b/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionApp.xcodeproj/project.pbxproj @@ -0,0 +1,777 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 77; + objects = { + +/* Begin PBXBuildFile section */ + C0DE47000000000000000001 /* CmuxExtensionKit in Frameworks */ = {isa = PBXBuildFile; productRef = C0DE47000000000000000002 /* CmuxExtensionKit */; }; + A3685C2E2FCA3B3700009F1B /* SampleSidebarExtension.appex in Embed ExtensionKit Extensions */ = {isa = PBXBuildFile; fileRef = A3685C242FCA3B2500009F1B /* SampleSidebarExtension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + A3685BF72FCA3AF000009F1B /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = A3685BE12FCA3AEE00009F1B /* Project object */; + proxyType = 1; + remoteGlobalIDString = A3685BE82FCA3AEE00009F1B; + remoteInfo = SampleSidebarExtensionApp; + }; + A3685C012FCA3AF000009F1B /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = A3685BE12FCA3AEE00009F1B /* Project object */; + proxyType = 1; + remoteGlobalIDString = A3685BE82FCA3AEE00009F1B; + remoteInfo = SampleSidebarExtensionApp; + }; + A3685C2F2FCA3B3700009F1B /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = A3685BE12FCA3AEE00009F1B /* Project object */; + proxyType = 1; + remoteGlobalIDString = A3685C232FCA3B2500009F1B; + remoteInfo = SampleSidebarExtension; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + A3685C312FCA3B3700009F1B /* Embed ExtensionKit Extensions */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = "$(EXTENSIONS_FOLDER_PATH)"; + dstSubfolderSpec = 16; + files = ( + A3685C2E2FCA3B3700009F1B /* SampleSidebarExtension.appex in Embed ExtensionKit Extensions */, + ); + name = "Embed ExtensionKit Extensions"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + A3685BE92FCA3AEE00009F1B /* SampleSidebarExtensionApp.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = SampleSidebarExtensionApp.app; sourceTree = BUILT_PRODUCTS_DIR; }; + A3685BF62FCA3AF000009F1B /* SampleSidebarExtensionAppTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = SampleSidebarExtensionAppTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + A3685C002FCA3AF000009F1B /* SampleSidebarExtensionAppUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = SampleSidebarExtensionAppUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + A3685C242FCA3B2500009F1B /* SampleSidebarExtension.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.extensionkit-extension"; includeInIndex = 0; path = SampleSidebarExtension.appex; sourceTree = BUILT_PRODUCTS_DIR; }; +/* End PBXFileReference section */ + +/* Begin PBXFileSystemSynchronizedBuildFileExceptionSet section */ + A3685C292FCA3B2500009F1B /* Exceptions for "SampleSidebarExtension" folder in "SampleSidebarExtension" target */ = { + isa = PBXFileSystemSynchronizedBuildFileExceptionSet; + membershipExceptions = ( + Info.plist, + ); + target = A3685C232FCA3B2500009F1B /* SampleSidebarExtension */; + }; +/* End PBXFileSystemSynchronizedBuildFileExceptionSet section */ + +/* Begin PBXFileSystemSynchronizedRootGroup section */ + A3685BEB2FCA3AEE00009F1B /* SampleSidebarExtensionApp */ = { + isa = PBXFileSystemSynchronizedRootGroup; + path = SampleSidebarExtensionApp; + sourceTree = ""; + }; + A3685BF92FCA3AF000009F1B /* SampleSidebarExtensionAppTests */ = { + isa = PBXFileSystemSynchronizedRootGroup; + path = SampleSidebarExtensionAppTests; + sourceTree = ""; + }; + A3685C032FCA3AF000009F1B /* SampleSidebarExtensionAppUITests */ = { + isa = PBXFileSystemSynchronizedRootGroup; + path = SampleSidebarExtensionAppUITests; + sourceTree = ""; + }; + A3685C252FCA3B2500009F1B /* SampleSidebarExtension */ = { + isa = PBXFileSystemSynchronizedRootGroup; + exceptions = ( + A3685C292FCA3B2500009F1B /* Exceptions for "SampleSidebarExtension" folder in "SampleSidebarExtension" target */, + ); + path = SampleSidebarExtension; + sourceTree = ""; + }; +/* End PBXFileSystemSynchronizedRootGroup section */ + +/* Begin PBXFrameworksBuildPhase section */ + A3685BE62FCA3AEE00009F1B /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A3685BF32FCA3AF000009F1B /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A3685BFD2FCA3AF000009F1B /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A3685C212FCA3B2500009F1B /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + C0DE47000000000000000001 /* CmuxExtensionKit in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + A3685BE02FCA3AEE00009F1B = { + isa = PBXGroup; + children = ( + A3685BEB2FCA3AEE00009F1B /* SampleSidebarExtensionApp */, + A3685BF92FCA3AF000009F1B /* SampleSidebarExtensionAppTests */, + A3685C032FCA3AF000009F1B /* SampleSidebarExtensionAppUITests */, + A3685C252FCA3B2500009F1B /* SampleSidebarExtension */, + A3685C2D2FCA3B3700009F1B /* Frameworks */, + A3685BEA2FCA3AEE00009F1B /* Products */, + ); + sourceTree = ""; + }; + A3685BEA2FCA3AEE00009F1B /* Products */ = { + isa = PBXGroup; + children = ( + A3685BE92FCA3AEE00009F1B /* SampleSidebarExtensionApp.app */, + A3685BF62FCA3AF000009F1B /* SampleSidebarExtensionAppTests.xctest */, + A3685C002FCA3AF000009F1B /* SampleSidebarExtensionAppUITests.xctest */, + A3685C242FCA3B2500009F1B /* SampleSidebarExtension.appex */, + ); + name = Products; + sourceTree = ""; + }; + A3685C2D2FCA3B3700009F1B /* Frameworks */ = { + isa = PBXGroup; + children = ( + ); + name = Frameworks; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + A3685BE82FCA3AEE00009F1B /* SampleSidebarExtensionApp */ = { + isa = PBXNativeTarget; + buildConfigurationList = A3685C0A2FCA3AF000009F1B /* Build configuration list for PBXNativeTarget "SampleSidebarExtensionApp" */; + buildPhases = ( + A3685BE52FCA3AEE00009F1B /* Sources */, + A3685BE62FCA3AEE00009F1B /* Frameworks */, + A3685BE72FCA3AEE00009F1B /* Resources */, + A3685C312FCA3B3700009F1B /* Embed ExtensionKit Extensions */, + ); + buildRules = ( + ); + dependencies = ( + A3685C302FCA3B3700009F1B /* PBXTargetDependency */, + ); + fileSystemSynchronizedGroups = ( + A3685BEB2FCA3AEE00009F1B /* SampleSidebarExtensionApp */, + ); + name = SampleSidebarExtensionApp; + packageProductDependencies = ( + ); + productName = SampleSidebarExtensionApp; + productReference = A3685BE92FCA3AEE00009F1B /* SampleSidebarExtensionApp.app */; + productType = "com.apple.product-type.application"; + }; + A3685BF52FCA3AF000009F1B /* SampleSidebarExtensionAppTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = A3685C0D2FCA3AF000009F1B /* Build configuration list for PBXNativeTarget "SampleSidebarExtensionAppTests" */; + buildPhases = ( + A3685BF22FCA3AF000009F1B /* Sources */, + A3685BF32FCA3AF000009F1B /* Frameworks */, + A3685BF42FCA3AF000009F1B /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + A3685BF82FCA3AF000009F1B /* PBXTargetDependency */, + ); + fileSystemSynchronizedGroups = ( + A3685BF92FCA3AF000009F1B /* SampleSidebarExtensionAppTests */, + ); + name = SampleSidebarExtensionAppTests; + packageProductDependencies = ( + ); + productName = SampleSidebarExtensionAppTests; + productReference = A3685BF62FCA3AF000009F1B /* SampleSidebarExtensionAppTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + A3685BFF2FCA3AF000009F1B /* SampleSidebarExtensionAppUITests */ = { + isa = PBXNativeTarget; + buildConfigurationList = A3685C102FCA3AF000009F1B /* Build configuration list for PBXNativeTarget "SampleSidebarExtensionAppUITests" */; + buildPhases = ( + A3685BFC2FCA3AF000009F1B /* Sources */, + A3685BFD2FCA3AF000009F1B /* Frameworks */, + A3685BFE2FCA3AF000009F1B /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + A3685C022FCA3AF000009F1B /* PBXTargetDependency */, + ); + fileSystemSynchronizedGroups = ( + A3685C032FCA3AF000009F1B /* SampleSidebarExtensionAppUITests */, + ); + name = SampleSidebarExtensionAppUITests; + packageProductDependencies = ( + ); + productName = SampleSidebarExtensionAppUITests; + productReference = A3685C002FCA3AF000009F1B /* SampleSidebarExtensionAppUITests.xctest */; + productType = "com.apple.product-type.bundle.ui-testing"; + }; + A3685C232FCA3B2500009F1B /* SampleSidebarExtension */ = { + isa = PBXNativeTarget; + buildConfigurationList = A3685C2A2FCA3B2500009F1B /* Build configuration list for PBXNativeTarget "SampleSidebarExtension" */; + buildPhases = ( + A3685C202FCA3B2500009F1B /* Sources */, + A3685C212FCA3B2500009F1B /* Frameworks */, + A3685C222FCA3B2500009F1B /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + fileSystemSynchronizedGroups = ( + A3685C252FCA3B2500009F1B /* SampleSidebarExtension */, + ); + name = SampleSidebarExtension; + packageProductDependencies = ( + C0DE47000000000000000002 /* CmuxExtensionKit */, + ); + productName = SampleSidebarExtension; + productReference = A3685C242FCA3B2500009F1B /* SampleSidebarExtension.appex */; + productType = "com.apple.product-type.extensionkit-extension"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + A3685BE12FCA3AEE00009F1B /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = 1; + LastSwiftUpdateCheck = 2650; + LastUpgradeCheck = 2650; + TargetAttributes = { + A3685BE82FCA3AEE00009F1B = { + CreatedOnToolsVersion = 26.5; + }; + A3685BF52FCA3AF000009F1B = { + CreatedOnToolsVersion = 26.5; + TestTargetID = A3685BE82FCA3AEE00009F1B; + }; + A3685BFF2FCA3AF000009F1B = { + CreatedOnToolsVersion = 26.5; + TestTargetID = A3685BE82FCA3AEE00009F1B; + }; + A3685C232FCA3B2500009F1B = { + CreatedOnToolsVersion = 26.5; + }; + }; + }; + buildConfigurationList = A3685BE42FCA3AEE00009F1B /* Build configuration list for PBXProject "SampleSidebarExtensionApp" */; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = A3685BE02FCA3AEE00009F1B; + minimizedProjectReferenceProxies = 1; + packageReferences = ( + C0DE47000000000000000003 /* XCLocalSwiftPackageReference "CmuxExtensionKit" */, + ); + preferredProjectObjectVersion = 77; + productRefGroup = A3685BEA2FCA3AEE00009F1B /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + A3685BE82FCA3AEE00009F1B /* SampleSidebarExtensionApp */, + A3685BF52FCA3AF000009F1B /* SampleSidebarExtensionAppTests */, + A3685BFF2FCA3AF000009F1B /* SampleSidebarExtensionAppUITests */, + A3685C232FCA3B2500009F1B /* SampleSidebarExtension */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + A3685BE72FCA3AEE00009F1B /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A3685BF42FCA3AF000009F1B /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A3685BFE2FCA3AF000009F1B /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A3685C222FCA3B2500009F1B /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + A3685BE52FCA3AEE00009F1B /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A3685BF22FCA3AF000009F1B /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A3685BFC2FCA3AF000009F1B /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A3685C202FCA3B2500009F1B /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + A3685BF82FCA3AF000009F1B /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = A3685BE82FCA3AEE00009F1B /* SampleSidebarExtensionApp */; + targetProxy = A3685BF72FCA3AF000009F1B /* PBXContainerItemProxy */; + }; + A3685C022FCA3AF000009F1B /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = A3685BE82FCA3AEE00009F1B /* SampleSidebarExtensionApp */; + targetProxy = A3685C012FCA3AF000009F1B /* PBXContainerItemProxy */; + }; + A3685C302FCA3B3700009F1B /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = A3685C232FCA3B2500009F1B /* SampleSidebarExtension */; + targetProxy = A3685C2F2FCA3B3700009F1B /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin XCBuildConfiguration section */ + A3685C082FCA3AF000009F1B /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + DEVELOPMENT_TEAM = 7WLXT3NR37; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + LOCALIZATION_PREFERS_STRING_CATALOGS = YES; + MACOSX_DEPLOYMENT_TARGET = 26.3; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = macosx; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + A3685C092FCA3AF000009F1B /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEVELOPMENT_TEAM = 7WLXT3NR37; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + LOCALIZATION_PREFERS_STRING_CATALOGS = YES; + MACOSX_DEPLOYMENT_TARGET = 26.3; + MTL_ENABLE_DEBUG_INFO = NO; + MTL_FAST_MATH = YES; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + }; + name = Release; + }; + A3685C0B2FCA3AF000009F1B /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = 7WLXT3NR37; + ENABLE_APP_SANDBOX = YES; + ENABLE_HARDENED_RUNTIME = YES; + ENABLE_PREVIEWS = YES; + ENABLE_USER_SELECTED_FILES = readonly; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_KEY_NSHumanReadableCopyright = ""; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + MACOSX_DEPLOYMENT_TARGET = 26.0; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = co.manaflow.SampleSidebarExtensionApp; + PRODUCT_NAME = "$(TARGET_NAME)"; + REGISTER_APP_GROUPS = YES; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SWIFT_APPROACHABLE_CONCURRENCY = YES; + SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES; + SWIFT_VERSION = 5.0; + }; + name = Debug; + }; + A3685C0C2FCA3AF000009F1B /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = 7WLXT3NR37; + ENABLE_APP_SANDBOX = YES; + ENABLE_HARDENED_RUNTIME = YES; + ENABLE_PREVIEWS = YES; + ENABLE_USER_SELECTED_FILES = readonly; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_KEY_NSHumanReadableCopyright = ""; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + MACOSX_DEPLOYMENT_TARGET = 26.0; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = co.manaflow.SampleSidebarExtensionApp; + PRODUCT_NAME = "$(TARGET_NAME)"; + REGISTER_APP_GROUPS = YES; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SWIFT_APPROACHABLE_CONCURRENCY = YES; + SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES; + SWIFT_VERSION = 5.0; + }; + name = Release; + }; + A3685C0E2FCA3AF000009F1B /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = 7WLXT3NR37; + GENERATE_INFOPLIST_FILE = YES; + MACOSX_DEPLOYMENT_TARGET = 26.3; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = co.manaflow.SampleSidebarExtensionAppTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + STRING_CATALOG_GENERATE_SYMBOLS = NO; + SWIFT_APPROACHABLE_CONCURRENCY = YES; + SWIFT_EMIT_LOC_STRINGS = NO; + SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/SampleSidebarExtensionApp.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/SampleSidebarExtensionApp"; + }; + name = Debug; + }; + A3685C0F2FCA3AF000009F1B /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = 7WLXT3NR37; + GENERATE_INFOPLIST_FILE = YES; + MACOSX_DEPLOYMENT_TARGET = 26.3; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = co.manaflow.SampleSidebarExtensionAppTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + STRING_CATALOG_GENERATE_SYMBOLS = NO; + SWIFT_APPROACHABLE_CONCURRENCY = YES; + SWIFT_EMIT_LOC_STRINGS = NO; + SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/SampleSidebarExtensionApp.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/SampleSidebarExtensionApp"; + }; + name = Release; + }; + A3685C112FCA3AF000009F1B /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = 7WLXT3NR37; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = co.manaflow.SampleSidebarExtensionAppUITests; + PRODUCT_NAME = "$(TARGET_NAME)"; + STRING_CATALOG_GENERATE_SYMBOLS = NO; + SWIFT_APPROACHABLE_CONCURRENCY = YES; + SWIFT_EMIT_LOC_STRINGS = NO; + SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES; + SWIFT_VERSION = 5.0; + TEST_TARGET_NAME = SampleSidebarExtensionApp; + }; + name = Debug; + }; + A3685C122FCA3AF000009F1B /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = 7WLXT3NR37; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = co.manaflow.SampleSidebarExtensionAppUITests; + PRODUCT_NAME = "$(TARGET_NAME)"; + STRING_CATALOG_GENERATE_SYMBOLS = NO; + SWIFT_APPROACHABLE_CONCURRENCY = YES; + SWIFT_EMIT_LOC_STRINGS = NO; + SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES; + SWIFT_VERSION = 5.0; + TEST_TARGET_NAME = SampleSidebarExtensionApp; + }; + name = Release; + }; + A3685C2B2FCA3B2500009F1B /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = 7WLXT3NR37; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_FILE = SampleSidebarExtension/Info.plist; + INFOPLIST_KEY_CFBundleDisplayName = SampleSidebarExtension; + INFOPLIST_KEY_NSHumanReadableCopyright = ""; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@executable_path/../../Frameworks", + ); + MACOSX_DEPLOYMENT_TARGET = 26.0; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = co.manaflow.SampleSidebarExtensionApp.SampleSidebarExtension; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = macosx; + SKIP_INSTALL = YES; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SWIFT_APPROACHABLE_CONCURRENCY = YES; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES; + SWIFT_VERSION = 5.0; + }; + name = Debug; + }; + A3685C2C2FCA3B2500009F1B /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = 7WLXT3NR37; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_FILE = SampleSidebarExtension/Info.plist; + INFOPLIST_KEY_CFBundleDisplayName = SampleSidebarExtension; + INFOPLIST_KEY_NSHumanReadableCopyright = ""; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@executable_path/../../Frameworks", + ); + MACOSX_DEPLOYMENT_TARGET = 26.0; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = co.manaflow.SampleSidebarExtensionApp.SampleSidebarExtension; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = macosx; + SKIP_INSTALL = YES; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SWIFT_APPROACHABLE_CONCURRENCY = YES; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES; + SWIFT_VERSION = 5.0; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + A3685BE42FCA3AEE00009F1B /* Build configuration list for PBXProject "SampleSidebarExtensionApp" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + A3685C082FCA3AF000009F1B /* Debug */, + A3685C092FCA3AF000009F1B /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + A3685C0A2FCA3AF000009F1B /* Build configuration list for PBXNativeTarget "SampleSidebarExtensionApp" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + A3685C0B2FCA3AF000009F1B /* Debug */, + A3685C0C2FCA3AF000009F1B /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + A3685C0D2FCA3AF000009F1B /* Build configuration list for PBXNativeTarget "SampleSidebarExtensionAppTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + A3685C0E2FCA3AF000009F1B /* Debug */, + A3685C0F2FCA3AF000009F1B /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + A3685C102FCA3AF000009F1B /* Build configuration list for PBXNativeTarget "SampleSidebarExtensionAppUITests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + A3685C112FCA3AF000009F1B /* Debug */, + A3685C122FCA3AF000009F1B /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + A3685C2A2FCA3B2500009F1B /* Build configuration list for PBXNativeTarget "SampleSidebarExtension" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + A3685C2B2FCA3B2500009F1B /* Debug */, + A3685C2C2FCA3B2500009F1B /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + +/* Begin XCLocalSwiftPackageReference section */ + C0DE47000000000000000003 /* XCLocalSwiftPackageReference "CmuxExtensionKit" */ = { + isa = XCLocalSwiftPackageReference; + relativePath = ../../Packages/CmuxExtensionKit; + }; +/* End XCLocalSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + C0DE47000000000000000002 /* CmuxExtensionKit */ = { + isa = XCSwiftPackageProductDependency; + package = C0DE47000000000000000003 /* XCLocalSwiftPackageReference "CmuxExtensionKit" */; + productName = CmuxExtensionKit; + }; +/* End XCSwiftPackageProductDependency section */ + }; + rootObject = A3685BE12FCA3AEE00009F1B /* Project object */; +} diff --git a/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionApp/Assets.xcassets/AccentColor.colorset/Contents.json b/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionApp/Assets.xcassets/AccentColor.colorset/Contents.json new file mode 100644 index 000000000000..eb8789700816 --- /dev/null +++ b/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionApp/Assets.xcassets/AccentColor.colorset/Contents.json @@ -0,0 +1,11 @@ +{ + "colors" : [ + { + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionApp/Assets.xcassets/AppIcon.appiconset/Contents.json b/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionApp/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 000000000000..3f00db43ec3c --- /dev/null +++ b/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionApp/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,58 @@ +{ + "images" : [ + { + "idiom" : "mac", + "scale" : "1x", + "size" : "16x16" + }, + { + "idiom" : "mac", + "scale" : "2x", + "size" : "16x16" + }, + { + "idiom" : "mac", + "scale" : "1x", + "size" : "32x32" + }, + { + "idiom" : "mac", + "scale" : "2x", + "size" : "32x32" + }, + { + "idiom" : "mac", + "scale" : "1x", + "size" : "128x128" + }, + { + "idiom" : "mac", + "scale" : "2x", + "size" : "128x128" + }, + { + "idiom" : "mac", + "scale" : "1x", + "size" : "256x256" + }, + { + "idiom" : "mac", + "scale" : "2x", + "size" : "256x256" + }, + { + "idiom" : "mac", + "scale" : "1x", + "size" : "512x512" + }, + { + "idiom" : "mac", + "scale" : "2x", + "size" : "512x512" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionApp/Assets.xcassets/Contents.json b/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionApp/Assets.xcassets/Contents.json new file mode 100644 index 000000000000..73c00596a7fc --- /dev/null +++ b/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionApp/Assets.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionApp/ContentView.swift b/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionApp/ContentView.swift new file mode 100644 index 000000000000..02c73ec19d15 --- /dev/null +++ b/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionApp/ContentView.swift @@ -0,0 +1,31 @@ +// +// ContentView.swift +// SampleSidebarExtensionApp +// +// Created by Abdulaziz Albahar on 5/29/26. +// + +import SwiftUI + +struct ContentView: View { + var body: some View { + VStack(alignment: .leading, spacing: 12) { + Image(systemName: "puzzlepiece.extension") + .imageScale(.large) + .foregroundStyle(.tint) + Text(String(localized: "sampleSidebarApp.title", defaultValue: "CMUX Sample Sidebar Extension")) + .font(.title2.weight(.semibold)) + Text(String( + localized: "sampleSidebarApp.detail", + defaultValue: "Install this app, then choose CMUX Extensions from the cmux sidebar selector to host the extension." + )) + .foregroundStyle(.secondary) + } + .padding(24) + .frame(width: 420, alignment: .leading) + } +} + +#Preview { + ContentView() +} diff --git a/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionApp/SampleSidebarExtensionAppApp.swift b/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionApp/SampleSidebarExtensionAppApp.swift new file mode 100644 index 000000000000..7b64304a5d26 --- /dev/null +++ b/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionApp/SampleSidebarExtensionAppApp.swift @@ -0,0 +1,17 @@ +// +// SampleSidebarExtensionAppApp.swift +// SampleSidebarExtensionApp +// +// Created by Abdulaziz Albahar on 5/29/26. +// + +import SwiftUI + +@main +struct SampleSidebarExtensionAppApp: App { + var body: some Scene { + WindowGroup { + ContentView() + } + } +} diff --git a/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionAppTests/SampleSidebarExtensionAppTests.swift b/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionAppTests/SampleSidebarExtensionAppTests.swift new file mode 100644 index 000000000000..e07db3b2da66 --- /dev/null +++ b/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionAppTests/SampleSidebarExtensionAppTests.swift @@ -0,0 +1,19 @@ +// +// SampleSidebarExtensionAppTests.swift +// SampleSidebarExtensionAppTests +// +// Created by Abdulaziz Albahar on 5/29/26. +// + +import Testing +@testable import SampleSidebarExtensionApp + +struct SampleSidebarExtensionAppTests { + + @Test func example() async throws { + // Write your test here and use APIs like `#expect(...)` to check expected conditions. + // Swift Testing Documentation + // https://developer.apple.com/documentation/testing + } + +} diff --git a/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionAppUITests/SampleSidebarExtensionAppUITests.swift b/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionAppUITests/SampleSidebarExtensionAppUITests.swift new file mode 100644 index 000000000000..b5b60426233a --- /dev/null +++ b/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionAppUITests/SampleSidebarExtensionAppUITests.swift @@ -0,0 +1,43 @@ +// +// SampleSidebarExtensionAppUITests.swift +// SampleSidebarExtensionAppUITests +// +// Created by Abdulaziz Albahar on 5/29/26. +// + +import XCTest + +final class SampleSidebarExtensionAppUITests: XCTestCase { + + override func setUpWithError() throws { + // Put setup code here. This method is called before the invocation of each test method in the class. + + // In UI tests it is usually best to stop immediately when a failure occurs. + continueAfterFailure = false + + // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. + } + + override func tearDownWithError() throws { + // Put teardown code here. This method is called after the invocation of each test method in the class. + } + + @MainActor + func testExample() throws { + // UI tests must launch the application that they test. + let app = XCUIApplication() + app.launch() + + // Use XCTAssert and related functions to verify your tests produce the correct results. + // XCUIAutomation Documentation + // https://developer.apple.com/documentation/xcuiautomation + } + + @MainActor + func testLaunchPerformance() throws { + // This measures how long it takes to launch your application. + measure(metrics: [XCTApplicationLaunchMetric()]) { + XCUIApplication().launch() + } + } +} diff --git a/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionAppUITests/SampleSidebarExtensionAppUITestsLaunchTests.swift b/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionAppUITests/SampleSidebarExtensionAppUITestsLaunchTests.swift new file mode 100644 index 000000000000..5341d2bd6f64 --- /dev/null +++ b/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionAppUITests/SampleSidebarExtensionAppUITestsLaunchTests.swift @@ -0,0 +1,35 @@ +// +// SampleSidebarExtensionAppUITestsLaunchTests.swift +// SampleSidebarExtensionAppUITests +// +// Created by Abdulaziz Albahar on 5/29/26. +// + +import XCTest + +final class SampleSidebarExtensionAppUITestsLaunchTests: XCTestCase { + + override class var runsForEachTargetApplicationUIConfiguration: Bool { + true + } + + override func setUpWithError() throws { + continueAfterFailure = false + } + + @MainActor + func testLaunch() throws { + let app = XCUIApplication() + app.launch() + + // Insert steps here to perform after app launch but before taking a screenshot, + // such as logging into a test account or navigating somewhere in the app + // XCUIAutomation Documentation + // https://developer.apple.com/documentation/xcuiautomation + + let attachment = XCTAttachment(screenshot: app.screenshot()) + attachment.name = "Launch Screen" + attachment.lifetime = .keepAlways + add(attachment) + } +} diff --git a/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Hosting/CMUXSidebarExtensionHostView.swift b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Hosting/CMUXSidebarExtensionHostView.swift index de57d4a5f815..c2f0503e6605 100644 --- a/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Hosting/CMUXSidebarExtensionHostView.swift +++ b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Hosting/CMUXSidebarExtensionHostView.swift @@ -1,5 +1,6 @@ import ExtensionFoundation import ExtensionKit +import Foundation import SwiftUI @available(macOS 14.0, *) @@ -8,8 +9,31 @@ public struct CMUXSidebarExtensionHostView: NSViewControllerRepresentable { public typealias NSViewControllerType = EXHostViewController /// Tracks the configuration currently installed on the host view controller. - public final class Coordinator { + public final class Coordinator: NSObject, EXHostViewControllerDelegate { fileprivate var currentKey: HostConfigurationKey? + private let onConnection: (@MainActor (NSXPCConnection) -> Void)? + private let onDeactivation: (@MainActor (Error?) -> Void)? + + fileprivate init( + onConnection: (@MainActor (NSXPCConnection) -> Void)?, + onDeactivation: (@MainActor (Error?) -> Void)? + ) { + self.onConnection = onConnection + self.onDeactivation = onDeactivation + } + + public func hostViewControllerDidActivate(_ viewController: EXHostViewController) { + guard let onConnection else { return } + do { + onConnection(try viewController.makeXPCConnection()) + } catch { + onDeactivation?(error) + } + } + + public func hostViewControllerWillDeactivate(_ viewController: EXHostViewController, error: (any Error)?) { + onDeactivation?(error) + } } fileprivate struct HostConfigurationKey: Equatable { @@ -19,20 +43,29 @@ public struct CMUXSidebarExtensionHostView: NSViewControllerRepresentable { private let identity: AppExtensionIdentity private let sceneID: String + private let onConnection: (@MainActor (NSXPCConnection) -> Void)? + private let onDeactivation: (@MainActor (Error?) -> Void)? /// Creates a sidebar extension host view. /// - Parameters: /// - identity: Extension identity to host. /// - sceneID: ExtensionKit scene identifier to render. - public init(identity: AppExtensionIdentity, sceneID: String = CMUXSidebarExtensionPoint.defaultSceneID) { + public init( + identity: AppExtensionIdentity, + sceneID: String = CMUXSidebarExtensionPoint.defaultSceneID, + onConnection: (@MainActor (NSXPCConnection) -> Void)? = nil, + onDeactivation: (@MainActor (Error?) -> Void)? = nil + ) { self.identity = identity self.sceneID = sceneID + self.onConnection = onConnection + self.onDeactivation = onDeactivation } /// Creates the configuration-tracking coordinator. /// - Returns: Coordinator for the hosted extension configuration. public func makeCoordinator() -> Coordinator { - Coordinator() + Coordinator(onConnection: onConnection, onDeactivation: onDeactivation) } /// Creates the ExtensionKit host view controller. @@ -40,6 +73,7 @@ public struct CMUXSidebarExtensionHostView: NSViewControllerRepresentable { /// - Returns: Configured `EXHostViewController`. public func makeNSViewController(context: Context) -> EXHostViewController { let viewController = EXHostViewController() + viewController.delegate = context.coordinator context.coordinator.currentKey = configurationKey viewController.configuration = EXHostViewController.Configuration( appExtension: identity, diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarXPC.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarXPC.swift new file mode 100644 index 000000000000..cfd72831706e --- /dev/null +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarXPC.swift @@ -0,0 +1,36 @@ +import Foundation + +@objc public protocol CMUXSidebarHostXPC { + func requestSidebarSnapshot(reply: @escaping (NSData?, NSString?) -> Void) + func performSidebarAction(_ payload: NSData, reply: @escaping (NSData?, NSString?) -> Void) +} + +@objc public protocol CMUXSidebarExtensionXPC { + func sidebarSnapshotDidChange(_ payload: NSData) +} + +public enum CMUXSidebarXPCCodec { + public static func encodeSnapshot(_ snapshot: CMUXSidebarSnapshot) throws -> NSData { + try JSONEncoder().encode(snapshot) as NSData + } + + public static func decodeSnapshot(_ payload: NSData) throws -> CMUXSidebarSnapshot { + try JSONDecoder().decode(CMUXSidebarSnapshot.self, from: payload as Data) + } + + public static func encodeAction(_ action: CMUXSidebarAction) throws -> NSData { + try JSONEncoder().encode(action) as NSData + } + + public static func decodeAction(_ payload: NSData) throws -> CMUXSidebarAction { + try JSONDecoder().decode(CMUXSidebarAction.self, from: payload as Data) + } + + public static func encodeActionResult(_ result: CMUXExtensionActionResult) throws -> NSData { + try JSONEncoder().encode(result) as NSData + } + + public static func decodeActionResult(_ payload: NSData) throws -> CMUXExtensionActionResult { + try JSONDecoder().decode(CMUXExtensionActionResult.self, from: payload as Data) + } +} diff --git a/Packages/CmuxExtensionKit/Tests/CmuxExtensionKitTests/CmuxExtensionKitTests.swift b/Packages/CmuxExtensionKit/Tests/CmuxExtensionKitTests/CmuxExtensionKitTests.swift index 13d11e6faa40..c3b7e2011b83 100644 --- a/Packages/CmuxExtensionKit/Tests/CmuxExtensionKitTests/CmuxExtensionKitTests.swift +++ b/Packages/CmuxExtensionKit/Tests/CmuxExtensionKitTests/CmuxExtensionKitTests.swift @@ -46,6 +46,46 @@ struct CMUXExtensionKitTests { try CMUXExtensionValidator.validateSidebarManifest(manifest) } + @Test + func testSidebarXPCCodecRoundTripsSnapshotActionAndResult() throws { + let workspaceID = UUID(uuidString: "33333333-3333-3333-3333-333333333333")! + let snapshot = CMUXSidebarSnapshot( + sequence: 43, + selectedWorkspaceID: workspaceID, + workspaces: [ + CMUXSidebarWorkspace( + id: workspaceID, + title: "Build", + detail: "Running tests", + isPinned: true, + rootPath: "/tmp/cmux", + projectRootPath: "/tmp/cmux", + gitBranch: "feature/sidebar", + unreadCount: 2, + latestNotification: "Tests failed", + listeningPorts: [3000], + pullRequestURLs: ["https://github.com/manaflow-ai/cmux/pull/4994"] + ), + ] + ) + let decodedSnapshot = try CMUXSidebarXPCCodec.decodeSnapshot( + try CMUXSidebarXPCCodec.encodeSnapshot(snapshot) + ) + #expect(decodedSnapshot == snapshot) + + let action = CMUXSidebarAction.selectWorkspace(workspaceID) + let decodedAction = try CMUXSidebarXPCCodec.decodeAction( + try CMUXSidebarXPCCodec.encodeAction(action) + ) + #expect(decodedAction == action) + + let result = CMUXExtensionActionResult(accepted: false, message: "Not found") + let decodedResult = try CMUXSidebarXPCCodec.decodeActionResult( + try CMUXSidebarXPCCodec.encodeActionResult(result) + ) + #expect(decodedResult == result) + } + @Test func testManifestValidationRejectsUnsupportedAPIVersion() { let manifest = CMUXExtensionManifest( diff --git a/Sources/CMUXInstalledExtensionSidebarHostView.swift b/Sources/CMUXInstalledExtensionSidebarHostView.swift index dca9eaeba0d8..60282a238ba1 100644 --- a/Sources/CMUXInstalledExtensionSidebarHostView.swift +++ b/Sources/CMUXInstalledExtensionSidebarHostView.swift @@ -1,16 +1,34 @@ import CMUXExtensionClient +import CmuxExtensionKit import ExtensionFoundation import SwiftUI struct CMUXInstalledExtensionSidebarHostView: View { + var snapshotProvider: @MainActor () -> CMUXSidebarSnapshot + var actionHandler: @MainActor (CMUXSidebarAction) -> CMUXExtensionActionResult + @State private var identity: AppExtensionIdentity? @State private var isLoading = true @State private var errorText: String? + @State private var xpcHost = CMUXSidebarExtensionHostXPC() var body: some View { Group { if let identity { - CMUXSidebarExtensionHostView(identity: identity) + CMUXSidebarExtensionHostView( + identity: identity, + onConnection: { connection in + xpcHost.attach( + connection: connection, + snapshotProvider: snapshotProvider, + actionHandler: actionHandler + ) + }, + onDeactivation: { error in + xpcHost.invalidate() + errorText = error?.localizedDescription + } + ) .accessibilityIdentifier("CMUXExtensionSidebarHostView") } else { VStack(alignment: .leading, spacing: 10) { @@ -43,8 +61,12 @@ struct CMUXInstalledExtensionSidebarHostView: View { } } .task { + xpcHost.update(snapshotProvider: snapshotProvider, actionHandler: actionHandler) await loadExtension() } + .onChange(of: snapshotProvider().sequence) { _, _ in + xpcHost.sendSnapshotDidChange() + } } private func loadExtension() async { @@ -70,3 +92,116 @@ struct CMUXInstalledExtensionSidebarHostView: View { } } } + +@MainActor +private final class CMUXSidebarExtensionHostXPC { + private var connection: NSXPCConnection? + private var extensionProxy: CMUXSidebarExtensionXPC? + private var exportedObject: CMUXSidebarHostXPCObject? + private var snapshotProvider: (() -> CMUXSidebarSnapshot)? + private var actionHandler: ((CMUXSidebarAction) -> CMUXExtensionActionResult)? + + func update( + snapshotProvider: @escaping @MainActor () -> CMUXSidebarSnapshot, + actionHandler: @escaping @MainActor (CMUXSidebarAction) -> CMUXExtensionActionResult + ) { + self.snapshotProvider = snapshotProvider + self.actionHandler = actionHandler + exportedObject?.snapshotProvider = snapshotProvider + exportedObject?.actionHandler = actionHandler + } + + func attach( + connection: NSXPCConnection, + snapshotProvider: @escaping @MainActor () -> CMUXSidebarSnapshot, + actionHandler: @escaping @MainActor (CMUXSidebarAction) -> CMUXExtensionActionResult + ) { + invalidate() + let exportedObject = CMUXSidebarHostXPCObject( + snapshotProvider: snapshotProvider, + actionHandler: actionHandler + ) + connection.exportedInterface = NSXPCInterface(with: CMUXSidebarHostXPC.self) + connection.exportedObject = exportedObject + connection.remoteObjectInterface = NSXPCInterface(with: CMUXSidebarExtensionXPC.self) + connection.invalidationHandler = { [weak self] in + Task { @MainActor in + self?.clearConnection() + } + } + connection.interruptionHandler = { [weak self] in + Task { @MainActor in + self?.clearProxy() + } + } + self.exportedObject = exportedObject + self.snapshotProvider = snapshotProvider + self.actionHandler = actionHandler + self.connection = connection + self.extensionProxy = connection.remoteObjectProxy as? CMUXSidebarExtensionXPC + connection.resume() + sendSnapshotDidChange() + } + + func sendSnapshotDidChange() { + guard let extensionProxy, let snapshotProvider else { return } + do { + extensionProxy.sidebarSnapshotDidChange(try CMUXSidebarXPCCodec.encodeSnapshot(snapshotProvider())) + } catch { +#if DEBUG + cmuxDebugLog("extension.sidebar.xpc.snapshot.encode.failed error=\(error.localizedDescription)") +#endif + } + } + + func invalidate() { + connection?.invalidate() + clearConnection() + } + + private func clearProxy() { + extensionProxy = nil + } + + private func clearConnection() { + connection = nil + extensionProxy = nil + exportedObject = nil + } +} + +private final class CMUXSidebarHostXPCObject: NSObject, CMUXSidebarHostXPC { + @MainActor var snapshotProvider: () -> CMUXSidebarSnapshot + @MainActor var actionHandler: (CMUXSidebarAction) -> CMUXExtensionActionResult + + @MainActor + init( + snapshotProvider: @escaping @MainActor () -> CMUXSidebarSnapshot, + actionHandler: @escaping @MainActor (CMUXSidebarAction) -> CMUXExtensionActionResult + ) { + self.snapshotProvider = snapshotProvider + self.actionHandler = actionHandler + } + + func requestSidebarSnapshot(reply: @escaping (NSData?, NSString?) -> Void) { + Task { @MainActor in + do { + reply(try CMUXSidebarXPCCodec.encodeSnapshot(snapshotProvider()), nil) + } catch { + reply(nil, error.localizedDescription as NSString) + } + } + } + + func performSidebarAction(_ payload: NSData, reply: @escaping (NSData?, NSString?) -> Void) { + Task { @MainActor in + do { + let action = try CMUXSidebarXPCCodec.decodeAction(payload) + let result = actionHandler(action) + reply(try CMUXSidebarXPCCodec.encodeActionResult(result), nil) + } catch { + reply(nil, error.localizedDescription as NSString) + } + } + } +} diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index d17afd2cb3bc..06c826c3b8fc 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -2292,6 +2292,9 @@ struct ContentView: View { anchorView: fullscreenControlsViewModel.notificationsAnchorView ) }, + onShowSidebarProviderMenu: { anchorView in + CmuxExtensionSidebarSelection.showMenu(anchorView: anchorView, event: nil) + }, onNewTab: { AppDelegate.shared?.performNewWorkspaceAction( tabManager: tabManager, @@ -2353,18 +2356,20 @@ struct ContentView: View { fullscreenControls } - // Draggable folder icon + focused command name - if let directory = focusedDirectory { - DetachedFolderDragIcon(directory: directory) - .frame(width: 16, height: 16) - .padding(.leading, -6) - } + if !sidebarState.isVisible { + // Draggable folder icon + focused command name + if let directory = focusedDirectory { + DetachedFolderDragIcon(directory: directory) + .frame(width: 16, height: 16) + .padding(.leading, -6) + } - Text(titlebarText) - .font(.system(size: 13, weight: .bold)) - .foregroundColor(fakeTitlebarTextColor(appearance: appearance)) - .lineLimit(1) - .allowsHitTesting(false) + Text(titlebarText) + .font(.system(size: 13, weight: .bold)) + .foregroundColor(fakeTitlebarTextColor(appearance: appearance)) + .lineLimit(1) + .allowsHitTesting(false) + } Spacer() @@ -10612,7 +10617,10 @@ struct VerticalTabsSidebar: View { @ViewBuilder private func extensionSidebarScrollArea(renderContext: WorkspaceListRenderContext) -> some View { if selectedExtensionSidebarProviderId == CmuxExtensionSidebarSelection.hostedExtensionsProviderId { - CMUXInstalledExtensionSidebarHostView() + CMUXInstalledExtensionSidebarHostView( + snapshotProvider: { cmuxSidebarSnapshotForCurrentTabs() }, + actionHandler: { handleCMUXSidebarExtensionAction($0) } + ) } else { TimelineView(.periodic(from: .now, by: 30)) { timeline in let model = extensionSidebarRenderModel(renderContext: renderContext, now: timeline.date) @@ -10806,6 +10814,64 @@ struct VerticalTabsSidebar: View { extensionSidebarSnapshot(workspaces: tabManager.tabs) } + private func cmuxSidebarSnapshotForCurrentTabs() -> CMUXSidebarSnapshot { + let snapshot = extensionSidebarSnapshotForCurrentTabs() + return CMUXSidebarSnapshot( + sequence: snapshot.sequence, + windowID: snapshot.windowId, + selectedWorkspaceID: snapshot.selectedWorkspaceId, + workspaces: snapshot.workspaces.map { workspace in + CMUXSidebarWorkspace( + id: workspace.id, + title: workspace.title, + detail: workspace.customDescription, + isPinned: workspace.isPinned, + rootPath: workspace.rootPath, + projectRootPath: workspace.projectRootPath, + gitBranch: workspace.branchSummary, + unreadCount: workspace.unreadCount, + latestNotification: workspace.latestNotificationText, + listeningPorts: workspace.listeningPorts, + pullRequestURLs: workspace.pullRequestURLs + ) + } + ) + } + + private func handleCMUXSidebarExtensionAction( + _ action: CMUXSidebarAction + ) -> CMUXExtensionActionResult { + switch action { + case .selectWorkspace(let workspaceId): + guard let workspace = tabManager.tabs.first(where: { $0.id == workspaceId }) else { + return CMUXExtensionActionResult( + accepted: false, + message: String(localized: "sidebar.extensions.action.workspaceNotFound", defaultValue: "Workspace not found") + ) + } + tabManager.selectWorkspace(workspace) + return .accepted + + case .closeWorkspace(let workspaceId): + guard tabManager.closeWorkspaceWithConfirmation(tabId: workspaceId) else { + return CMUXExtensionActionResult( + accepted: false, + message: String(localized: "sidebar.extensions.action.closeRejected", defaultValue: "Workspace could not be closed") + ) + } + return .accepted + + case .openURL(let urlString): + guard let url = URL(string: urlString), NSWorkspace.shared.open(url) else { + return CMUXExtensionActionResult( + accepted: false, + message: String(localized: "sidebar.extensions.action.urlRejected", defaultValue: "URL could not be opened") + ) + } + return .accepted + } + } + private func extensionSidebarSnapshot(workspaces: [Workspace]) -> CmuxExtensionSidebarSnapshot { CmuxExtensionSidebarSnapshot( sequence: UInt64(max(0, CmuxEventBus.shared.latestSequence)), diff --git a/Sources/Update/MinimalModeSidebarControls.swift b/Sources/Update/MinimalModeSidebarControls.swift index 7a777e240ac0..98df7b492605 100644 --- a/Sources/Update/MinimalModeSidebarControls.swift +++ b/Sources/Update/MinimalModeSidebarControls.swift @@ -194,6 +194,8 @@ final class MinimalModeSidebarControlActionView: NSView { return } switch slot { + case .sidebarProvider: + CmuxExtensionSidebarSelection.showMenu(anchorView: self, event: event) case .newTab: _ = AppDelegate.shared?.showNewWorkspaceContextMenu(anchorView: self, event: event) case .focusHistoryBack: diff --git a/Sources/Update/UpdateTitlebarAccessory.swift b/Sources/Update/UpdateTitlebarAccessory.swift index a14cf10751fa..a1513f94571e 100644 --- a/Sources/Update/UpdateTitlebarAccessory.swift +++ b/Sources/Update/UpdateTitlebarAccessory.swift @@ -133,6 +133,7 @@ func titlebarControlPressedScale(isPressed _: Bool) -> CGFloat { final class TitlebarControlsViewModel: ObservableObject { weak var notificationsAnchorView: NSView? + weak var sidebarProviderAnchorView: NSView? } @MainActor @@ -311,6 +312,21 @@ struct NotificationsAnchorView: NSViewRepresentable { func updateNSView(_ nsView: NSView, context: Context) {} } +struct TitlebarControlAnchorView: NSViewRepresentable { + let onResolve: (NSView) -> Void + + func makeNSView(context: Context) -> NSView { + let view = AnchorNSView() + view.onLayout = { [weak view] in + guard let view else { return } + onResolve(view) + } + return view + } + + func updateNSView(_ nsView: NSView, context: Context) {} +} + final class AnchorNSView: NSView { var onLayout: (() -> Void)? @@ -415,12 +431,28 @@ enum TitlebarShortcutHintActionSlot: Int, CaseIterable { return .focusHistoryForward } } + + var titlebarButtonIndex: Int { + switch self { + case .toggleSidebar: + return 0 + case .showNotifications: + return 2 + case .newTab: + return 3 + case .focusHistoryBack: + return 4 + case .focusHistoryForward: + return 5 + } + } } enum TitlebarControlsLayoutMetrics { static let outerLeadingPadding: CGFloat = TitlebarControlsHitRegions.outerLeadingPadding static let hintRightSafetyShift: CGFloat = 10 static let hintTrailingBaseInset: CGFloat = 8 + static let extraButtonCount = 1 static func hintTrailingInset(titlebarShortcutHintXOffset: Double = ShortcutHintDebugSettings.defaultTitlebarHintX) -> CGFloat { max(0, ShortcutHintDebugSettings.clamped(titlebarShortcutHintXOffset)) @@ -429,7 +461,7 @@ enum TitlebarControlsLayoutMetrics { } static func buttonRowWidth(config: TitlebarControlsStyleConfig) -> CGFloat { - let buttonCount = CGFloat(TitlebarShortcutHintActionSlot.allCases.count) + let buttonCount = CGFloat(TitlebarShortcutHintActionSlot.allCases.count + extraButtonCount) let gapCount = max(0, buttonCount - 1) return (buttonCount * config.buttonSize) + (gapCount * config.spacing) } @@ -705,6 +737,7 @@ struct TitlebarControlsView: View { @ObservedObject var viewModel: TitlebarControlsViewModel let onToggleSidebar: () -> Void let onToggleNotifications: () -> Void + let onShowSidebarProviderMenu: (NSView) -> Void let onNewTab: () -> Void let onFocusHistoryBack: () -> Void let onFocusHistoryForward: () -> Void @@ -842,6 +875,27 @@ struct TitlebarControlsView: View { } .safeHelp(KeyboardShortcutSettings.Action.toggleSidebar.tooltip(String(localized: "titlebar.sidebar.tooltip", defaultValue: "Show or hide the sidebar"))) + TitlebarControlButton( + config: config, + foregroundColor: foregroundColor, + accessibilityIdentifier: "titlebarControl.sidebarProvider", + accessibilityLabel: String(localized: "command.switchExtensionSidebar.subtitle", defaultValue: "Sidebar"), + action: { + guard let anchorView = viewModel.sidebarProviderAnchorView else { return } + onShowSidebarProviderMenu(anchorView) + }, + rightClickAction: { anchorView, event in + CmuxExtensionSidebarSelection.showMenu(anchorView: anchorView, event: event) + }) { + iconLabel( + systemName: "puzzlepiece.extension", + config: config, + iconGeometryKeyPrefix: "titlebarControl_sidebarProviderIcon" + ) + } + .background(TitlebarControlAnchorView { viewModel.sidebarProviderAnchorView = $0 }) + .safeHelp(String(localized: "command.switchExtensionSidebar.subtitle", defaultValue: "Sidebar")) + TitlebarControlButton( config: config, foregroundColor: foregroundColor, @@ -1024,7 +1078,7 @@ struct TitlebarControlsView: View { } private func titlebarButtonRightEdge(for slot: TitlebarShortcutHintActionSlot, config: TitlebarControlsStyleConfig) -> CGFloat { - let index = CGFloat(slot.rawValue) + let index = CGFloat(slot.titlebarButtonIndex) return (index + 1) * config.buttonSize + index * config.spacing } @@ -1282,6 +1336,9 @@ struct HiddenTitlebarSidebarControlsView: View { onToggleNotifications: { [viewModel] in onToggleNotifications(viewModel.notificationsAnchorView) }, + onShowSidebarProviderMenu: { anchorView in + CmuxExtensionSidebarSelection.showMenu(anchorView: anchorView, event: nil) + }, onNewTab: onNewTab, onFocusHistoryBack: onFocusHistoryBack, onFocusHistoryForward: onFocusHistoryForward, @@ -1310,6 +1367,8 @@ struct HiddenTitlebarSidebarControlsView: View { switch slot { case .toggleSidebar: onToggleSidebar() + case .sidebarProvider: + CmuxExtensionSidebarSelection.showMenu(anchorView: anchorView, event: nil) case .showNotifications: onToggleNotifications(anchorView) case .newTab: @@ -1818,6 +1877,9 @@ final class TitlebarControlsAccessoryViewController: NSTitlebarAccessoryViewCont let toggleNotifications: () -> Void = { [weak containerView] in _ = AppDelegate.shared?.toggleNotificationsPopover(animated: true, anchorView: containerView) } + let showSidebarProviderMenu: (NSView) -> Void = { anchorView in + CmuxExtensionSidebarSelection.showMenu(anchorView: anchorView, event: nil) + } let newTab = { _ = AppDelegate.shared?.performNewWorkspaceAction(debugSource: "titlebar.accessoryNewWorkspace") } let focusHistoryBack = { [weak containerView] in _ = AppDelegate.shared?.activeTabManagerForCommands(preferredWindow: containerView?.window)?.navigateBack() @@ -1831,6 +1893,7 @@ final class TitlebarControlsAccessoryViewController: NSTitlebarAccessoryViewCont viewModel: viewModel, onToggleSidebar: toggleSidebar, onToggleNotifications: toggleNotifications, + onShowSidebarProviderMenu: showSidebarProviderMenu, onNewTab: newTab, onFocusHistoryBack: focusHistoryBack, onFocusHistoryForward: focusHistoryForward, diff --git a/Sources/WindowDecorationsController.swift b/Sources/WindowDecorationsController.swift index 733cccde7076..750f51b2caab 100644 --- a/Sources/WindowDecorationsController.swift +++ b/Sources/WindowDecorationsController.swift @@ -338,6 +338,10 @@ final class WindowDecorationsController { switch slot { case .toggleSidebar: _ = AppDelegate.shared?.toggleSidebarInActiveMainWindow(preferredWindow: window) + case .sidebarProvider: + if let anchorView { + CmuxExtensionSidebarSelection.showMenu(anchorView: anchorView, event: nil) + } case .showNotifications: let resolvedAnchorView = NotificationsAnchorRegistry.shared.closestAnchor( in: window, diff --git a/Sources/WindowDragHandleView.swift b/Sources/WindowDragHandleView.swift index 11f6d8d508e6..7f82f5a6c30e 100644 --- a/Sources/WindowDragHandleView.swift +++ b/Sources/WindowDragHandleView.swift @@ -783,6 +783,7 @@ private func minimalModeTrafficLightFrameInContentCoordinates(for window: NSWind enum MinimalModeSidebarControlActionSlot: Int, CaseIterable { case toggleSidebar + case sidebarProvider case showNotifications case newTab case focusHistoryBack @@ -792,6 +793,8 @@ enum MinimalModeSidebarControlActionSlot: Int, CaseIterable { switch self { case .toggleSidebar: return "titlebarControl.toggleSidebar" + case .sidebarProvider: + return "titlebarControl.sidebarProvider" case .showNotifications: return "titlebarControl.showNotifications" case .newTab: @@ -807,6 +810,8 @@ enum MinimalModeSidebarControlActionSlot: Int, CaseIterable { switch self { case .toggleSidebar: return String(localized: "titlebar.sidebar.accessibilityLabel", defaultValue: "Toggle Sidebar") + case .sidebarProvider: + return String(localized: "command.switchExtensionSidebar.subtitle", defaultValue: "Sidebar") case .showNotifications: return String(localized: "titlebar.notifications.accessibilityLabel", defaultValue: "Notifications") case .newTab: @@ -822,6 +827,8 @@ enum MinimalModeSidebarControlActionSlot: Int, CaseIterable { switch self { case .toggleSidebar: return "toggleSidebar" + case .sidebarProvider: + return "sidebarProvider" case .showNotifications: return "showNotifications" case .newTab: @@ -835,7 +842,7 @@ enum MinimalModeSidebarControlActionSlot: Int, CaseIterable { var acceptsContextMenu: Bool { switch self { - case .newTab, .focusHistoryBack, .focusHistoryForward: + case .sidebarProvider, .newTab, .focusHistoryBack, .focusHistoryForward: return true case .toggleSidebar, .showNotifications: return false diff --git a/cmux.xcworkspace/contents.xcworkspacedata b/cmux.xcworkspace/contents.xcworkspacedata index eb54d885c873..af497f2aa058 100644 --- a/cmux.xcworkspace/contents.xcworkspacedata +++ b/cmux.xcworkspace/contents.xcworkspacedata @@ -39,7 +39,7 @@ location = "container:Examples" name = "Examples"> + location = "group:SampleSidebarExtensionApp/SampleSidebarExtensionApp.xcodeproj"> From 9e44614ce16c33f1dcef8d253fa2cb0060bdf34e Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Fri, 29 May 2026 16:49:24 -0500 Subject: [PATCH 07/44] Give sample sidebar extension a unique app identity --- .../project.pbxproj | 20 ++-- .../CMUXExtKitSampleSidebarApp.xcscheme | 91 +++++++++++++++++++ 2 files changed, 101 insertions(+), 10 deletions(-) create mode 100644 Examples/SampleSidebarExtensionApp/SampleSidebarExtensionApp.xcodeproj/xcshareddata/xcschemes/CMUXExtKitSampleSidebarApp.xcscheme diff --git a/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionApp.xcodeproj/project.pbxproj b/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionApp.xcodeproj/project.pbxproj index b19c6fa901e2..c0c00ba6d525 100644 --- a/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionApp.xcodeproj/project.pbxproj +++ b/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionApp.xcodeproj/project.pbxproj @@ -524,8 +524,8 @@ ); MACOSX_DEPLOYMENT_TARGET = 26.0; MARKETING_VERSION = 1.0; - PRODUCT_BUNDLE_IDENTIFIER = co.manaflow.SampleSidebarExtensionApp; - PRODUCT_NAME = "$(TARGET_NAME)"; + PRODUCT_BUNDLE_IDENTIFIER = co.manaflow.CMUXExtKitSampleSidebarApp; + PRODUCT_NAME = "CMUX ExtKit Sample Sidebar"; REGISTER_APP_GROUPS = YES; STRING_CATALOG_GENERATE_SYMBOLS = YES; SWIFT_APPROACHABLE_CONCURRENCY = YES; @@ -557,8 +557,8 @@ ); MACOSX_DEPLOYMENT_TARGET = 26.0; MARKETING_VERSION = 1.0; - PRODUCT_BUNDLE_IDENTIFIER = co.manaflow.SampleSidebarExtensionApp; - PRODUCT_NAME = "$(TARGET_NAME)"; + PRODUCT_BUNDLE_IDENTIFIER = co.manaflow.CMUXExtKitSampleSidebarApp; + PRODUCT_NAME = "CMUX ExtKit Sample Sidebar"; REGISTER_APP_GROUPS = YES; STRING_CATALOG_GENERATE_SYMBOLS = YES; SWIFT_APPROACHABLE_CONCURRENCY = YES; @@ -657,7 +657,7 @@ DEVELOPMENT_TEAM = 7WLXT3NR37; GENERATE_INFOPLIST_FILE = YES; INFOPLIST_FILE = SampleSidebarExtension/Info.plist; - INFOPLIST_KEY_CFBundleDisplayName = SampleSidebarExtension; + INFOPLIST_KEY_CFBundleDisplayName = "CMUX ExtKit Sample Sidebar"; INFOPLIST_KEY_NSHumanReadableCopyright = ""; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", @@ -666,8 +666,8 @@ ); MACOSX_DEPLOYMENT_TARGET = 26.0; MARKETING_VERSION = 1.0; - PRODUCT_BUNDLE_IDENTIFIER = co.manaflow.SampleSidebarExtensionApp.SampleSidebarExtension; - PRODUCT_NAME = "$(TARGET_NAME)"; + PRODUCT_BUNDLE_IDENTIFIER = co.manaflow.CMUXExtKitSampleSidebarApp.Extension; + PRODUCT_NAME = "CMUX ExtKit Sample Sidebar Extension"; SDKROOT = macosx; SKIP_INSTALL = YES; STRING_CATALOG_GENERATE_SYMBOLS = YES; @@ -686,7 +686,7 @@ DEVELOPMENT_TEAM = 7WLXT3NR37; GENERATE_INFOPLIST_FILE = YES; INFOPLIST_FILE = SampleSidebarExtension/Info.plist; - INFOPLIST_KEY_CFBundleDisplayName = SampleSidebarExtension; + INFOPLIST_KEY_CFBundleDisplayName = "CMUX ExtKit Sample Sidebar"; INFOPLIST_KEY_NSHumanReadableCopyright = ""; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", @@ -695,8 +695,8 @@ ); MACOSX_DEPLOYMENT_TARGET = 26.0; MARKETING_VERSION = 1.0; - PRODUCT_BUNDLE_IDENTIFIER = co.manaflow.SampleSidebarExtensionApp.SampleSidebarExtension; - PRODUCT_NAME = "$(TARGET_NAME)"; + PRODUCT_BUNDLE_IDENTIFIER = co.manaflow.CMUXExtKitSampleSidebarApp.Extension; + PRODUCT_NAME = "CMUX ExtKit Sample Sidebar Extension"; SDKROOT = macosx; SKIP_INSTALL = YES; STRING_CATALOG_GENERATE_SYMBOLS = YES; diff --git a/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionApp.xcodeproj/xcshareddata/xcschemes/CMUXExtKitSampleSidebarApp.xcscheme b/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionApp.xcodeproj/xcshareddata/xcschemes/CMUXExtKitSampleSidebarApp.xcscheme new file mode 100644 index 000000000000..e02f06e29804 --- /dev/null +++ b/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionApp.xcodeproj/xcshareddata/xcschemes/CMUXExtKitSampleSidebarApp.xcscheme @@ -0,0 +1,91 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + From 131df68de8f370d9414f3f664086cf86603775e5 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Fri, 29 May 2026 16:53:14 -0500 Subject: [PATCH 08/44] Fix sidebar extension titlebar placement --- .../Sidebar/CMUXSidebarXPC.swift | 4 +-- Sources/ContentView.swift | 5 +++- Sources/Update/UpdateTitlebarAccessory.swift | 25 +++++++++++++++++-- 3 files changed, 29 insertions(+), 5 deletions(-) diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarXPC.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarXPC.swift index cfd72831706e..a7bf059f5fb6 100644 --- a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarXPC.swift +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarXPC.swift @@ -1,11 +1,11 @@ import Foundation -@objc public protocol CMUXSidebarHostXPC { +@objc public protocol CMUXSidebarHostXPC: NSObjectProtocol { func requestSidebarSnapshot(reply: @escaping (NSData?, NSString?) -> Void) func performSidebarAction(_ payload: NSData, reply: @escaping (NSData?, NSString?) -> Void) } -@objc public protocol CMUXSidebarExtensionXPC { +@objc public protocol CMUXSidebarExtensionXPC: NSObjectProtocol { func sidebarSnapshotDidChange(_ payload: NSData) } diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index 06c826c3b8fc..7ab4f38db947 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -1579,7 +1579,10 @@ struct ContentView: View { private static let minimumTerminalWidthWithRightSidebar: CGFloat = 360 private var minimumSidebarWidth: CGFloat { - CGFloat(SessionPersistencePolicy.sanitizedMinimumSidebarWidth(sidebarMinimumWidthSetting)) + max( + CGFloat(SessionPersistencePolicy.sanitizedMinimumSidebarWidth(sidebarMinimumWidthSetting)), + TitlebarControlsLayoutMetrics.minimumSidebarWidth(config: titlebarControlsConfig) + ) } private enum SidebarResizerHandle: Hashable { diff --git a/Sources/Update/UpdateTitlebarAccessory.swift b/Sources/Update/UpdateTitlebarAccessory.swift index a1513f94571e..bab3549ea7df 100644 --- a/Sources/Update/UpdateTitlebarAccessory.swift +++ b/Sources/Update/UpdateTitlebarAccessory.swift @@ -453,6 +453,7 @@ enum TitlebarControlsLayoutMetrics { static let hintRightSafetyShift: CGFloat = 10 static let hintTrailingBaseInset: CGFloat = 8 static let extraButtonCount = 1 + static let trafficLightGap: CGFloat = 8 static func hintTrailingInset(titlebarShortcutHintXOffset: Double = ShortcutHintDebugSettings.defaultTitlebarHintX) -> CGFloat { max(0, ShortcutHintDebugSettings.clamped(titlebarShortcutHintXOffset)) @@ -487,6 +488,25 @@ enum TitlebarControlsLayoutMetrics { max(contentHeight, titlebarHeight) } + static func leadingOffset( + trafficLightFrame: NSRect?, + debugSnapshot: MinimalModeTitlebarDebugSnapshot + ) -> CGFloat { + let debugOffset = MinimalModeTitlebarDebugSettings.leftControlsXOffset( + leadingInset: debugSnapshot.leftControlsLeadingInset + ) + guard let trafficLightFrame, !trafficLightFrame.isEmpty else { + return debugOffset + } + return max(debugOffset, trafficLightFrame.maxX + trafficLightGap) + } + + static func minimumSidebarWidth(config: TitlebarControlsStyleConfig) -> CGFloat { + MinimalModeTitlebarDebugSettings.defaultTrafficLightTitlebarLeadingInset + + contentSize(config: config).width + + trafficLightGap + } + static func yOffset( contentHeight: CGFloat, containerHeight: CGFloat, @@ -2034,8 +2054,9 @@ final class TitlebarControlsAccessoryViewController: NSTitlebarAccessoryViewCont titlebarHeight: titlebarHeight ) let debugSnapshot = MinimalModeTitlebarDebugSettings.snapshot() - let xOffset = MinimalModeTitlebarDebugSettings.leftControlsXOffset( - leadingInset: debugSnapshot.leftControlsLeadingInset + let xOffset = TitlebarControlsLayoutMetrics.leadingOffset( + trafficLightFrame: trafficLightFrame, + debugSnapshot: debugSnapshot ) let yOffset = TitlebarControlsLayoutMetrics.yOffset( contentHeight: contentSize.height, From 1ee1091c385332918fe7548f48ca589b7a537e0f Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Fri, 29 May 2026 17:08:49 -0500 Subject: [PATCH 09/44] Use ExtensionKit browser for sidebar extensions --- ...CMUXSidebarExtensionBrowserPresenter.swift | 26 +++++++ .../CMUXSidebarExtensionDiscovery.swift | 18 +++++ ...om.manaflow.cmux.sidebar.appextensionpoint | 11 +++ ...MUXInstalledExtensionSidebarHostView.swift | 76 +++++++++++++++++-- Sources/ContentView.swift | 18 +++++ cmux.xcodeproj/project.pbxproj | 15 ++++ 6 files changed, 157 insertions(+), 7 deletions(-) create mode 100644 Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Browser/CMUXSidebarExtensionBrowserPresenter.swift create mode 100644 Resources/com.manaflow.cmux.sidebar.appextensionpoint diff --git a/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Browser/CMUXSidebarExtensionBrowserPresenter.swift b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Browser/CMUXSidebarExtensionBrowserPresenter.swift new file mode 100644 index 000000000000..79de4a8954e9 --- /dev/null +++ b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Browser/CMUXSidebarExtensionBrowserPresenter.swift @@ -0,0 +1,26 @@ +import AppKit +import ExtensionKit +import Foundation + +@available(macOS 13.0, *) +@MainActor +public enum CMUXSidebarExtensionBrowserPresenter { + public static func present(from anchorView: NSView, title: String) { + let browserViewController = EXAppExtensionBrowserViewController() + browserViewController.title = title + + let browserWindow = NSWindow(contentViewController: browserViewController) + browserWindow.title = title + browserWindow.styleMask = [.titled, .closable, .resizable] + browserWindow.contentMinSize = NSSize(width: 520, height: 420) + browserWindow.setContentSize(NSSize(width: 680, height: 560)) + browserWindow.isReleasedWhenClosed = true + + if let parentWindow = anchorView.window { + parentWindow.beginSheet(browserWindow) + } else { + browserWindow.center() + browserWindow.makeKeyAndOrderFront(nil) + } + } +} diff --git a/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Discovery/CMUXSidebarExtensionDiscovery.swift b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Discovery/CMUXSidebarExtensionDiscovery.swift index 6b3b651e5f55..1e37f341e684 100644 --- a/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Discovery/CMUXSidebarExtensionDiscovery.swift +++ b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Discovery/CMUXSidebarExtensionDiscovery.swift @@ -26,4 +26,22 @@ public struct CMUXSidebarExtensionDiscovery { } .sorted { $0.localizedName < $1.localizedName } } + + /// Lists enabled sidebar extensions using the modern ExtensionFoundation monitor. + /// - Parameter appExtensionPoint: Extension point declared by the host app. + /// - Returns: Enabled extensions sorted by localized name. + @available(macOS 26.0, *) + public func enabledExtensions( + appExtensionPoint: AppExtensionPoint + ) async throws -> [CMUXInstalledSidebarExtension] { + let monitor = try await AppExtensionPoint.Monitor(appExtensionPoint: appExtensionPoint) + return monitor.state.identities.map { + CMUXInstalledSidebarExtension( + bundleIdentifier: $0.bundleIdentifier, + localizedName: $0.localizedName, + extensionPointIdentifier: $0.extensionPointIdentifier + ) + } + .sorted { $0.localizedName < $1.localizedName } + } } diff --git a/Resources/com.manaflow.cmux.sidebar.appextensionpoint b/Resources/com.manaflow.cmux.sidebar.appextensionpoint new file mode 100644 index 000000000000..d5714dbd157a --- /dev/null +++ b/Resources/com.manaflow.cmux.sidebar.appextensionpoint @@ -0,0 +1,11 @@ + + + + + com.manaflow.cmux.sidebar + + EXPresentsUserInterface + + + + diff --git a/Sources/CMUXInstalledExtensionSidebarHostView.swift b/Sources/CMUXInstalledExtensionSidebarHostView.swift index 60282a238ba1..a1076f778377 100644 --- a/Sources/CMUXInstalledExtensionSidebarHostView.swift +++ b/Sources/CMUXInstalledExtensionSidebarHostView.swift @@ -10,6 +10,9 @@ struct CMUXInstalledExtensionSidebarHostView: View { @State private var identity: AppExtensionIdentity? @State private var isLoading = true @State private var errorText: String? + @State private var disabledExtensionCount = 0 + @State private var unapprovedExtensionCount = 0 + @State private var browserAnchorView: NSView? @State private var xpcHost = CMUXSidebarExtensionHostXPC() var body: some View { @@ -52,11 +55,35 @@ struct CMUXInstalledExtensionSidebarHostView: View { .font(.system(size: 12)) .foregroundStyle(.secondary) .fixedSize(horizontal: false, vertical: true) + if disabledExtensionCount > 0 || unapprovedExtensionCount > 0 { + Text(extensionAvailabilityDetail) + .font(.system(size: 12)) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + Button { + if let browserAnchorView { + CMUXSidebarExtensionBrowserPresenter.present( + from: browserAnchorView, + title: String( + localized: "sidebar.extensions.browser.title", + defaultValue: "Sidebar Extensions" + ) + ) + } + } label: { + Label( + String(localized: "sidebar.extensions.manage", defaultValue: "Manage Extensions"), + systemImage: "puzzlepiece.extension" + ) + } + .controlSize(.small) } } .padding(.horizontal, 14) .padding(.top, SidebarWorkspaceScrollInsets.workspaceList.top + 12) .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) + .background(TitlebarControlAnchorView { browserAnchorView = $0 }) .accessibilityIdentifier("CMUXExtensionSidebarEmptyState") } } @@ -73,13 +100,7 @@ struct CMUXInstalledExtensionSidebarHostView: View { isLoading = true errorText = nil do { - let update = try await Task.detached(priority: .userInitiated) { - var identities = try AppExtensionIdentity.matching( - appExtensionPointIDs: CMUXSidebarExtensionPoint.identifier - ) - .makeAsyncIterator() - return await identities.next() ?? [] - }.value + let update = try await loadEnabledExtensionIdentities() identity = update.sorted { $0.localizedName < $1.localizedName }.first isLoading = false } catch { @@ -91,6 +112,47 @@ struct CMUXInstalledExtensionSidebarHostView: View { ) } } + + private var extensionAvailabilityDetail: String { + if unapprovedExtensionCount > 0 { + return String( + localized: "sidebar.extensions.unapproved.detail", + defaultValue: "An installed sidebar extension needs approval before CMUX can use it." + ) + } + return String( + localized: "sidebar.extensions.disabled.detail", + defaultValue: "A sidebar extension is installed but disabled." + ) + } + + private func loadEnabledExtensionIdentities() async throws -> [AppExtensionIdentity] { + if #available(macOS 26.0, *) { + let extensionPoint = try AppExtensionPoint(identifier: "com.manaflow.cmux.sidebar") + let monitor = try await AppExtensionPoint.Monitor(appExtensionPoint: extensionPoint) + let state = monitor.state + disabledExtensionCount = state.disabledCount + unapprovedExtensionCount = state.unapprovedCount + return state.identities + } + + let availabilityTask = Task.detached(priority: .utility) { + var updates = AppExtensionIdentity.availabilityUpdates.makeAsyncIterator() + return await updates.next() + } + let update = try await Task.detached(priority: .userInitiated) { + var identities = try AppExtensionIdentity.matching( + appExtensionPointIDs: CMUXSidebarExtensionPoint.identifier + ) + .makeAsyncIterator() + return await identities.next() ?? [] + }.value + if let availability = await availabilityTask.value { + disabledExtensionCount = availability.disabledCount + unapprovedExtensionCount = availability.unapprovedCount + } + return update + } } @MainActor diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index 7ab4f38db947..0b6e2a2416ee 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -1,6 +1,7 @@ import AppKit import Bonsplit import Combine +import CMUXExtensionClient import CmuxExtensionKit import ImageIO import Observation @@ -9919,6 +9920,15 @@ enum CmuxExtensionSidebarSelection { item.state = selectedProviderId == descriptor.id ? .on : .off menu.addItem(item) } + menu.addItem(.separator()) + let manageItem = NSMenuItem( + title: String(localized: "sidebar.extensions.manage", defaultValue: "Manage Extensions"), + action: #selector(CmuxExtensionSidebarMenuTarget.manageExtensions(_:)), + keyEquivalent: "" + ) + manageItem.representedObject = anchorView + manageItem.target = CmuxExtensionSidebarMenuTarget.shared + menu.addItem(manageItem) menu.popUp( positioning: nil, at: NSPoint(x: 0, y: anchorView.bounds.maxY + 2), @@ -9935,6 +9945,14 @@ private final class CmuxExtensionSidebarMenuTarget: NSObject { guard let providerId = sender.representedObject as? String else { return } CmuxExtensionSidebarSelection.setProviderId(providerId) } + + @objc func manageExtensions(_ sender: NSMenuItem) { + guard let anchorView = sender.representedObject as? NSView else { return } + CMUXSidebarExtensionBrowserPresenter.present( + from: anchorView, + title: String(localized: "sidebar.extensions.browser.title", defaultValue: "Sidebar Extensions") + ) + } } @MainActor diff --git a/cmux.xcodeproj/project.pbxproj b/cmux.xcodeproj/project.pbxproj index 2379a0b71ef6..cdf404b9ea5a 100644 --- a/cmux.xcodeproj/project.pbxproj +++ b/cmux.xcodeproj/project.pbxproj @@ -169,6 +169,7 @@ D0B1000CA1B2C3D4E5F60001 /* CmuxWebViewDragRoutingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = D0B1000DA1B2C3D4E5F60001 /* CmuxWebViewDragRoutingTests.swift */; }; E30750000000000000000004 /* CmuxWorkspaceDefinition.swift in Sources */ = {isa = PBXBuildFile; fileRef = E30750000000000000000003 /* CmuxWorkspaceDefinition.swift */; }; AA11BB22CC33DD44EE550001 /* CMUXWorkstream in Frameworks */ = {isa = PBXBuildFile; productRef = AA11BB22CC33DD44EE550002 /* CMUXWorkstream */; }; + C0DE47000000000000000001 /* com.manaflow.cmux.sidebar.appextensionpoint in Copy Extension Points */ = {isa = PBXBuildFile; fileRef = C0DE47000000000000000002 /* com.manaflow.cmux.sidebar.appextensionpoint */; }; C4041001000000000000001B /* CommandClickFileOpenRouter.swift in Sources */ = {isa = PBXBuildFile; fileRef = C4041001000000000000001A /* CommandClickFileOpenRouter.swift */; }; C0DE32470000000000000005 /* CommandPaletteIdentifierClipboardUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DE32470000000000000006 /* CommandPaletteIdentifierClipboardUITests.swift */; }; C0DEC0DE000000000000F202 /* CommandPaletteNucleoFFILibrarySupport.swift in Sources */ = {isa = PBXBuildFile; fileRef = C0DEC0DE000000000000F201 /* CommandPaletteNucleoFFILibrarySupport.swift */; }; @@ -613,6 +614,17 @@ name = "Copy Dock Tile Plugin"; runOnlyForDeploymentPostprocessing = 0; }; + C0DE47000000000000000003 /* Copy Extension Points */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = Contents/Extensions; + dstSubfolderSpec = 1; + files = ( + C0DE47000000000000000001 /* com.manaflow.cmux.sidebar.appextensionpoint in Copy Extension Points */, + ); + name = "Copy Extension Points"; + runOnlyForDeploymentPostprocessing = 0; + }; /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ @@ -769,6 +781,7 @@ A5001510 /* CmuxWebView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Panels/CmuxWebView.swift; sourceTree = ""; }; D0B1000DA1B2C3D4E5F60001 /* CmuxWebViewDragRoutingTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CmuxWebViewDragRoutingTests.swift; sourceTree = ""; }; E30750000000000000000003 /* CmuxWorkspaceDefinition.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CmuxWorkspaceDefinition.swift; sourceTree = ""; }; + C0DE47000000000000000002 /* com.manaflow.cmux.sidebar.appextensionpoint */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = com.manaflow.cmux.sidebar.appextensionpoint; sourceTree = ""; }; C4041001000000000000001A /* CommandClickFileOpenRouter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CommandClickFileOpenRouter.swift; sourceTree = ""; }; C0DE32470000000000000006 /* CommandPaletteIdentifierClipboardUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CommandPaletteIdentifierClipboardUITests.swift; sourceTree = ""; }; C0DEC0DE000000000000F201 /* CommandPaletteNucleoFFILibrarySupport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CommandPaletteNucleoFFILibrarySupport.swift; sourceTree = ""; }; @@ -1208,6 +1221,7 @@ FEED0A00000000000000F006 /* feed-tui */, A9D9000000000000000F0016 /* markdown-viewer */, A5001622 /* cmux.sdef */, + C0DE47000000000000000002 /* com.manaflow.cmux.sidebar.appextensionpoint */, ); path = Resources; sourceTree = ""; @@ -1806,6 +1820,7 @@ A5001030 /* Frameworks */, A5001102 /* Resources */, D3664003D3664003D3664003 /* Compress Markdown Viewer Assets */, + C0DE47000000000000000003 /* Copy Extension Points */, D1320AA0D1320AA0D1320AA6 /* Copy Dock Tile Plugin */, A5001020 /* Embed Frameworks */, B900000AA1B2C3D4E5F60719 /* Copy CLI */, From fca8e6d71cd9987d64de773a511e3b7cb0f518de Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Fri, 29 May 2026 17:21:14 -0500 Subject: [PATCH 10/44] Fix sidebar extension browser presentation --- ...CMUXSidebarExtensionBrowserPresenter.swift | 75 ++++++++++++++++--- 1 file changed, 66 insertions(+), 9 deletions(-) diff --git a/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Browser/CMUXSidebarExtensionBrowserPresenter.swift b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Browser/CMUXSidebarExtensionBrowserPresenter.swift index 79de4a8954e9..483bf111465e 100644 --- a/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Browser/CMUXSidebarExtensionBrowserPresenter.swift +++ b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Browser/CMUXSidebarExtensionBrowserPresenter.swift @@ -8,19 +8,76 @@ public enum CMUXSidebarExtensionBrowserPresenter { public static func present(from anchorView: NSView, title: String) { let browserViewController = EXAppExtensionBrowserViewController() browserViewController.title = title + browserViewController.loadSidebarExtensionsIfSupported() - let browserWindow = NSWindow(contentViewController: browserViewController) - browserWindow.title = title - browserWindow.styleMask = [.titled, .closable, .resizable] - browserWindow.contentMinSize = NSSize(width: 520, height: 420) - browserWindow.setContentSize(NSSize(width: 680, height: 560)) - browserWindow.isReleasedWhenClosed = true + let browserPanel = NSPanel(contentViewController: browserViewController) + browserPanel.title = title + browserPanel.styleMask = [.titled, .closable, .resizable, .utilityWindow] + browserPanel.contentMinSize = NSSize(width: 560, height: 460) + browserPanel.setContentSize(NSSize(width: 760, height: 600)) + browserPanel.isFloatingPanel = true + browserPanel.hidesOnDeactivate = false + browserPanel.isReleasedWhenClosed = false if let parentWindow = anchorView.window { - parentWindow.beginSheet(browserWindow) + browserPanel.setFrameOrigin(Self.panelOrigin(anchorView: anchorView, parentWindow: parentWindow, panel: browserPanel)) + parentWindow.addChildWindow(browserPanel, ordered: .above) } else { - browserWindow.center() - browserWindow.makeKeyAndOrderFront(nil) + browserPanel.center() + } + BrowserPanelController.shared.show(panel: browserPanel) + } + + private static func panelOrigin(anchorView: NSView, parentWindow: NSWindow, panel: NSPanel) -> NSPoint { + let anchorFrame = anchorView.convert(anchorView.bounds, to: nil) + let anchorFrameInScreen = parentWindow.convertToScreen(anchorFrame) + let visibleFrame = parentWindow.screen?.visibleFrame ?? NSScreen.main?.visibleFrame ?? .zero + let proposedX = anchorFrameInScreen.minX + let proposedY = anchorFrameInScreen.minY - panel.frame.height - 8 + let x = min(max(proposedX, visibleFrame.minX + 12), visibleFrame.maxX - panel.frame.width - 12) + let y = min(max(proposedY, visibleFrame.minY + 12), visibleFrame.maxY - panel.frame.height - 12) + return NSPoint(x: x, y: y) + } +} + +@available(macOS 13.0, *) +@MainActor +private final class BrowserPanelController: NSObject, NSWindowDelegate { + static let shared = BrowserPanelController() + + private weak var parentWindow: NSWindow? + private var panel: NSPanel? + + func show(panel: NSPanel) { + if let existingPanel = self.panel { + if let parentWindow { + parentWindow.removeChildWindow(existingPanel) + } + existingPanel.close() + } + self.panel = panel + self.parentWindow = panel.parent + panel.delegate = self + panel.makeKeyAndOrderFront(nil) + NSApp.activate(ignoringOtherApps: true) + } + + func windowWillClose(_ notification: Notification) { + guard let window = notification.object as? NSWindow, window === panel else { return } + if let parentWindow, let panel { + parentWindow.removeChildWindow(panel) + } + self.panel = nil + self.parentWindow = nil + } +} + +@available(macOS 13.0, *) +private extension EXAppExtensionBrowserViewController { + func loadSidebarExtensionsIfSupported() { + let selector = NSSelectorFromString("loadExtensions") + if responds(to: selector) { + perform(selector) } } } From cd7b11bd245e6a4a75637d97e8bcbb502e6dd344 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Fri, 29 May 2026 17:55:17 -0500 Subject: [PATCH 11/44] Fix sidebar ExtensionKit approval --- .../project.pbxproj | 2 ++ .../CMUXSidebarExtensionBrowserPresenter.swift | 11 ----------- .../ExtensionPoint/CMUXSidebarExtensionPoint.swift | 2 ++ .../com.manaflow.cmux.sidebar.appextensionpoint | 4 ++++ .../CMUXInstalledExtensionSidebarHostView.swift | 14 ++++++++++---- 5 files changed, 18 insertions(+), 15 deletions(-) diff --git a/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionApp.xcodeproj/project.pbxproj b/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionApp.xcodeproj/project.pbxproj index c0c00ba6d525..2badcf2c79ad 100644 --- a/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionApp.xcodeproj/project.pbxproj +++ b/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionApp.xcodeproj/project.pbxproj @@ -655,6 +655,7 @@ CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = 1; DEVELOPMENT_TEAM = 7WLXT3NR37; + ENABLE_APP_SANDBOX = YES; GENERATE_INFOPLIST_FILE = YES; INFOPLIST_FILE = SampleSidebarExtension/Info.plist; INFOPLIST_KEY_CFBundleDisplayName = "CMUX ExtKit Sample Sidebar"; @@ -684,6 +685,7 @@ CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = 1; DEVELOPMENT_TEAM = 7WLXT3NR37; + ENABLE_APP_SANDBOX = YES; GENERATE_INFOPLIST_FILE = YES; INFOPLIST_FILE = SampleSidebarExtension/Info.plist; INFOPLIST_KEY_CFBundleDisplayName = "CMUX ExtKit Sample Sidebar"; diff --git a/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Browser/CMUXSidebarExtensionBrowserPresenter.swift b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Browser/CMUXSidebarExtensionBrowserPresenter.swift index 483bf111465e..f3b1bad3805a 100644 --- a/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Browser/CMUXSidebarExtensionBrowserPresenter.swift +++ b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Browser/CMUXSidebarExtensionBrowserPresenter.swift @@ -8,7 +8,6 @@ public enum CMUXSidebarExtensionBrowserPresenter { public static func present(from anchorView: NSView, title: String) { let browserViewController = EXAppExtensionBrowserViewController() browserViewController.title = title - browserViewController.loadSidebarExtensionsIfSupported() let browserPanel = NSPanel(contentViewController: browserViewController) browserPanel.title = title @@ -71,13 +70,3 @@ private final class BrowserPanelController: NSObject, NSWindowDelegate { self.parentWindow = nil } } - -@available(macOS 13.0, *) -private extension EXAppExtensionBrowserViewController { - func loadSidebarExtensionsIfSupported() { - let selector = NSSelectorFromString("loadExtensions") - if responds(to: selector) { - perform(selector) - } - } -} diff --git a/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/ExtensionPoint/CMUXSidebarExtensionPoint.swift b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/ExtensionPoint/CMUXSidebarExtensionPoint.swift index dbb178ac46d6..a5eae1048ccd 100644 --- a/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/ExtensionPoint/CMUXSidebarExtensionPoint.swift +++ b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/ExtensionPoint/CMUXSidebarExtensionPoint.swift @@ -2,6 +2,8 @@ public enum CMUXSidebarExtensionPoint { /// Extension point identifier third-party sidebar extensions register against. public static let identifier = "com.manaflow.cmux.sidebar" + /// StaticString form required by the modern ExtensionFoundation monitor API. + public static let staticIdentifier: StaticString = "com.manaflow.cmux.sidebar" /// Default ExtensionKit scene identifier hosted inside the cmux sidebar. public static let defaultSceneID = "sidebar" } diff --git a/Resources/com.manaflow.cmux.sidebar.appextensionpoint b/Resources/com.manaflow.cmux.sidebar.appextensionpoint index d5714dbd157a..c8da75ceee81 100644 --- a/Resources/com.manaflow.cmux.sidebar.appextensionpoint +++ b/Resources/com.manaflow.cmux.sidebar.appextensionpoint @@ -4,8 +4,12 @@ com.manaflow.cmux.sidebar + EXExtensionPointIsPublic + EXPresentsUserInterface + _EXScopeRestriction + none diff --git a/Sources/CMUXInstalledExtensionSidebarHostView.swift b/Sources/CMUXInstalledExtensionSidebarHostView.swift index a1076f778377..20446c77193a 100644 --- a/Sources/CMUXInstalledExtensionSidebarHostView.swift +++ b/Sources/CMUXInstalledExtensionSidebarHostView.swift @@ -100,7 +100,10 @@ struct CMUXInstalledExtensionSidebarHostView: View { isLoading = true errorText = nil do { - let update = try await loadEnabledExtensionIdentities() + let update = try await loadEnabledExtensionIdentities( + extensionPointIdentifier: CMUXSidebarExtensionPoint.identifier, + staticExtensionPointIdentifier: CMUXSidebarExtensionPoint.staticIdentifier + ) identity = update.sorted { $0.localizedName < $1.localizedName }.first isLoading = false } catch { @@ -126,9 +129,12 @@ struct CMUXInstalledExtensionSidebarHostView: View { ) } - private func loadEnabledExtensionIdentities() async throws -> [AppExtensionIdentity] { + private func loadEnabledExtensionIdentities( + extensionPointIdentifier: String, + staticExtensionPointIdentifier: StaticString + ) async throws -> [AppExtensionIdentity] { if #available(macOS 26.0, *) { - let extensionPoint = try AppExtensionPoint(identifier: "com.manaflow.cmux.sidebar") + let extensionPoint = try AppExtensionPoint(identifier: staticExtensionPointIdentifier) let monitor = try await AppExtensionPoint.Monitor(appExtensionPoint: extensionPoint) let state = monitor.state disabledExtensionCount = state.disabledCount @@ -142,7 +148,7 @@ struct CMUXInstalledExtensionSidebarHostView: View { } let update = try await Task.detached(priority: .userInitiated) { var identities = try AppExtensionIdentity.matching( - appExtensionPointIDs: CMUXSidebarExtensionPoint.identifier + appExtensionPointIDs: extensionPointIdentifier ) .makeAsyncIterator() return await identities.next() ?? [] From ee2d90d8fcc5d7eb5ce87e6f4b123d8d1e66a8e6 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Fri, 29 May 2026 18:10:52 -0500 Subject: [PATCH 12/44] Observe sidebar ExtensionKit enablement --- ...MUXInstalledExtensionSidebarHostView.swift | 82 +++++++++++++------ 1 file changed, 57 insertions(+), 25 deletions(-) diff --git a/Sources/CMUXInstalledExtensionSidebarHostView.swift b/Sources/CMUXInstalledExtensionSidebarHostView.swift index 20446c77193a..be12d38112cf 100644 --- a/Sources/CMUXInstalledExtensionSidebarHostView.swift +++ b/Sources/CMUXInstalledExtensionSidebarHostView.swift @@ -1,6 +1,7 @@ import CMUXExtensionClient import CmuxExtensionKit import ExtensionFoundation +import Observation import SwiftUI struct CMUXInstalledExtensionSidebarHostView: View { @@ -89,25 +90,24 @@ struct CMUXInstalledExtensionSidebarHostView: View { } .task { xpcHost.update(snapshotProvider: snapshotProvider, actionHandler: actionHandler) - await loadExtension() + await observeExtensionAvailability() } .onChange(of: snapshotProvider().sequence) { _, _ in xpcHost.sendSnapshotDidChange() } } - private func loadExtension() async { + private func observeExtensionAvailability() async { isLoading = true errorText = nil do { - let update = try await loadEnabledExtensionIdentities( + try await observeEnabledExtensionIdentities( extensionPointIdentifier: CMUXSidebarExtensionPoint.identifier, staticExtensionPointIdentifier: CMUXSidebarExtensionPoint.staticIdentifier ) - identity = update.sorted { $0.localizedName < $1.localizedName }.first - isLoading = false } catch { identity = nil + xpcHost.invalidate() isLoading = false errorText = String( localized: "sidebar.extensions.error", @@ -129,35 +129,67 @@ struct CMUXInstalledExtensionSidebarHostView: View { ) } - private func loadEnabledExtensionIdentities( + private func observeEnabledExtensionIdentities( extensionPointIdentifier: String, staticExtensionPointIdentifier: StaticString - ) async throws -> [AppExtensionIdentity] { + ) async throws { if #available(macOS 26.0, *) { let extensionPoint = try AppExtensionPoint(identifier: staticExtensionPointIdentifier) let monitor = try await AppExtensionPoint.Monitor(appExtensionPoint: extensionPoint) - let state = monitor.state - disabledExtensionCount = state.disabledCount - unapprovedExtensionCount = state.unapprovedCount - return state.identities + observeModernExtensionMonitor(monitor) + while !Task.isCancelled { + await waitForModernExtensionMonitorChange(monitor) + observeModernExtensionMonitor(monitor) + } + return } - let availabilityTask = Task.detached(priority: .utility) { - var updates = AppExtensionIdentity.availabilityUpdates.makeAsyncIterator() - return await updates.next() - } - let update = try await Task.detached(priority: .userInitiated) { - var identities = try AppExtensionIdentity.matching( - appExtensionPointIDs: extensionPointIdentifier - ) + var identities = try AppExtensionIdentity.matching(appExtensionPointIDs: extensionPointIdentifier) .makeAsyncIterator() - return await identities.next() ?? [] - }.value - if let availability = await availabilityTask.value { - disabledExtensionCount = availability.disabledCount - unapprovedExtensionCount = availability.unapprovedCount + let availabilityTask = Task { + var availabilityUpdates = AppExtensionIdentity.availabilityUpdates.makeAsyncIterator() + while !Task.isCancelled { + guard let availability = await availabilityUpdates.next() else { break } + disabledExtensionCount = availability.disabledCount + unapprovedExtensionCount = availability.unapprovedCount + } + } + defer { + availabilityTask.cancel() + } + while !Task.isCancelled { + guard let update = await identities.next() else { break } + applyEnabledExtensionIdentities(update) + } + } + + private func applyEnabledExtensionIdentities(_ identities: [AppExtensionIdentity]) { + let nextIdentity = identities.sorted { $0.localizedName < $1.localizedName }.first + if nextIdentity?.bundleIdentifier != identity?.bundleIdentifier { + xpcHost.invalidate() + identity = nextIdentity + } + isLoading = false + errorText = nil + } + + @available(macOS 26.0, *) + private func observeModernExtensionMonitor(_ monitor: AppExtensionPoint.Monitor) { + let state = monitor.state + disabledExtensionCount = state.disabledCount + unapprovedExtensionCount = state.unapprovedCount + applyEnabledExtensionIdentities(state.identities) + } + + @available(macOS 26.0, *) + private func waitForModernExtensionMonitorChange(_ monitor: AppExtensionPoint.Monitor) async { + await withCheckedContinuation { continuation in + withObservationTracking { + _ = monitor.state + } onChange: { + continuation.resume() + } } - return update } } From fb49cbafe97dda0934b63946951366389c38c310 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Fri, 29 May 2026 18:29:57 -0500 Subject: [PATCH 13/44] Harden sidebar extension dogfood flow --- .../Connection/SidebarConnectionModel.swift | 24 ++++ .../Model/SidebarInsightModel.swift | 2 +- .../UI/SampleSidebarView.swift | 35 ++--- .../ContentView.swift | 2 +- ...CMUXSidebarExtensionBrowserPresenter.swift | 29 ++-- ...MUXInstalledExtensionSidebarHostView.swift | 129 +++++++++++++++++- Sources/ContentView.swift | 5 +- 7 files changed, 190 insertions(+), 36 deletions(-) diff --git a/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/Connection/SidebarConnectionModel.swift b/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/Connection/SidebarConnectionModel.swift index 36a54a61e9d8..be8cdab74e3c 100644 --- a/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/Connection/SidebarConnectionModel.swift +++ b/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/Connection/SidebarConnectionModel.swift @@ -10,15 +10,33 @@ final class SidebarConnectionModel: @unchecked Sendable { private(set) var snapshot: CMUXSidebarSnapshot? private(set) var errorText: String? + @ObservationIgnored + private var connection: NSXPCConnection? + @ObservationIgnored private var host: CMUXSidebarHostXPC? private init() {} func accept(connection: NSXPCConnection) -> Bool { + self.connection?.invalidate() connection.exportedInterface = NSXPCInterface(with: CMUXSidebarExtensionXPC.self) connection.exportedObject = SidebarExtensionXPCReceiver(model: self) connection.remoteObjectInterface = NSXPCInterface(with: CMUXSidebarHostXPC.self) + connection.invalidationHandler = { [weak self] in + guard let model = self else { return } + Task { @MainActor [model] in + model.clearConnection() + } + } + connection.interruptionHandler = { [weak self] in + guard let model = self else { return } + Task { @MainActor [model] in + model.host = nil + model.errorText = String(localized: "sampleSidebar.waitingForHost", defaultValue: "Waiting for cmux") + } + } + self.connection = connection host = connection.remoteObjectProxyWithErrorHandler { [weak self] error in guard let model = self else { return } let message = error.localizedDescription @@ -101,6 +119,12 @@ final class SidebarConnectionModel: @unchecked Sendable { errorText = error.localizedDescription } } + + private func clearConnection() { + connection = nil + host = nil + errorText = String(localized: "sampleSidebar.waitingForHost", defaultValue: "Waiting for cmux") + } } private final class SidebarExtensionXPCReceiver: NSObject, CMUXSidebarExtensionXPC { diff --git a/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/Model/SidebarInsightModel.swift b/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/Model/SidebarInsightModel.swift index 81c6be675cea..dcc711ded774 100644 --- a/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/Model/SidebarInsightModel.swift +++ b/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/Model/SidebarInsightModel.swift @@ -23,7 +23,7 @@ struct SidebarInsightModel { pullRequestCount = insights.reduce(0) { $0 + $1.pullRequestCount } selectedWorkspace = insights.first(where: \.isSelected) focusQueue = insights - .filter(\.hasSignal) + .filter { $0.hasSignal && !$0.isSelected } .sorted { lhs, rhs in if lhs.score != rhs.score { return lhs.score > rhs.score } return lhs.title.localizedCaseInsensitiveCompare(rhs.title) == .orderedAscending diff --git a/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/UI/SampleSidebarView.swift b/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/UI/SampleSidebarView.swift index 9a04bc7e2de2..56d6384bdc23 100644 --- a/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/UI/SampleSidebarView.swift +++ b/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/UI/SampleSidebarView.swift @@ -4,24 +4,27 @@ struct SampleSidebarView: View { var model: SidebarConnectionModel var body: some View { - VStack(alignment: .leading, spacing: 12) { - if let insights = model.insights { - header(insights) - if let selected = insights.selectedWorkspace { - WorkspaceInsightRow( - insight: selected, - action: { model.selectWorkspace(selected.id) } - ) + ScrollView { + VStack(alignment: .leading, spacing: 12) { + if let insights = model.insights { + header(insights) + if let selected = insights.selectedWorkspace { + WorkspaceInsightRow( + insight: selected, + action: { model.selectWorkspace(selected.id) } + ) + } + Divider() + focusQueue(insights) + } else { + waitingState } - Divider() - focusQueue(insights) - } else { - waitingState + Spacer(minLength: 0) } - Spacer(minLength: 0) + .padding(.horizontal, 12) + .padding(.vertical, 14) + .frame(maxWidth: .infinity, alignment: .topLeading) } - .padding(.horizontal, 12) - .padding(.vertical, 14) .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) } @@ -47,7 +50,7 @@ struct SampleSidebarView: View { .font(.system(size: 12)) .foregroundStyle(.secondary) } else { - ForEach(insights.focusQueue.prefix(8)) { insight in + ForEach(insights.focusQueue) { insight in WorkspaceInsightRow( insight: insight, action: { model.selectWorkspace(insight.id) } diff --git a/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionApp/ContentView.swift b/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionApp/ContentView.swift index 02c73ec19d15..775bee71d843 100644 --- a/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionApp/ContentView.swift +++ b/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionApp/ContentView.swift @@ -17,7 +17,7 @@ struct ContentView: View { .font(.title2.weight(.semibold)) Text(String( localized: "sampleSidebarApp.detail", - defaultValue: "Install this app, then choose CMUX Extensions from the cmux sidebar selector to host the extension." + defaultValue: "Keep this app installed, then open cmux, use the sidebar puzzle button, choose Manage Extensions, enable this extension, and choose the extension sidebar." )) .foregroundStyle(.secondary) } diff --git a/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Browser/CMUXSidebarExtensionBrowserPresenter.swift b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Browser/CMUXSidebarExtensionBrowserPresenter.swift index f3b1bad3805a..692eb05a36be 100644 --- a/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Browser/CMUXSidebarExtensionBrowserPresenter.swift +++ b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Browser/CMUXSidebarExtensionBrowserPresenter.swift @@ -9,7 +9,7 @@ public enum CMUXSidebarExtensionBrowserPresenter { let browserViewController = EXAppExtensionBrowserViewController() browserViewController.title = title - let browserPanel = NSPanel(contentViewController: browserViewController) + let browserPanel = SidebarExtensionBrowserPanel(contentViewController: browserViewController) browserPanel.title = title browserPanel.styleMask = [.titled, .closable, .resizable, .utilityWindow] browserPanel.contentMinSize = NSSize(width: 560, height: 460) @@ -20,7 +20,6 @@ public enum CMUXSidebarExtensionBrowserPresenter { if let parentWindow = anchorView.window { browserPanel.setFrameOrigin(Self.panelOrigin(anchorView: anchorView, parentWindow: parentWindow, panel: browserPanel)) - parentWindow.addChildWindow(browserPanel, ordered: .above) } else { browserPanel.center() } @@ -39,23 +38,35 @@ public enum CMUXSidebarExtensionBrowserPresenter { } } +@available(macOS 13.0, *) +@MainActor +private final class SidebarExtensionBrowserPanel: NSPanel { + override func cancelOperation(_ sender: Any?) { + close() + } + + override func performKeyEquivalent(with event: NSEvent) -> Bool { + if event.modifierFlags.intersection(.deviceIndependentFlagsMask) == .command, + event.charactersIgnoringModifiers == "w" { + close() + return true + } + return super.performKeyEquivalent(with: event) + } +} + @available(macOS 13.0, *) @MainActor private final class BrowserPanelController: NSObject, NSWindowDelegate { static let shared = BrowserPanelController() - private weak var parentWindow: NSWindow? private var panel: NSPanel? func show(panel: NSPanel) { if let existingPanel = self.panel { - if let parentWindow { - parentWindow.removeChildWindow(existingPanel) - } existingPanel.close() } self.panel = panel - self.parentWindow = panel.parent panel.delegate = self panel.makeKeyAndOrderFront(nil) NSApp.activate(ignoringOtherApps: true) @@ -63,10 +74,6 @@ private final class BrowserPanelController: NSObject, NSWindowDelegate { func windowWillClose(_ notification: Notification) { guard let window = notification.object as? NSWindow, window === panel else { return } - if let parentWindow, let panel { - parentWindow.removeChildWindow(panel) - } self.panel = nil - self.parentWindow = nil } } diff --git a/Sources/CMUXInstalledExtensionSidebarHostView.swift b/Sources/CMUXInstalledExtensionSidebarHostView.swift index be12d38112cf..b902a3a0ec8d 100644 --- a/Sources/CMUXInstalledExtensionSidebarHostView.swift +++ b/Sources/CMUXInstalledExtensionSidebarHostView.swift @@ -5,10 +5,16 @@ import Observation import SwiftUI struct CMUXInstalledExtensionSidebarHostView: View { + private static let selectedExtensionBundleIDDefaultsKey = "cmuxExtensionSidebar.selectedExtensionBundleId" + var snapshotProvider: @MainActor () -> CMUXSidebarSnapshot var actionHandler: @MainActor (CMUXSidebarAction) -> CMUXExtensionActionResult @State private var identity: AppExtensionIdentity? + @State private var enabledIdentities: [AppExtensionIdentity] = [] + @State private var selectedExtensionBundleID = UserDefaults.standard.string( + forKey: Self.selectedExtensionBundleIDDefaultsKey + ) @State private var isLoading = true @State private var errorText: String? @State private var disabledExtensionCount = 0 @@ -30,10 +36,12 @@ struct CMUXInstalledExtensionSidebarHostView: View { }, onDeactivation: { error in xpcHost.invalidate() + self.identity = nil errorText = error?.localizedDescription } ) .accessibilityIdentifier("CMUXExtensionSidebarHostView") + .padding(.top, SidebarWorkspaceScrollInsets.workspaceList.top) } else { VStack(alignment: .leading, spacing: 10) { if isLoading { @@ -62,6 +70,9 @@ struct CMUXInstalledExtensionSidebarHostView: View { .foregroundStyle(.secondary) .fixedSize(horizontal: false, vertical: true) } + if enabledIdentities.count > 1 { + enabledExtensionPicker + } Button { if let browserAnchorView { CMUXSidebarExtensionBrowserPresenter.present( @@ -129,6 +140,33 @@ struct CMUXInstalledExtensionSidebarHostView: View { ) } + private var enabledExtensionPicker: some View { + VStack(alignment: .leading, spacing: 6) { + Text(String( + localized: "sidebar.extensions.choose.detail", + defaultValue: "Choose which enabled extension should replace the sidebar." + )) + .font(.system(size: 12)) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + ForEach(enabledIdentities, id: \.bundleIdentifier) { enabledIdentity in + Button { + selectExtension(enabledIdentity) + } label: { + HStack(spacing: 6) { + Image(systemName: enabledIdentity.bundleIdentifier == selectedExtensionBundleID ? "checkmark.circle.fill" : "circle") + .font(.system(size: 11, weight: .medium)) + Text(enabledIdentity.localizedName) + .font(.system(size: 12, weight: .medium)) + .lineLimit(1) + } + .frame(maxWidth: .infinity, alignment: .leading) + } + .buttonStyle(.plain) + } + } + } + private func observeEnabledExtensionIdentities( extensionPointIdentifier: String, staticExtensionPointIdentifier: StaticString @@ -137,6 +175,12 @@ struct CMUXInstalledExtensionSidebarHostView: View { let extensionPoint = try AppExtensionPoint(identifier: staticExtensionPointIdentifier) let monitor = try await AppExtensionPoint.Monitor(appExtensionPoint: extensionPoint) observeModernExtensionMonitor(monitor) + let identityTask = Task { @MainActor in + try? await observeIdentitySequence(extensionPointIdentifier: extensionPointIdentifier) + } + defer { + identityTask.cancel() + } while !Task.isCancelled { await waitForModernExtensionMonitorChange(monitor) observeModernExtensionMonitor(monitor) @@ -144,6 +188,10 @@ struct CMUXInstalledExtensionSidebarHostView: View { return } + try await observeIdentitySequence(extensionPointIdentifier: extensionPointIdentifier) + } + + private func observeIdentitySequence(extensionPointIdentifier: String) async throws { var identities = try AppExtensionIdentity.matching(appExtensionPointIDs: extensionPointIdentifier) .makeAsyncIterator() let availabilityTask = Task { @@ -152,6 +200,11 @@ struct CMUXInstalledExtensionSidebarHostView: View { guard let availability = await availabilityUpdates.next() else { break } disabledExtensionCount = availability.disabledCount unapprovedExtensionCount = availability.unapprovedCount + if let currentIdentities = try? await loadCurrentExtensionIdentities( + extensionPointIdentifier: extensionPointIdentifier + ) { + applyEnabledExtensionIdentities(currentIdentities) + } } } defer { @@ -163,8 +216,26 @@ struct CMUXInstalledExtensionSidebarHostView: View { } } + private func loadCurrentExtensionIdentities(extensionPointIdentifier: String) async throws -> [AppExtensionIdentity] { + var identities = try AppExtensionIdentity.matching(appExtensionPointIDs: extensionPointIdentifier) + .makeAsyncIterator() + return await identities.next() ?? [] + } + private func applyEnabledExtensionIdentities(_ identities: [AppExtensionIdentity]) { - let nextIdentity = identities.sorted { $0.localizedName < $1.localizedName }.first + let sortedIdentities = identities.sorted { $0.localizedName < $1.localizedName } + enabledIdentities = sortedIdentities + let nextIdentity: AppExtensionIdentity? + if let selectedExtensionBundleID, + let selectedIdentity = sortedIdentities.first(where: { $0.bundleIdentifier == selectedExtensionBundleID }) { + nextIdentity = selectedIdentity + } else if sortedIdentities.count == 1 { + nextIdentity = sortedIdentities[0] + selectedExtensionBundleID = nextIdentity?.bundleIdentifier + UserDefaults.standard.set(nextIdentity?.bundleIdentifier, forKey: Self.selectedExtensionBundleIDDefaultsKey) + } else { + nextIdentity = nil + } if nextIdentity?.bundleIdentifier != identity?.bundleIdentifier { xpcHost.invalidate() identity = nextIdentity @@ -173,6 +244,12 @@ struct CMUXInstalledExtensionSidebarHostView: View { errorText = nil } + private func selectExtension(_ selectedIdentity: AppExtensionIdentity) { + selectedExtensionBundleID = selectedIdentity.bundleIdentifier + UserDefaults.standard.set(selectedIdentity.bundleIdentifier, forKey: Self.selectedExtensionBundleIDDefaultsKey) + applyEnabledExtensionIdentities(enabledIdentities) + } + @available(macOS 26.0, *) private func observeModernExtensionMonitor(_ monitor: AppExtensionPoint.Monitor) { let state = monitor.state @@ -183,16 +260,56 @@ struct CMUXInstalledExtensionSidebarHostView: View { @available(macOS 26.0, *) private func waitForModernExtensionMonitorChange(_ monitor: AppExtensionPoint.Monitor) async { - await withCheckedContinuation { continuation in - withObservationTracking { - _ = monitor.state - } onChange: { - continuation.resume() + let continuationBox = MonitorContinuationBox() + await withTaskCancellationHandler { + await withCheckedContinuation { continuation in + continuationBox.set(continuation) + withObservationTracking { + _ = monitor.state + } onChange: { + continuationBox.resume() + } } + } onCancel: { + continuationBox.cancel() } } } +private final class MonitorContinuationBox: @unchecked Sendable { + private let lock = NSLock() + private var continuation: CheckedContinuation? + private var isCancelled = false + + func set(_ continuation: CheckedContinuation) { + lock.lock() + if isCancelled { + lock.unlock() + continuation.resume() + return + } + self.continuation = continuation + lock.unlock() + } + + func resume() { + lock.lock() + let continuation = continuation + self.continuation = nil + lock.unlock() + continuation?.resume() + } + + func cancel() { + lock.lock() + isCancelled = true + let continuation = continuation + self.continuation = nil + lock.unlock() + continuation?.resume() + } +} + @MainActor private final class CMUXSidebarExtensionHostXPC { private var connection: NSXPCConnection? diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index 0b6e2a2416ee..f04be5921d99 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -10883,7 +10883,10 @@ struct VerticalTabsSidebar: View { return .accepted case .openURL(let urlString): - guard let url = URL(string: urlString), NSWorkspace.shared.open(url) else { + guard let url = URL(string: urlString), + let scheme = url.scheme?.lowercased(), + ["https", "http"].contains(scheme), + NSWorkspace.shared.open(url) else { return CMUXExtensionActionResult( accepted: false, message: String(localized: "sidebar.extensions.action.urlRejected", defaultValue: "URL could not be opened") From 1d87f0a2c4b5d4d36d3fec87973d1135a013a93d Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Fri, 29 May 2026 19:05:01 -0500 Subject: [PATCH 14/44] Harden sidebar ExtensionKit host state --- .../Connection/SidebarConnectionModel.swift | 59 ++++-- .../ContentView.swift | 14 +- .../CMUXSidebarExtensionHostView.swift | 6 + .../Sidebar/CMUXSidebarSnapshot.swift | 11 ++ .../Sidebar/CMUXSidebarWorkspace.swift | 17 ++ .../Sidebar/CMUXSidebarXPC.swift | 9 + .../CmuxExtensionKitTests.swift | 48 +++++ Resources/Localizable.xcstrings | 148 ++++++++++++++- ...MUXInstalledExtensionSidebarHostView.swift | 170 ++++++++++++------ Sources/ContentView.swift | 13 +- Sources/Update/UpdateTitlebarAccessory.swift | 4 +- Sources/WindowDragHandleView.swift | 2 +- 12 files changed, 424 insertions(+), 77 deletions(-) diff --git a/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/Connection/SidebarConnectionModel.swift b/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/Connection/SidebarConnectionModel.swift index be8cdab74e3c..6e6ae5957022 100644 --- a/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/Connection/SidebarConnectionModel.swift +++ b/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/Connection/SidebarConnectionModel.swift @@ -6,6 +6,17 @@ import CmuxExtensionKit @Observable final class SidebarConnectionModel: @unchecked Sendable { static let shared = SidebarConnectionModel() + static let manifest = CMUXExtensionManifest( + id: "co.manaflow.CMUXExtKitSampleSidebarApp.Extension", + displayName: "CMUX Sample Sidebar Extension", + requestedScopes: [ + .workspaceMetadata, + .workspacePaths, + .notifications, + .networkPorts, + .pullRequests, + ] + ) private(set) var snapshot: CMUXSidebarSnapshot? private(set) var errorText: String? @@ -13,6 +24,9 @@ final class SidebarConnectionModel: @unchecked Sendable { @ObservationIgnored private var connection: NSXPCConnection? + @ObservationIgnored + private var connectionGeneration: UInt64 = 0 + @ObservationIgnored private var host: CMUXSidebarHostXPC? @@ -20,27 +34,31 @@ final class SidebarConnectionModel: @unchecked Sendable { func accept(connection: NSXPCConnection) -> Bool { self.connection?.invalidate() + connectionGeneration += 1 + let generation = connectionGeneration connection.exportedInterface = NSXPCInterface(with: CMUXSidebarExtensionXPC.self) - connection.exportedObject = SidebarExtensionXPCReceiver(model: self) + connection.exportedObject = SidebarExtensionXPCReceiver(model: self, generation: generation) connection.remoteObjectInterface = NSXPCInterface(with: CMUXSidebarHostXPC.self) connection.invalidationHandler = { [weak self] in guard let model = self else { return } - Task { @MainActor [model] in - model.clearConnection() + Task { @MainActor [model, generation] in + model.clearConnection(ifCurrentGeneration: generation) } } connection.interruptionHandler = { [weak self] in guard let model = self else { return } - Task { @MainActor [model] in + Task { @MainActor [model, generation] in + guard model.connectionGeneration == generation else { return } model.host = nil model.errorText = String(localized: "sampleSidebar.waitingForHost", defaultValue: "Waiting for cmux") } } self.connection = connection - host = connection.remoteObjectProxyWithErrorHandler { [weak self] error in + host = connection.remoteObjectProxyWithErrorHandler { [weak self, generation] error in guard let model = self else { return } let message = error.localizedDescription - Task { @MainActor in + Task { @MainActor [model, generation] in + guard model.connectionGeneration == generation else { return } model.errorText = message } } as? CMUXSidebarHostXPC @@ -58,11 +76,13 @@ final class SidebarConnectionModel: @unchecked Sendable { errorText = String(localized: "sampleSidebar.waitingForHost", defaultValue: "Waiting for cmux") return } + let generation = connectionGeneration host.requestSidebarSnapshot { [weak self] payload, error in guard let model = self else { return } let payload = payload.map { $0 as Data } let error = error.map { String($0) } - Task { @MainActor in + Task { @MainActor [model, generation] in + guard model.connectionGeneration == generation else { return } if let error { model.errorText = error return @@ -87,13 +107,15 @@ final class SidebarConnectionModel: @unchecked Sendable { private func send(_ action: CMUXSidebarAction) { guard let host else { return } + let generation = connectionGeneration do { let payload = try CMUXSidebarXPCCodec.encodeAction(action) host.performSidebarAction(payload) { [weak self] resultPayload, error in guard let model = self else { return } let resultPayload = resultPayload.map { $0 as Data } let error = error.map { String($0) } - Task { @MainActor in + Task { @MainActor [model, generation] in + guard model.connectionGeneration == generation else { return } if let error { model.errorText = error return @@ -111,7 +133,8 @@ final class SidebarConnectionModel: @unchecked Sendable { } } - fileprivate func receive(snapshot payload: Data) { + fileprivate func receive(snapshot payload: Data, ifCurrentGeneration generation: UInt64) { + guard connectionGeneration == generation else { return } do { snapshot = try CMUXSidebarXPCCodec.decodeSnapshot(payload as NSData) errorText = nil @@ -120,7 +143,8 @@ final class SidebarConnectionModel: @unchecked Sendable { } } - private func clearConnection() { + private func clearConnection(ifCurrentGeneration generation: UInt64) { + guard connectionGeneration == generation else { return } connection = nil host = nil errorText = String(localized: "sampleSidebar.waitingForHost", defaultValue: "Waiting for cmux") @@ -129,16 +153,27 @@ final class SidebarConnectionModel: @unchecked Sendable { private final class SidebarExtensionXPCReceiver: NSObject, CMUXSidebarExtensionXPC { weak var model: SidebarConnectionModel? + let generation: UInt64 - init(model: SidebarConnectionModel) { + init(model: SidebarConnectionModel, generation: UInt64) { self.model = model + self.generation = generation } func sidebarSnapshotDidChange(_ payload: NSData) { let payload = payload as Data let model = model + let generation = generation Task { @MainActor in - model?.receive(snapshot: payload) + model?.receive(snapshot: payload, ifCurrentGeneration: generation) + } + } + + func requestExtensionManifest(reply: @escaping (NSData?, NSString?) -> Void) { + do { + reply(try CMUXSidebarXPCCodec.encodeManifest(SidebarConnectionModel.manifest), nil) + } catch { + reply(nil, error.localizedDescription as NSString) } } } diff --git a/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionApp/ContentView.swift b/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionApp/ContentView.swift index 775bee71d843..ee52a42a503e 100644 --- a/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionApp/ContentView.swift +++ b/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionApp/ContentView.swift @@ -17,9 +17,21 @@ struct ContentView: View { .font(.title2.weight(.semibold)) Text(String( localized: "sampleSidebarApp.detail", - defaultValue: "Keep this app installed, then open cmux, use the sidebar puzzle button, choose Manage Extensions, enable this extension, and choose the extension sidebar." + defaultValue: "Keep this app installed. In cmux, click the puzzle button, choose Manage Sidebar Extensions..., enable CMUX Sample Sidebar Extension, choose Extension Sidebar, and confirm Workspace Signals appears." )) .foregroundStyle(.secondary) + Text(String( + localized: "sampleSidebarApp.identifier", + defaultValue: "Extension ID: co.manaflow.CMUXExtKitSampleSidebarApp.Extension" + )) + .font(.system(.caption, design: .monospaced)) + .foregroundStyle(.secondary) + Text(String( + localized: "sampleSidebarApp.scopes", + defaultValue: "Requests workspace metadata, paths, notifications, ports, and pull request links." + )) + .font(.caption) + .foregroundStyle(.secondary) } .padding(24) .frame(width: 420, alignment: .leading) diff --git a/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Hosting/CMUXSidebarExtensionHostView.swift b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Hosting/CMUXSidebarExtensionHostView.swift index c2f0503e6605..397993a730be 100644 --- a/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Hosting/CMUXSidebarExtensionHostView.swift +++ b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Hosting/CMUXSidebarExtensionHostView.swift @@ -95,6 +95,12 @@ public struct CMUXSidebarExtensionHostView: NSViewControllerRepresentable { ) } + public static func dismantleNSViewController(_ viewController: EXHostViewController, coordinator: Coordinator) { + coordinator.currentKey = nil + viewController.delegate = nil + viewController.configuration = nil + } + private var configurationKey: HostConfigurationKey { HostConfigurationKey(bundleIdentifier: identity.bundleIdentifier, sceneID: sceneID) } diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarSnapshot.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarSnapshot.swift index 8030f03fb506..710bf9ee5ece 100644 --- a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarSnapshot.swift +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarSnapshot.swift @@ -20,4 +20,15 @@ public struct CMUXSidebarSnapshot: Codable, Equatable, Sendable { self.selectedWorkspaceID = selectedWorkspaceID self.workspaces = workspaces } + + public func filtered(for scopes: some Sequence) -> CMUXSidebarSnapshot { + let scopeSet = Set(scopes) + return CMUXSidebarSnapshot( + apiVersion: apiVersion, + sequence: sequence, + windowID: windowID, + selectedWorkspaceID: selectedWorkspaceID, + workspaces: workspaces.map { $0.filtered(for: scopeSet) } + ) + } } diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarWorkspace.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarWorkspace.swift index ed42bd6a53e6..f45e3e2b9d55 100644 --- a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarWorkspace.swift +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarWorkspace.swift @@ -38,4 +38,21 @@ public struct CMUXSidebarWorkspace: Codable, Equatable, Identifiable, Sendable { self.listeningPorts = listeningPorts self.pullRequestURLs = pullRequestURLs } + + public func filtered(for scopes: some Sequence) -> CMUXSidebarWorkspace { + let scopeSet = Set(scopes) + return CMUXSidebarWorkspace( + id: id, + title: title, + detail: detail, + isPinned: isPinned, + rootPath: scopeSet.contains(.workspacePaths) ? rootPath : nil, + projectRootPath: scopeSet.contains(.workspacePaths) ? projectRootPath : nil, + gitBranch: gitBranch, + unreadCount: unreadCount, + latestNotification: scopeSet.contains(.notifications) ? latestNotification : nil, + listeningPorts: scopeSet.contains(.networkPorts) ? listeningPorts : [], + pullRequestURLs: scopeSet.contains(.pullRequests) ? pullRequestURLs : [] + ) + } } diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarXPC.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarXPC.swift index a7bf059f5fb6..bbf797cb50d5 100644 --- a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarXPC.swift +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarXPC.swift @@ -6,6 +6,7 @@ import Foundation } @objc public protocol CMUXSidebarExtensionXPC: NSObjectProtocol { + @objc optional func requestExtensionManifest(reply: @escaping (NSData?, NSString?) -> Void) func sidebarSnapshotDidChange(_ payload: NSData) } @@ -18,6 +19,14 @@ public enum CMUXSidebarXPCCodec { try JSONDecoder().decode(CMUXSidebarSnapshot.self, from: payload as Data) } + public static func encodeManifest(_ manifest: CMUXExtensionManifest) throws -> NSData { + try JSONEncoder().encode(manifest) as NSData + } + + public static func decodeManifest(_ payload: NSData) throws -> CMUXExtensionManifest { + try JSONDecoder().decode(CMUXExtensionManifest.self, from: payload as Data) + } + public static func encodeAction(_ action: CMUXSidebarAction) throws -> NSData { try JSONEncoder().encode(action) as NSData } diff --git a/Packages/CmuxExtensionKit/Tests/CmuxExtensionKitTests/CmuxExtensionKitTests.swift b/Packages/CmuxExtensionKit/Tests/CmuxExtensionKitTests/CmuxExtensionKitTests.swift index c3b7e2011b83..f608d4d2dfb9 100644 --- a/Packages/CmuxExtensionKit/Tests/CmuxExtensionKitTests/CmuxExtensionKitTests.swift +++ b/Packages/CmuxExtensionKit/Tests/CmuxExtensionKitTests/CmuxExtensionKitTests.swift @@ -46,6 +46,44 @@ struct CMUXExtensionKitTests { try CMUXExtensionValidator.validateSidebarManifest(manifest) } + @Test + func testSidebarSnapshotFilteringRemovesUngrantedScopeData() throws { + let workspaceID = UUID(uuidString: "44444444-4444-4444-4444-444444444444")! + let snapshot = CMUXSidebarSnapshot( + sequence: 44, + selectedWorkspaceID: workspaceID, + workspaces: [ + CMUXSidebarWorkspace( + id: workspaceID, + title: "Build", + detail: "Running tests", + isPinned: true, + rootPath: "/Users/example/secret", + projectRootPath: "/Users/example/secret", + gitBranch: "feature/sidebar", + unreadCount: 2, + latestNotification: "Private notification", + listeningPorts: [3000, 5173], + pullRequestURLs: ["https://github.com/manaflow-ai/cmux/pull/4994"] + ), + ] + ) + + let filtered = snapshot.filtered(for: [CMUXExtensionScope.workspaceMetadata]) + let workspace = try #require(filtered.workspaces.first) + + #expect(workspace.id == workspaceID) + #expect(workspace.title == "Build") + #expect(workspace.detail == "Running tests") + #expect(workspace.gitBranch == "feature/sidebar") + #expect(workspace.unreadCount == 2) + #expect(workspace.rootPath == nil) + #expect(workspace.projectRootPath == nil) + #expect(workspace.latestNotification == nil) + #expect(workspace.listeningPorts.isEmpty) + #expect(workspace.pullRequestURLs.isEmpty) + } + @Test func testSidebarXPCCodecRoundTripsSnapshotActionAndResult() throws { let workspaceID = UUID(uuidString: "33333333-3333-3333-3333-333333333333")! @@ -73,6 +111,16 @@ struct CMUXExtensionKitTests { ) #expect(decodedSnapshot == snapshot) + let manifest = CMUXExtensionManifest( + id: "dev.example.sidebar", + displayName: "Example Sidebar", + requestedScopes: [.workspaceMetadata, .networkPorts] + ) + let decodedManifest = try CMUXSidebarXPCCodec.decodeManifest( + try CMUXSidebarXPCCodec.encodeManifest(manifest) + ) + #expect(decodedManifest == manifest) + let action = CMUXSidebarAction.selectWorkspace(workspaceID) let decodedAction = try CMUXSidebarXPCCodec.decodeAction( try CMUXSidebarXPCCodec.encodeAction(action) diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index 66c98c7954ad..a20df82db197 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -42633,13 +42633,13 @@ "en": { "stringUnit": { "state": "translated", - "value": "Sidebar" + "value": "Choose Sidebar" } }, "ja": { "stringUnit": { "state": "translated", - "value": "サイドバー" + "value": "サイドバーを選択" } } } @@ -161776,7 +161776,7 @@ "en": { "stringUnit": { "state": "translated", - "value": "CMUX Extensions" + "value": "Extension Sidebar" } }, "es": { @@ -161800,7 +161800,7 @@ "ja": { "stringUnit": { "state": "translated", - "value": "CMUX拡張機能" + "value": "拡張サイドバー" } }, "km": { @@ -161901,7 +161901,7 @@ "en": { "stringUnit": { "state": "translated", - "value": "ExtensionKit" + "value": "Custom sidebar" } }, "es": { @@ -161925,7 +161925,7 @@ "ja": { "stringUnit": { "state": "translated", - "value": "ExtensionKit" + "value": "カスタムサイドバー" } }, "km": { @@ -162495,6 +162495,142 @@ } } } + }, + "sidebar.extensions.action.workspaceNotFound": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Workspace not found" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "ワークスペースが見つかりません" + } + } + } + }, + "sidebar.extensions.action.staleConnection": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Extension connection is no longer active" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "拡張機能の接続はもう有効ではありません" + } + } + } + }, + "sidebar.extensions.browser.title": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Sidebar Extensions" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "サイドバー拡張機能" + } + } + } + }, + "sidebar.extensions.choose.detail": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Choose which enabled extension should replace the sidebar." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "サイドバーを置き換える有効な拡張機能を選択してください。" + } + } + } + }, + "sidebar.extensions.disabled.detail": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "A sidebar extension is installed but disabled." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "サイドバー拡張機能がインストールされていますが、無効です。" + } + } + } + }, + "sidebar.extensions.manage": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Manage Sidebar Extensions..." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "サイドバー拡張機能を管理..." + } + } + } + }, + "sidebar.extensions.unapproved.detail": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "An installed sidebar extension needs approval before CMUX can use it." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "インストール済みのサイドバー拡張機能は、CMUXで使用する前に承認が必要です。" + } + } + } + }, + "sidebar.extensions.useDefault": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Use Workspace Sidebar" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "ワークスペースサイドバーを使う" + } + } + } } } } diff --git a/Sources/CMUXInstalledExtensionSidebarHostView.swift b/Sources/CMUXInstalledExtensionSidebarHostView.swift index b902a3a0ec8d..928c575d6c8a 100644 --- a/Sources/CMUXInstalledExtensionSidebarHostView.swift +++ b/Sources/CMUXInstalledExtensionSidebarHostView.swift @@ -9,6 +9,7 @@ struct CMUXInstalledExtensionSidebarHostView: View { var snapshotProvider: @MainActor () -> CMUXSidebarSnapshot var actionHandler: @MainActor (CMUXSidebarAction) -> CMUXExtensionActionResult + var onUseDefaultSidebar: @MainActor () -> Void = {} @State private var identity: AppExtensionIdentity? @State private var enabledIdentities: [AppExtensionIdentity] = [] @@ -36,7 +37,9 @@ struct CMUXInstalledExtensionSidebarHostView: View { }, onDeactivation: { error in xpcHost.invalidate() - self.identity = nil + if self.identity?.bundleIdentifier == identity.bundleIdentifier { + self.identity = nil + } errorText = error?.localizedDescription } ) @@ -85,11 +88,20 @@ struct CMUXInstalledExtensionSidebarHostView: View { } } label: { Label( - String(localized: "sidebar.extensions.manage", defaultValue: "Manage Extensions"), + String(localized: "sidebar.extensions.manage", defaultValue: "Manage Sidebar Extensions..."), systemImage: "puzzlepiece.extension" ) } .controlSize(.small) + Button { + onUseDefaultSidebar() + } label: { + Label( + String(localized: "sidebar.extensions.useDefault", defaultValue: "Use Workspace Sidebar"), + systemImage: "sidebar.left" + ) + } + .controlSize(.small) } } .padding(.horizontal, 14) @@ -174,17 +186,7 @@ struct CMUXInstalledExtensionSidebarHostView: View { if #available(macOS 26.0, *) { let extensionPoint = try AppExtensionPoint(identifier: staticExtensionPointIdentifier) let monitor = try await AppExtensionPoint.Monitor(appExtensionPoint: extensionPoint) - observeModernExtensionMonitor(monitor) - let identityTask = Task { @MainActor in - try? await observeIdentitySequence(extensionPointIdentifier: extensionPointIdentifier) - } - defer { - identityTask.cancel() - } - while !Task.isCancelled { - await waitForModernExtensionMonitorChange(monitor) - observeModernExtensionMonitor(monitor) - } + await observeModernExtensionMonitor(monitor) return } @@ -200,11 +202,6 @@ struct CMUXInstalledExtensionSidebarHostView: View { guard let availability = await availabilityUpdates.next() else { break } disabledExtensionCount = availability.disabledCount unapprovedExtensionCount = availability.unapprovedCount - if let currentIdentities = try? await loadCurrentExtensionIdentities( - extensionPointIdentifier: extensionPointIdentifier - ) { - applyEnabledExtensionIdentities(currentIdentities) - } } } defer { @@ -216,12 +213,6 @@ struct CMUXInstalledExtensionSidebarHostView: View { } } - private func loadCurrentExtensionIdentities(extensionPointIdentifier: String) async throws -> [AppExtensionIdentity] { - var identities = try AppExtensionIdentity.matching(appExtensionPointIDs: extensionPointIdentifier) - .makeAsyncIterator() - return await identities.next() ?? [] - } - private func applyEnabledExtensionIdentities(_ identities: [AppExtensionIdentity]) { let sortedIdentities = identities.sorted { $0.localizedName < $1.localizedName } enabledIdentities = sortedIdentities @@ -251,27 +242,31 @@ struct CMUXInstalledExtensionSidebarHostView: View { } @available(macOS 26.0, *) - private func observeModernExtensionMonitor(_ monitor: AppExtensionPoint.Monitor) { - let state = monitor.state + private func applyModernExtensionState(_ state: AppExtensionPoint.Monitor.State) { disabledExtensionCount = state.disabledCount unapprovedExtensionCount = state.unapprovedCount applyEnabledExtensionIdentities(state.identities) } @available(macOS 26.0, *) - private func waitForModernExtensionMonitorChange(_ monitor: AppExtensionPoint.Monitor) async { - let continuationBox = MonitorContinuationBox() - await withTaskCancellationHandler { - await withCheckedContinuation { continuation in - continuationBox.set(continuation) - withObservationTracking { - _ = monitor.state - } onChange: { - continuationBox.resume() + private func observeModernExtensionMonitor(_ monitor: AppExtensionPoint.Monitor) async { + while !Task.isCancelled { + let continuationBox = MonitorContinuationBox() + await withTaskCancellationHandler { + await withCheckedContinuation { continuation in + continuationBox.set(continuation) + withObservationTracking { + applyModernExtensionState(monitor.state) + } onChange: { + continuationBox.resume() + } } + } onCancel: { + continuationBox.cancel() + } + if Task.isCancelled { + break } - } onCancel: { - continuationBox.cancel() } } } @@ -312,11 +307,15 @@ private final class MonitorContinuationBox: @unchecked Sendable { @MainActor private final class CMUXSidebarExtensionHostXPC { + private static let fallbackScopes: Set = [.workspaceMetadata] + private var connection: NSXPCConnection? private var extensionProxy: CMUXSidebarExtensionXPC? private var exportedObject: CMUXSidebarHostXPCObject? private var snapshotProvider: (() -> CMUXSidebarSnapshot)? private var actionHandler: ((CMUXSidebarAction) -> CMUXExtensionActionResult)? + private var allowedScopes = fallbackScopes + private var connectionGeneration: UInt64 = 0 func update( snapshotProvider: @escaping @MainActor () -> CMUXSidebarSnapshot, @@ -324,8 +323,8 @@ private final class CMUXSidebarExtensionHostXPC { ) { self.snapshotProvider = snapshotProvider self.actionHandler = actionHandler - exportedObject?.snapshotProvider = snapshotProvider exportedObject?.actionHandler = actionHandler + updateExportedSnapshotFilter() } func attach( @@ -334,36 +333,42 @@ private final class CMUXSidebarExtensionHostXPC { actionHandler: @escaping @MainActor (CMUXSidebarAction) -> CMUXExtensionActionResult ) { invalidate() + connectionGeneration += 1 + let generation = connectionGeneration let exportedObject = CMUXSidebarHostXPCObject( - snapshotProvider: snapshotProvider, - actionHandler: actionHandler + snapshotProvider: { snapshotProvider().filtered(for: Self.fallbackScopes) }, + actionHandler: actionHandler, + isCurrentGeneration: { [weak self] in + self?.connectionGeneration == generation + } ) connection.exportedInterface = NSXPCInterface(with: CMUXSidebarHostXPC.self) connection.exportedObject = exportedObject connection.remoteObjectInterface = NSXPCInterface(with: CMUXSidebarExtensionXPC.self) - connection.invalidationHandler = { [weak self] in + connection.invalidationHandler = { [weak self, generation] in Task { @MainActor in - self?.clearConnection() + self?.clearConnection(ifCurrentGeneration: generation) } } - connection.interruptionHandler = { [weak self] in + connection.interruptionHandler = { [weak self, generation] in Task { @MainActor in - self?.clearProxy() + self?.clearProxy(ifCurrentGeneration: generation) } } self.exportedObject = exportedObject self.snapshotProvider = snapshotProvider self.actionHandler = actionHandler self.connection = connection + self.allowedScopes = Self.fallbackScopes self.extensionProxy = connection.remoteObjectProxy as? CMUXSidebarExtensionXPC connection.resume() - sendSnapshotDidChange() + requestManifestThenSendInitialSnapshot(generation: generation) } func sendSnapshotDidChange() { guard let extensionProxy, let snapshotProvider else { return } do { - extensionProxy.sidebarSnapshotDidChange(try CMUXSidebarXPCCodec.encodeSnapshot(snapshotProvider())) + extensionProxy.sidebarSnapshotDidChange(try CMUXSidebarXPCCodec.encodeSnapshot(filteredSnapshot(from: snapshotProvider))) } catch { #if DEBUG cmuxDebugLog("extension.sidebar.xpc.snapshot.encode.failed error=\(error.localizedDescription)") @@ -372,36 +377,97 @@ private final class CMUXSidebarExtensionHostXPC { } func invalidate() { + let generation = connectionGeneration connection?.invalidate() - clearConnection() + clearConnection(ifCurrentGeneration: generation) } - private func clearProxy() { + private func clearProxy(ifCurrentGeneration generation: UInt64) { + guard connectionGeneration == generation else { return } extensionProxy = nil } - private func clearConnection() { + private func clearConnection(ifCurrentGeneration generation: UInt64) { + guard connectionGeneration == generation else { return } connection = nil extensionProxy = nil exportedObject = nil + allowedScopes = Self.fallbackScopes + } + + private func requestManifestThenSendInitialSnapshot(generation: UInt64) { + guard let extensionProxy, + let requestExtensionManifest = extensionProxy.requestExtensionManifest else { + updateExportedSnapshotFilter() + sendSnapshotDidChange() + return + } + requestExtensionManifest { [weak self] payload, error in + Task { @MainActor [generation] in + guard let self else { return } + guard self.connectionGeneration == generation else { return } + if let payload { + do { + let manifest = try CMUXSidebarXPCCodec.decodeManifest(payload) + try CMUXExtensionValidator.validateSidebarManifest(manifest) + self.allowedScopes = Set(manifest.requestedScopes) + } catch { + self.allowedScopes = Self.fallbackScopes +#if DEBUG + cmuxDebugLog("extension.sidebar.manifest.invalid error=\(error.localizedDescription)") +#endif + } + } else { + self.allowedScopes = Self.fallbackScopes + if let error { +#if DEBUG + cmuxDebugLog("extension.sidebar.manifest.failed error=\(error)") +#endif + } + } + self.updateExportedSnapshotFilter() + self.sendSnapshotDidChange() + } + } + } + + private func filteredSnapshot(from snapshotProvider: () -> CMUXSidebarSnapshot) -> CMUXSidebarSnapshot { + snapshotProvider().filtered(for: allowedScopes) + } + + private func updateExportedSnapshotFilter() { + guard let snapshotProvider else { return } + exportedObject?.snapshotProvider = { [weak self] in + guard let self else { + return snapshotProvider().filtered(for: Self.fallbackScopes) + } + return filteredSnapshot(from: snapshotProvider) + } } } private final class CMUXSidebarHostXPCObject: NSObject, CMUXSidebarHostXPC { @MainActor var snapshotProvider: () -> CMUXSidebarSnapshot @MainActor var actionHandler: (CMUXSidebarAction) -> CMUXExtensionActionResult + @MainActor var isCurrentGeneration: () -> Bool @MainActor init( snapshotProvider: @escaping @MainActor () -> CMUXSidebarSnapshot, - actionHandler: @escaping @MainActor (CMUXSidebarAction) -> CMUXExtensionActionResult + actionHandler: @escaping @MainActor (CMUXSidebarAction) -> CMUXExtensionActionResult, + isCurrentGeneration: @escaping @MainActor () -> Bool ) { self.snapshotProvider = snapshotProvider self.actionHandler = actionHandler + self.isCurrentGeneration = isCurrentGeneration } func requestSidebarSnapshot(reply: @escaping (NSData?, NSString?) -> Void) { Task { @MainActor in + guard isCurrentGeneration() else { + reply(nil, String(localized: "sidebar.extensions.action.staleConnection", defaultValue: "Extension connection is no longer active") as NSString) + return + } do { reply(try CMUXSidebarXPCCodec.encodeSnapshot(snapshotProvider()), nil) } catch { @@ -412,6 +478,10 @@ private final class CMUXSidebarHostXPCObject: NSObject, CMUXSidebarHostXPC { func performSidebarAction(_ payload: NSData, reply: @escaping (NSData?, NSString?) -> Void) { Task { @MainActor in + guard isCurrentGeneration() else { + reply(nil, String(localized: "sidebar.extensions.action.staleConnection", defaultValue: "Extension connection is no longer active") as NSString) + return + } do { let action = try CMUXSidebarXPCCodec.decodeAction(payload) let result = actionHandler(action) diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index f04be5921d99..cf76d3a751b9 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -6694,7 +6694,7 @@ struct ContentView: View { CommandPaletteCommandContribution( commandId: commandPaletteExtensionSidebarCommandID(descriptor.id), title: constant(String.localizedStringWithFormat(titleFormat, title)), - subtitle: constant(String(localized: "command.switchExtensionSidebar.subtitle", defaultValue: "Sidebar")), + subtitle: constant(String(localized: "command.switchExtensionSidebar.subtitle", defaultValue: "Choose Sidebar")), keywords: ["sidebar", "switch", "extension", title.lowercased()] ) ) @@ -9867,11 +9867,11 @@ enum CmuxExtensionSidebarSelection { id: hostedExtensionsProviderId, title: CmuxExtensionLocalizedText( key: "sidebar.provider.extensions.title", - defaultValue: "CMUX Extensions" + defaultValue: "Extension Sidebar" ), subtitle: CmuxExtensionLocalizedText( key: "sidebar.provider.extensions.subtitle", - defaultValue: "ExtensionKit" + defaultValue: "Custom sidebar" ), systemImageName: "puzzlepiece.extension", isHostProvided: true @@ -9922,7 +9922,7 @@ enum CmuxExtensionSidebarSelection { } menu.addItem(.separator()) let manageItem = NSMenuItem( - title: String(localized: "sidebar.extensions.manage", defaultValue: "Manage Extensions"), + title: String(localized: "sidebar.extensions.manage", defaultValue: "Manage Sidebar Extensions..."), action: #selector(CmuxExtensionSidebarMenuTarget.manageExtensions(_:)), keyEquivalent: "" ) @@ -10640,7 +10640,10 @@ struct VerticalTabsSidebar: View { if selectedExtensionSidebarProviderId == CmuxExtensionSidebarSelection.hostedExtensionsProviderId { CMUXInstalledExtensionSidebarHostView( snapshotProvider: { cmuxSidebarSnapshotForCurrentTabs() }, - actionHandler: { handleCMUXSidebarExtensionAction($0) } + actionHandler: { handleCMUXSidebarExtensionAction($0) }, + onUseDefaultSidebar: { + CmuxExtensionSidebarSelection.setProviderId(CmuxExtensionSidebarProviderID.defaultWorkspaces) + } ) } else { TimelineView(.periodic(from: .now, by: 30)) { timeline in diff --git a/Sources/Update/UpdateTitlebarAccessory.swift b/Sources/Update/UpdateTitlebarAccessory.swift index bab3549ea7df..61971a6fc885 100644 --- a/Sources/Update/UpdateTitlebarAccessory.swift +++ b/Sources/Update/UpdateTitlebarAccessory.swift @@ -899,7 +899,7 @@ struct TitlebarControlsView: View { config: config, foregroundColor: foregroundColor, accessibilityIdentifier: "titlebarControl.sidebarProvider", - accessibilityLabel: String(localized: "command.switchExtensionSidebar.subtitle", defaultValue: "Sidebar"), + accessibilityLabel: String(localized: "command.switchExtensionSidebar.subtitle", defaultValue: "Choose Sidebar"), action: { guard let anchorView = viewModel.sidebarProviderAnchorView else { return } onShowSidebarProviderMenu(anchorView) @@ -914,7 +914,7 @@ struct TitlebarControlsView: View { ) } .background(TitlebarControlAnchorView { viewModel.sidebarProviderAnchorView = $0 }) - .safeHelp(String(localized: "command.switchExtensionSidebar.subtitle", defaultValue: "Sidebar")) + .safeHelp(String(localized: "command.switchExtensionSidebar.subtitle", defaultValue: "Choose Sidebar")) TitlebarControlButton( config: config, diff --git a/Sources/WindowDragHandleView.swift b/Sources/WindowDragHandleView.swift index 7f82f5a6c30e..d9403686f880 100644 --- a/Sources/WindowDragHandleView.swift +++ b/Sources/WindowDragHandleView.swift @@ -811,7 +811,7 @@ enum MinimalModeSidebarControlActionSlot: Int, CaseIterable { case .toggleSidebar: return String(localized: "titlebar.sidebar.accessibilityLabel", defaultValue: "Toggle Sidebar") case .sidebarProvider: - return String(localized: "command.switchExtensionSidebar.subtitle", defaultValue: "Sidebar") + return String(localized: "command.switchExtensionSidebar.subtitle", defaultValue: "Choose Sidebar") case .showNotifications: return String(localized: "titlebar.notifications.accessibilityLabel", defaultValue: "Notifications") case .newTab: From fc51da56c7fb6ed311f38e59386046e54043918a Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Fri, 29 May 2026 19:19:51 -0500 Subject: [PATCH 15/44] Add sidebar extension grants --- .../Connection/SidebarConnectionModel.swift | 3 + .../Manifest/CMUXExtensionManifest.swift | 22 +- .../Manifest/CMUXExtensionScope.swift | 6 + .../Sidebar/CMUXSidebarAction.swift | 11 + .../CmuxExtensionKitTests.swift | 7 +- Resources/Localizable.xcstrings | 85 ++++++ ...MUXInstalledExtensionSidebarHostView.swift | 253 ++++++++++++++++-- 7 files changed, 363 insertions(+), 24 deletions(-) diff --git a/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/Connection/SidebarConnectionModel.swift b/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/Connection/SidebarConnectionModel.swift index 6e6ae5957022..ce0f24dfd7e0 100644 --- a/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/Connection/SidebarConnectionModel.swift +++ b/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/Connection/SidebarConnectionModel.swift @@ -15,6 +15,9 @@ final class SidebarConnectionModel: @unchecked Sendable { .notifications, .networkPorts, .pullRequests, + ], + requestedActionScopes: [ + .selectWorkspace, ] ) diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Manifest/CMUXExtensionManifest.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Manifest/CMUXExtensionManifest.swift index c1e57fb2fcd3..fb23baa88e53 100644 --- a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Manifest/CMUXExtensionManifest.swift +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Manifest/CMUXExtensionManifest.swift @@ -6,18 +6,38 @@ public struct CMUXExtensionManifest: Codable, Equatable, Identifiable, Sendable public var kind: CMUXExtensionKind public var minimumAPIVersion: CMUXExtensionAPIVersion public var requestedScopes: [CMUXExtensionScope] + public var requestedActionScopes: [CMUXExtensionActionScope] public init( id: String, displayName: String, kind: CMUXExtensionKind = .sidebar, minimumAPIVersion: CMUXExtensionAPIVersion = .sidebarV1, - requestedScopes: [CMUXExtensionScope] = [.workspaceMetadata] + requestedScopes: [CMUXExtensionScope] = [.workspaceMetadata], + requestedActionScopes: [CMUXExtensionActionScope] = [.selectWorkspace] ) { self.id = id self.displayName = displayName self.kind = kind self.minimumAPIVersion = minimumAPIVersion self.requestedScopes = requestedScopes + self.requestedActionScopes = requestedActionScopes + } + + public init( + id: String, + displayName: String, + kind: CMUXExtensionKind = .sidebar, + minimumAPIVersion: CMUXExtensionAPIVersion = .sidebarV1, + requestedScopes: [CMUXExtensionScope] + ) { + self.init( + id: id, + displayName: displayName, + kind: kind, + minimumAPIVersion: minimumAPIVersion, + requestedScopes: requestedScopes, + requestedActionScopes: [.selectWorkspace] + ) } } diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Manifest/CMUXExtensionScope.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Manifest/CMUXExtensionScope.swift index 33fc01f3483b..71cec90f5c0a 100644 --- a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Manifest/CMUXExtensionScope.swift +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Manifest/CMUXExtensionScope.swift @@ -7,3 +7,9 @@ public enum CMUXExtensionScope: String, Codable, CaseIterable, Equatable, Sendab case networkPorts case pullRequests } + +public enum CMUXExtensionActionScope: String, Codable, CaseIterable, Equatable, Sendable { + case selectWorkspace + case closeWorkspace + case openURL +} diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarAction.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarAction.swift index 7773b7b33e6e..4e0f4ca8cdf9 100644 --- a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarAction.swift +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarAction.swift @@ -4,4 +4,15 @@ public enum CMUXSidebarAction: Codable, Equatable, Sendable { case selectWorkspace(UUID) case closeWorkspace(UUID) case openURL(String) + + public var requiredScope: CMUXExtensionActionScope { + switch self { + case .selectWorkspace: + return .selectWorkspace + case .closeWorkspace: + return .closeWorkspace + case .openURL: + return .openURL + } + } } diff --git a/Packages/CmuxExtensionKit/Tests/CmuxExtensionKitTests/CmuxExtensionKitTests.swift b/Packages/CmuxExtensionKit/Tests/CmuxExtensionKitTests/CmuxExtensionKitTests.swift index f608d4d2dfb9..c3f1cbc70921 100644 --- a/Packages/CmuxExtensionKit/Tests/CmuxExtensionKitTests/CmuxExtensionKitTests.swift +++ b/Packages/CmuxExtensionKit/Tests/CmuxExtensionKitTests/CmuxExtensionKitTests.swift @@ -40,7 +40,8 @@ struct CMUXExtensionKitTests { let manifest = CMUXExtensionManifest( id: "dev.example.sidebar", displayName: "Example Sidebar", - requestedScopes: [.workspaceMetadata, .workspacePaths] + requestedScopes: [.workspaceMetadata, .workspacePaths], + requestedActionScopes: [.selectWorkspace, .openURL] ) try CMUXExtensionValidator.validateSidebarManifest(manifest) @@ -114,7 +115,8 @@ struct CMUXExtensionKitTests { let manifest = CMUXExtensionManifest( id: "dev.example.sidebar", displayName: "Example Sidebar", - requestedScopes: [.workspaceMetadata, .networkPorts] + requestedScopes: [.workspaceMetadata, .networkPorts], + requestedActionScopes: [.selectWorkspace, .closeWorkspace] ) let decodedManifest = try CMUXSidebarXPCCodec.decodeManifest( try CMUXSidebarXPCCodec.encodeManifest(manifest) @@ -122,6 +124,7 @@ struct CMUXExtensionKitTests { #expect(decodedManifest == manifest) let action = CMUXSidebarAction.selectWorkspace(workspaceID) + #expect(action.requiredScope == .selectWorkspace) let decodedAction = try CMUXSidebarXPCCodec.decodeAction( try CMUXSidebarXPCCodec.encodeAction(action) ) diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index a20df82db197..f1fe90ffedee 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -162530,6 +162530,91 @@ } } }, + "sidebar.extensions.action.scopeRejected": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Extension action is not granted" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "拡張機能の操作は許可されていません" + } + } + } + }, + "sidebar.extensions.access.detail": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "%@ is using metadata-only access until you grant its requested data and actions." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "要求されたデータと操作を許可するまで、%@ はメタデータのみのアクセスを使用します。" + } + } + } + }, + "sidebar.extensions.access.grant": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Grant Requested Access" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "要求されたアクセスを許可" + } + } + } + }, + "sidebar.extensions.access.keepLimited": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Keep Limited" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "制限したままにする" + } + } + } + }, + "sidebar.extensions.access.title": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Limited extension access" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "制限付き拡張機能アクセス" + } + } + } + }, "sidebar.extensions.browser.title": { "extractionState": "manual", "localizations": { diff --git a/Sources/CMUXInstalledExtensionSidebarHostView.swift b/Sources/CMUXInstalledExtensionSidebarHostView.swift index 928c575d6c8a..59a1033c9f37 100644 --- a/Sources/CMUXInstalledExtensionSidebarHostView.swift +++ b/Sources/CMUXInstalledExtensionSidebarHostView.swift @@ -4,6 +4,102 @@ import ExtensionFoundation import Observation import SwiftUI +private struct CMUXSidebarExtensionGrant: Codable, Equatable { + var manifestID: String + var manifestDisplayName: String + var apiVersion: CMUXExtensionAPIVersion + var readScopes: Set + var actionScopes: Set +} + +private struct CMUXSidebarExtensionEffectiveGrant: Equatable { + var manifest: CMUXExtensionManifest + var readScopes: Set + var actionScopes: Set + + var needsAdditionalApproval: Bool { + !readScopes.isSuperset(of: manifest.requestedScopes) || + !actionScopes.isSuperset(of: manifest.requestedActionScopes) + } +} + +private struct CMUXSidebarExtensionGrantStore { + static let defaultReadScopes: Set = [.workspaceMetadata] + static let defaultActionScopes: Set = [.selectWorkspace] + + private static let defaultsKey = "cmuxExtensionSidebar.grants.v1" + + var defaults: UserDefaults = .standard + + func effectiveGrant( + bundleIdentifier: String, + manifest: CMUXExtensionManifest + ) -> CMUXSidebarExtensionEffectiveGrant { + let requestedReadScopes = Set(manifest.requestedScopes) + let requestedActionScopes = Set(manifest.requestedActionScopes) + guard let grant = storedGrants()[bundleIdentifier], + grant.manifestID == manifest.id, + grant.apiVersion == manifest.minimumAPIVersion else { + return CMUXSidebarExtensionEffectiveGrant( + manifest: manifest, + readScopes: requestedReadScopes.intersection(Self.defaultReadScopes), + actionScopes: requestedActionScopes.intersection(Self.defaultActionScopes) + ) + } + return CMUXSidebarExtensionEffectiveGrant( + manifest: manifest, + readScopes: requestedReadScopes.intersection(grant.readScopes), + actionScopes: requestedActionScopes.intersection(grant.actionScopes) + ) + } + + func grantRequestedAccess(bundleIdentifier: String, manifest: CMUXExtensionManifest) { + updateGrant( + bundleIdentifier: bundleIdentifier, + manifest: manifest, + readScopes: Set(manifest.requestedScopes), + actionScopes: Set(manifest.requestedActionScopes) + ) + } + + func revokeSensitiveAccess(bundleIdentifier: String, manifest: CMUXExtensionManifest) { + updateGrant( + bundleIdentifier: bundleIdentifier, + manifest: manifest, + readScopes: Set(manifest.requestedScopes).intersection(Self.defaultReadScopes), + actionScopes: Set(manifest.requestedActionScopes).intersection(Self.defaultActionScopes) + ) + } + + private func updateGrant( + bundleIdentifier: String, + manifest: CMUXExtensionManifest, + readScopes: Set, + actionScopes: Set + ) { + var grants = storedGrants() + grants[bundleIdentifier] = CMUXSidebarExtensionGrant( + manifestID: manifest.id, + manifestDisplayName: manifest.displayName, + apiVersion: manifest.minimumAPIVersion, + readScopes: readScopes, + actionScopes: actionScopes + ) + save(grants) + } + + private func storedGrants() -> [String: CMUXSidebarExtensionGrant] { + guard let data = defaults.data(forKey: Self.defaultsKey) else { return [:] } + return (try? JSONDecoder().decode([String: CMUXSidebarExtensionGrant].self, from: data)) ?? [:] + } + + private func save(_ grants: [String: CMUXSidebarExtensionGrant]) { + if let data = try? JSONEncoder().encode(grants) { + defaults.set(data, forKey: Self.defaultsKey) + } + } +} + struct CMUXInstalledExtensionSidebarHostView: View { private static let selectedExtensionBundleIDDefaultsKey = "cmuxExtensionSidebar.selectedExtensionBundleId" @@ -22,29 +118,40 @@ struct CMUXInstalledExtensionSidebarHostView: View { @State private var unapprovedExtensionCount = 0 @State private var browserAnchorView: NSView? @State private var xpcHost = CMUXSidebarExtensionHostXPC() + @State private var effectiveGrant: CMUXSidebarExtensionEffectiveGrant? var body: some View { Group { if let identity { - CMUXSidebarExtensionHostView( - identity: identity, - onConnection: { connection in - xpcHost.attach( - connection: connection, - snapshotProvider: snapshotProvider, - actionHandler: actionHandler - ) - }, - onDeactivation: { error in - xpcHost.invalidate() - if self.identity?.bundleIdentifier == identity.bundleIdentifier { - self.identity = nil - } - errorText = error?.localizedDescription + VStack(alignment: .leading, spacing: 0) { + if let effectiveGrant, effectiveGrant.needsAdditionalApproval { + extensionAccessBanner(identity: identity, effectiveGrant: effectiveGrant) } - ) - .accessibilityIdentifier("CMUXExtensionSidebarHostView") - .padding(.top, SidebarWorkspaceScrollInsets.workspaceList.top) + CMUXSidebarExtensionHostView( + identity: identity, + onConnection: { connection in + xpcHost.attach( + connection: connection, + bundleIdentifier: identity.bundleIdentifier, + snapshotProvider: snapshotProvider, + actionHandler: actionHandler, + onGrantChanged: { grant in + effectiveGrant = grant + } + ) + }, + onDeactivation: { error in + xpcHost.invalidate() + effectiveGrant = nil + if self.identity?.bundleIdentifier == identity.bundleIdentifier { + self.identity = nil + } + errorText = error?.localizedDescription + } + ) + .accessibilityIdentifier("CMUXExtensionSidebarHostView") + .padding(.top, effectiveGrant?.needsAdditionalApproval == true ? 8 : SidebarWorkspaceScrollInsets.workspaceList.top) + } } else { VStack(alignment: .leading, spacing: 10) { if isLoading { @@ -179,6 +286,46 @@ struct CMUXInstalledExtensionSidebarHostView: View { } } + private func extensionAccessBanner( + identity: AppExtensionIdentity, + effectiveGrant: CMUXSidebarExtensionEffectiveGrant + ) -> some View { + VStack(alignment: .leading, spacing: 8) { + Text(String(localized: "sidebar.extensions.access.title", defaultValue: "Limited extension access")) + .font(.system(size: 12, weight: .semibold)) + .foregroundStyle(.primary) + Text(String.localizedStringWithFormat( + String(localized: "sidebar.extensions.access.detail", defaultValue: "%@ is using metadata-only access until you grant its requested data and actions."), + effectiveGrant.manifest.displayName + )) + .font(.system(size: 11)) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + HStack(spacing: 8) { + Button { + xpcHost.grantRequestedAccess(bundleIdentifier: identity.bundleIdentifier) + self.effectiveGrant = xpcHost.currentEffectiveGrant + xpcHost.sendSnapshotDidChange() + } label: { + Text(String(localized: "sidebar.extensions.access.grant", defaultValue: "Grant Requested Access")) + } + .controlSize(.small) + Button { + xpcHost.revokeSensitiveAccess(bundleIdentifier: identity.bundleIdentifier) + self.effectiveGrant = xpcHost.currentEffectiveGrant + xpcHost.sendSnapshotDidChange() + } label: { + Text(String(localized: "sidebar.extensions.access.keepLimited", defaultValue: "Keep Limited")) + } + .controlSize(.small) + } + } + .padding(.horizontal, 12) + .padding(.top, SidebarWorkspaceScrollInsets.workspaceList.top + 8) + .padding(.bottom, 10) + .background(Color(nsColor: .controlBackgroundColor).opacity(0.88)) + } + private func observeEnabledExtensionIdentities( extensionPointIdentifier: String, staticExtensionPointIdentifier: StaticString @@ -229,6 +376,7 @@ struct CMUXInstalledExtensionSidebarHostView: View { } if nextIdentity?.bundleIdentifier != identity?.bundleIdentifier { xpcHost.invalidate() + effectiveGrant = nil identity = nextIdentity } isLoading = false @@ -308,6 +456,7 @@ private final class MonitorContinuationBox: @unchecked Sendable { @MainActor private final class CMUXSidebarExtensionHostXPC { private static let fallbackScopes: Set = [.workspaceMetadata] + private static let fallbackActionScopes: Set = [.selectWorkspace] private var connection: NSXPCConnection? private var extensionProxy: CMUXSidebarExtensionXPC? @@ -315,7 +464,17 @@ private final class CMUXSidebarExtensionHostXPC { private var snapshotProvider: (() -> CMUXSidebarSnapshot)? private var actionHandler: ((CMUXSidebarAction) -> CMUXExtensionActionResult)? private var allowedScopes = fallbackScopes + private var allowedActionScopes = fallbackActionScopes private var connectionGeneration: UInt64 = 0 + private var bundleIdentifier: String? + private var currentManifest: CMUXExtensionManifest? + private var onGrantChanged: ((CMUXSidebarExtensionEffectiveGrant?) -> Void)? + private let grantStore = CMUXSidebarExtensionGrantStore() + + var currentEffectiveGrant: CMUXSidebarExtensionEffectiveGrant? { + guard let bundleIdentifier, let currentManifest else { return nil } + return grantStore.effectiveGrant(bundleIdentifier: bundleIdentifier, manifest: currentManifest) + } func update( snapshotProvider: @escaping @MainActor () -> CMUXSidebarSnapshot, @@ -329,15 +488,25 @@ private final class CMUXSidebarExtensionHostXPC { func attach( connection: NSXPCConnection, + bundleIdentifier: String, snapshotProvider: @escaping @MainActor () -> CMUXSidebarSnapshot, - actionHandler: @escaping @MainActor (CMUXSidebarAction) -> CMUXExtensionActionResult + actionHandler: @escaping @MainActor (CMUXSidebarAction) -> CMUXExtensionActionResult, + onGrantChanged: @escaping @MainActor (CMUXSidebarExtensionEffectiveGrant?) -> Void ) { invalidate() connectionGeneration += 1 let generation = connectionGeneration let exportedObject = CMUXSidebarHostXPCObject( snapshotProvider: { snapshotProvider().filtered(for: Self.fallbackScopes) }, - actionHandler: actionHandler, + actionHandler: { [weak self] action in + guard let self, self.allowedActionScopes.contains(action.requiredScope) else { + return CMUXExtensionActionResult( + accepted: false, + message: String(localized: "sidebar.extensions.action.scopeRejected", defaultValue: "Extension action is not granted") + ) + } + return actionHandler(action) + }, isCurrentGeneration: { [weak self] in self?.connectionGeneration == generation } @@ -359,7 +528,11 @@ private final class CMUXSidebarExtensionHostXPC { self.snapshotProvider = snapshotProvider self.actionHandler = actionHandler self.connection = connection + self.bundleIdentifier = bundleIdentifier + self.currentManifest = nil + self.onGrantChanged = onGrantChanged self.allowedScopes = Self.fallbackScopes + self.allowedActionScopes = Self.fallbackActionScopes self.extensionProxy = connection.remoteObjectProxy as? CMUXSidebarExtensionXPC connection.resume() requestManifestThenSendInitialSnapshot(generation: generation) @@ -377,6 +550,7 @@ private final class CMUXSidebarExtensionHostXPC { } func invalidate() { + connectionGeneration += 1 let generation = connectionGeneration connection?.invalidate() clearConnection(ifCurrentGeneration: generation) @@ -393,6 +567,11 @@ private final class CMUXSidebarExtensionHostXPC { extensionProxy = nil exportedObject = nil allowedScopes = Self.fallbackScopes + allowedActionScopes = Self.fallbackActionScopes + bundleIdentifier = nil + currentManifest = nil + onGrantChanged?(nil) + onGrantChanged = nil } private func requestManifestThenSendInitialSnapshot(generation: UInt64) { @@ -410,15 +589,21 @@ private final class CMUXSidebarExtensionHostXPC { do { let manifest = try CMUXSidebarXPCCodec.decodeManifest(payload) try CMUXExtensionValidator.validateSidebarManifest(manifest) - self.allowedScopes = Set(manifest.requestedScopes) + self.applyManifest(manifest) } catch { self.allowedScopes = Self.fallbackScopes + self.allowedActionScopes = Self.fallbackActionScopes + self.currentManifest = nil + self.onGrantChanged?(nil) #if DEBUG cmuxDebugLog("extension.sidebar.manifest.invalid error=\(error.localizedDescription)") #endif } } else { self.allowedScopes = Self.fallbackScopes + self.allowedActionScopes = Self.fallbackActionScopes + self.currentManifest = nil + self.onGrantChanged?(nil) if let error { #if DEBUG cmuxDebugLog("extension.sidebar.manifest.failed error=\(error)") @@ -431,6 +616,32 @@ private final class CMUXSidebarExtensionHostXPC { } } + func grantRequestedAccess(bundleIdentifier: String) { + guard self.bundleIdentifier == bundleIdentifier, let currentManifest else { return } + grantStore.grantRequestedAccess(bundleIdentifier: bundleIdentifier, manifest: currentManifest) + applyManifest(currentManifest) + } + + func revokeSensitiveAccess(bundleIdentifier: String) { + guard self.bundleIdentifier == bundleIdentifier, let currentManifest else { return } + grantStore.revokeSensitiveAccess(bundleIdentifier: bundleIdentifier, manifest: currentManifest) + applyManifest(currentManifest) + } + + private func applyManifest(_ manifest: CMUXExtensionManifest) { + currentManifest = manifest + guard let bundleIdentifier else { + allowedScopes = Self.fallbackScopes + allowedActionScopes = Self.fallbackActionScopes + onGrantChanged?(nil) + return + } + let effectiveGrant = grantStore.effectiveGrant(bundleIdentifier: bundleIdentifier, manifest: manifest) + allowedScopes = effectiveGrant.readScopes + allowedActionScopes = effectiveGrant.actionScopes + onGrantChanged?(effectiveGrant) + } + private func filteredSnapshot(from snapshotProvider: () -> CMUXSidebarSnapshot) -> CMUXSidebarSnapshot { snapshotProvider().filtered(for: allowedScopes) } From 245bf971de79d8892444c761a84b029753b8329b Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Fri, 29 May 2026 19:27:28 -0500 Subject: [PATCH 16/44] Tear down disabled sidebar extensions --- Sources/CMUXInstalledExtensionSidebarHostView.swift | 5 ++++- Sources/ContentView.swift | 1 + 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/Sources/CMUXInstalledExtensionSidebarHostView.swift b/Sources/CMUXInstalledExtensionSidebarHostView.swift index 59a1033c9f37..a65dd1f66160 100644 --- a/Sources/CMUXInstalledExtensionSidebarHostView.swift +++ b/Sources/CMUXInstalledExtensionSidebarHostView.swift @@ -149,6 +149,7 @@ struct CMUXInstalledExtensionSidebarHostView: View { errorText = error?.localizedDescription } ) + .id(identity.bundleIdentifier) .accessibilityIdentifier("CMUXExtensionSidebarHostView") .padding(.top, effectiveGrant?.needsAdditionalApproval == true ? 8 : SidebarWorkspaceScrollInsets.workspaceList.top) } @@ -393,7 +394,9 @@ struct CMUXInstalledExtensionSidebarHostView: View { private func applyModernExtensionState(_ state: AppExtensionPoint.Monitor.State) { disabledExtensionCount = state.disabledCount unapprovedExtensionCount = state.unapprovedCount - applyEnabledExtensionIdentities(state.identities) + let unavailableCount = state.disabledCount + state.unapprovedCount + let enabledIdentities = unavailableCount >= state.identities.count ? [] : state.identities + applyEnabledExtensionIdentities(enabledIdentities) } @available(macOS 26.0, *) diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index cf76d3a751b9..9194fd2821f4 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -9948,6 +9948,7 @@ private final class CmuxExtensionSidebarMenuTarget: NSObject { @objc func manageExtensions(_ sender: NSMenuItem) { guard let anchorView = sender.representedObject as? NSView else { return } + CmuxExtensionSidebarSelection.setProviderId(CmuxExtensionSidebarSelection.hostedExtensionsProviderId) CMUXSidebarExtensionBrowserPresenter.present( from: anchorView, title: String(localized: "sidebar.extensions.browser.title", defaultValue: "Sidebar Extensions") From 19c91bc5307cc7e2218f5ff22e00e0be9f3d3d69 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Fri, 29 May 2026 19:32:12 -0500 Subject: [PATCH 17/44] Require sidebar extension manifests before host access --- .../Manifest/CMUXExtensionManifest.swift | 22 +++++ .../CmuxExtensionKitTests.swift | 19 +++++ ...MUXInstalledExtensionSidebarHostView.swift | 83 ++++++++++++------- 3 files changed, 93 insertions(+), 31 deletions(-) diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Manifest/CMUXExtensionManifest.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Manifest/CMUXExtensionManifest.swift index fb23baa88e53..f14744be4f0b 100644 --- a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Manifest/CMUXExtensionManifest.swift +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Manifest/CMUXExtensionManifest.swift @@ -40,4 +40,26 @@ public struct CMUXExtensionManifest: Codable, Equatable, Identifiable, Sendable requestedActionScopes: [.selectWorkspace] ) } + + private enum CodingKeys: String, CodingKey { + case id + case displayName + case kind + case minimumAPIVersion + case requestedScopes + case requestedActionScopes + } + + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + id = try container.decode(String.self, forKey: .id) + displayName = try container.decode(String.self, forKey: .displayName) + kind = try container.decode(CMUXExtensionKind.self, forKey: .kind) + minimumAPIVersion = try container.decode(CMUXExtensionAPIVersion.self, forKey: .minimumAPIVersion) + requestedScopes = try container.decode([CMUXExtensionScope].self, forKey: .requestedScopes) + requestedActionScopes = try container.decodeIfPresent( + [CMUXExtensionActionScope].self, + forKey: .requestedActionScopes + ) ?? [] + } } diff --git a/Packages/CmuxExtensionKit/Tests/CmuxExtensionKitTests/CmuxExtensionKitTests.swift b/Packages/CmuxExtensionKit/Tests/CmuxExtensionKitTests/CmuxExtensionKitTests.swift index c3f1cbc70921..54849b10e86e 100644 --- a/Packages/CmuxExtensionKit/Tests/CmuxExtensionKitTests/CmuxExtensionKitTests.swift +++ b/Packages/CmuxExtensionKit/Tests/CmuxExtensionKitTests/CmuxExtensionKitTests.swift @@ -47,6 +47,25 @@ struct CMUXExtensionKitTests { try CMUXExtensionValidator.validateSidebarManifest(manifest) } + @Test + func testManifestDecodingDefaultsMissingActionScopesToNone() throws { + let payload = Data(""" + { + "id": "dev.example.sidebar", + "displayName": "Example Sidebar", + "kind": "sidebar", + "minimumAPIVersion": { "major": 1, "minor": 0 }, + "requestedScopes": ["workspaceMetadata"] + } + """.utf8) + + let manifest = try JSONDecoder().decode(CMUXExtensionManifest.self, from: payload) + + #expect(manifest.requestedScopes == [.workspaceMetadata]) + #expect(manifest.requestedActionScopes.isEmpty) + try CMUXExtensionValidator.validateSidebarManifest(manifest) + } + @Test func testSidebarSnapshotFilteringRemovesUngrantedScopeData() throws { let workspaceID = UUID(uuidString: "44444444-4444-4444-4444-444444444444")! diff --git a/Sources/CMUXInstalledExtensionSidebarHostView.swift b/Sources/CMUXInstalledExtensionSidebarHostView.swift index a65dd1f66160..3acdcf59d563 100644 --- a/Sources/CMUXInstalledExtensionSidebarHostView.swift +++ b/Sources/CMUXInstalledExtensionSidebarHostView.swift @@ -458,16 +458,16 @@ private final class MonitorContinuationBox: @unchecked Sendable { @MainActor private final class CMUXSidebarExtensionHostXPC { - private static let fallbackScopes: Set = [.workspaceMetadata] - private static let fallbackActionScopes: Set = [.selectWorkspace] + private static let untrustedScopes: Set = [] + private static let untrustedActionScopes: Set = [] private var connection: NSXPCConnection? private var extensionProxy: CMUXSidebarExtensionXPC? private var exportedObject: CMUXSidebarHostXPCObject? private var snapshotProvider: (() -> CMUXSidebarSnapshot)? private var actionHandler: ((CMUXSidebarAction) -> CMUXExtensionActionResult)? - private var allowedScopes = fallbackScopes - private var allowedActionScopes = fallbackActionScopes + private var allowedScopes = untrustedScopes + private var allowedActionScopes = untrustedActionScopes private var connectionGeneration: UInt64 = 0 private var bundleIdentifier: String? private var currentManifest: CMUXExtensionManifest? @@ -485,7 +485,7 @@ private final class CMUXSidebarExtensionHostXPC { ) { self.snapshotProvider = snapshotProvider self.actionHandler = actionHandler - exportedObject?.actionHandler = actionHandler + exportedObject?.actionHandler = scopedActionHandler(actionHandler) updateExportedSnapshotFilter() } @@ -500,16 +500,8 @@ private final class CMUXSidebarExtensionHostXPC { connectionGeneration += 1 let generation = connectionGeneration let exportedObject = CMUXSidebarHostXPCObject( - snapshotProvider: { snapshotProvider().filtered(for: Self.fallbackScopes) }, - actionHandler: { [weak self] action in - guard let self, self.allowedActionScopes.contains(action.requiredScope) else { - return CMUXExtensionActionResult( - accepted: false, - message: String(localized: "sidebar.extensions.action.scopeRejected", defaultValue: "Extension action is not granted") - ) - } - return actionHandler(action) - }, + snapshotProvider: { Self.untrustedSnapshot(from: snapshotProvider()) }, + actionHandler: scopedActionHandler(actionHandler), isCurrentGeneration: { [weak self] in self?.connectionGeneration == generation } @@ -534,8 +526,8 @@ private final class CMUXSidebarExtensionHostXPC { self.bundleIdentifier = bundleIdentifier self.currentManifest = nil self.onGrantChanged = onGrantChanged - self.allowedScopes = Self.fallbackScopes - self.allowedActionScopes = Self.fallbackActionScopes + self.allowedScopes = Self.untrustedScopes + self.allowedActionScopes = Self.untrustedActionScopes self.extensionProxy = connection.remoteObjectProxy as? CMUXSidebarExtensionXPC connection.resume() requestManifestThenSendInitialSnapshot(generation: generation) @@ -569,8 +561,8 @@ private final class CMUXSidebarExtensionHostXPC { connection = nil extensionProxy = nil exportedObject = nil - allowedScopes = Self.fallbackScopes - allowedActionScopes = Self.fallbackActionScopes + allowedScopes = Self.untrustedScopes + allowedActionScopes = Self.untrustedActionScopes bundleIdentifier = nil currentManifest = nil onGrantChanged?(nil) @@ -580,8 +572,8 @@ private final class CMUXSidebarExtensionHostXPC { private func requestManifestThenSendInitialSnapshot(generation: UInt64) { guard let extensionProxy, let requestExtensionManifest = extensionProxy.requestExtensionManifest else { + blockUntrustedExtension(reason: "missingManifest") updateExportedSnapshotFilter() - sendSnapshotDidChange() return } requestExtensionManifest { [weak self] payload, error in @@ -594,19 +586,13 @@ private final class CMUXSidebarExtensionHostXPC { try CMUXExtensionValidator.validateSidebarManifest(manifest) self.applyManifest(manifest) } catch { - self.allowedScopes = Self.fallbackScopes - self.allowedActionScopes = Self.fallbackActionScopes - self.currentManifest = nil - self.onGrantChanged?(nil) + self.blockUntrustedExtension(reason: "invalidManifest") #if DEBUG cmuxDebugLog("extension.sidebar.manifest.invalid error=\(error.localizedDescription)") #endif } } else { - self.allowedScopes = Self.fallbackScopes - self.allowedActionScopes = Self.fallbackActionScopes - self.currentManifest = nil - self.onGrantChanged?(nil) + self.blockUntrustedExtension(reason: "manifestRequestFailed") if let error { #if DEBUG cmuxDebugLog("extension.sidebar.manifest.failed error=\(error)") @@ -634,8 +620,8 @@ private final class CMUXSidebarExtensionHostXPC { private func applyManifest(_ manifest: CMUXExtensionManifest) { currentManifest = manifest guard let bundleIdentifier else { - allowedScopes = Self.fallbackScopes - allowedActionScopes = Self.fallbackActionScopes + allowedScopes = Self.untrustedScopes + allowedActionScopes = Self.untrustedActionScopes onGrantChanged?(nil) return } @@ -653,11 +639,46 @@ private final class CMUXSidebarExtensionHostXPC { guard let snapshotProvider else { return } exportedObject?.snapshotProvider = { [weak self] in guard let self else { - return snapshotProvider().filtered(for: Self.fallbackScopes) + return Self.untrustedSnapshot(from: snapshotProvider()) } return filteredSnapshot(from: snapshotProvider) } } + + private func scopedActionHandler( + _ actionHandler: @escaping @MainActor (CMUXSidebarAction) -> CMUXExtensionActionResult + ) -> (@MainActor (CMUXSidebarAction) -> CMUXExtensionActionResult) { + { [weak self] action in + guard let self, + self.currentManifest != nil, + self.allowedActionScopes.contains(action.requiredScope) else { + return CMUXExtensionActionResult( + accepted: false, + message: String(localized: "sidebar.extensions.action.scopeRejected", defaultValue: "Extension action is not granted") + ) + } + return actionHandler(action) + } + } + + private func blockUntrustedExtension(reason: String) { + allowedScopes = Self.untrustedScopes + allowedActionScopes = Self.untrustedActionScopes + currentManifest = nil + onGrantChanged?(nil) +#if DEBUG + cmuxDebugLog("extension.sidebar.manifest.blocked reason=\(reason)") +#endif + } + + private static func untrustedSnapshot(from snapshot: CMUXSidebarSnapshot) -> CMUXSidebarSnapshot { + CMUXSidebarSnapshot( + apiVersion: snapshot.apiVersion, + sequence: snapshot.sequence, + selectedWorkspaceID: nil, + workspaces: [] + ) + } } private final class CMUXSidebarHostXPCObject: NSObject, CMUXSidebarHostXPC { From a0676d281ccc60afe73eaca3d5d7240547ecb2df Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Fri, 29 May 2026 19:37:19 -0500 Subject: [PATCH 18/44] Add sidebar extension host controls --- Resources/Localizable.xcstrings | 17 +++ ...MUXInstalledExtensionSidebarHostView.swift | 144 +++++++++++------- 2 files changed, 104 insertions(+), 57 deletions(-) diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index f1fe90ffedee..0b9056cf5c20 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -162598,6 +162598,23 @@ } } }, + "sidebar.extensions.access.statusLimited.help": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "This extension has limited access." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "この拡張機能のアクセスは制限されています。" + } + } + } + }, "sidebar.extensions.access.title": { "extractionState": "manual", "localizations": { diff --git a/Sources/CMUXInstalledExtensionSidebarHostView.swift b/Sources/CMUXInstalledExtensionSidebarHostView.swift index 3acdcf59d563..8b471d40dfc8 100644 --- a/Sources/CMUXInstalledExtensionSidebarHostView.swift +++ b/Sources/CMUXInstalledExtensionSidebarHostView.swift @@ -124,6 +124,7 @@ struct CMUXInstalledExtensionSidebarHostView: View { Group { if let identity { VStack(alignment: .leading, spacing: 0) { + extensionControlStrip(activeIdentity: identity) if let effectiveGrant, effectiveGrant.needsAdditionalApproval { extensionAccessBanner(identity: identity, effectiveGrant: effectiveGrant) } @@ -151,10 +152,11 @@ struct CMUXInstalledExtensionSidebarHostView: View { ) .id(identity.bundleIdentifier) .accessibilityIdentifier("CMUXExtensionSidebarHostView") - .padding(.top, effectiveGrant?.needsAdditionalApproval == true ? 8 : SidebarWorkspaceScrollInsets.workspaceList.top) + .padding(.top, effectiveGrant?.needsAdditionalApproval == true ? 8 : 0) } } else { VStack(alignment: .leading, spacing: 10) { + extensionControlStrip(activeIdentity: nil) if isLoading { ProgressView() .controlSize(.small) @@ -181,41 +183,9 @@ struct CMUXInstalledExtensionSidebarHostView: View { .foregroundStyle(.secondary) .fixedSize(horizontal: false, vertical: true) } - if enabledIdentities.count > 1 { - enabledExtensionPicker - } - Button { - if let browserAnchorView { - CMUXSidebarExtensionBrowserPresenter.present( - from: browserAnchorView, - title: String( - localized: "sidebar.extensions.browser.title", - defaultValue: "Sidebar Extensions" - ) - ) - } - } label: { - Label( - String(localized: "sidebar.extensions.manage", defaultValue: "Manage Sidebar Extensions..."), - systemImage: "puzzlepiece.extension" - ) - } - .controlSize(.small) - Button { - onUseDefaultSidebar() - } label: { - Label( - String(localized: "sidebar.extensions.useDefault", defaultValue: "Use Workspace Sidebar"), - systemImage: "sidebar.left" - ) - } - .controlSize(.small) } } - .padding(.horizontal, 14) - .padding(.top, SidebarWorkspaceScrollInsets.workspaceList.top + 12) .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) - .background(TitlebarControlAnchorView { browserAnchorView = $0 }) .accessibilityIdentifier("CMUXExtensionSidebarEmptyState") } } @@ -260,33 +230,86 @@ struct CMUXInstalledExtensionSidebarHostView: View { ) } - private var enabledExtensionPicker: some View { - VStack(alignment: .leading, spacing: 6) { - Text(String( - localized: "sidebar.extensions.choose.detail", - defaultValue: "Choose which enabled extension should replace the sidebar." - )) - .font(.system(size: 12)) - .foregroundStyle(.secondary) - .fixedSize(horizontal: false, vertical: true) - ForEach(enabledIdentities, id: \.bundleIdentifier) { enabledIdentity in - Button { - selectExtension(enabledIdentity) - } label: { - HStack(spacing: 6) { - Image(systemName: enabledIdentity.bundleIdentifier == selectedExtensionBundleID ? "checkmark.circle.fill" : "circle") - .font(.system(size: 11, weight: .medium)) - Text(enabledIdentity.localizedName) - .font(.system(size: 12, weight: .medium)) - .lineLimit(1) + private func extensionControlStrip(activeIdentity: AppExtensionIdentity?) -> some View { + HStack(spacing: 8) { + extensionIdentityControl(activeIdentity: activeIdentity) + Spacer(minLength: 8) + if effectiveGrant?.needsAdditionalApproval == true { + Image(systemName: "lock") + .font(.system(size: 11, weight: .medium)) + .foregroundStyle(.secondary) + .help(String(localized: "sidebar.extensions.access.statusLimited.help", defaultValue: "This extension has limited access.")) + } + Button { + onUseDefaultSidebar() + } label: { + Image(systemName: "sidebar.left") + } + .buttonStyle(.plain) + .controlSize(.small) + .help(String(localized: "sidebar.extensions.useDefault", defaultValue: "Use Workspace Sidebar")) + Button { + presentExtensionBrowser() + } label: { + Image(systemName: "puzzlepiece.extension") + } + .buttonStyle(.plain) + .controlSize(.small) + .help(String(localized: "sidebar.extensions.manage", defaultValue: "Manage Sidebar Extensions...")) + } + .padding(.horizontal, 12) + .padding(.top, SidebarWorkspaceScrollInsets.workspaceList.top + 8) + .padding(.bottom, 8) + .frame(maxWidth: .infinity, alignment: .leading) + .background(TitlebarControlAnchorView { browserAnchorView = $0 }) + .background(Color(nsColor: .controlBackgroundColor).opacity(0.86)) + } + + @ViewBuilder + private func extensionIdentityControl(activeIdentity: AppExtensionIdentity?) -> some View { + if enabledIdentities.count > 1 { + Menu { + ForEach(enabledIdentities, id: \.bundleIdentifier) { enabledIdentity in + Button { + selectExtension(enabledIdentity) + } label: { + Label( + enabledIdentity.localizedName, + systemImage: enabledIdentity.bundleIdentifier == activeIdentity?.bundleIdentifier ? "checkmark" : "puzzlepiece.extension" + ) } - .frame(maxWidth: .infinity, alignment: .leading) } - .buttonStyle(.plain) + } label: { + Label( + activeIdentity?.localizedName ?? String(localized: "sidebar.provider.extensions.title", defaultValue: "Extension Sidebar"), + systemImage: "puzzlepiece.extension" + ) + .lineLimit(1) } + .menuStyle(.button) + .controlSize(.small) + } else { + Label( + activeIdentity?.localizedName ?? String(localized: "sidebar.provider.extensions.title", defaultValue: "Extension Sidebar"), + systemImage: "puzzlepiece.extension" + ) + .font(.system(size: 12, weight: .semibold)) + .foregroundStyle(.secondary) + .lineLimit(1) } } + private func presentExtensionBrowser() { + guard let browserAnchorView else { return } + CMUXSidebarExtensionBrowserPresenter.present( + from: browserAnchorView, + title: String( + localized: "sidebar.extensions.browser.title", + defaultValue: "Sidebar Extensions" + ) + ) + } + private func extensionAccessBanner( identity: AppExtensionIdentity, effectiveGrant: CMUXSidebarExtensionEffectiveGrant @@ -394,9 +417,7 @@ struct CMUXInstalledExtensionSidebarHostView: View { private func applyModernExtensionState(_ state: AppExtensionPoint.Monitor.State) { disabledExtensionCount = state.disabledCount unapprovedExtensionCount = state.unapprovedCount - let unavailableCount = state.disabledCount + state.unapprovedCount - let enabledIdentities = unavailableCount >= state.identities.count ? [] : state.identities - applyEnabledExtensionIdentities(enabledIdentities) + applyEnabledExtensionIdentities(state.identities) } @available(macOS 26.0, *) @@ -502,6 +523,9 @@ private final class CMUXSidebarExtensionHostXPC { let exportedObject = CMUXSidebarHostXPCObject( snapshotProvider: { Self.untrustedSnapshot(from: snapshotProvider()) }, actionHandler: scopedActionHandler(actionHandler), + onAcceptedAction: { [weak self] in + self?.sendSnapshotDidChange() + }, isCurrentGeneration: { [weak self] in self?.connectionGeneration == generation } @@ -684,16 +708,19 @@ private final class CMUXSidebarExtensionHostXPC { private final class CMUXSidebarHostXPCObject: NSObject, CMUXSidebarHostXPC { @MainActor var snapshotProvider: () -> CMUXSidebarSnapshot @MainActor var actionHandler: (CMUXSidebarAction) -> CMUXExtensionActionResult + @MainActor var onAcceptedAction: () -> Void @MainActor var isCurrentGeneration: () -> Bool @MainActor init( snapshotProvider: @escaping @MainActor () -> CMUXSidebarSnapshot, actionHandler: @escaping @MainActor (CMUXSidebarAction) -> CMUXExtensionActionResult, + onAcceptedAction: @escaping @MainActor () -> Void, isCurrentGeneration: @escaping @MainActor () -> Bool ) { self.snapshotProvider = snapshotProvider self.actionHandler = actionHandler + self.onAcceptedAction = onAcceptedAction self.isCurrentGeneration = isCurrentGeneration } @@ -721,6 +748,9 @@ private final class CMUXSidebarHostXPCObject: NSObject, CMUXSidebarHostXPC { let action = try CMUXSidebarXPCCodec.decodeAction(payload) let result = actionHandler(action) reply(try CMUXSidebarXPCCodec.encodeActionResult(result), nil) + if result.accepted { + onAcceptedAction() + } } catch { reply(nil, error.localizedDescription as NSString) } From e03c71a7eef70108e348433795f3eaca66b58231 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Fri, 29 May 2026 19:41:03 -0500 Subject: [PATCH 19/44] Cap sidebar extension XPC payload sizes --- .../Sidebar/CMUXSidebarXPC.swift | 27 +++++++++++--- .../CMUXExtensionValidationError.swift | 1 + .../CmuxExtensionKitTests.swift | 36 +++++++++++++++++++ 3 files changed, 60 insertions(+), 4 deletions(-) diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarXPC.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarXPC.swift index bbf797cb50d5..a18f259892dd 100644 --- a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarXPC.swift +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarXPC.swift @@ -11,12 +11,18 @@ import Foundation } public enum CMUXSidebarXPCCodec { + public static let maximumSnapshotPayloadBytes = 512 * 1024 + public static let maximumManifestPayloadBytes = 64 * 1024 + public static let maximumActionPayloadBytes = 8 * 1024 + public static let maximumActionResultPayloadBytes = 8 * 1024 + public static func encodeSnapshot(_ snapshot: CMUXSidebarSnapshot) throws -> NSData { try JSONEncoder().encode(snapshot) as NSData } public static func decodeSnapshot(_ payload: NSData) throws -> CMUXSidebarSnapshot { - try JSONDecoder().decode(CMUXSidebarSnapshot.self, from: payload as Data) + try validatePayloadSize(payload, kind: "snapshot", maximumBytes: maximumSnapshotPayloadBytes) + return try JSONDecoder().decode(CMUXSidebarSnapshot.self, from: payload as Data) } public static func encodeManifest(_ manifest: CMUXExtensionManifest) throws -> NSData { @@ -24,7 +30,8 @@ public enum CMUXSidebarXPCCodec { } public static func decodeManifest(_ payload: NSData) throws -> CMUXExtensionManifest { - try JSONDecoder().decode(CMUXExtensionManifest.self, from: payload as Data) + try validatePayloadSize(payload, kind: "manifest", maximumBytes: maximumManifestPayloadBytes) + return try JSONDecoder().decode(CMUXExtensionManifest.self, from: payload as Data) } public static func encodeAction(_ action: CMUXSidebarAction) throws -> NSData { @@ -32,7 +39,8 @@ public enum CMUXSidebarXPCCodec { } public static func decodeAction(_ payload: NSData) throws -> CMUXSidebarAction { - try JSONDecoder().decode(CMUXSidebarAction.self, from: payload as Data) + try validatePayloadSize(payload, kind: "action", maximumBytes: maximumActionPayloadBytes) + return try JSONDecoder().decode(CMUXSidebarAction.self, from: payload as Data) } public static func encodeActionResult(_ result: CMUXExtensionActionResult) throws -> NSData { @@ -40,6 +48,17 @@ public enum CMUXSidebarXPCCodec { } public static func decodeActionResult(_ payload: NSData) throws -> CMUXExtensionActionResult { - try JSONDecoder().decode(CMUXExtensionActionResult.self, from: payload as Data) + try validatePayloadSize(payload, kind: "actionResult", maximumBytes: maximumActionResultPayloadBytes) + return try JSONDecoder().decode(CMUXExtensionActionResult.self, from: payload as Data) + } + + private static func validatePayloadSize(_ payload: NSData, kind: String, maximumBytes: Int) throws { + guard payload.length <= maximumBytes else { + throw CMUXExtensionValidationError.payloadTooLarge( + kind: kind, + actualBytes: payload.length, + maximumBytes: maximumBytes + ) + } } } diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Validation/CMUXExtensionValidationError.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Validation/CMUXExtensionValidationError.swift index eb28b5bc7e26..3a4c7d88b9e9 100644 --- a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Validation/CMUXExtensionValidationError.swift +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Validation/CMUXExtensionValidationError.swift @@ -5,4 +5,5 @@ public enum CMUXExtensionValidationError: Error, Equatable, Sendable { case unsupportedAPIVersion(requested: CMUXExtensionAPIVersion, supported: CMUXExtensionAPIVersion) case emptyIdentifier case emptyDisplayName + case payloadTooLarge(kind: String, actualBytes: Int, maximumBytes: Int) } diff --git a/Packages/CmuxExtensionKit/Tests/CmuxExtensionKitTests/CmuxExtensionKitTests.swift b/Packages/CmuxExtensionKit/Tests/CmuxExtensionKitTests/CmuxExtensionKitTests.swift index 54849b10e86e..0195bec6c087 100644 --- a/Packages/CmuxExtensionKit/Tests/CmuxExtensionKitTests/CmuxExtensionKitTests.swift +++ b/Packages/CmuxExtensionKit/Tests/CmuxExtensionKitTests/CmuxExtensionKitTests.swift @@ -156,6 +156,42 @@ struct CMUXExtensionKitTests { #expect(decodedResult == result) } + @Test + func testSidebarXPCCodecRejectsOversizedManifestPayload() { + let payload = Data(repeating: 0x20, count: CMUXSidebarXPCCodec.maximumManifestPayloadBytes + 1) as NSData + + do { + _ = try CMUXSidebarXPCCodec.decodeManifest(payload) + Issue.record("Expected oversized manifest payload to be rejected") + } catch { + #expect( + error as? CMUXExtensionValidationError == .payloadTooLarge( + kind: "manifest", + actualBytes: payload.length, + maximumBytes: CMUXSidebarXPCCodec.maximumManifestPayloadBytes + ) + ) + } + } + + @Test + func testSidebarXPCCodecRejectsOversizedActionPayload() { + let payload = Data(repeating: 0x20, count: CMUXSidebarXPCCodec.maximumActionPayloadBytes + 1) as NSData + + do { + _ = try CMUXSidebarXPCCodec.decodeAction(payload) + Issue.record("Expected oversized action payload to be rejected") + } catch { + #expect( + error as? CMUXExtensionValidationError == .payloadTooLarge( + kind: "action", + actualBytes: payload.length, + maximumBytes: CMUXSidebarXPCCodec.maximumActionPayloadBytes + ) + ) + } + } + @Test func testManifestValidationRejectsUnsupportedAPIVersion() { let manifest = CMUXExtensionManifest( From 81a6344aa18d8ef761bb83ac91c03b3d2f211124 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Fri, 29 May 2026 19:45:49 -0500 Subject: [PATCH 20/44] Show sidebar extension details --- Resources/Localizable.xcstrings | 340 ++++++++++++++++++ ...MUXInstalledExtensionSidebarHostView.swift | 159 ++++++++ 2 files changed, 499 insertions(+) diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index 0b9056cf5c20..5e48018024c7 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -162683,6 +162683,176 @@ } } }, + "sidebar.extensions.details.bundle": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Bundle" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "バンドル" + } + } + } + }, + "sidebar.extensions.details.granted": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Granted" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "許可済み" + } + } + } + }, + "sidebar.extensions.details.help": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Show extension details" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "拡張機能の詳細を表示" + } + } + } + }, + "sidebar.extensions.details.manifest": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Manifest" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "マニフェスト" + } + } + } + }, + "sidebar.extensions.details.pending": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Pending" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "未許可" + } + } + } + }, + "sidebar.extensions.details.permissions": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Permissions" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "権限" + } + } + } + }, + "sidebar.extensions.details.runtime": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "ExtensionKit host, XPC connection" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "ExtensionKitホスト、XPC接続" + } + } + } + }, + "sidebar.extensions.details.status": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Status" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "状態" + } + } + } + }, + "sidebar.extensions.details.statusActive": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Hosted out of process" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "別プロセスでホスト中" + } + } + } + }, + "sidebar.extensions.details.statusWaiting": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Waiting for an enabled extension" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "有効な拡張機能を待機中" + } + } + } + }, "sidebar.extensions.manage": { "extractionState": "manual", "localizations": { @@ -162700,6 +162870,159 @@ } } }, + "sidebar.extensions.manage.short": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Manage" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "管理" + } + } + } + }, + "sidebar.extensions.scope.networkPorts": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Network ports" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "ネットワークポート" + } + } + } + }, + "sidebar.extensions.scope.notifications": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Notifications" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "通知" + } + } + } + }, + "sidebar.extensions.scope.pullRequests": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Pull requests" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "プルリクエスト" + } + } + } + }, + "sidebar.extensions.scope.workspaceMetadata": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Workspace metadata" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "ワークスペースメタデータ" + } + } + } + }, + "sidebar.extensions.scope.workspacePaths": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Workspace paths" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "ワークスペースパス" + } + } + } + }, + "sidebar.extensions.actionScope.closeWorkspace": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Close workspaces" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "ワークスペースを閉じる" + } + } + } + }, + "sidebar.extensions.actionScope.openURL": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Open URLs" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "URLを開く" + } + } + } + }, + "sidebar.extensions.actionScope.selectWorkspace": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Select workspaces" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "ワークスペースを選択" + } + } + } + }, "sidebar.extensions.unapproved.detail": { "extractionState": "manual", "localizations": { @@ -162733,6 +163056,23 @@ } } } + }, + "sidebar.extensions.useDefault.short": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Use Default" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "デフォルトを使用" + } + } + } } } } diff --git a/Sources/CMUXInstalledExtensionSidebarHostView.swift b/Sources/CMUXInstalledExtensionSidebarHostView.swift index 8b471d40dfc8..800fa8f48199 100644 --- a/Sources/CMUXInstalledExtensionSidebarHostView.swift +++ b/Sources/CMUXInstalledExtensionSidebarHostView.swift @@ -119,6 +119,7 @@ struct CMUXInstalledExtensionSidebarHostView: View { @State private var browserAnchorView: NSView? @State private var xpcHost = CMUXSidebarExtensionHostXPC() @State private var effectiveGrant: CMUXSidebarExtensionEffectiveGrant? + @State private var isShowingExtensionDetails = false var body: some View { Group { @@ -240,6 +241,17 @@ struct CMUXInstalledExtensionSidebarHostView: View { .foregroundStyle(.secondary) .help(String(localized: "sidebar.extensions.access.statusLimited.help", defaultValue: "This extension has limited access.")) } + Button { + isShowingExtensionDetails = true + } label: { + Image(systemName: "info.circle") + } + .buttonStyle(.plain) + .controlSize(.small) + .help(String(localized: "sidebar.extensions.details.help", defaultValue: "Show extension details")) + .popover(isPresented: $isShowingExtensionDetails, arrowEdge: .top) { + extensionDetailsPopover(activeIdentity: activeIdentity) + } Button { onUseDefaultSidebar() } label: { @@ -265,6 +277,123 @@ struct CMUXInstalledExtensionSidebarHostView: View { .background(Color(nsColor: .controlBackgroundColor).opacity(0.86)) } + private func extensionDetailsPopover(activeIdentity: AppExtensionIdentity?) -> some View { + VStack(alignment: .leading, spacing: 12) { + HStack(spacing: 8) { + Image(systemName: "puzzlepiece.extension") + .font(.system(size: 18, weight: .medium)) + VStack(alignment: .leading, spacing: 2) { + Text(activeIdentity?.localizedName ?? String(localized: "sidebar.provider.extensions.title", defaultValue: "Extension Sidebar")) + .font(.system(size: 13, weight: .semibold)) + .lineLimit(1) + Text(String(localized: "sidebar.extensions.details.runtime", defaultValue: "ExtensionKit host, XPC connection")) + .font(.system(size: 11)) + .foregroundStyle(.secondary) + } + } + + VStack(alignment: .leading, spacing: 6) { + detailRow( + title: String(localized: "sidebar.extensions.details.status", defaultValue: "Status"), + value: activeIdentity == nil + ? String(localized: "sidebar.extensions.details.statusWaiting", defaultValue: "Waiting for an enabled extension") + : String(localized: "sidebar.extensions.details.statusActive", defaultValue: "Hosted out of process") + ) + if let activeIdentity { + detailRow( + title: String(localized: "sidebar.extensions.details.bundle", defaultValue: "Bundle"), + value: activeIdentity.bundleIdentifier + ) + } + if let manifest = effectiveGrant?.manifest { + detailRow( + title: String(localized: "sidebar.extensions.details.manifest", defaultValue: "Manifest"), + value: "\(manifest.id) · API \(manifest.minimumAPIVersion.major).\(manifest.minimumAPIVersion.minor)" + ) + } + } + + if let effectiveGrant { + Divider() + permissionSection(effectiveGrant: effectiveGrant) + } + + Divider() + + HStack(spacing: 8) { + if let activeIdentity, effectiveGrant?.needsAdditionalApproval == true { + Button(String(localized: "sidebar.extensions.access.grant", defaultValue: "Grant Requested Access")) { + xpcHost.grantRequestedAccess(bundleIdentifier: activeIdentity.bundleIdentifier) + self.effectiveGrant = xpcHost.currentEffectiveGrant + xpcHost.sendSnapshotDidChange() + } + .controlSize(.small) + } + Button(String(localized: "sidebar.extensions.manage.short", defaultValue: "Manage")) { + isShowingExtensionDetails = false + presentExtensionBrowser() + } + .controlSize(.small) + Button(String(localized: "sidebar.extensions.useDefault.short", defaultValue: "Use Default")) { + isShowingExtensionDetails = false + onUseDefaultSidebar() + } + .controlSize(.small) + } + } + .padding(14) + .frame(width: 340, alignment: .leading) + } + + private func detailRow(title: String, value: String) -> some View { + HStack(alignment: .firstTextBaseline, spacing: 8) { + Text(title) + .font(.system(size: 11, weight: .medium)) + .foregroundStyle(.secondary) + .frame(width: 64, alignment: .leading) + Text(value) + .font(.system(size: 11)) + .foregroundStyle(.primary) + .lineLimit(2) + .textSelection(.enabled) + } + } + + private func permissionSection(effectiveGrant: CMUXSidebarExtensionEffectiveGrant) -> some View { + VStack(alignment: .leading, spacing: 8) { + Text(String(localized: "sidebar.extensions.details.permissions", defaultValue: "Permissions")) + .font(.system(size: 12, weight: .semibold)) + ForEach(effectiveGrant.manifest.requestedScopes, id: \.self) { scope in + permissionRow( + title: scope.displayName, + isGranted: effectiveGrant.readScopes.contains(scope) + ) + } + ForEach(effectiveGrant.manifest.requestedActionScopes, id: \.self) { scope in + permissionRow( + title: scope.displayName, + isGranted: effectiveGrant.actionScopes.contains(scope) + ) + } + } + } + + private func permissionRow(title: String, isGranted: Bool) -> some View { + HStack(spacing: 6) { + Image(systemName: isGranted ? "checkmark.circle.fill" : "circle") + .font(.system(size: 11, weight: .medium)) + .foregroundStyle(isGranted ? .green : .secondary) + Text(title) + .font(.system(size: 11)) + Spacer() + Text(isGranted + ? String(localized: "sidebar.extensions.details.granted", defaultValue: "Granted") + : String(localized: "sidebar.extensions.details.pending", defaultValue: "Pending")) + .font(.system(size: 10, weight: .medium)) + .foregroundStyle(.secondary) + } + } + @ViewBuilder private func extensionIdentityControl(activeIdentity: AppExtensionIdentity?) -> some View { if enabledIdentities.count > 1 { @@ -477,6 +606,36 @@ private final class MonitorContinuationBox: @unchecked Sendable { } } +private extension CMUXExtensionScope { + var displayName: String { + switch self { + case .workspaceMetadata: + return String(localized: "sidebar.extensions.scope.workspaceMetadata", defaultValue: "Workspace metadata") + case .workspacePaths: + return String(localized: "sidebar.extensions.scope.workspacePaths", defaultValue: "Workspace paths") + case .notifications: + return String(localized: "sidebar.extensions.scope.notifications", defaultValue: "Notifications") + case .networkPorts: + return String(localized: "sidebar.extensions.scope.networkPorts", defaultValue: "Network ports") + case .pullRequests: + return String(localized: "sidebar.extensions.scope.pullRequests", defaultValue: "Pull requests") + } + } +} + +private extension CMUXExtensionActionScope { + var displayName: String { + switch self { + case .selectWorkspace: + return String(localized: "sidebar.extensions.actionScope.selectWorkspace", defaultValue: "Select workspaces") + case .closeWorkspace: + return String(localized: "sidebar.extensions.actionScope.closeWorkspace", defaultValue: "Close workspaces") + case .openURL: + return String(localized: "sidebar.extensions.actionScope.openURL", defaultValue: "Open URLs") + } + } +} + @MainActor private final class CMUXSidebarExtensionHostXPC { private static let untrustedScopes: Set = [] From b587225d162e70f45436df884f266ad43b1b79b6 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Fri, 29 May 2026 19:48:58 -0500 Subject: [PATCH 21/44] Gate sidebar metadata behind scope grant --- .../Sidebar/CMUXSidebarSnapshot.swift | 8 +++++ .../CmuxExtensionKitTests.swift | 34 +++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarSnapshot.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarSnapshot.swift index 710bf9ee5ece..f1417e917b39 100644 --- a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarSnapshot.swift +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarSnapshot.swift @@ -23,6 +23,14 @@ public struct CMUXSidebarSnapshot: Codable, Equatable, Sendable { public func filtered(for scopes: some Sequence) -> CMUXSidebarSnapshot { let scopeSet = Set(scopes) + guard scopeSet.contains(.workspaceMetadata) else { + return CMUXSidebarSnapshot( + apiVersion: apiVersion, + sequence: sequence, + selectedWorkspaceID: nil, + workspaces: [] + ) + } return CMUXSidebarSnapshot( apiVersion: apiVersion, sequence: sequence, diff --git a/Packages/CmuxExtensionKit/Tests/CmuxExtensionKitTests/CmuxExtensionKitTests.swift b/Packages/CmuxExtensionKit/Tests/CmuxExtensionKitTests/CmuxExtensionKitTests.swift index 0195bec6c087..1bca42698dd4 100644 --- a/Packages/CmuxExtensionKit/Tests/CmuxExtensionKitTests/CmuxExtensionKitTests.swift +++ b/Packages/CmuxExtensionKit/Tests/CmuxExtensionKitTests/CmuxExtensionKitTests.swift @@ -104,6 +104,40 @@ struct CMUXExtensionKitTests { #expect(workspace.pullRequestURLs.isEmpty) } + @Test + func testSidebarSnapshotFilteringWithNoScopesRemovesWorkspaceMetadata() { + let workspaceID = UUID(uuidString: "55555555-5555-5555-5555-555555555555")! + let windowID = UUID(uuidString: "66666666-6666-6666-6666-666666666666")! + let snapshot = CMUXSidebarSnapshot( + sequence: 45, + windowID: windowID, + selectedWorkspaceID: workspaceID, + workspaces: [ + CMUXSidebarWorkspace( + id: workspaceID, + title: "Private Workspace", + detail: "Sensitive detail", + isPinned: true, + rootPath: "/Users/example/private", + projectRootPath: "/Users/example/private", + gitBranch: "secret", + unreadCount: 9, + latestNotification: "Sensitive notification", + listeningPorts: [8080], + pullRequestURLs: ["https://github.com/manaflow-ai/cmux/pull/4994"] + ), + ] + ) + + let filtered = snapshot.filtered(for: [CMUXExtensionScope]()) + + #expect(filtered.apiVersion == .sidebarV1) + #expect(filtered.sequence == 45) + #expect(filtered.windowID == nil) + #expect(filtered.selectedWorkspaceID == nil) + #expect(filtered.workspaces.isEmpty) + } + @Test func testSidebarXPCCodecRoundTripsSnapshotActionAndResult() throws { let workspaceID = UUID(uuidString: "33333333-3333-3333-3333-333333333333")! From d35232ef18c877076b9a0c80f662a216b18e3a7f Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Fri, 29 May 2026 19:53:05 -0500 Subject: [PATCH 22/44] Require grants for sidebar extension actions --- .../Manifest/CMUXExtensionManifest.swift | 4 ++-- .../CmuxExtensionKitTests.swift | 12 ++++++++++++ Sources/CMUXInstalledExtensionSidebarHostView.swift | 2 +- 3 files changed, 15 insertions(+), 3 deletions(-) diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Manifest/CMUXExtensionManifest.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Manifest/CMUXExtensionManifest.swift index f14744be4f0b..c1bd6a46ca7f 100644 --- a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Manifest/CMUXExtensionManifest.swift +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Manifest/CMUXExtensionManifest.swift @@ -14,7 +14,7 @@ public struct CMUXExtensionManifest: Codable, Equatable, Identifiable, Sendable kind: CMUXExtensionKind = .sidebar, minimumAPIVersion: CMUXExtensionAPIVersion = .sidebarV1, requestedScopes: [CMUXExtensionScope] = [.workspaceMetadata], - requestedActionScopes: [CMUXExtensionActionScope] = [.selectWorkspace] + requestedActionScopes: [CMUXExtensionActionScope] = [] ) { self.id = id self.displayName = displayName @@ -37,7 +37,7 @@ public struct CMUXExtensionManifest: Codable, Equatable, Identifiable, Sendable kind: kind, minimumAPIVersion: minimumAPIVersion, requestedScopes: requestedScopes, - requestedActionScopes: [.selectWorkspace] + requestedActionScopes: [] ) } diff --git a/Packages/CmuxExtensionKit/Tests/CmuxExtensionKitTests/CmuxExtensionKitTests.swift b/Packages/CmuxExtensionKit/Tests/CmuxExtensionKitTests/CmuxExtensionKitTests.swift index 1bca42698dd4..ece629d2757a 100644 --- a/Packages/CmuxExtensionKit/Tests/CmuxExtensionKitTests/CmuxExtensionKitTests.swift +++ b/Packages/CmuxExtensionKit/Tests/CmuxExtensionKitTests/CmuxExtensionKitTests.swift @@ -66,6 +66,18 @@ struct CMUXExtensionKitTests { try CMUXExtensionValidator.validateSidebarManifest(manifest) } + @Test + func testManifestInitializerDefaultsActionScopesToNone() throws { + let manifest = CMUXExtensionManifest( + id: "dev.example.sidebar", + displayName: "Example Sidebar" + ) + + #expect(manifest.requestedScopes == [.workspaceMetadata]) + #expect(manifest.requestedActionScopes.isEmpty) + try CMUXExtensionValidator.validateSidebarManifest(manifest) + } + @Test func testSidebarSnapshotFilteringRemovesUngrantedScopeData() throws { let workspaceID = UUID(uuidString: "44444444-4444-4444-4444-444444444444")! diff --git a/Sources/CMUXInstalledExtensionSidebarHostView.swift b/Sources/CMUXInstalledExtensionSidebarHostView.swift index 800fa8f48199..b7d703421e27 100644 --- a/Sources/CMUXInstalledExtensionSidebarHostView.swift +++ b/Sources/CMUXInstalledExtensionSidebarHostView.swift @@ -25,7 +25,7 @@ private struct CMUXSidebarExtensionEffectiveGrant: Equatable { private struct CMUXSidebarExtensionGrantStore { static let defaultReadScopes: Set = [.workspaceMetadata] - static let defaultActionScopes: Set = [.selectWorkspace] + static let defaultActionScopes: Set = [] private static let defaultsKey = "cmuxExtensionSidebar.grants.v1" From 5c52883d1cd6c131afef8d07bb6e129d83d38fa5 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Fri, 29 May 2026 19:56:31 -0500 Subject: [PATCH 23/44] Enforce sidebar XPC payload caps on encode --- .../Sidebar/CMUXSidebarXPC.swift | 14 +++- .../CmuxExtensionKitTests.swift | 74 +++++++++++++++++++ 2 files changed, 84 insertions(+), 4 deletions(-) diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarXPC.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarXPC.swift index a18f259892dd..9c796d391a0c 100644 --- a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarXPC.swift +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarXPC.swift @@ -17,7 +17,7 @@ public enum CMUXSidebarXPCCodec { public static let maximumActionResultPayloadBytes = 8 * 1024 public static func encodeSnapshot(_ snapshot: CMUXSidebarSnapshot) throws -> NSData { - try JSONEncoder().encode(snapshot) as NSData + try encode(snapshot, kind: "snapshot", maximumBytes: maximumSnapshotPayloadBytes) } public static func decodeSnapshot(_ payload: NSData) throws -> CMUXSidebarSnapshot { @@ -26,7 +26,7 @@ public enum CMUXSidebarXPCCodec { } public static func encodeManifest(_ manifest: CMUXExtensionManifest) throws -> NSData { - try JSONEncoder().encode(manifest) as NSData + try encode(manifest, kind: "manifest", maximumBytes: maximumManifestPayloadBytes) } public static func decodeManifest(_ payload: NSData) throws -> CMUXExtensionManifest { @@ -35,7 +35,7 @@ public enum CMUXSidebarXPCCodec { } public static func encodeAction(_ action: CMUXSidebarAction) throws -> NSData { - try JSONEncoder().encode(action) as NSData + try encode(action, kind: "action", maximumBytes: maximumActionPayloadBytes) } public static func decodeAction(_ payload: NSData) throws -> CMUXSidebarAction { @@ -44,7 +44,7 @@ public enum CMUXSidebarXPCCodec { } public static func encodeActionResult(_ result: CMUXExtensionActionResult) throws -> NSData { - try JSONEncoder().encode(result) as NSData + try encode(result, kind: "actionResult", maximumBytes: maximumActionResultPayloadBytes) } public static func decodeActionResult(_ payload: NSData) throws -> CMUXExtensionActionResult { @@ -61,4 +61,10 @@ public enum CMUXSidebarXPCCodec { ) } } + + private static func encode(_ value: T, kind: String, maximumBytes: Int) throws -> NSData { + let payload = try JSONEncoder().encode(value) as NSData + try validatePayloadSize(payload, kind: kind, maximumBytes: maximumBytes) + return payload + } } diff --git a/Packages/CmuxExtensionKit/Tests/CmuxExtensionKitTests/CmuxExtensionKitTests.swift b/Packages/CmuxExtensionKit/Tests/CmuxExtensionKitTests/CmuxExtensionKitTests.swift index ece629d2757a..a7fc7d649330 100644 --- a/Packages/CmuxExtensionKit/Tests/CmuxExtensionKitTests/CmuxExtensionKitTests.swift +++ b/Packages/CmuxExtensionKit/Tests/CmuxExtensionKitTests/CmuxExtensionKitTests.swift @@ -238,6 +238,80 @@ struct CMUXExtensionKitTests { } } + @Test + func testSidebarXPCCodecRejectsOversizedSnapshotOnEncodeAndDecode() { + let oversizedTitle = String(repeating: "x", count: CMUXSidebarXPCCodec.maximumSnapshotPayloadBytes) + let snapshot = CMUXSidebarSnapshot( + sequence: 46, + selectedWorkspaceID: nil, + workspaces: [ + CMUXSidebarWorkspace(id: UUID(), title: oversizedTitle), + ] + ) + + do { + _ = try CMUXSidebarXPCCodec.encodeSnapshot(snapshot) + Issue.record("Expected oversized snapshot payload to be rejected on encode") + } catch { + if case let CMUXExtensionValidationError.payloadTooLarge(kind, actualBytes, maximumBytes) = error { + #expect(kind == "snapshot") + #expect(actualBytes > maximumBytes) + #expect(maximumBytes == CMUXSidebarXPCCodec.maximumSnapshotPayloadBytes) + } else { + Issue.record("Unexpected error: \(error)") + } + } + + let payload = Data(repeating: 0x20, count: CMUXSidebarXPCCodec.maximumSnapshotPayloadBytes + 1) as NSData + do { + _ = try CMUXSidebarXPCCodec.decodeSnapshot(payload) + Issue.record("Expected oversized snapshot payload to be rejected on decode") + } catch { + #expect( + error as? CMUXExtensionValidationError == .payloadTooLarge( + kind: "snapshot", + actualBytes: payload.length, + maximumBytes: CMUXSidebarXPCCodec.maximumSnapshotPayloadBytes + ) + ) + } + } + + @Test + func testSidebarXPCCodecRejectsOversizedActionResultOnEncodeAndDecode() { + let result = CMUXExtensionActionResult( + accepted: false, + message: String(repeating: "x", count: CMUXSidebarXPCCodec.maximumActionResultPayloadBytes) + ) + + do { + _ = try CMUXSidebarXPCCodec.encodeActionResult(result) + Issue.record("Expected oversized action result payload to be rejected on encode") + } catch { + if case let CMUXExtensionValidationError.payloadTooLarge(kind, actualBytes, maximumBytes) = error { + #expect(kind == "actionResult") + #expect(actualBytes > maximumBytes) + #expect(maximumBytes == CMUXSidebarXPCCodec.maximumActionResultPayloadBytes) + } else { + Issue.record("Unexpected error: \(error)") + } + } + + let payload = Data(repeating: 0x20, count: CMUXSidebarXPCCodec.maximumActionResultPayloadBytes + 1) as NSData + do { + _ = try CMUXSidebarXPCCodec.decodeActionResult(payload) + Issue.record("Expected oversized action result payload to be rejected on decode") + } catch { + #expect( + error as? CMUXExtensionValidationError == .payloadTooLarge( + kind: "actionResult", + actualBytes: payload.length, + maximumBytes: CMUXSidebarXPCCodec.maximumActionResultPayloadBytes + ) + ) + } + } + @Test func testManifestValidationRejectsUnsupportedAPIVersion() { let manifest = CMUXExtensionManifest( From 00c64ba160eb2741896ae4df412bf05972a3b09e Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Fri, 29 May 2026 19:59:22 -0500 Subject: [PATCH 24/44] Make sidebar extension grants reversible --- ...MUXInstalledExtensionSidebarHostView.swift | 50 +++++++++++++------ 1 file changed, 34 insertions(+), 16 deletions(-) diff --git a/Sources/CMUXInstalledExtensionSidebarHostView.swift b/Sources/CMUXInstalledExtensionSidebarHostView.swift index b7d703421e27..b942cddc0335 100644 --- a/Sources/CMUXInstalledExtensionSidebarHostView.swift +++ b/Sources/CMUXInstalledExtensionSidebarHostView.swift @@ -21,6 +21,11 @@ private struct CMUXSidebarExtensionEffectiveGrant: Equatable { !readScopes.isSuperset(of: manifest.requestedScopes) || !actionScopes.isSuperset(of: manifest.requestedActionScopes) } + + var hasSensitiveAccess: Bool { + readScopes.contains { !CMUXSidebarExtensionGrantStore.defaultReadScopes.contains($0) } || + actionScopes.contains { !CMUXSidebarExtensionGrantStore.defaultActionScopes.contains($0) } + } } private struct CMUXSidebarExtensionGrantStore { @@ -320,25 +325,38 @@ struct CMUXInstalledExtensionSidebarHostView: View { Divider() - HStack(spacing: 8) { - if let activeIdentity, effectiveGrant?.needsAdditionalApproval == true { - Button(String(localized: "sidebar.extensions.access.grant", defaultValue: "Grant Requested Access")) { - xpcHost.grantRequestedAccess(bundleIdentifier: activeIdentity.bundleIdentifier) - self.effectiveGrant = xpcHost.currentEffectiveGrant - xpcHost.sendSnapshotDidChange() + VStack(alignment: .leading, spacing: 8) { + if let activeIdentity, let effectiveGrant { + HStack(spacing: 8) { + Button(String(localized: "sidebar.extensions.access.grant", defaultValue: "Grant Requested Access")) { + xpcHost.grantRequestedAccess(bundleIdentifier: activeIdentity.bundleIdentifier) + self.effectiveGrant = xpcHost.currentEffectiveGrant + xpcHost.sendSnapshotDidChange() + } + .controlSize(.small) + .disabled(!effectiveGrant.needsAdditionalApproval) + + Button(String(localized: "sidebar.extensions.access.keepLimited", defaultValue: "Keep Limited")) { + xpcHost.revokeSensitiveAccess(bundleIdentifier: activeIdentity.bundleIdentifier) + self.effectiveGrant = xpcHost.currentEffectiveGrant + xpcHost.sendSnapshotDidChange() + } + .controlSize(.small) + .disabled(!effectiveGrant.hasSensitiveAccess) } - .controlSize(.small) } - Button(String(localized: "sidebar.extensions.manage.short", defaultValue: "Manage")) { - isShowingExtensionDetails = false - presentExtensionBrowser() - } - .controlSize(.small) - Button(String(localized: "sidebar.extensions.useDefault.short", defaultValue: "Use Default")) { - isShowingExtensionDetails = false - onUseDefaultSidebar() + HStack(spacing: 8) { + Button(String(localized: "sidebar.extensions.manage.short", defaultValue: "Manage")) { + isShowingExtensionDetails = false + presentExtensionBrowser() + } + .controlSize(.small) + Button(String(localized: "sidebar.extensions.useDefault.short", defaultValue: "Use Default")) { + isShowingExtensionDetails = false + onUseDefaultSidebar() + } + .controlSize(.small) } - .controlSize(.small) } } .padding(14) From 6fbd721b419ab0e6dbed29ac7faf1ce2272f1f1a Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Fri, 29 May 2026 20:05:36 -0500 Subject: [PATCH 25/44] Show blocked sidebar extension state --- Resources/Localizable.xcstrings | 119 ++++++++++++++++++ ...MUXInstalledExtensionSidebarHostView.swift | 85 ++++++++++++- 2 files changed, 198 insertions(+), 6 deletions(-) diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index 5e48018024c7..d2f3601c9e57 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -162632,6 +162632,125 @@ } } }, + "sidebar.extensions.blocked.detail.failedManifest": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "CMUX could not load this extension's manifest. No workspace data or actions were shared." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "CMUXはこの拡張機能のマニフェストを読み込めませんでした。ワークスペースデータや操作は共有されていません。" + } + } + } + }, + "sidebar.extensions.blocked.detail.invalidManifest": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "CMUX rejected this extension's manifest. No workspace data or actions were shared." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "CMUXはこの拡張機能のマニフェストを拒否しました。ワークスペースデータや操作は共有されていません。" + } + } + } + }, + "sidebar.extensions.blocked.detail.missingManifest": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "CMUX did not receive a sidebar extension manifest, so no workspace data or actions were shared." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "CMUXはサイドバー拡張機能のマニフェストを受信しなかったため、ワークスペースデータや操作は共有されていません。" + } + } + } + }, + "sidebar.extensions.blocked.status.failedManifest": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Blocked, manifest unavailable" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "ブロック中、マニフェストを利用できません" + } + } + } + }, + "sidebar.extensions.blocked.status.invalidManifest": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Blocked, invalid manifest" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "ブロック中、マニフェストが無効です" + } + } + } + }, + "sidebar.extensions.blocked.status.missingManifest": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Blocked, missing manifest" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "ブロック中、マニフェストがありません" + } + } + } + }, + "sidebar.extensions.blocked.title": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Extension Blocked" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "拡張機能をブロックしました" + } + } + } + }, "sidebar.extensions.browser.title": { "extractionState": "manual", "localizations": { diff --git a/Sources/CMUXInstalledExtensionSidebarHostView.swift b/Sources/CMUXInstalledExtensionSidebarHostView.swift index b942cddc0335..2adaea2e4856 100644 --- a/Sources/CMUXInstalledExtensionSidebarHostView.swift +++ b/Sources/CMUXInstalledExtensionSidebarHostView.swift @@ -124,6 +124,7 @@ struct CMUXInstalledExtensionSidebarHostView: View { @State private var browserAnchorView: NSView? @State private var xpcHost = CMUXSidebarExtensionHostXPC() @State private var effectiveGrant: CMUXSidebarExtensionEffectiveGrant? + @State private var blockedManifestReason: String? @State private var isShowingExtensionDetails = false var body: some View { @@ -144,21 +145,30 @@ struct CMUXInstalledExtensionSidebarHostView: View { actionHandler: actionHandler, onGrantChanged: { grant in effectiveGrant = grant + }, + onManifestBlocked: { reason in + blockedManifestReason = reason } ) }, onDeactivation: { error in xpcHost.invalidate() effectiveGrant = nil + blockedManifestReason = nil if self.identity?.bundleIdentifier == identity.bundleIdentifier { self.identity = nil } errorText = error?.localizedDescription } ) - .id(identity.bundleIdentifier) - .accessibilityIdentifier("CMUXExtensionSidebarHostView") - .padding(.top, effectiveGrant?.needsAdditionalApproval == true ? 8 : 0) + .id(identity.bundleIdentifier) + .opacity(blockedManifestReason == nil ? 1 : 0) + .frame(height: blockedManifestReason == nil ? nil : 0) + .accessibilityIdentifier("CMUXExtensionSidebarHostView") + .padding(.top, effectiveGrant?.needsAdditionalApproval == true ? 8 : 0) + if let blockedManifestReason { + blockedExtensionView(reason: blockedManifestReason) + } } } else { VStack(alignment: .leading, spacing: 10) { @@ -215,6 +225,7 @@ struct CMUXInstalledExtensionSidebarHostView: View { } catch { identity = nil xpcHost.invalidate() + blockedManifestReason = nil isLoading = false errorText = String( localized: "sidebar.extensions.error", @@ -300,9 +311,9 @@ struct CMUXInstalledExtensionSidebarHostView: View { VStack(alignment: .leading, spacing: 6) { detailRow( title: String(localized: "sidebar.extensions.details.status", defaultValue: "Status"), - value: activeIdentity == nil + value: blockedManifestReason.map(blockedStatusText(reason:)) ?? (activeIdentity == nil ? String(localized: "sidebar.extensions.details.statusWaiting", defaultValue: "Waiting for an enabled extension") - : String(localized: "sidebar.extensions.details.statusActive", defaultValue: "Hosted out of process") + : String(localized: "sidebar.extensions.details.statusActive", defaultValue: "Hosted out of process")) ) if let activeIdentity { detailRow( @@ -321,6 +332,12 @@ struct CMUXInstalledExtensionSidebarHostView: View { if let effectiveGrant { Divider() permissionSection(effectiveGrant: effectiveGrant) + } else if let blockedManifestReason { + Divider() + Text(blockedDetailText(reason: blockedManifestReason)) + .font(.system(size: 11)) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) } Divider() @@ -363,6 +380,55 @@ struct CMUXInstalledExtensionSidebarHostView: View { .frame(width: 340, alignment: .leading) } + private func blockedExtensionView(reason: String) -> some View { + VStack(alignment: .leading, spacing: 8) { + Image(systemName: "exclamationmark.triangle") + .font(.system(size: 20, weight: .regular)) + .foregroundStyle(.secondary) + Text(String(localized: "sidebar.extensions.blocked.title", defaultValue: "Extension Blocked")) + .font(.system(size: 13, weight: .semibold)) + Text(blockedDetailText(reason: reason)) + .font(.system(size: 12)) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + Button { + presentExtensionBrowser() + } label: { + Label( + String(localized: "sidebar.extensions.manage", defaultValue: "Manage Sidebar Extensions..."), + systemImage: "puzzlepiece.extension" + ) + } + .controlSize(.small) + } + .padding(.horizontal, 14) + .padding(.top, 14) + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) + .accessibilityIdentifier("CMUXExtensionSidebarBlockedState") + } + + private func blockedStatusText(reason: String) -> String { + switch reason { + case "missingManifest": + return String(localized: "sidebar.extensions.blocked.status.missingManifest", defaultValue: "Blocked, missing manifest") + case "invalidManifest": + return String(localized: "sidebar.extensions.blocked.status.invalidManifest", defaultValue: "Blocked, invalid manifest") + default: + return String(localized: "sidebar.extensions.blocked.status.failedManifest", defaultValue: "Blocked, manifest unavailable") + } + } + + private func blockedDetailText(reason: String) -> String { + switch reason { + case "missingManifest": + return String(localized: "sidebar.extensions.blocked.detail.missingManifest", defaultValue: "CMUX did not receive a sidebar extension manifest, so no workspace data or actions were shared.") + case "invalidManifest": + return String(localized: "sidebar.extensions.blocked.detail.invalidManifest", defaultValue: "CMUX rejected this extension's manifest. No workspace data or actions were shared.") + default: + return String(localized: "sidebar.extensions.blocked.detail.failedManifest", defaultValue: "CMUX could not load this extension's manifest. No workspace data or actions were shared.") + } + } + private func detailRow(title: String, value: String) -> some View { HStack(alignment: .firstTextBaseline, spacing: 8) { Text(title) @@ -670,6 +736,7 @@ private final class CMUXSidebarExtensionHostXPC { private var bundleIdentifier: String? private var currentManifest: CMUXExtensionManifest? private var onGrantChanged: ((CMUXSidebarExtensionEffectiveGrant?) -> Void)? + private var onManifestBlocked: ((String?) -> Void)? private let grantStore = CMUXSidebarExtensionGrantStore() var currentEffectiveGrant: CMUXSidebarExtensionEffectiveGrant? { @@ -692,7 +759,8 @@ private final class CMUXSidebarExtensionHostXPC { bundleIdentifier: String, snapshotProvider: @escaping @MainActor () -> CMUXSidebarSnapshot, actionHandler: @escaping @MainActor (CMUXSidebarAction) -> CMUXExtensionActionResult, - onGrantChanged: @escaping @MainActor (CMUXSidebarExtensionEffectiveGrant?) -> Void + onGrantChanged: @escaping @MainActor (CMUXSidebarExtensionEffectiveGrant?) -> Void, + onManifestBlocked: @escaping @MainActor (String?) -> Void ) { invalidate() connectionGeneration += 1 @@ -727,6 +795,7 @@ private final class CMUXSidebarExtensionHostXPC { self.bundleIdentifier = bundleIdentifier self.currentManifest = nil self.onGrantChanged = onGrantChanged + self.onManifestBlocked = onManifestBlocked self.allowedScopes = Self.untrustedScopes self.allowedActionScopes = Self.untrustedActionScopes self.extensionProxy = connection.remoteObjectProxy as? CMUXSidebarExtensionXPC @@ -768,6 +837,8 @@ private final class CMUXSidebarExtensionHostXPC { currentManifest = nil onGrantChanged?(nil) onGrantChanged = nil + onManifestBlocked?(nil) + onManifestBlocked = nil } private func requestManifestThenSendInitialSnapshot(generation: UInt64) { @@ -829,6 +900,7 @@ private final class CMUXSidebarExtensionHostXPC { let effectiveGrant = grantStore.effectiveGrant(bundleIdentifier: bundleIdentifier, manifest: manifest) allowedScopes = effectiveGrant.readScopes allowedActionScopes = effectiveGrant.actionScopes + onManifestBlocked?(nil) onGrantChanged?(effectiveGrant) } @@ -867,6 +939,7 @@ private final class CMUXSidebarExtensionHostXPC { allowedActionScopes = Self.untrustedActionScopes currentManifest = nil onGrantChanged?(nil) + onManifestBlocked?(reason) #if DEBUG cmuxDebugLog("extension.sidebar.manifest.blocked reason=\(reason)") #endif From 2594ca9e8d6b816a1fd38107d2193684b9d93063 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Fri, 29 May 2026 20:08:32 -0500 Subject: [PATCH 26/44] Tear down sidebar extension host explicitly --- .../Hosting/CMUXSidebarExtensionHostView.swift | 18 +++++++++++++++--- ...CMUXInstalledExtensionSidebarHostView.swift | 6 ++++++ 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Hosting/CMUXSidebarExtensionHostView.swift b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Hosting/CMUXSidebarExtensionHostView.swift index 397993a730be..896a50053565 100644 --- a/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Hosting/CMUXSidebarExtensionHostView.swift +++ b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Hosting/CMUXSidebarExtensionHostView.swift @@ -13,13 +13,16 @@ public struct CMUXSidebarExtensionHostView: NSViewControllerRepresentable { fileprivate var currentKey: HostConfigurationKey? private let onConnection: (@MainActor (NSXPCConnection) -> Void)? private let onDeactivation: (@MainActor (Error?) -> Void)? + private let onTeardown: (@MainActor () -> Void)? fileprivate init( onConnection: (@MainActor (NSXPCConnection) -> Void)?, - onDeactivation: (@MainActor (Error?) -> Void)? + onDeactivation: (@MainActor (Error?) -> Void)?, + onTeardown: (@MainActor () -> Void)? ) { self.onConnection = onConnection self.onDeactivation = onDeactivation + self.onTeardown = onTeardown } public func hostViewControllerDidActivate(_ viewController: EXHostViewController) { @@ -34,6 +37,11 @@ public struct CMUXSidebarExtensionHostView: NSViewControllerRepresentable { public func hostViewControllerWillDeactivate(_ viewController: EXHostViewController, error: (any Error)?) { onDeactivation?(error) } + + @MainActor + fileprivate func teardown() { + onTeardown?() + } } fileprivate struct HostConfigurationKey: Equatable { @@ -45,6 +53,7 @@ public struct CMUXSidebarExtensionHostView: NSViewControllerRepresentable { private let sceneID: String private let onConnection: (@MainActor (NSXPCConnection) -> Void)? private let onDeactivation: (@MainActor (Error?) -> Void)? + private let onTeardown: (@MainActor () -> Void)? /// Creates a sidebar extension host view. /// - Parameters: @@ -54,18 +63,20 @@ public struct CMUXSidebarExtensionHostView: NSViewControllerRepresentable { identity: AppExtensionIdentity, sceneID: String = CMUXSidebarExtensionPoint.defaultSceneID, onConnection: (@MainActor (NSXPCConnection) -> Void)? = nil, - onDeactivation: (@MainActor (Error?) -> Void)? = nil + onDeactivation: (@MainActor (Error?) -> Void)? = nil, + onTeardown: (@MainActor () -> Void)? = nil ) { self.identity = identity self.sceneID = sceneID self.onConnection = onConnection self.onDeactivation = onDeactivation + self.onTeardown = onTeardown } /// Creates the configuration-tracking coordinator. /// - Returns: Coordinator for the hosted extension configuration. public func makeCoordinator() -> Coordinator { - Coordinator(onConnection: onConnection, onDeactivation: onDeactivation) + Coordinator(onConnection: onConnection, onDeactivation: onDeactivation, onTeardown: onTeardown) } /// Creates the ExtensionKit host view controller. @@ -96,6 +107,7 @@ public struct CMUXSidebarExtensionHostView: NSViewControllerRepresentable { } public static func dismantleNSViewController(_ viewController: EXHostViewController, coordinator: Coordinator) { + coordinator.teardown() coordinator.currentKey = nil viewController.delegate = nil viewController.configuration = nil diff --git a/Sources/CMUXInstalledExtensionSidebarHostView.swift b/Sources/CMUXInstalledExtensionSidebarHostView.swift index 2adaea2e4856..fb9fe1c61849 100644 --- a/Sources/CMUXInstalledExtensionSidebarHostView.swift +++ b/Sources/CMUXInstalledExtensionSidebarHostView.swift @@ -159,6 +159,9 @@ struct CMUXInstalledExtensionSidebarHostView: View { self.identity = nil } errorText = error?.localizedDescription + }, + onTeardown: { + xpcHost.invalidate() } ) .id(identity.bundleIdentifier) @@ -212,6 +215,9 @@ struct CMUXInstalledExtensionSidebarHostView: View { .onChange(of: snapshotProvider().sequence) { _, _ in xpcHost.sendSnapshotDidChange() } + .onDisappear { + xpcHost.invalidate() + } } private func observeExtensionAvailability() async { From 4fa8f62ce9625a01c01dffa64c18f64f1d5baa5c Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Fri, 29 May 2026 20:12:48 -0500 Subject: [PATCH 27/44] Add sidebar extension empty-state actions --- Resources/Localizable.xcstrings | 34 +++++++++ ...MUXInstalledExtensionSidebarHostView.swift | 72 +++++++++++++++++-- 2 files changed, 101 insertions(+), 5 deletions(-) diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index d2f3601c9e57..b8ec2f805557 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -162768,6 +162768,23 @@ } } }, + "sidebar.extensions.choose.action": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Choose Extension" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "拡張機能を選択" + } + } + } + }, "sidebar.extensions.choose.detail": { "extractionState": "manual", "localizations": { @@ -162785,6 +162802,23 @@ } } }, + "sidebar.extensions.choose.title": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Choose a sidebar extension" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "サイドバー拡張機能を選択" + } + } + } + }, "sidebar.extensions.disabled.detail": { "extractionState": "manual", "localizations": { diff --git a/Sources/CMUXInstalledExtensionSidebarHostView.swift b/Sources/CMUXInstalledExtensionSidebarHostView.swift index fb9fe1c61849..9f09d594d2e8 100644 --- a/Sources/CMUXInstalledExtensionSidebarHostView.swift +++ b/Sources/CMUXInstalledExtensionSidebarHostView.swift @@ -186,13 +186,10 @@ struct CMUXInstalledExtensionSidebarHostView: View { Image(systemName: "puzzlepiece.extension") .font(.system(size: 22, weight: .regular)) .foregroundStyle(.secondary) - Text(String(localized: "sidebar.extensions.empty.title", defaultValue: "No sidebar extension enabled")) + Text(emptyStateTitle) .font(.system(size: 13, weight: .medium)) .foregroundStyle(.primary) - Text(errorText ?? String( - localized: "sidebar.extensions.empty.detail", - defaultValue: "Install and enable a CMUX sidebar extension to show it here." - )) + Text(errorText ?? emptyStateDetail) .font(.system(size: 12)) .foregroundStyle(.secondary) .fixedSize(horizontal: false, vertical: true) @@ -202,6 +199,7 @@ struct CMUXInstalledExtensionSidebarHostView: View { .foregroundStyle(.secondary) .fixedSize(horizontal: false, vertical: true) } + extensionEmptyActions() } } .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) @@ -240,6 +238,26 @@ struct CMUXInstalledExtensionSidebarHostView: View { } } + private var emptyStateTitle: String { + if enabledIdentities.count > 1 { + return String(localized: "sidebar.extensions.choose.title", defaultValue: "Choose a sidebar extension") + } + return String(localized: "sidebar.extensions.empty.title", defaultValue: "No sidebar extension enabled") + } + + private var emptyStateDetail: String { + if enabledIdentities.count > 1 { + return String( + localized: "sidebar.extensions.choose.detail", + defaultValue: "Choose which enabled extension should replace the sidebar." + ) + } + return String( + localized: "sidebar.extensions.empty.detail", + defaultValue: "Install and enable a CMUX sidebar extension to show it here." + ) + } + private var extensionAvailabilityDetail: String { if unapprovedExtensionCount > 0 { return String( @@ -253,6 +271,50 @@ struct CMUXInstalledExtensionSidebarHostView: View { ) } + @ViewBuilder + private func extensionEmptyActions() -> some View { + HStack(spacing: 8) { + if enabledIdentities.count > 1 { + Menu { + ForEach(enabledIdentities, id: \.bundleIdentifier) { enabledIdentity in + Button { + selectExtension(enabledIdentity) + } label: { + Label(enabledIdentity.localizedName, systemImage: "puzzlepiece.extension") + } + } + } label: { + Label( + String(localized: "sidebar.extensions.choose.action", defaultValue: "Choose Extension"), + systemImage: "puzzlepiece.extension" + ) + } + .menuStyle(.button) + .controlSize(.small) + } + + Button { + presentExtensionBrowser() + } label: { + Label( + String(localized: "sidebar.extensions.manage.short", defaultValue: "Manage"), + systemImage: "puzzlepiece.extension" + ) + } + .controlSize(.small) + + Button { + onUseDefaultSidebar() + } label: { + Label( + String(localized: "sidebar.extensions.useDefault.short", defaultValue: "Use Default"), + systemImage: "sidebar.left" + ) + } + .controlSize(.small) + } + } + private func extensionControlStrip(activeIdentity: AppExtensionIdentity?) -> some View { HStack(spacing: 8) { extensionIdentityControl(activeIdentity: activeIdentity) From aead7eba0ecbe8c12462addf8ae15f4df43be7b9 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Fri, 29 May 2026 20:15:18 -0500 Subject: [PATCH 28/44] Show interrupted sidebar extension state --- Resources/Localizable.xcstrings | 34 +++++++++++++++++++ ...MUXInstalledExtensionSidebarHostView.swift | 6 ++++ 2 files changed, 40 insertions(+) diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index b8ec2f805557..9c5a704d7d23 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -162649,6 +162649,23 @@ } } }, + "sidebar.extensions.blocked.detail.connectionInterrupted": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "CMUX lost the extension's XPC connection. No workspace data or actions are being shared." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "CMUXは拡張機能のXPC接続を失いました。ワークスペースデータや操作は共有されていません。" + } + } + } + }, "sidebar.extensions.blocked.detail.invalidManifest": { "extractionState": "manual", "localizations": { @@ -162683,6 +162700,23 @@ } } }, + "sidebar.extensions.blocked.status.connectionInterrupted": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Blocked, connection interrupted" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "ブロック中、接続が中断されました" + } + } + } + }, "sidebar.extensions.blocked.status.failedManifest": { "extractionState": "manual", "localizations": { diff --git a/Sources/CMUXInstalledExtensionSidebarHostView.swift b/Sources/CMUXInstalledExtensionSidebarHostView.swift index 9f09d594d2e8..8be39c09c377 100644 --- a/Sources/CMUXInstalledExtensionSidebarHostView.swift +++ b/Sources/CMUXInstalledExtensionSidebarHostView.swift @@ -477,6 +477,8 @@ struct CMUXInstalledExtensionSidebarHostView: View { private func blockedStatusText(reason: String) -> String { switch reason { + case "connectionInterrupted": + return String(localized: "sidebar.extensions.blocked.status.connectionInterrupted", defaultValue: "Blocked, connection interrupted") case "missingManifest": return String(localized: "sidebar.extensions.blocked.status.missingManifest", defaultValue: "Blocked, missing manifest") case "invalidManifest": @@ -488,6 +490,8 @@ struct CMUXInstalledExtensionSidebarHostView: View { private func blockedDetailText(reason: String) -> String { switch reason { + case "connectionInterrupted": + return String(localized: "sidebar.extensions.blocked.detail.connectionInterrupted", defaultValue: "CMUX lost the extension's XPC connection. No workspace data or actions are being shared.") case "missingManifest": return String(localized: "sidebar.extensions.blocked.detail.missingManifest", defaultValue: "CMUX did not receive a sidebar extension manifest, so no workspace data or actions were shared.") case "invalidManifest": @@ -892,6 +896,8 @@ private final class CMUXSidebarExtensionHostXPC { private func clearProxy(ifCurrentGeneration generation: UInt64) { guard connectionGeneration == generation else { return } extensionProxy = nil + blockUntrustedExtension(reason: "connectionInterrupted") + updateExportedSnapshotFilter() } private func clearConnection(ifCurrentGeneration generation: UInt64) { From 3e906adf95279faf59402b416652c8134f56f196 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Fri, 29 May 2026 20:19:50 -0500 Subject: [PATCH 29/44] Add sidebar extension author connection helper --- .../Connection/SidebarConnectionModel.swift | 156 ++------------- .../CMUXSidebarExtensionConnection.swift | 181 ++++++++++++++++++ 2 files changed, 201 insertions(+), 136 deletions(-) create mode 100644 Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarExtensionConnection.swift diff --git a/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/Connection/SidebarConnectionModel.swift b/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/Connection/SidebarConnectionModel.swift index ce0f24dfd7e0..2b1e46cdd438 100644 --- a/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/Connection/SidebarConnectionModel.swift +++ b/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/Connection/SidebarConnectionModel.swift @@ -25,49 +25,20 @@ final class SidebarConnectionModel: @unchecked Sendable { private(set) var errorText: String? @ObservationIgnored - private var connection: NSXPCConnection? - - @ObservationIgnored - private var connectionGeneration: UInt64 = 0 - - @ObservationIgnored - private var host: CMUXSidebarHostXPC? + private lazy var extensionConnection = CMUXSidebarExtensionConnection( + manifest: Self.manifest, + onSnapshot: { [weak self] snapshot in + self?.snapshot = snapshot + }, + onError: { [weak self] message in + self?.errorText = message.map(Self.localizedHostMessage) + } + ) private init() {} func accept(connection: NSXPCConnection) -> Bool { - self.connection?.invalidate() - connectionGeneration += 1 - let generation = connectionGeneration - connection.exportedInterface = NSXPCInterface(with: CMUXSidebarExtensionXPC.self) - connection.exportedObject = SidebarExtensionXPCReceiver(model: self, generation: generation) - connection.remoteObjectInterface = NSXPCInterface(with: CMUXSidebarHostXPC.self) - connection.invalidationHandler = { [weak self] in - guard let model = self else { return } - Task { @MainActor [model, generation] in - model.clearConnection(ifCurrentGeneration: generation) - } - } - connection.interruptionHandler = { [weak self] in - guard let model = self else { return } - Task { @MainActor [model, generation] in - guard model.connectionGeneration == generation else { return } - model.host = nil - model.errorText = String(localized: "sampleSidebar.waitingForHost", defaultValue: "Waiting for cmux") - } - } - self.connection = connection - host = connection.remoteObjectProxyWithErrorHandler { [weak self, generation] error in - guard let model = self else { return } - let message = error.localizedDescription - Task { @MainActor [model, generation] in - guard model.connectionGeneration == generation else { return } - model.errorText = message - } - } as? CMUXSidebarHostXPC - connection.resume() - refreshSnapshot() - return true + extensionConnection.accept(connection) } var insights: SidebarInsightModel? { @@ -75,108 +46,21 @@ final class SidebarConnectionModel: @unchecked Sendable { } func refreshSnapshot() { - guard let host else { - errorText = String(localized: "sampleSidebar.waitingForHost", defaultValue: "Waiting for cmux") - return - } - let generation = connectionGeneration - host.requestSidebarSnapshot { [weak self] payload, error in - guard let model = self else { return } - let payload = payload.map { $0 as Data } - let error = error.map { String($0) } - Task { @MainActor [model, generation] in - guard model.connectionGeneration == generation else { return } - if let error { - model.errorText = error - return - } - guard let payload else { - model.errorText = String(localized: "sampleSidebar.emptySnapshot", defaultValue: "cmux did not send a workspace snapshot") - return - } - do { - model.snapshot = try CMUXSidebarXPCCodec.decodeSnapshot(payload as NSData) - model.errorText = nil - } catch { - model.errorText = error.localizedDescription - } - } - } + extensionConnection.refreshSnapshot() } func selectWorkspace(_ id: UUID) { - send(.selectWorkspace(id)) - } - - private func send(_ action: CMUXSidebarAction) { - guard let host else { return } - let generation = connectionGeneration - do { - let payload = try CMUXSidebarXPCCodec.encodeAction(action) - host.performSidebarAction(payload) { [weak self] resultPayload, error in - guard let model = self else { return } - let resultPayload = resultPayload.map { $0 as Data } - let error = error.map { String($0) } - Task { @MainActor [model, generation] in - guard model.connectionGeneration == generation else { return } - if let error { - model.errorText = error - return - } - if let resultPayload { - let result = try? CMUXSidebarXPCCodec.decodeActionResult(resultPayload as NSData) - if result?.accepted == false { - model.errorText = result?.message - } - } - } - } - } catch { - errorText = error.localizedDescription - } - } - - fileprivate func receive(snapshot payload: Data, ifCurrentGeneration generation: UInt64) { - guard connectionGeneration == generation else { return } - do { - snapshot = try CMUXSidebarXPCCodec.decodeSnapshot(payload as NSData) - errorText = nil - } catch { - errorText = error.localizedDescription - } - } - - private func clearConnection(ifCurrentGeneration generation: UInt64) { - guard connectionGeneration == generation else { return } - connection = nil - host = nil - errorText = String(localized: "sampleSidebar.waitingForHost", defaultValue: "Waiting for cmux") - } -} - -private final class SidebarExtensionXPCReceiver: NSObject, CMUXSidebarExtensionXPC { - weak var model: SidebarConnectionModel? - let generation: UInt64 - - init(model: SidebarConnectionModel, generation: UInt64) { - self.model = model - self.generation = generation - } - - func sidebarSnapshotDidChange(_ payload: NSData) { - let payload = payload as Data - let model = model - let generation = generation - Task { @MainActor in - model?.receive(snapshot: payload, ifCurrentGeneration: generation) - } + extensionConnection.perform(.selectWorkspace(id)) } - func requestExtensionManifest(reply: @escaping (NSData?, NSString?) -> Void) { - do { - reply(try CMUXSidebarXPCCodec.encodeManifest(SidebarConnectionModel.manifest), nil) - } catch { - reply(nil, error.localizedDescription as NSString) + private static func localizedHostMessage(_ message: String) -> String { + switch message { + case "Waiting for cmux": + return String(localized: "sampleSidebar.waitingForHost", defaultValue: "Waiting for cmux") + case "cmux did not send a workspace snapshot": + return String(localized: "sampleSidebar.emptySnapshot", defaultValue: "cmux did not send a workspace snapshot") + default: + return message } } } diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarExtensionConnection.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarExtensionConnection.swift new file mode 100644 index 000000000000..aae064c1875a --- /dev/null +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarExtensionConnection.swift @@ -0,0 +1,181 @@ +import Foundation + +public final class CMUXSidebarExtensionConnection: @unchecked Sendable { + public typealias SnapshotHandler = @MainActor (CMUXSidebarSnapshot) -> Void + public typealias ErrorHandler = @MainActor (String?) -> Void + public typealias ActionReplyHandler = @MainActor (CMUXExtensionActionResult) -> Void + + public let manifest: CMUXExtensionManifest + + private let onSnapshot: SnapshotHandler + private let onError: ErrorHandler + private var connection: NSXPCConnection? + private var host: CMUXSidebarHostXPC? + private var connectionGeneration: UInt64 = 0 + + public init( + manifest: CMUXExtensionManifest, + onSnapshot: @escaping SnapshotHandler, + onError: @escaping ErrorHandler = { _ in } + ) { + self.manifest = manifest + self.onSnapshot = onSnapshot + self.onError = onError + } + + @discardableResult + public func accept(_ connection: NSXPCConnection) -> Bool { + self.connection?.invalidate() + connectionGeneration += 1 + let generation = connectionGeneration + connection.exportedInterface = NSXPCInterface(with: CMUXSidebarExtensionXPC.self) + connection.exportedObject = CMUXSidebarExtensionXPCReceiver( + manifest: manifest, + receiveSnapshot: { [weak self] payload, receiverGeneration in + self?.receive(snapshot: payload, ifCurrentGeneration: receiverGeneration) + }, + generation: generation + ) + connection.remoteObjectInterface = NSXPCInterface(with: CMUXSidebarHostXPC.self) + connection.invalidationHandler = { [weak self, generation] in + self?.clearConnection(ifCurrentGeneration: generation) + } + connection.interruptionHandler = { [weak self, generation] in + self?.markInterrupted(ifCurrentGeneration: generation) + } + self.connection = connection + host = connection.remoteObjectProxyWithErrorHandler { [weak self, generation] error in + self?.report(error.localizedDescription, ifCurrentGeneration: generation) + } as? CMUXSidebarHostXPC + connection.resume() + refreshSnapshot() + return true + } + + public func refreshSnapshot() { + guard let host else { + report("Waiting for cmux", ifCurrentGeneration: connectionGeneration) + return + } + let generation = connectionGeneration + host.requestSidebarSnapshot { [weak self] payload, error in + guard let self else { return } + if let error { + self.report(String(error), ifCurrentGeneration: generation) + return + } + guard let payload else { + self.report("cmux did not send a workspace snapshot", ifCurrentGeneration: generation) + return + } + self.receive(snapshot: payload, ifCurrentGeneration: generation) + } + } + + public func perform( + _ action: CMUXSidebarAction, + reply: @escaping ActionReplyHandler = { _ in } + ) { + guard let host else { + report("Waiting for cmux", ifCurrentGeneration: connectionGeneration) + return + } + let generation = connectionGeneration + do { + let payload = try CMUXSidebarXPCCodec.encodeAction(action) + host.performSidebarAction(payload) { [weak self] resultPayload, error in + guard let self else { return } + if let error { + self.report(String(error), ifCurrentGeneration: generation) + return + } + guard let resultPayload else { + self.report("cmux did not send an action result", ifCurrentGeneration: generation) + return + } + do { + let result = try CMUXSidebarXPCCodec.decodeActionResult(resultPayload) + Task { @MainActor [reply] in + reply(result) + } + if result.accepted { + self.report(nil, ifCurrentGeneration: generation) + } else { + self.report(result.message, ifCurrentGeneration: generation) + } + } catch { + self.report(error.localizedDescription, ifCurrentGeneration: generation) + } + } + } catch { + report(error.localizedDescription, ifCurrentGeneration: generation) + } + } + + public func invalidate() { + connectionGeneration += 1 + connection?.invalidate() + clearConnection(ifCurrentGeneration: connectionGeneration) + } + + private func receive(snapshot payload: NSData, ifCurrentGeneration generation: UInt64) { + guard connectionGeneration == generation else { return } + do { + let snapshot = try CMUXSidebarXPCCodec.decodeSnapshot(payload) + Task { @MainActor [onSnapshot, onError] in + onSnapshot(snapshot) + onError(nil) + } + } catch { + report(error.localizedDescription, ifCurrentGeneration: generation) + } + } + + private func report(_ message: String?, ifCurrentGeneration generation: UInt64) { + guard connectionGeneration == generation else { return } + Task { @MainActor [onError] in + onError(message) + } + } + + private func markInterrupted(ifCurrentGeneration generation: UInt64) { + guard connectionGeneration == generation else { return } + host = nil + report("Waiting for cmux", ifCurrentGeneration: generation) + } + + private func clearConnection(ifCurrentGeneration generation: UInt64) { + guard connectionGeneration == generation else { return } + connection = nil + host = nil + report("Waiting for cmux", ifCurrentGeneration: generation) + } +} + +private final class CMUXSidebarExtensionXPCReceiver: NSObject, CMUXSidebarExtensionXPC { + private let manifest: CMUXExtensionManifest + private let receiveSnapshot: @Sendable (NSData, UInt64) -> Void + private let generation: UInt64 + + init( + manifest: CMUXExtensionManifest, + receiveSnapshot: @escaping @Sendable (NSData, UInt64) -> Void, + generation: UInt64 + ) { + self.manifest = manifest + self.receiveSnapshot = receiveSnapshot + self.generation = generation + } + + func requestExtensionManifest(reply: @escaping (NSData?, NSString?) -> Void) { + do { + reply(try CMUXSidebarXPCCodec.encodeManifest(manifest), nil) + } catch { + reply(nil, error.localizedDescription as NSString) + } + } + + func sidebarSnapshotDidChange(_ payload: NSData) { + receiveSnapshot(payload, generation) + } +} From 56270dc4cd0b72888e606ae639a7709f003edae8 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Fri, 29 May 2026 20:22:25 -0500 Subject: [PATCH 30/44] Clarify sidebar extension permission grant --- Resources/Localizable.xcstrings | 136 ++++++++++++++++++ ...MUXInstalledExtensionSidebarHostView.swift | 64 ++++++++- 2 files changed, 193 insertions(+), 7 deletions(-) diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index 9c5a704d7d23..001ec0278cd9 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -163210,6 +163210,142 @@ } } }, + "sidebar.extensions.permission.closeWorkspace.detail": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Close workspaces from the extension" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "拡張機能からワークスペースを閉じます" + } + } + } + }, + "sidebar.extensions.permission.networkPorts.detail": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Read listening ports for each workspace" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "各ワークスペースの待ち受けポートを読み取ります" + } + } + } + }, + "sidebar.extensions.permission.notifications.detail": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Read latest workspace notifications" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "最新のワークスペース通知を読み取ります" + } + } + } + }, + "sidebar.extensions.permission.openURL.detail": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Open links from the extension" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "拡張機能からリンクを開きます" + } + } + } + }, + "sidebar.extensions.permission.pullRequests.detail": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Read pull request links associated with workspaces" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "ワークスペースに関連するプルリクエストリンクを読み取ります" + } + } + } + }, + "sidebar.extensions.permission.selectWorkspace.detail": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Select a workspace when you click in the extension" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "拡張機能内でクリックしたときにワークスペースを選択します" + } + } + } + }, + "sidebar.extensions.permission.workspaceMetadata.detail": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Read workspace names, branches, unread counts, and selection" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "ワークスペース名、ブランチ、未読数、選択状態を読み取ります" + } + } + } + }, + "sidebar.extensions.permission.workspacePaths.detail": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Read local workspace and project paths" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "ローカルのワークスペースとプロジェクトのパスを読み取ります" + } + } + } + }, "sidebar.extensions.unapproved.detail": { "extractionState": "manual", "localizations": { diff --git a/Sources/CMUXInstalledExtensionSidebarHostView.swift b/Sources/CMUXInstalledExtensionSidebarHostView.swift index 8be39c09c377..beb4c2aec7f3 100644 --- a/Sources/CMUXInstalledExtensionSidebarHostView.swift +++ b/Sources/CMUXInstalledExtensionSidebarHostView.swift @@ -610,6 +610,15 @@ struct CMUXInstalledExtensionSidebarHostView: View { .font(.system(size: 11)) .foregroundStyle(.secondary) .fixedSize(horizontal: false, vertical: true) + VStack(alignment: .leading, spacing: 4) { + ForEach(pendingPermissionDescriptions(effectiveGrant: effectiveGrant), id: \.self) { description in + Label(description, systemImage: "circle") + .font(.system(size: 11)) + .foregroundStyle(.secondary) + .labelStyle(.titleAndIcon) + } + } + .padding(.top, 2) HStack(spacing: 8) { Button { xpcHost.grantRequestedAccess(bundleIdentifier: identity.bundleIdentifier) @@ -619,14 +628,16 @@ struct CMUXInstalledExtensionSidebarHostView: View { Text(String(localized: "sidebar.extensions.access.grant", defaultValue: "Grant Requested Access")) } .controlSize(.small) - Button { - xpcHost.revokeSensitiveAccess(bundleIdentifier: identity.bundleIdentifier) - self.effectiveGrant = xpcHost.currentEffectiveGrant - xpcHost.sendSnapshotDidChange() - } label: { - Text(String(localized: "sidebar.extensions.access.keepLimited", defaultValue: "Keep Limited")) + if effectiveGrant.hasSensitiveAccess { + Button { + xpcHost.revokeSensitiveAccess(bundleIdentifier: identity.bundleIdentifier) + self.effectiveGrant = xpcHost.currentEffectiveGrant + xpcHost.sendSnapshotDidChange() + } label: { + Text(String(localized: "sidebar.extensions.access.keepLimited", defaultValue: "Keep Limited")) + } + .controlSize(.small) } - .controlSize(.small) } } .padding(.horizontal, 12) @@ -635,6 +646,45 @@ struct CMUXInstalledExtensionSidebarHostView: View { .background(Color(nsColor: .controlBackgroundColor).opacity(0.88)) } + private func pendingPermissionDescriptions( + effectiveGrant: CMUXSidebarExtensionEffectiveGrant + ) -> [String] { + let pendingReadScopes = effectiveGrant.manifest.requestedScopes.filter { + !effectiveGrant.readScopes.contains($0) + } + let pendingActionScopes = effectiveGrant.manifest.requestedActionScopes.filter { + !effectiveGrant.actionScopes.contains($0) + } + return pendingReadScopes.map(permissionDescription(scope:)) + + pendingActionScopes.map(permissionDescription(actionScope:)) + } + + private func permissionDescription(scope: CMUXExtensionScope) -> String { + switch scope { + case .workspaceMetadata: + return String(localized: "sidebar.extensions.permission.workspaceMetadata.detail", defaultValue: "Read workspace names, branches, unread counts, and selection") + case .workspacePaths: + return String(localized: "sidebar.extensions.permission.workspacePaths.detail", defaultValue: "Read local workspace and project paths") + case .notifications: + return String(localized: "sidebar.extensions.permission.notifications.detail", defaultValue: "Read latest workspace notifications") + case .networkPorts: + return String(localized: "sidebar.extensions.permission.networkPorts.detail", defaultValue: "Read listening ports for each workspace") + case .pullRequests: + return String(localized: "sidebar.extensions.permission.pullRequests.detail", defaultValue: "Read pull request links associated with workspaces") + } + } + + private func permissionDescription(actionScope: CMUXExtensionActionScope) -> String { + switch actionScope { + case .selectWorkspace: + return String(localized: "sidebar.extensions.permission.selectWorkspace.detail", defaultValue: "Select a workspace when you click in the extension") + case .closeWorkspace: + return String(localized: "sidebar.extensions.permission.closeWorkspace.detail", defaultValue: "Close workspaces from the extension") + case .openURL: + return String(localized: "sidebar.extensions.permission.openURL.detail", defaultValue: "Open links from the extension") + } + } + private func observeEnabledExtensionIdentities( extensionPointIdentifier: String, staticExtensionPointIdentifier: StaticString From ef81b4154bb2e1cadb2c62cdc2085271e8ba2600 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Fri, 29 May 2026 20:23:36 -0500 Subject: [PATCH 31/44] Document sidebar extension quickstart --- Examples/SampleSidebarExtensionApp/README.md | 60 +++++++++++++++++++ Packages/CmuxExtensionKit/README.md | 61 ++++++++++++++++++++ 2 files changed, 121 insertions(+) create mode 100644 Examples/SampleSidebarExtensionApp/README.md diff --git a/Examples/SampleSidebarExtensionApp/README.md b/Examples/SampleSidebarExtensionApp/README.md new file mode 100644 index 000000000000..12017896b100 --- /dev/null +++ b/Examples/SampleSidebarExtensionApp/README.md @@ -0,0 +1,60 @@ +# CMUX Sample Sidebar Extension + +This is a standalone macOS app that embeds a CMUX sidebar ExtensionKit app extension. It is the reference project for third-party sidebar authors. + +## Build and Enable + +1. Open `SampleSidebarExtensionApp.xcodeproj`. +2. Select the app and extension targets. +3. Replace the Manaflow signing team with your own team. +4. Replace the app and extension bundle identifiers with your own reverse-DNS identifiers. +5. Keep the extension point identifier as `com.manaflow.cmux.sidebar`. +6. Keep the ExtensionKit scene identifier as `sidebar`. +7. Build and launch the containing app once. +8. In CMUX, click the titlebar puzzle button, open Sidebar Extensions, and enable the sample. +9. Choose `CMUX ExtKit Sample Sidebar` as the active sidebar provider. + +The sample targets macOS 26 because it exercises CMUX's current ExtensionFoundation browser and ExtensionKit host path. The `CmuxExtensionKit` data contract is plain Swift and remains separate from that host requirement. + +## What It Shows + +The extension renders real workspace data supplied by CMUX: + +- workspace count +- unread total +- listening port count +- pull request count +- selected workspace +- focus queue based on unread workspaces + +It does not use fake workspaces. If CMUX only grants limited access, the sample still renders the metadata CMUX shares by default. After you grant requested access in CMUX, it can also show paths, ports, notifications, and pull request links. + +## Authoring Pattern + +The sample keeps app-specific state in `SidebarConnectionModel` and delegates XPC plumbing to `CMUXSidebarExtensionConnection`: + +```swift +private lazy var extensionConnection = CMUXSidebarExtensionConnection( + manifest: Self.manifest, + onSnapshot: { [weak self] snapshot in + self?.snapshot = snapshot + }, + onError: { [weak self] message in + self?.errorText = message + } +) + +func accept(connection: NSXPCConnection) -> Bool { + extensionConnection.accept(connection) +} +``` + +The manifest is the permission request CMUX shows to users. Request only the scopes your sidebar actually needs. + +## Troubleshooting + +If the extension does not appear in CMUX, launch the containing app once, then reopen CMUX's Sidebar Extensions browser. + +If it appears but cannot be enabled, check signing on both the containing app and the embedded appex. + +If it loads but shows limited information, open the CMUX extension details popover and grant the requested data/actions. diff --git a/Packages/CmuxExtensionKit/README.md b/Packages/CmuxExtensionKit/README.md index 3e03784856c2..394e645e3796 100644 --- a/Packages/CmuxExtensionKit/README.md +++ b/Packages/CmuxExtensionKit/README.md @@ -12,3 +12,64 @@ Version 1 only supports sidebar extensions. The API exposes a stable workspace s The snapshot intentionally starts small: workspace identity, title, detail text, paths, git branch, unread state, listening ports, and pull request URLs. It does not expose terminal buffers, shell history, environment variables, secrets, or arbitrary filesystem access. Host-side lifecycle, discovery, and display belong in `Packages/CMUXExtensionClient`. + +## Five-Minute Sidebar Extension + +Sidebar extensions are ExtensionKit app extensions. The package itself supports macOS 14+ because the data contract is plain Swift, but CMUX currently discovers and enables third-party sidebar app extensions through ExtensionFoundation and ExtensionKit on macOS 26. + +Use `Examples/SampleSidebarExtensionApp` as the reference project: + +1. Open `SampleSidebarExtensionApp.xcodeproj`. +2. Change the app and extension bundle identifiers to your own reverse-DNS prefix. +3. Change the signing team from Manaflow to your team. +4. Keep the extension point identifier as `com.manaflow.cmux.sidebar`. +5. Keep the scene identifier as `sidebar`. +6. Build and launch the containing app once so macOS registers the embedded extension. +7. In CMUX, open Sidebar Extensions from the titlebar puzzle button and enable your extension. +8. Choose the extension as the active sidebar provider. + +The extension target declares the extension point manually in its `Info.plist`: + +```xml +EXAppExtensionAttributes + + EXExtensionPointIdentifier + com.manaflow.cmux.sidebar + +``` + +Your extension view accepts CMUX's XPC connection and hands it to the kit helper: + +```swift +let sidebarConnection = CMUXSidebarExtensionConnection( + manifest: CMUXExtensionManifest( + id: "dev.example.sidebar", + displayName: "Example Sidebar", + requestedScopes: [.workspaceMetadata], + requestedActionScopes: [.selectWorkspace] + ), + onSnapshot: { snapshot in + // Render real CMUX workspace data. + }, + onError: { message in + // Show or clear extension-local error state. + } +) + +func accept(connection: NSXPCConnection) -> Bool { + sidebarConnection.accept(connection) +} +``` + +CMUX grants only workspace metadata by default. Anything else must be listed in the manifest and approved in CMUX: + +- `workspaceMetadata`: workspace names, branches, unread counts, and selection +- `workspacePaths`: local workspace and project paths +- `notifications`: latest workspace notifications +- `networkPorts`: listening ports for each workspace +- `pullRequests`: pull request links associated with workspaces +- `selectWorkspace`: select a workspace from your UI +- `closeWorkspace`: close workspaces from your UI +- `openURL`: open links from your UI + +If your extension does not appear, confirm the containing app has been launched, the embedded appex is signed by your team, the extension point identifier is unchanged, and CMUX's Sidebar Extensions browser shows the extension as enabled. From 59f1282ae1efd0a67d24d0a7e18ce227e15ebbcb Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Fri, 29 May 2026 20:25:59 -0500 Subject: [PATCH 32/44] Timeout stalled sidebar extension manifests --- Resources/Localizable.xcstrings | 34 ++++++++++++++++ ...MUXInstalledExtensionSidebarHostView.swift | 39 +++++++++++++++++++ 2 files changed, 73 insertions(+) diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index 001ec0278cd9..19eae2fc0a87 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -162683,6 +162683,23 @@ } } }, + "sidebar.extensions.blocked.detail.manifestTimedOut": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "CMUX did not receive this extension's manifest in time. No workspace data or actions are being shared." + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "CMUXはこの拡張機能のマニフェストを時間内に受信しませんでした。ワークスペースデータや操作は共有されていません。" + } + } + } + }, "sidebar.extensions.blocked.detail.missingManifest": { "extractionState": "manual", "localizations": { @@ -162751,6 +162768,23 @@ } } }, + "sidebar.extensions.blocked.status.manifestTimedOut": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Blocked, manifest timed out" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "ブロック中、マニフェストがタイムアウトしました" + } + } + } + }, "sidebar.extensions.blocked.status.missingManifest": { "extractionState": "manual", "localizations": { diff --git a/Sources/CMUXInstalledExtensionSidebarHostView.swift b/Sources/CMUXInstalledExtensionSidebarHostView.swift index beb4c2aec7f3..97075cc55614 100644 --- a/Sources/CMUXInstalledExtensionSidebarHostView.swift +++ b/Sources/CMUXInstalledExtensionSidebarHostView.swift @@ -479,6 +479,8 @@ struct CMUXInstalledExtensionSidebarHostView: View { switch reason { case "connectionInterrupted": return String(localized: "sidebar.extensions.blocked.status.connectionInterrupted", defaultValue: "Blocked, connection interrupted") + case "manifestTimedOut": + return String(localized: "sidebar.extensions.blocked.status.manifestTimedOut", defaultValue: "Blocked, manifest timed out") case "missingManifest": return String(localized: "sidebar.extensions.blocked.status.missingManifest", defaultValue: "Blocked, missing manifest") case "invalidManifest": @@ -492,6 +494,8 @@ struct CMUXInstalledExtensionSidebarHostView: View { switch reason { case "connectionInterrupted": return String(localized: "sidebar.extensions.blocked.detail.connectionInterrupted", defaultValue: "CMUX lost the extension's XPC connection. No workspace data or actions are being shared.") + case "manifestTimedOut": + return String(localized: "sidebar.extensions.blocked.detail.manifestTimedOut", defaultValue: "CMUX did not receive this extension's manifest in time. No workspace data or actions are being shared.") case "missingManifest": return String(localized: "sidebar.extensions.blocked.detail.missingManifest", defaultValue: "CMUX did not receive a sidebar extension manifest, so no workspace data or actions were shared.") case "invalidManifest": @@ -846,6 +850,7 @@ private extension CMUXExtensionActionScope { private final class CMUXSidebarExtensionHostXPC { private static let untrustedScopes: Set = [] private static let untrustedActionScopes: Set = [] + private static let manifestRequestTimeoutNanoseconds: UInt64 = 5_000_000_000 private var connection: NSXPCConnection? private var extensionProxy: CMUXSidebarExtensionXPC? @@ -859,6 +864,8 @@ private final class CMUXSidebarExtensionHostXPC { private var currentManifest: CMUXExtensionManifest? private var onGrantChanged: ((CMUXSidebarExtensionEffectiveGrant?) -> Void)? private var onManifestBlocked: ((String?) -> Void)? + private var awaitingManifestGeneration: UInt64? + private var manifestRequestTimeoutTask: Task? private let grantStore = CMUXSidebarExtensionGrantStore() var currentEffectiveGrant: CMUXSidebarExtensionEffectiveGrant? { @@ -946,12 +953,14 @@ private final class CMUXSidebarExtensionHostXPC { private func clearProxy(ifCurrentGeneration generation: UInt64) { guard connectionGeneration == generation else { return } extensionProxy = nil + cancelManifestRequestTimeout() blockUntrustedExtension(reason: "connectionInterrupted") updateExportedSnapshotFilter() } private func clearConnection(ifCurrentGeneration generation: UInt64) { guard connectionGeneration == generation else { return } + cancelManifestRequestTimeout() connection = nil extensionProxy = nil exportedObject = nil @@ -972,10 +981,13 @@ private final class CMUXSidebarExtensionHostXPC { updateExportedSnapshotFilter() return } + beginManifestRequestTimeout(generation: generation) requestExtensionManifest { [weak self] payload, error in Task { @MainActor [generation] in guard let self else { return } guard self.connectionGeneration == generation else { return } + guard self.awaitingManifestGeneration == generation else { return } + self.cancelManifestRequestTimeout() if let payload { do { let manifest = try CMUXSidebarXPCCodec.decodeManifest(payload) @@ -1001,6 +1013,31 @@ private final class CMUXSidebarExtensionHostXPC { } } + private func beginManifestRequestTimeout(generation: UInt64) { + cancelManifestRequestTimeout() + awaitingManifestGeneration = generation + manifestRequestTimeoutTask = Task { @MainActor [weak self, generation] in + do { + try await Task.sleep(nanoseconds: Self.manifestRequestTimeoutNanoseconds) + } catch { + return + } + guard let self, + self.connectionGeneration == generation, + self.awaitingManifestGeneration == generation else { return } + self.cancelManifestRequestTimeout() + self.blockUntrustedExtension(reason: "manifestTimedOut") + self.updateExportedSnapshotFilter() + self.sendSnapshotDidChange() + } + } + + private func cancelManifestRequestTimeout() { + awaitingManifestGeneration = nil + manifestRequestTimeoutTask?.cancel() + manifestRequestTimeoutTask = nil + } + func grantRequestedAccess(bundleIdentifier: String) { guard self.bundleIdentifier == bundleIdentifier, let currentManifest else { return } grantStore.grantRequestedAccess(bundleIdentifier: bundleIdentifier, manifest: currentManifest) @@ -1014,6 +1051,7 @@ private final class CMUXSidebarExtensionHostXPC { } private func applyManifest(_ manifest: CMUXExtensionManifest) { + cancelManifestRequestTimeout() currentManifest = manifest guard let bundleIdentifier else { allowedScopes = Self.untrustedScopes @@ -1059,6 +1097,7 @@ private final class CMUXSidebarExtensionHostXPC { } private func blockUntrustedExtension(reason: String) { + cancelManifestRequestTimeout() allowedScopes = Self.untrustedScopes allowedActionScopes = Self.untrustedActionScopes currentManifest = nil From db59ca504a9a809a03291fc4983d5701b409f05f Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Fri, 29 May 2026 20:28:39 -0500 Subject: [PATCH 33/44] Refresh hosted sidebar extension snapshots --- .../CMUXInstalledExtensionSidebarHostView.swift | 4 ++++ Sources/ContentView.swift | 14 ++++++++++++++ 2 files changed, 18 insertions(+) diff --git a/Sources/CMUXInstalledExtensionSidebarHostView.swift b/Sources/CMUXInstalledExtensionSidebarHostView.swift index 97075cc55614..71c370f4057e 100644 --- a/Sources/CMUXInstalledExtensionSidebarHostView.swift +++ b/Sources/CMUXInstalledExtensionSidebarHostView.swift @@ -109,6 +109,7 @@ struct CMUXInstalledExtensionSidebarHostView: View { private static let selectedExtensionBundleIDDefaultsKey = "cmuxExtensionSidebar.selectedExtensionBundleId" var snapshotProvider: @MainActor () -> CMUXSidebarSnapshot + var snapshotUpdateToken: UInt64 = 0 var actionHandler: @MainActor (CMUXSidebarAction) -> CMUXExtensionActionResult var onUseDefaultSidebar: @MainActor () -> Void = {} @@ -213,6 +214,9 @@ struct CMUXInstalledExtensionSidebarHostView: View { .onChange(of: snapshotProvider().sequence) { _, _ in xpcHost.sendSnapshotDidChange() } + .onChange(of: snapshotUpdateToken) { _, _ in + xpcHost.sendSnapshotDidChange() + } .onDisappear { xpcHost.invalidate() } diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index 9194fd2821f4..dd87ea9a0f82 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -10641,11 +10641,25 @@ struct VerticalTabsSidebar: View { if selectedExtensionSidebarProviderId == CmuxExtensionSidebarSelection.hostedExtensionsProviderId { CMUXInstalledExtensionSidebarHostView( snapshotProvider: { cmuxSidebarSnapshotForCurrentTabs() }, + snapshotUpdateToken: extensionSidebarUpdateToken, actionHandler: { handleCMUXSidebarExtensionAction($0) }, onUseDefaultSidebar: { CmuxExtensionSidebarSelection.setProviderId(CmuxExtensionSidebarProviderID.defaultWorkspaces) } ) + .onReceive( + extensionSidebarImmediateObservationPublisher(renderContext: renderContext) + .receive(on: RunLoop.main) + ) { _ in + refreshExtensionSidebarSnapshot() + } + .onReceive( + extensionSidebarDebouncedObservationPublisher(renderContext: renderContext) + .receive(on: RunLoop.main) + .debounce(for: Self.extensionSidebarObservationCoalesceInterval, scheduler: RunLoop.main) + ) { _ in + refreshExtensionSidebarSnapshot() + } } else { TimelineView(.periodic(from: .now, by: 30)) { timeline in let model = extensionSidebarRenderModel(renderContext: renderContext, now: timeline.date) From a820c88cedab0f47448a6dfd1c78f2a5b0801fbd Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Fri, 29 May 2026 21:00:07 -0500 Subject: [PATCH 34/44] Improve sidebar extension recovery copy --- Examples/SampleSidebarExtensionApp/README.md | 3 +- Resources/Localizable.xcstrings | 55 ++++++++++++++++++- ...MUXInstalledExtensionSidebarHostView.swift | 42 +++++++++++--- 3 files changed, 89 insertions(+), 11 deletions(-) diff --git a/Examples/SampleSidebarExtensionApp/README.md b/Examples/SampleSidebarExtensionApp/README.md index 12017896b100..f2f01a18ed98 100644 --- a/Examples/SampleSidebarExtensionApp/README.md +++ b/Examples/SampleSidebarExtensionApp/README.md @@ -12,7 +12,8 @@ This is a standalone macOS app that embeds a CMUX sidebar ExtensionKit app exten 6. Keep the ExtensionKit scene identifier as `sidebar`. 7. Build and launch the containing app once. 8. In CMUX, click the titlebar puzzle button, open Sidebar Extensions, and enable the sample. -9. Choose `CMUX ExtKit Sample Sidebar` as the active sidebar provider. +9. In the same puzzle menu, choose `Extension Sidebar`. +10. If more than one sidebar extension is enabled, choose `CMUX ExtKit Sample Sidebar` inside the hosted sidebar. The sample targets macOS 26 because it exercises CMUX's current ExtensionFoundation browser and ExtensionKit host path. The `CmuxExtensionKit` data contract is plain Swift and remains separate from that host requirement. diff --git a/Resources/Localizable.xcstrings b/Resources/Localizable.xcstrings index 19eae2fc0a87..94d011be4c44 100644 --- a/Resources/Localizable.xcstrings +++ b/Resources/Localizable.xcstrings @@ -154733,13 +154733,13 @@ "en": { "stringUnit": { "state": "translated", - "value": "Sidebar" + "value": "Choose Sidebar" } }, "ja": { "stringUnit": { "state": "translated", - "value": "サイドバー" + "value": "サイドバーを選択" } } } @@ -162513,6 +162513,40 @@ } } }, + "sidebar.extensions.action.closeRejected": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Workspace could not be closed" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "ワークスペースを閉じられませんでした" + } + } + } + }, + "sidebar.extensions.action.urlRejected": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "URL could not be opened" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "URLを開けませんでした" + } + } + } + }, "sidebar.extensions.action.staleConnection": { "extractionState": "manual", "localizations": { @@ -163040,6 +163074,23 @@ } } }, + "sidebar.extensions.retry": { + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Try Again" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "再試行" + } + } + } + }, "sidebar.extensions.details.statusActive": { "extractionState": "manual", "localizations": { diff --git a/Sources/CMUXInstalledExtensionSidebarHostView.swift b/Sources/CMUXInstalledExtensionSidebarHostView.swift index 71c370f4057e..728d4704082a 100644 --- a/Sources/CMUXInstalledExtensionSidebarHostView.swift +++ b/Sources/CMUXInstalledExtensionSidebarHostView.swift @@ -463,15 +463,41 @@ struct CMUXInstalledExtensionSidebarHostView: View { .font(.system(size: 12)) .foregroundStyle(.secondary) .fixedSize(horizontal: false, vertical: true) - Button { - presentExtensionBrowser() - } label: { - Label( - String(localized: "sidebar.extensions.manage", defaultValue: "Manage Sidebar Extensions..."), - systemImage: "puzzlepiece.extension" - ) + HStack(spacing: 8) { + Button { + blockedManifestReason = nil + xpcHost.invalidate() + Task { + await observeExtensionAvailability() + } + } label: { + Label( + String(localized: "sidebar.extensions.retry", defaultValue: "Try Again"), + systemImage: "arrow.clockwise" + ) + } + .controlSize(.small) + + Button { + onUseDefaultSidebar() + } label: { + Label( + String(localized: "sidebar.extensions.useDefault.short", defaultValue: "Use Default"), + systemImage: "sidebar.left" + ) + } + .controlSize(.small) + + Button { + presentExtensionBrowser() + } label: { + Label( + String(localized: "sidebar.extensions.manage.short", defaultValue: "Manage"), + systemImage: "puzzlepiece.extension" + ) + } + .controlSize(.small) } - .controlSize(.small) } .padding(.horizontal, 14) .padding(.top, 14) From 632e8098262cddf9114f00a1158eb400ccfc3482 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Fri, 29 May 2026 21:05:31 -0500 Subject: [PATCH 35/44] Fix sidebar extension retry and XPC actor isolation --- .../Connection/SidebarConnectionModel.swift | 1 + .../CMUXSidebarExtensionConnection.swift | 88 ++++++++++--------- ...MUXInstalledExtensionSidebarHostView.swift | 8 +- 3 files changed, 53 insertions(+), 44 deletions(-) diff --git a/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/Connection/SidebarConnectionModel.swift b/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/Connection/SidebarConnectionModel.swift index 2b1e46cdd438..3841dc2b815d 100644 --- a/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/Connection/SidebarConnectionModel.swift +++ b/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/Connection/SidebarConnectionModel.swift @@ -4,6 +4,7 @@ import SwiftUI import CmuxExtensionKit @Observable +@MainActor final class SidebarConnectionModel: @unchecked Sendable { static let shared = SidebarConnectionModel() static let manifest = CMUXExtensionManifest( diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarExtensionConnection.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarExtensionConnection.swift index aae064c1875a..5ca2030e00a7 100644 --- a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarExtensionConnection.swift +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarExtensionConnection.swift @@ -1,6 +1,7 @@ import Foundation -public final class CMUXSidebarExtensionConnection: @unchecked Sendable { +@MainActor +public final class CMUXSidebarExtensionConnection { public typealias SnapshotHandler = @MainActor (CMUXSidebarSnapshot) -> Void public typealias ErrorHandler = @MainActor (String?) -> Void public typealias ActionReplyHandler = @MainActor (CMUXExtensionActionResult) -> Void @@ -32,20 +33,29 @@ public final class CMUXSidebarExtensionConnection: @unchecked Sendable { connection.exportedObject = CMUXSidebarExtensionXPCReceiver( manifest: manifest, receiveSnapshot: { [weak self] payload, receiverGeneration in - self?.receive(snapshot: payload, ifCurrentGeneration: receiverGeneration) + let snapshotPayload = Data(referencing: payload) + Task { @MainActor in + self?.receive(snapshot: snapshotPayload, ifCurrentGeneration: receiverGeneration) + } }, generation: generation ) connection.remoteObjectInterface = NSXPCInterface(with: CMUXSidebarHostXPC.self) connection.invalidationHandler = { [weak self, generation] in - self?.clearConnection(ifCurrentGeneration: generation) + Task { @MainActor in + self?.clearConnection(ifCurrentGeneration: generation) + } } connection.interruptionHandler = { [weak self, generation] in - self?.markInterrupted(ifCurrentGeneration: generation) + Task { @MainActor in + self?.markInterrupted(ifCurrentGeneration: generation) + } } self.connection = connection host = connection.remoteObjectProxyWithErrorHandler { [weak self, generation] error in - self?.report(error.localizedDescription, ifCurrentGeneration: generation) + Task { @MainActor in + self?.report(error.localizedDescription, ifCurrentGeneration: generation) + } } as? CMUXSidebarHostXPC connection.resume() refreshSnapshot() @@ -60,15 +70,17 @@ public final class CMUXSidebarExtensionConnection: @unchecked Sendable { let generation = connectionGeneration host.requestSidebarSnapshot { [weak self] payload, error in guard let self else { return } - if let error { - self.report(String(error), ifCurrentGeneration: generation) - return - } - guard let payload else { - self.report("cmux did not send a workspace snapshot", ifCurrentGeneration: generation) - return + Task { @MainActor in + if let error { + self.report(String(error), ifCurrentGeneration: generation) + return + } + guard let payload else { + self.report("cmux did not send a workspace snapshot", ifCurrentGeneration: generation) + return + } + self.receive(snapshot: Data(referencing: payload), ifCurrentGeneration: generation) } - self.receive(snapshot: payload, ifCurrentGeneration: generation) } } @@ -85,26 +97,26 @@ public final class CMUXSidebarExtensionConnection: @unchecked Sendable { let payload = try CMUXSidebarXPCCodec.encodeAction(action) host.performSidebarAction(payload) { [weak self] resultPayload, error in guard let self else { return } - if let error { - self.report(String(error), ifCurrentGeneration: generation) - return - } - guard let resultPayload else { - self.report("cmux did not send an action result", ifCurrentGeneration: generation) - return - } - do { - let result = try CMUXSidebarXPCCodec.decodeActionResult(resultPayload) - Task { @MainActor [reply] in - reply(result) + Task { @MainActor in + if let error { + self.report(String(error), ifCurrentGeneration: generation) + return + } + guard let resultPayload else { + self.report("cmux did not send an action result", ifCurrentGeneration: generation) + return } - if result.accepted { - self.report(nil, ifCurrentGeneration: generation) - } else { - self.report(result.message, ifCurrentGeneration: generation) + do { + let result = try CMUXSidebarXPCCodec.decodeActionResult(resultPayload) + reply(result) + if result.accepted { + self.report(nil, ifCurrentGeneration: generation) + } else { + self.report(result.message, ifCurrentGeneration: generation) + } + } catch { + self.report(error.localizedDescription, ifCurrentGeneration: generation) } - } catch { - self.report(error.localizedDescription, ifCurrentGeneration: generation) } } } catch { @@ -118,14 +130,12 @@ public final class CMUXSidebarExtensionConnection: @unchecked Sendable { clearConnection(ifCurrentGeneration: connectionGeneration) } - private func receive(snapshot payload: NSData, ifCurrentGeneration generation: UInt64) { + private func receive(snapshot payload: Data, ifCurrentGeneration generation: UInt64) { guard connectionGeneration == generation else { return } do { - let snapshot = try CMUXSidebarXPCCodec.decodeSnapshot(payload) - Task { @MainActor [onSnapshot, onError] in - onSnapshot(snapshot) - onError(nil) - } + let snapshot = try CMUXSidebarXPCCodec.decodeSnapshot(payload as NSData) + onSnapshot(snapshot) + onError(nil) } catch { report(error.localizedDescription, ifCurrentGeneration: generation) } @@ -133,9 +143,7 @@ public final class CMUXSidebarExtensionConnection: @unchecked Sendable { private func report(_ message: String?, ifCurrentGeneration generation: UInt64) { guard connectionGeneration == generation else { return } - Task { @MainActor [onError] in - onError(message) - } + onError(message) } private func markInterrupted(ifCurrentGeneration generation: UInt64) { diff --git a/Sources/CMUXInstalledExtensionSidebarHostView.swift b/Sources/CMUXInstalledExtensionSidebarHostView.swift index 728d4704082a..1d7eb765c8a3 100644 --- a/Sources/CMUXInstalledExtensionSidebarHostView.swift +++ b/Sources/CMUXInstalledExtensionSidebarHostView.swift @@ -127,6 +127,7 @@ struct CMUXInstalledExtensionSidebarHostView: View { @State private var effectiveGrant: CMUXSidebarExtensionEffectiveGrant? @State private var blockedManifestReason: String? @State private var isShowingExtensionDetails = false + @State private var hostReloadToken: UInt64 = 0 var body: some View { Group { @@ -165,7 +166,7 @@ struct CMUXInstalledExtensionSidebarHostView: View { xpcHost.invalidate() } ) - .id(identity.bundleIdentifier) + .id("\(identity.bundleIdentifier)-\(hostReloadToken)") .opacity(blockedManifestReason == nil ? 1 : 0) .frame(height: blockedManifestReason == nil ? nil : 0) .accessibilityIdentifier("CMUXExtensionSidebarHostView") @@ -466,10 +467,9 @@ struct CMUXInstalledExtensionSidebarHostView: View { HStack(spacing: 8) { Button { blockedManifestReason = nil + effectiveGrant = nil xpcHost.invalidate() - Task { - await observeExtensionAvailability() - } + hostReloadToken &+= 1 } label: { Label( String(localized: "sidebar.extensions.retry", defaultValue: "Try Again"), From 27fb01e2d78592c811fae22c134dbbfbd6392e2b Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Sat, 30 May 2026 00:04:16 -0500 Subject: [PATCH 36/44] Add sidebar ExtensionKit support --- Examples/SampleSidebarExtensionApp/README.md | 95 ++- .../Connection/SidebarConnectionModel.swift | 105 ++- .../Extension/SampleSidebarExtension.swift | 42 +- .../Model/SidebarInsightModel.swift | 47 ++ .../UI/SampleSidebarView.swift | 143 +++- .../UI/WorkspaceInsightRow.swift | 78 +- .../project.pbxproj | 36 +- .../SampleSidebarExtensionApp.xcscheme | 79 ++ .../ContentView.swift | 4 +- .../project.pbxproj | 785 ++++++++++++++++++ .../AccentColor.colorset/Contents.json | 11 + .../AppIcon.appiconset/Contents.json | 58 ++ .../Assets.xcassets/Contents.json | 6 + .../TabsVisibleSidebar/ContentView.swift | 30 + .../TabsVisibleSidebarApp.swift | 17 + .../TabsVisibleSidebarExtension/Info.plist | 11 + .../TabsVisibleSidebarExtension.swift | 73 ++ .../TabsVisibleSidebarView.swift | 178 ++++ .../TabsVisibleSidebarTests.swift | 19 + .../TabsVisibleSidebarUITests.swift | 43 + ...TabsVisibleSidebarUITestsLaunchTests.swift | 35 + .../CMUXSidebarExtensionDiscovery.swift | 1 + .../CMUXSidebarExtensionHostView.swift | 5 +- .../CMUXSidebarExtensionRegistry.swift | 4 +- .../Session/CMUXSidebarExtensionSession.swift | 33 +- .../CMUXExtensionClientTests.swift | 69 +- Packages/CmuxExtensionKit/README.md | 93 ++- .../Extension/CmuxExtension.swift | 15 + .../CmuxExtensionKit/Extension/CmuxHost.swift | 33 + .../Extension/CmuxUIExtension.swift | 11 + ...uxExtensionSidebarProviderDescriptor.swift | 4 +- .../CmuxExtensionSidebarProviderID.swift | 7 - .../Manifest/CMUXExtensionManifest.swift | 2 +- .../Manifest/CMUXExtensionScope.swift | 10 + .../Sidebar/CMUXExtensionActionResult.swift | 4 + .../Sidebar/CMUXSidebarAction.swift | 35 + .../Sidebar/CMUXSidebarExtension.swift | 29 +- .../CMUXSidebarExtensionConnection.swift | 362 ++++++-- .../Sidebar}/CMUXSidebarExtensionPoint.swift | 4 +- .../Sidebar/CMUXSidebarSnapshot.swift | 35 +- .../Sidebar/CMUXSidebarSurface.swift | 51 ++ .../Sidebar/CMUXSidebarWorkspace.swift | 24 +- .../Sidebar/CMUXSidebarXPC.swift | 5 +- .../CmuxSidebarActionCancellation.swift | 17 + .../Sidebar/CmuxSidebarContext.swift | 36 + .../Sidebar/CmuxSidebarExtensionRuntime.swift | 35 + .../Sidebar/CmuxSidebarExtensionScene.swift | 49 ++ .../Sidebar/CmuxSidebarHost.swift | 196 +++++ .../Validation/CMUXExtensionValidator.swift | 39 +- .../CmuxExtensionKitTests.swift | 149 +++- Sources/AppDelegate.swift | 4 + ...MUXInstalledExtensionSidebarHostView.swift | 255 +++++- Sources/ContentView.swift | 233 +++++- .../Update/MinimalModeSidebarControls.swift | 2 - Sources/Update/UpdateTitlebarAccessory.swift | 91 +- Sources/WindowDecorationsController.swift | 4 - Sources/WindowDragHandleView.swift | 9 +- cmux.xcworkspace/contents.xcworkspacedata | 3 + 58 files changed, 3419 insertions(+), 434 deletions(-) create mode 100644 Examples/SampleSidebarExtensionApp/SampleSidebarExtensionApp.xcodeproj/xcshareddata/xcschemes/SampleSidebarExtensionApp.xcscheme create mode 100644 Examples/TabsVisibleSidebar/TabsVisibleSidebar.xcodeproj/project.pbxproj create mode 100644 Examples/TabsVisibleSidebar/TabsVisibleSidebar/Assets.xcassets/AccentColor.colorset/Contents.json create mode 100644 Examples/TabsVisibleSidebar/TabsVisibleSidebar/Assets.xcassets/AppIcon.appiconset/Contents.json create mode 100644 Examples/TabsVisibleSidebar/TabsVisibleSidebar/Assets.xcassets/Contents.json create mode 100644 Examples/TabsVisibleSidebar/TabsVisibleSidebar/ContentView.swift create mode 100644 Examples/TabsVisibleSidebar/TabsVisibleSidebar/TabsVisibleSidebarApp.swift create mode 100644 Examples/TabsVisibleSidebar/TabsVisibleSidebarExtension/Info.plist create mode 100644 Examples/TabsVisibleSidebar/TabsVisibleSidebarExtension/TabsVisibleSidebarExtension.swift create mode 100644 Examples/TabsVisibleSidebar/TabsVisibleSidebarExtension/TabsVisibleSidebarView.swift create mode 100644 Examples/TabsVisibleSidebar/TabsVisibleSidebarTests/TabsVisibleSidebarTests.swift create mode 100644 Examples/TabsVisibleSidebar/TabsVisibleSidebarUITests/TabsVisibleSidebarUITests.swift create mode 100644 Examples/TabsVisibleSidebar/TabsVisibleSidebarUITests/TabsVisibleSidebarUITestsLaunchTests.swift create mode 100644 Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Extension/CmuxExtension.swift create mode 100644 Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Extension/CmuxHost.swift create mode 100644 Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Extension/CmuxUIExtension.swift delete mode 100644 Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/HostCompatibility/CmuxExtensionSidebarProviderID.swift rename Packages/{CMUXExtensionClient/Sources/CMUXExtensionClient/ExtensionPoint => CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar}/CMUXSidebarExtensionPoint.swift (85%) create mode 100644 Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarSurface.swift create mode 100644 Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CmuxSidebarActionCancellation.swift create mode 100644 Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CmuxSidebarContext.swift create mode 100644 Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CmuxSidebarExtensionRuntime.swift create mode 100644 Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CmuxSidebarExtensionScene.swift create mode 100644 Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CmuxSidebarHost.swift diff --git a/Examples/SampleSidebarExtensionApp/README.md b/Examples/SampleSidebarExtensionApp/README.md index f2f01a18ed98..4a69438de5d7 100644 --- a/Examples/SampleSidebarExtensionApp/README.md +++ b/Examples/SampleSidebarExtensionApp/README.md @@ -9,13 +9,12 @@ This is a standalone macOS app that embeds a CMUX sidebar ExtensionKit app exten 3. Replace the Manaflow signing team with your own team. 4. Replace the app and extension bundle identifiers with your own reverse-DNS identifiers. 5. Keep the extension point identifier as `com.manaflow.cmux.sidebar`. -6. Keep the ExtensionKit scene identifier as `sidebar`. -7. Build and launch the containing app once. -8. In CMUX, click the titlebar puzzle button, open Sidebar Extensions, and enable the sample. -9. In the same puzzle menu, choose `Extension Sidebar`. -10. If more than one sidebar extension is enabled, choose `CMUX ExtKit Sample Sidebar` inside the hosted sidebar. +6. Build and launch the containing app once. +7. In CMUX, click the puzzle button next to the sidebar help button, open Sidebar Extensions, and enable the sample. +8. In the same puzzle menu, choose the extension sidebar provider. +9. In the extension sidebar header, choose `CMUX ExtKit Sample Sidebar` if more than one sidebar extension is enabled. -The sample targets macOS 26 because it exercises CMUX's current ExtensionFoundation browser and ExtensionKit host path. The `CmuxExtensionKit` data contract is plain Swift and remains separate from that host requirement. +The sample targets macOS 14+, matching CMUX. ## What It Shows @@ -23,34 +22,84 @@ The extension renders real workspace data supplied by CMUX: - workspace count - unread total -- listening port count -- pull request count +- pinned workspace count +- all shared workspaces - selected workspace -- focus queue based on unread workspaces +- each workspace's shared surfaces +- focused surface indicators +- compact focus summary based on workspace signals -It does not use fake workspaces. If CMUX only grants limited access, the sample still renders the metadata CMUX shares by default. After you grant requested access in CMUX, it can also show paths, ports, notifications, and pull request links. +It does not use fake workspaces. The sample requests workspace metadata, surface metadata, and the action permissions needed for its controls: selecting workspaces, selecting surfaces, moving to the previous or next workspace or surface, and creating a terminal surface. ## Authoring Pattern -The sample keeps app-specific state in `SidebarConnectionModel` and delegates XPC plumbing to `CMUXSidebarExtensionConnection`: +The sample's `@main` ExtensionKit entrypoint conforms directly to +`CmuxSidebarExtension`. App-specific state lives in `SidebarConnectionModel`. CMUX +delivers workspace updates through `update(context:)`, and the model uses the typed +host helpers for actions: ```swift -private lazy var extensionConnection = CMUXSidebarExtensionConnection( - manifest: Self.manifest, - onSnapshot: { [weak self] snapshot in - self?.snapshot = snapshot - }, - onError: { [weak self] message in - self?.errorText = message +@main +@MainActor +final class SampleSidebarExtension: CmuxSidebarExtension { + static let manifest = CMUXExtensionManifest(...) + private let model = SidebarConnectionModel() + + required init() {} + + var body: some View { + SampleSidebarView(model: model) } -) -func accept(connection: NSXPCConnection) -> Bool { - extensionConnection.accept(connection) + func update(context: CmuxSidebarContext) { + model.update(context: context) + } +} + +@Observable +@MainActor +final class SidebarConnectionModel { + private(set) var snapshot: CMUXSidebarSnapshot? + private var host: CmuxSidebarHost? + private var cmux: CmuxHost? + + func update(context: CmuxSidebarContext) { + snapshot = context.snapshot + host = context.host + cmux = context.cmux + } + + func selectWorkspace(_ id: UUID) { + Task { @MainActor in + _ = await host?.selectWorkspace(id) + } + } + + func selectNextWorkspace() { + Task { @MainActor in + _ = await cmux?.selectNextWorkspace() + } + } + + func createTerminalSurface(in workspaceID: UUID?) { + Task { @MainActor in + _ = await host?.createTerminalSurface(in: workspaceID) + } + } } ``` -The manifest is the permission request CMUX shows to users. Request only the scopes your sidebar actually needs. +`CmuxSidebarExtension` owns the ExtensionKit scene and XPC connection, so extension +authors do not define `configuration`, bind an extension point in Swift, or touch +`NSXPCConnection`. + +`CmuxSidebarContext` exposes two typed host channels: + +- `context.cmux` for generic CMUX actions that are useful across extension types. +- `context.host` for sidebar-specific actions that operate on sidebar snapshot data. + +The manifest is the permission request CMUX shows to users. Request only the scopes +your sidebar actually needs. ## Troubleshooting @@ -58,4 +107,4 @@ If the extension does not appear in CMUX, launch the containing app once, then r If it appears but cannot be enabled, check signing on both the containing app and the embedded appex. -If it loads but shows limited information, open the CMUX extension details popover and grant the requested data/actions. +If it loads but row clicks do not select workspaces, open the CMUX extension details popover and grant the requested action. diff --git a/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/Connection/SidebarConnectionModel.swift b/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/Connection/SidebarConnectionModel.swift index 3841dc2b815d..36944a28e271 100644 --- a/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/Connection/SidebarConnectionModel.swift +++ b/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/Connection/SidebarConnectionModel.swift @@ -5,41 +5,25 @@ import CmuxExtensionKit @Observable @MainActor -final class SidebarConnectionModel: @unchecked Sendable { - static let shared = SidebarConnectionModel() - static let manifest = CMUXExtensionManifest( - id: "co.manaflow.CMUXExtKitSampleSidebarApp.Extension", - displayName: "CMUX Sample Sidebar Extension", - requestedScopes: [ - .workspaceMetadata, - .workspacePaths, - .notifications, - .networkPorts, - .pullRequests, - ], - requestedActionScopes: [ - .selectWorkspace, - ] - ) - +final class SidebarConnectionModel { private(set) var snapshot: CMUXSidebarSnapshot? private(set) var errorText: String? @ObservationIgnored - private lazy var extensionConnection = CMUXSidebarExtensionConnection( - manifest: Self.manifest, - onSnapshot: { [weak self] snapshot in - self?.snapshot = snapshot - }, - onError: { [weak self] message in - self?.errorText = message.map(Self.localizedHostMessage) - } - ) + private var host: CmuxSidebarHost? - private init() {} + @ObservationIgnored + private var cmux: CmuxHost? - func accept(connection: NSXPCConnection) -> Bool { - extensionConnection.accept(connection) + func update(context: CmuxSidebarContext) { + snapshot = context.snapshot + host = context.host + cmux = context.cmux + errorText = nil + } + + func connectionErrorDidChange(_ message: String?) { + errorText = message.map(Self.localizedHostMessage) } var insights: SidebarInsightModel? { @@ -47,11 +31,70 @@ final class SidebarConnectionModel: @unchecked Sendable { } func refreshSnapshot() { - extensionConnection.refreshSnapshot() + host?.refresh() } func selectWorkspace(_ id: UUID) { - extensionConnection.perform(.selectWorkspace(id)) + guard let host else { return } + Task { @MainActor in + let result = await host.selectWorkspace(id) + if result.accepted { + errorText = nil + } else { + errorText = result.message ?? String(localized: "sampleSidebar.actionDenied", defaultValue: "cmux did not allow that action") + } + } + } + + func selectSurface(workspaceID: UUID, surfaceID: UUID) { + guard let host else { return } + Task { @MainActor in + let result = await host.selectSurface(workspaceID: workspaceID, surfaceID: surfaceID) + apply(result) + } + } + + func selectPreviousWorkspace() { + guard let cmux else { return } + Task { @MainActor in + apply(await cmux.selectPreviousWorkspace()) + } + } + + func selectNextWorkspace() { + guard let cmux else { return } + Task { @MainActor in + apply(await cmux.selectNextWorkspace()) + } + } + + func selectPreviousSurface() { + guard let host else { return } + Task { @MainActor in + apply(await host.selectPreviousSurface()) + } + } + + func selectNextSurface() { + guard let host else { return } + Task { @MainActor in + apply(await host.selectNextSurface()) + } + } + + func createTerminalSurface(in workspaceID: UUID?) { + guard let host else { return } + Task { @MainActor in + apply(await host.createTerminalSurface(in: workspaceID)) + } + } + + private func apply(_ result: CMUXExtensionActionResult) { + if result.accepted { + errorText = nil + } else { + errorText = result.message ?? String(localized: "sampleSidebar.actionDenied", defaultValue: "cmux did not allow that action") + } } private static func localizedHostMessage(_ message: String) -> String { diff --git a/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/Extension/SampleSidebarExtension.swift b/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/Extension/SampleSidebarExtension.swift index 3aa8735b4eb1..6113160de72b 100644 --- a/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/Extension/SampleSidebarExtension.swift +++ b/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/Extension/SampleSidebarExtension.swift @@ -1,26 +1,38 @@ -import ExtensionFoundation -import ExtensionKit -import SwiftUI import CmuxExtensionKit +import SwiftUI @main -final class SampleSidebarExtension: AppExtension { +final class SampleSidebarExtension: CmuxSidebarExtension { + static let manifest = CMUXExtensionManifest( + id: "co.manaflow.CMUXExtKitSampleSidebarApp.Extension", + displayName: "CMUX Sample Sidebar Extension", + requestedScopes: [ + .workspaceList, + .workspaceMetadata, + .surfaceMetadata, + ], + requestedActionScopes: [ + .createSurface, + .selectWorkspace, + .selectSurface, + .navigateWorkspace, + .navigateSurface, + ] + ) + + private let model = SidebarConnectionModel() + required init() {} - @AppExtensionPoint.Bind - var boundExtensionPoint: AppExtensionPoint { - AppExtensionPoint.Identifier("com.manaflow.cmux.sidebar") + var body: some View { + SampleSidebarView(model: model) } - var configuration: AppExtensionSceneConfiguration { - AppExtensionSceneConfiguration(self.body) + func update(context: CmuxSidebarContext) { + model.update(context: context) } - var body: some AppExtensionScene { - PrimitiveAppExtensionScene(id: "sidebar") { - SampleSidebarView(model: SidebarConnectionModel.shared) - } onConnection: { connection in - SidebarConnectionModel.shared.accept(connection: connection) - } + func connectionErrorDidChange(_ message: String?) { + model.connectionErrorDidChange(message) } } diff --git a/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/Model/SidebarInsightModel.swift b/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/Model/SidebarInsightModel.swift index dcc711ded774..ff28fe504ca3 100644 --- a/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/Model/SidebarInsightModel.swift +++ b/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/Model/SidebarInsightModel.swift @@ -8,7 +8,13 @@ struct SidebarInsightModel { var unreadCount: Int var portCount: Int var pullRequestCount: Int + var canSelectWorkspace: Bool + var canCreateSurface: Bool + var canNavigateWorkspace: Bool + var canNavigateSurface: Bool + var hasWorkspaceMetadata: Bool var selectedWorkspace: WorkspaceInsight? + var allWorkspaces: [WorkspaceInsight] var focusQueue: [WorkspaceInsight] init(snapshot: CMUXSidebarSnapshot) { @@ -21,7 +27,13 @@ struct SidebarInsightModel { unreadCount = insights.reduce(0) { $0 + $1.unreadCount } portCount = insights.reduce(0) { $0 + $1.portCount } pullRequestCount = insights.reduce(0) { $0 + $1.pullRequestCount } + canSelectWorkspace = snapshot.grantedActionScopes.contains(.selectWorkspace) + canCreateSurface = snapshot.grantedActionScopes.contains(.createSurface) + canNavigateWorkspace = snapshot.grantedActionScopes.contains(.navigateWorkspace) + canNavigateSurface = snapshot.grantedActionScopes.contains(.navigateSurface) + hasWorkspaceMetadata = snapshot.grantedReadScopes.contains(.workspaceMetadata) selectedWorkspace = insights.first(where: \.isSelected) + allWorkspaces = insights focusQueue = insights .filter { $0.hasSignal && !$0.isSelected } .sorted { lhs, rhs in @@ -42,6 +54,7 @@ struct WorkspaceInsight: Identifiable { var pullRequestCount: Int var branch: String? var latestNotification: String? + var surfaces: [SurfaceInsight] init(workspace: CMUXSidebarWorkspace, selectedWorkspaceID: UUID?) { id = workspace.id @@ -54,6 +67,7 @@ struct WorkspaceInsight: Identifiable { pullRequestCount = workspace.pullRequestURLs.count branch = workspace.gitBranch latestNotification = workspace.latestNotification + surfaces = workspace.surfaces.map(SurfaceInsight.init(surface:)) } var hasSignal: Bool { @@ -69,6 +83,39 @@ struct WorkspaceInsight: Identifiable { } } +struct SurfaceInsight: Identifiable { + var id: UUID + var title: String + var kind: CMUXSidebarSurfaceKind + var isFocused: Bool + var unreadCount: Int + + init(surface: CMUXSidebarSurface) { + id = surface.id + title = surface.title + kind = surface.kind + isFocused = surface.isFocused + unreadCount = max(0, surface.unreadCount) + } + + var iconName: String { + switch kind { + case .terminal: + return "terminal" + case .browser: + return "globe" + case .markdown: + return "doc.text" + case .filePreview: + return "doc" + case .rightSidebarTool: + return "sidebar.right" + case .unknown: + return "rectangle" + } + } +} + private extension String { var lastPathComponent: String { (self as NSString).lastPathComponent diff --git a/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/UI/SampleSidebarView.swift b/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/UI/SampleSidebarView.swift index 56d6384bdc23..a1322cb8ef16 100644 --- a/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/UI/SampleSidebarView.swift +++ b/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/UI/SampleSidebarView.swift @@ -8,14 +8,15 @@ struct SampleSidebarView: View { VStack(alignment: .leading, spacing: 12) { if let insights = model.insights { header(insights) - if let selected = insights.selectedWorkspace { - WorkspaceInsightRow( - insight: selected, - action: { model.selectWorkspace(selected.id) } - ) + if let errorText = model.errorText { + statusBanner(errorText) + } else if !insights.canSelectWorkspace { + statusBanner(String(localized: "sampleSidebar.selectionLimited", defaultValue: "Review access in cmux to enable selecting workspaces from this extension.")) } + actionBar(insights) + workspaceList(insights) Divider() - focusQueue(insights) + signalSummary(insights) } else { waitingState } @@ -32,34 +33,148 @@ struct SampleSidebarView: View { VStack(alignment: .leading, spacing: 8) { Text(String(localized: "sampleSidebar.title", defaultValue: "Workspace Signals")) .font(.system(size: 14, weight: .semibold)) + Text(String.localizedStringWithFormat( + String(localized: "sampleSidebar.workspaceCount", defaultValue: "%d workspaces shared by cmux"), + insights.totalCount + )) + .font(.system(size: 11)) + .foregroundStyle(.secondary) HStack(spacing: 6) { + SummaryPill(value: "\(insights.totalCount)", label: String(localized: "sampleSidebar.workspaces", defaultValue: "Workspaces")) SummaryPill(value: "\(insights.unreadCount)", label: String(localized: "sampleSidebar.unread", defaultValue: "Unread")) - SummaryPill(value: "\(insights.portCount)", label: String(localized: "sampleSidebar.ports", defaultValue: "Ports")) - SummaryPill(value: "\(insights.pullRequestCount)", label: String(localized: "sampleSidebar.prs", defaultValue: "PRs")) + SummaryPill(value: "\(insights.pinnedCount)", label: String(localized: "sampleSidebar.pinned", defaultValue: "Pinned")) } } } - private func focusQueue(_ insights: SidebarInsightModel) -> some View { + private func statusBanner(_ text: String) -> some View { + Text(text) + .font(.system(size: 11)) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + .padding(.horizontal, 8) + .padding(.vertical, 6) + .frame(maxWidth: .infinity, alignment: .leading) + .background(Color(nsColor: .controlBackgroundColor).opacity(0.9)) + .clipShape(RoundedRectangle(cornerRadius: 6, style: .continuous)) + } + + private func actionBar(_ insights: SidebarInsightModel) -> some View { + HStack(spacing: 6) { + Button { + model.selectPreviousWorkspace() + } label: { + Image(systemName: "chevron.up") + .frame(width: 18, height: 18) + } + .disabled(!insights.canNavigateWorkspace) + .help(String(localized: "sampleSidebar.previousWorkspace", defaultValue: "Previous workspace")) + + Button { + model.selectNextWorkspace() + } label: { + Image(systemName: "chevron.down") + .frame(width: 18, height: 18) + } + .disabled(!insights.canNavigateWorkspace) + .help(String(localized: "sampleSidebar.nextWorkspace", defaultValue: "Next workspace")) + + Divider() + .frame(height: 18) + + Button { + model.selectPreviousSurface() + } label: { + Image(systemName: "chevron.left") + .frame(width: 18, height: 18) + } + .disabled(!insights.canNavigateSurface) + .help(String(localized: "sampleSidebar.previousSurface", defaultValue: "Previous surface")) + + Button { + model.selectNextSurface() + } label: { + Image(systemName: "chevron.right") + .frame(width: 18, height: 18) + } + .disabled(!insights.canNavigateSurface) + .help(String(localized: "sampleSidebar.nextSurface", defaultValue: "Next surface")) + + Button { + model.createTerminalSurface(in: insights.selectedWorkspace?.id) + } label: { + Image(systemName: "plus.rectangle.on.rectangle") + .frame(width: 18, height: 18) + } + .disabled(!insights.canCreateSurface) + .help(String(localized: "sampleSidebar.newTerminalSurface", defaultValue: "New terminal surface")) + } + .buttonStyle(.borderless) + .font(.system(size: 11, weight: .medium)) + .foregroundStyle(.secondary) + } + + private func workspaceList(_ insights: SidebarInsightModel) -> some View { VStack(alignment: .leading, spacing: 7) { - Text(String(localized: "sampleSidebar.focusQueue", defaultValue: "Focus Queue")) + Text(String(localized: "sampleSidebar.allWorkspaces", defaultValue: "All Workspaces")) .font(.system(size: 11, weight: .medium)) .foregroundStyle(.secondary) - if insights.focusQueue.isEmpty { - Text(String(localized: "sampleSidebar.noSignals", defaultValue: "No active workspace signals")) + if !insights.hasWorkspaceMetadata { + Text(String(localized: "sampleSidebar.metadataLimited", defaultValue: "Workspace metadata has not been shared yet. Review access in cmux to show workspace rows.")) + .font(.system(size: 12)) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } else if insights.allWorkspaces.isEmpty { + Text(String(localized: "sampleSidebar.noWorkspaces", defaultValue: "No workspaces were shared by cmux.")) .font(.system(size: 12)) .foregroundStyle(.secondary) } else { - ForEach(insights.focusQueue) { insight in + ForEach(insights.allWorkspaces) { insight in WorkspaceInsightRow( insight: insight, - action: { model.selectWorkspace(insight.id) } + action: { model.selectWorkspace(insight.id) }, + surfaceAction: { surfaceID in + model.selectSurface(workspaceID: insight.id, surfaceID: surfaceID) + } ) } } } } + private func signalSummary(_ insights: SidebarInsightModel) -> some View { + VStack(alignment: .leading, spacing: 7) { + Text(String(localized: "sampleSidebar.focusQueue", defaultValue: "Focus Queue")) + .font(.system(size: 11, weight: .medium)) + .foregroundStyle(.secondary) + if insights.focusQueue.isEmpty { + Text(String(localized: "sampleSidebar.noSignals", defaultValue: "No active workspace signals beyond the selected workspace")) + .font(.system(size: 12)) + .foregroundStyle(.secondary) + } else { + Text(signalSummaryText(insights.focusQueue)) + .font(.system(size: 12)) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + } + } + + private func signalSummaryText(_ insights: [WorkspaceInsight]) -> String { + let names = insights.prefix(3).map(\.title).joined(separator: ", ") + if insights.count <= 3 { + return String.localizedStringWithFormat( + String(localized: "sampleSidebar.signalSummary", defaultValue: "Signals in %@"), + names + ) + } + return String.localizedStringWithFormat( + String(localized: "sampleSidebar.signalSummaryMore", defaultValue: "Signals in %@ and %d more"), + names, + insights.count - 3 + ) + } + private var waitingState: some View { VStack(alignment: .leading, spacing: 8) { ProgressView() diff --git a/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/UI/WorkspaceInsightRow.swift b/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/UI/WorkspaceInsightRow.swift index 432749d88893..c09a5566061c 100644 --- a/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/UI/WorkspaceInsightRow.swift +++ b/Examples/SampleSidebarExtensionApp/SampleSidebarExtension/UI/WorkspaceInsightRow.swift @@ -3,34 +3,72 @@ import SwiftUI struct WorkspaceInsightRow: View { var insight: WorkspaceInsight var action: () -> Void + var surfaceAction: (UUID) -> Void = { _ in } var body: some View { - Button(action: action) { - HStack(spacing: 8) { - Image(systemName: insight.isSelected ? "target" : "terminal") + VStack(alignment: .leading, spacing: 4) { + Button(action: action) { + rowHeader + } + .buttonStyle(.plain) + + surfaceStrip + } + .padding(.horizontal, 8) + .padding(.vertical, 7) + .background(insight.isSelected ? Color.blue.opacity(0.16) : Color.clear, in: RoundedRectangle(cornerRadius: 6, style: .continuous)) + } + + private var rowHeader: some View { + HStack(spacing: 8) { + Image(systemName: insight.isSelected ? "target" : "terminal") + .font(.system(size: 12, weight: .semibold)) + .frame(width: 16, height: 16) + .foregroundStyle(insight.isSelected ? .blue : .secondary) + VStack(alignment: .leading, spacing: 2) { + Text(insight.title) .font(.system(size: 12, weight: .semibold)) - .frame(width: 16, height: 16) - .foregroundStyle(insight.isSelected ? .blue : .secondary) - VStack(alignment: .leading, spacing: 2) { - Text(insight.title) - .font(.system(size: 12, weight: .semibold)) + .lineLimit(1) + if !insight.subtitle.isEmpty { + Text(insight.subtitle) + .font(.system(size: 10)) + .foregroundStyle(.secondary) .lineLimit(1) - if !insight.subtitle.isEmpty { - Text(insight.subtitle) - .font(.system(size: 10)) - .foregroundStyle(.secondary) - .lineLimit(1) + } + signalLine + } + Spacer(minLength: 0) + } + .contentShape(Rectangle()) + } + + @ViewBuilder + private var surfaceStrip: some View { + if !insight.surfaces.isEmpty { + HStack(spacing: 4) { + ForEach(insight.surfaces.prefix(4)) { surface in + Button { + surfaceAction(surface.id) + } label: { + Image(systemName: surface.iconName) + .font(.system(size: 9, weight: .medium)) + .frame(width: 18, height: 16) + .foregroundStyle(surface.isFocused ? .blue : .secondary) + .background( + surface.isFocused ? Color.blue.opacity(0.16) : Color(nsColor: .controlBackgroundColor).opacity(0.8), + in: RoundedRectangle(cornerRadius: 4, style: .continuous) + ) } - signalLine + .buttonStyle(.plain) + .help(surface.title) + } + if insight.surfaces.count > 4 { + Text("+\(insight.surfaces.count - 4)") + .font(.system(size: 9, weight: .medium)) + .foregroundStyle(.secondary) } - Spacer(minLength: 0) } - .padding(.horizontal, 8) - .padding(.vertical, 7) - .contentShape(Rectangle()) } - .buttonStyle(.plain) - .background(insight.isSelected ? Color.blue.opacity(0.16) : Color.clear, in: RoundedRectangle(cornerRadius: 6, style: .continuous)) } private var signalLine: some View { diff --git a/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionApp.xcodeproj/project.pbxproj b/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionApp.xcodeproj/project.pbxproj index 2badcf2c79ad..d87aa6df6c13 100644 --- a/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionApp.xcodeproj/project.pbxproj +++ b/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionApp.xcodeproj/project.pbxproj @@ -7,8 +7,8 @@ objects = { /* Begin PBXBuildFile section */ + A3685C2E2FCA3B3700009F1B /* CMUX ExtKit Sample Sidebar Extension.appex in Embed ExtensionKit Extensions */ = {isa = PBXBuildFile; fileRef = A3685C242FCA3B2500009F1B /* CMUX ExtKit Sample Sidebar Extension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; }; C0DE47000000000000000001 /* CmuxExtensionKit in Frameworks */ = {isa = PBXBuildFile; productRef = C0DE47000000000000000002 /* CmuxExtensionKit */; }; - A3685C2E2FCA3B3700009F1B /* SampleSidebarExtension.appex in Embed ExtensionKit Extensions */ = {isa = PBXBuildFile; fileRef = A3685C242FCA3B2500009F1B /* SampleSidebarExtension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -42,7 +42,7 @@ dstPath = "$(EXTENSIONS_FOLDER_PATH)"; dstSubfolderSpec = 16; files = ( - A3685C2E2FCA3B3700009F1B /* SampleSidebarExtension.appex in Embed ExtensionKit Extensions */, + A3685C2E2FCA3B3700009F1B /* CMUX ExtKit Sample Sidebar Extension.appex in Embed ExtensionKit Extensions */, ); name = "Embed ExtensionKit Extensions"; runOnlyForDeploymentPostprocessing = 0; @@ -50,10 +50,10 @@ /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ - A3685BE92FCA3AEE00009F1B /* SampleSidebarExtensionApp.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = SampleSidebarExtensionApp.app; sourceTree = BUILT_PRODUCTS_DIR; }; + A3685BE92FCA3AEE00009F1B /* SampleSidebarExtensionApp.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; name = SampleSidebarExtensionApp.app; path = "CMUX ExtKit Sample Sidebar.app"; sourceTree = BUILT_PRODUCTS_DIR; }; A3685BF62FCA3AF000009F1B /* SampleSidebarExtensionAppTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = SampleSidebarExtensionAppTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; A3685C002FCA3AF000009F1B /* SampleSidebarExtensionAppUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = SampleSidebarExtensionAppUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; - A3685C242FCA3B2500009F1B /* SampleSidebarExtension.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.extensionkit-extension"; includeInIndex = 0; path = SampleSidebarExtension.appex; sourceTree = BUILT_PRODUCTS_DIR; }; + A3685C242FCA3B2500009F1B /* CMUX ExtKit Sample Sidebar Extension.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.extensionkit-extension"; includeInIndex = 0; path = "CMUX ExtKit Sample Sidebar Extension.appex"; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ /* Begin PBXFileSystemSynchronizedBuildFileExceptionSet section */ @@ -143,7 +143,7 @@ A3685BE92FCA3AEE00009F1B /* SampleSidebarExtensionApp.app */, A3685BF62FCA3AF000009F1B /* SampleSidebarExtensionAppTests.xctest */, A3685C002FCA3AF000009F1B /* SampleSidebarExtensionAppUITests.xctest */, - A3685C242FCA3B2500009F1B /* SampleSidebarExtension.appex */, + A3685C242FCA3B2500009F1B /* CMUX ExtKit Sample Sidebar Extension.appex */, ); name = Products; sourceTree = ""; @@ -248,7 +248,7 @@ C0DE47000000000000000002 /* CmuxExtensionKit */, ); productName = SampleSidebarExtension; - productReference = A3685C242FCA3B2500009F1B /* SampleSidebarExtension.appex */; + productReference = A3685C242FCA3B2500009F1B /* CMUX ExtKit Sample Sidebar Extension.appex */; productType = "com.apple.product-type.extensionkit-extension"; }; /* End PBXNativeTarget section */ @@ -287,7 +287,7 @@ mainGroup = A3685BE02FCA3AEE00009F1B; minimizedProjectReferenceProxies = 1; packageReferences = ( - C0DE47000000000000000003 /* XCLocalSwiftPackageReference "CmuxExtensionKit" */, + C0DE47000000000000000003 /* XCLocalSwiftPackageReference "../../Packages/CmuxExtensionKit" */, ); preferredProjectObjectVersion = 77; productRefGroup = A3685BEA2FCA3AEE00009F1B /* Products */; @@ -437,7 +437,7 @@ GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; LOCALIZATION_PREFERS_STRING_CATALOGS = YES; - MACOSX_DEPLOYMENT_TARGET = 26.3; + MACOSX_DEPLOYMENT_TARGET = 14.0; MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; MTL_FAST_MATH = YES; ONLY_ACTIVE_ARCH = YES; @@ -495,7 +495,7 @@ GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; LOCALIZATION_PREFERS_STRING_CATALOGS = YES; - MACOSX_DEPLOYMENT_TARGET = 26.3; + MACOSX_DEPLOYMENT_TARGET = 14.0; MTL_ENABLE_DEBUG_INFO = NO; MTL_FAST_MATH = YES; SDKROOT = macosx; @@ -522,7 +522,7 @@ "$(inherited)", "@executable_path/../Frameworks", ); - MACOSX_DEPLOYMENT_TARGET = 26.0; + MACOSX_DEPLOYMENT_TARGET = 14.0; MARKETING_VERSION = 1.0; PRODUCT_BUNDLE_IDENTIFIER = co.manaflow.CMUXExtKitSampleSidebarApp; PRODUCT_NAME = "CMUX ExtKit Sample Sidebar"; @@ -555,7 +555,7 @@ "$(inherited)", "@executable_path/../Frameworks", ); - MACOSX_DEPLOYMENT_TARGET = 26.0; + MACOSX_DEPLOYMENT_TARGET = 14.0; MARKETING_VERSION = 1.0; PRODUCT_BUNDLE_IDENTIFIER = co.manaflow.CMUXExtKitSampleSidebarApp; PRODUCT_NAME = "CMUX ExtKit Sample Sidebar"; @@ -577,7 +577,7 @@ CURRENT_PROJECT_VERSION = 1; DEVELOPMENT_TEAM = 7WLXT3NR37; GENERATE_INFOPLIST_FILE = YES; - MACOSX_DEPLOYMENT_TARGET = 26.3; + MACOSX_DEPLOYMENT_TARGET = 14.0; MARKETING_VERSION = 1.0; PRODUCT_BUNDLE_IDENTIFIER = co.manaflow.SampleSidebarExtensionAppTests; PRODUCT_NAME = "$(TARGET_NAME)"; @@ -598,7 +598,7 @@ CURRENT_PROJECT_VERSION = 1; DEVELOPMENT_TEAM = 7WLXT3NR37; GENERATE_INFOPLIST_FILE = YES; - MACOSX_DEPLOYMENT_TARGET = 26.3; + MACOSX_DEPLOYMENT_TARGET = 14.0; MARKETING_VERSION = 1.0; PRODUCT_BUNDLE_IDENTIFIER = co.manaflow.SampleSidebarExtensionAppTests; PRODUCT_NAME = "$(TARGET_NAME)"; @@ -652,6 +652,7 @@ A3685C2B2FCA3B2500009F1B /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { + APPLICATION_EXTENSION_API_ONLY = YES; CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = 1; DEVELOPMENT_TEAM = 7WLXT3NR37; @@ -665,7 +666,7 @@ "@executable_path/Frameworks", "@executable_path/../../Frameworks", ); - MACOSX_DEPLOYMENT_TARGET = 26.0; + MACOSX_DEPLOYMENT_TARGET = 14.0; MARKETING_VERSION = 1.0; PRODUCT_BUNDLE_IDENTIFIER = co.manaflow.CMUXExtKitSampleSidebarApp.Extension; PRODUCT_NAME = "CMUX ExtKit Sample Sidebar Extension"; @@ -682,6 +683,7 @@ A3685C2C2FCA3B2500009F1B /* Release */ = { isa = XCBuildConfiguration; buildSettings = { + APPLICATION_EXTENSION_API_ONLY = YES; CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = 1; DEVELOPMENT_TEAM = 7WLXT3NR37; @@ -695,7 +697,7 @@ "@executable_path/Frameworks", "@executable_path/../../Frameworks", ); - MACOSX_DEPLOYMENT_TARGET = 26.0; + MACOSX_DEPLOYMENT_TARGET = 14.0; MARKETING_VERSION = 1.0; PRODUCT_BUNDLE_IDENTIFIER = co.manaflow.CMUXExtKitSampleSidebarApp.Extension; PRODUCT_NAME = "CMUX ExtKit Sample Sidebar Extension"; @@ -761,7 +763,7 @@ /* End XCConfigurationList section */ /* Begin XCLocalSwiftPackageReference section */ - C0DE47000000000000000003 /* XCLocalSwiftPackageReference "CmuxExtensionKit" */ = { + C0DE47000000000000000003 /* XCLocalSwiftPackageReference "../../Packages/CmuxExtensionKit" */ = { isa = XCLocalSwiftPackageReference; relativePath = ../../Packages/CmuxExtensionKit; }; @@ -770,7 +772,7 @@ /* Begin XCSwiftPackageProductDependency section */ C0DE47000000000000000002 /* CmuxExtensionKit */ = { isa = XCSwiftPackageProductDependency; - package = C0DE47000000000000000003 /* XCLocalSwiftPackageReference "CmuxExtensionKit" */; + package = C0DE47000000000000000003 /* XCLocalSwiftPackageReference "../../Packages/CmuxExtensionKit" */; productName = CmuxExtensionKit; }; /* End XCSwiftPackageProductDependency section */ diff --git a/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionApp.xcodeproj/xcshareddata/xcschemes/SampleSidebarExtensionApp.xcscheme b/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionApp.xcodeproj/xcshareddata/xcschemes/SampleSidebarExtensionApp.xcscheme new file mode 100644 index 000000000000..f496bdca6244 --- /dev/null +++ b/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionApp.xcodeproj/xcshareddata/xcschemes/SampleSidebarExtensionApp.xcscheme @@ -0,0 +1,79 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionApp/ContentView.swift b/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionApp/ContentView.swift index ee52a42a503e..9a5c88621ba3 100644 --- a/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionApp/ContentView.swift +++ b/Examples/SampleSidebarExtensionApp/SampleSidebarExtensionApp/ContentView.swift @@ -17,7 +17,7 @@ struct ContentView: View { .font(.title2.weight(.semibold)) Text(String( localized: "sampleSidebarApp.detail", - defaultValue: "Keep this app installed. In cmux, click the puzzle button, choose Manage Sidebar Extensions..., enable CMUX Sample Sidebar Extension, choose Extension Sidebar, and confirm Workspace Signals appears." + defaultValue: "Keep this app installed. In cmux, open Sidebar Extensions, enable CMUX Sample Sidebar Extension, choose it from the sidebar picker, and confirm Workspace Signals shows your real workspaces." )) .foregroundStyle(.secondary) Text(String( @@ -28,7 +28,7 @@ struct ContentView: View { .foregroundStyle(.secondary) Text(String( localized: "sampleSidebarApp.scopes", - defaultValue: "Requests workspace metadata, paths, notifications, ports, and pull request links." + defaultValue: "Requests workspace and surface metadata, plus navigation, selection, and create-surface actions for the sidebar controls." )) .font(.caption) .foregroundStyle(.secondary) diff --git a/Examples/TabsVisibleSidebar/TabsVisibleSidebar.xcodeproj/project.pbxproj b/Examples/TabsVisibleSidebar/TabsVisibleSidebar.xcodeproj/project.pbxproj new file mode 100644 index 000000000000..611ca51cf54f --- /dev/null +++ b/Examples/TabsVisibleSidebar/TabsVisibleSidebar.xcodeproj/project.pbxproj @@ -0,0 +1,785 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 77; + objects = { + +/* Begin PBXBuildFile section */ + 5C6D3E60080CC641DB4C8FBF /* Tabs Visible Sidebar Extension.appex in Embed ExtensionKit Extensions */ = {isa = PBXBuildFile; fileRef = 919B1CC81D12E5904103EF57 /* Tabs Visible Sidebar Extension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; }; + B58315CC6425366FAE7BFD8F /* Cocoa.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = B4EAC892E452FBC759B48364 /* Cocoa.framework */; }; + FE91D213B4728F007B68C7DD /* CmuxExtensionKit in Frameworks */ = {isa = PBXBuildFile; productRef = CFEB80E86E6CC742FD554B53 /* CmuxExtensionKit */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 515CEF3E778EC3FC2CC2B567 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = A3685D432FCA97E900009F1B /* Project object */; + proxyType = 1; + remoteGlobalIDString = 095AE40FC6A0494D72064FB6; + remoteInfo = TabsVisibleSidebarExtension; + }; + A3685D592FCA97EB00009F1B /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = A3685D432FCA97E900009F1B /* Project object */; + proxyType = 1; + remoteGlobalIDString = A3685D4A2FCA97E900009F1B; + remoteInfo = TabsVisibleSidebar; + }; + A3685D632FCA97EB00009F1B /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = A3685D432FCA97E900009F1B /* Project object */; + proxyType = 1; + remoteGlobalIDString = A3685D4A2FCA97E900009F1B; + remoteInfo = TabsVisibleSidebar; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + CC4F886D4540227AB3A37497 /* Embed ExtensionKit Extensions */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = "$(EXTENSIONS_FOLDER_PATH)"; + dstSubfolderSpec = 16; + files = ( + 5C6D3E60080CC641DB4C8FBF /* Tabs Visible Sidebar Extension.appex in Embed ExtensionKit Extensions */, + ); + name = "Embed ExtensionKit Extensions"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 919B1CC81D12E5904103EF57 /* Tabs Visible Sidebar Extension.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.extensionkit-extension"; includeInIndex = 0; path = "Tabs Visible Sidebar Extension.appex"; sourceTree = BUILT_PRODUCTS_DIR; }; + A3685D4B2FCA97E900009F1B /* TabsVisibleSidebar.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = TabsVisibleSidebar.app; sourceTree = BUILT_PRODUCTS_DIR; }; + A3685D582FCA97EB00009F1B /* TabsVisibleSidebarTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = TabsVisibleSidebarTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + A3685D622FCA97EB00009F1B /* TabsVisibleSidebarUITests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = TabsVisibleSidebarUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + B4EAC892E452FBC759B48364 /* Cocoa.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Cocoa.framework; path = Platforms/MacOSX.platform/Developer/SDKs/MacOSX15.0.sdk/System/Library/Frameworks/Cocoa.framework; sourceTree = DEVELOPER_DIR; }; +/* End PBXFileReference section */ + +/* Begin PBXFileSystemSynchronizedRootGroup section */ + A3685D4D2FCA97E900009F1B /* TabsVisibleSidebar */ = { + isa = PBXFileSystemSynchronizedRootGroup; + exceptions = ( + ); + path = TabsVisibleSidebar; + sourceTree = ""; + }; + A3685D5B2FCA97EB00009F1B /* TabsVisibleSidebarTests */ = { + isa = PBXFileSystemSynchronizedRootGroup; + exceptions = ( + ); + path = TabsVisibleSidebarTests; + sourceTree = ""; + }; + A3685D652FCA97EB00009F1B /* TabsVisibleSidebarUITests */ = { + isa = PBXFileSystemSynchronizedRootGroup; + exceptions = ( + ); + path = TabsVisibleSidebarUITests; + sourceTree = ""; + }; +/* End PBXFileSystemSynchronizedRootGroup section */ + +/* Begin PBXFrameworksBuildPhase section */ + 34A445F98B7F894A82A9A667 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + B58315CC6425366FAE7BFD8F /* Cocoa.framework in Frameworks */, + FE91D213B4728F007B68C7DD /* CmuxExtensionKit in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A3685D482FCA97E900009F1B /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A3685D552FCA97EB00009F1B /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A3685D5F2FCA97EB00009F1B /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 02B95A27EB74606C91612834 /* OS X */ = { + isa = PBXGroup; + children = ( + B4EAC892E452FBC759B48364 /* Cocoa.framework */, + ); + name = "OS X"; + sourceTree = ""; + }; + 9BE2A10F5A2FA917C4A18AA7 /* Frameworks */ = { + isa = PBXGroup; + children = ( + 02B95A27EB74606C91612834 /* OS X */, + ); + name = Frameworks; + sourceTree = ""; + }; + A3685D422FCA97E900009F1B = { + isa = PBXGroup; + children = ( + A3685D4D2FCA97E900009F1B /* TabsVisibleSidebar */, + A3685D5B2FCA97EB00009F1B /* TabsVisibleSidebarTests */, + A3685D652FCA97EB00009F1B /* TabsVisibleSidebarUITests */, + A3685D4C2FCA97E900009F1B /* Products */, + 9BE2A10F5A2FA917C4A18AA7 /* Frameworks */, + E7BF8D059BCCD649E62309D3 /* TabsVisibleSidebarExtension */, + ); + sourceTree = ""; + }; + A3685D4C2FCA97E900009F1B /* Products */ = { + isa = PBXGroup; + children = ( + A3685D4B2FCA97E900009F1B /* TabsVisibleSidebar.app */, + A3685D582FCA97EB00009F1B /* TabsVisibleSidebarTests.xctest */, + A3685D622FCA97EB00009F1B /* TabsVisibleSidebarUITests.xctest */, + 919B1CC81D12E5904103EF57 /* Tabs Visible Sidebar Extension.appex */, + ); + name = Products; + sourceTree = ""; + }; + E7BF8D059BCCD649E62309D3 /* TabsVisibleSidebarExtension */ = { + isa = PBXGroup; + children = ( + ); + name = TabsVisibleSidebarExtension; + path = TabsVisibleSidebarExtension; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 095AE40FC6A0494D72064FB6 /* TabsVisibleSidebarExtension */ = { + isa = PBXNativeTarget; + buildConfigurationList = CE3DC7B6BBC1237511AD3D38 /* Build configuration list for PBXNativeTarget "TabsVisibleSidebarExtension" */; + buildPhases = ( + A43CA654B1ADB8F2473F2BE6 /* Sources */, + 34A445F98B7F894A82A9A667 /* Frameworks */, + 8738F4731FF43293B4042F97 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = TabsVisibleSidebarExtension; + packageProductDependencies = ( + CFEB80E86E6CC742FD554B53 /* CmuxExtensionKit */, + ); + productName = TabsVisibleSidebarExtension; + productReference = 919B1CC81D12E5904103EF57 /* Tabs Visible Sidebar Extension.appex */; + productType = "com.apple.product-type.extensionkit-extension"; + }; + A3685D4A2FCA97E900009F1B /* TabsVisibleSidebar */ = { + isa = PBXNativeTarget; + buildConfigurationList = A3685D6C2FCA97EB00009F1B /* Build configuration list for PBXNativeTarget "TabsVisibleSidebar" */; + buildPhases = ( + A3685D472FCA97E900009F1B /* Sources */, + A3685D482FCA97E900009F1B /* Frameworks */, + A3685D492FCA97E900009F1B /* Resources */, + CC4F886D4540227AB3A37497 /* Embed ExtensionKit Extensions */, + ); + buildRules = ( + ); + dependencies = ( + 7D4C9BA6FB7CB87DF278F3DE /* PBXTargetDependency */, + ); + fileSystemSynchronizedGroups = ( + A3685D4D2FCA97E900009F1B /* TabsVisibleSidebar */, + ); + name = TabsVisibleSidebar; + productName = TabsVisibleSidebar; + productReference = A3685D4B2FCA97E900009F1B /* TabsVisibleSidebar.app */; + productType = "com.apple.product-type.application"; + }; + A3685D572FCA97EB00009F1B /* TabsVisibleSidebarTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = A3685D6F2FCA97EB00009F1B /* Build configuration list for PBXNativeTarget "TabsVisibleSidebarTests" */; + buildPhases = ( + A3685D542FCA97EB00009F1B /* Sources */, + A3685D552FCA97EB00009F1B /* Frameworks */, + A3685D562FCA97EB00009F1B /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + A3685D5A2FCA97EB00009F1B /* PBXTargetDependency */, + ); + fileSystemSynchronizedGroups = ( + A3685D5B2FCA97EB00009F1B /* TabsVisibleSidebarTests */, + ); + name = TabsVisibleSidebarTests; + productName = TabsVisibleSidebarTests; + productReference = A3685D582FCA97EB00009F1B /* TabsVisibleSidebarTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; + A3685D612FCA97EB00009F1B /* TabsVisibleSidebarUITests */ = { + isa = PBXNativeTarget; + buildConfigurationList = A3685D722FCA97EB00009F1B /* Build configuration list for PBXNativeTarget "TabsVisibleSidebarUITests" */; + buildPhases = ( + A3685D5E2FCA97EB00009F1B /* Sources */, + A3685D5F2FCA97EB00009F1B /* Frameworks */, + A3685D602FCA97EB00009F1B /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + A3685D642FCA97EB00009F1B /* PBXTargetDependency */, + ); + fileSystemSynchronizedGroups = ( + A3685D652FCA97EB00009F1B /* TabsVisibleSidebarUITests */, + ); + name = TabsVisibleSidebarUITests; + productName = TabsVisibleSidebarUITests; + productReference = A3685D622FCA97EB00009F1B /* TabsVisibleSidebarUITests.xctest */; + productType = "com.apple.product-type.bundle.ui-testing"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + A3685D432FCA97E900009F1B /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = 1; + LastSwiftUpdateCheck = 2650; + LastUpgradeCheck = 2650; + TargetAttributes = { + A3685D4A2FCA97E900009F1B = { + CreatedOnToolsVersion = 26.5; + }; + A3685D572FCA97EB00009F1B = { + CreatedOnToolsVersion = 26.5; + TestTargetID = A3685D4A2FCA97E900009F1B; + }; + A3685D612FCA97EB00009F1B = { + CreatedOnToolsVersion = 26.5; + TestTargetID = A3685D4A2FCA97E900009F1B; + }; + }; + }; + buildConfigurationList = A3685D462FCA97E900009F1B /* Build configuration list for PBXProject "TabsVisibleSidebar" */; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = A3685D422FCA97E900009F1B; + minimizedProjectReferenceProxies = 1; + packageReferences = ( + 4C7B40C3DDA8FC4D2ECAE012 /* XCLocalSwiftPackageReference "CmuxExtensionKit" */, + ); + preferredProjectObjectVersion = 77; + productRefGroup = A3685D4C2FCA97E900009F1B /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + A3685D4A2FCA97E900009F1B /* TabsVisibleSidebar */, + A3685D572FCA97EB00009F1B /* TabsVisibleSidebarTests */, + A3685D612FCA97EB00009F1B /* TabsVisibleSidebarUITests */, + 095AE40FC6A0494D72064FB6 /* TabsVisibleSidebarExtension */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 8738F4731FF43293B4042F97 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A3685D492FCA97E900009F1B /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A3685D562FCA97EB00009F1B /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A3685D602FCA97EB00009F1B /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + A3685D472FCA97E900009F1B /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A3685D542FCA97EB00009F1B /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A3685D5E2FCA97EB00009F1B /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; + A43CA654B1ADB8F2473F2BE6 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 7D4C9BA6FB7CB87DF278F3DE /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + name = TabsVisibleSidebarExtension; + target = 095AE40FC6A0494D72064FB6 /* TabsVisibleSidebarExtension */; + targetProxy = 515CEF3E778EC3FC2CC2B567 /* PBXContainerItemProxy */; + }; + A3685D5A2FCA97EB00009F1B /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = A3685D4A2FCA97E900009F1B /* TabsVisibleSidebar */; + targetProxy = A3685D592FCA97EB00009F1B /* PBXContainerItemProxy */; + }; + A3685D642FCA97EB00009F1B /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = A3685D4A2FCA97E900009F1B /* TabsVisibleSidebar */; + targetProxy = A3685D632FCA97EB00009F1B /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin XCBuildConfiguration section */ + 31431F113A409103628945F8 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; + APPLICATION_EXTENSION_API_ONLY = YES; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = 7WLXT3NR37; + ENABLE_APP_SANDBOX = YES; + ENABLE_DEBUG_DYLIB = NO; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_FILE = TabsVisibleSidebarExtension/Info.plist; + INFOPLIST_KEY_CFBundleDisplayName = "Tabs Visible Sidebar"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@executable_path/../../Frameworks", + ); + MACOSX_DEPLOYMENT_TARGET = 14.0; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = co.manaflow.TabsVisibleSidebar.Extension; + PRODUCT_NAME = "Tabs Visible Sidebar Extension"; + SDKROOT = macosx; + SKIP_INSTALL = YES; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SWIFT_APPROACHABLE_CONCURRENCY = YES; + SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES; + SWIFT_VERSION = 5.0; + }; + name = Debug; + }; + 7058EB05B7208E7F6DA95B87 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; + APPLICATION_EXTENSION_API_ONLY = YES; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = 7WLXT3NR37; + ENABLE_APP_SANDBOX = YES; + ENABLE_DEBUG_DYLIB = NO; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_FILE = TabsVisibleSidebarExtension/Info.plist; + INFOPLIST_KEY_CFBundleDisplayName = "Tabs Visible Sidebar"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@executable_path/../../Frameworks", + ); + MACOSX_DEPLOYMENT_TARGET = 14.0; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = co.manaflow.TabsVisibleSidebar.Extension; + PRODUCT_NAME = "Tabs Visible Sidebar Extension"; + SDKROOT = macosx; + SKIP_INSTALL = YES; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SWIFT_APPROACHABLE_CONCURRENCY = YES; + SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES; + SWIFT_VERSION = 5.0; + }; + name = Release; + }; + A3685D6A2FCA97EB00009F1B /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + DEVELOPMENT_TEAM = 7WLXT3NR37; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + LOCALIZATION_PREFERS_STRING_CATALOGS = YES; + MACOSX_DEPLOYMENT_TARGET = 14.0; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = macosx; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + A3685D6B2FCA97EB00009F1B /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + DEVELOPMENT_TEAM = 7WLXT3NR37; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_USER_SCRIPT_SANDBOXING = YES; + GCC_C_LANGUAGE_STANDARD = gnu17; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + LOCALIZATION_PREFERS_STRING_CATALOGS = YES; + MACOSX_DEPLOYMENT_TARGET = 14.0; + MTL_ENABLE_DEBUG_INFO = NO; + MTL_FAST_MATH = YES; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + }; + name = Release; + }; + A3685D6D2FCA97EB00009F1B /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = 7WLXT3NR37; + ENABLE_APP_SANDBOX = YES; + ENABLE_HARDENED_RUNTIME = YES; + ENABLE_PREVIEWS = YES; + ENABLE_USER_SELECTED_FILES = readonly; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_KEY_NSHumanReadableCopyright = ""; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + MACOSX_DEPLOYMENT_TARGET = 14.0; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = co.manaflow.TabsVisibleSidebar; + PRODUCT_NAME = "$(TARGET_NAME)"; + REGISTER_APP_GROUPS = YES; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SWIFT_APPROACHABLE_CONCURRENCY = YES; + SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES; + SWIFT_VERSION = 5.0; + }; + name = Debug; + }; + A3685D6E2FCA97EB00009F1B /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = 7WLXT3NR37; + ENABLE_APP_SANDBOX = YES; + ENABLE_HARDENED_RUNTIME = YES; + ENABLE_PREVIEWS = YES; + ENABLE_USER_SELECTED_FILES = readonly; + GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_KEY_NSHumanReadableCopyright = ""; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + MACOSX_DEPLOYMENT_TARGET = 14.0; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = co.manaflow.TabsVisibleSidebar; + PRODUCT_NAME = "$(TARGET_NAME)"; + REGISTER_APP_GROUPS = YES; + STRING_CATALOG_GENERATE_SYMBOLS = YES; + SWIFT_APPROACHABLE_CONCURRENCY = YES; + SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor; + SWIFT_EMIT_LOC_STRINGS = YES; + SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES; + SWIFT_VERSION = 5.0; + }; + name = Release; + }; + A3685D702FCA97EB00009F1B /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = 7WLXT3NR37; + GENERATE_INFOPLIST_FILE = YES; + MACOSX_DEPLOYMENT_TARGET = 14.0; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = co.manaflow.TabsVisibleSidebarTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + STRING_CATALOG_GENERATE_SYMBOLS = NO; + SWIFT_APPROACHABLE_CONCURRENCY = YES; + SWIFT_EMIT_LOC_STRINGS = NO; + SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/TabsVisibleSidebar.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/TabsVisibleSidebar"; + }; + name = Debug; + }; + A3685D712FCA97EB00009F1B /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = 7WLXT3NR37; + GENERATE_INFOPLIST_FILE = YES; + MACOSX_DEPLOYMENT_TARGET = 14.0; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = co.manaflow.TabsVisibleSidebarTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + STRING_CATALOG_GENERATE_SYMBOLS = NO; + SWIFT_APPROACHABLE_CONCURRENCY = YES; + SWIFT_EMIT_LOC_STRINGS = NO; + SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES; + SWIFT_VERSION = 5.0; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/TabsVisibleSidebar.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/TabsVisibleSidebar"; + }; + name = Release; + }; + A3685D732FCA97EB00009F1B /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = 7WLXT3NR37; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = co.manaflow.TabsVisibleSidebarUITests; + PRODUCT_NAME = "$(TARGET_NAME)"; + STRING_CATALOG_GENERATE_SYMBOLS = NO; + SWIFT_APPROACHABLE_CONCURRENCY = YES; + SWIFT_EMIT_LOC_STRINGS = NO; + SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES; + SWIFT_VERSION = 5.0; + TEST_TARGET_NAME = TabsVisibleSidebar; + }; + name = Debug; + }; + A3685D742FCA97EB00009F1B /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 1; + DEVELOPMENT_TEAM = 7WLXT3NR37; + GENERATE_INFOPLIST_FILE = YES; + MARKETING_VERSION = 1.0; + PRODUCT_BUNDLE_IDENTIFIER = co.manaflow.TabsVisibleSidebarUITests; + PRODUCT_NAME = "$(TARGET_NAME)"; + STRING_CATALOG_GENERATE_SYMBOLS = NO; + SWIFT_APPROACHABLE_CONCURRENCY = YES; + SWIFT_EMIT_LOC_STRINGS = NO; + SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY = YES; + SWIFT_VERSION = 5.0; + TEST_TARGET_NAME = TabsVisibleSidebar; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + A3685D462FCA97E900009F1B /* Build configuration list for PBXProject "TabsVisibleSidebar" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + A3685D6A2FCA97EB00009F1B /* Debug */, + A3685D6B2FCA97EB00009F1B /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + A3685D6C2FCA97EB00009F1B /* Build configuration list for PBXNativeTarget "TabsVisibleSidebar" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + A3685D6D2FCA97EB00009F1B /* Debug */, + A3685D6E2FCA97EB00009F1B /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + A3685D6F2FCA97EB00009F1B /* Build configuration list for PBXNativeTarget "TabsVisibleSidebarTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + A3685D702FCA97EB00009F1B /* Debug */, + A3685D712FCA97EB00009F1B /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + A3685D722FCA97EB00009F1B /* Build configuration list for PBXNativeTarget "TabsVisibleSidebarUITests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + A3685D732FCA97EB00009F1B /* Debug */, + A3685D742FCA97EB00009F1B /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + CE3DC7B6BBC1237511AD3D38 /* Build configuration list for PBXNativeTarget "TabsVisibleSidebarExtension" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 7058EB05B7208E7F6DA95B87 /* Release */, + 31431F113A409103628945F8 /* Debug */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + +/* Begin XCLocalSwiftPackageReference section */ + 4C7B40C3DDA8FC4D2ECAE012 /* XCLocalSwiftPackageReference "CmuxExtensionKit" */ = { + isa = XCLocalSwiftPackageReference; + relativePath = ../../Packages/CmuxExtensionKit; + }; +/* End XCLocalSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + CFEB80E86E6CC742FD554B53 /* CmuxExtensionKit */ = { + isa = XCSwiftPackageProductDependency; + package = 4C7B40C3DDA8FC4D2ECAE012 /* XCLocalSwiftPackageReference "CmuxExtensionKit" */; + productName = CmuxExtensionKit; + }; +/* End XCSwiftPackageProductDependency section */ + }; + rootObject = A3685D432FCA97E900009F1B /* Project object */; +} diff --git a/Examples/TabsVisibleSidebar/TabsVisibleSidebar/Assets.xcassets/AccentColor.colorset/Contents.json b/Examples/TabsVisibleSidebar/TabsVisibleSidebar/Assets.xcassets/AccentColor.colorset/Contents.json new file mode 100644 index 000000000000..eb8789700816 --- /dev/null +++ b/Examples/TabsVisibleSidebar/TabsVisibleSidebar/Assets.xcassets/AccentColor.colorset/Contents.json @@ -0,0 +1,11 @@ +{ + "colors" : [ + { + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Examples/TabsVisibleSidebar/TabsVisibleSidebar/Assets.xcassets/AppIcon.appiconset/Contents.json b/Examples/TabsVisibleSidebar/TabsVisibleSidebar/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 000000000000..3f00db43ec3c --- /dev/null +++ b/Examples/TabsVisibleSidebar/TabsVisibleSidebar/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,58 @@ +{ + "images" : [ + { + "idiom" : "mac", + "scale" : "1x", + "size" : "16x16" + }, + { + "idiom" : "mac", + "scale" : "2x", + "size" : "16x16" + }, + { + "idiom" : "mac", + "scale" : "1x", + "size" : "32x32" + }, + { + "idiom" : "mac", + "scale" : "2x", + "size" : "32x32" + }, + { + "idiom" : "mac", + "scale" : "1x", + "size" : "128x128" + }, + { + "idiom" : "mac", + "scale" : "2x", + "size" : "128x128" + }, + { + "idiom" : "mac", + "scale" : "1x", + "size" : "256x256" + }, + { + "idiom" : "mac", + "scale" : "2x", + "size" : "256x256" + }, + { + "idiom" : "mac", + "scale" : "1x", + "size" : "512x512" + }, + { + "idiom" : "mac", + "scale" : "2x", + "size" : "512x512" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Examples/TabsVisibleSidebar/TabsVisibleSidebar/Assets.xcassets/Contents.json b/Examples/TabsVisibleSidebar/TabsVisibleSidebar/Assets.xcassets/Contents.json new file mode 100644 index 000000000000..73c00596a7fc --- /dev/null +++ b/Examples/TabsVisibleSidebar/TabsVisibleSidebar/Assets.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Examples/TabsVisibleSidebar/TabsVisibleSidebar/ContentView.swift b/Examples/TabsVisibleSidebar/TabsVisibleSidebar/ContentView.swift new file mode 100644 index 000000000000..25cea2dd67af --- /dev/null +++ b/Examples/TabsVisibleSidebar/TabsVisibleSidebar/ContentView.swift @@ -0,0 +1,30 @@ +import SwiftUI + +struct ContentView: View { + var body: some View { + VStack(alignment: .leading, spacing: 12) { + Image(systemName: "sidebar.leading") + .imageScale(.large) + .foregroundStyle(.tint) + Text(String(localized: "tabsVisible.app.title", defaultValue: "Tabs Visible Sidebar")) + .font(.title2.weight(.semibold)) + Text(String( + localized: "tabsVisible.app.detail", + defaultValue: "Keep this app installed. Enable Tabs Visible Sidebar from cmux Sidebar Extensions, then choose the extension sidebar provider from the sidebar footer puzzle button." + )) + .foregroundStyle(.secondary) + Text(String( + localized: "tabsVisible.app.scopes", + defaultValue: "The extension shows workspaces as disclosure groups and lists each workspace surface underneath." + )) + .font(.caption) + .foregroundStyle(.secondary) + } + .padding(24) + .frame(width: 420, alignment: .leading) + } +} + +#Preview { + ContentView() +} diff --git a/Examples/TabsVisibleSidebar/TabsVisibleSidebar/TabsVisibleSidebarApp.swift b/Examples/TabsVisibleSidebar/TabsVisibleSidebar/TabsVisibleSidebarApp.swift new file mode 100644 index 000000000000..24154b0aca1b --- /dev/null +++ b/Examples/TabsVisibleSidebar/TabsVisibleSidebar/TabsVisibleSidebarApp.swift @@ -0,0 +1,17 @@ +// +// TabsVisibleSidebarApp.swift +// TabsVisibleSidebar +// +// Created by Abdulaziz Albahar on 5/29/26. +// + +import SwiftUI + +@main +struct TabsVisibleSidebarApp: App { + var body: some Scene { + WindowGroup { + ContentView() + } + } +} diff --git a/Examples/TabsVisibleSidebar/TabsVisibleSidebarExtension/Info.plist b/Examples/TabsVisibleSidebar/TabsVisibleSidebarExtension/Info.plist new file mode 100644 index 000000000000..7d1a05030b30 --- /dev/null +++ b/Examples/TabsVisibleSidebar/TabsVisibleSidebarExtension/Info.plist @@ -0,0 +1,11 @@ + + + + + EXAppExtensionAttributes + + EXExtensionPointIdentifier + com.manaflow.cmux.sidebar + + + diff --git a/Examples/TabsVisibleSidebar/TabsVisibleSidebarExtension/TabsVisibleSidebarExtension.swift b/Examples/TabsVisibleSidebar/TabsVisibleSidebarExtension/TabsVisibleSidebarExtension.swift new file mode 100644 index 000000000000..f5165a865053 --- /dev/null +++ b/Examples/TabsVisibleSidebar/TabsVisibleSidebarExtension/TabsVisibleSidebarExtension.swift @@ -0,0 +1,73 @@ +import CmuxExtensionKit +import Observation +import SwiftUI + +@main +@Observable +@MainActor +final class TabsVisibleSidebarExtension: CmuxSidebarExtension { + static let manifest = CMUXExtensionManifest( + id: "co.manaflow.TabsVisibleSidebar.Extension", + displayName: "Tabs Visible Sidebar", + requestedScopes: [ + .workspaceList, + .workspaceMetadata, + .surfaceMetadata, + ], + requestedActionScopes: [ + .selectWorkspace, + .selectSurface, + ] + ) + + private(set) var snapshot: CMUXSidebarSnapshot? + private(set) var errorText: String? + var expandedWorkspaceIDs: Set = [] + + @ObservationIgnored + private var host: CmuxSidebarHost? + + required init() {} + + var body: some View { + TabsVisibleSidebarView(extensionModel: self) + } + + func update(context: CmuxSidebarContext) { + snapshot = context.snapshot + host = context.host + errorText = nil + + if let selectedWorkspaceID = context.snapshot.selectedWorkspaceID { + expandedWorkspaceIDs.insert(selectedWorkspaceID) + } + } + + func connectionErrorDidChange(_ message: String?) { + errorText = message + } + + func selectWorkspace(_ workspaceID: UUID) { + guard let host else { return } + expandedWorkspaceIDs.insert(workspaceID) + Task { @MainActor in + apply(await host.selectWorkspace(workspaceID)) + } + } + + func selectSurface(workspaceID: UUID, surfaceID: UUID) { + guard let host else { return } + expandedWorkspaceIDs.insert(workspaceID) + Task { @MainActor in + apply(await host.selectSurface(workspaceID: workspaceID, surfaceID: surfaceID)) + } + } + + private func apply(_ result: CMUXExtensionActionResult) { + if result.accepted { + errorText = nil + } else { + errorText = result.message ?? String(localized: "tabsVisible.actionDenied", defaultValue: "cmux did not allow that action") + } + } +} diff --git a/Examples/TabsVisibleSidebar/TabsVisibleSidebarExtension/TabsVisibleSidebarView.swift b/Examples/TabsVisibleSidebar/TabsVisibleSidebarExtension/TabsVisibleSidebarView.swift new file mode 100644 index 000000000000..dba616c4cb86 --- /dev/null +++ b/Examples/TabsVisibleSidebar/TabsVisibleSidebarExtension/TabsVisibleSidebarView.swift @@ -0,0 +1,178 @@ +import CmuxExtensionKit +import SwiftUI + +struct TabsVisibleSidebarView: View { + var extensionModel: TabsVisibleSidebarExtension + + var body: some View { + ScrollView { + VStack(alignment: .leading, spacing: 10) { + Text(String(localized: "tabsVisible.title", defaultValue: "Workspaces")) + .font(.system(size: 14, weight: .semibold)) + + if let errorText = extensionModel.errorText { + status(errorText) + } + + if let snapshot = extensionModel.snapshot { + workspaceList(snapshot) + } else { + waitingState + } + + Spacer(minLength: 0) + } + .padding(.horizontal, 10) + .padding(.vertical, 12) + .frame(maxWidth: .infinity, alignment: .topLeading) + } + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) + } + + private func workspaceList(_ snapshot: CMUXSidebarSnapshot) -> some View { + VStack(alignment: .leading, spacing: 6) { + if snapshot.workspaces.isEmpty { + Text(String(localized: "tabsVisible.noWorkspaces", defaultValue: "No workspaces shared by cmux")) + .font(.system(size: 12)) + .foregroundStyle(.secondary) + } else { + ForEach(snapshot.workspaces) { workspace in + workspaceDisclosure(workspace, selectedWorkspaceID: snapshot.selectedWorkspaceID) + } + } + } + } + + private func workspaceDisclosure( + _ workspace: CMUXSidebarWorkspace, + selectedWorkspaceID: UUID? + ) -> some View { + let isExpanded = Binding( + get: { extensionModel.expandedWorkspaceIDs.contains(workspace.id) }, + set: { isExpanded in + if isExpanded { + extensionModel.expandedWorkspaceIDs.insert(workspace.id) + } else { + extensionModel.expandedWorkspaceIDs.remove(workspace.id) + } + } + ) + + return DisclosureGroup(isExpanded: isExpanded) { + surfacesList(workspace) + .padding(.leading, 18) + .padding(.top, 4) + } label: { + HStack(spacing: 7) { + Image(systemName: workspace.id == selectedWorkspaceID ? "target" : "folder") + .font(.system(size: 11, weight: .semibold)) + .frame(width: 14, height: 14) + .foregroundStyle(workspace.id == selectedWorkspaceID ? .blue : .secondary) + VStack(alignment: .leading, spacing: 1) { + Text(workspace.title) + .font(.system(size: 12, weight: .semibold)) + .lineLimit(1) + if let detail = workspace.detail, !detail.isEmpty { + Text(detail) + .font(.system(size: 10)) + .foregroundStyle(.secondary) + .lineLimit(1) + } + } + Spacer(minLength: 0) + Text("\(workspace.surfaces.count)") + .font(.system(size: 10, weight: .medium)) + .foregroundStyle(.secondary) + } + .contentShape(Rectangle()) + .onTapGesture { + extensionModel.selectWorkspace(workspace.id) + } + } + .padding(.horizontal, 7) + .padding(.vertical, 6) + .background( + workspace.id == selectedWorkspaceID ? Color.blue.opacity(0.14) : Color.clear, + in: RoundedRectangle(cornerRadius: 6, style: .continuous) + ) + } + + private func surfacesList(_ workspace: CMUXSidebarWorkspace) -> some View { + VStack(alignment: .leading, spacing: 3) { + if workspace.surfaces.isEmpty { + Text(String(localized: "tabsVisible.noSurfaces", defaultValue: "No shared tabs")) + .font(.system(size: 11)) + .foregroundStyle(.secondary) + } else { + ForEach(workspace.surfaces) { surface in + Button { + extensionModel.selectSurface(workspaceID: workspace.id, surfaceID: surface.id) + } label: { + HStack(spacing: 6) { + Image(systemName: iconName(for: surface.kind)) + .font(.system(size: 10, weight: .semibold)) + .frame(width: 14, height: 14) + .foregroundStyle(surface.isFocused ? .blue : .secondary) + Text(surface.title) + .font(.system(size: 11, weight: surface.isFocused ? .semibold : .regular)) + .lineLimit(1) + Spacer(minLength: 0) + if surface.unreadCount > 0 { + Text("\(surface.unreadCount)") + .font(.system(size: 9, weight: .semibold)) + .foregroundStyle(.secondary) + } + } + .padding(.horizontal, 6) + .padding(.vertical, 4) + .contentShape(Rectangle()) + } + .buttonStyle(.plain) + .background( + surface.isFocused ? Color.blue.opacity(0.12) : Color.clear, + in: RoundedRectangle(cornerRadius: 5, style: .continuous) + ) + } + } + } + } + + private var waitingState: some View { + VStack(alignment: .leading, spacing: 8) { + ProgressView() + .controlSize(.small) + Text(String(localized: "tabsVisible.waiting", defaultValue: "Waiting for cmux")) + .font(.system(size: 12)) + .foregroundStyle(.secondary) + } + } + + private func status(_ text: String) -> some View { + Text(text) + .font(.system(size: 11)) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + .padding(.horizontal, 8) + .padding(.vertical, 6) + .frame(maxWidth: .infinity, alignment: .leading) + .background(Color(nsColor: .controlBackgroundColor).opacity(0.9)) + .clipShape(RoundedRectangle(cornerRadius: 6, style: .continuous)) + } + + private func iconName(for kind: CMUXSidebarSurfaceKind) -> String { + switch kind { + case .terminal: + return "terminal" + case .browser: + return "globe" + case .markdown: + return "doc.text" + case .filePreview: + return "doc" + case .rightSidebarTool: + return "sidebar.right" + case .unknown: + return "rectangle" + } + } +} diff --git a/Examples/TabsVisibleSidebar/TabsVisibleSidebarTests/TabsVisibleSidebarTests.swift b/Examples/TabsVisibleSidebar/TabsVisibleSidebarTests/TabsVisibleSidebarTests.swift new file mode 100644 index 000000000000..e35738c0cd66 --- /dev/null +++ b/Examples/TabsVisibleSidebar/TabsVisibleSidebarTests/TabsVisibleSidebarTests.swift @@ -0,0 +1,19 @@ +// +// TabsVisibleSidebarTests.swift +// TabsVisibleSidebarTests +// +// Created by Abdulaziz Albahar on 5/29/26. +// + +import Testing +@testable import TabsVisibleSidebar + +struct TabsVisibleSidebarTests { + + @Test func example() async throws { + // Write your test here and use APIs like `#expect(...)` to check expected conditions. + // Swift Testing Documentation + // https://developer.apple.com/documentation/testing + } + +} diff --git a/Examples/TabsVisibleSidebar/TabsVisibleSidebarUITests/TabsVisibleSidebarUITests.swift b/Examples/TabsVisibleSidebar/TabsVisibleSidebarUITests/TabsVisibleSidebarUITests.swift new file mode 100644 index 000000000000..24492e39921e --- /dev/null +++ b/Examples/TabsVisibleSidebar/TabsVisibleSidebarUITests/TabsVisibleSidebarUITests.swift @@ -0,0 +1,43 @@ +// +// TabsVisibleSidebarUITests.swift +// TabsVisibleSidebarUITests +// +// Created by Abdulaziz Albahar on 5/29/26. +// + +import XCTest + +final class TabsVisibleSidebarUITests: XCTestCase { + + override func setUpWithError() throws { + // Put setup code here. This method is called before the invocation of each test method in the class. + + // In UI tests it is usually best to stop immediately when a failure occurs. + continueAfterFailure = false + + // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. + } + + override func tearDownWithError() throws { + // Put teardown code here. This method is called after the invocation of each test method in the class. + } + + @MainActor + func testExample() throws { + // UI tests must launch the application that they test. + let app = XCUIApplication() + app.launch() + + // Use XCTAssert and related functions to verify your tests produce the correct results. + // XCUIAutomation Documentation + // https://developer.apple.com/documentation/xcuiautomation + } + + @MainActor + func testLaunchPerformance() throws { + // This measures how long it takes to launch your application. + measure(metrics: [XCTApplicationLaunchMetric()]) { + XCUIApplication().launch() + } + } +} diff --git a/Examples/TabsVisibleSidebar/TabsVisibleSidebarUITests/TabsVisibleSidebarUITestsLaunchTests.swift b/Examples/TabsVisibleSidebar/TabsVisibleSidebarUITests/TabsVisibleSidebarUITestsLaunchTests.swift new file mode 100644 index 000000000000..12a5d91d69d4 --- /dev/null +++ b/Examples/TabsVisibleSidebar/TabsVisibleSidebarUITests/TabsVisibleSidebarUITestsLaunchTests.swift @@ -0,0 +1,35 @@ +// +// TabsVisibleSidebarUITestsLaunchTests.swift +// TabsVisibleSidebarUITests +// +// Created by Abdulaziz Albahar on 5/29/26. +// + +import XCTest + +final class TabsVisibleSidebarUITestsLaunchTests: XCTestCase { + + override class var runsForEachTargetApplicationUIConfiguration: Bool { + true + } + + override func setUpWithError() throws { + continueAfterFailure = false + } + + @MainActor + func testLaunch() throws { + let app = XCUIApplication() + app.launch() + + // Insert steps here to perform after app launch but before taking a screenshot, + // such as logging into a test account or navigating somewhere in the app + // XCUIAutomation Documentation + // https://developer.apple.com/documentation/xcuiautomation + + let attachment = XCTAttachment(screenshot: app.screenshot()) + attachment.name = "Launch Screen" + attachment.lifetime = .keepAlways + add(attachment) + } +} diff --git a/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Discovery/CMUXSidebarExtensionDiscovery.swift b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Discovery/CMUXSidebarExtensionDiscovery.swift index 1e37f341e684..0bf78ffaafd6 100644 --- a/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Discovery/CMUXSidebarExtensionDiscovery.swift +++ b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Discovery/CMUXSidebarExtensionDiscovery.swift @@ -1,4 +1,5 @@ import ExtensionFoundation +import CmuxExtensionKit import Foundation @available(macOS 14.0, *) diff --git a/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Hosting/CMUXSidebarExtensionHostView.swift b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Hosting/CMUXSidebarExtensionHostView.swift index 896a50053565..9c85db239ee9 100644 --- a/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Hosting/CMUXSidebarExtensionHostView.swift +++ b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Hosting/CMUXSidebarExtensionHostView.swift @@ -1,15 +1,16 @@ import ExtensionFoundation import ExtensionKit +import CmuxExtensionKit import Foundation import SwiftUI @available(macOS 14.0, *) /// SwiftUI bridge that hosts a sidebar extension scene through ExtensionKit. -public struct CMUXSidebarExtensionHostView: NSViewControllerRepresentable { +@_spi(CmuxHostTransport) public struct CMUXSidebarExtensionHostView: NSViewControllerRepresentable { public typealias NSViewControllerType = EXHostViewController /// Tracks the configuration currently installed on the host view controller. - public final class Coordinator: NSObject, EXHostViewControllerDelegate { + @_spi(CmuxHostTransport) public final class Coordinator: NSObject, EXHostViewControllerDelegate { fileprivate var currentKey: HostConfigurationKey? private let onConnection: (@MainActor (NSXPCConnection) -> Void)? private let onDeactivation: (@MainActor (Error?) -> Void)? diff --git a/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Registry/CMUXSidebarExtensionRegistry.swift b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Registry/CMUXSidebarExtensionRegistry.swift index ee48a55f9b79..eab7987787ed 100644 --- a/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Registry/CMUXSidebarExtensionRegistry.swift +++ b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Registry/CMUXSidebarExtensionRegistry.swift @@ -1,4 +1,4 @@ -import CmuxExtensionKit +@_spi(CmuxHostTransport) import CmuxExtensionKit import Foundation /// Validated collection of sidebar extensions available to the host. @@ -11,7 +11,7 @@ public struct CMUXSidebarExtensionRegistry: Sendable { public init(records: [CMUXSidebarExtensionRecord] = []) throws { var recordsByID: [String: CMUXSidebarExtensionRecord] = [:] for record in records { - try CMUXExtensionValidator.validateSidebarManifest(record.manifest) + try validateSidebarManifest(record.manifest) if recordsByID[record.id] != nil { throw CMUXExtensionClientError.duplicateExtensionIdentifier(record.id) } diff --git a/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Session/CMUXSidebarExtensionSession.swift b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Session/CMUXSidebarExtensionSession.swift index e41b57b08301..a3d895535ec4 100644 --- a/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Session/CMUXSidebarExtensionSession.swift +++ b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Session/CMUXSidebarExtensionSession.swift @@ -1,28 +1,46 @@ -import CmuxExtensionKit +@_spi(CmuxHostTransport) import CmuxExtensionKit import Foundation /// Host-side session that mediates snapshot refreshes and action dispatch for one sidebar extension. public actor CMUXSidebarExtensionSession { private let manifest: CMUXExtensionManifest private let client: CMUXSidebarHostClient + private let grantedReadScopes: Set + private let grantedActionScopes: Set private var latestSnapshot: CMUXSidebarSnapshot? /// Creates a sidebar extension session. /// - Parameters: /// - manifest: Manifest for the extension attached to this session. /// - client: Host callbacks used to fetch snapshots and dispatch actions. + /// - grantedReadScopes: Read scopes currently approved for this extension. + /// - grantedActionScopes: Action scopes currently approved for this extension. /// - Throws: Manifest validation errors. - public init(manifest: CMUXExtensionManifest, client: CMUXSidebarHostClient) throws { - try CMUXExtensionValidator.validateSidebarManifest(manifest) + public init( + manifest: CMUXExtensionManifest, + client: CMUXSidebarHostClient, + grantedReadScopes: Set? = nil, + grantedActionScopes: Set? = nil + ) throws { + try validateSidebarManifest(manifest) self.manifest = manifest self.client = client + self.grantedReadScopes = Set(manifest.requestedScopes).intersection( + grantedReadScopes ?? Set(manifest.requestedScopes) + ) + self.grantedActionScopes = Set(manifest.requestedActionScopes).intersection( + grantedActionScopes ?? Set(manifest.requestedActionScopes) + ) } /// Fetches and caches the latest sidebar snapshot. - /// - Returns: Snapshot returned by the host client. + /// - Returns: Host snapshot filtered to this session's granted read scopes. /// - Throws: Errors thrown by the host snapshot callback. public func refreshSnapshot() async throws -> CMUXSidebarSnapshot { - let snapshot = try await client.snapshot() + let snapshot = try await client.snapshot().filtered( + for: grantedReadScopes, + actionScopes: grantedActionScopes + ) latestSnapshot = snapshot return snapshot } @@ -32,7 +50,10 @@ public actor CMUXSidebarExtensionSession { /// - Returns: Host action result. /// - Throws: Errors thrown by the host dispatch callback. public func perform(_ action: CMUXSidebarAction) async throws -> CMUXExtensionActionResult { - try await client.dispatch(action) + guard grantedActionScopes.contains(action.requiredScope) else { + return .rejected("Extension action is not granted") + } + return try await client.dispatch(action) } /// Manifest associated with this session. diff --git a/Packages/CMUXExtensionClient/Tests/CMUXExtensionClientTests/CMUXExtensionClientTests.swift b/Packages/CMUXExtensionClient/Tests/CMUXExtensionClientTests/CMUXExtensionClientTests.swift index 0e54279a5618..7527359d1ac6 100644 --- a/Packages/CMUXExtensionClient/Tests/CMUXExtensionClientTests/CMUXExtensionClientTests.swift +++ b/Packages/CMUXExtensionClient/Tests/CMUXExtensionClientTests/CMUXExtensionClientTests.swift @@ -50,8 +50,14 @@ struct CMUXExtensionClientTests { } ) let session = try CMUXSidebarExtensionSession( - manifest: CMUXExtensionManifest(id: "dev.example.sidebar", displayName: "Example"), - client: client + manifest: CMUXExtensionManifest( + id: "dev.example.sidebar", + displayName: "Example", + requestedScopes: [.workspaceMetadata], + requestedActionScopes: [.selectWorkspace] + ), + client: client, + grantedActionScopes: [.selectWorkspace] ) let refreshed = try await session.refreshSnapshot() @@ -59,11 +65,66 @@ struct CMUXExtensionClientTests { let cached = await session.cachedSnapshot() let actions = await recorder.actions() - #expect(refreshed == snapshot) - #expect(cached == snapshot) + #expect(refreshed.workspaces == snapshot.workspaces) + #expect(refreshed.grantedReadScopes == [.workspaceMetadata]) + #expect(refreshed.grantedActionScopes == [.selectWorkspace]) + #expect(cached == refreshed) #expect(result == .accepted) #expect(actions == [.selectWorkspace(workspaceID)]) } + + @Test + func testSessionFiltersSnapshotsAndRejectsUngrantedActions() async throws { + let workspaceID = UUID() + let snapshot = CMUXSidebarSnapshot( + sequence: 8, + selectedWorkspaceID: workspaceID, + grantedReadScopes: [.workspaceMetadata, .workspacePaths], + grantedActionScopes: [.selectWorkspace], + workspaces: [ + CMUXSidebarWorkspace( + id: workspaceID, + title: "Private", + rootPath: "/Users/example/private", + projectRootPath: "/Users/example/private" + ), + ] + ) + let recorder = ActionRecorder() + let client = CMUXSidebarHostClient( + snapshot: { snapshot }, + dispatch: { action in + await recorder.append(action) + return .accepted + } + ) + let session = try CMUXSidebarExtensionSession( + manifest: CMUXExtensionManifest( + id: "dev.example.sidebar", + displayName: "Example", + requestedScopes: [.workspaceMetadata, .workspacePaths], + requestedActionScopes: [.selectWorkspace, .closeWorkspace] + ), + client: client, + grantedReadScopes: [.workspaceMetadata], + grantedActionScopes: [.selectWorkspace] + ) + + let filtered = try await session.refreshSnapshot() + let workspace = try #require(filtered.workspaces.first) + let rejected = try await session.perform(.closeWorkspace(workspaceID)) + let accepted = try await session.perform(.selectWorkspace(workspaceID)) + let actions = await recorder.actions() + + #expect(workspace.rootPath == nil) + #expect(workspace.projectRootPath == nil) + #expect(filtered.grantedReadScopes == [.workspaceMetadata]) + #expect(filtered.grantedActionScopes == [.selectWorkspace]) + #expect(!rejected.accepted) + #expect(rejected.message == "Extension action is not granted") + #expect(accepted == .accepted) + #expect(actions == [.selectWorkspace(workspaceID)]) + } } private actor ActionRecorder { diff --git a/Packages/CmuxExtensionKit/README.md b/Packages/CmuxExtensionKit/README.md index 394e645e3796..51489e8d91ca 100644 --- a/Packages/CmuxExtensionKit/README.md +++ b/Packages/CmuxExtensionKit/README.md @@ -1,21 +1,21 @@ # CMUX Extension Kit -`CmuxExtensionKit` is the zero-dependency public contract for CMUX sidebar extensions. +`CmuxExtensionKit` is the zero-dependency public SDK for CMUX sidebar extensions. -Version 1 only supports sidebar extensions. The API exposes a stable workspace snapshot and a small action channel: +Version 1 only supports sidebar extensions. The API exposes a stable workspace snapshot and typed action channels: - read the current sidebar snapshot -- select a workspace -- close a workspace +- create, select, navigate, and close workspaces +- create, select, navigate, split, zoom, and close surfaces - ask CMUX to open a URL -The snapshot intentionally starts small: workspace identity, title, detail text, paths, git branch, unread state, listening ports, and pull request URLs. It does not expose terminal buffers, shell history, environment variables, secrets, or arbitrary filesystem access. +The snapshot includes workspace identity, title, detail text, paths, git branch, unread state, listening ports, pull request URLs, and shared surface metadata. It does not expose terminal buffers, shell history, environment variables, secrets, or arbitrary filesystem access. Host-side lifecycle, discovery, and display belong in `Packages/CMUXExtensionClient`. ## Five-Minute Sidebar Extension -Sidebar extensions are ExtensionKit app extensions. The package itself supports macOS 14+ because the data contract is plain Swift, but CMUX currently discovers and enables third-party sidebar app extensions through ExtensionFoundation and ExtensionKit on macOS 26. +Sidebar extensions are ExtensionKit app extensions. `CmuxExtensionKit` and the reference projects target macOS 14+, matching CMUX. Use `Examples/SampleSidebarExtensionApp` as the reference project: @@ -23,10 +23,10 @@ Use `Examples/SampleSidebarExtensionApp` as the reference project: 2. Change the app and extension bundle identifiers to your own reverse-DNS prefix. 3. Change the signing team from Manaflow to your team. 4. Keep the extension point identifier as `com.manaflow.cmux.sidebar`. -5. Keep the scene identifier as `sidebar`. -6. Build and launch the containing app once so macOS registers the embedded extension. -7. In CMUX, open Sidebar Extensions from the titlebar puzzle button and enable your extension. -8. Choose the extension as the active sidebar provider. +5. Build and launch the containing app once so macOS registers the embedded extension. +6. In CMUX, open Sidebar Extensions from the puzzle button next to the sidebar help button and enable your extension. +7. Choose the extension sidebar provider from that puzzle menu. +8. If more than one sidebar extension is enabled, choose your extension from the extension sidebar header. The extension target declares the extension point manually in its `Info.plist`: @@ -38,38 +38,85 @@ The extension target declares the extension point manually in its `Info.plist`: ``` -Your extension view accepts CMUX's XPC connection and hands it to the kit helper: +Define your ExtensionKit entrypoint by conforming directly to `CmuxSidebarExtension`. +The SDK refines `ExtensionFoundation.AppExtension`, supplies the ExtensionKit +configuration, owns the scene/XPC wiring, and uses the stable sidebar scene ID. +Your extension provides the manifest, SwiftUI view, and update handling: ```swift -let sidebarConnection = CMUXSidebarExtensionConnection( - manifest: CMUXExtensionManifest( +import CmuxExtensionKit +import Observation +import SwiftUI + +@main +@Observable +@MainActor +final class ExampleSidebarExtension: CmuxSidebarExtension { + static let manifest = CMUXExtensionManifest( id: "dev.example.sidebar", displayName: "Example Sidebar", requestedScopes: [.workspaceMetadata], requestedActionScopes: [.selectWorkspace] - ), - onSnapshot: { snapshot in - // Render real CMUX workspace data. - }, - onError: { message in - // Show or clear extension-local error state. + ) + + private(set) var snapshot: CMUXSidebarSnapshot? + private var host: CmuxSidebarHost? + + required init() {} + + var body: some View { + List(snapshot?.workspaces ?? []) { workspace in + Button(workspace.title) { + Task { @MainActor in + _ = await host?.selectWorkspace(workspace.id) + } + } + } } -) -func accept(connection: NSXPCConnection) -> Bool { - sidebarConnection.accept(connection) + func update(context: CmuxSidebarContext) { + snapshot = context.snapshot + host = context.host + } } ``` -CMUX grants only workspace metadata by default. Anything else must be listed in the manifest and approved in CMUX: +## Extension Protocols + +`CmuxExtension` is the base protocol. It refines `AppExtension` and requires the +manifest CMUX uses for identity, compatibility, and permission review. + +`CmuxUIExtension` adds SwiftUI content through a `body` property. + +`CmuxSidebarExtension` is the only concrete extension kind supported in version 1. It +delivers `CmuxSidebarContext`, which contains the filtered `CMUXSidebarSnapshot` and a +typed `CmuxSidebarHost` command channel. + +The lower-level transport lives behind CMUX host SPI. New sidebar extensions should +conform to `CmuxSidebarExtension` and should not handle XPC directly. + +## Permissions + +List every scope and action your extension needs in its manifest. CMUX filters the +snapshot and rejects actions that have not been granted: +- `workspaceList`: workspace identities and ordering - `workspaceMetadata`: workspace names, branches, unread counts, and selection +- `surfaceMetadata`: shared tab/surface names, kinds, focus, and unread counts - `workspacePaths`: local workspace and project paths - `notifications`: latest workspace notifications - `networkPorts`: listening ports for each workspace - `pullRequests`: pull request links associated with workspaces +- `createWorkspace`: create workspaces - `selectWorkspace`: select a workspace from your UI - `closeWorkspace`: close workspaces from your UI +- `createSurface`: create terminal and browser surfaces +- `selectSurface`: select a surface within a workspace +- `closeSurface`: close a surface +- `splitSurface`: split a terminal or browser surface +- `zoomSurface`: toggle surface zoom +- `navigateWorkspace`: select the next or previous workspace +- `navigateSurface`: select the next or previous surface - `openURL`: open links from your UI If your extension does not appear, confirm the containing app has been launched, the embedded appex is signed by your team, the extension point identifier is unchanged, and CMUX's Sidebar Extensions browser shows the extension as enabled. diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Extension/CmuxExtension.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Extension/CmuxExtension.swift new file mode 100644 index 000000000000..8501e63a1e92 --- /dev/null +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Extension/CmuxExtension.swift @@ -0,0 +1,15 @@ +@_exported import ExtensionFoundation +@_exported import ExtensionKit +import Foundation + +/// Base protocol for all CMUX extensions. +/// +/// Conform to a concrete CMUX extension protocol, such as +/// `CmuxSidebarExtension`, from your `@main` app extension type. CMUX extension +/// protocols refine `AppExtension`, so the SDK owns ExtensionKit configuration +/// and extension-point binding while your extension provides its manifest and UI. +@MainActor +public protocol CmuxExtension: AppExtension, AnyObject where Configuration == AppExtensionSceneConfiguration { + /// Manifest describing this extension and the data/actions it requests. + static var manifest: CMUXExtensionManifest { get } +} diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Extension/CmuxHost.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Extension/CmuxHost.swift new file mode 100644 index 000000000000..58ac9f625405 --- /dev/null +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Extension/CmuxHost.swift @@ -0,0 +1,33 @@ +import Foundation + +/// Generic CMUX action channel available to extension UIs. +@MainActor +public struct CmuxHost: Sendable { + private let performAction: @MainActor @Sendable (CMUXSidebarAction) async -> CMUXExtensionActionResult + + public init( + perform: @escaping @MainActor @Sendable (CMUXSidebarAction) async -> CMUXExtensionActionResult + ) { + self.performAction = perform + } + + public func createWorkspace( + title: String? = nil, + workingDirectory: String? = nil, + select: Bool = true + ) async -> CMUXExtensionActionResult { + await performAction(.createWorkspace(title: title, workingDirectory: workingDirectory, select: select)) + } + + public func selectNextWorkspace() async -> CMUXExtensionActionResult { + await performAction(.selectNextWorkspace) + } + + public func selectPreviousWorkspace() async -> CMUXExtensionActionResult { + await performAction(.selectPreviousWorkspace) + } + + public func openURL(_ url: URL) async -> CMUXExtensionActionResult { + await performAction(.openURL(url.absoluteString)) + } +} diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Extension/CmuxUIExtension.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Extension/CmuxUIExtension.swift new file mode 100644 index 000000000000..9ebb3c626184 --- /dev/null +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Extension/CmuxUIExtension.swift @@ -0,0 +1,11 @@ +import SwiftUI + +/// Base protocol for CMUX extensions that render SwiftUI content. +@MainActor +public protocol CmuxUIExtension: CmuxExtension { + /// SwiftUI content rendered inside the extension scene. + associatedtype Body: View + + /// The view CMUX hosts for this extension. + @ViewBuilder var body: Body { get } +} diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/HostCompatibility/CmuxExtensionSidebarProviderDescriptor.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/HostCompatibility/CmuxExtensionSidebarProviderDescriptor.swift index 4b104af75c30..7fc6c52467b7 100644 --- a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/HostCompatibility/CmuxExtensionSidebarProviderDescriptor.swift +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/HostCompatibility/CmuxExtensionSidebarProviderDescriptor.swift @@ -1,6 +1,8 @@ import Foundation public struct CmuxExtensionSidebarProviderDescriptor: Identifiable, Codable, Equatable, Sendable { + public static let defaultWorkspacesID = "cmux.sidebar.default" + public var id: String public var title: CmuxExtensionLocalizedText public var subtitle: CmuxExtensionLocalizedText? @@ -22,7 +24,7 @@ public struct CmuxExtensionSidebarProviderDescriptor: Identifiable, Codable, Equ } public static let defaultWorkspaces = CmuxExtensionSidebarProviderDescriptor( - id: CmuxExtensionSidebarProviderID.defaultWorkspaces, + id: defaultWorkspacesID, title: CmuxExtensionLocalizedText(key: "sidebar.provider.default.title", defaultValue: "Default Workspaces"), subtitle: CmuxExtensionLocalizedText(key: "sidebar.provider.default.subtitle", defaultValue: "cmux"), systemImageName: "list.bullet", diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/HostCompatibility/CmuxExtensionSidebarProviderID.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/HostCompatibility/CmuxExtensionSidebarProviderID.swift deleted file mode 100644 index 3bbb37489f74..000000000000 --- a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/HostCompatibility/CmuxExtensionSidebarProviderID.swift +++ /dev/null @@ -1,7 +0,0 @@ -import Foundation - -// Compatibility name used only by the existing cmux app while the old prototype -// sidebar is removed in smaller follow-up steps. -public enum CmuxExtensionSidebarProviderID { - public static let defaultWorkspaces = "cmux.sidebar.default" -} diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Manifest/CMUXExtensionManifest.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Manifest/CMUXExtensionManifest.swift index c1bd6a46ca7f..eadb743c0591 100644 --- a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Manifest/CMUXExtensionManifest.swift +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Manifest/CMUXExtensionManifest.swift @@ -13,7 +13,7 @@ public struct CMUXExtensionManifest: Codable, Equatable, Identifiable, Sendable displayName: String, kind: CMUXExtensionKind = .sidebar, minimumAPIVersion: CMUXExtensionAPIVersion = .sidebarV1, - requestedScopes: [CMUXExtensionScope] = [.workspaceMetadata], + requestedScopes: [CMUXExtensionScope] = [], requestedActionScopes: [CMUXExtensionActionScope] = [] ) { self.id = id diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Manifest/CMUXExtensionScope.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Manifest/CMUXExtensionScope.swift index 71cec90f5c0a..cee708ee07a8 100644 --- a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Manifest/CMUXExtensionScope.swift +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Manifest/CMUXExtensionScope.swift @@ -1,7 +1,9 @@ import Foundation public enum CMUXExtensionScope: String, Codable, CaseIterable, Equatable, Sendable { + case workspaceList case workspaceMetadata + case surfaceMetadata case workspacePaths case notifications case networkPorts @@ -9,7 +11,15 @@ public enum CMUXExtensionScope: String, Codable, CaseIterable, Equatable, Sendab } public enum CMUXExtensionActionScope: String, Codable, CaseIterable, Equatable, Sendable { + case createWorkspace case selectWorkspace case closeWorkspace + case createSurface + case selectSurface + case closeSurface + case splitSurface + case zoomSurface + case navigateWorkspace + case navigateSurface case openURL } diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXExtensionActionResult.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXExtensionActionResult.swift index 871d005014d8..cee5e76dc94a 100644 --- a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXExtensionActionResult.swift +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXExtensionActionResult.swift @@ -10,4 +10,8 @@ public struct CMUXExtensionActionResult: Codable, Equatable, Sendable { } public static let accepted = CMUXExtensionActionResult(accepted: true) + + public static func rejected(_ message: String) -> CMUXExtensionActionResult { + CMUXExtensionActionResult(accepted: false, message: message) + } } diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarAction.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarAction.swift index 4e0f4ca8cdf9..ef20e8f665db 100644 --- a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarAction.swift +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarAction.swift @@ -1,16 +1,51 @@ import Foundation +public enum CMUXSplitDirection: String, Codable, CaseIterable, Equatable, Sendable { + case left + case right + case up + case down +} + public enum CMUXSidebarAction: Codable, Equatable, Sendable { + case createWorkspace(title: String?, workingDirectory: String?, select: Bool) case selectWorkspace(UUID) case closeWorkspace(UUID) + case selectNextWorkspace + case selectPreviousWorkspace + case createTerminalSurface(workspaceID: UUID?, initialInput: String?) + case createBrowserSurface(workspaceID: UUID?, url: String?) + case selectSurface(workspaceID: UUID, surfaceID: UUID) + case selectNextSurface + case selectPreviousSurface + case closeSurface(workspaceID: UUID, surfaceID: UUID) + case splitTerminal(workspaceID: UUID, surfaceID: UUID, direction: CMUXSplitDirection) + case splitBrowser(workspaceID: UUID, surfaceID: UUID, direction: CMUXSplitDirection, url: String?) + case toggleSurfaceZoom(workspaceID: UUID, surfaceID: UUID) case openURL(String) public var requiredScope: CMUXExtensionActionScope { switch self { + case .createWorkspace: + return .createWorkspace case .selectWorkspace: return .selectWorkspace case .closeWorkspace: return .closeWorkspace + case .selectNextWorkspace, .selectPreviousWorkspace: + return .navigateWorkspace + case .createTerminalSurface, .createBrowserSurface: + return .createSurface + case .selectSurface: + return .selectSurface + case .selectNextSurface, .selectPreviousSurface: + return .navigateSurface + case .closeSurface: + return .closeSurface + case .splitTerminal, .splitBrowser: + return .splitSurface + case .toggleSurfaceZoom: + return .zoomSurface case .openURL: return .openURL } diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarExtension.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarExtension.swift index 2b0592fcdd0d..4088408349fc 100644 --- a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarExtension.swift +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarExtension.swift @@ -1,8 +1,27 @@ -import Foundation +import SwiftUI -public protocol CMUXSidebarExtension: Sendable { - var manifest: CMUXExtensionManifest { get } +/// A SwiftUI sidebar extension hosted by CMUX. +/// +/// Conform to this protocol from your `@main` app extension type. The SDK +/// supplies the ExtensionKit configuration, scene, and XPC wiring. Your +/// extension supplies the manifest, SwiftUI body, and snapshot update handling. +@MainActor +public protocol CmuxSidebarExtension: CmuxUIExtension { + /// Called whenever CMUX sends a new filtered sidebar snapshot. + func update(context: CmuxSidebarContext) - func makeInitialSnapshot() async throws -> CMUXSidebarSnapshot - func handle(_ action: CMUXSidebarAction) async throws -> CMUXExtensionActionResult + /// Called when the CMUX host connection changes state or reports an error. + func connectionErrorDidChange(_ message: String?) +} + +public extension CmuxSidebarExtension { + /// ExtensionKit configuration for the CMUX sidebar extension point. + /// + /// Extension authors should not implement this unless they are deliberately + /// replacing the SDK's ExtensionKit scene wiring. + var configuration: AppExtensionSceneConfiguration { + AppExtensionSceneConfiguration(CmuxSidebarExtensionScene(self)) + } + + func connectionErrorDidChange(_ message: String?) {} } diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarExtensionConnection.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarExtensionConnection.swift index 5ca2030e00a7..d87d3f3eea24 100644 --- a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarExtensionConnection.swift +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarExtensionConnection.swift @@ -1,20 +1,33 @@ import Foundation -@MainActor -public final class CMUXSidebarExtensionConnection { - public typealias SnapshotHandler = @MainActor (CMUXSidebarSnapshot) -> Void - public typealias ErrorHandler = @MainActor (String?) -> Void - public typealias ActionReplyHandler = @MainActor (CMUXExtensionActionResult) -> Void +/// Lower-level transport object for sidebar extensions. +/// +/// Most extension authors should use `CmuxSidebarExtensionScene(_:)`, which owns +/// ExtensionKit scene setup and `NSXPCConnection` handling. This type remains +/// internal so the public SDK keeps extension authors on typed CMUX protocols. +final class CMUXSidebarExtensionConnection: @unchecked Sendable { + /// Receives a filtered workspace snapshot from CMUX. + typealias SnapshotHandler = @MainActor @Sendable (CMUXSidebarSnapshot) -> Void - public let manifest: CMUXExtensionManifest + /// Receives connection state changes and transport errors. + typealias ErrorHandler = @MainActor @Sendable (String?) -> Void + + /// Receives the result for a host action request. + typealias ActionReplyHandler = @MainActor @Sendable (CMUXExtensionActionResult) -> Void + + /// Manifest presented to CMUX for identity, compatibility, and permissions. + let manifest: CMUXExtensionManifest private let onSnapshot: SnapshotHandler private let onError: ErrorHandler - private var connection: NSXPCConnection? - private var host: CMUXSidebarHostXPC? - private var connectionGeneration: UInt64 = 0 + private let lifecycleLock = NSLock() + private let lock = NSLock() + private var state = ConnectionState() - public init( + /// Creates a lower-level sidebar transport connection. + /// + /// Prefer `CmuxSidebarExtensionScene(_:)` for new extensions. + init( manifest: CMUXExtensionManifest, onSnapshot: @escaping SnapshotHandler, onError: @escaping ErrorHandler = { _ in } @@ -24,140 +37,313 @@ public final class CMUXSidebarExtensionConnection { self.onError = onError } + /// Accepts a host-provided XPC connection. + /// + /// Prefer `CmuxSidebarExtensionScene(_:)` for new extensions. @discardableResult - public func accept(_ connection: NSXPCConnection) -> Bool { - self.connection?.invalidate() - connectionGeneration += 1 - let generation = connectionGeneration + func accept(_ connection: NSXPCConnection) -> Bool { + lifecycleLock.lock() + defer { lifecycleLock.unlock() } + + let generation = nextGeneration(for: connection) + connection.exportedInterface = NSXPCInterface(with: CMUXSidebarExtensionXPC.self) connection.exportedObject = CMUXSidebarExtensionXPCReceiver( manifest: manifest, receiveSnapshot: { [weak self] payload, receiverGeneration in - let snapshotPayload = Data(referencing: payload) - Task { @MainActor in - self?.receive(snapshot: snapshotPayload, ifCurrentGeneration: receiverGeneration) - } + self?.receive(snapshot: Data(referencing: payload), ifCurrentGeneration: receiverGeneration) }, generation: generation ) connection.remoteObjectInterface = NSXPCInterface(with: CMUXSidebarHostXPC.self) connection.invalidationHandler = { [weak self, generation] in - Task { @MainActor in - self?.clearConnection(ifCurrentGeneration: generation) - } + self?.clearConnection(ifCurrentGeneration: generation) } connection.interruptionHandler = { [weak self, generation] in - Task { @MainActor in - self?.markInterrupted(ifCurrentGeneration: generation) - } + self?.markInterrupted(ifCurrentGeneration: generation) } - self.connection = connection - host = connection.remoteObjectProxyWithErrorHandler { [weak self, generation] error in - Task { @MainActor in - self?.report(error.localizedDescription, ifCurrentGeneration: generation) - } + + let hostProxy = connection.remoteObjectProxyWithErrorHandler { [weak self, generation] error in + self?.report(error.localizedDescription, ifCurrentGeneration: generation) } as? CMUXSidebarHostXPC + setHost(hostProxy, ifCurrentGeneration: generation) connection.resume() refreshSnapshot() return true } - public func refreshSnapshot() { - guard let host else { - report("Waiting for cmux", ifCurrentGeneration: connectionGeneration) + /// Requests a fresh snapshot from CMUX. + func refreshSnapshot() { + guard let target = currentHost() else { + report("Waiting for cmux", ifCurrentGeneration: currentGeneration()) return } - let generation = connectionGeneration - host.requestSidebarSnapshot { [weak self] payload, error in - guard let self else { return } - Task { @MainActor in - if let error { - self.report(String(error), ifCurrentGeneration: generation) - return - } - guard let payload else { - self.report("cmux did not send a workspace snapshot", ifCurrentGeneration: generation) - return - } - self.receive(snapshot: Data(referencing: payload), ifCurrentGeneration: generation) + target.host.requestSidebarSnapshot { [weak self, generation = target.generation] payload, error in + if let error { + self?.report(String(error), ifCurrentGeneration: generation) + return } + guard let payload else { + self?.report("cmux did not send a workspace snapshot", ifCurrentGeneration: generation) + return + } + self?.receive(snapshot: Data(referencing: payload), ifCurrentGeneration: generation) } } - public func perform( + /// Sends a host action to CMUX. + func perform( _ action: CMUXSidebarAction, reply: @escaping ActionReplyHandler = { _ in } - ) { - guard let host else { - report("Waiting for cmux", ifCurrentGeneration: connectionGeneration) - return + ) -> CmuxSidebarActionCancellation? { + guard let target = currentHost() else { + let message = "Waiting for cmux" + report(message, ifCurrentGeneration: currentGeneration()) + deliver(.rejected(message), to: reply) + return nil } - let generation = connectionGeneration + + let generation = target.generation do { let payload = try CMUXSidebarXPCCodec.encodeAction(action) - host.performSidebarAction(payload) { [weak self] resultPayload, error in - guard let self else { return } - Task { @MainActor in - if let error { - self.report(String(error), ifCurrentGeneration: generation) - return - } - guard let resultPayload else { - self.report("cmux did not send an action result", ifCurrentGeneration: generation) - return - } - do { - let result = try CMUXSidebarXPCCodec.decodeActionResult(resultPayload) - reply(result) - if result.accepted { - self.report(nil, ifCurrentGeneration: generation) - } else { - self.report(result.message, ifCurrentGeneration: generation) - } - } catch { - self.report(error.localizedDescription, ifCurrentGeneration: generation) + let actionID = UUID() + guard storePendingAction(id: actionID, generation: generation, reply: reply) else { + deliver(.rejected("cmux connection changed"), to: reply) + return nil + } + target.host.performSidebarAction(payload) { [weak self] resultPayload, error in + guard let self else { + Self.deliver(.rejected("cmux connection was lost"), to: reply) + return + } + if let error { + let message = String(error) + guard self.completePendingAction(id: actionID, result: .rejected(message)) else { return } + self.report(message, ifCurrentGeneration: generation) + return + } + guard let resultPayload else { + let message = "cmux did not send an action result" + guard self.completePendingAction(id: actionID, result: .rejected(message)) else { return } + self.report(message, ifCurrentGeneration: generation) + return + } + do { + let result = try CMUXSidebarXPCCodec.decodeActionResult(resultPayload) + guard self.completePendingAction(id: actionID, result: result) else { return } + if result.accepted { + self.report(nil, ifCurrentGeneration: generation) + } else { + self.report(result.message, ifCurrentGeneration: generation) } + } catch { + let message = error.localizedDescription + guard self.completePendingAction(id: actionID, result: .rejected(message)) else { return } + self.report(message, ifCurrentGeneration: generation) } } + return CmuxSidebarActionCancellation { [weak self] in + self?.cancelPendingAction(id: actionID) + } } catch { - report(error.localizedDescription, ifCurrentGeneration: generation) + let message = error.localizedDescription + report(message, ifCurrentGeneration: generation) + deliver(.rejected(message), to: reply) + return nil } } - public func invalidate() { - connectionGeneration += 1 + /// Tears down the current host connection. + func invalidate() { + let (connection, pendingReplies, generation) = withState { state in + state.generation += 1 + let connection = state.connection + let pendingReplies = Array(state.pendingActions.values.map(\.reply)) + state.connection = nil + state.host = nil + state.pendingActions.removeAll() + return (connection, pendingReplies, state.generation) + } connection?.invalidate() - clearConnection(ifCurrentGeneration: connectionGeneration) + deliver(.rejected("cmux connection was closed"), to: pendingReplies) + report("Waiting for cmux", ifCurrentGeneration: generation) } private func receive(snapshot payload: Data, ifCurrentGeneration generation: UInt64) { - guard connectionGeneration == generation else { return } + guard isCurrent(generation) else { return } do { let snapshot = try CMUXSidebarXPCCodec.decodeSnapshot(payload as NSData) - onSnapshot(snapshot) - onError(nil) + deliver(snapshot, ifCurrentGeneration: generation) } catch { report(error.localizedDescription, ifCurrentGeneration: generation) } } + private func deliver(_ snapshot: CMUXSidebarSnapshot, ifCurrentGeneration generation: UInt64) { + Task { @MainActor [weak self] in + guard let self, self.isCurrent(generation) else { return } + onSnapshot(snapshot) + onError(nil) + } + } + private func report(_ message: String?, ifCurrentGeneration generation: UInt64) { - guard connectionGeneration == generation else { return } - onError(message) + Task { @MainActor [weak self] in + guard let self, self.isCurrent(generation) else { return } + onError(message) + } + } + + private func deliver( + _ result: CMUXExtensionActionResult, + to reply: @escaping ActionReplyHandler + ) { + Self.deliver(result, to: reply) } private func markInterrupted(ifCurrentGeneration generation: UInt64) { - guard connectionGeneration == generation else { return } - host = nil - report("Waiting for cmux", ifCurrentGeneration: generation) + let repliesToDrain = withState { state -> [ActionReplyHandler]? in + guard state.generation == generation else { return nil } + state.host = nil + let replies = pendingReplies(from: &state, matching: generation) + return replies + } + if let repliesToDrain { + deliver(.rejected("cmux connection was interrupted"), to: repliesToDrain) + report("Waiting for cmux", ifCurrentGeneration: generation) + } } private func clearConnection(ifCurrentGeneration generation: UInt64) { - guard connectionGeneration == generation else { return } - connection = nil - host = nil - report("Waiting for cmux", ifCurrentGeneration: generation) + let repliesToDrain = withState { state -> [ActionReplyHandler]? in + guard state.generation == generation else { return nil } + state.connection = nil + state.host = nil + let replies = pendingReplies(from: &state, matching: generation) + return replies + } + if let repliesToDrain { + deliver(.rejected("cmux connection was closed"), to: repliesToDrain) + report("Waiting for cmux", ifCurrentGeneration: generation) + } + } + + private func nextGeneration(for connection: NSXPCConnection) -> UInt64 { + let (generation, oldConnection, pendingReplies) = withState { state in + state.generation += 1 + let oldConnection = state.connection + let pendingReplies = Array(state.pendingActions.values.map(\.reply)) + state.connection = connection + state.host = nil + state.pendingActions.removeAll() + return (state.generation, oldConnection, pendingReplies) + } + oldConnection?.invalidate() + deliver(.rejected("cmux connection changed"), to: pendingReplies) + return generation + } + + private func setHost(_ host: CMUXSidebarHostXPC?, ifCurrentGeneration generation: UInt64) { + withState { state in + guard state.generation == generation else { return } + state.host = host + } + } + + private func currentHost() -> (host: CMUXSidebarHostXPC, generation: UInt64)? { + withState { state in + guard let host = state.host else { return nil } + return (host, state.generation) + } + } + + private func currentGeneration() -> UInt64 { + withState { state in + state.generation + } + } + + private func isCurrent(_ generation: UInt64) -> Bool { + withState { state in + state.generation == generation + } + } + + private func storePendingAction( + id: UUID, + generation: UInt64, + reply: @escaping ActionReplyHandler + ) -> Bool { + withState { state in + guard state.generation == generation else { return false } + state.pendingActions[id] = PendingAction(generation: generation, reply: reply) + return true + } + } + + private func completePendingAction(id: UUID, result: CMUXExtensionActionResult) -> Bool { + let reply = withState { state in + state.pendingActions.removeValue(forKey: id)?.reply + } + guard let reply else { return false } + deliver(result, to: reply) + return true + } + + private func cancelPendingAction(id: UUID) { + _ = withState { state in + state.pendingActions.removeValue(forKey: id) + } + } + + private func pendingReplies( + from state: inout ConnectionState, + matching generation: UInt64 + ) -> [ActionReplyHandler] { + let matchingActions = state.pendingActions.filter { _, action in + action.generation == generation + } + for id in matchingActions.keys { + state.pendingActions.removeValue(forKey: id) + } + return matchingActions.values.map(\.reply) } + + private func deliver( + _ result: CMUXExtensionActionResult, + to replies: [ActionReplyHandler] + ) { + for reply in replies { + deliver(result, to: reply) + } + } + + private static func deliver( + _ result: CMUXExtensionActionResult, + to reply: @escaping ActionReplyHandler + ) { + Task { @MainActor in + reply(result) + } + } + + private func withState(_ body: (inout ConnectionState) -> Result) -> Result { + lock.lock() + defer { lock.unlock() } + return body(&state) + } +} + +private struct ConnectionState { + var connection: NSXPCConnection? + var host: CMUXSidebarHostXPC? + var generation: UInt64 = 0 + var pendingActions: [UUID: PendingAction] = [:] +} + +private struct PendingAction { + var generation: UInt64 + var reply: CMUXSidebarExtensionConnection.ActionReplyHandler } private final class CMUXSidebarExtensionXPCReceiver: NSObject, CMUXSidebarExtensionXPC { diff --git a/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/ExtensionPoint/CMUXSidebarExtensionPoint.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarExtensionPoint.swift similarity index 85% rename from Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/ExtensionPoint/CMUXSidebarExtensionPoint.swift rename to Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarExtensionPoint.swift index a5eae1048ccd..267bcc93c880 100644 --- a/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/ExtensionPoint/CMUXSidebarExtensionPoint.swift +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarExtensionPoint.swift @@ -2,8 +2,10 @@ public enum CMUXSidebarExtensionPoint { /// Extension point identifier third-party sidebar extensions register against. public static let identifier = "com.manaflow.cmux.sidebar" - /// StaticString form required by the modern ExtensionFoundation monitor API. + + /// StaticString form required by ExtensionFoundation monitor APIs. public static let staticIdentifier: StaticString = "com.manaflow.cmux.sidebar" + /// Default ExtensionKit scene identifier hosted inside the cmux sidebar. public static let defaultSceneID = "sidebar" } diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarSnapshot.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarSnapshot.swift index f1417e917b39..ad8e56e1a28a 100644 --- a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarSnapshot.swift +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarSnapshot.swift @@ -5,6 +5,8 @@ public struct CMUXSidebarSnapshot: Codable, Equatable, Sendable { public var sequence: UInt64 public var windowID: UUID? public var selectedWorkspaceID: UUID? + public var grantedReadScopes: Set + public var grantedActionScopes: Set public var workspaces: [CMUXSidebarWorkspace] public init( @@ -12,22 +14,43 @@ public struct CMUXSidebarSnapshot: Codable, Equatable, Sendable { sequence: UInt64, windowID: UUID? = nil, selectedWorkspaceID: UUID?, + grantedReadScopes: Set = [], + grantedActionScopes: Set = [], workspaces: [CMUXSidebarWorkspace] ) { self.apiVersion = apiVersion self.sequence = sequence self.windowID = windowID self.selectedWorkspaceID = selectedWorkspaceID + self.grantedReadScopes = grantedReadScopes + self.grantedActionScopes = grantedActionScopes self.workspaces = workspaces } - public func filtered(for scopes: some Sequence) -> CMUXSidebarSnapshot { + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + apiVersion = try container.decode(CMUXExtensionAPIVersion.self, forKey: .apiVersion) + sequence = try container.decode(UInt64.self, forKey: .sequence) + windowID = try container.decodeIfPresent(UUID.self, forKey: .windowID) + selectedWorkspaceID = try container.decodeIfPresent(UUID.self, forKey: .selectedWorkspaceID) + grantedReadScopes = try container.decodeIfPresent(Set.self, forKey: .grantedReadScopes) ?? [] + grantedActionScopes = try container.decodeIfPresent(Set.self, forKey: .grantedActionScopes) ?? [] + workspaces = try container.decode([CMUXSidebarWorkspace].self, forKey: .workspaces) + } + + public func filtered( + for scopes: some Sequence, + actionScopes: some Sequence = [] + ) -> CMUXSidebarSnapshot { let scopeSet = Set(scopes) - guard scopeSet.contains(.workspaceMetadata) else { + let actionScopeSet = Set(actionScopes) + guard scopeSet.contains(.workspaceList) || scopeSet.contains(.workspaceMetadata) else { return CMUXSidebarSnapshot( apiVersion: apiVersion, sequence: sequence, selectedWorkspaceID: nil, + grantedReadScopes: scopeSet, + grantedActionScopes: actionScopeSet, workspaces: [] ) } @@ -36,7 +59,13 @@ public struct CMUXSidebarSnapshot: Codable, Equatable, Sendable { sequence: sequence, windowID: windowID, selectedWorkspaceID: selectedWorkspaceID, - workspaces: workspaces.map { $0.filtered(for: scopeSet) } + grantedReadScopes: scopeSet, + grantedActionScopes: actionScopeSet, + workspaces: workspaces.map { workspace in + scopeSet.contains(.workspaceMetadata) + ? workspace.filtered(for: scopeSet) + : CMUXSidebarWorkspace(id: workspace.id, title: workspace.title) + } ) } } diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarSurface.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarSurface.swift new file mode 100644 index 000000000000..8d5abe699a64 --- /dev/null +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarSurface.swift @@ -0,0 +1,51 @@ +import Foundation + +public enum CMUXSidebarSurfaceKind: String, Codable, CaseIterable, Equatable, Sendable { + case terminal + case browser + case markdown + case filePreview + case rightSidebarTool + case unknown +} + +public struct CMUXSidebarSurface: Codable, Equatable, Identifiable, Sendable { + public var id: UUID + public var title: String + public var kind: CMUXSidebarSurfaceKind + public var isFocused: Bool + public var isPinned: Bool + public var unreadCount: Int + public var workingDirectory: String? + + public init( + id: UUID, + title: String, + kind: CMUXSidebarSurfaceKind = .unknown, + isFocused: Bool = false, + isPinned: Bool = false, + unreadCount: Int = 0, + workingDirectory: String? = nil + ) { + self.id = id + self.title = title + self.kind = kind + self.isFocused = isFocused + self.isPinned = isPinned + self.unreadCount = unreadCount + self.workingDirectory = workingDirectory + } + + public func filtered(for scopes: some Sequence) -> CMUXSidebarSurface { + let scopeSet = Set(scopes) + return CMUXSidebarSurface( + id: id, + title: title, + kind: kind, + isFocused: isFocused, + isPinned: isPinned, + unreadCount: unreadCount, + workingDirectory: scopeSet.contains(.workspacePaths) ? workingDirectory : nil + ) + } +} diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarWorkspace.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarWorkspace.swift index f45e3e2b9d55..2bb95267d3ca 100644 --- a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarWorkspace.swift +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarWorkspace.swift @@ -12,6 +12,7 @@ public struct CMUXSidebarWorkspace: Codable, Equatable, Identifiable, Sendable { public var latestNotification: String? public var listeningPorts: [Int] public var pullRequestURLs: [String] + public var surfaces: [CMUXSidebarSurface] public init( id: UUID, @@ -24,7 +25,8 @@ public struct CMUXSidebarWorkspace: Codable, Equatable, Identifiable, Sendable { unreadCount: Int = 0, latestNotification: String? = nil, listeningPorts: [Int] = [], - pullRequestURLs: [String] = [] + pullRequestURLs: [String] = [], + surfaces: [CMUXSidebarSurface] = [] ) { self.id = id self.title = title @@ -37,6 +39,23 @@ public struct CMUXSidebarWorkspace: Codable, Equatable, Identifiable, Sendable { self.latestNotification = latestNotification self.listeningPorts = listeningPorts self.pullRequestURLs = pullRequestURLs + self.surfaces = surfaces + } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + id = try container.decode(UUID.self, forKey: .id) + title = try container.decode(String.self, forKey: .title) + detail = try container.decodeIfPresent(String.self, forKey: .detail) + isPinned = try container.decode(Bool.self, forKey: .isPinned) + rootPath = try container.decodeIfPresent(String.self, forKey: .rootPath) + projectRootPath = try container.decodeIfPresent(String.self, forKey: .projectRootPath) + gitBranch = try container.decodeIfPresent(String.self, forKey: .gitBranch) + unreadCount = try container.decode(Int.self, forKey: .unreadCount) + latestNotification = try container.decodeIfPresent(String.self, forKey: .latestNotification) + listeningPorts = try container.decode([Int].self, forKey: .listeningPorts) + pullRequestURLs = try container.decode([String].self, forKey: .pullRequestURLs) + surfaces = try container.decodeIfPresent([CMUXSidebarSurface].self, forKey: .surfaces) ?? [] } public func filtered(for scopes: some Sequence) -> CMUXSidebarWorkspace { @@ -52,7 +71,8 @@ public struct CMUXSidebarWorkspace: Codable, Equatable, Identifiable, Sendable { unreadCount: unreadCount, latestNotification: scopeSet.contains(.notifications) ? latestNotification : nil, listeningPorts: scopeSet.contains(.networkPorts) ? listeningPorts : [], - pullRequestURLs: scopeSet.contains(.pullRequests) ? pullRequestURLs : [] + pullRequestURLs: scopeSet.contains(.pullRequests) ? pullRequestURLs : [], + surfaces: scopeSet.contains(.surfaceMetadata) ? surfaces.map { $0.filtered(for: scopeSet) } : [] ) } } diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarXPC.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarXPC.swift index 9c796d391a0c..e214c87ada72 100644 --- a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarXPC.swift +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarXPC.swift @@ -1,15 +1,16 @@ import Foundation -@objc public protocol CMUXSidebarHostXPC: NSObjectProtocol { +@_spi(CmuxHostTransport) @objc public protocol CMUXSidebarHostXPC: NSObjectProtocol { func requestSidebarSnapshot(reply: @escaping (NSData?, NSString?) -> Void) func performSidebarAction(_ payload: NSData, reply: @escaping (NSData?, NSString?) -> Void) } -@objc public protocol CMUXSidebarExtensionXPC: NSObjectProtocol { +@_spi(CmuxHostTransport) @objc public protocol CMUXSidebarExtensionXPC: NSObjectProtocol { @objc optional func requestExtensionManifest(reply: @escaping (NSData?, NSString?) -> Void) func sidebarSnapshotDidChange(_ payload: NSData) } +@_spi(CmuxHostTransport) public enum CMUXSidebarXPCCodec { public static let maximumSnapshotPayloadBytes = 512 * 1024 public static let maximumManifestPayloadBytes = 64 * 1024 diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CmuxSidebarActionCancellation.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CmuxSidebarActionCancellation.swift new file mode 100644 index 000000000000..42385b8a7e80 --- /dev/null +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CmuxSidebarActionCancellation.swift @@ -0,0 +1,17 @@ +import Foundation + +/// Cancellation handle for a host action sent from a sidebar extension. +public struct CmuxSidebarActionCancellation: Sendable { + private let cancelAction: @Sendable () -> Void + + /// Creates a cancellation handle. + /// - Parameter cancel: Work that removes the pending action from the transport. + public init(_ cancel: @escaping @Sendable () -> Void) { + self.cancelAction = cancel + } + + /// Cancels the pending host action if it is still waiting for a reply. + public func cancel() { + cancelAction() + } +} diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CmuxSidebarContext.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CmuxSidebarContext.swift new file mode 100644 index 000000000000..fddca6a39ecc --- /dev/null +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CmuxSidebarContext.swift @@ -0,0 +1,36 @@ +import Foundation + +/// Current sidebar state delivered by CMUX to a sidebar extension. +public struct CmuxSidebarContext: Sendable { + /// Latest workspace snapshot filtered to the permissions granted by the user. + public let snapshot: CMUXSidebarSnapshot + + /// Read scopes CMUX granted for this snapshot. + public let grantedReadScopes: Set + + /// Host actions CMUX will currently accept from this extension. + public let grantedActionScopes: Set + + /// Typed command channel back to CMUX. + public let host: CmuxSidebarHost + + /// Generic CMUX action channel for commands that are not sidebar-specific. + public let cmux: CmuxHost + + @MainActor + public init( + snapshot: CMUXSidebarSnapshot, + grantedReadScopes: Set? = nil, + grantedActionScopes: Set? = nil, + host: CmuxSidebarHost, + cmux: CmuxHost? = nil + ) { + self.snapshot = snapshot + self.grantedReadScopes = grantedReadScopes ?? snapshot.grantedReadScopes + self.grantedActionScopes = grantedActionScopes ?? snapshot.grantedActionScopes + self.host = host + self.cmux = cmux ?? CmuxHost { action in + await host.perform(action) + } + } +} diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CmuxSidebarExtensionRuntime.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CmuxSidebarExtensionRuntime.swift new file mode 100644 index 000000000000..70dd579df9aa --- /dev/null +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CmuxSidebarExtensionRuntime.swift @@ -0,0 +1,35 @@ +import Foundation + +final class CmuxSidebarExtensionRuntime: @unchecked Sendable { + private let sidebarExtension: Extension + private let connection: CMUXSidebarExtensionConnection + + @MainActor + init(sidebarExtension: Extension) { + self.sidebarExtension = sidebarExtension + var transport: CMUXSidebarExtensionConnection! + transport = CMUXSidebarExtensionConnection( + manifest: Extension.manifest, + onSnapshot: { [weak sidebarExtension] snapshot in + let host = CmuxSidebarHost( + performCancellableAction: { action, reply in + transport.perform(action, reply: reply) + }, + refreshSnapshot: { + transport.refreshSnapshot() + } + ) + sidebarExtension?.update(context: CmuxSidebarContext(snapshot: snapshot, host: host)) + }, + onError: { [weak sidebarExtension] message in + sidebarExtension?.connectionErrorDidChange(message) + } + ) + self.connection = transport + } + + @discardableResult + func accept(_ connection: NSXPCConnection) -> Bool { + self.connection.accept(connection) + } +} diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CmuxSidebarExtensionScene.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CmuxSidebarExtensionScene.swift new file mode 100644 index 000000000000..5dfc37730368 --- /dev/null +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CmuxSidebarExtensionScene.swift @@ -0,0 +1,49 @@ +import ExtensionFoundation +import ExtensionKit +import Foundation +import SwiftUI + +/// Creates the ExtensionKit scene for a CMUX sidebar extension. +/// +/// Most extension authors should conform their `@main` extension type to +/// `CmuxSidebarExtension` and use the protocol's default ExtensionKit +/// configuration instead of constructing this scene directly. +public struct CmuxSidebarExtensionScene: AppExtensionScene { + private let sidebarExtension: Extension + private let id: String + + /// Creates an ExtensionKit scene for a CMUX sidebar extension. + public init(_ extension: Extension, id: String = CMUXSidebarExtensionPoint.defaultSceneID) { + self.sidebarExtension = `extension` + self.id = id + } + + @MainActor + public var body: PrimitiveAppExtensionScene { + let runtime = CmuxSidebarExtensionRuntime(sidebarExtension: sidebarExtension) + let runtimeBox: AnySidebarRuntimeBox = SidebarRuntimeBox(runtime) + return PrimitiveAppExtensionScene(id: id) { + sidebarExtension.body + } onConnection: { connection in + runtimeBox.accept(connection) + } + } +} + +private final class SidebarRuntimeBox: AnySidebarRuntimeBox, @unchecked Sendable { + private let runtime: CmuxSidebarExtensionRuntime + + init(_ runtime: CmuxSidebarExtensionRuntime) { + self.runtime = runtime + } + + override func accept(_ connection: NSXPCConnection) -> Bool { + runtime.accept(connection) + } +} + +private class AnySidebarRuntimeBox: @unchecked Sendable { + func accept(_ connection: NSXPCConnection) -> Bool { + false + } +} diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CmuxSidebarHost.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CmuxSidebarHost.swift new file mode 100644 index 000000000000..d0216bfb4aa6 --- /dev/null +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CmuxSidebarHost.swift @@ -0,0 +1,196 @@ +import Foundation + +/// Typed command channel from a sidebar extension back to CMUX. +@MainActor +public struct CmuxSidebarHost { + private let performAction: @MainActor @Sendable (CMUXSidebarAction, @escaping @MainActor @Sendable (CMUXExtensionActionResult) -> Void) -> CmuxSidebarActionCancellation? + private let refreshSnapshot: @MainActor @Sendable () -> Void + + public init( + performAction: @escaping @MainActor @Sendable (CMUXSidebarAction, @escaping @MainActor @Sendable (CMUXExtensionActionResult) -> Void) -> Void, + refreshSnapshot: @escaping @MainActor @Sendable () -> Void = {} + ) { + self.performAction = { action, reply in + performAction(action, reply) + return nil + } + self.refreshSnapshot = refreshSnapshot + } + + /// Creates a typed host channel with cancellable action dispatch. + /// + /// Use this initializer when the underlying transport can remove pending + /// replies after the caller's task is cancelled. + public init( + performCancellableAction: @escaping @MainActor @Sendable (CMUXSidebarAction, @escaping @MainActor @Sendable (CMUXExtensionActionResult) -> Void) -> CmuxSidebarActionCancellation?, + refreshSnapshot: @escaping @MainActor @Sendable () -> Void = {} + ) { + self.performAction = performCancellableAction + self.refreshSnapshot = refreshSnapshot + } + + /// Requests the latest sidebar snapshot from CMUX. + public func refresh() { + refreshSnapshot() + } + + /// Selects a workspace in CMUX. + public func selectWorkspace(_ id: UUID) async -> CMUXExtensionActionResult { + await perform(.selectWorkspace(id)) + } + + /// Requests that CMUX close a workspace. + public func closeWorkspace(_ id: UUID) async -> CMUXExtensionActionResult { + await perform(.closeWorkspace(id)) + } + + /// Requests that CMUX open a web URL. + public func openURL(_ url: URL) async -> CMUXExtensionActionResult { + await perform(.openURL(url.absoluteString)) + } + + public func createTerminalSurface( + in workspaceID: UUID? = nil, + initialInput: String? = nil + ) async -> CMUXExtensionActionResult { + await perform(.createTerminalSurface(workspaceID: workspaceID, initialInput: initialInput)) + } + + public func createBrowserSurface( + in workspaceID: UUID? = nil, + url: URL? = nil + ) async -> CMUXExtensionActionResult { + await perform(.createBrowserSurface(workspaceID: workspaceID, url: url?.absoluteString)) + } + + public func selectSurface(workspaceID: UUID, surfaceID: UUID) async -> CMUXExtensionActionResult { + await perform(.selectSurface(workspaceID: workspaceID, surfaceID: surfaceID)) + } + + public func selectNextSurface() async -> CMUXExtensionActionResult { + await perform(.selectNextSurface) + } + + public func selectPreviousSurface() async -> CMUXExtensionActionResult { + await perform(.selectPreviousSurface) + } + + public func closeSurface(workspaceID: UUID, surfaceID: UUID) async -> CMUXExtensionActionResult { + await perform(.closeSurface(workspaceID: workspaceID, surfaceID: surfaceID)) + } + + public func splitTerminal( + workspaceID: UUID, + surfaceID: UUID, + direction: CMUXSplitDirection + ) async -> CMUXExtensionActionResult { + await perform(.splitTerminal(workspaceID: workspaceID, surfaceID: surfaceID, direction: direction)) + } + + public func splitBrowser( + workspaceID: UUID, + surfaceID: UUID, + direction: CMUXSplitDirection, + url: URL? = nil + ) async -> CMUXExtensionActionResult { + await perform(.splitBrowser(workspaceID: workspaceID, surfaceID: surfaceID, direction: direction, url: url?.absoluteString)) + } + + public func toggleSurfaceZoom(workspaceID: UUID, surfaceID: UUID) async -> CMUXExtensionActionResult { + await perform(.toggleSurfaceZoom(workspaceID: workspaceID, surfaceID: surfaceID)) + } + + /// Sends a raw sidebar action and returns CMUX's acceptance result. + public func perform(_ action: CMUXSidebarAction) async -> CMUXExtensionActionResult { + let replyGate = CmuxSidebarActionReplyGate() + return await withTaskCancellationHandler { + await withCheckedContinuation { continuation in + Task { @MainActor in + guard replyGate.setContinuation(continuation) else { return } + let cancellation = performAction(action) { result in + replyGate.resume(returning: result) + } + replyGate.setCancellation(cancellation) + } + } + } onCancel: { + replyGate.cancel() + } + } + + /// Sends a raw sidebar action. Prefer the async typed helpers above when possible. + public func perform( + _ action: CMUXSidebarAction, + reply: @escaping @MainActor @Sendable (CMUXExtensionActionResult) -> Void + ) { + _ = performAction(action, reply) + } +} + +private final class CmuxSidebarActionReplyGate: @unchecked Sendable { + private let lock = NSLock() + private var continuation: CheckedContinuation? + private var cancellation: CmuxSidebarActionCancellation? + private var didComplete = false + + func setContinuation(_ continuation: CheckedContinuation) -> Bool { + lock.lock() + if didComplete { + lock.unlock() + continuation.resume(returning: .rejected("Extension action was cancelled")) + return false + } + self.continuation = continuation + lock.unlock() + return true + } + + func setCancellation(_ cancellation: CmuxSidebarActionCancellation?) { + lock.lock() + if didComplete { + lock.unlock() + cancellation?.cancel() + return + } + self.cancellation = cancellation + lock.unlock() + } + + func resume(returning result: CMUXExtensionActionResult) { + let continuation = complete() + continuation?.resume(returning: result) + } + + func cancel() { + let cancellation: CmuxSidebarActionCancellation? + let continuation: CheckedContinuation? + lock.lock() + if didComplete { + lock.unlock() + return + } + didComplete = true + cancellation = self.cancellation + continuation = self.continuation + self.cancellation = nil + self.continuation = nil + lock.unlock() + + cancellation?.cancel() + continuation?.resume(returning: .rejected("Extension action was cancelled")) + } + + private func complete() -> CheckedContinuation? { + lock.lock() + if didComplete { + lock.unlock() + return nil + } + didComplete = true + let continuation = self.continuation + self.continuation = nil + self.cancellation = nil + lock.unlock() + return continuation + } +} diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Validation/CMUXExtensionValidator.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Validation/CMUXExtensionValidator.swift index 5d09f727315c..e6d5b477309f 100644 --- a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Validation/CMUXExtensionValidator.swift +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Validation/CMUXExtensionValidator.swift @@ -1,24 +1,23 @@ import Foundation -public enum CMUXExtensionValidator { - public static func validateSidebarManifest( - _ manifest: CMUXExtensionManifest, - supportedAPIVersion: CMUXExtensionAPIVersion = .sidebarV1 - ) throws { - guard manifest.id.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == false else { - throw CMUXExtensionValidationError.emptyIdentifier - } - guard manifest.displayName.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == false else { - throw CMUXExtensionValidationError.emptyDisplayName - } - guard manifest.kind == .sidebar else { - throw CMUXExtensionValidationError.unsupportedKind(manifest.kind) - } - guard manifest.minimumAPIVersion <= supportedAPIVersion else { - throw CMUXExtensionValidationError.unsupportedAPIVersion( - requested: manifest.minimumAPIVersion, - supported: supportedAPIVersion - ) - } +/// Validates a sidebar extension manifest before CMUX trusts it. +public func validateSidebarManifest( + _ manifest: CMUXExtensionManifest, + supportedAPIVersion: CMUXExtensionAPIVersion = .sidebarV1 +) throws { + guard manifest.id.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == false else { + throw CMUXExtensionValidationError.emptyIdentifier + } + guard manifest.displayName.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty == false else { + throw CMUXExtensionValidationError.emptyDisplayName + } + guard manifest.kind == .sidebar else { + throw CMUXExtensionValidationError.unsupportedKind(manifest.kind) + } + guard manifest.minimumAPIVersion <= supportedAPIVersion else { + throw CMUXExtensionValidationError.unsupportedAPIVersion( + requested: manifest.minimumAPIVersion, + supported: supportedAPIVersion + ) } } diff --git a/Packages/CmuxExtensionKit/Tests/CmuxExtensionKitTests/CmuxExtensionKitTests.swift b/Packages/CmuxExtensionKit/Tests/CmuxExtensionKitTests/CmuxExtensionKitTests.swift index a7fc7d649330..15446c33ac7b 100644 --- a/Packages/CmuxExtensionKit/Tests/CmuxExtensionKitTests/CmuxExtensionKitTests.swift +++ b/Packages/CmuxExtensionKit/Tests/CmuxExtensionKitTests/CmuxExtensionKitTests.swift @@ -1,6 +1,6 @@ import Foundation import Testing -@testable import CmuxExtensionKit +@_spi(CmuxHostTransport) @testable import CmuxExtensionKit @Suite struct CMUXExtensionKitTests { @@ -11,6 +11,8 @@ struct CMUXExtensionKitTests { sequence: 42, windowID: UUID(uuidString: "22222222-2222-2222-2222-222222222222")!, selectedWorkspaceID: workspaceID, + grantedReadScopes: [.workspaceMetadata, .workspacePaths, .notifications, .networkPorts, .pullRequests], + grantedActionScopes: [.selectWorkspace], workspaces: [ CMUXSidebarWorkspace( id: workspaceID, @@ -33,6 +35,8 @@ struct CMUXExtensionKitTests { #expect(decoded == snapshot) #expect(decoded.apiVersion == CMUXExtensionAPIVersion.sidebarV1) + #expect(decoded.grantedReadScopes.contains(.workspaceMetadata)) + #expect(decoded.grantedActionScopes == [.selectWorkspace]) } @Test @@ -44,7 +48,7 @@ struct CMUXExtensionKitTests { requestedActionScopes: [.selectWorkspace, .openURL] ) - try CMUXExtensionValidator.validateSidebarManifest(manifest) + try validateSidebarManifest(manifest) } @Test @@ -63,7 +67,7 @@ struct CMUXExtensionKitTests { #expect(manifest.requestedScopes == [.workspaceMetadata]) #expect(manifest.requestedActionScopes.isEmpty) - try CMUXExtensionValidator.validateSidebarManifest(manifest) + try validateSidebarManifest(manifest) } @Test @@ -73,9 +77,9 @@ struct CMUXExtensionKitTests { displayName: "Example Sidebar" ) - #expect(manifest.requestedScopes == [.workspaceMetadata]) + #expect(manifest.requestedScopes.isEmpty) #expect(manifest.requestedActionScopes.isEmpty) - try CMUXExtensionValidator.validateSidebarManifest(manifest) + try validateSidebarManifest(manifest) } @Test @@ -104,6 +108,8 @@ struct CMUXExtensionKitTests { let filtered = snapshot.filtered(for: [CMUXExtensionScope.workspaceMetadata]) let workspace = try #require(filtered.workspaces.first) + #expect(filtered.grantedReadScopes == [.workspaceMetadata]) + #expect(filtered.grantedActionScopes.isEmpty) #expect(workspace.id == workspaceID) #expect(workspace.title == "Build") #expect(workspace.detail == "Running tests") @@ -147,9 +153,29 @@ struct CMUXExtensionKitTests { #expect(filtered.sequence == 45) #expect(filtered.windowID == nil) #expect(filtered.selectedWorkspaceID == nil) + #expect(filtered.grantedReadScopes.isEmpty) + #expect(filtered.grantedActionScopes.isEmpty) #expect(filtered.workspaces.isEmpty) } + @Test + func testSidebarSnapshotDecodingDefaultsMissingGrantedScopes() throws { + let payload = Data(""" + { + "apiVersion": { "major": 1, "minor": 0 }, + "sequence": 50, + "selectedWorkspaceID": null, + "workspaces": [] + } + """.utf8) + + let snapshot = try JSONDecoder().decode(CMUXSidebarSnapshot.self, from: payload) + + #expect(snapshot.sequence == 50) + #expect(snapshot.grantedReadScopes.isEmpty) + #expect(snapshot.grantedActionScopes.isEmpty) + } + @Test func testSidebarXPCCodecRoundTripsSnapshotActionAndResult() throws { let workspaceID = UUID(uuidString: "33333333-3333-3333-3333-333333333333")! @@ -177,6 +203,12 @@ struct CMUXExtensionKitTests { ) #expect(decodedSnapshot == snapshot) + let actionScopedSnapshot = snapshot.filtered( + for: [CMUXExtensionScope.workspaceMetadata], + actionScopes: [CMUXExtensionActionScope.selectWorkspace] + ) + #expect(actionScopedSnapshot.grantedActionScopes == [.selectWorkspace]) + let manifest = CMUXExtensionManifest( id: "dev.example.sidebar", displayName: "Example Sidebar", @@ -202,6 +234,66 @@ struct CMUXExtensionKitTests { #expect(decodedResult == result) } + @Test + @MainActor + func testSidebarHostTypedHelpersSendExpectedActions() async { + var actions = [CMUXSidebarAction]() + var refreshCount = 0 + let workspaceID = UUID(uuidString: "77777777-7777-7777-7777-777777777777")! + let url = URL(string: "https://example.com/pr/1")! + let host = CmuxSidebarHost( + performAction: { action, reply in + actions.append(action) + reply(CMUXExtensionActionResult(accepted: true)) + }, + refreshSnapshot: { + refreshCount += 1 + } + ) + + host.refresh() + let selectResult = await host.selectWorkspace(workspaceID) + let closeResult = await host.closeWorkspace(workspaceID) + let openResult = await host.openURL(url) + + #expect(refreshCount == 1) + #expect(selectResult.accepted) + #expect(closeResult.accepted) + #expect(openResult.accepted) + #expect(actions == [ + .selectWorkspace(workspaceID), + .closeWorkspace(workspaceID), + .openURL("https://example.com/pr/1"), + ]) + } + + @Test + @MainActor + func testSidebarHostCancelsPendingAsyncAction() async { + let cancellationBox = CancellationBox() + let startBox = ActionStartBox() + let workspaceID = UUID(uuidString: "88888888-8888-8888-8888-888888888888")! + let host = CmuxSidebarHost( + performCancellableAction: { _, _ in + startBox.markStarted() + return CmuxSidebarActionCancellation { + cancellationBox.cancel() + } + } + ) + + let task = Task { @MainActor in + await host.selectWorkspace(workspaceID) + } + await startBox.waitUntilStarted() + task.cancel() + let result = await task.value + + #expect(!result.accepted) + #expect(result.message == "Extension action was cancelled") + #expect(cancellationBox.didCancel) + } + @Test func testSidebarXPCCodecRejectsOversizedManifestPayload() { let payload = Data(repeating: 0x20, count: CMUXSidebarXPCCodec.maximumManifestPayloadBytes + 1) as NSData @@ -321,7 +413,7 @@ struct CMUXExtensionKitTests { ) do { - try CMUXExtensionValidator.validateSidebarManifest(manifest) + try validateSidebarManifest(manifest) Issue.record("Expected unsupported API version error") } catch { #expect( @@ -333,3 +425,48 @@ struct CMUXExtensionKitTests { } } } + +private final class CancellationBox: @unchecked Sendable { + private let lock = NSLock() + private var storage = false + + var didCancel: Bool { + lock.lock() + defer { lock.unlock() } + return storage + } + + func cancel() { + lock.lock() + storage = true + lock.unlock() + } +} + +private final class ActionStartBox: @unchecked Sendable { + private let lock = NSLock() + private var continuation: CheckedContinuation? + private var started = false + + func waitUntilStarted() async { + await withCheckedContinuation { continuation in + lock.lock() + if started { + lock.unlock() + continuation.resume() + return + } + self.continuation = continuation + lock.unlock() + } + } + + func markStarted() { + lock.lock() + started = true + let continuation = continuation + self.continuation = nil + lock.unlock() + continuation?.resume() + } +} diff --git a/Sources/AppDelegate.swift b/Sources/AppDelegate.swift index ac3778d2d1b4..ee67127e449f 100644 --- a/Sources/AppDelegate.swift +++ b/Sources/AppDelegate.swift @@ -11261,6 +11261,10 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent windowDecorationsController.apply(to: window) } + func updateTitlebarAccessorySidebarTrailingEdge(_ edge: CGFloat, for window: NSWindow) { + titlebarAccessoryController.updateSidebarTrailingEdge(edge, for: window) + } + func toggleNotificationsPopover(animated: Bool = true, anchorView: NSView? = nil) { titlebarAccessoryController.toggleNotificationsPopover(animated: animated, anchorView: anchorView) } diff --git a/Sources/CMUXInstalledExtensionSidebarHostView.swift b/Sources/CMUXInstalledExtensionSidebarHostView.swift index 1d7eb765c8a3..00643279f230 100644 --- a/Sources/CMUXInstalledExtensionSidebarHostView.swift +++ b/Sources/CMUXInstalledExtensionSidebarHostView.swift @@ -1,5 +1,5 @@ -import CMUXExtensionClient -import CmuxExtensionKit +@_spi(CmuxHostTransport) import CMUXExtensionClient +@_spi(CmuxHostTransport) import CmuxExtensionKit import ExtensionFoundation import Observation import SwiftUI @@ -29,7 +29,7 @@ private struct CMUXSidebarExtensionEffectiveGrant: Equatable { } private struct CMUXSidebarExtensionGrantStore { - static let defaultReadScopes: Set = [.workspaceMetadata] + static let defaultReadScopes: Set = [] static let defaultActionScopes: Set = [] private static let defaultsKey = "cmuxExtensionSidebar.grants.v1" @@ -105,8 +105,35 @@ private struct CMUXSidebarExtensionGrantStore { } } +private struct CMUXSidebarExtensionLimitedChoiceStore { + private static let defaultsKey = "cmuxExtensionSidebar.limitedChoices.v1" + + var defaults: UserDefaults = .standard + + func choices() -> Set { + Set(defaults.stringArray(forKey: Self.defaultsKey) ?? []) + } + + func insert(_ key: String) { + var choices = choices() + choices.insert(key) + save(choices) + } + + func remove(_ key: String) { + var choices = choices() + choices.remove(key) + save(choices) + } + + private func save(_ choices: Set) { + defaults.set(choices.sorted(), forKey: Self.defaultsKey) + } +} + struct CMUXInstalledExtensionSidebarHostView: View { private static let selectedExtensionBundleIDDefaultsKey = "cmuxExtensionSidebar.selectedExtensionBundleId" + private static let selectedExtensionNameDefaultsKey = "cmuxExtensionSidebar.selectedExtensionName" var snapshotProvider: @MainActor () -> CMUXSidebarSnapshot var snapshotUpdateToken: UInt64 = 0 @@ -127,6 +154,8 @@ struct CMUXInstalledExtensionSidebarHostView: View { @State private var effectiveGrant: CMUXSidebarExtensionEffectiveGrant? @State private var blockedManifestReason: String? @State private var isShowingExtensionDetails = false + @State private var isShowingAccessReview = false + @State private var keptLimitedManifestKeys = CMUXSidebarExtensionLimitedChoiceStore().choices() @State private var hostReloadToken: UInt64 = 0 var body: some View { @@ -134,7 +163,7 @@ struct CMUXInstalledExtensionSidebarHostView: View { if let identity { VStack(alignment: .leading, spacing: 0) { extensionControlStrip(activeIdentity: identity) - if let effectiveGrant, effectiveGrant.needsAdditionalApproval { + if let effectiveGrant, shouldShowAccessBanner(identity: identity, effectiveGrant: effectiveGrant) { extensionAccessBanner(identity: identity, effectiveGrant: effectiveGrant) } CMUXSidebarExtensionHostView( @@ -156,9 +185,8 @@ struct CMUXInstalledExtensionSidebarHostView: View { onDeactivation: { error in xpcHost.invalidate() effectiveGrant = nil - blockedManifestReason = nil if self.identity?.bundleIdentifier == identity.bundleIdentifier { - self.identity = nil + blockedManifestReason = "connectionInterrupted" } errorText = error?.localizedDescription }, @@ -221,6 +249,11 @@ struct CMUXInstalledExtensionSidebarHostView: View { .onDisappear { xpcHost.invalidate() } + .sheet(isPresented: $isShowingAccessReview) { + if let identity, let effectiveGrant { + accessReviewSheet(identity: identity, effectiveGrant: effectiveGrant) + } + } } private func observeExtensionAvailability() async { @@ -341,22 +374,6 @@ struct CMUXInstalledExtensionSidebarHostView: View { .popover(isPresented: $isShowingExtensionDetails, arrowEdge: .top) { extensionDetailsPopover(activeIdentity: activeIdentity) } - Button { - onUseDefaultSidebar() - } label: { - Image(systemName: "sidebar.left") - } - .buttonStyle(.plain) - .controlSize(.small) - .help(String(localized: "sidebar.extensions.useDefault", defaultValue: "Use Workspace Sidebar")) - Button { - presentExtensionBrowser() - } label: { - Image(systemName: "puzzlepiece.extension") - } - .buttonStyle(.plain) - .controlSize(.small) - .help(String(localized: "sidebar.extensions.manage", defaultValue: "Manage Sidebar Extensions...")) } .padding(.horizontal, 12) .padding(.top, SidebarWorkspaceScrollInsets.workspaceList.top + 8) @@ -418,10 +435,8 @@ struct CMUXInstalledExtensionSidebarHostView: View { VStack(alignment: .leading, spacing: 8) { if let activeIdentity, let effectiveGrant { HStack(spacing: 8) { - Button(String(localized: "sidebar.extensions.access.grant", defaultValue: "Grant Requested Access")) { - xpcHost.grantRequestedAccess(bundleIdentifier: activeIdentity.bundleIdentifier) - self.effectiveGrant = xpcHost.currentEffectiveGrant - xpcHost.sendSnapshotDidChange() + Button(String(localized: "sidebar.extensions.access.review", defaultValue: "Review Access...")) { + isShowingAccessReview = true } .controlSize(.small) .disabled(!effectiveGrant.needsAdditionalApproval) @@ -638,7 +653,7 @@ struct CMUXInstalledExtensionSidebarHostView: View { .font(.system(size: 12, weight: .semibold)) .foregroundStyle(.primary) Text(String.localizedStringWithFormat( - String(localized: "sidebar.extensions.access.detail", defaultValue: "%@ is using metadata-only access until you grant its requested data and actions."), + String(localized: "sidebar.extensions.access.detail", defaultValue: "%@ will not receive workspace data or run actions until you grant its requested access."), effectiveGrant.manifest.displayName )) .font(.system(size: 11)) @@ -655,31 +670,118 @@ struct CMUXInstalledExtensionSidebarHostView: View { .padding(.top, 2) HStack(spacing: 8) { Button { - xpcHost.grantRequestedAccess(bundleIdentifier: identity.bundleIdentifier) - self.effectiveGrant = xpcHost.currentEffectiveGrant - xpcHost.sendSnapshotDidChange() + isShowingAccessReview = true } label: { - Text(String(localized: "sidebar.extensions.access.grant", defaultValue: "Grant Requested Access")) + Text(String(localized: "sidebar.extensions.access.review", defaultValue: "Review Access...")) } .controlSize(.small) - if effectiveGrant.hasSensitiveAccess { - Button { - xpcHost.revokeSensitiveAccess(bundleIdentifier: identity.bundleIdentifier) - self.effectiveGrant = xpcHost.currentEffectiveGrant - xpcHost.sendSnapshotDidChange() - } label: { - Text(String(localized: "sidebar.extensions.access.keepLimited", defaultValue: "Keep Limited")) - } - .controlSize(.small) + Button { + keepLimitedAccess(identity: identity, effectiveGrant: effectiveGrant) + } label: { + Text(String(localized: "sidebar.extensions.access.keepLimited", defaultValue: "Keep Limited")) } + .controlSize(.small) } } .padding(.horizontal, 12) - .padding(.top, SidebarWorkspaceScrollInsets.workspaceList.top + 8) + .padding(.top, 8) .padding(.bottom, 10) .background(Color(nsColor: .controlBackgroundColor).opacity(0.88)) } + private func accessReviewSheet( + identity: AppExtensionIdentity, + effectiveGrant: CMUXSidebarExtensionEffectiveGrant + ) -> some View { + VStack(alignment: .leading, spacing: 14) { + HStack(spacing: 10) { + Image(systemName: "puzzlepiece.extension") + .font(.system(size: 22, weight: .medium)) + VStack(alignment: .leading, spacing: 2) { + Text(String.localizedStringWithFormat( + String(localized: "sidebar.extensions.access.review.title", defaultValue: "Review access for %@"), + effectiveGrant.manifest.displayName + )) + .font(.system(size: 15, weight: .semibold)) + Text(identity.bundleIdentifier) + .font(.system(size: 11)) + .foregroundStyle(.secondary) + .textSelection(.enabled) + } + } + + Text(String(localized: "sidebar.extensions.access.review.detail", defaultValue: "CMUX will only share the following data and actions if you allow this request.")) + .font(.system(size: 12)) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + + VStack(alignment: .leading, spacing: 8) { + detailRow( + title: String(localized: "sidebar.extensions.details.manifest", defaultValue: "Manifest"), + value: "\(effectiveGrant.manifest.id) · API \(effectiveGrant.manifest.minimumAPIVersion.major).\(effectiveGrant.manifest.minimumAPIVersion.minor)" + ) + Divider() + permissionSection(effectiveGrant: effectiveGrant) + } + + HStack(spacing: 8) { + Spacer() + Button(String(localized: "sidebar.extensions.access.keepLimited", defaultValue: "Keep Limited")) { + keepLimitedAccess(identity: identity, effectiveGrant: effectiveGrant) + isShowingAccessReview = false + } + .keyboardShortcut(.cancelAction) + Button(String(localized: "sidebar.extensions.access.allow", defaultValue: "Allow Requested Access")) { + grantRequestedAccess(identity: identity, effectiveGrant: effectiveGrant) + isShowingAccessReview = false + } + .keyboardShortcut(.defaultAction) + } + } + .padding(18) + .frame(width: 420, alignment: .leading) + } + + private func shouldShowAccessBanner( + identity: AppExtensionIdentity, + effectiveGrant: CMUXSidebarExtensionEffectiveGrant + ) -> Bool { + effectiveGrant.needsAdditionalApproval && !keptLimitedManifestKeys.contains(limitedChoiceKey(identity: identity, effectiveGrant: effectiveGrant)) + } + + private func grantRequestedAccess( + identity: AppExtensionIdentity, + effectiveGrant: CMUXSidebarExtensionEffectiveGrant + ) { + let key = limitedChoiceKey(identity: identity, effectiveGrant: effectiveGrant) + keptLimitedManifestKeys.remove(key) + CMUXSidebarExtensionLimitedChoiceStore().remove(key) + xpcHost.grantRequestedAccess(bundleIdentifier: identity.bundleIdentifier) + self.effectiveGrant = xpcHost.currentEffectiveGrant + xpcHost.sendSnapshotDidChange() + } + + private func keepLimitedAccess( + identity: AppExtensionIdentity, + effectiveGrant: CMUXSidebarExtensionEffectiveGrant + ) { + let key = limitedChoiceKey(identity: identity, effectiveGrant: effectiveGrant) + keptLimitedManifestKeys.insert(key) + CMUXSidebarExtensionLimitedChoiceStore().insert(key) + xpcHost.revokeSensitiveAccess(bundleIdentifier: identity.bundleIdentifier) + self.effectiveGrant = xpcHost.currentEffectiveGrant + xpcHost.sendSnapshotDidChange() + } + + private func limitedChoiceKey( + identity: AppExtensionIdentity, + effectiveGrant: CMUXSidebarExtensionEffectiveGrant + ) -> String { + let readScopes = effectiveGrant.manifest.requestedScopes.map(\.rawValue).sorted().joined(separator: ",") + let actionScopes = effectiveGrant.manifest.requestedActionScopes.map(\.rawValue).sorted().joined(separator: ",") + return "\(identity.bundleIdentifier)|\(effectiveGrant.manifest.id)|\(effectiveGrant.manifest.minimumAPIVersion.major).\(effectiveGrant.manifest.minimumAPIVersion.minor)|\(readScopes)|\(actionScopes)" + } + private func pendingPermissionDescriptions( effectiveGrant: CMUXSidebarExtensionEffectiveGrant ) -> [String] { @@ -695,8 +797,12 @@ struct CMUXInstalledExtensionSidebarHostView: View { private func permissionDescription(scope: CMUXExtensionScope) -> String { switch scope { + case .workspaceList: + return String(localized: "sidebar.extensions.permission.workspaceList.detail", defaultValue: "Read workspace IDs and names") case .workspaceMetadata: return String(localized: "sidebar.extensions.permission.workspaceMetadata.detail", defaultValue: "Read workspace names, branches, unread counts, and selection") + case .surfaceMetadata: + return String(localized: "sidebar.extensions.permission.surfaceMetadata.detail", defaultValue: "Read surfaces nested inside each workspace") case .workspacePaths: return String(localized: "sidebar.extensions.permission.workspacePaths.detail", defaultValue: "Read local workspace and project paths") case .notifications: @@ -710,10 +816,26 @@ struct CMUXInstalledExtensionSidebarHostView: View { private func permissionDescription(actionScope: CMUXExtensionActionScope) -> String { switch actionScope { + case .createWorkspace: + return String(localized: "sidebar.extensions.permission.createWorkspace.detail", defaultValue: "Create workspaces") case .selectWorkspace: return String(localized: "sidebar.extensions.permission.selectWorkspace.detail", defaultValue: "Select a workspace when you click in the extension") case .closeWorkspace: return String(localized: "sidebar.extensions.permission.closeWorkspace.detail", defaultValue: "Close workspaces from the extension") + case .createSurface: + return String(localized: "sidebar.extensions.permission.createSurface.detail", defaultValue: "Create terminal and browser surfaces") + case .selectSurface: + return String(localized: "sidebar.extensions.permission.selectSurface.detail", defaultValue: "Select surfaces inside a workspace") + case .closeSurface: + return String(localized: "sidebar.extensions.permission.closeSurface.detail", defaultValue: "Close surfaces inside a workspace") + case .splitSurface: + return String(localized: "sidebar.extensions.permission.splitSurface.detail", defaultValue: "Create split surfaces") + case .zoomSurface: + return String(localized: "sidebar.extensions.permission.zoomSurface.detail", defaultValue: "Toggle surface zoom") + case .navigateWorkspace: + return String(localized: "sidebar.extensions.permission.navigateWorkspace.detail", defaultValue: "Navigate between workspaces") + case .navigateSurface: + return String(localized: "sidebar.extensions.permission.navigateSurface.detail", defaultValue: "Navigate between surfaces") case .openURL: return String(localized: "sidebar.extensions.permission.openURL.detail", defaultValue: "Open links from the extension") } @@ -754,19 +876,20 @@ struct CMUXInstalledExtensionSidebarHostView: View { } private func applyEnabledExtensionIdentities(_ identities: [AppExtensionIdentity]) { - let sortedIdentities = identities.sorted { $0.localizedName < $1.localizedName } + let sortedIdentities = deduplicatedExtensionIdentities(identities) enabledIdentities = sortedIdentities let nextIdentity: AppExtensionIdentity? if let selectedExtensionBundleID, let selectedIdentity = sortedIdentities.first(where: { $0.bundleIdentifier == selectedExtensionBundleID }) { nextIdentity = selectedIdentity - } else if sortedIdentities.count == 1 { + } else if selectedExtensionBundleID == nil, sortedIdentities.count == 1 { nextIdentity = sortedIdentities[0] selectedExtensionBundleID = nextIdentity?.bundleIdentifier UserDefaults.standard.set(nextIdentity?.bundleIdentifier, forKey: Self.selectedExtensionBundleIDDefaultsKey) } else { nextIdentity = nil } + updateSelectedExtensionName(nextIdentity) if nextIdentity?.bundleIdentifier != identity?.bundleIdentifier { xpcHost.invalidate() effectiveGrant = nil @@ -776,12 +899,34 @@ struct CMUXInstalledExtensionSidebarHostView: View { errorText = nil } + private func deduplicatedExtensionIdentities(_ identities: [AppExtensionIdentity]) -> [AppExtensionIdentity] { + let sortedIdentities = identities.sorted { + if $0.localizedName == $1.localizedName { + return $0.bundleIdentifier < $1.bundleIdentifier + } + return $0.localizedName < $1.localizedName + } + var seenBundleIdentifiers = Set() + return sortedIdentities.filter { identity in + seenBundleIdentifiers.insert(identity.bundleIdentifier).inserted + } + } + private func selectExtension(_ selectedIdentity: AppExtensionIdentity) { selectedExtensionBundleID = selectedIdentity.bundleIdentifier UserDefaults.standard.set(selectedIdentity.bundleIdentifier, forKey: Self.selectedExtensionBundleIDDefaultsKey) + UserDefaults.standard.set(selectedIdentity.localizedName, forKey: Self.selectedExtensionNameDefaultsKey) applyEnabledExtensionIdentities(enabledIdentities) } + private func updateSelectedExtensionName(_ selectedIdentity: AppExtensionIdentity?) { + if let selectedIdentity { + UserDefaults.standard.set(selectedIdentity.localizedName, forKey: Self.selectedExtensionNameDefaultsKey) + } else if selectedExtensionBundleID == nil { + UserDefaults.standard.removeObject(forKey: Self.selectedExtensionNameDefaultsKey) + } + } + @available(macOS 26.0, *) private func applyModernExtensionState(_ state: AppExtensionPoint.Monitor.State) { disabledExtensionCount = state.disabledCount @@ -849,8 +994,12 @@ private final class MonitorContinuationBox: @unchecked Sendable { private extension CMUXExtensionScope { var displayName: String { switch self { + case .workspaceList: + return String(localized: "sidebar.extensions.scope.workspaceList", defaultValue: "Workspace list") case .workspaceMetadata: return String(localized: "sidebar.extensions.scope.workspaceMetadata", defaultValue: "Workspace metadata") + case .surfaceMetadata: + return String(localized: "sidebar.extensions.scope.surfaceMetadata", defaultValue: "Surface metadata") case .workspacePaths: return String(localized: "sidebar.extensions.scope.workspacePaths", defaultValue: "Workspace paths") case .notifications: @@ -866,10 +1015,26 @@ private extension CMUXExtensionScope { private extension CMUXExtensionActionScope { var displayName: String { switch self { + case .createWorkspace: + return String(localized: "sidebar.extensions.actionScope.createWorkspace", defaultValue: "Create workspaces") case .selectWorkspace: return String(localized: "sidebar.extensions.actionScope.selectWorkspace", defaultValue: "Select workspaces") case .closeWorkspace: return String(localized: "sidebar.extensions.actionScope.closeWorkspace", defaultValue: "Close workspaces") + case .createSurface: + return String(localized: "sidebar.extensions.actionScope.createSurface", defaultValue: "Create surfaces") + case .selectSurface: + return String(localized: "sidebar.extensions.actionScope.selectSurface", defaultValue: "Select surfaces") + case .closeSurface: + return String(localized: "sidebar.extensions.actionScope.closeSurface", defaultValue: "Close surfaces") + case .splitSurface: + return String(localized: "sidebar.extensions.actionScope.splitSurface", defaultValue: "Split surfaces") + case .zoomSurface: + return String(localized: "sidebar.extensions.actionScope.zoomSurface", defaultValue: "Zoom surfaces") + case .navigateWorkspace: + return String(localized: "sidebar.extensions.actionScope.navigateWorkspace", defaultValue: "Navigate workspaces") + case .navigateSurface: + return String(localized: "sidebar.extensions.actionScope.navigateSurface", defaultValue: "Navigate surfaces") case .openURL: return String(localized: "sidebar.extensions.actionScope.openURL", defaultValue: "Open URLs") } @@ -1021,7 +1186,7 @@ private final class CMUXSidebarExtensionHostXPC { if let payload { do { let manifest = try CMUXSidebarXPCCodec.decodeManifest(payload) - try CMUXExtensionValidator.validateSidebarManifest(manifest) + try validateSidebarManifest(manifest) self.applyManifest(manifest) } catch { self.blockUntrustedExtension(reason: "invalidManifest") @@ -1097,7 +1262,7 @@ private final class CMUXSidebarExtensionHostXPC { } private func filteredSnapshot(from snapshotProvider: () -> CMUXSidebarSnapshot) -> CMUXSidebarSnapshot { - snapshotProvider().filtered(for: allowedScopes) + snapshotProvider().filtered(for: allowedScopes, actionScopes: allowedActionScopes) } private func updateExportedSnapshotFilter() { diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index dd87ea9a0f82..7a20274b453e 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -1701,6 +1701,14 @@ struct ContentView: View { ) } + private func syncTitlebarControlsSidebarTrailingEdge() { + guard let observedWindow else { return } + AppDelegate.shared?.updateTitlebarAccessorySidebarTrailingEdge( + sidebarState.isVisible ? normalizedSidebarWidth(sidebarWidth) : 0, + for: observedWindow + ) + } + private func resolvedRightSidebarAvailableWidth(_ availableWidth: CGFloat? = nil) -> CGFloat { if let availableWidth { return availableWidth @@ -2296,9 +2304,6 @@ struct ContentView: View { anchorView: fullscreenControlsViewModel.notificationsAnchorView ) }, - onShowSidebarProviderMenu: { anchorView in - CmuxExtensionSidebarSelection.showMenu(anchorView: anchorView, event: nil) - }, onNewTab: { AppDelegate.shared?.performNewWorkspaceAction( tabManager: tabManager, @@ -2692,6 +2697,7 @@ struct ContentView: View { if abs(sidebarWidth - restoredWidth) > 0.5 { sidebarWidth = restoredWidth } + syncTitlebarControlsSidebarTrailingEdge() if abs(sidebarState.persistedWidth - restoredWidth) > 0.5 { sidebarState.persistedWidth = restoredWidth } @@ -3170,6 +3176,7 @@ struct ContentView: View { sidebarWidth = sanitized return } + syncTitlebarControlsSidebarTrailingEdge() if abs(sidebarState.persistedWidth - sanitized) > 0.5 { sidebarState.persistedWidth = sanitized } @@ -3192,6 +3199,7 @@ struct ContentView: View { schedulePortalGeometrySynchronize() updateSidebarResizerBandState() syncTrafficLightInset() + syncTitlebarControlsSidebarTrailingEdge() }) view = AnyView(view.onChange(of: fileExplorerState.isVisible) { isVisible in @@ -3282,6 +3290,7 @@ struct ContentView: View { syncCommandPaletteDebugStateForObservedWindow() installSidebarResizerPointerMonitorIfNeeded() updateSidebarResizerBandState() + syncTitlebarControlsSidebarTrailingEdge() } } @@ -9852,7 +9861,8 @@ private extension String { enum CmuxExtensionSidebarSelection { static let defaultsKey = "cmuxExtensionSidebar.providerId" - static let defaultProviderId = CmuxExtensionSidebarProviderID.defaultWorkspaces + static let selectedExtensionNameDefaultsKey = "cmuxExtensionSidebar.selectedExtensionName" + static let defaultProviderId = CmuxExtensionSidebarProviderDescriptor.defaultWorkspacesID static let hostedExtensionsProviderId = "cmux.sidebar.extensions" static var providers: [any CmuxExtensionSidebarProvider] { @@ -9863,19 +9873,24 @@ enum CmuxExtensionSidebarSelection { [.defaultWorkspaces, hostedExtensionsDescriptor] + providers.map { $0.descriptor } } - static let hostedExtensionsDescriptor = CmuxExtensionSidebarProviderDescriptor( - id: hostedExtensionsProviderId, - title: CmuxExtensionLocalizedText( - key: "sidebar.provider.extensions.title", - defaultValue: "Extension Sidebar" - ), - subtitle: CmuxExtensionLocalizedText( - key: "sidebar.provider.extensions.subtitle", - defaultValue: "Custom sidebar" - ), - systemImageName: "puzzlepiece.extension", - isHostProvided: true - ) + static var hostedExtensionsDescriptor: CmuxExtensionSidebarProviderDescriptor { + let selectedName = UserDefaults.standard.string(forKey: selectedExtensionNameDefaultsKey)?.nilIfEmpty + return CmuxExtensionSidebarProviderDescriptor( + id: hostedExtensionsProviderId, + title: CmuxExtensionLocalizedText( + key: "sidebar.provider.extensions.title", + defaultValue: selectedName ?? String(localized: "sidebar.provider.extensions.title", defaultValue: "Extension Sidebar") + ), + subtitle: CmuxExtensionLocalizedText( + key: "sidebar.provider.extensions.subtitle", + defaultValue: selectedName == nil + ? String(localized: "sidebar.provider.extensions.subtitle", defaultValue: "Custom sidebar") + : String(localized: "sidebar.provider.extensions.selectedSubtitle", defaultValue: "Sidebar extension") + ), + systemImageName: "puzzlepiece.extension", + isHostProvided: true + ) + } static func descriptor(for providerId: String) -> CmuxExtensionSidebarProviderDescriptor { descriptors.first { $0.id == providerId } ?? .defaultWorkspaces @@ -9948,7 +9963,6 @@ private final class CmuxExtensionSidebarMenuTarget: NSObject { @objc func manageExtensions(_ sender: NSMenuItem) { guard let anchorView = sender.representedObject as? NSView else { return } - CmuxExtensionSidebarSelection.setProviderId(CmuxExtensionSidebarSelection.hostedExtensionsProviderId) CMUXSidebarExtensionBrowserPresenter.present( from: anchorView, title: String(localized: "sidebar.extensions.browser.title", defaultValue: "Sidebar Extensions") @@ -10365,7 +10379,7 @@ struct VerticalTabsSidebar: View { ) ZStack(alignment: .bottomLeading) { - if CmuxExtensionSidebarSelection.descriptor(for: selectedExtensionSidebarProviderId).id == CmuxExtensionSidebarProviderID.defaultWorkspaces { + if CmuxExtensionSidebarSelection.descriptor(for: selectedExtensionSidebarProviderId).id == CmuxExtensionSidebarProviderDescriptor.defaultWorkspacesID { workspaceScrollArea(renderContext: renderContext) } else { extensionSidebarScrollArea(renderContext: renderContext) @@ -10644,7 +10658,7 @@ struct VerticalTabsSidebar: View { snapshotUpdateToken: extensionSidebarUpdateToken, actionHandler: { handleCMUXSidebarExtensionAction($0) }, onUseDefaultSidebar: { - CmuxExtensionSidebarSelection.setProviderId(CmuxExtensionSidebarProviderID.defaultWorkspaces) + CmuxExtensionSidebarSelection.setProviderId(CmuxExtensionSidebarProviderDescriptor.defaultWorkspacesID) } ) .onReceive( @@ -10868,22 +10882,63 @@ struct VerticalTabsSidebar: View { rootPath: workspace.rootPath, projectRootPath: workspace.projectRootPath, gitBranch: workspace.branchSummary, - unreadCount: workspace.unreadCount, - latestNotification: workspace.latestNotificationText, - listeningPorts: workspace.listeningPorts, - pullRequestURLs: workspace.pullRequestURLs - ) - } - ) + unreadCount: workspace.unreadCount, + latestNotification: workspace.latestNotificationText, + listeningPorts: workspace.listeningPorts, + pullRequestURLs: workspace.pullRequestURLs, + surfaces: cmuxSidebarSurfaces(for: workspace) + ) + } + ) + } + + private func cmuxSidebarSurfaces(for workspace: CmuxExtensionWorkspaceSnapshot) -> [CMUXSidebarSurface] { + guard let liveWorkspace = tabManager.tabs.first(where: { $0.id == workspace.id }) else { return [] } + return liveWorkspace.sidebarOrderedPanelIds().compactMap { panelId in + guard let panel = liveWorkspace.panels[panelId] else { return nil } + return CMUXSidebarSurface( + id: panelId, + title: liveWorkspace.panelTitle(panelId: panelId) ?? panel.displayTitle, + kind: cmuxSidebarSurfaceKind(for: panel.panelType), + isFocused: liveWorkspace.focusedPanelId == panelId, + isPinned: liveWorkspace.isPanelPinned(panelId), + unreadCount: liveWorkspace.manualUnreadPanelIds.contains(panelId) ? 1 : 0, + workingDirectory: liveWorkspace.panelDirectories[panelId] + ) + } + } + + private func cmuxSidebarSurfaceKind(for panelType: PanelType) -> CMUXSidebarSurfaceKind { + switch panelType { + case .terminal: + return .terminal + case .browser: + return .browser + case .markdown: + return .markdown + case .filePreview: + return .filePreview + case .rightSidebarTool: + return .rightSidebarTool + } } - private func handleCMUXSidebarExtensionAction( - _ action: CMUXSidebarAction - ) -> CMUXExtensionActionResult { - switch action { - case .selectWorkspace(let workspaceId): - guard let workspace = tabManager.tabs.first(where: { $0.id == workspaceId }) else { - return CMUXExtensionActionResult( + private func handleCMUXSidebarExtensionAction( + _ action: CMUXSidebarAction + ) -> CMUXExtensionActionResult { + switch action { + case .createWorkspace(let title, let workingDirectory, let select): + let workspace = tabManager.addWorkspace( + title: title, + workingDirectory: workingDirectory, + inheritWorkingDirectory: workingDirectory == nil, + select: select + ) + return CMUXExtensionActionResult(accepted: true, message: workspace.id.uuidString) + + case .selectWorkspace(let workspaceId): + guard let workspace = tabManager.tabs.first(where: { $0.id == workspaceId }) else { + return CMUXExtensionActionResult( accepted: false, message: String(localized: "sidebar.extensions.action.workspaceNotFound", defaultValue: "Workspace not found") ) @@ -10897,6 +10952,86 @@ struct VerticalTabsSidebar: View { accepted: false, message: String(localized: "sidebar.extensions.action.closeRejected", defaultValue: "Workspace could not be closed") ) + } + return .accepted + + case .selectNextWorkspace: + tabManager.selectNextTab() + return .accepted + + case .selectPreviousWorkspace: + tabManager.selectPreviousTab() + return .accepted + + case .createTerminalSurface(let workspaceId, let initialInput): + guard let workspace = workspaceId.flatMap({ id in tabManager.tabs.first(where: { $0.id == id }) }) ?? tabManager.selectedWorkspace else { + return .rejected(String(localized: "sidebar.extensions.action.workspaceNotFound", defaultValue: "Workspace not found")) + } + if tabManager.selectedTabId != workspace.id { + tabManager.selectWorkspace(workspace) + } + let panel = workspace.newTerminalSurfaceInFocusedPane(focus: true, initialInput: initialInput) + return panel.map { CMUXExtensionActionResult(accepted: true, message: $0.id.uuidString) } + ?? .rejected(String(localized: "sidebar.extensions.action.surfaceCreateRejected", defaultValue: "Surface could not be created")) + + case .createBrowserSurface(let workspaceId, let urlString): + guard let workspace = workspaceId.flatMap({ id in tabManager.tabs.first(where: { $0.id == id }) }) ?? tabManager.selectedWorkspace else { + return .rejected(String(localized: "sidebar.extensions.action.workspaceNotFound", defaultValue: "Workspace not found")) + } + if tabManager.selectedTabId != workspace.id { + tabManager.selectWorkspace(workspace) + } + let url = urlString.flatMap(URL.init(string:)) + let panelId = tabManager.createBrowserSplit(direction: .right, url: url) + return panelId.map { CMUXExtensionActionResult(accepted: true, message: $0.uuidString) } + ?? .rejected(String(localized: "sidebar.extensions.action.surfaceCreateRejected", defaultValue: "Surface could not be created")) + + case .selectSurface(let workspaceId, let surfaceId): + guard let workspace = tabManager.tabs.first(where: { $0.id == workspaceId }), + workspace.panels[surfaceId] != nil else { + return .rejected(String(localized: "sidebar.extensions.action.surfaceNotFound", defaultValue: "Surface not found")) + } + tabManager.selectWorkspace(workspace) + workspace.focusPanel(surfaceId) + return .accepted + + case .selectNextSurface: + tabManager.selectNextSurface() + return .accepted + + case .selectPreviousSurface: + tabManager.selectPreviousSurface() + return .accepted + + case .closeSurface(let workspaceId, let surfaceId): + guard tabManager.tabs.contains(where: { $0.id == workspaceId }) else { + return .rejected(String(localized: "sidebar.extensions.action.workspaceNotFound", defaultValue: "Workspace not found")) + } + tabManager.closePanelWithConfirmation(tabId: workspaceId, surfaceId: surfaceId) + return .accepted + + case .splitTerminal(let workspaceId, let surfaceId, let direction): + guard let splitDirection = splitDirection(from: direction), + let panelId = tabManager.createSplit(tabId: workspaceId, surfaceId: surfaceId, direction: splitDirection) else { + return .rejected(String(localized: "sidebar.extensions.action.surfaceCreateRejected", defaultValue: "Surface could not be created")) + } + return CMUXExtensionActionResult(accepted: true, message: panelId.uuidString) + + case .splitBrowser(let workspaceId, let surfaceId, let direction, let urlString): + guard let splitDirection = splitDirection(from: direction), + let tab = tabManager.tabs.first(where: { $0.id == workspaceId }), + tab.panels[surfaceId] != nil else { + return .rejected(String(localized: "sidebar.extensions.action.surfaceCreateRejected", defaultValue: "Surface could not be created")) + } + tabManager.selectWorkspace(tab) + tab.focusPanel(surfaceId) + let panelId = tabManager.createBrowserSplit(direction: splitDirection, url: urlString.flatMap(URL.init(string:))) + return panelId.map { CMUXExtensionActionResult(accepted: true, message: $0.uuidString) } + ?? .rejected(String(localized: "sidebar.extensions.action.surfaceCreateRejected", defaultValue: "Surface could not be created")) + + case .toggleSurfaceZoom(let workspaceId, let surfaceId): + guard tabManager.toggleSplitZoom(tabId: workspaceId, surfaceId: surfaceId) else { + return .rejected(String(localized: "sidebar.extensions.action.surfaceNotFound", defaultValue: "Surface not found")) } return .accepted @@ -10911,6 +11046,19 @@ struct VerticalTabsSidebar: View { ) } return .accepted + } + } + + private func splitDirection(from direction: CMUXSplitDirection) -> SplitDirection? { + switch direction { + case .left: + return .left + case .right: + return .right + case .up: + return .up + case .down: + return .down } } @@ -12718,10 +12866,27 @@ private struct SidebarFooterButtons: View { @ObservedObject var updateViewModel: UpdateViewModel @ObservedObject var fileExplorerState: FileExplorerState let onSendFeedback: () -> Void + @State private var extensionMenuAnchorView: NSView? var body: some View { HStack(spacing: 4) { SidebarHelpMenuButton(onSendFeedback: onSendFeedback) + Button { + guard let extensionMenuAnchorView else { return } + CmuxExtensionSidebarSelection.showMenu(anchorView: extensionMenuAnchorView, event: nil) + } label: { + Image(systemName: "puzzlepiece.extension") + .symbolRenderingMode(.monochrome) + .font(.system(size: 12, weight: .medium)) + .foregroundStyle(Color(nsColor: .secondaryLabelColor)) + .frame(width: 22, height: 22, alignment: .center) + } + .buttonStyle(SidebarFooterIconButtonStyle()) + .frame(width: 22, height: 22, alignment: .center) + .safeHelp(String(localized: "command.switchExtensionSidebar.subtitle", defaultValue: "Choose Sidebar")) + .accessibilityLabel(String(localized: "command.switchExtensionSidebar.subtitle", defaultValue: "Choose Sidebar")) + .accessibilityIdentifier("SidebarExtensionMenuButton") + .background(TitlebarControlAnchorView { extensionMenuAnchorView = $0 }) UpdatePill(model: updateViewModel) } .frame(maxWidth: .infinity, alignment: .leading) diff --git a/Sources/Update/MinimalModeSidebarControls.swift b/Sources/Update/MinimalModeSidebarControls.swift index 98df7b492605..7a777e240ac0 100644 --- a/Sources/Update/MinimalModeSidebarControls.swift +++ b/Sources/Update/MinimalModeSidebarControls.swift @@ -194,8 +194,6 @@ final class MinimalModeSidebarControlActionView: NSView { return } switch slot { - case .sidebarProvider: - CmuxExtensionSidebarSelection.showMenu(anchorView: self, event: event) case .newTab: _ = AppDelegate.shared?.showNewWorkspaceContextMenu(anchorView: self, event: event) case .focusHistoryBack: diff --git a/Sources/Update/UpdateTitlebarAccessory.swift b/Sources/Update/UpdateTitlebarAccessory.swift index 61971a6fc885..336bad43aa19 100644 --- a/Sources/Update/UpdateTitlebarAccessory.swift +++ b/Sources/Update/UpdateTitlebarAccessory.swift @@ -133,7 +133,6 @@ func titlebarControlPressedScale(isPressed _: Bool) -> CGFloat { final class TitlebarControlsViewModel: ObservableObject { weak var notificationsAnchorView: NSView? - weak var sidebarProviderAnchorView: NSView? } @MainActor @@ -437,22 +436,23 @@ enum TitlebarShortcutHintActionSlot: Int, CaseIterable { case .toggleSidebar: return 0 case .showNotifications: - return 2 + return 1 case .newTab: - return 3 + return 2 case .focusHistoryBack: - return 4 + return 3 case .focusHistoryForward: - return 5 + return 4 } } } enum TitlebarControlsLayoutMetrics { static let outerLeadingPadding: CGFloat = TitlebarControlsHitRegions.outerLeadingPadding + static let sidebarTrailingPadding: CGFloat = 16 static let hintRightSafetyShift: CGFloat = 10 - static let hintTrailingBaseInset: CGFloat = 8 - static let extraButtonCount = 1 + static let hintTrailingBaseInset: CGFloat = 14 + static let extraButtonCount = 0 static let trafficLightGap: CGFloat = 8 static func hintTrailingInset(titlebarShortcutHintXOffset: Double = ShortcutHintDebugSettings.defaultTitlebarHintX) -> CGFloat { @@ -489,16 +489,25 @@ enum TitlebarControlsLayoutMetrics { } static func leadingOffset( + contentWidth: CGFloat, trafficLightFrame: NSRect?, - debugSnapshot: MinimalModeTitlebarDebugSnapshot + debugSnapshot: MinimalModeTitlebarDebugSnapshot, + sidebarTrailingEdge: CGFloat = 0 ) -> CGFloat { let debugOffset = MinimalModeTitlebarDebugSettings.leftControlsXOffset( leadingInset: debugSnapshot.leftControlsLeadingInset ) - guard let trafficLightFrame, !trafficLightFrame.isEmpty else { - return debugOffset + let minimumOffset: CGFloat + if let trafficLightFrame, !trafficLightFrame.isEmpty { + minimumOffset = max(debugOffset, trafficLightFrame.maxX + trafficLightGap) + } else { + minimumOffset = debugOffset + } + + guard sidebarTrailingEdge > 0, contentWidth > 0 else { + return minimumOffset } - return max(debugOffset, trafficLightFrame.maxX + trafficLightGap) + return max(minimumOffset, sidebarTrailingEdge - contentWidth - sidebarTrailingPadding) } static func minimumSidebarWidth(config: TitlebarControlsStyleConfig) -> CGFloat { @@ -757,7 +766,6 @@ struct TitlebarControlsView: View { @ObservedObject var viewModel: TitlebarControlsViewModel let onToggleSidebar: () -> Void let onToggleNotifications: () -> Void - let onShowSidebarProviderMenu: (NSView) -> Void let onNewTab: () -> Void let onFocusHistoryBack: () -> Void let onFocusHistoryForward: () -> Void @@ -888,34 +896,11 @@ struct TitlebarControlsView: View { #endif onToggleSidebar() }, - rightClickAction: { anchorView, event in - CmuxExtensionSidebarSelection.showMenu(anchorView: anchorView, event: event) - }) { + rightClickAction: nil) { sidebarIconLabel(config: config, iconGeometryKeyPrefix: "titlebarControl_toggleSidebarIcon") } .safeHelp(KeyboardShortcutSettings.Action.toggleSidebar.tooltip(String(localized: "titlebar.sidebar.tooltip", defaultValue: "Show or hide the sidebar"))) - TitlebarControlButton( - config: config, - foregroundColor: foregroundColor, - accessibilityIdentifier: "titlebarControl.sidebarProvider", - accessibilityLabel: String(localized: "command.switchExtensionSidebar.subtitle", defaultValue: "Choose Sidebar"), - action: { - guard let anchorView = viewModel.sidebarProviderAnchorView else { return } - onShowSidebarProviderMenu(anchorView) - }, - rightClickAction: { anchorView, event in - CmuxExtensionSidebarSelection.showMenu(anchorView: anchorView, event: event) - }) { - iconLabel( - systemName: "puzzlepiece.extension", - config: config, - iconGeometryKeyPrefix: "titlebarControl_sidebarProviderIcon" - ) - } - .background(TitlebarControlAnchorView { viewModel.sidebarProviderAnchorView = $0 }) - .safeHelp(String(localized: "command.switchExtensionSidebar.subtitle", defaultValue: "Choose Sidebar")) - TitlebarControlButton( config: config, foregroundColor: foregroundColor, @@ -1356,9 +1341,6 @@ struct HiddenTitlebarSidebarControlsView: View { onToggleNotifications: { [viewModel] in onToggleNotifications(viewModel.notificationsAnchorView) }, - onShowSidebarProviderMenu: { anchorView in - CmuxExtensionSidebarSelection.showMenu(anchorView: anchorView, event: nil) - }, onNewTab: onNewTab, onFocusHistoryBack: onFocusHistoryBack, onFocusHistoryForward: onFocusHistoryForward, @@ -1387,8 +1369,6 @@ struct HiddenTitlebarSidebarControlsView: View { switch slot { case .toggleSidebar: onToggleSidebar() - case .sidebarProvider: - CmuxExtensionSidebarSelection.showMenu(anchorView: anchorView, event: nil) case .showNotifications: onToggleNotifications(anchorView) case .newTab: @@ -1884,6 +1864,7 @@ final class TitlebarControlsAccessoryViewController: NSTitlebarAccessoryViewCont private var windowGeometryObservers: [NSObjectProtocol] = [] private let viewModel = TitlebarControlsViewModel() private var userDefaultsObserver: NSObjectProtocol? + private var sidebarTrailingEdge: CGFloat = 0 var popoverIsShownForTesting: Bool { notificationsPopover.isShown } private var showsWorkspaceTitlebar: Bool { !WorkspacePresentationModeSettings.isMinimal() } @@ -1897,9 +1878,6 @@ final class TitlebarControlsAccessoryViewController: NSTitlebarAccessoryViewCont let toggleNotifications: () -> Void = { [weak containerView] in _ = AppDelegate.shared?.toggleNotificationsPopover(animated: true, anchorView: containerView) } - let showSidebarProviderMenu: (NSView) -> Void = { anchorView in - CmuxExtensionSidebarSelection.showMenu(anchorView: anchorView, event: nil) - } let newTab = { _ = AppDelegate.shared?.performNewWorkspaceAction(debugSource: "titlebar.accessoryNewWorkspace") } let focusHistoryBack = { [weak containerView] in _ = AppDelegate.shared?.activeTabManagerForCommands(preferredWindow: containerView?.window)?.navigateBack() @@ -1913,7 +1891,6 @@ final class TitlebarControlsAccessoryViewController: NSTitlebarAccessoryViewCont viewModel: viewModel, onToggleSidebar: toggleSidebar, onToggleNotifications: toggleNotifications, - onShowSidebarProviderMenu: showSidebarProviderMenu, onNewTab: newTab, onFocusHistoryBack: focusHistoryBack, onFocusHistoryForward: focusHistoryForward, @@ -2055,8 +2032,10 @@ final class TitlebarControlsAccessoryViewController: NSTitlebarAccessoryViewCont ) let debugSnapshot = MinimalModeTitlebarDebugSettings.snapshot() let xOffset = TitlebarControlsLayoutMetrics.leadingOffset( + contentWidth: contentSize.width, trafficLightFrame: trafficLightFrame, - debugSnapshot: debugSnapshot + debugSnapshot: debugSnapshot, + sidebarTrailingEdge: sidebarTrailingEdge ) let yOffset = TitlebarControlsLayoutMetrics.yOffset( contentHeight: contentSize.height, @@ -2083,6 +2062,14 @@ final class TitlebarControlsAccessoryViewController: NSTitlebarAccessoryViewCont hostingView.frame = NSRect(x: xOffset, y: yOffset, width: contentSize.width, height: contentSize.height) } + func setSidebarTrailingEdge(_ edge: CGFloat) { + let sanitizedEdge = max(0, edge) + guard abs(sidebarTrailingEdge - sanitizedEdge) > 0.5 else { return } + sidebarTrailingEdge = sanitizedEdge + lastAppliedLayoutSnapshot = nil + updateSize() + } + private func applyWorkspaceTitlebarVisibility() { let shouldShow = showsWorkspaceTitlebar self.isHidden = !shouldShow @@ -2808,6 +2795,7 @@ final class UpdateTitlebarAccessoryController { private var startupScanWorkItems: [DispatchWorkItem] = [] private let controlsIdentifier = NSUserInterfaceItemIdentifier("cmux.titlebarControls") private let controlsControllers = NSHashTable.weakObjects() + private var sidebarTrailingEdgesByWindow: [ObjectIdentifier: CGFloat] = [:] private var lastKnownPresentationMode: WorkspacePresentationModeSettings.Mode = WorkspacePresentationModeSettings.mode() private var detachedNotificationsPopover: NSPopover? private var detachedNotificationsPopoverDelegate: DetachedNotificationsPopoverDelegate? @@ -2960,6 +2948,7 @@ final class UpdateTitlebarAccessoryController { let controls = TitlebarControlsAccessoryViewController( notificationStore: TerminalNotificationStore.shared ) + controls.setSidebarTrailingEdge(sidebarTrailingEdgesByWindow[ObjectIdentifier(window)] ?? 0) controls.layoutAttribute = .left controls.view.identifier = controlsIdentifier window.addTitlebarAccessoryViewController(controls) @@ -2994,6 +2983,16 @@ final class UpdateTitlebarAccessoryController { } } + func updateSidebarTrailingEdge(_ edge: CGFloat, for window: NSWindow) { + guard isMainTerminalWindow(window) else { return } + let windowID = ObjectIdentifier(window) + let sanitizedEdge = max(0, edge) + sidebarTrailingEdgesByWindow[windowID] = sanitizedEdge + for controller in controlsControllers.allObjects where controller.view.window === window { + controller.setSidebarTrailingEdge(sanitizedEdge) + } + } + private func removeAccessoryIfPresent(from window: NSWindow) { guard canAccessTitlebarAccessories(on: window) else { attachedWindows.remove(window) diff --git a/Sources/WindowDecorationsController.swift b/Sources/WindowDecorationsController.swift index 750f51b2caab..733cccde7076 100644 --- a/Sources/WindowDecorationsController.swift +++ b/Sources/WindowDecorationsController.swift @@ -338,10 +338,6 @@ final class WindowDecorationsController { switch slot { case .toggleSidebar: _ = AppDelegate.shared?.toggleSidebarInActiveMainWindow(preferredWindow: window) - case .sidebarProvider: - if let anchorView { - CmuxExtensionSidebarSelection.showMenu(anchorView: anchorView, event: nil) - } case .showNotifications: let resolvedAnchorView = NotificationsAnchorRegistry.shared.closestAnchor( in: window, diff --git a/Sources/WindowDragHandleView.swift b/Sources/WindowDragHandleView.swift index d9403686f880..11f6d8d508e6 100644 --- a/Sources/WindowDragHandleView.swift +++ b/Sources/WindowDragHandleView.swift @@ -783,7 +783,6 @@ private func minimalModeTrafficLightFrameInContentCoordinates(for window: NSWind enum MinimalModeSidebarControlActionSlot: Int, CaseIterable { case toggleSidebar - case sidebarProvider case showNotifications case newTab case focusHistoryBack @@ -793,8 +792,6 @@ enum MinimalModeSidebarControlActionSlot: Int, CaseIterable { switch self { case .toggleSidebar: return "titlebarControl.toggleSidebar" - case .sidebarProvider: - return "titlebarControl.sidebarProvider" case .showNotifications: return "titlebarControl.showNotifications" case .newTab: @@ -810,8 +807,6 @@ enum MinimalModeSidebarControlActionSlot: Int, CaseIterable { switch self { case .toggleSidebar: return String(localized: "titlebar.sidebar.accessibilityLabel", defaultValue: "Toggle Sidebar") - case .sidebarProvider: - return String(localized: "command.switchExtensionSidebar.subtitle", defaultValue: "Choose Sidebar") case .showNotifications: return String(localized: "titlebar.notifications.accessibilityLabel", defaultValue: "Notifications") case .newTab: @@ -827,8 +822,6 @@ enum MinimalModeSidebarControlActionSlot: Int, CaseIterable { switch self { case .toggleSidebar: return "toggleSidebar" - case .sidebarProvider: - return "sidebarProvider" case .showNotifications: return "showNotifications" case .newTab: @@ -842,7 +835,7 @@ enum MinimalModeSidebarControlActionSlot: Int, CaseIterable { var acceptsContextMenu: Bool { switch self { - case .sidebarProvider, .newTab, .focusHistoryBack, .focusHistoryForward: + case .newTab, .focusHistoryBack, .focusHistoryForward: return true case .toggleSidebar, .showNotifications: return false diff --git a/cmux.xcworkspace/contents.xcworkspacedata b/cmux.xcworkspace/contents.xcworkspacedata index af497f2aa058..18e87fb9f8b2 100644 --- a/cmux.xcworkspace/contents.xcworkspacedata +++ b/cmux.xcworkspace/contents.xcworkspacedata @@ -38,6 +38,9 @@ + + From b706047e217f73d0145690fa1376888d2e814aa2 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Sat, 30 May 2026 00:21:09 -0500 Subject: [PATCH 37/44] Tighten titlebar accessory divider spacing --- Sources/Update/UpdateTitlebarAccessory.swift | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/Sources/Update/UpdateTitlebarAccessory.swift b/Sources/Update/UpdateTitlebarAccessory.swift index 336bad43aa19..85d292859152 100644 --- a/Sources/Update/UpdateTitlebarAccessory.swift +++ b/Sources/Update/UpdateTitlebarAccessory.swift @@ -449,9 +449,9 @@ enum TitlebarShortcutHintActionSlot: Int, CaseIterable { enum TitlebarControlsLayoutMetrics { static let outerLeadingPadding: CGFloat = TitlebarControlsHitRegions.outerLeadingPadding - static let sidebarTrailingPadding: CGFloat = 16 - static let hintRightSafetyShift: CGFloat = 10 - static let hintTrailingBaseInset: CGFloat = 14 + static let sidebarTrailingPadding: CGFloat = 8 + static let hintRightSafetyShift: CGFloat = 6 + static let hintTrailingBaseInset: CGFloat = 4 static let extraButtonCount = 0 static let trafficLightGap: CGFloat = 8 @@ -2031,11 +2031,13 @@ final class TitlebarControlsAccessoryViewController: NSTitlebarAccessoryViewCont titlebarHeight: titlebarHeight ) let debugSnapshot = MinimalModeTitlebarDebugSettings.snapshot() + let accessoryOriginXInWindow = view.convert(view.bounds, to: nil).minX + let sidebarTrailingEdgeInAccessory = max(0, sidebarTrailingEdge - accessoryOriginXInWindow) let xOffset = TitlebarControlsLayoutMetrics.leadingOffset( contentWidth: contentSize.width, trafficLightFrame: trafficLightFrame, debugSnapshot: debugSnapshot, - sidebarTrailingEdge: sidebarTrailingEdge + sidebarTrailingEdge: sidebarTrailingEdgeInAccessory ) let yOffset = TitlebarControlsLayoutMetrics.yOffset( contentHeight: contentSize.height, From 341aaf6bd6fc6f1efdee1fd5d9a37573fae0fd03 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Sat, 30 May 2026 00:30:55 -0500 Subject: [PATCH 38/44] Keep extension sidebar chrome within minimum width --- ...MUXInstalledExtensionSidebarHostView.swift | 2 ++ Sources/ContentView.swift | 20 ++++++++++++++--- cmuxTests/SidebarWidthPolicyTests.swift | 22 +++++++++++++++++++ .../UpdatePillReleaseVisibilityTests.swift | 4 ++-- 4 files changed, 43 insertions(+), 5 deletions(-) diff --git a/Sources/CMUXInstalledExtensionSidebarHostView.swift b/Sources/CMUXInstalledExtensionSidebarHostView.swift index 00643279f230..018ebfb85f9b 100644 --- a/Sources/CMUXInstalledExtensionSidebarHostView.swift +++ b/Sources/CMUXInstalledExtensionSidebarHostView.swift @@ -132,6 +132,8 @@ private struct CMUXSidebarExtensionLimitedChoiceStore { } struct CMUXInstalledExtensionSidebarHostView: View { + static let minimumSidebarWidth: CGFloat = 300 + private static let selectedExtensionBundleIDDefaultsKey = "cmuxExtensionSidebar.selectedExtensionBundleId" private static let selectedExtensionNameDefaultsKey = "cmuxExtensionSidebar.selectedExtensionName" diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index 7a20274b453e..80b899ca630a 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -1059,6 +1059,7 @@ struct ContentView: View { @Environment(\.colorScheme) private var colorScheme @AppStorage("titlebarControlsStyle") private var titlebarControlsStyleRawValue = TitlebarControlsStyle.classic.rawValue @AppStorage(SessionPersistencePolicy.sidebarMinimumWidthKey) private var sidebarMinimumWidthSetting = SessionPersistencePolicy.defaultMinimumSidebarWidth + @AppStorage(CmuxExtensionSidebarSelection.defaultsKey) private var selectedExtensionSidebarProviderId = CmuxExtensionSidebarSelection.defaultProviderId @AppStorage(MinimalModeTitlebarDebugSettings.leftControlsLeadingInsetKey) private var titlebarLeftControlsLeadingInset = MinimalModeTitlebarDebugSettings.defaultLeftControlsLeadingInset @AppStorage(MinimalModeTitlebarDebugSettings.leftControlsTopInsetKey) private var titlebarLeftControlsTopInset = MinimalModeTitlebarDebugSettings.defaultLeftControlsTopInset @AppStorage(MinimalModeTitlebarDebugSettings.trafficLightTabBarInsetKey) private var titlebarTrafficLightTabBarInset = MinimalModeTitlebarDebugSettings.defaultTrafficLightTabBarInset @@ -1580,12 +1581,25 @@ struct ContentView: View { private static let minimumTerminalWidthWithRightSidebar: CGFloat = 360 private var minimumSidebarWidth: CGFloat { - max( - CGFloat(SessionPersistencePolicy.sanitizedMinimumSidebarWidth(sidebarMinimumWidthSetting)), - TitlebarControlsLayoutMetrics.minimumSidebarWidth(config: titlebarControlsConfig) + Self.effectiveMinimumSidebarWidth( + configuredMinimum: CGFloat(SessionPersistencePolicy.sanitizedMinimumSidebarWidth(sidebarMinimumWidthSetting)), + titlebarControlsMinimum: TitlebarControlsLayoutMetrics.minimumSidebarWidth(config: titlebarControlsConfig), + selectedExtensionSidebarProviderId: selectedExtensionSidebarProviderId ) } + static func effectiveMinimumSidebarWidth( + configuredMinimum: CGFloat, + titlebarControlsMinimum: CGFloat, + selectedExtensionSidebarProviderId: String + ) -> CGFloat { + var minimumWidth = max(configuredMinimum, titlebarControlsMinimum) + if selectedExtensionSidebarProviderId == CmuxExtensionSidebarSelection.hostedExtensionsProviderId { + minimumWidth = max(minimumWidth, CMUXInstalledExtensionSidebarHostView.minimumSidebarWidth) + } + return minimumWidth + } + private enum SidebarResizerHandle: Hashable { case divider case explorerDivider diff --git a/cmuxTests/SidebarWidthPolicyTests.swift b/cmuxTests/SidebarWidthPolicyTests.swift index 0c8ea354c542..2d23c93233fb 100644 --- a/cmuxTests/SidebarWidthPolicyTests.swift +++ b/cmuxTests/SidebarWidthPolicyTests.swift @@ -47,6 +47,28 @@ final class SidebarWidthPolicyTests: XCTestCase { ) } + func testHostedExtensionSidebarUsesWiderMinimumWidth() { + XCTAssertEqual( + ContentView.effectiveMinimumSidebarWidth( + configuredMinimum: 216, + titlebarControlsMinimum: 224, + selectedExtensionSidebarProviderId: CmuxExtensionSidebarSelection.hostedExtensionsProviderId + ), + CMUXInstalledExtensionSidebarHostView.minimumSidebarWidth, + accuracy: 0.001 + ) + + XCTAssertEqual( + ContentView.effectiveMinimumSidebarWidth( + configuredMinimum: 216, + titlebarControlsMinimum: 224, + selectedExtensionSidebarProviderId: CmuxExtensionSidebarSelection.defaultProviderId + ), + 224, + accuracy: 0.001 + ) + } + func testSessionPersistenceReadsConfiguredMinimumSidebarWidth() { let suiteName = "SidebarWidthPolicyTests.minimumSidebarWidth.\(UUID().uuidString)" let defaults = UserDefaults(suiteName: suiteName)! diff --git a/cmuxTests/UpdatePillReleaseVisibilityTests.swift b/cmuxTests/UpdatePillReleaseVisibilityTests.swift index 1ea216fa385f..76a1e12ee0b7 100644 --- a/cmuxTests/UpdatePillReleaseVisibilityTests.swift +++ b/cmuxTests/UpdatePillReleaseVisibilityTests.swift @@ -219,11 +219,11 @@ final class TitlebarControlsSizingPolicyTests: XCTestCase { func testTitlebarControlsUseDeterministicContentSize() { let classic = TitlebarControlsLayoutMetrics.contentSize(config: TitlebarControlsStyle.classic.config) - XCTAssertEqual(classic.width, 150, accuracy: 0.001) + XCTAssertEqual(classic.width, 138, accuracy: 0.001) XCTAssertEqual(classic.height, WindowChromeMetrics.appTitlebarHeight, accuracy: 0.001) let compact = TitlebarControlsLayoutMetrics.contentSize(config: TitlebarControlsStyle.compact.config) - XCTAssertEqual(compact.width, 136, accuracy: 0.001) + XCTAssertEqual(compact.width, 124, accuracy: 0.001) XCTAssertEqual(compact.height, WindowChromeMetrics.appTitlebarHeight, accuracy: 0.001) } From c6e3a174bdd03a4ac18ec75b2f34d0eb995c63f9 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Sat, 30 May 2026 00:36:49 -0500 Subject: [PATCH 39/44] Fix titlebar accessory traffic light alignment --- ...MUXInstalledExtensionSidebarHostView.swift | 2 -- Sources/ContentView.swift | 20 +++-------------- Sources/Update/UpdateTitlebarAccessory.swift | 9 ++++++-- cmuxTests/SidebarWidthPolicyTests.swift | 22 ------------------- .../UpdatePillReleaseVisibilityTests.swift | 8 +++++++ 5 files changed, 18 insertions(+), 43 deletions(-) diff --git a/Sources/CMUXInstalledExtensionSidebarHostView.swift b/Sources/CMUXInstalledExtensionSidebarHostView.swift index 018ebfb85f9b..00643279f230 100644 --- a/Sources/CMUXInstalledExtensionSidebarHostView.swift +++ b/Sources/CMUXInstalledExtensionSidebarHostView.swift @@ -132,8 +132,6 @@ private struct CMUXSidebarExtensionLimitedChoiceStore { } struct CMUXInstalledExtensionSidebarHostView: View { - static let minimumSidebarWidth: CGFloat = 300 - private static let selectedExtensionBundleIDDefaultsKey = "cmuxExtensionSidebar.selectedExtensionBundleId" private static let selectedExtensionNameDefaultsKey = "cmuxExtensionSidebar.selectedExtensionName" diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index 80b899ca630a..7a20274b453e 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -1059,7 +1059,6 @@ struct ContentView: View { @Environment(\.colorScheme) private var colorScheme @AppStorage("titlebarControlsStyle") private var titlebarControlsStyleRawValue = TitlebarControlsStyle.classic.rawValue @AppStorage(SessionPersistencePolicy.sidebarMinimumWidthKey) private var sidebarMinimumWidthSetting = SessionPersistencePolicy.defaultMinimumSidebarWidth - @AppStorage(CmuxExtensionSidebarSelection.defaultsKey) private var selectedExtensionSidebarProviderId = CmuxExtensionSidebarSelection.defaultProviderId @AppStorage(MinimalModeTitlebarDebugSettings.leftControlsLeadingInsetKey) private var titlebarLeftControlsLeadingInset = MinimalModeTitlebarDebugSettings.defaultLeftControlsLeadingInset @AppStorage(MinimalModeTitlebarDebugSettings.leftControlsTopInsetKey) private var titlebarLeftControlsTopInset = MinimalModeTitlebarDebugSettings.defaultLeftControlsTopInset @AppStorage(MinimalModeTitlebarDebugSettings.trafficLightTabBarInsetKey) private var titlebarTrafficLightTabBarInset = MinimalModeTitlebarDebugSettings.defaultTrafficLightTabBarInset @@ -1581,25 +1580,12 @@ struct ContentView: View { private static let minimumTerminalWidthWithRightSidebar: CGFloat = 360 private var minimumSidebarWidth: CGFloat { - Self.effectiveMinimumSidebarWidth( - configuredMinimum: CGFloat(SessionPersistencePolicy.sanitizedMinimumSidebarWidth(sidebarMinimumWidthSetting)), - titlebarControlsMinimum: TitlebarControlsLayoutMetrics.minimumSidebarWidth(config: titlebarControlsConfig), - selectedExtensionSidebarProviderId: selectedExtensionSidebarProviderId + max( + CGFloat(SessionPersistencePolicy.sanitizedMinimumSidebarWidth(sidebarMinimumWidthSetting)), + TitlebarControlsLayoutMetrics.minimumSidebarWidth(config: titlebarControlsConfig) ) } - static func effectiveMinimumSidebarWidth( - configuredMinimum: CGFloat, - titlebarControlsMinimum: CGFloat, - selectedExtensionSidebarProviderId: String - ) -> CGFloat { - var minimumWidth = max(configuredMinimum, titlebarControlsMinimum) - if selectedExtensionSidebarProviderId == CmuxExtensionSidebarSelection.hostedExtensionsProviderId { - minimumWidth = max(minimumWidth, CMUXInstalledExtensionSidebarHostView.minimumSidebarWidth) - } - return minimumWidth - } - private enum SidebarResizerHandle: Hashable { case divider case explorerDivider diff --git a/Sources/Update/UpdateTitlebarAccessory.swift b/Sources/Update/UpdateTitlebarAccessory.swift index 85d292859152..813ab9665254 100644 --- a/Sources/Update/UpdateTitlebarAccessory.swift +++ b/Sources/Update/UpdateTitlebarAccessory.swift @@ -454,6 +454,7 @@ enum TitlebarControlsLayoutMetrics { static let hintTrailingBaseInset: CGFloat = 4 static let extraButtonCount = 0 static let trafficLightGap: CGFloat = 8 + static let trafficLightClusterWidth: CGFloat = 58 static func hintTrailingInset(titlebarShortcutHintXOffset: Double = ShortcutHintDebugSettings.defaultTitlebarHintX) -> CGFloat { max(0, ShortcutHintDebugSettings.clamped(titlebarShortcutHintXOffset)) @@ -512,8 +513,10 @@ enum TitlebarControlsLayoutMetrics { static func minimumSidebarWidth(config: TitlebarControlsStyleConfig) -> CGFloat { MinimalModeTitlebarDebugSettings.defaultTrafficLightTitlebarLeadingInset - + contentSize(config: config).width + + trafficLightClusterWidth + trafficLightGap + + contentSize(config: config).width + + sidebarTrailingPadding } static func yOffset( @@ -2017,7 +2020,9 @@ final class TitlebarControlsAccessoryViewController: NSTitlebarAccessoryViewCont guard contentSize.width > 0, contentSize.height > 0 else { return } let closeButton = view.window?.standardWindowButton(.closeButton) let titlebarView = closeButton?.superview - let trafficLightFrame = closeButton?.frame + let trafficLightFrame = closeButton.map { button in + view.convert(button.convert(button.bounds, to: nil), from: nil) + } #if DEBUG TitlebarChromeUITestRecorder.recordTrafficLightFrames(window: view.window) #endif diff --git a/cmuxTests/SidebarWidthPolicyTests.swift b/cmuxTests/SidebarWidthPolicyTests.swift index 2d23c93233fb..0c8ea354c542 100644 --- a/cmuxTests/SidebarWidthPolicyTests.swift +++ b/cmuxTests/SidebarWidthPolicyTests.swift @@ -47,28 +47,6 @@ final class SidebarWidthPolicyTests: XCTestCase { ) } - func testHostedExtensionSidebarUsesWiderMinimumWidth() { - XCTAssertEqual( - ContentView.effectiveMinimumSidebarWidth( - configuredMinimum: 216, - titlebarControlsMinimum: 224, - selectedExtensionSidebarProviderId: CmuxExtensionSidebarSelection.hostedExtensionsProviderId - ), - CMUXInstalledExtensionSidebarHostView.minimumSidebarWidth, - accuracy: 0.001 - ) - - XCTAssertEqual( - ContentView.effectiveMinimumSidebarWidth( - configuredMinimum: 216, - titlebarControlsMinimum: 224, - selectedExtensionSidebarProviderId: CmuxExtensionSidebarSelection.defaultProviderId - ), - 224, - accuracy: 0.001 - ) - } - func testSessionPersistenceReadsConfiguredMinimumSidebarWidth() { let suiteName = "SidebarWidthPolicyTests.minimumSidebarWidth.\(UUID().uuidString)" let defaults = UserDefaults(suiteName: suiteName)! diff --git a/cmuxTests/UpdatePillReleaseVisibilityTests.swift b/cmuxTests/UpdatePillReleaseVisibilityTests.swift index 76a1e12ee0b7..a9551fabb216 100644 --- a/cmuxTests/UpdatePillReleaseVisibilityTests.swift +++ b/cmuxTests/UpdatePillReleaseVisibilityTests.swift @@ -227,6 +227,14 @@ final class TitlebarControlsSizingPolicyTests: XCTestCase { XCTAssertEqual(compact.height, WindowChromeMetrics.appTitlebarHeight, accuracy: 0.001) } + func testTitlebarControlsMinimumSidebarWidthIncludesTrafficLightsAndTrailingPadding() { + XCTAssertEqual( + TitlebarControlsLayoutMetrics.minimumSidebarWidth(config: TitlebarControlsStyle.classic.config), + 290, + accuracy: 0.001 + ) + } + func testTitlebarControlsVerticalOffsetAlignsToTrafficLightsWhenAvailable() { let snapshot = MinimalModeTitlebarDebugSettings.snapshot() let yOffset = TitlebarControlsLayoutMetrics.yOffset( From 504cf5ff313e6d227ccd3544d4c768f42aadd7b8 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Sat, 30 May 2026 00:41:29 -0500 Subject: [PATCH 40/44] Guard modern extension monitor for Xcode 16 --- .../Discovery/CMUXSidebarExtensionDiscovery.swift | 2 ++ Sources/CMUXInstalledExtensionSidebarHostView.swift | 4 ++++ 2 files changed, 6 insertions(+) diff --git a/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Discovery/CMUXSidebarExtensionDiscovery.swift b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Discovery/CMUXSidebarExtensionDiscovery.swift index 0bf78ffaafd6..535f61cb39cb 100644 --- a/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Discovery/CMUXSidebarExtensionDiscovery.swift +++ b/Packages/CMUXExtensionClient/Sources/CMUXExtensionClient/Discovery/CMUXSidebarExtensionDiscovery.swift @@ -31,6 +31,7 @@ public struct CMUXSidebarExtensionDiscovery { /// Lists enabled sidebar extensions using the modern ExtensionFoundation monitor. /// - Parameter appExtensionPoint: Extension point declared by the host app. /// - Returns: Enabled extensions sorted by localized name. + #if compiler(>=6.2) @available(macOS 26.0, *) public func enabledExtensions( appExtensionPoint: AppExtensionPoint @@ -45,4 +46,5 @@ public struct CMUXSidebarExtensionDiscovery { } .sorted { $0.localizedName < $1.localizedName } } + #endif } diff --git a/Sources/CMUXInstalledExtensionSidebarHostView.swift b/Sources/CMUXInstalledExtensionSidebarHostView.swift index 00643279f230..88409dfa733b 100644 --- a/Sources/CMUXInstalledExtensionSidebarHostView.swift +++ b/Sources/CMUXInstalledExtensionSidebarHostView.swift @@ -845,12 +845,14 @@ struct CMUXInstalledExtensionSidebarHostView: View { extensionPointIdentifier: String, staticExtensionPointIdentifier: StaticString ) async throws { + #if compiler(>=6.2) if #available(macOS 26.0, *) { let extensionPoint = try AppExtensionPoint(identifier: staticExtensionPointIdentifier) let monitor = try await AppExtensionPoint.Monitor(appExtensionPoint: extensionPoint) await observeModernExtensionMonitor(monitor) return } + #endif try await observeIdentitySequence(extensionPointIdentifier: extensionPointIdentifier) } @@ -927,6 +929,7 @@ struct CMUXInstalledExtensionSidebarHostView: View { } } + #if compiler(>=6.2) @available(macOS 26.0, *) private func applyModernExtensionState(_ state: AppExtensionPoint.Monitor.State) { disabledExtensionCount = state.disabledCount @@ -955,6 +958,7 @@ struct CMUXInstalledExtensionSidebarHostView: View { } } } + #endif } private final class MonitorContinuationBox: @unchecked Sendable { From 0d72b16414c75c90a42b3337bc59c43d3e8a7dd0 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Sat, 30 May 2026 00:46:09 -0500 Subject: [PATCH 41/44] Reduce titlebar accessory minimum width --- Sources/Update/UpdateTitlebarAccessory.swift | 5 ++--- cmuxTests/UpdatePillReleaseVisibilityTests.swift | 2 +- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/Sources/Update/UpdateTitlebarAccessory.swift b/Sources/Update/UpdateTitlebarAccessory.swift index 813ab9665254..98ac14172b97 100644 --- a/Sources/Update/UpdateTitlebarAccessory.swift +++ b/Sources/Update/UpdateTitlebarAccessory.swift @@ -453,7 +453,7 @@ enum TitlebarControlsLayoutMetrics { static let hintRightSafetyShift: CGFloat = 6 static let hintTrailingBaseInset: CGFloat = 4 static let extraButtonCount = 0 - static let trafficLightGap: CGFloat = 8 + static let trafficLightGap: CGFloat = 4 static let trafficLightClusterWidth: CGFloat = 58 static func hintTrailingInset(titlebarShortcutHintXOffset: Double = ShortcutHintDebugSettings.defaultTitlebarHintX) -> CGFloat { @@ -512,8 +512,7 @@ enum TitlebarControlsLayoutMetrics { } static func minimumSidebarWidth(config: TitlebarControlsStyleConfig) -> CGFloat { - MinimalModeTitlebarDebugSettings.defaultTrafficLightTitlebarLeadingInset - + trafficLightClusterWidth + trafficLightClusterWidth + trafficLightGap + contentSize(config: config).width + sidebarTrailingPadding diff --git a/cmuxTests/UpdatePillReleaseVisibilityTests.swift b/cmuxTests/UpdatePillReleaseVisibilityTests.swift index a9551fabb216..bee45253c0c8 100644 --- a/cmuxTests/UpdatePillReleaseVisibilityTests.swift +++ b/cmuxTests/UpdatePillReleaseVisibilityTests.swift @@ -230,7 +230,7 @@ final class TitlebarControlsSizingPolicyTests: XCTestCase { func testTitlebarControlsMinimumSidebarWidthIncludesTrafficLightsAndTrailingPadding() { XCTAssertEqual( TitlebarControlsLayoutMetrics.minimumSidebarWidth(config: TitlebarControlsStyle.classic.config), - 290, + 208, accuracy: 0.001 ) } From c8160948e46e71739add7a12adcecf94dee690bb Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Sat, 30 May 2026 01:04:41 -0500 Subject: [PATCH 42/44] Update sidebar extension for latest main --- .../Sidebar/CMUXSidebarSurface.swift | 1 + Sources/ContentView.swift | 2 ++ Sources/Workspace.swift | 25 +++---------------- vendor/bonsplit | 2 +- 4 files changed, 8 insertions(+), 22 deletions(-) diff --git a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarSurface.swift b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarSurface.swift index 8d5abe699a64..d02c1d851099 100644 --- a/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarSurface.swift +++ b/Packages/CmuxExtensionKit/Sources/CmuxExtensionKit/Sidebar/CMUXSidebarSurface.swift @@ -6,6 +6,7 @@ public enum CMUXSidebarSurfaceKind: String, Codable, CaseIterable, Equatable, Se case markdown case filePreview case rightSidebarTool + case project case unknown } diff --git a/Sources/ContentView.swift b/Sources/ContentView.swift index fade57dc0c98..aeacc48b29b1 100644 --- a/Sources/ContentView.swift +++ b/Sources/ContentView.swift @@ -10928,6 +10928,8 @@ struct VerticalTabsSidebar: View { return .filePreview case .rightSidebarTool: return .rightSidebarTool + case .project: + return .project } } diff --git a/Sources/Workspace.swift b/Sources/Workspace.swift index a580a373852b..a9e785c4b1dc 100644 --- a/Sources/Workspace.swift +++ b/Sources/Workspace.swift @@ -10927,20 +10927,15 @@ final class Workspace: Identifiable, ObservableObject { } private func installBrowserPanelSubscription(_ browserPanel: BrowserPanel) { - let browserChromeState = Publishers.CombineLatest4( + let subscription = Publishers.CombineLatest4( browserPanel.$pageTitle.removeDuplicates(), browserPanel.$currentURL.removeDuplicates(), browserPanel.$isLoading.removeDuplicates(), browserPanel.$faviconPNGData.removeDuplicates(by: { $0 == $1 }) ) - let subscription = Publishers.CombineLatest( - browserChromeState, - browserPanel.$isMuted.removeDuplicates() - ) .receive(on: DispatchQueue.main) - .sink { [weak self, weak browserPanel] browserChromeState, isMuted in + .sink { [weak self, weak browserPanel] _, _, isLoading, favicon in guard let self = self, let browserPanel = browserPanel, let tabId = self.surfaceIdFromPanelId(browserPanel.id) else { return } - let (_, _, isLoading, favicon) = browserChromeState self.publishBrowserOpenTabSuggestion(for: browserPanel) guard let existing = self.bonsplitController.tab(tabId) else { return } let nextTitle = browserPanel.displayTitle @@ -10951,15 +10946,13 @@ final class Workspace: Identifiable, ObservableObject { let titleUpdate: String? = existing.title == resolvedTitle ? nil : resolvedTitle let faviconUpdate: Data?? = existing.iconImageData == favicon ? nil : .some(favicon) let loadingUpdate: Bool? = existing.isLoading == isLoading ? nil : isLoading - let muteUpdate: Bool? = existing.isAudioMuted == isMuted ? nil : isMuted - guard titleUpdate != nil || faviconUpdate != nil || loadingUpdate != nil || muteUpdate != nil else { return } + guard titleUpdate != nil || faviconUpdate != nil || loadingUpdate != nil else { return } self.bonsplitController.updateTab( tabId, title: titleUpdate, iconImageData: faviconUpdate, hasCustomTitle: self.panelCustomTitles[browserPanel.id] != nil, - isLoading: loadingUpdate, - isAudioMuted: muteUpdate + isLoading: loadingUpdate ) } panelSubscriptions[browserPanel.id] = subscription @@ -18181,16 +18174,6 @@ extension Workspace: BonsplitDelegate { case .duplicate: guard let panelId = panelIdFromSurfaceId(tab.id) else { return } _ = duplicateBrowserToRight(panelId: panelId) - case .toggleAudioMute: - guard let panelId = panelIdFromSurfaceId(tab.id), - let browser = browserPanel(for: panelId) else { return } -#if DEBUG - cmuxDebugLog( - "browser.audioMute.toggle.contextMenu panel=\(panelId.uuidString.prefix(5)) " + - "targetMuted=\(!browser.isMuted ? 1 : 0)" - ) -#endif - browser.toggleMute() case .togglePin: guard let panelId = panelIdFromSurfaceId(tab.id) else { return } let shouldPin = !pinnedPanelIds.contains(panelId) diff --git a/vendor/bonsplit b/vendor/bonsplit index 9166c3639fab..72b91bd9de10 160000 --- a/vendor/bonsplit +++ b/vendor/bonsplit @@ -1 +1 @@ -Subproject commit 9166c3639fabb80bca050d57d7cbf3fe66248c2e +Subproject commit 72b91bd9de10ecc08ecaf49b17a49c54583d2cae From 43c1fcdc572b59f720edae755108341e58720740 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Sat, 30 May 2026 01:13:44 -0500 Subject: [PATCH 43/44] Run release build on macOS 15 --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index aad3d0956055..caa784ee807d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -594,7 +594,7 @@ jobs: # Compile the same unsigned universal Release app that nightly builds before # signing, notarization, and publishing. This catches DEBUG/Release boundary # mistakes before they reach main. - runs-on: ${{ vars.MACOS_RUNNER_26 || 'warp-macos-26-arm64-6x' }} + runs-on: ${{ vars.MACOS_RUNNER_15 || 'warp-macos-15-arm64-6x' }} timeout-minutes: 20 steps: - name: Checkout From 67e62a10f7965bf4e780b75fca860949b06444f4 Mon Sep 17 00:00:00 2001 From: Aziz Albahar Date: Sat, 30 May 2026 01:44:22 -0500 Subject: [PATCH 44/44] Give UI regressions cold builds more time --- .github/workflows/ci.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index caa784ee807d..5642fb66af98 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -699,7 +699,9 @@ jobs: ui-regressions: runs-on: ${{ vars.MACOS_RUNNER_15 || 'warp-macos-15-arm64-6x' }} - timeout-minutes: 25 + # Cold builds after project/package changes can spend more than 25 minutes + # in build-for-testing before the UI regression script starts. + timeout-minutes: 45 steps: - name: Checkout uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2