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