Skip to content
35 changes: 35 additions & 0 deletions CLI/cmux.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1767,6 +1767,19 @@ struct CMUXCLI {
case "markdown":
try runMarkdownCommand(commandArgs: commandArgs, client: client, jsonOutput: jsonOutput, idFormat: idFormat)

// Popup terminal commands
case "popup-terminal-toggle":
let payload = try client.sendV2(method: "popup-terminal.toggle", params: [:])
printV2Payload(payload, jsonOutput: jsonOutput, idFormat: idFormat, fallbackText: v2OKSummary(payload, idFormat: idFormat))

case "popup-terminal-show":
let payload = try client.sendV2(method: "popup-terminal.show", params: [:])
printV2Payload(payload, jsonOutput: jsonOutput, idFormat: idFormat, fallbackText: v2OKSummary(payload, idFormat: idFormat))

case "popup-terminal-hide":
let payload = try client.sendV2(method: "popup-terminal.hide", params: [:])
printV2Payload(payload, jsonOutput: jsonOutput, idFormat: idFormat, fallbackText: v2OKSummary(payload, idFormat: idFormat))

Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
default:
print(usage())
throw CLIError(message: "Unknown command: \(command)")
Expand Down Expand Up @@ -5315,6 +5328,24 @@ struct CMUXCLI {
cmux markdown ~/project/CHANGELOG.md
cmux markdown open ./docs/design.md --workspace 0
"""
case "popup-terminal-toggle":
return """
Usage: cmux popup-terminal-toggle

Toggle the global popup terminal.
"""
case "popup-terminal-show":
return """
Usage: cmux popup-terminal-show

Show the global popup terminal.
"""
case "popup-terminal-hide":
return """
Usage: cmux popup-terminal-hide

Hide the global popup terminal.
"""
default:
return nil
}
Expand Down Expand Up @@ -8459,6 +8490,10 @@ struct CMUXCLI {
set-app-focus <active|inactive|clear>
simulate-app-active

popup-terminal-toggle Toggle the popup terminal
popup-terminal-show Show the popup terminal
popup-terminal-hide Hide the popup terminal

# tmux compatibility commands
capture-pane [--workspace <id|ref>] [--surface <id|ref>] [--scrollback] [--lines <n>]
resize-pane --pane <id|ref> [--workspace <id|ref>] (-L|-R|-U|-D) [--amount <n>]
Expand Down
12 changes: 12 additions & 0 deletions GhosttyTabs.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@
A50012F1 /* Backport.swift in Sources */ = {isa = PBXBuildFile; fileRef = A50012F0 /* Backport.swift */; };
A50012F3 /* KeyboardShortcutSettings.swift in Sources */ = {isa = PBXBuildFile; fileRef = A50012F2 /* KeyboardShortcutSettings.swift */; };
A50012F5 /* KeyboardLayout.swift in Sources */ = {isa = PBXBuildFile; fileRef = A50012F4 /* KeyboardLayout.swift */; };
A5008391 /* PopupTerminalController.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5008390 /* PopupTerminalController.swift */; };
A5008393 /* PopupTerminalSettings.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5008392 /* PopupTerminalSettings.swift */; };
A5001521 /* PostHogAnalytics.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5001520 /* PostHogAnalytics.swift */; };
A5001201 /* UpdateController.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5001211 /* UpdateController.swift */; };
A5001202 /* UpdateDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5001212 /* UpdateDelegate.swift */; };
Expand Down Expand Up @@ -96,6 +98,7 @@
FA000000A1B2C3D4E5F60718 /* WorkspaceStressProfileTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA000001A1B2C3D4E5F60718 /* WorkspaceStressProfileTests.swift */; };
A5008381 /* BrowserFindJavaScriptTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5008380 /* BrowserFindJavaScriptTests.swift */; };
A5008383 /* CommandPaletteSearchEngineTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5008382 /* CommandPaletteSearchEngineTests.swift */; };
FB900000A1B2C3D4E5F60718 /* PopupTerminalSettingsTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = FB900001A1B2C3D4E5F60718 /* PopupTerminalSettingsTests.swift */; };
DA7A10CA710E000000000003 /* Localizable.xcstrings in Resources */ = {isa = PBXBuildFile; fileRef = DA7A10CA710E000000000001 /* Localizable.xcstrings */; };
DA7A10CA710E000000000004 /* InfoPlist.xcstrings in Resources */ = {isa = PBXBuildFile; fileRef = DA7A10CA710E000000000002 /* InfoPlist.xcstrings */; };
A5001623 /* cmux.sdef in Resources */ = {isa = PBXBuildFile; fileRef = A5001622 /* cmux.sdef */; };
Expand Down Expand Up @@ -194,6 +197,8 @@
A50012F0 /* Backport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Backport.swift; sourceTree = "<group>"; };
A50012F2 /* KeyboardShortcutSettings.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KeyboardShortcutSettings.swift; sourceTree = "<group>"; };
A50012F4 /* KeyboardLayout.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KeyboardLayout.swift; sourceTree = "<group>"; };
A5008390 /* PopupTerminalController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PopupTerminalController.swift; sourceTree = "<group>"; };
A5008392 /* PopupTerminalSettings.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PopupTerminalSettings.swift; sourceTree = "<group>"; };
A5001211 /* UpdateController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Update/UpdateController.swift; sourceTree = "<group>"; };
A5001212 /* UpdateDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Update/UpdateDelegate.swift; sourceTree = "<group>"; };
A5001213 /* UpdateDriver.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Update/UpdateDriver.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -242,6 +247,7 @@
FA000001A1B2C3D4E5F60718 /* WorkspaceStressProfileTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WorkspaceStressProfileTests.swift; sourceTree = "<group>"; };
A5008380 /* BrowserFindJavaScriptTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BrowserFindJavaScriptTests.swift; sourceTree = "<group>"; };
A5008382 /* CommandPaletteSearchEngineTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CommandPaletteSearchEngineTests.swift; sourceTree = "<group>"; };
FB900001A1B2C3D4E5F60718 /* PopupTerminalSettingsTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PopupTerminalSettingsTests.swift; sourceTree = "<group>"; };
DA7A10CA710E000000000001 /* Localizable.xcstrings */ = {isa = PBXFileReference; lastKnownFileType = text.json.xcstrings; path = Localizable.xcstrings; sourceTree = "<group>"; };
DA7A10CA710E000000000002 /* InfoPlist.xcstrings */ = {isa = PBXFileReference; lastKnownFileType = text.json.xcstrings; path = InfoPlist.xcstrings; sourceTree = "<group>"; };
A5001622 /* cmux.sdef */ = {isa = PBXFileReference; lastKnownFileType = text.sdef; path = cmux.sdef; sourceTree = "<group>"; };
Expand Down Expand Up @@ -362,6 +368,8 @@
A50012F0 /* Backport.swift */,
A50012F2 /* KeyboardShortcutSettings.swift */,
A50012F4 /* KeyboardLayout.swift */,
A5008390 /* PopupTerminalController.swift */,
A5008392 /* PopupTerminalSettings.swift */,
A5001013 /* TabManager.swift */,
A5001511 /* UITestRecorder.swift */,
A5001520 /* PostHogAnalytics.swift */,
Expand Down Expand Up @@ -477,6 +485,7 @@
FA000001A1B2C3D4E5F60718 /* WorkspaceStressProfileTests.swift */,
A5008380 /* BrowserFindJavaScriptTests.swift */,
A5008382 /* CommandPaletteSearchEngineTests.swift */,
FB900001A1B2C3D4E5F60718 /* PopupTerminalSettingsTests.swift */,
);
path = cmuxTests;
sourceTree = "<group>";
Expand Down Expand Up @@ -634,6 +643,8 @@
A50012F1 /* Backport.swift in Sources */,
A50012F3 /* KeyboardShortcutSettings.swift in Sources */,
A50012F5 /* KeyboardLayout.swift in Sources */,
A5008391 /* PopupTerminalController.swift in Sources */,
A5008393 /* PopupTerminalSettings.swift in Sources */,
A5001003 /* TabManager.swift in Sources */,
A5001501 /* UITestRecorder.swift in Sources */,
A5001521 /* PostHogAnalytics.swift in Sources */,
Expand Down Expand Up @@ -717,6 +728,7 @@
FA000000A1B2C3D4E5F60718 /* WorkspaceStressProfileTests.swift in Sources */,
A5008381 /* BrowserFindJavaScriptTests.swift in Sources */,
A5008383 /* CommandPaletteSearchEngineTests.swift in Sources */,
FB900000A1B2C3D4E5F60718 /* PopupTerminalSettingsTests.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
Expand Down
114 changes: 112 additions & 2 deletions Sources/AppDelegate.swift
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import AppKit
import SwiftUI
import Bonsplit
import Carbon
import CoreServices
import UserNotifications
import Sentry
Expand Down Expand Up @@ -1905,6 +1906,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent
private var lifecycleSnapshotObservers: [NSObjectProtocol] = []
private var windowKeyObserver: NSObjectProtocol?
private var shortcutMonitor: Any?
private var globalHotkeyRef: EventHotKeyRef?
private var shortcutDefaultsObserver: NSObjectProtocol?
private var menuBarVisibilityObserver: NSObjectProtocol?
private var splitButtonTooltipRefreshScheduled = false
Expand Down Expand Up @@ -2321,6 +2323,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent
}
notificationStore?.clearAll()
enableSuddenTerminationIfNeeded()
unregisterPopupTerminalHotKey()
}

func applicationWillResignActive(_ notification: Notification) {
Expand Down Expand Up @@ -7523,6 +7526,102 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent
}
return event
}
registerPopupTerminalHotKey()
}

// MARK: - Global hotkey (Carbon RegisterEventHotKey)

private static let popupTerminalHotKeyID = EventHotKeyID(
signature: OSType(0x636D7578), // "cmux"
id: 1
)

func registerPopupTerminalHotKey() {
unregisterPopupTerminalHotKey()

guard PopupTerminalSettings.isEnabled else { return }
let shortcut = KeyboardShortcutSettings.shortcut(for: .togglePopupTerminal)
let key = shortcut.key.lowercased()

guard let fkCode = Self.functionKeyCodeMap[key] else {
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
#if DEBUG
dlog("popupTerminal.hotkey skipped reason=nonFunctionKey key=\(shortcut.key)")
#endif
return

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Badge Validate popup shortcut keys before attempting registration

This path silently skips registration for any non-function key, but the popup shortcut is configured through the generic recorder, which still allows combinations like ⌘K; users can save such a shortcut and end up with a non-working global hotkey with no feedback. That creates an easy-to-hit broken configuration state until they manually reset to an F key, so this should be rejected or surfaced at save time.

Useful? React with 👍 / 👎.

}
let keyCode = UInt32(fkCode)

var mods: UInt32 = 0
if shortcut.command { mods |= UInt32(cmdKey) }
if shortcut.shift { mods |= UInt32(shiftKey) }
if shortcut.option { mods |= UInt32(optionKey) }
if shortcut.control { mods |= UInt32(controlKey) }

installCarbonHotKeyHandler()

var hotKeyID = Self.popupTerminalHotKeyID
var ref: EventHotKeyRef?
let status = RegisterEventHotKey(keyCode, mods, hotKeyID, GetApplicationEventTarget(), 0, &ref)
if status == noErr, let ref {
globalHotkeyRef = ref
} else {
#if DEBUG
dlog("popupTerminal.hotkey registerFailed key=\(shortcut.key) status=\(status)")
#endif
}
}

func unregisterPopupTerminalHotKey() {
if let ref = globalHotkeyRef {
UnregisterEventHotKey(ref)
globalHotkeyRef = nil
}
}

/// One-time installation of the Carbon event handler that dispatches hotkey events.
private static var carbonHandlerInstalled = false
private func installCarbonHotKeyHandler() {
guard !Self.carbonHandlerInstalled else { return }
Self.carbonHandlerInstalled = true

var eventType = EventTypeSpec(eventClass: OSType(kEventClassKeyboard), eventKind: UInt32(kEventHotKeyPressed))
InstallEventHandler(
GetApplicationEventTarget(),
{ _, event, _ -> OSStatus in
var hotKeyID = EventHotKeyID()
let status = GetEventParameter(
event,
EventParamName(kEventParamDirectObject),
EventParamType(typeEventHotKeyID),
nil,
MemoryLayout<EventHotKeyID>.size,
nil,
&hotKeyID
)
guard status == noErr else { return status }

// Check if this is our popup terminal hotkey.
// Carbon RegisterEventHotKey consumes the key event at the system
// level, so no window (local or popup) ever sees the registered
// hotkey as a keyDown. This handler is the sole toggle path for
// the popup terminal.
if hotKeyID.signature == AppDelegate.popupTerminalHotKeyID.signature,
hotKeyID.id == AppDelegate.popupTerminalHotKeyID.id {
// Carbon event handlers on GetApplicationEventTarget() run
// on the main thread, so we can call toggle directly.
if PopupTerminalSettings.isEnabled {
PopupTerminalController.shared.toggle()
}
return noErr
}

return OSStatus(eventNotHandledErr)
},
1,
&eventType,
nil,
nil
)
Comment on lines +7583 to +7624

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify current Carbon handler installation flow and status handling.
rg -n -C4 'carbonHandlerInstalled|InstallEventHandler\(|registerPopupTerminalHotKey\(' Sources/AppDelegate.swift

Repository: manaflow-ai/cmux

Length of output: 2052


🏁 Script executed:

#!/bin/bash
# Check the unregisterPopupTerminalHotKey implementation and globalHotkeyRef usage
rg -n -B2 -A10 'globalHotkeyRef|UnregisterEventHotKey' Sources/AppDelegate.swift | head -50

Repository: manaflow-ai/cmux

Length of output: 1881


🏁 Script executed:

#!/bin/bash
# Get the complete installCarbonHotKeyHandler function
rg -n -A 45 'private func installCarbonHotKeyHandler' Sources/AppDelegate.swift

Repository: manaflow-ai/cmux

Length of output: 2249


Check InstallEventHandler status before setting carbonHandlerInstalled.

carbonHandlerInstalled is set to true before verifying handler installation succeeds. If InstallEventHandler fails, retries are permanently blocked and the hotkey system is effectively dead. The handler reference is also not captured, making cleanup impossible if needed.

Suggested fix
 private func installCarbonHotKeyHandler() {
     guard !Self.carbonHandlerInstalled else { return }
-    Self.carbonHandlerInstalled = true

     var eventType = EventTypeSpec(eventClass: OSType(kEventClassKeyboard), eventKind: UInt32(kEventHotKeyPressed))
-    InstallEventHandler(
+    var handlerRef: EventHandlerRef?
+    let status = InstallEventHandler(
         GetApplicationEventTarget(),
         { _, event, _ -> OSStatus in
             var hotKeyID = EventHotKeyID()
             let status = GetEventParameter(
                 event,
                 EventParamName(kEventParamDirectObject),
                 EventParamType(typeEventHotKeyID),
                 nil,
                 MemoryLayout<EventHotKeyID>.size,
                 nil,
                 &hotKeyID
             )
             guard status == noErr else { return status }
 
             // Check if this is our popup terminal hotkey.
             // Carbon RegisterEventHotKey consumes the key event at the system
             // level, so no window (local or popup) ever sees the registered
             // hotkey as a keyDown. This handler is the sole toggle path for
             // the popup terminal.
             if hotKeyID.signature == AppDelegate.popupTerminalHotKeyID.signature,
                hotKeyID.id == AppDelegate.popupTerminalHotKeyID.id {
                 // Carbon event handlers on GetApplicationEventTarget() run
                 // on the main thread, so we can call toggle directly.
                 if PopupTerminalSettings.isEnabled {
                     PopupTerminalController.shared.toggle()
                 }
                 return noErr
             }
 
             return OSStatus(eventNotHandledErr)
         },
         1,
         &eventType,
         nil,
-        nil
+        &handlerRef
     )
+    guard status == noErr else { return }
+    Self.carbonHandlerInstalled = true
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@Sources/AppDelegate.swift` around lines 7579 - 7620, The
installCarbonHotKeyHandler currently sets Self.carbonHandlerInstalled = true
before calling InstallEventHandler and does not capture the returned handler, so
failures permanently block retries and prevent cleanup; change the flow in
installCarbonHotKeyHandler to call InstallEventHandler first, check its OSStatus
result, and only set Self.carbonHandlerInstalled = true when status == noErr;
also capture the created EventHandlerRef (or store it in a new static var like
Self.carbonEventHandlerRef) so you can remove the handler later (using
RemoveEventHandler) on teardown or on failure, and if InstallEventHandler fails,
log the error and leave carbonHandlerInstalled false to allow retries.

}

private func installShortcutDefaultsObserver() {
Expand Down Expand Up @@ -8105,7 +8204,6 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent
return false
}

// Primary UI shortcuts
if matchShortcut(event: event, shortcut: KeyboardShortcutSettings.shortcut(for: .toggleSidebar)) {
_ = toggleSidebarInActiveMainWindow()
return true
Expand Down Expand Up @@ -9274,7 +9372,11 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent
return false
}

/// Match a shortcut against an event, handling normal keys.
private static let functionKeyCodeMap: [String: UInt16] = [
"f1": 122, "f2": 120, "f3": 99, "f4": 118, "f5": 96, "f6": 97,
"f7": 98, "f8": 100, "f9": 101, "f10": 109, "f11": 103, "f12": 111,
]

private func matchShortcut(event: NSEvent, shortcut: StoredShortcut) -> Bool {
// Some keys can include extra flags (e.g. .function) depending on the responder chain.
// Strip those for consistent matching across first responders (terminal, WebKit, etc).
Expand All @@ -9283,6 +9385,13 @@ final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCent
guard flags == shortcut.modifierFlags else { return false }

let shortcutKey = shortcut.key.lowercased()

// Function keys: match by keyCode since charactersIgnoringModifiers
// returns special Unicode characters that don't match "F11" etc.
if let expectedKeyCode = Self.functionKeyCodeMap[shortcutKey] {
return event.keyCode == expectedKeyCode
}

if shortcutKey == "\r" {
return event.keyCode == 36 || event.keyCode == 76
}
Expand Down Expand Up @@ -11063,6 +11172,7 @@ private extension NSWindow {
Self.cmuxOwningWebView(for: $0, in: self, event: event)
}
if let ghosttyView = firstResponderGhosttyView {

// If the IME is composing and the key has no Cmd modifier, don't intercept —
// let it flow through normal AppKit event dispatch so the input method can
// process it. Cmd-based shortcuts should still work during composition since
Expand Down
24 changes: 23 additions & 1 deletion Sources/KeyboardShortcutSettings.swift
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,9 @@ enum KeyboardShortcutSettings {
case toggleBrowserDeveloperTools
case showBrowserJavaScriptConsole

// Popup terminal
case togglePopupTerminal

var id: String { rawValue }

var label: String {
Expand Down Expand Up @@ -76,6 +79,7 @@ enum KeyboardShortcutSettings {
case .openBrowser: return String(localized: "shortcut.openBrowser.label", defaultValue: "Open Browser")
case .toggleBrowserDeveloperTools: return String(localized: "shortcut.toggleBrowserDevTools.label", defaultValue: "Toggle Browser Developer Tools")
case .showBrowserJavaScriptConsole: return String(localized: "shortcut.showBrowserJSConsole.label", defaultValue: "Show Browser JavaScript Console")
case .togglePopupTerminal: return String(localized: "shortcut.togglePopupTerminal.label", defaultValue: "Toggle Popup Terminal")
}
}

Expand Down Expand Up @@ -111,6 +115,7 @@ enum KeyboardShortcutSettings {
case .openBrowser: return "shortcut.openBrowser"
case .toggleBrowserDeveloperTools: return "shortcut.toggleBrowserDeveloperTools"
case .showBrowserJavaScriptConsole: return "shortcut.showBrowserJavaScriptConsole"
case .togglePopupTerminal: return "shortcut.togglePopupTerminal"
}
}

Expand Down Expand Up @@ -178,6 +183,8 @@ enum KeyboardShortcutSettings {
case .showBrowserJavaScriptConsole:
// Safari default: Show JavaScript Console.
return StoredShortcut(key: "c", command: true, shift: false, option: true, control: false)
case .togglePopupTerminal:
return StoredShortcut(key: "F10", command: false, shift: false, option: false, control: false)
}
}

Expand Down Expand Up @@ -368,7 +375,9 @@ struct StoredShortcut: Codable, Equatable {
)

// Avoid recording plain typing; require at least one modifier.
if !shortcut.command && !shortcut.shift && !shortcut.option && !shortcut.control {
// Exception: function keys (F1-F12) are allowed without modifiers.
let isFunctionKey = key.lowercased().hasPrefix("f") && key.count <= 3 && Int(key.dropFirst()) != nil
if !isFunctionKey && !shortcut.command && !shortcut.shift && !shortcut.option && !shortcut.control {
return nil
}
return shortcut
Expand All @@ -394,6 +403,19 @@ struct StoredShortcut: Codable, Equatable {
case 39: return "'" // kVK_ANSI_Quote
case 50: return "`" // kVK_ANSI_Grave
case 42: return "\\" // kVK_ANSI_Backslash
// Function keys
case 122: return "F1"
case 120: return "F2"
case 99: return "F3"
case 118: return "F4"
case 96: return "F5"
case 97: return "F6"
case 98: return "F7"
case 100: return "F8"
case 101: return "F9"
case 109: return "F10"
case 103: return "F11"
case 111: return "F12"
default:
break
}
Expand Down
Loading