root.go 7.4 KB

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