root.go 6.9 KB

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