Open source AI coding agent. Designed for large projects and real world tasks.
Go aiai-agentsai-developer-toolsai-toolsclicommand-linedeveloper-toolsgitgolanggpt-4llmopenaipolyglot-programmingterminalterminal-basedterminal-ui
Refactor plan config system and add file map caching. Move config to plans/users tables, add default configs, implement project-level file map cache for performance, update CLI commands for consistency, and improve context loading with better progress feedback.
Dane Schneiderd97a8ebd2320
diff --git a/app/cli/api/methods.go b/app/cli/api/methods.goindex 7a32d70b..0d35085c 100644--- a/app/cli/api/methods.go+++ b/app/cli/api/methods.go@@ -1054,6 +1054,34 @@ func (a *Api) ListContext(planId, branch string) ([]*shared.Context, *shared.Apireturn contexts, nil}+func (a *Api) LoadCachedFileMap(planId, branch string, req shared.LoadCachedFileMapRequest) (*shared.LoadCachedFileMapResponse, *shared.ApiError) {+ serverUrl := fmt.Sprintf("%s/plans/%s/%s/load_cached_file_map", GetApiHost(), planId, branch)+ reqBytes, err := json.Marshal(req)+ if err != nil {+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error marshalling request: %v", err)}+ }++ resp, err := authenticatedFastClient.Post(serverUrl, "application/json", bytes.NewBuffer(reqBytes))+ if err != nil {+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %v", err)}+ }+ defer resp.Body.Close()++ if resp.StatusCode >= 400 {+ errorBody, _ := io.ReadAll(resp.Body)+ apiErr := HandleApiError(resp, errorBody)+ return nil, apiErr+ }++ var loadResp shared.LoadCachedFileMapResponse+ err = json.NewDecoder(resp.Body).Decode(&loadResp)+ if err != nil {+ return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error decoding response: %v", err)}+ }++ return &loadResp, nil+}+func (a *Api) ListConvo(planId, branch string) ([]*shared.ConvoMessage, *shared.ApiError) {serverUrl := fmt.Sprintf("%s/plans/%s/%s/convo", GetApiHost(), planId, branch)@@ -1916,23 +1944,23 @@ func (a *Api) GetPlanConfig(planId string) (*shared.PlanConfig, *shared.ApiErrorreturn res.Config, nil}-func (a *Api) UpdatePlanConfig(planId string, req shared.UpdatePlanConfigRequest) (*shared.UpdatePlanConfigResponse, *shared.ApiError) {+func (a *Api) UpdatePlanConfig(planId string, req shared.UpdatePlanConfigRequest) *shared.ApiError {serverUrl := fmt.Sprintf("%s/plans/%s/config", GetApiHost(), planId)reqBytes, err := json.Marshal(req)if err != nil {- return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error marshalling request: %v", err)}+ return &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error marshalling request: %v", err)}}request, err := http.NewRequest(http.MethodPut, serverUrl, bytes.NewBuffer(reqBytes))if err != nil {- return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error creating request: %v", err)}+ return &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error creating request: %v", err)}}request.Header.Set("Content-Type", "application/json")resp, err := authenticatedFastClient.Do(request)if err != nil {- return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %v", err)}+ return &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %v", err)}}defer resp.Body.Close()@@ -1943,16 +1971,10 @@ func (a *Api) UpdatePlanConfig(planId string, req shared.UpdatePlanConfigRequestif tokenRefreshed {return a.UpdatePlanConfig(planId, req)}- return nil, apiErr- }-- var res shared.UpdatePlanConfigResponse- err = json.NewDecoder(resp.Body).Decode(&res)- if err != nil {- return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error decoding response: %v", err)}+ return apiErr}- return &res, nil+ return nil}func (a *Api) GetDefaultPlanConfig() (*shared.PlanConfig, *shared.ApiError) {@@ -1983,23 +2005,23 @@ func (a *Api) GetDefaultPlanConfig() (*shared.PlanConfig, *shared.ApiError) {return res.Config, nil}-func (a *Api) UpdateDefaultPlanConfig(req shared.UpdateDefaultPlanConfigRequest) (*shared.UpdateDefaultPlanConfigResponse, *shared.ApiError) {+func (a *Api) UpdateDefaultPlanConfig(req shared.UpdateDefaultPlanConfigRequest) *shared.ApiError {serverUrl := fmt.Sprintf("%s/default_plan_config", GetApiHost())reqBytes, err := json.Marshal(req)if err != nil {- return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error marshalling request: %v", err)}+ return &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error marshalling request: %v", err)}}request, err := http.NewRequest(http.MethodPut, serverUrl, bytes.NewBuffer(reqBytes))if err != nil {- return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error creating request: %v", err)}+ return &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error creating request: %v", err)}}request.Header.Set("Content-Type", "application/json")resp, err := authenticatedFastClient.Do(request)if err != nil {- return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %v", err)}+ return &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error sending request: %v", err)}}defer resp.Body.Close()@@ -2010,16 +2032,10 @@ func (a *Api) UpdateDefaultPlanConfig(req shared.UpdateDefaultPlanConfigRequest)if tokenRefreshed {return a.UpdateDefaultPlanConfig(req)}- return nil, apiErr- }-- var res shared.UpdateDefaultPlanConfigResponse- err = json.NewDecoder(resp.Body).Decode(&res)- if err != nil {- return nil, &shared.ApiError{Type: shared.ApiErrorTypeOther, Msg: fmt.Sprintf("error decoding response: %v", err)}+ return apiErr}- return &res, nil+ return nil}func (a *Api) CreateCustomModel(model *shared.AvailableModel) *shared.ApiError {diff --git a/app/cli/cmd/build.go b/app/cli/cmd/build.goindex 8508360d..a17034ab 100644--- a/app/cli/cmd/build.go+++ b/app/cli/cmd/build.go@@ -22,67 +22,20 @@ var buildCmd = &cobra.Command{func init() {RootCmd.AddCommand(buildCmd)- buildCmd.Flags().BoolVar(&tellBg, "bg", false, "Execute autonomously in the background")- buildCmd.Flags().BoolVarP(&autoConfirm, "yes", "y", false, "Automatically confirm context updates")- buildCmd.Flags().BoolVarP(&tellAutoApply, "apply", "a", false, "Automatically apply changes (and confirm context updates)")- buildCmd.Flags().BoolVarP(&autoCommit, "commit", "c", false, "Commit changes to git when --apply/-a is passed")- buildCmd.Flags().BoolVar(&noExec, "no-exec", false, "Disable command execution")- buildCmd.Flags().BoolVar(&autoExec, "auto-exec", false, "Automatically execute commands without confirmation when --apply is passed")- buildCmd.Flags().Var(newAutoDebugValue(&autoDebug), "debug", "Automatically execute and debug failing commands (optionally specify number of tries—default is 5)")+ initExecFlags(buildCmd, initExecFlagsParams{+ omitFile: true,+ omitNoBuild: true,+ omitEditor: true,+ omitStop: true,+ omitAutoContext: true,+ })}func build(cmd *cobra.Command, args []string) {- validateTellFlags()-- var config *shared.PlanConfig- if lib.CurrentPlanId != "" {- term.StartSpinner("")- var err error- config, err = api.Client.GetPlanConfig(lib.CurrentPlanId)- term.StopSpinner()-- if err != nil {- term.OutputErrorAndExit("Error getting plan config: %v", err)- }- } else {- term.StartSpinner("")- var err error- config, err = api.Client.GetDefaultPlanConfig()- term.StopSpinner()-- if err != nil {- term.OutputErrorAndExit("Error getting default plan config: %v", err)- }- }-- // Override config with flags- if cmd.Flags().Changed("yes") {- config.AutoContext = autoConfirm- }- if cmd.Flags().Changed("apply") {- config.AutoApply = tellAutoApply- }- if cmd.Flags().Changed("commit") {- config.AutoCommit = autoCommit- }- if cmd.Flags().Changed("no-exec") {- config.NoExec = noExec- }- if cmd.Flags().Changed("auto-exec") {- config.AutoDebug = autoExec- }- if cmd.Flags().Changed("debug") {- config.AutoDebug = true- config.AutoDebugTries = autoDebug- }-auth.MustResolveAuthWithOrg()lib.MustResolveProject()-- if lib.CurrentPlanId == "" {- term.OutputNoCurrentPlanErrorAndExit()- }+ mustSetPlanExecFlags(cmd)var apiKeys map[string]stringif !auth.Current.IntegratedModelsMode {@@ -94,7 +47,7 @@ func build(cmd *cobra.Command, args []string) {CurrentBranch: lib.CurrentBranch,ApiKeys: apiKeys,CheckOutdatedContext: func(maybeContexts []*shared.Context) (bool, bool, error) {- return lib.CheckOutdatedContextWithOutput(false, config.AutoContext, maybeContexts)+ return lib.CheckOutdatedContextWithOutput(false, tellAutoContext, maybeContexts)},}, tellBg)@@ -112,14 +65,14 @@ func build(cmd *cobra.Command, args []string) {fmt.Println("🏗️ Building plan in the background")fmt.Println()term.PrintCmds("", "ps", "connect", "stop")- } else if config.AutoApply {+ } else if tellAutoApply {flags := lib.ApplyFlags{AutoConfirm: true,- AutoCommit: config.AutoCommit,- NoCommit: !config.AutoCommit,- NoExec: config.NoExec,- AutoExec: config.AutoDebug,- AutoDebug: config.AutoDebugTries,+ AutoCommit: autoCommit,+ NoCommit: !autoCommit,+ NoExec: noExec,+ AutoExec: autoExec,+ AutoDebug: autoDebug,}lib.MustApplyPlan(@@ -133,4 +86,3 @@ func build(cmd *cobra.Command, args []string) {term.PrintCmds("", "diff", "diff --ui", "apply", "reject", "log")}}-diff --git a/app/cli/cmd/changes.go b/app/cli/cmd/changes.goindex 13593101..fd091ee3 100644--- a/app/cli/cmd/changes.go+++ b/app/cli/cmd/changes.go@@ -18,10 +18,9 @@ func init() {}var changesCmd = &cobra.Command{- Use: "changes",- Aliases: []string{"ch"},- Short: "View, copy, or manage changes for the current plan",- Run: changes,+ Use: "changes",+ Short: "View, copy, or manage changes for the current plan",+ Run: changes,}func changes(cmd *cobra.Command, args []string) {diff --git a/app/cli/cmd/chat.go b/app/cli/cmd/chat.goindex ec98e703..7521a5c7 100644--- a/app/cli/cmd/chat.go+++ b/app/cli/cmd/chat.go@@ -5,7 +5,6 @@ import ("plandex/auth""plandex/lib""plandex/plan_exec"- "plandex/term""github.com/plandex/plandex/shared""github.com/spf13/cobra"@@ -13,7 +12,7 @@ import (var chatCmd = &cobra.Command{Use: "chat [prompt]",- Aliases: []string{"ct"},+ Aliases: []string{"ch"},Short: "Chat without making changes",// Long: ``,Args: cobra.RangeArgs(0, 1),@@ -23,47 +22,20 @@ var chatCmd = &cobra.Command{func init() {RootCmd.AddCommand(chatCmd)- chatCmd.Flags().StringVarP(&tellPromptFile, "file", "f", "", "File containing prompt")- chatCmd.Flags().BoolVarP(&autoConfirm, "yes", "y", false, "Automatically confirm context updates")- chatCmd.Flags().BoolVar(&tellAutoContext, "auto-context", false, "Load and manage context automatically")+ initExecFlags(chatCmd, initExecFlagsParams{+ omitNoBuild: true,+ omitStop: true,+ omitBg: true,+ omitApply: true,+ omitExec: true,+ })+}func doChat(cmd *cobra.Command, args []string) {- var config *shared.PlanConfig- if lib.CurrentPlanId != "" {- term.StartSpinner("")- var err error- config, err = api.Client.GetPlanConfig(lib.CurrentPlanId)- term.StopSpinner()-- if err != nil {- term.OutputErrorAndExit("Error getting plan config: %v", err)- }- } else {- term.StartSpinner("")- var err error- config, err = api.Client.GetDefaultPlanConfig()- term.StopSpinner()-- if err != nil {- term.OutputErrorAndExit("Error getting default plan config: %v", err)- }- }-- // Override config with flags- if cmd.Flags().Changed("yes") {- config.AutoContext = autoConfirm- }- if cmd.Flags().Changed("auto-context") {- config.AutoContext = tellAutoContext- }-auth.MustResolveAuthWithOrg()lib.MustResolveProject()-- if lib.CurrentPlanId == "" {- term.OutputNoCurrentPlanErrorAndExit()- }+ mustSetPlanExecFlags(cmd)var apiKeys map[string]stringif !auth.Current.IntegratedModelsMode {@@ -82,11 +54,10 @@ func doChat(cmd *cobra.Command, args []string) {CurrentBranch: lib.CurrentBranch,ApiKeys: apiKeys,CheckOutdatedContext: func(maybeContexts []*shared.Context) (bool, bool, error) {- return lib.CheckOutdatedContextWithOutput(false, config.AutoContext, maybeContexts)+ return lib.CheckOutdatedContextWithOutput(false, tellAutoContext, maybeContexts)},}, prompt, plan_exec.TellFlags{IsChatOnly: true,- AutoContext: config.AutoContext,+ AutoContext: tellAutoContext,})}-diff --git a/app/cli/cmd/config.go b/app/cli/cmd/config.gonew file mode 100644index 00000000..ab95a2f4--- /dev/null+++ b/app/cli/cmd/config.go@@ -0,0 +1,74 @@+package cmd++import (+ "fmt"+ "plandex/api"+ "plandex/auth"+ "plandex/lib"+ "plandex/term"++ "github.com/fatih/color"+ "github.com/spf13/cobra"+)++func init() {+ RootCmd.AddCommand(configCmd)+ configCmd.AddCommand(defaultConfigCmd)+}++var configCmd = &cobra.Command{+ Use: "config",+ Short: "Show plan config",+ Run: config,+}++var defaultConfigCmd = &cobra.Command{+ Use: "default",+ Short: "Show default config for new plans",+ Run: defaultConfig,+}++func config(cmd *cobra.Command, args []string) {+ auth.MustResolveAuthWithOrg()+ lib.MustResolveProject()++ if lib.CurrentPlanId == "" {+ term.OutputNoCurrentPlanErrorAndExit()+ }++ term.StartSpinner("")++ config, apiErr := api.Client.GetPlanConfig(lib.CurrentPlanId)+ if apiErr != nil {+ term.StopSpinner()+ term.OutputErrorAndExit("Error getting config: %v", apiErr.Msg)+ return+ }++ term.StopSpinner()++ color.New(color.Bold, term.ColorHiCyan).Println("⚙️ Plan Config")+ lib.ShowPlanConfig(config, "")+ fmt.Println()++ term.PrintCmds("", "set-config", "config default", "set-config default")+}++func defaultConfig(cmd *cobra.Command, args []string) {+ auth.MustResolveAuth(false)++ term.StartSpinner("")+ config, err := api.Client.GetDefaultPlanConfig()+ term.StopSpinner()++ if err != nil {+ term.OutputErrorAndExit("Error getting default config: %v", err)+ return+ }++ color.New(color.Bold, term.ColorHiCyan).Println("⚙️ Default Config")+ lib.ShowPlanConfig(config, "")+ fmt.Println()++ term.PrintCmds("", "set-config default", "config", "set-config")+}diff --git a/app/cli/cmd/continue.go b/app/cli/cmd/continue.goindex aab8db77..1c39a5b1 100644--- a/app/cli/cmd/continue.go+++ b/app/cli/cmd/continue.go@@ -4,7 +4,6 @@ import ("plandex/auth""plandex/lib""plandex/plan_exec"- "plandex/term""github.com/plandex/plandex/shared""github.com/spf13/cobra"@@ -20,73 +19,16 @@ var continueCmd = &cobra.Command{func init() {RootCmd.AddCommand(continueCmd)- continueCmd.Flags().BoolVarP(&tellStop, "stop", "s", false, "Stop after a single reply")- continueCmd.Flags().BoolVarP(&tellNoBuild, "no-build", "n", false, "Don't build files")- continueCmd.Flags().BoolVar(&tellBg, "bg", false, "Execute autonomously in the background")-- continueCmd.Flags().BoolVarP(&autoConfirm, "yes", "y", false, "Automatically confirm context updates")- continueCmd.Flags().BoolVarP(&tellAutoApply, "apply", "a", false, "Automatically apply changes (and confirm context updates)")- continueCmd.Flags().BoolVarP(&autoCommit, "commit", "c", false, "Commit changes to git when --apply/-a is passed")- continueCmd.Flags().BoolVar(&tellAutoContext, "auto-context", false, "Load and manage context automatically")- continueCmd.Flags().BoolVar(&noExec, "no-exec", false, "Disable command execution")- continueCmd.Flags().BoolVar(&autoExec, "auto-exec", false, "Automatically execute commands without confirmation when --apply is passed")- continueCmd.Flags().Var(newAutoDebugValue(&autoDebug), "debug", "Automatically execute and debug failing commands (optionally specify number of tries—default is 5)")+ initExecFlags(continueCmd, initExecFlagsParams{+ omitFile: true,+ omitEditor: true,+ })}func doContinue(cmd *cobra.Command, args []string) {- validateTellFlags()-- var config *shared.PlanConfig- if lib.CurrentPlanId != "" {- term.StartSpinner("")- var err error- config, err = api.Client.GetPlanConfig(lib.CurrentPlanId)- term.StopSpinner()-- if err != nil {- term.OutputErrorAndExit("Error getting plan config: %v", err)- }- } else {- term.StartSpinner("")- var err error- config, err = api.Client.GetDefaultPlanConfig()- term.StopSpinner()-- if err != nil {- term.OutputErrorAndExit("Error getting default plan config: %v", err)- }- }-- // Override config with flags- if cmd.Flags().Changed("yes") {- config.AutoContext = autoConfirm- }- if cmd.Flags().Changed("apply") {- config.AutoApply = tellAutoApply- }- if cmd.Flags().Changed("commit") {- config.AutoCommit = autoCommit- }- if cmd.Flags().Changed("auto-context") {- config.AutoContext = tellAutoContext- }- if cmd.Flags().Changed("no-exec") {- config.NoExec = noExec- }- if cmd.Flags().Changed("auto-exec") {- config.AutoDebug = autoExec- }- if cmd.Flags().Changed("debug") {- config.AutoDebug = true- config.AutoDebugTries = autoDebug- }-auth.MustResolveAuthWithOrg()lib.MustResolveProject()-- if lib.CurrentPlanId == "" {- term.OutputNoCurrentPlanErrorAndExit()- }+ mustSetPlanExecFlags(cmd)var apiKeys map[string]stringif !auth.Current.IntegratedModelsMode {@@ -98,25 +40,25 @@ func doContinue(cmd *cobra.Command, args []string) {CurrentBranch: lib.CurrentBranch,ApiKeys: apiKeys,CheckOutdatedContext: func(maybeContexts []*shared.Context) (bool, bool, error) {- return lib.CheckOutdatedContextWithOutput(false, config.AutoContext, maybeContexts)+ return lib.CheckOutdatedContextWithOutput(false, tellAutoContext, maybeContexts)},}, "", plan_exec.TellFlags{TellBg: tellBg,TellStop: tellStop,TellNoBuild: tellNoBuild,IsUserContinue: true,- ExecEnabled: !config.NoExec,- AutoContext: config.AutoContext,+ ExecEnabled: !noExec,+ AutoContext: tellAutoContext,})- if config.AutoApply {+ if tellAutoApply {flags := lib.ApplyFlags{AutoConfirm: true,- AutoCommit: config.AutoCommit,- NoCommit: !config.AutoCommit,- AutoExec: config.AutoDebug,- NoExec: config.NoExec,- AutoDebug: config.AutoDebugTries,+ AutoCommit: autoCommit,+ NoCommit: !autoCommit,+ AutoExec: autoExec,+ NoExec: noExec,+ AutoDebug: autoDebug,}lib.MustApplyPlan(@@ -127,4 +69,3 @@ func doContinue(cmd *cobra.Command, args []string) {)}}-diff --git a/app/cli/cmd/new.go b/app/cli/cmd/new.goindex 587eb3f6..f3470fcd 100644--- a/app/cli/cmd/new.go+++ b/app/cli/cmd/new.go@@ -2,12 +2,12 @@ package cmdimport ("fmt"- "os""plandex/api""plandex/auth""plandex/lib""plandex/term"+ "plandex/types""github.com/fatih/color""github.com/plandex/plandex/shared"@@ -15,6 +15,7 @@ import ()var name string+var contextBaseDir string// newCmd represents the new commandvar newCmd = &cobra.Command{@@ -29,6 +30,7 @@ var newCmd = &cobra.Command{func init() {RootCmd.AddCommand(newCmd)newCmd.Flags().StringVarP(&name, "name", "n", "", "Name of the new plan")+ newCmd.Flags().StringVar(&contextBaseDir, "context-dir", ".", "Base directory to auto-load context from")}func new(cmd *cobra.Command, args []string) {@@ -36,34 +38,40 @@ func new(cmd *cobra.Command, args []string) {lib.MustResolveOrCreateProject()term.StartSpinner("")- res, apiErr := api.Client.CreatePlan(lib.CurrentProjectId, shared.CreatePlanRequest{Name: name})- term.StopSpinner()-- if apiErr != nil {- if apiErr.Type == shared.ApiErrorTypeTrialPlansExceeded {- fmt.Fprintf(os.Stderr, "🚨 You've reached the Plandex Cloud trial limit of %d plans\n", apiErr.TrialPlansExceededError.MaxPlans)- res, err := term.ConfirmYesNo("Upgrade now?")+ errCh := make(chan error, 2)- if err != nil {- term.OutputErrorAndExit("Error prompting upgrade trial: %v", err)- }+ var planId string+ var config *shared.PlanConfig- if res {- auth.ConvertTrial()- // re-run the command- new(cmd, args)- return- } else {- return- }+ go func() {+ res, apiErr := api.Client.CreatePlan(lib.CurrentProjectId, shared.CreatePlanRequest{Name: name})+ if apiErr != nil {+ errCh <- fmt.Errorf("error creating plan: %v", apiErr.Msg)+ return+ }+ planId = res.Id+ errCh <- nil+ }()++ go func() {+ var apiErr *shared.ApiError+ config, apiErr = api.Client.GetDefaultPlanConfig()+ if apiErr != nil {+ errCh <- fmt.Errorf("error getting plan config: %v", apiErr.Msg)+ return+ }+ errCh <- nil+ }()- } else {- term.OutputErrorAndExit("Error creating plan: %v", apiErr.Msg)+ for i := 0; i < 2; i++ {+ err := <-errCh+ if err != nil {+ term.OutputErrorAndExit("Error: %v", err)}}- err := lib.WriteCurrentPlan(res.Id)+ err := lib.WriteCurrentPlan(planId)if err != nil {term.OutputErrorAndExit("Error setting current plan: %v", err)@@ -73,32 +81,36 @@ func new(cmd *cobra.Command, args []string) {name = "draft"}+ term.StopSpinner()+fmt.Printf("✅ Started new plan %s and set it to current plan\n", color.New(color.Bold, term.ColorHiGreen).Sprint(name))+ fmt.Println("⚙️ Using default config")- term.StartSpinner("")- config, err := api.Client.GetDefaultPlanConfig()- term.StopSpinner()+ // autoModeLabel := shared.ConfigSettingsByKey["automode"].KeyToLabel(string(config.AutoMode))+ // fmt.Println("⚡️ Auto-mode:", autoModeLabel)- if err != nil {- term.OutputErrorAndExit("Error getting default config: %v", err)- }+ if config.AutoLoadContext {+ fmt.Println("📥 Automatic context loading is enabled")- fmt.Println()- color.New(color.Bold, term.ColorHiCyan).Println("⚙️ Default Settings")- table := tablewriter.NewWriter(os.Stdout)- table.SetAutoWrapText(false)- table.SetHeader([]string{"Name", "Value"})+ baseDir := contextBaseDir+ if baseDir == "" {+ baseDir = "."+ }- table.Append([]string{"Auto Apply", fmt.Sprintf("%t", config.AutoApply)})- table.Append([]string{"Auto Commit", fmt.Sprintf("%t", config.AutoCommit)})- table.Append([]string{"Auto Context", fmt.Sprintf("%t", config.AutoContext)})- table.Append([]string{"No Exec", fmt.Sprintf("%t", config.NoExec)})- table.Append([]string{"Auto Debug", fmt.Sprintf("%t", config.AutoDebug)})- table.Append([]string{"Auto Debug Tries", fmt.Sprintf("%d", config.AutoDebugTries)})+ lib.MustLoadContext([]string{baseDir}, &types.LoadContextParams{+ DefsOnly: true,+ SkipIgnoreWarning: true,+ })+ } else {+ fmt.Println()+ }++ cmds := []string{"tell", "chat", "plans", "current", "config"}- table.Render()+ if !config.AutoLoadContext {+ cmds = append([]string{"load"}, cmds...)+ }- fmt.Println()- term.PrintCmds("", "load", "tell", "chat", "plans", "current", "settings", "set")+ term.PrintCmds("", cmds...)}diff --git a/app/cli/cmd/plan_exec_helpers.go b/app/cli/cmd/plan_exec_helpers.gonew file mode 100644index 00000000..834e68c9--- /dev/null+++ b/app/cli/cmd/plan_exec_helpers.go@@ -0,0 +1,240 @@+package cmd++import (+ "fmt"+ "os"+ "plandex/api"+ "plandex/lib"+ "plandex/term"+ "strconv"++ "github.com/plandex/plandex/shared"+ "github.com/spf13/cobra"+)++const (+ EditorTypeVim string = "vim"+ EditorTypeNano string = "nano"+)++var defaultEditor = EditorTypeVim++const defaultAutoDebugTries = 5++var autoConfirm bool++var tellPromptFile string+var tellBg bool+var tellStop bool+var tellNoBuild bool+var tellAutoApply bool+var tellAutoContext bool+var noExec bool+var autoDebug int++var editor string++func init() {+ defaultEditor = os.Getenv("EDITOR")+ if defaultEditor == "" {+ defaultEditor = os.Getenv("VISUAL")+ if defaultEditor == "" {+ defaultEditor = string(defaultEditor)+ }+ }+}++type initExecFlagsParams struct {+ omitFile bool+ omitNoBuild bool+ omitEditor bool+ omitStop bool+ omitBg bool+ omitApply bool+ omitExec bool+ omitAutoContext bool+}++func initExecFlags(cmd *cobra.Command, params initExecFlagsParams) {+ if !params.omitFile {+ cmd.Flags().StringVarP(&tellPromptFile, "file", "f", "", "File containing prompt")+ }++ if !params.omitBg {+ cmd.Flags().BoolVar(&tellBg, "bg", false, "Execute autonomously in the background")+ }++ if !params.omitStop {+ cmd.Flags().BoolVarP(&tellStop, "stop", "s", false, "Stop after a single reply")+ }++ if !params.omitNoBuild {+ cmd.Flags().BoolVarP(&tellNoBuild, "no-build", "n", false, "Don't build files")+ }++ cmd.Flags().BoolVar(&autoConfirm, "auto-update-context", false, shared.ConfigSettingsByKey["auto-update-context"].Desc)++ if !params.omitAutoContext {+ cmd.Flags().BoolVar(&tellAutoContext, "auto-load-context", false, shared.ConfigSettingsByKey["auto-load-context"].Desc)+ }++ if !params.omitApply {+ cmd.Flags().BoolVar(&tellAutoApply, "apply", false, "Automatically apply changes")+ cmd.Flags().BoolVarP(&autoCommit, "commit", "c", false, "Commit changes to git when --apply is passed")+ }++ if !params.omitExec {+ cmd.Flags().BoolVar(&noExec, "no-exec", false, "Disable command execution")++ cmd.Flags().BoolVar(&autoExec, "auto-exec", false, "Automatically execute commands without confirmation")++ cmd.Flags().Var(newAutoDebugValue(&autoDebug), "debug", "Automatically execute and debug failing commands (optionally specify number of tries—default is 5)")++ cmd.Flag("debug").NoOptDefVal = strconv.Itoa(defaultAutoDebugTries)+ }++ if !params.omitEditor {+ cmd.Flags().Var(newEditorValue(&editor), "editor", "Write prompt in system editor")+ cmd.Flag("editor").NoOptDefVal = defaultEditor+ }+}++func validatePlanExecFlags() {+ if tellAutoApply && tellNoBuild {+ term.OutputErrorAndExit("🚨 --apply can't be used with --no-build/-n")+ }+ if tellAutoApply && tellBg {+ term.OutputErrorAndExit("🚨 --apply can't be used with --bg")+ }+ if autoCommit && !tellAutoApply {+ term.OutputErrorAndExit("🚨 --commit/-c can only be used with --apply")+ }+ if autoExec && !tellAutoApply {+ term.OutputErrorAndExit("🚨 --auto-exec can only be used with --apply")+ }+ if autoDebug > 0 && !tellAutoApply {+ term.OutputErrorAndExit("🚨 --debug can only be used with --apply")+ }+ if autoDebug > 0 && noExec {+ term.OutputErrorAndExit("🚨 --debug can't be used with --no-exec")+ }++ if tellAutoContext && tellBg {+ term.OutputErrorAndExit("🚨 --auto-context/-c can't be used with --bg")+ }+}++func mustSetPlanExecFlags(cmd *cobra.Command) {+ if lib.CurrentPlanId == "" {+ term.OutputNoCurrentPlanErrorAndExit()+ }++ config, apiErr := api.Client.GetPlanConfig(lib.CurrentPlanId)+ if apiErr != nil {+ term.OutputErrorAndExit("Error getting plan config: %v", apiErr)+ }++ // Set flag vars from config when flags aren't explicitly set+ if !cmd.Flags().Changed("stop") {+ tellStop = !config.AutoContinue+ }++ if !cmd.Flags().Changed("no-build") {+ tellNoBuild = !config.AutoBuild+ }++ if !cmd.Flags().Changed("auto-update-context") {+ autoConfirm = config.AutoUpdateContext+ }+ if !cmd.Flags().Changed("apply") {+ tellAutoApply = config.AutoApply+ }+ if !cmd.Flags().Changed("commit") {+ autoCommit = config.AutoCommit+ }+ if !cmd.Flags().Changed("auto-load-context") {+ tellAutoContext = config.AutoLoadContext+ }+ if !cmd.Flags().Changed("no-exec") {+ noExec = !config.CanExec+ }+ if !cmd.Flags().Changed("auto-exec") {+ autoExec = config.AutoExec+ }+ if !cmd.Flags().Changed("debug") {+ autoDebug = config.AutoDebugTries+ // Only set autoDebug if AutoDebug is enabled in config+ if !config.AutoDebug {+ autoDebug = 0+ }+ }++ validatePlanExecFlags()+}++// AutoDebugValue implements the flag.Value interface+type autoDebugValue struct {+ value *int+}++func newAutoDebugValue(p *int) *autoDebugValue {+ *p = 0 // Default to 0 (disabled)+ return &autoDebugValue{p}+}++func (f *autoDebugValue) Set(s string) error {+ if s == "" {+ *f.value = defaultAutoDebugTries+ return nil+ }+ v, err := strconv.Atoi(s)+ if err != nil {+ return fmt.Errorf("invalid value for --debug: %v", err)+ }+ if v <= 0 {+ return fmt.Errorf("--debug value must be greater than 0")+ }+ *f.value = v+ return nil+}++func (f *autoDebugValue) String() string {+ if f.value == nil {+ return "0"+ }+ return strconv.Itoa(*f.value)+}++func (f *autoDebugValue) Type() string {+ return "int"+}++// EditorValue implements the flag.Value interface+type editorValue struct {+ value *string+}++func newEditorValue(p *string) *editorValue {+ *p = "" // Default to empty string+ return &editorValue{p}+}++func (f *editorValue) Set(s string) error {+ if s == "" {+ *f.value = defaultEditor+ return nil+ }+ *f.value = s+ return nil+}++func (f *editorValue) String() string {+ if f.value == nil {+ return ""+ }+ return *f.value+}++func (f *editorValue) Type() string {+ return "string"+}diff --git a/app/cli/cmd/set.go b/app/cli/cmd/set.godeleted file mode 100644index f0a19673..00000000--- a/app/cli/cmd/set.go+++ /dev/null@@ -1,271 +0,0 @@-package cmd--import (- "fmt"- "plandex/api"- "plandex/auth"- "plandex/lib"- "plandex/term"- "strconv"- "strings"-- "github.com/plandex/plandex/shared"- "github.com/spf13/cobra"-)--func init() {- RootCmd.AddCommand(setCmd)- setCmd.AddCommand(defaultSetCmd)-}--var setCmd = &cobra.Command{- Use: "set [setting] [value]",- Short: "Update current plan config settings",- Run: set,- Args: cobra.MaximumNArgs(2),-}--var defaultSetCmd = &cobra.Command{- Use: "default [setting] [value]",- Short: "Update default plan config settings",- Run: defaultSet,- Args: cobra.MaximumNArgs(2),-}--func set(cmd *cobra.Command, args []string) {- auth.MustResolveAuthWithOrg()- lib.MustResolveProject()-- if lib.CurrentPlanId == "" {- term.OutputNoCurrentPlanErrorAndExit()- }-- term.StartSpinner("")- config, err := api.Client.GetPlanConfig(lib.CurrentPlanId)- term.StopSpinner()-- if err != nil {- term.OutputErrorAndExit("Error getting current config: %v", err)- return- }-- if config == nil {- config = &shared.PlanConfig{}- }-- updatedConfig := updateConfig(args, config)- if updatedConfig == nil {- return- }-- term.StartSpinner("")- res, err := api.Client.UpdatePlanConfig(lib.CurrentPlanId, shared.UpdatePlanConfigRequest{- Config: updatedConfig,- })- term.StopSpinner()-- if err != nil {- term.OutputErrorAndExit("Error updating config: %v", err)- return- }-- fmt.Println(res.Msg)- fmt.Println()- term.PrintCmds("", "settings", "set default", "models")-}--func defaultSet(cmd *cobra.Command, args []string) {- auth.MustResolveAuthWithOrg()-- term.StartSpinner("")- config, err := api.Client.GetDefaultPlanConfig()- term.StopSpinner()-- if err != nil {- term.OutputErrorAndExit("Error getting current config: %v", err)- return- }-- if config == nil {- config = &shared.PlanConfig{}- }-- updatedConfig := updateConfig(args, config)- if updatedConfig == nil {- return- }-- term.StartSpinner("")- res, err := api.Client.UpdateDefaultPlanConfig(shared.UpdateDefaultPlanConfigRequest{- Config: updatedConfig,- })- term.StopSpinner()-- if err != nil {- term.OutputErrorAndExit("Error updating config: %v", err)- return- }-- fmt.Println(res.Msg)- fmt.Println()- term.PrintCmds("", "settings", "set", "models")-}--func updateConfig(args []string, originalConfig *shared.PlanConfig) *shared.PlanConfig {- var setting, value string-- if len(args) > 0 {- setting = strings.ToLower(strings.ReplaceAll(args[0], "-", ""))- }-- if len(args) > 1 {- value = args[1]- }-- if setting == "" {- opts := []string{- "auto-apply → automatically apply changes when ready",- "auto-commit → automatically commit changes after apply",- "auto-context → automatically update context after changes",- "no-exec → disable command execution",- "auto-debug → automatically debug failed commands",- "auto-debug-tries → number of auto-debug attempts",- }-- selection, err := term.SelectFromList("Choose a setting to update:", opts)- if err != nil {- if err.Error() == "interrupt" {- return nil- }- term.OutputErrorAndExit("Error selecting setting: %v", err)- return nil- }-- setting = strings.Split(selection, " →")[0]- setting = strings.ToLower(strings.ReplaceAll(setting, "-", ""))- }-- config := *originalConfig-- switch setting {- case "autoapply":- if value == "" {- var err error- value, err = term.GetRequiredUserStringInput("Set auto-apply (true/false)")- if err != nil {- if err.Error() == "interrupt" {- return nil- }- term.OutputErrorAndExit("Error getting value: %v", err)- return nil- }- }- b, err := strconv.ParseBool(value)- if err != nil {- fmt.Println("Invalid value for auto-apply:", value)- return nil- }- config.AutoApply = b-- case "autocommit":- if value == "" {- var err error- value, err = term.GetRequiredUserStringInput("Set auto-commit (true/false)")- if err != nil {- if err.Error() == "interrupt" {- return nil- }- term.OutputErrorAndExit("Error getting value: %v", err)- return nil- }- }- b, err := strconv.ParseBool(value)- if err != nil {- fmt.Println("Invalid value for auto-commit:", value)- return nil- }- config.AutoCommit = b-- case "autocontext":- if value == "" {- var err error- value, err = term.GetRequiredUserStringInput("Set auto-context (true/false)")- if err != nil {- if err.Error() == "interrupt" {- return nil- }- term.OutputErrorAndExit("Error getting value: %v", err)- return nil- }- }- b, err := strconv.ParseBool(value)- if err != nil {- fmt.Println("Invalid value for auto-context:", value)- return nil- }- config.AutoContext = b-- case "noexec":- if value == "" {- var err error- value, err = term.GetRequiredUserStringInput("Set no-exec (true/false)")- if err != nil {- if err.Error() == "interrupt" {- return nil- }- term.OutputErrorAndExit("Error getting value: %v", err)- return nil- }- }- b, err := strconv.ParseBool(value)- if err != nil {- fmt.Println("Invalid value for no-exec:", value)- return nil- }- config.NoExec = b-- case "autodebug":- if value == "" {- var err error- value, err = term.GetRequiredUserStringInput("Set auto-debug (true/false)")- if err != nil {- if err.Error() == "interrupt" {- return nil- }- term.OutputErrorAndExit("Error getting value: %v", err)- return nil- }- }- b, err := strconv.ParseBool(value)- if err != nil {- fmt.Println("Invalid value for auto-debug:", value)- return nil- }- config.AutoDebug = b-- case "autodebugtries":- if value == "" {- var err error- value, err = term.GetRequiredUserStringInput("Set auto-debug-tries (number)")- if err != nil {- if err.Error() == "interrupt" {- return nil- }- term.OutputErrorAndExit("Error getting value: %v", err)- return nil- }- }- n, err := strconv.Atoi(value)- if err != nil {- fmt.Println("Invalid value for auto-debug-tries:", value)- return nil- }- config.AutoDebugTries = n-- default:- fmt.Printf("Unknown setting: %s\n", setting)- return nil- }-- return &config-}diff --git a/app/cli/cmd/set_config.go b/app/cli/cmd/set_config.gonew file mode 100644index 00000000..3a6a51cf--- /dev/null+++ b/app/cli/cmd/set_config.go@@ -0,0 +1,295 @@+package cmd++import (+ "fmt"+ "plandex/api"+ "plandex/auth"+ "plandex/lib"+ "plandex/term"+ "slices"+ "strconv"+ "strings"++ "github.com/plandex/plandex/shared"+ "github.com/spf13/cobra"+)++func init() {+ RootCmd.AddCommand(setCmd)+ setCmd.AddCommand(defaultSetCmd)+}++var setCmd = &cobra.Command{+ Use: "set-config [setting] [value]",+ Short: "Update current plan config",+ Run: set,+ Args: cobra.MaximumNArgs(2),+}++var defaultSetCmd = &cobra.Command{+ Use: "default [setting] [value]",+ Short: "Update default plan config",+ Run: defaultSet,+ Args: cobra.MaximumNArgs(2),+}++func set(cmd *cobra.Command, args []string) {+ auth.MustResolveAuthWithOrg()+ lib.MustResolveProject()++ if lib.CurrentPlanId == "" {+ term.OutputNoCurrentPlanErrorAndExit()+ }++ term.StartSpinner("")+ config, apiErr := api.Client.GetPlanConfig(lib.CurrentPlanId)+ term.StopSpinner()++ if apiErr != nil {+ term.OutputErrorAndExit("Error getting current config: %v", apiErr)+ return+ }++ if config == nil {+ config = &shared.PlanConfig{}+ }++ key, updatedConfig := updateConfig(args, config)+ if updatedConfig == nil {+ return+ }++ term.StartSpinner("")+ apiErr = api.Client.UpdatePlanConfig(lib.CurrentPlanId, shared.UpdatePlanConfigRequest{+ Config: updatedConfig,+ })+ term.StopSpinner()++ if apiErr != nil {+ term.OutputErrorAndExit("Error updating config: %v", apiErr)+ return+ }++ fmt.Println("✅ Config updated")+ lib.ShowPlanConfig(updatedConfig, key)+ fmt.Println()++ if updatedConfig.AutoLoadContext && !config.AutoLoadContext {+ hasMap := false++ context, err := api.Client.ListContext(lib.CurrentPlanId, lib.CurrentBranch)++ if err == nil {+ for _, c := range context {+ if c.ContextType == shared.ContextMapType {+ hasMap = true+ break+ }+ }++ if !hasMap {+ lib.MustLoadAutoContextMap()+ }+ }+ }++ term.PrintCmds("", "config", "config default", "set-config default")+}++func defaultSet(cmd *cobra.Command, args []string) {+ auth.MustResolveAuthWithOrg()++ term.StartSpinner("")+ config, apiErr := api.Client.GetDefaultPlanConfig()+ term.StopSpinner()++ if apiErr != nil {+ term.OutputErrorAndExit("Error getting current config: %v", apiErr)+ return+ }++ if config == nil {+ config = &shared.PlanConfig{}+ }++ key, updatedConfig := updateConfig(args, config)+ if updatedConfig == nil {+ return+ }++ term.StartSpinner("")+ apiErr = api.Client.UpdateDefaultPlanConfig(shared.UpdateDefaultPlanConfigRequest{+ Config: updatedConfig,+ })+ term.StopSpinner()++ if apiErr != nil {+ term.OutputErrorAndExit("Error updating config: %v", apiErr)+ return+ }++ fmt.Println("✅ Default config updated")+ lib.ShowPlanConfig(updatedConfig, key)+ fmt.Println()+ term.PrintCmds("", "config default", "config", "set-config")+}++type sortableSetting struct {+ sortKey string+ cfg shared.ConfigSetting+}++func updateConfig(args []string, originalConfig *shared.PlanConfig) (string, *shared.PlanConfig) {+ var setting, value string++ if len(args) > 0 {+ setting = strings.ToLower(strings.ReplaceAll(args[0], "-", ""))+ }++ if len(args) > 1 {+ value = args[1]+ }++ if setting == "" {+ var sorted []sortableSetting++ for key, cfg := range shared.ConfigSettingsByKey {+ var sortKey string+ if cfg.SortKey != "" {+ sortKey = cfg.SortKey+ } else {+ sortKey = key+ }+ sorted = append(sorted, sortableSetting{sortKey, cfg})+ }++ slices.SortFunc(sorted, func(a, b sortableSetting) int {+ return strings.Compare(a.sortKey, b.sortKey)+ })++ var opts []string+ for _, opt := range sorted {+ opts = append(opts, fmt.Sprintf("%s → %s", opt.cfg.Name, opt.cfg.Desc))+ }++ selection, err := term.SelectFromList("Choose a setting to update:", opts)+ if err != nil {+ if err.Error() == "interrupt" {+ return "", nil+ }+ term.OutputErrorAndExit("Error selecting setting: %v", err)+ return "", nil+ }++ setting = strings.Split(selection, " →")[0]+ setting = strings.ToLower(strings.ReplaceAll(setting, "-", ""))+ }++ config := *originalConfig+ cfgSetting, exists := shared.ConfigSettingsByKey[setting]+ if !exists {+ term.OutputErrorAndExit("Unknown setting: %s\n", setting)+ return "", nil+ }++ if value == "" {+ if cfgSetting.BoolSetter != nil {+ options := []string{"Enabled", "Disabled"}+ selection, err := term.SelectFromList(fmt.Sprintf("Set %s:", cfgSetting.Name), options)+ if err != nil {+ if err.Error() == "interrupt" {+ return "", nil+ }+ term.OutputErrorAndExit("Error selecting value: %v", err)+ return "", nil+ }+ cfgSetting.BoolSetter(&config, selection == "Enabled")+ } else if cfgSetting.IntSetter != nil {+ value, err := term.GetRequiredUserStringInput(fmt.Sprintf("Set %s (number)", cfgSetting.Name))+ if err != nil {+ if err.Error() == "interrupt" {+ return "", nil+ }+ term.OutputErrorAndExit("Error getting value: %v", err)+ return "", nil+ }+ n, err := strconv.Atoi(value)+ if err != nil {+ term.OutputErrorAndExit("Invalid number value for %s (%s)", cfgSetting.Name, value)+ return "", nil+ }+ cfgSetting.IntSetter(&config, n)+ } else if cfgSetting.StringSetter != nil {+ var selection string+ var err error+ choices := *cfgSetting.Choices+ if len(choices) > 0 {+ if cfgSetting.HasCustomChoice {+ choices = append(choices, "Other")+ }+ selection, err = term.SelectFromList(fmt.Sprintf("Set %s:", cfgSetting.Name), choices)+ if err != nil {+ if err.Error() == "interrupt" {+ return "", nil+ }+ term.OutputErrorAndExit("Error selecting value: %v", err)+ return "", nil+ }+ if selection == "Other" {+ selection, err = term.GetRequiredUserStringInput(fmt.Sprintf("Enter value for %s", cfgSetting.Name))+ if err != nil {+ if err.Error() == "interrupt" {+ return "", nil+ }+ term.OutputErrorAndExit("Error getting value: %v", err)+ return "", nil+ }+ } else if cfgSetting.ChoiceToKey != nil {+ selection = cfgSetting.ChoiceToKey(selection)+ }+ } else {+ selection, err = term.GetRequiredUserStringInput(fmt.Sprintf("Set %s", cfgSetting.Name))+ if err != nil {+ if err.Error() == "interrupt" {+ return "", nil+ }+ term.OutputErrorAndExit("Error getting value: %v", err)+ return "", nil+ }+ }+ cfgSetting.StringSetter(&config, selection)+ }+ } else {+ if cfgSetting.BoolSetter != nil {+ b, err := parseBooleanArg(value)+ if err != nil {+ term.OutputErrorAndExit("Invalid value for %s (%s)", cfgSetting.Name, value)+ return "", nil+ }+ cfgSetting.BoolSetter(&config, b)+ } else if cfgSetting.IntSetter != nil {+ n, err := strconv.Atoi(value)+ if err != nil {+ term.OutputErrorAndExit("Invalid number value for %s (%s)", cfgSetting.Name, value)+ return "", nil+ }+ cfgSetting.IntSetter(&config, n)+ } else if cfgSetting.StringSetter != nil {+ cfgSetting.StringSetter(&config, value)+ }+ }++ return setting, &config+}++func parseBooleanArg(value string) (bool, error) {+ switch value {+ case "enabled", "true", "t", "yes", "y", "1":+ return true, nil+ case "disabled", "false", "f", "no", "n", "0":+ return false, nil+ default:+ return false, fmt.Errorf("invalid value: %s", value)+ }++}diff --git a/app/cli/cmd/settings.go b/app/cli/cmd/settings.godeleted file mode 100644index 6c73a2c2..00000000--- a/app/cli/cmd/settings.go+++ /dev/null@@ -1,110 +0,0 @@-package cmd--import (- "fmt"- "os"- "plandex/api"- "plandex/auth"- "plandex/lib"- "plandex/term"-- "github.com/fatih/color"- "github.com/olekukonko/tablewriter"- "github.com/spf13/cobra"-)--func init() {- RootCmd.AddCommand(settingsCmd)- settingsCmd.AddCommand(defaultSettingsCmd)-}--var settingsCmd = &cobra.Command{- Use: "settings",- Short: "Show plan settings",- Run: settings,-}--var defaultSettingsCmd = &cobra.Command{- Use: "default",- Short: "Show default settings for new plans",- Run: defaultSettings,-}--func settings(cmd *cobra.Command, args []string) {- auth.MustResolveAuthWithOrg()- lib.MustResolveProject()-- if lib.CurrentPlanId == "" {- term.OutputNoCurrentPlanErrorAndExit()- }-- term.StartSpinner("")-- plan, err := api.Client.GetPlan(lib.CurrentPlanId)- if err != nil {- term.StopSpinner()- term.OutputErrorAndExit("Error getting plan: %v", err)- return- }-- config, err := api.Client.GetPlanConfig(lib.CurrentPlanId)- term.StopSpinner()-- if err != nil {- term.OutputErrorAndExit("Error getting settings: %v", err)- return- }-- title := fmt.Sprintf("%s Settings", color.New(color.Bold, term.ColorHiGreen).Sprint(plan.Name))-- table := tablewriter.NewWriter(os.Stdout)- table.SetAutoWrapText(false)- table.Append([]string{title})- table.Render()- fmt.Println()-- renderConfig(config)-- term.PrintCmds("", "set", "settings default", "models")-}--func defaultSettings(cmd *cobra.Command, args []string) {- auth.MustResolveAuthWithOrg()-- term.StartSpinner("")- config, err := api.Client.GetDefaultPlanConfig()- term.StopSpinner()-- if err != nil {- term.OutputErrorAndExit("Error getting default settings: %v", err)- return- }-- title := fmt.Sprintf("%s Settings", color.New(color.Bold, term.ColorHiGreen).Sprint("Default"))- table := tablewriter.NewWriter(os.Stdout)- table.SetAutoWrapText(false)- table.Append([]string{title})- table.Render()- fmt.Println()-- renderConfig(config)-- term.PrintCmds("", "set default", "settings", "models")-}--func renderConfig(config *shared.PlanConfig) {- color.New(color.Bold, term.ColorHiCyan).Println("⚙️ Settings")- table := tablewriter.NewWriter(os.Stdout)- table.SetAutoWrapText(false)- table.SetHeader([]string{"Name", "Value"})-- table.Append([]string{"Auto Apply", fmt.Sprintf("%t", config.AutoApply)})- table.Append([]string{"Auto Commit", fmt.Sprintf("%t", config.AutoCommit)})- table.Append([]string{"Auto Context", fmt.Sprintf("%t", config.AutoContext)})- table.Append([]string{"No Exec", fmt.Sprintf("%t", config.NoExec)})- table.Append([]string{"Auto Debug", fmt.Sprintf("%t", config.AutoDebug)})- table.Append([]string{"Auto Debug Tries", fmt.Sprintf("%d", config.AutoDebugTries)})-- table.Render()- fmt.Println()-}diff --git a/app/cli/cmd/tell.go b/app/cli/cmd/tell.goindex 258ced11..7a218e73 100644--- a/app/cli/cmd/tell.go+++ b/app/cli/cmd/tell.go@@ -11,7 +11,6 @@ import ("plandex/lib""plandex/plan_exec""plandex/term"- "strconv""strings""time"@@ -24,22 +23,6 @@ import ("github.com/spf13/cobra")-const defaultEditor = "vim"-const defaultAutoDebugTries = 5--var autoConfirm bool--// const defaultEditor = "nano"--var tellPromptFile string-var tellBg bool-var tellStop bool-var tellNoBuild bool-var tellAutoApply bool-var tellAutoContext bool-var noExec bool-var autoDebug int-// tellCmd represents the prompt commandvar tellCmd = &cobra.Command{Use: "tell [prompt]",@@ -53,78 +36,13 @@ var tellCmd = &cobra.Command{func init() {RootCmd.AddCommand(tellCmd)- tellCmd.Flags().StringVarP(&tellPromptFile, "file", "f", "", "File containing prompt")- tellCmd.Flags().BoolVarP(&tellStop, "stop", "s", false, "Stop after a single reply")- tellCmd.Flags().BoolVarP(&tellNoBuild, "no-build", "n", false, "Don't build files")- tellCmd.Flags().BoolVar(&tellBg, "bg", false, "Execute autonomously in the background")-- tellCmd.Flags().BoolVarP(&autoConfirm, "yes", "y", false, "Automatically confirm context updates")- tellCmd.Flags().BoolVar(&tellAutoApply, "apply", false, "Automatically apply changes (and confirm context updates)")- tellCmd.Flags().BoolVarP(&autoCommit, "commit", "c", false, "Commit changes to git when --apply is passed")-- tellCmd.Flags().BoolVar(&tellAutoContext, "auto-context", false, "Load and manage context automatically")-- tellCmd.Flags().BoolVar(&noExec, "no-exec", false, "Disable command execution")- tellCmd.Flags().BoolVar(&autoExec, "auto-exec", false, "Automatically execute commands without confirmation when --apply is passed")-- tellCmd.Flags().Var(newAutoDebugValue(&autoDebug), "debug", "Automatically execute and debug failing commands (optionally specify number of tries—default is 5)")- tellCmd.Flag("debug").NoOptDefVal = strconv.Itoa(defaultAutoDebugTries)+ initExecFlags(tellCmd, initExecFlagsParams{})}func doTell(cmd *cobra.Command, args []string) {- validateTellFlags()-- var config *shared.PlanConfig- if lib.CurrentPlanId != "" {- term.StartSpinner("")- var err error- config, err = api.Client.GetPlanConfig(lib.CurrentPlanId)- term.StopSpinner()-- if err != nil {- term.OutputErrorAndExit("Error getting plan config: %v", err)- }- } else {- term.StartSpinner("")- var err error- config, err = api.Client.GetDefaultPlanConfig()- term.StopSpinner()-- if err != nil {- term.OutputErrorAndExit("Error getting default plan config: %v", err)- }- }-- // Override config with flags- if cmd.Flags().Changed("yes") {- config.AutoContext = autoConfirm- }- if cmd.Flags().Changed("apply") {- config.AutoApply = tellAutoApply- }- if cmd.Flags().Changed("commit") {- config.AutoCommit = autoCommit- }- if cmd.Flags().Changed("auto-context") {- config.AutoContext = tellAutoContext- }- if cmd.Flags().Changed("no-exec") {- config.NoExec = noExec- }- if cmd.Flags().Changed("auto-exec") {- config.AutoDebug = autoExec- }- if cmd.Flags().Changed("debug") {- config.AutoDebug = true- config.AutoDebugTries = autoDebug- }-auth.MustResolveAuthWithOrg()lib.MustResolveProject()-- if lib.CurrentPlanId == "" {- term.OutputNoCurrentPlanErrorAndExit()- }+ mustSetPlanExecFlags(cmd)var apiKeys map[string]stringif !auth.Current.IntegratedModelsMode {@@ -225,25 +143,25 @@ func prepareEditorCommand(editor string, filename string) *exec.Cmd {}}-func getEditorInstructions(editor string) string {- return "👉 Write your prompt below, then save and exit to send it to Plandex.\n• To save and exit, press ESC, then type :wq! and press ENTER.\n• To exit without saving, press ESC, then type :q! and press ENTER.\n\n\n"-}+func getEditorInstructions() string {+ if editor == EditorTypeVim {+ return "👉 Write your prompt below, then save and exit to send it to Plandex.\n• To save and exit, press ESC, then type :wq! and press ENTER.\n• To exit without saving, press ESC, then type :q! and press ENTER.\n\n\n"+ }-func getEditorPrompt() string {- editor := os.Getenv("EDITOR")- if editor == "" {- editor = os.Getenv("VISUAL")- if editor == "" {- editor = defaultEditor- }+ if editor == EditorTypeNano {+ return "👉 Write your prompt below, then save and exit to send it to Plandex.\n• To save and exit, press Ctrl+X, then Y, then ENTER.\n• To exit without saving, press Ctrl+X, then N.\n\n\n"}+ return "👉 Write your prompt below, then save and exit to send it to Plandex.\n\n\n"+}++func getEditorPrompt() string {tempFile, err := os.CreateTemp(os.TempDir(), "plandex_prompt_*")if err != nil {term.OutputErrorAndExit("Failed to create temporary file: %v", err)}- instructions := getEditorInstructions(editor)+ instructions := getEditorInstructions()filename := tempFile.Name()err = os.WriteFile(filename, []byte(instructions), 0644)if err != nil {@@ -278,32 +196,6 @@ func getEditorPrompt() string {}-func validateTellFlags() {- if tellAutoApply && tellNoBuild {- term.OutputErrorAndExit("🚨 --apply can't be used with --no-build/-n")- }- if tellAutoApply && tellBg {- term.OutputErrorAndExit("🚨 --apply can't be used with --bg")- }- if autoCommit && !tellAutoApply {- term.OutputErrorAndExit("🚨 --commit/-c can only be used with --apply")- }- if autoExec && !tellAutoApply {- term.OutputErrorAndExit("🚨 --auto-exec can only be used with --apply")- }- if autoDebug > 0 && !tellAutoApply {- term.OutputErrorAndExit("🚨 --debug can only be used with --apply")- }- if autoDebug > 0 && noExec {- term.OutputErrorAndExit("🚨 --debug can't be used with --no-exec")- }-- if tellAutoContext && tellBg {- term.OutputErrorAndExit("🚨 --auto-context/-c can't be used with --bg")- }--}-func maybeShowDiffs() {diffs, err := api.Client.GetPlanDiffs(lib.CurrentPlanId, lib.CurrentBranch, plainTextOutput || showDiffUi)if err != nil {@@ -351,40 +243,3 @@ func maybeShowDiffs() {time.Sleep(100 * time.Millisecond)}}--// AutoDebugValue implements the flag.Value interface-type autoDebugValue struct {- value *int-}--func newAutoDebugValue(p *int) *autoDebugValue {- *p = 0 // Default to 0 (disabled)- return &autoDebugValue{p}-}--func (f *autoDebugValue) Set(s string) error {- if s == "" {- *f.value = defaultAutoDebugTries- return nil- }- v, err := strconv.Atoi(s)- if err != nil {- return fmt.Errorf("invalid value for --debug: %v", err)- }- if v <= 0 {- return fmt.Errorf("--debug value must be greater than 0")- }- *f.value = v- return nil-}--func (f *autoDebugValue) String() string {- if f.value == nil {- return "0"- }- return strconv.Itoa(*f.value)-}--func (f *autoDebugValue) Type() string {- return "int"-}diff --git a/app/cli/go.mod b/app/cli/go.modindex 0dccf219..2aa9dbc6 100644--- a/app/cli/go.mod+++ b/app/cli/go.mod@@ -5,6 +5,7 @@ go 1.23.3require (github.com/atotto/clipboard v0.1.4github.com/charmbracelet/lipgloss v0.10.0+ github.com/davecgh/go-spew v1.1.1github.com/fatih/color v1.16.0github.com/muesli/reflow v0.3.0github.com/muesli/termenv v0.15.2@@ -23,7 +24,6 @@ require (github.com/aymerick/douceur v0.2.0 // indirectgithub.com/containerd/console v1.0.4-0.20230313162750-1ae8d489ac81 // indirectgithub.com/cqroot/multichoose v0.1.1 // indirect- github.com/davecgh/go-spew v1.1.1 // indirectgithub.com/dlclark/regexp2 v1.11.4 // indirectgithub.com/google/uuid v1.6.0 // indirectgithub.com/gorilla/css v1.0.1 // indirectdiff --git a/app/cli/lib/context_load.go b/app/cli/lib/context_load.goindex b3171698..8fa3bdcc 100644--- a/app/cli/lib/context_load.go+++ b/app/cli/lib/context_load.go@@ -22,10 +22,14 @@ import (func MustLoadContext(resources []string, params *types.LoadContextParams) {if params.DefsOnly {- fmt.Println("⏳ Building a map can take a while in larger projects.")- term.StartSpinner("🗺️ Building map...")+ // while caching is set up to work with multiple map paths, it can end up in a partially loaded state if token limits are exceeded, so better to just load one at a time+ if len(resources) > 1 {+ term.OutputErrorAndExit("Please load a single map directory at a time")+ }++ term.LongSpinnerWithWarning("🗺️ Building project map...", "🗺️ This can take a while in larger projects...")} else if params.NamesOnly {- term.StartSpinner("🌳 Loading directory tree...")+ term.LongSpinnerWithWarning("🌳 Loading directory tree...", "🌳 This can take a while in larger projects...")} else {term.StartSpinner("📥 Loading context...")}@@ -125,6 +129,9 @@ func MustLoadContext(resources []string, params *types.LoadContextParams) {}}+ var cachedMapPaths map[string]bool+ var cachedMapLoadRes *shared.LoadContextResponse+if len(inputFilePaths) > 0 {mapInputsByPath := map[string]shared.FileMapInputs{}toLoadMapPaths := []string{}@@ -141,281 +148,316 @@ func MustLoadContext(resources []string, params *types.LoadContextParams) {mapInputsByPath[inputFilePath] = shared.FileMapInputs{}toLoadMapPaths = append(toLoadMapPaths, inputFilePath)}- }-- baseDir := fs.GetBaseDirForFilePaths(inputFilePaths)- paths, err := fs.GetProjectPaths(baseDir)- if err != nil {- onErr(fmt.Errorf("failed to get project paths: %v", err))- }-- // log.Println(spew.Sdump(paths))+ var uncachedMapPaths []string- // fmt.Println("active paths", len(paths.ActivePaths))- // fmt.Println("all paths", len(paths.AllPaths))- // fmt.Println("ignored paths", len(paths.IgnoredPaths))+ res, err := api.Client.LoadCachedFileMap(CurrentPlanId, CurrentBranch, shared.LoadCachedFileMapRequest{+ FilePaths: toLoadMapPaths,+ })- // spew.Dump(paths.IgnoredPaths)- // spew.Dump(paths.ActivePaths)+ if err != nil {+ onErr(fmt.Errorf("error checking cached file map: %v", err))+ }- if !params.ForceSkipIgnore {- var filteredPaths []string- for _, inputFilePath := range inputFilePaths {- // log.Println("inputFilePath", inputFilePath)+ if res.LoadRes != nil {+ if res.LoadRes.MaxTokensExceeded {+ term.StopSpinner()+ overage := res.LoadRes.TotalTokens - res.LoadRes.MaxTokens- if _, ok := paths.ActivePaths[inputFilePath]; !ok {- // log.Println("not active", inputFilePath)+ term.OutputErrorAndExit("Update would add %d 🪙 and exceed token limit (%d) by %d 🪙\n", res.LoadRes.TokensAdded, res.LoadRes.MaxTokens, overage)+ }- if _, ok := paths.IgnoredPaths[inputFilePath]; ok {- // log.Println("ignored", inputFilePath)+ cachedMapLoadRes = res.LoadRes+ cachedMapPaths = res.CachedByPath- ignoredPaths[inputFilePath] = paths.IgnoredPaths[inputFilePath]+ for _, path := range toLoadMapPaths {+ if cachedMapPaths[path] {+ uncachedMapPaths = append(uncachedMapPaths, path)}- } else {- // log.Println("active", inputFilePath)-- filteredPaths = append(filteredPaths, inputFilePath)}+ } else {+ uncachedMapPaths = toLoadMapPaths}- inputFilePaths = filteredPaths- }- if params.NamesOnly {- for _, inputFilePath := range inputFilePaths {- composite := strings.Join([]string{string(shared.ContextDirectoryTreeType), inputFilePath}, "|")- if existsByComposite[composite] != nil {- alreadyLoadedByComposite[composite] = existsByComposite[composite]- continue- }-- numRoutines++- go func(inputFilePath string) {- flattenedPaths, err := ParseInputPaths([]string{inputFilePath}, params)- if err != nil {- errCh <- fmt.Errorf("failed to parse input paths: %v", err)- return- }-- if !params.ForceSkipIgnore {- var filteredPaths []string- for _, path := range flattenedPaths {- if _, ok := paths.ActivePaths[path]; ok {- filteredPaths = append(filteredPaths, path)- } else {- if _, ok := paths.IgnoredPaths[path]; ok {- ignoredPaths[path] = paths.IgnoredPaths[path]- }- }- }- flattenedPaths = filteredPaths- }-- body := strings.Join(flattenedPaths, "\n")-- name := inputFilePath- if name == "." {- name = "cwd"- }- if name == ".." {- name = "parent"- }+ toLoadMapPaths = uncachedMapPaths+ inputFilePaths = toLoadMapPaths+ }- contextMu.Lock()- defer contextMu.Unlock()- loadContextReq = append(loadContextReq, &shared.LoadContextParams{- ContextType: shared.ContextDirectoryTreeType,- Name: name,- Body: body,- FilePath: inputFilePath,- ForceSkipIgnore: params.ForceSkipIgnore,- })-- errCh <- nil- }(inputFilePath)- }+ if len(inputFilePaths) > 0 {+ baseDir := fs.GetBaseDirForFilePaths(inputFilePaths)- } else {- flattenedPaths, err := ParseInputPaths(inputFilePaths, params)+ paths, err := fs.GetProjectPaths(baseDir)if err != nil {- onErr(fmt.Errorf("failed to parse input paths: %v", err))+ onErr(fmt.Errorf("failed to get project paths: %v", err))}- // // Dump flattenedPaths to JSON file for debugging- // debugData, err := json.MarshalIndent(flattenedPaths, "", " ")- // if err != nil {- // onErr(fmt.Errorf("failed to marshal flattened paths: %v", err))- // return- // }+ // log.Println(spew.Sdump(paths))- // if err := os.WriteFile("flattened_paths_debug.json", debugData, 0644); err != nil {- // onErr(fmt.Errorf("failed to write debug file: %v", err))- // return- // }+ // fmt.Println("active paths", len(paths.ActivePaths))+ // fmt.Println("all paths", len(paths.AllPaths))+ // fmt.Println("ignored paths", len(paths.IgnoredPaths))++ // spew.Dump(paths.IgnoredPaths)+ // spew.Dump(paths.ActivePaths)if !params.ForceSkipIgnore {var filteredPaths []string- for _, path := range flattenedPaths {- if _, ok := paths.ActivePaths[path]; ok {- filteredPaths = append(filteredPaths, path)- } else {- if _, ok := paths.IgnoredPaths[path]; ok {- ignoredPaths[path] = paths.IgnoredPaths[path]+ for _, inputFilePath := range inputFilePaths {+ // log.Println("inputFilePath", inputFilePath)++ if _, ok := paths.ActivePaths[inputFilePath]; !ok {+ // log.Println("not active", inputFilePath)++ if _, ok := paths.IgnoredPaths[inputFilePath]; ok {+ // log.Println("ignored", inputFilePath)++ ignoredPaths[inputFilePath] = paths.IgnoredPaths[inputFilePath]}- }- }- flattenedPaths = filteredPaths- }+ } else {+ // log.Println("active", inputFilePath)- // Add this check for the number of files (after filtering out ignored/irrelevant paths)- var numPaths int- if params.DefsOnly {- for _, path := range flattenedPaths {- if shared.HasFileMapSupport(path) {- numPaths+++ filteredPaths = append(filteredPaths, inputFilePath)}}- } else {- numPaths = len(flattenedPaths)- }-- if numPaths > shared.MaxContextCount {- onErr(fmt.Errorf("too many files to load (found %d, limit is %d)", numPaths, shared.MaxContextCount))+ inputFilePaths = filteredPaths}- inputFilePaths = flattenedPaths+ if params.NamesOnly {+ for _, inputFilePath := range inputFilePaths {+ composite := strings.Join([]string{string(shared.ContextDirectoryTreeType), inputFilePath}, "|")+ if existsByComposite[composite] != nil {+ alreadyLoadedByComposite[composite] = existsByComposite[composite]+ continue+ }- for _, path := range flattenedPaths {- var mapInputPath string- if params.DefsOnly {- for _, inputPath := range toLoadMapPaths {- // Clean and make absolute paths for comparison- absPath, err := filepath.Abs(path)+ numRoutines+++ go func(inputFilePath string) {+ flattenedPaths, err := ParseInputPaths([]string{inputFilePath}, params)if err != nil {- continue+ errCh <- fmt.Errorf("failed to parse input paths: %v", err)+ return}- absInputPath, err := filepath.Abs(inputPath)- if err != nil {- continue++ if !params.ForceSkipIgnore {+ var filteredPaths []string+ for _, path := range flattenedPaths {+ if _, ok := paths.ActivePaths[path]; ok {+ filteredPaths = append(filteredPaths, path)+ } else {+ if _, ok := paths.IgnoredPaths[path]; ok {+ ignoredPaths[path] = paths.IgnoredPaths[path]+ }+ }+ }+ flattenedPaths = filteredPaths}- // Check if paths are equal or if path is under inputPath- if absPath == absInputPath || strings.HasPrefix(absPath+string(filepath.Separator), absInputPath+string(filepath.Separator)) {- mapInputPath = inputPath- break+ body := strings.Join(flattenedPaths, "\n")++ name := inputFilePath+ if name == "." {+ name = "cwd"+ }+ if name == ".." {+ name = "parent"}- }- if mapInputPath == "" {- continue // not a child of any input path- }+ contextMu.Lock()+ defer contextMu.Unlock()+ loadContextReq = append(loadContextReq, &shared.LoadContextParams{+ ContextType: shared.ContextDirectoryTreeType,+ Name: name,+ Body: body,+ FilePath: inputFilePath,+ ForceSkipIgnore: params.ForceSkipIgnore,+ })- if !shared.HasFileMapSupport(path) {- // not a tree-sitter supported file type- continue- }+ errCh <- nil+ }(inputFilePath)+ }- if _, ok := mapInputsByPath[mapInputPath]; !ok {- mapInputsByPath[mapInputPath] = shared.FileMapInputs{}- }+ } else {+ flattenedPaths, err := ParseInputPaths(inputFilePaths, params)+ if err != nil {+ onErr(fmt.Errorf("failed to parse input paths: %v", err))+ }+ // // Dump flattenedPaths to JSON file for debugging+ // debugData, err := json.MarshalIndent(flattenedPaths, "", " ")+ // if err != nil {+ // onErr(fmt.Errorf("failed to marshal flattened paths: %v", err))+ // return+ // }++ // if err := os.WriteFile("flattened_paths_debug.json", debugData, 0644); err != nil {+ // onErr(fmt.Errorf("failed to write debug file: %v", err))+ // return+ // }++ if !params.ForceSkipIgnore {+ var filteredPaths []string+ for _, path := range flattenedPaths {+ if _, ok := paths.ActivePaths[path]; ok {+ filteredPaths = append(filteredPaths, path)+ } else {+ if _, ok := paths.IgnoredPaths[path]; ok {+ ignoredPaths[path] = paths.IgnoredPaths[path]+ }+ }+ }+ flattenedPaths = filteredPaths}- var contextType shared.ContextType- isImage := shared.IsImageFile(path)- if isImage {- contextType = shared.ContextImageType- } else if params.DefsOnly {- contextType = shared.ContextMapType+ // Add this check for the number of files (after filtering out ignored/irrelevant paths)+ var numPaths int+ if params.DefsOnly {+ for _, path := range flattenedPaths {+ if shared.HasFileMapSupport(path) {+ numPaths+++ }+ }} else {- contextType = shared.ContextFileType+ numPaths = len(flattenedPaths)}- if !params.DefsOnly {- composite := strings.Join([]string{string(contextType), path}, "|")+ if numPaths > shared.MaxContextCount {+ onErr(fmt.Errorf("too many files to load (found %d, limit is %d)", numPaths, shared.MaxContextCount))+ }++ inputFilePaths = flattenedPaths++ for _, path := range flattenedPaths {+ var mapInputPath string+ if params.DefsOnly {+ for _, inputPath := range toLoadMapPaths {+ // Clean and make absolute paths for comparison+ absPath, err := filepath.Abs(path)+ if err != nil {+ continue+ }+ absInputPath, err := filepath.Abs(inputPath)+ if err != nil {+ continue+ }++ // Check if paths are equal or if path is under inputPath+ if absPath == absInputPath || strings.HasPrefix(absPath+string(filepath.Separator), absInputPath+string(filepath.Separator)) {+ mapInputPath = inputPath+ break+ }+ }++ if mapInputPath == "" {+ continue // not a child of any input path+ }++ if !shared.HasFileMapSupport(path) {+ // not a tree-sitter supported file type+ continue+ }++ if _, ok := mapInputsByPath[mapInputPath]; !ok {+ mapInputsByPath[mapInputPath] = shared.FileMapInputs{}+ }- if existsByComposite[composite] != nil {- alreadyLoadedByComposite[composite] = existsByComposite[composite]- continue}- }- numRoutines++- go func(path string) {- // File size check- fileInfo, err := os.Stat(path)- if err != nil {- errCh <- fmt.Errorf("failed to get file info for %s: %v", path, err)- return+ var contextType shared.ContextType+ isImage := shared.IsImageFile(path)+ if isImage {+ contextType = shared.ContextImageType+ } else if params.DefsOnly {+ contextType = shared.ContextMapType+ } else {+ contextType = shared.ContextFileType}- size := fileInfo.Size()+ if !params.DefsOnly {+ composite := strings.Join([]string{string(contextType), path}, "|")- if size > shared.MaxContextBodySize {- errCh <- fmt.Errorf("file %s exceeds size limit (size %.2f MB, limit %d MB)", path, float64(fileInfo.Size())/1024/1024, int(shared.MaxContextBodySize)/1024/1024)- return+ if existsByComposite[composite] != nil {+ alreadyLoadedByComposite[composite] = existsByComposite[composite]+ continue+ }}- fileContent, err := os.ReadFile(path)- if err != nil {- errCh <- fmt.Errorf("failed to read the file %s: %v", path, err)- return- }+ numRoutines+++ go func(path string) {+ // File size check+ fileInfo, err := os.Stat(path)+ if err != nil {+ errCh <- fmt.Errorf("failed to get file info for %s: %v", path, err)+ return+ }- contextMu.Lock()- defer contextMu.Unlock()+ size := fileInfo.Size()- if params.DefsOnly {- if mapSize+size > shared.MaxContextMapInputSize {- errCh <- fmt.Errorf("map size limit exceeded (size %.2f MB, limit %d MB)", float64(mapSize+size)/1024/1024, int(shared.MaxContextBodySize)/1024/1024)+ if size > shared.MaxContextBodySize {+ errCh <- fmt.Errorf("file %s exceeds size limit (size %.2f MB, limit %d MB)", path, float64(fileInfo.Size())/1024/1024, int(shared.MaxContextBodySize)/1024/1024)return}- if len(mapInputsByPath[mapInputPath])+1 > shared.MaxContextMapPaths {- errCh <- fmt.Errorf("map paths limit exceeded (found %d, limit %d)", len(mapInputsByPath[mapInputPath])+1, shared.MaxContextMapPaths)+ fileContent, err := os.ReadFile(path)+ if err != nil {+ errCh <- fmt.Errorf("failed to read the file %s: %v", path, err)return}- mapInputsByPath[mapInputPath][path] = string(fileContent)- mapSize += size- } else if isImage {- loadContextReq = append(loadContextReq, &shared.LoadContextParams{- ContextType: shared.ContextImageType,- Name: path,- Body: base64.StdEncoding.EncodeToString(fileContent),- FilePath: path,- ImageDetail: params.ImageDetail,- })- } else {- loadContextReq = append(loadContextReq, &shared.LoadContextParams{- ContextType: shared.ContextFileType,- Name: path,- Body: string(fileContent),- FilePath: path,- })- }+ contextMu.Lock()+ defer contextMu.Unlock()- errCh <- nil- }(path)- }+ if params.DefsOnly {+ if mapSize+size > shared.MaxContextMapInputSize {+ errCh <- fmt.Errorf("map size limit exceeded (size %.2f MB, limit %d MB)", float64(mapSize+size)/1024/1024, int(shared.MaxContextBodySize)/1024/1024)+ return+ }- if params.DefsOnly {- for _, inputPath := range toLoadMapPaths {- var name string- if inputPath == "." {- name = "cwd"- } else if inputPath == ".." {- name = "parent"- } else {- name = inputPath- }+ if len(mapInputsByPath[mapInputPath])+1 > shared.MaxContextMapPaths {+ errCh <- fmt.Errorf("map paths limit exceeded (found %d, limit %d)", len(mapInputsByPath[mapInputPath])+1, shared.MaxContextMapPaths)+ return+ }++ mapInputsByPath[mapInputPath][path] = string(fileContent)+ mapSize += size+ } else if isImage {+ loadContextReq = append(loadContextReq, &shared.LoadContextParams{+ ContextType: shared.ContextImageType,+ Name: path,+ Body: base64.StdEncoding.EncodeToString(fileContent),+ FilePath: path,+ ImageDetail: params.ImageDetail,+ })+ } else {+ loadContextReq = append(loadContextReq, &shared.LoadContextParams{+ ContextType: shared.ContextFileType,+ Name: path,+ Body: string(fileContent),+ FilePath: path,+ })+ }++ errCh <- nil+ }(path)+ }++ if params.DefsOnly {+ for _, inputPath := range toLoadMapPaths {+ var name string+ if inputPath == "." {+ name = "cwd"+ } else if inputPath == ".." {+ name = "parent"+ } else {+ name = inputPath+ }- loadContextReq = append(loadContextReq, &shared.LoadContextParams{- ContextType: shared.ContextMapType,- Name: name,- MapInputs: mapInputsByPath[inputPath],- FilePath: inputPath,- })+ loadContextReq = append(loadContextReq, &shared.LoadContextParams{+ ContextType: shared.ContextMapType,+ Name: name,+ MapInputs: mapInputsByPath[inputPath],+ FilePath: inputPath,+ })+ }}}}@@ -478,7 +520,7 @@ func MustLoadContext(resources []string, params *types.LoadContextParams) {onErr(fmt.Errorf("failed to check context conflicts: %v", err))}- if len(loadContextReq) == 0 {+ if len(loadContextReq)+len(cachedMapPaths) == 0 {term.StopSpinner()fmt.Println("🤷♂️ No context loaded")@@ -487,7 +529,7 @@ func MustLoadContext(resources []string, params *types.LoadContextParams) {printAlreadyLoadedMsg(alreadyLoadedByComposite)didOutputReason = true}- if len(ignoredPaths) > 0 {+ if len(ignoredPaths) > 0 && !params.SkipIgnoreWarning {printIgnoredMsg()didOutputReason = true}@@ -521,10 +563,15 @@ func MustLoadContext(resources []string, params *types.LoadContextParams) {os.Exit(0)}- res, apiErr := api.Client.LoadContext(CurrentPlanId, CurrentBranch, loadContextReq)+ var res *shared.LoadContextResponse+ if cachedMapLoadRes != nil {+ res = cachedMapLoadRes+ } else {+ res, apiErr = api.Client.LoadContext(CurrentPlanId, CurrentBranch, loadContextReq)- if apiErr != nil {- onErr(fmt.Errorf("failed to load context: %v", apiErr.Msg))+ if apiErr != nil {+ onErr(fmt.Errorf("failed to load context: %v", apiErr.Msg))+ }}term.StopSpinner()@@ -551,7 +598,7 @@ func MustLoadContext(resources []string, params *types.LoadContextParams) {printAlreadyLoadedMsg(alreadyLoadedByComposite)}- if len(ignoredPaths) > 0 {+ if len(ignoredPaths) > 0 && !params.SkipIgnoreWarning {printIgnoredMsg()}}@@ -604,6 +651,26 @@ func AutoLoadContextFiles(files []string) (string, error) {return res.Msg, nil}+func MustLoadAutoContextMap() {+ fmt.Println("Select a base directory to load context from. Press enter to use current directory (.), otherwise use a relative path like 'src' or 'lib'.")+ fmt.Println()++ baseDir, err := term.GetUserStringInputWithDefault("Base directory for context:", ".")++ if err != nil {+ term.OutputErrorAndExit("Error: %v", err)+ }++ if baseDir == "" {+ baseDir = "."+ }++ MustLoadContext([]string{baseDir}, &types.LoadContextParams{+ DefsOnly: true,+ SkipIgnoreWarning: true,+ })+}+func printAlreadyLoadedMsg(alreadyLoadedByComposite map[string]*shared.Context) {fmt.Println()pronoun := "they're"diff --git a/app/cli/lib/plan_config.go b/app/cli/lib/plan_config.gonew file mode 100644index 00000000..6ace1fb4--- /dev/null+++ b/app/cli/lib/plan_config.go@@ -0,0 +1,59 @@+package lib++import (+ "os"+ "sort"++ "github.com/olekukonko/tablewriter"+ "github.com/plandex/plandex/shared"+)++func ShowPlanConfig(config *shared.PlanConfig, key string) {+ table := tablewriter.NewWriter(os.Stdout)+ table.SetAutoWrapText(true)+ table.SetHeader([]string{"Name", "Value", "Description"})++ numVisibleSettings := 0+ for k, setting := range shared.ConfigSettingsByKey {+ if key != "" && k != key {+ continue+ }++ if setting.Visible == nil || setting.Visible(config) {+ numVisibleSettings+++ }+ }+ numOutput := 0++ sortedSettings := make([][]string, 0, len(shared.ConfigSettingsByKey))++ for k, setting := range shared.ConfigSettingsByKey {+ if key != "" && k != key {+ continue+ }++ if setting.Visible == nil || setting.Visible(config) {+ var sortKey string+ if setting.SortKey != "" {+ sortKey = setting.SortKey+ } else {+ sortKey = k+ }+ sortedSettings = append(sortedSettings, []string{sortKey, setting.Name, setting.Getter(config), setting.Desc})+ }+ }++ sort.Slice(sortedSettings, func(i, j int) bool {+ return sortedSettings[i][0] < sortedSettings[j][0]+ })++ for _, row := range sortedSettings {+ table.Append(row[1:])+ numOutput+++ if numOutput < numVisibleSettings {+ table.Append([]string{"", "", ""})+ }+ }++ table.Render()+}diff --git a/app/cli/term/help.go b/app/cli/term/help.goindex b25831b6..ba21b948 100644--- a/app/cli/term/help.go+++ b/app/cli/term/help.go@@ -16,8 +16,8 @@ var CmdDesc = map[string][2]string{"cd": {"", "set current plan by name or index"},"load": {"l", "load files/dirs/urls/notes/images or pipe data into context"},"tell": {"t", "describe a task to complete"},- "chat": {"ct", "ask a question or chat"},- "changes": {"ch", "review pending changes in a TUI"},+ "chat": {"ch", "ask a question or chat"},+ "changes": {"", "review pending changes in a TUI"},"diff": {"", "review pending changes in 'git diff' format"},"diff --plain": {"", "review pending changes in 'git diff' format with no color formatting"},"diff --ui": {"", "review pending changes in a local browser UI"},@@ -69,6 +69,10 @@ var CmdDesc = map[string][2]string{"credits": {"", "show Plandex Cloud credits balance"},"usage": {"", "show Plandex Cloud credits transaction log"},"billing": {"", "show Plandex Cloud billing settings"},+ "config": {"", "show current plan config"},+ "set-config": {"", "update current plan config"},+ "config default": {"", "show default config for new plans"},+ "set-config default": {"", "update default config for new plans"},}func PrintCmds(prefix string, cmds ...string) {@@ -173,6 +177,10 @@ func PrintCustomHelp(all bool) {printCmds(builder, " ", []color.Attribute{color.Bold, ColorHiCyan}, "ps", "connect", "stop")fmt.Fprintln(builder)+ color.New(color.Bold, color.BgCyan, color.FgHiWhite).Fprintln(builder, " Config ")+ printCmds(builder, " ", []color.Attribute{color.Bold, ColorHiCyan}, "config", "set-config", "config default", "set-config default")+ fmt.Fprintln(builder)+color.New(color.Bold, color.BgCyan, color.FgHiWhite).Fprintln(builder, " AI Models ")printCmds(builder, " ", []color.Attribute{color.Bold, ColorHiCyan}, "models", "models default", "models available", "set-model", "set-model default", "models available --custom", "models add", "models delete", "model-packs", "model-packs --custom", "model-packs create", "model-packs delete")fmt.Fprintln(builder)diff --git a/app/cli/term/spinner.go b/app/cli/term/spinner.goindex 9ccd5e6a..21570353 100644--- a/app/cli/term/spinner.go+++ b/app/cli/term/spinner.go@@ -1,6 +1,7 @@package termimport (+ "sync/atomic""time""github.com/briandowns/spinner"@@ -14,6 +15,7 @@ var startedAt time.Timevar lastMessage stringvar active bool+var currentWarningLoop int32func StartSpinner(msg string) {if active {@@ -51,3 +53,29 @@ func ResumeSpinner() {StartSpinner(lastMessage)}}++func LongSpinnerWithWarning(msg, warning string) {+ atomic.AddInt32(¤tWarningLoop, 1)+ currentLoop := currentWarningLoop++ StartSpinner(msg)++ var flashWarning func()+ flashWarning = func() {+ go func() {+ time.Sleep(3 * time.Second)+ if !active || atomic.LoadInt32(¤tWarningLoop) != currentLoop {+ return+ }+ StartSpinner(warning)++ time.Sleep(2 * time.Second)+ if !active || atomic.LoadInt32(¤tWarningLoop) != currentLoop {+ return+ }+ StartSpinner(msg)+ flashWarning()+ }()+ }+ flashWarning()+}diff --git a/app/cli/types/api.go b/app/cli/types/api.goindex dde07a30..476834eb 100644--- a/app/cli/types/api.go+++ b/app/cli/types/api.go@@ -77,6 +77,7 @@ type ApiClient interface {UpdateContext(planId, branch string, req shared.UpdateContextRequest) (*shared.UpdateContextResponse, *shared.ApiError)DeleteContext(planId, branch string, req shared.DeleteContextRequest) (*shared.DeleteContextResponse, *shared.ApiError)ListContext(planId, branch string) ([]*shared.Context, *shared.ApiError)+ LoadCachedFileMap(planId, branch string, req shared.LoadCachedFileMapRequest) (*shared.LoadCachedFileMapResponse, *shared.ApiError)ListConvo(planId, branch string) ([]*shared.ConvoMessage, *shared.ApiError)GetPlanStatus(planId, branch string) (string, *shared.ApiError)@@ -94,9 +95,9 @@ type ApiClient interface {UpdateOrgDefaultSettings(req shared.UpdateSettingsRequest) (*shared.UpdateSettingsResponse, *shared.ApiError)GetPlanConfig(planId string) (*shared.PlanConfig, *shared.ApiError)- UpdatePlanConfig(planId string, req shared.UpdatePlanConfigRequest) (*shared.UpdatePlanConfigResponse, *shared.ApiError)+ UpdatePlanConfig(planId string, req shared.UpdatePlanConfigRequest) *shared.ApiErrorGetDefaultPlanConfig() (*shared.PlanConfig, *shared.ApiError)- UpdateDefaultPlanConfig(req shared.UpdateDefaultPlanConfigRequest) (*shared.UpdateDefaultPlanConfigResponse, *shared.ApiError)+ UpdateDefaultPlanConfig(req shared.UpdateDefaultPlanConfigRequest) *shared.ApiErrorCreateCustomModel(model *shared.AvailableModel) *shared.ApiErrorListCustomModels() ([]*shared.AvailableModel, *shared.ApiError)@@ -111,4 +112,3 @@ type ApiClient interface {GetContextBody(planId, branch, contextId string) (*shared.GetContextBodyResponse, *shared.ApiError)AutoLoadContext(planId, branch string, req shared.LoadContextRequest) (*shared.LoadContextResponse, *shared.ApiError)}-diff --git a/app/cli/types/types.go b/app/cli/types/types.goindex c8f776ca..fc84f39f 100644--- a/app/cli/types/types.go+++ b/app/cli/types/types.go@@ -6,12 +6,13 @@ import ()type LoadContextParams struct {- Note string- Recursive bool- NamesOnly bool- ForceSkipIgnore bool- ImageDetail openai.ImageURLDetail- DefsOnly bool+ Note string+ Recursive bool+ NamesOnly bool+ ForceSkipIgnore bool+ ImageDetail openai.ImageURLDetail+ DefsOnly bool+ SkipIgnoreWarning bool}type ContextOutdatedResult struct {diff --git a/app/server/db/context_helpers.go b/app/server/db/context_helpers.goindex 6d2b6138..f2e52546 100644--- a/app/server/db/context_helpers.go+++ b/app/server/db/context_helpers.go@@ -2,6 +2,7 @@ package dbimport ("context"+ "crypto/md5""crypto/sha256""encoding/hex""encoding/json"@@ -156,7 +157,7 @@ func ContextRemove(orgId, planId string, contexts []*Context) error {return nil}-func StoreContext(context *Context) error {+func StoreContext(context *Context, skipMapCache bool) error {// log.Println("Storing context", context.Id)// log.Println("Num tokens", context.NumTokens)@@ -224,9 +225,84 @@ func StoreContext(context *Context) error {context.Body = originalBodycontext.MapParts = originalMapParts+ if mapPath != "" && !skipMapCache {+ log.Println("StoreContext - context.MapParts length", len(context.MapParts))++ mapCacheDir := getProjectMapCacheDir(context.OrgId, context.ProjectId)++ // ensure map cache dir exists+ err = os.MkdirAll(mapCacheDir, os.ModePerm)+ if err != nil {+ return fmt.Errorf("error creating map cache dir: %v", err)+ }++ filePathHash := md5.Sum([]byte(context.FilePath))+ filePathHashStr := hex.EncodeToString(filePathHash[:])++ mapCachePath := filepath.Join(mapCacheDir, filePathHashStr+".json")++ log.Println("StoreContext - mapCachePath", mapCachePath)++ cachedContext := Context{+ ContextType: shared.ContextMapType,+ FilePath: context.FilePath,+ Name: context.Name,+ Body: context.Body,+ NumTokens: context.NumTokens,+ MapParts: context.MapParts,+ MapShas: context.MapShas,+ MapTokens: context.MapTokens,+ UpdatedAt: context.UpdatedAt,+ }++ cachedContextBytes, err := json.MarshalIndent(cachedContext, "", " ")+ if err != nil {+ return fmt.Errorf("failed to marshal cached context: %v", err)+ }++ err = os.WriteFile(mapCachePath, cachedContextBytes, 0644)+ if err != nil {+ return fmt.Errorf("failed to write context map to file %s: %v", mapCachePath, err)+ }+ }+return nil}+func GetCachedMap(orgId, projectId, filePath string) (*Context, error) {+ mapCacheDir := getProjectMapCacheDir(orgId, projectId)++ filePathHash := md5.Sum([]byte(filePath))+ filePathHashStr := hex.EncodeToString(filePathHash[:])++ mapCachePath := filepath.Join(mapCacheDir, filePathHashStr+".json")++ log.Println("GetCachedMap - mapCachePath", mapCachePath)++ mapCacheBytes, err := os.ReadFile(mapCachePath)+ if err != nil {+ if os.IsNotExist(err) {+ return nil, nil+ }++ return nil, fmt.Errorf("error reading cached map: %v", err)+ }++ var context Context+ err = json.Unmarshal(mapCacheBytes, &context)+ if err != nil {+ return nil, fmt.Errorf("error unmarshalling cached map: %v", err)+ }++ return &context, nil+}++type CachedMap struct {+ MapParts shared.FileMapBodies+ MapShas map[string]string+ MapTokens map[string]int+}+type LoadContextsParams struct {Req *shared.LoadContextRequestOrgId string@@ -234,6 +310,7 @@ type LoadContextsParams struct {BranchName stringUserId stringSkipConflictInvalidation bool+ CachedMapsByPath map[string]*CachedMap}func LoadContexts(ctx Ctx, params LoadContextsParams) (*shared.LoadContextResponse, []*Context, error) {@@ -297,28 +374,46 @@ func LoadContexts(ctx Ctx, params LoadContextsParams) (*shared.LoadContextRespon*req = filteredReq+ log.Println("LoadContexts - len(params.CachedMapsByPath)", len(params.CachedMapsByPath))+for _, context := range *req {tempId := uuid.New().String()var numTokens intvar err error- if context.ContextType == shared.ContextMapType && len(context.MapInputs) > 0 {- // Process file maps- mappedFiles, err := file_map.ProcessMapFiles(ctx, context.MapInputs)- if err != nil {- return nil, nil, fmt.Errorf("error processing map files: %v", err)+ if context.ContextType == shared.ContextMapType && (len(context.MapInputs) > 0 || params.CachedMapsByPath != nil) {+ var mappedFiles shared.FileMapBodies+ if params.CachedMapsByPath != nil && params.CachedMapsByPath[context.FilePath] != nil {+ log.Println("Using cached map for", context.FilePath)+ mappedFiles = params.CachedMapsByPath[context.FilePath].MapParts+ } else {+ log.Println("Processing map files for", context.FilePath)+ // Process file maps+ mappedFiles, err = file_map.ProcessMapFiles(ctx, context.MapInputs)+ if err != nil {+ return nil, nil, fmt.Errorf("error processing map files: %v", err)+ }}- mapShas := make(map[string]string, len(context.MapInputs))- mapTokens := make(map[string]int, len(context.MapInputs))- for path, input := range context.MapInputs {- hash := sha256.Sum256([]byte(input))- mapShas[path] = hex.EncodeToString(hash[:])- mapBody := mappedFiles[path]- mapTokens[path], err = shared.GetNumTokens(mapBody)- if err != nil {- return nil, nil, fmt.Errorf("error getting num tokens for %s: %v", path, err)+ var mapShas map[string]string+ var mapTokens map[string]int++ if params.CachedMapsByPath != nil && params.CachedMapsByPath[context.FilePath] != nil {+ mapShas = params.CachedMapsByPath[context.FilePath].MapShas+ mapTokens = params.CachedMapsByPath[context.FilePath].MapTokens+ } else {+ mapShas = make(map[string]string, len(context.MapInputs))+ mapTokens = make(map[string]int, len(context.MapInputs))++ for path, input := range context.MapInputs {+ hash := sha256.Sum256([]byte(input))+ mapShas[path] = hex.EncodeToString(hash[:])+ mapBody := mappedFiles[path]+ mapTokens[path], err = shared.GetNumTokens(mapBody)+ if err != nil {+ return nil, nil, fmt.Errorf("error getting num tokens for %s: %v", path, err)+ }}}@@ -334,6 +429,7 @@ func LoadContexts(ctx Ctx, params LoadContextsParams) (*shared.LoadContextResponOrgId: orgId,OwnerId: userId,PlanId: planId,+ ProjectId: plan.ProjectId,ContextType: shared.ContextMapType,Name: context.Name,Url: context.Url,@@ -375,14 +471,14 @@ func LoadContexts(ctx Ctx, params LoadContextsParams) (*shared.LoadContextRespondbContextsCh := make(chan *Context)errCh := make(chan error)- for tempId, params := range paramsByTempId {+ for tempId, loadParams := range paramsByTempId {- go func(tempId string, params *shared.LoadContextParams) {- hash := sha256.Sum256([]byte(params.Body))+ go func(tempId string, loadParams *shared.LoadContextParams) {+ hash := sha256.Sum256([]byte(loadParams.Body))sha := hex.EncodeToString(hash[:])var context Context- if mapContext, ok := mapContextsByFilePath[params.FilePath]; ok {+ if mapContext, ok := mapContextsByFilePath[loadParams.FilePath]; ok {context = mapContext} else {// log.Println("tempId", tempId, "params.FilePath", params.FilePath, "sha", sha)@@ -393,19 +489,20 @@ func LoadContexts(ctx Ctx, params LoadContextsParams) (*shared.LoadContextResponOrgId: orgId,OwnerId: userId,PlanId: planId,- ContextType: params.ContextType,- Name: params.Name,- Url: params.Url,- FilePath: params.FilePath,+ ProjectId: plan.ProjectId,+ ContextType: loadParams.ContextType,+ Name: loadParams.Name,+ Url: loadParams.Url,+ FilePath: loadParams.FilePath,NumTokens: numTokensByTempId[tempId],Sha: sha,- Body: params.Body,- ForceSkipIgnore: params.ForceSkipIgnore,- ImageDetail: params.ImageDetail,+ Body: loadParams.Body,+ ForceSkipIgnore: loadParams.ForceSkipIgnore,+ ImageDetail: loadParams.ImageDetail,}}- err := StoreContext(&context)+ err := StoreContext(&context, params.CachedMapsByPath != nil)if err != nil {errCh <- err@@ -414,7 +511,7 @@ func LoadContexts(ctx Ctx, params LoadContextsParams) (*shared.LoadContextRespondbContextsCh <- &context- }(tempId, params)+ }(tempId, loadParams)}var dbContexts []*Context@@ -698,7 +795,7 @@ func UpdateContexts(params UpdateContextsParams) (*shared.UpdateContextResponse,// log.Println("storing context", id)// log.Printf("context name: %s, sha: %s\n", context.Name, context.Sha)- err := StoreContext(context)+ err := StoreContext(context, false)if err != nil {errCh <- fmt.Errorf("error storing context: %v", err)@@ -708,6 +805,10 @@ func UpdateContexts(params UpdateContextsParams) (*shared.UpdateContextResponse,// log.Println("stored context", id)// log.Println()+ if context.ContextType == shared.ContextMapType {++ }+errCh <- nil}(id, params)}diff --git a/app/server/db/data_models.go b/app/server/db/data_models.goindex 0961d00e..5fc3362c 100644--- a/app/server/db/data_models.go+++ b/app/server/db/data_models.go@@ -42,22 +42,24 @@ func (org *Org) ToApi() *shared.Org {}type User struct {- Id string `db:"id"`- Name string `db:"name"`- Email string `db:"email"`- Domain string `db:"domain"`- NumNonDraftPlans int `db:"num_non_draft_plans"`- CreatedAt time.Time `db:"created_at"`- UpdatedAt time.Time `db:"updated_at"`+ Id string `db:"id"`+ Name string `db:"name"`+ Email string `db:"email"`+ Domain string `db:"domain"`+ NumNonDraftPlans int `db:"num_non_draft_plans"`+ DefaultPlanConfig *shared.PlanConfig `db:"default_plan_config"`+ CreatedAt time.Time `db:"created_at"`+ UpdatedAt time.Time `db:"updated_at"`}func (user *User) ToApi() *shared.User {return &shared.User{- Id: user.Id,- Name: user.Name,- Email: user.Email,- NumNonDraftPlans: user.NumNonDraftPlans,- IsTrial: false, // legacy field+ Id: user.Id,+ Name: user.Name,+ Email: user.Email,+ NumNonDraftPlans: user.NumNonDraftPlans,+ IsTrial: false, // legacy field+ DefaultPlanConfig: user.DefaultPlanConfig,}}@@ -121,17 +123,18 @@ func (project *Project) ToApi() *shared.Project {}type Plan struct {- Id string `db:"id"`- OrgId string `db:"org_id"`- OwnerId string `db:"owner_id"`- ProjectId string `db:"project_id"`- Name string `db:"name"`- SharedWithOrgAt *time.Time `db:"shared_with_org_at,omitempty"`- TotalReplies int `db:"total_replies"`- ActiveBranches int `db:"active_branches"`- ArchivedAt *time.Time `db:"archived_at,omitempty"`- CreatedAt time.Time `db:"created_at"`- UpdatedAt time.Time `db:"updated_at"`+ Id string `db:"id"`+ OrgId string `db:"org_id"`+ OwnerId string `db:"owner_id"`+ ProjectId string `db:"project_id"`+ Name string `db:"name"`+ SharedWithOrgAt *time.Time `db:"shared_with_org_at,omitempty"`+ TotalReplies int `db:"total_replies"`+ ActiveBranches int `db:"active_branches"`+ PlanConfig *shared.PlanConfig `db:"plan_config"`+ ArchivedAt *time.Time `db:"archived_at,omitempty"`+ CreatedAt time.Time `db:"created_at"`+ UpdatedAt time.Time `db:"updated_at"`}func (plan *Plan) ToApi() *shared.Plan {@@ -143,6 +146,7 @@ func (plan *Plan) ToApi() *shared.Plan {SharedWithOrgAt: plan.SharedWithOrgAt,TotalReplies: plan.TotalReplies,ActiveBranches: plan.ActiveBranches,+ PlanConfig: plan.PlanConfig,ArchivedAt: plan.ArchivedAt,CreatedAt: plan.CreatedAt,UpdatedAt: plan.UpdatedAt,@@ -379,6 +383,7 @@ type Context struct {Id string `json:"id"`OrgId string `json:"orgId"`OwnerId string `json:"ownerId"`+ ProjectId string `json:"projectId"`PlanId string `json:"planId"`ContextType shared.ContextType `json:"contextType"`Name string `json:"name"`@@ -397,6 +402,30 @@ type Context struct {UpdatedAt time.Time `json:"updatedAt"`}+func (context *Context) ToMeta() *Context {+ // everything except body and mapParts+ return &Context{+ Id: context.Id,+ OrgId: context.OrgId,+ OwnerId: context.OwnerId,+ ProjectId: context.ProjectId,+ PlanId: context.PlanId,+ ContextType: context.ContextType,+ Name: context.Name,+ Url: context.Url,+ FilePath: context.FilePath,+ Sha: context.Sha,+ NumTokens: context.NumTokens,+ BodySize: context.BodySize,+ ForceSkipIgnore: context.ForceSkipIgnore,+ ImageDetail: context.ImageDetail,+ MapShas: context.MapShas,+ MapTokens: context.MapTokens,+ CreatedAt: context.CreatedAt,+ UpdatedAt: context.UpdatedAt,+ }+}+func (context *Context) ToApi() *shared.Context {return &shared.Context{Id: context.Id,diff --git a/app/server/db/fs.go b/app/server/db/fs.goindex eebc4de1..b28a067d 100644--- a/app/server/db/fs.go+++ b/app/server/db/fs.go@@ -76,6 +76,14 @@ func getOrgDir(orgId string) string {return filepath.Join(BaseDir, "orgs", orgId)}+func getProjectDir(orgId, projectId string) string {+ return filepath.Join(getOrgDir(orgId), "projects", projectId)+}++func getProjectMapCacheDir(orgId, projectId string) string {+ return filepath.Join(getProjectDir(orgId, projectId), "map_cache")+}+func getPlanDir(orgId, planId string) string {return filepath.Join(getOrgDir(orgId), "plans", planId)}diff --git a/app/server/db/plan_config_helpers.go b/app/server/db/plan_config_helpers.goindex 043ddba0..04748e8a 100644--- a/app/server/db/plan_config_helpers.go+++ b/app/server/db/plan_config_helpers.go@@ -1,9 +1,7 @@package dbimport (- "database/sql""fmt"- "time""github.com/jmoiron/sqlx""github.com/plandex/plandex/shared"@@ -16,10 +14,6 @@ func GetPlanConfig(planId string) (*shared.PlanConfig, error) {err := Conn.Get(&config, query, planId)if err != nil {- if err == sql.ErrNoRows {- // Return empty config if not found- return &shared.PlanConfig{}, nil- }return nil, fmt.Errorf("error getting plan config: %v", err)}@@ -29,12 +23,11 @@ func GetPlanConfig(planId string) (*shared.PlanConfig, error) {func StorePlanConfig(planId string, config *shared.PlanConfig) error {query := `UPDATE plans- SET plan_config = $1, updated_at = $2- WHERE id = $3+ SET plan_config = $1+ WHERE id = $2`- updatedAt := time.Now()- _, err := Conn.Exec(query, config, updatedAt, planId)+ _, err := Conn.Exec(query, config, planId)if err != nil {return fmt.Errorf("error storing plan config: %v", err)@@ -44,50 +37,24 @@ func StorePlanConfig(planId string, config *shared.PlanConfig) error {}func GetDefaultPlanConfig(userId string) (*shared.PlanConfig, error) {- query := "SELECT plan_config FROM default_plan_config WHERE user_id = $1"+ query := "SELECT default_plan_config FROM users WHERE id = $1"var config shared.PlanConfigerr := Conn.Get(&config, query, userId)if err != nil {- if err == sql.ErrNoRows {- // Return empty config if not found- return &shared.PlanConfig{}, nil- }return nil, fmt.Errorf("error getting default plan config: %v", err)}return &config, nil}-func GetDefaultPlanConfigForUpdate(userId string, tx *sqlx.Tx) (*shared.PlanConfig, error) {- query := "SELECT plan_config FROM default_plan_config WHERE user_id = $1 FOR UPDATE"-- var config shared.PlanConfig- err := tx.Get(&config, query, userId)-- if err != nil {- if err == sql.ErrNoRows {- // Return empty config if not found- return &shared.PlanConfig{}, nil- }- return nil, fmt.Errorf("error getting default plan config for update: %v", err)- }-- return &config, nil-}-func StoreDefaultPlanConfig(userId string, config *shared.PlanConfig, tx *sqlx.Tx) error {query := `- INSERT INTO default_plan_config (user_id, plan_config, updated_at)- VALUES ($1, $2, $3)- ON CONFLICT (user_id) DO UPDATE- SET plan_config = EXCLUDED.plan_config,- updated_at = EXCLUDED.updated_at+ UPDATE users SET default_plan_config = $1 WHERE id = $2`- updatedAt := time.Now()- _, err := tx.Exec(query, userId, config, updatedAt)+ _, err := tx.Exec(query, config, userId)if err != nil {return fmt.Errorf("error storing default plan config: %v", err)diff --git a/app/server/db/plan_helpers.go b/app/server/db/plan_helpers.goindex bf955699..44093dc7 100644--- a/app/server/db/plan_helpers.go+++ b/app/server/db/plan_helpers.go@@ -33,15 +33,22 @@ func CreatePlan(orgId, projectId, userId, name string) (*Plan, error) {}}()- query := `INSERT INTO plans (org_id, owner_id, project_id, name)- VALUES ($1, $2, $3, $4)+ planConfig, err := GetDefaultPlanConfig(userId)++ if err != nil {+ return nil, fmt.Errorf("error getting default plan config: %v", err)+ }++ query := `INSERT INTO plans (org_id, owner_id, project_id, name, plan_config)+ VALUES ($1, $2, $3, $4, $5)RETURNING id, created_at, updated_at`plan := &Plan{- OrgId: orgId,- OwnerId: userId,- ProjectId: projectId,- Name: name,+ OrgId: orgId,+ OwnerId: userId,+ ProjectId: projectId,+ Name: name,+ PlanConfig: planConfig,}err = tx.QueryRow(@@ -50,6 +57,7 @@ func CreatePlan(orgId, projectId, userId, name string) (*Plan, error) {userId,projectId,name,+ planConfig,).Scan(&plan.Id,&plan.CreatedAt,@@ -413,3 +421,12 @@ func BumpPlanUpdatedAt(planId string, t time.Time) error {return nil}++func GetPlanIdsForProject(projectId string) ([]string, error) {+ var ids []string+ err := Conn.Select(&ids, "SELECT id FROM plans WHERE project_id = $1", projectId)+ if err != nil {+ return nil, fmt.Errorf("error getting plan ids for project: %v", err)+ }+ return ids, nil+}diff --git a/app/server/handlers/context_helper.go b/app/server/handlers/context_helper.goindex 2a9c664f..c2713f40 100644--- a/app/server/handlers/context_helper.go+++ b/app/server/handlers/context_helper.go@@ -21,6 +21,7 @@ func loadContexts(loadReq *shared.LoadContextRequest,plan *db.Plan,branchName string,+ cachedMapsByPath map[string]*db.CachedMap,) (*shared.LoadContextResponse, []*db.Context) {// check file count and size limitstotalFiles := 0@@ -137,11 +138,12 @@ func loadContexts(}res, dbContexts, err := db.LoadContexts(ctx, db.LoadContextsParams{- OrgId: auth.OrgId,- Plan: plan,- BranchName: branchName,- Req: loadReq,- UserId: auth.User.Id,+ OrgId: auth.OrgId,+ Plan: plan,+ BranchName: branchName,+ Req: loadReq,+ UserId: auth.User.Id,+ CachedMapsByPath: cachedMapsByPath,})if err != nil {diff --git a/app/server/handlers/file_maps.go b/app/server/handlers/file_maps.goindex 5e416186..fc3b2e2f 100644--- a/app/server/handlers/file_maps.go+++ b/app/server/handlers/file_maps.go@@ -5,16 +5,23 @@ import ("fmt""log""net/http"+ "plandex-server/db""plandex-server/syntax/file_map""runtime""sync"+ "github.com/gorilla/mux""github.com/plandex/plandex/shared")func GetFileMapHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received request for GetFileMapHandler")+ auth := Authenticate(w, r, true)+ if auth == nil {+ return+ }+var req shared.GetFileMapRequestif err := json.NewDecoder(r.Body).Decode(&req); err != nil {http.Error(w, fmt.Sprintf("Error decoding request: %v", err), http.StatusBadRequest)@@ -67,3 +74,106 @@ func GetFileMapHandler(w http.ResponseWriter, r *http.Request) {w.Header().Set("Content-Type", "application/json")w.Write(respBytes)}++func LoadCachedFileMapHandler(w http.ResponseWriter, r *http.Request) {+ log.Println("Received request for LoadCachedFileMapHandler")++ auth := Authenticate(w, r, true)+ if auth == nil {+ return+ }++ vars := mux.Vars(r)+ planId := vars["planId"]+ branchName := vars["branch"]+ log.Println("planId: ", planId, "branchName: ", branchName)++ plan := authorizePlan(w, planId, auth)++ if plan == nil {+ return+ }++ var req shared.LoadCachedFileMapRequest+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ http.Error(w, fmt.Sprintf("Error decoding request: %v", err), http.StatusBadRequest)+ return+ }++ cachedMetaByPath := map[string]*shared.Context{}+ cachedMapsByPath := map[string]*db.CachedMap{}+ var mu sync.Mutex+ errCh := make(chan error, len(req.FilePaths))++ for _, path := range req.FilePaths {+ go func(path string) {+ cachedContext, err := db.GetCachedMap(plan.OrgId, plan.ProjectId, path)+ if err != nil {+ errCh <- fmt.Errorf("error getting cached map: %v", err)+ return+ }+ if cachedContext != nil {+ mu.Lock()+ cachedMetaByPath[path] = cachedContext.ToMeta().ToApi()+ cachedMapsByPath[path] = &db.CachedMap{+ MapParts: cachedContext.MapParts,+ MapShas: cachedContext.MapShas,+ MapTokens: cachedContext.MapTokens,+ }+ mu.Unlock()+ }+ errCh <- nil+ }(path)+ }++ for range req.FilePaths {+ err := <-errCh+ if err != nil {+ http.Error(w, fmt.Sprintf("Error getting cached map: %v", err), http.StatusInternalServerError)+ return+ }+ }++ resp := shared.LoadCachedFileMapResponse{}++ var loadRes *shared.LoadContextResponse+ if len(cachedMetaByPath) == 0 {+ log.Println("no cached maps found")+ } else {+ log.Println("cached map found")++ cachedByPath := map[string]bool{}+ for _, cachedContext := range cachedMetaByPath {+ cachedByPath[cachedContext.FilePath] = true+ }+ resp.CachedByPath = cachedByPath++ var loadReq shared.LoadContextRequest+ for _, cachedContext := range cachedMetaByPath {+ loadReq = append(loadReq, &shared.LoadContextParams{+ ContextType: shared.ContextMapType,+ Name: cachedContext.Name,+ FilePath: cachedContext.FilePath,+ Body: cachedContext.Body,+ })+ }++ loadRes, _ = loadContexts(w, r, auth, &loadReq, plan, branchName, cachedMapsByPath)++ if loadRes == nil {+ log.Println("LoadCachedFileMapHandler - loadRes is nil")+ return+ }++ resp.LoadRes = loadRes+ }++ bytes, err := json.Marshal(resp)+ if err != nil {+ log.Printf("Error marshalling response: %v", err)+ http.Error(w, fmt.Sprintf("Error marshalling response: %v", err), http.StatusInternalServerError)+ return+ }++ w.Write(bytes)+}diff --git a/app/server/handlers/plan_config.go b/app/server/handlers/plan_config.goindex 6ab10394..8e95fee2 100644--- a/app/server/handlers/plan_config.go+++ b/app/server/handlers/plan_config.go@@ -1,7 +1,6 @@package handlersimport (- "context""encoding/json""log""net/http"@@ -84,18 +83,6 @@ func UpdatePlanConfigHandler(w http.ResponseWriter, r *http.Request) {return}- res := shared.UpdatePlanConfigResponse{- Msg: "Successfully updated plan config",- }-- bytes, err := json.Marshal(res)- if err != nil {- log.Println("Error marshalling response: ", err)- http.Error(w, "Error marshalling response", http.StatusInternalServerError)- return- }-- w.Write(bytes)log.Println("UpdatePlanConfigHandler processed successfully")}@@ -107,7 +94,7 @@ func GetDefaultPlanConfigHandler(w http.ResponseWriter, r *http.Request) {return}- config, err := db.GetDefaultPlanConfig(auth.UserId)+ config, err := db.GetDefaultPlanConfig(auth.User.Id)if err != nil {log.Println("Error getting default plan config: ", err)http.Error(w, "Error getting default plan config", http.StatusInternalServerError)@@ -160,7 +147,7 @@ func UpdateDefaultPlanConfigHandler(w http.ResponseWriter, r *http.Request) {}}()- err = db.StoreDefaultPlanConfig(auth.UserId, req.Config, tx)+ err = db.StoreDefaultPlanConfig(auth.User.Id, req.Config, tx)if err != nil {log.Println("Error storing default plan config: ", err)http.Error(w, "Error storing default plan config", http.StatusInternalServerError)@@ -174,17 +161,5 @@ func UpdateDefaultPlanConfigHandler(w http.ResponseWriter, r *http.Request) {return}- res := shared.UpdateDefaultPlanConfigResponse{- Msg: "Successfully updated default plan config",- }-- bytes, err := json.Marshal(res)- if err != nil {- log.Println("Error marshalling response: ", err)- http.Error(w, "Error marshalling response", http.StatusInternalServerError)- return- }-- w.Write(bytes)log.Println("UpdateDefaultPlanConfigHandler processed successfully")}diff --git a/app/server/handlers/plans_context.go b/app/server/handlers/plans_context.goindex 1f306c8f..23e9cf10 100644--- a/app/server/handlers/plans_context.go+++ b/app/server/handlers/plans_context.go@@ -160,7 +160,7 @@ func LoadContextHandler(w http.ResponseWriter, r *http.Request) {return}- res, _ := loadContexts(w, r, auth, &requestBody, plan, branchName)+ res, _ := loadContexts(w, r, auth, &requestBody, plan, branchName, nil)if res == nil {returndiff --git a/app/server/handlers/plans_exec.go b/app/server/handlers/plans_exec.goindex 57d0a67c..f5f6920a 100644--- a/app/server/handlers/plans_exec.go+++ b/app/server/handlers/plans_exec.go@@ -333,7 +333,7 @@ func RespondMissingFileHandler(w http.ResponseWriter, r *http.Request) {FilePath: requestBody.FilePath,Body: requestBody.Body,},- }, plan, branch)+ }, plan, branch, nil)if res == nil {return}@@ -404,7 +404,7 @@ func AutoLoadContextHandler(w http.ResponseWriter, r *http.Request) {}log.Println("AutoLoadContextHandler - loading contexts")- res, dbContexts := loadContexts(w, r, auth, &requestBody, plan, branch)+ res, dbContexts := loadContexts(w, r, auth, &requestBody, plan, branch, nil)if res == nil {returndiff --git a/app/server/migrations/2024121400_plan_config.down.sql b/app/server/migrations/2024121400_plan_config.down.sqlindex 0f1f28dc..c9e70d15 100644--- a/app/server/migrations/2024121400_plan_config.down.sql+++ b/app/server/migrations/2024121400_plan_config.down.sql@@ -1,2 +1,3 @@-DROP TABLE IF EXISTS default_plan_config;ALTER TABLE plans DROP COLUMN IF EXISTS plan_config;++ALTER TABLE users DROP COLUMN IF EXISTS default_plan_config;\ No newline at end of filediff --git a/app/server/migrations/2024121400_plan_config.up.sql b/app/server/migrations/2024121400_plan_config.up.sqlindex ce19dbe1..9081f489 100644--- a/app/server/migrations/2024121400_plan_config.up.sql+++ b/app/server/migrations/2024121400_plan_config.up.sql@@ -1,14 +1,3 @@ALTER TABLE plans ADD COLUMN IF NOT EXISTS plan_config JSON;-CREATE TABLE IF NOT EXISTS default_plan_config (- id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),- user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,-- plan_config JSON,-- updated_at TIMESTAMP NOT NULL DEFAULT NOW(),- created_at TIMESTAMP NOT NULL DEFAULT NOW()-);-CREATE TRIGGER update_default_plan_config_modtime BEFORE UPDATE ON default_plan_config FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();--CREATE UNIQUE INDEX default_plan_config_user_idx ON default_plan_config(user_id);+ALTER TABLE users ADD COLUMN IF NOT EXISTS default_plan_config JSON;diff --git a/app/server/routes/routes.go b/app/server/routes/routes.goindex 96ce8420..4ce45301 100644--- a/app/server/routes/routes.go+++ b/app/server/routes/routes.go@@ -144,6 +144,13 @@ func addApiRoutes(r *mux.Router, prefix string) {r.HandleFunc(prefix+"/default_settings", handlers.UpdateDefaultSettingsHandler).Methods("PUT")r.HandleFunc(prefix+"/file_map", handlers.GetFileMapHandler).Methods("POST")+ r.HandleFunc(prefix+"/plans/{planId}/{branch}/load_cached_file_map", handlers.LoadCachedFileMapHandler).Methods("POST")r.HandleFunc(prefix+"/plans/{planId}/{branch}/auto_load_context", handlers.AutoLoadContextHandler).Methods("POST")++ r.HandleFunc(prefix+"/plans/{planId}/config", handlers.GetPlanConfigHandler).Methods("GET")+ r.HandleFunc(prefix+"/plans/{planId}/config", handlers.UpdatePlanConfigHandler).Methods("PUT")++ r.HandleFunc(prefix+"/default_plan_config", handlers.GetDefaultPlanConfigHandler).Methods("GET")+ r.HandleFunc(prefix+"/default_plan_config", handlers.UpdateDefaultPlanConfigHandler).Methods("PUT")}diff --git a/app/server/syntax/file_map/cli/go.mod b/app/server/syntax/file_map/cli/go.modindex a414b47f..047d7f30 100644--- a/app/server/syntax/file_map/cli/go.mod+++ b/app/server/syntax/file_map/cli/go.mod@@ -54,7 +54,7 @@ require (github.com/plandex-ai/survey/v2 v2.3.7 // indirectgithub.com/rivo/uniseg v0.4.7 // indirectgithub.com/sabhiram/go-gitignore v0.0.0-20210923224102-525f6e181f06 // indirect- github.com/sashabaranov/go-openai v1.35.7 // indirect+ github.com/sashabaranov/go-openai v1.36.0 // indirectgithub.com/shopspring/decimal v1.4.0 // indirectgithub.com/smacker/go-tree-sitter v0.0.0-20240827094217-dd81d9e9be82 // indirectgithub.com/yuin/goldmark v1.6.0 // indirectdiff --git a/app/server/syntax/file_map/cli/go.sum b/app/server/syntax/file_map/cli/go.sumindex f01e3722..088f4358 100644--- a/app/server/syntax/file_map/cli/go.sum+++ b/app/server/syntax/file_map/cli/go.sum@@ -633,8 +633,8 @@ github.com/sabhiram/go-gitignore v0.0.0-20210923224102-525f6e181f06 h1:OkMGxebDjgithub.com/sabhiram/go-gitignore v0.0.0-20210923224102-525f6e181f06/go.mod h1:+ePHsJ1keEjQtpvf9HHw0f4ZeJ0TLRsxhunSI2hYJSs=github.com/sagikazarmark/crypt v0.8.0/go.mod h1:TmKwZAo97S4Fy4sfMH/HX/cQP5D+ijra2NyLpNNmttY=github.com/sahilm/fuzzy v0.1.0/go.mod h1:VFvziUEIMCrT6A6tw2RFIXPXXmzXbOsSHF0DOI8ZK9Y=-github.com/sashabaranov/go-openai v1.35.7 h1:icyrRbkYoKPa4rbO1WSInpJu3qDQrPEnsoJVZ6QymdI=-github.com/sashabaranov/go-openai v1.35.7/go.mod h1:lj5b/K+zjTSFxVLijLSTDZuP7adOgerWeFyZLUhAKRg=+github.com/sashabaranov/go-openai v1.36.0 h1:fcSrn8uGuorzPWCBp8L0aCR95Zjb/Dd+ZSML0YZy9EI=+github.com/sashabaranov/go-openai v1.36.0/go.mod h1:lj5b/K+zjTSFxVLijLSTDZuP7adOgerWeFyZLUhAKRg=github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc=github.com/segmentio/ksuid v1.0.4/go.mod h1:/XUiZBD3kVx5SmUOl55voK5yeAbBNNIed+2O73XgrPE=github.com/shopspring/decimal v1.4.0 h1:bxl37RwXBklmTi0C79JfXCEBD1cqqHt0bbgBAGFp81k=diff --git a/app/shared/data_models.go b/app/shared/data_models.goindex 226116d7..b8884241 100644--- a/app/shared/data_models.go+++ b/app/shared/data_models.go@@ -27,6 +27,8 @@ type User struct {Email string `json:"email"`IsTrial bool `json:"isTrial"`NumNonDraftPlans int `json:"numNonDraftPlans"`++ DefaultPlanConfig *PlanConfig `json:"defaultPlanConfig,omitempty"`}type OrgUser struct {@@ -53,16 +55,17 @@ type Project struct {}type Plan struct {- Id string `json:"id"`- OwnerId string `json:"ownerId"`- ProjectId string `json:"projectId"`- Name string `json:"name"`- SharedWithOrgAt *time.Time `json:"sharedWithOrgAt,omitempty"`- TotalReplies int `json:"totalReplies"`- ActiveBranches int `json:"activeBranches"`- ArchivedAt *time.Time `json:"archivedAt,omitempty"`- CreatedAt time.Time `json:"createdAt"`- UpdatedAt time.Time `json:"updatedAt"`+ Id string `json:"id"`+ OwnerId string `json:"ownerId"`+ ProjectId string `json:"projectId"`+ Name string `json:"name"`+ SharedWithOrgAt *time.Time `json:"sharedWithOrgAt,omitempty"`+ TotalReplies int `json:"totalReplies"`+ ActiveBranches int `json:"activeBranches"`+ PlanConfig *PlanConfig `json:"planConfig,omitempty"`+ ArchivedAt *time.Time `json:"archivedAt,omitempty"`+ CreatedAt time.Time `json:"createdAt"`+ UpdatedAt time.Time `json:"updatedAt"`}type Branch struct {@@ -400,41 +403,6 @@ type CloudBillingFields struct {StripePaymentMethod *string `json:"stripePaymentMethod"`}-type PlanConfig struct {- AutoApply bool `json:"autoApply"`- AutoCommit bool `json:"autoCommit"`- AutoContext bool `json:"autoContext"`- NoExec bool `json:"noExec"`- AutoDebug bool `json:"autoDebug"`- AutoDebugTries int `json:"autoDebugTries"`-}--func (p *PlanConfig) Scan(src interface{}) error {- if src == nil {- return nil- }- switch s := src.(type) {- case []byte:- return json.Unmarshal(s, p)- case string:- return json.Unmarshal([]byte(s), p)- default:- return fmt.Errorf("unsupported data type: %T", src)- }-}--func (p PlanConfig) Value() (driver.Value, error) {- return json.Marshal(p)-}--type DefaultPlanConfig struct {- Id string `json:"id"`- UserId string `json:"userId"`- Config PlanConfig `json:"config"`- CreatedAt time.Time `json:"createdAt"`- UpdatedAt time.Time `json:"updatedAt"`-}-type CreditsTransactionType stringconst (diff --git a/app/shared/plan_config.go b/app/shared/plan_config.gonew file mode 100644index 00000000..ca32c49c--- /dev/null+++ b/app/shared/plan_config.go@@ -0,0 +1,459 @@+package shared++import (+ "database/sql/driver"+ "encoding/json"+ "fmt"+)++const defaultAutoDebugTries = 5++const (+ EditorTypeVim string = "vim"+ EditorTypeNano string = "nano"+)++const defaultEditor = EditorTypeVim++type ReplType string++const (+ ReplTypeTell ReplType = "tell"+ ReplTypeChat ReplType = "chat"+ ReplTypeAuto ReplType = "auto"+)++type AutoModeType string++const (+ AutoModeFull AutoModeType = "full"+ AutoModeSemi AutoModeType = "semi"+ AutoModeBasicPlus AutoModeType = "basic-plus"+ AutoModeBasic AutoModeType = "basic"+ AutoModeNone AutoModeType = "none"+ AutoModeCustom AutoModeType = "custom"+)++var AutoModeOptions = [][2]string{+ {string(AutoModeFull), "Full Auto"},++ // "→ automatically selects context, updates changes context, includes only necessary context for each step, continues iterating until plan is complete, builds plan into file edits, applies changes, executes commands, and debugs failed commands up to " + strconv.Itoa(defaultAutoDebugTries) + " attempts."},++ {string(AutoModeSemi), "Semi Auto"},++ // "→ automatically selects context, updates changed context, includes only necessary context for each step, continues iterating until plan is complete, and builds plan into pending file edits. User applies changes manually. Automatically commits after apply in git repos. Plans can include commands to execute, but user must approve execution and debugging of failed commands."},++ {string(AutoModeBasic), "Basic Plus"},++ // " → manual selection of context. Context with changes is updates automatically. Includes only necessary context for each step. Continues iterating until plan is complete, and builds plan into pending file edits. User applies changes manually. Automatically commits after apply in git repos. Plans can include commands to execute, but user must approve execution and debugging of failed commands."},++ {string(AutoModeBasic), "Basic"},++ // " → manual selection of context. Updating changed context must be approved. Each step includes all context (no smart context). Continues iterating until plan is complete, and builds plan into pending file edits. User applies changes manually. No automatic commit after apply in git repos. No execution of commands."},++ {string(AutoModeNone), "None"},++ // "→ manual selection of context. Updating changes context must be approved. Each step includes all context (no smart context). Plans only proceed one iteration at a time with no automatic continuation. Changes are not automatically built into pending file edits. User builds and applies changes manually. No automatic commit after apply in git repos. No execution of commands."},++ {string(AutoModeCustom), "Custom"},++ // " → mix and match config settings individually."},+}++// populated in init()+var AutoModeChoices []string++type PlanConfig struct {+ AutoMode AutoModeType `json:"autoMode"`+ // QuietMode bool `json:"quietMode"`++ Editor string `json:"editor"`+ AutoContinue bool `json:"autoContinue"`+ AutoBuild bool `json:"autoBuild"`++ AutoUpdateContext bool `json:"autoUpdateContext"`+ AutoLoadContext bool `json:"autoContext"`+ SmartContext bool `json:"smartContext"`++ // AutoApproveContext bool `json:"autoApproveContext"`+ // QuietContext bool `json:"quietContext"`++ // AutoApprovePlan bool `json:"autoApprovePlan"`++ // QuietCoding bool `json:"quietCoding"`+ // ParallelCoding bool `json:"parallelCoding"`++ AutoApply bool `json:"autoApply"`+ AutoCommit bool `json:"autoCommit"`++ CanExec bool `json:"canExec"`+ AutoExec bool `json:"autoExec"`+ AutoDebug bool `json:"autoDebug"`+ AutoDebugTries int `json:"autoDebugTries"`++ // ReplMode bool `json:"replMode"`+ // DefaultRepl ReplType `json:"defaultRepl"`++ // PlainTextMode bool `json:"plainTextMode"`+ // PlainTextCommands bool `json:"plainTextCommands"`+ // PlainTextStream bool `json:"plainTextStream"`+}++// autonomy settings are configured below in init()+var DefaultPlanConfig = PlanConfig{+ Editor: defaultEditor,+}++func (p *PlanConfig) Scan(src interface{}) error {+ if src == nil {+ *p = DefaultPlanConfig+ return nil+ }+ switch s := src.(type) {+ case []byte:+ if len(s) == 0 {+ *p = DefaultPlanConfig+ return nil+ }+ return json.Unmarshal(s, p)+ case string:+ if s == "" {+ *p = DefaultPlanConfig+ return nil+ }+ return json.Unmarshal([]byte(s), p)+ default:+ return fmt.Errorf("unsupported data type: %T", src)+ }+}++func (p PlanConfig) Value() (driver.Value, error) {+ return json.Marshal(p)+}++func (p *PlanConfig) SetAutoMode(mode AutoModeType) {+ p.AutoMode = mode++ switch p.AutoMode {+ case AutoModeFull:+ p.AutoContinue = true+ p.AutoBuild = true+ p.AutoUpdateContext = true+ p.AutoLoadContext = true+ p.SmartContext = true+ p.AutoApply = true+ p.AutoCommit = true+ p.CanExec = true+ p.AutoExec = true+ p.AutoDebug = true+ p.AutoDebugTries = defaultAutoDebugTries++ case AutoModeSemi:+ p.AutoContinue = true+ p.AutoBuild = true+ p.AutoUpdateContext = true+ p.AutoLoadContext = true+ p.SmartContext = true+ p.AutoApply = false+ p.AutoCommit = true+ p.CanExec = true+ p.AutoExec = false+ p.AutoDebug = false++ case AutoModeBasicPlus:+ p.AutoContinue = true+ p.AutoBuild = true+ p.AutoUpdateContext = true+ p.AutoLoadContext = false+ p.SmartContext = true+ p.AutoApply = false+ p.AutoCommit = true+ p.CanExec = true+ p.AutoExec = false+ p.AutoDebug = false++ case AutoModeBasic:+ p.AutoContinue = true+ p.AutoBuild = true+ p.AutoUpdateContext = false+ p.AutoLoadContext = false+ p.SmartContext = false+ p.AutoApply = false+ p.AutoCommit = false+ p.CanExec = false+ p.AutoExec = false+ p.AutoDebug = false++ case AutoModeNone:+ p.AutoContinue = false+ p.AutoBuild = false+ p.AutoUpdateContext = false+ p.AutoLoadContext = false+ p.SmartContext = false+ p.AutoApply = false+ p.AutoCommit = false+ p.CanExec = false+ p.AutoExec = false+ p.AutoDebug = false+ }+}++type ConfigSetting struct {+ Name string+ Desc string+ Visible func(p *PlanConfig) bool+ BoolSetter func(p *PlanConfig, enabled bool)+ IntSetter func(p *PlanConfig, value int)+ StringSetter func(p *PlanConfig, value string)+ Getter func(p *PlanConfig) string+ Choices *[]string+ HasCustomChoice bool+ ChoiceToKey func(choice string) string+ SortKey string+ KeyToLabel func(key string) string+}++var ConfigSettingsByKey = map[string]ConfigSetting{++ "automode": {+ Name: "auto-mode",+ Desc: "Use preset config based on desired level of autonomy",+ StringSetter: func(p *PlanConfig, value string) {+ p.SetAutoMode(AutoModeType(value))+ },+ Getter: func(p *PlanConfig) string {+ return string(p.AutoMode)+ },+ Choices: &AutoModeChoices,+ ChoiceToKey: func(choice string) string {+ for _, option := range AutoModeOptions {+ if option[1] == choice {+ return option[0]+ }+ }+ return ""+ },+ KeyToLabel: func(key string) string {+ for _, option := range AutoModeOptions {+ if option[0] == key {+ return option[1]+ }+ }+ return ""+ },+ SortKey: "0",+ },++ "editor": {+ Name: "editor",+ Desc: "System editor",+ StringSetter: func(p *PlanConfig, value string) {+ p.Editor = value+ },+ Getter: func(p *PlanConfig) string {+ return p.Editor+ },+ Choices: &[]string{EditorTypeVim, EditorTypeNano},+ HasCustomChoice: true,+ },++ "autocontinue": {+ Name: "auto-continue",+ Desc: "Continue iterating until plan is complete",+ BoolSetter: func(p *PlanConfig, enabled bool) {+ if enabled != p.AutoContinue {+ p.AutoMode = AutoModeCustom+ }++ p.AutoContinue = enabled+ },+ Getter: func(p *PlanConfig) string {+ return fmt.Sprintf("%t", p.AutoContinue)+ },+ },++ "autobuild": {+ Name: "auto-build",+ Desc: "Automatically generate pending file edits",+ BoolSetter: func(p *PlanConfig, enabled bool) {+ if enabled != p.AutoBuild {+ p.AutoMode = AutoModeCustom+ }++ p.AutoBuild = enabled++ if !enabled {+ p.AutoApply = false+ }+ },+ Getter: func(p *PlanConfig) string {+ return fmt.Sprintf("%t", p.AutoBuild)+ },+ },+ "autoupdatecontext": {+ Name: "auto-update-context",+ Desc: "Automatically update context after changes",+ BoolSetter: func(p *PlanConfig, enabled bool) {+ if enabled != p.AutoUpdateContext {+ p.AutoMode = AutoModeCustom+ }+ p.AutoUpdateContext = enabled+ },+ Getter: func(p *PlanConfig) string {+ return fmt.Sprintf("%t", p.AutoUpdateContext)+ },+ },+ "autoloadcontext": {+ Name: "auto-load-context",+ Desc: "Find and load context automatically",+ BoolSetter: func(p *PlanConfig, enabled bool) {+ if enabled != p.AutoLoadContext {+ p.AutoMode = AutoModeCustom+ }+ p.AutoLoadContext = enabled+ },+ Getter: func(p *PlanConfig) string {+ return fmt.Sprintf("%t", p.AutoLoadContext)+ },+ },+ "smartcontext": {+ Name: "smart-context",+ Desc: "Load only necessary context for each task in the plan",+ BoolSetter: func(p *PlanConfig, enabled bool) {+ if enabled != p.SmartContext {+ p.AutoMode = AutoModeCustom+ }+ p.SmartContext = enabled+ },+ Getter: func(p *PlanConfig) string {+ return fmt.Sprintf("%t", p.SmartContext)+ },+ },+ "autocommit": {+ Name: "auto-commit",+ Desc: "Automatically commit changes after apply",+ BoolSetter: func(p *PlanConfig, enabled bool) {+ if enabled != p.AutoCommit {+ p.AutoMode = AutoModeCustom+ }+ p.AutoCommit = enabled+ },+ Getter: func(p *PlanConfig) string {+ return fmt.Sprintf("%t", p.AutoCommit)+ },+ },+ "autoapply": {+ Name: "auto-apply",+ Desc: "Automatically apply changes after plan finishes",+ BoolSetter: func(p *PlanConfig, enabled bool) {+ if enabled != p.AutoApply {+ p.AutoMode = AutoModeCustom+ }+ p.AutoApply = enabled++ if enabled {+ p.AutoBuild = true+ }+ },+ Getter: func(p *PlanConfig) string {+ return fmt.Sprintf("%t", p.AutoApply)+ },+ },+ "canexec": {+ Name: "can-exec",+ Desc: "Allow execution of commands",+ BoolSetter: func(p *PlanConfig, enabled bool) {+ if enabled != p.CanExec {+ p.AutoMode = AutoModeCustom+ }+ p.CanExec = enabled++ if !enabled {+ p.AutoExec = false+ p.AutoDebug = false+ }+ },+ Getter: func(p *PlanConfig) string {+ return fmt.Sprintf("%t", p.CanExec)+ },+ },+ "autoexec": {+ Name: "auto-exec",+ Desc: "Automatically execute commands after plan is applied",+ Visible: func(p *PlanConfig) bool {+ return p.CanExec+ },+ BoolSetter: func(p *PlanConfig, enabled bool) {+ if enabled != p.AutoExec {+ p.AutoMode = AutoModeCustom+ }+ p.AutoExec = enabled++ if enabled {+ p.CanExec = true+ } else {+ p.AutoDebug = false+ }+ },+ Getter: func(p *PlanConfig) string {+ return fmt.Sprintf("%t", p.AutoExec)+ },+ },+ "autodebug": {+ Name: "auto-debug",+ Desc: "Automatically debug failed commands",+ Visible: func(p *PlanConfig) bool {+ return p.AutoExec+ },+ BoolSetter: func(p *PlanConfig, enabled bool) {+ if enabled != p.AutoDebug {+ p.AutoMode = AutoModeCustom+ }+ p.AutoDebug = enabled++ if enabled {+ p.CanExec = true+ p.AutoExec = true++ if p.AutoDebugTries == 0 {+ p.AutoDebugTries = defaultAutoDebugTries+ }+ }+ },+ Getter: func(p *PlanConfig) string {+ return fmt.Sprintf("%t", p.AutoDebug)+ },+ },+ "autodebugtries": {+ Name: "auto-debug-tries",+ Desc: "Number of auto-debug attempts",+ Visible: func(p *PlanConfig) bool {+ return p.AutoDebug+ },+ IntSetter: func(p *PlanConfig, value int) {+ if value != p.AutoDebugTries {+ p.AutoMode = AutoModeCustom+ }+ p.AutoDebugTries = value++ if p.AutoDebugTries == 0 {+ p.AutoDebug = false+ } else {+ p.CanExec = true+ p.AutoExec = true+ p.AutoDebug = true+ }+ },+ Getter: func(p *PlanConfig) string {+ return fmt.Sprintf("%d", p.AutoDebugTries)+ },+ },+}++func init() {+ DefaultPlanConfig.SetAutoMode(AutoModeSemi)++ for _, choice := range AutoModeOptions {+ AutoModeChoices = append(AutoModeChoices, choice[1])+ }+}diff --git a/app/shared/req_res.go b/app/shared/req_res.goindex 9dda9039..4a70fe47 100644--- a/app/shared/req_res.go+++ b/app/shared/req_res.go@@ -170,8 +170,8 @@ type LoadContextParams struct {Body string `json:"body"`ForceSkipIgnore bool `json:"forceSkipIgnore"`ImageDetail openai.ImageURLDetail `json:"imageDetail"`- DefsOnly bool `json:"defsOnly"`- MapInputs FileMapInputs `json:"mapInputs"`++ MapInputs FileMapInputs `json:"mapInputs"`// For naming piped dataApiKeys map[string]string `json:"apiKeys"`@@ -204,6 +204,15 @@ type GetFileMapResponse struct {MapBodies FileMapBodies `json:"mapBodies"`}+type LoadCachedFileMapRequest struct {+ FilePaths []string `json:"filePaths"`+}++type LoadCachedFileMapResponse struct {+ LoadRes *LoadContextResponse `json:"loadRes"`+ CachedByPath map[string]bool `json:"cachedByPath"`+}+type GetContextBodyRequest struct {ContextId string `json:"contextId"`}@@ -264,18 +273,10 @@ type UpdatePlanConfigRequest struct {Config *PlanConfig `json:"config"`}-type UpdatePlanConfigResponse struct {- Msg string `json:"msg"`-}-type UpdateDefaultPlanConfigRequest struct {Config *PlanConfig `json:"config"`}-type UpdateDefaultPlanConfigResponse struct {- Msg string `json:"msg"`-}-type GetPlanConfigResponse struct {Config *PlanConfig `json:"config"`}