import SwiftUI import AppKit import OSLog import AnalyticsKit import AnalyticsUI /// `Graphley --mcp` runs the STDIO MCP server on the same local store (Inkspring pattern). /// Without it, the normal Mac app starts. @main enum Entry { static func main() { if CommandLine.arguments.contains("--mcp") { let semaphore = DispatchSemaphore(value: 0) Task.detached { do { await MCPServer(store: try WorkspaceStore()).run() } catch { FileHandle.standardError.write(Data("Could not open the workspace: \(error)\n".utf8)) } semaphore.signal() } semaphore.wait() exit(0) } Tide.registerFonts() AnalyticsMacApp.main() } } struct AnalyticsMacApp: App { @State private var model = AppModel() @StateObject private var updates = AppUpdates() var body: some Scene { WindowGroup("Graphley") { ContentView().environment(model).environmentObject(updates).frame(minWidth: 900, idealWidth: 1280, minHeight: 600, idealHeight: 820) .task { await model.start() } } .defaultSize(width: 1280, height: 820) .commands { CommandGroup(after: .appInfo) { if updates.isAvailable { CheckForUpdatesButton(updates: updates) } } // Settings is a screen in the main window, not a separate window. CommandGroup(replacing: .appSettings) { Button("Settings…") { model.selection = .settings }.keyboardShortcut(",") } CommandGroup(after: .newItem) { Button("Refresh Now") { Task { await model.refresh() } }.keyboardShortcut("r") } CommandGroup(after: .sidebar) { Button("Last 7 Days") { model.range = 7 }.keyboardShortcut("1") Button("Last 30 Days") { model.range = 30 }.keyboardShortcut("2") Button("Last 90 Days") { model.range = 90 }.keyboardShortcut("3") } } } } @MainActor @Observable final class AppModel { let store: WorkspaceStore let cloud = SnapshotSync() var workspace = Workspace() var points: [DataPoint] = [] var lastReport: Refresher.Report? var refreshing = false /// The house iCloud Sync and Diagnostics status for Settings → iPhone and iPad (same fields as Inkspring's). var cloudStatus = CloudSyncStatus() var checkingCloud = false var range = 30 var selection: SidebarItem = .overview /// Bumped after the app changes the Keychain, so views that read key state redraw. var keysVersion = 0 /// Set to open the Choose Sites sheet on Sources & keys. var wantsSitePicker = false private var started = false private var loadedVersion: Date? init() { store = try! WorkspaceStore() } /// Runs once per app launch. Every new window calls it, so a reopened window must not start /// another set of loops. func start() async { guard !started else { return } started = true reload() #if DEBUG // `GRAPHLEY_APPEARANCE=light|dark` pins the appearance for screenshots. switch ProcessInfo.processInfo.environment["GRAPHLEY_APPEARANCE"] { case "light": NSApp.appearance = NSAppearance(named: .aqua) case "dark": NSApp.appearance = NSAppearance(named: .darkAqua) default: break } if let path = ProcessInfo.processInfo.environment["GRAPHLEY_SNAPSHOT"] { Task { try? await Task.sleep(for: .seconds(3)); WindowSnapshot.write(to: URL(fileURLWithPath: path)) } } // `GRAPHLEY_SNAPSHOT_DIR=/path/` writes one PNG per main screen (overview.png, sources.png, …). if let dir = ProcessInfo.processInfo.environment["GRAPHLEY_SNAPSHOT_DIR"] { Task { // `GRAPHLEY_SNAPSHOT_SIZE=1280x820` sizes the window first (a locked display opens it at the minimum). let size = (ProcessInfo.processInfo.environment["GRAPHLEY_SNAPSHOT_SIZE"] ?? "1280x820").split(separator: "x").compactMap { Double($0) } if size.count == 2, let window = NSApp.windows.first(where: { $0.isVisible }) { window.setContentSize(NSSize(width: size[0], height: size[1])) } var screens: [(String, SidebarItem)] = [("overview", .overview), ("app-store", .apps), ("agents", .agents), ("sources", .sources), ("settings", .settings)] for d in workspace.dashboards { let slug = d.name.lowercased().map { $0.isLetter || $0.isNumber ? String($0) : "-" }.joined() screens.append(("dashboard-\(slug)", .dashboard(d.id))) } if let s = sites.first { screens.append(("site", .site(s.id))) } for (name, item) in screens { selection = item try? await Task.sleep(for: .seconds(2)) WindowSnapshot.write(to: URL(fileURLWithPath: dir).appendingPathComponent("\(name).png")) // Hold the screen so an outside `screencapture -l` can grab the real window (sidebar included). try? await Task.sleep(for: .seconds(1.5)) } } } // `GRAPHLEY_TOUR=1` walks every screen on its own (about 3.5 s each) for screen recordings, // and skips the launch refresh so the recording shows the numbers already in the store. if ProcessInfo.processInfo.environment["GRAPHLEY_TOUR"] != nil { Task { try? await Task.sleep(for: .seconds(3)) var screens: [SidebarItem] = [.overview, .apps] + workspace.dashboards.map { .dashboard($0.id) } screens += sites.prefix(3).map { .site($0.id) } + [.agents, .sources, .settings, .overview] for item in screens { selection = item; try? await Task.sleep(for: .seconds(3.5)) } for r in [90, 7, 30] { range = r; try? await Task.sleep(for: .seconds(2)) } } 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() } } // Share on every launch, not only when nothing was ever shared: lastSharedAt lives in the store, // so a Debug build (Development iCloud) or an agent's --mcp refresh can set it without the // Production database the iPhone reads ever getting the numbers. One small record, so it's cheap. if workspace.settings.shareWithIPhone && !points.isEmpty { shareSoon() } // Daily refresh at the configured hour, plus one on launch if today's has not run. Numbers that // arrived after the last share (an agent's refresh, a failed push) go to the iPhone on the same tick. Task { while !Task.isCancelled { if needsDailyRefresh { await refresh() } else if needsShare { shareSoon() } try? await Task.sleep(for: .seconds(600)) } } } /// Re-reads the store whenever its files changed on disk. Read errors keep the current values /// and retry on the next tick instead of being mistaken for "nothing changed". func reload() { let version = store.lastModified() guard version == nil || version != loadedVersion else { return } do { let ws = try store.load(), pts = try store.points() if ws != workspace { workspace = ws } if pts != points { points = pts } loadedVersion = version } catch { Self.log.error("Could not read the store: \(error.localizedDescription, privacy: .public)") } } static let log = Logger(subsystem: "com.protomota.graphley", category: "store") var needsDailyRefresh: Bool { let latest = points.map(\.day).max() ?? "" let hour = Calendar.current.component(.hour, from: .now) return latest < (DayKey.lastDays(1).last ?? "") && hour >= workspace.settings.refreshHour } /// True when the store has numbers newer than the last copy sent to the iPhone. var needsShare: Bool { let s = workspace.settings guard s.shareWithIPhone, !points.isEmpty, let refreshed = s.lastRefreshAt else { return false } return (s.lastSharedAt ?? .distantPast) < refreshed } func refresh() async { guard !refreshing else { return } refreshing = true; defer { refreshing = false } lastReport = await Refresher(store: store, cloud: cloud).refreshAll() reload() await checkCloud(share: false) } /// Check Now: asks iCloud for the account, shares the latest numbers when sharing is on (so a /// rejected record shows its real CloudKit error), then reads back whether iCloud has the snapshot. func checkCloud(share: Bool = true) async { guard !checkingCloud, cloud.isAvailable else { return } checkingCloud = true; defer { checkingCloud = false } var status = cloudStatus status.lastCheck = .now status.clearError() var checkedAccount = false do { status.accountStatus = try await cloud.accountStatusText() checkedAccount = true guard status.accountStatus == "Connected" else { status.error = "This Mac isn't signed in to iCloud. Sign in in System Settings, then check again." cloudStatus = status return } if share, workspace.settings.shareWithIPhone, let snap = try? store.snapshot(refreshedAt: workspace.settings.lastRefreshAt) { try await cloud.push(snap) _ = try? store.update { $0.settings.lastSharedAt = .now } reload() } let date = try await cloud.remoteSnapshotDate() status.lastCloudContact = .now status.snapshotFound = date != nil status.snapshotDate = date if date == nil, workspace.settings.shareWithIPhone, workspace.settings.lastSharedAt != nil { status.error = "iCloud accepted the last share but has no snapshot. The CloudKit schema may not be deployed to Production." } } catch { if !checkedAccount { status.accountStatus = "Unavailable" } status.record(error) Self.log.error("iCloud check failed: \(String(describing: error), privacy: .public)") } cloudStatus = status } func keysChanged() { keysVersion += 1 } /// Reorders the sidebar's sites. Saved right away and, after a short pause so a drag across /// several rows sends one update, shared with the iPhone so it shows the same order. func moveSite(_ id: String, to target: String) { guard workspace.sites.contains(where: { $0.id == id }), id != target else { return } _ = try? store.update { $0.moveSite(id, to: target) } reload() shareSoon() } func moveSite(_ id: String, by step: Int) { _ = try? store.update { $0.moveSite(id, by: step) } reload() shareSoon() } private var sharePush: Task? /// Pushes the store to the iPhone after a short pause (a drag across several rows sends one update). private 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, let snap = try? store.snapshot(refreshedAt: ws.settings.lastRefreshAt) else { return } do { try await cloud.push(snap) _ = try? store.update { $0.settings.lastSharedAt = .now } reload() await checkCloud(share: false) } catch { cloudStatus.record(error) Self.log.error("Could not share with the iPhone: \(String(describing: error), privacy: .public)") } } } func updateSettings(_ change: (inout AnalyticsKit.Settings) -> Void) { _ = try? store.update { change(&$0.settings) } reload() } /// Sources whose last refresh failed, keyed by source name. var failures: [String: String] { lastReport?.failed ?? [:] } var hasAppStoreKey: Bool { _ = keysVersion #if DEBUG // Unsigned review builds can't read the Keychain; `GRAPHLEY_ASSUME_KEYS=1` shows the App Store cards anyway. if ProcessInfo.processInfo.environment["GRAPHLEY_ASSUME_KEYS"] != nil { return true } #endif return AppStoreConnect().isConfigured } var googleConnected: Bool { _ = keysVersion; return GoogleAuth.isConfigured } var days: [String] { DayKey.lastDays(range) } var sites: [Site] { workspace.sites.filter { !$0.archived } } @ObservationIgnored private var portfolioCache: (key: String, data: PortfolioData)? /// The store indexed for dashboards, rebuilt only when the store changes. var portfolio: PortfolioData { let key = "\(loadedVersion?.timeIntervalSince1970 ?? 0)|\(points.count)|\(workspace.sites.count)" if let c = portfolioCache, c.key == key { return c.data } let w = workspace 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) portfolioCache = (key, data) return data } func series(_ metric: Metric, sites ids: Set = [], days: [String]) -> [Double] { points.daily(metric, subjects: ids, days: days) } func total(_ metric: Metric, site: String? = nil, days n: Int, offset: Int = 0) -> Double { let all = DayKey.lastDays(n + offset); return points.daily(metric, subjects: site.map { [$0] } ?? [], days: Array(all.prefix(n))).reduce(0, +) } } #if DEBUG /// Debug builds only: `GRAPHLEY_SNAPSHOT=/path/out.png` renders the app's own main window (title bar /// included) to a PNG a few seconds after launch, plus a view-tree `.txt` beside it. Lets agents capture the running app headlessly /// when the session has no Screen Recording permission. @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 else { return } // Always 2x, even on a 1x display. cacheDisplay draws through AppKit, so the sidebar's // vibrancy list appears; the layer render below is the fallback. // `GRAPHLEY_SNAPSHOT_SCROLL=end` scrolls each screen to its bottom first (Settings → About on a short display). if ProcessInfo.processInfo.environment["GRAPHLEY_SNAPSHOT_SCROLL"] == "end" { scrollToEnd(frameView) } let size = frameView.bounds.size if let rep = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: Int(size.width * 2), pixelsHigh: Int(size.height * 2), bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0) { rep.size = size frameView.cacheDisplay(in: frameView.bounds, to: rep) try? rep.representation(using: .png, properties: [:])?.write(to: url) } try? viewTree(frameView).write(to: url.deletingPathExtension().appendingPathExtension("txt"), atomically: true, encoding: .utf8) } static func scrollToEnd(_ view: NSView) { if let scroll = view as? NSScrollView, scroll.frame.width > 500, let document = scroll.documentView { let y = document.isFlipped ? max(0, document.bounds.height - scroll.contentView.bounds.height) : 0 scroll.contentView.scroll(to: NSPoint(x: 0, y: y)); scroll.reflectScrolledClipView(scroll.contentView) } view.subviews.forEach(scrollToEnd) } /// Text outline of the window: view classes, frames, table row counts and accessibility labels. static func viewTree(_ view: NSView, depth: Int = 0) -> String { var line = String(repeating: " ", count: depth) + "\(type(of: view)) \(view.frame.integral)" if let table = view as? NSTableView { line += " rows=\(table.numberOfRows)" } if let label = view.accessibilityLabel(), !label.isEmpty { line += " label=\"\(label)\"" } return ([line] + view.subviews.map { viewTree($0, depth: depth + 1) }).joined(separator: "\n") } } #endif