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