gent-link 0.2.22

Connect Codex and Claude Code chats across machines with the Gent CLI and desktop companion.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
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

public typealias TraySizeRead = @convention(c) (UnsafePointer<CChar>, UnsafeMutablePointer<Int32>,
                                               UnsafeMutablePointer<Int32>) -> Bool
public typealias TraySizeSave = @convention(c) (UnsafePointer<CChar>, Int32, Int32) -> 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 extension NSScreen {
    var trayDisplayID: CGDirectDisplayID? {
        (deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")] as? NSNumber)?.uint32Value
    }

    var trayDisplayKey: String? {
        guard let id = trayDisplayID, let uuid = CGDisplayCreateUUIDFromDisplayID(id)?.takeRetainedValue() else { return nil }
        return (CFUUIDCreateString(nil, uuid) as String).lowercased()
    }
}

// Wire values match popup::ResizeEdge.
private enum ResizeEdge: Int32 {
    case top, right, bottom, left, bottomLeft, bottomRight
}

private final class TrayControl: NSView {
    weak var popup: NSWindow?
    private var clickedDisplay: CGDirectDisplayID?
    // A screen without a stable UUID can still remember a size for this session.
    private var sessionSizes: [CGDirectDisplayID: NSSize] = [:]
    private var pressPoint: NSPoint?
    private var resizeDrag: (edge: ResizeEdge, size: NSSize, screen: NSScreen, key: String?, latest: NSSize?)?
    private var dockedLevel: NSWindow.Level?
    private var changingFullscreen = false
    let click: TrayClick
    let dismiss: TrayDismiss
    let readTraySize: TraySizeRead
    let saveTraySize: TraySizeSave
    var localMonitor: Any?
    var globalMonitor: Any?

    init(button: NSStatusBarButton, click: @escaping TrayClick, dismiss: @escaping TrayDismiss,
         read: @escaping TraySizeRead, save: @escaping TraySizeSave) {
        self.click = click
        self.dismiss = dismiss
        self.readTraySize = read
        self.saveTraySize = save
        super.init(frame: button.bounds)
        autoresizingMask = [.width, .height]
        setAccessibilityElement(false)
        button.addSubview(self, positioned: .above, relativeTo: nil)
        button.target = self
        button.action = #selector(activate)
        NotificationCenter.default.addObserver(self, selector: #selector(willTerminate(_:)),
                                               name: NSApplication.willTerminateNotification, object: nil)
    }

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

    @objc private func activate() {
        finishResize()
        clickedDisplay = window?.screen?.trayDisplayID
        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, .leftMouseDragged, .leftMouseUp])) { [weak self] event in
            guard let self else { return event }
            switch event.type {
            case .keyDown:
                if event.keyCode == 53 && self.dockedLevel == nil && event.window === self.popup {
                    if !event.isARepeat { self.clickedAway() }
                    return nil
                }
            case .leftMouseDragged, .leftMouseUp:
                self.drag(to: NSEvent.mouseLocation)
                if event.type == .leftMouseUp {
                    self.finishResize()
                }
            default:
                if let target = event.window, target === self.popup {
                    if event.type == .leftMouseDown {
                        // The WebKit pointerdown reaches the bridge asynchronously.
                        self.pressPoint = target.convertPoint(toScreen: event.locationInWindow)
                    }
                } else if let target = event.window,
                          !(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() {
        finishResize()
        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)
        NotificationCenter.default.removeObserver(self, name: NSApplication.didChangeScreenParametersNotification, object: nil)
        restoreLevel()
        popup = nil
        clickedDisplay = nil
    }

    private var selectedScreen: NSScreen? {
        NSScreen.screens.first { $0.trayDisplayID == clickedDisplay } ?? window?.screen
    }

    private func place(_ panel: NSWindow, on screen: NSScreen, size: NSSize) {
        let visible = screen.visibleFrame
        let width = min(size.width, visible.width)
        let height = min(size.height, visible.height)
        let frame = NSRect(x: visible.maxX - width, y: visible.maxY - height, width: width, height: height)
        if panel.frame != frame {
            panel.setFrame(frame, display: true)
        }
    }

    private func layout(_ panel: NSWindow, on screen: NSScreen) {
        if dockedLevel != nil {
            if panel.frame != screen.frame { panel.setFrame(screen.frame, display: true) }
            return
        }
        let area = screen.visibleFrame
        let size = savedSize(on: screen, key: screen.trayDisplayKey)
            ?? NSSize(width: (area.width / 2).rounded(), height: (area.height / 2).rounded())
        place(panel, on: screen, size: size)
    }

    private func savedSize(on screen: NSScreen, key: String?) -> NSSize? {
        guard let key else { return screen.trayDisplayID.flatMap { sessionSizes[$0] } }
        var width: Int32 = 0, height: Int32 = 0
        guard readTraySize(key, &width, &height) else { return nil }
        return NSSize(width: Int(width), height: Int(height))
    }

    private func saveResize(from start: NSSize, to size: NSSize, on screen: NSScreen, key: String?) {
        guard size != start else { return }
        // Keep the preferred extent of an untouched axis even if its visible frame was clipped.
        let previous = savedSize(on: screen, key: key) ?? start
        let preferred = NSSize(width: size.width == start.width ? previous.width : size.width,
                               height: size.height == start.height ? previous.height : size.height)
        if let key {
            saveTraySize(key, Int32(preferred.width), Int32(preferred.height))
        } else if let id = screen.trayDisplayID {
            sessionSizes[id] = preferred
        }
    }

    private func finishResize() {
        if let drag = resizeDrag, let size = drag.latest {
            saveResize(from: drag.size, to: size, on: drag.screen, key: drag.key)
        }
        pressPoint = nil
        resizeDrag = nil
    }

    @objc private func willTerminate(_ note: Notification) { finishResize() }

    private func restoreLevel() {
        if let previous = dockedLevel {
            dockedLevel = nil
            popup?.level = previous
        }
    }

    func setFullscreen(_ panel: NSWindow, enabled: Bool) -> Bool {
        if !enabled && dockedLevel == nil { return true }
        guard popup === panel, let screen = selectedScreen, !enabled || panel.isVisible else { return false }
        if enabled == (dockedLevel != nil) { return true }
        finishResize()
        changingFullscreen = true
        defer { changingFullscreen = false }
        if enabled {
            // AppKit simple fullscreen keeps this borderless tray on its current display and Space.
            dockedLevel = panel.level
            // Accessory apps can still have a status item above their fullscreen exit button.
            panel.level = NSWindow.Level(rawValue: NSWindow.Level.statusBar.rawValue + 1)
        } else {
            restoreLevel()
        }
        layout(panel, on: screen)
        return true
    }

    private func resize(_ panel: NSWindow, on screen: NSScreen, to requested: NSSize) -> NSSize? {
        let area = screen.visibleFrame
        let size = NSSize(width: min(area.width, max(240, requested.width.rounded())),
                          height: min(area.height, max(160, requested.height.rounded())))
        guard size != panel.frame.size else { return nil }
        place(panel, on: screen, size: size)
        return size
    }

    private func drag(to point: NSPoint) {
        guard let panel = popup, let press = pressPoint, let drag = resizeDrag,
              point != press || panel.frame.size != drag.size else { return }
        let dx = point.x - press.x, dy = point.y - press.y   // AppKit y increases upwards.
        var size = drag.size
        switch drag.edge {
        case .top: size.height += dy
        case .right: size.width += dx
        case .bottom: size.height -= dy
        case .left: size.width -= dx
        case .bottomLeft:
            size.width -= dx
            size.height -= dy
        case .bottomRight:
            size.width += dx
            size.height -= dy
        }
        if let size = resize(panel, on: drag.screen, to: size) { resizeDrag?.latest = size }
    }

    func startResize(_ panel: NSWindow, edge: ResizeEdge) -> Bool {
        guard popup === panel, panel.isVisible, dockedLevel == nil else { return false }
        // A quick click can finish before the bridge call arrives. Keep its size.
        if NSEvent.pressedMouseButtons & 1 != 0, pressPoint != nil, let screen = selectedScreen {
            resizeDrag = (edge, panel.frame.size, screen, screen.trayDisplayKey, nil)
            drag(to: NSEvent.mouseLocation)
        }
        return true
    }

    func resizeBy(_ panel: NSWindow, dx: Int32, dy: Int32) -> Bool {
        guard popup === panel, panel.isVisible, dockedLevel == nil, let screen = selectedScreen else { return false }
        finishResize()
        let size = panel.frame.size
        if let resized = resize(panel, on: screen, to: NSSize(width: size.width + CGFloat(dx), height: size.height + CGFloat(dy))) {
            saveResize(from: size, to: resized, on: screen, key: screen.trayDisplayKey)
        }
        return true
    }

    @objc private func screensChanged(_ note: Notification) {
        finishResize()
        if let panel = popup, let screen = selectedScreen { layout(panel, on: screen) }
    }

    func show(_ panel: NSWindow) -> Bool {
        guard let screen = selectedScreen, !screen.visibleFrame.isEmpty else { return false }
        panel.level = .floating
        panel.collectionBehavior = [.moveToActiveSpace, .fullScreenAuxiliary, .ignoresCycle]
        layout(panel, on: screen)
        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)
            NotificationCenter.default.addObserver(self, selector: #selector(screensChanged(_:)),
                                                   name: NSApplication.didChangeScreenParametersNotification, object: nil)
        }
        watchForDismissal()
        if #available(macOS 14.0, *) { NSApp.activate() } else { NSApp.activate(ignoringOtherApps: true) }
        panel.makeKeyAndOrderFront(nil)
        return true
    }

    @objc private func resignedKey(_ note: Notification) {
        guard !changingFullscreen, let panel = popup else { return }
        DispatchQueue.main.async { [weak self, weak panel] in
            guard let self, let panel, self.popup === panel, !panel.isKeyWindow else { return }
            self.clickedAway()
        }
    }
}

@_cdecl("gent_mac_install_tray")
public func installTray(_ pointer: UnsafeRawPointer, _ click: @escaping TrayClick, _ dismiss: @escaping TrayDismiss,
                        _ read: @escaping TraySizeRead, _ save: @escaping TraySizeSave) -> 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, read: read, save: save)
    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
}

@_cdecl("gent_mac_start_resize")
public func startResize(_ pointer: UnsafeMutableRawPointer, _ edgeCode: Int32) -> Bool {
    guard let edge = ResizeEdge(rawValue: edgeCode) else { return false }
    let panel = Unmanaged<NSWindow>.fromOpaque(pointer).takeUnretainedValue()
    return trayControl?.startResize(panel, edge: edge) ?? false
}

@_cdecl("gent_mac_set_tray_fullscreen")
public func setTrayFullscreen(_ pointer: UnsafeMutableRawPointer, _ enabled: Bool) -> Bool {
    let panel = Unmanaged<NSWindow>.fromOpaque(pointer).takeUnretainedValue()
    return trayControl?.setFullscreen(panel, enabled: enabled) ?? false
}

@_cdecl("gent_mac_resize_by")
public func resizeBy(_ pointer: UnsafeMutableRawPointer, _ dx: Int32, _ dy: Int32) -> Bool {
    let panel = Unmanaged<NSWindow>.fromOpaque(pointer).takeUnretainedValue()
    return trayControl?.resizeBy(panel, dx: dx, dy: dy) ?? 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, _ boardSize: UnsafePointer<CChar>,
                           _ ready: @escaping @convention(c) (Bool) -> Void) {
    let view = Unmanaged<WKWebView>.fromOpaque(pointer).takeUnretainedValue()
    let content = view.configuration.userContentController
    content.addUserScript(WKUserScript(source: String(cString: boardSize), injectionTime: .atDocumentEnd,
                                       forMainFrameOnly: false, in: .world(name: "gent-board-size")))
    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 }
        content.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)
}