Open source AI coding agent. Designed for large projects and real world tasks.
Go aiai-agentsai-developer-toolsai-toolsclicommand-linedeveloper-toolsgitgolanggpt-4llmopenaipolyglot-programmingterminalterminal-basedterminal-ui
simplify local mode quickstart and sign in
Dane Schneideraeeac2bd0067
diff --git a/app/_env b/app/_envdeleted file mode 100644index 0754205c..00000000--- a/app/_env+++ /dev/null@@ -1,8 +0,0 @@-POSTGRES_PASSWORD=plandex-POSTGRES_USER=plandex-POSTGRES_DATABASE=plandex-PGDATA_DIR=/var/lib/postgresql/data-PLANDEX_DATA_DIR=/var/lib/plandex/data # local path to store plandex data (outside container)-GOENV=development-PLANDEX_BASE_DIR=/plandex-server # container path to store plandex data (inside container)-API_HOST= # host of the api server in production mode - defaults to 'http://localhost:8080' in development mode\ No newline at end of filediff --git a/app/clear_local.sh b/app/clear_local.shnew file mode 100755index 00000000..8d67c7e8--- /dev/null+++ b/app/clear_local.sh@@ -0,0 +1,25 @@+#!/bin/bash++# Get the absolute path to the script's directory, regardless of where it's run from+SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"++# Change to the app directory if we're not already there+cd "$SCRIPT_DIR"++echo "WARNING: This will delete all Plandex server data and reset the database."+echo "This action cannot be undone."+read -p "Are you sure you want to continue? (y/N) " -n 1 -r+echo+if [[ ! $REPLY =~ ^[Yy]$ ]]+then+ echo "Reset cancelled."+ exit 1+fi++echo "Resetting local mode..."+echo "Stopping containers and removing volumes..."++# Stop containers and remove volumes+docker compose down -v++echo "Database and data directories cleared. Server stopped."\ No newline at end of filediff --git a/app/cli/api/clients.go b/app/cli/api/clients.goindex 6dde4aa7..61156283 100644--- a/app/cli/api/clients.go+++ b/app/cli/api/clients.go@@ -22,7 +22,7 @@ func init() {if os.Getenv("PLANDEX_ENV") == "development" {CloudApiHost = os.Getenv("PLANDEX_API_HOST")if CloudApiHost == "" {- CloudApiHost = "http://localhost:8080"+ CloudApiHost = "http://localhost:8099"}} else {CloudApiHost = "https://api.plandex.ai"diff --git a/app/cli/auth/account.go b/app/cli/auth/account.goindex c3889f77..9b718419 100644--- a/app/cli/auth/account.go+++ b/app/cli/auth/account.go@@ -28,6 +28,8 @@ func SelectOrSignInOrCreate() error {if err != nil {return fmt.Errorf("error signing in to new account: %v", err)}++ return nil}var options []string@@ -65,8 +67,10 @@ func SelectOrSignInOrCreate() error {return fmt.Errorf("error selecting account: account not found")}+ selectedAuth := *selected+setAuth(&shared.ClientAuth{- ClientAccount: *selected,+ ClientAccount: selectedAuth,})term.StartSpinner("")@@ -77,7 +81,7 @@ func SelectOrSignInOrCreate() error {return fmt.Errorf("error listing orgs: %v", apiErr.Msg)}- org, err := resolveOrgAuth(orgs)+ org, err := resolveOrgAuth(orgs, selectedAuth.IsLocalMode)if err != nil {return fmt.Errorf("error resolving org: %v", err)@@ -104,7 +108,7 @@ func SelectOrSignInOrCreate() error {fmt.Printf("✅ Signed in as %s | Org: %s\n", color.New(color.Bold, term.ColorHiGreen).Sprintf("<%s> %s", Current.UserName, Current.Email), color.New(term.ColorHiCyan).Sprint(Current.OrgName))fmt.Println()- term.PrintCmds("", "new", "plans")+ term.PrintCmds("", "", "new", "plans")return nil}@@ -148,11 +152,12 @@ func promptInitialAuth() error {const (SignInCloudOption = "Plandex Cloud"+ SignInLocalOption = "Local mode host"SignInOtherOption = "Another host")func promptSignInNewAccount() error {- selected, err := term.SelectFromList("Use Plandex Cloud or another host?", []string{SignInCloudOption, SignInOtherOption})+ selected, err := term.SelectFromList("Use Plandex Cloud or another host?", []string{SignInCloudOption, SignInLocalOption, SignInOtherOption})if err != nil {return fmt.Errorf("error selecting sign in option: %v", err)@@ -168,50 +173,71 @@ func promptSignInNewAccount() error {return fmt.Errorf("error prompting email: %v", err)}} else {- host, err = term.GetRequiredUserStringInput("Host:")+ if selected == SignInLocalOption {+ host, err = term.GetRequiredUserStringInputWithDefault("Host:", "http://localhost:8099")+ } else {+ host, err = term.GetRequiredUserStringInput("Host:")+ }if err != nil {return fmt.Errorf("error prompting host: %v", err)}- email, err = term.GetRequiredUserStringInput("Your email:")+ if selected == SignInLocalOption {+ email = "[email protected]"+ } else {+ email, err = term.GetRequiredUserStringInput("Your email:")+ }if err != nil {return fmt.Errorf("error prompting email: %v", err)}}- hasAccount, pin, err := verifyEmail(email, host)+ res, err := verifyEmail(email, host)if err != nil {return fmt.Errorf("error verifying email: %v", err)}- if hasAccount {- err := signIn(email, pin, host)+ if res.hasAccount {+ err := signIn(email, res.pin, host)if err != nil {return fmt.Errorf("error signing in: %v", err)}} else {- err := createAccount(email, pin, host)+ err := createAccount(email, res.pin, host, res.isLocalMode)if err != nil {return fmt.Errorf("error creating account: %v", err)}}- term.PrintCmds("", "new", "plans")+ term.PrintCmds("", "", "new", "plans")return nil}-func verifyEmail(email, host string) (bool, string, error) {+type verifyEmailRes struct {+ hasAccount bool+ isLocalMode bool+ pin string+}+func verifyEmail(email, host string) (*verifyEmailRes, error) {term.StartSpinner("")res, apiErr := apiClient.CreateEmailVerification(email, host, "")term.StopSpinner()if apiErr != nil {- return false, "", fmt.Errorf("error creating email verification: %v", apiErr.Msg)+ return nil, fmt.Errorf("error creating email verification: %v", apiErr.Msg)+ }++ if res.IsLocalMode {+ return &verifyEmailRes{+ hasAccount: res.HasAccount,+ isLocalMode: true,+ pin: "",+ }, nil}fmt.Println("✉️ You'll now receive a 6 character pin by email. It will be valid for 10 minutes.")@@ -219,10 +245,14 @@ func verifyEmail(email, host string) (bool, string, error) {pin, err := term.GetUserPasswordInput("Please enter your pin:")if err != nil {- return false, "", fmt.Errorf("error prompting pin: %v", err)+ return nil, fmt.Errorf("error prompting pin: %v", err)}- return res.HasAccount, pin, nil+ return &verifyEmailRes{+ hasAccount: res.HasAccount,+ isLocalMode: false,+ pin: pin,+ }, nil}func signIn(email, pin, host string) error {@@ -241,15 +271,18 @@ func signIn(email, pin, host string) error {}func handleSignInResponse(res *shared.SessionResponse, host string) error {+ isLocalMode := host != "" && res.IsLocalMode+err := setAuth(&shared.ClientAuth{ClientAccount: shared.ClientAccount{- Email: res.Email,- UserId: res.UserId,- UserName: res.UserName,- Token: res.Token,- IsTrial: false,- IsCloud: host == "",- Host: host,+ Email: res.Email,+ UserId: res.UserId,+ UserName: res.UserName,+ Token: res.Token,+ IsTrial: false,+ IsCloud: host == "",+ Host: host,+ IsLocalMode: isLocalMode,},})@@ -257,7 +290,7 @@ func handleSignInResponse(res *shared.SessionResponse, host string) error {return fmt.Errorf("error setting auth: %v", err)}- org, err := resolveOrgAuth(res.Orgs)+ org, err := resolveOrgAuth(res.Orgs, isLocalMode)if err != nil {return fmt.Errorf("error resolving org: %v", err)@@ -279,12 +312,18 @@ func handleSignInResponse(res *shared.SessionResponse, host string) error {return nil}-func createAccount(email, pin, host string) error {+func createAccount(email, pin, host string, isLocalMode bool) error {+ var name string- name, err := term.GetUserStringInput("Your name:")+ if isLocalMode {+ name = "Local Admin"+ } else {+ var err error+ name, err = term.GetUserStringInput("Your name:")- if err != nil {- return fmt.Errorf("error prompting name: %v", err)+ if err != nil {+ return fmt.Errorf("error prompting name: %v", err)+ }}term.StartSpinner("🌟 Creating account...")@@ -299,15 +338,20 @@ func createAccount(email, pin, host string) error {return fmt.Errorf("error creating account: %v", apiErr.Msg)}- err = setAuth(&shared.ClientAuth{+ if res.IsLocalMode {+ isLocalMode = true+ }++ err := setAuth(&shared.ClientAuth{ClientAccount: shared.ClientAccount{- Email: res.Email,- UserId: res.UserId,- UserName: res.UserName,- Token: res.Token,- IsTrial: false,- IsCloud: host == "",- Host: host,+ Email: res.Email,+ UserId: res.UserId,+ UserName: res.UserName,+ Token: res.Token,+ IsTrial: false,+ IsCloud: host == "",+ Host: host,+ IsLocalMode: isLocalMode,},})@@ -315,12 +359,16 @@ func createAccount(email, pin, host string) error {return fmt.Errorf("error setting auth: %v", err)}- org, err := resolveOrgAuth(res.Orgs)+ org, err := resolveOrgAuth(res.Orgs, isLocalMode)if err != nil {return fmt.Errorf("error resolving org: %v", err)}+ if org == nil {+ return fmt.Errorf("no org selected")+ }+Current.OrgId = org.IdCurrent.OrgName = org.NameCurrent.IntegratedModelsMode = org.IntegratedModelsModediff --git a/app/cli/auth/auth.go b/app/cli/auth/auth.goindex be8ad585..ed6034b9 100644--- a/app/cli/auth/auth.go+++ b/app/cli/auth/auth.go@@ -64,7 +64,7 @@ func MustResolveAuth(requireOrg bool) {term.OutputErrorAndExit("Error listing orgs: %v", apiErr.Msg)}- org, err := resolveOrgAuth(orgs)+ org, err := resolveOrgAuth(orgs, Current.IsLocalMode)if err != nil {term.OutputErrorAndExit("Error resolving org: %v", err)@@ -92,14 +92,14 @@ func RefreshInvalidToken() error {return fmt.Errorf("error refreshing token: auth not loaded")}- hasAccount, pin, err := verifyEmail(Current.Email, Current.Host)+ res, err := verifyEmail(Current.Email, Current.Host)if err != nil {return fmt.Errorf("error verifying email: %v", err)}- if hasAccount {- return signIn(Current.Email, pin, Current.Host)+ if res.hasAccount {+ return signIn(Current.Email, res.pin, Current.Host)} else {host := Current.Hostif host == "" {diff --git a/app/cli/auth/org.go b/app/cli/auth/org.goindex d0c6aa37..cc7716cc 100644--- a/app/cli/auth/org.go+++ b/app/cli/auth/org.go@@ -8,12 +8,16 @@ import (shared "plandex-shared")-func resolveOrgAuth(orgs []*shared.Org) (*shared.Org, error) {+func resolveOrgAuth(orgs []*shared.Org, isLocalMode bool) (*shared.Org, error) {var org *shared.Orgvar err errorif len(orgs) == 0 {- org, err = promptNoOrgs()+ if isLocalMode {+ org, err = createOrg(isLocalMode)+ } else {+ org, err = promptNoOrgs()+ }if err != nil {return nil, fmt.Errorf("error prompting no orgs: %v", err)@@ -22,7 +26,7 @@ func resolveOrgAuth(orgs []*shared.Org) (*shared.Org, error) {} else if len(orgs) == 1 {org = orgs[0]} else {- org, err = selectOrg(orgs)+ org, err = selectOrg(orgs, isLocalMode)if err != nil {return nil, fmt.Errorf("error selecting org: %v", err)@@ -42,22 +46,31 @@ func promptNoOrgs() (*shared.Org, error) {}if shouldCreate {- return createOrg()+ return createOrg(false)}return nil, nil}-func createOrg() (*shared.Org, error) {- name, err := term.GetRequiredUserStringInput("Org name:")+func createOrg(isLocalMode bool) (*shared.Org, error) {+ var err error+ var name string+ var autoAddDomainUsers bool++ if isLocalMode {+ name = "Local Org"+ } else {+ name, err = term.GetRequiredUserStringInput("Org name:")+ }if err != nil {return nil, fmt.Errorf("error prompting org name: %v", err)}- autoAddDomainUsers, err := promptAutoAddUsersIfValid(Current.Email)-- if err != nil {- return nil, fmt.Errorf("error prompting auto add domain users: %v", err)+ if !isLocalMode {+ autoAddDomainUsers, err = promptAutoAddUsersIfValid(Current.Email)+ if err != nil {+ return nil, fmt.Errorf("error prompting auto add domain users: %v", err)+ }}term.StartSpinner("")@@ -91,7 +104,7 @@ func promptAutoAddUsersIfValid(email string) (bool, error) {const CreateOrgOption = "Create a new org"-func selectOrg(orgs []*shared.Org) (*shared.Org, error) {+func selectOrg(orgs []*shared.Org, isLocalMode bool) (*shared.Org, error) {var options []stringfor _, org := range orgs {options = append(options, org.Name)@@ -105,7 +118,7 @@ func selectOrg(orgs []*shared.Org) (*shared.Org, error) {}if selected == CreateOrgOption {- return createOrg()+ return createOrg(isLocalMode)}var selectedOrg *shared.Orgdiff --git a/app/cli/cmd/diffs.go b/app/cli/cmd/diffs.goindex 42433c68..26a1bca0 100644--- a/app/cli/cmd/diffs.go+++ b/app/cli/cmd/diffs.go@@ -138,7 +138,7 @@ func diffs(cmd *cobra.Command, args []string) {fmt.Printf("%s for git diff format\n", color.New(color.Bold, term.ColorHiGreen).Sprintf("(g)"))fmt.Printf("%s to quit\n", color.New(color.Bold, term.ColorHiGreen).Sprintf("(q)"))- color.New(term.ColorHiMagenta, color.Bold).Print("Hotkey 👉 ")+ color.New(term.ColorHiMagenta, color.Bold).Print("Press a hotkey> ")char, key, err := term.GetUserKeyInput()if err != nil {@@ -167,6 +167,7 @@ func diffs(cmd *cobra.Command, args []string) {fmt.Println()os.Exit(0)} else {+ fmt.Println()break}} else if string(char) == "\x03" { // Ctrl+Cdiff --git a/app/cli/cmd/repl.go b/app/cli/cmd/repl.goindex a51b88f3..55700b8f 100644--- a/app/cli/cmd/repl.go+++ b/app/cli/cmd/repl.go@@ -58,6 +58,10 @@ func runRepl(cmd *cobra.Command, args []string) {auth.MustResolveAuthWithOrg()lib.MustResolveOrCreateProject()+ if !auth.Current.IntegratedModelsMode {+ lib.MustVerifyApiKeys()+ }+term.StartSpinner("")lib.LoadState()diff --git a/app/cli/plan_exec/tell.go b/app/cli/plan_exec/tell.goindex 60eccfeb..96bd95dd 100644--- a/app/cli/plan_exec/tell.go+++ b/app/cli/plan_exec/tell.go@@ -287,7 +287,7 @@ func showHotkeyMenu(diffs []string) {table.Render()fmt.Print(b.String())- color.New(term.ColorHiMagenta, color.Bold).Printf("Press a hotkey, %s %s, or %s %s 👉 ", color.New(color.FgHiWhite, color.Bold).Sprintf("↓"), color.New(term.ColorHiMagenta, color.Bold).Sprintf("to select"), color.New(color.FgHiWhite, color.Bold).Sprintf("q"), color.New(term.ColorHiMagenta, color.Bold).Sprintf("to quit"))+ color.New(term.ColorHiMagenta, color.Bold).Printf("Press a hotkey, %s %s, or %s %s> ", color.New(color.FgHiWhite, color.Bold).Sprintf("↓"), color.New(term.ColorHiMagenta, color.Bold).Sprintf("to select"), color.New(color.FgHiWhite, color.Bold).Sprintf("q"), color.New(term.ColorHiMagenta, color.Bold).Sprintf("to quit"))}func handleHotkey(diffs []string, params ExecParams) {diff --git a/app/cli/term/help.go b/app/cli/term/help.goindex 3c6e1f2a..15550aa3 100644--- a/app/cli/term/help.go+++ b/app/cli/term/help.go@@ -17,6 +17,7 @@ type CmdConfig struct {}var CliCommands = []CmdConfig{+ {"", "", "start the Plandex REPL", false},{"new", "", "start a new plan", true},{"plans", "pl", "list plans", true},{"cd", "", "set current plan by name or index", true},@@ -144,6 +145,8 @@ func printCmds(w io.Writer, prefix string, colors []color.Attribute, cmds ...strvar styled stringif IsRepl {styled = color.New(colors...).Sprintf(" \\%s ", cmd)+ } else if cmd == "" { // special case for the repl+ styled = color.New(colors...).Sprintf(" plandex ")} else {styled = color.New(colors...).Sprintf(" plandex %s ", cmd)}diff --git a/app/docker-compose.yml b/app/docker-compose.ymlindex aba85634..fd9ce70e 100644--- a/app/docker-compose.yml+++ b/app/docker-compose.yml@@ -2,34 +2,29 @@ services:plandex-postgres:image: postgres:latestrestart: always- env_file:- - ./.env+ environment:+ POSTGRES_PASSWORD: plandex+ POSTGRES_USER: plandex+ POSTGRES_DB: plandexports:- "5432:5432"volumes:- - ./scripts/init-db:/docker-entrypoint-initdb.d- - ${PGDATA_DIR}:/var/lib/postgresql/data- - /etc/timezone:/etc/timezone:ro- - /etc/localtime:/etc/localtime:ro+ - plandex-db:/var/lib/postgresql/datanetworks:- plandex-networkplandex-server:build:- context: ./server- dockerfile: ./server/Dockerfile+ context: .+ dockerfile: server/Dockerfilevolumes:- - "${PLANDEX_DATA_DIR}:${PLANDEX_BASE_DIR}"- - /etc/timezone:/etc/timezone:ro- - /etc/localtime:/etc/localtime:ro+ - plandex-files:/plandex-serverports:- - "8080:8080"- env_file:- - ./.env+ - "8099:8099"environment:- DATABASE_URL: "postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@plandex-postgres:5432/${POSTGRES_DATABASE}?sslmode=disable"- GOENV: $GOENV- PLANDEX_BASE_DIR: $PLANDEX_BASE_DIR-+ DATABASE_URL: "postgres://plandex:plandex@plandex-postgres:5432/plandex?sslmode=disable"+ GOENV: development+ LOCAL_MODE: 1+ PLANDEX_BASE_DIR: /plandex-servernetworks:- plandex-networkdepends_on:@@ -39,3 +34,7 @@ services:networks:plandex-network:driver: bridge++volumes:+ plandex-db:+ plandex-files:\ No newline at end of filediff --git a/app/reset_local.sh b/app/reset_local.shnew file mode 100755index 00000000..08ce00d4--- /dev/null+++ b/app/reset_local.sh@@ -0,0 +1,13 @@+# Get the absolute path to the script's directory, regardless of where it's run from+SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"++# Change to the app directory if we're not already there+cd "$SCRIPT_DIR"++echo "Clearing local mode..."++./clear_local.sh++echo "Starting local mode..."++./start_local.sh\ No newline at end of filediff --git a/app/scripts/init-db/01-init.sh b/app/scripts/init-db/01-init.shdeleted file mode 100755index 7bb31e88..00000000--- a/app/scripts/init-db/01-init.sh+++ /dev/null@@ -1,9 +0,0 @@-#!/bin/bash-set -e--psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" <<-EOSQL- CREATE USER $POSTGRES_USER WITH PASSWORD '$POSTGRES_PASSWORD';- CREATE DATABASE $POSTGRES_DATABASE OWNER $POSTGRES_USER;- GRANT ALL PRIVILEGES ON DATABASE $POSTGRES_DATABASE TO $POSTGRES_USER;-EOSQL-diff --git a/app/server/Dockerfile b/app/server/Dockerfileindex 5be6cb1c..89157ccd 100644--- a/app/server/Dockerfile+++ b/app/server/Dockerfile@@ -29,8 +29,8 @@ ENV GOARCH=amd64RUN rm -f plandex-server && go build -o plandex-server .# Set the port and expose it-ENV PORT=8080-EXPOSE 8080+ENV PORT=8099+EXPOSE 8099# Command to run the executableCMD ["./plandex-server"]diff --git a/app/server/db/account_helpers.go b/app/server/db/account_helpers.goindex 85110252..f4893c5f 100644--- a/app/server/db/account_helpers.go+++ b/app/server/db/account_helpers.go@@ -2,6 +2,7 @@ package dbimport ("fmt"+ "os""github.com/jmoiron/sqlx")@@ -13,6 +14,7 @@ type CreateAccountResult struct {}func CreateAccount(name, email, emailVerificationId string, tx *sqlx.Tx) (*CreateAccountResult, error) {+ isLocalMode := (os.Getenv("GOENV") == "development" && os.Getenv("LOCAL_MODE") == "1")// create useruser, err := CreateUser(name, email, tx)@@ -30,11 +32,14 @@ func CreateAccount(name, email, emailVerificationId string, tx *sqlx.Tx) (*Creatreturn nil, fmt.Errorf("error creating auth token: %v", err)}- // 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", userId, authTokenId, emailVerificationId)+ // skipping email verification in local mode+ if !isLocalMode {+ // 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", userId, authTokenId, emailVerificationId)- if err != nil {- return nil, fmt.Errorf("error updating email verification: %v", err)+ if err != nil {+ return nil, fmt.Errorf("error updating email verification: %v", err)+ }}// add to org matching domain if one exists and auto add domain users is true for that orgdiff --git a/app/server/db/fs.go b/app/server/db/fs.goindex b28a067d..8f681a1b 100644--- a/app/server/db/fs.go+++ b/app/server/db/fs.go@@ -18,6 +18,9 @@ func init() {log.Println("Plandex server home dir:", home)log.Println("os.Getenv(PLANDEX_BASE_DIR):", os.Getenv("PLANDEX_BASE_DIR"))log.Println("GOENV:", os.Getenv("GOENV"))+ if os.Getenv("GOENV") == "development" && os.Getenv("LOCAL_MODE") == "1" {+ log.Println("Local mode enabled")+ }BaseDir = os.Getenv("PLANDEX_BASE_DIR")diff --git a/app/server/handlers/accounts.go b/app/server/handlers/accounts.goindex d8541696..42a6acd4 100644--- a/app/server/handlers/accounts.go+++ b/app/server/handlers/accounts.go@@ -23,6 +23,8 @@ func CreateAccountHandler(w http.ResponseWriter, r *http.Request) {return}+ isLocalMode := (os.Getenv("GOENV") == "development" && os.Getenv("LOCAL_MODE") == "1")+// read the request bodybody, err := io.ReadAll(r.Body)if err != nil {@@ -40,12 +42,17 @@ func CreateAccountHandler(w http.ResponseWriter, r *http.Request) {}req.Email = strings.ToLower(req.Email)- emailVerificationId, err := db.ValidateEmailVerification(req.Email, req.Pin)+ var emailVerificationId string- if err != nil {- log.Printf("Error validating email verification: %v\n", err)- http.Error(w, "Error validating email verification: "+err.Error(), http.StatusInternalServerError)- return+ // skipping email verification in dev/local mode+ if !isLocalMode {+ 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@@ -119,11 +126,12 @@ func CreateAccountHandler(w http.ResponseWriter, r *http.Request) {}resp := shared.SessionResponse{- UserId: userId,- Token: token,- Email: req.Email,- UserName: req.UserName,- Orgs: apiOrgs,+ UserId: userId,+ Token: token,+ Email: req.Email,+ UserName: req.UserName,+ Orgs: apiOrgs,+ IsLocalMode: os.Getenv("GOENV") == "development" && os.Getenv("LOCAL_MODE") == "1",}bytes, err := json.Marshal(resp)diff --git a/app/server/handlers/auth_helpers.go b/app/server/handlers/auth_helpers.goindex ef875142..ed7cd5b0 100644--- a/app/server/handlers/auth_helpers.go+++ b/app/server/handlers/auth_helpers.go@@ -294,6 +294,8 @@ func ValidateAndSignIn(w http.ResponseWriter, r *http.Request, req shared.SignInvar signInCodeOrgId stringvar err error+ isLocalMode := (os.Getenv("GOENV") == "development" && os.Getenv("LOCAL_MODE") == "1")+if req.IsSignInCode {res, err := db.ValidateSignInCode(req.Pin)@@ -330,14 +332,17 @@ func ValidateAndSignIn(w http.ResponseWriter, r *http.Request, req shared.SignInreturn nil, fmt.Errorf("not found")}- emailVerificationId, err = db.ValidateEmailVerification(req.Email, req.Pin)+ // only validate email in non-local mode+ if !isLocalMode {+ 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)- }+ if err != nil {+ log.Printf("Error validating email verification: %v\n", err)+ return nil, fmt.Errorf("error validating email verification: %v", err)+ }- log.Println("Email verification successful")+ log.Println("Email verification successful")+ }}// start a transaction@@ -374,7 +379,7 @@ func ValidateAndSignIn(w http.ResponseWriter, r *http.Request, req shared.SignInlog.Printf("Error updating sign in code: %v\n", err)return nil, fmt.Errorf("error updating sign in code: %v", err)}- } else {+ } else if !isLocalMode { // only update email verification in non-local mode// 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)@@ -433,11 +438,12 @@ func ValidateAndSignIn(w http.ResponseWriter, r *http.Request, req shared.SignIn}resp := shared.SessionResponse{- UserId: user.Id,- Token: token,- Email: user.Email,- UserName: user.Name,- Orgs: apiOrgs,+ UserId: user.Id,+ Token: token,+ Email: user.Email,+ UserName: user.Name,+ Orgs: apiOrgs,+ IsLocalMode: os.Getenv("GOENV") == "development" && os.Getenv("LOCAL_MODE") == "1",}return &resp, nildiff --git a/app/server/handlers/invites.go b/app/server/handlers/invites.goindex 7841aa59..ba619a38 100644--- a/app/server/handlers/invites.go+++ b/app/server/handlers/invites.go@@ -4,6 +4,7 @@ import ("encoding/json""log""net/http"+ "os""plandex-server/db""plandex-server/email""strings"@@ -15,6 +16,16 @@ import (func InviteUserHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received a request for InviteUserHandler")++ if os.Getenv("GOENV") == "development" && os.Getenv("LOCAL_MODE") == "1" {+ writeApiError(w, shared.ApiError{+ Type: shared.ApiErrorTypeOther,+ Status: http.StatusForbidden,+ Msg: "Local mode is not supported for invites",+ })+ return+ }+auth := Authenticate(w, r, true)if auth == nil {return@@ -166,6 +177,16 @@ func InviteUserHandler(w http.ResponseWriter, r *http.Request) {func ListPendingInvitesHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received a request for ListInvitesHandler")++ if os.Getenv("GOENV") == "development" && os.Getenv("LOCAL_MODE") == "1" {+ writeApiError(w, shared.ApiError{+ Type: shared.ApiErrorTypeOther,+ Status: http.StatusForbidden,+ Msg: "Local mode is not supported for invites",+ })+ return+ }+auth := Authenticate(w, r, true)if auth == nil {return@@ -214,6 +235,16 @@ func ListPendingInvitesHandler(w http.ResponseWriter, r *http.Request) {func ListAcceptedInvitesHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received a request for ListAcceptedInvitesHandler")++ if os.Getenv("GOENV") == "development" && os.Getenv("LOCAL_MODE") == "1" {+ writeApiError(w, shared.ApiError{+ Type: shared.ApiErrorTypeOther,+ Status: http.StatusForbidden,+ Msg: "Local mode is not supported for invites",+ })+ return+ }+auth := Authenticate(w, r, true)if auth == nil {return@@ -262,6 +293,16 @@ func ListAcceptedInvitesHandler(w http.ResponseWriter, r *http.Request) {func ListAllInvitesHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received a request for ListAllInvitesHandler")++ if os.Getenv("GOENV") == "development" && os.Getenv("LOCAL_MODE") == "1" {+ writeApiError(w, shared.ApiError{+ Type: shared.ApiErrorTypeOther,+ Status: http.StatusForbidden,+ Msg: "Local mode is not supported for invites",+ })+ return+ }+auth := Authenticate(w, r, true)if auth == nil {return@@ -310,6 +351,16 @@ func ListAllInvitesHandler(w http.ResponseWriter, r *http.Request) {func DeleteInviteHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received a request for DeleteInviteHandler")++ if os.Getenv("GOENV") == "development" && os.Getenv("LOCAL_MODE") == "1" {+ writeApiError(w, shared.ApiError{+ Type: shared.ApiErrorTypeOther,+ Status: http.StatusForbidden,+ Msg: "Local mode is not supported for invites",+ })+ return+ }+auth := Authenticate(w, r, true)if auth == nil {returndiff --git a/app/server/handlers/sessions.go b/app/server/handlers/sessions.goindex a3cbd949..5501df3d 100644--- a/app/server/handlers/sessions.go+++ b/app/server/handlers/sessions.go@@ -7,6 +7,7 @@ import ("io""log""net/http"+ "os""plandex-server/db""plandex-server/email""strings"@@ -79,37 +80,46 @@ func CreateEmailVerificationHandler(w http.ResponseWriter, r *http.Request) {return}- // create pin - 6 alphanumeric characters- pinBytes, err := shared.GetRandomAlphanumeric(6)- if err != nil {- log.Printf("Error generating random pin: %v\n", err)- http.Error(w, "Error generating random pin: "+err.Error(), http.StatusInternalServerError)- return- }+ var res shared.CreateEmailVerificationResponse- // get sha256 hash of pin- hashBytes := sha256.Sum256(pinBytes)- pinHash := hex.EncodeToString(hashBytes[:])+ if !(os.Getenv("GOENV") == "development" && os.Getenv("LOCAL_MODE") == "1") {+ // create pin - 6 alphanumeric characters+ pinBytes, err := shared.GetRandomAlphanumeric(6)+ if err != nil {+ log.Printf("Error generating random pin: %v\n", err)+ http.Error(w, "Error generating random pin: "+err.Error(), http.StatusInternalServerError)+ return+ }- // create verification- err = db.CreateEmailVerification(req.Email, req.UserId, pinHash)+ // get sha256 hash of pin+ hashBytes := sha256.Sum256(pinBytes)+ pinHash := hex.EncodeToString(hashBytes[:])- if err != nil {- log.Printf("Error creating email verification: %v\n", err)- http.Error(w, "Error creating email verification: "+err.Error(), http.StatusInternalServerError)- return- }+ // create verification+ err = db.CreateEmailVerification(req.Email, req.UserId, pinHash)- err = email.SendVerificationEmail(req.Email, string(pinBytes))+ if err != nil {+ log.Printf("Error creating email verification: %v\n", err)+ http.Error(w, "Error creating email verification: "+err.Error(), http.StatusInternalServerError)+ return+ }- if err != nil {- log.Printf("Error sending verification email: %v\n", err)- http.Error(w, "Error sending verification email: "+err.Error(), http.StatusInternalServerError)- return- }+ err = email.SendVerificationEmail(req.Email, string(pinBytes))- res := shared.CreateEmailVerificationResponse{- HasAccount: hasAccount,+ if err != nil {+ log.Printf("Error sending verification email: %v\n", err)+ http.Error(w, "Error sending verification email: "+err.Error(), http.StatusInternalServerError)+ return+ }++ res = shared.CreateEmailVerificationResponse{+ HasAccount: hasAccount,+ }+ } else {+ res = shared.CreateEmailVerificationResponse{+ HasAccount: hasAccount,+ IsLocalMode: true,+ }}bytes, err := json.Marshal(res)diff --git a/app/server/handlers/users.go b/app/server/handlers/users.goindex 04dba2ec..c5152c58 100644--- a/app/server/handlers/users.go+++ b/app/server/handlers/users.go@@ -4,6 +4,7 @@ import ("encoding/json""log""net/http"+ "os""plandex-server/db""strings"@@ -14,6 +15,16 @@ import (func ListUsersHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received a request for ListUsersHandler")++ if os.Getenv("GOENV") == "development" && os.Getenv("LOCAL_MODE") == "1" {+ writeApiError(w, shared.ApiError{+ Type: shared.ApiErrorTypeOther,+ Status: http.StatusForbidden,+ Msg: "Local mode is not supported for user management",+ })+ return+ }+auth := Authenticate(w, r, true)if auth == nil {return@@ -79,6 +90,16 @@ func ListUsersHandler(w http.ResponseWriter, r *http.Request) {func DeleteOrgUserHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received a request for DeleteOrgUserHandler")++ if os.Getenv("GOENV") == "development" && os.Getenv("LOCAL_MODE") == "1" {+ writeApiError(w, shared.ApiError{+ Type: shared.ApiErrorTypeOther,+ Status: http.StatusForbidden,+ Msg: "Local mode is not supported for user management",+ })+ return+ }+auth := Authenticate(w, r, true)if auth == nil {returndiff --git a/app/server/setup/setup.go b/app/server/setup/setup.goindex ed0d1156..7e6e5409 100644--- a/app/server/setup/setup.go+++ b/app/server/setup/setup.go@@ -71,10 +71,10 @@ func StartServer(handler http.Handler) {log.Println("Database connection closed")}()- // Get externalPort from the environment variable or default to 8080+ // Get externalPort from the environment variable or default to 8099externalPort := os.Getenv("PORT")if externalPort == "" {- externalPort = "8080"+ externalPort = "8099"}// Add logging middleware before the maxBytes middlewarediff --git a/app/shared/auth.go b/app/shared/auth.goindex f14782a2..982af1bc 100644--- a/app/shared/auth.go+++ b/app/shared/auth.go@@ -52,12 +52,13 @@ type ApiError struct {}type ClientAccount struct {- IsCloud bool `json:"isCloud"`- Host string `json:"host"`- Email string `json:"email"`- UserName string `json:"userName"`- UserId string `json:"userId"`- Token string `json:"token"`+ IsCloud bool `json:"isCloud"`+ Host string `json:"host"`+ Email string `json:"email"`+ UserName string `json:"userName"`+ UserId string `json:"userId"`+ Token string `json:"token"`+ IsLocalMode bool `json:"isLocalMode"`IsTrial bool `json:"isTrial"` // legacy field}diff --git a/app/shared/req_res.go b/app/shared/req_res.goindex 4a70fe47..2c603dca 100644--- a/app/shared/req_res.go+++ b/app/shared/req_res.go@@ -14,7 +14,8 @@ type CreateEmailVerificationRequest struct {}type CreateEmailVerificationResponse struct {- HasAccount bool `json:"hasAccount"`+ HasAccount bool `json:"hasAccount"`+ IsLocalMode bool `json:"isLocalMode"`}type VerifyEmailPinRequest struct {@@ -40,11 +41,12 @@ type CreateAccountRequest struct {}type SessionResponse struct {- UserId string `json:"userId"`- Token string `json:"token"`- Email string `json:"email"`- UserName string `json:"userName"`- Orgs []*Org `json:"orgs"`+ UserId string `json:"userId"`+ Token string `json:"token"`+ Email string `json:"email"`+ UserName string `json:"userName"`+ Orgs []*Org `json:"orgs"`+ IsLocalMode bool `json:"isLocalMode"`}type CreateOrgRequest struct {diff --git a/app/start_local.sh b/app/start_local.shindex 2ec31fe2..791c1720 100755--- a/app/start_local.sh+++ b/app/start_local.sh@@ -1,5 +1,11 @@#!/bin/bash+# Get the absolute path to the script's directory, regardless of where it's run from+SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"++# Change to the app directory if we're not already there+cd "$SCRIPT_DIR"+echo "Checking dependencies..."if ! [ -x "$(command -v git)" ]; then@@ -23,23 +29,7 @@ if ! [ -x "$(command -v docker-compose)" ]; thenfifi-# make sure that we are in the same directory as the script-cd "$(dirname "$0")"--# copy the _env file to .env unless it already exists-if [ -f .env ]; then- echo ".env file already exists, won't overwrite it with _env"- echo "Add any custom values to .env"-else- echo "Copying _env file to .env"- cp _env .env- echo ".env has been populated with default values"- echo "Add any custom values to .env"-fi--echo "Setup complete!"--echo "Starting the application..."+echo "Starting the local Plandex server and database..."docker compose builddocker compose updiff --git a/docs/docs/development.md b/docs/docs/development.mdindex 1f8734c4..201d80be 100644--- a/docs/docs/development.md+++ b/docs/docs/development.md@@ -46,7 +46,7 @@ You might also need sudo on MacOS if you don't have write permissions to `/usr/lThis creates watchers with `reflex` to rebuild both the server and the CLI when relevant files change.-The server runs on port 8080 by default.+The server runs on port 8099 by default.After each build, the CLI is copied to `/usr/local/bin/plandex-dev`so you can use it with just `plandex-dev` in any directory. A `pdxd` alias is also created. Note the difference from the `plandex` binary and `pdx` aliases which are installed for production usage—aliases are used for development to avoid overwriting the production install.diff --git a/docs/docs/environment-variables.md b/docs/docs/environment-variables.mdindex 99aeeca6..ffbaf2f5 100644--- a/docs/docs/environment-variables.md+++ b/docs/docs/environment-variables.md@@ -13,7 +13,7 @@ This is an overview of all the environment variables that can be used with Pland```bashPLANDEX_ENV=development # Set this to 'development' to default to the local development server instead of Plandex Cloud when working on Plandex itself.-PLANDEX_API_HOST= # Defaults to 'http://localhost:8080' if PLANDEX_ENV is development, otherwise it's 'https://api.plandex.ai'—override this to use a different host.+PLANDEX_API_HOST= # Defaults to 'http://localhost:8099' if PLANDEX_ENV is development, otherwise it's 'https://api.plandex.ai'—override this to use a different host.```### LLM Providers@@ -56,7 +56,7 @@ Check out the [Self-Hosting Guide](./hosting/self-hosting.md) for more details.GOENV=development # Whether to run in development or production mode. Must be 'development' or 'production'PLANDEX_BASE_DIR= # The base directory to read and write files. Defaults to '$HOME/plandex-server' in development mode, '/plandex-server' in production.API_HOST= # The host the API server listens on. Defaults to 'http://localhost:$PORT'. In production mode, should be a host like 'https://api.your-domain.ai'.-PORT=8080 # The port the server listens on. Defaults to 8080.+PORT=8099 # The port the server listens on. Defaults to 8099.```### docker-compose@@ -65,7 +65,6 @@ For self-hosting with docker-compose, default environment variables are set in ````bashPLANDEX_DATA_DIR=/var/lib/plandex/data # When using docker-compose, this is the directory *on your machine* that the Plandex server will use to store data—it will be mounted to the Docker container as a volume.-PGDATA_DIR=/var/lib/postgresql/data # Where PostgreSQL should store its data.# Database CredentialsPOSTGRES_DATABASE=plandex # Your postgres database.diff --git a/docs/docs/hosting/self-hosting.md b/docs/docs/hosting/self-hosting.mdindex e8774fcc..3b4b23d4 100644--- a/docs/docs/hosting/self-hosting.md+++ b/docs/docs/hosting/self-hosting.md@@ -11,7 +11,7 @@ Plandex is open source and uses a client-server architecture. The server can beThe self-hosting quickstart requires git, docker, and docker-compose. It's designed for local use with a single user. If you instead want to run Plandex on a remote server with multiple users or orgs, continue on to the [Requirements](#requirements) section below.-1. Run the server in development mode:+1. Run the server in local mode:```bashgit clone https://github.com/plandex-ai/plandex.git@@ -19,19 +19,39 @@ cd plandex/app./start_local.sh```-2. Install the Plandex CLI if you haven't already:+2. In a new terminal session, install the Plandex CLI if you haven't already:```bashcurl -sL https://plandex.ai/install.sh | bash```-3. Then run:+3. Run:```bashplandex sign-in```-4. Follow the prompts from there to create a new account on your self-hosted server. From there, check out the more general [CLI quickstart](../quick-start.md) to get fully up and running.+4. When prompted 'Use Plandex Cloud or another host?', select 'Local mode host'. Confirm the default host, which is `http://localhost:8099`.++5. If you don't have an OpenRouter account, first [sign up here.](https://openrouter.ai/signup) Then [generate an API key here.](https://openrouter.ai/keys) Set the `OPENROUTER_API_KEY` environment variable:++```bash+export OPENROUTER_API_KEY=<your-openrouter-api-key>+```++6. If you don't have an OpenAI account, first [sign up here.](https://platform.openai.com/signup) Then [generate an API key here.](https://platform.openai.com/account/api-keys) Set the `OPENAI_API_KEY` environment variable:++```bash+export OPENAI_API_KEY=<your-openai-api-key>+```++7. In a project directory, start the Plandex REPL:++```bash+plandex+```++You're ready to start building!## Requirements@@ -47,7 +67,7 @@ Production mode is designed for multiple users or organizations. Email is enableDevelopment or production mode is set with the `GOENV` environment variable. It should be set to either `development` or `production`.-In both development and production mode, the server runs on port 8080 by default. This can be changed with the `PORT` environment variable.+In both development and production mode, the server runs on port 8099 by default. This can be changed with the `PORT` environment variable.## docker-compose@@ -127,7 +147,7 @@ git checkout server/v$VERSIONcd plandex/appmkdir ~/plandex-server # or another directory where you want to store filesdocker build -t plandex-server -f Dockerfile.server .-docker run -p 8080:8080 \+docker run -p 8099:8099 \-v ~/plandex-server:/plandex-server \-e DATABASE_URL \-e GOENV \