Branchwell

Graphley / app · graphley.ai / Apps / Mac / MacApp.swift

1import SwiftUI
2import AppKit
3import OSLog
4import AnalyticsKit
5import AnalyticsUI
6
7/// `Graphley --mcp` runs the STDIO MCP server on the same local store (Inkspring pattern).
8/// Without it, the normal Mac app starts.
9@main
10enum Entry {
11 static func main() {
12 if CommandLine.arguments.contains("--mcp") {
13 let semaphore = DispatchSemaphore(value: 0)
14 Task.detached {
15 do { await MCPServer(store: try WorkspaceStore()).run() }
16 catch { FileHandle.standardError.write(Data("Could not open the workspace: \(error)\n".utf8)) }
17 semaphore.signal()
18 }
19 semaphore.wait()
20 exit(0)
21 }
22 Tide.registerFonts()
23 AnalyticsMacApp.main()
24 }
25}
26
27struct AnalyticsMacApp: App {
28 @State private var model = AppModel()
29 @StateObject private var updates = AppUpdates()
30 var body: some Scene {
31 WindowGroup("Graphley") {
32 ContentView().environment(model).environmentObject(updates).frame(minWidth: 900, idealWidth: 1280, minHeight: 600, idealHeight: 820)
33 .task { await model.start() }
34 }
35 .defaultSize(width: 1280, height: 820)
36 .commands {
37 CommandGroup(after: .appInfo) {
38 if updates.isAvailable { CheckForUpdatesButton(updates: updates) }
39 }
40 // Settings is a screen in the main window, not a separate window.
41 CommandGroup(replacing: .appSettings) {
42 Button("Settings…") { model.selection = .settings }.keyboardShortcut(",")
43 }
44 CommandGroup(after: .newItem) {
45 Button("Refresh Now") { Task { await model.refresh() } }.keyboardShortcut("r")
46 }
47 CommandGroup(after: .sidebar) {
48 Button("Last 7 Days") { model.range = 7 }.keyboardShortcut("1")
49 Button("Last 30 Days") { model.range = 30 }.keyboardShortcut("2")
50 Button("Last 90 Days") { model.range = 90 }.keyboardShortcut("3")
51 }
52 }
53 }
54}
55
56@MainActor @Observable
57final class AppModel {
58 let store: WorkspaceStore
59 let cloud = SnapshotSync()
60 var workspace = Workspace()
61 var points: [DataPoint] = []
62 var lastReport: Refresher.Report?
63 var refreshing = false
64 /// The house iCloud Sync and Diagnostics status for Settings → iPhone and iPad (same fields as Inkspring's).
65 var cloudStatus = CloudSyncStatus()
66 var checkingCloud = false
67 var range = 30
68 var selection: SidebarItem = .overview
69 /// Bumped after the app changes the Keychain, so views that read key state redraw.
70 var keysVersion = 0
71 /// Set to open the Choose Sites sheet on Sources & keys.
72 var wantsSitePicker = false
73 private var started = false
74 private var loadedVersion: Date?
75
76 init() { store = try! WorkspaceStore() }
77
78 /// Runs once per app launch. Every new window calls it, so a reopened window must not start
79 /// another set of loops.
80 func start() async {
81 guard !started else { return }
82 started = true
83 reload()
84 #if DEBUG
85 // `GRAPHLEY_APPEARANCE=light|dark` pins the appearance for screenshots.
86 switch ProcessInfo.processInfo.environment["GRAPHLEY_APPEARANCE"] {
87 case "light": NSApp.appearance = NSAppearance(named: .aqua)
88 case "dark": NSApp.appearance = NSAppearance(named: .darkAqua)
89 default: break
90 }
91 if let path = ProcessInfo.processInfo.environment["GRAPHLEY_SNAPSHOT"] {
92 Task { try? await Task.sleep(for: .seconds(3)); WindowSnapshot.write(to: URL(fileURLWithPath: path)) }
93 }
94 // `GRAPHLEY_SNAPSHOT_DIR=/path/` writes one PNG per main screen (overview.png, sources.png, …).
95 if let dir = ProcessInfo.processInfo.environment["GRAPHLEY_SNAPSHOT_DIR"] {
96 Task {
97 // `GRAPHLEY_SNAPSHOT_SIZE=1280x820` sizes the window first (a locked display opens it at the minimum).
98 let size = (ProcessInfo.processInfo.environment["GRAPHLEY_SNAPSHOT_SIZE"] ?? "1280x820").split(separator: "x").compactMap { Double($0) }
99 if size.count == 2, let window = NSApp.windows.first(where: { $0.isVisible }) { window.setContentSize(NSSize(width: size[0], height: size[1])) }
100 var screens: [(String, SidebarItem)] = [("overview", .overview), ("app-store", .apps), ("agents", .agents), ("sources", .sources), ("settings", .settings)]
101 for d in workspace.dashboards {
102 let slug = d.name.lowercased().map { $0.isLetter || $0.isNumber ? String($0) : "-" }.joined()
103 screens.append(("dashboard-\(slug)", .dashboard(d.id)))
104 }
105 if let s = sites.first { screens.append(("site", .site(s.id))) }
106 for (name, item) in screens {
107 selection = item
108 try? await Task.sleep(for: .seconds(2))
109 WindowSnapshot.write(to: URL(fileURLWithPath: dir).appendingPathComponent("\(name).png"))
110 // Hold the screen so an outside `screencapture -l` can grab the real window (sidebar included).
111 try? await Task.sleep(for: .seconds(1.5))
112 }
113 }
114 }
115 // `GRAPHLEY_TOUR=1` walks every screen on its own (about 3.5 s each) for screen recordings,
116 // and skips the launch refresh so the recording shows the numbers already in the store.
117 if ProcessInfo.processInfo.environment["GRAPHLEY_TOUR"] != nil {
118 Task {
119 try? await Task.sleep(for: .seconds(3))
120 var screens: [SidebarItem] = [.overview, .apps] + workspace.dashboards.map { .dashboard($0.id) }
121 screens += sites.prefix(3).map { .site($0.id) } + [.agents, .sources, .settings, .overview]
122 for item in screens { selection = item; try? await Task.sleep(for: .seconds(3.5)) }
123 for r in [90, 7, 30] { range = r; try? await Task.sleep(for: .seconds(2)) }
124 }
125 return
126 }
127 #endif
128 // Agents change the store from the --mcp process; pick up their edits.
129 Task { while !Task.isCancelled { try? await Task.sleep(for: .seconds(3)); reload() } }
130 // Share on every launch, not only when nothing was ever shared: lastSharedAt lives in the store,
131 // so a Debug build (Development iCloud) or an agent's --mcp refresh can set it without the
132 // Production database the iPhone reads ever getting the numbers. One small record, so it's cheap.
133 if workspace.settings.shareWithIPhone && !points.isEmpty { shareSoon() }
134 // Daily refresh at the configured hour, plus one on launch if today's has not run. Numbers that
135 // arrived after the last share (an agent's refresh, a failed push) go to the iPhone on the same tick.
136 Task {
137 while !Task.isCancelled {
138 if needsDailyRefresh { await refresh() } else if needsShare { shareSoon() }
139 try? await Task.sleep(for: .seconds(600))
140 }
141 }
142 }
143
144 /// Re-reads the store whenever its files changed on disk. Read errors keep the current values
145 /// and retry on the next tick instead of being mistaken for "nothing changed".
146 func reload() {
147 let version = store.lastModified()
148 guard version == nil || version != loadedVersion else { return }
149 do {
150 let ws = try store.load(), pts = try store.points()
151 if ws != workspace { workspace = ws }
152 if pts != points { points = pts }
153 loadedVersion = version
154 } catch {
155 Self.log.error("Could not read the store: \(error.localizedDescription, privacy: .public)")
156 }
157 }
158 static let log = Logger(subsystem: "com.protomota.graphley", category: "store")
159
160 var needsDailyRefresh: Bool {
161 let latest = points.map(\.day).max() ?? ""
162 let hour = Calendar.current.component(.hour, from: .now)
163 return latest < (DayKey.lastDays(1).last ?? "") && hour >= workspace.settings.refreshHour
164 }
165
166 /// True when the store has numbers newer than the last copy sent to the iPhone.
167 var needsShare: Bool {
168 let s = workspace.settings
169 guard s.shareWithIPhone, !points.isEmpty, let refreshed = s.lastRefreshAt else { return false }
170 return (s.lastSharedAt ?? .distantPast) < refreshed
171 }
172
173 func refresh() async {
174 guard !refreshing else { return }
175 refreshing = true; defer { refreshing = false }
176 lastReport = await Refresher(store: store, cloud: cloud).refreshAll()
177 reload()
178 await checkCloud(share: false)
179 }
180
181 /// Check Now: asks iCloud for the account, shares the latest numbers when sharing is on (so a
182 /// rejected record shows its real CloudKit error), then reads back whether iCloud has the snapshot.
183 func checkCloud(share: Bool = true) async {
184 guard !checkingCloud, cloud.isAvailable else { return }
185 checkingCloud = true; defer { checkingCloud = false }
186 var status = cloudStatus
187 status.lastCheck = .now
188 status.clearError()
189 var checkedAccount = false
190 do {
191 status.accountStatus = try await cloud.accountStatusText()
192 checkedAccount = true
193 guard status.accountStatus == "Connected" else {
194 status.error = "This Mac isn't signed in to iCloud. Sign in in System Settings, then check again."
195 cloudStatus = status
196 return
197 }
198 if share, workspace.settings.shareWithIPhone, let snap = try? store.snapshot(refreshedAt: workspace.settings.lastRefreshAt) {
199 try await cloud.push(snap)
200 _ = try? store.update { $0.settings.lastSharedAt = .now }
201 reload()
202 }
203 let date = try await cloud.remoteSnapshotDate()
204 status.lastCloudContact = .now
205 status.snapshotFound = date != nil
206 status.snapshotDate = date
207 if date == nil, workspace.settings.shareWithIPhone, workspace.settings.lastSharedAt != nil {
208 status.error = "iCloud accepted the last share but has no snapshot. The CloudKit schema may not be deployed to Production."
209 }
210 } catch {
211 if !checkedAccount { status.accountStatus = "Unavailable" }
212 status.record(error)
213 Self.log.error("iCloud check failed: \(String(describing: error), privacy: .public)")
214 }
215 cloudStatus = status
216 }
217
218 func keysChanged() { keysVersion += 1 }
219
220 /// Reorders the sidebar's sites. Saved right away and, after a short pause so a drag across
221 /// several rows sends one update, shared with the iPhone so it shows the same order.
222 func moveSite(_ id: String, to target: String) {
223 guard workspace.sites.contains(where: { $0.id == id }), id != target else { return }
224 _ = try? store.update { $0.moveSite(id, to: target) }
225 reload()
226 shareSoon()
227 }
228
229 func moveSite(_ id: String, by step: Int) {
230 _ = try? store.update { $0.moveSite(id, by: step) }
231 reload()
232 shareSoon()
233 }
234
235 private var sharePush: Task<Void, Never>?
236 /// Pushes the store to the iPhone after a short pause (a drag across several rows sends one update).
237 private func shareSoon() {
238 sharePush?.cancel()
239 sharePush = Task { [store, cloud] in
240 try? await Task.sleep(for: .seconds(1.5))
241 guard !Task.isCancelled, cloud.isAvailable, let ws = try? store.load(), ws.settings.shareWithIPhone,
242 let snap = try? store.snapshot(refreshedAt: ws.settings.lastRefreshAt) else { return }
243 do {
244 try await cloud.push(snap)
245 _ = try? store.update { $0.settings.lastSharedAt = .now }
246 reload()
247 await checkCloud(share: false)
248 } catch {
249 cloudStatus.record(error)
250 Self.log.error("Could not share with the iPhone: \(String(describing: error), privacy: .public)")
251 }
252 }
253 }
254
255 func updateSettings(_ change: (inout AnalyticsKit.Settings) -> Void) {
256 _ = try? store.update { change(&$0.settings) }
257 reload()
258 }
259
260 /// Sources whose last refresh failed, keyed by source name.
261 var failures: [String: String] { lastReport?.failed ?? [:] }
262 var hasAppStoreKey: Bool {
263 _ = keysVersion
264 #if DEBUG
265 // Unsigned review builds can't read the Keychain; `GRAPHLEY_ASSUME_KEYS=1` shows the App Store cards anyway.
266 if ProcessInfo.processInfo.environment["GRAPHLEY_ASSUME_KEYS"] != nil { return true }
267 #endif
268 return AppStoreConnect().isConfigured
269 }
270 var googleConnected: Bool { _ = keysVersion; return GoogleAuth.isConfigured }
271
272 var days: [String] { DayKey.lastDays(range) }
273 var sites: [Site] { workspace.sites.filter { !$0.archived } }
274 @ObservationIgnored private var portfolioCache: (key: String, data: PortfolioData)?
275 /// The store indexed for dashboards, rebuilt only when the store changes.
276 var portfolio: PortfolioData {
277 let key = "\(loadedVersion?.timeIntervalSince1970 ?? 0)|\(points.count)|\(workspace.sites.count)"
278 if let c = portfolioCache, c.key == key { return c.data }
279 let w = workspace
280 let data = PortfolioData(sites: w.sites, apps: w.apps, socials: w.socials, points: points, reviews: w.reviews, campaigns: w.campaigns, videos: w.videos, caveats: w.caveats)
281 portfolioCache = (key, data)
282 return data
283 }
284 func series(_ metric: Metric, sites ids: Set<String> = [], days: [String]) -> [Double] { points.daily(metric, subjects: ids, days: days) }
285 func total(_ metric: Metric, site: String? = nil, days n: Int, offset: Int = 0) -> Double {
286 let all = DayKey.lastDays(n + offset); return points.daily(metric, subjects: site.map { [$0] } ?? [], days: Array(all.prefix(n))).reduce(0, +)
287 }
288}
289
290#if DEBUG
291/// Debug builds only: `GRAPHLEY_SNAPSHOT=/path/out.png` renders the app's own main window (title bar
292/// included) to a PNG a few seconds after launch, plus a view-tree `.txt` beside it. Lets agents capture the running app headlessly
293/// when the session has no Screen Recording permission.
294@MainActor
295enum WindowSnapshot {
296 static func write(to url: URL) {
297 guard let window = NSApp.windows.first(where: { $0.isVisible && $0.contentView != nil }),
298 let frameView = window.contentView?.superview else { return }
299 // Always 2x, even on a 1x display. cacheDisplay draws through AppKit, so the sidebar's
300 // vibrancy list appears; the layer render below is the fallback.
301 // `GRAPHLEY_SNAPSHOT_SCROLL=end` scrolls each screen to its bottom first (Settings → About on a short display).
302 if ProcessInfo.processInfo.environment["GRAPHLEY_SNAPSHOT_SCROLL"] == "end" { scrollToEnd(frameView) }
303 let size = frameView.bounds.size
304 if let rep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(size.width * 2), pixelsHigh: Int(size.height * 2), bitsPerSample: 8,
305 samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0) {
306 rep.size = size
307 frameView.cacheDisplay(in: frameView.bounds, to: rep)
308 try? rep.representation(using: .png, properties: [:])?.write(to: url)
309 }
310 try? viewTree(frameView).write(to: url.deletingPathExtension().appendingPathExtension("txt"), atomically: true, encoding: .utf8)
311 }
312
313 static func scrollToEnd(_ view: NSView) {
314 if let scroll = view as? NSScrollView, scroll.frame.width > 500, let document = scroll.documentView {
315 let y = document.isFlipped ? max(0, document.bounds.height - scroll.contentView.bounds.height) : 0
316 scroll.contentView.scroll(to: NSPoint(x: 0, y: y)); scroll.reflectScrolledClipView(scroll.contentView)
317 }
318 view.subviews.forEach(scrollToEnd)
319 }
320
321 /// Text outline of the window: view classes, frames, table row counts and accessibility labels.
322 static func viewTree(_ view: NSView, depth: Int = 0) -> String {
323 var line = String(repeating: " ", count: depth) + "\(type(of: view)) \(view.frame.integral)"
324 if let table = view as? NSTableView { line += " rows=\(table.numberOfRows)" }
325 if let label = view.accessibilityLabel(), !label.isEmpty { line += " label=\"\(label)\"" }
326 return ([line] + view.subviews.map { viewTree($0, depth: depth + 1) }).joined(separator: "\n")
327 }
328}
329#endif