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 "git.secluded.site/crush/internal/agent"
20 "git.secluded.site/crush/internal/agent/tools/mcp"
21 "git.secluded.site/crush/internal/config"
22 "git.secluded.site/crush/internal/csync"
23 "git.secluded.site/crush/internal/db"
24 "git.secluded.site/crush/internal/format"
25 "git.secluded.site/crush/internal/history"
26 "git.secluded.site/crush/internal/log"
27 "git.secluded.site/crush/internal/lsp"
28 "git.secluded.site/crush/internal/message"
29 "git.secluded.site/crush/internal/permission"
30 "git.secluded.site/crush/internal/pubsub"
31 "git.secluded.site/crush/internal/session"
32 "git.secluded.site/crush/internal/shell"
33 "git.secluded.site/crush/internal/term"
34 "git.secluded.site/crush/internal/tui/components/anim"
35 "git.secluded.site/crush/internal/tui/styles"
36 "git.secluded.site/crush/internal/update"
37 "git.secluded.site/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 return app.AgentCoordinator.UpdateModels(ctx)
264}
265
266func (app *App) setupEvents() {
267 ctx, cancel := context.WithCancel(app.globalCtx)
268 app.eventsCtx = ctx
269 setupSubscriber(ctx, app.serviceEventsWG, "sessions", app.Sessions.Subscribe, app.events)
270 setupSubscriber(ctx, app.serviceEventsWG, "messages", app.Messages.Subscribe, app.events)
271 setupSubscriber(ctx, app.serviceEventsWG, "permissions", app.Permissions.Subscribe, app.events)
272 setupSubscriber(ctx, app.serviceEventsWG, "permissions-notifications", app.Permissions.SubscribeNotifications, app.events)
273 setupSubscriber(ctx, app.serviceEventsWG, "history", app.History.Subscribe, app.events)
274 setupSubscriber(ctx, app.serviceEventsWG, "mcp", mcp.SubscribeEvents, app.events)
275 setupSubscriber(ctx, app.serviceEventsWG, "lsp", SubscribeLSPEvents, app.events)
276 cleanupFunc := func() error {
277 cancel()
278 app.serviceEventsWG.Wait()
279 return nil
280 }
281 app.cleanupFuncs = append(app.cleanupFuncs, cleanupFunc)
282}
283
284func setupSubscriber[T any](
285 ctx context.Context,
286 wg *sync.WaitGroup,
287 name string,
288 subscriber func(context.Context) <-chan pubsub.Event[T],
289 outputCh chan<- tea.Msg,
290) {
291 wg.Go(func() {
292 subCh := subscriber(ctx)
293 for {
294 select {
295 case event, ok := <-subCh:
296 if !ok {
297 slog.Debug("subscription channel closed", "name", name)
298 return
299 }
300 var msg tea.Msg = event
301 select {
302 case outputCh <- msg:
303 case <-time.After(2 * time.Second):
304 slog.Warn("message dropped due to slow consumer", "name", name)
305 case <-ctx.Done():
306 slog.Debug("subscription cancelled", "name", name)
307 return
308 }
309 case <-ctx.Done():
310 slog.Debug("subscription cancelled", "name", name)
311 return
312 }
313 }
314 })
315}
316
317func (app *App) InitCoderAgent(ctx context.Context) error {
318 coderAgentCfg := app.config.Agents[config.AgentCoder]
319 if coderAgentCfg.ID == "" {
320 return fmt.Errorf("coder agent configuration is missing")
321 }
322 var err error
323 app.AgentCoordinator, err = agent.NewCoordinator(
324 ctx,
325 app.config,
326 app.Sessions,
327 app.Messages,
328 app.Permissions,
329 app.History,
330 app.LSPClients,
331 )
332 if err != nil {
333 slog.Error("Failed to create coder agent", "err", err)
334 return err
335 }
336 return nil
337}
338
339// Subscribe sends events to the TUI as tea.Msgs.
340func (app *App) Subscribe(program *tea.Program) {
341 defer log.RecoverPanic("app.Subscribe", func() {
342 slog.Info("TUI subscription panic: attempting graceful shutdown")
343 program.Quit()
344 })
345
346 app.tuiWG.Add(1)
347 tuiCtx, tuiCancel := context.WithCancel(app.globalCtx)
348 app.cleanupFuncs = append(app.cleanupFuncs, func() error {
349 slog.Debug("Cancelling TUI message handler")
350 tuiCancel()
351 app.tuiWG.Wait()
352 return nil
353 })
354 defer app.tuiWG.Done()
355
356 for {
357 select {
358 case <-tuiCtx.Done():
359 slog.Debug("TUI message handler shutting down")
360 return
361 case msg, ok := <-app.events:
362 if !ok {
363 slog.Debug("TUI message channel closed")
364 return
365 }
366 program.Send(msg)
367 }
368 }
369}
370
371// Shutdown performs a graceful shutdown of the application.
372func (app *App) Shutdown() {
373 if app.AgentCoordinator != nil {
374 app.AgentCoordinator.CancelAll()
375 }
376
377 // Kill all background shells.
378 shell.GetBackgroundShellManager().KillAll()
379
380 // Shutdown all LSP clients.
381 for name, client := range app.LSPClients.Seq2() {
382 shutdownCtx, cancel := context.WithTimeout(app.globalCtx, 5*time.Second)
383 if err := client.Close(shutdownCtx); err != nil {
384 slog.Error("Failed to shutdown LSP client", "name", name, "error", err)
385 }
386 cancel()
387 }
388
389 // Call call cleanup functions.
390 for _, cleanup := range app.cleanupFuncs {
391 if cleanup != nil {
392 if err := cleanup(); err != nil {
393 slog.Error("Failed to cleanup app properly on shutdown", "error", err)
394 }
395 }
396 }
397}
398
399// checkForUpdates checks for available updates.
400func (app *App) checkForUpdates(ctx context.Context) {
401 checkCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
402 defer cancel()
403
404 info, err := update.Check(checkCtx, version.Version, update.Default)
405 if err != nil || !info.Available() {
406 return
407 }
408 app.events <- pubsub.UpdateAvailableMsg{
409 CurrentVersion: info.Current,
410 LatestVersion: info.Latest,
411 IsDevelopment: info.IsDevelopment(),
412 }
413}