From 151e2fac2559a36349f31c0ba0fb3174d864cd34 Mon Sep 17 00:00:00 2001 From: maximkrouk Date: Sat, 14 Nov 2026 02:56:56 +0100 Subject: [PATCH] feat: Add open-url to deliver an app link to one workspace's instance (DEV-860) fxcodex open-url sends a codex:// link to that workspace's Codex only: a kAEGetURL Apple Event addressed to the recorded process ID when it runs, or a new instance launched with the workspace's environment and the link when it doesn't. Never routes by scheme through Launch Services. Extracts launchConfiguration(for:) so both launch paths share it, as in fxclaude. Release builds are signed with com.apple.security.automation.apple-events, because the hardened runtime rejects Apple Events (errAEEventNotPermitted, no prompt) without it. custom-dump stays on 1.6: 1.7 depends on swift-issue-reporting, whose IssueReporting targets clash with xctest-dynamic-overlay used by Dependencies 1.14. --- Documentation/ExtensionAPI.md | 12 ++ Package.swift | 3 +- README.md | 36 ++++ Scripts/fxcodex.entitlements | 9 + Scripts/sign-release.sh | 11 +- Sources/fxcodex-cli/AppCommand.swift | 1 + .../fxcodex-cli/Commands/OpenURLCommand.swift | 59 ++++++ .../fxcodex-cli/Models/OpenURLOutput.swift | 18 ++ .../fxcodex-client/Common/FXCodexError.swift | 10 ++ Sources/fxcodex-client/FXCodexClient.swift | 2 + .../Manager/CodexApplicationClient.swift | 15 ++ .../Manager/CodexApplicationController.swift | 170 ++++++++++++++++-- .../fxcodex-client/Manager/CodexManager.swift | 36 ++++ .../fxcodex-client/Models/URLDelivery.swift | 29 +++ .../fxcodex-cli-tests/OpenCommandTests.swift | 22 +++ .../Client/OpenURLTests.swift | 166 +++++++++++++++++ .../Fixtures/ClientTestFixture.swift | 59 +++++- .../CodexApplicationControllerTests.swift | 128 +++++++++++++ 18 files changed, 770 insertions(+), 16 deletions(-) create mode 100644 Scripts/fxcodex.entitlements create mode 100644 Sources/fxcodex-cli/Commands/OpenURLCommand.swift create mode 100644 Sources/fxcodex-cli/Models/OpenURLOutput.swift create mode 100644 Sources/fxcodex-client/Models/URLDelivery.swift create mode 100644 Tests/fxcodex-client-tests/Client/OpenURLTests.swift diff --git a/Documentation/ExtensionAPI.md b/Documentation/ExtensionAPI.md index 2dac550..b80ede9 100644 --- a/Documentation/ExtensionAPI.md +++ b/Documentation/ExtensionAPI.md @@ -12,6 +12,7 @@ fxcodex workspace list --json fxcodex workspace paths work --json fxcodex open work --json fxcodex open --workspace-id 00000000-0000-0000-0000-000000000001 --json +fxcodex open-url work 'codex://auth/callback?code=…' --json fxcodex delete work personal --yes --json ``` @@ -82,6 +83,7 @@ The machine interface is available for: - `workspace rename` - `workspace use` and its root `use` alias - `workspace open` and its root `open` alias +- `open-url` - `workspace delete` and its root `delete` alias - `workspace erase` and its root `erase` alias - `integrations attributes get` @@ -101,6 +103,16 @@ already records the directory; this component is deprecated in favor of the extension. Extension installation requires `--yes` when Raycast is absent, or `--open-in-browser` to bypass Raycast installation. +## Delivering a link + +`open-url ` hands an app link to one workspace's Codex instance. A +running instance receives a `kAEGetURL` Apple Event addressed to its process +ID; a stopped one launches with the workspace's environment and the link. The +response data contains `workspace_name`, `workspace_id`, `process_id` and +`delivery` (`apple-event` or `launch`). Errors use `workspace_not_found`, +`unsupported_url` (the scheme isn't one Codex registers, or the value isn't a +URL), `application_not_found` and `url_delivery_failed`. + ## Stable workspace identities Schema 2.0 assigns every workspace a stable lowercase UUID. Workspace names diff --git a/Package.swift b/Package.swift index 168bd84..ac80dd6 100644 --- a/Package.swift +++ b/Package.swift @@ -40,7 +40,8 @@ let package = Package( ), .package( url: "https://github.com/pointfreeco/swift-custom-dump.git", - .upToNextMajor(from: "1.6.1") + // Keep the IssueReporting package graph used by Dependencies 1.14. + .upToNextMinor(from: "1.6.1") ), .package( url: "https://github.com/onmyway133/Promptberry.git", diff --git a/README.md b/README.md index cd12005..690877d 100644 --- a/README.md +++ b/README.md @@ -32,6 +32,7 @@ name. - [Quick start](#quick-start) - [Desktop and terminal usage](#desktop-and-terminal-usage) - [Managing workspaces](#managing-workspaces) +- [Delivering links to a workspace](#delivering-links-to-a-workspace) - [App naming](#app-naming) - [Updates](#updates) - [Integration attributes](#integration-attributes) @@ -195,6 +196,7 @@ Arguments after `--` are forwarded unchanged to `codex` or `codex exec`. | Create and select it | `fxcodex workspace create --use` | | Create and open it | `fxcodex workspace create --open` | | Open or focus a workspace | `fxcodex open [name]` | +| Deliver a link to one workspace | `fxcodex open-url ` | | Select the current workspace | `fxcodex use [name]` | | Rename the current managed workspace | `fxcodex workspace rename ` | | Rename a specified managed workspace | `fxcodex workspace rename ` | @@ -222,6 +224,39 @@ fxcodex workspace paths work --no-all --codex-home --user-data Raw components are `workspace-root`, `codex-home`, and `user-data`. +## Delivering links to a workspace + +A plain `open codex://…` reaches whichever Codex instance macOS picks. To hand +a link, such as a sign-in callback, to one workspace's Codex: + +```sh +fxcodex open-url work 'codex://auth/callback?code=…' +``` + +If that workspace's Codex is running, fxcodex sends the link to its process +only, as a `kAEGetURL` Apple Event addressed by process ID, the same event +Launch Services would send. If it is not running, that workspace's Codex +launches with its own Codex home, profile and the link. The link never goes +through Launch Services' scheme routing. + +The command accepts the app-link schemes the installed Codex registers in its +`CFBundleURLTypes` (`codex` today); `http` and `https` are not app links and are +rejected. It exits non-zero with a one-line message on stderr when the workspace +doesn't exist, Codex doesn't handle the link, or delivery fails. `--json` +returns the workspace, process ID and `delivery` (`apple-event` or `launch`). + +The first link sent to a running instance can trigger macOS's Automation prompt +("… wants to control Codex") for the app that runs fxcodex, such as Terminal or +Arx. If it was declined, allow it in System Settings > Privacy & Security > +Automation. + +In Arx, Air Traffic Control can run a script for `codex://` links, chosen per +profile, with the link as `$1`: + +```sh +fxcodex open-url work "$1" +``` + ## App naming App renaming is optional and independent of workspace isolation. Rename a valid @@ -380,6 +415,7 @@ integrations: fxcodex --json status --all FXCODEX_JSON=1 fxcodex workspace list fxcodex workspace paths work --json --no-user-data +fxcodex open-url work 'codex://…' --json fxcodex integrations attributes get raycast --path script_commands --json fxcodex integrations raycast install script-command \ --directory "$HOME/.config/raycast/script-commands" \ diff --git a/Scripts/fxcodex.entitlements b/Scripts/fxcodex.entitlements new file mode 100644 index 0000000..63c4f9f --- /dev/null +++ b/Scripts/fxcodex.entitlements @@ -0,0 +1,9 @@ + + + + + + com.apple.security.automation.apple-events + + + diff --git a/Scripts/sign-release.sh b/Scripts/sign-release.sh index 18ecbaf..e34145a 100755 --- a/Scripts/sign-release.sh +++ b/Scripts/sign-release.sh @@ -6,12 +6,14 @@ CODESIGN="${CODESIGN:-codesign}" SHASUM="${SHASUM:-shasum}" SIGNING_IDENTITY="${SIGNING_IDENTITY:-}" SIGNING_KEYCHAIN="${SIGNING_KEYCHAIN:-}" +ENTITLEMENTS="${ENTITLEMENTS:-$(dirname -- "$0")/fxcodex.entitlements}" usage() { printf '%s\n' \ "Usage: SIGNING_IDENTITY= ./Scripts/sign-release.sh ..." \ "" \ - "Signs each executable with hardened runtime and a secure timestamp," \ + "Signs each executable with hardened runtime, the entitlements in" \ + "Scripts/fxcodex.entitlements (override with ENTITLEMENTS) and a secure timestamp," \ "verifies the signature, and replaces its adjacent SHA-256 checksum." \ "Set SIGNING_KEYCHAIN when the identity is stored in a non-default keychain." } @@ -21,6 +23,11 @@ if [ -z "$SIGNING_IDENTITY" ] || [ "$#" -eq 0 ]; then exit 64 fi +if [ ! -f "$ENTITLEMENTS" ]; then + printf 'Missing entitlements: %s\n' "$ENTITLEMENTS" >&2 + exit 1 +fi + for executable in "$@"; do if [ ! -f "$executable" ]; then printf 'Missing executable: %s\n' "$executable" >&2 @@ -32,6 +39,7 @@ for executable in "$@"; do --force \ --keychain "$SIGNING_KEYCHAIN" \ --options runtime \ + --entitlements "$ENTITLEMENTS" \ --sign "$SIGNING_IDENTITY" \ --timestamp \ "$executable" @@ -39,6 +47,7 @@ for executable in "$@"; do "$CODESIGN" \ --force \ --options runtime \ + --entitlements "$ENTITLEMENTS" \ --sign "$SIGNING_IDENTITY" \ --timestamp \ "$executable" diff --git a/Sources/fxcodex-cli/AppCommand.swift b/Sources/fxcodex-cli/AppCommand.swift index 9c99e2c..6af077f 100644 --- a/Sources/fxcodex-cli/AppCommand.swift +++ b/Sources/fxcodex-cli/AppCommand.swift @@ -37,6 +37,7 @@ internal struct AppCommand: AsyncParsableCommand { WorkspaceCommand.Erase.self, RenameApplicationCommand.self, OpenCommand.self, + OpenURLCommand.self, CLICommand.self, ExecCommand.self, StatusCommand.self, diff --git a/Sources/fxcodex-cli/Commands/OpenURLCommand.swift b/Sources/fxcodex-cli/Commands/OpenURLCommand.swift new file mode 100644 index 0000000..697d399 --- /dev/null +++ b/Sources/fxcodex-cli/Commands/OpenURLCommand.swift @@ -0,0 +1,59 @@ +import ArgumentParser +import Dependencies +import FXCodexClient + +extension AppCommand { + internal struct OpenURLCommand: AsyncParsableCommand { + internal static let configuration: CommandConfiguration = .init( + commandName: "open-url", + abstract: "Deliver an app link to one workspace's Codex instance.", + discussion: """ + Sends a link such as codex://… to the named workspace's Codex only. A running + instance receives it as an Apple Event addressed to its process ID; otherwise + that workspace's Codex launches with the link. The link never goes through + Launch Services' scheme routing, so other workspaces never see it. + + The first delivery to a running instance can trigger macOS's Automation prompt + for the app that runs fxcodex. + + Air Traffic Control in Arx can run it as a profile's script: + fxcodex open-url work "$1" + """ + ) + + @Argument(help: "Workspace name, such as primary or work.") + internal var workspaceName: String + + @Argument(help: "The link to deliver, such as codex://….") + internal var url: String + + @Flag( + inversion: .prefixedNo, + exclusivity: .chooseLast, + help: "Print a versioned machine-readable JSON response. Defaults from FXCODEX_JSON." + ) + internal var json: Bool? + + internal init() {} + + internal func run() async throws { + @Dependency(\.fxCodexClient) + var client: FXCodexClient + + let delivery: URLDelivery = try await client.openURL(self.url, self.workspaceName) + + if machineOutputRequested(self.json) { + try printMachineResponse(OpenURLOutput(delivery)) + return + } + + let reporter: TerminalReporter = await .init() + switch delivery.method { + case .appleEvent: + await reporter.success("Sent the link to Codex · \(delivery.workspace.name) · pid \(delivery.processID).") + case .launch: + await reporter.success("Launched Codex · \(delivery.workspace.name) · pid \(delivery.processID) with the link.") + } + } + } +} diff --git a/Sources/fxcodex-cli/Models/OpenURLOutput.swift b/Sources/fxcodex-cli/Models/OpenURLOutput.swift new file mode 100644 index 0000000..71c80ae --- /dev/null +++ b/Sources/fxcodex-cli/Models/OpenURLOutput.swift @@ -0,0 +1,18 @@ +import Foundation +import FXCodexClient + +internal struct OpenURLOutput: Encodable { + internal let workspaceName: String + internal let workspaceID: WorkspaceID + internal let processID: Int32 + internal let delivery: URLDelivery.Method + + internal init( + _ delivery: URLDelivery + ) { + self.workspaceName = delivery.workspace.name + self.workspaceID = delivery.workspace.id + self.processID = delivery.processID + self.delivery = delivery.method + } +} diff --git a/Sources/fxcodex-client/Common/FXCodexError.swift b/Sources/fxcodex-client/Common/FXCodexError.swift index 8535aec..0bd9526 100644 --- a/Sources/fxcodex-client/Common/FXCodexError.swift +++ b/Sources/fxcodex-client/Common/FXCodexError.swift @@ -22,6 +22,8 @@ public enum FXCodexError: Error, Equatable, LocalizedError, Sendable { case updateExecutableInvalid(URL) case updateRequestFailed(Int) case unsupportedSchemaVersion(SchemaVersion) + case unsupportedURL(String, supportedSchemes: [String]) + case urlDeliveryFailed(String) case workspaceAlreadyExists(String) case workspaceIsRunning(String) case workspaceNotFound(String) @@ -49,6 +51,8 @@ public enum FXCodexError: Error, Equatable, LocalizedError, Sendable { case .updateExecutableInvalid: "update_executable_invalid" case .updateRequestFailed: "update_request_failed" case .unsupportedSchemaVersion: "unsupported_schema_version" + case .unsupportedURL: "unsupported_url" + case .urlDeliveryFailed: "url_delivery_failed" case .workspaceAlreadyExists: "workspace_already_exists" case .workspaceIsRunning: "workspace_is_running" case .workspaceNotFound: "workspace_not_found" @@ -120,6 +124,12 @@ public enum FXCodexError: Error, Equatable, LocalizedError, Sendable { case let .unsupportedSchemaVersion(version): "Storage schema \(version) is unsupported. This fxcodex build supports schema 2.0." + case let .unsupportedURL(url, supportedSchemes): + "Codex does not handle '\(url)'. Supported schemes: \(supportedSchemes.map { "\($0)://" }.joined(separator: ", "))." + + case let .urlDeliveryFailed(message): + "Could not deliver the link to Codex: \(message)" + case let .workspaceAlreadyExists(name): "Workspace '\(name)' already exists." diff --git a/Sources/fxcodex-client/FXCodexClient.swift b/Sources/fxcodex-client/FXCodexClient.swift index 62ab21e..0070d57 100644 --- a/Sources/fxcodex-client/FXCodexClient.swift +++ b/Sources/fxcodex-client/FXCodexClient.swift @@ -26,6 +26,7 @@ public struct FXCodexClient: Sendable { public var useWorkspaceByID: @Sendable (WorkspaceID) async throws -> Void public var openWorkspace: @Sendable (String?) async throws -> Int32 public var openWorkspaceByID: @Sendable (WorkspaceID) async throws -> Int32 + public var openURL: @Sendable (_ url: String, _ workspaceName: String) async throws -> URLDelivery public var codexInvocation: @Sendable (String?, [String]) async throws -> CommandInvocation public var status: @Sendable () async throws -> FXCodexStatus } @@ -63,6 +64,7 @@ extension DependencyValues { useWorkspaceByID: { try await manager.useWorkspace(id: $0) }, openWorkspace: manager.openWorkspace, openWorkspaceByID: { try await manager.openWorkspace(id: $0) }, + openURL: { try await manager.openURL($0, inWorkspaceNamed: $1) }, codexInvocation: { try await manager.codexInvocation(workspaceName: $0, arguments: $1) }, status: manager.status ) diff --git a/Sources/fxcodex-client/Manager/CodexApplicationClient.swift b/Sources/fxcodex-client/Manager/CodexApplicationClient.swift index ed506e2..ed03391 100644 --- a/Sources/fxcodex-client/Manager/CodexApplicationClient.swift +++ b/Sources/fxcodex-client/Manager/CodexApplicationClient.swift @@ -8,6 +8,9 @@ struct CodexApplicationClient: Sendable { var rename: @Sendable (CodexApplicationName) async throws -> CodexApplicationRenameResult var open: @Sendable (Workspace) async throws -> Int32 var runningProcessID: @Sendable (Workspace) async throws -> Int32? + var urlSchemes: @Sendable () async throws -> [String] + var sendURL: @Sendable (_ url: URL, _ processID: Int32) async throws -> Void + var launchWithURL: @Sendable (_ workspace: Workspace, _ url: URL) async throws -> Int32 var removeRecord: @Sendable (_ workspace: Workspace) async throws -> Void } @@ -31,6 +34,18 @@ extension DependencyValues { let controller: CodexApplicationController = await .init() return try await controller.runningProcessID(for: $0) }, + urlSchemes: { + let controller: CodexApplicationController = await .init() + return try await controller.urlSchemes() + }, + sendURL: { url, processID in + let controller: CodexApplicationController = await .init() + try await controller.send(url: url, toProcessID: processID) + }, + launchWithURL: { workspace, url in + let controller: CodexApplicationController = await .init() + return try await controller.launch(workspace: workspace, with: url) + }, removeRecord: { let controller: CodexApplicationController = await .init() try await controller.removeRecord(forWorkspaceID: $0.id) diff --git a/Sources/fxcodex-client/Manager/CodexApplicationController.swift b/Sources/fxcodex-client/Manager/CodexApplicationController.swift index 5d0d669..d088563 100644 --- a/Sources/fxcodex-client/Manager/CodexApplicationController.swift +++ b/Sources/fxcodex-client/Manager/CodexApplicationController.swift @@ -1,4 +1,5 @@ import AppKit +import CoreServices import Foundation import Dependencies @@ -112,6 +113,86 @@ public final class CodexApplicationController { guard let applicationURL = self.applicationURL() else { throw FXCodexError.applicationNotFound } + let application: NSRunningApplication = try await self.workspace.openApplication( + at: applicationURL, + configuration: self.launchConfiguration(for: workspace) + ) + try self.cache( + application: application, + forWorkspaceID: workspace.id + ) + + return application.processIdentifier + } + + /// URL schemes the installed Codex registers in `CFBundleURLTypes`, lowercased. + /// + /// Web schemes are left out: they are not app links. + public func urlSchemes() throws -> [String] { + guard let applicationURL = self.applicationURL() else { throw FXCodexError.applicationNotFound } + return Self.urlSchemes(ofApplicationAt: applicationURL) + } + + /// Sends a `kAEGetURL` Apple Event to one process, the way Launch Services delivers a link, + /// then brings that instance forward. + public func send( + url: URL, + toProcessID processID: Int32 + ) throws { + let event: NSAppleEventDescriptor = Self.getURLEvent( + url: url, + processID: processID + ) + + let reply: NSAppleEventDescriptor + do { + reply = try event.sendEvent( + options: [.waitForReply], + timeout: Self.appleEventTimeout + ) + } catch let error as NSError { + throw FXCodexError.urlDeliveryFailed( + Self.appleEventFailureMessage(code: error.code, processID: processID) + ) + } + + // The app's handler can reject the event; that error comes back in the reply, not as a throw. + if let code = Self.handlerErrorCode(in: reply) { + throw FXCodexError.urlDeliveryFailed( + Self.appleEventFailureMessage(code: code, processID: processID) + ) + } + + if let application = NSRunningApplication(processIdentifier: processID) { + application.unhide() + application.activate(options: [.activateAllWindows]) + } + } + + /// Launches a new instance of the workspace's Codex with the link, so it starts and + /// receives the link in one call. + public func launch( + workspace: Workspace, + with url: URL + ) async throws -> Int32 { + guard let applicationURL = self.applicationURL() else { throw FXCodexError.applicationNotFound } + + let application: NSRunningApplication = try await self.workspace.open( + [url], + withApplicationAt: applicationURL, + configuration: self.launchConfiguration(for: workspace) + ) + try self.cache( + application: application, + forWorkspaceID: workspace.id + ) + + return application.processIdentifier + } + + internal func launchConfiguration( + for workspace: Workspace + ) throws -> NSWorkspace.OpenConfiguration { let configuration: NSWorkspace.OpenConfiguration = .init() configuration.activates = true configuration.createsNewApplicationInstance = true @@ -131,16 +212,7 @@ public final class CodexApplicationController { ] } - let application: NSRunningApplication = try await self.workspace.openApplication( - at: applicationURL, - configuration: configuration - ) - try self.cache( - application: application, - forWorkspaceID: workspace.id - ) - - return application.processIdentifier + return configuration } public func runningProcessID(for workspace: Workspace) throws -> Int32? { @@ -260,3 +332,81 @@ public final class CodexApplicationController { self.applicationURL(for: .codex) } } + +extension CodexApplicationController { + nonisolated static let appleEventTimeout: TimeInterval = 15 + + nonisolated static let webURLSchemes: Set = ["file", "http", "https"] + + nonisolated static func urlSchemes( + ofApplicationAt applicationURL: URL + ) -> [String] { + guard + let bundle = Bundle(url: applicationURL), + let types = bundle.object(forInfoDictionaryKey: "CFBundleURLTypes") as? [[String: Any]] + else { return [] } + + return types + .flatMap { ($0["CFBundleURLSchemes"] as? [String]) ?? [] } + .map { $0.lowercased() } + .filter { !Self.webURLSchemes.contains($0) } + .reduce(into: [String]()) { schemes, scheme in + guard !schemes.contains(scheme) else { return } + schemes.append(scheme) + } + } + + /// A GURL event addressed to one process ID, never to a bundle identifier, + /// so no other instance of the same app can receive it. + nonisolated static func getURLEvent( + url: URL, + processID: Int32 + ) -> NSAppleEventDescriptor { + let event: NSAppleEventDescriptor = .init( + eventClass: AEEventClass(kInternetEventClass), + eventID: AEEventID(kAEGetURL), + targetDescriptor: NSAppleEventDescriptor(processIdentifier: processID), + returnID: AEReturnID(kAutoGenerateReturnID), + transactionID: AETransactionID(kAnyTransactionID) + ) + event.setParam( + NSAppleEventDescriptor(string: url.absoluteString), + forKeyword: AEKeyword(keyDirectObject) + ) + return event + } + + /// The nonzero `keyErrorNumber` an Apple Event reply carries when the handler failed. + nonisolated static func handlerErrorCode( + in reply: NSAppleEventDescriptor + ) -> Int? { + guard + let descriptor = reply.paramDescriptor(forKeyword: AEKeyword(keyErrorNumber)), + descriptor.int32Value != 0 + else { return nil } + + return Int(descriptor.int32Value) + } + + nonisolated static func appleEventFailureMessage( + code: Int, + processID: Int32 + ) -> String { + switch code { + case Int(errAEEventNotPermitted): + "macOS blocked Apple Events to Codex (pid \(processID)). Allow it in System Settings > Privacy & Security > Automation." + + case Int(procNotFound), Int(connectionInvalid): + "Codex (pid \(processID)) is no longer running." + + case Int(errAEEventNotHandled): + "Codex (pid \(processID)) did not accept the link." + + case Int(errAETimeout): + "Codex (pid \(processID)) did not answer within \(Int(Self.appleEventTimeout)) seconds." + + default: + "Apple Event to Codex (pid \(processID)) failed with OSStatus \(code)." + } + } +} diff --git a/Sources/fxcodex-client/Manager/CodexManager.swift b/Sources/fxcodex-client/Manager/CodexManager.swift index 13cf895..070e9f4 100644 --- a/Sources/fxcodex-client/Manager/CodexManager.swift +++ b/Sources/fxcodex-client/Manager/CodexManager.swift @@ -220,6 +220,42 @@ actor CodexManager { try await self.application.open(self.workspacesStorage.findWorkspaceByID(id)) } + /// Delivers an app link to one workspace's Codex instance. + /// + /// A running instance gets a `kAEGetURL` Apple Event addressed to its process ID. + /// Otherwise a new instance launches with the workspace's environment and the link. + /// Neither path asks Launch Services to route the link by scheme. + func openURL( + _ rawURL: String, + inWorkspaceNamed name: String + ) async throws -> URLDelivery { + let workspace: Workspace = try self.workspacesStorage.findWorkspace(named: name) + let schemes: [String] = try await self.application.urlSchemes() + + guard + let url = URL(string: rawURL), + let scheme = url.scheme?.lowercased(), + schemes.contains(scheme) + else { throw FXCodexError.unsupportedURL(rawURL, supportedSchemes: schemes) } + + if let processID = try await self.application.runningProcessID(workspace) { + try await self.application.sendURL(url, processID) + return .init( + workspace: workspace, + url: url, + processID: processID, + method: .appleEvent + ) + } + + return .init( + workspace: workspace, + url: url, + processID: try await self.application.launchWithURL(workspace, url), + method: .launch + ) + } + func codexInvocation( workspaceName: String?, arguments: [String] diff --git a/Sources/fxcodex-client/Models/URLDelivery.swift b/Sources/fxcodex-client/Models/URLDelivery.swift new file mode 100644 index 0000000..51af66b --- /dev/null +++ b/Sources/fxcodex-client/Models/URLDelivery.swift @@ -0,0 +1,29 @@ +import Foundation + +/// How `openURL` handed a link to a workspace's Codex instance. +public struct URLDelivery: Codable, Equatable, Sendable { + public enum Method: String, Codable, Equatable, Sendable { + /// The instance was running and received a `kAEGetURL` Apple Event addressed by process ID. + case appleEvent = "apple-event" + + /// The instance was not running and launched with the link. + case launch + } + + public let workspace: Workspace + public let url: URL + public let processID: Int32 + public let method: Method + + public init( + workspace: Workspace, + url: URL, + processID: Int32, + method: Method + ) { + self.workspace = workspace + self.url = url + self.processID = processID + self.method = method + } +} diff --git a/Tests/fxcodex-cli-tests/OpenCommandTests.swift b/Tests/fxcodex-cli-tests/OpenCommandTests.swift index cbb3b43..9c88fb3 100644 --- a/Tests/fxcodex-cli-tests/OpenCommandTests.swift +++ b/Tests/fxcodex-cli-tests/OpenCommandTests.swift @@ -17,3 +17,25 @@ struct OpenCommandTests { #expect(command.workspaceName == nil) } } + +@Suite("Open URL command") +struct OpenURLCommandTests { + @Test("Takes the workspace and the link as positional arguments") + func arguments() async throws { + let command: AppCommand.OpenURLCommand = try .parse(["work", "codex://login/callback?code=1"]) + #expect(command.workspaceName == "work") + #expect(command.url == "codex://login/callback?code=1") + } + + @Test("Requires both the workspace and the link") + func missingArguments() async throws { + #expect(throws: (any Error).self) { + _ = try AppCommand.OpenURLCommand.parse(["work"]) + } + } + + @Test("Is registered as a root subcommand") + func registered() { + #expect(AppCommand.configuration.subcommands.contains { $0 == AppCommand.OpenURLCommand.self }) + } +} diff --git a/Tests/fxcodex-client-tests/Client/OpenURLTests.swift b/Tests/fxcodex-client-tests/Client/OpenURLTests.swift new file mode 100644 index 0000000..5b7de7f --- /dev/null +++ b/Tests/fxcodex-client-tests/Client/OpenURLTests.swift @@ -0,0 +1,166 @@ +import Dependencies +import Foundation +import Testing +@_spi(Internals) +@testable +import FXCodexClient + +@Suite("Open URL") +struct OpenURLTests { + private let link: String = "codex://auth/callback?code=abc&state=xyz" + + @Test("A running workspace gets the link at its own process ID only") + func runningInstance() async throws { + let fixture: ClientTestFixture = try .init() + let application: CodexApplicationSpy = .init() + defer { fixture.remove() } + + try await self.withClient(fixture, application) { client in + _ = try await client.createWorkspace("work") + _ = try await client.createWorkspace("personal") + await application.setProcessID(1_001, forWorkspaceNamed: Workspace.primaryName) + await application.setProcessID(2_002, forWorkspaceNamed: "work") + await application.setProcessID(3_003, forWorkspaceNamed: "personal") + + let delivery: URLDelivery = try await client.openURL(self.link, "work") + + #expect(delivery.workspace.name == "work") + #expect(delivery.processID == 2_002) + #expect(delivery.method == .appleEvent) + #expect(delivery.url.absoluteString == self.link) + } + + let snapshot: CodexApplicationSpy.Snapshot = await application.snapshot() + #expect(snapshot.sentURLs == [.init(url: try #require(URL(string: self.link)), processID: 2_002)]) + #expect(snapshot.launchedURLs.isEmpty) + #expect(snapshot.openedWorkspaceNames.isEmpty) + } + + @Test("A stopped workspace launches with the link") + func stoppedInstance() async throws { + let fixture: ClientTestFixture = try .init() + let application: CodexApplicationSpy = .init(openedProcessID: 7_007) + defer { fixture.remove() } + + try await self.withClient(fixture, application) { client in + _ = try await client.createWorkspace("work") + await application.setProcessID(1_001, forWorkspaceNamed: Workspace.primaryName) + + let delivery: URLDelivery = try await client.openURL(self.link, "work") + + #expect(delivery.processID == 7_007) + #expect(delivery.method == .launch) + } + + let snapshot: CodexApplicationSpy.Snapshot = await application.snapshot() + #expect(snapshot.launchedURLs == [.init(workspaceName: "work", url: try #require(URL(string: self.link)))]) + #expect(snapshot.sentURLs.isEmpty) + } + + @Test("Scheme matching ignores case and accepts every registered scheme") + func registeredSchemes() async throws { + let fixture: ClientTestFixture = try .init() + let application: CodexApplicationSpy = .init(processIDs: ["primary": 1_001]) + defer { fixture.remove() } + + try await self.withClient(fixture, application) { client in + _ = try await client.openURL("CODEX://new", Workspace.primaryName) + _ = try await client.openURL("codex://threads/1", Workspace.primaryName) + } + + let snapshot: CodexApplicationSpy.Snapshot = await application.snapshot() + #expect(snapshot.sentURLs.map(\.processID) == [1_001, 1_001]) + } + + @Test("An unknown workspace fails before anything is delivered") + func unknownWorkspace() async throws { + let fixture: ClientTestFixture = try .init() + let application: CodexApplicationSpy = .init(processIDs: ["primary": 1_001]) + defer { fixture.remove() } + + try await self.withClient(fixture, application) { client in + await #expect(throws: FXCodexError.workspaceNotFound("work")) { + _ = try await client.openURL(self.link, "work") + } + } + + let snapshot: CodexApplicationSpy.Snapshot = await application.snapshot() + #expect(snapshot.sentURLs.isEmpty) + #expect(snapshot.launchedURLs.isEmpty) + } + + @Test("Links Codex does not handle are rejected") + func unsupportedURL() async throws { + let fixture: ClientTestFixture = try .init() + let application: CodexApplicationSpy = .init(processIDs: ["primary": 1_001]) + defer { fixture.remove() } + + try await self.withClient(fixture, application) { client in + for rawURL in ["https://chatgpt.com/auth", "claude://login/callback", "not a url", ""] { + await #expect( + throws: FXCodexError.unsupportedURL( + rawURL, + supportedSchemes: ["codex"] + ) + ) { + _ = try await client.openURL(rawURL, Workspace.primaryName) + } + } + } + + let snapshot: CodexApplicationSpy.Snapshot = await application.snapshot() + #expect(snapshot.sentURLs.isEmpty) + #expect(snapshot.launchedURLs.isEmpty) + } + + @Test("Delivery failures surface instead of launching another instance") + func deliveryFailure() async throws { + let fixture: ClientTestFixture = try .init() + let failure: FXCodexError = .urlDeliveryFailed("blocked") + let application: CodexApplicationSpy = .init( + processIDs: ["primary": 1_001], + sendError: failure + ) + defer { fixture.remove() } + + try await self.withClient(fixture, application) { client in + await #expect(throws: failure) { + _ = try await client.openURL(self.link, Workspace.primaryName) + } + } + + let snapshot: CodexApplicationSpy.Snapshot = await application.snapshot() + #expect(snapshot.launchedURLs.isEmpty) + } + + @Test("A missing Codex installation is reported") + func missingApplication() async throws { + let fixture: ClientTestFixture = try .init() + let application: CodexApplicationSpy = .init(urlSchemes: nil) + defer { fixture.remove() } + + try await self.withClient(fixture, application) { client in + await #expect(throws: FXCodexError.applicationNotFound) { + _ = try await client.openURL(self.link, Workspace.primaryName) + } + } + } + + private func withClient( + _ fixture: ClientTestFixture, + _ application: CodexApplicationSpy, + operation: (FXCodexClient) async throws -> Void + ) async throws { + try await withDependencies { + $0.context = .live + $0._fxcodexApplication = application.client + $0._fxcodexPaths = .init(rootURL: fixture.rootURL) + $0._fxcodexRaycast = .fixture + } operation: { + @Dependency(\.fxCodexClient) + var client: FXCodexClient + + try await operation(client) + } + } +} diff --git a/Tests/fxcodex-client-tests/Fixtures/ClientTestFixture.swift b/Tests/fxcodex-client-tests/Fixtures/ClientTestFixture.swift index 1ca46b3..ee8b461 100644 --- a/Tests/fxcodex-client-tests/Fixtures/ClientTestFixture.swift +++ b/Tests/fxcodex-client-tests/Fixtures/ClientTestFixture.swift @@ -51,7 +51,8 @@ final class ClientTestFixture { func makeApplication( named name: String, - bundleIdentifier: String = CodexApplicationController.bundleIdentifier + bundleIdentifier: String = CodexApplicationController.bundleIdentifier, + urlSchemes: [[String]] = [] ) throws -> URL { let applicationURL: URL = self.applicationsURL.appending( path: "\(name).app", @@ -66,12 +67,15 @@ final class ClientTestFixture { withIntermediateDirectories: true, attributes: nil ) - let information: [String: Any] = [ + var information: [String: Any] = [ "CFBundleIdentifier": bundleIdentifier, "CFBundleName": name, "CFBundlePackageType": "APPL", "CFBundleVersion": "1", ] + if !urlSchemes.isEmpty { + information["CFBundleURLTypes"] = urlSchemes.map { ["CFBundleURLSchemes": $0] } + } let data: Data = try PropertyListSerialization.data( fromPropertyList: information, format: .xml, @@ -113,6 +117,18 @@ actor CodexApplicationSpy { let openedWorkspaceNames: [String] let removedWorkspaceNames: [String] let renamedWorkspaces: [WorkspaceRename] + let sentURLs: [SentURL] + let launchedURLs: [LaunchedURL] + } + + struct SentURL: Equatable, Sendable { + let url: URL + let processID: Int32 + } + + struct LaunchedURL: Equatable, Sendable { + let workspaceName: String + let url: URL } struct WorkspaceRename: Equatable, Sendable { @@ -130,14 +146,22 @@ actor CodexApplicationSpy { private var processIDs: [String: Int32] private var removedWorkspaceNames: [String] = [] private var renamedWorkspaces: [WorkspaceRename] = [] + private var sentURLs: [SentURL] = [] + private var launchedURLs: [LaunchedURL] = [] + private let urlSchemesValue: [String]? + private let sendError: FXCodexError? init( applicationURL: URL? = nil, openedProcessID: Int32 = 4_242, processIDs: [String: Int32] = [:], renameError: FXCodexError? = nil, - renameOutcome: CodexApplicationRenameResult.Outcome = .alreadyNamed + renameOutcome: CodexApplicationRenameResult.Outcome = .alreadyNamed, + urlSchemes: [String]? = ["codex"], + sendError: FXCodexError? = nil ) { + self.urlSchemesValue = urlSchemes + self.sendError = sendError self.applicationURLValue = applicationURL self.openedProcessID = openedProcessID self.processIDs = processIDs @@ -151,6 +175,9 @@ actor CodexApplicationSpy { rename: { try await self.rename(to: $0) }, open: { await self.open($0) }, runningProcessID: { await self.runningProcessID(for: $0) }, + urlSchemes: { try await self.urlSchemes() }, + sendURL: { try await self.sendURL($0, toProcessID: $1) }, + launchWithURL: { await self.launch($0, with: $1) }, removeRecord: { await self.removeRecord(for: $0.name) } ) } @@ -168,7 +195,9 @@ actor CodexApplicationSpy { requestedApplicationNames: self.requestedApplicationNames, openedWorkspaceNames: self.openedWorkspaceNames, removedWorkspaceNames: self.removedWorkspaceNames, - renamedWorkspaces: self.renamedWorkspaces + renamedWorkspaces: self.renamedWorkspaces, + sentURLs: self.sentURLs, + launchedURLs: self.launchedURLs ) } @@ -205,6 +234,28 @@ actor CodexApplicationSpy { self.processIDs[workspace.name] } + private func urlSchemes() throws -> [String] { + guard let urlSchemesValue else { throw FXCodexError.applicationNotFound } + return urlSchemesValue + } + + private func sendURL( + _ url: URL, + toProcessID processID: Int32 + ) throws { + if let sendError { throw sendError } + self.sentURLs.append(.init(url: url, processID: processID)) + } + + private func launch( + _ workspace: Workspace, + with url: URL + ) -> Int32 { + self.launchedURLs.append(.init(workspaceName: workspace.name, url: url)) + self.processIDs[workspace.name] = self.openedProcessID + return self.openedProcessID + } + private func removeRecord(for name: String) { self.processIDs.removeValue(forKey: name) self.removedWorkspaceNames.append(name) diff --git a/Tests/fxcodex-client-tests/Manager/CodexApplicationControllerTests.swift b/Tests/fxcodex-client-tests/Manager/CodexApplicationControllerTests.swift index f0dac98..a4883cd 100644 --- a/Tests/fxcodex-client-tests/Manager/CodexApplicationControllerTests.swift +++ b/Tests/fxcodex-client-tests/Manager/CodexApplicationControllerTests.swift @@ -1,3 +1,5 @@ +import AppKit +import CoreServices import Dependencies import Foundation import Testing @@ -153,6 +155,132 @@ struct CodexApplicationControllerTests { } } + @Test("Managed launches carry the workspace's Codex home and profile; primary carries none") + @MainActor + func launchConfiguration() async throws { + let fixture: ClientTestFixture = try .init() + defer { fixture.remove() } + let codexHomeURL: URL = fixture.rootURL.appending(path: "work/codex-home", directoryHint: .isDirectory) + let userDataURL: URL = fixture.rootURL.appending(path: "work/user-data", directoryHint: .isDirectory) + let work: Workspace = .init( + name: "work", + kind: .managed, + rootURL: fixture.rootURL, + codexHomeURL: codexHomeURL, + userDataURL: userDataURL + ) + let primary: Workspace = .init( + name: Workspace.primaryName, + kind: .primary, + rootURL: fixture.rootURL, + codexHomeURL: nil, + userDataURL: nil + ) + let controller: CodexApplicationController = self.controller(for: fixture) + let workConfiguration = try controller.launchConfiguration(for: work) + let primaryConfiguration = try controller.launchConfiguration(for: primary) + + #expect(workConfiguration.createsNewApplicationInstance) + #expect(workConfiguration.environment == [ + "CODEX_ELECTRON_USER_DATA_PATH": userDataURL.path, + "CODEX_HOME": codexHomeURL.path, + ]) + #expect(workConfiguration.arguments == ["--user-data-dir=\(userDataURL.path)"]) + #expect(primaryConfiguration.createsNewApplicationInstance) + #expect(primaryConfiguration.environment.isEmpty) + #expect(primaryConfiguration.arguments.isEmpty) + } + + @Test("Reads app link schemes from the installed bundle and drops web schemes") + @MainActor + func urlSchemes() async throws { + let fixture: ClientTestFixture = try .init() + defer { fixture.remove() } + _ = try fixture.makeApplication( + named: "Codex", + urlSchemes: [ + ["codex", "http", "HTTPS", "Codex"], + ] + ) + + #expect(try self.controller(for: fixture).urlSchemes() == ["codex"]) + } + + @Test("Link schemes need an installed Codex") + @MainActor + func urlSchemesWithoutApplication() async throws { + let fixture: ClientTestFixture = try .init() + defer { fixture.remove() } + + #expect(throws: FXCodexError.applicationNotFound) { + try self.controller(for: fixture).urlSchemes() + } + } + + @Test("The GURL Apple Event is addressed to one process ID and carries the link") + func getURLEvent() throws { + let link: String = "codex://auth/callback?code=abc" + let event: NSAppleEventDescriptor = CodexApplicationController.getURLEvent( + url: try #require(URL(string: link)), + processID: 4_321 + ) + let target: NSAppleEventDescriptor = try #require( + event.attributeDescriptor(forKeyword: AEKeyword(keyAddressAttr)) + ) + let processID: Int32 = target.data.withUnsafeBytes { $0.load(as: Int32.self) } + + #expect(event.eventClass == AEEventClass(kInternetEventClass)) + #expect(event.eventID == AEEventID(kAEGetURL)) + #expect(target.descriptorType == DescType(typeKernelProcessID)) + #expect(processID == 4_321) + #expect(event.paramDescriptor(forKeyword: AEKeyword(keyDirectObject))?.stringValue == link) + } + + @Test("Apple Event failures explain what to do") + func appleEventFailureMessages() { + let denied: String = CodexApplicationController.appleEventFailureMessage( + code: Int(errAEEventNotPermitted), + processID: 12 + ) + let gone: String = CodexApplicationController.appleEventFailureMessage( + code: Int(procNotFound), + processID: 12 + ) + let rejected: String = CodexApplicationController.appleEventFailureMessage( + code: Int(errAEEventNotHandled), + processID: 12 + ) + + #expect(denied.contains("Privacy & Security > Automation")) + #expect(gone == "Codex (pid 12) is no longer running.") + #expect(rejected == "Codex (pid 12) did not accept the link.") + } + + @Test("A handler error in the reply counts as a failed delivery") + func replyHandlerError() { + let success: NSAppleEventDescriptor = .appleEvent( + withEventClass: AEEventClass(kCoreEventClass), + eventID: AEEventID(kAEAnswer), + targetDescriptor: nil, + returnID: AEReturnID(kAutoGenerateReturnID), + transactionID: AETransactionID(kAnyTransactionID) + ) + let failure: NSAppleEventDescriptor = .appleEvent( + withEventClass: AEEventClass(kCoreEventClass), + eventID: AEEventID(kAEAnswer), + targetDescriptor: nil, + returnID: AEReturnID(kAutoGenerateReturnID), + transactionID: AETransactionID(kAnyTransactionID) + ) + failure.setParam( + NSAppleEventDescriptor(int32: Int32(errAEEventNotHandled)), + forKeyword: AEKeyword(keyErrorNumber) + ) + + #expect(CodexApplicationController.handlerErrorCode(in: success) == nil) + #expect(CodexApplicationController.handlerErrorCode(in: failure) == Int(errAEEventNotHandled)) + } + @MainActor private func controller( for fixture: ClientTestFixture