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
changes tui close to done, needs a bit more work. some general refactoring/fixes
Dane Schneiderc3aec0168158
diff --git a/cli/changes_tui/actions.go b/cli/changes_tui/actions.gonew file mode 100644index 00000000..3a286d82--- /dev/null+++ b/cli/changes_tui/actions.go@@ -0,0 +1,125 @@+package changes_tui++import (+ "fmt"++ "github.com/atotto/clipboard"+ "github.com/muesli/reflow/wrap"+ "github.com/plandex/plandex/shared"+)++func (m changesUIModel) rejectChange() error {++ return nil+}++func (m changesUIModel) applyAllChanges() error {++ return nil+}++func (m changesUIModel) rejectAllChanges() error {++ return nil+}++func (m changesUIModel) copyCurrentChange() error {+ selectionInfo := m.selectionInfo+ if selectionInfo.currentRep == nil {+ return fmt.Errorf("no change is currently selected")+ }++ // Copy the 'New' content of the replacement to the clipboard+ if err := clipboard.WriteAll(selectionInfo.currentRep.New); err != nil {+ return fmt.Errorf("failed to copy to clipboard: %v", err)+ }++ return nil+}++func (m *changesUIModel) up() {+ paths := m.currentPlan.SortedPaths+ if m.selectedReplacementIndex > 0 {+ m.selectedReplacementIndex--+ } else if m.selectedFileIndex > 0 {+ m.selectedFileIndex--+ m.selectedReplacementIndex = len(m.resultsInfo.ReplacementsByPath[paths[m.selectedFileIndex]]) - 1+ }+ m.setSelectionInfo()+ m.updateMainView()+}++func (m *changesUIModel) down() {+ paths := m.currentPlan.SortedPaths+ var currentReplacements []*shared.Replacement+ if m.selectionInfo != nil {+ currentReplacements = m.selectionInfo.currentReplacements+ }++ if m.selectedReplacementIndex < len(currentReplacements)-1 {+ m.selectedReplacementIndex+++ } else if m.selectedFileIndex < len(paths)-1 {+ m.selectedFileIndex+++ m.selectedReplacementIndex = 0+ }+ m.setSelectionInfo()+ m.updateMainView()+}++func (m *changesUIModel) scrollUp() {+ if m.selectionInfo.currentRep == nil && m.fileScrollable() {+ m.fileViewport.LineUp(1)+ } else if m.selectedViewport == 0 && m.oldScrollable() {+ m.changeOldViewport.LineUp(1)+ } else if m.newScrollable() {+ m.changeNewViewport.LineUp(1)+ }+}++func (m *changesUIModel) scrollDown() {+ if m.selectionInfo.currentRep == nil && m.fileScrollable() {+ m.fileViewport.LineDown(1)+ } else if m.selectedViewport == 0 && m.oldScrollable() {+ m.changeOldViewport.LineDown(1)+ } else if m.newScrollable() {+ m.changeNewViewport.LineDown(1)+ }+}++func (m *changesUIModel) pageUp() {++}++func (m *changesUIModel) pageDown() {++}++func (m *changesUIModel) switchView() {+ m.selectedViewport = 1 - m.selectedViewport+ m.updateMainView()+}++func (m *changesUIModel) windowResized(w, h int) {+ m.width = w+ m.height = h+ if !m.ready {+ m.initViewports()+ m.ready = true+ }+ m.updateMainView()+}++func (m *changesUIModel) updateMainView() {+ updatedFile := m.selectionInfo.currentPlanBeforeReplacement.CurrentPlanFiles.Files[m.selectionInfo.currentPath]++ oldContentDisplay, prependContent, appendContent := m.getReplacementOldDisplay()++ m.changeOldViewport.SetContent(oldContentDisplay)++ newContentDisplay := m.getReplacementNewDisplay(prependContent, appendContent)+ m.changeNewViewport.SetContent(newContentDisplay)++ m.fileViewport.SetContent(wrap.String(updatedFile, m.fileViewport.Width-2))++ m.updateViewportSizes()+}diff --git a/cli/changes_tui/main_viewport.go b/cli/changes_tui/main_viewport.gonew file mode 100644index 00000000..7dd70008--- /dev/null+++ b/cli/changes_tui/main_viewport.go@@ -0,0 +1,90 @@+package changes_tui++import (+ "github.com/charmbracelet/lipgloss"+)++func (m changesUIModel) renderMainView() string {+ oldView := m.changeOldViewport.View()+ newView := m.changeNewViewport.View()++ oldViews := []string{oldView}+ newViews := []string{newView}++ if m.oldScrollable() && m.selectedViewport == 0 {+ oldViews = append(oldViews, m.renderScrollFooter())+ } else if m.newScrollable() {+ newViews = append(newViews, m.renderScrollFooter())+ }++ oldContainer := lipgloss.JoinVertical(lipgloss.Left, oldViews...)+ newContainer := lipgloss.JoinVertical(lipgloss.Left, newViews...)++ oldContainerStyle := lipgloss.NewStyle().Width(m.changeOldViewport.Width)+ oldContainer = oldContainerStyle.Render(oldContainer)++ newContainerStyle := lipgloss.NewStyle().+ BorderStyle(lipgloss.NormalBorder()).+ BorderLeft(true).+ BorderForeground(lipgloss.Color(borderColor)).+ Width(m.changeNewViewport.Width)++ newContainer = newContainerStyle.Render(newContainer)++ return lipgloss.JoinVertical(lipgloss.Left,+ m.renderMainViewHeader(),+ lipgloss.JoinHorizontal(lipgloss.Top,+ oldContainer,+ newContainer,+ ),+ m.renderMainViewFooter(),+ )+}++func (m changesUIModel) renderMainViewHeader() string {+ if m.selectionInfo == nil {+ return "\n"+ }++ sidebarWidth := lipgloss.Width(m.renderSidebar())+ style := lipgloss.NewStyle().+ Width(m.width - sidebarWidth).+ BorderStyle(lipgloss.NormalBorder()).+ BorderBottom(true).+ BorderForeground(borderColor)++ header := " π " + m.selectionInfo.currentRep.Summary+ return style.Render(header)+}++func (m changesUIModel) renderMainViewFooter() string {+ sidebarWidth := lipgloss.Width(m.renderSidebar())+ style := lipgloss.NewStyle().Width(m.width - sidebarWidth).Inherit(topBorderStyle).Foreground(lipgloss.Color(helpTextColor))+ footer := ` (d)iscard selected change β’ (c)opy to clipboard`+ return style.Render(footer)+}++func (m changesUIModel) renderScrollFooter() string {+ if m.selectionInfo == nil {+ return ""+ }++ oldScrollable := m.changeOldViewport.TotalLineCount() > m.changeOldViewport.VisibleLineCount()+ newScrollable := m.changeNewViewport.TotalLineCount() > m.changeNewViewport.VisibleLineCount()++ width, _ := m.getMainViewDims()++ if m.selectionInfo.currentRes != nil {+ width = width / 2+ }++ footer := ` (j/k) scroll`++ if oldScrollable && newScrollable {+ footer += ` β’ (tab) switch view`+ }++ style := lipgloss.NewStyle().Width(width).Inherit(topBorderStyle).Foreground(lipgloss.Color(helpTextColor))++ return style.Render(footer)+}diff --git a/cli/changes_tui/model.go b/cli/changes_tui/model.gonew file mode 100644index 00000000..531520c1--- /dev/null+++ b/cli/changes_tui/model.go@@ -0,0 +1,115 @@+package changes_tui++import (+ "fmt"+ "log"+ "plandex/lib"+ "plandex/types"++ "github.com/charmbracelet/bubbles/help"+ bubbleKey "github.com/charmbracelet/bubbles/key"+ "github.com/charmbracelet/bubbles/viewport"+ tea "github.com/charmbracelet/bubbletea"+)++type changesUIModel struct {+ help help.Model+ keymap keymap+ selectedFileIndex int+ selectedReplacementIndex int+ selectedViewport int+ resultsInfo *types.PlanResultsInfo+ currentPlan *types.CurrentPlanState+ changeOldViewport viewport.Model+ changeNewViewport viewport.Model+ fileViewport viewport.Model+ selectionInfo *selectionInfo+ ready bool+ width int+ height int+}++type keymap = struct {+ up,+ down,+ left,+ right,+ scrollUp,+ scrollDown,+ pageUp,+ pageDown,+ switchView,+ reject,+ copy,+ applyAll,+ rejectAll,+ quit bubbleKey.Binding+}++func (m changesUIModel) Init() tea.Cmd {+ return nil+}++func initialModel() *changesUIModel {+ currentPlan, err := lib.GetCurrentPlanState()+ if err != nil {+ err = fmt.Errorf("error getting current plan state: %v", err)+ log.Println(err)+ panic(err)+ }++ initialState := changesUIModel{+ currentPlan: currentPlan,+ selectedFileIndex: 0,+ selectedReplacementIndex: 0,+ help: help.New(),+ keymap: keymap{+ up: bubbleKey.NewBinding(+ bubbleKey.WithKeys("up"),+ bubbleKey.WithHelp("up", "prev change"),+ ),++ down: bubbleKey.NewBinding(+ bubbleKey.WithKeys("down"),+ bubbleKey.WithHelp("down", "next change"),+ ),++ scrollDown: bubbleKey.NewBinding(+ bubbleKey.WithKeys("j"),+ bubbleKey.WithHelp("j", "scroll down"),+ ),++ scrollUp: bubbleKey.NewBinding(+ bubbleKey.WithKeys("k"),+ bubbleKey.WithHelp("k", "scroll up"),+ ),++ switchView: bubbleKey.NewBinding(+ bubbleKey.WithKeys("tab"),+ bubbleKey.WithHelp("tab", "switch view"),+ ),++ reject: bubbleKey.NewBinding(+ bubbleKey.WithKeys("d"),+ bubbleKey.WithHelp("d", "discard change"),+ ),++ copy: bubbleKey.NewBinding(+ bubbleKey.WithKeys("c"),+ bubbleKey.WithHelp("c", "copy change"),+ ),++ applyAll: bubbleKey.NewBinding(+ bubbleKey.WithKeys("ctrl+a"),+ bubbleKey.WithHelp("ctrl+a", "apply all changes"),+ ),++ quit: bubbleKey.NewBinding(+ bubbleKey.WithKeys("q", "ctrl+c"),+ bubbleKey.WithHelp("q", "quit"),+ ),+ },+ }++ return &initialState+}diff --git a/cli/changes_tui/path_tabs.go b/cli/changes_tui/path_tabs.gonew file mode 100644index 00000000..755be47a--- /dev/null+++ b/cli/changes_tui/path_tabs.go@@ -0,0 +1,79 @@+package changes_tui++import (+ "strings"++ "github.com/charmbracelet/lipgloss"+ "github.com/fatih/color"+)++func (m changesUIModel) renderPathTabs() string {+ if m.selectionInfo == nil || m.width == 0 {+ return ""+ }++ var tabRows [][]string++ lineWidth := 0+ lineNum := 0++ paths := m.currentPlan.SortedPaths++ for i, path := range paths {+ selected := i == m.selectedFileIndex++ if len(path) > 20 {+ path = path[:10] + "β―" + path[len(path)-10:]+ }++ tab := " π " + path + " "++ results := m.currentPlan.PlanResByPath[path]+ pathColor := color.FgHiGreen+ bgColor := color.BgGreen+ anyFailed := false+ for _, result := range results {+ if result.AnyFailed {+ anyFailed = true+ break+ }+ }+ if anyFailed {+ pathColor = color.FgHiRed+ bgColor = color.BgRed+ }++ if selected {+ tab = color.New(color.Bold, bgColor, color.FgHiWhite).Sprint(tab)+ } else {+ tab = color.New(pathColor).Sprint(tab)+ }++ tabWidth := lipgloss.Width(tab)++ if lineWidth+tabWidth > m.width {+ lineWidth = 0+ lineNum+++ }++ if len(tabRows) <= lineNum {+ tabRows = append(tabRows, []string{})+ }++ tabs := tabRows[lineNum]+ tabs = append(tabs, tab)+ tabRows[lineNum] = tabs++ lineWidth += tabWidth+ }++ resRows := make([]string, len(tabRows))++ for i, row := range tabRows {+ resRows[i] = strings.Join(row, "")+ }++ style := lipgloss.NewStyle().BorderStyle(lipgloss.NormalBorder()).BorderBottom(true).BorderForeground(lipgloss.Color(borderColor)).Width(m.width)++ return style.Render(strings.Join(resRows, "\n"))+}diff --git a/cli/changes_tui/replacement.go b/cli/changes_tui/replacement.gonew file mode 100644index 00000000..c0077570--- /dev/null+++ b/cli/changes_tui/replacement.go@@ -0,0 +1,100 @@+package changes_tui++import (+ "strings"++ "github.com/fatih/color"+ "github.com/muesli/reflow/wrap"+)++const prependLines = 10+const appendLines = 10++func (m changesUIModel) getReplacementOldDisplay() (string, string, string) {+ oldContent := m.selectionInfo.currentRep.Old+ originalFile := m.selectionInfo.currentPlanBeforeReplacement.CurrentPlanFiles.Files[m.selectionInfo.currentPath]++ // log.Printf("oldContent: %v", oldContent)+ // log.Printf("originalFile: %v", originalFile)++ fileIdx := strings.Index(originalFile, oldContent)+ if fileIdx == -1 {+ panic("old content not found in full file") // should never happen+ }++ toPrepend := ""+ numLinesPrepended := 0+ for i := fileIdx - 1; i >= 0; i-- {+ s := string(originalFile[i])+ toPrepend = s + toPrepend+ if originalFile[i] == '\n' {+ numLinesPrepended+++ if numLinesPrepended == prependLines {+ break+ }+ }+ }++ toPrepend = strings.TrimLeft(toPrepend, "\n")++ toAppend := ""+ numLinesAppended := 0+ for i := fileIdx + len(oldContent); i < len(originalFile); i++ {+ s := string(originalFile[i])+ if s == "\t" {+ s = " "+ }+ toAppend += s+ if originalFile[i] == '\n' {+ numLinesAppended+++ if numLinesAppended == appendLines {+ break+ }+ }+ }++ toAppend = strings.TrimRight(toAppend, "\n")++ wrapWidth := m.changeOldViewport.Width - 6+ toPrepend = wrap.String(toPrepend, wrapWidth)+ oldContent = wrap.String(oldContent, wrapWidth)+ toAppend = wrap.String(toAppend, wrapWidth)++ toPrependLines := strings.Split(toPrepend, "\n")+ for i, line := range toPrependLines {+ toPrependLines[i] = color.New(color.FgWhite).Sprint(line)+ }+ toPrepend = strings.Join(toPrependLines, "\n")++ oldContentLines := strings.Split(oldContent, "\n")+ for i, line := range oldContentLines {+ oldContentLines[i] = color.New(color.FgHiRed).Sprint(line)+ }+ oldContent = strings.Join(oldContentLines, "\n")++ toAppendLines := strings.Split(toAppend, "\n")+ for i, line := range toAppendLines {+ toAppendLines[i] = color.New(color.FgWhite).Sprint(line)+ }+ toAppend = strings.Join(toAppendLines, "\n")++ oldDisplayContent :=+ toPrepend ++ oldContent ++ toAppend++ return oldDisplayContent, toPrepend, toAppend+}++func (m changesUIModel) getReplacementNewDisplay(prependContent, appendContent string) string {+ newContent := m.selectionInfo.currentRep.New+ newContent = wrap.String(newContent, m.changeNewViewport.Width-6)++ newContentLines := strings.Split(newContent, "\n")+ for i, line := range newContentLines {+ newContentLines[i] = color.New(color.FgHiGreen).Sprint(line)+ }+ newContent = strings.Join(newContentLines, "\n")++ return prependContent + newContent + appendContent+}diff --git a/cli/changes_tui/selection.go b/cli/changes_tui/selection.gonew file mode 100644index 00000000..b0455996--- /dev/null+++ b/cli/changes_tui/selection.go@@ -0,0 +1,64 @@+package changes_tui++import (+ "fmt"+ "log"+ "plandex/lib"+ "plandex/types"++ "github.com/plandex/plandex/shared"+)++type selectionInfo struct {+ currentPath string+ currentRes *shared.PlanResult+ currentReplacements []*shared.Replacement+ currentRep *shared.Replacement+ currentPlanBeforeReplacement *types.CurrentPlanState+}++func (m *changesUIModel) setSelectionInfo() {+ paths := m.currentPlan.SortedPaths+ currentPath := paths[m.selectedFileIndex]++ results := m.currentPlan.PlanResByPath[currentPath]++ var currentRes *shared.PlanResult+ var currentRep *shared.Replacement++ var pathReplacements []*shared.Replacement++ for i, res := range results {+ for j, rep := range res.Replacements {+ pathReplacements = append(pathReplacements, rep)++ flatIndex := i*len(res.Replacements) + j+ if flatIndex == m.selectedReplacementIndex {+ currentRes = res+ currentRep = rep+ }+ }+ }++ var currentPlanAtReplacement *types.CurrentPlanState+ var err error++ if currentRep == nil {+ currentPlanAtReplacement = m.currentPlan+ } else {+ currentPlanAtReplacement, err = lib.GetCurrentPlanStateBeforeReplacement(currentRep.Id)+ }+ if err != nil {+ err = fmt.Errorf("error getting current plan state: %v", err)+ log.Println(err)+ panic(err)+ }++ m.selectionInfo = &selectionInfo{+ currentPath: currentPath,+ currentRes: currentRes,+ currentReplacements: pathReplacements,+ currentRep: currentRep,+ currentPlanBeforeReplacement: currentPlanAtReplacement,+ }+}diff --git a/cli/changes_tui/sidebar.go b/cli/changes_tui/sidebar.gonew file mode 100644index 00000000..34d44ff9--- /dev/null+++ b/cli/changes_tui/sidebar.go@@ -0,0 +1,86 @@+package changes_tui++import (+ "strings"++ "github.com/charmbracelet/lipgloss"+ "github.com/fatih/color"+)++func (m changesUIModel) renderSidebar() string {+ paths := m.currentPlan.SortedPaths++ if m.selectionInfo == nil {+ return ""+ }++ currentPath := m.selectionInfo.currentPath+ currentRes := m.selectionInfo.currentRes+ currentRep := m.selectionInfo.currentRep++ var sb strings.Builder++ for _, path := range paths {+ results := m.currentPlan.PlanResByPath[path]+ selectedPath := path == currentPath++ selectedFullFile := selectedPath && currentRes == nil++ anyFailed := false++ // Change entries+ for i, result := range results {+ for j, rep := range result.Replacements {+ flatIndex := i*len(result.Replacements) + j++ selected := selectedPath && rep.Id == currentRep.Id++ s := ""++ labelColor := color.FgHiGreen+ if rep.Failed {+ labelColor = color.FgHiRed+ anyFailed = true+ }++ if selected {+ s += color.New(color.Bold, labelColor).Sprintf(" > ") + color.New(color.Bold, labelColor).Sprintf("%d", flatIndex)+ } else {+ s += color.New(labelColor).Sprintf(" - %d", flatIndex)+ }++ if result.RejectedAt != "" {+ s += " π«"+ }++ s += "\n"++ sb.WriteString(s)+ }++ }++ labelColor := color.FgHiGreen+ if anyFailed {+ labelColor = color.FgHiRed+ }++ if selectedFullFile {+ sb.WriteString(color.New(color.Bold, labelColor).Sprint(" > π \n "))+ } else {+ sb.WriteString(color.New(labelColor).Sprint(" - π \n"))+ }+ }++ helpHeight := lipgloss.Height(m.renderHelp())+ tabsHeight := lipgloss.Height(m.renderPathTabs())+ sidebar := sb.String()++ style := lipgloss.NewStyle().+ Height(m.height - (helpHeight + tabsHeight)).+ BorderStyle(lipgloss.NormalBorder()).+ BorderRight(true).+ BorderForeground(borderColor)++ return style.Render(sidebar)+}diff --git a/cli/changes_tui/start.go b/cli/changes_tui/start.gonew file mode 100644index 00000000..4e26bef4--- /dev/null+++ b/cli/changes_tui/start.go@@ -0,0 +1,27 @@+package changes_tui++import (+ "fmt"++ tea "github.com/charmbracelet/bubbletea"+)++func StartChangesUI() error {+ initial := initialModel()++ if len(initial.currentPlan.SortedPaths) == 0 {+ fmt.Println("π€·ββοΈ No changes to apply")+ return nil+ }++ _, err := tea.NewProgram(initial, tea.WithAltScreen()).Run()++ if err != nil {+ return fmt.Errorf("error running changes UI: %v", err)+ }++ // fmt.Println("exited changes UI")+ // spew.Dump(m)++ return nil+}diff --git a/cli/changes_tui/update.go b/cli/changes_tui/update.gonew file mode 100644index 00000000..7ecbe0d2--- /dev/null+++ b/cli/changes_tui/update.go@@ -0,0 +1,95 @@+package changes_tui++import (+ "time"++ bubbleKey "github.com/charmbracelet/bubbles/key"+ tea "github.com/charmbracelet/bubbletea"+)++func (m changesUIModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {+ // log.Println("msg:", msg)++ if m.selectionInfo == nil {+ m.setSelectionInfo()+ }++ switch msg := msg.(type) {++ case tea.WindowSizeMsg:+ m.windowResized(msg.Width, msg.Height)++ case tea.KeyMsg:++ switch {++ case bubbleKey.Matches(msg, m.keymap.up):+ m.up()++ case bubbleKey.Matches(msg, m.keymap.down):+ m.down()++ case bubbleKey.Matches(msg, m.keymap.scrollDown):+ m.scrollDown()++ case bubbleKey.Matches(msg, m.keymap.scrollUp):+ m.scrollUp()++ case bubbleKey.Matches(msg, m.keymap.switchView):+ m.switchView()++ case bubbleKey.Matches(msg, m.keymap.reject):+ m.rejectChange()++ case bubbleKey.Matches(msg, m.keymap.applyAll):+ m.applyAllChanges()++ case bubbleKey.Matches(msg, m.keymap.rejectAll):+ m.rejectAllChanges()++ case bubbleKey.Matches(msg, m.keymap.copy):+ m.copyCurrentChange()++ case bubbleKey.Matches(msg, m.keymap.quit):+ return m, tea.Quit++ default:+ // handle escape sequences sometimes sent by arrow keys+ m.resolveEscapeSequence(msg.String())+ }+ }++ return m, nil+}++var escReceivedAt time.Time+var escSeq string++func (m *changesUIModel) resolveEscapeSequence(val string) {+ if val == "esc" || val == "alt+[" {+ escReceivedAt = time.Now()+ go func() {+ time.Sleep(51 * time.Millisecond)+ escReceivedAt = time.Time{}+ escSeq = ""+ }()+ }++ if !escReceivedAt.IsZero() {+ elapsed := time.Since(escReceivedAt)++ if elapsed < 50*time.Millisecond {+ escSeq += val++ if escSeq == "esc[A" || escSeq == "alt+[A" {+ m.up()+ escReceivedAt = time.Time{}+ escSeq = ""+ } else if escSeq == "esc[B" || escSeq == "alt+[B" {+ m.down()+ escReceivedAt = time.Time{}+ escSeq = ""+ }+ }+ }+}diff --git a/cli/changes_tui/view.go b/cli/changes_tui/view.gonew file mode 100644index 00000000..2a783ebe--- /dev/null+++ b/cli/changes_tui/view.go@@ -0,0 +1,101 @@+package changes_tui++import (+ "github.com/charmbracelet/bubbles/viewport"+ "github.com/charmbracelet/lipgloss"+)++var borderColor = lipgloss.Color("#444")+var helpTextColor = lipgloss.Color("#ddd")+var topBorderStyle = lipgloss.NewStyle().+ BorderStyle(lipgloss.NormalBorder()).+ BorderTop(true).+ BorderForeground(borderColor)++func (m changesUIModel) View() string {+ help := m.renderHelp()++ tabs := m.renderPathTabs()++ sidebar := m.renderSidebar()++ mainView := m.renderMainView()++ layout := lipgloss.JoinHorizontal(lipgloss.Top, sidebar, mainView)++ return lipgloss.JoinVertical(lipgloss.Left,+ tabs,+ layout,+ help,+ )+}++func (m changesUIModel) getMainViewDims() (int, int) {+ tabsHeight := lipgloss.Height(m.renderPathTabs())+ helpHeight := lipgloss.Height(m.renderHelp())+ sidebarWidth := lipgloss.Width(m.renderSidebar())+ mainViewWidth := m.width - sidebarWidth+ mainViewHeight := m.height - (helpHeight + tabsHeight + lipgloss.Height(m.renderMainViewHeader()) + lipgloss.Height(m.renderMainViewFooter()))++ return mainViewWidth, mainViewHeight+}++func (m *changesUIModel) initViewports() {+ mainViewWidth, mainViewHeight := m.getMainViewDims()+ m.changeOldViewport = viewport.New(mainViewWidth/2, mainViewHeight)+ m.changeOldViewport.Style = lipgloss.NewStyle().Padding(1)+ m.changeNewViewport = viewport.New(mainViewWidth/2, mainViewHeight)+ m.changeNewViewport.Style = lipgloss.NewStyle().Padding(1)+ m.fileViewport = viewport.New(mainViewWidth, mainViewHeight)+ m.fileViewport.Style = lipgloss.NewStyle().Padding(1)+}++func (m *changesUIModel) updateViewportSizes() {+ mainViewWidth, mainViewHeight := m.getMainViewDims()++ oldViewHeight := mainViewHeight++ if m.selectedViewport == 0 && m.changeOldViewport.TotalLineCount() > m.changeOldViewport.VisibleLineCount() {+ footerHeight := lipgloss.Height(m.renderScrollFooter())+ oldViewHeight -= footerHeight+ }++ newViewHeight := mainViewHeight++ if m.selectedViewport == 1 && m.changeNewViewport.TotalLineCount() > m.changeNewViewport.VisibleLineCount() {+ footerHeight := lipgloss.Height(m.renderScrollFooter())+ newViewHeight -= footerHeight+ }++ fileViewHeight := mainViewHeight++ if m.fileViewport.TotalLineCount() > m.fileViewport.VisibleLineCount() {+ footerHeight := lipgloss.Height(m.renderScrollFooter())+ fileViewHeight -= footerHeight+ }++ m.changeOldViewport.Width = mainViewWidth / 2+ m.changeOldViewport.Height = oldViewHeight+ m.changeNewViewport.Width = mainViewWidth / 2+ m.changeNewViewport.Height = newViewHeight+ m.fileViewport.Width = mainViewWidth+ m.fileViewport.Height = fileViewHeight+}++func (m changesUIModel) renderHelp() string {+ help := ` (β/β) select change β’ (ctrl+a) apply pending β’ (ctrl+d) discard all β’ (q)uit`+ style := lipgloss.NewStyle().Width(m.width).Inherit(topBorderStyle).Foreground(lipgloss.Color(helpTextColor))+ return style.Render(help)+}++func (m changesUIModel) oldScrollable() bool {+ return m.changeOldViewport.TotalLineCount() > m.changeOldViewport.VisibleLineCount()+}++func (m changesUIModel) newScrollable() bool {+ return m.changeNewViewport.TotalLineCount() > m.changeNewViewport.VisibleLineCount()+}++func (m changesUIModel) fileScrollable() bool {+ return m.fileViewport.TotalLineCount() > m.fileViewport.VisibleLineCount()+}diff --git a/cli/cmd/changes.go b/cli/cmd/changes.goindex 2bc1a9e6..adb3010d 100644--- a/cli/cmd/changes.go+++ b/cli/cmd/changes.go@@ -3,7 +3,7 @@ package cmdimport ("fmt""os"- "plandex/lib"+ "plandex/changes_tui""github.com/spf13/cobra")@@ -21,7 +21,7 @@ var changesCmd = &cobra.Command{func changes(cmd *cobra.Command, args []string) {- err := lib.StartChangesUI()+ err := changes_tui.StartChangesUI()if err != nil {fmt.Fprintf(os.Stderr, "Error starting changes UI: %v\n", err)diff --git a/cli/cmd/convo.go b/cli/cmd/convo.goindex a1f889bc..83176fd9 100644--- a/cli/cmd/convo.go+++ b/cli/cmd/convo.go@@ -4,6 +4,7 @@ import ("fmt""os""plandex/lib"+ "plandex/term""strings""time"@@ -72,7 +73,7 @@ func convo(cmd *cobra.Command, args []string) {totalTokens += msg.Tokens}- markdownString, err := lib.GetMarkdown(strings.Join(convMarkdown, "\n"))+ markdownString, err := term.GetMarkdown(strings.Join(convMarkdown, "\n"))if err != nil {fmt.Fprintln(os.Stderr, "Error creating markdown representation:", err)return@@ -80,8 +81,8 @@ func convo(cmd *cobra.Command, args []string) {output :=fmt.Sprintf("\n%s", markdownString) +- lib.GetDivisionLine() ++ term.GetDivisionLine() +color.New(color.Bold, color.FgCyan).Sprint(" Conversation size β") + fmt.Sprintf(" %d πͺ", totalTokens) + "\n\n"- lib.PageOutputReverse(output)+ term.PageOutputReverse(output)}diff --git a/cli/cmd/current.go b/cli/cmd/current.goindex ed78a018..a667f64f 100644--- a/cli/cmd/current.go+++ b/cli/cmd/current.go@@ -5,6 +5,7 @@ import ("os""plandex/format""plandex/lib"+ "plandex/term""strconv""time"@@ -84,6 +85,6 @@ func current(cmd *cobra.Command, args []string) {table.Render()fmt.Println()- lib.PrintCmds("", "tell", "ls", "plans")+ term.PrintCmds("", "tell", "ls", "plans")}diff --git a/cli/cmd/load.go b/cli/cmd/load.goindex a4cb2658..15bc5033 100644--- a/cli/cmd/load.go+++ b/cli/cmd/load.go@@ -2,6 +2,7 @@ package cmdimport ("plandex/lib"+ "plandex/term""plandex/types""github.com/spf13/cobra"@@ -35,5 +36,5 @@ func contextLoad(cmd *cobra.Command, args []string) {NamesOnly: namesOnly,})- lib.PrintCmds("", "ls", "tell")+ term.PrintCmds("", "ls", "tell")}diff --git a/cli/cmd/log.go b/cli/cmd/log.goindex 65ef8e6b..9bebbff3 100644--- a/cli/cmd/log.go+++ b/cli/cmd/log.go@@ -4,6 +4,7 @@ import ("fmt""os""plandex/lib"+ "plandex/term""github.com/spf13/cobra")@@ -45,5 +46,5 @@ func runLog(cmd *cobra.Command, args []string) {return}- lib.PageOutput(history)+ term.PageOutput(history)}diff --git a/cli/cmd/ls.go b/cli/cmd/ls.goindex 804730d6..2e6201a5 100644--- a/cli/cmd/ls.go+++ b/cli/cmd/ls.go@@ -5,6 +5,7 @@ import ("os""plandex/format""plandex/lib"+ "plandex/term""strconv""time"@@ -37,7 +38,7 @@ func context(cmd *cobra.Command, args []string) {if len(context) == 0 {fmt.Println("π€·ββοΈ No context")fmt.Println()- lib.PrintCmds("", "load")+ term.PrintCmds("", "load")return}@@ -84,7 +85,7 @@ func context(cmd *cobra.Command, args []string) {tokensTbl.Render()fmt.Println()- lib.PrintCmds("", "load", "rm", "clear")+ term.PrintCmds("", "load", "rm", "clear")}diff --git a/cli/cmd/new.go b/cli/cmd/new.goindex 371374e6..3de157ce 100644--- a/cli/cmd/new.go+++ b/cli/cmd/new.go@@ -7,6 +7,7 @@ import ("path/filepath""plandex/lib"+ "plandex/term""plandex/types""github.com/fatih/color"@@ -177,6 +178,6 @@ func new(cmd *cobra.Command, args []string) {}fmt.Println()- lib.PrintCmds("", "load", "tell", "plans")+ term.PrintCmds("", "load", "tell", "plans")}diff --git a/cli/cmd/plans.go b/cli/cmd/plans.goindex 1685ff62..4e7105ca 100644--- a/cli/cmd/plans.go+++ b/cli/cmd/plans.go@@ -8,6 +8,7 @@ import ("plandex/format""plandex/lib"+ "plandex/term""github.com/fatih/color""github.com/olekukonko/tablewriter"@@ -40,7 +41,7 @@ func plans(cmd *cobra.Command, args []string) {if len(plans) == 0 {fmt.Println("π€·ββοΈ No plans")fmt.Println()- lib.PrintCmds("", "new")+ term.PrintCmds("", "new")return}@@ -91,5 +92,5 @@ func plans(cmd *cobra.Command, args []string) {}table.Render()fmt.Println()- lib.PrintCmds("", "new", "cd", "delete-plan")+ term.PrintCmds("", "new", "cd", "delete-plan")}diff --git a/cli/cmd/tell.go b/cli/cmd/tell.goindex c8e62a76..37755157 100644--- a/cli/cmd/tell.go+++ b/cli/cmd/tell.go@@ -5,6 +5,7 @@ import ("os""os/exec""plandex/lib"+ "plandex/term""strings""github.com/spf13/cobra"@@ -94,11 +95,11 @@ func tell(cmd *cobra.Command, args []string) {if prompt != "" {fmt.Print("\n\n")- fmt.Print(lib.GetDivisionLine())+ fmt.Print(term.GetDivisionLine())fmt.Print("\n\n")fmt.Println(prompt)fmt.Print("\n\n")- fmt.Print(lib.GetDivisionLine())+ fmt.Print(term.GetDivisionLine())fmt.Print("\n\n")}}diff --git a/cli/go.mod b/cli/go.modindex c88f73c3..e594d55c 100644--- a/cli/go.mod+++ b/cli/go.mod@@ -8,6 +8,7 @@ require (github.com/davecgh/go-spew v1.1.1github.com/fatih/color v1.16.0github.com/looplab/fsm v1.0.1+ github.com/muesli/reflow v0.3.0github.com/olekukonko/tablewriter v0.0.5github.com/plandex-ai/survey/v2 v2.0.0-00010101000000-000000000000github.com/spf13/cobra v1.8.0@@ -33,10 +34,8 @@ require (github.com/mitchellh/go-homedir v1.1.0 // indirectgithub.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirectgithub.com/muesli/cancelreader v0.2.2 // indirect- github.com/muesli/reflow v0.3.0 // indirectgithub.com/muesli/termenv v0.15.2 // indirectgithub.com/rivo/uniseg v0.4.4 // indirect- github.com/sahilm/fuzzy v0.1.0 // indirectgithub.com/yuin/goldmark v1.6.0 // indirectgithub.com/yuin/goldmark-emoji v1.0.2 // indirectgolang.org/x/net v0.18.0 // indirectdiff --git a/cli/go.sum b/cli/go.sumindex 4f6134af..2d8c04bd 100644--- a/cli/go.sum+++ b/cli/go.sum@@ -491,7 +491,6 @@ github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBgithub.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=-github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=github.com/looplab/fsm v1.0.1 h1:OEW0ORrIx095N/6lgoGkFkotqH6s7vaFPsgjLAaF5QU=github.com/looplab/fsm v1.0.1/go.mod h1:PmD3fFvQEIsjMEfvZdrCDZ6y8VwKTwWNjlpEr6IKPO4=@@ -630,7 +629,6 @@ github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tbgithub.com/ryanuber/columnize v2.1.0+incompatible/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts=github.com/sabhiram/go-gitignore v0.0.0-20180611051255-d3107576ba94/go.mod h1:b18R55ulyQ/h3RaWyloPyER7fWQVZvimKKhnI5OfrJQ=github.com/sagikazarmark/crypt v0.8.0/go.mod h1:TmKwZAo97S4Fy4sfMH/HX/cQP5D+ijra2NyLpNNmttY=-github.com/sahilm/fuzzy v0.1.0 h1:FzWGaw2Opqyu+794ZQ9SYifWv2EIXpwP4q8dY1kDAwI=github.com/sahilm/fuzzy v0.1.0/go.mod h1:VFvziUEIMCrT6A6tw2RFIXPXXmzXbOsSHF0DOI8ZK9Y=github.com/sashabaranov/go-openai v1.17.7 h1:MPcAwlwbeo7ZmhQczoOgZBHtIBY1TfZqsdx6+/ndloM=github.com/sashabaranov/go-openai v1.17.7/go.mod h1:lj5b/K+zjTSFxVLijLSTDZuP7adOgerWeFyZLUhAKRg=diff --git a/cli/lib/api_propose.go b/cli/lib/api_propose.goindex ed7a24ae..ae757031 100644--- a/cli/lib/api_propose.go+++ b/cli/lib/api_propose.go@@ -35,14 +35,14 @@ func (api *API) Propose(prompt, parentProposalId, rootId string, onStream types.// Goroutine for loading plan files and contextgo func() {- planFiles, _, modelContext, err := GetCurrentPlanStateWithContext()+ res, err := GetCurrentPlanState()if err != nil {fmt.Println("Error loading plan")errCh <- errreturn}- planFilesCh <- planFiles- contextCh <- modelContext+ planFilesCh <- res.CurrentPlanFiles+ contextCh <- res.ModelContext}()// Goroutine for loading summariesdiff --git a/cli/lib/apply.go b/cli/lib/apply.goindex 7edb1369..159db5d1 100644--- a/cli/lib/apply.go+++ b/cli/lib/apply.go@@ -6,6 +6,7 @@ import ("fmt""os""path/filepath"+ "plandex/term""plandex/types""github.com/fatih/color"@@ -35,12 +36,15 @@ func ApplyPlanWithOutput(name string, autoConfirm bool) error {return fmt.Errorf("error checking if plan exists: %w", err)}- currentPlanFiles, planResByPath, _, err := GetCurrentPlanStateWithContext()+ res, err := GetCurrentPlanState()if err != nil {return fmt.Errorf("error getting current plan files: %w", err)}+ currentPlanFiles := res.CurrentPlanFiles+ planResByPath := res.PlanResByPath+aborted := false// check if any files have been modified since the plan result was generated@@ -196,7 +200,7 @@ func ApplyPlanWithOutput(name string, autoConfirm bool) error {types.PlanOutdatedStrategyCancel,)- choice, err := SelectFromList("π€ How do you want to handle it?", options)+ choice, err := term.SelectFromList("π€ How do you want to handle it?", options)if err != nil {return fmt.Errorf("failed to get user input: %w", err)@@ -260,7 +264,7 @@ func ApplyPlanWithOutput(name string, autoConfirm bool) error {if numToApply > 1 {suffix = "s"}- shouldContinue, err := ConfirmYesNo("Apply changes to %d file%s?", numToApply, suffix)+ shouldContinue, err := term.ConfirmYesNo("Apply changes to %d file%s?", numToApply, suffix)if err != nil {return fmt.Errorf("failed to get confirmation user input: %s", err)diff --git a/cli/lib/changes_ui.go b/cli/lib/changes_ui.godeleted file mode 100644index 0fad5b02..00000000--- a/cli/lib/changes_ui.go+++ /dev/null@@ -1,470 +0,0 @@-package lib--import (- "fmt"- "log"- "os"- "strings"- "time"-- "github.com/charmbracelet/bubbles/help"- bubbleKey "github.com/charmbracelet/bubbles/key"- "github.com/charmbracelet/bubbles/list"- tea "github.com/charmbracelet/bubbletea"- "github.com/charmbracelet/lipgloss"- "github.com/fatih/color"- "github.com/plandex/plandex/shared"-- "github.com/atotto/clipboard"-)--type keymap = struct {- up, down, reject, copy, applyAll, quit bubbleKey.Binding-}--type changesUIModel struct {- mainViewport struct {- fileContent list.Model- oldChange list.Model- newChange list.Model- }- help help.Model- keymap keymap- selectedFileIndex int- selectedReplacementIndex int- resultsInfo *planResultsInfo- currentPlanFiles *shared.CurrentPlanFiles- sidebar list.Model-}--func init() {- // set up a file logger- file, err := os.OpenFile("changes_ui.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)- if err != nil {- log.Fatal(err)- }-- // Set the output of the logger to the file- log.SetOutput(file)-- log.Print("\n\n\nStarting changes UI...\n\n")-}--func StartChangesUI() error {- _, err := tea.NewProgram(initialModel(), tea.WithAltScreen()).Run()-- if err != nil {- return fmt.Errorf("error running changes UI: %v", err)- }-- // fmt.Println("exited changes UI")- // spew.Dump(m)-- return nil-}--func (m changesUIModel) Init() tea.Cmd {- return nil-}--func initialModel() changesUIModel {- errChn := make(chan error, 1)- resultsInfoCh := make(chan *planResultsInfo, 1)- currentPlanFilesCh := make(chan *shared.CurrentPlanFiles, 1)-- var resultsInfo *planResultsInfo- var currentPlanFiles *shared.CurrentPlanFiles-- go func() {- planResByPath, err := getPlanResultsInfo()- if err != nil {- errChn <- fmt.Errorf("error getting plan results: %v", err)- return- }- resultsInfoCh <- planResByPath- }()-- go func() {- var err error- currentPlanFiles, err = GetCurrentPlanFiles()- if err != nil {- errChn <- fmt.Errorf("error getting current plan files: %v", err)- return- }- currentPlanFilesCh <- currentPlanFiles- }()-- for i := 0; i < 2; i++ {- select {- case err := <-errChn:- panic(fmt.Errorf("error getting plan results: %v", err))- case resultsInfo = <-resultsInfoCh:- case currentPlanFiles = <-currentPlanFilesCh:- }- }-- initialState := changesUIModel{- mainViewport: struct {- fileContent list.Model- oldChange list.Model- newChange list.Model- }{- fileContent: list.NewModel([]string{}, nil, false),- oldChange: list.NewModel([]string{}, nil, false),- newChange: list.NewModel([]string{}, nil, false),- },- resultsInfo: resultsInfo,- selectedFileIndex: 0,- selectedReplacementIndex: 0,- help: help.New(),- keymap: keymap{- up: bubbleKey.NewBinding(- bubbleKey.WithKeys("up"),- bubbleKey.WithHelp("up", "prev change"),- ),-- down: bubbleKey.NewBinding(- bubbleKey.WithKeys("down"),- bubbleKey.WithHelp("down", "next change"),- ),-- reject: bubbleKey.NewBinding(- bubbleKey.WithKeys("r"),- bubbleKey.WithHelp("r", "reject change"),- ),-- copy: bubbleKey.NewBinding(- bubbleKey.WithKeys("c"),- bubbleKey.WithHelp("c", "copy change"),- ),-- applyAll: bubbleKey.NewBinding(- bubbleKey.WithKeys("ctrl+a"),- bubbleKey.WithHelp("ctrl+a", "apply all changes"),- ),-- quit: bubbleKey.NewBinding(- bubbleKey.WithKeys("q", "ctrl+c"),- bubbleKey.WithHelp("q", "quit"),- ),- },- }-- return initialState-}--var escPressedAt time.Time-var escSeq string--func (m changesUIModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {- switch msg := msg.(type) {- case tea.KeyMsg:- switch msg.String() {- case "up":- if m.state == viewingChange {- m.mainViewport.oldChange.CursorUp(1)- m.mainViewport.newChange.CursorUp(1)- } else {- m.mainViewport.fileContent.CursorUp(1)- }- case "down":- if m.state == viewingChange {- m.mainViewport.oldChange.CursorDown(1)- m.mainViewport.newChange.CursorDown(1)- } else {- m.mainViewport.fileContent.CursorDown(1)- }- }- }-- selectionInfo := m.getSelectionInfo()- paths := m.resultsInfo.sortedPaths- currentReplacements := selectionInfo.currentReplacements-- log.Printf("msg: %v", msg)-- up := func() {- log.Println("up")- log.Printf("selectedReplacementIndex before: %d", m.selectedReplacementIndex)- log.Printf("selectedFileIndex before: %d", m.selectedFileIndex)- if m.selectedReplacementIndex > 0 {- m.selectedReplacementIndex--- } else if m.selectedFileIndex > 0 {- m.selectedFileIndex--- m.selectedReplacementIndex = len(m.resultsInfo.replacementsByPath[paths[m.selectedFileIndex]]) - 1- }-- log.Printf("selectedReplacementIndex after: %d", m.selectedReplacementIndex)- log.Printf("selectedFileIndex after: %d", m.selectedFileIndex)- }-- down := func() {- log.Println("down")- log.Printf("selectedReplacementIndex before: %d", m.selectedReplacementIndex)- log.Printf("len(currentReplacements)-1: %d", len(currentReplacements)-1)- log.Printf("selectedFileIndex before: %d", m.selectedFileIndex)- log.Printf("len(paths)-1: %d", len(paths)-1)- if m.selectedReplacementIndex < len(currentReplacements)-1 {- m.selectedReplacementIndex++- } else if m.selectedFileIndex < len(paths)-1 {- m.selectedFileIndex++- m.selectedReplacementIndex = 0- }- log.Printf("selectedReplacementIndex after: %d", m.selectedReplacementIndex)- log.Printf("selectedFileIndex after: %d", m.selectedFileIndex)- }-- switch msg := msg.(type) {- case tea.KeyMsg:-- switch {-- case bubbleKey.Matches(msg, m.keymap.up):- up()-- case bubbleKey.Matches(msg, m.keymap.down):- down()-- case bubbleKey.Matches(msg, m.keymap.reject):- m.rejectChange()-- case bubbleKey.Matches(msg, m.keymap.applyAll):- // TODO: need to close the TUI then apply-- case bubbleKey.Matches(msg, m.keymap.copy):- m.copyCurrentChange()-- case bubbleKey.Matches(msg, m.keymap.quit):- return m, tea.Quit-- default:- if msg.String() == "esc" {- // log.Println("esc")- escPressedAt = time.Now()- go func() {- time.Sleep(51 * time.Millisecond)- // log.Println("esc timeout")- escPressedAt = time.Time{}- escSeq = ""- }()- }-- if !escPressedAt.IsZero() {- elapsed := time.Since(escPressedAt)-- // log.Println("elapsed: ", elapsed)-- if elapsed < 50*time.Millisecond {- escSeq += msg.String()-- // log.Println("escSeq: ", escSeq)-- if escSeq == "esc[A" {- up()- escPressedAt = time.Time{}- escSeq = ""- } else if escSeq == "esc[B" {- down()- escPressedAt = time.Time{}- escSeq = ""- }-- return m, nil- }- }-- }- }-- return m, nil-}--func (m changesUIModel) View() string {- help := m.help.ShortHelpView([]bubbleKey.Binding{- m.keymap.up,- m.keymap.down,- m.keymap.applyAll,- m.keymap.quit,- })-- sidebar := m.renderSidebar()- mainView := m.renderMainView()-- layout := lipgloss.JoinHorizontal(lipgloss.Top, sidebar, mainView)-- return lipgloss.JoinVertical(lipgloss.Left,- layout,- help,- )-}--func (m *changesUIModel) renderSidebar() string {- // log.Print("renderSidebar")-- var sb strings.Builder-- selectionInfo := m.getSelectionInfo()- paths := m.resultsInfo.sortedPaths- currentPath := selectionInfo.currentPath- currentRes := selectionInfo.currentRes- currentRep := selectionInfo.currentRep-- // log.Printf("paths: %v", paths)- // log.Printf("currentPath: %v", currentPath)- // log.Printf("currentRes: %v", currentRes)- // log.Printf("currentRep: %v", currentRep)-- for _, path := range paths {- results := m.resultsInfo.resultsByPath[path]- selectedPath := path == currentPath-- selectedFullFile := selectedPath && currentRes == nil-- pathColor := color.FgHiGreen-- anyFailed := false- for _, result := range results {- if result.AnyFailed {- anyFailed = true- break- }- }- if anyFailed {- pathColor = color.FgHiRed- }-- sb.WriteString(color.New(pathColor).Sprint(" π " + path + "\n"))-- // Change entries- for _, result := range results {- for _, rep := range result.Replacements {- selected := selectedPath && rep.Id == currentRep.Id-- s := ""-- labelColor := color.FgHiGreen- if rep.Failed {- labelColor = color.FgHiRed- }-- if selected {- s += color.New(color.Bold).Sprintf(" > ") + color.New(color.Bold, labelColor).Sprint(shortenText(rep.Summary, 50))- } else {- s += color.New(labelColor).Sprintf(" - %s", shortenText(rep.Summary, 50))- }-- if result.RejectedAt != "" {- s += " π«"- }-- s += "\n"-- sb.WriteString(s)- }-- }-- if selectedFullFile {- sb.WriteString(color.New(color.Bold, color.FgHiCyan).Sprint(" > ") + color.New(color.Bold).Sprint("Updated file\n"))- } else {- sb.WriteString(" - Updated file\n")- }- }-- return sb.String()-}--// Helper function to shorten text if necessary-func shortenText(s string, maxLength int) string {- if len(s) <= maxLength {- return s- }- return s[:maxLength-3] + "..."-}--func (m *changesUIModel) renderMainView() string {- selectionInfo := m.getSelectionInfo()-- if selectionInfo.currentRep == nil {- // Show whole file-- } else {- // Show replacement- return fmt.Sprintf(`- Old:-- `+"```"+`- %s- `+"```"+`-- New:-- `+"```"+`- %s- `+"```", selectionInfo.currentRep.Old, selectionInfo.currentRep.New)- }-- return ""-}--func (m *changesUIModel) rejectChange() error {-- return nil-}--func (m *changesUIModel) applyAllChanges() error {-- return nil-}--type selectionInfo struct {- currentPath string- currentRes *shared.PlanResult- currentReplacements []*shared.Replacement- currentRep *shared.Replacement-}--func (m *changesUIModel) getSelectionInfo() selectionInfo {- paths := m.resultsInfo.sortedPaths- currentPath := paths[m.selectedFileIndex]-- results := m.resultsInfo.resultsByPath[currentPath]-- var currentRes *shared.PlanResult- var currentRep *shared.Replacement-- var pathReplacements []*shared.Replacement-- for i, res := range results {- for j, rep := range res.Replacements {- pathReplacements = append(pathReplacements, rep)-- flatIndex := i*len(res.Replacements) + j- if flatIndex == m.selectedReplacementIndex {- currentRes = res- currentRep = rep- }- }- }-- return selectionInfo{- currentPath: currentPath,- currentRes: currentRes,- currentReplacements: pathReplacements,- currentRep: currentRep,- }-}--func (m *changesUIModel) copyCurrentChange() error {- selectionInfo := m.getSelectionInfo()- if selectionInfo.currentRep == nil {- return fmt.Errorf("no change is currently selected")- }-- // Copy the 'New' content of the replacement to the clipboard- if err := clipboard.WriteAll(selectionInfo.currentRep.New); err != nil {- return fmt.Errorf("failed to copy to clipboard: %v", err)- }-- return nil-}diff --git a/cli/lib/context_load.go b/cli/lib/context_load.goindex f0d84c37..c646c558 100644--- a/cli/lib/context_load.go+++ b/cli/lib/context_load.go@@ -10,7 +10,9 @@ import ("os""path/filepath""plandex/format"+ "plandex/term""plandex/types"+ "plandex/url""strings""sync""time"@@ -34,7 +36,7 @@ func MustLoadContext(resources []string, params *types.LoadContextParams) (int,planState, err := GetPlanState()if err != nil {s.Stop()- ClearCurrentLine()+ term.ClearCurrentLine()log.Fatalf("Failed to get plan state: %v", err)}@@ -66,7 +68,7 @@ func MustLoadContext(resources []string, params *types.LoadContextParams) (int,if totalTokens > maxTokens {s.Stop()- ClearCurrentLine()+ term.ClearCurrentLine()log.Fatalf("The total number of tokens (%d) exceeds the maximum allowed (%d)", totalTokens, maxTokens)}}()@@ -77,7 +79,7 @@ func MustLoadContext(resources []string, params *types.LoadContextParams) (int,fileNameResp, err := Api.FileName(body)if err != nil {s.Stop()- ClearCurrentLine()+ term.ClearCurrentLine()log.Fatalf("Failed to get a file name for the text: %v", err)}@@ -106,7 +108,7 @@ func MustLoadContext(resources []string, params *types.LoadContextParams) (int,fileInfo, err := os.Stdin.Stat()if err != nil {s.Stop()- ClearCurrentLine()+ term.ClearCurrentLine()log.Fatalf("Failed to stat stdin: %v", err)}if fileInfo.Mode()&os.ModeNamedPipe != 0 {@@ -114,7 +116,7 @@ func MustLoadContext(resources []string, params *types.LoadContextParams) (int,pipedData, err := io.ReadAll(reader)if err != nil {s.Stop()- ClearCurrentLine()+ term.ClearCurrentLine()log.Fatalf("Failed to read piped data: %v", err)}@@ -137,7 +139,7 @@ func MustLoadContext(resources []string, params *types.LoadContextParams) (int,tokensAdded += numTokensif totalTokens > maxTokens {s.Stop()- ClearCurrentLine()+ term.ClearCurrentLine()log.Fatalf("The total number of tokens (%d) exceeds the maximum allowed (%d)", totalTokens, maxTokens)}}()@@ -148,7 +150,7 @@ func MustLoadContext(resources []string, params *types.LoadContextParams) (int,fileNameResp, err := Api.FileName(body)if err != nil {s.Stop()- ClearCurrentLine()+ term.ClearCurrentLine()log.Fatalf("Failed to get a file name for piped data: %v", err)}@@ -179,7 +181,7 @@ func MustLoadContext(resources []string, params *types.LoadContextParams) (int,if len(resources) > 0 {for _, resource := range resources {// so far resources are either files or urls- if IsValidURL(resource) {+ if url.IsValidURL(resource) {inputUrls = append(inputUrls, resource)} else {inputFilePaths = append(inputFilePaths, resource)@@ -198,7 +200,7 @@ func MustLoadContext(resources []string, params *types.LoadContextParams) (int,flattenedPaths, err := ParseInputPaths([]string{inputFilePath}, params)if err != nil {s.Stop()- ClearCurrentLine()+ term.ClearCurrentLine()log.Fatalf("Failed to parse input paths: %v", err)}@@ -217,7 +219,7 @@ func MustLoadContext(resources []string, params *types.LoadContextParams) (int,tokensAdded += numTokensif totalTokens > maxTokens {s.Stop()- ClearCurrentLine()+ term.ClearCurrentLine()log.Fatalf("The total number of tokens (%d) exceeds the maximum allowed (%d)", totalTokens, maxTokens)}@@ -256,7 +258,7 @@ func MustLoadContext(resources []string, params *types.LoadContextParams) (int,flattenedPaths, err := ParseInputPaths(inputFilePaths, params)if err != nil {s.Stop()- ClearCurrentLine()+ term.ClearCurrentLine()log.Fatalf("Failed to parse input paths: %v", err)}@@ -269,7 +271,7 @@ func MustLoadContext(resources []string, params *types.LoadContextParams) (int,fileContent, err := os.ReadFile(path)if err != nil {s.Stop()- ClearCurrentLine()+ term.ClearCurrentLine()log.Fatalf("Failed to read the file %s: %v", path, err)}@@ -286,7 +288,7 @@ func MustLoadContext(resources []string, params *types.LoadContextParams) (int,totalUpdatableTokens += numTokensif totalTokens > maxTokens {s.Stop()- ClearCurrentLine()+ term.ClearCurrentLine()log.Fatalf("The total number of tokens (%d) exceeds the maximum allowed (%d)", totalTokens, maxTokens)}@@ -317,17 +319,17 @@ func MustLoadContext(resources []string, params *types.LoadContextParams) (int,}if len(inputUrls) > 0 {- for _, url := range inputUrls {+ for _, u := range inputUrls {wg.Add(1)- go func(url string) {+ go func(u string) {defer wg.Done()- body, err := FetchURLContent(url)+ body, err := url.FetchURLContent(u)if err != nil {s.Stop()- ClearCurrentLine()- log.Fatalf("Failed to fetch content from URL %s: %v", url, err)+ term.ClearCurrentLine()+ log.Fatalf("Failed to fetch content from URL %s: %v", u, err)}numTokens := shared.GetNumTokens(body)@@ -340,7 +342,7 @@ func MustLoadContext(resources []string, params *types.LoadContextParams) (int,totalUpdatableTokens += numTokensif totalTokens > maxTokens {s.Stop()- ClearCurrentLine()+ term.ClearCurrentLine()log.Fatalf("The total number of tokens (%d) exceeds the maximum allowed (%d)", totalTokens, maxTokens)}}()@@ -350,7 +352,7 @@ func MustLoadContext(resources []string, params *types.LoadContextParams) (int,ts := shared.StringTs()- name := SanitizeURL(url)+ name := url.SanitizeURL(u)// show the first 20 characters, then ellipsis then the last 20 characters of 'name'if len(name) > 40 {name = name[:20] + "β―" + name[len(name)-20:]@@ -359,7 +361,7 @@ func MustLoadContext(resources []string, params *types.LoadContextParams) (int,contextPart := &shared.ModelContextPart{Type: shared.ContextURLType,Name: name,- Url: url,+ Url: u,Body: body,Sha: sha,NumTokens: numTokens,@@ -370,7 +372,7 @@ func MustLoadContext(resources []string, params *types.LoadContextParams) (int,contextPartsMutex.Lock()contextParts = append(contextParts, contextPart)contextPartsMutex.Unlock()- }(url)+ }(u)}}@@ -472,13 +474,13 @@ func MustLoadContext(resources []string, params *types.LoadContextParams) (int,if err != nil {s.Stop()- ClearCurrentLine()+ term.ClearCurrentLine()log.Fatalf("Failed to get total tokens: %v", err)}if err != nil {s.Stop()- ClearCurrentLine()+ term.ClearCurrentLine()log.Fatalf("Failed to commit context update to git: %v", err)}@@ -488,7 +490,7 @@ func MustLoadContext(resources []string, params *types.LoadContextParams) (int,}s.Stop()- ClearCurrentLine()+ term.ClearCurrentLine()fmt.Println("β " + msg)if len(contextParts) > 0 {@@ -497,7 +499,7 @@ func MustLoadContext(resources []string, params *types.LoadContextParams) (int,err = GitCommitContextUpdate(msg + "\n\n" + tableString)if err != nil {s.Stop()- ClearCurrentLine()+ term.ClearCurrentLine()log.Fatalf("Failed to commit context update to git: %v", err)}fmt.Println(tableString)diff --git a/cli/lib/context_update.go b/cli/lib/context_update.goindex 2e9a9e32..f70e72b3 100644--- a/cli/lib/context_update.go+++ b/cli/lib/context_update.go@@ -6,7 +6,9 @@ import ("fmt""math""os"+ "plandex/term""plandex/types"+ "plandex/url""strconv""strings""sync"@@ -46,7 +48,7 @@ func MustUpdateContextWithOuput() *updateRes {time.Sleep(700*time.Millisecond - elapsed)}s.Stop()- ClearCurrentLine()+ term.ClearCurrentLine()}updateRes, err := UpdateContext()@@ -297,7 +299,7 @@ func checkOutdatedAndMaybeUpdateContext(doUpdate bool) (*updateRes, error) {wg.Add(1)go func(part *shared.ModelContextPart) {defer wg.Done()- body, err := FetchURLContent(part.Url)+ body, err := url.FetchURLContent(part.Url)if err != nil {errCh <- fmt.Errorf("failed to fetch the URL %s: %v", part.Url, err)returndiff --git a/cli/lib/plan_files.go b/cli/lib/current_plan.gosimilarity index 68%rename from cli/lib/plan_files.gorename to cli/lib/current_plan.goindex 8fb1dcb8..980db88f 100644--- a/cli/lib/plan_files.go+++ b/cli/lib/current_plan.go@@ -5,19 +5,27 @@ import ("fmt""os""path/filepath"+ "plandex/types""sort""github.com/plandex/plandex/shared")func GetCurrentPlanFiles() (*shared.CurrentPlanFiles, error) {- currentPlanFiles, _, _, err := GetCurrentPlanStateWithContext()- return currentPlanFiles, err+ res, err := GetCurrentPlanState()+ if err != nil {+ return nil, err+ }+ return res.CurrentPlanFiles, err+}++func GetCurrentPlanState() (*types.CurrentPlanState, error) {+ return GetCurrentPlanStateBeforeReplacement("")}-func GetCurrentPlanStateWithContext() (*shared.CurrentPlanFiles, shared.PlanResultsByPath, shared.ModelContext, error) {+func GetCurrentPlanStateBeforeReplacement(id string) (*types.CurrentPlanState, error) {errCh := make(chan error, 1)- planResByPathCh := make(chan shared.PlanResultsByPath, 1)+ planResInfoCh := make(chan *types.PlanResultsInfo, 1)contextCh := make(chan shared.ModelContext, 1)go func() {@@ -30,22 +38,22 @@ func GetCurrentPlanStateWithContext() (*shared.CurrentPlanFiles, shared.PlanResu}()go func() {- planResInfo, err := getPlanResultsInfo()+ planResInfo, err := GetPlanResultsInfo()if err != nil {errCh <- fmt.Errorf("error getting plan results: %v", err)return}- planResByPathCh <- planResInfo.resultsByPath+ planResInfoCh <- planResInfo}()- var planResByPath shared.PlanResultsByPath+ var planResInfo *types.PlanResultsInfovar modelContext shared.ModelContextfor i := 0; i < 2; i++ {select {case err := <-errCh:- return nil, nil, nil, err- case planResByPath = <-planResByPathCh:+ return nil, err+ case planResInfo = <-planResInfoCh:case modelContext = <-contextCh:}}@@ -60,7 +68,7 @@ func GetCurrentPlanStateWithContext() (*shared.CurrentPlanFiles, shared.PlanResu// fmt.Printf("contextPart: %s\n", contextPart.FilePath)- _, hasPath := planResByPath[contextPart.FilePath]+ _, hasPath := planResInfo.PlanResByPath[contextPart.FilePath]// fmt.Printf("hasPath: %v\n", hasPath)@@ -70,12 +78,13 @@ func GetCurrentPlanStateWithContext() (*shared.CurrentPlanFiles, shared.PlanResu}}- for path, planResults := range planResByPath {+ for path, planResults := range planResInfo.PlanResByPath {updated := files[path]// fmt.Printf("path: %s\n", path)// fmt.Printf("updated: %s\n", updated)+ PlanResLoop:for _, planRes := range planResults {if !planRes.IsPending() {continue@@ -83,7 +92,7 @@ func GetCurrentPlanStateWithContext() (*shared.CurrentPlanFiles, shared.PlanResuif len(planRes.Replacements) == 0 {if updated != "" {- return nil, nil, nil, fmt.Errorf("plan updates out of order: %s", path)+ return nil, fmt.Errorf("plan updates out of order: %s", path)}updated = planRes.Content@@ -94,26 +103,38 @@ func GetCurrentPlanStateWithContext() (*shared.CurrentPlanFiles, shared.PlanResucontextSha := shas[path]if contextSha != "" && planRes.ContextSha != contextSha {- return nil, nil, nil, fmt.Errorf("result sha doesn't match context sha: %s", path)+ return nil, fmt.Errorf("result sha doesn't match context sha: %s", path)}if len(planRes.Replacements) == 0 {continue}+ replacements := []*shared.Replacement{}+ for _, replacement := range planRes.Replacements {+ if replacement.Id == id {+ break PlanResLoop+ }+ replacements = append(replacements, replacement)+ }+var allSucceeded bool- updated, allSucceeded = shared.ApplyReplacements(updated, planRes.Replacements, false)+ updated, allSucceeded = shared.ApplyReplacements(updated, replacements, false)if !allSucceeded {-- return nil, nil, nil, fmt.Errorf("plan replacement failed: %s", path)+ return nil, fmt.Errorf("plan replacement failed: %s", path)}}files[path] = updated}- return &shared.CurrentPlanFiles{Files: files, ContextShas: shas}, planResByPath, modelContext, nil+ return &types.CurrentPlanState{+ CurrentPlanFiles: &shared.CurrentPlanFiles{Files: files, ContextShas: shas},+ ModelContext: modelContext,+ ContextByPath: modelContext.ByPath(),+ PlanResultsInfo: *planResInfo,+ }, nil}func SetPendingResultsApplied(planResByPath shared.PlanResultsByPath) error {@@ -161,13 +182,7 @@ func SetPendingResultsApplied(planResByPath shared.PlanResultsByPath) error {return nil}-type planResultsInfo struct {- resultsByPath shared.PlanResultsByPath- sortedPaths []string- replacementsByPath map[string][]*shared.Replacement-}--func getPlanResultsInfo() (*planResultsInfo, error) {+func GetPlanResultsInfo() (*types.PlanResultsInfo, error) {resByPath := make(shared.PlanResultsByPath)replacementsByPath := make(map[string][]*shared.Replacement)var paths []string@@ -199,8 +214,15 @@ func getPlanResultsInfo() (*planResultsInfo, error) {return fmt.Errorf("error unmarshalling plan result JSON from file %s: %v", path, err)}- resByPath[planRes.Path] = append(resByPath[planRes.Path], &planRes)- paths = append(paths, planRes.Path)+ if planRes.IsPending() {+ _, hasPath := resByPath[planRes.Path]++ resByPath[planRes.Path] = append(resByPath[planRes.Path], &planRes)++ if !hasPath {+ paths = append(paths, planRes.Path)+ }+ }return nil})@@ -225,9 +247,9 @@ func getPlanResultsInfo() (*planResultsInfo, error) {return paths[i] < paths[j]})- return &planResultsInfo{- resultsByPath: resByPath,- sortedPaths: paths,- replacementsByPath: replacementsByPath,+ return &types.PlanResultsInfo{+ PlanResByPath: resByPath,+ SortedPaths: paths,+ ReplacementsByPath: replacementsByPath,}, nil}diff --git a/cli/lib/proposal.go b/cli/lib/proposal.goindex 6860ef44..974539c0 100644--- a/cli/lib/proposal.go+++ b/cli/lib/proposal.go@@ -7,9 +7,11 @@ import ("os""path/filepath""plandex/format"+ "plandex/term""plandex/types""strconv""strings"+ "sync""time""github.com/fatih/color"@@ -84,6 +86,7 @@ func Propose(prompt string) error {var filesFinished boolvar lastReplyTokenAdded time.TimefinishedByPath := make(map[string]bool)+ var buildMu sync.MutexnumStreamedTokensByPath := make(map[string]int)@@ -124,9 +127,9 @@ func Propose(prompt string) error {}printReply := func() {- ClearScreen()- MoveCursorToTopLeft()- mdFull, _ := GetMarkdown(reply)+ term.ClearScreen()+ term.MoveCursorToTopLeft()+ mdFull, _ := term.GetMarkdown(reply)fmt.Println(mdFull)fmt.Println(displayHotkeys())termState = mdFull@@ -151,7 +154,7 @@ func Propose(prompt string) error {endReply := func() {replyUpdateTimer.Stop()printReply()- BackToMain()+ term.BackToMain()fmt.Print(termState)}@@ -178,8 +181,9 @@ func Propose(prompt string) error {}// Clear previous lines+ numLines := len(files) + 4- MoveUpLines(len(files) + 4)+ term.MoveUpLines(numLines)for _, filePath := range files {numStreamedTokens := numStreamedTokensByPath[filePath]@@ -193,7 +197,7 @@ func Propose(prompt string) error {fmtStr += " | done β "}- ClearCurrentLine()+ term.ClearCurrentLine()fmt.Printf(fmtStr+"\n", fmtArgs...)}@@ -235,7 +239,7 @@ func Propose(prompt string) error {content := params.ContentonError := func(err error) {- BackToMain()+ term.BackToMain()fmt.Fprintln(os.Stderr, "Error:", err)cancelKeywatch()if !closedDone {@@ -276,8 +280,8 @@ func Propose(prompt string) error {}s.Stop()- ClearCurrentLine()- alternateScreen()+ term.ClearCurrentLine()+ term.AlternateScreen()replyStarted = truelastReplyTokenAdded = time.Now()@@ -298,13 +302,12 @@ func Propose(prompt string) error {case shared.STATE_FINISHED:s.Stop()+ buildMu.Lock()+ defer buildMu.Unlock()streamFinished = true-- if filesFinished {- if !closedDone {- close(done)- closedDone = true- }+ if filesFinished && !closedDone {+ close(done)+ closedDone = truewriteFileProgress()}@@ -404,6 +407,8 @@ func Propose(prompt string) error {// fmt.Printf("Wrote %d / %d files", len(finishedByPath), len(files))if len(finishedByPath) == len(desc.Files) {+ buildMu.Lock()+ defer buildMu.Unlock()filesFinished = trueerr = GitCommitPlanUpdate(desc.CommitMsg)@@ -412,11 +417,9 @@ func Propose(prompt string) error {return}- if streamFinished {- if !closedDone {- close(done)- closedDone = true- }+ if streamFinished && !closedDone {+ close(done)+ closedDone = truewriteFileProgress()}}@@ -426,7 +429,7 @@ func Propose(prompt string) error {apiReq, err = Api.Propose(prompt, parentProposalId, rootId, handleStream)if err != nil {- BackToMain()+ term.BackToMain()return fmt.Errorf("failed to send prompt to server: %s", err)}@@ -444,7 +447,7 @@ func Propose(prompt string) error {case <-ctx.Done():returndefault:- k, err := GetUserInput()+ k, err := term.GetUserInput()if err != nil {errChn <- errreturn@@ -481,19 +484,19 @@ Loop:if desc.MadePlan && len(desc.Files) > 0 {fmt.Println()for _, cmd := range []string{"apply", "diffs", "preview"} {- ClearCurrentLine()- PrintCmds(" ", cmd)+ term.ClearCurrentLine()+ term.PrintCmds(" ", cmd)}}- ClearCurrentLine()- PrintCustomCmd(" ", "tell", "t", "update the plan, give more info, or chat")+ term.ClearCurrentLine()+ term.PrintCustomCmd(" ", "tell", "t", "update the plan, give more info, or chat")- ClearCurrentLine()- PrintCmds(" ", "continue")+ term.ClearCurrentLine()+ term.PrintCmds(" ", "continue")- ClearCurrentLine()- PrintCmds(" ", "rewind")+ term.ClearCurrentLine()+ term.PrintCmds(" ", "rewind")}// fmt.Println("Finished proposal")@@ -513,7 +516,7 @@ func checkOutdatedContext(s *spinner.Spinner) (bool, error) {stopSpinner := func() {s.Stop()- ClearCurrentLine()+ term.ClearCurrentLine()}outdatedRes, err := CheckOutdatedContext()@@ -583,7 +586,7 @@ func checkOutdatedContext(s *spinner.Spinner) (bool, error) {fmt.Println()- confirmed, canceled, err := ConfirmYesNoCancel("Update context now?")+ confirmed, canceled, err := term.ConfirmYesNoCancel("Update context now?")if err != nil {return false, fmt.Errorf("failed to get user input: %s", err)@@ -597,3 +600,24 @@ func checkOutdatedContext(s *spinner.Spinner) (bool, error) {return shouldContinue, nil}++func handleAbortKey(proposalId string) error {+ return Abort(proposalId)+}++func handleKeyPress(input rune, proposalId string) error {+ switch input {+ case 's':+ return handleAbortKey(proposalId)+ default:+ return fmt.Errorf("invalid key pressed: %s", string(input))+ }+}++func displayHotkeys() string {+ divisionLine := term.GetDivisionLine()++ return divisionLine + "\n" ++ " \x1b[1m(s)\x1b[0m" + `top+` + divisionLine+}diff --git a/cli/lib/utils.go b/cli/lib/utils.godeleted file mode 100644index aed0d838..00000000--- a/cli/lib/utils.go+++ /dev/null@@ -1,48 +0,0 @@-package lib--import (- "regexp"- "strconv"- "time"-)--func EnsureMinDuration(start time.Time, minDuration time.Duration) {- elapsed := time.Since(start)- if elapsed < minDuration {- time.Sleep(minDuration - elapsed)- }-}--func cleanJsonFragment(s string) string {- // replace escaped quotes with unescaped quotes- s = regexp.MustCompile(`\\\"`).ReplaceAllString(s, `"`)-- // replace escaped backslashes with unescaped backslashes- s = regexp.MustCompile(`\\\\`).ReplaceAllString(s, `\`)-- // replace escaped newlines with unescaped newlines- s = regexp.MustCompile(`\\n`).ReplaceAllString(s, "\n")-- // replace escaped tabs with unescaped tabs- s = regexp.MustCompile(`\\t`).ReplaceAllString(s, "\t")-- // replace escaped carriage returns with unescaped carriage returns- s = regexp.MustCompile(`\\r`).ReplaceAllString(s, "\r")-- // replace escaped backspaces with unescaped backspaces- s = regexp.MustCompile(`\\b`).ReplaceAllString(s, "\b")-- // replace escaped form feeds with unescaped form feeds- s = regexp.MustCompile(`\\f`).ReplaceAllString(s, "\f")-- // replace escaped forward slashes with unescaped forward slashes- s = regexp.MustCompile(`\\\/`).ReplaceAllString(s, "/")-- // replace escaped unicode characters with unescaped unicode characters- s = regexp.MustCompile(`\\u([0-9a-fA-F]{4})`).ReplaceAllStringFunc(s, func(match string) string {- unicode, _ := strconv.ParseInt(match[2:], 16, 32)- return string(rune(unicode))- })-- return s-}diff --git a/cli/lib/glow.go b/cli/term/glow.gosimilarity index 96%rename from cli/lib/glow.gorename to cli/term/glow.goindex ec9bd14f..76c18be2 100644--- a/cli/lib/glow.go+++ b/cli/term/glow.go@@ -1,4 +1,4 @@-package lib+package termimport ("github.com/charmbracelet/glamour"diff --git a/cli/lib/select.go b/cli/term/select.gosimilarity index 97%rename from cli/lib/select.gorename to cli/term/select.goindex 51e45e3a..c171b014 100644--- a/cli/lib/select.go+++ b/cli/term/select.go@@ -1,4 +1,4 @@-package lib+package termimport ("fmt"diff --git a/cli/lib/term.go b/cli/term/term.gosimilarity index 91%rename from cli/lib/term.gorename to cli/term/term.goindex 7feedebc..431508bf 100644--- a/cli/lib/term.go+++ b/cli/term/term.go@@ -1,4 +1,4 @@-package lib+package termimport ("fmt"@@ -57,7 +57,7 @@ func PrintCustomCmd(prefix, cmd, alias, desc string) {fmt.Printf("%s%s π %s\n", prefix, styled, desc)}-func alternateScreen() {+func AlternateScreen() {// Switch to alternate screen and hide the cursorfmt.Print("\x1b[?1049h\x1b[?25l")}@@ -179,19 +179,6 @@ func GetDivisionLine() string {return strings.Repeat("β", terminalWidth)}-func handleAbortKey(proposalId string) error {- return Abort(proposalId)-}--func handleKeyPress(input rune, proposalId string) error {- switch input {- case 's':- return handleAbortKey(proposalId)- default:- return fmt.Errorf("invalid key pressed: %s", string(input))- }-}-func getTerminalWidth() (int, error) {width, _, err := term.GetSize(int(os.Stdout.Fd()))if err != nil {@@ -199,11 +186,3 @@ func getTerminalWidth() (int, error) {}return width, nil}--func displayHotkeys() string {- divisionLine := GetDivisionLine()-- return divisionLine + "\n" +- " \x1b[1m(s)\x1b[0m" + `top-` + divisionLine-}diff --git a/cli/types/types.go b/cli/types/types.goindex d79e6f14..2f148795 100644--- a/cli/types/types.go+++ b/cli/types/types.go@@ -73,3 +73,16 @@ const (PlanOutdatedStrategyRebuild string = "Rebuild the plan with updated context"PlanOutdatedStrategyCancel string = "Cancel")++type PlanResultsInfo struct {+ SortedPaths []string+ PlanResByPath shared.PlanResultsByPath+ ReplacementsByPath map[string][]*shared.Replacement+}++type CurrentPlanState struct {+ PlanResultsInfo+ CurrentPlanFiles *shared.CurrentPlanFiles+ ModelContext shared.ModelContext+ ContextByPath map[string]*shared.ModelContextPart+}diff --git a/cli/lib/url.go b/cli/url/url.gosimilarity index 99%rename from cli/lib/url.gorename to cli/url/url.goindex 473b63a3..8b001248 100644--- a/cli/lib/url.go+++ b/cli/url/url.go@@ -1,4 +1,4 @@-package lib+package urlimport ("errors"diff --git a/cli/utils/utils.go b/cli/utils/utils.gonew file mode 100644index 00000000..346500bb--- /dev/null+++ b/cli/utils/utils.go@@ -0,0 +1,12 @@+package utils++import (+ "time"+)++func EnsureMinDuration(start time.Time, minDuration time.Duration) {+ elapsed := time.Since(start)+ if elapsed < minDuration {+ time.Sleep(minDuration - elapsed)+ }+}diff --git a/server/model/openai_models.go b/server/model/openai_models.goindex 7e2abb00..116d4fd3 100644--- a/server/model/openai_models.go+++ b/server/model/openai_models.go@@ -6,13 +6,13 @@ import ("github.com/sashabaranov/go-openai")-const strongModel = openai.GPT4 //openai.GPT4TurboPreview+const strongModel = openai.GPT4const mediumModel = openai.GPT4TurboPreviewconst weakModel = openai.GPT3Dot5Turbo1106var PlannerModel = strongModel-var PlanSummaryModel = mediumModel //strongModel-var BuilderModel = strongModel //openai.GPT4+var PlanSummaryModel = mediumModel+var BuilderModel = mediumModelvar ShortSummaryModel = weakModelvar NameModel = weakModelvar CommitMsgModel = weakModeldiff --git a/server/model/prompts/create.go b/server/model/prompts/create.goindex 712e8c11..b92b8743 100644--- a/server/model/prompts/create.go+++ b/server/model/prompts/create.go@@ -25,7 +25,7 @@ const SysCreate = Identity + ` A plan is a set of files with an attached context2. Decide whether this task is small enough to be completed in a single response.a. If so, write out the code to complete the task. Include only lines that will change and lines that are necessary to know where the changes should be applied. Precede the code block with the file path like this '- file_path:'--for example:- src/main.rs:- - lib/utils.go:+ - lib/term.go:- main.py:File paths should always come *before* the opening triple backticks of a code block. They should *not* be included in the code block itself.File paths should appear *immediately* before the opening triple backticks of a code block. There should be *no other lines* between the file path and the code block. Any explanations should come either *before the file path or after the code block.*@@ -37,7 +37,7 @@ const SysCreate = Identity + ` A plan is a set of files with an attached contextIf code is being included for explanatory purposes and is not meant to be applied to a specific file, you MUST NOT label the code block in the format described in 2a. Instead, output the code without a label.- Every file you reference in a plan should either exist in the context directly or be a new file that will be created in the same base directory a file in the context. For example, if there is a file in context at path 'lib/utils.go', you can create a new file at path 'lib/utils_test.go' but *not* at path 'src/lib/utils.go'.+ Every file you reference in a plan should either exist in the context directly or be a new file that will be created in the same base directory a file in the context. For example, if there is a file in context at path 'lib/term.go', you can create a new file at path 'lib/utils_test.go' but *not* at path 'src/lib/term.go'.For code in markdown blocks, always include the language name after the opening triple backticks.diff --git a/shared/model_context.go b/shared/model_context.gonew file mode 100644index 00000000..be995458--- /dev/null+++ b/shared/model_context.go@@ -0,0 +1,34 @@+package shared++type ModelContextPartType string++const (+ ContextFileType ModelContextPartType = "file"+ ContextURLType ModelContextPartType = "url"+ ContextNoteType ModelContextPartType = "note"+ ContextDirectoryTreeType ModelContextPartType = "directory tree"+ ContextPipedDataType ModelContextPartType = "piped data"+)++type ModelContextPart struct {+ Type ModelContextPartType `json:"type"`+ Name string `json:"name"`+ Body string `json:"body"`+ Url string `json:"url"`+ FilePath string `json:"filePath"`+ Sha string `json:"sha"`+ NumTokens int `json:"numTokens"`+ AddedAt string `json:"addedAt"`+ UpdatedAt string `json:"updatedAt"`+}+type ModelContext []*ModelContextPart++func (c ModelContext) ByPath() map[string]*ModelContextPart {+ byPath := make(map[string]*ModelContextPart)+ for _, part := range c {+ if part.FilePath != "" {+ byPath[part.FilePath] = part+ }+ }+ return byPath+}diff --git a/shared/replace.go b/shared/replace.goindex 139ef16a..9e2d474c 100644--- a/shared/replace.go+++ b/shared/replace.go@@ -1,6 +1,8 @@package shared-import "strings"+import (+ "strings"+)type Replacement struct {Id string `json:"id"`@@ -28,6 +30,12 @@ func ApplyReplacements(content string, replacements []*Replacement, setFailed boif setFailed {replacement.Failed = true}++ // jsonBytes, _ := json.Marshal(replacement)+ // log.Println(string(jsonBytes))++ // log.Println("Replacement: " + replacement.Old + " -> " + replacement.New)+} else {replaced := strings.Replace(sub, replacement.Old, replacement.New, 1)diff --git a/shared/types.go b/shared/types.goindex 3856df9f..b1e9bc10 100644--- a/shared/types.go+++ b/shared/types.go@@ -46,29 +46,6 @@ type BuildRequest struct {ProposalIds []string `json:"proposalIds"`}-type ModelContextPartType string--const (- ContextFileType ModelContextPartType = "file"- ContextURLType ModelContextPartType = "url"- ContextNoteType ModelContextPartType = "note"- ContextDirectoryTreeType ModelContextPartType = "directory tree"- ContextPipedDataType ModelContextPartType = "piped data"-)--type ModelContextPart struct {- Type ModelContextPartType `json:"type"`- Name string `json:"name"`- Body string `json:"body"`- Url string `json:"url"`- FilePath string `json:"filePath"`- Sha string `json:"sha"`- NumTokens int `json:"numTokens"`- AddedAt string `json:"addedAt"`- UpdatedAt string `json:"updatedAt"`-}-type ModelContext []*ModelContextPart-type PlanTokenCount struct {Path string `json:"path"`NumTokens int `json:"numTokens"`