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