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