root.go 6.3 KB

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