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/fantasy"
 19	"charm.land/lipgloss/v2"
 20	"github.com/charmbracelet/crush/internal/agent"
 21	"github.com/charmbracelet/crush/internal/agent/tools/mcp"
 22	"github.com/charmbracelet/crush/internal/config"
 23	"github.com/charmbracelet/crush/internal/csync"
 24	"github.com/charmbracelet/crush/internal/db"
 25	"github.com/charmbracelet/crush/internal/format"
 26	"github.com/charmbracelet/crush/internal/history"
 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/tui/components/anim"
 35	"github.com/charmbracelet/crush/internal/tui/styles"
 36	"github.com/charmbracelet/crush/internal/update"
 37	"github.com/charmbracelet/crush/internal/version"
 38	"github.com/charmbracelet/x/ansi"
 39	"github.com/charmbracelet/x/exp/charmtone"
 40	"github.com/charmbracelet/x/term"
 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
 51	LSPClients *csync.Map[string, *lsp.Client]
 52
 53	config *config.Config
 54
 55	// program holds reference to the TUI program for sending events.
 56	program *tea.Program
 57
 58	// global context and cleanup functions
 59	globalCtx    context.Context
 60	cleanupFuncs []func() error
 61}
 62
 63// New initializes a new application instance.
 64func New(ctx context.Context, conn *sql.DB, cfg *config.Config) (*App, error) {
 65	q := db.New(conn)
 66	sessions := session.NewService(q)
 67	messages := message.NewService(q)
 68	files := history.NewService(q, conn)
 69	skipPermissionsRequests := cfg.Permissions != nil && cfg.Permissions.SkipRequests
 70	var allowedTools []string
 71	if cfg.Permissions != nil && cfg.Permissions.AllowedTools != nil {
 72		allowedTools = cfg.Permissions.AllowedTools
 73	}
 74
 75	app := &App{
 76		Sessions:    sessions,
 77		Messages:    messages,
 78		History:     files,
 79		Permissions: permission.NewPermissionService(cfg.WorkingDir(), skipPermissionsRequests, allowedTools),
 80		LSPClients:  csync.NewMap[string, *lsp.Client](),
 81
 82		globalCtx: ctx,
 83
 84		config: cfg,
 85	}
 86
 87	// Initialize LSP clients in the background.
 88	app.initLSPClients(ctx)
 89
 90	// Check for updates in the background.
 91	go app.checkForUpdates(ctx)
 92
 93	go func() {
 94		slog.Info("Initializing MCP clients")
 95		mcp.Initialize(ctx, app.Permissions, cfg)
 96	}()
 97
 98	// cleanup database upon app shutdown
 99	app.cleanupFuncs = append(app.cleanupFuncs, conn.Close, mcp.Close)
100
101	// TODO: remove the concept of agent config, most likely.
102	if !cfg.IsConfigured() {
103		slog.Warn("No agent configuration found")
104		return app, nil
105	}
106	if err := app.InitCoderAgent(ctx); err != nil {
107		return nil, fmt.Errorf("failed to initialize coder agent: %w", err)
108	}
109	return app, nil
110}
111
112// Config returns the application configuration.
113func (app *App) Config() *config.Config {
114	return app.config
115}
116
117// RunNonInteractive runs the application in non-interactive mode with the
118// given prompt, printing to stdout.
119func (app *App) RunNonInteractive(ctx context.Context, output io.Writer, prompt string, quiet bool) error {
120	slog.Info("Running in non-interactive mode")
121
122	ctx, cancel := context.WithCancel(ctx)
123	defer cancel()
124
125	var (
126		spinner   *format.Spinner
127		stdoutTTY bool
128		stderrTTY bool
129		stdinTTY  bool
130	)
131
132	if f, ok := output.(*os.File); ok {
133		stdoutTTY = term.IsTerminal(f.Fd())
134	}
135	stderrTTY = term.IsTerminal(os.Stderr.Fd())
136	stdinTTY = term.IsTerminal(os.Stdin.Fd())
137
138	if !quiet && stderrTTY {
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 && stdinTTY && stdoutTTY {
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
169	// Wait for MCP initialization to complete before reading MCP tools.
170	if err := mcp.WaitForInit(ctx); err != nil {
171		return fmt.Errorf("failed to wait for MCP initialization: %w", err)
172	}
173
174	// force update of agent models before running so mcp tools are loaded
175	app.AgentCoordinator.UpdateModels(ctx)
176
177	defer stopSpinner()
178
179	const maxPromptLengthForTitle = 100
180	const titlePrefix = "Non-interactive: "
181	var titleSuffix string
182
183	if len(prompt) > maxPromptLengthForTitle {
184		titleSuffix = prompt[:maxPromptLengthForTitle] + "..."
185	} else {
186		titleSuffix = prompt
187	}
188	title := titlePrefix + titleSuffix
189
190	sess, err := app.Sessions.Create(ctx, title)
191	if err != nil {
192		return fmt.Errorf("failed to create session for non-interactive mode: %w", err)
193	}
194	slog.Info("Created session for non-interactive run", "session_id", sess.ID)
195
196	// Automatically approve all permission requests for this non-interactive
197	// session.
198	app.Permissions.AutoApproveSession(sess.ID)
199
200	type response struct {
201		result *fantasy.AgentResult
202		err    error
203	}
204	done := make(chan response, 1)
205
206	go func(ctx context.Context, sessionID, prompt string) {
207		result, err := app.AgentCoordinator.Run(ctx, sess.ID, prompt)
208		if err != nil {
209			done <- response{
210				err: fmt.Errorf("failed to start agent processing stream: %w", err),
211			}
212		}
213		done <- response{
214			result: result,
215		}
216	}(ctx, sess.ID, prompt)
217
218	var (
219		messageReadBytes   = make(map[string]int)
220		messageReadBytesMu sync.Mutex
221	)
222
223	// Register callback to process messages directly.
224	app.Messages.AddListener(func(event pubsub.Event[message.Message]) {
225		msg := event.Payload
226		if msg.SessionID != sess.ID || msg.Role != message.Assistant || len(msg.Parts) == 0 {
227			return
228		}
229
230		content := msg.Content().String()
231		if content != "" {
232			stopSpinner()
233		}
234
235		messageReadBytesMu.Lock()
236		readBytes := messageReadBytes[msg.ID]
237		if len(content) >= readBytes {
238			part := content[readBytes:]
239			// Trim leading whitespace. Sometimes the LLM includes leading
240			// formatting and indentation, which we don't want here.
241			if readBytes == 0 {
242				part = strings.TrimLeft(part, " \t")
243			}
244			fmt.Fprint(output, part)
245			messageReadBytes[msg.ID] = len(content)
246		}
247		messageReadBytesMu.Unlock()
248	})
249
250	defer func() {
251		if stderrTTY {
252			_, _ = fmt.Fprintf(os.Stderr, ansi.ResetProgressBar)
253		}
254
255		// Always print a newline at the end. If output is a TTY this will
256		// prevent the prompt from overwriting the last line of output.
257		_, _ = fmt.Fprintln(output)
258	}()
259
260	// Wait for agent completion or cancellation.
261	for {
262		if stderrTTY {
263			// HACK: Reinitialize the terminal progress bar on every iteration
264			// so it doesn't get hidden by the terminal due to inactivity.
265			_, _ = fmt.Fprintf(os.Stderr, ansi.SetIndeterminateProgressBar)
266		}
267
268		select {
269		case result := <-done:
270			stopSpinner()
271			if result.err != nil {
272				if errors.Is(result.err, context.Canceled) || errors.Is(result.err, agent.ErrRequestCancelled) {
273					slog.Info("Non-interactive: agent processing cancelled", "session_id", sess.ID)
274					return nil
275				}
276				return fmt.Errorf("agent processing failed: %w", result.err)
277			}
278			return nil
279
280		case <-ctx.Done():
281			stopSpinner()
282			return ctx.Err()
283		}
284	}
285}
286
287func (app *App) UpdateAgentModel(ctx context.Context) error {
288	if app.AgentCoordinator == nil {
289		return fmt.Errorf("agent configuration is missing")
290	}
291	return app.AgentCoordinator.UpdateModels(ctx)
292}
293
294func (app *App) InitCoderAgent(ctx context.Context) error {
295	coderAgentCfg := app.config.Agents[config.AgentCoder]
296	if coderAgentCfg.ID == "" {
297		return fmt.Errorf("coder agent configuration is missing")
298	}
299	var err error
300	app.AgentCoordinator, err = agent.NewCoordinator(
301		ctx,
302		app.config,
303		app.Sessions,
304		app.Messages,
305		app.Permissions,
306		app.History,
307		app.LSPClients,
308	)
309	if err != nil {
310		slog.Error("Failed to create coder agent", "err", err)
311		return err
312	}
313	return nil
314}
315
316// Subscribe registers event listeners that send events to the TUI program.
317func (app *App) Subscribe(program *tea.Program) {
318	defer log.RecoverPanic("app.Subscribe", func() {
319		slog.Info("TUI subscription panic: attempting graceful shutdown")
320		program.Quit()
321	})
322
323	app.program = program
324
325	// Register listeners that send directly to the program.
326	app.Sessions.AddListener(func(event pubsub.Event[session.Session]) {
327		program.Send(event)
328	})
329	app.Messages.AddListener(func(event pubsub.Event[message.Message]) {
330		program.Send(event)
331	})
332	app.Permissions.AddListener(func(event pubsub.Event[permission.PermissionRequest]) {
333		program.Send(event)
334	})
335	app.Permissions.AddNotificationListener(func(event pubsub.Event[permission.PermissionNotification]) {
336		program.Send(event)
337	})
338	app.History.AddListener(func(event pubsub.Event[history.File]) {
339		program.Send(event)
340	})
341	mcp.AddEventListener(func(event pubsub.Event[mcp.Event]) {
342		program.Send(event)
343	})
344	AddLSPEventListener(func(event pubsub.Event[LSPEvent]) {
345		program.Send(event)
346	})
347}
348
349// Shutdown performs a graceful shutdown of the application.
350func (app *App) Shutdown() {
351	start := time.Now()
352	defer func() { slog.Info("Shutdown took " + time.Since(start).String()) }()
353
354	// First, cancel all agents and wait for them to finish. This must complete
355	// before closing the DB so agents can finish writing their state.
356	if app.AgentCoordinator != nil {
357		app.AgentCoordinator.CancelAll()
358	}
359
360	// Now run remaining cleanup tasks in parallel.
361	var wg sync.WaitGroup
362
363	// Kill all background shells.
364	wg.Go(func() {
365		shell.GetBackgroundShellManager().KillAll()
366	})
367
368	// Shutdown all LSP clients.
369	shutdownCtx, cancel := context.WithTimeout(app.globalCtx, 5*time.Second)
370	defer cancel()
371	for name, client := range app.LSPClients.Seq2() {
372		wg.Go(func() {
373			if err := client.Close(shutdownCtx); err != nil &&
374				!errors.Is(err, io.EOF) &&
375				!errors.Is(err, context.Canceled) &&
376				err.Error() != "signal: killed" {
377				slog.Warn("Failed to shutdown LSP client", "name", name, "error", err)
378			}
379		})
380	}
381
382	// Call all cleanup functions.
383	for _, cleanup := range app.cleanupFuncs {
384		if cleanup != nil {
385			wg.Go(func() {
386				if err := cleanup(); err != nil {
387					slog.Error("Failed to cleanup app properly on shutdown", "error", err)
388				}
389			})
390		}
391	}
392	wg.Wait()
393}
394
395// checkForUpdates checks for available updates.
396func (app *App) checkForUpdates(ctx context.Context) {
397	checkCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
398	defer cancel()
399
400	info, err := update.Check(checkCtx, version.Version, update.Default)
401	if err != nil || !info.Available() {
402		return
403	}
404	if app.program != nil {
405		app.program.Send(pubsub.UpdateAvailableMsg{
406			CurrentVersion: info.Current,
407			LatestVersion:  info.Latest,
408			IsDevelopment:  info.IsDevelopment(),
409		})
410	}
411}