app.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. // Package app wires together services, coordinates agents, and manages
  2. // application lifecycle.
  3. package app
  4. import (
  5. "context"
  6. "database/sql"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "log/slog"
  11. "os"
  12. "sync"
  13. "time"
  14. tea "charm.land/bubbletea/v2"
  15. "charm.land/fantasy"
  16. "charm.land/lipgloss/v2"
  17. "github.com/charmbracelet/crush/internal/agent"
  18. "github.com/charmbracelet/crush/internal/agent/tools/mcp"
  19. "github.com/charmbracelet/crush/internal/config"
  20. "github.com/charmbracelet/crush/internal/csync"
  21. "github.com/charmbracelet/crush/internal/db"
  22. "github.com/charmbracelet/crush/internal/format"
  23. "github.com/charmbracelet/crush/internal/history"
  24. "github.com/charmbracelet/crush/internal/log"
  25. "github.com/charmbracelet/crush/internal/lsp"
  26. "github.com/charmbracelet/crush/internal/message"
  27. "github.com/charmbracelet/crush/internal/permission"
  28. "github.com/charmbracelet/crush/internal/pubsub"
  29. "github.com/charmbracelet/crush/internal/session"
  30. "github.com/charmbracelet/crush/internal/term"
  31. "github.com/charmbracelet/crush/internal/tui/components/anim"
  32. "github.com/charmbracelet/crush/internal/tui/styles"
  33. "github.com/charmbracelet/x/ansi"
  34. "github.com/charmbracelet/x/exp/charmtone"
  35. )
  36. type App struct {
  37. Sessions session.Service
  38. Messages message.Service
  39. History history.Service
  40. Permissions permission.Service
  41. AgentCoordinator agent.Coordinator
  42. LSPClients *csync.Map[string, *lsp.Client]
  43. config *config.Config
  44. serviceEventsWG *sync.WaitGroup
  45. eventsCtx context.Context
  46. events chan tea.Msg
  47. tuiWG *sync.WaitGroup
  48. // global context and cleanup functions
  49. globalCtx context.Context
  50. cleanupFuncs []func() error
  51. }
  52. // New initializes a new applcation instance.
  53. func New(ctx context.Context, conn *sql.DB, cfg *config.Config) (*App, error) {
  54. q := db.New(conn)
  55. sessions := session.NewService(q)
  56. messages := message.NewService(q)
  57. files := history.NewService(q, conn)
  58. skipPermissionsRequests := cfg.Permissions != nil && cfg.Permissions.SkipRequests
  59. allowedTools := []string{}
  60. if cfg.Permissions != nil && cfg.Permissions.AllowedTools != nil {
  61. allowedTools = cfg.Permissions.AllowedTools
  62. }
  63. app := &App{
  64. Sessions: sessions,
  65. Messages: messages,
  66. History: files,
  67. Permissions: permission.NewPermissionService(cfg.WorkingDir(), skipPermissionsRequests, allowedTools),
  68. LSPClients: csync.NewMap[string, *lsp.Client](),
  69. globalCtx: ctx,
  70. config: cfg,
  71. events: make(chan tea.Msg, 100),
  72. serviceEventsWG: &sync.WaitGroup{},
  73. tuiWG: &sync.WaitGroup{},
  74. }
  75. app.setupEvents()
  76. // Initialize LSP clients in the background.
  77. app.initLSPClients(ctx)
  78. go func() {
  79. slog.Info("Initializing MCP clients")
  80. mcp.Initialize(ctx, app.Permissions, cfg)
  81. }()
  82. // cleanup database upon app shutdown
  83. app.cleanupFuncs = append(app.cleanupFuncs, conn.Close, mcp.Close)
  84. // TODO: remove the concept of agent config, most likely.
  85. if !cfg.IsConfigured() {
  86. slog.Warn("No agent configuration found")
  87. return app, nil
  88. }
  89. if err := app.InitCoderAgent(ctx); err != nil {
  90. return nil, fmt.Errorf("failed to initialize coder agent: %w", err)
  91. }
  92. return app, nil
  93. }
  94. // Config returns the application configuration.
  95. func (app *App) Config() *config.Config {
  96. return app.config
  97. }
  98. // RunNonInteractive runs the application in non-interactive mode with the
  99. // given prompt, printing to stdout.
  100. func (app *App) RunNonInteractive(ctx context.Context, output io.Writer, prompt string, quiet bool) error {
  101. slog.Info("Running in non-interactive mode")
  102. ctx, cancel := context.WithCancel(ctx)
  103. defer cancel()
  104. var spinner *format.Spinner
  105. if !quiet {
  106. t := styles.CurrentTheme()
  107. // Detect background color to set the appropriate color for the
  108. // spinner's 'Generating...' text. Without this, that text would be
  109. // unreadable in light terminals.
  110. hasDarkBG := true
  111. if f, ok := output.(*os.File); ok {
  112. hasDarkBG = lipgloss.HasDarkBackground(os.Stdin, f)
  113. }
  114. defaultFG := lipgloss.LightDark(hasDarkBG)(charmtone.Pepper, t.FgBase)
  115. spinner = format.NewSpinner(ctx, cancel, anim.Settings{
  116. Size: 10,
  117. Label: "Generating",
  118. LabelColor: defaultFG,
  119. GradColorA: t.Primary,
  120. GradColorB: t.Secondary,
  121. CycleColors: true,
  122. })
  123. spinner.Start()
  124. }
  125. // Helper function to stop spinner once.
  126. stopSpinner := func() {
  127. if !quiet && spinner != nil {
  128. spinner.Stop()
  129. spinner = nil
  130. }
  131. }
  132. defer stopSpinner()
  133. const maxPromptLengthForTitle = 100
  134. const titlePrefix = "Non-interactive: "
  135. var titleSuffix string
  136. if len(prompt) > maxPromptLengthForTitle {
  137. titleSuffix = prompt[:maxPromptLengthForTitle] + "..."
  138. } else {
  139. titleSuffix = prompt
  140. }
  141. title := titlePrefix + titleSuffix
  142. sess, err := app.Sessions.Create(ctx, title)
  143. if err != nil {
  144. return fmt.Errorf("failed to create session for non-interactive mode: %w", err)
  145. }
  146. slog.Info("Created session for non-interactive run", "session_id", sess.ID)
  147. // Automatically approve all permission requests for this non-interactive
  148. // session.
  149. app.Permissions.AutoApproveSession(sess.ID)
  150. type response struct {
  151. result *fantasy.AgentResult
  152. err error
  153. }
  154. done := make(chan response, 1)
  155. go func(ctx context.Context, sessionID, prompt string) {
  156. result, err := app.AgentCoordinator.Run(ctx, sess.ID, prompt)
  157. if err != nil {
  158. done <- response{
  159. err: fmt.Errorf("failed to start agent processing stream: %w", err),
  160. }
  161. }
  162. done <- response{
  163. result: result,
  164. }
  165. }(ctx, sess.ID, prompt)
  166. messageEvents := app.Messages.Subscribe(ctx)
  167. messageReadBytes := make(map[string]int)
  168. supportsProgressBar := term.SupportsProgressBar()
  169. defer func() {
  170. if supportsProgressBar {
  171. _, _ = fmt.Fprintf(os.Stderr, ansi.ResetProgressBar)
  172. }
  173. // Always print a newline at the end. If output is a TTY this will
  174. // prevent the prompt from overwriting the last line of output.
  175. _, _ = fmt.Fprintln(output)
  176. }()
  177. for {
  178. if supportsProgressBar {
  179. // HACK: Reinitialize the terminal progress bar on every iteration so
  180. // it doesn't get hidden by the terminal due to inactivity.
  181. _, _ = fmt.Fprintf(os.Stderr, ansi.SetIndeterminateProgressBar)
  182. }
  183. select {
  184. case result := <-done:
  185. stopSpinner()
  186. if result.err != nil {
  187. if errors.Is(result.err, context.Canceled) || errors.Is(result.err, agent.ErrRequestCancelled) {
  188. slog.Info("Non-interactive: agent processing cancelled", "session_id", sess.ID)
  189. return nil
  190. }
  191. return fmt.Errorf("agent processing failed: %w", result.err)
  192. }
  193. return nil
  194. case event := <-messageEvents:
  195. msg := event.Payload
  196. if msg.SessionID == sess.ID && msg.Role == message.Assistant && len(msg.Parts) > 0 {
  197. stopSpinner()
  198. content := msg.Content().String()
  199. readBytes := messageReadBytes[msg.ID]
  200. if len(content) < readBytes {
  201. slog.Error("Non-interactive: message content is shorter than read bytes", "message_length", len(content), "read_bytes", readBytes)
  202. return fmt.Errorf("message content is shorter than read bytes: %d < %d", len(content), readBytes)
  203. }
  204. part := content[readBytes:]
  205. fmt.Fprint(output, part)
  206. messageReadBytes[msg.ID] = len(content)
  207. }
  208. case <-ctx.Done():
  209. stopSpinner()
  210. return ctx.Err()
  211. }
  212. }
  213. }
  214. func (app *App) UpdateAgentModel(ctx context.Context) error {
  215. return app.AgentCoordinator.UpdateModels(ctx)
  216. }
  217. func (app *App) setupEvents() {
  218. ctx, cancel := context.WithCancel(app.globalCtx)
  219. app.eventsCtx = ctx
  220. setupSubscriber(ctx, app.serviceEventsWG, "sessions", app.Sessions.Subscribe, app.events)
  221. setupSubscriber(ctx, app.serviceEventsWG, "messages", app.Messages.Subscribe, app.events)
  222. setupSubscriber(ctx, app.serviceEventsWG, "permissions", app.Permissions.Subscribe, app.events)
  223. setupSubscriber(ctx, app.serviceEventsWG, "permissions-notifications", app.Permissions.SubscribeNotifications, app.events)
  224. setupSubscriber(ctx, app.serviceEventsWG, "history", app.History.Subscribe, app.events)
  225. setupSubscriber(ctx, app.serviceEventsWG, "mcp", mcp.SubscribeEvents, app.events)
  226. setupSubscriber(ctx, app.serviceEventsWG, "lsp", SubscribeLSPEvents, app.events)
  227. cleanupFunc := func() error {
  228. cancel()
  229. app.serviceEventsWG.Wait()
  230. return nil
  231. }
  232. app.cleanupFuncs = append(app.cleanupFuncs, cleanupFunc)
  233. }
  234. func setupSubscriber[T any](
  235. ctx context.Context,
  236. wg *sync.WaitGroup,
  237. name string,
  238. subscriber func(context.Context) <-chan pubsub.Event[T],
  239. outputCh chan<- tea.Msg,
  240. ) {
  241. wg.Go(func() {
  242. subCh := subscriber(ctx)
  243. for {
  244. select {
  245. case event, ok := <-subCh:
  246. if !ok {
  247. slog.Debug("subscription channel closed", "name", name)
  248. return
  249. }
  250. var msg tea.Msg = event
  251. select {
  252. case outputCh <- msg:
  253. case <-time.After(2 * time.Second):
  254. slog.Warn("message dropped due to slow consumer", "name", name)
  255. case <-ctx.Done():
  256. slog.Debug("subscription cancelled", "name", name)
  257. return
  258. }
  259. case <-ctx.Done():
  260. slog.Debug("subscription cancelled", "name", name)
  261. return
  262. }
  263. }
  264. })
  265. }
  266. func (app *App) InitCoderAgent(ctx context.Context) error {
  267. coderAgentCfg := app.config.Agents[config.AgentCoder]
  268. if coderAgentCfg.ID == "" {
  269. return fmt.Errorf("coder agent configuration is missing")
  270. }
  271. var err error
  272. app.AgentCoordinator, err = agent.NewCoordinator(
  273. ctx,
  274. app.config,
  275. app.Sessions,
  276. app.Messages,
  277. app.Permissions,
  278. app.History,
  279. app.LSPClients,
  280. )
  281. if err != nil {
  282. slog.Error("Failed to create coder agent", "err", err)
  283. return err
  284. }
  285. return nil
  286. }
  287. // Subscribe sends events to the TUI as tea.Msgs.
  288. func (app *App) Subscribe(program *tea.Program) {
  289. defer log.RecoverPanic("app.Subscribe", func() {
  290. slog.Info("TUI subscription panic: attempting graceful shutdown")
  291. program.Quit()
  292. })
  293. app.tuiWG.Add(1)
  294. tuiCtx, tuiCancel := context.WithCancel(app.globalCtx)
  295. app.cleanupFuncs = append(app.cleanupFuncs, func() error {
  296. slog.Debug("Cancelling TUI message handler")
  297. tuiCancel()
  298. app.tuiWG.Wait()
  299. return nil
  300. })
  301. defer app.tuiWG.Done()
  302. for {
  303. select {
  304. case <-tuiCtx.Done():
  305. slog.Debug("TUI message handler shutting down")
  306. return
  307. case msg, ok := <-app.events:
  308. if !ok {
  309. slog.Debug("TUI message channel closed")
  310. return
  311. }
  312. program.Send(msg)
  313. }
  314. }
  315. }
  316. // Shutdown performs a graceful shutdown of the application.
  317. func (app *App) Shutdown() {
  318. if app.AgentCoordinator != nil {
  319. app.AgentCoordinator.CancelAll()
  320. }
  321. // Shutdown all LSP clients.
  322. for name, client := range app.LSPClients.Seq2() {
  323. shutdownCtx, cancel := context.WithTimeout(app.globalCtx, 5*time.Second)
  324. if err := client.Close(shutdownCtx); err != nil {
  325. slog.Error("Failed to shutdown LSP client", "name", name, "error", err)
  326. }
  327. cancel()
  328. }
  329. // Call call cleanup functions.
  330. for _, cleanup := range app.cleanupFuncs {
  331. if cleanup != nil {
  332. if err := cleanup(); err != nil {
  333. slog.Error("Failed to cleanup app properly on shutdown", "error", err)
  334. }
  335. }
  336. }
  337. }