Skip to content

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

fixes, logging, use GPT4 for strong model rather than turbo

Dane Schneider316c35a3dc57
diff --git a/cli/cmd/apply.go b/cli/cmd/apply.go
index 833600e7..80e264f6 100644
--- a/cli/cmd/apply.go
+++ b/cli/cmd/apply.go
@@ -1,17 +1,9 @@
package cmd
import (
- "crypto/sha256"
- "encoding/hex"
- "fmt"
- "os"
- "path/filepath"
"plandex/lib"
- "plandex/types"
"strings"
- "github.com/fatih/color"
- "github.com/olekukonko/tablewriter"
"github.com/spf13/cobra"
)
@@ -31,7 +23,6 @@ var applyCmd = &cobra.Command{
}
func apply(cmd *cobra.Command, args []string) error {
- plandexDir, _, err := lib.FindOrCreatePlandex()
var name string
if len(args) > 0 {
@@ -39,290 +30,9 @@ func apply(cmd *cobra.Command, args []string) error {
name = strings.TrimSpace(name)
}
- if err != nil {
- return fmt.Errorf("error: %v", err)
- }
-
if name == "" || name == "current" {
name = lib.CurrentPlanName
}
- if name == "" {
- fmt.Println("πŸ€·β€β™‚οΈ No plan specified and no current plan")
- return nil
- }
-
- rootDir := filepath.Join(plandexDir, name)
-
- _, err = os.Stat(rootDir)
-
- if os.IsNotExist(err) {
- fmt.Printf("πŸ€·β€β™‚οΈ Plan with name '%s' doesn't exist\n", name)
- return nil
- } else if err != nil {
- return fmt.Errorf("error checking if plan exists: %w", err)
- }
-
- currentPlanFiles, planResByPath, _, err := lib.GetCurrentPlanStateWithContext()
-
- if err != nil {
- return fmt.Errorf("error getting current plan files: %w", err)
- }
-
- aborted := false
-
- // check if any files have been modified since the plan result was generated
- pathsRemoved := []string{}
- pathsOutdated := []string{}
- pathsUnmodified := []string{}
- pathsNew := []string{}
- pathsRemovedOrOutdatedSet := map[string]bool{}
-
- for path := range currentPlanFiles.Files {
- contextSha := currentPlanFiles.ContextShas[path]
-
- if contextSha == "" {
- // the path wasn't in context
- pathsNew = append(pathsNew, path)
- continue
- }
-
- // Compute destination path
- dstPath := filepath.Join(lib.ProjectRoot, path)
-
- // Check if the file has been removed
- _, err := os.Stat(dstPath)
-
- if os.IsNotExist(err) {
- pathsRemoved = append(pathsRemoved, path)
- pathsRemovedOrOutdatedSet[path] = true
- } else if err != nil {
- return fmt.Errorf("failed to check existence of %s: %w", dstPath, err)
- }
-
- // Read the file
- bytes, err := os.ReadFile(dstPath)
-
- if err != nil {
- return fmt.Errorf("failed to read %s: %w", dstPath, err)
- }
-
- // Get the sha of the file
- hash := sha256.Sum256(bytes)
- fileSha := hex.EncodeToString(hash[:])
-
- if fileSha == contextSha {
- pathsUnmodified = append(pathsUnmodified, path)
- } else {
- pathsOutdated = append(pathsOutdated, path)
- pathsRemovedOrOutdatedSet[path] = true
- }
- }
-
- table := tablewriter.NewWriter(os.Stdout)
- table.SetHeader([]string{"Path", "Status"})
- table.SetAutoWrapText(false)
-
- numConflicts := len(pathsRemoved) + len(pathsOutdated)
- hasConflicts := numConflicts > 0
-
- if hasConflicts {
- suffix := ""
- verb := "has"
- if numConflicts > 1 {
- suffix = "s"
- verb = "have"
- }
-
- color.New(color.Bold).Printf("⚠️ %d file%s in context %s been modified since the plan was generated\n\n", numConflicts, suffix, verb)
-
- for _, path := range pathsRemoved {
- table.Rich([]string{path, "πŸ”΄ Removed"}, []tablewriter.Colors{
- {tablewriter.FgHiRedColor, tablewriter.Bold},
- {tablewriter.FgHiWhiteColor},
- })
- }
-
- for _, path := range pathsOutdated {
- table.Rich([]string{path, "🟑 Modified"}, []tablewriter.Colors{
- {tablewriter.FgHiYellowColor, tablewriter.Bold},
- {tablewriter.FgHiWhiteColor},
- })
- }
- } else {
- numUnmodified := len(pathsUnmodified) + len(pathsNew)
- suffix := ""
-
- if numUnmodified > 1 {
- suffix = "s"
- }
-
- color.New(color.Bold).Printf("⚑️ %d file%s will be updated\n\n", numUnmodified, suffix)
- }
-
- for _, path := range pathsUnmodified {
- table.Rich([]string{path, "🟒 Ready for update"}, []tablewriter.Colors{
- {tablewriter.FgHiGreenColor, tablewriter.Bold},
- {tablewriter.FgHiWhiteColor},
- })
- }
-
- for _, path := range pathsNew {
- table.Rich([]string{path, "πŸ”΅ New file"}, []tablewriter.Colors{
- {tablewriter.FgHiCyanColor, tablewriter.Bold},
- {tablewriter.FgHiWhiteColor},
- })
- }
-
- table.Render()
-
- var conflictStrategy string
-
- if hasConflicts {
- fmt.Println()
-
- if conflictStrategy == "" {
- options := []string{
- types.PlanOutdatedStrategyOverwrite,
- }
-
- if len(currentPlanFiles.Files) > (len(pathsRemoved) + len(pathsOutdated)) {
- options = append(options, types.PlanOutdatedStrategyApplyUnmodified)
- }
-
- options = append(options,
- types.PlanOutdatedStrategyRebuild,
- types.PlanOutdatedStrategyCancel,
- )
-
- choice, err := lib.SelectFromList("πŸ€” How do you want to handle it?", options)
-
- if err != nil {
- return fmt.Errorf("failed to get user input: %w", err)
- }
-
- conflictStrategy = choice
- }
- }
-
- switch conflictStrategy {
- case types.PlanOutdatedStrategyOverwrite:
- fmt.Println("⚑️ Overwriting modifications")
-
- case types.PlanOutdatedStrategyApplyUnmodified:
- fmt.Println("⚑️ Applying only new and unmodified files")
-
- case types.PlanOutdatedStrategyRebuild:
- fmt.Println("⚑️ Rebuilding the plan with updated context")
-
- case types.PlanOutdatedStrategyCancel:
- aborted = true
- return nil
- }
-
- isRepo := lib.CwdIsGitRepo()
-
- hasUncommittedChanges := false
- if isRepo {
- // Check if there are any uncommitted changes
- hasUncommittedChanges, err = lib.CheckUncommittedChanges()
-
- if err != nil {
- return fmt.Errorf("error checking for uncommitted changes: %w", err)
- }
- }
-
- toApply := map[string]string{}
- for path, content := range currentPlanFiles.Files {
- outdated := pathsRemovedOrOutdatedSet[path]
- if outdated {
- if conflictStrategy == types.PlanOutdatedStrategyOverwrite {
- toApply[path] = content
- }
- } else {
- toApply[path] = content
- }
- }
-
- if len(toApply) == 0 {
- fmt.Println("πŸ€·β€β™‚οΈ No changes to apply")
- } else {
- if !autoConfirm && !hasConflicts {
- fmt.Println()
- numToApply := len(toApply)
- suffix := ""
- if numToApply > 1 {
- suffix = "s"
- }
- shouldContinue, err := lib.ConfirmYesNo("Apply changes to %d file%s?", numToApply, suffix)
-
- if err != nil {
- return fmt.Errorf("failed to get confirmation user input: %s", err)
- }
-
- if !shouldContinue {
- aborted = true
- return nil
- }
- }
-
- if isRepo && hasUncommittedChanges {
- // If there are uncommitted changes, stash them
- err := lib.GitStashCreate("Plandex auto-stash")
- if err != nil {
- return fmt.Errorf("failed to create git stash: %w", err)
- }
-
- defer func() {
- if aborted {
- // clear any partially applied changes before popping the stash
- err := lib.GitClearUncommittedChanges()
- if err != nil {
- fmt.Printf("failed to clear uncommitted changes: %v\n", err)
- }
- }
-
- err := lib.GitStashPop(conflictStrategy)
- if err != nil {
- fmt.Printf("failed to pop git stash: %v\n", err)
- }
- }()
- }
-
- for path, content := range toApply {
- // Compute destination path
- dstPath := filepath.Join(lib.ProjectRoot, path)
- // Write the file
- err = os.WriteFile(dstPath, []byte(content), 0644)
- if err != nil {
- aborted = true
- return fmt.Errorf("failed to write %s: %w", dstPath, err)
- }
- }
-
- err := lib.SetPendingResultsApplied(planResByPath)
- if err != nil {
- aborted = true
- return fmt.Errorf("failed to set pending results applied: %w", err)
- }
-
- if isRepo {
- desc, err := lib.GetLatestPlanDescription()
- if err != nil {
- aborted = true
- return fmt.Errorf("failed to get latest plan description: %w", err)
- }
-
- // Commit the changes
- err = lib.GitAddAndCommit(lib.ProjectRoot, color.New(color.BgBlue, color.FgHiWhite, color.Bold).Sprintln(" πŸ€– Plandex ")+desc.CommitMsg, true)
- if err != nil {
- aborted = true
- return fmt.Errorf("failed to commit changes: %w", err)
- }
- }
-
- fmt.Println("βœ… Applied changes")
- }
-
- return nil
+ return lib.ApplyPlanWithOutput(name, autoConfirm)
}
diff --git a/cli/cmd/changes.go b/cli/cmd/changes.go
index 8993ca7e..2bc1a9e6 100644
--- a/cli/cmd/changes.go
+++ b/cli/cmd/changes.go
@@ -13,9 +13,10 @@ func init() {
}
var changesCmd = &cobra.Command{
- Use: "changes",
- Short: "View, copy, or manage changes for the current plan",
- Run: changes,
+ Use: "changes",
+ Aliases: []string{"ch"},
+ Short: "View, copy, or manage changes for the current plan",
+ Run: changes,
}
func changes(cmd *cobra.Command, args []string) {
diff --git a/cli/cmd/current.go b/cli/cmd/current.go
index a2f42a72..ed78a018 100644
--- a/cli/cmd/current.go
+++ b/cli/cmd/current.go
@@ -1,28 +1,89 @@
package cmd
-// import (
-// "fmt"
-// "plandex/lib"
-
-// "github.com/spf13/cobra"
-// )
-
-// var currentCmd = &cobra.Command{
-// Use: "current",
-// Aliases: []string{"c"},
-// Short: "Get the current plan",
-// Run: current,
-// }
-
-// func init() {
-// RootCmd.AddCommand(currentCmd)
-// }
-
-// func current(cmd *cobra.Command, args []string) {
-// if lib.CurrentPlanName == "" {
-// fmt.Println("No current plan.")
-// return
-// }
-// fmt.Println(lib.CurrentPlanName)
-
-// }
+import (
+ "fmt"
+ "os"
+ "plandex/format"
+ "plandex/lib"
+ "strconv"
+ "time"
+
+ "github.com/fatih/color"
+ "github.com/olekukonko/tablewriter"
+ "github.com/plandex/plandex/shared"
+ "github.com/spf13/cobra"
+)
+
+var currentCmd = &cobra.Command{
+ Use: "current",
+ Aliases: []string{"cu"},
+ Short: "Get the current plan",
+ Run: current,
+}
+
+func init() {
+ RootCmd.AddCommand(currentCmd)
+}
+
+func current(cmd *cobra.Command, args []string) {
+ if lib.CurrentPlanName == "" {
+ fmt.Println("πŸ€·β€β™‚οΈ No current plan")
+ return
+ }
+
+ planState, err := lib.GetPlanState()
+ if err != nil {
+ fmt.Println("Error getting plan state:", err)
+ return
+ }
+
+ table := tablewriter.NewWriter(os.Stdout)
+ table.SetAutoWrapText(false)
+ table.SetHeader([]string{"Current Plan", "Updated", "Created", "Context", "Convo"})
+
+ var name string
+ if planState.Name == lib.CurrentPlanName {
+ name = color.New(color.Bold, color.FgGreen).Sprint(planState.Name)
+ } else {
+ name = planState.Name
+ }
+
+ createdAt, err := time.Parse(shared.TsFormat, planState.CreatedAt)
+ if err != nil {
+ fmt.Fprintln(os.Stderr, "Error parsing time:", err)
+ return
+ }
+
+ updatedAt, err := time.Parse(shared.TsFormat, planState.UpdatedAt)
+ if err != nil {
+ fmt.Fprintln(os.Stderr, "Error parsing time:", err)
+ return
+ }
+
+ row := []string{
+ name,
+ format.Time(updatedAt),
+ format.Time(createdAt),
+ strconv.Itoa(planState.ContextTokens) + " πŸͺ™",
+ strconv.Itoa(planState.ConvoTokens) + " πŸͺ™",
+ }
+
+ var style []tablewriter.Colors
+ if planState.Name == lib.CurrentPlanName {
+ style = []tablewriter.Colors{
+ {tablewriter.FgGreenColor, tablewriter.Bold},
+ }
+ } else {
+ style = []tablewriter.Colors{
+ {tablewriter.FgHiWhiteColor, tablewriter.Bold},
+ {tablewriter.FgHiWhiteColor},
+ }
+ }
+
+ table.Rich(row, style)
+
+ table.Render()
+ fmt.Println()
+ lib.PrintCmds("", "tell", "ls", "plans")
+
+}
diff --git a/cli/go.mod b/cli/go.mod
index 6702425a..c88f73c3 100644
--- a/cli/go.mod
+++ b/cli/go.mod
@@ -3,7 +3,9 @@ module plandex
go 1.21.3
require (
+ github.com/atotto/clipboard v0.1.4
github.com/charmbracelet/lipgloss v0.9.1
+ github.com/davecgh/go-spew v1.1.1
github.com/fatih/color v1.16.0
github.com/looplab/fsm v1.0.1
github.com/olekukonko/tablewriter v0.0.5
@@ -34,6 +36,7 @@ require (
github.com/muesli/reflow v0.3.0 // indirect
github.com/muesli/termenv v0.15.2 // indirect
github.com/rivo/uniseg v0.4.4 // indirect
+ github.com/sahilm/fuzzy v0.1.0 // indirect
github.com/yuin/goldmark v1.6.0 // indirect
github.com/yuin/goldmark-emoji v1.0.2 // indirect
golang.org/x/net v0.18.0 // indirect
diff --git a/cli/go.sum b/cli/go.sum
index 3d72c2b7..4f6134af 100644
--- a/cli/go.sum
+++ b/cli/go.sum
@@ -208,6 +208,7 @@ github.com/armon/go-metrics v0.4.0/go.mod h1:E6amYzXo6aW1tqzoZGT755KkbgrJsSdpwZ+
github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8=
github.com/armon/go-radix v1.0.0/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8=
github.com/atotto/clipboard v0.1.2/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI=
+github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4=
github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI=
github.com/aymanbagabas/go-osc52 v1.0.3/go.mod h1:zT8H+Rk4VSabYN90pWyugflM3ZhpTZNC7cASDfUCdT4=
github.com/aymanbagabas/go-osc52 v1.2.1/go.mod h1:zT8H+Rk4VSabYN90pWyugflM3ZhpTZNC7cASDfUCdT4=
@@ -490,6 +491,7 @@ github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NB
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
+github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
github.com/looplab/fsm v1.0.1 h1:OEW0ORrIx095N/6lgoGkFkotqH6s7vaFPsgjLAaF5QU=
github.com/looplab/fsm v1.0.1/go.mod h1:PmD3fFvQEIsjMEfvZdrCDZ6y8VwKTwWNjlpEr6IKPO4=
@@ -628,6 +630,7 @@ github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb
github.com/ryanuber/columnize v2.1.0+incompatible/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts=
github.com/sabhiram/go-gitignore v0.0.0-20180611051255-d3107576ba94/go.mod h1:b18R55ulyQ/h3RaWyloPyER7fWQVZvimKKhnI5OfrJQ=
github.com/sagikazarmark/crypt v0.8.0/go.mod h1:TmKwZAo97S4Fy4sfMH/HX/cQP5D+ijra2NyLpNNmttY=
+github.com/sahilm/fuzzy v0.1.0 h1:FzWGaw2Opqyu+794ZQ9SYifWv2EIXpwP4q8dY1kDAwI=
github.com/sahilm/fuzzy v0.1.0/go.mod h1:VFvziUEIMCrT6A6tw2RFIXPXXmzXbOsSHF0DOI8ZK9Y=
github.com/sashabaranov/go-openai v1.17.7 h1:MPcAwlwbeo7ZmhQczoOgZBHtIBY1TfZqsdx6+/ndloM=
github.com/sashabaranov/go-openai v1.17.7/go.mod h1:lj5b/K+zjTSFxVLijLSTDZuP7adOgerWeFyZLUhAKRg=
diff --git a/cli/lib/apply.go b/cli/lib/apply.go
new file mode 100644
index 00000000..7edb1369
--- /dev/null
+++ b/cli/lib/apply.go
@@ -0,0 +1,335 @@
+package lib
+
+import (
+ "crypto/sha256"
+ "encoding/hex"
+ "fmt"
+ "os"
+ "path/filepath"
+ "plandex/types"
+
+ "github.com/fatih/color"
+ "github.com/olekukonko/tablewriter"
+ "github.com/plandex/plandex/shared"
+)
+
+func ApplyPlanWithOutput(name string, autoConfirm bool) error {
+ plandexDir, _, err := FindOrCreatePlandex()
+ if err != nil {
+ return fmt.Errorf("error finding or creating plandex dir: %w", err)
+ }
+
+ if name == "" {
+ fmt.Println("πŸ€·β€β™‚οΈ No plan specified and no current plan")
+ return nil
+ }
+
+ rootDir := filepath.Join(plandexDir, name)
+
+ _, err = os.Stat(rootDir)
+
+ if os.IsNotExist(err) {
+ fmt.Printf("πŸ€·β€β™‚οΈ Plan with name '%s' doesn't exist\n", name)
+ return nil
+ } else if err != nil {
+ return fmt.Errorf("error checking if plan exists: %w", err)
+ }
+
+ currentPlanFiles, planResByPath, _, err := GetCurrentPlanStateWithContext()
+
+ if err != nil {
+ return fmt.Errorf("error getting current plan files: %w", err)
+ }
+
+ aborted := false
+
+ // check if any files have been modified since the plan result was generated
+ pathsRemoved := []string{}
+ pathsOutdated := []string{}
+ pathsUnmodified := []string{}
+ pathsNew := []string{}
+ pathsRemovedOrOutdatedSet := map[string]bool{}
+ outdatedCanMergeSet := map[string]bool{}
+
+ canMergeAllOutdated := true
+
+ for path := range currentPlanFiles.Files {
+ contextSha := currentPlanFiles.ContextShas[path]
+
+ if contextSha == "" {
+ // the path wasn't in context
+ pathsNew = append(pathsNew, path)
+ continue
+ }
+
+ // Compute destination path
+ dstPath := filepath.Join(ProjectRoot, path)
+
+ // Check if the file has been removed
+ _, err := os.Stat(dstPath)
+
+ if os.IsNotExist(err) {
+ pathsRemoved = append(pathsRemoved, path)
+ pathsRemovedOrOutdatedSet[path] = true
+ } else if err != nil {
+ return fmt.Errorf("failed to check existence of %s: %w", dstPath, err)
+ }
+
+ // Read the file
+ bytes, err := os.ReadFile(dstPath)
+
+ if err != nil {
+ return fmt.Errorf("failed to read %s: %w", dstPath, err)
+ }
+
+ // Get the sha of the file
+ hash := sha256.Sum256(bytes)
+ fileSha := hex.EncodeToString(hash[:])
+
+ if fileSha == contextSha {
+ pathsUnmodified = append(pathsUnmodified, path)
+ } else {
+ pathsOutdated = append(pathsOutdated, path)
+ pathsRemovedOrOutdatedSet[path] = true
+
+ planRes := planResByPath[path]
+
+ updated := string(bytes)
+ allSucceeded := true
+ for _, res := range planRes {
+ var succeeded bool
+ updated, succeeded = shared.ApplyReplacements(updated, res.Replacements, false)
+ if !succeeded {
+ allSucceeded = false
+ canMergeAllOutdated = false
+ break
+ }
+ }
+ outdatedCanMergeSet[path] = allSucceeded
+ }
+ }
+
+ table := tablewriter.NewWriter(os.Stdout)
+ table.SetHeader([]string{"Path", "Status"})
+ table.SetAutoWrapText(false)
+
+ numConflicts := len(pathsRemoved) + len(pathsOutdated)
+ hasConflicts := numConflicts > 0
+
+ if hasConflicts {
+ suffix := ""
+ verb := "has"
+ if numConflicts > 1 {
+ suffix = "s"
+ verb = "have"
+ }
+
+ color.New(color.Bold).Printf("⚠️ %d file%s in context %s been modified since the plan was generated\n\n", numConflicts, suffix, verb)
+
+ for _, path := range pathsRemoved {
+ table.Rich([]string{path, "πŸ”΄ Removed"}, []tablewriter.Colors{
+ {tablewriter.FgHiRedColor, tablewriter.Bold},
+ {tablewriter.FgHiWhiteColor},
+ })
+ }
+
+ for _, path := range pathsOutdated {
+ s := "🟑 Modified"
+ if outdatedCanMergeSet[path] {
+ s += " " + color.New(color.BgGreen).Sprint(" Can still apply changes ")
+ } else {
+ s += " " + color.New(color.BgRed).Sprint(" Can't apply changes ")
+ }
+
+ table.Rich([]string{path, s}, []tablewriter.Colors{
+ {tablewriter.FgHiYellowColor, tablewriter.Bold},
+ {tablewriter.FgHiWhiteColor},
+ })
+ }
+ } else {
+ numUnmodified := len(pathsUnmodified) + len(pathsNew)
+ suffix := ""
+
+ if numUnmodified > 1 {
+ suffix = "s"
+ }
+
+ color.New(color.Bold).Printf("⚑️ %d file%s will be updated\n\n", numUnmodified, suffix)
+ }
+
+ for _, path := range pathsUnmodified {
+ table.Rich([]string{path, "🟒 Ready for update"}, []tablewriter.Colors{
+ {tablewriter.FgHiGreenColor, tablewriter.Bold},
+ {tablewriter.FgHiWhiteColor},
+ })
+ }
+
+ for _, path := range pathsNew {
+ table.Rich([]string{path, "πŸ”΅ New file"}, []tablewriter.Colors{
+ {tablewriter.FgHiCyanColor, tablewriter.Bold},
+ {tablewriter.FgHiWhiteColor},
+ })
+ }
+
+ table.Render()
+
+ var conflictStrategy string
+
+ if hasConflicts {
+ fmt.Println()
+
+ if conflictStrategy == "" {
+ options := []string{
+ types.PlanOutdatedStrategyOverwrite,
+ }
+
+ if len(currentPlanFiles.Files) > (len(pathsRemoved) + len(pathsOutdated)) {
+ options = append(options, types.PlanOutdatedStrategyApplyUnmodified)
+ }
+
+ if canMergeAllOutdated {
+ options = append(options, types.PlanOutdatedStrategyApplyNoConflicts)
+ }
+
+ options = append(options,
+ // types.PlanOutdatedStrategyRebuild, // TODO: implement rebuild
+ types.PlanOutdatedStrategyCancel,
+ )
+
+ choice, err := SelectFromList("πŸ€” How do you want to handle it?", options)
+
+ if err != nil {
+ return fmt.Errorf("failed to get user input: %w", err)
+ }
+
+ conflictStrategy = choice
+ }
+ }
+
+ switch conflictStrategy {
+ case types.PlanOutdatedStrategyOverwrite:
+ fmt.Println("⚑️ Overwriting modifications")
+
+ case types.PlanOutdatedStrategyApplyUnmodified:
+ fmt.Println("⚑️ Applying only new and unmodified files")
+
+ case types.PlanOutdatedStrategyApplyNoConflicts:
+ // nothing to do
+
+ case types.PlanOutdatedStrategyRebuild:
+ fmt.Println("⚑️ Rebuilding the plan with updated context")
+ // TODO: rebuild the plan
+ return nil
+
+ case types.PlanOutdatedStrategyCancel:
+ aborted = true
+ return nil
+ }
+
+ isRepo := CwdIsGitRepo()
+
+ hasUncommittedChanges := false
+ if isRepo {
+ // Check if there are any uncommitted changes
+ hasUncommittedChanges, err = CheckUncommittedChanges()
+
+ if err != nil {
+ return fmt.Errorf("error checking for uncommitted changes: %w", err)
+ }
+ }
+
+ toApply := map[string]string{}
+ for path, content := range currentPlanFiles.Files {
+ outdated := pathsRemovedOrOutdatedSet[path]
+ if outdated {
+ if conflictStrategy == types.PlanOutdatedStrategyOverwrite || conflictStrategy == types.PlanOutdatedStrategyApplyNoConflicts {
+ toApply[path] = content
+ }
+ } else {
+ toApply[path] = content
+ }
+ }
+
+ if len(toApply) == 0 {
+ fmt.Println("πŸ€·β€β™‚οΈ No changes to apply")
+ } else {
+ if !autoConfirm && !hasConflicts {
+ fmt.Println()
+ numToApply := len(toApply)
+ suffix := ""
+ if numToApply > 1 {
+ suffix = "s"
+ }
+ shouldContinue, err := ConfirmYesNo("Apply changes to %d file%s?", numToApply, suffix)
+
+ if err != nil {
+ return fmt.Errorf("failed to get confirmation user input: %s", err)
+ }
+
+ if !shouldContinue {
+ aborted = true
+ return nil
+ }
+ }
+
+ if isRepo && hasUncommittedChanges {
+ // If there are uncommitted changes, stash them
+ err := GitStashCreate("Plandex auto-stash")
+ if err != nil {
+ return fmt.Errorf("failed to create git stash: %w", err)
+ }
+
+ defer func() {
+ if aborted {
+ // clear any partially applied changes before popping the stash
+ err := GitClearUncommittedChanges()
+ if err != nil {
+ fmt.Printf("failed to clear uncommitted changes: %v\n", err)
+ }
+ }
+
+ err := GitStashPop(conflictStrategy)
+ if err != nil {
+ fmt.Printf("failed to pop git stash: %v\n", err)
+ }
+ }()
+ }
+
+ for path, content := range toApply {
+ // Compute destination path
+ dstPath := filepath.Join(ProjectRoot, path)
+ // Write the file
+ err = os.WriteFile(dstPath, []byte(content), 0644)
+ if err != nil {
+ aborted = true
+ return fmt.Errorf("failed to write %s: %w", dstPath, err)
+ }
+ }
+
+ err := SetPendingResultsApplied(planResByPath)
+ if err != nil {
+ aborted = true
+ return fmt.Errorf("failed to set pending results applied: %w", err)
+ }
+
+ if isRepo {
+ desc, err := GetLatestPlanDescription()
+ if err != nil {
+ aborted = true
+ return fmt.Errorf("failed to get latest plan description: %w", err)
+ }
+
+ // Commit the changes
+ err = GitAddAndCommit(ProjectRoot, color.New(color.BgBlue, color.FgHiWhite, color.Bold).Sprintln(" πŸ€– Plandex ")+desc.CommitMsg, true)
+ if err != nil {
+ aborted = true
+ return fmt.Errorf("failed to commit changes: %w", err)
+ }
+ }
+
+ fmt.Println("βœ… Applied changes")
+ }
+
+ return nil
+
+}
diff --git a/cli/lib/changes_ui.go b/cli/lib/changes_ui.go
index cee2da4b..45800707 100644
--- a/cli/lib/changes_ui.go
+++ b/cli/lib/changes_ui.go
@@ -2,57 +2,47 @@ package lib
import (
"fmt"
+ "log"
+ "strings"
+ "time"
"github.com/charmbracelet/bubbles/help"
bubbleKey "github.com/charmbracelet/bubbles/key"
+ "github.com/charmbracelet/bubbles/list"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
+ "github.com/fatih/color"
"github.com/plandex/plandex/shared"
+
+ "github.com/atotto/clipboard"
)
type keymap = struct {
up, down, reject, copy, applyAll, quit bubbleKey.Binding
}
-type UIState int
-
-const (
- ViewState UIState = iota
- ChangeState
-)
-
-type changeDetail struct {
- Path string
- Index int
- Change shared.PlanResultReplacement
- OldView string
- NewView string
-}
-
type changesUIModel struct {
help help.Model
keymap keymap
selectedFileIndex int
selectedReplacementIndex int
- resultsByPath shared.PlanResultsByPath
+ resultsInfo *planResultsInfo
currentPlanFiles *shared.CurrentPlanFiles
- state UIState
- fileViewer string
- changeDetails *changeDetail
- clipboard clipboardUtil
+ sidebar list.Model
}
-type clipboardUtil struct{}
+func StartChangesUI() error {
+ log.Print("\n\n\nStarting changes UI...\n\n")
-func (c *clipboardUtil) copy(text string) error {
- // Implementation goes here.
- return nil
-}
+ _, err := tea.NewProgram(initialModel(), tea.WithAltScreen()).Run()
-func StartChangesUI() error {
- if _, err := tea.NewProgram(initialModel(), tea.WithAltScreen()).Run(); err != nil {
+ if err != nil {
return fmt.Errorf("error running changes UI: %v", err)
}
+
+ // fmt.Println("exited changes UI")
+ // spew.Dump(m)
+
return nil
}
@@ -62,19 +52,19 @@ func (m changesUIModel) Init() tea.Cmd {
func initialModel() changesUIModel {
errChn := make(chan error, 1)
- planResByPathChn := make(chan shared.PlanResultsByPath, 1)
- currentPlanFilesChn := make(chan *shared.CurrentPlanFiles, 1)
+ resultsInfoCh := make(chan *planResultsInfo, 1)
+ currentPlanFilesCh := make(chan *shared.CurrentPlanFiles, 1)
- var resultsByPath shared.PlanResultsByPath
+ var resultsInfo *planResultsInfo
var currentPlanFiles *shared.CurrentPlanFiles
go func() {
- planResByPath, err := getPlanResultsByPath()
+ planResByPath, err := getPlanResultsInfo()
if err != nil {
errChn <- fmt.Errorf("error getting plan results: %v", err)
return
}
- planResByPathChn <- planResByPath
+ resultsInfoCh <- planResByPath
}()
go func() {
@@ -84,26 +74,20 @@ func initialModel() changesUIModel {
errChn <- fmt.Errorf("error getting current plan files: %v", err)
return
}
- currentPlanFilesChn <- currentPlanFiles
+ currentPlanFilesCh <- currentPlanFiles
}()
for i := 0; i < 2; i++ {
select {
case err := <-errChn:
panic(fmt.Errorf("error getting plan results: %v", err))
- case resultsByPath = <-planResByPathChn:
- case currentPlanFiles = <-currentPlanFilesChn:
+ case resultsInfo = <-resultsInfoCh:
+ case currentPlanFiles = <-currentPlanFilesCh:
}
}
- state: ViewState,
- fileViewer: resultsByPath["example.go"][0].Content,
- changeDetails: &changeDetail{
- Path: "example.go",
- Index: 0,
- },
- clipboard: clipboardUtil{},
- resultsByPath: resultsByPath,
+ initialState := changesUIModel{
+ resultsInfo: resultsInfo,
selectedFileIndex: 0,
selectedReplacementIndex: 0,
help: help.New(),
@@ -134,33 +118,116 @@ func initialModel() changesUIModel {
),
quit: bubbleKey.NewBinding(
- bubbleKey.WithKeys("esc"),
- bubbleKey.WithHelp("esc", "quit"),
+ bubbleKey.WithKeys("q", "ctrl+c"),
+ bubbleKey.WithHelp("q", "quit"),
),
},
}
+
+ return initialState
}
+var escPressedAt time.Time
+var escSeq string
+
func (m changesUIModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
- switch msg := msg.(type) {
+ selectionInfo := m.getSelectionInfo()
+ paths := m.resultsInfo.sortedPaths
+ currentReplacements := selectionInfo.currentReplacements
+
+ log.Printf("msg: %v", msg)
+
+ up := func() {
+ log.Println("up")
+ log.Printf("selectedReplacementIndex before: %d", m.selectedReplacementIndex)
+ log.Printf("selectedFileIndex before: %d", m.selectedFileIndex)
+ if m.selectedReplacementIndex > 0 {
+ m.selectedReplacementIndex--
+ } else if m.selectedFileIndex > 0 {
+ m.selectedFileIndex--
+ m.selectedReplacementIndex = len(m.resultsInfo.replacementsByPath[paths[m.selectedFileIndex]]) - 1
+ }
+
+ log.Printf("selectedReplacementIndex after: %d", m.selectedReplacementIndex)
+ log.Printf("selectedFileIndex after: %d", m.selectedFileIndex)
+ }
+
+ down := func() {
+ log.Println("down")
+ log.Printf("selectedReplacementIndex before: %d", m.selectedReplacementIndex)
+ log.Printf("len(currentReplacements)-1: %d", len(currentReplacements)-1)
+ log.Printf("selectedFileIndex before: %d", m.selectedFileIndex)
+ log.Printf("len(paths)-1: %d", len(paths)-1)
+ if m.selectedReplacementIndex < len(currentReplacements)-1 {
+ m.selectedReplacementIndex++
+ } else if m.selectedFileIndex < len(paths)-1 {
+ m.selectedFileIndex++
+ m.selectedReplacementIndex = 0
+ }
+ log.Printf("selectedReplacementIndex after: %d", m.selectedReplacementIndex)
+ log.Printf("selectedFileIndex after: %d", m.selectedFileIndex)
+ }
+
+ switch msg := msg.(type) {
case tea.KeyMsg:
switch {
case bubbleKey.Matches(msg, m.keymap.up):
+ up()
case bubbleKey.Matches(msg, m.keymap.down):
+ down()
case bubbleKey.Matches(msg, m.keymap.reject):
+ m.rejectChange()
case bubbleKey.Matches(msg, m.keymap.applyAll):
+ // TODO: need to close the TUI then apply
case bubbleKey.Matches(msg, m.keymap.copy):
+ m.copyCurrentChange()
case bubbleKey.Matches(msg, m.keymap.quit):
return m, tea.Quit
+ default:
+ if msg.String() == "esc" {
+ // log.Println("esc")
+ escPressedAt = time.Now()
+ go func() {
+ time.Sleep(51 * time.Millisecond)
+ // log.Println("esc timeout")
+ escPressedAt = time.Time{}
+ escSeq = ""
+ }()
+ }
+
+ if !escPressedAt.IsZero() {
+ elapsed := time.Since(escPressedAt)
+
+ // log.Println("elapsed: ", elapsed)
+
+ if elapsed < 50*time.Millisecond {
+ escSeq += msg.String()
+
+ // log.Println("escSeq: ", escSeq)
+
+ if escSeq == "esc[A" {
+ up()
+ escPressedAt = time.Time{}
+ escSeq = ""
+ } else if escSeq == "esc[B" {
+ down()
+ escPressedAt = time.Time{}
+ escSeq = ""
+ }
+
+ return m, nil
+ }
+ }
+
}
}
@@ -175,7 +242,184 @@ func (m changesUIModel) View() string {
m.keymap.quit,
})
- var views []string
+ sidebar := m.renderSidebar()
+ mainView := m.renderMainView()
+
+ layout := lipgloss.JoinHorizontal(lipgloss.Top, sidebar, mainView)
+
+ return lipgloss.JoinVertical(lipgloss.Left,
+ layout,
+ help,
+ )
+}
+
+func (m *changesUIModel) renderSidebar() string {
+ // log.Print("renderSidebar")
+
+ var sb strings.Builder
+
+ selectionInfo := m.getSelectionInfo()
+ paths := m.resultsInfo.sortedPaths
+ currentPath := selectionInfo.currentPath
+ currentRes := selectionInfo.currentRes
+ currentRep := selectionInfo.currentRep
+
+ // log.Printf("paths: %v", paths)
+ // log.Printf("currentPath: %v", currentPath)
+ // log.Printf("currentRes: %v", currentRes)
+ // log.Printf("currentRep: %v", currentRep)
+
+ for _, path := range paths {
+ results := m.resultsInfo.resultsByPath[path]
+ selectedPath := path == currentPath
+
+ selectedFullFile := selectedPath && currentRes == nil
+
+ pathColor := color.FgHiGreen
+
+ anyFailed := false
+ for _, result := range results {
+ if result.AnyFailed {
+ anyFailed = true
+ break
+ }
+ }
+ if anyFailed {
+ pathColor = color.FgHiRed
+ }
+
+ sb.WriteString(color.New(pathColor).Sprint(" πŸ“„ " + path + "\n"))
+
+ // Change entries
+ for _, result := range results {
+ for _, rep := range result.Replacements {
+ selected := selectedPath && rep.Id == currentRep.Id
+
+ s := ""
+
+ labelColor := color.FgHiGreen
+ if rep.Failed {
+ labelColor = color.FgHiRed
+ }
+
+ if selected {
+ s += color.New(color.Bold).Sprintf(" > ") + color.New(color.Bold, labelColor).Sprint(shortenText(rep.Summary, 50))
+ } else {
+ s += color.New(labelColor).Sprintf(" - %s", shortenText(rep.Summary, 50))
+ }
+
+ if result.RejectedAt != "" {
+ s += " 🚫"
+ }
+
+ s += "\n"
+
+ sb.WriteString(s)
+ }
- return lipgloss.JoinHorizontal(lipgloss.Top, views...) + "\n\n" + help
+ }
+
+ if selectedFullFile {
+ sb.WriteString(color.New(color.Bold, color.FgHiCyan).Sprint(" > ") + color.New(color.Bold).Sprint("Updated file\n"))
+ } else {
+ sb.WriteString(" - Updated file\n")
+ }
+ }
+
+ return sb.String()
+}
+
+// Helper function to shorten text if necessary
+func shortenText(s string, maxLength int) string {
+ if len(s) <= maxLength {
+ return s
+ }
+ return s[:maxLength-3] + "..."
+}
+
+func (m *changesUIModel) renderMainView() string {
+ selectionInfo := m.getSelectionInfo()
+
+ if selectionInfo.currentRep == nil {
+ // Show whole file
+
+ } else {
+ // Show replacement
+ return fmt.Sprintf(`
+ Old:
+
+ `+"```"+`
+ %s
+ `+"```"+`
+
+ New:
+
+ `+"```"+`
+ %s
+ `+"```", selectionInfo.currentRep.Old, selectionInfo.currentRep.New)
+ }
+
+ return ""
+}
+
+func (m *changesUIModel) rejectChange() error {
+
+ return nil
+}
+
+func (m *changesUIModel) applyAllChanges() error {
+
+ return nil
+}
+
+type selectionInfo struct {
+ currentPath string
+ currentRes *shared.PlanResult
+ currentReplacements []*shared.Replacement
+ currentRep *shared.Replacement
+}
+
+func (m *changesUIModel) getSelectionInfo() selectionInfo {
+ paths := m.resultsInfo.sortedPaths
+ currentPath := paths[m.selectedFileIndex]
+
+ results := m.resultsInfo.resultsByPath[currentPath]
+
+ var currentRes *shared.PlanResult
+ var currentRep *shared.Replacement
+
+ var pathReplacements []*shared.Replacement
+
+ for i, res := range results {
+ for j, rep := range res.Replacements {
+ pathReplacements = append(pathReplacements, rep)
+
+ flatIndex := i*len(res.Replacements) + j
+ if flatIndex == m.selectedReplacementIndex {
+ currentRes = res
+ currentRep = rep
+ }
+ }
+ }
+
+ return selectionInfo{
+ currentPath: currentPath,
+ currentRes: currentRes,
+ currentReplacements: pathReplacements,
+ currentRep: currentRep,
+ }
+}
+
+func (m *changesUIModel) copyCurrentChange() error {
+ selectionInfo := m.getSelectionInfo()
+ if selectionInfo.currentRep == nil {
+ return fmt.Errorf("no change is currently selected")
+ }
+
+ // Copy the 'New' content of the replacement to the clipboard
+ if err := clipboard.WriteAll(selectionInfo.currentRep.New); err != nil {
+ return fmt.Errorf("failed to copy to clipboard: %v", err)
+ }
+
+ return nil
}
diff --git a/cli/lib/plan_files.go b/cli/lib/plan_files.go
index 338c74f9..8fb1dcb8 100644
--- a/cli/lib/plan_files.go
+++ b/cli/lib/plan_files.go
@@ -6,7 +6,6 @@ import (
"os"
"path/filepath"
"sort"
- "strings"
"github.com/plandex/plandex/shared"
)
@@ -31,12 +30,12 @@ func GetCurrentPlanStateWithContext() (*shared.CurrentPlanFiles, shared.PlanResu
}()
go func() {
- planResByPath, err := getPlanResultsByPath()
+ planResInfo, err := getPlanResultsInfo()
if err != nil {
errCh <- fmt.Errorf("error getting plan results: %v", err)
return
}
- planResByPathCh <- planResByPath
+ planResByPathCh <- planResInfo.resultsByPath
}()
var planResByPath shared.PlanResultsByPath
@@ -77,12 +76,12 @@ func GetCurrentPlanStateWithContext() (*shared.CurrentPlanFiles, shared.PlanResu
// fmt.Printf("path: %s\n", path)
// fmt.Printf("updated: %s\n", updated)
- for i, planRes := range planResults {
+ for _, planRes := range planResults {
if !planRes.IsPending() {
continue
}
- if planRes.Content != "" {
+ if len(planRes.Replacements) == 0 {
if updated != "" {
return nil, nil, nil, fmt.Errorf("plan updates out of order: %s", path)
}
@@ -102,38 +101,12 @@ func GetCurrentPlanStateWithContext() (*shared.CurrentPlanFiles, shared.PlanResu
continue
}
- lastInsertedIdx := 0
- for j, replacement := range planRes.Replacements {
- if !replacement.IsPending() {
- continue
- }
-
- pre := updated[:lastInsertedIdx]
- sub := updated[lastInsertedIdx:]
- originalIdx := strings.Index(sub, replacement.Old)
-
- // fmt.Println("replacement.Old: " + replacement.Old)
- // fmt.Println("Pre: " + pre)
- // fmt.Println("Sub: " + sub)
- // fmt.Println("Idx: " + fmt.Sprintf("%d", i))
- // fmt.Printf("OriginalIdx: %d\n", originalIdx)
- // fmt.Printf("LastInsertedIdx: %d\n", lastInsertedIdx)
-
- if originalIdx == -1 {
- // replacement failed, return error (checked server-side so this shouldn't happen)
-
- err := fmt.Errorf("replacement failed. path: %s, ts: %s, resIdx: %d, replaceIdx: %d", path, planRes.Ts, i, j)
-
- fmt.Println(err.Error())
+ var allSucceeded bool
+ updated, allSucceeded = shared.ApplyReplacements(updated, planRes.Replacements, false)
- // fmt.Println("Updated: " + updated)
+ if !allSucceeded {
- return nil, nil, nil, err
- } else {
- replaced := strings.Replace(sub, replacement.Old, replacement.New, 1)
- updated = pre + replaced
- lastInsertedIdx = lastInsertedIdx + originalIdx + len(replacement.New)
- }
+ return nil, nil, nil, fmt.Errorf("plan replacement failed: %s", path)
}
}
@@ -188,17 +161,24 @@ func SetPendingResultsApplied(planResByPath shared.PlanResultsByPath) error {
return nil
}
-func getPlanResultsByPath() (shared.PlanResultsByPath, error) {
+type planResultsInfo struct {
+ resultsByPath shared.PlanResultsByPath
+ sortedPaths []string
+ replacementsByPath map[string][]*shared.Replacement
+}
+
+func getPlanResultsInfo() (*planResultsInfo, error) {
resByPath := make(shared.PlanResultsByPath)
+ replacementsByPath := make(map[string][]*shared.Replacement)
+ var paths []string
_, err := os.Stat(ResultsSubdir)
resDirExists := !os.IsNotExist(err)
if !resDirExists {
- return resByPath, nil
+ return nil, nil
}
- // resFiles, err := os.ReadDir(ResultsSubdir)
err = filepath.Walk(ResultsSubdir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return fmt.Errorf("error reading results dir: %v", err)
@@ -220,6 +200,7 @@ func getPlanResultsByPath() (shared.PlanResultsByPath, error) {
}
resByPath[planRes.Path] = append(resByPath[planRes.Path], &planRes)
+ paths = append(paths, planRes.Path)
return nil
})
@@ -233,7 +214,20 @@ func getPlanResultsByPath() (shared.PlanResultsByPath, error) {
sort.Slice(results, func(i, j int) bool {
return results[i].Ts < results[j].Ts
})
+
+ for _, planRes := range results {
+ replacementsByPath[planRes.Path] = append(replacementsByPath[planRes.Path], planRes.Replacements...)
+ }
}
- return resByPath, nil
+ // sort paths ascending
+ sort.Slice(paths, func(i, j int) bool {
+ return paths[i] < paths[j]
+ })
+
+ return &planResultsInfo{
+ resultsByPath: resByPath,
+ sortedPaths: paths,
+ replacementsByPath: replacementsByPath,
+ }, nil
}
diff --git a/cli/lib/proposal.go b/cli/lib/proposal.go
index 3108a86e..6860ef44 100644
--- a/cli/lib/proposal.go
+++ b/cli/lib/proposal.go
@@ -128,6 +128,7 @@ func Propose(prompt string) error {
MoveCursorToTopLeft()
mdFull, _ := GetMarkdown(reply)
fmt.Println(mdFull)
+ fmt.Println(displayHotkeys())
termState = mdFull
}
diff --git a/cli/main.go b/cli/main.go
index 20c81f13..04945888 100644
--- a/cli/main.go
+++ b/cli/main.go
@@ -1,9 +1,35 @@
package main
import (
+ "log"
+ "os"
+ "path/filepath"
"plandex/cmd"
)
+func init() {
+ // set up a file logger
+ // TODO: log rotation
+ home, err := os.UserHomeDir()
+ if err != nil {
+ panic(err)
+ }
+
+ dir := filepath.Join(home, ".plandex")
+ err = os.MkdirAll(dir, os.ModePerm)
+ if err != nil {
+ panic(err)
+ }
+
+ file, err := os.OpenFile(filepath.Join(dir, "plandex.log"), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
+ if err != nil {
+ log.Fatal(err)
+ }
+
+ // Set the output of the logger to the file
+ log.SetOutput(file)
+}
+
func main() {
cmd.Execute()
}
diff --git a/cli/types/types.go b/cli/types/types.go
index 0199cb58..d79e6f14 100644
--- a/cli/types/types.go
+++ b/cli/types/types.go
@@ -67,8 +67,9 @@ type LoadContextParams struct {
}
const (
- PlanOutdatedStrategyOverwrite string = "Clear the modifications and then apply"
- PlanOutdatedStrategyApplyUnmodified string = "Apply only new and unmodified files"
- PlanOutdatedStrategyRebuild string = "Rebuild the plan with updated context"
- PlanOutdatedStrategyCancel string = "Cancel"
+ PlanOutdatedStrategyOverwrite string = "Clear the modifications and then apply"
+ PlanOutdatedStrategyApplyUnmodified string = "Apply only new and unmodified files"
+ PlanOutdatedStrategyApplyNoConflicts string = "Apply anyway since there are no conflicts"
+ PlanOutdatedStrategyRebuild string = "Rebuild the plan with updated context"
+ PlanOutdatedStrategyCancel string = "Cancel"
)
diff --git a/server/model/openai_models.go b/server/model/openai_models.go
index c180bd7f..7e2abb00 100644
--- a/server/model/openai_models.go
+++ b/server/model/openai_models.go
@@ -6,12 +6,13 @@ import (
"github.com/sashabaranov/go-openai"
)
-const strongModel = openai.GPT4TurboPreview
+const strongModel = openai.GPT4 //openai.GPT4TurboPreview
+const mediumModel = openai.GPT4TurboPreview
const weakModel = openai.GPT3Dot5Turbo1106
var PlannerModel = strongModel
-var PlanSummaryModel = strongModel
-var BuilderModel = strongModel //openai.GPT4
+var PlanSummaryModel = mediumModel //strongModel
+var BuilderModel = strongModel //openai.GPT4
var ShortSummaryModel = weakModel
var NameModel = weakModel
var CommitMsgModel = weakModel
diff --git a/server/model/prompts/create.go b/server/model/prompts/create.go
index e7cfdb72..712e8c11 100644
--- a/server/model/prompts/create.go
+++ b/server/model/prompts/create.go
@@ -33,7 +33,9 @@ const SysCreate = Identity + ` A plan is a set of files with an attached context
- Explicitly say "Let's break up this task."
- Divide the task into smaller subtasks and list them in a numbered list. Stop there.
- Always precede code blocks in a plan with the file path as described above in 2a. Code must *always* be labelled with the path.
+ Always precede code blocks in a plan with the file path as described above in 2a. Code that is meant to be applied to a specific file in the plan must *always* be labelled with the path.
+
+ If code is being included for explanatory purposes and is not meant to be applied to a specific file, you MUST NOT label the code block in the format described in 2a. Instead, output the code without a label.
Every file you reference in a plan should either exist in the context directly or be a new file that will be created in the same base directory a file in the context. For example, if there is a file in context at path 'lib/utils.go', you can create a new file at path 'lib/utils_test.go' but *not* at path 'src/lib/utils.go'.
@@ -51,7 +53,10 @@ const SysCreate = Identity + ` A plan is a set of files with an attached context
For changes that are larger or more complex, only include one change per response.
- At the end of a plan, you can suggest additional iterations to make the plan better. You can also ask the user to load more files or information into context if it would help you make a better plan.` +
+ At the end of a plan, you can suggest additional iterations to make the plan better. You can also ask the user to load more files or information into context if it would help you make a better plan.
+
+ Be aware that since the plan started, the context may have been updated. It may have been updated by the user implementing your suggestions, by the user implementing their own work, or by the user adding more files or information to context. Be sure to consider the current state of the context when continuing with the plan, and whether the plan needs to be updated to reflect the latest context. For example, if you are working on a plan that has been broken up into subtasks, and you've reached the point of implementing a particular subtask, first consider whether the subtask is still necessary looking at the files in context. If it has already been implemented or is no longer necessary, say so, revise the plan if needed, and move on. Otherwise, implement the subtask.
+ ` +
"\n```\n\n" +
"User-provided context:"
diff --git a/server/model/proposal/build.go b/server/model/proposal/build.go
index 2edd7532..01655a0e 100644
--- a/server/model/proposal/build.go
+++ b/server/model/proposal/build.go
@@ -23,6 +23,8 @@ const MaxRetries = 3
const MaxReplacementRetries = 1
func BuildPlan(params *types.BuildParams, onStream types.OnStreamFunc) error {
+ fmt.Printf("Building plan: %s\n", params.ProposalId)
+
// proposalId := params.ProposalId
// fileContents := params.FileContents
// numTokensByFile := params.NumTokensByFile
@@ -228,16 +230,17 @@ func BuildPlan(params *types.BuildParams, onStream types.OnStreamFunc) error {
fmt.Println("Calling model for file: " + filePath)
- for _, msg := range fileMessages {
- fmt.Printf("%s: %s\n", msg.Role, msg.Content)
- }
+ // for _, msg := range fileMessages {
+ // fmt.Printf("%s: %s\n", msg.Role, msg.Content)
+ // }
modelReq := openai.ChatCompletionRequest{
- Model: model.BuilderModel,
- Functions: []openai.FunctionDefinition{prompts.ReplaceFn},
- Messages: fileMessages,
- Temperature: 0.0,
- ResponseFormat: &openai.ChatCompletionResponseFormat{Type: "json_object"},
+ Model: model.BuilderModel,
+ Functions: []openai.FunctionDefinition{prompts.ReplaceFn},
+ Messages: fileMessages,
+ Temperature: 0.2,
+ TopP: 0.1,
+ // ResponseFormat: &openai.ChatCompletionResponseFormat{Type: "json_object"},
}
stream, err := model.Client.CreateChatCompletionStream(ctx, modelReq)
@@ -266,8 +269,9 @@ func BuildPlan(params *types.BuildParams, onStream types.OnStreamFunc) error {
handleErrorRetry := func(maxRetryErr error, shouldSleep bool, isReplacementsRetry bool, res *shared.PlanResult) {
fmt.Printf("Error for file %s: %v\n", filePath, maxRetryErr)
- if (isReplacementsRetry && numReplacementsRetry >= MaxReplacementRetries) ||
- (!isReplacementsRetry && numRetry >= MaxRetries) {
+ if isReplacementsRetry && numReplacementsRetry >= MaxReplacementRetries {
+ // in this case, we just want to ignore the error and continue
+ } else if !isReplacementsRetry && numRetry >= MaxRetries {
onBuildFileError(filePath, maxRetryErr)
} else {
if shouldSleep {
@@ -308,11 +312,14 @@ func BuildPlan(params *types.BuildParams, onStream types.OnStreamFunc) error {
<-timer.C
}
timer.Reset(model.OPENAI_STREAM_CHUNK_TIMEOUT)
- }
-
- if err != nil {
+ } else {
fmt.Printf("File %s: Error receiving stream chunk: %v\n", filePath, err)
+ if err == context.Canceled {
+ fmt.Printf("File %s: Stream canceled\n", filePath)
+ return
+ }
+
handleErrorRetry(
fmt.Errorf("stream error for file '%s' after %d retries: %v", filePath, numRetry, err),
true,
@@ -395,7 +402,17 @@ func BuildPlan(params *types.BuildParams, onStream types.OnStreamFunc) error {
if err == nil && len(replacements.Replacements) > 0 {
fmt.Printf("File %s: Parsed replacements\n", filePath)
- planResult, allSucceeded := getPlanResult(proposalId, filePath, currentState, contextPart, replacements.Replacements)
+ planResult, allSucceeded := getPlanResult(
+ planResultParams{
+ proposalId: proposalId,
+ filePath: filePath,
+ currentState: currentState,
+ contextPart: contextPart,
+ replacements: replacements.Replacements,
+ },
+ )
+
+ // proposalId, filePath, currentState, contextPart, replacements.Replacements)
if !allSucceeded {
fmt.Println("Failed replacements:")
@@ -406,7 +423,7 @@ func BuildPlan(params *types.BuildParams, onStream types.OnStreamFunc) error {
}
handleErrorRetry(
- fmt.Errorf("failed replacements for file '%s' after %d retries", filePath, numReplacementsRetry),
+ nil, // no error -- if we reach MAX_REPLACEMENT_RETRIES, we just ignore the error and continue
false,
true,
planResult,
@@ -444,7 +461,22 @@ func BuildPlan(params *types.BuildParams, onStream types.OnStreamFunc) error {
return nil
}
-func getPlanResult(proposalId, filePath, currentState string, contextPart *shared.ModelContextPart, replacements []*shared.Replacement) (*shared.PlanResult, bool) {
+type planResultParams struct {
+ proposalId string
+ filePath string
+ currentState string
+ contextPart *shared.ModelContextPart
+ replacements []*shared.Replacement
+ fileBlock string
+}
+
+func getPlanResult(params planResultParams) (*shared.PlanResult, bool) {
+ proposalId := params.proposalId
+ filePath := params.filePath
+ currentState := params.currentState
+ contextPart := params.contextPart
+ replacements := params.replacements
+
updated := currentState
sort.Slice(replacements, func(i, j int) bool {
@@ -453,38 +485,24 @@ func getPlanResult(proposalId, filePath, currentState string, contextPart *share
return iIdx < jIdx
})
- allSucceeded := true
-
- lastInsertedIdx := 0
- for _, replacement := range replacements {
- pre := updated[:lastInsertedIdx]
- sub := updated[lastInsertedIdx:]
- originalIdx := strings.Index(sub, replacement.Old)
-
- if originalIdx == -1 {
- allSucceeded = false
- replacement.Failed = true
- } else {
- replaced := strings.Replace(sub, replacement.Old, replacement.New, 1)
-
- // 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)
-
- updated = pre + replaced
- lastInsertedIdx = lastInsertedIdx + originalIdx + len(replacement.New)
- }
-
- }
+ _, allSucceeded := shared.ApplyReplacements(currentState, replacements, true)
var contextSha string
if contextPart != nil {
contextSha = contextPart.Sha
}
+ for _, replacement := range replacements {
+ replacementUUID, err := uuid.NewRandom()
+ if err != nil {
+ fmt.Printf("Failed to generate replacement id: %v\n", err)
+ return nil, false
+ }
+ replacement.Id = replacementUUID.String()
+ }
+
return &shared.PlanResult{
+ Content: params.fileBlock,
ProposalId: proposalId,
Path: filePath,
Replacements: replacements,
diff --git a/server/model/proposal/create.go b/server/model/proposal/create.go
index 1b639e23..0d4a49bc 100644
--- a/server/model/proposal/create.go
+++ b/server/model/proposal/create.go
@@ -173,9 +173,11 @@ func CreateProposal(req shared.PromptRequest, onStream types.OnStreamFunc) error
replyInfo := shared.NewReplyInfo()
modelReq := openai.ChatCompletionRequest{
- Model: model.PlannerModel,
- Messages: messages,
- Stream: true,
+ Model: model.PlannerModel,
+ Messages: messages,
+ Stream: true,
+ Temperature: 0.6,
+ TopP: 0.7,
}
stream, err := model.Client.CreateChatCompletionStream(ctx, modelReq)
diff --git a/shared/plan_result.go b/shared/plan_result.go
index 47ca71a1..bfd84ffe 100644
--- a/shared/plan_result.go
+++ b/shared/plan_result.go
@@ -1,14 +1,5 @@
package shared
-type Replacement struct {
- Old string `json:"old"`
- New string `json:"new"`
- Summary string `json:"summary"`
- Failed bool `json:"failed"`
- RejectedAt string `json:"rejectedAt"`
- ResolvedAt string `json:"resolvedAt"`
-}
-
type PlanResult struct {
ProposalId string `json:"proposalId"`
Path string `json:"path"`