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