Skip to content

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

Go

Add canonical PostHog core metrics events (#2302)

Multica Evece00e05169ac
diff --git a/.env.example b/.env.example
index 43737630de..7c296f2ffc 100644
--- a/.env.example
+++ b/.env.example
@@ -132,5 +132,8 @@ ALLOWED_EMAILS=
# will run a no-op analytics client and ship nothing. See docs/analytics.md.
POSTHOG_API_KEY=
POSTHOG_HOST=https://us.i.posthog.com
+# Optional override for the `environment` PostHog event property.
+# Defaults from APP_ENV and normalizes to production / staging / dev.
+ANALYTICS_ENVIRONMENT=
# Force the no-op client even when POSTHOG_API_KEY is set (CI / opt-out).
ANALYTICS_DISABLED=
diff --git a/docs/analytics.md b/docs/analytics.md
index 05119de74f..91b98a4cb3 100644
--- a/docs/analytics.md
+++ b/docs/analytics.md
@@ -14,6 +14,7 @@ All analytics shipping is toggled by environment variables (see `.env.example`):
|---|---|---|
| `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_ENVIRONMENT` | Optional override for the standard `environment` event property. Normalized to `production`, `staging`, or `dev`; defaults from `APP_ENV`. | `APP_ENV` / `dev` |
| `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
@@ -82,6 +83,50 @@ handler → analytics.Client.Capture(Event) ← non-blocking, returns immediat
`$set_once` only for values that must never be overwritten (email,
initial attribution, first-completion timestamp).
+## Taxonomy
+
+Every event is assigned to one dashboard category:
+
+| Category | Events |
+|---|---|
+| `core_loop` | `workspace_created`, `runtime_registered`, `runtime_ready`, `runtime_failed`, `runtime_offline`, `agent_created`, `issue_created`, `chat_message_sent`, `agent_task_queued`, `agent_task_started`, `agent_task_completed`, `agent_task_failed`, `agent_task_cancelled`, `autopilot_run_started`, `autopilot_run_completed`, `autopilot_run_failed` |
+| `onboarding_support` | `onboarding_started`, `onboarding_questionnaire_submitted`, `onboarding_completed`, `onboarding_runtime_path_selected`, `onboarding_runtime_detected`, `starter_content_decided` |
+| `acquisition` | `signup`, `download_intent_expressed`, `download_page_viewed`, `download_initiated`, `cloud_waitlist_joined` |
+| `ops_feedback` | `feedback_opened`, `feedback_submitted` |
+| `system/noise` | `$pageview`, `$set`, `$identify`, `$autocapture`, `$rageclick` |
+
+The v0 core dashboard must use only `core_loop` plus the specific
+`onboarding_support` steps used by the activation funnel. Acquisition,
+feedback, and system/noise events stay in separate dashboards.
+
+## Standard core properties
+
+Canonical core events should carry these properties whenever the entity exists:
+
+| Property | Type | Notes |
+|---|---|---|
+| `environment` | string | `production` / `staging` / `dev`; stamped by backend and frontend analytics clients. |
+| `event_schema_version` | int | Current version: `2`. |
+| `user_id` | string UUID | Human user ID when known. Agent/system events may omit it. |
+| `workspace_id` | string UUID | Required for workspace-scoped events. |
+| `agent_id` | string UUID | Required for agent/task events. |
+| `task_id` | string UUID | Required for `agent_task_*` events. |
+| `issue_id` / `chat_session_id` / `autopilot_run_id` | string UUID | Relevant source entity for the task/entry event. |
+| `source` | string | Canonical values: `onboarding`, `manual`, `chat`, `autopilot`, `api`. UI surface details use `surface` or `trigger_source`. |
+| `runtime_mode` | string | `cloud` / `local` when a runtime/agent task is involved. |
+| `provider` | string | `claude`, `codex`, `cursor`, etc. when a runtime/agent task is involved. |
+| `is_demo` | bool | Currently always `false`; reserved for future demo/test workspace filtering. |
+
+Task terminal events additionally carry `duration_ms`; failures carry
+`failure_reason`, `error_type`, and `will_retry`. Runtime failure events carry
+`recoverable`; runtime ready events carry `runtime_id`, `ready_duration_ms`
+only when it is actually measured, and `daemon_id` for local runtimes.
+
+Schema v2 is the first canonical core-metrics schema. It replaces early v1
+drafts that mirrored `failure_reason` into `error_type`, used `recoverable`
+for task/autopilot failures, and emitted `ready_duration_ms: 0` before the
+registration path had a measured duration.
+
## Event contract
### `signup`
@@ -128,6 +173,8 @@ extra query, no race.
| Property | Type | Description |
|---|---|---|
| `runtime_id` | string (UUID) | The newly created agent_runtime row id. |
+| `daemon_id` | string | Local daemon identity when available. |
+| `runtime_mode` | string | Currently `local`; reserved for cloud runtimes. |
| `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. |
@@ -137,6 +184,114 @@ 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.
+### `runtime_ready`
+
+Fires when a runtime is first registered in an online/ready state. This is the
+activation-funnel step that should replace treating `runtime_registered` as
+proof of readiness. The backend emits this only on the INSERT path for a new
+`agent_runtime` row; ordinary daemon reconnects update the existing row and do
+not emit another `runtime_ready`. Dashboard funnels should still count
+distinct `runtime_id`.
+
+| Property | Type | Description |
+|---|---|---|
+| `runtime_id` | string (UUID) | The `agent_runtime` row id. |
+| `daemon_id` | string | Local daemon identity when available. |
+| `ready_duration_ms` | int64 | Optional. Time from registration start to ready; omitted until the registration path can measure it. |
+| `runtime_mode` | string | `local` / `cloud`. |
+| `provider` | string | Runtime provider. |
+
+### `runtime_failed`
+
+Fires when runtime setup/registration fails before a ready runtime can be
+recorded. Today this is scoped to backend registration persistence failures;
+future setup flows should reuse it for provider detection or daemon boot
+failures.
+
+| Property | Type | Description |
+|---|---|---|
+| `daemon_id` | string | Local daemon identity when available. |
+| `provider` | string | Runtime provider attempted. |
+| `failure_reason` | string | Stable coarse reason. |
+| `error_type` | string | Stable error classifier. |
+| `recoverable` | bool | Whether retrying setup may succeed. |
+
+### `runtime_offline`
+
+Fires when a runtime is explicitly deregistered or the backend sweeper marks it
+offline after missed heartbeats. This is not an activation step; it supports
+local runtime retention and drop-off diagnosis.
+
+### `issue_created`
+
+Fires after an issue row is created, including manual UI/API issue creation,
+quick-create issue creation by an agent, and autopilot `create_issue` runs.
+
+| Property | Type | Description |
+|---|---|---|
+| `issue_id` | string (UUID) | Created issue. |
+| `agent_id` | string (UUID) | Agent assignee or creating agent when applicable. |
+| `task_id` | string (UUID) | Present for quick-create issue creation. |
+| `autopilot_run_id` | string (UUID) | Present for autopilot-created issues. |
+| `source` | string | `manual`, `api`, or `autopilot`. |
+
+### `chat_message_sent`
+
+Fires after a user chat message is persisted and the corresponding agent task
+is queued.
+
+| Property | Type | Description |
+|---|---|---|
+| `chat_session_id` | string (UUID) | Chat session. |
+| `task_id` | string (UUID) | Queued agent task. |
+| `agent_id` | string (UUID) | Chat agent. |
+| `source` | string | Always `chat`. |
+
+### `agent_task_queued` / `agent_task_started` / `agent_task_completed`
+
+Canonical task lifecycle events emitted from `agent_task_queue` state
+transitions. These replace `issue_executed` for core loop success metrics.
+
+| Property | Type | Description |
+|---|---|---|
+| `task_id` | string (UUID) | `agent_task_queue.id`; required. |
+| `agent_id` | string (UUID) | Owning agent. |
+| `issue_id` | string (UUID) | Present for issue-linked tasks. |
+| `chat_session_id` | string (UUID) | Present for chat tasks. |
+| `autopilot_run_id` | string (UUID) | Present for run-only autopilot tasks. |
+| `source` | string | `manual`, `chat`, or `autopilot`. |
+| `runtime_mode` | string | `local` / `cloud`. |
+| `provider` | string | Runtime provider. |
+| `duration_ms` | int64 | Terminal events only; measured from `started_at` when available. |
+
+### `agent_task_failed` / `agent_task_cancelled`
+
+Terminal task lifecycle events. They use the same join fields as
+`agent_task_completed`. `agent_task_failed` also carries:
+
+| Property | Type | Description |
+|---|---|---|
+| `failure_reason` | string | Stable reason from `agent_task_queue.failure_reason`, default `agent_error`. |
+| `error_type` | string | Stable coarse classifier, e.g. `runtime`, `timeout`, `agent_output`, `cancelled`, `agent_error`. |
+| `will_retry` | bool | Whether the backend auto-retry policy will create another task attempt. |
+
+### `autopilot_run_started` / `autopilot_run_completed` / `autopilot_run_failed`
+
+Fires from `autopilot_run` lifecycle changes. `source` is always
+`autopilot`; the trigger origin is carried in `trigger_source` (`manual`,
+`schedule`, `webhook`, or `api`).
+
+| Property | Type | Description |
+|---|---|---|
+| `autopilot_id` | string (UUID) | Autopilot definition. |
+| `autopilot_run_id` | string (UUID) | Run row. |
+| `agent_id` | string (UUID) | Assigned agent. |
+| `trigger_source` | string | `manual`, `schedule`, `webhook`, or `api`. |
+| `duration_ms` | int64 | Terminal events only. |
+| `failure_reason` | string | Failed events only. |
+| `error_type` | string | Failed events only; stable coarse classifier such as `configuration`, `issue_terminal`, `dispatch_error`, `task_error`, or `autopilot_error`. |
+| `will_retry` | bool | Failed events only; currently `false` because autopilot retry cadence is owned by triggers/schedules. |
+
### `issue_executed`
Fires **at most once per issue** — when the first task on that issue
@@ -149,6 +304,11 @@ distinct issues, not tasks.
| Property | Type | Description |
|---|---|---|
| `issue_id` | string (UUID) | |
+| `task_id` | string (UUID) | Completing task. |
+| `agent_id` | string (UUID) | Completing agent. |
+| `source` | string | `manual`, `chat`, or `autopilot`. |
+| `runtime_mode` | string | `local` / `cloud`. |
+| `provider` | string | Runtime provider. |
| `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
@@ -165,6 +325,10 @@ emit `n=1`. PostHog answers the same question at query time via
and funnel steps of the form "workspace has had ≥2 `issue_executed`
events" are expressible without the property. No information is lost.
+Compatibility: `issue_executed` remains a historical compatibility event for
+old dashboards. New core-loop success dashboards should use
+`agent_task_completed` and filter by `source`/`issue_id` as needed.
+
### `team_invite_sent`
Fires from `CreateInvitation` after the DB row is written.
@@ -188,6 +352,17 @@ accepted and the member row is inserted in the same transaction.
`distinct_id` is the invitee's user id — this is the event that closes the
expansion funnel.
+### `onboarding_started`
+
+Fires once when the onboarding shell mounts and the initial workspace list has
+resolved. Existing-workspace users carry `workspace_id`; brand-new users do
+not have a workspace yet.
+
+| Property | Type | Description |
+|---|---|---|
+| `workspace_id` | string (UUID) | Present only when the user already has a workspace. |
+| `source` | string | Always `onboarding`. |
+
### `onboarding_questionnaire_submitted`
Fires on the first PatchOnboarding that transitions the user's
@@ -226,6 +401,7 @@ isolates the Step 4 signal from later agent additions.
|---|---|---|
| `agent_id` | string (UUID) | |
| `provider` | string | Runtime provider the agent is bound to (`claude`, `codex`, etc). |
+| `runtime_mode` | string | Runtime mode copied from the bound runtime. |
| `template` | string | Template slug used to seed the agent (`coding` / `planning` / `writing` / `assistant`). Empty when the caller didn't come from a template picker. |
| `is_first_agent_in_workspace` | bool | `true` when the workspace had zero agents before this insert. |
@@ -241,7 +417,8 @@ which exit the user took.
| Property | Type | Description |
|---|---|---|
-| `completion_path` | string | One of `full` / `runtime_skipped` / `cloud_waitlist` / `skip_existing` / `unknown`. See below. |
+| `workspace_id` | string (UUID) | Present for workspace-linked onboarding completions. |
+| `completion_path` | string | One of `full` / `runtime_skipped` / `cloud_waitlist` / `skip_existing` / `invite_accept` / `unknown`. See below. |
| `joined_cloud_waitlist` | bool | Derived from `user.cloud_waitlist_email`. Orthogonal to `completion_path` — a user may submit the waitlist form and still pick CLI. |
Person properties set with `$set_once`:
@@ -256,6 +433,7 @@ Person properties set with `$set_once`:
- `runtime_skipped` — Completed without connecting a runtime (user hit Skip in Step 3).
- `cloud_waitlist` — Submitted the cloud waitlist form and skipped Step 3.
- `skip_existing` — "I've done this before" from Welcome. The user already had a workspace.
+- `invite_accept` — Accepted at least one workspace invitation.
- `unknown` — Legacy fallback when the client didn't send a path. Should stay near zero after rollout.
### `cloud_waitlist_joined`
@@ -314,11 +492,11 @@ request payload.
`packages/views/onboarding/steps/step-platform-fork.tsx` when the web
user clicks one of the three Step 3 fork cards (before any server
call happens, so it's frontend-only). Properties: `path`
- (`download_desktop` / `cli` / `cloud_waitlist`), `source` (`step3`;
- literal today but reserved for future surfaces reusing this event),
- `is_mac`. Also writes `platform_preference` (`web` / `desktop`) to
- person properties so every subsequent event on the user can be
- broken down by chosen platform. **Note**: semantic "download
+ (`download_desktop` / `cli` / `cloud_waitlist`), `source`
+ (`onboarding`), `surface` (`step3`), `workspace_id`, and `is_mac`.
+ Also writes `platform_preference` (`web` / `desktop`) to person
+ properties so every subsequent event on the user can be broken down
+ by chosen platform. **Note**: semantic "download
intent" is now better served by `download_intent_expressed` below —
`path: "download_desktop"` signals Step 3 path choice specifically,
not actual download start.
@@ -334,8 +512,9 @@ request payload.
`runtime_registered` is silent on that cohort. Splits
`completion_path=runtime_skipped` into "had CLIs, skipped anyway"
vs "no CLIs available, had no choice". Properties:
- - `source`: `step3_desktop` (literal; reserved for a future web
- emission under a different value).
+ - `source`: `onboarding`.
+ - `surface`: `step3_desktop`.
+ - `workspace_id`: current onboarding workspace.
- `outcome`: `found` (at least one runtime registered before the
5 s grace window expired) or `empty` (none registered by then).
- `runtime_count`: number of runtimes visible to this user at
@@ -419,6 +598,38 @@ request payload.
`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.
+## Reconciliation
+
+`agent_task_completed` is the canonical PostHog-side task success event. It
+should reconcile daily against the operational source of truth:
+
+```sql
+SELECT date_trunc('day', completed_at AT TIME ZONE 'UTC') AS day,
+ count(*) AS db_completed_tasks
+FROM agent_task_queue
+WHERE status = 'completed'
+ AND completed_at >= now() - interval '30 days'
+GROUP BY 1
+ORDER BY 1;
+```
+
+Equivalent HogQL:
+
+```sql
+SELECT toStartOfDay(timestamp) AS day,
+ count() AS posthog_completed_tasks
+FROM events
+WHERE event = 'agent_task_completed'
+ AND properties.environment = 'production'
+ AND timestamp >= now() - interval 30 day
+GROUP BY day
+ORDER BY day
+```
+
+The expected difference should be near zero. Allow a small delay window for
+PostHog ingestion and backend analytics queue drops; sustained drift means
+either an emission site is missing or PostHog shipping is unhealthy.
+
## Governance
Before adding, renaming, or removing any event:
diff --git a/packages/core/analytics/index.test.ts b/packages/core/analytics/index.test.ts
index 90ffe3ae36..d68d5995ac 100644
--- a/packages/core/analytics/index.test.ts
+++ b/packages/core/analytics/index.test.ts
@@ -45,20 +45,33 @@ describe("initAnalytics super-properties", () => {
expect(posthog.register).toHaveBeenCalledWith({
client_type: "web",
app_version: "1.2.3",
+ environment: "dev",
+ event_schema_version: 2,
+ is_demo: false,
});
});
it("omits app_version when not provided", async () => {
const { analytics, posthog } = await loadModule();
analytics.initAnalytics({ key: "k", host: "" });
- expect(posthog.register).toHaveBeenCalledWith({ client_type: "web" });
+ expect(posthog.register).toHaveBeenCalledWith({
+ client_type: "web",
+ environment: "dev",
+ event_schema_version: 2,
+ is_demo: false,
+ });
});
it("detects desktop when window.electron is present", async () => {
vi.stubGlobal("window", { electron: {} });
const { analytics, posthog } = await loadModule();
analytics.initAnalytics({ key: "k", host: "" });
- expect(posthog.register).toHaveBeenCalledWith({ client_type: "desktop" });
+ expect(posthog.register).toHaveBeenCalledWith({
+ client_type: "desktop",
+ environment: "dev",
+ event_schema_version: 2,
+ is_demo: false,
+ });
});
});
@@ -76,6 +89,9 @@ describe("resetAnalytics", () => {
expect(posthog.register).toHaveBeenCalledWith({
client_type: "web",
app_version: "1.2.3",
+ environment: "dev",
+ event_schema_version: 2,
+ is_demo: false,
});
});
diff --git a/packages/core/analytics/index.ts b/packages/core/analytics/index.ts
index 4438a77edc..ed7c76978e 100644
--- a/packages/core/analytics/index.ts
+++ b/packages/core/analytics/index.ts
@@ -14,6 +14,8 @@
import posthog from "posthog-js";
+export const EVENT_SCHEMA_VERSION = 2;
+
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
@@ -34,6 +36,8 @@ let initialized = false;
// 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;
+let currentUserId: string | null = null;
+let analyticsEnvironment = "dev";
// 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
@@ -78,6 +82,7 @@ export interface AnalyticsConfig {
* available.
*/
appVersion?: string;
+ environment?: string;
}
export type ClientType = "desktop" | "web";
@@ -135,6 +140,7 @@ export function initAnalytics(config: AnalyticsConfig | null | undefined): boole
disable_session_recording: true,
disable_surveys: true,
});
+ analyticsEnvironment = normalizeEnvironment(config.environment);
// Register super-properties — attached to every event emitted from this
// client. `client_type` is the canonical split between desktop and web
// (PostHog's own `$lib` reports "web" for both because Electron renderers
@@ -142,13 +148,19 @@ export function initAnalytics(config: AnalyticsConfig | null | undefined): boole
// builds without a version don't pollute the property.
// We cache the set so resetAnalytics() can re-apply it after
// posthog.reset() — reset() clears persisted super-properties otherwise.
- superProperties = { client_type: detectClientType() };
+ superProperties = {
+ client_type: detectClientType(),
+ event_schema_version: EVENT_SCHEMA_VERSION,
+ environment: analyticsEnvironment,
+ is_demo: false,
+ };
if (config.appVersion) superProperties.app_version = config.appVersion;
posthog.register(superProperties);
initialized = true;
// Flush any identify() that arrived before init resolved.
if (pendingIdentify) {
+ currentUserId = pendingIdentify.userId;
posthog.identify(pendingIdentify.userId, pendingIdentify.props);
pendingIdentify = null;
}
@@ -164,7 +176,7 @@ export function initAnalytics(config: AnalyticsConfig | null | undefined): boole
while (pendingOps.length > 0) {
const op = pendingOps.shift()!;
if (op.kind === "event") {
- posthog.capture(op.name, op.props);
+ posthog.capture(op.name, withClientEventProperties(op.props));
} else {
capturePersonSet(op.props);
}
@@ -182,6 +194,7 @@ export function initAnalytics(config: AnalyticsConfig | null | undefined): boole
* config and user in parallel, so identify can arrive first.
*/
export function identify(userId: string, userProperties?: Record<string, unknown>): void {
+ currentUserId = userId;
if (!initialized) {
pendingIdentify = { userId, props: userProperties };
return;
@@ -194,6 +207,7 @@ export function identify(userId: string, userProperties?: Record<string, unknown
* and doesn't bleed the previous user's events into a new session.
*/
export function resetAnalytics(): void {
+ currentUserId = null;
pendingIdentify = null;
pendingPageview = null;
pendingOps.length = 0;
@@ -225,7 +239,7 @@ export function captureEvent(
pendingOps.push({ kind: "event", name, props });
return;
}
- posthog.capture(name, props);
+ posthog.capture(name, withClientEventProperties(props));
}
/**
@@ -253,6 +267,43 @@ function capturePersonSet(props: Record<string, unknown>): void {
posthog.capture("$set", { $set: props });
}
+function withClientEventProperties(
+ props?: Record<string, unknown>,
+): Record<string, unknown> {
+ const next: Record<string, unknown> = { ...(props ?? {}) };
+ if (currentUserId && next.user_id === undefined) {
+ next.user_id = currentUserId;
+ }
+ if (next.event_schema_version === undefined) {
+ next.event_schema_version = EVENT_SCHEMA_VERSION;
+ }
+ if (next.environment === undefined) {
+ next.environment = analyticsEnvironment;
+ }
+ if (next.is_demo === undefined) {
+ next.is_demo = false;
+ }
+ return next;
+}
+
+function normalizeEnvironment(value: string | undefined): string {
+ switch ((value || "").trim().toLowerCase()) {
+ case "production":
+ case "prod":
+ return "production";
+ case "staging":
+ case "stage":
+ return "staging";
+ case "development":
+ case "dev":
+ case "test":
+ case "local":
+ return "dev";
+ default:
+ return "dev";
+ }
+}
+
/**
* Capture a page view. Call once per client-side navigation. We disable
* posthog's automatic pageview tracking in init() so this module owns the
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index 4e2225d59f..a217c3c738 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -334,6 +334,7 @@ export class ApiClient {
async markOnboardingComplete(payload?: {
completion_path?: OnboardingCompletionPath;
+ workspace_id?: string;
}): Promise<User> {
return this.fetch("/api/me/onboarding/complete", {
method: "POST",
@@ -854,6 +855,7 @@ export class ApiClient {
google_client_id?: string;
posthog_key?: string;
posthog_host?: string;
+ analytics_environment?: string;
}> {
return this.fetch("/api/config");
}
diff --git a/packages/core/onboarding/store.ts b/packages/core/onboarding/store.ts
index a2edb19c9a..9857f14f9d 100644
--- a/packages/core/onboarding/store.ts
+++ b/packages/core/onboarding/store.ts
@@ -42,9 +42,12 @@ export async function saveQuestionnaire(
*/
export async function completeOnboarding(
completionPath?: OnboardingCompletionPath,
+ workspaceId?: string,
): Promise<void> {
await api.markOnboardingComplete(
- completionPath ? { completion_path: completionPath } : undefined,
+ completionPath || workspaceId
+ ? { completion_path: completionPath, workspace_id: workspaceId }
+ : undefined,
);
await useAuthStore.getState().refreshMe();
}
diff --git a/packages/core/platform/auth-initializer.tsx b/packages/core/platform/auth-initializer.tsx
index 79e1168f4f..9fe77ec222 100644
--- a/packages/core/platform/auth-initializer.tsx
+++ b/packages/core/platform/auth-initializer.tsx
@@ -59,6 +59,7 @@ export function AuthInitializer({
key: cfg.posthog_key,
host: cfg.posthog_host || "",
appVersion: identity?.version,
+ environment: cfg.analytics_environment,
});
}
})
diff --git a/packages/views/invitations/invitations-page.test.tsx b/packages/views/invitations/invitations-page.test.tsx
index 18a6dd9425..5a3fa3e50c 100644
--- a/packages/views/invitations/invitations-page.test.tsx
+++ b/packages/views/invitations/invitations-page.test.tsx
@@ -156,6 +156,7 @@ describe("InvitationsPage", () => {
expect(acceptInvitation).toHaveBeenCalledWith("inv-1");
expect(markOnboardingComplete).toHaveBeenCalledWith({
completion_path: "invite_accept",
+ workspace_id: "ws-1",
});
expect(refreshMe).toHaveBeenCalled();
expect(navigate).toHaveBeenCalledWith("/acme/issues");
diff --git a/packages/views/invitations/invitations-page.tsx b/packages/views/invitations/invitations-page.tsx
index 3296339967..59991a9ba9 100644
--- a/packages/views/invitations/invitations-page.tsx
+++ b/packages/views/invitations/invitations-page.tsx
@@ -81,12 +81,19 @@ export function InvitationsPage() {
acceptedIds.push(id);
}
+ const firstAcceptedInvite = invitations?.find(
+ (inv) => inv.id === acceptedIds[0],
+ );
+
// markOnboardingComplete is a frontend-side belt to the backend braces:
// each AcceptInvitation transaction already sets onboarded_at via
// MarkUserOnboarded, but calling this from the client makes sure the
// returned `User` is freshly written and gives refreshMe something
// canonical to read.
- await api.markOnboardingComplete({ completion_path: "invite_accept" });
+ await api.markOnboardingComplete({
+ completion_path: "invite_accept",
+ workspace_id: firstAcceptedInvite?.workspace_id,
+ });
await useAuthStore.getState().refreshMe();
qc.invalidateQueries({ queryKey: workspaceKeys.myInvitations() });
@@ -95,9 +102,6 @@ export function InvitationsPage() {
staleTime: 0,
});
- const firstAcceptedInvite = invitations?.find(
- (inv) => inv.id === acceptedIds[0],
- );
const targetWs = firstAcceptedInvite
? wsList.find((w) => w.id === firstAcceptedInvite.workspace_id)
: undefined;
diff --git a/packages/views/invite/invite-page.tsx b/packages/views/invite/invite-page.tsx
index 4a899faa2c..a46f2e81c8 100644
--- a/packages/views/invite/invite-page.tsx
+++ b/packages/views/invite/invite-page.tsx
@@ -69,7 +69,10 @@ export function InvitePage({ invitationId, onBack }: InvitePageProps) {
// onboarded_at inside the same transaction, but explicitly calling
// markOnboardingComplete + refreshMe here keeps local user state in
// sync immediately so downstream guards don't see stale `null`.
- await api.markOnboardingComplete({ completion_path: "invite_accept" });
+ await api.markOnboardingComplete({
+ completion_path: "invite_accept",
+ workspace_id: invitation?.workspace_id,
+ });
await useAuthStore.getState().refreshMe();
setDone("accepted");
// Fetch the refreshed workspace list so we know the joined workspace's slug.
diff --git a/packages/views/onboarding/onboarding-flow.tsx b/packages/views/onboarding/onboarding-flow.tsx
index 460a79d104..700dd6429b 100644
--- a/packages/views/onboarding/onboarding-flow.tsx
+++ b/packages/views/onboarding/onboarding-flow.tsx
@@ -1,8 +1,9 @@
"use client";
-import { useCallback, useState } from "react";
+import { useCallback, useEffect, useRef, useState } from "react";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { toast } from "sonner";
+import { captureEvent } from "@multica/core/analytics";
import { setCurrentWorkspace } from "@multica/core/platform";
import { useAuthStore } from "@multica/core/auth";
import {
@@ -93,6 +94,15 @@ export function OnboardingFlow({
});
const existingWorkspace = workspace ?? workspaces[0] ?? null;
const canSkipWelcome = workspacesFetched && workspaces.length > 0;
+ const startedEmittedRef = useRef(false);
+ useEffect(() => {
+ if (startedEmittedRef.current || !workspacesFetched) return;
+ startedEmittedRef.current = true;
+ captureEvent("onboarding_started", {
+ source: "onboarding",
+ ...(existingWorkspace ? { workspace_id: existingWorkspace.id } : {}),
+ });
+ }, [existingWorkspace, workspacesFetched]);
// The `runtimeInstructions` slot is only plumbed by the web shell
// (desktop bundles a daemon, so a CLI install card would be noise
@@ -113,7 +123,7 @@ export function OnboardingFlow({
// they never got a starter project and may want one now.
const handleWelcomeSkip = useCallback(async () => {
try {
- await completeOnboarding("skip_existing");
+ await completeOnboarding("skip_existing", workspaces[0]?.id);
} catch (err) {
toast.error(
err instanceof Error ? err.message : t(($) => $.errors.skip_failed),
@@ -279,6 +289,7 @@ export function OnboardingFlow({
<StepFirstIssue
onFinished={handleFinished}
completionPath={completionPath}
+ workspaceId={workspace?.id}
/>
)}
</div>
diff --git a/packages/views/onboarding/steps/step-first-issue.tsx b/packages/views/onboarding/steps/step-first-issue.tsx
index 31d45fd390..d2a2b3d5cb 100644
--- a/packages/views/onboarding/steps/step-first-issue.tsx
+++ b/packages/views/onboarding/steps/step-first-issue.tsx
@@ -30,6 +30,7 @@ import { useT } from "../../i18n";
export function StepFirstIssue({
onFinished,
completionPath,
+ workspaceId,
}: {
/** Called after `onboarded_at` is set server-side. Parent handles
* navigation to the workspace landing page. */
@@ -38,6 +39,7 @@ export function StepFirstIssue({
* Computed in the parent shell where runtime + waitlist state are
* both in scope. */
completionPath: OnboardingCompletionPath;
+ workspaceId?: string;
}) {
const { t } = useT("onboarding");
const [error, setError] = useState<string | null>(null);
@@ -47,13 +49,18 @@ export function StepFirstIssue({
onFinishedRef.current = onFinished;
const completionPathRef = useRef(completionPath);
completionPathRef.current = completionPath;
+ const workspaceIdRef = useRef(workspaceId);
+ workspaceIdRef.current = workspaceId;
useEffect(() => {
if (started.current) return;
started.current = true;
(async () => {
try {
- await completeOnboarding(completionPathRef.current);
+ await completeOnboarding(
+ completionPathRef.current,
+ workspaceIdRef.current,
+ );
onFinishedRef.current();
} catch (err) {
setError(
@@ -68,10 +75,14 @@ export function StepFirstIssue({
setRetrying(true);
setError(null);
try {
- await completeOnboarding(completionPathRef.current);
+ await completeOnboarding(
+ completionPathRef.current,
+ workspaceIdRef.current,
+ );
onFinishedRef.current();
} catch (err) {
- const msg = err instanceof Error ? err.message : t(($) => $.first_issue.retry_failed);
+ const msg =
+ err instanceof Error ? err.message : t(($) => $.first_issue.retry_failed);
setError(msg);
toast.error(msg);
} finally {
diff --git a/packages/views/onboarding/steps/step-platform-fork.tsx b/packages/views/onboarding/steps/step-platform-fork.tsx
index 822793c2db..86141ab544 100644
--- a/packages/views/onboarding/steps/step-platform-fork.tsx
+++ b/packages/views/onboarding/steps/step-platform-fork.tsx
@@ -101,8 +101,10 @@ export function StepPlatformFork({
// `source: "step3"` future-proofs if the event is reused from
// another surface later.
captureEvent("onboarding_runtime_path_selected", {
+ workspace_id: wsId,
path: "download_desktop",
- source: "step3",
+ source: "onboarding",
+ surface: "step3",
is_mac: isMac,
});
// Cross-surface Desktop intent event — also fires from landing
@@ -115,8 +117,10 @@ export function StepPlatformFork({
const handleOpenCli = () => {
setDialog("cli");
captureEvent("onboarding_runtime_path_selected", {
+ workspace_id: wsId,
path: "cli",
- source: "step3",
+ source: "onboarding",
+ surface: "step3",
is_mac: isMac,
});
setPersonProperties({ platform_preference: "web" });
@@ -125,8 +129,10 @@ export function StepPlatformFork({
const handleOpenCloud = () => {
setDialog("cloud");
captureEvent("onboarding_runtime_path_selected", {
+ workspace_id: wsId,
path: "cloud_waitlist",
- source: "step3",
+ source: "onboarding",
+ surface: "step3",
is_mac: isMac,
});
};
diff --git a/packages/views/onboarding/steps/step-runtime-connect.test.tsx b/packages/views/onboarding/steps/step-runtime-connect.test.tsx
index e86d1f2d51..9563e584c1 100644
--- a/packages/views/onboarding/steps/step-runtime-connect.test.tsx
+++ b/packages/views/onboarding/steps/step-runtime-connect.test.tsx
@@ -98,7 +98,9 @@ describe("StepRuntimeConnect — onboarding_runtime_detected", () => {
const [name, props] = mocks.captureEvent.mock.calls[0]!;
expect(name).toBe("onboarding_runtime_detected");
expect(props).toMatchObject({
- source: "step3_desktop",
+ source: "onboarding",
+ surface: "step3_desktop",
+ workspace_id: "ws_test",
outcome: "found",
runtime_count: 1,
online_count: 1,
@@ -154,7 +156,9 @@ describe("StepRuntimeConnect — onboarding_runtime_detected", () => {
expect(mocks.captureEvent).toHaveBeenCalledTimes(1);
const props = mocks.captureEvent.mock.calls[0]![1] as Record<string, unknown>;
expect(props).toMatchObject({
- source: "step3_desktop",
+ source: "onboarding",
+ surface: "step3_desktop",
+ workspace_id: "ws_test",
outcome: "empty",
runtime_count: 0,
online_count: 0,
diff --git a/packages/views/onboarding/steps/step-runtime-connect.tsx b/packages/views/onboarding/steps/step-runtime-connect.tsx
index 68c2b38e96..880d4da8cd 100644
--- a/packages/views/onboarding/steps/step-runtime-connect.tsx
+++ b/packages/views/onboarding/steps/step-runtime-connect.tsx
@@ -58,6 +58,7 @@ export function StepRuntimeConnect({
return (
<FancyView
+ wsId={wsId}
runtimes={runtimes}
selected={selected}
selectedId={selectedId}
@@ -79,6 +80,7 @@ type Phase = "scanning" | "found" | "empty";
const EMPTY_TIMEOUT_MS = 5000;
function FancyView({
+ wsId,
runtimes,
selected,
selectedId,
@@ -87,6 +89,7 @@ function FancyView({
onBack,
onWaitlistSubmitted,
}: {
+ wsId: string;
runtimes: AgentRuntime[];
selected: AgentRuntime | null;
selectedId: string | null;
@@ -142,7 +145,9 @@ function FancyView({
const detectMs = Math.round(now - (detectStartRef.current ?? now));
captureEvent("onboarding_runtime_detected", {
- source: "step3_desktop",
+ source: "onboarding",
+ surface: "step3_desktop",
+ workspace_id: wsId,
outcome: phase,
runtime_count: runtimes.length,
online_count: onlineCount,
@@ -597,4 +602,3 @@ function RadioMark({ selected }: { selected: boolean }) {
</span>
);
}
-
diff --git a/server/cmd/server/main.go b/server/cmd/server/main.go
index 1d9c6b45e9..29d5733bab 100644
--- a/server/cmd/server/main.go
+++ b/server/cmd/server/main.go
@@ -299,6 +299,7 @@ func main() {
sweepCtx, sweepCancel := context.WithCancel(context.Background())
autopilotCtx, autopilotCancel := context.WithCancel(context.Background())
taskSvc := service.NewTaskService(queries, pool, hub, bus, daemonWakeup)
+ taskSvc.Analytics = analyticsClient
autopilotSvc := service.NewAutopilotService(queries, pool, bus, taskSvc)
registerAutopilotListeners(bus, autopilotSvc)
diff --git a/server/cmd/server/rerun_session_test.go b/server/cmd/server/rerun_session_test.go
index 8a8075c2f7..03cd9f1de7 100644
--- a/server/cmd/server/rerun_session_test.go
+++ b/server/cmd/server/rerun_session_test.go
@@ -24,6 +24,7 @@ func setupRerunTestFixture(t *testing.T) (string, string, string) {
JOIN member m ON m.workspace_id = a.workspace_id
JOIN "user" u ON u.id = m.user_id
WHERE u.email = $1
+ AND a.archived_at IS NULL
LIMIT 1
`, integrationTestEmail).Scan(&agentID, &runtimeID); err != nil {
t.Fatalf("failed to find test agent: %v", err)
diff --git a/server/cmd/server/runtime_sweeper.go b/server/cmd/server/runtime_sweeper.go
index 4dd00f5b45..908cfe62da 100644
--- a/server/cmd/server/runtime_sweeper.go
+++ b/server/cmd/server/runtime_sweeper.go
@@ -6,6 +6,7 @@ import (
"time"
"github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/analytics"
"github.com/multica-ai/multica/server/internal/events"
"github.com/multica-ai/multica/server/internal/handler"
"github.com/multica-ai/multica/server/internal/service"
@@ -96,6 +97,17 @@ func sweepStaleRuntimes(ctx context.Context, queries *db.Queries, liveness handl
// SELECT and the UPDATE. Nothing to broadcast.
return
}
+ if taskSvc != nil && taskSvc.Analytics != nil {
+ for _, row := range staleRows {
+ taskSvc.Analytics.Capture(analytics.RuntimeOffline(
+ util.UUIDToString(row.OwnerID),
+ util.UUIDToString(row.WorkspaceID),
+ util.UUIDToString(row.ID),
+ row.DaemonID.String,
+ row.Provider,
+ ))
+ }
+ }
// Collect unique workspace IDs to notify.
workspaces := make(map[string]bool)
diff --git a/server/internal/analytics/client.go b/server/internal/analytics/client.go
index 9dd5c65ede..de0a5dfb15 100644
--- a/server/internal/analytics/client.go
+++ b/server/internal/analytics/client.go
@@ -15,6 +15,7 @@ package analytics
import (
"log/slog"
"os"
+ "strings"
"time"
)
@@ -66,6 +67,7 @@ type Client interface {
//
// - POSTHOG_API_KEY: project API key. Empty → no-op client.
// - POSTHOG_HOST: API host (default https://us.i.posthog.com).
+// - ANALYTICS_ENVIRONMENT: production/staging/dev. Defaults from APP_ENV.
// - 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 {
@@ -83,7 +85,11 @@ func NewFromEnv() Client {
host = "https://us.i.posthog.com"
}
slog.Info("analytics: posthog client enabled", "host", host)
- return NewPostHogClient(PostHogConfig{APIKey: key, Host: host})
+ return NewPostHogClient(PostHogConfig{
+ APIKey: key,
+ Host: host,
+ Environment: EnvironmentFromEnv(),
+ })
}
func isDisabled() bool {
@@ -91,6 +97,29 @@ func isDisabled() bool {
return v == "true" || v == "1"
}
+func EnvironmentFromEnv() string {
+ if v := normalizeEnvironment(os.Getenv("ANALYTICS_ENVIRONMENT")); v != "" {
+ return v
+ }
+ if v := normalizeEnvironment(os.Getenv("APP_ENV")); v != "" {
+ return v
+ }
+ return "dev"
+}
+
+func normalizeEnvironment(v string) string {
+ switch strings.ToLower(strings.TrimSpace(v)) {
+ case "production", "prod":
+ return "production"
+ case "staging", "stage":
+ return "staging"
+ case "development", "dev", "test", "local":
+ return "dev"
+ default:
+ return ""
+ }
+}
+
// 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{}
diff --git a/server/internal/analytics/events.go b/server/internal/analytics/events.go
index 1230155804..c8096f05b8 100644
--- a/server/internal/analytics/events.go
+++ b/server/internal/analytics/events.go
@@ -7,9 +7,23 @@ const (
EventSignup = "signup"
EventWorkspaceCreated = "workspace_created"
EventRuntimeRegistered = "runtime_registered"
+ EventRuntimeReady = "runtime_ready"
+ EventRuntimeFailed = "runtime_failed"
+ EventRuntimeOffline = "runtime_offline"
EventIssueExecuted = "issue_executed"
+ EventIssueCreated = "issue_created"
+ EventChatMessageSent = "chat_message_sent"
+ EventAgentTaskQueued = "agent_task_queued"
+ EventAgentTaskStarted = "agent_task_started"
+ EventAgentTaskCompleted = "agent_task_completed"
+ EventAgentTaskFailed = "agent_task_failed"
+ EventAgentTaskCancelled = "agent_task_cancelled"
+ EventAutopilotRunStarted = "autopilot_run_started"
+ EventAutopilotRunCompleted = "autopilot_run_completed"
+ EventAutopilotRunFailed = "autopilot_run_failed"
EventTeamInviteSent = "team_invite_sent"
EventTeamInviteAccepted = "team_invite_accepted"
+ EventOnboardingStarted = "onboarding_started"
EventOnboardingQuestionnaireSubmit = "onboarding_questionnaire_submitted"
EventAgentCreated = "agent_created"
EventOnboardingCompleted = "onboarding_completed"
@@ -18,6 +32,36 @@ const (
EventFeedbackSubmitted = "feedback_submitted"
)
+const EventSchemaVersion = 2
+
+const (
+ SourceOnboarding = "onboarding"
+ SourceManual = "manual"
+ SourceChat = "chat"
+ SourceAutopilot = "autopilot"
+ SourceAPI = "api"
+)
+
+// CoreProperties are the shared join and segmentation fields used by the
+// canonical PostHog events. Empty values are omitted, except is_demo which is
+// always stamped so dashboards can filter demo data without sparse-property
+// edge cases.
+type CoreProperties struct {
+ UserID string
+ WorkspaceID string
+ AgentID string
+ TaskID string
+ IssueID string
+ ChatSessionID string
+ AutopilotRunID string
+ Source string
+ RuntimeMode string
+ Provider string
+ IsDemo bool
+}
+
+type TaskContext = CoreProperties
+
// Onboarding completion paths. Keep in sync with docs/analytics.md.
const (
OnboardingPathFull = "full" // reached first_issue end of flow
@@ -73,6 +117,11 @@ func WorkspaceCreated(userID, workspaceID string) Event {
Name: EventWorkspaceCreated,
DistinctID: userID,
WorkspaceID: workspaceID,
+ Properties: withCoreProperties(nil, CoreProperties{
+ UserID: userID,
+ WorkspaceID: workspaceID,
+ Source: SourceManual,
+ }),
}
}
@@ -84,7 +133,7 @@ func WorkspaceCreated(userID, workspaceID string) 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 {
+func RuntimeRegistered(ownerID, workspaceID, runtimeID, daemonID, provider, runtimeVersion, cliVersion string) Event {
distinct := ownerID
if distinct == "" {
// A per-workspace synthetic id keeps PostHog from merging unrelated
@@ -97,12 +146,92 @@ func RuntimeRegistered(ownerID, workspaceID, runtimeID, provider, runtimeVersion
Name: EventRuntimeRegistered,
DistinctID: distinct,
WorkspaceID: workspaceID,
- Properties: map[string]any{
+ Properties: withCoreProperties(map[string]any{
"runtime_id": runtimeID,
+ "daemon_id": daemonID,
"provider": provider,
+ "runtime_mode": "local",
"runtime_version": runtimeVersion,
"cli_version": cliVersion,
- },
+ }, CoreProperties{
+ UserID: ownerID,
+ WorkspaceID: workspaceID,
+ Source: SourceManual,
+ RuntimeMode: "local",
+ Provider: provider,
+ }),
+ }
+}
+
+func RuntimeReady(ownerID, workspaceID, runtimeID, daemonID, provider string, readyDurationMS int64) Event {
+ distinct := ownerID
+ if distinct == "" {
+ distinct = "workspace:" + workspaceID
+ }
+ props := map[string]any{
+ "runtime_id": runtimeID,
+ "daemon_id": daemonID,
+ }
+ if readyDurationMS > 0 {
+ props["ready_duration_ms"] = readyDurationMS
+ }
+ return Event{
+ Name: EventRuntimeReady,
+ DistinctID: distinct,
+ WorkspaceID: workspaceID,
+ Properties: withCoreProperties(props, CoreProperties{
+ UserID: ownerID,
+ WorkspaceID: workspaceID,
+ Source: SourceManual,
+ RuntimeMode: "local",
+ Provider: provider,
+ }),
+ }
+}
+
+func RuntimeFailed(ownerID, workspaceID, daemonID, provider, failureReason, errorType string, recoverable bool) Event {
+ distinct := ownerID
+ if distinct == "" && workspaceID != "" {
+ distinct = "workspace:" + workspaceID
+ }
+ return Event{
+ Name: EventRuntimeFailed,
+ DistinctID: distinct,
+ WorkspaceID: workspaceID,
+ Properties: withCoreProperties(map[string]any{
+ "daemon_id": daemonID,
+ "failure_reason": failureReason,
+ "error_type": errorType,
+ "recoverable": recoverable,
+ }, CoreProperties{
+ UserID: ownerID,
+ WorkspaceID: workspaceID,
+ Source: SourceManual,
+ RuntimeMode: "local",
+ Provider: provider,
+ }),
+ }
+}
+
+func RuntimeOffline(ownerID, workspaceID, runtimeID, daemonID, provider string) Event {
+ distinct := ownerID
+ if distinct == "" {
+ distinct = "workspace:" + workspaceID
+ }
+ return Event{
+ Name: EventRuntimeOffline,
+ DistinctID: distinct,
+ WorkspaceID: workspaceID,
+ Properties: withCoreProperties(map[string]any{
+ "runtime_id": runtimeID,
+ "daemon_id": daemonID,
+ }, CoreProperties{
+ UserID: ownerID,
+ WorkspaceID: workspaceID,
+ Source: SourceManual,
+ RuntimeMode: "local",
+ Provider: provider,
+ }),
}
}
@@ -115,18 +244,113 @@ func RuntimeRegistered(ownerID, workspaceID, runtimeID, provider, runtimeVersion
// 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 {
+func IssueExecuted(actorID, workspaceID, issueID, taskID, agentID, source, runtimeMode, provider string, taskDurationMS int64) Event {
return Event{
Name: EventIssueExecuted,
DistinctID: actorID,
WorkspaceID: workspaceID,
- Properties: map[string]any{
+ Properties: withCoreProperties(map[string]any{
"issue_id": issueID,
+ "task_id": taskID,
+ "agent_id": agentID,
"task_duration_ms": taskDurationMS,
- },
+ "duration_ms": taskDurationMS,
+ }, CoreProperties{
+ UserID: nonAgentUserID(actorID),
+ WorkspaceID: workspaceID,
+ AgentID: agentID,
+ TaskID: taskID,
+ IssueID: issueID,
+ Source: source,
+ RuntimeMode: runtimeMode,
+ Provider: provider,
+ }),
}
}
+func IssueCreated(actorID, workspaceID, issueID, agentID, taskID, autopilotRunID, source string) Event {
+ return Event{
+ Name: EventIssueCreated,
+ DistinctID: actorID,
+ WorkspaceID: workspaceID,
+ Properties: withCoreProperties(nil, CoreProperties{
+ UserID: nonAgentUserID(actorID),
+ WorkspaceID: workspaceID,
+ AgentID: agentID,
+ TaskID: taskID,
+ IssueID: issueID,
+ AutopilotRunID: autopilotRunID,
+ Source: source,
+ }),
+ }
+}
+
+func ChatMessageSent(userID, workspaceID, chatSessionID, taskID, agentID, runtimeMode, provider string) Event {
+ return Event{
+ Name: EventChatMessageSent,
+ DistinctID: userID,
+ WorkspaceID: workspaceID,
+ Properties: withCoreProperties(nil, CoreProperties{
+ UserID: userID,
+ WorkspaceID: workspaceID,
+ AgentID: agentID,
+ TaskID: taskID,
+ ChatSessionID: chatSessionID,
+ Source: SourceChat,
+ RuntimeMode: runtimeMode,
+ Provider: provider,
+ }),
+ }
+}
+
+func AgentTaskQueued(ctx TaskContext) Event {
+ return agentTaskEvent(EventAgentTaskQueued, ctx, nil)
+}
+
+func AgentTaskStarted(ctx TaskContext) Event {
+ return agentTaskEvent(EventAgentTaskStarted, ctx, nil)
+}
+
+func AgentTaskCompleted(ctx TaskContext, durationMS int64) Event {
+ return agentTaskEvent(EventAgentTaskCompleted, ctx, map[string]any{
+ "duration_ms": durationMS,
+ })
+}
+
+func AgentTaskFailed(ctx TaskContext, durationMS int64, failureReason, errorType string, willRetry bool) Event {
+ return agentTaskEvent(EventAgentTaskFailed, ctx, map[string]any{
+ "duration_ms": durationMS,
+ "failure_reason": failureReason,
+ "error_type": errorType,
+ "will_retry": willRetry,
+ })
+}
+
+func AgentTaskCancelled(ctx TaskContext, durationMS int64) Event {
+ return agentTaskEvent(EventAgentTaskCancelled, ctx, map[string]any{
+ "duration_ms": durationMS,
+ })
+}
+
+func AutopilotRunStarted(actorID, workspaceID, autopilotID, runID, agentID, triggerSource string) Event {
+ return autopilotRunEvent(EventAutopilotRunStarted, actorID, workspaceID, autopilotID, runID, agentID, triggerSource, nil)
+}
+
+func AutopilotRunCompleted(actorID, workspaceID, autopilotID, runID, agentID, triggerSource string, durationMS int64) Event {
+ return autopilotRunEvent(EventAutopilotRunCompleted, actorID, workspaceID, autopilotID, runID, agentID, triggerSource, map[string]any{
+ "duration_ms": durationMS,
+ })
+}
+
+func AutopilotRunFailed(actorID, workspaceID, autopilotID, runID, agentID, triggerSource, failureReason, errorType string, willRetry bool, durationMS int64) Event {
+ return autopilotRunEvent(EventAutopilotRunFailed, actorID, workspaceID, autopilotID, runID, agentID, triggerSource, map[string]any{
+ "duration_ms": durationMS,
+ "failure_reason": failureReason,
+ "error_type": errorType,
+ "will_retry": willRetry,
+ })
+}
+
// 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.
@@ -173,14 +397,17 @@ func OnboardingQuestionnaireSubmitted(userID, teamSize, role, useCase string, te
return Event{
Name: EventOnboardingQuestionnaireSubmit,
DistinctID: userID,
- Properties: map[string]any{
+ Properties: withCoreProperties(map[string]any{
"team_size": teamSize,
"role": role,
"use_case": useCase,
"team_size_has_other": teamSizeOther,
"role_has_other": roleOther,
"use_case_has_other": useCaseOther,
- },
+ }, CoreProperties{
+ UserID: userID,
+ Source: SourceOnboarding,
+ }),
Set: map[string]any{
"team_size": teamSize,
"role": role,
@@ -196,17 +423,25 @@ func OnboardingQuestionnaireSubmitted(userID, teamSize, role, useCase string, te
// template is the template slug the frontend used to seed the agent
// (e.g. "coding", "planning", "writing", "assistant") — empty when the
// caller didn't come from a template picker.
-func AgentCreated(actorID, workspaceID, agentID, provider, template string, isFirstAgentInWorkspace bool) Event {
+func AgentCreated(actorID, workspaceID, agentID, provider, runtimeMode, template string, isFirstAgentInWorkspace bool) Event {
return Event{
Name: EventAgentCreated,
DistinctID: actorID,
WorkspaceID: workspaceID,
- Properties: map[string]any{
+ Properties: withCoreProperties(map[string]any{
"agent_id": agentID,
"provider": provider,
+ "runtime_mode": runtimeMode,
"template": template,
"is_first_agent_in_workspace": isFirstAgentInWorkspace,
- },
+ }, CoreProperties{
+ UserID: actorID,
+ WorkspaceID: workspaceID,
+ AgentID: agentID,
+ Source: SourceManual,
+ RuntimeMode: runtimeMode,
+ Provider: provider,
+ }),
}
}
@@ -220,14 +455,19 @@ func AgentCreated(actorID, workspaceID, agentID, provider, template string, isFi
// onboardedAt is an RFC3339 timestamp set $set_once on the person so
// "onboarded before date X" cohorts are queryable directly from
// person_properties without re-emitting per-event.
-func OnboardingCompleted(userID, completionPath, onboardedAt string, joinedCloudWaitlist bool) Event {
+func OnboardingCompleted(userID, workspaceID, completionPath, onboardedAt string, joinedCloudWaitlist bool) Event {
return Event{
- Name: EventOnboardingCompleted,
- DistinctID: userID,
- Properties: map[string]any{
+ Name: EventOnboardingCompleted,
+ DistinctID: userID,
+ WorkspaceID: workspaceID,
+ Properties: withCoreProperties(map[string]any{
"completion_path": completionPath,
"joined_cloud_waitlist": joinedCloudWaitlist,
- },
+ }, CoreProperties{
+ UserID: userID,
+ WorkspaceID: workspaceID,
+ Source: SourceOnboarding,
+ }),
SetOnce: map[string]any{
"onboarded_at": onboardedAt,
},
@@ -241,9 +481,12 @@ func CloudWaitlistJoined(userID string, hasReason bool) Event {
return Event{
Name: EventCloudWaitlistJoined,
DistinctID: userID,
- Properties: map[string]any{
+ Properties: withCoreProperties(map[string]any{
"has_reason": hasReason,
- },
+ }, CoreProperties{
+ UserID: userID,
+ Source: SourceOnboarding,
+ }),
}
}
@@ -257,10 +500,14 @@ func StarterContentDecided(userID, workspaceID, decision, branch string) Event {
Name: EventStarterContentDecided,
DistinctID: userID,
WorkspaceID: workspaceID,
- Properties: map[string]any{
+ Properties: withCoreProperties(map[string]any{
"decision": decision,
"branch": branch,
- },
+ }, CoreProperties{
+ UserID: userID,
+ WorkspaceID: workspaceID,
+ Source: SourceOnboarding,
+ }),
}
}
@@ -283,10 +530,101 @@ func FeedbackSubmitted(userID, workspaceID string, messageLen int, hasImages boo
Name: EventFeedbackSubmitted,
DistinctID: userID,
WorkspaceID: workspaceID,
+ Properties: withCoreProperties(props, CoreProperties{
+ UserID: userID,
+ WorkspaceID: workspaceID,
+ Source: "ops_feedback",
+ }),
+ }
+}
+
+func agentTaskEvent(name string, ctx TaskContext, extra map[string]any) Event {
+ props := withCoreProperties(extra, CoreProperties(ctx))
+ return Event{
+ Name: name,
+ DistinctID: distinctID(ctx.UserID, ctx.WorkspaceID, ctx.AgentID),
+ WorkspaceID: ctx.WorkspaceID,
+ Properties: props,
+ }
+}
+
+func autopilotRunEvent(name, actorID, workspaceID, autopilotID, runID, agentID, triggerSource string, extra map[string]any) Event {
+ if extra == nil {
+ extra = map[string]any{}
+ }
+ extra["trigger_source"] = triggerSource
+ props := withCoreProperties(extra, CoreProperties{
+ UserID: nonAgentUserID(actorID),
+ WorkspaceID: workspaceID,
+ AgentID: agentID,
+ AutopilotRunID: runID,
+ Source: SourceAutopilot,
+ })
+ props["autopilot_id"] = autopilotID
+ return Event{
+ Name: name,
+ DistinctID: actorID,
+ WorkspaceID: workspaceID,
Properties: props,
}
}
+func withCoreProperties(props map[string]any, core CoreProperties) map[string]any {
+ if props == nil {
+ props = map[string]any{}
+ }
+ if core.UserID != "" {
+ props["user_id"] = core.UserID
+ }
+ if core.AgentID != "" {
+ props["agent_id"] = core.AgentID
+ }
+ if core.TaskID != "" {
+ props["task_id"] = core.TaskID
+ }
+ if core.IssueID != "" {
+ props["issue_id"] = core.IssueID
+ }
+ if core.ChatSessionID != "" {
+ props["chat_session_id"] = core.ChatSessionID
+ }
+ if core.AutopilotRunID != "" {
+ props["autopilot_run_id"] = core.AutopilotRunID
+ }
+ if core.Source != "" {
+ props["source"] = core.Source
+ }
+ if core.RuntimeMode != "" {
+ props["runtime_mode"] = core.RuntimeMode
+ }
+ if core.Provider != "" {
+ props["provider"] = core.Provider
+ }
+ props["is_demo"] = core.IsDemo
+ return props
+}
+
+func distinctID(userID, workspaceID, agentID string) string {
+ if userID != "" {
+ return userID
+ }
+ // Synthetic PostHog distinct IDs are namespace-prefixed; user UUIDs are not.
+ if agentID != "" {
+ return "agent:" + agentID
+ }
+ if workspaceID != "" {
+ return "workspace:" + workspaceID
+ }
+ return ""
+}
+
+func nonAgentUserID(distinct string) string {
+ if distinct == "" || strings.Contains(distinct, ":") {
+ return ""
+ }
+ return distinct
+}
+
func feedbackLengthBucket(n int) string {
switch {
case n < 100:
diff --git a/server/internal/analytics/events_test.go b/server/internal/analytics/events_test.go
new file mode 100644
index 0000000000..bc437a81a7
--- /dev/null
+++ b/server/internal/analytics/events_test.go
@@ -0,0 +1,40 @@
+package analytics
+
+import "testing"
+
+func TestRuntimeReadyOmitsUnmeasuredDuration(t *testing.T) {
+ ev := RuntimeReady("user-1", "workspace-1", "runtime-1", "daemon-1", "codex", 0)
+ if _, ok := ev.Properties["ready_duration_ms"]; ok {
+ t.Fatalf("ready_duration_ms should be omitted until it is measured")
+ }
+
+ ev = RuntimeReady("user-1", "workspace-1", "runtime-1", "daemon-1", "codex", 123)
+ if got := ev.Properties["ready_duration_ms"]; got != int64(123) {
+ t.Fatalf("ready_duration_ms = %v, want 123", got)
+ }
+}
+
+func TestFailedEventsUseWillRetry(t *testing.T) {
+ ctx := TaskContext{
+ UserID: "user-1",
+ WorkspaceID: "workspace-1",
+ AgentID: "agent-1",
+ TaskID: "task-1",
+ Source: SourceManual,
+ }
+ taskEv := AgentTaskFailed(ctx, 10, "runtime_offline", "runtime", true)
+ if got := taskEv.Properties["will_retry"]; got != true {
+ t.Fatalf("task will_retry = %v, want true", got)
+ }
+ if _, ok := taskEv.Properties["recoverable"]; ok {
+ t.Fatalf("task failure should not emit recoverable")
+ }
+
+ runEv := AutopilotRunFailed("user-1", "workspace-1", "autopilot-1", "run-1", "agent-1", "manual", "task failed", "task_error", false, 10)
+ if got := runEv.Properties["will_retry"]; got != false {
+ t.Fatalf("autopilot will_retry = %v, want false", got)
+ }
+ if _, ok := runEv.Properties["recoverable"]; ok {
+ t.Fatalf("autopilot failure should not emit recoverable")
+ }
+}
diff --git a/server/internal/analytics/posthog.go b/server/internal/analytics/posthog.go
index 60741cb573..d6e162447e 100644
--- a/server/internal/analytics/posthog.go
+++ b/server/internal/analytics/posthog.go
@@ -6,6 +6,7 @@ import (
"encoding/json"
"log/slog"
"net/http"
+ "strings"
"sync"
"sync/atomic"
"time"
@@ -20,8 +21,9 @@ const (
// PostHogConfig configures the live PostHog client.
type PostHogConfig struct {
- APIKey string
- Host string
+ APIKey string
+ Host string
+ Environment string
// Optional overrides. Zero values fall back to sensible defaults.
QueueSize int
@@ -59,6 +61,9 @@ func NewPostHogClient(cfg PostHogConfig) *PostHogClient {
if cfg.HTTPClient == nil {
cfg.HTTPClient = &http.Client{Timeout: defaultFlushTimeout}
}
+ if cfg.Environment == "" {
+ cfg.Environment = EnvironmentFromEnv()
+ }
c := &PostHogClient{
cfg: cfg,
ch: make(chan Event, cfg.QueueSize),
@@ -163,6 +168,14 @@ func (c *PostHogClient) send(batch []Event) {
if e.WorkspaceID != "" {
props["workspace_id"] = e.WorkspaceID
}
+ props["event_schema_version"] = EventSchemaVersion
+ props["environment"] = c.cfg.Environment
+ if _, ok := props["is_demo"]; !ok {
+ props["is_demo"] = false
+ }
+ if _, ok := props["user_id"]; !ok && e.DistinctID != "" && !strings.Contains(e.DistinctID, ":") {
+ props["user_id"] = e.DistinctID
+ }
if len(e.SetOnce) > 0 {
props["$set_once"] = e.SetOnce
}
diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.go
index dfc98e00c3..b62332790b 100644
--- a/server/internal/handler/agent.go
+++ b/server/internal/handler/agent.go
@@ -515,6 +515,7 @@ func (h *Handler) CreateAgent(w http.ResponseWriter, r *http.Request) {
workspaceID,
uuidToString(agent.ID),
runtime.Provider,
+ runtime.RuntimeMode,
req.Template,
isFirstAgent,
))
@@ -725,8 +726,10 @@ func (h *Handler) ArchiveAgent(w http.ResponseWriter, r *http.Request) {
// rows here — the agent:archived event below already triggers a full
// active-tasks invalidation on every connected client, so per-task
// task:cancelled events would be redundant noise.
- if _, err := h.Queries.CancelAgentTasksByAgent(r.Context(), agent.ID); err != nil {
+ if cancelled, err := h.Queries.CancelAgentTasksByAgent(r.Context(), agent.ID); err != nil {
slog.Warn("cancel agent tasks on archive failed", append(logger.RequestAttrs(r), "error", err, "agent_id", id)...)
+ } else {
+ h.TaskService.CaptureCancelledTasks(r.Context(), cancelled)
}
wsID := uuidToString(archived.WorkspaceID)
diff --git a/server/internal/handler/chat.go b/server/internal/handler/chat.go
index fb707f6c9b..0948523a9f 100644
--- a/server/internal/handler/chat.go
+++ b/server/internal/handler/chat.go
@@ -8,6 +8,7 @@ import (
"github.com/go-chi/chi/v5"
"github.com/jackc/pgx/v5"
+ "github.com/multica-ai/multica/server/internal/analytics"
db "github.com/multica-ai/multica/server/pkg/db/generated"
"github.com/multica-ai/multica/server/pkg/protocol"
)
@@ -318,6 +319,16 @@ func (h *Handler) SendChatMessage(w http.ResponseWriter, r *http.Request) {
if err := h.Queries.TouchChatSession(r.Context(), session.ID); err != nil {
slog.Warn("failed to touch chat session", "session_id", sessionID, "error", err)
}
+ taskContext := h.TaskService.AnalyticsContextForTask(r.Context(), task)
+ h.Analytics.Capture(analytics.ChatMessageSent(
+ userID,
+ workspaceID,
+ uuidToString(session.ID),
+ uuidToString(task.ID),
+ uuidToString(session.AgentID),
+ taskContext.RuntimeMode,
+ taskContext.Provider,
+ ))
// Broadcast the user message.
resolvedSessionID := uuidToString(session.ID)
diff --git a/server/internal/handler/config.go b/server/internal/handler/config.go
index 3b330e21c7..3c7bfd54da 100644
--- a/server/internal/handler/config.go
+++ b/server/internal/handler/config.go
@@ -3,6 +3,8 @@ package handler
import (
"net/http"
"os"
+
+ "github.com/multica-ai/multica/server/internal/analytics"
)
type AppConfig struct {
@@ -18,8 +20,9 @@ type AppConfig struct {
// 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"`
+ PosthogKey string `json:"posthog_key"`
+ PosthogHost string `json:"posthog_host"`
+ AnalyticsEnvironment string `json:"analytics_environment"`
}
// GetConfig is mounted on the public (unauthenticated) route group because
@@ -40,6 +43,7 @@ func (h *Handler) GetConfig(w http.ResponseWriter, r *http.Request) {
if v := os.Getenv("ANALYTICS_DISABLED"); v != "true" && v != "1" {
config.PosthogKey = os.Getenv("POSTHOG_API_KEY")
config.PosthogHost = os.Getenv("POSTHOG_HOST")
+ config.AnalyticsEnvironment = analytics.EnvironmentFromEnv()
if config.PosthogHost == "" && config.PosthogKey != "" {
config.PosthogHost = "https://us.i.posthog.com"
}
diff --git a/server/internal/handler/config_test.go b/server/internal/handler/config_test.go
index df4f2f8525..bf2bcf5228 100644
--- a/server/internal/handler/config_test.go
+++ b/server/internal/handler/config_test.go
@@ -45,4 +45,7 @@ func TestGetConfigIncludesRuntimeAuthConfig(t *testing.T) {
if cfg.PosthogHost != "https://eu.i.posthog.com" {
t.Fatalf("posthog_host: want https://eu.i.posthog.com, got %q", cfg.PosthogHost)
}
+ if cfg.AnalyticsEnvironment != "dev" {
+ t.Fatalf("analytics_environment: want dev, got %q", cfg.AnalyticsEnvironment)
+ }
}
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index d6903eb1a8..a48a82ca64 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -298,6 +298,15 @@ func (h *Handler) DaemonRegister(w http.ResponseWriter, r *http.Request) {
OwnerID: ownerID,
})
if err != nil {
+ h.Analytics.Capture(analytics.RuntimeFailed(
+ uuidToString(ownerID),
+ req.WorkspaceID,
+ req.DaemonID,
+ provider,
+ "registration_failed",
+ "db_error",
+ true,
+ ))
writeError(w, http.StatusInternalServerError, "failed to register runtime: "+err.Error())
return
}
@@ -319,15 +328,28 @@ func (h *Handler) DaemonRegister(w http.ResponseWriter, r *http.Request) {
LegacyDaemonID: row.LegacyDaemonID,
}
+ // Inserted is false for normal daemon reconnects/upserts, so
+ // runtime_ready is a first-ready-per-runtime-row signal.
if row.Inserted {
h.Analytics.Capture(analytics.RuntimeRegistered(
uuidToString(ownerID),
req.WorkspaceID,
uuidToString(registered.ID),
+ req.DaemonID,
provider,
runtime.Version,
req.CLIVersion,
))
+ if registered.Status == "online" {
+ h.Analytics.Capture(analytics.RuntimeReady(
+ uuidToString(ownerID),
+ req.WorkspaceID,
+ uuidToString(registered.ID),
+ req.DaemonID,
+ provider,
+ 0,
+ ))
+ }
}
// Seamless migration from the previous hostname-derived identity. The
@@ -500,6 +522,13 @@ func (h *Handler) DaemonDeregister(w http.ResponseWriter, r *http.Request) {
slog.Warn("deregister: failed to set offline", "runtime_id", rid, "error", err)
continue
}
+ h.Analytics.Capture(analytics.RuntimeOffline(
+ uuidToString(rt.OwnerID),
+ wsID,
+ uuidToString(rt.ID),
+ rt.DaemonID.String,
+ rt.Provider,
+ ))
affectedWorkspaces[wsID] = true
}
@@ -1379,6 +1408,7 @@ func (h *Handler) emitIssueExecutedOnFirstCompletion(r *http.Request, task *db.A
if task.StartedAt.Valid && task.CompletedAt.Valid {
durationMS = task.CompletedAt.Time.Sub(task.StartedAt.Time).Milliseconds()
}
+ taskContext := h.TaskService.AnalyticsContextForTask(r.Context(), *task)
// 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
@@ -1391,6 +1421,11 @@ func (h *Handler) emitIssueExecutedOnFirstCompletion(r *http.Request, task *db.A
distinct,
uuidToString(marked.WorkspaceID),
uuidToString(marked.ID),
+ uuidToString(task.ID),
+ uuidToString(task.AgentID),
+ taskContext.Source,
+ taskContext.RuntimeMode,
+ taskContext.Provider,
durationMS,
))
}
diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.go
index 47b9819b34..e0975e0315 100644
--- a/server/internal/handler/handler.go
+++ b/server/internal/handler/handler.go
@@ -99,6 +99,7 @@ func New(queries *db.Queries, txStarter txStarter, hub *realtime.Hub, bus *event
}
taskSvc := service.NewTaskService(queries, txStarter, hub, bus, daemonHub)
+ taskSvc.Analytics = analyticsClient
return &Handler{
Queries: queries,
DB: executor,
diff --git a/server/internal/handler/invitation.go b/server/internal/handler/invitation.go
index c1566a4fa6..ac10961734 100644
--- a/server/internal/handler/invitation.go
+++ b/server/internal/handler/invitation.go
@@ -431,7 +431,9 @@ func (h *Handler) AcceptInvitation(w http.ResponseWriter, r *http.Request) {
// "member row exists ↔ onboarded_at != null" cannot be violated.
// COALESCE in MarkUserOnboarded keeps this idempotent for users joining
// additional workspaces after their first.
- if _, err := qtx.MarkUserOnboarded(r.Context(), user.ID); err != nil {
+ firstOnboardingCompletion := !user.OnboardedAt.Valid
+ onboardedUser, err := qtx.MarkUserOnboarded(r.Context(), user.ID)
+ if err != nil {
writeError(w, http.StatusInternalServerError, "failed to mark user onboarded")
return
}
@@ -471,6 +473,19 @@ func (h *Handler) AcceptInvitation(w http.ResponseWriter, r *http.Request) {
wsID,
daysSinceInvite,
))
+ if firstOnboardingCompletion {
+ onboardedAt := ""
+ if onboardedUser.OnboardedAt.Valid {
+ onboardedAt = onboardedUser.OnboardedAt.Time.UTC().Format("2006-01-02T15:04:05Z07:00")
+ }
+ h.Analytics.Capture(analytics.OnboardingCompleted(
+ userID,
+ wsID,
+ analytics.OnboardingPathInviteAccept,
+ onboardedAt,
+ onboardedUser.CloudWaitlistEmail.Valid,
+ ))
+ }
writeJSON(w, http.StatusOK, memberResp)
}
diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.go
index 3c3bf502d8..446bb4bb8b 100644
--- a/server/internal/handler/issue.go
+++ b/server/internal/handler/issue.go
@@ -16,6 +16,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"
"github.com/multica-ai/multica/server/internal/util"
"github.com/multica-ai/multica/server/pkg/agent"
@@ -1276,6 +1277,44 @@ func (h *Handler) CreateIssue(w http.ResponseWriter, r *http.Request) {
slog.Info("issue created", append(logger.RequestAttrs(r), "issue_id", uuidToString(issue.ID), "title", issue.Title, "status", issue.Status, "workspace_id", workspaceID)...)
h.publish(protocol.EventIssueCreated, workspaceID, creatorType, actualCreatorID, map[string]any{"issue": resp})
+ analyticsActorID := actualCreatorID
+ analyticsAgentID := ""
+ if issue.AssigneeType.Valid && issue.AssigneeType.String == "agent" {
+ analyticsAgentID = uuidToString(issue.AssigneeID)
+ }
+ if creatorType == "agent" {
+ analyticsActorID = "agent:" + actualCreatorID
+ if analyticsAgentID == "" {
+ analyticsAgentID = actualCreatorID
+ }
+ }
+ analyticsSource := analytics.SourceManual
+ analyticsTaskID := ""
+ analyticsAutopilotRunID := ""
+ if originType.Valid {
+ switch originType.String {
+ case "quick_create":
+ analyticsSource = analytics.SourceManual
+ analyticsTaskID = uuidToString(originID)
+ case "autopilot":
+ analyticsSource = analytics.SourceAutopilot
+ analyticsAutopilotRunID = uuidToString(originID)
+ default:
+ slog.Warn("analytics: unknown issue origin type",
+ "origin_type", originType.String,
+ "issue_id", uuidToString(issue.ID),
+ )
+ }
+ }
+ h.Analytics.Capture(analytics.IssueCreated(
+ analyticsActorID,
+ workspaceID,
+ uuidToString(issue.ID),
+ analyticsAgentID,
+ analyticsTaskID,
+ analyticsAutopilotRunID,
+ analyticsSource,
+ ))
// Enqueue agent task when an agent-assigned issue is created.
if issue.AssigneeType.Valid && issue.AssigneeID.Valid {
diff --git a/server/internal/handler/onboarding.go b/server/internal/handler/onboarding.go
index 7d04e21efa..386bb49854 100644
--- a/server/internal/handler/onboarding.go
+++ b/server/internal/handler/onboarding.go
@@ -45,6 +45,7 @@ const (
// funnel-ready label.
type completeOnboardingRequest struct {
CompletionPath string `json:"completion_path,omitempty"`
+ WorkspaceID string `json:"workspace_id,omitempty"`
}
var validCompletionPaths = map[string]struct{}{
@@ -106,6 +107,7 @@ func (h *Handler) CompleteOnboarding(w http.ResponseWriter, r *http.Request) {
}
h.Analytics.Capture(analytics.OnboardingCompleted(
userID,
+ req.WorkspaceID,
path,
onboardedAt,
user.CloudWaitlistEmail.Valid,
diff --git a/server/internal/service/autopilot.go b/server/internal/service/autopilot.go
index 9505a24b04..7f531b2c89 100644
--- a/server/internal/service/autopilot.go
+++ b/server/internal/service/autopilot.go
@@ -9,6 +9,7 @@ import (
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/analytics"
"github.com/multica-ai/multica/server/internal/events"
"github.com/multica-ai/multica/server/internal/util"
db "github.com/multica-ai/multica/server/pkg/db/generated"
@@ -57,20 +58,24 @@ func (s *AutopilotService) DispatchAutopilot(
if err != nil {
return nil, fmt.Errorf("create run: %w", err)
}
+ s.captureAutopilotRunStarted(autopilot, run, source)
switch autopilot.ExecutionMode {
case "create_issue":
if err := s.dispatchCreateIssue(ctx, autopilot, &run); err != nil {
s.failRun(ctx, run.ID, err.Error())
+ s.captureAutopilotRunFailed(autopilot, run, source, err.Error())
return &run, fmt.Errorf("dispatch create_issue: %w", err)
}
case "run_only":
if err := s.dispatchRunOnly(ctx, autopilot, &run); err != nil {
s.failRun(ctx, run.ID, err.Error())
+ s.captureAutopilotRunFailed(autopilot, run, source, err.Error())
return &run, fmt.Errorf("dispatch run_only: %w", err)
}
default:
s.failRun(ctx, run.ID, "unknown execution_mode: "+autopilot.ExecutionMode)
+ s.captureAutopilotRunFailed(autopilot, run, source, "unknown execution_mode: "+autopilot.ExecutionMode)
return &run, fmt.Errorf("unknown execution_mode: %s", autopilot.ExecutionMode)
}
@@ -160,6 +165,7 @@ func (s *AutopilotService) dispatchCreateIssue(ctx context.Context, ap db.Autopi
"issue": issueToMap(issue, prefix),
},
})
+ s.captureIssueCreatedFromAutopilot(ap, run, issue)
// Enqueue agent task via the existing flow.
if _, err := s.TaskSvc.EnqueueTaskForIssue(ctx, issue); err != nil {
@@ -220,7 +226,7 @@ func (s *AutopilotService) dispatchRunOnly(ctx context.Context, ap db.Autopilot,
// (bypassing TaskService.Enqueue*), so without this the runtime
// would not get a wakeup and any cached "empty" verdict would
// stall the task until the TTL expired.
- s.TaskSvc.NotifyTaskEnqueued(task)
+ s.TaskSvc.NotifyTaskEnqueued(ctx, task)
slog.Info("autopilot dispatched (run_only)",
"autopilot_id", util.UUIDToString(ap.ID),
@@ -240,28 +246,36 @@ func (s *AutopilotService) SyncRunFromIssue(ctx context.Context, issue db.Issue)
if err != nil {
return // no active run linked to this issue
}
+ autopilot, err := s.Queries.GetAutopilot(ctx, run.AutopilotID)
+ if err != nil {
+ return
+ }
wsID := util.UUIDToString(issue.WorkspaceID)
switch issue.Status {
case "done", "in_review":
- if _, err := s.Queries.UpdateAutopilotRunCompleted(ctx, db.UpdateAutopilotRunCompletedParams{
+ updatedRun, err := s.Queries.UpdateAutopilotRunCompleted(ctx, db.UpdateAutopilotRunCompletedParams{
ID: run.ID,
- }); err != nil {
+ })
+ if err != nil {
slog.Warn("failed to complete autopilot run", "run_id", util.UUIDToString(run.ID), "error", err)
return
}
- s.publishRunDone(wsID, run, "completed")
+ s.captureAutopilotRunCompleted(autopilot, updatedRun)
+ s.publishRunDone(wsID, updatedRun, "completed")
case "cancelled", "blocked":
reason := "issue " + issue.Status
- if _, err := s.Queries.UpdateAutopilotRunFailed(ctx, db.UpdateAutopilotRunFailedParams{
+ updatedRun, err := s.Queries.UpdateAutopilotRunFailed(ctx, db.UpdateAutopilotRunFailedParams{
ID: run.ID,
FailureReason: pgtype.Text{String: reason, Valid: true},
- }); err != nil {
+ })
+ if err != nil {
slog.Warn("failed to fail autopilot run", "run_id", util.UUIDToString(run.ID), "error", err)
return
}
- s.publishRunDone(wsID, run, "failed")
+ s.captureAutopilotRunFailed(autopilot, updatedRun, updatedRun.Source, reason)
+ s.publishRunDone(wsID, updatedRun, "failed")
}
}
@@ -284,31 +298,34 @@ func (s *AutopilotService) SyncRunFromTask(ctx context.Context, task db.AgentTas
switch task.Status {
case "completed":
- if _, err := s.Queries.UpdateAutopilotRunCompleted(ctx, db.UpdateAutopilotRunCompletedParams{
+ updatedRun, err := s.Queries.UpdateAutopilotRunCompleted(ctx, db.UpdateAutopilotRunCompletedParams{
ID: run.ID,
Result: task.Result,
- }); err != nil {
+ })
+ if err != nil {
slog.Warn("failed to complete autopilot run from task", "run_id", util.UUIDToString(run.ID), "error", err)
return
}
- s.publishRunDone(wsID, run, "completed")
+ s.captureAutopilotRunCompleted(autopilot, updatedRun)
+ s.publishRunDone(wsID, updatedRun, "completed")
case "failed", "cancelled":
reason := "task " + task.Status
if task.Error.Valid {
reason = task.Error.String
}
- if _, err := s.Queries.UpdateAutopilotRunFailed(ctx, db.UpdateAutopilotRunFailedParams{
+ updatedRun, err := s.Queries.UpdateAutopilotRunFailed(ctx, db.UpdateAutopilotRunFailedParams{
ID: run.ID,
FailureReason: pgtype.Text{String: reason, Valid: true},
- }); err != nil {
+ })
+ if err != nil {
slog.Warn("failed to fail autopilot run from task", "run_id", util.UUIDToString(run.ID), "error", err)
return
}
- s.publishRunDone(wsID, run, "failed")
+ s.captureAutopilotRunFailed(autopilot, updatedRun, updatedRun.Source, reason)
+ s.publishRunDone(wsID, updatedRun, "failed")
}
}
-
func (s *AutopilotService) failRun(ctx context.Context, runID pgtype.UUID, reason string) {
if _, err := s.Queries.UpdateAutopilotRunFailed(ctx, db.UpdateAutopilotRunFailedParams{
ID: runID,
@@ -331,6 +348,115 @@ func (s *AutopilotService) publishRunDone(workspaceID string, run db.AutopilotRu
})
}
+func (s *AutopilotService) captureIssueCreatedFromAutopilot(ap db.Autopilot, run *db.AutopilotRun, issue db.Issue) {
+ if s.TaskSvc == nil || s.TaskSvc.Analytics == nil {
+ return
+ }
+ s.TaskSvc.Analytics.Capture(analytics.IssueCreated(
+ autopilotActorID(ap),
+ util.UUIDToString(ap.WorkspaceID),
+ util.UUIDToString(issue.ID),
+ util.UUIDToString(ap.AssigneeID),
+ "",
+ util.UUIDToString(run.ID),
+ analytics.SourceAutopilot,
+ ))
+}
+
+func (s *AutopilotService) captureAutopilotRunStarted(ap db.Autopilot, run db.AutopilotRun, triggerSource string) {
+ if s.TaskSvc == nil || s.TaskSvc.Analytics == nil {
+ return
+ }
+ s.TaskSvc.Analytics.Capture(analytics.AutopilotRunStarted(
+ autopilotActorID(ap),
+ util.UUIDToString(ap.WorkspaceID),
+ util.UUIDToString(ap.ID),
+ util.UUIDToString(run.ID),
+ util.UUIDToString(ap.AssigneeID),
+ triggerSource,
+ ))
+}
+
+func (s *AutopilotService) captureAutopilotRunCompleted(ap db.Autopilot, run db.AutopilotRun) {
+ if s.TaskSvc == nil || s.TaskSvc.Analytics == nil {
+ return
+ }
+ s.TaskSvc.Analytics.Capture(analytics.AutopilotRunCompleted(
+ autopilotActorID(ap),
+ util.UUIDToString(ap.WorkspaceID),
+ util.UUIDToString(ap.ID),
+ util.UUIDToString(run.ID),
+ util.UUIDToString(ap.AssigneeID),
+ run.Source,
+ autopilotRunDurationMS(run),
+ ))
+}
+
+func (s *AutopilotService) captureAutopilotRunFailed(ap db.Autopilot, run db.AutopilotRun, triggerSource, reason string) {
+ if s.TaskSvc == nil || s.TaskSvc.Analytics == nil {
+ return
+ }
+ if reason == "" {
+ reason = "unknown"
+ }
+ s.TaskSvc.Analytics.Capture(analytics.AutopilotRunFailed(
+ autopilotActorID(ap),
+ util.UUIDToString(ap.WorkspaceID),
+ util.UUIDToString(ap.ID),
+ util.UUIDToString(run.ID),
+ util.UUIDToString(ap.AssigneeID),
+ triggerSource,
+ reason,
+ autopilotErrorType(reason),
+ false,
+ autopilotRunDurationMS(run),
+ ))
+}
+
+func autopilotErrorType(reason string) string {
+ switch {
+ case strings.Contains(reason, "unknown execution_mode"):
+ return "configuration"
+ case strings.HasPrefix(reason, "issue "):
+ return "issue_terminal"
+ case strings.Contains(reason, "create issue"), strings.Contains(reason, "enqueue task"), strings.Contains(reason, "dispatch"):
+ return "dispatch_error"
+ case strings.HasPrefix(reason, "task "):
+ return "task_error"
+ default:
+ return "autopilot_error"
+ }
+}
+
+func autopilotActorID(ap db.Autopilot) string {
+ id := util.UUIDToString(ap.CreatedByID)
+ if ap.CreatedByType == "agent" && id != "" {
+ return "agent:" + id
+ }
+ if id != "" {
+ return id
+ }
+ return "system"
+}
+
+func autopilotRunDurationMS(run db.AutopilotRun) int64 {
+ if !run.CompletedAt.Valid {
+ return 0
+ }
+ start := run.TriggeredAt
+ if !start.Valid {
+ start = run.CreatedAt
+ }
+ if !start.Valid {
+ return 0
+ }
+ ms := run.CompletedAt.Time.Sub(start.Time).Milliseconds()
+ if ms < 0 {
+ return 0
+ }
+ return ms
+}
+
// buildIssueDescription appends an autopilot system instruction to the
// user-provided description, asking the agent to rename the issue after
// it understands the actual work.
diff --git a/server/internal/service/autopilot_test.go b/server/internal/service/autopilot_test.go
new file mode 100644
index 0000000000..5666b4119c
--- /dev/null
+++ b/server/internal/service/autopilot_test.go
@@ -0,0 +1,20 @@
+package service
+
+import "testing"
+
+func TestAutopilotErrorType(t *testing.T) {
+ cases := map[string]string{
+ "unknown execution_mode: nope": "configuration",
+ "issue blocked": "issue_terminal",
+ "issue cancelled": "issue_terminal",
+ "enqueue task: no runtime": "dispatch_error",
+ "task failed": "task_error",
+ "unexpected": "autopilot_error",
+ }
+
+ for reason, want := range cases {
+ if got := autopilotErrorType(reason); got != want {
+ t.Fatalf("autopilotErrorType(%q) = %q, want %q", reason, got, want)
+ }
+ }
+}
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index 8c44512b4e..f88f0c74ba 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -6,13 +6,14 @@ import (
"errors"
"fmt"
"log/slog"
-
"strconv"
"strings"
+ "sync"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/analytics"
"github.com/multica-ai/multica/server/internal/events"
"github.com/multica-ai/multica/server/internal/mention"
"github.com/multica-ai/multica/server/internal/realtime"
@@ -27,6 +28,7 @@ type TaskService struct {
TxStarter TxStarter
Hub *realtime.Hub
Bus *events.Bus
+ Analytics analytics.Client
Wakeup TaskWakeupNotifier
// EmptyClaim caches "this runtime has no queued task" so the daemon
// poll path can skip a Postgres scan on the steady-state empty case.
@@ -34,6 +36,10 @@ type TaskService struct {
// goes through the DB. Wired in router.go from the shared Redis
// client.
EmptyClaim *EmptyClaimCache
+
+ analyticsContextMu sync.Mutex
+ analyticsContextCache map[string]analytics.TaskContext
+ analyticsContextOrder []string
}
type TaskWakeupNotifier interface {
@@ -71,6 +77,8 @@ func truncateForSummary(s string, maxRunes int) string {
return string(rs[:maxRunes]) + "…"
}
+const taskAnalyticsContextCacheMax = 4096
+
// buildCommentTriggerSummary fetches the comment content and truncates
// it for storage on the task row. Returns an invalid pgtype.Text when
// the comment is missing (deleted / wrong workspace / etc) so the column
@@ -98,6 +106,246 @@ func NewTaskService(q *db.Queries, tx TxStarter, hub *realtime.Hub, bus *events.
return &TaskService{Queries: q, TxStarter: tx, Hub: hub, Bus: bus, Wakeup: wakeup}
}
+func (s *TaskService) captureTaskQueued(ctx context.Context, task db.AgentTaskQueue) {
+ s.captureTaskEvent(ctx, analytics.AgentTaskQueued(s.taskAnalyticsContext(ctx, task)))
+}
+
+func (s *TaskService) AnalyticsContextForTask(ctx context.Context, task db.AgentTaskQueue) analytics.TaskContext {
+ return s.taskAnalyticsContext(ctx, task)
+}
+
+func (s *TaskService) captureTaskStarted(ctx context.Context, task db.AgentTaskQueue) {
+ s.captureTaskEvent(ctx, analytics.AgentTaskStarted(s.taskAnalyticsContext(ctx, task)))
+}
+
+func (s *TaskService) captureTaskCompleted(ctx context.Context, task db.AgentTaskQueue) {
+ s.captureTaskEvent(ctx, analytics.AgentTaskCompleted(
+ s.taskAnalyticsContext(ctx, task),
+ taskDurationMS(task),
+ ))
+}
+
+func (s *TaskService) captureTaskFailed(ctx context.Context, task db.AgentTaskQueue) {
+ failureReason := taskFailureReason(task)
+ s.captureTaskEvent(ctx, analytics.AgentTaskFailed(
+ s.taskAnalyticsContext(ctx, task),
+ taskDurationMS(task),
+ failureReason,
+ taskErrorType(failureReason),
+ s.willRetryTask(task),
+ ))
+}
+
+func (s *TaskService) captureTaskCancelled(ctx context.Context, task db.AgentTaskQueue) {
+ s.captureTaskEvent(ctx, analytics.AgentTaskCancelled(
+ s.taskAnalyticsContext(ctx, task),
+ taskDurationMS(task),
+ ))
+}
+
+func (s *TaskService) captureTaskEvent(ctx context.Context, event analytics.Event) {
+ if s.Analytics == nil {
+ return
+ }
+ if event.WorkspaceID == "" {
+ return
+ }
+ s.Analytics.Capture(event)
+}
+
+func (s *TaskService) cachedTaskAnalyticsContext(task db.AgentTaskQueue) (analytics.TaskContext, bool) {
+ key := taskAnalyticsContextKey(task)
+ if key == "" {
+ return analytics.TaskContext{}, false
+ }
+ s.analyticsContextMu.Lock()
+ defer s.analyticsContextMu.Unlock()
+ if s.analyticsContextCache == nil {
+ return analytics.TaskContext{}, false
+ }
+ tc, ok := s.analyticsContextCache[key]
+ return tc, ok
+}
+
+func (s *TaskService) storeTaskAnalyticsContext(task db.AgentTaskQueue, tc analytics.TaskContext) {
+ if tc.WorkspaceID == "" {
+ return
+ }
+ key := taskAnalyticsContextKey(task)
+ if key == "" {
+ return
+ }
+ s.analyticsContextMu.Lock()
+ defer s.analyticsContextMu.Unlock()
+ if s.analyticsContextCache == nil {
+ s.analyticsContextCache = make(map[string]analytics.TaskContext)
+ }
+ if _, ok := s.analyticsContextCache[key]; !ok {
+ s.analyticsContextOrder = append(s.analyticsContextOrder, key)
+ if len(s.analyticsContextOrder) > taskAnalyticsContextCacheMax {
+ oldest := s.analyticsContextOrder[0]
+ s.analyticsContextOrder = s.analyticsContextOrder[1:]
+ delete(s.analyticsContextCache, oldest)
+ }
+ }
+ s.analyticsContextCache[key] = tc
+}
+
+func taskAnalyticsContextKey(task db.AgentTaskQueue) string {
+ taskID := util.UUIDToString(task.ID)
+ if taskID == "" {
+ return ""
+ }
+ return strings.Join([]string{
+ taskID,
+ util.UUIDToString(task.RuntimeID),
+ util.UUIDToString(task.IssueID),
+ util.UUIDToString(task.ChatSessionID),
+ util.UUIDToString(task.AutopilotRunID),
+ }, "|")
+}
+
+func (s *TaskService) taskAnalyticsContext(ctx context.Context, task db.AgentTaskQueue) analytics.TaskContext {
+ if tc, ok := s.cachedTaskAnalyticsContext(task); ok {
+ return tc
+ }
+ tc := analytics.TaskContext{
+ AgentID: util.UUIDToString(task.AgentID),
+ TaskID: util.UUIDToString(task.ID),
+ Source: analytics.SourceManual,
+ }
+ if task.IssueID.Valid {
+ tc.IssueID = util.UUIDToString(task.IssueID)
+ }
+ if task.ChatSessionID.Valid {
+ tc.ChatSessionID = util.UUIDToString(task.ChatSessionID)
+ tc.Source = analytics.SourceChat
+ }
+ if task.AutopilotRunID.Valid {
+ tc.AutopilotRunID = util.UUIDToString(task.AutopilotRunID)
+ tc.Source = analytics.SourceAutopilot
+ }
+
+ if task.RuntimeID.Valid {
+ if rt, err := s.Queries.GetAgentRuntime(ctx, task.RuntimeID); err == nil {
+ tc.WorkspaceID = util.UUIDToString(rt.WorkspaceID)
+ tc.RuntimeMode = rt.RuntimeMode
+ tc.Provider = rt.Provider
+ }
+ }
+ if tc.WorkspaceID == "" || tc.RuntimeMode == "" {
+ if agent, err := s.Queries.GetAgent(ctx, task.AgentID); err == nil {
+ if tc.WorkspaceID == "" {
+ tc.WorkspaceID = util.UUIDToString(agent.WorkspaceID)
+ }
+ if tc.RuntimeMode == "" {
+ tc.RuntimeMode = agent.RuntimeMode
+ }
+ }
+ }
+
+ if task.IssueID.Valid {
+ if issue, err := s.Queries.GetIssue(ctx, task.IssueID); err == nil {
+ tc.WorkspaceID = util.UUIDToString(issue.WorkspaceID)
+ if issue.CreatorType == "member" {
+ tc.UserID = util.UUIDToString(issue.CreatorID)
+ }
+ if issue.OriginType.Valid {
+ switch issue.OriginType.String {
+ case "autopilot":
+ tc.Source = analytics.SourceAutopilot
+ if ap, err := s.Queries.GetAutopilot(ctx, issue.OriginID); err == nil {
+ if ap.CreatedByType == "member" {
+ tc.UserID = util.UUIDToString(ap.CreatedByID)
+ }
+ }
+ case "quick_create":
+ tc.Source = analytics.SourceManual
+ }
+ }
+ }
+ }
+ if task.ChatSessionID.Valid {
+ if cs, err := s.Queries.GetChatSession(ctx, task.ChatSessionID); err == nil {
+ tc.WorkspaceID = util.UUIDToString(cs.WorkspaceID)
+ tc.UserID = util.UUIDToString(cs.CreatorID)
+ }
+ }
+ if task.AutopilotRunID.Valid {
+ if run, err := s.Queries.GetAutopilotRun(ctx, task.AutopilotRunID); err == nil {
+ if ap, err := s.Queries.GetAutopilot(ctx, run.AutopilotID); err == nil {
+ tc.WorkspaceID = util.UUIDToString(ap.WorkspaceID)
+ if ap.CreatedByType == "member" {
+ tc.UserID = util.UUIDToString(ap.CreatedByID)
+ }
+ }
+ }
+ }
+ if qc, ok := s.parseQuickCreateContext(task); ok {
+ tc.WorkspaceID = qc.WorkspaceID
+ tc.UserID = qc.RequesterID
+ tc.Source = analytics.SourceManual
+ }
+ s.storeTaskAnalyticsContext(task, tc)
+ return tc
+}
+
+func taskDurationMS(task db.AgentTaskQueue) int64 {
+ if !task.CompletedAt.Valid {
+ return 0
+ }
+ start := task.CreatedAt
+ if task.StartedAt.Valid {
+ start = task.StartedAt
+ } else if task.DispatchedAt.Valid {
+ start = task.DispatchedAt
+ }
+ if !start.Valid {
+ return 0
+ }
+ ms := task.CompletedAt.Time.Sub(start.Time).Milliseconds()
+ if ms < 0 {
+ return 0
+ }
+ return ms
+}
+
+func taskFailureReason(task db.AgentTaskQueue) string {
+ if task.FailureReason.Valid && task.FailureReason.String != "" {
+ return task.FailureReason.String
+ }
+ return "agent_error"
+}
+
+func taskErrorType(reason string) string {
+ switch reason {
+ case "runtime_offline", "runtime_recovery":
+ return "runtime"
+ case "timeout":
+ return "timeout"
+ case "iteration_limit", "agent_fallback_message":
+ return "agent_output"
+ case "cancelled", "user_cancelled":
+ return "cancelled"
+ default:
+ return "agent_error"
+ }
+}
+
+func (s *TaskService) willRetryTask(task db.AgentTaskQueue) bool {
+ reason := taskFailureReason(task)
+ if !retryableReasons[reason] {
+ return false
+ }
+ if task.Attempt >= task.MaxAttempts {
+ return false
+ }
+ if task.AutopilotRunID.Valid {
+ return false
+ }
+ return task.IssueID.Valid || task.ChatSessionID.Valid
+}
+
// EnqueueTaskForIssue creates a queued task for an agent-assigned issue.
// No context snapshot is stored — the agent fetches all data it needs at
// runtime via the multica CLI.
@@ -161,7 +409,7 @@ func (s *TaskService) enqueueIssueTask(ctx context.Context, issue db.Issue, trig
// before the queued one (rare but unsafe-by-construction). Publishing
// in the desired observe-order makes correctness independent of timing.
s.broadcastTaskEvent(ctx, protocol.EventTaskQueued, task)
- s.notifyTaskAvailable(task)
+ s.NotifyTaskEnqueued(ctx, task)
return task, nil
}
@@ -199,7 +447,7 @@ func (s *TaskService) EnqueueTaskForMention(ctx context.Context, issue db.Issue,
slog.Info("mention task enqueued", "task_id", util.UUIDToString(task.ID), "issue_id", util.UUIDToString(issue.ID), "agent_id", util.UUIDToString(agentID))
// See EnqueueTaskForIssue for ordering rationale.
s.broadcastTaskEvent(ctx, protocol.EventTaskQueued, task)
- s.notifyTaskAvailable(task)
+ s.NotifyTaskEnqueued(ctx, task)
return task, nil
}
@@ -267,7 +515,7 @@ func (s *TaskService) EnqueueQuickCreateTask(ctx context.Context, workspaceID, r
// cycle. Without this the user perceives "quick create never
// triggered" because the modal closes immediately and the task
// sits in 'queued' until the next sleepWithContextOrWakeup tick.
- s.notifyTaskAvailable(task)
+ s.NotifyTaskEnqueued(ctx, task)
return task, nil
}
@@ -300,7 +548,7 @@ func (s *TaskService) EnqueueChatTask(ctx context.Context, chatSession db.ChatSe
slog.Info("chat task enqueued", "task_id", util.UUIDToString(task.ID), "chat_session_id", util.UUIDToString(chatSession.ID), "agent_id", util.UUIDToString(chatSession.AgentID))
// See EnqueueTaskForIssue for ordering rationale.
s.broadcastTaskEvent(ctx, protocol.EventTaskQueued, task)
- s.notifyTaskAvailable(task)
+ s.NotifyTaskEnqueued(ctx, task)
return task, nil
}
@@ -319,6 +567,7 @@ func (s *TaskService) CancelTasksForIssue(ctx context.Context, issueID pgtype.UU
return err
}
for _, t := range cancelled {
+ s.captureTaskCancelled(ctx, t)
s.ReconcileAgentStatus(ctx, t.AgentID)
s.broadcastTaskEvent(ctx, protocol.EventTaskCancelled, t)
}
@@ -337,6 +586,7 @@ func (s *TaskService) CancelTasksForAgent(ctx context.Context, agentID pgtype.UU
return nil, err
}
for _, t := range cancelled {
+ s.captureTaskCancelled(ctx, t)
s.broadcastTaskEvent(ctx, protocol.EventTaskCancelled, t)
}
// Reconcile once after the loop — agent transitions from
@@ -358,6 +608,7 @@ func (s *TaskService) CancelTasksByTriggerComment(ctx context.Context, commentID
return err
}
for _, t := range cancelled {
+ s.captureTaskCancelled(ctx, t)
s.ReconcileAgentStatus(ctx, t.AgentID)
s.broadcastTaskEvent(ctx, protocol.EventTaskCancelled, t)
}
@@ -370,11 +621,18 @@ func (s *TaskService) CancelTasksByTriggerComment(ctx context.Context, commentID
// that the tx might still roll back.
func (s *TaskService) BroadcastCancelledTasks(ctx context.Context, cancelled []db.AgentTaskQueue) {
for _, t := range cancelled {
+ s.captureTaskCancelled(ctx, t)
s.ReconcileAgentStatus(ctx, t.AgentID)
s.broadcastTaskEvent(ctx, protocol.EventTaskCancelled, t)
}
}
+func (s *TaskService) CaptureCancelledTasks(ctx context.Context, cancelled []db.AgentTaskQueue) {
+ for _, t := range cancelled {
+ s.captureTaskCancelled(ctx, t)
+ }
+}
+
// CancelTask cancels a single task by ID. It broadcasts a task:cancelled event
// so frontends can update immediately.
func (s *TaskService) CancelTask(ctx context.Context, taskID pgtype.UUID) (*db.AgentTaskQueue, error) {
@@ -391,6 +649,7 @@ func (s *TaskService) CancelTask(ctx context.Context, taskID pgtype.UUID) (*db.A
}
slog.Info("task cancelled", "task_id", util.UUIDToString(task.ID), "issue_id", util.UUIDToString(task.IssueID))
+ s.captureTaskCancelled(ctx, task)
// Reconcile agent status
s.ReconcileAgentStatus(ctx, task.AgentID)
@@ -590,6 +849,7 @@ func (s *TaskService) StartTask(ctx context.Context, taskID pgtype.UUID) (*db.Ag
}
slog.Info("task started", "task_id", util.UUIDToString(task.ID), "issue_id", util.UUIDToString(task.IssueID))
+ s.captureTaskStarted(ctx, task)
return &task, nil
}
@@ -668,6 +928,7 @@ func (s *TaskService) CompleteTask(ctx context.Context, taskID pgtype.UUID, resu
}
slog.Info("task completed", "task_id", util.UUIDToString(task.ID), "issue_id", util.UUIDToString(task.IssueID))
+ s.captureTaskCompleted(ctx, task)
// Invariant: every completed issue task must have at least one agent
// comment on the issue, so the user always sees something when a run
@@ -820,6 +1081,7 @@ func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg,
}
slog.Warn("task failed", "task_id", util.UUIDToString(task.ID), "issue_id", util.UUIDToString(task.IssueID), "error", errMsg, "failure_reason", failureReason)
+ s.captureTaskFailed(ctx, task)
// Auto-retry eligible failures (orphan, timeout, runtime_offline,
// runtime_recovery). The helper itself enforces attempt < max_attempts
@@ -944,7 +1206,7 @@ func (s *TaskService) MaybeRetryFailedTask(ctx context.Context, parent db.AgentT
// as EnqueueTaskFor*. Broadcast queued first, then notify the daemon —
// see EnqueueTaskForIssue for ordering rationale.
s.broadcastTaskEvent(ctx, protocol.EventTaskQueued, child)
- s.notifyTaskAvailable(child)
+ s.NotifyTaskEnqueued(ctx, child)
return &child, nil
}
@@ -986,6 +1248,7 @@ func (s *TaskService) RerunIssue(ctx context.Context, issueID pgtype.UUID, trigg
)
}
for _, t := range cancelled {
+ s.captureTaskCancelled(ctx, t)
s.ReconcileAgentStatus(ctx, t.AgentID)
s.broadcastTaskEvent(ctx, protocol.EventTaskCancelled, t)
}
@@ -1036,6 +1299,7 @@ func (s *TaskService) HandleFailedTasks(ctx context.Context, tasks []db.AgentTas
if t.FailureReason.Valid && t.FailureReason.String != "" {
failureReason = t.FailureReason.String
}
+ s.captureTaskFailed(ctx, t)
workspaceID := ""
if t.IssueID.Valid {
@@ -1229,7 +1493,8 @@ func priorityToInt(p string) int32 {
// row into agent_task_queue directly. Invalidates the empty-claim
// cache and kicks the daemon WS so the new task is claimed without
// waiting for the next poll.
-func (s *TaskService) NotifyTaskEnqueued(task db.AgentTaskQueue) {
+func (s *TaskService) NotifyTaskEnqueued(ctx context.Context, task db.AgentTaskQueue) {
+ s.captureTaskQueued(ctx, task)
s.notifyTaskAvailable(task)
}
diff --git a/server/pkg/db/generated/runtime.sql.go b/server/pkg/db/generated/runtime.sql.go
index 86b03592d8..a2f8f07630 100644
--- a/server/pkg/db/generated/runtime.sql.go
+++ b/server/pkg/db/generated/runtime.sql.go
@@ -381,7 +381,7 @@ SET status = 'offline', updated_at = now()
WHERE status = 'online'
AND id = ANY($1::uuid[])
AND last_seen_at < now() - make_interval(secs => $2::double precision)
-RETURNING id, workspace_id
+RETURNING id, workspace_id, owner_id, daemon_id, provider
`
type MarkRuntimesOfflineByIDsParams struct {
@@ -392,6 +392,9 @@ type MarkRuntimesOfflineByIDsParams struct {
type MarkRuntimesOfflineByIDsRow struct {
ID pgtype.UUID `json:"id"`
WorkspaceID pgtype.UUID `json:"workspace_id"`
+ OwnerID pgtype.UUID `json:"owner_id"`
+ DaemonID pgtype.Text `json:"daemon_id"`
+ Provider string `json:"provider"`
}
// Flips a known set of runtime IDs from online to offline. Paired with
@@ -414,7 +417,13 @@ func (q *Queries) MarkRuntimesOfflineByIDs(ctx context.Context, arg MarkRuntimes
items := []MarkRuntimesOfflineByIDsRow{}
for rows.Next() {
var i MarkRuntimesOfflineByIDsRow
- if err := rows.Scan(&i.ID, &i.WorkspaceID); err != nil {
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.OwnerID,
+ &i.DaemonID,
+ &i.Provider,
+ ); err != nil {
return nil, err
}
items = append(items, i)
@@ -488,7 +497,7 @@ func (q *Queries) RecordRuntimeLegacyDaemonID(ctx context.Context, arg RecordRun
}
const selectStaleOnlineRuntimes = `-- name: SelectStaleOnlineRuntimes :many
-SELECT id, workspace_id FROM agent_runtime
+SELECT id, workspace_id, owner_id, daemon_id, provider FROM agent_runtime
WHERE status = 'online'
AND last_seen_at < now() - make_interval(secs => $1::double precision)
`
@@ -496,6 +505,9 @@ WHERE status = 'online'
type SelectStaleOnlineRuntimesRow struct {
ID pgtype.UUID `json:"id"`
WorkspaceID pgtype.UUID `json:"workspace_id"`
+ OwnerID pgtype.UUID `json:"owner_id"`
+ DaemonID pgtype.Text `json:"daemon_id"`
+ Provider string `json:"provider"`
}
// Lists online runtimes whose last_seen_at exceeds the stale window. The
@@ -511,7 +523,13 @@ func (q *Queries) SelectStaleOnlineRuntimes(ctx context.Context, staleSeconds fl
items := []SelectStaleOnlineRuntimesRow{}
for rows.Next() {
var i SelectStaleOnlineRuntimesRow
- if err := rows.Scan(&i.ID, &i.WorkspaceID); err != nil {
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.OwnerID,
+ &i.DaemonID,
+ &i.Provider,
+ ); err != nil {
return nil, err
}
items = append(items, i)
@@ -639,8 +657,8 @@ type UpsertAgentRuntimeRow struct {
}
// (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.
+// that updated an existing row (false). Analytics reads this to fire
+// runtime_registered/runtime_ready only on first-time registration.
func (q *Queries) UpsertAgentRuntime(ctx context.Context, arg UpsertAgentRuntimeParams) (UpsertAgentRuntimeRow, error) {
row := q.db.QueryRow(ctx, upsertAgentRuntime,
arg.WorkspaceID,
diff --git a/server/pkg/db/queries/runtime.sql b/server/pkg/db/queries/runtime.sql
index 4a21af1d29..f9e34ab4c2 100644
--- a/server/pkg/db/queries/runtime.sql
+++ b/server/pkg/db/queries/runtime.sql
@@ -13,8 +13,8 @@ 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.
+-- that updated an existing row (false). Analytics reads this to fire
+-- runtime_registered/runtime_ready only on first-time registration.
INSERT INTO agent_runtime (
workspace_id,
daemon_id,
@@ -89,7 +89,7 @@ WHERE id = $1;
-- sweeper uses this as a candidate set, then optionally filters via the
-- LivenessStore before flipping rows to offline (a fresh Redis liveness
-- record means the DB row is just lagging, not actually dead).
-SELECT id, workspace_id FROM agent_runtime
+SELECT id, workspace_id, owner_id, daemon_id, provider FROM agent_runtime
WHERE status = 'online'
AND last_seen_at < now() - make_interval(secs => @stale_seconds::double precision);
@@ -110,7 +110,7 @@ SET status = 'offline', updated_at = now()
WHERE status = 'online'
AND id = ANY(@ids::uuid[])
AND last_seen_at < now() - make_interval(secs => @stale_seconds::double precision)
-RETURNING id, workspace_id;
+RETURNING id, workspace_id, owner_id, daemon_id, provider;
-- name: FailTasksForOfflineRuntimes :many
-- Marks dispatched/running tasks as failed when their runtime is offline.