Branchwell

Bucksley / app · bucksley.ai / Apps / Mac / MacApp.swift

1import SwiftUI
2import AppKit
3import OSLog
4import BucksleyKit
5import BucksleyUI
6
7/// `Bucksley --mcp` runs the STDIO MCP server on the same local store (Inkspring pattern).
8/// `Bucksley --sync` syncs every bank connection once and prints what each one sent.
9/// Without either, the normal Mac app starts.
10@main
11enum Entry {
12 static func main() {
13 SandboxMigration.run()
14 AskAgent.install()
15 // `Bucksley --ask "question"` prints Ask Bucksley's answer with whoever is set to answer.
16 if let i = CommandLine.arguments.firstIndex(of: "--ask"), i + 1 < CommandLine.arguments.count {
17 let question = CommandLine.arguments[i + 1]
18 let semaphore = DispatchSemaphore(value: 0)
19 Task.detached {
20 do {
21 let ledger = try WorkspaceStore().ledger()
22 let settings = ledger.workspace.settings
23 let provider = AskBucksley.provider(for: settings)
24 let answer = try await AskBucksley().ask(question, ledger: ledger, provider: provider, model: settings.model(for: provider))
25 print("[\(answer.provider)] \(answer.text)\nLinked: \(answer.transactionIDs.count) · budget button: \(answer.offersBudgetPlan)")
26 } catch { FileHandle.standardError.write(Data("Ask failed: \(error.localizedDescription)\n".utf8)) }
27 semaphore.signal()
28 }
29 semaphore.wait()
30 exit(0)
31 }
32 let readOnly = CommandLine.arguments.contains("--mcp-ask")
33 if CommandLine.arguments.contains("--mcp") || readOnly {
34 let semaphore = DispatchSemaphore(value: 0)
35 Task.detached {
36 do { await MCPServer(store: try WorkspaceStore(), readOnly: readOnly).run() }
37 catch { FileHandle.standardError.write(Data("Could not open the Bucksley store: \(error)\n".utf8)) }
38 semaphore.signal()
39 }
40 semaphore.wait()
41 exit(0)
42 }
43 if CommandLine.arguments.contains("--sync") {
44 let semaphore = DispatchSemaphore(value: 0)
45 Task.detached {
46 do {
47 let store = try WorkspaceStore()
48 let report = await BankSync(store: store).syncAll()
49 let ws = try store.load()
50 var lines = ["Synced: \(report.synced.joined(separator: ", ")) · \(report.added) new, \(report.updated) updated"]
51 for (name, error) in report.failed { lines.append("Failed: \(name): \(error)") }
52 for c in ws.connections {
53 lines.append("\(c.name): \(ws.accounts.filter { $0.connectionID == c.id }.count) accounts" + (c.lastError.map { " · \($0)" } ?? ""))
54 }
55 for a in ws.accounts { lines.append(" \(a.institution) · \(a.name) · \(a.kind.title)") }
56 print(lines.joined(separator: "\n"))
57 } catch { FileHandle.standardError.write(Data("Could not sync: \(error)\n".utf8)) }
58 semaphore.signal()
59 }
60 semaphore.wait()
61 exit(0)
62 }
63 BucksleyMacApp.main()
64 }
65}
66
67struct BucksleyMacApp: App {
68 @NSApplicationDelegateAdaptor(AppDelegate.self) private var delegate
69 @State private var model = AppModel()
70 @StateObject private var updates = AppUpdates()
71
72 var body: some Scene {
73 WindowGroup("Bucksley") {
74 ThemedRoot {
75 ContentView()
76 .environment(model)
77 .environmentObject(updates)
78 .frame(minWidth: 980, idealWidth: 1280, minHeight: 640, idealHeight: 820)
79 .task { await model.start() }
80 }
81 .defaultAppStorage(BucksleyPreferences.store)
82 }
83 .defaultSize(width: 1280, height: 820)
84 .commands {
85 CommandGroup(after: .appInfo) {
86 if updates.isAvailable { CheckForUpdatesButton(updates: updates) }
87 }
88 CommandGroup(replacing: .appSettings) {
89 Button("Settings…") { model.selection = .settings }.keyboardShortcut(",")
90 }
91 CommandGroup(after: .newItem) {
92 Button("Sync Banks Now") { Task { await model.syncBanks() } }.keyboardShortcut("r")
93 Button("Import CSV…") { model.selection = .settings; model.wantsCSVImport = true }
94 }
95 CommandGroup(after: .sidebar) {
96 ForEach(Array(Screen.main.enumerated()), id: \.offset) { i, screen in
97 Button(screen.title) { model.selection = screen }.keyboardShortcut(KeyEquivalent(Character("\(i + 1)")))
98 }
99 }
100 }
101 }
102}
103
104final class AppDelegate: NSObject, NSApplicationDelegate {
105 func applicationDidFinishLaunching(_ notification: Notification) {
106 NSApp.registerForRemoteNotifications()
107 AppIcon.apply(BucksleyTheme(preference: BucksleyPreferences.store.string(forKey: BucksleyTheme.preferenceKey)))
108 }
109 func application(_ application: NSApplication, didReceiveRemoteNotification userInfo: [String: Any]) {
110 Task { @MainActor in await AppModel.shared?.pullFromICloud() }
111 }
112 func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { false }
113}
114
115/// The Mac's Dock icon follows the theme. (macOS has no persistent alternate icons for a signed
116/// app; changing the bundle's icon file would break its signature, so only the running icon changes.)
117@MainActor
118enum AppIcon {
119 static func apply(_ theme: BucksleyTheme) {
120 guard let name = theme.iconName, let image = NSImage(named: name) else { NSApp.applicationIconImage = nil; return }
121 NSApp.applicationIconImage = image
122 }
123}
124
125enum Screen: Hashable, Identifiable {
126 case overview, accounts, investments, transactions, cashFlow, categories, budgets, recurring, ask, agents, settings
127 static let main: [Screen] = [.overview, .accounts, .investments, .transactions, .cashFlow, .categories, .budgets, .recurring, .ask]
128 var id: Self { self }
129 var title: String {
130 switch self {
131 case .overview: "Overview"
132 case .accounts: "Accounts"
133 case .investments: "Investments"
134 case .transactions: "Transactions"
135 case .cashFlow: "Cash Flow"
136 case .categories: "Categories & Rules"
137 case .budgets: "Budgets"
138 case .recurring: "Recurring"
139 case .ask: "Ask Bucksley"
140 case .agents: "Agents"
141 case .settings: "Settings"
142 }
143 }
144 /// Which of the theme's chart colors tints the sidebar icon.
145 var colorIndex: Int? {
146 switch self {
147 case .overview: 0
148 case .accounts: 2
149 case .investments: 1
150 case .transactions: 3
151 case .cashFlow: 1
152 case .categories: 4
153 case .budgets: 1
154 case .recurring: 2
155 case .ask: 0
156 case .agents, .settings: nil
157 }
158 }
159 var symbol: String {
160 switch self {
161 case .overview: "chart.line.uptrend.xyaxis"
162 case .accounts: "building.columns"
163 case .investments: "chart.bar.xaxis"
164 case .transactions: "list.bullet.rectangle"
165 case .categories: "square.grid.2x2"
166 case .budgets: "chart.pie"
167 case .recurring: "repeat"
168 case .ask: "sparkles"
169 case .cashFlow: "arrow.left.arrow.right.circle"
170 case .agents: "terminal"
171 case .settings: "gearshape"
172 }
173 }
174}
175
176@MainActor @Observable
177final class AppModel {
178 static weak var shared: AppModel?
179 let store: WorkspaceStore
180 let cloud: CloudSync
181 var ledger: Ledger
182 var selection: Screen = .overview
183 var syncing = false
184 var lastReport: BankSync.Report?
185 var cloudStatus = "Not synced yet"
186 var message: String?
187 var wantsCSVImport = false
188 /// Bumped after Keychain changes, so views that read key state redraw.
189 var keysVersion = 0
190 var selectedTransactionID: String?
191 /// Screenshot tour only: shows the end of the current screen.
192 var tourScrolledToEnd = false
193 var tourAnchor: UnitPoint?
194
195 /// Opening a transaction is reviewing it: it leaves the review queue right away.
196 func open(_ entry: LedgerEntry) {
197 selectedTransactionID = entry.id
198 if !entry.reviewed { edit(entry.id) { $0.reviewed = true } }
199 }
200 var range = 90
201 private var started = false
202 private var loadedVersion: Date?
203
204 init() {
205 let store = try! WorkspaceStore()
206 self.store = store
207 cloud = CloudSync(store: store)
208 ledger = (try? store.ledger()) ?? Ledger(workspace: Workspace(), transactions: [], edits: [:], balances: [])
209 Self.shared = self
210 }
211
212 var workspace: Workspace { ledger.workspace }
213
214 func start() async {
215 guard !started else { return }
216 started = true
217 reload(force: true)
218 #if DEBUG
219 await DebugSetup.run(model: self)
220 if let dir = ProcessInfo.processInfo.environment["BUCKSLEY_SNAPSHOT_DIR"] {
221 Task { await ScreenTour.capture(into: URL(fileURLWithPath: dir), model: self) }
222 return
223 }
224 #endif
225 // Agents change the store from the --mcp process; pick up their edits.
226 Task { while !Task.isCancelled { try? await Task.sleep(for: .seconds(3)); reload() } }
227 Task {
228 if cloud.isAvailable { try? await cloud.subscribe() }
229 await pullFromICloud()
230 while !Task.isCancelled {
231 if needsBankSync { await syncBanks() }
232 try? await Task.sleep(for: .seconds(300))
233 await pullFromICloud()
234 }
235 }
236 }
237
238 var needsBankSync: Bool {
239 guard workspace.connections.contains(where: { $0.kind.syncs }) else { return false }
240 guard let last = workspace.settings.lastSyncAt else { return true }
241 return Date.now.timeIntervalSince(last) > Double(workspace.settings.syncEveryHours) * 3600
242 }
243
244 /// Re-reads the store when its files changed on disk.
245 func reload(force: Bool = false) {
246 let version = store.lastModified()
247 guard force || version == nil || version != loadedVersion else { return }
248 do {
249 ledger = try store.ledger()
250 loadedVersion = version
251 refreshInsights()
252 } catch {
253 Self.log.error("Could not read the store: \(error.localizedDescription, privacy: .public)")
254 }
255 }
256 static let log = Logger(subsystem: "com.protomota.bucksley", category: "app")
257
258 func syncBanks() async {
259 guard !syncing else { return }
260 syncing = true; defer { syncing = false }
261 lastReport = await BankSync(store: store).syncAll()
262 reload(force: true)
263 shareSoon()
264 }
265
266 /// Reads the iPhone's edits (review inbox, recategorizing, notes) and any Apple Wallet import.
267 func pullFromICloud() async {
268 guard cloud.isAvailable else { cloudStatus = "iCloud sync needs the signed app"; return }
269 guard await cloud.accountReady() else { cloudStatus = "Sign in to iCloud to sync with iPhone"; return }
270 do {
271 let changes = try await cloud.pullChanges(into: store)
272 if let wallet = changes.wallet { try WalletImport.apply(wallet, store: store) }
273 if changes.edits > 0 || changes.wallet != nil { reload(force: true); shareSoon() }
274 cloudStatus = "Synced with iCloud " + Date.now.formatted(date: .omitted, time: .shortened)
275 } catch {
276 cloudStatus = "iCloud: \(error.localizedDescription)"
277 }
278 }
279
280 private var sharePush: Task<Void, Never>?
281 /// Pushes edits and a fresh snapshot to iCloud after a short pause, so a burst of edits sends once.
282 func shareSoon() {
283 sharePush?.cancel()
284 sharePush = Task { [store, cloud] in
285 try? await Task.sleep(for: .seconds(1.5))
286 guard !Task.isCancelled, cloud.isAvailable, let ws = try? store.load(), ws.settings.shareWithIPhone else { return }
287 do {
288 try await cloud.pushEdits(from: store)
289 try await cloud.pushSnapshot(try CloudSync.snapshot(from: store))
290 _ = try? store.update { $0.settings.lastSharedAt = .now }
291 cloudStatus = "Synced with iCloud " + Date.now.formatted(date: .omitted, time: .shortened)
292 } catch {
293 cloudStatus = "iCloud: \(error.localizedDescription)"
294 Self.log.error("Could not share with iCloud: \(error.localizedDescription, privacy: .public)")
295 }
296 }
297 }
298
299 // MARK: Edits
300
301 func edit(_ id: String, _ change: (inout TransactionEdit) -> Void) {
302 do { try store.edit(id, change); reload(force: true); shareSoon(); SupportPrompt.recordCoreAction() }
303 catch { message = error.localizedDescription }
304 }
305
306 func updateWorkspace(_ change: (inout Workspace) -> Void) {
307 do { try store.update(change); reload(force: true); shareSoon() }
308 catch { message = error.localizedDescription }
309 }
310
311 func keysChanged() { keysVersion += 1 }
312
313 var reviewCount: Int { ledger.reviewQueue.count }
314
315 // MARK: Insights
316
317 /// Flags, refund matches and category suggestions, worked out once per reload.
318 struct Insights {
319 var flags: [Ledger.Flag] = []
320 var flagByEntry: [String: Ledger.Flag] = [:]
321 var refunds: [Ledger.RefundMatch] = []
322 var refundByEntry: [String: Ledger.RefundMatch] = [:]
323 var suggestions: [String: Ledger.CategorySuggestion] = [:]
324 var reviewOrder: [LedgerEntry] = []
325 }
326 var insights = Insights()
327 private var modelSuggestions: [String: Ledger.CategorySuggestion] = [:]
328 private var suggesting: Task<Void, Never>?
329
330 func refreshInsights() {
331 var i = Insights()
332 i.flags = ledger.flags()
333 i.flagByEntry = Dictionary(i.flags.map { ($0.entryID, $0) }, uniquingKeysWith: { a, _ in a })
334 i.refunds = ledger.refundMatches()
335 i.refundByEntry = Dictionary(i.refunds.map { ($0.refundID, $0) }, uniquingKeysWith: { a, _ in a })
336 let open = Set(ledger.entries.filter(ledger.needsCategory).map(\.id))
337 i.suggestions = modelSuggestions.filter { open.contains($0.key) }
338 for s in ledger.historySuggestions() { i.suggestions[s.entryID] = s }
339 i.reviewOrder = ledger.prioritizedReviewQueue()
340 insights = i
341 suggestWithAppleIntelligence(missing: ledger.entries.filter { ledger.needsCategory($0) && i.suggestions[$0.id] == nil && modelSuggestions[$0.id] == nil })
342 }
343
344 /// Asks the on-device model about uncategorized transactions history can't place, a batch at a time.
345 private func suggestWithAppleIntelligence(missing: [LedgerEntry]) {
346 guard AskBucksley.appleModelAvailable, !missing.isEmpty, suggesting == nil else { return }
347 let batch = Array(missing.prefix(25)), categories = workspace.categories
348 suggesting = Task {
349 let found = await AskBucksley.suggestCategories(for: batch, categories: categories)
350 for s in found { modelSuggestions[s.entryID] = s }
351 // Mark the rest as asked so they aren't sent again this session.
352 for e in batch where modelSuggestions[e.id] == nil { modelSuggestions[e.id] = Ledger.CategorySuggestion(entryID: e.id, categoryID: "", reason: "") }
353 suggesting = nil
354 refreshInsights()
355 }
356 }
357
358 func suggestion(for id: String) -> Ledger.CategorySuggestion? {
359 insights.suggestions[id].flatMap { $0.categoryID.isEmpty ? nil : $0 }
360 }
361
362 /// Links a refund to its purchase and files it in the purchase's category.
363 func acceptRefund(_ match: Ledger.RefundMatch) {
364 guard let purchase = ledger.entry(match.purchaseID) else { return }
365 edit(match.refundID) { $0.refundOf = match.purchaseID; $0.categoryID = purchase.categoryID }
366 }
367}
368
369#if DEBUG
370/// Debug builds only: `BUCKSLEY_SNAPSHOT_DIR=/path` walks every screen in every theme, light and
371/// dark, and writes one PNG of the app's own window per view (`<theme>-<light|dark>-<screen>.png`).
372/// Lets agents capture the running app headlessly, even with the display locked.
373/// Debug builds only, for test runs and screenshots: `BUCKSLEY_DEMO_CONNECT=1` connects the public
374/// SimpleFIN demo bank through the real connector; `BUCKSLEY_IMPORT_CSV=/path.csv` imports a CSV
375/// through the real importer; `BUCKSLEY_FIXTURE_BALANCES="Account name=123.45;…"` sets CSV balances.
376@MainActor
377enum DebugSetup {
378 static func run(model: AppModel) async {
379 let env = ProcessInfo.processInfo.environment
380 let sync = BankSync(store: model.store)
381 if env["BUCKSLEY_DEMO_CONNECT"] != nil, !model.workspace.connections.contains(where: { $0.kind == .simplefin }) {
382 do { _ = try await sync.connectSimpleFIN(setupToken: nil) } catch { model.message = "SimpleFIN demo: \(error.localizedDescription)" }
383 }
384 if let path = env["BUCKSLEY_IMPORT_CSV"], !model.workspace.connections.contains(where: { $0.kind == .csv }),
385 let text = try? String(contentsOfFile: path, encoding: .utf8) {
386 do { _ = try sync.importCSV(text, fileName: URL(fileURLWithPath: path).lastPathComponent) } catch { model.message = "CSV: \(error.localizedDescription)" }
387 }
388 if let spec = env["BUCKSLEY_FIXTURE_BALANCES"] {
389 for pair in spec.split(separator: ";") {
390 let parts = pair.split(separator: "=", maxSplits: 1).map(String.init)
391 guard parts.count == 2, let value = Decimal(money: parts[1]),
392 let account = (try? model.store.load())?.accounts.first(where: { $0.name == parts[0] }) else { continue }
393 try? sync.setManualBalance(account.id, balance: value)
394 }
395 }
396 // Test fixture positions: "Account name=SYM:Name:shares:value:cost|…;…" (screenshots only).
397 if let spec = env["BUCKSLEY_FIXTURE_HOLDINGS"] {
398 for entry in spec.split(separator: ";") {
399 let parts = entry.split(separator: "=", maxSplits: 1).map(String.init)
400 guard parts.count == 2 else { continue }
401 let holdings = parts[1].split(separator: "|").enumerated().compactMap { i, h -> Holding? in
402 let f = h.split(separator: ":").map(String.init)
403 guard f.count == 5, let value = Decimal(money: f[3]) else { return nil }
404 return Holding(id: "fixture-\(i)", symbol: f[0], name: f[1], shares: Decimal(string: f[2]), marketValue: value, costBasis: Decimal(money: f[4]))
405 }
406 _ = try? model.store.update { ws in if let i = ws.accounts.firstIndex(where: { $0.name == parts[0] }) { ws.accounts[i].holdings = holdings } }
407 }
408 }
409 // Test fixture: imported rows on or after this day come in unreviewed, like a fresh bank sync.
410 if let since = env["BUCKSLEY_FIXTURE_UNREVIEWED_SINCE"], let ledger = try? model.store.ledger() {
411 for e in ledger.entries where e.day >= since && e.reviewed { _ = try? model.store.edit(e.id) { $0.reviewed = false } }
412 }
413 // Test fixture Coinbase connection with made-up wallets (screenshots only).
414 if env["BUCKSLEY_FIXTURE_COINBASE"] != nil, !model.workspace.connections.contains(where: { $0.kind == .coinbase }) {
415 let connection = Connection(kind: .coinbase, name: "Coinbase (test fixture)")
416 _ = try? model.store.update { $0.connections.append(connection) }
417 _ = try? sync.apply(Coinbase.fixturePull(connectionID: connection.id), to: connection)
418 }
419 // Adds the first N suggested budgets the way the Add budget button does, for screenshots.
420 if let count = env["BUCKSLEY_ACCEPT_SUGGESTIONS"].flatMap(Int.init), (try? model.store.load())?.budgets.isEmpty == true,
421 let ledger = try? model.store.ledger() {
422 let picks = ledger.budgetSuggestions().prefix(count)
423 _ = try? model.store.update { ws in
424 for s in picks { ws.budgets.append(Budget(categoryID: s.categoryID, amount: s.amount, rollover: ws.budgets.isEmpty)) }
425 }
426 }
427 model.reload(force: true)
428 }
429}
430
431@MainActor
432enum ScreenTour {
433 static func capture(into dir: URL, model: AppModel) async {
434 try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
435 try? await Task.sleep(for: .seconds(2))
436 if ProcessInfo.processInfo.environment["BUCKSLEY_TOUR_SUPPORT_CARD"] != nil { captureSupportCard(into: dir) }
437 let themes = ProcessInfo.processInfo.environment["BUCKSLEY_SNAPSHOT_THEMES"].map { $0.split(separator: ",").compactMap { BucksleyTheme(rawValue: String($0)) } } ?? BucksleyTheme.allCases
438 let screens: [Screen] = Screen.main + [.agents, .settings]
439 // One real question through Ask Bucksley so the Ask screen shows a live answer.
440 if let question = ProcessInfo.processInfo.environment["BUCKSLEY_TOUR_QUESTION"] {
441 let ask = AskModel.shared
442 ask.turns = [AskModel.Turn(question: question)]
443 do {
444 let provider = AskBucksley.provider(for: model.workspace.settings)
445 let answer = try await AskBucksley().ask(question, ledger: model.ledger, provider: provider, model: model.workspace.settings.model(for: provider))
446 ask.turns[0].answer = answer.text; ask.turns[0].provider = answer.provider; ask.turns[0].transactionIDs = answer.transactionIDs; ask.turns[0].offersBudgetPlan = answer.offersBudgetPlan
447 } catch { ask.turns[0].answer = error.localizedDescription }
448 }
449 for theme in themes {
450 BucksleyPreferences.store.set(theme.rawValue, forKey: BucksleyTheme.preferenceKey)
451 AppIcon.apply(theme)
452 for appearance in [BucksleyAppearance.light, .dark] {
453 BucksleyPreferences.store.set(appearance.rawValue, forKey: BucksleyAppearance.preferenceKey)
454 NSApp.appearance = NSAppearance(named: appearance == .dark ? .darkAqua : .aqua)
455 for screen in screens {
456 model.selection = screen
457 if screen == .transactions { model.selectedTransactionID = model.ledger.entries.first?.id }
458 try? await Task.sleep(for: .seconds(1.2))
459 WindowSnapshot.write(to: dir.appendingPathComponent("\(theme.rawValue)-\(appearance.rawValue)-\(name(screen)).png"))
460 if screen == .transactions {
461 TransactionsFilter.shared.unreviewedOnly = true
462 try? await Task.sleep(for: .seconds(1.2))
463 WindowSnapshot.write(to: dir.appendingPathComponent("\(theme.rawValue)-\(appearance.rawValue)-\(name(screen))-review.png"))
464 TransactionsFilter.shared.unreviewedOnly = false
465 }
466 if screen == .settings {
467 model.tourAnchor = UnitPoint(x: 0.5, y: 0.42)
468 try? await Task.sleep(for: .seconds(1.2))
469 WindowSnapshot.write(to: dir.appendingPathComponent("\(theme.rawValue)-\(appearance.rawValue)-\(name(screen))-middle.png"))
470 model.tourAnchor = nil
471 }
472 if screen == .budgets {
473 for step in 0..<SmartBudgetWalkthrough.steps.count {
474 SmartBudgetFlow.shared.presented = true; SmartBudgetFlow.shared.step = step
475 try? await Task.sleep(for: .seconds(1.2))
476 WindowSnapshot.write(to: dir.appendingPathComponent("\(theme.rawValue)-\(appearance.rawValue)-5-smart-budgets-\(step + 1).png"))
477 }
478 SmartBudgetFlow.shared.presented = false
479 }
480 if screen == .settings || screen == .accounts || screen == .budgets || screen == .cashFlow || screen == .overview {
481 model.tourScrolledToEnd = true
482 try? await Task.sleep(for: .seconds(1.2))
483 WindowSnapshot.write(to: dir.appendingPathComponent("\(theme.rawValue)-\(appearance.rawValue)-\(name(screen))-end.png"))
484 model.tourScrolledToEnd = false
485 }
486 }
487 }
488 }
489 BucksleyPreferences.store.set(BucksleyTheme.defaultPreference.rawValue, forKey: BucksleyTheme.preferenceKey)
490 BucksleyPreferences.store.set(BucksleyAppearance.system.rawValue, forKey: BucksleyAppearance.preferenceKey)
491 try? "done".write(to: dir.appendingPathComponent("DONE"), atomically: true, encoding: .utf8)
492 NSApp.terminate(nil)
493 }
494
495 /// The reminder card with its Later and Don't show again buttons (headless render, dark theme).
496 static func captureSupportCard(into dir: URL) {
497 let renderer = ImageRenderer(content: SupportSheet(isReminder: true).environment(\.colorScheme, .dark))
498 renderer.scale = 2
499 guard let image = renderer.cgImage else { return }
500 try? NSBitmapImageRep(cgImage: image).representation(using: .png, properties: [:])?.write(to: dir.appendingPathComponent("support-card.png"))
501 }
502
503 static func name(_ s: Screen) -> String {
504 switch s {
505 case .overview: "1-overview"; case .accounts: "2-accounts"; case .investments: "2b-investments"; case .transactions: "3-transactions"; case .cashFlow: "3b-cash-flow"; case .categories: "4-categories-rules"
506 case .budgets: "5-budgets"; case .recurring: "6-recurring"; case .ask: "7-ask"; case .agents: "8-agents"; case .settings: "9-settings"
507 }
508 }
509}
510
511@MainActor
512enum WindowSnapshot {
513 static func write(to url: URL) {
514 guard let window = NSApp.windows.first(where: { $0.isVisible && $0.contentView != nil }),
515 let frameView = window.contentView?.superview, let layer = frameView.layer else { return }
516 let scale = window.backingScaleFactor
517 let size = frameView.bounds.size
518 guard let context = CGContext(data: nil, width: Int(size.width * scale), height: Int(size.height * scale), bitsPerComponent: 8,
519 bytesPerRow: 0, space: CGColorSpaceCreateDeviceRGB(),
520 bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue) else { return }
521 window.effectiveAppearance.performAsCurrentDrawingAppearance { context.setFillColor(NSColor.windowBackgroundColor.cgColor) }
522 context.fill(CGRect(x: 0, y: 0, width: size.width * scale, height: size.height * scale))
523 context.scaleBy(x: scale, y: scale)
524 layer.render(in: context)
525 guard let image = context.makeImage() else { return }
526 try? NSBitmapImageRep(cgImage: image).representation(using: .png, properties: [:])?.write(to: url)
527 }
528}
529#endif