Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

fix(analytics): join onboarding answers with UTM attribution

Louis Beaumont89270f104b84
diff --git a/apps/screenpipe-app-tauri/components/onboarding/acquisition-step.test.tsx b/apps/screenpipe-app-tauri/components/onboarding/acquisition-step.test.tsx
index b205757ff..88e138588 100644
--- a/apps/screenpipe-app-tauri/components/onboarding/acquisition-step.test.tsx
+++ b/apps/screenpipe-app-tauri/components/onboarding/acquisition-step.test.tsx
@@ -6,12 +6,16 @@ import "@testing-library/jest-dom/vitest";
import React from "react";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
-import AcquisitionStep, { ACQUISITION_SOURCES } from "./acquisition-step";
+import AcquisitionStep, {
+ ACQUISITION_SOURCES,
+ buildAcquisitionAnalyticsProperties,
+} from "./acquisition-step";
const mocks = vi.hoisted(() => ({
updateSettings: vi.fn().mockResolvedValue(undefined),
capture: vi.fn(),
setPerson: vi.fn(),
+ getOnboardingAttribution: vi.fn().mockResolvedValue(null),
}));
vi.mock("@/lib/hooks/use-settings", () => ({
@@ -28,6 +32,12 @@ vi.mock("posthog-js", () => ({
},
}));
+vi.mock("@/lib/utils/tauri", () => ({
+ commands: {
+ getOnboardingAttribution: mocks.getOnboardingAttribution,
+ },
+}));
+
beforeEach(() => {
vi.clearAllMocks();
});
@@ -48,7 +58,12 @@ describe("acquisition step", () => {
});
expect(mocks.capture).toHaveBeenCalledWith(
"onboarding_acquisition_answered",
- expect.objectContaining({ source: "reddit", answered: true }),
+ expect.objectContaining({
+ source: "reddit",
+ acquisition_source: "reddit",
+ answered: true,
+ attribution_available: false,
+ }),
);
});
@@ -62,7 +77,12 @@ describe("acquisition step", () => {
expect(mocks.updateSettings).not.toHaveBeenCalled();
expect(mocks.capture).toHaveBeenCalledWith(
"onboarding_acquisition_answered",
- expect.objectContaining({ source: "skipped", answered: false }),
+ expect.objectContaining({
+ source: "skipped",
+ acquisition_source: "skipped",
+ answered: false,
+ attribution_available: false,
+ }),
);
});
@@ -75,6 +95,45 @@ describe("acquisition step", () => {
fireEvent.click(screen.getByTestId("acquisition-option-search"));
await waitFor(() => expect(next).toHaveBeenCalledTimes(1));
+ expect(mocks.capture).toHaveBeenCalledWith(
+ "onboarding_acquisition_answered",
+ expect.objectContaining({ acquisition_source: "search" }),
+ );
+ });
+
+ it("puts observed website attribution beside the self-reported answer", async () => {
+ mocks.getOnboardingAttribution.mockResolvedValueOnce({
+ utmSource: "chatgpt.com",
+ utmMedium: "referral",
+ utmCampaign: "launch",
+ utmContent: null,
+ utmTerm: null,
+ });
+ const next = vi.fn();
+ render(<AcquisitionStep handleNextSlide={next} />);
+
+ fireEvent.click(screen.getByTestId("acquisition-option-ai_assistant"));
+
+ await waitFor(() => expect(next).toHaveBeenCalledTimes(1));
+ expect(mocks.capture).toHaveBeenCalledWith(
+ "onboarding_acquisition_answered",
+ expect.objectContaining({
+ acquisition_source: "ai_assistant",
+ attribution_available: true,
+ utm_source: "chatgpt.com",
+ utm_medium: "referral",
+ utm_campaign: "launch",
+ }),
+ );
+ });
+
+ it("omits absent UTM fields instead of inventing direct attribution", () => {
+ expect(buildAcquisitionAnalyticsProperties("friend", null)).toEqual({
+ source: "friend",
+ acquisition_source: "friend",
+ answered: true,
+ attribution_available: false,
+ });
});
it("offers every source and never a free-text field", () => {
diff --git a/apps/screenpipe-app-tauri/components/onboarding/acquisition-step.tsx b/apps/screenpipe-app-tauri/components/onboarding/acquisition-step.tsx
index 81d9141fb..b30641859 100644
--- a/apps/screenpipe-app-tauri/components/onboarding/acquisition-step.tsx
+++ b/apps/screenpipe-app-tauri/components/onboarding/acquisition-step.tsx
@@ -8,6 +8,7 @@ import React, { useState } from "react";
import { motion } from "framer-motion";
import posthog from "posthog-js";
import { useSettings } from "@/lib/hooks/use-settings";
+import { commands, type Attribution } from "@/lib/utils/tauri";
interface AcquisitionStepProps {
handleNextSlide: () => void;
@@ -42,6 +43,29 @@ export const ACQUISITION_SOURCES = [
export type AcquisitionSource = (typeof ACQUISITION_SOURCES)[number]["value"];
+export function buildAcquisitionAnalyticsProperties(
+ source: AcquisitionSource | null,
+ attribution: Attribution | null,
+) {
+ const acquisitionSource = source ?? "skipped";
+
+ return {
+ // Keep `source` while existing PostHog insights migrate to the canonical
+ // property name used on the person profile.
+ source: acquisitionSource,
+ acquisition_source: acquisitionSource,
+ answered: Boolean(source),
+ attribution_available: Boolean(attribution),
+ ...(attribution?.utmSource && { utm_source: attribution.utmSource }),
+ ...(attribution?.utmMedium && { utm_medium: attribution.utmMedium }),
+ ...(attribution?.utmCampaign && {
+ utm_campaign: attribution.utmCampaign,
+ }),
+ ...(attribution?.utmContent && { utm_content: attribution.utmContent }),
+ ...(attribution?.utmTerm && { utm_term: attribution.utmTerm }),
+ };
+}
+
const AcquisitionStep: React.FC<AcquisitionStepProps> = ({
handleNextSlide,
}) => {
@@ -56,16 +80,34 @@ const AcquisitionStep: React.FC<AcquisitionStepProps> = ({
if (source) {
// Persist locally so a later reinstall or support conversation can see
// it, and set it as a person property so cohorts can be built on it.
- await updateSettings({ acquisitionSource: source });
- posthog.people?.set?.({ acquisition_source: source });
+ try {
+ await updateSettings({ acquisitionSource: source });
+ } catch (error) {
+ console.warn("[onboarding] failed to persist acquisition source", error);
+ }
+ try {
+ posthog.people?.set?.({ acquisition_source: source });
+ } catch (error) {
+ console.warn("[onboarding] failed to set acquisition person property", error);
+ }
+ }
+
+ let attribution: Attribution | null = null;
+ try {
+ attribution = await commands.getOnboardingAttribution();
+ } catch (error) {
+ console.warn("[onboarding] failed to read website attribution", error);
+ }
+
+ try {
+ posthog.capture(
+ "onboarding_acquisition_answered",
+ buildAcquisitionAnalyticsProperties(source, attribution),
+ );
+ } catch (error) {
+ // A missing attribution event must never block setup.
+ console.warn("[onboarding] failed to record acquisition source", error);
}
- posthog.capture("onboarding_acquisition_answered", {
- source: source ?? "skipped",
- answered: Boolean(source),
- });
- } catch (error) {
- // A missing attribution answer must never block setup.
- console.warn("[onboarding] failed to record acquisition source", error);
} finally {
setSaving(false);
handleNextSlide();
diff --git a/apps/screenpipe-app-tauri/lib/utils/tauri.ts b/apps/screenpipe-app-tauri/lib/utils/tauri.ts
index b3bfc7b03..45af6ea97 100644
--- a/apps/screenpipe-app-tauri/lib/utils/tauri.ts
+++ b/apps/screenpipe-app-tauri/lib/utils/tauri.ts
@@ -707,6 +707,15 @@ async getMonitors() : Promise<Result<MonitorDevice[], string>> {
else return { status: "error", error: e as any };
}
},
+/**
+ * Return the website UTM attribution already resolved at app startup.
+ *
+ * This is read-only and never triggers another network request. Analytics can
+ * be disabled before the manager is installed, so absence is a normal result.
+ */
+async getOnboardingAttribution() : Promise<Attribution | null> {
+ return await TAURI_INVOKE("get_onboarding_attribution");
+},
async getOnboardingStatus() : Promise<Result<OnboardingStore, string>> {
try {
return { status: "ok", data: await TAURI_INVOKE("get_onboarding_status") };
@@ -2972,6 +2981,7 @@ export type ActivityHistoryCoverage = { start: string; end: string }
export type ActivityHistoryEntry = { id: string; kind: string; meeting_id: number | null; start_at: string; end_at: string; title: string; summary: string; evidence: ActivityHistoryEvidence[] }
export type ActivityHistoryEvidence = { kind: string; at: string; frame_id: number | null; meeting_id: number | null; app_name: string | null; label: string }
export type AecMode = "off" | "screenpipe" | "macos" | "windows"
+export type Attribution = { utmSource: string | null; utmMedium: string | null; utmCampaign: string | null; utmContent: string | null; utmTerm: string | null }
export type AudioDeviceInfo = { name: string; isDefault: boolean;
/**
* True for a Bluetooth *input* device that is also a combo headset (the
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/analytics.rs b/apps/screenpipe-app-tauri/src-tauri/src/analytics.rs
index 71e84ae89..f195f1861 100755
--- a/apps/screenpipe-app-tauri/src-tauri/src/analytics.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/analytics.rs
@@ -14,7 +14,8 @@ use sysinfo::{System, SystemExt};
use tokio::sync::Mutex;
use tokio::time::interval;
-#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, specta::Type)]
+#[serde(rename_all = "camelCase")]
pub struct Attribution {
pub utm_source: Option<String>,
pub utm_medium: Option<String>,
@@ -146,6 +147,13 @@ impl AnalyticsManager {
}
}
+ /// Return the website attribution cached at app startup without making
+ /// another network request. The onboarding webview uses this snapshot to
+ /// put the observed UTM fields on the same event as the user's answer.
+ pub async fn attribution_snapshot(&self) -> Option<Attribution> {
+ self.attribution.lock().await.clone()
+ }
+
/// Send a $create_alias event so PostHog merges the email-based identity
/// (used by the website download endpoint) with this app's analytics UUID.
pub async fn send_alias(&self, alias: &str) {
@@ -642,4 +650,28 @@ mod tests {
"always"
);
}
+
+ #[tokio::test]
+ async fn attribution_snapshot_returns_the_cached_first_touch_values() {
+ let manager = AnalyticsManager::new(
+ "posthog-key".to_string(),
+ "analytics-id".to_string(),
+ String::new(),
+ 1,
+ "http://127.0.0.1:3030".to_string(),
+ None,
+ PathBuf::new(),
+ false,
+ );
+ let expected = Attribution {
+ utm_source: Some("chatgpt.com".to_string()),
+ utm_medium: Some("referral".to_string()),
+ utm_campaign: None,
+ utm_content: None,
+ utm_term: None,
+ };
+ *manager.attribution.lock().await = Some(expected.clone());
+
+ assert_eq!(manager.attribution_snapshot().await, Some(expected));
+ }
}
diff --git a/apps/screenpipe-app-tauri/src-tauri/src/commands.rs b/apps/screenpipe-app-tauri/src-tauri/src/commands.rs
index 6eb12c049..ee58b4fc5 100644
--- a/apps/screenpipe-app-tauri/src-tauri/src/commands.rs
+++ b/apps/screenpipe-app-tauri/src-tauri/src/commands.rs
@@ -10,6 +10,7 @@ mod native_actions;
pub(crate) mod overlay_anchor;
use crate::{
+ analytics::{AnalyticsManager, Attribution},
native_notification, native_shortcut_reminder,
store::{OnboardingStore, SettingsStore},
updates::is_enterprise_build,
@@ -413,6 +414,18 @@ pub fn is_telemetry_disabled_by_env() -> bool {
screenpipe_engine::analytics::telemetry_disabled_by_env()
}
+/// Return the website UTM attribution already resolved at app startup.
+///
+/// This is read-only and never triggers another network request. Analytics can
+/// be disabled before the manager is installed, so absence is a normal result.
+#[tauri::command]
+#[specta::specta]
+pub async fn get_onboarding_attribution(app_handle: tauri::AppHandle) -> Option<Attribution> {
+ let analytics = app_handle.try_state::<std::sync::Arc<AnalyticsManager>>()?;
+ let analytics = std::sync::Arc::clone(&analytics);
+ analytics.attribution_snapshot().await
+}
+
/// Return the macOS bundle identifier of the running app
/// (e.g. `screenpi.pe`, `screenpi.pe.beta`, `screenpi.pe.dev`,
/// `screenpi.pe.enterprise`). The onboarding stuck-screen surfaces this so