Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 21 additions & 1 deletion pkg/analytics/posthog.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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) {
Expand Down Expand Up @@ -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 {
Expand Down
12 changes: 3 additions & 9 deletions pkg/cmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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 {
Expand Down
Loading