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// 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.Config().Options.Progress == nil || *app.config.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.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.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.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.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.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, "agent-notifications", app.agentNotifications.Subscribe, app.events)
432 setupSubscriber(ctx, app.serviceEventsWG, "mcp", mcp.SubscribeEvents, app.events)
433 setupSubscriber(ctx, app.serviceEventsWG, "lsp", SubscribeLSPEvents, app.events)
434 cleanupFunc := func(context.Context) error {
435 cancel()
436 app.serviceEventsWG.Wait()
437 return nil
438 }
439 app.cleanupFuncs = append(app.cleanupFuncs, cleanupFunc)
440}
441
442const subscriberSendTimeout = 2 * time.Second
443
444func setupSubscriber[T any](
445 ctx context.Context,
446 wg *sync.WaitGroup,
447 name string,
448 subscriber func(context.Context) <-chan pubsub.Event[T],
449 outputCh chan<- tea.Msg,
450) {
451 wg.Go(func() {
452 subCh := subscriber(ctx)
453 sendTimer := time.NewTimer(0)
454 <-sendTimer.C
455 defer sendTimer.Stop()
456
457 for {
458 select {
459 case event, ok := <-subCh:
460 if !ok {
461 slog.Debug("Subscription channel closed", "name", name)
462 return
463 }
464 var msg tea.Msg = event
465 if !sendTimer.Stop() {
466 select {
467 case <-sendTimer.C:
468 default:
469 }
470 }
471 sendTimer.Reset(subscriberSendTimeout)
472
473 select {
474 case outputCh <- msg:
475 case <-sendTimer.C:
476 slog.Debug("Message dropped due to slow consumer", "name", name)
477 case <-ctx.Done():
478 slog.Debug("Subscription cancelled", "name", name)
479 return
480 }
481 case <-ctx.Done():
482 slog.Debug("Subscription cancelled", "name", name)
483 return
484 }
485 }
486 })
487}
488
489func (app *App) InitCoderAgent(ctx context.Context) error {
490 coderAgentCfg := app.config.Config().Agents[config.AgentCoder]
491 if coderAgentCfg.ID == "" {
492 return fmt.Errorf("coder agent configuration is missing")
493 }
494 var err error
495 app.AgentCoordinator, err = agent.NewCoordinator(
496 ctx,
497 app.config,
498 app.Sessions,
499 app.Messages,
500 app.Permissions,
501 app.History,
502 app.FileTracker,
503 app.LSPManager,
504 app.agentNotifications,
505 )
506 if err != nil {
507 slog.Error("Failed to create coder agent", "err", err)
508 return err
509 }
510 return nil
511}
512
513// Subscribe sends events to the TUI as tea.Msgs.
514func (app *App) Subscribe(program *tea.Program) {
515 defer log.RecoverPanic("app.Subscribe", func() {
516 slog.Info("TUI subscription panic: attempting graceful shutdown")
517 program.Quit()
518 })
519
520 app.tuiWG.Add(1)
521 tuiCtx, tuiCancel := context.WithCancel(app.globalCtx)
522 app.cleanupFuncs = append(app.cleanupFuncs, func(context.Context) error {
523 slog.Debug("Cancelling TUI message handler")
524 tuiCancel()
525 app.tuiWG.Wait()
526 return nil
527 })
528 defer app.tuiWG.Done()
529
530 for {
531 select {
532 case <-tuiCtx.Done():
533 slog.Debug("TUI message handler shutting down")
534 return
535 case msg, ok := <-app.events:
536 if !ok {
537 slog.Debug("TUI message channel closed")
538 return
539 }
540 program.Send(msg)
541 }
542 }
543}
544
545// Shutdown performs a graceful shutdown of the application.
546func (app *App) Shutdown() {
547 start := time.Now()
548 defer func() { slog.Debug("Shutdown took " + time.Since(start).String()) }()
549
550 // First, cancel all agents and wait for them to finish. This must complete
551 // before closing the DB so agents can finish writing their state.
552 if app.AgentCoordinator != nil {
553 app.AgentCoordinator.CancelAll()
554 }
555
556 // Now run remaining cleanup tasks in parallel.
557 var wg sync.WaitGroup
558
559 // Shared shutdown context for all timeout-bounded cleanup.
560 shutdownCtx, cancel := context.WithTimeout(context.WithoutCancel(app.globalCtx), 5*time.Second)
561 defer cancel()
562
563 // Send exit event
564 wg.Go(func() {
565 event.AppExited()
566 })
567
568 // Kill all background shells.
569 wg.Go(func() {
570 shell.GetBackgroundShellManager().KillAll(shutdownCtx)
571 })
572
573 // Shutdown all LSP clients.
574 wg.Go(func() {
575 app.LSPManager.KillAll(shutdownCtx)
576 })
577
578 // Call all cleanup functions.
579 for _, cleanup := range app.cleanupFuncs {
580 if cleanup != nil {
581 wg.Go(func() {
582 if err := cleanup(shutdownCtx); err != nil {
583 slog.Error("Failed to cleanup app properly on shutdown", "error", err)
584 }
585 })
586 }
587 }
588 wg.Wait()
589}
590
591// checkForUpdates checks for available updates.
592func (app *App) checkForUpdates(ctx context.Context) {
593 checkCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
594 defer cancel()
595
596 info, err := update.Check(checkCtx, version.Version, update.Default)
597 if err != nil || !info.Available() {
598 return
599 }
600 app.events <- UpdateAvailableMsg{
601 CurrentVersion: info.Current,
602 LatestVersion: info.Latest,
603 IsDevelopment: info.IsDevelopment(),
604 }
605}