root.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. package cmd
  2. import (
  3. "context"
  4. "fmt"
  5. "os"
  6. "sync"
  7. "time"
  8. tea "github.com/charmbracelet/bubbletea"
  9. zone "github.com/lrstanley/bubblezone"
  10. "github.com/opencode-ai/opencode/internal/app"
  11. "github.com/opencode-ai/opencode/internal/config"
  12. "github.com/opencode-ai/opencode/internal/db"
  13. "github.com/opencode-ai/opencode/internal/llm/agent"
  14. "github.com/opencode-ai/opencode/internal/logging"
  15. "github.com/opencode-ai/opencode/internal/pubsub"
  16. "github.com/opencode-ai/opencode/internal/tui"
  17. "github.com/opencode-ai/opencode/internal/version"
  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. )
  75. // Initialize MCP tools in the background
  76. initMCPTools(ctx, app)
  77. // Setup the subscriptions, this will send services events to the TUI
  78. ch, cancelSubs := setupSubscriptions(app, ctx)
  79. // Create a context for the TUI message handler
  80. tuiCtx, tuiCancel := context.WithCancel(ctx)
  81. var tuiWg sync.WaitGroup
  82. tuiWg.Add(1)
  83. // Set up message handling for the TUI
  84. go func() {
  85. defer tuiWg.Done()
  86. defer logging.RecoverPanic("TUI-message-handler", func() {
  87. attemptTUIRecovery(program)
  88. })
  89. for {
  90. select {
  91. case <-tuiCtx.Done():
  92. logging.Info("TUI message handler shutting down")
  93. return
  94. case msg, ok := <-ch:
  95. if !ok {
  96. logging.Info("TUI message channel closed")
  97. return
  98. }
  99. program.Send(msg)
  100. }
  101. }
  102. }()
  103. // Cleanup function for when the program exits
  104. cleanup := func() {
  105. // Shutdown the app
  106. app.Shutdown()
  107. // Cancel subscriptions first
  108. cancelSubs()
  109. // Then cancel TUI message handler
  110. tuiCancel()
  111. // Wait for TUI message handler to finish
  112. tuiWg.Wait()
  113. logging.Info("All goroutines cleaned up")
  114. }
  115. // Run the TUI
  116. result, err := program.Run()
  117. cleanup()
  118. if err != nil {
  119. logging.Error("TUI error: %v", err)
  120. return fmt.Errorf("TUI error: %v", err)
  121. }
  122. logging.Info("TUI exited with result: %v", result)
  123. return nil
  124. },
  125. }
  126. // attemptTUIRecovery tries to recover the TUI after a panic
  127. func attemptTUIRecovery(program *tea.Program) {
  128. logging.Info("Attempting to recover TUI after panic")
  129. // We could try to restart the TUI or gracefully exit
  130. // For now, we'll just quit the program to avoid further issues
  131. program.Quit()
  132. }
  133. func initMCPTools(ctx context.Context, app *app.App) {
  134. go func() {
  135. defer logging.RecoverPanic("MCP-goroutine", nil)
  136. // Create a context with timeout for the initial MCP tools fetch
  137. ctxWithTimeout, cancel := context.WithTimeout(ctx, 30*time.Second)
  138. defer cancel()
  139. // Set this up once with proper error handling
  140. agent.GetMcpTools(ctxWithTimeout, app.Permissions)
  141. logging.Info("MCP message handling goroutine exiting")
  142. }()
  143. }
  144. func setupSubscriber[T any](
  145. ctx context.Context,
  146. wg *sync.WaitGroup,
  147. name string,
  148. subscriber func(context.Context) <-chan pubsub.Event[T],
  149. outputCh chan<- tea.Msg,
  150. ) {
  151. wg.Add(1)
  152. go func() {
  153. defer wg.Done()
  154. defer logging.RecoverPanic(fmt.Sprintf("subscription-%s", name), nil)
  155. subCh := subscriber(ctx)
  156. for {
  157. select {
  158. case event, ok := <-subCh:
  159. if !ok {
  160. logging.Info("subscription channel closed", "name", name)
  161. return
  162. }
  163. var msg tea.Msg = event
  164. select {
  165. case outputCh <- msg:
  166. case <-time.After(2 * time.Second):
  167. logging.Warn("message dropped due to slow consumer", "name", name)
  168. case <-ctx.Done():
  169. logging.Info("subscription cancelled", "name", name)
  170. return
  171. }
  172. case <-ctx.Done():
  173. logging.Info("subscription cancelled", "name", name)
  174. return
  175. }
  176. }
  177. }()
  178. }
  179. func setupSubscriptions(app *app.App, parentCtx context.Context) (chan tea.Msg, func()) {
  180. ch := make(chan tea.Msg, 100)
  181. wg := sync.WaitGroup{}
  182. ctx, cancel := context.WithCancel(parentCtx) // Inherit from parent context
  183. setupSubscriber(ctx, &wg, "logging", logging.Subscribe, ch)
  184. setupSubscriber(ctx, &wg, "sessions", app.Sessions.Subscribe, ch)
  185. setupSubscriber(ctx, &wg, "messages", app.Messages.Subscribe, ch)
  186. setupSubscriber(ctx, &wg, "permissions", app.Permissions.Subscribe, ch)
  187. cleanupFunc := func() {
  188. logging.Info("Cancelling all subscriptions")
  189. cancel() // Signal all goroutines to stop
  190. waitCh := make(chan struct{})
  191. go func() {
  192. defer logging.RecoverPanic("subscription-cleanup", nil)
  193. wg.Wait()
  194. close(waitCh)
  195. }()
  196. select {
  197. case <-waitCh:
  198. logging.Info("All subscription goroutines completed successfully")
  199. close(ch) // Only close after all writers are confirmed done
  200. case <-time.After(5 * time.Second):
  201. logging.Warn("Timed out waiting for some subscription goroutines to complete")
  202. close(ch)
  203. }
  204. }
  205. return ch, cleanupFunc
  206. }
  207. func Execute() {
  208. err := rootCmd.Execute()
  209. if err != nil {
  210. os.Exit(1)
  211. }
  212. }
  213. func init() {
  214. rootCmd.Flags().BoolP("help", "h", false, "Help")
  215. rootCmd.Flags().BoolP("version", "v", false, "Version")
  216. rootCmd.Flags().BoolP("debug", "d", false, "Debug")
  217. rootCmd.Flags().StringP("cwd", "c", "", "Current working directory")
  218. }