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