Skip to content

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

Improve model streaming stability and performance by adding retry logic for stream errors, optimizing prompt handling, refactoring stream state management with mutex locks, enhancing error handling in the CLI and server components, adjusting model role configurations to better handle large outputs, and fixing various UI and UX issues including better handling of terminal dimensions and styling.

Dane Schneider1cfa6b58fc98
diff --git a/app/cli/api/stream.go b/app/cli/api/stream.go
index 0119c89c..8a0dde71 100644
--- a/app/cli/api/stream.go
+++ b/app/cli/api/stream.go
@@ -33,7 +33,7 @@ func connectPlanRespStream(body io.ReadCloser, onStream types.OnStreamPlan) {
return
}
- // log.Println("Received message:", msg)
+ // log.Println("connectPlanRespStream: received message:", msg)
onStream(types.OnStreamPlanParams{Msg: &msg, Err: nil})
diff --git a/app/cli/cmd/diffs.go b/app/cli/cmd/diffs.go
index 6a05aec7..f3ad7caf 100644
--- a/app/cli/cmd/diffs.go
+++ b/app/cli/cmd/diffs.go
@@ -118,7 +118,10 @@ func diffs(cmd *cobra.Command, args []string) {
} else {
term.PageOutput(diffs)
}
+ fmt.Println()
}
+
+ term.PrintCmds("", "apply", "reject")
}
var htmlTemplate = `<!doctype html>
diff --git a/app/cli/cmd/repl.go b/app/cli/cmd/repl.go
index b9ecfe89..eea63f51 100644
--- a/app/cli/cmd/repl.go
+++ b/app/cli/cmd/repl.go
@@ -172,6 +172,16 @@ func getSuggestions() []prompt.Suggest {
}
suggestions = append(suggestions, prompt.Suggest{Text: "\\load " + loadArgs})
+ if isDir {
+ loadArgs = path
+ loadArgs += " --map"
+ suggestions = append(suggestions, prompt.Suggest{Text: "\\load " + loadArgs})
+
+ loadArgs = path
+ loadArgs += " --tree"
+ suggestions = append(suggestions, prompt.Suggest{Text: "\\load " + loadArgs})
+ }
+
if filepath.Ext(path) == ".md" || filepath.Ext(path) == ".txt" {
suggestions = append(suggestions, prompt.Suggest{Text: "\\run " + path})
}
@@ -582,6 +592,52 @@ func completer(in prompt.Document) ([]prompt.Suggest, pstrings.RuneNumber, pstri
fuzzySuggestions := prompt.FilterFuzzy(getSuggestions(), w, true)
prefixMatches := prompt.FilterHasPrefix(getSuggestions(), w, true)
+ runFilteredFuzzy := []prompt.Suggest{}
+ runFilteredPrefixMatches := []prompt.Suggest{}
+ for _, s := range fuzzySuggestions {
+ if strings.HasPrefix(s.Text, "\\run ") {
+ if wCmd == "run" {
+ runFilteredFuzzy = append(runFilteredFuzzy, s)
+ }
+ } else {
+ runFilteredFuzzy = append(runFilteredFuzzy, s)
+ }
+ }
+ for _, s := range prefixMatches {
+ if strings.HasPrefix(s.Text, "\\run ") {
+ if wCmd == "run" {
+ runFilteredPrefixMatches = append(runFilteredPrefixMatches, s)
+ }
+ } else {
+ runFilteredPrefixMatches = append(runFilteredPrefixMatches, s)
+ }
+ }
+ fuzzySuggestions = runFilteredFuzzy
+ prefixMatches = runFilteredPrefixMatches
+
+ loadFilteredFuzzy := []prompt.Suggest{}
+ loadFilteredPrefixMatches := []prompt.Suggest{}
+ for _, s := range fuzzySuggestions {
+ if strings.HasPrefix(s.Text, "\\load ") {
+ if wCmd == "load" {
+ loadFilteredFuzzy = append(loadFilteredFuzzy, s)
+ }
+ } else {
+ loadFilteredFuzzy = append(loadFilteredFuzzy, s)
+ }
+ }
+ for _, s := range prefixMatches {
+ if strings.HasPrefix(s.Text, "\\load ") {
+ if wCmd == "load" {
+ loadFilteredPrefixMatches = append(loadFilteredPrefixMatches, s)
+ }
+ } else {
+ loadFilteredPrefixMatches = append(loadFilteredPrefixMatches, s)
+ }
+ }
+ fuzzySuggestions = loadFilteredFuzzy
+ prefixMatches = loadFilteredPrefixMatches
+
if strings.TrimSpace(w) != "\\" {
sort.Slice(prefixMatches, func(i, j int) bool {
iTxt := prefixMatches[i].Text
diff --git a/app/cli/cmd/rewind.go b/app/cli/cmd/rewind.go
index 667413d3..165f0aea 100644
--- a/app/cli/cmd/rewind.go
+++ b/app/cli/cmd/rewind.go
@@ -6,27 +6,26 @@ import (
"plandex/auth"
"plandex/lib"
"plandex/term"
+ "regexp"
"strconv"
+ "strings"
"github.com/plandex/plandex/shared"
"github.com/spf13/cobra"
)
-// rewindCmd represents the rewind command
var rewindCmd = &cobra.Command{
Use: "rewind [steps-or-sha]",
Aliases: []string{"rw"},
Short: "Rewind the plan to an earlier state",
Long: `Rewind the plan to an earlier state.
- You can pass a "steps" number or a commit sha. If a steps number is passed, the plan will be rewound that many steps. If a commit sha is passed, the plan will be rewound to that commit. If neither a steps number nor a commit sha is passed, the target scope will be rewound by 1 step.
- `,
+ You can pass a "steps" number or a commit sha. If a steps number is passed, the plan will be rewound that many steps. If a commit sha is passed, the plan will be rewound to that commit. If neither a steps number nor a commit sha is passed, you will be prompted to select a step from the history.`,
Args: cobra.MaximumNArgs(1),
Run: rewind,
}
func init() {
- // Add rewind command
RootCmd.AddCommand(rewindCmd)
}
@@ -38,48 +37,86 @@ func rewind(cmd *cobra.Command, args []string) {
term.OutputNoCurrentPlanErrorAndExit()
}
- var stepsOrSha string
- if len(args) > 0 {
- stepsOrSha = args[0]
- } else {
- stepsOrSha = "1"
- }
-
+ // Get logs
term.StartSpinner("")
logsRes, apiErr := api.Client.ListLogs(lib.CurrentPlanId, lib.CurrentBranch)
-
if apiErr != nil {
+ term.StopSpinner()
term.OutputErrorAndExit("Error getting logs: %v", apiErr)
}
+ term.StopSpinner()
var targetSha string
+ var steps int
+ var isSha bool
+
+ if len(args) == 0 {
+ // No arguments - show selection list
+ options := make([]string, 0)
+ logEntries := strings.Split(logsRes.Body, "\n\n")
+
+ for _, log := range logEntries {
+ if log == "" {
+ continue
+ }
+
+ // Parse the log entry
+ lines := strings.Split(log, "\n")
+ if len(lines) < 2 {
+ continue
+ }
+
+ // Extract sha and timestamp from first line
+ // Format: 📝 Update 526c4a9[0;22m | [36mToday | 2:35:18am PST[0m
+ parts := strings.Split(lines[0], "|")
+ if len(parts) < 2 {
+ continue
+ }
+
+ shaLine := strings.TrimSpace(parts[0])
+ sha := regexp.MustCompile(`📝 Update (\w+)`).FindStringSubmatch(shaLine)[1]
+
+ // Get message from second line and format it
+ msg := strings.TrimSpace(lines[1])
+
+ // Format the two-line option
+ option := fmt.Sprintf("%s | %s", sha, formatLogMessage(msg))
+ options = append(options, option)
+ }
- // log.Println("shas:", logsRes.Shas)
+ selected, err := term.SelectFromList("Select step to rewind to:", options)
+ if err != nil {
+ term.OutputErrorAndExit("Error selecting step: %v", err)
+ }
- steps, err := strconv.Atoi(stepsOrSha)
- isSha := false
+ // Parse selected option to get sha
+ parts := strings.Split(selected, " | ")
+ if len(parts) < 2 {
+ term.OutputErrorAndExit("Invalid selection")
+ }
- if err == nil && steps > 0 && steps < 999 {
- // log.Println("steps:", steps)
- // Rewind by the specified number of steps
- targetSha = logsRes.Shas[steps]
- } else if sha := stepsOrSha; sha != "" {
- // log.Println("sha provided:", sha)
- // Rewind to the specified Sha
- targetSha = sha
+ targetSha = parts[0]
isSha = true
- } else if stepsOrSha == "" {
- // log.Println("No steps or sha provided, rewinding by 1 step")
- // Rewind by 1 step
- steps = 1
- targetSha = logsRes.Shas[1]
+
} else {
- term.OutputErrorAndExit("Invalid steps or sha. Steps must be a positive integer, and sha must be a valid commit hash.")
+ // Arguments provided - use direct rewind logic
+ stepsOrSha := args[0]
+ steps, err := strconv.Atoi(stepsOrSha)
+
+ if err == nil && steps > 0 && steps < 999 {
+ // Rewind by the specified number of steps
+ targetSha = logsRes.Shas[steps]
+ } else if sha := stepsOrSha; sha != "" {
+ // Rewind to the specified Sha
+ targetSha = sha
+ isSha = true
+ } else {
+ term.OutputErrorAndExit("Invalid steps or sha. Steps must be a positive integer, and sha must be a valid commit hash.")
+ }
}
- // log.Println("Rewinding to", targetSha)
-
// Rewind to the target sha
+ term.StartSpinner("")
_, apiErr = api.Client.RewindPlan(lib.CurrentPlanId, lib.CurrentBranch, shared.RewindPlanRequest{Sha: targetSha})
term.StopSpinner()
@@ -95,7 +132,6 @@ func rewind(cmd *cobra.Command, args []string) {
if steps == 1 {
postfix = ""
}
-
msg = fmt.Sprintf("✅ Rewound %d step%s to %s", steps, postfix, targetSha)
}
@@ -103,6 +139,27 @@ func rewind(cmd *cobra.Command, args []string) {
fmt.Println()
term.PrintCmds("", "log", "continue")
+}
+
+func formatLogMessage(msg string) string {
+ var res string
+
+ // Check for message type patterns
+ switch {
+ case strings.Contains(msg, "User prompt"):
+ res = "💬 " + msg
+ case strings.Contains(msg, "Plandex reply"):
+ if coins := regexp.MustCompile(`(\d+) 🪙`).FindStringSubmatch(msg); len(coins) >= 2 {
+ res = "🤖 AI Response | " + coins[1] + " 🪙"
+ }
+ res = "🤖 " + msg
+ case strings.Contains(msg, "Build pending"):
+ res = "🏗️ Building changes"
+ case strings.Contains(msg, "Loaded"):
+ res = "📚 " + msg
+ default:
+ res = msg
+ }
- // fmt.Println(rwRes.LatestCommit)
+ return res
}
diff --git a/app/cli/go.mod b/app/cli/go.mod
index fb7d78d8..a571c723 100644
--- a/app/cli/go.mod
+++ b/app/cli/go.mod
@@ -4,10 +4,11 @@ go 1.23.3
require (
github.com/atotto/clipboard v0.1.4
- github.com/charmbracelet/lipgloss v0.10.0
+ github.com/charmbracelet/lipgloss v1.0.0
+ github.com/davecgh/go-spew v1.1.1
github.com/fatih/color v1.18.0
github.com/muesli/reflow v0.3.0
- github.com/muesli/termenv v0.15.2
+ github.com/muesli/termenv v0.15.3-0.20240618155329-98d742f6907a
github.com/olekukonko/tablewriter v0.0.5
github.com/plandex-ai/go-prompt v0.0.0-20250130142100-3d8d7ab8d071
github.com/plandex-ai/survey/v2 v2.3.7
@@ -22,10 +23,11 @@ require (
github.com/andybalholm/cascadia v1.3.2 // indirect
github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
github.com/aymerick/douceur v0.2.0 // indirect
- github.com/containerd/console v1.0.4-0.20230313162750-1ae8d489ac81 // indirect
+ github.com/charmbracelet/x/ansi v0.8.0 // indirect
+ github.com/charmbracelet/x/term v0.2.1 // indirect
github.com/cqroot/multichoose v0.1.1 // indirect
- github.com/davecgh/go-spew v1.1.1 // indirect
github.com/dlclark/regexp2 v1.11.4 // indirect
+ github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/gorilla/css v1.0.1 // indirect
github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 // indirect
@@ -34,7 +36,7 @@ require (
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-localereader v0.0.1 // indirect
github.com/mattn/go-tty v0.0.3 // indirect
- github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d // indirect
+ github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b // indirect
github.com/microcosm-cc/bluemonday v1.0.26 // indirect
github.com/mitchellh/go-homedir v1.1.0 // indirect
github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect
@@ -45,16 +47,16 @@ require (
github.com/yuin/goldmark-emoji v1.0.2 // indirect
golang.org/x/exp v0.0.0-20230626212559-97b1e661b5df // indirect
golang.org/x/net v0.18.0 // indirect
- golang.org/x/sync v0.9.0 // indirect
- golang.org/x/sys v0.25.0 // indirect
+ golang.org/x/sync v0.11.0 // indirect
+ golang.org/x/sys v0.30.0 // indirect
)
require (
github.com/Masterminds/semver v1.5.0
github.com/PuerkitoBio/goquery v1.8.1
github.com/briandowns/spinner v1.23.0
- github.com/charmbracelet/bubbles v0.17.2-0.20240108170749-ec883029c8e6
- github.com/charmbracelet/bubbletea v0.25.0
+ github.com/charmbracelet/bubbles v0.20.0
+ github.com/charmbracelet/bubbletea v1.3.0
github.com/charmbracelet/glamour v0.6.0
github.com/charmbracelet/glow v1.5.1
github.com/cqroot/prompt v0.9.3
@@ -69,7 +71,7 @@ require (
github.com/spf13/pflag v1.0.5 // indirect
github.com/xlab/treeprint v1.2.0
golang.org/x/image v0.22.0 // indirect
- golang.org/x/text v0.20.0 // indirect
+ golang.org/x/text v0.22.0 // indirect
)
replace github.com/plandex/plandex/shared => ../shared
diff --git a/app/cli/go.sum b/app/cli/go.sum
index bb9daa50..32f605e8 100644
--- a/app/cli/go.sum
+++ b/app/cli/go.sum
@@ -184,6 +184,8 @@ dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
github.com/DataDog/datadog-go v3.2.0+incompatible/go.mod h1:LButxg5PwREeZtORoXG3tL4fMGNddJ+vMq1mwgfaqoQ=
+github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ4pzQ=
+github.com/MakeNowJust/heredoc v1.0.0/go.mod h1:mG5amYoWBHf8vpLOuehzbGGw0EHxpZZ6lCpQ4fNJ8LE=
github.com/Masterminds/semver v1.5.0 h1:H65muMkzWKEuNDnfl9d70GUjFniHKHRbFPGBuZ3QEww=
github.com/Masterminds/semver v1.5.0/go.mod h1:MB6lktGJrhw8PrUyiEoblNEGEQ+RzHPF078ddwwvV3Y=
github.com/Netflix/go-expect v0.0.0-20220104043353-73e0943537d2 h1:+vx7roKuyA63nhn5WAunQHLTznkw5W8b1Xc0dNjp83s=
@@ -231,13 +233,13 @@ github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghf
github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/charmbracelet/bubbles v0.7.5/go.mod h1:IRTORFvhEI6OUH7WhN2Ks8Z8miNGimk1BE6cmHijOkM=
github.com/charmbracelet/bubbles v0.15.0/go.mod h1:Y7gSFbBzlMpUDR/XM9MhZI374Q+1p1kluf1uLl8iK74=
-github.com/charmbracelet/bubbles v0.17.2-0.20240108170749-ec883029c8e6 h1:6nVCV8pqGaeyxetur3gpX3AAaiyKgzjIoCPV3NXKZBE=
-github.com/charmbracelet/bubbles v0.17.2-0.20240108170749-ec883029c8e6/go.mod h1:9HxZWlkCqz2PRwsCbYl7a3KXvGzFaDHpYbSYMJ+nE3o=
+github.com/charmbracelet/bubbles v0.20.0 h1:jSZu6qD8cRQ6k9OMfR1WlM+ruM8fkPWkHvQWD9LIutE=
+github.com/charmbracelet/bubbles v0.20.0/go.mod h1:39slydyswPy+uVOHZ5x/GjwVAFkCsV8IIVy+4MhzwwU=
github.com/charmbracelet/bubbletea v0.12.2/go.mod h1:3gZkYELUOiEUOp0bTInkxguucy/xRbGSOcbMs1geLxg=
github.com/charmbracelet/bubbletea v0.23.1/go.mod h1:JAfGK/3/pPKHTnAS8JIE2u9f61BjWTQY57RbT25aMXU=
github.com/charmbracelet/bubbletea v0.23.2/go.mod h1:FaP3WUivcTM0xOKNmhciz60M6I+weYLF76mr1JyI7sM=
-github.com/charmbracelet/bubbletea v0.25.0 h1:bAfwk7jRz7FKFl9RzlIULPkStffg5k6pNt5dywy4TcM=
-github.com/charmbracelet/bubbletea v0.25.0/go.mod h1:EN3QDR1T5ZdWmdfDzYcqOCAps45+QIJbLOBxmVNWNNg=
+github.com/charmbracelet/bubbletea v1.3.0 h1:fPMyirm0u3Fou+flch7hlJN9krlnVURrkUVDwqXjoAc=
+github.com/charmbracelet/bubbletea v1.3.0/go.mod h1:eTaHfqbIwvBhFQM/nlT1NsGc4kp8jhF8LfUK67XiTDM=
github.com/charmbracelet/charm v0.8.7/go.mod h1:ApJYwJljEjODkOYJgFDzbUqztLrCWQct9zyPD+xcVr4=
github.com/charmbracelet/glamour v0.6.0 h1:wi8fse3Y7nfcabbbDuwolqTqMQPMnVPeZhDM273bISc=
github.com/charmbracelet/glamour v0.6.0/go.mod h1:taqWV4swIMMbWALc0m7AfE9JkPSU8om2538k9ITBxOc=
@@ -245,8 +247,12 @@ github.com/charmbracelet/glow v1.5.1 h1:o1mwT4xXXpkfUhJG6euQayNxLZf9yKctOCNHLztr
github.com/charmbracelet/glow v1.5.1/go.mod h1:rGgop0a2/4gXWiAxUW1iEQseoE+9Ctpb7M4sM9cY9CU=
github.com/charmbracelet/harmonica v0.2.0/go.mod h1:KSri/1RMQOZLbw7AHqgcBycp8pgJnQMYYT8QZRqZ1Ao=
github.com/charmbracelet/lipgloss v0.6.0/go.mod h1:tHh2wr34xcHjC2HCXIlGSG1jaDF0S0atAUvBMP6Ppuk=
-github.com/charmbracelet/lipgloss v0.10.0 h1:KWeXFSexGcfahHX+54URiZGkBFazf70JNMtwg/AFW3s=
-github.com/charmbracelet/lipgloss v0.10.0/go.mod h1:Wig9DSfvANsxqkRsqj6x87irdy123SR4dOXlKa91ciE=
+github.com/charmbracelet/lipgloss v1.0.0 h1:O7VkGDvqEdGi93X+DeqsQ7PKHDgtQfF8j8/O2qFMQNg=
+github.com/charmbracelet/lipgloss v1.0.0/go.mod h1:U5fy9Z+C38obMs+T+tJqst9VGzlOYGj4ri9reL3qUlo=
+github.com/charmbracelet/x/ansi v0.8.0 h1:9GTq3xq9caJW8ZrBTe0LIe2fvfLR/bYXKTx2llXn7xE=
+github.com/charmbracelet/x/ansi v0.8.0/go.mod h1:wdYl/ONOLHLIVmQaxbIYEC/cRKOQyjTkowiI4blgS9Q=
+github.com/charmbracelet/x/term v0.2.1 h1:AQeHeLZ1OqSXhrAWpYUtZyX1T3zVxfpZuEQMIQaGIAQ=
+github.com/charmbracelet/x/term v0.2.1/go.mod h1:oQ4enTYFV7QN4m0i9mzHrViD7TQKvNEEkHUMCmsxdUg=
github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI=
github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU=
@@ -264,8 +270,6 @@ github.com/cncf/xds/go v0.0.0-20211001041855-01bcc9b48dfe/go.mod h1:eXthEFrGJvWH
github.com/cncf/xds/go v0.0.0-20211011173535-cb28da3451f1/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs=
github.com/containerd/console v1.0.1/go.mod h1:XUsP6YE/mKtz6bxc+I8UiKKTP04qjQL4qcS3XoQ5xkw=
github.com/containerd/console v1.0.3/go.mod h1:7LqA/THxQ86k76b8c/EMSiaJ3h1eZkMkXar0TQ1gf3U=
-github.com/containerd/console v1.0.4-0.20230313162750-1ae8d489ac81 h1:q2hJAaP1k2wIvVRd/hEHD7lacgqrCPS+k8g1MndzfWY=
-github.com/containerd/console v1.0.4-0.20230313162750-1ae8d489ac81/go.mod h1:YynlIjWYF8myEu6sdkwKIvGQq+cOckRm6So2avqoYAk=
github.com/coreos/bbolt v1.3.2/go.mod h1:iRUV2dpdMOn7Bo10OQBFzIJO9kkE559Wcmn+qkEiiKk=
github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE=
github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk=
@@ -305,6 +309,8 @@ github.com/envoyproxy/go-control-plane v0.9.9-0.20210512163311-63b5d3c536b0/go.m
github.com/envoyproxy/go-control-plane v0.9.10-0.20210907150352-cf90f659a021/go.mod h1:AFq3mo9L8Lqqiid3OhADV3RfLJnjiw63cSpi+fDTRC0=
github.com/envoyproxy/go-control-plane v0.10.2-0.20220325020618-49ff273808a1/go.mod h1:KJwIaB5Mv44NWtYuAOFCVOjcI94vtpEz2JU/D2v6IjE=
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
+github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4=
+github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM=
github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4=
github.com/fatih/color v1.9.0/go.mod h1:eQcE1qtQxscV5RaZvpXrrb8Drkc3/DdQ+uUYCNjL+zU=
github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk=
@@ -539,9 +545,8 @@ github.com/mattn/go-tty v0.0.3/go.mod h1:ihxohKRERHTVzN+aSVRwACLCeqIoZAWpoICkkvr
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
github.com/meowgorithm/babyenv v1.3.0/go.mod h1:lwNX+J6AGBFqNrMZ2PTLkM6SO+W4X8DOg9zBDO4j3Ig=
github.com/meowgorithm/babyenv v1.3.1/go.mod h1:lwNX+J6AGBFqNrMZ2PTLkM6SO+W4X8DOg9zBDO4j3Ig=
+github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b h1:j7+1HpAFS1zy5+Q4qx1fWh90gTKwiN4QCGoY9TWyyO4=
github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b/go.mod h1:01TrycV0kFyexm33Z7vhZRXopbI8J3TDReVlkTgMUxE=
-github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d h1:5PJl274Y63IEHC+7izoQE9x6ikvDFZS2mDVS3drnohI=
-github.com/mgutz/ansi v0.0.0-20200706080929-d51e80ef957d/go.mod h1:01TrycV0kFyexm33Z7vhZRXopbI8J3TDReVlkTgMUxE=
github.com/microcosm-cc/bluemonday v1.0.21/go.mod h1:ytNkv4RrDrLJ2pqlsSI46O6IVXmZOBBD4SaJyDwwTkM=
github.com/microcosm-cc/bluemonday v1.0.26 h1:xbqSvqzQMeEHCqMi64VAs4d8uy6Mequs3rQ0k/Khz58=
github.com/microcosm-cc/bluemonday v1.0.26/go.mod h1:JyzOCs9gkyQyjs+6h10UEVSe02CGwkhd72Xdqh78TWs=
@@ -580,8 +585,8 @@ github.com/muesli/termenv v0.11.1-0.20220204035834-5ac8409525e0/go.mod h1:Bd5NYQ
github.com/muesli/termenv v0.13.0/go.mod h1:sP1+uffeLaEYpyOTb8pLCUctGcGLnoFjSn4YJK5e2bc=
github.com/muesli/termenv v0.14.0/go.mod h1:kG/pF1E7fh949Xhe156crRUrHNyK221IuGO7Ez60Uc8=
github.com/muesli/termenv v0.15.1/go.mod h1:HeAQPTzpfs016yGtA4g00CsdYnVLJvxsS4ANqrZs2sQ=
-github.com/muesli/termenv v0.15.2 h1:GohcuySI0QmI3wN8Ok9PtKGkgkFIk7y6Vpb5PvrY+Wo=
-github.com/muesli/termenv v0.15.2/go.mod h1:Epx+iuz8sNs7mNKhxzH4fWXGNpZwUaJKRS1noLXviQ8=
+github.com/muesli/termenv v0.15.3-0.20240618155329-98d742f6907a h1:2MaM6YC3mGu54x+RKAA6JiFFHlHDY1UbkxqppT7wYOg=
+github.com/muesli/termenv v0.15.3-0.20240618155329-98d742f6907a/go.mod h1:hxSnBBYLK21Vtq/PHd0S2FYCxBXzBua8ov5s1RobyRQ=
github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U=
@@ -891,8 +896,8 @@ golang.org/x/sync v0.0.0-20220601150217-0de741cfad7f/go.mod h1:RxMgew5VJxzue5/jJ
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220929204114-8fcdb60fdcc0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
-golang.org/x/sync v0.9.0 h1:fEo0HyrW1GIgZdpbhCRO0PkJajUS5H9IFUztCgEo2jQ=
-golang.org/x/sync v0.9.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
+golang.org/x/sync v0.11.0 h1:GGz8+XQP4FvTTrjZPzNKTMFtSXH80RAzG+5ghFPgK9w=
+golang.org/x/sync v0.11.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
@@ -962,6 +967,7 @@ golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBc
golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210806184541-e5e7981a1069/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210823070655-63515b42dcdf/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210908233432-aa78b53d3365/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
@@ -988,8 +994,8 @@ golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
-golang.org/x/sys v0.25.0 h1:r+8e+loiHxRqhXVl6ML1nO3l1+oFoWbnlu2Ehimmi34=
-golang.org/x/sys v0.25.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
+golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc=
+golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
@@ -1008,8 +1014,8 @@ golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
-golang.org/x/text v0.20.0 h1:gK/Kv2otX8gz+wn7Rmb3vT96ZwuoxnQlY+HlJVj7Qug=
-golang.org/x/text v0.20.0/go.mod h1:D4IsuqiFMhST5bX19pQ9ikHC2GsaKyk/oF+pn3ducp4=
+golang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM=
+golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY=
golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
diff --git a/app/cli/lib/log_format.go b/app/cli/lib/log_format.go
new file mode 100644
index 00000000..d05c89cd
--- /dev/null
+++ b/app/cli/lib/log_format.go
@@ -0,0 +1,122 @@
+package lib
+
+import (
+ "regexp"
+ "strings"
+ "time"
+)
+
+// Regular expressions for parsing log entries
+var (
+ // Match the update ID and timestamp
+ updateRegex = regexp.MustCompile(`📝 Update ([a-f0-9]+)\[0;22m \| \[36m(.*?)\[0m`)
+
+ // Match message number and type
+ messageRegex = regexp.MustCompile(`Message #(\d+) \| (.+?) \|`)
+
+ // Match coin count
+ coinRegex = regexp.MustCompile(`(\d+) 🪙`)
+
+ // Match context load summary
+ contextRegex = regexp.MustCompile(`Loaded (\d+) .+ into context`)
+)
+
+// LogEntry represents a parsed log entry
+type LogEntry struct {
+ ID string
+ Timestamp string
+ Type string
+ Message string
+}
+
+// ParseLogEntry parses a raw log entry string into a structured LogEntry
+func ParseLogEntry(raw string) LogEntry {
+ lines := strings.Split(raw, "\n")
+ entry := LogEntry{}
+
+ // Parse first line for update ID and timestamp
+ if matches := updateRegex.FindStringSubmatch(lines[0]); len(matches) >= 3 {
+ entry.ID = matches[1]
+ entry.Timestamp = parseTimestamp(matches[2])
+ }
+
+ // Parse second line for message type and details
+ if len(lines) > 1 {
+ if matches := messageRegex.FindStringSubmatch(lines[1]); len(matches) >= 3 {
+ entry.Type = cleanType(matches[2])
+ entry.Message = lines[1]
+ } else if matches := contextRegex.FindStringSubmatch(lines[1]); len(matches) >= 2 {
+ entry.Type = "Context Load"
+ entry.Message = lines[1]
+ }
+ }
+
+ return entry
+}
+
+// FormatCompactSummary creates a compact one-line summary of the log entry
+func FormatCompactSummary(entry LogEntry) string {
+ var summary strings.Builder
+
+ // Add timestamp
+ summary.WriteString(entry.Timestamp)
+ summary.WriteString(" | ")
+
+ // Add type indicator and summary based on type
+ switch {
+ case strings.Contains(entry.Type, "User prompt"):
+ summary.WriteString("💬 User: ")
+ msg := extractFirstLine(entry.Message)
+ if len(msg) > 40 {
+ msg = msg[:37] + "..."
+ }
+ summary.WriteString(msg)
+
+ case strings.Contains(entry.Type, "Plandex reply"):
+ summary.WriteString("🤖 AI: ")
+ if coins := coinRegex.FindStringSubmatch(entry.Message); len(coins) >= 2 {
+ summary.WriteString(coins[1] + "🪙")
+ }
+
+ case strings.Contains(entry.Type, "Context Load"):
+ summary.WriteString("📚 ")
+ if matches := contextRegex.FindStringSubmatch(entry.Message); len(matches) >= 2 {
+ summary.WriteString("Loaded " + matches[1] + " items")
+ }
+
+ case strings.Contains(entry.Type, "Build"):
+ summary.WriteString("🏗️ Build changes")
+
+ default:
+ summary.WriteString(entry.Type)
+ }
+
+ return summary.String()
+}
+
+// Helper functions
+
+func parseTimestamp(ts string) string {
+ // Convert timestamp to a consistent format
+ ts = strings.TrimSpace(ts)
+ if ts == "Today" {
+ return time.Now().Format("15:04:05")
+ }
+ if ts == "Yesterday" {
+ return "Yesterday"
+ }
+ return ts
+}
+
+func cleanType(t string) string {
+ // Remove ANSI color codes and clean up type string
+ t = strings.TrimSpace(t)
+ return strings.ReplaceAll(t, "[0m", "")
+}
+
+func extractFirstLine(s string) string {
+ if idx := strings.Index(s, "\n"); idx != -1 {
+ return s[:idx]
+ }
+ return s
+}
diff --git a/app/cli/lib/repl.go b/app/cli/lib/repl.go
index 6b09dc39..deb87552 100644
--- a/app/cli/lib/repl.go
+++ b/app/cli/lib/repl.go
@@ -7,6 +7,7 @@ import (
"path/filepath"
"plandex/fs"
"plandex/term"
+ "strconv"
)
var ReplSettingsDir string
@@ -147,10 +148,24 @@ func ExecPlandexCommand(args []string) (string, error) {
tmpFile.Close()
defer os.Remove(tmpPath)
+ columns := term.GetTerminalWidth()
+ hasDarkBackground := term.HasDarkBackground()
+ streamForegroundColor := term.GetStreamForegroundColor()
+
+ var glamourStyle string
+ if hasDarkBackground {
+ glamourStyle = "dark"
+ } else {
+ glamourStyle = "light"
+ }
+
// Set env vars
env := append(os.Environ(),
"PLANDEX_REPL=1",
"PLANDEX_REPL_OUTPUT_FILE="+tmpPath,
+ "PLANDEX_COLUMNS="+strconv.Itoa(columns),
+ "PLANDEX_STREAM_FOREGROUND_COLOR="+streamForegroundColor.Sequence(false),
+ "GLAMOUR_STYLE="+glamourStyle,
)
// Run command
@@ -159,7 +174,6 @@ func ExecPlandexCommand(args []string) (string, error) {
// Connect stdin directly
cmd.Stdin = os.Stdin
- // Use MultiWriter to send output to both buffer and os.Stdout
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
diff --git a/app/cli/stream_tui/model.go b/app/cli/stream_tui/model.go
index cd9872aa..1ec9c670 100644
--- a/app/cli/stream_tui/model.go
+++ b/app/cli/stream_tui/model.go
@@ -2,6 +2,7 @@ package streamtui
import (
"log"
+ "sync"
"time"
bubbleKey "github.com/charmbracelet/bubbles/key"
@@ -30,6 +31,8 @@ var missingFileSelectOpts = []string{
MissingFileOverwriteLabel,
}
+var stateMu sync.RWMutex
+
type streamUIModel struct {
buildOnly bool
keymap keymap
@@ -91,10 +94,11 @@ type keymap = struct {
}
func (m streamUIModel) Init() tea.Cmd {
+ log.Println("Model Init start")
m.mainViewport.MouseWheelEnabled = true
-
- // start spinner
- return m.Tick()
+ cmd := m.Tick()
+ log.Println("Model Init complete")
+ return cmd
}
func initialModel(prestartReply, prompt string, buildOnly bool) *streamUIModel {
@@ -191,5 +195,19 @@ func (m streamUIModel) Tick() tea.Cmd {
func (m *streamUIModel) cleanup() {
log.Println("Cleaning up stream UI model")
- m.sharedTicker.Stop()
+ m.updateState(func() {
+ m.sharedTicker.Stop()
+ })
+}
+
+func (m *streamUIModel) readState() streamUIModel {
+ stateMu.RLock()
+ defer stateMu.RUnlock()
+ return *m
+}
+
+func (m *streamUIModel) updateState(updateFn func()) {
+ stateMu.Lock()
+ defer stateMu.Unlock()
+ updateFn()
}
diff --git a/app/cli/stream_tui/run.go b/app/cli/stream_tui/run.go
index 110c9630..4b9e34e2 100644
--- a/app/cli/stream_tui/run.go
+++ b/app/cli/stream_tui/run.go
@@ -31,16 +31,22 @@ func StartStreamUI(prompt string, buildOnly bool) error {
os.Exit(0)
}
+ log.Println("Starting stream UI")
+
initial := initialModel(prestartReply, prompt, buildOnly)
mu.Lock()
ui = tea.NewProgram(initial, tea.WithAltScreen())
mu.Unlock()
+ log.Println("Running bubbletea program")
wg.Add(1)
m, err := ui.Run()
+ log.Println("Bubbletea program finished")
wg.Done()
+ log.Println("Stream UI finished")
+
if err != nil {
return fmt.Errorf("error running stream UI: %v", err)
}
@@ -132,7 +138,6 @@ func Send(msg shared.StreamMessage) {
}
mu.Lock()
defer mu.Unlock()
- // log.Printf("sending stream message to UI: %s\n", msg.Type)
ui.Send(msg)
}
diff --git a/app/cli/stream_tui/update.go b/app/cli/stream_tui/update.go
index 05a534c7..3de41ab6 100644
--- a/app/cli/stream_tui/update.go
+++ b/app/cli/stream_tui/update.go
@@ -20,18 +20,24 @@ import (
)
func (m streamUIModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
- // log.Println("Update received message:", spew.Sdump(msg))
+ // log.Println("Stream TUI - Update received message:", spew.Sdump(msg))
switch msg := msg.(type) {
case spinner.TickMsg:
- if m.processing || m.starting {
- spinnerModel, _ := m.spinner.Update(msg)
- m.spinner = spinnerModel
+ state := m.readState()
+
+ if state.processing || state.starting {
+ m.updateState(func() {
+ spinnerModel, _ := m.spinner.Update(msg)
+ m.spinner = spinnerModel
+ })
}
- if m.building {
- buildSpinnerModel, _ := m.buildSpinner.Update(msg)
- m.buildSpinner = buildSpinnerModel
+ if state.building {
+ m.updateState(func() {
+ buildSpinnerModel, _ := m.buildSpinner.Update(msg)
+ m.buildSpinner = buildSpinnerModel
+ })
}
return m, m.Tick()
@@ -39,13 +45,12 @@ func (m streamUIModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
m.windowResized(msg.Width, msg.Height)
case shared.StreamMessage:
- if !m.updateDebouncer.ShouldUpdate() {
- return m, nil // Skip this update if it's too soon
- }
return m.streamUpdate(&msg, false)
case delayFileRestartMsg:
- m.finishedByPath[msg.path] = false
+ m.updateState(func() {
+ m.finishedByPath[msg.path] = false
+ })
// Scroll wheel doesn't seem to work--not sure why
// case tea.MouseMsg:
@@ -69,9 +74,13 @@ func (m streamUIModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
apiErr := api.Client.StopPlan(lib.CurrentPlanId, lib.CurrentBranch)
if apiErr != nil {
log.Println("stop plan api error:", apiErr)
- m.apiErr = apiErr
+ m.updateState(func() {
+ m.apiErr = apiErr
+ })
}
- m.stopped = true
+ m.updateState(func() {
+ m.stopped = true
+ })
return m, tea.Quit
case bubbleKey.Matches(msg, m.keymap.scrollDown) && !m.promptingMissingFile:
@@ -102,58 +111,77 @@ func (m streamUIModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
}
func (m *streamUIModel) windowResized(w, h int) {
- m.width = w
- m.height = h
+ m.updateState(func() {
+ m.width = w
+ m.height = h
+ })
- _, viewportHeight := m.getViewportDimensions()
+ state := m.readState()
- if m.ready {
+ _, viewportHeight := state.getViewportDimensions()
+
+ if state.ready {
m.updateViewportDimensions()
} else {
- m.mainViewport = viewport.New(w, viewportHeight)
- m.mainViewport.Style = lipgloss.NewStyle().Padding(0, 1, 0, 1)
+ m.updateState(func() {
+ m.mainViewport = viewport.New(w, viewportHeight)
+ m.mainViewport.Style = lipgloss.NewStyle().Padding(0, 1, 0, 1)
+ })
+
m.updateReplyDisplay()
- m.ready = true
+
+ m.updateState(func() {
+ m.ready = true
+ })
}
}
func (m *streamUIModel) updateReplyDisplay() {
- if m.buildOnly {
+ state := m.readState()
+
+ if state.buildOnly {
return
}
s := ""
- if m.prompt != "" {
- promptTxt := term.GetPlain(m.prompt)
+ if state.prompt != "" {
+ promptTxt := term.GetPlain(state.prompt)
s += color.New(color.BgGreen, color.Bold, color.FgHiWhite).Sprintf(" 💬 User prompt 👇 ")
s += "\n\n" + strings.TrimSpace(promptTxt) + "\n"
}
- if m.reply != "" {
- replyMd, _ := term.GetMarkdown(m.reply)
+ if state.reply != "" {
+ replyMd, _ := term.GetMarkdown(state.reply)
s += "\n" + color.New(color.BgBlue, color.Bold, color.FgHiWhite).Sprintf(" 🤖 Plandex reply 👇 ")
s += "\n\n" + strings.TrimSpace(replyMd)
} else {
s += "\n"
}
- m.mainDisplay = s
- m.mainViewport.SetContent(s)
+ m.updateState(func() {
+ m.mainDisplay = s
+ m.mainViewport.SetContent(s)
+ })
+
m.updateViewportDimensions()
- if m.atScrollBottom {
- m.mainViewport.GotoBottom()
+ if state.atScrollBottom {
+ m.updateState(func() {
+ m.mainViewport.GotoBottom()
+ })
}
}
func (m *streamUIModel) updateViewportDimensions() {
- // log.Println("updateViewportDimensions")
+ state := m.readState()
+ w, h := state.getViewportDimensions()
- w, h := m.getViewportDimensions()
- m.mainViewport.Width = w
- m.mainViewport.Height = h
+ m.updateState(func() {
+ m.mainViewport.Width = w
+ m.mainViewport.Height = h
+ })
}
func (m *streamUIModel) getViewportDimensions() (int, int) {
@@ -167,9 +195,6 @@ func (m *streamUIModel) getViewportDimensions() (int, int) {
buildHeight = len(m.getRows(false))
}
- // log.Println("building:", m.building)
- // log.Println("buildHeight:", buildHeight)
-
var processingHeight int
if m.starting || m.processing {
processingHeight = lipgloss.Height(m.renderProcessing())
@@ -179,8 +204,6 @@ func (m *streamUIModel) getViewportDimensions() (int, int) {
viewportHeight := min(maxViewportHeight, lipgloss.Height(m.mainDisplay))
viewportWidth := w
- // log.Println("viewportWidth:", viewportWidth)
-
return viewportWidth, viewportHeight
}
@@ -189,54 +212,83 @@ func (m streamUIModel) replyScrollable() bool {
}
func (m *streamUIModel) scrollDown() {
- if m.replyScrollable() {
- m.mainViewport.LineDown(1)
+ state := m.readState()
+
+ if state.replyScrollable() {
+ m.updateState(func() {
+ m.mainViewport.LineDown(1)
+ })
}
- m.atScrollBottom = !m.replyScrollable() || m.mainViewport.AtBottom()
+ state = m.readState()
+
+ m.updateState(func() {
+ m.atScrollBottom = !state.replyScrollable() || state.mainViewport.AtBottom()
+ })
}
func (m *streamUIModel) scrollUp() {
- if m.replyScrollable() {
- m.mainViewport.LineUp(1)
- m.atScrollBottom = false
+ state := m.readState()
+
+ if state.replyScrollable() {
+ m.updateState(func() {
+ m.mainViewport.LineUp(1)
+ m.atScrollBottom = false
+ })
}
}
func (m *streamUIModel) pageDown() {
- if m.replyScrollable() {
- m.mainViewport.ViewDown()
+ state := m.readState()
+
+ if state.replyScrollable() {
+ m.updateState(func() {
+ m.mainViewport.ViewDown()
+ })
}
- m.atScrollBottom = !m.replyScrollable() || m.mainViewport.AtBottom()
+ state = m.readState()
+
+ m.updateState(func() {
+ m.atScrollBottom = !state.replyScrollable() || state.mainViewport.AtBottom()
+ })
}
func (m *streamUIModel) pageUp() {
- if m.replyScrollable() {
- m.mainViewport.ViewUp()
- m.atScrollBottom = false
+ state := m.readState()
+
+ if state.replyScrollable() {
+ m.updateState(func() {
+ m.mainViewport.ViewUp()
+ m.atScrollBottom = false
+ })
}
}
func (m *streamUIModel) scrollStart() {
- if m.replyScrollable() {
- m.mainViewport.GotoTop()
- m.atScrollBottom = false
+ state := m.readState()
+
+ if state.replyScrollable() {
+ m.updateState(func() {
+ m.mainViewport.GotoTop()
+ m.atScrollBottom = false
+ })
}
}
func (m *streamUIModel) scrollEnd() {
- if m.replyScrollable() {
- m.mainViewport.GotoBottom()
- m.atScrollBottom = true
+ state := m.readState()
+
+ if state.replyScrollable() {
+ m.updateState(func() {
+ m.mainViewport.GotoBottom()
+ m.atScrollBottom = true
+ })
}
}
func (m *streamUIModel) streamUpdate(msg *shared.StreamMessage, deferUIUpdate bool) (tea.Model, tea.Cmd) {
- // log.Println("streamUI received message:", msg.Type)
- // log.Println(spew.Sdump(msg))
-
switch msg.Type {
case shared.StreamMessageMulti:
@@ -257,24 +309,29 @@ func (m *streamUIModel) streamUpdate(msg *shared.StreamMessage, deferUIUpdate bo
return m, tea.Batch(cmds...)
case shared.StreamMessageConnectActive:
-
if msg.InitPrompt != "" {
- m.prompt = msg.InitPrompt
+ m.updateState(func() {
+ m.prompt = msg.InitPrompt
+ })
}
if msg.InitBuildOnly {
- m.buildOnly = true
+ m.updateState(func() {
+ m.buildOnly = true
+ })
}
if len(msg.InitReplies) > 0 {
- m.reply = strings.Join(msg.InitReplies, "\n\n👇\n\n")
+ m.updateState(func() {
+ m.reply = strings.Join(msg.InitReplies, "\n\n👇\n\n")
+ })
}
m.updateReplyDisplay()
-
return m.checkMissingFile(msg)
case shared.StreamMessagePromptMissingFile:
return m.checkMissingFile(msg)
case shared.StreamMessageReply:
+ // log.Println("streamUpdate received reply message")
// log.Println("Stream message reply:")
// log.Println(spew.Sdump(msg))
@@ -283,26 +340,32 @@ func (m *streamUIModel) streamUpdate(msg *shared.StreamMessage, deferUIUpdate bo
return m, nil
}
- if m.starting {
- m.starting = false
+ state := m.readState()
+
+ if state.starting {
+ m.updateState(func() {
+ m.starting = false
+ })
}
- if m.processing {
+ if state.processing {
log.Println("Non-empty message reply, setting processing to false")
- m.processing = false
- if m.promptedMissingFile || m.autoLoadedMissingFile {
- log.Println("Prompted missing file or auto loaded missing file, resetting (and skipping 👇 marker)")
- m.promptedMissingFile = false
- m.autoLoadedMissingFile = false
- } else {
- log.Println("Not prompted missing file or auto loaded missing file, adding 👇 marker")
- m.reply += "\n\n👇\n\n"
- }
+ m.updateState(func() {
+ m.processing = false
+ if state.promptedMissingFile || state.autoLoadedMissingFile {
+ log.Println("Prompted missing file or auto loaded missing file, resetting (and skipping 👇 marker)")
+ m.promptedMissingFile = false
+ m.autoLoadedMissingFile = false
+ } else {
+ log.Println("Not prompted missing file or auto loaded missing file, adding 👇 marker")
+ m.reply += "\n\n👇\n\n"
+ }
+ })
}
- m.reply += msg.ReplyChunk
-
- // log.Println(m.reply)
+ m.updateState(func() {
+ m.reply += msg.ReplyChunk
+ })
if !deferUIUpdate {
m.updateReplyDisplay()
@@ -312,32 +375,47 @@ func (m *streamUIModel) streamUpdate(msg *shared.StreamMessage, deferUIUpdate bo
// log.Println("Stream message build info")
// log.Println(spew.Sdump(msg))
- if m.starting {
- m.starting = false
+ state := m.readState()
+
+ if state.starting {
+ m.updateState(func() {
+ m.starting = false
+ })
}
- m.building = true
- wasFinished := m.finishedByPath[msg.BuildInfo.Path]
+ m.updateState(func() {
+ m.building = true
+ })
+ wasFinished := state.finishedByPath[msg.BuildInfo.Path]
nowFinished := msg.BuildInfo.Finished
- if msg.BuildInfo.Removed {
- m.removedByPath[msg.BuildInfo.Path] = true
- } else {
- m.removedByPath[msg.BuildInfo.Path] = false
- }
+ m.updateState(func() {
+ if msg.BuildInfo.Removed {
+ m.removedByPath[msg.BuildInfo.Path] = true
+ } else {
+ m.removedByPath[msg.BuildInfo.Path] = false
+ }
+ })
if msg.BuildInfo.Finished {
- m.tokensByPath[msg.BuildInfo.Path] = 0
- m.finishedByPath[msg.BuildInfo.Path] = true
+ m.updateState(func() {
+ m.tokensByPath[msg.BuildInfo.Path] = 0
+ m.finishedByPath[msg.BuildInfo.Path] = true
+ })
} else {
if wasFinished && !nowFinished {
// delay for a second before marking not finished again (so check flashes green prior to restarting build)
+ log.Println("Stream message build info - delaying for 1 second before marking not finished again")
return m, startDelay(msg.BuildInfo.Path, time.Second*1)
} else {
- m.finishedByPath[msg.BuildInfo.Path] = false
+ m.updateState(func() {
+ m.finishedByPath[msg.BuildInfo.Path] = false
+ })
}
- m.tokensByPath[msg.BuildInfo.Path] += msg.BuildInfo.NumTokens
+ m.updateState(func() {
+ m.tokensByPath[msg.BuildInfo.Path] += msg.BuildInfo.NumTokens
+ })
}
if !deferUIUpdate {
@@ -348,7 +426,10 @@ func (m *streamUIModel) streamUpdate(msg *shared.StreamMessage, deferUIUpdate bo
case shared.StreamMessageDescribing:
log.Println("Message describing, setting processing to true")
- m.processing = true
+
+ m.updateState(func() {
+ m.processing = true
+ })
return m, m.Tick()
@@ -361,29 +442,42 @@ func (m *streamUIModel) streamUpdate(msg *shared.StreamMessage, deferUIUpdate bo
return m, tea.Quit
}
- m.reply += "\n\n" + msg + "\n\n"
+ m.updateState(func() {
+ m.reply += "\n\n" + msg + "\n\n"
+ })
+
m.updateReplyDisplay()
return m, m.Tick()
case shared.StreamMessageError:
- m.apiErr = msg.Error
+ m.updateState(func() {
+ m.apiErr = msg.Error
+ })
return m, tea.Quit
case shared.StreamMessageFinished:
// log.Println("stream finished")
- m.finished = true
+ m.updateState(func() {
+ m.finished = true
+ })
return m, tea.Quit
case shared.StreamMessageAborted:
- m.stopped = true
+ m.updateState(func() {
+ m.stopped = true
+ })
return m, tea.Quit
case shared.StreamMessageRepliesFinished:
log.Println("Replies finished, setting processing to false")
- m.processing = false
+ state := m.readState()
+
+ m.updateState(func() {
+ m.processing = false
+ })
- if m.building {
+ if state.building {
return m, m.Tick()
}
}
@@ -439,20 +533,30 @@ func (m *streamUIModel) resolveEscapeSequence(val string) {
}
func (m *streamUIModel) up() {
- if m.promptingMissingFile {
- m.missingFileSelectedIdx = max(m.missingFileSelectedIdx-1, 0)
+ state := m.readState()
+
+ if state.promptingMissingFile {
+ m.updateState(func() {
+ m.missingFileSelectedIdx = max(m.missingFileSelectedIdx-1, 0)
+ })
}
}
func (m *streamUIModel) down() {
- if m.promptingMissingFile {
- m.missingFileSelectedIdx = min(m.missingFileSelectedIdx+1, len(missingFileSelectOpts)-1)
+ state := m.readState()
+
+ if state.promptingMissingFile {
+ m.updateState(func() {
+ m.missingFileSelectedIdx = min(m.missingFileSelectedIdx+1, len(missingFileSelectOpts)-1)
+ })
}
}
func (m *streamUIModel) selectedMissingFileOpt() (tea.Model, tea.Cmd) {
- choice := promptChoices[m.missingFileSelectedIdx]
+ state := m.readState()
+
+ choice := promptChoices[state.missingFileSelectedIdx]
if choice == "" {
return m, nil
@@ -466,23 +570,30 @@ func (m *streamUIModel) selectedMissingFileOpt() (tea.Model, tea.Cmd) {
if apiErr != nil {
log.Println("missing file prompt api error:", apiErr)
- m.apiErr = apiErr
+ m.updateState(func() {
+ m.apiErr = apiErr
+ })
return m, nil
}
if choice == shared.RespondMissingFileChoiceSkip {
- replyLines := strings.Split(m.reply, "\n")
- m.reply = strings.Join(replyLines[:len(replyLines)-3], "\n")
+ replyLines := strings.Split(state.reply, "\n")
+ m.updateState(func() {
+ m.reply = strings.Join(replyLines[:len(replyLines)-3], "\n")
+ })
+
m.updateReplyDisplay()
}
- m.promptingMissingFile = false
- m.missingFilePath = ""
- m.missingFileSelectedIdx = 0
- m.missingFileContent = ""
- m.missingFileTokens = 0
- m.promptedMissingFile = true
- m.processing = true
+ m.updateState(func() {
+ m.promptingMissingFile = false
+ m.missingFilePath = ""
+ m.missingFileSelectedIdx = 0
+ m.missingFileContent = ""
+ m.missingFileTokens = 0
+ m.promptedMissingFile = true
+ m.processing = true
+ })
return m, func() tea.Msg {
<-m.sharedTicker.C
@@ -496,8 +607,10 @@ func (m *streamUIModel) checkMissingFile(msg *shared.StreamMessage) (tea.Model,
if msg.MissingFileAutoContext {
log.Println("checkMissingFile - received missing file message | auto context")
- m.processing = true
- m.autoLoadedMissingFile = true
+ m.updateState(func() {
+ m.processing = true
+ m.autoLoadedMissingFile = true
+ })
return m, tea.Batch(
func() tea.Msg {
@@ -522,7 +635,9 @@ func (m *streamUIModel) checkMissingFile(msg *shared.StreamMessage) (tea.Model,
if apiErr != nil {
log.Println("missing file prompt api error:", apiErr)
- m.apiErr = apiErr
+ m.updateState(func() {
+ m.apiErr = apiErr
+ })
return tea.Quit
}
@@ -533,21 +648,32 @@ func (m *streamUIModel) checkMissingFile(msg *shared.StreamMessage) (tea.Model,
)
}
- m.promptingMissingFile = true
- m.missingFilePath = msg.MissingFilePath
+ m.updateState(func() {
+ m.promptingMissingFile = true
+ m.missingFilePath = msg.MissingFilePath
+ })
log.Println("checkMissingFile - reading file")
bytes, err := os.ReadFile(m.missingFilePath)
if err != nil {
log.Println("failed to read file:", err)
- m.err = fmt.Errorf("failed to read file: %w", err)
+ m.updateState(func() {
+ m.err = fmt.Errorf("failed to read file: %w", err)
+ })
return m, nil
}
- m.missingFileContent = string(bytes)
+
+ missingFileContent := string(bytes)
+
+ m.updateState(func() {
+ m.missingFileContent = missingFileContent
+ })
log.Println("checkMissingFile - estimating tokens")
- numTokens := shared.GetNumTokensEstimate(m.missingFileContent)
- m.missingFileTokens = numTokens
+ numTokens := shared.GetNumTokensEstimate(missingFileContent)
+ m.updateState(func() {
+ m.missingFileTokens = numTokens
+ })
}
return m, nil
diff --git a/app/cli/term/format.go b/app/cli/term/format.go
index b97b821f..427f5125 100644
--- a/app/cli/term/format.go
+++ b/app/cli/term/format.go
@@ -1,6 +1,8 @@
package term
import (
+ "fmt"
+ "os"
"strings"
"github.com/charmbracelet/glamour"
@@ -9,18 +11,58 @@ import (
"github.com/muesli/termenv"
)
-func GetMarkdown(input string) (string, error) {
- width := getTerminalWidth()
+func init() {
+ // pre-cache the glamour renderer
+ getGlamourRenderer()
+}
- inputBytes := utils.RemoveFrontmatter([]byte(input))
+var (
+ cachedGlamourRenderer *glamour.TermRenderer
+ cachedGlamourRendererWidth int
+)
+
+func getGlamourRenderer() (*glamour.TermRenderer, error) {
+ width := GetTerminalWidth()
+
+ if cachedGlamourRenderer != nil && cachedGlamourRendererWidth == width {
+ return cachedGlamourRenderer, nil
+ }
+
+ // Build the renderer options.
+ var opts []glamour.TermRendererOption
+
+ // Check for a GLAMOUR_STYLE env variable.
+ if style, ok := os.LookupEnv("GLAMOUR_STYLE"); ok && style != "" {
+ opts = append(opts, glamour.WithStandardStyle(style))
+ } else {
+ // Fallback to auto style detection.
+ opts = append(opts, glamour.WithAutoStyle())
+ }
- r, _ := glamour.NewTermRenderer(
- // detect background color and pick either the default dark or light theme
- glamour.WithAutoStyle(),
+ // Always set word wrap and preserved newlines.
+ opts = append(opts,
glamour.WithWordWrap(min(width, 80)),
glamour.WithPreservedNewLines(),
)
+ r, err := glamour.NewTermRenderer(opts...)
+ if err != nil {
+ return nil, fmt.Errorf("failed to create glamour renderer: %w", err)
+ }
+
+ cachedGlamourRenderer = r
+ cachedGlamourRendererWidth = width
+ return r, nil
+}
+
+func GetMarkdown(input string) (string, error) {
+ inputBytes := utils.RemoveFrontmatter([]byte(input))
+
+ r, err := getGlamourRenderer()
+ if err != nil {
+ return "", err
+ }
+
out, err := r.RenderBytes(inputBytes)
if err != nil {
return "", err
@@ -30,10 +72,9 @@ func GetMarkdown(input string) (string, error) {
}
func GetPlain(input string) string {
- width := getTerminalWidth()
+ width := GetTerminalWidth()
s := wordwrap.String(input, min(width-2, 80))
-
// add padding
lines := strings.Split(s, "\n")
for i := range lines {
@@ -41,10 +82,7 @@ func GetPlain(input string) string {
}
s = strings.Join(lines, "\n")
- c := "234"
- if termenv.HasDarkBackground() {
- c = "251"
- }
+ s = termenv.String(s).Foreground(GetStreamForegroundColor()).String()
- return termenv.String(s).Foreground(termenv.ANSI256.Color(c)).String()
+ return s
}
diff --git a/app/cli/term/utils.go b/app/cli/term/utils.go
index f9eb2395..e36fbc50 100644
--- a/app/cli/term/utils.go
+++ b/app/cli/term/utils.go
@@ -7,9 +7,18 @@ import (
"strconv"
"strings"
+ "github.com/muesli/termenv"
"golang.org/x/term"
)
+func init() {
+ // pre-cache terminal settings
+ IsTerminal()
+ GetTerminalWidth()
+ GetStreamForegroundColor()
+ HasDarkBackground()
+}
+
func AlternateScreen() {
// Switch to alternate screen and hide the cursor
fmt.Print("\x1b[?1049h\x1b[?25l")
@@ -64,40 +73,88 @@ func PageOutputReverse(output string) {
func GetDivisionLine() string {
// Get the terminal width
- terminalWidth := getTerminalWidth()
+ terminalWidth := GetTerminalWidth()
return strings.Repeat("─", terminalWidth)
}
-func getTerminalWidth() int {
- // Try to get terminal size
- if w, _, err := term.GetSize(int(os.Stdout.Fd())); err == nil {
- return w
+var envReplCols int
+var envDefaultCols int
+
+func GetTerminalWidth() int {
+ if envReplCols != 0 {
+ return envReplCols
}
- // Use tput to get terminal width
- if w, err := getWidthFromTput(); err == nil {
- return w
+ if os.Getenv("PLANDEX_COLUMNS") != "" {
+ w, err := strconv.Atoi(os.Getenv("PLANDEX_COLUMNS"))
+ if err == nil {
+ envReplCols = w
+ return w
+ }
}
+ if IsTerminal() {
+ // Try to get terminal size
+ if w, _, err := term.GetSize(int(os.Stdout.Fd())); err == nil {
+ return w
+ }
+ }
+
+ if envDefaultCols != 0 {
+ return envDefaultCols
+ }
+
+ // Not running in a TTY or GetSize failed; use a default.
// Try to get width from environment variable
if w, err := strconv.Atoi(os.Getenv("COLUMNS")); err == nil {
+ envDefaultCols = w
return w
}
// Fallback to default width
- return 50
+ return 80
}
-func getWidthFromTput() (int, error) {
- cmd := exec.Command("tput", "cols")
- cmd.Stdin = os.Stdin
- out, err := cmd.Output()
- if err != nil {
- return 0, err
+var envStreamForegroundColor termenv.Color
+
+func GetStreamForegroundColor() termenv.Color {
+ if envStreamForegroundColor != nil {
+ return envStreamForegroundColor
}
- width, err := strconv.Atoi(strings.TrimSpace(string(out)))
- if err != nil {
- return 0, err
+
+ if os.Getenv("PLANDEX_STREAM_FOREGROUND_COLOR") != "" {
+ envStreamForegroundColor = termenv.ANSI256.Color(os.Getenv("PLANDEX_STREAM_FOREGROUND_COLOR"))
+ return envStreamForegroundColor
+ }
+
+ c := "234"
+ if HasDarkBackground() {
+ c = "251"
+ }
+ envStreamForegroundColor = termenv.ANSI256.Color(c)
+ return envStreamForegroundColor
+}
+
+var envHasDarkBackground bool
+var cachedHasDarkBackground bool
+
+func HasDarkBackground() bool {
+ if cachedHasDarkBackground {
+ return envHasDarkBackground
+ }
+ envHasDarkBackground = termenv.HasDarkBackground()
+ cachedHasDarkBackground = true
+ return envHasDarkBackground
+}
+
+var envIsTerminal bool
+var cachedIsTerminal bool
+
+func IsTerminal() bool {
+ if cachedIsTerminal {
+ return envIsTerminal
}
- return width, nil
+ envIsTerminal = term.IsTerminal(int(os.Stdout.Fd()))
+ cachedIsTerminal = true
+ return envIsTerminal
}
diff --git a/app/server/model/client.go b/app/server/model/client.go
index e4b2b4b2..4555529e 100644
--- a/app/server/model/client.go
+++ b/app/server/model/client.go
@@ -82,8 +82,9 @@ type OpenRouterProviderConfig struct {
type ExtendedChatCompletionRequest struct {
*openai.ChatCompletionRequest
- Prediction *OpenAIPrediction `json:"prediction,omitempty"`
- Provider *OpenRouterProviderConfig `json:"provider,omitempty"`
+ Prediction *OpenAIPrediction `json:"prediction,omitempty"`
+ Provider *OpenRouterProviderConfig `json:"provider,omitempty"`
+ ReasoningEffort *shared.ReasoningEffort `json:"reasoning_effort,omitempty"`
}
// ExtendedChatCompletionStream can wrap either a native OpenAI stream or our custom implementation
@@ -111,43 +112,20 @@ type ErrorAccumulator struct {
// JSONUnmarshaler handles JSON unmarshaling for stream responses
type JSONUnmarshaler struct{}
-func CreateChatCompletionStreamWithRetries(
+func CreateChatCompletionStreamWithRetries[T openai.ChatCompletionRequest | ExtendedChatCompletionRequest](
clients map[string]ClientInfo,
modelConfig *shared.ModelRoleConfig,
ctx context.Context,
- req interface{},
+ req T,
) (*ExtendedChatCompletionStream, error) {
client, ok := clients[modelConfig.BaseModelConfig.ApiKeyEnvVar]
if !ok {
return nil, fmt.Errorf("client not found for api key env var: %s", modelConfig.BaseModelConfig.ApiKeyEnvVar)
}
- var baseReq *openai.ChatCompletionRequest
- var finalReq *ExtendedChatCompletionRequest
-
- switch typedReq := req.(type) {
- case openai.ChatCompletionRequest:
- baseReq = &typedReq
- finalReq = &ExtendedChatCompletionRequest{
- ChatCompletionRequest: baseReq,
- }
-
- case ExtendedChatCompletionRequest:
- baseReq = typedReq.ChatCompletionRequest
- finalReq = &typedReq
-
- default:
- return nil, fmt.Errorf("invalid request type: %T", req)
- }
-
- resolveReq(baseReq, modelConfig)
-
- providerOrder := getOpenRouterProviderOrder(modelConfig)
- if len(providerOrder) > 0 {
- finalReq.Provider = &OpenRouterProviderConfig{
- Order: providerOrder,
- AllowFallbacks: modelConfig.BaseModelConfig.OpenRouterAllowFallbacks,
- }
+ finalReq, err := getFinalReq(req, modelConfig)
+ if err != nil {
+ return nil, fmt.Errorf("error setting up request: %w", err)
}
return withRetries(ctx, func() (*ExtendedChatCompletionStream, error) {
@@ -166,6 +144,17 @@ func CreateChatCompletionWithRetries[T openai.ChatCompletionRequest | ExtendedCh
return openai.ChatCompletionResponse{}, fmt.Errorf("client not found for api key env var: %s", modelConfig.BaseModelConfig.ApiKeyEnvVar)
}
+ finalReq, err := getFinalReq(req, modelConfig)
+ if err != nil {
+ return openai.ChatCompletionResponse{}, fmt.Errorf("error setting up request: %w", err)
+ }
+
+ return withRetries(ctx, func() (openai.ChatCompletionResponse, error) {
+ return createChatCompletionExtended(client, modelConfig.BaseModelConfig.BaseUrl, ctx, *finalReq)
+ })
+}
+
+func getFinalReq[T openai.ChatCompletionRequest | ExtendedChatCompletionRequest](req T, modelConfig *shared.ModelRoleConfig) (*ExtendedChatCompletionRequest, error) {
var baseReq *openai.ChatCompletionRequest
var finalReq *ExtendedChatCompletionRequest
@@ -190,14 +179,12 @@ func CreateChatCompletionWithRetries[T openai.ChatCompletionRequest | ExtendedCh
} else {
log.Println("Invalid request type")
log.Println("Request type:", reflect.TypeOf(req))
- return openai.ChatCompletionResponse{}, fmt.Errorf("invalid request type")
+ return nil, fmt.Errorf("invalid request type")
}
resolveReq(baseReq, modelConfig)
- return withRetries(ctx, func() (openai.ChatCompletionResponse, error) {
- return createChatCompletionExtended(client, modelConfig.BaseModelConfig.BaseUrl, ctx, *finalReq)
- })
+ return finalReq, nil
}
func createChatCompletionExtended(
diff --git a/app/server/model/plan/build_structured_edits.go b/app/server/model/plan/build_structured_edits.go
index 76db1088..b2590315 100644
--- a/app/server/model/plan/build_structured_edits.go
+++ b/app/server/model/plan/build_structured_edits.go
@@ -93,7 +93,10 @@ func (fileState *activeBuildStreamFileState) buildStructuredEdits() {
log.Printf("buildStructuredEdits - %s - initial isValid: %t\n", filePath, isValid)
- var buildStage BuildStage = BuildStageInitial
+ // var buildStage BuildStage = BuildStageInitial
+
+ // Starting on BuildStageValidateAndCorrect is a hacky way to skip the validation/replacements step and instead do a single validation pass, followed by whole file build. For now, this is offering better results—it seems that on changes where the deterministic structural edits algorithm fails, replacements fail at a pretty high rate as well... so better to go straight to whole file build and save the extra requests.
+ var buildStage BuildStage = BuildStageValidateAndCorrect
for !isValid && int(buildStage) <= int(BuildStageValidateAndCorrect) {
buildStage = BuildStage(int(buildStage) + 1)
diff --git a/app/server/model/plan/build_whole_file.go b/app/server/model/plan/build_whole_file.go
index 355b762a..c385b747 100644
--- a/app/server/model/plan/build_whole_file.go
+++ b/app/server/model/plan/build_whole_file.go
@@ -43,6 +43,9 @@ func (fileState *activeBuildStreamFileState) buildWholeFileFallback(proposedCont
},
}
+ maxExpectedOutputTokens := shared.GetNumTokensEstimate(originalFile + proposedContent)
+ modelConfig := config.GetRoleForOutputTokens(maxExpectedOutputTokens)
+
inputTokens := shared.GetMessagesTokenEstimate(messages...) + shared.TokensPerRequest
_, apiErr := hooks.ExecHook(hooks.WillSendModelRequest, hooks.HookParams{
@@ -50,8 +53,8 @@ func (fileState *activeBuildStreamFileState) buildWholeFileFallback(proposedCont
Plan: fileState.plan,
WillSendModelRequestParams: &hooks.WillSendModelRequestParams{
InputTokens: inputTokens,
- OutputTokens: config.GetReservedOutputTokens(),
- ModelName: config.BaseModelConfig.ModelName,
+ OutputTokens: modelConfig.GetReservedOutputTokens(),
+ ModelName: modelConfig.BaseModelConfig.ModelName,
},
})
if apiErr != nil {
@@ -59,21 +62,21 @@ func (fileState *activeBuildStreamFileState) buildWholeFileFallback(proposedCont
return
}
- log.Println("buildWholeFile - calling model for applied changes validation")
+ log.Println("buildWholeFile - calling model for whole file write")
var resp openai.ChatCompletionResponse
var err error
modelReq := &openai.ChatCompletionRequest{
- Model: config.BaseModelConfig.ModelName,
+ Model: modelConfig.BaseModelConfig.ModelName,
Messages: messages,
- Temperature: config.Temperature,
- TopP: config.TopP,
+ Temperature: modelConfig.Temperature,
+ TopP: modelConfig.TopP,
}
- log.Println("buildWholeFile - config.BaseModelConfig.PredictedOutputEnabled:", config.BaseModelConfig.PredictedOutputEnabled)
+ log.Println("buildWholeFile - modelConfig.BaseModelConfig.PredictedOutputEnabled:", modelConfig.BaseModelConfig.PredictedOutputEnabled)
- if config.BaseModelConfig.PredictedOutputEnabled {
+ if modelConfig.BaseModelConfig.PredictedOutputEnabled {
extendedReq := &model.ExtendedChatCompletionRequest{
ChatCompletionRequest: modelReq,
Prediction: &model.OpenAIPrediction{
@@ -110,8 +113,8 @@ No comments
DidSendModelRequestParams: &hooks.DidSendModelRequestParams{
InputTokens: resp.Usage.PromptTokens,
OutputTokens: resp.Usage.CompletionTokens,
- ModelName: config.BaseModelConfig.ModelName,
- ModelProvider: config.BaseModelConfig.Provider,
+ ModelName: modelConfig.BaseModelConfig.ModelName,
+ ModelProvider: modelConfig.BaseModelConfig.Provider,
ModelPackName: fileState.settings.ModelPack.Name,
ModelRole: shared.ModelRoleBuilder,
Purpose: "File edit (whole file)",
diff --git a/app/server/model/plan/tell_exec.go b/app/server/model/plan/tell_exec.go
index 8169beb8..cd72a7a4 100644
--- a/app/server/model/plan/tell_exec.go
+++ b/app/server/model/plan/tell_exec.go
@@ -75,7 +75,6 @@ func execTellPlan(params execTellPlanParams) {
iteration := params.iteration
missingFileResponse := params.missingFileResponse
shouldBuildPending := params.shouldBuildPending
- numErrorRetry := params.numErrorRetry
shouldLoadFollowUpContext := params.shouldLoadFollowUpContext
didLoadFollowUpContext := params.didLoadFollowUpContext
didMakeFollowUpPlan := params.didMakeFollowUpPlan
@@ -122,16 +121,16 @@ func execTellPlan(params execTellPlanParams) {
log.Println("execTellPlan - Plan status set to replying")
state := &activeTellStreamState{
- clients: clients,
- req: req,
- auth: auth,
- currentOrgId: currentOrgId,
- currentUserId: currentUserId,
- plan: plan,
- branch: branch,
- iteration: iteration,
- missingFileResponse: missingFileResponse,
- currentReplyNumRetries: numErrorRetry,
+ execTellPlanParams: params,
+ clients: clients,
+ req: req,
+ auth: auth,
+ currentOrgId: currentOrgId,
+ currentUserId: currentUserId,
+ plan: plan,
+ branch: branch,
+ iteration: iteration,
+ missingFileResponse: missingFileResponse,
}
log.Println("execTellPlan - Loading tell plan")
@@ -280,10 +279,10 @@ func execTellPlan(params execTellPlanParams) {
modelConfig = plannerConfig.ModelRoleConfig
if isContextStage {
log.Println("Tell plan - isContextStage - setting modelConfig to context loader")
- modelConfig = state.settings.ModelPack.GetContextLoader().GetRoleForTokens(requestTokens)
+ modelConfig = state.settings.ModelPack.GetContextLoader().GetRoleForInputTokens(requestTokens)
}
} else if isImplementationStage {
- modelConfig = state.settings.ModelPack.GetCoder().GetRoleForTokens(requestTokens)
+ modelConfig = state.settings.ModelPack.GetCoder().GetRoleForInputTokens(requestTokens)
}
log.Println("totalRequestTokens:", requestTokens)
diff --git a/app/server/model/plan/tell_prompt_message.go b/app/server/model/plan/tell_prompt_message.go
index b1bc80bc..dcd11a68 100644
--- a/app/server/model/plan/tell_prompt_message.go
+++ b/app/server/model/plan/tell_prompt_message.go
@@ -15,6 +15,11 @@ func (state *activeTellStreamState) resolvePromptMessage(isPlanningStage, isCont
active := state.activePlan
isFollowUp := state.isFollowUp
+ if isFollowUp && (req.IsApplyDebug || req.IsUserDebug) {
+ log.Println("resolvePromptMessage: IsApplyDebug or IsUserDebug - setting isFollowUp to false")
+ isFollowUp = false
+ }
+
var promptMessage *openai.ChatCompletionMessage
var lastMessage *openai.ChatCompletionMessage
diff --git a/app/server/model/plan/tell_state.go b/app/server/model/plan/tell_state.go
index f27a8d73..a7a2f03e 100644
--- a/app/server/model/plan/tell_state.go
+++ b/app/server/model/plan/tell_state.go
@@ -9,39 +9,41 @@ import (
"github.com/sashabaranov/go-openai"
)
+const NumTellStreamRetries = 4
+
type activeTellStreamState struct {
- activePlan *types.ActivePlan
- clients map[string]model.ClientInfo
- req *shared.TellPlanRequest
- auth *types.ServerAuth
- currentOrgId string
- currentUserId string
- plan *db.Plan
- branch string
- iteration int
- replyId string
- modelContext []*db.Context
- hasContextMap bool
- contextMapEmpty bool
- convo []*db.ConvoMessage
- promptConvoMessage *db.ConvoMessage
- currentPlanState *shared.CurrentPlanState
- missingFileResponse shared.RespondMissingFileChoice
- summaries []*db.ConvoSummary
- summarizedToMessageId string
- latestSummaryTokens int
- userPrompt string
- promptMessage *openai.ChatCompletionMessage
- replyParser *types.ReplyParser
- replyNumTokens int
- messages []openai.ChatCompletionMessage
- tokensBeforeConvo int
- totalRequestTokens int
- settings *shared.PlanSettings
- currentReplyNumRetries int
- subtasks []*db.Subtask
- currentSubtask *db.Subtask
- hasAssistantReply bool
+ activePlan *types.ActivePlan
+ execTellPlanParams execTellPlanParams
+ clients map[string]model.ClientInfo
+ req *shared.TellPlanRequest
+ auth *types.ServerAuth
+ currentOrgId string
+ currentUserId string
+ plan *db.Plan
+ branch string
+ iteration int
+ replyId string
+ modelContext []*db.Context
+ hasContextMap bool
+ contextMapEmpty bool
+ convo []*db.ConvoMessage
+ promptConvoMessage *db.ConvoMessage
+ currentPlanState *shared.CurrentPlanState
+ missingFileResponse shared.RespondMissingFileChoice
+ summaries []*db.ConvoSummary
+ summarizedToMessageId string
+ latestSummaryTokens int
+ userPrompt string
+ promptMessage *openai.ChatCompletionMessage
+ replyParser *types.ReplyParser
+ replyNumTokens int
+ messages []openai.ChatCompletionMessage
+ tokensBeforeConvo int
+ totalRequestTokens int
+ settings *shared.PlanSettings
+ subtasks []*db.Subtask
+ currentSubtask *db.Subtask
+ hasAssistantReply bool
isContextStage bool
isPlanningStage bool
diff --git a/app/server/model/plan/tell_stream_error.go b/app/server/model/plan/tell_stream_error.go
index d45e06ba..c585966e 100644
--- a/app/server/model/plan/tell_stream_error.go
+++ b/app/server/model/plan/tell_stream_error.go
@@ -6,12 +6,31 @@ import (
"log"
"net/http"
"plandex-server/db"
+ "strconv"
+ "time"
"github.com/plandex/plandex/shared"
)
-func (state *activeTellStreamState) onError(streamErr error, storeDesc bool, convoMessageId, commitMsg string) {
- log.Printf("\nStream error: %v\n", streamErr)
+type onErrorParams struct {
+ streamErr error
+ storeDesc bool
+ convoMessageId string
+ commitMsg string
+ canRetry bool
+}
+
+type onErrorResult struct {
+ shouldContinueMainLoop bool
+ shouldReturn bool
+}
+
+func (state *activeTellStreamState) onError(params onErrorParams) onErrorResult {
+ log.Printf("\nStream error: %v\n", params.streamErr)
+ streamErr := params.streamErr
+ storeDesc := params.storeDesc
+ convoMessageId := params.convoMessageId
+ commitMsg := params.commitMsg
planId := state.plan.Id
branch := state.branch
@@ -19,10 +38,43 @@ func (state *activeTellStreamState) onError(streamErr error, storeDesc bool, con
summarizedToMessageId := state.summarizedToMessageId
active := GetActivePlan(planId, branch)
+ numRetries := state.execTellPlanParams.numErrorRetry
if active == nil {
log.Printf("tellStream onError - Active plan not found for plan ID %s on branch %s\n", planId, branch)
- return
+ return onErrorResult{
+ shouldReturn: true,
+ }
+ }
+
+ canRetry := params.canRetry
+
+ if canRetry {
+ if numRetries >= NumTellStreamRetries {
+ log.Printf("tellStream onError - Max retries reached for plan ID %s on branch %s\n", planId, branch)
+
+ canRetry = false
+ }
+ }
+
+ if canRetry {
+ // stop stream via context (ensures we stop child streams too)
+ active.CancelModelStreamFn()
+
+ active.ResetModelCtx()
+
+ retryDelaySeconds := 1 * numRetries * (numRetries / 2)
+
+ log.Printf("tellStream onError - Retry %d/%d - Retrying stream in %d seconds", numRetries+1, NumTellStreamRetries, retryDelaySeconds)
+ time.Sleep(time.Duration(retryDelaySeconds) * time.Second)
+
+ params := state.execTellPlanParams
+ params.numErrorRetry = numRetries + 1
+
+ execTellPlan(params)
+ return onErrorResult{
+ shouldReturn: true,
+ }
}
storeDescAndReply := func() error {
@@ -105,10 +157,19 @@ func (state *activeTellStreamState) onError(streamErr error, storeDesc bool, con
storeDescAndReply()
+ msg := "Stream error: " + streamErr.Error()
+ if params.canRetry && numRetries >= NumTellStreamRetries {
+ msg += " | Failed after " + strconv.Itoa(numRetries) + " retries."
+ }
+
active.StreamDoneCh <- &shared.ApiError{
Type: shared.ApiErrorTypeOther,
Status: http.StatusInternalServerError,
- Msg: "Stream error: " + streamErr.Error(),
+ Msg: msg,
+ }
+
+ return onErrorResult{
+ shouldContinueMainLoop: true,
}
}
@@ -116,5 +177,8 @@ func (state *activeTellStreamState) onActivePlanMissingError() {
planId := state.plan.Id
branch := state.branch
log.Printf("Active plan not found for plan ID %s on branch %s\n", planId, branch)
- state.onError(fmt.Errorf("active plan not found for plan ID %s on branch %s", planId, branch), true, "", "")
+ state.onError(onErrorParams{
+ streamErr: fmt.Errorf("active plan not found for plan ID %s on branch %s", planId, branch),
+ storeDesc: true,
+ })
}
diff --git a/app/server/model/plan/tell_stream_finish.go b/app/server/model/plan/tell_stream_finish.go
index 309f179d..3e984951 100644
--- a/app/server/model/plan/tell_stream_finish.go
+++ b/app/server/model/plan/tell_stream_finish.go
@@ -56,10 +56,14 @@ func (state *activeTellStreamState) handleStreamFinished() handleStreamFinishedR
err = db.SetPlanStatus(planId, branch, shared.PlanStatusDescribing, "")
if err != nil {
- state.onError(fmt.Errorf("failed to set plan status to describing: %v", err), true, "", "")
+ res := state.onError(onErrorParams{
+ streamErr: fmt.Errorf("failed to set plan status to describing: %v", err),
+ storeDesc: true,
+ })
+
return handleStreamFinishedResult{
- shouldContinueMainLoop: true,
- shouldReturn: false,
+ shouldContinueMainLoop: res.shouldContinueMainLoop,
+ shouldReturn: res.shouldReturn,
}
}
@@ -151,10 +155,13 @@ func (state *activeTellStreamState) handleStreamFinished() handleStreamFinishedR
}
case <-time.After(30 * time.Second):
log.Println("Timeout waiting for auto load context")
- state.onError(fmt.Errorf("timeout waiting for auto load context response"), true, "", "")
+ res := state.onError(onErrorParams{
+ streamErr: fmt.Errorf("timeout waiting for auto load context response"),
+ storeDesc: true,
+ })
return handleStreamFinishedResult{
- shouldContinueMainLoop: true,
- shouldReturn: false,
+ shouldContinueMainLoop: res.shouldContinueMainLoop,
+ shouldReturn: res.shouldReturn,
}
case <-active.AutoLoadContextCh:
}
@@ -332,11 +339,14 @@ func (state *activeTellStreamState) handleDescAndExecStatus(autoLoadContextFiles
for i := 0; i < 2; i++ {
err := <-errCh
if err != nil {
- state.onError(err, true, "", "")
+ res := state.onError(onErrorParams{
+ streamErr: err,
+ storeDesc: true,
+ })
return handleDescAndExecStatusResult{
handleStreamFinishedResult: handleStreamFinishedResult{
- shouldContinueMainLoop: true,
- shouldReturn: false,
+ shouldContinueMainLoop: res.shouldContinueMainLoop,
+ shouldReturn: res.shouldReturn,
},
subtaskFinished: subtaskFinished,
shouldContinue: shouldContinue,
@@ -455,7 +465,10 @@ func (state *activeTellStreamState) storeOnFinished(params storeOnFinishedParams
assistantMsg, convoCommitMsg, err := state.storeAssistantReply(replyType) // updates state.convo
if err != nil {
- state.onError(fmt.Errorf("failed to store assistant message: %v", err), true, "", "")
+ state.onError(onErrorParams{
+ streamErr: fmt.Errorf("failed to store assistant message: %v", err),
+ storeDesc: true,
+ })
return err
}
@@ -480,7 +493,12 @@ func (state *activeTellStreamState) storeOnFinished(params storeOnFinishedParams
err = db.StoreDescription(description)
if err != nil {
- state.onError(fmt.Errorf("failed to store description: %v", err), false, assistantMsg.Id, convoCommitMsg)
+ state.onError(onErrorParams{
+ streamErr: fmt.Errorf("failed to store description: %v", err),
+ storeDesc: false,
+ convoMessageId: assistantMsg.Id,
+ commitMsg: convoCommitMsg,
+ })
return err
}
log.Println("Description stored")
@@ -500,7 +518,12 @@ func (state *activeTellStreamState) storeOnFinished(params storeOnFinishedParams
err = db.StorePlanSubtasks(currentOrgId, planId, state.subtasks)
if err != nil {
log.Printf("Error storing plan subtasks: %v\n", err)
- state.onError(fmt.Errorf("failed to store plan subtasks: %v", err), false, assistantMsg.Id, convoCommitMsg)
+ state.onError(onErrorParams{
+ streamErr: fmt.Errorf("failed to store plan subtasks: %v", err),
+ storeDesc: false,
+ convoMessageId: assistantMsg.Id,
+ commitMsg: convoCommitMsg,
+ })
return err
}
@@ -540,7 +563,12 @@ func (state *activeTellStreamState) storeOnFinished(params storeOnFinishedParams
err = db.GitAddAndCommit(currentOrgId, planId, branch, convoCommitMsg)
if err != nil {
- state.onError(fmt.Errorf("failed to commit: %v", err), false, assistantMsg.Id, convoCommitMsg)
+ state.onError(onErrorParams{
+ streamErr: fmt.Errorf("failed to commit: %v", err),
+ storeDesc: false,
+ convoMessageId: assistantMsg.Id,
+ commitMsg: convoCommitMsg,
+ })
return err
}
log.Println("Assistant reply, description, and subtasks committed")
diff --git a/app/server/model/plan/tell_stream_main.go b/app/server/model/plan/tell_stream_main.go
index fff64d06..5f605621 100644
--- a/app/server/model/plan/tell_stream_main.go
+++ b/app/server/model/plan/tell_stream_main.go
@@ -56,8 +56,17 @@ mainLoop:
state.execHookOnStop(true)
return
} else {
- state.onError(fmt.Errorf("stream timeout due to inactivity | This usually means the model is not responding."), true, "", "")
- continue mainLoop
+ res := state.onError(onErrorParams{
+ streamErr: fmt.Errorf("stream timeout due to inactivity | This usually means the model is not responding."),
+ storeDesc: true,
+ canRetry: true,
+ })
+ if res.shouldReturn {
+ return
+ }
+ if res.shouldContinueMainLoop {
+ continue mainLoop
+ }
}
default:
@@ -85,19 +94,39 @@ mainLoop:
state.generationId = response.ID
}
- if response.Usage != nil {
- state.handleUsageChunk(response.Usage)
- return
- }
-
if len(response.Choices) == 0 {
- state.onError(fmt.Errorf("stream finished with no choices | This usually means the model failed to generate a valid response."), true, "", "")
- continue mainLoop
+ if response.Usage != nil {
+ state.handleUsageChunk(response.Usage)
+ return
+ }
+
+ res := state.onError(onErrorParams{
+ streamErr: fmt.Errorf("stream finished with no choices | This usually means the model failed to generate a valid response."),
+ storeDesc: true,
+ canRetry: true,
+ })
+ if res.shouldReturn {
+ return
+ }
+ if res.shouldContinueMainLoop {
+ // continue instead of returning so that context cancellation is handled
+ continue mainLoop
+ }
}
if len(response.Choices) > 1 {
- state.onError(fmt.Errorf("stream finished with more than one choice | This usually means the model failed to generate a valid response."), true, "", "")
- continue mainLoop
+ res := state.onError(onErrorParams{
+ streamErr: fmt.Errorf("stream finished with more than one choice | This usually means the model failed to generate a valid response."),
+ storeDesc: true,
+ canRetry: true,
+ })
+ if res.shouldReturn {
+ return
+ }
+ if res.shouldContinueMainLoop {
+ // continue instead of returning so that context cancellation is handled
+ continue mainLoop
+ }
}
choice := response.Choices[0]
@@ -112,8 +141,17 @@ mainLoop:
log.Println("Finish reason: ", choice.FinishReason)
if choice.FinishReason == "error" {
- state.onError(fmt.Errorf("model stopped with error status | This usually means the model is not responding."), true, "", "")
- continue mainLoop
+ res := state.onError(onErrorParams{
+ streamErr: fmt.Errorf("model stopped with error status | This usually means the model is not responding."),
+ storeDesc: true,
+ canRetry: true,
+ })
+ if res.shouldReturn {
+ return
+ }
+ if res.shouldContinueMainLoop {
+ continue mainLoop
+ }
}
streamFinishResult := state.handleStreamFinished()
@@ -139,6 +177,9 @@ mainLoop:
timer.Reset(model.OPENAI_USAGE_CHUNK_TIMEOUT)
streamFinished = true
continue
+ } else if response.Usage != nil {
+ state.handleUsageChunk(response.Usage)
+ return
}
// let main loop continue
}
diff --git a/app/server/model/plan/tell_stream_processor.go b/app/server/model/plan/tell_stream_processor.go
index fa638dc5..3ec66f33 100644
--- a/app/server/model/plan/tell_stream_processor.go
+++ b/app/server/model/plan/tell_stream_processor.go
@@ -19,18 +19,6 @@ const verboseLogging = false
var openingTagRegex = regexp.MustCompile(`<PlandexBlock\s+lang="(.+?)"\s+path="(.+?)".*?>`)
-// matches any prefix of the opening tag
-var partialOpeningTagRegex = regexp.MustCompile(
- `^` +
- // 1) Nested optional groups for "PlandexBlock":
- `P(?:l(?:a(?:n(?:d(?:e(?:x(?:B(?:l(?:o(?:c(?:k)?)?)?)?)?)?)?)?)?)?)?` +
- // 2) Optional lang="..." (with optional final quote):
- `(?:\s+lang="[^"]*(?:")?)?` +
- // 3) Optional path="..." (with optional final quote):
- `(?:\s+path="[^"]*(?:")?)?` +
- `$`,
-)
-
type processChunkResult struct {
shouldReturn bool
}
@@ -205,31 +193,9 @@ func (processor *chunkProcessor) bufferOrStream(content string, parserRes *types
if verboseLogging {
log.Println("processor.awaitingBlockOpeningTag")
}
- split := strings.Split(content, "<")
var matchedPrefix bool
- if len(split) > 1 {
- last := split[len(split)-1]
- if verboseLogging {
- log.Printf("last: %s\n", last)
- }
- if partialOpeningTagRegex.MatchString(last) {
- if verboseLogging {
- log.Println("partialOpeningTagRegex.MatchString(last)")
- }
- shouldStream = false
- matchedPrefix = true
- } else {
- if verboseLogging {
- log.Println("partialOpeningTagRegex.MatchString(last) is false")
- }
- }
- }
- if !matchedPrefix && parserRes.MaybeFilePath == "" && parserRes.CurrentFilePath == "" {
- // wasn't really a file path / code block
- processor.awaitingBlockOpeningTag = false
- shouldStream = true
- } else if parserRes.CurrentFilePath != "" {
+ if parserRes.CurrentFilePath != "" {
matched, replaced := replaceCodeBlockOpeningTag(content, func(lang string) string {
blockLang = lang
return "```" + lang
@@ -250,6 +216,38 @@ func (processor *chunkProcessor) bufferOrStream(content string, parserRes *types
content += "\n```" // add ``` to the end of the line to close the markdown code block
shouldStream = true
}
+ } else {
+ split := strings.Split(content, "<")
+
+ if len(split) > 1 {
+ last := split[len(split)-1]
+ if verboseLogging {
+ log.Printf("last: %s\n", last)
+ }
+ if strings.HasPrefix(`PlandexBlock lang="`, last) {
+ if verboseLogging {
+ log.Println("strings.HasPrefix(`PlandexBlock lang=", last)
+ }
+ shouldStream = false
+ matchedPrefix = true
+ } else if strings.HasPrefix(last, `PlandexBlock lang="`) {
+ if verboseLogging {
+ log.Println("partialOpeningTagRegex.MatchString(last)")
+ }
+ shouldStream = false
+ matchedPrefix = true
+ } else {
+ if verboseLogging {
+ log.Println("partialOpeningTagRegex.MatchString(last) is false")
+ }
+ }
+ }
+ }
+
+ if !matchedPrefix && parserRes.MaybeFilePath == "" && parserRes.CurrentFilePath == "" {
+ // wasn't really a file path / code block
+ processor.awaitingBlockOpeningTag = false
+ shouldStream = true
}
} else if processor.awaitingBlockClosingTag {
if parserRes.CurrentFilePath == "" {
@@ -288,10 +286,15 @@ func (processor *chunkProcessor) bufferOrStream(content string, parserRes *types
if parserRes.MaybeFilePath != "" && parserRes.CurrentFilePath == "" {
processor.awaitingBlockOpeningTag = true
} else {
+ // this will set processor.awaitingBlockOpeningTag to true if the content starts with any prefix of<PlandexBlock lang=" *or* any prefix of a full opening tag
+ // if the full tag is in the content, it will later get set to false again when the full tag is handled
split := strings.Split(content, "<")
if len(split) > 1 {
last := split[len(split)-1]
- if partialOpeningTagRegex.MatchString(last) {
+
+ if strings.HasPrefix(`PlandexBlock lang="`, last) {
+ processor.awaitingBlockOpeningTag = true
+ } else if strings.HasPrefix(last, `PlandexBlock lang="`) {
processor.awaitingBlockOpeningTag = true
}
}
@@ -391,6 +394,7 @@ func (processor *chunkProcessor) bufferOrStream(content string, parserRes *types
}
if matchedOpeningTag {
+ processor.awaitingBlockOpeningTag = false
content = replaced
}
}
@@ -592,7 +596,10 @@ func (state *activeTellStreamState) handleMissingFile(content, currentFile, bloc
case <-time.After(30 * time.Minute): // long timeout here since we're waiting for user input
log.Println("Timeout waiting for missing file choice")
- state.onError(fmt.Errorf("timeout waiting for missing file choice"), true, "", "")
+ state.onError(onErrorParams{
+ streamErr: fmt.Errorf("timeout waiting for missing file choice"),
+ storeDesc: true,
+ })
return processChunkResult{}
case userChoice = <-active.MissingFileResponseCh:
diff --git a/app/server/model/plan/tell_sys_prompt.go b/app/server/model/plan/tell_sys_prompt.go
index 10f6e181..2ebf19fc 100644
--- a/app/server/model/plan/tell_sys_prompt.go
+++ b/app/server/model/plan/tell_sys_prompt.go
@@ -25,15 +25,21 @@ func (state *activeTellStreamState) getTellSysPrompt(autoContextEnabled, smartCo
if isPlanningStage {
log.Println("isPlanningStage")
+ log.Println("autoContextEnabled", autoContextEnabled)
+ log.Println("isContextStage", isContextStage)
if autoContextEnabled && isContextStage {
+ log.Println("autoContextEnabled && isContextStage -- adding auto context preamble")
sysCreate = prompts.AutoContextTellPreamble
} else if autoContextEnabled || smartContextEnabled {
+ log.Println("autoContextEnabled || smartContextEnabled -- adding auto context preamble")
sysCreate = prompts.SysPlanningAutoContext
- if isFollowUp {
+ if isFollowUp && !req.IsApplyDebug && !req.IsUserDebug {
+ log.Println("isFollowUp && !req.IsApplyDebug && !req.IsUserDebug -- adding follow up classifier prompt")
sysCreate = prompts.FollowUpPlanClassifierPrompt + "\n\n" + sysCreate
}
} else {
+ log.Println("sysPlanningBasic")
sysCreate = prompts.SysPlanningBasic
}
} else {
diff --git a/app/server/model/prompts/build.go b/app/server/model/prompts/build.go
index 3ad2ec9f..0b96c179 100644
--- a/app/server/model/prompts/build.go
+++ b/app/server/model/prompts/build.go
@@ -61,7 +61,10 @@ func GetValidateEditsPrompt(params ValidateEditsPromptParams) string {
if len(syntaxErrors) > 0 {
editsIncorrect = true
- s += `The proposed changes, when applied, resulted in a file with syntax errors, meaning the proposed changes were either written incorrectly or were not correctly applied. The resulting file has the following syntax errors:\n\n` + strings.Join(syntaxErrors, "\n") + `\n\n`
+ s += `The proposed changes, when applied, resulted in a file with syntax errors, meaning the proposed changes were either written incorrectly or were not correctly applied. The resulting file has the following syntax errors:\n\n` + strings.Join(syntaxErrors, "\n") + `
+
+ In your evaluation step, include an assessment of what caused the syntax errors.
+ `
}
if fullCorrection {
@@ -81,19 +84,26 @@ func GetValidateEditsPrompt(params ValidateEditsPromptParams) string {
s += ValidateOnlyExample
}
+ s += `You will examine ONLY whether the changes were correctly applied according to the proposed changes explanation. Do NOT evaluate code quality, best practices, or potential issues - focus solely on whether the applied changes match what was proposed.`
+
return s
}
const EditsValidateBasePrompt = `
-Your task is to examine the applied changes diff and output EXACTLY ONE of these patterns:
-
-Your evaluation should assess:
-a. Whether any code was removed that should have been kept
-b. Whether any code was duplicated that should not have been
-c. Whether any code was incorrectly inserted or replaced
-d. Whether any code was inserted at the wrong location
-
-Be succinct—do not add additional text or summarize the changes beyond what is necessary.
+Your task is to ONLY examine whether the changes were applied as described in the proposed changes explanation. Do NOT evaluate:
+- Code quality
+- Missing imports
+- Unused variables
+- Best practices
+- Potential bugs
+- Syntax (unless syntax errors have been previously specified)
+
+Your evaluation should ONLY assess:
+a. Whether the changes were applied at the correct location as specified
+b. Whether the changes included all the specified additions/modifications
+c. Whether any unintended changes were made to surrounding code
+d. Whether any specified code was accidentally removed or duplicated
+e. Any syntax errors that have been previously specified
`
const EditsValidateCorrectPattern = `
diff --git a/app/server/types/active_plan.go b/app/server/types/active_plan.go
index a37e1e7b..8ef18865 100644
--- a/app/server/types/active_plan.go
+++ b/app/server/types/active_plan.go
@@ -181,9 +181,13 @@ func (ap *ActivePlan) FlushStreamBuffer() {
}
}
+const verboseStreamLogging = false
+
func (ap *ActivePlan) Stream(msg shared.StreamMessage) {
- // log.Println("ActivePlan.Stream:")
- // log.Println(msg)
+ if verboseStreamLogging {
+ log.Println("ActivePlan.Stream:")
+ log.Println(msg)
+ }
ap.streamMu.Lock()
@@ -194,17 +198,23 @@ func (ap *ActivePlan) Stream(msg shared.StreamMessage) {
// Special messages bypass buffering
if !skipBuffer {
- // log.Println("ActivePlan.Stream: time since last message sent:", time.Since(ap.lastStreamMessageSent))
+ if verboseStreamLogging {
+ log.Println("ActivePlan.Stream: time since last message sent:", time.Since(ap.lastStreamMessageSent))
+ }
if time.Since(ap.lastStreamMessageSent) < MaxStreamRate {
- // log.Println("ActivePlan.Stream: buffering message")
+ if verboseStreamLogging {
+ log.Println("ActivePlan.Stream: buffering message")
+ }
// Buffer the message
ap.streamMessageBuffer = append(ap.streamMessageBuffer, msg)
ap.streamMu.Unlock()
return
} else if len(ap.streamMessageBuffer) > 0 {
- // log.Println("ActivePlan.Stream: flushing buffer")
+ if verboseStreamLogging {
+ log.Println("ActivePlan.Stream: flushing buffer")
+ }
// Need to flush buffer first
ap.streamMessageBuffer = append(ap.streamMessageBuffer, msg)
@@ -212,9 +222,10 @@ func (ap *ActivePlan) Stream(msg shared.StreamMessage) {
ap.streamMessageBuffer = []shared.StreamMessage{}
ap.streamMu.Unlock()
- // log.Println("ActivePlan.Stream: sending multi-message:")
- // log.Println(bufferToFlush)
-
+ if verboseStreamLogging {
+ log.Println("ActivePlan.Stream: sending multi-message:")
+ log.Println(bufferToFlush)
+ }
// Send as multi-message
ap.Stream(shared.StreamMessage{
Type: shared.StreamMessageMulti,
@@ -273,8 +284,10 @@ func (ap *ActivePlan) Stream(msg shared.StreamMessage) {
}
}
- // log.Println("ActivePlan.Stream: sending direct message")
- // log.Println(string(msgJson))
+ if verboseStreamLogging {
+ log.Println("ActivePlan.Stream: sending direct message")
+ log.Println(string(msgJson))
+ }
ap.streamCh <- string(msgJson)
diff --git a/app/shared/ai_models_available.go b/app/shared/ai_models_available.go
index dcf78896..7d6f5dfc 100644
--- a/app/shared/ai_models_available.go
+++ b/app/shared/ai_models_available.go
@@ -65,6 +65,7 @@ var AvailableModels = []*AvailableModel{
BaseUrl: OpenAIV1BaseUrl,
PreferredModelOutputFormat: ModelOutputFormatToolCallJson,
RoleParamsDisabled: true,
+ ReasoningEffortEnabled: true,
},
},
{
diff --git a/app/shared/ai_models_data_models.go b/app/shared/ai_models_data_models.go
index e64fcd1a..03caecee 100644
--- a/app/shared/ai_models_data_models.go
+++ b/app/shared/ai_models_data_models.go
@@ -31,6 +31,7 @@ type BaseModelConfig struct {
SystemPromptDisabled bool `json:"systemPromptDisabled"`
RoleParamsDisabled bool `json:"roleParamsDisabled"`
PredictedOutputEnabled bool `json:"predictedOutputEnabled"`
+ ReasoningEffortEnabled bool `json:"reasoningEffortEnabled"`
ModelCompatibility
}
@@ -49,14 +50,24 @@ type PlannerModelConfig struct {
MaxConvoTokens int `json:"maxConvoTokens"`
}
+type ReasoningEffort string
+
+const (
+ ReasoningEffortLow ReasoningEffort = "low"
+ ReasoningEffortMedium ReasoningEffort = "medium"
+ ReasoningEffortHigh ReasoningEffort = "high"
+)
+
type ModelRoleConfig struct {
Role ModelRole `json:"role"`
BaseModelConfig BaseModelConfig `json:"baseModelConfig"`
Temperature float32 `json:"temperature"`
TopP float32 `json:"topP"`
ReservedOutputTokens int `json:"reservedOutputTokens"`
+ ReasoningEffort ReasoningEffort `json:"reasoningEffort"`
LargeContextFallback *ModelRoleConfig `json:"largeContextFallback"`
+ LargeOutputFallback *ModelRoleConfig `json:"largeOutputFallback"`
// ErrorFallback *ModelRoleConfig `json:"errorFallback"`
}
@@ -106,12 +117,35 @@ func (m ModelRoleConfig) GetFinalLargeContextFallback() ModelRoleConfig {
return currentConfig
}
+func (m ModelRoleConfig) GetFinalLargeOutputFallback() ModelRoleConfig {
+ var currentConfig ModelRoleConfig = m
+ var n int = 0
+
+ if currentConfig.LargeOutputFallback == nil {
+ return currentConfig.GetFinalLargeContextFallback()
+ }
+
+ for {
+ if currentConfig.LargeOutputFallback == nil {
+ return currentConfig
+ } else {
+ currentConfig = *currentConfig.LargeOutputFallback
+ }
+ n++
+ if n > maxFallbackDepth {
+ break
+ }
+ }
+
+ return currentConfig
+}
+
// note that if the token number exeeds all the fallback models, it will return the last fallback model
-func (m ModelRoleConfig) GetRoleForTokens(tokens int) ModelRoleConfig {
+func (m ModelRoleConfig) GetRoleForInputTokens(inputTokens int) ModelRoleConfig {
var currentConfig ModelRoleConfig = m
var n int = 0
for {
- if currentConfig.BaseModelConfig.MaxTokens >= tokens {
+ if currentConfig.BaseModelConfig.MaxTokens >= inputTokens {
return currentConfig
}
@@ -128,6 +162,31 @@ func (m ModelRoleConfig) GetRoleForTokens(tokens int) ModelRoleConfig {
return currentConfig
}
+func (m ModelRoleConfig) GetRoleForOutputTokens(outputTokens int) ModelRoleConfig {
+ var currentConfig ModelRoleConfig = m
+ var n int = 0
+ for {
+ if currentConfig.GetReservedOutputTokens() >= outputTokens {
+ return currentConfig
+ }
+
+ if currentConfig.LargeOutputFallback == nil {
+ if currentConfig.LargeContextFallback == nil {
+ return currentConfig
+ } else {
+ currentConfig = *currentConfig.LargeContextFallback
+ }
+ } else {
+ currentConfig = *currentConfig.LargeOutputFallback
+ }
+ n++
+ if n > maxFallbackDepth {
+ break
+ }
+ }
+ return currentConfig
+}
+
type PlannerRoleConfig struct {
ModelRoleConfig
PlannerModelConfig
diff --git a/app/shared/ai_models_packs.go b/app/shared/ai_models_packs.go
index 524de5b0..99fddba5 100644
--- a/app/shared/ai_models_packs.go
+++ b/app/shared/ai_models_packs.go
@@ -24,35 +24,38 @@ func init() {
ModelRoleConfig: *claude35sonnet(ModelRolePlanner, nil),
PlannerModelConfig: getPlannerModelConfig(ModelProviderOpenRouter, "anthropic/claude-3.5-sonnet"),
PlannerLargeContextFallback: &PlannerRoleConfig{
- ModelRoleConfig: *gemini15pro(ModelRolePlanner, nil),
- PlannerModelConfig: getPlannerModelConfig(ModelProviderOpenRouter, "google/gemini-pro-1.5"),
+ ModelRoleConfig: *gemini15pro(ModelRolePlanner, nil),
+ PlannerModelConfig: PlannerModelConfig{
+ // Use the same max convo tokens as the default model so we don't mess with summarization too much
+ MaxConvoTokens: GetAvailableModel(ModelProviderOpenRouter, "anthropic/claude-3.5-sonnet").DefaultMaxConvoTokens,
+ },
},
},
Coder: claude35sonnet(ModelRoleCoder, nil),
ContextLoader: claude35sonnet(ModelRoleContextLoader, &modelConfigFallbacks{
largeContextFallback: gemini15pro(ModelRoleContextLoader, nil),
}),
- PlanSummary: *openaio3mini(ModelRolePlanSummary, nil),
- Builder: *openaio3mini(ModelRoleBuilder, nil),
- WholeFileBuilder: openaio3mini(ModelRoleWholeFileBuilder, nil),
+ PlanSummary: *openaio3mini(ModelRolePlanSummary, ReasoningEffortLow, nil),
+ Builder: *openaio3mini(ModelRoleBuilder, ReasoningEffortMedium, nil),
+ WholeFileBuilder: openaio3mini(ModelRoleWholeFileBuilder, ReasoningEffortLow, nil),
Namer: *openai4omini(ModelRoleName, nil),
CommitMsg: *openai4omini(ModelRoleCommitMsg, nil),
- ExecStatus: *openaio3mini(ModelRoleExecStatus, nil),
+ ExecStatus: *openaio3mini(ModelRoleExecStatus, ReasoningEffortMedium, nil),
}
O3MiniModelPack = ModelPack{
Name: "o3-mini-pack",
Description: "OpenAI blend. Supports up to 200k context. Uses OpenAI's o3-mini model for heavy lifting, GPT-4o Mini for lighter tasks.",
Planner: PlannerRoleConfig{
- ModelRoleConfig: *openaio3mini(ModelRolePlanner, nil),
+ ModelRoleConfig: *openaio3mini(ModelRolePlanner, ReasoningEffortHigh, nil),
PlannerModelConfig: getPlannerModelConfig(ModelProviderOpenAI, "o3-mini"),
},
- PlanSummary: *openaio3mini(ModelRolePlanSummary, nil),
- Builder: *openaio3mini(ModelRoleBuilder, nil),
- WholeFileBuilder: openaio3mini(ModelRoleWholeFileBuilder, nil),
+ PlanSummary: *openaio3mini(ModelRolePlanSummary, ReasoningEffortLow, nil),
+ Builder: *openaio3mini(ModelRoleBuilder, ReasoningEffortMedium, nil),
+ WholeFileBuilder: openaio3mini(ModelRoleWholeFileBuilder, ReasoningEffortMedium, nil),
Namer: *openai4omini(ModelRoleName, nil),
CommitMsg: *openai4omini(ModelRoleCommitMsg, nil),
- ExecStatus: *openai4o(ModelRoleExecStatus, nil),
+ ExecStatus: *openaio3mini(ModelRoleExecStatus, ReasoningEffortMedium, nil),
}
ClaudeModelPack = ModelPack{
@@ -72,7 +75,8 @@ func init() {
type modelConfigFallbacks struct {
largeContextFallback *ModelRoleConfig
- errorFallback *ModelRoleConfig
+ largeOutputFallback *ModelRoleConfig
+ // errorFallback *ModelRoleConfig
}
func getModelConfig(role ModelRole, provider ModelProvider, modelName string, fallbacks *modelConfigFallbacks) *ModelRoleConfig {
@@ -87,21 +91,31 @@ func getModelConfig(role ModelRole, provider ModelProvider, modelName string, fa
TopP: DefaultConfigByRole[role].TopP,
LargeContextFallback: fallbacks.largeContextFallback,
+ LargeOutputFallback: fallbacks.largeOutputFallback,
// ErrorFallback: fallbacks.errorFallback,
}
}
// allow OpenAI calls to first try OpenAI directly, then fallback to OpenRouter (which can route to Azure if OpenAI is down)
-func getOpenAIModelConfig(role ModelRole, modelName string, fallbacks *modelConfigFallbacks) *ModelRoleConfig {
+func getOpenAIModelConfig(role ModelRole, modelName string, reasoningEffort ReasoningEffort, fallbacks *modelConfigFallbacks) *ModelRoleConfig {
var largeContextFallback *ModelRoleConfig
+ var largeOutputFallback *ModelRoleConfig
if fallbacks != nil {
largeContextFallback = fallbacks.largeContextFallback
+ largeOutputFallback = fallbacks.largeOutputFallback
}
- return getModelConfig(role, ModelProviderOpenAI, modelName, &modelConfigFallbacks{
+ config := getModelConfig(role, ModelProviderOpenAI, modelName, &modelConfigFallbacks{
largeContextFallback: largeContextFallback,
- errorFallback: getModelConfig(role, ModelProviderOpenRouter, "openai/gpt-4o", nil),
+ largeOutputFallback: largeOutputFallback,
+ // errorFallback: getModelConfig(role, ModelProviderOpenRouter, "openai/gpt-4o", nil),
})
+
+ if reasoningEffort != "" {
+ config.ReasoningEffort = reasoningEffort
+ }
+
+ return config
}
func claude35sonnet(role ModelRole, fallbacks *modelConfigFallbacks) *ModelRoleConfig {
@@ -117,17 +131,17 @@ func gemini15pro(role ModelRole, fallbacks *modelConfigFallbacks) *ModelRoleConf
}
func openai4o(role ModelRole, fallbacks *modelConfigFallbacks) *ModelRoleConfig {
- return getOpenAIModelConfig(role, "gpt-4o", fallbacks)
+ return getOpenAIModelConfig(role, "gpt-4o", "", fallbacks)
}
func openai4omini(role ModelRole, fallbacks *modelConfigFallbacks) *ModelRoleConfig {
- return getOpenAIModelConfig(role, "gpt-4o-mini", fallbacks)
+ return getOpenAIModelConfig(role, "gpt-4o-mini", "", fallbacks)
}
func openaio1mini(role ModelRole, fallbacks *modelConfigFallbacks) *ModelRoleConfig {
- return getOpenAIModelConfig(role, "o1-mini", fallbacks)
+ return getOpenAIModelConfig(role, "o1-mini", "", fallbacks)
}
-func openaio3mini(role ModelRole, fallbacks *modelConfigFallbacks) *ModelRoleConfig {
- return getOpenAIModelConfig(role, "o3-mini", fallbacks)
+func openaio3mini(role ModelRole, reasoningEffort ReasoningEffort, fallbacks *modelConfigFallbacks) *ModelRoleConfig {
+ return getOpenAIModelConfig(role, "o3-mini", reasoningEffort, fallbacks)
}
diff --git a/app/shared/plan_model_settings.go b/app/shared/plan_model_settings.go
index cd16da25..b31d0b29 100644
--- a/app/shared/plan_model_settings.go
+++ b/app/shared/plan_model_settings.go
@@ -82,10 +82,10 @@ func (ps PlanSettings) GetWholeFileBuilderMaxReservedOutputTokens() int {
if ps.ModelOverrides.MaxTokens == nil {
if ps.ModelPack == nil {
defaultBuilder := DefaultModelPack.WholeFileBuilder
- return defaultBuilder.GetFinalLargeContextFallback().GetReservedOutputTokens()
+ return defaultBuilder.GetFinalLargeOutputFallback().GetReservedOutputTokens()
} else {
builder := ps.ModelPack.WholeFileBuilder
- return builder.GetFinalLargeContextFallback().GetReservedOutputTokens()
+ return builder.GetFinalLargeOutputFallback().GetReservedOutputTokens()
}
} else {
return *ps.ModelOverrides.MaxTokens
diff --git a/plandex-cursor.code-workspace b/plandex-cursor.code-workspace
index 233d7237..71834411 100644
--- a/plandex-cursor.code-workspace
+++ b/plandex-cursor.code-workspace
@@ -42,6 +42,12 @@
},
{
"path": "../go-prompt"
+ },
+ {
+ "path": "../survey"
+ },
+ {
+ "path": "../bubbletea"
}
],
"settings": {