The VS Code of video editing, built for agents.
TypeScript
Refactor analytics tracking and configuration in desktop application
konstantin-paulus73e578f47cd7
diff --git a/apps/desktop/src/analytics.ts b/apps/desktop/src/analytics.tsindex dc60ac90..ff536c64 100644--- a/apps/desktop/src/analytics.ts+++ b/apps/desktop/src/analytics.ts@@ -3,84 +3,105 @@* file, You can obtain one at http://mozilla.org/MPL/2.0/. */import { app } from "electron";+import { randomUUID } from "node:crypto";import { join } from "node:path";-import { access, writeFile } from "node:fs/promises";+import { stat, writeFile } from "node:fs/promises";-/**- * Desktop analytics. The renderer's Umami script never fires inside Electron- * (its `data-domains` gate does not match the `file://` origin), so main- * posts events directly to Umami's send API: the renderer's product events- * arrive over `ANALYTICS_TRACK`, and the install event is sent from here.- *- * Install tracking is proxied by the first launch of a packaged build: one- * event, then a marker file in `userData` to never send it again. Offline- * first launches retry on the next launch.- */+import type { ClientEventName, TrackedEvent, TrackProps } from "@diffusionstudio/api-contract";++const enabled = app.isPackaged || process.env.DIFFUSION_ANALYTICS === "1";++const FLUSH_INTERVAL_MS = 30_000;+const BATCH_MAX = 100;+const QUEUE_MAX = 2_000;-const UMAMI_ENDPOINT = "https://cloud.umami.is/api/send";-const UMAMI_WEBSITE_ID = "e898e381-6ce3-4f5f-a485-8327ec9aa88b";-const HOSTNAME = "desktop.diffusion.studio";-const MARKER_FILE = "install-tracked";--// Umami discards events whose User-Agent trips its bot filter, which both-// Node's fetch default and Electron's own UA do — send a plain browser UA-// that still attributes the right OS.-function userAgent(): string {- const platform =- process.platform === "darwin"- ? "Macintosh; Intel Mac OS X 10_15_7"- : process.platform === "win32"- ? "Windows NT 10.0; Win64; x64"- : "X11; Linux x86_64";- return `Mozilla/5.0 (${platform}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36`;+const queue: TrackedEvent[] = [];++let apiUrl: string | null = null;+let token: string | null | undefined;++/** Canvas edits by kind, and source files changed from outside the app, since the last flush. */+let canvasEdits: Record<string, number> = {};+let changedFiles = new Set<string>();++export function configureAnalytics(config: { apiUrl: string; token: string | null }): void {+ apiUrl = config.apiUrl;+ token = config.token;}-export type AnalyticsEventData = Record<string, string | number | boolean>;+export function track(name: ClientEventName, props: TrackProps = {}): void {+ if (!enabled) return;+ // Undefined values would fail validation; JSON leaves them out.+ queue.push({+ id: randomUUID(),+ at: new Date().toISOString(),+ name,+ props: JSON.parse(JSON.stringify(props)),+ });-/** Post one event to Umami. Resolves to whether Umami accepted it; never throws. */-async function sendEvent(name: string, url: string, data: AnalyticsEventData): Promise<boolean> {- try {- const response = await fetch(UMAMI_ENDPOINT, {- method: "POST",- headers: { "Content-Type": "application/json", "User-Agent": userAgent() },- body: JSON.stringify({- type: "event",- payload: { website: UMAMI_WEBSITE_ID, hostname: HOSTNAME, url, name, data },- }),- });- return response.ok;- } catch {- // Offline or Umami unreachable.- return false;+ if (queue.length > QUEUE_MAX) {+ queue.splice(0, queue.length - QUEUE_MAX);}}-/** A product event from the renderer. Dev builds stay out of the numbers. */-export async function trackEvent(name: string, data: AnalyticsEventData = {}): Promise<void> {- if (!app.isPackaged) return;- await sendEvent(name, "/desktop", {- ...data,- platform: process.platform,- version: app.getVersion(),- });+/** Edits the canvas wrote back to the source (move, insert, remove, …). */+export function countCanvasEdits(kinds: string[]): void {+ for (const kind of kinds) {+ canvasEdits[kind] = (canvasEdits[kind] ?? 0) + 1;+ }+}++/** A source file changed from outside the app: an agent or an editor writing code. */+export function countCodeChange(path: string): void {+ changedFiles.add(path);}-export async function trackInstall(): Promise<void> {- if (!app.isPackaged) return;+/**+ * Starts the flush timer and records the launch. The first launch of an+ * install is recorded once, guarded by a marker file in `userData`; its age+ * goes on every `app_opened`, so install-to-sign-up time needs no device id.+ */+export async function startAnalytics(): Promise<void> {+ if (!enabled) return;++ setInterval(flush, FLUSH_INTERVAL_MS);- const marker = join(app.getPath("userData"), MARKER_FILE);+ const marker = join(app.getPath("userData"), "install-tracked");+ const installedAt = await stat(marker).then((info) => info.birthtimeMs, () => null);++ if (installedAt === null) {+ track("app_installed", { arch: process.arch });+ await writeFile(marker, new Date().toISOString()).catch(() => { });+ }++ track("app_opened", { install_age_s: Math.round((Date.now() - (installedAt ?? Date.now())) / 1000) });+}++async function flush(): Promise<void> {+ const edits = Object.values(canvasEdits).reduce((sum, n) => sum + n, 0);+ if (edits) {+ track("canvas_edited", { edits, ...canvasEdits });+ }+ if (changedFiles.size) {+ track("code_changed", { files: changedFiles.size });+ }+ canvasEdits = {};+ changedFiles = new Set();++ if (!queue.length || !apiUrl || token === undefined) return;+ const batch = queue.splice(0, BATCH_MAX);try {- await access(marker);- return;+ const response = await fetch(`${apiUrl}/api/v2/trpc/events.track`, {+ method: "POST",+ headers: { "Content-Type": "application/json", ...(token ? { Authorization: `Bearer ${token}` } : {}) },+ body: JSON.stringify({ source: "desktop", appVersion: app.getVersion(), platform: process.platform, events: batch }),+ signal: AbortSignal.timeout(10_000),+ });+ // Sent, or a batch the API will never take (400): either way it is done.+ if (response.ok || response.status === 400) return;} catch {- // No marker yet — this is the first (tracked) launch.+ // Offline or the API unreachable.}- const sent = await sendEvent("desktop_install", "/desktop/install", {- platform: process.platform,- arch: process.arch,- version: app.getVersion(),- });- // Not sent — retried on the next launch.- if (sent) await writeFile(marker, new Date().toISOString()).catch(() => {});+ queue.unshift(...batch);}diff --git a/apps/desktop/src/dapi/server.ts b/apps/desktop/src/dapi/server.tsindex 5b0bef1b..dff2dbfc 100644--- a/apps/desktop/src/dapi/server.ts+++ b/apps/desktop/src/dapi/server.ts@@ -3,13 +3,14 @@* file, You can obtain one at http://mozilla.org/MPL/2.0/. */import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";-import { MCP_HOST, MCP_PATH, MCP_PORT, tools } from "@diffusionstudio/dapi";+import { MCP_HOST, MCP_PATH, MCP_PORT, isDapiError, tools } from "@diffusionstudio/dapi";import { mainHandlers } from "./handlers";import { DapiHttpServer } from "./http";import { instructions } from "./docs";import { RendererCalls } from "./renderer-calls";import { serveCatalog } from "./tools-session";+import type { TrackProps } from "@diffusionstudio/api-contract";import type { LogEntry } from "@diffusionstudio/dapi";import type { AppWindow, MainContext, MainToolName } from "./handler";import type { RendererHost } from "./renderer-calls";@@ -33,6 +34,8 @@ export type DapiServerDeps = {};/** The staged docs: INSTRUCTIONS.md, their path, and the skill headers, all for every session. Null when not staged. */docsDir: string | null;+ /** Told about every finished call, as `tool_called` analytics props. */+ onToolCall?(props: TrackProps): void;};/**@@ -100,12 +103,27 @@ export class DapiServer {const session = new McpServer({ name: SERVER_NAME, title: "Diffusion Studio", version: this.deps.version }, { instructions: this.instructionsText });serveCatalog(session, async (tool, args, signal) => {const release = this.deps.window.hold();+ const startedAt = performance.now();+ // The failure's code (`not-found`, `busy`, …), never its message: messages name the user's files.+ let error: string | undefined;try {return await (tool.environment === "main" ?this.runInMain(tool.name as MainToolName, args, signal): this.renderer.call(tool.name, args, signal));+ } catch (thrown) {+ error = isDapiError(thrown) ? thrown.code : "error";+ throw thrown;} finally {release();+ const client = session.server.getClientVersion();+ this.deps.onToolCall?.({+ tool: tool.name,+ client: client?.name,+ client_version: client?.version,+ ok: !error,+ error,+ duration_ms: Math.round(performance.now() - startedAt),+ });}});return session;diff --git a/apps/desktop/src/main-channels.ts b/apps/desktop/src/main-channels.tsindex 67673215..17d1bc16 100644--- a/apps/desktop/src/main-channels.ts+++ b/apps/desktop/src/main-channels.ts@@ -30,7 +30,7 @@ export const MAIN_CHANNELS = {// Renderer→Main requestsAPP_OPEN_EXTERNAL: "app:open-external",APP_SHOW_IN_FOLDER: "app:show-in-folder",- ANALYTICS_TRACK: "analytics:track",+ ANALYTICS_CONFIGURE: "analytics:configure",AUTH_GET_PENDING_CALLBACK: "auth:get-pending-callback",CHECKOUT_GET_PENDING_CALLBACK: "checkout:get-pending-callback",WINDOW_IS_FULLSCREEN: "window:is-fullscreen",@@ -177,10 +177,9 @@ export type MainRequestMap = {request: { url: string };response: void;};- // A product event, posted to Umami by main (the renderer's script is inert- // in Electron).- [MAIN_CHANNELS.ANALYTICS_TRACK]: {- request: { event: string; data?: Record<string, string | number | boolean> };+ // Where main sends events and as whom: on launch and every auth change.+ [MAIN_CHANNELS.ANALYTICS_CONFIGURE]: {+ request: { apiUrl: string; token: string | null };response: void;};[MAIN_CHANNELS.AUTH_GET_PENDING_CALLBACK]: {diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.tsindex fc9006ef..bba51fa8 100644--- a/apps/desktop/src/main.ts+++ b/apps/desktop/src/main.ts@@ -14,7 +14,7 @@ import { DapiServer } from "./dapi/server";import { agentChatEndpoint, configureAgentChat, deleteProjectChats, stopAgentChat } from "./agent-chat";import { cliStatus, installCli, refreshCliShim, uninstallCli } from "./cli-install";import { applyMcp, healMcpRegistrations, mcpStatus } from "./mcp-install";-import { trackEvent, trackInstall } from "./analytics";+import { configureAnalytics, countCanvasEdits, startAnalytics, track } from "./analytics";import { setupAppMenu } from "./menu";import { AppTray } from "./tray";import { WindowHost } from "./window-host";@@ -171,6 +171,7 @@ const dapi = new DapiServer({hold: () => windows.hold(),lastProject: () => lastProject,},+ onToolCall: (props) => track("tool_called", props),});function pushLog(level: LogEntry["level"], message: string, source: string) {@@ -355,7 +356,7 @@ if (squirrelLaunch) {mainBridge.handle(MAIN_CHANNELS.APP_OPEN_EXTERNAL, ({ url }) => shell.openExternal(url));mainBridge.handle(MAIN_CHANNELS.APP_SHOW_IN_FOLDER, ({ path }) => shell.showItemInFolder(path));- mainBridge.handle(MAIN_CHANNELS.ANALYTICS_TRACK, ({ event, data }) => trackEvent(event, data));+ mainBridge.handle(MAIN_CHANNELS.ANALYTICS_CONFIGURE, (config) => configureAnalytics(config));mainBridge.handle(MAIN_CHANNELS.AUTH_GET_PENDING_CALLBACK, () =>takePendingDeepLink(MAIN_CHANNELS.AUTH_CALLBACK),);@@ -395,7 +396,10 @@ if (squirrelLaunch) {mainBridge.handle(MAIN_CHANNELS.PROJECTS_DUPLICATE, ({ dir }) => duplicateProject(dir));mainBridge.handle(MAIN_CHANNELS.PROJECTS_DELETE, ({ dir }) => deleteProject(dir).then(deleteProjectChats));mainBridge.handle(MAIN_CHANNELS.PROJECTS_COMPILE, ({ dir }) => compileProject(dir));- mainBridge.handle(MAIN_CHANNELS.PROJECTS_WRITE, ({ dir, edits }) => writeProject(dir, edits));+ mainBridge.handle(MAIN_CHANNELS.PROJECTS_WRITE, ({ dir, edits }) => {+ countCanvasEdits(edits.map((edit) => edit.kind));+ return writeProject(dir, edits);+ });mainBridge.handle(MAIN_CHANNELS.PROJECTS_WATCH, ({ dir }, event) => {lastProject = dir;tray.refresh();@@ -507,7 +511,7 @@ if (squirrelLaunch) {);refreshCliShim();healMcpRegistrations();- trackInstall();+ startAnalytics();tray.start();// Opened by a person (Finder, Dock, Start menu): show the editordiff --git a/apps/desktop/src/projects.ts b/apps/desktop/src/projects.tsindex 5bf04c33..a787d4c7 100644--- a/apps/desktop/src/projects.ts+++ b/apps/desktop/src/projects.ts@@ -16,6 +16,7 @@ import { parse as parseYaml, stringify as stringifyYaml } from "yaml";import type { PluginItem, TransformOptions } from "@babel/core";import type { BuildOptions, Plugin } from "esbuild";+import { countCodeChange } from "./analytics";import { isTempPath, TEMP_PREFIX, writeFileAtomic } from "./atomic";import { windowsCloudSyncKind } from "./cloud-sync-windows";import { mainBridge } from "./main-manager";@@ -1244,6 +1245,9 @@ export async function noteRenamed(temp: string, as: string): Promise<void> {claim(as, await digestOf(temp));}+/** The files a change to which counts as code being written, for analytics. */+const SOURCE_FILE = /\.[cm]?[jt]sx?$/;+export function watchProject(window: BrowserWindow | null, dir: string): void {if (watchers.has(dir)) return;@@ -1269,6 +1273,8 @@ export function watchProject(window: BrowserWindow | null, dir: string): void {const current = await digestOf(file);if (settleClaim(file, current) || known.get(file) === current) return;known.set(file, current);+ if (SOURCE_FILE.test(path) && current !== ABSENT) countCodeChange(path);+mainBridge.emit(window, MAIN_CHANNELS.PROJECTS_CHANGED, { dir, path });}).catch(() => { });diff --git a/apps/web/.env.example b/apps/web/.env.exampleindex 3042c542..fac63030 100644--- a/apps/web/.env.example+++ b/apps/web/.env.example@@ -1,9 +1,5 @@VITE_SUPABASE_URL=https://mpvhvyxuqfcemfnwiaiq.supabase.coVITE_SUPABASE_ANON_KEY=sb_publishable_V-K9coUWXVy8dsZPGKDw-g_d1JzJf8u-VITE_UMAMI_WEBSITE_ID=e898e381-6ce3-4f5f-a485-8327ec9aa88b-VITE_UMAMI_SCRIPT_URL=https://cloud.umami.is/script.js-VITE_UMAMI_DOMAINS=diffusion.studio,app.diffusion.studio-# The Diffusion Studio API; http://localhost:3000 for a local oneVITE_API_URL=https://api.diffusion.studiodiff --git a/apps/web/src/agent-chat/store.ts b/apps/web/src/agent-chat/store.tsindex f3e446a3..c4107bee 100644--- a/apps/web/src/agent-chat/store.ts+++ b/apps/web/src/agent-chat/store.ts@@ -28,6 +28,7 @@ import {import type { Transcript } from "@diffusionstudio/agent-chat";import { store as settings } from "@/init";+import { track } from "@/lib/analytics";import { createStoredSignal } from "@/lib/store";import { projectRoute } from "@/hooks/use-project-route";import type { ProjectInfo } from "@/projects";@@ -301,6 +302,13 @@ export type SendOptions = {/** Sends a turn; resolves with the chat id as soon as the host accepted it. */export async function send(options: SendOptions): Promise<string> {const key = draftKey(options.projectId, options.chatId);+ track("prompt_sent", {+ new_chat: !options.chatId,+ harness: options.model.harness,+ model: options.model.model,+ length: options.text.length,+ attachments: options.attachments.length,+ });const optimistic: Item = {id: `optimistic-${Date.now()}`,kind: "user",@@ -383,7 +391,14 @@ export async function startChat(options: StartChatOptions): Promise<void> {// is written directly: the editor reads it when it mounts.settings.define<boolean>("layout.uiVisible", true).value = true;try {- await send({ projectId, cwd: options.project.dir, chatId: null, text: options.text, attachments: options.attachments, model: options.model });+ await send({+ projectId,+ cwd: options.project.dir,+ chatId: null,+ text: options.text,+ attachments: options.attachments,+ model: options.model,+ });} catch (error) {setActiveChat(projectId, null);setState("drafts", draftKey(projectId, null), {diff --git a/apps/web/src/components/dashboard/home-view.tsx b/apps/web/src/components/dashboard/home-view.tsxindex c559bfea..0fa73925 100644--- a/apps/web/src/components/dashboard/home-view.tsx+++ b/apps/web/src/components/dashboard/home-view.tsx@@ -218,11 +218,6 @@ export function DashboardHomeView() {const project = await resolveTarget();if (!project) return;- track("home_prompt_sent", {- agent: `${ref.harness}/${ref.model}`,- target: target().kind,- attachments: paths.length,- });// The chat starts before the page switches: the host has the turn as// soon as it answers, and the editor lands with the reply streaming.// On failure the text survives as the project's draft (see startChat).diff --git a/apps/web/src/components/dashboard/plans-view.tsx b/apps/web/src/components/dashboard/plans-view.tsxindex 5eb5c7f7..8d440890 100644--- a/apps/web/src/components/dashboard/plans-view.tsx+++ b/apps/web/src/components/dashboard/plans-view.tsx@@ -121,7 +121,7 @@ export function DashboardPlansView() {const handleChoose = async (plan: PaidPlan) => {if (checkoutPlan()) return;setCheckoutPlan(plan);- track("subscription_checkout_started", { plan, billing_period: billingPeriod() });+ track("checkout_started", { kind: "subscription", plan, billing_period: billingPeriod() });try {await startSubscriptionCheckout({ plan, billingPeriod: billingPeriod() });} finally {diff --git a/apps/web/src/components/purchase-success.tsx b/apps/web/src/components/purchase-success.tsxindex eb5ed608..94dee83a 100644--- a/apps/web/src/components/purchase-success.tsx+++ b/apps/web/src/components/purchase-success.tsx@@ -12,7 +12,6 @@ import { Button } from "@/components/ui/button";import { hideUpgradeDialog } from "@/components/upgrade-dialog";import { Dialog, DialogContent, DialogPortal } from "@/components/ui/dialog";import { useAuth } from "@/context/auth";-import { track } from "@/lib/analytics";import { PLANS } from "@/lib/checkout";import { mainBridge } from "@/lib/ipc";import { MAIN_CHANNELS } from "@desktop/main-channels";@@ -155,11 +154,6 @@ export function PurchaseSuccess() {hideUpgradeDialog();setOpen(true);auth.refreshAccount();- track("purchase_success_viewed", {- kind: next.kind,- ...(next.kind === "plan" && { plan: next.plan }),- ...(next.kind === "credits" && { credits: next.credits }),- });};createEffect(() => {diff --git a/apps/web/src/components/upgrade-dialog.tsx b/apps/web/src/components/upgrade-dialog.tsxindex 98b9db64..26d94b3e 100644--- a/apps/web/src/components/upgrade-dialog.tsx+++ b/apps/web/src/components/upgrade-dialog.tsx@@ -68,7 +68,8 @@ function ProUpgradeContent() {const handleUpgrade = async () => {if (loading()) return;setLoading(true);- track('subscription_checkout_started', {+ track('checkout_started', {+ kind: 'subscription',plan: plan(),billing_period: billingPeriod(),});@@ -83,7 +84,7 @@ function ProUpgradeContent() {};onMount(() => {- track('subscription_checkout_viewed');+ track('checkout_viewed', { kind: 'subscription' });});return (@@ -157,7 +158,7 @@ function TopupContent() {const tier = selected();if (!tier || loading()) return;setLoading(true);- track('topup_checkout_started', { credit_tier: tier });+ track('checkout_started', { kind: 'topup', credits: tier });try {await startTopupCheckout(tier);} finally {@@ -166,7 +167,7 @@ function TopupContent() {};onMount(() => {- track('topup_checkout_viewed');+ track('checkout_viewed', { kind: 'topup' });});return (diff --git a/apps/web/src/context/auth.tsx b/apps/web/src/context/auth.tsxindex e4ec3e5a..2e791dbe 100644--- a/apps/web/src/context/auth.tsx+++ b/apps/web/src/context/auth.tsx@@ -20,7 +20,7 @@ import type { Account, Plan } from '@diffusionstudio/api-contract';import { supabase } from '@/lib/supabase';import { api } from '@/lib/api';import { FREE_CREDITS } from '@/lib/checkout';-import { identify, resetIdentity, track } from '@/lib/analytics';+import { setAnalyticsSession, track } from '@/lib/analytics';import { mainBridge } from '@/lib/ipc';import { MAIN_CHANNELS } from '@desktop/main-channels';import { assert } from '@/utils';@@ -61,24 +61,25 @@ export function AuthProvider(props: { children: JSX.Element }) {const [isLoading, setIsLoading] = createSignal(true);onMount(() => {if (!supabase) {+ setAnalyticsSession(null);setIsLoading(false);return;}void supabase.auth.getSession().then(({ data }) => {setSession(data.session);+ setAnalyticsSession(data.session?.access_token ?? null);setIsLoading(false);});const { data: { subscription } } = supabase.auth.onAuthStateChange((event, newSession) => {setSession(newSession);+ // Every change, token refreshes included: desktop main sends events with it.+ setAnalyticsSession(newSession?.access_token ?? null);if (event === 'SIGNED_IN' && newSession?.user) {- const provider = newSession.user.app_metadata?.provider ?? 'unknown';- identify(newSession.user.id, { provider });- track('sign_in', { provider });+ track('signed_in', { provider: newSession.user.app_metadata?.provider ?? 'unknown' });} else if (event === 'SIGNED_OUT') {- track('sign_out');- resetIdentity();+ track('signed_out', {});}});@@ -253,7 +254,6 @@ export function AuthProvider(props: { children: JSX.Element }) {try {await api.account.delete.mutate();- track('account_deleted');// Sign out locally after successful server-side deletionawait supabase.auth.signOut();diff --git a/apps/web/src/context/render.ts b/apps/web/src/context/render.tsindex f6c89711..f31e69cb 100644--- a/apps/web/src/context/render.ts+++ b/apps/web/src/context/render.ts@@ -102,7 +102,10 @@ export async function renderScene(track("export_failed", {...event,duration_ms: elapsed(),- error: (error as Error)?.message?.slice(0, 200) ?? "unknown",+ // Ensure its not too long for the database.+ error: String((error as Error)?.message ?? "unknown")+ .replace(/(?:[A-Za-z]:)?[\\/][^\s'"`]+/g, "<path>")+ .slice(0, 200),});track("export_started", {...event,@@ -128,13 +131,13 @@ export async function renderScene(setOverlay((prev) =>prev? {- ...prev,- progress: percent,- remaining: {- minutes: p.remaining.getUTCMinutes(),- seconds: p.remaining.getUTCSeconds(),- },- }+ ...prev,+ progress: percent,+ remaining: {+ minutes: p.remaining.getUTCMinutes(),+ seconds: p.remaining.getUTCSeconds(),+ },+ }: prev,);},@@ -144,7 +147,9 @@ export async function renderScene(const result = await encoder.render();if (result.type === "success") {- track("export_completed", { ...event, duration_ms: elapsed() });+ track("export_succeeded", { ...event, duration_ms: elapsed() });+ } else if (result.type === "canceled") {+ track("export_canceled", { ...event, duration_ms: elapsed() });} else if (result.type === "error") {failed(result.error);}diff --git a/apps/web/src/lib/analytics.ts b/apps/web/src/lib/analytics.tsindex e80ca0b0..f70acec0 100644--- a/apps/web/src/lib/analytics.ts+++ b/apps/web/src/lib/analytics.ts@@ -2,89 +2,59 @@* License, v. 2.0. If a copy of the MPL was not distributed with this* file, You can obtain one at http://mozilla.org/MPL/2.0/. */-/**- * Umami analytics wrapper. Loads the Umami script lazily and exposes- * type-safe `track` / `identify` helpers that no-op when Umami is- * disabled (env vars unset) or has not finished loading yet.- *- * Inside the desktop app the Umami script is inert (its `data-domains` gate- * does not match the `file://` origin), so `track` hands events to main,- * which posts them to Umami itself.- *- * Pageviews and SPA route changes are auto-tracked by the Umami script- * via the History API — call `track` only for custom product events.- */import { MAIN_CHANNELS } from "@desktop/main-channels";+import { api } from "@/lib/api";import { mainBridge } from "@/lib/ipc";-type UmamiEventData = Record<string, string | number | boolean | undefined>;+import type { ClientEventName, TrackedEvent, TrackProps } from "@diffusionstudio/api-contract";-type UmamiClient = {- track: (event?: string | UmamiEventData, data?: UmamiEventData) => void;- identify: (data: UmamiEventData) => void;-};+const FLUSH_INTERVAL_MS = 5_000;-declare global {- interface Window {- umami?: UmamiClient;- }-}--const websiteId = import.meta.env.VITE_UMAMI_WEBSITE_ID ?? '';-const scriptUrl = import.meta.env.VITE_UMAMI_SCRIPT_URL ?? '';-const domains = import.meta.env.VITE_UMAMI_DOMAINS ?? '';--let initialized = false;+/** Events waiting for the next flush. */+let queue: TrackedEvent[] = [];+/** Starts sending. Dev builds are not tracked. */export function initAnalytics(): void {- if (initialized) return;- initialized = true;-- const script = document.createElement("script");- script.async = true;- script.defer = true;- script.src = scriptUrl;- script.setAttribute("data-website-id", websiteId);- script.setAttribute("data-domains", domains);- script.setAttribute("data-tag", "web-app-v1");- script.setAttribute("data-performance", "true");- document.head.appendChild(script);-}--/** Drop undefined entries — Umami rejects payloads with `undefined` values. */-function clean(data?: UmamiEventData): UmamiEventData | undefined {- if (!data) return undefined;- const out: UmamiEventData = {};- for (const k in data) {- const v = data[k];- if (v !== undefined) {- out[k] = v- };+ if (import.meta.env.DEV) return;+ // The desktop app's launch is recorded by main: once per launch, not per window.+ if (!window.desktop) {+ track("app_opened");}- return out;-}-export function track(event: string, data?: UmamiEventData): void {- const payload = clean(data);- if (window.desktop) {- mainBridge- .call(MAIN_CHANNELS.ANALYTICS_TRACK, { event, data: payload as Record<string, string | number | boolean> | undefined })- .catch(() => {});- return;- }- if (payload) {- window.umami?.track(event, payload);- } else {- window.umami?.track(event);- }+ setInterval(() => {+ if (!queue.length) return;+ const events = queue.splice(0, 100);+ // Best effort: a failed batch is dropped rather than replayed under a different session.+ api.events.track+ .mutate({+ source: window.desktop ? "desktop" : "web",+ appVersion: APP_VERSION,+ platform: window.desktop?.platform ?? "web",+ events,+ })+ .catch(() => { });+ }, FLUSH_INTERVAL_MS);}-export function identify(userId: string, traits?: UmamiEventData): void {- const payload = clean(traits);- window.umami?.identify({ id: userId, ...(payload ?? {}) });+/**+ * Desktop: tells main where events go and as whom. Call on launch and on+ * every auth change, token refreshes included; `null` when signed out.+ */+export function setAnalyticsSession(token: string | null): void {+ if (!window.desktop) return;+ mainBridge+ .call(MAIN_CHANNELS.ANALYTICS_CONFIGURE, { apiUrl: import.meta.env.VITE_API_URL ?? '', token })+ .catch(() => { });}-export function resetIdentity(): void {- window.umami?.identify({});+export function track(name: ClientEventName, props: TrackProps = {}): void {+ if (import.meta.env.DEV) return;+ // Undefined values would fail validation; JSON leaves them out.+ queue.push({+ id: crypto.randomUUID(),+ at: new Date().toISOString(),+ name,+ props: JSON.parse(JSON.stringify(props))+ });}