Skip to content

Open source AI coding agent. Designed for large projects and real world tasks.

lots of work on billing

Dane Schneiderdc85a805b812
diff --git a/app/cli/api/clients.go b/app/cli/api/clients.go
index 4c4a253b..87e789a1 100644
--- a/app/cli/api/clients.go
+++ b/app/cli/api/clients.go
@@ -15,26 +15,25 @@ const slowReqTimeout = 5 * time.Minute
type Api struct{}
-var cloudApiHost string
-
+var CloudApiHost string
var Client types.ApiClient = (*Api)(nil)
func init() {
if os.Getenv("PLANDEX_ENV") == "development" {
- cloudApiHost = os.Getenv("PLANDEX_API_HOST")
- if cloudApiHost == "" {
- cloudApiHost = "http://localhost:8080"
+ CloudApiHost = os.Getenv("PLANDEX_API_HOST")
+ if CloudApiHost == "" {
+ CloudApiHost = "http://localhost:8080"
}
} else {
- cloudApiHost = "https://api.plandex.ai"
+ CloudApiHost = "https://api.plandex.ai"
}
}
-func getApiHost() string {
+func GetApiHost() string {
if auth.Current == nil {
return ""
} else if auth.Current.IsCloud {
- return cloudApiHost
+ return CloudApiHost
} else {
return auth.Current.Host
}
diff --git a/app/cli/api/errors.go b/app/cli/api/errors.go
index 04878c1b..2e8604cf 100644
--- a/app/cli/api/errors.go
+++ b/app/cli/api/errors.go
@@ -5,12 +5,13 @@ import (
"log"
"net/http"
"plandex/auth"
+ "plandex/term"
"strings"
"github.com/plandex/plandex/shared"
)
-func handleApiError(r *http.Response, errBody []byte) *shared.ApiError {
+func HandleApiError(r *http.Response, errBody []byte) *shared.ApiError {
// Check if the response is JSON
if r.Header.Get("Content-Type") != "application/json" {
return &shared.ApiError{
@@ -30,6 +31,8 @@ func handleApiError(r *http.Response, errBody []byte) *shared.ApiError {
}
}
+ term.HandleApiError(&apiError)
+
return &apiError
}
diff --git a/app/cli/api/methods.go b/app/cli/api/methods.go
index 7e0ac1e4..e60ce51d 100644
--- a/app/cli/api/methods.go
+++ b/app/cli/api/methods.go
@@ -13,38 +13,64 @@ import (
"github.com/plandex/plandex/shared"
)
-func (a *Api) StartTrial(req shared.StartTrialRequest) (*shared.StartTrialResponse, *shared.ApiError) {
- serverUrl := cloudApiHost + "/accounts/start_trial"
+func (a *Api) CreateCliTrialSession() (string, *shared.ApiError) {
+ serverUrl := CloudApiHost + "/accounts/cli_trial_session"
+
+ resp, err := unauthenticatedClient.Post(serverUrl, "application/json", nil)
- reqBytes, err := json.Marshal(req)
if err != nil {
- return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error marshalling request: %v", err)}
+ return "", &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %v", err)}
}
- resp, err := unauthenticatedClient.Post(serverUrl, "application/json", bytes.NewBuffer(reqBytes))
+ defer resp.Body.Close()
+
+ if resp.StatusCode >= 400 {
+ errorBody, _ := io.ReadAll(resp.Body)
+ apiErr := HandleApiError(resp, errorBody)
+ return "", apiErr
+ }
+
+ bytes, err := io.ReadAll(resp.Body)
+
+ if err != nil {
+ return "", &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error reading response: %v", err)}
+ }
+
+ return string(bytes), nil
+}
+
+func (a *Api) GetCliTrialSession(token string) (*shared.SessionResponse, *shared.ApiError) {
+ serverUrl := fmt.Sprintf("%s/accounts/cli_trial_session/%s", CloudApiHost, token)
+
+ resp, err := unauthenticatedClient.Get(serverUrl)
+
if err != nil {
return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %v", err)}
}
+ if resp.StatusCode == 404 {
+ return nil, nil
+ }
+
defer resp.Body.Close()
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
return nil, apiErr
}
- var startTrialResponse shared.StartTrialResponse
- err = json.NewDecoder(resp.Body).Decode(&startTrialResponse)
+ var session shared.SessionResponse
+ err = json.NewDecoder(resp.Body).Decode(&session)
if err != nil {
return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error decoding response: %v", err)}
}
- return &startTrialResponse, nil
+ return &session, nil
}
func (a *Api) CreateProject(req shared.CreateProjectRequest) (*shared.CreateProjectResponse, *shared.ApiError) {
- serverUrl := getApiHost() + "/projects"
+ serverUrl := GetApiHost() + "/projects"
reqBytes, err := json.Marshal(req)
if err != nil {
@@ -59,7 +85,7 @@ func (a *Api) CreateProject(req shared.CreateProjectRequest) (*shared.CreateProj
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
if tokenRefreshed {
return a.CreateProject(req)
@@ -77,7 +103,7 @@ func (a *Api) CreateProject(req shared.CreateProjectRequest) (*shared.CreateProj
}
func (a *Api) ListProjects() ([]*shared.Project, *shared.ApiError) {
- serverUrl := getApiHost() + "/projects"
+ serverUrl := GetApiHost() + "/projects"
resp, err := authenticatedFastClient.Get(serverUrl)
if err != nil {
return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %v", err)}
@@ -86,7 +112,7 @@ func (a *Api) ListProjects() ([]*shared.Project, *shared.ApiError) {
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
if tokenRefreshed {
return a.ListProjects()
@@ -104,7 +130,7 @@ func (a *Api) ListProjects() ([]*shared.Project, *shared.ApiError) {
}
func (a *Api) SetProjectPlan(projectId string, req shared.SetProjectPlanRequest) *shared.ApiError {
- serverUrl := fmt.Sprintf("%s/projects/%s/set_plan", getApiHost(), projectId)
+ serverUrl := fmt.Sprintf("%s/projects/%s/set_plan", GetApiHost(), projectId)
reqBytes, err := json.Marshal(req)
if err != nil {
return &shared.ApiError{Msg: fmt.Sprintf("error marshalling request: %v", err)}
@@ -124,7 +150,7 @@ func (a *Api) SetProjectPlan(projectId string, req shared.SetProjectPlanRequest)
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
didRefresh, apiErr := refreshTokenIfNeeded(apiErr)
if didRefresh {
return a.SetProjectPlan(projectId, req)
@@ -136,7 +162,7 @@ func (a *Api) SetProjectPlan(projectId string, req shared.SetProjectPlanRequest)
}
func (a *Api) RenameProject(projectId string, req shared.RenameProjectRequest) *shared.ApiError {
- serverUrl := fmt.Sprintf("%s/projects/%s/rename", getApiHost(), projectId)
+ serverUrl := fmt.Sprintf("%s/projects/%s/rename", GetApiHost(), projectId)
reqBytes, err := json.Marshal(req)
if err != nil {
return &shared.ApiError{Msg: fmt.Sprintf("error marshalling request: %v", err)}
@@ -156,7 +182,7 @@ func (a *Api) RenameProject(projectId string, req shared.RenameProjectRequest) *
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
didRefresh, apiErr := refreshTokenIfNeeded(apiErr)
if didRefresh {
@@ -168,7 +194,7 @@ func (a *Api) RenameProject(projectId string, req shared.RenameProjectRequest) *
return nil
}
func (a *Api) ListPlans(projectIds []string) ([]*shared.Plan, *shared.ApiError) {
- serverUrl := fmt.Sprintf("%s/plans?", getApiHost())
+ serverUrl := fmt.Sprintf("%s/plans?", GetApiHost())
parts := []string{}
for _, projectId := range projectIds {
parts = append(parts, fmt.Sprintf("projectId=%s", projectId))
@@ -184,7 +210,7 @@ func (a *Api) ListPlans(projectIds []string) ([]*shared.Plan, *shared.ApiError)
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
didRefresh, apiErr := refreshTokenIfNeeded(apiErr)
if didRefresh {
@@ -203,7 +229,7 @@ func (a *Api) ListPlans(projectIds []string) ([]*shared.Plan, *shared.ApiError)
}
func (a *Api) ListArchivedPlans(projectIds []string) ([]*shared.Plan, *shared.ApiError) {
- serverUrl := fmt.Sprintf("%s/plans/archive?", getApiHost())
+ serverUrl := fmt.Sprintf("%s/plans/archive?", GetApiHost())
parts := []string{}
for _, projectId := range projectIds {
parts = append(parts, fmt.Sprintf("projectId=%s", projectId))
@@ -218,7 +244,7 @@ func (a *Api) ListArchivedPlans(projectIds []string) ([]*shared.Plan, *shared.Ap
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
if tokenRefreshed {
return a.ListArchivedPlans(projectIds)
@@ -236,7 +262,7 @@ func (a *Api) ListArchivedPlans(projectIds []string) ([]*shared.Plan, *shared.Ap
}
func (a *Api) ListPlansRunning(projectIds []string, includeRecent bool) (*shared.ListPlansRunningResponse, *shared.ApiError) {
- serverUrl := fmt.Sprintf("%s/plans/ps?", getApiHost())
+ serverUrl := fmt.Sprintf("%s/plans/ps?", GetApiHost())
parts := []string{}
for _, projectId := range projectIds {
parts = append(parts, fmt.Sprintf("projectId=%s", projectId))
@@ -254,7 +280,7 @@ func (a *Api) ListPlansRunning(projectIds []string, includeRecent bool) (*shared
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
if tokenRefreshed {
return a.ListPlansRunning(projectIds, includeRecent)
@@ -272,7 +298,7 @@ func (a *Api) ListPlansRunning(projectIds []string, includeRecent bool) (*shared
}
func (a *Api) GetCurrentBranchByPlanId(projectId string, req shared.GetCurrentBranchByPlanIdRequest) (map[string]*shared.Branch, *shared.ApiError) {
- serverUrl := fmt.Sprintf("%s/projects/%s/plans/current_branches", getApiHost(), projectId)
+ serverUrl := fmt.Sprintf("%s/projects/%s/plans/current_branches", GetApiHost(), projectId)
reqBytes, err := json.Marshal(req)
if err != nil {
@@ -297,7 +323,7 @@ func (a *Api) GetCurrentBranchByPlanId(projectId string, req shared.GetCurrentBr
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
didRefresh, apiErr := refreshTokenIfNeeded(apiErr)
if didRefresh {
@@ -316,7 +342,7 @@ func (a *Api) GetCurrentBranchByPlanId(projectId string, req shared.GetCurrentBr
}
func (a *Api) CreatePlan(projectId string, req shared.CreatePlanRequest) (*shared.CreatePlanResponse, *shared.ApiError) {
- serverUrl := fmt.Sprintf("%s/projects/%s/plans", getApiHost(), projectId)
+ serverUrl := fmt.Sprintf("%s/projects/%s/plans", GetApiHost(), projectId)
reqBytes, err := json.Marshal(req)
if err != nil {
return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error marshalling request: %v", err)}
@@ -330,7 +356,7 @@ func (a *Api) CreatePlan(projectId string, req shared.CreatePlanRequest) (*share
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
if tokenRefreshed {
return a.CreatePlan(projectId, req)
@@ -348,7 +374,7 @@ func (a *Api) CreatePlan(projectId string, req shared.CreatePlanRequest) (*share
}
func (a *Api) GetPlan(planId string) (*shared.Plan, *shared.ApiError) {
- serverUrl := fmt.Sprintf("%s/plans/%s", getApiHost(), planId)
+ serverUrl := fmt.Sprintf("%s/plans/%s", GetApiHost(), planId)
resp, err := authenticatedFastClient.Get(serverUrl)
if err != nil {
@@ -359,7 +385,7 @@ func (a *Api) GetPlan(planId string) (*shared.Plan, *shared.ApiError) {
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
if tokenRefreshed {
return a.GetPlan(planId)
@@ -377,7 +403,7 @@ func (a *Api) GetPlan(planId string) (*shared.Plan, *shared.ApiError) {
}
func (a *Api) DeletePlan(planId string) *shared.ApiError {
- serverUrl := fmt.Sprintf("%s/plans/%s", getApiHost(), planId)
+ serverUrl := fmt.Sprintf("%s/plans/%s", GetApiHost(), planId)
req, err := http.NewRequest(http.MethodDelete, serverUrl, nil)
if err != nil {
@@ -392,7 +418,7 @@ func (a *Api) DeletePlan(planId string) *shared.ApiError {
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
didRefresh, apiErr := refreshTokenIfNeeded(apiErr)
if didRefresh {
@@ -405,7 +431,7 @@ func (a *Api) DeletePlan(planId string) *shared.ApiError {
}
func (a *Api) DeleteAllPlans(projectId string) *shared.ApiError {
- serverUrl := fmt.Sprintf("%s/projects/%s/plans", getApiHost(), projectId)
+ serverUrl := fmt.Sprintf("%s/projects/%s/plans", GetApiHost(), projectId)
req, err := http.NewRequest(http.MethodDelete, serverUrl, nil)
if err != nil {
@@ -420,7 +446,7 @@ func (a *Api) DeleteAllPlans(projectId string) *shared.ApiError {
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
didRefresh, apiErr := refreshTokenIfNeeded(apiErr)
@@ -435,7 +461,7 @@ func (a *Api) DeleteAllPlans(projectId string) *shared.ApiError {
func (a *Api) TellPlan(planId, branch string, req shared.TellPlanRequest, onStream types.OnStreamPlan) *shared.ApiError {
- serverUrl := fmt.Sprintf("%s/plans/%s/%s/tell", getApiHost(), planId, branch)
+ serverUrl := fmt.Sprintf("%s/plans/%s/%s/tell", GetApiHost(), planId, branch)
reqBytes, err := json.Marshal(req)
if err != nil {
return &shared.ApiError{Msg: fmt.Sprintf("error marshalling request: %v", err)}
@@ -461,7 +487,7 @@ func (a *Api) TellPlan(planId, branch string, req shared.TellPlanRequest, onStre
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
didRefresh, apiErr := refreshTokenIfNeeded(apiErr)
@@ -486,7 +512,7 @@ func (a *Api) BuildPlan(planId, branch string, req shared.BuildPlanRequest, onSt
log.Println("Calling BuildPlan")
- serverUrl := fmt.Sprintf("%s/plans/%s/%s/build", getApiHost(), planId, branch)
+ serverUrl := fmt.Sprintf("%s/plans/%s/%s/build", GetApiHost(), planId, branch)
reqBytes, err := json.Marshal(req)
if err != nil {
return &shared.ApiError{Msg: fmt.Sprintf("error marshalling request: %v", err)}
@@ -514,7 +540,7 @@ func (a *Api) BuildPlan(planId, branch string, req shared.BuildPlanRequest, onSt
log.Println("Error response from build plan", resp.StatusCode)
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
didRefresh, apiErr := refreshTokenIfNeeded(apiErr)
@@ -536,7 +562,7 @@ func (a *Api) BuildPlan(planId, branch string, req shared.BuildPlanRequest, onSt
}
func (a *Api) RespondMissingFile(planId, branch string, req shared.RespondMissingFileRequest) *shared.ApiError {
- serverUrl := fmt.Sprintf("%s/plans/%s/%s/respond_missing_file", getApiHost(), planId, branch)
+ serverUrl := fmt.Sprintf("%s/plans/%s/%s/respond_missing_file", GetApiHost(), planId, branch)
reqBytes, err := json.Marshal(req)
if err != nil {
@@ -556,7 +582,7 @@ func (a *Api) RespondMissingFile(planId, branch string, req shared.RespondMissin
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
didRefresh, apiErr := refreshTokenIfNeeded(apiErr)
@@ -571,7 +597,7 @@ func (a *Api) RespondMissingFile(planId, branch string, req shared.RespondMissin
}
func (a *Api) ConnectPlan(planId, branch string, onStream types.OnStreamPlan) *shared.ApiError {
- serverUrl := fmt.Sprintf("%s/plans/%s/%s/connect", getApiHost(), planId, branch)
+ serverUrl := fmt.Sprintf("%s/plans/%s/%s/connect", GetApiHost(), planId, branch)
req, err := http.NewRequest(http.MethodPatch, serverUrl, nil)
if err != nil {
@@ -585,7 +611,7 @@ func (a *Api) ConnectPlan(planId, branch string, onStream types.OnStreamPlan) *s
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
didRefresh, apiErr := refreshTokenIfNeeded(apiErr)
@@ -602,7 +628,7 @@ func (a *Api) ConnectPlan(planId, branch string, onStream types.OnStreamPlan) *s
}
func (a *Api) StopPlan(planId, branch string) *shared.ApiError {
- serverUrl := fmt.Sprintf("%s/plans/%s/%s/stop", getApiHost(), planId, branch)
+ serverUrl := fmt.Sprintf("%s/plans/%s/%s/stop", GetApiHost(), planId, branch)
req, err := http.NewRequest(http.MethodDelete, serverUrl, nil)
if err != nil {
@@ -617,7 +643,7 @@ func (a *Api) StopPlan(planId, branch string) *shared.ApiError {
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
didRefresh, apiErr := refreshTokenIfNeeded(apiErr)
if didRefresh {
return a.StopPlan(planId, branch)
@@ -629,7 +655,7 @@ func (a *Api) StopPlan(planId, branch string) *shared.ApiError {
}
func (a *Api) GetCurrentPlanState(planId, branch string) (*shared.CurrentPlanState, *shared.ApiError) {
- serverUrl := fmt.Sprintf("%s/plans/%s/%s/current_plan", getApiHost(), planId, branch)
+ serverUrl := fmt.Sprintf("%s/plans/%s/%s/current_plan", GetApiHost(), planId, branch)
resp, err := authenticatedFastClient.Get(serverUrl)
if err != nil {
@@ -639,7 +665,7 @@ func (a *Api) GetCurrentPlanState(planId, branch string) (*shared.CurrentPlanSta
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
if tokenRefreshed {
return a.GetCurrentPlanState(planId, branch)
@@ -657,7 +683,7 @@ func (a *Api) GetCurrentPlanState(planId, branch string) (*shared.CurrentPlanSta
}
func (a *Api) ApplyPlan(planId, branch string, req shared.ApplyPlanRequest) (string, *shared.ApiError) {
- serverUrl := fmt.Sprintf("%s/plans/%s/%s/apply", getApiHost(), planId, branch)
+ serverUrl := fmt.Sprintf("%s/plans/%s/%s/apply", GetApiHost(), planId, branch)
reqBytes, err := json.Marshal(req)
if err != nil {
@@ -678,7 +704,7 @@ func (a *Api) ApplyPlan(planId, branch string, req shared.ApplyPlanRequest) (str
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
didRefresh, apiErr := refreshTokenIfNeeded(apiErr)
if didRefresh {
@@ -697,7 +723,7 @@ func (a *Api) ApplyPlan(planId, branch string, req shared.ApplyPlanRequest) (str
}
func (a *Api) ArchivePlan(planId string) *shared.ApiError {
- serverUrl := fmt.Sprintf("%s/plans/%s/archive", getApiHost(), planId)
+ serverUrl := fmt.Sprintf("%s/plans/%s/archive", GetApiHost(), planId)
req, err := http.NewRequest(http.MethodPatch, serverUrl, nil)
if err != nil {
@@ -712,7 +738,7 @@ func (a *Api) ArchivePlan(planId string) *shared.ApiError {
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
didRefresh, apiErr := refreshTokenIfNeeded(apiErr)
if didRefresh {
@@ -725,7 +751,7 @@ func (a *Api) ArchivePlan(planId string) *shared.ApiError {
}
func (a *Api) UnarchivePlan(planId string) *shared.ApiError {
- serverUrl := fmt.Sprintf("%s/plans/%s/unarchive", getApiHost(), planId)
+ serverUrl := fmt.Sprintf("%s/plans/%s/unarchive", GetApiHost(), planId)
req, err := http.NewRequest(http.MethodPatch, serverUrl, nil)
if err != nil {
@@ -740,7 +766,7 @@ func (a *Api) UnarchivePlan(planId string) *shared.ApiError {
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
didRefresh, apiErr := refreshTokenIfNeeded(apiErr)
if didRefresh {
@@ -753,7 +779,7 @@ func (a *Api) UnarchivePlan(planId string) *shared.ApiError {
}
func (a *Api) RenamePlan(planId string, name string) *shared.ApiError {
- serverUrl := fmt.Sprintf("%s/plans/%s/rename", getApiHost(), planId)
+ serverUrl := fmt.Sprintf("%s/plans/%s/rename", GetApiHost(), planId)
reqBytes, err := json.Marshal(shared.RenamePlanRequest{Name: name})
if err != nil {
@@ -779,7 +805,7 @@ func (a *Api) RenamePlan(planId string, name string) *shared.ApiError {
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
didRefresh, apiErr := refreshTokenIfNeeded(apiErr)
if didRefresh {
@@ -792,7 +818,7 @@ func (a *Api) RenamePlan(planId string, name string) *shared.ApiError {
}
func (a *Api) RejectAllChanges(planId, branch string) *shared.ApiError {
- serverUrl := fmt.Sprintf("%s/plans/%s/%s/reject_all", getApiHost(), planId, branch)
+ serverUrl := fmt.Sprintf("%s/plans/%s/%s/reject_all", GetApiHost(), planId, branch)
req, err := http.NewRequest(http.MethodPatch, serverUrl, nil)
if err != nil {
@@ -807,7 +833,7 @@ func (a *Api) RejectAllChanges(planId, branch string) *shared.ApiError {
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
didRefresh, apiErr := refreshTokenIfNeeded(apiErr)
if didRefresh {
@@ -820,7 +846,7 @@ func (a *Api) RejectAllChanges(planId, branch string) *shared.ApiError {
}
func (a *Api) RejectFile(planId, branch, filePath string) *shared.ApiError {
- serverUrl := fmt.Sprintf("%s/plans/%s/%s/reject_file", getApiHost(), planId, branch)
+ serverUrl := fmt.Sprintf("%s/plans/%s/%s/reject_file", GetApiHost(), planId, branch)
reqBytes, err := json.Marshal(shared.RejectFileRequest{FilePath: filePath})
@@ -842,7 +868,7 @@ func (a *Api) RejectFile(planId, branch, filePath string) *shared.ApiError {
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
didRefresh, apiErr := refreshTokenIfNeeded(apiErr)
if didRefresh {
a.RejectFile(planId, branch, filePath)
@@ -854,7 +880,7 @@ func (a *Api) RejectFile(planId, branch, filePath string) *shared.ApiError {
}
func (a *Api) RejectFiles(planId, branch string, paths []string) *shared.ApiError {
- serverUrl := fmt.Sprintf("%s/plans/%s/%s/reject_files", getApiHost(), planId, branch)
+ serverUrl := fmt.Sprintf("%s/plans/%s/%s/reject_files", GetApiHost(), planId, branch)
reqBytes, err := json.Marshal(shared.RejectFilesRequest{Paths: paths})
@@ -876,7 +902,7 @@ func (a *Api) RejectFiles(planId, branch string, paths []string) *shared.ApiErro
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
didRefresh, apiErr := refreshTokenIfNeeded(apiErr)
if didRefresh {
a.RejectFiles(planId, branch, paths)
@@ -888,7 +914,7 @@ func (a *Api) RejectFiles(planId, branch string, paths []string) *shared.ApiErro
}
func (a *Api) LoadContext(planId, branch string, req shared.LoadContextRequest) (*shared.LoadContextResponse, *shared.ApiError) {
- serverUrl := fmt.Sprintf("%s/plans/%s/%s/context", getApiHost(), planId, branch)
+ serverUrl := fmt.Sprintf("%s/plans/%s/%s/context", GetApiHost(), planId, branch)
reqBytes, err := json.Marshal(req)
if err != nil {
return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error marshalling request: %v", err)}
@@ -903,7 +929,7 @@ func (a *Api) LoadContext(planId, branch string, req shared.LoadContextRequest)
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
if tokenRefreshed {
return a.LoadContext(planId, branch, req)
@@ -921,7 +947,7 @@ func (a *Api) LoadContext(planId, branch string, req shared.LoadContextRequest)
}
func (a *Api) UpdateContext(planId, branch string, req shared.UpdateContextRequest) (*shared.UpdateContextResponse, *shared.ApiError) {
- serverUrl := fmt.Sprintf("%s/plans/%s/%s/context", getApiHost(), planId, branch)
+ serverUrl := fmt.Sprintf("%s/plans/%s/%s/context", GetApiHost(), planId, branch)
reqBytes, err := json.Marshal(req)
if err != nil {
@@ -945,7 +971,7 @@ func (a *Api) UpdateContext(planId, branch string, req shared.UpdateContextReque
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
if tokenRefreshed {
return a.UpdateContext(planId, branch, req)
@@ -963,7 +989,7 @@ func (a *Api) UpdateContext(planId, branch string, req shared.UpdateContextReque
}
func (a *Api) DeleteContext(planId, branch string, req shared.DeleteContextRequest) (*shared.DeleteContextResponse, *shared.ApiError) {
- serverUrl := fmt.Sprintf("%s/plans/%s/%s/context", getApiHost(), planId, branch)
+ serverUrl := fmt.Sprintf("%s/plans/%s/%s/context", GetApiHost(), planId, branch)
reqBytes, err := json.Marshal(req)
if err != nil {
return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error marshalling request: %v", err)}
@@ -983,7 +1009,7 @@ func (a *Api) DeleteContext(planId, branch string, req shared.DeleteContextReque
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
if tokenRefreshed {
return a.DeleteContext(planId, branch, req)
@@ -1001,7 +1027,7 @@ func (a *Api) DeleteContext(planId, branch string, req shared.DeleteContextReque
}
func (a *Api) ListContext(planId, branch string) ([]*shared.Context, *shared.ApiError) {
- serverUrl := fmt.Sprintf("%s/plans/%s/%s/context", getApiHost(), planId, branch)
+ serverUrl := fmt.Sprintf("%s/plans/%s/%s/context", GetApiHost(), planId, branch)
resp, err := authenticatedFastClient.Get(serverUrl)
if err != nil {
@@ -1011,7 +1037,7 @@ func (a *Api) ListContext(planId, branch string) ([]*shared.Context, *shared.Api
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
if tokenRefreshed {
return a.ListContext(planId, branch)
@@ -1029,7 +1055,7 @@ func (a *Api) ListContext(planId, branch string) ([]*shared.Context, *shared.Api
}
func (a *Api) ListConvo(planId, branch string) ([]*shared.ConvoMessage, *shared.ApiError) {
- serverUrl := fmt.Sprintf("%s/plans/%s/%s/convo", getApiHost(), planId, branch)
+ serverUrl := fmt.Sprintf("%s/plans/%s/%s/convo", GetApiHost(), planId, branch)
resp, err := authenticatedFastClient.Get(serverUrl)
if err != nil {
@@ -1039,7 +1065,7 @@ func (a *Api) ListConvo(planId, branch string) ([]*shared.ConvoMessage, *shared.
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
if tokenRefreshed {
return a.ListConvo(planId, branch)
@@ -1057,7 +1083,7 @@ func (a *Api) ListConvo(planId, branch string) ([]*shared.ConvoMessage, *shared.
}
func (a *Api) GetPlanStatus(planId, branch string) (string, *shared.ApiError) {
- serverUrl := fmt.Sprintf("%s/plans/%s/%s/status", getApiHost(), planId, branch)
+ serverUrl := fmt.Sprintf("%s/plans/%s/%s/status", GetApiHost(), planId, branch)
resp, err := authenticatedFastClient.Get(serverUrl)
if err != nil {
@@ -1067,7 +1093,7 @@ func (a *Api) GetPlanStatus(planId, branch string) (string, *shared.ApiError) {
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
if tokenRefreshed {
return a.GetPlanStatus(planId, branch)
@@ -1085,7 +1111,7 @@ func (a *Api) GetPlanStatus(planId, branch string) (string, *shared.ApiError) {
}
func (a *Api) GetPlanDiffs(planId, branch string) (string, *shared.ApiError) {
- serverUrl := fmt.Sprintf("%s/plans/%s/%s/diffs", getApiHost(), planId, branch)
+ serverUrl := fmt.Sprintf("%s/plans/%s/%s/diffs", GetApiHost(), planId, branch)
resp, err := authenticatedFastClient.Get(serverUrl)
if err != nil {
@@ -1095,7 +1121,7 @@ func (a *Api) GetPlanDiffs(planId, branch string) (string, *shared.ApiError) {
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
if tokenRefreshed {
return a.GetPlanDiffs(planId, branch)
@@ -1113,7 +1139,7 @@ func (a *Api) GetPlanDiffs(planId, branch string) (string, *shared.ApiError) {
}
func (a *Api) ListLogs(planId, branch string) (*shared.LogResponse, *shared.ApiError) {
- serverUrl := fmt.Sprintf("%s/plans/%s/%s/logs", getApiHost(), planId, branch)
+ serverUrl := fmt.Sprintf("%s/plans/%s/%s/logs", GetApiHost(), planId, branch)
resp, err := authenticatedFastClient.Get(serverUrl)
if err != nil {
@@ -1124,7 +1150,7 @@ func (a *Api) ListLogs(planId, branch string) (*shared.LogResponse, *shared.ApiE
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
if tokenRefreshed {
return a.ListLogs(planId, branch)
@@ -1142,7 +1168,7 @@ func (a *Api) ListLogs(planId, branch string) (*shared.LogResponse, *shared.ApiE
}
func (a *Api) RewindPlan(planId, branch string, req shared.RewindPlanRequest) (*shared.RewindPlanResponse, *shared.ApiError) {
- serverUrl := fmt.Sprintf("%s/plans/%s/%s/rewind", getApiHost(), planId, branch)
+ serverUrl := fmt.Sprintf("%s/plans/%s/%s/rewind", GetApiHost(), planId, branch)
reqBytes, err := json.Marshal(req)
if err != nil {
return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error marshalling request: %v", err)}
@@ -1163,7 +1189,7 @@ func (a *Api) RewindPlan(planId, branch string, req shared.RewindPlanRequest) (*
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
if tokenRefreshed {
return a.RewindPlan(planId, branch, req)
@@ -1183,7 +1209,7 @@ func (a *Api) RewindPlan(planId, branch string, req shared.RewindPlanRequest) (*
func (a *Api) SignIn(req shared.SignInRequest, customHost string) (*shared.SessionResponse, *shared.ApiError) {
host := customHost
if host == "" {
- host = cloudApiHost
+ host = CloudApiHost
}
serverUrl := host + "/accounts/sign_in"
reqBytes, err := json.Marshal(req)
@@ -1199,7 +1225,7 @@ func (a *Api) SignIn(req shared.SignInRequest, customHost string) (*shared.Sessi
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
return nil, apiErr
}
@@ -1215,7 +1241,7 @@ func (a *Api) SignIn(req shared.SignInRequest, customHost string) (*shared.Sessi
func (a *Api) CreateAccount(req shared.CreateAccountRequest, customHost string) (*shared.SessionResponse, *shared.ApiError) {
host := customHost
if host == "" {
- host = cloudApiHost
+ host = CloudApiHost
}
serverUrl := host + "/accounts"
reqBytes, err := json.Marshal(req)
@@ -1231,35 +1257,7 @@ func (a *Api) CreateAccount(req shared.CreateAccountRequest, customHost string)
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
- return nil, apiErr
- }
-
- var sessionResponse shared.SessionResponse
- err = json.NewDecoder(resp.Body).Decode(&sessionResponse)
- if err != nil {
- return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error decoding response: %v", err)}
- }
-
- return &sessionResponse, nil
-}
-
-func (a *Api) ConvertTrial(req shared.ConvertTrialRequest) (*shared.SessionResponse, *shared.ApiError) {
- serverUrl := getApiHost() + "/accounts/convert_trial"
- reqBytes, err := json.Marshal(req)
- if err != nil {
- return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error marshalling request: %v", err)}
- }
-
- resp, err := authenticatedFastClient.Post(serverUrl, "application/json", bytes.NewBuffer(reqBytes))
- if err != nil {
- return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %v", err)}
- }
- defer resp.Body.Close()
-
- if resp.StatusCode >= 400 {
- errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
return nil, apiErr
}
@@ -1273,7 +1271,7 @@ func (a *Api) ConvertTrial(req shared.ConvertTrialRequest) (*shared.SessionRespo
}
func (a *Api) CreateOrg(req shared.CreateOrgRequest) (*shared.CreateOrgResponse, *shared.ApiError) {
- serverUrl := getApiHost() + "/orgs"
+ serverUrl := GetApiHost() + "/orgs"
reqBytes, err := json.Marshal(req)
if err != nil {
return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error marshalling request: %v", err)}
@@ -1287,7 +1285,7 @@ func (a *Api) CreateOrg(req shared.CreateOrgRequest) (*shared.CreateOrgResponse,
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
if tokenRefreshed {
return a.CreateOrg(req)
@@ -1305,7 +1303,7 @@ func (a *Api) CreateOrg(req shared.CreateOrgRequest) (*shared.CreateOrgResponse,
}
func (a *Api) GetOrgSession() (*shared.Org, *shared.ApiError) {
- serverUrl := getApiHost() + "/orgs/session"
+ serverUrl := GetApiHost() + "/orgs/session"
resp, err := authenticatedFastClient.Get(serverUrl)
if err != nil {
return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %v", err)}
@@ -1314,7 +1312,7 @@ func (a *Api) GetOrgSession() (*shared.Org, *shared.ApiError) {
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
if tokenRefreshed {
return a.GetOrgSession()
@@ -1334,7 +1332,7 @@ func (a *Api) GetOrgSession() (*shared.Org, *shared.ApiError) {
}
func (a *Api) ListOrgs() ([]*shared.Org, *shared.ApiError) {
- serverUrl := getApiHost() + "/orgs"
+ serverUrl := GetApiHost() + "/orgs"
resp, err := authenticatedFastClient.Get(serverUrl)
if err != nil {
return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %v", err)}
@@ -1343,7 +1341,7 @@ func (a *Api) ListOrgs() ([]*shared.Org, *shared.ApiError) {
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
if tokenRefreshed {
return a.ListOrgs()
@@ -1361,7 +1359,7 @@ func (a *Api) ListOrgs() ([]*shared.Org, *shared.ApiError) {
}
func (a *Api) DeleteUser(userId string) *shared.ApiError {
- serverUrl := fmt.Sprintf("%s/orgs/users/%s", getApiHost(), userId)
+ serverUrl := fmt.Sprintf("%s/orgs/users/%s", GetApiHost(), userId)
req, err := http.NewRequest(http.MethodDelete, serverUrl, nil)
if err != nil {
return &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error creating request: %v", err)}
@@ -1375,7 +1373,7 @@ func (a *Api) DeleteUser(userId string) *shared.ApiError {
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
if tokenRefreshed {
return a.DeleteUser(userId)
@@ -1387,7 +1385,7 @@ func (a *Api) DeleteUser(userId string) *shared.ApiError {
}
func (a *Api) ListOrgRoles() ([]*shared.OrgRole, *shared.ApiError) {
- serverUrl := getApiHost() + "/orgs/roles"
+ serverUrl := GetApiHost() + "/orgs/roles"
resp, err := authenticatedFastClient.Get(serverUrl)
if err != nil {
return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %s", err)}
@@ -1397,7 +1395,7 @@ func (a *Api) ListOrgRoles() ([]*shared.OrgRole, *shared.ApiError) {
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
if tokenRefreshed {
return a.ListOrgRoles()
@@ -1415,7 +1413,7 @@ func (a *Api) ListOrgRoles() ([]*shared.OrgRole, *shared.ApiError) {
}
func (a *Api) InviteUser(req shared.InviteRequest) *shared.ApiError {
- serverUrl := getApiHost() + "/invites"
+ serverUrl := GetApiHost() + "/invites"
reqBytes, err := json.Marshal(req)
if err != nil {
return &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error marshalling request: %v", err)}
@@ -1429,7 +1427,7 @@ func (a *Api) InviteUser(req shared.InviteRequest) *shared.ApiError {
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
if tokenRefreshed {
@@ -1442,7 +1440,7 @@ func (a *Api) InviteUser(req shared.InviteRequest) *shared.ApiError {
}
func (a *Api) ListPendingInvites() ([]*shared.Invite, *shared.ApiError) {
- serverUrl := getApiHost() + "/invites/pending"
+ serverUrl := GetApiHost() + "/invites/pending"
resp, err := authenticatedFastClient.Get(serverUrl)
if err != nil {
return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %v", err)}
@@ -1451,7 +1449,7 @@ func (a *Api) ListPendingInvites() ([]*shared.Invite, *shared.ApiError) {
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
if tokenRefreshed {
return a.ListPendingInvites()
@@ -1469,7 +1467,7 @@ func (a *Api) ListPendingInvites() ([]*shared.Invite, *shared.ApiError) {
}
func (a *Api) ListAcceptedInvites() ([]*shared.Invite, *shared.ApiError) {
- serverUrl := getApiHost() + "/invites/accepted"
+ serverUrl := GetApiHost() + "/invites/accepted"
resp, err := authenticatedFastClient.Get(serverUrl)
if err != nil {
return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %v", err)}
@@ -1478,7 +1476,7 @@ func (a *Api) ListAcceptedInvites() ([]*shared.Invite, *shared.ApiError) {
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
if tokenRefreshed {
return a.ListAcceptedInvites()
@@ -1496,7 +1494,7 @@ func (a *Api) ListAcceptedInvites() ([]*shared.Invite, *shared.ApiError) {
}
func (a *Api) ListAllInvites() ([]*shared.Invite, *shared.ApiError) {
- serverUrl := getApiHost() + "/invites/all"
+ serverUrl := GetApiHost() + "/invites/all"
resp, err := authenticatedFastClient.Get(serverUrl)
if err != nil {
return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %v", err)}
@@ -1505,7 +1503,7 @@ func (a *Api) ListAllInvites() ([]*shared.Invite, *shared.ApiError) {
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
if tokenRefreshed {
return a.ListAllInvites()
@@ -1523,7 +1521,7 @@ func (a *Api) ListAllInvites() ([]*shared.Invite, *shared.ApiError) {
}
func (a *Api) DeleteInvite(inviteId string) *shared.ApiError {
- serverUrl := fmt.Sprintf("%s/invites/%s", getApiHost(), inviteId)
+ serverUrl := fmt.Sprintf("%s/invites/%s", GetApiHost(), inviteId)
req, err := http.NewRequest(http.MethodDelete, serverUrl, nil)
if err != nil {
return &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error creating request: %v", err)}
@@ -1537,7 +1535,7 @@ func (a *Api) DeleteInvite(inviteId string) *shared.ApiError {
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
if tokenRefreshed {
@@ -1552,7 +1550,7 @@ func (a *Api) DeleteInvite(inviteId string) *shared.ApiError {
func (a *Api) CreateEmailVerification(email, customHost, userId string) (*shared.CreateEmailVerificationResponse, *shared.ApiError) {
host := customHost
if host == "" {
- host = cloudApiHost
+ host = CloudApiHost
}
serverUrl := host + "/accounts/email_verifications"
req := shared.CreateEmailVerificationRequest{Email: email, UserId: userId}
@@ -1569,7 +1567,7 @@ func (a *Api) CreateEmailVerification(email, customHost, userId string) (*shared
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- return nil, handleApiError(resp, errorBody)
+ return nil, HandleApiError(resp, errorBody)
}
var verificationResponse shared.CreateEmailVerificationResponse
@@ -1581,8 +1579,36 @@ func (a *Api) CreateEmailVerification(email, customHost, userId string) (*shared
return &verificationResponse, nil
}
+func (a *Api) CreateSignInCode() (string, *shared.ApiError) {
+ serverUrl := GetApiHost() + "/accounts/sign_in_codes"
+ resp, err := authenticatedFastClient.Post(serverUrl, "application/json", nil)
+ if err != nil {
+ return "", &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %v", err)}
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode >= 400 {
+ errorBody, _ := io.ReadAll(resp.Body)
+ apiErr := HandleApiError(resp, errorBody)
+ tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
+ if tokenRefreshed {
+ return a.CreateSignInCode()
+ }
+ return "", apiErr
+ }
+
+ var signInCode string
+ body, err := io.ReadAll(resp.Body)
+ if err != nil {
+ return "", &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error reading response body: %v", err)}
+ }
+ signInCode = string(body)
+
+ return signInCode, nil
+}
+
func (a *Api) SignOut() *shared.ApiError {
- serverUrl := getApiHost() + "/accounts/sign_out"
+ serverUrl := GetApiHost() + "/accounts/sign_out"
req, err := http.NewRequest(http.MethodPost, serverUrl, nil)
if err != nil {
@@ -1597,14 +1623,14 @@ func (a *Api) SignOut() *shared.ApiError {
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- return handleApiError(resp, errorBody)
+ return HandleApiError(resp, errorBody)
}
return nil
}
func (a *Api) ListUsers() (*shared.ListUsersResponse, *shared.ApiError) {
- serverUrl := getApiHost() + "/users"
+ serverUrl := GetApiHost() + "/users"
resp, err := authenticatedFastClient.Get(serverUrl)
if err != nil {
return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %v", err)}
@@ -1613,7 +1639,7 @@ func (a *Api) ListUsers() (*shared.ListUsersResponse, *shared.ApiError) {
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
if tokenRefreshed {
return a.ListUsers()
@@ -1631,7 +1657,7 @@ func (a *Api) ListUsers() (*shared.ListUsersResponse, *shared.ApiError) {
}
func (a *Api) ListBranches(planId string) ([]*shared.Branch, *shared.ApiError) {
- serverUrl := fmt.Sprintf("%s/plans/%s/branches", getApiHost(), planId)
+ serverUrl := fmt.Sprintf("%s/plans/%s/branches", GetApiHost(), planId)
resp, err := authenticatedFastClient.Get(serverUrl)
if err != nil {
@@ -1642,7 +1668,7 @@ func (a *Api) ListBranches(planId string) ([]*shared.Branch, *shared.ApiError) {
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
if tokenRefreshed {
return a.ListBranches(planId)
@@ -1660,7 +1686,7 @@ func (a *Api) ListBranches(planId string) ([]*shared.Branch, *shared.ApiError) {
}
func (a *Api) CreateBranch(planId, branch string, req shared.CreateBranchRequest) *shared.ApiError {
- serverUrl := fmt.Sprintf("%s/plans/%s/%s/branches", getApiHost(), planId, branch)
+ serverUrl := fmt.Sprintf("%s/plans/%s/%s/branches", GetApiHost(), planId, branch)
reqBytes, err := json.Marshal(req)
if err != nil {
@@ -1676,7 +1702,7 @@ func (a *Api) CreateBranch(planId, branch string, req shared.CreateBranchRequest
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
if tokenRefreshed {
return a.CreateBranch(planId, branch, req)
@@ -1688,7 +1714,7 @@ func (a *Api) CreateBranch(planId, branch string, req shared.CreateBranchRequest
}
func (a *Api) DeleteBranch(planId, branch string) *shared.ApiError {
- serverUrl := fmt.Sprintf("%s/plans/%s/branches/%s", getApiHost(), planId, branch)
+ serverUrl := fmt.Sprintf("%s/plans/%s/branches/%s", GetApiHost(), planId, branch)
req, err := http.NewRequest(http.MethodDelete, serverUrl, nil)
if err != nil {
@@ -1704,7 +1730,7 @@ func (a *Api) DeleteBranch(planId, branch string) *shared.ApiError {
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
if tokenRefreshed {
return a.DeleteBranch(planId, branch)
@@ -1716,7 +1742,7 @@ func (a *Api) DeleteBranch(planId, branch string) *shared.ApiError {
}
func (a *Api) GetSettings(planId, branch string) (*shared.PlanSettings, *shared.ApiError) {
- serverUrl := fmt.Sprintf("%s/plans/%s/%s/settings", getApiHost(), planId, branch)
+ serverUrl := fmt.Sprintf("%s/plans/%s/%s/settings", GetApiHost(), planId, branch)
resp, err := authenticatedFastClient.Get(serverUrl)
@@ -1727,7 +1753,7 @@ func (a *Api) GetSettings(planId, branch string) (*shared.PlanSettings, *shared.
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
if tokenRefreshed {
return a.GetSettings(planId, branch)
@@ -1745,7 +1771,7 @@ func (a *Api) GetSettings(planId, branch string) (*shared.PlanSettings, *shared.
}
func (a *Api) UpdateSettings(planId, branch string, req shared.UpdateSettingsRequest) (*shared.UpdateSettingsResponse, *shared.ApiError) {
- serverUrl := fmt.Sprintf("%s/plans/%s/%s/settings", getApiHost(), planId, branch)
+ serverUrl := fmt.Sprintf("%s/plans/%s/%s/settings", GetApiHost(), planId, branch)
reqBytes, err := json.Marshal(req)
if err != nil {
@@ -1769,7 +1795,7 @@ func (a *Api) UpdateSettings(planId, branch string, req shared.UpdateSettingsReq
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
if tokenRefreshed {
return a.UpdateSettings(planId, branch, req)
@@ -1788,7 +1814,7 @@ func (a *Api) UpdateSettings(planId, branch string, req shared.UpdateSettingsReq
}
func (a *Api) GetOrgDefaultSettings() (*shared.PlanSettings, *shared.ApiError) {
- serverUrl := fmt.Sprintf("%s/default_settings", getApiHost())
+ serverUrl := fmt.Sprintf("%s/default_settings", GetApiHost())
resp, err := authenticatedFastClient.Get(serverUrl)
@@ -1799,7 +1825,7 @@ func (a *Api) GetOrgDefaultSettings() (*shared.PlanSettings, *shared.ApiError) {
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
if tokenRefreshed {
return a.GetOrgDefaultSettings()
@@ -1817,7 +1843,7 @@ func (a *Api) GetOrgDefaultSettings() (*shared.PlanSettings, *shared.ApiError) {
}
func (a *Api) UpdateOrgDefaultSettings(req shared.UpdateSettingsRequest) (*shared.UpdateSettingsResponse, *shared.ApiError) {
- serverUrl := fmt.Sprintf("%s/default_settings", getApiHost())
+ serverUrl := fmt.Sprintf("%s/default_settings", GetApiHost())
reqBytes, err := json.Marshal(req)
if err != nil {
@@ -1841,7 +1867,7 @@ func (a *Api) UpdateOrgDefaultSettings(req shared.UpdateSettingsRequest) (*share
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
if tokenRefreshed {
return a.UpdateOrgDefaultSettings(req)
@@ -1860,7 +1886,7 @@ func (a *Api) UpdateOrgDefaultSettings(req shared.UpdateSettingsRequest) (*share
}
func (a *Api) CreateCustomModel(model *shared.AvailableModel) *shared.ApiError {
- serverUrl := fmt.Sprintf("%s/custom_models", getApiHost())
+ serverUrl := fmt.Sprintf("%s/custom_models", GetApiHost())
body, err := json.Marshal(model)
if err != nil {
return &shared.ApiError{Msg: "Failed to marshal model"}
@@ -1875,7 +1901,7 @@ func (a *Api) CreateCustomModel(model *shared.AvailableModel) *shared.ApiError {
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
if tokenRefreshed {
return a.CreateCustomModel(model)
@@ -1887,7 +1913,7 @@ func (a *Api) CreateCustomModel(model *shared.AvailableModel) *shared.ApiError {
}
func (a *Api) ListCustomModels() ([]*shared.AvailableModel, *shared.ApiError) {
- serverUrl := fmt.Sprintf("%s/custom_models", getApiHost())
+ serverUrl := fmt.Sprintf("%s/custom_models", GetApiHost())
resp, err := authenticatedFastClient.Get(serverUrl)
if err != nil {
return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %v", err)}
@@ -1897,7 +1923,7 @@ func (a *Api) ListCustomModels() ([]*shared.AvailableModel, *shared.ApiError) {
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
if tokenRefreshed {
return a.ListCustomModels()
@@ -1915,7 +1941,7 @@ func (a *Api) ListCustomModels() ([]*shared.AvailableModel, *shared.ApiError) {
}
func (a *Api) DeleteAvailableModel(modelId string) *shared.ApiError {
- serverUrl := fmt.Sprintf("%s/custom_models/%s", getApiHost(), modelId)
+ serverUrl := fmt.Sprintf("%s/custom_models/%s", GetApiHost(), modelId)
req, err := http.NewRequest(http.MethodDelete, serverUrl, nil)
if err != nil {
return &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error creating request: %v", err)}
@@ -1930,7 +1956,7 @@ func (a *Api) DeleteAvailableModel(modelId string) *shared.ApiError {
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
if tokenRefreshed {
return a.DeleteAvailableModel(modelId)
@@ -1942,7 +1968,7 @@ func (a *Api) DeleteAvailableModel(modelId string) *shared.ApiError {
}
func (a *Api) CreateModelPack(set *shared.ModelPack) *shared.ApiError {
- serverUrl := fmt.Sprintf("%s/model_sets", getApiHost())
+ serverUrl := fmt.Sprintf("%s/model_sets", GetApiHost())
body, err := json.Marshal(set)
if err != nil {
return &shared.ApiError{Msg: "Failed to marshal model pack"}
@@ -1957,7 +1983,7 @@ func (a *Api) CreateModelPack(set *shared.ModelPack) *shared.ApiError {
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
if tokenRefreshed {
return a.CreateModelPack(set)
@@ -1970,7 +1996,7 @@ func (a *Api) CreateModelPack(set *shared.ModelPack) *shared.ApiError {
}
func (a *Api) ListModelPacks() ([]*shared.ModelPack, *shared.ApiError) {
- serverUrl := fmt.Sprintf("%s/model_sets", getApiHost())
+ serverUrl := fmt.Sprintf("%s/model_sets", GetApiHost())
resp, err := authenticatedFastClient.Get(serverUrl)
if err != nil {
@@ -1981,7 +2007,7 @@ func (a *Api) ListModelPacks() ([]*shared.ModelPack, *shared.ApiError) {
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
if tokenRefreshed {
return a.ListModelPacks()
@@ -2000,7 +2026,7 @@ func (a *Api) ListModelPacks() ([]*shared.ModelPack, *shared.ApiError) {
}
func (a *Api) DeleteModelPack(setId string) *shared.ApiError {
- serverUrl := fmt.Sprintf("%s/model_sets/%s", getApiHost(), setId)
+ serverUrl := fmt.Sprintf("%s/model_sets/%s", GetApiHost(), setId)
req, err := http.NewRequest(http.MethodDelete, serverUrl, nil)
if err != nil {
@@ -2016,7 +2042,7 @@ func (a *Api) DeleteModelPack(setId string) *shared.ApiError {
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
if tokenRefreshed {
return a.DeleteModelPack(setId)
@@ -2028,7 +2054,7 @@ func (a *Api) DeleteModelPack(setId string) *shared.ApiError {
}
func (a *Api) GetCreditsTransactions(pageSize, pageNum int) (*shared.CreditsLogResponse, *shared.ApiError) {
- serverUrl := fmt.Sprintf("%s/billing/credits_transactions?size=%d&page=%d", getApiHost(), pageSize, pageNum)
+ serverUrl := fmt.Sprintf("%s/billing/credits_transactions?size=%d&page=%d", GetApiHost(), pageSize, pageNum)
resp, err := authenticatedFastClient.Get(serverUrl)
if err != nil {
@@ -2039,7 +2065,7 @@ func (a *Api) GetCreditsTransactions(pageSize, pageNum int) (*shared.CreditsLogR
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
- apiErr := handleApiError(resp, errorBody)
+ apiErr := HandleApiError(resp, errorBody)
tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
if tokenRefreshed {
return a.GetCreditsTransactions(pageSize, pageNum)
diff --git a/app/cli/auth/account.go b/app/cli/auth/account.go
index 94248a77..abb914bb 100644
--- a/app/cli/auth/account.go
+++ b/app/cli/auth/account.go
@@ -9,8 +9,8 @@ import (
)
const (
- AuthFreeTrialOption = "Start a trial on Plandex Cloud"
- AuthAccountOption = "Sign in, accept an invite, or create an account"
+ AuthTrialOption = "Start a trial on Plandex Cloud"
+ AuthAccountOption = "Sign in, accept an invite, or create an account"
)
const AddAccountOption = "Add another account"
@@ -124,19 +124,15 @@ func SignInWithCode(code, host string) error {
}
func promptInitialAuth() error {
- selected, err := term.SelectFromList("👋 Hey there!\nIt looks like this is your first time using Plandex on this computer.\nWhat would you like to do?", []string{AuthFreeTrialOption, AuthAccountOption})
+ selected, err := term.SelectFromList("👋 Hey there!\nIt looks like this is your first time using Plandex on this computer.\nWhat would you like to do?", []string{AuthTrialOption, AuthAccountOption})
if err != nil {
return fmt.Errorf("error selecting auth option: %v", err)
}
switch selected {
- case AuthFreeTrialOption:
- err = startTrial()
-
- if err != nil {
- return fmt.Errorf("error starting trial: %v", err)
- }
+ case AuthTrialOption:
+ startTrial()
case AuthAccountOption:
err = SelectOrSignInOrCreate()
diff --git a/app/cli/auth/api.go b/app/cli/auth/api.go
index 3aed52c7..60088cb4 100644
--- a/app/cli/auth/api.go
+++ b/app/cli/auth/api.go
@@ -33,7 +33,7 @@ func SetAuthHeader(req *http.Request) error {
}
// base64 encode
- token := base64.StdEncoding.EncodeToString(bytes)
+ token := base64.URLEncoding.EncodeToString(bytes)
req.Header.Set("Authorization", "Bearer "+token)
diff --git a/app/cli/auth/auth.go b/app/cli/auth/auth.go
index cb7171fe..9eb99c33 100644
--- a/app/cli/auth/auth.go
+++ b/app/cli/auth/auth.go
@@ -10,6 +10,17 @@ import (
"github.com/plandex/plandex/shared"
)
+var openUnauthenticatedCloudURL func(msg, path string)
+var openAuthenticatedURL func(msg, path string)
+
+func SetOpenUnauthenticatedCloudURLFn(fn func(msg, path string)) {
+ openUnauthenticatedCloudURL = fn
+}
+
+func SetOpenAuthenticatedURLFn(fn func(msg, path string)) {
+ openAuthenticatedURL = fn
+}
+
func MustResolveAuthWithOrg() {
MustResolveAuth(true)
}
diff --git a/app/cli/auth/trial.go b/app/cli/auth/trial.go
index 553a4c0b..e0bfeaa6 100644
--- a/app/cli/auth/trial.go
+++ b/app/cli/auth/trial.go
@@ -3,205 +3,85 @@ package auth
import (
"fmt"
"plandex/term"
-
- "github.com/fatih/color"
- "github.com/plandex/plandex/shared"
+ "time"
)
-func ConvertTrial() error {
- email, err := term.GetRequiredUserStringInput("Your email:")
-
- if err != nil {
- return fmt.Errorf("error prompting email: %v", err)
- }
-
- hasAccount, pin, err := verifyEmail(email, "")
+func ConvertTrial() {
+ openAuthenticatedURL("Opening Plandex Cloud upgrade flow in your browser.", "/settings/billing?upgrade=1&cliUpgrade=1")
- if err != nil {
- return fmt.Errorf("error verifying email: %v", err)
- }
+ fmt.Println("\nCommand will continue automatically once you've upgraded...")
+ fmt.Println()
+ term.StartSpinner("")
- if hasAccount {
- term.OutputErrorAndExit("Can't convert a trial into an account that already exists")
- }
+ startTime := time.Now()
+ expirationTime := startTime.Add(1 * time.Hour)
- name, err := term.GetUserStringInput("Your name:")
+ for time.Now().Before(expirationTime) {
+ org, apiErr := apiClient.GetOrgSession()
- if err != nil {
- return fmt.Errorf("error prompting name: %v", err)
- }
+ if apiErr != nil {
+ term.StopSpinner()
+ term.OutputErrorAndExit("error getting org session: %s", apiErr.Msg)
+ }
- orgName, err := term.GetRequiredUserStringInput("Org name:")
+ if org != nil && !org.IsTrial {
+ term.StopSpinner()
+ fmt.Println("🚀 Trial upgraded")
+ fmt.Println()
+ return
+ }
- if err != nil {
- return fmt.Errorf("error prompting org name: %v", err)
+ time.Sleep(1500 * time.Millisecond)
}
- autoAddDomainUsers, err := promptAutoAddUsersIfValid(email)
-
- if err != nil {
- return fmt.Errorf("error prompting auto add domain users: %v", err)
- }
+ term.StopSpinner()
+ term.OutputErrorAndExit("Timed out waiting for upgrade. Please try again. Email [email protected] if the problem persists.")
+}
+func startTrial() {
term.StartSpinner("")
- res, apiErr := apiClient.ConvertTrial(shared.ConvertTrialRequest{
- Email: email,
- Pin: pin,
- UserName: name,
- OrgName: orgName,
- OrgAutoAddDomainUsers: autoAddDomainUsers,
- })
+ cliTrialToken, apiErr := apiClient.CreateCliTrialSession()
term.StopSpinner()
if apiErr != nil {
- return fmt.Errorf("error converting trial: %v", apiErr)
+ term.OutputErrorAndExit("error starting trial: %s", apiErr.Msg)
}
- err = setAuth(&shared.ClientAuth{
- ClientAccount: shared.ClientAccount{
- Email: res.Email,
- UserId: res.UserId,
- UserName: res.UserName,
- Token: res.Token,
- IsCloud: true,
- IsTrial: false,
- },
- OrgId: res.Orgs[0].Id,
- OrgName: res.Orgs[0].Id,
- OrgIsTrial: res.Orgs[0].IsTrial,
- IntegratedModelsMode: res.Orgs[0].IntegratedModelsMode,
- })
-
- if err != nil {
- return fmt.Errorf("error setting auth: %v", err)
- }
-
- return nil
-}
-
-const (
- TrialIntegratedModelsOption = "Integrated Models Mode\n • no OpenAI (or other provider) account required\n • Use OpenAI, Anthropic, and open source models\n • start with $5 trial"
- TrialBYOModelsOption = "BYO API Key Mode\n • requires OpenAI account (or another provider) and API key\n • start with free trial"
-)
-
-func startTrial() error {
- fmt.Printf("\n☁️ There are %s to use Plandex Cloud.\n\nYou can use %s to purchase LLM credits from Plandex directly, avoiding rate limits and the need to manage model provider accounts and API keys.\n\nOr you can use %s to use Plandex with your own account and API key from OpenAI or another model provider.\n\n",
- color.New(color.Bold).Sprint("two ways"),
- color.New(color.Bold, term.ColorHiYellow).Sprint("Integrated Models Mode"),
- color.New(color.Bold, term.ColorHiYellow).Sprint("BYO API Key Mode"),
+ openUnauthenticatedCloudURL(
+ "Opening Plandex Cloud trial flow in your browser.",
+ fmt.Sprintf("/start?cliTrialToken=%s", cliTrialToken),
)
- selected, err := term.SelectFromList("Which do you want to start with?", []string{TrialIntegratedModelsOption, TrialBYOModelsOption})
-
- if err != nil {
- return fmt.Errorf("error selecting integrated models option: %v", err)
- }
-
- integratedModelsMode := selected == TrialIntegratedModelsOption
-
- email, err := term.GetRequiredUserStringInput("Your email:")
-
- if err != nil {
- return fmt.Errorf("error prompting email: %v", err)
- }
-
- hasAccount, pin, err := verifyEmail(email, "")
-
- if err != nil {
- return fmt.Errorf("error verifying email: %v", err)
- }
-
- if hasAccount {
- term.OutputErrorAndExit("Can't convert a trial into an account that already exists")
- }
-
- name, err := term.GetUserStringInput("Your name:")
+ fmt.Println("\nCommand will continue automatically once you've started your trial...")
+ fmt.Println()
+ term.StartSpinner("")
- if err != nil {
- return fmt.Errorf("error prompting name: %v", err)
- }
+ startTime := time.Now()
+ expirationTime := startTime.Add(1 * time.Hour)
- orgName, err := term.GetRequiredUserStringInput("Org name:")
+ for time.Now().Before(expirationTime) {
+ cliTrialSession, apiErr := apiClient.GetCliTrialSession(cliTrialToken)
- if err != nil {
- return fmt.Errorf("error prompting org name: %v", err)
- }
+ if apiErr != nil {
+ term.StopSpinner()
+ term.OutputErrorAndExit("error getting cli trial session: %s", apiErr.Msg)
+ }
- autoAddDomainUsers, err := promptAutoAddUsersIfValid(email)
+ if cliTrialSession != nil {
+ // Trial session is valid, break the loop and sign in
+ term.StopSpinner()
+ fmt.Println("🚀 Trial started")
+ fmt.Println()
+ err := handleSignInResponse(cliTrialSession, "")
+ if err != nil {
+ term.OutputErrorAndExit("error signing in after trial started: %s", err)
+ }
+ return
+ }
- if err != nil {
- return fmt.Errorf("error prompting auto add domain users: %v", err)
+ time.Sleep(1500 * time.Millisecond)
}
- term.StartSpinner("🌟 Starting trial...")
- res, apiErr := apiClient.StartTrial(shared.StartTrialRequest{
- Account: shared.CreateAccountRequest{
- Email: email,
- Pin: pin,
- UserName: name,
- },
- Org: shared.CreateCloudOrgRequest{
- CreateOrgRequest: shared.CreateOrgRequest{
- Name: orgName,
- AutoAddDomainUsers: autoAddDomainUsers,
- },
- IntegratedModelsMode: integratedModelsMode,
- },
- })
term.StopSpinner()
-
- if apiErr != nil {
- return fmt.Errorf("error starting trial: %v", apiErr)
- }
-
- err = setAuth(&shared.ClientAuth{
- ClientAccount: shared.ClientAccount{
- Email: email,
- UserId: res.UserId,
- UserName: name,
- Token: res.Token,
- IsCloud: true,
- IsTrial: true,
- },
- OrgId: res.OrgId,
- OrgName: orgName,
- IntegratedModelsMode: integratedModelsMode,
- })
-
- if err != nil {
- return fmt.Errorf("error setting auth: %v", err)
- }
-
- return nil
+ term.OutputErrorAndExit("Timed out waiting for trial to start. Please try again. Email [email protected] if the problem persists.")
}
-
-// func startTrial() error {
-
-// term.StartSpinner("🌟 Starting trial...")
-
-// res, apiErr := apiClient.StartTrial()
-
-// term.StopSpinner()
-// if apiErr != nil {
-// return fmt.Errorf("error starting trial: %v", apiErr.Msg)
-// }
-
-// err := setAuth(&shared.ClientAuth{
-// ClientAccount: shared.ClientAccount{
-// Email: res.Email,
-// UserId: res.UserId,
-// UserName: res.UserName,
-// Token: res.Token,
-// IsTrial: true,
-// IsCloud: true,
-// },
-// OrgId: res.OrgId,
-// OrgName: res.OrgName,
-// })
-
-// if err != nil {
-// return fmt.Errorf("error setting auth: %v", err)
-// }
-
-// return nil
-// }
diff --git a/app/cli/cmd/billing.go b/app/cli/cmd/billing.go
new file mode 100644
index 00000000..01d1ae5c
--- /dev/null
+++ b/app/cli/cmd/billing.go
@@ -0,0 +1,29 @@
+package cmd
+
+import (
+ "plandex/auth"
+ "plandex/term"
+ "plandex/ui"
+
+ "github.com/spf13/cobra"
+)
+
+var billingCmd = &cobra.Command{
+ Use: "billing",
+ Short: "Open the billing page in the browser",
+ Run: billing,
+}
+
+func init() {
+ RootCmd.AddCommand(billingCmd)
+}
+
+func billing(cmd *cobra.Command, args []string) {
+ auth.MustResolveAuthWithOrg()
+
+ if !auth.Current.IsCloud {
+ term.OutputErrorAndExit("This command is only available for Plandex Cloud accounts.")
+ }
+
+ ui.OpenAuthenticatedURL("Opening billing page in your default browser...", "/settings/billing")
+}
diff --git a/app/cli/cmd/credits_log.go b/app/cli/cmd/credits_log.go
index 0e144673..2d9aaae8 100644
--- a/app/cli/cmd/credits_log.go
+++ b/app/cli/cmd/credits_log.go
@@ -101,6 +101,8 @@ func creditsLog(cmd *cobra.Command, args []string) {
case shared.CreditTypeSwitch:
desc += "Switched to Integrated Models mode"
}
+
+ desc += "\n"
}
amountStr := transaction.Amount.StringFixed(6)
diff --git a/app/cli/cmd/new.go b/app/cli/cmd/new.go
index 4d0d6f08..a17ab814 100644
--- a/app/cli/cmd/new.go
+++ b/app/cli/cmd/new.go
@@ -41,25 +41,23 @@ func new(cmd *cobra.Command, args []string) {
if apiErr != nil {
if apiErr.Type == shared.ApiErrorTypeTrialPlansExceeded {
- fmt.Fprintf(os.Stderr, "🚨 You've reached the Plandex Cloud anonymous trial limit of %d plans\n", apiErr.TrialPlansExceededError.MaxPlans)
+ fmt.Fprintf(os.Stderr, "🚨 You've reached the Plandex Cloud trial limit of %d plans\n", apiErr.TrialPlansExceededError.MaxPlans)
- res, err := term.ConfirmYesNo("Upgrade to an unlimited free account?")
+ res, err := term.ConfirmYesNo("Upgrade now?")
if err != nil {
term.OutputErrorAndExit("Error prompting upgrade trial: %v", err)
}
if res {
- err := auth.ConvertTrial()
- if err != nil {
- term.OutputErrorAndExit("Error converting trial: %v", err)
- }
+ auth.ConvertTrial()
+ } else {
+ return
}
- return
+ } else {
+ term.OutputErrorAndExit("Error creating plan: %v", apiErr.Msg)
}
-
- term.OutputErrorAndExit("Error creating plan: %v", apiErr.Msg)
}
err := lib.WriteCurrentPlan(res.Id)
diff --git a/app/cli/go.mod b/app/cli/go.mod
index e4cbeb43..e2369781 100644
--- a/app/cli/go.mod
+++ b/app/cli/go.mod
@@ -38,7 +38,6 @@ require (
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect
github.com/muesli/cancelreader v0.2.2 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
- github.com/stripe/stripe-go/v79 v79.10.0 // indirect
github.com/yuin/goldmark v1.6.0 // indirect
github.com/yuin/goldmark-emoji v1.0.2 // indirect
golang.org/x/net v0.18.0 // indirect
@@ -59,6 +58,7 @@ require (
github.com/inconshreveable/go-update v0.0.0-20160112193335-8152e7eb6ccf
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/mattn/go-runewidth v0.0.15 // indirect
+ github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c
github.com/pkoukk/tiktoken-go v0.1.6 // indirect
github.com/plandex/plandex/shared v0.0.0-00010101000000-000000000000
github.com/sabhiram/go-gitignore v0.0.0-20210923224102-525f6e181f06
diff --git a/app/cli/go.sum b/app/cli/go.sum
index 54db3076..363fc02c 100644
--- a/app/cli/go.sum
+++ b/app/cli/go.sum
@@ -588,6 +588,8 @@ github.com/pascaldekloe/goe v0.1.0/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144T
github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic=
github.com/pelletier/go-toml v1.9.5/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c=
github.com/pelletier/go-toml/v2 v2.0.5/go.mod h1:OMHamSCAODeSsVrwwvcJOaoN0LIUIaFVNZzmWyNfXas=
+github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ=
+github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU=
github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
@@ -683,8 +685,6 @@ github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
-github.com/stripe/stripe-go/v79 v79.10.0 h1:yaZ92m4gqxVlj/qFu2ImligxeKUvK5wVhTkXcetdx/8=
-github.com/stripe/stripe-go/v79 v79.10.0/go.mod h1:cuH6X0zC8peY6f1AubHwgJ/fJSn2dh5pfiCr6CjyKVU=
github.com/subosito/gotenv v1.4.1/go.mod h1:ayKnFf/c6rvx/2iiLrJUk1e6plDbT3edrFNGqEflhK0=
github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U=
github.com/tv42/httpunix v0.0.0-20150427012821-b75d8614f926/go.mod h1:9ESjWnEqriFuLhtthL60Sar/7RFoluCcXsuvEwTV5KM=
@@ -824,7 +824,6 @@ golang.org/x/net v0.0.0-20210316092652-d523dce5a7f4/go.mod h1:RBQZq4jEuRlivfhVLd
golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM=
golang.org/x/net v0.0.0-20210410081132-afb366fc7cd1/go.mod h1:9tjilg8BloeKEkVJvy7fQ90B1CfIiPueXVOjqfkSzI8=
golang.org/x/net v0.0.0-20210503060351-7fd8e65b6420/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
-golang.org/x/net v0.0.0-20210520170846-37e1c6afe023/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20210916014120-12bc252f5db8/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20211216030914-fe4d6282115f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
diff --git a/app/cli/main.go b/app/cli/main.go
index 19dd5f5f..33b16ff8 100644
--- a/app/cli/main.go
+++ b/app/cli/main.go
@@ -11,6 +11,7 @@ import (
"plandex/lib"
"plandex/plan_exec"
"plandex/term"
+ "plandex/ui"
"github.com/plandex/plandex/shared"
)
@@ -18,6 +19,13 @@ import (
func init() {
// inter-package dependency injections to avoid circular imports
auth.SetApiClient(api.Client)
+
+ auth.SetOpenUnauthenticatedCloudURLFn(ui.OpenUnauthenticatedCloudURL)
+ auth.SetOpenAuthenticatedURLFn(ui.OpenAuthenticatedURL)
+
+ term.SetOpenAuthenticatedURLFn(ui.OpenAuthenticatedURL)
+ term.SetOpenUnauthenticatedCloudURLFn(ui.OpenUnauthenticatedCloudURL)
+
lib.SetBuildPlanInlineFn(func(maybeContexts []*shared.Context) (bool, error) {
var apiKeys map[string]string
if !auth.Current.IntegratedModelsMode {
diff --git a/app/cli/plan_exec/tell.go b/app/cli/plan_exec/tell.go
index b9a71e35..ff5e48bd 100644
--- a/app/cli/plan_exec/tell.go
+++ b/app/cli/plan_exec/tell.go
@@ -93,19 +93,16 @@ func TellPlan(
if apiErr != nil {
if apiErr.Type == shared.ApiErrorTypeTrialMessagesExceeded {
- fmt.Fprintf(os.Stderr, "\n🚨 You've reached the Plandex Cloud anonymous trial limit of %d messages per plan\n", apiErr.TrialMessagesExceededError.MaxReplies)
+ fmt.Fprintf(os.Stderr, "\n🚨 You've reached the Plandex Cloud trial limit of %d messages per plan\n", apiErr.TrialMessagesExceededError.MaxReplies)
- res, err := term.ConfirmYesNo("Upgrade to an unlimited free account?")
+ res, err := term.ConfirmYesNo("Upgrade now?")
if err != nil {
term.OutputErrorAndExit("Error prompting upgrade trial: %v", err)
}
if res {
- err := auth.ConvertTrial()
- if err != nil {
- term.OutputErrorAndExit("Error converting trial: %v", err)
- }
+ auth.ConvertTrial()
// retry action after converting trial
return fn()
}
diff --git a/app/cli/stream_tui/run.go b/app/cli/stream_tui/run.go
index f9bb9cd3..5922ae45 100644
--- a/app/cli/stream_tui/run.go
+++ b/app/cli/stream_tui/run.go
@@ -70,7 +70,8 @@ func StartStreamUI(prompt string, buildOnly bool) error {
if mod.apiErr != nil {
fmt.Println()
- term.OutputErrorAndExit("Server error: " + mod.apiErr.Msg)
+
+ term.HandleApiError(mod.apiErr)
}
if mod.stopped {
diff --git a/app/cli/term/errors.go b/app/cli/term/errors.go
index acf4daea..832c144b 100644
--- a/app/cli/term/errors.go
+++ b/app/cli/term/errors.go
@@ -9,6 +9,17 @@ import (
"github.com/plandex/plandex/shared"
)
+var openUnauthenticatedCloudURL func(msg, path string)
+var openAuthenticatedURL func(msg, path string)
+
+func SetOpenUnauthenticatedCloudURLFn(fn func(msg, path string)) {
+ openUnauthenticatedCloudURL = fn
+}
+
+func SetOpenAuthenticatedURLFn(fn func(msg, path string)) {
+ openAuthenticatedURL = fn
+}
+
func OutputNoOpenAIApiKeyMsgAndExit() {
fmt.Fprintln(os.Stderr, color.New(color.Bold, ColorHiRed).Sprintln("\n🚨 OPENAI_API_KEY environment variable is not set.")+color.New().Sprintln("\nSet it with:\n\nexport OPENAI_API_KEY=your-api-key\n\nThen try again.\n\n👉 If you don't have an OpenAI account, sign up here → https://platform.openai.com/signup\n\n🔑 Generate an api key here → https://platform.openai.com/api-keys"))
os.Exit(1)
@@ -88,3 +99,81 @@ func OutputNoCurrentPlanErrorAndExit() {
PrintCmds("", "new", "cd")
os.Exit(1)
}
+
+func HandleApiError(apiError *shared.ApiError) {
+ if apiError.Type == shared.ApiErrorTypeCloudSubscriptionPaused {
+ if apiError.BillingError.HasBillingPermission {
+ StopSpinner()
+ fmt.Println("Your org's Plandex Cloud subscription is paused.")
+ res, err := ConfirmYesNo("Go to billing settings?")
+ if err != nil {
+ OutputErrorAndExit("error getting confirmation")
+ }
+ if res {
+ openAuthenticatedURL("Opening billing settings in your browser.", "/settings/billing")
+ os.Exit(0)
+ } else {
+ os.Exit(0)
+ }
+ } else {
+ OutputErrorAndExit("Your org's subscription is paused. Please contact an org owner to continue.")
+ }
+ }
+
+ if apiError.Type == shared.ApiErrorTypeCloudSubscriptionOverdue {
+ if apiError.BillingError.HasBillingPermission {
+ StopSpinner()
+ OutputSimpleError("Your org's Plandex Cloud subscription is overdue.")
+ res, err := ConfirmYesNo("Go to billing settings?")
+ if err != nil {
+ OutputErrorAndExit("error getting confirmation")
+ }
+ if res {
+ openAuthenticatedURL("Opening billing settings in your browser.", "/settings/billing")
+ os.Exit(0)
+ } else {
+ os.Exit(0)
+ }
+ } else {
+ OutputErrorAndExit("Your org's subscription is overdue. Please contact an org owner to continue.")
+ }
+ }
+
+ if apiError.Type == shared.ApiErrorTypeCloudMonthlyMaxReached {
+ if apiError.BillingError.HasBillingPermission {
+ StopSpinner()
+ OutputSimpleError("Your org has reached its monthly limit for Plandex Cloud.")
+ res, err := ConfirmYesNo("Go to billing settings?")
+ if err != nil {
+ OutputErrorAndExit("error getting confirmation")
+ }
+ if res {
+ openAuthenticatedURL("Opening billing settings in your browser.", "/settings/billing")
+ os.Exit(0)
+ } else {
+ os.Exit(0)
+ }
+ } else {
+ OutputErrorAndExit("Your org has reached its monthly limit for Plandex Cloud.")
+ }
+ }
+
+ if apiError.Type == shared.ApiErrorTypeCloudInsufficientCredits {
+ if apiError.BillingError.HasBillingPermission {
+ StopSpinner()
+ OutputSimpleError("Insufficient credits.")
+ res, err := ConfirmYesNo("Go to billing settings?")
+ if err != nil {
+ OutputErrorAndExit("error getting confirmation")
+ }
+ if res {
+ openAuthenticatedURL("Opening billing settings in your browser.", "/settings/billing")
+ os.Exit(0)
+ } else {
+ os.Exit(0)
+ }
+ } else {
+ OutputErrorAndExit("Insufficient credits.")
+ }
+ }
+}
diff --git a/app/cli/term/prompt.go b/app/cli/term/prompt.go
index 43675ee6..5400209e 100644
--- a/app/cli/term/prompt.go
+++ b/app/cli/term/prompt.go
@@ -68,11 +68,16 @@ func ConfirmYesNo(fmtStr string, fmtArgs ...interface{}) (bool, error) {
color.New(ColorHiMagenta, color.Bold).Printf(fmtStr+" (y)es | (n)o", fmtArgs...)
color.New(ColorHiMagenta, color.Bold).Print("> ")
- char, _, err := GetUserKeyInput()
+ char, key, err := GetUserKeyInput()
if err != nil {
return false, fmt.Errorf("failed to get user input: %s", err)
}
+ if key == keyboard.KeyCtrlC {
+ fmt.Println()
+ os.Exit(0)
+ }
+
fmt.Println(string(char))
if char == 'y' || char == 'Y' {
return true, nil
@@ -89,11 +94,16 @@ func ConfirmYesNoCancel(fmtStr string, fmtArgs ...interface{}) (bool, bool, erro
color.New(ColorHiMagenta, color.Bold).Printf(fmtStr+" (y)es | (n)o | (c)ancel", fmtArgs...)
color.New(ColorHiMagenta, color.Bold).Print("> ")
- char, _, err := GetUserKeyInput()
+ char, key, err := GetUserKeyInput()
if err != nil {
return false, false, fmt.Errorf("failed to get user input: %s", err)
}
+ if key == keyboard.KeyCtrlC {
+ fmt.Println()
+ os.Exit(0)
+ }
+
fmt.Println(string(char))
if char == 'y' || char == 'Y' {
return true, false, nil
diff --git a/app/cli/types/api.go b/app/cli/types/api.go
index 070081a4..acd1ef8f 100644
--- a/app/cli/types/api.go
+++ b/app/cli/types/api.go
@@ -12,13 +12,16 @@ type OnStreamPlanParams struct {
type OnStreamPlan func(params OnStreamPlanParams)
type ApiClient interface {
- StartTrial(req shared.StartTrialRequest) (*shared.StartTrialResponse, *shared.ApiError)
- ConvertTrial(req shared.ConvertTrialRequest) (*shared.SessionResponse, *shared.ApiError)
+ CreateCliTrialSession() (string, *shared.ApiError)
+ GetCliTrialSession(token string) (*shared.SessionResponse, *shared.ApiError)
CreateEmailVerification(email, customHost, userId string) (*shared.CreateEmailVerificationResponse, *shared.ApiError)
+ CreateSignInCode() (string, *shared.ApiError)
+
CreateAccount(req shared.CreateAccountRequest, customHost string) (*shared.SessionResponse, *shared.ApiError)
SignIn(req shared.SignInRequest, customHost string) (*shared.SessionResponse, *shared.ApiError)
+
SignOut() *shared.ApiError
GetOrgSession() (*shared.Org, *shared.ApiError)
diff --git a/app/cli/ui/ui.go b/app/cli/ui/ui.go
new file mode 100644
index 00000000..6cc538bc
--- /dev/null
+++ b/app/cli/ui/ui.go
@@ -0,0 +1,67 @@
+package ui
+
+import (
+ "encoding/base64"
+ "encoding/json"
+ "fmt"
+ "log"
+ "plandex/api"
+ "plandex/term"
+
+ "github.com/fatih/color"
+ "github.com/pkg/browser"
+
+ "github.com/plandex/plandex/shared"
+)
+
+func OpenAuthenticatedURL(msg, path string) {
+ signInCode, apiErr := api.Client.CreateSignInCode()
+ if apiErr != nil {
+ log.Fatalf("Error creating sign in code: %v", apiErr)
+ }
+
+ host := api.GetApiHost()
+
+ token := shared.UiSignInToken{
+ Pin: signInCode,
+ RedirectTo: path,
+ }
+
+ jsonToken, err := json.Marshal(token)
+ if err != nil {
+ log.Fatalf("Error marshalling token: %v", err)
+ }
+
+ encodedToken := base64.URLEncoding.EncodeToString(jsonToken)
+
+ url := fmt.Sprintf("%s/auth/%s", host, encodedToken)
+
+ fmt.Printf(
+ "%s\n\nIf it doesn't open automatically, use this URL:\n%s\n",
+ color.New(term.ColorHiGreen).Sprintf(msg),
+ url,
+ )
+
+ err = browser.OpenURL(url)
+ if err != nil {
+ fmt.Printf("Failed to open URL automatically: %v\n", err)
+ fmt.Println("Please open the URL manually in your browser.")
+ }
+}
+
+func OpenUnauthenticatedCloudURL(msg, path string) {
+ host := api.CloudApiHost
+ url := fmt.Sprintf("%s%s", host, path)
+
+ fmt.Printf(
+ "%s\n\nIf it doesn't open automatically, use this URL:\n%s\n",
+ color.New(term.ColorHiGreen).Sprintf(msg),
+ url,
+ )
+
+ err := browser.OpenURL(url)
+ if err != nil {
+ fmt.Printf("Failed to open URL automatically: %v\n", err)
+ fmt.Println("Please open the URL manually in your browser.")
+ }
+}
diff --git a/app/server/db/account_helpers.go b/app/server/db/account_helpers.go
index 76bfead8..85110252 100644
--- a/app/server/db/account_helpers.go
+++ b/app/server/db/account_helpers.go
@@ -24,7 +24,7 @@ func CreateAccount(name, email, emailVerificationId string, tx *sqlx.Tx) (*Creat
domain := user.Domain
// create auth token
- token, authTokenId, err := CreateAuthToken(userId, false, tx)
+ token, authTokenId, err := CreateAuthToken(userId, tx)
if err != nil {
return nil, fmt.Errorf("error creating auth token: %v", err)
diff --git a/app/server/db/auth_helpers.go b/app/server/db/auth_helpers.go
index 987a575c..f37b2172 100644
--- a/app/server/db/auth_helpers.go
+++ b/app/server/db/auth_helpers.go
@@ -15,13 +15,13 @@ import (
const tokenExpirationDays = 90 // (trial tokens don't expire)
-func CreateAuthToken(userId string, isTrial bool, tx *sqlx.Tx) (token, id string, err error) {
+func CreateAuthToken(userId string, tx *sqlx.Tx) (token, id string, err error) {
uid := uuid.New()
bytes := uid[:]
hashBytes := sha256.Sum256(bytes)
hash := hex.EncodeToString(hashBytes[:])
- err = tx.QueryRow("INSERT INTO auth_tokens (user_id, token_hash, is_trial) VALUES ($1, $2, $3) RETURNING id", userId, hash, isTrial).Scan(&id)
+ err = tx.QueryRow("INSERT INTO auth_tokens (user_id, token_hash) VALUES ($1, $2) RETURNING id", userId, hash).Scan(&id)
if err != nil {
return "", "", fmt.Errorf("error creating auth token: %v", err)
@@ -43,8 +43,7 @@ func ValidateAuthToken(token string) (*AuthToken, error) {
tokenHash := hex.EncodeToString(hashBytes[:])
var authToken AuthToken
- // trial tokens don't expire
- err = Conn.Get(&authToken, "SELECT * FROM auth_tokens WHERE token_hash = $1 AND (created_at > $2 OR is_trial = TRUE) AND deleted_at IS NULL", tokenHash, time.Now().AddDate(0, 0, -tokenExpirationDays))
+ err = Conn.Get(&authToken, "SELECT * FROM auth_tokens WHERE token_hash = $1 AND created_at > $2 AND deleted_at IS NULL", tokenHash, time.Now().AddDate(0, 0, -tokenExpirationDays))
if err != nil {
if err == sql.ErrNoRows {
diff --git a/app/server/db/data_models.go b/app/server/db/data_models.go
index 92264de8..0c1486a1 100644
--- a/app/server/db/data_models.go
+++ b/app/server/db/data_models.go
@@ -16,7 +16,6 @@ type AuthToken struct {
Id string `db:"id"`
UserId string `db:"user_id"`
TokenHash string `db:"token_hash"`
- IsTrial bool `db:"is_trial"`
CreatedAt time.Time `db:"created_at"`
DeletedAt *time.Time `db:"deleted_at"`
}
@@ -35,8 +34,10 @@ type Org struct {
func (org *Org) ToApi() *shared.Org {
return &shared.Org{
- Id: org.Id,
- Name: org.Name,
+ Id: org.Id,
+ Name: org.Name,
+ AutoAddDomainUsers: org.AutoAddDomainUsers,
+ IsTrial: org.IsTrial,
}
}
@@ -46,7 +47,6 @@ type User struct {
Email string `db:"email"`
Domain string `db:"domain"`
NumNonDraftPlans int `db:"num_non_draft_plans"`
- IsTrial bool `db:"is_trial"`
CreatedAt time.Time `db:"created_at"`
UpdatedAt time.Time `db:"updated_at"`
}
@@ -57,7 +57,7 @@ func (user *User) ToApi() *shared.User {
Name: user.Name,
Email: user.Email,
NumNonDraftPlans: user.NumNonDraftPlans,
- IsTrial: user.IsTrial,
+ IsTrial: false, // legacy field
}
}
diff --git a/app/server/db/user_helpers.go b/app/server/db/user_helpers.go
index 79a85b8d..c41b0765 100644
--- a/app/server/db/user_helpers.go
+++ b/app/server/db/user_helpers.go
@@ -116,7 +116,7 @@ func CreateUser(name, email string, tx *sqlx.Tx) (*User, error) {
Domain: domain,
}
- err := tx.QueryRow("INSERT INTO users (name, email, domain, is_trial) VALUES ($1, $2, $3, $4) RETURNING id", user.Name, user.Email, user.Domain, user.IsTrial).Scan(&user.Id)
+ err := tx.QueryRow("INSERT INTO users (name, email, domain) VALUES ($1, $2, $3) RETURNING id", user.Name, user.Email, user.Domain).Scan(&user.Id)
if err != nil {
if IsNonUniqueErr(err) {
diff --git a/app/server/handlers/accounts.go b/app/server/handlers/accounts.go
index 3df4008c..5d81557f 100644
--- a/app/server/handlers/accounts.go
+++ b/app/server/handlers/accounts.go
@@ -5,8 +5,10 @@ import (
"io"
"log"
"net/http"
+ "os"
"plandex-server/db"
"plandex-server/hooks"
+ "plandex-server/types"
"strings"
"github.com/plandex/plandex/shared"
@@ -15,6 +17,12 @@ import (
func CreateAccountHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Received request for CreateAccountHandler")
+ if os.Getenv("IS_CLOUD") != "" {
+ log.Println("Creating accounts is not supported in cloud mode")
+ http.Error(w, "Creating accounts is not supported in cloud mode", http.StatusNotImplemented)
+ return
+ }
+
// read the request body
body, err := io.ReadAll(r.Body)
if err != nil {
@@ -75,8 +83,10 @@ func CreateAccountHandler(w http.ResponseWriter, r *http.Request) {
orgId := res.OrgId
_, apiErr = hooks.ExecHook(hooks.CreateAccount, hooks.HookParams{
- User: user,
- OrgId: orgId,
+ Auth: &types.ServerAuth{
+ User: user,
+ OrgId: orgId,
+ },
})
if apiErr != nil {
writeApiError(w, *apiErr)
diff --git a/app/server/handlers/auth_helpers.go b/app/server/handlers/auth_helpers.go
index 103815eb..32f52474 100644
--- a/app/server/handlers/auth_helpers.go
+++ b/app/server/handlers/auth_helpers.go
@@ -8,6 +8,7 @@ import (
"net/http"
"os"
"plandex-server/db"
+ "plandex-server/hooks"
"plandex-server/types"
"strings"
@@ -22,139 +23,6 @@ func AuthenticateOptional(w http.ResponseWriter, r *http.Request, requireOrg boo
return execAuthenticate(w, r, requireOrg, false)
}
-func execAuthenticate(w http.ResponseWriter, r *http.Request, requireOrg bool, raiseErr bool) *types.ServerAuth {
- log.Println("authenticating request")
-
- parsed, err := GetAuthHeader(r)
-
- if err != nil {
- log.Printf("error getting auth header: %v\n", err)
- if raiseErr {
- http.Error(w, "error getting auth header", http.StatusInternalServerError)
- }
- return nil
- }
-
- if parsed == nil {
- log.Println("no auth header")
- if raiseErr {
- http.Error(w, "no auth header", http.StatusUnauthorized)
- }
- return nil
- }
-
- // validate the token
- authToken, err := db.ValidateAuthToken(parsed.Token)
-
- if err != nil {
- log.Printf("error validating auth token: %v\n", err)
-
- writeApiError(w, shared.ApiError{
- Type: shared.ApiErrorTypeInvalidToken,
- Status: http.StatusUnauthorized,
- Msg: "Invalid auth token",
- })
- return nil
- }
-
- user, err := db.GetUser(authToken.UserId)
-
- if err != nil {
- log.Printf("error getting user: %v\n", err)
- if raiseErr {
- http.Error(w, "error getting user", http.StatusInternalServerError)
- }
- return nil
- }
-
- if !requireOrg {
- return &types.ServerAuth{
- AuthToken: authToken,
- User: user,
- }
- }
-
- if parsed.OrgId == "" {
- log.Println("no org id")
- if raiseErr {
- http.Error(w, "no org id", http.StatusUnauthorized)
- }
- return nil
- }
-
- // validate the org membership
- isMember, err := db.ValidateOrgMembership(authToken.UserId, parsed.OrgId)
-
- if err != nil {
- log.Printf("error validating org membership: %v\n", err)
- if raiseErr {
- http.Error(w, "error validating org membership", http.StatusInternalServerError)
- }
- return nil
- }
-
- if !isMember {
- // check if there's an invite for this user and accept it if so (adds the user to the org)
- invite, err := db.GetActiveInviteByEmail(parsed.OrgId, user.Email)
-
- if err != nil {
- log.Printf("error getting invite for org user: %v\n", err)
- if raiseErr {
- http.Error(w, "error getting invite for org user", http.StatusInternalServerError)
- }
- return nil
- }
-
- if invite != nil {
- log.Println("accepting invite")
-
- err := db.AcceptInvite(invite, authToken.UserId)
-
- if err != nil {
- log.Printf("error accepting invite: %v\n", err)
- if raiseErr {
- http.Error(w, "error accepting invite", http.StatusInternalServerError)
- }
- return nil
- }
-
- } else {
- log.Println("user is not a member of the org")
- if raiseErr {
- http.Error(w, "not a member of org", http.StatusUnauthorized)
- }
- return nil
- }
- }
-
- // get user permissions
- permissions, err := db.GetUserPermissions(authToken.UserId, parsed.OrgId)
-
- if err != nil {
- log.Printf("error getting user permissions: %v\n", err)
- if raiseErr {
- http.Error(w, "error getting user permissions", http.StatusInternalServerError)
- }
- return nil
- }
-
- // build the permissions map
- permissionsMap := make(shared.Permissions)
- for _, permission := range permissions {
- permissionsMap[permission] = true
- }
-
- log.Printf("UserId: %s, Email: %s, OrgId: %s\n", authToken.UserId, user.Email, parsed.OrgId)
-
- return &types.ServerAuth{
- AuthToken: authToken,
- User: user,
- OrgId: parsed.OrgId,
- Permissions: permissionsMap,
- }
-
-}
-
func GetAuthHeader(r *http.Request) (*shared.AuthHeader, error) {
authHeader := r.Header.Get("Authorization")
@@ -188,7 +56,7 @@ func GetAuthHeader(r *http.Request) (*shared.AuthHeader, error) {
encoded := strings.TrimPrefix(authHeader, "Bearer ")
// decode the base64-encoded credentials
- bytes, err := base64.StdEncoding.DecodeString(encoded)
+ bytes, err := base64.URLEncoding.DecodeString(encoded)
if err != nil {
return nil, fmt.Errorf("error decoding auth token: %v", err)
@@ -258,7 +126,7 @@ func ClearAccountFromCookies(w http.ResponseWriter, r *http.Request, userId stri
}
// Encode to base64
- encodedAccounts := base64.StdEncoding.EncodeToString(updatedAccountsBytes)
+ encodedAccounts := base64.URLEncoding.EncodeToString(updatedAccountsBytes)
// Set the updated accounts cookie
http.SetCookie(w, &http.Cookie{
@@ -310,7 +178,7 @@ func SetAuthCookieIfBrowser(w http.ResponseWriter, r *http.Request, user *db.Use
}
// base64 encode
- token = base64.StdEncoding.EncodeToString(bytes)
+ token = base64.URLEncoding.EncodeToString(bytes)
http.SetCookie(w, &http.Cookie{
Name: "authToken",
@@ -355,7 +223,7 @@ func SetAuthCookieIfBrowser(w http.ResponseWriter, r *http.Request, user *db.Use
}
// base64 encode
- accounts := base64.StdEncoding.EncodeToString(bytes)
+ accounts := base64.URLEncoding.EncodeToString(bytes)
http.SetCookie(w, &http.Cookie{
Name: "accounts",
@@ -378,7 +246,7 @@ func GetAccountsFromCookie(r *http.Request) ([]*shared.ClientAccount, error) {
return nil, fmt.Errorf("error getting accounts cookie: %v", err)
}
- bytes, err := base64.StdEncoding.DecodeString(accountsCookie.Value)
+ bytes, err := base64.URLEncoding.DecodeString(accountsCookie.Value)
if err != nil {
return nil, fmt.Errorf("error decoding accounts cookie: %v", err)
}
@@ -392,6 +260,304 @@ func GetAccountsFromCookie(r *http.Request) ([]*shared.ClientAccount, error) {
return accounts, nil
}
+func ValidateAndSignIn(w http.ResponseWriter, r *http.Request, req shared.SignInRequest) (*shared.SessionResponse, error) {
+ var user *db.User
+ var emailVerificationId string
+ var signInCodeId string
+ var signInCodeOrgId string
+ var err error
+
+ if req.IsSignInCode {
+ res, err := db.ValidateSignInCode(req.Pin)
+
+ if err != nil {
+ log.Printf("Error validating sign in code: %v\n", err)
+ return nil, fmt.Errorf("error validating sign in code: %v", err)
+ }
+
+ user, err = db.GetUser(res.UserId)
+
+ if err != nil {
+ log.Printf("Error getting user: %v\n", err)
+ return nil, fmt.Errorf("error getting user: %v", err)
+ }
+
+ if user == nil {
+ log.Printf("User not found for id: %v\n", res.UserId)
+ return nil, fmt.Errorf("user not found")
+ }
+
+ signInCodeId = res.Id
+ signInCodeOrgId = res.OrgId
+ } else {
+ req.Email = strings.ToLower(req.Email)
+ user, err = db.GetUserByEmail(req.Email)
+
+ if err != nil {
+ log.Printf("Error getting user: %v\n", err)
+ return nil, fmt.Errorf("error getting user: %v", err)
+ }
+
+ if user == nil {
+ log.Printf("User not found for email: %v\n", req.Email)
+ return nil, fmt.Errorf("not found")
+ }
+
+ emailVerificationId, err = db.ValidateEmailVerification(req.Email, req.Pin)
+
+ if err != nil {
+ log.Printf("Error validating email verification: %v\n", err)
+ return nil, fmt.Errorf("error validating email verification: %v", err)
+ }
+ }
+
+ // start a transaction
+ tx, err := db.Conn.Beginx()
+ if err != nil {
+ log.Printf("Error starting transaction: %v\n", err)
+ return nil, fmt.Errorf("error starting transaction: %v", err)
+ }
+
+ // Ensure that rollback is attempted in case of failure
+ defer func() {
+ if err != nil {
+ if rbErr := tx.Rollback(); rbErr != nil {
+ log.Printf("transaction rollback error: %v\n", rbErr)
+ } else {
+ log.Println("transaction rolled back")
+ }
+ }
+ }()
+
+ // create auth token
+ token, authTokenId, err := db.CreateAuthToken(user.Id, tx)
+
+ if err != nil {
+ log.Printf("Error creating auth token: %v\n", err)
+ return nil, fmt.Errorf("error creating auth token: %v", err)
+ }
+
+ if req.IsSignInCode {
+ // update sign in code with auth token id
+ _, err = tx.Exec("UPDATE sign_in_codes SET auth_token_id = $1 WHERE id = $2", authTokenId, signInCodeId)
+
+ if err != nil {
+ log.Printf("Error updating sign in code: %v\n", err)
+ return nil, fmt.Errorf("error updating sign in code: %v", err)
+ }
+ } else {
+ // update email verification with user and auth token ids
+ _, err = tx.Exec("UPDATE email verifications SET user_id = $1, auth_token_id = $2 WHERE id = $3", user.Id, authTokenId, emailVerificationId)
+
+ if err != nil {
+ log.Printf("Error updating email verification: %v\n", err)
+ return nil, fmt.Errorf("error updating email verification: %v", err)
+ }
+ }
+
+ // commit transaction
+ err = tx.Commit()
+ if err != nil {
+ log.Printf("Error committing transaction: %v\n", err)
+ return nil, fmt.Errorf("error committing transaction: %v", err)
+ }
+
+ // get orgs
+ orgs, err := db.GetAccessibleOrgsForUser(user)
+
+ if err != nil {
+ log.Printf("Error getting orgs for user: %v\n", err)
+ return nil, fmt.Errorf("error getting orgs for user: %v", err)
+ }
+
+ if req.IsSignInCode {
+ filteredOrgs := []*db.Org{}
+ for _, org := range orgs {
+ if org.Id == signInCodeOrgId {
+ filteredOrgs = append(filteredOrgs, org)
+ }
+ }
+ orgs = filteredOrgs
+ }
+
+ // with a single org, set the orgId in the cookie
+ // otherwise, the user will be prompted to select an org
+ var orgId string
+ if len(orgs) == 1 {
+ orgId = orgs[0].Id
+ }
+
+ err = SetAuthCookieIfBrowser(w, r, user, token, orgId)
+ if err != nil {
+ log.Printf("Error setting auth cookie: %v\n", err)
+ return nil, fmt.Errorf("error setting auth cookie: %v", err)
+ }
+
+ apiOrgs, apiErr := toApiOrgs(orgs)
+
+ if apiErr != nil {
+ log.Printf("Error converting orgs to api orgs: %v\n", apiErr)
+ return nil, fmt.Errorf("error converting orgs to api orgs: %v", apiErr)
+ }
+
+ resp := shared.SessionResponse{
+ UserId: user.Id,
+ Token: token,
+ Email: user.Email,
+ UserName: user.Name,
+ Orgs: apiOrgs,
+ }
+
+ return &resp, nil
+}
+
+func execAuthenticate(w http.ResponseWriter, r *http.Request, requireOrg bool, raiseErr bool) *types.ServerAuth {
+ log.Println("authenticating request")
+
+ parsed, err := GetAuthHeader(r)
+
+ if err != nil {
+ log.Printf("error getting auth header: %v\n", err)
+ if raiseErr {
+ http.Error(w, "error getting auth header", http.StatusInternalServerError)
+ }
+ return nil
+ }
+
+ if parsed == nil {
+ log.Println("no auth header")
+ if raiseErr {
+ http.Error(w, "no auth header", http.StatusUnauthorized)
+ }
+ return nil
+ }
+
+ // validate the token
+ authToken, err := db.ValidateAuthToken(parsed.Token)
+
+ if err != nil {
+ log.Printf("error validating auth token: %v\n", err)
+
+ writeApiError(w, shared.ApiError{
+ Type: shared.ApiErrorTypeInvalidToken,
+ Status: http.StatusUnauthorized,
+ Msg: "Invalid auth token",
+ })
+ return nil
+ }
+
+ user, err := db.GetUser(authToken.UserId)
+
+ if err != nil {
+ log.Printf("error getting user: %v\n", err)
+ if raiseErr {
+ http.Error(w, "error getting user", http.StatusInternalServerError)
+ }
+ return nil
+ }
+
+ if !requireOrg {
+ return &types.ServerAuth{
+ AuthToken: authToken,
+ User: user,
+ }
+ }
+
+ if parsed.OrgId == "" {
+ log.Println("no org id")
+ if raiseErr {
+ http.Error(w, "no org id", http.StatusUnauthorized)
+ }
+ return nil
+ }
+
+ // validate the org membership
+ isMember, err := db.ValidateOrgMembership(authToken.UserId, parsed.OrgId)
+
+ if err != nil {
+ log.Printf("error validating org membership: %v\n", err)
+ if raiseErr {
+ http.Error(w, "error validating org membership", http.StatusInternalServerError)
+ }
+ return nil
+ }
+
+ if !isMember {
+ // check if there's an invite for this user and accept it if so (adds the user to the org)
+ invite, err := db.GetActiveInviteByEmail(parsed.OrgId, user.Email)
+
+ if err != nil {
+ log.Printf("error getting invite for org user: %v\n", err)
+ if raiseErr {
+ http.Error(w, "error getting invite for org user", http.StatusInternalServerError)
+ }
+ return nil
+ }
+
+ if invite != nil {
+ log.Println("accepting invite")
+
+ err := db.AcceptInvite(invite, authToken.UserId)
+
+ if err != nil {
+ log.Printf("error accepting invite: %v\n", err)
+ if raiseErr {
+ http.Error(w, "error accepting invite", http.StatusInternalServerError)
+ }
+ return nil
+ }
+
+ } else {
+ log.Println("user is not a member of the org")
+ if raiseErr {
+ http.Error(w, "not a member of org", http.StatusUnauthorized)
+ }
+ return nil
+ }
+ }
+
+ // get user permissions
+ permissions, err := db.GetUserPermissions(authToken.UserId, parsed.OrgId)
+
+ if err != nil {
+ log.Printf("error getting user permissions: %v\n", err)
+ if raiseErr {
+ http.Error(w, "error getting user permissions", http.StatusInternalServerError)
+ }
+ return nil
+ }
+
+ // build the permissions map
+ permissionsMap := make(shared.Permissions)
+ for _, permission := range permissions {
+ permissionsMap[permission] = true
+ }
+
+ auth := &types.ServerAuth{
+ AuthToken: authToken,
+ User: user,
+ OrgId: parsed.OrgId,
+ Permissions: permissionsMap,
+ }
+
+ _, apiErr := hooks.ExecHook(hooks.Authenticate, hooks.HookParams{
+ Auth: auth,
+ AuthenticateHookRequestParams: &hooks.AuthenticateHookRequestParams{
+ Path: r.URL.Path,
+ },
+ })
+
+ if apiErr != nil {
+ writeApiError(w, *apiErr)
+ return nil
+ }
+
+ log.Printf("UserId: %s, Email: %s, OrgId: %s\n", authToken.UserId, user.Email, parsed.OrgId)
+
+ return auth
+
+}
+
func authorizeProject(w http.ResponseWriter, projectId string, auth *types.ServerAuth) bool {
return authorizeProjectOptional(w, projectId, auth, true)
}
diff --git a/app/server/handlers/client_helper.go b/app/server/handlers/client_helper.go
index 02f3d586..8c5714bf 100644
--- a/app/server/handlers/client_helper.go
+++ b/app/server/handlers/client_helper.go
@@ -31,9 +31,8 @@ func initClients(params initClientsParams) map[string]*openai.Client {
var endpoint string
hookResult, apiErr := hooks.ExecHook(hooks.GetIntegratedModels, hooks.HookParams{
- User: params.auth.User,
- OrgId: params.auth.OrgId,
- Plan: params.plan,
+ Auth: params.auth,
+ Plan: params.plan,
})
if apiErr != nil {
diff --git a/app/server/handlers/invites.go b/app/server/handlers/invites.go
index 487f2f03..bbce7ffe 100644
--- a/app/server/handlers/invites.go
+++ b/app/server/handlers/invites.go
@@ -19,11 +19,19 @@ func InviteUserHandler(w http.ResponseWriter, r *http.Request) {
return
}
- if auth.User.IsTrial {
+ org, err := db.GetOrg(auth.OrgId)
+
+ if err != nil {
+ log.Printf("Error getting org: %v\n", err)
+ http.Error(w, "Error getting org: "+err.Error(), http.StatusInternalServerError)
+ return
+ }
+
+ if org.IsTrial {
writeApiError(w, shared.ApiError{
Type: shared.ApiErrorTypeTrialActionNotAllowed,
Status: http.StatusForbidden,
- Msg: "Anonymous trial user can't invite other users",
+ Msg: "Trial user can't invite other users",
})
return
@@ -32,7 +40,7 @@ func InviteUserHandler(w http.ResponseWriter, r *http.Request) {
currentUserId := auth.User.Id
var req shared.InviteRequest
- err := json.NewDecoder(r.Body).Decode(&req)
+ err = json.NewDecoder(r.Body).Decode(&req)
if err != nil {
log.Printf("Error unmarshalling request: %v\n", err)
http.Error(w, "Error unmarshalling request: "+err.Error(), http.StatusInternalServerError)
@@ -57,13 +65,6 @@ func InviteUserHandler(w http.ResponseWriter, r *http.Request) {
return
}
domain := &split[1]
- org, err := db.GetOrg(auth.OrgId)
-
- if err != nil {
- log.Printf("Error getting org: %v\n", err)
- http.Error(w, "Error getting org: "+err.Error(), http.StatusInternalServerError)
- return
- }
if org.AutoAddDomainUsers && org.Domain == domain {
log.Printf("User already has access to org via domain: %v\n", domain)
@@ -169,11 +170,18 @@ func ListPendingInvitesHandler(w http.ResponseWriter, r *http.Request) {
return
}
- if auth.User.IsTrial {
+ org, err := db.GetOrg(auth.OrgId)
+ if err != nil {
+ log.Printf("Error getting org: %v\n", err)
+ http.Error(w, "Error getting org: "+err.Error(), http.StatusInternalServerError)
+ return
+ }
+
+ if org.IsTrial {
writeApiError(w, shared.ApiError{
Type: shared.ApiErrorTypeTrialActionNotAllowed,
Status: http.StatusForbidden,
- Msg: "Anonymous trial user can't list invites",
+ Msg: "Trial user can't list invites",
})
return
}
@@ -210,11 +218,18 @@ func ListAcceptedInvitesHandler(w http.ResponseWriter, r *http.Request) {
return
}
- if auth.User.IsTrial {
+ org, err := db.GetOrg(auth.OrgId)
+ if err != nil {
+ log.Printf("Error getting org: %v\n", err)
+ http.Error(w, "Error getting org: "+err.Error(), http.StatusInternalServerError)
+ return
+ }
+
+ if org.IsTrial {
writeApiError(w, shared.ApiError{
Type: shared.ApiErrorTypeTrialActionNotAllowed,
Status: http.StatusForbidden,
- Msg: "Anonymous trial user can't list invites",
+ Msg: "Trial user can't list invites",
})
return
}
@@ -251,11 +266,18 @@ func ListAllInvitesHandler(w http.ResponseWriter, r *http.Request) {
return
}
- if auth.User.IsTrial {
+ org, err := db.GetOrg(auth.OrgId)
+ if err != nil {
+ log.Printf("Error getting org: %v\n", err)
+ http.Error(w, "Error getting org: "+err.Error(), http.StatusInternalServerError)
+ return
+ }
+
+ if org.IsTrial {
writeApiError(w, shared.ApiError{
Type: shared.ApiErrorTypeTrialActionNotAllowed,
Status: http.StatusForbidden,
- Msg: "Anonymous trial user can't list invites",
+ Msg: "Trial user can't list invites",
})
return
}
@@ -292,11 +314,18 @@ func DeleteInviteHandler(w http.ResponseWriter, r *http.Request) {
return
}
- if auth.User.IsTrial {
+ org, err := db.GetOrg(auth.OrgId)
+ if err != nil {
+ log.Printf("Error getting org: %v\n", err)
+ http.Error(w, "Error getting org: "+err.Error(), http.StatusInternalServerError)
+ return
+ }
+
+ if org.IsTrial {
writeApiError(w, shared.ApiError{
Type: shared.ApiErrorTypeTrialActionNotAllowed,
Status: http.StatusForbidden,
- Msg: "Anonymous trial user can't delete invites",
+ Msg: "Trial user can't delete invites",
})
return
}
diff --git a/app/server/handlers/orgs.go b/app/server/handlers/orgs.go
index cfd8c65c..43e3ceb8 100644
--- a/app/server/handlers/orgs.go
+++ b/app/server/handlers/orgs.go
@@ -5,6 +5,7 @@ import (
"io"
"log"
"net/http"
+ "os"
"plandex-server/db"
"plandex-server/hooks"
@@ -51,20 +52,20 @@ func ListOrgsHandler(w http.ResponseWriter, r *http.Request) {
func CreateOrgHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Received request for CreateOrgHandler")
- auth := Authenticate(w, r, false)
- if auth == nil {
- return
- }
-
- if auth.User.IsTrial {
+ if os.Getenv("IS_CLOUD") != "" {
writeApiError(w, shared.ApiError{
- Type: shared.ApiErrorTypeTrialActionNotAllowed,
+ Type: shared.ApiErrorTypeOther,
Status: http.StatusForbidden,
- Msg: "Anonymous trial user can't create org",
+ Msg: "Plandex Cloud orgs can only be created by starting a trial",
})
return
}
+ auth := Authenticate(w, r, false)
+ if auth == nil {
+ return
+ }
+
// read the request body
body, err := io.ReadAll(r.Body)
if err != nil {
@@ -133,7 +134,7 @@ func CreateOrgHandler(w http.ResponseWriter, r *http.Request) {
}
_, apiErr = hooks.ExecHook(hooks.CreateOrg, hooks.HookParams{
- User: auth.User,
+ Auth: auth,
Tx: tx,
CreateOrgHookRequestParams: &hooks.CreateOrgHookRequestParams{
@@ -222,11 +223,18 @@ func ListOrgRolesHandler(w http.ResponseWriter, r *http.Request) {
return
}
- if auth.User.IsTrial {
+ org, err := db.GetOrg(auth.OrgId)
+ if err != nil {
+ log.Printf("Error getting org: %v\n", err)
+ http.Error(w, "Error getting org: "+err.Error(), http.StatusInternalServerError)
+ return
+ }
+
+ if org.IsTrial {
writeApiError(w, shared.ApiError{
Type: shared.ApiErrorTypeTrialActionNotAllowed,
Status: http.StatusForbidden,
- Msg: "Anonymous trial user can't list org roles",
+ Msg: "Trial user can't list org roles",
})
return
}
diff --git a/app/server/handlers/plans_crud.go b/app/server/handlers/plans_crud.go
index ff2cddba..f69407f8 100644
--- a/app/server/handlers/plans_crud.go
+++ b/app/server/handlers/plans_crud.go
@@ -39,7 +39,7 @@ func CreatePlanHandler(w http.ResponseWriter, r *http.Request) {
return
}
- _, apiErr := hooks.ExecHook(hooks.WillCreatePlan, hooks.HookParams{User: auth.User})
+ _, apiErr := hooks.ExecHook(hooks.WillCreatePlan, hooks.HookParams{Auth: auth})
if apiErr != nil {
writeApiError(w, *apiErr)
return
diff --git a/app/server/handlers/plans_exec.go b/app/server/handlers/plans_exec.go
index 57443fcc..74284302 100644
--- a/app/server/handlers/plans_exec.go
+++ b/app/server/handlers/plans_exec.go
@@ -57,7 +57,7 @@ func TellPlanHandler(w http.ResponseWriter, r *http.Request) {
}
_, apiErr := hooks.ExecHook(hooks.WillTellPlan, hooks.HookParams{
- User: auth.User,
+ Auth: auth,
Plan: plan,
})
if apiErr != nil {
diff --git a/app/server/handlers/sessions.go b/app/server/handlers/sessions.go
index 699b86ec..0429de1e 100644
--- a/app/server/handlers/sessions.go
+++ b/app/server/handlers/sessions.go
@@ -217,152 +217,14 @@ func SignInHandler(w http.ResponseWriter, r *http.Request) {
return
}
- var user *db.User
- var emailVerificationId string
- var signInCodeId string
- var signInCodeOrgId string
-
- if req.IsSignInCode {
- res, err := db.ValidateSignInCode(req.Pin)
-
- if err != nil {
- log.Printf("Error validating sign in code: %v\n", err)
- http.Error(w, "Error validating sign in code: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- user, err = db.GetUser(res.UserId)
-
- if err != nil {
- log.Printf("Error getting user: %v\n", err)
- http.Error(w, "Error getting user: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- if user == nil {
- log.Printf("User not found for id: %v\n", res.UserId)
- http.Error(w, "User not found", http.StatusNotFound)
- return
- }
-
- signInCodeId = res.Id
- signInCodeOrgId = res.OrgId
- } else {
- req.Email = strings.ToLower(req.Email)
- user, err = db.GetUserByEmail(req.Email)
-
- if err != nil {
- log.Printf("Error getting user: %v\n", err)
- http.Error(w, "Error getting user: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- if user == nil {
- log.Printf("User not found for email: %v\n", req.Email)
- http.Error(w, "Not found", http.StatusNotFound)
- return
- }
-
- emailVerificationId, err = db.ValidateEmailVerification(req.Email, req.Pin)
-
- if err != nil {
- log.Printf("Error validating email verification: %v\n", err)
- http.Error(w, "Error validating email verification: "+err.Error(), http.StatusInternalServerError)
- return
- }
- }
-
- // start a transaction
- tx, err := db.Conn.Beginx()
- if err != nil {
- log.Printf("Error starting transaction: %v\n", err)
- http.Error(w, "Error starting transaction: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- // Ensure that rollback is attempted in case of failure
- defer func() {
- if err != nil {
- if rbErr := tx.Rollback(); rbErr != nil {
- log.Printf("transaction rollback error: %v\n", rbErr)
- } else {
- log.Println("transaction rolled back")
- }
- }
- }()
-
- // create auth token
- token, authTokenId, err := db.CreateAuthToken(user.Id, false, tx)
-
- if err != nil {
- log.Printf("Error creating auth token: %v\n", err)
- http.Error(w, "Error creating auth token: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- if req.IsSignInCode {
- // update sign in code with auth token id
- _, err = tx.Exec("UPDATE sign_in_codes SET auth_token_id = $1 WHERE id = $2", authTokenId, signInCodeId)
-
- if err != nil {
- log.Printf("Error updating sign in code: %v\n", err)
- http.Error(w, "Error updating sign in code: "+err.Error(), http.StatusInternalServerError)
- return
- }
- } else {
- // update email verification with user and auth token ids
- _, err = tx.Exec("UPDATE email_verifications SET user_id = $1, auth_token_id = $2 WHERE id = $3", user.Id, authTokenId, emailVerificationId)
- }
+ resp, err := ValidateAndSignIn(w, r, req)
if err != nil {
- log.Printf("Error updating email verification: %v\n", err)
- http.Error(w, "Error updating email verification: "+err.Error(), http.StatusInternalServerError)
+ log.Printf("Error signing in: %v\n", err)
+ http.Error(w, "Error signing in: "+err.Error(), http.StatusInternalServerError)
return
}
- // commit transaction
- err = tx.Commit()
- if err != nil {
- log.Printf("Error committing transaction: %v\n", err)
- http.Error(w, "Error committing transaction: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- // get orgs
- orgs, err := db.GetAccessibleOrgsForUser(user)
-
- if err != nil {
- log.Printf("Error getting orgs for user: %v\n", err)
- http.Error(w, "Error getting orgs for user: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
- if req.IsSignInCode {
- filteredOrgs := []*db.Org{}
- for _, org := range orgs {
- if org.Id == signInCodeOrgId {
- filteredOrgs = append(filteredOrgs, org)
- }
- }
- orgs = filteredOrgs
- }
-
- apiOrgs, apiErr := toApiOrgs(orgs)
-
- if apiErr != nil {
- log.Printf("Error converting orgs to api orgs: %v\n", apiErr)
- writeApiError(w, *apiErr)
- return
- }
-
- resp := shared.SessionResponse{
- UserId: user.Id,
- Token: token,
- Email: user.Email,
- UserName: user.Name,
- Orgs: apiOrgs,
- }
-
bytes, err := json.Marshal(resp)
if err != nil {
@@ -371,20 +233,6 @@ func SignInHandler(w http.ResponseWriter, r *http.Request) {
return
}
- // with a single org, set the orgId in the cookie
- // otherwise, the user will be prompted to select an org
- var orgId string
- if len(orgs) == 1 {
- orgId = orgs[0].Id
- }
-
- err = SetAuthCookieIfBrowser(w, r, user, token, orgId)
- if err != nil {
- log.Printf("Error setting auth cookie: %v\n", err)
- http.Error(w, "Error setting auth cookie: "+err.Error(), http.StatusInternalServerError)
- return
- }
-
log.Println("Successfully signed in")
w.Write(bytes)
diff --git a/app/server/handlers/users.go b/app/server/handlers/users.go
index bf7f2574..b0b7318e 100644
--- a/app/server/handlers/users.go
+++ b/app/server/handlers/users.go
@@ -18,11 +18,18 @@ func ListUsersHandler(w http.ResponseWriter, r *http.Request) {
return
}
- if auth.User.IsTrial {
+ org, err := db.GetOrg(auth.OrgId)
+ if err != nil {
+ log.Printf("Error getting org: %v\n", err)
+ http.Error(w, "Error getting org: "+err.Error(), http.StatusInternalServerError)
+ return
+ }
+
+ if org.IsTrial {
writeApiError(w, shared.ApiError{
Type: shared.ApiErrorTypeTrialActionNotAllowed,
Status: http.StatusForbidden,
- Msg: "Anonymous trial user can't list users",
+ Msg: "Trial user can't list users",
})
return
}
@@ -76,11 +83,18 @@ func DeleteOrgUserHandler(w http.ResponseWriter, r *http.Request) {
return
}
- if auth.User.IsTrial {
+ org, err := db.GetOrg(auth.OrgId)
+ if err != nil {
+ log.Printf("Error getting org: %v\n", err)
+ http.Error(w, "Error getting org: "+err.Error(), http.StatusInternalServerError)
+ return
+ }
+
+ if org.IsTrial {
writeApiError(w, shared.ApiError{
Type: shared.ApiErrorTypeTrialActionNotAllowed,
Status: http.StatusForbidden,
- Msg: "Anonymous trial user can't delete users",
+ Msg: "Trial user can't delete users",
})
return
}
diff --git a/app/server/hooks/hooks.go b/app/server/hooks/hooks.go
index f121645d..06f03619 100644
--- a/app/server/hooks/hooks.go
+++ b/app/server/hooks/hooks.go
@@ -2,6 +2,7 @@ package hooks
import (
"plandex-server/db"
+ "plandex-server/types"
"github.com/jmoiron/sqlx"
"github.com/plandex/plandex/shared"
@@ -16,6 +17,7 @@ const (
DidSendModelRequest = "did_send_model_request"
CreateOrg = "create_org"
+ Authenticate = "authenticate"
GetIntegratedModels = "get_integrated_models"
GetApiOrgs = "get_api_orgs"
)
@@ -40,16 +42,20 @@ type CreateOrgHookRequestParams struct {
Org *db.Org
}
+type AuthenticateHookRequestParams struct {
+ Path string
+}
+
type HookParams struct {
- User *db.User
- OrgId string
- Plan *db.Plan
- Tx *sqlx.Tx
-
- WillSendModelRequestParams *WillSendModelRequestParams
- DidSendModelRequestParams *DidSendModelRequestParams
- CreateOrgHookRequestParams *CreateOrgHookRequestParams
- GetApiOrgIds []string
+ Auth *types.ServerAuth
+ Plan *db.Plan
+ Tx *sqlx.Tx
+
+ WillSendModelRequestParams *WillSendModelRequestParams
+ DidSendModelRequestParams *DidSendModelRequestParams
+ CreateOrgHookRequestParams *CreateOrgHookRequestParams
+ GetApiOrgIds []string
+ AuthenticateHookRequestParams *AuthenticateHookRequestParams
}
type GetIntegratedModelsResult struct {
diff --git a/app/server/migrations/2024092100_remove_trial_fields.down.sql b/app/server/migrations/2024092100_remove_trial_fields.down.sql
new file mode 100644
index 00000000..81f018d5
--- /dev/null
+++ b/app/server/migrations/2024092100_remove_trial_fields.down.sql
@@ -0,0 +1,2 @@
+ALTER TABLE auth_tokens ADD COLUMN is_trial BOOLEAN NOT NULL DEFAULT FALSE;
+ALTER TABLE users ADD COLUMN is_trial BOOLEAN NOT NULL DEFAULT FALSE;
\ No newline at end of file
diff --git a/app/server/migrations/2024092100_remove_trial_fields.up.sql b/app/server/migrations/2024092100_remove_trial_fields.up.sql
new file mode 100644
index 00000000..d4efed21
--- /dev/null
+++ b/app/server/migrations/2024092100_remove_trial_fields.up.sql
@@ -0,0 +1,2 @@
+ALTER TABLE auth_tokens DROP COLUMN is_trial;
+ALTER TABLE users DROP COLUMN is_trial;
\ No newline at end of file
diff --git a/app/server/model/name.go b/app/server/model/name.go
index bf333db6..67b78d8d 100644
--- a/app/server/model/name.go
+++ b/app/server/model/name.go
@@ -46,9 +46,8 @@ func GenPlanName(
}
_, apiErr := hooks.ExecHook(hooks.WillSendModelRequest, hooks.HookParams{
- User: auth.User,
- OrgId: auth.OrgId,
- Plan: plan,
+ Auth: auth,
+ Plan: plan,
WillSendModelRequestParams: &hooks.WillSendModelRequestParams{
InputTokens: numTokens,
OutputTokens: shared.AvailableModelsByName[config.BaseModelConfig.ModelName].DefaultReservedOutputTokens,
@@ -115,9 +114,8 @@ func GenPlanName(
}
_, apiErr = hooks.ExecHook(hooks.DidSendModelRequest, hooks.HookParams{
- User: auth.User,
- OrgId: auth.OrgId,
- Plan: plan,
+ Auth: auth,
+ Plan: plan,
DidSendModelRequestParams: &hooks.DidSendModelRequestParams{
InputTokens: inputTokens,
OutputTokens: outputTokens,
@@ -178,9 +176,8 @@ func GenPipedDataName(
}
_, apiErr := hooks.ExecHook(hooks.WillSendModelRequest, hooks.HookParams{
- User: auth.User,
- OrgId: auth.OrgId,
- Plan: plan,
+ Auth: auth,
+ Plan: plan,
WillSendModelRequestParams: &hooks.WillSendModelRequestParams{
InputTokens: numTokens,
OutputTokens: shared.AvailableModelsByName[config.BaseModelConfig.ModelName].DefaultReservedOutputTokens,
@@ -255,9 +252,8 @@ func GenPipedDataName(
}
_, apiErr = hooks.ExecHook(hooks.DidSendModelRequest, hooks.HookParams{
- User: auth.User,
- OrgId: auth.OrgId,
- Plan: plan,
+ Auth: auth,
+ Plan: plan,
DidSendModelRequestParams: &hooks.DidSendModelRequestParams{
InputTokens: inputTokens,
OutputTokens: outputTokens,
@@ -322,9 +318,8 @@ func GenNoteName(
}
_, apiErr := hooks.ExecHook(hooks.WillSendModelRequest, hooks.HookParams{
- User: auth.User,
- OrgId: auth.OrgId,
- Plan: plan,
+ Auth: auth,
+ Plan: plan,
WillSendModelRequestParams: &hooks.WillSendModelRequestParams{
InputTokens: numTokens,
OutputTokens: shared.AvailableModelsByName[config.BaseModelConfig.ModelName].DefaultReservedOutputTokens,
@@ -399,9 +394,8 @@ func GenNoteName(
}
_, apiErr = hooks.ExecHook(hooks.DidSendModelRequest, hooks.HookParams{
- User: auth.User,
- OrgId: auth.OrgId,
- Plan: plan,
+ Auth: auth,
+ Plan: plan,
DidSendModelRequestParams: &hooks.DidSendModelRequestParams{
InputTokens: inputTokens,
OutputTokens: outputTokens,
diff --git a/app/server/model/plan/build_exec.go b/app/server/model/plan/build_exec.go
index c790e56e..712da00d 100644
--- a/app/server/model/plan/build_exec.go
+++ b/app/server/model/plan/build_exec.go
@@ -329,9 +329,8 @@ func (fileState *activeBuildStreamFileState) buildFileLineNums() {
fileState.inputTokens = inputTokens
_, apiErr := hooks.ExecHook(hooks.WillSendModelRequest, hooks.HookParams{
- User: auth.User,
- OrgId: auth.OrgId,
- Plan: fileState.plan,
+ Auth: auth,
+ Plan: fileState.plan,
WillSendModelRequestParams: &hooks.WillSendModelRequestParams{
InputTokens: inputTokens,
OutputTokens: shared.AvailableModelsByName[fileState.settings.ModelPack.Builder.BaseModelConfig.ModelName].DefaultReservedOutputTokens,
diff --git a/app/server/model/plan/build_fix.go b/app/server/model/plan/build_fix.go
index 2984ee74..bf1fbed3 100644
--- a/app/server/model/plan/build_fix.go
+++ b/app/server/model/plan/build_fix.go
@@ -76,9 +76,8 @@ func (fileState *activeBuildStreamFileState) fixFileLineNums() {
fileState.inputTokens = inputTokens
_, apiErr := hooks.ExecHook(hooks.WillSendModelRequest, hooks.HookParams{
- User: auth.User,
- OrgId: auth.OrgId,
- Plan: fileState.plan,
+ Auth: auth,
+ Plan: fileState.plan,
WillSendModelRequestParams: &hooks.WillSendModelRequestParams{
InputTokens: inputTokens,
OutputTokens: shared.AvailableModelsByName[fileState.settings.ModelPack.GetAutoFix().BaseModelConfig.ModelName].DefaultReservedOutputTokens,
diff --git a/app/server/model/plan/build_fix_stream.go b/app/server/model/plan/build_fix_stream.go
index 00e3adcf..ad182d54 100644
--- a/app/server/model/plan/build_fix_stream.go
+++ b/app/server/model/plan/build_fix_stream.go
@@ -40,9 +40,8 @@ func (fileState *activeBuildStreamFileState) listenStreamFixChanges(stream *open
execHookOnStop := func(sendStreamErr bool) {
_, apiErr := hooks.ExecHook(hooks.DidSendModelRequest, hooks.HookParams{
- User: auth.User,
- OrgId: auth.OrgId,
- Plan: fileState.plan,
+ Auth: auth,
+ Plan: fileState.plan,
DidSendModelRequestParams: &hooks.DidSendModelRequestParams{
InputTokens: fileState.inputTokens,
OutputTokens: fileState.activeBuild.FixBufferTokens,
@@ -120,9 +119,8 @@ func (fileState *activeBuildStreamFileState) listenStreamFixChanges(stream *open
spew.Dump(response.Usage)
_, apiErr := hooks.ExecHook(hooks.DidSendModelRequest, hooks.HookParams{
- User: auth.User,
- OrgId: auth.OrgId,
- Plan: fileState.plan,
+ Auth: auth,
+ Plan: fileState.plan,
DidSendModelRequestParams: &hooks.DidSendModelRequestParams{
InputTokens: response.Usage.PromptTokens,
OutputTokens: response.Usage.CompletionTokens,
diff --git a/app/server/model/plan/build_stream_line_nums.go b/app/server/model/plan/build_stream_line_nums.go
index 8cc3799a..5fcfe26d 100644
--- a/app/server/model/plan/build_stream_line_nums.go
+++ b/app/server/model/plan/build_stream_line_nums.go
@@ -42,9 +42,8 @@ func (fileState *activeBuildStreamFileState) listenStreamChangesWithLineNums(str
execHookOnStop := func(sendStreamErr bool) {
_, apiErr := hooks.ExecHook(hooks.DidSendModelRequest, hooks.HookParams{
- User: auth.User,
- OrgId: auth.OrgId,
- Plan: fileState.plan,
+ Auth: auth,
+ Plan: fileState.plan,
DidSendModelRequestParams: &hooks.DidSendModelRequestParams{
InputTokens: fileState.inputTokens,
OutputTokens: fileState.activeBuild.WithLineNumsBufferTokens,
@@ -124,9 +123,8 @@ func (fileState *activeBuildStreamFileState) listenStreamChangesWithLineNums(str
spew.Dump(response.Usage)
_, apiErr := hooks.ExecHook(hooks.DidSendModelRequest, hooks.HookParams{
- User: auth.User,
- OrgId: auth.OrgId,
- Plan: fileState.plan,
+ Auth: auth,
+ Plan: fileState.plan,
DidSendModelRequestParams: &hooks.DidSendModelRequestParams{
InputTokens: response.Usage.PromptTokens,
OutputTokens: response.Usage.CompletionTokens,
diff --git a/app/server/model/plan/build_verify.go b/app/server/model/plan/build_verify.go
index e0ce5dbf..f309f085 100644
--- a/app/server/model/plan/build_verify.go
+++ b/app/server/model/plan/build_verify.go
@@ -96,9 +96,8 @@ func (fileState *activeBuildStreamFileState) verifyFileBuild() {
fileState.inputTokens = inputTokens
_, apiErr := hooks.ExecHook(hooks.WillSendModelRequest, hooks.HookParams{
- User: auth.User,
- OrgId: auth.OrgId,
- Plan: fileState.plan,
+ Auth: auth,
+ Plan: fileState.plan,
WillSendModelRequestParams: &hooks.WillSendModelRequestParams{
InputTokens: inputTokens,
OutputTokens: shared.AvailableModelsByName[fileState.settings.ModelPack.GetVerifier().BaseModelConfig.ModelName].DefaultReservedOutputTokens,
diff --git a/app/server/model/plan/build_verify_stream.go b/app/server/model/plan/build_verify_stream.go
index 3937c211..e6742105 100644
--- a/app/server/model/plan/build_verify_stream.go
+++ b/app/server/model/plan/build_verify_stream.go
@@ -39,9 +39,8 @@ func (fileState *activeBuildStreamFileState) listenStreamVerifyOutput(stream *op
execHookOnStop := func(sendStreamErr bool) {
_, apiErr := hooks.ExecHook(hooks.DidSendModelRequest, hooks.HookParams{
- User: auth.User,
- OrgId: auth.OrgId,
- Plan: fileState.plan,
+ Auth: auth,
+ Plan: fileState.plan,
DidSendModelRequestParams: &hooks.DidSendModelRequestParams{
InputTokens: fileState.inputTokens,
OutputTokens: fileState.activeBuild.VerifyBufferTokens,
@@ -120,9 +119,8 @@ func (fileState *activeBuildStreamFileState) listenStreamVerifyOutput(stream *op
spew.Dump(response.Usage)
_, apiErr := hooks.ExecHook(hooks.DidSendModelRequest, hooks.HookParams{
- User: auth.User,
- OrgId: auth.OrgId,
- Plan: fileState.plan,
+ Auth: auth,
+ Plan: fileState.plan,
DidSendModelRequestParams: &hooks.DidSendModelRequestParams{
InputTokens: response.Usage.PromptTokens,
OutputTokens: response.Usage.CompletionTokens,
diff --git a/app/server/model/plan/commit_msg.go b/app/server/model/plan/commit_msg.go
index a2cc874d..af8b2ee2 100644
--- a/app/server/model/plan/commit_msg.go
+++ b/app/server/model/plan/commit_msg.go
@@ -39,9 +39,8 @@ func (state *activeTellStreamState) genPlanDescription() (*db.ConvoMessageDescri
numTokens := prompts.ExtraTokensPerRequest + (prompts.ExtraTokensPerMessage * 2) + prompts.SysDescribeNumTokens + activePlan.NumTokens
_, apiErr := hooks.ExecHook(hooks.WillSendModelRequest, hooks.HookParams{
- User: auth.User,
- OrgId: auth.OrgId,
- Plan: plan,
+ Auth: auth,
+ Plan: plan,
WillSendModelRequestParams: &hooks.WillSendModelRequestParams{
InputTokens: numTokens,
OutputTokens: shared.AvailableModelsByName[config.BaseModelConfig.ModelName].DefaultReservedOutputTokens,
@@ -117,9 +116,8 @@ func (state *activeTellStreamState) genPlanDescription() (*db.ConvoMessageDescri
}
_, apiErr = hooks.ExecHook(hooks.DidSendModelRequest, hooks.HookParams{
- User: auth.User,
- OrgId: auth.OrgId,
- Plan: plan,
+ Auth: auth,
+ Plan: plan,
DidSendModelRequestParams: &hooks.DidSendModelRequestParams{
InputTokens: inputTokens,
OutputTokens: outputTokens,
@@ -182,9 +180,8 @@ func GenCommitMsgForPendingResults(auth *types.ServerAuth, plan *db.Plan, client
numTokens := prompts.ExtraTokensPerRequest + (prompts.ExtraTokensPerMessage * 2) + prompts.SysPendingResultsNumTokens + contentTokens
_, apiErr := hooks.ExecHook(hooks.WillSendModelRequest, hooks.HookParams{
- User: auth.User,
- OrgId: auth.OrgId,
- Plan: plan,
+ Auth: auth,
+ Plan: plan,
WillSendModelRequestParams: &hooks.WillSendModelRequestParams{
InputTokens: numTokens,
OutputTokens: shared.AvailableModelsByName[config.BaseModelConfig.ModelName].DefaultReservedOutputTokens,
@@ -244,9 +241,8 @@ func GenCommitMsgForPendingResults(auth *types.ServerAuth, plan *db.Plan, client
}
_, apiErr = hooks.ExecHook(hooks.DidSendModelRequest, hooks.HookParams{
- User: auth.User,
- OrgId: auth.OrgId,
- Plan: plan,
+ Auth: auth,
+ Plan: plan,
DidSendModelRequestParams: &hooks.DidSendModelRequestParams{
InputTokens: inputTokens,
OutputTokens: outputTokens,
diff --git a/app/server/model/plan/exec_status.go b/app/server/model/plan/exec_status.go
index acd179e6..15837f5d 100644
--- a/app/server/model/plan/exec_status.go
+++ b/app/server/model/plan/exec_status.go
@@ -84,9 +84,8 @@ func (state *activeTellStreamState) execStatusShouldContinue(message string, lat
numTokens := prompts.ExtraTokensPerRequest + prompts.ExtraTokensPerMessage + contentTokens
_, apiErr := hooks.ExecHook(hooks.WillSendModelRequest, hooks.HookParams{
- User: auth.User,
- OrgId: auth.OrgId,
- Plan: plan,
+ Auth: auth,
+ Plan: plan,
WillSendModelRequestParams: &hooks.WillSendModelRequestParams{
InputTokens: numTokens,
OutputTokens: shared.AvailableModelsByName[config.BaseModelConfig.ModelName].DefaultReservedOutputTokens,
@@ -183,9 +182,8 @@ func (state *activeTellStreamState) execStatusShouldContinue(message string, lat
}
_, apiErr = hooks.ExecHook(hooks.DidSendModelRequest, hooks.HookParams{
- User: auth.User,
- OrgId: auth.OrgId,
- Plan: plan,
+ Auth: auth,
+ Plan: plan,
DidSendModelRequestParams: &hooks.DidSendModelRequestParams{
InputTokens: inputTokens,
OutputTokens: outputTokens,
diff --git a/app/server/model/plan/tell_exec.go b/app/server/model/plan/tell_exec.go
index ee733275..599766eb 100644
--- a/app/server/model/plan/tell_exec.go
+++ b/app/server/model/plan/tell_exec.go
@@ -68,8 +68,9 @@ func execTellPlan(
}
if missingFileResponse == "" {
+ log.Println("Executing WillExecPlanHook")
_, apiErr := hooks.ExecHook(hooks.WillExecPlan, hooks.HookParams{
- User: auth.User,
+ Auth: auth,
Plan: plan,
})
@@ -415,9 +416,8 @@ func execTellPlan(
// }
_, apiErr := hooks.ExecHook(hooks.WillSendModelRequest, hooks.HookParams{
- User: auth.User,
- OrgId: auth.OrgId,
- Plan: plan,
+ Auth: auth,
+ Plan: plan,
WillSendModelRequestParams: &hooks.WillSendModelRequestParams{
InputTokens: state.totalRequestTokens,
OutputTokens: state.settings.ModelPack.Planner.ReservedOutputTokens,
diff --git a/app/server/model/plan/tell_stream.go b/app/server/model/plan/tell_stream.go
index 5e612b81..e5df31d2 100644
--- a/app/server/model/plan/tell_stream.go
+++ b/app/server/model/plan/tell_stream.go
@@ -60,9 +60,8 @@ func (state *activeTellStreamState) listenStream(stream *openai.ChatCompletionSt
execHookOnStop := func(sendStreamErr bool) {
_, apiErr := hooks.ExecHook(hooks.DidSendModelRequest, hooks.HookParams{
- User: auth.User,
- OrgId: auth.OrgId,
- Plan: plan,
+ Auth: auth,
+ Plan: plan,
DidSendModelRequestParams: &hooks.DidSendModelRequestParams{
InputTokens: state.totalRequestTokens,
OutputTokens: active.NumTokens,
@@ -138,9 +137,8 @@ mainLoop:
spew.Dump(response.Usage)
_, apiErr := hooks.ExecHook(hooks.DidSendModelRequest, hooks.HookParams{
- User: auth.User,
- OrgId: auth.OrgId,
- Plan: plan,
+ Auth: auth,
+ Plan: plan,
DidSendModelRequestParams: &hooks.DidSendModelRequestParams{
InputTokens: response.Usage.PromptTokens,
OutputTokens: response.Usage.CompletionTokens,
@@ -356,7 +354,7 @@ mainLoop:
// summarize in the background
go func() {
err := summarizeConvo(client, settings.ModelPack.PlanSummary, summarizeConvoParams{
- user: auth.User,
+ auth: auth,
plan: plan,
branch: branch,
convo: convo,
diff --git a/app/server/model/plan/tell_summary.go b/app/server/model/plan/tell_summary.go
index 44eb770e..623037fb 100644
--- a/app/server/model/plan/tell_summary.go
+++ b/app/server/model/plan/tell_summary.go
@@ -9,6 +9,7 @@ import (
"plandex-server/db"
"plandex-server/model"
"plandex-server/model/prompts"
+ "plandex-server/types"
"time"
"github.com/davecgh/go-spew/spew"
@@ -174,8 +175,8 @@ func (state *activeTellStreamState) injectSummariesAsNeeded() bool {
}
type summarizeConvoParams struct {
+ auth *types.ServerAuth
plan *db.Plan
- user *db.User
branch string
convo []*db.ConvoMessage
summaries []*db.ConvoSummary
@@ -188,7 +189,6 @@ type summarizeConvoParams struct {
func summarizeConvo(client *openai.Client, config shared.ModelRoleConfig, params summarizeConvoParams, ctx context.Context) error {
plan := params.plan
- user := params.user
planId := plan.Id
log.Printf("summarizeConvo: Called for plan ID %s on branch %s\n", planId, params.branch)
log.Printf("summarizeConvo: Starting summarizeConvo for planId: %s\n", planId)
@@ -197,7 +197,6 @@ func summarizeConvo(client *openai.Client, config shared.ModelRoleConfig, params
convo := params.convo
summaries := params.summaries
userPrompt := params.userPrompt
- currentOrgId := params.currentOrgId
currentReply := params.currentReply
active := GetActivePlan(planId, branch)
@@ -318,9 +317,8 @@ func summarizeConvo(client *openai.Client, config shared.ModelRoleConfig, params
LatestConvoMessageId: latestMessageId,
LatestConvoMessageCreatedAt: latestMessageSummarizedAt,
NumMessages: numMessagesSummarized,
- OrgId: currentOrgId,
+ Auth: params.auth,
Plan: plan,
- User: user,
ModelPackName: params.modelPackName,
}, ctx)
diff --git a/app/server/model/summarize.go b/app/server/model/summarize.go
index bdd8d61e..bcc3a32b 100644
--- a/app/server/model/summarize.go
+++ b/app/server/model/summarize.go
@@ -15,8 +15,7 @@ import (
)
type PlanSummaryParams struct {
- User *db.User
- OrgId string
+ Auth *types.ServerAuth
Plan *db.Plan
ActivePlan *types.ActivePlan
ModelPackName string
@@ -49,9 +48,8 @@ func PlanSummary(client *openai.Client, config shared.ModelRoleConfig, params Pl
numTokens += prompts.PlanSummaryNumTokens
_, apiErr := hooks.ExecHook(hooks.WillSendModelRequest, hooks.HookParams{
- User: params.User,
- OrgId: params.OrgId,
- Plan: params.Plan,
+ Auth: params.Auth,
+ Plan: params.Plan,
WillSendModelRequestParams: &hooks.WillSendModelRequestParams{
InputTokens: numTokens,
OutputTokens: shared.AvailableModelsByName[config.BaseModelConfig.ModelName].DefaultReservedOutputTokens,
@@ -103,9 +101,8 @@ func PlanSummary(client *openai.Client, config shared.ModelRoleConfig, params Pl
}
_, apiErr = hooks.ExecHook(hooks.DidSendModelRequest, hooks.HookParams{
- User: params.User,
- OrgId: params.OrgId,
- Plan: params.Plan,
+ Auth: params.Auth,
+ Plan: params.Plan,
DidSendModelRequestParams: &hooks.DidSendModelRequestParams{
InputTokens: inputTokens,
OutputTokens: outputTokens,
@@ -125,7 +122,7 @@ func PlanSummary(client *openai.Client, config shared.ModelRoleConfig, params Pl
// log.Println(content)
return &db.ConvoSummary{
- OrgId: params.OrgId,
+ OrgId: params.Auth.OrgId,
PlanId: params.Plan.Id,
Summary: "## Summary of the plan so far:\n\n" + content,
Tokens: resp.Usage.CompletionTokens,
diff --git a/app/server/setup/setup.go b/app/server/setup/setup.go
index b4c31375..5db1d6c6 100644
--- a/app/server/setup/setup.go
+++ b/app/server/setup/setup.go
@@ -47,7 +47,14 @@ func StartServer(r *mux.Router) {
}
// Ensure database connection is closed
- defer db.Conn.Close()
+ defer func() {
+ log.Println("Closing database connection...")
+ err := db.Conn.Close()
+ if err != nil {
+ log.Printf("Error closing database connection: %v", err)
+ }
+ log.Println("Database connection closed")
+ }()
// Get externalPort from the environment variable or default to 8080
externalPort := os.Getenv("PORT")
@@ -100,7 +107,7 @@ func StartServer(r *mux.Router) {
defer cancel()
if err := server.Shutdown(ctx); err != nil {
- log.Fatalf("Server forced to shutdown: %v", err)
+ log.Printf("Server forced to shutdown: %v", err)
}
// Wait for active plans to complete
diff --git a/app/server/types/trial.go b/app/server/types/trial.go
index ae8dd059..08fed988 100644
--- a/app/server/types/trial.go
+++ b/app/server/types/trial.go
@@ -1,4 +1,4 @@
package types
const TrialMaxReplies = 10
-const TrialMaxPlans = 10
+const TrialMaxPlans = 0
diff --git a/app/shared/auth.go b/app/shared/auth.go
index 38fcebe8..f14782a2 100644
--- a/app/shared/auth.go
+++ b/app/shared/auth.go
@@ -17,6 +17,8 @@ const (
ApiErrorTypeCloudInsufficientCredits ApiErrorType = "cloud_insufficient_credits"
ApiErrorTypeCloudMonthlyMaxReached ApiErrorType = "cloud_monthly_max_reached"
+ ApiErrorTypeCloudSubscriptionPaused ApiErrorType = "cloud_subscription_paused"
+ ApiErrorTypeCloudSubscriptionOverdue ApiErrorType = "cloud_subscription_overdue"
ApiErrorTypeOther ApiErrorType = "other"
)
@@ -29,6 +31,11 @@ type TrialMessagesExceededError struct {
MaxReplies int `json:"maxMessages"`
}
+type BillingError struct {
+ HasBillingPermission bool `json:"hasBillingPermission"`
+ IsTrial bool `json:"isTrial"`
+}
+
type ApiError struct {
Type ApiErrorType `json:"type"`
Status int `json:"status"`
@@ -39,6 +46,9 @@ type ApiError struct {
// only used for trial messages exceeded error
TrialMessagesExceededError *TrialMessagesExceededError `json:"trialMessagesExceededError,omitempty"`
+
+ // only used for billing errors
+ BillingError *BillingError `json:"billingError,omitempty"`
}
type ClientAccount struct {
@@ -48,7 +58,8 @@ type ClientAccount struct {
UserName string `json:"userName"`
UserId string `json:"userId"`
Token string `json:"token"`
- IsTrial bool `json:"isTrial"`
+
+ IsTrial bool `json:"isTrial"` // legacy field
}
type ClientAuth struct {
diff --git a/app/shared/data_models.go b/app/shared/data_models.go
index 9f280f91..a9975791 100644
--- a/app/shared/data_models.go
+++ b/app/shared/data_models.go
@@ -11,9 +11,10 @@ import (
)
type Org struct {
- Id string `json:"id"`
- Name string `json:"name"`
- IsTrial bool `json:"isTrial"`
+ Id string `json:"id"`
+ Name string `json:"name"`
+ IsTrial bool `json:"isTrial"`
+ AutoAddDomainUsers bool `json:"autoAddDomainUsers"`
// optional cloud attributes
IntegratedModelsMode bool `json:"integratedModelsMode,omitempty"`
diff --git a/app/shared/req_res.go b/app/shared/req_res.go
index ca097b7b..ec4f01af 100644
--- a/app/shared/req_res.go
+++ b/app/shared/req_res.go
@@ -28,6 +28,11 @@ type SignInRequest struct {
IsSignInCode bool `json:"isSignInCode"`
}
+type UiSignInToken struct {
+ Pin string `json:"pin"`
+ RedirectTo string `json:"redirectTo"`
+}
+
type CreateAccountRequest struct {
Email string `json:"email"`
Pin string `json:"pin"`
@@ -242,23 +247,6 @@ type RenamePlanRequest struct {
}
// Cloud requests and responses
-type CreateCloudOrgRequest struct {
- CreateOrgRequest
- IntegratedModelsMode bool `json:"integratedModelsMode"`
-}
-
-type StartTrialRequest struct {
- Account CreateAccountRequest `json:"account"`
- Org CreateCloudOrgRequest `json:"org"`
-}
-
-type StartTrialResponse struct {
- UserId string `json:"userId"`
- Token string `json:"token"`
- OrgId string `json:"orgId"`
- StripeCustomerId string `json:"stripeCustomerId"`
-}
-
type CreditsLogRequest struct {
PageSize int `json:"pageSize"`
Page int `json:"page"`
diff --git a/plandex-cursor.code-workspace b/plandex-cursor.code-workspace
new file mode 100644
index 00000000..7b536cfa
--- /dev/null
+++ b/plandex-cursor.code-workspace
@@ -0,0 +1,35 @@
+{
+ "folders": [
+ {
+ "name": "plandex",
+ "path": "."
+ },
+ {
+ "name": "static",
+ "path": "static"
+ },
+ {
+ "name": "cli",
+ "path": "app/cli"
+ },
+ {
+ "name": "server",
+ "path": "app/server"
+ },
+ {
+ "name": "cloud",
+ "path": "app/server/cloud"
+ },
+ {
+ "name": "shared",
+ "path": "app/shared"
+ },
+ {
+ "name": "node",
+ "path": "app/server/cloud/ui/node"
+ }
+ ],
+ "settings": {
+ "git.ignoreLimitWarning": true
+ }
+}