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
context load/update invalidate conflicting changes
Dane Schneider36102364f0e2
diff --git a/app/cli/changes_tui/actions.go b/app/cli/changes_tui/actions.goindex bd874b07..c3b64cf0 100644--- a/app/cli/changes_tui/actions.go+++ b/app/cli/changes_tui/actions.go@@ -181,7 +181,7 @@ func (m *changesUIModel) updateMainView(scrollReplacement bool) {// var updateMsg types.ChangesUIViewportsUpdateif m.selectedNewFile() || m.selectedFullFile() {- originalFile := m.currentPlan.PlanResult.FileResultsByPath.OriginalContextForPath(m.selectionInfo.currentPath)+ originalFile := m.currentPlan.ContextsByPath[m.selectionInfo.currentPath].Bodyvar updatedFile stringdiff --git a/app/cli/changes_tui/model.go b/app/cli/changes_tui/model.goindex 9515664d..204f976b 100644--- a/app/cli/changes_tui/model.go+++ b/app/cli/changes_tui/model.go@@ -141,7 +141,7 @@ func initialModel() *changesUIModel {// ),quit: bubbleKey.NewBinding(- bubbleKey.WithKeys("q", "ctrl+c"),+ bubbleKey.WithKeys("q", "ctrl+c", "esc"),bubbleKey.WithHelp("q", "quit"),),},diff --git a/app/cli/cmd/build.go b/app/cli/cmd/build.goindex a201227f..85c66a5e 100644--- a/app/cli/cmd/build.go+++ b/app/cli/cmd/build.go@@ -2,18 +2,12 @@ package cmdimport ("fmt"- "log""os"- "plandex/api""plandex/auth"- "plandex/fs""plandex/lib"- "plandex/stream"- streamtui "plandex/stream_tui"+ "plandex/plan_exec""plandex/term"- "github.com/fatih/color"- "github.com/plandex/plandex/shared""github.com/spf13/cobra")@@ -47,57 +41,29 @@ func build(cmd *cobra.Command, args []string) {return}- lib.MustCheckOutdatedContextWithOutput()-- contexts, apiErr := api.Client.ListContext(lib.CurrentPlanId, lib.CurrentBranch)-- if apiErr != nil {- color.New(color.FgRed).Fprintln(os.Stderr, "Error getting context:", apiErr)- os.Exit(1)- }-- projectPaths, _, err := fs.GetProjectPaths(fs.GetBaseDirForContexts(contexts))+ didBuild, err := plan_exec.Build(plan_exec.ExecParams{+ CurrentPlanId: lib.CurrentPlanId,+ CurrentBranch: lib.CurrentBranch,+ CheckOutdatedContext: func() { lib.MustCheckOutdatedContext(false) },+ }, buildBg)if err != nil {- fmt.Fprintln(os.Stderr, "Error getting project paths:", err)+ fmt.Fprintln(os.Stderr, err)return}- apiErr = api.Client.BuildPlan(lib.CurrentPlanId, lib.CurrentBranch, shared.BuildPlanRequest{- ConnectStream: !buildBg,- ProjectPaths: projectPaths,- ApiKey: os.Getenv("OPENAI_API_KEY"),- }, stream.OnStreamPlan)-- if apiErr != nil {- if apiErr.Msg == shared.NoBuildsErr {- streamtui.Quit()- fmt.Println("π€·ββοΈ This plan has no pending changes to build")- return- }-- fmt.Fprintln(os.Stderr, "Error building plan:", apiErr.Msg)+ if !didBuild {+ fmt.Println()+ term.PrintCmds("", "log", "tell", "continue")return}if buildBg {fmt.Println("ποΈ Building plan in the background")+ fmt.Println()+ term.PrintCmds("", "ps", "connect", "stop")} else {- go func() {- err := streamtui.StartStreamUI("", true)-- if err != nil {- log.Printf("Error starting stream UI: %v\n", err)- os.Exit(1)- }-- fmt.Println()- term.PrintCmds("", "changes", "apply", "log")-- os.Exit(0)- }()-- // Wait for the stream to finish- select {}+ fmt.Println()+ term.PrintCmds("", "changes", "apply", "log")}}diff --git a/app/cli/cmd/continue.go b/app/cli/cmd/continue.goindex 970a967d..9b6712fa 100644--- a/app/cli/cmd/continue.go+++ b/app/cli/cmd/continue.go@@ -5,7 +5,7 @@ import ("os""plandex/auth""plandex/lib"- "plandex/tell"+ "plandex/plan_exec""plandex/term""github.com/spf13/cobra"@@ -34,12 +34,15 @@ func doContinue(cmd *cobra.Command, args []string) {auth.MustResolveAuthWithOrg()lib.MustResolveProject()- lib.MustCheckOutdatedContextWithOutput()if lib.CurrentPlanId == "" {fmt.Fprintln(os.Stderr, "No current plan")return}- tell.TellPlan("", tellBg, tellStop, tellNoBuild, true)+ plan_exec.TellPlan(plan_exec.ExecParams{+ CurrentPlanId: lib.CurrentPlanId,+ CurrentBranch: lib.CurrentBranch,+ CheckOutdatedContext: func() { lib.MustCheckOutdatedContext(false) },+ }, "", tellBg, tellStop, tellNoBuild, true)}diff --git a/app/cli/cmd/tell.go b/app/cli/cmd/tell.goindex 0b1dae82..2831138e 100644--- a/app/cli/cmd/tell.go+++ b/app/cli/cmd/tell.go@@ -6,7 +6,7 @@ import ("os/exec""plandex/auth""plandex/lib"- "plandex/tell"+ "plandex/plan_exec""plandex/term""strings"@@ -67,54 +67,7 @@ func doTell(cmd *cobra.Command, args []string) {}prompt = string(bytes)} else {- editor := os.Getenv("EDITOR")- if editor == "" {- editor = os.Getenv("VISUAL")- if editor == "" {- editor = defaultEditor- }- }-- tempFile, err := os.CreateTemp(os.TempDir(), "plandex_prompt_*")- if err != nil {- fmt.Fprintln(os.Stderr, "Failed to create temporary file:", err)- return- }-- instructions := getEditorInstructions(editor)- filename := tempFile.Name()- err = os.WriteFile(filename, []byte(instructions), 0644)- if err != nil {- fmt.Fprintln(os.Stderr, "Failed to write instructions to temporary file:", err)- return- }-- editorCmd := prepareEditorCommand(editor, filename)- editorCmd.Stdin = os.Stdin- editorCmd.Stdout = os.Stdout- editorCmd.Stderr = os.Stderr- err = editorCmd.Run()- if err != nil {- fmt.Fprintln(os.Stderr, "Error opening editor:", err)- return- }-- bytes, err := os.ReadFile(tempFile.Name())- if err != nil {- fmt.Fprintln(os.Stderr, "Error reading temporary file:", err)- return- }-- prompt = string(bytes)-- err = os.Remove(tempFile.Name())- if err != nil {- fmt.Fprintln(os.Stderr, "Error removing temporary file:", err)- return- }-- prompt = strings.TrimPrefix(prompt, strings.TrimSpace(instructions))- prompt = strings.TrimSpace(prompt)+ prompt = getEditorPrompt()}if prompt == "" {@@ -122,9 +75,11 @@ func doTell(cmd *cobra.Command, args []string) {return}- lib.MustCheckOutdatedContextWithOutput()-- tell.TellPlan(prompt, tellBg, tellStop, tellNoBuild, false)+ plan_exec.TellPlan(plan_exec.ExecParams{+ CurrentPlanId: lib.CurrentPlanId,+ CurrentBranch: lib.CurrentBranch,+ CheckOutdatedContext: func() { lib.MustCheckOutdatedContext(false) },+ }, prompt, tellBg, tellStop, tellNoBuild, false)}func prepareEditorCommand(editor string, filename string) *exec.Cmd {@@ -143,3 +98,57 @@ func getEditorInstructions(editor string) string {return "Write your prompt below, then save and exit to send it to Plandex.\n\n"}++func getEditorPrompt() string {+ editor := os.Getenv("EDITOR")+ if editor == "" {+ editor = os.Getenv("VISUAL")+ if editor == "" {+ editor = defaultEditor+ }+ }++ tempFile, err := os.CreateTemp(os.TempDir(), "plandex_prompt_*")+ if err != nil {+ fmt.Fprintln(os.Stderr, "Failed to create temporary file:", err)+ os.Exit(1)+ }++ instructions := getEditorInstructions(editor)+ filename := tempFile.Name()+ err = os.WriteFile(filename, []byte(instructions), 0644)+ if err != nil {+ fmt.Fprintln(os.Stderr, "Failed to write instructions to temporary file:", err)+ os.Exit(1)+ }++ editorCmd := prepareEditorCommand(editor, filename)+ editorCmd.Stdin = os.Stdin+ editorCmd.Stdout = os.Stdout+ editorCmd.Stderr = os.Stderr+ err = editorCmd.Run()+ if err != nil {+ fmt.Fprintln(os.Stderr, "Error opening editor:", err)+ os.Exit(1)+ }++ bytes, err := os.ReadFile(tempFile.Name())+ if err != nil {+ fmt.Fprintln(os.Stderr, "Error reading temporary file:", err)+ os.Exit(1)+ }++ prompt := string(bytes)++ err = os.Remove(tempFile.Name())+ if err != nil {+ fmt.Fprintln(os.Stderr, "Error removing temporary file:", err)+ os.Exit(1)+ }++ prompt = strings.TrimPrefix(prompt, strings.TrimSpace(instructions))+ prompt = strings.TrimSpace(prompt)++ return prompt++}diff --git a/app/cli/cmd/update.go b/app/cli/cmd/update.goindex d75dcde9..9f3e9f79 100644--- a/app/cli/cmd/update.go+++ b/app/cli/cmd/update.go@@ -24,5 +24,5 @@ func update(cmd *cobra.Command, args []string) {auth.MustResolveAuthWithOrg()lib.MustResolveProject()- lib.MustUpdateContextWithOuput()+ lib.MustUpdateContext()}diff --git a/app/cli/go.mod b/app/cli/go.modindex c38f941f..299dd064 100644--- a/app/cli/go.mod+++ b/app/cli/go.mod@@ -5,7 +5,6 @@ go 1.21.3require (github.com/atotto/clipboard v0.1.4github.com/charmbracelet/lipgloss v0.9.1- github.com/davecgh/go-spew v1.1.1github.com/fatih/color v1.16.0github.com/muesli/reflow v0.3.0github.com/muesli/termenv v0.15.2diff --git a/app/cli/lib/apply.go b/app/cli/lib/apply.goindex 6622da2b..3aeb62b6 100644--- a/app/cli/lib/apply.go+++ b/app/cli/lib/apply.go@@ -49,7 +49,11 @@ func ApplyPlanWithOutput(planId, branch string, autoConfirm bool) error {var err errorfor path := range currentPlanFiles.Files {- contextSha := currentPlanFiles.ContextShas[path]+ context := currentPlanState.ContextsByPath[path]+ var contextSha string+ if context != nil {+ contextSha = currentPlanState.ContextsByPath[path].Sha+ }if contextSha == "" {// the path wasn't in contextdiff --git a/app/cli/lib/build.go b/app/cli/lib/build.gonew file mode 100644index 00000000..36ae5e53--- /dev/null+++ b/app/cli/lib/build.go@@ -0,0 +1,7 @@+package lib++var buildPlanInlineFn func() (bool, error)++func SetBuildPlanInlineFn(fn func() (bool, error)) {+ buildPlanInlineFn = fn+}diff --git a/app/cli/lib/context_conflict.go b/app/cli/lib/context_conflict.gonew file mode 100644index 00000000..f96a2626--- /dev/null+++ b/app/cli/lib/context_conflict.go@@ -0,0 +1,48 @@+package lib++import (+ "fmt"+ "os"+ "plandex/api"+ "plandex/term"++ "github.com/fatih/color"+)++func checkContextConflicts(filesByPath map[string]string) (bool, error) {+ // log.Println("Checking for context conflicts.")+ // log.Println(spew.Sdump(filesByPath))++ currentPlan, err := api.Client.GetCurrentPlanState(CurrentPlanId, CurrentBranch)++ if err != nil {+ return false, fmt.Errorf("error getting current plan state: %v", err)+ }++ conflictedPaths := currentPlan.PlanResult.FileResultsByPath.ConflictedPaths(filesByPath)++ // log.Println("Conflicted paths:", conflictedPaths)++ if len(conflictedPaths) > 0 {+ term.StopSpinner()+ color.New(color.Bold, color.FgHiYellow).Println("β οΈ Some updates conflict with pending changes:")+ for path := range conflictedPaths {+ fmt.Println("π " + path)+ }++ fmt.Println()++ res, err := term.ConfirmYesNo("Update context and rebuild changes?")++ if err != nil {+ return false, fmt.Errorf("error confirming update and rebuild: %v", err)+ }++ if !res {+ fmt.Println("Context update canceled")+ os.Exit(0)+ }+ }++ return len(conflictedPaths) > 0, nil+}diff --git a/app/cli/lib/context_load.go b/app/cli/lib/context_load.goindex 50b31805..898bee84 100644--- a/app/cli/lib/context_load.go+++ b/app/cli/lib/context_load.go@@ -73,7 +73,6 @@ func MustLoadContext(resources []string, params *types.LoadContextParams) {ignoredPaths := make(map[string]string)if len(inputFilePaths) > 0 {-projectPaths := make(map[string]bool)var plandexIgnored *ignore.GitIgnore@@ -220,6 +219,19 @@ func MustLoadContext(resources []string, params *types.LoadContextParams) {}}+ filesToLoad := map[string]string{}+ for _, context := range loadContextReq {+ if context.ContextType == shared.ContextFileType {+ filesToLoad[context.FilePath] = context.Body+ }+ }++ hasConflicts, err := checkContextConflicts(filesToLoad)++ if err != nil {+ onErr(fmt.Errorf("failed to check context conflicts: %v", err))+ }+if len(loadContextReq) == 0 {term.StopSpinner()fmt.Println("π€·ββοΈ No context loaded")@@ -244,6 +256,17 @@ func MustLoadContext(resources []string, params *types.LoadContextParams) {os.Exit(1)}+ if hasConflicts {+ term.StartSpinner("ποΈ Starting build...")+ _, err := buildPlanInlineFn()++ if err != nil {+ onErr(fmt.Errorf("failed to build plan: %v", err))+ }++ fmt.Println()+ }+fmt.Println("β " + res.Msg)if len(ignoredPaths) > 0 {diff --git a/app/cli/lib/context_update.go b/app/cli/lib/context_update.goindex 5fe1f912..61ec5984 100644--- a/app/cli/lib/context_update.go+++ b/app/cli/lib/context_update.go@@ -18,8 +18,10 @@ import ("github.com/plandex/plandex/shared")-func MustCheckOutdatedContextWithOutput() {- term.StartSpinner("π¬ Checking context...")+func MustCheckOutdatedContext(quiet bool) {+ if !quiet {+ term.StartSpinner("π¬ Checking context...")+ }outdatedRes, err := CheckOutdatedContext()if err != nil {@@ -27,10 +29,14 @@ func MustCheckOutdatedContextWithOutput() {panic(fmt.Errorf("failed to check outdated context: %s", err))}- term.StopSpinner()+ if !quiet {+ term.StopSpinner()+ }if len(outdatedRes.UpdatedContexts) == 0 {- fmt.Println("β Context is up to date")+ if !quiet {+ fmt.Println("β Context is up to date")+ }return}types := []string{}@@ -90,7 +96,7 @@ func MustCheckOutdatedContextWithOutput() {}if confirmed {- MustUpdateContextWithOuput()+ MustUpdateContext()}if canceled {@@ -99,7 +105,7 @@ func MustCheckOutdatedContextWithOutput() {}-func MustUpdateContextWithOuput() {+func MustUpdateContext() {term.StartSpinner("π Updating context...")updateRes, err := UpdateContext()@@ -141,8 +147,10 @@ func checkOutdatedAndMaybeUpdateContext(doUpdate bool) (*types.ContextOutdatedRevar numTrees intvar mu sync.Mutexvar wg sync.WaitGroup+ contextsById := map[string]*shared.Context{}for _, context := range contexts {+ contextsById[context.Id] = contextif context.ContextType == shared.ContextFileType {wg.Add(1)@@ -259,19 +267,45 @@ func checkOutdatedAndMaybeUpdateContext(doUpdate bool) (*types.ContextOutdatedRe}var msg string+ var hasConflicts boolif len(req) == 0 {return &types.ContextOutdatedResult{Msg: "Context is up to date",}, nil} else if doUpdate {- res, err := api.Client.UpdateContext(CurrentPlanId, CurrentBranch, req)+ filesToLoad := map[string]string{}+ for id := range req {+ context := contextsById[id]+ if context.ContextType == shared.ContextFileType {+ filesToLoad[context.FilePath] = context.Body+ }+ }++ var err error+ hasConflicts, err = checkContextConflicts(filesToLoad)if err != nil {- return nil, fmt.Errorf("failed to update context: %v", err)+ return nil, fmt.Errorf("failed to check context conflicts: %v", err)+ }++ res, apiErr := api.Client.UpdateContext(CurrentPlanId, CurrentBranch, req)+ if apiErr != nil {+ return nil, fmt.Errorf("failed to update context: %v", apiErr)}msg = res.Msg}+ if hasConflicts {+ term.StartSpinner("ποΈ Starting build...")+ _, err := buildPlanInlineFn()++ if err != nil {+ return nil, fmt.Errorf("failed to build plan: %v", err)+ }++ fmt.Println()+ }+return &types.ContextOutdatedResult{Msg: msg,UpdatedContexts: updatedContexts,diff --git a/app/cli/main.go b/app/cli/main.goindex dea909d9..2f99a060 100644--- a/app/cli/main.go+++ b/app/cli/main.go@@ -9,10 +9,20 @@ import ("plandex/auth""plandex/cmd""plandex/fs"+ "plandex/lib"+ "plandex/plan_exec")func init() {+ // inter-package dependency injections to avoid circular importsauth.SetApiClient(api.Client)+ lib.SetBuildPlanInlineFn(func() (bool, error) {+ return plan_exec.Build(plan_exec.ExecParams{+ CurrentPlanId: lib.CurrentPlanId,+ CurrentBranch: lib.CurrentBranch,+ CheckOutdatedContext: func() { lib.MustCheckOutdatedContext(true) },+ }, false)+ })// set up a file logger// TODO: log rotationdiff --git a/app/cli/plan_exec/build.go b/app/cli/plan_exec/build.gonew file mode 100644index 00000000..49545fe9--- /dev/null+++ b/app/cli/plan_exec/build.go@@ -0,0 +1,76 @@+package plan_exec++import (+ "fmt"+ "os"+ "plandex/api"+ "plandex/fs"+ "plandex/stream"+ streamtui "plandex/stream_tui"+ "plandex/term"++ "github.com/fatih/color"+ "github.com/plandex/plandex/shared"+)++func Build(params ExecParams, buildBg bool) (bool, error) {+ params.CheckOutdatedContext()++ term.StartSpinner("ποΈ Starting build...")++ contexts, apiErr := api.Client.ListContext(params.CurrentPlanId, params.CurrentBranch)++ if apiErr != nil {+ color.New(color.FgRed).Fprintln(os.Stderr, "Error getting context:", apiErr)+ os.Exit(1)+ }++ projectPaths, _, err := fs.GetProjectPaths(fs.GetBaseDirForContexts(contexts))++ if err != nil {+ fmt.Fprintln(os.Stderr, "Error getting project paths:", err)+ return false, fmt.Errorf("error getting project paths: %v", err)+ }++ apiErr = api.Client.BuildPlan(params.CurrentPlanId, params.CurrentBranch, shared.BuildPlanRequest{+ ConnectStream: !buildBg,+ ProjectPaths: projectPaths,+ ApiKey: os.Getenv("OPENAI_API_KEY"),+ }, stream.OnStreamPlan)++ term.StopSpinner()++ if apiErr != nil {+ if apiErr.Msg == shared.NoBuildsErr {+ fmt.Println("π€·ββοΈ This plan has no pending changes to build")+ return false, nil+ }++ fmt.Fprintln(os.Stderr, "Error building plan:", apiErr.Msg)+ return false, fmt.Errorf("error building plan: %v", apiErr.Msg)+ }++ if !buildBg {+ ch := make(chan error)++ go func() {+ err := streamtui.StartStreamUI("", true)++ if err != nil {+ ch <- fmt.Errorf("error starting stream UI: %v", err)+ return+ }++ ch <- nil+ }()++ // Wait for the stream to finish+ err := <-ch++ if err != nil {+ return false, err+ }+ }++ return true, nil+}diff --git a/app/cli/plan_exec/params.go b/app/cli/plan_exec/params.gonew file mode 100644index 00000000..749e9021--- /dev/null+++ b/app/cli/plan_exec/params.go@@ -0,0 +1,7 @@+package plan_exec++type ExecParams struct {+ CurrentPlanId string+ CurrentBranch string+ CheckOutdatedContext func()+}diff --git a/app/cli/tell/tell.go b/app/cli/plan_exec/tell.gosimilarity index 84%rename from app/cli/tell/tell.gorename to app/cli/plan_exec/tell.goindex cf5fbbed..356a6290 100644--- a/app/cli/tell/tell.go+++ b/app/cli/plan_exec/tell.go@@ -1,4 +1,4 @@-package tell+package plan_execimport ("fmt"@@ -7,7 +7,6 @@ import ("plandex/api""plandex/auth""plandex/fs"- "plandex/lib""plandex/stream"streamtui "plandex/stream_tui""plandex/term"@@ -16,8 +15,17 @@ import ("github.com/plandex/plandex/shared")-func TellPlan(prompt string, tellBg, tellStop, tellNoBuild, isUserContinue bool) {- contexts, apiErr := api.Client.ListContext(lib.CurrentPlanId, lib.CurrentBranch)+func TellPlan(+ params ExecParams,+ prompt string,+ tellBg,+ tellStop,+ tellNoBuild,+ isUserContinue bool,+) {+ params.CheckOutdatedContext()++ contexts, apiErr := api.Client.ListContext(params.CurrentPlanId, params.CurrentBranch)if apiErr != nil {color.New(color.FgRed).Fprintln(os.Stderr, "Error getting context:", apiErr)@@ -41,9 +49,13 @@ func TellPlan(prompt string, tellBg, tellStop, tellNoBuild, isUserContinue bool)buildMode = shared.BuildModeAuto}- term.StartSpinner("π¬ Sending prompt...")+ if isUserContinue {+ term.StartSpinner("β‘οΈ Continuing plan...")+ } else {+ term.StartSpinner("π¬ Sending prompt...")+ }- apiErr := api.Client.TellPlan(lib.CurrentPlanId, lib.CurrentBranch, shared.TellPlanRequest{+ apiErr := api.Client.TellPlan(params.CurrentPlanId, params.CurrentBranch, shared.TellPlanRequest{Prompt: prompt,ConnectStream: !tellBg,AutoContinue: !tellStop,@@ -57,8 +69,6 @@ func TellPlan(prompt string, tellBg, tellStop, tellNoBuild, isUserContinue bool)if apiErr != nil {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.MaxReplies)res, err := term.ConfirmYesNo("Upgrade now?")diff --git a/app/cli/stream_tui/model.go b/app/cli/stream_tui/model.goindex f14decb2..feab0353 100644--- a/app/cli/stream_tui/model.go+++ b/app/cli/stream_tui/model.go@@ -98,7 +98,7 @@ func initialModel(prestartReply, prompt string, buildOnly bool) *streamUIModel {reply: prestartReply,keymap: keymap{quit: bubbleKey.NewBinding(- bubbleKey.WithKeys("ctrl+c"),+ bubbleKey.WithKeys("b", "ctrl+c", "esc"),bubbleKey.WithHelp("ctrl+c", "quit"),),diff --git a/app/cli/stream_tui/view.go b/app/cli/stream_tui/view.goindex fd901c0e..901023f8 100644--- a/app/cli/stream_tui/view.go+++ b/app/cli/stream_tui/view.go@@ -40,9 +40,9 @@ func (m streamUIModel) renderHelp() string {style := lipgloss.NewStyle().Width(m.width).Foreground(lipgloss.Color(helpTextColor)).BorderStyle(lipgloss.NormalBorder()).BorderTop(true).BorderForeground(lipgloss.Color(borderColor))if m.buildOnly {- return style.Render(" (s)top")+ return style.Render(" (s)top β’ (b)ackground")} else {- return style.Render(" (s)top β’ (j/k) scroll β’ (d/u) page β’ (g/G) start/end")+ return style.Render(" (s)top β’ (b)ackground β’ (j/k) scroll β’ (d/u) page β’ (g/G) start/end")}}diff --git a/app/cli/term/prompt.go b/app/cli/term/prompt.gonew file mode 100644index 00000000..1140e820--- /dev/null+++ b/app/cli/term/prompt.go@@ -0,0 +1,78 @@+package term++import (+ "fmt"++ "github.com/cqroot/prompt"+ "github.com/cqroot/prompt/input"+ "github.com/eiannone/keyboard"+ "github.com/fatih/color"+)++func GetUserStringInput(msg string) (string, error) {+ return prompt.New().Ask(msg).Input("")+}++func GetUserPasswordInput(msg string) (string, error) {+ return prompt.New().Ask(msg).Input("", input.WithEchoMode(input.EchoPassword))+}++func GetUserKeyInput() (rune, error) {+ if err := keyboard.Open(); err != nil {+ return 0, fmt.Errorf("failed to open keyboard: %s", err)+ }+ defer func() {+ _ = keyboard.Close()+ }()++ char, _, err := keyboard.GetKey()+ if err != nil {+ return 0, fmt.Errorf("failed to read keypress: %s", err)+ }++ return char, nil+}++func ConfirmYesNo(fmtStr string, fmtArgs ...interface{}) (bool, error) {+ color.New(color.FgHiMagenta, color.Bold).Printf(fmtStr+" (y)es | (n)o", fmtArgs...)+ color.New(color.FgHiMagenta, color.Bold).Print("> ")++ char, err := GetUserKeyInput()+ if err != nil {+ return false, fmt.Errorf("failed to get user input: %s", err)+ }++ fmt.Println(string(char))+ if char == 'y' || char == 'Y' {+ return true, nil+ } else if char == 'n' || char == 'N' {+ return false, nil+ } else {+ fmt.Println()+ color.New(color.FgHiRed, color.Bold).Print("Invalid input.\nEnter 'y' for yes or 'n' for no.\n\n")+ return ConfirmYesNo(fmtStr, fmtArgs...)+ }+}++func ConfirmYesNoCancel(fmtStr string, fmtArgs ...interface{}) (bool, bool, error) {+ color.New(color.FgHiMagenta, color.Bold).Printf(fmtStr+" (y)es | (n)o | (c)ancel", fmtArgs...)+ color.New(color.FgHiMagenta, color.Bold).Print("> ")++ char, err := GetUserKeyInput()+ if err != nil {+ return false, false, fmt.Errorf("failed to get user input: %s", err)+ }++ fmt.Println(string(char))+ if char == 'y' || char == 'Y' {+ return true, false, nil+ } else if char == 'n' || char == 'N' {+ return false, false, nil+ } else if char == 'c' || char == 'C' {+ return false, true, nil+ } else {+ fmt.Println()+ color.New(color.FgHiRed, color.Bold).Print("Invalid input.\nEnter 'y' for yes, 'n' for no, or 'c' for cancel.\n\n")+ return ConfirmYesNoCancel(fmtStr, fmtArgs...)+ }+}diff --git a/app/cli/term/spinner.go b/app/cli/term/spinner.goindex 77ee8c6a..f7f24428 100644--- a/app/cli/term/spinner.go+++ b/app/cli/term/spinner.go@@ -11,10 +11,23 @@ const minDuration = 700 * time.Millisecondvar s = spinner.New(spinner.CharSets[33], 100*time.Millisecond)var startedAt time.Time+var lastMessage string+var active bool+func StartSpinner(msg string) {+ if active {+ if msg == lastMessage {+ return+ }++ s.Stop()+ }+startedAt = time.Now()s.Prefix = msg + " "+ lastMessage = msgs.Start()+ active = true}func StopSpinner() {@@ -25,4 +38,12 @@ func StopSpinner() {s.Stop()ClearCurrentLine()++ active = false+}++func ResumeSpinner() {+ if !active {+ StartSpinner(lastMessage)+ }}diff --git a/app/cli/term/term.go b/app/cli/term/term.goindex c428e088..cf53867f 100644--- a/app/cli/term/term.go+++ b/app/cli/term/term.go@@ -6,12 +6,8 @@ import ("os/exec""strings"- "github.com/eiannone/keyboard""github.com/fatih/color""golang.org/x/term"-- "github.com/cqroot/prompt"- "github.com/cqroot/prompt/input")var CmdDesc = map[string][2]string{@@ -131,74 +127,6 @@ func PageOutputReverse(output string) {}}-func GetUserStringInput(msg string) (string, error) {- return prompt.New().Ask(msg).Input("")-}--func GetUserPasswordInput(msg string) (string, error) {- return prompt.New().Ask(msg).Input("", input.WithEchoMode(input.EchoPassword))-}--func GetUserKeyInput() (rune, error) {- if err := keyboard.Open(); err != nil {- return 0, fmt.Errorf("failed to open keyboard: %s", err)- }- defer func() {- _ = keyboard.Close()- }()-- char, _, err := keyboard.GetKey()- if err != nil {- return 0, fmt.Errorf("failed to read keypress: %s", err)- }-- return char, nil-}--func ConfirmYesNo(fmtStr string, fmtArgs ...interface{}) (bool, error) {- color.New(color.FgHiMagenta, color.Bold).Printf(fmtStr+" (y)es | (n)o", fmtArgs...)- color.New(color.FgHiMagenta, color.Bold).Print("> ")-- char, err := GetUserKeyInput()- if err != nil {- return false, fmt.Errorf("failed to get user input: %s", err)- }-- fmt.Println(string(char))- if char == 'y' || char == 'Y' {- return true, nil- } else if char == 'n' || char == 'N' {- return false, nil- } else {- fmt.Println()- color.New(color.FgHiRed, color.Bold).Print("Invalid input.\nEnter 'y' for yes or 'n' for no.\n\n")- return ConfirmYesNo(fmtStr, fmtArgs...)- }-}--func ConfirmYesNoCancel(fmtStr string, fmtArgs ...interface{}) (bool, bool, error) {- color.New(color.FgHiMagenta, color.Bold).Printf(fmtStr+" (y)es | (n)o | (c)ancel", fmtArgs...)- color.New(color.FgHiMagenta, color.Bold).Print("> ")-- char, err := GetUserKeyInput()- if err != nil {- return false, false, fmt.Errorf("failed to get user input: %s", err)- }-- fmt.Println(string(char))- if char == 'y' || char == 'Y' {- return true, false, nil- } else if char == 'n' || char == 'N' {- return false, false, nil- } else if char == 'c' || char == 'C' {- return false, true, nil- } else {- fmt.Println()- color.New(color.FgHiRed, color.Bold).Print("Invalid input.\nEnter 'y' for yes, 'n' for no, or 'c' for cancel.\n\n")- return ConfirmYesNoCancel(fmtStr, fmtArgs...)- }-}-func GetDivisionLine() string {// Get the terminal widthterminalWidth, err := getTerminalWidth()diff --git a/app/server/db/context_helpers.go b/app/server/db/context_helpers.goindex 7268ac95..c9bdf54a 100644--- a/app/server/db/context_helpers.go+++ b/app/server/db/context_helpers.go@@ -184,6 +184,17 @@ func LoadContexts(params LoadContextsParams) (*shared.LoadContextResponse, []*CobranchName := params.BranchNameuserId := params.UserId+ filesToLoad := map[string]string{}+ for _, context := range *req {+ if context.ContextType == shared.ContextFileType {+ filesToLoad[context.FilePath] = context.Body+ }+ }+ err := invalidateConflictedResults(orgId, planId, filesToLoad)+ if err != nil {+ return nil, nil, fmt.Errorf("error invalidating conflicted results: %v", err)+ }+tokensAdded := 0paramsByTempId := make(map[string]*shared.LoadContextParams)@@ -392,6 +403,13 @@ func UpdateContexts(params UpdateContextsParams) (*shared.UpdateContextResponse,}(id, params)}+ for i := 0; i < len(*req); i++ {+ err := <-errCh+ if err != nil {+ return nil, fmt.Errorf("error getting context: %v", err)+ }+ }+updateRes := &shared.ContextUpdateResult{UpdatedContexts: updatedContexts,TokenDiffsById: tokenDiffsById,@@ -412,15 +430,18 @@ func UpdateContexts(params UpdateContextsParams) (*shared.UpdateContextResponse,}, nil}- for i := 0; i < len(*req); i++ {- err := <-errCh- if err != nil {- return nil, fmt.Errorf("error getting context: %v", err)+ filesToLoad := map[string]string{}+ for _, context := range updatedContexts {+ if context.ContextType == shared.ContextFileType {+ filesToLoad[context.FilePath] = (*req)[context.Id].Body}}+ err = invalidateConflictedResults(orgId, planId, filesToLoad)+ if err != nil {+ return nil, fmt.Errorf("error invalidating conflicted results: %v", err)+ }errCh = make(chan error)- dbContextsCh := make(chan *Context)for id, params := range *req {go func(id string, params *shared.UpdateContextParams) {@@ -440,17 +461,14 @@ func UpdateContexts(params UpdateContextsParams) (*shared.UpdateContextResponse,return}- dbContextsCh <- context+ errCh <- nil}(id, params)}- var dbContexts []*Contextfor i := 0; i < len(*req); i++ {- select {- case err := <-errCh:+ err := <-errCh+ if err != nil {return nil, fmt.Errorf("error storing context: %v", err)- case dbContext := <-dbContextsCh:- dbContexts = append(dbContexts, dbContext)}}@@ -467,3 +485,80 @@ func UpdateContexts(params UpdateContextsParams) (*shared.UpdateContextResponse,Msg: commitMsg,}, nil}++func invalidateConflictedResults(orgId, planId string, filesToLoad map[string]string) error {+ descriptions, err := GetConvoMessageDescriptions(orgId, planId)+ if err != nil {+ return fmt.Errorf("error getting pending build descriptions: %v", err)+ }++ currentPlan, err := GetCurrentPlanState(CurrentPlanStateParams{+ OrgId: orgId,+ PlanId: planId,+ ConvoMessageDescriptions: descriptions,+ })++ if err != nil {+ return fmt.Errorf("error getting current plan state: %v", err)+ }++ conflictPaths := currentPlan.PlanResult.FileResultsByPath.ConflictedPaths(filesToLoad)++ // log.Println("invalidateConflictedResults - Conflicted paths:", conflictPaths)++ if len(conflictPaths) > 0 {+ errCh := make(chan error)+ numRoutines := 0++ for _, desc := range descriptions {+ if !desc.DidBuild || desc.AppliedAt != nil {+ continue+ }++ for _, path := range desc.Files {+ if _, found := conflictPaths[path]; found {+ if desc.BuildPathsInvalidated == nil {+ desc.BuildPathsInvalidated = make(map[string]bool)+ }+ desc.BuildPathsInvalidated[path] = true++ // log.Printf("Invalidating build for path: %s, desc: %s\n", path, desc.Id)++ go func(desc *ConvoMessageDescription) {+ err := StoreDescription(desc)++ if err != nil {+ errCh <- fmt.Errorf("error storing description: %v", err)+ return+ }++ errCh <- nil+ }(desc)++ numRoutines+++ }+ }+ }++ go func() {+ err := DeletePendingResultsForPaths(orgId, planId, conflictPaths)++ if err != nil {+ errCh <- fmt.Errorf("error deleting pending results: %v", err)+ return+ }++ errCh <- nil+ }()+ numRoutines++++ for i := 0; i < numRoutines; i++ {+ err := <-errCh+ if err != nil {+ return fmt.Errorf("error storing description: %v", err)+ }+ }+ }++ return nil+}diff --git a/app/server/db/data_models.go b/app/server/db/data_models.goindex 4f3cf50c..007aa13f 100644--- a/app/server/db/data_models.go+++ b/app/server/db/data_models.go@@ -21,14 +21,15 @@ type AuthToken struct {}type Org struct {- Id string `db:"id"`- Name string `db:"name"`- Domain *string `db:"domain"`- AutoAddDomainUsers bool `db:"auto_add_domain_users"`- OwnerId string `db:"owner_id"`- IsTrial bool `db:"is_trial"`- CreatedAt time.Time `db:"created_at"`- UpdatedAt time.Time `db:"updated_at"`+ Id string `db:"id"`+ Name string `db:"name"`+ Domain *string `db:"domain"`+ AutoAddDomainUsers bool `db:"auto_add_domain_users"`+ OwnerId string `db:"owner_id"`+ IsTrial bool `db:"is_trial"`++ CreatedAt time.Time `db:"created_at"`+ UpdatedAt time.Time `db:"updated_at"`}func (org *Org) ToApi() *shared.Org {@@ -355,19 +356,20 @@ func (msg *ConvoMessage) ToApi() *shared.ConvoMessage {}type ConvoMessageDescription struct {- Id string `json:"id"`- OrgId string `json:"orgId"`- PlanId string `json:"planId"`- ConvoMessageId string `json:"convoMessageId"`- SummarizedToMessageId string `json:"summarizedToMessageId"`- MadePlan bool `json:"madePlan"`- CommitMsg string `json:"commitMsg"`- Files []string `json:"files"`- Error string `json:"error"`- DidBuild bool `json:"didBuild"`- AppliedAt *time.Time `json:"appliedAt,omitempty"`- CreatedAt time.Time `json:"createdAt"`- UpdatedAt time.Time `json:"updatedAt"`+ Id string `json:"id"`+ OrgId string `json:"orgId"`+ PlanId string `json:"planId"`+ ConvoMessageId string `json:"convoMessageId"`+ SummarizedToMessageId string `json:"summarizedToMessageId"`+ MadePlan bool `json:"madePlan"`+ CommitMsg string `json:"commitMsg"`+ Files []string `json:"files"`+ Error string `json:"error"`+ DidBuild bool `json:"didBuild"`+ BuildPathsInvalidated map[string]bool `json:"buildPathsInvalidated"`+ AppliedAt *time.Time `json:"appliedAt,omitempty"`+ CreatedAt time.Time `json:"createdAt"`+ UpdatedAt time.Time `json:"updatedAt"`}func (desc *ConvoMessageDescription) ToApi() *shared.ConvoMessageDescription {@@ -379,6 +381,7 @@ func (desc *ConvoMessageDescription) ToApi() *shared.ConvoMessageDescription {CommitMsg: desc.CommitMsg,Files: desc.Files,DidBuild: desc.DidBuild,+ BuildPathsInvalidated: desc.BuildPathsInvalidated,Error: desc.Error,CreatedAt: desc.CreatedAt,UpdatedAt: desc.UpdatedAt,@@ -392,8 +395,6 @@ type PlanFileResult struct {ConvoMessageId string `json:"convoMessageId"`PlanBuildId string `json:"planBuildId"`Path string `json:"path"`- ContextSha string `json:"contextSha"`- ContextBody string `json:"contextBody"`Content string `json:"content,omitempty"`Replacements []*shared.Replacement `json:"replacements"`AnyFailed bool `json:"anyFailed"`@@ -410,8 +411,6 @@ func (res *PlanFileResult) ToApi() *shared.PlanFileResult {PlanBuildId: res.PlanBuildId,ConvoMessageId: res.ConvoMessageId,Path: res.Path,- ContextSha: res.ContextSha,- ContextBody: res.ContextBody,Content: res.Content,AnyFailed: res.AnyFailed,AppliedAt: res.AppliedAt,diff --git a/app/server/db/result_helpers.go b/app/server/db/result_helpers.goindex 2300e7a5..aa2db100 100644--- a/app/server/db/result_helpers.go+++ b/app/server/db/result_helpers.go@@ -3,6 +3,7 @@ package dbimport ("encoding/json""fmt"+ "log""os""path/filepath""sort"@@ -50,6 +51,7 @@ type CurrentPlanStateParams struct {PlanId stringPlanFileResults []*PlanFileResultConvoMessageDescriptions []*ConvoMessageDescription+ Contexts []*Context}func GetCurrentPlanState(params CurrentPlanStateParams) (*shared.CurrentPlanState, error) {@@ -58,6 +60,7 @@ func GetCurrentPlanState(params CurrentPlanStateParams) (*shared.CurrentPlanStatvar dbPlanFileResults []*PlanFileResultvar convoMessageDescriptions []*shared.ConvoMessageDescription+ contextsByPath := map[string]*Context{}errCh := make(chan error)@@ -97,7 +100,29 @@ func GetCurrentPlanState(params CurrentPlanStateParams) (*shared.CurrentPlanStaterrCh <- nil}()- for i := 0; i < 2; i++ {+ go func() {+ var contexts []*Context+ if params.Contexts == nil {+ res, err := GetPlanContexts(orgId, planId, true)+ if err != nil {+ errCh <- fmt.Errorf("error getting contexts: %v", err)+ return+ }+ contexts = res+ } else {+ contexts = params.Contexts+ }++ for _, context := range contexts {+ if context.FilePath != "" {+ contextsByPath[context.FilePath] = context+ }+ }++ errCh <- nil+ }()++ for i := 0; i < 3; i++ {err := <-errChif err != nil {return nil, err@@ -105,15 +130,29 @@ func GetCurrentPlanState(params CurrentPlanStateParams) (*shared.CurrentPlanStat}var apiPlanFileResults []*shared.PlanFileResult+ pendingResultPaths := map[string]bool{}for _, dbPlanFileResult := range dbPlanFileResults {- apiPlanFileResults = append(apiPlanFileResults, dbPlanFileResult.ToApi())+ apiResult := dbPlanFileResult.ToApi()+ apiPlanFileResults = append(apiPlanFileResults, apiResult)++ if apiResult.IsPending() {+ pendingResultPaths[apiResult.Path] = true+ }}planResult := GetPlanResult(apiPlanFileResults)+ pendingContextsByPath := map[string]*shared.Context{}+ for path, context := range contextsByPath {+ if pendingResultPaths[path] {+ pendingContextsByPath[path] = context.ToApi()+ }+ }+planState := &shared.CurrentPlanState{PlanResult: planResult,ConvoMessageDescriptions: convoMessageDescriptions,+ ContextsByPath: pendingContextsByPath,}currentPlanFiles, err := planState.GetFiles()@@ -549,6 +588,67 @@ func RejectAllResults(orgId, planId string) error {return nil}+func DeletePendingResultsForPaths(orgId, planId string, paths map[string]bool) error {+ // log.Println("Deleting pending results for paths")+ resultsDir := getPlanResultsDir(orgId, planId)+ files, err := os.ReadDir(resultsDir)++ if err != nil {+ if os.IsNotExist(err) {+ return nil+ }++ return fmt.Errorf("error reading results dir: %v", err)+ }++ errCh := make(chan error, len(files))++ for _, file := range files {+ resultId := strings.TrimSuffix(file.Name(), ".json")++ go func(resultId string) {+ bytes, err := os.ReadFile(filepath.Join(resultsDir, resultId+".json"))++ if err != nil {+ errCh <- fmt.Errorf("error reading result file: %v", err)+ return+ }++ var result PlanFileResult+ err = json.Unmarshal(bytes, &result)++ if err != nil {+ errCh <- fmt.Errorf("error unmarshalling result file: %v", err)+ return+ }++ // log.Printf("Checking pending result: %s", resultId)++ if result.ToApi().IsPending() && paths[result.Path] {+ log.Printf("Deleting pending result: %s", resultId)++ err = os.Remove(filepath.Join(resultsDir, resultId+".json"))++ if err != nil {+ errCh <- fmt.Errorf("error deleting result file: %v", err)+ return+ }+ }++ errCh <- nil+ }(resultId)+ }++ for i := 0; i < len(files); i++ {+ err := <-errCh+ if err != nil {+ return fmt.Errorf("error deleting pending results: %v", err)+ }+ }++ return nil+}+func RejectPlanFileResult(orgId, planId, resultId string, now time.Time) error {resultsDir := getPlanResultsDir(orgId, planId)diff --git a/app/server/model/plan/build_exec.go b/app/server/model/plan/build_exec.goindex e27c63a0..2ccf6df2 100644--- a/app/server/model/plan/build_exec.go+++ b/app/server/model/plan/build_exec.go@@ -11,7 +11,12 @@ import ("github.com/sashabaranov/go-openai")-func Build(client *openai.Client, plan *db.Plan, branch string, auth *types.ServerAuth) (int, error) {+func Build(+ client *openai.Client,+ plan *db.Plan,+ branch string,+ auth *types.ServerAuth,+) (int, error) {log.Printf("Build: Called with plan ID %s on branch %s\n", plan.Id, branch)log.Println("Build: Starting Build operation")@@ -24,11 +29,16 @@ func Build(client *openai.Client, plan *db.Plan, branch string, auth *types.Servbranch: branch,}- active := GetActivePlan(plan.Id, branch)+ streamDone := func() {+ active := GetActivePlan(plan.Id, branch)+ if active != nil {+ active.StreamDoneCh <- nil+ }+ }onErr := func(err error) (int, error) {log.Printf("Build error: %v\n", err)- active.StreamDoneCh <- nil+ streamDone()return 0, err}@@ -39,7 +49,7 @@ func Build(client *openai.Client, plan *db.Plan, branch string, auth *types.Servif len(pendingBuildsByPath) == 0 {log.Println("No pending builds")- active.StreamDoneCh <- nil+ streamDone()return 0, nil}@@ -157,24 +167,9 @@ func (fileState *activeBuildStreamFileState) buildFile() {if fileInCurrentPlan {log.Printf("File %s found in current plan.\n", filePath)- if contextPart == nil {- log.Println("No context - using current plan state.")- currentState = currentPlanFile- } else {- currentFileUpdatedAt := currentPlan.CurrentPlanFiles.UpdatedAtByPath[filePath]- contextFileUpdatedAt := contextPart.UpdatedAt-- if currentFileUpdatedAt.After(contextFileUpdatedAt) {- log.Println("Current plan file is newer than context. Using current plan state.")- currentState = currentPlanFile- } else {- log.Println("Context is newer than current plan file. Using context state.")- currentState = contextPart.Body- }- }+ currentState = currentPlanFile} else if contextPart != nil {log.Printf("File %s found in model context. Using context state.\n", filePath)-currentState = contextPart.Bodyif currentState == "" {@@ -183,7 +178,6 @@ func (fileState *activeBuildStreamFileState) buildFile() {}fileState.currentState = currentState- fileState.contextPart = contextPartif currentState == "" {log.Printf("File %s not found in model context or current plan. Creating new file.\n", filePath)diff --git a/app/server/model/plan/build_finish.go b/app/server/model/plan/build_finish.goindex 7c5e9caa..cacdb6a1 100644--- a/app/server/model/plan/build_finish.go+++ b/app/server/model/plan/build_finish.go@@ -100,7 +100,7 @@ func (state *activeBuildStreamFileState) onFinishBuild() {var unbuiltDescs []*db.ConvoMessageDescriptionfor _, desc := range planDescs {- if !desc.DidBuild {+ if !desc.DidBuild || len(desc.BuildPathsInvalidated) > 0 {unbuiltDescs = append(unbuiltDescs, desc)}}@@ -121,6 +121,7 @@ func (state *activeBuildStreamFileState) onFinishBuild() {for _, desc := range unbuiltDescs {if len(desc.Files) > 0 {desc.DidBuild = true+ desc.BuildPathsInvalidated = map[string]bool{}}go func(desc *db.ConvoMessageDescription) {diff --git a/app/server/model/plan/build_result.go b/app/server/model/plan/build_result.goindex fd176626..5cb647d5 100644--- a/app/server/model/plan/build_result.go+++ b/app/server/model/plan/build_result.go@@ -17,7 +17,6 @@ type planResultParams struct {convoMessageId stringfilePath stringcurrentState string- context *db.ContextfileContent stringstreamedReplacements []*types.StreamedReplacement}@@ -28,7 +27,6 @@ func getPlanResult(params planResultParams) (*db.PlanFileResult, bool) {planBuildId := params.planBuildIdfilePath := params.filePathcurrentState := params.currentState- contextPart := params.contextstreamedReplacements := params.streamedReplacementsupdated := params.currentStatefileContent := params.fileContent@@ -70,13 +68,6 @@ func getPlanResult(params planResultParams) (*db.PlanFileResult, bool) {_, allSucceeded := shared.ApplyReplacements(currentState, replacements, true)- var contextSha string- var contextBody string- if contextPart != nil {- contextSha = contextPart.Sha- contextBody = contextPart.Body- }-for _, replacement := range replacements {id := uuid.New().String()replacement.Id = id@@ -90,8 +81,6 @@ func getPlanResult(params planResultParams) (*db.PlanFileResult, bool) {Content: "",Path: filePath,Replacements: replacements,- ContextSha: contextSha,- ContextBody: contextBody,AnyFailed: !allSucceeded,}, allSucceeded}diff --git a/app/server/model/plan/build_stream.go b/app/server/model/plan/build_stream.goindex db7d033d..172dbfae 100644--- a/app/server/model/plan/build_stream.go+++ b/app/server/model/plan/build_stream.go@@ -34,7 +34,6 @@ type activeBuildStreamFileState struct {currentPlanState *shared.CurrentPlanStateactiveBuild *types.ActiveBuildbuffer string- contextPart *db.ContextcurrentState string}@@ -45,7 +44,6 @@ func (fileState *activeBuildStreamFileState) listenStream(stream *openai.ChatComplanId := fileState.plan.Idbranch := fileState.branchcurrentState := fileState.currentState- contextPart := fileState.contextPartactiveBuild := fileState.activeBuildactivePlan := GetActivePlan(planId, branch)@@ -127,7 +125,6 @@ func (fileState *activeBuildStreamFileState) listenStream(stream *openai.ChatComconvoMessageId: build.ConvoMessageId,filePath: filePath,currentState: currentState,- context: contextPart,fileContent: activeBuild.FileContent,streamedReplacements: streamed.Replacements,},diff --git a/app/server/model/plan/tell_stream.go b/app/server/model/plan/tell_stream.goindex 05b45fcd..437e589a 100644--- a/app/server/model/plan/tell_stream.go+++ b/app/server/model/plan/tell_stream.go@@ -209,6 +209,7 @@ func (state *activeTellStreamState) listenStream(stream *openai.ChatCompletionStPlanId: planId,ConvoMessageId: assistantMsg.Id,SummarizedToMessageId: summarizedToMessageId,+ BuildPathsInvalidated: map[string]bool{},MadePlan: false,}} else {@@ -578,6 +579,7 @@ func (state *activeTellStreamState) onError(streamErr error, storeDesc bool, conSummarizedToMessageId: summarizedToMessageId,MadePlan: false,ConvoMessageId: convoMessageId,+ BuildPathsInvalidated: map[string]bool{},Error: streamErr.Error(),})if err == nil {diff --git a/app/server/types/active_plan_pending_builds.go b/app/server/types/active_plan_pending_builds.goindex 672b2ca9..02468c9a 100644--- a/app/server/types/active_plan_pending_builds.go+++ b/app/server/types/active_plan_pending_builds.go@@ -36,7 +36,7 @@ func (ap *ActivePlan) PendingBuildsByPath(orgId, userId string, convoMessagesArgactiveBuildsByPath := map[string][]*ActiveBuild{}for _, desc := range planDescs {- if !desc.DidBuild && len(desc.Files) > 0 {+ if (!desc.DidBuild && len(desc.Files) > 0) || len(desc.BuildPathsInvalidated) > 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)@@ -54,6 +54,11 @@ func (ap *ActivePlan) PendingBuildsByPath(orgId, userId string, convoMessagesArgparserRes := replyParser.FinishAndRead()for i, file := range desc.Files {++ if desc.DidBuild && !desc.BuildPathsInvalidated[file] {+ continue+ }+if activeBuildsByPath[file] == nil {activeBuildsByPath[file] = []*ActiveBuild{}}diff --git a/app/shared/data_models.go b/app/shared/data_models.goindex aa88db5b..a6168546 100644--- a/app/shared/data_models.go+++ b/app/shared/data_models.go@@ -113,17 +113,18 @@ type ConvoSummary struct {}type ConvoMessageDescription struct {- Id string `json:"id"`- ConvoMessageId string `json:"convoMessageId"`- SummarizedToMessageId string `json:"summarizedToMessageId"`- MadePlan bool `json:"madePlan"`- CommitMsg string `json:"commitMsg"`- Files []string `json:"files"`- DidBuild bool `json:"didBuild"`- Error string `json:"error"`- AppliedAt *time.Time `json:"appliedAt,omitempty"`- CreatedAt time.Time `json:"createdAt"`- UpdatedAt time.Time `json:"updatedAt"`+ Id string `json:"id"`+ ConvoMessageId string `json:"convoMessageId"`+ SummarizedToMessageId string `json:"summarizedToMessageId"`+ MadePlan bool `json:"madePlan"`+ CommitMsg string `json:"commitMsg"`+ Files []string `json:"files"`+ DidBuild bool `json:"didBuild"`+ BuildPathsInvalidated map[string]bool `json:"buildPathsInvalidated"`+ Error string `json:"error"`+ AppliedAt *time.Time `json:"appliedAt,omitempty"`+ CreatedAt time.Time `json:"createdAt"`+ UpdatedAt time.Time `json:"updatedAt"`}type PlanBuild struct {@@ -149,8 +150,6 @@ type PlanFileResult struct {ConvoMessageId string `json:"convoMessageId"`PlanBuildId string `json:"planBuildId"`Path string `json:"path"`- ContextBody string `json:"contextBody"`- ContextSha string `json:"contextSha"`Content string `json:"content"`AnyFailed bool `json:"anyFailed"`AppliedAt *time.Time `json:"appliedAt,omitempty"`@@ -162,7 +161,6 @@ type PlanFileResult struct {type CurrentPlanFiles struct {Files map[string]string `json:"files"`- ContextShas map[string]string `json:"contextShas"`UpdatedAtByPath map[string]time.Time `json:"updatedAtByPath"`}@@ -179,6 +177,7 @@ type CurrentPlanState struct {PlanResult *PlanResult `json:"planResult"`CurrentPlanFiles *CurrentPlanFiles `json:"currentPlanFiles"`ConvoMessageDescriptions []*ConvoMessageDescription `json:"convoMessageDescriptions"`+ ContextsByPath map[string]*Context `json:"contextsByPath"`}type OrgRole struct {diff --git a/app/shared/plan_result.go b/app/shared/plan_result.goindex 510f2ac2..dfbe127d 100644--- a/app/shared/plan_result.go+++ b/app/shared/plan_result.go@@ -1,6 +1,7 @@package sharedimport (+ "log""time")@@ -67,12 +68,50 @@ func (p PlanFileResultsByPath) NumPending() int {return numPending}-func (p PlanFileResultsByPath) OriginalContextForPath(path string) string {- planResults := p[path]- if len(planResults) == 0 {- return ""+func (p PlanFileResultsByPath) ConflictedPaths(filesByPath map[string]string) map[string]bool {+ conflictedPaths := map[string]bool{}++ for path, body := range filesByPath {+ planRes := p[path]++ // log.Println("Checking for conflicts in path:", path)+ // log.Println("Body:")+ // log.Println(body)++ if planRes == nil {+ continue+ }++ updated := body++ noConflicts := true+ for _, res := range planRes {++ log.Println("res:", res.Id)+ if len(res.Replacements) == 0 {+ continue+ }++ var succeeded bool+ updated, succeeded = ApplyReplacements(updated, res.Replacements, false)++ // log.Println("updated:", updated)+ // log.Println("succeeded:", succeeded)++ if !succeeded {+ noConflicts = false+ break+ }+ }++ // log.Println("No conflicts:", noConflicts)++ if !noConflicts {+ conflictedPaths[path] = true+ }}- return planResults[0].ContextBody++ return conflictedPaths}func (r PlanResult) NumPendingForPath(path string) int {@@ -88,7 +127,7 @@ func (r PlanResult) NumPendingForPath(path string) int {func (desc *ConvoMessageDescription) NumBuildsPendingByPath() map[string]int {res := map[string]int{}- if !desc.DidBuild && len(desc.Files) > 0 {+ if (!desc.DidBuild && len(desc.Files) > 0) || len(desc.BuildPathsInvalidated) > 0 {for _, file := range desc.Files {res[file]++}diff --git a/app/shared/plan_result_pending_summary.go b/app/shared/plan_result_pending_summary.goindex eca3c14e..4bf82ba8 100644--- a/app/shared/plan_result_pending_summary.go+++ b/app/shared/plan_result_pending_summary.go@@ -10,8 +10,6 @@ import (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 == "" {@@ -56,7 +54,7 @@ func (state *CurrentPlanState) PendingChangesSummary() string {for _, convoMessageId := range uniqueConvoIds {if desc, ok := descByConvoMessageId[convoMessageId]; ok {- if !ch.descsSet[convoMessageId] && !desc.DidBuild {+ if !ch.descsSet[convoMessageId] && (!desc.DidBuild || len(desc.BuildPathsInvalidated) > 0) {ch.descs = append(ch.descs, desc)ch.descsSet[convoMessageId] = true}@@ -82,6 +80,36 @@ func (state *CurrentPlanState) PendingChangesSummary() string {return sortedChangesets[i].descs[0].CreatedAt.Before(sortedChangesets[j].descs[0].CreatedAt)})+ isRebuild := true+ rebuildPathsSet := make(map[string]bool)+ for _, ch := range sortedChangesets {+ allRebuild := true+ for _, desc := range ch.descs {+ if len(desc.BuildPathsInvalidated) == 0 {+ allRebuild = false+ break+ } else {+ for path := range desc.BuildPathsInvalidated {+ rebuildPathsSet[path] = true+ }+ }+ }+ if !allRebuild {+ isRebuild = false+ break+ }+ }++ if isRebuild {+ msgs = append(msgs, "ποΈ Rebuild paths invalidated by context update")+ for path := range rebuildPathsSet {+ msgs = append(msgs, fmt.Sprintf(" β’ rebuild β %s", path))+ }+ return strings.Join(msgs, "\n")+ }++ msgs = append(msgs, "ποΈ Build pending changes")+for _, ch := range sortedChangesets {var descMsgs []stringdiff --git a/app/shared/plan_result_replacements.go b/app/shared/plan_result_replacements.goindex 53d4093c..4970d6c6 100644--- a/app/shared/plan_result_replacements.go+++ b/app/shared/plan_result_replacements.go@@ -18,6 +18,8 @@ func ApplyReplacements(content string, replacements []*Replacement, setFailed bosub := updated[lastInsertedIdx:]originalIdx := strings.Index(sub, replacement.Old)+ // log.Println("originalIdx:", originalIdx)+if originalIdx == -1 {allSucceeded = falseif setFailed {@@ -72,8 +74,9 @@ func (planState *CurrentPlanState) GetFilesBeforeReplacement(files[path] = updatedcontinue} else if updated == "" {- updated = planRes.ContextBody- shas[path] = planRes.ContextSha+ context := planState.ContextsByPath[path]+ updated = context.Body+ shas[path] = context.Sha}replacements := []*Replacement{}@@ -97,5 +100,5 @@ func (planState *CurrentPlanState) GetFilesBeforeReplacement(files[path] = updated}- return &CurrentPlanFiles{Files: files, ContextShas: shas}, nil+ return &CurrentPlanFiles{Files: files, UpdatedAtByPath: updatedAtByPath}, nil}