gent-link 0.2.2

Connect Codex and Claude Code chats across machines with the Gent CLI and desktop companion.
import AppKit
import CoreServices
import Security
import UserNotifications
import WebKit

private final class NotificationPresentation: NSObject, UNUserNotificationCenterDelegate {
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification,
                                withCompletionHandler reply: @escaping (UNNotificationPresentationOptions) -> Void) {
        reply([.banner, .list])
    }
}

// The bridge entry points run on the app's main thread. Keep the center's weak delegate alive.
private let presentation = NotificationPresentation()
private var delivery: NativeNotifications?

// Only the application schemes and bundled data assets are needed by the shell.
// A content rule filters resource loads; it does not disable WebRTC transports.
@_cdecl("gent_mac_protect_webview")
public func protectWebView(_ pointer: UnsafeMutableRawPointer, _ ready: @escaping @convention(c) (Bool) -> Void) {
    let view = Unmanaged<WKWebView>.fromOpaque(pointer).takeUnretainedValue()
    let rules = #"""
        [
          {"trigger":{"url-filter":"^https?://"},"action":{"type":"block"}},
          {"trigger":{"url-filter":"^wss?://"},"action":{"type":"block"}},
          {"trigger":{"url-filter":"^ftp://"},"action":{"type":"block"}}
        ]
        """#
    WKContentRuleListStore.default().compileContentRuleList(forIdentifier: "GentDesktopOffline",
                                                            encodedContentRuleList: rules) { list, _ in
        guard let list else { ready(false); return }
        view.configuration.userContentController.add(list)
        ready(true)
    }
}

@_cdecl("gent_mac_launch")
public func launchUnmanaged() -> Int32 {
    guard Bundle.main.bundleIdentifier == "link.gent.notifications" else { return 1 }
    var session = SessionAttributeBits()
    let graphical = SessionGetInfo(callerSecuritySession, nil, &session) == errSecSuccess
        && session.contains(.sessionHasGraphicAccess)
    let app = NSApplication.shared
    app.setActivationPolicy(.accessory)
    let launcher = DesktopLauncher(graphical: graphical)
    app.delegate = launcher
    withExtendedLifetime(launcher) { app.run() }
    return 0
}

public typealias NativeReply = @convention(c) (UnsafePointer<UInt8>?, Int) -> Void

@_cdecl("gent_mac_initialize")
public func initializeNotifications(_ diagnose: Bool, _ reply: @escaping NativeReply) {
    let send: NativeNotifications.Send = { fields in
        guard let data = try? JSONSerialization.data(withJSONObject: fields) else { return }
        data.withUnsafeBytes { raw in reply(raw.bindMemory(to: UInt8.self).baseAddress, raw.count) }
    }
    var center: UNUserNotificationCenter?
    if Bundle.main.bundleIdentifier == "link.gent.notifications" {
        let bundle = Bundle.main.bundleURL
        let launchedByServices = CommandLine.arguments.contains("--launch-services")
        let registration = launchedByServices ? nil : LSRegisterURL(bundle as CFURL, true)
        if diagnose {
            let preferred = NSWorkspace.shared.urlForApplication(withBundleIdentifier: "link.gent.notifications")
            var info: [String: Any] = ["op":"notification_diagnostic", "stage":"lookup",
                "preferred":preferred == nil ? "missing" : preferred?.resolvingSymlinksInPath() == bundle.resolvingSymlinksInPath() ? "same" : "other",
                "translocated":bundle.pathComponents.contains("AppTranslocation")]
            if let registration { info["code"] = registration }
            send(info)
        }
        if registration == nil || registration == noErr {
            center = UNUserNotificationCenter.current()
            center?.delegate = presentation
        }
    }
    let notifications = NativeNotifications(center: center, send: send)
    delivery = notifications
    notifications.prepare()
}

@_cdecl("gent_mac_notify")
public func notify(_ bytes: UnsafePointer<UInt8>, _ count: Int) {
    guard let banner = try? JSONDecoder().decode(Banner.self, from: Data(bytes: bytes, count: count)) else { return }
    delivery?.receive(banner)
}