root.go 6.4 KB

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