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
various fixes
Dane Schneider629e6d5e14b0
diff --git a/app/cli/cmd/rewind.go b/app/cli/cmd/rewind.goindex 97c63b0b..9490cd93 100644--- a/app/cli/cmd/rewind.go+++ b/app/cli/cmd/rewind.go@@ -2,7 +2,6 @@ package cmdimport ("fmt"- "log""os""plandex/api""plandex/auth"@@ -41,20 +40,27 @@ func rewind(cmd *cobra.Command, args []string) {return}- stepsOrSha := args[0]+ var stepsOrSha string+ if len(args) > 0 {+ stepsOrSha = args[0]+ } else {+ stepsOrSha = "1"+ }- logsRes, err := api.Client.ListLogs(lib.CurrentPlanId, lib.CurrentBranch)+ logsRes, apiErr := api.Client.ListLogs(lib.CurrentPlanId, lib.CurrentBranch)- if err != nil {- fmt.Printf("Error getting logs: %v\n", err)+ if apiErr != nil {+ fmt.Printf("Error getting logs: %v\n", apiErr)return}var targetSha string- log.Println("shas:", logsRes.Shas)+ // log.Println("shas:", logsRes.Shas)++ steps, err := strconv.Atoi(stepsOrSha)- if steps, err := strconv.Atoi(stepsOrSha); err == nil && steps > 0 {+ if err == nil && steps > 0 {// log.Println("steps:", steps)// Rewind by the specified number of stepstargetSha = logsRes.Shas[steps]@@ -74,14 +80,24 @@ func rewind(cmd *cobra.Command, args []string) {// log.Println("Rewinding to", targetSha)// Rewind to the target sha- _, err = api.Client.RewindPlan(lib.CurrentPlanId, lib.CurrentBranch, shared.RewindPlanRequest{Sha: targetSha})+ _, apiErr = api.Client.RewindPlan(lib.CurrentPlanId, lib.CurrentBranch, shared.RewindPlanRequest{Sha: targetSha})- if err != nil {- fmt.Fprintf(os.Stderr, "Error rewinding plan: %v\n", err)+ if apiErr != nil {+ fmt.Fprintf(os.Stderr, "Error rewinding plan: %v\n", apiErr)return}- msg := "✅ Rewound to " + targetSha+ var msg string+ if steps == 0 {+ msg = "✅ Rewound to " + targetSha+ } else {+ postfix := "s"+ if steps == 1 {+ postfix = ""+ }++ msg = fmt.Sprintf("✅ Rewound %d step%s to %s", steps, postfix, targetSha)+ }fmt.Println(msg)fmt.Println()diff --git a/app/cli/stream_tui/update.go b/app/cli/stream_tui/update.goindex 3f75417f..f463e6b3 100644--- a/app/cli/stream_tui/update.go+++ b/app/cli/stream_tui/update.go@@ -2,6 +2,7 @@ package streamtuiimport ("plandex/term"+ "time"bubbleKey "github.com/charmbracelet/bubbles/key""github.com/charmbracelet/bubbles/spinner"@@ -29,6 +30,9 @@ func (m *streamUIModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {case shared.StreamMessage:return m.streamUpdate(&msg)+ case delayFileRestartMsg:+ m.finishedByPath[msg.path] = false+case tea.MouseMsg:if msg.Type == tea.MouseWheelUp {m.replyViewport.LineUp(3)@@ -153,8 +157,23 @@ func (m *streamUIModel) streamUpdate(msg *shared.StreamMessage) (tea.Model, tea.case shared.StreamMessageBuildInfo:m.building = true- m.tokensByPath[msg.BuildInfo.Path] += msg.BuildInfo.NumTokens- m.finishedByPath[msg.BuildInfo.Path] = msg.BuildInfo.Finished+ wasFinished := m.finishedByPath[msg.BuildInfo.Path]+ nowFinished := msg.BuildInfo.Finished++ if msg.BuildInfo.Finished {+ m.tokensByPath[msg.BuildInfo.Path] = 0+ m.finishedByPath[msg.BuildInfo.Path] = true+ } else {+ if wasFinished && !nowFinished {+ // delay for a second before marking not finished again (so check flashes green prior to restarting build)+ return m, startDelay(msg.BuildInfo.Path, time.Second*1)+ } else {+ m.finishedByPath[msg.BuildInfo.Path] = false+ }++ m.tokensByPath[msg.BuildInfo.Path] += msg.BuildInfo.NumTokens+ }+m.updateViewportDimensions()case shared.StreamMessageDescribing:@@ -170,3 +189,14 @@ func (m *streamUIModel) streamUpdate(msg *shared.StreamMessage) (tea.Model, tea.return m, nil}++type delayFileRestartMsg struct {+ path string+}++func startDelay(path string, delay time.Duration) tea.Cmd {+ return func() tea.Msg {+ time.Sleep(delay)+ return delayFileRestartMsg{path: path}+ }+}diff --git a/app/server/db/build_helpers.go b/app/server/db/build_helpers.goindex 3387a646..e5f35619 100644--- a/app/server/db/build_helpers.go+++ b/app/server/db/build_helpers.go@@ -3,12 +3,30 @@ package dbimport ("fmt""time"++ "github.com/lib/pq")func StorePlanBuild(build *PlanBuild) error {- query := `INSERT INTO plan_builds (org_id, plan_id, convo_message_id, file_path) VALUES (:org_id, :plan_id, :convo_message_id, :file_path) RETURNING id, created_at, updated_at`+ if build.ConvoMessageIds == nil || len(build.ConvoMessageIds) == 0 {+ return fmt.Errorf("error storing plan build: ConvoMessageIds cannot be nil or empty")+ }++ query := `INSERT INTO plan_builds (org_id, plan_id, convo_message_ids, file_path) VALUES (:org_id, :plan_id, :convo_message_ids, :file_path) RETURNING id, created_at, updated_at`++ // Wrap the ConvoMessageIds slice with pq.Array+ args := map[string]interface{}{+ "org_id": build.OrgId,+ "plan_id": build.PlanId,+ "convo_message_ids": pq.Array(build.ConvoMessageIds),+ "file_path": build.FilePath,+ }- row, err := Conn.NamedQuery(query, build)+ row, err := Conn.NamedQuery(query, args)+ if err != nil {+ return fmt.Errorf("error storing plan build: %v", err)+ }+ defer row.Close()if err != nil {return fmt.Errorf("error storing plan build: %v", err)diff --git a/app/server/db/db.go b/app/server/db/db.goindex eef029b5..8fdcbd95 100644--- a/app/server/db/db.go+++ b/app/server/db/db.go@@ -59,7 +59,7 @@ func MigrationsUp() error {// Uncomment below (and update migration version) to reset migration state to a specific version after a failure// if os.Getenv("GOENV") == "development" {- // migrateVersion := 2024012400+ // migrateVersion := 2024013000// if err := m.Force(migrateVersion); err != nil {// return fmt.Errorf("error forcing migration version: %v", err)// }diff --git a/app/server/db/git.go b/app/server/db/git.goindex 1e5f262c..6c503cd2 100644--- a/app/server/db/git.go+++ b/app/server/db/git.go@@ -329,13 +329,6 @@ func lockRepo(orgId, userId, planId, planBuildId, branch string, scope LockScopeif len(expiredLockIds) > 0 {query := "DELETE FROM repo_locks WHERE id = ANY($1)"-- args := make([]interface{}, len(expiredLockIds))- for i, id := range expiredLockIds {- args[i] = id- }-- // Execute the query with the slice as a parameter_, err := tx.Exec(query, pq.Array(expiredLockIds))if err != nil {return fmt.Errorf("error removing expired locks: %v", err)diff --git a/app/server/db/models.go b/app/server/db/models.goindex 2d5fa837..4ec520ee 100644--- a/app/server/db/models.go+++ b/app/server/db/models.go@@ -210,24 +210,24 @@ func (summary *ConvoSummary) ToApi() *shared.ConvoSummary {}type PlanBuild struct {- Id string `db:"id"`- OrgId string `db:"org_id"`- PlanId string `db:"plan_id"`- ConvoMessageId string `db:"convo_message_id"`- FilePath string `db:"file_path"`- Error string `db:"error"`- CreatedAt time.Time `db:"created_at"`- UpdatedAt time.Time `db:"updated_at"`+ Id string `db:"id"`+ OrgId string `db:"org_id"`+ PlanId string `db:"plan_id"`+ ConvoMessageIds []string `db:"convo_message_ids"`+ FilePath string `db:"file_path"`+ Error string `db:"error"`+ CreatedAt time.Time `db:"created_at"`+ UpdatedAt time.Time `db:"updated_at"`}func (build *PlanBuild) ToApi() *shared.PlanBuild {return &shared.PlanBuild{- Id: build.Id,- ConvoMessageId: build.ConvoMessageId,- Error: build.Error,- FilePath: build.FilePath,- CreatedAt: build.CreatedAt,- UpdatedAt: build.UpdatedAt,+ Id: build.Id,+ ConvoMessageIds: build.ConvoMessageIds,+ Error: build.Error,+ FilePath: build.FilePath,+ CreatedAt: build.CreatedAt,+ UpdatedAt: build.UpdatedAt,}}@@ -380,38 +380,38 @@ func (desc *ConvoMessageDescription) ToApi() *shared.ConvoMessageDescription {}type PlanFileResult struct {- Id string `json:"id"`- OrgId string `json:"orgId"`- PlanId string `json:"planId"`- ConvoMessageId string `json:"convoMessageId"`- PlanBuildId string `json:"planBuildId"`- Path string `json:"path"`- ContextSha string `json:"contextSha"`- ContextBody string `json:"contextBody"`- Content string `json:"content,omitempty"`- Replacements []*shared.Replacement `json:"replacements"`- AnyFailed bool `json:"anyFailed"`- Error string `json:"error"`- AppliedAt *time.Time `json:"appliedAt,omitempty"`- RejectedAt *time.Time `json:"rejectedAt,omitempty"`- CreatedAt time.Time `json:"createdAt"`- UpdatedAt time.Time `json:"updatedAt"`+ Id string `json:"id"`+ OrgId string `json:"orgId"`+ PlanId string `json:"planId"`+ ConvoMessageIds []string `json:"convoMessageIds"`+ PlanBuildId string `json:"planBuildId"`+ Path string `json:"path"`+ ContextSha string `json:"contextSha"`+ ContextBody string `json:"contextBody"`+ Content string `json:"content,omitempty"`+ Replacements []*shared.Replacement `json:"replacements"`+ AnyFailed bool `json:"anyFailed"`+ Error string `json:"error"`+ AppliedAt *time.Time `json:"appliedAt,omitempty"`+ RejectedAt *time.Time `json:"rejectedAt,omitempty"`+ CreatedAt time.Time `json:"createdAt"`+ UpdatedAt time.Time `json:"updatedAt"`}func (res *PlanFileResult) ToApi() *shared.PlanFileResult {return &shared.PlanFileResult{- Id: res.Id,- PlanBuildId: res.PlanBuildId,- ConvoMessageId: res.ConvoMessageId,- Path: res.Path,- ContextSha: res.ContextSha,- ContextBody: res.ContextBody,- Content: res.Content,- AnyFailed: res.AnyFailed,- AppliedAt: res.AppliedAt,- RejectedAt: res.RejectedAt,- Replacements: res.Replacements,- CreatedAt: res.CreatedAt,- UpdatedAt: res.UpdatedAt,+ Id: res.Id,+ PlanBuildId: res.PlanBuildId,+ ConvoMessageIds: res.ConvoMessageIds,+ Path: res.Path,+ ContextSha: res.ContextSha,+ ContextBody: res.ContextBody,+ Content: res.Content,+ AnyFailed: res.AnyFailed,+ AppliedAt: res.AppliedAt,+ RejectedAt: res.RejectedAt,+ Replacements: res.Replacements,+ CreatedAt: res.CreatedAt,+ UpdatedAt: res.UpdatedAt,}}diff --git a/app/server/db/stream_helpers.go b/app/server/db/stream_helpers.goindex 47fb70e3..0bb4d596 100644--- a/app/server/db/stream_helpers.go+++ b/app/server/db/stream_helpers.go@@ -33,7 +33,7 @@ func StoreModelStream(stream *ModelStream) error {}func SetModelStreamFinished(id string) error {- log.Println("Setting model stream finished")+ log.Println("Setting model stream finished:", id)_, err := Conn.Exec("UPDATE model_streams SET finished_at = NOW() WHERE id = $1", id)@@ -41,6 +41,8 @@ func SetModelStreamFinished(id string) error {return fmt.Errorf("error setting model stream finished: %v", err)}+ log.Println("Set model stream finished successfully:", id)+return nil}diff --git a/app/server/db/summary_helpers.go b/app/server/db/summary_helpers.goindex 0143aea8..4bd41a95 100644--- a/app/server/db/summary_helpers.go+++ b/app/server/db/summary_helpers.go@@ -3,12 +3,14 @@ package dbimport ("fmt""time"++ "github.com/lib/pq")-func GetPlanSummaries(planId string) ([]*ConvoSummary, error) {+func GetPlanSummaries(planId string, convoMessageIds []string) ([]*ConvoSummary, error) {var summaries []*ConvoSummary- err := Conn.Select(&summaries, "SELECT * FROM convo_summaries WHERE plan_id = $1 ORDER BY created_at", planId)+ err := Conn.Select(&summaries, "SELECT * FROM convo_summaries WHERE plan_id = $1 AND latest_convo_message_id = ANY($2) ORDER BY created_at", planId, pq.Array(convoMessageIds))if err != nil {return nil, fmt.Errorf("error getting plan summaries: %v", err)diff --git a/app/server/go.mod b/app/server/go.modindex 9cb02fc2..191ad31b 100644--- a/app/server/go.mod+++ b/app/server/go.mod@@ -8,7 +8,7 @@ require (github.com/gorilla/mux v1.8.1github.com/pkg/errors v0.9.1github.com/plandex/plandex/shared v0.0.0-00010101000000-000000000000- github.com/sashabaranov/go-openai v1.17.5+ github.com/sashabaranov/go-openai v1.19.2)require (diff --git a/app/server/go.sum b/app/server/go.sumindex 78c88536..5a104c84 100644--- a/app/server/go.sum+++ b/app/server/go.sum@@ -75,8 +75,8 @@ github.com/pkoukk/tiktoken-go v0.1.6 h1:JF0TlJzhTbrI30wCvFuiw6FzP2+/bR+FIxUdgEAcgithub.com/pkoukk/tiktoken-go v0.1.6/go.mod h1:9NiV+i9mJKGj1rYOT+njbv+ZwA/zJxYdewGl6qVatpg=github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=-github.com/sashabaranov/go-openai v1.17.5 h1:ItBzlrrfTtkFWOFlgfOhk3y/xRBC4PJol4gdbiK7hgg=-github.com/sashabaranov/go-openai v1.17.5/go.mod h1:lj5b/K+zjTSFxVLijLSTDZuP7adOgerWeFyZLUhAKRg=+github.com/sashabaranov/go-openai v1.19.2 h1:+dkuCADSnwXV02YVJkdphY8XD9AyHLUWwk6V7LB6EL8=+github.com/sashabaranov/go-openai v1.19.2/go.mod h1:lj5b/K+zjTSFxVLijLSTDZuP7adOgerWeFyZLUhAKRg=github.com/sirupsen/logrus v1.9.2 h1:oxx1eChJGI6Uks2ZC4W1zpLlVgqB8ner4EuQwV4Ik1Y=github.com/sirupsen/logrus v1.9.2/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=diff --git a/app/server/handlers/plans_exec.go b/app/server/handlers/plans_exec.goindex 916d2853..a80d5564 100644--- a/app/server/handlers/plans_exec.go+++ b/app/server/handlers/plans_exec.go@@ -97,7 +97,7 @@ func TellPlanHandler(w http.ResponseWriter, r *http.Request) {if requestBody.ConnectStream {active := model.GetActivePlan(planId, branch)subscriptionId, ch := model.SubscribePlan(planId, branch)- startResponseStream(w, ch, active.Ctx, func() {+ startResponseStream(w, ch, active, func() {model.UnsubscribePlan(planId, branch, subscriptionId)})}diff --git a/app/server/handlers/stream_helper.go b/app/server/handlers/stream_helper.goindex 1105abfe..2de24f56 100644--- a/app/server/handlers/stream_helper.go+++ b/app/server/handlers/stream_helper.go@@ -1,14 +1,14 @@package handlersimport (- "context""log""net/http"+ "plandex-server/types""github.com/plandex/plandex/shared")-func startResponseStream(w http.ResponseWriter, ch chan string, ctx context.Context, closeFn func()) {+func startResponseStream(w http.ResponseWriter, ch chan string, active *types.ActivePlan, closeFn func()) {log.Println("Response stream manager: starting plan stream")w.Header().Set("Transfer-Encoding", "chunked")@@ -21,7 +21,7 @@ func startResponseStream(w http.ResponseWriter, ch chan string, ctx context.Contfor {select {- case <-ctx.Done():+ case <-active.Ctx.Done():log.Println("Response stream manager: context done")returncase msg := <-ch:@@ -31,6 +31,9 @@ func startResponseStream(w http.ResponseWriter, ch chan string, ctx context.Cont_, err := w.Write(bytes)if err != nil {log.Printf("Response stream mananger: error writing to client: %v\n", err)+ if !active.IsBackground && active.NumSubscribers() == 1 {+ active.CancelFn()+ }return}if flusher, ok := w.(http.Flusher); ok {diff --git a/app/server/model/openai_models.go b/app/server/model/openai_models.goindex 2889127e..290e8917 100644--- a/app/server/model/openai_models.go+++ b/app/server/model/openai_models.go@@ -6,9 +6,8 @@ import ("github.com/sashabaranov/go-openai")-// const strongModel = openai.GPT4 // gpt-4-turbo-preview has huge context and is faster, but seems much weaker so far than gpt-4 (this could change in the future)-const strongModel = openai.GPT4TurboPreview-const mediumModel = openai.GPT4TurboPreview+const strongModel = openai.GPT4Turbo1106+const mediumModel = openai.GPT4Turbo1106const weakModel = openai.GPT3Dot5Turbo1106var PlannerModel = strongModeldiff --git a/app/server/model/plan/build.go b/app/server/model/plan/build.goindex 370f6be5..d327f9e3 100644--- a/app/server/model/plan/build.go+++ b/app/server/model/plan/build.go@@ -40,17 +40,28 @@ func QueueBuild(currentOrgId, currentUserId, planId, branch string, activeBuildreturn} else {log.Printf("Will process build queue for file %s\n", filePath)- go execPlanBuild(currentOrgId, currentUserId, branch, activePlan, activeBuild)+ go execPlanBuild(currentOrgId, currentUserId, branch, activePlan, []*types.ActiveBuild{activeBuild})}}-func execPlanBuild(currentOrgId, currentUserId, branch string, activePlan *types.ActivePlan, activeBuild *types.ActiveBuild) {- UpdateActivePlan(activePlan.Id, activePlan.Branch, func(ap *types.ActivePlan) {- ap.IsBuildingByPath[activeBuild.Path] = true- })+func execPlanBuild(currentOrgId, currentUserId, branch string, activePlan *types.ActivePlan, activeBuilds []*types.ActiveBuild) {+ if len(activeBuilds) == 0 {+ log.Println("No active builds")+ return+ }+ // all builds should have the same path+ filePath := activeBuilds[0].PathplanId := activePlan.Id- filePath := activeBuild.Path+ var convoMessageIds []string++ for _, activeBuild := range activeBuilds {+ convoMessageIds = append(convoMessageIds, activeBuild.AssistantMessageId)+ }++ UpdateActivePlan(activePlan.Id, activePlan.Branch, func(ap *types.ActivePlan) {+ ap.IsBuildingByPath[filePath] = true+ })buildInfo := &shared.BuildInfo{Path: filePath,@@ -69,10 +80,10 @@ func execPlanBuild(currentOrgId, currentUserId, branch string, activePlan *typesgo func() {build = &db.PlanBuild{- OrgId: currentOrgId,- PlanId: planId,- ConvoMessageId: activeBuild.AssistantMessageId,- FilePath: filePath,+ OrgId: currentOrgId,+ PlanId: planId,+ ConvoMessageIds: convoMessageIds,+ FilePath: filePath,}err := db.StorePlanBuild(build)@@ -111,7 +122,7 @@ func execPlanBuild(currentOrgId, currentUserId, branch string, activePlan *typesif err != nil {log.Printf("Error building plan %s: %v\n", planId, err)UpdateActivePlan(activePlan.Id, activePlan.Branch, func(ap *types.ActivePlan) {- ap.IsBuildingByPath[activeBuild.Path] = false+ ap.IsBuildingByPath[filePath] = false})activePlan.StreamDoneCh <- &shared.ApiError{Type: shared.ApiErrorTypeOther,@@ -179,7 +190,9 @@ func execPlanBuild(currentOrgId, currentUserId, branch string, activePlan *typesreturn}- activeBuild.Success = true+ for _, build := range activeBuilds {+ build.Success = true+ }UpdateActivePlan(planId, branch, func(ap *types.ActivePlan) {ap.BuiltFiles[filePath] = true@@ -198,20 +211,19 @@ func execPlanBuild(currentOrgId, currentUserId, branch string, activePlan *types} else {if !activePlan.PathFinished(filePath) {log.Printf("Processing next build for file %s\n", filePath)- var nextBuild *types.ActiveBuild+ var nextBuilds []*types.ActiveBuildfor _, build := range activePlan.BuildQueuesByPath[filePath] {- if !build.BuildFinished() {- nextBuild = build- break+ if !build.BuildFinished() && len(nextBuilds) < 5 {+ nextBuilds = append(nextBuilds, build)}}- log.Println("Next build:")- spew.Dump(nextBuild)+ log.Println("Next builds:")+ spew.Dump(nextBuilds)- if nextBuild != nil {+ if len(nextBuilds) > 0 {log.Println("Calling execPlanBuild for next build in queue")- go execPlanBuild(currentOrgId, currentUserId, branch, activePlan, nextBuild)+ go execPlanBuild(currentOrgId, currentUserId, branch, activePlan, nextBuilds)}return} else {@@ -223,7 +235,10 @@ func execPlanBuild(currentOrgId, currentUserId, branch string, activePlan *typesonBuildFileError := func(filePath string, err error) {log.Printf("Error for file %s: %v\n", filePath, err)- activeBuild.Error = err+ for _, build := range activeBuilds {+ build.Success = false+ build.Error = err+ }activePlan.StreamDoneCh <- &shared.ApiError{Type: shared.ApiErrorTypeOther,@@ -243,7 +258,7 @@ func execPlanBuild(currentOrgId, currentUserId, branch string, activePlan *types}UpdateActivePlan(activePlan.Id, activePlan.Branch, func(ap *types.ActivePlan) {- ap.IsBuildingByPath[activeBuild.Path] = false+ ap.IsBuildingByPath[filePath] = false})}@@ -283,12 +298,12 @@ func execPlanBuild(currentOrgId, currentUserId, branch string, activePlan *types// new fileplanRes := &db.PlanFileResult{- OrgId: currentOrgId,- PlanId: planId,- PlanBuildId: build.Id,- ConvoMessageId: build.ConvoMessageId,- Path: filePath,- Content: activeBuild.FileContent,+ OrgId: currentOrgId,+ PlanId: planId,+ PlanBuildId: build.Id,+ ConvoMessageIds: build.ConvoMessageIds,+ Path: filePath,+ Content: activeBuilds[0].FileContent,}onFinishBuildFile(filePath, planRes)return@@ -301,16 +316,27 @@ func execPlanBuild(currentOrgId, currentUserId, branch string, activePlan *typescurrentStatePrompt := prompts.GetBuildCurrentStatePrompt(filePath, currentState)sysPrompt := prompts.GetBuildSysPrompt(filePath, currentStatePrompt)+ var mergedReply string+ for _, activeBuild := range activeBuilds {+ mergedReply += "\n\n" + activeBuild.ReplyContent+ }++ log.Println("Num active builds: " + fmt.Sprintf("%d", len(activeBuilds)))+ log.Println("Merged reply:")+ log.Println(mergedReply)+fileMessages := []openai.ChatCompletionMessage{{Role: openai.ChatMessageRoleSystem,Content: sysPrompt,- }, {+ },+ {Role: openai.ChatMessageRoleUser,Content: activePlan.Prompt,- }, {+ },+ {Role: openai.ChatMessageRoleAssistant,- Content: activePlan.CurrentReplyContent,+ Content: mergedReply,},{Role: openai.ChatMessageRoleUser,@@ -374,6 +400,8 @@ func execPlanBuild(currentOrgId, currentUserId, branch string, activePlan *typesreturn}+ buffer := ""+go func() {defer stream.Close()@@ -469,7 +497,7 @@ func execPlanBuild(currentOrgId, currentUserId, branch string, activePlan *typesif !active.BuiltFiles[filePath] {log.Printf("Stream finished before replacements parsed. File: %s\n", filePath)log.Println("Buffer:")- log.Println(activeBuild.Buffer)+ log.Println(buffer)handleErrorRetry(fmt.Errorf("stream finished before replacements parsed. File: %s", filePath),@@ -504,23 +532,23 @@ func execPlanBuild(currentOrgId, currentUserId, branch string, activePlan *typesBuildInfo: buildInfo,})- activeBuild.Buffer += content+ buffer += contentvar streamed types.StreamedReplacements- err = json.Unmarshal([]byte(activeBuild.Buffer), &streamed)+ err = json.Unmarshal([]byte(buffer), &streamed)if err == nil && len(streamed.Replacements) > 0 {log.Printf("File %s: Parsed replacements\n", filePath)planFileResult, allSucceeded := getPlanResult(planResultParams{- orgId: currentOrgId,- planId: planId,- planBuildId: build.Id,- convoMessageId: build.ConvoMessageId,- filePath: filePath,- currentState: currentState,- context: contextPart,- replacements: streamed.Replacements,+ orgId: currentOrgId,+ planId: planId,+ planBuildId: build.Id,+ convoMessageIds: build.ConvoMessageIds,+ filePath: filePath,+ currentState: currentState,+ context: contextPart,+ replacements: streamed.Replacements,},)@@ -567,14 +595,14 @@ func execPlanBuild(currentOrgId, currentUserId, branch string, activePlan *types}type planResultParams struct {- orgId string- planId string- planBuildId string- convoMessageId string- filePath string- currentState string- context *db.Context- replacements []*shared.Replacement+ orgId string+ planId string+ planBuildId string+ convoMessageIds []string+ filePath string+ currentState string+ context *db.Context+ replacements []*shared.Replacement}func getPlanResult(params planResultParams) (*db.PlanFileResult, bool) {@@ -606,15 +634,15 @@ func getPlanResult(params planResultParams) (*db.PlanFileResult, bool) {}return &db.PlanFileResult{- OrgId: orgId,- PlanId: planId,- PlanBuildId: planBuildId,- ConvoMessageId: params.convoMessageId,- Content: "",- Path: filePath,- Replacements: replacements,- ContextSha: contextSha,- ContextBody: contextPart.Body,- AnyFailed: !allSucceeded,+ OrgId: orgId,+ PlanId: planId,+ PlanBuildId: planBuildId,+ ConvoMessageIds: params.convoMessageIds,+ Content: "",+ Path: filePath,+ Replacements: replacements,+ ContextSha: contextSha,+ ContextBody: contextPart.Body,+ AnyFailed: !allSucceeded,}, allSucceeded}diff --git a/app/server/model/plan/state.go b/app/server/model/plan/state.goindex ad773e8b..de1c4e99 100644--- a/app/server/model/plan/state.go+++ b/app/server/model/plan/state.go@@ -33,6 +33,14 @@ func CreateActivePlan(planId, branch, prompt string) *types.ActivePlan {if err != nil {log.Printf("Error setting model stream %s finished: %v\n", activePlan.ModelStreamId, err)}++ err = db.SetPlanStatus(planId, branch, shared.PlanStatusStopped, "")+ if err != nil {+ log.Printf("Error setting plan %s status to stopped: %v\n", planId, err)+ }++ DeleteActivePlan(planId, branch)+returncase apiErr := <-activePlan.StreamDoneCh:log.Printf("case apiErr := <-activePlan.StreamDoneCh: %s\n", planId)diff --git a/app/server/model/plan/tell.go b/app/server/model/plan/tell.goindex 1caa879f..442cf08e 100644--- a/app/server/model/plan/tell.go+++ b/app/server/model/plan/tell.go@@ -48,6 +48,23 @@ func Tell(plan *db.Plan, branch string, auth *types.ServerAuth, req *shared.Tellactive = CreateActivePlan(plan.Id, branch, req.Prompt)+ modelStream = &db.ModelStream{+ OrgId: auth.OrgId,+ PlanId: plan.Id,+ InternalIp: host.Ip,+ Branch: branch,+ }+ err = db.StoreModelStream(modelStream)++ if err != nil {+ log.Printf("Error storing model stream: %v\n", err)+ return fmt.Errorf("error storing model stream: %v", err)+ }++ active.ModelStreamId = modelStream.Id++ log.Println("Model stream id:", modelStream.Id)+go execTellPlan(plan, branch, auth, req, active, 0)return nil@@ -165,37 +182,57 @@ func execTellPlan(plan *db.Plan, branch string, auth *types.ServerAuth, req *shareturn}- if iteration == 0 {- userMsg := db.ConvoMessage{- OrgId: currentOrgId,- PlanId: planId,- UserId: currentUserId,- Role: openai.ChatMessageRoleUser,- Tokens: promptTokens,- Num: len(convo) + 1,- Message: req.Prompt,+ innerErrCh := make(chan error)++ go func() {+ if iteration == 0 {+ userMsg := db.ConvoMessage{+ OrgId: currentOrgId,+ PlanId: planId,+ UserId: currentUserId,+ Role: openai.ChatMessageRoleUser,+ Tokens: promptTokens,+ Num: len(convo) + 1,+ Message: req.Prompt,+ }++ _, err = db.StoreConvoMessage(&userMsg, auth.User.Id, branch, true)++ if err != nil {+ log.Printf("Error storing user message: %v\n", err)+ innerErrCh <- fmt.Errorf("error storing user message: %v", err)+ return+ }}- _, err = db.StoreConvoMessage(&userMsg, auth.User.Id, branch, true)+ innerErrCh <- nil+ }()++ go func() {+ var convoMessageIds []string+ for _, convoMessage := range convo {+ convoMessageIds = append(convoMessageIds, convoMessage.Id)+ }++ res, err := db.GetPlanSummaries(planId, convoMessageIds)if err != nil {- log.Printf("Error storing user message: %v\n", err)- errCh <- fmt.Errorf("error storing user message: %v", err)+ log.Printf("Error getting plan summaries: %v\n", err)+ innerErrCh <- fmt.Errorf("error getting plan summaries: %v", err)return}- }+ summaries = res- errCh <- nil- }()+ innerErrCh <- nil+ }()- go func() {- res, err := db.GetPlanSummaries(planId)- if err != nil {- log.Printf("Error getting plan summaries: %v\n", err)- errCh <- fmt.Errorf("error getting plan summaries: %v", err)- return+ for i := 0; i < 2; i++ {+ err := <-innerErrCh+ if err != nil {+ errCh <- err+ return+ }}- summaries = reserrCh <- nil}()@@ -214,7 +251,7 @@ func execTellPlan(plan *db.Plan, branch string, auth *types.ServerAuth, req *sha}}()- for i := 0; i < 4; i++ {+ for i := 0; i < 3; i++ {err := <-errChif err != nil {active.StreamDoneCh <- &shared.ApiError{@@ -244,6 +281,12 @@ func execTellPlan(plan *db.Plan, branch string, auth *types.ServerAuth, req *sha}}})+ } else {+ // reset current reply content and num tokens+ UpdateActivePlan(planId, branch, func(ap *types.ActivePlan) {+ ap.CurrentReplyContent = ""+ ap.NumTokens = 0+ })}modelContextText, modelContextTokens, err := lib.FormatModelContext(modelContext)@@ -475,26 +518,6 @@ func execTellPlan(plan *db.Plan, branch string, auth *types.ServerAuth, req *shareturn}- modelStream := &db.ModelStream{- OrgId: currentOrgId,- PlanId: planId,- InternalIp: host.Ip,- Branch: branch,- }- err = db.StoreModelStream(modelStream)-- if err != nil {- log.Printf("Error storing model stream: %v\n", err)- active.StreamDoneCh <- &shared.ApiError{- Type: shared.ApiErrorTypeOther,- Status: http.StatusInternalServerError,- Msg: "Error storing model stream",- }- return- }-- active.ModelStreamId = modelStream.Id-storeAssistantReply := func() (*db.ConvoMessage, []string, string, error) {num := len(convo) + 1if iteration == 0 {@@ -769,18 +792,15 @@ func execTellPlan(plan *db.Plan, branch string, auth *types.ServerAuth, req *shareplyNumTokens = numTokens// log.Printf("Reply num tokens: %d\n", replyNumTokens)- // log.Printf("Reply files: %v\n", files)if len(files) > len(replyFiles) {- for i := len(files) - 1; i > 0; i-- {- if i < len(replyFiles) {- break- }+ log.Printf("Files: %v\n", files)+ for i := len(files) - 1; i > len(replyFiles)-1; i-- {file := files[i]log.Printf("Queuing build for %s\n", file)QueueBuild(currentOrgId, currentUserId, planId, branch, &types.ActiveBuild{AssistantMessageId: replyId,- ReplyContent: content,+ ReplyContent: active.CurrentReplyContent,FileContent: fileContents[i],Path: file,})diff --git a/app/server/model/prompts/build.go b/app/server/model/prompts/build.goindex d42fb1cb..3129db75 100644--- a/app/server/model/prompts/build.go+++ b/app/server/model/prompts/build.go@@ -35,10 +35,12 @@ For the 'new' text, apart from the exceptions I mentioned in the previous paragrYou MUST call only 'writeReplacements'--don't call any other function or produce any other output.+You MUST only generate replacements for the *current file*--don't generate replacements for any other file. If other files are present in the plan, ignore them. Only generate replacements for the current file.+Replacement examples below. Note: >>> and <<< indicate the start and end of an example response.1.)-If the current file is:+If the current file is 'main.go' and the state is:`+"```"+`package main@@ -90,7 +92,7 @@ writeReplacements({})2.)-If the current file is:+If the current file is 'helpers.go' and the state is:`+"```"+`package helpers@@ -125,7 +127,7 @@ writeReplacements({})3.)-If the current file is:+If the current file is 'main.go' and the state is:`+"```"+`package main@@ -171,7 +173,7 @@ func GetBuildCurrentStatePrompt(filePath, currentState string) string {if currentState == "" {return ""}- return fmt.Sprintf("\n\n**Current state of file for %s:**\n```\n%s\n```", filePath, currentState) + "\n\n"+ return fmt.Sprintf("**The current file is %s. Current state of the file:**\n```\n%s\n```", filePath, currentState) + "\n\n"}var ReplaceFn = openai.FunctionDefinition{@@ -208,7 +210,7 @@ var ReplaceFn = openai.FunctionDefinition{func GetReplacePrompt(filePath string) string {return fmt.Sprintf(`- 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)+ 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. You *must always call the 'writeReplacements' function*. Don't call any other function.`, filePath)}func GetCorrectReplacementPrompt(replacements []*shared.Replacement, currentState string) (string, error) {diff --git a/app/server/types/active_plan.go b/app/server/types/active_plan.goindex f4e38633..2e3d1ce3 100644--- a/app/server/types/active_plan.go+++ b/app/server/types/active_plan.go@@ -37,9 +37,11 @@ type ActivePlan struct {BuildQueuesByPath map[string][]*ActiveBuildRepliesFinished boolStreamDoneCh chan *shared.ApiError- ModelStreamId string- streamCh chan string- subscriptions map[string]chan string++ ModelStreamId string+ IsBackground bool+ streamCh chan string+ subscriptions map[string]chan string}func NewActivePlan(planId, branch, prompt string) *ActivePlan {@@ -124,6 +126,10 @@ func (ap *ActivePlan) Unsubscribe(id string) {delete(ap.subscriptions, id)}+func (ap *ActivePlan) NumSubscribers() int {+ return len(ap.subscriptions)+}+func (b *ActiveBuild) BuildFinished() bool {return b.Success || b.Error != nil}diff --git a/app/server/types/reply.go b/app/server/types/reply.goindex 9f29c7ff..d8a7cddb 100644--- a/app/server/types/reply.go+++ b/app/server/types/reply.go@@ -1,7 +1,6 @@package typesimport (- "log""strings")@@ -97,7 +96,7 @@ func (r *replyParser) AddChunk(chunk string, addToTotal bool) {r.fileContents = append(r.fileContents, "")r.maybeFilePath = ""r.currentFileLines = []string{}- log.Println("Confirmed file path:", r.currentFilePath) // Logging the confirmed file path+ // log.Println("Confirmed file path:", r.currentFilePath) // Logging the confirmed file pathreturn} else if prevFullLineTrimmed != "" {@@ -133,18 +132,18 @@ func (r *replyParser) AddChunk(chunk string, addToTotal bool) {}}} else {- log.Println("Current file path is not empty--adding to current file...")+ // log.Println("Current file path is not empty--adding to current file...")if strings.HasPrefix(prevFullLineTrimmed, "```") {- log.Println("Found closing ticks--adding file to files and resetting current file...")+ // log.Println("Found closing ticks--adding file to files and resetting current file...")r.files = append(r.files, r.currentFilePath)r.currentFilePath = ""} else {- log.Println("Adding tokens to current file...") // Logging token addition+ // log.Println("Adding tokens to current file...") // Logging token additionr.fileContents[r.currentFileIdx] += prevFullLine + "\n"r.currentFileLines = append(r.currentFileLines, prevFullLine)- // fmt.Printf("Added %d tokens to %s\n", tokens, r.currentFilePath) // Logging token addition+ // log.Printf("Added %d tokens to %s\n", tokens, r.currentFilePath) // Logging token addition}}}diff --git a/app/shared/models.go b/app/shared/models.goindex acd09c1a..67cffd61 100644--- a/app/shared/models.go+++ b/app/shared/models.go@@ -132,12 +132,12 @@ type ConvoMessageDescription struct {}type PlanBuild struct {- Id string `json:"id"`- ConvoMessageId string `json:"convoMessageId"`- FilePath string `json:"filePath"`- Error string `json:"error"`- CreatedAt time.Time `json:"createdAt"`- UpdatedAt time.Time `json:"updatedAt"`+ Id string `json:"id"`+ ConvoMessageIds []string `json:"convoMessageIds"`+ FilePath string `json:"filePath"`+ Error string `json:"error"`+ CreatedAt time.Time `json:"createdAt"`+ UpdatedAt time.Time `json:"updatedAt"`}type Replacement struct {@@ -150,19 +150,19 @@ type Replacement struct {}type PlanFileResult struct {- Id string `json:"id"`- ConvoMessageId string `json:"convoMessageId"`- PlanBuildId string `json:"planBuildId"`- Path string `json:"path"`- ContextBody string `json:"contextBody"`- ContextSha string `json:"contextSha"`- Content string `json:"content"`- AnyFailed bool `json:"anyFailed"`- AppliedAt *time.Time `json:"appliedAt,omitempty"`- RejectedAt *time.Time `json:"rejectedAt,omitempty"`- Replacements []*Replacement `json:"replacements"`- CreatedAt time.Time `json:"createdAt"`- UpdatedAt time.Time `json:"updatedAt"`+ Id string `json:"id"`+ ConvoMessageIds []string `json:"convoMessageIds"`+ PlanBuildId string `json:"planBuildId"`+ Path string `json:"path"`+ ContextBody string `json:"contextBody"`+ ContextSha string `json:"contextSha"`+ Content string `json:"content"`+ AnyFailed bool `json:"anyFailed"`+ AppliedAt *time.Time `json:"appliedAt,omitempty"`+ RejectedAt *time.Time `json:"rejectedAt,omitempty"`+ Replacements []*Replacement `json:"replacements"`+ CreatedAt time.Time `json:"createdAt"`+ UpdatedAt time.Time `json:"updatedAt"`}type CurrentPlanFiles struct {diff --git a/app/shared/plan_result.go b/app/shared/plan_result.goindex 238b8bb9..2d761162 100644--- a/app/shared/plan_result.go+++ b/app/shared/plan_result.go@@ -181,22 +181,35 @@ func (planState *CurrentPlanState) GetFilesBeforeReplacement(}func (state *CurrentPlanState) PendingChangesSummary() string {+var msgs []string- for _, desc := range state.PendingBuildDescriptions {+ var multiDescs [][]*ConvoMessageDescription+ for i, result := range state.PlanResult.Results {+ if i >= len(multiDescs) {+ multiDescs = append(multiDescs, []*ConvoMessageDescription{})+ }+ for _, convoMessageId := range result.ConvoMessageIds {+ for _, desc := range state.PendingBuildDescriptions {+ if desc.ConvoMessageId == convoMessageId {+ multiDescs[i] = append(multiDescs[i], desc)+ }+ }+ }+ }+ for i, descs := range multiDescs {+ result := state.PlanResult.Results[i]pendingNewFilesSet := make(map[string]bool)pendingReplacementPathsSet := make(map[string]bool)pendingReplacementsByPath := make(map[string][]*Replacement)- for _, result := range state.PlanResult.Results {- if result.ConvoMessageId == desc.ConvoMessageId && result.IsPending() {- if len(result.Replacements) == 0 && result.Content != "" {- pendingNewFilesSet[result.Path] = true- } else {- pendingReplacementPathsSet[result.Path] = true- pendingReplacementsByPath[result.Path] = append(pendingReplacementsByPath[result.Path], result.Replacements...)- }+ if result.IsPending() {+ if len(result.Replacements) == 0 && result.Content != "" {+ pendingNewFilesSet[result.Path] = true+ } else {+ pendingReplacementPathsSet[result.Path] = true+ pendingReplacementsByPath[result.Path] = append(pendingReplacementsByPath[result.Path], result.Replacements...)}}@@ -224,8 +237,9 @@ func (state *CurrentPlanState) PendingChangesSummary() string {})var descMsgs []string-- descMsgs = append(descMsgs, fmt.Sprintf("📝 %s", desc.CommitMsg))+ for _, desc := range descs {+ descMsgs = append(descMsgs, fmt.Sprintf("📝 %s", desc.CommitMsg))+ }if len(pendingNewFiles) > 0 {newMsg := " 📄 New files:\n"@@ -251,6 +265,7 @@ func (state *CurrentPlanState) PendingChangesSummary() string {}msgs = append(msgs, strings.Join(descMsgs, "\n"))+}return strings.Join(msgs, "\n")}