From aeab0d25bec8a4c0182e78f39cd1937fdace2f15 Mon Sep 17 00:00:00 2001 From: pashpashpash Date: Mon, 13 Oct 2025 09:44:29 -0700 Subject: [PATCH] onboarding cli + log verbosity cleanup + fixing bug with default instances (#6787) * starting instance before anything else * auth wizard from root if no credentials * removing debug logs * better design * moving more things to verbose flag * ensuring that when a new cline instance is started and there are no others, that it is set as default * auth wizard should always have an instance at the beginning with ensuredefaultinstance * setting welcome state to true when user inputs credentials --- cli/cmd/cline/main.go | 106 ++++++++++++++++++++-- cli/pkg/cli/auth/auth_cline_provider.go | 16 +--- cli/pkg/cli/auth/auth_menu.go | 6 ++ cli/pkg/cli/auth/models_cline.go | 28 +++++- cli/pkg/cli/auth/wizard_byo.go | 13 +++ cli/pkg/cli/display/markdown_renderer.go | 111 +++++++++++++++++------ cli/pkg/cli/display/renderer.go | 33 +++++-- cli/pkg/cli/global/cline-clients.go | 102 +++++++++++++++------ cli/pkg/cli/global/global.go | 21 +++-- cli/pkg/cli/task.go | 52 +++++------ cli/pkg/cli/task/input_handler.go | 2 +- cli/pkg/cli/task/manager.go | 2 +- 12 files changed, 367 insertions(+), 125 deletions(-) diff --git a/cli/cmd/cline/main.go b/cli/cmd/cline/main.go index 810f1910..4d6c1084 100644 --- a/cli/cmd/cline/main.go +++ b/cli/cmd/cline/main.go @@ -2,14 +2,18 @@ package main import ( "context" + "encoding/json" "fmt" "os" "strings" "github.com/charmbracelet/huh" "github.com/cline/cli/pkg/cli" + "github.com/cline/cli/pkg/cli/auth" + "github.com/cline/cli/pkg/cli/display" "github.com/cline/cli/pkg/cli/global" "github.com/cline/cli/pkg/common" + "github.com/cline/grpc-go/cline" "github.com/spf13/cobra" ) @@ -55,6 +59,62 @@ This CLI also provides task management, configuration, and monitoring capabiliti RunE: func(cmd *cobra.Command, args []string) error { ctx := cmd.Context() + var instanceAddress string + + // If --address flag not provided, start instance BEFORE getting prompt + if !cmd.Flags().Changed("address") { + if global.Config.Verbose { + fmt.Println("Starting new Cline instance...") + } + instance, err := global.Clients.StartNewInstance(ctx) + if err != nil { + return fmt.Errorf("failed to start new instance: %w", err) + } + instanceAddress = instance.Address + if global.Config.Verbose { + fmt.Printf("Started instance at %s\n\n", instanceAddress) + } + + // Set up cleanup on exit + defer func() { + if global.Config.Verbose { + fmt.Println("\nCleaning up instance...") + } + registry := global.Clients.GetRegistry() + if err := global.KillInstanceByAddress(context.Background(), registry, instanceAddress); err != nil { + if global.Config.Verbose { + fmt.Printf("Warning: Failed to clean up instance: %v\n", err) + } + } + }() + + // Check if user has credentials configured + if !isUserReadyToUse(ctx, instanceAddress) { + // Create renderer for welcome messages + renderer := display.NewRenderer(global.Config.OutputFormat) + + markdown := "## hey there! looks like you're new here. let's get you set up" + rendered := renderer.RenderMarkdown(markdown) + fmt.Printf("\n%s\n\n", rendered) + + if err := auth.HandleAuthMenuNoArgs(ctx); err != nil { + return fmt.Errorf("auth setup failed: %w", err) + } + + // Re-check after auth wizard + if !isUserReadyToUse(ctx, instanceAddress) { + return fmt.Errorf("credentials still not configured - please run 'cline auth' to complete setup") + } + + markdown = "## ✓ setup complete, you can now use the cline cli" + rendered = renderer.RenderMarkdown(markdown) + fmt.Printf("\n%s\n\n", rendered) + } + } else { + // User specified --address flag, use that + instanceAddress = coreAddress + } + var prompt string // If args provided, use as prompt @@ -72,14 +132,6 @@ This CLI also provides task management, configuration, and monitoring capabiliti } } - // Create task + follow - // Don't pass address unless explicitly set via --address flag - // This allows the default instance resolution logic to work - var addr string - if cmd.Flags().Changed("address") { - addr = coreAddress - } - return cli.CreateAndFollowTask(ctx, prompt, cli.TaskOptions{ Images: images, Files: files, @@ -87,7 +139,7 @@ This CLI also provides task management, configuration, and monitoring capabiliti Mode: mode, Settings: settings, Yolo: yolo, - Address: addr, // Empty string means use default instance + Address: instanceAddress, }) }, } @@ -138,3 +190,39 @@ func promptForInitialTask() (string, error) { return strings.TrimSpace(prompt), nil } + +// isUserReadyToUse checks if the user has completed initial setup +// Returns true if welcomeViewCompleted flag is set OR user is authenticated +// Matches extension logic: welcomeViewCompleted = Boolean(globalState.welcomeViewCompleted || user?.uid) +func isUserReadyToUse(ctx context.Context, instanceAddress string) bool { + manager, err := cli.NewTaskManagerForAddress(ctx, instanceAddress) + if err != nil { + return false + } + + // Get state + state, err := manager.GetClient().State.GetLatestState(ctx, &cline.EmptyRequest{}) + if err != nil { + return false + } + + // Parse state JSON + stateMap := make(map[string]interface{}) + if err := json.Unmarshal([]byte(state.StateJson), &stateMap); err != nil { + return false + } + + // Check 1: welcomeViewCompleted flag + if welcomeCompleted, ok := stateMap["welcomeViewCompleted"].(bool); ok && welcomeCompleted { + return true + } + + // Check 2: Is user authenticated? (matches extension's || user?.uid check) + if userInfo, ok := stateMap["userInfo"].(map[string]interface{}); ok { + if uid, ok := userInfo["uid"].(string); ok && uid != "" { + return true + } + } + + return false +} diff --git a/cli/pkg/cli/auth/auth_cline_provider.go b/cli/pkg/cli/auth/auth_cline_provider.go index db645758..2e122d77 100644 --- a/cli/pkg/cli/auth/auth_cline_provider.go +++ b/cli/pkg/cli/auth/auth_cline_provider.go @@ -16,7 +16,7 @@ var isSessionAuthenticated bool // Cline provider specific code func HandleClineAuth(ctx context.Context) error { - fmt.Println("Authenticating with Cline...") + verboseLog("Authenticating with Cline...") // Check if already authenticated if IsAuthenticated(ctx) { @@ -28,7 +28,10 @@ func HandleClineAuth(ctx context.Context) error { return err } - fmt.Println("✓ You are signed in!") + fmt.Println() + + verboseLog("✓ You are signed in!") + // Configure default Cline model after successful authentication if err := configureDefaultClineModel(ctx); err != nil { @@ -84,15 +87,6 @@ func signIn(ctx context.Context) error { return nil } - verboseLog("Ensuring default instance exists...") - if err := global.EnsureDefaultInstance(ctx); err != nil { - verboseLog("Failed to ensure default instance: %v", err) - return fmt.Errorf("failed to ensure default instance: %w", err) - } - - verboseLog("Default instance ensured successfully.") - time.Sleep(2 * time.Second) // Allow services to start - // Subscribe to auth updates before initiating login verboseLog("Subscribing to auth status updates...") listener, err := NewAuthStatusListener(ctx) diff --git a/cli/pkg/cli/auth/auth_menu.go b/cli/pkg/cli/auth/auth_menu.go index eebfc235..3deff724 100644 --- a/cli/pkg/cli/auth/auth_menu.go +++ b/cli/pkg/cli/auth/auth_menu.go @@ -56,6 +56,12 @@ func HandleAuthCommand(ctx context.Context, args []string) error { // HandleAuthMenuNoArgs prepares the auth menu when no arguments are provided func HandleAuthMenuNoArgs(ctx context.Context) error { + // Ensure a default instance exists BEFORE trying to create task manager + // This is necessary because createTaskManager() needs a default instance to connect to + if err := global.EnsureDefaultInstance(ctx); err != nil { + return fmt.Errorf("failed to ensure default instance: %w", err) + } + // Check if Cline is authenticated isClineAuth := IsAuthenticated(ctx) diff --git a/cli/pkg/cli/auth/models_cline.go b/cli/pkg/cli/auth/models_cline.go index 3f0e54eb..93bf1f74 100644 --- a/cli/pkg/cli/auth/models_cline.go +++ b/cli/pkg/cli/auth/models_cline.go @@ -64,8 +64,15 @@ func SetDefaultClineModel(ctx context.Context, manager *task.Manager) error { return fmt.Errorf("no usable Cline models found") } - // Apply the default model - return applyClineModelConfiguration(ctx, manager, DefaultClineModelID, modelInfo) + if err := applyClineModelConfiguration(ctx, manager, DefaultClineModelID, modelInfo); err != nil { + return err + } + + if err := setWelcomeViewCompletedWithManager(ctx, manager); err != nil { + verboseLog("Warning: Failed to mark welcome view as completed: %v", err) + } + + return nil } // SelectClineModel presents a menu to select a Cline model and applies the configuration. @@ -116,8 +123,19 @@ func applyClineModelConfiguration(ctx context.Context, manager *task.Manager, mo return UpdateProviderPartial(ctx, manager, provider, updates, true) } -// applyDefaultClineModel applies the default Cline model without model info. -// This is a fallback when model fetching fails. func applyDefaultClineModel(ctx context.Context, manager *task.Manager, modelInfo *cline.OpenRouterModelInfo) error { - return applyClineModelConfiguration(ctx, manager, DefaultClineModelID, modelInfo) + if err := applyClineModelConfiguration(ctx, manager, DefaultClineModelID, modelInfo); err != nil { + return err + } + + if err := setWelcomeViewCompletedWithManager(ctx, manager); err != nil { + verboseLog("Warning: Failed to mark welcome view as completed: %v", err) + } + + return nil +} + +func setWelcomeViewCompletedWithManager(ctx context.Context, manager *task.Manager) error { + _, err := manager.GetClient().State.SetWelcomeViewCompleted(ctx, &cline.BooleanRequest{Value: true}) + return err } diff --git a/cli/pkg/cli/auth/wizard_byo.go b/cli/pkg/cli/auth/wizard_byo.go index d3551334..ecf1578c 100644 --- a/cli/pkg/cli/auth/wizard_byo.go +++ b/cli/pkg/cli/auth/wizard_byo.go @@ -127,6 +127,10 @@ func (pw *ProviderWizard) handleAddProvider() error { return fmt.Errorf("failed to save configuration: %w", err) } + if err := setWelcomeViewCompleted(pw.ctx, pw.manager); err != nil { + verboseLog("Warning: Failed to mark welcome view as completed: %v", err) + } + fmt.Println("✓ Provider configured successfully!") return nil } @@ -153,6 +157,10 @@ func (pw *ProviderWizard) handleAddBedrockProvider() error { return fmt.Errorf("failed to save Bedrock configuration: %w", err) } + if err := setWelcomeViewCompleted(pw.ctx, pw.manager); err != nil { + verboseLog("Warning: Failed to mark welcome view as completed: %v", err) + } + fmt.Println("✓ Bedrock provider configured successfully!") return nil } @@ -664,3 +672,8 @@ func (pw *ProviderWizard) handleRemoveProvider() error { func (pw *ProviderWizard) clearProviderAPIKey(provider cline.ApiProvider) error { return RemoveProviderPartial(pw.ctx, pw.manager, provider) } + +func setWelcomeViewCompleted(ctx context.Context, manager *task.Manager) error { + _, err := manager.GetClient().State.SetWelcomeViewCompleted(ctx, &cline.BooleanRequest{Value: true}) + return err +} diff --git a/cli/pkg/cli/display/markdown_renderer.go b/cli/pkg/cli/display/markdown_renderer.go index f06d8a09..3ae58844 100644 --- a/cli/pkg/cli/display/markdown_renderer.go +++ b/cli/pkg/cli/display/markdown_renderer.go @@ -2,8 +2,11 @@ package display import ( "os" + "strconv" "strings" + "fmt" + "github.com/charmbracelet/glamour" "golang.org/x/term" ) @@ -13,25 +16,71 @@ type MarkdownRenderer struct { width int } -// Custom style JSON that removes margins while keeping all other auto style features -// This is based on the "auto" style but with document and code_block margins set to 0 -const noMarginAutoStyleDark = `{ - "document": { - "block_prefix": "\n", - "block_suffix": "\n", - "color": "252", - "margin": 0 - }, - "code_block": { - "margin": 0 - } -}` +// i went back and forth on whether or not to enable word wrap +// setting line width to 0 enables the terminal to handle wrapping +// setting it to a terminal width enables glamour's word wrap +// the thing is, glamour's nice indentation looks really good, and +// won't work without glamour's word wrap - if you use the terminal's +// word wrap, the indentation looks weird so you have to turn it off +// and everything will be right next to the left margin +// but if you DO use glamours word wrap, it also means if you resize the terminal, +// it will scuff everything. but given that this is the case for the input anyway, +// i figure we just make things as beautiful as possible +// and if you resize the terminal, you'll learn real quick. +// anyway, you can set this to true or false to experiment +const USETERMINALWORDWRAP = false + + +// seems like a reliable way to check for terminals +// for now i'm keeping everything as auto +// eventually we can define a custom glamour style for ghostty / iterm +// https://github.com/charmbracelet/glamour/blob/master/styles/README.md) +func detectTerminalTheme() string { + switch os.Getenv("TERM_PROGRAM") { + case "iTerm.app", "Ghostty": + return "auto" + } + if os.Getenv("GHOSTTY_VERSION") != "" { + return "auto" + } + return "auto" +} + +func glamourStyleJSON(terminalWrap bool) string { + const tmpl = `{ + "document": { + "block_prefix": "\n", + "block_suffix": "\n", + "color": "252", + "margin": %s + }, + "code_block": { + "margin": 0 + } + }` + if terminalWrap { + return fmt.Sprintf(tmpl, "0") + } + return fmt.Sprintf(tmpl, "2") +} + + + func NewMarkdownRenderer() (*MarkdownRenderer, error) { + var wordWrap int + if USETERMINALWORDWRAP { + // terminal handles wrapping -> disable glamour wrap + wordWrap = 0 + } else { + // glamour handles wrapping -> set to current width + wordWrap = terminalWidthOr(0) + } + r, err := glamour.NewTermRenderer( - glamour.WithStandardStyle("auto"), // Load full auto style first - glamour.WithStylesFromJSONBytes([]byte(noMarginAutoStyleDark)), // Then override just margins - glamour.WithWordWrap(0), // 0 = no wrapping, let terminal handle it + glamour.WithStandardStyle(detectTerminalTheme()), // Load full auto style first + glamour.WithStylesFromJSONBytes([]byte(glamourStyleJSON(USETERMINALWORDWRAP))), // Then override just margins + glamour.WithWordWrap(wordWrap), glamour.WithPreservedNewLines(), ) if err != nil { @@ -44,32 +93,40 @@ func NewMarkdownRenderer() (*MarkdownRenderer, error) { }, nil } +// terminalWidthOr returns the terminal width or the provided fallback. +// It first tries term.GetSize, then falls back to $COLUMNS if set. +func terminalWidthOr(fallback int) int { + if w, _, err := term.GetSize(int(os.Stdout.Fd())); err == nil && w > 0 { + return w + } + if cols := os.Getenv("COLUMNS"); cols != "" { + if n, err := strconv.Atoi(cols); err == nil && n > 0 { + return n + } + } + return fallback +} + // NewMarkdownRendererWithWidth creates a markdown renderer with a specific width. // Useful for tables and other content that should fit within terminal bounds. func NewMarkdownRendererWithWidth(width int) (*MarkdownRenderer, error) { r, err := glamour.NewTermRenderer( - glamour.WithStandardStyle("auto"), // Load full auto style first - glamour.WithStylesFromJSONBytes([]byte(noMarginAutoStyleDark)), // Then override just margins + glamour.WithStandardStyle(detectTerminalTheme()), + glamour.WithStylesFromJSONBytes([]byte(glamourStyleJSON(false))), glamour.WithWordWrap(width), glamour.WithPreservedNewLines(), ) if err != nil { return nil, err } - - return &MarkdownRenderer{ - renderer: r, - width: width, - }, nil + return &MarkdownRenderer{renderer: r, width: width}, nil } + // NewMarkdownRendererForTerminal creates a markdown renderer using the actual terminal width. // Falls back to 120 if terminal width cannot be determined. func NewMarkdownRendererForTerminal() (*MarkdownRenderer, error) { - width, _, err := term.GetSize(int(os.Stdout.Fd())) - if err != nil || width == 0 { - width = 120 // Fallback width - } + width := terminalWidthOr(120) return NewMarkdownRendererWithWidth(width) } diff --git a/cli/pkg/cli/display/renderer.go b/cli/pkg/cli/display/renderer.go index 03e82722..448dfc45 100644 --- a/cli/pkg/cli/display/renderer.go +++ b/cli/pkg/cli/display/renderer.go @@ -58,15 +58,29 @@ func formatNumber(n int) string { // formatUsageInfo formats token usage information (extracted from RenderAPI) func (r *Renderer) formatUsageInfo(tokensIn, tokensOut, cacheReads, cacheWrites int, cost float64) string { - tokenDetails := fmt.Sprintf("[tokens in: %s, out: %s; cache read: %s, write: %s]", - formatNumber(tokensIn), - formatNumber(tokensOut), - formatNumber(cacheReads), - formatNumber(cacheWrites)) + parts := make([]string, 0, 4) - return fmt.Sprintf("%s ($%.4f)", tokenDetails, cost) + if tokensIn != 0 { + parts = append(parts, fmt.Sprintf("↑ %s", formatNumber(tokensIn))) + } + if tokensOut != 0 { + parts = append(parts, fmt.Sprintf("↓ %s", formatNumber(tokensOut))) + } + if cacheReads != 0 { + parts = append(parts, fmt.Sprintf("→ %s", formatNumber(cacheReads))) + } + if cacheWrites != 0 { + parts = append(parts, fmt.Sprintf("← %s", formatNumber(cacheWrites))) + } + + if len(parts) == 0 { + return fmt.Sprintf("$%.4f", cost) + } + + return fmt.Sprintf("%s $%.4f", strings.Join(parts, " "), cost) } + func (r *Renderer) RenderAPI(status string, apiInfo *types.APIRequestInfo) error { if apiInfo.Cost >= 0 { usageInfo := r.formatUsageInfo(apiInfo.TokensIn, apiInfo.TokensOut, apiInfo.CacheReads, apiInfo.CacheWrites, apiInfo.Cost) @@ -92,6 +106,13 @@ func (r *Renderer) RenderRetry(attempt, maxAttempts, delaySec int) error { return nil } +func (r *Renderer) RenderTaskCancelled() error { + markdown := "## Task cancelled" + rendered := r.RenderMarkdown(markdown) + fmt.Printf("\n%s\n", rendered) + return nil +} + // RenderTaskList displays task history with improved formatting func (r *Renderer) RenderTaskList(tasks []*cline.TaskItem) error { const maxTasks = 20 diff --git a/cli/pkg/cli/global/cline-clients.go b/cli/pkg/cli/global/cline-clients.go index 3daf99ba..f7ccf2e1 100644 --- a/cli/pkg/cli/global/cline-clients.go +++ b/cli/pkg/cli/global/cline-clients.go @@ -42,7 +42,9 @@ func (c *ClineClients) StartNewInstance(ctx context.Context) (*common.CoreInstan return nil, fmt.Errorf("failed to find available ports: %w", err) } - fmt.Printf("Starting new Cline instance on ports %d (core) and %d (host bridge)\n", corePort, hostPort) + if Config.Verbose { + fmt.Printf("Starting new Cline instance on ports %d (core) and %d (host bridge)\n", corePort, hostPort) + } // Start cline-host first hostCmd, err := startClineHost(hostPort, corePort) @@ -61,7 +63,9 @@ func (c *ClineClients) StartNewInstance(ctx context.Context) (*common.CoreInstan } fullAddress := fmt.Sprintf("localhost:%d", corePort) - fmt.Println("Waiting for services to start and self-register in SQLite...") + if Config.Verbose { + fmt.Println("Waiting for services to start and self-register in SQLite...") + } // Use RetryOperation to wait for instance to be ready var instance *common.CoreInstanceInfo @@ -95,11 +99,22 @@ func (c *ClineClients) StartNewInstance(ctx context.Context) (*common.CoreInstan return nil, fmt.Errorf("failed to start instance: %w", err) } - fmt.Println("Services started and registered successfully!") - fmt.Printf(" Address: %s\n", instance.Address) - fmt.Printf(" Core Port: %d\n", instance.CorePort()) - fmt.Printf(" Host Bridge Port: %d\n", instance.HostPort()) - fmt.Printf(" Process PID: %d\n", coreCmd.Process.Pid) + if Config.Verbose { + fmt.Println("Services started and registered successfully!") + fmt.Printf(" Address: %s\n", instance.Address) + fmt.Printf(" Core Port: %d\n", instance.CorePort()) + fmt.Printf(" Host Bridge Port: %d\n", instance.HostPort()) + fmt.Printf(" Process PID: %d\n", coreCmd.Process.Pid) + } + + // If this is the first instance, set it as default + instances := c.registry.ListInstances() + if err := c.registry.EnsureDefaultInstance(instances); err != nil { + if Config.Verbose { + fmt.Printf("Warning: Failed to set default instance: %v\n", err) + } + } + return instance, nil } @@ -114,7 +129,9 @@ func (c *ClineClients) StartNewInstanceAtPort(ctx context.Context, corePort int) return nil, fmt.Errorf("port %d is already in use by another Cline instance", corePort) } - fmt.Printf("Starting new Cline instance on ports %d (core) and %d (host bridge)\n", corePort, hostPort) + if Config.Verbose { + fmt.Printf("Starting new Cline instance on ports %d (core) and %d (host bridge)\n", corePort, hostPort) + } // Start cline-host first hostCmd, err := startClineHost(hostPort, corePort) @@ -133,7 +150,9 @@ func (c *ClineClients) StartNewInstanceAtPort(ctx context.Context, corePort int) } fullAddress := fmt.Sprintf("localhost:%d", corePort) - fmt.Println("Waiting for services to start and self-register in SQLite...") + if Config.Verbose { + fmt.Println("Waiting for services to start and self-register in SQLite...") + } // Use RetryOperation to wait for instance to be ready var instance *common.CoreInstanceInfo @@ -167,11 +186,22 @@ func (c *ClineClients) StartNewInstanceAtPort(ctx context.Context, corePort int) return nil, fmt.Errorf("failed to start instance at port %d: %w", corePort, err) } - fmt.Println("Services started and registered successfully!") - fmt.Printf(" Address: %s\n", instance.Address) - fmt.Printf(" Core Port: %d\n", instance.CorePort()) - fmt.Printf(" Host Bridge Port: %d\n", instance.HostPort()) - fmt.Printf(" Process PID: %d\n", coreCmd.Process.Pid) + if Config.Verbose { + fmt.Println("Services started and registered successfully!") + fmt.Printf(" Address: %s\n", instance.Address) + fmt.Printf(" Core Port: %d\n", instance.CorePort()) + fmt.Printf(" Host Bridge Port: %d\n", instance.HostPort()) + fmt.Printf(" Process PID: %d\n", coreCmd.Process.Pid) + } + + // If this is the first instance, set it as default + instances := c.registry.ListInstances() + if err := c.registry.EnsureDefaultInstance(instances); err != nil { + if Config.Verbose { + fmt.Printf("Warning: Failed to set default instance: %v\n", err) + } + } + return instance, nil } @@ -212,7 +242,9 @@ func (c *ClineClients) EnsureInstanceAtAddress(ctx context.Context, address stri } func startClineHost(hostPort, corePort int) (*exec.Cmd, error) { - fmt.Printf("Starting cline-host on port %d\n", hostPort) + if Config.Verbose { + fmt.Printf("Starting cline-host on port %d\n", hostPort) + } // Get the directory where the cline binary is located execPath, err := os.Executable() @@ -256,8 +288,10 @@ func startClineHost(hostPort, corePort int) (*exec.Cmd, error) { return nil, fmt.Errorf("failed to start cline-host: %w", err) } - fmt.Printf("Started cline-host (PID: %d)\n", cmd.Process.Pid) - fmt.Printf("Logging cline-host output to: %s\n", logFilePath) + if Config.Verbose { + fmt.Printf("Started cline-host (PID: %d)\n", cmd.Process.Pid) + fmt.Printf("Logging cline-host output to: %s\n", logFilePath) + } return cmd, nil } @@ -269,7 +303,9 @@ func KillInstanceByAddress(ctx context.Context, registry *ClientRegistry, addres return fmt.Errorf("instance %s not found in registry", address) } - fmt.Printf("Killing instance: %s\n", address) + if Config.Verbose { + fmt.Printf("Killing instance: %s\n", address) + } // Get gRPC client and process info client, err := registry.GetClient(ctx, address) @@ -283,7 +319,9 @@ func KillInstanceByAddress(ctx context.Context, registry *ClientRegistry, addres } pid := int(processInfo.ProcessId) - fmt.Printf("Terminating process PID %d...\n", pid) + if Config.Verbose { + fmt.Printf("Terminating process PID %d...\n", pid) + } // Kill the process if err := syscall.Kill(pid, syscall.SIGTERM); err != nil { @@ -291,11 +329,15 @@ func KillInstanceByAddress(ctx context.Context, registry *ClientRegistry, addres } // Wait for the instance to remove itself from registry - fmt.Printf("Waiting for instance to clean up registry entry...\n") + if Config.Verbose { + fmt.Printf("Waiting for instance to clean up registry entry...\n") + } for i := 0; i < 5; i++ { time.Sleep(1 * time.Second) if !registry.HasInstanceAtAddress(address) { - fmt.Printf("Instance %s successfully killed and removed from registry.\n", address) + if Config.Verbose { + fmt.Printf("Instance %s successfully killed and removed from registry.\n", address) + } // Update default instance if needed instances, err := registry.ListInstancesCleaned(ctx) @@ -305,7 +347,9 @@ func KillInstanceByAddress(ctx context.Context, registry *ClientRegistry, addres if defaultInstance == address || defaultInstance == "" { if len(instances) > 0 { if err := registry.SetDefaultInstance(instances[0].Address); err == nil { - fmt.Printf("Updated default instance to: %s\n", instances[0].Address) + if Config.Verbose { + fmt.Printf("Updated default instance to: %s\n", instances[0].Address) + } } } } @@ -319,7 +363,9 @@ func KillInstanceByAddress(ctx context.Context, registry *ClientRegistry, addres } func startClineCore(corePort, hostPort int) (*exec.Cmd, error) { - fmt.Printf("Starting cline-core on port %d (with hostbridge on %d)\n", corePort, hostPort) + if Config.Verbose { + fmt.Printf("Starting cline-core on port %d (with hostbridge on %d)\n", corePort, hostPort) + } // Get paths relative to the cline binary location execPath, err := os.Executable() @@ -352,10 +398,6 @@ func startClineCore(corePort, hostPort int) (*exec.Cmd, error) { "--host-bridge-port", fmt.Sprintf("%d", hostPort), "--config", Config.ConfigPath} - fmt.Printf("DEBUG: Starting cline-core with command: %s %v\n", nodePath, args) - fmt.Printf("DEBUG: Working directory: %s\n", installDir) - fmt.Printf("DEBUG: Config path: %s\n", Config.ConfigPath) - cmd := exec.Command(nodePath, args...) // Set working directory to installation root @@ -385,7 +427,9 @@ func startClineCore(corePort, hostPort int) (*exec.Cmd, error) { return nil, fmt.Errorf("failed to start cline-core: %w", err) } - fmt.Printf("Started cline-core (PID: %d)\n", cmd.Process.Pid) - fmt.Printf("Logging cline-core output to: %s\n", logFilePath) + if Config.Verbose { + fmt.Printf("Started cline-core (PID: %d)\n", cmd.Process.Pid) + fmt.Printf("Logging cline-core output to: %s\n", logFilePath) + } return cmd, nil } diff --git a/cli/pkg/cli/global/global.go b/cli/pkg/cli/global/global.go index ce5dc41b..80f45206 100644 --- a/cli/pkg/cli/global/global.go +++ b/cli/pkg/cli/global/global.go @@ -72,19 +72,24 @@ func EnsureDefaultInstance(ctx context.Context) error { return fmt.Errorf("global clients not initialized") } - // Check if we have any instances in the registry registry := Clients.GetRegistry() + + // First, check if there are any instances already registered in SQLite + instances := registry.ListInstances() + + // Use the registry's EnsureDefaultInstance to auto-set first instance as default if needed + if err := registry.EnsureDefaultInstance(instances); err != nil { + return fmt.Errorf("failed to ensure default from existing instances: %w", err) + } + + // Now check if we have a default set if registry.GetDefaultInstance() == "" { - // No default instance, start a new one - instance, err := Clients.StartNewInstance(ctx) + // No instances exist, start a new one + // Note: StartNewInstance will automatically set it as default since it's the first instance + _, err := Clients.StartNewInstance(ctx) if err != nil { return fmt.Errorf("failed to start new default instance: %w", err) } - - // Set the new instance as default - if err := registry.SetDefaultInstance(instance.Address); err != nil { - return fmt.Errorf("failed to set default instance: %w", err) - } } return nil diff --git a/cli/pkg/cli/task.go b/cli/pkg/cli/task.go index c262dc95..2606ed71 100644 --- a/cli/pkg/cli/task.go +++ b/cli/pkg/cli/task.go @@ -134,7 +134,9 @@ func newTaskNewCommand() *cobra.Command { if err := taskManager.SetMode(ctx, mode, nil, nil, nil); err != nil { return fmt.Errorf("failed to set mode: %w", err) } - fmt.Printf("Mode set to: %s\n", mode) + if global.Config.Verbose { + fmt.Printf("Mode set to: %s\n", mode) + } } // Inject yolo_mode_toggled setting if --yolo flag is set @@ -150,8 +152,10 @@ func newTaskNewCommand() *cobra.Command { if err != nil { return fmt.Errorf("failed to create task: %w", err) } - - fmt.Printf("Task created successfully with ID: %s\n", taskID) + + if global.Config.Verbose { + fmt.Printf("Task created successfully with ID: %s\n", taskID) + } return nil }, @@ -205,7 +209,10 @@ func newTaskOneshotCommand() *cobra.Command { if err := taskManager.SetMode(ctx, "plan", nil, nil, nil); err != nil { return fmt.Errorf("failed to set plan mode: %w", err) } - fmt.Println("Mode set to: plan") + + if global.Config.Verbose { + fmt.Println("Mode set to: plan") + } // Inject yolo mode into settings settings = append(settings, "yolo_mode_toggled=true") @@ -554,31 +561,16 @@ func CleanupTaskManager() { } } +// NewTaskManagerForAddress is an exported wrapper around task.NewManagerForAddress +func NewTaskManagerForAddress(ctx context.Context, address string) (*task.Manager, error) { + return task.NewManagerForAddress(ctx, address) +} + // CreateAndFollowTask creates a new task and immediately follows it in interactive mode // This is used by the root command to provide a streamlined UX func CreateAndFollowTask(ctx context.Context, prompt string, opts TaskOptions) error { - // Always start a fresh new instance for the root command - // This ensures users get a clean slate every time they run `cline` - fmt.Println("Starting new Cline instance...") - instance, err := global.Clients.StartNewInstance(ctx) - if err != nil { - return fmt.Errorf("failed to start new instance: %w", err) - } - - fmt.Printf("Started instance at %s\n", instance.Address) - - // Set up cleanup on exit - kill the instance when this function returns - defer func() { - fmt.Println("\nCleaning up instance...") - registry := global.Clients.GetRegistry() - - if err := global.KillInstanceByAddress(context.Background(), registry, instance.Address); err != nil { - fmt.Printf("Warning: Failed to clean up instance: %v\n", err) - } - }() - - // Initialize task manager with the new instance - if err := ensureTaskManager(ctx, instance.Address); err != nil { + // Initialize task manager with the provided instance address + if err := ensureTaskManager(ctx, opts.Address); err != nil { return err } @@ -592,7 +584,9 @@ func CreateAndFollowTask(ctx context.Context, prompt string, opts TaskOptions) e if err := taskManager.SetMode(ctx, opts.Mode, nil, nil, nil); err != nil { return fmt.Errorf("failed to set mode: %w", err) } - fmt.Printf("Mode set to: %s\n", opts.Mode) + if global.Config.Verbose { + fmt.Printf("Mode set to: %s\n", opts.Mode) + } } // Inject yolo_mode_toggled setting if --yolo flag is set @@ -606,7 +600,9 @@ func CreateAndFollowTask(ctx context.Context, prompt string, opts TaskOptions) e return fmt.Errorf("failed to create task: %w", err) } - fmt.Printf("Task created successfully with ID: %s\n\n", taskID) + if global.Config.Verbose { + fmt.Printf("Task created successfully with ID: %s\n\n", taskID) + } // Immediately follow the conversation in interactive mode return taskManager.FollowConversation(ctx, taskManager.GetCurrentInstance(), true) diff --git a/cli/pkg/cli/task/input_handler.go b/cli/pkg/cli/task/input_handler.go index bda59fad..b3f4fb0e 100644 --- a/cli/pkg/cli/task/input_handler.go +++ b/cli/pkg/cli/task/input_handler.go @@ -325,7 +325,7 @@ func (ih *InputHandler) parseModeSwitch(message string) (string, string, bool) { func (ih *InputHandler) handleSpecialCommand(ctx context.Context, message string) bool { switch strings.ToLower(strings.TrimSpace(message)) { case "/cancel": - fmt.Println("\nCancelling task...") + ih.manager.GetRenderer().RenderTaskCancelled() if err := ih.manager.CancelTask(ctx); err != nil { fmt.Printf("Error cancelling task: %v\n", err) } else { diff --git a/cli/pkg/cli/task/manager.go b/cli/pkg/cli/task/manager.go index afd9bc08..6435a94d 100644 --- a/cli/pkg/cli/task/manager.go +++ b/cli/pkg/cli/task/manager.go @@ -734,7 +734,7 @@ func (m *Manager) FollowConversation(ctx context.Context, instanceAddress string // Do nothing here, let the input handler deal with it } else { // Streaming mode - cancel the task and stay in follow mode - fmt.Println("\nCancelling task...") + m.renderer.RenderTaskCancelled() if err := m.CancelTask(context.Background()); err != nil { fmt.Printf("Error cancelling task: %v\n", err) }