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