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.

fix(cli): link the analytics identity only after credentials persist

Kshitij Jhunjhunwalab93a05ea823f
diff --git a/ts/packages/cli/src/commands/login.cmd.ts b/ts/packages/cli/src/commands/login.cmd.ts
index 79ba3e92a..523d635ee 100644
--- a/ts/packages/cli/src/commands/login.cmd.ts
+++ b/ts/packages/cli/src/commands/login.cmd.ts
@@ -324,8 +324,6 @@ const directLogin = (params: { userApiKey: string; org?: string }) =>
userApiKey: params.userApiKey,
});
- yield* linkApolloIdentityForAnalytics(sessionInfo.org_member.id, params.userApiKey);
-
const selectedOrg = yield* resolveDirectLoginOrganization({
apiKey: params.userApiKey,
baseURL: ctx.data.baseURL,
@@ -340,6 +338,7 @@ const directLogin = (params: { userApiKey: string; org?: string }) =>
: Option.getOrUndefined(ctx.data.testUserId);
yield* ctx.login(params.userApiKey, selectedOrg.id, testUserId);
+ yield* linkApolloIdentityForAnalytics(sessionInfo.org_member.id, params.userApiKey);
yield* primeConsumerConnectedToolkitsCacheInBackground({
orgId: selectedOrg.id,
});
@@ -363,6 +362,8 @@ const storeCredentials = (params: {
initialOrgId: string;
initialProjectId: string;
fallbackEmail: string;
+ /** Fallback Apollo org_member id for analytics linking when session/info fails here. */
+ orgMemberId?: string;
/** When true, skip the init/switch hints and outro (shown later after org picker). */
skipHints?: boolean;
/** When true, skip JSON output (emitted later after org picker with final selection). */
@@ -377,6 +378,7 @@ const storeCredentials = (params: {
initialOrgId,
initialProjectId,
fallbackEmail,
+ orgMemberId,
skipHints = false,
skipOutput = false,
} = params;
@@ -419,6 +421,11 @@ const storeCredentials = (params: {
}
yield* ctx.login(uakApiKey, orgId, testUserId);
+ // Linked only after the credential persists, so stitching cannot outlive a failed login.
+ const linkedOrgMemberId = sessionInfo?.org_member.id ?? orgMemberId;
+ if (linkedOrgMemberId) {
+ yield* linkApolloIdentityForAnalytics(linkedOrgMemberId, uakApiKey);
+ }
yield* primeConsumerConnectedToolkitsCacheInBackground({
orgId,
});
@@ -509,8 +516,6 @@ const loginWithKey = (params: {
userApiKey: uakApiKey,
});
- yield* linkApolloIdentityForAnalytics(uakSessionInfo.org_member.id, uakApiKey);
-
const organizations = params.defaultToFirstOrg
? yield* listOrganizations({
baseURL: ctx.data.baseURL,
@@ -537,6 +542,7 @@ const loginWithKey = (params: {
initialOrgId: xOrgId,
initialProjectId: xProjectId,
fallbackEmail: linkedSession.account.email,
+ orgMemberId: uakSessionInfo.org_member.id,
skipHints: willRunPicker,
skipOutput: true,
});
@@ -717,8 +723,6 @@ export const browserLogin = (params: {
userApiKey: uakApiKey,
});
- yield* linkApolloIdentityForAnalytics(uakSessionInfo.org_member.id, uakApiKey);
-
// e.g., "pr_xlSR6oN5jIlk"
const xProjectId = uakSessionInfo.project.nano_id;
// e.g., "k2OiqRLMdHyM"
@@ -733,6 +737,7 @@ export const browserLogin = (params: {
initialOrgId: xOrgId,
initialProjectId: xProjectId,
fallbackEmail: linkedSession.account.email,
+ orgMemberId: uakSessionInfo.org_member.id,
skipHints: willRunPicker,
skipOutput: willRunPicker,
});
@@ -891,20 +896,6 @@ export const loginCmd = Command.make(
yield* ensureAgentSignupAllowed;
const identity = yield* getOrSignupReadyAgent();
yield* loginWithAgentIdentity(identity);
- const agentUserApiKey = identity.composio?.user_api_key;
- if (agentUserApiKey) {
- const agentSessionInfo = yield* getSessionInfoByUserApiKey({
- baseURL: ctx.data.baseURL,
- userApiKey: agentUserApiKey,
- orgId: identity.composio?.org_id ?? undefined,
- }).pipe(Effect.catchAll(() => Effect.succeed(null)));
- if (agentSessionInfo) {
- yield* linkApolloIdentityForAnalytics(
- agentSessionInfo.org_member.id,
- agentUserApiKey
- );
- }
- }
const summary = safeAgentSummary(identity);
yield* ui.log.success(
`Logged in as Composio agent ${summary.email ?? summary.slug ?? ''}`
diff --git a/ts/packages/cli/src/services/agents.ts b/ts/packages/cli/src/services/agents.ts
index b47a36307..3a7b49ffb 100644
--- a/ts/packages/cli/src/services/agents.ts
+++ b/ts/packages/cli/src/services/agents.ts
@@ -3,7 +3,9 @@ import { Data, Effect, Option, Predicate, Schema } from 'effect';
import { JsonRecordSchema } from 'src/effects/json';
import { setupCacheDir } from 'src/effects/setup-cache-dir';
import { ComposioUserContext } from 'src/services/user-context';
+import { getSessionInfoByUserApiKey } from 'src/services/composio-clients';
import { primeConsumerConnectedToolkitsCacheInBackground } from 'src/services/consumer-short-term-cache';
+import { linkApolloIdentityForAnalytics } from 'src/analytics/dispatch';
export const AGENT_CONFIG_FILE_NAME = 'agent.json';
export const DEFAULT_AGENTS_BASE_URL = 'https://agents.composio.dev';
@@ -398,5 +400,10 @@ export const loginWithAgentIdentity = (identity: AgentIdentity) =>
}
yield* ctx.login(userApiKey, orgId);
+ // Best-effort analytics stitch after the credential persists; must never break login.
+ yield* getSessionInfoByUserApiKey({ baseURL: ctx.data.baseURL, userApiKey, orgId }).pipe(
+ Effect.flatMap(info => linkApolloIdentityForAnalytics(info.org_member.id, userApiKey)),
+ Effect.catchAllCause(() => Effect.void)
+ );
yield* primeConsumerConnectedToolkitsCacheInBackground({ orgId });
});
diff --git a/ts/packages/cli/test/src/commands/login.cmd.test.ts b/ts/packages/cli/test/src/commands/login.cmd.test.ts
index 168c1e0a6..74a8bf2c7 100644
--- a/ts/packages/cli/test/src/commands/login.cmd.test.ts
+++ b/ts/packages/cli/test/src/commands/login.cmd.test.ts
@@ -9,6 +9,25 @@ import * as constants from 'src/constants';
import { setupCacheDir } from 'src/effects/setup-cache-dir';
import { ComposioUserContext } from 'src/services/user-context';
+const analyticsMocks = vi.hoisted(() => ({
+ linkCalls: [] as Array<{ apolloUserId: string; loggedInAtLinkTime: boolean }>,
+}));
+
+// Records each identity link and whether the credential had already been
+// stored via ctx.login at call time — the link-after-persistence ordering.
+vi.mock('src/analytics/dispatch', async importOriginal => {
+ const actual = await importOriginal<typeof import('src/analytics/dispatch')>();
+ const { Effect } = await import('effect');
+ const { ComposioUserContext } = await import('src/services/user-context');
+ return {
+ ...actual,
+ linkApolloIdentityForAnalytics: ((apolloUserId: string) =>
+ Effect.map(ComposioUserContext, ctx => {
+ analyticsMocks.linkCalls.push({ apolloUserId, loggedInAtLinkTime: ctx.isLoggedIn() });
+ })) as unknown as typeof actual.linkApolloIdentityForAnalytics,
+ };
+});
+
const mockFetchResponse = (body: unknown, status = 200) =>
new Response(JSON.stringify(body), {
status,
@@ -39,6 +58,7 @@ const setTtyState = (state: { stdin: boolean; stdout: boolean; stderr: boolean }
describe('CLI: composio login', () => {
afterEach(() => {
vi.restoreAllMocks();
+ analyticsMocks.linkCalls.length = 0;
});
describe('login --help', () => {
@@ -203,6 +223,12 @@ describe('CLI: composio login', () => {
const output = (yield* MockConsole.getLines({ stripAnsi: true })).join('\n');
expect(output).toContain('Logged in as [email protected] in "Selected Org"');
+
+ // The analytics identity is linked exactly once, and only after the
+ // credential was stored via ctx.login.
+ expect(analyticsMocks.linkCalls).toEqual([
+ { apolloUserId: 'member_123', loggedInAtLinkTime: true },
+ ]);
})
);
});