eleven / messenger Public

Clone
git clone https://amadan.net/eleven/messenger

Plain git — no account needed to clone.

Download

Download this file

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