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, verbose 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, verbose)
245 if err != nil {
246 done <- response{
247 err: fmt.Errorf("failed to start agent processing stream: %w", err),
248 }
249 return
250 }
251 done <- response{
252 result: result,
253 }
254 }(ctx, sess.ID, prompt)
255
256 messageEvents := app.Messages.Subscribe(ctx)
257 messageReadBytes := make(map[string]int)
258 var printed bool
259
260 defer func() {
261 if progress && stderrTTY {
262 _, _ = fmt.Fprintf(os.Stderr, ansi.ResetProgressBar)
263 }
264
265 // Always print a newline at the end. If output is a TTY this will
266 // prevent the prompt from overwriting the last line of output.
267 _, _ = fmt.Fprintln(output)
268 }()
269
270 for {
271 if progress && stderrTTY {
272 // HACK: Reinitialize the terminal progress bar on every iteration
273 // so it doesn't get hidden by the terminal due to inactivity.
274 _, _ = fmt.Fprintf(os.Stderr, ansi.SetIndeterminateProgressBar)
275 }
276
277 select {
278 case result := <-done:
279 stopSpinner()
280 if result.err != nil {
281 if errors.Is(result.err, context.Canceled) || errors.Is(result.err, agent.ErrRequestCancelled) {
282 slog.Debug("Non-interactive: agent processing cancelled", "session_id", sess.ID)
283 return nil
284 }
285 return fmt.Errorf("agent processing failed: %w", result.err)
286 }
287 return nil
288
289 case event := <-messageEvents:
290 msg := event.Payload
291 if msg.SessionID == sess.ID && msg.Role == message.Assistant && len(msg.Parts) > 0 {
292 stopSpinner()
293
294 content := msg.Content().String()
295 readBytes := messageReadBytes[msg.ID]
296
297 if len(content) < readBytes {
298 slog.Error("Non-interactive: message content is shorter than read bytes", "message_length", len(content), "read_bytes", readBytes)
299 return fmt.Errorf("message content is shorter than read bytes: %d < %d", len(content), readBytes)
300 }
301
302 part := content[readBytes:]
303 // Trim leading whitespace. Sometimes the LLM includes leading
304 // formatting and intentation, which we don't want here.
305 if readBytes == 0 {
306 part = strings.TrimLeft(part, " \t")
307 }
308 // Ignore initial whitespace-only messages.
309 if printed || strings.TrimSpace(part) != "" {
310 printed = true
311 fmt.Fprint(output, part)
312 }
313 messageReadBytes[msg.ID] = len(content)
314 }
315
316 case <-ctx.Done():
317 stopSpinner()
318 return ctx.Err()
319 }
320 }
321}
322
323func (app *App) UpdateAgentModel(ctx context.Context) error {
324 if app.AgentCoordinator == nil {
325 return fmt.Errorf("agent configuration is missing")
326 }
327 return app.AgentCoordinator.UpdateModels(ctx)
328}
329
330// overrideModelsForNonInteractive parses the model strings and temporarily
331// overrides the model configurations, then rebuilds the agent.
332// Format: "model-name" (searches all providers) or "provider/model-name".
333// Model matching is case-insensitive.
334// If largeModel is provided but smallModel is not, the small model defaults to
335// the provider's default small model.
336func (app *App) overrideModelsForNonInteractive(ctx context.Context, largeModel, smallModel string) error {
337 providers := app.config.Providers.Copy()
338
339 largeMatches, smallMatches, err := findModels(providers, largeModel, smallModel)
340 if err != nil {
341 return err
342 }
343
344 var largeProviderID string
345
346 // Override large model.
347 if largeModel != "" {
348 found, err := validateMatches(largeMatches, largeModel, "large")
349 if err != nil {
350 return err
351 }
352 largeProviderID = found.provider
353 slog.Info("Overriding large model for non-interactive run", "provider", found.provider, "model", found.modelID)
354 app.config.Models[config.SelectedModelTypeLarge] = config.SelectedModel{
355 Provider: found.provider,
356 Model: found.modelID,
357 }
358 }
359
360 // Override small model.
361 switch {
362 case smallModel != "":
363 found, err := validateMatches(smallMatches, smallModel, "small")
364 if err != nil {
365 return err
366 }
367 slog.Info("Overriding small model for non-interactive run", "provider", found.provider, "model", found.modelID)
368 app.config.Models[config.SelectedModelTypeSmall] = config.SelectedModel{
369 Provider: found.provider,
370 Model: found.modelID,
371 }
372
373 case largeModel != "":
374 // No small model specified, but large model was - use provider's default.
375 smallCfg := app.GetDefaultSmallModel(largeProviderID)
376 app.config.Models[config.SelectedModelTypeSmall] = smallCfg
377 }
378
379 return app.AgentCoordinator.UpdateModels(ctx)
380}
381
382// GetDefaultSmallModel returns the default small model for the given
383// provider. Falls back to the large model if no default is found.
384func (app *App) GetDefaultSmallModel(providerID string) config.SelectedModel {
385 cfg := app.config
386 largeModelCfg := cfg.Models[config.SelectedModelTypeLarge]
387
388 // Find the provider in the known providers list to get its default small model.
389 knownProviders, _ := config.Providers(cfg)
390 var knownProvider *catwalk.Provider
391 for _, p := range knownProviders {
392 if string(p.ID) == providerID {
393 knownProvider = &p
394 break
395 }
396 }
397
398 // For unknown/local providers, use the large model as small.
399 if knownProvider == nil {
400 slog.Warn("Using large model as small model for unknown provider", "provider", providerID, "model", largeModelCfg.Model)
401 return largeModelCfg
402 }
403
404 defaultSmallModelID := knownProvider.DefaultSmallModelID
405 model := cfg.GetModel(providerID, defaultSmallModelID)
406 if model == nil {
407 slog.Warn("Default small model not found, using large model", "provider", providerID, "model", largeModelCfg.Model)
408 return largeModelCfg
409 }
410
411 slog.Info("Using provider default small model", "provider", providerID, "model", defaultSmallModelID)
412 return config.SelectedModel{
413 Provider: providerID,
414 Model: defaultSmallModelID,
415 MaxTokens: model.DefaultMaxTokens,
416 ReasoningEffort: model.DefaultReasoningEffort,
417 }
418}
419
420func (app *App) setupEvents() {
421 ctx, cancel := context.WithCancel(app.globalCtx)
422 app.eventsCtx = ctx
423 setupSubscriber(ctx, app.serviceEventsWG, "sessions", app.Sessions.Subscribe, app.events)
424 setupSubscriber(ctx, app.serviceEventsWG, "messages", app.Messages.Subscribe, app.events)
425 setupSubscriber(ctx, app.serviceEventsWG, "permissions", app.Permissions.Subscribe, app.events)
426 setupSubscriber(ctx, app.serviceEventsWG, "permissions-notifications", app.Permissions.SubscribeNotifications, app.events)
427 setupSubscriber(ctx, app.serviceEventsWG, "history", app.History.Subscribe, app.events)
428 setupSubscriber(ctx, app.serviceEventsWG, "mcp", mcp.SubscribeEvents, app.events)
429 setupSubscriber(ctx, app.serviceEventsWG, "lsp", SubscribeLSPEvents, app.events)
430 cleanupFunc := func(context.Context) error {
431 cancel()
432 app.serviceEventsWG.Wait()
433 return nil
434 }
435 app.cleanupFuncs = append(app.cleanupFuncs, cleanupFunc)
436}
437
438const subscriberSendTimeout = 2 * time.Second
439
440func setupSubscriber[T any](
441 ctx context.Context,
442 wg *sync.WaitGroup,
443 name string,
444 subscriber func(context.Context) <-chan pubsub.Event[T],
445 outputCh chan<- tea.Msg,
446) {
447 wg.Go(func() {
448 subCh := subscriber(ctx)
449 sendTimer := time.NewTimer(0)
450 <-sendTimer.C
451 defer sendTimer.Stop()
452
453 for {
454 select {
455 case event, ok := <-subCh:
456 if !ok {
457 slog.Debug("Subscription channel closed", "name", name)
458 return
459 }
460 var msg tea.Msg = event
461 if !sendTimer.Stop() {
462 select {
463 case <-sendTimer.C:
464 default:
465 }
466 }
467 sendTimer.Reset(subscriberSendTimeout)
468
469 select {
470 case outputCh <- msg:
471 case <-sendTimer.C:
472 slog.Debug("Message dropped due to slow consumer", "name", name)
473 case <-ctx.Done():
474 slog.Debug("Subscription cancelled", "name", name)
475 return
476 }
477 case <-ctx.Done():
478 slog.Debug("Subscription cancelled", "name", name)
479 return
480 }
481 }
482 })
483}
484
485func (app *App) InitCoderAgent(ctx context.Context) error {
486 coderAgentCfg := app.config.Agents[config.AgentCoder]
487 if coderAgentCfg.ID == "" {
488 return fmt.Errorf("coder agent configuration is missing")
489 }
490 var err error
491 app.AgentCoordinator, err = agent.NewCoordinator(
492 ctx,
493 app.config,
494 app.Sessions,
495 app.Messages,
496 app.Permissions,
497 app.History,
498 app.FileTracker,
499 app.LSPManager,
500 )
501 if err != nil {
502 slog.Error("Failed to create coder agent", "err", err)
503 return err
504 }
505 return nil
506}
507
508// Subscribe sends events to the TUI as tea.Msgs.
509func (app *App) Subscribe(program *tea.Program) {
510 defer log.RecoverPanic("app.Subscribe", func() {
511 slog.Info("TUI subscription panic: attempting graceful shutdown")
512 program.Quit()
513 })
514
515 app.tuiWG.Add(1)
516 tuiCtx, tuiCancel := context.WithCancel(app.globalCtx)
517 app.cleanupFuncs = append(app.cleanupFuncs, func(context.Context) error {
518 slog.Debug("Cancelling TUI message handler")
519 tuiCancel()
520 app.tuiWG.Wait()
521 return nil
522 })
523 defer app.tuiWG.Done()
524
525 for {
526 select {
527 case <-tuiCtx.Done():
528 slog.Debug("TUI message handler shutting down")
529 return
530 case msg, ok := <-app.events:
531 if !ok {
532 slog.Debug("TUI message channel closed")
533 return
534 }
535 program.Send(msg)
536 }
537 }
538}
539
540// Shutdown performs a graceful shutdown of the application.
541func (app *App) Shutdown() {
542 start := time.Now()
543 defer func() { slog.Debug("Shutdown took " + time.Since(start).String()) }()
544
545 // First, cancel all agents and wait for them to finish. This must complete
546 // before closing the DB so agents can finish writing their state.
547 if app.AgentCoordinator != nil {
548 app.AgentCoordinator.CancelAll()
549 }
550
551 // Now run remaining cleanup tasks in parallel.
552 var wg sync.WaitGroup
553
554 // Shared shutdown context for all timeout-bounded cleanup.
555 shutdownCtx, cancel := context.WithTimeout(context.WithoutCancel(app.globalCtx), 5*time.Second)
556 defer cancel()
557
558 // Send exit event
559 wg.Go(func() {
560 event.AppExited()
561 })
562
563 // Kill all background shells.
564 wg.Go(func() {
565 shell.GetBackgroundShellManager().KillAll(shutdownCtx)
566 })
567
568 // Shutdown all LSP clients.
569 wg.Go(func() {
570 app.LSPManager.KillAll(shutdownCtx)
571 })
572
573 // Call all cleanup functions.
574 for _, cleanup := range app.cleanupFuncs {
575 if cleanup != nil {
576 wg.Go(func() {
577 if err := cleanup(shutdownCtx); err != nil {
578 slog.Error("Failed to cleanup app properly on shutdown", "error", err)
579 }
580 })
581 }
582 }
583 wg.Wait()
584}
585
586// checkForUpdates checks for available updates.
587func (app *App) checkForUpdates(ctx context.Context) {
588 checkCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
589 defer cancel()
590
591 info, err := update.Check(checkCtx, version.Version, update.Default)
592 if err != nil || !info.Available() {
593 return
594 }
595 app.events <- UpdateAvailableMsg{
596 CurrentVersion: info.Current,
597 LatestVersion: info.Latest,
598 IsDevelopment: info.IsDevelopment(),
599 }
600}