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