The VS Code of video editing, built for agents.
TypeScript
Enhance desktop analytics tracking and event handling
konstantin-pauluscb1116b23d6b
diff --git a/apps/desktop/src/analytics.ts b/apps/desktop/src/analytics.tsindex 3e326178..dc60ac90 100644--- a/apps/desktop/src/analytics.ts+++ b/apps/desktop/src/analytics.ts@@ -7,11 +7,14 @@ import { join } from "node:path";import { access, writeFile } from "node:fs/promises";/**- * Install tracking, proxied by the first launch of a packaged build. The- * renderer's Umami script never fires inside Electron (its `data-domains`- * gate does not match the `file://` origin), so main posts one event- * directly to Umami's send API and drops a marker file in `userData` to- * never send it again. Offline first launches retry on the next launch.+ * 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.*/const UMAMI_ENDPOINT = "https://cloud.umami.is/api/send";@@ -32,40 +35,52 @@ function userAgent(): string {return `Mozilla/5.0 (${platform}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36`;}-export async function trackInstall(): Promise<void> {- if (!app.isPackaged) return;-- const marker = join(app.getPath("userData"), MARKER_FILE);- try {- await access(marker);- return;- } catch {- // No marker yet — this is the first (tracked) launch.- }+export type AnalyticsEventData = Record<string, string | number | boolean>;+/** 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: "/desktop/install",- name: "desktop_install",- data: {- platform: process.platform,- arch: process.arch,- version: app.getVersion(),- },- },+ payload: { website: UMAMI_WEBSITE_ID, hostname: HOSTNAME, url, name, data },}),});- if (response.ok) {- await writeFile(marker, new Date().toISOString());- }+ return response.ok;+ } catch {+ // Offline or Umami unreachable.+ return false;+ }+}++/** 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(),+ });+}++export async function trackInstall(): Promise<void> {+ if (!app.isPackaged) return;++ const marker = join(app.getPath("userData"), MARKER_FILE);+ try {+ await access(marker);+ return;} catch {- // Offline or Umami unreachable — retried on the next launch.+ // No marker yet — this is the first (tracked) launch.}++ 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(() => {});}diff --git a/apps/desktop/src/main-channels.ts b/apps/desktop/src/main-channels.tsindex 3c5a33e0..49be16cc 100644--- a/apps/desktop/src/main-channels.ts+++ b/apps/desktop/src/main-channels.ts@@ -30,6 +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",AUTH_GET_PENDING_CALLBACK: "auth:get-pending-callback",CHECKOUT_GET_PENDING_CALLBACK: "checkout:get-pending-callback",WINDOW_IS_FULLSCREEN: "window:is-fullscreen",@@ -173,6 +174,12 @@ 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> };+ response: void;+ };[MAIN_CHANNELS.AUTH_GET_PENDING_CALLBACK]: {request: void;response: string | null;diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.tsindex 5c380d62..db71aec3 100644--- a/apps/desktop/src/main.ts+++ b/apps/desktop/src/main.ts@@ -15,7 +15,7 @@ import { agentChatEndpoint, deleteProjectChats, startAgentChat, stopAgentChat }import { cliStatus, installCli, uninstallCli } from "./cli-install";import { applyMcp, healMcpRegistrations, mcpStatus } from "./mcp-install";import { enableHeadless } from "./headless";-import { trackInstall } from "./analytics";+import { trackEvent, trackInstall } from "./analytics";import { setupAppMenu } from "./menu";import { mainBridge } from "./main-manager";import { MAIN_CHANNELS } from "./main-channels";@@ -284,6 +284,7 @@ if (app.requestSingleInstanceLock()) {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.AUTH_GET_PENDING_CALLBACK, () =>takePendingDeepLink(MAIN_CHANNELS.AUTH_CALLBACK),);diff --git a/apps/web/src/context/export.tsx b/apps/web/src/context/export.tsxindex 43054dd6..cd9f98b5 100644--- a/apps/web/src/context/export.tsx+++ b/apps/web/src/context/export.tsx@@ -7,11 +7,10 @@ import { toast } from "somoto";import { canEncodeVideo } from "mediabunny";import { useWorld } from "@diffusionstudio/koota-solid";import { computeOutputSize } from "@diffusionstudio/encoder";-import { Computed, FrameRate, getActiveEntity } from "@diffusionstudio/runtime";+import { Computed, getActiveEntity } from "@diffusionstudio/runtime";import { assert, downloadObject, isInputTarget } from "@/utils";import { useEngineContext } from "@/engine";import { useProject } from "@/context/project";-import { track } from "@/lib/analytics";import { ExportProgress, type ExportConfig } from "@/components/sidebar-right/inspector/export-progress";import { renderScene, renderOverlay, cancelRender } from "@/context/render";import {@@ -37,9 +36,6 @@ export function ExportProvider(props: { children: JSX.Element }) {const exporting = () => !!renderOverlay();- const sceneDurationSeconds = (scene: Entity) =>- (scene.get(Computed)?.duration ?? 0) / (world.get(FrameRate)?.value || 30);-const exportScene: ExportContextValue["exportScene"] = async (scene, config) => {if (!scene?.isAlive()) return;@@ -96,51 +92,24 @@ export function ExportProvider(props: { children: JSX.Element }) {return;}- track('export_started', {- format,- resolution: config.video?.resolution,- fps: config.video?.fps,- video_codec: config.video?.codec,- audio_codec: config.audio?.codec,- scene_duration_s: Math.round(sceneDurationSeconds(scene)),- });- const startedAt = performance.now();-try {- const result = await renderScene(engine, { scene, target, config, dir: project.dir() });+ const result = await renderScene(engine, { scene, target, config, dir: project.dir(), source: "ui" });if (result.type === "error") {console.error("Export failed:", result.error);toast.error("Export failed", {description: result.error.message,});- track('export_failed', {- format,- duration_ms: Math.round(performance.now() - startedAt),- error: result.error.message?.slice(0, 200) ?? 'unknown',- });} else if (result.type === "success") {toast("Export complete", {description: "Your video has been successfully exported",});- track('export_completed', {- format,- resolution: config.video?.resolution,- fps: config.video?.fps,- scene_duration_s: Math.round(sceneDurationSeconds(scene)),- duration_ms: Math.round(performance.now() - startedAt),- });}} catch (e) {console.error("Export failed:", e);toast.error("Export failed", {description: (e as Error).message,});- track('export_failed', {- format,- duration_ms: Math.round(performance.now() - startedAt),- error: (e as Error).message?.slice(0, 200) ?? 'unknown',- });}};diff --git a/apps/web/src/context/render.ts b/apps/web/src/context/render.tsindex b7003a9d..1d205217 100644--- a/apps/web/src/context/render.ts+++ b/apps/web/src/context/render.ts@@ -7,6 +7,7 @@ import { createEncoder, computeOutputSize } from "@diffusionstudio/encoder";import { Computed, FrameRate, Workarea } from "@diffusionstudio/runtime";import { createCapture } from "@/engine/capture";+import { track } from "@/lib/analytics";import { version } from "../../package.json";import type { Entity } from "koota";@@ -16,10 +17,11 @@ import type { Engine } from "@/engine";import type { ExportConfig } from "@/components/sidebar-right/inspector/export-progress";/**- * Unified scene render path, used by the UI export (`ExportProvider.exportScene`):- * the "Exporting Composition" overlay, the engine stop/start lifecycle, the- * capture world the encode runs against, progress reporting, and cancel wiring- * all live in {@link renderScene}.+ * Unified scene render path, used by the UI export (`ExportProvider.exportScene`)+ * and the agent's export tool (`dapi/handlers/export`): the "Exporting+ * Composition" overlay, the engine stop/start lifecycle, the capture world the+ * encode runs against, progress reporting, cancel wiring, and the export+ * analytics events all live in {@link renderScene}.*/export type RenderOverlayState = {@@ -54,11 +56,13 @@ export type RenderSceneOptions = {config?: Partial<EncoderConfig>;/** The project's folder, so the encode compiles the sources as they are now. */dir?: string;+ /** Who asked for the render: the in-app export, or an agent through the export tool. */+ source: "ui" | "agent";};export async function renderScene(engine: Engine,- { scene, target, config, dir }: RenderSceneOptions,+ { scene, target, config, dir, source }: RenderSceneOptions,): Promise<ExportResult> {const world = engine.world;@@ -89,6 +93,27 @@ export async function renderScene(engine.stop();+ const event = {+ source,+ format: config?.format,+ resolution: config?.video?.resolution,+ fps: config?.video?.fps,+ scene_duration_s: Math.round(duration),+ };+ const startedAt = performance.now();+ const elapsed = () => Math.round(performance.now() - startedAt);+ const failed = (error: unknown) =>+ track("export_failed", {+ ...event,+ duration_ms: elapsed(),+ error: (error as Error)?.message?.slice(0, 200) ?? "unknown",+ });+ track("export_started", {+ ...event,+ video_codec: config?.video?.codec,+ audio_codec: config?.audio?.codec,+ });+let capture: Capture | undefined;try {capture = await createCapture(world, scene, {@@ -120,7 +145,19 @@ export async function renderScene(});cancelActive = encoder.cancel;- return await encoder.render();+ const result = await encoder.render();++ if (result.type === "success") {+ track("export_completed", { ...event, duration_ms: elapsed() });+ } else if (result.type === "error") {+ failed(result.error);+ }++ return result;+ } catch (error) {+ // Setup failures (capture, encoder) as well as a throwing encode.+ failed(error);+ throw error;} finally {cancelActive = undefined;setOverlay(null);diff --git a/apps/web/src/dapi/handlers/export.ts b/apps/web/src/dapi/handlers/export.tsindex aa325624..5f9a6f96 100644--- a/apps/web/src/dapi/handlers/export.ts+++ b/apps/web/src/dapi/handlers/export.ts@@ -121,7 +121,7 @@ export const exportScene: ToolHandler<"export"> = async ({ id, path }, ctx) => {throw new DapiError("unsupported",`Cannot encode ${codec.toUpperCase()} at ${width}×${height}. ` +- "Set a lower resolution, a lower bitrate, or another codec in the scene's export entry.",+ "Set a lower resolution, a lower bitrate, or another codec in the scene's export entry.",);}}@@ -140,12 +140,23 @@ export const exportScene: ToolHandler<"export"> = async ({ id, path }, ctx) => {const handle = new ElectronWritableFileHandle(target);try {- const result = await renderScene(engine, { scene, target: handle, config: { ...settings, format }, dir: project.dir() });- if (result.type === "canceled") throw new DapiError("canceled", "Export canceled in the app");- if (result.type === "error") throw result.error;+ const result = await renderScene(engine, {+ scene,+ target: handle,+ config: { ...settings, format },+ dir: project.dir(),+ source: "agent"+ }+ );+ if (result.type === "canceled") {+ throw new DapiError("canceled", "Export canceled in the app");+ }+ if (result.type === "error") {+ throw result.error;+ }} catch (error) {// Close the fd and drop the partial file; a failed export leaves nothing.- await handle.dispose().catch(() => {});+ await handle.dispose().catch(() => { });throw error;}diff --git a/apps/web/src/lib/analytics.ts b/apps/web/src/lib/analytics.tsindex 080fc1f9..e80ca0b0 100644--- a/apps/web/src/lib/analytics.ts+++ b/apps/web/src/lib/analytics.ts@@ -7,10 +7,17 @@* 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 { mainBridge } from "@/lib/ipc";+type UmamiEventData = Record<string, string | number | boolean | undefined>;type UmamiClient = {@@ -60,6 +67,12 @@ function clean(data?: UmamiEventData): UmamiEventData | undefined {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 {