Skip to content

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

branches, server git repo locking, some work on host management

Dane Schneider0585747d0a94
diff --git a/app/cli/api/methods.go b/app/cli/api/methods.go
index 65fb4a95..5a564dce 100644
--- a/app/cli/api/methods.go
+++ b/app/cli/api/methods.go
@@ -161,7 +161,6 @@ func (a *Api) RenameProject(projectId string, req shared.RenameProjectRequest) *
return nil
}
-
func (a *Api) ListPlans(projectId string) ([]*shared.Plan, *shared.ApiError) {
serverUrl := fmt.Sprintf("%s/projects/%s/plans", getApiHost(), projectId)
@@ -173,9 +172,11 @@ func (a *Api) ListPlans(projectId string) ([]*shared.Plan, *shared.ApiError) {
if resp.StatusCode >= 400 {
errorBody, _ := io.ReadAll(resp.Body)
+
apiErr := handleApiError(resp, errorBody)
- tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
- if tokenRefreshed {
+
+ didRefresh, apiErr := refreshTokenIfNeeded(apiErr)
+ if didRefresh {
return a.ListPlans(projectId)
}
return nil, apiErr
@@ -190,6 +191,50 @@ func (a *Api) ListPlans(projectId string) ([]*shared.Plan, *shared.ApiError) {
return plans, nil
}
+func (a *Api) GetCurrentBranchByPlanId(projectId string, req shared.GetCurrentBranchByPlanIdRequest) (map[string]*shared.Branch, *shared.ApiError) {
+ serverUrl := fmt.Sprintf("%s/projects/%s/plans/current_branches", getApiHost(), projectId)
+
+ reqBytes, err := json.Marshal(req)
+ if err != nil {
+ return nil, &shared.ApiError{Msg: fmt.Sprintf("error marshalling request: %v", err)}
+ }
+
+ request, err := http.NewRequest(http.MethodPost, serverUrl, bytes.NewBuffer(reqBytes))
+
+ if err != nil {
+ return nil, &shared.ApiError{Msg: fmt.Sprintf("error creating request: %v", err)}
+ }
+
+ request.Header.Set("Content-Type", "application/json")
+
+ resp, err := authenticatedFastClient.Do(request)
+
+ if err != nil {
+ return nil, &shared.ApiError{Msg: fmt.Sprintf("error sending request: %v", err)}
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode >= 400 {
+ errorBody, _ := io.ReadAll(resp.Body)
+
+ apiErr := handleApiError(resp, errorBody)
+
+ didRefresh, apiErr := refreshTokenIfNeeded(apiErr)
+ if didRefresh {
+ return a.GetCurrentBranchByPlanId(projectId, req)
+ }
+ return nil, apiErr
+ }
+
+ var respBody map[string]*shared.Branch
+ err = json.NewDecoder(resp.Body).Decode(&respBody)
+ if err != nil {
+ return nil, &shared.ApiError{Msg: fmt.Sprintf("error decoding response: %v", err)}
+ }
+
+ return respBody, nil
+}
+
func (a *Api) ListArchivedPlans(projectId string) ([]*shared.Plan, *shared.ApiError) {
serverUrl := fmt.Sprintf("%s/projects/%s/plans/archive", getApiHost(), projectId)
@@ -364,9 +409,9 @@ func (a *Api) DeleteAllPlans(projectId string) *shared.ApiError {
return nil
}
-func (a *Api) TellPlan(planId string, req shared.TellPlanRequest, onStream types.OnStreamPlan) *shared.ApiError {
+func (a *Api) TellPlan(planId, branch string, req shared.TellPlanRequest, onStream types.OnStreamPlan) *shared.ApiError {
- serverUrl := fmt.Sprintf("%s/plans/%s/tell", getApiHost(), planId)
+ serverUrl := fmt.Sprintf("%s/plans/%s/%s/tell", getApiHost(), planId, branch)
reqBytes, err := json.Marshal(req)
if err != nil {
return &shared.ApiError{Msg: fmt.Sprintf("error marshalling request: %v", err)}
@@ -397,7 +442,7 @@ func (a *Api) TellPlan(planId string, req shared.TellPlanRequest, onStream types
didRefresh, apiErr := refreshTokenIfNeeded(apiErr)
if didRefresh {
- return a.TellPlan(planId, req, onStream)
+ return a.TellPlan(planId, branch, req, onStream)
}
return apiErr
}
@@ -410,8 +455,8 @@ func (a *Api) TellPlan(planId string, req shared.TellPlanRequest, onStream types
return nil
}
-func (a *Api) ConnectPlan(planId string, onStream types.OnStreamPlan) *shared.ApiError {
- serverUrl := fmt.Sprintf("%s/plans/%s/connect", getApiHost(), planId)
+func (a *Api) ConnectPlan(planId, branch string, onStream types.OnStreamPlan) *shared.ApiError {
+ serverUrl := fmt.Sprintf("%s/plans/%s/%s/connect", getApiHost(), planId, branch)
req, err := http.NewRequest(http.MethodPatch, serverUrl, nil)
if err != nil {
@@ -431,7 +476,7 @@ func (a *Api) ConnectPlan(planId string, onStream types.OnStreamPlan) *shared.Ap
didRefresh, apiErr := refreshTokenIfNeeded(apiErr)
if didRefresh {
- return a.ConnectPlan(planId, onStream)
+ return a.ConnectPlan(planId, branch, onStream)
}
return apiErr
@@ -442,8 +487,8 @@ func (a *Api) ConnectPlan(planId string, onStream types.OnStreamPlan) *shared.Ap
return nil
}
-func (a *Api) StopPlan(planId string) *shared.ApiError {
- serverUrl := fmt.Sprintf("%s/plans/%s/stop", getApiHost(), planId)
+func (a *Api) StopPlan(planId, branch string) *shared.ApiError {
+ serverUrl := fmt.Sprintf("%s/plans/%s/%s/stop", getApiHost(), planId, branch)
req, err := http.NewRequest(http.MethodDelete, serverUrl, nil)
if err != nil {
@@ -461,7 +506,7 @@ func (a *Api) StopPlan(planId string) *shared.ApiError {
apiErr := handleApiError(resp, errorBody)
didRefresh, apiErr := refreshTokenIfNeeded(apiErr)
if didRefresh {
- return a.StopPlan(planId)
+ return a.StopPlan(planId, branch)
}
return apiErr
}
@@ -469,8 +514,8 @@ func (a *Api) StopPlan(planId string) *shared.ApiError {
return nil
}
-func (a *Api) GetCurrentPlanState(planId string) (*shared.CurrentPlanState, *shared.ApiError) {
- serverUrl := fmt.Sprintf("%s/plans/%s/current_plan", getApiHost(), planId)
+func (a *Api) GetCurrentPlanState(planId, branch string) (*shared.CurrentPlanState, *shared.ApiError) {
+ serverUrl := fmt.Sprintf("%s/plans/%s/%s/current_plan", getApiHost(), planId, branch)
resp, err := authenticatedFastClient.Get(serverUrl)
if err != nil {
@@ -483,7 +528,7 @@ func (a *Api) GetCurrentPlanState(planId string) (*shared.CurrentPlanState, *sha
apiErr := handleApiError(resp, errorBody)
tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
if tokenRefreshed {
- return a.GetCurrentPlanState(planId)
+ return a.GetCurrentPlanState(planId, branch)
}
return nil, apiErr
}
@@ -497,8 +542,8 @@ func (a *Api) GetCurrentPlanState(planId string) (*shared.CurrentPlanState, *sha
return &state, nil
}
-func (a *Api) ApplyPlan(planId string) *shared.ApiError {
- serverUrl := fmt.Sprintf("%s/plans/%s/apply", getApiHost(), planId)
+func (a *Api) ApplyPlan(planId, branch string) *shared.ApiError {
+ serverUrl := fmt.Sprintf("%s/plans/%s/%s/apply", getApiHost(), planId, branch)
req, err := http.NewRequest(http.MethodPatch, serverUrl, nil)
if err != nil {
@@ -517,7 +562,7 @@ func (a *Api) ApplyPlan(planId string) *shared.ApiError {
didRefresh, apiErr := refreshTokenIfNeeded(apiErr)
if didRefresh {
- return a.ApplyPlan(planId)
+ return a.ApplyPlan(planId, branch)
}
return apiErr
}
@@ -553,8 +598,8 @@ func (a *Api) ArchivePlan(planId string) *shared.ApiError {
return nil
}
-func (a *Api) RejectAllChanges(planId string) *shared.ApiError {
- serverUrl := fmt.Sprintf("%s/plans/%s/reject_all", getApiHost(), planId)
+func (a *Api) RejectAllChanges(planId, branch string) *shared.ApiError {
+ serverUrl := fmt.Sprintf("%s/plans/%s/%s/reject_all", getApiHost(), planId, branch)
req, err := http.NewRequest(http.MethodPatch, serverUrl, nil)
if err != nil {
@@ -573,7 +618,7 @@ func (a *Api) RejectAllChanges(planId string) *shared.ApiError {
didRefresh, apiErr := refreshTokenIfNeeded(apiErr)
if didRefresh {
- return a.RejectAllChanges(planId)
+ return a.RejectAllChanges(planId, branch)
}
return apiErr
}
@@ -581,8 +626,8 @@ func (a *Api) RejectAllChanges(planId string) *shared.ApiError {
return nil
}
-func (a *Api) RejectResult(planId, resultId string) *shared.ApiError {
- serverUrl := fmt.Sprintf("%s/plans/%s/results/%s/reject", getApiHost(), planId, resultId)
+func (a *Api) RejectResult(planId, branch, resultId string) *shared.ApiError {
+ serverUrl := fmt.Sprintf("%s/plans/%s/%s/results/%s/reject", getApiHost(), planId, resultId)
req, err := http.NewRequest(http.MethodPatch, serverUrl, nil)
if err != nil {
@@ -600,7 +645,7 @@ func (a *Api) RejectResult(planId, resultId string) *shared.ApiError {
apiErr := handleApiError(resp, errorBody)
didRefresh, apiErr := refreshTokenIfNeeded(apiErr)
if didRefresh {
- a.RejectResult(planId, resultId)
+ a.RejectResult(planId, branch, resultId)
}
return apiErr
}
@@ -608,8 +653,8 @@ func (a *Api) RejectResult(planId, resultId string) *shared.ApiError {
return nil
}
-func (a *Api) RejectReplacement(planId, resultId, replacementId string) *shared.ApiError {
- serverUrl := fmt.Sprintf("%s/plans/%s/results/%s/replacements/%s/reject", getApiHost(), planId, resultId, replacementId)
+func (a *Api) RejectReplacement(planId, branch, resultId, replacementId string) *shared.ApiError {
+ serverUrl := fmt.Sprintf("%s/plans/%s/%s/results/%s/replacements/%s/reject", getApiHost(), planId, resultId, replacementId)
req, err := http.NewRequest(http.MethodPatch, serverUrl, nil)
if err != nil {
@@ -628,7 +673,7 @@ func (a *Api) RejectReplacement(planId, resultId, replacementId string) *shared.
didRefresh, apiErr := refreshTokenIfNeeded(apiErr)
if didRefresh {
- a.RejectReplacement(planId, resultId, replacementId)
+ a.RejectReplacement(planId, branch, resultId, replacementId)
}
return apiErr
}
@@ -636,8 +681,8 @@ func (a *Api) RejectReplacement(planId, resultId, replacementId string) *shared.
return nil
}
-func (a *Api) LoadContext(planId string, req shared.LoadContextRequest) (*shared.LoadContextResponse, *shared.ApiError) {
- serverUrl := fmt.Sprintf("%s/plans/%s/context", getApiHost(), planId)
+func (a *Api) LoadContext(planId, branch string, req shared.LoadContextRequest) (*shared.LoadContextResponse, *shared.ApiError) {
+ serverUrl := fmt.Sprintf("%s/plans/%s/%s/context", getApiHost(), planId, branch)
reqBytes, err := json.Marshal(req)
if err != nil {
return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error marshalling request: %v", err)}
@@ -655,7 +700,7 @@ func (a *Api) LoadContext(planId string, req shared.LoadContextRequest) (*shared
apiErr := handleApiError(resp, errorBody)
tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
if tokenRefreshed {
- return a.LoadContext(planId, req)
+ return a.LoadContext(planId, branch, req)
}
return nil, apiErr
}
@@ -669,8 +714,8 @@ func (a *Api) LoadContext(planId string, req shared.LoadContextRequest) (*shared
return &loadContextResponse, nil
}
-func (a *Api) UpdateContext(planId string, req shared.UpdateContextRequest) (*shared.UpdateContextResponse, *shared.ApiError) {
- serverUrl := fmt.Sprintf("%s/plans/%s/context", getApiHost(), planId)
+func (a *Api) UpdateContext(planId, branch string, req shared.UpdateContextRequest) (*shared.UpdateContextResponse, *shared.ApiError) {
+ serverUrl := fmt.Sprintf("%s/plans/%s/%s/context", getApiHost(), planId, branch)
reqBytes, err := json.Marshal(req)
if err != nil {
@@ -697,7 +742,7 @@ func (a *Api) UpdateContext(planId string, req shared.UpdateContextRequest) (*sh
apiErr := handleApiError(resp, errorBody)
tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
if tokenRefreshed {
- return a.UpdateContext(planId, req)
+ return a.UpdateContext(planId, branch, req)
}
return nil, apiErr
}
@@ -711,8 +756,8 @@ func (a *Api) UpdateContext(planId string, req shared.UpdateContextRequest) (*sh
return &updateContextResponse, nil
}
-func (a *Api) DeleteContext(planId string, req shared.DeleteContextRequest) (*shared.DeleteContextResponse, *shared.ApiError) {
- serverUrl := fmt.Sprintf("%s/plans/%s/context", getApiHost(), planId)
+func (a *Api) DeleteContext(planId, branch string, req shared.DeleteContextRequest) (*shared.DeleteContextResponse, *shared.ApiError) {
+ serverUrl := fmt.Sprintf("%s/plans/%s/%s/context", getApiHost(), planId, branch)
reqBytes, err := json.Marshal(req)
if err != nil {
return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error marshalling request: %v", err)}
@@ -735,7 +780,7 @@ func (a *Api) DeleteContext(planId string, req shared.DeleteContextRequest) (*sh
apiErr := handleApiError(resp, errorBody)
tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
if tokenRefreshed {
- return a.DeleteContext(planId, req)
+ return a.DeleteContext(planId, branch, req)
}
return nil, apiErr
}
@@ -749,8 +794,8 @@ func (a *Api) DeleteContext(planId string, req shared.DeleteContextRequest) (*sh
return &deleteContextResponse, nil
}
-func (a *Api) ListContext(planId string) ([]*shared.Context, *shared.ApiError) {
- serverUrl := fmt.Sprintf("%s/plans/%s/context", getApiHost(), planId)
+func (a *Api) ListContext(planId, branch string) ([]*shared.Context, *shared.ApiError) {
+ serverUrl := fmt.Sprintf("%s/plans/%s/%s/context", getApiHost(), planId, branch)
resp, err := authenticatedFastClient.Get(serverUrl)
if err != nil {
@@ -763,7 +808,7 @@ func (a *Api) ListContext(planId string) ([]*shared.Context, *shared.ApiError) {
apiErr := handleApiError(resp, errorBody)
tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
if tokenRefreshed {
- return a.ListContext(planId)
+ return a.ListContext(planId, branch)
}
return nil, apiErr
}
@@ -777,8 +822,8 @@ func (a *Api) ListContext(planId string) ([]*shared.Context, *shared.ApiError) {
return contexts, nil
}
-func (a *Api) ListConvo(planId string) ([]*shared.ConvoMessage, *shared.ApiError) {
- serverUrl := fmt.Sprintf("%s/plans/%s/convo", getApiHost(), planId)
+func (a *Api) ListConvo(planId, branch string) ([]*shared.ConvoMessage, *shared.ApiError) {
+ serverUrl := fmt.Sprintf("%s/plans/%s/%s/convo", getApiHost(), planId, branch)
resp, err := authenticatedFastClient.Get(serverUrl)
if err != nil {
@@ -791,7 +836,7 @@ func (a *Api) ListConvo(planId string) ([]*shared.ConvoMessage, *shared.ApiError
apiErr := handleApiError(resp, errorBody)
tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
if tokenRefreshed {
- return a.ListConvo(planId)
+ return a.ListConvo(planId, branch)
}
return nil, apiErr
}
@@ -805,8 +850,8 @@ func (a *Api) ListConvo(planId string) ([]*shared.ConvoMessage, *shared.ApiError
return convos, nil
}
-func (a *Api) ListLogs(planId string) (*shared.LogResponse, *shared.ApiError) {
- serverUrl := fmt.Sprintf("%s/plans/%s/logs", getApiHost(), planId)
+func (a *Api) ListLogs(planId, branch string) (*shared.LogResponse, *shared.ApiError) {
+ serverUrl := fmt.Sprintf("%s/plans/%s/%s/logs", getApiHost(), planId, branch)
resp, err := authenticatedFastClient.Get(serverUrl)
if err != nil {
@@ -820,7 +865,7 @@ func (a *Api) ListLogs(planId string) (*shared.LogResponse, *shared.ApiError) {
apiErr := handleApiError(resp, errorBody)
tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
if tokenRefreshed {
- return a.ListLogs(planId)
+ return a.ListLogs(planId, branch)
}
return nil, apiErr
}
@@ -834,8 +879,8 @@ func (a *Api) ListLogs(planId string) (*shared.LogResponse, *shared.ApiError) {
return &logs, nil
}
-func (a *Api) RewindPlan(planId string, req shared.RewindPlanRequest) (*shared.RewindPlanResponse, *shared.ApiError) {
- serverUrl := fmt.Sprintf("%s/plans/%s/rewind", getApiHost(), planId)
+func (a *Api) RewindPlan(planId, branch string, req shared.RewindPlanRequest) (*shared.RewindPlanResponse, *shared.ApiError) {
+ serverUrl := fmt.Sprintf("%s/plans/%s/%s/rewind", getApiHost(), planId, branch)
reqBytes, err := json.Marshal(req)
if err != nil {
return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error marshalling request: %v", err)}
@@ -859,7 +904,7 @@ func (a *Api) RewindPlan(planId string, req shared.RewindPlanRequest) (*shared.R
apiErr := handleApiError(resp, errorBody)
tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
if tokenRefreshed {
- return a.RewindPlan(planId, req)
+ return a.RewindPlan(planId, branch, req)
}
return nil, apiErr
}
@@ -1293,3 +1338,88 @@ func (a *Api) ListUsers() ([]*shared.User, *shared.ApiError) {
return users, nil
}
+
+func (a *Api) ListBranches(planId string) ([]*shared.Branch, *shared.ApiError) {
+ serverUrl := fmt.Sprintf("%s/plans/%s/branches", getApiHost(), planId)
+
+ resp, err := authenticatedFastClient.Get(serverUrl)
+ if err != nil {
+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %s", err)}
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode >= 400 {
+ errorBody, _ := io.ReadAll(resp.Body)
+
+ apiErr := handleApiError(resp, errorBody)
+ tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
+ if tokenRefreshed {
+ return a.ListBranches(planId)
+ }
+ return nil, apiErr
+ }
+
+ var branches []*shared.Branch
+ err = json.NewDecoder(resp.Body).Decode(&branches)
+ if err != nil {
+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error decoding response: %s", err)}
+ }
+
+ return branches, nil
+}
+
+func (a *Api) CreateBranch(planId, branch string, req shared.CreateBranchRequest) *shared.ApiError {
+ serverUrl := fmt.Sprintf("%s/plans/%s/%s/branches", getApiHost(), planId, branch)
+
+ reqBytes, err := json.Marshal(req)
+ if err != nil {
+ return &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error marshalling request: %s", err)}
+ }
+
+ resp, err := authenticatedFastClient.Post(serverUrl, "application/json", bytes.NewBuffer(reqBytes))
+ if err != nil {
+ return &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %s", err)}
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode >= 400 {
+ errorBody, _ := io.ReadAll(resp.Body)
+
+ apiErr := handleApiError(resp, errorBody)
+ tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
+ if tokenRefreshed {
+ return a.CreateBranch(planId, branch, req)
+ }
+ return apiErr
+ }
+
+ return nil
+}
+
+func (a *Api) DeleteBranch(planId, branch string) *shared.ApiError {
+ serverUrl := fmt.Sprintf("%s/plans/%s/branches/%s", getApiHost(), planId)
+
+ req, err := http.NewRequest(http.MethodDelete, serverUrl, nil)
+ if err != nil {
+ return &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error creating request: %s", err)}
+ }
+
+ resp, err := authenticatedFastClient.Do(req)
+ if err != nil {
+ return &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %s", err)}
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode >= 400 {
+ errorBody, _ := io.ReadAll(resp.Body)
+
+ apiErr := handleApiError(resp, errorBody)
+ tokenRefreshed, apiErr := refreshTokenIfNeeded(apiErr)
+ if tokenRefreshed {
+ return a.DeleteBranch(planId, branch)
+ }
+ return apiErr
+ }
+
+ return nil
+}
diff --git a/app/cli/changes_tui/actions.go b/app/cli/changes_tui/actions.go
index bbddb4a7..5dab3849 100644
--- a/app/cli/changes_tui/actions.go
+++ b/app/cli/changes_tui/actions.go
@@ -19,7 +19,7 @@ func (m *changesUIModel) rejectChange() {
return
}
- err := api.Client.RejectReplacement(lib.CurrentPlanId, m.selectionInfo.currentRes.Id, m.selectionInfo.currentRep.Id)
+ err := api.Client.RejectReplacement(lib.CurrentPlanId, lib.CurrentBranch, m.selectionInfo.currentRes.Id, m.selectionInfo.currentRep.Id)
if err != nil {
log.Printf("error dropping change: %v", err)
diff --git a/app/cli/changes_tui/model.go b/app/cli/changes_tui/model.go
index 06881134..706c8a4a 100644
--- a/app/cli/changes_tui/model.go
+++ b/app/cli/changes_tui/model.go
@@ -53,7 +53,7 @@ func (m changesUIModel) Init() tea.Cmd {
}
func initialModel() *changesUIModel {
- currentPlan, apiErr := api.Client.GetCurrentPlanState(lib.CurrentPlanId)
+ currentPlan, apiErr := api.Client.GetCurrentPlanState(lib.CurrentPlanId, lib.CurrentBranch)
if apiErr != nil {
err := fmt.Errorf("error getting current plan state: %v", apiErr.Msg)
log.Println(err)
diff --git a/app/cli/changes_tui/run.go b/app/cli/changes_tui/run.go
index 51b979a6..6a2de4fa 100644
--- a/app/cli/changes_tui/run.go
+++ b/app/cli/changes_tui/run.go
@@ -23,13 +23,13 @@ func StartChangesUI() error {
}
if m.(changesUIModel).shouldApplyAll {
- err := lib.ApplyPlanWithOutput(lib.CurrentPlanId, false)
+ err := lib.ApplyPlanWithOutput(lib.CurrentPlanId, lib.CurrentBranch, false)
if err != nil {
return fmt.Errorf("error applying plan: %v", err)
}
} else if m.(changesUIModel).shouldRejectAll {
- err := api.Client.RejectAllChanges(lib.CurrentPlanId)
+ err := api.Client.RejectAllChanges(lib.CurrentPlanId, lib.CurrentBranch)
if err != nil {
return fmt.Errorf("error rejecting plan: %v", err)
diff --git a/app/cli/cmd/apply.go b/app/cli/cmd/apply.go
index a743e4a7..9bb9e917 100644
--- a/app/cli/cmd/apply.go
+++ b/app/cli/cmd/apply.go
@@ -2,13 +2,9 @@ package cmd
import (
"fmt"
- "os"
- "plandex/api"
"plandex/auth"
"plandex/lib"
- "strconv"
- "github.com/plandex/plandex/shared"
"github.com/spf13/cobra"
)
@@ -23,70 +19,77 @@ var applyCmd = &cobra.Command{
Use: "apply [name-or-index]",
Aliases: []string{"ap"},
Short: "Apply a plan to the project",
- Args: cobra.MaximumNArgs(1),
- RunE: apply,
+ Run: apply,
}
-func apply(cmd *cobra.Command, args []string) error {
+func apply(cmd *cobra.Command, args []string) {
auth.MustResolveAuthWithOrg()
lib.MustResolveProject()
- var planId string
-
- if len(args) == 0 {
- if lib.CurrentPlanId == "" {
- fmt.Fprintln(os.Stderr, "No current plan")
- os.Exit(1)
- }
-
- planId = lib.CurrentPlanId
- } else {
- nameOrIdx := args[0]
-
- if nameOrIdx == "current" {
- if lib.CurrentPlanId == "" {
- fmt.Fprintln(os.Stderr, "No current plan")
- os.Exit(1)
- }
-
- planId = lib.CurrentPlanId
- } else {
- var plan *shared.Plan
-
- plans, apiErr := api.Client.ListPlans(lib.CurrentProjectId)
-
- if apiErr != nil {
- fmt.Fprintln(os.Stderr, "Error getting plans:", apiErr.Msg)
- os.Exit(1)
- }
-
- // see if it's an index
- idx, err := strconv.Atoi(nameOrIdx)
-
- if err == nil {
- if idx > 0 && idx <= len(plans) {
- plan = plans[idx-1]
- } else {
- fmt.Fprintln(os.Stderr, "Error: index out of range")
- os.Exit(1)
- }
- } else {
- for _, p := range plans {
- if p.Name == nameOrIdx {
- plan = p
- break
- }
- }
-
- if plan == nil {
- fmt.Printf("🤷‍♂️ Plan with name '%s' doesn't exist\n", nameOrIdx)
- os.Exit(1)
- }
- }
-
- planId = plan.Id
- }
+ if lib.CurrentPlanId == "" {
+ fmt.Println("🤷‍♂️ No current plan")
+ return
}
- return lib.ApplyPlanWithOutput(planId, autoConfirm)
+ // if len(args) == 0 {
+ // if lib.CurrentPlanId == "" {
+ // fmt.Fprintln(os.Stderr, "No current plan")
+ // os.Exit(1)
+ // }
+
+ // planId = lib.CurrentPlanId
+ // } else {
+ // nameOrIdx := args[0]
+
+ // if nameOrIdx == "current" {
+ // if lib.CurrentPlanId == "" {
+ // fmt.Fprintln(os.Stderr, "No current plan")
+ // os.Exit(1)
+ // }
+
+ // planId = lib.CurrentPlanId
+ // } else {
+ // var plan *shared.Plan
+
+ // plans, apiErr := api.Client.ListPlans(lib.CurrentProjectId)
+
+ // if apiErr != nil {
+ // fmt.Fprintln(os.Stderr, "Error getting plans:", apiErr.Msg)
+ // os.Exit(1)
+ // }
+
+ // // see if it's an index
+ // idx, err := strconv.Atoi(nameOrIdx)
+
+ // if err == nil {
+ // if idx > 0 && idx <= len(plans) {
+ // plan = plans[idx-1]
+ // } else {
+ // fmt.Fprintln(os.Stderr, "Error: index out of range")
+ // os.Exit(1)
+ // }
+ // } else {
+ // for _, p := range plans {
+ // if p.Name == nameOrIdx {
+ // plan = p
+ // break
+ // }
+ // }
+
+ // if plan == nil {
+ // fmt.Printf("🤷‍♂️ Plan with name '%s' doesn't exist\n", nameOrIdx)
+ // os.Exit(1)
+ // }
+ // }
+
+ // planId = plan.Id
+ // }
+ // }
+
+ err := lib.ApplyPlanWithOutput(lib.CurrentPlanId, lib.CurrentBranch, autoConfirm)
+
+ if err != nil {
+ fmt.Println("Error applying plan:", err)
+ return
+ }
}
diff --git a/app/cli/cmd/cd.go b/app/cli/cmd/cd.go
index c0f00919..ed768296 100644
--- a/app/cli/cmd/cd.go
+++ b/app/cli/cmd/cd.go
@@ -64,12 +64,15 @@ func cd(cmd *cobra.Command, args []string) {
}
}
- err = lib.SetCurrentPlan(plan.Id)
+ err = lib.WriteCurrentPlan(plan.Id)
if err != nil {
fmt.Fprintln(os.Stderr, "Error setting current plan:", err)
os.Exit(1)
}
+ // reload current plan, which will also handle setting the right branch
+ lib.MustLoadCurrentPlan()
+
// fire and forget SetProjectPlan request (we don't care about the response or errors)
// this only matters for setting the current plan on a new device (i.e. when the current plan is not set)
go api.Client.SetProjectPlan(lib.CurrentProjectId, shared.SetProjectPlanRequest{PlanId: plan.Id})
diff --git a/app/cli/cmd/clear.go b/app/cli/cmd/clear.go
index 248bce37..12f2842d 100644
--- a/app/cli/cmd/clear.go
+++ b/app/cli/cmd/clear.go
@@ -27,7 +27,7 @@ func clearAllContext(cmd *cobra.Command, args []string) {
return
}
- contexts, err := api.Client.ListContext(lib.CurrentPlanId)
+ contexts, err := api.Client.ListContext(lib.CurrentPlanId, lib.CurrentBranch)
if err != nil {
fmt.Fprintln(os.Stderr, "Error retrieving context:", err)
@@ -41,7 +41,7 @@ func clearAllContext(cmd *cobra.Command, args []string) {
}
if len(deleteIds) > 0 {
- res, err := api.Client.DeleteContext(lib.CurrentPlanId, shared.DeleteContextRequest{
+ res, err := api.Client.DeleteContext(lib.CurrentPlanId, lib.CurrentBranch, shared.DeleteContextRequest{
Ids: deleteIds,
})
diff --git a/app/cli/cmd/continue.go b/app/cli/cmd/continue.go
index d591bc77..7f34ebf9 100644
--- a/app/cli/cmd/continue.go
+++ b/app/cli/cmd/continue.go
@@ -48,7 +48,7 @@ func next(cmd *cobra.Command, args []string) {
var fn func() bool
fn = func() bool {
- apiErr := api.Client.TellPlan(lib.CurrentPlanId, shared.TellPlanRequest{
+ apiErr := api.Client.TellPlan(lib.CurrentPlanId, lib.CurrentBranch, shared.TellPlanRequest{
Prompt: continuePrompt,
ConnectStream: !continueBg,
}, lib.OnStreamPlan)
@@ -56,7 +56,7 @@ func next(cmd *cobra.Command, args []string) {
if apiErr.Type == shared.ApiErrorTypeTrialMessagesExceeded {
streamtui.Quit()
- fmt.Fprintf(os.Stderr, "🚨 You've reached the free trial limit of %d messages per plan\n", apiErr.TrialMessagesExceededError.MaxMessages)
+ fmt.Fprintf(os.Stderr, "🚨 You've reached the free trial limit of %d messages per plan\n", apiErr.TrialMessagesExceededError.MaxReplies)
res, err := term.ConfirmYesNo("Upgrade now?")
diff --git a/app/cli/cmd/convo.go b/app/cli/cmd/convo.go
index d3a3e177..b007f8f8 100644
--- a/app/cli/cmd/convo.go
+++ b/app/cli/cmd/convo.go
@@ -29,7 +29,7 @@ func convo(cmd *cobra.Command, args []string) {
auth.MustResolveAuthWithOrg()
lib.MustResolveProject()
- conversation, apiErr := api.Client.ListConvo(lib.CurrentPlanId)
+ conversation, apiErr := api.Client.ListConvo(lib.CurrentPlanId, lib.CurrentBranch)
if apiErr != nil {
fmt.Fprintln(os.Stderr, "Error loading conversation:", apiErr.Msg)
return
diff --git a/app/cli/cmd/current.go b/app/cli/cmd/current.go
index 3a92938c..549900db 100644
--- a/app/cli/cmd/current.go
+++ b/app/cli/cmd/current.go
@@ -12,6 +12,7 @@ import (
"github.com/fatih/color"
"github.com/olekukonko/tablewriter"
+ "github.com/plandex/plandex/shared"
"github.com/spf13/cobra"
)
@@ -41,18 +42,32 @@ func current(cmd *cobra.Command, args []string) {
return
}
+ currentBranchesByPlanId, err := api.Client.GetCurrentBranchByPlanId(lib.CurrentProjectId, shared.GetCurrentBranchByPlanIdRequest{
+ CurrentBranchByPlanId: map[string]string{
+ lib.CurrentPlanId: lib.CurrentBranch,
+ },
+ })
+
+ if err != nil {
+ fmt.Fprintln(os.Stderr, "Error getting current branches:", err)
+ return
+ }
+
table := tablewriter.NewWriter(os.Stdout)
table.SetAutoWrapText(false)
- table.SetHeader([]string{"Current Plan", "Updated", "Created", "Context", "Convo"})
+ table.SetHeader([]string{"Current Plan", "Updated", "Created", "Branches", "Branch", "Context", "Convo"})
name := color.New(color.Bold, color.FgGreen).Sprint(plan.Name)
+ branch := currentBranchesByPlanId[lib.CurrentPlanId]
row := []string{
name,
format.Time(plan.UpdatedAt),
format.Time(plan.CreatedAt),
- strconv.Itoa(plan.ContextTokens) + " 🪙",
- strconv.Itoa(plan.ConvoTokens) + " 🪙",
+ strconv.Itoa(plan.ActiveBranches),
+ lib.CurrentBranch,
+ strconv.Itoa(branch.ContextTokens) + " 🪙",
+ strconv.Itoa(branch.ConvoTokens) + " 🪙",
}
style := []tablewriter.Colors{
diff --git a/app/cli/cmd/log.go b/app/cli/cmd/log.go
index 86bafa36..0a9c636c 100644
--- a/app/cli/cmd/log.go
+++ b/app/cli/cmd/log.go
@@ -34,7 +34,7 @@ func runLog(cmd *cobra.Command, args []string) {
return
}
- res, err := api.Client.ListLogs(lib.CurrentPlanId)
+ res, err := api.Client.ListLogs(lib.CurrentPlanId, lib.CurrentBranch)
if err != nil {
fmt.Printf("Error: %v\n", err)
return
diff --git a/app/cli/cmd/ls.go b/app/cli/cmd/ls.go
index a901654f..7fba56b8 100644
--- a/app/cli/cmd/ls.go
+++ b/app/cli/cmd/ls.go
@@ -26,7 +26,7 @@ func context(cmd *cobra.Command, args []string) {
auth.MustResolveAuthWithOrg()
lib.MustResolveProject()
- contexts, err := api.Client.ListContext(lib.CurrentPlanId)
+ contexts, err := api.Client.ListContext(lib.CurrentPlanId, lib.CurrentBranch)
if err != nil {
color.New(color.FgRed).Fprintln(os.Stderr, "Error listing context:", err)
diff --git a/app/cli/cmd/new.go b/app/cli/cmd/new.go
index 30e06749..41df3447 100644
--- a/app/cli/cmd/new.go
+++ b/app/cli/cmd/new.go
@@ -63,7 +63,7 @@ func new(cmd *cobra.Command, args []string) {
return
}
- err := lib.SetCurrentPlan(res.Id)
+ err := lib.WriteCurrentPlan(res.Id)
if err != nil {
fmt.Fprintln(os.Stderr, "Error setting current plan:", err)
diff --git a/app/cli/cmd/plans.go b/app/cli/cmd/plans.go
index 04dfdc80..e448e58e 100644
--- a/app/cli/cmd/plans.go
+++ b/app/cli/cmd/plans.go
@@ -13,6 +13,7 @@ import (
"github.com/fatih/color"
"github.com/olekukonko/tablewriter"
+ "github.com/plandex/plandex/shared"
"github.com/spf13/cobra"
)
@@ -22,25 +23,47 @@ func init() {
// plansCmd represents the list command
var plansCmd = &cobra.Command{
- Use: "plans",
- Short: "List all available plans",
- Run: plans,
+ Use: "plans",
+ Aliases: []string{"pl"},
+ Short: "List all available plans",
+ Run: plans,
}
func plans(cmd *cobra.Command, args []string) {
auth.MustResolveAuthWithOrg()
lib.MustResolveProject()
- plans, err := api.Client.ListPlans(lib.CurrentProjectId)
+ plans, apiErr := api.Client.ListPlans(lib.CurrentProjectId)
+
+ if apiErr != nil {
+ fmt.Fprintln(os.Stderr, "Error getting plans:", apiErr)
+ return
+ }
+
+ var planIds []string
+ for _, p := range plans {
+ planIds = append(planIds, p.Id)
+ }
+
+ currentBranchNamesByPlanId, err := lib.GetCurrentBranchNamesByPlanId(planIds)
if err != nil {
- fmt.Fprintln(os.Stderr, "Error getting plans:", err)
+ fmt.Fprintln(os.Stderr, "Error getting current branches:", err)
+ return
+ }
+
+ currentBranchesByPlanId, apiErr := api.Client.GetCurrentBranchByPlanId(lib.CurrentProjectId, shared.GetCurrentBranchByPlanIdRequest{
+ CurrentBranchByPlanId: currentBranchNamesByPlanId,
+ })
+
+ if apiErr != nil {
+ fmt.Fprintln(os.Stderr, "Error getting current branches:", apiErr)
return
}
table := tablewriter.NewWriter(os.Stdout)
table.SetAutoWrapText(false)
- table.SetHeader([]string{"#", "Name", "Updated", "Created", "Context", "Convo"})
+ table.SetHeader([]string{"#", "Name", "Updated", "Created", "Branches", "Branch", "Context", "Convo"})
if len(plans) == 0 {
fmt.Println("🤷‍♂️ No plans")
@@ -58,13 +81,17 @@ func plans(cmd *cobra.Command, args []string) {
name = p.Name
}
+ currentBranch := currentBranchesByPlanId[p.Id]
+
row := []string{
strconv.Itoa(i + 1),
name,
format.Time(p.UpdatedAt),
format.Time(p.CreatedAt),
- strconv.Itoa(p.ContextTokens) + " 🪙",
- strconv.Itoa(p.ConvoTokens) + " 🪙",
+ strconv.Itoa(p.ActiveBranches),
+ currentBranch.Name,
+ strconv.Itoa(currentBranch.ContextTokens) + " 🪙",
+ strconv.Itoa(currentBranch.ConvoTokens) + " 🪙",
}
var style []tablewriter.Colors
diff --git a/app/cli/cmd/rewind.go b/app/cli/cmd/rewind.go
index 95f48d7c..7e7e54cb 100644
--- a/app/cli/cmd/rewind.go
+++ b/app/cli/cmd/rewind.go
@@ -42,7 +42,7 @@ func rewind(cmd *cobra.Command, args []string) {
stepsOrSha := args[0]
- logsRes, err := api.Client.ListLogs(lib.CurrentPlanId)
+ logsRes, err := api.Client.ListLogs(lib.CurrentPlanId, lib.CurrentBranch)
if err != nil {
fmt.Printf("Error getting logs: %v\n", err)
@@ -73,7 +73,7 @@ func rewind(cmd *cobra.Command, args []string) {
// log.Println("Rewinding to", targetSha)
// Rewind to the target sha
- rwRes, err := api.Client.RewindPlan(lib.CurrentPlanId, shared.RewindPlanRequest{Sha: targetSha})
+ rwRes, err := api.Client.RewindPlan(lib.CurrentPlanId, lib.CurrentBranch, shared.RewindPlanRequest{Sha: targetSha})
if err != nil {
fmt.Fprintf(os.Stderr, "Error rewinding plan: %v\n", err)
diff --git a/app/cli/cmd/rm.go b/app/cli/cmd/rm.go
index fa8d0519..e69ee421 100644
--- a/app/cli/cmd/rm.go
+++ b/app/cli/cmd/rm.go
@@ -30,7 +30,7 @@ func contextRm(cmd *cobra.Command, args []string) {
return
}
- contexts, err := api.Client.ListContext(lib.CurrentPlanId)
+ contexts, err := api.Client.ListContext(lib.CurrentPlanId, lib.CurrentBranch)
if err != nil {
fmt.Fprintln(os.Stderr, "Error retrieving context:", err)
@@ -60,7 +60,7 @@ func contextRm(cmd *cobra.Command, args []string) {
}
if len(deleteIds) > 0 {
- res, err := api.Client.DeleteContext(lib.CurrentPlanId, shared.DeleteContextRequest{
+ res, err := api.Client.DeleteContext(lib.CurrentPlanId, lib.CurrentBranch, shared.DeleteContextRequest{
Ids: deleteIds,
})
diff --git a/app/cli/cmd/tell.go b/app/cli/cmd/tell.go
index a1114816..c6436b6e 100644
--- a/app/cli/cmd/tell.go
+++ b/app/cli/cmd/tell.go
@@ -139,7 +139,7 @@ func tell(cmd *cobra.Command, args []string) {
var fn func() bool
fn = func() bool {
- apiErr := api.Client.TellPlan(lib.CurrentPlanId, shared.TellPlanRequest{
+ apiErr := api.Client.TellPlan(lib.CurrentPlanId, lib.CurrentBranch, shared.TellPlanRequest{
Prompt: prompt,
ConnectStream: !tellBg,
AutoContinue: !tellStep,
@@ -148,7 +148,7 @@ func tell(cmd *cobra.Command, args []string) {
if apiErr.Type == shared.ApiErrorTypeTrialMessagesExceeded {
streamtui.Quit()
- fmt.Fprintf(os.Stderr, "\n🚨 You've reached the free trial limit of %d messages per plan\n", apiErr.TrialMessagesExceededError.MaxMessages)
+ fmt.Fprintf(os.Stderr, "\n🚨 You've reached the free trial limit of %d messages per plan\n", apiErr.TrialMessagesExceededError.MaxReplies)
res, err := term.ConfirmYesNo("Upgrade now?")
diff --git a/app/cli/lib/apply.go b/app/cli/lib/apply.go
index 2f41cde2..e0816e0a 100644
--- a/app/cli/lib/apply.go
+++ b/app/cli/lib/apply.go
@@ -16,8 +16,8 @@ import (
"github.com/plandex/plandex/shared"
)
-func ApplyPlanWithOutput(planId string, autoConfirm bool) error {
- currentPlanState, apiErr := api.Client.GetCurrentPlanState(planId)
+func ApplyPlanWithOutput(planId, branch string, autoConfirm bool) error {
+ currentPlanState, apiErr := api.Client.GetCurrentPlanState(planId, branch)
if apiErr != nil {
return fmt.Errorf("error getting current plan state: %s", apiErr.Msg)
@@ -304,7 +304,7 @@ func ApplyPlanWithOutput(planId string, autoConfirm bool) error {
}
}
- apiErr := api.Client.ApplyPlan(planId)
+ apiErr := api.Client.ApplyPlan(planId, branch)
if apiErr != nil {
aborted = true
diff --git a/app/cli/lib/context_load.go b/app/cli/lib/context_load.go
index 839a8902..d047a056 100644
--- a/app/cli/lib/context_load.go
+++ b/app/cli/lib/context_load.go
@@ -169,7 +169,7 @@ func MustLoadContext(resources []string, params *types.LoadContextParams) {
os.Exit(0)
}
- res, apiErr := api.Client.LoadContext(CurrentPlanId, loadContextReq)
+ res, apiErr := api.Client.LoadContext(CurrentPlanId, CurrentBranch, loadContextReq)
if apiErr != nil {
onErr(fmt.Errorf("failed to load context: %v", apiErr.Msg))
diff --git a/app/cli/lib/context_update.go b/app/cli/lib/context_update.go
index 7ded206a..25c232ed 100644
--- a/app/cli/lib/context_update.go
+++ b/app/cli/lib/context_update.go
@@ -126,7 +126,7 @@ func CheckOutdatedContext() (*types.ContextOutdatedResult, error) {
func checkOutdatedAndMaybeUpdateContext(doUpdate bool) (*types.ContextOutdatedResult, error) {
- contexts, err := api.Client.ListContext(CurrentPlanId)
+ contexts, err := api.Client.ListContext(CurrentPlanId, CurrentBranch)
if err != nil {
return nil, fmt.Errorf("error retrieving context: %w", err)
}
@@ -265,7 +265,7 @@ func checkOutdatedAndMaybeUpdateContext(doUpdate bool) (*types.ContextOutdatedRe
Msg: "Context is up to date",
}, nil
} else if doUpdate {
- res, err := api.Client.UpdateContext(CurrentPlanId, req)
+ res, err := api.Client.UpdateContext(CurrentPlanId, CurrentBranch, req)
if err != nil {
return nil, fmt.Errorf("failed to update context: %w", err)
}
diff --git a/app/cli/lib/current.go b/app/cli/lib/current.go
index 736b2864..2ec8a9b3 100644
--- a/app/cli/lib/current.go
+++ b/app/cli/lib/current.go
@@ -14,6 +14,7 @@ import (
var CurrentProjectId string
var CurrentPlanId string
+var CurrentBranch string
var HomeCurrentProjectDir string
var HomeCurrentPlanPath string
@@ -46,7 +47,7 @@ func MustResolveProject() {
panic(fmt.Errorf("error reading project.json: %v", err))
}
- var settings types.ProjectSettings
+ var settings types.CurrentProjectSettings
err = json.Unmarshal(bytes, &settings)
if err != nil {
@@ -87,14 +88,60 @@ func MustLoadCurrentPlan() {
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)
+ var currentPlan types.CurrentPlanSettings
+ err = json.Unmarshal(fileBytes, &currentPlan)
if err != nil {
panic(fmt.Errorf("error unmarshalling current_plan.json: %v", err))
}
- CurrentPlanId = planSettings.Id
+ CurrentPlanId = currentPlan.Id
+
+ err = loadCurrentBranch()
+
+ if err != nil {
+ panic(fmt.Errorf("error loading current branch: %v", err))
+ }
+
+ if CurrentBranch == "" {
+ err = WriteCurrentBranch("main")
+
+ if err != nil {
+ panic(fmt.Errorf("error setting current branch: %v", err))
+ }
+ }
+}
+
+func loadCurrentBranch() error {
+ // Load plan-specific settings
+ if CurrentPlanId == "" {
+ return fmt.Errorf("no current plan")
+ }
+
+ path := filepath.Join(HomeCurrentProjectDir, CurrentPlanId, "settings.json")
+
+ // Check if the file exists
+ _, err := os.Stat(path)
+
+ if os.IsNotExist(err) {
+ return nil
+ } else if err != nil {
+ return fmt.Errorf("error checking if settings.json exists: %v", err)
+ }
+
+ fileBytes, err := os.ReadFile(path)
+ if err != nil {
+ panic(fmt.Errorf("error reading settings.json: %v", err))
+ }
+
+ var settings types.PlanSettings
+ err = json.Unmarshal(fileBytes, &settings)
+ if err != nil {
+ panic(fmt.Errorf("error unmarshalling settings.json: %v", err))
+ }
+
+ CurrentBranch = settings.Branch
+
+ return nil
}
func mustInitProject() {
@@ -108,7 +155,7 @@ func mustInitProject() {
// write project.json
path := filepath.Join(fs.PlandexDir, "project.json")
- bytes, err := json.Marshal(types.ProjectSettings{
+ bytes, err := json.Marshal(types.CurrentProjectSettings{
Id: CurrentProjectId,
})
@@ -131,7 +178,7 @@ func mustInitProject() {
}
path = filepath.Join(dir, "current_plan.json")
- bytes, err = json.Marshal(types.PlanSettings{
+ bytes, err = json.Marshal(types.CurrentPlanSettings{
Id: "",
})
diff --git a/app/cli/lib/plans.go b/app/cli/lib/plans.go
index 736eab4a..4176f52e 100644
--- a/app/cli/lib/plans.go
+++ b/app/cli/lib/plans.go
@@ -1,12 +1,15 @@
package lib
import (
+ "encoding/json"
"fmt"
"os"
+ "path/filepath"
"plandex/fs"
+ "plandex/types"
)
-func SetCurrentPlan(id string) error {
+func WriteCurrentPlan(id string) error {
if fs.HomePlandexDir == "" {
return fmt.Errorf("HomePlandexDir not set")
}
@@ -15,11 +18,22 @@ func SetCurrentPlan(id string) error {
return fmt.Errorf("no current project")
}
- err := os.WriteFile(HomeCurrentPlanPath, []byte(fmt.Sprintf(`{"id": "%s"}`, id)), 0644)
+ settings := types.CurrentPlanSettings{
+ Id: id,
+ }
+ bytes, err := json.Marshal(settings)
+
if err != nil {
- return err
+ return fmt.Errorf("error marshalling current plan: %v", err)
}
+ err = os.WriteFile(HomeCurrentPlanPath, bytes, 0644)
+ if err != nil {
+ return fmt.Errorf("error writing current plan: %v", err)
+ }
+
+ CurrentPlanId = id
+
return nil
}
@@ -37,5 +51,112 @@ func ClearCurrentPlan() error {
return err
}
+ CurrentPlanId = ""
+
+ return nil
+}
+
+func WriteCurrentBranch(branch string) error {
+ if fs.HomePlandexDir == "" {
+ return fmt.Errorf("HomePlandexDir not set")
+ }
+
+ if CurrentProjectId == "" || HomeCurrentPlanPath == "" {
+ return fmt.Errorf("no current project")
+ }
+
+ if CurrentPlanId == "" {
+ return fmt.Errorf("no current plan")
+ }
+
+ settings := types.PlanSettings{
+ Branch: branch,
+ }
+
+ bytes, err := json.Marshal(settings)
+
+ if err != nil {
+ return fmt.Errorf("error marshalling current plan settings: %v", err)
+ }
+
+ path := filepath.Join(fs.HomePlandexDir, CurrentProjectId, CurrentPlanId, "settings.json")
+
+ err = os.WriteFile(path, bytes, 0644)
+
+ if err != nil {
+ return fmt.Errorf("error writing current plan settings: %v", err)
+ }
+
+ CurrentBranch = branch
+
return nil
}
+
+func GetCurrentBranchNamesByPlanId(planIds []string) (map[string]string, error) {
+ if fs.HomePlandexDir == "" {
+ return nil, fmt.Errorf("HomePlandexDir not set")
+ }
+
+ if CurrentProjectId == "" || HomeCurrentPlanPath == "" {
+ return nil, fmt.Errorf("no current project")
+ }
+
+ branches := make(map[string]string)
+ errCh := make(chan error, len(planIds))
+ for _, planId := range planIds {
+ go func(planId string) {
+ branch, err := getPlanCurrentBranch(planId)
+ if err != nil {
+ errCh <- fmt.Errorf("error getting plan current branch: %v", err)
+ } else {
+ errCh <- nil
+ branches[planId] = branch
+ }
+ }(planId)
+ }
+
+ for i := 0; i < len(planIds); i++ {
+ err := <-errCh
+ if err != nil {
+ return nil, err
+ }
+ }
+
+ return branches, nil
+}
+
+func getPlanCurrentBranch(planId string) (string, error) {
+ if fs.HomePlandexDir == "" {
+ return "", fmt.Errorf("HomePlandexDir not set")
+ }
+
+ if CurrentProjectId == "" || HomeCurrentPlanPath == "" {
+ return "", fmt.Errorf("no current project")
+ }
+
+ path := filepath.Join(fs.HomePlandexDir, CurrentProjectId, planId, "settings.json")
+
+ // Check if settings.json exists
+ _, err := os.Stat(path)
+
+ if os.IsNotExist(err) {
+ return "main", nil
+ } else if err != nil {
+ return "", fmt.Errorf("error checking if settings.json exists: %v", err)
+ }
+
+ bytes, err := os.ReadFile(path)
+
+ if err != nil {
+ return "", fmt.Errorf("error reading plan settings: %v", err)
+ }
+
+ var settings types.PlanSettings
+ err = json.Unmarshal(bytes, &settings)
+
+ if err != nil {
+ return "", fmt.Errorf("error unmarshalling plan settings: %v", err)
+ }
+
+ return settings.Branch, nil
+}
diff --git a/app/cli/stream_tui/model.go b/app/cli/stream_tui/model.go
index 21d87ea1..82302c6a 100644
--- a/app/cli/stream_tui/model.go
+++ b/app/cli/stream_tui/model.go
@@ -41,7 +41,10 @@ type keymap = struct {
}
func (m streamUIModel) Init() tea.Cmd {
- return nil
+ m.replyViewport.MouseWheelEnabled = true
+
+ // start spinner
+ return m.spinner.Tick
}
func initialModel() *streamUIModel {
@@ -85,10 +88,6 @@ func initialModel() *streamUIModel {
spinner: s,
atScrollBottom: true,
starting: true,
-
- // Enable mouse support for the viewport
- replyViewport: viewport.Model{Width: initialState.width, Height: initialState.height},
- replyViewport.MouseWheelEnabled = true,
}
return &initialState
diff --git a/app/cli/stream_tui/update.go b/app/cli/stream_tui/update.go
index f707d3e8..3f75417f 100644
--- a/app/cli/stream_tui/update.go
+++ b/app/cli/stream_tui/update.go
@@ -168,9 +168,5 @@ func (m *streamUIModel) streamUpdate(msg *shared.StreamMessage) (tea.Model, tea.
case shared.StreamMessageAborted:
}
- if m.starting {
- return m, m.spinner.Tick
- } else {
- return m, nil
- }
+ return m, nil
}
diff --git a/app/cli/term/term.go b/app/cli/term/term.go
index a503a4ee..2ebd4fb1 100644
--- a/app/cli/term/term.go
+++ b/app/cli/term/term.go
@@ -30,7 +30,7 @@ var CmdDesc = map[string][2]string{
"rm": {"", "remove context by name, index, or glob"},
"clear": {"", "remove all context"},
"delete-plan": {"del", "delete plan by name or index"},
- "plans": {"", "list plans"},
+ "plans": {"pl", "list plans"},
"update": {"u", "update outdated context"},
}
diff --git a/app/cli/types/api.go b/app/cli/types/api.go
index 549f24c2..ee77e06b 100644
--- a/app/cli/types/api.go
+++ b/app/cli/types/api.go
@@ -41,31 +41,38 @@ type ApiClient interface {
RenameProject(projectId string, req shared.RenameProjectRequest) *shared.ApiError
ListPlans(projectId string) ([]*shared.Plan, *shared.ApiError)
+
+ GetCurrentBranchByPlanId(projectId string, req shared.GetCurrentBranchByPlanIdRequest) (map[string]*shared.Branch, *shared.ApiError)
+
ListArchivedPlans(projectId string) ([]*shared.Plan, *shared.ApiError)
ListPlansRunning(projectId string) ([]*shared.Plan, *shared.ApiError)
GetPlan(planId string) (*shared.Plan, *shared.ApiError)
CreatePlan(projectId string, req shared.CreatePlanRequest) (*shared.CreatePlanResponse, *shared.ApiError)
- TellPlan(planId string, req shared.TellPlanRequest, onStreamPlan OnStreamPlan) *shared.ApiError
+ TellPlan(planId, branch string, req shared.TellPlanRequest, onStreamPlan OnStreamPlan) *shared.ApiError
DeletePlan(planId string) *shared.ApiError
DeleteAllPlans(projectId string) *shared.ApiError
- ConnectPlan(planId string, onStreamPlan OnStreamPlan) *shared.ApiError
- StopPlan(planId string) *shared.ApiError
+ ConnectPlan(planId, branch string, onStreamPlan OnStreamPlan) *shared.ApiError
+ StopPlan(planId, branch string) *shared.ApiError
ArchivePlan(planId string) *shared.ApiError
- GetCurrentPlanState(planId string) (*shared.CurrentPlanState, *shared.ApiError)
- ApplyPlan(planId string) *shared.ApiError
- RejectAllChanges(planId string) *shared.ApiError
- RejectResult(planId, resultId string) *shared.ApiError
- RejectReplacement(planId, resultId, replacementId string) *shared.ApiError
+ GetCurrentPlanState(planId, branch string) (*shared.CurrentPlanState, *shared.ApiError)
+ ApplyPlan(planId, branch string) *shared.ApiError
+ RejectAllChanges(planId, branch string) *shared.ApiError
+ RejectResult(planId, branch, resultId string) *shared.ApiError
+ RejectReplacement(planId, branch, resultId, replacementId string) *shared.ApiError
+
+ LoadContext(planId, branch string, req shared.LoadContextRequest) (*shared.LoadContextResponse, *shared.ApiError)
+ UpdateContext(planId, branch string, req shared.UpdateContextRequest) (*shared.UpdateContextResponse, *shared.ApiError)
+ DeleteContext(planId, branch string, req shared.DeleteContextRequest) (*shared.DeleteContextResponse, *shared.ApiError)
+ ListContext(planId, branch string) ([]*shared.Context, *shared.ApiError)
- LoadContext(planId string, req shared.LoadContextRequest) (*shared.LoadContextResponse, *shared.ApiError)
- UpdateContext(planId string, req shared.UpdateContextRequest) (*shared.UpdateContextResponse, *shared.ApiError)
- DeleteContext(planId string, req shared.DeleteContextRequest) (*shared.DeleteContextResponse, *shared.ApiError)
- ListContext(planId string) ([]*shared.Context, *shared.ApiError)
+ ListConvo(planId, branch string) ([]*shared.ConvoMessage, *shared.ApiError)
+ ListLogs(planId, branch string) (*shared.LogResponse, *shared.ApiError)
+ RewindPlan(planId, branch string, req shared.RewindPlanRequest) (*shared.RewindPlanResponse, *shared.ApiError)
- ListConvo(planId string) ([]*shared.ConvoMessage, *shared.ApiError)
- ListLogs(planId string) (*shared.LogResponse, *shared.ApiError)
- RewindPlan(planId string, req shared.RewindPlanRequest) (*shared.RewindPlanResponse, *shared.ApiError)
+ ListBranches(planId string) ([]*shared.Branch, *shared.ApiError)
+ DeleteBranch(planId, branch string) *shared.ApiError
+ CreateBranch(planId, branch string, req shared.CreateBranchRequest) *shared.ApiError
}
diff --git a/app/cli/types/types.go b/app/cli/types/types.go
index 364e63d5..f27a87a2 100644
--- a/app/cli/types/types.go
+++ b/app/cli/types/types.go
@@ -41,11 +41,15 @@ const (
PlanOutdatedStrategyCancel string = "Cancel"
)
-type PlanSettings struct {
+type CurrentPlanSettings struct {
Id string `json:"id"`
}
-type ProjectSettings struct {
+type PlanSettings struct {
+ Branch string `json:"branch"`
+}
+
+type CurrentProjectSettings struct {
Id string `json:"id"`
}
diff --git a/app/server/db/convo_helpers.go b/app/server/db/convo_helpers.go
index cb47adcf..0a889e96 100644
--- a/app/server/db/convo_helpers.go
+++ b/app/server/db/convo_helpers.go
@@ -62,7 +62,7 @@ func GetPlanConvo(orgId, planId string) ([]*ConvoMessage, error) {
return convo, nil
}
-func StoreConvoMessage(message *ConvoMessage, commit bool) (string, error) {
+func StoreConvoMessage(message *ConvoMessage, currentUserId, branch string, commit bool) (string, error) {
convoDir := getPlanConversationDir(message.OrgId, message.PlanId)
ts := time.Now().UTC()
@@ -85,7 +85,7 @@ func StoreConvoMessage(message *ConvoMessage, commit bool) (string, error) {
return "", fmt.Errorf("error writing convo message: %v", err)
}
- err = AddPlanConvoMessage(message.PlanId, message.Tokens)
+ err = AddPlanConvoMessage(message, branch)
if err != nil {
return "", fmt.Errorf("error adding convo tokens: %v", err)
@@ -105,7 +105,7 @@ func StoreConvoMessage(message *ConvoMessage, commit bool) (string, error) {
msg := fmt.Sprintf("Message #%d | %s | %d 🪙", message.Num, desc, message.Tokens)
if commit {
- err = GitAddAndCommit(message.OrgId, message.PlanId, msg)
+ err = GitAddAndCommit(message.OrgId, message.PlanId, branch, msg)
if err != nil {
return "", fmt.Errorf("error committing convo message: %v", err)
}
@@ -113,39 +113,3 @@ func StoreConvoMessage(message *ConvoMessage, commit bool) (string, error) {
return msg, nil
}
-
-func GetPlanSummaries(planId string) ([]*ConvoSummary, error) {
- var summaries []*ConvoSummary
-
- err := Conn.Select(&summaries, "SELECT * FROM convo_summaries WHERE plan_id = $1 ORDER BY created_at", planId)
-
- if err != nil {
- return nil, fmt.Errorf("error getting plan summaries: %v", err)
- }
- return summaries, nil
-}
-
-func StoreSummary(summary *ConvoSummary) error {
- query := "INSERT INTO convo_summaries (org_id, plan_id, latest_convo_message_id, latest_convo_message_created_at, summary, tokens, num_messages) VALUES (:org_id, :plan_id, :latest_convo_message_id, :latest_convo_message_created_at, :summary, :tokens, :num_messages) RETURNING id, created_at"
-
- row, err := Conn.NamedQuery(query, summary)
-
- if err != nil {
- return fmt.Errorf("error storing summary: %v", err)
- }
-
- defer row.Close()
-
- if row.Next() {
- var createdAt time.Time
- var id string
- if err := row.Scan(&id, &createdAt); err != nil {
- return fmt.Errorf("error storing summary: %v", err)
- }
-
- summary.Id = id
- summary.CreatedAt = createdAt
- }
-
- return nil
-}
diff --git a/app/server/db/db.go b/app/server/db/db.go
index 520efd60..320ec981 100644
--- a/app/server/db/db.go
+++ b/app/server/db/db.go
@@ -57,17 +57,17 @@ func MigrationsUp() error {
// }
// Uncomment below to run down migrations (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("ran down migrations - database was reset")
- // }
+ 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("ran down migrations - database was reset")
+ }
err = m.Up()
diff --git a/app/server/db/git.go b/app/server/db/git.go
index 3b70e261..be740953 100644
--- a/app/server/db/git.go
+++ b/app/server/db/git.go
@@ -3,6 +3,7 @@ package db
import (
"bytes"
"fmt"
+ "log"
"os/exec"
"strconv"
"strings"
@@ -30,7 +31,7 @@ func InitGitRepo(orgId, planId string) error {
return nil
}
-func GitAddAndCommit(orgId, planId, message string) error {
+func GitAddAndCommit(orgId, planId, branch, message string) error {
dir := getPlanDir(orgId, planId)
err := gitAdd(dir, ".")
@@ -46,7 +47,7 @@ func GitAddAndCommit(orgId, planId, message string) error {
return nil
}
-func GitRewindToSha(orgId, planId, sha string) error {
+func GitRewindToSha(orgId, planId, branch, sha string) error {
dir := getPlanDir(orgId, planId)
err := gitRewindToSha(dir, sha)
@@ -57,7 +58,7 @@ func GitRewindToSha(orgId, planId, sha string) error {
return nil
}
-func GetGitCommitHistory(orgId, planId string) (body string, shas []string, err error) {
+func GetGitCommitHistory(orgId, planId, branch string) (body string, shas []string, err error) {
dir := getPlanDir(orgId, planId)
body, shas, err = getGitCommitHistory(dir)
@@ -68,7 +69,7 @@ func GetGitCommitHistory(orgId, planId string) (body string, shas []string, err
return body, shas, nil
}
-func GetLatestCommit(orgId, planId string) (sha, body string, err error) {
+func GetLatestCommit(orgId, planId, branch string) (sha, body string, err error) {
dir := getPlanDir(orgId, planId)
sha, body, err = getLatestCommit(dir)
@@ -79,6 +80,54 @@ func GetLatestCommit(orgId, planId string) (sha, body string, err error) {
return sha, body, nil
}
+func GitListBranches(orgId, planId string) ([]string, error) {
+ dir := getPlanDir(orgId, planId)
+
+ var out bytes.Buffer
+ cmd := exec.Command("git", "branch", "--format=%(refname:short)")
+ cmd.Dir = dir
+ cmd.Stdout = &out
+ err := cmd.Run()
+ if err != nil {
+ return nil, fmt.Errorf("error getting git branches for dir: %s, err: %v", dir, err)
+ }
+
+ branches := strings.Split(strings.TrimSpace(out.String()), "\n")
+
+ return branches, nil
+}
+
+func GitCreateBranch(orgId, planId, branch, newBranch string) error {
+ dir := getPlanDir(orgId, planId)
+
+ res, err := exec.Command("git", "-C", dir, "checkout", "-b", newBranch).CombinedOutput()
+ if err != nil {
+ return fmt.Errorf("error creating git branch for dir: %s, err: %v, output: %s", dir, err, string(res))
+ }
+
+ return nil
+}
+
+func GitDeleteBranch(orgId, planId, branchName string) error {
+ dir := getPlanDir(orgId, planId)
+
+ res, err := exec.Command("git", "-C", dir, "branch", "-D", branchName).CombinedOutput()
+ if err != nil {
+ return fmt.Errorf("error deleting git branch for dir: %s, err: %v, output: %s", dir, err, string(res))
+ }
+
+ return nil
+}
+
+func gitCheckoutBranch(repoDir, branch string) error {
+ res, err := exec.Command("git", "-C", repoDir, "checkout", branch).CombinedOutput()
+ if err != nil {
+ return fmt.Errorf("error checking out git branch for dir: %s, err: %v, output: %s", repoDir, err, string(res))
+ }
+
+ return nil
+}
+
func gitRewindToSha(repoDir, sha string) error {
res, err := exec.Command("git", "-C", repoDir, "reset", "--hard",
sha).CombinedOutput()
@@ -202,3 +251,143 @@ func gitCommit(repoDir, commitMsg string) error {
return nil
}
+
+// distributed locking to ensure only one user can write to a plan repo at a time
+// multiple readers are allowed, but read locks block writes
+// write lock is exclusive (blocks both reads and writes)
+const lockTimeout = 60 * time.Second
+
+func LockRepo(orgId, userId, planId, branch string, scope LockScope) (string, error) {
+ return lockRepo(orgId, userId, planId, branch, scope, 0)
+}
+
+func lockRepo(orgId, userId, planId, branch string, scope LockScope, numRetry int) (string, error) {
+ tx, err := Conn.Begin()
+ if err != nil {
+ return "", fmt.Errorf("error starting transaction: %v", err)
+ }
+
+ // Ensure that rollback is attempted in case of failure
+ defer func() {
+ if err != nil {
+ if rbErr := tx.Rollback(); rbErr != nil {
+ log.Printf("transaction rollback error: %v\n", rbErr)
+ } else {
+ log.Println("transaction rolled back")
+ }
+ }
+ }()
+
+ query := "SELECT * FROM repo_locks WHERE plan_id = $1 FOR UPDATE"
+ queryArgs := []interface{}{planId}
+
+ var locks []*repoLock
+
+ fn := func() error {
+ rows, err := tx.Query(query, queryArgs...)
+ if err != nil {
+ return fmt.Errorf("error getting repo locks: %v", err)
+ }
+
+ defer rows.Close()
+
+ now := time.Now()
+ for rows.Next() {
+ var lock repoLock
+ if err := rows.Scan(&lock.Id, &lock.OrgId, &lock.UserId, &lock.PlanId, &lock.Scope, &lock.CreatedAt); err != nil {
+ return fmt.Errorf("error scanning repo lock: %v", err)
+ }
+ if now.Sub(lock.CreatedAt) < lockTimeout {
+ locks = append(locks, &lock)
+ } else {
+ _, err = tx.Exec("DELETE FROM repo_locks WHERE id = $1", lock.Id)
+ if err != nil {
+ return fmt.Errorf("error removing expired lock: %v", err)
+ }
+ }
+ }
+
+ return nil
+ }
+ if err := fn(); err != nil {
+ return "", err
+ }
+
+ canAcquire := true
+ canRetry := true
+
+ for _, lock := range locks {
+ lockBranch := ""
+ if lock.Branch != nil {
+ lockBranch = *lock.Branch
+ }
+
+ if scope == LockScopeRead {
+ canAcquireThisLock := lock.Scope == LockScopeRead && lockBranch == branch
+
+ if !canAcquireThisLock {
+ canAcquire = false
+ }
+ } else if scope == LockScopeWrite {
+ canAcquire = false
+ if lock.Scope == LockScopeWrite && lockBranch == branch {
+ canRetry = false
+ }
+ } else {
+ err = fmt.Errorf("invalid lock scope: %v", scope)
+ return "", err
+ }
+ }
+
+ if !canAcquire {
+ if canRetry {
+ // 10 second timeout
+ if numRetry > 20 {
+ err = fmt.Errorf("plan is currently being updated by another user")
+ return "", err
+ }
+ time.Sleep(500 * time.Millisecond)
+ return lockRepo(orgId, userId, planId, branch, scope, numRetry+1)
+ }
+ err = fmt.Errorf("plan is currently being updated by another user")
+ return "", err
+ }
+
+ // Insert the new lock
+ newLock := &repoLock{
+ OrgId: orgId,
+ UserId: userId,
+ PlanId: planId,
+ Scope: scope,
+ }
+ insertQuery := "INSERT INTO repo_locks (org_id, user_id, plan_id, scope, branch) VALUES ($1, $2, $3, $4, $5) RETURNING id"
+ err = tx.QueryRow(insertQuery, newLock.OrgId, newLock.UserId, newLock.PlanId, newLock.Scope, branch).Scan(&newLock.Id)
+ if err != nil {
+ return "", fmt.Errorf("error inserting new lock: %v", err)
+ }
+
+ if branch != "" {
+ // checkout the branch
+ err = gitCheckoutBranch(getPlanDir(orgId, planId), branch)
+ if err != nil {
+ return "", fmt.Errorf("error checking out branch: %v", err)
+ }
+ }
+
+ // Commit the transaction
+ if err = tx.Commit(); err != nil {
+ return "", fmt.Errorf("error committing transaction: %v", err)
+ }
+
+ return newLock.Id, nil
+}
+
+func UnlockRepo(id string) error {
+ query := "DELETE FROM repo_locks WHERE id = $1"
+ _, err := Conn.Exec(query, id)
+ if err != nil {
+ return fmt.Errorf("error removing lock: %v", err)
+ }
+
+ return nil
+}
diff --git a/app/server/db/models.go b/app/server/db/models.go
index d0ca2c68..c0e406d0 100644
--- a/app/server/db/models.go
+++ b/app/server/db/models.go
@@ -124,35 +124,63 @@ type UserProject struct {
}
type Plan struct {
+ Id string `db:"id"`
+ OrgId string `db:"org_id"`
+ OwnerId string `db:"owner_id"`
+ ProjectId string `db:"project_id"`
+ Name string `db:"name"`
+ SharedWithOrgAt *time.Time `db:"shared_with_org_at,omitempty"`
+ TotalReplies int `db:"total_replies"`
+ ActiveBranches int `db:"active_branches"`
+ ArchivedAt *time.Time `db:"archived_at,omitempty"`
+ CreatedAt time.Time `db:"created_at"`
+ UpdatedAt time.Time `db:"updated_at"`
+}
+
+func (plan *Plan) ToApi() *shared.Plan {
+ return &shared.Plan{
+ Id: plan.Id,
+ OwnerId: plan.OwnerId,
+ Name: plan.Name,
+ SharedWithOrgAt: plan.SharedWithOrgAt,
+ TotalReplies: plan.TotalReplies,
+ ActiveBranches: plan.ActiveBranches,
+ ArchivedAt: plan.ArchivedAt,
+ CreatedAt: plan.CreatedAt,
+ UpdatedAt: plan.UpdatedAt,
+ }
+}
+
+type Branch struct {
Id string `db:"id"`
OrgId string `db:"org_id"`
OwnerId string `db:"owner_id"`
- ProjectId string `db:"project_id"`
+ PlanId string `db:"plan_id"`
+ ParentBranchId *string `db:"parent_branch_id"`
Name string `db:"name"`
Status shared.PlanStatus `db:"status"`
Error *string `db:"error"`
ContextTokens int `db:"context_tokens"`
ConvoTokens int `db:"convo_tokens"`
SharedWithOrgAt *time.Time `db:"shared_with_org_at,omitempty"`
- TotalMessages int `db:"total_messages"`
ArchivedAt *time.Time `db:"archived_at,omitempty"`
CreatedAt time.Time `db:"created_at"`
UpdatedAt time.Time `db:"updated_at"`
}
-func (plan *Plan) ToApi() *shared.Plan {
- return &shared.Plan{
- Id: plan.Id,
- OwnerId: plan.OwnerId,
- Name: plan.Name,
- Status: plan.Status,
- ContextTokens: plan.ContextTokens,
- ConvoTokens: plan.ConvoTokens,
- SharedWithOrgAt: plan.SharedWithOrgAt,
- TotalMessages: plan.TotalMessages,
- ArchivedAt: plan.ArchivedAt,
- CreatedAt: plan.CreatedAt,
- UpdatedAt: plan.UpdatedAt,
+func (branch *Branch) ToApi() *shared.Branch {
+ return &shared.Branch{
+ Id: branch.Id,
+ OwnerId: branch.OwnerId,
+ ParentBranchId: branch.ParentBranchId,
+ Name: branch.Name,
+ Status: branch.Status,
+ ContextTokens: branch.ContextTokens,
+ ConvoTokens: branch.ConvoTokens,
+ SharedWithOrgAt: branch.SharedWithOrgAt,
+ ArchivedAt: branch.ArchivedAt,
+ CreatedAt: branch.CreatedAt,
+ UpdatedAt: branch.UpdatedAt,
}
}
@@ -221,6 +249,43 @@ func (role *OrgRole) ToApi() *shared.OrgRole {
}
}
+type ModelStream struct {
+ Id string `db:"id"`
+ OrgId string `db:"org_id"`
+ PlanId string `db:"plan_id"`
+ InternalIp string `db:"internal_ip"`
+ CreatedAt time.Time `db:"created_at"`
+ FinishedAt *time.Time `db:"finished_at"`
+}
+
+// type ModelStreamSubscription struct {
+// Id string `db:"id"`
+// OrgId string `db:"org_id"`
+// PlanId string `db:"plan_id"`
+// UserId string `db:"user_id"`
+// ModelStreamId string `db:"model_stream_id"`
+// UserIp string `db:"user_ip"`
+// CreatedAt time.Time `db:"created_at"`
+// FinishedAt *time.Time `db:"finished_at"`
+// }
+
+type LockScope string
+
+const (
+ LockScopeRead LockScope = "r"
+ LockScopeWrite LockScope = "w"
+)
+
+type repoLock struct {
+ Id string `db:"id"`
+ OrgId string `db:"org_id"`
+ UserId string `db:"user_id"`
+ PlanId string `db:"plan_id"`
+ Scope LockScope `db:"scope"`
+ Branch *string `db:"branch"`
+ CreatedAt time.Time `db:"created_at"`
+}
+
// Models below are stored in files, not in the database.
// This allows us to store them in a git repo and use git to manage history.
diff --git a/app/server/db/plan_helpers.go b/app/server/db/plan_helpers.go
index a4531e88..e7850dff 100644
--- a/app/server/db/plan_helpers.go
+++ b/app/server/db/plan_helpers.go
@@ -1,6 +1,7 @@
package db
import (
+ "database/sql"
"encoding/json"
"fmt"
"log"
@@ -10,37 +11,58 @@ import (
"github.com/google/uuid"
"github.com/plandex/plandex/shared"
+ "github.com/sashabaranov/go-openai"
)
func CreatePlan(orgId, projectId, userId, name string) (*Plan, error) {
- query := "INSERT INTO plans (org_id, owner_id, project_id, name, status) VALUES (:org_id, :owner_id, :project_id, :name, :status) RETURNING id, created_at, updated_at"
+ // start a transaction
+ tx, err := Conn.Begin()
+ if err != nil {
+ return nil, fmt.Errorf("error starting transaction: %v", err)
+ }
+
+ // Ensure that rollback is attempted in case of failure
+ defer func() {
+ if err != nil {
+ if rbErr := tx.Rollback(); rbErr != nil {
+ log.Printf("transaction rollback error: %v\n", rbErr)
+ } else {
+ log.Println("transaction rolled back")
+ }
+ }
+ }()
+
+ query := `INSERT INTO plans (org_id, owner_id, project_id, name)
+ VALUES ($1, $2, $3, $4)
+ RETURNING id, created_at, updated_at`
plan := &Plan{
OrgId: orgId,
OwnerId: userId,
ProjectId: projectId,
Name: name,
- Status: shared.PlanStatusDraft,
}
- row, err := Conn.NamedQuery(query, plan)
+ err = tx.QueryRow(
+ query,
+ orgId,
+ userId,
+ projectId,
+ name,
+ ).Scan(
+ &plan.Id,
+ &plan.CreatedAt,
+ &plan.UpdatedAt,
+ )
if err != nil {
return nil, fmt.Errorf("error creating plan: %v", err)
}
- defer row.Close()
+ _, err = CreateBranch(plan, nil, "main", tx)
- if row.Next() {
- var createdAt, updatedAt time.Time
- var id string
- if err := row.Scan(&id, &createdAt, &updatedAt); err != nil {
- return nil, fmt.Errorf("error creating plan: %v", err)
- }
-
- plan.Id = id
- plan.CreatedAt = createdAt
- plan.UpdatedAt = updatedAt
+ if err != nil {
+ return nil, fmt.Errorf("error creating main branch: %v", err)
}
err = InitPlan(orgId, plan.Id)
@@ -52,8 +74,8 @@ func CreatePlan(orgId, projectId, userId, name string) (*Plan, error) {
return plan, nil
}
-func ListOwnedPlans(projectId, userId string, archived bool, status string) ([]shared.Plan, error) {
- qs := "SELECT id, owner_id, name, status, context_tokens, convo_tokens, shared_with_org_at, archived_at, created_at, updated_at FROM plans WHERE project_id = $1 AND owner_id = $2"
+func ListOwnedPlans(projectId, userId string, archived bool) ([]shared.Plan, error) {
+ qs := "SELECT id, owner_id, name, shared_with_org_at, archived_at, created_at, updated_at FROM plans WHERE project_id = $1 AND owner_id = $2"
qargs := []interface{}{projectId, userId}
if archived {
@@ -62,11 +84,6 @@ func ListOwnedPlans(projectId, userId string, archived bool, status string) ([]s
qs += " AND archived_at IS NULL"
}
- if status != "" {
- qs += " AND status = $3"
- qargs = append(qargs, status)
- }
-
qs += " ORDER BY updated_at DESC"
res, err := Conn.Query(qs, qargs...)
@@ -79,7 +96,7 @@ func ListOwnedPlans(projectId, userId string, archived bool, status string) ([]s
for res.Next() {
var plan shared.Plan
- err := res.Scan(&plan.Id, &plan.OwnerId, &plan.Name, &plan.Status, &plan.ContextTokens, &plan.ConvoTokens, &plan.SharedWithOrgAt, &plan.ArchivedAt, &plan.CreatedAt, &plan.UpdatedAt)
+ err := res.Scan(&plan.Id, &plan.OwnerId, &plan.Name, &plan.SharedWithOrgAt, &plan.ArchivedAt, &plan.CreatedAt, &plan.UpdatedAt)
if err != nil {
return nil, fmt.Errorf("error scanning plan: %v", err)
@@ -90,23 +107,52 @@ func ListOwnedPlans(projectId, userId string, archived bool, status string) ([]s
return plans, nil
}
-func AddPlanContextTokens(planId string, addTokens int) error {
- _, err := Conn.Exec("UPDATE plans SET context_tokens = context_tokens + $1 WHERE id = $2", addTokens, planId)
+func AddPlanContextTokens(planId, branch string, addTokens int) error {
+ _, err := Conn.Exec("UPDATE branches SET context_tokens = context_tokens + $1 WHERE plan_id = $2 AND name = $3", addTokens, planId, branch)
if err != nil {
return fmt.Errorf("error updating plan tokens: %v", err)
}
return nil
}
-func AddPlanConvoMessage(planId string, addTokens int) error {
- _, err := Conn.Exec("UPDATE plans SET convo_tokens = convo_tokens + $1, total_messages = total_messages + 1 WHERE id = $2", addTokens, planId)
- if err != nil {
- return fmt.Errorf("error updating plan tokens: %v", err)
+func AddPlanConvoMessage(msg *ConvoMessage, branch string) error {
+ errCh := make(chan error)
+
+ go func() {
+ _, err := Conn.Exec("UPDATE branches SET convo_tokens = convo_tokens + $1 WHERE plan_id = $2 AND name = $3", msg.Tokens, msg.PlanId, branch)
+
+ if err != nil {
+ errCh <- fmt.Errorf("error updating plan tokens: %v", err)
+ return
+ }
+
+ errCh <- nil
+ }()
+
+ go func() {
+ if msg.Role != openai.ChatMessageRoleAssistant {
+ errCh <- nil
+ return
+ }
+ _, err := Conn.Exec("UPDATE plans SET total_replies = total_replies + 1 WHERE id = $1", msg.PlanId)
+ if err != nil {
+ errCh <- fmt.Errorf("error updating plan total replies: %v", err)
+ }
+
+ errCh <- nil
+ }()
+
+ for i := 0; i < 2; i++ {
+ err := <-errCh
+ if err != nil {
+ return fmt.Errorf("error updating plan tokens: %v", err)
+ }
}
+
return nil
}
-func SyncPlanTokens(orgId, planId string) error {
+func SyncPlanTokens(orgId, planId, branch string) error {
var contexts []*Context
var convos []*ConvoMessage
errCh := make(chan error)
@@ -152,7 +198,7 @@ func SyncPlanTokens(orgId, planId string) error {
func GetPlan(planId string) (*Plan, error) {
var plan Plan
- err := Conn.Get(&plan, "SELECT id, org_id, owner_id, project_id, name, status, error, context_tokens, convo_tokens, shared_with_org_at, total_messages, archived_at, created_at, updated_at FROM plans WHERE id = $1", planId)
+ err := Conn.Get(&plan, "SELECT id, org_id, owner_id, project_id, name, status, error, context_tokens, convo_tokens, shared_with_org_at, total_replies, archived_at, created_at, updated_at FROM plans WHERE id = $1", planId)
if err != nil {
return nil, fmt.Errorf("error getting plan: %v", err)
@@ -181,6 +227,16 @@ func RenamePlan(planId string, name string) error {
return nil
}
+func IncActiveBranches(planId string, inc int, tx *sql.Tx) error {
+ _, err := tx.Exec("UPDATE plans SET active_branches = active_branches + $1 WHERE id = $2", inc, planId)
+
+ if err != nil {
+ return fmt.Errorf("error updating plan active branches: %v", err)
+ }
+
+ return nil
+}
+
func IncNumNonDraftPlans(userId string) error {
_, err := Conn.Exec("UPDATE users SET num_non_draft_plans = num_non_draft_plans + 1 WHERE id = $1", userId)
diff --git a/app/server/db/result_helpers.go b/app/server/db/result_helpers.go
index 99b67f91..5a5dcc14 100644
--- a/app/server/db/result_helpers.go
+++ b/app/server/db/result_helpers.go
@@ -297,7 +297,7 @@ func GetPlanResult(planFileResults []*shared.PlanFileResult) *shared.PlanResult
}
}
-func ApplyPlan(orgId, planId string) error {
+func ApplyPlan(orgId, planId, branch string) error {
resultsDir := getPlanResultsDir(orgId, planId)
errCh := make(chan error)
@@ -414,7 +414,7 @@ func ApplyPlan(orgId, planId string) error {
msg := "Marked pending results as applied." + "\n\n" + planState.PendingChangesSummary()
- err = GitAddAndCommit(orgId, planId, msg)
+ err = GitAddAndCommit(orgId, planId, branch, msg)
if err != nil {
return fmt.Errorf("error committing plan: %v", err)
diff --git a/app/server/handlers/plans_changes.go b/app/server/handlers/plans_changes.go
index 2b076c9a..ac0f0639 100644
--- a/app/server/handlers/plans_changes.go
+++ b/app/server/handlers/plans_changes.go
@@ -27,6 +27,13 @@ func CurrentPlanHandler(w http.ResponseWriter, r *http.Request) {
return
}
+ unlockFn := lockRepo(w, r, auth, db.LockScopeRead)
+ if unlockFn == nil {
+ return
+ } else {
+ defer (*unlockFn)()
+ }
+
contexts, err := db.GetPlanContexts(auth.OrgId, planId, true)
if err != nil {
@@ -70,13 +77,21 @@ func ApplyPlanHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
planId := vars["planId"]
+ branch := vars["branch"]
log.Println("planId: ", planId)
if authorizePlan(w, planId, auth) == nil {
return
}
- err := db.ApplyPlan(auth.OrgId, planId)
+ unlockFn := lockRepo(w, r, auth, db.LockScopeWrite)
+ if unlockFn == nil {
+ return
+ } else {
+ defer (*unlockFn)()
+ }
+
+ err := db.ApplyPlan(auth.OrgId, planId, branch)
if err != nil {
log.Printf("Error applying plan: %v\n", err)
@@ -103,6 +118,13 @@ func RejectAllChangesHandler(w http.ResponseWriter, r *http.Request) {
return
}
+ unlockFn := lockRepo(w, r, auth, db.LockScopeWrite)
+ if unlockFn == nil {
+ return
+ } else {
+ defer (*unlockFn)()
+ }
+
err := db.RejectAllResults(auth.OrgId, planId)
if err != nil {
@@ -132,6 +154,13 @@ func RejectResultHandler(w http.ResponseWriter, r *http.Request) {
return
}
+ unlockFn := lockRepo(w, r, auth, db.LockScopeWrite)
+ if unlockFn == nil {
+ return
+ } else {
+ defer (*unlockFn)()
+ }
+
err := db.RejectPlanFileResult(auth.OrgId, planId, resultId, time.Now())
if err != nil {
@@ -162,6 +191,13 @@ func RejectReplacementHandler(w http.ResponseWriter, r *http.Request) {
return
}
+ unlockFn := lockRepo(w, r, auth, db.LockScopeWrite)
+ if unlockFn == nil {
+ return
+ } else {
+ defer (*unlockFn)()
+ }
+
err := db.RejectReplacement(auth.OrgId, planId, resultId, replacementId)
if err != nil {
diff --git a/app/server/handlers/plans_context.go b/app/server/handlers/plans_context.go
index 54ebfaf0..660609ad 100644
--- a/app/server/handlers/plans_context.go
+++ b/app/server/handlers/plans_context.go
@@ -32,6 +32,13 @@ func ListContextHandler(w http.ResponseWriter, r *http.Request) {
return
}
+ unlockFn := lockRepo(w, r, auth, db.LockScopeRead)
+ if unlockFn == nil {
+ return
+ } else {
+ defer (*unlockFn)()
+ }
+
dbContexts, err := db.GetPlanContexts(auth.OrgId, planId, false)
if err != nil {
@@ -68,9 +75,18 @@ func LoadContextHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
planId := vars["planId"]
+ branchName := vars["branch"]
log.Println("planId: ", planId)
- if authorizePlan(w, planId, auth) == nil {
+ plan := authorizePlan(w, planId, auth)
+ if plan == nil {
+ return
+ }
+
+ branch, err := db.GetDbBranch(planId, branchName)
+ if err != nil {
+ log.Printf("Error getting branch: %v\n", err)
+ http.Error(w, "Error getting branch: "+err.Error(), http.StatusInternalServerError)
return
}
@@ -90,17 +106,9 @@ func LoadContextHandler(w http.ResponseWriter, r *http.Request) {
return
}
- // load plan
- plan, err := db.GetPlan(planId)
-
- if err != nil {
- log.Printf("Plan not found: %v\n", err)
- http.Error(w, "Plan not found: "+err.Error(), http.StatusBadRequest)
- }
-
maxTokens := shared.MaxContextTokens
tokensAdded := 0
- totalTokens := plan.ContextTokens
+ totalTokens := branch.ContextTokens
paramsByTempId := make(map[string]*shared.LoadContextParams)
numTokensByTempId := make(map[string]int)
@@ -142,6 +150,13 @@ func LoadContextHandler(w http.ResponseWriter, r *http.Request) {
return
}
+ unlockFn := lockRepo(w, r, auth, db.LockScopeWrite)
+ if unlockFn == nil {
+ return
+ } else {
+ defer (*unlockFn)()
+ }
+
dbContextsCh := make(chan *db.Context)
errCh := make(chan error)
for tempId, params := range paramsByTempId {
@@ -192,7 +207,7 @@ func LoadContextHandler(w http.ResponseWriter, r *http.Request) {
}
commitMsg := shared.SummaryForLoadContext(apiContexts, tokensAdded, totalTokens) + "\n\n" + shared.TableForLoadContext(apiContexts)
- err = db.GitAddAndCommit(auth.OrgId, planId, commitMsg)
+ err = db.GitAddAndCommit(auth.OrgId, planId, branchName, commitMsg)
if err != nil {
log.Printf("Error committing changes: %v\n", err)
@@ -200,7 +215,7 @@ func LoadContextHandler(w http.ResponseWriter, r *http.Request) {
return
}
- err = db.AddPlanContextTokens(planId, tokensAdded)
+ err = db.AddPlanContextTokens(planId, branchName, tokensAdded)
if err != nil {
log.Printf("Error updating plan tokens: %v\n", err)
http.Error(w, "Error updating plan tokens: "+err.Error(), http.StatusInternalServerError)
@@ -236,9 +251,18 @@ func UpdateContextHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
planId := vars["planId"]
+ branchName := vars["branch"]
log.Println("planId: ", planId)
- if authorizePlan(w, planId, auth) == nil {
+ plan := authorizePlan(w, planId, auth)
+ if plan == nil {
+ return
+ }
+
+ branch, err := db.GetDbBranch(planId, branchName)
+ if err != nil {
+ log.Printf("Error getting branch: %v\n", err)
+ http.Error(w, "Error getting branch: "+err.Error(), http.StatusInternalServerError)
return
}
@@ -258,17 +282,9 @@ func UpdateContextHandler(w http.ResponseWriter, r *http.Request) {
return
}
- // load plan
- plan, err := db.GetPlan(planId)
-
- if err != nil {
- log.Printf("Plan not found: %v\n", err)
- http.Error(w, "Plan not found: "+err.Error(), http.StatusBadRequest)
- }
-
maxTokens := shared.MaxContextTokens
tokensDiff := 0
- totalTokens := plan.ContextTokens
+ totalTokens := branch.ContextTokens
tokensDiffById := make(map[string]int)
contextsById := make(map[string]*db.Context)
var updatedContexts []*shared.Context
@@ -352,6 +368,13 @@ func UpdateContextHandler(w http.ResponseWriter, r *http.Request) {
return
}
+ unlockFn := lockRepo(w, r, auth, db.LockScopeWrite)
+ if unlockFn == nil {
+ return
+ } else {
+ defer (*unlockFn)()
+ }
+
errCh = make(chan error)
for id, params := range requestBody {
@@ -389,7 +412,7 @@ func UpdateContextHandler(w http.ResponseWriter, r *http.Request) {
}
commitMsg := shared.SummaryForUpdateContext(updateRes) + "\n\n" + shared.TableForContextUpdate(updateRes)
- err = db.GitAddAndCommit(auth.OrgId, planId, commitMsg)
+ err = db.GitAddAndCommit(auth.OrgId, planId, branchName, commitMsg)
if err != nil {
log.Printf("Error committing changes: %v\n", err)
@@ -397,7 +420,7 @@ func UpdateContextHandler(w http.ResponseWriter, r *http.Request) {
return
}
- err = db.AddPlanContextTokens(planId, tokensDiff)
+ err = db.AddPlanContextTokens(planId, branchName, tokensDiff)
if err != nil {
log.Printf("Error updating plan tokens: %v\n", err)
http.Error(w, "Error updating plan tokens: "+err.Error(), http.StatusInternalServerError)
@@ -433,6 +456,7 @@ func DeleteContextHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
planId := vars["planId"]
+ branchName := vars["branch"]
log.Println("planId: ", planId)
plan := authorizePlan(w, planId, auth)
@@ -441,6 +465,8 @@ func DeleteContextHandler(w http.ResponseWriter, r *http.Request) {
return
}
+ branch, err := db.GetDbBranch(planId, branchName)
+
// read the request body
body, err := io.ReadAll(r.Body)
if err != nil {
@@ -457,6 +483,13 @@ func DeleteContextHandler(w http.ResponseWriter, r *http.Request) {
return
}
+ unlockFn := lockRepo(w, r, auth, db.LockScopeWrite)
+ if unlockFn == nil {
+ return
+ } else {
+ defer (*unlockFn)()
+ }
+
dbContexts, err := db.GetPlanContexts(auth.OrgId, planId, false)
if err != nil {
@@ -487,8 +520,8 @@ func DeleteContextHandler(w http.ResponseWriter, r *http.Request) {
removeTokens += dbContext.NumTokens
}
- commitMsg := shared.SummaryForRemoveContext(toRemoveApiContexts, plan.ContextTokens) + "\n\n" + shared.TableForRemoveContext(toRemoveApiContexts)
- err = db.GitAddAndCommit(auth.OrgId, planId, commitMsg)
+ commitMsg := shared.SummaryForRemoveContext(toRemoveApiContexts, branch.ContextTokens) + "\n\n" + shared.TableForRemoveContext(toRemoveApiContexts)
+ err = db.GitAddAndCommit(auth.OrgId, planId, branchName, commitMsg)
if err != nil {
log.Printf("Error committing changes: %v\n", err)
@@ -496,7 +529,7 @@ func DeleteContextHandler(w http.ResponseWriter, r *http.Request) {
return
}
- err = db.AddPlanContextTokens(planId, -removeTokens)
+ err = db.AddPlanContextTokens(planId, branchName, -removeTokens)
if err != nil {
log.Printf("Error updating plan tokens: %v\n", err)
http.Error(w, "Error updating plan tokens: "+err.Error(), http.StatusInternalServerError)
@@ -505,7 +538,7 @@ func DeleteContextHandler(w http.ResponseWriter, r *http.Request) {
res := shared.DeleteContextResponse{
TokensRemoved: removeTokens,
- TotalTokens: plan.ContextTokens - removeTokens,
+ TotalTokens: branch.ContextTokens - removeTokens,
Msg: commitMsg,
}
diff --git a/app/server/handlers/plans_convo.go b/app/server/handlers/plans_convo.go
index 7bb3e873..4509b21d 100644
--- a/app/server/handlers/plans_convo.go
+++ b/app/server/handlers/plans_convo.go
@@ -25,6 +25,13 @@ func ListConvoHandler(w http.ResponseWriter, r *http.Request) {
return
}
+ unlockFn := lockRepo(w, r, auth, db.LockScopeRead)
+ if unlockFn == nil {
+ return
+ } else {
+ defer (*unlockFn)()
+ }
+
convoMessage, err := db.GetPlanConvo(auth.OrgId, planId)
if err != nil {
diff --git a/app/server/handlers/plans_crud.go b/app/server/handlers/plans_crud.go
index 4647719a..1c04d7f8 100644
--- a/app/server/handlers/plans_crud.go
+++ b/app/server/handlers/plans_crud.go
@@ -9,6 +9,7 @@ import (
"os"
"plandex-server/db"
"plandex-server/types"
+ "strings"
"github.com/gorilla/mux"
"github.com/plandex/plandex/shared"
@@ -255,7 +256,8 @@ func DeleteAllPlansHandler(w http.ResponseWriter, r *http.Request) {
}
func ListPlansHandler(w http.ResponseWriter, r *http.Request) {
- log.Println("Received request for ListPlansHandler")
+ log.Println("Received request for ListPlans")
+
auth := authenticate(w, r, true)
if auth == nil {
return
@@ -270,24 +272,101 @@ func ListPlansHandler(w http.ResponseWriter, r *http.Request) {
return
}
- plans, err := db.ListOwnedPlans(projectId, auth.User.Id, false, "")
+ plans, err := db.ListOwnedPlans(projectId, auth.User.Id, false)
if err != nil {
- log.Printf("Error listing plans: %v\n", err)
- http.Error(w, "Error listing plans: "+err.Error(), http.StatusInternalServerError)
+ log.Printf("Error listing plan ids: %v\n", err)
+ http.Error(w, "Error listing plan ids: "+err.Error(), http.StatusInternalServerError)
return
}
- jsonBytes, err := json.Marshal(plans)
+ bytes, err := json.Marshal(plans)
+
if err != nil {
- log.Printf("Error marshalling plans: %v\n", err)
- http.Error(w, "Error marshalling plans: "+err.Error(), http.StatusInternalServerError)
+ log.Printf("Error marshalling plan ids: %v\n", err)
+ http.Error(w, "Error marshalling plan ids: "+err.Error(), http.StatusInternalServerError)
return
}
- log.Println("Successfully processed ListPlansHandler request")
+ w.Write(bytes)
+}
- w.Write(jsonBytes)
+func GetCurrentBranchByPlanIdHandler(w http.ResponseWriter, r *http.Request) {
+ log.Println("Received request for CurrentBranchByPlanIdHandler")
+ auth := authenticate(w, r, true)
+ if auth == nil {
+ return
+ }
+
+ vars := mux.Vars(r)
+ projectId := vars["projectId"]
+
+ log.Println("projectId: ", projectId)
+
+ if !authorizeProject(w, projectId, auth) {
+ return
+ }
+
+ var req shared.GetCurrentBranchByPlanIdRequest
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ log.Printf("Error parsing request body: %v\n", err)
+ http.Error(w, "Error parsing request body", http.StatusBadRequest)
+ return
+ }
+
+ plans, err := db.ListOwnedPlans(projectId, auth.User.Id, false)
+
+ if err != nil {
+ log.Printf("Error listing plan ids: %v\n", err)
+ http.Error(w, "Error listing plan ids: "+err.Error(), http.StatusInternalServerError)
+ return
+ }
+
+ query := "SELECT * FROM branches WHERE "
+
+ var orConditions []string
+ var queryArgs []interface{}
+ currentArg := 1
+ for _, plan := range plans {
+ branchName, ok := req.CurrentBranchByPlanId[plan.Id]
+
+ if !ok {
+ continue
+ }
+
+ orConditions = append(orConditions, fmt.Sprintf("(plan_id = $%d AND name = $%d)", currentArg, currentArg+1))
+ queryArgs = append(queryArgs, plan.Id, branchName)
+
+ currentArg += 2
+ }
+
+ query += "(" + strings.Join(orConditions, " OR ") + ") AND archived_at IS NULL AND deleted_at IS NULL"
+
+ var branches []db.Branch
+ err = db.Conn.Select(&branches, query, queryArgs...)
+
+ if err != nil {
+ log.Printf("Error getting branches: %v\n", err)
+ http.Error(w, "Error getting branches: "+err.Error(), http.StatusInternalServerError)
+ return
+ }
+
+ res := map[string]*shared.Branch{}
+ for _, branch := range branches {
+ res[branch.PlanId] = branch.ToApi()
+ }
+
+ bytes, err := json.Marshal(res)
+
+ if err != nil {
+ log.Printf("Error marshalling branches: %v\n", err)
+ http.Error(w, "Error marshalling branches: "+err.Error(), http.StatusInternalServerError)
+ return
+ }
+
+ log.Println("Successfully processed GetCurrentBranchByPlanIdHandler request")
+
+ w.Write(bytes)
}
func ListArchivedPlansHandler(w http.ResponseWriter, r *http.Request) {
@@ -306,7 +385,7 @@ func ListArchivedPlansHandler(w http.ResponseWriter, r *http.Request) {
return
}
- plans, err := db.ListOwnedPlans(projectId, "", true, "")
+ plans, err := db.ListOwnedPlans(projectId, "", true)
if err != nil {
log.Printf("Error listing plans: %v\n", err)
diff --git a/app/server/handlers/plans_exec.go b/app/server/handlers/plans_exec.go
index b68c8815..5736aa0f 100644
--- a/app/server/handlers/plans_exec.go
+++ b/app/server/handlers/plans_exec.go
@@ -14,7 +14,7 @@ import (
"github.com/plandex/plandex/shared"
)
-const TrialMaxMessages = 15
+const TrialMaxReplies = 10
func TellPlanHandler(w http.ResponseWriter, r *http.Request) {
log.Println("Received request for TellPlanHandler")
@@ -26,6 +26,7 @@ func TellPlanHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
planId := vars["planId"]
+ branch := vars["branch"]
log.Println("planId: ", planId)
@@ -69,13 +70,13 @@ func TellPlanHandler(w http.ResponseWriter, r *http.Request) {
}
if user.IsTrial {
- if plan.TotalMessages >= types.TrialMaxMessages {
+ if plan.TotalReplies >= types.TrialMaxReplies {
writeApiError(w, shared.ApiError{
Type: shared.ApiErrorTypeTrialMessagesExceeded,
Status: http.StatusForbidden,
Msg: "Free trial message limit exceeded",
TrialMessagesExceededError: &shared.TrialMessagesExceededError{
- MaxMessages: types.TrialMaxMessages,
+ MaxReplies: types.TrialMaxReplies,
},
})
return
@@ -83,7 +84,7 @@ func TellPlanHandler(w http.ResponseWriter, r *http.Request) {
}
}
- err = model.Tell(plan, auth, &requestBody)
+ err = model.Tell(plan, branch, auth, &requestBody)
if err != nil {
log.Printf("Error telling plan: %v\n", err)
@@ -139,6 +140,8 @@ func ConnectPlanHandler(w http.ResponseWriter, r *http.Request) {
}
func StopPlanHandler(w http.ResponseWriter, r *http.Request) {
+ // TODO: this handler should lookup the IP of the active plan stream and forward the request if it's not the same as this server's IP
+
log.Println("Received request for StopPlanHandler")
auth := authenticate(w, r, true)
if auth == nil {
@@ -147,6 +150,7 @@ func StopPlanHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
planId := vars["planId"]
+ branch := vars["branch"]
log.Println("planId: ", planId)
@@ -154,4 +158,20 @@ func StopPlanHandler(w http.ResponseWriter, r *http.Request) {
return
}
+ unlockFn := lockRepo(w, r, auth, db.LockScopeWrite)
+ if unlockFn == nil {
+ return
+ } else {
+ defer (*unlockFn)()
+ }
+
+ err := model.Stop(planId, branch, auth.User.Id, auth.OrgId)
+
+ if err != nil {
+ log.Printf("Error stopping plan: %v\n", err)
+ http.Error(w, "Error stopping plan", http.StatusInternalServerError)
+ return
+ }
+
+ log.Println("Successfully processed request for StopPlanHandler")
}
diff --git a/app/server/handlers/plans_versions.go b/app/server/handlers/plans_versions.go
index 653a03bf..26e5d769 100644
--- a/app/server/handlers/plans_versions.go
+++ b/app/server/handlers/plans_versions.go
@@ -21,6 +21,7 @@ func ListLogsHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
planId := vars["planId"]
+ branch := vars["branch"]
log.Println("planId: ", planId)
@@ -28,7 +29,14 @@ func ListLogsHandler(w http.ResponseWriter, r *http.Request) {
return
}
- body, shas, err := db.GetGitCommitHistory(auth.OrgId, planId)
+ unlockFn := lockRepo(w, r, auth, db.LockScopeRead)
+ if unlockFn == nil {
+ return
+ } else {
+ defer (*unlockFn)()
+ }
+
+ body, shas, err := db.GetGitCommitHistory(auth.OrgId, planId, branch)
if err != nil {
log.Println("Error getting logs: ", err)
@@ -64,6 +72,7 @@ func RewindPlanHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
planId := vars["planId"]
+ branch := vars["branch"]
log.Println("planId: ", planId)
@@ -87,7 +96,14 @@ func RewindPlanHandler(w http.ResponseWriter, r *http.Request) {
return
}
- err = db.GitRewindToSha(auth.OrgId, planId, requestBody.Sha)
+ unlockFn := lockRepo(w, r, auth, db.LockScopeWrite)
+ if unlockFn == nil {
+ return
+ } else {
+ defer (*unlockFn)()
+ }
+
+ err = db.GitRewindToSha(auth.OrgId, planId, branch, requestBody.Sha)
if err != nil {
log.Println("Error rewinding plan: ", err)
@@ -95,7 +111,7 @@ func RewindPlanHandler(w http.ResponseWriter, r *http.Request) {
return
}
- err = db.SyncPlanTokens(auth.OrgId, planId)
+ err = db.SyncPlanTokens(auth.OrgId, planId, branch)
if err != nil {
log.Println("Error syncing plan tokens: ", err)
@@ -103,7 +119,7 @@ func RewindPlanHandler(w http.ResponseWriter, r *http.Request) {
return
}
- sha, latest, err := db.GetLatestCommit(auth.OrgId, planId)
+ sha, latest, err := db.GetLatestCommit(auth.OrgId, planId, branch)
if err != nil {
log.Println("Error getting latest commit: ", err)
diff --git a/app/server/main.go b/app/server/main.go
index 45bf897a..5858c914 100644
--- a/app/server/main.go
+++ b/app/server/main.go
@@ -5,19 +5,27 @@ import (
"log"
"net/http"
"os"
+ "os/signal"
"plandex-server/db"
+ "plandex-server/host"
+ "plandex-server/model/plan"
+ "syscall"
+ "time"
- openai "github.com/sashabaranov/go-openai"
+ "github.com/gorilla/mux"
)
-var client *openai.Client
-
func main() {
if os.Getenv("OPENAI_API_KEY") == "" {
log.Fatal("OPENAI_API_KEY environment variable is not set")
}
- err := db.Connect()
+ err := host.LoadIp()
+ if err != nil {
+ log.Fatal("Error loading IP: ", err)
+ }
+
+ err = db.Connect()
if err != nil {
log.Fatal("Error initializing database: ", err)
}
@@ -27,14 +35,39 @@ func main() {
log.Fatal("Error running migrations: ", err)
}
- routes := InitRoutes()
-
- // Get port from the environment variable or default to 8088
- port := os.Getenv("PORT")
- if port == "" {
- port = "8088"
+ // Get externalPort from the environment variable or default to 8088
+ externalPort := os.Getenv("PORT")
+ if externalPort == "" {
+ externalPort = "8088"
}
- log.Printf("Plandex server is running on :%s", port)
- log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", port), routes))
+ go startServer(externalPort, routes())
+ log.Println("Started server on port " + externalPort)
+
+ sigTermChan := make(chan os.Signal, 1)
+ signal.Notify(sigTermChan, syscall.SIGTERM)
+
+ go func() {
+ <-sigTermChan
+
+ for {
+ l := plan.Active.Len()
+ if l == 0 {
+ break
+ }
+ log.Printf("Waiting for %d active plans to finish...\n", l)
+ time.Sleep(1 * time.Second)
+ }
+
+ os.Exit(0)
+ }()
+
+ select {}
+}
+
+func startServer(port string, routes *mux.Router) {
+ err := http.ListenAndServe(fmt.Sprintf(":%s", port), routes)
+ if err != nil {
+ log.Fatalf("Failed to start server on port %s: %v", port, err)
+ }
}
diff --git a/app/server/migrations/2023120500_init.up.sql b/app/server/migrations/2023120500_init.up.sql
index fa2eeead..f6dc307c 100644
--- a/app/server/migrations/2023120500_init.up.sql
+++ b/app/server/migrations/2023120500_init.up.sql
@@ -103,21 +103,40 @@ CREATE TABLE IF NOT EXISTS plans (
org_id UUID NOT NULL REFERENCES orgs(id) ON DELETE CASCADE,
owner_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
project_id UUID NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
+ name VARCHAR(255) NOT NULL,
+ shared_with_org_at TIMESTAMP,
+ total_replies INTEGER NOT NULL DEFAULT 0,
+ active_branches INTEGER NOT NULL DEFAULT 0,
+ archived_at TIMESTAMP,
+ created_at TIMESTAMP NOT NULL DEFAULT NOW(),
+ updated_at TIMESTAMP NOT NULL DEFAULT NOW()
+);
+CREATE TRIGGER update_plans_modtime BEFORE UPDATE ON plans FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
+
+CREATE INDEX plans_name_idx ON plans(project_id, owner_id, name);
+CREATE INDEX plans_archived_idx ON plans(project_id, owner_id, archived_at);
+
+CREATE TABLE IF NOT EXISTS branches (
+ id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
+ org_id UUID NOT NULL REFERENCES orgs(id) ON DELETE CASCADE,
+ owner_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ plan_id UUID NOT NULL REFERENCES plans(id) ON DELETE CASCADE,
+ parent_branch_id UUID REFERENCES branches(id) ON DELETE CASCADE,
name VARCHAR(255) NOT NULL,
status VARCHAR(32) NOT NULL,
error TEXT,
context_tokens INTEGER NOT NULL DEFAULT 0,
convo_tokens INTEGER NOT NULL DEFAULT 0,
shared_with_org_at TIMESTAMP,
- total_messages INTEGER NOT NULL DEFAULT 0,
archived_at TIMESTAMP,
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
updated_at TIMESTAMP NOT NULL DEFAULT NOW()
+ deleted_at TIMESTAMP
);
-CREATE TRIGGER update_plans_modtime BEFORE UPDATE ON plans FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
+CREATE TRIGGER update_branches_modtime BEFORE UPDATE ON branches FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();
+
+CREATE UNIQUE INDEX branches_name_idx ON branches(plan_id, name, archived_at, deleted_at);
-CREATE INDEX plans_name_idx ON plans(project_id, owner_id, name);
-CREATE INDEX plans_archived_idx ON plans(project_id, owner_id, archived_at);
CREATE TABLE IF NOT EXISTS users_projects (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
diff --git a/app/server/migrations/2024012400_hosts.down.sql b/app/server/migrations/2024012400_hosts.down.sql
deleted file mode 100644
index 246d46ed..00000000
--- a/app/server/migrations/2024012400_hosts.down.sql
+++ /dev/null
@@ -1 +0,0 @@
-DROP TABLE IF EXISTS hosts;
\ No newline at end of file
diff --git a/app/server/migrations/2024012400_hosts.up.sql b/app/server/migrations/2024012400_hosts.up.sql
deleted file mode 100644
index 83e62303..00000000
--- a/app/server/migrations/2024012400_hosts.up.sql
+++ /dev/null
@@ -1,5 +0,0 @@
-CREATE UNLOGGED TABLE IF NOT EXISTS hosts (
- ip VARCHAR(45) PRIMARY KEY,
- active_at TIMESTAMP NOT NULL,
- created_at TIMESTAMP NOT NULL DEFAULT NOW()
-);
\ No newline at end of file
diff --git a/app/server/model/plan/build.go b/app/server/model/plan/build.go
index adbdbce1..84154166 100644
--- a/app/server/model/plan/build.go
+++ b/app/server/model/plan/build.go
@@ -24,7 +24,7 @@ import (
const MaxRetries = 3
const MaxReplacementRetries = 1
-func QueueBuild(currentOrgId, planId string, activeBuild *types.ActiveBuild) {
+func QueueBuild(currentOrgId, currentUserId, planId, branch string, activeBuild *types.ActiveBuild) {
activePlan := Active.Get(planId)
filePath := activeBuild.Path
@@ -38,11 +38,11 @@ func QueueBuild(currentOrgId, planId string, activeBuild *types.ActiveBuild) {
return
} else {
log.Printf("Will process build queue for file %s\n", filePath)
- go execPlanBuild(currentOrgId, activePlan, activeBuild)
+ go execPlanBuild(currentOrgId, currentUserId, branch, activePlan, activeBuild)
}
}
-func execPlanBuild(currentOrgId string, activePlan *types.ActivePlan, activeBuild *types.ActiveBuild) {
+func execPlanBuild(currentOrgId, currentUserId, branch string, activePlan *types.ActivePlan, activeBuild *types.ActiveBuild) {
Active.Update(activePlan.Id, func(ap *types.ActivePlan) {
ap.IsBuildingByPath[activeBuild.Path] = true
})
@@ -141,17 +141,42 @@ func execPlanBuild(currentOrgId string, activePlan *types.ActivePlan, activeBuil
// log.Println("onFinishBuildFile: " + filePath)
// spew.Dump(planRes)
- err := db.StorePlanResult(planRes)
+ repoLockId, err := db.LockRepo(currentOrgId, currentUserId, planId, branch, db.LockScopeWrite)
if err != nil {
- log.Printf("Error storing plan result: %v\n", err)
+ log.Printf("Error locking repo: %v\n", err)
activePlan.StreamDoneCh <- &shared.ApiError{
Type: shared.ApiErrorTypeOther,
Status: http.StatusInternalServerError,
- Msg: "Error storing plan result: " + err.Error(),
+ Msg: "Error locking repo: " + err.Error(),
}
return
}
+ err = func() error {
+ defer func() {
+ err := db.UnlockRepo(repoLockId)
+ if err != nil {
+ log.Printf("Error unlocking repo: %v\n", err)
+ }
+ }()
+
+ err = db.StorePlanResult(planRes)
+ if err != nil {
+ log.Printf("Error storing plan result: %v\n", err)
+ activePlan.StreamDoneCh <- &shared.ApiError{
+ Type: shared.ApiErrorTypeOther,
+ Status: http.StatusInternalServerError,
+ Msg: "Error storing plan result: " + err.Error(),
+ }
+ return err
+ }
+ return nil
+ }()
+
+ if err != nil {
+ return
+ }
+
activeBuild.Success = true
Active.Update(planId, func(ap *types.ActivePlan) {
@@ -173,7 +198,7 @@ func execPlanBuild(currentOrgId string, activePlan *types.ActivePlan, activeBuil
}
}
if nextBuild != nil {
- go execPlanBuild(currentOrgId, activePlan, nextBuild)
+ go execPlanBuild(currentOrgId, currentUserId, branch, activePlan, nextBuild)
}
return
}
diff --git a/app/server/model/plan/state.go b/app/server/model/plan/state.go
index edb1c571..9f08a2ef 100644
--- a/app/server/model/plan/state.go
+++ b/app/server/model/plan/state.go
@@ -40,7 +40,6 @@ func CreateActivePlan(planId, prompt string) *types.ActivePlan {
}
activePlan.CancelFn()
-
Active.Delete(planId)
return
}
diff --git a/app/server/model/plan/stop.go b/app/server/model/plan/stop.go
index 80fffd6e..6dcffcd7 100644
--- a/app/server/model/plan/stop.go
+++ b/app/server/model/plan/stop.go
@@ -7,8 +7,7 @@ import (
"github.com/sashabaranov/go-openai"
)
-func Stop(planId, currentUserId, currentOrgId string) error {
-
+func Stop(planId, branch, currentUserId, currentOrgId string) error {
active := Active.Get(planId)
if active == nil {
@@ -30,7 +29,7 @@ func Stop(planId, currentUserId, currentOrgId string) error {
Message: content,
}
- _, err := db.StoreConvoMessage(&userMsg, true)
+ _, err := db.StoreConvoMessage(&userMsg, currentUserId, branch, true)
if err != nil {
return fmt.Errorf("error storing convo message: %v", err)
diff --git a/app/server/model/plan/tell.go b/app/server/model/plan/tell.go
index 3eeae0f5..8a2536b3 100644
--- a/app/server/model/plan/tell.go
+++ b/app/server/model/plan/tell.go
@@ -10,6 +10,7 @@ import (
"time"
"plandex-server/db"
+ "plandex-server/host"
"plandex-server/model"
"plandex-server/model/lib"
"plandex-server/model/prompts"
@@ -21,7 +22,7 @@ import (
)
// Proposal function to create a new proposal
-func Tell(plan *db.Plan, auth *types.ServerAuth, req *shared.TellPlanRequest) error {
+func Tell(plan *db.Plan, branch string, auth *types.ServerAuth, req *shared.TellPlanRequest) error {
// goEnv := os.Getenv("GOENV") // Fetch the GOENV environment variable
// log.Println("GOENV: " + goEnv)
@@ -39,24 +40,24 @@ func Tell(plan *db.Plan, auth *types.ServerAuth, req *shared.TellPlanRequest) er
active = CreateActivePlan(planId, req.Prompt)
- go execTellPlan(plan, auth, req, active, 0)
+ go execTellPlan(plan, branch, auth, req, active, 0)
return nil
}
-func execTellPlan(plan *db.Plan, auth *types.ServerAuth, req *shared.TellPlanRequest, active *types.ActivePlan, iteration int) {
+func execTellPlan(plan *db.Plan, branch string, auth *types.ServerAuth, req *shared.TellPlanRequest, active *types.ActivePlan, iteration int) {
currentUserId := auth.User.Id
currentOrgId := auth.OrgId
if os.Getenv("IS_CLOUD") != "" {
if auth.User.IsTrial {
- if plan.TotalMessages >= types.TrialMaxMessages {
+ if plan.TotalReplies >= types.TrialMaxReplies {
active.StreamDoneCh <- &shared.ApiError{
Type: shared.ApiErrorTypeTrialMessagesExceeded,
Status: http.StatusForbidden,
Msg: "Free trial message limit exceeded",
TrialMessagesExceededError: &shared.TrialMessagesExceededError{
- MaxMessages: types.TrialMaxMessages,
+ MaxReplies: types.TrialMaxReplies,
},
}
return
@@ -77,6 +78,22 @@ func execTellPlan(plan *db.Plan, auth *types.ServerAuth, req *shared.TellPlanReq
return
}
+ lockScope := db.LockScopeWrite
+ if iteration > 0 {
+ lockScope = db.LockScopeRead
+ }
+ repoLockId, err := db.LockRepo(auth.OrgId, auth.User.Id, planId, branch, lockScope)
+
+ if err != nil {
+ log.Printf("Error locking repo: %v\n", err)
+ active.StreamDoneCh <- &shared.ApiError{
+ Type: shared.ApiErrorTypeOther,
+ Status: http.StatusInternalServerError,
+ Msg: "Error locking repo",
+ }
+ return
+ }
+
errCh := make(chan error)
var modelContext []*db.Context
var convo []*db.ConvoMessage
@@ -151,7 +168,7 @@ func execTellPlan(plan *db.Plan, auth *types.ServerAuth, req *shared.TellPlanReq
Message: req.Prompt,
}
- _, err = db.StoreConvoMessage(&userMsg, true)
+ _, err = db.StoreConvoMessage(&userMsg, auth.User.Id, branch, true)
if err != nil {
log.Printf("Error storing user message: %v\n", err)
@@ -175,16 +192,37 @@ func execTellPlan(plan *db.Plan, auth *types.ServerAuth, req *shared.TellPlanReq
errCh <- nil
}()
- for i := 0; i < 4; i++ {
- err := <-errCh
- if err != nil {
- active.StreamDoneCh <- &shared.ApiError{
- Type: shared.ApiErrorTypeOther,
- Status: http.StatusInternalServerError,
- Msg: "Error getting plan, context, convo, or summaries",
+ err = func() error {
+ defer func() {
+ err = db.UnlockRepo(repoLockId)
+ if err != nil {
+ log.Printf("Error unlocking repo: %v\n", err)
+ active.StreamDoneCh <- &shared.ApiError{
+ Type: shared.ApiErrorTypeOther,
+ Status: http.StatusInternalServerError,
+ Msg: "Error unlocking repo",
+ }
+ return
+ }
+ }()
+
+ for i := 0; i < 4; i++ {
+ err := <-errCh
+ if err != nil {
+ active.StreamDoneCh <- &shared.ApiError{
+ Type: shared.ApiErrorTypeOther,
+ Status: http.StatusInternalServerError,
+ Msg: "Error getting plan, context, convo, or summaries",
+ }
+ return err
}
- return
}
+
+ return nil
+ }()
+
+ if err != nil {
+ return
}
if iteration == 0 {
@@ -420,6 +458,22 @@ func execTellPlan(plan *db.Plan, auth *types.ServerAuth, req *shared.TellPlanReq
return
}
+ err = db.StoreModelStream(&db.ModelStream{
+ OrgId: currentOrgId,
+ PlanId: planId,
+ InternalIp: host.Ip,
+ })
+
+ if err != nil {
+ log.Printf("Error storing model stream: %v\n", err)
+ active.StreamDoneCh <- &shared.ApiError{
+ Type: shared.ApiErrorTypeOther,
+ Status: http.StatusInternalServerError,
+ Msg: "Error storing model stream",
+ }
+ return
+ }
+
storeAssistantReply := func() (*db.ConvoMessage, []string, string, error) {
num := len(convo) + 1
if iteration == 0 {
@@ -437,7 +491,7 @@ func execTellPlan(plan *db.Plan, auth *types.ServerAuth, req *shared.TellPlanReq
Message: Active.Get(planId).CurrentReplyContent,
}
- commitMsg, err := db.StoreConvoMessage(&assistantMsg, false)
+ commitMsg, err := db.StoreConvoMessage(&assistantMsg, auth.User.Id, branch, false)
if err != nil {
log.Printf("Error storing assistant message: %v\n", err)
@@ -486,7 +540,7 @@ func execTellPlan(plan *db.Plan, auth *types.ServerAuth, req *shared.TellPlanReq
}
if storedMessage || storedDesc {
- err = db.GitAddAndCommit(currentOrgId, planId, commitMsg)
+ err = db.GitAddAndCommit(currentOrgId, planId, branch, commitMsg)
if err != nil {
log.Printf("Error committing after stream error: %v\n", err)
}
@@ -563,74 +617,96 @@ func execTellPlan(plan *db.Plan, auth *types.ServerAuth, req *shared.TellPlanReq
})
}
- assistantMsg, files, convoCommitMsg, err := storeAssistantReply()
+ repoLockId, err := db.LockRepo(auth.OrgId, auth.User.Id, planId, branch, db.LockScopeWrite)
- if err != nil {
- onError(fmt.Errorf("failed to store assistant message: %v", err), true, "", "")
- return
- }
-
- var description *db.ConvoMessageDescription
var execStatus *types.PlanExecStatus
+ err = func() error {
+ defer func() {
+ err = db.UnlockRepo(repoLockId)
+ if err != nil {
+ log.Printf("Error unlocking repo: %v\n", err)
+ active.StreamDoneCh <- &shared.ApiError{
+ Type: shared.ApiErrorTypeOther,
+ Status: http.StatusInternalServerError,
+ Msg: "Error unlocking repo",
+ }
+ }
+ }()
+
+ assistantMsg, files, convoCommitMsg, err := storeAssistantReply()
- errCh := make(chan error, 2)
+ if err != nil {
+ onError(fmt.Errorf("failed to store assistant message: %v", err), true, "", "")
+ return err
+ }
- go func() {
- if len(files) == 0 {
- description = &db.ConvoMessageDescription{
- OrgId: currentOrgId,
- PlanId: planId,
- ConvoMessageId: assistantMsg.Id,
- SummarizedToMessageId: summarizedToMessageId,
- MadePlan: false,
+ var description *db.ConvoMessageDescription
+
+ errCh := make(chan error, 2)
+
+ go func() {
+ if len(files) == 0 {
+ description = &db.ConvoMessageDescription{
+ OrgId: currentOrgId,
+ PlanId: planId,
+ ConvoMessageId: assistantMsg.Id,
+ SummarizedToMessageId: summarizedToMessageId,
+ MadePlan: false,
+ }
+ } else {
+ description, err = genPlanDescription(planId, active.Ctx)
+ if err != nil {
+ onError(fmt.Errorf("failed to generate plan description: %v", err), true, assistantMsg.Id, convoCommitMsg)
+ return
+ }
+
+ description.OrgId = currentOrgId
+ description.ConvoMessageId = assistantMsg.Id
+ description.SummarizedToMessageId = summarizedToMessageId
+ description.MadePlan = true
+ description.Files = files
}
- } else {
- description, err = genPlanDescription(planId, active.Ctx)
+
+ err = db.StoreDescription(description)
+
if err != nil {
- onError(fmt.Errorf("failed to generate plan description: %v", err), true, assistantMsg.Id, convoCommitMsg)
+ onError(fmt.Errorf("failed to store description: %v", err), false, assistantMsg.Id, convoCommitMsg)
+ errCh <- err
return
}
- description.OrgId = currentOrgId
- description.ConvoMessageId = assistantMsg.Id
- description.SummarizedToMessageId = summarizedToMessageId
- description.MadePlan = true
- description.Files = files
- }
+ errCh <- nil
+ }()
- err = db.StoreDescription(description)
+ go func() {
- if err != nil {
- onError(fmt.Errorf("failed to store description: %v", err), false, assistantMsg.Id, convoCommitMsg)
- errCh <- err
- return
- }
+ execStatus, err = ExecStatus(assistantMsg.Message, active.Ctx)
+ if err != nil {
+ onError(fmt.Errorf("failed to get exec status: %v", err), false, assistantMsg.Id, convoCommitMsg)
+ errCh <- err
+ return
+ }
- errCh <- nil
- }()
+ errCh <- nil
+ }()
- go func() {
+ for i := 0; i < 2; i++ {
+ err := <-errCh
+ if err != nil {
+ return err
+ }
+ }
- execStatus, err = ExecStatus(assistantMsg.Message, active.Ctx)
+ err = db.GitAddAndCommit(currentOrgId, planId, branch, convoCommitMsg)
if err != nil {
- onError(fmt.Errorf("failed to get exec status: %v", err), false, assistantMsg.Id, convoCommitMsg)
- errCh <- err
- return
+ onError(fmt.Errorf("failed to commit: %v", err), false, assistantMsg.Id, convoCommitMsg)
+ return err
}
- errCh <- nil
+ return nil
}()
- for i := 0; i < 2; i++ {
- err := <-errCh
- if err != nil {
- return
- }
- }
-
- err = db.GitAddAndCommit(currentOrgId, planId, convoCommitMsg)
if err != nil {
- onError(fmt.Errorf("failed to commit: %v", err), false, assistantMsg.Id, convoCommitMsg)
return
}
@@ -647,7 +723,7 @@ func execTellPlan(plan *db.Plan, auth *types.ServerAuth, req *shared.TellPlanReq
} else {
// continue plan
- execTellPlan(plan, auth, req, active, iteration+1)
+ execTellPlan(plan, branch, auth, req, active, iteration+1)
}
return
@@ -680,7 +756,7 @@ func execTellPlan(plan *db.Plan, auth *types.ServerAuth, req *shared.TellPlanReq
})
log.Printf("Queuing build for %s\n", latestFile)
- QueueBuild(currentOrgId, planId, &types.ActiveBuild{
+ QueueBuild(currentOrgId, currentUserId, branch, planId, &types.ActiveBuild{
AssistantMessageId: replyId,
ReplyContent: content,
Path: latestFile,
diff --git a/app/server/routes.go b/app/server/routes.go
index ca553915..e961d63d 100644
--- a/app/server/routes.go
+++ b/app/server/routes.go
@@ -8,7 +8,7 @@ import (
"github.com/gorilla/mux"
)
-func InitRoutes() *mux.Router {
+func routes() *mux.Router {
r := mux.NewRouter()
r.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
@@ -39,35 +39,45 @@ func InitRoutes() *mux.Router {
r.HandleFunc("/projects", handlers.ListProjectsHandler).Methods("GET")
r.HandleFunc("/projects/{projectId}/set_plan", handlers.ProjectSetPlanHandler).Methods("PUT")
r.HandleFunc("/projects/{projectId}/rename", handlers.RenameProjectHandler).Methods("PUT")
+
r.HandleFunc("/projects/{projectId}/plans", handlers.ListPlansHandler).Methods("GET")
+
+ r.HandleFunc("/projects/{projectId}/plans/current_branches", handlers.GetCurrentBranchByPlanIdHandler).Methods("POST")
+
r.HandleFunc("/projects/{projectId}/plans/archive", handlers.ListArchivedPlansHandler).Methods("GET")
r.HandleFunc("/projects/{projectId}/plans/ps", handlers.ListPlansRunningHandler).Methods("GET")
r.HandleFunc("/projects/{projectId}/plans", handlers.CreatePlanHandler).Methods("POST")
+
r.HandleFunc("/projects/{projectId}/plans", handlers.CreatePlanHandler).Methods("DELETE")
+
r.HandleFunc("/plans/{planId}", handlers.GetPlanHandler).Methods("GET")
r.HandleFunc("/plans/{planId}", handlers.DeletePlanHandler).Methods("DELETE")
- r.HandleFunc("/plans/{planId}/tell", handlers.TellPlanHandler).Methods("POST")
- r.HandleFunc("/plans/{planId}/build", handlers.BuildPlanHandler).Methods("PATCH")
- r.HandleFunc("/plans/{planId}/connect", handlers.ConnectPlanHandler).Methods("PATCH")
- r.HandleFunc("/plans/{planId}/stop", handlers.StopPlanHandler).Methods("DELETE")
-
- r.HandleFunc("/plans/{planId}/current_plan", handlers.CurrentPlanHandler).Methods("GET")
- r.HandleFunc("/plans/{planId}/apply", handlers.ApplyPlanHandler).Methods("PATCH")
- r.HandleFunc("/plans/{planId}/archive", handlers.ArchivePlanHandler).Methods("PATCH")
- r.HandleFunc("/plans/{planId}/reject_all", handlers.RejectAllChangesHandler).Methods("PATCH")
- r.HandleFunc("/plans/{planId}/results/{resultId}/reject", handlers.RejectResultHandler).Methods("PATCH")
- r.HandleFunc("/plans/{planId}/results/{resultId}/replacements/{replacementId}/reject", handlers.RejectReplacementHandler).Methods("PATCH")
-
- r.HandleFunc("/plans/{planId}/context", handlers.ListContextHandler).Methods("GET")
- r.HandleFunc("/plans/{planId}/context", handlers.LoadContextHandler).Methods("POST")
- r.HandleFunc("/plans/{planId}/context", handlers.UpdateContextHandler).Methods("PUT")
- r.HandleFunc("/plans/{planId}/context", handlers.DeleteContextHandler).Methods("DELETE")
-
- r.HandleFunc("/plans/{planId}/convo", handlers.ListConvoHandler).Methods("GET")
- r.HandleFunc("/plans/{planId}/rewind", handlers.RewindPlanHandler).Methods("PATCH")
- r.HandleFunc("/plans/{planId}/logs", handlers.ListLogsHandler).Methods("GET")
+ r.HandleFunc("/plans/{planId}/{branch}/tell", handlers.TellPlanHandler).Methods("POST")
+ r.HandleFunc("/plans/{planId}/{branch}/build", handlers.BuildPlanHandler).Methods("PATCH")
+ r.HandleFunc("/plans/{planId}/{branch}/connect", handlers.ConnectPlanHandler).Methods("PATCH")
+ r.HandleFunc("/plans/{planId}/{branch}/stop", handlers.StopPlanHandler).Methods("DELETE")
+
+ r.HandleFunc("/plans/{planId}/{branch}/current_plan", handlers.CurrentPlanHandler).Methods("GET")
+ r.HandleFunc("/plans/{planId}/{branch}/apply", handlers.ApplyPlanHandler).Methods("PATCH")
+ r.HandleFunc("/plans/{planId}/{branch}/archive", handlers.ArchivePlanHandler).Methods("PATCH")
+ r.HandleFunc("/plans/{planId}/{branch}/reject_all", handlers.RejectAllChangesHandler).Methods("PATCH")
+ r.HandleFunc("/plans/{planId}/{branch}/results/{resultId}/reject", handlers.RejectResultHandler).Methods("PATCH")
+ r.HandleFunc("/plans/{planId}/{branch}/results/{resultId}/replacements/{replacementId}/reject", handlers.RejectReplacementHandler).Methods("PATCH")
+
+ r.HandleFunc("/plans/{planId}/{branch}/context", handlers.ListContextHandler).Methods("GET")
+ r.HandleFunc("/plans/{planId}/{branch}/context", handlers.LoadContextHandler).Methods("POST")
+ r.HandleFunc("/plans/{planId}/{branch}/context", handlers.UpdateContextHandler).Methods("PUT")
+ r.HandleFunc("/plans/{planId}/{branch}/context", handlers.DeleteContextHandler).Methods("DELETE")
+
+ r.HandleFunc("/plans/{planId}/{branch}/convo", handlers.ListConvoHandler).Methods("GET")
+ r.HandleFunc("/plans/{planId}/{branch}/rewind", handlers.RewindPlanHandler).Methods("PATCH")
+ r.HandleFunc("/plans/{planId}/{branch}/logs", handlers.ListLogsHandler).Methods("GET")
+
+ r.HandleFunc("/plans/{planId}/branches", handlers.ListBranchesHandler).Methods("GET")
+ r.HandleFunc("/plans/{planId}/branches/{branch}", handlers.DeleteBranchHandler).Methods("DELETE")
+ r.HandleFunc("/plans/{planId}/{branch}/branches", handlers.CreateBranchHandler).Methods("POST")
return r
}
diff --git a/app/server/types/safe_map.go b/app/server/types/safe_map.go
index eda9cf71..cdc7dad7 100644
--- a/app/server/types/safe_map.go
+++ b/app/server/types/safe_map.go
@@ -54,3 +54,9 @@ func (sm *SafeMap[V]) Keys() []string {
}
return keys
}
+
+func (sm *SafeMap[V]) Len() int {
+ sm.mu.Lock()
+ defer sm.mu.Unlock()
+ return len(sm.items)
+}
diff --git a/app/server/types/trial.go b/app/server/types/trial.go
index 86604657..ae8dd059 100644
--- a/app/server/types/trial.go
+++ b/app/server/types/trial.go
@@ -1,4 +1,4 @@
package types
-const TrialMaxMessages = 15
+const TrialMaxReplies = 10
const TrialMaxPlans = 10
diff --git a/app/shared/auth.go b/app/shared/auth.go
index 8d7bf1d8..7634b67d 100644
--- a/app/shared/auth.go
+++ b/app/shared/auth.go
@@ -21,7 +21,7 @@ type TrialPlansExceededError struct {
}
type TrialMessagesExceededError struct {
- MaxMessages int `json:"maxMessages"`
+ MaxReplies int `json:"maxMessages"`
}
type ApiError struct {
diff --git a/app/shared/models.go b/app/shared/models.go
index bc1a911b..a89c3dfd 100644
--- a/app/shared/models.go
+++ b/app/shared/models.go
@@ -51,11 +51,23 @@ type Plan struct {
Id string `json:"id"`
OwnerId string `json:"ownerId"`
Name string `json:"name"`
+ SharedWithOrgAt *time.Time `json:"sharedWithOrgAt,omitempty"`
+ TotalReplies int `json:"totalReplies"`
+ ActiveBranches int `json:"activeBranches"`
+ ArchivedAt *time.Time `json:"archivedAt,omitempty"`
+ CreatedAt time.Time `json:"createdAt"`
+ UpdatedAt time.Time `json:"updatedAt"`
+}
+
+type Branch struct {
+ Id string `json:"id"`
+ OwnerId string `json:"ownerId"`
+ ParentBranchId *string `json:"parentBranchId"`
+ Name string `json:"name"`
Status PlanStatus `json:"status"`
ContextTokens int `json:"contextTokens"`
ConvoTokens int `json:"convoTokens"`
SharedWithOrgAt *time.Time `json:"sharedWithOrgAt,omitempty"`
- TotalMessages int `json:"totalMessages"`
ArchivedAt *time.Time `json:"archivedAt,omitempty"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
diff --git a/app/shared/req_res.go b/app/shared/req_res.go
index c454e240..1dcf16cc 100644
--- a/app/shared/req_res.go
+++ b/app/shared/req_res.go
@@ -85,6 +85,10 @@ type CreatePlanResponse struct {
Name string `json:"name"`
}
+type GetCurrentBranchByPlanIdRequest struct {
+ CurrentBranchByPlanId map[string]string `json:"currentBranchByPlanId"`
+}
+
type TellPlanRequest struct {
Prompt string `json:"prompt"`
ConnectStream bool `json:"connectStream"`
@@ -139,3 +143,7 @@ type LogResponse struct {
Shas []string `json:"shas"`
Body string `json:"body"`
}
+
+type CreateBranchRequest struct {
+ Name string `json:"name"`
+}
diff --git a/infra/src/main.ts b/infra/src/main.ts
index f83e3831..2d87525c 100644
--- a/infra/src/main.ts
+++ b/infra/src/main.ts
@@ -46,23 +46,30 @@ export class MyStack extends cdk.Stack {
);
// Create an RDS Aurora PostgreSQL database
- const dbInstance = new rds.DatabaseInstance(this, `plandex-rds-instance-${tag}`, {
- engine: rds.DatabaseInstanceEngine.postgres({
- version: rds.PostgresEngineVersion.VER_14_2,
- }),
- instanceType: ec2.InstanceType.of(
- ec2.InstanceClass.BURSTABLE2,
- ec2.InstanceSize.MICRO
- ),
- vpc,
- vpcSubnets: {
- subnetType: ec2.SubnetType.PRIVATE_ISOLATED,
- },
- credentials: rds.Credentials.fromSecret(dbCredentialsSecret), // Use credentials from Secrets Manager
- });
+ const dbInstance = new rds.DatabaseInstance(
+ this,
+ `plandex-rds-instance-${tag}`,
+ {
+ engine: rds.DatabaseInstanceEngine.postgres({
+ version: rds.PostgresEngineVersion.VER_14_2,
+ }),
+ instanceType: ec2.InstanceType.of(
+ ec2.InstanceClass.BURSTABLE2,
+ ec2.InstanceSize.MICRO
+ ),
+ vpc,
+ vpcSubnets: {
+ subnetType: ec2.SubnetType.PRIVATE_ISOLATED,
+ },
+ credentials: rds.Credentials.fromSecret(dbCredentialsSecret), // Use credentials from Secrets Manager
+ }
+ );
// Create an ECR repository
- const ecrRepository = new ecr.Repository(this, `plandex-ecr-repository-${tag}`);
+ const ecrRepository = new ecr.Repository(
+ this,
+ `plandex-ecr-repository-${tag}`
+ );
// Create an ECS cluster
const ecsCluster = new ecs.Cluster(this, `plandex-ecs-cluster-${tag}`, {
@@ -70,9 +77,13 @@ export class MyStack extends cdk.Stack {
});
// Create an EFS file system
- const fileSystem = new efs.FileSystem(this, `plandex-efs-file-system-${tag}`, {
- vpc,
- });
+ const fileSystem = new efs.FileSystem(
+ this,
+ `plandex-efs-file-system-${tag}`,
+ {
+ vpc,
+ }
+ );
// Create an IAM role for the Fargate task to interact with SES
const taskRole = new iam.Role(this, `plandex-task-role-${tag}`, {
@@ -97,6 +108,9 @@ export class MyStack extends cdk.Stack {
const container = taskDefinition.addContainer("MyContainer", {
image: ecs.ContainerImage.fromEcrRepository(ecrRepository),
logging: new ecs.AwsLogDriver({ streamPrefix: "MyContainer" }),
+ environment: {
+ ECS_CONTAINER_STOP_TIMEOUT: "10m", // gives time for streams to finish before container is stopped
+ },
});
// Mount the EFS file system to the container
@@ -130,12 +144,16 @@ export class MyStack extends cdk.Stack {
"Allow Fargate service to access RDS instance"
);
- const fargateService = new ecs.FargateService(this, `plandex-fargate-service-${tag}`, {
- cluster: ecsCluster,
- taskDefinition,
- desiredCount: 1,
- securityGroups: [fargateServiceSecurityGroup],
- });
+ const fargateService = new ecs.FargateService(
+ this,
+ `plandex-fargate-service-${tag}`,
+ {
+ cluster: ecsCluster,
+ taskDefinition,
+ desiredCount: 1,
+ securityGroups: [fargateServiceSecurityGroup],
+ }
+ );
// Create an SES email sending resource
// Note: SES setup can vary based on the region and verification status. Here, we're creating a simple rule set.