Bucksley / app · bucksley.ai / Apps / Mac / SettingsScreen.swift
| 1 | import SwiftUI |
| 2 | import WebKit |
| 3 | import AuthenticationServices |
| 4 | import UniformTypeIdentifiers |
| 5 | import BucksleyKit |
| 6 | import BucksleyUI |
| 7 | |
| 8 | struct SettingsScreen: View { |
| 9 | @Environment(AppModel.self) private var model |
| 10 | @Environment(\.palette) private var palette |
| 11 | @EnvironmentObject private var updates: AppUpdates |
| 12 | @Environment(\.openURL) private var openURL |
| 13 | @AppStorage(BucksleyTheme.preferenceKey) private var themeRaw = BucksleyTheme.defaultPreference.rawValue |
| 14 | @AppStorage(BucksleyAppearance.preferenceKey) private var appearanceRaw = BucksleyAppearance.system.rawValue |
| 15 | @State private var simplefinToken = "" |
| 16 | @State private var plaidClientID = "" |
| 17 | @State private var plaidSecret = "" |
| 18 | @State private var plaidEnvironment = Plaid.Environment.production |
| 19 | @State private var plaidLinkToken: String? |
| 20 | @State private var claudeKey = "" |
| 21 | @State private var openAIKey = "" |
| 22 | @State private var working: String? |
| 23 | @State private var importing = false |
| 24 | @State private var coinbaseName = "" |
| 25 | @State private var coinbaseSecret = "" |
| 26 | @State private var coinbaseSignInReady = false |
| 27 | |
| 28 | var body: some View { |
| 29 | @Bindable var model = model |
| 30 | let ws = model.workspace |
| 31 | ScreenScaffold("Settings") { |
| 32 | EmptyView() |
| 33 | } content: { |
| 34 | VStack(alignment: .leading, spacing: 24) { |
| 35 | appearance |
| 36 | connections(ws) |
| 37 | ask(ws) |
| 38 | sync(ws) |
| 39 | yourData |
| 40 | support |
| 41 | about |
| 42 | } |
| 43 | .frame(maxWidth: 760, alignment: .leading) |
| 44 | .frame(maxWidth: .infinity, alignment: .leading) |
| 45 | } |
| 46 | .fileImporter(isPresented: $importing, allowedContentTypes: [.commaSeparatedText, .plainText]) { result in importCSV(result) } |
| 47 | .onChange(of: model.wantsCSVImport, initial: true) { _, wants in if wants { importing = true; model.wantsCSVImport = false } } |
| 48 | .sheet(item: Binding(get: { plaidLinkToken.map { LinkToken(token: $0) } }, set: { plaidLinkToken = $0?.token })) { link in |
| 49 | PlaidLinkSheet(token: link.token) { publicToken, institution in |
| 50 | plaidLinkToken = nil |
| 51 | guard let publicToken else { return } |
| 52 | run("Connecting \(institution ?? "your bank")…") { |
| 53 | _ = try await BankSync(store: model.store).connectPlaid(publicToken: publicToken, institution: institution ?? "Bank", environment: plaidEnvironment) |
| 54 | } |
| 55 | } |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | // MARK: Appearance |
| 60 | |
| 61 | var appearance: some View { |
| 62 | VStack(alignment: .leading, spacing: 10) { |
| 63 | SectionHeader("Appearance") |
| 64 | ForEach(BucksleyTheme.allCases) { theme in |
| 65 | Button { themeRaw = theme.rawValue } label: { |
| 66 | HStack(spacing: 12) { |
| 67 | HStack(spacing: 4) { ThemeSwatch(theme: theme, dark: false); ThemeSwatch(theme: theme, dark: true) } |
| 68 | VStack(alignment: .leading, spacing: 2) { |
| 69 | HStack(spacing: 6) { |
| 70 | Text(theme.title).font(.system(size: 13, weight: .semibold)) |
| 71 | if theme == .afterhours { Text("Default").font(.system(size: 10, weight: .bold)).foregroundStyle(palette.muted) } |
| 72 | } |
| 73 | Text(theme.summary + ". The app icon follows.").font(.system(size: 12)).foregroundStyle(palette.muted) |
| 74 | } |
| 75 | Spacer() |
| 76 | Image(nsImage: NSImage(named: theme.iconName ?? "AppIconImage") ?? NSImage()).resizable().frame(width: 28, height: 28) |
| 77 | if themeRaw == theme.rawValue { Image(systemName: "checkmark.circle.fill").foregroundStyle(palette.accent).font(.system(size: 16)) } |
| 78 | } |
| 79 | .padding(10) |
| 80 | .background(palette.card, in: RoundedRectangle(cornerRadius: 10)) |
| 81 | .overlay { RoundedRectangle(cornerRadius: 10).strokeBorder(themeRaw == theme.rawValue ? palette.accent : .clear, lineWidth: 1.5) } |
| 82 | .contentShape(Rectangle()) |
| 83 | } |
| 84 | .buttonStyle(.plain) |
| 85 | .accessibilityAddTraits(themeRaw == theme.rawValue ? .isSelected : []) |
| 86 | .accessibilityIdentifier("theme.\(theme.rawValue)") |
| 87 | } |
| 88 | HStack { |
| 89 | Text("Appearance Mode").font(.system(size: 13)).frame(width: 130, alignment: .leading) |
| 90 | PillPicker(BucksleyAppearance.allCases.map { ($0.rawValue, $0.title) }, selection: $appearanceRaw).fixedSize() |
| 91 | .accessibilityIdentifier("settingsAppearanceModePicker") |
| 92 | } |
| 93 | } |
| 94 | } |
| 95 | |
| 96 | // MARK: Connections |
| 97 | |
| 98 | func connections(_ ws: Workspace) -> some View { |
| 99 | VStack(alignment: .leading, spacing: 12) { |
| 100 | SectionHeader("Connections") { if let working { HStack(spacing: 6) { ProgressView().controlSize(.small); Text(working).font(.system(size: 12)) } } } |
| 101 | Text("Bank sync runs on this Mac only, straight to your bank's data provider with your own credentials. Credentials stay in your Keychain.") |
| 102 | .font(.system(size: 12)).foregroundStyle(palette.muted).fixedSize(horizontal: false, vertical: true) |
| 103 | ForEach(ws.connections) { c in |
| 104 | HStack(spacing: 10) { |
| 105 | Image(systemName: icon(c.kind)).frame(width: 22) |
| 106 | VStack(alignment: .leading, spacing: 2) { |
| 107 | Text(c.name).font(.system(size: 13, weight: .semibold)) |
| 108 | Text("\(c.kind.title) · \(ws.accounts.filter { $0.connectionID == c.id }.count) accounts · " + (c.lastSyncAt.map { "synced \($0.formatted(.relative(presentation: .named)))" } ?? "never synced")) |
| 109 | .font(.system(size: 11)).foregroundStyle(palette.muted) |
| 110 | if let e = c.lastError { Text(e).font(.system(size: 11)).foregroundStyle(palette.loss).fixedSize(horizontal: false, vertical: true) } |
| 111 | } |
| 112 | Spacer() |
| 113 | if c.kind.syncs { |
| 114 | Button("Sync") { run("Syncing \(c.name)…") { try await BankSync(store: model.store).sync(c) } }.buttonStyle(SecondaryButtonStyle()) |
| 115 | } |
| 116 | Button("Remove") { do { try BankSync(store: model.store).disconnect(c.id); model.reload(force: true) } catch { model.message = error.localizedDescription } } |
| 117 | .buttonStyle(SecondaryButtonStyle()) |
| 118 | } |
| 119 | .padding(10).background(palette.card, in: RoundedRectangle(cornerRadius: 10)) |
| 120 | } |
| 121 | |
| 122 | Panel { |
| 123 | VStack(alignment: .leading, spacing: 8) { |
| 124 | Text("SimpleFIN Bridge").font(.system(size: 13, weight: .semibold)) |
| 125 | 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.") |
| 126 | .font(.system(size: 12)).foregroundStyle(palette.muted).fixedSize(horizontal: false, vertical: true) |
| 127 | HStack { |
| 128 | SecureField("Setup token", text: $simplefinToken).textFieldStyle(.roundedBorder).accessibilityIdentifier("simplefin.token") |
| 129 | Button("Connect") { |
| 130 | let token = simplefinToken; simplefinToken = "" |
| 131 | run("Connecting SimpleFIN…") { _ = try await BankSync(store: model.store).connectSimpleFIN(setupToken: token) } |
| 132 | } |
| 133 | .buttonStyle(PrimaryButtonStyle()).disabled(simplefinToken.isEmpty) |
| 134 | Button("Try the demo bank") { run("Loading the SimpleFIN demo…") { _ = try await BankSync(store: model.store).connectSimpleFIN(setupToken: nil) } } |
| 135 | .buttonStyle(SecondaryButtonStyle()).accessibilityIdentifier("simplefin.demo") |
| 136 | } |
| 137 | } |
| 138 | } |
| 139 | Panel { |
| 140 | VStack(alignment: .leading, spacing: 8) { |
| 141 | HStack { |
| 142 | Text("Plaid (your own keys)").font(.system(size: 13, weight: .semibold)) |
| 143 | Spacer() |
| 144 | if Keychain.has(.plaidClientID) { Label("Keys saved", systemImage: "key.fill").font(.system(size: 11)).foregroundStyle(palette.gain) } |
| 145 | } |
| 146 | .id(model.keysVersion) |
| 147 | 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.") |
| 148 | .font(.system(size: 12)).foregroundStyle(palette.muted).fixedSize(horizontal: false, vertical: true) |
| 149 | HStack { |
| 150 | TextField("Client ID", text: $plaidClientID).textFieldStyle(.roundedBorder) |
| 151 | SecureField("Secret", text: $plaidSecret).textFieldStyle(.roundedBorder) |
| 152 | PillPicker(Plaid.Environment.allCases.map { ($0, $0.rawValue.capitalized) }, selection: $plaidEnvironment).fixedSize() |
| 153 | Button("Save keys") { |
| 154 | do { |
| 155 | try Keychain.set(plaidClientID.trimmingCharacters(in: .whitespaces), for: .plaidClientID) |
| 156 | try Keychain.set(plaidSecret.trimmingCharacters(in: .whitespaces), for: .plaidSecret) |
| 157 | plaidClientID = ""; plaidSecret = ""; model.keysChanged() |
| 158 | } catch { model.message = error.localizedDescription } |
| 159 | } |
| 160 | .buttonStyle(SecondaryButtonStyle()).disabled(plaidClientID.isEmpty || plaidSecret.isEmpty) |
| 161 | } |
| 162 | HStack { |
| 163 | Button("Connect a bank with Plaid") { |
| 164 | run("Starting Plaid Link…") { |
| 165 | guard let plaid = Plaid.fromKeychain(environment: plaidEnvironment) else { throw BucksleyError.missing("Save your Plaid keys first.") } |
| 166 | plaidLinkToken = try await plaid.linkToken(userID: DeviceName.current) |
| 167 | } |
| 168 | } |
| 169 | .buttonStyle(PrimaryButtonStyle()) |
| 170 | if plaidEnvironment == .sandbox { |
| 171 | Button("Add Plaid's test bank") { |
| 172 | run("Connecting the Plaid sandbox bank…") { |
| 173 | guard let plaid = Plaid.fromKeychain(environment: .sandbox) else { throw BucksleyError.missing("Save your Plaid sandbox keys first.") } |
| 174 | let token = try await plaid.sandboxPublicToken() |
| 175 | _ = try await BankSync(store: model.store).connectPlaid(publicToken: token, institution: "First Platypus Bank (sandbox)", environment: .sandbox) |
| 176 | } |
| 177 | } |
| 178 | .buttonStyle(SecondaryButtonStyle()) |
| 179 | } |
| 180 | } |
| 181 | .id(model.keysVersion) |
| 182 | } |
| 183 | } |
| 184 | coinbase |
| 185 | Panel { |
| 186 | HStack { |
| 187 | VStack(alignment: .leading, spacing: 4) { |
| 188 | Text("Import a CSV").font(.system(size: 13, weight: .semibold)) |
| 189 | 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.") |
| 190 | .font(.system(size: 12)).foregroundStyle(palette.muted).fixedSize(horizontal: false, vertical: true) |
| 191 | } |
| 192 | Spacer() |
| 193 | Button("Choose file…") { importing = true }.buttonStyle(SecondaryButtonStyle()) |
| 194 | } |
| 195 | } |
| 196 | Panel { |
| 197 | HStack { |
| 198 | VStack(alignment: .leading, spacing: 4) { |
| 199 | Text("Apple Card, Apple Cash and Savings").font(.system(size: 13, weight: .semibold)) |
| 200 | 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.") |
| 201 | .font(.system(size: 12)).foregroundStyle(palette.muted).fixedSize(horizontal: false, vertical: true) |
| 202 | } |
| 203 | Spacer() |
| 204 | } |
| 205 | } |
| 206 | HStack { |
| 207 | Text("Sync every").font(.system(size: 13)) |
| 208 | PillPicker([1, 3, 6, 12, 24].map { ($0, $0 == 24 ? "Day" : "\($0)h") }, |
| 209 | selection: Binding(get: { ws.settings.syncEveryHours }, set: { v in model.updateWorkspace { $0.settings.syncEveryHours = v } })).fixedSize() |
| 210 | Text("while Bucksley is open").font(.system(size: 13)).foregroundStyle(palette.muted) |
| 211 | } |
| 212 | } |
| 213 | } |
| 214 | |
| 215 | func icon(_ kind: SourceKind) -> String { |
| 216 | switch kind { |
| 217 | case .csv: "doc.text" |
| 218 | case .financekit: "wallet.pass" |
| 219 | case .coinbase: "bitcoinsign.circle" |
| 220 | default: "building.columns" |
| 221 | } |
| 222 | } |
| 223 | |
| 224 | /// Coinbase, read-only: crypto wallets as holdings, USD as a cash account. Sign in with Coinbase, |
| 225 | /// or paste a CDP key with View permission. |
| 226 | var coinbase: some View { |
| 227 | Panel { |
| 228 | VStack(alignment: .leading, spacing: 8) { |
| 229 | HStack { |
| 230 | Text("Coinbase").font(.system(size: 13, weight: .semibold)) |
| 231 | Spacer() |
| 232 | if coinbaseSignInReady { |
| 233 | Button { signInWithCoinbase() } label: { Label("Sign in with Coinbase", systemImage: "person.badge.key") } |
| 234 | .buttonStyle(PrimaryButtonStyle()).accessibilityIdentifier("coinbase.signin") |
| 235 | } |
| 236 | } |
| 237 | 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.") |
| 238 | .font(.system(size: 12)).foregroundStyle(palette.muted).fixedSize(horizontal: false, vertical: true) |
| 239 | Text(coinbaseSignInReady |
| 240 | ? "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." |
| 241 | : "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.") |
| 242 | .font(.system(size: 11)).foregroundStyle(palette.muted).fixedSize(horizontal: false, vertical: true) |
| 243 | HStack(alignment: .top) { |
| 244 | TextField("Key name (organizations/…/apiKeys/…), or paste the JSON", text: $coinbaseName).textFieldStyle(.roundedBorder) |
| 245 | .accessibilityIdentifier("coinbase.name") |
| 246 | SecureField("Private key", text: $coinbaseSecret).textFieldStyle(.roundedBorder).frame(width: 200) |
| 247 | .accessibilityIdentifier("coinbase.secret") |
| 248 | Button("Connect") { |
| 249 | let key = Coinbase.Key(json: coinbaseName) ?? Coinbase.Key(name: coinbaseName, privateKey: coinbaseSecret) |
| 250 | coinbaseName = ""; coinbaseSecret = "" |
| 251 | run("Connecting Coinbase…") { _ = try await BankSync(store: model.store).connectCoinbase(key) } |
| 252 | } |
| 253 | .buttonStyle(SecondaryButtonStyle()) |
| 254 | .disabled(coinbaseName.isEmpty || (coinbaseSecret.isEmpty && Coinbase.Key(json: coinbaseName) == nil)) |
| 255 | } |
| 256 | } |
| 257 | } |
| 258 | .task { coinbaseSignInReady = await CoinbaseSignIn.isAvailable() } |
| 259 | } |
| 260 | |
| 261 | func signInWithCoinbase() { |
| 262 | run("Signing in to Coinbase…") { |
| 263 | let request = try await CoinbaseSignIn.start() |
| 264 | let callback = try await WebSignIn.open(request.url, callbackScheme: CoinbaseSignIn.callbackScheme) |
| 265 | let code = try CoinbaseSignIn.code(from: callback, expecting: request) |
| 266 | _ = try await BankSync(store: model.store).connectCoinbase(signInCode: code, verifier: request.verifier) |
| 267 | } |
| 268 | } |
| 269 | |
| 270 | // MARK: Your data |
| 271 | |
| 272 | var yourData: some View { |
| 273 | VStack(alignment: .leading, spacing: 8) { |
| 274 | SectionHeader("Your data") |
| 275 | 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.") |
| 276 | .font(.system(size: 12)).foregroundStyle(palette.muted).fixedSize(horizontal: false, vertical: true) |
| 277 | HStack(spacing: 8) { |
| 278 | Button { exportCSV() } label: { Label("Export transactions (CSV)", systemImage: "tablecells") }.buttonStyle(SecondaryButtonStyle()) |
| 279 | Button { backUp() } label: { Label("Back up everything", systemImage: "externaldrive") }.buttonStyle(SecondaryButtonStyle()) |
| 280 | Button { restore() } label: { Label("Restore from a backup…", systemImage: "clock.arrow.circlepath") }.buttonStyle(SecondaryButtonStyle()) |
| 281 | } |
| 282 | } |
| 283 | } |
| 284 | |
| 285 | func exportCSV() { |
| 286 | let panel = NSSavePanel() |
| 287 | panel.nameFieldStringValue = "Bucksley transactions \(DayKey.today).csv" |
| 288 | panel.allowedContentTypes = [.commaSeparatedText] |
| 289 | guard panel.runModal() == .OK, let url = panel.url else { return } |
| 290 | do { |
| 291 | try Backup.csv(model.ledger).write(to: url, atomically: true, encoding: .utf8) |
| 292 | model.message = "Saved \(model.ledger.entries.count) transactions to \(url.lastPathComponent)." |
| 293 | } catch { model.message = error.localizedDescription } |
| 294 | } |
| 295 | |
| 296 | func backUp() { |
| 297 | let panel = NSSavePanel() |
| 298 | panel.nameFieldStringValue = Backup.fileName() |
| 299 | panel.allowedContentTypes = [.json] |
| 300 | guard panel.runModal() == .OK, let url = panel.url else { return } |
| 301 | do { |
| 302 | try Backup.make(from: model.store).write(to: url, options: .atomic) |
| 303 | model.message = "Backed up to \(url.lastPathComponent)." |
| 304 | } catch { model.message = error.localizedDescription } |
| 305 | } |
| 306 | |
| 307 | func restore() { |
| 308 | let panel = NSOpenPanel() |
| 309 | panel.allowedContentTypes = [.json] |
| 310 | panel.allowsMultipleSelection = false |
| 311 | guard panel.runModal() == .OK, let url = panel.url else { return } |
| 312 | do { |
| 313 | let data = try Data(contentsOf: url) |
| 314 | let file = try Backup.read(data) |
| 315 | let alert = NSAlert() |
| 316 | alert.messageText = "Replace everything with this backup?" |
| 317 | 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." |
| 318 | alert.addButton(withTitle: "Restore") |
| 319 | alert.addButton(withTitle: "Cancel") |
| 320 | guard alert.runModal() == .alertFirstButtonReturn else { return } |
| 321 | let safety = try Backup.restore(data, into: model.store) |
| 322 | model.reload(force: true); model.shareSoon() |
| 323 | model.message = "Restored. Your previous data is saved as \(safety.lastPathComponent) in Bucksley's Backups folder." |
| 324 | } catch { model.message = error.localizedDescription } |
| 325 | } |
| 326 | |
| 327 | // MARK: Ask |
| 328 | |
| 329 | func ask(_ ws: Workspace) -> some View { |
| 330 | let provider = AskBucksley.provider(for: ws.settings) |
| 331 | let installed = AskBucksley.installedAgents() |
| 332 | return VStack(alignment: .leading, spacing: 10) { |
| 333 | SectionHeader("Ask") |
| 334 | Text("Who answers").font(.system(size: 12, weight: .semibold)) |
| 335 | AskSourcePicker() |
| 336 | Text(sourceNote(provider, installed: installed)).font(.system(size: 12)).foregroundStyle(palette.muted).fixedSize(horizontal: false, vertical: true) |
| 337 | if provider.isAgent { |
| 338 | HStack(spacing: 6) { |
| 339 | Text("Model").font(.system(size: 12, weight: .semibold)) |
| 340 | ForEach(AskAgent.models(provider), id: \.name) { option in |
| 341 | let on = ws.settings.model(for: provider) == option.id |
| 342 | Button { model.updateWorkspace { var m = $0.settings.agentModels ?? [:]; m[provider.rawValue] = option.id; $0.settings.agentModels = m } } label: { |
| 343 | Text(option.name).font(.system(size: 12, weight: on ? .semibold : .regular)) |
| 344 | .padding(.horizontal, 10).padding(.vertical, 5) |
| 345 | .foregroundStyle(on ? palette.accentText : palette.text) |
| 346 | .background(on ? palette.accent : palette.card, in: Capsule()) |
| 347 | .overlay { Capsule().strokeBorder(on ? Color.clear : palette.line) } |
| 348 | } |
| 349 | .buttonStyle(.plain) |
| 350 | } |
| 351 | } |
| 352 | } |
| 353 | if provider == .claude { |
| 354 | keyRow("Claude API key", text: $claudeKey, item: .claudeKey, model: Binding(get: { ws.settings.claudeModel }, set: { v in model.updateWorkspace { $0.settings.claudeModel = v } })) |
| 355 | } |
| 356 | if provider == .openai { |
| 357 | keyRow("OpenAI API key", text: $openAIKey, item: .openAIKey, model: Binding(get: { ws.settings.openAIModel }, set: { v in model.updateWorkspace { $0.settings.openAIModel = v } })) |
| 358 | } |
| 359 | } |
| 360 | } |
| 361 | |
| 362 | func sourceNote(_ provider: AskProvider, installed: [AskProvider]) -> String { |
| 363 | switch provider { |
| 364 | case .claudeCode, .codex: |
| 365 | 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." |
| 366 | case .gemini: |
| 367 | 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." |
| 368 | case .apple: |
| 369 | return "Apple Intelligence: \(AskBucksley.appleModelStatus). Nothing leaves this Mac." + |
| 370 | (installed.isEmpty ? " Install Claude Code or Codex and sign in to answer with a smarter model." |
| 371 | : " To answer with \(installed[0].title), choose it above. Bucksley asks before sending anything.") |
| 372 | case .claude, .openai: |
| 373 | return "Your question and a short summary of your numbers go straight to the provider with your key. Bucksley has no server." |
| 374 | } |
| 375 | } |
| 376 | |
| 377 | func keyRow(_ label: String, text: Binding<String>, item: Keychain.Item, model modelName: Binding<String>) -> some View { |
| 378 | HStack { |
| 379 | SecureField(Keychain.has(item) ? "Saved in Keychain" : label, text: text).textFieldStyle(.roundedBorder) |
| 380 | TextField("Model", text: modelName).textFieldStyle(.roundedBorder).frame(width: 170) |
| 381 | Button("Save") { |
| 382 | do { try Keychain.set(text.wrappedValue.trimmingCharacters(in: .whitespacesAndNewlines), for: item); text.wrappedValue = ""; model.keysChanged() } |
| 383 | catch { model.message = error.localizedDescription } |
| 384 | } |
| 385 | .buttonStyle(SecondaryButtonStyle()).disabled(text.wrappedValue.isEmpty) |
| 386 | } |
| 387 | .id(model.keysVersion) |
| 388 | } |
| 389 | |
| 390 | // MARK: Sync |
| 391 | |
| 392 | func sync(_ ws: Workspace) -> some View { |
| 393 | VStack(alignment: .leading, spacing: 8) { |
| 394 | SectionHeader("iCloud and iPhone") |
| 395 | Toggle("Share with Bucksley on my iPhone and iPad", isOn: Binding(get: { ws.settings.shareWithIPhone }, set: { v in model.updateWorkspace { $0.settings.shareWithIPhone = v } })) |
| 396 | 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.") |
| 397 | .font(.system(size: 12)).foregroundStyle(palette.muted).fixedSize(horizontal: false, vertical: true) |
| 398 | HStack { |
| 399 | Text(model.cloudStatus).font(.system(size: 12)).foregroundStyle(palette.muted) |
| 400 | Spacer() |
| 401 | Button("Sync with iCloud now") { Task { await model.pullFromICloud(); model.shareSoon() } }.buttonStyle(SecondaryButtonStyle()) |
| 402 | } |
| 403 | HStack { |
| 404 | Text("Agents").font(.system(size: 13, weight: .semibold)) |
| 405 | Text(ws.settings.agentsCanWrite ? "can read and make changes" : "can read").font(.system(size: 12)).foregroundStyle(palette.muted) |
| 406 | Spacer() |
| 407 | Button("Agent settings") { model.selection = .agents }.buttonStyle(SecondaryButtonStyle()) |
| 408 | } |
| 409 | .padding(.top, 6) |
| 410 | } |
| 411 | .font(.system(size: 13)) |
| 412 | } |
| 413 | |
| 414 | // MARK: Support (Standard Settings) |
| 415 | |
| 416 | var support: some View { |
| 417 | VStack(alignment: .leading, spacing: 8) { |
| 418 | SectionHeader("Support Bucksley") |
| 419 | supportRow("Share Your Experience", "Rate Bucksley and tell us what you think", "star.fill", "settings.review") { SupportPrompt.record(.feedback); openURL(SupportPrompt.Links.feedback) } |
| 420 | supportRow("Technical Support", "Free help from a real person", "headphones", "settings.support") { SupportPrompt.record(.support); openURL(SupportPrompt.Links.support) } |
| 421 | ShareLink(item: SupportPrompt.Links.website) { supportLabel("Share Bucksley", "Send someone a link to the app", "square.and.arrow.up.fill") } |
| 422 | .buttonStyle(.plain).simultaneousGesture(TapGesture().onEnded { SupportPrompt.record(.share) }) |
| 423 | supportRow("More Free Apps from Project ATOM", "projectatom.ai/apps", "square.grid.2x2.fill", "settings.apps") { SupportPrompt.record(.apps); openURL(SupportPrompt.Links.protomotaApps) } |
| 424 | Text("Bucksley is free. Every feature, including support, stays free.").font(.system(size: 12)).foregroundStyle(palette.muted).padding(.top, 2) |
| 425 | } |
| 426 | } |
| 427 | |
| 428 | func supportRow(_ title: String, _ detail: String, _ symbol: String, _ id: String, action: @escaping () -> Void) -> some View { |
| 429 | Button(action: action) { supportLabel(title, detail, symbol) }.buttonStyle(.plain).accessibilityIdentifier(id) |
| 430 | } |
| 431 | |
| 432 | func supportLabel(_ title: String, _ detail: String, _ symbol: String) -> some View { |
| 433 | HStack(spacing: 12) { |
| 434 | Image(systemName: symbol).foregroundStyle(palette.accent).frame(width: 28, height: 28).background(palette.accent.opacity(0.13), in: RoundedRectangle(cornerRadius: 7)) |
| 435 | VStack(alignment: .leading, spacing: 1) { |
| 436 | Text(title).font(.system(size: 13, weight: .semibold)) |
| 437 | Text(detail).font(.system(size: 11)).foregroundStyle(palette.muted) |
| 438 | } |
| 439 | Spacer() |
| 440 | Image(systemName: "chevron.right").font(.system(size: 11)).foregroundStyle(palette.muted) |
| 441 | } |
| 442 | .padding(9).background(palette.card, in: RoundedRectangle(cornerRadius: 10)).contentShape(Rectangle()) |
| 443 | } |
| 444 | |
| 445 | var about: some View { |
| 446 | VStack(alignment: .leading, spacing: 8) { |
| 447 | SectionHeader("About") |
| 448 | HStack(spacing: 12) { |
| 449 | Image(BucksleyTheme(preference: themeRaw).iconName ?? "AppIconImage").resizable().frame(width: 44, height: 44) |
| 450 | VStack(alignment: .leading, spacing: 2) { |
| 451 | Text("Bucksley").font(palette.title(16)) |
| 452 | Text("Version \(Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "0") (\(Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "0"))") |
| 453 | .font(.system(size: 12)).foregroundStyle(palette.muted) |
| 454 | Text("Free and open source, public domain (Unlicense). Read-only: Bucksley never moves money.").font(.system(size: 12)).foregroundStyle(palette.muted) |
| 455 | } |
| 456 | Spacer() |
| 457 | if updates.isAvailable { CheckForUpdatesButton(updates: updates).buttonStyle(SecondaryButtonStyle()) } |
| 458 | Button("bucksley.ai") { openURL(SupportPrompt.Links.website) }.buttonStyle(SecondaryButtonStyle()) |
| 459 | } |
| 460 | Rectangle().fill(palette.line).frame(height: 1).padding(.top, 14) |
| 461 | HStack { |
| 462 | ProtomotaProductPill() |
| 463 | Spacer(minLength: 12) |
| 464 | Text("A Project ATOM project").font(.system(size: 12)).foregroundStyle(palette.muted) |
| 465 | } |
| 466 | .padding(.top, 6) |
| 467 | } |
| 468 | } |
| 469 | |
| 470 | // MARK: Actions |
| 471 | |
| 472 | func run(_ label: String, _ work: @escaping () async throws -> Void) { |
| 473 | working = label |
| 474 | Task { |
| 475 | do { try await work(); SupportPrompt.recordCoreAction() } |
| 476 | catch { model.message = error.localizedDescription } |
| 477 | working = nil |
| 478 | model.reload(force: true) |
| 479 | model.shareSoon() |
| 480 | } |
| 481 | } |
| 482 | |
| 483 | func importCSV(_ result: Result<URL, Error>) { |
| 484 | do { |
| 485 | let url = try result.get() |
| 486 | let access = url.startAccessingSecurityScopedResource() |
| 487 | defer { if access { url.stopAccessingSecurityScopedResource() } } |
| 488 | let text = try String(contentsOf: url, encoding: .utf8) |
| 489 | let counts = try BankSync(store: model.store).importCSV(text, fileName: url.lastPathComponent) |
| 490 | model.reload(force: true); model.shareSoon() |
| 491 | model.message = "Imported \(counts.transactions) transactions into \(counts.accounts) account\(counts.accounts == 1 ? "" : "s")." |
| 492 | } catch { model.message = error.localizedDescription } |
| 493 | } |
| 494 | } |
| 495 | |
| 496 | struct LinkToken: Identifiable { let token: String; var id: String { token } } |
| 497 | |
| 498 | /// Plaid Link for web in a WebKit sheet. Link hands back a public token, which the Mac exchanges |
| 499 | /// with Plaid directly for the item's access token. |
| 500 | struct PlaidLinkSheet: View { |
| 501 | let token: String |
| 502 | let done: (String?, String?) -> Void |
| 503 | var body: some View { |
| 504 | VStack(spacing: 0) { |
| 505 | HStack { Text("Connect with Plaid").font(.headline); Spacer(); Button("Cancel") { done(nil, nil) } }.padding(12) |
| 506 | PlaidLinkView(token: token, done: done) |
| 507 | } |
| 508 | .frame(width: 460, height: 700) |
| 509 | } |
| 510 | } |
| 511 | |
| 512 | struct PlaidLinkView: NSViewRepresentable { |
| 513 | let token: String |
| 514 | let done: (String?, String?) -> Void |
| 515 | |
| 516 | func makeCoordinator() -> Coordinator { Coordinator(done: done) } |
| 517 | |
| 518 | func makeNSView(context: Context) -> WKWebView { |
| 519 | let config = WKWebViewConfiguration() |
| 520 | config.userContentController.add(context.coordinator, name: "bucksley") |
| 521 | let view = WKWebView(frame: .zero, configuration: config) |
| 522 | let escaped = token.replacingOccurrences(of: "\"", with: "") |
| 523 | let html = """ |
| 524 | <!doctype html><html><head><meta name="viewport" content="width=device-width"><script src="https://cdn.plaid.com/link/v2/stable/link-initialize.js"></script></head> |
| 525 | <body style="margin:0;background:#fff"><script> |
| 526 | const handler = Plaid.create({ token: "\(escaped)", |
| 527 | onSuccess: (public_token, metadata) => window.webkit.messageHandlers.bucksley.postMessage({ public_token, institution: (metadata.institution || {}).name || "" }), |
| 528 | onExit: () => window.webkit.messageHandlers.bucksley.postMessage({ exit: true }) }); |
| 529 | handler.open(); |
| 530 | </script></body></html> |
| 531 | """ |
| 532 | view.loadHTMLString(html, baseURL: URL(string: "https://bucksley.ai/")) |
| 533 | return view |
| 534 | } |
| 535 | |
| 536 | func updateNSView(_ nsView: WKWebView, context: Context) {} |
| 537 | |
| 538 | final class Coordinator: NSObject, WKScriptMessageHandler { |
| 539 | let done: (String?, String?) -> Void |
| 540 | init(done: @escaping (String?, String?) -> Void) { self.done = done } |
| 541 | func userContentController(_ controller: WKUserContentController, didReceive message: WKScriptMessage) { |
| 542 | let body = message.body as? [String: Any] ?? [:] |
| 543 | let token = body["public_token"] as? String, institution = body["institution"] as? String |
| 544 | Task { @MainActor in self.done(token, institution) } |
| 545 | } |
| 546 | } |
| 547 | } |
| 548 | |
| 549 | /// A system sign-in sheet (ASWebAuthenticationSession) that hands back the final callback URL. |
| 550 | @MainActor |
| 551 | final class WebSignIn: NSObject, ASWebAuthenticationPresentationContextProviding { |
| 552 | private static var current: WebSignIn? |
| 553 | private var session: ASWebAuthenticationSession? |
| 554 | |
| 555 | static func open(_ url: URL, callbackScheme: String) async throws -> URL { |
| 556 | let signIn = WebSignIn() |
| 557 | current = signIn |
| 558 | defer { current = nil } |
| 559 | return try await withCheckedThrowingContinuation { continuation in |
| 560 | let session = ASWebAuthenticationSession(url: url, callback: .customScheme(callbackScheme)) { callback, error in |
| 561 | if let callback { continuation.resume(returning: callback) } |
| 562 | else if let error = error as? ASWebAuthenticationSessionError, error.code == .canceledLogin { |
| 563 | continuation.resume(throwing: BucksleyError.notAllowed("Coinbase sign-in was canceled.")) |
| 564 | } else { continuation.resume(throwing: error ?? BucksleyError.network("Coinbase sign-in didn't finish.")) } |
| 565 | } |
| 566 | session.presentationContextProvider = signIn |
| 567 | signIn.session = session |
| 568 | if !session.start() { continuation.resume(throwing: BucksleyError.network("Couldn't open the Coinbase sign-in window.")) } |
| 569 | } |
| 570 | } |
| 571 | |
| 572 | nonisolated func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor { |
| 573 | MainActor.assumeIsolated { NSApp.keyWindow ?? NSApp.windows.first ?? NSWindow() } |
| 574 | } |
| 575 | } |