Open source CapCut alternative.
TypeScript
feat(analytics): the phone reads the summary and pages the accounts
David Lec18f82551c23
diff --git a/.github/workflows/analytics-contract.yml b/.github/workflows/analytics-contract.ymlindex 358c99b3..121c1fed 100644--- a/.github/workflows/analytics-contract.yml+++ b/.github/workflows/analytics-contract.yml@@ -1,9 +1,9 @@name: Analytics Contract-# The phone decodes the analytics rollup the site's nightly pipeline writes.-# The site test regenerates the rollup from the pipeline and fails when the-# checked-in fixture is behind it; the DonkeyKit tests decode that fixture.-# Together they fail any change that moves the rollup's shape without the+# The phone decodes the analytics summary the site folds out of its nightly+# rollup. The site test rebuilds that summary from the pipeline and fails when+# the checked-in fixture is behind it; the DonkeyKit tests decode that fixture.+# Together they fail any change that moves the summary's shape without the# phone's model moving with it.## The fixture's bytes follow whatever the pipeline imports (the referraldiff --git a/apps/ios/Donkey/Controllers/CutCloudClient.swift b/apps/ios/Donkey/Controllers/CutCloudClient.swiftindex 556cb7f6..7effc998 100644--- a/apps/ios/Donkey/Controllers/CutCloudClient.swift+++ b/apps/ios/Donkey/Controllers/CutCloudClient.swift@@ -708,17 +708,35 @@ extension CutCloudClient: CloudProjectsServicing {// MARK: - Analyticsextension CutCloudClient: AnalyticsServicing {- /// The nightly analytics rollup. The API serves it to super users only,- /// so a regular account reads as unauthorized here.- func fetchAnalyticsRollup() async throws -> AnalyticsRollup {- let (data, http) = try await perform(try request("GET", "/api/analytics/rollup"))+ /// The nightly rollup folded to the numbers the charts draw. The API+ /// serves it to super users only, so a regular account reads as+ /// unauthorized here.+ func fetchAnalyticsSummary() async throws -> AnalyticsSummaryDocument {+ let (data, http) = try await perform(try request("GET", "/api/analytics/summary"))switch http.statusCode {case 200..<300: breakcase 404: throw AnalyticsError.noRollupcase 401, 403: throw CloudSyncError.unauthorizeddefault: throw CloudSyncError.refused("The server answered \(http.statusCode).")}- return try AnalyticsRollup.decode(data)+ return try AnalyticsSummaryDocument.decode(data)+ }++ /// One page of accounts in the API's rank order. The page size is the+ /// server's; this follows the cursor it hands back.+ func fetchAnalyticsUsers(sort: String, cursor: Int) async throws -> AnalyticsUsersPage {+ let (data, http) = try await perform(try request(+ "GET",+ "/api/analytics/users",+ query: [URLQueryItem(name: "sort", value: sort), URLQueryItem(name: "cursor", value: String(cursor))]+ ))+ switch http.statusCode {+ case 200..<300: break+ case 404: throw AnalyticsError.noRollup+ case 401, 403: throw CloudSyncError.unauthorized+ default: throw CloudSyncError.refused("The server answered \(http.statusCode).")+ }+ return try AnalyticsUsersPage.decode(data)}}diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Analytics.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Analytics.swiftindex a89c1639..7d829323 100644--- a/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Analytics.swift+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitModels/Analytics.swift@@ -1,26 +1,25 @@import Foundation-/// The nightly analytics rollup as /api/analytics/rollup serves it, pared to-/// the fields the phone renders.-nonisolated public struct AnalyticsRollup: Decodable, Sendable {- nonisolated public struct MissingEntry: Decodable, Sendable {+/// The analytics summary as /api/analytics/summary serves it, pared to the+/// fields the phone renders. The server folds the nightly rollup into this —+/// one point per day plus the headline numbers — so the phone reads tens of+/// kilobytes whatever the account table does, and no one's email or balance+/// rides along.+nonisolated public struct AnalyticsSummaryDocument: Decodable, Sendable {+ nonisolated public struct Day: Decodable, Sendable {public var day: String+ /// Nil on a day the pipeline never extracted: unknown, not zero.+ public var active: Int?+ public var working: Int?+ public var signups: Int+ public var totalRegistered: Int- public init(day: String) {+ public init(day: String, active: Int?, working: Int?, signups: Int, totalRegistered: Int) {self.day = day- }- }-- nonisolated public struct User: Decodable, Sendable {- public var registeredAt: String- public var balanceMicros: String- /// One source bitmask per entry of `days`.- public var activity: [Int]-- public init(registeredAt: String, balanceMicros: String, activity: [Int]) {- self.registeredAt = registeredAt- self.balanceMicros = balanceMicros- self.activity = activity+ self.active = active+ self.working = working+ self.signups = signups+ self.totalRegistered = totalRegistered}}@@ -72,38 +71,53 @@ nonisolated public struct AnalyticsRollup: Decodable, Sendable {}public var generatedAt: String- /// Oldest → newest; every user's activity array aligns with this.- public var days: [String]- /// Bit order of the activity masks.- public var sources: [String]+ /// One entry per day of the activity window, oldest → newest.+ public var series: [Day]+ public var registered: Int+ public var signups7d: Int+ public var signupsWindow: Int+ public var activeYesterday: Int?+ public var active7d: Int?+ public var activePrior7d: Int?+ /// Credit held across every account, micros as a decimal string.+ public var balanceMicros: String/// Days the consolidation could not read; their counts are unknown.- public var missing: [MissingEntry]- /// Absent from rollups written before billing shipped.+ public var missing: [String]+ /// Absent from summaries of rollups written before billing shipped.public var billing: Billing?- public var users: [User]public init(generatedAt: String,- days: [String],- sources: [String],- missing: [MissingEntry],- billing: Billing?,- users: [User]+ series: [Day],+ registered: Int,+ signups7d: Int,+ signupsWindow: Int,+ activeYesterday: Int?,+ active7d: Int?,+ activePrior7d: Int?,+ balanceMicros: String,+ missing: [String],+ billing: Billing?) {self.generatedAt = generatedAt- self.days = days- self.sources = sources+ self.series = series+ self.registered = registered+ self.signups7d = signups7d+ self.signupsWindow = signupsWindow+ self.activeYesterday = activeYesterday+ self.active7d = active7d+ self.activePrior7d = activePrior7d+ self.balanceMicros = balanceMicrosself.missing = missingself.billing = billing- self.users = users}/// Decodes the API's JSON. A body this build cannot read fails as/// `AnalyticsError.unreadable` naming the field, so the screen says/// which part of the contract moved.- public static func decode(_ data: Data) throws -> AnalyticsRollup {+ public static func decode(_ data: Data) throws -> AnalyticsSummaryDocument {do {- return try JSONDecoder().decode(AnalyticsRollup.self, from: data)+ return try JSONDecoder().decode(AnalyticsSummaryDocument.self, from: data)} catch let error as DecodingError {throw AnalyticsError.unreadable(mismatch(error))} catch {@@ -111,48 +125,139 @@ nonisolated public struct AnalyticsRollup: Decodable, Sendable {}}- /// "billing.canceling is not an array", "users[0].activity is missing".+ /// "billing.canceling is not an array", "series[0].signups is missing".static func mismatch(_ error: DecodingError) -> String {- func path(_ context: DecodingError.Context) -> String {- let joined = context.codingPath.reduce(into: "") { text, key in- if let index = key.intValue {- text += "[\(index)]"- } else {- text += text.isEmpty ? key.stringValue : ".\(key.stringValue)"- }- }- return joined.isEmpty ? "the rollup" : joined+ analyticsMismatch(error, whole: "the summary")+ }+}++/// One page of accounts as /api/analytics/users answers it: the server ranks+/// the whole window and hands back a page plus the cursor for the next one.+/// The web dashboard reads the same endpoint the same way.+nonisolated public struct AnalyticsUsersPage: Decodable, Sendable {+ nonisolated public struct Person: Decodable, Sendable, Identifiable {+ public var id: String+ public var email: String+ public var name: String+ public var registeredAt: String+ public var balanceMicros: String+ /// All-time paid charges; absent for accounts that never paid.+ public var fundedMicros: String?+ public var superUser: Bool?+ public var activeDays: Int++ public init(+ id: String,+ email: String,+ name: String,+ registeredAt: String,+ balanceMicros: String,+ fundedMicros: String? = nil,+ superUser: Bool? = nil,+ activeDays: Int+ ) {+ self.id = id+ self.email = email+ self.name = name+ self.registeredAt = registeredAt+ self.balanceMicros = balanceMicros+ self.fundedMicros = fundedMicros+ self.superUser = superUser+ self.activeDays = activeDays+ }+ }++ /// The orders the API ranks by. They come off the wire so the phone offers+ /// exactly what the server sorts by, and the web's chips read the same list.+ nonisolated public struct Sort: Decodable, Sendable, Identifiable, Equatable {+ public var id: String+ public var label: String++ public init(id: String, label: String) {+ self.id = id+ self.label = label}- func name(_ type: Any.Type) -> String {- switch type {- case is String.Type: return "a string"- case is Bool.Type: return "a boolean"- case is Int.Type, is Double.Type, is Float.Type, is Int64.Type, is UInt.Type: return "a number"- default:- let text = String(describing: type)- if text.hasPrefix("Array<") { return "an array" }- if text.hasPrefix("Dictionary<") { return "an object" }- return text+ }++ /// The rollup these ranks came from. A page stamped with a different one+ /// belongs to a different order.+ public var generatedAt: String+ public var users: [Person]+ public var total: Int+ /// The offset of the next page, or nil at the end of the list.+ public var nextCursor: Int?+ public var sorts: [Sort]+ public var pageSize: Int++ public init(+ generatedAt: String,+ users: [Person],+ total: Int,+ nextCursor: Int?,+ sorts: [Sort],+ pageSize: Int+ ) {+ self.generatedAt = generatedAt+ self.users = users+ self.total = total+ self.nextCursor = nextCursor+ self.sorts = sorts+ self.pageSize = pageSize+ }++ public static func decode(_ data: Data) throws -> AnalyticsUsersPage {+ do {+ return try JSONDecoder().decode(AnalyticsUsersPage.self, from: data)+ } catch let error as DecodingError {+ throw AnalyticsError.unreadable(analyticsMismatch(error, whole: "the page"))+ } catch {+ throw AnalyticsError.unreadable(error.localizedDescription)+ }+ }+}++/// Names the field a decoder tripped on, so a screen can say which part of the+/// contract moved: "billing.canceling is not an array", "users[0].email is+/// missing".+nonisolated func analyticsMismatch(_ error: DecodingError, whole: String) -> String {+ func path(_ context: DecodingError.Context) -> String {+ let joined = context.codingPath.reduce(into: "") { text, key in+ if let index = key.intValue {+ text += "[\(index)]"+ } else {+ text += text.isEmpty ? key.stringValue : ".\(key.stringValue)"}}- switch error {- case .typeMismatch(let type, let context):- return "\(path(context)) is not \(name(type))"- case .valueNotFound(let type, let context):- return "\(path(context)) is null, expected \(name(type))"- case .keyNotFound(let key, let context):- let parent = path(context)- return parent == "the rollup" ? "\(key.stringValue) is missing" : "\(parent).\(key.stringValue) is missing"- case .dataCorrupted(let context):- return context.debugDescription- @unknown default:- return String(describing: error)+ return joined.isEmpty ? whole : joined+ }+ func name(_ type: Any.Type) -> String {+ switch type {+ case is String.Type: return "a string"+ case is Bool.Type: return "a boolean"+ case is Int.Type, is Double.Type, is Float.Type, is Int64.Type, is UInt.Type: return "a number"+ default:+ let text = String(describing: type)+ if text.hasPrefix("Array<") { return "an array" }+ if text.hasPrefix("Dictionary<") { return "an object" }+ return text}}+ switch error {+ case .typeMismatch(let type, let context):+ return "\(path(context)) is not \(name(type))"+ case .valueNotFound(let type, let context):+ return "\(path(context)) is null, expected \(name(type))"+ case .keyNotFound(let key, let context):+ let parent = path(context)+ return parent == whole ? "\(key.stringValue) is missing" : "\(parent).\(key.stringValue) is missing"+ case .dataCorrupted(let context):+ return context.debugDescription+ @unknown default:+ return String(describing: error)+ }}-/// The rollup reduced to what the dashboard draws: one point per day plus the-/// headline numbers. Pure derivation, mirrored from the web dashboard.+/// The summary in the shapes the charts draw: days as dates, money as dollars.nonisolated public struct AnalyticsSummary: Sendable, Equatable {nonisolated public struct DayPoint: Sendable, Equatable, Identifiable {public var day: Date@@ -212,51 +317,18 @@ nonisolated public struct AnalyticsSummary: Sendable, Equatable {public var missingDayCount: Intpublic var generatedAt: Date?- public init(rollup: AnalyticsRollup) {- // Any source bit marks a day active; the DB sources mark it working.- let workBits = rollup.sources.enumerated().reduce(0) { mask, entry in- entry.element == "posthog" ? mask : mask | (1 << entry.offset)- }- let missingDays = Set(rollup.missing.map(\.day))-- var signupsByDay: [String: Int] = [:]- for user in rollup.users {- signupsByDay[String(user.registeredAt.prefix(10)), default: 0] += 1- }-- // Cumulative registrations start from everyone who signed up before- // the window, so the total line carries the real base.- let firstDay = rollup.days.first ?? ""- var totalRegistered = rollup.users.filter { String($0.registeredAt.prefix(10)) < firstDay }.count-- var points: [DayPoint] = []- for (i, day) in rollup.days.enumerated() {- let signups = signupsByDay[day] ?? 0- totalRegistered += signups- var active: Int?- var working: Int?- if !missingDays.contains(day) {- var visited = 0- var worked = 0- for user in rollup.users {- let mask = i < user.activity.count ? user.activity[i] : 0- if mask != 0 { visited += 1 }- if mask & workBits != 0 { worked += 1 }- }- active = visited- working = worked- }- points.append(DayPoint(- day: Self.date(fromDay: day),- active: active,- working: working,- signups: signups,- totalRegistered: totalRegistered- ))+ public init(document: AnalyticsSummaryDocument) {+ points = document.series.map { day in+ DayPoint(+ day: Self.date(fromDay: day.day),+ active: day.active,+ working: day.working,+ signups: day.signups,+ totalRegistered: day.totalRegistered+ )}-// Money rides the billing window, which runs through today.- let revenue = rollup.billing.map { billing in+ let revenue = document.billing.map { billing inzip(billing.days, billing.revenue).map { day, entry inRevenuePoint(day: Self.date(fromDay: day),@@ -265,48 +337,33 @@ nonisolated public struct AnalyticsSummary: Sendable, Equatable {)}} ?? []-- // Counts users active on any known day in the range; nil when the- // whole range went unextracted.- let activeInRange = { (from: Int, to: Int) -> Int? in- let known = (max(0, from)..<max(0, to)).filter { !missingDays.contains(rollup.days[$0]) }- guard !known.isEmpty else { return nil }- return rollup.users.filter { user in- known.contains { ($0 < user.activity.count ? user.activity[$0] : 0) != 0 }- }.count- }-- let len = rollup.days.count- let active7d = activeInRange(len - 7, len)- let activePrior7d = activeInRange(len - 14, len - 7)-- self.points = pointsself.revenue = revenue- registered = rollup.users.count- signups7d = rollup.days.suffix(7).reduce(0) { $0 + (signupsByDay[$1] ?? 0) }- signupsWindow = points.reduce(0) { $0 + $1.signups }- activeYesterday = points.last?.active ?? nil- self.active7d = active7d- weekDeltaPercent = if let active7d, let activePrior7d, activePrior7d > 0 {- Double(active7d - activePrior7d) / Double(activePrior7d) * 100+ registered = document.registered+ signups7d = document.signups7d+ signupsWindow = document.signupsWindow+ activeYesterday = document.activeYesterday+ active7d = document.active7d+ weekDeltaPercent = if let active7d = document.active7d,+ let prior = document.activePrior7d, prior > 0 {+ Double(active7d - prior) / Double(prior) * 100} else {nil}- balanceDollars = rollup.users.reduce(0) { $0 + Self.dollars(fromMicros: $1.balanceMicros) }- subscribers = rollup.billing?.subscribers- canceling = rollup.billing?.canceling.count- funded = rollup.billing?.funded- fundedDollars = rollup.billing.map { Self.dollars(fromMicros: $0.fundedMicros) }- revenueDollars = rollup.billing.map { _ in revenue.reduce(0) { $0 + $1.revenueDollars } }- missingDayCount = missingDays.count- generatedAt = Self.timestamp(from: rollup.generatedAt)+ balanceDollars = Self.dollars(fromMicros: document.balanceMicros)+ subscribers = document.billing?.subscribers+ canceling = document.billing?.canceling.count+ funded = document.billing?.funded+ fundedDollars = document.billing.map { Self.dollars(fromMicros: $0.fundedMicros) }+ revenueDollars = document.billing.map { _ in revenue.reduce(0) { $0 + $1.revenueDollars } }+ missingDayCount = document.missing.count+ generatedAt = Self.timestamp(from: document.generatedAt)}private static func dollars(fromMicros micros: String) -> Double {(Double(micros) ?? 0) / 1_000_000}- /// "YYYY-MM-DD" as midnight UTC, matching the rollup's day keys.+ /// "YYYY-MM-DD" as midnight UTC, matching the summary's day keys.private static func date(fromDay day: String) -> Date {let parts = day.split(separator: "-").compactMap { Int($0) }var components = DateComponents()@@ -322,7 +379,7 @@ nonisolated public struct AnalyticsSummary: Sendable, Equatable {return calendar}()- /// The rollup stamps milliseconds (JS toISOString).+ /// The summary stamps milliseconds (JS toISOString).private static func timestamp(from string: String) -> Date? {let formatter = ISO8601DateFormatter()formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]@@ -334,14 +391,15 @@ nonisolated public struct AnalyticsSummary: Sendable, Equatable {nonisolated public enum AnalyticsError: Error, Equatable {/// The nightly job hasn't written a rollup yet.case noRollup- /// The answer came back, and it was not a rollup this build can read;+ /// The answer came back, and it was not a summary this build can read;/// the text names the field that moved.case unreadable(String)}/// What the app target's CutCloudClient does for the analytics dashboard.public protocol AnalyticsServicing: AnyObject {- func fetchAnalyticsRollup() async throws -> AnalyticsRollup+ func fetchAnalyticsSummary() async throws -> AnalyticsSummaryDocument+ func fetchAnalyticsUsers(sort: String, cursor: Int) async throws -> AnalyticsUsersPage}@Observable@@ -357,13 +415,82 @@ public final class AnalyticsModel {public private(set) var state: State = .loading+ /// The accounts list, in the order the API ranked them. It arrives a page+ /// at a time — the phone asks for the first page and follows the cursor,+ /// exactly as the web dashboard does — so neither client ever holds the+ /// whole account table.+ public private(set) var people: [AnalyticsUsersPage.Person] = []+ /// The orders the API offers, as it named them.+ public private(set) var sorts: [AnalyticsUsersPage.Sort] = []+ public private(set) var sort = "active"+ public private(set) var peopleTotal = 0+ public private(set) var isLoadingPeople = false+ /// Set when a page failed; the list keeps whatever already loaded.+ public private(set) var peopleError: String?+ /// The offset of the next page, or nil at the end of the list.+ private var nextCursor: Int? = 0+ /// The rollup the loaded pages were ranked against.+ private var peopleStamp: String?+private let service: any AnalyticsServicingpublic init(service: any AnalyticsServicing) {self.service = service}- /// Fetches the rollup. A refresh over loaded data keeps the charts up+ /// Whether another page exists to ask for.+ public var hasMorePeople: Bool { nextCursor != nil }++ /// Loads the next page, if there is one and none is in flight. The list+ /// view calls this as its last row comes into view.+ public func loadMorePeople() async {+ guard !isLoadingPeople, let cursor = nextCursor else { return }+ await loadPeople(cursor: cursor)+ }++ /// Switches the order. Ranks are per order, so the list starts over.+ public func choosePeople(sort: String) async {+ guard sort != self.sort else { return }+ self.sort = sort+ resetPeople()+ await loadPeople(cursor: 0)+ }++ private func resetPeople() {+ people = []+ peopleTotal = 0+ nextCursor = 0+ peopleStamp = nil+ peopleError = nil+ }++ private func loadPeople(cursor: Int) async {+ isLoadingPeople = true+ defer { isLoadingPeople = false }+ do {+ let page = try await service.fetchAnalyticsUsers(sort: sort, cursor: cursor)+ // A nightly run landing while the list is open reorders the ranks,+ // so pages from the older order are dropped rather than stitched+ // onto the new one.+ if let stamp = peopleStamp, stamp != page.generatedAt, cursor > 0 {+ resetPeople()+ await loadPeople(cursor: 0)+ return+ }+ peopleStamp = page.generatedAt+ people = cursor == 0 ? page.users : people + page.users+ peopleTotal = page.total+ nextCursor = page.nextCursor+ if !page.sorts.isEmpty { sorts = page.sorts }+ peopleError = nil+ } catch is CancellationError {+ return+ } catch {+ peopleError = Self.reason(for: error)+ }+ }++ /// Fetches the summary. A refresh over loaded data keeps the charts up/// while it runs and on failure; a retry over a failure spins, so the tap/// shows something happening. A first load surfaces the error, saying/// which one it was — a failure that only reads "try again" tells nobody@@ -373,8 +500,12 @@ public final class AnalyticsModel {public func refresh() async {if case .failed = state { state = .loading }do {- let rollup = try await service.fetchAnalyticsRollup()- state = .loaded(AnalyticsSummary(rollup: rollup))+ let document = try await service.fetchAnalyticsSummary()+ state = .loaded(AnalyticsSummary(document: document))+ // The numbers and the list come from the same rollup, so a refresh+ // takes the list back to its first page.+ resetPeople()+ await loadPeople(cursor: 0)} catch AnalyticsError.noRollup {state = .empty} catch is CancellationError {@@ -394,9 +525,9 @@ public final class AnalyticsModel {case CloudSyncError.unreachable(let reach, let code):"\(reach.sentence) (\(code))"case AnalyticsError.unreadable(let detail):- "The rollup came back in a shape this build doesn't read: \(detail)."+ "The summary came back in a shape this build doesn't read: \(detail)."default:- "The rollup didn't load. Try again."+ "The summary didn't load. Try again."}}}diff --git a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/AnalyticsScreen.swift b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/AnalyticsScreen.swiftindex 0709c223..dfe1f98c 100644--- a/apps/ios/DonkeyKit/Sources/DonkeyKitUI/AnalyticsScreen.swift+++ b/apps/ios/DonkeyKit/Sources/DonkeyKitUI/AnalyticsScreen.swift@@ -34,7 +34,7 @@ public struct AnalyticsScreen: View {Task { await analytics.refresh() }}case .loaded(let summary):- SummaryList(summary: summary)+ SummaryList(analytics: analytics, summary: summary).refreshable { await analytics.refresh() }}}@@ -52,6 +52,7 @@ public struct AnalyticsScreen: View {}private struct SummaryList: View {+ var analytics: AnalyticsModellet summary: AnalyticsSummaryvar body: some View {@@ -99,6 +100,9 @@ private struct SummaryList: View {ActiveChart(points: summary.points)}+ Divider()+ PeopleSection(analytics: analytics)+if let generatedAt = summary.generatedAt {Text("From the nightly rollup generated \(generatedAt.formatted(date: .abbreviated, time: .shortened)).").font(.caption)@@ -148,6 +152,124 @@ private struct StatGrid: View {}}+/// The accounts the API ranks, a page at a time. The rows arrive as the list+/// reaches them: the last row asks for the next page, the same cursor the web+/// grid follows.+private struct PeopleSection: View {+ var analytics: AnalyticsModel++ var body: some View {+ VStack(alignment: .leading, spacing: 3) {+ HStack(alignment: .firstTextBaseline) {+ Text("People")+ .font(.headline)+ Spacer()+ if !analytics.sorts.isEmpty {+ Menu {+ ForEach(analytics.sorts) { sort in+ Button(sort.label) {+ Task { await analytics.choosePeople(sort: sort.id) }+ }+ }+ } label: {+ Text(selectedLabel)+ .font(.footnote.weight(.medium))+ }+ }+ }+ Text(caption)+ .font(.footnote)+ .foregroundStyle(.secondary)++ LazyVStack(alignment: .leading, spacing: 0) {+ ForEach(analytics.people) { person in+ PersonRow(person: person)+ .task {+ if person.id == analytics.people.last?.id {+ await analytics.loadMorePeople()+ }+ }+ }+ if let peopleError = analytics.peopleError {+ Text(peopleError)+ .font(.footnote)+ .foregroundStyle(.secondary)+ .padding(.vertical, 12)+ } else if analytics.isLoadingPeople {+ ProgressView()+ .frame(maxWidth: .infinity)+ .padding(.vertical, 12)+ }+ }+ .padding(.top, 8)+ }+ .padding(.vertical, 20)+ .task { await analytics.loadMorePeople() }+ }++ private var selectedLabel: String {+ analytics.sorts.first { $0.id == analytics.sort }?.label ?? "Sort"+ }++ private var caption: String {+ guard analytics.peopleTotal > 0 else { return "Accounts in rank order" }+ return "\(analytics.people.count.formatted()) of \(analytics.peopleTotal.formatted()) accounts"+ }+}++private struct PersonRow: View {+ let person: AnalyticsUsersPage.Person++ var body: some View {+ VStack(alignment: .leading, spacing: 2) {+ HStack(spacing: 6) {+ Text(person.email)+ .font(.subheadline)+ .lineLimit(1)+ if person.superUser == true {+ Text("su")+ .font(.caption2)+ .foregroundStyle(.secondary)+ .padding(.horizontal, 4)+ .padding(.vertical, 1)+ .background(Color.secondary.opacity(0.15), in: RoundedRectangle(cornerRadius: 4))+ }+ }+ Text(sub)+ .font(.caption)+ .foregroundStyle(.secondary)+ .lineLimit(1)+ }+ .frame(maxWidth: .infinity, alignment: .leading)+ .padding(.vertical, 8)+ }++ private var sub: String {+ var parts = [+ person.activeDays == 0+ ? "no activity"+ : "\(person.activeDays) active \(person.activeDays == 1 ? "day" : "days")",+ "joined \(joined)",+ usd(person.balanceMicros),+ ]+ if let funded = person.fundedMicros {+ parts.append("paid \(usd(funded))")+ }+ return parts.joined(separator: " · ")+ }++ private func usd(_ micros: String) -> String {+ dollars((Double(micros) ?? 0) / 1_000_000)+ }++ private var joined: String {+ let iso = ISO8601DateFormatter()+ iso.formatOptions = [.withInternetDateTime, .withFractionalSeconds]+ let date = iso.date(from: person.registeredAt) ?? ISO8601DateFormatter().date(from: person.registeredAt)+ return date?.formatted(.dateTime.month(.abbreviated).day()) ?? String(person.registeredAt.prefix(10))+ }+}+private struct StatTile: View {let label: Stringlet value: Stringdiff --git a/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/DonkeyKitModelsTests.swift b/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/DonkeyKitModelsTests.swiftindex 789bb41c..4f11d44d 100644--- a/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/DonkeyKitModelsTests.swift+++ b/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/DonkeyKitModelsTests.swift@@ -1311,49 +1311,46 @@ import Testing}@Suite struct AnalyticsSummaryTests {- // Three days over two sources (one DB, one posthog); day two never got- // extracted. User A signed up before the window and works daily; user B- // signed up on day two and only opened the app on day three.- func rollup(billing: AnalyticsRollup.Billing? = nil) -> AnalyticsRollup {- AnalyticsRollup(+ // Three days, one of them never extracted, as the server folds them.+ func document(billing: AnalyticsSummaryDocument.Billing? = nil) -> AnalyticsSummaryDocument {+ AnalyticsSummaryDocument(generatedAt: "2026-08-21T04:00:00.000Z",- days: ["2026-08-18", "2026-08-19", "2026-08-20"],- sources: ["renders", "posthog"],- missing: [.init(day: "2026-08-19")],- billing: billing,- users: [- .init(registeredAt: "2026-08-01T10:00:00.000Z", balanceMicros: "3000000", activity: [1, 0, 3]),- .init(registeredAt: "2026-08-19T12:00:00.000Z", balanceMicros: "500000", activity: [0, 0, 2]),- ]+ series: [+ .init(day: "2026-08-18", active: 1, working: 1, signups: 0, totalRegistered: 1),+ .init(day: "2026-08-19", active: nil, working: nil, signups: 1, totalRegistered: 2),+ .init(day: "2026-08-20", active: 2, working: 1, signups: 0, totalRegistered: 2),+ ],+ registered: 2,+ signups7d: 1,+ signupsWindow: 1,+ activeYesterday: 2,+ active7d: 2,+ activePrior7d: 1,+ balanceMicros: "3500000",+ missing: ["2026-08-19"],+ billing: billing)}- @Test func derivesCountsAndSkipsMissingDays() {- let summary = AnalyticsSummary(rollup: rollup())+ @Test func drawsThePointsTheServerFolded() {+ let summary = AnalyticsSummary(document: document())#expect(summary.registered == 2)#expect(summary.points.count == 3)- #expect(summary.points[0].active == 1)- #expect(summary.points[0].working == 1)- #expect(summary.points[1].active == nil)- #expect(summary.points[2].active == 2)- #expect(summary.points[2].working == 1)+ #expect(summary.points.map(\.active) == [1, nil, 2])+ #expect(summary.points.map(\.working) == [1, nil, 1])+ #expect(summary.points.map(\.signups) == [0, 1, 0])+ #expect(summary.points.map(\.totalRegistered) == [1, 2, 2])#expect(summary.missingDayCount == 1)#expect(summary.activeYesterday == 2)#expect(summary.active7d == 2)- }-- @Test func signupsAndTotalsCarryThePreWindowBase() {- let summary = AnalyticsSummary(rollup: rollup())- #expect(summary.points.map(\.signups) == [0, 1, 0])- #expect(summary.points.map(\.totalRegistered) == [1, 2, 2])- #expect(summary.signups7d == 1)+ #expect(summary.weekDeltaPercent == 100)#expect(summary.balanceDollars == 3.5)}@Test func billingChartsOnItsOwnWindow() {// The billing window runs a day past the activity window, and every// day of it counts: today's money is in the total the day it lands.- let billing = AnalyticsRollup.Billing(+ let billing = AnalyticsSummaryDocument.Billing(days: ["2026-08-18", "2026-08-19", "2026-08-20", "2026-08-21"],subscribers: 4,canceling: [.init(subscriptionId: "sub_1")],@@ -1366,7 +1363,7 @@ import Testing.init(proMicros: "30000000", topupMicros: "0"),])- let summary = AnalyticsSummary(rollup: rollup(billing: billing))+ let summary = AnalyticsSummary(document: document(billing: billing))#expect(summary.subscribers == 4)#expect(summary.canceling == 1)#expect(summary.fundedDollars == 120)@@ -1377,32 +1374,36 @@ import Testing#expect(summary.revenue[3].revenueDollars == 30)}- @Test func billinglessRollupLeavesRevenueUnknown() {- let summary = AnalyticsSummary(rollup: rollup())+ @Test func billinglessSummaryLeavesRevenueUnknown() {+ let summary = AnalyticsSummary(document: document())#expect(summary.revenueDollars == nil)#expect(summary.revenue.isEmpty)#expect(summary.subscribers == nil)}++ @Test func aWeekWithoutABaselineHasNoDelta() {+ var doc = document()+ doc.activePrior7d = nil+ #expect(AnalyticsSummary(document: doc).weekDeltaPercent == nil)+ }}-/// The rollup the site's pipeline writes today, decoded by this build. The-/// fixture is generated by `npm run analytics:rollup-fixture` in site/ and-/// checked by the site's tests, so a shape change on the server fails here-/// before it reaches a phone.+/// The summary the site's API serves today, decoded by this build. The fixture+/// is generated by `npm run analytics:summary-fixture` in site/ and checked by+/// the site's tests, so a shape change on the server fails here before it+/// reaches a phone.@Suite struct AnalyticsContractTests {func fixture() throws -> Data {let url = try #require(Bundle.module.url(- forResource: "analytics-rollup",+ forResource: "analytics-summary",withExtension: "json",subdirectory: "Fixtures"))return try Data(contentsOf: url)}- @Test func decodesTheRollupThePipelineWrites() throws {- let rollup = try AnalyticsRollup.decode(fixture())- let summary = AnalyticsSummary(rollup: rollup)- #expect(rollup.days == ["2026-08-30", "2026-08-31", "2026-09-01"])+ @Test func decodesTheSummaryTheApiServes() throws {+ let summary = try AnalyticsSummary(document: AnalyticsSummaryDocument.decode(fixture()))#expect(summary.registered == 3)#expect(summary.points.map(\.active) == [2, nil, 3])#expect(summary.points.map(\.working) == [2, nil, 1])@@ -1421,6 +1422,29 @@ import Testing#expect(summary.generatedAt != nil)}+ /// Nobody's email or balance rides in what the phone reads.+ @Test func carriesNoAccountRows() throws {+ let json = try #require(try JSONSerialization.jsonObject(with: fixture()) as? [String: Any])+ #expect(json["users"] == nil)+ }++ @Test func decodesTheUsersPageTheApiServes() throws {+ let url = try #require(Bundle.module.url(+ forResource: "analytics-users",+ withExtension: "json",+ subdirectory: "Fixtures"+ ))+ let page = try AnalyticsUsersPage.decode(try Data(contentsOf: url))+ #expect(page.users.map(\.email) == ["[email protected]", "[email protected]", "[email protected]"])+ #expect(page.users.map(\.activeDays) == [2, 1, 2])+ #expect(page.users.last?.superUser == true)+ #expect(page.users.first?.fundedMicros == "20000000")+ #expect(page.total == 3)+ #expect(page.nextCursor == nil)+ #expect(page.pageSize == 50)+ #expect(page.sorts.map(\.id) == ["active", "recent", "joined", "paid"])+ }+@Test func aMovedFieldIsNamed() throws {var json = try #require(try JSONSerialization.jsonObject(with: fixture()) as? [String: Any])var billing = try #require(json["billing"] as? [String: Any])@@ -1428,7 +1452,7 @@ import Testingjson["billing"] = billinglet data = try JSONSerialization.data(withJSONObject: json)#expect(throws: AnalyticsError.unreadable("billing.canceling is not an array")) {- try AnalyticsRollup.decode(data)+ try AnalyticsSummaryDocument.decode(data)}}@@ -1439,39 +1463,88 @@ import Testingjson["billing"] = billinglet data = try JSONSerialization.data(withJSONObject: json)#expect(throws: AnalyticsError.unreadable("billing.subscribers is not a number")) {- try AnalyticsRollup.decode(data)+ try AnalyticsSummaryDocument.decode(data)}}@Test func aMissingFieldIsNamed() throws {var json = try #require(try JSONSerialization.jsonObject(with: fixture()) as? [String: Any])- json["days"] = nil+ json["series"] = nillet data = try JSONSerialization.data(withJSONObject: json)- #expect(throws: AnalyticsError.unreadable("days is missing")) {- try AnalyticsRollup.decode(data)+ #expect(throws: AnalyticsError.unreadable("series is missing")) {+ try AnalyticsSummaryDocument.decode(data)}}}@Suite struct AnalyticsModelTests {final class Service: AnalyticsServicing, @unchecked Sendable {- var answer: Result<AnalyticsRollup, any Error> = .failure(CloudSyncError.transport)+ var answer: Result<AnalyticsSummaryDocument, any Error> = .failure(CloudSyncError.transport)var calls = 0+ /// Pages keyed by the cursor asked for, and every (sort, cursor) asked.+ var pages: [Int: AnalyticsUsersPage] = [:]+ var pageCalls: [(sort: String, cursor: Int)] = []+ var pageFailure: (any Error)?- func fetchAnalyticsRollup() async throws -> AnalyticsRollup {+ func fetchAnalyticsSummary() async throws -> AnalyticsSummaryDocument {calls += 1return try answer.get()}++ func fetchAnalyticsUsers(sort: String, cursor: Int) async throws -> AnalyticsUsersPage {+ pageCalls.append((sort, cursor))+ if let pageFailure { throw pageFailure }+ return pages[cursor] ?? AnalyticsUsersPage(+ generatedAt: "2026-08-21T04:00:00.000Z",+ users: [],+ total: 0,+ nextCursor: nil,+ sorts: [],+ pageSize: 50+ )+ }+ }++ static func person(_ id: String) -> AnalyticsUsersPage.Person {+ .init(+ id: id,+ email: "\(id)@x.test",+ name: id,+ registeredAt: "2026-08-01T10:00:00.000Z",+ balanceMicros: "1000000",+ activeDays: 2+ )+ }++ static func page(+ _ ids: [String],+ next: Int?,+ total: Int,+ generatedAt: String = "2026-08-21T04:00:00.000Z"+ ) -> AnalyticsUsersPage {+ AnalyticsUsersPage(+ generatedAt: generatedAt,+ users: ids.map(person),+ total: total,+ nextCursor: next,+ sorts: [.init(id: "active", label: "Most active"), .init(id: "joined", label: "Newest")],+ pageSize: 2+ )}- func rollup() -> AnalyticsRollup {- AnalyticsRollup(+ func document() -> AnalyticsSummaryDocument {+ AnalyticsSummaryDocument(generatedAt: "2026-08-21T04:00:00.000Z",- days: ["2026-08-20"],- sources: ["renders"],+ series: [.init(day: "2026-08-20", active: 1, working: 1, signups: 0, totalRegistered: 1)],+ registered: 1,+ signups7d: 0,+ signupsWindow: 0,+ activeYesterday: 1,+ active7d: 1,+ activePrior7d: nil,+ balanceMicros: "0",missing: [],- billing: nil,- users: [.init(registeredAt: "2026-08-01T10:00:00.000Z", balanceMicros: "0", activity: [1])]+ billing: nil)}@@ -1516,7 +1589,7 @@ import Testingservice.answer = .failure(CloudSyncError.unreachable(.timedOut, code: -1001))let model = AnalyticsModel(service: service)await model.refresh()- service.answer = .success(rollup())+ service.answer = .success(document())await model.refresh()guard case .loaded(let summary) = model.state else {Issue.record("expected the retry to load")@@ -1528,7 +1601,7 @@ import Testing@Test func aFailedRefreshKeepsChartsThatAlreadyLoaded() async {let service = Service()- service.answer = .success(rollup())+ service.answer = .success(document())let model = AnalyticsModel(service: service)await model.refresh()service.answer = .failure(CloudSyncError.unreachable(.dropped, code: -1005))@@ -1538,6 +1611,77 @@ import Testingreturn}}++ // The list follows the cursor the API hands back, the same rule the web+ // dashboard's grid follows: ask for the first page, then the next.+ @Test func peopleArriveAPageAtATime() async {+ let service = Service()+ service.answer = .success(document())+ service.pages = [+ 0: Self.page(["a", "b"], next: 2, total: 3),+ 2: Self.page(["c"], next: nil, total: 3),+ ]+ let model = AnalyticsModel(service: service)+ await model.refresh()+ #expect(model.people.map(\.id) == ["a", "b"])+ #expect(model.peopleTotal == 3)+ #expect(model.hasMorePeople)+ #expect(model.sorts.map(\.id) == ["active", "joined"])++ await model.loadMorePeople()+ #expect(model.people.map(\.id) == ["a", "b", "c"])+ #expect(!model.hasMorePeople)++ // The end of the list is the end: nothing more is asked for.+ await model.loadMorePeople()+ #expect(service.pageCalls.map(\.cursor) == [0, 2])+ }++ @Test func aNewOrderStartsTheListOver() async {+ let service = Service()+ service.answer = .success(document())+ service.pages = [0: Self.page(["a", "b"], next: 2, total: 3)]+ let model = AnalyticsModel(service: service)+ await model.refresh()+ await model.loadMorePeople()++ service.pages = [0: Self.page(["c"], next: nil, total: 3)]+ await model.choosePeople(sort: "joined")+ #expect(model.sort == "joined")+ #expect(model.people.map(\.id) == ["c"])+ #expect(service.pageCalls.last?.sort == "joined")+ #expect(service.pageCalls.last?.cursor == 0)+ }++ // A nightly run landing mid-scroll reorders the ranks, so pages from the+ // older rollup are dropped instead of stitched onto the new order.+ @Test func aRollupWrittenMidScrollRestartsTheList() async {+ let service = Service()+ service.answer = .success(document())+ service.pages = [0: Self.page(["a", "b"], next: 2, total: 4)]+ let model = AnalyticsModel(service: service)+ await model.refresh()++ service.pages = [+ 0: Self.page(["x", "y"], next: 2, total: 4, generatedAt: "2026-08-22T04:00:00.000Z"),+ 2: Self.page(["z"], next: nil, total: 4, generatedAt: "2026-08-22T04:00:00.000Z"),+ ]+ await model.loadMorePeople()+ #expect(model.people.map(\.id) == ["x", "y"])+ #expect(model.hasMorePeople)+ }++ @Test func aFailedPageKeepsTheRowsAlreadyLoaded() async {+ let service = Service()+ service.answer = .success(document())+ service.pages = [0: Self.page(["a", "b"], next: 2, total: 3)]+ let model = AnalyticsModel(service: service)+ await model.refresh()+ service.pageFailure = CloudSyncError.unreachable(.timedOut, code: -1001)+ await model.loadMorePeople()+ #expect(model.people.map(\.id) == ["a", "b"])+ #expect(model.peopleError?.contains("-1001") == true)+ }}@Suite struct UserProfileDecodingTests {diff --git a/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/Fixtures/analytics-rollup.json b/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/Fixtures/analytics-summary.jsonsimilarity index 78%rename from apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/Fixtures/analytics-rollup.jsonrename to apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/Fixtures/analytics-summary.jsonindex e97b882f..87d532fa 100644--- a/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/Fixtures/analytics-rollup.json+++ b/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/Fixtures/analytics-summary.json@@ -1,4 +1,8 @@{+ "active7d": 3,+ "activePrior7d": null,+ "activeYesterday": 3,+ "balanceMicros": "3500000","billing": {"canceling": [{@@ -119,13 +123,7 @@],"generatedAt": "2026-09-02T04:00:00.000Z","missing": [- {- "day": "2026-08-31",- "sources": [- "db",- "posthog"- ]- }+ "2026-08-31"],"referrals": {"days": [@@ -173,6 +171,32 @@"other"]},+ "registered": 3,+ "series": [+ {+ "active": 2,+ "day": "2026-08-30",+ "signups": 0,+ "totalRegistered": 2,+ "working": 2+ },+ {+ "active": null,+ "day": "2026-08-31",+ "signups": 1,+ "totalRegistered": 3,+ "working": null+ },+ {+ "active": 3,+ "day": "2026-09-01",+ "signups": 0,+ "totalRegistered": 3,+ "working": 1+ }+ ],+ "signups7d": 1,+ "signupsWindow": 1,"sources": ["inference","renders",@@ -182,52 +206,5 @@"creditLedger","posthog"],- "users": [- {- "activity": [- 0,- 0,- 64- ],- "balanceMicros": "0",- "email": "[email protected]",- "fundedMicros": "5000000",- "id": "u_new",- "name": "New Person",- "registeredAt": "2026-08-31T12:00:00.000Z",- "storageBytes": "0",- "storageQuotaBytes": 262144000- },- {- "activity": [- 65,- 0,- 64- ],- "balanceMicros": "3000000",- "email": "[email protected]",- "fundedMicros": "20000000",- "id": "u_pro",- "name": "Pro Person",- "registeredAt": "2026-08-01T10:00:00.000Z",- "storageBytes": "1048576",- "storageQuotaBytes": 107374182400- },- {- "activity": [- 2,- 0,- 2- ],- "balanceMicros": "500000",- "email": "[email protected]",- "id": "u_su",- "name": "Super Person",- "registeredAt": "2026-07-01T00:00:00.000Z",- "storageBytes": "0",- "storageQuotaBytes": null,- "superUser": true- }- ],"version": 1}diff --git a/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/Fixtures/analytics-users.json b/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/Fixtures/analytics-users.jsonnew file mode 100644index 00000000..a17ce28c--- /dev/null+++ b/apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/Fixtures/analytics-users.json@@ -0,0 +1,80 @@+{+ "generatedAt": "2026-09-02T04:00:00.000Z",+ "nextCursor": null,+ "pageSize": 50,+ "sorts": [+ {+ "id": "active",+ "label": "Most active"+ },+ {+ "id": "recent",+ "label": "Recently active"+ },+ {+ "id": "joined",+ "label": "Newest"+ },+ {+ "id": "paid",+ "label": "Top paid"+ }+ ],+ "total": 3,+ "users": [+ {+ "activity": [+ 65,+ 0,+ 64+ ],+ "balanceMicros": "3000000",+ "email": "[email protected]",+ "fundedMicros": "20000000",+ "id": "u_pro",+ "name": "Pro Person",+ "registeredAt": "2026-08-01T10:00:00.000Z",+ "storageBytes": "1048576",+ "storageQuotaBytes": 107374182400,+ "activeDays": 2,+ "lastActive": 2,+ "score": 1.2557236642639067+ },+ {+ "activity": [+ 0,+ 0,+ 64+ ],+ "balanceMicros": "0",+ "email": "[email protected]",+ "fundedMicros": "5000000",+ "id": "u_new",+ "name": "New Person",+ "registeredAt": "2026-08-31T12:00:00.000Z",+ "storageBytes": "0",+ "storageQuotaBytes": 262144000,+ "activeDays": 1,+ "lastActive": 2,+ "score": 0.35+ },+ {+ "activity": [+ 2,+ 0,+ 2+ ],+ "balanceMicros": "500000",+ "email": "[email protected]",+ "id": "u_su",+ "name": "Super Person",+ "registeredAt": "2026-07-01T00:00:00.000Z",+ "storageBytes": "0",+ "storageQuotaBytes": null,+ "superUser": true,+ "activeDays": 2,+ "lastActive": 2,+ "score": 1.9057236642639066+ }+ ]+}diff --git a/docs/guides/ios-app.md b/docs/guides/ios-app.mdindex 18832086..85d8cdb2 100644--- a/docs/guides/ios-app.md+++ b/docs/guides/ios-app.md@@ -223,14 +223,16 @@ platform has to be installed in Xcode (Settings → Components, or### The analytics contract-The Analytics screen decodes the rollup the site's nightly pipeline writes,-and the two sides are held together by one fixture. The site builds it by-running the real consolidation over a small fixed record, so the JSON is what-the server serves today; the checked-in copy lives with the DonkeyKit tests,-and the site's tests fail while that copy is behind the pipeline. The DonkeyKit-tests decode the copy through the phone's model. Changing what the rollup-carries means regenerating the fixture from `site/` with-`npm run analytics:rollup-fixture` and running the DonkeyKit tests; the+The Analytics screen reads what the web dashboard reads: the summary the site+folds out of its nightly rollup — one point per day and the headline numbers,+no account rows — and the accounts a page at a time, following the cursor the+API hands back. Two fixtures hold the sides together: the site builds them by+running the real consolidation over a small fixed record and folding it the way+the API does, so the JSON is what the server serves today; the checked-in copies live+with the DonkeyKit tests, and the site's tests fail while one is behind the+pipeline. The DonkeyKit tests decode them through the phone's model. Changing+what either carries means regenerating them from `site/` with+`npm run analytics:summary-fixture` and running the DonkeyKit tests; theAnalytics Contract workflow runs both on every change to either side, and theTestFlight script runs the DonkeyKit tests before it archives.diff --git a/site/package.json b/site/package.jsonindex 1b5e0922..1df7d1bc 100644--- a/site/package.json+++ b/site/package.json@@ -33,7 +33,7 @@"eval:cut-headless": "bun run scripts/eval-cut-headless.ts","email:dev": "email dev --dir src/emails --port 3001","test": "bun test src packages/effects-kit/src packages/abexp/src scripts/lib/cut-eval",- "analytics:rollup-fixture": "bun run scripts/analytics-rollup-fixture.ts",+ "analytics:summary-fixture": "bun run scripts/analytics-summary-fixture.ts","test:genvideo": "bun run scripts/genvideo-selftest.ts","eval:genvideo": "bun run scripts/genvideo-eval.ts","eval:cut-perf": "bun run scripts/eval-cut-perf.ts",diff --git a/site/scripts/analytics-rollup-fixture.ts b/site/scripts/analytics-rollup-fixture.tsdeleted file mode 100644index bcab3687..00000000--- a/site/scripts/analytics-rollup-fixture.ts+++ /dev/null@@ -1,14 +0,0 @@-// Rewrites the analytics rollup fixture the DonkeyKit tests decode. Run it-// after changing what the rollup carries, then run the DonkeyKit tests.-//-// npm run analytics:rollup-fixture-import { mkdirSync, writeFileSync } from "node:fs";-import { dirname, resolve } from "node:path";-import { fileURLToPath } from "node:url";--import { ROLLUP_FIXTURE_PATH, rollupFixtureJson } from "@/lib/analytics/rollup-fixture";--const path = resolve(fileURLToPath(new URL("../..", import.meta.url)), ROLLUP_FIXTURE_PATH);-mkdirSync(dirname(path), { recursive: true });-writeFileSync(path, await rollupFixtureJson());-console.log(`wrote ${path}`);diff --git a/site/scripts/analytics-summary-fixture.ts b/site/scripts/analytics-summary-fixture.tsnew file mode 100644index 00000000..5892c1a2--- /dev/null+++ b/site/scripts/analytics-summary-fixture.ts@@ -0,0 +1,26 @@+// Rewrites the analytics fixtures the DonkeyKit tests decode — the summary and+// the first page of accounts. Run it after changing what either carries, then+// run the DonkeyKit tests.+//+// npm run analytics:summary-fixture+import { mkdirSync, writeFileSync } from "node:fs";+import { dirname, resolve } from "node:path";+import { fileURLToPath } from "node:url";++import {+ SUMMARY_FIXTURE_PATH,+ USERS_FIXTURE_PATH,+ summaryFixtureJson,+ usersFixtureJson,+} from "@/lib/analytics/summary-fixture";++const root = fileURLToPath(new URL("../..", import.meta.url));+for (const [relative, json] of [+ [SUMMARY_FIXTURE_PATH, await summaryFixtureJson()],+ [USERS_FIXTURE_PATH, await usersFixtureJson()],+] as const) {+ const path = resolve(root, relative);+ mkdirSync(dirname(path), { recursive: true });+ writeFileSync(path, json);+ console.log(`wrote ${path}`);+}diff --git a/site/src/lib/analytics/rollup-fixture.test.ts b/site/src/lib/analytics/rollup-fixture.test.tsdeleted file mode 100644index ab1f7e27..00000000--- a/site/src/lib/analytics/rollup-fixture.test.ts+++ /dev/null@@ -1,29 +0,0 @@-import { describe, expect, test } from "bun:test";-import { readFileSync } from "node:fs";-import { resolve } from "node:path";-import { fileURLToPath } from "node:url";--import { ROLLUP_FIXTURE_PATH, buildRollupFixture, rollupFixtureJson } from "./rollup-fixture";-import { analyticsRollupSchema } from "./schema";--describe("the phone's rollup fixture", () => {- test("is a rollup the dashboards read", async () => {- const parsed = analyticsRollupSchema.parse(await buildRollupFixture());- expect(parsed.days).toHaveLength(3);- expect(parsed.billing?.days).toHaveLength(4);- expect(parsed.missing).toEqual([{ day: "2026-08-31", sources: ["db", "posthog"] }]);- expect(parsed.users.map((u) => u.id)).toEqual(["u_new", "u_pro", "u_su"]);- });-- test("matches the copy checked in with the DonkeyKit tests", async () => {- const here = fileURLToPath(new URL(".", import.meta.url));- const checkedIn = readFileSync(resolve(here, "../../../..", ROLLUP_FIXTURE_PATH), "utf8");- const current = await rollupFixtureJson();- if (checkedIn !== current) {- throw new Error(- "The rollup's shape changed. Run `npm run analytics:rollup-fixture` in site/, then `swift test` in apps/ios/DonkeyKit so the phone's model still reads it.",- );- }- expect(checkedIn).toBe(current);- });-});diff --git a/site/src/lib/analytics/summary-fixture.test.ts b/site/src/lib/analytics/summary-fixture.test.tsnew file mode 100644index 00000000..2394d083--- /dev/null+++ b/site/src/lib/analytics/summary-fixture.test.ts@@ -0,0 +1,59 @@+import { describe, expect, test } from "bun:test";+import { readFileSync } from "node:fs";+import { resolve } from "node:path";+import { fileURLToPath } from "node:url";++import {+ SUMMARY_FIXTURE_PATH,+ USERS_FIXTURE_PATH,+ buildRollupFixture,+ buildSummaryFixture,+ buildUsersFixture,+ summaryFixtureJson,+ usersFixtureJson,+} from "./summary-fixture";+import { analyticsRollupSchema } from "./schema";++describe("the phone's summary fixture", () => {+ test("is a rollup the dashboards read", async () => {+ const parsed = analyticsRollupSchema.parse(await buildRollupFixture());+ expect(parsed.days).toHaveLength(3);+ expect(parsed.billing?.days).toHaveLength(4);+ expect(parsed.missing).toEqual([{ day: "2026-08-31", sources: ["db", "posthog"] }]);+ expect(parsed.users.map((u) => u.id)).toEqual(["u_new", "u_pro", "u_su"]);+ });++ test("carries the folded numbers and no account rows", async () => {+ const summary = await buildSummaryFixture();+ expect(summary.series).toHaveLength(3);+ expect(summary.registered).toBe(3);+ expect(summary.series.map((point) => point.active)).toEqual([2, null, 3]);+ expect(summary.missing).toEqual(["2026-08-31"]);+ expect(Object.keys(summary)).not.toContain("users");+ });++ test("pages accounts the way both clients read them", async () => {+ const page = await buildUsersFixture();+ expect(page.users.map((user) => user.id)).toEqual(["u_pro", "u_new", "u_su"]);+ expect(page.total).toBe(3);+ expect(page.nextCursor).toBeNull();+ expect(page.sorts.map((sort) => sort.id)).toEqual(["active", "recent", "joined", "paid"]);+ });++ test("matches the copies checked in with the DonkeyKit tests", async () => {+ const here = fileURLToPath(new URL(".", import.meta.url));+ const copies = [+ [SUMMARY_FIXTURE_PATH, await summaryFixtureJson()],+ [USERS_FIXTURE_PATH, await usersFixtureJson()],+ ] as const;+ for (const [path, current] of copies) {+ const checkedIn = readFileSync(resolve(here, "../../../..", path), "utf8");+ if (checkedIn !== current) {+ throw new Error(+ `${path} is behind the code. Run \`npm run analytics:summary-fixture\` in site/, then \`swift test\` in apps/ios/DonkeyKit so the phone's model still reads it.`,+ );+ }+ expect(checkedIn).toBe(current);+ }+ });+});diff --git a/site/src/lib/analytics/rollup-fixture.ts b/site/src/lib/analytics/summary-fixture.tssimilarity index 72%rename from site/src/lib/analytics/rollup-fixture.tsrename to site/src/lib/analytics/summary-fixture.tsindex 4d3e9dec..ea5af9ea 100644--- a/site/src/lib/analytics/rollup-fixture.ts+++ b/site/src/lib/analytics/summary-fixture.ts@@ -1,17 +1,22 @@-// The rollup the phone's model is tested against. It is the real consolidation-// (buildRollup) run over a small fixed record, so the JSON says exactly what-// the nightly job writes today.+// The summary the phone's model is tested against. It is the real+// consolidation (buildRollup) run over a small fixed record, folded by the+// same summarizeRollup the API answers with, so the JSON says exactly what+// /api/analytics/summary serves today.//// The checked-in copy lives with the DonkeyKit tests; `npm run-// analytics:rollup-fixture` rewrites it. rollup-fixture.test.ts fails while+// analytics:summary-fixture` rewrites it. summary-fixture.test.ts fails while// the copy is behind this code, and the DonkeyKit tests decode the copy, so a-// change to the rollup's shape reaches the phone in the same change.+// change to the summary's shape reaches the phone in the same change.import { buildRollup } from "./pipeline";+import { rankUsers, USER_SORTS, USERS_PAGE_SIZE, type AnalyticsUsersPage } from "./rank";+import { summarizeRollup, type AnalyticsSummary } from "./summarize";import type { AnalyticsRollup, AnalyticsSnapshotFile } from "./schema";import type { AnalyticsDayFiles } from "./pipeline";-export const ROLLUP_FIXTURE_PATH =- "apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/Fixtures/analytics-rollup.json";+export const SUMMARY_FIXTURE_PATH =+ "apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/Fixtures/analytics-summary.json";+export const USERS_FIXTURE_PATH =+ "apps/ios/DonkeyKit/Tests/DonkeyKitModelsTests/Fixtures/analytics-users.json";// Three closed days of activity, and a billing window that runs one day// further, to today: the two windows never line up by index.@@ -95,6 +100,29 @@ export function buildRollupFixture(): Promise<AnalyticsRollup> {});}-export async function rollupFixtureJson(): Promise<string> {- return `${JSON.stringify(await buildRollupFixture(), null, 2)}\n`;+export async function buildSummaryFixture(): Promise<AnalyticsSummary> {+ return summarizeRollup(await buildRollupFixture());+}++export async function summaryFixtureJson(): Promise<string> {+ return `${JSON.stringify(await buildSummaryFixture(), null, 2)}\n`;+}++/** The first page of accounts, exactly as the users route answers it. */+export async function buildUsersFixture(): Promise<AnalyticsUsersPage> {+ const rollup = await buildRollupFixture();+ const ranked = rankUsers(rollup, "active");+ const end = USERS_PAGE_SIZE;+ return {+ generatedAt: rollup.generatedAt,+ nextCursor: end >= ranked.length ? null : end,+ pageSize: USERS_PAGE_SIZE,+ sorts: USER_SORTS,+ total: ranked.length,+ users: ranked.slice(0, end),+ };+}++export async function usersFixtureJson(): Promise<string> {+ return `${JSON.stringify(await buildUsersFixture(), null, 2)}\n`;}