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
updates to code block format in order to correctly handle markdown output with triple backticks. buffering in tell stream in order to still return nicely formatted markdown code blocks to client. significant refactoring of tell stream processing, since it was getting out of control.
Dane Schneiderd8f24b3d3c09
diff --git a/app/cli/go.mod b/app/cli/go.modindex 2aa9dbc6..24773538 100644--- a/app/cli/go.mod+++ b/app/cli/go.mod@@ -3,6 +3,7 @@ module plandexgo 1.23.3require (+ github.com/alecthomas/chroma/v2 v2.14.0github.com/atotto/clipboard v0.1.4github.com/charmbracelet/lipgloss v0.10.0github.com/davecgh/go-spew v1.1.1diff --git a/app/cli/go.sum b/app/cli/go.sumindex f137bbeb..5bb1487a 100644--- a/app/cli/go.sum+++ b/app/cli/go.sum@@ -191,8 +191,14 @@ github.com/Netflix/go-expect v0.0.0-20220104043353-73e0943537d2/go.mod h1:HBCaDegithub.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU=github.com/PuerkitoBio/goquery v1.8.1 h1:uQxhNlArOIdbrH1tr0UXwdVFgDcZDrZVdcpygAcwmWM=github.com/PuerkitoBio/goquery v1.8.1/go.mod h1:Q8ICL1kNUJ2sXGoAhPGUdYDJvgQgHzJsnnd3H7Ho5jQ=+github.com/alecthomas/assert/v2 v2.7.0 h1:QtqSACNS3tF7oasA8CU6A6sXZSBDqnm7RfpLl9bZqbE=+github.com/alecthomas/assert/v2 v2.7.0/go.mod h1:Bze95FyfUr7x34QZrjL+XP+0qgp/zg8yS+TtBj1WA3k=github.com/alecthomas/chroma v0.10.0 h1:7XDcGkCQopCNKjZHfYrNLraA+M7e0fMiJ/Mfikbfjek=github.com/alecthomas/chroma v0.10.0/go.mod h1:jtJATyUxlIORhUOFNA9NZDWGAQ8wpxQQqNSB4rjA/1s=+github.com/alecthomas/chroma/v2 v2.14.0 h1:R3+wzpnUArGcQz7fCETQBzO5n9IMNi13iIs46aU4V9E=+github.com/alecthomas/chroma/v2 v2.14.0/go.mod h1:QolEbTfmUHIMVpBqxeDnNBj2uoeI4EbYP4i6n68SG4I=+github.com/alecthomas/repr v0.4.0 h1:GhI2A8MACjfegCPVq9f1FLvIBS+DrQ2KQBFZP1iFzXc=+github.com/alecthomas/repr v0.4.0/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4=github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=@@ -462,6 +468,8 @@ github.com/hashicorp/memberlist v0.3.0/go.mod h1:MS2lj3INKhZjWNqd3N0m3J+Jxf3DAOngithub.com/hashicorp/memberlist v0.3.1/go.mod h1:MS2lj3INKhZjWNqd3N0m3J+Jxf3DAOnAH9VT3Sh9MUE=github.com/hashicorp/serf v0.9.7/go.mod h1:TXZNMjZQijwlDvp+r0b63xZ45H7JmCmgg4gpTwn9UV4=github.com/hashicorp/serf v0.9.8/go.mod h1:TXZNMjZQijwlDvp+r0b63xZ45H7JmCmgg4gpTwn9UV4=+github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM=+github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg=github.com/hinshun/vt10x v0.0.0-20220119200601-820417d04eec h1:qv2VnGeEQHchGaZ/u7lxST/RaJw+cv273q79D81Xbog=github.com/hinshun/vt10x v0.0.0-20220119200601-820417d04eec/go.mod h1:Q48J4R4DvxnHolD5P8pOtXigYlRuPLGl6moFx3ulM68=github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=diff --git a/app/server/model/plan/tell_file_ops.go b/app/server/model/plan/tell_file_ops.goindex 0c7e987d..9bc02178 100644--- a/app/server/model/plan/tell_file_ops.go+++ b/app/server/model/plan/tell_file_ops.go@@ -1,7 +1,11 @@package planimport (+ "log""plandex-server/model/parse"+ "plandex-server/types"++ "github.com/plandex/plandex/shared")func (state *activeTellStreamState) checkMoveFileOps() []parse.FileMove {@@ -39,3 +43,79 @@ func (state *activeTellStreamState) checkResetFileOps() []string {return resetFiles}++func (state *activeTellStreamState) handleFileOps() {+ req := state.req+ clients := state.clients+ auth := state.auth+ currentOrgId := state.currentOrgId+ currentUserId := state.currentUserId+ plan := state.plan+ branch := state.branch+ settings := state.settings+ replyId := state.replyId++ moveFiles := state.checkMoveFileOps()+ removeFiles := state.checkRemoveFileOps()+ resetFiles := state.checkResetFileOps()++ if req.BuildMode == shared.BuildModeAuto {+ getBuildState := func() *activeBuildStreamState {+ return &activeBuildStreamState{+ tellState: state,+ clients: clients,+ auth: auth,+ currentOrgId: currentOrgId,+ currentUserId: currentUserId,+ plan: plan,+ branch: branch,+ settings: settings,+ modelContext: state.modelContext,+ }+ }++ if len(moveFiles) > 0 {+ log.Println("Detected move files, queuing builds")+ for i, moveFile := range moveFiles {+ getBuildState().queueBuilds([]*types.ActiveBuild{+ {+ ReplyId: replyId,+ Idx: i,+ Path: moveFile.Source,+ IsMoveOp: true,+ MoveDestination: moveFile.Destination,+ },+ })+ }+ }++ if len(removeFiles) > 0 {+ log.Println("Detected remove files, queuing builds")+ for i, removeFile := range removeFiles {+ getBuildState().queueBuilds([]*types.ActiveBuild{+ {+ ReplyId: replyId,+ Idx: i,+ Path: removeFile,+ IsRemoveOp: true,+ },+ })+ }+ }++ if len(resetFiles) > 0 {+ log.Println("Detected reset files, queuing builds")++ for i, resetFile := range resetFiles {+ getBuildState().queueBuilds([]*types.ActiveBuild{+ {+ ReplyId: replyId,+ Idx: i,+ Path: resetFile,+ IsResetOp: true,+ },+ })+ }+ }+ }+}diff --git a/app/server/model/plan/tell_state.go b/app/server/model/plan/tell_state.goindex 98dc64f7..69edc3c7 100644--- a/app/server/model/plan/tell_state.go+++ b/app/server/model/plan/tell_state.go@@ -3,6 +3,7 @@ package planimport ("plandex-server/db""plandex-server/types"+ "strings""github.com/plandex/plandex/shared""github.com/sashabaranov/go-openai"@@ -36,4 +37,17 @@ type activeTellStreamState struct {currentReplyNumRetries intsubtasks []*db.SubtaskcurrentSubtask *db.Subtask++ chunkProcessor *chunkProcessor+}++type chunkProcessor struct {+ replyFiles []string+ chunksReceived int+ maybeRedundantOpeningTagContent string+ fileOpen bool+ contentBuffer strings.Builder+ awaitingOpeningTag bool+ awaitingClosingTag bool+ awaitingBackticks bool}diff --git a/app/server/model/plan/tell_stream.go b/app/server/model/plan/tell_stream.godeleted file mode 100644index 6018bd3c..00000000--- a/app/server/model/plan/tell_stream.go+++ /dev/null@@ -1,1012 +0,0 @@-package plan--import (- "context"- "fmt"- "log"- "net/http"- "plandex-server/db"- "plandex-server/hooks"- "plandex-server/model"- "plandex-server/types"- "strings"- "time"-- "github.com/davecgh/go-spew/spew"- "github.com/plandex/plandex/shared"- "github.com/sashabaranov/go-openai"-)--const MaxAutoContinueIterations = 100-const MaxSendRate = 30 * time.Millisecond-const MaxTellStreamRetries = 4--func (state *activeTellStreamState) listenStream(stream *openai.ChatCompletionStream) {- defer stream.Close()-- clients := state.clients- auth := state.auth- req := state.req- plan := state.plan- planId := plan.Id- branch := state.branch- currentOrgId := state.currentOrgId- currentUserId := state.currentUserId- convo := state.convo- summaries := state.summaries- summarizedToMessageId := state.summarizedToMessageId- iteration := state.iteration- missingFileResponse := state.missingFileResponse- replyId := state.replyId- replyParser := state.replyParser- settings := state.settings-- 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 := ""- fileOpen := false-- // Create a timer that will trigger if no chunk is received within the specified duration- timer := time.NewTimer(model.OPENAI_STREAM_CHUNK_TIMEOUT)- defer timer.Stop()-- streamFinished := false-- execHookOnStop := func(sendStreamErr bool) {- _, apiErr := hooks.ExecHook(hooks.DidSendModelRequest, hooks.HookParams{- Auth: auth,- Plan: plan,- DidSendModelRequestParams: &hooks.DidSendModelRequestParams{- InputTokens: state.totalRequestTokens,- OutputTokens: active.NumTokens,- ModelName: state.settings.ModelPack.Planner.BaseModelConfig.ModelName,- ModelProvider: state.settings.ModelPack.Planner.BaseModelConfig.Provider,- ModelPackName: state.settings.ModelPack.Name,- ModelRole: shared.ModelRolePlanner,- Purpose: "Generated plan reply",- },- })-- if apiErr != nil {- log.Printf("Error executing did send model request hook after cancel or error: %v\n", apiErr)-- if sendStreamErr {- activePlan := GetActivePlan(planId, branch)-- if activePlan == nil {- log.Printf(" Active plan not found for plan ID %s on branch %s\n", planId, branch)- return- }-- activePlan.StreamDoneCh <- apiErr- }- }- }--mainLoop:- for {- select {- case <-active.Ctx.Done():- // The main modelContext was canceled (not the timer)- log.Println("\nTell: stream canceled")- execHookOnStop(false)- return- case <-timer.C:- // Timer triggered because no new chunk was received in time- log.Println("\nTell: stream timeout due to inactivity")- if streamFinished {- log.Println("Tell stream finished—timed out waiting for usage chunk")- execHookOnStop(true)- return- } else {- state.onError(fmt.Errorf("stream timeout due to inactivity | This usually means the model is not responding."), true, "", "")- continue mainLoop- }-- default:- response, err := stream.Recv()-- if err == nil {- // Successfully received a chunk, reset the timer- if !timer.Stop() {- <-timer.C- }- timer.Reset(model.OPENAI_STREAM_CHUNK_TIMEOUT)- } else {- if err.Error() == "context canceled" {- log.Println("Tell: stream context canceled")- execHookOnStop(false)- return- }-- log.Printf("Tell: error receiving stream chunk: %v\n", err)- execHookOnStop(true)- return- }-- if len(response.Choices) == 0 {- if response.Usage != nil {-- log.Println("Tell stream usage:")- spew.Dump(response.Usage)-- _, apiErr := hooks.ExecHook(hooks.DidSendModelRequest, hooks.HookParams{- Auth: auth,- Plan: plan,- DidSendModelRequestParams: &hooks.DidSendModelRequestParams{- InputTokens: response.Usage.PromptTokens,- OutputTokens: response.Usage.CompletionTokens,- ModelName: state.settings.ModelPack.Planner.BaseModelConfig.ModelName,- ModelProvider: state.settings.ModelPack.Planner.BaseModelConfig.Provider,- ModelPackName: state.settings.ModelPack.Name,- ModelRole: shared.ModelRolePlanner,- Purpose: "Generated plan reply",- },- })-- if apiErr != nil {- log.Printf("Tell stream: error executing did send model request hook: %v\n", err)-- // ensure the active plan is still available- activePlan := GetActivePlan(planId, branch)-- if activePlan == nil {- log.Printf(" Active plan not found for plan ID %s on branch %s\n", planId, branch)- return- }-- activePlan.StreamDoneCh <- apiErr- }- return- }-- state.onError(fmt.Errorf("stream finished with no choices | This usually means the model failed to generate a valid response."), true, "", "")- continue mainLoop- }-- // if stream finished and it's not a usage chunk, keeep listening for usage chunk- if streamFinished {- // log.Println("Tell stream finished—no usage chunk-will keep listening")- // continue- }-- if len(response.Choices) > 1 {- state.onError(fmt.Errorf("stream finished with more than one choice | This usually means the model failed to generate a valid response."), true, "", "")- continue mainLoop- }-- choice := response.Choices[0]-- if choice.FinishReason != "" {- log.Println("Model stream finished")- log.Println("Finish reason: ", choice.FinishReason)-- if choice.FinishReason == "error" {- state.onError(fmt.Errorf("model stopped with error status | This usually means the model is not responding."), true, "", "")- continue mainLoop- }-- time.Sleep(30 * time.Millisecond)- active.FlushStreamBuffer()- time.Sleep(100 * time.Millisecond)-- active.Stream(shared.StreamMessage{- Type: shared.StreamMessageDescribing,- })- active.FlushStreamBuffer()-- err := db.SetPlanStatus(planId, branch, shared.PlanStatusDescribing, "")- if err != nil {- state.onError(fmt.Errorf("failed to set plan status to describing: %v", err), true, "", "")- continue mainLoop- }-- var generatedDescription *db.ConvoMessageDescription- var shouldContinue bool- var subtaskFinished bool-- autoLoadContextFiles := state.checkAutoLoadContext()- hasNewSubtasks := state.checkNewSubtasks()- moveFiles := state.checkMoveFileOps()- removeFiles := state.checkRemoveFileOps()- resetFiles := state.checkResetFileOps()- var allSubtasksFinished bool-- if req.BuildMode == shared.BuildModeAuto {- getBuildState := func() *activeBuildStreamState {- return &activeBuildStreamState{- tellState: state,- clients: clients,- auth: auth,- currentOrgId: currentOrgId,- currentUserId: currentUserId,- plan: plan,- branch: branch,- settings: settings,- modelContext: state.modelContext,- }- }-- if len(moveFiles) > 0 {- log.Println("Detected move files, queuing builds")- for i, moveFile := range moveFiles {- getBuildState().queueBuilds([]*types.ActiveBuild{- {- ReplyId: replyId,- Idx: i,- Path: moveFile.Source,- IsMoveOp: true,- MoveDestination: moveFile.Destination,- },- })- }- }-- if len(removeFiles) > 0 {- log.Println("Detected remove files, queuing builds")- for i, removeFile := range removeFiles {- getBuildState().queueBuilds([]*types.ActiveBuild{- {- ReplyId: replyId,- Idx: i,- Path: removeFile,- IsRemoveOp: true,- },- })- }- }-- if len(resetFiles) > 0 {- log.Println("Detected reset files, queuing builds")-- for i, resetFile := range resetFiles {- getBuildState().queueBuilds([]*types.ActiveBuild{- {- ReplyId: replyId,- Idx: i,- Path: resetFile,- IsResetOp: true,- },- })- }- }- }-- var errCh = make(chan error, 2)-- go func() {- if len(replyFiles) > 0 {- log.Println("Generating plan description")-- res, err := state.genPlanDescription()- if err != nil {- errCh <- fmt.Errorf("failed to generate plan description: %v", err)- return- }-- generatedDescription = res- generatedDescription.OrgId = currentOrgId- generatedDescription.SummarizedToMessageId = summarizedToMessageId- generatedDescription.MadePlan = true- generatedDescription.Files = replyFiles-- log.Println("Generated plan description.")- }- errCh <- nil- }()-- if req.IsChatOnly || len(autoLoadContextFiles) > 0 || hasNewSubtasks || !req.AutoContinue {-- // if we're auto-loading context files, we always want to continue for at least another iteration with the loaded context (even if it's chat only)- if len(autoLoadContextFiles) > 0 && !hasNewSubtasks {- log.Printf("Auto loading context files, so continuing to planning phase")- shouldContinue = true- } else if req.IsChatOnly {- log.Printf("Chat only, won't continue")- shouldContinue = false- } else if hasNewSubtasks {- log.Printf("Has new subtasks, can continue")- shouldContinue = req.AutoContinue- }-- errCh <- nil- } else {- go func() {- log.Println("Getting exec status")- subtaskFinished, shouldContinue, err = state.execStatusShouldContinue(active.CurrentReplyContent, active.Ctx)- if err != nil {- errCh <- fmt.Errorf("failed to get exec status: %v", err)- return- }-- log.Printf("Should continue: %v\n", shouldContinue)-- errCh <- nil- }()- }-- for i := 0; i < 2; i++ {- err := <-errCh- if err != nil {- state.onError(err, true, "", "")- continue mainLoop- }- }-- log.Println("Locking repo to store assistant reply and description")-- repoLockId, err := db.LockRepo(- db.LockRepoParams{- OrgId: currentOrgId,- UserId: currentUserId,- PlanId: planId,- Branch: branch,- Scope: db.LockScopeWrite,- Ctx: active.Ctx,- CancelFn: active.CancelFn,- },- )-- if err != nil {- log.Printf("Error locking repo: %v\n", err)- active.StreamDoneCh <- &shared.ApiError{- Type: shared.ApiErrorTypeOther,- Status: http.StatusInternalServerError,- Msg: "Error locking repo",- }- continue mainLoop- }-- log.Println("Locked repo for assistant reply and description")-- err = func() error {- defer func() {- if err != nil {- log.Printf("Error storing reply and description: %v\n", err)- err = db.GitClearUncommittedChanges(auth.OrgId, planId)- if err != nil {- log.Printf("Error clearing uncommitted changes: %v\n", err)- }- }-- log.Println("Unlocking repo for assistant reply and description")-- err = db.DeleteRepoLock(repoLockId)- if err != nil {- log.Printf("Error unlocking repo: %v\n", err)- active.StreamDoneCh <- &shared.ApiError{- Type: shared.ApiErrorTypeOther,- Status: http.StatusInternalServerError,- Msg: "Error unlocking repo",- }- }- }()-- assistantMsg, convoCommitMsg, err := state.storeAssistantReply() // updates state.convo- convo = state.convo-- if err != nil {- state.onError(fmt.Errorf("failed to store assistant message: %v", err), true, "", "")- return err- }-- log.Println("getting description for assistant message: ", assistantMsg.Id)-- var description *db.ConvoMessageDescription- if len(replyFiles) == 0 {- description = &db.ConvoMessageDescription{- OrgId: currentOrgId,- PlanId: planId,- ConvoMessageId: assistantMsg.Id,- SummarizedToMessageId: summarizedToMessageId,- BuildPathsInvalidated: map[string]bool{},- MadePlan: false,- }- } else {- description = generatedDescription- description.ConvoMessageId = assistantMsg.Id- }-- log.Println("Storing description")- err = db.StoreDescription(description)-- if err != nil {- state.onError(fmt.Errorf("failed to store description: %v", err), false, assistantMsg.Id, convoCommitMsg)- return err- }- log.Println("Description stored")-- if hasNewSubtasks || subtaskFinished {- if subtaskFinished && state.currentSubtask != nil {- log.Println("Subtask finished")- log.Println("Current subtask:")- log.Println(state.currentSubtask.Title)- state.currentSubtask.IsFinished = true-- log.Println("Updated state. Current subtask:")- log.Println(state.currentSubtask)- }-- log.Println("Storing plan subtasks")- err = db.StorePlanSubtasks(currentOrgId, planId, state.subtasks)- if err != nil {- log.Printf("Error storing plan subtasks: %v\n", err)- state.onError(fmt.Errorf("failed to store plan subtasks: %v", err), false, assistantMsg.Id, convoCommitMsg)- return err- }-- state.currentSubtask = nil- allSubtasksFinished = true- for _, subtask := range state.subtasks {- if !subtask.IsFinished {- state.currentSubtask = subtask- allSubtasksFinished = false- break- }- }-- log.Println("Set new current subtask. Current subtask:")- log.Println(state.currentSubtask)- log.Println("All subtasks finished:", allSubtasksFinished)-- log.Println("Update state of subtasks")- spew.Dump(state.subtasks)- }-- // spew.Dump(description)-- log.Println("Comitting reply message, description, and subtasks")-- err = db.GitAddAndCommit(currentOrgId, planId, branch, convoCommitMsg)- if err != nil {- state.onError(fmt.Errorf("failed to commit: %v", err), false, assistantMsg.Id, convoCommitMsg)- return err- }- log.Println("Assistant reply, description, and subtasks committed")-- return nil- }()-- if err != nil {- continue mainLoop- }-- // summarize convo needs to come *after* the reply is stored in order to correctly summarize the latest message- log.Println("summarize convo")- envVar := settings.ModelPack.PlanSummary.BaseModelConfig.ApiKeyEnvVar- client := clients[envVar]-- // summarize in the background- go func() {- err := summarizeConvo(client, settings.ModelPack.PlanSummary, summarizeConvoParams{- auth: auth,- plan: plan,- branch: branch,- convo: convo,- summaries: summaries,- userPrompt: state.userPrompt,- currentOrgId: currentOrgId,- currentReply: active.CurrentReplyContent,- currentReplyNumTokens: active.NumTokens,- modelPackName: settings.ModelPack.Name,- }, active.SummaryCtx)-- if err != nil {- log.Printf("Error summarizing convo: %v\n", err)- active.StreamDoneCh <- &shared.ApiError{- Type: shared.ApiErrorTypeOther,- Status: http.StatusInternalServerError,- Msg: fmt.Sprintf("Error summarizing convo: %v", err),- }- }- }()-- log.Println("Sending active.CurrentReplyDoneCh <- true")-- active.CurrentReplyDoneCh <- true-- log.Println("Resetting active.CurrentReplyDoneCh")-- UpdateActivePlan(planId, branch, func(ap *types.ActivePlan) {- ap.CurrentStreamingReplyId = ""- ap.CurrentReplyDoneCh = nil- })-- log.Printf("len(autoLoadContextFiles): %d\n", len(autoLoadContextFiles))- if len(autoLoadContextFiles) > 0 {- log.Println("Sending stream message to load context files")-- active.Stream(shared.StreamMessage{- Type: shared.StreamMessageLoadContext,- LoadContextFiles: autoLoadContextFiles,- })- active.FlushStreamBuffer()-- // Force a small delay to ensure message is processed- time.Sleep(100 * time.Millisecond)-- log.Println("Waiting for client to auto load context (30s timeout)")-- select {- case <-active.Ctx.Done():- log.Println("Context cancelled while waiting for auto load context")- execHookOnStop(true)- return- case <-time.After(30 * time.Second):- log.Println("Timeout waiting for auto load context")- state.onError(fmt.Errorf("timeout waiting for auto load context response"), true, "", "")- continue mainLoop- case <-active.AutoLoadContextCh:- }- }-- // if we're auto-loading context files, we always want to continue for at least another iteration with the loaded context- log.Printf("req.AutoContinue: %v\n", req.AutoContinue)- log.Printf("shouldContinue: %v\n", shouldContinue)- log.Printf("iteration: %d\n", iteration)- log.Printf("MaxAutoContinueIterations: %d\n", MaxAutoContinueIterations)- log.Printf("hasNewSubtasks: %v\n", hasNewSubtasks)- log.Printf("len(state.subtasks): %d\n", len(state.subtasks))- log.Printf("allSubtasksFinished: %v\n", allSubtasksFinished)-- if (len(autoLoadContextFiles) > 0 && !hasNewSubtasks) ||- (req.AutoContinue && shouldContinue && iteration < MaxAutoContinueIterations &&- !(len(state.subtasks) > 0 && allSubtasksFinished)) {- log.Println("Auto continue plan")- // continue plan- execTellPlan(clients, plan, branch, auth, req, iteration+1, "", false, 0)- } else {- var buildFinished bool- UpdateActivePlan(planId, branch, func(ap *types.ActivePlan) {- buildFinished = ap.BuildFinished()- ap.RepliesFinished = true- })-- log.Printf("Won't continue plan. Build finished: %v\n", buildFinished)-- time.Sleep(50 * time.Millisecond)-- // note: tell-based verification is currently disabled, so 'verifyOrFinish' will pass through to 'finish' logic- // ShouldVerifyDiff will always be false unless we re-enable tell-based verification- if buildFinished {- log.Println("Reply is finished and build is finished, calling verifyOrFinish")- active := GetActivePlan(planId, branch)-- if active == nil {- log.Printf("Active plan not found for planId: %s, branch: %s\n", planId, branch)- continue mainLoop- }-- active.Finish()- } else {- log.Println("Plan is still building")- log.Println("Updating status to building")- err := db.SetPlanStatus(planId, branch, shared.PlanStatusBuilding, "")- if err != nil {- log.Printf("Error setting plan status to building: %v\n", err)- active.StreamDoneCh <- &shared.ApiError{- Type: shared.ApiErrorTypeOther,- Status: http.StatusInternalServerError,- Msg: "Error setting plan status to building",- }- continue mainLoop- }-- log.Println("Sending RepliesFinished stream message")- active.Stream(shared.StreamMessage{- Type: shared.StreamMessageRepliesFinished,- })-- }- }-- // Reset the timer for the usage chunk- if !timer.Stop() {- <-timer.C- }- timer.Reset(model.OPENAI_USAGE_CHUNK_TIMEOUT)- streamFinished = true- continue- }-- chunksReceived++- delta := choice.Delta- content := delta.Content-- // log.Printf("content: %s\n", content)-- if missingFileResponse != "" {- if maybeRedundantBacktickContent != "" {- if strings.Contains(content, "\n") {- maybeRedundantBacktickContent = ""- } else {- maybeRedundantBacktickContent += content- }- continue // skip processing this chunk- } else if chunksReceived < 3 && strings.Contains(content, "```") {- // received closing triple backticks in first 3 chunks after missing file response- // means this is a redundant start of a new file block, so just ignore it-- maybeRedundantBacktickContent += content- continue // skip processing this chunk- }- }-- // log.Printf("Adding chunk to parser: %s\n", content)- // log.Printf("fileOpen: %v\n", fileOpen)-- replyParser.AddChunk(content, true)- parserRes := replyParser.Read()-- if !fileOpen && parserRes.CurrentFilePath != "" {- log.Printf("File open: %s\n", parserRes.CurrentFilePath)- fileOpen = true- }-- if fileOpen && strings.HasSuffix(content, "```") {- log.Println("FinishAndRead because of closing backticks")- parserRes = replyParser.FinishAndRead()- fileOpen = false- }-- if fileOpen && parserRes.CurrentFilePath == "" {- // log.Println("File open but current file path is empty, closing file")- fileOpen = false- }-- files := parserRes.Files- fileContents := parserRes.FileContents- state.replyNumTokens = parserRes.TotalTokens- currentFile := parserRes.CurrentFilePath- fileDescriptions := parserRes.FileDescriptions-- // log.Printf("currentFile: %s\n", currentFile)- // log.Println("files:")- // spew.Dump(files)-- // Handle file that is present in project paths but not in context- // Prompt user for what to do on the client side, stop the stream, and wait for user response before proceeding- if currentFile != "" &&- !req.IsChatOnly &&- active.ContextsByPath[currentFile] == nil &&- req.ProjectPaths[currentFile] && !active.AllowOverwritePaths[currentFile] {- log.Printf("Attempting to overwrite a file that isn't in context: %s\n", currentFile)-- // attempting to overwrite a file that isn't in context- // we will stop the stream and ask the user what to do- err := db.SetPlanStatus(planId, branch, shared.PlanStatusMissingFile, "")-- if err != nil {- log.Printf("Error setting plan %s status to prompting: %v\n", planId, err)- active.StreamDoneCh <- &shared.ApiError{- Type: shared.ApiErrorTypeOther,- Status: http.StatusInternalServerError,- Msg: "Error setting plan status to prompting",- }- continue mainLoop- }-- var previousReplyContent string- var trimmedContent string-- UpdateActivePlan(planId, branch, func(ap *types.ActivePlan) {- ap.MissingFilePath = currentFile- previousReplyContent = ap.CurrentReplyContent- trimmedContent = replyParser.GetReplyForMissingFile()- ap.CurrentReplyContent = trimmedContent- })-- log.Println("Previous reply content:")- log.Println(previousReplyContent)-- // log.Println("Trimmed content:")- // log.Println(trimmedContent)-- chunkToStream := getCroppedChunk(previousReplyContent+content, trimmedContent, content)-- // log.Printf("chunkToStream: %s\n", chunkToStream)-- if chunkToStream != "" {- log.Printf("Streaming remaining chunk before missing file prompt: %s\n", chunkToStream)- active.Stream(shared.StreamMessage{- Type: shared.StreamMessageReply,- ReplyChunk: chunkToStream,- })- }-- log.Printf("Prompting user for missing file: %s\n", currentFile)-- active.Stream(shared.StreamMessage{- Type: shared.StreamMessagePromptMissingFile,- MissingFilePath: currentFile,- MissingFileAutoContext: active.AutoContext,- })-- log.Printf("Stopping stream for missing file: %s\n", currentFile)- // log.Printf("Chunk content: %s\n", content)- // log.Printf("Current reply content: %s\n", active.CurrentReplyContent)-- // stop stream for now- active.CancelModelStreamFn()-- log.Printf("Stopped stream for missing file: %s\n", currentFile)-- // wait for user response to come in- var userChoice shared.RespondMissingFileChoice- select {- case <-active.Ctx.Done():- log.Println("Context cancelled while waiting for missing file response")- execHookOnStop(true)- return- case <-time.After(30 * time.Minute): // long timeout here since we're waiting for user input- log.Println("Timeout waiting for missing file choice")- state.onError(fmt.Errorf("timeout waiting for missing file choice"), true, "", "")- continue mainLoop- case userChoice = <-active.MissingFileResponseCh:- }-- log.Printf("User choice for missing file: %s\n", userChoice)-- active.ResetModelCtx()-- UpdateActivePlan(planId, branch, func(ap *types.ActivePlan) {- ap.MissingFilePath = ""- ap.CurrentReplyContent = replyParser.GetReplyForMissingFile()- })-- log.Println("Continuing stream")-- // continue plan- execTellPlan(- clients,- plan,- branch,- auth,- req,- iteration, // keep the same iteration- userChoice,- false,- 0,- )- return- }-- UpdateActivePlan(planId, branch, func(ap *types.ActivePlan) {- ap.CurrentReplyContent += content- ap.NumTokens++- })-- // log.Printf("Sending stream msg: %s", content)- active.Stream(shared.StreamMessage{- Type: shared.StreamMessageReply,- ReplyChunk: content,- })-- // log.Println("Content:", content)- // log.Println("Current reply content:", active.CurrentReplyContent)- // log.Println("Current file:", currentFile)- // log.Println("files:")- // spew.Dump(files)- // log.Println("replyFiles:")- // spew.Dump(replyFiles)-- if !req.IsChatOnly && len(files) > len(replyFiles) {- log.Printf("%d new files\n", len(files)-len(replyFiles))-- for i, file := range files {- if i < len(replyFiles) {- continue- }-- log.Printf("Detected file: %s\n", file)-- if req.BuildMode == shared.BuildModeAuto {- log.Printf("Queuing build for %s\n", file)- // log.Println("Content:")- // log.Println(fileContents[i])-- buildState := &activeBuildStreamState{- tellState: state,- clients: clients,- auth: auth,- currentOrgId: currentOrgId,- currentUserId: currentUserId,- plan: plan,- branch: branch,- settings: settings,- modelContext: state.modelContext,- }-- fileContentTokens, err := shared.GetNumTokens(fileContents[i])-- if err != nil {- log.Printf("Error getting num tokens for file %s: %v\n", file, err)- state.onError(fmt.Errorf("error getting num tokens for file %s: %v", file, err), true, "", "")- continue mainLoop- }-- buildState.queueBuilds([]*types.ActiveBuild{{- ReplyId: replyId,- Idx: i,- FileDescription: fileDescriptions[i],- FileContent: fileContents[i],- FileContentTokens: fileContentTokens,- Path: file,- }})- }- replyFiles = append(replyFiles, file)- UpdateActivePlan(planId, branch, func(ap *types.ActivePlan) {- ap.Files = append(ap.Files, file)- })- }- }- }- }-}--func (state *activeTellStreamState) storeAssistantReply() (*db.ConvoMessage, string, error) {- currentOrgId := state.currentOrgId- currentUserId := state.currentUserId- planId := state.plan.Id- branch := state.branch- auth := state.auth- replyNumTokens := state.replyNumTokens- replyId := state.replyId- convo := state.convo-- num := len(convo) + 1-- 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,- PlanId: planId,- UserId: currentUserId,- Role: openai.ChatMessageRoleAssistant,- Tokens: replyNumTokens,- Num: num,- Message: activePlan.CurrentReplyContent,- }-- commitMsg, err := db.StoreConvoMessage(&assistantMsg, auth.User.Id, branch, false)-- if err != nil {- log.Printf("Error storing assistant message: %v\n", err)- return nil, "", err- }-- UpdateActivePlan(planId, branch, func(ap *types.ActivePlan) {- ap.MessageNum = num- ap.StoredReplyIds = append(ap.StoredReplyIds, replyId)- })-- convo = append(convo, &assistantMsg)- state.convo = convo-- return &assistantMsg, commitMsg, err-}--func (state *activeTellStreamState) onError(streamErr error, storeDesc bool, convoMessageId, commitMsg string) {- log.Printf("\nStream error: %v\n", streamErr)-- planId := state.plan.Id- branch := state.branch- currentOrgId := state.currentOrgId- 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- }-- storeDescAndReply := func() error {- ctx, cancelFn := context.WithCancel(context.Background())-- repoLockId, err := db.LockRepo(- db.LockRepoParams{- UserId: state.currentUserId,- OrgId: state.currentOrgId,- PlanId: planId,- Branch: branch,- Scope: db.LockScopeWrite,- Ctx: ctx,- CancelFn: cancelFn,- },- )-- if err != nil {- log.Printf("Error locking repo for plan %s: %v\n", planId, err)- return err- } else {-- defer func() {- err := db.DeleteRepoLock(repoLockId)- if err != nil {- log.Printf("Error unlocking repo for plan %s: %v\n", planId, err)- }- }()-- err := db.GitClearUncommittedChanges(state.currentOrgId, planId)- if err != nil {- log.Printf("Error clearing uncommitted changes for plan %s: %v\n", planId, err)- return err- }- }-- storedMessage := false- storedDesc := false-- if convoMessageId == "" {- assistantMsg, msg, err := state.storeAssistantReply()- if err == nil {- convoMessageId = assistantMsg.Id- commitMsg = msg- storedMessage = true- } else {- log.Printf("Error storing assistant message after stream error: %v\n", err)- return err- }- }-- if storeDesc && convoMessageId != "" {- err := db.StoreDescription(&db.ConvoMessageDescription{- OrgId: currentOrgId,- PlanId: planId,- SummarizedToMessageId: summarizedToMessageId,- MadePlan: false,- ConvoMessageId: convoMessageId,- BuildPathsInvalidated: map[string]bool{},- Error: streamErr.Error(),- })- if err == nil {- storedDesc = true- } else {- log.Printf("Error storing description after stream error: %v\n", err)- return err- }- }-- if storedMessage || storedDesc {- err := db.GitAddAndCommit(currentOrgId, planId, branch, commitMsg)- if err != nil {- log.Printf("Error committing after stream error: %v\n", err)- return err- }- }-- return nil- }-- storeDescAndReply()-- active.StreamDoneCh <- &shared.ApiError{- Type: shared.ApiErrorTypeOther,- Status: http.StatusInternalServerError,- Msg: "Stream error: " + streamErr.Error(),- }-}--func getCroppedChunk(uncropped, cropped, chunk string) string {- uncroppedIdx := strings.Index(uncropped, chunk)- if uncroppedIdx == -1 {- return ""- }- croppedChunk := cropped[uncroppedIdx:]- return croppedChunk-}diff --git a/app/server/model/plan/tell_stream_error.go b/app/server/model/plan/tell_stream_error.gonew file mode 100644index 00000000..b13451de--- /dev/null+++ b/app/server/model/plan/tell_stream_error.go@@ -0,0 +1,120 @@+package plan++import (+ "context"+ "fmt"+ "log"+ "net/http"+ "plandex-server/db"++ "github.com/plandex/plandex/shared"+)++func (state *activeTellStreamState) onError(streamErr error, storeDesc bool, convoMessageId, commitMsg string) {+ log.Printf("\nStream error: %v\n", streamErr)++ planId := state.plan.Id+ branch := state.branch+ currentOrgId := state.currentOrgId+ 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+ }++ storeDescAndReply := func() error {+ ctx, cancelFn := context.WithCancel(context.Background())++ repoLockId, err := db.LockRepo(+ db.LockRepoParams{+ UserId: state.currentUserId,+ OrgId: state.currentOrgId,+ PlanId: planId,+ Branch: branch,+ Scope: db.LockScopeWrite,+ Ctx: ctx,+ CancelFn: cancelFn,+ },+ )++ if err != nil {+ log.Printf("Error locking repo for plan %s: %v\n", planId, err)+ return err+ } else {++ defer func() {+ err := db.DeleteRepoLock(repoLockId)+ if err != nil {+ log.Printf("Error unlocking repo for plan %s: %v\n", planId, err)+ }+ }()++ err := db.GitClearUncommittedChanges(state.currentOrgId, planId)+ if err != nil {+ log.Printf("Error clearing uncommitted changes for plan %s: %v\n", planId, err)+ return err+ }+ }++ storedMessage := false+ storedDesc := false++ if convoMessageId == "" {+ assistantMsg, msg, err := state.storeAssistantReply()+ if err == nil {+ convoMessageId = assistantMsg.Id+ commitMsg = msg+ storedMessage = true+ } else {+ log.Printf("Error storing assistant message after stream error: %v\n", err)+ return err+ }+ }++ if storeDesc && convoMessageId != "" {+ err := db.StoreDescription(&db.ConvoMessageDescription{+ OrgId: currentOrgId,+ PlanId: planId,+ SummarizedToMessageId: summarizedToMessageId,+ MadePlan: false,+ ConvoMessageId: convoMessageId,+ BuildPathsInvalidated: map[string]bool{},+ Error: streamErr.Error(),+ })+ if err == nil {+ storedDesc = true+ } else {+ log.Printf("Error storing description after stream error: %v\n", err)+ return err+ }+ }++ if storedMessage || storedDesc {+ err := db.GitAddAndCommit(currentOrgId, planId, branch, commitMsg)+ if err != nil {+ log.Printf("Error committing after stream error: %v\n", err)+ return err+ }+ }++ return nil+ }++ storeDescAndReply()++ active.StreamDoneCh <- &shared.ApiError{+ Type: shared.ApiErrorTypeOther,+ Status: http.StatusInternalServerError,+ Msg: "Stream error: " + streamErr.Error(),+ }+}++func (state *activeTellStreamState) onActivePlanMissingError() {+ planId := state.plan.Id+ branch := state.branch+ log.Printf("Active plan not found for plan ID %s on branch %s\n", planId, branch)+ state.onError(fmt.Errorf("active plan not found for plan ID %s on branch %s", planId, branch), true, "", "")+}diff --git a/app/server/model/plan/tell_stream_finish.go b/app/server/model/plan/tell_stream_finish.gonew file mode 100644index 00000000..9ee33511--- /dev/null+++ b/app/server/model/plan/tell_stream_finish.go@@ -0,0 +1,563 @@+package plan++import (+ "fmt"+ "log"+ "net/http"+ "plandex-server/db"+ "plandex-server/types"+ "time"++ "github.com/davecgh/go-spew/spew"+ "github.com/plandex/plandex/shared"+ "github.com/sashabaranov/go-openai"+)++const MaxAutoContinueIterations = 100++type handleStreamFinishedResult struct {+ shouldContinueMainLoop bool+ shouldReturn bool+}++func (state *activeTellStreamState) handleStreamFinished() handleStreamFinishedResult {+ planId := state.plan.Id+ branch := state.branch+ auth := state.auth+ plan := state.plan+ req := state.req+ clients := state.clients+ settings := state.settings+ currentOrgId := state.currentOrgId+ summaries := state.summaries+ convo := state.convo+ iteration := state.iteration+ replyFiles := state.chunkProcessor.replyFiles++ active := GetActivePlan(planId, branch)++ if active == nil {+ state.onActivePlanMissingError()+ return handleStreamFinishedResult{+ shouldContinueMainLoop: true,+ shouldReturn: false,+ }+ }++ time.Sleep(30 * time.Millisecond)+ active.FlushStreamBuffer()+ time.Sleep(100 * time.Millisecond)++ active.Stream(shared.StreamMessage{+ Type: shared.StreamMessageDescribing,+ })+ active.FlushStreamBuffer()++ err := db.SetPlanStatus(planId, branch, shared.PlanStatusDescribing, "")+ if err != nil {+ state.onError(fmt.Errorf("failed to set plan status to describing: %v", err), true, "", "")+ return handleStreamFinishedResult{+ shouldContinueMainLoop: true,+ shouldReturn: false,+ }+ }++ autoLoadContextFiles := state.checkAutoLoadContext()+ hasNewSubtasks := state.checkNewSubtasks()+ state.handleFileOps()++ handleDescAndExecStatusRes := state.handleDescAndExecStatus(autoLoadContextFiles, hasNewSubtasks)+ if handleDescAndExecStatusRes.shouldContinueMainLoop || handleDescAndExecStatusRes.shouldReturn {+ return handleDescAndExecStatusRes.handleStreamFinishedResult+ }+ generatedDescription := handleDescAndExecStatusRes.generatedDescription+ shouldContinue := handleDescAndExecStatusRes.shouldContinue+ subtaskFinished := handleDescAndExecStatusRes.subtaskFinished++ storeOnFinishedResult := state.storeOnFinished(replyFiles, generatedDescription, subtaskFinished, hasNewSubtasks)+ if storeOnFinishedResult.shouldContinueMainLoop || storeOnFinishedResult.shouldReturn {+ return storeOnFinishedResult.handleStreamFinishedResult+ }+ allSubtasksFinished := storeOnFinishedResult.allSubtasksFinished++ // summarize convo needs to come *after* the reply is stored in order to correctly summarize the latest message+ log.Println("summarize convo")+ envVar := settings.ModelPack.PlanSummary.BaseModelConfig.ApiKeyEnvVar+ client := clients[envVar]++ // summarize in the background+ go func() {+ err := summarizeConvo(client, settings.ModelPack.PlanSummary, summarizeConvoParams{+ auth: auth,+ plan: plan,+ branch: branch,+ convo: convo,+ summaries: summaries,+ userPrompt: state.userPrompt,+ currentOrgId: currentOrgId,+ currentReply: active.CurrentReplyContent,+ currentReplyNumTokens: active.NumTokens,+ modelPackName: settings.ModelPack.Name,+ }, active.SummaryCtx)++ if err != nil {+ log.Printf("Error summarizing convo: %v\n", err)+ active.StreamDoneCh <- &shared.ApiError{+ Type: shared.ApiErrorTypeOther,+ Status: http.StatusInternalServerError,+ Msg: fmt.Sprintf("Error summarizing convo: %v", err),+ }+ }+ }()++ log.Println("Sending active.CurrentReplyDoneCh <- true")++ active.CurrentReplyDoneCh <- true++ log.Println("Resetting active.CurrentReplyDoneCh")++ UpdateActivePlan(planId, branch, func(ap *types.ActivePlan) {+ ap.CurrentStreamingReplyId = ""+ ap.CurrentReplyDoneCh = nil+ })++ log.Printf("len(autoLoadContextFiles): %d\n", len(autoLoadContextFiles))+ if len(autoLoadContextFiles) > 0 {+ log.Println("Sending stream message to load context files")++ active.Stream(shared.StreamMessage{+ Type: shared.StreamMessageLoadContext,+ LoadContextFiles: autoLoadContextFiles,+ })+ active.FlushStreamBuffer()++ // Force a small delay to ensure message is processed+ time.Sleep(100 * time.Millisecond)++ log.Println("Waiting for client to auto load context (30s timeout)")++ select {+ case <-active.Ctx.Done():+ log.Println("Context cancelled while waiting for auto load context")+ state.execHookOnStop(true)+ return handleStreamFinishedResult{+ shouldContinueMainLoop: false,+ shouldReturn: true,+ }+ case <-time.After(30 * time.Second):+ log.Println("Timeout waiting for auto load context")+ state.onError(fmt.Errorf("timeout waiting for auto load context response"), true, "", "")+ return handleStreamFinishedResult{+ shouldContinueMainLoop: true,+ shouldReturn: false,+ }+ case <-active.AutoLoadContextCh:+ }+ }++ // if we're auto-loading context files, we always want to continue for at least another iteration with the loaded context+ log.Printf("req.AutoContinue: %v\n", req.AutoContinue)+ log.Printf("shouldContinue: %v\n", shouldContinue)+ log.Printf("iteration: %d\n", iteration)+ log.Printf("MaxAutoContinueIterations: %d\n", MaxAutoContinueIterations)+ log.Printf("hasNewSubtasks: %v\n", hasNewSubtasks)+ log.Printf("len(state.subtasks): %d\n", len(state.subtasks))+ log.Printf("allSubtasksFinished: %v\n", allSubtasksFinished)++ if (len(autoLoadContextFiles) > 0 && !hasNewSubtasks) ||+ (req.AutoContinue && shouldContinue && iteration < MaxAutoContinueIterations &&+ !(len(state.subtasks) > 0 && allSubtasksFinished)) {+ log.Println("Auto continue plan")+ // continue plan+ execTellPlan(clients, plan, branch, auth, req, iteration+1, "", false, 0)+ } else {+ var buildFinished bool+ UpdateActivePlan(planId, branch, func(ap *types.ActivePlan) {+ buildFinished = ap.BuildFinished()+ ap.RepliesFinished = true+ })++ log.Printf("Won't continue plan. Build finished: %v\n", buildFinished)++ time.Sleep(50 * time.Millisecond)++ if buildFinished {+ log.Println("Reply is finished and build is finished, calling active.Finish()")+ active := GetActivePlan(planId, branch)++ if active == nil {+ state.onActivePlanMissingError()+ return handleStreamFinishedResult{+ shouldContinueMainLoop: true,+ shouldReturn: false,+ }+ }++ active.Finish()+ } else {+ log.Println("Plan is still building")+ log.Println("Updating status to building")+ err := db.SetPlanStatus(planId, branch, shared.PlanStatusBuilding, "")+ if err != nil {+ log.Printf("Error setting plan status to building: %v\n", err)+ active.StreamDoneCh <- &shared.ApiError{+ Type: shared.ApiErrorTypeOther,+ Status: http.StatusInternalServerError,+ Msg: "Error setting plan status to building",+ }+ return handleStreamFinishedResult{+ shouldContinueMainLoop: true,+ shouldReturn: false,+ }+ }++ log.Println("Sending RepliesFinished stream message")+ active.Stream(shared.StreamMessage{+ Type: shared.StreamMessageRepliesFinished,+ })++ }+ }++ return handleStreamFinishedResult{}+}++type handleDescAndExecStatusResult struct {+ handleStreamFinishedResult+ subtaskFinished bool+ generatedDescription *db.ConvoMessageDescription+ shouldContinue bool+}++func (state *activeTellStreamState) handleDescAndExecStatus(autoLoadContextFiles []string, hasNewSubtasks bool) handleDescAndExecStatusResult {+ req := state.req+ currentOrgId := state.currentOrgId+ summarizedToMessageId := state.summarizedToMessageId+ planId := state.plan.Id+ branch := state.branch+ replyFiles := state.chunkProcessor.replyFiles++ active := GetActivePlan(planId, branch)+ if active == nil {+ state.onActivePlanMissingError()+ return handleDescAndExecStatusResult{+ handleStreamFinishedResult: handleStreamFinishedResult{+ shouldContinueMainLoop: true,+ shouldReturn: false,+ },+ }+ }++ var generatedDescription *db.ConvoMessageDescription+ var shouldContinue bool+ var subtaskFinished bool++ var errCh = make(chan error, 2)++ go func() {+ if len(replyFiles) > 0 {+ log.Println("Generating plan description")++ res, err := state.genPlanDescription()+ if err != nil {+ errCh <- fmt.Errorf("failed to generate plan description: %v", err)+ return+ }++ generatedDescription = res+ generatedDescription.OrgId = currentOrgId+ generatedDescription.SummarizedToMessageId = summarizedToMessageId+ generatedDescription.MadePlan = true+ generatedDescription.Files = replyFiles++ log.Println("Generated plan description.")+ }+ errCh <- nil+ }()++ if req.IsChatOnly || len(autoLoadContextFiles) > 0 || hasNewSubtasks || !req.AutoContinue {++ // if we're auto-loading context files, we always want to continue for at least another iteration with the loaded context (even if it's chat only)+ if len(autoLoadContextFiles) > 0 && !hasNewSubtasks {+ log.Printf("Auto loading context files, so continuing to planning phase")+ shouldContinue = true+ } else if req.IsChatOnly {+ log.Printf("Chat only, won't continue")+ shouldContinue = false+ } else if hasNewSubtasks {+ log.Printf("Has new subtasks, can continue")+ shouldContinue = req.AutoContinue+ }++ errCh <- nil+ } else {+ go func() {+ log.Println("Getting exec status")+ var err error+ subtaskFinished, shouldContinue, err = state.execStatusShouldContinue(active.CurrentReplyContent, active.Ctx)+ if err != nil {+ errCh <- fmt.Errorf("failed to get exec status: %v", err)+ return+ }++ log.Printf("Should continue: %v\n", shouldContinue)++ errCh <- nil+ }()+ }++ for i := 0; i < 2; i++ {+ err := <-errCh+ if err != nil {+ state.onError(err, true, "", "")+ return handleDescAndExecStatusResult{+ handleStreamFinishedResult: handleStreamFinishedResult{+ shouldContinueMainLoop: true,+ shouldReturn: false,+ },+ subtaskFinished: subtaskFinished,+ shouldContinue: shouldContinue,+ generatedDescription: generatedDescription,+ }+ }+ }++ return handleDescAndExecStatusResult{+ handleStreamFinishedResult: handleStreamFinishedResult{},+ subtaskFinished: subtaskFinished,+ shouldContinue: shouldContinue,+ generatedDescription: generatedDescription,+ }+}++type storeOnFinishedResult struct {+ handleStreamFinishedResult+ allSubtasksFinished bool+}++func (state *activeTellStreamState) storeOnFinished(replyFiles []string, generatedDescription *db.ConvoMessageDescription, subtaskFinished, hasNewSubtasks bool) storeOnFinishedResult {+ currentOrgId := state.currentOrgId+ currentUserId := state.currentUserId+ planId := state.plan.Id+ branch := state.branch+ auth := state.auth+ summarizedToMessageId := state.summarizedToMessageId++ active := GetActivePlan(planId, branch)++ if active == nil {+ state.onActivePlanMissingError()+ return storeOnFinishedResult{+ handleStreamFinishedResult: handleStreamFinishedResult{+ shouldContinueMainLoop: true,+ shouldReturn: false,+ },+ allSubtasksFinished: false,+ }+ }++ var allSubtasksFinished bool++ log.Println("Locking repo to store assistant reply and description")++ repoLockId, err := db.LockRepo(+ db.LockRepoParams{+ OrgId: currentOrgId,+ UserId: currentUserId,+ PlanId: planId,+ Branch: branch,+ Scope: db.LockScopeWrite,+ Ctx: active.Ctx,+ CancelFn: active.CancelFn,+ },+ )++ if err != nil {+ log.Printf("Error locking repo: %v\n", err)+ active.StreamDoneCh <- &shared.ApiError{+ Type: shared.ApiErrorTypeOther,+ Status: http.StatusInternalServerError,+ Msg: "Error locking repo",+ }+ return storeOnFinishedResult{+ handleStreamFinishedResult: handleStreamFinishedResult{+ shouldContinueMainLoop: true,+ shouldReturn: false,+ },+ allSubtasksFinished: false,+ }+ }++ log.Println("Locked repo for assistant reply and description")++ err = func() error {+ defer func() {+ if err != nil {+ log.Printf("Error storing reply and description: %v\n", err)+ err = db.GitClearUncommittedChanges(auth.OrgId, planId)+ if err != nil {+ log.Printf("Error clearing uncommitted changes: %v\n", err)+ }+ }++ log.Println("Unlocking repo for assistant reply and description")++ err = db.DeleteRepoLock(repoLockId)+ if err != nil {+ log.Printf("Error unlocking repo: %v\n", err)+ active.StreamDoneCh <- &shared.ApiError{+ Type: shared.ApiErrorTypeOther,+ Status: http.StatusInternalServerError,+ Msg: "Error unlocking repo",+ }+ }+ }()++ assistantMsg, convoCommitMsg, err := state.storeAssistantReply() // updates state.convo++ if err != nil {+ state.onError(fmt.Errorf("failed to store assistant message: %v", err), true, "", "")+ return err+ }++ log.Println("getting description for assistant message: ", assistantMsg.Id)++ var description *db.ConvoMessageDescription+ if len(replyFiles) == 0 {+ description = &db.ConvoMessageDescription{+ OrgId: currentOrgId,+ PlanId: planId,+ ConvoMessageId: assistantMsg.Id,+ SummarizedToMessageId: summarizedToMessageId,+ BuildPathsInvalidated: map[string]bool{},+ MadePlan: false,+ }+ } else {+ description = generatedDescription+ description.ConvoMessageId = assistantMsg.Id+ }++ log.Println("Storing description")+ err = db.StoreDescription(description)++ if err != nil {+ state.onError(fmt.Errorf("failed to store description: %v", err), false, assistantMsg.Id, convoCommitMsg)+ return err+ }+ log.Println("Description stored")++ if hasNewSubtasks || subtaskFinished {+ if subtaskFinished && state.currentSubtask != nil {+ log.Println("Subtask finished")+ log.Println("Current subtask:")+ log.Println(state.currentSubtask.Title)+ state.currentSubtask.IsFinished = true++ log.Println("Updated state. Current subtask:")+ log.Println(state.currentSubtask)+ }++ log.Println("Storing plan subtasks")+ err = db.StorePlanSubtasks(currentOrgId, planId, state.subtasks)+ if err != nil {+ log.Printf("Error storing plan subtasks: %v\n", err)+ state.onError(fmt.Errorf("failed to store plan subtasks: %v", err), false, assistantMsg.Id, convoCommitMsg)+ return err+ }++ state.currentSubtask = nil+ allSubtasksFinished = true+ for _, subtask := range state.subtasks {+ if !subtask.IsFinished {+ state.currentSubtask = subtask+ allSubtasksFinished = false+ break+ }+ }++ log.Println("Set new current subtask. Current subtask:")+ log.Println(state.currentSubtask)+ log.Println("All subtasks finished:", allSubtasksFinished)++ log.Println("Update state of subtasks")+ spew.Dump(state.subtasks)+ }++ // spew.Dump(description)++ log.Println("Comitting reply message, description, and subtasks")++ err = db.GitAddAndCommit(currentOrgId, planId, branch, convoCommitMsg)+ if err != nil {+ state.onError(fmt.Errorf("failed to commit: %v", err), false, assistantMsg.Id, convoCommitMsg)+ return err+ }+ log.Println("Assistant reply, description, and subtasks committed")++ return nil+ }()++ if err != nil {+ return storeOnFinishedResult{+ handleStreamFinishedResult: handleStreamFinishedResult{+ shouldContinueMainLoop: true,+ shouldReturn: false,+ },+ allSubtasksFinished: allSubtasksFinished,+ }+ }++ return storeOnFinishedResult{+ handleStreamFinishedResult: handleStreamFinishedResult{},+ allSubtasksFinished: allSubtasksFinished,+ }+}++func (state *activeTellStreamState) storeAssistantReply() (*db.ConvoMessage, string, error) {+ currentOrgId := state.currentOrgId+ currentUserId := state.currentUserId+ planId := state.plan.Id+ branch := state.branch+ auth := state.auth+ replyNumTokens := state.replyNumTokens+ replyId := state.replyId+ convo := state.convo++ num := len(convo) + 1++ 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,+ PlanId: planId,+ UserId: currentUserId,+ Role: openai.ChatMessageRoleAssistant,+ Tokens: replyNumTokens,+ Num: num,+ Message: activePlan.CurrentReplyContent,+ }++ commitMsg, err := db.StoreConvoMessage(&assistantMsg, auth.User.Id, branch, false)++ if err != nil {+ log.Printf("Error storing assistant message: %v\n", err)+ return nil, "", err+ }++ UpdateActivePlan(planId, branch, func(ap *types.ActivePlan) {+ ap.MessageNum = num+ ap.StoredReplyIds = append(ap.StoredReplyIds, replyId)+ })++ convo = append(convo, &assistantMsg)+ state.convo = convo++ return &assistantMsg, commitMsg, err+}diff --git a/app/server/model/plan/tell_stream_main.go b/app/server/model/plan/tell_stream_main.gonew file mode 100644index 00000000..cfe6e69a--- /dev/null+++ b/app/server/model/plan/tell_stream_main.go@@ -0,0 +1,135 @@+package plan++import (+ "fmt"+ "log"+ "plandex-server/model"+ "strings"+ "time"++ "github.com/sashabaranov/go-openai"+)++func (state *activeTellStreamState) listenStream(stream *openai.ChatCompletionStream) {+ defer stream.Close()++ plan := state.plan+ planId := plan.Id+ branch := state.branch++ 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+ }++ state.chunkProcessor = &chunkProcessor{+ replyFiles: []string{},+ chunksReceived: 0,+ maybeRedundantOpeningTagContent: "",+ fileOpen: false,+ contentBuffer: strings.Builder{},+ awaitingOpeningTag: false,+ awaitingClosingTag: false,+ awaitingBackticks: false,+ }++ // Create a timer that will trigger if no chunk is received within the specified duration+ timer := time.NewTimer(model.OPENAI_STREAM_CHUNK_TIMEOUT)+ defer timer.Stop()++ streamFinished := false++mainLoop:+ for {+ select {+ case <-active.Ctx.Done():+ // The main modelContext was canceled (not the timer)+ log.Println("\nTell: stream canceled")+ state.execHookOnStop(false)+ return+ case <-timer.C:+ // Timer triggered because no new chunk was received in time+ log.Println("\nTell: stream timeout due to inactivity")+ if streamFinished {+ log.Println("Tell stream finished—timed out waiting for usage chunk")+ state.execHookOnStop(true)+ return+ } else {+ state.onError(fmt.Errorf("stream timeout due to inactivity | This usually means the model is not responding."), true, "", "")+ continue mainLoop+ }++ default:+ response, err := stream.Recv()++ if err == nil {+ // Successfully received a chunk, reset the timer+ if !timer.Stop() {+ <-timer.C+ }+ timer.Reset(model.OPENAI_STREAM_CHUNK_TIMEOUT)+ } else {+ if err.Error() == "context canceled" {+ log.Println("Tell: stream context canceled")+ state.execHookOnStop(false)+ return+ }++ log.Printf("Tell: error receiving stream chunk: %v\n", err)+ state.execHookOnStop(true)+ return+ }++ if len(response.Choices) == 0 {+ if response.Usage != nil {+ state.handleUsageChunk(response.Usage)+ return+ }++ state.onError(fmt.Errorf("stream finished with no choices | This usually means the model failed to generate a valid response."), true, "", "")+ continue mainLoop+ }++ if len(response.Choices) > 1 {+ state.onError(fmt.Errorf("stream finished with more than one choice | This usually means the model failed to generate a valid response."), true, "", "")+ continue mainLoop+ }++ choice := response.Choices[0]++ if choice.FinishReason != "" {+ log.Println("Model stream finished")+ log.Println("Finish reason: ", choice.FinishReason)++ if choice.FinishReason == "error" {+ state.onError(fmt.Errorf("model stopped with error status | This usually means the model is not responding."), true, "", "")+ continue mainLoop+ }++ streamFinishResult := state.handleStreamFinished()+ if streamFinishResult.shouldContinueMainLoop {+ continue mainLoop+ }+ if streamFinishResult.shouldReturn {+ return+ }++ // Reset the timer for the usage chunk+ if !timer.Stop() {+ <-timer.C+ }+ timer.Reset(model.OPENAI_USAGE_CHUNK_TIMEOUT)+ streamFinished = true+ continue+ }++ processChunkRes := state.processChunk(choice)+ if processChunkRes.shouldReturn {+ return+ }+ // let main loop continue+ }+ }+}diff --git a/app/server/model/plan/tell_stream_processor.go b/app/server/model/plan/tell_stream_processor.gonew file mode 100644index 00000000..a97298a0--- /dev/null+++ b/app/server/model/plan/tell_stream_processor.go@@ -0,0 +1,461 @@+package plan++import (+ "fmt"+ "log"+ "net/http"+ "plandex-server/db"+ "plandex-server/types"+ "regexp"+ "strings"+ "time"++ "github.com/plandex/plandex/shared"+ "github.com/sashabaranov/go-openai"+)++var openingTagRegex = regexp.MustCompile(`<PlandexBlock\s+lang="(.+?)".*?>`)++type processChunkResult struct {+ shouldReturn bool+}++func (state *activeTellStreamState) processChunk(choice openai.ChatCompletionStreamChoice) processChunkResult {+ req := state.req+ missingFileResponse := state.missingFileResponse+ processor := state.chunkProcessor+ replyParser := state.replyParser+ plan := state.plan+ planId := plan.Id+ branch := state.branch+ active := GetActivePlan(planId, branch)++ if active == nil {+ state.onActivePlanMissingError()+ return processChunkResult{}+ }++ processor.chunksReceived+++ delta := choice.Delta+ content := delta.Content++ // log.Printf("content: %s\n", content)++ // buffer if we're continuing after a missing file response to avoid sending redundant opening tags+ if missingFileResponse != "" {+ if processor.maybeRedundantOpeningTagContent != "" {+ if strings.Contains(content, "\n") {+ processor.maybeRedundantOpeningTagContent = ""+ } else {+ processor.maybeRedundantOpeningTagContent += content+ }++ // skip processing this chunk+ return processChunkResult{}+ } else if processor.chunksReceived < 3 && strings.Contains(content, "<PlandexBlock") {+ // received <PlandexBlock in first 3 chunks after missing file response+ // means this is a redundant start of a new file block, so just ignore it++ processor.maybeRedundantOpeningTagContent += content++ // skip processing this chunk+ return processChunkResult{}+ }+ }++ // log.Printf("Adding chunk to parser: %s\n", content)+ // log.Printf("fileOpen: %v\n", fileOpen)++ replyParser.AddChunk(content, true)+ parserRes := replyParser.Read()++ if !processor.fileOpen && parserRes.CurrentFilePath != "" {+ log.Printf("File open: %s\n", parserRes.CurrentFilePath)+ processor.fileOpen = true+ }++ if processor.fileOpen && strings.HasSuffix(active.CurrentReplyContent+content, "</PlandexBlock>") {+ log.Println("FinishAndRead because of closing tag")+ parserRes = replyParser.FinishAndRead()+ processor.fileOpen = false+ }++ if processor.fileOpen && parserRes.CurrentFilePath == "" {+ // log.Println("File open but current file path is empty, closing file")+ processor.fileOpen = false+ }++ files := parserRes.Files+ state.replyNumTokens = parserRes.TotalTokens+ currentFile := parserRes.CurrentFilePath++ // log.Printf("currentFile: %s\n", currentFile)+ // log.Println("files:")+ // spew.Dump(files)++ // Handle file that is present in project paths but not in context+ // Prompt user for what to do on the client side, stop the stream, and wait for user response before proceeding+ if currentFile != "" &&+ !req.IsChatOnly &&+ active.ContextsByPath[currentFile] == nil &&+ req.ProjectPaths[currentFile] && !active.AllowOverwritePaths[currentFile] {+ return state.handleMissingFile(content, currentFile)+ }++ UpdateActivePlan(planId, branch, func(ap *types.ActivePlan) {+ ap.CurrentReplyContent += content+ ap.NumTokens+++ })++ state.bufferOrStream(content, &parserRes, active)++ if !req.IsChatOnly && len(files) > len(processor.replyFiles) {+ state.handleNewFiles(&parserRes)+ }++ return processChunkResult{}+}++func (state *activeTellStreamState) bufferOrStream(content string, parserRes *types.ReplyParserRes, active *types.ActivePlan) {+ processor := state.chunkProcessor++ var shouldStream bool+ if processor.awaitingOpeningTag || processor.awaitingClosingTag || processor.awaitingBackticks {+ processor.contentBuffer.WriteString(content)+ s := processor.contentBuffer.String()++ if processor.awaitingBackticks {+ if strings.Contains(s, "```") {+ processor.awaitingBackticks = false+ s = strings.ReplaceAll(s, "```", "\\`\\`\\`")++ if processor.awaitingOpeningTag || processor.awaitingClosingTag {+ // update buffer with escaped backticks+ processor.contentBuffer.Reset()+ processor.contentBuffer.WriteString(s)+ } else {+ content = s+ processor.contentBuffer.Reset()+ shouldStream = true+ }+ } else if !strings.HasSuffix(s, "`") {+ // fewer than 3 backticks, no need to escape+ processor.awaitingBackticks = false++ if !(processor.awaitingOpeningTag || processor.awaitingClosingTag) {+ content = s+ processor.contentBuffer.Reset()+ shouldStream = true+ }+ }+ }++ if processor.awaitingOpeningTag {+ if parserRes.MaybeFilePath == "" && parserRes.CurrentFilePath == "" {+ // wasn't really a file path / code block+ processor.awaitingOpeningTag = false+ content = s+ processor.contentBuffer.Reset()+ shouldStream = true+ } else if parserRes.CurrentFilePath != "" {+ // check for opening tag matching <PlandexBlock lang="...">+ match := openingTagRegex.FindStringSubmatch(s)++ if match != nil {+ // Found complete opening tag with lang attribute+ lang := match[1] // Extract the language from the first capture group+ log.Printf("Found language: %s\n", lang)++ shouldStream = true+ processor.awaitingOpeningTag = false+ processor.fileOpen = true++ // replace entire opening tag with ```lang+ s = strings.Replace(s, match[0], "```"+lang, 1)++ content = s+ processor.contentBuffer.Reset()+ } else if strings.Contains(s, "<PlandexBlock>") {+ // Missing lang attribute+ shouldStream = true+ processor.awaitingOpeningTag = false+ processor.fileOpen = true+ // replace entire opening tag with ``` without language+ s = strings.Replace(s, "<PlandexBlock>", "```", 1)+ content = s+ processor.contentBuffer.Reset()+ } else {+ // tag is missing - something is wrong - we shouldn't be here but let's try to recover anyway+ log.Printf("Opening <PlandexBlock> tag is missing even though parserRes.CurrentFile is set - something is wrong: %s\n", s)+ processor.awaitingOpeningTag = false+ processor.fileOpen = false+ s += "\n```" // add ``` to the end of the line to close the markdown code block+ content = s+ processor.contentBuffer.Reset()+ shouldStream = true+ }+ }+ } else if processor.awaitingClosingTag {+ if parserRes.CurrentFilePath == "" {+ if strings.Contains(strings.ReplaceAll(s, " ", ""), "</PlandexBlock>") {+ shouldStream = true+ processor.awaitingClosingTag = false+ processor.fileOpen = false+ // replace </PlandexBlock> with ``` to close the markdown code block+ s = strings.ReplaceAll(s, "</PlandexBlock>", "```")+ content = s+ processor.contentBuffer.Reset()+ } else {+ log.Printf("Closing </PlandexBlock> tag is missing even though parserRes.CurrentFile is empty - something is wrong: %s\n", s)+ processor.awaitingClosingTag = false+ content = s+ processor.contentBuffer.Reset()+ shouldStream = true+ }+ }+ }++ } else {+ if processor.contentBuffer.Len() > 0 {+ processor.contentBuffer.WriteString(content)+ content = processor.contentBuffer.String()+ }++ if parserRes.MaybeFilePath != "" && parserRes.CurrentFilePath == "" {+ processor.awaitingOpeningTag = true+ }++ if parserRes.CurrentFilePath != "" {+ if strings.Contains(content, "</PlandexBlock>") {+ processor.awaitingClosingTag = true+ } else {+ split := strings.Split(content, "<")+ if len(split) > 1 {+ last := split[len(split)-1]+ if strings.HasPrefix("</PlandexBlock>", last) {+ processor.awaitingClosingTag = true+ }+ }+ }+ }++ if processor.fileOpen && (strings.Contains(content, "```") || strings.HasSuffix(content, "`")) {+ processor.awaitingBackticks = true+ }++ if !processor.awaitingOpeningTag && !processor.awaitingClosingTag && !processor.awaitingBackticks {+ if processor.contentBuffer.Len() > 0 {+ processor.contentBuffer.Reset()+ }++ shouldStream = true+ }+ }++ if shouldStream {+ // log.Printf("Sending stream msg: %s", content)+ active.Stream(shared.StreamMessage{+ Type: shared.StreamMessageReply,+ ReplyChunk: content,+ })+ }+}++func (state *activeTellStreamState) handleNewFiles(parserRes *types.ReplyParserRes) {++ processor := state.chunkProcessor+ plan := state.plan+ planId := plan.Id+ branch := state.branch+ clients := state.clients+ auth := state.auth+ req := state.req+ replyId := state.replyId+ currentOrgId := state.currentOrgId+ currentUserId := state.currentUserId+ settings := state.settings++ files := parserRes.Files+ fileContents := parserRes.FileContents+ fileDescriptions := parserRes.FileDescriptions++ log.Printf("%d new files\n", len(files)-len(processor.replyFiles))++ for i, file := range files {+ if i < len(processor.replyFiles) {+ continue+ }++ log.Printf("Detected file: %s\n", file)++ if req.BuildMode == shared.BuildModeAuto {+ log.Printf("Queuing build for %s\n", file)+ // log.Println("Content:")+ // log.Println(fileContents[i])++ buildState := &activeBuildStreamState{+ tellState: state,+ clients: clients,+ auth: auth,+ currentOrgId: currentOrgId,+ currentUserId: currentUserId,+ plan: plan,+ branch: branch,+ settings: settings,+ modelContext: state.modelContext,+ }++ fileContentTokens, err := shared.GetNumTokens(fileContents[i])++ if err != nil {+ log.Printf("Error getting num tokens for file %s: %v\n", file, err)+ state.onError(fmt.Errorf("error getting num tokens for file %s: %v", file, err), true, "", "")+ return+ }++ buildState.queueBuilds([]*types.ActiveBuild{{+ ReplyId: replyId,+ Idx: i,+ FileDescription: fileDescriptions[i],+ FileContent: fileContents[i],+ FileContentTokens: fileContentTokens,+ Path: file,+ }})+ }+ processor.replyFiles = append(processor.replyFiles, file)+ UpdateActivePlan(planId, branch, func(ap *types.ActivePlan) {+ ap.Files = append(ap.Files, file)+ })+ }++}++func (state *activeTellStreamState) handleMissingFile(content, currentFile string) processChunkResult {+ branch := state.branch+ plan := state.plan+ planId := plan.Id+ replyParser := state.replyParser+ iteration := state.iteration+ clients := state.clients+ auth := state.auth+ req := state.req++ active := GetActivePlan(planId, branch)++ if active == nil {+ state.onActivePlanMissingError()+ return processChunkResult{}+ }++ log.Printf("Attempting to overwrite a file that isn't in context: %s\n", currentFile)++ // attempting to overwrite a file that isn't in context+ // we will stop the stream and ask the user what to do+ err := db.SetPlanStatus(planId, branch, shared.PlanStatusMissingFile, "")++ if err != nil {+ log.Printf("Error setting plan %s status to prompting: %v\n", planId, err)+ active.StreamDoneCh <- &shared.ApiError{+ Type: shared.ApiErrorTypeOther,+ Status: http.StatusInternalServerError,+ Msg: "Error setting plan status to prompting",+ }+ return processChunkResult{}+ }++ var previousReplyContent string+ var trimmedContent string++ UpdateActivePlan(planId, branch, func(ap *types.ActivePlan) {+ ap.MissingFilePath = currentFile+ previousReplyContent = ap.CurrentReplyContent+ trimmedContent = replyParser.GetReplyForMissingFile()+ ap.CurrentReplyContent = trimmedContent+ })++ log.Println("Previous reply content:")+ log.Println(previousReplyContent)++ // log.Println("Trimmed content:")+ // log.Println(trimmedContent)++ chunkToStream := getCroppedChunk(previousReplyContent+content, trimmedContent, content)++ // log.Printf("chunkToStream: %s\n", chunkToStream)++ if chunkToStream != "" {+ log.Printf("Streaming remaining chunk before missing file prompt: %s\n", chunkToStream)+ active.Stream(shared.StreamMessage{+ Type: shared.StreamMessageReply,+ ReplyChunk: chunkToStream,+ })+ }++ log.Printf("Prompting user for missing file: %s\n", currentFile)++ active.Stream(shared.StreamMessage{+ Type: shared.StreamMessagePromptMissingFile,+ MissingFilePath: currentFile,+ MissingFileAutoContext: active.AutoContext,+ })++ log.Printf("Stopping stream for missing file: %s\n", currentFile)+ // log.Printf("Chunk content: %s\n", content)+ // log.Printf("Current reply content: %s\n", active.CurrentReplyContent)++ // stop stream for now+ active.CancelModelStreamFn()++ log.Printf("Stopped stream for missing file: %s\n", currentFile)++ // wait for user response to come in+ var userChoice shared.RespondMissingFileChoice+ select {+ case <-active.Ctx.Done():+ log.Println("Context cancelled while waiting for missing file response")+ state.execHookOnStop(true)+ return processChunkResult{shouldReturn: true}++ case <-time.After(30 * time.Minute): // long timeout here since we're waiting for user input+ log.Println("Timeout waiting for missing file choice")+ state.onError(fmt.Errorf("timeout waiting for missing file choice"), true, "", "")+ return processChunkResult{}++ case userChoice = <-active.MissingFileResponseCh:+ }++ log.Printf("User choice for missing file: %s\n", userChoice)++ active.ResetModelCtx()++ UpdateActivePlan(planId, branch, func(ap *types.ActivePlan) {+ ap.MissingFilePath = ""+ ap.CurrentReplyContent = replyParser.GetReplyForMissingFile()+ })++ log.Println("Continuing stream")++ // continue plan+ execTellPlan(+ clients,+ plan,+ branch,+ auth,+ req,+ iteration, // keep the same iteration+ userChoice,+ false,+ 0,+ )++ return processChunkResult{shouldReturn: true}+}++func getCroppedChunk(uncropped, cropped, chunk string) string {+ uncroppedIdx := strings.Index(uncropped, chunk)+ if uncroppedIdx == -1 {+ return ""+ }+ croppedChunk := cropped[uncroppedIdx:]+ return croppedChunk+}diff --git a/app/server/model/plan/tell_stream_usage.go b/app/server/model/plan/tell_stream_usage.gonew file mode 100644index 00000000..fbd5e099--- /dev/null+++ b/app/server/model/plan/tell_stream_usage.go@@ -0,0 +1,90 @@+package plan++import (+ "log"+ "plandex-server/hooks"++ "github.com/davecgh/go-spew/spew"+ "github.com/plandex/plandex/shared"+ "github.com/sashabaranov/go-openai"+)++func (state *activeTellStreamState) handleUsageChunk(usage *openai.Usage) {+ planId := state.plan.Id+ branch := state.branch+ auth := state.auth+ plan := state.plan++ log.Println("Tell stream usage:")+ spew.Dump(usage)++ _, apiErr := hooks.ExecHook(hooks.DidSendModelRequest, hooks.HookParams{+ Auth: auth,+ Plan: plan,+ DidSendModelRequestParams: &hooks.DidSendModelRequestParams{+ InputTokens: usage.PromptTokens,+ OutputTokens: usage.CompletionTokens,+ ModelName: state.settings.ModelPack.Planner.BaseModelConfig.ModelName,+ ModelProvider: state.settings.ModelPack.Planner.BaseModelConfig.Provider,+ ModelPackName: state.settings.ModelPack.Name,+ ModelRole: shared.ModelRolePlanner,+ Purpose: "Generated plan reply",+ },+ })++ if apiErr != nil {+ log.Printf("Tell stream: error executing did send model request hook: %v\n", apiErr)++ // ensure the active plan is still available+ activePlan := GetActivePlan(planId, branch)++ if activePlan == nil {+ log.Printf(" Active plan not found for plan ID %s on branch %s\n", planId, branch)+ return+ }++ activePlan.StreamDoneCh <- apiErr+ }+}++func (state *activeTellStreamState) execHookOnStop(sendStreamErr bool) {+ planId := state.plan.Id+ branch := state.branch+ auth := state.auth+ plan := state.plan+ active := GetActivePlan(planId, branch)++ if active == nil {+ log.Printf(" Active plan not found for plan ID %s on branch %s\n", planId, branch)+ return+ }++ _, apiErr := hooks.ExecHook(hooks.DidSendModelRequest, hooks.HookParams{+ Auth: auth,+ Plan: plan,+ DidSendModelRequestParams: &hooks.DidSendModelRequestParams{+ InputTokens: state.totalRequestTokens,+ OutputTokens: active.NumTokens,+ ModelName: state.settings.ModelPack.Planner.BaseModelConfig.ModelName,+ ModelProvider: state.settings.ModelPack.Planner.BaseModelConfig.Provider,+ ModelPackName: state.settings.ModelPack.Name,+ ModelRole: shared.ModelRolePlanner,+ Purpose: "Generated plan reply",+ },+ })++ if apiErr != nil {+ log.Printf("Error executing did send model request hook after cancel or error: %v\n", apiErr)++ if sendStreamErr {+ activePlan := GetActivePlan(planId, branch)++ if activePlan == nil {+ log.Printf(" Active plan not found for plan ID %s on branch %s\n", planId, branch)+ return+ }++ activePlan.StreamDoneCh <- apiErr+ }+ }+}diff --git a/app/server/model/prompts/apply_exec.go b/app/server/model/prompts/apply_exec.goindex a4829a34..7198cdd0 100644--- a/app/server/model/prompts/apply_exec.go+++ b/app/server/model/prompts/apply_exec.go@@ -71,19 +71,19 @@ When breaking up a task into subtasks, remember that you MUST NOT use the _applyWhen running commands in _apply.sh, DO NOT hide or filter the output of the commands in any way. For example, do not do something like this:-` + "```bash" + `+<PlandexBlock lang="bash">if ! make clean && make; thenecho "Error: Compilation failed"exit 1fi-` + "```" + `+</PlandexBlock>because the output of the 'make clean' and 'make' commands won't be shown to the user. Instead, run each command separately and show the output:-` + "```bash" + `+<PlandexBlock lang="bash">make cleanmake-` + "```" + `+</PlandexBlock>` + ApplyScriptResetOrUpdatePrompt + `@@ -95,10 +95,10 @@ You MUST NOT include the shebang line ` + "(`#!/bin/bash` or `#!/bin/zsh`)" + `Similarly, you MUST NOT add the following lines (or similar lines) for error handling at the top of the _apply.sh script:-` + "```bash" + `+<PlandexBlock lang="bash">set -euo pipefailtrap 'echo "Error on line $LINENO: $BASH_COMMAND"' ERR-` + "```" + `+</PlandexBlock>The _apply.sh script will be executed with the above error handling already included.@@ -111,7 +111,7 @@ You MUST NOT tell the user to do anything themselves that's included in the _appExample, creating initial _apply.sh:- _apply.sh:-` + "```bash" + `+<PlandexBlock lang="bash"># Check for node/npmif ! command -v node > /dev/null; thenecho "Error: node is not installed"@@ -135,12 +135,12 @@ if [ ! -f "tsconfig.json" ]; thenecho "Generating TypeScript configuration..."npx tsc --init --jsx reactfi-` + "```" + `+</PlandexBlock>Example, updating an existing _apply.sh:- _apply.sh:-` + "```bash" + `+<PlandexBlock lang="bash"># ... existing code ...# Install dependencies@@ -153,7 +153,7 @@ npm install --save-dev \"jest@^29.0.0"# ... existing code ...-` + "```" + `+</PlandexBlock>`var ApplyScriptPromptNumTokens int@@ -207,14 +207,14 @@ If it succeeds, the _apply.sh script will then be *reset* to an empty state.The current state of the _apply.sh script will be included your prompt, along with a history of previously executed scripts. For example:Previously executed _apply.sh:-` + "```bash" + `+` + "```" + `npm install typescript expressnpm run buildnpm start` + "```" + `Previously executed _apply.sh:-` + "```bash" + `+` + "```" + `npm install jestnpm test` + "```" + `@@ -235,16 +235,16 @@ The latest state of the _apply.sh script that is included in your prompt *takesIf you are updating an *existing* _apply.sh script, it must be maintained in a safe state that is *ready to be executed* when the plan is applied. Do NOT overwrite the existing _apply.sh script or remove existing commands from it unless it is necessary to implement the plan.For example, if you first add commands to install dependencies:-` + "```bash" + `+<PlandexBlock lang="bash">npm install expressnpm install typescript-` + "```" + `+</PlandexBlock>And then in a later step add build commands:-` + "```bash" + `+<PlandexBlock lang="bash"># ... existing code ...npm run build-` + "```" + `+</PlandexBlock>Both sets of commands will be preserved and run when the plan is applied. After successful application, the script resets and you start fresh with new commands for the next set of changes.@@ -264,15 +264,15 @@ When writing a new script after reset:For example, if you see this history:Previously executed _apply.sh:-` + "```bash" + `+` + "```" + `npm install typescriptnpm run build` + "```" + `And you're making changes to TypeScript source files, you should include the build command again:-` + "```bash" + `+<PlandexBlock lang="bash">npm run build-` + "```" + `+</PlandexBlock>Examples of commands that typically need to be repeated after reset:- Build commands after source changes: make, npm run build, cargo builddiff --git a/app/server/model/prompts/code_block_langs.go b/app/server/model/prompts/code_block_langs.gonew file mode 100644index 00000000..be03ccbb--- /dev/null+++ b/app/server/model/prompts/code_block_langs.go@@ -0,0 +1,167 @@+package prompts++const ValidLangIdentifiers = `+abap+abl+abnf+actionscript3+ada+agda+ahk+al+alloy+antlr+apache+apl+applescript+aql+arduino+armasm+awk+ballerina+bash+basic+bibtex+bicep+blitzbasic+bnf+brainfuck+c+cpp+csharp+caddy+capnp+cassandra+ceylon+chapel+clojure+cmake+cobol+coffeescript+common-lisp+console+coq+crystal+css+cucumber+cue+cython+d+dart+dax+diff+django+dockerfile+dtd+dylan+ebnf+elixir+elm+erlang+factor+fennel+fish+forth+fortran+fsharp+gawk+gdscript+gherkin+gleam+glsl+gnuplot+go+graphql+groff+groovy+handlebars+hare+haskell+haxe+hcl+hlsl+html+http+idris+ini+io+java+javascript+jinja+json+jsx+julia+kotlin+latex+lisp+llvm+lua+make+markdown+mathematica+matlab+meson+mlir+modula2+mysql+nasm+nginx+nim+nix+objc+ocaml+octave+odin+openscad+org+perl+php+plpgsql+postscript+powershell+prolog+promql+protobuf+prql+python+qml+r+racket+raku+reason+rego+restructuredtext+rexx+ruby+rust+sas+sass+scala+scheme+scss+shell+smalltalk+solidity+sparql+sql+swift+systemverilog+tcl+terraform+tex+toml+tsx+turtle+typescript+vala+vbnet+verilog+vhdl+vim+vue+wgsl+xml+yaml+zig+zsh+`diff --git a/app/server/model/prompts/implement.go b/app/server/model/prompts/implement.goindex 87be0991..f19abbf8 100644--- a/app/server/model/prompts/implement.go+++ b/app/server/model/prompts/implement.go@@ -17,24 +17,31 @@ Describe in detail the current task to be done and what your approach will be, t- lib/term.go:- main.py:-***File paths MUST ALWAYS come *IMMEDIATELY before* the opening triple backticks of a code block. They should *not* be included in the code block itself. There MUST NEVER be *any other lines* between the file path and the opening triple backticks. Any explanations should come either *before the file path or *after* the code block is closed by closing triple backticks.*+Immediately after the file path, you MUST output an opening <PlandexBlock> tag. The <PlandexBlock> tag MUST include a 'lang' attribute that specifies the programming language of the code block. 'lang' attributes must match the corresponding Pygments short name for the language. Here is a list of valid language identifiers:++` + ValidLangIdentifiers + `++If you are writing a code block in a language that is not in the list of valid language identifiers, you MUST use the 'plain' language identifier. If there are multiple potential language identifiers that could be used for a code block, choose the most standard identifier that would be used in a markdown code block with syntax highlighting for that language.++***File paths MUST ALWAYS come *IMMEDIATELY before* the opening <PlandexBlock> tag of a code block. They MUST NOT be included *inside* the <PlandexBlock> tags. There MUST NEVER be *any other lines* between the file path and the opening <PlandexBlock> tag. Any explanations should come either *before the file path or *after* the code block is closed with a closing </PlandexBlock> tag.*++The <PlandexBlock> tag MUST ONLY contain the code for the code block and NOTHING ELSE. Do NOT wrap the code block in triple backticks, CDATA tags, or any other text or formatting. Output ONLY the code and nothing else within the <PlandexBlock> tag.***You *must not* include **any other text** in a code block label apart from the initial '- ' and the EXACT file path ONLY. DO NOT UNDER ANY CIRCUMSTANCES use a label like 'File path: src/main.rs' or 'src/main.rs: (Create this file)' or 'File to Create: src/main.rs' or 'File to Update: src/main.rs'. Instead use EXACTLY 'src/main.rs:'. DO NOT include any explanatory text in the code block label like 'src/main.rs: (Add a new function)'. Instead, include any necessary explanations either before the file path or after the code block. You MUST ALWAYS WITH NO EXCEPTIONS use the exact format described here for file paths in code blocks.-***Do NOT include the file path again within the triple backticks, inside the code block itself. The file path must be included *only* in the file block label *preceding* the opening triple backticks.***+***Do NOT include the file path again within the <PlandexBlock> tag, inside the code block itself. The file path must be included *only* in the file block label *preceding* the opening <PlandexBlock> tag.***Labelled code block example:- src/game.h:-` + "```c" + `-- #ifndef GAME_LOGIC_H- #define GAME_LOGIC_H-- void updateGameLogic();-- #endif- ` + "```" + `+<PlandexBlock lang="c">+#ifndef GAME_LOGIC_H+#define GAME_LOGIC_H++void updateGameLogic();++#endif+</PlandexBlock>- If you are working on a subtask and the subtask is too large to be implemented in a single response, it should be further broken down into smaller subtasks. In that case, divide the subtask into even smaller steps, and list them in a numbered list. Then continue on to implement the first step in the list. Do NOT do this repetitively for the same subtask. Only break down a given subtask into smaller steps once.@@ -52,11 +59,11 @@ Files MUST NOT be labelled with a comment like "// File to create: src/main.rs"File block labels MUST ONLY include a *single* file path. You must NEVER include multiple files in a single file block. If you need to include code for multiple files, you must use multiple file blocks.-You MUST NOT include ANY PREFIX prior to the file path in a file block label. Include ONLY the EXACT file path like '- src/main.rs:' with no other text. You MUST NOT include the file path again in the code block itself. The file path must be included *only* in the file block label. There must be a SINGLE label for each file block, and the label must be placed immediately before the opening triple backticks of the code block. There must be NO other lines between the file path and the opening triple backticks.+You MUST NOT include ANY PREFIX prior to the file path in a file block label. Include ONLY the EXACT file path like '- src/main.rs:' with no other text. You MUST NOT include the file path again inside of the <PlandexBlock> tag. The file path must be included *only* in the file block label. There must be a SINGLE label for each file block, and the label must be placed immediately before the opening <PlandexBlock> tag. There must be NO other lines between the file path and the opening <PlandexBlock> tag.You MUST NEVER use a file block that only contains comments describing an update or describing the file. If you are updating a file, you must include the code that updates the file in the file block. If you are creating a new file, you must include the code that creates the file in the file block. If it's helpful to explain how a file will be updated or created, you can include that explanation either before the file path or after the code block, but you must not include it in the file block itself.-You MUST NOT use the labelled file block format followed by triple backticks for **any purpose** other than creating or updating a file in the plan. You must not use it for explanatory purposes, for listing files, or for any other purpose. If you need to label a section or a list of files, use a markdown section header instead like this: '## Files to update'.+You MUST NOT use the labelled file block format followed by <PlandexBlock> tags for **any purpose** other than creating or updating a file in the plan. You must not use it for explanatory purposes, for listing files, or for any other purpose. ONLY use it for creating or updating files in the plan.If a change is related to code in an existing file in context, make the change as an update to the existing file. Do NOT create a new file for a change that applies to an existing file in context. For example, if there is an 'Page.tsx' file in the existing context and the user has asked you to update the structure of the page component, make the change in the existing 'Page.tsx' file. Do NOT create a new file like 'page.tsx' or 'NewPage.tsx' for the change. If the user has specifically asked you to apply a change to a new file, then you can create a new file. If there is no existing file that makes sense to apply a change to, then you can create a new file.@@ -64,9 +71,7 @@ If a change is related to code in an existing file in context, make the change aDo NOT treat files that do not exist in context as files to be updated. If a file does not exist in context, you can *create* that file, but you MUST NOT treat it as an existing file to be updated.-For code in markdown blocks, always include the language name after the opening triple backticks.--If there are triple backticks within any file in context, they will be escaped with backslashes like this '` + "\\`\\`\\`" + `'. If you are outputting triple backticks in a code block, you MUST escape them in exactly the same way.+For code blocks, always include the language identifier in the 'lang' attribute of the <PlandexBlock> tag.DO NOT create directories independently of files, whether in _apply.sh or in code blocks by adding a '.gitkeep' file in any other way. Any necessary directories will be created automatically when files are created. You MUST NOT create directories independently of files.diff --git a/app/server/model/prompts/missing_file.go b/app/server/model/prompts/missing_file.goindex 599dacc1..2d160506 100644--- a/app/server/model/prompts/missing_file.go+++ b/app/server/model/prompts/missing_file.go@@ -7,5 +7,5 @@ func GetSkipMissingFilePrompt(path string) string {}func GetMissingFileContinueGeneratingPrompt(path string) string {- return fmt.Sprintf("Continue generating the file '%s'. Continue EXACTLY where you left off in the previous message. Don't produce any other output before continuing or repeat any part of the previous message. Do *not* duplicate the last line of the previous response before continuing. Do *not* include triple backticks and a language name like '```python' or '```yaml' at the start of the response, since these have already been included in the previous message. Continue from where you left off seamlessly to generate the rest of the file block. You must include closing triple backticks at the end of the file block. When the file block is finished, continue with the plan according to the 'Your instructions' sections if there are any remaining tasks or subtasks. If there are no remaining tasks or subtasks, stop there. DO NOT UNDER ANY CIRCUMSTANCES INCLUDE THE FILE PATH OR THE OPENING TRIPLE BACKTICKS IN THE RESPONSE. DO NOT UNDER ANY CIRCUMSTANCES begin your response with *anything* except for the code that belongs in the '%s' file block.", path, path)+ return fmt.Sprintf("Continue generating the file '%s'. Continue EXACTLY where you left off in the previous message. Don't produce any other output before continuing or repeat any part of the previous message. Do *not* duplicate the last line of the previous response before continuing. Do *not* include an opening <PlandexBlock> tag at the start of the response, since this has already been included in the previous message. Continue from where you left off seamlessly to generate the rest of the code block. You must include a closing </PlandexBlock> tag at the end of the code block. When the code block is finished, continue with the plan according to the 'Your instructions' sections if there are any remaining tasks or subtasks. If there are no remaining tasks or subtasks, stop there. DO NOT UNDER ANY CIRCUMSTANCES INCLUDE THE FILE PATH OR THE OPENING <PlandexBlock> TAG IN THE RESPONSE. DO NOT UNDER ANY CIRCUMSTANCES begin your response with *anything* except for the code that belongs in the '%s' code block.", path, path)}diff --git a/app/server/model/prompts/update_format.go b/app/server/model/prompts/update_format.goindex 2236fe96..c83925cd 100644--- a/app/server/model/prompts/update_format.go+++ b/app/server/model/prompts/update_format.go@@ -871,7 +871,7 @@ Here are some important examples of INCORRECT vs CORRECT file updates:Example 1 - Adding a new route:❌ INCORRECT - Replacing instead of inserting:-` + "```go" + `+<PlandexBlock lang="go">// ... existing code ...r.HandleFunc(prefix+"/api/users", handlers.ListUsersHandler).Methods("GET")@@ -879,11 +879,11 @@ r.HandleFunc(prefix+"/api/users", handlers.ListUsersHandler).Methods("GET")r.HandleFunc(prefix+"/api/config", handlers.GetConfigHandler).Methods("GET")// ... existing code ...-` + "```" + `+</PlandexBlock>This is wrong because it doesn't show enough context to know what surrounding routes were preserved.✅ CORRECT - Proper insertion with context:-` + "```go" + `+<PlandexBlock lang="go">// ... existing code ...r.HandleFunc(prefix+"/api/users", handlers.ListUsersHandler).Methods("GET")@@ -895,12 +895,12 @@ r.HandleFunc(prefix+"/api/settings", handlers.GetSettingsHandler).Methods("GET")r.HandleFunc(prefix+"/api/status", handlers.GetStatusHandler).Methods("GET")// ... existing code ...-` + "```" + `+</PlandexBlock>Example 2 - Adding a method to a class:❌ INCORRECT - Ambiguous insertion:-` + "```go" + `+<PlandexBlock lang="go">class UserService {// ... existing code ...@@ -910,11 +910,11 @@ class UserService {// ... existing code ...}-` + "```" + `+</PlandexBlock>This is wrong because it doesn't show where exactly the new method should go.✅ CORRECT - Clear insertion point:-` + "```go" + `+<PlandexBlock lang="go">class UserService {// ... existing code ...@@ -932,12 +932,12 @@ class UserService {// ... existing code ...}-` + "```" + `+</PlandexBlock>Example 3 - Adding a configuration section:❌ INCORRECT - Lost context:-` + "```json" + `+<PlandexBlock lang="json">{"database": {"host": "localhost",@@ -948,11 +948,11 @@ Example 3 - Adding a configuration section:"timeout": 30}}-` + "```" + `+</PlandexBlock>This is wrong because it dropped existing configuration sections.✅ CORRECT - Preserved context:-` + "```json" + `+<PlandexBlock lang="json">{// ... existing code ...@@ -974,7 +974,7 @@ This is wrong because it dropped existing configuration sections.// ... existing code ...}-` + "```" + `+</PlandexBlock>Key principles demonstrated in these examples:1. Always show the surrounding context that will be preserved@@ -1074,7 +1074,7 @@ Example:**Updating ` + "`server/something/something.go`**" + `: I'll add the new 'anotherThing' function call immediately after the 'doSomethingElse' method.- server/something/something.go:-` + "```" + `+<PlandexBlock lang="go">// ... existing code ...func Add(t *T) {@@ -1084,7 +1084,7 @@ func Add(t *T) {doSomethingElseAgain()// ... existing code ...}-` + "```" + `+</PlandexBlock>*diff --git a/app/server/model/prompts/user_prompt.go b/app/server/model/prompts/user_prompt.goindex 6670dfcc..3b5f6085 100644--- a/app/server/model/prompts/user_prompt.go+++ b/app/server/model/prompts/user_prompt.go@@ -38,7 +38,9 @@ If you're making a plan, remember to label code blocks with the file path *exactYou MUST NOT include any other text in a code block label apart from the initial '- ' and the EXACT file path ONLY. DO NOT UNDER ANY CIRCUMSTANCES use a label like 'File path: src/main.rs' or 'src/main.rs: (Create this file)' or 'File to Create: src/main.rs' or 'File to Update: src/main.rs'. Instead use EXACTLY 'src/main.rs:'. DO NOT include any explanatory text in the code block label like 'src/main.rs: (Add a new function)'. It is EXTREMELY IMPORTANT that the code block label includes *only* the initial '- ', the file path, and NO OTHER TEXT whatsoever. If additional text apart from the initial '- ' and the exact file path is included in the code block label, the plan will not be parsed properly and you will have failed at the task of generating a usable plan.-Always use triple backticks to start and end code blocks.+Always use an opening <PlandexBlock> tag to start a code block and a closing </PlandexBlock> tag to end a code block.++The <PlandexBlock> tag MUST ONLY contain the code for the code block and NOTHING ELSE. Do NOT wrap the code block in triple backticks, CDATA tags, or any other text or formatting. Output ONLY the code and nothing else within the <PlandexBlock> tag.` + UpdateFormatPrompt + `diff --git a/app/server/types/reply.go b/app/server/types/reply.goindex 337d91b2..2730d516 100644--- a/app/server/types/reply.go+++ b/app/server/types/reply.go@@ -128,8 +128,8 @@ func (r *ReplyParser) AddChunk(chunk string, addToTotal bool) {if r.maybeFilePath != "" {// log.Println("Maybe file path is:", r.maybeFilePath) // Logging the maybeFilePath- if strings.HasPrefix(prevFullLineTrimmed, "```") {- // log.Println("Found opening ticks--confirming file path...") // Logging the confirmed file path+ if strings.HasPrefix(prevFullLineTrimmed, "<PlandexBlock") {+ // log.Println("Found opening tag--confirming file path...") // Logging the confirmed file pathr.currentFilePath = r.maybeFilePathr.currentFileIdx = len(r.files)@@ -177,8 +177,8 @@ func (r *ReplyParser) AddChunk(chunk string, addToTotal bool) {}} else {// 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...")+ if strings.HasPrefix(prevFullLineTrimmed, "</PlandexBlock") {+ // log.Println("Found closing tag--adding file to files and resetting current file...")r.files = append(r.files, r.currentFilePath)r.currentFilePath = ""diff --git a/app/server/types/reply_test_examples/1.md b/app/server/types/reply_test_examples/1.mdindex 2f65daa9..61ea06e3 100644--- a/app/server/types/reply_test_examples/1.md+++ b/app/server/types/reply_test_examples/1.md@@ -9,7 +9,7 @@ The code changes are as follows:- file: cmd/apply.go-```go+<PlandexBlock lang="go">package cmd// ... other imports ...@@ -51,11 +51,11 @@ func apply(cmd *cobra.Command, args []string) error {}// ... rest of the code ...-```+</PlandexBlock>- file: cmd/checkout.go-```go+<PlandexBlock lang="go">package cmd// ... other imports ...@@ -73,6 +73,6 @@ func checkout(cmd *cobra.Command, args []string) {// ... rest of the code ...}-```+</PlandexBlock>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/app/server/types/reply_test_examples/2.md b/app/server/types/reply_test_examples/2.mdindex 6eace5c3..3a3d7e97 100644--- a/app/server/types/reply_test_examples/2.md+++ b/app/server/types/reply_test_examples/2.md@@ -2,8 +2,7 @@ Sure, here's how you could structure your 'context rm' command and 'context upda**cmd/context_rm.go**-```go-+<PlandexBlock lang="go">package cmdimport (@@ -52,12 +51,11 @@ func init() {contextCmd.AddCommand(contextRmCmd)contextRmCmd.Flags().BoolP("all", "a", false, "remove all contexts")}-```+</PlandexBlock>**cmd/context_update.go**-```go-+<PlandexBlock lang="go">package cmdimport (@@ -96,6 +94,6 @@ to quickly create a Cobra application.`,func init() {contextCmd.AddCommand(contextUpdateCmd)}-```+</PlandexBlock>In your next iteration, you could implement the functions in 'lib' package such as `RemoveAllContexts`, `RemoveContext`, and `UpdateContext`.diff --git a/app/server/types/reply_test_examples/3.md b/app/server/types/reply_test_examples/3.mdindex 6eace5c3..3a3d7e97 100644--- a/app/server/types/reply_test_examples/3.md+++ b/app/server/types/reply_test_examples/3.md@@ -2,8 +2,7 @@ Sure, here's how you could structure your 'context rm' command and 'context upda**cmd/context_rm.go**-```go-+<PlandexBlock lang="go">package cmdimport (@@ -52,12 +51,11 @@ func init() {contextCmd.AddCommand(contextRmCmd)contextRmCmd.Flags().BoolP("all", "a", false, "remove all contexts")}-```+</PlandexBlock>**cmd/context_update.go**-```go-+<PlandexBlock lang="go">package cmdimport (@@ -96,6 +94,6 @@ to quickly create a Cobra application.`,func init() {contextCmd.AddCommand(contextUpdateCmd)}-```+</PlandexBlock>In your next iteration, you could implement the functions in 'lib' package such as `RemoveAllContexts`, `RemoveContext`, and `UpdateContext`.diff --git a/app/server/types/reply_test_examples/4.md b/app/server/types/reply_test_examples/4.mdindex 041a5933..15ea4ff6 100644--- a/app/server/types/reply_test_examples/4.md+++ b/app/server/types/reply_test_examples/4.md@@ -9,7 +9,7 @@ In `server/types/` directory, create a new `section.go` file.- server/types/section.go-```go+<PlandexBlock lang="go">package typestype Section struct {@@ -21,6 +21,6 @@ type Section struct {type SectionizeResponse struct {Sections []Section}-```+</PlandexBlock>Once you have checked and confirmed this task, I will proceed to the next task which is creating a sectionize function in the server model.diff --git a/app/server/types/reply_test_examples/5.md b/app/server/types/reply_test_examples/5.mdindex f68314f6..7fde5b3d 100644--- a/app/server/types/reply_test_examples/5.md+++ b/app/server/types/reply_test_examples/5.md@@ -4,18 +4,18 @@ Given that a summarization utility exists, the plan can be further simplified to- shared/types.go:- ```go+ <PlandexBlock lang="go">type ChatCompletionMessage struct {// existing fields...Summarized bool}- ```+ </PlandexBlock>2. Modify the loadConversation function in cli/lib/conversation.go to take advantage of this new field.- cli/lib/conversation.go:- ```go+ <PlandexBlock lang="go">// modified part of loadConversation...messages = append(messages, openai.ChatCompletionMessage{@@ -24,7 +24,7 @@ Given that a summarization utility exists, the plan can be further simplified toSummarized: checkIfMsgSummarized(filePath, currentRole)})...- ```+ </PlandexBlock>- Add the helper functions, checkIfMsgSummarized to check if a given message has already been summarized.3. In the server/model/proposal/create.go, handle the token limit error by introducing a summarization step.diff --git a/app/server/types/reply_test_examples/6.md b/app/server/types/reply_test_examples/6.mdindex 979f60e3..df459c26 100644--- a/app/server/types/reply_test_examples/6.md+++ b/app/server/types/reply_test_examples/6.md@@ -8,7 +8,7 @@ Changes will include:-server/model/proposal/create.go:-```go+<PlandexBlock lang="go">// Add this at the start of the CreateProposal functionconst maxTokens = 8192 // The maximum tokens allowed by the model@@ -41,7 +41,7 @@ if tokenNumbers > maxTokens {...// Proceed the rest of the function as usual-```+</PlandexBlock>This block of code handles the error arising from exceeding the maximum tokens supported by the model. If the tokens exceeded are detected, we start the process of summarizing conversation pairs till we are within allowed token limits. This is implemented via a recursive call to `CreateProposal`.diff --git a/app/server/types/reply_test_examples/7.md b/app/server/types/reply_test_examples/7.mdindex e0c1d9f6..92c7fb32 100644--- a/app/server/types/reply_test_examples/7.md+++ b/app/server/types/reply_test_examples/7.md@@ -1,7 +1,7 @@**Updating `file_map/map.go`**: I'll add debug logging to the mapMarkup function between the function declaration and the end of the file.- file_map/map.go:-```go+<PlandexBlock lang="go">// ... existing code ...func mapMarkup(node *tree_sitter.Node, content []byte) []Definition {@@ -113,4 +113,4 @@ func mapMarkup(node *tree_sitter.Node, content []byte) []Definition {}// ... existing code ...-```\ No newline at end of file+</PlandexBlock>\ No newline at end of filediff --git a/app/server/types/reply_test_examples/8.md b/app/server/types/reply_test_examples/8.mdindex ace48b14..f6b7198d 100644--- a/app/server/types/reply_test_examples/8.md+++ b/app/server/types/reply_test_examples/8.md@@ -3,7 +3,7 @@First, I'll create a basic project structure with a Makefile that will compile our game.- Makefile:-```makefile+<PlandexBlock lang="makefile">CC = gccCFLAGS = -Wall -Wextra -I./includeLDFLAGS = -framework OpenGL -framework GLUT@@ -30,10 +30,10 @@ $(OBJ_DIR)/%.o: $(SRC_DIR)/%.cclean:rm -rf $(OBJ_DIR) $(BIN_DIR)-```+</PlandexBlock>- _apply.sh:-```bash+<PlandexBlock lang="bash"># Create necessary directories if they don't existmkdir -p src include obj bin@@ -54,8 +54,8 @@ make clean && make# Run the game./bin/pong-```+</PlandexBlock>**Creating the project structure and Makefile** has been completed.-Next, I'll implement the header files for game structures and constants.\ No newline at end of file+Next, I'll implement the header files for game structures and constants.