Branchwell

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

Raw 34.4 KB on 07e410940d4dd3ce1e1e51286babef75b272eb4f
1import SwiftUI
2import BucksleyKit
3import BucksleyUI
4
5struct OverviewScreen: View {
6 @Environment(AppModel.self) private var model
7 @Environment(\.palette) private var palette
8 @State private var question = ""
9
10 var body: some View {
11 @Bindable var model = model
12 let ledger = model.ledger
13 ScreenScaffold("Overview", subtitle: Date.now.formatted(.dateTime.weekday(.wide).month(.wide).day())) {
14 PillPicker([(30, "1M"), (90, "3M"), (365, "1Y"), (730, "All")], selection: $model.range)
15 } content: {
16 if ledger.visibleAccounts.isEmpty {
17 ConnectFirst()
18 } else {
19 VStack(alignment: .leading, spacing: 18) {
20 hero(ledger)
21 NetWorthChart(ledger.netWorthSeries(days: model.range)).frame(height: 230)
22 HStack(alignment: .top, spacing: 18) {
23 Panel {
24 VStack(alignment: .leading, spacing: 12) {
25 SectionHeader("Spending in \(MonthKey.title(MonthKey.current).components(separatedBy: " ").first ?? "")") {
26 Button("Details") { model.selection = .budgets }.buttonStyle(.plain).font(.system(size: 12, weight: .semibold)).foregroundStyle(palette.accent)
27 }
28 SpendingChart(ledger.spending(), workspace: ledger.workspace)
29 }
30 }
31 Panel {
32 VStack(alignment: .leading, spacing: 10) {
33 SectionHeader("Budgets") {
34 Button("All budgets") { model.selection = .budgets }.buttonStyle(.plain).font(.system(size: 12, weight: .semibold)).foregroundStyle(palette.accent)
35 }
36 let budgets = ledger.budgetStatus()
37 if budgets.isEmpty {
38 Text("No budgets yet. Bucksley can suggest them from your spending.").font(.system(size: 13)).foregroundStyle(palette.muted)
39 Button("See suggestions") { model.selection = .budgets }.buttonStyle(SecondaryButtonStyle())
40 }
41 ForEach(budgets.prefix(4)) { status in
42 BudgetProgress(status, name: ledger.budgetName(status.id), colorIndex: ledger.workspace.category(status.id)?.colorIndex ?? 1)
43 }
44 }
45 }
46 }
47 HStack(alignment: .top, spacing: 18) {
48 Panel {
49 VStack(alignment: .leading, spacing: 4) {
50 SectionHeader("Recent transactions") {
51 Button("See all") { model.selection = .transactions }.buttonStyle(.plain).font(.system(size: 12, weight: .semibold)).foregroundStyle(palette.accent)
52 }
53 ForEach(ledger.entries.prefix(7)) { entry in
54 Button { model.open(entry); model.selection = .transactions } label: { TransactionRow(entry, workspace: ledger.workspace) }
55 .buttonStyle(.plain)
56 }
57 }
58 }
59 .frame(maxWidth: .infinity)
60 VStack(alignment: .leading, spacing: 18) {
61 WorthALook()
62 if let tip = AskBucksley.suggestion(ledger) {
63 Panel {
64 VStack(alignment: .leading, spacing: 8) {
65 Label("Bucksley noticed", systemImage: "sparkles").font(.system(size: 12, weight: .bold)).foregroundStyle(palette.accent)
66 Text(tip).font(palette.theme == .almanac ? .system(size: 15, design: .serif) : .system(size: 14)).fixedSize(horizontal: false, vertical: true)
67 }
68 }
69 }
70 askField
71 }
72 .frame(width: 320)
73 }
74 }
75 }
76 }
77 }
78
79 @ViewBuilder func hero(_ ledger: Ledger) -> some View {
80 let change = ledger.change(days: model.range)
81 let start = ledger.netWorth - change
82 let pct = start != 0 ? (change / abs(start)).double * 100 : 0
83 VStack(alignment: .leading, spacing: 6) {
84 if palette.theme == .almanac {
85 Text(almanacHeadline(ledger)).font(.system(size: 26, weight: .medium, design: .serif)).tracking(-0.3).fixedSize(horizontal: false, vertical: true)
86 } else {
87 Text(palette.theme == .afterhours ? "NET WORTH" : "Net worth").font(palette.theme == .afterhours ? .system(size: 11, weight: .bold) : .system(size: 13, weight: .medium))
88 .tracking(palette.theme == .afterhours ? 1.1 : 0).foregroundStyle(palette.muted)
89 }
90 HStack(alignment: .firstTextBaseline, spacing: 12) {
91 HeroMoney(ledger.netWorth, size: palette.theme == .almanac ? 30 : 42)
92 Text("\(Money.format(change, cents: false, signed: true)) · \(String(format: "%.1f", pct))%")
93 .font(palette.figure(13, weight: .medium)).foregroundStyle(change >= 0 ? palette.gain : palette.loss)
94 Text(rangeLabel).font(.system(size: 12)).foregroundStyle(palette.muted)
95 }
96 if palette.theme == .afterhours {
97 HStack(spacing: 18) {
98 ForEach(AccountGroup.allCases, id: \.self) { g in
99 let total = ledger.total(g)
100 if total != 0 {
101 HStack(spacing: 6) {
102 RoundedRectangle(cornerRadius: 2).fill(palette.color(for: g)).frame(width: 9, height: 9)
103 Text(g.title).font(.system(size: 12)).foregroundStyle(palette.muted)
104 Text(Money.short(total)).font(palette.figure(12, weight: .medium))
105 }
106 }
107 }
108 }
109 }
110 }
111 }
112
113 var rangeLabel: String {
114 switch model.range { case 30: "past month"; case 90: "past 3 months"; case 365: "past year"; default: "all time" }
115 }
116
117 func almanacHeadline(_ ledger: Ledger) -> String {
118 let month = ledger.change(days: Int(DayKey.today.suffix(2)) ?? 30), year = ledger.change(days: 365)
119 let dir = month >= 0 ? "up" : "down"
120 let yearStart = DayKey.adding(-365, to: DayKey.today)
121 let since = ledger.historyStart.flatMap { $0 > yearStart ? DayKey.date($0) : nil }
122 let span = since.map { "since " + $0.formatted(.dateTime.month(.wide)) } ?? "on the year"
123 return "Net worth is \(dir) \(Money.format(abs(month), cents: false)) this month, and \(Money.format(year, cents: false, signed: true)) \(span)."
124 }
125
126 var askField: some View {
127 HStack(spacing: 8) {
128 Image(systemName: "sparkles").foregroundStyle(palette.accent)
129 TextField("\(AskBucksley.title(for: AskBucksley.provider(for: model.workspace.settings))) about your money…", text: $question)
130 .textFieldStyle(.plain).font(.system(size: 13))
131 .onSubmit { send() }
132 Button { send() } label: { Image(systemName: "arrow.up").font(.system(size: 12, weight: .bold)).frame(width: 26, height: 26) }
133 .buttonStyle(.plain).foregroundStyle(palette.accentText).background(palette.accent, in: Circle())
134 .accessibilityLabel("Ask")
135 }
136 .padding(.leading, 14).padding(.trailing, 5).padding(.vertical, 5)
137 .background(palette.card, in: Capsule())
138 .overlay { Capsule().strokeBorder(palette.line) }
139 }
140
141 func send() {
142 let q = question.trimmingCharacters(in: .whitespaces)
143 guard !q.isEmpty else { return }
144 AskModel.shared.pending = q
145 question = ""
146 model.selection = .ask
147 }
148}
149
150struct AccountsScreen: View {
151 @Environment(AppModel.self) private var model
152 @Environment(\.palette) private var palette
153 @State private var selected: String?
154
155 var body: some View {
156 let ledger = model.ledger
157 ScreenScaffold("Accounts", subtitle: "\(ledger.visibleAccounts.count) accounts · net worth \(Money.format(ledger.netWorth, cents: false))") {
158 Button("Add account") { model.selection = .settings }.buttonStyle(SecondaryButtonStyle())
159 } content: {
160 if ledger.workspace.accounts.isEmpty { ConnectFirst() }
161 VStack(alignment: .leading, spacing: 28) {
162 HStack(spacing: 14) {
163 stat("Assets", ledger.assets)
164 stat("Debts", ledger.debts)
165 stat("Net worth", ledger.netWorth)
166 }
167 ForEach(AccountGroup.allCases, id: \.self) { group in
168 let accounts = ledger.workspace.accounts.filter { $0.kind.group == group }
169 if !accounts.isEmpty {
170 VStack(alignment: .leading, spacing: 10) {
171 SectionHeader(group.title) { MoneyText(ledger.total(group), size: 13, cents: false) }
172 ForEach(accounts) { account in
173 AccountRow(account: account, open: Binding(get: { selected == account.id }, set: { selected = $0 ? account.id : nil }))
174 }
175 }
176 }
177 }
178 }
179 }
180 }
181
182 func stat(_ label: String, _ value: Decimal) -> some View {
183 Panel {
184 VStack(alignment: .leading, spacing: 4) {
185 Text(label).font(.system(size: 12, weight: .medium)).foregroundStyle(palette.muted)
186 MoneyText(value, size: 22, cents: false, colored: label == "Debts")
187 }
188 }
189 }
190
191}
192
193/// One account on the Accounts screen: a roomy row that lights up on hover and opens in place to
194/// show its balance history and settings.
195struct AccountRow: View {
196 @Environment(AppModel.self) private var model
197 @Environment(\.palette) private var palette
198 let account: Account
199 @Binding var open: Bool
200 @State private var hovering = false
201
202 var body: some View {
203 let ledger = model.ledger
204 let history = ledger.accountSeries(account.id, days: 60)
205 let connection = ledger.workspace.connections.first { $0.id == account.connectionID }
206 let tint = account.kind.group == .credit ? 4 : account.kind.group == .investments ? 0 : account.kind.group == .other ? 2 : 1
207 VStack(alignment: .leading, spacing: 14) {
208 Button { withAnimation(.snappy) { open.toggle() } } label: {
209 HStack(spacing: 14) {
210 MerchantBadge(name: account.institution, colorIndex: tint, size: 38, brand: palette.color(for: account))
211 VStack(alignment: .leading, spacing: 4) {
212 HStack(spacing: 6) {
213 Text(account.displayName).font(.system(size: 14, weight: .semibold)).lineLimit(1)
214 if account.hidden { Text("Hidden").font(.system(size: 10, weight: .bold)).foregroundStyle(palette.muted) }
215 }
216 Text([account.institution, account.kind.title, connection?.kind.title].compactMap { $0 }.reduce(into: [String]()) { if !$0.contains($1) { $0.append($1) } }.joined(separator: " · "))
217 .font(.system(size: 12)).foregroundStyle(palette.muted).lineLimit(1)
218 }
219 Spacer(minLength: 16)
220 if palette.theme == .afterhours, history.count > 4 {
221 Sparkline(stride(from: 0, to: history.count, by: max(1, history.count / 14)).map { history[$0].balance.double }, colorIndex: tint)
222 }
223 VStack(alignment: .trailing, spacing: 4) {
224 MoneyText(account.balance, size: 16)
225 Text("as of " + account.balanceDate.formatted(date: .abbreviated, time: .omitted)).font(.system(size: 11)).foregroundStyle(palette.muted)
226 }
227 Image(systemName: "chevron.right")
228 .font(.system(size: 11, weight: .bold))
229 .foregroundStyle(hovering || open ? palette.accent : palette.muted)
230 .rotationEffect(.degrees(open ? 90 : 0))
231 .frame(width: 16)
232 }
233 .contentShape(Rectangle())
234 }
235 .buttonStyle(.plain)
236 .help(open ? "Hide details" : "Show balance history and settings")
237 .accessibilityHint("Shows balance history and account settings")
238 if open { details(history: history, connection: connection) }
239 }
240 .padding(.horizontal, palette.ruled ? 6 : 18).padding(.vertical, 16)
241 .background { background }
242 .onHover { inside in
243 hovering = inside
244 if inside { NSCursor.pointingHand.push() } else { NSCursor.pop() }
245 }
246 .animation(.easeOut(duration: 0.14), value: hovering)
247 }
248
249 @ViewBuilder var background: some View {
250 let shape = RoundedRectangle(cornerRadius: palette.cardRadius, style: .continuous)
251 if palette.ruled {
252 ZStack(alignment: .top) {
253 shape.fill(hovering || open ? palette.text.opacity(0.045) : .clear)
254 Rectangle().fill(palette.line).frame(height: 1)
255 }
256 } else {
257 shape.fill(hovering ? palette.card.mix(with: palette.text, by: palette.dark ? 0.05 : 0.025) : palette.card)
258 .overlay { shape.strokeBorder(hovering || open ? palette.accent.opacity(open ? 0.45 : 0.6) : palette.line.opacity(0.7), lineWidth: 1) }
259 .shadow(color: .black.opacity(hovering ? (palette.dark ? 0.35 : 0.08) : 0), radius: 10, y: 4)
260 }
261 }
262
263 func details(history: [(day: String, balance: Decimal)], connection: Connection?) -> some View {
264 VStack(alignment: .leading, spacing: 12) {
265 if history.count > 1 {
266 NetWorthChart(history.map { Ledger.NetWorthPoint(day: $0.day, total: $0.balance, byGroup: [account.kind.group: max(0, $0.balance)]) }).frame(height: 120)
267 }
268 HStack {
269 TextField("Nickname", text: Binding(get: { account.nickname ?? "" }, set: { v in model.updateWorkspace { ws in if let i = ws.accounts.firstIndex(where: { $0.id == account.id }) { ws.accounts[i].nickname = v.isEmpty ? nil : v } } }))
270 .textFieldStyle(.roundedBorder).frame(width: 200)
271 ChoiceButton(AccountKind.allCases.map { (value: $0, title: $0.title, emoji: nil) },
272 selection: Binding(get: { account.kind }, set: { v in model.updateWorkspace { ws in if let i = ws.accounts.firstIndex(where: { $0.id == account.id }) { ws.accounts[i].kind = v; ws.accounts[i].kindChosen = true } } }))
273 .frame(width: 200)
274 Toggle("Hide from totals", isOn: Binding(get: { account.hidden }, set: { v in model.updateWorkspace { ws in if let i = ws.accounts.firstIndex(where: { $0.id == account.id }) { ws.accounts[i].hidden = v } } }))
275 if connection?.kind == .csv || connection?.kind == .manual {
276 TextField("Balance", value: Binding(get: { account.balance }, set: { v in
277 do { try BankSync(store: model.store).setManualBalance(account.id, balance: v); model.reload(force: true); model.shareSoon() }
278 catch { model.message = error.localizedDescription }
279 }), format: .currency(code: account.currency)).textFieldStyle(.roundedBorder).frame(width: 120).help("Imported accounts have no live balance; type it here")
280 }
281 Spacer()
282 Button("Transactions") { model.selection = .transactions; TransactionsFilter.shared.accountID = account.id }.buttonStyle(SecondaryButtonStyle())
283 }
284 .font(.system(size: 12))
285 }
286 }
287}
288
289struct RecurringScreen: View {
290 @Environment(AppModel.self) private var model
291 @Environment(\.palette) private var palette
292
293 var body: some View {
294 let ledger = model.ledger
295 let items = ledger.recurring()
296 let active = items.filter { $0.status != .dismissed }
297 let monthly = active.reduce(Decimal(0)) { $0 + $1.amount * Decimal(30) / Decimal($1.cadence.days) }.rounded(0)
298 ScreenScaffold("Recurring", subtitle: active.isEmpty ? "Charges that repeat show up here after three on a steady schedule." : "\(active.count) recurring · about \(Money.format(monthly, cents: false)) a month") {
299 EmptyView()
300 } content: {
301 VStack(alignment: .leading, spacing: 16) {
302 if items.isEmpty && ledger.entries.isEmpty { ConnectFirst() }
303 let bills = ledger.monthBills()
304 if !bills.isEmpty {
305 monthSummary(bills)
306 VStack(alignment: .leading, spacing: 4) {
307 SectionHeader("This month")
308 ForEach(bills) { bill in billRow(bill, ledger.workspace) }
309 }
310 }
311 ForEach([RecurringStatus.confirmed, .detected, .dismissed], id: \.self) { status in
312 let group = items.filter { $0.status == status }
313 if !group.isEmpty {
314 VStack(alignment: .leading, spacing: 6) {
315 SectionHeader(status == .confirmed ? "All recurring" : status == .detected ? "Found by Bucksley" : "Not recurring")
316 ForEach(group) { item in row(item, ledger.workspace) }
317 }
318 }
319 }
320 }
321 }
322 }
323
324 func monthSummary(_ bills: [Ledger.MonthBill]) -> some View {
325 let paid = bills.reduce(Decimal(0)) { $0 + ($1.paid ?? 0) }
326 let left = bills.filter { $0.paid == nil }.reduce(Decimal(0)) { $0 + $1.item.amount }
327 let share = (paid + left) > 0 ? (paid / (paid + left)).double : 0
328 return Panel(padding: 22) {
329 HStack(spacing: 28) {
330 VStack(alignment: .leading, spacing: 4) {
331 MoneyText(left, size: 26, cents: false)
332 Text("left to pay").font(.system(size: 12, weight: .medium)).foregroundStyle(palette.muted)
333 }
334 Spacer()
335 ZStack {
336 Circle().stroke(palette.line, lineWidth: 10)
337 Circle().trim(from: 0, to: share).stroke(palette.accent, style: StrokeStyle(lineWidth: 10, lineCap: .round)).rotationEffect(.degrees(-90))
338 Text("\(Int((share * 100).rounded()))%").font(palette.figure(13)).foregroundStyle(palette.muted)
339 }
340 .frame(width: 74, height: 74)
341 .accessibilityLabel("\(Int((share * 100).rounded())) percent of this month's recurring paid")
342 Spacer()
343 VStack(alignment: .trailing, spacing: 4) {
344 MoneyText(paid, size: 26, cents: false)
345 Text("paid so far").font(.system(size: 12, weight: .medium)).foregroundStyle(palette.muted)
346 }
347 }
348 }
349 }
350
351 func billRow(_ bill: Ledger.MonthBill, _ ws: Workspace) -> some View {
352 let category = ws.category(bill.item.categoryID)
353 return HStack(spacing: 12) {
354 Text(bill.overdue ? "Overdue" : TransactionRow.shortDay(bill.day))
355 .font(palette.figure(12, weight: .regular)).foregroundStyle(bill.overdue ? palette.loss : palette.muted)
356 .frame(width: 64, alignment: .leading)
357 Text(category?.icon ?? "🔁").font(.system(size: 14))
358 Text(bill.item.name).font(.system(size: 13, weight: .semibold)).lineLimit(1)
359 Text(bill.item.cadence.title).font(.system(size: 12)).foregroundStyle(palette.muted)
360 Spacer(minLength: 8)
361 CategoryTag(category)
362 MoneyText(bill.paid ?? bill.item.amount, size: 13).frame(width: 90, alignment: .trailing)
363 Image(systemName: bill.paid != nil ? "checkmark.circle.fill" : "circle")
364 .foregroundStyle(bill.paid != nil ? palette.gain : palette.line)
365 .accessibilityLabel(bill.paid != nil ? "Paid" : "Not paid yet")
366 }
367 .padding(.vertical, 8).padding(.horizontal, palette.ruled ? 0 : 12)
368 .overlay(alignment: .bottom) { Rectangle().fill(palette.line.opacity(0.6)).frame(height: 0.5) }
369 }
370
371 func row(_ item: RecurringItem, _ ws: Workspace) -> some View {
372 HStack(spacing: 12) {
373 MerchantBadge(name: item.name, colorIndex: ws.category(item.categoryID)?.colorIndex ?? 5)
374 VStack(alignment: .leading, spacing: 2) {
375 Text(item.name).font(.system(size: 13, weight: .semibold))
376 Text("\(item.cadence.title) · \(item.count) charges · last \(TransactionRow.shortDay(item.lastDay))").font(.system(size: 11)).foregroundStyle(palette.muted)
377 }
378 Spacer()
379 VStack(alignment: .trailing, spacing: 2) {
380 MoneyText(item.amount, size: 13)
381 Text("next \(TransactionRow.shortDay(item.nextDay))").font(.system(size: 11)).foregroundStyle(palette.muted)
382 }
383 .frame(width: 110, alignment: .trailing)
384 Menu {
385 Button("Confirm recurring") { model.updateWorkspace { $0.recurring[item.id] = .confirmed } }
386 Button("Not recurring") { model.updateWorkspace { $0.recurring[item.id] = .dismissed } }
387 Button("Reset") { model.updateWorkspace { $0.recurring[item.id] = nil } }
388 } label: { Image(systemName: "ellipsis.circle") }
389 .menuStyle(.borderlessButton).menuIndicator(.hidden).frame(width: 28)
390 }
391 .padding(.vertical, 6).padding(.horizontal, palette.ruled ? 0 : 12)
392 .background(palette.ruled ? Color.clear : palette.card, in: RoundedRectangle(cornerRadius: palette.cardRadius, style: .continuous))
393 .overlay(alignment: .bottom) { if palette.ruled { Rectangle().fill(palette.line).frame(height: 0.5) } }
394 }
395}
396
397struct AgentsScreen: View {
398 @Environment(AppModel.self) private var model
399 @Environment(\.palette) private var palette
400 @State private var client = Client.claudeCode
401 @State private var message: String?
402 @State private var testing = false
403
404 enum Client: String, CaseIterable { case claudeCode = "Claude Code", codex = "Codex", gemini = "Gemini CLI", claudeChat = "Claude chat" }
405
406 var body: some View {
407 let ws = model.workspace
408 ScreenScaffold("Agents", subtitle: "Let Claude Code, Codex or Gemini read your money and help tidy it up.") {
409 EmptyView()
410 } content: {
411 VStack(alignment: .leading, spacing: 18) {
412 Panel {
413 VStack(alignment: .leading, spacing: 12) {
414 SectionHeader("Connect an agent")
415 Text("Bucksley runs its own MCP server on this Mac. MCP requests are handled locally.")
416 .font(.system(size: 13)).foregroundStyle(palette.muted).fixedSize(horizontal: false, vertical: true)
417 PillPicker(Client.allCases.map { ($0, $0.rawValue) }, selection: $client)
418 .accessibilityIdentifier("agents.client")
419 clientSetup
420 HStack(spacing: 10) {
421 Button { test() } label: { Label("Test connection", systemImage: "bolt.horizontal") }
422 .buttonStyle(SecondaryButtonStyle()).disabled(testing).accessibilityIdentifier("agents.test")
423 if testing { ProgressView().controlSize(.small) }
424 }
425 if let message {
426 Text(message).font(.system(size: 12)).foregroundStyle(palette.muted).textSelection(.enabled).fixedSize(horizontal: false, vertical: true)
427 }
428 }
429 }
430 .onChange(of: client) { message = nil }
431 Panel {
432 VStack(alignment: .leading, spacing: 10) {
433 SectionHeader("Ask Bucksley")
434 Text("Connecting an agent lets it work in Bucksley from Claude Code, Codex or Gemini. The Ask screen inside Bucksley is separate: pick who answers there.")
435 .font(.system(size: 13)).foregroundStyle(palette.muted).fixedSize(horizontal: false, vertical: true)
436 AskSourcePicker()
437 Text(askNote(ws)).font(.system(size: 12)).foregroundStyle(palette.muted).fixedSize(horizontal: false, vertical: true)
438 }
439 }
440 Panel {
441 VStack(alignment: .leading, spacing: 8) {
442 SectionHeader("Access")
443 Toggle("Let agents make changes (review, recategorize, notes, rules, budgets)", isOn: Binding(get: { ws.settings.agentsCanWrite }, set: { v in model.updateWorkspace { $0.settings.agentsCanWrite = v } }))
444 .font(.system(size: 13)).accessibilityIdentifier("agents.write")
445 Text("Agents can always read. No tool can move money.").font(.system(size: 12)).foregroundStyle(palette.muted)
446 }
447 }
448 Panel { AgentSkillSection() }
449 VStack(alignment: .leading, spacing: 6) {
450 SectionHeader("Agent activity") { Text("\(ws.agentLog.count)").font(.system(size: 12)).foregroundStyle(palette.muted) }
451 if ws.agentLog.isEmpty {
452 Text("Nothing yet. Every change an agent makes shows up here.").font(.system(size: 13)).foregroundStyle(palette.muted).padding(.vertical, 8)
453 }
454 ForEach(ws.agentLog.prefix(100)) { action in
455 HStack(alignment: .firstTextBaseline, spacing: 10) {
456 Text(action.at.formatted(date: .abbreviated, time: .shortened)).font(palette.figure(11, weight: .regular)).foregroundStyle(palette.muted).frame(width: 140, alignment: .leading)
457 Text(action.client).font(.system(size: 12, weight: .semibold)).frame(width: 110, alignment: .leading)
458 Text(action.summary).font(.system(size: 12))
459 Spacer()
460 Text(action.tool).font(palette.figure(11, weight: .regular)).foregroundStyle(palette.muted)
461 }
462 .padding(.vertical, 5)
463 .overlay(alignment: .bottom) { Rectangle().fill(palette.line).frame(height: 0.5) }
464 }
465 }
466 }
467 }
468 }
469
470 func askNote(_ ws: Workspace) -> String {
471 let provider = AskBucksley.provider(for: ws.settings)
472 if provider == .apple {
473 return "Ask uses Apple Intelligence, which keeps everything on this Mac. Choosing an agent shows what it would read before anything is sent."
474 }
475 return "Ask uses \(provider.title). Change the model in Settings → Ask."
476 }
477
478 @ViewBuilder var clientSetup: some View {
479 switch client {
480 case .claudeCode:
481 Text("Save the connection in the folder you open in Claude Code, then start a new session there and approve Bucksley.")
482 .font(.system(size: 13)).fixedSize(horizontal: false, vertical: true)
483 Button { run { try AgentSetup.saveProjectConnection() } } label: { Label("Save project connection…", systemImage: "folder.badge.plus") }
484 .buttonStyle(PrimaryButtonStyle()).accessibilityIdentifier("agents.claudeCode")
485 case .codex:
486 Text("In Codex Settings → MCP servers, add a STDIO server named bucksley. Paste both fields, save, then type /mcp in a new chat.")
487 .font(.system(size: 13)).fixedSize(horizontal: false, vertical: true)
488 copyField("Command", AgentSetup.command)
489 copyField("Argument", AgentSetup.argument)
490 case .gemini:
491 Text("Choose the project folder you use with Gemini CLI. Bucksley adds itself to .gemini/settings.json and keeps your other settings.")
492 .font(.system(size: 13)).fixedSize(horizontal: false, vertical: true)
493 Button { run { try AgentSetup.saveProjectConnection(gemini: true) } } label: { Label("Save Gemini connection…", systemImage: "folder.badge.plus") }
494 .buttonStyle(PrimaryButtonStyle())
495 case .claudeChat:
496 Text("Save the extension, then in the Claude app open Settings → Extensions → Advanced settings → Install Extension… and choose Bucksley.mcpb.")
497 .font(.system(size: 13)).fixedSize(horizontal: false, vertical: true)
498 Button { run(AgentSetup.saveClaudeExtension) } label: { Label("Save Claude extension…", systemImage: "puzzlepiece.extension") }
499 .buttonStyle(PrimaryButtonStyle())
500 }
501 }
502
503 func copyField(_ label: String, _ value: String) -> some View {
504 HStack(spacing: 8) {
505 Text(label).font(.system(size: 12, weight: .semibold)).frame(width: 76, alignment: .leading)
506 Text(value).font(.system(size: 11, design: .monospaced)).textSelection(.enabled).lineLimit(1).truncationMode(.middle).help(value)
507 .padding(.horizontal, 10).padding(.vertical, 6).frame(maxWidth: .infinity, alignment: .leading)
508 .background(palette.canvas, in: RoundedRectangle(cornerRadius: 8))
509 Button { AgentSetup.copy(value); message = "\(label) copied." } label: { Label("Copy", systemImage: "doc.on.doc") }
510 .buttonStyle(SecondaryButtonStyle())
511 }
512 }
513
514 func run(_ action: () throws -> String?) {
515 do { if let result = try action() { message = result } } catch { message = error.localizedDescription }
516 }
517
518 func test() {
519 testing = true
520 message = nil
521 let mode = model.workspace.settings.agentsCanWrite ? "reading and making changes" : "reading"
522 Task {
523 switch await AgentSetup.testConnection(executable: AgentSetup.command) {
524 case .success(let count): message = "Connection check passed. Bucksley offers \(count) tools, allowed for \(mode)."
525 case .failure(let error): message = "Connection check failed. \(error.localizedDescription)"
526 }
527 testing = false
528 }
529 }
530}
531
532/// The charges worth a second look, likely refunds and transactions Bucksley can file for you.
533struct WorthALook: View {
534 @Environment(AppModel.self) private var model
535 @Environment(\.palette) private var palette
536
537 var body: some View {
538 let ledger = model.ledger, insights = model.insights
539 let suggestions = insights.suggestions.values.filter { !$0.categoryID.isEmpty }
540 if !insights.flags.isEmpty || !insights.refunds.isEmpty || !suggestions.isEmpty {
541 Panel {
542 VStack(alignment: .leading, spacing: 10) {
543 Label("Worth a look", systemImage: "eye").font(.system(size: 12, weight: .bold)).foregroundStyle(palette.accent)
544 ForEach(insights.flags.prefix(3)) { flag in
545 if let entry = ledger.entry(flag.entryID) {
546 Button { model.open(entry); model.selection = .transactions } label: {
547 HStack(alignment: .top, spacing: 8) {
548 Image(systemName: symbol(flag.kind)).foregroundStyle(palette.loss).frame(width: 16)
549 Text(flag.reason).font(.system(size: 12)).fixedSize(horizontal: false, vertical: true).multilineTextAlignment(.leading)
550 Spacer(minLength: 0)
551 }
552 .contentShape(Rectangle())
553 }
554 .buttonStyle(.plain)
555 }
556 }
557 if insights.flags.count > 3 {
558 Text("\(insights.flags.count - 3) more in Transactions → To review").font(.system(size: 11)).foregroundStyle(palette.muted)
559 }
560 if let match = insights.refunds.first, let refund = ledger.entry(match.refundID), let purchase = ledger.entry(match.purchaseID) {
561 HStack(alignment: .top, spacing: 8) {
562 Image(systemName: "arrow.uturn.backward").foregroundStyle(palette.gain).frame(width: 16)
563 VStack(alignment: .leading, spacing: 6) {
564 Text("\(Money.format(refund.amount)) from \(refund.name) looks like a refund of your \(DayKey.short(purchase.day)) purchase.")
565 .font(.system(size: 12)).fixedSize(horizontal: false, vertical: true)
566 Button("Count it as a refund") { model.acceptRefund(match) }.buttonStyle(SecondaryButtonStyle())
567 }
568 }
569 }
570 if !suggestions.isEmpty {
571 HStack(alignment: .top, spacing: 8) {
572 Image(systemName: "tag").foregroundStyle(palette.accent).frame(width: 16)
573 VStack(alignment: .leading, spacing: 6) {
574 Text("Bucksley can file \(suggestions.count) uncategorized transaction\(suggestions.count == 1 ? "" : "s").")
575 .font(.system(size: 12)).fixedSize(horizontal: false, vertical: true)
576 Button("Review suggestions") {
577 TransactionsFilter.shared.unreviewedOnly = false
578 TransactionsFilter.shared.suggestedOnly = true
579 model.selection = .transactions
580 }
581 .buttonStyle(SecondaryButtonStyle())
582 }
583 }
584 }
585 }
586 .frame(maxWidth: .infinity, alignment: .leading)
587 }
588 .accessibilityIdentifier("worthALook")
589 }
590 }
591
592 func symbol(_ kind: Ledger.FlagKind) -> String {
593 switch kind {
594 case .duplicate: "doc.on.doc"
595 case .aboveUsual: "arrow.up.right"
596 case .newMerchant: "sparkle"
597 case .priceChange: "tag"
598 }
599 }
600}