Skip to content

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

Update API endpoints and handlers with improved error handling and request flow

Dane Schneiderbbcfa7294a31
diff --git a/app/cli/api/clients.go b/app/cli/api/clients.go
index 61156283..3ba98166 100644
--- a/app/cli/api/clients.go
+++ b/app/cli/api/clients.go
@@ -25,7 +25,7 @@ func init() {
CloudApiHost = "http://localhost:8099"
}
} else {
- CloudApiHost = "https://api.plandex.ai"
+ CloudApiHost = "https://api-v2.plandex.ai"
}
}
diff --git a/app/cli/api/methods.go b/app/cli/api/methods.go
index 2de8db1b..a6bf4338 100644
--- a/app/cli/api/methods.go
+++ b/app/cli/api/methods.go
@@ -656,7 +656,20 @@ func (a *Api) StopPlan(ctx context.Context, planId, branch string) *shared.ApiEr
}
func (a *Api) GetCurrentPlanState(planId, branch string) (*shared.CurrentPlanState, *shared.ApiError) {
- serverUrl := fmt.Sprintf("%s/plans/%s/%s/current_plan", GetApiHost(), planId, branch)
+ return a.getCurrentPlanState(planId, branch, "")
+}
+
+func (a *Api) GetCurrentPlanStateAtSha(planId, sha string) (*shared.CurrentPlanState, *shared.ApiError) {
+ return a.getCurrentPlanState(planId, "", sha)
+}
+
+func (a *Api) getCurrentPlanState(planId, branch, sha string) (*shared.CurrentPlanState, *shared.ApiError) {
+ var serverUrl string
+ if sha != "" {
+ serverUrl = fmt.Sprintf("%s/plans/%s/current_plan/%s", GetApiHost(), planId, sha)
+ } else {
+ serverUrl = fmt.Sprintf("%s/plans/%s/%s/current_plan", GetApiHost(), planId, branch)
+ }
resp, err := authenticatedFastClient.Get(serverUrl)
if err != nil {
@@ -669,7 +682,7 @@ func (a *Api) GetCurrentPlanState(planId, branch string) (*shared.CurrentPlanSta
apiErr := HandleApiError(resp, errorBody)
tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
if tokenRefreshed {
- return a.GetCurrentPlanState(planId, branch)
+ return a.getCurrentPlanState(planId, branch, sha)
}
return nil, apiErr
}
diff --git a/app/server/handlers/context_helper.go b/app/server/handlers/context_helper.go
index 4c56bdd5..d339ca61 100644
--- a/app/server/handlers/context_helper.go
+++ b/app/server/handlers/context_helper.go
@@ -13,15 +13,29 @@ import (
shared "plandex-shared"
)
+type loadContextsParams struct {
+ w http.ResponseWriter
+ r *http.Request
+ auth *types.ServerAuth
+ loadReq *shared.LoadContextRequest
+ plan *db.Plan
+ branchName string
+ cachedMapsByPath map[string]*db.CachedMap
+ autoLoaded bool
+}
+
func loadContexts(
- w http.ResponseWriter,
- r *http.Request,
- auth *types.ServerAuth,
- loadReq *shared.LoadContextRequest,
- plan *db.Plan,
- branchName string,
- cachedMapsByPath map[string]*db.CachedMap,
+ params loadContextsParams,
) (*shared.LoadContextResponse, []*db.Context) {
+ w := params.w
+ r := params.r
+ auth := params.auth
+ loadReq := params.loadReq
+ plan := params.plan
+ branchName := params.branchName
+ cachedMapsByPath := params.cachedMapsByPath
+ autoLoaded := params.autoLoaded
+
// check file count and size limits
totalFiles := 0
for _, context := range *loadReq {
@@ -144,6 +158,7 @@ func loadContexts(
Req: loadReq,
UserId: auth.User.Id,
CachedMapsByPath: cachedMapsByPath,
+ AutoLoaded: autoLoaded,
})
if err != nil {
diff --git a/app/server/handlers/file_maps.go b/app/server/handlers/file_maps.go
index 692868cd..2777560f 100644
--- a/app/server/handlers/file_maps.go
+++ b/app/server/handlers/file_maps.go
@@ -166,7 +166,15 @@ func LoadCachedFileMapHandler(w http.ResponseWriter, r *http.Request) {
})
}
- loadRes, _ = loadContexts(w, r, auth, &loadReq, plan, branchName, cachedMapsByPath)
+ loadRes, _ = loadContexts(loadContextsParams{
+ w: w,
+ r: r,
+ auth: auth,
+ loadReq: &loadReq,
+ plan: plan,
+ branchName: branchName,
+ cachedMapsByPath: cachedMapsByPath,
+ })
if loadRes == nil {
log.Println("LoadCachedFileMapHandler - loadRes is nil")
diff --git a/app/server/handlers/fs_helper.go b/app/server/handlers/fs_helper.go
index 812c02e0..92768007 100644
--- a/app/server/handlers/fs_helper.go
+++ b/app/server/handlers/fs_helper.go
@@ -12,13 +12,21 @@ import (
"github.com/gorilla/mux"
)
+const locksVerboseLogging = true
+
func LockRepo(w http.ResponseWriter, r *http.Request, auth *types.ServerAuth, scope db.LockScope, ctx context.Context, cancelFn context.CancelFunc, requireBranch bool) *func(err error) {
vars := mux.Vars(r)
planId := vars["planId"]
branch := vars["branch"]
+ if locksVerboseLogging {
+ log.Printf("LockRepo: %s, planId: %s, branch: %s", scope, planId, branch)
+ }
+
if requireBranch && branch == "" {
- log.Println("Branch not specified")
+ if locksVerboseLogging {
+ log.Println("Branch not specified")
+ }
http.Error(w, "Branch not specified", http.StatusBadRequest)
return nil
}
@@ -30,6 +38,10 @@ func LockRepoForBranch(w http.ResponseWriter, r *http.Request, auth *types.Serve
vars := mux.Vars(r)
planId := vars["planId"]
+ if locksVerboseLogging {
+ log.Printf("LockRepoForBranch: %s, planId: %s, branch: %s", scope, planId, branch)
+ }
+
return lockRepo(w, r, auth, scope, ctx, cancelFn, planId, branch)
}
@@ -53,6 +65,10 @@ func lockRepo(w http.ResponseWriter, r *http.Request, auth *types.ServerAuth, sc
}
}
+ if locksVerboseLogging {
+ log.Printf("lockRepo: %s, planId: %s, branch: %s", params.Scope, params.PlanId, params.Branch)
+ }
+
repoLockId, err := db.LockRepo(params)
if err != nil {
@@ -74,7 +90,7 @@ func lockRepo(w http.ResponseWriter, r *http.Request, auth *types.ServerAuth, sc
}
// log.Println("Rolling back repo if error")
- err = RollbackRepoIfErr(auth.OrgId, planId, err)
+ err = RollbackRepoIfErr(auth.OrgId, planId, branch, err)
if err != nil {
log.Printf("Error rolling back repo: %v\n", err)
}
@@ -88,7 +104,7 @@ func lockRepo(w http.ResponseWriter, r *http.Request, auth *types.ServerAuth, sc
return &fn
}
-func RollbackRepoIfErr(orgId, planId string, err error) error {
+func RollbackRepoIfErr(orgId, planId, branch string, err error) error {
// if no error, return nil
if err == nil {
log.Println("No error, not rolling back repo")
@@ -98,7 +114,7 @@ func RollbackRepoIfErr(orgId, planId string, err error) error {
log.Println("Rolling back repo due to error")
// if any errors, rollback repo
- err = db.GitClearUncommittedChanges(orgId, planId)
+ err = db.GitClearUncommittedChanges(orgId, planId, branch)
if err != nil {
return fmt.Errorf("error clearing uncommitted changes: %v", err)
diff --git a/app/server/handlers/plans_changes.go b/app/server/handlers/plans_changes.go
index d331ade0..f24384a6 100644
--- a/app/server/handlers/plans_changes.go
+++ b/app/server/handlers/plans_changes.go
@@ -26,8 +26,10 @@ func CurrentPlanHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
planId := vars["planId"]
+ branch := vars["branch"]
+ sha := vars["sha"]
- log.Println("planId: ", planId)
+ log.Println("planId: ", planId, "branch: ", branch, "sha: ", sha)
if authorizePlan(w, planId, auth) == nil {
return
@@ -39,7 +41,14 @@ func CurrentPlanHandler(w http.ResponseWriter, r *http.Request) {
var err error
ctx, cancel := context.WithCancel(r.Context())
- unlockFn := LockRepo(w, r, auth, db.LockScopeRead, ctx, cancel, true)
+ scope := db.LockScopeRead
+ requireBranch := true
+ if sha != "" {
+ scope = db.LockScopeWrite
+ requireBranch = false
+ }
+ log.Printf("locking with scope: %s", scope)
+ unlockFn := LockRepo(w, r, auth, scope, ctx, cancel, requireBranch)
if unlockFn == nil {
return
} else {
@@ -48,6 +57,22 @@ func CurrentPlanHandler(w http.ResponseWriter, r *http.Request) {
}()
}
+ if sha != "" {
+ err = db.GitCheckoutSha(auth.OrgId, planId, sha)
+ if err != nil {
+ log.Printf("Error checking out sha: %v\n", err)
+ http.Error(w, "Error checking out sha: "+err.Error(), http.StatusInternalServerError)
+ return
+ }
+
+ defer func() {
+ checkoutErr := db.GitCheckoutBranch(auth.OrgId, planId, branch)
+ if checkoutErr != nil {
+ log.Printf("Error checking out branch: %v\n", checkoutErr)
+ }
+ }()
+ }
+
planState, err := db.GetCurrentPlanState(db.CurrentPlanStateParams{
OrgId: auth.OrgId,
PlanId: planId,
@@ -83,7 +108,7 @@ func ApplyPlanHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
planId := vars["planId"]
branch := vars["branch"]
- log.Println("planId: ", planId)
+ log.Println("planId: ", planId, "branch: ", branch)
plan := authorizePlan(w, planId, auth)
if plan == nil {
@@ -128,14 +153,23 @@ func ApplyPlanHandler(w http.ResponseWriter, r *http.Request) {
return
}
- currentPlan, err := db.ApplyPlan(ctx, auth.OrgId, auth.User.Id, branch, plan)
+ currentPlanParams, err := db.GetFullCurrentPlanStateParams(auth.OrgId, planId)
+ if err != nil {
+ log.Printf("Error getting current plan state params: %v\n", err)
+ http.Error(w, "Error getting current plan state params: "+err.Error(), http.StatusInternalServerError)
+ return
+ }
+
+ currentPlan, err := db.GetCurrentPlanState(currentPlanParams)
if err != nil {
- log.Printf("Error applying plan: %v\n", err)
- http.Error(w, "Error applying plan: "+err.Error(), http.StatusInternalServerError)
+ log.Printf("Error getting current plan state: %v\n", err)
+ http.Error(w, "Error getting current plan state: "+err.Error(), http.StatusInternalServerError)
return
}
+ log.Println("ApplyPlanHandler: Got current plan state:", currentPlan != nil)
+
clients := initClients(
initClientsParams{
w: w,
@@ -147,7 +181,7 @@ func ApplyPlanHandler(w http.ResponseWriter, r *http.Request) {
},
)
- s, err := modelPlan.GenCommitMsgForPendingResults(auth, plan, clients, settings, currentPlan, r.Context())
+ commitMsg, err := modelPlan.GenCommitMsgForPendingResults(auth, plan, clients, settings, currentPlan, r.Context())
if err != nil {
log.Printf("Error generating commit message: %v\n", err)
@@ -155,7 +189,23 @@ func ApplyPlanHandler(w http.ResponseWriter, r *http.Request) {
return
}
- w.Write([]byte(s))
+ err = db.ApplyPlan(ctx, db.ApplyPlanParams{
+ OrgId: auth.OrgId,
+ UserId: auth.User.Id,
+ BranchName: branch,
+ Plan: plan,
+ CurrentPlanState: currentPlan,
+ CurrentPlanStateParams: &currentPlanParams,
+ CommitMsg: commitMsg,
+ })
+
+ if err != nil {
+ log.Printf("Error applying plan: %v\n", err)
+ http.Error(w, "Error applying plan: "+err.Error(), http.StatusInternalServerError)
+ return
+ }
+
+ w.Write([]byte(commitMsg))
log.Println("Successfully applied plan", planId)
}
diff --git a/app/server/handlers/plans_context.go b/app/server/handlers/plans_context.go
index b7786fb3..04600f62 100644
--- a/app/server/handlers/plans_context.go
+++ b/app/server/handlers/plans_context.go
@@ -161,7 +161,14 @@ func LoadContextHandler(w http.ResponseWriter, r *http.Request) {
return
}
- res, _ := loadContexts(w, r, auth, &requestBody, plan, branchName, nil)
+ res, _ := loadContexts(loadContextsParams{
+ w: w,
+ r: r,
+ auth: auth,
+ loadReq: &requestBody,
+ plan: plan,
+ branchName: branchName,
+ })
if res == nil {
return
diff --git a/app/server/handlers/plans_exec.go b/app/server/handlers/plans_exec.go
index a6e6afb6..b2243c0c 100644
--- a/app/server/handlers/plans_exec.go
+++ b/app/server/handlers/plans_exec.go
@@ -325,14 +325,22 @@ func RespondMissingFileHandler(w http.ResponseWriter, r *http.Request) {
if requestBody.Choice == shared.RespondMissingFileChoiceLoad {
log.Println("loading missing file")
- res, dbContexts := loadContexts(w, r, auth, &shared.LoadContextRequest{
- &shared.LoadContextParams{
- ContextType: shared.ContextFileType,
- Name: requestBody.FilePath,
- FilePath: requestBody.FilePath,
- Body: requestBody.Body,
+ res, dbContexts := loadContexts(loadContextsParams{
+ w: w,
+ r: r,
+ auth: auth,
+ loadReq: &shared.LoadContextRequest{
+ &shared.LoadContextParams{
+ ContextType: shared.ContextFileType,
+ Name: requestBody.FilePath,
+ FilePath: requestBody.FilePath,
+ Body: requestBody.Body,
+ },
},
- }, plan, branch, nil)
+ plan: plan,
+ branchName: branch,
+ autoLoaded: true,
+ })
if res == nil {
return
}
@@ -408,7 +416,15 @@ func AutoLoadContextHandler(w http.ResponseWriter, r *http.Request) {
}
log.Println("AutoLoadContextHandler - loading contexts")
- res, dbContexts := loadContexts(w, r, auth, &requestBody, plan, branch, nil)
+ res, dbContexts := loadContexts(loadContextsParams{
+ w: w,
+ r: r,
+ auth: auth,
+ loadReq: &requestBody,
+ plan: plan,
+ branchName: branch,
+ autoLoaded: true,
+ })
if res == nil {
return
diff --git a/app/server/handlers/plans_versions.go b/app/server/handlers/plans_versions.go
index e6f77714..4ac63390 100644
--- a/app/server/handlers/plans_versions.go
+++ b/app/server/handlers/plans_versions.go
@@ -25,7 +25,7 @@ func ListLogsHandler(w http.ResponseWriter, r *http.Request) {
planId := vars["planId"]
branch := vars["branch"]
- log.Println("planId: ", planId)
+ log.Println("planId: ", planId, "branch: ", branch)
if authorizePlan(w, planId, auth) == nil {
return
diff --git a/app/server/routes/routes.go b/app/server/routes/routes.go
index 21cd2297..23d17292 100644
--- a/app/server/routes/routes.go
+++ b/app/server/routes/routes.go
@@ -102,6 +102,7 @@ func addApiRoutes(r *mux.Router, prefix string) {
r.HandleFunc(prefix+"/plans/{planId}", handlers.GetPlanHandler).Methods("GET")
r.HandleFunc(prefix+"/plans/{planId}", handlers.DeletePlanHandler).Methods("DELETE")
+ r.HandleFunc(prefix+"/plans/{planId}/current_plan/{sha}", handlers.CurrentPlanHandler).Methods("GET")
r.HandleFunc(prefix+"/plans/{planId}/{branch}/current_plan", handlers.CurrentPlanHandler).Methods("GET")
r.HandleFunc(prefix+"/plans/{planId}/{branch}/apply", handlers.ApplyPlanHandler).Methods("PATCH")
r.HandleFunc(prefix+"/plans/{planId}/archive", handlers.ArchivePlanHandler).Methods("PATCH")
diff --git a/app/server/setup/setup.go b/app/server/setup/setup.go
index caacff7b..3b8d7370 100644
--- a/app/server/setup/setup.go
+++ b/app/server/setup/setup.go
@@ -110,10 +110,11 @@ func StartServer(handler http.Handler, configureFn func(handler http.Handler) ht
// Capture SIGTERM and SIGINT signals
sigTermChan := make(chan os.Signal, 1)
+
signal.Notify(sigTermChan, syscall.SIGTERM, syscall.SIGINT)
- <-sigTermChan
- log.Println("Plandex server shutting down gracefully...")
+ sig := <-sigTermChan
+ log.Printf("Received signal %v, shutting down gracefully...\n", sig)
// Create a channel to track completion of active plans
plansDone := make(chan struct{})
diff --git a/app/shared/data_models.go b/app/shared/data_models.go
index e19ba49d..916e6206 100644
--- a/app/shared/data_models.go
+++ b/app/shared/data_models.go
@@ -110,23 +110,41 @@ type Context struct {
MapParts FileMapBodies `json:"mapParts,omitempty"`
MapShas map[string]string `json:"mapShas,omitempty"`
MapTokens map[string]int `json:"mapTokens,omitempty"`
+ AutoLoaded bool `json:"autoLoaded"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
+type TellStage string
+
+const (
+ TellStagePlanning TellStage = "planning"
+ TellStageImplementation TellStage = "implementation"
+)
+
+type PlanningPhase string
+
+const (
+ PlanningPhaseContext PlanningPhase = "context"
+ PlanningPhasePlanning PlanningPhase = "planning"
+)
+
+type CurrentStage struct {
+ TellStage TellStage
+ PlanningPhase PlanningPhase
+}
+
type ConvoMessageFlags struct {
DidMakePlan bool `json:"didMakePlan"`
+ DidRemoveTasks bool `json:"didRemoveTasks"`
DidMakeDebuggingPlan bool `json:"didMakeDebuggingPlan"`
DidLoadContext bool `json:"didLoadContext"`
- IsPlanningStage bool `json:"isPlanningStage"`
- IsContextStage bool `json:"isContextStage"`
- IsImplementationStage bool `json:"isImplementationStage"`
- IsFollowUpReply bool `json:"isFollowUpReply"`
+ CurrentStage CurrentStage
IsChat bool `json:"isChat"`
- NeedsFollowUpContext bool `json:"needsFollowUpContext"`
DidWriteCode bool `json:"didWriteCode"`
DidCompleteTask bool `json:"didCompleteTask"`
DidCompletePlan bool `json:"didCompletePlan"`
+ HasUnfinishedSubtasks bool `json:"hasUnfinishedSubtasks"`
}
type Subtask struct {
@@ -137,17 +155,19 @@ type Subtask struct {
}
type ConvoMessage struct {
- Id string `json:"id"`
- UserId string `json:"userId"`
- Role string `json:"role"`
- Tokens int `json:"tokens"`
- Num int `json:"num"`
- Message string `json:"message"`
- Stopped bool `json:"stopped"`
- Flags ConvoMessageFlags `json:"flags"`
- Subtask *Subtask `json:"subtask,omitempty"`
- AddedSubtasks []*Subtask `json:"addedSubtasks,omitempty"`
- CreatedAt time.Time `json:"createdAt"`
+ Id string `json:"id"`
+ UserId string `json:"userId"`
+ Role string `json:"role"`
+ Tokens int `json:"tokens"`
+ Num int `json:"num"`
+ Message string `json:"message"`
+ Stopped bool `json:"stopped"`
+ Flags ConvoMessageFlags `json:"flags"`
+ Subtask *Subtask `json:"subtask,omitempty"`
+ AddedSubtasks []*Subtask `json:"addedSubtasks,omitempty"`
+ RemovedSubtasks []string `json:"removedSubtasks,omitempty"`
+ ActiveContextIds []string `json:"activeContextIds"`
+ CreatedAt time.Time `json:"createdAt"`
}
type ConvoSummary struct {
@@ -260,7 +280,6 @@ type CurrentPlanFiles struct {
}
type PlanFileResultsByPath map[string][]*PlanFileResult
-
type PlanResult struct {
SortedPaths []string `json:"sortedPaths"`
FileResultsByPath PlanFileResultsByPath `json:"fileResultsByPath"`
@@ -268,10 +287,21 @@ type PlanResult struct {
ReplacementsByPath map[string][]*Replacement `json:"replacementsByPath"`
}
+type PlanApply struct {
+ Id string `json:"id"`
+ UserId string `json:"userId"`
+ ConvoMessageIds []string `json:"convoMessageIds"`
+ ConvoMessageDescriptionIds []string `json:"convoMessageDescriptionIds"`
+ PlanFileResultIds []string `json:"planFileResultIds"`
+ CommitMsg string `json:"commitMsg"`
+ CreatedAt time.Time `json:"createdAt"`
+}
+
type CurrentPlanState struct {
PlanResult *PlanResult `json:"planResult"`
CurrentPlanFiles *CurrentPlanFiles `json:"currentPlanFiles"`
ConvoMessageDescriptions []*ConvoMessageDescription `json:"convoMessageDescriptions"`
+ PlanApplies []*PlanApply `json:"planApplies"`
ContextsByPath map[string]*Context `json:"contextsByPath"`
}
diff --git a/app/shared/req_res.go b/app/shared/req_res.go
index 2c603dca..c1f367ce 100644
--- a/app/shared/req_res.go
+++ b/app/shared/req_res.go
@@ -117,23 +117,25 @@ const (
)
type TellPlanRequest struct {
- Prompt string `json:"prompt"`
- BuildMode BuildMode `json:"buildMode"`
- ConnectStream bool `json:"connectStream"`
- AutoContinue bool `json:"autoContinue"`
- IsUserContinue bool `json:"isUserContinue"`
- IsUserDebug bool `json:"isUserDebug"`
- IsApplyDebug bool `json:"isApplyDebug"`
- IsChatOnly bool `json:"isChatOnly"`
- AutoContext bool `json:"autoContext"`
- ExecEnabled bool `json:"execEnabled"`
- OsDetails string `json:"osDetails"`
- ApiKey string `json:"apiKey"` // deprecated
- Endpoint string `json:"endpoint"` // deprecated
- ApiKeys map[string]string `json:"apiKeys"`
- OpenAIBase string `json:"openAIBase"`
- OpenAIOrgId string `json:"openAIOrgId"`
- ProjectPaths map[string]bool `json:"projectPaths"`
+ Prompt string `json:"prompt"`
+ BuildMode BuildMode `json:"buildMode"`
+ ConnectStream bool `json:"connectStream"`
+ AutoContinue bool `json:"autoContinue"`
+ IsUserContinue bool `json:"isUserContinue"`
+ IsUserDebug bool `json:"isUserDebug"`
+ IsApplyDebug bool `json:"isApplyDebug"`
+ IsChatOnly bool `json:"isChatOnly"`
+ AutoContext bool `json:"autoContext"`
+ SmartContext bool `json:"smartContext"`
+ ExecEnabled bool `json:"execEnabled"`
+ OsDetails string `json:"osDetails"`
+ ApiKey string `json:"apiKey"` // deprecated
+ Endpoint string `json:"endpoint"` // deprecated
+ ApiKeys map[string]string `json:"apiKeys"`
+ OpenAIBase string `json:"openAIBase"`
+ OpenAIOrgId string `json:"openAIOrgId"`
+ ProjectPaths map[string]bool `json:"projectPaths"`
+ IsImplementationOfChat bool `json:"isImplementationOfChat"`
}
type BuildPlanRequest struct {