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