Skip to content

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

some groundwork for ui

Dane Schneiderc44b62e5c4ab
diff --git a/app/cli/api/clients.go b/app/cli/api/clients.go
index 2f03597b..2ba1c1fc 100644
--- a/app/cli/api/clients.go
+++ b/app/cli/api/clients.go
@@ -46,17 +46,35 @@ type authenticatedTransport struct {
// RoundTrip executes a single HTTP transaction and adds a custom header
func (t *authenticatedTransport) RoundTrip(req *http.Request) (*http.Response, error) {
+ if os.Getenv("PLANDEX_ENV") == "development" {
+ req.Host = "api.localhost" // Set the Host header to api.localhost for local development
+ }
+
auth.SetAuthHeader(req)
return t.underlyingTransport.RoundTrip(req)
}
+type unauthenticatedTransport struct {
+ underlyingTransport http.RoundTripper
+}
+
+func (t *unauthenticatedTransport) RoundTrip(req *http.Request) (*http.Response, error) {
+ if os.Getenv("PLANDEX_ENV") == "development" {
+ req.Host = "api.localhost" // Set the Host header to api.localhost for local development
+ }
+
+ return t.underlyingTransport.RoundTrip(req)
+}
+
var netDialer = &net.Dialer{
Timeout: dialTimeout,
}
var unauthenticatedClient = &http.Client{
- Transport: &http.Transport{
- Dial: netDialer.Dial,
+ Transport: &unauthenticatedTransport{
+ underlyingTransport: &http.Transport{
+ Dial: netDialer.Dial,
+ },
},
Timeout: fastReqTimeout,
}
diff --git a/app/cli/auth/account.go b/app/cli/auth/account.go
index de8a9576..a7fe2a13 100644
--- a/app/cli/auth/account.go
+++ b/app/cli/auth/account.go
@@ -3,7 +3,6 @@ package auth
import (
"fmt"
"plandex/term"
- "plandex/types"
"github.com/fatih/color"
"github.com/plandex/plandex/shared"
@@ -79,7 +78,7 @@ func SelectOrSignInOrCreate() error {
return nil
}
- var selected *types.ClientAccount
+ var selected *shared.ClientAccount
for i, opt := range options {
if selectedOpt == opt {
selected = accounts[i]
@@ -91,7 +90,7 @@ func SelectOrSignInOrCreate() error {
return fmt.Errorf("error selecting account: account not found")
}
- setAuth(&types.ClientAuth{
+ setAuth(&shared.ClientAuth{
ClientAccount: *selected,
})
@@ -109,10 +108,11 @@ func SelectOrSignInOrCreate() error {
return fmt.Errorf("error resolving org: %v", err)
}
- err = setAuth(&types.ClientAuth{
+ err = setAuth(&shared.ClientAuth{
ClientAccount: *selected,
OrgId: org.Id,
OrgName: org.Name,
+ OrgIsTrial: org.IsTrial,
IntegratedModelsMode: org.IntegratedModelsMode,
})
@@ -225,8 +225,8 @@ func signIn(email, pin, host string) error {
return fmt.Errorf("error signing in: %v", apiErr.Msg)
}
- err := setAuth(&types.ClientAuth{
- ClientAccount: types.ClientAccount{
+ err := setAuth(&shared.ClientAuth{
+ ClientAccount: shared.ClientAccount{
Email: res.Email,
UserId: res.UserId,
UserName: res.UserName,
@@ -283,8 +283,8 @@ func createAccount(email, pin, host string) error {
return fmt.Errorf("error creating account: %v", apiErr.Msg)
}
- err = setAuth(&types.ClientAuth{
- ClientAccount: types.ClientAccount{
+ err = setAuth(&shared.ClientAuth{
+ ClientAccount: shared.ClientAccount{
Email: res.Email,
UserId: res.UserId,
UserName: res.UserName,
diff --git a/app/cli/auth/auth.go b/app/cli/auth/auth.go
index 28e2aad8..cb7171fe 100644
--- a/app/cli/auth/auth.go
+++ b/app/cli/auth/auth.go
@@ -6,7 +6,8 @@ import (
"os"
"plandex/fs"
"plandex/term"
- "plandex/types"
+
+ "github.com/plandex/plandex/shared"
)
func MustResolveAuthWithOrg() {
@@ -35,7 +36,7 @@ func MustResolveAuth(requireOrg bool) {
}
}
- var auth types.ClientAuth
+ var auth shared.ClientAuth
err = json.Unmarshal(bytes, &auth)
if err != nil {
term.OutputErrorAndExit("error unmarshalling auth.json: %v", err)
diff --git a/app/cli/auth/state.go b/app/cli/auth/state.go
index 2c9c4009..bc7160b1 100644
--- a/app/cli/auth/state.go
+++ b/app/cli/auth/state.go
@@ -5,24 +5,25 @@ import (
"fmt"
"os"
"plandex/fs"
- "plandex/types"
+
+ "github.com/plandex/plandex/shared"
)
-var Current *types.ClientAuth
+var Current *shared.ClientAuth
-func loadAccounts() ([]*types.ClientAccount, error) {
+func loadAccounts() ([]*shared.ClientAccount, error) {
bytes, err := os.ReadFile(fs.HomeAccountsPath)
if err != nil {
if os.IsNotExist(err) {
// no accounts
- return []*types.ClientAccount{}, nil
+ return []*shared.ClientAccount{}, nil
} else {
return nil, fmt.Errorf("error reading accounts.json: %v", err)
}
}
- var accounts []*types.ClientAccount
+ var accounts []*shared.ClientAccount
err = json.Unmarshal(bytes, &accounts)
if err != nil {
@@ -32,7 +33,7 @@ func loadAccounts() ([]*types.ClientAccount, error) {
return accounts, nil
}
-func setAuth(auth *types.ClientAuth) error {
+func setAuth(auth *shared.ClientAuth) error {
err := storeAccount(&auth.ClientAccount)
if err != nil {
@@ -50,7 +51,7 @@ func setAuth(auth *types.ClientAuth) error {
return nil
}
-func storeAccount(toStore *types.ClientAccount) error {
+func storeAccount(toStore *shared.ClientAccount) error {
accounts, err := loadAccounts()
if err != nil {
diff --git a/app/cli/auth/trial.go b/app/cli/auth/trial.go
index 0ec63981..553a4c0b 100644
--- a/app/cli/auth/trial.go
+++ b/app/cli/auth/trial.go
@@ -3,7 +3,6 @@ package auth
import (
"fmt"
"plandex/term"
- "plandex/types"
"github.com/fatih/color"
"github.com/plandex/plandex/shared"
@@ -58,8 +57,8 @@ func ConvertTrial() error {
return fmt.Errorf("error converting trial: %v", apiErr)
}
- err = setAuth(&types.ClientAuth{
- ClientAccount: types.ClientAccount{
+ err = setAuth(&shared.ClientAuth{
+ ClientAccount: shared.ClientAccount{
Email: res.Email,
UserId: res.UserId,
UserName: res.UserName,
@@ -69,6 +68,7 @@ func ConvertTrial() error {
},
OrgId: res.Orgs[0].Id,
OrgName: res.Orgs[0].Id,
+ OrgIsTrial: res.Orgs[0].IsTrial,
IntegratedModelsMode: res.Orgs[0].IntegratedModelsMode,
})
@@ -154,8 +154,8 @@ func startTrial() error {
return fmt.Errorf("error starting trial: %v", apiErr)
}
- err = setAuth(&types.ClientAuth{
- ClientAccount: types.ClientAccount{
+ err = setAuth(&shared.ClientAuth{
+ ClientAccount: shared.ClientAccount{
Email: email,
UserId: res.UserId,
UserName: name,
@@ -186,8 +186,8 @@ func startTrial() error {
// return fmt.Errorf("error starting trial: %v", apiErr.Msg)
// }
-// err := setAuth(&types.ClientAuth{
-// ClientAccount: types.ClientAccount{
+// err := setAuth(&shared.ClientAuth{
+// ClientAccount: shared.ClientAccount{
// Email: res.Email,
// UserId: res.UserId,
// UserName: res.UserName,
diff --git a/app/cli/cmd/credits_log.go b/app/cli/cmd/credits_log.go
index a140a800..44d3c164 100644
--- a/app/cli/cmd/credits_log.go
+++ b/app/cli/cmd/credits_log.go
@@ -121,18 +121,23 @@ func creditsLog(cmd *cobra.Command, args []string) {
table.Render()
- pageLine := fmt.Sprintf("Page size %d. Showing page %d of %d", logCreditsPageSize, logCreditsPage, res.NumPages)
- if res.NumPagesMax {
- pageLine += "+"
- }
+ var output string
+ var pageLine string
- output := pageLine + "\n\n" + tableString.String()
+ if res.NumPages > 1 {
+ pageLine = fmt.Sprintf("Page size %d. Showing page %d of %d", logCreditsPageSize, logCreditsPage, res.NumPages)
+ if res.NumPagesMax {
+ pageLine = "+"
+ }
+ output = pageLine + "\n\n" + tableString.String()
+ } else {
+ output = tableString.String()
+ }
term.PageOutput(output)
var inputFn func()
inputFn = func() {
-
fmt.Println("\n" + pageLine)
prompts := []string{}
@@ -145,7 +150,7 @@ func creditsLog(cmd *cobra.Command, args []string) {
prompts = append(prompts, "Press 'p' for previous page")
}
- prompts = append(prompts, "Press any number to jump to a page")
+ prompts = append(prompts, "Type any number and press enter to jump to a page")
prompts = append(prompts, "Press 'q' to quit")
@@ -195,6 +200,16 @@ func creditsLog(cmd *cobra.Command, args []string) {
if unicode.IsDigit(char) {
numberInput.WriteRune(char)
fmt.Print(string(char)) // Show the digit
+ } else if key == keyboard.KeyBackspace || key == keyboard.KeyBackspace2 {
+ // Handle backspace
+ if numberInput.Len() > 0 {
+ // Remove the last rune
+ input := numberInput.String()
+ numberInput.Reset()
+ numberInput.WriteString(input[:len(input)-1])
+ fmt.Print("\b \b") // Erase the digit
+ }
+
} else {
// Handle invalid input while typing a number
fmt.Println()
@@ -237,6 +252,7 @@ func creditsLog(cmd *cobra.Command, args []string) {
}
- inputFn()
-
+ if res.NumPages > 1 {
+ inputFn()
+ }
}
diff --git a/app/cli/nodemon.json b/app/cli/nodemon.json
new file mode 100644
index 00000000..5b22fe0e
--- /dev/null
+++ b/app/cli/nodemon.json
@@ -0,0 +1,8 @@
+{
+ "watch": [
+ ".",
+ "../shared"
+ ],
+ "ext": "go,mod,sum",
+ "exec": "./dev.sh"
+}
\ No newline at end of file
diff --git a/app/cli/types/types.go b/app/cli/types/types.go
index 65567acb..99c176c6 100644
--- a/app/cli/types/types.go
+++ b/app/cli/types/types.go
@@ -5,23 +5,6 @@ import (
"github.com/sashabaranov/go-openai"
)
-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"`
- IsTrial bool `json:"isTrial"`
-}
-
-type ClientAuth struct {
- ClientAccount
- OrgId string `json:"orgId"`
- OrgName string `json:"orgName"`
- IntegratedModelsMode bool `json:"integratedModelsMode"`
-}
-
type LoadContextParams struct {
Note string
Recursive bool
diff --git a/app/server/handlers/auth_helpers.go b/app/server/handlers/auth_helpers.go
index 8f1fc45d..605b8218 100644
--- a/app/server/handlers/auth_helpers.go
+++ b/app/server/handlers/auth_helpers.go
@@ -3,6 +3,7 @@ package handlers
import (
"encoding/base64"
"encoding/json"
+ "fmt"
"log"
"net/http"
"plandex-server/db"
@@ -15,39 +16,17 @@ import (
func Authenticate(w http.ResponseWriter, r *http.Request, requireOrg bool) *types.ServerAuth {
log.Println("authenticating request")
- authHeader := r.Header.Get("Authorization")
-
- if authHeader == "" {
- log.Println("no auth header")
- http.Error(w, "no auth header", http.StatusUnauthorized)
- return nil
- }
-
- if !strings.HasPrefix(authHeader, "Bearer ") {
- log.Println("invalid auth header")
- http.Error(w, "invalid auth header", http.StatusUnauthorized)
- return nil
- }
-
- // strip off the "Bearer " prefix
- encoded := strings.TrimPrefix(authHeader, "Bearer ")
-
- // decode the base64-encoded credentials
- bytes, err := base64.StdEncoding.DecodeString(encoded)
+ parsed, err := GetAuthHeader(r)
if err != nil {
- log.Printf("error decoding auth token: %v\n", err)
- http.Error(w, "error decoding auth token", http.StatusUnauthorized)
+ log.Printf("error getting auth header: %v\n", err)
+ http.Error(w, "error getting auth header", http.StatusInternalServerError)
return nil
}
- // parse the credentials
- var parsed shared.AuthHeader
- err = json.Unmarshal(bytes, &parsed)
-
- if err != nil {
- log.Printf("error parsing auth token: %v\n", err)
- http.Error(w, "error parsing auth token", http.StatusUnauthorized)
+ if parsed == nil {
+ log.Println("no auth header")
+ http.Error(w, "no auth header", http.StatusUnauthorized)
return nil
}
@@ -149,6 +128,167 @@ func Authenticate(w http.ResponseWriter, r *http.Request, requireOrg bool) *type
}
+func GetAuthHeader(r *http.Request) (*shared.AuthHeader, error) {
+ authHeader := r.Header.Get("Authorization")
+
+ // check for a cookie as well for ui requests
+ if authHeader == "" {
+ // Try to get auth token from a cookie as a fallback
+ cookie, err := r.Cookie("authToken")
+ if err != nil {
+ if err == http.ErrNoCookie {
+ return nil, nil
+ }
+ return nil, fmt.Errorf("error retrieving auth cookie: %v", err)
+ }
+ // Use the token from the cookie as the fallback authorization header
+ authHeader = cookie.Value
+ }
+
+ if authHeader == "" {
+ return nil, nil
+ }
+
+ if !strings.HasPrefix(authHeader, "Bearer ") {
+ return nil, fmt.Errorf("invalid auth header")
+ }
+
+ // strip off the "Bearer " prefix
+ encoded := strings.TrimPrefix(authHeader, "Bearer ")
+
+ // decode the base64-encoded credentials
+ bytes, err := base64.StdEncoding.DecodeString(encoded)
+
+ if err != nil {
+ return nil, fmt.Errorf("error decoding auth token: %v", err)
+ }
+
+ // parse the credentials
+ var parsed shared.AuthHeader
+ err = json.Unmarshal(bytes, &parsed)
+
+ if err != nil {
+ return nil, fmt.Errorf("error parsing auth token: %v", err)
+ }
+
+ return &parsed, nil
+}
+
+func SetAuthCookieIfBrowser(w http.ResponseWriter, r *http.Request, user *db.User, token, orgId string) error {
+ isBrowser := false
+ acceptHeader := r.Header.Get("Accept")
+ if strings.Contains(acceptHeader, "text/html") {
+ isBrowser = true
+ }
+ if !isBrowser {
+ return nil
+ }
+
+ if token == "" {
+ authHeader, err := GetAuthHeader(r)
+ if err != nil {
+ return fmt.Errorf("error getting auth header: %v", err)
+ }
+ token = authHeader.Token
+ }
+
+ if token == "" {
+ return fmt.Errorf("no token")
+ }
+
+ // set authToken cookie
+ authHeader := shared.AuthHeader{
+ Token: token,
+ OrgId: 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)
+
+ http.SetCookie(w, &http.Cookie{
+ Name: "authToken",
+ Value: "Bearer " + token,
+ Secure: true,
+ HttpOnly: true,
+ SameSite: http.SameSiteStrictMode,
+ })
+
+ storedAccounts, err := GetAccountsFromCookie(r)
+
+ if err != nil {
+ return fmt.Errorf("error getting accounts from cookie: %v", err)
+ }
+
+ found := false
+ for _, account := range storedAccounts {
+ if account.UserId == user.Id {
+ found = true
+
+ account.Token = token
+ account.Email = user.Email
+ account.UserName = user.Name
+ break
+ }
+ }
+
+ if !found {
+ storedAccounts = append(storedAccounts, &shared.ClientAccount{
+ Email: user.Email,
+ UserName: user.Name,
+ UserId: user.Id,
+ Token: token,
+ })
+ }
+
+ bytes, err = json.Marshal(storedAccounts)
+
+ if err != nil {
+ return fmt.Errorf("error marshalling accounts: %v", err)
+ }
+
+ // base64 encode
+ accounts := base64.StdEncoding.EncodeToString(bytes)
+
+ http.SetCookie(w, &http.Cookie{
+ Name: "accounts",
+ Value: accounts,
+ Secure: true,
+ HttpOnly: true,
+ SameSite: http.SameSiteStrictMode,
+ })
+
+ return nil
+}
+
+func GetAccountsFromCookie(r *http.Request) ([]*shared.ClientAccount, error) {
+ accountsCookie, err := r.Cookie("accounts")
+
+ if err == http.ErrNoCookie {
+ return []*shared.ClientAccount{}, nil
+ } else if err != nil {
+ return nil, fmt.Errorf("error getting accounts cookie: %v", err)
+ }
+
+ bytes, err := base64.StdEncoding.DecodeString(accountsCookie.Value)
+ if err != nil {
+ return nil, fmt.Errorf("error decoding accounts cookie: %v", err)
+ }
+
+ var accounts []*shared.ClientAccount
+ err = json.Unmarshal(bytes, &accounts)
+ if err != nil {
+ return nil, fmt.Errorf("error unmarshalling accounts cookie: %v", err)
+ }
+
+ return accounts, nil
+}
+
func authorizeProject(w http.ResponseWriter, projectId string, auth *types.ServerAuth) bool {
return authorizeProjectOptional(w, projectId, auth, true)
}
diff --git a/app/server/handlers/orgs.go b/app/server/handlers/orgs.go
index 5ffaf5b1..98284bde 100644
--- a/app/server/handlers/orgs.go
+++ b/app/server/handlers/orgs.go
@@ -163,6 +163,13 @@ func CreateOrgHandler(w http.ResponseWriter, r *http.Request) {
return
}
+ err = SetAuthCookieIfBrowser(w, r, auth.User, "", org.Id)
+ if err != nil {
+ log.Printf("Error setting auth cookie: %v\n", err)
+ http.Error(w, "Error setting auth cookie: "+err.Error(), http.StatusInternalServerError)
+ return
+ }
+
log.Println("Successfully created org")
w.Write(bytes)
@@ -193,6 +200,13 @@ func GetOrgSessionHandler(w http.ResponseWriter, r *http.Request) {
return
}
+ err = SetAuthCookieIfBrowser(w, r, auth.User, "", org.Id)
+ if err != nil {
+ log.Printf("Error setting auth cookie: %v\n", err)
+ http.Error(w, "Error setting auth cookie: "+err.Error(), http.StatusInternalServerError)
+ return
+ }
+
w.Write(bytes)
log.Println("Successfully got org session")
diff --git a/app/server/handlers/sessions.go b/app/server/handlers/sessions.go
index 0a063ee6..6e218bc6 100644
--- a/app/server/handlers/sessions.go
+++ b/app/server/handlers/sessions.go
@@ -257,6 +257,14 @@ func SignInHandler(w http.ResponseWriter, r *http.Request) {
return
}
+ // org still needs to be selected
+ err = SetAuthCookieIfBrowser(w, r, user, token, "")
+ if err != nil {
+ log.Printf("Error setting auth cookie: %v\n", err)
+ http.Error(w, "Error setting auth cookie: "+err.Error(), http.StatusInternalServerError)
+ return
+ }
+
log.Println("Successfully signed in")
w.Write(bytes)
diff --git a/app/server/main.go b/app/server/main.go
index d65de4c2..d15348fd 100644
--- a/app/server/main.go
+++ b/app/server/main.go
@@ -1,7 +1,9 @@
package main
import (
+ "fmt"
"log"
+ "os"
"plandex-server/setup"
"github.com/gorilla/mux"
@@ -11,8 +13,19 @@ func main() {
// Configure the default logger to include milliseconds in timestamps
log.SetFlags(log.LstdFlags | log.Lmicroseconds)
+ var domain string
+ if os.Getenv("DOMAIN") != "" {
+ domain = os.Getenv("DOMAIN")
+ } else if os.Getenv("GOENV") == "development" {
+ domain = "localhost"
+ } else {
+ panic(fmt.Errorf("DOMAIN environment variable is required unless GOENV is set to development"))
+ }
+
r := mux.NewRouter()
+ apiRouter := r.Host("api." + domain).Subrouter()
+
setup.MustLoadIp()
setup.MustInitDb()
- setup.StartServer(r)
+ setup.StartServer(apiRouter)
}
diff --git a/app/server/routes/routes.go b/app/server/routes/routes.go
index b037c93e..4ff84543 100644
--- a/app/server/routes/routes.go
+++ b/app/server/routes/routes.go
@@ -9,7 +9,7 @@ import (
"github.com/gorilla/mux"
)
-func AddRoutes(r *mux.Router) {
+func AddApiRoutes(r *mux.Router) {
r.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "OK")
})
diff --git a/app/server/setup/setup.go b/app/server/setup/setup.go
index d3b3f2b6..29070243 100644
--- a/app/server/setup/setup.go
+++ b/app/server/setup/setup.go
@@ -52,7 +52,7 @@ func StartServer(r *mux.Router) {
externalPort = "8080"
}
- routes.AddRoutes(r)
+ routes.AddApiRoutes(r)
// Enable CORS based on environment
var corsHandler http.Handler
diff --git a/app/shared/auth.go b/app/shared/auth.go
index 3207e9c2..38fcebe8 100644
--- a/app/shared/auth.go
+++ b/app/shared/auth.go
@@ -40,3 +40,21 @@ type ApiError struct {
// only used for trial messages exceeded error
TrialMessagesExceededError *TrialMessagesExceededError `json:"trialMessagesExceededError,omitempty"`
}
+
+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"`
+ IsTrial bool `json:"isTrial"`
+}
+
+type ClientAuth struct {
+ ClientAccount
+ OrgId string `json:"orgId"`
+ OrgName string `json:"orgName"`
+ OrgIsTrial bool `json:"orgIsTrial"`
+ IntegratedModelsMode bool `json:"integratedModelsMode"`
+}
diff --git a/app/shared/data_models.go b/app/shared/data_models.go
index 80154fdd..c340318f 100644
--- a/app/shared/data_models.go
+++ b/app/shared/data_models.go
@@ -11,8 +11,9 @@ import (
)
type Org struct {
- Id string `json:"id"`
- Name string `json:"name"`
+ Id string `json:"id"`
+ Name string `json:"name"`
+ IsTrial bool `json:"isTrial"`
// optional cloud attributes
IntegratedModelsMode bool `json:"integratedModelsMode,omitempty"`