Skip to content

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

feat(cli): send telemetry direct to PostHog and stitch install→Apollo identity

Kshitij Jhunjhunwala06e97b71794e
diff --git a/ts/packages/cli/CHANGELOG.md b/ts/packages/cli/CHANGELOG.md
index 87585eff7..5ec532e78 100644
--- a/ts/packages/cli/CHANGELOG.md
+++ b/ts/packages/cli/CHANGELOG.md
@@ -1,5 +1,9 @@
# @composio/cli
+## Unreleased
+
+- Telemetry now delivers directly to PostHog instead of through the Apollo analytics endpoint. This fixes the dark top-of-funnel: pre-login `install`/`setup`/`plugin-setup` events no longer require a logged-in API base URL, so they are captured under the anonymous `install_id`. At login the CLI persists the Apollo `org_member.id` and fires a single `$create_alias`, so post-login events (and all later CLI activity) resolve to the same PostHog person as web onboarding. Existing opt-outs (`COMPOSIO_CLI_TELEMETRY_DISABLED`, `TELEMETRY_DISABLED`, `COMPOSIO_DISABLE_TELEMETRY`, `CI`, `NODE_ENV=test`) are unchanged, and no secrets or tool-argument values are ever sent.
+
## 0.3.0
### Security
diff --git a/ts/packages/cli/src/analytics/dispatch.ts b/ts/packages/cli/src/analytics/dispatch.ts
index 8ef3a9377..11d12f4b3 100644
--- a/ts/packages/cli/src/analytics/dispatch.ts
+++ b/ts/packages/cli/src/analytics/dispatch.ts
@@ -23,9 +23,13 @@ const INTERNAL_CODACT_FAILURE_WORKER_FLAG = '__codact-failure-worker';
const COMPOSIO_DIR = '.composio';
const ANALYTICS_STATE_FILE_NAME = 'analytics.json';
const CONSUMER_SHORT_TERM_CACHE_FILE_NAME = 'consumer-short-term-cache.json';
-const CLI_ANALYTICS_PATH = '/api/v3/cli/analytics';
const CLI_CODACT_FAILURES_PATH = '/api/v3/cli/codact_failures';
+// PostHog's single-event capture endpoint expects `$create_alias` to merge an
+// anonymous person into an identified one (`properties.alias` -> `distinct_id`).
+const POSTHOG_ALIAS_EVENT = '$create_alias';
+const POSTHOG_LIB = 'composio-cli';
+
export type CliCodactFailureType = 'wrong_tool_slug' | 'wrong_tool_input_param';
export type CliCodactFailureToolInfo = {
@@ -98,6 +102,24 @@ const analyticsDisabled = environmentProvider.load(
)
);
+// Resolves the direct-to-PostHog transport target. Both fields fall back to the
+// embedded constants; env overrides exist for tests and staging. Crucially this
+// does NOT depend on the Composio API base URL (which is only written at login),
+// so pre-login install/setup events can be delivered.
+const getPostHogConfig = environmentProvider
+ .load(
+ Config.all({
+ ingestUrl: optionalString('COMPOSIO_POSTHOG_INGEST_URL'),
+ projectKey: optionalString('COMPOSIO_POSTHOG_KEY'),
+ })
+ )
+ .pipe(
+ Effect.map(({ ingestUrl, projectKey }) => ({
+ ingestUrl: configuredString(ingestUrl) ?? constants.COMPOSIO_POSTHOG_INGEST_URL,
+ projectKey: configuredString(projectKey) ?? constants.COMPOSIO_POSTHOG_PROJECT_KEY,
+ }))
+ );
+
const jsonFromString = Schema.parseJson();
const prettyJsonFromString = Schema.parseJson({ space: 2 });
const decodeJson = Schema.decodeUnknown(jsonFromString);
@@ -153,10 +175,22 @@ const readOptionalJson = <A>(filePath: string) =>
return (yield* decodeJson(raw)) as A;
}).pipe(Effect.catchAll(() => Effect.succeed(undefined)));
-const hashString = (value: string): string => djb2Hash(value).toString(16).padStart(8, '0');
+// Persisted `~/.composio/analytics.json`. `install_id` is the anonymous device
+// UUID; `apollo_user_id` (the Apollo `org_member.id`, persisted at login) becomes
+// the PostHog identity so CLI events join the same person as web onboarding.
+type AnalyticsState = {
+ readonly install_id?: string;
+ readonly apollo_user_id?: string;
+ readonly created_at?: string;
+};
const makeInstallId = Effect.sync(() => crypto.randomUUID());
+const readAnalyticsState = Effect.gen(function* () {
+ const paths = yield* getAnalyticsPaths;
+ return yield* readOptionalJson<AnalyticsState>(paths.analyticsStatePath);
+});
+
const getOrCreateInstallId = Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const paths = yield* getAnalyticsPaths;
@@ -165,7 +199,7 @@ const getOrCreateInstallId = Effect.gen(function* () {
.makeDirectory(paths.analyticsDir, { recursive: true })
.pipe(Effect.catchAll(() => Effect.void));
- const state = yield* readOptionalJson<{ install_id?: unknown }>(paths.analyticsStatePath);
+ const state = yield* readOptionalJson<AnalyticsState>(paths.analyticsStatePath);
if (typeof state?.install_id === 'string' && state.install_id.length > 0) {
return state.install_id;
}
@@ -173,6 +207,7 @@ const getOrCreateInstallId = Effect.gen(function* () {
const installId = yield* makeInstallId;
const createdAt = DateTime.formatIso(yield* DateTime.now);
const contents = yield* encodeJson({
+ ...(state ?? {}),
install_id: installId,
created_at: createdAt,
});
@@ -180,6 +215,35 @@ const getOrCreateInstallId = Effect.gen(function* () {
return installId;
}).pipe(Effect.catchAll(() => makeInstallId));
+const readApolloUserId = Effect.map(readAnalyticsState, state =>
+ typeof state?.apollo_user_id === 'string' && state.apollo_user_id.length > 0
+ ? state.apollo_user_id
+ : null
+);
+
+// Persists the Apollo `org_member.id` into the analytics state, preserving the
+// existing `install_id`/`created_at` so the anonymous device identity is kept
+// for the login-time alias. Best-effort: never surfaces or throws.
+const persistApolloUserId = (installId: string, apolloUserId: string) =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const paths = yield* getAnalyticsPaths;
+
+ yield* fs
+ .makeDirectory(paths.analyticsDir, { recursive: true })
+ .pipe(Effect.catchAll(() => Effect.void));
+
+ const state = yield* readOptionalJson<AnalyticsState>(paths.analyticsStatePath);
+ const createdAt = state?.created_at ?? DateTime.formatIso(yield* DateTime.now);
+ const contents = yield* encodeJson({
+ ...(state ?? {}),
+ install_id: state?.install_id ?? installId,
+ apollo_user_id: apolloUserId,
+ created_at: createdAt,
+ });
+ yield* fs.writeFileString(paths.analyticsStatePath, contents);
+ }).pipe(Effect.catchAll(() => Effect.void));
+
const readUserConfig = Effect.gen(function* () {
const paths = yield* getAnalyticsPaths;
return yield* readOptionalJson<{ api_key?: unknown; base_url?: unknown }>(paths.userConfigPath);
@@ -199,10 +263,12 @@ const getUserApiKey = Effect.gen(function* () {
: null;
});
+// Post-login events key on the Apollo `org_member.id` (persisted at login) so
+// they resolve to the same PostHog person as web onboarding. Pre-login, the raw
+// `install_id` is the distinct id (NOT wrapped as `anon_<id>` — the login-time
+// `$create_alias` merges this exact value into the Apollo person).
const getDistinctId = (installId: string) =>
- Effect.map(getUserApiKey, userApiKey =>
- userApiKey ? `user_${hashString(userApiKey)}` : `anon_${installId}`
- );
+ Effect.map(readApolloUserId, apolloUserId => apolloUserId ?? installId);
const cwdHash = (cwd: string): string => djb2Hash(cwd).toString(36);
@@ -256,10 +322,6 @@ export const readApiBaseUrl = Effect.gen(function* () {
: null;
}).pipe(Effect.catchAllCause(() => Effect.succeed(null)));
-const getAnalyticsEndpoint = Effect.map(readApiBaseUrl, baseUrl =>
- baseUrl ? `${baseUrl}${CLI_ANALYTICS_PATH}` : null
-);
-
const getCliCodactFailuresEndpoint = Effect.map(readApiBaseUrl, baseUrl =>
baseUrl ? `${baseUrl}${CLI_CODACT_FAILURES_PATH}` : null
);
@@ -298,40 +360,57 @@ const spawnWorker = (command: string, args: ReadonlyArray<string>) =>
);
});
-const captureToComposioAnalytics = (envelope: AnalyticsEnvelope) =>
+// Shapes an analytics envelope into a PostHog single-event capture body. The
+// public project write key authenticates the ingest in-band (no user API key),
+// which is what lets pre-login events send. Only allowlisted, already-shaped
+// properties from the event builders flow through here — no secrets or tool-arg
+// values (see events.ts).
+const buildPostHogBody = (envelope: AnalyticsEnvelope, projectKey: string) => ({
+ api_key: projectKey,
+ event: envelope.event,
+ distinct_id: envelope.distinctId,
+ timestamp: envelope.sentAt,
+ properties: {
+ ...(envelope.properties ?? {}),
+ install_id: envelope.installId,
+ $lib: POSTHOG_LIB,
+ $lib_version: constants.APP_VERSION,
+ },
+});
+
+const captureToPostHog = (envelope: AnalyticsEnvelope) =>
Effect.gen(function* () {
- const endpoint = yield* getAnalyticsEndpoint;
const disabled = yield* analyticsDisabled;
- if (!endpoint || disabled) {
- yield* telemetryDebugLog('delivery_skipped', {
- reason: disabled ? 'disabled' : 'missing_endpoint',
- endpoint,
+ const { ingestUrl, projectKey } = yield* getPostHogConfig;
+ if (disabled || projectKey.length === 0) {
+ yield* telemetryDebugLog('posthog_delivery_skipped', {
+ reason: disabled ? 'disabled' : 'missing_project_key',
+ endpoint: ingestUrl,
eventName: envelope.event,
});
return;
}
const httpClient = yield* HttpClient.HttpClient;
- const userApiKey = yield* getUserApiKey;
- const request = yield* HttpClientRequest.post(endpoint).pipe(
- HttpClientRequest.setHeaders({
- 'x-composio-analytics-source': 'cli',
- ...(userApiKey ? { 'x-user-api-key': userApiKey } : {}),
- }),
- HttpClientRequest.bodyJson(envelope)
+ const request = yield* HttpClientRequest.post(ingestUrl).pipe(
+ HttpClientRequest.setHeader('x-composio-analytics-source', 'cli'),
+ HttpClientRequest.bodyJson(buildPostHogBody(envelope, projectKey))
);
const response = yield* httpClient.execute(request);
const responseOk = response.status >= 200 && response.status < 300;
const debugEnabled = yield* telemetryDebugEnabled;
const responseBody = !responseOk && debugEnabled ? yield* response.text : undefined;
- yield* telemetryDebugLog(responseOk ? 'delivery_succeeded' : 'delivery_failed', {
- endpoint,
- eventName: envelope.event,
- status: response.status,
- ok: responseOk,
- responseBody: responseBody?.slice(0, 1000),
- });
+ yield* telemetryDebugLog(
+ responseOk ? 'posthog_delivery_succeeded' : 'posthog_delivery_failed',
+ {
+ endpoint: ingestUrl,
+ eventName: envelope.event,
+ status: response.status,
+ ok: responseOk,
+ responseBody: responseBody?.slice(0, 1000),
+ }
+ );
});
type CliCodactFailureBody = {
@@ -425,20 +504,32 @@ const captureToComposioCodactFailures = (failure: CliCodactFailure) =>
});
});
+// Encodes an envelope and hands it to the detached best-effort worker, which
+// delivers it directly to PostHog. Shared by event tracking and login aliasing.
+const enqueuePostHogEnvelope = (envelope: AnalyticsEnvelope) =>
+ Effect.gen(function* () {
+ yield* telemetryDebugLog('enqueue', { envelope });
+ const serializedEnvelope = yield* encodeJson(envelope);
+ const encodedPayload = Encoding.encodeBase64Url(serializedEnvelope);
+ const { command, args } = yield* getWorkerSpawnArgs(
+ INTERNAL_ANALYTICS_WORKER_FLAG,
+ encodedPayload
+ );
+ yield* spawnWorker(command, args);
+ });
+
export const trackCliEventEffect = (event: TrackEvent) =>
Effect.gen(function* () {
if (!event) {
return;
}
- const endpoint = yield* getAnalyticsEndpoint;
+ // The direct PostHog transport carries a fixed endpoint + embedded public
+ // key, so — unlike the old Apollo path — there is no base-URL gate here and
+ // pre-login install/setup events are delivered.
const disabled = yield* analyticsDisabled;
- if (disabled || !endpoint) {
- yield* telemetryDebugLog('skip', {
- reason: disabled ? 'disabled' : 'missing_endpoint',
- eventName: event.name,
- endpoint,
- });
+ if (disabled) {
+ yield* telemetryDebugLog('skip', { reason: 'disabled', eventName: event.name });
return;
}
@@ -459,14 +550,52 @@ export const trackCliEventEffect = (event: TrackEvent) =>
distinctId,
installId,
};
- yield* telemetryDebugLog('enqueue', { endpoint, envelope });
- const serializedEnvelope = yield* encodeJson(envelope);
- const encodedPayload = Encoding.encodeBase64Url(serializedEnvelope);
- const { command, args } = yield* getWorkerSpawnArgs(
- INTERNAL_ANALYTICS_WORKER_FLAG,
- encodedPayload
- );
- yield* spawnWorker(command, args);
+ yield* enqueuePostHogEnvelope(envelope);
+ }).pipe(Effect.catchAllCause(() => Effect.void));
+
+// Fires a single PostHog `$create_alias` merging the anonymous `install_id`
+// device person into the identified Apollo `org_member.id` person. Best-effort.
+export const emitPostHogAlias = (installId: string, apolloUserId: string) =>
+ Effect.gen(function* () {
+ const disabled = yield* analyticsDisabled;
+ if (disabled) {
+ yield* telemetryDebugLog('alias_skip', { reason: 'disabled', installId });
+ return;
+ }
+
+ const sentAt = DateTime.formatIso(yield* DateTime.now);
+ const envelope: AnalyticsEnvelope = {
+ event: POSTHOG_ALIAS_EVENT,
+ properties: {
+ // PostHog merges `properties.alias` into the event's `distinct_id`.
+ distinct_id: apolloUserId,
+ alias: installId,
+ cli_version: constants.APP_VERSION,
+ },
+ sentAt,
+ source: 'cli',
+ distinctId: apolloUserId,
+ installId,
+ };
+ yield* enqueuePostHogEnvelope(envelope);
+ }).pipe(Effect.catchAllCause(() => Effect.void));
+
+// Called at login: persists the Apollo `org_member.id` as the analytics identity
+// and stitches the pre-login anonymous device into that person via one alias.
+// Fully non-fatal so login never fails on telemetry.
+export const linkApolloIdentityForAnalytics = (apolloUserId: string) =>
+ Effect.gen(function* () {
+ if (typeof apolloUserId !== 'string' || apolloUserId.trim().length === 0) {
+ return;
+ }
+
+ const disabled = yield* analyticsDisabled;
+ const installId = yield* getOrCreateInstallId;
+ yield* persistApolloUserId(installId, apolloUserId);
+ if (disabled) {
+ return;
+ }
+ yield* emitPostHogAlias(installId, apolloUserId);
}).pipe(Effect.catchAllCause(() => Effect.void));
export const trackCliCodactFailureEffect = (failure: CliCodactFailure) =>
@@ -523,7 +652,7 @@ const runAnalyticsWorker = (argv: ReadonlyArray<string>) => {
if (typeof envelope?.event !== 'string' || envelope.event.length === 0) {
return true;
}
- yield* captureToComposioAnalytics(envelope);
+ yield* captureToPostHog(envelope);
return true;
}).pipe(
Effect.catchAllCause(cause =>
diff --git a/ts/packages/cli/src/commands/login.cmd.ts b/ts/packages/cli/src/commands/login.cmd.ts
index c34234e71..8fdab0483 100644
--- a/ts/packages/cli/src/commands/login.cmd.ts
+++ b/ts/packages/cli/src/commands/login.cmd.ts
@@ -18,6 +18,7 @@ import { setupCacheDir } from 'src/effects/setup-cache-dir';
import { primeConsumerConnectedToolkitsCacheInBackground } from 'src/services/consumer-short-term-cache';
import { inferSkillReleaseChannel, installSkillSafe } from 'src/effects/install-skill';
import { handleAgentAuthError } from 'src/effects/handle-agent-auth-error';
+import { linkApolloIdentityForAnalytics } from 'src/analytics/dispatch';
import { APP_VERSION } from 'src/constants';
import {
ensureAgentSignupAllowed,
@@ -323,6 +324,9 @@ const directLogin = (params: { userApiKey: string; org?: string }) =>
userApiKey: params.userApiKey,
});
+ // Stitch the anonymous pre-login install into the Apollo person (non-fatal).
+ yield* linkApolloIdentityForAnalytics(sessionInfo.org_member.id);
+
const selectedOrg = yield* resolveDirectLoginOrganization({
apiKey: params.userApiKey,
baseURL: ctx.data.baseURL,
@@ -506,6 +510,9 @@ const loginWithKey = (params: {
userApiKey: uakApiKey,
});
+ // Stitch the anonymous pre-login install into the Apollo person (non-fatal).
+ yield* linkApolloIdentityForAnalytics(uakSessionInfo.org_member.id);
+
const organizations = params.defaultToFirstOrg
? yield* listOrganizations({
baseURL: ctx.data.baseURL,
@@ -712,6 +719,9 @@ export const browserLogin = (params: {
userApiKey: uakApiKey,
});
+ // Stitch the anonymous pre-login install into the Apollo person (non-fatal).
+ yield* linkApolloIdentityForAnalytics(uakSessionInfo.org_member.id);
+
// e.g., "pr_xlSR6oN5jIlk"
const xProjectId = uakSessionInfo.project.nano_id;
// e.g., "k2OiqRLMdHyM"
diff --git a/ts/packages/cli/src/constants.ts b/ts/packages/cli/src/constants.ts
index 43cb77758..92353cb50 100644
--- a/ts/packages/cli/src/constants.ts
+++ b/ts/packages/cli/src/constants.ts
@@ -77,6 +77,30 @@ export const PROJECT_ENV_FILE_NAME = '.env';
*/
export const PROJECT_COMPOSIO_DIR = '.composio';
+/**
+ * PostHog ingest endpoint the CLI sends telemetry directly to.
+ *
+ * This is the public single-event capture API. It does not depend on the
+ * Composio API base URL, so pre-login install/setup events can be delivered
+ * before the user has ever authenticated. Overridable via the
+ * `COMPOSIO_POSTHOG_INGEST_URL` environment variable (used by tests / staging).
+ */
+export const COMPOSIO_POSTHOG_INGEST_URL = 'https://us.i.posthog.com/i/v0/e/';
+
+/**
+ * Public, write-only PostHog project write key for project 196278
+ * ("Composio Platform"). This is client-embeddable by design (same trust model
+ * as the dashboard JS bundle): it can only ingest events, never read them.
+ *
+ * Overridable via the `COMPOSIO_POSTHOG_KEY` environment variable.
+ *
+ * TODO(kj): fill in the real public `phc_*` project-196278 write key from the
+ * PostHog project settings. While this is empty, direct PostHog delivery is a
+ * safe no-op (the transport skips when no key is configured). Do NOT commit a
+ * real token into tests or fixtures.
+ */
+export const COMPOSIO_POSTHOG_PROJECT_KEY = '';
+
/**
* GitHub repository information for release fetching
*/
diff --git a/ts/packages/cli/test/src/analytics.dispatch.test.ts b/ts/packages/cli/test/src/analytics.dispatch.test.ts
index 66789d834..527bb9dc6 100644
--- a/ts/packages/cli/test/src/analytics.dispatch.test.ts
+++ b/ts/packages/cli/test/src/analytics.dispatch.test.ts
@@ -5,12 +5,15 @@ import { BunFileSystem, BunPath } from '@effect/platform-bun';
import { Effect, Layer } from 'effect';
import * as tempy from 'tempy';
import {
+ emitPostHogAlias,
getCurrentCwdSessionId,
+ linkApolloIdentityForAnalytics,
readApiBaseUrl,
runBackgroundWorkerFromArgv,
trackCliCodactFailureEffect,
trackCliEventEffect,
} from 'src/analytics/dispatch';
+import { CLI_ANALYTICS_EVENTS } from 'src/analytics/events';
import { APP_VERSION, USER_CONFIG_FILE_NAME } from 'src/constants';
import { defaultNodeOs, NodeOs } from 'src/services/node-os';
import { TerminalUITest } from 'test/__utils__/services/terminal-ui-test';
@@ -149,29 +152,29 @@ describe('CLI analytics dispatch', () => {
]).pipe(Effect.provide(makePlatformLayer(home)));
});
- it.effect('delivers analytics worker payloads to the configured endpoint', () => {
+ it.effect('delivers analytics worker payloads directly to PostHog', () => {
const home = tempy.temporaryDirectory();
const envelope = {
event: 'cli_command_invoked',
+ properties: { cli_version: '9.9.9' },
sentAt: '2026-07-16T00:00:00.000Z',
source: 'cli' as const,
- distinctId: 'anon_test',
+ distinctId: 'install_test',
installId: 'install_test',
};
const encodedPayload = btoa(JSON.stringify(envelope))
.replace(/\+/gu, '-')
.replace(/\//gu, '_')
.replace(/=+$/u, '');
- vi.stubEnv('COMPOSIO_BASE_URL', 'https://backend.example.test');
- vi.stubEnv('COMPOSIO_USER_API_KEY', 'uak_test');
- vi.stubEnv('NODE_ENV', 'development');
- vi.stubEnv('CI', 'false');
- vi.stubEnv('COMPOSIO_CLI_TELEMETRY_DISABLED', 'false');
- vi.stubEnv('TELEMETRY_DISABLED', 'false');
- vi.stubEnv('COMPOSIO_DISABLE_TELEMETRY', 'false');
+ enableTelemetry();
+ // Direct-to-PostHog transport does NOT read the Composio base URL. Overriding
+ // the ingest URL + a fake public key keeps the test off the real project.
+ vi.stubEnv('COMPOSIO_BASE_URL', '');
+ vi.stubEnv('COMPOSIO_POSTHOG_INGEST_URL', 'https://posthog.example.test/i/v0/e/');
+ vi.stubEnv('COMPOSIO_POSTHOG_KEY', 'phc_test_key');
const fetchSpy = vi
.spyOn(globalThis, 'fetch')
- .mockResolvedValue(new Response(null, { status: 204 }));
+ .mockResolvedValue(new Response(null, { status: 200 }));
return Effect.gen(function* () {
yield* runBackgroundWorkerFromArgv([
@@ -183,16 +186,60 @@ describe('CLI analytics dispatch', () => {
expect(fetchSpy).toHaveBeenCalledTimes(1);
const [endpoint, request] = fetchSpy.mock.calls[0]!;
- expect(String(endpoint)).toBe('https://backend.example.test/api/v3/cli/analytics');
+ expect(String(endpoint)).toBe('https://posthog.example.test/i/v0/e/');
expect(request).toMatchObject({
method: 'POST',
headers: expect.objectContaining({
'content-type': 'application/json',
'x-composio-analytics-source': 'cli',
- 'x-user-api-key': 'uak_test',
}),
});
- expect(JSON.parse(new TextDecoder().decode(request?.body as Uint8Array))).toEqual(envelope);
+ // The public write key authenticates in-band; no user API key is attached.
+ expect((request?.headers as Record<string, string>)['x-user-api-key']).toBeUndefined();
+ const body = JSON.parse(new TextDecoder().decode(request?.body as Uint8Array));
+ expect(body).toMatchObject({
+ api_key: 'phc_test_key',
+ event: 'cli_command_invoked',
+ distinct_id: 'install_test',
+ timestamp: '2026-07-16T00:00:00.000Z',
+ properties: expect.objectContaining({
+ cli_version: '9.9.9',
+ install_id: 'install_test',
+ $lib: 'composio-cli',
+ }),
+ });
+ });
+ });
+
+ it.effect('skips PostHog delivery when no project key is configured', () => {
+ const home = tempy.temporaryDirectory();
+ const envelope = {
+ event: 'cli_command_invoked',
+ sentAt: '2026-07-16T00:00:00.000Z',
+ source: 'cli' as const,
+ distinctId: 'install_test',
+ installId: 'install_test',
+ };
+ const encodedPayload = btoa(JSON.stringify(envelope))
+ .replace(/\+/gu, '-')
+ .replace(/\//gu, '_')
+ .replace(/=+$/u, '');
+ enableTelemetry();
+ // No COMPOSIO_POSTHOG_KEY override -> falls back to the empty embedded
+ // placeholder, so delivery is a safe no-op until the real key is filled in.
+ const fetchSpy = vi
+ .spyOn(globalThis, 'fetch')
+ .mockResolvedValue(new Response(null, { status: 200 }));
+
+ return Effect.gen(function* () {
+ yield* runBackgroundWorkerFromArgv([
+ process.execPath,
+ 'composio',
+ '__analytics-worker',
+ encodedPayload,
+ ]).pipe(Effect.provide(makePlatformLayer(home)));
+
+ expect(fetchSpy).not.toHaveBeenCalled();
});
});
@@ -319,11 +366,110 @@ describe('CLI analytics dispatch', () => {
failureType: 'wrong_tool_slug',
ctx: { slug: 'MISSING_TOOL' },
});
+ yield* emitPostHogAlias('install_disabled', 'apollo_user_disabled');
+ yield* linkApolloIdentityForAnalytics('apollo_user_disabled');
expect(childProcessMocks.spawn).not.toHaveBeenCalled();
}).pipe(Effect.provide(makePlatformLayer(home)));
});
+ it.effect('keys pre-login events on the bare install_id', () => {
+ const home = tempy.temporaryDirectory();
+ const scriptPath = `${home}/composio.ts`;
+ // No persisted apollo_user_id and no user API key -> anonymous device identity.
+ enableTelemetry('');
+ process.argv[1] = scriptPath;
+
+ return Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ yield* fs.writeFileString(scriptPath, '');
+ yield* trackCliEventEffect({ name: CLI_ANALYTICS_EVENTS.CLI_SETUP_SUCCEEDED });
+
+ expect(childProcessMocks.spawn).toHaveBeenCalledTimes(1);
+ const args = childProcessMocks.spawn.mock.calls[0]![1] as string[];
+ const payload = decodeWorkerPayload<{ distinctId: string; installId: string }>(args[2]!);
+ // Pre-login, distinct_id is the raw install_id (not `anon_<id>`), so the
+ // login-time alias can merge this exact person into the Apollo user.
+ expect(payload.installId.length).toBeGreaterThan(0);
+ expect(payload.distinctId).toBe(payload.installId);
+ }).pipe(Effect.provide(makePlatformLayer(home)));
+ });
+
+ it.effect('keys post-login events on the persisted apollo_user_id', () => {
+ const home = tempy.temporaryDirectory();
+ const scriptPath = `${home}/composio.ts`;
+ enableTelemetry('');
+ process.argv[1] = scriptPath;
+
+ return Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ yield* fs.writeFileString(scriptPath, '');
+ const composioDir = path.join(home, '.composio');
+ yield* fs.makeDirectory(composioDir, { recursive: true });
+ yield* fs.writeFileString(
+ path.join(composioDir, 'analytics.json'),
+ JSON.stringify({ install_id: 'install_persisted', apollo_user_id: 'om_apollo_123' })
+ );
+
+ yield* trackCliEventEffect({ name: CLI_ANALYTICS_EVENTS.CLI_EXECUTE_SUCCEEDED });
+
+ expect(childProcessMocks.spawn).toHaveBeenCalledTimes(1);
+ const args = childProcessMocks.spawn.mock.calls[0]![1] as string[];
+ const payload = decodeWorkerPayload<{ distinctId: string; installId: string }>(args[2]!);
+ expect(payload.distinctId).toBe('om_apollo_123');
+ expect(payload.installId).toBe('install_persisted');
+ }).pipe(Effect.provide(makePlatformLayer(home)));
+ });
+
+ it.effect('persists apollo_user_id and emits exactly one $create_alias at login', () => {
+ const home = tempy.temporaryDirectory();
+ const scriptPath = `${home}/composio.ts`;
+ enableTelemetry('');
+ process.argv[1] = scriptPath;
+
+ return Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ yield* fs.writeFileString(scriptPath, '');
+ const composioDir = path.join(home, '.composio');
+ yield* fs.makeDirectory(composioDir, { recursive: true });
+ yield* fs.writeFileString(
+ path.join(composioDir, 'analytics.json'),
+ JSON.stringify({ install_id: 'install_login', created_at: '2026-01-01T00:00:00.000Z' })
+ );
+
+ yield* linkApolloIdentityForAnalytics('om_apollo_login');
+
+ // Exactly one alias event is spawned.
+ expect(childProcessMocks.spawn).toHaveBeenCalledTimes(1);
+ const args = childProcessMocks.spawn.mock.calls[0]![1] as string[];
+ const payload = decodeWorkerPayload<{
+ event: string;
+ distinctId: string;
+ installId: string;
+ properties: { distinct_id: string; alias: string };
+ }>(args[2]!);
+ expect(payload.event).toBe('$create_alias');
+ expect(payload.distinctId).toBe('om_apollo_login');
+ expect(payload.installId).toBe('install_login');
+ expect(payload.properties).toMatchObject({
+ distinct_id: 'om_apollo_login',
+ alias: 'install_login',
+ });
+
+ // The Apollo id is persisted while keeping the original install_id/created_at.
+ const persisted = JSON.parse(
+ yield* fs.readFileString(path.join(composioDir, 'analytics.json'), 'utf8')
+ ) as { install_id: string; apollo_user_id: string; created_at: string };
+ expect(persisted).toMatchObject({
+ install_id: 'install_login',
+ apollo_user_id: 'om_apollo_login',
+ created_at: '2026-01-01T00:00:00.000Z',
+ });
+ }).pipe(Effect.provide(makePlatformLayer(home)));
+ });
+
it.effect('delivers codact worker failures with the user key and session body', () => {
const home = tempy.temporaryDirectory();
const failureBody = {