| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303 |
- package cmd
- import (
- "context"
- "fmt"
- "os"
- "sync"
- "time"
- tea "github.com/charmbracelet/bubbletea/v2"
- "github.com/charmbracelet/crush/internal/app"
- "github.com/charmbracelet/crush/internal/config"
- "github.com/charmbracelet/crush/internal/db"
- "github.com/charmbracelet/crush/internal/format"
- "github.com/charmbracelet/crush/internal/llm/agent"
- "github.com/charmbracelet/crush/internal/logging"
- "github.com/charmbracelet/crush/internal/pubsub"
- "github.com/charmbracelet/crush/internal/tui"
- "github.com/charmbracelet/crush/internal/version"
- "github.com/charmbracelet/fang"
- "github.com/spf13/cobra"
- )
- var rootCmd = &cobra.Command{
- Use: "crush",
- Short: "Terminal-based AI assistant for software development",
- Long: `Crush is a powerful terminal-based AI assistant that helps with software development tasks.
- It provides an interactive chat interface with AI capabilities, code analysis, and LSP integration
- to assist developers in writing, debugging, and understanding code directly from the terminal.`,
- Example: `
- # Run in interactive mode
- crush
- # Run with debug logging
- crush -d
- # Run with debug logging in a specific directory
- crush -d -c /path/to/project
- # Print version
- crush -v
- # Run a single non-interactive prompt
- crush -p "Explain the use of context in Go"
- # Run a single non-interactive prompt with JSON output format
- crush -p "Explain the use of context in Go" -f json
- `,
- RunE: func(cmd *cobra.Command, args []string) error {
- // Load the config
- debug, _ := cmd.Flags().GetBool("debug")
- cwd, _ := cmd.Flags().GetString("cwd")
- prompt, _ := cmd.Flags().GetString("prompt")
- outputFormat, _ := cmd.Flags().GetString("output-format")
- quiet, _ := cmd.Flags().GetBool("quiet")
- // Validate format option
- if !format.IsValid(outputFormat) {
- return fmt.Errorf("invalid format option: %s\n%s", outputFormat, format.GetHelpText())
- }
- if cwd != "" {
- err := os.Chdir(cwd)
- if err != nil {
- return fmt.Errorf("failed to change directory: %v", err)
- }
- }
- if cwd == "" {
- c, err := os.Getwd()
- if err != nil {
- return fmt.Errorf("failed to get current working directory: %v", err)
- }
- cwd = c
- }
- _, err := config.Init(cwd, debug)
- if err != nil {
- return err
- }
- // Create main context for the application
- ctx, cancel := context.WithCancel(context.Background())
- defer cancel()
- // Connect DB, this will also run migrations
- conn, err := db.Connect(ctx)
- if err != nil {
- return err
- }
- app, err := app.New(ctx, conn)
- if err != nil {
- logging.Error("Failed to create app: %v", err)
- return err
- }
- // Defer shutdown here so it runs for both interactive and non-interactive modes
- defer app.Shutdown()
- // Initialize MCP tools early for both modes
- initMCPTools(ctx, app)
- // Non-interactive mode
- if prompt != "" {
- // Run non-interactive flow using the App method
- return app.RunNonInteractive(ctx, prompt, outputFormat, quiet)
- }
- // Set up the TUI
- program := tea.NewProgram(
- tui.New(app),
- tea.WithAltScreen(),
- tea.WithKeyReleases(),
- tea.WithUniformKeyLayout(),
- )
- // Setup the subscriptions, this will send services events to the TUI
- ch, cancelSubs := setupSubscriptions(app, ctx)
- // Create a context for the TUI message handler
- tuiCtx, tuiCancel := context.WithCancel(ctx)
- var tuiWg sync.WaitGroup
- tuiWg.Add(1)
- // Set up message handling for the TUI
- go func() {
- defer tuiWg.Done()
- defer logging.RecoverPanic("TUI-message-handler", func() {
- attemptTUIRecovery(program)
- })
- for {
- select {
- case <-tuiCtx.Done():
- logging.Info("TUI message handler shutting down")
- return
- case msg, ok := <-ch:
- if !ok {
- logging.Info("TUI message channel closed")
- return
- }
- program.Send(msg)
- }
- }
- }()
- // Cleanup function for when the program exits
- cleanup := func() {
- // Shutdown the app
- app.Shutdown()
- // Cancel subscriptions first
- cancelSubs()
- // Then cancel TUI message handler
- tuiCancel()
- // Wait for TUI message handler to finish
- tuiWg.Wait()
- logging.Info("All goroutines cleaned up")
- }
- // Run the TUI
- result, err := program.Run()
- cleanup()
- if err != nil {
- logging.Error("TUI error: %v", err)
- return fmt.Errorf("TUI error: %v", err)
- }
- logging.Info("TUI exited with result: %v", result)
- return nil
- },
- }
- // attemptTUIRecovery tries to recover the TUI after a panic
- func attemptTUIRecovery(program *tea.Program) {
- logging.Info("Attempting to recover TUI after panic")
- // We could try to restart the TUI or gracefully exit
- // For now, we'll just quit the program to avoid further issues
- program.Quit()
- }
- func initMCPTools(ctx context.Context, app *app.App) {
- go func() {
- defer logging.RecoverPanic("MCP-goroutine", nil)
- // Create a context with timeout for the initial MCP tools fetch
- ctxWithTimeout, cancel := context.WithTimeout(ctx, 30*time.Second)
- defer cancel()
- // Set this up once with proper error handling
- agent.GetMcpTools(ctxWithTimeout, app.Permissions)
- logging.Info("MCP message handling goroutine exiting")
- }()
- }
- func setupSubscriber[T any](
- ctx context.Context,
- wg *sync.WaitGroup,
- name string,
- subscriber func(context.Context) <-chan pubsub.Event[T],
- outputCh chan<- tea.Msg,
- ) {
- wg.Add(1)
- go func() {
- defer wg.Done()
- defer logging.RecoverPanic(fmt.Sprintf("subscription-%s", name), nil)
- subCh := subscriber(ctx)
- for {
- select {
- case event, ok := <-subCh:
- if !ok {
- logging.Info("subscription channel closed", "name", name)
- return
- }
- var msg tea.Msg = event
- select {
- case outputCh <- msg:
- case <-time.After(2 * time.Second):
- logging.Warn("message dropped due to slow consumer", "name", name)
- case <-ctx.Done():
- logging.Info("subscription cancelled", "name", name)
- return
- }
- case <-ctx.Done():
- logging.Info("subscription cancelled", "name", name)
- return
- }
- }
- }()
- }
- func setupSubscriptions(app *app.App, parentCtx context.Context) (chan tea.Msg, func()) {
- ch := make(chan tea.Msg, 100)
- wg := sync.WaitGroup{}
- ctx, cancel := context.WithCancel(parentCtx) // Inherit from parent context
- setupSubscriber(ctx, &wg, "logging", logging.Subscribe, ch)
- setupSubscriber(ctx, &wg, "sessions", app.Sessions.Subscribe, ch)
- setupSubscriber(ctx, &wg, "messages", app.Messages.Subscribe, ch)
- setupSubscriber(ctx, &wg, "permissions", app.Permissions.Subscribe, ch)
- setupSubscriber(ctx, &wg, "coderAgent", app.CoderAgent.Subscribe, ch)
- setupSubscriber(ctx, &wg, "history", app.History.Subscribe, ch)
- cleanupFunc := func() {
- logging.Info("Cancelling all subscriptions")
- cancel() // Signal all goroutines to stop
- waitCh := make(chan struct{})
- go func() {
- defer logging.RecoverPanic("subscription-cleanup", nil)
- wg.Wait()
- close(waitCh)
- }()
- select {
- case <-waitCh:
- logging.Info("All subscription goroutines completed successfully")
- close(ch) // Only close after all writers are confirmed done
- case <-time.After(5 * time.Second):
- logging.Warn("Timed out waiting for some subscription goroutines to complete")
- close(ch)
- }
- }
- return ch, cleanupFunc
- }
- func Execute() {
- if err := fang.Execute(
- context.Background(),
- rootCmd,
- fang.WithVersion(version.Version),
- ); err != nil {
- os.Exit(1)
- }
- }
- func init() {
- rootCmd.Flags().BoolP("help", "h", false, "Help")
- rootCmd.Flags().BoolP("debug", "d", false, "Debug")
- rootCmd.Flags().StringP("cwd", "c", "", "Current working directory")
- rootCmd.Flags().StringP("prompt", "p", "", "Prompt to run in non-interactive mode")
- // Add format flag with validation logic
- rootCmd.Flags().StringP("output-format", "f", format.Text.String(),
- "Output format for non-interactive mode (text, json)")
- // Add quiet flag to hide spinner in non-interactive mode
- rootCmd.Flags().BoolP("quiet", "q", false, "Hide spinner in non-interactive mode")
- // Register custom validation for the format flag
- rootCmd.RegisterFlagCompletionFunc("output-format", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
- return format.SupportedFormats, cobra.ShellCompDirectiveNoFileComp
- })
- }
|