import SwiftUI import WebKit import AuthenticationServices import UniformTypeIdentifiers import BucksleyKit import BucksleyUI struct SettingsScreen: View { @Environment(AppModel.self) private var model @Environment(\.palette) private var palette @EnvironmentObject private var updates: AppUpdates @Environment(\.openURL) private var openURL @AppStorage(BucksleyTheme.preferenceKey) private var themeRaw = BucksleyTheme.defaultPreference.rawValue @AppStorage(BucksleyAppearance.preferenceKey) private var appearanceRaw = BucksleyAppearance.system.rawValue @State private var simplefinToken = "" @State private var plaidClientID = "" @State private var plaidSecret = "" @State private var plaidEnvironment = Plaid.Environment.production @State private var plaidLinkToken: String? @State private var claudeKey = "" @State private var openAIKey = "" @State private var working: String? @State private var importing = false @State private var coinbaseName = "" @State private var coinbaseSecret = "" @State private var coinbaseSignInReady = false var body: some View { @Bindable var model = model let ws = model.workspace ScreenScaffold("Settings") { EmptyView() } content: { VStack(alignment: .leading, spacing: 24) { appearance connections(ws) ask(ws) sync(ws) yourData support about } .frame(maxWidth: 760, alignment: .leading) .frame(maxWidth: .infinity, alignment: .leading) } .fileImporter(isPresented: $importing, allowedContentTypes: [.commaSeparatedText, .plainText]) { result in importCSV(result) } .onChange(of: model.wantsCSVImport, initial: true) { _, wants in if wants { importing = true; model.wantsCSVImport = false } } .sheet(item: Binding(get: { plaidLinkToken.map { LinkToken(token: $0) } }, set: { plaidLinkToken = $0?.token })) { link in PlaidLinkSheet(token: link.token) { publicToken, institution in plaidLinkToken = nil guard let publicToken else { return } run("Connecting \(institution ?? "your bank")…") { _ = try await BankSync(store: model.store).connectPlaid(publicToken: publicToken, institution: institution ?? "Bank", environment: plaidEnvironment) } } } } // MARK: Appearance var appearance: some View { VStack(alignment: .leading, spacing: 10) { SectionHeader("Appearance") ForEach(BucksleyTheme.allCases) { theme in Button { themeRaw = theme.rawValue } label: { HStack(spacing: 12) { HStack(spacing: 4) { ThemeSwatch(theme: theme, dark: false); ThemeSwatch(theme: theme, dark: true) } VStack(alignment: .leading, spacing: 2) { HStack(spacing: 6) { Text(theme.title).font(.system(size: 13, weight: .semibold)) if theme == .afterhours { Text("Default").font(.system(size: 10, weight: .bold)).foregroundStyle(palette.muted) } } Text(theme.summary + ". The app icon follows.").font(.system(size: 12)).foregroundStyle(palette.muted) } Spacer() Image(nsImage: NSImage(named: theme.iconName ?? "AppIconImage") ?? NSImage()).resizable().frame(width: 28, height: 28) if themeRaw == theme.rawValue { Image(systemName: "checkmark.circle.fill").foregroundStyle(palette.accent).font(.system(size: 16)) } } .padding(10) .background(palette.card, in: RoundedRectangle(cornerRadius: 10)) .overlay { RoundedRectangle(cornerRadius: 10).strokeBorder(themeRaw == theme.rawValue ? palette.accent : .clear, lineWidth: 1.5) } .contentShape(Rectangle()) } .buttonStyle(.plain) .accessibilityAddTraits(themeRaw == theme.rawValue ? .isSelected : []) .accessibilityIdentifier("theme.\(theme.rawValue)") } HStack { Text("Appearance Mode").font(.system(size: 13)).frame(width: 130, alignment: .leading) PillPicker(BucksleyAppearance.allCases.map { ($0.rawValue, $0.title) }, selection: $appearanceRaw).fixedSize() .accessibilityIdentifier("settingsAppearanceModePicker") } } } // MARK: Connections func connections(_ ws: Workspace) -> some View { VStack(alignment: .leading, spacing: 12) { SectionHeader("Connections") { if let working { HStack(spacing: 6) { ProgressView().controlSize(.small); Text(working).font(.system(size: 12)) } } } Text("Bank sync runs on this Mac only, straight to your bank's data provider with your own credentials. Credentials stay in your Keychain.") .font(.system(size: 12)).foregroundStyle(palette.muted).fixedSize(horizontal: false, vertical: true) ForEach(ws.connections) { c in HStack(spacing: 10) { Image(systemName: icon(c.kind)).frame(width: 22) VStack(alignment: .leading, spacing: 2) { Text(c.name).font(.system(size: 13, weight: .semibold)) Text("\(c.kind.title) · \(ws.accounts.filter { $0.connectionID == c.id }.count) accounts · " + (c.lastSyncAt.map { "synced \($0.formatted(.relative(presentation: .named)))" } ?? "never synced")) .font(.system(size: 11)).foregroundStyle(palette.muted) if let e = c.lastError { Text(e).font(.system(size: 11)).foregroundStyle(palette.loss).fixedSize(horizontal: false, vertical: true) } } Spacer() if c.kind.syncs { Button("Sync") { run("Syncing \(c.name)…") { try await BankSync(store: model.store).sync(c) } }.buttonStyle(SecondaryButtonStyle()) } Button("Remove") { do { try BankSync(store: model.store).disconnect(c.id); model.reload(force: true) } catch { model.message = error.localizedDescription } } .buttonStyle(SecondaryButtonStyle()) } .padding(10).background(palette.card, in: RoundedRectangle(cornerRadius: 10)) } Panel { VStack(alignment: .leading, spacing: 8) { Text("SimpleFIN Bridge").font(.system(size: 13, weight: .semibold)) Text("Make a setup token at beta-bridge.simplefin.org (SimpleFIN → My Account → Connect an app), then paste it here. It works with most US banks for $15 a year, paid to SimpleFIN.") .font(.system(size: 12)).foregroundStyle(palette.muted).fixedSize(horizontal: false, vertical: true) HStack { SecureField("Setup token", text: $simplefinToken).textFieldStyle(.roundedBorder).accessibilityIdentifier("simplefin.token") Button("Connect") { let token = simplefinToken; simplefinToken = "" run("Connecting SimpleFIN…") { _ = try await BankSync(store: model.store).connectSimpleFIN(setupToken: token) } } .buttonStyle(PrimaryButtonStyle()).disabled(simplefinToken.isEmpty) Button("Try the demo bank") { run("Loading the SimpleFIN demo…") { _ = try await BankSync(store: model.store).connectSimpleFIN(setupToken: nil) } } .buttonStyle(SecondaryButtonStyle()).accessibilityIdentifier("simplefin.demo") } } } Panel { VStack(alignment: .leading, spacing: 8) { HStack { Text("Plaid (your own keys)").font(.system(size: 13, weight: .semibold)) Spacer() if Keychain.has(.plaidClientID) { Label("Keys saved", systemImage: "key.fill").font(.system(size: 11)).foregroundStyle(palette.gain) } } .id(model.keysVersion) Text("Create a free Plaid account at dashboard.plaid.com, copy your client ID and secret (Developers → Keys), and Bucksley talks to Plaid directly. Production access is free for personal use with limits set by Plaid.") .font(.system(size: 12)).foregroundStyle(palette.muted).fixedSize(horizontal: false, vertical: true) HStack { TextField("Client ID", text: $plaidClientID).textFieldStyle(.roundedBorder) SecureField("Secret", text: $plaidSecret).textFieldStyle(.roundedBorder) PillPicker(Plaid.Environment.allCases.map { ($0, $0.rawValue.capitalized) }, selection: $plaidEnvironment).fixedSize() Button("Save keys") { do { try Keychain.set(plaidClientID.trimmingCharacters(in: .whitespaces), for: .plaidClientID) try Keychain.set(plaidSecret.trimmingCharacters(in: .whitespaces), for: .plaidSecret) plaidClientID = ""; plaidSecret = ""; model.keysChanged() } catch { model.message = error.localizedDescription } } .buttonStyle(SecondaryButtonStyle()).disabled(plaidClientID.isEmpty || plaidSecret.isEmpty) } HStack { Button("Connect a bank with Plaid") { run("Starting Plaid Link…") { guard let plaid = Plaid.fromKeychain(environment: plaidEnvironment) else { throw BucksleyError.missing("Save your Plaid keys first.") } plaidLinkToken = try await plaid.linkToken(userID: DeviceName.current) } } .buttonStyle(PrimaryButtonStyle()) if plaidEnvironment == .sandbox { Button("Add Plaid's test bank") { run("Connecting the Plaid sandbox bank…") { guard let plaid = Plaid.fromKeychain(environment: .sandbox) else { throw BucksleyError.missing("Save your Plaid sandbox keys first.") } let token = try await plaid.sandboxPublicToken() _ = try await BankSync(store: model.store).connectPlaid(publicToken: token, institution: "First Platypus Bank (sandbox)", environment: .sandbox) } } .buttonStyle(SecondaryButtonStyle()) } } .id(model.keysVersion) } } coinbase Panel { HStack { VStack(alignment: .leading, spacing: 4) { Text("Import a CSV").font(.system(size: 13, weight: .semibold)) Text("Bring your history from another money app (a Copilot Money export keeps its categories, tags, notes and reviewed state) or a bank's CSV download.") .font(.system(size: 12)).foregroundStyle(palette.muted).fixedSize(horizontal: false, vertical: true) } Spacer() Button("Choose file…") { importing = true }.buttonStyle(SecondaryButtonStyle()) } } Panel { HStack { VStack(alignment: .leading, spacing: 4) { Text("Apple Card, Apple Cash and Savings").font(.system(size: 13, weight: .semibold)) Text("Open Bucksley on your iPhone and turn on Apple Wallet in Settings. The iPhone reads them with your permission and shares them with this Mac through iCloud.") .font(.system(size: 12)).foregroundStyle(palette.muted).fixedSize(horizontal: false, vertical: true) } Spacer() } } HStack { Text("Sync every").font(.system(size: 13)) PillPicker([1, 3, 6, 12, 24].map { ($0, $0 == 24 ? "Day" : "\($0)h") }, selection: Binding(get: { ws.settings.syncEveryHours }, set: { v in model.updateWorkspace { $0.settings.syncEveryHours = v } })).fixedSize() Text("while Bucksley is open").font(.system(size: 13)).foregroundStyle(palette.muted) } } } func icon(_ kind: SourceKind) -> String { switch kind { case .csv: "doc.text" case .financekit: "wallet.pass" case .coinbase: "bitcoinsign.circle" default: "building.columns" } } /// Coinbase, read-only: crypto wallets as holdings, USD as a cash account. Sign in with Coinbase, /// or paste a CDP key with View permission. var coinbase: some View { Panel { VStack(alignment: .leading, spacing: 8) { HStack { Text("Coinbase").font(.system(size: 13, weight: .semibold)) Spacer() if coinbaseSignInReady { Button { signInWithCoinbase() } label: { Label("Sign in with Coinbase", systemImage: "person.badge.key") } .buttonStyle(PrimaryButtonStyle()).accessibilityIdentifier("coinbase.signin") } } Text("Bucksley reads your coins and your Coinbase cash, read-only. It can't trade or move money, and your key stays in this Mac's Keychain.") .font(.system(size: 12)).foregroundStyle(palette.muted).fixedSize(horizontal: false, vertical: true) Text(coinbaseSignInReady ? "Or use your own API key: at portal.cdp.coinbase.com → API Keys, create a Secret API key with only View permission, then paste its name and private key, or the whole downloaded JSON file." : "At portal.cdp.coinbase.com → API Keys, create a Secret API key with only View permission, then paste its name and private key, or the whole downloaded JSON file.") .font(.system(size: 11)).foregroundStyle(palette.muted).fixedSize(horizontal: false, vertical: true) HStack(alignment: .top) { TextField("Key name (organizations/…/apiKeys/…), or paste the JSON", text: $coinbaseName).textFieldStyle(.roundedBorder) .accessibilityIdentifier("coinbase.name") SecureField("Private key", text: $coinbaseSecret).textFieldStyle(.roundedBorder).frame(width: 200) .accessibilityIdentifier("coinbase.secret") Button("Connect") { let key = Coinbase.Key(json: coinbaseName) ?? Coinbase.Key(name: coinbaseName, privateKey: coinbaseSecret) coinbaseName = ""; coinbaseSecret = "" run("Connecting Coinbase…") { _ = try await BankSync(store: model.store).connectCoinbase(key) } } .buttonStyle(SecondaryButtonStyle()) .disabled(coinbaseName.isEmpty || (coinbaseSecret.isEmpty && Coinbase.Key(json: coinbaseName) == nil)) } } } .task { coinbaseSignInReady = await CoinbaseSignIn.isAvailable() } } func signInWithCoinbase() { run("Signing in to Coinbase…") { let request = try await CoinbaseSignIn.start() let callback = try await WebSignIn.open(request.url, callbackScheme: CoinbaseSignIn.callbackScheme) let code = try CoinbaseSignIn.code(from: callback, expecting: request) _ = try await BankSync(store: model.store).connectCoinbase(signInCode: code, verifier: request.verifier) } } // MARK: Your data var yourData: some View { VStack(alignment: .leading, spacing: 8) { SectionHeader("Your data") Text("Everything Bucksley keeps is yours to take with you. A backup holds your accounts, transactions, categories, rules, budgets and edits. It never holds bank logins or API keys, so after a restore you connect your banks again.") .font(.system(size: 12)).foregroundStyle(palette.muted).fixedSize(horizontal: false, vertical: true) HStack(spacing: 8) { Button { exportCSV() } label: { Label("Export transactions (CSV)", systemImage: "tablecells") }.buttonStyle(SecondaryButtonStyle()) Button { backUp() } label: { Label("Back up everything", systemImage: "externaldrive") }.buttonStyle(SecondaryButtonStyle()) Button { restore() } label: { Label("Restore from a backup…", systemImage: "clock.arrow.circlepath") }.buttonStyle(SecondaryButtonStyle()) } } } func exportCSV() { let panel = NSSavePanel() panel.nameFieldStringValue = "Bucksley transactions \(DayKey.today).csv" panel.allowedContentTypes = [.commaSeparatedText] guard panel.runModal() == .OK, let url = panel.url else { return } do { try Backup.csv(model.ledger).write(to: url, atomically: true, encoding: .utf8) model.message = "Saved \(model.ledger.entries.count) transactions to \(url.lastPathComponent)." } catch { model.message = error.localizedDescription } } func backUp() { let panel = NSSavePanel() panel.nameFieldStringValue = Backup.fileName() panel.allowedContentTypes = [.json] guard panel.runModal() == .OK, let url = panel.url else { return } do { try Backup.make(from: model.store).write(to: url, options: .atomic) model.message = "Backed up to \(url.lastPathComponent)." } catch { model.message = error.localizedDescription } } func restore() { let panel = NSOpenPanel() panel.allowedContentTypes = [.json] panel.allowsMultipleSelection = false guard panel.runModal() == .OK, let url = panel.url else { return } do { let data = try Data(contentsOf: url) let file = try Backup.read(data) let alert = NSAlert() alert.messageText = "Replace everything with this backup?" alert.informativeText = "From \(file.device), \(file.createdAt.formatted(date: .abbreviated, time: .shortened)): \(file.transactions.count) transactions in \(file.workspace.accounts.count) accounts. Bucksley saves a copy of what's here now first, so you can undo this by restoring that copy." alert.addButton(withTitle: "Restore") alert.addButton(withTitle: "Cancel") guard alert.runModal() == .alertFirstButtonReturn else { return } let safety = try Backup.restore(data, into: model.store) model.reload(force: true); model.shareSoon() model.message = "Restored. Your previous data is saved as \(safety.lastPathComponent) in Bucksley's Backups folder." } catch { model.message = error.localizedDescription } } // MARK: Ask func ask(_ ws: Workspace) -> some View { let provider = AskBucksley.provider(for: ws.settings) let installed = AskBucksley.installedAgents() return VStack(alignment: .leading, spacing: 10) { SectionHeader("Ask") Text("Who answers").font(.system(size: 12, weight: .semibold)) AskSourcePicker() Text(sourceNote(provider, installed: installed)).font(.system(size: 12)).foregroundStyle(palette.muted).fixedSize(horizontal: false, vertical: true) if provider.isAgent { HStack(spacing: 6) { Text("Model").font(.system(size: 12, weight: .semibold)) ForEach(AskAgent.models(provider), id: \.name) { option in let on = ws.settings.model(for: provider) == option.id Button { model.updateWorkspace { var m = $0.settings.agentModels ?? [:]; m[provider.rawValue] = option.id; $0.settings.agentModels = m } } label: { Text(option.name).font(.system(size: 12, weight: on ? .semibold : .regular)) .padding(.horizontal, 10).padding(.vertical, 5) .foregroundStyle(on ? palette.accentText : palette.text) .background(on ? palette.accent : palette.card, in: Capsule()) .overlay { Capsule().strokeBorder(on ? Color.clear : palette.line) } } .buttonStyle(.plain) } } } if provider == .claude { keyRow("Claude API key", text: $claudeKey, item: .claudeKey, model: Binding(get: { ws.settings.claudeModel }, set: { v in model.updateWorkspace { $0.settings.claudeModel = v } })) } if provider == .openai { keyRow("OpenAI API key", text: $openAIKey, item: .openAIKey, model: Binding(get: { ws.settings.openAIModel }, set: { v in model.updateWorkspace { $0.settings.openAIModel = v } })) } } } func sourceNote(_ provider: AskProvider, installed: [AskProvider]) -> String { switch provider { case .claudeCode, .codex: return "\(provider.title) answers with your own sign-in and the model you pick. It reads your numbers through Bucksley's tools on this Mac and can't change anything. Your question goes to \(provider.company) under your account." case .gemini: return "Gemini answers through Antigravity with your own Google sign-in and the model you pick. It gets a summary of your numbers, has no tools, and can't change anything. Your question goes to Google under your account." case .apple: return "Apple Intelligence: \(AskBucksley.appleModelStatus). Nothing leaves this Mac." + (installed.isEmpty ? " Install Claude Code or Codex and sign in to answer with a smarter model." : " To answer with \(installed[0].title), choose it above. Bucksley asks before sending anything.") case .claude, .openai: return "Your question and a short summary of your numbers go straight to the provider with your key. Bucksley has no server." } } func keyRow(_ label: String, text: Binding, item: Keychain.Item, model modelName: Binding) -> some View { HStack { SecureField(Keychain.has(item) ? "Saved in Keychain" : label, text: text).textFieldStyle(.roundedBorder) TextField("Model", text: modelName).textFieldStyle(.roundedBorder).frame(width: 170) Button("Save") { do { try Keychain.set(text.wrappedValue.trimmingCharacters(in: .whitespacesAndNewlines), for: item); text.wrappedValue = ""; model.keysChanged() } catch { model.message = error.localizedDescription } } .buttonStyle(SecondaryButtonStyle()).disabled(text.wrappedValue.isEmpty) } .id(model.keysVersion) } // MARK: Sync func sync(_ ws: Workspace) -> some View { VStack(alignment: .leading, spacing: 8) { SectionHeader("iCloud and iPhone") Toggle("Share with Bucksley on my iPhone and iPad", isOn: Binding(get: { ws.settings.shareWithIPhone }, set: { v in model.updateWorkspace { $0.settings.shareWithIPhone = v } })) Text("Your accounts and transactions go to your private iCloud, not to a Bucksley server. Reviews, categories and notes you change on iPhone come back here, and your own edits always win over bank data.") .font(.system(size: 12)).foregroundStyle(palette.muted).fixedSize(horizontal: false, vertical: true) HStack { Text(model.cloudStatus).font(.system(size: 12)).foregroundStyle(palette.muted) Spacer() Button("Sync with iCloud now") { Task { await model.pullFromICloud(); model.shareSoon() } }.buttonStyle(SecondaryButtonStyle()) } HStack { Text("Agents").font(.system(size: 13, weight: .semibold)) Text(ws.settings.agentsCanWrite ? "can read and make changes" : "can read").font(.system(size: 12)).foregroundStyle(palette.muted) Spacer() Button("Agent settings") { model.selection = .agents }.buttonStyle(SecondaryButtonStyle()) } .padding(.top, 6) } .font(.system(size: 13)) } // MARK: Support (Standard Settings) var support: some View { VStack(alignment: .leading, spacing: 8) { SectionHeader("Support Bucksley") supportRow("Share Your Experience", "Rate Bucksley and tell us what you think", "star.fill", "settings.review") { SupportPrompt.record(.feedback); openURL(SupportPrompt.Links.feedback) } supportRow("Technical Support", "Free help from a real person", "headphones", "settings.support") { SupportPrompt.record(.support); openURL(SupportPrompt.Links.support) } ShareLink(item: SupportPrompt.Links.website) { supportLabel("Share Bucksley", "Send someone a link to the app", "square.and.arrow.up.fill") } .buttonStyle(.plain).simultaneousGesture(TapGesture().onEnded { SupportPrompt.record(.share) }) supportRow("More Free Apps from Project ATOM", "projectatom.ai/apps", "square.grid.2x2.fill", "settings.apps") { SupportPrompt.record(.apps); openURL(SupportPrompt.Links.protomotaApps) } Text("Bucksley is free. Every feature, including support, stays free.").font(.system(size: 12)).foregroundStyle(palette.muted).padding(.top, 2) } } func supportRow(_ title: String, _ detail: String, _ symbol: String, _ id: String, action: @escaping () -> Void) -> some View { Button(action: action) { supportLabel(title, detail, symbol) }.buttonStyle(.plain).accessibilityIdentifier(id) } func supportLabel(_ title: String, _ detail: String, _ symbol: String) -> some View { HStack(spacing: 12) { Image(systemName: symbol).foregroundStyle(palette.accent).frame(width: 28, height: 28).background(palette.accent.opacity(0.13), in: RoundedRectangle(cornerRadius: 7)) VStack(alignment: .leading, spacing: 1) { Text(title).font(.system(size: 13, weight: .semibold)) Text(detail).font(.system(size: 11)).foregroundStyle(palette.muted) } Spacer() Image(systemName: "chevron.right").font(.system(size: 11)).foregroundStyle(palette.muted) } .padding(9).background(palette.card, in: RoundedRectangle(cornerRadius: 10)).contentShape(Rectangle()) } var about: some View { VStack(alignment: .leading, spacing: 8) { SectionHeader("About") HStack(spacing: 12) { Image(BucksleyTheme(preference: themeRaw).iconName ?? "AppIconImage").resizable().frame(width: 44, height: 44) VStack(alignment: .leading, spacing: 2) { Text("Bucksley").font(palette.title(16)) Text("Version \(Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "0") (\(Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "0"))") .font(.system(size: 12)).foregroundStyle(palette.muted) Text("Free and open source, public domain (Unlicense). Read-only: Bucksley never moves money.").font(.system(size: 12)).foregroundStyle(palette.muted) } Spacer() if updates.isAvailable { CheckForUpdatesButton(updates: updates).buttonStyle(SecondaryButtonStyle()) } Button("bucksley.ai") { openURL(SupportPrompt.Links.website) }.buttonStyle(SecondaryButtonStyle()) } Rectangle().fill(palette.line).frame(height: 1).padding(.top, 14) HStack { ProtomotaProductPill() Spacer(minLength: 12) Text("A Project ATOM project").font(.system(size: 12)).foregroundStyle(palette.muted) } .padding(.top, 6) } } // MARK: Actions func run(_ label: String, _ work: @escaping () async throws -> Void) { working = label Task { do { try await work(); SupportPrompt.recordCoreAction() } catch { model.message = error.localizedDescription } working = nil model.reload(force: true) model.shareSoon() } } func importCSV(_ result: Result) { do { let url = try result.get() let access = url.startAccessingSecurityScopedResource() defer { if access { url.stopAccessingSecurityScopedResource() } } let text = try String(contentsOf: url, encoding: .utf8) let counts = try BankSync(store: model.store).importCSV(text, fileName: url.lastPathComponent) model.reload(force: true); model.shareSoon() model.message = "Imported \(counts.transactions) transactions into \(counts.accounts) account\(counts.accounts == 1 ? "" : "s")." } catch { model.message = error.localizedDescription } } } struct LinkToken: Identifiable { let token: String; var id: String { token } } /// Plaid Link for web in a WebKit sheet. Link hands back a public token, which the Mac exchanges /// with Plaid directly for the item's access token. struct PlaidLinkSheet: View { let token: String let done: (String?, String?) -> Void var body: some View { VStack(spacing: 0) { HStack { Text("Connect with Plaid").font(.headline); Spacer(); Button("Cancel") { done(nil, nil) } }.padding(12) PlaidLinkView(token: token, done: done) } .frame(width: 460, height: 700) } } struct PlaidLinkView: NSViewRepresentable { let token: String let done: (String?, String?) -> Void func makeCoordinator() -> Coordinator { Coordinator(done: done) } func makeNSView(context: Context) -> WKWebView { let config = WKWebViewConfiguration() config.userContentController.add(context.coordinator, name: "bucksley") let view = WKWebView(frame: .zero, configuration: config) let escaped = token.replacingOccurrences(of: "\"", with: "") let html = """ """ view.loadHTMLString(html, baseURL: URL(string: "https://bucksley.ai/")) return view } func updateNSView(_ nsView: WKWebView, context: Context) {} final class Coordinator: NSObject, WKScriptMessageHandler { let done: (String?, String?) -> Void init(done: @escaping (String?, String?) -> Void) { self.done = done } func userContentController(_ controller: WKUserContentController, didReceive message: WKScriptMessage) { let body = message.body as? [String: Any] ?? [:] let token = body["public_token"] as? String, institution = body["institution"] as? String Task { @MainActor in self.done(token, institution) } } } } /// A system sign-in sheet (ASWebAuthenticationSession) that hands back the final callback URL. @MainActor final class WebSignIn: NSObject, ASWebAuthenticationPresentationContextProviding { private static var current: WebSignIn? private var session: ASWebAuthenticationSession? static func open(_ url: URL, callbackScheme: String) async throws -> URL { let signIn = WebSignIn() current = signIn defer { current = nil } return try await withCheckedThrowingContinuation { continuation in let session = ASWebAuthenticationSession(url: url, callback: .customScheme(callbackScheme)) { callback, error in if let callback { continuation.resume(returning: callback) } else if let error = error as? ASWebAuthenticationSessionError, error.code == .canceledLogin { continuation.resume(throwing: BucksleyError.notAllowed("Coinbase sign-in was canceled.")) } else { continuation.resume(throwing: error ?? BucksleyError.network("Coinbase sign-in didn't finish.")) } } session.presentationContextProvider = signIn signIn.session = session if !session.start() { continuation.resume(throwing: BucksleyError.network("Couldn't open the Coinbase sign-in window.")) } } } nonisolated func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor { MainActor.assumeIsolated { NSApp.keyWindow ?? NSApp.windows.first ?? NSWindow() } } }