Open source AI coding agent. Designed for large projects and real world tasks.
Go aiai-agentsai-developer-toolsai-toolsclicommand-linedeveloper-toolsgitgolanggpt-4llmopenaipolyglot-programmingterminalterminal-basedterminal-ui
work on file progress, general fixes
Dane Schneider4c4ef8511273
diff --git a/cli/cmd/apply.go b/cli/cmd/apply.goindex e3d25adc..6b4e58aa 100644--- a/cli/cmd/apply.go+++ b/cli/cmd/apply.go@@ -19,20 +19,19 @@ func init() {var applyCmd = &cobra.Command{Use: "apply [name]",Short: "Apply a plan to the project",- Args: cobra.ExactArgs(1),- Run: apply,+ Args: cobra.MaximumNArgs(1),+ RunE: apply,}-func apply(cmd *cobra.Command, args []string) {+func apply(cmd *cobra.Command, args []string) error {plandexDir, _, err := lib.FindOrCreatePlandex()name := args[0]if err != nil {- fmt.Fprintln(os.Stderr, "Error:", err)- return+ return fmt.Errorf("Error: %v", err)}- if name == "" {+ if name == "current" {name = lib.CurrentPlanName}@@ -48,8 +47,7 @@ func apply(cmd *cobra.Command, args []string) {rootDir := filepath.Join(plandexDir, name)if _, err := os.Stat(rootDir); os.IsNotExist(err) {- fmt.Fprintln(os.Stderr, "Error: plan with name '"+name+"' does not exist")- return+ return fmt.Errorf("Error: plan with name '%+v' does not exist", name)}copiedAny := false@@ -82,8 +80,7 @@ func apply(cmd *cobra.Command, args []string) {})if err != nil {- fmt.Fprintln(os.Stderr, "Error processing files:", err)- return+ return fmt.Errorf("Error processing files: %v", err)}didExec := false@@ -98,8 +95,7 @@ func apply(cmd *cobra.Command, args []string) {err = cmd.Run()if err != nil {- fmt.Fprintln(os.Stderr, "Error executing plan:", err)- return+ return fmt.Errorf("Error executing plan: %v", err)}didExec = true}@@ -107,10 +103,10 @@ func apply(cmd *cobra.Command, args []string) {if copiedAny || didExec {fmt.Println("Plan applied successfully!")} else {- fmt.Fprintf(os.Stderr, "This plan has no changes to apply.")- os.Exit(1)+ return fmt.Errorf("This plan has no changes to apply.")}+ return nil}// Utility function to copy filesdiff --git a/cli/cmd/checkout.go b/cli/cmd/checkout.gonew file mode 100644index 00000000..f7285fcd--- /dev/null+++ b/cli/cmd/checkout.go@@ -0,0 +1,49 @@+package cmd++import (+ "fmt"+ "log"+ "os"+ "os/exec"+ "plandex/lib"+ "strings"++ "github.com/spf13/cobra"+)++func init() {+ RootCmd.AddCommand(checkoutCmd)+}++var checkoutCmd = &cobra.Command{+ Use: "checkout [name]",+ Short: "Checkout to a new branch and apply a plan",+ Args: cobra.ExactArgs(1),+ Run: checkout,+}++func checkout(cmd *cobra.Command, args []string) {+ if !lib.IsCommandAvailable("git") {+ log.Fatalln("Error: git is required")+ }++ 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")+ }++ branchName := "pdx_" + args[0]+ _, err = exec.Command("git", "checkout", "-b", branchName).CombinedOutput()++ if err != nil {+ log.Fatalln("Error: could not checkout to a new branch.")+ }++ err = apply(cmd, args)++ if err != nil {+ fmt.Fprintln(os.Stderr, "Error committing plan: ", err)+ return+ }+ fmt.Println("Plan applied and committed successfully to branch", branchName, "!")+}diff --git a/cli/go.mod b/cli/go.modindex 5b19600e..35d9e327 100644--- a/cli/go.mod+++ b/cli/go.mod@@ -3,8 +3,8 @@ module plandexgo 1.21.0require (+ github.com/looplab/fsm v1.0.1github.com/spf13/cobra v1.7.0- golang.org/x/term v0.12.0)require (@@ -14,28 +14,22 @@ require (github.com/aymerick/douceur v0.2.0 // indirectgithub.com/dlclark/regexp2 v1.10.0 // indirectgithub.com/fatih/color v1.13.0 // indirect- github.com/gdamore/encoding v1.0.0 // indirect- github.com/gdamore/tcell/v2 v2.6.0 // indirectgithub.com/google/uuid v1.3.0 // indirectgithub.com/gorilla/css v1.0.0 // indirect- github.com/hashicorp/errwrap v1.0.0 // indirect- github.com/looplab/fsm v1.0.1 // indirectgithub.com/lucasb-eyer/go-colorful v1.2.0 // indirectgithub.com/mattn/go-colorable v0.1.12 // indirectgithub.com/mattn/go-isatty v0.0.18 // indirectgithub.com/microcosm-cc/bluemonday v1.0.21 // indirectgithub.com/mitchellh/go-homedir v1.1.0 // indirect- github.com/mitchellh/go-wordwrap v1.0.0 // indirectgithub.com/muesli/reflow v0.3.0 // indirectgithub.com/muesli/termenv v0.15.1 // indirect- github.com/nsf/termbox-go v0.0.0-20190121233118-02980233997d // indirectgithub.com/olekukonko/tablewriter v0.0.5 // indirectgithub.com/rivo/uniseg v0.4.3 // indirectgithub.com/yuin/goldmark v1.5.2 // indirectgithub.com/yuin/goldmark-emoji v1.0.1 // indirectgolang.org/x/net v0.7.0 // indirectgolang.org/x/sys v0.12.0 // indirect- golang.org/x/text v0.9.0 // indirect+ golang.org/x/term v0.12.0 // indirect)require (@@ -43,14 +37,12 @@ require (github.com/briandowns/spinner v1.23.0github.com/charmbracelet/glamour v0.6.0github.com/charmbracelet/glow v1.5.1+ github.com/davecgh/go-spew v1.1.1github.com/eiannone/keyboard v0.0.0-20220611211555-0d226195f203- github.com/gizak/termui/v3 v3.1.0- github.com/hashicorp/go-multierror v1.1.1github.com/inconshreveable/mousetrap v1.1.0 // indirectgithub.com/mattn/go-runewidth v0.0.15 // indirectgithub.com/pkoukk/tiktoken-go v0.1.5github.com/plandex/plandex/shared v0.0.0-00010101000000-000000000000- github.com/rivo/tview v0.0.0-20230928053139-9bc1d28d88a9github.com/sashabaranov/go-openai v1.15.1github.com/spf13/pflag v1.0.5 // indirect)diff --git a/cli/go.sum b/cli/go.sumindex 44cfa9f8..5cf036a9 100644--- a/cli/go.sum+++ b/cli/go.sum@@ -291,13 +291,7 @@ github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFgithub.com/frankban/quicktest v1.14.3/go.mod h1:mgiwOwqx65TmIk1wJ6Q7wvnVMocbUorkibMOrVTHZps=github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw=-github.com/gdamore/encoding v1.0.0 h1:+7OoQ1Bc6eTm5niUzBa0Ctsh6JbMW6Ra+YNuAtDBdko=-github.com/gdamore/encoding v1.0.0/go.mod h1:alR0ol34c49FCSBLjhosxzcPHQbf2trDkoo5dl+VrEg=-github.com/gdamore/tcell/v2 v2.6.0 h1:OKbluoP9VYmJwZwq/iLb4BxwKcwGthaa1YNBJIyCySg=-github.com/gdamore/tcell/v2 v2.6.0/go.mod h1:be9omFATkdr0D9qewWW3d+MEvl5dha+Etb5y65J2H8Y=github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=-github.com/gizak/termui/v3 v3.1.0 h1:ZZmVDgwHl7gR7elfKf1xc4IudXZ5qqfDh4wExk4Iajc=-github.com/gizak/termui/v3 v3.1.0/go.mod h1:bXQEBkJpzxUAKf0+xq9MSWAvWZlE7c+aidmyFlkYTrY=github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU=github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=@@ -411,7 +405,6 @@ github.com/grpc-ecosystem/grpc-gateway v1.9.0/go.mod h1:vNeuVxBJEsws4ogUvrchl83tgithub.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw=github.com/hashicorp/consul/api v1.15.3/go.mod h1:/g/qgcoBcEXALCNZgRRisyTW0nY86++L0KbeAMXYCeY=github.com/hashicorp/consul/sdk v0.11.0/go.mod h1:yPkX5Q6CsxTFMjQQDJwzeNmUUF5NUGGbrDsv9wTb8cw=-github.com/hashicorp/errwrap v1.0.0 h1:hLrqtEDnRye3+sgx6z4qVLNuviH3MR5aQ0ykNJa/UYA=github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=github.com/hashicorp/go-cleanhttp v0.5.0/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80=github.com/hashicorp/go-cleanhttp v0.5.1/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80=@@ -426,7 +419,6 @@ github.com/hashicorp/go-msgpack v0.5.3/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPgithub.com/hashicorp/go-msgpack v0.5.5/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPBM1vqhUKIvfM=github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk=github.com/hashicorp/go-multierror v1.1.0/go.mod h1:spPvp8C1qA32ftKqdAHm4hHTbPw+vmowP0z+KUhOZdA=-github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo=github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM=github.com/hashicorp/go-retryablehttp v0.5.3/go.mod h1:9B5zBasrRhHXnJnui7y6sL7es7NDiJgTc6Er0maI1Xs=github.com/hashicorp/go-rootcerts v1.0.2/go.mod h1:pqUvnprVnM5bf7AOirdbb01K4ccR319Vf4pU3K5EGc8=@@ -502,7 +494,6 @@ github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/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/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88=-github.com/mattn/go-runewidth v0.0.2/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU=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=github.com/mattn/go-runewidth v0.0.12/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk=@@ -522,8 +513,6 @@ github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTgithub.com/mitchellh/cli v1.1.0/go.mod h1:xcISNoH86gajksDmfB23e/pu+B+GeFRMYmoHXxx3xhI=github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y=github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=-github.com/mitchellh/go-wordwrap v0.0.0-20150314170334-ad45545899c7/go.mod h1:ZXFpozHsX6DPmq2I0TCekCxypsnAUbP2oI0UX1GXzOo=-github.com/mitchellh/go-wordwrap v1.0.0 h1:6GlHJ/LTGMrIJbwgdqdl2eEH8o+Exx/0m8ir9Gns0u4=github.com/mitchellh/go-wordwrap v1.0.0/go.mod h1:ZXFpozHsX6DPmq2I0TCekCxypsnAUbP2oI0UX1GXzOo=github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=@@ -552,8 +541,6 @@ github.com/muesli/termenv v0.15.1 h1:UzuTb/+hhlBugQz28rpzey4ZuKcZ03MeKsoG7IJZIxsgithub.com/muesli/termenv v0.15.1/go.mod h1:HeAQPTzpfs016yGtA4g00CsdYnVLJvxsS4ANqrZs2sQ=github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=-github.com/nsf/termbox-go v0.0.0-20190121233118-02980233997d h1:x3S6kxmy49zXVVyhcnrFqxvNVCBPb2KZ9hV2RBdS840=-github.com/nsf/termbox-go v0.0.0-20190121233118-02980233997d/go.mod h1:IuKpRQcYE1Tfu+oAQqaLisqDeXgjyyltCfsaoYN18NQ=github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U=github.com/olekukonko/tablewriter v0.0.5 h1:P2Ga83D34wi1o9J6Wh1mRuqd4mF/x/lgBS7N7AbDhec=github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY=@@ -595,10 +582,7 @@ github.com/prometheus/procfs v0.0.8/go.mod h1:7Qr8sr6344vo1JqZ6HhLceV9o3AJ1Ff+Gxgithub.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU=github.com/prometheus/procfs v0.6.0/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA=github.com/prometheus/tsdb v0.7.1/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU=-github.com/rivo/tview v0.0.0-20230928053139-9bc1d28d88a9 h1:NPymdplpGOYdO5OxmIvsqC7WMYIir5OGXAWlmbnlLbk=-github.com/rivo/tview v0.0.0-20230928053139-9bc1d28d88a9/go.mod h1:nVwGv4MP47T0jvlk7KuTTjjuSmrGO4JF0iaiNt4bufE=github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=-github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=github.com/rivo/uniseg v0.4.3 h1:utMvzDsuh3suAEnhH0RdHmoPbU648o6CvXxTx4SBMOw=github.com/rivo/uniseg v0.4.3/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=@@ -954,7 +938,6 @@ golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=-golang.org/x/text v0.9.0 h1:2sjJmO8cDvYveuX97RDLsxlyUxLl+GHoLxBiRdHllBE=golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=diff --git a/cli/lib/api.go b/cli/lib/api.goindex a5929786..9a23c0b2 100644--- a/cli/lib/api.go+++ b/cli/lib/api.go@@ -21,7 +21,7 @@ var Api types.APIHandler = (*API)(nil)type API struct{}-func (api *API) Propose(prompt string, onStream types.OnStreamPlan) error {+func (api *API) Propose(prompt string, onStream types.OnStreamPlan) (*shared.PromptRequest, error) {serverUrl := apiHost + "/proposal"// Channels to receive data and errors@@ -76,14 +76,14 @@ func (api *API) Propose(prompt string, onStream types.OnStreamPlan) error {select {case modelContext = <-contextChan:case err = <-contextErrChan:- return err+ return nil, err}// Using select to receive from either data or error channel for conversationselect {case conversation = <-conversationChan:case err = <-conversationErrChan:- return err+ return nil, err}// Using select to receive from either data or error channel for plan@@ -91,7 +91,7 @@ func (api *API) Propose(prompt string, onStream types.OnStreamPlan) error {case plan := <-planChan:currentPlan = plancase err = <-planErrChan:- return err+ return nil, err}payload := shared.PromptRequest{@@ -103,19 +103,19 @@ func (api *API) Propose(prompt string, onStream types.OnStreamPlan) error {jsonData, err := json.Marshal(payload)if err != nil {- return err+ return nil, err}resp, err := http.Post(serverUrl, "application/json", bytes.NewBuffer(jsonData))if err != nil {- return err+ return nil, err}// Check the HTTP status codeif resp.StatusCode >= 400 {// Read the error message from the bodyerrorBody, _ := io.ReadAll(resp.Body)- return fmt.Errorf("server returned an error %d: %s", resp.StatusCode, string(errorBody))+ return &payload, fmt.Errorf("server returned an error %d: %s", resp.StatusCode, string(errorBody))}reader := bufio.NewReader(resp.Body)@@ -165,7 +165,7 @@ func (api *API) Propose(prompt string, onStream types.OnStreamPlan) error {}}()- return nil+ return &payload, nil}func (api *API) Abort(proposalId string) error {diff --git a/cli/lib/conversation.go b/cli/lib/conversation.goindex e23c3377..0c68a1ec 100644--- a/cli/lib/conversation.go+++ b/cli/lib/conversation.go@@ -2,7 +2,9 @@ package libimport ("bufio"+ "fmt""os"+ "path/filepath""strings"openai "github.com/sashabaranov/go-openai"@@ -75,3 +77,185 @@ func loadConversation() ([]openai.ChatCompletionMessage, error) {return messages, nil}++func appendConversation(timestamp, prompt, reply string) error {+ // Create or append to conversation file+ responseTimestamp := StringTs()+ conversationFilePath := filepath.Join(ConversationSubdir, fmt.Sprintf("%s.md", timestamp))+ userHeader := fmt.Sprintf("@@@!>user|%s\n\n", timestamp)+ responseHeader := fmt.Sprintf("@@@!>response|%s\n\n", responseTimestamp)++ // TODO: store both summary and full response in conversation file for different use cases/context needs+ conversationFileContents := fmt.Sprintf("%s%s\n\n%s%s", userHeader, prompt, responseHeader, reply)+ conversationFile, err := os.OpenFile(conversationFilePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)+ if err != nil {+ return fmt.Errorf("failed to write conversation file: %s\n", err)+ }+ defer conversationFile.Close()++ _, err = conversationFile.WriteString(conversationFileContents)+ if err != nil {+ return fmt.Errorf("failed to write conversation file: %s\n", err)+ }++ return nil+}++type replyTokenCounter struct {+ lines []string+ lineIndex int+ maybeFilePath string+ currentFilePath string+ numTokensByFile map[string]int+}++func NewReplyTokenCounter() *replyTokenCounter {+ return &replyTokenCounter{+ lines: []string{""},+ numTokensByFile: make(map[string]int),+ }+}++func (r *replyTokenCounter) AddChunk(chunk string) {+ // fmt.Println("Adding chunk:", strconv.Quote(chunk)) // Logging the chunk that's being processed++ hasNewLine := false+ nextChunk := ""++ if chunk == "\n" {+ // fmt.Println("Chunk is \\n, adding new line")+ r.lines = append(r.lines, "")+ hasNewLine = true+ r.lineIndex+++ } else {+ chunkLines := strings.Split(chunk, "\n")++ // fmt.Println("Chunk lines:", len(chunkLines))++ currentLine := r.lines[r.lineIndex]+ currentLine += chunkLines[0]++ // fmt.Println("Current line:", strconv.Quote(currentLine))+ r.lines[r.lineIndex] = currentLine++ if len(chunkLines) > 1 {+ r.lines = append(r.lines, chunkLines[1])+ r.lineIndex+++ hasNewLine = true++ if len(chunkLines) > 2 {+ tail := chunkLines[2:]+ nextChunk = "\n" + strings.Join(tail, "\n")+ defer func() {+ // fmt.Println("Recursive add next queued chunk:", strconv.Quote(nextChunk))+ r.AddChunk(nextChunk)+ }()+ }+ }+ }++ if r.lineIndex == 0 || !hasNewLine {+ return+ }++ prevFullLine := r.lines[r.lineIndex-1]+ // fmt.Println("Previous full line:", strconv.Quote(prevFullLine)) // Logging the full line that's being checked++ if r.maybeFilePath != "" {+ // fmt.Println("Maybe file path is:", r.maybeFilePath) // Logging the maybeFilePath+ if strings.HasPrefix(prevFullLine, "```") {+ r.currentFilePath = r.maybeFilePath+ r.maybeFilePath = ""+ // fmt.Println("Confirmed file path:", r.currentFilePath) // Logging the confirmed file path+ } else if prevFullLine != "" {+ // turns out previous maybeFilePath was not a file path since there's a non-empty line before finding opening ticks+ r.maybeFilePath = ""+ }+ return+ }++ if r.currentFilePath == "" {+ var gotPath string+ if (strings.HasPrefix(prevFullLine, "-") && strings.HasSuffix(prevFullLine, ":")) || strings.HasPrefix(prevFullLine, "-file:") || strings.HasPrefix(prevFullLine, "- file:") {+ p := strings.TrimPrefix(prevFullLine, "-")+ p = strings.TrimSpace(p)+ p = strings.TrimPrefix(p, "file:")+ p = strings.TrimSuffix(p, ":")+ p = strings.TrimSpace(p)+ gotPath = p+ }++ if gotPath != "" {+ // fmt.Println("Detected possible file path:", gotPath) // Logging the possible file path++ if r.maybeFilePath == "" {+ r.maybeFilePath = gotPath+ } else {+ r.maybeFilePath = gotPath+ }+ }+ } else {+ if strings.HasPrefix(prevFullLine, "```") {+ r.currentFilePath = ""+ // fmt.Println("Exited file block.")+ } else {+ tokens := int(GetNumTokens(prevFullLine))+ r.numTokensByFile[r.currentFilePath] += tokens+ // r.contentByFile[r.currentFilePath] += prevFullLine + "\n"+ // fmt.Printf("Added %d tokens to %s\n", tokens, r.currentFilePath) // Logging token addition+ }+ }+}++func (r *replyTokenCounter) FinishAndRead() map[string]int {+ r.AddChunk("\n")+ return r.numTokensByFile+}++// func getTokensPerFilePath(reply string) map[string]int {+// lines := strings.Split(reply, "\n")++// numTokensByFile := make(map[string]int)++// currentFilePath := ""+// foundOpeningTicks := false++// for i, line := range lines {+// if currentFilePath == "" {+// line = strings.TrimSpace(line)++// // fmt.Println("checking line for file path: ", line)++// if (strings.HasPrefix(line, "-") && strings.HasSuffix(line, ":")) || strings.HasPrefix(line, "- file:") {+// // fmt.Println("Found file path line: ", line)++// // check if '```' is in the next two lines+// if i+2 < len(lines) && (strings.HasPrefix(lines[i+1], "```") || strings.HasPrefix(lines[i+2], "```")) {+// // this is a file path+// currentFilePath = strings.TrimPrefix(line, "-")+// currentFilePath = strings.TrimPrefix(line, "- file:")+// currentFilePath = strings.TrimSuffix(currentFilePath, ":")+// numTokensByFile[currentFilePath] = 0+// // fmt.Printf("Found file path: %s\n", currentFilePath)+// }++// }+// } else if foundOpeningTicks {+// if strings.HasPrefix(line, "```") {+// // found closing ticks+// currentFilePath = ""+// foundOpeningTicks = false+// // fmt.Println("Found closing ticks")+// } else {+// numTokensByFile[currentFilePath] += int(GetNumTokens(line))+// // fmt.Printf("Added %d tokens to file %s\n", int(GetNumTokens(line)), currentFilePath)+// }+// } else if strings.HasPrefix(line, "```") {+// // found opening ticks+// foundOpeningTicks = true+// // fmt.Println("Found opening ticks")+// }+// }++// return numTokensByFile+// }diff --git a/cli/lib/conversation_test.go b/cli/lib/conversation_test.gonew file mode 100644index 00000000..721a9764--- /dev/null+++ b/cli/lib/conversation_test.go@@ -0,0 +1,61 @@+package lib++import (+ "os"+ "testing"+)++func TestReplyTokenCounter(t *testing.T) {+ bytes, err := os.ReadFile("conversation_test.md")+ if err != nil {+ t.Error(err)+ }++ content := string(bytes)++ chunkSize := 10++ counter := NewReplyTokenCounter()++ for i := 0; i < len(content); {+ end := i + chunkSize+ if end > len(content) {+ end = len(content)+ }+ chunk := content[i:end]+ counter.AddChunk(chunk)+ i = end+ }++ tokensByFilePath := counter.FinishAndRead()++ if len(tokensByFilePath) != 2 {+ t.Error("Expected 2 file paths")+ }++}++// func TestGetTokensPerFilePath(t *testing.T) {++// bytes, err := os.ReadFile("conversation_test.md")++// if err != nil {+// t.Error(err)+// }++// // time the function call to ensure it is fast enough+// start := time.Now()++// tokensByFilePath := getTokensPerFilePath(string(bytes))++// elapsed := time.Since(start)++// if len(tokensByFilePath) != 2 {+// t.Error("Expected 2 file paths")+// }++// fmt.Println("getTokensPerFilePath took ", elapsed)++// spew.Dump(tokensByFilePath)++// }diff --git a/cli/lib/conversation_test.md b/cli/lib/conversation_test.mdnew file mode 100644index 00000000..2f65daa9--- /dev/null+++ b/cli/lib/conversation_test.md@@ -0,0 +1,78 @@+Thank you for the update. In order to handle errors from the apply command execution, we need to modify the 'checkout' command and the 'apply' command and function.++Follow the steps below:++1. Modify the 'apply' function to return an error.+2. Change 'apply' command invocation in 'checkout' function to handle the returned error.++The code changes are as follows:++- file: cmd/apply.go++```go+package cmd++// ... other imports ...++func init() {+ RootCmd.AddCommand(applyCmd)+}++var applyCmd = &cobra.Command{+ Use: "apply [name]",+ Short: "Apply a plan to the project",+ Args: cobra.MaximumNArgs(1),+ RunE: apply, // We use RunE instead of Run, to allow us to return an error from the apply function+}++func apply(cmd *cobra.Command, args []string) error {++ // ... rest of the code ...++ if err != nil {+ // Return error to the caller instead of directly logging it+ return fmt.Errorf("Error processing files: %v", err)+ }++ // ... rest of the code ...++ if err != nil {+ // Return error to the caller instead of directly logging it+ return fmt.Errorf("Error executing plan: %v", err)+ }++ if copiedAny || didExec {+ fmt.Println("Plan applied successfully!")+ } else {+ return fmt.Errorf("This plan has no changes to apply.")+ }++ return nil+}++// ... rest of the code ...+```++- file: cmd/checkout.go++```go+package cmd++// ... other imports ...++func checkout(cmd *cobra.Command, args []string) {++ // ... rest of the code ...++ err = apply(cmd, args)++ if err != nil {+ fmt.Fprintln(os.Stderr, "Error committing plan: ", err)+ return+ }++ // ... rest of the code ...+}+```++Next, compile and run your application to verify that any error from the 'apply' command would be gracefully handled by the 'checkout' command. Changes have been made in such a way that 'apply' command can still work standalone, besides working in sync with 'checkout' command.diff --git a/cli/lib/git.go b/cli/lib/git.goindex 71e51819..6ad2fa06 100644--- a/cli/lib/git.go+++ b/cli/lib/git.go@@ -98,3 +98,35 @@ func GitCommit(repoDir, commitMsg string, lockMutex bool) error {return nil}++func gitCommitPlanUpdate(commitMsg string) error {++ err := GitAddAndCommit(ConversationSubdir, commitMsg)+ if err != nil {+ return fmt.Errorf("failed to commit files to conversation dir: %s\n", err)+ }++ err = GitAddAndCommit(PlanSubdir, commitMsg)+ if err != nil {+ return fmt.Errorf("failed to commit files to plan dir: %s\n", err)+ }++ // Stage changes in the submodules in the root repo+ err = GitAdd(CurrentPlanRootDir, ConversationSubdir, true)+ if err != nil {+ return fmt.Errorf("failed to stage submodule changes in conversation dir: %s\n", err)+ }++ err = GitAdd(CurrentPlanRootDir, PlanSubdir, true)+ if err != nil {+ return fmt.Errorf("failed to stage submodule changes in plan dir: %s\n", err)+ }++ // Commit these staged submodule changes in the root repo+ err = GitCommit(CurrentPlanRootDir, commitMsg, true)+ if err != nil {+ return fmt.Errorf("failed to commit submodule updates in root dir: %s\n", err)+ }++ return nil+}diff --git a/cli/lib/prompt.go b/cli/lib/prompt.godeleted file mode 100644index fb80cb23..00000000--- a/cli/lib/prompt.go+++ /dev/null@@ -1,512 +0,0 @@-package lib--import (- "bufio"- "context"- "encoding/json"- "fmt"- "os"- "path/filepath"- "plandex/types"- "regexp"- "strconv"- "time"-- "github.com/looplab/fsm"- "github.com/plandex/plandex/shared"-- "github.com/briandowns/spinner"-)--type key struct {- value rune-}--type openFileState struct {- file *os.File- buffer string- jsonBuffer string- wrotePrefix bool- setExecPerms bool- numTokens int- isNew bool- finished bool-}--func Propose(prompt string) error {- s := spinner.New(spinner.CharSets[14], 100*time.Millisecond) // Choose spinner style- s.Start()-- timestamp := StringTs()- reply := ""- done := make(chan struct{})-- termState := ""-- updateTimer := time.NewTimer(100 * time.Millisecond)- defer updateTimer.Stop()-- var proposalId string- var terminalHasPendingUpdate bool- var endedReply bool-- var descJson string- var desc *shared.PlanDescription- var state *fsm.FSM-- fileStates := make(map[string]*openFileState)-- defer clearFileStates(fileStates)-- go func() {- for range updateTimer.C {- if terminalHasPendingUpdate {- // Clear screen- fmt.Print("\x1b[2J")- // Move cursor to top-left- fmt.Print("\x1b[H")- mdFull, _ := GetMarkdown(reply)- fmt.Println(mdFull)- fmt.Printf(displayHotkeys())- termState = mdFull- terminalHasPendingUpdate = false- }- updateTimer.Reset(100 * time.Millisecond)- }- }()-- keyChan := make(chan *key, 1)- ctx, cancelKeywatch := context.WithCancel(context.Background())- errChn := make(chan error, 1)-- endReply := func() {- time.Sleep(100 * time.Millisecond)- backToMain()- fmt.Print(termState)- err := appendConversation(timestamp, prompt, reply)- if err != nil {- fmt.Printf("failed to append conversation: %s\n", err)- }- endedReply = true- }-- running := false- queue := make(chan types.OnStreamPlanParams, 1)-- var handleStream types.OnStreamPlan- handleStream = func(params types.OnStreamPlanParams) {- if running {- queue <- params- return- }-- defer func() {- if len(queue) > 0 {- params := <-queue- handleStream(params)- } else {- running = false- }- }()-- state = params.State- err := params.Err- content := params.Content-- onError := func(err error) {- backToMain()- fmt.Fprintln(os.Stderr, "Error:", err)- close(done)- }-- if err != nil {- onError(err)- return- }-- if proposalId == "" {- if content == "" {- onError(fmt.Errorf("proposal id not sent in first chunk"))- return- } else {- proposalId = content- s.Stop()- // Switch to alternate screen and hide the cursor- fmt.Print("\x1b[?1049h\x1b[?25l")-- return- }- }-- switch state.Current() {- case shared.STATE_REPLYING, shared.STATE_REVISING:- reply += content- terminalHasPendingUpdate = true-- case shared.STATE_FINISHED:- if !endedReply {- endReply()- }-- fmt.Println("Done")-- close(done)- return-- case shared.STATE_DESCRIBING:- if content == shared.STREAM_DESCRIPTION_PHASE {- endReply()-- } else {- descJson = content- err := json.Unmarshal([]byte(descJson), &desc)- if err != nil {- onError(fmt.Errorf("error parsing plan description: %v", err))- return- }-- if desc.MadePlan && (len(desc.Files) > 0 || desc.HasExec) {- fmt.Println("Writing files:")- for _, filePath := range desc.Files {- fmt.Println(filePath)- }- if desc.HasExec {- fmt.Println("exec.sh")- }- }- }-- case shared.STATE_BUILDING:- if content == shared.STREAM_BUILD_PHASE {- // plan build mode started-- } else {- var chunk shared.PlanChunk- err := json.Unmarshal([]byte(content), &chunk)- if err != nil {- onError(fmt.Errorf("error parsing plan chunk: %v", err))- return- }-- err = writeChunkToFile(fileStates, chunk)- if err != nil {- onError(fmt.Errorf("error writing plan chunk to file. chunk: %v, err: %v", chunk, err))- return- }- }- }-- }-- err := Api.Propose(prompt, handleStream)- if err != nil {- backToMain()- return fmt.Errorf("failed to send prompt to server: %s\n", err)- }-- go func(ctx context.Context, errChn chan error) {- for {- select {- case <-ctx.Done():- return- default:- k, err := getUserInput()- if err != nil {- errChn <- err- return- }- keyChan <- &key{k}- }- }- }(ctx, errChn)-- handleKey := func(k *key) error {- return handleKeyPress(k.value, proposalId)- }--Loop:- for {- select {- case k := <-keyChan:- if err := handleKey(k); err != nil {- cancelKeywatch()- return err- }- case <-done: // Evidence of operation completion- cancelKeywatch()- break Loop- case err := <-errChn: // Listening for errors- cancelKeywatch()- return err- }- }-- return nil-}--func Abort(proposalId string) error {- err := Api.Abort(proposalId)- return err-}--// Function for 'a' key action-func handleAbortKey(proposalId string) error {- return Abort(proposalId)-}--// Function for 'r' key action-func handleReviseKey(proposalId string) error {- // Terminate current operation- err := Api.Abort(proposalId)- if err != nil {- return err- }-- // Prompt the user for new message- fmt.Println(">\"")- reader := bufio.NewReader(os.Stdin)- newMessage, _ := reader.ReadString('"')-- // Propose the new message- err = Propose(newMessage)- if err != nil {- return err- }-- fmt.Println("Revision proposed.")- return nil-}--func handleKeyPress(input rune, proposalId string) error {- switch input {- case 'a':- return handleAbortKey(proposalId)- case 'r':- return handleReviseKey(proposalId)- default:- return fmt.Errorf("invalid key pressed: %s", string(input))- }-}--func displayHotkeys() string {- return `- ────────────────────────- ` + "\x1b[1m(a)\x1b[0m" + `bort ` + "\x1b[1m(r)\x1b[0m" + `evise- ────────────────────────- `-}--func backToMain() {- // Switch back to main screen and show the cursor on exit- fmt.Print("\x1b[?1049l\x1b[?25h")-}--func gitCommit(commitMsg string) error {-- err := GitAddAndCommit(ConversationSubdir, commitMsg)- if err != nil {- return fmt.Errorf("failed to commit files to conversation dir: %s\n", err)- }-- err = GitAddAndCommit(PlanSubdir, commitMsg)- if err != nil {- return fmt.Errorf("failed to commit files to plan dir: %s\n", err)- }-- // Stage changes in the submodules in the root repo- err = GitAdd(CurrentPlanRootDir, ConversationSubdir, true)- if err != nil {- return fmt.Errorf("failed to stage submodule changes in conversation dir: %s\n", err)- }-- err = GitAdd(CurrentPlanRootDir, PlanSubdir, true)- if err != nil {- return fmt.Errorf("failed to stage submodule changes in plan dir: %s\n", err)- }-- // Commit these staged submodule changes in the root repo- err = GitCommit(CurrentPlanRootDir, commitMsg, true)- if err != nil {- return fmt.Errorf("failed to commit submodule updates in root dir: %s\n", err)- }-- return nil-}--func appendConversation(timestamp, prompt, reply string) error {- // Create or append to conversation file- responseTimestamp := StringTs()- conversationFilePath := filepath.Join(ConversationSubdir, fmt.Sprintf("%s.md", timestamp))- userHeader := fmt.Sprintf("@@@!>user|%s\n\n", timestamp)- responseHeader := fmt.Sprintf("@@@!>response|%s\n\n", responseTimestamp)-- // TODO: store both summary and full response in conversation file for different use cases/context needs- conversationFileContents := fmt.Sprintf("%s%s\n\n%s%s", userHeader, prompt, responseHeader, reply)- conversationFile, err := os.OpenFile(conversationFilePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)- if err != nil {- return fmt.Errorf("failed to write conversation file: %s\n", err)- }- defer conversationFile.Close()-- _, err = conversationFile.WriteString(conversationFileContents)- if err != nil {- return fmt.Errorf("failed to write conversation file: %s\n", err)- }-- return nil-}--var jsonStartRegex = regexp.MustCompile(`\{\s*?"content"\s*?:\s*"`)--func writeChunkToFile(- fileStates map[string]*openFileState,- chunk shared.PlanChunk) error {- var filePath string- if chunk.IsExec {- filePath = filepath.Join(PlanSubdir, "exec.sh")- } else {- filePath = filepath.Join(PlanFilesDir, chunk.FilePath)- }-- state, ok := fileStates[filePath]- if !ok {- state = &openFileState{isNew: true}- fileStates[filePath] = state- }-- if state.finished {- return nil- }-- err := os.MkdirAll(filepath.Dir(filePath), os.ModePerm)- if err != nil {- return fmt.Errorf("failed to create directory: %s\n", err)- }-- file := state.file- if file == nil {- var openFlags int- if state.isNew {- openFlags = os.O_TRUNC | os.O_CREATE | os.O_WRONLY- } else {- openFlags = os.O_APPEND | os.O_CREATE | os.O_WRONLY- }-- file, err = os.OpenFile(filePath, openFlags,- 0644)- if err != nil {- return fmt.Errorf("failed to open plan file '%s': %v\n", filePath,- err)- }-- // don't cache the file handle on first chunk because we need to first clear the file- // the second chunk will instantiate a new appending file handle and cache it- // subsequent chunks will used the cached appending file handle- if state.isNew {- state.isNew = false- defer file.Close()- } else {- state.file = file- }- }-- state.jsonBuffer += chunk.Content-- if state.wrotePrefix {- var streamed shared.StreamedFile- err = json.Unmarshal([]byte(state.jsonBuffer), &streamed)-- if err == nil {- // get diff between full content and current buffer- diff := streamed.Content[len(state.buffer):]- cleaned := cleanJsonString(diff)-- state.finished = true-- _, err = file.WriteString(cleaned)- if err != nil {- return fmt.Errorf("failed to write to plan file '%s': %v\n", filePath, err)- }- } else {- cleaned := cleanJsonString(chunk.Content)-- state.buffer += cleaned-- _, err := file.WriteString(cleaned)- if err != nil {- return fmt.Errorf("failed to write to plan file '%s': %v\n", filePath, err)- }- }-- } else {- // Check if buffer matches start of JSON syntax- if jsonStartRegex.MatchString(state.jsonBuffer) {- // replace the json start regex in buffer- s := jsonStartRegex.ReplaceAllString(state.jsonBuffer, "")- cleaned := cleanJsonString(s)-- _, err := file.WriteString(cleaned)- if err != nil {- return fmt.Errorf("failed to write to plan file '%s': %v\n", filePath, err)- }-- state.buffer = cleaned- state.wrotePrefix = true- }- }-- if chunk.IsExec && !state.setExecPerms {- err = os.Chmod(filePath, 0755)- if err != nil {- return fmt.Errorf("failed to make exec file executable: %s\n", err)- }- state.setExecPerms = true- }-- state.numTokens += 1- fileStates[filePath] = state-- return nil-}--func cleanJsonString(s string) string {- // replace escaped quotes with unescaped quotes- s = regexp.MustCompile(`\\\"`).ReplaceAllString(s, `"`)-- // replace escaped backslashes with unescaped backslashes- s = regexp.MustCompile(`\\\\`).ReplaceAllString(s, `\`)-- // replace escaped newlines with unescaped newlines- s = regexp.MustCompile(`\\n`).ReplaceAllString(s, "\n")-- // replace escaped tabs with unescaped tabs- s = regexp.MustCompile(`\\t`).ReplaceAllString(s, "\t")-- // replace escaped carriage returns with unescaped carriage returns- s = regexp.MustCompile(`\\r`).ReplaceAllString(s, "\r")-- // replace escaped backspaces with unescaped backspaces- s = regexp.MustCompile(`\\b`).ReplaceAllString(s, "\b")-- // replace escaped form feeds with unescaped form feeds- s = regexp.MustCompile(`\\f`).ReplaceAllString(s, "\f")-- // replace escaped forward slashes with unescaped forward slashes- s = regexp.MustCompile(`\\\/`).ReplaceAllString(s, "/")-- // replace escaped unicode characters with unescaped unicode characters- s = regexp.MustCompile(`\\u([0-9a-fA-F]{4})`).ReplaceAllStringFunc(s, func(match string) string {- unicode, _ := strconv.ParseInt(match[2:], 16, 32)- return string(rune(unicode))- })-- return s-}--func clearFileStates(fileStates map[string]*openFileState) {- for path, state := range fileStates {- state.file.Close()- fmt.Println("closed file", path)- delete(fileStates, path)- }-}diff --git a/cli/lib/proposal.go b/cli/lib/proposal.gonew file mode 100644index 00000000..0852bed0--- /dev/null+++ b/cli/lib/proposal.go@@ -0,0 +1,291 @@+package lib++import (+ "context"+ "encoding/json"+ "fmt"+ "os"+ "plandex/types"+ "time"++ "github.com/looplab/fsm"+ "github.com/plandex/plandex/shared"++ "github.com/briandowns/spinner"+)++type key struct {+ value rune+}++func Propose(prompt string) error {+ s := spinner.New(spinner.CharSets[14], 100*time.Millisecond) // Choose spinner style+ s.Start()++ timestamp := StringTs()+ reply := ""+ done := make(chan struct{})++ termState := ""++ replyUpdateTimer := time.NewTimer(100 * time.Millisecond)+ defer replyUpdateTimer.Stop()++ var proposalId string+ var terminalHasPendingUpdate bool+ var endedReply bool++ var descJson string+ var desc *shared.PlanDescription+ var state *fsm.FSM+ var streamFinished bool+ var filesFinished bool+ finishedByFile := make(map[string]bool)++ jsonBuffers := make(map[string]string)+ contextTokensByFile := make(map[string]int)++ replyTokenCounter := NewReplyTokenCounter()+ var tokensAddedByFile map[string]int++ go func() {+ for range replyUpdateTimer.C {+ if terminalHasPendingUpdate {+ clearScreen()+ moveCursorToTopLeft()+ mdFull, _ := GetMarkdown(reply)+ fmt.Println(mdFull)+ fmt.Printf(displayHotkeys())+ termState = mdFull+ terminalHasPendingUpdate = false+ }+ replyUpdateTimer.Reset(100 * time.Millisecond)+ }+ }()++ keyChan := make(chan *key, 1)+ ctx, cancelKeywatch := context.WithCancel(context.Background())+ errChn := make(chan error, 1)++ endReply := func() {+ replyUpdateTimer.Stop()+ time.Sleep(50 * time.Millisecond)+ backToMain()+ fmt.Print(termState)+ err := appendConversation(timestamp, prompt, reply)+ if err != nil {+ fmt.Printf("failed to append conversation: %s\n", err)+ }+ tokensAddedByFile = replyTokenCounter.FinishAndRead()+ endedReply = true+ }++ contextByFilePath := make(map[string]shared.ModelContextPart)++ running := false+ queue := make(chan types.OnStreamPlanParams, 1)++ var handleStream types.OnStreamPlan+ handleStream = func(params types.OnStreamPlanParams) {+ if running {+ queue <- params+ return+ }++ defer func() {+ if len(queue) > 0 {+ params := <-queue+ handleStream(params)+ } else {+ running = false+ }+ }()++ state = params.State+ err := params.Err+ content := params.Content++ onError := func(err error) {+ backToMain()+ fmt.Fprintln(os.Stderr, "Error:", err)+ cancelKeywatch()+ close(done)+ }++ if err != nil {+ onError(err)+ return+ }++ if proposalId == "" {+ if content == "" {+ onError(fmt.Errorf("proposal id not sent in first chunk"))+ return+ } else {+ proposalId = content+ s.Stop()+ alternateScreen()+ return+ }+ }++ switch state.Current() {+ case shared.STATE_REPLYING, shared.STATE_REVISING:+ reply += content+ replyTokenCounter.AddChunk(content)+ terminalHasPendingUpdate = true++ case shared.STATE_FINISHED:+ if !endedReply {+ endReply()+ }+ streamFinished = true++ if filesFinished {+ close(done)+ }+ return++ case shared.STATE_DESCRIBING:+ if content == shared.STREAM_DESCRIPTION_PHASE {+ endReply()++ } else {+ descJson = content+ err := json.Unmarshal([]byte(descJson), &desc)+ if err != nil {+ onError(fmt.Errorf("error parsing plan description: %v", err))+ return+ }++ if desc.MadePlan && (len(desc.Files) > 0 || desc.HasExec) {+ fmt.Println("Writing plan files:")+ for _, filePath := range desc.Files {+ fmt.Printf("- %s\n", filePath)+ }+ if desc.HasExec {+ fmt.Printf("- %s\n", "exec.sh")+ }+ }++ }++ case shared.STATE_BUILDING:+ if content == shared.STREAM_BUILD_PHASE {+ // plan build mode started++ } else {+ wroteFile, err := receiveFileChunk(content, desc, jsonBuffers, contextTokensByFile, finishedByFile)++ if err != nil {+ onError(err)+ return+ }++ files := make([]string, len(desc.Files))+ copy(files, desc.Files)+ if desc.HasExec {+ files = append(files, "exec.sh")+ }++ // Clear previous lines+ moveUpLines(len(files))++ for _, filePath := range files {+ contextPart, foundContext := contextByFilePath[filePath]+ contextTokens := contextTokensByFile[filePath]+ added := tokensAddedByFile[filePath]++ fmtStr := "- %s | %d tokens"+ fmtArgs := []interface{}{filePath, contextTokens}++ finished := finishedByFile[filePath]++ if finished {+ fmtStr += " | done ✅"+ } else {+ if foundContext {+ fmtStr += " / %d estimated (%d base + ~%d changes)"+ contextTotal := int(contextPart.NumTokens)+ total := contextTotal + added++ fmtArgs = append(fmtArgs, total, contextTotal, added)+ } else {+ fmtStr += " / %d estimated"+ fmtArgs = append(fmtArgs, added)+ }+ }++ clearCurrentLine()+ fmt.Printf(fmtStr+"\n", fmtArgs...)+ }++ if wroteFile {+ if len(finishedByFile) == len(files) {+ filesFinished = true++ if streamFinished {+ close(done)+ }+ }++ }++ }+ }++ }++ apiReq, err := Api.Propose(prompt, handleStream)+ if err != nil {+ backToMain()+ return fmt.Errorf("failed to send prompt to server: %s\n", err)+ }+ for _, part := range apiReq.ModelContext {+ contextByFilePath[part.FilePath] = part+ }++ go func(ctx context.Context, errChn chan error) {+ for {+ select {+ case <-ctx.Done():+ return+ default:+ k, err := getUserInput()+ if err != nil {+ errChn <- err+ return+ }+ keyChan <- &key{k}+ }+ }+ }(ctx, errChn)++ handleKey := func(k *key) error {+ return handleKeyPress(k.value, proposalId)+ }++Loop:+ for {+ select {+ case k := <-keyChan:+ if err := handleKey(k); err != nil {+ cancelKeywatch()+ return err+ }+ case <-done: // Evidence of operation completion+ cancelKeywatch()+ break Loop+ case err := <-errChn: // Listening for errors+ cancelKeywatch()+ return err+ }+ }++ return nil+}++func Abort(proposalId string) error {+ err := Api.Abort(proposalId)+ return err+}diff --git a/cli/lib/stream.go b/cli/lib/stream.gonew file mode 100644index 00000000..542bb90b--- /dev/null+++ b/cli/lib/stream.go@@ -0,0 +1,67 @@+package lib++import (+ "encoding/json"+ "fmt"+ "os"+ "path/filepath"++ "github.com/plandex/plandex/shared"+)++func receiveFileChunk(content string, desc *shared.PlanDescription, jsonBuffers map[string]string, numTokensByFile map[string]int, finishedByFile map[string]bool) (bool, error) {+ var chunk shared.PlanChunk+ err := json.Unmarshal([]byte(content), &chunk)+ if err != nil {+ return false, fmt.Errorf("error parsing plan chunk: %v", err)++ }++ var filePath string+ if chunk.IsExec {+ filePath = filepath.Join(PlanSubdir, "exec.sh")+ } else {+ filePath = filepath.Join(PlanFilesDir, chunk.FilePath)+ }++ buffer := jsonBuffers[chunk.FilePath]+ buffer += chunk.Content+ jsonBuffers[chunk.FilePath] = buffer++ numTokens := int(GetNumTokens(chunk.Content))+ numTokensByFile[chunk.FilePath] += numTokens++ var streamed shared.StreamedFile+ err = json.Unmarshal([]byte(jsonBuffers[chunk.FilePath]), &streamed)++ if err == nil {+ // full file content received+ err := os.MkdirAll(filepath.Dir(filePath), os.ModePerm)+ if err != nil {+ return false, fmt.Errorf("failed to create directory: %s\n", err)++ }+ file, err := os.OpenFile(filePath, os.O_TRUNC|os.O_CREATE|os.O_WRONLY,+ 0644)+ if err != nil {+ return false, fmt.Errorf("failed to open plan file '%s': %v\n", filePath,+ err)+ }+ defer file.Close()+ _, err = file.WriteString(streamed.Content)++ if err != nil {+ return false, fmt.Errorf("failed to write plan file '%s': %v\n", filePath, err)+ }++ // fmt.Println("Wrote to file " + filePath)++ finishedByFile[chunk.FilePath] = true++ return true, nil++ } else {+ return false, nil+ }++}diff --git a/cli/lib/term.go b/cli/lib/term.goindex 5c5808ea..4235cfd1 100644--- a/cli/lib/term.go+++ b/cli/lib/term.go@@ -1,7 +1,98 @@package lib-import "fmt"+import (+ "bufio"+ "fmt"+ "os"+ "strings"-func ClearScreen() {- fmt.Printf("\033[H\033[J") // Move to top-left and clear from cursor to end of screen+ "golang.org/x/term"+)++func alternateScreen() {+ // Switch to alternate screen and hide the cursor+ fmt.Print("\x1b[?1049h\x1b[?25l")+}++func clearScreen() {+ fmt.Print("\x1b[2J")+}++func moveCursorToTopLeft() {+ fmt.Print("\x1b[H")+}++func clearCurrentLine() {+ fmt.Print("\033[2K")+}++func moveUpLines(numLines int) {+ fmt.Printf("\033[%dA", numLines)+}++func backToMain() {+ // Switch back to main screen and show the cursor on exit+ fmt.Print("\x1b[?1049l\x1b[?25h")+}++// Function for 'a' key action+func handleAbortKey(proposalId string) error {+ return Abort(proposalId)+}++// Function for 'r' key action+func handleReviseKey(proposalId string) error {+ // Terminate current operation+ err := Api.Abort(proposalId)+ if err != nil {+ return err+ }++ // Prompt the user for new message+ fmt.Println(">\"")+ reader := bufio.NewReader(os.Stdin)+ newMessage, _ := reader.ReadString('"')++ // Propose the new message+ err = Propose(newMessage)+ if err != nil {+ return err+ }++ fmt.Println("Revision proposed.")+ return nil+}++func handleKeyPress(input rune, proposalId string) error {+ switch input {+ case 'a':+ return handleAbortKey(proposalId)+ case 'r':+ return handleReviseKey(proposalId)+ default:+ return fmt.Errorf("invalid key pressed: %s", string(input))+ }+}++func getTerminalWidth() (int, error) {+ width, _, err := term.GetSize(int(os.Stdout.Fd()))+ if err != nil {+ return 0, err+ }+ return width, nil+}++func displayHotkeys() string {+ // Get the terminal width+ terminalWidth, err := getTerminalWidth()+ if err != nil {+ fmt.Println("Error fetching terminal size:", err)+ terminalWidth = 50 // default width if unable to fetch width+ }+ // Creating the terminal width long division line+ divisionLine := strings.Repeat("─", terminalWidth)++ return divisionLine + "\n" ++ " \x1b[1m(a)\x1b[0m" + `bort ` + "\x1b[1m(r)\x1b[0m" + `evise+` + divisionLine}diff --git a/cli/lib/utils.go b/cli/lib/utils.goindex 6306d7b7..37d345a2 100644--- a/cli/lib/utils.go+++ b/cli/lib/utils.go@@ -3,6 +3,8 @@ package libimport ("fmt""path/filepath"+ "regexp"+ "strconv""strings""time"@@ -51,3 +53,37 @@ func getUserInput() (rune, error) {return char, nil}++func cleanJsonFragment(s string) string {+ // replace escaped quotes with unescaped quotes+ s = regexp.MustCompile(`\\\"`).ReplaceAllString(s, `"`)++ // replace escaped backslashes with unescaped backslashes+ s = regexp.MustCompile(`\\\\`).ReplaceAllString(s, `\`)++ // replace escaped newlines with unescaped newlines+ s = regexp.MustCompile(`\\n`).ReplaceAllString(s, "\n")++ // replace escaped tabs with unescaped tabs+ s = regexp.MustCompile(`\\t`).ReplaceAllString(s, "\t")++ // replace escaped carriage returns with unescaped carriage returns+ s = regexp.MustCompile(`\\r`).ReplaceAllString(s, "\r")++ // replace escaped backspaces with unescaped backspaces+ s = regexp.MustCompile(`\\b`).ReplaceAllString(s, "\b")++ // replace escaped form feeds with unescaped form feeds+ s = regexp.MustCompile(`\\f`).ReplaceAllString(s, "\f")++ // replace escaped forward slashes with unescaped forward slashes+ s = regexp.MustCompile(`\\\/`).ReplaceAllString(s, "/")++ // replace escaped unicode characters with unescaped unicode characters+ s = regexp.MustCompile(`\\u([0-9a-fA-F]{4})`).ReplaceAllStringFunc(s, func(match string) string {+ unicode, _ := strconv.ParseInt(match[2:], 16, 32)+ return string(rune(unicode))+ })++ return s+}diff --git a/cli/types/types.go b/cli/types/types.goindex 839f0497..82ad86b5 100644--- a/cli/types/types.go+++ b/cli/types/types.go@@ -25,7 +25,7 @@ type OnStreamPlan func(params OnStreamPlanParams)// APIHandler is an interface that represents the public API functionstype APIHandler interface {- Propose(prompt string, onStream OnStreamPlan) error+ Propose(prompt string, onStream OnStreamPlan) (*shared.PromptRequest, error)Summarize(text string) (*shared.SummarizeResponse, error)Abort(proposalId string) error}diff --git a/server/handlers/proposal.go b/server/handlers/proposal.goindex 22ff83e0..1e6d87e5 100644--- a/server/handlers/proposal.go+++ b/server/handlers/proposal.go@@ -7,6 +7,7 @@ import ("log""net/http""plandex-server/model/proposal"+ "sync""github.com/plandex/plandex/shared")@@ -43,8 +44,12 @@ func ProposalHandler(w http.ResponseWriter, r *http.Request) {var isResponseClosed booldone := make(chan struct{})- // this is called serially; no need for mutex on 'isResponseClosed'+ var streamMu sync.Mutex+onStream := func(content string, err error) {+ streamMu.Lock()+ defer streamMu.Unlock()+if isResponseClosed {return}@@ -65,6 +70,7 @@ func ProposalHandler(w http.ResponseWriter, r *http.Request) {if err != nil {isResponseClosed = truelog.Printf("Error writing stream content to client: %v\n", err)+ log.Printf("Content: %s\n", string(bytes))close(done)return}diff --git a/server/model/proposal/confirm.go b/server/model/proposal/confirm.goindex 2ba86ddb..a2cece41 100644--- a/server/model/proposal/confirm.go+++ b/server/model/proposal/confirm.go@@ -9,6 +9,7 @@ import ("plandex-server/model""plandex-server/types""strings"+ "sync""time"lorem "github.com/drhodes/golorem"@@ -154,15 +155,6 @@ func confirmProposal(proposalId string, onStream types.OnStreamFunc) error {if choice.FinishReason != "" {if choice.FinishReason == openai.FinishReasonFunctionCall {- // parse the writeFile function call- plan := plans.Get(proposalId)- var resp shared.StreamedFile- err := json.Unmarshal([]byte(plan.Files[filePath]), &resp)- if err != nil {- onError(fmt.Errorf("error parsing writeFile function call: %v", err))- return- }-finished := falseplans.Update(proposalId, func(plan *types.Plan) {plan.FilesFinished[filePath] = true@@ -319,15 +311,6 @@ func confirmProposal(proposalId string, onStream types.OnStreamFunc) error {if choice.FinishReason != "" {if choice.FinishReason == openai.FinishReasonFunctionCall {- // parse the writeExec function call- plan := plans.Get(proposalId)- var resp shared.StreamedFile- err := json.Unmarshal([]byte(plan.Exec), &resp)- if err != nil {- onExecErr(fmt.Errorf("error parsing writeExec function call: %v", err))- return- }-finished := falseplans.Update(proposalId, func(plan *types.Plan) {plan.ExecFinished = true@@ -358,23 +341,14 @@ func confirmProposal(proposalId string, onStream types.OnStreamFunc) error {content = delta.FunctionCall.Arguments}- fmt.Printf("exec.sh content: %s", content)-- // Check if content includes phrase 'No commands'- if strings.Contains(strings.ToLower(content), "no exec commands") {- fmt.Println("No commands to execute for exec.sh")- } else {- fmt.Println("Commands to execute for exec.sh")-- chunk := shared.PlanChunk{IsExec: true, Content: content}- chunkJson, err := json.Marshal(chunk)- if err != nil {- onExecErr(fmt.Errorf("error marshalling exec.sh chunk: %v", err))- return- }-- onStream(string(chunkJson), nil)+ chunk := shared.PlanChunk{IsExec: true, Content: content}+ chunkJson, err := json.Marshal(chunk)+ if err != nil {+ onExecErr(fmt.Errorf("error marshalling exec.sh chunk: %v", err))+ return}++ onStream(string(chunkJson), nil)}}}()@@ -391,18 +365,23 @@ func streamFilesLoremIpsum(onStream types.OnStreamFunc) {}// For each file in the proposal, stream some unstyled lorem ipsum content+ var wg sync.WaitGroupfiles := []string{"file1.txt", "file2.txt"}for _, filePath := range files {- text := strings.Join([]string{lorem.Paragraph(2, 3), lorem.Paragraph(2, 3), lorem.Paragraph(2, 3)}, "\n\n")- streamedFile := shared.StreamedFile{Content: text}- fileContent, _ := json.Marshal(streamedFile)-- for _, line := range strings.Split(string(fileContent), "\n") {- for _, word := range strings.Split(line, " ") {- writeChunk(filePath, false, word+" ")+ wg.Add(1)+ go func(filePath string) {+ defer wg.Done()+ text := strings.Join([]string{lorem.Paragraph(2, 3), lorem.Paragraph(2, 3), lorem.Paragraph(2, 3)}, "\n\n")+ streamedFile := shared.StreamedFile{Content: text}+ fileContent, _ := json.Marshal(streamedFile)++ for _, line := range strings.Split(string(fileContent), "\n") {+ for _, word := range strings.Split(line, " ") {+ writeChunk(filePath, false, word+" ")+ }+ writeChunk(filePath, false, "\n")}- writeChunk(filePath, false, "\n")- }+ }(filePath)}// For the exec.sh script, generate a script that echoes some lorem ipsum content@@ -419,12 +398,19 @@ echo "` + lorem.Sentence(5, 6) + `"` +streamedFile := shared.StreamedFile{Content: echoContent}fileContent, _ := json.Marshal(streamedFile)- for _, line := range strings.Split(string(fileContent), "\n") {- for _, word := range strings.Split(line, " ") {- writeChunk("", true, word+" ")+ wg.Add(1)++ go func() {+ defer wg.Done()+ for _, line := range strings.Split(string(fileContent), "\n") {+ for _, word := range strings.Split(line, " ") {+ writeChunk("", true, word+" ")+ }+ writeChunk("", true, "\n")}- writeChunk("", true, "\n")- }+ }()++ wg.Wait()onStream(shared.STREAM_FINISHED, nil)}diff --git a/server/model/proposal/create.go b/server/model/proposal/create.goindex e505aea4..f33d1a62 100644--- a/server/model/proposal/create.go+++ b/server/model/proposal/create.go@@ -302,6 +302,14 @@ func genPlanDescriptionJson(proposalId string, ctx context.Context) (*shared.Plareturn nil, "", err}+ for i, filePath := range planDesc.Files {+ filePath = strings.TrimSpace(filePath)+ filePath = strings.TrimPrefix(filePath, "-")+ filePath = strings.TrimSpace(filePath)+ planDesc.Files[i] = filePath+ fmt.Println("file path: " + filePath)+ }+bytes, err := json.Marshal(planDesc)if err != nil {fmt.Printf("Error marshalling plan description: %v\n", err)