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	"sync"
 14	"time"
 15
 16	tea "charm.land/bubbletea/v2"
 17	"charm.land/fantasy"
 18	"charm.land/lipgloss/v2"
 19	"github.com/charmbracelet/crush/internal/agent"
 20	"github.com/charmbracelet/crush/internal/agent/tools/mcp"
 21	"github.com/charmbracelet/crush/internal/config"
 22	"github.com/charmbracelet/crush/internal/csync"
 23	"github.com/charmbracelet/crush/internal/db"
 24	"github.com/charmbracelet/crush/internal/format"
 25	"github.com/charmbracelet/crush/internal/history"
 26	"github.com/charmbracelet/crush/internal/hooks"
 27	"github.com/charmbracelet/crush/internal/log"
 28	"github.com/charmbracelet/crush/internal/lsp"
 29	"github.com/charmbracelet/crush/internal/message"
 30	"github.com/charmbracelet/crush/internal/permission"
 31	"github.com/charmbracelet/crush/internal/pubsub"
 32	"github.com/charmbracelet/crush/internal/session"
 33	"github.com/charmbracelet/crush/internal/shell"
 34	"github.com/charmbracelet/crush/internal/term"
 35	"github.com/charmbracelet/crush/internal/tui/components/anim"
 36	"github.com/charmbracelet/crush/internal/tui/styles"
 37	"github.com/charmbracelet/crush/internal/update"
 38	"github.com/charmbracelet/crush/internal/version"
 39	"github.com/charmbracelet/x/ansi"
 40	"github.com/charmbracelet/x/exp/charmtone"
 41)
 42
 43type App struct {
 44	Sessions    session.Service
 45	Messages    message.Service
 46	History     history.Service
 47	Permissions permission.Service
 48
 49	AgentCoordinator agent.Coordinator
 50	HooksManager     hooks.Manager
 51
 52	LSPClients *csync.Map[string, *lsp.Client]
 53
 54	config *config.Config
 55
 56	serviceEventsWG *sync.WaitGroup
 57	eventsCtx       context.Context
 58	events          chan tea.Msg
 59	tuiWG           *sync.WaitGroup
 60
 61	// global context and cleanup functions
 62	globalCtx    context.Context
 63	cleanupFuncs []func() error
 64}
 65
 66// New initializes a new applcation instance.
 67func New(ctx context.Context, conn *sql.DB, cfg *config.Config) (*App, error) {
 68	q := db.New(conn)
 69	sessions := session.NewService(q)
 70	messages := message.NewService(q)
 71	files := history.NewService(q, conn)
 72	skipPermissionsRequests := cfg.Permissions != nil && cfg.Permissions.SkipRequests
 73	allowedTools := []string{}
 74	if cfg.Permissions != nil && cfg.Permissions.AllowedTools != nil {
 75		allowedTools = cfg.Permissions.AllowedTools
 76	}
 77
 78	app := &App{
 79		Sessions:    sessions,
 80		Messages:    messages,
 81		History:     files,
 82		Permissions: permission.NewPermissionService(cfg.WorkingDir(), skipPermissionsRequests, allowedTools),
 83		LSPClients:  csync.NewMap[string, *lsp.Client](),
 84
 85		globalCtx: ctx,
 86
 87		config: cfg,
 88
 89		events:          make(chan tea.Msg, 100),
 90		serviceEventsWG: &sync.WaitGroup{},
 91		tuiWG:           &sync.WaitGroup{},
 92	}
 93
 94	// Initialize hooks manager.
 95	app.HooksManager = hooks.NewManager(cfg.WorkingDir(), cfg.Options.DataDirectory, cfg.Hooks)
 96
 97	app.setupEvents()
 98
 99	// Initialize LSP clients in the background.
100	app.initLSPClients(ctx)
101
102	// Check for updates in the background.
103	go app.checkForUpdates(ctx)
104
105	go func() {
106		slog.Info("Initializing MCP clients")
107		mcp.Initialize(ctx, app.Permissions, cfg)
108	}()
109
110	// cleanup database upon app shutdown
111	app.cleanupFuncs = append(app.cleanupFuncs, conn.Close, mcp.Close)
112
113	// TODO: remove the concept of agent config, most likely.
114	if !cfg.IsConfigured() {
115		slog.Warn("No agent configuration found")
116		return app, nil
117	}
118	if err := app.InitCoderAgent(ctx); err != nil {
119		return nil, fmt.Errorf("failed to initialize coder agent: %w", err)
120	}
121	return app, nil
122}
123
124// Config returns the application configuration.
125func (app *App) Config() *config.Config {
126	return app.config
127}
128
129// RunNonInteractive runs the application in non-interactive mode with the
130// given prompt, printing to stdout.
131func (app *App) RunNonInteractive(ctx context.Context, output io.Writer, prompt string, quiet bool) error {
132	slog.Info("Running in non-interactive mode")
133
134	ctx, cancel := context.WithCancel(ctx)
135	defer cancel()
136
137	var spinner *format.Spinner
138	if !quiet {
139		t := styles.CurrentTheme()
140
141		// Detect background color to set the appropriate color for the
142		// spinner's 'Generating...' text. Without this, that text would be
143		// unreadable in light terminals.
144		hasDarkBG := true
145		if f, ok := output.(*os.File); ok {
146			hasDarkBG = lipgloss.HasDarkBackground(os.Stdin, f)
147		}
148		defaultFG := lipgloss.LightDark(hasDarkBG)(charmtone.Pepper, t.FgBase)
149
150		spinner = format.NewSpinner(ctx, cancel, anim.Settings{
151			Size:        10,
152			Label:       "Generating",
153			LabelColor:  defaultFG,
154			GradColorA:  t.Primary,
155			GradColorB:  t.Secondary,
156			CycleColors: true,
157		})
158		spinner.Start()
159	}
160
161	// Helper function to stop spinner once.
162	stopSpinner := func() {
163		if !quiet && spinner != nil {
164			spinner.Stop()
165			spinner = nil
166		}
167	}
168	defer stopSpinner()
169
170	const maxPromptLengthForTitle = 100
171	const titlePrefix = "Non-interactive: "
172	var titleSuffix string
173
174	if len(prompt) > maxPromptLengthForTitle {
175		titleSuffix = prompt[:maxPromptLengthForTitle] + "..."
176	} else {
177		titleSuffix = prompt
178	}
179	title := titlePrefix + titleSuffix
180
181	sess, err := app.Sessions.Create(ctx, title)
182	if err != nil {
183		return fmt.Errorf("failed to create session for non-interactive mode: %w", err)
184	}
185	slog.Info("Created session for non-interactive run", "session_id", sess.ID)
186
187	// Automatically approve all permission requests for this non-interactive
188	// session.
189	app.Permissions.AutoApproveSession(sess.ID)
190
191	type response struct {
192		result *fantasy.AgentResult
193		err    error
194	}
195	done := make(chan response, 1)
196
197	go func(ctx context.Context, sessionID, prompt string) {
198		result, err := app.AgentCoordinator.Run(ctx, sess.ID, prompt)
199		if err != nil {
200			done <- response{
201				err: fmt.Errorf("failed to start agent processing stream: %w", err),
202			}
203		}
204		done <- response{
205			result: result,
206		}
207	}(ctx, sess.ID, prompt)
208
209	messageEvents := app.Messages.Subscribe(ctx)
210	messageReadBytes := make(map[string]int)
211	supportsProgressBar := term.SupportsProgressBar()
212
213	defer func() {
214		if supportsProgressBar {
215			_, _ = fmt.Fprintf(os.Stderr, ansi.ResetProgressBar)
216		}
217
218		// Always print a newline at the end. If output is a TTY this will
219		// prevent the prompt from overwriting the last line of output.
220		_, _ = fmt.Fprintln(output)
221	}()
222
223	for {
224		if supportsProgressBar {
225			// HACK: Reinitialize the terminal progress bar on every iteration so
226			// it doesn't get hidden by the terminal due to inactivity.
227			_, _ = fmt.Fprintf(os.Stderr, ansi.SetIndeterminateProgressBar)
228		}
229
230		select {
231		case result := <-done:
232			stopSpinner()
233			if result.err != nil {
234				if errors.Is(result.err, context.Canceled) || errors.Is(result.err, agent.ErrRequestCancelled) {
235					slog.Info("Non-interactive: agent processing cancelled", "session_id", sess.ID)
236					return nil
237				}
238				return fmt.Errorf("agent processing failed: %w", result.err)
239			}
240			return nil
241
242		case event := <-messageEvents:
243			msg := event.Payload
244			if msg.SessionID == sess.ID && msg.Role == message.Assistant && len(msg.Parts) > 0 {
245				stopSpinner()
246
247				content := msg.Content().String()
248				readBytes := messageReadBytes[msg.ID]
249
250				if len(content) < readBytes {
251					slog.Error("Non-interactive: message content is shorter than read bytes", "message_length", len(content), "read_bytes", readBytes)
252					return fmt.Errorf("message content is shorter than read bytes: %d < %d", len(content), readBytes)
253				}
254
255				part := content[readBytes:]
256				fmt.Fprint(output, part)
257				messageReadBytes[msg.ID] = len(content)
258			}
259
260		case <-ctx.Done():
261			stopSpinner()
262			return ctx.Err()
263		}
264	}
265}
266
267func (app *App) UpdateAgentModel(ctx context.Context) error {
268	return app.AgentCoordinator.UpdateModels(ctx)
269}
270
271func (app *App) setupEvents() {
272	ctx, cancel := context.WithCancel(app.globalCtx)
273	app.eventsCtx = ctx
274	setupSubscriber(ctx, app.serviceEventsWG, "sessions", app.Sessions.Subscribe, app.events)
275	setupSubscriber(ctx, app.serviceEventsWG, "messages", app.Messages.Subscribe, app.events)
276	setupSubscriber(ctx, app.serviceEventsWG, "permissions", app.Permissions.Subscribe, app.events)
277	setupSubscriber(ctx, app.serviceEventsWG, "permissions-notifications", app.Permissions.SubscribeNotifications, app.events)
278	setupSubscriber(ctx, app.serviceEventsWG, "history", app.History.Subscribe, app.events)
279	setupSubscriber(ctx, app.serviceEventsWG, "mcp", mcp.SubscribeEvents, app.events)
280	setupSubscriber(ctx, app.serviceEventsWG, "lsp", SubscribeLSPEvents, app.events)
281	cleanupFunc := func() error {
282		cancel()
283		app.serviceEventsWG.Wait()
284		return nil
285	}
286	app.cleanupFuncs = append(app.cleanupFuncs, cleanupFunc)
287}
288
289func setupSubscriber[T any](
290	ctx context.Context,
291	wg *sync.WaitGroup,
292	name string,
293	subscriber func(context.Context) <-chan pubsub.Event[T],
294	outputCh chan<- tea.Msg,
295) {
296	wg.Go(func() {
297		subCh := subscriber(ctx)
298		for {
299			select {
300			case event, ok := <-subCh:
301				if !ok {
302					slog.Debug("subscription channel closed", "name", name)
303					return
304				}
305				var msg tea.Msg = event
306				select {
307				case outputCh <- msg:
308				case <-time.After(2 * time.Second):
309					slog.Warn("message dropped due to slow consumer", "name", name)
310				case <-ctx.Done():
311					slog.Debug("subscription cancelled", "name", name)
312					return
313				}
314			case <-ctx.Done():
315				slog.Debug("subscription cancelled", "name", name)
316				return
317			}
318		}
319	})
320}
321
322func (app *App) InitCoderAgent(ctx context.Context) error {
323	coderAgentCfg := app.config.Agents[config.AgentCoder]
324	if coderAgentCfg.ID == "" {
325		return fmt.Errorf("coder agent configuration is missing")
326	}
327	var err error
328	app.AgentCoordinator, err = agent.NewCoordinator(
329		ctx,
330		app.config,
331		app.Sessions,
332		app.Messages,
333		app.Permissions,
334		app.History,
335		app.LSPClients,
336		app.HooksManager,
337	)
338	if err != nil {
339		slog.Error("Failed to create coder agent", "err", err)
340		return err
341	}
342	return nil
343}
344
345// Subscribe sends events to the TUI as tea.Msgs.
346func (app *App) Subscribe(program *tea.Program) {
347	defer log.RecoverPanic("app.Subscribe", func() {
348		slog.Info("TUI subscription panic: attempting graceful shutdown")
349		program.Quit()
350	})
351
352	app.tuiWG.Add(1)
353	tuiCtx, tuiCancel := context.WithCancel(app.globalCtx)
354	app.cleanupFuncs = append(app.cleanupFuncs, func() error {
355		slog.Debug("Cancelling TUI message handler")
356		tuiCancel()
357		app.tuiWG.Wait()
358		return nil
359	})
360	defer app.tuiWG.Done()
361
362	for {
363		select {
364		case <-tuiCtx.Done():
365			slog.Debug("TUI message handler shutting down")
366			return
367		case msg, ok := <-app.events:
368			if !ok {
369				slog.Debug("TUI message channel closed")
370				return
371			}
372			program.Send(msg)
373		}
374	}
375}
376
377// Shutdown performs a graceful shutdown of the application.
378func (app *App) Shutdown() {
379	if app.AgentCoordinator != nil {
380		app.AgentCoordinator.CancelAll()
381	}
382
383	// Kill all background shells.
384	shell.GetBackgroundShellManager().KillAll()
385
386	// Shutdown all LSP clients.
387	for name, client := range app.LSPClients.Seq2() {
388		shutdownCtx, cancel := context.WithTimeout(app.globalCtx, 5*time.Second)
389		if err := client.Close(shutdownCtx); err != nil {
390			slog.Error("Failed to shutdown LSP client", "name", name, "error", err)
391		}
392		cancel()
393	}
394
395	// Call call cleanup functions.
396	for _, cleanup := range app.cleanupFuncs {
397		if cleanup != nil {
398			if err := cleanup(); err != nil {
399				slog.Error("Failed to cleanup app properly on shutdown", "error", err)
400			}
401		}
402	}
403}
404
405// checkForUpdates checks for available updates.
406func (app *App) checkForUpdates(ctx context.Context) {
407	checkCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
408	defer cancel()
409
410	info, err := update.Check(checkCtx, version.Version, update.Default)
411	if err != nil || !info.Available() {
412		return
413	}
414	app.events <- pubsub.UpdateAvailableMsg{
415		CurrentVersion: info.Current,
416		LatestVersion:  info.Latest,
417		IsDevelopment:  info.IsDevelopment(),
418	}
419}