Workaround for OS Window focus on notification in macOS when there are multiple kitty instances

Fixes #10805
This commit is contained in:
Kovid Goyal 2026-11-04 20:12:23 +05:30
parent 91fb38aee6
commit 5cd1d37017
No known key found for this signature in database
GPG key ID: 06BC317B515ACE7C
5 changed files with 79 additions and 6 deletions

View file

@ -225,6 +225,10 @@ Detailed list of changes
- :doc:`choose-files <kittens/choose-files>`: Fix concurrent custom preview
commands occasionally receiving the path of a different file.
- macOS: Add a workaround for clicking notifications not focusing the correct
OS Window when there are multiple kitty instances because of Cocoa
limitations (:iss:`10805`)
0.50.0 [2026-11-03]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

View file

@ -71,3 +71,4 @@ void set_cocoa_pending_action(CocoaPendingAction action, const char *);
void cocoa_report_live_notifications(const char *ident);
void cocoa_set_dock_badge(const char *label);
void cocoa_clear_dock_badge_if_set(void);
bool cocoa_yield_reopen_to_other_instance(void);

View file

@ -21,6 +21,7 @@
#include <AvailabilityMacros.h>
// Needed for _NSGetProgname
#include <crt_externs.h>
#include <libproc.h>
#include <objc/runtime.h>
static inline void
@ -402,6 +403,8 @@ get_dock_menu(id self UNUSED, SEL _cmd UNUSED, NSApplication *sender UNUSED) {
}
static PyObject *notification_activated_callback = NULL;
static monotonic_t last_notification_response_at = 0;
static struct { pid_t pid; monotonic_t at; } last_other_instance_activation = {0};
static PyObject *
set_notification_activated_callback(PyObject *self UNUSED, PyObject *callback) {
@ -440,6 +443,7 @@ do_notification_callback(const char *identifier, const char *event, const char *
didReceiveNotificationResponse:(UNNotificationResponse *)response
withCompletionHandler:(void (^)(void))completionHandler {
(void)(center);
last_notification_response_at = monotonic();
char *identifier = strdup(response.notification.request.identifier.UTF8String);
char *action_identifier = strdup(response.actionIdentifier.UTF8String);
const char *event = "button";
@ -1800,5 +1804,55 @@ init_cocoa(PyObject *module) {
object:nil
queue:[NSOperationQueue mainQueue]
usingBlock:^(NSNotification *note UNUSED) { cocoa_set_dock_badge(NULL); }];
[[[NSWorkspace sharedWorkspace] notificationCenter] addObserverForName:NSWorkspaceDidActivateApplicationNotification
object:nil
queue:[NSOperationQueue mainQueue]
usingBlock:^(NSNotification *note) {
NSRunningApplication *app = note.userInfo[NSWorkspaceApplicationKey];
// LaunchServices activates us before sending the reopen event, so ignore our own activation
if (!app || app.processIdentifier == getpid()) return;
NSString *our_id = [[NSBundle mainBundle] bundleIdentifier];
if (our_id && [app.bundleIdentifier isEqualToString:our_id]) {
last_other_instance_activation.pid = app.processIdentifier;
last_other_instance_activation.at = monotonic();
} else {
last_other_instance_activation.pid = 0;
}
}];
return true;
}
bool
cocoa_yield_reopen_to_other_instance(void) {
// When a notification is clicked, macOS delivers the response to the kitty
// instance that posted it, which brings itself forward. Then usernoted asks
// LaunchServices to bring the application forward by bundle URL, which
// picks an arbitrary running instance and sends it a reopen event, stealing
// focus. Detect that and hand activation back to the posting instance.
NSAppleEventDescriptor *event = [[NSAppleEventManager sharedAppleEventManager] currentAppleEvent];
if (!event) return false;
NSData *token = [[event attributeDescriptorForKeyword:keySenderAuditTokenAttr] data];
if (!token || token.length != sizeof(audit_token_t)) return false;
audit_token_t t; memcpy(&t, token.bytes, sizeof(t));
char name[256] = {0};
// val[5] is the pid, see audit_token_to_pid() in libbsm
if (proc_name((pid_t)t.val[5], name, sizeof(name)) <= 0 || strcmp(name, "usernoted") != 0) return false;
const monotonic_t now = monotonic(), threshold = s_double_to_monotonic_t(2.0);
// We received the notification response so this reopen is for us
if (last_notification_response_at && now - last_notification_response_at < threshold) return false;
if (!last_other_instance_activation.pid || now - last_other_instance_activation.at > threshold) return false;
NSRunningApplication *app = [NSRunningApplication runningApplicationWithProcessIdentifier:last_other_instance_activation.pid];
if (!app || app.terminated) return false;
debug_rendering("Yielding activation to kitty instance: %d that owns the clicked notification\n", app.processIdentifier);
// yieldActivationToApplication was introduced in macOS 14 (Sonoma)
SEL selector = NSSelectorFromString(@"yieldActivationToApplication:");
if ([NSApp respondsToSelector:selector]) {
[NSApp performSelector:selector withObject:app];
[app activateWithOptions:0];
} else {
#define NSApplicationActivateIgnoringOtherApps 2
[app activateWithOptions:NSApplicationActivateIgnoringOtherApps];
#undef NSApplicationActivateIgnoringOtherApps
}
return true;
}

View file

@ -1926,6 +1926,7 @@ filter_option(int key UNUSED, int mods, unsigned int native_key UNUSED, unsigned
static bool
on_application_reopen(int has_visible_windows) {
if (cocoa_yield_reopen_to_other_instance()) return false;
if (has_visible_windows) return true;
set_cocoa_pending_action(NEW_OS_WINDOW, NULL);
return false;

View file

@ -537,6 +537,9 @@ class MacOSIntegration(DesktopIntegration):
from .fast_data_types import cocoa_set_notification_activated_callback
self.id_counter = count(start=1)
# All kitty instances share a single notification center, so
# namespace our notification identifiers with our pid
self.ident_prefix = f'{os.getpid()}-'
self.live_notification_queries: list[tuple[int, str]] = []
self.failed_icons: OrderedDict[str, bool] = OrderedDict()
self.icd_key_prefix = os.urandom(16).hex()
@ -547,6 +550,17 @@ class MacOSIntegration(DesktopIntegration):
self.current_categories: frozenset[MacOSNotificationCategory] = frozenset()
cocoa_set_notification_activated_callback(self.notification_activated)
def to_ident(self, desktop_notification_id: int) -> str:
return f'{self.ident_prefix}{desktop_notification_id}'
def from_ident(self, ident: str) -> int | None:
if ident.startswith(self.ident_prefix):
try:
return int(ident[len(self.ident_prefix):])
except Exception:
pass
return None
def query_live_notifications(self, channel_id: int, identifier: str) -> None:
from .fast_data_types import cocoa_live_delivered_notifications
@ -558,7 +572,7 @@ class MacOSIntegration(DesktopIntegration):
def close_notification(self, desktop_notification_id: int) -> bool:
from .fast_data_types import cocoa_remove_delivered_notification
close_succeeded = cocoa_remove_delivered_notification(str(desktop_notification_id))
close_succeeded = cocoa_remove_delivered_notification(self.to_ident(desktop_notification_id))
if debug_desktop_integration:
log_error(f'Close request for {desktop_notification_id=} {"succeeded" if close_succeeded else "failed"}')
return close_succeeded
@ -632,7 +646,7 @@ class MacOSIntegration(DesktopIntegration):
cocoa_send_notification(
nc.application_name or 'kitty',
str(desktop_notification_id),
self.to_ident(desktop_notification_id),
nc.title,
body,
category=category,
@ -645,7 +659,7 @@ class MacOSIntegration(DesktopIntegration):
def notification_activated(self, event: str, ident: str, button_id: str) -> None:
if event == 'live':
live_ids = tuple(int(x) for x in ident.split(',') if x)
live_ids = tuple(x for x in map(self.from_ident, ident.split(',')) if x is not None)
if debug_desktop_integration:
log_error(f'Live notifications: {live_ids}')
self.notification_manager.purge_dead_notifications(live_ids)
@ -655,9 +669,8 @@ class MacOSIntegration(DesktopIntegration):
return
if debug_desktop_integration:
log_error(f'Notification {ident=} {event=} {button_id=}')
try:
desktop_notification_id = int(ident)
except Exception:
desktop_notification_id = self.from_ident(ident)
if desktop_notification_id is None:
log_error(f'Got unexpected notification activated event with id: {ident!r} from cocoa')
return
if event == 'created':