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