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
fixes and tests for code block formatting and buffering. don't build map if there are no file paths (i.e. empty directory)--skip auto context step if there are no maps in context
Dane Schneiderf9a7c4cbb35d
diff --git a/app/cli/cmd/new.go b/app/cli/cmd/new.goindex f3470fcd..1dfc11f3 100644--- a/app/cli/cmd/new.go+++ b/app/cli/cmd/new.go@@ -98,8 +98,9 @@ func new(cmd *cobra.Command, args []string) {}lib.MustLoadContext([]string{baseDir}, &types.LoadContextParams{- DefsOnly: true,- SkipIgnoreWarning: true,+ DefsOnly: true,+ SkipIgnoreWarning: true,+ SkipDefsOnlyNoContextOutput: true,})} else {fmt.Println()diff --git a/app/cli/lib/context_load.go b/app/cli/lib/context_load.goindex 94278589..6d56e756 100644--- a/app/cli/lib/context_load.go+++ b/app/cli/lib/context_load.go@@ -5,7 +5,6 @@ import ("encoding/base64""fmt""io"- "log""os""path/filepath""plandex/api"@@ -16,17 +15,16 @@ import ("plandex/url""strings""sync"- "time""github.com/fatih/color""github.com/plandex/plandex/shared")func MustLoadContext(resources []string, params *types.LoadContextParams) {- startTime := time.Now()+ // startTime := time.Now()showElapsed := func(msg string) {- elapsed := time.Since(startTime)- log.Println(msg, "elapsed: %s\n", elapsed)+ // elapsed := time.Since(startTime)+ // log.Println(msg, "elapsed: %s\n", elapsed)}if params.DefsOnly {@@ -343,6 +341,14 @@ func MustLoadContext(resources []string, params *types.LoadContextParams) {if numPaths > shared.MaxContextCount {onErr(fmt.Errorf("too many files to load (found %d, limit is %d)", numPaths, shared.MaxContextCount))+ } else if numPaths == 0 {+ term.StopSpinner()+ if params.DefsOnly && params.SkipDefsOnlyNoContextOutput {+ fmt.Println()+ } else {+ fmt.Println("🤷♂️ No context loaded")+ }+ return}inputFilePaths = flattenedPathsdiff --git a/app/cli/types/types.go b/app/cli/types/types.goindex fc84f39f..dd3eb7bd 100644--- a/app/cli/types/types.go+++ b/app/cli/types/types.go@@ -6,13 +6,14 @@ import ()type LoadContextParams struct {- Note string- Recursive bool- NamesOnly bool- ForceSkipIgnore bool- ImageDetail openai.ImageURLDetail- DefsOnly bool- SkipIgnoreWarning bool+ Note string+ Recursive bool+ NamesOnly bool+ ForceSkipIgnore bool+ ImageDetail openai.ImageURLDetail+ DefsOnly bool+ SkipIgnoreWarning bool+ SkipDefsOnlyNoContextOutput bool}type ContextOutdatedResult struct {diff --git a/app/server/model/plan/tell_exec.go b/app/server/model/plan/tell_exec.goindex 7d2baf06..82d148e4 100644--- a/app/server/model/plan/tell_exec.go+++ b/app/server/model/plan/tell_exec.go@@ -158,9 +158,10 @@ func execTellPlan(}}- isPlanningStage := req.IsChatOnly || (!req.IsUserContinue && (iteration == 0 || (req.AutoContext && iteration == 1)))+ autoContextEnabled := req.AutoContext && state.hasContextMap+ isPlanningStage := req.IsChatOnly || (!req.IsUserContinue && (iteration == 0 || (autoContextEnabled && iteration == 1)))isImplementationStage := !isPlanningStage- isContextStage := isPlanningStage && req.AutoContext && iteration == 0+ isContextStage := isPlanningStage && autoContextEnabled && iteration == 0log.Printf("isPlanningStage: %t, isImplementationStage: %t, isContextStage: %t\n", isPlanningStage, isImplementationStage, isContextStage)@@ -193,8 +194,8 @@ func execTellPlan(if isPlanningStage {log.Println("isPlanningStage")- if req.AutoContext {- if iteration == 0 {+ if req.AutoContext && state.hasContextMap {+ if isContextStage {sysCreate = prompts.AutoContextPreamblesysCreateTokens = prompts.AutoContextPreambleNumTokens} else {@@ -274,7 +275,7 @@ func execTellPlan(sysCreateTokens += subtaskTokens}- log.Println("**sysCreate:**\n", sysCreate)+ // log.Println("**sysCreate:**\n", sysCreate)state.messages = []openai.ChatCompletionMessage{{diff --git a/app/server/model/plan/tell_load.go b/app/server/model/plan/tell_load.goindex b3b81c69..369080a3 100644--- a/app/server/model/plan/tell_load.go+++ b/app/server/model/plan/tell_load.go@@ -339,5 +339,13 @@ func (state *activeTellStreamState) loadTellPlan() error {}}+ state.hasContextMap = false+ for _, context := range state.modelContext {+ if context.ContextType == shared.ContextMapType {+ state.hasContextMap = true+ break+ }+ }+return nil}diff --git a/app/server/model/plan/tell_state.go b/app/server/model/plan/tell_state.goindex 69edc3c7..0d947467 100644--- a/app/server/model/plan/tell_state.go+++ b/app/server/model/plan/tell_state.go@@ -20,6 +20,7 @@ type activeTellStreamState struct {iteration intreplyId stringmodelContext []*db.Context+ hasContextMap boolconvo []*db.ConvoMessagecurrentPlanState *shared.CurrentPlanStatemissingFileResponse shared.RespondMissingFileChoice@@ -46,7 +47,7 @@ type chunkProcessor struct {chunksReceived intmaybeRedundantOpeningTagContent stringfileOpen bool- contentBuffer strings.Builder+ contentBuffer *strings.BuilderawaitingOpeningTag boolawaitingClosingTag boolawaitingBackticks booldiff --git a/app/server/model/plan/tell_stream_main.go b/app/server/model/plan/tell_stream_main.goindex cfe6e69a..9ef58b9c 100644--- a/app/server/model/plan/tell_stream_main.go+++ b/app/server/model/plan/tell_stream_main.go@@ -29,7 +29,7 @@ func (state *activeTellStreamState) listenStream(stream *openai.ChatCompletionStchunksReceived: 0,maybeRedundantOpeningTagContent: "",fileOpen: false,- contentBuffer: strings.Builder{},+ contentBuffer: &strings.Builder{},awaitingOpeningTag: false,awaitingClosingTag: false,awaitingBackticks: false,diff --git a/app/server/model/plan/tell_stream_processor.go b/app/server/model/plan/tell_stream_processor.goindex a97298a0..ce28d2b3 100644--- a/app/server/model/plan/tell_stream_processor.go+++ b/app/server/model/plan/tell_stream_processor.go@@ -64,7 +64,7 @@ func (state *activeTellStreamState) processChunk(choice openai.ChatCompletionStr}// log.Printf("Adding chunk to parser: %s\n", content)- // log.Printf("fileOpen: %v\n", fileOpen)+ // log.Printf("fileOpen: %v\n", processor.fileOpen)replyParser.AddChunk(content, true)parserRes := replyParser.Read()@@ -81,7 +81,7 @@ func (state *activeTellStreamState) processChunk(choice openai.ChatCompletionStr}if processor.fileOpen && parserRes.CurrentFilePath == "" {- // log.Println("File open but current file path is empty, closing file")+ log.Println("File open but current file path is empty, closing file")processor.fileOpen = false}@@ -107,7 +107,25 @@ func (state *activeTellStreamState) processChunk(choice openai.ChatCompletionStrap.NumTokens++})- state.bufferOrStream(content, &parserRes, active)+ // log.Println("processor before bufferOrStream")+ // spew.Dump(processor)+ // log.Println("maybeFilePath", parserRes.MaybeFilePath)+ // log.Println("currentFilePath", parserRes.CurrentFilePath)++ res := processor.bufferOrStream(content, parserRes.MaybeFilePath, parserRes.CurrentFilePath)++ // log.Println("res")+ // spew.Dump(res)++ if res.shouldStream {+ active.Stream(shared.StreamMessage{+ Type: shared.StreamMessageReply,+ ReplyChunk: res.content,+ })+ }++ // log.Println("processor after bufferOrStream")+ // spew.Dump(processor)if !req.IsChatOnly && len(files) > len(processor.replyFiles) {state.handleNewFiles(&parserRes)@@ -116,14 +134,19 @@ func (state *activeTellStreamState) processChunk(choice openai.ChatCompletionStrreturn processChunkResult{}}-func (state *activeTellStreamState) bufferOrStream(content string, parserRes *types.ReplyParserRes, active *types.ActivePlan) {- processor := state.chunkProcessor+type bufferOrStreamResult struct {+ shouldStream bool+ content string+}+func (processor *chunkProcessor) bufferOrStream(content, maybeFilePath, currentFilePath string) bufferOrStreamResult {var shouldStream boolif processor.awaitingOpeningTag || processor.awaitingClosingTag || processor.awaitingBackticks {processor.contentBuffer.WriteString(content)s := processor.contentBuffer.String()+ // log.Printf("s: %q\n", s)+if processor.awaitingBackticks {if strings.Contains(s, "```") {processor.awaitingBackticks = false@@ -151,38 +174,20 @@ func (state *activeTellStreamState) bufferOrStream(content string, parserRes *ty}if processor.awaitingOpeningTag {- if parserRes.MaybeFilePath == "" && parserRes.CurrentFilePath == "" {+ if maybeFilePath == "" && currentFilePath == "" {// wasn't really a file path / code blockprocessor.awaitingOpeningTag = falsecontent = sprocessor.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)+ } else if currentFilePath != "" {+ matched, replaced := matchCodeBlockOpeningTag(s)+ if matched {shouldStream = trueprocessor.awaitingOpeningTag = falseprocessor.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+ content = replacedprocessor.contentBuffer.Reset()} else {// tag is missing - something is wrong - we shouldn't be here but let's try to recover anyway@@ -196,8 +201,8 @@ func (state *activeTellStreamState) bufferOrStream(content string, parserRes *ty}}} else if processor.awaitingClosingTag {- if parserRes.CurrentFilePath == "" {- if strings.Contains(strings.ReplaceAll(s, " ", ""), "</PlandexBlock>") {+ if currentFilePath == "" {+ if strings.Contains(s, "</PlandexBlock>") {shouldStream = trueprocessor.awaitingClosingTag = falseprocessor.fileOpen = false@@ -216,48 +221,51 @@ func (state *activeTellStreamState) bufferOrStream(content string, parserRes *ty}} else {- if processor.contentBuffer.Len() > 0 {- processor.contentBuffer.WriteString(content)- content = processor.contentBuffer.String()- }-- if parserRes.MaybeFilePath != "" && parserRes.CurrentFilePath == "" {+ if maybeFilePath != "" && currentFilePath == "" {processor.awaitingOpeningTag = true}- if parserRes.CurrentFilePath != "" {+ if currentFilePath != "" {if strings.Contains(content, "</PlandexBlock>") {processor.awaitingClosingTag = true} else {split := strings.Split(content, "<")+ // log.Printf("split: %v\n", split)if len(split) > 1 {last := split[len(split)-1]- if strings.HasPrefix("</PlandexBlock>", last) {+ // log.Printf("last: %s\n", last)+ if strings.HasPrefix("/PlandexBlock>", last) {processor.awaitingClosingTag = true}}}+ } else if strings.Contains(content, "</PlandexBlock>") {+ content = strings.Replace(content, "</PlandexBlock>", "```", 1)}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()+ var matchedOpeningTag bool+ if processor.fileOpen {+ var replaced string+ matchedOpeningTag, replaced = matchCodeBlockOpeningTag(content)+ if matchedOpeningTag {+ content = replaced}+ }- shouldStream = true+ shouldStream = !processor.awaitingOpeningTag && !processor.awaitingClosingTag && !processor.awaitingBackticks++ if !shouldStream {+ processor.contentBuffer.WriteString(content)}}- if shouldStream {- // log.Printf("Sending stream msg: %s", content)- active.Stream(shared.StreamMessage{- Type: shared.StreamMessageReply,- ReplyChunk: content,- })+ return bufferOrStreamResult{+ shouldStream: shouldStream,+ content: content,}}@@ -459,3 +467,18 @@ func getCroppedChunk(uncropped, cropped, chunk string) string {croppedChunk := cropped[uncroppedIdx:]return croppedChunk}++func matchCodeBlockOpeningTag(content string) (bool, string) {+ // check for opening tag matching <PlandexBlock lang="...">+ match := openingTagRegex.FindStringSubmatch(content)++ if match != nil {+ // Found complete opening tag with lang attribute+ lang := match[1] // Extract the language from the first capture group+ return true, strings.Replace(content, match[0], "```"+lang, 1)+ } else if strings.Contains(content, "<PlandexBlock>") {+ return true, strings.Replace(content, "<PlandexBlock>", "```", 1)+ }++ return false, ""+}diff --git a/app/server/model/plan/tell_stream_processor_test.go b/app/server/model/plan/tell_stream_processor_test.gonew file mode 100644index 00000000..7c5dab3f--- /dev/null+++ b/app/server/model/plan/tell_stream_processor_test.go@@ -0,0 +1,311 @@+package plan++import (+ "strings"+ "testing"+)++func TestBufferOrStream(t *testing.T) {+ tests := []struct {+ name string+ initialState *chunkProcessor+ chunk string+ maybeFilePath string+ currentFilePath string+ want bufferOrStreamResult+ wantState *chunkProcessor // To verify state transitions+ }{+ {+ name: "streams regular content",+ initialState: &chunkProcessor{+ contentBuffer: &strings.Builder{},+ },+ chunk: "some regular text",+ want: bufferOrStreamResult{+ shouldStream: true,+ content: "some regular text",+ },+ wantState: &chunkProcessor{+ awaitingOpeningTag: false,+ awaitingClosingTag: false,+ awaitingBackticks: false,+ fileOpen: false,+ },+ },+ {+ name: "buffers partial opening tag",+ initialState: &chunkProcessor{+ awaitingOpeningTag: true,+ fileOpen: false,+ contentBuffer: &strings.Builder{},+ },+ chunk: `<Pland`,+ maybeFilePath: "main.go",+ currentFilePath: "",+ want: bufferOrStreamResult{+ shouldStream: false,+ },+ wantState: &chunkProcessor{+ awaitingOpeningTag: true,+ awaitingClosingTag: false,+ awaitingBackticks: false,+ fileOpen: false,+ contentBuffer: func() *strings.Builder {+ b := &strings.Builder{}+ b.WriteString(`<Pland`)+ return b+ }(),+ },+ },+ {+ name: "converts opening tag",+ initialState: &chunkProcessor{+ fileOpen: true,+ contentBuffer: func() *strings.Builder {+ b := &strings.Builder{}+ b.WriteString(`<PlandexBlock lang="go">` + "\n")+ return b+ }(),+ awaitingOpeningTag: true,+ },+ chunk: `package`,+ maybeFilePath: "",+ currentFilePath: "main.go",+ want: bufferOrStreamResult{+ shouldStream: true,+ content: "```go\npackage",+ },+ wantState: &chunkProcessor{+ awaitingOpeningTag: false,+ awaitingClosingTag: false,+ awaitingBackticks: false,+ fileOpen: true,+ },+ },+ {+ // occurs when replayParser can't identify a 'maybeFilePath' prior a full opening tag being sent ('maybeFilePath' gets skipped and 'currentFilePath' is set immediately)+ name: "converts opening tag without awaitingOpeningTag",+ initialState: &chunkProcessor{+ fileOpen: true,+ contentBuffer: &strings.Builder{},+ awaitingOpeningTag: false,+ },+ chunk: `<PlandexBlock lang="go">` + "\npackage",+ maybeFilePath: "",+ currentFilePath: "main.go",+ want: bufferOrStreamResult{+ shouldStream: true,+ content: "```go\npackage",+ },+ wantState: &chunkProcessor{+ awaitingOpeningTag: false,+ awaitingClosingTag: false,+ awaitingBackticks: false,+ fileOpen: true,+ },+ },+ {+ name: "buffers partial backticks",+ initialState: &chunkProcessor{+ fileOpen: true,+ contentBuffer: func() *strings.Builder {+ b := &strings.Builder{}+ b.WriteString("here's some co")+ return b+ }(),+ },+ chunk: "de:`",+ currentFilePath: "main.go",+ want: bufferOrStreamResult{+ shouldStream: false,+ },+ wantState: &chunkProcessor{+ awaitingBackticks: true,+ fileOpen: true,+ },+ },+ {+ name: "escapes backticks in content",+ initialState: &chunkProcessor{+ fileOpen: true,+ awaitingBackticks: true,+ contentBuffer: func() *strings.Builder {+ b := &strings.Builder{}+ b.WriteString("here's some code:\n`")+ return b+ }(),+ },+ chunk: "``\npackage",+ currentFilePath: "main.go",+ want: bufferOrStreamResult{+ shouldStream: true,+ content: "here's some code:\n\\`\\`\\`\npackage",+ },+ wantState: &chunkProcessor{+ awaitingOpeningTag: false,+ awaitingClosingTag: false,+ awaitingBackticks: false,+ fileOpen: true,+ },+ },+ {+ name: "buffers partial closing tag",+ initialState: &chunkProcessor{+ fileOpen: true,+ awaitingClosingTag: false,+ contentBuffer: &strings.Builder{},+ },+ currentFilePath: "main.go",+ chunk: "\n}</Plan",+ want: bufferOrStreamResult{+ shouldStream: false,+ },+ wantState: &chunkProcessor{+ awaitingClosingTag: true,+ fileOpen: true,+ contentBuffer: func() *strings.Builder {+ b := &strings.Builder{}+ b.WriteString("\n}</Plan")+ return b+ }(),+ },+ },+ {+ name: "buffers full closing tag with file open",+ initialState: &chunkProcessor{+ fileOpen: true,+ awaitingClosingTag: false,+ contentBuffer: &strings.Builder{},+ },+ currentFilePath: "main.go",+ chunk: "\n}</PlandexBlock>",+ want: bufferOrStreamResult{+ shouldStream: false,+ },+ wantState: &chunkProcessor{+ awaitingClosingTag: true,+ fileOpen: true,+ contentBuffer: func() *strings.Builder {+ b := &strings.Builder{}+ b.WriteString("\n}</PlandexBlock>")+ return b+ }(),+ },+ },+ {+ name: "replaces full closing tag with file closed",+ initialState: &chunkProcessor{+ fileOpen: false,+ awaitingClosingTag: false,+ contentBuffer: &strings.Builder{},+ },+ currentFilePath: "",+ chunk: "\n}</PlandexBlock>",+ want: bufferOrStreamResult{+ shouldStream: true,+ content: "\n}```",+ },+ wantState: &chunkProcessor{+ awaitingClosingTag: false,+ fileOpen: false,+ },+ },+ {+ name: "handles single backticks",+ initialState: &chunkProcessor{+ fileOpen: true,+ awaitingBackticks: true,+ contentBuffer: func() *strings.Builder {+ b := &strings.Builder{}+ b.WriteString("`file.go`")+ return b+ }(),+ },+ chunk: "\nsomething",+ currentFilePath: "main.go",+ want: bufferOrStreamResult{+ shouldStream: true,+ content: "`file.go`\nsomething",+ },+ wantState: &chunkProcessor{+ awaitingOpeningTag: false,+ awaitingClosingTag: false,+ awaitingBackticks: false,+ fileOpen: true,+ },+ },+ {+ name: "handles close and re-open backticks",+ initialState: &chunkProcessor{+ fileOpen: true,+ awaitingBackticks: true,+ contentBuffer: func() *strings.Builder {+ b := &strings.Builder{}+ b.WriteString("`file.go`")+ return b+ }(),+ },+ chunk: "\n`file2.go`",+ currentFilePath: "main.go",+ want: bufferOrStreamResult{+ shouldStream: false,+ },+ wantState: &chunkProcessor{+ awaitingOpeningTag: false,+ awaitingClosingTag: false,+ awaitingBackticks: true,+ fileOpen: true,+ contentBuffer: func() *strings.Builder {+ b := &strings.Builder{}+ b.WriteString("`file.go`\n`file2.go`")+ return b+ }(),+ },+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ processor := tt.initialState++ // Initialize content buffer if needed+ if processor.contentBuffer == nil {+ processor.contentBuffer = &strings.Builder{}+ }++ got := processor.bufferOrStream(tt.chunk, tt.maybeFilePath, tt.currentFilePath)++ if got.shouldStream != tt.want.shouldStream {+ t.Errorf("shouldStream = %v, want %v", got.shouldStream, tt.want.shouldStream)+ }+ if got.shouldStream && got.content != tt.want.content {+ t.Errorf("content = %q, want %q", got.content, tt.want.content)+ }++ // Check all state transitions+ if processor.fileOpen != tt.wantState.fileOpen {+ t.Errorf("fileOpen = %v, want %v", processor.fileOpen, tt.wantState.fileOpen)+ }+ if processor.awaitingOpeningTag != tt.wantState.awaitingOpeningTag {+ t.Errorf("awaitingOpeningTag = %v, want %v", processor.awaitingOpeningTag, tt.wantState.awaitingOpeningTag)+ }+ if processor.awaitingClosingTag != tt.wantState.awaitingClosingTag {+ t.Errorf("awaitingClosingTag = %v, want %v", processor.awaitingClosingTag, tt.wantState.awaitingClosingTag)+ }+ if processor.awaitingBackticks != tt.wantState.awaitingBackticks {+ t.Errorf("awaitingBackticks = %v, want %v", processor.awaitingBackticks, tt.wantState.awaitingBackticks)+ }++ if tt.wantState.contentBuffer != nil {+ if processor.contentBuffer.String() != tt.wantState.contentBuffer.String() {+ t.Errorf("content buffer = %q, want %q", processor.contentBuffer.String(), tt.wantState.contentBuffer.String())+ }+ }++ // Check buffer is reset when it should be+ if tt.want.shouldStream && processor.contentBuffer.Len() > 0 {+ t.Error("content buffer should be reset after streaming")+ }+ })+ }+}diff --git a/test/test_prompts/pong.txt b/test/test_prompts/pong.txtindex 4264adf6..33fe2b7e 100644--- a/test/test_prompts/pong.txt+++ b/test/test_prompts/pong.txt@@ -5,3 +5,5 @@ Create all the necessary functionality for the project so that it will be readyInclude a script that will install any necessary dependencies that are missing on Mac OSC. Prefer homebrew where possible for package management.Also include a Makefile that will compile the project.++Include a README.md file that will describe the project and how to run it from the command line.