root.go 6.2 KB

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