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