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