root.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. package cmd
  2. import (
  3. "context"
  4. "fmt"
  5. "os"
  6. "sync"
  7. "time"
  8. tea "github.com/charmbracelet/bubbletea"
  9. "github.com/kujtimiihoxha/opencode/internal/app"
  10. "github.com/kujtimiihoxha/opencode/internal/config"
  11. "github.com/kujtimiihoxha/opencode/internal/db"
  12. "github.com/kujtimiihoxha/opencode/internal/llm/agent"
  13. "github.com/kujtimiihoxha/opencode/internal/logging"
  14. "github.com/kujtimiihoxha/opencode/internal/pubsub"
  15. "github.com/kujtimiihoxha/opencode/internal/tui"
  16. zone "github.com/lrstanley/bubblezone"
  17. "github.com/spf13/cobra"
  18. )
  19. var rootCmd = &cobra.Command{
  20. Use: "OpenCode",
  21. Short: "A terminal AI assistant for software development",
  22. Long: `OpenCode is a powerful terminal-based AI assistant that helps with software development tasks.
  23. It provides an interactive chat interface with AI capabilities, code analysis, and LSP integration
  24. to assist developers in writing, debugging, and understanding code directly from the terminal.`,
  25. RunE: func(cmd *cobra.Command, args []string) error {
  26. // If the help flag is set, show the help message
  27. if cmd.Flag("help").Changed {
  28. cmd.Help()
  29. return nil
  30. }
  31. // Load the config
  32. debug, _ := cmd.Flags().GetBool("debug")
  33. cwd, _ := cmd.Flags().GetString("cwd")
  34. if cwd != "" {
  35. err := os.Chdir(cwd)
  36. if err != nil {
  37. return fmt.Errorf("failed to change directory: %v", err)
  38. }
  39. }
  40. if cwd == "" {
  41. c, err := os.Getwd()
  42. if err != nil {
  43. return fmt.Errorf("failed to get current working directory: %v", err)
  44. }
  45. cwd = c
  46. }
  47. _, err := config.Load(cwd, debug)
  48. if err != nil {
  49. return err
  50. }
  51. // Connect DB, this will also run migrations
  52. conn, err := db.Connect()
  53. if err != nil {
  54. return err
  55. }
  56. // Create main context for the application
  57. ctx, cancel := context.WithCancel(context.Background())
  58. defer cancel()
  59. app, err := app.New(ctx, conn)
  60. if err != nil {
  61. logging.Error("Failed to create app: %v", err)
  62. return err
  63. }
  64. // Set up the TUI
  65. zone.NewGlobal()
  66. program := tea.NewProgram(
  67. tui.New(app),
  68. tea.WithAltScreen(),
  69. tea.WithMouseCellMotion(),
  70. )
  71. // Initialize MCP tools in the background
  72. initMCPTools(ctx, app)
  73. // Setup the subscriptions, this will send services events to the TUI
  74. ch, cancelSubs := setupSubscriptions(app, ctx)
  75. // Create a context for the TUI message handler
  76. tuiCtx, tuiCancel := context.WithCancel(ctx)
  77. var tuiWg sync.WaitGroup
  78. tuiWg.Add(1)
  79. // Set up message handling for the TUI
  80. go func() {
  81. defer tuiWg.Done()
  82. defer logging.RecoverPanic("TUI-message-handler", func() {
  83. attemptTUIRecovery(program)
  84. })
  85. for {
  86. select {
  87. case <-tuiCtx.Done():
  88. logging.Info("TUI message handler shutting down")
  89. return
  90. case msg, ok := <-ch:
  91. if !ok {
  92. logging.Info("TUI message channel closed")
  93. return
  94. }
  95. program.Send(msg)
  96. }
  97. }
  98. }()
  99. // Cleanup function for when the program exits
  100. cleanup := func() {
  101. // Shutdown the app
  102. app.Shutdown()
  103. // Cancel subscriptions first
  104. cancelSubs()
  105. // Then cancel TUI message handler
  106. tuiCancel()
  107. // Wait for TUI message handler to finish
  108. tuiWg.Wait()
  109. logging.Info("All goroutines cleaned up")
  110. }
  111. // Run the TUI
  112. result, err := program.Run()
  113. cleanup()
  114. if err != nil {
  115. logging.Error("TUI error: %v", err)
  116. return fmt.Errorf("TUI error: %v", err)
  117. }
  118. logging.Info("TUI exited with result: %v", result)
  119. return nil
  120. },
  121. }
  122. // attemptTUIRecovery tries to recover the TUI after a panic
  123. func attemptTUIRecovery(program *tea.Program) {
  124. logging.Info("Attempting to recover TUI after panic")
  125. // We could try to restart the TUI or gracefully exit
  126. // For now, we'll just quit the program to avoid further issues
  127. program.Quit()
  128. }
  129. func initMCPTools(ctx context.Context, app *app.App) {
  130. go func() {
  131. defer logging.RecoverPanic("MCP-goroutine", nil)
  132. // Create a context with timeout for the initial MCP tools fetch
  133. ctxWithTimeout, cancel := context.WithTimeout(ctx, 30*time.Second)
  134. defer cancel()
  135. // Set this up once with proper error handling
  136. agent.GetMcpTools(ctxWithTimeout, app.Permissions)
  137. logging.Info("MCP message handling goroutine exiting")
  138. }()
  139. }
  140. func setupSubscriber[T any](
  141. ctx context.Context,
  142. wg *sync.WaitGroup,
  143. name string,
  144. subscriber func(context.Context) <-chan pubsub.Event[T],
  145. outputCh chan<- tea.Msg,
  146. ) {
  147. wg.Add(1)
  148. go func() {
  149. defer wg.Done()
  150. defer logging.RecoverPanic(fmt.Sprintf("subscription-%s", name), nil)
  151. subCh := subscriber(ctx)
  152. for {
  153. select {
  154. case event, ok := <-subCh:
  155. if !ok {
  156. logging.Info("subscription channel closed", "name", name)
  157. return
  158. }
  159. var msg tea.Msg = event
  160. select {
  161. case outputCh <- msg:
  162. case <-time.After(2 * time.Second):
  163. logging.Warn("message dropped due to slow consumer", "name", name)
  164. case <-ctx.Done():
  165. logging.Info("subscription cancelled", "name", name)
  166. return
  167. }
  168. case <-ctx.Done():
  169. logging.Info("subscription cancelled", "name", name)
  170. return
  171. }
  172. }
  173. }()
  174. }
  175. func setupSubscriptions(app *app.App, parentCtx context.Context) (chan tea.Msg, func()) {
  176. ch := make(chan tea.Msg, 100)
  177. wg := sync.WaitGroup{}
  178. ctx, cancel := context.WithCancel(parentCtx) // Inherit from parent context
  179. setupSubscriber(ctx, &wg, "logging", logging.Subscribe, ch)
  180. setupSubscriber(ctx, &wg, "sessions", app.Sessions.Subscribe, ch)
  181. setupSubscriber(ctx, &wg, "messages", app.Messages.Subscribe, ch)
  182. setupSubscriber(ctx, &wg, "permissions", app.Permissions.Subscribe, ch)
  183. cleanupFunc := func() {
  184. logging.Info("Cancelling all subscriptions")
  185. cancel() // Signal all goroutines to stop
  186. waitCh := make(chan struct{})
  187. go func() {
  188. defer logging.RecoverPanic("subscription-cleanup", nil)
  189. wg.Wait()
  190. close(waitCh)
  191. }()
  192. select {
  193. case <-waitCh:
  194. logging.Info("All subscription goroutines completed successfully")
  195. close(ch) // Only close after all writers are confirmed done
  196. case <-time.After(5 * time.Second):
  197. logging.Warn("Timed out waiting for some subscription goroutines to complete")
  198. close(ch)
  199. }
  200. }
  201. return ch, cleanupFunc
  202. }
  203. func Execute() {
  204. err := rootCmd.Execute()
  205. if err != nil {
  206. os.Exit(1)
  207. }
  208. }
  209. func init() {
  210. rootCmd.Flags().BoolP("help", "h", false, "Help")
  211. rootCmd.Flags().BoolP("debug", "d", false, "Debug")
  212. rootCmd.Flags().StringP("cwd", "c", "", "Current working directory")
  213. }