Skip to content

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

package reorg, api timeouts, working on auth/accounts

Dane Schneider8c6954ee1507
diff --git a/cli/api/client.go b/cli/api/client.go
deleted file mode 100644
index dada8eb6..00000000
--- a/cli/api/client.go
+++ /dev/null
@@ -1,17 +0,0 @@
-package api
-
-import (
- "os"
-)
-
-var apiHost string
-
-var Client ApiClient = (*Api)(nil)
-
-func init() {
- var port = os.Getenv("PORT")
- if port == "" {
- port = "8088"
- }
- apiHost = "http://localhost:" + port
-}
diff --git a/cli/api/clients.go b/cli/api/clients.go
new file mode 100644
index 00000000..0a88c30d
--- /dev/null
+++ b/cli/api/clients.go
@@ -0,0 +1,76 @@
+package api
+
+import (
+ "net"
+ "net/http"
+ "os"
+ "plandex/auth"
+ "plandex/types"
+ "time"
+)
+
+const dialTimeout = 10 * time.Second
+const fastReqTimeout = 30 * time.Second
+const slowReqTimeout = 5 * time.Minute
+
+type Api struct{}
+
+var apiHost string
+
+var Client types.ApiClient = (*Api)(nil)
+
+func init() {
+ var port = os.Getenv("PORT")
+ if port == "" {
+ port = "8088"
+ }
+ apiHost = "http://localhost:" + port
+}
+
+type authenticatedTransport struct {
+ underlyingTransport http.RoundTripper
+}
+
+// RoundTrip executes a single HTTP transaction and adds a custom header
+func (t *authenticatedTransport) RoundTrip(req *http.Request) (*http.Response, error) {
+ auth.SetAuthHeader(req)
+ return t.underlyingTransport.RoundTrip(req)
+}
+
+var netDialer = &net.Dialer{
+ Timeout: dialTimeout,
+}
+
+var unauthenticatedClient = &http.Client{
+ Transport: &http.Transport{
+ Dial: netDialer.Dial,
+ },
+ Timeout: fastReqTimeout,
+}
+
+var authenticatedFastClient = &http.Client{
+ Transport: &authenticatedTransport{
+ underlyingTransport: &http.Transport{
+ Dial: netDialer.Dial,
+ },
+ },
+ Timeout: fastReqTimeout,
+}
+
+var authenticatedSlowClient = &http.Client{
+ Transport: &authenticatedTransport{
+ underlyingTransport: &http.Transport{
+ Dial: netDialer.Dial,
+ },
+ },
+ Timeout: slowReqTimeout,
+}
+
+var authenticatedStreamingClient = &http.Client{
+ Transport: &authenticatedTransport{
+ underlyingTransport: &http.Transport{
+ Dial: netDialer.Dial,
+ },
+ },
+ // No global timeout set for the streaming client
+}
diff --git a/cli/api/methods.go b/cli/api/methods.go
index e31dbc7b..5afe5f92 100644
--- a/cli/api/methods.go
+++ b/cli/api/methods.go
@@ -7,10 +7,35 @@ import (
"io"
"log"
"net/http"
+ "plandex/types"
"github.com/plandex/plandex/shared"
)
+func (a *Api) StartTrial() (*shared.StartTrialResponse, error) {
+ serverUrl := apiHost + "/accounts/start-trial"
+
+ resp, err := unauthenticatedClient.Post(serverUrl, "application/json", nil)
+ if err != nil {
+ return nil, fmt.Errorf("error sending request: %v", err)
+ }
+
+ defer resp.Body.Close()
+
+ if resp.StatusCode >= 400 {
+ errorBody, _ := io.ReadAll(resp.Body)
+ return nil, fmt.Errorf("error starting trial: %d - %s", resp.StatusCode, string(errorBody))
+ }
+
+ var startTrialResponse shared.StartTrialResponse
+ err = json.NewDecoder(resp.Body).Decode(&startTrialResponse)
+ if err != nil {
+ return nil, fmt.Errorf("error decoding response: %v", err)
+ }
+
+ return &startTrialResponse, nil
+}
+
func (a *Api) CreateProject(req shared.CreateProjectRequest) (*shared.CreateProjectResponse, error) {
serverUrl := apiHost + "/projects"
reqBytes, err := json.Marshal(req)
@@ -18,7 +43,7 @@ func (a *Api) CreateProject(req shared.CreateProjectRequest) (*shared.CreateProj
return nil, fmt.Errorf("error marshalling request: %v", err)
}
- resp, err := http.Post(serverUrl, "application/json", bytes.NewBuffer(reqBytes))
+ resp, err := authenticatedFastClient.Post(serverUrl, "application/json", bytes.NewBuffer(reqBytes))
if err != nil {
return nil, fmt.Errorf("error sending request: %v", err)
}
@@ -40,7 +65,7 @@ func (a *Api) CreateProject(req shared.CreateProjectRequest) (*shared.CreateProj
func (a *Api) ListProjects() ([]*shared.Project, error) {
serverUrl := apiHost + "/projects"
- resp, err := http.Get(serverUrl)
+ resp, err := authenticatedFastClient.Get(serverUrl)
if err != nil {
return nil, fmt.Errorf("error sending request: %v", err)
}
@@ -73,7 +98,7 @@ func (a *Api) SetProjectPlan(projectId string, req shared.SetProjectPlanRequest)
}
request.Header.Set("Content-Type", "application/json")
- resp, err := http.DefaultClient.Do(request)
+ resp, err := authenticatedFastClient.Do(request)
if err != nil {
return fmt.Errorf("error sending request: %v", err)
}
@@ -100,7 +125,7 @@ func (a *Api) RenameProject(projectId string, req shared.RenameProjectRequest) e
}
request.Header.Set("Content-Type", "application/json")
- resp, err := http.DefaultClient.Do(request)
+ resp, err := authenticatedFastClient.Do(request)
if err != nil {
return fmt.Errorf("error sending request: %v", err)
}
@@ -117,7 +142,7 @@ func (a *Api) RenameProject(projectId string, req shared.RenameProjectRequest) e
func (a *Api) ListPlans(projectId string) ([]*shared.Plan, error) {
serverUrl := fmt.Sprintf("%s/projects/%s/plans", apiHost, projectId)
- resp, err := http.Get(serverUrl)
+ resp, err := authenticatedFastClient.Get(serverUrl)
if err != nil {
return nil, fmt.Errorf("error sending request: %v", err)
}
@@ -140,7 +165,7 @@ func (a *Api) ListPlans(projectId string) ([]*shared.Plan, error) {
func (a *Api) ListArchivedPlans(projectId string) ([]*shared.Plan, error) {
serverUrl := fmt.Sprintf("%s/projects/%s/plans/archive", apiHost, projectId)
- resp, err := http.Get(serverUrl)
+ resp, err := authenticatedFastClient.Get(serverUrl)
if err != nil {
return nil, fmt.Errorf("error sending request: %v", err)
}
@@ -163,7 +188,7 @@ func (a *Api) ListArchivedPlans(projectId string) ([]*shared.Plan, error) {
func (a *Api) ListPlansRunning(projectId string) ([]*shared.Plan, error) {
serverUrl := fmt.Sprintf("%s/projects/%s/plans/ps", apiHost, projectId)
- resp, err := http.Get(serverUrl)
+ resp, err := authenticatedFastClient.Get(serverUrl)
if err != nil {
return nil, fmt.Errorf("error sending request: %v", err)
}
@@ -190,7 +215,7 @@ func (a *Api) CreatePlan(projectId string, req shared.CreatePlanRequest) (*share
return nil, fmt.Errorf("error marshalling request: %v", err)
}
- resp, err := http.Post(serverUrl, "application/json", bytes.NewBuffer(reqBytes))
+ resp, err := authenticatedFastClient.Post(serverUrl, "application/json", bytes.NewBuffer(reqBytes))
if err != nil {
return nil, fmt.Errorf("error sending request: %v", err)
}
@@ -213,7 +238,7 @@ func (a *Api) CreatePlan(projectId string, req shared.CreatePlanRequest) (*share
func (a *Api) GetPlan(planId string) (*shared.Plan, error) {
serverUrl := fmt.Sprintf("%s/plans/%s", apiHost, planId)
- resp, err := http.Get(serverUrl)
+ resp, err := authenticatedFastClient.Get(serverUrl)
if err != nil {
return nil, fmt.Errorf("error sending request: %v", err)
}
@@ -242,7 +267,7 @@ func (a *Api) DeletePlan(planId string) error {
return fmt.Errorf("error creating request: %v", err)
}
- resp, err := http.DefaultClient.Do(req)
+ resp, err := authenticatedFastClient.Do(req)
if err != nil {
return fmt.Errorf("error sending request: %v", err)
}
@@ -264,7 +289,7 @@ func (a *Api) DeleteAllPlans(projectId string) error {
return fmt.Errorf("error creating request: %v", err)
}
- resp, err := http.DefaultClient.Do(req)
+ resp, err := authenticatedFastClient.Do(req)
if err != nil {
return fmt.Errorf("error sending request: %v", err)
}
@@ -278,7 +303,7 @@ func (a *Api) DeleteAllPlans(projectId string) error {
return nil
}
-func (a *Api) TellPlan(planId string, req shared.TellPlanRequest, onStream OnStreamPlan) error {
+func (a *Api) TellPlan(planId string, req shared.TellPlanRequest, onStream types.OnStreamPlan) error {
serverUrl := fmt.Sprintf("%s/plans/%s/tell", apiHost, planId)
reqBytes, err := json.Marshal(req)
@@ -292,7 +317,14 @@ func (a *Api) TellPlan(planId string, req shared.TellPlanRequest, onStream OnStr
}
request.Header.Set("Content-Type", "application/json")
- resp, err := http.DefaultClient.Do(request)
+ var client *http.Client
+ if req.ConnectStream {
+ client = authenticatedStreamingClient
+ } else {
+ client = authenticatedFastClient
+ }
+
+ resp, err := client.Do(request)
if err != nil {
return fmt.Errorf("error sending request: %v", err)
}
@@ -310,7 +342,7 @@ func (a *Api) TellPlan(planId string, req shared.TellPlanRequest, onStream OnStr
return nil
}
-func (a *Api) ConnectPlan(planId string, onStream OnStreamPlan) error {
+func (a *Api) ConnectPlan(planId string, onStream types.OnStreamPlan) error {
serverUrl := fmt.Sprintf("%s/plans/%s/connect", apiHost, planId)
req, err := http.NewRequest(http.MethodPatch, serverUrl, nil)
@@ -318,7 +350,7 @@ func (a *Api) ConnectPlan(planId string, onStream OnStreamPlan) error {
return fmt.Errorf("error creating request: %v", err)
}
- resp, err := http.DefaultClient.Do(req)
+ resp, err := authenticatedStreamingClient.Do(req)
if err != nil {
return fmt.Errorf("error sending request: %v", err)
}
@@ -342,7 +374,7 @@ func (a *Api) StopPlan(planId string) error {
return fmt.Errorf("error creating request: %v", err)
}
- resp, err := http.DefaultClient.Do(req)
+ resp, err := authenticatedFastClient.Do(req)
if err != nil {
return fmt.Errorf("error sending request: %v", err)
}
@@ -359,7 +391,7 @@ func (a *Api) StopPlan(planId string) error {
func (a *Api) GetCurrentPlanState(planId string) (*shared.CurrentPlanState, error) {
serverUrl := fmt.Sprintf("%s/plans/%s/current_plan", apiHost, planId)
- resp, err := http.Get(serverUrl)
+ resp, err := authenticatedFastClient.Get(serverUrl)
if err != nil {
return nil, fmt.Errorf("error sending request: %v", err)
}
@@ -387,7 +419,7 @@ func (a *Api) ApplyPlan(planId string) error {
return fmt.Errorf("error creating request: %v", err)
}
- resp, err := http.DefaultClient.Do(req)
+ resp, err := authenticatedFastClient.Do(req)
if err != nil {
return fmt.Errorf("error sending request: %v", err)
}
@@ -409,7 +441,7 @@ func (a *Api) ArchivePlan(planId string) error {
return fmt.Errorf("error creating request: %v", err)
}
- resp, err := http.DefaultClient.Do(req)
+ resp, err := authenticatedFastClient.Do(req)
if err != nil {
return fmt.Errorf("error sending request: %v", err)
}
@@ -431,7 +463,7 @@ func (a *Api) RejectAllChanges(planId string) error {
return fmt.Errorf("error creating request: %v", err)
}
- resp, err := http.DefaultClient.Do(req)
+ resp, err := authenticatedFastClient.Do(req)
if err != nil {
return fmt.Errorf("error sending request: %v", err)
}
@@ -453,7 +485,7 @@ func (a *Api) RejectResult(planId, resultId string) error {
return fmt.Errorf("error creating request: %v", err)
}
- resp, err := http.DefaultClient.Do(req)
+ resp, err := authenticatedFastClient.Do(req)
if err != nil {
return fmt.Errorf("error sending request: %v", err)
}
@@ -475,7 +507,7 @@ func (a *Api) RejectReplacement(planId, resultId, replacementId string) error {
return fmt.Errorf("error creating request: %v", err)
}
- resp, err := http.DefaultClient.Do(req)
+ resp, err := authenticatedFastClient.Do(req)
if err != nil {
return fmt.Errorf("error sending request: %v", err)
}
@@ -496,7 +528,8 @@ func (a *Api) LoadContext(planId string, req shared.LoadContextRequest) (*shared
return nil, fmt.Errorf("error marshalling request: %v", err)
}
- resp, err := http.Post(serverUrl, "application/json", bytes.NewBuffer(reqBytes))
+ // use the slow client since we may be uploading relatively large files
+ resp, err := authenticatedSlowClient.Post(serverUrl, "application/json", bytes.NewBuffer(reqBytes))
if err != nil {
return nil, fmt.Errorf("error sending request: %v", err)
}
@@ -532,7 +565,8 @@ func (a *Api) UpdateContext(planId string, req shared.UpdateContextRequest) (*sh
request.Header.Set("Content-Type", "application/json")
- resp, err := http.DefaultClient.Do(request)
+ // use the slow client since we may be uploading relatively large files
+ resp, err := authenticatedSlowClient.Do(request)
if err != nil {
return nil, fmt.Errorf("error sending request: %v", err)
}
@@ -565,7 +599,7 @@ func (a *Api) DeleteContext(planId string, req shared.DeleteContextRequest) (*sh
}
request.Header.Set("Content-Type", "application/json")
- resp, err := http.DefaultClient.Do(request)
+ resp, err := authenticatedFastClient.Do(request)
if err != nil {
return nil, fmt.Errorf("error sending request: %v", err)
}
@@ -588,7 +622,7 @@ func (a *Api) DeleteContext(planId string, req shared.DeleteContextRequest) (*sh
func (a *Api) ListContext(planId string) ([]*shared.Context, error) {
serverUrl := fmt.Sprintf("%s/plans/%s/context", apiHost, planId)
- resp, err := http.Get(serverUrl)
+ resp, err := authenticatedFastClient.Get(serverUrl)
if err != nil {
return nil, fmt.Errorf("error sending request: %v", err)
}
@@ -611,7 +645,7 @@ func (a *Api) ListContext(planId string) ([]*shared.Context, error) {
func (a *Api) ListConvo(planId string) ([]*shared.ConvoMessage, error) {
serverUrl := fmt.Sprintf("%s/plans/%s/convo", apiHost, planId)
- resp, err := http.Get(serverUrl)
+ resp, err := authenticatedFastClient.Get(serverUrl)
if err != nil {
return nil, fmt.Errorf("error sending request: %v", err)
}
@@ -634,7 +668,7 @@ func (a *Api) ListConvo(planId string) ([]*shared.ConvoMessage, error) {
func (a *Api) ListLogs(planId string) (*shared.LogResponse, error) {
serverUrl := fmt.Sprintf("%s/plans/%s/logs", apiHost, planId)
- resp, err := http.Get(serverUrl)
+ resp, err := authenticatedFastClient.Get(serverUrl)
if err != nil {
return nil, fmt.Errorf("error sending request: %v", err)
}
@@ -668,7 +702,7 @@ func (a *Api) RewindPlan(planId string, req shared.RewindPlanRequest) (*shared.R
}
request.Header.Set("Content-Type", "application/json")
- resp, err := http.DefaultClient.Do(request)
+ resp, err := authenticatedFastClient.Do(request)
if err != nil {
return nil, fmt.Errorf("error sending request: %v", err)
}
diff --git a/cli/api/stream.go b/cli/api/stream.go
index 34fc0342..92fd25dd 100644
--- a/cli/api/stream.go
+++ b/cli/api/stream.go
@@ -6,11 +6,12 @@ import (
"context"
"io"
"log"
+ "plandex/types"
"github.com/plandex/plandex/shared"
)
-func connectPlanRespStream(body io.ReadCloser, onStream OnStreamPlan) {
+func connectPlanRespStream(body io.ReadCloser, onStream types.OnStreamPlan) {
streamState := shared.NewPlanStreamState()
reader := bufio.NewReader(body)
@@ -20,7 +21,7 @@ func connectPlanRespStream(body io.ReadCloser, onStream OnStreamPlan) {
if err != nil {
log.Println("Error reading line:", err)
streamState.Event(context.Background(), shared.EVENT_ERROR)
- onStream(OnStreamPlanParams{Content: "", State: streamState, Err: err})
+ onStream(types.OnStreamPlanParams{Content: "", State: streamState, Err: err})
body.Close()
return
}
@@ -38,7 +39,7 @@ func connectPlanRespStream(body io.ReadCloser, onStream OnStreamPlan) {
if err != nil {
log.Printf("Error triggering state change %s: %s\n", evt, err)
}
- onStream(OnStreamPlanParams{Content: "", State: streamState, Err: err})
+ onStream(types.OnStreamPlanParams{Content: "", State: streamState, Err: err})
body.Close()
return
}
@@ -51,12 +52,12 @@ func connectPlanRespStream(body io.ReadCloser, onStream OnStreamPlan) {
if err != nil {
log.Println("Error setting state:", err)
- onStream(OnStreamPlanParams{Content: "", State: streamState, Err: err})
+ onStream(types.OnStreamPlanParams{Content: "", State: streamState, Err: err})
body.Close()
return
}
- onStream(OnStreamPlanParams{Content: s, State: streamState, Err: nil})
+ onStream(types.OnStreamPlanParams{Content: s, State: streamState, Err: nil})
}
}()
}
diff --git a/cli/auth/auth.go b/cli/auth/auth.go
new file mode 100644
index 00000000..50d0c6de
--- /dev/null
+++ b/cli/auth/auth.go
@@ -0,0 +1,222 @@
+package auth
+
+import (
+ "encoding/base64"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "os"
+ "plandex/fs"
+ "plandex/term"
+ "plandex/types"
+
+ "github.com/plandex/plandex/shared"
+)
+
+var Current *types.ClientAuth
+var apiClient types.ApiClient
+
+func SetApiClient(client types.ApiClient) {
+ apiClient = client
+}
+
+func MustResolveAuth() {
+ if apiClient == nil {
+ panic(fmt.Errorf("error resolving auth: api client not set"))
+ }
+
+ // load HomeAuthPath file into ClientAuth struct
+ bytes, err := os.ReadFile(fs.HomeAuthPath)
+
+ if err != nil {
+ if os.IsNotExist(err) {
+ err = promptAuth()
+
+ if err != nil {
+ panic(fmt.Errorf("error resolving auth: %v", err))
+ }
+
+ return
+ } else {
+ panic(fmt.Errorf("error reading auth.json: %v", err))
+ }
+ }
+
+ var auth types.ClientAuth
+ err = json.Unmarshal(bytes, &auth)
+ if err != nil {
+ panic(fmt.Errorf("error unmarshalling auth.json: %v", err))
+ }
+
+ Current = &auth
+}
+
+func LoadAccounts() ([]*types.ClientAccount, error) {
+ bytes, err := os.ReadFile(fs.HomeAccountsPath)
+
+ if err != nil {
+ if os.IsNotExist(err) {
+ // no accounts
+ return []*types.ClientAccount{}, nil
+ } else {
+ return nil, fmt.Errorf("error reading accounts.json: %v", err)
+ }
+ }
+
+ var accounts []*types.ClientAccount
+ err = json.Unmarshal(bytes, &accounts)
+
+ if err != nil {
+ return nil, fmt.Errorf("error unmarshalling accounts.json: %v", err)
+ }
+
+ return accounts, nil
+}
+
+func StoreAccountIfNew(acct *types.ClientAccount) error {
+ accounts, err := LoadAccounts()
+
+ if err != nil {
+ return fmt.Errorf("error loading accounts: %v", err)
+ }
+
+ for _, account := range accounts {
+ if account.UserId == acct.UserId {
+ return nil
+ }
+ }
+
+ accounts = append(accounts, acct)
+
+ bytes, err := json.Marshal(accounts)
+
+ if err != nil {
+ return fmt.Errorf("error marshalling accounts: %v", err)
+ }
+
+ err = os.WriteFile(fs.HomeAccountsPath, bytes, os.ModePerm)
+
+ if err != nil {
+ return fmt.Errorf("error writing accounts: %v", err)
+ }
+
+ return nil
+}
+
+func SetAuthHeader(req *http.Request) error {
+ if Current == nil {
+ return fmt.Errorf("error setting auth header: auth not loaded")
+ }
+
+ authHeader := shared.AuthHeader{
+ Token: Current.Token,
+ OrgId: Current.OrgId,
+ }
+
+ bytes, err := json.Marshal(authHeader)
+
+ if err != nil {
+ return fmt.Errorf("error marshalling auth header: %v", err)
+ }
+
+ // base64 encode
+ token := base64.StdEncoding.EncodeToString(bytes)
+
+ req.Header.Set("Authorization", "Bearer "+token)
+
+ return nil
+}
+
+func writeCurrentAuth() error {
+ if Current == nil {
+ return fmt.Errorf("error writing auth: auth not loaded")
+ }
+
+ bytes, err := json.Marshal(Current)
+
+ if err != nil {
+ return fmt.Errorf("error marshalling auth: %v", err)
+ }
+
+ err = os.WriteFile(fs.HomeAuthPath, bytes, os.ModePerm)
+
+ if err != nil {
+ return fmt.Errorf("error writing auth: %v", err)
+ }
+
+ return nil
+}
+
+const (
+ AuthFreeTrialOption = "Start a free trial on Plandex Cloud"
+ AuthSignInOption = "Sign in to an existing account on Plandex Cloud or another host"
+ AuthCreateAccount = "Create a new account on Plandex Cloud or another host"
+)
+
+func promptAuth() error {
+ selected, err := term.SelectFromList("πŸ‘‹ Hey there! It looks like this is your first time using Plandex on this computer. What would you like to do?", []string{AuthFreeTrialOption, AuthSignInOption, AuthCreateAccount})
+
+ 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 AuthSignInOption:
+ // sign in
+ // TODO
+
+ case AuthCreateAccount:
+ // create account
+ // TODO
+ }
+
+ return nil
+}
+
+func startTrial() error {
+ term.StartSpinner("🌟 Starting trial...")
+
+ res, err := apiClient.StartTrial()
+
+ if err != nil {
+ term.StopSpinner()
+ return fmt.Errorf("error starting trial: %v", err)
+ }
+
+ term.StopSpinner()
+
+ err = StoreAccountIfNew(&types.ClientAccount{
+ UserId: res.UserId,
+ UserName: res.UserName,
+ Token: res.Token,
+ IsTrial: true,
+ })
+
+ if err != nil {
+ return fmt.Errorf("error storing trial account: %v", err)
+ }
+
+ Current = &types.ClientAuth{
+ UserId: res.UserId,
+ UserName: res.UserName,
+ OrgId: res.OrgId,
+ OrgName: res.OrgName,
+ Token: res.Token,
+ IsTrial: true,
+ }
+
+ err = writeCurrentAuth()
+
+ if err != nil {
+ return fmt.Errorf("error writing auth: %v", err)
+ }
+
+ return nil
+}
diff --git a/cli/cmd/new.go b/cli/cmd/new.go
index 50a75571..f6b2ba2f 100644
--- a/cli/cmd/new.go
+++ b/cli/cmd/new.go
@@ -5,6 +5,7 @@ import (
"os"
"plandex/api"
+ "plandex/auth"
"plandex/lib"
"plandex/term"
@@ -31,6 +32,7 @@ func init() {
}
func new(cmd *cobra.Command, args []string) {
+ auth.MustResolveAuth()
lib.MustResolveProject()
res, err := api.Client.CreatePlan(lib.CurrentProjectId, shared.CreatePlanRequest{Name: name})
diff --git a/cli/cmd/sign_in.go b/cli/cmd/sign_in.go
new file mode 100644
index 00000000..1d619dd0
--- /dev/null
+++ b/cli/cmd/sign_in.go
@@ -0,0 +1 @@
+package cmd
diff --git a/cli/fs/fs.go b/cli/fs/fs.go
new file mode 100644
index 00000000..c76efe67
--- /dev/null
+++ b/cli/fs/fs.go
@@ -0,0 +1,76 @@
+package fs
+
+import (
+ "os"
+ "path/filepath"
+)
+
+var Cwd string
+var PlandexDir string
+var ProjectRoot string
+var HomePlandexDir string
+var CacheDir string
+
+var HomeAuthPath string
+var HomeAccountsPath string
+
+func init() {
+ var err error
+ Cwd, err = os.Getwd()
+ if err != nil {
+ panic(err)
+ }
+
+ home, err := os.UserHomeDir()
+ if err != nil {
+ panic("Couldn't find home dir:" + err.Error())
+ }
+ HomePlandexDir = filepath.Join(home, ".plandex-home")
+ CacheDir = filepath.Join(HomePlandexDir, "cache")
+ HomeAuthPath = filepath.Join(HomePlandexDir, "auth.json")
+ HomeAccountsPath = filepath.Join(HomePlandexDir, "accounts.json")
+
+ err = os.MkdirAll(filepath.Join(CacheDir, "tiktoken"), os.ModePerm)
+ if err != nil {
+ panic(err)
+ }
+ err = os.Setenv("TIKTOKEN_CACHE_DIR", CacheDir)
+ if err != nil {
+ panic(err)
+ }
+
+ PlandexDir, ProjectRoot = findPlandex()
+}
+
+func FindOrCreatePlandex() (string, bool, error) {
+ PlandexDir, ProjectRoot = findPlandex()
+
+ if PlandexDir != "" && ProjectRoot != "" {
+ return PlandexDir, false, nil
+ }
+
+ // Determine the directory path
+ dir := filepath.Join(Cwd, ".plandex")
+
+ err := os.Mkdir(dir, os.ModePerm)
+ if err != nil {
+ return "", false, err
+ }
+ PlandexDir = dir
+ ProjectRoot = Cwd
+
+ return dir, true, nil
+}
+
+func findPlandex() (string, string) {
+ searchPath := Cwd
+ for searchPath != "/" {
+ dir := filepath.Join(searchPath, ".plandex")
+ if _, err := os.Stat(dir); !os.IsNotExist(err) {
+ return dir, searchPath
+ }
+ searchPath = filepath.Dir(searchPath)
+ }
+
+ return "", ""
+}
diff --git a/cli/go.mod b/cli/go.mod
index 4ee3b11f..57e977f4 100644
--- a/cli/go.mod
+++ b/cli/go.mod
@@ -5,7 +5,6 @@ go 1.21.3
require (
github.com/atotto/clipboard v0.1.4
github.com/charmbracelet/lipgloss v0.9.1
- github.com/davecgh/go-spew v1.1.1
github.com/fatih/color v1.16.0
github.com/looplab/fsm v1.0.1
github.com/muesli/reflow v0.3.0
diff --git a/cli/lib/apply.go b/cli/lib/apply.go
index d9b07685..b7e985ca 100644
--- a/cli/lib/apply.go
+++ b/cli/lib/apply.go
@@ -7,6 +7,7 @@ import (
"os"
"path/filepath"
"plandex/api"
+ "plandex/fs"
"plandex/term"
"plandex/types"
@@ -52,7 +53,7 @@ func ApplyPlanWithOutput(planId string, autoConfirm bool) error {
}
// Compute destination path
- dstPath := filepath.Join(ProjectRoot, path)
+ dstPath := filepath.Join(fs.ProjectRoot, path)
// Check if the file has been removed
_, err := os.Stat(dstPath)
@@ -286,7 +287,7 @@ func ApplyPlanWithOutput(planId string, autoConfirm bool) error {
for path, content := range toApply {
// Compute destination path
- dstPath := filepath.Join(ProjectRoot, path)
+ dstPath := filepath.Join(fs.ProjectRoot, path)
// Create the directory if it doesn't exist
err := os.MkdirAll(filepath.Dir(dstPath), 0755)
if err != nil {
@@ -311,7 +312,7 @@ func ApplyPlanWithOutput(planId string, autoConfirm bool) error {
if isRepo {
// Commit the changes
- err = GitAddAndCommit(ProjectRoot, color.New(color.BgBlue, color.FgHiWhite, color.Bold).Sprintln(" πŸ€– Plandex ")+currentPlanState.PendingChangesSummary(), true)
+ err = GitAddAndCommit(fs.ProjectRoot, color.New(color.BgBlue, color.FgHiWhite, color.Bold).Sprintln(" πŸ€– Plandex ")+currentPlanState.PendingChangesSummary(), true)
if err != nil {
aborted = true
return fmt.Errorf("failed to commit changes: %w", err)
diff --git a/cli/lib/context_load.go b/cli/lib/context_load.go
index 37177c2e..eec7a791 100644
--- a/cli/lib/context_load.go
+++ b/cli/lib/context_load.go
@@ -10,20 +10,16 @@ import (
"plandex/types"
"plandex/url"
"strings"
- "time"
- "github.com/briandowns/spinner"
"github.com/plandex/plandex/shared"
)
func MustLoadContext(resources []string, params *types.LoadContextParams) {
- s := spinner.New(spinner.CharSets[33], 100*time.Millisecond)
- s.Prefix = "πŸ“₯ Loading context... "
- s.Start()
+
+ term.StartSpinner("πŸ“₯ Loading context...")
onErr := func(err error) {
- s.Stop()
- term.ClearCurrentLine()
+ term.StopSpinner()
fmt.Fprintf(os.Stderr, "Failed to load context: %v\n", err)
os.Exit(1)
}
@@ -168,8 +164,7 @@ func MustLoadContext(resources []string, params *types.LoadContextParams) {
}
if len(loadContextReq) == 0 {
- s.Stop()
- term.ClearCurrentLine()
+ term.StopSpinner()
fmt.Println("πŸ€·β€β™‚οΈ No context loaded")
os.Exit(0)
}
@@ -180,8 +175,7 @@ func MustLoadContext(resources []string, params *types.LoadContextParams) {
onErr(fmt.Errorf("failed to load context: %v", err))
}
- s.Stop()
- term.ClearCurrentLine()
+ term.StopSpinner()
if res.MaxTokensExceeded {
overage := res.TotalTokens - shared.MaxContextTokens
diff --git a/cli/lib/context_paths.go b/cli/lib/context_paths.go
new file mode 100644
index 00000000..c8f4f81c
--- /dev/null
+++ b/cli/lib/context_paths.go
@@ -0,0 +1,77 @@
+package lib
+
+import (
+ "fmt"
+ "os"
+ "path/filepath"
+ "plandex/types"
+ "sync"
+)
+
+func ParseInputPaths(fileOrDirPaths []string, params *types.LoadContextParams) ([]string, error) {
+ var wg sync.WaitGroup
+ var mu sync.Mutex
+ var firstErr error
+ resPaths := []string{}
+
+ for _, path := range fileOrDirPaths {
+ wg.Add(1)
+ go func(p string) {
+ defer wg.Done()
+
+ err := filepath.Walk(p, func(path string, info os.FileInfo, err error) error {
+ if err != nil {
+ return err
+ }
+
+ mu.Lock()
+ defer mu.Unlock()
+ if firstErr != nil {
+ return firstErr // If an error was encountered, stop walking
+ }
+
+ if info.IsDir() {
+ if info.Name() == ".git" || info.Name() == ".plandex" {
+ return filepath.SkipDir
+ }
+
+ if !(params.Recursive || params.NamesOnly) {
+ return fmt.Errorf("cannot process directory %s: --recursive or --tree flag not set", path)
+ }
+
+ // calculate directory depth from base
+ // depth := strings.Count(path[len(p):], string(filepath.Separator))
+ // if params.MaxDepth != -1 && depth > params.MaxDepth {
+ // return filepath.SkipDir
+ // }
+
+ if params.NamesOnly {
+ // add directory name to results
+ resPaths = append(resPaths, path)
+ }
+ } else {
+ // add file path to results
+ resPaths = append(resPaths, path)
+ }
+
+ return nil
+ })
+
+ if err != nil {
+ mu.Lock()
+ if firstErr == nil {
+ firstErr = err
+ }
+ mu.Unlock()
+ }
+ }(path)
+ }
+
+ wg.Wait()
+
+ if firstErr != nil {
+ return nil, firstErr
+ }
+
+ return resPaths, nil
+}
diff --git a/cli/lib/context_update.go b/cli/lib/context_update.go
index d8a4ba04..7ded206a 100644
--- a/cli/lib/context_update.go
+++ b/cli/lib/context_update.go
@@ -12,7 +12,6 @@ import (
"strconv"
"strings"
"sync"
- "time"
"github.com/fatih/color"
"github.com/olekukonko/tablewriter"
@@ -20,28 +19,15 @@ import (
)
func MustCheckOutdatedContextWithOutput() {
- s := term.Spinner
- start := time.Now()
- s.Prefix = "πŸ”¬ Checking context... "
- s.Start()
-
- stopSpinner := func() {
- s.Stop()
- term.ClearCurrentLine()
- }
+ term.StartSpinner("πŸ”¬ Checking context...")
outdatedRes, err := CheckOutdatedContext()
if err != nil {
- stopSpinner()
+ term.StopSpinner()
panic(fmt.Errorf("failed to check outdated context: %s", err))
}
- elapsed := time.Since(start)
- if elapsed < 700*time.Millisecond {
- time.Sleep(700*time.Millisecond - elapsed)
- }
-
- stopSpinner()
+ term.StopSpinner()
if len(outdatedRes.UpdatedContexts) == 0 {
fmt.Println("βœ… Context is up to date")
@@ -114,30 +100,17 @@ func MustCheckOutdatedContextWithOutput() {
}
func MustUpdateContextWithOuput() {
- timeStart := time.Now()
-
- s := term.Spinner
- s.Prefix = "πŸ”„ Updating context... "
- s.Start()
-
- stopFn := func() {
- elapsed := time.Since(timeStart)
- if elapsed < 700*time.Millisecond {
- time.Sleep(700*time.Millisecond - elapsed)
- }
- s.Stop()
- term.ClearCurrentLine()
- }
+ term.StartSpinner("πŸ”„ Updating context...")
updateRes, err := UpdateContext()
if err != nil {
- stopFn()
+ term.StopSpinner()
fmt.Fprintln(os.Stderr, "Error updating context:", err)
os.Exit(1)
}
- stopFn()
+ term.StopSpinner()
fmt.Println("βœ… " + updateRes.Msg)
diff --git a/cli/lib/current.go b/cli/lib/current.go
new file mode 100644
index 00000000..437088af
--- /dev/null
+++ b/cli/lib/current.go
@@ -0,0 +1,147 @@
+package lib
+
+import (
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+ "plandex/api"
+ "plandex/fs"
+ "plandex/types"
+
+ "github.com/plandex/plandex/shared"
+)
+
+var CurrentProjectId string
+var CurrentPlanId string
+var HomeCurrentProjectDir string
+var HomeCurrentPlanPath string
+
+func MustResolveProject() {
+ if fs.PlandexDir == "" {
+ _, _, err := fs.FindOrCreatePlandex()
+ if err != nil {
+ panic(fmt.Errorf("error finding or creating plandex: %v", err))
+ }
+ }
+
+ if fs.PlandexDir == "" || fs.ProjectRoot == "" {
+ panic(fmt.Errorf("could not find or create plandex directory"))
+ }
+
+ // check if project.json exists in PlandexDir
+ path := filepath.Join(fs.PlandexDir, "project.json")
+ _, err := os.Stat(path)
+
+ if os.IsNotExist(err) {
+ mustInitProject()
+ } else if err != nil {
+ panic(fmt.Errorf("error checking if project.json exists: %v", err))
+ }
+
+ // read project.json
+ bytes, err := os.ReadFile(path)
+
+ if err != nil {
+ panic(fmt.Errorf("error reading project.json: %v", err))
+ }
+
+ var settings types.ProjectSettings
+ err = json.Unmarshal(bytes, &settings)
+
+ if err != nil {
+ panic(fmt.Errorf("error unmarshalling project.json: %v", err))
+ }
+
+ CurrentProjectId = settings.Id
+
+ HomeCurrentProjectDir = filepath.Join(fs.HomePlandexDir, CurrentProjectId)
+ HomeCurrentPlanPath = filepath.Join(HomeCurrentProjectDir, "current_plan.json")
+
+ err = os.MkdirAll(HomeCurrentProjectDir, os.ModePerm)
+
+ if err != nil {
+ panic(fmt.Errorf("error creating project dir: %v", err))
+ }
+
+ MustLoadCurrentPlan()
+}
+
+func MustLoadCurrentPlan() {
+ if CurrentProjectId == "" {
+ panic("No current project")
+ }
+
+ // Check if the file exists
+ _, err := os.Stat(HomeCurrentPlanPath)
+
+ if os.IsNotExist(err) {
+ return
+ } else if err != nil {
+ panic(fmt.Errorf("error checking if current_plan.json exists: %v", err))
+ }
+
+ // Read the contents of the file
+ fileBytes, err := os.ReadFile(HomeCurrentPlanPath)
+ if err != nil {
+ panic(fmt.Errorf("error reading current_plan.json: %v", err))
+ }
+
+ // Unmarshal the JSON data into the shared.PlanSettings type
+ var planSettings types.PlanSettings
+ err = json.Unmarshal(fileBytes, &planSettings)
+ if err != nil {
+ panic(fmt.Errorf("error unmarshalling current_plan.json: %v", err))
+ }
+
+ CurrentPlanId = planSettings.Id
+}
+
+func mustInitProject() {
+ res, err := api.Client.CreateProject(shared.CreateProjectRequest{Name: filepath.Base(fs.ProjectRoot)})
+
+ if err != nil {
+ panic(fmt.Errorf("error creating project: %v", err))
+ }
+
+ CurrentProjectId = res.Id
+
+ // write project.json
+ path := filepath.Join(fs.PlandexDir, "project.json")
+ bytes, err := json.Marshal(types.ProjectSettings{
+ Id: CurrentProjectId,
+ })
+
+ if err != nil {
+ panic(fmt.Errorf("error marshalling project settings: %v", err))
+ }
+
+ err = os.WriteFile(path, bytes, os.ModePerm)
+
+ if err != nil {
+ panic(fmt.Errorf("error writing project.json: %v", err))
+ }
+
+ // write current_plan.json to PlandexHomeDir/[projectId]/current_plan.json
+ dir := filepath.Join(fs.HomePlandexDir, CurrentProjectId)
+ err = os.MkdirAll(dir, os.ModePerm)
+
+ if err != nil {
+ panic(fmt.Errorf("error creating project dir: %v", err))
+ }
+
+ path = filepath.Join(dir, "current_plan.json")
+ bytes, err = json.Marshal(types.PlanSettings{
+ Id: "",
+ })
+
+ if err != nil {
+ panic(fmt.Errorf("error marshalling plan settings: %v", err))
+ }
+
+ err = os.WriteFile(path, bytes, os.ModePerm)
+
+ if err != nil {
+ panic(fmt.Errorf("error writing current_plan.json: %v", err))
+ }
+}
diff --git a/cli/lib/fs.go b/cli/lib/fs.go
deleted file mode 100644
index ce7cf8c7..00000000
--- a/cli/lib/fs.go
+++ /dev/null
@@ -1,285 +0,0 @@
-package lib
-
-import (
- "encoding/json"
- "fmt"
- "os"
- "path/filepath"
- "plandex/api"
- "plandex/types"
- "sync"
-
- "github.com/plandex/plandex/shared"
-)
-
-var Cwd string
-var PlandexDir string
-var ProjectRoot string
-var HomePlandexDir string
-var CacheDir string
-
-var CurrentProjectId string
-var CurrentOrgId string
-var CurrentUserId string
-var CurrentPlanId string
-
-var HomeCurrentProjectDir string
-var HomeCurrentPlanPath string
-
-func init() {
- var err error
- Cwd, err = os.Getwd()
- if err != nil {
- panic(err)
- }
-
- home, err := os.UserHomeDir()
- if err != nil {
- panic(err)
- }
- HomePlandexDir = filepath.Join(home, ".plandex-home")
- CacheDir = filepath.Join(HomePlandexDir, "cache")
- err = os.MkdirAll(filepath.Join(CacheDir, "tiktoken"), os.ModePerm)
- if err != nil {
- panic(err)
- }
- err = os.Setenv("TIKTOKEN_CACHE_DIR", CacheDir)
- if err != nil {
- panic(err)
- }
-
- PlandexDir, ProjectRoot = findPlandex()
-}
-
-func MustResolveProject() {
- if PlandexDir == "" {
- _, _, err := findOrCreatePlandex()
- if err != nil {
- panic(fmt.Errorf("error finding or creating plandex: %v", err))
- }
- }
-
- if PlandexDir == "" || ProjectRoot == "" {
- panic(fmt.Errorf("could not find or create plandex directory"))
- }
-
- // check if project.json exists in PlandexDir
- path := filepath.Join(PlandexDir, "project.json")
- _, err := os.Stat(path)
-
- if os.IsNotExist(err) {
- mustInitProject()
- } else if err != nil {
- panic(fmt.Errorf("error checking if project.json exists: %v", err))
- }
-
- // read project.json
- bytes, err := os.ReadFile(path)
-
- if err != nil {
- panic(fmt.Errorf("error reading project.json: %v", err))
- }
-
- var settings types.ProjectSettings
- err = json.Unmarshal(bytes, &settings)
-
- if err != nil {
- panic(fmt.Errorf("error unmarshalling project.json: %v", err))
- }
-
- CurrentProjectId = settings.Id
- CurrentOrgId = settings.OrgId
-
- HomeCurrentProjectDir = filepath.Join(HomePlandexDir, CurrentProjectId)
- HomeCurrentPlanPath = filepath.Join(HomeCurrentProjectDir, "current_plan.json")
-
- err = os.MkdirAll(HomeCurrentProjectDir, os.ModePerm)
-
- if err != nil {
- panic(fmt.Errorf("error creating project dir: %v", err))
- }
-
- MustLoadCurrentPlan()
-}
-
-func MustLoadCurrentPlan() {
- if CurrentProjectId == "" {
- panic("No current project")
- }
-
- // Check if the file exists
- _, err := os.Stat(HomeCurrentPlanPath)
-
- if os.IsNotExist(err) {
- return
- } else if err != nil {
- panic(fmt.Errorf("error checking if current_plan.json exists: %v", err))
- }
-
- // Read the contents of the file
- fileBytes, err := os.ReadFile(HomeCurrentPlanPath)
- if err != nil {
- panic(fmt.Errorf("error reading current_plan.json: %v", err))
- }
-
- // Unmarshal the JSON data into the shared.PlanSettings type
- var planSettings types.PlanSettings
- err = json.Unmarshal(fileBytes, &planSettings)
- if err != nil {
- panic(fmt.Errorf("error unmarshalling current_plan.json: %v", err))
- }
-
- CurrentPlanId = planSettings.Id
-}
-
-func ParseInputPaths(fileOrDirPaths []string, params *types.LoadContextParams) ([]string, error) {
- var wg sync.WaitGroup
- var mu sync.Mutex
- var firstErr error
- resPaths := []string{}
-
- for _, path := range fileOrDirPaths {
- wg.Add(1)
- go func(p string) {
- defer wg.Done()
-
- err := filepath.Walk(p, func(path string, info os.FileInfo, err error) error {
- if err != nil {
- return err
- }
-
- mu.Lock()
- defer mu.Unlock()
- if firstErr != nil {
- return firstErr // If an error was encountered, stop walking
- }
-
- if info.IsDir() {
- if info.Name() == ".git" || info.Name() == ".plandex" {
- return filepath.SkipDir
- }
-
- if !(params.Recursive || params.NamesOnly) {
- return fmt.Errorf("cannot process directory %s: --recursive or --tree flag not set", path)
- }
-
- // calculate directory depth from base
- // depth := strings.Count(path[len(p):], string(filepath.Separator))
- // if params.MaxDepth != -1 && depth > params.MaxDepth {
- // return filepath.SkipDir
- // }
-
- if params.NamesOnly {
- // add directory name to results
- resPaths = append(resPaths, path)
- }
- } else {
- // add file path to results
- resPaths = append(resPaths, path)
- }
-
- return nil
- })
-
- if err != nil {
- mu.Lock()
- if firstErr == nil {
- firstErr = err
- }
- mu.Unlock()
- }
- }(path)
- }
-
- wg.Wait()
-
- if firstErr != nil {
- return nil, firstErr
- }
-
- return resPaths, nil
-}
-
-func mustInitProject() {
- res, err := api.Client.CreateProject(shared.CreateProjectRequest{Name: filepath.Base(ProjectRoot)})
-
- if err != nil {
- panic(fmt.Errorf("error creating project: %v", err))
- }
-
- CurrentProjectId = res.Id
- CurrentOrgId = res.OrgId
-
- // write project.json
- path := filepath.Join(PlandexDir, "project.json")
- bytes, err := json.Marshal(types.ProjectSettings{
- Id: CurrentProjectId,
- OrgId: CurrentOrgId,
- })
-
- if err != nil {
- panic(fmt.Errorf("error marshalling project settings: %v", err))
- }
-
- err = os.WriteFile(path, bytes, os.ModePerm)
-
- if err != nil {
- panic(fmt.Errorf("error writing project.json: %v", err))
- }
-
- // write current_plan.json to PlandexHomeDir/[projectId]/current_plan.json
- dir := filepath.Join(HomePlandexDir, CurrentProjectId)
- err = os.MkdirAll(dir, os.ModePerm)
-
- if err != nil {
- panic(fmt.Errorf("error creating project dir: %v", err))
- }
-
- path = filepath.Join(dir, "current_plan.json")
- bytes, err = json.Marshal(types.PlanSettings{
- Id: "",
- })
-
- if err != nil {
- panic(fmt.Errorf("error marshalling plan settings: %v", err))
- }
-
- err = os.WriteFile(path, bytes, os.ModePerm)
-
- if err != nil {
- panic(fmt.Errorf("error writing current_plan.json: %v", err))
- }
-}
-
-func findOrCreatePlandex() (string, bool, error) {
- PlandexDir, ProjectRoot = findPlandex()
-
- if PlandexDir != "" && ProjectRoot != "" {
- return PlandexDir, false, nil
- }
-
- // Determine the directory path
- dir := filepath.Join(Cwd, ".plandex")
-
- err := os.Mkdir(dir, os.ModePerm)
- if err != nil {
- return "", false, err
- }
- PlandexDir = dir
- ProjectRoot = Cwd
-
- return dir, true, nil
-}
-
-func findPlandex() (string, string) {
- searchPath := Cwd
- for searchPath != "/" {
- dir := filepath.Join(searchPath, ".plandex")
- if _, err := os.Stat(dir); !os.IsNotExist(err) {
- return dir, searchPath
- }
- searchPath = filepath.Dir(searchPath)
- }
-
- return "", ""
-}
diff --git a/cli/lib/plans.go b/cli/lib/plans.go
index 0ea2eed7..736eab4a 100644
--- a/cli/lib/plans.go
+++ b/cli/lib/plans.go
@@ -3,15 +3,16 @@ package lib
import (
"fmt"
"os"
+ "plandex/fs"
)
func SetCurrentPlan(id string) error {
- if HomePlandexDir == "" {
+ if fs.HomePlandexDir == "" {
return fmt.Errorf("HomePlandexDir not set")
}
if CurrentProjectId == "" || HomeCurrentPlanPath == "" {
- return fmt.Errorf("No current project")
+ return fmt.Errorf("no current project")
}
err := os.WriteFile(HomeCurrentPlanPath, []byte(fmt.Sprintf(`{"id": "%s"}`, id)), 0644)
@@ -23,12 +24,12 @@ func SetCurrentPlan(id string) error {
}
func ClearCurrentPlan() error {
- if HomePlandexDir == "" {
+ if fs.HomePlandexDir == "" {
return fmt.Errorf("HomePlandexDir not set")
}
if CurrentProjectId == "" || HomeCurrentPlanPath == "" {
- return fmt.Errorf("No current project")
+ return fmt.Errorf("no current project")
}
err := os.Remove(HomeCurrentPlanPath)
diff --git a/cli/lib/proposal.go.old b/cli/lib/proposal.go.old
deleted file mode 100644
index be98cf82..00000000
--- a/cli/lib/proposal.go.old
+++ /dev/null
@@ -1,615 +0,0 @@
-// package lib
-
-// import (
-// "time"
-// )
-
-// const replyStreamThrottle = 70 * time.Millisecond
-
-// type key struct {
-// value rune
-// }
-
-// func Propose(prompt string) error {
-// // var err error
-
-// // planState, err := GetPlanState()
-// // if err != nil {
-// // return fmt.Errorf("failed to get plan state: %s", err)
-// // }
-
-// // s := spinner.New(spinner.CharSets[33], 100*time.Millisecond)
-// // if planState.ContextUpdatableTokens > 0 {
-// // shouldContinue, err := checkOutdatedContext(s)
-// // if err != nil {
-// // fmt.Fprintf(os.Stderr, "Failed to check outdated context: %v\n", err)
-// // return err
-// // }
-
-// // if !shouldContinue {
-// // return nil
-// // }
-// // }
-
-// // start := time.Now()
-// // s.Prefix = "πŸ’¬ Sending prompt... "
-// // s.Start()
-
-// // if CurrentPlanIsDraft() {
-// // fileNameResp, err := Api.FileName(prompt)
-// // if err != nil {
-// // fmt.Fprintln(os.Stderr, "\nError getting file name for prompt:", err)
-// // return err
-// // }
-// // err = RenameCurrentDraftPlan(planState, format.GetFileNameWithoutExt(fileNameResp.FileName))
-// // if err != nil {
-// // fmt.Fprintln(os.Stderr, "\nError renaming draft plan:", err)
-// // return err
-// // }
-// // }
-
-// // // fmt.Println("Checked current plan is draft")
-
-// // timestamp := shared.StringTs()
-// // reply := ""
-// // done := make(chan struct{})
-// // closedDone := false
-
-// // termState := ""
-
-// // replyUpdateTimer := time.NewTimer(150 * time.Millisecond)
-// // defer replyUpdateTimer.Stop()
-
-// // var proposalId string
-// // var replyStarted bool
-// // var terminalHasPendingUpdate bool
-// // var desc *shared.PlanDescription
-// // var state *fsm.FSM
-// // var streamFinished bool
-// // var filesFinished bool
-// // var lastReplyTokenAdded time.Time
-// // finishedByPath := make(map[string]bool)
-// // var buildMu sync.Mutex
-
-// // numStreamedTokensByPath := make(map[string]int)
-
-// // replyTokenCounter := shared.NewReplyInfo()
-
-// // var parentProposalId string
-// // var rootId string
-
-// // parentProposalId = planState.ProposalId
-// // rootId = planState.RootId
-
-// // if rootId != "" {
-// // err = saveLatestConvoSummary(rootId)
-// // if err != nil {
-// // return fmt.Errorf("failed to save latest convo summary: %s", err)
-// // }
-// // }
-
-// // // fmt.Println("Initialized locals")
-
-// // promptNumTokens, err := shared.GetNumTokens(prompt)
-// // if err != nil {
-// // return fmt.Errorf("failed to get number of tokens in prompt: %s", err)
-// // }
-
-// // // fmt.Println("Got prompt num tokens")
-
-// // err = appendConversation(types.AppendConversationParams{
-// // Timestamp: timestamp,
-// // PlanState: planState,
-// // PromptParams: &types.AppendConversationPromptParams{
-// // Prompt: prompt,
-// // PromptTokens: promptNumTokens,
-// // },
-// // })
-
-// // // fmt.Println("Appended conversation")
-
-// // if err != nil {
-// // return fmt.Errorf("failed to append prompt to conversation: %s", err)
-// // }
-
-// // printReply := func() {
-// // term.ClearScreen()
-// // term.MoveCursorToTopLeft()
-// // mdFull, _ := term.GetMarkdown(reply)
-// // fmt.Println(mdFull)
-// // fmt.Println(displayHotkeys())
-// // termState = mdFull
-// // }
-
-// // go func() {
-// // for range replyUpdateTimer.C {
-// // if replyStarted && terminalHasPendingUpdate {
-// // printReply()
-// // terminalHasPendingUpdate = false
-// // }
-// // replyUpdateTimer.Reset(100 * time.Millisecond)
-// // }
-// // }()
-
-// // // fmt.Println("Starting proposal")
-
-// // keyChan := make(chan *key, 1)
-// // ctx, cancelKeywatch := context.WithCancel(context.Background())
-// // errChn := make(chan error, 1)
-
-// // endReply := func() {
-// // replyUpdateTimer.Stop()
-// // printReply()
-// // term.BackToMain()
-// // fmt.Print(termState)
-// // }
-
-// // appendConvoReply := func() error {
-// // var totalTokens int
-// // _, _, _, totalTokens = replyTokenCounter.FinishAndRead()
-
-// // return appendConversation(types.AppendConversationParams{
-// // Timestamp: timestamp,
-// // PlanState: planState,
-// // ReplyParams: &types.AppendConversationReplyParams{
-// // ResponseTimestamp: desc.ResponseTimestamp,
-// // Reply: reply,
-// // ReplyTokens: totalTokens,
-// // },
-// // })
-// // }
-
-// // writeFileProgress := func() {
-// // files := desc.Files
-
-// // if len(files) == 0 {
-// // return
-// // }
-
-// // // Clear previous lines
-// // numLines := len(files) + 4
-
-// // term.MoveUpLines(numLines)
-
-// // for _, filePath := range files {
-// // numStreamedTokens := numStreamedTokensByPath[filePath]
-
-// // fmtStr := " πŸ“„ %s | %d πŸͺ™"
-// // fmtArgs := []interface{}{filePath, numStreamedTokens}
-
-// // _, finished := finishedByPath[filePath]
-
-// // if finished {
-// // fmtStr += " | done βœ…"
-// // }
-
-// // term.ClearCurrentLine()
-
-// // fmt.Printf(fmtStr+"\n", fmtArgs...)
-// // }
-
-// // if !(filesFinished && streamFinished) {
-// // fmt.Println()
-// // fmt.Printf(displayHotkeys() + "\n")
-// // }
-// // }
-
-// // contextByFilePath := make(map[string]*shared.ModelContextPart)
-
-// // running := false
-// // queue := make(chan types.OnStreamPlanParams, 1)
-
-// // var apiReq *shared.PromptRequest
-
-// // var handleStream types.OnStreamPlan
-
-// // // fmt.Println("Starting handleStream")
-
-// // handleStream = func(params types.OnStreamPlanParams) {
-// // if running {
-// // queue <- params
-// // return
-// // }
-
-// // defer func() {
-// // if len(queue) > 0 {
-// // params := <-queue
-// // handleStream(params)
-// // } else {
-// // running = false
-// // }
-// // }()
-
-// // state = params.State
-// // err := params.Err
-// // content := params.Content
-
-// // onError := func(err error) {
-// // term.BackToMain()
-// // fmt.Fprintln(os.Stderr, "Error:", err)
-// // cancelKeywatch()
-// // if !closedDone {
-// // close(done)
-// // closedDone = true
-// // }
-// // }
-
-// // if err != nil {
-// // onError(err)
-// // return
-// // }
-
-// // if proposalId == "" {
-// // if content == "" {
-// // onError(fmt.Errorf("proposal id not sent in first chunk"))
-// // return
-// // } else {
-// // proposalId = content
-// // if rootId == "" {
-// // rootId = proposalId
-// // }
-
-// // // Save proposal id to [CurrentPlanRootDir]/plan.json
-// // planState.ProposalId = proposalId
-// // planState.RootId = rootId
-// // err = SetPlanState(planState, shared.StringTs())
-// // if err != nil {
-// // onError(fmt.Errorf("failed to update plan state: %s", err))
-// // return
-// // }
-// // return
-// // }
-// // } else if !replyStarted {
-// // elapsed := time.Since(start)
-// // if elapsed < 700*time.Millisecond {
-// // time.Sleep(700*time.Millisecond - elapsed)
-// // }
-
-// // s.Stop()
-// // term.ClearCurrentLine()
-// // term.AlternateScreen()
-
-// // replyStarted = true
-// // lastReplyTokenAdded = time.Now()
-// // }
-
-// // switch state.Current() {
-// // case shared.STATE_REPLYING:
-// // elapsed := time.Since(lastReplyTokenAdded)
-
-// // if elapsed < replyStreamThrottle {
-// // time.Sleep(replyStreamThrottle - elapsed)
-// // }
-
-// // reply += content
-// // replyTokenCounter.AddToken(content, true)
-// // terminalHasPendingUpdate = true
-// // lastReplyTokenAdded = time.Now()
-
-// // case shared.STATE_FINISHED:
-// // s.Stop()
-// // buildMu.Lock()
-// // defer buildMu.Unlock()
-// // streamFinished = true
-// // if filesFinished && !closedDone {
-// // close(done)
-// // closedDone = true
-// // writeFileProgress()
-// // fmt.Println()
-// // fmt.Println()
-// // }
-
-// // case shared.STATE_DESCRIBING:
-// // if content == shared.STREAM_DESCRIPTION_PHASE {
-// // return
-// // }
-
-// // describeStart := time.Now()
-
-// // bytes := []byte(content)
-
-// // err := json.Unmarshal(bytes, &desc)
-// // if err != nil {
-// // onError(fmt.Errorf("error parsing plan description: %v", err))
-// // return
-// // }
-
-// // if len(desc.Files) > 0 {
-// // s = spinner.New(spinner.CharSets[33], 100*time.Millisecond)
-// // s.Prefix = " "
-// // s.Start()
-// // }
-
-// // err = os.MkdirAll(DescriptionsSubdir, os.ModePerm)
-// // if err != nil {
-// // onError(fmt.Errorf("failed to create plan descriptions directory: %s", err))
-// // return
-// // }
-// // descriptionsPath := filepath.Join(DescriptionsSubdir, desc.ResponseTimestamp+".json")
-// // err = os.WriteFile(descriptionsPath, bytes, 0644)
-// // if err != nil {
-// // onError(fmt.Errorf("failed to write plan description to file: %s", err))
-// // return
-// // }
-
-// // // fmt.Println("appending convo reply")
-
-// // err = appendConvoReply()
-// // if err != nil {
-// // onError(fmt.Errorf("failed to append reply to conversation: %s", err))
-// // return
-// // }
-
-// // // fmt.Println("appended convo reply")
-
-// // // wait a bit if necessary to avoid jarring output of conversation as soon as stream finishes
-// // elapsed := time.Since(describeStart)
-// // if elapsed < 1500*time.Millisecond {
-// // time.Sleep(1500*time.Millisecond - elapsed)
-// // }
-
-// // // fmt.Println("waited elapsed")
-
-// // endReply()
-
-// // // fmt.Println("ended reply")
-// // s.Stop()
-
-// // if desc.MadePlan && (len(desc.Files) > 0) {
-// // fmt.Println(" " + color.New(color.BgGreen, color.FgHiWhite, color.Bold).Sprint(" πŸ— ") + color.New(color.BgGreen, color.FgHiWhite).Sprint("Building plan "))
-// // for _, filePath := range desc.Files {
-// // fmt.Printf(" πŸ“„ %s\n", filePath)
-// // }
-// // fmt.Println()
-// // fmt.Printf(displayHotkeys() + "\n")
-// // } else {
-// // filesFinished = true
-// // }
-
-// // case shared.STATE_BUILDING:
-// // if content == shared.STREAM_BUILD_PHASE {
-// // return
-
-// // }
-// // err := updateTokenCounts(content, numStreamedTokensByPath, finishedByPath)
-
-// // if err != nil {
-// // onError(err)
-// // return
-// // }
-
-// // writeFileProgress()
-
-// // case shared.STATE_WRITING:
-// // if content == shared.STREAM_WRITE_PHASE {
-// // // write phase started
-// // return
-// // }
-
-// // err := writePlanRes(content)
-
-// // if err != nil {
-// // onError(fmt.Errorf("failed to write plan file: %s", err))
-// // return
-// // }
-
-// // // fmt.Printf("Wrote %d / %d files", len(finishedByPath), len(files))
-// // if len(finishedByPath) == len(desc.Files) {
-// // buildMu.Lock()
-// // defer buildMu.Unlock()
-// // filesFinished = true
-
-// // err = GitCommitPlanUpdate(desc.CommitMsg)
-// // if err != nil {
-// // onError(fmt.Errorf("failed to commit root update: %s", err))
-// // return
-// // }
-
-// // if streamFinished && !closedDone {
-// // close(done)
-// // closedDone = true
-// // writeFileProgress()
-// // fmt.Println()
-// // fmt.Println()
-// // }
-// // }
-// // }
-
-// // }
-
-// // apiReq, err = Api.Propose(prompt, parentProposalId, rootId, handleStream)
-// // if err != nil {
-// // term.BackToMain()
-// // return fmt.Errorf("failed to send prompt to server: %s", err)
-// // }
-
-// // // fmt.Println("Sent prompt to server")
-
-// // for _, part := range apiReq.ModelContext {
-// // contextByFilePath[part.FilePath] = part
-// // }
-
-// // // fmt.Println("Got context")
-
-// // go func(ctx context.Context, errChn chan error) {
-// // for {
-// // select {
-// // case <-ctx.Done():
-// // return
-// // default:
-// // k, err := term.GetUserInput()
-// // if err != nil {
-// // errChn <- err
-// // return
-// // }
-// // keyChan <- &key{k}
-// // }
-// // }
-// // }(ctx, errChn)
-
-// // handleKey := func(k *key) error {
-// // return handleKeyPress(k.value, proposalId)
-// // }
-
-// // Loop:
-// // for {
-// // select {
-// // case k := <-keyChan:
-// // if err := handleKey(k); err != nil {
-// // cancelKeywatch()
-// // return err
-// // }
-// // case <-done: // Evidence of operation completion
-// // cancelKeywatch()
-// // break Loop
-// // case err := <-errChn: // Listening for errors
-// // cancelKeywatch()
-// // return err
-// // }
-// // }
-
-// // // fmt.Println("Started key loop")
-
-// // if desc != nil {
-// // if desc.MadePlan && len(desc.Files) > 0 {
-// // fmt.Println()
-// // for _, cmd := range []string{"apply", "diffs", "preview"} {
-// // term.ClearCurrentLine()
-// // term.PrintCmds(" ", cmd)
-// // }
-// // }
-
-// // term.ClearCurrentLine()
-// // term.PrintCustomCmd(" ", "tell", "t", "update the plan, give more info, or chat")
-
-// // term.ClearCurrentLine()
-// // term.PrintCmds(" ", "continue")
-
-// // term.ClearCurrentLine()
-// // term.PrintCmds(" ", "rewind")
-// // }
-
-// // // fmt.Println("Finished proposal")
-
-// // return nil
-// // }
-
-// // func Abort(proposalId string) error {
-// // err := Api.Abort(proposalId)
-// // return err
-// // }
-
- // func checkOutdatedContext(s *spinner.Spinner) (bool, error) {
- // start := time.Now()
- // s.Prefix = "πŸ”¬ Checking context... "
- // s.Start()
-
- // stopSpinner := func() {
- // s.Stop()
- // term.ClearCurrentLine()
- // }
-
- // outdatedRes, err := CheckOutdatedContext()
- // if err != nil {
- // stopSpinner()
- // return false, fmt.Errorf("failed to check outdated context: %s", err)
- // }
-
- // elapsed := time.Since(start)
- // if elapsed < 700*time.Millisecond {
- // time.Sleep(700*time.Millisecond - elapsed)
- // }
-
- // stopSpinner()
-
- // if len(outdatedRes.UpdatedContexts) == 0 {
- // fmt.Println("βœ… Context is up to date")
- // return true, nil
- // }
- // types := []string{}
- // if outdatedRes.NumFiles > 0 {
- // lbl := "file"
- // if outdatedRes.NumFiles > 1 {
- // lbl = "files"
- // }
- // lbl = strconv.Itoa(outdatedRes.NumFiles) + " " + lbl
- // types = append(types, lbl)
- // }
- // if outdatedRes.NumUrls > 0 {
- // lbl := "url"
- // if outdatedRes.NumUrls > 1 {
- // lbl = "urls"
- // }
- // lbl = strconv.Itoa(outdatedRes.NumUrls) + " " + lbl
- // types = append(types, lbl)
- // }
- // if outdatedRes.NumTrees > 0 {
- // lbl := "directory tree"
- // if outdatedRes.NumTrees > 1 {
- // lbl = "directory trees"
- // }
- // lbl = strconv.Itoa(outdatedRes.NumTrees) + " " + lbl
- // types = append(types, lbl)
- // }
-
- // var msg string
- // if len(types) <= 2 {
- // msg += strings.Join(types, " and ")
- // } else {
- // for i, add := range types {
- // if i == len(types)-1 {
- // msg += ", and " + add
- // } else {
- // msg += ", " + add
- // }
- // }
- // }
-
- // phrase := "have been"
- // if len(outdatedRes.UpdatedContexts) == 1 {
- // phrase = "has been"
- // }
- // color.New(color.FgHiCyan, color.Bold).Printf("%s in context %s modified πŸ‘‡\n\n", msg, phrase)
-
- // tableString := TableForContextUpdateRes(outdatedRes)
- // fmt.Println(tableString)
-
- // fmt.Println()
-
- // confirmed, canceled, err := term.ConfirmYesNoCancel("Update context now?")
-
- // if err != nil {
- // return false, fmt.Errorf("failed to get user input: %s", err)
- // }
-
- // if confirmed {
- // MustUpdateContextWithOuput()
- // }
-
- // shouldContinue := !canceled
-
- // return shouldContinue, nil
-
- return nil
-}
-
-// func handleAbortKey(proposalId string) error {
-// return Abort(proposalId)
-// }
-
-// func handleKeyPress(input rune, proposalId string) error {
-// switch input {
-// case 's':
-// return handleAbortKey(proposalId)
-// default:
-// return fmt.Errorf("invalid key pressed: %s", string(input))
-// }
-// }
-
-// func displayHotkeys() string {
-// divisionLine := term.GetDivisionLine()
-
-// return divisionLine + "\n" +
-// " \x1b[1m(s)\x1b[0m" + `top
-// ` + divisionLine
-// }
diff --git a/cli/lib/stream.go b/cli/lib/stream.go
index 7771b590..6331fcd9 100644
--- a/cli/lib/stream.go
+++ b/cli/lib/stream.go
@@ -3,14 +3,13 @@ package lib
import (
"encoding/json"
"log"
- "plandex/api"
streamtui "plandex/stream_tui"
"plandex/types"
"github.com/plandex/plandex/shared"
)
-var OnStreamPlan api.OnStreamPlan = func(params api.OnStreamPlanParams) {
+var OnStreamPlan types.OnStreamPlan = func(params types.OnStreamPlanParams) {
switch params.State.Current() {
case shared.STATE_REPLYING:
streamtui.Send(types.StreamTUIUpdate{
diff --git a/cli/main.go b/cli/main.go
index 28548233..4bfe9390 100644
--- a/cli/main.go
+++ b/cli/main.go
@@ -5,10 +5,14 @@ import (
"log"
"os"
"path/filepath"
+ "plandex/api"
+ "plandex/auth"
"plandex/cmd"
)
func init() {
+ auth.SetApiClient(api.Client)
+
// set up a file logger
// TODO: log rotation
home, err := os.UserHomeDir()
diff --git a/cli/term/spinner.go b/cli/term/spinner.go
new file mode 100644
index 00000000..77ee8c6a
--- /dev/null
+++ b/cli/term/spinner.go
@@ -0,0 +1,28 @@
+package term
+
+import (
+ "time"
+
+ "github.com/briandowns/spinner"
+)
+
+const minDuration = 700 * time.Millisecond
+
+var s = spinner.New(spinner.CharSets[33], 100*time.Millisecond)
+var startedAt time.Time
+
+func StartSpinner(msg string) {
+ startedAt = time.Now()
+ s.Prefix = msg + " "
+ s.Start()
+}
+
+func StopSpinner() {
+ elapsed := time.Since(startedAt)
+ if elapsed < minDuration {
+ time.Sleep(minDuration - elapsed)
+ }
+
+ s.Stop()
+ ClearCurrentLine()
+}
diff --git a/cli/term/term.go b/cli/term/term.go
index 67bc8ef7..431508bf 100644
--- a/cli/term/term.go
+++ b/cli/term/term.go
@@ -5,9 +5,7 @@ import (
"os"
"os/exec"
"strings"
- "time"
- "github.com/briandowns/spinner"
"github.com/eiannone/keyboard"
"github.com/fatih/color"
"golang.org/x/term"
@@ -33,8 +31,6 @@ var CmdDesc = map[string][2]string{
"update": {"u", "update outdated context"},
}
-var Spinner = spinner.New(spinner.CharSets[33], 100*time.Millisecond)
-
func PrintCmds(prefix string, cmds ...string) {
for _, cmd := range cmds {
config, ok := CmdDesc[cmd]
diff --git a/cli/api/types.go b/cli/types/api.go
similarity index 96%
rename from cli/api/types.go
rename to cli/types/api.go
index dc638218..ea811a76 100644
--- a/cli/api/types.go
+++ b/cli/types/api.go
@@ -1,4 +1,4 @@
-package api
+package types
import (
"github.com/looplab/fsm"
@@ -13,9 +13,8 @@ type OnStreamPlanParams struct {
type OnStreamPlan func(params OnStreamPlanParams)
-type Api struct{}
-
type ApiClient interface {
+ StartTrial() (*shared.StartTrialResponse, error)
CreateProject(req shared.CreateProjectRequest) (*shared.CreateProjectResponse, error)
ListProjects() ([]*shared.Project, error)
SetProjectPlan(projectId string, req shared.SetProjectPlanRequest) error
diff --git a/cli/types/types.go b/cli/types/types.go
index eb087805..3136dddf 100644
--- a/cli/types/types.go
+++ b/cli/types/types.go
@@ -2,6 +2,22 @@ package types
import "github.com/plandex/plandex/shared"
+type ClientAccount struct {
+ UserName string `json:"userName"`
+ UserId string `json:"userId"`
+ Token string `json:"token"`
+ IsTrial bool `json:"isTrial"`
+}
+
+type ClientAuth struct {
+ OrgId string `json:"orgId"`
+ OrgName string `json:"orgName"`
+ UserId string `json:"userId"`
+ UserName string `json:"userName"`
+ Token string `json:"token"`
+ IsTrial bool `json:"isTrial"`
+}
+
type LoadContextParams struct {
Note string
Recursive bool
@@ -30,8 +46,7 @@ type PlanSettings struct {
}
type ProjectSettings struct {
- Id string `json:"id"`
- OrgId string `json:"orgId"`
+ Id string `json:"id"`
}
type StreamTUIUpdate struct {
diff --git a/server/db/auth_helpers.go b/server/db/auth_helpers.go
new file mode 100644
index 00000000..87ae27ec
--- /dev/null
+++ b/server/db/auth_helpers.go
@@ -0,0 +1,25 @@
+package db
+
+import (
+ "crypto/sha256"
+ "database/sql"
+ "encoding/hex"
+ "fmt"
+
+ "github.com/google/uuid"
+)
+
+func GenAuthToken(userId string, tx *sql.Tx) (string, error) {
+ uid := uuid.New()
+ bytes := uid[:]
+ hashBytes := sha256.Sum256(bytes)
+ hash := hex.EncodeToString(hashBytes[:])
+
+ _, err := tx.Exec("INSERT INTO auth_tokens (user_id, token_hash) VALUES ($1, $2)", userId, hash)
+
+ if err != nil {
+ return "", fmt.Errorf("error creating auth token: %v", err)
+ }
+
+ return uid.String(), nil
+}
diff --git a/server/db/db.go b/server/db/db.go
index 5735d0ec..cfec0ad4 100644
--- a/server/db/db.go
+++ b/server/db/db.go
@@ -3,6 +3,7 @@ package db
import (
"errors"
"fmt"
+ "log"
"os"
"github.com/golang-migrate/migrate/v4"
@@ -47,24 +48,37 @@ func MigrationsUp() error {
return fmt.Errorf("error creating migration instance: %v", err)
}
- // Uncomment below to reset migration state after an error / dirty state
- // // Check if database is dirty
- // version, dirty, err := m.Version()
- // if err != nil {
- // return fmt.Errorf("error getting migration version: %v", err)
+ // Uncomment below to reset migration state to a specific version after a failure
+ // if err := m.Force(); err != nil {
+ // return fmt.Errorf("error forcing migration version: %v", err)
// }
- // if dirty {
- // // Force the version to the current version to clean the dirty state
- // if err := m.Force(int(version)); err != nil {
- // return fmt.Errorf("error forcing migration version: %v", err)
+ // Uncomment below to run down migrations in development (resets database)
+ // if os.Getenv("GOENV") == "development" {
+ // err = m.Down()
+ // if err != nil {
+ // if err == migrate.ErrNoChange {
+ // log.Println("no migrations to run down")
+ // } else {
+ // return fmt.Errorf("error running down migrations: %v", err)
+ // }
// }
+ // log.Println("database reset")
// }
err = m.Up()
- if err != nil && err != migrate.ErrNoChange {
- return fmt.Errorf("error running migrations: %v", err)
+ if err != nil {
+ if err == migrate.ErrNoChange {
+ log.Println("migration state is up to date")
+ } else {
+
+ return fmt.Errorf("error running migrations: %v", err)
+ }
+ }
+
+ if err == nil {
+ log.Println("ran migrations successfully")
}
return nil
diff --git a/server/handlers/accounts.go b/server/handlers/accounts.go
new file mode 100644
index 00000000..09b026a1
--- /dev/null
+++ b/server/handlers/accounts.go
@@ -0,0 +1,157 @@
+package handlers
+
+import (
+ "crypto/rand"
+ "encoding/json"
+ "fmt"
+ "log"
+ "net/http"
+ "plandex-server/db"
+
+ "github.com/plandex/plandex/shared"
+)
+
+func StartTrialHandler(w http.ResponseWriter, r *http.Request) {
+ log.Println("Received request for StartTrialHandler")
+
+ // start a transaction
+ tx, err := db.Conn.Begin()
+ 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")
+ }
+ }
+ }()
+
+ b := make([]byte, 3)
+ if _, err := rand.Read(b); err != nil {
+ log.Printf("Error generating random tag: %v\n", err)
+ http.Error(w, "Error generating random tag: "+err.Error(), http.StatusInternalServerError)
+ return
+ }
+ tag := fmt.Sprintf("%x", b)
+
+ name := "Trial User " + tag
+ email := tag + "@trial.plandex.ai"
+
+ var userId string
+ userRow, err := tx.Query("INSERT INTO users (name, email, is_trial) VALUES ($1, $2, true) RETURNING id", name, email)
+ closedUserRow := false
+
+ if err != nil {
+ log.Printf("Error creating user: %v\n", err)
+ http.Error(w, "Error creating user: "+err.Error(), http.StatusInternalServerError)
+ return
+ }
+
+ defer func() {
+ if !closedUserRow {
+ userRow.Close()
+ }
+ }()
+
+ if userRow.Next() {
+ if err := userRow.Scan(&userId); err != nil {
+ log.Printf("Error scanning user: %v\n", err)
+ http.Error(w, "Error scanning user: "+err.Error(), http.StatusInternalServerError)
+ return
+ }
+ }
+
+ err = userRow.Close()
+ if err != nil {
+ log.Printf("Error closing user row: %v\n", err)
+ http.Error(w, "Error closing user row: "+err.Error(), http.StatusInternalServerError)
+ return
+ }
+ closedUserRow = true
+
+ // create a new org
+ orgName := "Trial Org " + tag
+ orgRow, err := tx.Query("INSERT INTO orgs (name, creator_id, is_trial) VALUES ($1, $2, true) RETURNING id", orgName, userId)
+ closedOrgRow := false
+
+ if err != nil {
+ log.Printf("Error creating org: %v\n", err)
+ http.Error(w, "Error creating org: "+err.Error(), http.StatusInternalServerError)
+ return
+ }
+
+ defer func() {
+ if !closedOrgRow {
+ orgRow.Close()
+ }
+ }()
+
+ var orgId string
+ if orgRow.Next() {
+ if err := orgRow.Scan(&orgId); err != nil {
+ log.Printf("Error scanning org: %v\n", err)
+ http.Error(w, "Error scanning org: "+err.Error(), http.StatusInternalServerError)
+ return
+ }
+ }
+
+ err = orgRow.Close()
+ if err != nil {
+ log.Printf("Error closing org row: %v\n", err)
+ http.Error(w, "Error closing org row: "+err.Error(), http.StatusInternalServerError)
+ return
+ }
+ closedOrgRow = true
+
+ // insert org user
+ _, err = tx.Exec("INSERT INTO orgs_users (org_id, user_id) VALUES ($1, $2)", orgId, userId)
+ if err != nil {
+ log.Printf("Error inserting org user: %v\n", err)
+ http.Error(w, "Error inserting org user: "+err.Error(), http.StatusInternalServerError)
+ return
+ }
+
+ // create auth token
+ token, err := db.GenAuthToken(userId, 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
+ }
+
+ // 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
+ }
+
+ resp := shared.StartTrialResponse{
+ UserId: userId,
+ OrgId: orgId,
+ Token: token,
+ UserName: name,
+ OrgName: orgName,
+ }
+
+ bytes, err := json.Marshal(resp)
+
+ if err != nil {
+ log.Printf("Error marshalling response: %v\n", err)
+ http.Error(w, "Error marshalling response: "+err.Error(), http.StatusInternalServerError)
+ return
+ }
+
+ log.Println("Successfully started trial")
+
+ w.Write(bytes)
+}
diff --git a/server/handlers/projects.go b/server/handlers/projects.go
index 5aca5380..c6fedd08 100644
--- a/server/handlers/projects.go
+++ b/server/handlers/projects.go
@@ -50,8 +50,7 @@ func CreateProjectHandler(w http.ResponseWriter, r *http.Request) {
}
resp := shared.CreateProjectResponse{
- Id: id,
- OrgId: currentOrgId,
+ Id: id,
}
bytes, err := json.Marshal(resp)
diff --git a/server/migrations/2023120500_init.down.sql b/server/migrations/2023120500_init.down.sql
index f5b58ed4..1e55a0ab 100644
--- a/server/migrations/2023120500_init.down.sql
+++ b/server/migrations/2023120500_init.down.sql
@@ -1,8 +1,12 @@
-DROP TABLE IF EXISTS orgs;
+DROP TABLE IF EXISTS convo_summaries;
+DROP TABLE IF EXISTS plan_builds;
+
+DROP TABLE IF EXISTS users_projects;
+DROP TABLE IF EXISTS plans;
DROP TABLE IF EXISTS projects;
DROP TABLE IF EXISTS orgs_users;
-DROP TABLE IF EXISTS users_projects;
+
+DROP TABLE IF EXISTS auth_tokens;
+
+DROP TABLE IF EXISTS orgs;
DROP TABLE IF EXISTS users;
-DROP TABLE IF EXISTS plans;
-DROP TABLE IF EXISTS convo_summaries;
-DROP TABLE IF EXISTS plan_builds;
diff --git a/server/migrations/2023120500_init.up.sql b/server/migrations/2023120500_init.up.sql
index c851e2f2..ea5227a3 100644
--- a/server/migrations/2023120500_init.up.sql
+++ b/server/migrations/2023120500_init.up.sql
@@ -12,45 +12,49 @@ CREATE TABLE IF NOT EXISTS users (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
name VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL,
+ is_trial BOOLEAN NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
updated_at TIMESTAMP NOT NULL DEFAULT NOW()
);
CREATE TRIGGER update_users_modtime BEFORE UPDATE ON users FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
--- Default user, remove when auth is implemented
-INSERT INTO users (id, name, email) VALUES ('bc9c75ee-57b0-4552-aa1b-f80cf8c09f3f', 'Default User', '[email protected]');
-
CREATE TABLE IF NOT EXISTS orgs (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
name VARCHAR(255) NOT NULL,
domain VARCHAR(255),
auto_add_domain_users BOOLEAN NOT NULL DEFAULT FALSE,
creator_id UUID NOT NULL REFERENCES users(id),
+ is_trial BOOLEAN NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
updated_at TIMESTAMP NOT NULL DEFAULT NOW()
);
CREATE TRIGGER update_orgs_modtime BEFORE UPDATE ON orgs FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
--- Default org, remove when auth is implemented
-INSERT INTO orgs (id, name, creator_id) VALUES ('2ff5bc12-1160-4305-8707-9a165319de5a', 'Default Org', 'bc9c75ee-57b0-4552-aa1b-f80cf8c09f3f');
-
-CREATE TABLE IF NOT EXISTS projects (
+CREATE TABLE IF NOT EXISTS orgs_users (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
org_id UUID NOT NULL REFERENCES orgs(id) ON DELETE CASCADE,
- name VARCHAR(255) NOT NULL,
+ user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
updated_at TIMESTAMP NOT NULL DEFAULT NOW()
);
-CREATE TRIGGER update_projects_modtime BEFORE UPDATE ON projects FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
+CREATE TRIGGER update_orgs_users_modtime BEFORE UPDATE ON orgs_users FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
-CREATE TABLE IF NOT EXISTS orgs_users (
+CREATE TABLE IF NOT EXISTS auth_tokens (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
- org_id UUID NOT NULL REFERENCES orgs(id) ON DELETE CASCADE,
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ token_hash VARCHAR(64) NOT NULL,
+ created_at TIMESTAMP NOT NULL DEFAULT NOW()
+);
+CREATE INDEX auth_tokens_hash_idx ON auth_tokens(token_hash);
+
+CREATE TABLE IF NOT EXISTS projects (
+ id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
+ org_id UUID NOT NULL REFERENCES orgs(id) ON DELETE CASCADE,
+ name VARCHAR(255) NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
updated_at TIMESTAMP NOT NULL DEFAULT NOW()
);
-CREATE TRIGGER update_orgs_users_modtime BEFORE UPDATE ON orgs_users FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
+CREATE TRIGGER update_projects_modtime BEFORE UPDATE ON projects FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
CREATE TABLE IF NOT EXISTS plans (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
diff --git a/server/routes.go b/server/routes.go
index b20d9b44..d8f0a933 100644
--- a/server/routes.go
+++ b/server/routes.go
@@ -15,6 +15,8 @@ func InitRoutes() *mux.Router {
fmt.Fprintf(w, "OK")
})
+ r.HandleFunc("/accounts/start-trial", handlers.StartTrialHandler).Methods("POST")
+
r.HandleFunc("/projects", handlers.CreateProjectHandler).Methods("POST")
r.HandleFunc("/projects", handlers.ListProjectsHandler).Methods("GET")
r.HandleFunc("/projects/{projectId}/set-plan", handlers.ProjectSetPlanHandler).Methods("PUT")
diff --git a/shared/auth.go b/shared/auth.go
new file mode 100644
index 00000000..211152d9
--- /dev/null
+++ b/shared/auth.go
@@ -0,0 +1,6 @@
+package shared
+
+type AuthHeader struct {
+ Token string `json:"token"`
+ OrgId string `json:"orgId"`
+}
diff --git a/shared/req_res.go b/shared/req_res.go
index 589ed3db..fa49900b 100644
--- a/shared/req_res.go
+++ b/shared/req_res.go
@@ -1,12 +1,19 @@
package shared
+type StartTrialResponse struct {
+ UserId string `json:"userId"`
+ Token string `json:"token"`
+ OrgId string `json:"orgId"`
+ UserName string `json:"userName"`
+ OrgName string `json:"orgName"`
+}
+
type CreateProjectRequest struct {
Name string `json:"name"`
}
type CreateProjectResponse struct {
- Id string `json:"id"`
- OrgId string `json:"orgId"`
+ Id string `json:"id"`
}
type SetProjectPlanRequest struct {