root.go 6.6 KB

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