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