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