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 "github.com/charmbracelet/crush/internal/agent"
22 "github.com/charmbracelet/crush/internal/agent/notify"
23 "github.com/charmbracelet/crush/internal/agent/tools/mcp"
24 "github.com/charmbracelet/crush/internal/config"
25 "github.com/charmbracelet/crush/internal/db"
26 "github.com/charmbracelet/crush/internal/event"
27 "github.com/charmbracelet/crush/internal/filetracker"
28 "github.com/charmbracelet/crush/internal/format"
29 "github.com/charmbracelet/crush/internal/history"
30 "github.com/charmbracelet/crush/internal/log"
31 "github.com/charmbracelet/crush/internal/lsp"
32 "github.com/charmbracelet/crush/internal/message"
33 "github.com/charmbracelet/crush/internal/permission"
34 "github.com/charmbracelet/crush/internal/pubsub"
35 "github.com/charmbracelet/crush/internal/session"
36 "github.com/charmbracelet/crush/internal/shell"
37 "github.com/charmbracelet/crush/internal/skills"
38 "github.com/charmbracelet/crush/internal/ui/anim"
39 "github.com/charmbracelet/crush/internal/ui/styles"
40 "github.com/charmbracelet/crush/internal/update"
41 "github.com/charmbracelet/crush/internal/version"
42 "github.com/charmbracelet/x/ansi"
43 "github.com/charmbracelet/x/exp/charmtone"
44 "github.com/charmbracelet/x/term"
45)
46
47// UpdateAvailableMsg is sent when a new version is available.
48type UpdateAvailableMsg struct {
49 CurrentVersion string
50 LatestVersion string
51 IsDevelopment bool
52}
53
54type App struct {
55 Sessions session.Service
56 Messages message.Service
57 History history.Service
58 Permissions permission.Service
59 FileTracker filetracker.Service
60
61 AgentCoordinator agent.Coordinator
62
63 LSPManager *lsp.Manager
64
65 Skills *skills.Manager
66
67 config *config.ConfigStore
68
69 serviceEventsWG *sync.WaitGroup
70 eventsCtx context.Context
71 events *pubsub.Broker[tea.Msg]
72 tuiWG *sync.WaitGroup
73
74 // global context and cleanup functions
75 globalCtx context.Context
76 cleanupFuncs []func(context.Context) error
77 agentNotifications *pubsub.Broker[notify.Notification]
78 // runCompletions is the authoritative per-run completion signal,
79 // emitted once per top-level agent turn after all message
80 // updates have been flushed. Bridged into app.events so SSE
81 // subscribers (notably `crush run` in client/server mode) can
82 // drive their exit on a deterministic, payload-bearing event
83 // instead of guessing from message finish parts.
84 runCompletions *pubsub.Broker[notify.RunComplete]
85}
86
87// New initializes a new application instance. skillsMgr carries the
88// per-workspace skill discovery results computed by the caller; the
89// caller is responsible for constructing it (typically via
90// skills.NewManager + skills.DiscoverFromConfig).
91func New(ctx context.Context, conn *sql.DB, store *config.ConfigStore, skillsMgr *skills.Manager) (*App, error) {
92 q := db.New(conn)
93 sessions := session.NewService(q, conn)
94 messages := message.NewService(q)
95 files := history.NewService(q, conn)
96 cfg := store.Config()
97 skipPermissionsRequests := store.Overrides().SkipPermissionRequests
98 var allowedTools []string
99 if cfg.Permissions != nil && cfg.Permissions.AllowedTools != nil {
100 allowedTools = cfg.Permissions.AllowedTools
101 }
102
103 app := &App{
104 Sessions: sessions,
105 Messages: messages,
106 History: files,
107 Permissions: permission.NewPermissionService(store.WorkingDir(), skipPermissionsRequests, allowedTools),
108 FileTracker: filetracker.NewService(q),
109 LSPManager: lsp.NewManager(store),
110 Skills: skillsMgr,
111
112 globalCtx: ctx,
113
114 config: store,
115
116 events: pubsub.NewBroker[tea.Msg](),
117 serviceEventsWG: &sync.WaitGroup{},
118 tuiWG: &sync.WaitGroup{},
119 agentNotifications: pubsub.NewBroker[notify.Notification](),
120 runCompletions: pubsub.NewBroker[notify.RunComplete](),
121 }
122
123 app.setupEvents()
124
125 // Check for updates in the background.
126 go app.checkForUpdates(ctx)
127
128 go mcp.Initialize(ctx, app.Permissions, store)
129
130 // Release the shared database connection on shutdown. The pool
131 // closes the underlying *sql.DB when the last reference is released.
132 dataDir := cfg.Options.DataDirectory
133 app.cleanupFuncs = append(
134 app.cleanupFuncs,
135 func(context.Context) error { return db.Release(dataDir) },
136 func(ctx context.Context) error { return mcp.Close(ctx) },
137 )
138
139 // TODO: remove the concept of agent config, most likely.
140 if !cfg.IsConfigured() {
141 slog.Warn("No agent configuration found")
142 return app, nil
143 }
144 if err := app.InitCoderAgent(ctx); err != nil {
145 return nil, fmt.Errorf("failed to initialize coder agent: %w", err)
146 }
147
148 // Set up callback for LSP state updates.
149 app.LSPManager.SetCallback(func(name string, client *lsp.Client) {
150 if client == nil {
151 updateLSPState(name, lsp.StateUnstarted, nil, nil, 0)
152 return
153 }
154 client.SetDiagnosticsCallback(updateLSPDiagnostics)
155 updateLSPState(name, client.GetServerState(), nil, client, 0)
156 })
157 go app.LSPManager.TrackConfigured()
158
159 return app, nil
160}
161
162// Config returns the pure-data configuration.
163func (app *App) Config() *config.Config {
164 return app.config.Config()
165}
166
167// Store returns the config store.
168func (app *App) Store() *config.ConfigStore {
169 return app.config
170}
171
172// Events returns a per-caller subscription channel for application events.
173// Each caller receives its own channel; all callers receive every event.
174func (app *App) Events(ctx context.Context) <-chan pubsub.Event[tea.Msg] {
175 return app.events.Subscribe(ctx)
176}
177
178// SendEvent publishes a message to all event subscribers.
179func (app *App) SendEvent(msg tea.Msg) {
180 app.events.Publish(pubsub.UpdatedEvent, msg)
181}
182
183// AgentNotifications returns the broker for agent notification events.
184func (app *App) AgentNotifications() *pubsub.Broker[notify.Notification] {
185 return app.agentNotifications
186}
187
188// RunCompletions returns the broker for the authoritative per-run
189// terminal RunComplete events. The dispatcher (backend.runAgent) uses
190// it to emit a reliable terminal event when a run fails before the
191// coordinator could publish one of its own.
192func (app *App) RunCompletions() *pubsub.Broker[notify.RunComplete] {
193 return app.runCompletions
194}
195
196// resolveSession resolves which session to use for a non-interactive run
197// If continueSessionID is set, it looks up that session by ID
198// If useLast is set, it returns the most recently updated top-level session
199// Otherwise, it creates a new session
200func (app *App) resolveSession(ctx context.Context, continueSessionID string, useLast bool) (session.Session, error) {
201 switch {
202 case continueSessionID != "":
203 if app.Sessions.IsAgentToolSession(continueSessionID) {
204 return session.Session{}, fmt.Errorf("cannot continue an agent tool session: %s", continueSessionID)
205 }
206 sess, err := app.Sessions.Get(ctx, continueSessionID)
207 if err != nil {
208 return session.Session{}, fmt.Errorf("session not found: %s", continueSessionID)
209 }
210 if sess.ParentSessionID != "" {
211 return session.Session{}, fmt.Errorf("cannot continue a child session: %s", continueSessionID)
212 }
213 return sess, nil
214
215 case useLast:
216 sess, err := app.Sessions.GetLast(ctx)
217 if err != nil {
218 return session.Session{}, fmt.Errorf("no sessions found to continue")
219 }
220 return sess, nil
221
222 default:
223 return app.Sessions.Create(ctx, agent.DefaultSessionName)
224 }
225}
226
227// RunNonInteractive runs the application in non-interactive mode with the
228// given prompt, printing to stdout.
229func (app *App) RunNonInteractive(ctx context.Context, output io.Writer, prompt, largeModel, smallModel string, hideSpinner bool, continueSessionID string, useLast bool) error {
230 slog.Info("Running in non-interactive mode")
231
232 ctx, cancel := context.WithCancel(ctx)
233 defer cancel()
234
235 if largeModel != "" || smallModel != "" {
236 if err := app.overrideModelsForNonInteractive(ctx, largeModel, smallModel); err != nil {
237 return fmt.Errorf("failed to override models: %w", err)
238 }
239 }
240
241 var (
242 spinner *format.Spinner
243 stdoutTTY bool
244 stderrTTY bool
245 stdinTTY bool
246 progress bool
247 )
248
249 if f, ok := output.(*os.File); ok {
250 stdoutTTY = term.IsTerminal(f.Fd())
251 }
252 stderrTTY = term.IsTerminal(os.Stderr.Fd())
253 stdinTTY = term.IsTerminal(os.Stdin.Fd())
254 progress = app.config.Config().Options.Progress == nil || *app.config.Config().Options.Progress
255
256 if !hideSpinner && stderrTTY {
257 t := styles.ThemeForProvider(app.config.Config().Models[config.SelectedModelTypeLarge].Provider)
258
259 // Detect background color to set the appropriate color for the
260 // spinner's 'Generating...' text. Without this, that text would be
261 // unreadable in light terminals.
262 hasDarkBG := true
263 if f, ok := output.(*os.File); ok && stdinTTY && stdoutTTY {
264 hasDarkBG = lipgloss.HasDarkBackground(os.Stdin, f)
265 }
266 defaultFG := lipgloss.LightDark(hasDarkBG)(charmtone.Pepper, t.WorkingLabelColor)
267
268 spinner = format.NewSpinner(ctx, cancel, anim.Settings{
269 Size: 10,
270 Label: "Generating",
271 LabelColor: defaultFG,
272 GradColorA: t.WorkingGradFromColor,
273 GradColorB: t.WorkingGradToColor,
274 CycleColors: true,
275 })
276 spinner.Start()
277 }
278
279 // Helper function to stop spinner once.
280 stopSpinner := func() {
281 if !hideSpinner && spinner != nil {
282 spinner.Stop()
283 spinner = nil
284 }
285 }
286
287 // Wait for MCP initialization to complete before reading MCP tools.
288 if err := mcp.WaitForInit(ctx); err != nil {
289 return fmt.Errorf("failed to wait for MCP initialization: %w", err)
290 }
291
292 // force update of agent models before running so mcp tools are loaded
293 app.AgentCoordinator.UpdateModels(ctx)
294
295 defer stopSpinner()
296
297 sess, err := app.resolveSession(ctx, continueSessionID, useLast)
298 if err != nil {
299 return fmt.Errorf("failed to create session for non-interactive mode: %w", err)
300 }
301
302 if continueSessionID != "" || useLast {
303 slog.Info("Continuing session for non-interactive run", "session_id", sess.ID)
304 } else {
305 slog.Info("Created session for non-interactive run", "session_id", sess.ID)
306 }
307
308 // Automatically approve all permission requests for this non-interactive
309 // session.
310 app.Permissions.AutoApproveSession(sess.ID)
311
312 type response struct {
313 result *fantasy.AgentResult
314 err error
315 }
316 done := make(chan response, 1)
317
318 go func(ctx context.Context, sessionID, prompt string) {
319 result, err := app.AgentCoordinator.Run(ctx, sess.ID, prompt)
320 if err != nil {
321 done <- response{
322 err: fmt.Errorf("failed to start agent processing stream: %w", err),
323 }
324 return
325 }
326 done <- response{
327 result: result,
328 }
329 }(ctx, sess.ID, prompt)
330
331 messageEvents := app.Messages.Subscribe(ctx)
332 messageReadBytes := make(map[string]int)
333 var printed bool
334
335 defer func() {
336 if progress && stderrTTY {
337 _, _ = fmt.Fprintf(os.Stderr, ansi.ResetProgressBar)
338 }
339
340 // Always print a newline at the end. If output is a TTY this will
341 // prevent the prompt from overwriting the last line of output.
342 _, _ = fmt.Fprintln(output)
343 }()
344
345 for {
346 if progress && stderrTTY {
347 // HACK: Reinitialize the terminal progress bar on every iteration
348 // so it doesn't get hidden by the terminal due to inactivity.
349 _, _ = fmt.Fprintf(os.Stderr, ansi.SetIndeterminateProgressBar)
350 }
351
352 select {
353 case result := <-done:
354 stopSpinner()
355 if result.err != nil {
356 if errors.Is(result.err, context.Canceled) || errors.Is(result.err, agent.ErrRequestCancelled) {
357 slog.Debug("Non-interactive: agent processing cancelled", "session_id", sess.ID)
358 return nil
359 }
360 return fmt.Errorf("agent processing failed: %w", result.err)
361 }
362 return nil
363
364 case event := <-messageEvents:
365 msg := event.Payload
366 if msg.SessionID == sess.ID && msg.Role == message.Assistant && len(msg.Parts) > 0 {
367 stopSpinner()
368
369 content := msg.Content().String()
370 readBytes := messageReadBytes[msg.ID]
371
372 if len(content) < readBytes {
373 slog.Error("Non-interactive: message content is shorter than read bytes", "message_length", len(content), "read_bytes", readBytes)
374 return fmt.Errorf("message content is shorter than read bytes: %d < %d", len(content), readBytes)
375 }
376
377 part := content[readBytes:]
378 // Trim leading whitespace. Sometimes the LLM includes leading
379 // formatting and intentation, which we don't want here.
380 if readBytes == 0 {
381 part = strings.TrimLeft(part, " \t")
382 }
383 // Ignore initial whitespace-only messages.
384 if printed || strings.TrimSpace(part) != "" {
385 printed = true
386 fmt.Fprint(output, part)
387 }
388 messageReadBytes[msg.ID] = len(content)
389 }
390
391 case <-ctx.Done():
392 stopSpinner()
393 return ctx.Err()
394 }
395 }
396}
397
398func (app *App) UpdateAgentModel(ctx context.Context) error {
399 if app.AgentCoordinator == nil {
400 return fmt.Errorf("agent configuration is missing")
401 }
402 return app.AgentCoordinator.UpdateModels(ctx)
403}
404
405// overrideModelsForNonInteractive parses the model strings and temporarily
406// overrides the model configurations, then rebuilds the agent.
407// Format: "model-name" (searches all providers) or "provider/model-name".
408// Model matching is case-insensitive.
409// If largeModel is provided but smallModel is not, the small model defaults to
410// the provider's default small model.
411func (app *App) overrideModelsForNonInteractive(ctx context.Context, largeModel, smallModel string) error {
412 providers := app.config.Config().Providers.Copy()
413
414 largeMatches, smallMatches, err := findModels(providers, largeModel, smallModel)
415 if err != nil {
416 return err
417 }
418
419 var largeProviderID string
420
421 // Override large model.
422 if largeModel != "" {
423 found, err := validateMatches(largeMatches, largeModel, "large")
424 if err != nil {
425 return err
426 }
427 largeProviderID = found.provider
428 slog.Info("Overriding large model for non-interactive run", "provider", found.provider, "model", found.modelID)
429 app.config.Config().Models[config.SelectedModelTypeLarge] = config.SelectedModel{
430 Provider: found.provider,
431 Model: found.modelID,
432 }
433 }
434
435 // Override small model.
436 switch {
437 case smallModel != "":
438 found, err := validateMatches(smallMatches, smallModel, "small")
439 if err != nil {
440 return err
441 }
442 slog.Info("Overriding small model for non-interactive run", "provider", found.provider, "model", found.modelID)
443 app.config.Config().Models[config.SelectedModelTypeSmall] = config.SelectedModel{
444 Provider: found.provider,
445 Model: found.modelID,
446 }
447
448 case largeModel != "":
449 // No small model specified, but large model was - use provider's default.
450 smallCfg := app.GetDefaultSmallModel(largeProviderID)
451 app.config.Config().Models[config.SelectedModelTypeSmall] = smallCfg
452 }
453
454 return app.AgentCoordinator.UpdateModels(ctx)
455}
456
457// GetDefaultSmallModel returns the default small model for the given
458// provider. Falls back to the large model if no default is found.
459func (app *App) GetDefaultSmallModel(providerID string) config.SelectedModel {
460 cfg := app.config.Config()
461 largeModelCfg := cfg.Models[config.SelectedModelTypeLarge]
462
463 // Find the provider in the known providers list to get its default small model.
464 knownProviders, _ := config.Providers(cfg)
465 var knownProvider *catwalk.Provider
466 for _, p := range knownProviders {
467 if string(p.ID) == providerID {
468 knownProvider = &p
469 break
470 }
471 }
472
473 // For unknown/local providers, use the large model as small.
474 if knownProvider == nil {
475 slog.Warn("Using large model as small model for unknown provider", "provider", providerID, "model", largeModelCfg.Model)
476 return largeModelCfg
477 }
478
479 defaultSmallModelID := knownProvider.DefaultSmallModelID
480 model := cfg.GetModel(providerID, defaultSmallModelID)
481 if model == nil {
482 slog.Warn("Default small model not found, using large model", "provider", providerID, "model", largeModelCfg.Model)
483 return largeModelCfg
484 }
485
486 slog.Info("Using provider default small model", "provider", providerID, "model", defaultSmallModelID)
487 return config.SelectedModel{
488 Provider: providerID,
489 Model: defaultSmallModelID,
490 MaxTokens: model.DefaultMaxTokens,
491 ReasoningEffort: model.DefaultReasoningEffort,
492 }
493}
494
495func (app *App) setupEvents() {
496 ctx, cancel := context.WithCancel(app.globalCtx)
497 app.eventsCtx = ctx
498 setupSubscriber(ctx, app.serviceEventsWG, "sessions", app.Sessions.Subscribe, app.events)
499 setupSubscriber(ctx, app.serviceEventsWG, "messages", app.Messages.Subscribe, app.events)
500 setupSubscriber(ctx, app.serviceEventsWG, "permissions", app.Permissions.Subscribe, app.events)
501 setupSubscriber(ctx, app.serviceEventsWG, "permissions-notifications", app.Permissions.SubscribeNotifications, app.events)
502 setupSubscriber(ctx, app.serviceEventsWG, "history", app.History.Subscribe, app.events)
503 setupSubscriber(ctx, app.serviceEventsWG, "agent-notifications", app.agentNotifications.Subscribe, app.events)
504 setupSubscriberMustDeliver(ctx, app.serviceEventsWG, "run-completions", app.runCompletions.Subscribe, app.events)
505 setupSubscriber(ctx, app.serviceEventsWG, "mcp", mcp.SubscribeEvents, app.events)
506 setupSubscriber(ctx, app.serviceEventsWG, "lsp", SubscribeLSPEvents, app.events)
507 if app.Skills != nil {
508 setupSubscriber(ctx, app.serviceEventsWG, "skills", app.Skills.SubscribeEvents, app.events)
509 }
510 cleanupFunc := func(context.Context) error {
511 cancel()
512 app.serviceEventsWG.Wait()
513 app.events.Shutdown()
514 return nil
515 }
516 app.cleanupFuncs = append(app.cleanupFuncs, cleanupFunc)
517}
518
519func setupSubscriber[T any](
520 ctx context.Context,
521 wg *sync.WaitGroup,
522 name string,
523 subscriber func(context.Context) <-chan pubsub.Event[T],
524 broker *pubsub.Broker[tea.Msg],
525) {
526 wg.Go(func() {
527 subCh := subscriber(ctx)
528 for {
529 select {
530 case event, ok := <-subCh:
531 if !ok {
532 slog.Debug("Subscription channel closed", "name", name)
533 return
534 }
535 broker.Publish(pubsub.UpdatedEvent, tea.Msg(event))
536 case <-ctx.Done():
537 slog.Debug("Subscription cancelled", "name", name)
538 return
539 }
540 }
541 })
542}
543
544// setupSubscriberMustDeliver is the bounded-blocking fan-in variant of
545// setupSubscriber: it re-publishes upstream events onto the shared
546// app.events broker using PublishMustDeliver instead of Publish. Use
547// this for terminal events that subscribers cannot tolerate losing —
548// notably RunComplete, which is the authoritative end-of-run signal
549// for `crush run`. A lossy fan-in here can drop the only terminal
550// event and hang non-interactive clients waiting on it.
551func setupSubscriberMustDeliver[T any](
552 ctx context.Context,
553 wg *sync.WaitGroup,
554 name string,
555 subscriber func(context.Context) <-chan pubsub.Event[T],
556 broker *pubsub.Broker[tea.Msg],
557) {
558 wg.Go(func() {
559 subCh := subscriber(ctx)
560 for {
561 select {
562 case event, ok := <-subCh:
563 if !ok {
564 slog.Debug("Subscription channel closed", "name", name)
565 return
566 }
567 broker.PublishMustDeliver(ctx, pubsub.UpdatedEvent, tea.Msg(event))
568 case <-ctx.Done():
569 slog.Debug("Subscription cancelled", "name", name)
570 return
571 }
572 }
573 })
574}
575
576func (app *App) InitCoderAgent(ctx context.Context) error {
577 coderAgentCfg := app.config.Config().Agents[config.AgentCoder]
578 if coderAgentCfg.ID == "" {
579 return fmt.Errorf("coder agent configuration is missing")
580 }
581 var err error
582 app.AgentCoordinator, err = agent.NewCoordinator(
583 ctx,
584 app.config,
585 app.Sessions,
586 app.Messages,
587 app.Permissions,
588 app.History,
589 app.FileTracker,
590 app.LSPManager,
591 app.agentNotifications,
592 app.runCompletions,
593 app.Skills,
594 )
595 if err != nil {
596 slog.Error("Failed to create coder agent", "err", err)
597 return err
598 }
599 return nil
600}
601
602// Subscribe sends events to the TUI as tea.Msgs.
603func (app *App) Subscribe(program *tea.Program) {
604 defer log.RecoverPanic("app.Subscribe", func() {
605 slog.Info("TUI subscription panic: attempting graceful shutdown")
606 program.Quit()
607 })
608
609 app.tuiWG.Add(1)
610 tuiCtx, tuiCancel := context.WithCancel(app.globalCtx)
611 app.cleanupFuncs = append(app.cleanupFuncs, func(context.Context) error {
612 slog.Debug("Cancelling TUI message handler")
613 tuiCancel()
614 app.tuiWG.Wait()
615 return nil
616 })
617 defer app.tuiWG.Done()
618
619 events := app.events.Subscribe(tuiCtx)
620 for {
621 select {
622 case <-tuiCtx.Done():
623 slog.Debug("TUI message handler shutting down")
624 return
625 case ev, ok := <-events:
626 if !ok {
627 slog.Debug("TUI message channel closed")
628 return
629 }
630 program.Send(ev.Payload)
631 }
632 }
633}
634
635// Shutdown performs a graceful shutdown of the application.
636func (app *App) Shutdown() {
637 start := time.Now()
638 defer func() { slog.Debug("Shutdown took " + time.Since(start).String()) }()
639
640 // First, cancel all agents and wait for them to finish. This must complete
641 // before closing the DB so agents can finish writing their state.
642 if app.AgentCoordinator != nil {
643 app.AgentCoordinator.CancelAll()
644 }
645
646 // Shared shutdown context for all timeout-bounded cleanup.
647 shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
648 defer cancel()
649
650 // Drain any debounced message updates before the DB-close cleanup
651 // runs in the parallel block below. message.Service buffers
652 // streaming deltas (see internal/message/message.go) and we must
653 // land them while the connection is still open.
654 if app.Messages != nil {
655 if err := app.Messages.FlushAll(shutdownCtx); err != nil {
656 slog.Error("Failed to flush pending message updates on shutdown", "error", err)
657 }
658 }
659
660 // Now run remaining cleanup tasks in parallel.
661 var wg sync.WaitGroup
662
663 // Send exit event
664 wg.Go(func() {
665 event.AppExited()
666 })
667
668 // Kill all background shells.
669 wg.Go(func() {
670 shell.GetBackgroundShellManager().KillAll(shutdownCtx)
671 })
672
673 // Shutdown all LSP clients.
674 wg.Go(func() {
675 app.LSPManager.KillAll(shutdownCtx)
676 })
677
678 // Call all cleanup functions.
679 for _, cleanup := range app.cleanupFuncs {
680 if cleanup != nil {
681 wg.Go(func() {
682 if err := cleanup(shutdownCtx); err != nil {
683 slog.Error("Failed to cleanup app properly on shutdown", "error", err)
684 }
685 })
686 }
687 }
688 wg.Wait()
689}
690
691// checkForUpdates checks for available updates.
692func (app *App) checkForUpdates(ctx context.Context) {
693 checkCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
694 defer cancel()
695
696 info, err := update.Check(checkCtx, version.Version, update.Default)
697 if err != nil || !info.Available() {
698 return
699 }
700 app.events.Publish(pubsub.UpdatedEvent, UpdateAvailableMsg{
701 CurrentVersion: info.Current,
702 LatestVersion: info.Latest,
703 IsDevelopment: info.IsDevelopment(),
704 })
705}