Skip to content

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

working on apply cmd file consistency and git integration, plus some basis for changes ui, other fixes and improvements

Dane Schneidera6c966b5747d
diff --git a/cli/cmd/apply.go b/cli/cmd/apply.go
index e7e9cc36..40685d2a 100644
--- a/cli/cmd/apply.go
+++ b/cli/cmd/apply.go
@@ -1,6 +1,8 @@
package cmd
import (
+ "crypto/sha256"
+ "encoding/hex"
"fmt"
"os"
"path/filepath"
@@ -45,51 +47,122 @@ func apply(cmd *cobra.Command, args []string) error {
return fmt.Errorf("error: plan with name '%+v' does not exist", name)
}
- // isRepo := lib.CwdIsGitRepo()
+ appliedAny := false
+ currentPlanFiles, planResByPath, _, err := lib.GetCurrentPlanStateWithContext()
- // if isRepo {
+ // check if any files have been modified since the plan result was generated
- // planState, err := lib.GetPlanState()
- // if err != nil {
- // return fmt.Errorf("error loading plan state: %v", err)
- // }
+ pathsRemoved := []string{}
+ pathsOutdated := []string{}
- // }
+ for path := range currentPlanFiles.Files {
+ contextSha := currentPlanFiles.ContextShas[path]
- copiedAny := false
- // Enumerate all paths in [draftDir]/files
- filesDir := filepath.Join(rootDir, "draft", "files")
- err = filepath.Walk(filesDir, func(srcPath string, info os.FileInfo, err error) error {
- if err != nil {
- return err
+ if contextSha == "" {
+ // the path wasn't in context
+ continue
}
- if info.IsDir() {
- return nil
+
+ // 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)
+ } else if err != nil {
+ return fmt.Errorf("failed to check existence of %s: %w", dstPath, err)
}
- // Compute relative path
- relPath, err := filepath.Rel(filesDir, srcPath)
+ // Read the file
+ bytes, err := os.ReadFile(dstPath)
+
if err != nil {
- return err
+ return fmt.Errorf("failed to read %s: %w", dstPath, err)
}
- // Compute destination path
- dstPath := filepath.Join(lib.ProjectRoot, relPath)
+ // Get the sha of the file
+ hash := sha256.Sum256(bytes)
+ fileSha := hex.EncodeToString(hash[:])
+
+ if fileSha != contextSha {
+ pathsOutdated = append(pathsOutdated, path)
+ }
+ }
+
+ if len(pathsRemoved) > 0 || len(pathsOutdated) > 0 {
+ fmt.Println("⚠️ Files in context have been modified since the plan was generated:")
+ for _, path := range pathsRemoved {
+ fmt.Println(" - " + path + " was removed")
+ }
+ for _, path := range pathsOutdated {
+ fmt.Println(" - " + path + " was modified")
+ }
+ os.Exit(0)
+ }
+
+ isRepo := lib.CwdIsGitRepo()
+
+ hasUncommittedChanges := false
+ if isRepo {
+ // Check if there are any uncommitted changes
+ hasUncommittedChanges, err = lib.CheckUncommittedChanges()
- // Copy the file
- err = lib.CopyFile(srcPath, dstPath)
if err != nil {
- return fmt.Errorf("failed to copy %s to %s: %w", srcPath, dstPath, err)
+ return fmt.Errorf("error checking for uncommitted changes: %w", err)
+ }
+
+ if 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)
+ }
}
- copiedAny = true
- return nil
- })
+ }
if err != nil {
- return fmt.Errorf("error processing files: %v", err)
+ return fmt.Errorf("error getting current plan files: %w", err)
+ }
+
+ for path, content := range currentPlanFiles.Files {
+ // Compute destination path
+ dstPath := filepath.Join(lib.ProjectRoot, path)
+ // Write the file
+ err = os.WriteFile(dstPath, []byte(content), 0644)
+ if err != nil {
+ return fmt.Errorf("failed to write %s: %w", dstPath, err)
+ }
+ appliedAny = true
}
- if copiedAny {
+ if appliedAny {
+ err := lib.SetPendingResultsApplied(planResByPath)
+ if err != nil {
+ return fmt.Errorf("failed to set pending results applied: %w", err)
+ }
+
+ if isRepo {
+ desc, err := lib.GetLatestPlanDescription()
+ if err != nil {
+ return fmt.Errorf("failed to get latest plan description: %w", err)
+ }
+
+ // Commit the changes
+ // After commit, try to pop the stash if one was created
+ if hasUncommittedChanges {
+ err := lib.GitStashPopNoConflict()
+ if err != nil {
+ return fmt.Errorf("failed to pop git stash: %w", err)
+ }
+ }
+ err = lib.GitCommit(lib.ProjectRoot, "🤖 Plandex → "+desc.CommitMsg, true)
+ if err != nil {
+ return fmt.Errorf("failed to commit changes: %w", err)
+ }
+ }
+
fmt.Println("✅ Applied changes")
} else {
return fmt.Errorf("this plan has no changes to apply")
diff --git a/cli/cmd/changes.go b/cli/cmd/changes.go
new file mode 100644
index 00000000..8993ca7e
--- /dev/null
+++ b/cli/cmd/changes.go
@@ -0,0 +1,29 @@
+package cmd
+
+import (
+ "fmt"
+ "os"
+ "plandex/lib"
+
+ "github.com/spf13/cobra"
+)
+
+func init() {
+ RootCmd.AddCommand(changesCmd)
+}
+
+var changesCmd = &cobra.Command{
+ Use: "changes",
+ Short: "View, copy, or manage changes for the current plan",
+ Run: changes,
+}
+
+func changes(cmd *cobra.Command, args []string) {
+
+ err := lib.StartChangesUI()
+
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "Error starting changes UI: %v\n", err)
+ }
+
+}
diff --git a/cli/cmd/diffs.go b/cli/cmd/diffs.go
index 16056e65..9ac05edb 100644
--- a/cli/cmd/diffs.go
+++ b/cli/cmd/diffs.go
@@ -1,126 +1,126 @@
package cmd
-import (
- "fmt"
- "os"
- "os/exec"
- "path/filepath"
- "plandex/lib"
-
- "github.com/spf13/cobra"
-)
-
-const tempBranchName = "pdx_temp"
-
-func init() {
- RootCmd.AddCommand(diffsCmd)
-}
-
-var diffsCmd = &cobra.Command{
- Use: "diffs",
- Aliases: []string{"d"},
- Short: "Show differences for each individual file between plan files and project files",
- Run: diffs,
-}
-
-func diffs(cmd *cobra.Command, args []string) {
- err := showDiffs()
- if err != nil {
- fmt.Println("An error occurred while generating diffs:", err)
- }
-}
-
-func showDiffs() error {
- // Check if git is installed
- if !lib.IsCommandAvailable("git") {
- return fmt.Errorf("git is required to generate diffs")
- }
-
- originalDir, err := os.Getwd()
- if err != nil {
- return fmt.Errorf("error getting current directory: %v", err)
- }
-
- // Create a temporary directory
- tempDir, err := os.MkdirTemp(os.TempDir(), "plandex-diffs-*")
- if err != nil {
- return fmt.Errorf("error creating temp directory: %v", err)
- }
- defer os.RemoveAll(tempDir) // Cleanup temporary directory
-
- // Copy relevant project files to the temporary directory
- paths, err := lib.GetCurrentPlanFilePaths()
- ch := make(chan error)
- for _, filePath := range paths {
- go func(filePath string) {
- ch <- lib.CopyFile(filepath.Join(lib.ProjectRoot, filePath), filepath.Join(tempDir, filePath))
- }(filePath)
- }
-
- for range paths {
- select {
- case err := <-ch:
- if err != nil {
- if !os.IsNotExist(err) {
- return fmt.Errorf("error copying file: %v", err)
- }
- }
- }
- }
-
- // Navigate to the temporary directory
- err = os.Chdir(tempDir)
- if err != nil {
- return fmt.Errorf("error changing to temp directory: %v", err)
- }
- defer os.Chdir(originalDir)
-
- // Initialize a new git repo in the temporary directory
- cmd := exec.Command("git", "init")
- err = cmd.Run()
- if err != nil {
- return fmt.Errorf("error initializing git repo in temp directory: %v", err)
- }
-
- // Add and commit changes in the temporary directory
- cmd = exec.Command("git", "add", ".")
- output, err := cmd.CombinedOutput()
- if err != nil {
- err = fmt.Errorf("error adding changes in temp directory: %v", err)
- fmt.Println(err)
- fmt.Println(string(output))
- }
-
- cmd = exec.Command("git", "commit", "-m", "temp commit", "--allow-empty")
- output, err = cmd.CombinedOutput()
- if err != nil {
- err = fmt.Errorf("error committing changes in temp directory: %v", err)
- fmt.Println(err)
- fmt.Println(string(output))
- }
-
- err = lib.CopyDir(lib.DraftFilesDir, tempDir)
- if err != nil {
- return fmt.Errorf("error copying files to temp directory: %v", err)
- }
-
- cmd = exec.Command("git", "add", ".")
- output, err = cmd.CombinedOutput()
- if err != nil {
- err = fmt.Errorf("error adding changes in temp directory: %v", err)
- fmt.Println(err)
- fmt.Println(string(output))
- }
-
- // Show the diff
- cmd = exec.Command("git", "diff", "--cached")
- cmd.Stdin = os.Stdin
- cmd.Stdout = os.Stdout
- cmd.Stderr = os.Stderr
- err = cmd.Run()
- if err != nil {
- return fmt.Errorf("error showing diffs: %v", err)
- }
-
- return nil
-}
+// import (
+// "fmt"
+// "os"
+// "os/exec"
+// "path/filepath"
+// "plandex/lib"
+
+// "github.com/spf13/cobra"
+// )
+
+// const tempBranchName = "pdx_temp"
+
+// func init() {
+// RootCmd.AddCommand(diffsCmd)
+// }
+
+// var diffsCmd = &cobra.Command{
+// Use: "diffs",
+// Aliases: []string{"d"},
+// Short: "Show differences for each individual file between plan files and project files",
+// Run: diffs,
+// }
+
+// func diffs(cmd *cobra.Command, args []string) {
+// err := showDiffs()
+// if err != nil {
+// fmt.Println("An error occurred while generating diffs:", err)
+// }
+// }
+
+// func showDiffs() error {
+// // Check if git is installed
+// if !lib.IsCommandAvailable("git") {
+// return fmt.Errorf("git is required to generate diffs")
+// }
+
+// originalDir, err := os.Getwd()
+// if err != nil {
+// return fmt.Errorf("error getting current directory: %v", err)
+// }
+
+// // Create a temporary directory
+// tempDir, err := os.MkdirTemp(os.TempDir(), "plandex-diffs-*")
+// if err != nil {
+// return fmt.Errorf("error creating temp directory: %v", err)
+// }
+// defer os.RemoveAll(tempDir) // Cleanup temporary directory
+
+// // Copy relevant project files to the temporary directory
+// paths, err := lib.GetCurrentPlanFilePaths()
+// ch := make(chan error)
+// for _, filePath := range paths {
+// go func(filePath string) {
+// ch <- lib.CopyFile(filepath.Join(lib.ProjectRoot, filePath), filepath.Join(tempDir, filePath))
+// }(filePath)
+// }
+
+// for range paths {
+// select {
+// case err := <-ch:
+// if err != nil {
+// if !os.IsNotExist(err) {
+// return fmt.Errorf("error copying file: %v", err)
+// }
+// }
+// }
+// }
+
+// // Navigate to the temporary directory
+// err = os.Chdir(tempDir)
+// if err != nil {
+// return fmt.Errorf("error changing to temp directory: %v", err)
+// }
+// defer os.Chdir(originalDir)
+
+// // Initialize a new git repo in the temporary directory
+// cmd := exec.Command("git", "init")
+// err = cmd.Run()
+// if err != nil {
+// return fmt.Errorf("error initializing git repo in temp directory: %v", err)
+// }
+
+// // Add and commit changes in the temporary directory
+// cmd = exec.Command("git", "add", ".")
+// output, err := cmd.CombinedOutput()
+// if err != nil {
+// err = fmt.Errorf("error adding changes in temp directory: %v", err)
+// fmt.Println(err)
+// fmt.Println(string(output))
+// }
+
+// cmd = exec.Command("git", "commit", "-m", "temp commit", "--allow-empty")
+// output, err = cmd.CombinedOutput()
+// if err != nil {
+// err = fmt.Errorf("error committing changes in temp directory: %v", err)
+// fmt.Println(err)
+// fmt.Println(string(output))
+// }
+
+// err = lib.CopyDir(lib.DraftFilesDir, tempDir)
+// if err != nil {
+// return fmt.Errorf("error copying files to temp directory: %v", err)
+// }
+
+// cmd = exec.Command("git", "add", ".")
+// output, err = cmd.CombinedOutput()
+// if err != nil {
+// err = fmt.Errorf("error adding changes in temp directory: %v", err)
+// fmt.Println(err)
+// fmt.Println(string(output))
+// }
+
+// // Show the diff
+// cmd = exec.Command("git", "diff", "--cached")
+// cmd.Stdin = os.Stdin
+// cmd.Stdout = os.Stdout
+// cmd.Stderr = os.Stderr
+// err = cmd.Run()
+// if err != nil {
+// return fmt.Errorf("error showing diffs: %v", err)
+// }
+
+// return nil
+// }
diff --git a/cli/cmd/log.go b/cli/cmd/log.go
index cf38cd41..65ef8e6b 100644
--- a/cli/cmd/log.go
+++ b/cli/cmd/log.go
@@ -33,7 +33,7 @@ func runLog(cmd *cobra.Command, args []string) {
case args[0] == "context":
dir = lib.ContextSubdir
case args[0] == "draft":
- dir = lib.DraftSubdir
+ dir = lib.ResultsSubdir
default:
fmt.Fprint(os.Stderr, "Invalid scope. Valid scopes are 'convo', 'context', and 'draft'")
os.Exit(1)
diff --git a/cli/cmd/preview.go b/cli/cmd/preview.go
index 7fe8a56b..6c840f02 100644
--- a/cli/cmd/preview.go
+++ b/cli/cmd/preview.go
@@ -1,83 +1,83 @@
package cmd
-import (
- "bytes"
- "fmt"
- "log"
- "os"
- "os/exec"
- "plandex/lib"
- "strings"
-
- "github.com/spf13/cobra"
-)
-
-func init() {
- RootCmd.AddCommand(checkoutCmd)
-}
-
-var checkoutCmd = &cobra.Command{
- Use: "preview [name]",
- Aliases: []string{"pv"},
- Short: "Preview changes in a new branch",
- Args: cobra.MaximumNArgs(1),
- Run: checkout,
-}
-
-func getCurrentBranch() (string, error) {
- cmd := exec.Command("git", "rev-parse", "--abbrev-ref", "HEAD")
- var out bytes.Buffer
- cmd.Stdout = &out
- err := cmd.Run()
- if err != nil {
- return "", err
- }
- return strings.TrimSpace(out.String()), nil
-}
-
-func checkout(cmd *cobra.Command, args []string) {
- if !lib.IsCommandAvailable("git") {
- log.Fatalln("Error: git is required")
- }
-
- var name string
-
- if len(args) > 0 {
- name = args[0]
- name = strings.TrimSpace(name)
- }
-
- output, err := exec.Command("git", "rev-parse", "--is-inside-work-tree").CombinedOutput()
- if err != nil || strings.TrimSpace(string(output)) != "true" {
- log.Fatalln("Error: please make sure you're inside of a git repository")
- }
-
- if name == "" || name == "current" {
- name = lib.CurrentPlanName
- }
-
- branchName := name
-
- currentBranch, err := getCurrentBranch()
- if err != nil {
- log.Fatalf("Error: could not retrieve current branch: %v\n", err)
- }
-
- if currentBranch == branchName {
- fmt.Printf("Already on branch %s\n", branchName)
- } else {
- _, err = exec.Command("git", "checkout", "-b", branchName).CombinedOutput()
- fmt.Printf("✅ Checked out branch %s\n", branchName)
- if err != nil {
- log.Fatalf("Error: could not checkout to a new branch: %v\n", err)
- }
- }
-
- err = apply(cmd, args)
-
- if err != nil {
- fmt.Fprintln(os.Stderr, "Error committing plan: ", err)
- return
- }
-
-}
+// import (
+// "bytes"
+// "fmt"
+// "log"
+// "os"
+// "os/exec"
+// "plandex/lib"
+// "strings"
+
+// "github.com/spf13/cobra"
+// )
+
+// func init() {
+// RootCmd.AddCommand(checkoutCmd)
+// }
+
+// var checkoutCmd = &cobra.Command{
+// Use: "preview [name]",
+// Aliases: []string{"pv"},
+// Short: "Preview changes in a new branch",
+// Args: cobra.MaximumNArgs(1),
+// Run: checkout,
+// }
+
+// func getCurrentBranch() (string, error) {
+// cmd := exec.Command("git", "rev-parse", "--abbrev-ref", "HEAD")
+// var out bytes.Buffer
+// cmd.Stdout = &out
+// err := cmd.Run()
+// if err != nil {
+// return "", err
+// }
+// return strings.TrimSpace(out.String()), nil
+// }
+
+// func checkout(cmd *cobra.Command, args []string) {
+// if !lib.IsCommandAvailable("git") {
+// log.Fatalln("Error: git is required")
+// }
+
+// var name string
+
+// if len(args) > 0 {
+// name = args[0]
+// name = strings.TrimSpace(name)
+// }
+
+// output, err := exec.Command("git", "rev-parse", "--is-inside-work-tree").CombinedOutput()
+// if err != nil || strings.TrimSpace(string(output)) != "true" {
+// log.Fatalln("Error: please make sure you're inside of a git repository")
+// }
+
+// if name == "" || name == "current" {
+// name = lib.CurrentPlanName
+// }
+
+// branchName := name
+
+// currentBranch, err := getCurrentBranch()
+// if err != nil {
+// log.Fatalf("Error: could not retrieve current branch: %v\n", err)
+// }
+
+// if currentBranch == branchName {
+// fmt.Printf("Already on branch %s\n", branchName)
+// } else {
+// _, err = exec.Command("git", "checkout", "-b", branchName).CombinedOutput()
+// fmt.Printf("✅ Checked out branch %s\n", branchName)
+// if err != nil {
+// log.Fatalf("Error: could not checkout to a new branch: %v\n", err)
+// }
+// }
+
+// err = apply(cmd, args)
+
+// if err != nil {
+// fmt.Fprintln(os.Stderr, "Error committing plan: ", err)
+// return
+// }
+
+// }
diff --git a/cli/cmd/rewind.go b/cli/cmd/rewind.go
index 9d450137..e3b66e4b 100644
--- a/cli/cmd/rewind.go
+++ b/cli/cmd/rewind.go
@@ -45,7 +45,7 @@ func rewind(cmd *cobra.Command, args []string) {
case "context":
dir = lib.ContextSubdir
case "draft":
- dir = lib.DraftSubdir
+ dir = lib.ResultsSubdir
default:
dir = lib.CurrentPlanDir // Rewind the whole plan by default
}
diff --git a/cli/go.mod b/cli/go.mod
index 0304447f..27f92948 100644
--- a/cli/go.mod
+++ b/cli/go.mod
@@ -3,9 +3,10 @@ module plandex
go 1.21.3
require (
- github.com/davecgh/go-spew v1.1.1
+ github.com/charmbracelet/lipgloss v0.7.1
github.com/fatih/color v1.13.0
github.com/looplab/fsm v1.0.1
+ github.com/olekukonko/tablewriter v0.0.5
github.com/spf13/cobra v1.7.0
golang.org/x/term v0.12.0
)
@@ -15,30 +16,35 @@ require (
github.com/andybalholm/cascadia v1.3.1 // indirect
github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
github.com/aymerick/douceur v0.2.0 // indirect
+ github.com/containerd/console v1.0.4-0.20230313162750-1ae8d489ac81 // indirect
github.com/dlclark/regexp2 v1.10.0 // indirect
github.com/google/uuid v1.3.0 // indirect
github.com/gorilla/css v1.0.0 // indirect
github.com/lucasb-eyer/go-colorful v1.2.0 // indirect
github.com/mattn/go-colorable v0.1.12 // indirect
github.com/mattn/go-isatty v0.0.18 // indirect
+ github.com/mattn/go-localereader v0.0.1 // indirect
github.com/microcosm-cc/bluemonday v1.0.21 // indirect
github.com/mitchellh/go-homedir v1.1.0 // indirect
+ github.com/muesli/ansi v0.0.0-20211018074035-2e021307bc4b // indirect
+ github.com/muesli/cancelreader v0.2.2 // indirect
github.com/muesli/reflow v0.3.0 // indirect
github.com/muesli/termenv v0.15.1 // indirect
- github.com/olekukonko/tablewriter v0.0.5 // indirect
github.com/rivo/uniseg v0.4.3 // indirect
github.com/yuin/goldmark v1.5.2 // indirect
github.com/yuin/goldmark-emoji v1.0.1 // indirect
golang.org/x/net v0.7.0 // indirect
+ golang.org/x/sync v0.1.0 // indirect
golang.org/x/sys v0.12.0 // indirect
)
require (
github.com/PuerkitoBio/goquery v1.8.1
github.com/briandowns/spinner v1.23.0
+ github.com/charmbracelet/bubbles v0.16.1
+ github.com/charmbracelet/bubbletea v0.24.2
github.com/charmbracelet/glamour v0.6.0
github.com/charmbracelet/glow v1.5.1
- github.com/dustin/go-humanize v1.0.1
github.com/eiannone/keyboard v0.0.0-20220611211555-0d226195f203
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/mattn/go-runewidth v0.0.15 // indirect
@@ -46,7 +52,7 @@ require (
github.com/plandex/plandex/shared v0.0.0-00010101000000-000000000000
github.com/sashabaranov/go-openai v1.15.1
github.com/spf13/pflag v1.0.5 // indirect
- golang.org/x/text v0.14.0
+ golang.org/x/text v0.14.0 // indirect
)
replace github.com/plandex/plandex/shared => ../shared
diff --git a/cli/go.sum b/cli/go.sum
index dd9cd4d5..e29323b1 100644
--- a/cli/go.sum
+++ b/cli/go.sum
@@ -225,9 +225,13 @@ github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghf
github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/charmbracelet/bubbles v0.7.5/go.mod h1:IRTORFvhEI6OUH7WhN2Ks8Z8miNGimk1BE6cmHijOkM=
github.com/charmbracelet/bubbles v0.15.0/go.mod h1:Y7gSFbBzlMpUDR/XM9MhZI374Q+1p1kluf1uLl8iK74=
+github.com/charmbracelet/bubbles v0.16.1 h1:6uzpAAaT9ZqKssntbvZMlksWHruQLNxg49H5WdeuYSY=
+github.com/charmbracelet/bubbles v0.16.1/go.mod h1:2QCp9LFlEsBQMvIYERr7Ww2H2bA7xen1idUDIzm/+Xc=
github.com/charmbracelet/bubbletea v0.12.2/go.mod h1:3gZkYELUOiEUOp0bTInkxguucy/xRbGSOcbMs1geLxg=
github.com/charmbracelet/bubbletea v0.23.1/go.mod h1:JAfGK/3/pPKHTnAS8JIE2u9f61BjWTQY57RbT25aMXU=
github.com/charmbracelet/bubbletea v0.23.2/go.mod h1:FaP3WUivcTM0xOKNmhciz60M6I+weYLF76mr1JyI7sM=
+github.com/charmbracelet/bubbletea v0.24.2 h1:uaQIKx9Ai6Gdh5zpTbGiWpytMU+CfsPp06RaW2cx/SY=
+github.com/charmbracelet/bubbletea v0.24.2/go.mod h1:XdrNrV4J8GiyshTtx3DNuYkR1FDaJmO3l2nejekbsgg=
github.com/charmbracelet/charm v0.8.7/go.mod h1:ApJYwJljEjODkOYJgFDzbUqztLrCWQct9zyPD+xcVr4=
github.com/charmbracelet/glamour v0.6.0 h1:wi8fse3Y7nfcabbbDuwolqTqMQPMnVPeZhDM273bISc=
github.com/charmbracelet/glamour v0.6.0/go.mod h1:taqWV4swIMMbWALc0m7AfE9JkPSU8om2538k9ITBxOc=
@@ -235,6 +239,8 @@ github.com/charmbracelet/glow v1.5.1 h1:o1mwT4xXXpkfUhJG6euQayNxLZf9yKctOCNHLztr
github.com/charmbracelet/glow v1.5.1/go.mod h1:rGgop0a2/4gXWiAxUW1iEQseoE+9Ctpb7M4sM9cY9CU=
github.com/charmbracelet/harmonica v0.2.0/go.mod h1:KSri/1RMQOZLbw7AHqgcBycp8pgJnQMYYT8QZRqZ1Ao=
github.com/charmbracelet/lipgloss v0.6.0/go.mod h1:tHh2wr34xcHjC2HCXIlGSG1jaDF0S0atAUvBMP6Ppuk=
+github.com/charmbracelet/lipgloss v0.7.1 h1:17WMwi7N1b1rVWOjMT+rCh7sQkvDU75B2hbZpc5Kc1E=
+github.com/charmbracelet/lipgloss v0.7.1/go.mod h1:yG0k3giv8Qj8edTCbbg6AlQ5e8KNWpFujkNawKNhE2c=
github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI=
github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU=
@@ -252,6 +258,8 @@ github.com/cncf/xds/go v0.0.0-20211001041855-01bcc9b48dfe/go.mod h1:eXthEFrGJvWH
github.com/cncf/xds/go v0.0.0-20211011173535-cb28da3451f1/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs=
github.com/containerd/console v1.0.1/go.mod h1:XUsP6YE/mKtz6bxc+I8UiKKTP04qjQL4qcS3XoQ5xkw=
github.com/containerd/console v1.0.3/go.mod h1:7LqA/THxQ86k76b8c/EMSiaJ3h1eZkMkXar0TQ1gf3U=
+github.com/containerd/console v1.0.4-0.20230313162750-1ae8d489ac81 h1:q2hJAaP1k2wIvVRd/hEHD7lacgqrCPS+k8g1MndzfWY=
+github.com/containerd/console v1.0.4-0.20230313162750-1ae8d489ac81/go.mod h1:YynlIjWYF8myEu6sdkwKIvGQq+cOckRm6So2avqoYAk=
github.com/coreos/bbolt v1.3.2/go.mod h1:iRUV2dpdMOn7Bo10OQBFzIJO9kkE559Wcmn+qkEiiKk=
github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE=
github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk=
@@ -272,8 +280,6 @@ github.com/dlclark/regexp2 v1.10.0 h1:+/GIL799phkJqYW+3YbOd8LCcbHzT0Pbo8zl70MHsq
github.com/dlclark/regexp2 v1.10.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk=
github.com/dustin/go-humanize v1.0.1-0.20200219035652-afde56e7acac/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk=
-github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
-github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
github.com/eiannone/keyboard v0.0.0-20220611211555-0d226195f203 h1:XBBHcIb256gUJtLmY22n99HaZTz+r2Z51xUPi01m3wg=
github.com/eiannone/keyboard v0.0.0-20220611211555-0d226195f203/go.mod h1:E1jcSv8FaEny+OP/5k9UxZVw9YFWGj7eI4KR/iOBqCg=
github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
@@ -495,6 +501,7 @@ github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/
github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.18 h1:DOKFKCQ7FNG2L1rbrmstDN4QVRdS89Nkh85u68Uwp98=
github.com/mattn/go-isatty v0.0.18/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
+github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4=
github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88=
github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
github.com/mattn/go-runewidth v0.0.10/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk=
@@ -525,7 +532,9 @@ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJ
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
+github.com/muesli/ansi v0.0.0-20211018074035-2e021307bc4b h1:1XF24mVaiu7u+CFywTdcDo2ie1pzzhwjt6RHqzpMU34=
github.com/muesli/ansi v0.0.0-20211018074035-2e021307bc4b/go.mod h1:fQuZ0gauxyBcmsdE3ZT4NasjaRdxmbCS0jRHsrWu3Ho=
+github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=
github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=
github.com/muesli/gitcha v0.2.0/go.mod h1:Ri8m9TZS4+ORG4JVmVKUQcWZuxDvUW3UKxMdQfzG2zI=
github.com/muesli/go-app-paths v0.2.1/go.mod h1:SxS3Umca63pcFcLtbjVb+J0oD7cl4ixQWoBKhGEtEho=
@@ -828,6 +837,7 @@ golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJ
golang.org/x/sync v0.0.0-20220601150217-0de741cfad7f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220929204114-8fcdb60fdcc0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o=
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
@@ -918,6 +928,7 @@ golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.0.0-20220728004956-3c1f35247d10/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220908164124-27713097b956/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
diff --git a/cli/lib/api_propose.go b/cli/lib/api_propose.go
index e93d2f96..ed7a24ae 100644
--- a/cli/lib/api_propose.go
+++ b/cli/lib/api_propose.go
@@ -16,50 +16,33 @@ import (
func (api *API) Propose(prompt, parentProposalId, rootId string, onStream types.OnStreamPlan) (*shared.PromptRequest, error) {
serverUrl := apiHost + "/proposal"
- // Channels to receive data and errors
- contextChan := make(chan shared.ModelContext, 1) // Buffered channels to prevent deadlock
- contextErrChan := make(chan error, 1)
-
- conversationChan := make(chan []shared.ConversationMessage, 1)
- conversationErrChan := make(chan error, 1)
-
- planChan := make(chan shared.CurrentPlanFiles, 1)
- planErrChan := make(chan error, 1)
-
- summaryChan := make(chan []shared.ConversationSummary, 1)
- summaryErrChan := make(chan error, 1)
-
- // Goroutine for loading context
- go func() {
- modelContext, err := GetAllContext(false)
- if err != nil {
- fmt.Println("Error loading context:" + err.Error())
- contextErrChan <- err
- return
- }
- contextChan <- modelContext
- }()
+ errCh := make(chan error, 1)
+ contextCh := make(chan shared.ModelContext, 1)
+ conversationCh := make(chan []*shared.ConversationMessage, 1)
+ planFilesCh := make(chan *shared.CurrentPlanFiles, 1)
+ summaryCh := make(chan []*shared.ConversationSummary, 1)
// Goroutine for loading conversation
go func() {
conversation, err := LoadConversation()
if err != nil {
fmt.Println("Error loading conversation")
- conversationErrChan <- err
+ errCh <- err
return
}
- conversationChan <- conversation
+ conversationCh <- conversation
}()
- // Goroutine for loading plan
+ // Goroutine for loading plan files and context
go func() {
- plan, err := getCurrentPlanFiles()
+ planFiles, _, modelContext, err := GetCurrentPlanStateWithContext()
if err != nil {
fmt.Println("Error loading plan")
- planErrChan <- err
+ errCh <- err
return
}
- planChan <- plan
+ planFilesCh <- planFiles
+ contextCh <- modelContext
}()
// Goroutine for loading summaries
@@ -67,45 +50,26 @@ func (api *API) Propose(prompt, parentProposalId, rootId string, onStream types.
summaries, err := LoadSummaries()
if err != nil {
fmt.Println("Error loading summaries")
- summaryErrChan <- err
+ errCh <- err
return
}
- summaryChan <- summaries
+ summaryCh <- summaries
}()
var modelContext shared.ModelContext
- var currentPlan shared.CurrentPlanFiles
- var conversation []shared.ConversationMessage
- var summaries []shared.ConversationSummary
- var err error
-
- // Using select to receive from either data or error channel for context
- select {
- case modelContext = <-contextChan:
- case err = <-contextErrChan:
- return nil, err
- }
-
- // Using select to receive from either data or error channel for conversation
- select {
- case conversation = <-conversationChan:
- case err = <-conversationErrChan:
- return nil, err
- }
-
- // Using select to receive from either data or error channel for plan
- select {
- case plan := <-planChan:
- currentPlan = plan
- case err = <-planErrChan:
- return nil, err
- }
-
- // Using select to receive from either data or error channel for summaries
- select {
- case summaries = <-summaryChan:
- case err = <-summaryErrChan:
- return nil, err
+ var currentPlanFiles *shared.CurrentPlanFiles
+ var conversation []*shared.ConversationMessage
+ var summaries []*shared.ConversationSummary
+
+ for i := 0; i < 4; i++ {
+ select {
+ case err := <-errCh:
+ return nil, fmt.Errorf("error loading plan data: %v", err)
+ case modelContext = <-contextCh:
+ case conversation = <-conversationCh:
+ case currentPlanFiles = <-planFilesCh:
+ case summaries = <-summaryCh:
+ }
}
payload := shared.PromptRequest{
@@ -113,7 +77,7 @@ func (api *API) Propose(prompt, parentProposalId, rootId string, onStream types.
ModelContext: modelContext,
Conversation: conversation,
ConversationSummaries: summaries,
- CurrentPlan: currentPlan,
+ CurrentPlan: currentPlanFiles,
ParentProposalId: parentProposalId,
RootProposalId: rootId,
}
diff --git a/cli/lib/changes_ui.go b/cli/lib/changes_ui.go
new file mode 100644
index 00000000..fe1a9fb8
--- /dev/null
+++ b/cli/lib/changes_ui.go
@@ -0,0 +1,149 @@
+package lib
+
+import (
+ "fmt"
+
+ "github.com/charmbracelet/bubbles/help"
+ bubbleKey "github.com/charmbracelet/bubbles/key"
+ tea "github.com/charmbracelet/bubbletea"
+ "github.com/charmbracelet/lipgloss"
+ "github.com/plandex/plandex/shared"
+)
+
+type keymap = struct {
+ up, down, reject, copy, applyAll, quit bubbleKey.Binding
+}
+
+type changesUIModel struct {
+ help help.Model
+ keymap keymap
+ selectedFileIndex int
+ selectedReplacementIndex int
+ resultsByPath shared.PlanResultsByPath
+ currentPlanFiles *shared.CurrentPlanFiles
+}
+
+func StartChangesUI() error {
+ if _, err := tea.NewProgram(initialModel(), tea.WithAltScreen()).Run(); err != nil {
+ return fmt.Errorf("error running changes UI: %v", err)
+ }
+ return nil
+}
+
+func (m changesUIModel) Init() tea.Cmd {
+ return nil
+}
+
+func initialModel() changesUIModel {
+ errChn := make(chan error, 1)
+ planResByPathChn := make(chan shared.PlanResultsByPath, 1)
+ currentPlanFilesChn := make(chan *shared.CurrentPlanFiles, 1)
+
+ var resultsByPath shared.PlanResultsByPath
+ var currentPlanFiles *shared.CurrentPlanFiles
+
+ go func() {
+ planResByPath, err := getPlanResultsByPath()
+ if err != nil {
+ errChn <- fmt.Errorf("error getting plan results: %v", err)
+ return
+ }
+ planResByPathChn <- planResByPath
+ }()
+
+ go func() {
+ var err error
+ currentPlanFiles, err = GetCurrentPlanFiles()
+ if err != nil {
+ errChn <- fmt.Errorf("error getting current plan files: %v", err)
+ return
+ }
+ currentPlanFilesChn <- 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:
+ }
+ }
+
+ return changesUIModel{
+ selectedFileIndex: 0,
+ selectedReplacementIndex: 0,
+ resultsByPath: resultsByPath,
+ help: help.New(),
+ keymap: keymap{
+ up: bubbleKey.NewBinding(
+ bubbleKey.WithKeys("up"),
+ bubbleKey.WithHelp("up", "prev change"),
+ ),
+
+ down: bubbleKey.NewBinding(
+ bubbleKey.WithKeys("down"),
+ bubbleKey.WithHelp("down", "next change"),
+ ),
+
+ reject: bubbleKey.NewBinding(
+ bubbleKey.WithKeys("r"),
+ bubbleKey.WithHelp("r", "reject change"),
+ ),
+
+ copy: bubbleKey.NewBinding(
+ bubbleKey.WithKeys("c"),
+ bubbleKey.WithHelp("c", "copy change"),
+ ),
+
+ applyAll: bubbleKey.NewBinding(
+ bubbleKey.WithKeys("ctrl+a"),
+ bubbleKey.WithHelp("ctrl+a", "apply all changes"),
+ ),
+
+ quit: bubbleKey.NewBinding(
+ bubbleKey.WithKeys("esc"),
+ bubbleKey.WithHelp("esc", "quit"),
+ ),
+ },
+ }
+}
+
+func (m changesUIModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
+ switch msg := msg.(type) {
+
+ case tea.KeyMsg:
+
+ switch {
+
+ case bubbleKey.Matches(msg, m.keymap.up):
+
+ case bubbleKey.Matches(msg, m.keymap.down):
+
+ case bubbleKey.Matches(msg, m.keymap.reject):
+
+ case bubbleKey.Matches(msg, m.keymap.applyAll):
+
+ case bubbleKey.Matches(msg, m.keymap.copy):
+
+ case bubbleKey.Matches(msg, m.keymap.quit):
+ return m, tea.Quit
+
+ }
+ }
+
+ return m, nil
+}
+
+func (m changesUIModel) View() string {
+ help := m.help.ShortHelpView([]bubbleKey.Binding{
+ m.keymap.up,
+ m.keymap.down,
+ m.keymap.applyAll,
+ m.keymap.quit,
+ })
+
+ var views []string
+
+ return lipgloss.JoinHorizontal(lipgloss.Top, views...) + "\n\n" + help
+}
diff --git a/cli/lib/context_get.go b/cli/lib/context_get.go
index e3e4d493..ce8bc777 100644
--- a/cli/lib/context_get.go
+++ b/cli/lib/context_get.go
@@ -11,14 +11,14 @@ import (
"github.com/plandex/plandex/shared"
)
-func GetAllContext(metaOnly bool) ([]*shared.ModelContextPart, error) {
+func GetAllContext(metaOnly bool) (shared.ModelContext, error) {
files, err := os.ReadDir(ContextSubdir)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to read context directory: %v", err)
return nil, err
}
- var context []*shared.ModelContextPart
+ var context shared.ModelContext
for _, file := range files {
filename := file.Name()
diff --git a/cli/lib/context_load.go b/cli/lib/context_load.go
index e04522f2..f0d84c37 100644
--- a/cli/lib/context_load.go
+++ b/cli/lib/context_load.go
@@ -349,9 +349,16 @@ func MustLoadContext(resources []string, params *types.LoadContextParams) (int,
sha := hex.EncodeToString(hash[:])
ts := shared.StringTs()
+
+ name := SanitizeURL(url)
+ // show the first 20 characters, then ellipsis then the last 20 characters of 'name'
+ if len(name) > 40 {
+ name = name[:20] + "⋯" + name[len(name)-20:]
+ }
+
contextPart := &shared.ModelContextPart{
Type: shared.ContextURLType,
- Name: SanitizeAndClipURL(url, 70),
+ Name: name,
Url: url,
Body: body,
Sha: sha,
diff --git a/cli/lib/conversation.go b/cli/lib/conversation.go
index 28da44e1..f6aa93f7 100644
--- a/cli/lib/conversation.go
+++ b/cli/lib/conversation.go
@@ -14,8 +14,8 @@ import (
openai "github.com/sashabaranov/go-openai"
)
-func LoadConversation() ([]shared.ConversationMessage, error) {
- var messages []shared.ConversationMessage
+func LoadConversation() ([]*shared.ConversationMessage, error) {
+ var messages []*shared.ConversationMessage
files, err := os.ReadDir(ConversationSubdir)
if err != nil {
@@ -46,7 +46,7 @@ func LoadConversation() ([]shared.ConversationMessage, error) {
if strings.HasPrefix(line, "@@@!>user|") {
if currentRole != "" {
// Save the previous message before starting a new one
- messages = append(messages, shared.ConversationMessage{
+ messages = append(messages, &shared.ConversationMessage{
Message: openai.ChatCompletionMessage{
Role: currentRole,
Content: strings.Join(contentBuffer, "\n"),
@@ -70,7 +70,7 @@ func LoadConversation() ([]shared.ConversationMessage, error) {
} else if strings.HasPrefix(line, "@@@!>response|") {
if currentRole != "" {
// Save the previous message before starting a new one
- messages = append(messages, shared.ConversationMessage{
+ messages = append(messages, &shared.ConversationMessage{
Message: openai.ChatCompletionMessage{
Role: currentRole,
Content: strings.Join(contentBuffer, "\n"),
@@ -97,7 +97,7 @@ func LoadConversation() ([]shared.ConversationMessage, error) {
// Add the last message in the file
if currentRole != "" && len(contentBuffer) > 0 {
- messages = append(messages, shared.ConversationMessage{
+ messages = append(messages, &shared.ConversationMessage{
Message: openai.ChatCompletionMessage{
Role: currentRole,
Content: strings.Join(contentBuffer, "\n"),
@@ -113,7 +113,7 @@ func LoadConversation() ([]shared.ConversationMessage, error) {
return messages, nil
}
-func LoadSummaries() ([]shared.ConversationSummary, error) {
+func LoadSummaries() ([]*shared.ConversationSummary, error) {
// check if summaries subdirectory exists
summariesPath := filepath.Join(ConversationSubdir, "summaries")
exists := false
@@ -124,7 +124,7 @@ func LoadSummaries() ([]shared.ConversationSummary, error) {
return nil, err
}
- var summaries []shared.ConversationSummary
+ var summaries []*shared.ConversationSummary
if exists {
files, err := os.ReadDir(summariesPath)
@@ -158,7 +158,7 @@ func LoadSummaries() ([]shared.ConversationSummary, error) {
return nil, fmt.Errorf("failed to parse tokens: %s", err)
}
- summaries = append(summaries, shared.ConversationSummary{
+ summaries = append(summaries, &shared.ConversationSummary{
Summary: summary,
LastMessageTimestamp: timestamp,
Tokens: tokens,
diff --git a/cli/lib/fs.go b/cli/lib/fs.go
index 5ff9ac5d..3e8b3053 100644
--- a/cli/lib/fs.go
+++ b/cli/lib/fs.go
@@ -20,9 +20,8 @@ var CacheDir string
var CurrentPlanName string
var CurrentPlanDir string
-var DraftSubdir string
-var DraftFilesDir string
-var DescriptionsDir string
+var ResultsSubdir string
+var DescriptionsSubdir string
var ConversationSubdir string
var ContextSubdir string
@@ -94,9 +93,8 @@ func LoadCurrentPlan() error {
CurrentPlanName = planSettings.Name
CurrentPlanDir = filepath.Join(PlandexDir, CurrentPlanName)
- DraftSubdir = filepath.Join(CurrentPlanDir, "draft")
- DraftFilesDir = filepath.Join(DraftSubdir, "files")
- DescriptionsDir = filepath.Join(CurrentPlanDir, "descriptions")
+ ResultsSubdir = filepath.Join(CurrentPlanDir, "results")
+ DescriptionsSubdir = filepath.Join(CurrentPlanDir, "descriptions")
ConversationSubdir = filepath.Join(CurrentPlanDir, "conversation")
ContextSubdir = filepath.Join(CurrentPlanDir, "context")
@@ -252,7 +250,7 @@ func CopyDir(srcDir, dstDir string) error {
func GetLatestPlanDescription() (*shared.PlanDescription, error) {
// List files in descriptions directory
- entries, err := os.ReadDir(DescriptionsDir)
+ entries, err := os.ReadDir(DescriptionsSubdir)
if err != nil {
return nil, err
}
@@ -266,7 +264,7 @@ func GetLatestPlanDescription() (*shared.PlanDescription, error) {
}
// Read the contents of the latest file
- bytes, err := os.ReadFile(filepath.Join(DescriptionsDir, latestFile.Name()))
+ bytes, err := os.ReadFile(filepath.Join(DescriptionsSubdir, latestFile.Name()))
if err != nil {
return nil, fmt.Errorf("error reading latest description file: %v", err)
}
diff --git a/cli/lib/git.go b/cli/lib/git.go
index 0273141b..5b692d90 100644
--- a/cli/lib/git.go
+++ b/cli/lib/git.go
@@ -104,6 +104,48 @@ func GitCommit(repoDir, commitMsg string, lockMutex bool) error {
return nil
}
+func CheckUncommittedChanges() (bool, error) {
+ gitMutex.Lock()
+ defer gitMutex.Unlock()
+
+ // Check if there are any changes
+ res, err := exec.Command("git", "status", "--porcelain").CombinedOutput()
+ if err != nil {
+ return false, fmt.Errorf("error checking for uncommitted changes: %v, output: %s", err, string(res))
+ }
+
+ // If there's output, there are uncommitted changes
+ return strings.TrimSpace(string(res)) != "", nil
+}
+
+func GitStashCreate(message string) error {
+ gitMutex.Lock()
+ defer gitMutex.Unlock()
+
+ res, err := exec.Command("git", "stash", "push", "-m", message).CombinedOutput()
+ if err != nil {
+ return fmt.Errorf("error creating git stash: %v, output: %s", err, string(res))
+ }
+
+ return nil
+}
+
+func GitStashPopNoConflict() error {
+ gitMutex.Lock()
+ defer gitMutex.Unlock()
+
+ res, err := exec.Command("git", "stash", "pop", "--quiet", "--theirs").CombinedOutput()
+ if err != nil {
+ if strings.Contains(string(res), "Merge conflict") {
+ // We have a merge conflict but we are choosing to favor committed changes over stash
+ return nil
+ }
+ return fmt.Errorf("error popping git stash: %v, output: %s", err, string(res))
+ }
+
+ return nil
+}
+
func CwdIsGitRepo() bool {
isGitRepo := false
if IsCommandAvailable("git") {
@@ -164,7 +206,7 @@ func GitCommitConvoUpdate(commitMsg string) error {
}
func GitCommitPlanUpdate(commitMsg string) error {
- err := GitAddAndCommit(DraftSubdir, commitMsg)
+ err := GitAddAndCommit(ResultsSubdir, commitMsg)
if err != nil {
return fmt.Errorf("failed to commit files to plan dir: %s", err)
}
diff --git a/cli/lib/plan_files.go b/cli/lib/plan_files.go
index 46426b12..4cc1c9d2 100644
--- a/cli/lib/plan_files.go
+++ b/cli/lib/plan_files.go
@@ -1,135 +1,229 @@
package lib
import (
+ "encoding/json"
"fmt"
"os"
"path/filepath"
- "sync"
+ "sort"
+ "strings"
"github.com/plandex/plandex/shared"
)
-type safePlanFiles struct {
- mux sync.Mutex
- data map[string]string
+func GetCurrentPlanFiles() (*shared.CurrentPlanFiles, error) {
+ currentPlanFiles, _, _, err := GetCurrentPlanStateWithContext()
+ return currentPlanFiles, err
}
-func (s *safePlanFiles) Add(key string, value string) {
- s.mux.Lock()
- s.data[key] = value
- s.mux.Unlock()
-}
+func GetCurrentPlanStateWithContext() (*shared.CurrentPlanFiles, shared.PlanResultsByPath, shared.ModelContext, error) {
+ errCh := make(chan error, 1)
+ planResByPathCh := make(chan shared.PlanResultsByPath, 1)
+ contextCh := make(chan shared.ModelContext, 1)
-var planFiles safePlanFiles
+ go func() {
+ modelContext, err := GetAllContext(false)
+ if err != nil {
+ errCh <- fmt.Errorf("error loading context: %v", err)
+ return
+ }
+ contextCh <- modelContext
+ }()
-func worker(dir string, srcPath string, info os.FileInfo, err error, doneCh chan<- error) {
- // Compute relative path
- relPath, err := filepath.Rel(dir, srcPath)
- if err != nil {
- doneCh <- err
- return
+ go func() {
+ planResByPath, err := getPlanResultsByPath()
+ if err != nil {
+ errCh <- fmt.Errorf("error getting plan results: %v", err)
+ return
+ }
+ planResByPathCh <- planResByPath
+ }()
+
+ var planResByPath shared.PlanResultsByPath
+ var modelContext shared.ModelContext
+
+ for i := 0; i < 2; i++ {
+ select {
+ case err := <-errCh:
+ return nil, nil, nil, err
+ case planResByPath = <-planResByPathCh:
+ case modelContext = <-contextCh:
+ }
}
- // Read file content
- content, err := os.ReadFile(srcPath)
- if err != nil {
- doneCh <- err
- return
- }
+ files := make(map[string]string)
+ shas := make(map[string]string)
- // Add file content to planFiles with relative path as key
- planFiles.Add(relPath, string(content))
- doneCh <- nil
-}
+ for _, contextPart := range modelContext {
+ if contextPart.FilePath == "" {
+ continue
+ }
+
+ // fmt.Printf("contextPart: %s\n", contextPart.FilePath)
-func getCurrentPlanFiles() (shared.CurrentPlanFiles, error) {
- planFiles.data = make(map[string]string)
+ _, hasPath := planResByPath[contextPart.FilePath]
- _, err := os.Stat(DraftFilesDir)
- filesDirExists := !os.IsNotExist(err)
+ // fmt.Printf("hasPath: %v\n", hasPath)
- numFiles := 0
+ if hasPath {
+ files[contextPart.FilePath] = contextPart.Body
+ shas[contextPart.FilePath] = contextPart.Sha
+ }
+ }
- if filesDirExists {
- doneCh := make(chan error)
+ for path, planResults := range planResByPath {
+ updated := files[path]
+ lastInsertedIdx := 0
- if filesDirExists {
- // Enumerate all paths in [planDir]/files
- err = filepath.Walk(DraftFilesDir, func(srcPath string, info os.FileInfo, err error) error {
- if err != nil {
- return err
+ // fmt.Printf("path: %s\n", path)
+ // fmt.Printf("updated: %s\n", updated)
+
+ for _, planRes := range planResults {
+ if !planRes.IsPending() {
+ continue
+ }
+
+ if planRes.Content != "" {
+ if updated != "" {
+ return nil, nil, nil, fmt.Errorf("plan updates out of order: %s", path)
}
- if info.IsDir() {
- return nil
+
+ updated = planRes.Content
+ files[path] = updated
+ continue
+ }
+
+ contextSha := shas[path]
+ if contextSha != "" && planRes.ContextSha != contextSha {
+ return nil, nil, nil, fmt.Errorf("result sha doesn't match context sha: %s", path)
+ }
+
+ if len(planRes.Replacements) == 0 {
+ continue
+ }
+
+ for i, replacement := range planRes.Replacements {
+ if replacement.Failed || replacement.RejectedAt != "" {
+ continue
}
- numFiles++
- go worker(DraftFilesDir, srcPath, info, err, doneCh)
- return nil
- })
- }
- numFinished := 0
- for numFinished < numFiles {
- select {
- case err := <-doneCh:
- if err != nil {
- fmt.Fprintf(os.Stderr, "Error processing files: %v", err)
- return shared.CurrentPlanFiles{}, err
+ pre := updated[:lastInsertedIdx]
+ sub := updated[lastInsertedIdx:]
+ originalIdx := strings.Index(sub, replacement.Old)
+
+ if originalIdx == -1 {
+ // replacement failed, return error (checked server-side so this shouldn't happen)
+
+ // fmt.Printf("replacement failed. path: %s, ts: %s, i: %d", path, planRes.Ts, i)
+ // fmt.Println("Replacement: " + replacement.Old + " -> " + replacement.New)
+ // fmt.Println("Pre: " + pre)
+ // fmt.Println("Sub: " + sub)
+ // fmt.Println("Idx: " + fmt.Sprintf("%d", lastInsertedIdx))
+ // fmt.Println("Updated: " + updated)
+
+ return nil, nil, nil, fmt.Errorf("replacement failed. path: %s, ts: %s, i: %d", path, planRes.Ts, i)
+ } else {
+ replaced := strings.Replace(sub, replacement.Old, replacement.New, 1)
+ updated = pre + replaced
+ lastInsertedIdx = lastInsertedIdx + originalIdx + len(replacement.New)
}
- numFinished++
}
}
+
+ files[path] = updated
}
- return shared.CurrentPlanFiles{Files: planFiles.data}, nil
+ return &shared.CurrentPlanFiles{Files: files, ContextShas: shas}, planResByPath, modelContext, nil
}
-func GetCurrentPlanFilePaths() ([]string, error) {
- _, err := os.Stat(DraftFilesDir)
- filesDirExists := !os.IsNotExist(err)
+func getPlanResultsByPath() (shared.PlanResultsByPath, error) {
+ resByPath := make(shared.PlanResultsByPath)
- filePaths := make([]string, 0)
+ _, err := os.Stat(ResultsSubdir)
+ resDirExists := !os.IsNotExist(err)
- if filesDirExists {
- // Enumerate all paths in [planDir]/files
- err = filepath.Walk(DraftFilesDir, func(srcPath string, info os.FileInfo, err error) error {
- if err != nil {
- return err
- }
-
- if info.IsDir() {
- return nil
- }
+ if !resDirExists {
+ return resByPath, nil
+ }
- relPath, err := filepath.Rel(DraftFilesDir, srcPath)
- if err != nil {
- return err
- }
+ // 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)
+ }
- filePaths = append(filePaths, relPath)
+ if info.IsDir() {
return nil
- })
+ }
+ bytes, err := os.ReadFile(path)
if err != nil {
- fmt.Fprintf(os.Stderr, "Error listing files: %v", err)
- return []string{}, err
+ return fmt.Errorf("error reading file %s: %v", path, err)
}
+
+ var planRes shared.PlanResult
+ err = json.Unmarshal(bytes, &planRes)
+ if err != nil {
+ return fmt.Errorf("error unmarshalling plan result JSON from file %s: %v", path, err)
+ }
+
+ resByPath[planRes.Path] = append(resByPath[planRes.Path], &planRes)
+
+ return nil
+ })
+
+ if err != nil {
+ return nil, fmt.Errorf("error reading results dir: %v", err)
+ }
+
+ // sort results by timestamp
+ for _, results := range resByPath {
+ sort.Slice(results, func(i, j int) bool {
+ return results[i].Ts < results[j].Ts
+ })
}
- return filePaths, nil
+ return resByPath, nil
}
-func isFilePathInPlan(filePath string) bool {
- filePaths, err := GetCurrentPlanFilePaths()
- if err != nil {
- return false
+func SetPendingResultsApplied(planResByPath shared.PlanResultsByPath) error {
+ ts := shared.StringTs()
+ planResByPath.SetApplied(ts)
+ numPending := planResByPath.NumPending()
+
+ errCh := make(chan error, numPending)
+
+ for _, planResults := range planResByPath {
+ for _, planResult := range planResults {
+ if !planResult.IsPending() {
+ continue
+ }
+
+ go func(planResult *shared.PlanResult) {
+ bytes, err := json.Marshal(planResult)
+ if err != nil {
+ errCh <- fmt.Errorf("error marshalling plan result: %v", err)
+ return
+ }
+
+ err = os.WriteFile(filepath.Join(ResultsSubdir, planResult.Path, planResult.Ts), bytes, 0644)
+ if err != nil {
+ errCh <- fmt.Errorf("error writing plan result: %v", err)
+ return
+ }
+
+ errCh <- nil
+
+ }(planResult)
+ }
}
- for _, path := range filePaths {
- if path == filePath {
- return true
+ for i := 0; i < numPending; i++ {
+ err := <-errCh
+ if err != nil {
+ return fmt.Errorf("error wrting plan result file after SetApplied: %v", err)
}
}
- return false
+ return nil
}
diff --git a/cli/lib/proposal.go b/cli/lib/proposal.go
index fcffb795..eec20db9 100644
--- a/cli/lib/proposal.go
+++ b/cli/lib/proposal.go
@@ -306,12 +306,12 @@ func Propose(prompt string) error {
return
}
- err = os.MkdirAll(DescriptionsDir, os.ModePerm)
+ err = os.MkdirAll(DescriptionsSubdir, os.ModePerm)
if err != nil {
onError(fmt.Errorf("failed to create plan descriptions directory: %s", err))
return
}
- descriptionsPath := filepath.Join(DescriptionsDir, desc.ResponseTimestamp+".json")
+ descriptionsPath := filepath.Join(DescriptionsSubdir, desc.ResponseTimestamp+".json")
err = os.WriteFile(descriptionsPath, bytes, 0644)
if err != nil {
onError(fmt.Errorf("failed to write plan description to file: %s", err))
@@ -356,7 +356,7 @@ func Propose(prompt string) error {
return
}
- err := writePlanFile(content)
+ err := writePlanRes(content)
if err != nil {
onError(fmt.Errorf("failed to write plan file: %s", err))
diff --git a/cli/lib/stream.go b/cli/lib/stream.go
index 01670283..5c28a284 100644
--- a/cli/lib/stream.go
+++ b/cli/lib/stream.go
@@ -26,30 +26,23 @@ func updateTokenCounts(content string, numStreamedTokensByPath map[string]int, f
return nil
}
-func writePlanFile(content string) error {
- var planFile shared.PlanFile
- err := json.Unmarshal([]byte(content), &planFile)
+func writePlanRes(content string) error {
+ var planRes shared.PlanResult
+ err := json.Unmarshal([]byte(content), &planRes)
if err != nil {
return fmt.Errorf("failed to unmarshal plan file: %s", err)
}
- // spew.Dump(planFile)
-
- writeToPath := filepath.Join(DraftFilesDir, planFile.Path)
-
- // fmt.Printf("Writing plan file '%s'...\n", writeToPath)
-
- err = os.MkdirAll(filepath.Dir(writeToPath), os.ModePerm)
+ path := filepath.Join(ResultsSubdir, planRes.Path, planRes.Ts+".json")
+ err = os.MkdirAll(filepath.Dir(path), os.ModePerm)
if err != nil {
- fmt.Printf("failed to create directory: %s", err)
- return fmt.Errorf("failed to create directory: %s", err)
-
+ return fmt.Errorf("failed to create directory: %s", err)
}
- err = os.WriteFile(writeToPath, []byte(planFile.Content), 0644)
+ err = os.WriteFile(path, []byte(content), 0644)
if err != nil {
- fmt.Printf("failed to write plan file '%s': %v", writeToPath, err)
- return fmt.Errorf("failed to write plan file '%s': %v", writeToPath, err)
+ // fmt.Printf("failed to write plan file '%s': %v", path, err)
+ return fmt.Errorf("failed to write plan result '%s': %v", path, err)
}
return nil
diff --git a/cli/lib/term.go b/cli/lib/term.go
index 41a38868..3aa2328d 100644
--- a/cli/lib/term.go
+++ b/cli/lib/term.go
@@ -14,11 +14,11 @@ import (
var cmdDesc = map[string][2]string{
"new": {"", "start a new plan"},
// "current": {"c", "show current plan"},
- "cd": {"", "set current plan by name or index"},
- "load": {"l", "load files/directories/urls/notes or pipe data into context"},
- "tell": {"t", "describe a task, ask a question, or chat"},
- "diffs": {"d", "show diffs between plan and project files"},
- "preview": {"pv", "preview the plan in a branch"},
+ "cd": {"", "set current plan by name or index"},
+ "load": {"l", "load files/directories/urls/notes or pipe data into context"},
+ "tell": {"t", "describe a task, ask a question, or chat"},
+ // "diffs": {"d", "show diffs between plan and project files"},
+ // "preview": {"pv", "preview the plan in a branch"},
"apply": {"ap", "apply the plan to your project files"},
"continue": {"c", "continue the plan"},
"status": {"s", "show status of the plan"},
diff --git a/cli/lib/url.go b/cli/lib/url.go
index c294f38d..473b63a3 100644
--- a/cli/lib/url.go
+++ b/cli/lib/url.go
@@ -68,7 +68,7 @@ func ExtractTextualContent(htmlContent string) string {
return doc.Text()
}
-func SanitizeAndClipURL(url string, maxLength int) string {
+func SanitizeURL(url string) string {
// remove protocol portion with a regex
re := regexp.MustCompile(`^.*?://`)
url = re.ReplaceAllString(url, "")
@@ -83,9 +83,6 @@ func SanitizeAndClipURL(url string, maxLength int) string {
sanitized = strings.ReplaceAll(sanitized, "%", "_")
sanitized = strings.ReplaceAll(sanitized, "*", "_")
sanitized = strings.ReplaceAll(sanitized, " ", "_")
- if len(sanitized) > maxLength {
- return sanitized[:maxLength]
- }
return sanitized
}
diff --git a/server/model/prompts/replace.go b/server/model/prompts/replace.go
index 98fc058d..bccac55e 100644
--- a/server/model/prompts/replace.go
+++ b/server/model/prompts/replace.go
@@ -14,7 +14,7 @@ const SysReplace = `
You are an AI replacer. You apply changes from a plan to a given code file using the 'writeReplacements' function. You call 'writeReplacements' with a valid JSON array of replacements.
-Each replacement is an object with two properties: 'old' and 'new'. 'old' is the *exact* old text to replace, and 'new' is the new text to replace it with.
+Each replacement is an object with 3 properties: 'old', 'new', and 'summary'. 'old' is the *exact* old text to replace. 'new' is the new text to replace it with. 'summary' is a brief 1 line summary of the change.
Use your judgment on how to logically apply the changes from the plan in a series of replacements. Use both the code and the plan description to determine the correct order of replacements. BE COMPLETELY SURE that replacements are inserted logically at the correct locations in the file and do not break any syntax or logic rules of the programming language.
@@ -73,11 +73,13 @@ writeReplacements({
replacements: [
{
old: "import \"fmt\"",
- new: "import (\n\t\"fmt\"\n\t\"time\"\n)"
+ new: "import (\n\t\"fmt\"\n\t\"time\"\n)",
+ summary: "Import time package"
},
{
old: "fmt.Println(\"Hello, world!\")",
- new: "fmt.Println(time.Now())"
+ new: "fmt.Println(time.Now())",
+ summary: "Print current time"
}
}
})
@@ -111,7 +113,8 @@ writeReplacements({
replacements: [
{
old: "\n}",
- new: "\n}\n\nfunc Subtract(a, b int) int {\n\treturn a - b\n}"
+ new: "\n}\n\nfunc Subtract(a, b int) int {\n\treturn a - b\n}",
+ summary: "Add Subtract function"
}
]
})
@@ -148,7 +151,8 @@ writeReplacements({
replacements: [
{
old: "fmt.Println(\"Hello, world!\")",
- new: "fmt.Println(\"Hello, world!\")\n\tfmt.Println(\"I love you!\")"
+ new: "fmt.Println(\"Hello, world!\")\n\tfmt.Println(\"I love you!\")",
+ summary: "Also print \"I love you!\""
}
]
})
@@ -174,8 +178,12 @@ var ReplaceFn = openai.FunctionDefinition{
Type: jsonschema.String,
Description: "The new text to replace it with from the changes suggested in the previous response.",
},
+ "summary": {
+ Type: jsonschema.String,
+ Description: "A brief 1 line summary of the change.",
+ },
},
- Required: []string{"old", "new"},
+ Required: []string{"old", "new", "summary"},
},
},
},
@@ -188,18 +196,21 @@ func GetReplacePrompt(filePath string) string {
Based on your instructions, apply the changes from the plan to %s. Call the 'writeReplacements' function with a JSON array of replacements to apply to the file from your previous response.`, filePath)
}
-func GetCorrectReplacementPrompt(failedReplacements map[int]*shared.Replacement, currentState string) (string, error) {
+func GetCorrectReplacementPrompt(replacements []*shared.Replacement, currentState string) (string, error) {
msg := "There were errors with the replacements you suggested."
- for i, failedReplacement := range failedReplacements {
+ for i, replacement := range replacements {
- bytes, err := json.Marshal(failedReplacement)
- if err != nil {
- return "", fmt.Errorf("failed to marshal replacement: %w", err)
- }
+ if replacement.Failed {
+ bytes, err := json.Marshal(replacement)
+ if err != nil {
+ return "", fmt.Errorf("failed to marshal replacement: %w", err)
+ }
- msg += fmt.Sprintf("\n- The replacement at index %d was invalid. The replacement you suggested was:\n\n```%s```\n\n", i, string(bytes))
+ msg += fmt.Sprintf("\n- The replacement at index %d was invalid. The replacement you suggested was:\n\n```%s```\n\n", i, string(bytes))
+
+ msg += fmt.Sprintf("\n- The string `%s` (which you set for the 'old' key of this replacement) was not found in the current state of the file.", replacement.Old)
+ }
- msg += fmt.Sprintf("\n- The string `%s` (which you set for the 'old' key of this replacement) was not found in the current state of the file.", failedReplacement.Old)
}
msg += "\n\nPlease review these errors and try again to call the 'writeReplacements' function with corrected replacements. Pay special attention to any special characters in the strings, extra spaces, or anything else that might cause the strings to not match exactly. You MUST call 'writeReplacements' with an updated list of replacements. Don't call any other function, produce any other output, or call 'writeReplacements' with the same list of replacements as before--it must be called with an updated list of replacements to fix the errors."
diff --git a/server/model/proposal/build.go b/server/model/proposal/build.go
index 6512adfe..d8d64773 100644
--- a/server/model/proposal/build.go
+++ b/server/model/proposal/build.go
@@ -18,7 +18,8 @@ import (
"github.com/sashabaranov/go-openai"
)
-const MAX_RETRIES = 3
+const MaxRetries = 3
+const MaxReplacementRetries = 1
type buildPlanParams struct {
ProposalId string
@@ -54,8 +55,8 @@ func buildPlan(params buildPlanParams) error {
ProposalId: proposalId,
NumFiles: len(proposal.PlanDescription.Files),
Buffers: map[string]string{},
- Files: map[string]*shared.PlanFile{},
- FileErrs: map[string]error{},
+ Results: map[string]*shared.PlanResult{},
+ Errs: map[string]error{},
ProposalStage: types.ProposalStage{
CancelFn: &cancel,
},
@@ -67,12 +68,11 @@ func buildPlan(params buildPlanParams) error {
onStream(shared.STREAM_WRITE_PHASE, nil)
plan := plans.Get(proposalId)
+ ts := shared.StringTs()
- for _, planFile := range plan.Files {
- // fmt.Println()
- // spew.Dump(planFile)
-
- bytes, err := json.Marshal(planFile)
+ for _, planRes := range plan.Results {
+ planRes.Ts = ts
+ bytes, err := json.Marshal(planRes)
if err != nil {
onStream("", err)
return
@@ -85,14 +85,14 @@ func buildPlan(params buildPlanParams) error {
onStream(shared.STREAM_FINISHED, nil)
}
- onFinishBuildFile := func(filePath string, planFile *shared.PlanFile) {
+ onFinishBuildFile := func(filePath string, planRes *shared.PlanResult) {
finished := false
// fmt.Println("onFinishBuildFile: " + filePath)
- // spew.Dump(planFile)
+ // spew.Dump(planRes)
plans.Update(proposalId, func(plan *types.Plan) {
- plan.Files[filePath] = planFile
+ plan.Results[filePath] = planRes
if plan.DidFinish() {
plan.Finish()
@@ -110,21 +110,21 @@ func buildPlan(params buildPlanParams) error {
onBuildFileError := func(filePath string, err error) {
fmt.Printf("Error for file %s: %v\n", filePath, err)
plans.Update(proposalId, func(p *types.Plan) {
- p.FileErrs[filePath] = err
+ p.Errs[filePath] = err
p.SetErr(err)
})
onStream("", err)
}
- var buildFile func(filePath string, numRetry int, replacements []*shared.Replacement, failedReplacements map[int]*shared.Replacement)
- buildFile = func(filePath string, numRetry int, replacements []*shared.Replacement, failedReplacements map[int]*shared.Replacement) {
+ var buildFile func(filePath string, numRetry int, numReplacementRetry int, res *shared.PlanResult)
+ buildFile = func(filePath string, numRetry int, numReplacementsRetry int, res *shared.PlanResult) {
fmt.Printf("Building file %s, numRetry: %d\n", filePath, numRetry)
// get relevant file context (if any)
- var fileContext *shared.ModelContextPart
+ var contextPart *shared.ModelContextPart
for _, part := range proposal.Request.ModelContext {
if part.FilePath == filePath {
- fileContext = part
+ contextPart = part
break
}
}
@@ -134,8 +134,8 @@ func buildPlan(params buildPlanParams) error {
if fileInCurrentPlan {
currentState = currentPlanFile
- } else if fileContext != nil {
- currentState = fileContext.Body
+ } else if contextPart != nil {
+ currentState = contextPart.Body
}
if currentState == "" {
@@ -156,11 +156,11 @@ func buildPlan(params buildPlanParams) error {
onStream(string(planTokenCountJson), nil)
// new file
- planFile := &shared.PlanFile{
+ planRes := &shared.PlanResult{
Path: filePath,
Content: fileContents[filePath],
}
- onFinishBuildFile(filePath, planFile)
+ onFinishBuildFile(filePath, planRes)
return
}
@@ -190,14 +190,14 @@ func buildPlan(params buildPlanParams) error {
},
}
- if numRetry > 0 && replacements != nil && failedReplacements != nil {
- bytes, err := json.Marshal(replacements)
+ if numReplacementsRetry > 0 && res != nil {
+ bytes, err := json.Marshal(res.Replacements)
if err != nil {
onBuildFileError(filePath, fmt.Errorf("error marshalling replacements: %v", err))
return
}
- correctReplacementPrompt, err := prompts.GetCorrectReplacementPrompt(failedReplacements, currentState)
+ correctReplacementPrompt, err := prompts.GetCorrectReplacementPrompt(res.Replacements, currentState)
if err != nil {
onBuildFileError(filePath, fmt.Errorf("error getting correct replacement prompt: %v", err))
return
@@ -233,11 +233,11 @@ func buildPlan(params buildPlanParams) error {
if err != nil {
fmt.Printf("Error creating plan file stream for path '%s': %v\n", filePath, err)
- if numRetry >= MAX_RETRIES {
+ if numRetry >= MaxRetries {
onBuildFileError(filePath, fmt.Errorf("failed to create plan file stream for path '%s' after %d retries: %v", filePath, numRetry, err))
} else {
fmt.Println("Retrying build plan for file: " + filePath)
- buildFile(filePath, numRetry+1, replacements, failedReplacements)
+ buildFile(filePath, numRetry+1, numReplacementsRetry, res)
if err != nil {
onBuildFileError(filePath, fmt.Errorf("failed to retry build plan for file '%s': %v", filePath, err))
}
@@ -252,16 +252,20 @@ func buildPlan(params buildPlanParams) error {
timer := time.NewTimer(model.OPENAI_STREAM_CHUNK_TIMEOUT)
defer timer.Stop()
- handleErrorRetry := func(maxRetryErr error, shouldSleep bool, rep []*shared.Replacement, failed map[int]*shared.Replacement) {
+ handleErrorRetry := func(maxRetryErr error, shouldSleep bool, isReplacementsRetry bool, res *shared.PlanResult) {
fmt.Printf("Error for file %s: %v\n", filePath, maxRetryErr)
- if numRetry >= MAX_RETRIES {
+ if numRetry >= MaxRetries {
onBuildFileError(filePath, maxRetryErr)
} else {
if shouldSleep {
time.Sleep(1 * time.Second * time.Duration(math.Pow(float64(numRetry+1), 2)))
}
- buildFile(filePath, numRetry+1, rep, failed)
+ if isReplacementsRetry {
+ buildFile(filePath, numRetry+1, numReplacementsRetry+1, res)
+ } else {
+ buildFile(filePath, numRetry+1, numReplacementsRetry, res)
+ }
if err != nil {
onBuildFileError(filePath, fmt.Errorf("failed to retry build plan for file '%s': %v", filePath, err))
}
@@ -279,8 +283,8 @@ func buildPlan(params buildPlanParams) error {
handleErrorRetry(
fmt.Errorf("stream timeout due to inactivity for file '%s' after %d retries", filePath, numRetry),
true,
- replacements,
- failedReplacements,
+ false,
+ res,
)
return
default:
@@ -300,14 +304,14 @@ func buildPlan(params buildPlanParams) error {
handleErrorRetry(
fmt.Errorf("stream error for file '%s' after %d retries: %v", filePath, numRetry, err),
true,
- replacements,
- failedReplacements,
+ false,
+ res,
)
return
}
if len(response.Choices) == 0 {
- handleErrorRetry(fmt.Errorf("stream error: no choices"), true, replacements, failedReplacements)
+ handleErrorRetry(fmt.Errorf("stream error: no choices"), true, false, res)
return
}
@@ -318,8 +322,8 @@ func buildPlan(params buildPlanParams) error {
handleErrorRetry(
fmt.Errorf("stream finished without a function call. Reason: %s, File: %s", choice.FinishReason, filePath),
false,
- replacements,
- failedReplacements,
+ false,
+ res,
)
return
}
@@ -328,7 +332,7 @@ func buildPlan(params buildPlanParams) error {
fmt.Println("finish reason: " + choice.FinishReason)
plan := plans.Get(proposalId)
- if plan.Files[filePath] == nil {
+ if plan.Results[filePath] == nil {
fmt.Printf("Stream finished before replacements parsed. File: %s\n", filePath)
fmt.Println("Buffer:")
fmt.Println(plan.Buffers[filePath])
@@ -336,8 +340,8 @@ func buildPlan(params buildPlanParams) error {
handleErrorRetry(
fmt.Errorf("stream finished before replacements parsed. File: %s", filePath),
true,
- replacements,
- failedReplacements,
+ false,
+ res,
)
return
}
@@ -379,17 +383,25 @@ func buildPlan(params buildPlanParams) error {
if err == nil && len(replacements.Replacements) > 0 {
fmt.Printf("File %s: Parsed replacements\n", filePath)
- planFile, failed := applyReplacements(filePath, currentState, proposal.Content, replacements.Replacements)
+ planResult, allSucceeded := getPlanResult(filePath, currentState, contextPart, replacements.Replacements)
- if failed != nil {
+ if !allSucceeded {
fmt.Println("Failed replacements:")
- spew.Dump(failed)
- handleErrorRetry(
- fmt.Errorf("failed to apply replacements to file '%s' after %d retries", filePath, numRetry),
- false,
- replacements.Replacements,
- failed,
- )
+ for _, replacement := range planResult.Replacements {
+ if replacement.Failed {
+ spew.Dump(replacement)
+ }
+ }
+
+ if numRetry < MaxReplacementRetries {
+ handleErrorRetry(
+ nil,
+ false,
+ true,
+ planResult,
+ )
+ }
+
return
}
@@ -407,7 +419,7 @@ func buildPlan(params buildPlanParams) error {
}
onStream(string(planTokenCountJson), nil)
- onFinishBuildFile(filePath, planFile)
+ onFinishBuildFile(filePath, planResult)
return
}
}
@@ -416,14 +428,14 @@ func buildPlan(params buildPlanParams) error {
}
for _, filePath := range proposal.PlanDescription.Files {
- go buildFile(filePath, 0, nil, nil)
+ go buildFile(filePath, 0, 0, nil)
}
return nil
}
-func applyReplacements(filePath string, original string, planSuggestion string, replacements []*shared.Replacement) (*shared.PlanFile, map[int]*shared.Replacement) {
- updated := original
+func getPlanResult(filePath, currentState string, contextPart *shared.ModelContextPart, replacements []*shared.Replacement) (*shared.PlanResult, bool) {
+ updated := currentState
sort.Slice(replacements, func(i, j int) bool {
iIdx := strings.Index(updated, replacements[i].Old)
@@ -431,16 +443,17 @@ func applyReplacements(filePath string, original string, planSuggestion string,
return iIdx < jIdx
})
- failedReplacements := map[int]*shared.Replacement{}
+ allSucceeded := true
lastInsertedIdx := 0
- for i, replacement := range replacements {
+ for _, replacement := range replacements {
pre := updated[:lastInsertedIdx]
sub := updated[lastInsertedIdx:]
originalIdx := strings.Index(sub, replacement.Old)
if originalIdx == -1 {
- failedReplacements[i] = replacement
+ allSucceeded = false
+ replacement.Failed = true
} else {
replaced := strings.Replace(sub, replacement.Old, replacement.New, 1)
@@ -451,18 +464,20 @@ func applyReplacements(filePath string, original string, planSuggestion string,
// log.Println("Updated: " + updated)
updated = pre + replaced
-
lastInsertedIdx = lastInsertedIdx + originalIdx + len(replacement.New)
}
}
- if len(failedReplacements) > 0 {
- return nil, failedReplacements
+ var contextSha string
+ if contextPart != nil {
+ contextSha = contextPart.Sha
}
- return &shared.PlanFile{
- Path: filePath,
- Content: updated,
- }, nil
+ return &shared.PlanResult{
+ Path: filePath,
+ Replacements: replacements,
+ ContextSha: contextSha,
+ AnyFailed: !allSucceeded,
+ }, allSucceeded
}
diff --git a/server/model/proposal/create.go b/server/model/proposal/create.go
index 9098000a..1175a14a 100644
--- a/server/model/proposal/create.go
+++ b/server/model/proposal/create.go
@@ -120,7 +120,7 @@ func CreateProposal(req shared.PromptRequest, onStream types.OnStreamFunc) error
if updatedConversationTokens <= shared.MaxConvoTokens &&
(totalTokens+updatedConversationTokens) <= shared.MaxTokens {
fmt.Printf("Summarizing up to %s | saving %d tokens\n", s.LastMessageTimestamp, savedTokens)
- summary = &s
+ summary = s
break
}
}
@@ -274,7 +274,7 @@ func CreateProposal(req shared.PromptRequest, onStream types.OnStreamFunc) error
var latestSummary *shared.ConversationSummary
var numMessagesSummarized int = 0
if len(req.ConversationSummaries) > 0 {
- latestSummary = &req.ConversationSummaries[len(req.ConversationSummaries)-1]
+ latestSummary = req.ConversationSummaries[len(req.ConversationSummaries)-1]
numMessagesSummarized = latestSummary.NumMessages
}
diff --git a/server/types/plan.go b/server/types/plan.go
index ddcf4d0f..92251e72 100644
--- a/server/types/plan.go
+++ b/server/types/plan.go
@@ -6,11 +6,11 @@ type Plan struct {
ProposalId string
NumFiles int
Buffers map[string]string
- Files map[string]*shared.PlanFile
- FileErrs map[string]error
+ Results map[string]*shared.PlanResult
+ Errs map[string]error
ProposalStage
}
func (s *Plan) DidFinish() bool {
- return len(s.Files) == int(s.NumFiles)
+ return len(s.Results) == int(s.NumFiles)
}
diff --git a/shared/plan_result.go b/shared/plan_result.go
new file mode 100644
index 00000000..ca614f72
--- /dev/null
+++ b/shared/plan_result.go
@@ -0,0 +1,87 @@
+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 {
+ Path string `json:"path"`
+ ContextSha string `json:"contextSha"`
+ Content string `json:"content"`
+ Ts string `json:"ts"`
+ AnyFailed bool `json:"anyFailed"`
+ Replacements []*Replacement `json:"replacements"`
+ AppliedAt string `json:"appliedAt"`
+ RejectedAt string `json:"rejectedAt"`
+ ResolvedAt string `json:"resolvedAt"`
+}
+
+type PlanResultsByPath map[string][]*PlanResult
+
+func (rep *Replacement) IsPending() bool {
+ return !rep.Failed && rep.RejectedAt == "" && rep.ResolvedAt == ""
+}
+
+func (res *PlanResult) NumPendingReplacements() int {
+ numPending := 0
+ for _, rep := range res.Replacements {
+ if rep.IsPending() {
+ numPending++
+ }
+ }
+ return numPending
+}
+
+func (res *PlanResult) IsPending() bool {
+ return res.AppliedAt == "" && res.RejectedAt == "" && res.ResolvedAt == "" && res.NumPendingReplacements() > 0
+}
+
+func (p PlanResultsByPath) SetApplied(ts string) {
+ for _, planResults := range p {
+ for _, planResult := range planResults {
+ if !planResult.IsPending() {
+ continue
+ }
+ planResult.AppliedAt = ts
+ }
+ }
+}
+
+func (p PlanResultsByPath) SetRejected(ts string) {
+ for _, planResults := range p {
+ for _, planResult := range planResults {
+ if !planResult.IsPending() {
+ continue
+ }
+ planResult.RejectedAt = ts
+ }
+ }
+}
+
+func (p PlanResultsByPath) SetResolved(ts string) {
+ for _, planResults := range p {
+ for _, planResult := range planResults {
+ if !planResult.IsPending() {
+ continue
+ }
+ planResult.ResolvedAt = ts
+ }
+ }
+}
+
+func (p PlanResultsByPath) NumPending() int {
+ numPending := 0
+ for _, planResults := range p {
+ for _, planResult := range planResults {
+ if planResult.IsPending() {
+ numPending++
+ }
+ }
+ }
+ return numPending
+}
diff --git a/shared/stream.go b/shared/stream.go
index 76411d1c..ff2a2a45 100644
--- a/shared/stream.go
+++ b/shared/stream.go
@@ -52,11 +52,6 @@ type StreamedFile struct {
Content string `json:"content"`
}
-type Replacement struct {
- Old string `json:"old"`
- New string `json:"new"`
-}
-
type StreamedReplacements struct {
Replacements []*Replacement `json:"replacements"`
}
diff --git a/shared/types.go b/shared/types.go
index 871b3eb1..d8c4f1c8 100644
--- a/shared/types.go
+++ b/shared/types.go
@@ -5,7 +5,8 @@ import (
)
type CurrentPlanFiles struct {
- Files map[string]string `json:"files"`
+ Files map[string]string `json:"files"`
+ ContextShas map[string]string `json:"contextShas"`
}
type ConversationMessage struct {
@@ -15,14 +16,14 @@ type ConversationMessage struct {
}
type PromptRequest struct {
- Timestamp string `json:"timestamp"`
- Prompt string `json:"prompt"`
- ModelContext ModelContext `json:"modelContext"`
- CurrentPlan CurrentPlanFiles `json:"currentPlan"`
- Conversation []ConversationMessage `json:"conversation"`
- ConversationSummaries []ConversationSummary `json:"conversationSummaries"`
- ParentProposalId string `json:"parentProposalId"`
- RootProposalId string `json:"rootProposalId"`
+ Timestamp string `json:"timestamp"`
+ Prompt string `json:"prompt"`
+ ModelContext ModelContext `json:"modelContext"`
+ CurrentPlan *CurrentPlanFiles `json:"currentPlan"`
+ Conversation []*ConversationMessage `json:"conversation"`
+ ConversationSummaries []*ConversationSummary `json:"conversationSummaries"`
+ ParentProposalId string `json:"parentProposalId"`
+ RootProposalId string `json:"rootProposalId"`
}
type ShortSummaryRequest struct {
@@ -70,11 +71,6 @@ type PlanTokenCount struct {
Finished bool `json:"finished"`
}
-type PlanFile struct {
- Path string `json:"path"`
- Content string `json:"content"`
-}
-
type PlanDescription struct {
MadePlan bool `json:"madePlan"`
CommitMsg string `json:"commitMsg"`