root.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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/config"
  13. "github.com/sst/opencode/internal/logging"
  14. "github.com/sst/opencode/internal/pubsub"
  15. "github.com/sst/opencode/internal/tui"
  16. "github.com/sst/opencode/internal/tui/app"
  17. "github.com/sst/opencode/internal/version"
  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. if cmd.Flag("version").Changed {
  32. fmt.Println(version.Version)
  33. return nil
  34. }
  35. // Setup logging
  36. file, err := os.OpenFile("app.log", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
  37. if err != nil {
  38. panic(err)
  39. }
  40. defer file.Close()
  41. logger := slog.New(slog.NewTextHandler(file, &slog.HandlerOptions{Level: slog.LevelDebug}))
  42. slog.SetDefault(logger)
  43. // Load the config
  44. debug, _ := cmd.Flags().GetBool("debug")
  45. cwd, _ := cmd.Flags().GetString("cwd")
  46. if cwd != "" {
  47. err := os.Chdir(cwd)
  48. if err != nil {
  49. return fmt.Errorf("failed to change directory: %v", err)
  50. }
  51. }
  52. if cwd == "" {
  53. c, err := os.Getwd()
  54. if err != nil {
  55. return fmt.Errorf("failed to get current working directory: %v", err)
  56. }
  57. cwd = c
  58. }
  59. _, err = config.Load(cwd, debug)
  60. if err != nil {
  61. return err
  62. }
  63. // Create main context for the application
  64. ctx, cancel := context.WithCancel(context.Background())
  65. defer cancel()
  66. app, err := app.New(ctx)
  67. if err != nil {
  68. slog.Error("Failed to create app", "error", err)
  69. return err
  70. }
  71. // Set up the TUI
  72. zone.NewGlobal()
  73. program := tea.NewProgram(
  74. tui.New(app),
  75. tea.WithAltScreen(),
  76. )
  77. evts, err := app.Events.Event(ctx)
  78. if err != nil {
  79. slog.Error("Failed to subscribe to events", "error", err)
  80. return err
  81. }
  82. go func() {
  83. for item := range evts {
  84. program.Send(item)
  85. }
  86. }()
  87. // Setup the subscriptions, this will send services events to the TUI
  88. ch, cancelSubs := setupSubscriptions(app, ctx)
  89. // Create a context for the TUI message handler
  90. tuiCtx, tuiCancel := context.WithCancel(ctx)
  91. var tuiWg sync.WaitGroup
  92. tuiWg.Add(1)
  93. // Set up message handling for the TUI
  94. go func() {
  95. defer tuiWg.Done()
  96. defer logging.RecoverPanic("TUI-message-handler", func() {
  97. attemptTUIRecovery(program)
  98. })
  99. for {
  100. select {
  101. case <-tuiCtx.Done():
  102. slog.Info("TUI message handler shutting down")
  103. return
  104. case msg, ok := <-ch:
  105. if !ok {
  106. slog.Info("TUI message channel closed")
  107. return
  108. }
  109. program.Send(msg)
  110. }
  111. }
  112. }()
  113. // Cleanup function for when the program exits
  114. cleanup := func() {
  115. // Cancel subscriptions first
  116. cancelSubs()
  117. // Then shutdown the app
  118. app.Shutdown()
  119. // Then cancel TUI message handler
  120. tuiCancel()
  121. // Wait for TUI message handler to finish
  122. tuiWg.Wait()
  123. slog.Info("All goroutines cleaned up")
  124. }
  125. // Run the TUI
  126. result, err := program.Run()
  127. cleanup()
  128. if err != nil {
  129. slog.Error("TUI error", "error", err)
  130. return fmt.Errorf("TUI error: %v", err)
  131. }
  132. slog.Info("TUI exited", "result", result)
  133. return nil
  134. },
  135. }
  136. // attemptTUIRecovery tries to recover the TUI after a panic
  137. func attemptTUIRecovery(program *tea.Program) {
  138. slog.Info("Attempting to recover TUI after panic")
  139. // We could try to restart the TUI or gracefully exit
  140. // For now, we'll just quit the program to avoid further issues
  141. program.Quit()
  142. }
  143. func setupSubscriber[T any](
  144. ctx context.Context,
  145. wg *sync.WaitGroup,
  146. name string,
  147. subscriber func(context.Context) <-chan pubsub.Event[T],
  148. outputCh chan<- tea.Msg,
  149. ) {
  150. wg.Add(1)
  151. go func() {
  152. defer wg.Done()
  153. defer logging.RecoverPanic(fmt.Sprintf("subscription-%s", name), nil)
  154. subCh := subscriber(ctx)
  155. if subCh == nil {
  156. slog.Warn("subscription channel is nil", "name", name)
  157. return
  158. }
  159. for {
  160. select {
  161. case event, ok := <-subCh:
  162. if !ok {
  163. slog.Info("subscription channel closed", "name", name)
  164. return
  165. }
  166. var msg tea.Msg = event
  167. select {
  168. case outputCh <- msg:
  169. case <-time.After(2 * time.Second):
  170. slog.Warn("message dropped due to slow consumer", "name", name)
  171. case <-ctx.Done():
  172. slog.Info("subscription cancelled", "name", name)
  173. return
  174. }
  175. case <-ctx.Done():
  176. slog.Info("subscription cancelled", "name", name)
  177. return
  178. }
  179. }
  180. }()
  181. }
  182. func setupSubscriptions(app *app.App, parentCtx context.Context) (chan tea.Msg, func()) {
  183. ch := make(chan tea.Msg, 100)
  184. wg := sync.WaitGroup{}
  185. ctx, cancel := context.WithCancel(parentCtx) // Inherit from parent context
  186. setupSubscriber(ctx, &wg, "status", app.Status.Subscribe, ch)
  187. cleanupFunc := func() {
  188. slog.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. slog.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. slog.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. rootCmd.Flags().StringP("prompt", "p", "", "Run a single prompt in non-interactive mode")
  219. rootCmd.Flags().StringP("output-format", "f", "text", "Output format for non-interactive mode (text, json)")
  220. rootCmd.Flags().BoolP("quiet", "q", false, "Hide spinner in non-interactive mode")
  221. rootCmd.Flags().BoolP("verbose", "", false, "Display logs to stderr in non-interactive mode")
  222. rootCmd.Flags().StringSlice("allowedTools", nil, "Restrict the agent to only use the specified tools in non-interactive mode (comma-separated list)")
  223. rootCmd.Flags().StringSlice("excludedTools", nil, "Prevent the agent from using the specified tools in non-interactive mode (comma-separated list)")
  224. // Make allowedTools and excludedTools mutually exclusive
  225. rootCmd.MarkFlagsMutuallyExclusive("allowedTools", "excludedTools")
  226. // Make quiet and verbose mutually exclusive
  227. rootCmd.MarkFlagsMutuallyExclusive("quiet", "verbose")
  228. }