app.go

  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	sess, err := app.Sessions.Create(ctx, agent.DefaultSessionName)
217	if err != nil {
218		return fmt.Errorf("failed to create session for non-interactive mode: %w", err)
219	}
220	slog.Info("Created session for non-interactive run", "session_id", sess.ID)
221
222	// Automatically approve all permission requests for this non-interactive
223	// session.
224	app.Permissions.AutoApproveSession(sess.ID)
225
226	type response struct {
227		result *fantasy.AgentResult
228		err    error
229	}
230	done := make(chan response, 1)
231
232	go func(ctx context.Context, sessionID, prompt string) {
233		result, err := app.AgentCoordinator.Run(ctx, sess.ID, prompt)
234		if err != nil {
235			done <- response{
236				err: fmt.Errorf("failed to start agent processing stream: %w", err),
237			}
238			return
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(context.Context) 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(context.Context) 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	// Shared shutdown context for all timeout-bounded cleanup.
544	shutdownCtx, cancel := context.WithTimeout(context.WithoutCancel(app.globalCtx), 5*time.Second)
545	defer cancel()
546
547	// Send exit event
548	wg.Go(func() {
549		event.AppExited()
550	})
551
552	// Kill all background shells.
553	wg.Go(func() {
554		shell.GetBackgroundShellManager().KillAll(shutdownCtx)
555	})
556
557	// Shutdown all LSP clients.
558	wg.Go(func() {
559		app.LSPManager.KillAll(shutdownCtx)
560	})
561
562	// Call all cleanup functions.
563	for _, cleanup := range app.cleanupFuncs {
564		if cleanup != nil {
565			wg.Go(func() {
566				if err := cleanup(shutdownCtx); err != nil {
567					slog.Error("Failed to cleanup app properly on shutdown", "error", err)
568				}
569			})
570		}
571	}
572	wg.Wait()
573}
574
575// checkForUpdates checks for available updates.
576func (app *App) checkForUpdates(ctx context.Context) {
577	checkCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
578	defer cancel()
579
580	info, err := update.Check(checkCtx, version.Version, update.Default)
581	if err != nil || !info.Available() {
582		return
583	}
584	app.events <- UpdateAvailableMsg{
585		CurrentVersion: info.Current,
586		LatestVersion:  info.Latest,
587		IsDevelopment:  info.IsDevelopment(),
588	}
589}