Crash When Clicking on Definition View Created by AppKit's showDefinition(for:at)

I'm encountering a crash issue in my macOS application when clicking on the view generated by AppKit's showDefinition(for:at) function. I'm seeking assistance to resolve this issue.

**Problem Description: **

I'm developing a macOS application where I utilize the showDefinition(for:at) function provided by AppKit to display the definition view of words. However, whenever I click on this view, the application crashes abruptly.

**Error Message: **

The crash log reveals the following error message:

Fault: deferNSXPCInvocationOntoMainThread_block_invoke caught NSInternalInconsistencyException '_CPSSetFrontProcessWithOptions failed due to CGError -606 4294966690 fffffda2 (appIsDaemon)'

Attempts Made:

Tried wrapping relevant code blocks with DispatchQueue.main.async, suspecting a threading issue.

Making the DefinitionWindow variable a global one to manually control its lifecycle

Development Environment:

macOS Version: 14.3.1 Xcode Version: 15

Below is a complete and reproducible code snippet that can be directly executed within a terminal project template. Please note that it requires Accessibility permissions to be granted in the Privacy settings.

import Cocoa
import SwiftUI
import AppKit

class AppDelegate: NSObject, NSApplicationDelegate {
    func applicationDidFinishLaunching(_ notification: Notification) {
        NSEvent.addGlobalMonitorForEvents(matching: .keyDown) { [weak self] event in
            guard let self = self else { return }
            if event.modifierFlags.contains(.command) && event.charactersIgnoringModifiers == "c" {
                self.ShowWordDefinition()
            }
        }
        NSApp.servicesProvider = self
        NSApp.registerServicesMenuSendTypes([.string], returnTypes: [])
    }
    func ShowWordDefinition(){
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
            let attributedString = NSAttributedString(string:NSPasteboard.general.string(forType: .string)!)
            let DefinitionWindow = NSWindow(contentRect: NSRect(origin: .zero, size: NSSize(width: 1, height: 1)), styleMask: [.borderless], backing: .buffered, defer: false)
            // on the top
            DefinitionWindow.level = .floating
            let pointInWindow = NSPoint(x:0,y:0); //default value
            DefinitionWindow.contentView?.showDefinition(for: attributedString, at: pointInWindow)
            DefinitionWindow.orderFront(nil)
        }
    }
}
let delegate = AppDelegate()
let app = NSApplication.shared
app.delegate = delegate
app.run()

full crash log reveals the following error message:

FAULT: deferNSXPCInvocationOntoMainThread_block_invoke caught NSInternalInconsistencyException '_CPSSetFrontProcessWithOptions failed due to CGError -606 4294966690 fffffda2 (appIsDaemon)' with backtrace (
    "0   CoreFoundation                      __exceptionPreprocess + 176",
    "1   libobjc.A.dylib                     objc_exception_throw + 60",
    "2   CoreFoundation                      +[NSException exceptionWithName:reason:userInfo:] + 0",
    "3   ViewBridge                          assertCGError + 80",
    "4   ViewBridge                          -[NSRemoteView _serviceWindowWouldActivate] + 724",
    "5   CoreFoundation                      __invoking___ + 148",
    "6   CoreFoundation                      -[NSInvocation invoke] + 428",
    "7   ViewBridge                          __deferNSXPCInvocationOntoMainThread_block_invoke + 120",
    "8   ViewBridge                          __wrapBlockWithVoucher_block_invoke + 56",
    "9   ViewBridge                          deferredBlockOpportunity_block_invoke_2 + 360",
    "10  CoreFoundation                      __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 28",
    "11  CoreFoundation                      __CFRunLoopDoBlocks + 356",
    "12  CoreFoundation                      __CFRunLoopRun + 2440",
    "13  CoreFoundation                      CFRunLoopRunSpecific + 608",
    "14  HIToolbox                           RunCurrentEventLoopInMode + 292",
    "15  HIToolbox                           ReceiveNextEventCommon + 648",
    "16  HIToolbox                           _BlockUntilNextEventMatchingListInModeWithFilter + 76",
    "17  AppKit                              _DPSNextEvent + 660",
    "18  AppKit                              -[NSApplication(NSEventRouting) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 716",
    "19  AppKit                              -[NSApplication run] + 476",
    "20  try                                 main + 160",
    "21  dyld                                start + 2360"
)

Just a reminder, the application will crash when you click on the displayed definition window.

Potential Questions and Concerns:

Could there be an issue related to UI transitions or the main thread?

How exactly does the showDefinition(for:at) process work internally?

Maybe , the view's display level being raised when clicked caused conflict?

If anyone could provide any insights or guidance on resolving this issue, it would be greatly appreciated. Thank you!

Crash When Clicking on Definition View Created by AppKit's showDefinition(for:at)
 
 
Q