1// Package app wires together services, coordinates agents, and manages
2// application lifecycle.
16 tea "charm.land/bubbletea/v2"
18 "charm.land/lipgloss/v2"
19 "github.com/charmbracelet/crush/internal/agent"
20 "github.com/charmbracelet/crush/internal/agent/tools/mcp"
21 "github.com/charmbracelet/crush/internal/config"
22 "github.com/charmbracelet/crush/internal/csync"
23 "github.com/charmbracelet/crush/internal/db"
24 "github.com/charmbracelet/crush/internal/format"
25 "github.com/charmbracelet/crush/internal/history"
26 "github.com/charmbracelet/crush/internal/log"
27 "github.com/charmbracelet/crush/internal/lsp"
28 "github.com/charmbracelet/crush/internal/message"
29 "github.com/charmbracelet/crush/internal/permission"
30 "github.com/charmbracelet/crush/internal/pubsub"
31 "github.com/charmbracelet/crush/internal/session"
32 "github.com/charmbracelet/crush/internal/shell"
33 "github.com/charmbracelet/crush/internal/term"
34 "github.com/charmbracelet/crush/internal/tui/components/anim"
35 "github.com/charmbracelet/crush/internal/tui/styles"
36 "github.com/charmbracelet/crush/internal/update"
37 "github.com/charmbracelet/crush/internal/version"
38 "github.com/charmbracelet/x/ansi"
39 "github.com/charmbracelet/x/exp/charmtone"
43 Sessions session.Service
44 Messages message.Service
45 History history.Service
46 Permissions permission.Service
48 AgentCoordinator agent.Coordinator
50 LSPClients *csync.Map[string, *lsp.Client]
54 serviceEventsWG *sync.WaitGroup
55 eventsCtx context.Context
59 // global context and cleanup functions
60 globalCtx context.Context
61 cleanupFuncs []func() error
64// New initializes a new applcation instance.
65func New(ctx context.Context, conn *sql.DB, cfg *config.Config) (*App, error) {
67 sessions := session.NewService(q)
68 messages := message.NewService(q)
69 files := history.NewService(q, conn)
70 skipPermissionsRequests := cfg.Permissions != nil && cfg.Permissions.SkipRequests
71 allowedTools := []string{}
72 if cfg.Permissions != nil && cfg.Permissions.AllowedTools != nil {
73 allowedTools = cfg.Permissions.AllowedTools
80 Permissions: permission.NewPermissionService(cfg.WorkingDir(), skipPermissionsRequests, allowedTools),
81 LSPClients: csync.NewMap[string, *lsp.Client](),
87 events: make(chan tea.Msg, 100),
88 serviceEventsWG: &sync.WaitGroup{},
89 tuiWG: &sync.WaitGroup{},
94 // Initialize LSP clients in the background.
95 app.initLSPClients(ctx)
97 // Check for updates in the background.
98 go app.checkForUpdates(ctx)
101 slog.Info("Initializing MCP clients")
102 mcp.Initialize(ctx, app.Permissions, cfg)
105 // cleanup database upon app shutdown
106 app.cleanupFuncs = append(app.cleanupFuncs, conn.Close, mcp.Close)
108 // TODO: remove the concept of agent config, most likely.
109 if !cfg.IsConfigured() {
110 slog.Warn("No agent configuration found")
113 if err := app.InitCoderAgent(ctx); err != nil {
114 return nil, fmt.Errorf("failed to initialize coder agent: %w", err)
119// Config returns the application configuration.
120func (app *App) Config() *config.Config {
124// RunNonInteractive runs the application in non-interactive mode with the
125// given prompt, printing to stdout.
126func (app *App) RunNonInteractive(ctx context.Context, output io.Writer, prompt string, quiet bool) error {
127 slog.Info("Running in non-interactive mode")
129 ctx, cancel := context.WithCancel(ctx)
132 var spinner *format.Spinner
134 t := styles.CurrentTheme()
136 // Detect background color to set the appropriate color for the
137 // spinner's 'Generating...' text. Without this, that text would be
138 // unreadable in light terminals.
140 if f, ok := output.(*os.File); ok {
141 hasDarkBG = lipgloss.HasDarkBackground(os.Stdin, f)
143 defaultFG := lipgloss.LightDark(hasDarkBG)(charmtone.Pepper, t.FgBase)
145 spinner = format.NewSpinner(ctx, cancel, anim.Settings{
148 LabelColor: defaultFG,
149 GradColorA: t.Primary,
150 GradColorB: t.Secondary,
156 // Helper function to stop spinner once.
157 stopSpinner := func() {
158 if !quiet && spinner != nil {
165 const maxPromptLengthForTitle = 100
166 const titlePrefix = "Non-interactive: "
167 var titleSuffix string
169 if len(prompt) > maxPromptLengthForTitle {
170 titleSuffix = prompt[:maxPromptLengthForTitle] + "..."
174 title := titlePrefix + titleSuffix
176 sess, err := app.Sessions.Create(ctx, title)
178 return fmt.Errorf("failed to create session for non-interactive mode: %w", err)
180 slog.Info("Created session for non-interactive run", "session_id", sess.ID)
182 // Automatically approve all permission requests for this non-interactive
184 app.Permissions.AutoApproveSession(sess.ID)
186 type response struct {
187 result *fantasy.AgentResult
190 done := make(chan response, 1)
192 go func(ctx context.Context, sessionID, prompt string) {
193 result, err := app.AgentCoordinator.Run(ctx, sess.ID, prompt)
196 err: fmt.Errorf("failed to start agent processing stream: %w", err),
202 }(ctx, sess.ID, prompt)
204 messageEvents := app.Messages.Subscribe(ctx)
205 messageReadBytes := make(map[string]int)
206 supportsProgressBar := term.SupportsProgressBar()
209 if supportsProgressBar {
210 _, _ = fmt.Fprintf(os.Stderr, ansi.ResetProgressBar)
213 // Always print a newline at the end. If output is a TTY this will
214 // prevent the prompt from overwriting the last line of output.
215 _, _ = fmt.Fprintln(output)
219 if supportsProgressBar {
220 // HACK: Reinitialize the terminal progress bar on every iteration so
221 // it doesn't get hidden by the terminal due to inactivity.
222 _, _ = fmt.Fprintf(os.Stderr, ansi.SetIndeterminateProgressBar)
226 case result := <-done:
228 if result.err != nil {
229 if errors.Is(result.err, context.Canceled) || errors.Is(result.err, agent.ErrRequestCancelled) {
230 slog.Info("Non-interactive: agent processing cancelled", "session_id", sess.ID)
233 return fmt.Errorf("agent processing failed: %w", result.err)
237 case event := <-messageEvents:
239 if msg.SessionID == sess.ID && msg.Role == message.Assistant && len(msg.Parts) > 0 {
242 content := msg.Content().String()
243 readBytes := messageReadBytes[msg.ID]
245 if len(content) < readBytes {
246 slog.Error("Non-interactive: message content is shorter than read bytes", "message_length", len(content), "read_bytes", readBytes)
247 return fmt.Errorf("message content is shorter than read bytes: %d < %d", len(content), readBytes)
250 part := content[readBytes:]
251 fmt.Fprint(output, part)
252 messageReadBytes[msg.ID] = len(content)
262func (app *App) UpdateAgentModel(ctx context.Context) error {
263 if app.AgentCoordinator == nil {
264 return fmt.Errorf("agent configuration is missing")
266 return app.AgentCoordinator.UpdateModels(ctx)
269func (app *App) setupEvents() {
270 ctx, cancel := context.WithCancel(app.globalCtx)
272 setupSubscriber(ctx, app.serviceEventsWG, "sessions", app.Sessions.Subscribe, app.events)
273 setupSubscriber(ctx, app.serviceEventsWG, "messages", app.Messages.Subscribe, app.events)
274 setupSubscriber(ctx, app.serviceEventsWG, "permissions", app.Permissions.Subscribe, app.events)
275 setupSubscriber(ctx, app.serviceEventsWG, "permissions-notifications", app.Permissions.SubscribeNotifications, app.events)
276 setupSubscriber(ctx, app.serviceEventsWG, "history", app.History.Subscribe, app.events)
277 setupSubscriber(ctx, app.serviceEventsWG, "mcp", mcp.SubscribeEvents, app.events)
278 setupSubscriber(ctx, app.serviceEventsWG, "lsp", SubscribeLSPEvents, app.events)
279 cleanupFunc := func() error {
281 app.serviceEventsWG.Wait()
284 app.cleanupFuncs = append(app.cleanupFuncs, cleanupFunc)
287func setupSubscriber[T any](
291 subscriber func(context.Context) <-chan pubsub.Event[T],
292 outputCh chan<- tea.Msg,
295 subCh := subscriber(ctx)
298 case event, ok := <-subCh:
300 slog.Debug("subscription channel closed", "name", name)
303 var msg tea.Msg = event
305 case outputCh <- msg:
306 case <-time.After(2 * time.Second):
307 slog.Warn("message dropped due to slow consumer", "name", name)
309 slog.Debug("subscription cancelled", "name", name)
313 slog.Debug("subscription cancelled", "name", name)
320func (app *App) InitCoderAgent(ctx context.Context) error {
321 coderAgentCfg := app.config.Agents[config.AgentCoder]
322 if coderAgentCfg.ID == "" {
323 return fmt.Errorf("coder agent configuration is missing")
326 app.AgentCoordinator, err = agent.NewCoordinator(
336 slog.Error("Failed to create coder agent", "err", err)
342// Subscribe sends events to the TUI as tea.Msgs.
343func (app *App) Subscribe(program *tea.Program) {
344 defer log.RecoverPanic("app.Subscribe", func() {
345 slog.Info("TUI subscription panic: attempting graceful shutdown")
350 tuiCtx, tuiCancel := context.WithCancel(app.globalCtx)
351 app.cleanupFuncs = append(app.cleanupFuncs, func() error {
352 slog.Debug("Cancelling TUI message handler")
357 defer app.tuiWG.Done()
361 case <-tuiCtx.Done():
362 slog.Debug("TUI message handler shutting down")
364 case msg, ok := <-app.events:
366 slog.Debug("TUI message channel closed")
374// Shutdown performs a graceful shutdown of the application.
375func (app *App) Shutdown() {
377 defer func() { slog.Info("Shutdown took " + time.Since(start).String()) }()
378 var wg sync.WaitGroup
379 if app.AgentCoordinator != nil {
381 app.AgentCoordinator.CancelAll()
385 // Kill all background shells.
387 shell.GetBackgroundShellManager().KillAll()
390 // Shutdown all LSP clients.
391 for name, client := range app.LSPClients.Seq2() {
393 shutdownCtx, cancel := context.WithTimeout(app.globalCtx, 5*time.Second)
395 if err := client.Close(shutdownCtx); err != nil {
396 slog.Error("Failed to shutdown LSP client", "name", name, "error", err)
401 // Call call cleanup functions.
402 for _, cleanup := range app.cleanupFuncs {
405 if err := cleanup(); err != nil {
406 slog.Error("Failed to cleanup app properly on shutdown", "error", err)
414// checkForUpdates checks for available updates.
415func (app *App) checkForUpdates(ctx context.Context) {
416 checkCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
419 info, err := update.Check(checkCtx, version.Version, update.Default)
420 if err != nil || !info.Available() {
423 app.events <- pubsub.UpdateAvailableMsg{
424 CurrentVersion: info.Current,
425 LatestVersion: info.Latest,
426 IsDevelopment: info.IsDevelopment(),
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list