gent-link 0.2.12

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?

@_cdecl("gent_mac_hour_cycle")
public func hourCycle() -> Int32 {
    let pattern = DateFormatter.dateFormat(fromTemplate: "j", options: 0, locale: .autoupdatingCurrent) ?? ""
    var quoted = false
    for c in pattern {
        if c == "'" { quoted.toggle() }
        if quoted { continue }
        if c == "h" || c == "K" { return 12 }
        if c == "H" || c == "k" { return 24 }
    }
    return 0
}

public typealias TrayClick = @convention(c) (Bool) -> Void
public typealias TrayDismiss = @convention(c) () -> Void

// The button owns this view. Tauri's tray also has a mouse target on the
// button; handle presses above it so each press reaches exactly one action.
private weak var trayControl: TrayControl?

private final class TrayControl: NSView {
    weak var popup: NSWindow?
    private weak var sizedPanel: NSWindow?
    private var preferredSize = NSSize.zero
    let click: TrayClick
    let dismiss: TrayDismiss
    var localMonitor: Any?
    var globalMonitor: Any?

    init(button: NSStatusBarButton, click: @escaping TrayClick, dismiss: @escaping TrayDismiss) {
        self.click = click
        self.dismiss = dismiss
        super.init(frame: button.bounds)
        autoresizingMask = [.width, .height]
        setAccessibilityElement(false)
        button.addSubview(self, positioned: .above, relativeTo: nil)
        button.target = self
        button.action = #selector(activate)
    }

    required init?(coder: NSCoder) { nil }
    override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true }

    @objc private func activate() {
        watchForDismissal()
        click(false)
    }

    override func mouseDown(with event: NSEvent) {
        if event.modifierFlags.contains(.control) { click(true) } else { activate() }
    }

    override func rightMouseDown(with event: NSEvent) { click(true) }

    private func watchForDismissal() {
        guard localMonitor == nil else { return }
        let presses: NSEvent.EventTypeMask = [.leftMouseDown, .rightMouseDown, .otherMouseDown]
        // Start at the press, so a click elsewhere also cancels a pending dashboard read.
        localMonitor = NSEvent.addLocalMonitorForEvents(matching: presses.union(.keyDown)) { [weak self] event in
            guard let self else { return event }
            if event.type == .keyDown {
                if event.keyCode == 53 && event.window === self.popup {
                    self.clickedAway()
                    return nil
                }
            } else if let target = event.window, target !== self.popup,
                      !(target === self.window && self.bounds.contains(self.convert(event.locationInWindow, from: nil))) {
                self.clickedAway()
            }
            return event
        }
        globalMonitor = NSEvent.addGlobalMonitorForEvents(matching: presses) { [weak self] _ in
            self?.clickedAway()
        }
    }

    @objc private func clickedAway() {
        stopWatching()
        dismiss()
    }

    func stopWatching() {
        if let localMonitor { NSEvent.removeMonitor(localMonitor) }
        if let globalMonitor { NSEvent.removeMonitor(globalMonitor) }
        localMonitor = nil
        globalMonitor = nil
        NotificationCenter.default.removeObserver(self, name: NSWindow.didResignKeyNotification, object: popup)
        popup = nil
    }

    func show(_ panel: NSWindow) -> Bool {
        guard let statusWindow = window, let screen = statusWindow.screen else { return false }
        let anchor = statusWindow.convertToScreen(convert(bounds, to: nil))
        let visible = screen.visibleFrame
        let top = min(visible.maxY, anchor.minY)
        // A reusable panel can move from a small display back to a larger one.
        // Clamp its original Tauri size independently on each presentation.
        if sizedPanel !== panel {
            preferredSize = panel.frame.size
            sizedPanel = panel
        }
        let width = min(preferredSize.width, visible.width)
        let height = min(preferredSize.height, top - visible.minY)
        guard width > 0, height > 0 else { return false }
        let x = max(visible.minX, min(floor(anchor.midX - width / 2), visible.maxX - width))
        panel.level = .floating
        panel.collectionBehavior = [.moveToActiveSpace, .fullScreenAuxiliary, .ignoresCycle]
        panel.setFrame(NSRect(x: x, y: top - height, width: width, height: height), display: true)
        if popup !== panel {
            NotificationCenter.default.removeObserver(self, name: NSWindow.didResignKeyNotification, object: popup)
            popup = panel
            NotificationCenter.default.addObserver(self, selector: #selector(resignedKey(_:)),
                                                   name: NSWindow.didResignKeyNotification, object: panel)
        }
        watchForDismissal()
        if #available(macOS 14.0, *) { NSApp.activate() } else { NSApp.activate(ignoringOtherApps: true) }
        panel.makeKeyAndOrderFront(nil)
        return true
    }

    @objc private func resignedKey(_ note: Notification) { clickedAway() }
}

@_cdecl("gent_mac_install_tray")
public func installTray(_ pointer: UnsafeRawPointer, _ click: @escaping TrayClick, _ dismiss: @escaping TrayDismiss) -> Bool {
    let item = Unmanaged<NSStatusItem>.fromOpaque(pointer).takeUnretainedValue()
    item.length = NSStatusItem.squareLength
    guard let button = item.button, let image = button.image else { return false }
    image.size = NSSize(width: 20, height: 20)
    button.image = image
    let control = TrayControl(button: button, click: click, dismiss: dismiss)
    trayControl = control
    return true
}

@_cdecl("gent_mac_end_tray_tracking")
public func endTrayTracking() { trayControl?.stopWatching() }

@_cdecl("gent_mac_show_popup")
public func showPopup(_ pointer: UnsafeMutableRawPointer) -> Bool {
    let panel = Unmanaged<NSWindow>.fromOpaque(pointer).takeUnretainedValue()
    return trayControl?.show(panel) ?? false
}

// 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)
}