Usage insights

From gustavscirulis/snapgrid · View interactive version

Usage insights is an AI agent skill from the GitHub repository gustavscirulis/snapgrid. Generates user-facing usage statistics, activity summaries, and personalized insights dashboards (weekly recaps, year-in-review, Spotify Wrapped-style). Use when user wants to show usage stats, activity insights, or shareable recap screens. Different from analytics-setup which sends data to a backen

How to use this skill

Skill file

Usage Insights Generator

Generate a production usage insights system that records user activity events with SwiftData, computes personalized insights (streaks, most active day, top categories), and displays them in a dashboard with insight cards, period pickers, trend indicators, and optional shareable recap screens.

When This Skill Activates

Use this skill when the user:

Pre-Generation Checks

1. Project Context Detection

2. Conflict Detection

Search for existing usage tracking or insights code:

Glob: **/*UsageEvent*.swift, **/*Insight*.swift, **/*Recap*.swift, **/*ActivityLog*.swift
Grep: "UsageEvent" or "InsightCalculator" or "activitySummary" or "SwiftData" and "event"

If existing analytics/tracking found:

3. Data Layer Detection

Check for SwiftData usage:

Grep: "import SwiftData" or "@Model" or "ModelContainer"

If SwiftData already in use:

If no SwiftData:

Configuration Questions

Ask user via AskUserQuestion:

  1. Insight period?
  1. Visualization style?
  1. Include shareable recap card?
  1. Data source?

Generation Process

Step 1: Read Templates

Read templates.md for production Swift code.

Step 2: Create Core Data Files

Generate these files:

  1. UsageEvent.swift — SwiftData @Model for recording user activity events
  2. InsightResult.swift — Model for computed insights (title, value, trend, visualization type)

Step 3: Create Calculation Engine

  1. InsightCalculator.swift — Pure functions that aggregate events into insights

Step 4: Create UI Files

  1. InsightsDashboardView.swift — Main dashboard with grid of insight cards and period picker
  2. InsightCardView.swift — Individual insight card with icon, value, trend indicator, sparkline

Step 5: Create Optional Files

Based on configuration:

Step 6: Determine File Location

Check project structure:

Output Format

After generation, provide:

Files Created

UsageInsights/
├── UsageEvent.swift           # SwiftData @Model for activity events
├── InsightResult.swift        # Computed insight model
├── InsightCalculator.swift    # Aggregation engine
├── InsightsDashboardView.swift # Dashboard with period picker
├── InsightCardView.swift      # Individual insight card
├── UsageRecapView.swift       # Shareable recap (optional)
└── UsageEventRecorder.swift   # Event recording helper (optional)

Integration Steps

Add ModelContainer (if not already present):

@main
struct MyApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        .modelContainer(for: [UsageEvent.self])
    }
}

Record events from anywhere in the app:

struct TaskDetailView: View {
    @Environment(\.modelContext) private var modelContext
    @State private var recorder: UsageEventRecorder?

    var body: some View {
        Button("Complete Task") {
            completeTask()
            recorder?.record(
                .taskCompleted,
                metadata: ["category": "work", "priority": "high"]
            )
        }
        .onAppear {
            recorder = UsageEventRecorder(modelContext: modelContext)
        }
    }
}

Show the insights dashboard:

NavigationLink("My Insights") {
    InsightsDashboardView()
}

Show a weekly recap:

struct WeeklyRecapSheet: View {
    @Environment(\.modelContext) private var modelContext
    @State private var showRecap = false

    var body: some View {
        Button("View Weekly Recap") {
            showRecap = true
        }
        .sheet(isPresented: $showRecap) {
            UsageRecapView(period: .week)
        }
    }
}

Record events with duration tracking:

// Start a timed session
let sessionStart = Date()

// ... user does work ...

// Record when session ends
recorder?.record(
    .sessionCompleted,
    metadata: ["screen": "editor"],
    duration: Date().timeIntervalSince(sessionStart)
)

Testing

@Test
func calculatesWeeklySummaryCorrectly() async throws {
    let calendar = Calendar.current
    let now = Date()
    let events: [UsageEvent] = (0..<7).flatMap { dayOffset in
        let date = calendar.date(byAdding: .day, value: -dayOffset, to: now)!
        return (0..<(dayOffset == 2 ? 5 : 2)).map { _ in
            UsageEvent(eventType: "taskCompleted", timestamp: date)
        }
    }

    let calculator = InsightCalculator()
    let insights = calculator.weeklySummary(from: events, referenceDate: now)

    let totalInsight = insights.first { $0.title == "Total Events" }
    #expect(totalInsight != nil)
    #expect(totalInsight?.value == "19") // 5 + (6 * 2)
}

@Test
func identifiesMostActiveDay() async throws {
    let calendar = Calendar.current
    let now = Date()

    // Create 5 events on Wednesday, 2 on other days
    var events: [UsageEvent] = []
    for dayOffset in 0..<7 {
        let date = calendar.date(byAdding: .day, value: -dayOffset, to: now)!
        let count = calendar.component(.weekday, from: date) == 4 ? 5 : 1
        for _ in 0..<count {
            events.append(UsageEvent(eventType: "action", timestamp: date))
        }
    }

    let calculator = InsightCalculator()
    let insights = calculator.weeklySummary(from: events, referenceDate: now)
    let mostActive = insights.first { $0.title == "Most Active Day" }
    #expect(mostActive?.value == "Wednesday")
}

@Test
func handlesEmptyEventList() async throws {
    let calculator = InsightCalculator()
    let insights = calculator.weeklySummary(from: [], referenceDate: Date())

    #expect(!insights.isEmpty) // Should still return cards with zero values
    let totalInsight = insights.first { $0.title == "Total Events" }
    #expect(totalInsight?.value == "0")
}

@Test
func recorderBatchesWritesForPerformance() async throws {
    let config = ModelConfiguration(isStoredInMemoryOnly: true)
    let container = try ModelContainer(for: UsageEvent.self, configurations: config)
    let context = ModelContext(container)
    let recorder = UsageEventRecorder(modelContext: context)

    // Record 100 events rapidly
    for i in 0..<100 {
        recorder.record(.custom("event_\(i)"))
    }

    // Flush pending writes
    recorder.flush()

    let descriptor = FetchDescriptor<UsageEvent>()
    let count = try context.fetchCount(descriptor)
    #expect(count == 100)
}

Common Patterns

Record an Event

recorder?.record(.featureUsed, metadata: ["feature": "darkMode"])

Calculate a Weekly Summary

let calculator = InsightCalculator()
let events = try modelContext.fetch(FetchDescriptor<UsageEvent>())
let insights = calculator.weeklySummary(from: events, referenceDate: Date())

Render Insight Cards in a Grid

LazyVGrid(columns: [GridItem(.flexible()), GridItem(.flexible())], spacing: 16) {
    ForEach(insights) { insight in
        InsightCardView(insight: insight)
    }
}

Generate and Share a Recap Image

let renderer = ImageRenderer(content: UsageRecapView(period: .week))
renderer.scale = 2.0
if let image = renderer.uiImage {
    // Use with ShareLink or UIActivityViewController
}

Gotchas

Privacy: All Data Stays On-Device

Performance with Large Datasets

Calendar-Based Period Calculations

Swift Charts Considerations

Trend Comparison Edge Cases

References

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.