Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(analytics): full PostHog pipeline + 6 funnel events (MUL-1122) (#1367)

devv-eve637bdc8eb332
diff --git a/.env.example b/.env.example
index c0ecc835c4..2bfe58cc41 100644
--- a/.env.example
+++ b/.env.example
@@ -101,3 +101,12 @@ ALLOWED_EMAIL_DOMAINS=
# Optional: Only allow these exact email addresses (comma-separated)
ALLOWED_EMAILS=
+# ==================== Analytics (PostHog) ====================
+# Product analytics events feed the acquisition → activation → expansion funnel.
+# Leave POSTHOG_API_KEY empty for local dev / self-hosted instances; the server
+# will run a no-op analytics client and ship nothing. See docs/analytics.md.
+POSTHOG_API_KEY=
+POSTHOG_HOST=https://us.i.posthog.com
+# Force the no-op client even when POSTHOG_API_KEY is set (CI / opt-out).
+ANALYTICS_DISABLED=
+
diff --git a/apps/web/components/pageview-tracker.tsx b/apps/web/components/pageview-tracker.tsx
new file mode 100644
index 0000000000..3d33495908
--- /dev/null
+++ b/apps/web/components/pageview-tracker.tsx
@@ -0,0 +1,29 @@
+"use client";
+
+import { useEffect } from "react";
+import { usePathname, useSearchParams } from "next/navigation";
+import { capturePageview } from "@multica/core/analytics";
+
+/**
+ * Fires a PostHog $pageview whenever the Next.js App Router path or query
+ * string changes. Mounted once at the root so every route transition is
+ * covered, including transitions into workspace-scoped subtrees.
+ *
+ * PostHog's own `capture_pageview: true` auto-capture is deliberately
+ * disabled in `initAnalytics` so we own the event shape — this component
+ * is what actually fires the event. Before this existed the acquisition
+ * funnel's `/ → signup` step was empty.
+ */
+export function PageviewTracker() {
+ const pathname = usePathname();
+ const searchParams = useSearchParams();
+
+ useEffect(() => {
+ if (!pathname) return;
+ const qs = searchParams?.toString();
+ const url = qs ? `${pathname}?${qs}` : pathname;
+ capturePageview(url);
+ }, [pathname, searchParams]);
+
+ return null;
+}
diff --git a/apps/web/components/web-providers.tsx b/apps/web/components/web-providers.tsx
index f9820b8bc7..eb9347caf5 100644
--- a/apps/web/components/web-providers.tsx
+++ b/apps/web/components/web-providers.tsx
@@ -1,11 +1,13 @@
"use client";
+import { Suspense } from "react";
import { CoreProvider } from "@multica/core/platform";
import { WebNavigationProvider } from "@/platform/navigation";
import {
setLoggedInCookie,
clearLoggedInCookie,
} from "@/features/auth/auth-cookie";
+import { PageviewTracker } from "./pageview-tracker";
// Legacy token in localStorage → keep this session in token mode so users who
// logged in before the cookie-auth migration stay authed. They migrate to
@@ -42,6 +44,11 @@ export function WebProviders({ children }: { children: React.ReactNode }) {
onLogin={setLoggedInCookie}
onLogout={clearLoggedInCookie}
>
+ {/* Suspense boundary is required by Next.js for useSearchParams in
+ a client component mounted this high in the tree. */}
+ <Suspense fallback={null}>
+ <PageviewTracker />
+ </Suspense>
<WebNavigationProvider>{children}</WebNavigationProvider>
</CoreProvider>
);
diff --git a/docs/analytics.md b/docs/analytics.md
new file mode 100644
index 0000000000..765cf01fa0
--- /dev/null
+++ b/docs/analytics.md
@@ -0,0 +1,207 @@
+# Product Analytics
+
+This document is the source of truth for the analytics events Multica ships
+to PostHog. Events feed the acquisition → activation → expansion funnel that
+drives our weekly Active Workspaces (WAW) north-star metric.
+
+See [MUL-1122](https://github.com/multica-ai/multica) for the design context.
+
+## Configuration
+
+All analytics shipping is toggled by environment variables (see `.env.example`):
+
+| Variable | Meaning | Default |
+|---|---|---|
+| `POSTHOG_API_KEY` | PostHog project API key. Empty = no events are shipped. | `""` |
+| `POSTHOG_HOST` | PostHog host (US or EU cloud, or self-hosted URL). | `https://us.i.posthog.com` |
+| `ANALYTICS_DISABLED` | Set to `true`/`1` to force the no-op client even when `POSTHOG_API_KEY` is set. | `""` |
+
+Local dev and self-hosted instances run with `POSTHOG_API_KEY=""`, so **no
+events leave the process unless the operator explicitly opts in**.
+
+### Self-hosted instances
+
+Self-hosters should **never inherit a Multica-issued `POSTHOG_API_KEY`** —
+that would route their users' behavior to our analytics project. The
+defaults guarantee this:
+
+- `.env.example` ships `POSTHOG_API_KEY=` empty. The Docker self-host
+ compose does not set a default either.
+- With the key unset, `NewFromEnv` returns `NoopClient` and logs
+ `analytics: POSTHOG_API_KEY not set, using noop client` at startup — a
+ visible confirmation that nothing is shipped.
+- Operators who want their own analytics can set `POSTHOG_API_KEY` and
+ `POSTHOG_HOST` to point at their own PostHog project (Cloud or
+ self-hosted PostHog).
+- The frontend receives the key via `/api/config` (planned for PR 2), so
+ self-hosts' blank server config also disables frontend event shipping
+ automatically — no separate frontend opt-out plumbing required.
+
+## Architecture
+
+```
+handler → analytics.Client.Capture(Event) ← non-blocking, returns immediately
+ │
+ ▼
+ bounded queue (1024 events)
+ │
+ ▼
+ background worker: batch + POST /batch/
+ │
+ ▼
+ PostHog
+```
+
+- `analytics.Capture` is **never allowed to block a request handler**. A
+ broken backend must not degrade the product — when the queue is full,
+ events are dropped and counted (visible via `slog` + the `dropped` counter
+ on shutdown).
+- Batches flush either when `BatchSize` is reached or every `FlushEvery`
+ (default 10 s), whichever comes first.
+- `Close()` drains remaining events during graceful shutdown. Called from
+ `server/cmd/server/main.go` via `defer`.
+
+## Identity model
+
+- **`distinct_id`** — always the user's UUID for logged-in events. The
+ frontend's `posthog.identify(user.id)` merges any prior anonymous events
+ under the same identity, so acquisition attribution (UTM / referrer) stays
+ intact across signup.
+- **`workspace_id`** — added to every event as a property when present. v1
+ uses event property filtering (free tier) rather than PostHog Groups
+ Analytics (paid) to compute workspace-level metrics.
+- **PII** — events carry `email_domain` (e.g. `gmail.com`), not the full
+ email. Full email is stored once in person properties via `$set_once` so
+ it's available for individual debugging but not broadcast with every
+ event.
+
+## Event contract
+
+### `signup`
+
+Fires when a new user is created. Covers both verification-code and Google
+OAuth entry points (`findOrCreateUser` is the single emission site).
+
+| Property | Type | Description |
+|---|---|---|
+| `email_domain` | string | Lower-cased domain portion of the user's email. |
+| `signup_source` | string | Opaque attribution bundle from the frontend cookie `multica_signup_source` (UTM + referrer). Empty when the cookie is absent. |
+| `auth_method` | string | Optional. `"google"` for Google OAuth signups. Absent for verification-code signups. |
+
+Person properties set with `$set_once`:
+
+| Property | Type | Description |
+|---|---|---|
+| `email` | string | Full email. Never broadcast per-event. |
+| `signup_source` | string | Same as above; kept on the person for later segmentation. |
+
+### `workspace_created`
+
+Fires after a `CreateWorkspace` transaction commits successfully.
+
+| Property | Type | Description |
+|---|---|---|
+| `workspace_id` | string (UUID) | Added globally; present here for clarity. |
+
+**Note on "first workspace" segmentation** — we deliberately do *not* stamp
+an `is_first_workspace` boolean at emit time. Computing it correctly would
+require an extra column or transaction-scoped logic that still races under
+concurrent creates. Instead, PostHog answers the same question exactly by
+looking at whether the user has a prior `workspace_created` event (use a
+funnel with "first time user does X" or a cohort on
+`person_properties.$initial_event`). No information is lost.
+
+### `runtime_registered`
+
+Fires the first time a `(workspace_id, daemon_id, provider)` tuple is
+upserted. Heartbeats and repeat registrations never re-emit. First-time
+detection uses Postgres `xmax = 0` on the upsert RETURNING clause — no
+extra query, no race.
+
+| Property | Type | Description |
+|---|---|---|
+| `runtime_id` | string (UUID) | The newly created agent_runtime row id. |
+| `provider` | string | e.g. `"codex"`, `"claude"`. |
+| `runtime_version` | string | Version of the agent runtime binary. |
+| `cli_version` | string | Version of the `multica` CLI that registered it. |
+
+`distinct_id` is the authenticated owner's user id when the daemon was
+registered via a member's JWT/PAT; daemon-token registrations fall back to
+`workspace:<workspace_id>` so PostHog doesn't bucket unrelated daemons
+under a single "anonymous" person.
+
+### `issue_executed`
+
+Fires **at most once per issue** — when the first task on that issue
+reaches terminal `done` state. Backed by an atomic
+`UPDATE issue SET first_executed_at = now() WHERE id = $1 AND first_executed_at IS NULL RETURNING *`;
+retries, re-assignments, and comment-triggered follow-up tasks all hit the
+WHERE clause and no-op, so the `≥1 / ≥2 / ≥5 / ≥10` funnel buckets count
+distinct issues, not tasks.
+
+| Property | Type | Description |
+|---|---|---|
+| `issue_id` | string (UUID) | |
+| `task_duration_ms` | int64 | Wall-clock time between `task.started_at` and `task.completed_at`. Zero when the task was created in a completed state (rare). |
+
+`distinct_id` prefers the issue's human creator so agent-executed events
+flow into the issue-author's person profile (same place `signup` and
+`workspace_created` land). Agent-created issues prefix with `agent:` to
+keep PostHog from merging the agent into a user record.
+
+**Note on workspace-Nth ordinals** — we deliberately do *not* stamp
+`nth_issue_for_workspace` at emit time. Computing it correctly would
+require either a serialised transaction or an advisory lock per workspace;
+two concurrent first-completions could otherwise both read `count=1` and
+emit `n=1`. PostHog answers the same question at query time via
+`row_number() OVER (PARTITION BY properties.workspace_id ORDER BY timestamp)`,
+and funnel steps of the form "workspace has had ≥2 `issue_executed`
+events" are expressible without the property. No information is lost.
+
+### `team_invite_sent`
+
+Fires from `CreateInvitation` after the DB row is written.
+
+| Property | Type | Description |
+|---|---|---|
+| `invited_email_domain` | string | Lower-cased domain; full email lives in the invitation row, not the event. |
+| `invite_method` | string | Currently always `"email"`. Future non-email invite flows (share link, SCIM) should pass their own value. |
+
+`distinct_id` is the inviter's user id.
+
+### `team_invite_accepted`
+
+Fires from `AcceptInvitation` after both the invitation row is marked
+accepted and the member row is inserted in the same transaction.
+
+| Property | Type | Description |
+|---|---|---|
+| `days_since_invite` | int64 | Whole days from invitation creation to acceptance. Lets us segment "accepted same day" (warm) from "dug out of email weeks later" (cold). |
+
+`distinct_id` is the invitee's user id — this is the event that closes the
+expansion funnel.
+
+### Frontend-only events
+
+- `$pageview` — fired by `apps/web/components/pageview-tracker.tsx` on
+ every Next.js App Router path or query-string change. The tracker
+ mounts once under `WebProviders` and drives the acquisition funnel's
+ `/ → signup` step. posthog-js's automatic pageview capture is
+ disabled in `initAnalytics` so we own the event shape.
+- Attribution is NOT a separate event; UTM + referrer origin are written
+ to the `multica_signup_source` cookie on the first anonymous pageview
+ and read by the backend's `signup` emission. The cookie carries a JSON
+ payload URL-encoded at write time (`encodeURIComponent`) and
+ URL-decoded at read time (`url.QueryUnescape`) — the JSON is never
+ mid-truncated; individual values are capped at 96 chars before
+ `JSON.stringify`, and the entire payload is dropped if it still exceeds
+ 512 chars. That way PostHog sees either intact JSON or nothing at all.
+
+## Governance
+
+Before adding, renaming, or removing any event:
+
+1. Update this document first.
+2. Update `server/internal/analytics/events.go` constants and helpers to
+ match.
+3. PR description must state which existing funnel / insight is affected.
diff --git a/packages/core/analytics/index.ts b/packages/core/analytics/index.ts
new file mode 100644
index 0000000000..0a2173d56c
--- /dev/null
+++ b/packages/core/analytics/index.ts
@@ -0,0 +1,198 @@
+// Frontend analytics glue. Thin wrapper over posthog-js.
+//
+// The source-of-truth event catalog is `docs/analytics.md`. This module only
+// handles the two things the backend can't do itself: attribution capture on
+// first anonymous pageview, and person-identity merge on login. Every funnel
+// event (signup, workspace_created, runtime_registered, issue_executed,
+// invite_sent, invite_accepted) is emitted server-side — see
+// `server/internal/analytics`.
+//
+// Configuration comes from the backend's `/api/config` response (populated
+// from POSTHOG_API_KEY on the server), NOT from NEXT_PUBLIC_* envs. That
+// keeps self-hosted Docker images from leaking our project key — their
+// backend returns an empty key and this module stays inert.
+
+import posthog from "posthog-js";
+
+const SIGNUP_SOURCE_COOKIE = "multica_signup_source";
+// Per-value cap keeps a long utm_content from blowing the budget. We drop
+// the entire cookie if the JSON still exceeds the overall limit — partial
+// JSON is worse than no attribution because PostHog can't parse it.
+const SIGNUP_SOURCE_VALUE_MAX_LEN = 96;
+const SIGNUP_SOURCE_MAX_LEN = 512;
+const UTM_KEYS = [
+ "utm_source",
+ "utm_medium",
+ "utm_campaign",
+ "utm_content",
+ "utm_term",
+] as const;
+
+let initialized = false;
+// auth-initializer fetches /api/config and /api/me in parallel — on a
+// slow-config path, identify() can fire before initAnalytics(). Buffer the
+// most recent pending identify (only one matters, since it's per-session)
+// and flush it inside initAnalytics.
+let pendingIdentify: { userId: string; props?: Record<string, unknown> } | null = null;
+// Likewise pageviews: the initial "/" pageview is the anchor of the
+// acquisition funnel, and the Next.js router fires it on mount before the
+// config fetch resolves. We keep the first pending pageview so that step
+// doesn't silently drop.
+let pendingPageview: string | undefined | null = null;
+
+export interface AnalyticsConfig {
+ key: string;
+ host: string;
+}
+
+/**
+ * Initialize posthog-js if a key is present. Safe to call multiple times;
+ * subsequent calls with the same config are no-ops.
+ *
+ * Returns `true` when analytics is actually running; `false` when disabled
+ * (no key, SSR, or already initialized with a conflicting key — which we
+ * treat as "use the existing instance").
+ */
+export function initAnalytics(config: AnalyticsConfig | null | undefined): boolean {
+ if (typeof window === "undefined") return false;
+ if (!config?.key) return false;
+ if (initialized) return true;
+
+ posthog.init(config.key, {
+ api_host: config.host || "https://us.i.posthog.com",
+ // person_profiles=identified_only keeps anonymous drive-by traffic off
+ // the billed events until they actually identify, which aligns with how
+ // our funnel is set up: signup is the first real funnel step.
+ person_profiles: "identified_only",
+ // We set attribution ourselves (see captureSignupSource); posthog's own
+ // autocapture-based attribution would double-count.
+ capture_pageview: false,
+ });
+ initialized = true;
+
+ // Flush any identify() that arrived before init resolved.
+ if (pendingIdentify) {
+ posthog.identify(pendingIdentify.userId, pendingIdentify.props);
+ pendingIdentify = null;
+ }
+ // And any first pageview we captured while config was loading.
+ if (pendingPageview !== null) {
+ posthog.capture("$pageview", pendingPageview ? { $current_url: pendingPageview } : undefined);
+ pendingPageview = null;
+ }
+ return true;
+}
+
+/**
+ * Merge the current anonymous session into the logged-in person. Must be
+ * called exactly once per auth transition (login / session-resume). Pulling
+ * attribution properties into person_properties on identify is how we keep
+ * UTM / referrer on the user profile without re-emitting them per event.
+ *
+ * Calls before initAnalytics() are buffered — auth-initializer fetches
+ * config and user in parallel, so identify can arrive first.
+ */
+export function identify(userId: string, userProperties?: Record<string, unknown>): void {
+ if (!initialized) {
+ pendingIdentify = { userId, props: userProperties };
+ return;
+ }
+ posthog.identify(userId, userProperties);
+}
+
+/**
+ * Clear the client-side identity on logout so the next login merges cleanly
+ * and doesn't bleed the previous user's events into a new session.
+ */
+export function resetAnalytics(): void {
+ pendingIdentify = null;
+ pendingPageview = null;
+ if (!initialized) return;
+ posthog.reset();
+}
+
+/**
+ * Capture a page view. Call once per client-side navigation. We disable
+ * posthog's automatic pageview tracking in init() so this module owns the
+ * event shape — that makes it trivial to add properties (e.g. workspace
+ * slug) without fighting the SDK.
+ *
+ * Calls before initAnalytics() buffer the most-recent path so the first
+ * pageview isn't dropped on slow /api/config fetches. Subsequent pre-init
+ * pageviews overwrite the buffer; after init flushes, every navigation
+ * captures synchronously as expected.
+ */
+export function capturePageview(path?: string): void {
+ if (!initialized) {
+ pendingPageview = path ?? "";
+ return;
+ }
+ posthog.capture("$pageview", path ? { $current_url: path } : undefined);
+}
+
+/**
+ * On the very first anonymous pageview in a browser session, read UTM +
+ * referrer and stash them in a cookie that the backend reads during signup.
+ *
+ * Never use raw `document.referrer` as attribution — it can leak OAuth
+ * callback URLs with `code` / `state` in the query string. We keep only the
+ * referrer's origin (scheme + host), which is what a funnel actually needs.
+ *
+ * This cookie is what `signup_source` in the backend's signup event reads
+ * from; both fields are intentionally opaque JSON so the schema can evolve
+ * without a backend deploy.
+ */
+export function captureSignupSource(): void {
+ if (typeof window === "undefined" || typeof document === "undefined") return;
+ if (readCookie(SIGNUP_SOURCE_COOKIE)) return;
+
+ const source: Record<string, string> = {};
+ const cap = (v: string) =>
+ v.length > SIGNUP_SOURCE_VALUE_MAX_LEN ? v.slice(0, SIGNUP_SOURCE_VALUE_MAX_LEN) : v;
+
+ try {
+ const params = new URLSearchParams(window.location.search);
+ for (const key of UTM_KEYS) {
+ const v = params.get(key);
+ if (v) source[key] = cap(v);
+ }
+ } catch {
+ // URL APIs unavailable — skip silently.
+ }
+
+ const refOrigin = safeReferrerOrigin(document.referrer);
+ if (refOrigin) source.referrer_origin = cap(refOrigin);
+
+ if (Object.keys(source).length === 0) return;
+
+ const payload = JSON.stringify(source);
+ // Drop rather than mid-JSON truncate — a half-string would fail to parse
+ // on the backend and the attribution would be worse than missing.
+ if (payload.length > SIGNUP_SOURCE_MAX_LEN) return;
+
+ // 30-day expiry covers the typical signup consideration window. Lax is
+ // the right default — the cookie is only consumed by same-origin auth.
+ const maxAge = 60 * 60 * 24 * 30;
+ document.cookie = `${SIGNUP_SOURCE_COOKIE}=${encodeURIComponent(payload)}; path=/; max-age=${maxAge}; samesite=lax`;
+}
+
+function safeReferrerOrigin(referrer: string): string {
+ if (!referrer) return "";
+ try {
+ const url = new URL(referrer);
+ if (url.origin === window.location.origin) return "";
+ return url.origin;
+ } catch {
+ return "";
+ }
+}
+
+function readCookie(name: string): string {
+ if (typeof document === "undefined") return "";
+ const prefix = `${name}=`;
+ const parts = document.cookie ? document.cookie.split("; ") : [];
+ for (const part of parts) {
+ if (part.startsWith(prefix)) return decodeURIComponent(part.slice(prefix.length));
+ }
+ return "";
+}
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index b39307d3d1..592dc6a22d 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -542,7 +542,11 @@ export class ApiClient {
}
// App Config
- async getConfig(): Promise<{ cdn_domain: string }> {
+ async getConfig(): Promise<{
+ cdn_domain: string;
+ posthog_key?: string;
+ posthog_host?: string;
+ }> {
return this.fetch("/api/config");
}
diff --git a/packages/core/auth/store.ts b/packages/core/auth/store.ts
index b0e744d1b3..0f0251e4f1 100644
--- a/packages/core/auth/store.ts
+++ b/packages/core/auth/store.ts
@@ -1,5 +1,6 @@
import { create } from "zustand";
import type { User, StorageAdapter } from "../types";
+import { identify as identifyAnalytics, resetAnalytics } from "../analytics";
import { ApiError, type ApiClient } from "../api/client";
import { setCurrentWorkspace } from "../platform/workspace-storage";
@@ -84,6 +85,7 @@ export function createAuthStore(options: AuthStoreOptions) {
api.setToken(token);
}
onLogin?.();
+ identifyAnalytics(user.id, { email: user.email, name: user.name });
set({ user });
return user;
},
@@ -95,6 +97,7 @@ export function createAuthStore(options: AuthStoreOptions) {
api.setToken(token);
}
onLogin?.();
+ identifyAnalytics(user.id, { email: user.email, name: user.name });
set({ user });
return user;
},
@@ -104,6 +107,7 @@ export function createAuthStore(options: AuthStoreOptions) {
api.setToken(token);
const user = await api.getMe();
onLogin?.();
+ identifyAnalytics(user.id, { email: user.email, name: user.name });
set({ user, isLoading: false });
return user;
},
@@ -116,6 +120,7 @@ export function createAuthStore(options: AuthStoreOptions) {
storage.removeItem("multica_token");
api.setToken(null);
setCurrentWorkspace(null, null);
+ resetAnalytics();
onLogout?.();
set({ user: null });
},
diff --git a/packages/core/package.json b/packages/core/package.json
index 0628d3c4af..c27e562761 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -63,11 +63,13 @@
"./logger": "./logger.ts",
"./utils": "./utils.ts",
"./constants/*": "./constants/*.ts",
- "./platform": "./platform/index.ts"
+ "./platform": "./platform/index.ts",
+ "./analytics": "./analytics/index.ts"
},
"dependencies": {
"@tanstack/react-query": "catalog:",
"@tanstack/react-query-devtools": "^5.96.2",
+ "posthog-js": "catalog:",
"zustand": "catalog:"
},
"peerDependencies": {
diff --git a/packages/core/platform/auth-initializer.tsx b/packages/core/platform/auth-initializer.tsx
index 802288131f..abcd2b0b2b 100644
--- a/packages/core/platform/auth-initializer.tsx
+++ b/packages/core/platform/auth-initializer.tsx
@@ -4,12 +4,19 @@ import { useEffect, type ReactNode } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { getApi } from "../api";
import { useAuthStore } from "../auth";
+import {
+ captureSignupSource,
+ identify as identifyAnalytics,
+ initAnalytics,
+ resetAnalytics,
+} from "../analytics";
import { configStore } from "../config";
import { workspaceKeys } from "../workspace/queries";
import { createLogger } from "../logger";
import { defaultStorage } from "./storage";
import { setCurrentWorkspace } from "./workspace-storage";
import type { StorageAdapter } from "../types/storage";
+import type { User } from "../types";
const logger = createLogger("auth");
@@ -31,10 +38,34 @@ export function AuthInitializer({
useEffect(() => {
const api = getApi();
- // Fetch app config (CDN domain, etc.) in the background — non-blocking.
- api.getConfig().then((cfg) => {
- if (cfg.cdn_domain) configStore.getState().setCdnDomain(cfg.cdn_domain);
- }).catch(() => { /* config is optional — legacy file card matching degrades gracefully */ });
+ // Stamp attribution before anything else — the signup event (server-side)
+ // reads this cookie, so it has to be present before the user hits submit.
+ captureSignupSource();
+
+ // Fetch app config (CDN domain, PostHog key, …) in the background — non-blocking.
+ api
+ .getConfig()
+ .then((cfg) => {
+ if (cfg.cdn_domain) configStore.getState().setCdnDomain(cfg.cdn_domain);
+ if (cfg.posthog_key) {
+ initAnalytics({ key: cfg.posthog_key, host: cfg.posthog_host || "" });
+ }
+ })
+ .catch(() => {
+ /* config is optional — legacy file card matching degrades gracefully */
+ });
+
+ const onAuthSuccess = (user: User) => {
+ onLogin?.();
+ useAuthStore.setState({ user, isLoading: false });
+ identifyAnalytics(user.id, { email: user.email, name: user.name });
+ };
+
+ const onAuthFailure = () => {
+ onLogout?.();
+ resetAnalytics();
+ useAuthStore.setState({ user: null, isLoading: false });
+ };
if (cookieAuth) {
// Cookie mode: the HttpOnly cookie is sent automatically by the browser.
@@ -46,14 +77,12 @@ export function AuthInitializer({
// selection here.
Promise.all([api.getMe(), api.listWorkspaces()])
.then(([user, wsList]) => {
- onLogin?.();
- useAuthStore.setState({ user, isLoading: false });
+ onAuthSuccess(user);
qc.setQueryData(workspaceKeys.list(), wsList);
})
.catch((err) => {
logger.error("cookie auth init failed", err);
- onLogout?.();
- useAuthStore.setState({ user: null, isLoading: false });
+ onAuthFailure();
});
return;
}
@@ -70,8 +99,7 @@ export function AuthInitializer({
Promise.all([api.getMe(), api.listWorkspaces()])
.then(([user, wsList]) => {
- onLogin?.();
- useAuthStore.setState({ user, isLoading: false });
+ onAuthSuccess(user);
// Seed React Query cache so the URL-driven layout can resolve the
// slug without a second fetch.
qc.setQueryData(workspaceKeys.list(), wsList);
@@ -81,8 +109,7 @@ export function AuthInitializer({
api.setToken(null);
setCurrentWorkspace(null, null);
storage.removeItem("multica_token");
- onLogout?.();
- useAuthStore.setState({ user: null, isLoading: false });
+ onAuthFailure();
});
}, []);
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index b17e07c7f0..6a0f37fbca 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -39,6 +39,9 @@ catalogs:
lucide-react:
specifier: ^1.0.1
version: 1.0.1
+ posthog-js:
+ specifier: ^1.176.1
+ version: 1.369.3
react:
specifier: 19.2.3
version: 19.2.3
@@ -195,25 +198,25 @@ importers:
version: 5.9.3
vitest:
specifier: 'catalog:'
apps/docs:
dependencies:
fumadocs-core:
specifier: ^15.5.2
fumadocs-mdx:
specifier: ^12.0.3
fumadocs-ui:
specifier: ^15.5.2
lucide-react:
specifier: 'catalog:'
version: 1.0.1([email protected])
next:
specifier: ^15.3.3
react:
specifier: 'catalog:'
version: 19.2.3
@@ -355,7 +358,7 @@ importers:
version: 1.0.1([email protected])
next:
specifier: ^16.2.3
next-themes:
specifier: ^0.4.6
@@ -437,7 +440,7 @@ importers:
version: 5.9.3
vitest:
specifier: 'catalog:'
packages/core:
dependencies:
@@ -447,6 +450,9 @@ importers:
'@tanstack/react-query-devtools':
specifier: ^5.96.2
+ posthog-js:
+ specifier: 'catalog:'
+ version: 1.369.3
react:
specifier: 'catalog:'
version: 19.2.3
@@ -465,7 +471,7 @@ importers:
version: 5.9.3
vitest:
specifier: 'catalog:'
packages/eslint-config:
dependencies:
@@ -742,7 +748,7 @@ importers:
version: 5.9.3
vitest:
specifier: 'catalog:'
packages:
@@ -1734,6 +1740,78 @@ packages:
'@open-draft/[email protected]':
resolution: {integrity: sha512-U69T3ItWHvLwGg5eJ0n3I62nWuE6ilHlmz7zM0npLBRvPRd7e6NYmg54vvRtP5mZG7kZqZCFVdsTWo7BPtBujg==}
+ '@opentelemetry/[email protected]':
+ resolution: {integrity: sha512-CjruKY9V6NMssL/T1kAFgzosF1v9o6oeN+aX5JB/C/xPNtmgIJqcXHG7fA82Ou1zCpWGl4lROQUKwUNE1pMCyg==}
+ engines: {node: '>=8.0.0'}
+
+ '@opentelemetry/[email protected]':
+ resolution: {integrity: sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q==}
+ engines: {node: '>=8.0.0'}
+
+ '@opentelemetry/[email protected]':
+ resolution: {integrity: sha512-FuabnnUm8LflnieVxs6eP7Z383hgQU4W1e3KJS6aOG3RxWxcHyBxH8fDMHNgu/gFx/M2jvTOW/4/PHhLz6bjWw==}
+ engines: {node: ^18.19.0 || >=20.6.0}
+ peerDependencies:
+ '@opentelemetry/api': '>=1.0.0 <1.10.0'
+
+ '@opentelemetry/[email protected]':
+ resolution: {integrity: sha512-DT12SXVwV2eoJrGf4nnsvZojxxeQo+LlNAsoYGRRObPWTeN6APiqZ2+nqDCQDvQX40eLi1AePONS0onoASp3yQ==}
+ engines: {node: ^18.19.0 || >=20.6.0}
+ peerDependencies:
+ '@opentelemetry/api': '>=1.0.0 <1.10.0'
+
+ '@opentelemetry/[email protected]':
+ resolution: {integrity: sha512-jOv40Bs9jy9bZVLo/i8FwUiuCvbjWDI+ZW13wimJm4LjnlwJxGgB+N/VWOZUTpM+ah/awXeQqKdNlpLf2EjvYg==}
+ engines: {node: ^18.19.0 || >=20.6.0}
+ peerDependencies:
+ '@opentelemetry/api': ^1.3.0
+
+ '@opentelemetry/[email protected]':
+ resolution: {integrity: sha512-gMd39gIfVb2OgxldxUtOwGJYSH8P1kVFFlJLuut32L6KgUC4gl1dMhn+YC2mGn0bDOiQYSk/uHOdSjuKp58vvA==}
+ engines: {node: ^18.19.0 || >=20.6.0}
+ peerDependencies:
+ '@opentelemetry/api': ^1.3.0
+
+ '@opentelemetry/[email protected]':
+ resolution: {integrity: sha512-DCFPY8C6lAQHUNkzcNT9R+qYExvsk6C5Bto2pbNxgicpcSWbe2WHShLxkOxIdNcBiYPdVHv/e7vH7K6TI+C+fQ==}
+ engines: {node: ^18.19.0 || >=20.6.0}
+ peerDependencies:
+ '@opentelemetry/api': ^1.3.0
+
+ '@opentelemetry/[email protected]':
+ resolution: {integrity: sha512-1pNQf/JazQTMA0BiO5NINUzH0cbLbbl7mntLa4aJNmCCXSj0q03T5ZXXL0zw4G55TjdL9Tz32cznGClf+8zr5A==}
+ engines: {node: ^18.19.0 || >=20.6.0}
+ peerDependencies:
+ '@opentelemetry/api': '>=1.3.0 <1.10.0'
+
+ '@opentelemetry/[email protected]':
+ resolution: {integrity: sha512-K+oi0hNMv94EpZbnW3eyu2X6SGVpD3O5DhG2NIp65Hc7lhAj9brRXTAVzh3wB82+q3ThakEf7Zd7RsFUqcTc7A==}
+ engines: {node: ^18.19.0 || >=20.6.0}
+ peerDependencies:
+ '@opentelemetry/api': '>=1.3.0 <1.10.0'
+
+ '@opentelemetry/[email protected]':
+ resolution: {integrity: sha512-QlAyL1jRpOeaqx7/leG1vJMp84g0xKP6gJmfELBpnI4O/9xPX+Hu5m1POk9Kl+veNkyth5t19hRlN6tNY1sjbA==}
+ engines: {node: ^18.19.0 || >=20.6.0}
+ peerDependencies:
+ '@opentelemetry/api': '>=1.4.0 <1.10.0'
+
+ '@opentelemetry/[email protected]':
+ resolution: {integrity: sha512-G5KYP6+VJMZzpGipQw7Giif48h6SGQ2PFKEYCybeXJsOCB4fp8azqMAAzE5lnnHK3ZVwYQrgmFbsUJO/zOnwGw==}
+ engines: {node: ^18.19.0 || >=20.6.0}
+ peerDependencies:
+ '@opentelemetry/api': '>=1.9.0 <1.10.0'
+
+ '@opentelemetry/[email protected]':
+ resolution: {integrity: sha512-xWQgL0Bmctsalg6PaXExmzdedSp3gyKV8mQBwK/j9VGdCDu2fmXIb2gAehBKbkXCpJ4HPkgv3QfoJWRT4dHWbw==}
+ engines: {node: ^18.19.0 || >=20.6.0}
+ peerDependencies:
+ '@opentelemetry/api': '>=1.3.0 <1.10.0'
+
+ '@opentelemetry/[email protected]':
+ resolution: {integrity: sha512-cifvXDhcqMwwTlTK04GBNeIe7yyo28Mfby85QXFe1Yk8nmi36Ab/5UQwptOx84SsoGNRg+EVSjwzfSZMy6pmlw==}
+ engines: {node: '>=14'}
+
resolution: {integrity: sha512-a61ljmRVVyG5MC/698C8/FfFDw5a8LOIvyOLW5fztgUXqUpc1jOfQzOitSCbge657OgXXThmY3Tk8fpiDb4UcA==}
engines: {node: '>= 20.0.0'}
@@ -1750,6 +1828,42 @@ packages:
engines: {node: '>=18'}
hasBin: true
+ '@posthog/[email protected]':
+ resolution: {integrity: sha512-h2FO7ut/BbfwpAXWpwdDHTzQgUo9ibDFEs6ZO+3cI3KPWQt5XwczK1OLAuPprcjm8T/jl0SH8jSFo5XdU4RbTg==}
+
+ '@posthog/[email protected]':
+ resolution: {integrity: sha512-Ywqvs4513PixR2TIA5O3GMEyK4F65uefwxPfsIUeHr9ruGylyXp00YJ4CEbp8U0DMzCkeF+LsMKVnHgN3pAXcA==}
+
+ '@protobufjs/[email protected]':
+ resolution: {integrity: sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==}
+
+ '@protobufjs/[email protected]':
+ resolution: {integrity: sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==}
+
+ '@protobufjs/[email protected]':
+ resolution: {integrity: sha512-YyFaikqM5sH0ziFZCN3xDC7zeGaB/d0IUb9CATugHWbd1FRFwWwt4ld4OYMPWu5a3Xe01mGAULCdqhMlPl29Jg==}
+
+ '@protobufjs/[email protected]':
+ resolution: {integrity: sha512-j9ednRT81vYJ9OfVuXG6ERSTdEL1xVsNgqpkxMsbIabzSo3goCjDIveeGv5d03om39ML71RdmrGNjG5SReBP/Q==}
+
+ '@protobufjs/[email protected]':
+ resolution: {integrity: sha512-lljVXpqXebpsijW71PZaCYeIcE5on1w5DlQy5WH6GLbFryLUrBD4932W/E2BSpfRJWseIL4v/KPgBFxDOIdKpQ==}
+
+ '@protobufjs/[email protected]':
+ resolution: {integrity: sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==}
+
+ '@protobufjs/[email protected]':
+ resolution: {integrity: sha512-kdSefcPdruJiFMVSbn801t4vFK7KB/5gd2fYvrxhuJYg8ILrmn9SKSX2tZdV6V+ksulWqS7aXjBcRXl3wHoD9Q==}
+
+ '@protobufjs/[email protected]':
+ resolution: {integrity: sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==}
+
+ '@protobufjs/[email protected]':
+ resolution: {integrity: sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==}
+
+ '@protobufjs/[email protected]':
+ resolution: {integrity: sha512-Vvn3zZrhQZkkBE8LSuW3em98c0FwgO4nxzv6OdSxPKJIEKY2bGbHn+mhGIPerzI4twdxaP8/0+06HBpwf345Lw==}
+
'@radix-ui/[email protected]':
resolution: {integrity: sha512-MkKCwxlXTgz6CFoJx3pCwn07GKp36+aZyu/u2Ln2VrA5DcdyCZkASEDBTd8x5whTQQL5CiYf4prXKLcgQdv29g==}
@@ -2812,6 +2926,9 @@ packages:
resolution: {integrity: sha512-xMAgYwceFhRA2zY+XbEA7mxYbA093wdiW8Vu6gZPGWy9cmOyU9XesH1tNcEWsKFd5Vzrqx5T3D38PWx1FIIXkA==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==}
+
resolution: {integrity: sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA==}
@@ -3383,6 +3500,9 @@ packages:
resolution: {integrity: sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==}
engines: {node: '>=18'}
+ resolution: {integrity: sha512-es1U2+YTtzpwkxVLwAFdSpaIMyQaq0PBgm3YD1W3Qpsn1NAmO3KSgZfu+oGSWVu6NvLHoHCV/aYcsE5wiB7ALg==}
+
resolution: {integrity: sha512-3lqz5YjWTYnW6dlDa5TLaTCcShfar1e40rmcJVwCBJC6mWlFuj0eCHIElmG1g5kyuJ/GD+8Wn4FFCcz4gJPfaQ==}
@@ -3616,6 +3736,9 @@ packages:
resolution: {integrity: sha512-7ZgogeTnjuHbo+ct10G9Ffp0mif17idi0IyWNVA/wcwcm7NPOD/WEHVP3n7n3MhXqxoIYm8d6MuZohYWIZ4T3w==}
+ resolution: {integrity: sha512-nolgK9JcaUXMSmW+j1yaSvaEaoXYHwWyGJlkoCTghc97KgGDDSnpoU/PlEnw63Ah+TGKFOyY+X5LnxaWbCSfXg==}
+
resolution: {integrity: sha512-zIHwmZPRshsCdpMDyVsqGmgyP0yT8GAgXUnkdAoJisxvf33k7yO6OuoKmcTGuXPWSsm8Oh88nZicRLA9Y0rUeA==}
engines: {node: '>=12'}
@@ -3990,6 +4113,9 @@ packages:
resolution: {integrity: sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==}
engines: {node: ^12.20 || >= 14.13}
+ resolution: {integrity: sha512-FJqqoDBR00Mdj9ppamLa/Y7vxm+PRmNWA67N846RvsoYVMKB4q3y/de5PA7gUmRMYK/8CMz2GDZQmCRN1wBcWA==}
+
resolution: {integrity: sha512-d+l3qxjSesT4V7v2fh+QnmFnUWv9lSpjarhShNTgBOfA0ttejbQUAlHLitbjkoRiDulW0OPoQPYIGhIC8ohejg==}
engines: {node: '>=18'}
@@ -4886,6 +5012,9 @@ packages:
resolution: {integrity: sha512-i24m8rpwhmPIS4zscNzK6MSEhk0DUWa/8iYQWxhffV8jkI4Phvs3F+quL5xvS0gdQR0FyTCMMH33Y78dDTzzIw==}
engines: {node: '>=18'}
+ resolution: {integrity: sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==}
+
resolution: {integrity: sha512-9Ri+o0JYgehTaVBBDoMqIl8GXtbWg711O3srftcHhZ0dqnETqLaoIK0x17fUw9rFSlK/0NlsKe0Ahhyl5pXE2g==}
@@ -5619,6 +5748,9 @@ packages:
resolution: {integrity: sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==}
engines: {node: '>=0.10.0'}
+ resolution: {integrity: sha512-t4vk8mgkSdhIYr8YDRdLG45uJYH58MC7bPL83lKTEeDgoejyXbJ1/G77GZB/aWVQDST055GkgjQtUtK5DiYGkg==}
+
resolution: {integrity: sha512-b9Eb8h2eVqNE8edvKdwqkrY6O7kAwmI8kcnBv1NScolYJbo59XUF0noFq+lxbC1yN20bmC0WBEbDC5H/7ASb0A==}
engines: {node: '>=14.0.0'}
@@ -5628,6 +5760,9 @@ packages:
resolution: {integrity: sha512-dM0jVuXJPsDN6DvRpea484tCUaMiXWjuCn++HGTqUWzGDjv5tZkEZldAJ/UMlqRYGFrD/etByo4/xOuC/snX2A==}
engines: {node: '>=20'}
+ resolution: {integrity: sha512-gQCLc/vWroE8lIpleXtdJhTFDogTdZG9AjMUpVkDf2iTCNwYNWA+u16dL41TqUDJO4gm2IgrcMv3uTpjd4Pwmg==}
+
resolution: {integrity: sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==}
engines: {node: '>= 0.8.0'}
@@ -5726,6 +5861,10 @@ packages:
resolution: {integrity: sha512-jUwKNCEIGiqdvhlS91/2QAg21e4dfU5bH2iwmSDQeosXJgKF7smG0YSplOWK0cjSNgIqXe7VXqo7EIfUFJdt3w==}
+ resolution: {integrity: sha512-3wY1AxV+VBNW8Yypfd1yQY9pXnqTAN+KwQxL8iYm3/BjKYMNg4i0owhEe26PWDOMaIrzeeF98Lqd5NGz4omiIg==}
+ engines: {node: '>=12.0.0'}
+
resolution: {integrity: sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==}
engines: {node: '>= 0.10'}
@@ -5745,6 +5884,9 @@ packages:
resolution: {integrity: sha512-mAZTtNCeetKMH+pSjrb76NAM8V9a05I9aBZOHztWy/UqcJdQYNsf59vrRKWnojAT9Y+GbIvoTBC++CPHqpDBhQ==}
engines: {node: '>=0.6'}
+ resolution: {integrity: sha512-lT5yCqEBgfoMYpf3F2xQRK7zEr1rhIIZuceDK6+xRkJQ4NMbHTwXqk4NkwDwQMNqXgG9r9fyHnzwNVs6zV5KRw==}
+
resolution: {integrity: sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==}
@@ -6750,6 +6892,9 @@ packages:
resolution: {integrity: sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==}
engines: {node: '>= 8'}
+ resolution: {integrity: sha512-i2z98bEmaCqSDiHEDu+gHl/dmR4Q+TxFmG3/13KkMO+o8UxQzCqWaDRCiLgEa41nlO4VpXSI0ASa1xWmO9sBlA==}
+
resolution: {integrity: sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==}
engines: {node: '>=20'}
@@ -7876,6 +8021,82 @@ snapshots:
'@open-draft/[email protected]': {}
+ '@opentelemetry/[email protected]':
+ dependencies:
+ '@opentelemetry/api': 1.9.1
+
+ '@opentelemetry/[email protected]': {}
+
+ '@opentelemetry/[email protected](@opentelemetry/[email protected])':
+ dependencies:
+ '@opentelemetry/api': 1.9.1
+ '@opentelemetry/semantic-conventions': 1.40.0
+
+ '@opentelemetry/[email protected](@opentelemetry/[email protected])':
+ dependencies:
+ '@opentelemetry/api': 1.9.1
+ '@opentelemetry/semantic-conventions': 1.40.0
+
+ '@opentelemetry/[email protected](@opentelemetry/[email protected])':
+ dependencies:
+ '@opentelemetry/api': 1.9.1
+ '@opentelemetry/api-logs': 0.208.0
+ '@opentelemetry/core': 2.2.0(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-exporter-base': 0.208.0(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-transformer': 0.208.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-logs': 0.208.0(@opentelemetry/[email protected])
+
+ '@opentelemetry/[email protected](@opentelemetry/[email protected])':
+ dependencies:
+ '@opentelemetry/api': 1.9.1
+ '@opentelemetry/core': 2.2.0(@opentelemetry/[email protected])
+ '@opentelemetry/otlp-transformer': 0.208.0(@opentelemetry/[email protected])
+
+ '@opentelemetry/[email protected](@opentelemetry/[email protected])':
+ dependencies:
+ '@opentelemetry/api': 1.9.1
+ '@opentelemetry/api-logs': 0.208.0
+ '@opentelemetry/core': 2.2.0(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.2.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-logs': 0.208.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-metrics': 2.2.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-trace-base': 2.2.0(@opentelemetry/[email protected])
+ protobufjs: 7.5.5
+
+ '@opentelemetry/[email protected](@opentelemetry/[email protected])':
+ dependencies:
+ '@opentelemetry/api': 1.9.1
+ '@opentelemetry/core': 2.2.0(@opentelemetry/[email protected])
+ '@opentelemetry/semantic-conventions': 1.40.0
+
+ '@opentelemetry/[email protected](@opentelemetry/[email protected])':
+ dependencies:
+ '@opentelemetry/api': 1.9.1
+ '@opentelemetry/core': 2.7.0(@opentelemetry/[email protected])
+ '@opentelemetry/semantic-conventions': 1.40.0
+
+ '@opentelemetry/[email protected](@opentelemetry/[email protected])':
+ dependencies:
+ '@opentelemetry/api': 1.9.1
+ '@opentelemetry/api-logs': 0.208.0
+ '@opentelemetry/core': 2.2.0(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.2.0(@opentelemetry/[email protected])
+
+ '@opentelemetry/[email protected](@opentelemetry/[email protected])':
+ dependencies:
+ '@opentelemetry/api': 1.9.1
+ '@opentelemetry/core': 2.2.0(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.2.0(@opentelemetry/[email protected])
+
+ '@opentelemetry/[email protected](@opentelemetry/[email protected])':
+ dependencies:
+ '@opentelemetry/api': 1.9.1
+ '@opentelemetry/core': 2.2.0(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.2.0(@opentelemetry/[email protected])
+ '@opentelemetry/semantic-conventions': 1.40.0
+
+ '@opentelemetry/[email protected]': {}
+
'@orama/[email protected]': {}
'@oxc-project/[email protected]': {}
@@ -7887,6 +8108,33 @@ snapshots:
dependencies:
playwright: 1.58.2
+ '@posthog/[email protected]': {}
+
+ '@posthog/[email protected]': {}
+
+ '@protobufjs/[email protected]': {}
+
+ '@protobufjs/[email protected]': {}
+
+ '@protobufjs/[email protected]': {}
+
+ '@protobufjs/[email protected]': {}
+
+ '@protobufjs/[email protected]':
+ dependencies:
+ '@protobufjs/aspromise': 1.1.2
+ '@protobufjs/inquire': 1.1.0
+
+ '@protobufjs/[email protected]': {}
+
+ '@protobufjs/[email protected]': {}
+
+ '@protobufjs/[email protected]': {}
+
+ '@protobufjs/[email protected]': {}
+
+ '@protobufjs/[email protected]': {}
+
'@radix-ui/[email protected]': {}
'@radix-ui/[email protected]': {}
@@ -8909,6 +9157,9 @@ snapshots:
'@types/[email protected]': {}
+ '@types/[email protected]':
+ optional: true
+
'@types/[email protected]': {}
'@types/[email protected]': {}
@@ -9557,6 +9808,8 @@ snapshots:
+
optional: true
@@ -9778,6 +10031,10 @@ snapshots:
+ optionalDependencies:
+ '@types/trusted-types': 2.0.7
+
dependencies:
dotenv: 16.6.1
@@ -10372,6 +10629,8 @@ snapshots:
node-domexception: 1.0.0
web-streams-polyfill: 3.3.3
+
dependencies:
is-unicode-supported: 2.1.0
@@ -10484,7 +10743,7 @@ snapshots:
optional: true
dependencies:
'@formatjs/intl-localematcher': 0.6.2
'@orama/orama': 3.1.18
@@ -10507,21 +10766,21 @@ snapshots:
optionalDependencies:
'@types/react': 19.2.14
lucide-react: 1.0.1([email protected])
react: 19.2.3
react-dom: 19.2.3([email protected])
transitivePeerDependencies:
- supports-color
dependencies:
'@mdx-js/mdx': 3.1.1
'@standard-schema/spec': 1.1.0
chokidar: 4.0.3
esbuild: 0.25.12
estree-util-value-to-estree: 3.5.0
js-yaml: 4.1.1
lru-cache: 11.2.7
mdast-util-to-markdown: 2.1.2
@@ -10534,12 +10793,12 @@ snapshots:
unist-util-visit: 5.1.0
zod: 4.3.6
optionalDependencies:
react: 19.2.3
transitivePeerDependencies:
- supports-color
dependencies:
@@ -10552,7 +10811,7 @@ snapshots:
'@radix-ui/react-slot': 1.2.4(@types/[email protected])([email protected])
class-variance-authority: 0.7.1
lodash.merge: 4.6.2
postcss-selector-parser: 7.1.1
@@ -10563,7 +10822,7 @@ snapshots:
tailwind-merge: 3.5.0
optionalDependencies:
'@types/react': 19.2.14
tailwindcss: 4.2.2
transitivePeerDependencies:
- '@mixedbread/sdk'
@@ -11345,6 +11604,8 @@ snapshots:
chalk: 5.6.2
is-unicode-supported: 1.3.0
+
@@ -11983,7 +12244,7 @@ snapshots:
react: 19.2.3
react-dom: 19.2.3([email protected])
dependencies:
'@next/env': 15.5.15
'@swc/helpers': 0.5.15
@@ -12001,13 +12262,14 @@ snapshots:
'@next/swc-linux-x64-musl': 15.5.15
'@next/swc-win32-arm64-msvc': 15.5.15
'@next/swc-win32-x64-msvc': 15.5.15
+ '@opentelemetry/api': 1.9.1
'@playwright/test': 1.58.2
sharp: 0.34.5
transitivePeerDependencies:
- '@babel/core'
- babel-plugin-macros
dependencies:
'@next/env': 16.2.3
'@swc/helpers': 0.5.15
@@ -12026,6 +12288,7 @@ snapshots:
'@next/swc-linux-x64-musl': 16.2.3
'@next/swc-win32-arm64-msvc': 16.2.3
'@next/swc-win32-x64-msvc': 16.2.3
+ '@opentelemetry/api': 1.9.1
'@playwright/test': 1.58.2
sharp: 0.34.5
transitivePeerDependencies:
@@ -12368,6 +12631,22 @@ snapshots:
dependencies:
xtend: 4.0.2
+ dependencies:
+ '@opentelemetry/api': 1.9.1
+ '@opentelemetry/api-logs': 0.208.0
+ '@opentelemetry/exporter-logs-otlp-http': 0.208.0(@opentelemetry/[email protected])
+ '@opentelemetry/resources': 2.7.0(@opentelemetry/[email protected])
+ '@opentelemetry/sdk-logs': 0.208.0(@opentelemetry/[email protected])
+ '@posthog/core': 1.25.2
+ '@posthog/types': 1.369.3
+ core-js: 3.49.0
+ dompurify: 3.4.0
+ fflate: 0.4.8
+ preact: 10.29.1
+ query-selector-shadow-dom: 1.0.1
+ web-vitals: 5.2.0
+
dependencies:
commander: 9.5.0
@@ -12375,6 +12654,8 @@ snapshots:
+
@@ -12522,6 +12803,21 @@ snapshots:
prosemirror-state: 1.4.4
prosemirror-transform: 1.11.0
+ dependencies:
+ '@protobufjs/aspromise': 1.1.2
+ '@protobufjs/base64': 1.1.2
+ '@protobufjs/codegen': 2.0.4
+ '@protobufjs/eventemitter': 1.1.0
+ '@protobufjs/fetch': 1.1.0
+ '@protobufjs/float': 1.0.2
+ '@protobufjs/inquire': 1.1.0
+ '@protobufjs/path': 1.1.2
+ '@protobufjs/pool': 1.1.0
+ '@protobufjs/utf8': 1.1.0
+ '@types/node': 25.5.0
+ long: 5.3.2
+
dependencies:
forwarded: 0.2.0
@@ -12540,6 +12836,8 @@ snapshots:
dependencies:
side-channel: 1.1.0
+
@@ -13717,7 +14015,7 @@ snapshots:
fsevents: 2.3.3
jiti: 2.6.1
dependencies:
'@vitest/expect': 4.1.0
@@ -13740,6 +14038,7 @@ snapshots:
why-is-node-running: 2.3.0
optionalDependencies:
+ '@opentelemetry/api': 1.9.1
'@types/node': 25.5.0
jsdom: 29.0.1(@noble/[email protected])
transitivePeerDependencies:
@@ -13759,6 +14058,8 @@ snapshots:
+
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 39681b74c8..4e3ac14ad4 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -28,6 +28,9 @@ catalog:
# Icons
lucide-react: "^1.0.1"
+ # Product analytics
+ posthog-js: "^1.176.1"
+
# Testing
vitest: "^4.1.0"
jsdom: "^29.0.1"
diff --git a/server/cmd/server/integration_test.go b/server/cmd/server/integration_test.go
index 161f3e5919..caef6a8ac4 100644
--- a/server/cmd/server/integration_test.go
+++ b/server/cmd/server/integration_test.go
@@ -17,6 +17,7 @@ import (
"github.com/gorilla/websocket"
"github.com/jackc/pgx/v5/pgxpool"
+ "github.com/multica-ai/multica/server/internal/analytics"
"github.com/multica-ai/multica/server/internal/auth"
"github.com/multica-ai/multica/server/internal/events"
"github.com/multica-ai/multica/server/internal/realtime"
@@ -70,7 +71,7 @@ func TestMain(m *testing.M) {
bus := events.New()
registerListeners(bus, hub)
- router := NewRouter(pool, hub, bus)
+ router := NewRouter(pool, hub, bus, analytics.NoopClient{})
testServer = httptest.NewServer(router)
// Generate a JWT token directly for the test user
diff --git a/server/cmd/server/main.go b/server/cmd/server/main.go
index fd69bdd3f0..bc0403c3cc 100644
--- a/server/cmd/server/main.go
+++ b/server/cmd/server/main.go
@@ -9,6 +9,7 @@ import (
"syscall"
"time"
+ "github.com/multica-ai/multica/server/internal/analytics"
"github.com/multica-ai/multica/server/internal/events"
"github.com/multica-ai/multica/server/internal/logger"
"github.com/multica-ai/multica/server/internal/realtime"
@@ -58,6 +59,9 @@ func main() {
go hub.Run()
registerListeners(bus, hub)
+ analyticsClient := analytics.NewFromEnv()
+ defer analyticsClient.Close()
+
queries := db.New(pool)
// Order matters: subscriber listeners must register BEFORE notification listeners.
// The notification listener queries the subscriber table to determine recipients,
@@ -66,7 +70,7 @@ func main() {
registerActivityListeners(bus, queries)
registerNotificationListeners(bus, queries)
- r := NewRouter(pool, hub, bus)
+ r := NewRouter(pool, hub, bus, analyticsClient)
srv := &http.Server{
Addr: ":" + port,
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 5f499a6c27..64687a8589 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -12,6 +12,7 @@ import (
"github.com/jackc/pgx/v5/pgtype"
"github.com/jackc/pgx/v5/pgxpool"
+ "github.com/multica-ai/multica/server/internal/analytics"
"github.com/multica-ai/multica/server/internal/auth"
"github.com/multica-ai/multica/server/internal/events"
"github.com/multica-ai/multica/server/internal/handler"
@@ -53,7 +54,7 @@ func allowedOrigins() []string {
}
// NewRouter creates the fully-configured Chi router with all middleware and routes.
-func NewRouter(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus) chi.Router {
+func NewRouter(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus, analyticsClient analytics.Client) chi.Router {
queries := db.New(pool)
emailSvc := service.NewEmailService()
@@ -76,7 +77,7 @@ func NewRouter(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus) chi.Route
AllowedEmails: splitAndTrim(os.Getenv("ALLOWED_EMAILS")),
AllowedEmailDomains: splitAndTrim(os.Getenv("ALLOWED_EMAIL_DOMAINS")),
}
- h := handler.New(queries, pool, hub, bus, emailSvc, store, cfSigner, signupConfig)
+ h := handler.New(queries, pool, hub, bus, emailSvc, store, cfSigner, analyticsClient, signupConfig)
r := chi.NewRouter()
diff --git a/server/internal/analytics/client.go b/server/internal/analytics/client.go
new file mode 100644
index 0000000000..4df0d3dc35
--- /dev/null
+++ b/server/internal/analytics/client.go
@@ -0,0 +1,94 @@
+// Package analytics ships product telemetry events to an external analytics
+// backend (PostHog). Events feed the acquisition → activation → expansion
+// funnel — see docs/analytics.md for the event contract.
+//
+// Design:
+// - Capture is non-blocking. Request handlers must never wait on analytics
+// network I/O, so we enqueue into a bounded channel and a background
+// worker flushes to PostHog in batches.
+// - When the queue is full events are dropped (and counted). A broken
+// analytics backend must never degrade the product.
+// - When POSTHOG_API_KEY is empty the package runs a no-op client, which
+// keeps local dev and self-hosted instances friction-free.
+package analytics
+
+import (
+ "log/slog"
+ "os"
+ "time"
+)
+
+// Event is a single analytics capture. Fields mirror PostHog's /capture/ shape
+// but are framework-agnostic so alternate backends can plug in later.
+type Event struct {
+ // Name of the event (e.g. "signup", "workspace_created").
+ Name string
+
+ // DistinctID identifies the person this event belongs to. For logged-in
+ // users this is user.id; for anonymous events it should be the anon_id
+ // that was previously used on the frontend so identity merging works.
+ DistinctID string
+
+ // WorkspaceID scopes the event to a workspace. Required when the event is
+ // about a workspace-level action (workspace_created, issue_executed, ...).
+ // Empty is allowed for pre-workspace events (signup).
+ WorkspaceID string
+
+ // Properties is the free-form bag of event attributes. Only serialisable
+ // values (string, number, bool, nested maps/slices of the same) should
+ // go here. Never put raw PII like full emails here — use email_domain.
+ Properties map[string]any
+
+ // SetOnce properties attach to the person record and are only written the
+ // first time they appear. Use this for acquisition attribution
+ // (initial_utm_source, etc.) so later events don't overwrite the origin.
+ SetOnce map[string]any
+
+ // Timestamp is optional; when zero the client fills in time.Now().
+ Timestamp time.Time
+}
+
+// Client is the narrow surface the rest of the codebase depends on. Handlers
+// call Capture and move on; the implementation is responsible for buffering,
+// batching, and shipping.
+type Client interface {
+ Capture(e Event)
+ // Close drains pending events. Call once during graceful shutdown.
+ Close()
+}
+
+// NewFromEnv returns a Client configured from environment variables:
+//
+// - POSTHOG_API_KEY: project API key. Empty → no-op client.
+// - POSTHOG_HOST: API host (default https://us.i.posthog.com).
+// - ANALYTICS_DISABLED: set to "true"/"1" to force a no-op client even
+// when POSTHOG_API_KEY is set (useful for CI and self-hosted opt-out).
+func NewFromEnv() Client {
+ if isDisabled() {
+ slog.Info("analytics disabled via ANALYTICS_DISABLED")
+ return NoopClient{}
+ }
+ key := os.Getenv("POSTHOG_API_KEY")
+ if key == "" {
+ slog.Info("analytics: POSTHOG_API_KEY not set, using noop client")
+ return NoopClient{}
+ }
+ host := os.Getenv("POSTHOG_HOST")
+ if host == "" {
+ host = "https://us.i.posthog.com"
+ }
+ slog.Info("analytics: posthog client enabled", "host", host)
+ return NewPostHogClient(PostHogConfig{APIKey: key, Host: host})
+}
+
+func isDisabled() bool {
+ v := os.Getenv("ANALYTICS_DISABLED")
+ return v == "true" || v == "1"
+}
+
+// NoopClient silently drops all events. Used in tests, in local dev when
+// POSTHOG_API_KEY is unset, and in self-hosted instances that opt out.
+type NoopClient struct{}
+
+func (NoopClient) Capture(Event) {}
+func (NoopClient) Close() {}
diff --git a/server/internal/analytics/client_test.go b/server/internal/analytics/client_test.go
new file mode 100644
index 0000000000..ef6732ebcd
--- /dev/null
+++ b/server/internal/analytics/client_test.go
@@ -0,0 +1,119 @@
+package analytics
+
+import (
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "sync"
+ "testing"
+ "time"
+)
+
+func TestNoopClient(t *testing.T) {
+ c := NoopClient{}
+ c.Capture(Event{Name: "foo"})
+ c.Close()
+}
+
+func TestPostHogClient_Batching(t *testing.T) {
+ var (
+ mu sync.Mutex
+ received [][]captureItem
+ )
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/batch/" {
+ t.Errorf("unexpected path %s", r.URL.Path)
+ }
+ body, _ := io.ReadAll(r.Body)
+ var payload capturePayload
+ if err := json.Unmarshal(body, &payload); err != nil {
+ t.Errorf("decode payload: %v", err)
+ }
+ if payload.APIKey != "test-key" {
+ t.Errorf("api_key = %q, want test-key", payload.APIKey)
+ }
+ mu.Lock()
+ received = append(received, payload.Batch)
+ mu.Unlock()
+ w.WriteHeader(http.StatusOK)
+ }))
+ defer srv.Close()
+
+ c := NewPostHogClient(PostHogConfig{
+ APIKey: "test-key",
+ Host: srv.URL,
+ BatchSize: 2,
+ FlushEvery: time.Hour, // irrelevant, we hit the size trigger
+ })
+
+ c.Capture(Event{Name: "signup", DistinctID: "u1", WorkspaceID: "w1"})
+ c.Capture(Event{Name: "workspace_created", DistinctID: "u1", WorkspaceID: "w1"})
+ c.Close() // drains
+
+ mu.Lock()
+ defer mu.Unlock()
+ total := 0
+ for _, b := range received {
+ total += len(b)
+ }
+ if total != 2 {
+ t.Fatalf("received %d events, want 2 (batches=%d)", total, len(received))
+ }
+ // Both events should carry workspace_id in properties.
+ for _, batch := range received {
+ for _, item := range batch {
+ if item.Properties["workspace_id"] != "w1" {
+ t.Errorf("missing workspace_id on event %s", item.Event)
+ }
+ if item.DistinctID != "u1" {
+ t.Errorf("distinct_id = %q, want u1", item.DistinctID)
+ }
+ }
+ }
+}
+
+func TestPostHogClient_DropsWhenFull(t *testing.T) {
+ // Handler blocks so batches never flush — queue will fill up.
+ block := make(chan struct{})
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ <-block
+ }))
+ defer srv.Close()
+ defer close(block)
+
+ c := NewPostHogClient(PostHogConfig{
+ APIKey: "test-key",
+ Host: srv.URL,
+ QueueSize: 2,
+ BatchSize: 1,
+ FlushEvery: time.Hour,
+ })
+ defer c.Close()
+
+ // First event may be consumed by the worker (which is now blocked in send).
+ // Next events will sit in the queue (cap=2) until it's full and then drop.
+ for i := 0; i < 20; i++ {
+ c.Capture(Event{Name: "spam", DistinctID: "u"})
+ }
+ // Give the worker a chance to pick up at least one.
+ time.Sleep(50 * time.Millisecond)
+ if c.dropped.Load() == 0 {
+ t.Fatalf("expected some drops when queue saturated")
+ }
+}
+
+func TestEmailDomain(t *testing.T) {
+ cases := map[string]string{
+ "[email protected]": "example.com",
+ "[email protected]": "company.co.uk",
+ "": "",
+ "no-at": "",
+ "trailing@": "",
+ }
+ for in, want := range cases {
+ if got := emailDomain(in); got != want {
+ t.Errorf("emailDomain(%q) = %q, want %q", in, got, want)
+ }
+ }
+}
diff --git a/server/internal/analytics/events.go b/server/internal/analytics/events.go
new file mode 100644
index 0000000000..69e58efa04
--- /dev/null
+++ b/server/internal/analytics/events.go
@@ -0,0 +1,141 @@
+package analytics
+
+import "strings"
+
+// Event names. Keep in sync with docs/analytics.md.
+const (
+ EventSignup = "signup"
+ EventWorkspaceCreated = "workspace_created"
+ EventRuntimeRegistered = "runtime_registered"
+ EventIssueExecuted = "issue_executed"
+ EventTeamInviteSent = "team_invite_sent"
+ EventTeamInviteAccepted = "team_invite_accepted"
+)
+
+// Platform is used as the "platform" event property so funnels can split by
+// web / desktop / cli. Request-path events use PlatformServer as a fallback
+// when the caller is a server-originating action (e.g. auto-created user);
+// otherwise the frontend passes the real platform via a header / body field
+// in later iterations.
+const (
+ PlatformServer = "server"
+ PlatformWeb = "web"
+ PlatformDesktop = "desktop"
+ PlatformCLI = "cli"
+)
+
+// Signup builds the signup event. signupSource is populated from the
+// frontend's stored UTM/referrer cookie if present; leave empty otherwise.
+func Signup(userID, email, signupSource string) Event {
+ return Event{
+ Name: EventSignup,
+ DistinctID: userID,
+ Properties: map[string]any{
+ "email_domain": emailDomain(email),
+ "signup_source": signupSource,
+ },
+ SetOnce: map[string]any{
+ "email": email,
+ "signup_source": signupSource,
+ },
+ }
+}
+
+// WorkspaceCreated builds the workspace_created event. "Is this the user's
+// first workspace?" is deliberately not stamped here — it's derived in
+// PostHog by checking whether the user has a prior workspace_created event.
+func WorkspaceCreated(userID, workspaceID string) Event {
+ return Event{
+ Name: EventWorkspaceCreated,
+ DistinctID: userID,
+ WorkspaceID: workspaceID,
+ }
+}
+
+// RuntimeRegistered fires on the first time a (workspace, daemon, provider)
+// triple is upserted. The handler uses a `xmax = 0` flag returned from the
+// upsert query to distinguish inserts from updates — heartbeats and repeat
+// registrations never emit this event.
+//
+// ownerID may be empty when the daemon authenticates via a daemon token
+// (no user context); downstream funnels that need per-user attribution
+// fall back to `workspace_id` as the grouping key.
+func RuntimeRegistered(ownerID, workspaceID, runtimeID, provider, runtimeVersion, cliVersion string) Event {
+ distinct := ownerID
+ if distinct == "" {
+ // A per-workspace synthetic id keeps PostHog from merging unrelated
+ // daemon registrations across workspaces under a single "anonymous"
+ // person. It's stable within a workspace so repeat heartbeats (which
+ // don't emit anyway) would at least group correctly.
+ distinct = "workspace:" + workspaceID
+ }
+ return Event{
+ Name: EventRuntimeRegistered,
+ DistinctID: distinct,
+ WorkspaceID: workspaceID,
+ Properties: map[string]any{
+ "runtime_id": runtimeID,
+ "provider": provider,
+ "runtime_version": runtimeVersion,
+ "cli_version": cliVersion,
+ },
+ }
+}
+
+// IssueExecuted fires at most once per issue lifetime — on the first task
+// completion that flips `issues.first_executed_at` from NULL via an atomic
+// UPDATE. Retries, re-assignments, and comment-triggered follow-ups never
+// re-emit, which is what keeps the ≥1/≥2/≥5/≥10 funnel buckets honest.
+//
+// Deliberately not stamped here: the workspace's Nth-issue ordinal.
+// Computing it at emit time is not atomic (two concurrent first-completions
+// both read count=1, both emit n=1), and PostHog derives the same number
+// exactly at query time from the event stream.
+func IssueExecuted(actorID, workspaceID, issueID string, taskDurationMS int64) Event {
+ return Event{
+ Name: EventIssueExecuted,
+ DistinctID: actorID,
+ WorkspaceID: workspaceID,
+ Properties: map[string]any{
+ "issue_id": issueID,
+ "task_duration_ms": taskDurationMS,
+ },
+ }
+}
+
+// TeamInviteSent fires when a workspace admin creates an invitation.
+// inviteMethod is "email" for now; future non-email invite flows can pass
+// their own value to keep this stable.
+func TeamInviteSent(inviterID, workspaceID, invitedEmail, inviteMethod string) Event {
+ return Event{
+ Name: EventTeamInviteSent,
+ DistinctID: inviterID,
+ WorkspaceID: workspaceID,
+ Properties: map[string]any{
+ "invited_email_domain": emailDomain(invitedEmail),
+ "invite_method": inviteMethod,
+ },
+ }
+}
+
+// TeamInviteAccepted fires when the invitee accepts and joins the workspace.
+// daysSinceInvite lets us segment fast-acceptance (warm) from long-tail
+// acceptance (someone dug through old email).
+func TeamInviteAccepted(inviteeID, workspaceID string, daysSinceInvite int64) Event {
+ return Event{
+ Name: EventTeamInviteAccepted,
+ DistinctID: inviteeID,
+ WorkspaceID: workspaceID,
+ Properties: map[string]any{
+ "days_since_invite": daysSinceInvite,
+ },
+ }
+}
+
+func emailDomain(email string) string {
+ at := strings.LastIndex(email, "@")
+ if at < 0 || at == len(email)-1 {
+ return ""
+ }
+ return strings.ToLower(email[at+1:])
+}
diff --git a/server/internal/analytics/posthog.go b/server/internal/analytics/posthog.go
new file mode 100644
index 0000000000..d41b8f1f76
--- /dev/null
+++ b/server/internal/analytics/posthog.go
@@ -0,0 +1,207 @@
+package analytics
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "log/slog"
+ "net/http"
+ "sync"
+ "sync/atomic"
+ "time"
+)
+
+const (
+ defaultQueueSize = 1024
+ defaultBatchSize = 64
+ defaultFlushEvery = 10 * time.Second
+ defaultFlushTimeout = 5 * time.Second
+)
+
+// PostHogConfig configures the live PostHog client.
+type PostHogConfig struct {
+ APIKey string
+ Host string
+
+ // Optional overrides. Zero values fall back to sensible defaults.
+ QueueSize int
+ BatchSize int
+ FlushEvery time.Duration
+ HTTPClient *http.Client
+}
+
+// PostHogClient ships events to PostHog's /batch/ endpoint. It enqueues events
+// into a bounded buffer (non-blocking Capture) and flushes them from a
+// background worker.
+type PostHogClient struct {
+ cfg PostHogConfig
+ ch chan Event
+ done chan struct{}
+ wg sync.WaitGroup
+
+ dropped atomic.Uint64 // events dropped because the queue was full
+ sent atomic.Uint64
+ failed atomic.Uint64
+}
+
+// NewPostHogClient starts the background flush worker. Caller must call Close
+// on shutdown to drain pending events.
+func NewPostHogClient(cfg PostHogConfig) *PostHogClient {
+ if cfg.QueueSize <= 0 {
+ cfg.QueueSize = defaultQueueSize
+ }
+ if cfg.BatchSize <= 0 {
+ cfg.BatchSize = defaultBatchSize
+ }
+ if cfg.FlushEvery <= 0 {
+ cfg.FlushEvery = defaultFlushEvery
+ }
+ if cfg.HTTPClient == nil {
+ cfg.HTTPClient = &http.Client{Timeout: defaultFlushTimeout}
+ }
+ c := &PostHogClient{
+ cfg: cfg,
+ ch: make(chan Event, cfg.QueueSize),
+ done: make(chan struct{}),
+ }
+ c.wg.Add(1)
+ go c.run()
+ return c
+}
+
+// Capture enqueues an event. Returns immediately; on a full queue the event
+// is dropped and counted. Analytics must never block a request handler.
+func (c *PostHogClient) Capture(e Event) {
+ if e.Timestamp.IsZero() {
+ e.Timestamp = time.Now().UTC()
+ }
+ select {
+ case c.ch <- e:
+ default:
+ n := c.dropped.Add(1)
+ // Log periodically — every 100 drops — so a broken pipe is visible but
+ // doesn't spam logs under sustained load.
+ if n%100 == 1 {
+ slog.Warn("analytics: queue full, dropping event", "event", e.Name, "total_dropped", n)
+ }
+ }
+}
+
+// Close stops accepting events and drains whatever is already queued.
+func (c *PostHogClient) Close() {
+ close(c.done)
+ c.wg.Wait()
+ slog.Info("analytics: posthog client closed",
+ "sent", c.sent.Load(),
+ "dropped", c.dropped.Load(),
+ "failed", c.failed.Load(),
+ )
+}
+
+func (c *PostHogClient) run() {
+ defer c.wg.Done()
+ ticker := time.NewTicker(c.cfg.FlushEvery)
+ defer ticker.Stop()
+
+ batch := make([]Event, 0, c.cfg.BatchSize)
+ flush := func() {
+ if len(batch) == 0 {
+ return
+ }
+ c.send(batch)
+ batch = batch[:0]
+ }
+
+ for {
+ select {
+ case e := <-c.ch:
+ batch = append(batch, e)
+ if len(batch) >= c.cfg.BatchSize {
+ flush()
+ }
+ case <-ticker.C:
+ flush()
+ case <-c.done:
+ // Drain remaining events. The channel is not closed by Close() to
+ // avoid racing with Capture, so we loop until it's empty.
+ for {
+ select {
+ case e := <-c.ch:
+ batch = append(batch, e)
+ if len(batch) >= c.cfg.BatchSize {
+ flush()
+ }
+ default:
+ flush()
+ return
+ }
+ }
+ }
+ }
+}
+
+// capturePayload mirrors the PostHog /batch/ JSON shape.
+type capturePayload struct {
+ APIKey string `json:"api_key"`
+ Batch []captureItem `json:"batch"`
+}
+
+type captureItem struct {
+ Event string `json:"event"`
+ DistinctID string `json:"distinct_id"`
+ Properties map[string]any `json:"properties"`
+ Timestamp string `json:"timestamp"`
+}
+
+func (c *PostHogClient) send(batch []Event) {
+ items := make([]captureItem, 0, len(batch))
+ for _, e := range batch {
+ props := make(map[string]any, len(e.Properties)+2)
+ for k, v := range e.Properties {
+ props[k] = v
+ }
+ if e.WorkspaceID != "" {
+ props["workspace_id"] = e.WorkspaceID
+ }
+ if len(e.SetOnce) > 0 {
+ props["$set_once"] = e.SetOnce
+ }
+ items = append(items, captureItem{
+ Event: e.Name,
+ DistinctID: e.DistinctID,
+ Properties: props,
+ Timestamp: e.Timestamp.UTC().Format(time.RFC3339Nano),
+ })
+ }
+
+ body, err := json.Marshal(capturePayload{APIKey: c.cfg.APIKey, Batch: items})
+ if err != nil {
+ c.failed.Add(uint64(len(batch)))
+ slog.Error("analytics: marshal batch", "error", err)
+ return
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), defaultFlushTimeout)
+ defer cancel()
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.cfg.Host+"/batch/", bytes.NewReader(body))
+ if err != nil {
+ c.failed.Add(uint64(len(batch)))
+ slog.Error("analytics: build request", "error", err)
+ return
+ }
+ req.Header.Set("Content-Type", "application/json")
+
+ resp, err := c.cfg.HTTPClient.Do(req)
+ if err != nil {
+ c.failed.Add(uint64(len(batch)))
+ slog.Warn("analytics: send batch failed", "error", err, "events", len(batch))
+ return
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode >= 400 {
+ c.failed.Add(uint64(len(batch)))
+ slog.Warn("analytics: posthog rejected batch", "status", resp.StatusCode, "events", len(batch))
+ return
+ }
+ c.sent.Add(uint64(len(batch)))
+}
diff --git a/server/internal/handler/auth.go b/server/internal/handler/auth.go
index 5b7ce07fd8..7c7787c6e5 100644
--- a/server/internal/handler/auth.go
+++ b/server/internal/handler/auth.go
@@ -18,6 +18,7 @@ import (
"github.com/golang-jwt/jwt/v5"
"github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/analytics"
"github.com/multica-ai/multica/server/internal/auth"
"github.com/multica-ai/multica/server/internal/logger"
db "github.com/multica-ai/multica/server/pkg/db/generated"
@@ -89,29 +90,66 @@ func (h *Handler) issueJWT(user db.User) (string, error) {
return token.SignedString(auth.JWTSecret())
}
-func (h *Handler) findOrCreateUser(ctx context.Context, email string) (db.User, error) {
- user, err := h.Queries.GetUserByEmail(ctx, email)
- isNewUser := isNotFound(err)
- if err != nil && !isNewUser {
- return db.User{}, err
+// findOrCreateUser returns the existing user for an email, or creates one if
+// none exists. isNew reports whether this call created the user — the signup
+// event fires on that edge, covering both the verification-code and Google
+// OAuth entry points.
+func (h *Handler) findOrCreateUser(ctx context.Context, email string) (user db.User, isNew bool, err error) {
+ user, err = h.Queries.GetUserByEmail(ctx, email)
+ isNew = isNotFound(err)
+ if err != nil && !isNew {
+ return db.User{}, false, err
}
- if err := h.checkSignupAllowed(email, isNewUser); err != nil {
- return db.User{}, err
+ if err := h.checkSignupAllowed(email, isNew); err != nil {
+ return db.User{}, false, err
}
- if !isNewUser {
- return user, nil
+ if !isNew {
+ return user, false, nil
}
name := email
if at := strings.Index(email, "@"); at > 0 {
name = email[:at]
}
- return h.Queries.CreateUser(ctx, db.CreateUserParams{
+ created, err := h.Queries.CreateUser(ctx, db.CreateUserParams{
Name: name,
Email: email,
})
+ if err != nil {
+ return db.User{}, false, err
+ }
+ return created, true, nil
+}
+
+// signupSourceFromRequest reads the attribution cookie the web frontend
+// sets on the first pageview (UTM + referrer bundle). The frontend writes
+// a JSON string URL-encoded into the cookie value — Go does not
+// auto-decode Cookie.Value, so we have to unescape here before the string
+// lands in PostHog. Missing cookie / decode failures collapse to the
+// empty string; that simply omits signup_source from the event rather
+// than sending percent-encoded garbage. Never fall back to r.Referer() —
+// the frontend has already sanitised attribution and a raw referer can
+// leak OAuth code/state from the callback URL.
+//
+// The cap is the server-side defence against a client that manages to set
+// an oversize cookie; it matches SIGNUP_SOURCE_MAX_LEN on the frontend.
+const signupSourceMaxLen = 512
+
+func signupSourceFromRequest(r *http.Request) string {
+ c, err := r.Cookie("multica_signup_source")
+ if err != nil || c == nil {
+ return ""
+ }
+ decoded, err := url.QueryUnescape(c.Value)
+ if err != nil {
+ return ""
+ }
+ if len(decoded) > signupSourceMaxLen {
+ return ""
+ }
+ return decoded
}
func (h *Handler) checkSignupAllowed(email string, isNewUser bool) error {
@@ -272,7 +310,7 @@ func (h *Handler) VerifyCode(w http.ResponseWriter, r *http.Request) {
return
}
- user, err := h.findOrCreateUser(r.Context(), email)
+ user, isNew, err := h.findOrCreateUser(r.Context(), email)
if err != nil {
var signupErr SignupError
if errors.As(err, &signupErr) {
@@ -282,6 +320,9 @@ func (h *Handler) VerifyCode(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusInternalServerError, "failed to create user")
return
}
+ if isNew {
+ h.Analytics.Capture(analytics.Signup(uuidToString(user.ID), user.Email, signupSourceFromRequest(r)))
+ }
tokenString, err := h.issueJWT(user)
if err != nil {
@@ -433,7 +474,7 @@ func (h *Handler) GoogleLogin(w http.ResponseWriter, r *http.Request) {
email := strings.ToLower(strings.TrimSpace(gUser.Email))
- user, err := h.findOrCreateUser(r.Context(), email)
+ user, isNew, err := h.findOrCreateUser(r.Context(), email)
if err != nil {
var signupErr SignupError
if errors.As(err, &signupErr) {
@@ -443,6 +484,11 @@ func (h *Handler) GoogleLogin(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusInternalServerError, "failed to create user")
return
}
+ if isNew {
+ evt := analytics.Signup(uuidToString(user.ID), user.Email, signupSourceFromRequest(r))
+ evt.Properties["auth_method"] = "google"
+ h.Analytics.Capture(evt)
+ }
// Update name and avatar from Google profile if the user was just created
// (default name is email prefix) or has no avatar yet.
diff --git a/server/internal/handler/auth_signup_test.go b/server/internal/handler/auth_signup_test.go
index cc3e14554b..227dcaf6d5 100644
--- a/server/internal/handler/auth_signup_test.go
+++ b/server/internal/handler/auth_signup_test.go
@@ -71,10 +71,13 @@ func TestFindOrCreateUserGating(t *testing.T) {
h := newTestHandler(cfg)
h.Queries = db.New(&mockDB{getUserErr: pgx.ErrNoRows})
- _, err := h.findOrCreateUser(context.Background(), "[email protected]")
+ _, isNew, err := h.findOrCreateUser(context.Background(), "[email protected]")
if err == nil {
t.Fatal("expected error for new user when signup disabled")
}
+ if isNew {
+ t.Fatal("isNew should be false when signup is blocked")
+ }
if !strings.Contains(err.Error(), "registration is disabled") {
t.Fatalf("expected registration disabled error, got %v", err)
}
@@ -86,10 +89,13 @@ func TestFindOrCreateUserGating(t *testing.T) {
// mockDB returns nil error for Scan, simulating user found
h.Queries = db.New(&mockDB{getUserErr: nil})
- _, err := h.findOrCreateUser(context.Background(), "[email protected]")
+ _, isNew, err := h.findOrCreateUser(context.Background(), "[email protected]")
if err != nil {
t.Fatalf("expected no error for existing user, got %v", err)
}
+ if isNew {
+ t.Fatal("existing user should not be flagged as new")
+ }
})
t.Run("whitelisted_user_allowed", func(t *testing.T) {
@@ -100,7 +106,7 @@ func TestFindOrCreateUserGating(t *testing.T) {
// This will pass checkSignupAllowed and move to CreateUser.
// Our mockDB Exec returns success, but Queries.CreateUser might expect QueryRow for RETURNING id.
// Let's see if it works.
- _, err := h.findOrCreateUser(context.Background(), "[email protected]")
+ _, _, err := h.findOrCreateUser(context.Background(), "[email protected]")
if err != nil && strings.Contains(err.Error(), "registration is disabled") {
t.Fatalf("expected whitelisted user to pass signup check, but got %v", err)
}
diff --git a/server/internal/handler/config.go b/server/internal/handler/config.go
index 0736cec77c..3815e7db8a 100644
--- a/server/internal/handler/config.go
+++ b/server/internal/handler/config.go
@@ -1,9 +1,20 @@
package handler
-import "net/http"
+import (
+ "net/http"
+ "os"
+)
type AppConfig struct {
CdnDomain string `json:"cdn_domain"`
+
+ // PostHog public config for the frontend. The key is the same Project
+ // API Key the backend uses; returning it here (instead of baking it
+ // into the frontend bundle via NEXT_PUBLIC_*) means self-hosted
+ // instances — whose server returns an empty key — automatically
+ // disable frontend event shipping too.
+ PosthogKey string `json:"posthog_key"`
+ PosthogHost string `json:"posthog_host"`
}
func (h *Handler) GetConfig(w http.ResponseWriter, r *http.Request) {
@@ -11,5 +22,16 @@ func (h *Handler) GetConfig(w http.ResponseWriter, r *http.Request) {
if h.Storage != nil {
config.CdnDomain = h.Storage.CdnDomain()
}
+
+ // Re-read from env on every request so operators can rotate keys via
+ // secret refresh without a server restart.
+ if v := os.Getenv("ANALYTICS_DISABLED"); v != "true" && v != "1" {
+ config.PosthogKey = os.Getenv("POSTHOG_API_KEY")
+ config.PosthogHost = os.Getenv("POSTHOG_HOST")
+ if config.PosthogHost == "" && config.PosthogKey != "" {
+ config.PosthogHost = "https://us.i.posthog.com"
+ }
+ }
+
writeJSON(w, http.StatusOK, config)
}
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index 41cfffd381..166eb6b505 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -14,6 +14,7 @@ import (
"github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/analytics"
"github.com/multica-ai/multica/server/internal/middleware"
db "github.com/multica-ai/multica/server/pkg/db/generated"
"github.com/multica-ai/multica/server/pkg/protocol"
@@ -262,7 +263,7 @@ func (h *Handler) DaemonRegister(w http.ResponseWriter, r *http.Request) {
"launched_by": req.LaunchedBy,
})
- registered, err := h.Queries.UpsertAgentRuntime(r.Context(), db.UpsertAgentRuntimeParams{
+ row, err := h.Queries.UpsertAgentRuntime(r.Context(), db.UpsertAgentRuntimeParams{
WorkspaceID: parseUUID(req.WorkspaceID),
DaemonID: strToText(req.DaemonID),
Name: name,
@@ -278,6 +279,34 @@ func (h *Handler) DaemonRegister(w http.ResponseWriter, r *http.Request) {
return
}
+ registered := db.AgentRuntime{
+ ID: row.ID,
+ WorkspaceID: row.WorkspaceID,
+ DaemonID: row.DaemonID,
+ Name: row.Name,
+ RuntimeMode: row.RuntimeMode,
+ Provider: row.Provider,
+ Status: row.Status,
+ DeviceInfo: row.DeviceInfo,
+ Metadata: row.Metadata,
+ LastSeenAt: row.LastSeenAt,
+ CreatedAt: row.CreatedAt,
+ UpdatedAt: row.UpdatedAt,
+ OwnerID: row.OwnerID,
+ LegacyDaemonID: row.LegacyDaemonID,
+ }
+
+ if row.Inserted {
+ h.Analytics.Capture(analytics.RuntimeRegistered(
+ uuidToString(ownerID),
+ req.WorkspaceID,
+ uuidToString(registered.ID),
+ provider,
+ runtime.Version,
+ req.CLIVersion,
+ ))
+ }
+
// Seamless migration from the previous hostname-derived identity. The
// daemon sends every legacy daemon_id it may have registered under
// (e.g. "host.local", "host", "host-staging"); for each match we
@@ -838,10 +867,48 @@ func (h *Handler) CompleteTask(w http.ResponseWriter, r *http.Request) {
return
}
+ h.emitIssueExecutedOnFirstCompletion(r, task)
+
slog.Info("task completed", "task_id", taskID, "agent_id", uuidToString(task.AgentID))
writeJSON(w, http.StatusOK, taskToResponse(*task))
}
+// emitIssueExecutedOnFirstCompletion atomically flips issue.first_executed_at
+// and fires the issue_executed analytics event iff this is the first task on
+// the issue to reach terminal done. Retries / re-assignments / comment-
+// triggered follow-ups hit the WHERE first_executed_at IS NULL clause and
+// no-op, so the funnel counts unique issues, not tasks.
+func (h *Handler) emitIssueExecutedOnFirstCompletion(r *http.Request, task *db.AgentTaskQueue) {
+ if task == nil {
+ return
+ }
+ marked, err := h.Queries.MarkIssueFirstExecuted(r.Context(), task.IssueID)
+ if err != nil {
+ if !isNotFound(err) {
+ slog.Warn("analytics: mark issue first-executed failed", "issue_id", uuidToString(task.IssueID), "error", err)
+ }
+ return
+ }
+ var durationMS int64
+ if task.StartedAt.Valid && task.CompletedAt.Valid {
+ durationMS = task.CompletedAt.Time.Sub(task.StartedAt.Time).Milliseconds()
+ }
+ // distinct_id prefers the human creator so agent-driven events flow into
+ // the issue-author's person profile (same place signup and
+ // workspace_created land). Agent-created issues keep the agent id with a
+ // prefix so PostHog doesn't merge them into a user by accident.
+ distinct := uuidToString(marked.CreatorID)
+ if marked.CreatorType == "agent" {
+ distinct = "agent:" + distinct
+ }
+ h.Analytics.Capture(analytics.IssueExecuted(
+ distinct,
+ uuidToString(marked.WorkspaceID),
+ uuidToString(marked.ID),
+ durationMS,
+ ))
+}
+
// ReportTaskUsage stores per-task token usage. Called independently of
// complete/fail so usage is captured even when tasks fail or are blocked.
type TaskUsagePayload struct {
diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.go
index 6fc4394146..fa5b7b3f2f 100644
--- a/server/internal/handler/handler.go
+++ b/server/internal/handler/handler.go
@@ -11,6 +11,7 @@ import (
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/analytics"
"github.com/multica-ai/multica/server/internal/auth"
"github.com/multica-ai/multica/server/internal/events"
"github.com/multica-ai/multica/server/internal/middleware"
@@ -51,15 +52,20 @@ type Handler struct {
ModelListStore *ModelListStore
Storage storage.Storage
CFSigner *auth.CloudFrontSigner
+ Analytics analytics.Client
cfg Config
}
-func New(queries *db.Queries, txStarter txStarter, hub *realtime.Hub, bus *events.Bus, emailService *service.EmailService, store storage.Storage, cfSigner *auth.CloudFrontSigner, cfg Config) *Handler {
+func New(queries *db.Queries, txStarter txStarter, hub *realtime.Hub, bus *events.Bus, emailService *service.EmailService, store storage.Storage, cfSigner *auth.CloudFrontSigner, analyticsClient analytics.Client, cfg Config) *Handler {
var executor dbExecutor
if candidate, ok := txStarter.(dbExecutor); ok {
executor = candidate
}
+ if analyticsClient == nil {
+ analyticsClient = analytics.NoopClient{}
+ }
+
taskSvc := service.NewTaskService(queries, txStarter, hub, bus)
return &Handler{
Queries: queries,
@@ -75,6 +81,7 @@ func New(queries *db.Queries, txStarter txStarter, hub *realtime.Hub, bus *event
ModelListStore: NewModelListStore(),
Storage: store,
CFSigner: cfSigner,
+ Analytics: analyticsClient,
cfg: cfg,
}
}
diff --git a/server/internal/handler/handler_test.go b/server/internal/handler/handler_test.go
index 4ce77f8a92..216c043171 100644
--- a/server/internal/handler/handler_test.go
+++ b/server/internal/handler/handler_test.go
@@ -13,6 +13,7 @@ import (
"github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v5/pgxpool"
+ "github.com/multica-ai/multica/server/internal/analytics"
"github.com/multica-ai/multica/server/internal/events"
"github.com/multica-ai/multica/server/internal/realtime"
"github.com/multica-ai/multica/server/internal/service"
@@ -54,7 +55,7 @@ func TestMain(m *testing.M) {
go hub.Run()
bus := events.New()
emailSvc := service.NewEmailService()
- testHandler = New(queries, pool, hub, bus, emailSvc, nil, nil, Config{AllowSignup: true})
+ testHandler = New(queries, pool, hub, bus, emailSvc, nil, nil, analytics.NoopClient{}, Config{AllowSignup: true})
testPool = pool
testUserID, testWorkspaceID, err = setupHandlerTestFixture(ctx, pool)
diff --git a/server/internal/handler/invitation.go b/server/internal/handler/invitation.go
index 6bd5fafb52..a524e2ef54 100644
--- a/server/internal/handler/invitation.go
+++ b/server/internal/handler/invitation.go
@@ -9,6 +9,7 @@ import (
"github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/analytics"
"github.com/multica-ai/multica/server/internal/logger"
db "github.com/multica-ai/multica/server/pkg/db/generated"
"github.com/multica-ai/multica/server/pkg/protocol"
@@ -141,6 +142,13 @@ func (h *Handler) CreateInvitation(w http.ResponseWriter, r *http.Request) {
}
h.publish(protocol.EventInvitationCreated, workspaceID, "member", userID, eventPayload)
+ h.Analytics.Capture(analytics.TeamInviteSent(
+ uuidToString(requester.UserID),
+ workspaceID,
+ email,
+ "email",
+ ))
+
// Send invitation email (fire-and-forget).
if h.EmailService != nil && workspaceName != "" {
inviterName := email // fallback
@@ -409,6 +417,19 @@ func (h *Handler) AcceptInvitation(w http.ResponseWriter, r *http.Request) {
"member": memberResp,
})
+ // days_since_invite rounds down to whole days so the funnel segments
+ // "accepted same day" cleanly from "accepted later". inv.CreatedAt is
+ // the invitation row's insertion time so this is safe to compute here.
+ var daysSinceInvite int64
+ if inv.CreatedAt.Valid {
+ daysSinceInvite = int64(time.Since(inv.CreatedAt.Time).Hours() / 24)
+ }
+ h.Analytics.Capture(analytics.TeamInviteAccepted(
+ userID,
+ wsID,
+ daysSinceInvite,
+ ))
+
writeJSON(w, http.StatusOK, memberResp)
}
diff --git a/server/internal/handler/workspace.go b/server/internal/handler/workspace.go
index 9ec9bd4b03..2e945c17fc 100644
--- a/server/internal/handler/workspace.go
+++ b/server/internal/handler/workspace.go
@@ -9,6 +9,7 @@ import (
"github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/analytics"
"github.com/multica-ai/multica/server/internal/logger"
db "github.com/multica-ai/multica/server/pkg/db/generated"
"github.com/multica-ai/multica/server/pkg/protocol"
@@ -201,6 +202,12 @@ func (h *Handler) CreateWorkspace(w http.ResponseWriter, r *http.Request) {
return
}
+ // "Is this the user's first workspace?" is derived in PostHog by looking
+ // at whether they have a prior workspace_created event, not stamped at
+ // emit time. Stamping here would race under concurrent creates without
+ // a schema change, and the event stream answers the question exactly.
+ h.Analytics.Capture(analytics.WorkspaceCreated(userID, uuidToString(ws.ID)))
+
slog.Info("workspace created", append(logger.RequestAttrs(r), "workspace_id", uuidToString(ws.ID), "name", ws.Name, "slug", ws.Slug)...)
writeJSON(w, http.StatusCreated, workspaceToResponse(ws))
}
diff --git a/server/migrations/050_issue_first_executed_at.down.sql b/server/migrations/050_issue_first_executed_at.down.sql
new file mode 100644
index 0000000000..f72d964075
--- /dev/null
+++ b/server/migrations/050_issue_first_executed_at.down.sql
@@ -0,0 +1,2 @@
+DROP INDEX IF EXISTS idx_issue_first_executed_at;
+ALTER TABLE issue DROP COLUMN IF EXISTS first_executed_at;
diff --git a/server/migrations/050_issue_first_executed_at.up.sql b/server/migrations/050_issue_first_executed_at.up.sql
new file mode 100644
index 0000000000..6511e707e3
--- /dev/null
+++ b/server/migrations/050_issue_first_executed_at.up.sql
@@ -0,0 +1,15 @@
+-- first_executed_at is stamped atomically the first time an issue's task
+-- reaches a terminal `done` state. Analytics reads this as the single
+-- source of truth for the issue_executed funnel event — atomic UPDATE …
+-- WHERE first_executed_at IS NULL guarantees at-most-one emission per
+-- issue regardless of retries, re-assignments, or comment-triggered
+-- follow-up tasks.
+ALTER TABLE issue
+ ADD COLUMN first_executed_at TIMESTAMPTZ NULL;
+
+-- A partial index on the NULL-until-set column lets the workspace-scoped
+-- "how many issues executed so far?" count (nth_issue_for_workspace)
+-- skip the large tail of never-executed issues.
+CREATE INDEX IF NOT EXISTS idx_issue_first_executed_at
+ ON issue (workspace_id, first_executed_at)
+ WHERE first_executed_at IS NOT NULL;
diff --git a/server/pkg/db/generated/issue.sql.go b/server/pkg/db/generated/issue.sql.go
index 891ca158a1..d33dc7eb41 100644
--- a/server/pkg/db/generated/issue.sql.go
+++ b/server/pkg/db/generated/issue.sql.go
@@ -136,7 +136,7 @@ INSERT INTO issue (
parent_issue_id, position, due_date, number, project_id
) VALUES (
$1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14
-) RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id
+) RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at
`
type CreateIssueParams struct {
@@ -196,6 +196,7 @@ func (q *Queries) CreateIssue(ctx context.Context, arg CreateIssueParams) (Issue
&i.ProjectID,
&i.OriginType,
&i.OriginID,
+ &i.FirstExecutedAt,
)
return i, err
}
@@ -209,7 +210,7 @@ INSERT INTO issue (
) VALUES (
$1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14,
$15, $16
-) RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id
+) RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at
`
type CreateIssueWithOriginParams struct {
@@ -273,6 +274,7 @@ func (q *Queries) CreateIssueWithOrigin(ctx context.Context, arg CreateIssueWith
&i.ProjectID,
&i.OriginType,
&i.OriginID,
+ &i.FirstExecutedAt,
)
return i, err
}
@@ -287,7 +289,7 @@ func (q *Queries) DeleteIssue(ctx context.Context, id pgtype.UUID) error {
}
const getIssue = `-- name: GetIssue :one
-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id FROM issue
+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at FROM issue
WHERE id = $1
`
@@ -316,12 +318,13 @@ func (q *Queries) GetIssue(ctx context.Context, id pgtype.UUID) (Issue, error) {
&i.ProjectID,
&i.OriginType,
&i.OriginID,
+ &i.FirstExecutedAt,
)
return i, err
}
const getIssueByNumber = `-- name: GetIssueByNumber :one
-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id FROM issue
+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at FROM issue
WHERE workspace_id = $1 AND number = $2
`
@@ -355,12 +358,13 @@ func (q *Queries) GetIssueByNumber(ctx context.Context, arg GetIssueByNumberPara
&i.ProjectID,
&i.OriginType,
&i.OriginID,
+ &i.FirstExecutedAt,
)
return i, err
}
const getIssueInWorkspace = `-- name: GetIssueInWorkspace :one
-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id FROM issue
+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at FROM issue
WHERE id = $1 AND workspace_id = $2
`
@@ -394,12 +398,13 @@ func (q *Queries) GetIssueInWorkspace(ctx context.Context, arg GetIssueInWorkspa
&i.ProjectID,
&i.OriginType,
&i.OriginID,
+ &i.FirstExecutedAt,
)
return i, err
}
const listChildIssues = `-- name: ListChildIssues :many
-SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id FROM issue
+SELECT id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at FROM issue
WHERE parent_issue_id = $1
ORDER BY position ASC, created_at DESC
`
@@ -435,6 +440,7 @@ func (q *Queries) ListChildIssues(ctx context.Context, parentIssueID pgtype.UUID
&i.ProjectID,
&i.OriginType,
&i.OriginID,
+ &i.FirstExecutedAt,
); err != nil {
return nil, err
}
@@ -631,6 +637,40 @@ func (q *Queries) ListOpenIssues(ctx context.Context, arg ListOpenIssuesParams)
return items, nil
}
+const markIssueFirstExecuted = `-- name: MarkIssueFirstExecuted :one
+
+UPDATE issue
+SET first_executed_at = now()
+WHERE id = $1 AND first_executed_at IS NULL
+RETURNING id, workspace_id, creator_type, creator_id, first_executed_at
+`
+
+type MarkIssueFirstExecutedRow struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ CreatorType string `json:"creator_type"`
+ CreatorID pgtype.UUID `json:"creator_id"`
+ FirstExecutedAt pgtype.Timestamptz `json:"first_executed_at"`
+}
+
+// SearchIssues: moved to handler (dynamic SQL for multi-word search support).
+// Flips first_executed_at from NULL to now() atomically. Returns the row if
+// this was the first time the issue was executed; no rows otherwise. The
+// analytics issue_executed event fires exactly when this returns a row —
+// retries and re-assignments hit the WHERE clause and no-op.
+func (q *Queries) MarkIssueFirstExecuted(ctx context.Context, id pgtype.UUID) (MarkIssueFirstExecutedRow, error) {
+ row := q.db.QueryRow(ctx, markIssueFirstExecuted, id)
+ var i MarkIssueFirstExecutedRow
+ err := row.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.CreatorType,
+ &i.CreatorID,
+ &i.FirstExecutedAt,
+ )
+ return i, err
+}
+
const updateIssue = `-- name: UpdateIssue :one
UPDATE issue SET
title = COALESCE($2, title),
@@ -645,7 +685,7 @@ UPDATE issue SET
project_id = $11,
updated_at = now()
WHERE id = $1
-RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id
+RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at
`
type UpdateIssueParams struct {
@@ -699,6 +739,7 @@ func (q *Queries) UpdateIssue(ctx context.Context, arg UpdateIssueParams) (Issue
&i.ProjectID,
&i.OriginType,
&i.OriginID,
+ &i.FirstExecutedAt,
)
return i, err
}
@@ -708,7 +749,7 @@ UPDATE issue SET
status = $2,
updated_at = now()
WHERE id = $1
-RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id
+RETURNING id, workspace_id, title, description, status, priority, assignee_type, assignee_id, creator_type, creator_id, parent_issue_id, acceptance_criteria, context_refs, position, due_date, created_at, updated_at, number, project_id, origin_type, origin_id, first_executed_at
`
type UpdateIssueStatusParams struct {
@@ -741,6 +782,7 @@ func (q *Queries) UpdateIssueStatus(ctx context.Context, arg UpdateIssueStatusPa
&i.ProjectID,
&i.OriginType,
&i.OriginID,
+ &i.FirstExecutedAt,
)
return i, err
}
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index d82a5366ea..f8eb8a9577 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -256,6 +256,7 @@ type Issue struct {
ProjectID pgtype.UUID `json:"project_id"`
OriginType pgtype.Text `json:"origin_type"`
OriginID pgtype.UUID `json:"origin_id"`
+ FirstExecutedAt pgtype.Timestamptz `json:"first_executed_at"`
}
type IssueDependency struct {
diff --git a/server/pkg/db/generated/runtime.sql.go b/server/pkg/db/generated/runtime.sql.go
index f55cea58b9..813153f2aa 100644
--- a/server/pkg/db/generated/runtime.sql.go
+++ b/server/pkg/db/generated/runtime.sql.go
@@ -481,7 +481,7 @@ DO UPDATE SET
owner_id = COALESCE(EXCLUDED.owner_id, agent_runtime.owner_id),
last_seen_at = now(),
updated_at = now()
-RETURNING id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id
+RETURNING id, workspace_id, daemon_id, name, runtime_mode, provider, status, device_info, metadata, last_seen_at, created_at, updated_at, owner_id, legacy_daemon_id, (xmax = 0) AS inserted
`
type UpsertAgentRuntimeParams struct {
@@ -496,7 +496,28 @@ type UpsertAgentRuntimeParams struct {
OwnerID pgtype.UUID `json:"owner_id"`
}
-func (q *Queries) UpsertAgentRuntime(ctx context.Context, arg UpsertAgentRuntimeParams) (AgentRuntime, error) {
+type UpsertAgentRuntimeRow struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ DaemonID pgtype.Text `json:"daemon_id"`
+ Name string `json:"name"`
+ RuntimeMode string `json:"runtime_mode"`
+ Provider string `json:"provider"`
+ Status string `json:"status"`
+ DeviceInfo string `json:"device_info"`
+ Metadata []byte `json:"metadata"`
+ LastSeenAt pgtype.Timestamptz `json:"last_seen_at"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+ OwnerID pgtype.UUID `json:"owner_id"`
+ LegacyDaemonID pgtype.Text `json:"legacy_daemon_id"`
+ Inserted bool `json:"inserted"`
+}
+
+// (xmax = 0) AS inserted distinguishes a fresh insert (true) from an upsert
+// that updated an existing row (false). Analytics reads this to fire the
+// runtime_registered event only on first-time registration.
+func (q *Queries) UpsertAgentRuntime(ctx context.Context, arg UpsertAgentRuntimeParams) (UpsertAgentRuntimeRow, error) {
row := q.db.QueryRow(ctx, upsertAgentRuntime,
arg.WorkspaceID,
arg.DaemonID,
@@ -508,7 +529,7 @@ func (q *Queries) UpsertAgentRuntime(ctx context.Context, arg UpsertAgentRuntime
arg.Metadata,
arg.OwnerID,
)
- var i AgentRuntime
+ var i UpsertAgentRuntimeRow
err := row.Scan(
&i.ID,
&i.WorkspaceID,
@@ -524,6 +545,7 @@ func (q *Queries) UpsertAgentRuntime(ctx context.Context, arg UpsertAgentRuntime
&i.UpdatedAt,
&i.OwnerID,
&i.LegacyDaemonID,
+ &i.Inserted,
)
return i, err
}
diff --git a/server/pkg/db/queries/issue.sql b/server/pkg/db/queries/issue.sql
index 8125e8b770..617e7fab84 100644
--- a/server/pkg/db/queries/issue.sql
+++ b/server/pkg/db/queries/issue.sql
@@ -124,3 +124,13 @@ WHERE workspace_id = $1
GROUP BY parent_issue_id;
-- SearchIssues: moved to handler (dynamic SQL for multi-word search support).
+
+-- name: MarkIssueFirstExecuted :one
+-- Flips first_executed_at from NULL to now() atomically. Returns the row if
+-- this was the first time the issue was executed; no rows otherwise. The
+-- analytics issue_executed event fires exactly when this returns a row —
+-- retries and re-assignments hit the WHERE clause and no-op.
+UPDATE issue
+SET first_executed_at = now()
+WHERE id = $1 AND first_executed_at IS NULL
+RETURNING id, workspace_id, creator_type, creator_id, first_executed_at;
diff --git a/server/pkg/db/queries/runtime.sql b/server/pkg/db/queries/runtime.sql
index 0f74ee800e..adc1f01960 100644
--- a/server/pkg/db/queries/runtime.sql
+++ b/server/pkg/db/queries/runtime.sql
@@ -12,6 +12,9 @@ SELECT * FROM agent_runtime
WHERE id = $1 AND workspace_id = $2;
-- name: UpsertAgentRuntime :one
+-- (xmax = 0) AS inserted distinguishes a fresh insert (true) from an upsert
+-- that updated an existing row (false). Analytics reads this to fire the
+-- runtime_registered event only on first-time registration.
INSERT INTO agent_runtime (
workspace_id,
daemon_id,
@@ -34,7 +37,7 @@ DO UPDATE SET
owner_id = COALESCE(EXCLUDED.owner_id, agent_runtime.owner_id),
last_seen_at = now(),
updated_at = now()
-RETURNING *;
+RETURNING *, (xmax = 0) AS inserted;
-- name: UpdateAgentRuntimeHeartbeat :one
UPDATE agent_runtime