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