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