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