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
auto-continue mostly working, handle new file + replacements in changes ui, various fixes
Dane Schneider7942a80ceda4
diff --git a/app/cli/changes_tui/actions.go b/app/cli/changes_tui/actions.goindex a678d12f..bbddb4a7 100644--- a/app/cli/changes_tui/actions.go+++ b/app/cli/changes_tui/actions.go@@ -78,12 +78,18 @@ func (m *changesUIModel) down() {currentReplacements = m.selectionInfo.currentReplacements}- // allow for selection of 'full file' option at bottom of replacement list in sidebarmax := len(currentReplacements) - 1++ // allow for selection of 'full file' option at bottom of replacement list in sidebarif m.currentPlan.PlanResult.NumPendingForPath(m.selectionInfo.currentPath) > 0 {max++}+ // allow for selection of 'new file' option at top of replacement list in sidebar+ if m.hasNewFile() {+ max+++ }+if m.selectedReplacementIndex < max {// log.Println("down")m.selectedReplacementIndex++@@ -154,14 +160,20 @@ func (m *changesUIModel) updateMainView(scrollReplacement bool) {// var updateMsg types.ChangesUIViewportsUpdate- if m.selectedFullFile() {+ if m.selectedNewFile() || m.selectedFullFile() {context := m.currentPlan.ContextsByPath[m.selectionInfo.currentPath]var originalFile stringif context != nil {originalFile = context.Body}- updatedFile := m.currentPlan.CurrentPlanFiles.Files[m.selectionInfo.currentPath]+ var updatedFile string++ if m.selectedNewFile() {+ updatedFile = m.selectionInfo.currentRes.Content+ } else {+ updatedFile = m.currentPlan.CurrentPlanFiles.Files[m.selectionInfo.currentPath]+ }wrapWidth := m.fileViewport.Width - 2fileSegments := []string{}diff --git a/app/cli/changes_tui/main_viewport.go b/app/cli/changes_tui/main_viewport.goindex 1409c8af..4b47ae3b 100644--- a/app/cli/changes_tui/main_viewport.go+++ b/app/cli/changes_tui/main_viewport.go@@ -12,7 +12,7 @@ func (m changesUIModel) renderMainView() string {mainViewHeader := m.renderMainViewHeader()- if m.selectedFullFile() {+ if m.selectedNewFile() || m.selectedFullFile() {fileView := m.fileViewport.View()fileViews := []string{fileView}@@ -78,6 +78,9 @@ func (m changesUIModel) renderMainViewHeader() string {var header stringif m.selectedFullFile() {numChanges := m.currentPlan.PlanResult.NumPendingForPath(m.selectionInfo.currentPath)+ if m.hasNewFile() {+ numChanges+++ }if numChanges > 0 {suffix := "s"@@ -86,8 +89,17 @@ func (m changesUIModel) renderMainViewHeader() string {}header = fmt.Sprintf(" ✅ Final state of %s (%d change%s)", m.selectionInfo.currentPath, numChanges, suffix)} else {- header = fmt.Sprintf(" ✅ New file: %s", m.selectionInfo.currentPath)+ header = fmt.Sprintf(" 🌟 New file: %s", m.selectionInfo.currentPath)+ }+ } else if m.selectedNewFile() {+ numChanges := m.currentPlan.PlanResult.NumPendingForPath(m.selectionInfo.currentPath)+ icon := "🌟"+ if numChanges > 1 {+ icon = "👉"}++ header = fmt.Sprintf(" %s New file: %s", icon, m.selectionInfo.currentPath)+} else {header = " 👉 " + m.selectionInfo.currentRep.Summary}@@ -113,13 +125,13 @@ func (m changesUIModel) renderScrollFooter() string {width, _ := m.getMainViewDims()- if m.selectionInfo.currentRes != nil {+ if !m.selectedNewFile() && !m.selectedFullFile() {width = width / 2}var footer string- if m.selectedFullFile() {+ if m.selectedNewFile() || m.selectedFullFile() {footer = `(j/k) scroll down/up • (J/K) page down/up`} else {footer = ` (j/k) scroll`diff --git a/app/cli/changes_tui/selection.go b/app/cli/changes_tui/selection.goindex 29492ab8..7d02aeff 100644--- a/app/cli/changes_tui/selection.go+++ b/app/cli/changes_tui/selection.go@@ -31,11 +31,23 @@ func (m *changesUIModel) setSelectionInfo() {}i := 0+outer:for _, res := range results {+ if i == 0 && len(res.Replacements) == 0 && res.Content != "" {+ if m.selectedReplacementIndex == 0 {+ currentRes = res+ break outer+ } else {+ i+++ continue+ }+ }+for _, rep := range res.Replacements {if i == m.selectedReplacementIndex {currentRes = rescurrentRep = rep+ break outer}i++}diff --git a/app/cli/changes_tui/sidebar.go b/app/cli/changes_tui/sidebar.goindex 9a27f076..28eefc20 100644--- a/app/cli/changes_tui/sidebar.go+++ b/app/cli/changes_tui/sidebar.go@@ -24,13 +24,36 @@ func (m changesUIModel) renderSidebar() string {anyReplacements := falsevar replacements []*shared.Replacement-- for _, result := range results {- replacements = append(replacements, result.Replacements...)+ var createdFile bool++ for i, result := range results {+ if m.hasNewFile() && i == 0 {+ createdFile = true+ selected := m.selectedNewFile()+ fgColor := color.FgHiGreen+ bgColor := color.BgGreen+ icon := "🌟"++ var s string+ if selected {+ s += color.New(color.Bold, bgColor, color.FgHiWhite).Sprintf(" %s %d ", icon, 1)+ } else {+ s += color.New(fgColor).Sprintf(" %s %d ", icon, 1)+ }++ s += "\n"+ sb.WriteString(s)+ } else {+ replacements = append(replacements, result.Replacements...)+ }}// Change entriesfor i, rep := range replacements {+ num := i + 1+ if createdFile {+ num+++ }anyReplacements = trueselected := currentRep != nil && rep.Id == currentRep.Ids := ""@@ -60,9 +83,9 @@ func (m changesUIModel) renderSidebar() string {}if selected {- s += color.New(color.Bold, bgColor, color.FgHiWhite).Sprintf(" > %s %d ", icon, i+1)+ s += color.New(color.Bold, bgColor, color.FgHiWhite).Sprintf(" %s %d ", icon, num)} else {- s += color.New(fgColor).Sprintf(" - %s %d ", icon, i+1)+ s += color.New(fgColor).Sprintf(" %s %d ", icon, num)}s += "\n"@@ -83,9 +106,9 @@ func (m changesUIModel) renderSidebar() string {}if m.selectedFullFile() {- sb.WriteString(color.New(color.Bold, bgColor, color.FgHiWhite).Sprint(" > 🔀 "))+ sb.WriteString(color.New(color.Bold, bgColor, color.FgHiWhite).Sprint(" 🔀 → "))} else {- sb.WriteString(color.New(fgColor).Sprint(" - 🔀 "))+ sb.WriteString(color.New(fgColor).Sprint(" 🔀 "))}}diff --git a/app/cli/changes_tui/view.go b/app/cli/changes_tui/view.goindex 468d4555..4441a8bf 100644--- a/app/cli/changes_tui/view.go+++ b/app/cli/changes_tui/view.go@@ -44,7 +44,7 @@ func (m changesUIModel) getMainViewDims() (int, int) {mainViewWidth := m.width - sidebarWidthmainViewHeight := m.height - (helpHeight + tabsHeight)- if m.selectedFullFile() {+ if m.selectedNewFile() || m.selectedFullFile() {mainViewHeight -= mainViewHeaderHeight} else {mainViewHeight -= (mainViewHeaderHeight + mainViewFooterHeight)@@ -70,7 +70,7 @@ func (m *changesUIModel) updateViewportSizes() {mainViewWidth, mainViewHeight := m.getMainViewDims()- if m.selectedFullFile() {+ if m.selectedNewFile() || m.selectedFullFile() {fileViewHeight := mainViewHeightif m.fileScrollable() {@@ -160,8 +160,22 @@ func (m changesUIModel) fileScrollable() bool {return m.fileViewport.TotalLineCount() > m.fileViewport.VisibleLineCount()}+func (m changesUIModel) hasNewFile() bool {+ firstRes := m.currentPlan.PlanResult.FileResultsByPath[m.selectionInfo.currentPath][0]+ return len(firstRes.Replacements) == 0 && firstRes.Content != ""+}++func (m changesUIModel) selectedNewFile() bool {+ return m.selectionInfo != nil &&+ m.hasNewFile() &&+ m.selectedReplacementIndex == 0 &&+ m.selectionInfo.currentRes != nil &&+ len(m.selectionInfo.currentRes.Replacements) == 0 &&+ m.selectionInfo.currentRes.Content != ""+}+func (m changesUIModel) selectedFullFile() bool {- return m.selectionInfo != nil && m.selectionInfo.currentRep == nil+ return !m.selectedNewFile() && m.selectionInfo != nil && m.selectionInfo.currentRep == nil}func (m *changesUIModel) scrollReplacementIntoView(oldContent, newContent string, numLinesPrepended int) {diff --git a/app/cli/stream_tui/model.go b/app/cli/stream_tui/model.goindex 4f14154e..4a6cc33b 100644--- a/app/cli/stream_tui/model.go+++ b/app/cli/stream_tui/model.go@@ -17,6 +17,7 @@ type streamUIModel struct {replyViewport viewport.Modelprocessing bool+ starting boolspinner spinner.Modelbuilding bool@@ -83,6 +84,7 @@ func initialModel() *streamUIModel {finishedByPath: make(map[string]bool),spinner: s,atScrollBottom: true,+ starting: true,}return &initialStatediff --git a/app/cli/stream_tui/update.go b/app/cli/stream_tui/update.goindex c7ec527f..b805f838 100644--- a/app/cli/stream_tui/update.go+++ b/app/cli/stream_tui/update.go@@ -17,7 +17,7 @@ func (m *streamUIModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {switch msg := msg.(type) {case spinner.TickMsg:- if m.processing {+ if m.processing || m.starting {spinnerModel, cmd := m.spinner.Update(msg)m.spinner = spinnerModelreturn m, cmd@@ -86,10 +86,13 @@ func (m *streamUIModel) getViewportDimensions() (int, int) {helpHeight := lipgloss.Height(m.renderHelp())buildHeight := lipgloss.Height(m.renderBuild())processingHeight := lipgloss.Height(m.renderProcessing())- maxViewportHeight := h - (helpHeight + buildHeight + processingHeight)+ maxViewportHeight := h - (helpHeight + processingHeight + buildHeight)viewportHeight := min(maxViewportHeight, lipgloss.Height(m.replyDisplay))+ viewportWidth := w++ // log.Println("viewportWidth:", viewportWidth)- return w, viewportHeight+ return viewportWidth, viewportHeight}func (m streamUIModel) replyScrollable() bool {@@ -129,9 +132,13 @@ func (m *streamUIModel) pageUp() {func (m *streamUIModel) streamUpdate(msg *shared.StreamMessage) (tea.Model, tea.Cmd) {switch msg.Type {case shared.StreamMessageReply:+ if m.starting {+ m.starting = false+ }+if m.processing {m.processing = false- m.reply += "\n\n"+ m.reply += "\n\n👉 "}m.reply += msg.ReplyChunk@@ -140,9 +147,8 @@ func (m *streamUIModel) streamUpdate(msg *shared.StreamMessage) (tea.Model, tea.case shared.StreamMessageBuildInfo:m.building = truem.tokensByPath[msg.BuildInfo.Path] += msg.BuildInfo.NumTokens- if msg.BuildInfo.Finished {- m.finishedByPath[msg.BuildInfo.Path] = true- }+ m.finishedByPath[msg.BuildInfo.Path] = msg.BuildInfo.Finished+ m.updateViewportDimensions()case shared.StreamMessageDescribing:m.processing = true@@ -155,5 +161,9 @@ func (m *streamUIModel) streamUpdate(msg *shared.StreamMessage) (tea.Model, tea.case shared.StreamMessageAborted:}- return m, nil+ if m.starting {+ return m, m.spinner.Tick+ } else {+ return m, nil+ }}diff --git a/app/cli/stream_tui/view.go b/app/cli/stream_tui/view.goindex 86a3354f..1975e3b5 100644--- a/app/cli/stream_tui/view.go+++ b/app/cli/stream_tui/view.go@@ -32,7 +32,7 @@ func (m streamUIModel) renderHelp() string {}func (m streamUIModel) renderProcessing() string {- if m.processing {+ if m.starting || m.processing {style := lipgloss.NewStyle().Width(m.width).BorderStyle(lipgloss.NormalBorder()).BorderTop(true).BorderForeground(lipgloss.Color(borderColor))return style.Render(m.spinner.View())@@ -50,9 +50,6 @@ func (m streamUIModel) renderBuild() string {head := color.New(color.BgGreen, color.FgHiWhite, color.Bold).Sprint(" 🏗 ") + color.New(color.BgGreen, color.FgHiWhite).Sprint("Building plan ")- var lines []string- lines = append(lines, head)-filePaths := make([]string, 0, len(m.tokensByPath))for filePath := range m.tokensByPath {filePaths = append(filePaths, filePath)@@ -60,18 +57,45 @@ func (m streamUIModel) renderBuild() string {sort.Strings(filePaths)+ var rows [][]string+ lineWidth := 0+ lineNum := 0+for _, filePath := range filePaths {tokens := m.tokensByPath[filePath]finished := m.finishedByPath[filePath]- line := fmt.Sprintf(" 📄 %s", filePath)+ block := fmt.Sprintf(" 📄 %s", filePath)if tokens > 0 {- line += fmt.Sprintf(" | %d 🪙", tokens)+ block += fmt.Sprintf(" | %d 🪙", tokens)}if finished {- line += " | ✅"+ block += " | ✅"+ }++ blockWidth := lipgloss.Width(block)++ if lineWidth+blockWidth > m.width {+ lineWidth = 0+ lineNum+++ }++ if len(rows) <= lineNum {+ rows = append(rows, []string{})}- lines = append(lines, line)++ row := rows[lineNum]+ row = append(row, block)+ rows[lineNum] = row++ lineWidth += blockWidth+ }++ resRows := make([]string, len(rows)+1)++ resRows[0] = head+ for i, row := range rows {+ resRows[i+1] = strings.Join(row, "")}- return style.Render(strings.Join(lines, "\n"))+ return style.Render(strings.Join(resRows, "\n"))}diff --git a/app/server/db/org_helpers.go b/app/server/db/org_helpers.goindex cefd379e..4dafb3f0 100644--- a/app/server/db/org_helpers.go+++ b/app/server/db/org_helpers.go@@ -80,7 +80,7 @@ func CreateOrg(req *shared.CreateOrgRequest, userId string, domain *string, tx *if err != nil {if IsNonUniqueErr(err) {// Handle the uniqueness constraint violation- return nil, fmt.Errorf("an org with domain %s already exists", domain)+ return nil, fmt.Errorf("an org with domain %s already exists", *domain)}diff --git a/app/server/model/plan/build.go b/app/server/model/plan/build.goindex b68a4016..adbdbce1 100644--- a/app/server/model/plan/build.go+++ b/app/server/model/plan/build.go@@ -33,7 +33,7 @@ func QueueBuild(currentOrgId, planId string, activeBuild *types.ActiveBuild) {})log.Printf("Queued build for file %s\n", filePath)- if !activePlan.PathFinished(filePath) {+ if activePlan.IsBuildingByPath[filePath] {log.Printf("Already building file %s\n", filePath)return} else {@@ -43,6 +43,10 @@ func QueueBuild(currentOrgId, planId string, activeBuild *types.ActiveBuild) {}func execPlanBuild(currentOrgId string, activePlan *types.ActivePlan, activeBuild *types.ActiveBuild) {+ Active.Update(activePlan.Id, func(ap *types.ActivePlan) {+ ap.IsBuildingByPath[activeBuild.Path] = true+ })+planId := activePlan.IdfilePath := activeBuild.Path@@ -109,6 +113,9 @@ func execPlanBuild(currentOrgId string, activePlan *types.ActivePlan, activeBuilerr := <-errChif err != nil {log.Printf("Error building plan %s: %v\n", planId, err)+ Active.Update(activePlan.Id, func(ap *types.ActivePlan) {+ ap.IsBuildingByPath[activeBuild.Path] = false+ })activePlan.StreamDoneCh <- &shared.ApiError{Type: shared.ApiErrorTypeOther,Status: http.StatusInternalServerError,@@ -119,9 +126,13 @@ func execPlanBuild(currentOrgId string, activePlan *types.ActivePlan, activeBuil}onFinishBuild := func() {- log.Println("Build finished.")- // activePlan.StreamCh <- shared.STREAM_FINISHED- activePlan.StreamDoneCh <- nil+ log.Println("Build finished")++ if Active.Get(planId).RepliesFinished {+ activePlan.Stream(shared.StreamMessage{+ Type: shared.StreamMessageFinished,+ })+ }}onFinishBuildFile := func(filePath string, planRes *db.PlanFileResult) {@@ -145,12 +156,28 @@ func execPlanBuild(currentOrgId string, activePlan *types.ActivePlan, activeBuilActive.Update(planId, func(ap *types.ActivePlan) {ap.BuiltFiles[filePath] = true+ ap.IsBuildingByPath[filePath] = falseif ap.BuildFinished() {finished = true}})+ if !activePlan.PathFinished(filePath) {+ log.Printf("Processing next build for file %s\n", filePath)+ var nextBuild *types.ActiveBuild+ for _, build := range activePlan.BuildQueuesByPath[filePath] {+ if !build.BuildFinished() {+ nextBuild = build+ break+ }+ }+ if nextBuild != nil {+ go execPlanBuild(currentOrgId, activePlan, nextBuild)+ }+ return+ }+log.Printf("Finished building file %s\n", filePath)if finished {@@ -179,6 +206,10 @@ func execPlanBuild(currentOrgId string, activePlan *types.ActivePlan, activeBuilif err != nil {log.Printf("Error setting build error: %v\n", err)}++ Active.Update(activePlan.Id, func(ap *types.ActivePlan) {+ ap.IsBuildingByPath[activeBuild.Path] = false+ })}var buildFile func(filePath string, numRetry int, numReplacementRetry int, res *db.PlanFileResult)diff --git a/app/server/model/plan/tell.go b/app/server/model/plan/tell.goindex d3bf163c..2e114c87 100644--- a/app/server/model/plan/tell.go+++ b/app/server/model/plan/tell.go@@ -503,10 +503,11 @@ func execTellPlan(plan *db.Plan, auth *types.ServerAuth, req *shared.TellPlanReqselect {case <-active.Ctx.Done():// The main modelContext was canceled (not the timer)+ log.Println("\nTell: stream canceled")returncase <-timer.C:// Timer triggered because no new chunk was received in time- log.Println("\nStream timeout due to inactivity")+ log.Println("\nTell: stream timeout due to inactivity")onError(fmt.Errorf("stream timeout due to inactivity"), true, "", "")returndefault:@@ -633,13 +634,17 @@ func execTellPlan(plan *db.Plan, auth *types.ServerAuth, req *shared.TellPlanReq}if !req.AutoContinue || execStatus.Finished || execStatus.NeedsInput {- active.Stream(shared.StreamMessage{- Type: shared.StreamMessageFinished,- })- active.StreamDoneCh <- nil- } else {- // TODO: validate that user can continue plan+ if Active.Get(planId).BuildFinished() {+ active.Stream(shared.StreamMessage{+ Type: shared.StreamMessageFinished,+ })+ } else {+ Active.Update(planId, func(active *types.ActivePlan) {+ active.RepliesFinished = true+ })+ }+ } else {// continue planexecTellPlan(plan, auth, req, active, iteration+1)}@@ -664,14 +669,11 @@ func execTellPlan(plan *db.Plan, auth *types.ServerAuth, req *shared.TellPlanReqfiles, _, _, numTokens := replyParser.Read()replyNumTokens = numTokens- log.Printf("Reply num tokens: %d\n", replyNumTokens)- log.Printf("Reply files: %v\n", files)+ // log.Printf("Reply num tokens: %d\n", replyNumTokens)+ // log.Printf("Reply files: %v\n", files)if len(files) > len(replyFiles) {- log.Println("New files found")-latestFile := files[len(files)-1]-Active.Update(planId, func(active *types.ActivePlan) {active.Files = files})diff --git a/app/server/types/active_plan.go b/app/server/types/active_plan.goindex 99d7adec..bce99f01 100644--- a/app/server/types/active_plan.go+++ b/app/server/types/active_plan.go@@ -29,10 +29,12 @@ type ActivePlan struct {ContextsByPath map[string]*db.ContextFiles []stringBuiltFiles map[string]bool+ IsBuildingByPath map[string]boolCurrentReplyContent stringNumTokens intPromptMessageNum intBuildQueuesByPath map[string][]*ActiveBuild+ RepliesFinished boolStreamDoneCh chan *shared.ApiErrorstreamCh chan string@@ -52,10 +54,10 @@ func NewActivePlan(planId, prompt string) *ActivePlan {ContextsByPath: map[string]*db.Context{},Files: []string{},BuiltFiles: map[string]bool{},-- streamCh: make(chan string),- StreamDoneCh: make(chan *shared.ApiError),- subscriptions: map[string]chan string{},+ IsBuildingByPath: map[string]bool{},+ StreamDoneCh: make(chan *shared.ApiError),+ streamCh: make(chan string),+ subscriptions: map[string]chan string{},}go func() {@@ -85,6 +87,10 @@ func (ap *ActivePlan) Stream(msg shared.StreamMessage) {return}ap.streamCh <- string(msgJson)++ if msg.Type == shared.StreamMessageFinished {+ ap.StreamDoneCh <- nil+ }}func (ap *ActivePlan) BuildFinished() bool {diff --git a/app/server/types/reply.go b/app/server/types/reply.goindex 29fbdb09..2dbef629 100644--- a/app/server/types/reply.go+++ b/app/server/types/reply.go@@ -1,8 +1,6 @@package typesimport (- "log"- "strconv""strings")@@ -31,7 +29,7 @@ func NewReplyParser() *replyParser {}func (r *replyParser) AddChunk(chunk string, addToTotal bool) {- log.Println("Adding chunk:", strconv.Quote(chunk)) // Logging the chunk that's being processed+ // log.Println("Adding chunk:", strconv.Quote(chunk)) // Logging the chunk that's being processedhasNewLine := falsenextChunk := ""@@ -43,19 +41,19 @@ func (r *replyParser) AddChunk(chunk string, addToTotal bool) {r.numTokensByFile[r.currentFilePath]++}- log.Println("Total tokens:", r.numTokens)- log.Println("Tokens by file path:", r.numTokensByFile)+ // log.Println("Total tokens:", r.numTokens)+ // log.Println("Tokens by file path:", r.numTokensByFile)}if chunk == "\n" {- log.Println("Chunk is \\n, adding new line")+ // log.Println("Chunk is \\n, adding new line")r.lines = append(r.lines, "")hasNewLine = truer.lineIndex++} else {chunkLines := strings.Split(chunk, "\n")- log.Println("Chunk lines:", len(chunkLines))+ // log.Println("Chunk lines:", len(chunkLines))currentLine := r.lines[r.lineIndex]currentLine += chunkLines[0]@@ -80,22 +78,22 @@ func (r *replyParser) AddChunk(chunk string, addToTotal bool) {}if r.lineIndex == 0 || !hasNewLine {- log.Println("No new line detected--returning")+ // log.Println("No new line detected--returning")return}prevFullLine := r.lines[r.lineIndex-1]- log.Println("Previous full line:", strconv.Quote(prevFullLine)) // Logging the full line that's being checked+ // log.Println("Previous full line:", strconv.Quote(prevFullLine)) // Logging the full line that's being checkedprevFullLineTrimmed := strings.TrimSpace(prevFullLine)if r.maybeFilePath != "" {- log.Println("Maybe file path is:", r.maybeFilePath) // Logging the maybeFilePath+ // log.Println("Maybe file path is:", r.maybeFilePath) // Logging the maybeFilePathif strings.HasPrefix(prevFullLineTrimmed, "```") {r.currentFilePath = r.maybeFilePathr.maybeFilePath = ""r.currentFileLines = []string{}- log.Println("Confirmed file path:", r.currentFilePath) // Logging the confirmed file path+ // log.Println("Confirmed file path:", r.currentFilePath) // Logging the confirmed file pathreturn} else if prevFullLineTrimmed != "" {// turns out previous maybeFilePath was not a file path since there's a non-empty line before finding opening ticks@@ -104,7 +102,7 @@ func (r *replyParser) AddChunk(chunk string, addToTotal bool) {}if r.currentFilePath == "" {- log.Println("Current file path is empty--checking for possible file path...")+ // log.Println("Current file path is empty--checking for possible file path...")var gotPath stringif (strings.HasPrefix(prevFullLineTrimmed, "-")) || strings.HasPrefix(prevFullLineTrimmed, "-file:") || strings.HasPrefix(prevFullLineTrimmed, "- file:") || (strings.HasPrefix(prevFullLineTrimmed, "**") && strings.HasSuffix(prevFullLineTrimmed, "**")) {@@ -117,11 +115,11 @@ func (r *replyParser) AddChunk(chunk string, addToTotal bool) {p = strings.TrimSpace(p)gotPath = p} else {- log.Println("No possible file path detected.", strconv.Quote(prevFullLineTrimmed))+ // log.Println("No possible file path detected.", strconv.Quote(prevFullLineTrimmed))}if gotPath != "" {- log.Println("Detected possible file path:", gotPath) // Logging the possible file path+ // log.Println("Detected possible file path:", gotPath) // Logging the possible file pathif r.maybeFilePath == "" {r.maybeFilePath = gotPath@@ -131,10 +129,10 @@ func (r *replyParser) AddChunk(chunk string, addToTotal bool) {}} else {if strings.HasPrefix(prevFullLineTrimmed, "```") {+ r.files[r.currentFilePath] = truer.currentFilePath = ""- log.Println("Exited file block.")+ // log.Println("Exited file block.")} else {- r.files[r.currentFilePath] = truer.fileContents[r.currentFilePath] += prevFullLine + "\n"r.currentFileLines = append(r.currentFileLines, prevFullLine)diff --git a/app/server/types/reply_test.go b/app/server/types/reply_test.goindex 92f6eede..518ba7cf 100644--- a/app/server/types/reply_test.go+++ b/app/server/types/reply_test.go@@ -17,43 +17,43 @@ var examples = []TestExample{{N: 1,TokensByFilePath: map[string]int{- "cmd/checkout.go": 17,- "cmd/apply.go": 41,+ "cmd/checkout.go": 54,+ "cmd/apply.go": 180,+ },+ },+ {+ N: 2,+ TokensByFilePath: map[string]int{+ "cmd/context_rm.go": 210,+ "cmd/context_update.go": 188,+ },+ },+ {+ N: 3,+ TokensByFilePath: map[string]int{+ "cmd/context_rm.go": 210,+ "cmd/context_update.go": 188,+ },+ },+ {+ N: 4,+ TokensByFilePath: map[string]int{+ "server/types/section.go": 32,+ },+ },+ {+ N: 5,+ TokensByFilePath: map[string]int{+ "shared/types.go": 20,+ "cli/lib/conversation.go": 58,+ },+ },+ {+ N: 6,+ TokensByFilePath: map[string]int{+ "server/model/proposal/create.go": 239,},},- // {- // N: 2,- // TokensByFilePath: map[string]int{- // "cmd/context_rm.go": 51,- // "cmd/context_update.go": 41,- // },- // },- // {- // N: 3,- // TokensByFilePath: map[string]int{- // "cmd/context_rm.go": 51,- // "cmd/context_update.go": 41,- // },- // },- // {- // N: 4,- // TokensByFilePath: map[string]int{- // "server/types/section.go": 11,- // },- // },- // {- // N: 5,- // TokensByFilePath: map[string]int{- // "shared/types.go": 5,- // "cli/lib/conversation.go": 8,- // },- // },- // {- // N: 6,- // TokensByFilePath: map[string]int{- // "server/model/proposal/create.go": 32,- // },- // },}func TestReplyTokenCounter(t *testing.T) {@@ -87,22 +87,22 @@ func TestReplyTokenCounter(t *testing.T) {files, fileContents, tokensByFilePath, totalCounted := counter.FinishAndRead()- // fmt.Printf("Total tokens counted: %d\n", totalCounted)- // fmt.Printf("%d files: %v\n", len(files), files)- // fmt.Printf("%d file content: %v\n", len(fileContents), fileContents)- // fmt.Println("Tokens by file path:")- // for filePath, tokens := range tokensByFilePath {- // fmt.Printf("%s: %d\n", filePath, tokens)- // }+ fmt.Printf("Total tokens counted: %d\n", totalCounted)+ fmt.Printf("%d files: %v\n", len(files), files)+ fmt.Printf("%d file content: %v\n", len(fileContents), fileContents)+ fmt.Println("Tokens by file path:")+ for filePath, tokens := range tokensByFilePath {+ fmt.Printf("%s: %d\n", filePath, tokens)+ }- // if totalCounted != totalTokens {- // t.Errorf("Expected %d tokens, got %d", totalTokens, totalCounted)- // }+ if totalCounted != totalTokens {+ t.Errorf("Expected %d tokens, got %d", totalTokens, totalCounted)+ }- // for filePath, tokens := range example.TokensByFilePath {- // if tokensByFilePath[filePath] != tokens {- // t.Errorf("Expected %d tokens for %s, got %d", tokens, filePath, tokensByFilePath[filePath])- // }- // }+ for filePath, tokens := range example.TokensByFilePath {+ if tokensByFilePath[filePath] != tokens {+ t.Errorf("Expected %d tokens for %s, got %d", tokens, filePath, tokensByFilePath[filePath])+ }+ }}}diff --git a/app/shared/tokens.go b/app/shared/tokens.goindex 82070b6c..2a4d1312 100644--- a/app/shared/tokens.go+++ b/app/shared/tokens.go@@ -6,9 +6,9 @@ import ("github.com/pkoukk/tiktoken-go")-var MaxTokens int = 7000 //120000-var MaxContextTokens int = 5000 //50000-var MaxConvoTokens int = 2000 //20000+var MaxTokens int = 120000+var MaxContextTokens int = 50000+var MaxConvoTokens int = 5000func GetNumTokens(text string) (int, error) {tkm, err := tiktoken.EncodingForModel("gpt-4")