1// Package app wires together services, coordinates agents, and manages
2// application lifecycle.
3package app
4
5import (
6 "context"
7 "database/sql"
8 "errors"
9 "fmt"
10 "io"
11 "log/slog"
12 "os"
13 "strings"
14 "sync"
15 "time"
16
17 tea "charm.land/bubbletea/v2"
18 "charm.land/catwalk/pkg/catwalk"
19 "charm.land/fantasy"
20 "charm.land/lipgloss/v2"
21 "github.com/charmbracelet/crush/internal/agent"
22 "github.com/charmbracelet/crush/internal/agent/tools/mcp"
23 "github.com/charmbracelet/crush/internal/config"
24 "github.com/charmbracelet/crush/internal/db"
25 "github.com/charmbracelet/crush/internal/event"
26 "github.com/charmbracelet/crush/internal/filetracker"
27 "github.com/charmbracelet/crush/internal/format"
28 "github.com/charmbracelet/crush/internal/history"
29 "github.com/charmbracelet/crush/internal/log"
30 "github.com/charmbracelet/crush/internal/lsp"
31 "github.com/charmbracelet/crush/internal/message"
32 "github.com/charmbracelet/crush/internal/permission"
33 "github.com/charmbracelet/crush/internal/pubsub"
34 "github.com/charmbracelet/crush/internal/session"
35 "github.com/charmbracelet/crush/internal/shell"
36 "github.com/charmbracelet/crush/internal/ui/anim"
37 "github.com/charmbracelet/crush/internal/ui/styles"
38 "github.com/charmbracelet/crush/internal/update"
39 "github.com/charmbracelet/crush/internal/version"
40 "github.com/charmbracelet/x/ansi"
41 "github.com/charmbracelet/x/exp/charmtone"
42 "github.com/charmbracelet/x/term"
43)
44
45// UpdateAvailableMsg is sent when a new version is available.
46type UpdateAvailableMsg struct {
47 CurrentVersion string
48 LatestVersion string
49 IsDevelopment bool
50}
51
52type App struct {
53 Sessions session.Service
54 Messages message.Service
55 History history.Service
56 Permissions permission.Service
57 FileTracker filetracker.Service
58
59 AgentCoordinator agent.Coordinator
60
61 LSPManager *lsp.Manager
62
63 config *config.Config
64
65 serviceEventsWG *sync.WaitGroup
66 eventsCtx context.Context
67 events chan tea.Msg
68 tuiWG *sync.WaitGroup
69
70 // global context and cleanup functions
71 globalCtx context.Context
72 cleanupFuncs []func(context.Context) error
73}
74
75// New initializes a new application instance.
76func New(ctx context.Context, conn *sql.DB, cfg *config.Config) (*App, error) {
77 q := db.New(conn)
78 sessions := session.NewService(q, conn)
79 messages := message.NewService(q)
80 files := history.NewService(q, conn)
81 skipPermissionsRequests := cfg.Permissions != nil && cfg.Permissions.SkipRequests
82 var allowedTools []string
83 if cfg.Permissions != nil && cfg.Permissions.AllowedTools != nil {
84 allowedTools = cfg.Permissions.AllowedTools
85 }
86
87 app := &App{
88 Sessions: sessions,
89 Messages: messages,
90 History: files,
91 Permissions: permission.NewPermissionService(cfg.WorkingDir(), skipPermissionsRequests, allowedTools),
92 FileTracker: filetracker.NewService(q),
93 LSPManager: lsp.NewManager(cfg),
94
95 globalCtx: ctx,
96
97 config: cfg,
98
99 events: make(chan tea.Msg, 100),
100 serviceEventsWG: &sync.WaitGroup{},
101 tuiWG: &sync.WaitGroup{},
102 }
103
104 app.setupEvents()
105
106 // Check for updates in the background.
107 go app.checkForUpdates(ctx)
108
109 go mcp.Initialize(ctx, app.Permissions, cfg)
110
111 // cleanup database upon app shutdown
112 app.cleanupFuncs = append(
113 app.cleanupFuncs,
114 func(context.Context) error { return conn.Close() },
115 mcp.Close,
116 )
117
118 // TODO: remove the concept of agent config, most likely.
119 if !cfg.IsConfigured() {
120 slog.Warn("No agent configuration found")
121 return app, nil
122 }
123 if err := app.InitCoderAgent(ctx); err != nil {
124 return nil, fmt.Errorf("failed to initialize coder agent: %w", err)
125 }
126
127 // Set up callback for LSP state updates.
128 app.LSPManager.SetCallback(func(name string, client *lsp.Client) {
129 if client == nil {
130 updateLSPState(name, lsp.StateUnstarted, nil, nil, 0)
131 return
132 }
133 client.SetDiagnosticsCallback(updateLSPDiagnostics)
134 updateLSPState(name, client.GetServerState(), nil, client, 0)
135 })
136 go app.LSPManager.TrackConfigured()
137
138 return app, nil
139}
140
141// Config returns the application configuration.
142func (app *App) Config() *config.Config {
143 return app.config
144}
145
146// Events returns the events channel for the application.
147func (app *App) Events() <-chan tea.Msg {
148 return app.events
149}
150
151// SendEvent pushes a message into the application's events channel.
152// It is non-blocking; the message is dropped if the channel is full.
153func (app *App) SendEvent(msg tea.Msg) {
154 select {
155 case app.events <- msg:
156 default:
157 }
158}
159
160// RunNonInteractive runs the application in non-interactive mode with the
161// given prompt, printing to stdout.
162func (app *App) RunNonInteractive(ctx context.Context, output io.Writer, prompt, largeModel, smallModel string, hideSpinner bool) error {
163 slog.Info("Running in non-interactive mode")
164
165 ctx, cancel := context.WithCancel(ctx)
166 defer cancel()
167
168 if largeModel != "" || smallModel != "" {
169 if err := app.overrideModelsForNonInteractive(ctx, largeModel, smallModel); err != nil {
170 return fmt.Errorf("failed to override models: %w", err)
171 }
172 }
173
174 var (
175 spinner *format.Spinner
176 stdoutTTY bool
177 stderrTTY bool
178 stdinTTY bool
179 progress bool
180 )
181
182 if f, ok := output.(*os.File); ok {
183 stdoutTTY = term.IsTerminal(f.Fd())
184 }
185 stderrTTY = term.IsTerminal(os.Stderr.Fd())
186 stdinTTY = term.IsTerminal(os.Stdin.Fd())
187 progress = app.config.Options.Progress == nil || *app.config.Options.Progress
188
189 if !hideSpinner && stderrTTY {
190 t := styles.DefaultStyles()
191
192 // Detect background color to set the appropriate color for the
193 // spinner's 'Generating...' text. Without this, that text would be
194 // unreadable in light terminals.
195 hasDarkBG := true
196 if f, ok := output.(*os.File); ok && stdinTTY && stdoutTTY {
197 hasDarkBG = lipgloss.HasDarkBackground(os.Stdin, f)
198 }
199 defaultFG := lipgloss.LightDark(hasDarkBG)(charmtone.Pepper, t.FgBase)
200
201 spinner = format.NewSpinner(ctx, cancel, anim.Settings{
202 Size: 10,
203 Label: "Generating",
204 LabelColor: defaultFG,
205 GradColorA: t.Primary,
206 GradColorB: t.Secondary,
207 CycleColors: true,
208 })
209 spinner.Start()
210 }
211
212 // Helper function to stop spinner once.
213 stopSpinner := func() {
214 if !hideSpinner && spinner != nil {
215 spinner.Stop()
216 spinner = nil
217 }
218 }
219
220 // Wait for MCP initialization to complete before reading MCP tools.
221 if err := mcp.WaitForInit(ctx); err != nil {
222 return fmt.Errorf("failed to wait for MCP initialization: %w", err)
223 }
224
225 // force update of agent models before running so mcp tools are loaded
226 app.AgentCoordinator.UpdateModels(ctx)
227
228 defer stopSpinner()
229
230 sess, err := app.Sessions.Create(ctx, agent.DefaultSessionName)
231 if err != nil {
232 return fmt.Errorf("failed to create session for non-interactive mode: %w", err)
233 }
234 slog.Info("Created session for non-interactive run", "session_id", sess.ID)
235
236 // Automatically approve all permission requests for this non-interactive
237 // session.
238 app.Permissions.AutoApproveSession(sess.ID)
239
240 type response struct {
241 result *fantasy.AgentResult
242 err error
243 }
244 done := make(chan response, 1)
245
246 go func(ctx context.Context, sessionID, prompt string) {
247 result, err := app.AgentCoordinator.Run(ctx, sess.ID, prompt)
248 if err != nil {
249 done <- response{
250 err: fmt.Errorf("failed to start agent processing stream: %w", err),
251 }
252 return
253 }
254 done <- response{
255 result: result,
256 }
257 }(ctx, sess.ID, prompt)
258
259 messageEvents := app.Messages.Subscribe(ctx)
260 messageReadBytes := make(map[string]int)
261 var printed bool
262
263 defer func() {
264 if progress && stderrTTY {
265 _, _ = fmt.Fprintf(os.Stderr, ansi.ResetProgressBar)
266 }
267
268 // Always print a newline at the end. If output is a TTY this will
269 // prevent the prompt from overwriting the last line of output.
270 _, _ = fmt.Fprintln(output)
271 }()
272
273 for {
274 if progress && stderrTTY {
275 // HACK: Reinitialize the terminal progress bar on every iteration
276 // so it doesn't get hidden by the terminal due to inactivity.
277 _, _ = fmt.Fprintf(os.Stderr, ansi.SetIndeterminateProgressBar)
278 }
279
280 select {
281 case result := <-done:
282 stopSpinner()
283 if result.err != nil {
284 if errors.Is(result.err, context.Canceled) || errors.Is(result.err, agent.ErrRequestCancelled) {
285 slog.Debug("Non-interactive: agent processing cancelled", "session_id", sess.ID)
286 return nil
287 }
288 return fmt.Errorf("agent processing failed: %w", result.err)
289 }
290 return nil
291
292 case event := <-messageEvents:
293 msg := event.Payload
294 if msg.SessionID == sess.ID && msg.Role == message.Assistant && len(msg.Parts) > 0 {
295 stopSpinner()
296
297 content := msg.Content().String()
298 readBytes := messageReadBytes[msg.ID]
299
300 if len(content) < readBytes {
301 slog.Error("Non-interactive: message content is shorter than read bytes", "message_length", len(content), "read_bytes", readBytes)
302 return fmt.Errorf("message content is shorter than read bytes: %d < %d", len(content), readBytes)
303 }
304
305 part := content[readBytes:]
306 // Trim leading whitespace. Sometimes the LLM includes leading
307 // formatting and intentation, which we don't want here.
308 if readBytes == 0 {
309 part = strings.TrimLeft(part, " \t")
310 }
311 // Ignore initial whitespace-only messages.
312 if printed || strings.TrimSpace(part) != "" {
313 printed = true
314 fmt.Fprint(output, part)
315 }
316 messageReadBytes[msg.ID] = len(content)
317 }
318
319 case <-ctx.Done():
320 stopSpinner()
321 return ctx.Err()
322 }
323 }
324}
325
326func (app *App) UpdateAgentModel(ctx context.Context) error {
327 if app.AgentCoordinator == nil {
328 return fmt.Errorf("agent configuration is missing")
329 }
330 return app.AgentCoordinator.UpdateModels(ctx)
331}
332
333// overrideModelsForNonInteractive parses the model strings and temporarily
334// overrides the model configurations, then rebuilds the agent.
335// Format: "model-name" (searches all providers) or "provider/model-name".
336// Model matching is case-insensitive.
337// If largeModel is provided but smallModel is not, the small model defaults to
338// the provider's default small model.
339func (app *App) overrideModelsForNonInteractive(ctx context.Context, largeModel, smallModel string) error {
340 providers := app.config.Providers.Copy()
341
342 largeMatches, smallMatches, err := findModels(providers, largeModel, smallModel)
343 if err != nil {
344 return err
345 }
346
347 var largeProviderID string
348
349 // Override large model.
350 if largeModel != "" {
351 found, err := validateMatches(largeMatches, largeModel, "large")
352 if err != nil {
353 return err
354 }
355 largeProviderID = found.provider
356 slog.Info("Overriding large model for non-interactive run", "provider", found.provider, "model", found.modelID)
357 app.config.Models[config.SelectedModelTypeLarge] = config.SelectedModel{
358 Provider: found.provider,
359 Model: found.modelID,
360 }
361 }
362
363 // Override small model.
364 switch {
365 case smallModel != "":
366 found, err := validateMatches(smallMatches, smallModel, "small")
367 if err != nil {
368 return err
369 }
370 slog.Info("Overriding small model for non-interactive run", "provider", found.provider, "model", found.modelID)
371 app.config.Models[config.SelectedModelTypeSmall] = config.SelectedModel{
372 Provider: found.provider,
373 Model: found.modelID,
374 }
375
376 case largeModel != "":
377 // No small model specified, but large model was - use provider's default.
378 smallCfg := app.GetDefaultSmallModel(largeProviderID)
379 app.config.Models[config.SelectedModelTypeSmall] = smallCfg
380 }
381
382 return app.AgentCoordinator.UpdateModels(ctx)
383}
384
385// GetDefaultSmallModel returns the default small model for the given
386// provider. Falls back to the large model if no default is found.
387func (app *App) GetDefaultSmallModel(providerID string) config.SelectedModel {
388 cfg := app.config
389 largeModelCfg := cfg.Models[config.SelectedModelTypeLarge]
390
391 // Find the provider in the known providers list to get its default small model.
392 knownProviders, _ := config.Providers(cfg)
393 var knownProvider *catwalk.Provider
394 for _, p := range knownProviders {
395 if string(p.ID) == providerID {
396 knownProvider = &p
397 break
398 }
399 }
400
401 // For unknown/local providers, use the large model as small.
402 if knownProvider == nil {
403 slog.Warn("Using large model as small model for unknown provider", "provider", providerID, "model", largeModelCfg.Model)
404 return largeModelCfg
405 }
406
407 defaultSmallModelID := knownProvider.DefaultSmallModelID
408 model := cfg.GetModel(providerID, defaultSmallModelID)
409 if model == nil {
410 slog.Warn("Default small model not found, using large model", "provider", providerID, "model", largeModelCfg.Model)
411 return largeModelCfg
412 }
413
414 slog.Info("Using provider default small model", "provider", providerID, "model", defaultSmallModelID)
415 return config.SelectedModel{
416 Provider: providerID,
417 Model: defaultSmallModelID,
418 MaxTokens: model.DefaultMaxTokens,
419 ReasoningEffort: model.DefaultReasoningEffort,
420 }
421}
422
423func (app *App) setupEvents() {
424 ctx, cancel := context.WithCancel(app.globalCtx)
425 app.eventsCtx = ctx
426 setupSubscriber(ctx, app.serviceEventsWG, "sessions", app.Sessions.Subscribe, app.events)
427 setupSubscriber(ctx, app.serviceEventsWG, "messages", app.Messages.Subscribe, app.events)
428 setupSubscriber(ctx, app.serviceEventsWG, "permissions", app.Permissions.Subscribe, app.events)
429 setupSubscriber(ctx, app.serviceEventsWG, "permissions-notifications", app.Permissions.SubscribeNotifications, app.events)
430 setupSubscriber(ctx, app.serviceEventsWG, "history", app.History.Subscribe, app.events)
431 setupSubscriber(ctx, app.serviceEventsWG, "mcp", mcp.SubscribeEvents, app.events)
432 setupSubscriber(ctx, app.serviceEventsWG, "lsp", SubscribeLSPEvents, app.events)
433 cleanupFunc := func(context.Context) error {
434 cancel()
435 app.serviceEventsWG.Wait()
436 return nil
437 }
438 app.cleanupFuncs = append(app.cleanupFuncs, cleanupFunc)
439}
440
441const subscriberSendTimeout = 2 * time.Second
442
443func setupSubscriber[T any](
444 ctx context.Context,
445 wg *sync.WaitGroup,
446 name string,
447 subscriber func(context.Context) <-chan pubsub.Event[T],
448 outputCh chan<- tea.Msg,
449) {
450 wg.Go(func() {
451 subCh := subscriber(ctx)
452 sendTimer := time.NewTimer(0)
453 <-sendTimer.C
454 defer sendTimer.Stop()
455
456 for {
457 select {
458 case event, ok := <-subCh:
459 if !ok {
460 slog.Debug("Subscription channel closed", "name", name)
461 return
462 }
463 var msg tea.Msg = event
464 if !sendTimer.Stop() {
465 select {
466 case <-sendTimer.C:
467 default:
468 }
469 }
470 sendTimer.Reset(subscriberSendTimeout)
471
472 select {
473 case outputCh <- msg:
474 case <-sendTimer.C:
475 slog.Debug("Message dropped due to slow consumer", "name", name)
476 case <-ctx.Done():
477 slog.Debug("Subscription cancelled", "name", name)
478 return
479 }
480 case <-ctx.Done():
481 slog.Debug("Subscription cancelled", "name", name)
482 return
483 }
484 }
485 })
486}
487
488func (app *App) InitCoderAgent(ctx context.Context) error {
489 coderAgentCfg := app.config.Agents[config.AgentCoder]
490 if coderAgentCfg.ID == "" {
491 return fmt.Errorf("coder agent configuration is missing")
492 }
493 var err error
494 app.AgentCoordinator, err = agent.NewCoordinator(
495 ctx,
496 app.config,
497 app.Sessions,
498 app.Messages,
499 app.Permissions,
500 app.History,
501 app.FileTracker,
502 app.LSPManager,
503 )
504 if err != nil {
505 slog.Error("Failed to create coder agent", "err", err)
506 return err
507 }
508 return nil
509}
510
511// Subscribe sends events to the TUI as tea.Msgs.
512func (app *App) Subscribe(program *tea.Program) {
513 defer log.RecoverPanic("app.Subscribe", func() {
514 slog.Info("TUI subscription panic: attempting graceful shutdown")
515 program.Quit()
516 })
517
518 app.tuiWG.Add(1)
519 tuiCtx, tuiCancel := context.WithCancel(app.globalCtx)
520 app.cleanupFuncs = append(app.cleanupFuncs, func(context.Context) error {
521 slog.Debug("Cancelling TUI message handler")
522 tuiCancel()
523 app.tuiWG.Wait()
524 return nil
525 })
526 defer app.tuiWG.Done()
527
528 for {
529 select {
530 case <-tuiCtx.Done():
531 slog.Debug("TUI message handler shutting down")
532 return
533 case msg, ok := <-app.events:
534 if !ok {
535 slog.Debug("TUI message channel closed")
536 return
537 }
538 program.Send(msg)
539 }
540 }
541}
542
543// Shutdown performs a graceful shutdown of the application.
544func (app *App) Shutdown() {
545 start := time.Now()
546 defer func() { slog.Debug("Shutdown took " + time.Since(start).String()) }()
547
548 // First, cancel all agents and wait for them to finish. This must complete
549 // before closing the DB so agents can finish writing their state.
550 if app.AgentCoordinator != nil {
551 app.AgentCoordinator.CancelAll()
552 }
553
554 // Now run remaining cleanup tasks in parallel.
555 var wg sync.WaitGroup
556
557 // Shared shutdown context for all timeout-bounded cleanup.
558 shutdownCtx, cancel := context.WithTimeout(context.WithoutCancel(app.globalCtx), 5*time.Second)
559 defer cancel()
560
561 // Send exit event
562 wg.Go(func() {
563 event.AppExited()
564 })
565
566 // Kill all background shells.
567 wg.Go(func() {
568 shell.GetBackgroundShellManager().KillAll(shutdownCtx)
569 })
570
571 // Shutdown all LSP clients.
572 wg.Go(func() {
573 app.LSPManager.KillAll(shutdownCtx)
574 })
575
576 // Call all cleanup functions.
577 for _, cleanup := range app.cleanupFuncs {
578 if cleanup != nil {
579 wg.Go(func() {
580 if err := cleanup(shutdownCtx); err != nil {
581 slog.Error("Failed to cleanup app properly on shutdown", "error", err)
582 }
583 })
584 }
585 }
586 wg.Wait()
587}
588
589// checkForUpdates checks for available updates.
590func (app *App) checkForUpdates(ctx context.Context) {
591 checkCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
592 defer cancel()
593
594 info, err := update.Check(checkCtx, version.Version, update.Default)
595 if err != nil || !info.Available() {
596 return
597 }
598 app.events <- UpdateAvailableMsg{
599 CurrentVersion: info.Current,
600 LatestVersion: info.Latest,
601 IsDevelopment: info.IsDevelopment(),
602 }
603}