Skip to content

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

- Added crash prevention measures across the board - Fix for occasional "replacements failed" error - Reliability and improvements for file updates - Fix for role name of auto-continue model

Dane Schneidera3098bffafe4
diff --git a/app/server/handlers/stream_helper.go b/app/server/handlers/stream_helper.go
index cd15a4e1..f5c8c13a 100644
--- a/app/server/handlers/stream_helper.go
+++ b/app/server/handlers/stream_helper.go
@@ -18,6 +18,12 @@ func startResponseStream(w http.ResponseWriter, auth *types.ServerAuth, planId,
active := modelPlan.GetActivePlan(planId, branch)
+ if active == nil {
+ log.Printf("Response stream manager: active plan not found for plan ID %s on branch %s\n", planId, branch)
+ http.Error(w, "Active plan not found", http.StatusNotFound)
+ return
+ }
+
w.Header().Set("Transfer-Encoding", "chunked")
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
@@ -98,6 +104,10 @@ func initConnectActive(auth *types.ServerAuth, planId, branch string, w http.Res
active := modelPlan.GetActivePlan(planId, branch)
+ if active == nil {
+ return fmt.Errorf("active plan not found for plan ID %s on branch %s", planId, branch)
+ }
+
msg := shared.StreamMessage{
Type: shared.StreamMessageConnectActive,
}
diff --git a/app/server/model/plan/build_exec.go b/app/server/model/plan/build_exec.go
index 174decf5..afe7bfb9 100644
--- a/app/server/model/plan/build_exec.go
+++ b/app/server/model/plan/build_exec.go
@@ -239,6 +239,8 @@ func (fileState *activeBuildStreamFileState) buildFile() {
log.Println("Getting file from model: " + filePath)
// log.Println("File context:", fileContext)
+ // log.Println("currentState:", currentState)
+
sysPrompt := prompts.GetBuildSysPrompt(filePath, currentState, activeBuild.FileDescription, activeBuild.FileContent)
fileMessages := []openai.ChatCompletionMessage{
diff --git a/app/server/model/plan/build_finish.go b/app/server/model/plan/build_finish.go
index fa948d16..0c187b4a 100644
--- a/app/server/model/plan/build_finish.go
+++ b/app/server/model/plan/build_finish.go
@@ -20,12 +20,16 @@ func (state *activeBuildStreamFileState) onFinishBuild() {
convoMessageId := state.convoMessageId
build := state.build
- activePlan := GetActivePlan(planId, branch)
-
// first check if any of the messages we're building hasen't finished streaming yet
stillStreaming := false
var doneCh chan bool
ap := GetActivePlan(planId, branch)
+
+ if ap == nil {
+ log.Println("onFinishBuild - Active plan not found")
+ return
+ }
+
if ap.CurrentStreamingReplyId == convoMessageId {
stillStreaming = true
doneCh = ap.CurrentReplyDoneCh
@@ -38,6 +42,12 @@ func (state *activeBuildStreamFileState) onFinishBuild() {
// Check again if build is finished
// (more builds could have been queued while we were waiting for the reply to finish streaming)
ap = GetActivePlan(planId, branch)
+
+ if ap == nil {
+ log.Println("onFinishBuild - Active plan not found")
+ return
+ }
+
if !ap.BuildFinished() {
log.Println("Build not finished after waiting for reply to finish streaming")
return
@@ -53,14 +63,14 @@ func (state *activeBuildStreamFileState) onFinishBuild() {
Branch: branch,
PlanBuildId: build.Id,
Scope: db.LockScopeWrite,
- Ctx: activePlan.Ctx,
- CancelFn: activePlan.CancelFn,
+ Ctx: ap.Ctx,
+ CancelFn: ap.CancelFn,
},
)
if err != nil {
log.Printf("Error locking repo for finished build: %v\n", err)
- activePlan.StreamDoneCh <- &shared.ApiError{
+ ap.StreamDoneCh <- &shared.ApiError{
Type: shared.ApiErrorTypeOther,
Status: http.StatusInternalServerError,
Msg: "Error locking repo for finished build: " + err.Error(),
@@ -148,7 +158,7 @@ func (state *activeBuildStreamFileState) onFinishBuild() {
if err != nil {
log.Printf("Error committing plan build: %v\n", err)
- activePlan.StreamDoneCh <- &shared.ApiError{
+ ap.StreamDoneCh <- &shared.ApiError{
Type: shared.ApiErrorTypeOther,
Status: http.StatusInternalServerError,
Msg: "Error committing plan build: " + err.Error(),
@@ -169,7 +179,7 @@ func (state *activeBuildStreamFileState) onFinishBuild() {
active := GetActivePlan(planId, branch)
if active != nil && (active.RepliesFinished || active.BuildOnly) {
- activePlan.Stream(shared.StreamMessage{
+ active.Stream(shared.StreamMessage{
Type: shared.StreamMessageFinished,
})
}
@@ -184,6 +194,12 @@ func (fileState *activeBuildStreamFileState) onFinishBuildFile(planRes *db.PlanF
activeBuild := fileState.activeBuild
activePlan := GetActivePlan(planId, branch)
+
+ if activePlan == nil {
+ log.Println("onFinishBuildFile - Active plan not found")
+ return
+ }
+
filePath := fileState.filePath
finished := false
diff --git a/app/server/model/plan/build_load.go b/app/server/model/plan/build_load.go
index 12265025..f799efef 100644
--- a/app/server/model/plan/build_load.go
+++ b/app/server/model/plan/build_load.go
@@ -128,6 +128,10 @@ func (state *activeBuildStreamFileState) loadBuildFile(activeBuild *types.Active
activePlan := GetActivePlan(planId, branch)
+ if activePlan == nil {
+ return fmt.Errorf("active plan not found")
+ }
+
convoMessageId := activeBuild.ReplyId
build := &db.PlanBuild{
diff --git a/app/server/model/plan/build_result.go b/app/server/model/plan/build_result.go
index aaa46333..ac8977c7 100644
--- a/app/server/model/plan/build_result.go
+++ b/app/server/model/plan/build_result.go
@@ -1,6 +1,7 @@
package plan
import (
+ "log"
"plandex-server/db"
"sort"
"strings"
@@ -53,6 +54,14 @@ func getPlanResult(params planResultParams) (*db.PlanFileResult, bool) {
startLine := streamedChange.Old.StartLine
endLine := streamedChange.Old.EndLine
+ if startLine == 0 && streamedChange.Old.MaybeStartLine != 0 {
+ startLine = streamedChange.Old.MaybeStartLine
+ }
+
+ if endLine == 0 && streamedChange.Old.MaybeEndLine != 0 {
+ endLine = streamedChange.Old.MaybeEndLine
+ }
+
if startLine < 1 {
startLine = 1
}
@@ -90,6 +99,12 @@ func getPlanResult(params planResultParams) (*db.PlanFileResult, bool) {
return iIdx < jIdx
})
+ log.Println("Will apply replacements")
+ // log.Println("currentState:", currentState)
+
+ // log.Println("Replacements:")
+ // spew.Dump(replacements)
+
_, allSucceeded := shared.ApplyReplacements(currentState, replacements, true)
for _, replacement := range replacements {
diff --git a/app/server/model/plan/build_stream.go b/app/server/model/plan/build_stream.go
index fda7307d..3ed21371 100644
--- a/app/server/model/plan/build_stream.go
+++ b/app/server/model/plan/build_stream.go
@@ -5,6 +5,7 @@ import (
"encoding/json"
"fmt"
"log"
+ "math"
"plandex-server/db"
"plandex-server/model"
"plandex-server/types"
@@ -51,6 +52,11 @@ func (fileState *activeBuildStreamFileState) listenStream(stream *openai.ChatCom
activePlan := GetActivePlan(planId, branch)
+ if activePlan == nil {
+ log.Printf("listenStream - Active plan not found for plan ID %s on branch %s\n", planId, branch)
+ return
+ }
+
defer stream.Close()
// Create a timer that will trigger if no chunk is received within the specified duration
@@ -125,11 +131,12 @@ func (fileState *activeBuildStreamFileState) listenStream(stream *openai.ChatCom
fileState.activeBuild.BufferTokens++
// After a reasonable threshhold, if buffer has significantly more tokens than original file + proposed changes, something is wrong
- if fileState.activeBuild.BufferTokens > 500 && fileState.activeBuild.BufferTokens > int(float64(fileState.activeBuild.CurrentFileTokens+fileState.activeBuild.FileContentTokens)*1.5) {
+ cutoff := int(math.Max(float64(fileState.activeBuild.CurrentFileTokens+fileState.activeBuild.FileContentTokens), 500) * 1.5)
+ if fileState.activeBuild.BufferTokens > 500 && fileState.activeBuild.BufferTokens > cutoff {
log.Printf("File %s: Stream buffer tokens too high\n", filePath)
log.Printf("Current file tokens: %d\n", fileState.activeBuild.CurrentFileTokens)
log.Printf("File content tokens: %d\n", fileState.activeBuild.FileContentTokens)
- log.Printf("Cutoff: %d\n", int(float64(fileState.activeBuild.CurrentFileTokens+fileState.activeBuild.FileContentTokens)*1.5))
+ log.Printf("Cutoff: %d\n", cutoff)
log.Printf("Buffer tokens: %d\n", fileState.activeBuild.BufferTokens)
log.Println("Buffer:")
log.Println(fileState.activeBuild.Buffer)
diff --git a/app/server/model/plan/commit_msg.go b/app/server/model/plan/commit_msg.go
index 01f16d92..83cd8d25 100644
--- a/app/server/model/plan/commit_msg.go
+++ b/app/server/model/plan/commit_msg.go
@@ -13,6 +13,10 @@ import (
)
func genPlanDescription(client *openai.Client, config shared.TaskRoleConfig, planId, branch string, ctx context.Context) (*db.ConvoMessageDescription, error) {
+ activePlan := GetActivePlan(planId, branch)
+ if activePlan == nil {
+ return nil, fmt.Errorf("active plan not found")
+ }
descResp, err := model.CreateChatCompletionWithRetries(
client,
@@ -38,7 +42,7 @@ func genPlanDescription(client *openai.Client, config shared.TaskRoleConfig, pla
},
{
Role: openai.ChatMessageRoleAssistant,
- Content: GetActivePlan(planId, branch).CurrentReplyContent,
+ Content: activePlan.CurrentReplyContent,
},
},
Temperature: config.Temperature,
diff --git a/app/server/model/plan/tell_exec.go b/app/server/model/plan/tell_exec.go
index 97852428..68044c9b 100644
--- a/app/server/model/plan/tell_exec.go
+++ b/app/server/model/plan/tell_exec.go
@@ -58,6 +58,11 @@ func execTellPlan(
active := GetActivePlan(plan.Id, branch)
+ if active == nil {
+ log.Printf("execTellPlan: Active plan not found for plan ID %s on branch %s\n", plan.Id, branch)
+ return
+ }
+
if os.Getenv("IS_CLOUD") != "" &&
missingFileResponse == "" {
log.Println("execTellPlan: IS_CLOUD environment variable is set")
diff --git a/app/server/model/plan/tell_load.go b/app/server/model/plan/tell_load.go
index bb7aec30..03986113 100644
--- a/app/server/model/plan/tell_load.go
+++ b/app/server/model/plan/tell_load.go
@@ -26,6 +26,10 @@ func (state *activeTellStreamState) loadTellPlan() error {
active := GetActivePlan(plan.Id, branch)
+ if active == nil {
+ return fmt.Errorf("no active plan with id %s", plan.Id)
+ }
+
lockScope := db.LockScopeWrite
if iteration > 0 || missingFileResponse != "" {
lockScope = db.LockScopeRead
diff --git a/app/server/model/plan/tell_stream.go b/app/server/model/plan/tell_stream.go
index c86db36a..dc2cf4a4 100644
--- a/app/server/model/plan/tell_stream.go
+++ b/app/server/model/plan/tell_stream.go
@@ -62,6 +62,11 @@ func (state *activeTellStreamState) listenStream(stream *openai.ChatCompletionSt
active := GetActivePlan(planId, branch)
+ if active == nil {
+ log.Printf("listenStream - Active plan not found for plan ID %s on branch %s\n", planId, branch)
+ return
+ }
+
replyFiles := []string{}
chunksReceived := 0
maybeRedundantBacktickContent := ""
@@ -477,7 +482,7 @@ func (state *activeTellStreamState) listenStream(stream *openai.ChatCompletionSt
continue
}
- log.Printf("New file: %s\n", file)
+ log.Printf("Detected file: %s\n", file)
if req.BuildMode == shared.BuildModeAuto {
log.Printf("Queuing build for %s\n", file)
buildState := &activeBuildStreamState{
@@ -532,6 +537,12 @@ func (state *activeTellStreamState) storeAssistantReply() (*db.ConvoMessage, str
log.Printf("storing assistant reply | len(convo) %d | num %d\n", len(convo), num)
+ activePlan := GetActivePlan(planId, branch)
+
+ if activePlan == nil {
+ return nil, "", fmt.Errorf("active plan not found")
+ }
+
assistantMsg := db.ConvoMessage{
Id: replyId,
OrgId: currentOrgId,
@@ -540,7 +551,7 @@ func (state *activeTellStreamState) storeAssistantReply() (*db.ConvoMessage, str
Role: openai.ChatMessageRoleAssistant,
Tokens: replyNumTokens,
Num: num,
- Message: GetActivePlan(planId, branch).CurrentReplyContent,
+ Message: activePlan.CurrentReplyContent,
}
commitMsg, err := db.StoreConvoMessage(&assistantMsg, auth.User.Id, branch, false)
@@ -567,6 +578,12 @@ func (state *activeTellStreamState) onError(streamErr error, storeDesc bool, con
summarizedToMessageId := state.summarizedToMessageId
active := GetActivePlan(planId, branch)
+
+ if active == nil {
+ log.Printf("tellStream onError - Active plan not found for plan ID %s on branch %s\n", planId, branch)
+ return
+ }
+
active.StreamDoneCh <- &shared.ApiError{
Type: shared.ApiErrorTypeOther,
Status: http.StatusInternalServerError,
diff --git a/app/server/model/plan/tell_summary.go b/app/server/model/plan/tell_summary.go
index 7bf7a56a..95d3d521 100644
--- a/app/server/model/plan/tell_summary.go
+++ b/app/server/model/plan/tell_summary.go
@@ -22,6 +22,11 @@ func (state *activeTellStreamState) summarizeMessagesIfNeeded() bool {
active := GetActivePlan(state.plan.Id, state.branch)
+ if active == nil {
+ log.Println("summarizeMessagesIfNeeded - Active plan not found")
+ return false
+ }
+
conversationTokens := 0
tokensUpToTimestamp := make(map[int64]int)
for _, convoMessage := range convo {
diff --git a/app/server/model/prompts/build.go b/app/server/model/prompts/build.go
index e750202d..14dfaeff 100644
--- a/app/server/model/prompts/build.go
+++ b/app/server/model/prompts/build.go
@@ -9,7 +9,14 @@ import (
)
func GetBuildSysPrompt(filePath, currentState, desc, changes string) string {
- return listChangesPrompt + "\n\n" + getBuildCurrentStatePrompt(filePath, currentState) + "\n\n" + getBuildPrompt(desc, changes)
+ currentStateWithLineNums := ""
+ var lastLineNum int
+ for i, line := range strings.Split(currentState, "\n") {
+ currentStateWithLineNums += fmt.Sprintf("%d: %s\n", i+1, line)
+ lastLineNum = i + 1
+ }
+
+ return getListChangesPrompt(lastLineNum) + "\n\n" + getBuildCurrentStatePrompt(filePath, currentStateWithLineNums) + "\n\n" + getBuildPrompt(desc, changes)
}
func getBuildPrompt(desc, changes string) string {
@@ -31,33 +38,32 @@ func getBuildPrompt(desc, changes string) string {
return s
}
-func getBuildCurrentStatePrompt(filePath, currentState string) string {
- if currentState == "" {
+func getBuildCurrentStatePrompt(filePath, withLineNums string) string {
+ if withLineNums == "" {
return ""
}
- withLineNums := ""
- for i, line := range strings.Split(currentState, "\n") {
- withLineNums += fmt.Sprintf("%d: %s\n", i+1, line)
- }
-
return fmt.Sprintf("**The current file is %s. Original state of the file:**\n```\n%s\n```", filePath, withLineNums) + "\n\n"
}
-var listChangesPrompt = `
+func getListChangesPrompt(lastLineNum int) string {
+ return fmt.Sprintf(`
You are an AI that analyzes a code file and an AI-generated plan to update the code file and produces a list of changes.
[YOUR INSTRUCTIONS]
Call the 'listChanges' function with a valid JSON object that includes the 'changes' keys.
- 'changes': An array of changes. Each change is an object with properties: 'summary', 'section', 'old', and 'new'.
+ 'changes': An array of NON-OVERLAPPING changes. Each change is an object with properties: 'summary', 'section', 'old', and 'new'.
- The 'summary' property is a brief summary of the change.
+ The 'summary' property is a brief summary of the change. At the end of the summary, consider if this change will overlap with any ensuing changes. If it will, include those changes in *this* change instead. Continue the summary and includes those ensuing changes that would otherwise overlap. Changes that remove code are especially likely to overlap with ensuing changes.
'summary' examples:
- 'Update loop that aggregates the results to iterate 10 times instead of 5 and log the value of someVar.'
- 'Update the Org model to include StripeCustomerId and StripeSubscriptionId fields.'
- 'Add function ExecQuery to execute a query.'
+
+ 'summary' that is larger to avoid overlap:
+ - 'Insert function ExecQuery after GetResults function in loop body. Update loop that aggregates the results to iterate 10 times instead of 5 and log the value of someVar. Add function ExecQuery to execute a query.'
The 'section' property is a description of what section of code from the original file will be replaced.
@@ -73,11 +79,25 @@ var listChangesPrompt = `
Ends: ' }\n }\n}'
---
- The 'old' property is an object with two properties: 'startLine' and 'endLine'.
+ The 'old' property is an object with 5 properties: 'maybeStartLine', 'maybeEndLine', 'err', 'startLine' and 'endLine'.
- 'startLine' is the line number where the section to be replaced begins in the original file. 'endLine' is the line number where the section to be replaced ends in the original file. For a single line replacement, 'startLine' and 'endLine' will be the same.
-
- Line numbers in 'startLine' and 'endLine' are 1-indexed. 1 is the minimum line number. The maximum line number is the number of lines in the original file. 'startLine' and 'endLine' must be valid line numbers in the original file, greater than or equal to 1 and less than or equal to the number of lines in the original file. You MUST refer to 1-indexed line numbers exactly as they are labeled in the original file. If the 'startLine' or 'endLine' is the first line of the file, 'startLine' or 'endLine' will be 1. If the 'startLine' or 'endLine' is the last line of the file, 'startLine' or 'endLine' will be the number of lines in the file. 'startLine' must NEVER be 0, -1, or any other number less than 1.
+ 'maybeStartLine' is the line number where the section to be replaced begins in the original file. 'maybeEndLine' is the line number where the section to be replaced ends in the original file. For a single line replacement, 'maybeStartLine' and 'maybeEndLine' will be the same.
+
+ 'maybeEndLine' MUST ABSOLUTELY ALWAYS be greater than or equal to 'maybeStartLine'.
+
+ Line numbers in 'maybeStartLine' and 'maybeEndLine' are 1-indexed. 1 is the minimum line number. The maximum line number is %d, the number of lines in the original file. 'maybeStartLine' and 'maybeEndLine' MUST be valid line numbers in the original file, greater than or equal to 1 and less than or equal to %d.
+
+ You MUST refer to 1-indexed line numbers exactly as they are labeled in the original file. If the 'maybeStartLine' or 'maybeEndLine' is the first line of the file, 'maybeStartLine' or 'maybeEndLine' will be 1.
+
+ If the 'maybeStartLine' or 'maybeEndLine' is the last line of the file, 'maybeStartLine' or 'maybeEndLine' will be %d.
+
+ Both 'maybeStartLine' and 'maybeEndLine' must NEVER be 0, -1, or any other number less than 1. They must NEVER be a number higher than %d.
+
+ 'err' is a string. If 'maybeEndLine' is greater than or equal to 'maybeStartLine', 'err' must be an empty string. Otherwise, 'err' must be a string that describes how the section from the original file can be better described in order to make the line numbers unambiguous and correct.
+
+ 'startLine' is the line number where the section to be replaced begins in the original file. *'startLine' MUST be an integer greater than 0.* If 'err' is not set or is an empty string, 'startLine' must be equal to 'maybeStartLine'. If 'err' is set and is *not* an empty string, 'startLine' should be the *corrected* line number where the section to be replaced begins in the original file.
+
+ 'endLine' is the line number where the section to be replaced ends in the original file. *'endLine' MUST be an integer greater than 0.* If 'err' is not set or is an empty string, 'endLine' must be equal to 'maybeEndLine'. If 'err' is set and is *not* an empty string, 'endLine' should be the *corrected* line number where the section to be replaced ends in the original file.
The 'new' property is a string that represents the new code that will replace the old code. The new code must be valid and consistent with the intention of the plan. If the the proposed update is to remove code, the 'new' property should be an empty string.
@@ -87,8 +107,11 @@ var listChangesPrompt = `
---
listChanges([{
summary: "Insert function ExecQuery after GetResults function in loop body.",
- section' "Begins: 'for i := 0; i < 10; i++ {...'\nEnds with ' }\n }\n}'",
+ section' "Begins: 'for i := 0; i < 10; i++ {...'\nEnds: ' }\n }\n}'",
old: {
+ maybeStartLine: 5,
+ maybeEndLine: 10,
+ err: "",
startLine: 5,
endLine: 10,
},
@@ -96,6 +119,23 @@ var listChangesPrompt = `
}])
---
+ Example function calls with errors:
+ ---
+ listChanges([{
+ summary: "Insert function ExecQuery after GetResults function in loop body.",
+ section' "Begins: 'for i := 0; i < 10; i++ {...'\nEnds: ' }\n }\n}'",
+ old: {
+ maybeStartLine: 5,
+ maybeEndLine: 4,
+ err: "maybeStartLine is greater than maybeEndLine. The 'begins' section is ambiguous. Here's a better 'begins' section: '// Loop up to 10\nfor i := 0; i < 10; i++ {\n // Loop body'",
+ startLine: 5,
+ endLine: 10,
+ },
+ new: " execQuery()\n }\n }\n}",
+ }])
+
+ You ABSOLUTELY MUST NOT generate overlapping changes. The start line of each change MUST be **greater than** the end line of the previous change. Group smaller changes together into larger changes where necessary to avoid overlap. Only generate multiple changes when you are ABSOLUTELY CERTAIN that they do not overlap--otherwise group them together into a single change.
+
Apply changes intelligently in order to avoid syntax errors, breaking code, or removing code from the original file that should not be removed. Consider the reason behind the update and make sure the result is consistent with the intention of the plan.
You ABSOLUTELY MUST NOT ovewrite or delete code from the original file unless the plan *clearly intends* for the code to be overwritten or removed. Do NOT replace a full section of code with only new code unless that is the clear intention of the plan. Instead, merge the original code and the proposed changes together intelligently according to the intention of the plan.
@@ -105,7 +145,9 @@ var listChangesPrompt = `
The 'listChanges' function MUST be called *valid JSON*. Double quotes within json properties of the 'listChanges' function call parameters JSON object *must be properly escaped* with a backslash.
[END YOUR INSTRUCTIONS]
-`
+`, lastLineNum, lastLineNum, lastLineNum, lastLineNum)
+}
+
var ListReplacementsFn = openai.FunctionDefinition{
Name: "listChanges",
Parameters: &jsonschema.Definition{
@@ -125,6 +167,15 @@ var ListReplacementsFn = openai.FunctionDefinition{
"old": {
Type: jsonschema.Object,
Properties: map[string]jsonschema.Definition{
+ "maybeStartLine": {
+ Type: jsonschema.Integer,
+ },
+ "maybeEndLine": {
+ Type: jsonschema.Integer,
+ },
+ "err": {
+ Type: jsonschema.String,
+ },
"startLine": {
Type: jsonschema.Integer,
},
@@ -132,7 +183,7 @@ var ListReplacementsFn = openai.FunctionDefinition{
Type: jsonschema.Integer,
},
},
- Required: []string{"startLine", "endLine"},
+ Required: []string{"maybeStartLine", "maybeEndLine", "startLine", "endLine"},
},
"new": {
Type: jsonschema.String,
diff --git a/app/shared/plan_result_replacements.go b/app/shared/plan_result_replacements.go
index 8627f3d1..c20dd011 100644
--- a/app/shared/plan_result_replacements.go
+++ b/app/shared/plan_result_replacements.go
@@ -10,33 +10,83 @@ import (
)
func ApplyReplacements(content string, replacements []*Replacement, setFailed bool) (string, bool) {
- updated := content
+ apply := func(replacements []*Replacement) (string, int) {
+ updated := content
+ lastInsertedIdx := 0
- allSucceeded := true
+ for i, replacement := range replacements {
+ // log.Println("replacement.Old:\n", replacement.Old)
+ // log.Println("updated:\n", updated)
+ // log.Println("lastInsertedIdx:", lastInsertedIdx)
- for _, replacement := range replacements {
- originalIdx := strings.Index(updated, replacement.Old)
+ pre := updated[:lastInsertedIdx]
+ sub := updated[lastInsertedIdx:]
+ originalIdx := strings.Index(updated, replacement.Old)
- // log.Println("originalIdx:", originalIdx)
+ // log.Println("originalIdx:", originalIdx)
- if originalIdx == -1 {
- allSucceeded = false
- if setFailed {
- replacement.Failed = true
+ if originalIdx == -1 {
+ if setFailed {
+ replacement.Failed = true
+ }
+
+ log.Println("Replacement failed at index:", i)
+ log.Println("Replacement:")
+ log.Println(spew.Sdump(replacement))
+
+ log.Println("Updated:")
+ log.Println(updated)
+
+ return updated, i
+ } else {
+ // log.Printf("originalIdx: %d, len(replacement.Old): %d\n", originalIdx, len(replacement.Old))
+ // log.Println("Old: ", replacement.Old)
+ // log.Println("New: ", replacement.New)
+ replaced := strings.Replace(sub, replacement.Old, replacement.New, 1)
+
+ // log.Println("replaced:")
+ // log.Println(replaced)
+
+ updated = pre + replaced
+
+ // log.Printf("lastInsertedIdx: %d, originalIdx: %d, len(replacement.New): %d\n", lastInsertedIdx, originalIdx, len(replacement.New))
+
+ // log.Println("updated after replacement:")
+ // log.Println(updated)
+
+ lastInsertedIdx = lastInsertedIdx + originalIdx + len(replacement.New)
}
+ }
+
+ return updated, -1
+ }
+
+ for {
+ res, failedAtIndex := apply(replacements)
- log.Println("Replacement failed:")
- log.Println(spew.Sdump(replacement))
+ if failedAtIndex == 0 {
+ return res, false
+ } else if failedAtIndex > 0 {
+ // check if there's overlap between the failed replacement and the previous replacement
+ // if there is, remove the previous one and try again
+ failed := replacements[failedAtIndex]
+ prev := replacements[failedAtIndex-1]
- log.Println("Updated:")
- log.Println(updated)
+ hasOverlap := failed.StreamedChange.Old.StartLine <= prev.StreamedChange.Old.EndLine
+
+ if hasOverlap {
+ replacements = append(replacements[:failedAtIndex-1], replacements[failedAtIndex:]...)
+
+ continue
+ } else {
+ return res, false
+ }
} else {
- updated = strings.Replace(updated, replacement.Old, replacement.New, 1)
+ return res, true
}
}
- return updated, allSucceeded
}
func (planState *CurrentPlanState) GetFiles() (*CurrentPlanFiles, error) {
diff --git a/app/shared/plan_settings.go b/app/shared/plan_settings.go
index 5a017a87..c682c395 100644
--- a/app/shared/plan_settings.go
+++ b/app/shared/plan_settings.go
@@ -12,7 +12,7 @@ const (
ModelRoleBuilder ModelRole = "builder"
ModelRoleName ModelRole = "names"
ModelRoleCommitMsg ModelRole = "commit-messages"
- ModelRoleExecStatus ModelRole = "auto-complete"
+ ModelRoleExecStatus ModelRole = "auto-continue"
)
var AllModelRoles = []ModelRole{ModelRolePlanner, ModelRolePlanSummary, ModelRoleBuilder, ModelRoleName, ModelRoleCommitMsg, ModelRoleExecStatus}
diff --git a/app/shared/streamed_change.go b/app/shared/streamed_change.go
index 2954771c..71a799e1 100644
--- a/app/shared/streamed_change.go
+++ b/app/shared/streamed_change.go
@@ -1,6 +1,10 @@
package shared
type StreamedChangeSection struct {
+ MaybeStartLine int `json:"maybeStartLine"`
+ MaybeEndLine int `json:"maybeEndLine"`
+ Err string `json:"err"`
+
StartLine int `json:"startLine"`
EndLine int `json:"endLine"`
}
diff --git a/releases/server/versions/0.8.2.md b/releases/server/versions/0.8.2.md
index 7be7206d..440e7c0f 100644
--- a/releases/server/versions/0.8.2.md
+++ b/releases/server/versions/0.8.2.md
@@ -1 +1,6 @@
-- Fix for creating an org that auto-adds users based on email domain (https://github.com/plandex-ai/plandex/issues/24)
\ No newline at end of file
+- Fix for creating an org that auto-adds users based on email domain (https://github.com/plandex-ai/plandex/issues/24)
+- Fix for possible crash after error in file build
+- Added crash prevention measures across the board
+- Fix for occasional "replacements failed" error
+- Reliability and improvements for file updates
+- Fix for role name of auto-continue model
\ No newline at end of file
diff --git a/test/test_prompts/pong.txt b/test/test_prompts/pong.txt
new file mode 100644
index 00000000..821fb18a
--- /dev/null
+++ b/test/test_prompts/pong.txt
@@ -0,0 +1,2 @@
+let's create a basic pong game using C and OpenGL. create all the files for
+ the project so that it will be ready to compile and run
diff --git a/test/test_prompts/tic-tac-toe.txt b/test/test_prompts/tic-tac-toe.txt
new file mode 100644
index 00000000..158cc000
--- /dev/null
+++ b/test/test_prompts/tic-tac-toe.txt
@@ -0,0 +1 @@
+Build a complete tic-tac-toe game in rust