| 1 | import LChatCore |
| 2 | import SwiftUI |
| 3 | import AppKit |
| 4 | import WebKit |
| 5 | import UserNotifications |
| 6 | import Sparkle |
| 7 | import os |
| 8 | |
| 9 | // Verification tap for the native-identity store (log stream --predicate |
| 10 | // 'subsystem == "com.elevenmessenger.mac"'). Names, never keys. |
| 11 | extension Logger { |
| 12 | static let identity = Logger(subsystem: "com.elevenmessenger.mac", category: "identity") |
| 13 | } |
| 14 | |
| 15 | // A genuinely native macOS app — NOT Mac Catalyst. The window, sidebar, toolbar |
| 16 | // and menu bar are real AppKit-backed SwiftUI, so scrolling, the title bar and the |
| 17 | // menu bar feel like a Mac app instead of an iPad app in a window. |
| 18 | // |
| 19 | // Fully native: the feed, composer and crypto all run in Swift (LChatCore). |
| 20 | // The only WKWebViews left are SCOPED — mini-app panels (AppThreadWebView) and |
| 21 | // nothing else; the full-frame web fallback (and its paste-a-link join) is |
| 22 | // gone. Entry is by signing in with Eleven; identities ride the vault. |
| 23 | @main |
| 24 | struct LChatMacApp: App { |
| 25 | @NSApplicationDelegateAdaptor(AppDelegate.self) private var appDelegate |
| 26 | @StateObject private var app = MacAppState() |
| 27 | // Observed here only so the View-menu items' enabled state tracks the pref. |
| 28 | @AppStorage(ChatTextSize.key) private var chatTextSize = ChatTextSize.defaultSize |
| 29 | |
| 30 | init() { |
| 31 | // Match the web feed's text rendering: style.css sets |
| 32 | // -webkit-font-smoothing: antialiased, which turns OFF macOS's |
| 33 | // stroke-dilating font smoothing — AppKit leaves it on, so the same |
| 34 | // SF glyphs render visibly heavier in native text than in the |
| 35 | // webview. This is the app-wide equivalent of that CSS. |
| 36 | UserDefaults.standard.set(0, forKey: "AppleFontSmoothing") |
| 37 | // Sockets heartbeat "active" while the app is frontmost (presence + |
| 38 | // push suppression) — wired per platform because LChatCore can't see AppKit. |
| 39 | ChatSocket.appIsActive = { NSApp.isActive } |
| 40 | #if DEBUG |
| 41 | // Unread flips land in the Debug Events windows beside the frames |
| 42 | // that did (or didn't) cause them (ThreadDebug.swift). |
| 43 | ThreadEventLog.installStoreTaps() |
| 44 | #endif |
| 45 | } |
| 46 | |
| 47 | var body: some Scene { |
| 48 | // Window, NOT WindowGroup: the root surface is one window, full stop — |
| 49 | // WindowGroup let `open`/URL callbacks and reopen events spawn extra |
| 50 | // copies of the whole app UI. Windows for breaking specific features |
| 51 | // out (a lightbox, an app) can be their own scenes later. |
| 52 | Window("Eleven", id: "main") { |
| 53 | RootView() |
| 54 | .environmentObject(app) |
| 55 | .environmentObject(appDelegate.gentleReminder) |
| 56 | .frame(minWidth: 820, minHeight: 560) |
| 57 | .onAppear { appDelegate.appState = app } |
| 58 | .onOpenURL { url in |
| 59 | // The browser sign-in handoff (elevenmessenger:// |
| 60 | // home-session#…): claimed first, always. |
| 61 | if MacHomeSignIn.handleCallback(url, into: app) { |
| 62 | NSApp.activate(ignoringOtherApps: true) |
| 63 | return |
| 64 | } |
| 65 | // The join page's "Open in the app" (issue #1089's |
| 66 | // handoff cousin): elevenmessenger://add?url=<join or |
| 67 | // add-device link, fragment riding encoded inside the |
| 68 | // query value — the secret never reaches any server>. |
| 69 | // Validated here, then PRE-FILLS the Add-from-link sheet |
| 70 | // rather than joining — one confirming click, with the |
| 71 | // link visible, for any URL that arrived from outside. |
| 72 | if url.host == "add", |
| 73 | let link = URLComponents(url: url, resolvingAgainstBaseURL: false)? |
| 74 | .queryItems?.first(where: { $0.name == "url" })?.value, |
| 75 | parseJoinLink(link) != nil { |
| 76 | app.pendingAddLink = link |
| 77 | NSApp.activate(ignoringOtherApps: true) |
| 78 | } |
| 79 | } |
| 80 | } |
| 81 | // Hide the title bar so the feed runs to the top; the web header is made |
| 82 | // draggable via an injected script (see ChatFeedWebView), and the top of the |
| 83 | // rail drags via the system title-bar region. No title, toolbar, or toggle. |
| 84 | .windowStyle(.hiddenTitleBar) |
| 85 | .defaultSize(width: 1160, height: 820) |
| 86 | .commands { |
| 87 | CommandGroup(replacing: .newItem) { |
| 88 | // File → New Space: the goes-to-eleven create flow (the rail's |
| 89 | // "+"). ⇧⌘N, the new-container idiom. The Sidebar owns the |
| 90 | // sheet; it opens on the tick. |
| 91 | Button("New space") { app.requestCreateSpace() } |
| 92 | .keyboardShortcut("n", modifiers: [.command, .shift]) |
| 93 | .disabled(app.instances.isEmpty) |
| 94 | } |
| 95 | CommandGroup(after: .newItem) { |
| 96 | // A MENU shortcut, deliberately: a view-level hidden button |
| 97 | // lost ⌘F whenever a greedy first responder (a mini-app's |
| 98 | // WKWebView, a text view) swallowed the key equivalent — menu |
| 99 | // items win the same way ⌘C does. |
| 100 | Button("Find Chat…") { app.focusSearchTick += 1 } |
| 101 | .keyboardShortcut("f", modifiers: .command) |
| 102 | // ⌘[ / ⌘] step through the chat list (Slack's ⌥↑/↓, in the |
| 103 | // bracket idiom Paul asked for). Ticks, not toggles — each |
| 104 | // press must fire even when the direction repeats. |
| 105 | Button("Previous Chat") { app.cycleChatTick -= 1 } |
| 106 | .keyboardShortcut("[", modifiers: .command) |
| 107 | Button("Next Chat") { app.cycleChatTick += 1 } |
| 108 | .keyboardShortcut("]", modifiers: .command) |
| 109 | } |
| 110 | // View → Make Text Bigger/Smaller (Messages' menu), stepping the |
| 111 | // same ladder as the Settings slider and the web's. The menu key |
| 112 | // equivalent is "+", which strictly means ⌘⇧=; AppDelegate's key |
| 113 | // monitor also maps the unshifted ⌘= press — what "cmd and plus" |
| 114 | // physically is on most keyboards — like Messages/Safari accept. |
| 115 | CommandGroup(before: .toolbar) { |
| 116 | Button("Make Text Bigger") { ChatTextSize.bump(+1) } |
| 117 | .keyboardShortcut("+", modifiers: .command) |
| 118 | .disabled(ChatTextSize.snap(chatTextSize) >= ChatTextSize.stops.last!) |
| 119 | Button("Make Text Smaller") { ChatTextSize.bump(-1) } |
| 120 | .keyboardShortcut("-", modifiers: .command) |
| 121 | .disabled(ChatTextSize.snap(chatTextSize) <= ChatTextSize.stops.first!) |
| 122 | Button("Default Text Size") { ChatTextSize.reset() } |
| 123 | .keyboardShortcut("0", modifiers: .command) |
| 124 | Divider() |
| 125 | } |
| 126 | // The keyboard's two message verbs (issue #392), the web feed's |
| 127 | // ⌘R / ⌘T. Menu items for the same reason ⌘F is one: the composer |
| 128 | // is a real NSTextView and a mini-app pane is a WKWebView, and |
| 129 | // either would swallow a view-level key equivalent — a menu item |
| 130 | // wins first, the way ⌘C does. |
| 131 | CommandMenu("Message") { |
| 132 | Button("Reply to Latest Message") { app.replyLatestTick += 1 } |
| 133 | .keyboardShortcut("r", modifiers: .command) |
| 134 | // ⌘R's thread-pane twin (thread-pane spec §3.5): opens the |
| 135 | // latest message's thread in the docked pane instead of |
| 136 | // staging a reply on the channel bar. |
| 137 | Button("Reply in Thread to Latest Message") { app.replyInThreadLatestTick += 1 } |
| 138 | .keyboardShortcut("r", modifiers: [.command, .shift]) |
| 139 | Button("React to Latest Message") { app.reactLatestTick += 1 } |
| 140 | .keyboardShortcut("t", modifiers: .command) |
| 141 | } |
| 142 | // ⌘1…⌘9 jump straight to a space, like browser/Slack tabs. The |
| 143 | // menu mirrors the rail: favourites (else the first nine active), |
| 144 | // the rest under More, and the two ways a space arrives. |
| 145 | CommandMenu("Spaces") { |
| 146 | Button("Quick switch…") { app.showPalette = true } |
| 147 | .keyboardShortcut("k", modifiers: .command) |
| 148 | Divider() |
| 149 | ForEach(Array(app.menuSpaces.enumerated()), id: \.element.id) { index, chat in |
| 150 | Button(app.serverName(chat)) { app.selection = chat.id } |
| 151 | .keyboardShortcut(KeyEquivalent(Character("\(index + 1)")), modifiers: .command) |
| 152 | } |
| 153 | if !app.menuOverflow.isEmpty { |
| 154 | Menu("More") { |
| 155 | ForEach(app.menuOverflow) { chat in |
| 156 | Button(app.serverName(chat)) { app.selection = chat.id } |
| 157 | } |
| 158 | } |
| 159 | } |
| 160 | Divider() |
| 161 | Button("Create a space") { app.requestCreateSpace() } |
| 162 | Button("Add from link…") { app.requestAddFromLink() } |
| 163 | } |
| 164 | // Our own About item, so the standard panel can carry the git SHA |
| 165 | // the build was stamped with (BuildInfo). Same position and title |
| 166 | // as the one SwiftUI provides — it just opens the panel with |
| 167 | // options. |
| 168 | CommandGroup(replacing: .appInfo) { |
| 169 | Button("About \(BuildInfo.appName)") { BuildInfo.showAboutPanel() } |
| 170 | } |
| 171 | // Sits right below "About Eleven" in the app menu. |
| 172 | CommandGroup(after: .appInfo) { |
| 173 | CheckForUpdatesView(updater: appDelegate.updaterController.updater) |
| 174 | } |
| 175 | #if DEBUG |
| 176 | // Dev builds only: the client-wide event log — every WebSocket |
| 177 | // frame from every mounted space (ThreadDebug.swift). The |
| 178 | // per-thread view lives in the thread context menu. |
| 179 | CommandMenu("Debug") { |
| 180 | Button("All Received Events") { ThreadDebugWindows.showAll() } |
| 181 | } |
| 182 | #endif |
| 183 | } |
| 184 | Settings { |
| 185 | TabView { |
| 186 | MacSettingsView() |
| 187 | .tabItem { Label("General", systemImage: "gearshape") } |
| 188 | UpdatesSettingsView(updater: appDelegate.updaterController.updater) |
| 189 | .tabItem { Label("Updates", systemImage: "arrow.down.circle") } |
| 190 | MacAdvancedSettingsView() |
| 191 | .tabItem { Label("Advanced", systemImage: "wrench.and.screwdriver") } |
| 192 | } |
| 193 | .environmentObject(app) |
| 194 | // ONE fixed frame for the whole Settings window, here on the |
| 195 | // TabView — per-pane frames made the window resize on every tab |
| 196 | // switch (and shrink-and-stick after visiting the short Updates |
| 197 | // pane). Panes size to fill; a grouped Form scrolls if it must. |
| 198 | .frame(width: 600, height: 560) |
| 199 | } |
| 200 | } |
| 201 | } |
| 202 | |
| 203 | // Owns notification authorization + delivery. Local notifications only (no APNs / |
| 204 | // no paid account): chat.js posts a decrypted preview via the `lchatNotify` bridge, |
| 205 | // we display it, and a tap jumps to that instance. |
| 206 | final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCenterDelegate { |
| 207 | weak var appState: MacAppState? |
| 208 | // Gentle update reminders (UpdaterUI): scheduled checks publish into this |
| 209 | // instead of popping Sparkle's dialog; the rail shows the indicator. |
| 210 | let gentleReminder: GentleUpdateReminder |
| 211 | let updaterController: SPUStandardUpdaterController |
| 212 | |
| 213 | override init() { |
| 214 | let reminder = GentleUpdateReminder() |
| 215 | gentleReminder = reminder |
| 216 | updaterController = SPUStandardUpdaterController( |
| 217 | startingUpdater: true, updaterDelegate: nil, userDriverDelegate: reminder) |
| 218 | reminder.updater = updaterController.updater |
| 219 | super.init() |
| 220 | } |
| 221 | |
| 222 | // Every activation pulls the vault — switching back from the browser or |
| 223 | // another Mac is exactly when a home-page change is freshest. |
| 224 | func applicationDidBecomeActive(_ notification: Notification) { |
| 225 | appState?.pullHome() |
| 226 | } |
| 227 | |
| 228 | func applicationDidFinishLaunching(_ notification: Notification) { |
| 229 | ClickLab.start() |
| 230 | // Signposts + (consent-gated) perf recording, shared with iOS (Perf.swift). |
| 231 | Perf.install() |
| 232 | // The DEK-sync migrate-by-addition moment (#1089, flag-gated): an |
| 233 | // existing signed-in install adds the synchronizable DEK item on its |
| 234 | // first unlocked launch — write-gated on the account holding a SiwA |
| 235 | // anchor; a no-op for everyone else. |
| 236 | Task { await DEKSync.writeIfEligible() } |
| 237 | // "cmd and plus": the View menu's ⌘+ equivalent strictly needs the |
| 238 | // shifted key (⌘⇧=), but people press ⌘= and expect bigger text — |
| 239 | // Messages and Safari both accept it, so map it here. (⌘− needs no |
| 240 | // help; "-" is unshifted already.) |
| 241 | NSEvent.addLocalMonitorForEvents(matching: .keyDown) { event in |
| 242 | guard event.modifierFlags.intersection(.deviceIndependentFlagsMask) == .command, |
| 243 | event.charactersIgnoringModifiers == "=" else { return event } |
| 244 | ChatTextSize.bump(+1) |
| 245 | return nil |
| 246 | } |
| 247 | let center = UNUserNotificationCenter.current() |
| 248 | center.delegate = self |
| 249 | center.requestAuthorization(options: [.alert, .sound]) { _, _ in } |
| 250 | } |
| 251 | |
| 252 | // Show the banner even when Eleven is frontmost — the web layer already dropped |
| 253 | // the one chat you're actively reading, so anything that reaches here is wanted. |
| 254 | func userNotificationCenter(_ center: UNUserNotificationCenter, |
| 255 | willPresent notification: UNNotification, |
| 256 | withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { |
| 257 | completionHandler([.banner, .sound]) |
| 258 | } |
| 259 | |
| 260 | // Tapping a notification brings Eleven forward and lands on the message it |
| 261 | // was about: its space, its chat, and the bubble itself (waved, its thread |
| 262 | // opened when the reply lives only there). The banner carries all three — |
| 263 | // notifyIfBackgrounded stamps instance/thread/message into userInfo — so |
| 264 | // this only has to hand them to the surfaces that own each step. |
| 265 | func userNotificationCenter(_ center: UNUserNotificationCenter, |
| 266 | didReceive response: UNNotificationResponse, |
| 267 | withCompletionHandler completionHandler: @escaping () -> Void) { |
| 268 | let info = response.notification.request.content.userInfo |
| 269 | let id = info["instance"] as? String |
| 270 | let thread = info["thread"] as? String |
| 271 | let message = (info["message"] as? NSNumber)?.int64Value |
| 272 | DispatchQueue.main.async { |
| 273 | NSApp.activate(ignoringOtherApps: true) |
| 274 | if let id { self.appState?.selection = id } |
| 275 | guard let thread else { return } |
| 276 | // Both requests PARK until the surface that owns them can act — the |
| 277 | // jump until its feed is the one on screen (consumeJump leaves a |
| 278 | // target that isn't this thread's alone), the chat until its space |
| 279 | // is active with threads in hand (consumeOpenThread) — so a tap into |
| 280 | // a space this session never opened lands just as well as one into |
| 281 | // the chat already in front of you. A turn after the space switch |
| 282 | // simply lets the common case land on the first pass. |
| 283 | DispatchQueue.main.async { |
| 284 | if let message, message > 0 { |
| 285 | self.appState?.nativeJump = .init(thread: thread, message: message) |
| 286 | } |
| 287 | self.appState?.nativeOpenThread = thread |
| 288 | } |
| 289 | } |
| 290 | completionHandler() |
| 291 | } |
| 292 | } |
| 293 | |
| 294 | // The saved chats (each a separate lchat instance) and which one is selected. |
| 295 | // Mirrors the iOS AppState, trimmed to what the Mac shell needs. |
| 296 | final class MacAppState: ObservableObject { |
| 297 | @Published var chats: [SavedChat] |
| 298 | @Published var showPalette = false |
| 299 | // Fetched group names (chat id -> name), shared by the rail and the ⌘K palette. |
| 300 | @Published var names: [String: String] = [:] |
| 301 | // Fetched per-instance server photos (chat id -> image). Public branding served |
| 302 | // in the clear at /api/server-avatar; the rail shows it instead of the initial |
| 303 | // when set. Only populated for instances whose /api/group reports one. |
| 304 | @Published var avatars: [String: NSImage] = [:] |
| 305 | // Chat ids, most-recently-selected first — drives the ⌘K palette order. The rail |
| 306 | // keeps its own manual (drag-reorderable) order in `chats`. |
| 307 | @Published var recent: [String] = [] |
| 308 | // Native identities, keyed by origin ({token, name, keypair}), parked in |
| 309 | // the Keychain (InstancesStore) — arriving via the vault (sign-in + |
| 310 | // foreground pulls); everything native reads from here. |
| 311 | @Published private(set) var instances: [SavedInstance] |
| 312 | // The photo / video the lightbox is showing (nil = closed). App-level state |
| 313 | // because the overlay must cover the whole window, not the pane that |
| 314 | // spawned it. |
| 315 | @Published var lightbox: LightboxItem? |
| 316 | @Published var videoLightbox: VideoLightboxItem? |
| 317 | @Published var youtubeLightbox: YouTubeLightboxItem? |
| 318 | |
| 319 | // The ⌘K bridge for the NATIVE surface: the active NativeChatView publishes |
| 320 | // its thread list here (the webview's lchatPaletteItems equivalent), and |
| 321 | // the palette requests a thread by writing nativeOpenThread, which the |
| 322 | // active NativeChatView consumes. |
| 323 | @Published var nativeChats: [NativePaletteChat] = [] |
| 324 | // Bumped by File ▸ Find Chat (⌘F) — the active surface focuses its search. |
| 325 | @Published var focusSearchTick = 0 |
| 326 | // ⌘[ / ⌘] chat cycling: the SIGN of each change is the direction (the |
| 327 | // counter moves ±1), and any change is one step — the active NativeChatView |
| 328 | // observes it. |
| 329 | @Published var cycleChatTick = 0 |
| 330 | // Message ▸ Reply to / React to Latest Message (⌘R / ⌘T, issue #392). |
| 331 | // Ticks like the two above — pressing the same shortcut twice must fire |
| 332 | // twice — consumed by whichever native feed is on screen. |
| 333 | @Published var replyLatestTick = 0 |
| 334 | // Message ▸ Reply in Thread to Latest Message (⇧⌘R) — ⌘R's docked-pane |
| 335 | // twin, the same tick shape. |
| 336 | @Published var replyInThreadLatestTick = 0 |
| 337 | @Published var reactLatestTick = 0 |
| 338 | // File → New Space (and anything else app-level) asks for the create flow |
| 339 | // by bumping this; RootView owns the takeover and opens on the tick. |
| 340 | @Published var createSpaceTick = 0 |
| 341 | // Spaces → Add from link…: RootView owns the paste sheet. |
| 342 | @Published var addFromLinkTick = 0 |
| 343 | // A join/add-device link handed over by the browser (the join page's |
| 344 | // "Open in the app" → elevenmessenger://add?url=…). Pre-fills the |
| 345 | // Add-from-link sheet — the sheet IS the confirming click; a URL arriving |
| 346 | // from outside the app must never join silently. Consumed on sheet appear. |
| 347 | @Published var pendingAddLink: String? |
| 348 | // Context for the sheet when a rung opens it (the locked pane's "Link |
| 349 | // from Your iPhone…" / "Ask for a New Invite…") — replaces the sheet's |
| 350 | // generic subtitle for that one presentation. Consumed on sheet appear. |
| 351 | @Published var addFromLinkHint: String? |
| 352 | |
| 353 | func requestCreateSpace() { createSpaceTick += 1 } |
| 354 | func requestAddFromLink(hint: String? = nil) { |
| 355 | addFromLinkHint = hint |
| 356 | addFromLinkTick += 1 |
| 357 | } |
| 358 | |
| 359 | // The Spaces menu's rail mirror: favourites when any exist, else the first |
| 360 | // nine active spaces (⌘1…⌘9 follow this order); the rest fold under More. |
| 361 | var menuSpaces: [SavedChat] { |
| 362 | let active = chats.filter { !isArchived($0) } |
| 363 | let starred = active.filter { isStarred($0) } |
| 364 | return starred.isEmpty ? Array(active.prefix(9)) : Array(starred.prefix(9)) |
| 365 | } |
| 366 | |
| 367 | var menuOverflow: [SavedChat] { |
| 368 | let active = chats.filter { !isArchived($0) } |
| 369 | let shown = Set(menuSpaces.map(\.id)) |
| 370 | return active.filter { !shown.contains($0.id) } |
| 371 | } |
| 372 | // A "open this thread AND land on this message" request (search hits): |
| 373 | // the matching feed consumes it once its history contains the target. |
| 374 | @Published var nativeJump: NativeJumpTarget? |
| 375 | struct NativeJumpTarget: Equatable { |
| 376 | let thread: String |
| 377 | let message: Int64 |
| 378 | } |
| 379 | var nativeChatsOwner: String? // instance id, so a deactivating view only clears its own rows |
| 380 | @Published var nativeOpenThread: String? |
| 381 | // "Show the Threads list in this chat" — the header kebab's Threads row. |
| 382 | // The header is painted by NativeChatView and the right-hand dock lives in |
| 383 | // NativeFeedView, so the request crosses on this channel: the matching feed |
| 384 | // consumes it and nils it. |
| 385 | // |
| 386 | // It carries a TICK, unlike nativeJump, because the header outlives the |
| 387 | // feed: a group in Interface mode (and every app thread) draws the header |
| 388 | // over a pane with no NativeFeedView mounted, so a click there strands the |
| 389 | // request until the feed next appears. Without the tick the second click |
| 390 | // would write the same chat id, onChange would see no change, and the row |
| 391 | // would be dead for that chat for the rest of the session. |
| 392 | @Published var nativeReplyThreadList: NativeThreadListRequest? |
| 393 | struct NativeThreadListRequest: Equatable { |
| 394 | let thread: String |
| 395 | let tick: Int |
| 396 | } |
| 397 | private var threadListTick = 0 |
| 398 | func showReplyThreadList(_ thread: String) { |
| 399 | threadListTick += 1 |
| 400 | nativeReplyThreadList = .init(thread: thread, tick: threadListTick) |
| 401 | } |
| 402 | |
| 403 | struct NativePaletteChat { |
| 404 | let id: String |
| 405 | let title: String |
| 406 | let glyph: String? |
| 407 | let avatar: AvatarSource? // the chat's real photo, when we hold the key |
| 408 | var appId: String? = nil // set for app-threads — drives the identity mark |
| 409 | } |
| 410 | |
| 411 | // Selecting a chat records it as most-recently-accessed (for the palette). |
| 412 | @Published var selection: SavedChat.ID? { |
| 413 | didSet { |
| 414 | guard let s = selection, s != oldValue else { return } |
| 415 | recent.removeAll { $0 == s } |
| 416 | recent.insert(s, at: 0) |
| 417 | MacChatsStore.saveRecent(recent) |
| 418 | applyAppearance() |
| 419 | } |
| 420 | } |
| 421 | |
| 422 | init() { |
| 423 | chats = MacChatsStore.load() |
| 424 | recent = MacChatsStore.loadRecent() |
| 425 | instances = InstancesStore.load() |
| 426 | // Launch into the space last open on this Mac (recent[0] — selection's |
| 427 | // didSet keeps it current), falling back to the top of the rail. |
| 428 | let chatIDs = Set(chats.map(\.id)) |
| 429 | selection = recent.first { chatIDs.contains($0) } ?? chats.first?.id |
| 430 | // didSet doesn't fire during init |
| 431 | } |
| 432 | |
| 433 | // Store (or refresh) the native identity for an origin, extracted from the |
| 434 | // webview's session. Writes only on change, so the per-page-load extraction |
| 435 | // doesn't hammer the Keychain; an unchanged identity keeps its resolved |
| 436 | // myUserId/groupName. Signing out removes it (see remove(_:)). |
| 437 | func noteIdentity(origin: String, token: String, name: String, |
| 438 | userPub: String, userPriv: String) { |
| 439 | var inst = SavedInstance(origin: origin, deviceToken: token, screenName: name, |
| 440 | userPub: userPub, userPriv: userPriv) |
| 441 | if let i = instances.firstIndex(where: { $0.origin == origin }) { |
| 442 | inst.myUserId = instances[i].myUserId |
| 443 | inst.groupName = instances[i].groupName |
| 444 | // Every locally-resolved field must survive the refresh — dropping |
| 445 | // one silently reverts it on each page load (starred was cleared |
| 446 | // this way, un-starring the space everywhere via the vault sync). |
| 447 | inst.starred = instances[i].starred |
| 448 | inst.archived = instances[i].archived |
| 449 | // Especially addedAt: a page-load extraction is not a deliberate |
| 450 | // add, so it must not re-arm the entry against a removal tombstone. |
| 451 | inst.addedAt = instances[i].addedAt |
| 452 | guard instances[i] != inst else { return } |
| 453 | instances[i] = inst |
| 454 | } else { |
| 455 | // A first extraction IS the join on this Mac — stamp it so the |
| 456 | // entry beats any older home-page removal tombstone. |
| 457 | inst.addedAt = Date().timeIntervalSince1970 * 1000 |
| 458 | instances.append(inst) |
| 459 | } |
| 460 | InstancesStore.save(instances) |
| 461 | Logger.identity.info("stored native identity for \(origin, privacy: .public)") |
| 462 | } |
| 463 | |
| 464 | var selected: SavedChat? { chats.first { $0.id == selection } } |
| 465 | |
| 466 | // The instance's display name: fetched group name, else the host from the invite |
| 467 | // URL (works for new-format links where `session` is nil). |
| 468 | func serverName(_ chat: SavedChat) -> String { |
| 469 | names[chat.id] ?? chat.origin?.host ?? "Chat" |
| 470 | } |
| 471 | |
| 472 | // A stable hue per instance so its icon colour is the same across launches |
| 473 | // (String.hashValue is randomised per process, so roll a small FNV-ish hash). |
| 474 | func hue(for id: String) -> Double { |
| 475 | var h: UInt64 = 5381 |
| 476 | for b in id.utf8 { h = (h &* 33) &+ UInt64(b) } |
| 477 | return Double(h % 360) / 360.0 |
| 478 | } |
| 479 | |
| 480 | // Icon initials for the rail + palette. Single-word names get one letter; names |
| 481 | // with two or more words get the first letters of the first two words (Campbell |
| 482 | // Family → CF, lchat.run.garden → LR). Computed per-instance, independent of the |
| 483 | // other chats and their order — so reordering the rail never changes an initial. |
| 484 | func initials() -> [String: String] { |
| 485 | func words(_ chat: SavedChat) -> [Substring] { |
| 486 | serverName(chat).split { !($0.isLetter || $0.isNumber) } |
| 487 | } |
| 488 | func head(_ w: Substring?) -> String? { w?.first.map { String($0).uppercased() } } |
| 489 | var out: [String: String] = [:] |
| 490 | for chat in chats { |
| 491 | let ws = words(chat) |
| 492 | guard let first = head(ws.first) else { out[chat.id] = "?"; continue } |
| 493 | out[chat.id] = ws.count >= 2 ? first + (head(ws[1]) ?? "") : first |
| 494 | } |
| 495 | return out |
| 496 | } |
| 497 | |
| 498 | // The screen name is entered in the web join flow (and editable later in the |
| 499 | // profile), so adding a chat only needs its link. |
| 500 | func add(url: String) { |
| 501 | let chat = SavedChat(url: url, name: "") |
| 502 | // De-dupe by token so re-adding an instance just re-selects it. |
| 503 | if let i = chats.firstIndex(where: { $0.token != nil && $0.token == chat.token }) { |
| 504 | selection = chats[i].id |
| 505 | } else if let origin = chat.origin, let i = chats.firstIndex(where: { $0.origin == origin }) { |
| 506 | // Same server, different link: you're already connected, so open what |
| 507 | // you have instead of adding a second copy — the webview's keys are |
| 508 | // per-origin, so a duplicate would just mirror the identical session |
| 509 | // (and clutter the rail + ⌘K with twins). If the saved entry never got |
| 510 | // a session (its old invite may be spent), adopt the fresh link so the |
| 511 | // join can succeed — the webview only replays a join link when the |
| 512 | // origin holds no session, so a working login is never disturbed. |
| 513 | if chats[i].session == nil { chats[i].url = url } |
| 514 | selection = chats[i].id |
| 515 | } else { |
| 516 | chats.append(chat) |
| 517 | selection = chat.id |
| 518 | } |
| 519 | MacChatsStore.save(chats) |
| 520 | } |
| 521 | |
| 522 | func remove(_ chat: SavedChat) { |
| 523 | chats.removeAll { $0.id == chat.id } |
| 524 | if selection == chat.id { selection = chats.first?.id } |
| 525 | MacChatsStore.save(chats) |
| 526 | // Signing out must not strand the chat's private key in the Keychain. |
| 527 | if let origin = chat.origin?.absoluteString, |
| 528 | instances.contains(where: { $0.origin == origin }) { |
| 529 | instances.removeAll { $0.origin == origin } |
| 530 | InstancesStore.save(instances) |
| 531 | Logger.identity.info("removed native identity for \(origin, privacy: .public)") |
| 532 | syncHome() |
| 533 | } |
| 534 | } |
| 535 | |
| 536 | // ---- home-vault sync ---------------------------------------------------- |
| 537 | |
| 538 | /// Instances in RAIL order (`chats` drives the rail; identities without a |
| 539 | /// rail entry tail in their stored order) — the order the vault should hold. |
| 540 | func instancesInRailOrder() -> [SavedInstance] { |
| 541 | var rest = instances |
| 542 | var out: [SavedInstance] = [] |
| 543 | for chat in chats { |
| 544 | guard let origin = chat.origin?.absoluteString, |
| 545 | let i = rest.firstIndex(where: { $0.origin == origin }) else { continue } |
| 546 | out.append(rest.remove(at: i)) |
| 547 | } |
| 548 | return out + rest |
| 549 | } |
| 550 | |
| 551 | /// Push the rail's order + stars to the home vault. DORMANT until Mac |
| 552 | /// sign-in ships: the Keychain session is per-app, and the Mac has no |
| 553 | /// sign-in entry point yet (needs the webcredentials entitlement — a real |
| 554 | /// provisioning profile + this Mac registered — and the macOS 15 PRF API). |
| 555 | /// Wired now so starring works locally and syncs the moment sign-in lands; |
| 556 | /// until then Mac stars live on this device only (iOS-first, deliberately). |
| 557 | func syncHome() { HomeSync.pushSoon(instances: instancesInRailOrder()) } |
| 558 | |
| 559 | /// The silent vault pull (app activation): stars/archive/order made on the |
| 560 | /// home page or another device land here without a re-sign-in. applyVault |
| 561 | /// is the same vault-wins merge sign-in uses. |
| 562 | func pullHome() { |
| 563 | Task { @MainActor in |
| 564 | if let contents = await HomeSync.pull() { |
| 565 | _ = applyVault(contents.servers, removed: contents.removed) |
| 566 | } |
| 567 | } |
| 568 | } |
| 569 | |
| 570 | /// Apply home-page removals: drop any instance whose vault tombstone is |
| 571 | /// newer than when this Mac gained it — AND its rail entry, because a |
| 572 | /// lingering SavedChat would re-extract the webview's identity on next |
| 573 | /// open (noteIdentity stamps addedAt=now) and resurrect the space. Chats |
| 574 | /// with no native identity fall to the same rule (no addedAt to defend |
| 575 | /// them — the account says the space is gone). |
| 576 | func dropTombstoned(_ removed: [HomeVault.Tombstone]?) { |
| 577 | guard let removed, !removed.isEmpty else { return } |
| 578 | var dropped = false |
| 579 | instances.removeAll { inst in |
| 580 | let gone = HomeVault.tombstonedAt(removed, url: inst.origin) > (inst.addedAt ?? 0) |
| 581 | if gone { dropped = true } |
| 582 | return gone |
| 583 | } |
| 584 | chats.removeAll { chat in |
| 585 | guard let origin = chat.origin?.absoluteString, |
| 586 | HomeVault.tombstonedAt(removed, url: origin) > 0, |
| 587 | !instances.contains(where: { $0.origin == origin }) else { return false } |
| 588 | dropped = true |
| 589 | return true |
| 590 | } |
| 591 | guard dropped else { return } |
| 592 | InstancesStore.save(instances) |
| 593 | MacChatsStore.save(chats) |
| 594 | if let sel = selection, !chats.contains(where: { $0.id == sel }) { |
| 595 | selection = chats.first?.id |
| 596 | } |
| 597 | } |
| 598 | |
| 599 | /// Sign-in merge — the vault wins: upsert each vault server's identity + |
| 600 | /// star, ensure a rail entry (SavedChat) exists, and apply the vault's |
| 601 | /// order to the rail (Mac-only chats tail). Returns how many servers were |
| 602 | /// NEW to this Mac. The caller pushes after, so the write-back reflects |
| 603 | /// the merged state (the iOS data-loss lesson). |
| 604 | func applyVault(_ servers: [HomeVault.Server], removed: [HomeVault.Tombstone]? = nil) -> Int { |
| 605 | dropTombstoned(removed) |
| 606 | var added = 0 |
| 607 | for s in servers { |
| 608 | guard let creds = s.credentials else { continue } // bookmark entry |
| 609 | // Entry + tombstone at once = a stale client re-pushed a removed |
| 610 | // space; upserting it would re-arm it here (and a fresh addedAt |
| 611 | // would clear the tombstone on push). Let the vault heal instead. |
| 612 | guard HomeVault.tombstonedAt(removed, url: s.url) == 0 else { continue } |
| 613 | var inst = SavedInstance(origin: s.url, deviceToken: creds.token, |
| 614 | screenName: creds.name ?? s.name ?? "", |
| 615 | userPub: creds.userPub, userPriv: creds.userPriv, |
| 616 | groupName: s.name ?? "", |
| 617 | starred: s.isStarred ? true : nil, |
| 618 | archived: s.isArchived ? true : nil) |
| 619 | if let i = instances.firstIndex(where: { $0.origin == s.url }) { |
| 620 | inst.myUserId = instances[i].myUserId |
| 621 | if inst.groupName.isEmpty { inst.groupName = instances[i].groupName } |
| 622 | inst.addedAt = instances[i].addedAt |
| 623 | instances[i] = inst |
| 624 | } else { |
| 625 | inst.addedAt = Date().timeIntervalSince1970 * 1000 |
| 626 | instances.append(inst) |
| 627 | } |
| 628 | if !chats.contains(where: { $0.origin?.absoluteString == s.url }) { |
| 629 | chats.append(SavedChat(url: s.url, name: creds.name ?? "")) |
| 630 | added += 1 |
| 631 | } |
| 632 | } |
| 633 | // Vault order drives the rail; Mac-only chats keep their relative order |
| 634 | // at the end. |
| 635 | var rest = chats |
| 636 | var ordered: [SavedChat] = [] |
| 637 | for s in servers { |
| 638 | if let i = rest.firstIndex(where: { $0.origin?.absoluteString == s.url }) { |
| 639 | ordered.append(rest.remove(at: i)) |
| 640 | } |
| 641 | } |
| 642 | chats = ordered + rest |
| 643 | InstancesStore.save(instances) |
| 644 | MacChatsStore.save(chats) |
| 645 | if selection == nil { selection = chats.first?.id } |
| 646 | return added |
| 647 | } |
| 648 | |
| 649 | /// A single natively-created identity (the create-a-space claim): upsert |
| 650 | /// the SavedInstance, ensure a rail entry, select it, and push the vault — |
| 651 | /// applyVault's one-server sibling for a space born on this Mac. |
| 652 | func addInstance(_ inst: SavedInstance) { |
| 653 | if let i = instances.firstIndex(where: { $0.origin == inst.origin }) { |
| 654 | instances[i] = inst |
| 655 | } else { |
| 656 | instances.append(inst) |
| 657 | } |
| 658 | InstancesStore.save(instances) |
| 659 | if !chats.contains(where: { $0.origin?.absoluteString == inst.origin }) { |
| 660 | chats.append(SavedChat(url: inst.origin, name: inst.screenName)) |
| 661 | MacChatsStore.save(chats) |
| 662 | } |
| 663 | selection = chats.first(where: { $0.origin?.absoluteString == inst.origin })?.id |
| 664 | syncHome() |
| 665 | } |
| 666 | |
| 667 | // ---- starring (rail = stars only; the rest fold under "More") ---------- |
| 668 | |
| 669 | /// Star state lives on the shared SavedInstance (the same record iOS uses and |
| 670 | /// the home vault syncs) — a chat is starred iff its native identity is. |
| 671 | func isStarred(_ chat: SavedChat) -> Bool { |
| 672 | guard let origin = chat.origin?.absoluteString else { return false } |
| 673 | return instances.first { $0.origin == origin }?.isStarred ?? false |
| 674 | } |
| 675 | |
| 676 | /// A chat can be starred once its native identity exists (extracted on first |
| 677 | /// open). Before that there's nothing durable to pin the flag to. |
| 678 | func canStar(_ chat: SavedChat) -> Bool { |
| 679 | guard let origin = chat.origin?.absoluteString else { return false } |
| 680 | return instances.contains { $0.origin == origin } |
| 681 | } |
| 682 | |
| 683 | /// Star or unstar a chat: flip the flag on its SavedInstance and reposition |
| 684 | /// BOTH lists with the vault's toggleStar semantics (star → end of the starred |
| 685 | /// group, unstar → top of the rest), so the rail, iOS, and home stay in step. |
| 686 | func toggleStar(_ chat: SavedChat) { |
| 687 | guard let origin = chat.origin?.absoluteString, |
| 688 | let i = instances.firstIndex(where: { $0.origin == origin }) else { return } |
| 689 | var flipped = instances[i] |
| 690 | flipped.starred = flipped.isStarred ? nil : true |
| 691 | let starredInst = instances.filter { $0.origin != origin && $0.isStarred } |
| 692 | let otherInst = instances.filter { $0.origin != origin && !$0.isStarred } |
| 693 | instances = starredInst + [flipped] + otherInst |
| 694 | InstancesStore.save(instances) |
| 695 | // The rail renders from `chats` — mirror the same boundary move there. |
| 696 | // (isStarred reads the just-updated instances, so partitioning is fresh.) |
| 697 | if let j = chats.firstIndex(where: { $0.id == chat.id }) { |
| 698 | let moved = chats.remove(at: j) |
| 699 | let starredChats = chats.filter { isStarred($0) } |
| 700 | let otherChats = chats.filter { !isStarred($0) } |
| 701 | chats = starredChats + [moved] + otherChats |
| 702 | MacChatsStore.save(chats) |
| 703 | } |
| 704 | syncHome() |
| 705 | } |
| 706 | |
| 707 | /// Archived: hidden from the rail and the overflow list, reachable via the |
| 708 | /// "…" menu's Archived group. Same identity-flag shape as starring (and |
| 709 | /// synced to the vault the same way). |
| 710 | func isArchived(_ chat: SavedChat) -> Bool { |
| 711 | guard let origin = chat.origin?.absoluteString else { return false } |
| 712 | return instances.first { $0.origin == origin }?.isArchived ?? false |
| 713 | } |
| 714 | |
| 715 | /// Archive or unarchive a chat, repositioning BOTH lists with the vault's |
| 716 | /// setArchived semantics (archive → drop the star, top of the archived |
| 717 | /// group; unarchive → bottom of the active list — both the active/archived |
| 718 | /// boundary), so the rail, iOS, and home stay in step. |
| 719 | func toggleArchive(_ chat: SavedChat) { |
| 720 | guard let origin = chat.origin?.absoluteString, |
| 721 | let i = instances.firstIndex(where: { $0.origin == origin }) else { return } |
| 722 | var flipped = instances[i] |
| 723 | let on = !flipped.isArchived |
| 724 | flipped.archived = on ? true : nil |
| 725 | if on { flipped.starred = nil } // leaving the rail |
| 726 | let starredInst = instances.filter { $0.origin != origin && $0.isStarred && !$0.isArchived } |
| 727 | let otherInst = instances.filter { $0.origin != origin && !$0.isStarred && !$0.isArchived } |
| 728 | let archivedInst = instances.filter { $0.origin != origin && $0.isArchived } |
| 729 | instances = starredInst + otherInst + [flipped] + archivedInst |
| 730 | InstancesStore.save(instances) |
| 731 | // The rail renders from `chats` — mirror the same boundary move there. |
| 732 | // (isArchived reads the just-updated instances, so partitioning is fresh.) |
| 733 | if let j = chats.firstIndex(where: { $0.id == chat.id }) { |
| 734 | let moved = chats.remove(at: j) |
| 735 | let activeChats = chats.filter { !isArchived($0) } |
| 736 | let archivedChats = chats.filter { isArchived($0) } |
| 737 | chats = activeChats + [moved] + archivedChats |
| 738 | MacChatsStore.save(chats) |
| 739 | } |
| 740 | syncHome() |
| 741 | } |
| 742 | |
| 743 | // Live-reorder the rail during a drag: pull the dragged chat out and reinsert it |
| 744 | // at the hovered chat's slot. Call persistChats() when the drop lands. |
| 745 | func reorder(_ dragging: SavedChat, over target: SavedChat) { |
| 746 | guard dragging.id != target.id, |
| 747 | let from = chats.firstIndex(where: { $0.id == dragging.id }), |
| 748 | let to = chats.firstIndex(where: { $0.id == target.id }) else { return } |
| 749 | let item = chats.remove(at: from) |
| 750 | chats.insert(item, at: to) |
| 751 | } |
| 752 | |
| 753 | func persistChats() { |
| 754 | MacChatsStore.save(chats) |
| 755 | syncHome() |
| 756 | } |
| 757 | |
| 758 | // Native appearance follows the web feed's light/dark: each webview reports its |
| 759 | // effective mode (setAppearance), and the *selected* instance's mode drives the |
| 760 | // whole app (rail, palette, title bar) so the chrome matches what's on screen. |
| 761 | private var appearanceMode: [String: String] = [:] // "light" | "dark" | "system" |
| 762 | |
| 763 | func setAppearance(mode: String, for id: String) { |
| 764 | appearanceMode[id] = mode |
| 765 | if id == selection { applyAppearance() } |
| 766 | } |
| 767 | |
| 768 | private func applyAppearance() { |
| 769 | guard let sel = selection, let mode = appearanceMode[sel] else { return } |
| 770 | // "system" must UNPIN (nil = follow macOS): the webview's |
| 771 | // prefers-color-scheme reads NSApp.appearance, so a pinned value here is |
| 772 | // what the page's "follow my device" resolves against — pinning dark once |
| 773 | // would make system mode stick dark forever. |
| 774 | NSApp.appearance = mode == "system" ? nil : NSAppearance(named: mode == "dark" ? .darkAqua : .aqua) |
| 775 | } |
| 776 | } |
| 777 | |
| 778 | // The Mac scaffold persists its server list to a JSON file in Application Support |
| 779 | // rather than the Keychain. Ad-hoc code signing (no identity on this machine) |
| 780 | // re-signs on every rebuild, which invalidates the Keychain item's ACL and makes |
| 781 | // macOS re-prompt for access on each launch. A file avoids that. Acceptable |
| 782 | // trade-off here: the app is non-sandboxed + ad-hoc, the real session keys already |
| 783 | // live in the webview's own on-disk store, and the saved invite URLs are new-format |
| 784 | // one-time secrets that are spent after joining. A ship build with a real signing |
| 785 | // identity should switch back to the Keychain (ChatsStore). |
| 786 | enum MacChatsStore { |
| 787 | private static var base: URL { |
| 788 | let dir = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0] |
| 789 | .appendingPathComponent("lchat", isDirectory: true) |
| 790 | try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) |
| 791 | return dir |
| 792 | } |
| 793 | private static var fileURL: URL { base.appendingPathComponent("servers.json") } |
| 794 | private static var recentURL: URL { base.appendingPathComponent("recent.json") } |
| 795 | |
| 796 | static func load() -> [SavedChat] { |
| 797 | guard let data = try? Data(contentsOf: fileURL) else { return [] } |
| 798 | return (try? JSONDecoder().decode([SavedChat].self, from: data)) ?? [] |
| 799 | } |
| 800 | |
| 801 | static func save(_ chats: [SavedChat]) { |
| 802 | guard let data = try? JSONEncoder().encode(chats) else { return } |
| 803 | try? data.write(to: fileURL, options: .atomic) |
| 804 | } |
| 805 | |
| 806 | // Recency list for the ⌘K palette (most-recent-first chat ids). Stored beside |
| 807 | // servers.json — the ids are the same invite URLs already persisted there. |
| 808 | static func loadRecent() -> [String] { |
| 809 | guard let data = try? Data(contentsOf: recentURL) else { return [] } |
| 810 | return (try? JSONDecoder().decode([String].self, from: data)) ?? [] |
| 811 | } |
| 812 | |
| 813 | static func saveRecent(_ ids: [String]) { |
| 814 | guard let data = try? JSONEncoder().encode(ids) else { return } |
| 815 | try? data.write(to: recentURL, options: .atomic) |
| 816 | } |
| 817 | } |
| 818 | |