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/catwalk/pkg/catwalk"
19 "charm.land/fantasy"
20 "charm.land/lipgloss/v2"
21 "git.secluded.site/crush/internal/agent"
22 "git.secluded.site/crush/internal/agent/tools/mcp"
23 "git.secluded.site/crush/internal/config"
24 "git.secluded.site/crush/internal/csync"
25 "git.secluded.site/crush/internal/db"
26 "git.secluded.site/crush/internal/filetracker"
27 "git.secluded.site/crush/internal/format"
28 "git.secluded.site/crush/internal/history"
29 "git.secluded.site/crush/internal/log"
30 "git.secluded.site/crush/internal/lsp"
31 "git.secluded.site/crush/internal/message"
32 "git.secluded.site/crush/internal/permission"
33 "git.secluded.site/crush/internal/pubsub"
34 "git.secluded.site/crush/internal/session"
35 "git.secluded.site/crush/internal/shell"
36 "git.secluded.site/crush/internal/tui/components/anim"
37 "git.secluded.site/crush/internal/tui/styles"
38 "git.secluded.site/crush/internal/ui/notification"
39 "git.secluded.site/crush/internal/update"
40 "git.secluded.site/crush/internal/version"
41 "github.com/charmbracelet/x/ansi"
42 "github.com/charmbracelet/x/exp/charmtone"
43 "github.com/charmbracelet/x/term"
44)
45
46// UpdateAvailableMsg is sent when a new version is available.
47type UpdateAvailableMsg struct {
48 CurrentVersion string
49 LatestVersion string
50 IsDevelopment bool
51}
52
53type App struct {
54 Sessions session.Service
55 Messages message.Service
56 History history.Service
57 Permissions permission.Service
58 FileTracker filetracker.Service
59
60 AgentCoordinator agent.Coordinator
61
62 LSPClients *csync.Map[string, *lsp.Client]
63
64 config *config.Config
65
66 serviceEventsWG *sync.WaitGroup
67 eventsCtx context.Context
68 events chan tea.Msg
69 tuiWG *sync.WaitGroup
70
71 // global context and cleanup functions
72 globalCtx context.Context
73 cleanupFuncs []func() error
74 notifications chan notification.Notification
75}
76
77// New initializes a new application instance.
78func New(ctx context.Context, conn *sql.DB, cfg *config.Config) (*App, error) {
79 q := db.New(conn)
80 sessions := session.NewService(q, conn)
81 messages := message.NewService(q)
82 files := history.NewService(q, conn)
83 skipPermissionsRequests := cfg.Permissions != nil && cfg.Permissions.SkipRequests
84 var allowedTools []string
85 if cfg.Permissions != nil && cfg.Permissions.AllowedTools != nil {
86 allowedTools = cfg.Permissions.AllowedTools
87 }
88
89 app := &App{
90 Sessions: sessions,
91 Messages: messages,
92 History: files,
93 Permissions: permission.NewPermissionService(cfg.WorkingDir(), skipPermissionsRequests, allowedTools),
94 FileTracker: filetracker.NewService(q),
95 LSPClients: csync.NewMap[string, *lsp.Client](),
96
97 globalCtx: ctx,
98
99 config: cfg,
100
101 events: make(chan tea.Msg, 100),
102 serviceEventsWG: &sync.WaitGroup{},
103 tuiWG: &sync.WaitGroup{},
104 notifications: make(chan notification.Notification, 1),
105 }
106
107 app.setupEvents()
108
109 // Initialize LSP clients in the background.
110 go app.initLSPClients(ctx)
111
112 // Check for updates in the background.
113 go app.checkForUpdates(ctx)
114
115 go func() {
116 slog.Info("Initializing MCP clients")
117 mcp.Initialize(ctx, app.Permissions, cfg)
118 }()
119
120 // cleanup database upon app shutdown
121 app.cleanupFuncs = append(app.cleanupFuncs, conn.Close, mcp.Close)
122
123 // TODO: remove the concept of agent config, most likely.
124 if !cfg.IsConfigured() {
125 slog.Warn("No agent configuration found")
126 return app, nil
127 }
128 if err := app.InitCoderAgent(ctx); err != nil {
129 return nil, fmt.Errorf("failed to initialize coder agent: %w", err)
130 }
131 return app, nil
132}
133
134// Config returns the application configuration.
135func (app *App) Config() *config.Config {
136 return app.config
137}
138
139// Notifications returns the channel for receiving notification requests.
140func (app *App) Notifications() <-chan notification.Notification {
141 return app.notifications
142}
143
144// NotifySink returns a Sink function for publishing notifications.
145func (app *App) NotifySink() notification.Sink {
146 return notification.NewChannelSink(app.notifications)
147}
148
149// RunNonInteractive runs the application in non-interactive mode with the
150// given prompt, printing to stdout.
151func (app *App) RunNonInteractive(ctx context.Context, output io.Writer, prompt, largeModel, smallModel string, hideSpinner bool) error {
152 slog.Info("Running in non-interactive mode")
153
154 ctx, cancel := context.WithCancel(ctx)
155 defer cancel()
156
157 if largeModel != "" || smallModel != "" {
158 if err := app.overrideModelsForNonInteractive(ctx, largeModel, smallModel); err != nil {
159 return fmt.Errorf("failed to override models: %w", err)
160 }
161 }
162
163 var (
164 spinner *format.Spinner
165 stdoutTTY bool
166 stderrTTY bool
167 stdinTTY bool
168 progress bool
169 )
170
171 if f, ok := output.(*os.File); ok {
172 stdoutTTY = term.IsTerminal(f.Fd())
173 }
174 stderrTTY = term.IsTerminal(os.Stderr.Fd())
175 stdinTTY = term.IsTerminal(os.Stdin.Fd())
176 progress = app.config.Options.Progress == nil || *app.config.Options.Progress
177
178 if !hideSpinner && stderrTTY {
179 t := styles.CurrentTheme()
180
181 // Detect background color to set the appropriate color for the
182 // spinner's 'Generating...' text. Without this, that text would be
183 // unreadable in light terminals.
184 hasDarkBG := true
185 if f, ok := output.(*os.File); ok && stdinTTY && stdoutTTY {
186 hasDarkBG = lipgloss.HasDarkBackground(os.Stdin, f)
187 }
188 defaultFG := lipgloss.LightDark(hasDarkBG)(charmtone.Pepper, t.FgBase)
189
190 spinner = format.NewSpinner(ctx, cancel, anim.Settings{
191 Size: 10,
192 Label: "Generating",
193 LabelColor: defaultFG,
194 GradColorA: t.Primary,
195 GradColorB: t.Secondary,
196 CycleColors: true,
197 })
198 spinner.Start()
199 }
200
201 // Helper function to stop spinner once.
202 stopSpinner := func() {
203 if !hideSpinner && spinner != nil {
204 spinner.Stop()
205 spinner = nil
206 }
207 }
208
209 // Wait for MCP initialization to complete before reading MCP tools.
210 if err := mcp.WaitForInit(ctx); err != nil {
211 return fmt.Errorf("failed to wait for MCP initialization: %w", err)
212 }
213
214 // force update of agent models before running so mcp tools are loaded
215 app.AgentCoordinator.UpdateModels(ctx)
216
217 defer stopSpinner()
218
219 const maxPromptLengthForTitle = 100
220 const titlePrefix = "Non-interactive: "
221 var titleSuffix string
222
223 if len(prompt) > maxPromptLengthForTitle {
224 titleSuffix = prompt[:maxPromptLengthForTitle] + "..."
225 } else {
226 titleSuffix = prompt
227 }
228 title := titlePrefix + titleSuffix
229
230 sess, err := app.Sessions.Create(ctx, title)
231 if err != nil {
232 return fmt.Errorf("failed to create session for non-interactive mode: %w", err)
233 }
234 slog.Info("Created session for non-interactive run", "session_id", sess.ID)
235
236 // Automatically approve all permission requests for this non-interactive
237 // session.
238 app.Permissions.AutoApproveSession(sess.ID)
239
240 type response struct {
241 result *fantasy.AgentResult
242 err error
243 }
244 done := make(chan response, 1)
245
246 go func(ctx context.Context, sessionID, prompt string) {
247 result, err := app.AgentCoordinator.Run(ctx, sess.ID, prompt)
248 if err != nil {
249 done <- response{
250 err: fmt.Errorf("failed to start agent processing stream: %w", err),
251 }
252 }
253 done <- response{
254 result: result,
255 }
256 }(ctx, sess.ID, prompt)
257
258 messageEvents := app.Messages.Subscribe(ctx)
259 messageReadBytes := make(map[string]int)
260 var printed bool
261
262 defer func() {
263 if progress && stderrTTY {
264 _, _ = fmt.Fprintf(os.Stderr, ansi.ResetProgressBar)
265 }
266
267 // Always print a newline at the end. If output is a TTY this will
268 // prevent the prompt from overwriting the last line of output.
269 _, _ = fmt.Fprintln(output)
270 }()
271
272 for {
273 if progress && stderrTTY {
274 // HACK: Reinitialize the terminal progress bar on every iteration
275 // so it doesn't get hidden by the terminal due to inactivity.
276 _, _ = fmt.Fprintf(os.Stderr, ansi.SetIndeterminateProgressBar)
277 }
278
279 select {
280 case result := <-done:
281 stopSpinner()
282 if result.err != nil {
283 if errors.Is(result.err, context.Canceled) || errors.Is(result.err, agent.ErrRequestCancelled) {
284 slog.Debug("Non-interactive: agent processing cancelled", "session_id", sess.ID)
285 return nil
286 }
287 return fmt.Errorf("agent processing failed: %w", result.err)
288 }
289 return nil
290
291 case event := <-messageEvents:
292 msg := event.Payload
293 if msg.SessionID == sess.ID && msg.Role == message.Assistant && len(msg.Parts) > 0 {
294 stopSpinner()
295
296 content := msg.Content().String()
297 readBytes := messageReadBytes[msg.ID]
298
299 if len(content) < readBytes {
300 slog.Error("Non-interactive: message content is shorter than read bytes", "message_length", len(content), "read_bytes", readBytes)
301 return fmt.Errorf("message content is shorter than read bytes: %d < %d", len(content), readBytes)
302 }
303
304 part := content[readBytes:]
305 // Trim leading whitespace. Sometimes the LLM includes leading
306 // formatting and intentation, which we don't want here.
307 if readBytes == 0 {
308 part = strings.TrimLeft(part, " \t")
309 }
310 // Ignore initial whitespace-only messages.
311 if printed || strings.TrimSpace(part) != "" {
312 printed = true
313 fmt.Fprint(output, part)
314 }
315 messageReadBytes[msg.ID] = len(content)
316 }
317
318 case <-ctx.Done():
319 stopSpinner()
320 return ctx.Err()
321 }
322 }
323}
324
325func (app *App) UpdateAgentModel(ctx context.Context) error {
326 if app.AgentCoordinator == nil {
327 return fmt.Errorf("agent configuration is missing")
328 }
329 return app.AgentCoordinator.UpdateModels(ctx)
330}
331
332// overrideModelsForNonInteractive parses the model strings and temporarily
333// overrides the model configurations, then rebuilds the agent.
334// Format: "model-name" (searches all providers) or "provider/model-name".
335// Model matching is case-insensitive.
336// If largeModel is provided but smallModel is not, the small model defaults to
337// the provider's default small model.
338func (app *App) overrideModelsForNonInteractive(ctx context.Context, largeModel, smallModel string) error {
339 providers := app.config.Providers.Copy()
340
341 largeMatches, smallMatches, err := findModels(providers, largeModel, smallModel)
342 if err != nil {
343 return err
344 }
345
346 var largeProviderID string
347
348 // Override large model.
349 if largeModel != "" {
350 found, err := validateMatches(largeMatches, largeModel, "large")
351 if err != nil {
352 return err
353 }
354 largeProviderID = found.provider
355 slog.Info("Overriding large model for non-interactive run", "provider", found.provider, "model", found.modelID)
356 app.config.Models[config.SelectedModelTypeLarge] = config.SelectedModel{
357 Provider: found.provider,
358 Model: found.modelID,
359 }
360 }
361
362 // Override small model.
363 switch {
364 case smallModel != "":
365 found, err := validateMatches(smallMatches, smallModel, "small")
366 if err != nil {
367 return err
368 }
369 slog.Info("Overriding small model for non-interactive run", "provider", found.provider, "model", found.modelID)
370 app.config.Models[config.SelectedModelTypeSmall] = config.SelectedModel{
371 Provider: found.provider,
372 Model: found.modelID,
373 }
374
375 case largeModel != "":
376 // No small model specified, but large model was - use provider's default.
377 smallCfg := app.GetDefaultSmallModel(largeProviderID)
378 app.config.Models[config.SelectedModelTypeSmall] = smallCfg
379 }
380
381 return app.AgentCoordinator.UpdateModels(ctx)
382}
383
384// GetDefaultSmallModel returns the default small model for the given
385// provider. Falls back to the large model if no default is found.
386func (app *App) GetDefaultSmallModel(providerID string) config.SelectedModel {
387 cfg := app.config
388 largeModelCfg := cfg.Models[config.SelectedModelTypeLarge]
389
390 // Find the provider in the known providers list to get its default small model.
391 knownProviders, _ := config.Providers(cfg)
392 var knownProvider *catwalk.Provider
393 for _, p := range knownProviders {
394 if string(p.ID) == providerID {
395 knownProvider = &p
396 break
397 }
398 }
399
400 // For unknown/local providers, use the large model as small.
401 if knownProvider == nil {
402 slog.Warn("Using large model as small model for unknown provider", "provider", providerID, "model", largeModelCfg.Model)
403 return largeModelCfg
404 }
405
406 defaultSmallModelID := knownProvider.DefaultSmallModelID
407 model := cfg.GetModel(providerID, defaultSmallModelID)
408 if model == nil {
409 slog.Warn("Default small model not found, using large model", "provider", providerID, "model", largeModelCfg.Model)
410 return largeModelCfg
411 }
412
413 slog.Info("Using provider default small model", "provider", providerID, "model", defaultSmallModelID)
414 return config.SelectedModel{
415 Provider: providerID,
416 Model: defaultSmallModelID,
417 MaxTokens: model.DefaultMaxTokens,
418 ReasoningEffort: model.DefaultReasoningEffort,
419 }
420}
421
422func (app *App) setupEvents() {
423 ctx, cancel := context.WithCancel(app.globalCtx)
424 app.eventsCtx = ctx
425 setupSubscriber(ctx, app.serviceEventsWG, "sessions", app.Sessions.Subscribe, app.events)
426 setupSubscriber(ctx, app.serviceEventsWG, "messages", app.Messages.Subscribe, app.events)
427 setupSubscriber(ctx, app.serviceEventsWG, "permissions", app.Permissions.Subscribe, app.events)
428 setupSubscriber(ctx, app.serviceEventsWG, "permissions-notifications", app.Permissions.SubscribeNotifications, app.events)
429 setupSubscriber(ctx, app.serviceEventsWG, "history", app.History.Subscribe, app.events)
430 setupSubscriber(ctx, app.serviceEventsWG, "mcp", mcp.SubscribeEvents, app.events)
431 setupSubscriber(ctx, app.serviceEventsWG, "lsp", SubscribeLSPEvents, app.events)
432 cleanupFunc := func() error {
433 cancel()
434 app.serviceEventsWG.Wait()
435 return nil
436 }
437 app.cleanupFuncs = append(app.cleanupFuncs, cleanupFunc)
438}
439
440func setupSubscriber[T any](
441 ctx context.Context,
442 wg *sync.WaitGroup,
443 name string,
444 subscriber func(context.Context) <-chan pubsub.Event[T],
445 outputCh chan<- tea.Msg,
446) {
447 wg.Go(func() {
448 subCh := subscriber(ctx)
449 for {
450 select {
451 case event, ok := <-subCh:
452 if !ok {
453 slog.Debug("Subscription channel closed", "name", name)
454 return
455 }
456 var msg tea.Msg = event
457 select {
458 case outputCh <- msg:
459 case <-time.After(2 * time.Second):
460 slog.Debug("Message dropped due to slow consumer", "name", name)
461 case <-ctx.Done():
462 slog.Debug("Subscription cancelled", "name", name)
463 return
464 }
465 case <-ctx.Done():
466 slog.Debug("Subscription cancelled", "name", name)
467 return
468 }
469 }
470 })
471}
472
473func (app *App) InitCoderAgent(ctx context.Context) error {
474 coderAgentCfg := app.config.Agents[config.AgentCoder]
475 if coderAgentCfg.ID == "" {
476 return fmt.Errorf("coder agent configuration is missing")
477 }
478 var err error
479 app.AgentCoordinator, err = agent.NewCoordinator(
480 ctx,
481 app.config,
482 app.Sessions,
483 app.Messages,
484 app.Permissions,
485 app.History,
486 app.FileTracker,
487 app.LSPClients,
488 app.NotifySink(),
489 )
490 if err != nil {
491 slog.Error("Failed to create coder agent", "err", err)
492 return err
493 }
494 return nil
495}
496
497// Subscribe sends events to the TUI as tea.Msgs.
498func (app *App) Subscribe(program *tea.Program) {
499 defer log.RecoverPanic("app.Subscribe", func() {
500 slog.Info("TUI subscription panic: attempting graceful shutdown")
501 program.Quit()
502 })
503
504 app.tuiWG.Add(1)
505 tuiCtx, tuiCancel := context.WithCancel(app.globalCtx)
506 app.cleanupFuncs = append(app.cleanupFuncs, func() error {
507 slog.Debug("Cancelling TUI message handler")
508 tuiCancel()
509 app.tuiWG.Wait()
510 return nil
511 })
512 defer app.tuiWG.Done()
513
514 for {
515 select {
516 case <-tuiCtx.Done():
517 slog.Debug("TUI message handler shutting down")
518 return
519 case msg, ok := <-app.events:
520 if !ok {
521 slog.Debug("TUI message channel closed")
522 return
523 }
524 program.Send(msg)
525 }
526 }
527}
528
529// Shutdown performs a graceful shutdown of the application.
530func (app *App) Shutdown() {
531 start := time.Now()
532 defer func() { slog.Debug("Shutdown took " + time.Since(start).String()) }()
533
534 // First, cancel all agents and wait for them to finish. This must complete
535 // before closing the DB so agents can finish writing their state.
536 if app.AgentCoordinator != nil {
537 app.AgentCoordinator.CancelAll()
538 }
539
540 // Now run remaining cleanup tasks in parallel.
541 var wg sync.WaitGroup
542
543 // Kill all background shells.
544 wg.Go(func() {
545 shell.GetBackgroundShellManager().KillAll()
546 })
547
548 // Shutdown all LSP clients.
549 shutdownCtx, cancel := context.WithTimeout(app.globalCtx, 5*time.Second)
550 defer cancel()
551 for name, client := range app.LSPClients.Seq2() {
552 wg.Go(func() {
553 if err := client.Close(shutdownCtx); err != nil &&
554 !errors.Is(err, io.EOF) &&
555 !errors.Is(err, context.Canceled) &&
556 err.Error() != "signal: killed" {
557 slog.Warn("Failed to shutdown LSP client", "name", name, "error", err)
558 }
559 })
560 }
561
562 // Call all cleanup functions.
563 for _, cleanup := range app.cleanupFuncs {
564 if cleanup != nil {
565 wg.Go(func() {
566 if err := cleanup(); err != nil {
567 slog.Error("Failed to cleanup app properly on shutdown", "error", err)
568 }
569 })
570 }
571 }
572 wg.Wait()
573}
574
575// checkForUpdates checks for available updates.
576func (app *App) checkForUpdates(ctx context.Context) {
577 checkCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
578 defer cancel()
579
580 info, err := update.Check(checkCtx, version.Version, update.Default)
581 if err != nil || !info.Available() {
582 return
583 }
584 app.events <- UpdateAvailableMsg{
585 CurrentVersion: info.Current,
586 LatestVersion: info.Latest,
587 IsDevelopment: info.IsDevelopment(),
588 }
589}