From a6e6f9802c82fa6ab8cbcf8e3cbc6a78985e8adf Mon Sep 17 00:00:00 2001 From: Alec Fong Date: Tue, 24 Mar 2026 11:19:28 -0700 Subject: [PATCH] feat: resolve real user ID in analytics via UserStore interface Instead of manually passing user IDs through callers, analytics now accepts a UserStore interface and resolves the user ID directly. GetOrCreateAnalyticsID prefers the real user ID when available, falling back to the anonymous UUID. --- pkg/analytics/posthog.go | 22 +++++++++++++++++++++- pkg/cmd/cmd.go | 12 +++--------- 2 files changed, 24 insertions(+), 10 deletions(-) diff --git a/pkg/analytics/posthog.go b/pkg/analytics/posthog.go index 9a6f6bd4c..7750a9227 100644 --- a/pkg/analytics/posthog.go +++ b/pkg/analytics/posthog.go @@ -19,6 +19,11 @@ import ( const posthogAPIKey = "phc_PWWXIQgQ31lXWMGI2dnTY3FyjBh7gPcMhlno1RLapLm" +// UserStore provides the current user ID for analytics tracking. +type UserStore interface { + GetCurrentUserID() (string, error) +} + var ( client posthog.Client clientOnce sync.Once @@ -31,6 +36,9 @@ var ( storedCmd *cobra.Command storedArgs []string storedUser string + + // userStore is set via SetUserStore so GetOrCreateAnalyticsID can resolve the real user ID. + userStore UserStore ) func getClient() (posthog.Client, error) { @@ -100,8 +108,20 @@ func SetAnalyticsPreference(enabled bool) error { return nil } -// GetOrCreateAnalyticsID returns a stable anonymous UUID for tracking, creating one if needed. +// SetUserStore configures the store used to resolve the current user ID. +func SetUserStore(s UserStore) { + userStore = s +} + +// GetOrCreateAnalyticsID returns the user's distinct ID for tracking. +// It prefers the real user ID from the store if available, falling back to a stable anonymous UUID. func GetOrCreateAnalyticsID() string { + if userStore != nil { + if uid, err := userStore.GetCurrentUserID(); err == nil && uid != "" { + return uid + } + } + fs := files.AppFs home, err := getHomeDir() if err != nil { diff --git a/pkg/cmd/cmd.go b/pkg/cmd/cmd.go index 46d6f2ac9..6912df3ac 100644 --- a/pkg/cmd/cmd.go +++ b/pkg/cmd/cmd.go @@ -132,6 +132,8 @@ func NewBrevCommand() *cobra.Command { //nolint:funlen,gocognit,gocyclo // defin ) noLoginCmdStore := noAuthCmdStore.WithAuth(noLoginAuth) + analytics.SetUserStore(noLoginCmdStore) + workspaceGroupID, err := fsStore.GetCurrentWorkspaceGroupID() if err != nil { fmt.Printf("%v\n", err) @@ -165,15 +167,7 @@ func NewBrevCommand() *cobra.Command { //nolint:funlen,gocognit,gocyclo // defin } }, PersistentPostRunE: func(cmd *cobra.Command, args []string) error { - userID := "" - user, err := noLoginCmdStore.GetCurrentUser() - if err == nil && user != nil { - userID = user.ID - } - if userID == "" { - userID = analytics.GetOrCreateAnalyticsID() - } - analytics.CaptureCommand(userID, cmd, args) + analytics.CaptureCommand(analytics.GetOrCreateAnalyticsID(), cmd, args) return nil }, PersistentPreRunE: func(cmd *cobra.Command, args []string) error {