import SwiftUI import AppKit import OSLog import BucksleyKit import BucksleyUI /// `Bucksley --mcp` runs the STDIO MCP server on the same local store (Inkspring pattern). /// `Bucksley --sync` syncs every bank connection once and prints what each one sent. /// Without either, the normal Mac app starts. @main enum Entry { static func main() { SandboxMigration.run() AskAgent.install() // `Bucksley --ask "question"` prints Ask Bucksley's answer with whoever is set to answer. if let i = CommandLine.arguments.firstIndex(of: "--ask"), i + 1 < CommandLine.arguments.count { let question = CommandLine.arguments[i + 1] let semaphore = DispatchSemaphore(value: 0) Task.detached { do { let ledger = try WorkspaceStore().ledger() let settings = ledger.workspace.settings let provider = AskBucksley.provider(for: settings) let answer = try await AskBucksley().ask(question, ledger: ledger, provider: provider, model: settings.model(for: provider)) print("[\(answer.provider)] \(answer.text)\nLinked: \(answer.transactionIDs.count) · budget button: \(answer.offersBudgetPlan)") } catch { FileHandle.standardError.write(Data("Ask failed: \(error.localizedDescription)\n".utf8)) } semaphore.signal() } semaphore.wait() exit(0) } let readOnly = CommandLine.arguments.contains("--mcp-ask") if CommandLine.arguments.contains("--mcp") || readOnly { let semaphore = DispatchSemaphore(value: 0) Task.detached { do { await MCPServer(store: try WorkspaceStore(), readOnly: readOnly).run() } catch { FileHandle.standardError.write(Data("Could not open the Bucksley store: \(error)\n".utf8)) } semaphore.signal() } semaphore.wait() exit(0) } if CommandLine.arguments.contains("--sync") { let semaphore = DispatchSemaphore(value: 0) Task.detached { do { let store = try WorkspaceStore() let report = await BankSync(store: store).syncAll() let ws = try store.load() var lines = ["Synced: \(report.synced.joined(separator: ", ")) · \(report.added) new, \(report.updated) updated"] for (name, error) in report.failed { lines.append("Failed: \(name): \(error)") } for c in ws.connections { lines.append("\(c.name): \(ws.accounts.filter { $0.connectionID == c.id }.count) accounts" + (c.lastError.map { " · \($0)" } ?? "")) } for a in ws.accounts { lines.append(" \(a.institution) · \(a.name) · \(a.kind.title)") } print(lines.joined(separator: "\n")) } catch { FileHandle.standardError.write(Data("Could not sync: \(error)\n".utf8)) } semaphore.signal() } semaphore.wait() exit(0) } BucksleyMacApp.main() } } struct BucksleyMacApp: App { @NSApplicationDelegateAdaptor(AppDelegate.self) private var delegate @State private var model = AppModel() @StateObject private var updates = AppUpdates() var body: some Scene { WindowGroup("Bucksley") { ThemedRoot { ContentView() .environment(model) .environmentObject(updates) .frame(minWidth: 980, idealWidth: 1280, minHeight: 640, idealHeight: 820) .task { await model.start() } } .defaultAppStorage(BucksleyPreferences.store) } .defaultSize(width: 1280, height: 820) .commands { CommandGroup(after: .appInfo) { if updates.isAvailable { CheckForUpdatesButton(updates: updates) } } CommandGroup(replacing: .appSettings) { Button("Settings…") { model.selection = .settings }.keyboardShortcut(",") } CommandGroup(after: .newItem) { Button("Sync Banks Now") { Task { await model.syncBanks() } }.keyboardShortcut("r") Button("Import CSV…") { model.selection = .settings; model.wantsCSVImport = true } } CommandGroup(after: .sidebar) { ForEach(Array(Screen.main.enumerated()), id: \.offset) { i, screen in Button(screen.title) { model.selection = screen }.keyboardShortcut(KeyEquivalent(Character("\(i + 1)"))) } } } } } final class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ notification: Notification) { NSApp.registerForRemoteNotifications() AppIcon.apply(BucksleyTheme(preference: BucksleyPreferences.store.string(forKey: BucksleyTheme.preferenceKey))) } func application(_ application: NSApplication, didReceiveRemoteNotification userInfo: [String: Any]) { Task { @MainActor in await AppModel.shared?.pullFromICloud() } } func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { false } } /// The Mac's Dock icon follows the theme. (macOS has no persistent alternate icons for a signed /// app; changing the bundle's icon file would break its signature, so only the running icon changes.) @MainActor enum AppIcon { static func apply(_ theme: BucksleyTheme) { guard let name = theme.iconName, let image = NSImage(named: name) else { NSApp.applicationIconImage = nil; return } NSApp.applicationIconImage = image } } enum Screen: Hashable, Identifiable { case overview, accounts, investments, transactions, cashFlow, categories, budgets, recurring, ask, agents, settings static let main: [Screen] = [.overview, .accounts, .investments, .transactions, .cashFlow, .categories, .budgets, .recurring, .ask] var id: Self { self } var title: String { switch self { case .overview: "Overview" case .accounts: "Accounts" case .investments: "Investments" case .transactions: "Transactions" case .cashFlow: "Cash Flow" case .categories: "Categories & Rules" case .budgets: "Budgets" case .recurring: "Recurring" case .ask: "Ask Bucksley" case .agents: "Agents" case .settings: "Settings" } } /// Which of the theme's chart colors tints the sidebar icon. var colorIndex: Int? { switch self { case .overview: 0 case .accounts: 2 case .investments: 1 case .transactions: 3 case .cashFlow: 1 case .categories: 4 case .budgets: 1 case .recurring: 2 case .ask: 0 case .agents, .settings: nil } } var symbol: String { switch self { case .overview: "chart.line.uptrend.xyaxis" case .accounts: "building.columns" case .investments: "chart.bar.xaxis" case .transactions: "list.bullet.rectangle" case .categories: "square.grid.2x2" case .budgets: "chart.pie" case .recurring: "repeat" case .ask: "sparkles" case .cashFlow: "arrow.left.arrow.right.circle" case .agents: "terminal" case .settings: "gearshape" } } } @MainActor @Observable final class AppModel { static weak var shared: AppModel? let store: WorkspaceStore let cloud: CloudSync var ledger: Ledger var selection: Screen = .overview var syncing = false var lastReport: BankSync.Report? var cloudStatus = "Not synced yet" var message: String? var wantsCSVImport = false /// Bumped after Keychain changes, so views that read key state redraw. var keysVersion = 0 var selectedTransactionID: String? /// Screenshot tour only: shows the end of the current screen. var tourScrolledToEnd = false var tourAnchor: UnitPoint? /// Opening a transaction is reviewing it: it leaves the review queue right away. func open(_ entry: LedgerEntry) { selectedTransactionID = entry.id if !entry.reviewed { edit(entry.id) { $0.reviewed = true } } } var range = 90 private var started = false private var loadedVersion: Date? init() { let store = try! WorkspaceStore() self.store = store cloud = CloudSync(store: store) ledger = (try? store.ledger()) ?? Ledger(workspace: Workspace(), transactions: [], edits: [:], balances: []) Self.shared = self } var workspace: Workspace { ledger.workspace } func start() async { guard !started else { return } started = true reload(force: true) #if DEBUG await DebugSetup.run(model: self) if let dir = ProcessInfo.processInfo.environment["BUCKSLEY_SNAPSHOT_DIR"] { Task { await ScreenTour.capture(into: URL(fileURLWithPath: dir), model: self) } return } #endif // Agents change the store from the --mcp process; pick up their edits. Task { while !Task.isCancelled { try? await Task.sleep(for: .seconds(3)); reload() } } Task { if cloud.isAvailable { try? await cloud.subscribe() } await pullFromICloud() while !Task.isCancelled { if needsBankSync { await syncBanks() } try? await Task.sleep(for: .seconds(300)) await pullFromICloud() } } } var needsBankSync: Bool { guard workspace.connections.contains(where: { $0.kind.syncs }) else { return false } guard let last = workspace.settings.lastSyncAt else { return true } return Date.now.timeIntervalSince(last) > Double(workspace.settings.syncEveryHours) * 3600 } /// Re-reads the store when its files changed on disk. func reload(force: Bool = false) { let version = store.lastModified() guard force || version == nil || version != loadedVersion else { return } do { ledger = try store.ledger() loadedVersion = version refreshInsights() } catch { Self.log.error("Could not read the store: \(error.localizedDescription, privacy: .public)") } } static let log = Logger(subsystem: "com.protomota.bucksley", category: "app") func syncBanks() async { guard !syncing else { return } syncing = true; defer { syncing = false } lastReport = await BankSync(store: store).syncAll() reload(force: true) shareSoon() } /// Reads the iPhone's edits (review inbox, recategorizing, notes) and any Apple Wallet import. func pullFromICloud() async { guard cloud.isAvailable else { cloudStatus = "iCloud sync needs the signed app"; return } guard await cloud.accountReady() else { cloudStatus = "Sign in to iCloud to sync with iPhone"; return } do { let changes = try await cloud.pullChanges(into: store) if let wallet = changes.wallet { try WalletImport.apply(wallet, store: store) } if changes.edits > 0 || changes.wallet != nil { reload(force: true); shareSoon() } cloudStatus = "Synced with iCloud " + Date.now.formatted(date: .omitted, time: .shortened) } catch { cloudStatus = "iCloud: \(error.localizedDescription)" } } private var sharePush: Task? /// Pushes edits and a fresh snapshot to iCloud after a short pause, so a burst of edits sends once. func shareSoon() { sharePush?.cancel() sharePush = Task { [store, cloud] in try? await Task.sleep(for: .seconds(1.5)) guard !Task.isCancelled, cloud.isAvailable, let ws = try? store.load(), ws.settings.shareWithIPhone else { return } do { try await cloud.pushEdits(from: store) try await cloud.pushSnapshot(try CloudSync.snapshot(from: store)) _ = try? store.update { $0.settings.lastSharedAt = .now } cloudStatus = "Synced with iCloud " + Date.now.formatted(date: .omitted, time: .shortened) } catch { cloudStatus = "iCloud: \(error.localizedDescription)" Self.log.error("Could not share with iCloud: \(error.localizedDescription, privacy: .public)") } } } // MARK: Edits func edit(_ id: String, _ change: (inout TransactionEdit) -> Void) { do { try store.edit(id, change); reload(force: true); shareSoon(); SupportPrompt.recordCoreAction() } catch { message = error.localizedDescription } } func updateWorkspace(_ change: (inout Workspace) -> Void) { do { try store.update(change); reload(force: true); shareSoon() } catch { message = error.localizedDescription } } func keysChanged() { keysVersion += 1 } var reviewCount: Int { ledger.reviewQueue.count } // MARK: Insights /// Flags, refund matches and category suggestions, worked out once per reload. struct Insights { var flags: [Ledger.Flag] = [] var flagByEntry: [String: Ledger.Flag] = [:] var refunds: [Ledger.RefundMatch] = [] var refundByEntry: [String: Ledger.RefundMatch] = [:] var suggestions: [String: Ledger.CategorySuggestion] = [:] var reviewOrder: [LedgerEntry] = [] } var insights = Insights() private var modelSuggestions: [String: Ledger.CategorySuggestion] = [:] private var suggesting: Task? func refreshInsights() { var i = Insights() i.flags = ledger.flags() i.flagByEntry = Dictionary(i.flags.map { ($0.entryID, $0) }, uniquingKeysWith: { a, _ in a }) i.refunds = ledger.refundMatches() i.refundByEntry = Dictionary(i.refunds.map { ($0.refundID, $0) }, uniquingKeysWith: { a, _ in a }) let open = Set(ledger.entries.filter(ledger.needsCategory).map(\.id)) i.suggestions = modelSuggestions.filter { open.contains($0.key) } for s in ledger.historySuggestions() { i.suggestions[s.entryID] = s } i.reviewOrder = ledger.prioritizedReviewQueue() insights = i suggestWithAppleIntelligence(missing: ledger.entries.filter { ledger.needsCategory($0) && i.suggestions[$0.id] == nil && modelSuggestions[$0.id] == nil }) } /// Asks the on-device model about uncategorized transactions history can't place, a batch at a time. private func suggestWithAppleIntelligence(missing: [LedgerEntry]) { guard AskBucksley.appleModelAvailable, !missing.isEmpty, suggesting == nil else { return } let batch = Array(missing.prefix(25)), categories = workspace.categories suggesting = Task { let found = await AskBucksley.suggestCategories(for: batch, categories: categories) for s in found { modelSuggestions[s.entryID] = s } // Mark the rest as asked so they aren't sent again this session. for e in batch where modelSuggestions[e.id] == nil { modelSuggestions[e.id] = Ledger.CategorySuggestion(entryID: e.id, categoryID: "", reason: "") } suggesting = nil refreshInsights() } } func suggestion(for id: String) -> Ledger.CategorySuggestion? { insights.suggestions[id].flatMap { $0.categoryID.isEmpty ? nil : $0 } } /// Links a refund to its purchase and files it in the purchase's category. func acceptRefund(_ match: Ledger.RefundMatch) { guard let purchase = ledger.entry(match.purchaseID) else { return } edit(match.refundID) { $0.refundOf = match.purchaseID; $0.categoryID = purchase.categoryID } } } #if DEBUG /// Debug builds only: `BUCKSLEY_SNAPSHOT_DIR=/path` walks every screen in every theme, light and /// dark, and writes one PNG of the app's own window per view (`--.png`). /// Lets agents capture the running app headlessly, even with the display locked. /// Debug builds only, for test runs and screenshots: `BUCKSLEY_DEMO_CONNECT=1` connects the public /// SimpleFIN demo bank through the real connector; `BUCKSLEY_IMPORT_CSV=/path.csv` imports a CSV /// through the real importer; `BUCKSLEY_FIXTURE_BALANCES="Account name=123.45;…"` sets CSV balances. @MainActor enum DebugSetup { static func run(model: AppModel) async { let env = ProcessInfo.processInfo.environment let sync = BankSync(store: model.store) if env["BUCKSLEY_DEMO_CONNECT"] != nil, !model.workspace.connections.contains(where: { $0.kind == .simplefin }) { do { _ = try await sync.connectSimpleFIN(setupToken: nil) } catch { model.message = "SimpleFIN demo: \(error.localizedDescription)" } } if let path = env["BUCKSLEY_IMPORT_CSV"], !model.workspace.connections.contains(where: { $0.kind == .csv }), let text = try? String(contentsOfFile: path, encoding: .utf8) { do { _ = try sync.importCSV(text, fileName: URL(fileURLWithPath: path).lastPathComponent) } catch { model.message = "CSV: \(error.localizedDescription)" } } if let spec = env["BUCKSLEY_FIXTURE_BALANCES"] { for pair in spec.split(separator: ";") { let parts = pair.split(separator: "=", maxSplits: 1).map(String.init) guard parts.count == 2, let value = Decimal(money: parts[1]), let account = (try? model.store.load())?.accounts.first(where: { $0.name == parts[0] }) else { continue } try? sync.setManualBalance(account.id, balance: value) } } // Test fixture positions: "Account name=SYM:Name:shares:value:cost|…;…" (screenshots only). if let spec = env["BUCKSLEY_FIXTURE_HOLDINGS"] { for entry in spec.split(separator: ";") { let parts = entry.split(separator: "=", maxSplits: 1).map(String.init) guard parts.count == 2 else { continue } let holdings = parts[1].split(separator: "|").enumerated().compactMap { i, h -> Holding? in let f = h.split(separator: ":").map(String.init) guard f.count == 5, let value = Decimal(money: f[3]) else { return nil } return Holding(id: "fixture-\(i)", symbol: f[0], name: f[1], shares: Decimal(string: f[2]), marketValue: value, costBasis: Decimal(money: f[4])) } _ = try? model.store.update { ws in if let i = ws.accounts.firstIndex(where: { $0.name == parts[0] }) { ws.accounts[i].holdings = holdings } } } } // Test fixture: imported rows on or after this day come in unreviewed, like a fresh bank sync. if let since = env["BUCKSLEY_FIXTURE_UNREVIEWED_SINCE"], let ledger = try? model.store.ledger() { for e in ledger.entries where e.day >= since && e.reviewed { _ = try? model.store.edit(e.id) { $0.reviewed = false } } } // Test fixture Coinbase connection with made-up wallets (screenshots only). if env["BUCKSLEY_FIXTURE_COINBASE"] != nil, !model.workspace.connections.contains(where: { $0.kind == .coinbase }) { let connection = Connection(kind: .coinbase, name: "Coinbase (test fixture)") _ = try? model.store.update { $0.connections.append(connection) } _ = try? sync.apply(Coinbase.fixturePull(connectionID: connection.id), to: connection) } // Adds the first N suggested budgets the way the Add budget button does, for screenshots. if let count = env["BUCKSLEY_ACCEPT_SUGGESTIONS"].flatMap(Int.init), (try? model.store.load())?.budgets.isEmpty == true, let ledger = try? model.store.ledger() { let picks = ledger.budgetSuggestions().prefix(count) _ = try? model.store.update { ws in for s in picks { ws.budgets.append(Budget(categoryID: s.categoryID, amount: s.amount, rollover: ws.budgets.isEmpty)) } } } model.reload(force: true) } } @MainActor enum ScreenTour { static func capture(into dir: URL, model: AppModel) async { try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) try? await Task.sleep(for: .seconds(2)) if ProcessInfo.processInfo.environment["BUCKSLEY_TOUR_SUPPORT_CARD"] != nil { captureSupportCard(into: dir) } let themes = ProcessInfo.processInfo.environment["BUCKSLEY_SNAPSHOT_THEMES"].map { $0.split(separator: ",").compactMap { BucksleyTheme(rawValue: String($0)) } } ?? BucksleyTheme.allCases let screens: [Screen] = Screen.main + [.agents, .settings] // One real question through Ask Bucksley so the Ask screen shows a live answer. if let question = ProcessInfo.processInfo.environment["BUCKSLEY_TOUR_QUESTION"] { let ask = AskModel.shared ask.turns = [AskModel.Turn(question: question)] do { let provider = AskBucksley.provider(for: model.workspace.settings) let answer = try await AskBucksley().ask(question, ledger: model.ledger, provider: provider, model: model.workspace.settings.model(for: provider)) ask.turns[0].answer = answer.text; ask.turns[0].provider = answer.provider; ask.turns[0].transactionIDs = answer.transactionIDs; ask.turns[0].offersBudgetPlan = answer.offersBudgetPlan } catch { ask.turns[0].answer = error.localizedDescription } } for theme in themes { BucksleyPreferences.store.set(theme.rawValue, forKey: BucksleyTheme.preferenceKey) AppIcon.apply(theme) for appearance in [BucksleyAppearance.light, .dark] { BucksleyPreferences.store.set(appearance.rawValue, forKey: BucksleyAppearance.preferenceKey) NSApp.appearance = NSAppearance(named: appearance == .dark ? .darkAqua : .aqua) for screen in screens { model.selection = screen if screen == .transactions { model.selectedTransactionID = model.ledger.entries.first?.id } try? await Task.sleep(for: .seconds(1.2)) WindowSnapshot.write(to: dir.appendingPathComponent("\(theme.rawValue)-\(appearance.rawValue)-\(name(screen)).png")) if screen == .transactions { TransactionsFilter.shared.unreviewedOnly = true try? await Task.sleep(for: .seconds(1.2)) WindowSnapshot.write(to: dir.appendingPathComponent("\(theme.rawValue)-\(appearance.rawValue)-\(name(screen))-review.png")) TransactionsFilter.shared.unreviewedOnly = false } if screen == .settings { model.tourAnchor = UnitPoint(x: 0.5, y: 0.42) try? await Task.sleep(for: .seconds(1.2)) WindowSnapshot.write(to: dir.appendingPathComponent("\(theme.rawValue)-\(appearance.rawValue)-\(name(screen))-middle.png")) model.tourAnchor = nil } if screen == .budgets { for step in 0.. String { switch s { 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" case .budgets: "5-budgets"; case .recurring: "6-recurring"; case .ask: "7-ask"; case .agents: "8-agents"; case .settings: "9-settings" } } } @MainActor enum WindowSnapshot { static func write(to url: URL) { guard let window = NSApp.windows.first(where: { $0.isVisible && $0.contentView != nil }), let frameView = window.contentView?.superview, let layer = frameView.layer else { return } let scale = window.backingScaleFactor let size = frameView.bounds.size guard let context = CGContext(data: nil, width: Int(size.width * scale), height: Int(size.height * scale), bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue) else { return } window.effectiveAppearance.performAsCurrentDrawingAppearance { context.setFillColor(NSColor.windowBackgroundColor.cgColor) } context.fill(CGRect(x: 0, y: 0, width: size.width * scale, height: size.height * scale)) context.scaleBy(x: scale, y: scale) layer.render(in: context) guard let image = context.makeImage() else { return } try? NSBitmapImageRep(cgImage: image).representation(using: .png, properties: [:])?.write(to: url) } } #endif