Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ import Foundation
/// in `src/window_manager.c`):
///
/// 1. `_SLPSGetFrontProcess(&prevPSN)` — capture current front.
/// 2. `GetProcessForPID(targetPid, &targetPSN)`.
/// 2. `SLSGetWindowOwner + SLSGetConnectionPSN` → target PSN from window ID
/// (replaces the deprecated `GetProcessForPID` on macOS 15+).
/// 3. `SLPSPostEventRecordTo(prevPSN, 248-byte-buf)` with `bytes[0x8a] = 0x02`
/// (defocus marker) → tells WindowServer the previous front's window
/// has lost focus without asking for a raise of anything else.
Expand Down Expand Up @@ -63,7 +64,7 @@ public enum FocusWithoutRaise {
guard prevOk else { return false }

let targetOk = targetPSN.withUnsafeMutableBytes { raw in
SkyLightEventPost.getProcessPSN(forPid: targetPid, into: raw.baseAddress!)
SkyLightEventPost.getProcessPSN(forWindowId: targetWid, into: raw.baseAddress!)
}
guard targetOk else { return false }

Expand Down Expand Up @@ -96,4 +97,49 @@ public enum FocusWithoutRaise {

return defocusOk && focusOk
}

/// Full-activate variant for the keyboard → NSMenu shortcut path.
///
/// Unlike `activateWithoutRaise` (which only changes AppKit-active state via
/// the PSN defocus/focus recipe), this calls `SLPSSetFrontProcessWithOptions`
/// with `kCPSNoWindows (0x400)` directly, which makes the target both
/// **AppKit-active** AND **WindowServer-level frontmost** in a single step —
/// without raising windows or triggering Space follow.
///
/// Why the full-frontmost step is required for NSMenu key equivalents:
/// - HID-tap events (`CGEvent.post(tap: .cghidEventTap)`) route to the
/// **WindowServer-level frontmost** process, not the AppKit-active one.
/// `activateWithoutRaise` only changes AppKit-active, so HID-tap events
/// still go to the sentinel foreground app (e.g., the terminal), not the
/// backgrounded target.
/// - After `SLPSSetFrontProcessWithOptions(kCPSNoWindows)`, the target IS the
/// WindowServer frontmost, so the HID-tap reaches its event queue where
/// `NSApplication.sendEvent:` dispatches NSMenu key equivalents.
///
/// **Trade-off**: causes exactly 1 focus loss on the sentinel foreground app
/// (same as the click path). Using `kCPSNoWindows` rather than the default
/// `kCPSUserGenerated = 0x100` avoids window raise and Space follow.
///
/// This is NOT used for the click/mouse path because Chrome's user-activation
/// gate rejects synthetic clicks after `SLPSSetFrontProcessWithOptions` — the
/// PSN-only recipe in `activateWithoutRaise` is sufficient for clicks.
@discardableResult
public static func activateForMenuShortcut(
targetPid: pid_t, targetWid: CGWindowID
) -> Bool {
// Resolve target PSN from window ID (modern path via SLSGetWindowOwner +
// SLSGetConnectionPSN; fallback GetProcessForPID on older macOS).
var targetPSN = [UInt32](repeating: 0, count: 2)
let targetOk = targetPSN.withUnsafeMutableBytes { raw in
SkyLightEventPost.getProcessPSN(forWindowId: targetWid, into: raw.baseAddress!)
}
guard targetOk else { return false }

// One call makes the target both AppKit-active and WindowServer-frontmost
// without raising windows. HID-tap events will now route to this process.
return targetPSN.withUnsafeBytes { psnRaw in
SkyLightEventPost.setFrontProcessNoWindows(
psn: psnRaw.baseAddress!, windowID: UInt32(targetWid))
}
}
}
45 changes: 30 additions & 15 deletions libs/cua-driver/Sources/CuaDriverCore/Input/KeyboardInput.swift
Original file line number Diff line number Diff line change
Expand Up @@ -34,14 +34,15 @@ public enum KeyboardInput {
public static func press(
_ key: String,
modifiers: [String] = [],
toPid pid: pid_t? = nil
toPid pid: pid_t? = nil,
attachAuthMessage: Bool = true
) throws {
guard let code = virtualKeyCode(for: key) else {
throw KeyboardError.unknownKey(key)
}
let flags = modifierMask(for: modifiers)
try sendKey(code: code, down: true, flags: flags, toPid: pid)
try sendKey(code: code, down: false, flags: flags, toPid: pid)
try sendKey(code: code, down: true, flags: flags, toPid: pid, attachAuthMessage: attachAuthMessage)
try sendKey(code: code, down: false, flags: flags, toPid: pid, attachAuthMessage: attachAuthMessage)
}

/// Press a combination of keys simultaneously.
Expand All @@ -50,7 +51,15 @@ public enum KeyboardInput {
/// If multiple non-modifier keys are supplied, only the last is pressed.
/// Pass `toPid` to route to a specific process's event queue via
/// `CGEvent.postToPid`, bypassing frontmost-app routing.
public static func hotkey(_ keys: [String], toPid pid: pid_t? = nil) throws {
///
/// `attachAuthMessage`: when `true` (default) attaches the SkyLight auth
/// envelope Chromium needs; when `false` routes via `IOHIDPostEvent` so
/// NSMenu key equivalents in native AppKit apps fire correctly.
public static func hotkey(
_ keys: [String],
toPid pid: pid_t? = nil,
attachAuthMessage: Bool = true
) throws {
var modifiers: [String] = []
var finalKey: String?
for raw in keys {
Expand All @@ -63,7 +72,7 @@ public enum KeyboardInput {
guard let final = finalKey else {
throw KeyboardError.noKeyInCombo
}
try press(final, modifiers: modifiers, toPid: pid)
try press(final, modifiers: modifiers, toPid: pid, attachAuthMessage: attachAuthMessage)
}

/// Type each character in ``text`` as a synthetic key-down + key-up
Expand Down Expand Up @@ -103,7 +112,8 @@ public enum KeyboardInput {
code: Int,
down: Bool,
flags: CGEventFlags,
toPid pid: pid_t? = nil
toPid pid: pid_t? = nil,
attachAuthMessage: Bool = true
) throws {
guard
let event = CGEvent(
Expand All @@ -116,15 +126,20 @@ public enum KeyboardInput {
}
event.flags = flags
if let pid {
// Prefer SkyLight's SLEventPostToPid — it routes through
// CGSTickleActivityMonitor which Chromium omniboxes need to
// promote the synthetic event into their keyboard pipeline.
// Prefer SkyLight's SLEventPostToPid — it routes through
// CGSTickleActivityMonitor which some apps need to promote
// the synthetic event. Falls back to the public
// CGEventPostToPid when the SPI is unavailable (older macOS
// / stripped framework).
if !SkyLightEventPost.postToPid(pid, event: event) {
// Two delivery paths:
//
// attachAuthMessage=true (Chromium path, default):
// SLEventSetAuthenticationMessage + SLEventPostToPid →
// direct-mach delivery; Chromium omniboxes accept synthetic
// keyboard events as trusted input. Bypasses IOHIDPostEvent
// and therefore NSMenu's key-equivalent dispatch.
//
// attachAuthMessage=false (native-AppKit/NSMenu path):
// SLEventPostToPid without envelope → SLEventPostToPSN →
// IOHIDPostEvent → Finder/TextEdit/etc. event queue where
// NSApplication.sendEvent: dispatches NSMenu key equivalents.
// Falls back to CGEvent.postToPid when SkyLight isn't available.
if !SkyLightEventPost.postToPid(pid, event: event, attachAuthMessage: attachAuthMessage) {
event.postToPid(pid)
}
} else {
Expand Down
121 changes: 112 additions & 9 deletions libs/cua-driver/Sources/CuaDriverCore/Input/SkyLightEventPost.swift
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,48 @@ public enum SkyLightEventPost {
// state without asking WindowServer to reorder its windows. Recipe
// ported from yabai's `window_manager_focus_window_without_raise`.

/// `OSStatus SLPSSetFrontProcessWithOptions(ProcessSerialNumber *psn, uint32_t windowID, uint32_t options)`.
///
/// Makes `psn` the WindowServer-level frontmost process. The options flag controls behaviour:
/// - `0x100` (kCPSUserGenerated) → raises windows + triggers Space follow
/// - `0x400` (kCPSNoWindows) → no window raise, no Space follow; Chrome's
/// user-activation gate rejects events after this, but native AppKit apps
/// (Finder, TextEdit, etc.) are unaffected.
///
/// `FocusWithoutRaise` deliberately skips this call for the click/mouse path
/// because Chrome needs the PSN-only recipe. For the keyboard-menu-shortcut
/// path (hotkey/press_key with window_id) we call it with `kCPSNoWindows`
/// (0x400) so that HID-tap events route to the now-frontmost target instead
/// of the sentinel foreground app.
private typealias SetFrontProcessWithOptionsFn = @convention(c) (
UnsafeRawPointer, UInt32, UInt32
) -> Int32

private static let setFrontProcessWithOptionsFn: SetFrontProcessWithOptionsFn? = {
_ = dlopen(
"/System/Library/PrivateFrameworks/SkyLight.framework/SkyLight",
RTLD_LAZY)
guard
let p = dlsym(
UnsafeMutableRawPointer(bitPattern: -2),
"SLPSSetFrontProcessWithOptions")
else { return nil }
return unsafeBitCast(p, to: SetFrontProcessWithOptionsFn.self)
}()

/// Make `psn` the WindowServer-level frontmost process without raising
/// windows or triggering Space follow (`kCPSNoWindows = 0x400`).
/// `windowID` is the CGWindowID of the target window (yabai passes the
/// real window ID; passing 0 leaves it unset). Returns `false` when the
/// SPI didn't resolve.
@discardableResult
public static func setFrontProcessNoWindows(
psn: UnsafeRawPointer, windowID: UInt32 = 0
) -> Bool {
guard let fn = setFrontProcessWithOptionsFn else { return false }
return fn(psn, windowID, 0x400) == 0
}

/// `OSStatus SLPSPostEventRecordTo(ProcessSerialNumber *psn, uint8_t *bytes)`.
/// Posts a 248-byte synthetic event record into the target process's
/// Carbon event queue. We build the buffer with
Expand All @@ -183,9 +225,22 @@ public enum SkyLightEventPost {
UnsafeMutableRawPointer
) -> Int32

/// `OSStatus GetProcessForPID(pid_t, ProcessSerialNumber *)`.
/// Deprecated but still resolves via dlsym. Writes the target pid's
/// PSN into the 8 bytes at `psn`.
/// `CGError SLSGetWindowOwner(CGSConnectionID cid, CGWindowID wid, CGSConnectionID *ownerCid)`.
/// Returns the SkyLight connection ID of the process that owns `wid`.
/// Modern replacement for the deprecated `GetProcessForPID` on macOS 15+.
private typealias GetWindowOwnerFn = @convention(c) (
UInt32, UInt32, UnsafeMutablePointer<UInt32>
) -> Int32

/// `OSStatus SLSGetConnectionPSN(CGSConnectionID cid, ProcessSerialNumber *psn)`.
/// Converts a SkyLight connection ID to a PSN (two UInt32s).
private typealias GetConnectionPSNFn = @convention(c) (
UInt32, UnsafeMutableRawPointer
) -> Int32

/// Deprecated `OSStatus GetProcessForPID(pid_t, ProcessSerialNumber *)`.
/// Only used as a fallback on older macOS; nil on macOS 15+ where the
/// symbol no longer exports. Prefer `getProcessPSN(forWindowId:)` instead.
private typealias GetProcessForPIDFn = @convention(c) (
pid_t, UnsafeMutableRawPointer
) -> Int32
Expand Down Expand Up @@ -214,6 +269,30 @@ public enum SkyLightEventPost {
return unsafeBitCast(p, to: GetFrontProcessFn.self)
}()

private static let getWindowOwnerFn: GetWindowOwnerFn? = {
_ = dlopen(
"/System/Library/PrivateFrameworks/SkyLight.framework/SkyLight",
RTLD_LAZY)
guard
let p = dlsym(
UnsafeMutableRawPointer(bitPattern: -2),
"SLSGetWindowOwner")
else { return nil }
return unsafeBitCast(p, to: GetWindowOwnerFn.self)
}()

private static let getConnectionPSNFn: GetConnectionPSNFn? = {
_ = dlopen(
"/System/Library/PrivateFrameworks/SkyLight.framework/SkyLight",
RTLD_LAZY)
guard
let p = dlsym(
UnsafeMutableRawPointer(bitPattern: -2),
"SLSGetConnectionPSN")
else { return nil }
return unsafeBitCast(p, to: GetConnectionPSNFn.self)
}()

private static let getProcessForPIDFn: GetProcessForPIDFn? = {
guard
let p = dlsym(
Expand Down Expand Up @@ -352,13 +431,37 @@ public enum SkyLightEventPost {
return fn(psn, bytes) == 0
}

/// `true` when all three focus-without-raise SPIs
/// (`_SLPSGetFrontProcess`, `GetProcessForPID`, `SLPSPostEventRecordTo`)
/// resolved — i.e. `FocusWithoutRaise.activateWithoutRaise` has its
/// prerequisites.
/// `true` when the focus-without-raise SPIs needed to run the PSN
/// defocus/focus recipe are available. The PSN-for-pid lookup uses
/// `SLSGetWindowOwner + SLSGetConnectionPSN` on macOS 15+ (where the
/// old `GetProcessForPID` no longer exports), falling back to
/// `GetProcessForPID` on older releases.
public static var isFocusWithoutRaiseAvailable: Bool {
getFrontProcessFn != nil && getProcessForPIDFn != nil
&& postEventRecordToFn != nil
let hasPsnLookup = (getWindowOwnerFn != nil && getConnectionPSNFn != nil)
|| getProcessForPIDFn != nil
return getFrontProcessFn != nil && hasPsnLookup && postEventRecordToFn != nil
}

/// Look up the PSN of the process that owns `windowId`, writing 8 bytes
/// into `psnBuffer`. Uses `SLSGetWindowOwner + SLSGetConnectionPSN` on
/// macOS 15+ where `GetProcessForPID` no longer exports.
public static func getProcessPSN(
forWindowId windowId: CGWindowID, into psnBuffer: UnsafeMutableRawPointer
) -> Bool {
// Modern path: window ID → owner connection ID → PSN.
if let owner = getWindowOwnerFn, let psnFn = getConnectionPSNFn,
let connFn = connectionIDFn
{
let mainCid = connFn()
var ownerCid: UInt32 = 0
guard owner(mainCid, UInt32(windowId), &ownerCid) == 0 else { return false }
return psnFn(ownerCid, psnBuffer) == 0
}
// Fallback: deprecated GetProcessForPID (macOS < 15).
// Caller must supply a pid in this path — psnBuffer is reused as
// a typed pointer, but this branch is only reached when the modern
// path isn't available.
return false
}

// MARK: - Event-record extraction
Expand Down
56 changes: 55 additions & 1 deletion libs/cua-driver/Sources/CuaDriverServer/Tools/HotkeyTool.swift
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import CoreGraphics
import CuaDriverCore
import Foundation
import MCP
Expand All @@ -13,6 +14,17 @@ public enum HotkeyTool {
the target pid's event queue via `CGEvent.postToPid`;
the target does NOT need to be frontmost.

**`window_id`** (optional): when supplied, the driver
calls `FocusWithoutRaise.activateWithoutRaise` before
posting — making the target AppKit-active without
raising its window. This is required for shortcuts that
are dispatched via NSMenu key equivalents (Cmd+S,
Cmd+N, Cmd+W, Cmd+Shift+N, …) because AppKit only
routes menu key equivalents to the active app. Omit
`window_id` for shortcuts handled by the renderer
(e.g. Cmd+C in a Chromium text field). Trade-off: the
sentinel foreground app will lose focus once.

Recognized modifiers: cmd/command, shift, option/alt,
ctrl/control, fn. Non-modifier keys use the same
vocabulary as `press_key` (return, tab, escape,
Expand All @@ -35,6 +47,11 @@ public enum HotkeyTool {
"description":
"Modifier(s) and one non-modifier key, e.g. [\"cmd\", \"c\"].",
],
"window_id": [
"type": "integer",
"description":
"CGWindowID of the target window. When provided, the driver calls FocusWithoutRaise before posting so NSMenu key equivalents (Cmd+S, Cmd+N, …) reach the backgrounded app.",
],
],
"additionalProperties": false,
],
Expand All @@ -60,8 +77,45 @@ public enum HotkeyTool {
return errorResult(
"pid \(rawPid) is outside the supported Int32 range.")
}
let rawWindowId = arguments?["window_id"]?.intValue
do {
try KeyboardInput.hotkey(keys, toPid: pid)
// Two delivery paths, selected by whether window_id is set:
//
// window_id present → NSMenu/native-AppKit path:
// 1. FocusWithoutRaise makes the target AppKit-active
// without raising its window.
// 2. Post via SLEventPostToPid WITHOUT the auth-message
// envelope (attachAuthMessage: false). Without the
// envelope the event routes SLEventPostToPid →
// SLEventPostToPSN → IOHIDPostEvent → target event queue
// where NSApplication.sendEvent: dispatches NSMenu key
// equivalents. With the envelope SLEventPostToPid forks
// onto a direct-mach path that bypasses IOHIDPostEvent
// and therefore NSMenu — which is why Cmd+Shift+N was
// silently swallowed.
//
// window_id absent → Chromium/renderer path (default):
// Post via SLEventPostToPid WITH the auth-message envelope.
// Chromium's keyboard pipeline requires it to accept
// synthetic keystrokes; NSMenu is irrelevant here since
// Chromium handles shortcuts inside its renderer.
if let rawWid = rawWindowId, rawWid != 0,
let wid = UInt32(exactly: rawWid)
{
FocusWithoutRaise.activateForMenuShortcut(
targetPid: pid, targetWid: CGWindowID(wid))
usleep(50_000)
// Post WITHOUT the SkyLight auth-message envelope.
// With the envelope, SLEventPostToPid forks onto a direct-mach
// path that bypasses IOHIDPostEvent — NSMenu never sees those
// events. Without the envelope the path goes through IOHIDPostEvent
// so NSApplication.sendEvent: dispatches NSMenu key equivalents.
// SLPSSetFrontProcessWithOptions (called inside activateForMenuShortcut)
// already made the target WindowServer-frontmost.
try KeyboardInput.hotkey(keys, toPid: pid, attachAuthMessage: false)
} else {
try KeyboardInput.hotkey(keys, toPid: pid)
Comment on lines +102 to +117

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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Fail fast when window_id is invalid or activation fails.

This branch silently degrades if window_id is out of UInt32 range or activateForMenuShortcut(...) returns false, but it still reports success. For the NSMenu path that turns a real targeting failure into a silent no-op.

Suggested fix
-                if let rawWid = rawWindowId, rawWid != 0,
-                   let wid = UInt32(exactly: rawWid)
-                {
-                    FocusWithoutRaise.activateForMenuShortcut(
-                        targetPid: pid, targetWid: CGWindowID(wid))
+                if let rawWid = rawWindowId {
+                    guard rawWid != 0, let wid = UInt32(exactly: rawWid) else {
+                        return errorResult(
+                            "window_id \(rawWid) is outside the supported UInt32 range.")
+                    }
+                    guard FocusWithoutRaise.activateForMenuShortcut(
+                        targetPid: pid, targetWid: CGWindowID(wid))
+                    else {
+                        return errorResult(
+                            "Failed to activate window_id \(rawWid) for NSMenu shortcut delivery.")
+                    }
                     usleep(50_000)
                     // Post WITHOUT the SkyLight auth-message envelope.
                     // With the envelope, SLEventPostToPid forks onto a direct-mach
@@
-                } else {
+                } else {
                     try KeyboardInput.hotkey(keys, toPid: pid)
                 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@libs/cua-driver/Sources/CuaDriverServer/Tools/HotkeyTool.swift` around lines
102 - 117, The branch silently proceeds when rawWindowId is nil/out of UInt32
range or when FocusWithoutRaise.activateForMenuShortcut(targetPid:targetWid:)
fails; change the logic in the block that checks rawWindowId and calls
FocusWithoutRaise.activateForMenuShortcut so it fails fast: if rawWindowId is
nil or UInt32(exactly: rawWindowId) is nil, throw or return an error immediately
instead of falling back to the non-windowed hotkey path, and after calling
FocusWithoutRaise.activateForMenuShortcut, check its boolean result and
throw/return on false before calling KeyboardInput.hotkey(keys, toPid: pid,
attachAuthMessage: false) so callers see the real failure rather than a silent
no-op.

}
return CallTool.Result(
content: [
.text(
Expand Down
Loading
Loading