import LChatCore import SwiftUI import AppKit import WebKit import UserNotifications import Sparkle import os // Verification tap for the native-identity store (log stream --predicate // 'subsystem == "com.elevenmessenger.mac"'). Names, never keys. extension Logger { static let identity = Logger(subsystem: "com.elevenmessenger.mac", category: "identity") } // A genuinely native macOS app — NOT Mac Catalyst. The window, sidebar, toolbar // and menu bar are real AppKit-backed SwiftUI, so scrolling, the title bar and the // menu bar feel like a Mac app instead of an iPad app in a window. // // Fully native: the feed, composer and crypto all run in Swift (LChatCore). // The only WKWebViews left are SCOPED — mini-app panels (AppThreadWebView) and // nothing else; the full-frame web fallback (and its paste-a-link join) is // gone. Entry is by signing in with Eleven; identities ride the vault. @main struct LChatMacApp: App { @NSApplicationDelegateAdaptor(AppDelegate.self) private var appDelegate @StateObject private var app = MacAppState() // Observed here only so the View-menu items' enabled state tracks the pref. @AppStorage(ChatTextSize.key) private var chatTextSize = ChatTextSize.defaultSize init() { // Match the web feed's text rendering: style.css sets // -webkit-font-smoothing: antialiased, which turns OFF macOS's // stroke-dilating font smoothing — AppKit leaves it on, so the same // SF glyphs render visibly heavier in native text than in the // webview. This is the app-wide equivalent of that CSS. UserDefaults.standard.set(0, forKey: "AppleFontSmoothing") // Sockets heartbeat "active" while the app is frontmost (presence + // push suppression) — wired per platform because LChatCore can't see AppKit. ChatSocket.appIsActive = { NSApp.isActive } #if DEBUG // Unread flips land in the Debug Events windows beside the frames // that did (or didn't) cause them (ThreadDebug.swift). ThreadEventLog.installStoreTaps() #endif } var body: some Scene { // Window, NOT WindowGroup: the root surface is one window, full stop — // WindowGroup let `open`/URL callbacks and reopen events spawn extra // copies of the whole app UI. Windows for breaking specific features // out (a lightbox, an app) can be their own scenes later. Window("Eleven", id: "main") { RootView() .environmentObject(app) .frame(minWidth: 820, minHeight: 560) .onAppear { appDelegate.appState = app } .onOpenURL { url in // The browser sign-in handoff (elevenmessenger:// // home-session#…): claimed first, always. if MacHomeSignIn.handleCallback(url, into: app) { NSApp.activate(ignoringOtherApps: true) return } // The join page's "Open in the app" (issue #1089's // handoff cousin): elevenmessenger://add?url=. // Validated here, then PRE-FILLS the Add-from-link sheet // rather than joining — one confirming click, with the // link visible, for any URL that arrived from outside. if url.host == "add", let link = URLComponents(url: url, resolvingAgainstBaseURL: false)? .queryItems?.first(where: { $0.name == "url" })?.value, parseJoinLink(link) != nil { app.pendingAddLink = link NSApp.activate(ignoringOtherApps: true) } } } // Hide the title bar so the feed runs to the top; the web header is made // draggable via an injected script (see ChatFeedWebView), and the top of the // rail drags via the system title-bar region. No title, toolbar, or toggle. .windowStyle(.hiddenTitleBar) .defaultSize(width: 1160, height: 820) .commands { CommandGroup(replacing: .newItem) { // File → New Space: the goes-to-eleven create flow (the rail's // "+"). ⇧⌘N, the new-container idiom. The Sidebar owns the // sheet; it opens on the tick. Button("New space") { app.requestCreateSpace() } .keyboardShortcut("n", modifiers: [.command, .shift]) .disabled(app.instances.isEmpty) } CommandGroup(after: .newItem) { // A MENU shortcut, deliberately: a view-level hidden button // lost ⌘F whenever a greedy first responder (a mini-app's // WKWebView, a text view) swallowed the key equivalent — menu // items win the same way ⌘C does. Button("Find Chat…") { app.focusSearchTick += 1 } .keyboardShortcut("f", modifiers: .command) // ⌘[ / ⌘] step through the chat list (Slack's ⌥↑/↓, in the // bracket idiom Paul asked for). Ticks, not toggles — each // press must fire even when the direction repeats. Button("Previous Chat") { app.cycleChatTick -= 1 } .keyboardShortcut("[", modifiers: .command) Button("Next Chat") { app.cycleChatTick += 1 } .keyboardShortcut("]", modifiers: .command) } // View → Make Text Bigger/Smaller (Messages' menu), stepping the // same ladder as the Settings slider and the web's. The menu key // equivalent is "+", which strictly means ⌘⇧=; AppDelegate's key // monitor also maps the unshifted ⌘= press — what "cmd and plus" // physically is on most keyboards — like Messages/Safari accept. CommandGroup(before: .toolbar) { Button("Make Text Bigger") { ChatTextSize.bump(+1) } .keyboardShortcut("+", modifiers: .command) .disabled(ChatTextSize.snap(chatTextSize) >= ChatTextSize.stops.last!) Button("Make Text Smaller") { ChatTextSize.bump(-1) } .keyboardShortcut("-", modifiers: .command) .disabled(ChatTextSize.snap(chatTextSize) <= ChatTextSize.stops.first!) Button("Default Text Size") { ChatTextSize.reset() } .keyboardShortcut("0", modifiers: .command) Divider() } // The keyboard's two message verbs (issue #392), the web feed's // ⌘R / ⌘T. Menu items for the same reason ⌘F is one: the composer // is a real NSTextView and a mini-app pane is a WKWebView, and // either would swallow a view-level key equivalent — a menu item // wins first, the way ⌘C does. CommandMenu("Message") { Button("Reply to Latest Message") { app.replyLatestTick += 1 } .keyboardShortcut("r", modifiers: .command) Button("React to Latest Message") { app.reactLatestTick += 1 } .keyboardShortcut("t", modifiers: .command) } // ⌘1…⌘9 jump straight to a space, like browser/Slack tabs. The // menu mirrors the rail: favourites (else the first nine active), // the rest under More, and the two ways a space arrives. CommandMenu("Spaces") { Button("Quick switch…") { app.showPalette = true } .keyboardShortcut("k", modifiers: .command) Divider() ForEach(Array(app.menuSpaces.enumerated()), id: \.element.id) { index, chat in Button(app.serverName(chat)) { app.selection = chat.id } .keyboardShortcut(KeyEquivalent(Character("\(index + 1)")), modifiers: .command) } if !app.menuOverflow.isEmpty { Menu("More") { ForEach(app.menuOverflow) { chat in Button(app.serverName(chat)) { app.selection = chat.id } } } } Divider() Button("Create a space") { app.requestCreateSpace() } Button("Add from link…") { app.requestAddFromLink() } } // Our own About item, so the standard panel can carry the git SHA // the build was stamped with (BuildInfo). Same position and title // as the one SwiftUI provides — it just opens the panel with // options. CommandGroup(replacing: .appInfo) { Button("About \(BuildInfo.appName)") { BuildInfo.showAboutPanel() } } // Sits right below "About Eleven" in the app menu. CommandGroup(after: .appInfo) { CheckForUpdatesView(updater: appDelegate.updaterController.updater) } #if DEBUG // Dev builds only: the client-wide event log — every WebSocket // frame from every mounted space (ThreadDebug.swift). The // per-thread view lives in the thread context menu. CommandMenu("Debug") { Button("All Received Events") { ThreadDebugWindows.showAll() } } #endif } Settings { TabView { MacSettingsView() .tabItem { Label("General", systemImage: "gearshape") } UpdatesSettingsView(updater: appDelegate.updaterController.updater) .tabItem { Label("Updates", systemImage: "arrow.down.circle") } MacAdvancedSettingsView() .tabItem { Label("Advanced", systemImage: "wrench.and.screwdriver") } } .environmentObject(app) // ONE fixed frame for the whole Settings window, here on the // TabView — per-pane frames made the window resize on every tab // switch (and shrink-and-stick after visiting the short Updates // pane). Panes size to fill; a grouped Form scrolls if it must. .frame(width: 600, height: 560) } } } // Owns notification authorization + delivery. Local notifications only (no APNs / // no paid account): chat.js posts a decrypted preview via the `lchatNotify` bridge, // we display it, and a tap jumps to that instance. final class AppDelegate: NSObject, NSApplicationDelegate, UNUserNotificationCenterDelegate { weak var appState: MacAppState? let updaterController = SPUStandardUpdaterController( startingUpdater: true, updaterDelegate: nil, userDriverDelegate: nil) // Every activation pulls the vault — switching back from the browser or // another Mac is exactly when a home-page change is freshest. func applicationDidBecomeActive(_ notification: Notification) { appState?.pullHome() } func applicationDidFinishLaunching(_ notification: Notification) { ClickLab.start() // Signposts + (consent-gated) perf recording, shared with iOS (Perf.swift). Perf.install() // The DEK-sync migrate-by-addition moment (#1089, flag-gated): an // existing signed-in install adds the synchronizable DEK item on its // first unlocked launch — write-gated on the account holding a SiwA // anchor; a no-op for everyone else. Task { await DEKSync.writeIfEligible() } // "cmd and plus": the View menu's ⌘+ equivalent strictly needs the // shifted key (⌘⇧=), but people press ⌘= and expect bigger text — // Messages and Safari both accept it, so map it here. (⌘− needs no // help; "-" is unshifted already.) NSEvent.addLocalMonitorForEvents(matching: .keyDown) { event in guard event.modifierFlags.intersection(.deviceIndependentFlagsMask) == .command, event.charactersIgnoringModifiers == "=" else { return event } ChatTextSize.bump(+1) return nil } let center = UNUserNotificationCenter.current() center.delegate = self center.requestAuthorization(options: [.alert, .sound]) { _, _ in } } // Show the banner even when Eleven is frontmost — the web layer already dropped // the one chat you're actively reading, so anything that reaches here is wanted. func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { completionHandler([.banner, .sound]) } // Tapping a notification brings Eleven forward and selects the message's instance. func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { let id = response.notification.request.content.userInfo["instance"] as? String DispatchQueue.main.async { NSApp.activate(ignoringOtherApps: true) if let id { self.appState?.selection = id } } completionHandler() } } // The saved chats (each a separate lchat instance) and which one is selected. // Mirrors the iOS AppState, trimmed to what the Mac shell needs. final class MacAppState: ObservableObject { @Published var chats: [SavedChat] @Published var showPalette = false // Fetched group names (chat id -> name), shared by the rail and the ⌘K palette. @Published var names: [String: String] = [:] // Fetched per-instance server photos (chat id -> image). Public branding served // in the clear at /api/server-avatar; the rail shows it instead of the initial // when set. Only populated for instances whose /api/group reports one. @Published var avatars: [String: NSImage] = [:] // Chat ids, most-recently-selected first — drives the ⌘K palette order. The rail // keeps its own manual (drag-reorderable) order in `chats`. @Published var recent: [String] = [] // Native identities, keyed by origin ({token, name, keypair}), parked in // the Keychain (InstancesStore) — arriving via the vault (sign-in + // foreground pulls); everything native reads from here. @Published private(set) var instances: [SavedInstance] // The photo / video the lightbox is showing (nil = closed). App-level state // because the overlay must cover the whole window, not the pane that // spawned it. @Published var lightbox: LightboxItem? @Published var videoLightbox: VideoLightboxItem? @Published var youtubeLightbox: YouTubeLightboxItem? // The ⌘K bridge for the NATIVE surface: the active NativeChatView publishes // its thread list here (the webview's lchatPaletteItems equivalent), and // the palette requests a thread by writing nativeOpenThread, which the // active NativeChatView consumes. @Published var nativeChats: [NativePaletteChat] = [] // Bumped by File ▸ Find Chat (⌘F) — the active surface focuses its search. @Published var focusSearchTick = 0 // ⌘[ / ⌘] chat cycling: the SIGN of each change is the direction (the // counter moves ±1), and any change is one step — the active NativeChatView // observes it. @Published var cycleChatTick = 0 // Message ▸ Reply to / React to Latest Message (⌘R / ⌘T, issue #392). // Ticks like the two above — pressing the same shortcut twice must fire // twice — consumed by whichever native feed is on screen. @Published var replyLatestTick = 0 @Published var reactLatestTick = 0 // File → New Space (and anything else app-level) asks for the create flow // by bumping this; RootView owns the takeover and opens on the tick. @Published var createSpaceTick = 0 // Spaces → Add from link…: RootView owns the paste sheet. @Published var addFromLinkTick = 0 // A join/add-device link handed over by the browser (the join page's // "Open in the app" → elevenmessenger://add?url=…). Pre-fills the // Add-from-link sheet — the sheet IS the confirming click; a URL arriving // from outside the app must never join silently. Consumed on sheet appear. @Published var pendingAddLink: String? // Context for the sheet when a rung opens it (the locked pane's "Link // from Your iPhone…" / "Ask for a New Invite…") — replaces the sheet's // generic subtitle for that one presentation. Consumed on sheet appear. @Published var addFromLinkHint: String? func requestCreateSpace() { createSpaceTick += 1 } func requestAddFromLink(hint: String? = nil) { addFromLinkHint = hint addFromLinkTick += 1 } // The Spaces menu's rail mirror: favourites when any exist, else the first // nine active spaces (⌘1…⌘9 follow this order); the rest fold under More. var menuSpaces: [SavedChat] { let active = chats.filter { !isArchived($0) } let starred = active.filter { isStarred($0) } return starred.isEmpty ? Array(active.prefix(9)) : Array(starred.prefix(9)) } var menuOverflow: [SavedChat] { let active = chats.filter { !isArchived($0) } let shown = Set(menuSpaces.map(\.id)) return active.filter { !shown.contains($0.id) } } // A "open this thread AND land on this message" request (search hits): // the matching feed consumes it once its history contains the target. @Published var nativeJump: NativeJumpTarget? struct NativeJumpTarget: Equatable { let thread: String let message: Int64 } var nativeChatsOwner: String? // instance id, so a deactivating view only clears its own rows @Published var nativeOpenThread: String? struct NativePaletteChat { let id: String let title: String let glyph: String? let avatar: AvatarSource? // the chat's real photo, when we hold the key var appId: String? = nil // set for app-threads — drives the identity mark } // Selecting a chat records it as most-recently-accessed (for the palette). @Published var selection: SavedChat.ID? { didSet { guard let s = selection, s != oldValue else { return } recent.removeAll { $0 == s } recent.insert(s, at: 0) MacChatsStore.saveRecent(recent) applyAppearance() } } init() { chats = MacChatsStore.load() recent = MacChatsStore.loadRecent() instances = InstancesStore.load() // Launch into the space last open on this Mac (recent[0] — selection's // didSet keeps it current), falling back to the top of the rail. let chatIDs = Set(chats.map(\.id)) selection = recent.first { chatIDs.contains($0) } ?? chats.first?.id // didSet doesn't fire during init } // Store (or refresh) the native identity for an origin, extracted from the // webview's session. Writes only on change, so the per-page-load extraction // doesn't hammer the Keychain; an unchanged identity keeps its resolved // myUserId/groupName. Signing out removes it (see remove(_:)). func noteIdentity(origin: String, token: String, name: String, userPub: String, userPriv: String) { var inst = SavedInstance(origin: origin, deviceToken: token, screenName: name, userPub: userPub, userPriv: userPriv) if let i = instances.firstIndex(where: { $0.origin == origin }) { inst.myUserId = instances[i].myUserId inst.groupName = instances[i].groupName // Every locally-resolved field must survive the refresh — dropping // one silently reverts it on each page load (starred was cleared // this way, un-starring the space everywhere via the vault sync). inst.starred = instances[i].starred inst.archived = instances[i].archived // Especially addedAt: a page-load extraction is not a deliberate // add, so it must not re-arm the entry against a removal tombstone. inst.addedAt = instances[i].addedAt guard instances[i] != inst else { return } instances[i] = inst } else { // A first extraction IS the join on this Mac — stamp it so the // entry beats any older home-page removal tombstone. inst.addedAt = Date().timeIntervalSince1970 * 1000 instances.append(inst) } InstancesStore.save(instances) Logger.identity.info("stored native identity for \(origin, privacy: .public)") } var selected: SavedChat? { chats.first { $0.id == selection } } // The instance's display name: fetched group name, else the host from the invite // URL (works for new-format links where `session` is nil). func serverName(_ chat: SavedChat) -> String { names[chat.id] ?? chat.origin?.host ?? "Chat" } // A stable hue per instance so its icon colour is the same across launches // (String.hashValue is randomised per process, so roll a small FNV-ish hash). func hue(for id: String) -> Double { var h: UInt64 = 5381 for b in id.utf8 { h = (h &* 33) &+ UInt64(b) } return Double(h % 360) / 360.0 } // Icon initials for the rail + palette. Single-word names get one letter; names // with two or more words get the first letters of the first two words (Campbell // Family → CF, lchat.run.garden → LR). Computed per-instance, independent of the // other chats and their order — so reordering the rail never changes an initial. func initials() -> [String: String] { func words(_ chat: SavedChat) -> [Substring] { serverName(chat).split { !($0.isLetter || $0.isNumber) } } func head(_ w: Substring?) -> String? { w?.first.map { String($0).uppercased() } } var out: [String: String] = [:] for chat in chats { let ws = words(chat) guard let first = head(ws.first) else { out[chat.id] = "?"; continue } out[chat.id] = ws.count >= 2 ? first + (head(ws[1]) ?? "") : first } return out } // The screen name is entered in the web join flow (and editable later in the // profile), so adding a chat only needs its link. func add(url: String) { let chat = SavedChat(url: url, name: "") // De-dupe by token so re-adding an instance just re-selects it. if let i = chats.firstIndex(where: { $0.token != nil && $0.token == chat.token }) { selection = chats[i].id } else if let origin = chat.origin, let i = chats.firstIndex(where: { $0.origin == origin }) { // Same server, different link: you're already connected, so open what // you have instead of adding a second copy — the webview's keys are // per-origin, so a duplicate would just mirror the identical session // (and clutter the rail + ⌘K with twins). If the saved entry never got // a session (its old invite may be spent), adopt the fresh link so the // join can succeed — the webview only replays a join link when the // origin holds no session, so a working login is never disturbed. if chats[i].session == nil { chats[i].url = url } selection = chats[i].id } else { chats.append(chat) selection = chat.id } MacChatsStore.save(chats) } func remove(_ chat: SavedChat) { chats.removeAll { $0.id == chat.id } if selection == chat.id { selection = chats.first?.id } MacChatsStore.save(chats) // Signing out must not strand the chat's private key in the Keychain. if let origin = chat.origin?.absoluteString, instances.contains(where: { $0.origin == origin }) { instances.removeAll { $0.origin == origin } InstancesStore.save(instances) Logger.identity.info("removed native identity for \(origin, privacy: .public)") syncHome() } } // ---- home-vault sync ---------------------------------------------------- /// Instances in RAIL order (`chats` drives the rail; identities without a /// rail entry tail in their stored order) — the order the vault should hold. func instancesInRailOrder() -> [SavedInstance] { var rest = instances var out: [SavedInstance] = [] for chat in chats { guard let origin = chat.origin?.absoluteString, let i = rest.firstIndex(where: { $0.origin == origin }) else { continue } out.append(rest.remove(at: i)) } return out + rest } /// Push the rail's order + stars to the home vault. DORMANT until Mac /// sign-in ships: the Keychain session is per-app, and the Mac has no /// sign-in entry point yet (needs the webcredentials entitlement — a real /// provisioning profile + this Mac registered — and the macOS 15 PRF API). /// Wired now so starring works locally and syncs the moment sign-in lands; /// until then Mac stars live on this device only (iOS-first, deliberately). func syncHome() { HomeSync.pushSoon(instances: instancesInRailOrder()) } /// The silent vault pull (app activation): stars/archive/order made on the /// home page or another device land here without a re-sign-in. applyVault /// is the same vault-wins merge sign-in uses. func pullHome() { Task { @MainActor in if let contents = await HomeSync.pull() { _ = applyVault(contents.servers, removed: contents.removed) } } } /// Apply home-page removals: drop any instance whose vault tombstone is /// newer than when this Mac gained it — AND its rail entry, because a /// lingering SavedChat would re-extract the webview's identity on next /// open (noteIdentity stamps addedAt=now) and resurrect the space. Chats /// with no native identity fall to the same rule (no addedAt to defend /// them — the account says the space is gone). func dropTombstoned(_ removed: [HomeVault.Tombstone]?) { guard let removed, !removed.isEmpty else { return } var dropped = false instances.removeAll { inst in let gone = HomeVault.tombstonedAt(removed, url: inst.origin) > (inst.addedAt ?? 0) if gone { dropped = true } return gone } chats.removeAll { chat in guard let origin = chat.origin?.absoluteString, HomeVault.tombstonedAt(removed, url: origin) > 0, !instances.contains(where: { $0.origin == origin }) else { return false } dropped = true return true } guard dropped else { return } InstancesStore.save(instances) MacChatsStore.save(chats) if let sel = selection, !chats.contains(where: { $0.id == sel }) { selection = chats.first?.id } } /// Sign-in merge — the vault wins: upsert each vault server's identity + /// star, ensure a rail entry (SavedChat) exists, and apply the vault's /// order to the rail (Mac-only chats tail). Returns how many servers were /// NEW to this Mac. The caller pushes after, so the write-back reflects /// the merged state (the iOS data-loss lesson). func applyVault(_ servers: [HomeVault.Server], removed: [HomeVault.Tombstone]? = nil) -> Int { dropTombstoned(removed) var added = 0 for s in servers { guard let creds = s.credentials else { continue } // bookmark entry // Entry + tombstone at once = a stale client re-pushed a removed // space; upserting it would re-arm it here (and a fresh addedAt // would clear the tombstone on push). Let the vault heal instead. guard HomeVault.tombstonedAt(removed, url: s.url) == 0 else { continue } var inst = SavedInstance(origin: s.url, deviceToken: creds.token, screenName: creds.name ?? s.name ?? "", userPub: creds.userPub, userPriv: creds.userPriv, groupName: s.name ?? "", starred: s.isStarred ? true : nil, archived: s.isArchived ? true : nil) if let i = instances.firstIndex(where: { $0.origin == s.url }) { inst.myUserId = instances[i].myUserId if inst.groupName.isEmpty { inst.groupName = instances[i].groupName } inst.addedAt = instances[i].addedAt instances[i] = inst } else { inst.addedAt = Date().timeIntervalSince1970 * 1000 instances.append(inst) } if !chats.contains(where: { $0.origin?.absoluteString == s.url }) { chats.append(SavedChat(url: s.url, name: creds.name ?? "")) added += 1 } } // Vault order drives the rail; Mac-only chats keep their relative order // at the end. var rest = chats var ordered: [SavedChat] = [] for s in servers { if let i = rest.firstIndex(where: { $0.origin?.absoluteString == s.url }) { ordered.append(rest.remove(at: i)) } } chats = ordered + rest InstancesStore.save(instances) MacChatsStore.save(chats) if selection == nil { selection = chats.first?.id } return added } /// A single natively-created identity (the create-a-space claim): upsert /// the SavedInstance, ensure a rail entry, select it, and push the vault — /// applyVault's one-server sibling for a space born on this Mac. func addInstance(_ inst: SavedInstance) { if let i = instances.firstIndex(where: { $0.origin == inst.origin }) { instances[i] = inst } else { instances.append(inst) } InstancesStore.save(instances) if !chats.contains(where: { $0.origin?.absoluteString == inst.origin }) { chats.append(SavedChat(url: inst.origin, name: inst.screenName)) MacChatsStore.save(chats) } selection = chats.first(where: { $0.origin?.absoluteString == inst.origin })?.id syncHome() } // ---- starring (rail = stars only; the rest fold under "More") ---------- /// Star state lives on the shared SavedInstance (the same record iOS uses and /// the home vault syncs) — a chat is starred iff its native identity is. func isStarred(_ chat: SavedChat) -> Bool { guard let origin = chat.origin?.absoluteString else { return false } return instances.first { $0.origin == origin }?.isStarred ?? false } /// A chat can be starred once its native identity exists (extracted on first /// open). Before that there's nothing durable to pin the flag to. func canStar(_ chat: SavedChat) -> Bool { guard let origin = chat.origin?.absoluteString else { return false } return instances.contains { $0.origin == origin } } /// Star or unstar a chat: flip the flag on its SavedInstance and reposition /// BOTH lists with the vault's toggleStar semantics (star → end of the starred /// group, unstar → top of the rest), so the rail, iOS, and home stay in step. func toggleStar(_ chat: SavedChat) { guard let origin = chat.origin?.absoluteString, let i = instances.firstIndex(where: { $0.origin == origin }) else { return } var flipped = instances[i] flipped.starred = flipped.isStarred ? nil : true let starredInst = instances.filter { $0.origin != origin && $0.isStarred } let otherInst = instances.filter { $0.origin != origin && !$0.isStarred } instances = starredInst + [flipped] + otherInst InstancesStore.save(instances) // The rail renders from `chats` — mirror the same boundary move there. // (isStarred reads the just-updated instances, so partitioning is fresh.) if let j = chats.firstIndex(where: { $0.id == chat.id }) { let moved = chats.remove(at: j) let starredChats = chats.filter { isStarred($0) } let otherChats = chats.filter { !isStarred($0) } chats = starredChats + [moved] + otherChats MacChatsStore.save(chats) } syncHome() } /// Archived: hidden from the rail and the overflow list, reachable via the /// "…" menu's Archived group. Same identity-flag shape as starring (and /// synced to the vault the same way). func isArchived(_ chat: SavedChat) -> Bool { guard let origin = chat.origin?.absoluteString else { return false } return instances.first { $0.origin == origin }?.isArchived ?? false } /// Archive or unarchive a chat, repositioning BOTH lists with the vault's /// setArchived semantics (archive → drop the star, top of the archived /// group; unarchive → bottom of the active list — both the active/archived /// boundary), so the rail, iOS, and home stay in step. func toggleArchive(_ chat: SavedChat) { guard let origin = chat.origin?.absoluteString, let i = instances.firstIndex(where: { $0.origin == origin }) else { return } var flipped = instances[i] let on = !flipped.isArchived flipped.archived = on ? true : nil if on { flipped.starred = nil } // leaving the rail let starredInst = instances.filter { $0.origin != origin && $0.isStarred && !$0.isArchived } let otherInst = instances.filter { $0.origin != origin && !$0.isStarred && !$0.isArchived } let archivedInst = instances.filter { $0.origin != origin && $0.isArchived } instances = starredInst + otherInst + [flipped] + archivedInst InstancesStore.save(instances) // The rail renders from `chats` — mirror the same boundary move there. // (isArchived reads the just-updated instances, so partitioning is fresh.) if let j = chats.firstIndex(where: { $0.id == chat.id }) { let moved = chats.remove(at: j) let activeChats = chats.filter { !isArchived($0) } let archivedChats = chats.filter { isArchived($0) } chats = activeChats + [moved] + archivedChats MacChatsStore.save(chats) } syncHome() } // Live-reorder the rail during a drag: pull the dragged chat out and reinsert it // at the hovered chat's slot. Call persistChats() when the drop lands. func reorder(_ dragging: SavedChat, over target: SavedChat) { guard dragging.id != target.id, let from = chats.firstIndex(where: { $0.id == dragging.id }), let to = chats.firstIndex(where: { $0.id == target.id }) else { return } let item = chats.remove(at: from) chats.insert(item, at: to) } func persistChats() { MacChatsStore.save(chats) syncHome() } // Native appearance follows the web feed's light/dark: each webview reports its // effective mode (setAppearance), and the *selected* instance's mode drives the // whole app (rail, palette, title bar) so the chrome matches what's on screen. private var appearanceMode: [String: String] = [:] // "light" | "dark" | "system" func setAppearance(mode: String, for id: String) { appearanceMode[id] = mode if id == selection { applyAppearance() } } private func applyAppearance() { guard let sel = selection, let mode = appearanceMode[sel] else { return } // "system" must UNPIN (nil = follow macOS): the webview's // prefers-color-scheme reads NSApp.appearance, so a pinned value here is // what the page's "follow my device" resolves against — pinning dark once // would make system mode stick dark forever. NSApp.appearance = mode == "system" ? nil : NSAppearance(named: mode == "dark" ? .darkAqua : .aqua) } } // The Mac scaffold persists its server list to a JSON file in Application Support // rather than the Keychain. Ad-hoc code signing (no identity on this machine) // re-signs on every rebuild, which invalidates the Keychain item's ACL and makes // macOS re-prompt for access on each launch. A file avoids that. Acceptable // trade-off here: the app is non-sandboxed + ad-hoc, the real session keys already // live in the webview's own on-disk store, and the saved invite URLs are new-format // one-time secrets that are spent after joining. A ship build with a real signing // identity should switch back to the Keychain (ChatsStore). enum MacChatsStore { private static var base: URL { let dir = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0] .appendingPathComponent("lchat", isDirectory: true) try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) return dir } private static var fileURL: URL { base.appendingPathComponent("servers.json") } private static var recentURL: URL { base.appendingPathComponent("recent.json") } static func load() -> [SavedChat] { guard let data = try? Data(contentsOf: fileURL) else { return [] } return (try? JSONDecoder().decode([SavedChat].self, from: data)) ?? [] } static func save(_ chats: [SavedChat]) { guard let data = try? JSONEncoder().encode(chats) else { return } try? data.write(to: fileURL, options: .atomic) } // Recency list for the ⌘K palette (most-recent-first chat ids). Stored beside // servers.json — the ids are the same invite URLs already persisted there. static func loadRecent() -> [String] { guard let data = try? Data(contentsOf: recentURL) else { return [] } return (try? JSONDecoder().decode([String].self, from: data)) ?? [] } static func saveRecent(_ ids: [String]) { guard let data = try? JSONEncoder().encode(ids) else { return } try? data.write(to: recentURL, options: .atomic) } }