Open source AI coding agent. Designed for large projects and real world tasks.
Go aiai-agentsai-developer-toolsai-toolsclicommand-linedeveloper-toolsgitgolanggpt-4llmopenaipolyglot-programmingterminalterminal-basedterminal-ui
lots of fixes, AI-driven infra work
Dane Schneider982408814571
diff --git a/app/cli/changes_tui/actions.go b/app/cli/changes_tui/actions.goindex 5dab3849..a98da4ec 100644--- a/app/cli/changes_tui/actions.go+++ b/app/cli/changes_tui/actions.go@@ -161,11 +161,7 @@ func (m *changesUIModel) updateMainView(scrollReplacement bool) {// var updateMsg types.ChangesUIViewportsUpdateif m.selectedNewFile() || m.selectedFullFile() {- context := m.currentPlan.ContextsByPath[m.selectionInfo.currentPath]- var originalFile string- if context != nil {- originalFile = context.Body- }+ originalFile := m.currentPlan.PlanResult.FileResultsByPath.OriginalContextForPath(m.selectionInfo.currentPath)var updatedFile string@@ -179,7 +175,7 @@ func (m *changesUIModel) updateMainView(scrollReplacement bool) {fileSegments := []string{}replacementSegments := map[int]bool{}- if context == nil {+ if originalFile == "" {// the file is new, so all lines are new and should be highlightedfileSegments = append(fileSegments, updatedFile)replacementSegments[0] = truediff --git a/app/cli/changes_tui/main_viewport.go b/app/cli/changes_tui/main_viewport.goindex 4b47ae3b..58e11a1e 100644--- a/app/cli/changes_tui/main_viewport.go+++ b/app/cli/changes_tui/main_viewport.go@@ -132,7 +132,7 @@ func (m changesUIModel) renderScrollFooter() string {var footer stringif m.selectedNewFile() || m.selectedFullFile() {- footer = `(j/k) scroll down/up • (J/K) page down/up`+ footer = `(j/k) scroll down/up • (d/u) page down/up`} else {footer = ` (j/k) scroll`if m.oldScrollable() && m.newScrollable() {diff --git a/app/cli/changes_tui/model.go b/app/cli/changes_tui/model.goindex 706c8a4a..254e5952 100644--- a/app/cli/changes_tui/model.go+++ b/app/cli/changes_tui/model.go@@ -94,13 +94,13 @@ func initialModel() *changesUIModel {),pageDown: bubbleKey.NewBinding(- bubbleKey.WithKeys("J", "pageDown"),- bubbleKey.WithHelp("J", "page down"),+ bubbleKey.WithKeys("d", "pageDown"),+ bubbleKey.WithHelp("d", "page down"),),pageUp: bubbleKey.NewBinding(- bubbleKey.WithKeys("K", "pageUp"),- bubbleKey.WithHelp("K", "page up"),+ bubbleKey.WithKeys("u", "pageUp"),+ bubbleKey.WithHelp("u", "page up"),),switchView: bubbleKey.NewBinding(diff --git a/app/cli/cmd/cd.go b/app/cli/cmd/cd.goindex ed768296..235894b1 100644--- a/app/cli/cmd/cd.go+++ b/app/cli/cmd/cd.go@@ -6,6 +6,7 @@ import ("plandex/api""plandex/auth""plandex/lib"+ "plandex/term""strconv""time"@@ -81,4 +82,7 @@ func cd(cmd *cobra.Command, args []string) {time.Sleep(50 * time.Millisecond)fmt.Fprintln(os.Stderr, "✅ Changed current plan to "+color.New(color.FgGreen, color.Bold).Sprint(plan.Name))++ fmt.Println()+ term.PrintCmds("", "current")}diff --git a/app/cli/cmd/continue.go b/app/cli/cmd/continue.goindex 4739d980..327296c5 100644--- a/app/cli/cmd/continue.go+++ b/app/cli/cmd/continue.go@@ -38,6 +38,7 @@ func next(cmd *cobra.Command, args []string) {lib.MustResolveProject()lib.MustCheckOutdatedContextWithOutput()+ promptingTrialExceeded := falseif !continueBg {go func() {err := streamtui.StartStreamUI()@@ -46,6 +47,10 @@ func next(cmd *cobra.Command, args []string) {fmt.Fprintln(os.Stderr, "Error starting stream UI:", err)os.Exit(1)}++ if !promptingTrialExceeded {+ os.Exit(0)+ }}()}@@ -58,7 +63,9 @@ func next(cmd *cobra.Command, args []string) {if apiErr != nil {log.Println("Error telling plan:", apiErr)if apiErr.Type == shared.ApiErrorTypeTrialMessagesExceeded {+ promptingTrialExceeded = truestreamtui.Quit()+ promptingTrialExceeded = falsefmt.Fprintf(os.Stderr, "🚨 You've reached the free trial limit of %d messages per plan\n", apiErr.TrialMessagesExceededError.MaxReplies)diff --git a/app/cli/cmd/current.go b/app/cli/cmd/current.goindex 549900db..a15c7ac5 100644--- a/app/cli/cmd/current.go+++ b/app/cli/cmd/current.go@@ -55,7 +55,7 @@ func current(cmd *cobra.Command, args []string) {table := tablewriter.NewWriter(os.Stdout)table.SetAutoWrapText(false)- table.SetHeader([]string{"Current Plan", "Updated", "Created", "Branches", "Branch", "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]@@ -64,7 +64,7 @@ func current(cmd *cobra.Command, args []string) {name,format.Time(plan.UpdatedAt),format.Time(plan.CreatedAt),- strconv.Itoa(plan.ActiveBranches),+ // strconv.Itoa(plan.ActiveBranches),lib.CurrentBranch,strconv.Itoa(branch.ContextTokens) + " 🪙",strconv.Itoa(branch.ConvoTokens) + " 🪙",diff --git a/app/cli/cmd/new.go b/app/cli/cmd/new.goindex 41df3447..50b6f0f6 100644--- a/app/cli/cmd/new.go+++ b/app/cli/cmd/new.go@@ -77,6 +77,6 @@ func new(cmd *cobra.Command, args []string) {}fmt.Println()- term.PrintCmds("", "load", "tell", "plans")+ term.PrintCmds("", "load", "tell", "plans", "current")}diff --git a/app/cli/cmd/plans.go b/app/cli/cmd/plans.goindex 4d98fc3b..e7cce40a 100644--- a/app/cli/cmd/plans.go+++ b/app/cli/cmd/plans.go@@ -70,7 +70,7 @@ func plans(cmd *cobra.Command, args []string) {table := tablewriter.NewWriter(os.Stdout)table.SetAutoWrapText(false)- table.SetHeader([]string{"#", "Name", "Updated", "Created", "Branches", "Branch", "Context", "Convo"})+ table.SetHeader([]string{"#", "Name", "Updated", "Created" /*"Branches",*/, "Branch", "Context", "Convo"})for i, p := range plans {@@ -88,7 +88,7 @@ func plans(cmd *cobra.Command, args []string) {name,format.Time(p.UpdatedAt),format.Time(p.CreatedAt),- strconv.Itoa(p.ActiveBranches),+ // strconv.Itoa(p.ActiveBranches),currentBranch.Name,strconv.Itoa(currentBranch.ContextTokens) + " 🪙",strconv.Itoa(currentBranch.ConvoTokens) + " 🪙",diff --git a/app/cli/cmd/rewind.go b/app/cli/cmd/rewind.goindex 7e7e54cb..97c63b0b 100644--- a/app/cli/cmd/rewind.go+++ b/app/cli/cmd/rewind.go@@ -7,6 +7,7 @@ import ("plandex/api""plandex/auth""plandex/lib"+ "plandex/term""strconv""github.com/plandex/plandex/shared"@@ -73,7 +74,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, lib.CurrentBranch, shared.RewindPlanRequest{Sha: targetSha})+ _, 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)@@ -84,5 +85,8 @@ func rewind(cmd *cobra.Command, args []string) {fmt.Println(msg)fmt.Println()- fmt.Println(rwRes.LatestCommit)++ term.PrintCmds("", "log")++ // fmt.Println(rwRes.LatestCommit)}diff --git a/app/cli/cmd/tell.go b/app/cli/cmd/tell.goindex dd299105..6e5a6de7 100644--- a/app/cli/cmd/tell.go+++ b/app/cli/cmd/tell.go@@ -123,6 +123,7 @@ func tell(cmd *cobra.Command, args []string) {lib.MustCheckOutdatedContextWithOutput()+ promptingTrialExceeded := falseif !tellBg {go func() {err := streamtui.StartStreamUI()@@ -131,6 +132,10 @@ func tell(cmd *cobra.Command, args []string) {fmt.Fprintln(os.Stderr, "Error starting stream UI:", err)os.Exit(1)}++ if !promptingTrialExceeded {+ os.Exit(0)+ }}()}@@ -143,7 +148,9 @@ func tell(cmd *cobra.Command, args []string) {}, lib.OnStreamPlan)if apiErr != nil {if apiErr.Type == shared.ApiErrorTypeTrialMessagesExceeded {+ promptingTrialExceeded = truestreamtui.Quit()+ promptingTrialExceeded = falsefmt.Fprintf(os.Stderr, "\n🚨 You've reached the free trial limit of %d messages per plan\n", apiErr.TrialMessagesExceededError.MaxReplies)diff --git a/app/cli/term/term.go b/app/cli/term/term.goindex 2ebd4fb1..b7dbc8a7 100644--- a/app/cli/term/term.go+++ b/app/cli/term/term.go@@ -15,11 +15,11 @@ import ()var CmdDesc = map[string][2]string{- "new": {"", "start a new plan"},- // "current": {"c", "show current plan"},- "cd": {"", "set current plan by name or index"},- "load": {"l", "load files, dirs, urls, notes or piped data into context"},- "tell": {"t", "describe a task, ask a question, or chat"},+ "new": {"", "start a new plan"},+ "current": {"cu", "show current plan"},+ "cd": {"", "set current plan by name or index"},+ "load": {"l", "load files, dirs, urls, notes or piped data into context"},+ "tell": {"t", "describe a task, ask a question, or chat"},// "diffs": {"d", "show diffs between plan and project files"},// "preview": {"pv", "preview the plan in a branch"},"apply": {"ap", "apply the plan to your project files"},@@ -32,6 +32,9 @@ var CmdDesc = map[string][2]string{"delete-plan": {"del", "delete plan by name or index"},"plans": {"pl", "list plans"},"update": {"u", "update outdated context"},+ "log": {"", "show log of plan updates"},+ "branches": {"br", "list plan branches"},+ // "checkout": {"co", "checkout or create a branch"}, need to implement non-contiguous aliases}func PrintCmds(prefix string, cmds ...string) {diff --git a/app/server/db/db.go b/app/server/db/db.goindex 8cb5621f..eef029b5 100644--- a/app/server/db/db.go+++ b/app/server/db/db.go@@ -78,6 +78,15 @@ func MigrationsUp() error {// log.Println("ran down migrations - database was reset")// }+ // go back one migration+ // if os.Getenv("GOENV") == "development" {+ // err = m.Steps(-1)+ // if err != nil {+ // return fmt.Errorf("error running down migrations: %v", err)+ // }+ // log.Println("went down 1 migration")+ // }+err = m.Up()if err != nil {diff --git a/app/server/db/git.go b/app/server/db/git.goindex 1bab6687..1e5f262c 100644--- a/app/server/db/git.go+++ b/app/server/db/git.go@@ -10,6 +10,7 @@ import ("time""github.com/fatih/color"+ "github.com/lib/pq")func init() {@@ -274,10 +275,14 @@ func gitCommit(repoDir, commitMsg string) error {const lockTimeout = 60 * time.Secondfunc LockRepo(orgId, userId, planId, branch string, scope LockScope) (string, error) {- return lockRepo(orgId, userId, planId, branch, scope, 0)+ return lockRepo(orgId, userId, planId, "", branch, scope, 0)}-func lockRepo(orgId, userId, planId, branch string, scope LockScope, numRetry int) (string, error) {+func LockRepoForBuild(orgId, userId, planId, planBuildId, branch string, scope LockScope) (string, error) {+ return lockRepo(orgId, userId, planId, planBuildId, branch, scope, 0)+}++func lockRepo(orgId, userId, planId, planBuildId, branch string, scope LockScope, numRetry int) (string, error) {tx, err := Conn.Begin()if err != nil {return "", fmt.Errorf("error starting transaction: %v", err)@@ -294,7 +299,7 @@ func lockRepo(orgId, userId, planId, branch string, scope LockScope, numRetry in}}()- query := "SELECT * FROM repo_locks WHERE plan_id = $1 FOR UPDATE"+ query := "SELECT id, org_id, user_id, plan_id, plan_build_id, scope, branch, created_at FROM repo_locks WHERE plan_id = $1 FOR UPDATE"queryArgs := []interface{}{planId}var locks []*repoLock@@ -307,19 +312,33 @@ func lockRepo(orgId, userId, planId, branch string, scope LockScope, numRetry indefer rows.Close()+ var expiredLockIds []string+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 {+ if err := rows.Scan(&lock.Id, &lock.OrgId, &lock.UserId, &lock.PlanId, &lock.PlanBuildId, &lock.Scope, &lock.Branch, &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)- }+ expiredLockIds = append(expiredLockIds, lock.Id)+ }+ }++ if len(expiredLockIds) > 0 {+ query := "DELETE FROM repo_locks WHERE id = ANY($1)"++ args := make([]interface{}, len(expiredLockIds))+ for i, id := range expiredLockIds {+ args[i] = id+ }++ // Execute the query with the slice as a parameter+ _, err := tx.Exec(query, pq.Array(expiredLockIds))+ if err != nil {+ return fmt.Errorf("error removing expired locks: %v", err)}}@@ -332,6 +351,9 @@ func lockRepo(orgId, userId, planId, branch string, scope LockScope, numRetry incanAcquire := truecanRetry := true+ // log.Println("locks:")+ // spew.Dump(locks)+for _, lock := range locks {lockBranch := ""if lock.Branch != nil {@@ -340,12 +362,17 @@ func lockRepo(orgId, userId, planId, branch string, scope LockScope, numRetry inif scope == LockScopeRead {canAcquireThisLock := lock.Scope == LockScopeRead && lockBranch == branch-if !canAcquireThisLock {canAcquire = false}} else if scope == LockScopeWrite {canAcquire = false++ // if lock is for the same plan plan and branch, allow parallel writes+ if planId == lock.PlanId && branch == lockBranch {+ canAcquire = true+ }+if lock.Scope == LockScopeWrite && lockBranch == branch {canRetry = false}@@ -363,21 +390,44 @@ func lockRepo(orgId, userId, planId, branch string, scope LockScope, numRetry inreturn "", err}time.Sleep(500 * time.Millisecond)- return lockRepo(orgId, userId, planId, branch, scope, numRetry+1)+ return lockRepo(orgId, userId, planId, planBuildId, branch, scope, numRetry+1)}err = fmt.Errorf("plan is currently being updated by another user")return "", err}// Insert the new lock+ var lockPlanBuildId *string+ if planBuildId != "" {+ lockPlanBuildId = &planBuildId+ }++ var lockBranch *string+ if branch != "" {+ lockBranch = &branch+ }+newLock := &repoLock{- OrgId: orgId,- UserId: userId,- PlanId: planId,- Scope: scope,+ OrgId: orgId,+ UserId: userId,+ PlanId: planId,+ PlanBuildId: lockPlanBuildId,+ Scope: scope,+ Branch: lockBranch,}- 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)+ // log.Println("newLock:")+ // spew.Dump(newLock)++ insertQuery := "INSERT INTO repo_locks (org_id, user_id, plan_id, plan_build_id, scope, branch) VALUES ($1, $2, $3, $4, $5, $6) RETURNING id"+ err = tx.QueryRow(+ insertQuery,+ newLock.OrgId,+ newLock.UserId,+ newLock.PlanId,+ newLock.PlanBuildId,+ newLock.Scope,+ newLock.Branch,+ ).Scan(&newLock.Id)if err != nil {return "", fmt.Errorf("error inserting new lock: %v", err)}diff --git a/app/server/db/models.go b/app/server/db/models.goindex 4b598017..2d5fa837 100644--- a/app/server/db/models.go+++ b/app/server/db/models.go@@ -279,13 +279,14 @@ const ()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"`+ 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"`+ PlanBuildId *string `db:"plan_build_id"`+ CreatedAt time.Time `db:"created_at"`}// Models below are stored in files, not in the database.diff --git a/app/server/db/result_helpers.go b/app/server/db/result_helpers.goindex 29164ef4..94c46025 100644--- a/app/server/db/result_helpers.go+++ b/app/server/db/result_helpers.go@@ -48,7 +48,6 @@ func StorePlanResult(result *PlanFileResult) error {type CurrentPlanStateParams struct {OrgId stringPlanId string- Contexts []*ContextPlanFileResults []*PlanFileResultPendingBuildDescriptions []*ConvoMessageDescription}@@ -59,7 +58,6 @@ func GetCurrentPlanState(params CurrentPlanStateParams) (*shared.CurrentPlanStatvar dbPlanFileResults []*PlanFileResultvar pendingBuildDescriptions []*shared.ConvoMessageDescription- var contexts []*ContexterrCh := make(chan error)@@ -99,22 +97,7 @@ func GetCurrentPlanState(params CurrentPlanStateParams) (*shared.CurrentPlanStaterrCh <- nil}()- go func() {- if params.Contexts == nil {- res, err := GetPlanContexts(orgId, planId, true)- if err != nil {- errCh <- fmt.Errorf("error getting plan contexts: %v", err)- return- }- contexts = res- } else {- contexts = params.Contexts- }-- errCh <- nil- }()-- for i := 0; i < 3; i++ {+ for i := 0; i < 2; i++ {err := <-errChif err != nil {return nil, err@@ -128,21 +111,8 @@ func GetCurrentPlanState(params CurrentPlanStateParams) (*shared.CurrentPlanStat}planResult := GetPlanResult(apiPlanFileResults)- var apiContexts []*shared.Context- apiContextsByPath := make(map[string]*shared.Context)-- for _, context := range contexts {- apiContexts = append(apiContexts, context.ToApi())-- if context.FilePath != "" {- apiContextsByPath[context.FilePath] = context.ToApi()- }- }-planState := &shared.CurrentPlanState{PlanResult: planResult,- Contexts: apiContexts,- ContextsByPath: apiContextsByPath,PendingBuildDescriptions: pendingBuildDescriptions,}@@ -308,7 +278,6 @@ func ApplyPlan(orgId, planId, branch string) error {var results []*PlanFileResultvar pendingBuildDescriptions []*ConvoMessageDescription- var contexts []*Contextgo func() {res, err := GetPlanFileResults(orgId, planId)@@ -330,17 +299,7 @@ func ApplyPlan(orgId, planId, branch string) error {errCh <- nil}()- go func() {- res, err := GetPlanContexts(orgId, planId, true)- if err != nil {- errCh <- fmt.Errorf("error getting plan contexts: %v", err)- return- }- contexts = res- errCh <- nil- }()-- for i := 0; i < 3; i++ {+ for i := 0; i < 2; i++ {err := <-errChif err != nil {return fmt.Errorf("error applying plan: %v", err)@@ -350,7 +309,6 @@ func ApplyPlan(orgId, planId, branch string) error {planState, err := GetCurrentPlanState(CurrentPlanStateParams{OrgId: orgId,PlanId: planId,- Contexts: contexts,PlanFileResults: results,PendingBuildDescriptions: pendingBuildDescriptions,})diff --git a/app/server/db/stream_helpers.go b/app/server/db/stream_helpers.goindex 7b76ac0a..47fb70e3 100644--- a/app/server/db/stream_helpers.go+++ b/app/server/db/stream_helpers.go@@ -3,6 +3,7 @@ package dbimport ("database/sql""fmt"+ "log""time")@@ -32,6 +33,8 @@ func StoreModelStream(stream *ModelStream) error {}func SetModelStreamFinished(id string) error {+ log.Println("Setting model stream finished")+_, err := Conn.Exec("UPDATE model_streams SET finished_at = NOW() WHERE id = $1", id)if err != nil {diff --git a/app/server/handlers/plans_changes.go b/app/server/handlers/plans_changes.goindex ac0f0639..a857e311 100644--- a/app/server/handlers/plans_changes.go+++ b/app/server/handlers/plans_changes.go@@ -34,18 +34,9 @@ func CurrentPlanHandler(w http.ResponseWriter, r *http.Request) {defer (*unlockFn)()}- contexts, err := db.GetPlanContexts(auth.OrgId, planId, true)-- if err != nil {- log.Printf("Error getting plan contexts: %v\n", err)- http.Error(w, "Error getting plan contexts: "+err.Error(), http.StatusInternalServerError)- return- }-planState, err := db.GetCurrentPlanState(db.CurrentPlanStateParams{- OrgId: auth.OrgId,- PlanId: planId,- Contexts: contexts,+ OrgId: auth.OrgId,+ PlanId: planId,})if err != nil {diff --git a/app/server/migrations/2024012500_locks.up.sql b/app/server/migrations/2024012500_locks.up.sqlindex 755301ba..2ba06e27 100644--- a/app/server/migrations/2024012500_locks.up.sql+++ b/app/server/migrations/2024012500_locks.up.sql@@ -1,13 +1,12 @@-CREATE UNLOGGED TABLE IF NOT EXISTS repo_locks (id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),org_id UUID NOT NULL REFERENCES orgs(id) ON DELETE CASCADE,user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,plan_id UUID NOT NULL REFERENCES plans(id) ON DELETE CASCADE,+ plan_build_id UUID REFERENCES plan_builds(id) ON DELETE CASCADE,scope VARCHAR(1) NOT NULL,branch VARCHAR(255),created_at TIMESTAMP NOT NULL DEFAULT NOW());CREATE INDEX repo_locks_plan_idx ON repo_locks(plan_id);-CREATE UNIQUE INDEX repo_locks_write_idx ON repo_locks(plan_id) WHERE scope = 'w';diff --git a/app/server/model/plan/build.go b/app/server/model/plan/build.goindex 6d187ae3..370f6be5 100644--- a/app/server/model/plan/build.go+++ b/app/server/model/plan/build.go@@ -32,6 +32,8 @@ func QueueBuild(currentOrgId, currentUserId, planId, branch string, activeBuildactive.BuildQueuesByPath[filePath] = append(active.BuildQueuesByPath[filePath], activeBuild)})log.Printf("Queued build for file %s\n", filePath)+ log.Printf("Queue:")+ spew.Dump(activePlan.BuildQueuesByPath[filePath])if activePlan.IsBuildingByPath[filePath] {log.Printf("Already building file %s\n", filePath)@@ -60,10 +62,6 @@ func execPlanBuild(currentOrgId, currentUserId, branch string, activePlan *typesBuildInfo: buildInfo,})- replyInfo := types.NewReplyParser()- replyInfo.AddChunk(activePlan.CurrentReplyContent, true)- _, fileContents, _, _ := replyInfo.Read()-errCh := make(chan error)var build *db.PlanBuild@@ -97,9 +95,8 @@ func execPlanBuild(currentOrgId, currentUserId, branch string, activePlan *typesgo func() {res, err := db.GetCurrentPlanState(db.CurrentPlanStateParams{- OrgId: currentOrgId,- PlanId: planId,- Contexts: activePlan.Contexts,+ OrgId: currentOrgId,+ PlanId: planId,})if err != nil {errCh <- fmt.Errorf("error getting current plan state: %v", err)@@ -137,17 +134,22 @@ func execPlanBuild(currentOrgId, currentUserId, branch string, activePlan *typesonFinishBuildFile := func(filePath string, planRes *db.PlanFileResult) {finished := false-- // log.Println("onFinishBuildFile: " + filePath)- // spew.Dump(planRes)-- repoLockId, err := db.LockRepo(currentOrgId, currentUserId, planId, branch, db.LockScopeWrite)+ log.Println("onFinishBuildFile: " + filePath)++ repoLockId, err := db.LockRepoForBuild(+ currentOrgId,+ currentUserId,+ planId,+ planRes.PlanBuildId,+ branch,+ db.LockScopeWrite,+ )if err != nil {- log.Printf("Error locking repo: %v\n", err)+ log.Printf("Error locking repo for build file: %v\n", err)activePlan.StreamDoneCh <- &shared.ApiError{Type: shared.ApiErrorTypeOther,Status: http.StatusInternalServerError,- Msg: "Error locking repo: " + err.Error(),+ Msg: "Error locking repo for build file: " + err.Error(),}return}@@ -188,25 +190,33 @@ func execPlanBuild(currentOrgId, currentUserId, branch string, activePlan *types}})- if !activePlan.PathFinished(filePath) {- log.Printf("Processing next build for file %s\n", filePath)- var nextBuild *types.ActiveBuild- for _, build := range activePlan.BuildQueuesByPath[filePath] {- if !build.BuildFinished() {- nextBuild = build- break- }- }- if nextBuild != nil {- go execPlanBuild(currentOrgId, currentUserId, branch, activePlan, nextBuild)- }- return- }-log.Printf("Finished building file %s\n", filePath)if finished {+ log.Println("Finished building plan, calling onFinishBuild")onFinishBuild()+ } else {+ if !activePlan.PathFinished(filePath) {+ log.Printf("Processing next build for file %s\n", filePath)+ var nextBuild *types.ActiveBuild+ for _, build := range activePlan.BuildQueuesByPath[filePath] {+ if !build.BuildFinished() {+ nextBuild = build+ break+ }+ }++ log.Println("Next build:")+ spew.Dump(nextBuild)++ if nextBuild != nil {+ log.Println("Calling execPlanBuild for next build in queue")+ go execPlanBuild(currentOrgId, currentUserId, branch, activePlan, nextBuild)+ }+ return+ } else {+ log.Printf("File %s finished, but not all builds finished\n", filePath)+ }}}@@ -251,8 +261,8 @@ func execPlanBuild(currentOrgId, currentUserId, branch string, activePlan *typescurrentState = currentPlanFilelog.Printf("File %s found in current plan. Using current state.\n", filePath)- log.Println("Current state:")- log.Println(currentState)+ // log.Println("Current state:")+ // log.Println(currentState)} else if contextPart != nil {currentState = contextPart.Body}@@ -278,7 +288,7 @@ func execPlanBuild(currentOrgId, currentUserId, branch string, activePlan *typesPlanBuildId: build.Id,ConvoMessageId: build.ConvoMessageId,Path: filePath,- Content: fileContents[filePath],+ Content: activeBuild.FileContent,}onFinishBuildFile(filePath, planRes)returndiff --git a/app/server/model/plan/state.go b/app/server/model/plan/state.goindex 0e66bcbd..ad773e8b 100644--- a/app/server/model/plan/state.go+++ b/app/server/model/plan/state.go@@ -27,8 +27,17 @@ func CreateActivePlan(planId, branch, prompt string) *types.ActivePlan {for {select {case <-activePlan.Ctx.Done():+ log.Printf("case <-activePlan.Ctx.Done(): %s\n", planId)++ err := db.SetModelStreamFinished(activePlan.ModelStreamId)+ if err != nil {+ log.Printf("Error setting model stream %s finished: %v\n", activePlan.ModelStreamId, err)+ }returncase apiErr := <-activePlan.StreamDoneCh:+ log.Printf("case apiErr := <-activePlan.StreamDoneCh: %s\n", planId)+ log.Printf("apiErr: %v\n", apiErr)+if apiErr == nil {log.Printf("Plan %s stream completed successfully", planId)@@ -70,6 +79,7 @@ func UpdateActivePlan(planId, branch string, fn func(*types.ActivePlan)) {}func SubscribePlan(planId, branch string) (string, chan string) {+ log.Printf("Subscribing to plan %s\n", planId)var id stringvar ch chan stringUpdateActivePlan(planId, branch, func(activePlan *types.ActivePlan) {@@ -79,6 +89,8 @@ func SubscribePlan(planId, branch string) (string, chan string) {}func UnsubscribePlan(planId, branch, subscriptionId string) {+ log.Printf("Unsubscribing from plan %s\n", planId)+active := GetActivePlan(planId, branch)if active == nil {diff --git a/app/server/model/plan/tell.go b/app/server/model/plan/tell.goindex 675c9e1e..1caa879f 100644--- a/app/server/model/plan/tell.go+++ b/app/server/model/plan/tell.go@@ -16,12 +16,12 @@ import ("plandex-server/model/prompts""plandex-server/types"+ "github.com/davecgh/go-spew/spew""github.com/google/uuid""github.com/plandex/plandex/shared""github.com/sashabaranov/go-openai")-// Proposal function to create a new proposalfunc Tell(plan *db.Plan, branch string, auth *types.ServerAuth, req *shared.TellPlanRequest) error {// goEnv := os.Getenv("GOENV") // Fetch the GOENV environment variable@@ -36,6 +36,16 @@ func Tell(plan *db.Plan, branch string, auth *types.ServerAuth, req *shared.Tellreturn fmt.Errorf("plan %s branch %s already has an active stream on this host", plan.Id, branch)}+ modelStream, err := db.GetActiveModelStream(plan.Id, branch)+ if err != nil {+ log.Printf("Error getting active model stream: %v\n", err)+ return fmt.Errorf("error getting active model stream: %v", err)+ }++ if modelStream != nil {+ return fmt.Errorf("plan %s branch %s already has an active stream on host %s", plan.Id, branch, modelStream.InternalIp)+ }+active = CreateActivePlan(plan.Id, branch, req.Prompt)go execTellPlan(plan, branch, auth, req, active, 0)@@ -338,6 +348,15 @@ func execTellPlan(plan *db.Plan, branch string, auth *types.ServerAuth, req *shaif !ok {err := fmt.Errorf("conversation summary timestamp not found in conversation")log.Printf("Error: %v\n", err)++ log.Println("timestamp:", timestamp)++ log.Println("Conversation summary:")+ spew.Dump(s)++ log.Println("tokensUpToTimestamp:")+ spew.Dump(tokensUpToTimestamp)+active.StreamDoneCh <- &shared.ApiError{Type: shared.ApiErrorTypeOther,Status: http.StatusInternalServerError,@@ -746,26 +765,30 @@ func execTellPlan(plan *db.Plan, branch string, auth *types.ServerAuth, req *sha})replyParser.AddChunk(content, true)- files, _, _, numTokens := replyParser.Read()+ files, fileContents, _, numTokens := replyParser.Read()replyNumTokens = numTokens// log.Printf("Reply num tokens: %d\n", replyNumTokens)// log.Printf("Reply files: %v\n", files)if len(files) > len(replyFiles) {- latestFile := files[len(files)-1]- UpdateActivePlan(planId, branch, func(active *types.ActivePlan) {- active.Files = files- })-- log.Printf("Queuing build for %s\n", latestFile)- QueueBuild(currentOrgId, currentUserId, planId, branch, &types.ActiveBuild{- AssistantMessageId: replyId,- ReplyContent: content,- Path: latestFile,- })-- replyFiles = files+ for i := len(files) - 1; i > 0; i-- {+ if i < len(replyFiles) {+ break+ }+ file := files[i]+ log.Printf("Queuing build for %s\n", file)+ QueueBuild(currentOrgId, currentUserId, planId, branch, &types.ActiveBuild{+ AssistantMessageId: replyId,+ ReplyContent: content,+ FileContent: fileContents[i],+ Path: file,+ })+ replyFiles = append(replyFiles, file)+ UpdateActivePlan(planId, branch, func(active *types.ActivePlan) {+ active.Files = append(active.Files, file)+ })+ }}}diff --git a/app/server/types/reply.go b/app/server/types/reply.goindex 2dbef629..9f29c7ff 100644--- a/app/server/types/reply.go+++ b/app/server/types/reply.go@@ -1,6 +1,7 @@package typesimport (+ "log""strings")@@ -10,8 +11,9 @@ type replyParser struct {lineIndex intmaybeFilePath stringcurrentFilePath string- files map[string]bool- fileContents map[string]string+ currentFileIdx int+ files []string+ fileContents []stringnumTokens intnumTokensByFile map[string]int}@@ -20,8 +22,8 @@ func NewReplyParser() *replyParser {info := &replyParser{lines: []string{""},currentFileLines: []string{},- files: make(map[string]bool),- fileContents: make(map[string]string),+ files: []string{},+ fileContents: []string{},numTokensByFile: make(map[string]int),}@@ -91,9 +93,12 @@ func (r *replyParser) AddChunk(chunk string, addToTotal bool) {// log.Println("Maybe file path is:", r.maybeFilePath) // Logging the maybeFilePathif strings.HasPrefix(prevFullLineTrimmed, "```") {r.currentFilePath = r.maybeFilePath+ r.currentFileIdx = len(r.files)+ r.fileContents = append(r.fileContents, "")r.maybeFilePath = ""r.currentFileLines = []string{}- // log.Println("Confirmed file path:", r.currentFilePath) // Logging the confirmed file path+ log.Println("Confirmed file path:", r.currentFilePath) // Logging the confirmed file path+return} else if prevFullLineTrimmed != "" {// turns out previous maybeFilePath was not a file path since there's a non-empty line before finding opening ticks@@ -128,30 +133,27 @@ func (r *replyParser) AddChunk(chunk string, addToTotal bool) {}}} else {+ log.Println("Current file path is not empty--adding to current file...")+if strings.HasPrefix(prevFullLineTrimmed, "```") {- r.files[r.currentFilePath] = true+ log.Println("Found closing ticks--adding file to files and resetting current file...")+ r.files = append(r.files, r.currentFilePath)r.currentFilePath = ""- // log.Println("Exited file block.")} else {- r.fileContents[r.currentFilePath] += prevFullLine + "\n"- r.currentFileLines = append(r.currentFileLines, prevFullLine)+ log.Println("Adding tokens to current file...") // Logging token addition- // r.contentByFile[r.currentFilePath] += prevFullLine + "\n"+ r.fileContents[r.currentFileIdx] += prevFullLine + "\n"+ r.currentFileLines = append(r.currentFileLines, prevFullLine)// fmt.Printf("Added %d tokens to %s\n", tokens, r.currentFilePath) // Logging token addition}}}-func (r *replyParser) Read() (files []string, fileContents map[string]string, numTokensByFile map[string]int, totalTokens int) {- files = make([]string, 0, len(r.files))- for file := range r.files {- files = append(files, file)- }-- return files, r.fileContents, r.numTokensByFile, r.numTokens+func (r *replyParser) Read() (files []string, fileContents []string, numTokensByFile map[string]int, totalTokens int) {+ return r.files, r.fileContents, r.numTokensByFile, r.numTokens}-func (r *replyParser) FinishAndRead() (files []string, fileContents map[string]string, numTokensByFile map[string]int, totalTokens int) {+func (r *replyParser) FinishAndRead() (files []string, fileContents []string, numTokensByFile map[string]int, totalTokens int) {r.AddChunk("\n", false)return r.Read()}diff --git a/app/shared/models.go b/app/shared/models.goindex 0a34ea19..acd09c1a 100644--- a/app/shared/models.go+++ b/app/shared/models.go@@ -182,8 +182,6 @@ type PlanResult struct {type CurrentPlanState struct {PlanResult *PlanResult `json:"planResult"`CurrentPlanFiles *CurrentPlanFiles `json:"currentPlanFiles"`- Contexts []*Context `json:"contexts"`- ContextsByPath map[string]*Context `json:"contextsByPath"`PendingBuildDescriptions []*ConvoMessageDescription `json:"pendingBuildDescriptions"`}diff --git a/app/shared/plan_result.go b/app/shared/plan_result.goindex ed75773a..238b8bb9 100644--- a/app/shared/plan_result.go+++ b/app/shared/plan_result.go@@ -2,6 +2,7 @@ package sharedimport ("fmt"+ "log""sort""strings""time"@@ -70,6 +71,14 @@ func (p PlanFileResultsByPath) NumPending() int {return numPending}+func (p PlanFileResultsByPath) OriginalContextForPath(path string) string {+ planResults := p[path]+ if len(planResults) == 0 {+ return ""+ }+ return planResults[0].ContextBody+}+func (r PlanResult) NumPendingForPath(path string) int {res := 0results := r.FileResultsByPath[path]@@ -92,17 +101,17 @@ func ApplyReplacements(content string, replacements []*Replacement, setFailed bosub := updated[lastInsertedIdx:]originalIdx := strings.Index(sub, replacement.Old)- // log.Println("Replacement: " + replacement.Old + " -> " + replacement.New)- // log.Println("Pre: " + pre)- // log.Println("Sub: " + sub)- // log.Println("Idx: " + fmt.Sprintf("%d", idx))- // log.Println("Updated: " + updated)-if originalIdx == -1 {allSucceeded = falseif setFailed {replacement.Failed = true}++ log.Println("Replacement failed: " + replacement.Old + " -> " + replacement.New)+ log.Println("Pre: " + pre)+ log.Println("Sub: " + sub)+ log.Println("Updated: " + updated)+} else {replaced := strings.Replace(sub, replacement.Old, replacement.New, 1)diff --git a/infra/package-lock.json b/infra/package-lock.jsonindex eaea7201..913d129c 100644--- a/infra/package-lock.json+++ b/infra/package-lock.json@@ -20,6 +20,7 @@"uuid": "^9.0.1"},"devDependencies": {+ "@types/node": "^20.11.10","@types/uuid": "^9.0.7","aws-cdk": "^2.122.0","typescript": "^5.3.3"@@ -1438,6 +1439,15 @@"node": ">= 14.15.0"}},+ "node_modules/@types/node": {+ "version": "20.11.10",+ "resolved": "https://registry.npmjs.org/@types/node/-/node-20.11.10.tgz",+ "integrity": "sha512-rZEfe/hJSGYmdfX9tvcPMYeYPW2sNl50nsw4jZmRcaG0HIAb0WYEpsB05GOb53vjqpyE9GUhlDQ4jLSoB5q9kg==",+ "dev": true,+ "dependencies": {+ "undici-types": "~5.26.4"+ }+ },"node_modules/@types/uuid": {"version": "9.0.7","resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-9.0.7.tgz",@@ -1494,6 +1504,12 @@"node": ">=14.17"}},+ "node_modules/undici-types": {+ "version": "5.26.5",+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz",+ "integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==",+ "dev": true+ },"node_modules/uuid": {"version": "9.0.1","resolved": "https://registry.npmjs.org/uuid/-/uuid-9.0.1.tgz",diff --git a/infra/package.json b/infra/package.jsonindex 7b9c5781..f8bb6f3d 100644--- a/infra/package.json+++ b/infra/package.json@@ -15,6 +15,7 @@"uuid": "^9.0.1"},"devDependencies": {+ "@types/node": "^20.11.10","@types/uuid": "^9.0.7","aws-cdk": "^2.122.0","typescript": "^5.3.3"diff --git a/infra/src/main.ts b/infra/src/main.tsindex 65737f75..8b6e0460 100644--- a/infra/src/main.ts+++ b/infra/src/main.ts@@ -10,10 +10,12 @@ import * as iam from "@aws-cdk/aws-iam";import * as acm from "@aws-cdk/aws-certificatemanager";import { v4 as uuid } from "uuid";-const tag = process.env.STACK_TAG || uuid().split("-")[0];+const tag = process.env.STACK_TAG;export class PlandexStack extends cdk.Stack {constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {+ if (!tag) throw new Error("STACK_TAG environment variable is not set");+super(scope, id, props);// Create a VPC with two public and two private subnets