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
some reorg, methods to check pending builds
Dane Schneider1f7f9eb21a9e
diff --git a/app/server/db/result_helpers.go b/app/server/db/result_helpers.goindex 490a8345..2300e7a5 100644--- a/app/server/db/result_helpers.go+++ b/app/server/db/result_helpers.go@@ -49,7 +49,7 @@ type CurrentPlanStateParams struct {OrgId stringPlanId stringPlanFileResults []*PlanFileResult- PendingBuildDescriptions []*ConvoMessageDescription+ ConvoMessageDescriptions []*ConvoMessageDescription}func GetCurrentPlanState(params CurrentPlanStateParams) (*shared.CurrentPlanState, error) {@@ -57,7 +57,7 @@ func GetCurrentPlanState(params CurrentPlanStateParams) (*shared.CurrentPlanStatplanId := params.PlanIdvar dbPlanFileResults []*PlanFileResult- var pendingBuildDescriptions []*shared.ConvoMessageDescription+ var convoMessageDescriptions []*shared.ConvoMessageDescriptionerrCh := make(chan error)@@ -78,19 +78,19 @@ func GetCurrentPlanState(params CurrentPlanStateParams) (*shared.CurrentPlanStat}()go func() {- if params.PendingBuildDescriptions == nil {- res, err := GetPendingBuildDescriptions(orgId, planId)+ if params.ConvoMessageDescriptions == nil {+ res, err := GetConvoMessageDescriptions(orgId, planId)if err != nil {errCh <- fmt.Errorf("error getting latest plan build description: %v", err)return}for _, desc := range res {- pendingBuildDescriptions = append(pendingBuildDescriptions, desc.ToApi())+ convoMessageDescriptions = append(convoMessageDescriptions, desc.ToApi())}} else {- for _, desc := range params.PendingBuildDescriptions {- pendingBuildDescriptions = append(pendingBuildDescriptions, desc.ToApi())+ for _, desc := range params.ConvoMessageDescriptions {+ convoMessageDescriptions = append(convoMessageDescriptions, desc.ToApi())}}@@ -113,7 +113,7 @@ func GetCurrentPlanState(params CurrentPlanStateParams) (*shared.CurrentPlanStatplanState := &shared.CurrentPlanState{PlanResult: planResult,- PendingBuildDescriptions: pendingBuildDescriptions,+ ConvoMessageDescriptions: convoMessageDescriptions,}currentPlanFiles, err := planState.GetFiles()@@ -127,7 +127,7 @@ func GetCurrentPlanState(params CurrentPlanStateParams) (*shared.CurrentPlanStatreturn planState, nil}-func GetPendingBuildDescriptions(orgId, planId string) ([]*ConvoMessageDescription, error) {+func GetConvoMessageDescriptions(orgId, planId string) ([]*ConvoMessageDescription, error) {var descriptions []*ConvoMessageDescriptiondescriptionsDir := getPlanDescriptionsDir(orgId, planId)files, err := os.ReadDir(descriptionsDir)@@ -283,7 +283,7 @@ func ApplyPlan(orgId, userId, branchName string, plan *Plan) error {errCh := make(chan error)var results []*PlanFileResult- var pendingBuildDescriptions []*ConvoMessageDescription+ var convoMessageDescriptions []*ConvoMessageDescriptioncontextsById := make(map[string]*Context)contextsByPath := make(map[string]*Context)@@ -298,12 +298,12 @@ func ApplyPlan(orgId, userId, branchName string, plan *Plan) error {}()go func() {- res, err := GetPendingBuildDescriptions(orgId, planId)+ res, err := GetConvoMessageDescriptions(orgId, planId)if err != nil {errCh <- fmt.Errorf("error getting latest plan build description: %v", err)return}- pendingBuildDescriptions = res+ convoMessageDescriptions = reserrCh <- nil}()@@ -359,7 +359,7 @@ func ApplyPlan(orgId, userId, branchName string, plan *Plan) error {OrgId: orgId,PlanId: plan.Id,PlanFileResults: results,- PendingBuildDescriptions: pendingBuildDescriptions,+ ConvoMessageDescriptions: convoMessageDescriptions,})if err != nil {@@ -395,7 +395,7 @@ func ApplyPlan(orgId, userId, branchName string, plan *Plan) error {}(result)}- for _, description := range pendingBuildDescriptions {+ for _, description := range convoMessageDescriptions {go func(description *ConvoMessageDescription) {description.AppliedAt = &now@@ -474,7 +474,7 @@ func ApplyPlan(orgId, userId, branchName string, plan *Plan) error {}numRoutines := len(pendingDbResults) +- len(pendingBuildDescriptions)+ len(convoMessageDescriptions)if len(pendingNewFilesSet) > 0 {numRoutines++}diff --git a/app/server/model/plan/build_finish.go b/app/server/model/plan/build_finish.goindex f9e8b550..7e3d044a 100644--- a/app/server/model/plan/build_finish.go+++ b/app/server/model/plan/build_finish.go@@ -90,7 +90,7 @@ func (state *activeBuildStreamFileState) onFinishBuild() {// get plan descriptionsvar planDescs []*db.ConvoMessageDescription- planDescs, err = db.GetPendingBuildDescriptions(currentOrgId, planId)+ planDescs, err = db.GetConvoMessageDescriptions(currentOrgId, planId)if err != nil {log.Printf("Error getting pending build descriptions: %v\n", err)return fmt.Errorf("error getting pending build descriptions: %v", err)@@ -101,7 +101,7 @@ func (state *activeBuildStreamFileState) onFinishBuild() {currentPlan, err = db.GetCurrentPlanState(db.CurrentPlanStateParams{OrgId: currentOrgId,PlanId: planId,- PendingBuildDescriptions: planDescs,+ ConvoMessageDescriptions: planDescs,})if err != nil {log.Printf("Error getting current plan state: %v\n", err)diff --git a/app/server/types/active_plan.go b/app/server/types/active_plan.goindex e741ed11..feb4b33c 100644--- a/app/server/types/active_plan.go+++ b/app/server/types/active_plan.go@@ -3,8 +3,6 @@ package typesimport ("context""encoding/json"- "fmt"- "log""net/http""plandex-server/db""time"@@ -158,95 +156,3 @@ func (ap *ActivePlan) NumSubscribers() int {func (b *ActiveBuild) BuildFinished() bool {return b.Success || b.Error != nil}--func (ap *ActivePlan) PendingBuildsByPath(orgId, userId string, convoMessagesArg []*db.ConvoMessage) (map[string][]*ActiveBuild, error) {- var planDescs []*db.ConvoMessageDescription- var convoMessagesById map[string]*db.ConvoMessage-- errCh := make(chan error)-- go func() {- var err error- planDescs, err = db.GetPendingBuildDescriptions(orgId, ap.Id)- if err != nil {- errCh <- fmt.Errorf("error getting pending build descriptions: %v", err)- return- }-- errCh <- nil- }()-- go func() {- var convoMessages []*db.ConvoMessage- if convoMessagesArg == nil {- var err error- convoMessages, err = db.GetPlanConvo(orgId, ap.Id)-- if err != nil {- errCh <- fmt.Errorf("error getting plan convo: %v", err)- return- }- } else {- convoMessages = convoMessagesArg- }-- convoMessagesById = map[string]*db.ConvoMessage{}- for _, msg := range convoMessages {- convoMessagesById[msg.Id] = msg- }-- errCh <- nil- }()-- for i := 0; i < 2; i++ {- err := <-errCh- if err != nil {- log.Printf("Error getting plan data: %v\n", err)- return nil, err- }- }-- // log.Println("planDescs:")- // spew.Dump(planDescs)-- activeBuildsByPath := map[string][]*ActiveBuild{}-- for _, desc := range planDescs {- if !desc.DidBuild && len(desc.Files) > 0 {- if desc.ConvoMessageId == "" {- log.Printf("No convo message ID for description: %v\n", desc)- return nil, fmt.Errorf("no convo message ID for description: %v", desc)- }-- if convoMessagesById[desc.ConvoMessageId] == nil {- log.Printf("No convo message for ID: %s\n", desc.ConvoMessageId)- return nil, fmt.Errorf("no convo message for ID: %s", desc.ConvoMessageId)- }-- convoMessage := convoMessagesById[desc.ConvoMessageId]-- replyParser := NewReplyParser()- replyParser.AddChunk(convoMessage.Message, false)- parserRes := replyParser.FinishAndRead()-- for i, file := range desc.Files {- if activeBuildsByPath[file] == nil {- activeBuildsByPath[file] = []*ActiveBuild{}- }-- activeBuildsByPath[file] = append(activeBuildsByPath[file], &ActiveBuild{- ReplyId: desc.ConvoMessageId,- Idx: i,- FileContent: parserRes.FileContents[i],- Path: file,- FileDescription: parserRes.FileDescriptions[i],- })- }- }- }-- // log.Println("activeBuildsByPath:")- // spew.Dump(activeBuildsByPath)-- return activeBuildsByPath, nil-}diff --git a/app/server/types/active_plan_pending_builds.go b/app/server/types/active_plan_pending_builds.gonew file mode 100644index 00000000..672b2ca9--- /dev/null+++ b/app/server/types/active_plan_pending_builds.go@@ -0,0 +1,76 @@+package types++import (+ "fmt"+ "log"+ "plandex-server/db"+)++func (ap *ActivePlan) PendingBuildsByPath(orgId, userId string, convoMessagesArg []*db.ConvoMessage) (map[string][]*ActiveBuild, error) {+ planDescs, err := db.GetConvoMessageDescriptions(orgId, ap.Id)+ if err != nil {+ return nil, fmt.Errorf("error getting pending build descriptions: %v", err)+ }++ if !HasPendingBuilds(planDescs) {+ return map[string][]*ActiveBuild{}, nil+ }++ var convoMessages []*db.ConvoMessage+ if convoMessagesArg == nil {+ var err error+ convoMessages, err = db.GetPlanConvo(orgId, ap.Id)++ if err != nil {+ return nil, fmt.Errorf("error getting plan convo: %v", err)+ }+ } else {+ convoMessages = convoMessagesArg+ }++ convoMessagesById := map[string]*db.ConvoMessage{}+ for _, msg := range convoMessages {+ convoMessagesById[msg.Id] = msg+ }++ activeBuildsByPath := map[string][]*ActiveBuild{}++ for _, desc := range planDescs {+ if !desc.DidBuild && len(desc.Files) > 0 {+ if desc.ConvoMessageId == "" {+ log.Printf("No convo message ID for description: %v\n", desc)+ return nil, fmt.Errorf("no convo message ID for description: %v", desc)+ }++ if convoMessagesById[desc.ConvoMessageId] == nil {+ log.Printf("No convo message for ID: %s\n", desc.ConvoMessageId)+ return nil, fmt.Errorf("no convo message for ID: %s", desc.ConvoMessageId)+ }++ convoMessage := convoMessagesById[desc.ConvoMessageId]++ replyParser := NewReplyParser()+ replyParser.AddChunk(convoMessage.Message, false)+ parserRes := replyParser.FinishAndRead()++ for i, file := range desc.Files {+ if activeBuildsByPath[file] == nil {+ activeBuildsByPath[file] = []*ActiveBuild{}+ }++ activeBuildsByPath[file] = append(activeBuildsByPath[file], &ActiveBuild{+ ReplyId: desc.ConvoMessageId,+ Idx: i,+ FileContent: parserRes.FileContents[i],+ Path: file,+ FileDescription: parserRes.FileDescriptions[i],+ })+ }+ }+ }++ // log.Println("activeBuildsByPath:")+ // spew.Dump(activeBuildsByPath)++ return activeBuildsByPath, nil+}diff --git a/app/server/types/convo_message_desc.go b/app/server/types/convo_message_desc.gonew file mode 100644index 00000000..dbe8bc89--- /dev/null+++ b/app/server/types/convo_message_desc.go@@ -0,0 +1,16 @@+package types++import (+ "plandex-server/db"++ "github.com/plandex/plandex/shared"+)++func HasPendingBuilds(planDescs []*db.ConvoMessageDescription) bool {+ apiDescs := make([]*shared.ConvoMessageDescription, len(planDescs))+ for i, desc := range planDescs {+ apiDescs[i] = desc.ToApi()+ }++ return shared.HasPendingBuilds(apiDescs)+}diff --git a/app/shared/data_models.go b/app/shared/data_models.goindex c6abb04a..eb215ed4 100644--- a/app/shared/data_models.go+++ b/app/shared/data_models.go@@ -190,7 +190,7 @@ type PlanResult struct {type CurrentPlanState struct {PlanResult *PlanResult `json:"planResult"`CurrentPlanFiles *CurrentPlanFiles `json:"currentPlanFiles"`- PendingBuildDescriptions []*ConvoMessageDescription `json:"pendingBuildDescriptions"`+ ConvoMessageDescriptions []*ConvoMessageDescription `json:"convoMessageDescriptions"`}type OrgRole struct {diff --git a/app/shared/plan_result.go b/app/shared/plan_result.goindex 211531a6..510f2ac2 100644--- a/app/shared/plan_result.go+++ b/app/shared/plan_result.go@@ -1,10 +1,6 @@package sharedimport (- "fmt"- "log"- "sort"- "strings""time")@@ -90,234 +86,38 @@ func (r PlanResult) NumPendingForPath(path string) int {return res}-func ApplyReplacements(content string, replacements []*Replacement, setFailed bool) (string, bool) {- updated := content- lastInsertedIdx := 0-- allSucceeded := true-- for _, replacement := range replacements {- pre := updated[:lastInsertedIdx]- sub := updated[lastInsertedIdx:]- originalIdx := strings.Index(sub, replacement.Old)-- if originalIdx == -1 {- allSucceeded = false- if 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)-- updated = pre + replaced- lastInsertedIdx = lastInsertedIdx + originalIdx + len(replacement.New)+func (desc *ConvoMessageDescription) NumBuildsPendingByPath() map[string]int {+ res := map[string]int{}+ if !desc.DidBuild && len(desc.Files) > 0 {+ for _, file := range desc.Files {+ res[file]++}}-- return updated, allSucceeded+ return res}-func (planState *CurrentPlanState) GetFiles() (*CurrentPlanFiles, error) {- return planState.GetFilesBeforeReplacement("")+func (desc *ConvoMessageDescription) HasPendingBuilds() bool {+ return len(desc.NumBuildsPendingByPath()) > 0}-func (planState *CurrentPlanState) GetFilesBeforeReplacement(- replacementId string,-) (*CurrentPlanFiles, error) {- planRes := planState.PlanResult-- files := make(map[string]string)- shas := make(map[string]string)- updatedAtByPath := make(map[string]time.Time)-- for path, planResults := range planRes.FileResultsByPath {- updated := files[path]-- PlanResLoop:- for _, planRes := range planResults {-- if !planRes.IsPending() {- continue- }-- if len(planRes.Replacements) == 0 {- if updated != "" {- return nil, fmt.Errorf("plan updates out of order: %s", path)- }-- updated = planRes.Content- files[path] = updated- continue- } else if updated == "" {- updated = planRes.ContextBody- shas[path] = planRes.ContextSha- }-- replacements := []*Replacement{}- for _, replacement := range planRes.Replacements {- if replacement.Id == replacementId {- break PlanResLoop- }- replacements = append(replacements, replacement)- }-- var allSucceeded bool- updated, allSucceeded = ApplyReplacements(updated, replacements, false)-- if !allSucceeded {- return nil, fmt.Errorf("plan replacement failed: %s", path)- }-- updatedAtByPath[path] = planRes.CreatedAt+func NumBuildsPendingByPath(planDescs []*ConvoMessageDescription) map[string]int {+ res := map[string]int{}+ for _, desc := range planDescs {+ for file, num := range desc.NumBuildsPendingByPath() {+ res[file] += num}-- files[path] = updated}-- return &CurrentPlanFiles{Files: files, ContextShas: shas}, nil+ return res}-func (state *CurrentPlanState) PendingChangesSummary() string {- var msgs []string-- msgs = append(msgs, "ποΈ Build pending changes")-- descByConvoMessageId := make(map[string]*ConvoMessageDescription)- for _, desc := range state.PendingBuildDescriptions {- if desc.ConvoMessageId == "" {- log.Println("Warning: ConvoMessageId is empty for description:", desc)- continue- }-- descByConvoMessageId[desc.ConvoMessageId] = desc- }-- type changeset struct {- descsSet map[string]bool- descs []*ConvoMessageDescription- results []*PlanFileResult- }- byDescs := map[string]*changeset{}-- for _, result := range state.PlanResult.Results {- convoIds := map[string]bool{}- if descByConvoMessageId[result.ConvoMessageId] != nil {- convoIds[result.ConvoMessageId] = true- }- var uniqueConvoIds []string- for convoId := range convoIds {- uniqueConvoIds = append(uniqueConvoIds, convoId)- }-- composite := strings.Join(uniqueConvoIds, "|")- if _, ok := byDescs[composite]; !ok {- byDescs[composite] = &changeset{- descsSet: make(map[string]bool),- }- }-- ch := byDescs[composite]- ch.results = append(byDescs[composite].results, result)-- for _, convoMessageId := range uniqueConvoIds {- if desc, ok := descByConvoMessageId[convoMessageId]; ok {- if !ch.descsSet[convoMessageId] {- ch.descs = append(ch.descs, desc)- ch.descsSet[convoMessageId] = true- }- } else {- log.Println("Warning: no description for convo message id:", convoMessageId)- }- }- }-- var sortedChangesets []*changeset- for _, ch := range byDescs {- sortedChangesets = append(sortedChangesets, ch)- }-- sort.Slice(sortedChangesets, func(i, j int) bool {- // put changesets with no descriptions last, otherwise sort by date- if len(sortedChangesets[i].descs) == 0 {- return false- }- if len(sortedChangesets[j].descs) == 0 {- return true- }- return sortedChangesets[i].descs[0].CreatedAt.Before(sortedChangesets[j].descs[0].CreatedAt)- })-- for _, ch := range sortedChangesets {- var descMsgs []string-- if len(ch.descs) == 0 {- descMsgs = append(descMsgs, " βοΈ Changes")- } else {- for _, desc := range ch.descs {- descMsgs = append(descMsgs, fmt.Sprintf(" βοΈ %s", desc.CommitMsg))- }- }-- pendingNewFilesSet := make(map[string]bool)- pendingReplacementPathsSet := make(map[string]bool)- pendingReplacementsByPath := make(map[string][]*Replacement)-- for _, result := range ch.results {-- if result.IsPending() {- if len(result.Replacements) == 0 && result.Content != "" {- pendingNewFilesSet[result.Path] = true- } else {- pendingReplacementPathsSet[result.Path] = true- pendingReplacementsByPath[result.Path] = append(pendingReplacementsByPath[result.Path], result.Replacements...)- }- }- }-- if len(pendingNewFilesSet) == 0 && len(pendingReplacementPathsSet) == 0 {- continue- }-- msgs = append(msgs, descMsgs...)-- var pendingNewFiles []string- var pendingReplacementPaths []string-- for path := range pendingNewFilesSet {- pendingNewFiles = append(pendingNewFiles, path)- }-- for path := range pendingReplacementPathsSet {- pendingReplacementPaths = append(pendingReplacementPaths, path)- }-- sort.Slice(pendingReplacementPaths, func(i, j int) bool {- return pendingReplacementPaths[i] < pendingReplacementPaths[j]- })-- sort.Slice(pendingNewFiles, func(i, j int) bool {- return pendingNewFiles[i] < pendingNewFiles[j]- })-- if len(pendingNewFiles) > 0 {- for _, path := range pendingNewFiles {- msgs = append(msgs, fmt.Sprintf(" β’ new file β %s", path))- }- }-- if len(pendingReplacementPaths) > 0 {- for _, path := range pendingReplacementPaths {- msgs = append(msgs, fmt.Sprintf(" β’ edit β %s", path))- }+func HasPendingBuilds(planDescs []*ConvoMessageDescription) bool {+ return len(NumBuildsPendingByPath(planDescs)) > 0+}- }+func (c *CurrentPlanState) NumBuildsPendingByPath() map[string]int {+ return NumBuildsPendingByPath(c.ConvoMessageDescriptions)+}- }- return strings.Join(msgs, "\n")+func (c *CurrentPlanState) HasPendingBuilds() bool {+ return len(c.NumBuildsPendingByPath()) > 0}diff --git a/app/shared/plan_result_pending_summary.go b/app/shared/plan_result_pending_summary.gonew file mode 100644index 00000000..4a97c2d4--- /dev/null+++ b/app/shared/plan_result_pending_summary.go@@ -0,0 +1,147 @@+package shared++import (+ "fmt"+ "log"+ "sort"+ "strings"+)++func (state *CurrentPlanState) PendingChangesSummary() string {+ var msgs []string++ msgs = append(msgs, "ποΈ Build pending changes")++ descByConvoMessageId := make(map[string]*ConvoMessageDescription)+ for _, desc := range state.ConvoMessageDescriptions {+ if desc.ConvoMessageId == "" {+ log.Println("Warning: ConvoMessageId is empty for description:", desc)+ continue+ }++ descByConvoMessageId[desc.ConvoMessageId] = desc+ }++ type changeset struct {+ descsSet map[string]bool+ descs []*ConvoMessageDescription+ results []*PlanFileResult+ }+ byDescs := map[string]*changeset{}++ for _, result := range state.PlanResult.Results {+ convoIds := map[string]bool{}+ if descByConvoMessageId[result.ConvoMessageId] != nil {+ convoIds[result.ConvoMessageId] = true+ }+ var uniqueConvoIds []string+ for convoId := range convoIds {+ uniqueConvoIds = append(uniqueConvoIds, convoId)+ }++ composite := strings.Join(uniqueConvoIds, "|")+ if _, ok := byDescs[composite]; !ok {+ byDescs[composite] = &changeset{+ descsSet: make(map[string]bool),+ }+ }++ ch := byDescs[composite]+ ch.results = append(byDescs[composite].results, result)++ for _, convoMessageId := range uniqueConvoIds {+ if desc, ok := descByConvoMessageId[convoMessageId]; ok {+ if !ch.descsSet[convoMessageId] {+ ch.descs = append(ch.descs, desc)+ ch.descsSet[convoMessageId] = true+ }+ } else {+ log.Println("Warning: no description for convo message id:", convoMessageId)+ }+ }+ }++ var sortedChangesets []*changeset+ for _, ch := range byDescs {+ sortedChangesets = append(sortedChangesets, ch)+ }++ sort.Slice(sortedChangesets, func(i, j int) bool {+ // put changesets with no descriptions last, otherwise sort by date+ if len(sortedChangesets[i].descs) == 0 {+ return false+ }+ if len(sortedChangesets[j].descs) == 0 {+ return true+ }+ return sortedChangesets[i].descs[0].CreatedAt.Before(sortedChangesets[j].descs[0].CreatedAt)+ })++ for _, ch := range sortedChangesets {+ var descMsgs []string++ if len(ch.descs) == 0 {+ descMsgs = append(descMsgs, " βοΈ Changes")+ } else {+ for _, desc := range ch.descs {+ descMsgs = append(descMsgs, fmt.Sprintf(" βοΈ %s", desc.CommitMsg))+ }+ }++ pendingNewFilesSet := make(map[string]bool)+ pendingReplacementPathsSet := make(map[string]bool)+ pendingReplacementsByPath := make(map[string][]*Replacement)++ for _, result := range ch.results {++ if result.IsPending() {+ if len(result.Replacements) == 0 && result.Content != "" {+ pendingNewFilesSet[result.Path] = true+ } else {+ pendingReplacementPathsSet[result.Path] = true+ pendingReplacementsByPath[result.Path] = append(pendingReplacementsByPath[result.Path], result.Replacements...)+ }+ }+ }++ if len(pendingNewFilesSet) == 0 && len(pendingReplacementPathsSet) == 0 {+ continue+ }++ msgs = append(msgs, descMsgs...)++ var pendingNewFiles []string+ var pendingReplacementPaths []string++ for path := range pendingNewFilesSet {+ pendingNewFiles = append(pendingNewFiles, path)+ }++ for path := range pendingReplacementPathsSet {+ pendingReplacementPaths = append(pendingReplacementPaths, path)+ }++ sort.Slice(pendingReplacementPaths, func(i, j int) bool {+ return pendingReplacementPaths[i] < pendingReplacementPaths[j]+ })++ sort.Slice(pendingNewFiles, func(i, j int) bool {+ return pendingNewFiles[i] < pendingNewFiles[j]+ })++ if len(pendingNewFiles) > 0 {+ for _, path := range pendingNewFiles {+ msgs = append(msgs, fmt.Sprintf(" β’ new file β %s", path))+ }+ }++ if len(pendingReplacementPaths) > 0 {+ for _, path := range pendingReplacementPaths {+ msgs = append(msgs, fmt.Sprintf(" β’ edit β %s", path))+ }++ }++ }+ return strings.Join(msgs, "\n")+}diff --git a/app/shared/plan_result_replacements.go b/app/shared/plan_result_replacements.gonew file mode 100644index 00000000..53d4093c--- /dev/null+++ b/app/shared/plan_result_replacements.go@@ -0,0 +1,101 @@+package shared++import (+ "fmt"+ "log"+ "strings"+ "time"+)++func ApplyReplacements(content string, replacements []*Replacement, setFailed bool) (string, bool) {+ updated := content+ lastInsertedIdx := 0++ allSucceeded := true++ for _, replacement := range replacements {+ pre := updated[:lastInsertedIdx]+ sub := updated[lastInsertedIdx:]+ originalIdx := strings.Index(sub, replacement.Old)++ if originalIdx == -1 {+ allSucceeded = false+ if 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)++ updated = pre + replaced+ lastInsertedIdx = lastInsertedIdx + originalIdx + len(replacement.New)+ }+ }++ return updated, allSucceeded+}++func (planState *CurrentPlanState) GetFiles() (*CurrentPlanFiles, error) {+ return planState.GetFilesBeforeReplacement("")+}++func (planState *CurrentPlanState) GetFilesBeforeReplacement(+ replacementId string,+) (*CurrentPlanFiles, error) {+ planRes := planState.PlanResult++ files := make(map[string]string)+ shas := make(map[string]string)+ updatedAtByPath := make(map[string]time.Time)++ for path, planResults := range planRes.FileResultsByPath {+ updated := files[path]++ PlanResLoop:+ for _, planRes := range planResults {++ if !planRes.IsPending() {+ continue+ }++ if len(planRes.Replacements) == 0 {+ if updated != "" {+ return nil, fmt.Errorf("plan updates out of order: %s", path)+ }++ updated = planRes.Content+ files[path] = updated+ continue+ } else if updated == "" {+ updated = planRes.ContextBody+ shas[path] = planRes.ContextSha+ }++ replacements := []*Replacement{}+ for _, replacement := range planRes.Replacements {+ if replacement.Id == replacementId {+ break PlanResLoop+ }+ replacements = append(replacements, replacement)+ }++ var allSucceeded bool+ updated, allSucceeded = ApplyReplacements(updated, replacements, false)++ if !allSucceeded {+ return nil, fmt.Errorf("plan replacement failed: %s", path)+ }++ updatedAtByPath[path] = planRes.CreatedAt+ }++ files[path] = updated+ }++ return &CurrentPlanFiles{Files: files, ContextShas: shas}, nil+}