Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Add optional company-scoped PostHog analytics (#1348)

Regan Bell68b5f5ba70bf
diff --git a/cli/src/commands/check.ts b/cli/src/commands/check.ts
index 6f9fd8708..e2218192b 100644
--- a/cli/src/commands/check.ts
+++ b/cli/src/commands/check.ts
@@ -95,6 +95,7 @@ export function runChecks(
secretNames.has(name) ||
(/(?:_SECRET|_TOKEN|_KEY|_CREDENTIALS?|PASSWORD)$/.test(name) &&
!name.endsWith("PUBLIC_KEY") &&
+ !(name === "POSTHOG_API_KEY" && /^phc_[A-Za-z0-9]+$/.test(value)) &&
!/^[.~/]/.test(value));
if (secretish) {
configError(
diff --git a/cli/test/check.test.ts b/cli/test/check.test.ts
index 1fc62bfd6..b9b971141 100644
--- a/cli/test/check.test.ts
+++ b/cli/test/check.test.ts
@@ -525,3 +525,15 @@ test("quiet checks reject invalid supplied sandbox credentials just like human c
rmSync(dir, { recursive: true, force: true });
}
});
+
+test("only public PostHog ingestion tokens may be configured as plaintext", () => {
+ for (const value of ["phc_example123", "phx_personal123", "private-token"]) {
+ const d = deployment(() => {}, { env: { core: { POSTHOG_API_KEY: value } } });
+ try {
+ if (value.startsWith("phc_")) assert.doesNotThrow(() => check(d));
+ else assert.throws(() => check(d), /POSTHOG_API_KEY belongs in the target secret store/);
+ } finally {
+ rmSync(d.dir, { recursive: true, force: true });
+ }
+ }
+});
diff --git a/plugins/web-ui/.env.example b/plugins/web-ui/.env.example
index 08c73b4e8..53ecd0008 100644
--- a/plugins/web-ui/.env.example
+++ b/plugins/web-ui/.env.example
@@ -5,3 +5,5 @@ WEB_UI_PUBLIC_URL=http://localhost:8096
WEB_UI_PRINCIPALS=
CORE_SIGNING_SECRET=
+POSTHOG_API_KEY=
+POSTHOG_HOST=https://us.i.posthog.com
diff --git a/plugins/web-ui/README.md b/plugins/web-ui/README.md
index ebf2a7ee9..1a56c6a4a 100644
--- a/plugins/web-ui/README.md
+++ b/plugins/web-ui/README.md
@@ -286,3 +286,21 @@ The welcome uses the organization's configured branding `orgName`, falling back
### Setup widgets in agent replies
In web chat, an assistant reply can include `::connect-apps{}` as a standalone paragraph to render the reusable app picker. The separate `::add-to-slack{}` directive renders the Slack setup action for administrators; include both to show both. It omits the welcome and animation and uses the signed-in viewer’s authorization routes. The Composio skill teaches this response for requests to connect apps or reopen setup. Code blocks, quotations, and inline examples remain ordinary text. The directive persists in the transcript and renders again when reopened. Connected-account status retains the same limitations as the onboarding picker and local return-flow preview.
+
+## Optional product analytics
+
+Set `POSTHOG_API_KEY` to a PostHog project ingestion token to enable browser
+analytics. `POSTHOG_HOST` defaults to `https://us.i.posthog.com` and must be an
+HTTPS origin. The authenticated `/me` response supplies this public configuration;
+the portal serves the same web application, so it needs no separate SDK.
+
+Events are explicit pageviews by navigation view, accepted `message_sent` events,
+and `session_started` for the first user message in a chat. Company grouping uses
+`CORE_ORG_ID`; user identities combine company and authenticated principal. Browser
+analytics is disabled during impersonation. Autocapture, replay, exception capture,
+performance capture and feature flags are disabled. Event properties exclude chat
+content, URLs, query strings, titles and referrers. Delivery is best effort.
+
+Set the same variables on core to capture `app_published` after a successful new
+application or version deployment. Core events use the application's creator and
+company, matching browser identity. No key means no analytics requests.
diff --git a/plugins/web-ui/package-lock.json b/plugins/web-ui/package-lock.json
index f6e105204..1a12fc346 100644
--- a/plugins/web-ui/package-lock.json
+++ b/plugins/web-ui/package-lock.json
@@ -23,7 +23,8 @@
"lru-cache": "^11.5.2",
"lucide": "^0.544.0",
"marked": "^18.0.5",
- "morphdom": "2.7.8"
+ "morphdom": "2.7.8",
+ "posthog-js": "1.433.10"
},
"devDependencies": {
"@types/jsdom": "^28.0.3",
@@ -681,6 +682,7 @@
}
],
"license": "MIT",
+ "peer": true,
"engines": {
"node": ">=20.19.0"
},
@@ -729,6 +731,7 @@
}
],
"license": "MIT",
+ "peer": true,
"engines": {
"node": ">=20.19.0"
}
@@ -1350,6 +1353,7 @@
"version": "0.2.1",
"resolved": "https://registry.npmjs.org/@mariozechner/mini-lit/-/mini-lit-0.2.1.tgz",
"integrity": "sha512-u300euLgCsDDlb8o2Wbz+55eSJga5X2vB58s9XBuFIr2Bi3iI+GMR7t/NYo/O6Vr6obXShXgYjR3SRUJVgo+kQ==",
+ "peer": true,
"dependencies": {
"@preact/signals-core": "^1.12.1",
"class-variance-authority": "^0.7.1",
@@ -1640,6 +1644,31 @@
],
"license": "MIT"
},
+ "node_modules/@posthog/browser-common": {
+ "version": "0.9.0",
+ "resolved": "https://registry.npmjs.org/@posthog/browser-common/-/browser-common-0.9.0.tgz",
+ "integrity": "sha512-EWoVzs1vVY7ihpn8yOjj3jyjriHUEEMVSBNL/TW3hk09fTriWRe76vJXrRg0G0yjTYxHmtlSkNn4mOV24ZEzzA==",
+ "license": "MIT",
+ "dependencies": {
+ "@posthog/core": "^1.54.2",
+ "@posthog/types": "^1.412.1"
+ }
+ },
+ "node_modules/@posthog/core": {
+ "version": "1.54.4",
+ "resolved": "https://registry.npmjs.org/@posthog/core/-/core-1.54.4.tgz",
+ "integrity": "sha512-Y5SWMUqeiq4R7h1ZflP0iGlqq1SSMNnFHz0XIUAXxuPDyOaZu1UVTefc2qCPRWPR3nQ9bx3LeQEBu9tw8fNHvg==",
+ "license": "MIT",
+ "dependencies": {
+ "@posthog/types": "^1.412.1"
+ }
+ },
+ "node_modules/@posthog/types": {
+ "version": "1.412.1",
+ "resolved": "https://registry.npmjs.org/@posthog/types/-/types-1.412.1.tgz",
+ "integrity": "sha512-FxXsb9YOOME8bJI5K09qKeSvLjnZQ2dPV7wZpI7a8sERQtXkAuhBcPB/balCnVE7TYwhgtHj5NQss9BgQ5bAfQ==",
+ "license": "MIT"
+ },
"node_modules/@preact/signals-core": {
"version": "1.14.2",
"resolved": "https://registry.npmjs.org/@preact/signals-core/-/signals-core-1.14.2.tgz",
@@ -2474,6 +2503,20 @@
"node": ">= 12"
}
},
+ "node_modules/core-js": {
+ "version": "3.50.0",
+ "resolved": "https://registry.npmjs.org/core-js/-/core-js-3.50.0.tgz",
+ "integrity": "sha512-BRWgOLKkFeCgRudR6zrs8p9XJZcE14grzKMMssoYrk6krtuEZ7MTKPIY5RzOnqsEKIR9kst7wNzphttraT+Yqw==",
+ "hasInstallScript": true,
+ "license": "MIT",
+ "engines": {
+ "node": "*"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/core-js"
+ }
+ },
"node_modules/core-util-is": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz",
@@ -2732,6 +2775,12 @@
"node": "^12.20 || >= 14.13"
}
},
+ "node_modules/fflate": {
+ "version": "0.4.9",
+ "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.4.9.tgz",
+ "integrity": "sha512-zdxgIEddhfsyCaWpJ2SdXEP8ZMrKJ6+5jl4OupODcywU0IhRk6gdXuVGcPICyfx2H97hVK7xmJtRLPjkxAX8Vw==",
+ "license": "MIT"
+ },
"node_modules/formdata-polyfill": {
"version": "4.0.10",
"resolved": "https://registry.npmjs.org/formdata-polyfill/-/formdata-polyfill-4.0.10.tgz",
@@ -3057,6 +3106,7 @@
"resolved": "https://registry.npmjs.org/lit/-/lit-3.3.3.tgz",
"integrity": "sha512-fycuvZg/hkpozL00lm1pEJH5nN/lr9ZXd6mJI2HSN4+Bzc+LDNdEApJ6HFbPkdFNHLvOplIIuJvxkS4XUxqirw==",
"license": "BSD-3-Clause",
+ "peer": true,
"dependencies": {
"@lit/reactive-element": "^2.1.0",
"lit-element": "^4.2.0",
@@ -3300,6 +3350,7 @@
"integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==",
"dev": true,
"license": "MIT",
+ "peer": true,
"engines": {
"node": ">=12"
},
@@ -3336,6 +3387,54 @@
"node": "^10 || ^12 || >=14"
}
},
+ "node_modules/posthog-js": {
+ "version": "1.433.10",
+ "resolved": "https://registry.npmjs.org/posthog-js/-/posthog-js-1.433.10.tgz",
+ "integrity": "sha512-IBb535Pr+QShN8Qc+6FbYN4gdDxTzRSx1ri9EHwdr57Ob2etyuuqLwCoOwvjHCrmG4xFKYdEf3jUuJ899kKWnA==",
+ "license": "(Apache-2.0 AND MIT)",
+ "dependencies": {
+ "@posthog/browser-common": "^0.9.0",
+ "@posthog/core": "^1.54.4",
+ "@posthog/types": "^1.412.1",
+ "core-js": "^3.49.0",
+ "dompurify": "^3.4.13",
+ "fflate": "^0.4.8",
+ "preact": "^10.29.3",
+ "query-selector-shadow-dom": "^1.0.1",
+ "web-vitals": "^6.2.1",
+ "web-vitals-soft-navs": "npm:[email protected]"
+ },
+ "peerDependencies": {
+ "@types/react": ">=16.8.0",
+ "react": ">=16.8.0"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "react": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/preact": {
+ "version": "10.29.8",
+ "resolved": "https://registry.npmjs.org/preact/-/preact-10.29.8.tgz",
+ "integrity": "sha512-ej2aVZ+vZ8WO7tvlQWRM9N63A0KzF9q4mWJfDUHgYaIofWY9hu74QdnQrjoPMmZi2/nZ5gN0bJCQF49xQqx09Q==",
+ "license": "MIT",
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/preact"
+ },
+ "peerDependencies": {
+ "preact-render-to-string": ">=5"
+ },
+ "peerDependenciesMeta": {
+ "preact-render-to-string": {
+ "optional": true
+ }
+ }
+ },
"node_modules/process-nextick-args": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz",
@@ -3375,6 +3474,12 @@
"node": ">=6"
}
},
+ "node_modules/query-selector-shadow-dom": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/query-selector-shadow-dom/-/query-selector-shadow-dom-1.0.1.tgz",
+ "integrity": "sha512-lT5yCqEBgfoMYpf3F2xQRK7zEr1rhIIZuceDK6+xRkJQ4NMbHTwXqk4NkwDwQMNqXgG9r9fyHnzwNVs6zV5KRw==",
+ "license": "MIT"
+ },
"node_modules/readable-stream": {
"version": "2.3.8",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz",
@@ -3560,6 +3665,7 @@
"resolved": "https://registry.npmjs.org/tailwind-merge/-/tailwind-merge-3.6.0.tgz",
"integrity": "sha512-uxL7qAVQriqRQPAyK3pj66VqskWqoZ37PW94jwOTwNfq/z9oyu1V+eqrZqtR2+fCiXdYOZe/Modt8GtvqNzu+w==",
"license": "MIT",
+ "peer": true,
"funding": {
"type": "github",
"url": "https://github.com/sponsors/dcastil"
@@ -3814,6 +3920,19 @@
"node": ">= 8"
}
},
+ "node_modules/web-vitals": {
+ "version": "6.2.2",
+ "resolved": "https://registry.npmjs.org/web-vitals/-/web-vitals-6.2.2.tgz",
+ "integrity": "sha512-oto5x6dLEgrRqfcWed+pZEUb2q6ikbFmqF54CRDhI/QGbn+qxC49b4C4OkbH+kb9C3a8shpFD3SgR9kRcs80ZQ==",
+ "license": "Apache-2.0"
+ },
+ "node_modules/web-vitals-soft-navs": {
+ "name": "web-vitals",
+ "version": "6.2.1",
+ "resolved": "https://registry.npmjs.org/web-vitals/-/web-vitals-6.2.1.tgz",
+ "integrity": "sha512-rLcLXA2sx6+9dE88NHFubwTtGxpK4yYBLj6qHPdFoCaLr0cXGb4efOqtKLlm4loGA4OEKHIQKMKzZkKyOh5ctw==",
+ "license": "Apache-2.0"
+ },
"node_modules/webidl-conversions": {
"version": "8.0.1",
"resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-8.0.1.tgz",
@@ -3940,6 +4059,7 @@
"resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz",
"integrity": "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==",
"license": "MIT",
+ "peer": true,
"funding": {
"url": "https://github.com/sponsors/colinhacks"
}
diff --git a/plugins/web-ui/package.json b/plugins/web-ui/package.json
index 462d98837..a8c039bb8 100644
--- a/plugins/web-ui/package.json
+++ b/plugins/web-ui/package.json
@@ -31,7 +31,8 @@
"lru-cache": "^11.5.2",
"lucide": "^0.544.0",
"marked": "^18.0.5",
- "morphdom": "2.7.8"
+ "morphdom": "2.7.8",
+ "posthog-js": "1.433.10"
},
"devDependencies": {
"@types/jsdom": "^28.0.3",
diff --git a/plugins/web-ui/server/index.ts b/plugins/web-ui/server/index.ts
index ac9102974..729c4bb42 100644
--- a/plugins/web-ui/server/index.ts
+++ b/plugins/web-ui/server/index.ts
@@ -172,13 +172,30 @@ const CONTENT_TYPES: Record<string, string> = {
".wasm": "application/wasm",
};
+const analyticsKey = process.env.POSTHOG_API_KEY?.trim();
+if (analyticsKey && !/^phc_[A-Za-z0-9]+$/.test(analyticsKey))
+ throw new Error("POSTHOG_API_KEY must be a public project ingestion token");
+const analyticsHost = new URL((analyticsKey && process.env.POSTHOG_HOST?.trim()) || "https://us.i.posthog.com");
+if (
+ analyticsKey &&
+ (analyticsHost.protocol !== "https:" ||
+ analyticsHost.username ||
+ analyticsHost.password ||
+ analyticsHost.search ||
+ analyticsHost.hash ||
+ analyticsHost.pathname !== "/")
+) {
+ throw new Error("POSTHOG_HOST must be an HTTPS origin");
+}
+const analyticsConfig = analyticsKey ? { apiKey: analyticsKey, host: analyticsHost.origin } : undefined;
+
const SPA_CSP = [
"default-src 'self'",
"script-src 'self' 'wasm-unsafe-eval'",
"style-src 'self' 'unsafe-inline'",
"img-src 'self' data: blob: https:",
"font-src 'self' data:",
- "connect-src 'self'",
+ `connect-src 'self'${analyticsConfig ? ` ${analyticsConfig.host}` : ""}`,
"frame-src 'self' data: https:",
"worker-src 'self' blob:",
"frame-ancestors 'self'",
@@ -1224,6 +1241,7 @@ const apiRoutes: readonly WebRoute[] = [
user,
org: ORG,
companyName: companyBranding.orgName?.trim() || null,
+ ...(analyticsConfig && !resolveIdentity(req)?.impersonator ? { analytics: analyticsConfig } : {}),
mode: AUTH_MODE,
slackWorkspaceUrl: workspaceUrl,
individualModelAuth: parsed.individualModelAuth === true,
diff --git a/plugins/web-ui/src/core-bridge.ts b/plugins/web-ui/src/core-bridge.ts
index 25d6e75c9..49129cfce 100644
--- a/plugins/web-ui/src/core-bridge.ts
+++ b/plugins/web-ui/src/core-bridge.ts
@@ -1,3 +1,4 @@
+import { captureMessage } from "./product-analytics.ts";
import { streamedAnswer } from "./timeline.ts";
import { EventType } from "@tanstack/ai/client";
import { fetchServerSentEvents, StreamProcessor } from "@tanstack/ai-client";
@@ -1173,6 +1174,14 @@ async function drive(
});
if (submit.runId) {
+ if (!opener) {
+ const userMessages = agent.state.messages.filter(
+ (message) =>
+ (message.role === "user" || message.role === "user-with-attachments") &&
+ !(message as { opener?: boolean }).opener,
+ );
+ captureMessage(submit.runId, userMessages.length === 1);
+ }
const message = agent.state.messages.find((message) => idempotencyKey && sendKeyOf(message) === idempotencyKey);
if (message) (message as unknown as HistoryUserMessage).runId = submit.runId;
await followRun(stream, partial, submit.runId, signal, notify, undefined, slot, gen);
diff --git a/plugins/web-ui/src/product-analytics.ts b/plugins/web-ui/src/product-analytics.ts
new file mode 100644
index 000000000..c21e9ebfe
--- /dev/null
+++ b/plugins/web-ui/src/product-analytics.ts
@@ -0,0 +1,116 @@
+import type { Me } from "./shell-state";
+import type { PostHog, PostHogConfig } from "posthog-js";
+
+let client: PostHog | undefined;
+let initialized = false;
+let generation = 0;
+let currentView = "chats";
+let lastCapturedView: string | undefined;
+const sent = new Set<string>();
+const allowedProperties = new Set([
+ "token",
+ "distinct_id",
+ "$device_id",
+ "$user_id",
+ "$session_id",
+ "$window_id",
+ "$groups",
+ "$group_type",
+ "$group_key",
+ "$group_set",
+ "$set",
+ "$set_once",
+ "$anon_distinct_id",
+ "$lib",
+ "$lib_version",
+ "$process_person_profile",
+ "$insert_id",
+ "company_id",
+ "surface",
+ "view",
+]);
+
+export function stopAnalytics(): void {
+ generation++;
+ client?.set_config({ before_send: () => null });
+ client = undefined;
+ sent.clear();
+ lastCapturedView = undefined;
+ currentView = "chats";
+}
+
+export async function initializeAnalytics(me: Me, view = "chats"): Promise<void> {
+ currentView = view;
+ const current = ++generation;
+ client?.set_config({ before_send: () => null });
+ client = undefined;
+ sent.clear();
+ lastCapturedView = undefined;
+ if (!me.analytics?.apiKey || me.impersonatedBy) return;
+ try {
+ const { default: posthog } = await import("posthog-js");
+ if (current !== generation) return;
+ const options: Partial<PostHogConfig> = {
+ api_host: me.analytics.host,
+ persistence: "memory",
+ bootstrap: { distinctID: JSON.stringify([me.org, me.user]), isIdentifiedID: true },
+ autocapture: false,
+ capture_pageview: false,
+ capture_pageleave: false,
+ capture_exceptions: false,
+ capture_performance: false,
+ disable_session_recording: true,
+ disable_surveys: true,
+ disable_external_dependency_loading: true,
+ advanced_disable_flags: true,
+ person_profiles: "identified_only",
+ save_referrer: false,
+ save_campaign_params: false,
+ before_send: (event) => {
+ if (!event) return null;
+ for (const key of Object.keys(event.properties)) {
+ if (!allowedProperties.has(key)) delete event.properties[key];
+ }
+ delete event.properties.$set;
+ delete event.properties.$set_once;
+ delete event.$set_once;
+ delete event.$set;
+ return event;
+ },
+ };
+ if (initialized) posthog.set_config({ ...options, token: me.analytics.apiKey });
+ else posthog.init(me.analytics.apiKey, options);
+ initialized = true;
+ if (posthog.get_distinct_id() !== JSON.stringify([me.org, me.user])) posthog.reset();
+ posthog.identify(JSON.stringify([me.org, me.user]));
+ posthog.group("company", me.org);
+ posthog.register({ company_id: me.org, surface: "web" });
+ client = posthog;
+ capturePageview(currentView);
+ } catch {
+ client = undefined;
+ }
+}
+
+export function capturePageview(view: string): void {
+ currentView = view;
+ if (!client || lastCapturedView === view) return;
+ try {
+ client.capture("$pageview", { view });
+ lastCapturedView = view;
+ } catch {
+ return;
+ }
+}
+
+export function captureMessage(runId: string, firstMessage: boolean): void {
+ if (!client || sent.has(runId)) return;
+ sent.add(runId);
+ if (sent.size > 1000) sent.delete(sent.values().next().value!);
+ try {
+ client.capture("message_sent", { $insert_id: `${runId}:message_sent` });
+ if (firstMessage) client.capture("session_started", { $insert_id: `${runId}:session_started` });
+ } catch {
+ return;
+ }
+}
diff --git a/plugins/web-ui/src/shell-state.ts b/plugins/web-ui/src/shell-state.ts
index d1b963bbf..df6172484 100644
--- a/plugins/web-ui/src/shell-state.ts
+++ b/plugins/web-ui/src/shell-state.ts
@@ -3,6 +3,7 @@ import type { SuggestedActivity } from "../../chassis/src/suggested-activities.t
export type AuthMode = "portal" | "dev";
export interface Me {
+ analytics?: { apiKey: string; host: string };
companyName?: string | null;
welcomeCohort?: string;
suggestedActivities?: SuggestedActivity[];
diff --git a/plugins/web-ui/src/shell.ts b/plugins/web-ui/src/shell.ts
index a29de4f96..83f26de1c 100644
--- a/plugins/web-ui/src/shell.ts
+++ b/plugins/web-ui/src/shell.ts
@@ -1,3 +1,4 @@
+import { initializeAnalytics, capturePageview, stopAnalytics } from "./product-analytics";
import { captureConnectionReturn } from "./connection-return";
import { openModelConnectManager, renderModelConnectGate } from "./model-connect";
import { html, nothing, render, type TemplateResult } from "lit";
@@ -221,6 +222,7 @@ const ICON = {
};
export async function signOut(): Promise<void> {
+ stopAnalytics();
const portal = authMode === "portal";
if (!portal) {
try {
@@ -438,6 +440,7 @@ export type AuthGate =
| { kind: "dev"; value?: string; error?: string; pending?: boolean };
export function renderAuthGate(gate: AuthGate): void {
+ stopAnalytics();
shellMounted = false;
const body = (() => {
switch (gate.kind) {
@@ -678,6 +681,7 @@ export function switchView(v: View): void {
return;
}
appState.currentView = v;
+ capturePageview(v);
appState.viewRenderSeq++;
sessionsState.openMenuId = null;
sessionsState.renamingId = null;
@@ -1031,6 +1035,7 @@ export async function boot(): Promise<void> {
}
resetKeychainState();
appState.me = (await r.json()) as Me;
+ void initializeAnalytics(appState.me, isView(wanted) && canView(wanted) ? wanted : "chats");
authMode = appState.me.mode ?? "portal";
clearPortalAttempt();
if (appState.me.individualModelAuth && !appState.me.modelAuthConnected) {
diff --git a/plugins/web-ui/test/product-analytics-routes.test.ts b/plugins/web-ui/test/product-analytics-routes.test.ts
new file mode 100644
index 000000000..6eeb5d544
--- /dev/null
+++ b/plugins/web-ui/test/product-analytics-routes.test.ts
@@ -0,0 +1,62 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import { createServer } from "node:http";
+import type { AddressInfo } from "node:net";
+import { mintPortalIdentity, PORTAL_IDENTITY_HEADER } from "../../chassis/src/portal-identity.ts";
+
+let coreStatus = 200;
+const core = createServer((req, res) => {
+ res.writeHead(coreStatus, { "content-type": "application/json" });
+ if (req.url?.startsWith("/v1/approvals/approval-1?")) {
+ res.end(
+ JSON.stringify({
+ request: {
+ actor: { externalId: "[email protected]" },
+ conversation: { threadRef: "web:[email protected]:default" },
+ text: "private approval text",
+ },
+ }),
+ );
+ return;
+ }
+ res.end(JSON.stringify(req.url?.startsWith("/v1/turns") ? { runId: "accepted-run" } : {}));
+});
+await new Promise<void>((resolve) => core.listen(0, "127.0.0.1", resolve));
+const secret = "analytics-route-test-secret";
+process.env.CORE_API_URL = `http://127.0.0.1:${(core.address() as AddressInfo).port}`;
+process.env.CORE_ORG_ID = "acme";
+process.env.CORE_SIGNING_SECRET = secret;
+process.env.PORTAL_IDENTITY_SECRET = secret;
+process.env.ALLOW_UNSIGNED_TEST_IDENTITY = "0";
+process.env.POSTHOG_API_KEY = "phc_test";
+process.env.POSTHOG_HOST = "https://us.i.posthog.com";
+const { handler } = await import("../server/index.ts");
+const surface = createServer((req, res) => void handler(req, res));
+await new Promise<void>((resolve) => surface.listen(0, "127.0.0.1", resolve));
+const base = `http://127.0.0.1:${(surface.address() as AddressInfo).port}`;
+const headers = (imp?: string) => ({
+ "content-type": "application/json",
+ [PORTAL_IDENTITY_HEADER]: mintPortalIdentity(
+ { p: "[email protected]", exp: Date.now() + 60_000, ...(imp ? { imp } : {}) },
+ secret,
+ ),
+});
+
+test.after(() => {
+ surface.closeAllConnections();
+ surface.close();
+ core.closeAllConnections();
+ core.close();
+});
+
+test("analytics config is authenticated, company-scoped and omitted during impersonation", async () => {
+ assert.equal((await fetch(`${base}/me`)).status, 401);
+ const response = await fetch(`${base}/me`, { headers: headers() });
+ const body = await response.json();
+ assert.deepEqual(body.analytics, { apiKey: "phc_test", host: "https://us.i.posthog.com" });
+ assert.equal(body.org, "acme");
+ assert.equal(body.user, "[email protected]");
+ assert.equal((await (await fetch(`${base}/me`, { headers: headers("admin") })).json()).analytics, undefined);
+ coreStatus = 503;
+ assert.equal((await fetch(`${base}/me`, { headers: headers() })).status, 503);
+});
diff --git a/src/config.ts b/src/config.ts
index 9b96d3bac..86aa63da9 100644
--- a/src/config.ts
+++ b/src/config.ts
@@ -42,6 +42,7 @@ import {
import { resolveSwarmSettings, type SwarmSettings } from "./swarms/swarm-settings.ts";
export interface Config {
+ productAnalytics?: { apiKey: string; host?: string };
slackContextSource?: SlackContextSource;
suggestedActivitiesEnabled?: boolean;
suggestedActivitiesContext?: string;
@@ -1280,6 +1281,9 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config {
port: numEnvStrict("PORT", env.PORT) ?? CONFIG_DEFAULTS.port,
dataDir,
orgId: env.ORG_ID ?? DEFAULT_ORG_ID,
+ ...(env.POSTHOG_API_KEY?.trim()
+ ? { productAnalytics: { apiKey: env.POSTHOG_API_KEY.trim(), host: env.POSTHOG_HOST?.trim() } }
+ : {}),
sessionStore: env.SESSION_STORE === "postgres" ? "postgres" : "memory",
...(env.DATABASE_URL ? { databaseUrl: env.DATABASE_URL } : {}),
...(env.DATABASE_POOL_URL ? { databasePoolUrl: env.DATABASE_POOL_URL } : {}),
diff --git a/src/deploy/deploy-service.ts b/src/deploy/deploy-service.ts
index d52a57221..00653b00f 100644
--- a/src/deploy/deploy-service.ts
+++ b/src/deploy/deploy-service.ts
@@ -113,6 +113,7 @@ export interface DeployServiceDeps {
provider: DeployProvider;
deployDir: string;
auditLog: AuditLog;
+ appPublished?: (principal: string, deploymentId: string, version: number) => Promise<void>;
acl: AclStore;
leaderLease?: LeaderLease;
advisoryLock?: AdvisoryLock;
@@ -371,6 +372,7 @@ export function createDeployService(deps: DeployServiceDeps): DeployService {
});
const endpoint = await applyVersion(d.id, d.versions[0]!);
await markVersionRunning(d.id, d.versions[0]!.version, endpoint);
+ void deps.appPublished?.(input.createdBy, d.id, d.versions[0]!.version).catch(() => {});
deps.auditLog.record({
at: Date.now(),
principalId: input.createdBy,
@@ -400,6 +402,7 @@ export function createDeployService(deps: DeployServiceDeps): DeployService {
});
const endpoint = await applyVersion(id, v, before.appliedVersion ?? before.currentVersion, input.alwaysOn);
await markVersionRunning(id, v.version, endpoint);
+ void deps.appPublished?.(before.createdBy, id, v.version).catch(() => {});
deps.auditLog.record({
at: Date.now(),
principalId: before.createdBy,
@@ -590,6 +593,7 @@ export function createDeployService(deps: DeployServiceDeps): DeployService {
if (!v) return result;
const endpoint = await applyVersion(id, v, before.appliedVersion ?? before.currentVersion);
await markVersionRunning(id, v.version, endpoint);
+ void deps.appPublished?.(before.createdBy, id, v.version).catch(() => {});
deps.auditLog.record({
at: Date.now(),
principalId: before.createdBy,
diff --git a/src/util/product-analytics.ts b/src/util/product-analytics.ts
new file mode 100644
index 000000000..8cc82538f
--- /dev/null
+++ b/src/util/product-analytics.ts
@@ -0,0 +1,41 @@
+export function createProductAnalytics(
+ companyId: string,
+ config: { apiKey?: string; host?: string } = {},
+ send: typeof fetch = fetch,
+): { appPublished(principal: string, deploymentId: string, version: number): Promise<void> } {
+ const apiKey = config.apiKey?.trim();
+ const host = (config.host?.trim() || "https://us.i.posthog.com").replace(/\/$/, "");
+ let inFlight = 0;
+ return {
+ async appPublished(principal, deploymentId, version) {
+ if (!apiKey || !companyId || !principal || inFlight >= 16) return;
+ inFlight++;
+ try {
+ const response = await send(`${host}/i/v0/e/`, {
+ method: "POST",
+ redirect: "error",
+ signal: AbortSignal.timeout(2_000),
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({
+ api_key: apiKey,
+ event: "app_published",
+ timestamp: new Date().toISOString(),
+ properties: {
+ distinct_id: JSON.stringify([companyId, principal]),
+ company_id: companyId,
+ $groups: { company: companyId },
+ $insert_id: `${deploymentId}:${version}:app_published`,
+ $geoip_disable: true,
+ surface: "core",
+ },
+ }),
+ });
+ await response.body?.cancel();
+ } catch {
+ return;
+ } finally {
+ inFlight--;
+ }
+ },
+ };
+}
diff --git a/src/wiring.ts b/src/wiring.ts
index 42d53ac56..7a4f1a015 100644
--- a/src/wiring.ts
+++ b/src/wiring.ts
@@ -1,3 +1,4 @@
+import { createProductAnalytics } from "./util/product-analytics.ts";
import { createAdmittedWork } from "./util/admitted-work.ts";
import { runSessionSmoke } from "./deployment/postdeploy-smoke.ts";
import {
@@ -1525,6 +1526,7 @@ export function buildApp(
const deployGitSecret = config.signingSecret;
const deployGitBase = config.apiBaseUrl;
const deployService = createDeployService({
+ appPublished: createProductAnalytics(config.orgId, config.productAnalytics).appPublished,
deployStore,
provider: deployProvider,
deployDir: join(config.dataDir, "deployments"),
diff --git a/test/product-analytics.test.ts b/test/product-analytics.test.ts
new file mode 100644
index 000000000..74a49641c
--- /dev/null
+++ b/test/product-analytics.test.ts
@@ -0,0 +1,48 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { createProductAnalytics } from "../src/util/product-analytics.ts";
+
+test("disabled analytics makes no requests", async () => {
+ let requests = 0;
+ const analytics = createProductAnalytics("company", {}, async () => {
+ requests += 1;
+ return new Response("ok");
+ });
+ await analytics.appPublished("person", "app", 1);
+ assert.equal(requests, 0);
+});
+
+test("publication has matching company identity, groups and deduplication without app content", async () => {
+ let body: Record<string, any> = {};
+ const analytics = createProductAnalytics("company", { apiKey: "public-token" }, async (url, init) => {
+ assert.equal(url, "https://us.i.posthog.com/i/v0/e/");
+ assert.equal(init?.redirect, "error");
+ body = JSON.parse(String(init?.body));
+ return new Response("ok");
+ });
+ await analytics.appPublished("person", "app", 2);
+ assert.equal(body.event, "app_published");
+ assert.equal(body.properties.distinct_id, JSON.stringify(["company", "person"]));
+ assert.deepEqual(body.properties.$groups, { company: "company" });
+ assert.equal(body.properties.$insert_id, "app:2:app_published");
+ assert.deepEqual(
+ Object.keys(body.properties).sort(),
+ ["distinct_id", "company_id", "$groups", "$insert_id", "$geoip_disable", "surface"].sort(),
+ );
+});
+
+test("delivery failures cannot fail publication and concurrent requests are bounded", async () => {
+ const failing = createProductAnalytics("company", { apiKey: "token" }, async () => {
+ throw Error("offline");
+ });
+ await assert.doesNotReject(failing.appPublished("person", "app", 1));
+ const releases: Array<() => void> = [];
+ const bounded = createProductAnalytics("company", { apiKey: "token" }, async () => {
+ await new Promise<void>((resolve) => releases.push(resolve));
+ return new Response("ok");
+ });
+ const requests = Array.from({ length: 20 }, () => bounded.appPublished("person", "app", 1));
+ assert.equal(releases.length, 16);
+ releases.forEach((release) => release());
+ await Promise.all(requests);
+});