Skip to content
Closed
48 changes: 47 additions & 1 deletion CLI/cmux.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1403,9 +1403,16 @@ struct CMUXCLI {
return
}

// Explicit `open` command: cmux open /path/to/folder [--window <id>]
if command == "open" {
let openPath = commandArgs.first ?? "."
try openProjectPath(openPath, socketPath: resolvedSocketPath, windowId: windowId)
return
}

// If the argument looks like a path (not a known command), open a workspace there.
if looksLikePath(command) {
try openPath(command, socketPath: resolvedSocketPath)
try openProjectPath(command, socketPath: resolvedSocketPath, windowId: windowId)
return
}

Expand Down Expand Up @@ -2490,6 +2497,45 @@ struct CMUXCLI {
try activateApp()
}

/// Open a project via the project.open socket command (supports .cmux.yaml).
private func openProjectPath(_ path: String, socketPath: String, windowId: String?) throws {
let resolved = resolvePath(path)
var isDir: ObjCBool = false
let exists = FileManager.default.fileExists(atPath: resolved, isDirectory: &isDir)

let directory: String
if exists && isDir.boolValue {
directory = resolved
} else if exists {
directory = (resolved as NSString).deletingLastPathComponent
} else {
throw CLIError(message: "Path does not exist: \(resolved)")
}

let client = SocketClient(path: socketPath)

@cubic-dev-ai cubic-dev-ai Bot Mar 25, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: openProjectPath bypasses socket authentication, so cmux open can fail in password-protected socket mode.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At CLI/cmux.swift, line 2515:

<comment>`openProjectPath` bypasses socket authentication, so `cmux open` can fail in password-protected socket mode.</comment>

<file context>
@@ -2490,6 +2497,45 @@ struct CMUXCLI {
+            throw CLIError(message: "Path does not exist: \(resolved)")
+        }
+
+        let client = SocketClient(path: socketPath)
+        if (try? client.connect()) == nil {
+            client.close()
</file context>
Fix with Cubic

if (try? client.connect()) == nil {
client.close()
try launchApp()
let launchedClient = try SocketClient.waitForConnectableSocket(path: socketPath, timeout: 10)
defer { launchedClient.close() }
var params: [String: Any] = ["path": directory]
if let windowId { params["window_id"] = windowId }
let response = try launchedClient.sendV2(method: "project.open", params: params)
let groupId = (response["group_id"] as? String) ?? ""
if !groupId.isEmpty { print("OK \(groupId)") }
try activateApp()
return
}
defer { client.close() }

var params: [String: Any] = ["path": directory]
if let windowId { params["window_id"] = windowId }
let response = try client.sendV2(method: "project.open", params: params)
let groupId = (response["group_id"] as? String) ?? ""
if !groupId.isEmpty { print("OK \(groupId)") }
try activateApp()
}

private func runFeedback(
commandArgs: [String],
socketPath: String,
Expand Down
142 changes: 141 additions & 1 deletion GhosttyTabs.xcodeproj/project.pbxproj

Large diffs are not rendered by default.

26 changes: 4 additions & 22 deletions Resources/Info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@
<string></string>
<key>NSMainStoryboardFile</key>
<string></string>
<key>NSLocalNetworkUsageDescription</key>
<string>cmux scans listening ports on your terminal processes to display active servers in the workspace sidebar.</string>
<key>NSMicrophoneUsageDescription</key>
<string>A program running within cmux would like to use your microphone.</string>
<key>NSCameraUsageDescription</key>
Expand Down Expand Up @@ -73,10 +75,10 @@
<key>NSMenuItem</key>
<dict>
<key>default</key>
<string>New $(PRODUCT_NAME) Workspace Here</string>
<string>Open in $(PRODUCT_NAME)</string>
</dict>
<key>NSMessage</key>
<string>openTab</string>
<string>openInCmux</string>
<key>NSRequiredContext</key>
<dict>
<key>NSTextContent</key>
Expand All @@ -85,26 +87,6 @@
<key>NSSendTypes</key>
<array>
<string>NSFilenamesPboardType</string>
<string>public.plain-text</string>
</array>
</dict>
<dict>
<key>NSMenuItem</key>
<dict>
<key>default</key>
<string>New $(PRODUCT_NAME) Window Here</string>
</dict>
<key>NSMessage</key>
<string>openWindow</string>
<key>NSRequiredContext</key>
<dict>
<key>NSTextContent</key>
<string>FilePath</string>
</dict>
<key>NSSendTypes</key>
<array>
<string>NSFilenamesPboardType</string>
<string>public.plain-text</string>
</array>
</dict>
</array>
Expand Down
163 changes: 155 additions & 8 deletions Sources/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2331,6 +2331,9 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent
installMenuBarVisibilityObserver()
syncMenuBarExtraVisibility()
updateController.startUpdaterIfNeeded()
NSApp.servicesProvider = self
ScriptRepository.shared.seedDefaultScripts()
TemplateRepository.shared.seedDefaultTemplates()
}
titlebarAccessoryController.start()
windowDecorationsController.start()
Expand Down Expand Up @@ -4231,6 +4234,11 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent
mainWindowContexts.values.first(where: { $0.windowId == windowId })?.tabManager
}

/// Returns all TabManagers across all windows.
func allTabManagers() -> [TabManager] {
mainWindowContexts.values.map(\.tabManager)
}

func windowId(for tabManager: TabManager) -> UUID? {
mainWindowContexts.values.first(where: { $0.tabManager === tabManager })?.windowId
}
Expand Down Expand Up @@ -4764,13 +4772,10 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent
alert.addButton(withTitle: String(localized: "common.close", defaultValue: "Close"))
alert.addButton(withTitle: String(localized: "common.cancel", defaultValue: "Cancel"))

let alertWindow = alert.window
if let closeButton = alert.buttons.first {
alertWindow.defaultButtonCell = closeButton.cell as? NSButtonCell
alertWindow.initialFirstResponder = closeButton
DispatchQueue.main.async {
_ = alertWindow.makeFirstResponder(closeButton)
}
// Mark the Close button as destructive so the system renders it with
// red text, fixing a contrast issue in dark mode.
if #available(macOS 12.0, *) {
alert.buttons[0].hasDestructiveAction = true
}

return alert.runModal() == .alertFirstButtonReturn
Expand Down Expand Up @@ -5186,6 +5191,26 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent
return nil
}

/// Resolve the best current `TabManager` for menu/UI reads without mutating
/// the app-wide active window pointers. Use this in SwiftUI computed properties
/// and CommandMenu closures to avoid triggering @Published re-evaluation loops.
func preferredTabManager(preferredWindow: NSWindow? = nil) -> TabManager? {
if let preferredWindow,
let context = contextForMainWindow(preferredWindow) {
return context.tabManager
}
if let context = contextForMainWindow(NSApp.keyWindow) {
return context.tabManager
}
if let context = contextForMainWindow(NSApp.mainWindow) {
return context.tabManager
}
if let activeManager = tabManager {
return activeManager
}
return mainWindowContexts.values.first?.tabManager
}

/// Re-sync app-level active window pointers from the currently focused main terminal window.
/// This keeps menu/shortcut actions window-scoped even if the cached `tabManager` drifts.
@discardableResult
Expand Down Expand Up @@ -11330,6 +11355,129 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent
}
#endif

// MARK: - Finder Services

/// macOS Services handler: "Open in cmux"
/// Accepts folder paths from Finder right-click > Services.
@objc func openInCmux(
_ pasteboard: NSPasteboard,
userData: String,
error: AutoreleasingUnsafeMutablePointer<NSString>
) {
guard let items = pasteboard.readObjects(forClasses: [NSURL.self], options: [
.urlReadingFileURLsOnly: true
]) as? [URL] else { return }

// Use the first window's tab manager, or create a window if none exists
let tm: TabManager
if let firstWindowSummary = listMainWindowSummaries().first,

@cubic-dev-ai cubic-dev-ai Bot Mar 25, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Finder service selects the target window via listMainWindowSummaries().first, which is built from Dictionary values and therefore unordered. With multiple windows open, this can route Finder service opens to an arbitrary background window instead of the key/main window.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At Sources/AppDelegate.swift, line 11376:

<comment>Finder service selects the target window via listMainWindowSummaries().first, which is built from Dictionary values and therefore unordered. With multiple windows open, this can route Finder service opens to an arbitrary background window instead of the key/main window.</comment>

<file context>
@@ -11330,6 +11358,129 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent
+
+        // Use the first window's tab manager, or create a window if none exists
+        let tm: TabManager
+        if let firstWindowSummary = listMainWindowSummaries().first,
+           let existingTm = tabManagerFor(windowId: firstWindowSummary.windowId) {
+            tm = existingTm
</file context>
Fix with Cubic

let existingTm = tabManagerFor(windowId: firstWindowSummary.windowId) {
tm = existingTm
} else if let firstURL = items.first {
let path = resolvedDirectoryPath(for: firstURL)
_ = createMainWindow(initialWorkingDirectory: path)
NSApp.activate(ignoringOtherApps: true)
return

@cubic-dev-ai cubic-dev-ai Bot Mar 25, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Finder Services return immediately after creating a cold-start window, so only the first selected item is opened and template services never apply the template on cold start.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At Sources/AppDelegate.swift, line 11383:

<comment>Finder Services return immediately after creating a cold-start window, so only the first selected item is opened and template services never apply the template on cold start.</comment>

<file context>
@@ -11330,6 +11358,129 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent
+            let path = resolvedDirectoryPath(for: firstURL)
+            _ = createMainWindow(initialWorkingDirectory: path)
+            NSApp.activate(ignoringOtherApps: true)
+            return
+        } else {
+            return
</file context>
Fix with Cubic

} else {
return
}

for url in items {
var isDir: ObjCBool = false
let path: String
if FileManager.default.fileExists(atPath: url.path, isDirectory: &isDir), isDir.boolValue {
path = url.path
} else {
path = url.deletingLastPathComponent().path
}

let dirURL = URL(fileURLWithPath: path)
let canonicalPath = dirURL.resolvingSymlinksInPath().path

// Dedupe: check if a parent workspace already targets this directory
var found = false
for wsId in tm.items {
guard let ws = tm.workspace(for: wsId),
ws.hasChildren else { continue }
let wsPath = URL(fileURLWithPath: ws.currentDirectory)
.resolvingSymlinksInPath().path
if wsPath == canonicalPath {
tm.selectedTabId = ws.id
found = true
break
}
}
if found { continue }

// Create project workspace
let projectName = dirURL.lastPathComponent
let ws = tm.addWorkspace(workingDirectory: path, select: true)
ws.title = projectName
}

NSApp.activate(ignoringOtherApps: true)
}

// MARK: - Finder Services (Builder / Fixer)

@objc func openInCmuxBuilder(
_ pasteboard: NSPasteboard,
userData: String,
error: AutoreleasingUnsafeMutablePointer<NSString>
) {
openInCmuxWithTemplate(pasteboard, templateName: "Builder", error: error)
}

@objc func openInCmuxFixer(
_ pasteboard: NSPasteboard,
userData: String,
error: AutoreleasingUnsafeMutablePointer<NSString>
) {
openInCmuxWithTemplate(pasteboard, templateName: "Fixer", error: error)
}

private func openInCmuxWithTemplate(
_ pasteboard: NSPasteboard,
templateName: String,
error: AutoreleasingUnsafeMutablePointer<NSString>
) {
guard let items = pasteboard.readObjects(forClasses: [NSURL.self], options: [
.urlReadingFileURLsOnly: true
]) as? [URL] else { return }

guard let firstWindowSummary = listMainWindowSummaries().first,
let tm = tabManagerFor(windowId: firstWindowSummary.windowId) else {
// No window exists — create one for the first directory
if let firstURL = items.first {
let path = resolvedDirectoryPath(for: firstURL)
_ = createMainWindow(initialWorkingDirectory: path)
}
return
}

let template = try? TemplateRepository.shared.getTemplate(named: templateName)

for url in items {
let path = resolvedDirectoryPath(for: url)
if let template {
tm.openTemplate(template, directory: path)
} else {
// Fallback: plain workspace if template not found
let ws = tm.addWorkspace(workingDirectory: path, select: true)
ws.title = URL(fileURLWithPath: path).lastPathComponent
}
}

NSApp.activate(ignoringOtherApps: true)
}

private func resolvedDirectoryPath(for url: URL) -> String {
var isDir: ObjCBool = false
if FileManager.default.fileExists(atPath: url.path, isDirectory: &isDir), isDir.boolValue {
return url.path
}
return url.deletingLastPathComponent().path
}
}

@MainActor
Expand Down Expand Up @@ -12673,5 +12821,4 @@ private extension NSWindow {
}
return hitWebView === webView
}

}
33 changes: 33 additions & 0 deletions Sources/CmuxConfigError.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import Foundation

/// Fatal errors during `.cmux.yaml` parsing. Thrown for unrecoverable failures.
enum CmuxConfigError: Error, Equatable {
case invalidYaml(details: String)
case fileNotReadable(path: String)
}

/// Non-fatal warnings during `.cmux.yaml` parsing.
/// The config is still applied, but with the warned items degraded.
enum CmuxConfigWarning: Equatable {
/// A referenced startup script was not found in the script repository.
case scriptNotFound(name: String)
/// A sub-group tried to nest groups beyond the 2-level limit.
case maxDepthExceeded(groupName: String)
}

/// Result of parsing a `.cmux.yaml` file.
/// Contains the project definition plus any non-fatal warnings.
struct ConfigParseResult {
let projectName: String
let projectColor: String?
let warnings: [CmuxConfigWarning]
/// Tab definitions with their startup script names (to be resolved later).
let tabDefinitions: [ConfigTabDefinition]
}

/// A tab definition from `.cmux.yaml`, not yet resolved to a workspace.
struct ConfigTabDefinition {
let title: String
let startupScript: String?
let groupPath: [String] // empty = top-level, ["sub"] = inside sub-group "sub"
}
Loading