app.go

  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// resolveSession resolves which session to use for a non-interactive run
189// If continueSessionID is set, it looks up that session by ID
190// If useLast is set, it returns the most recently updated top-level session
191// Otherwise, it creates a new session
192func (app *App) resolveSession(ctx context.Context, continueSessionID string, useLast bool) (session.Session, error) {
193	switch {
194	case continueSessionID != "":
195		if app.Sessions.IsAgentToolSession(continueSessionID) {
196			return session.Session{}, fmt.Errorf("cannot continue an agent tool session: %s", continueSessionID)
197		}
198		sess, err := app.Sessions.Get(ctx, continueSessionID)
199		if err != nil {
200			return session.Session{}, fmt.Errorf("session not found: %s", continueSessionID)
201		}
202		if sess.ParentSessionID != "" {
203			return session.Session{}, fmt.Errorf("cannot continue a child session: %s", continueSessionID)
204		}
205		return sess, nil
206
207	case useLast:
208		sess, err := app.Sessions.GetLast(ctx)
209		if err != nil {
210			return session.Session{}, fmt.Errorf("no sessions found to continue")
211		}
212		return sess, nil
213
214	default:
215		return app.Sessions.Create(ctx, agent.DefaultSessionName)
216	}
217}
218
219// RunNonInteractive runs the application in non-interactive mode with the
220// given prompt, printing to stdout.
221func (app *App) RunNonInteractive(ctx context.Context, output io.Writer, prompt, largeModel, smallModel string, hideSpinner bool, continueSessionID string, useLast bool) error {
222	slog.Info("Running in non-interactive mode")
223
224	ctx, cancel := context.WithCancel(ctx)
225	defer cancel()
226
227	if largeModel != "" || smallModel != "" {
228		if err := app.overrideModelsForNonInteractive(ctx, largeModel, smallModel); err != nil {
229			return fmt.Errorf("failed to override models: %w", err)
230		}
231	}
232
233	var (
234		spinner   *format.Spinner
235		stdoutTTY bool
236		stderrTTY bool
237		stdinTTY  bool
238		progress  bool
239	)
240
241	if f, ok := output.(*os.File); ok {
242		stdoutTTY = term.IsTerminal(f.Fd())
243	}
244	stderrTTY = term.IsTerminal(os.Stderr.Fd())
245	stdinTTY = term.IsTerminal(os.Stdin.Fd())
246	progress = app.config.Config().Options.Progress == nil || *app.config.Config().Options.Progress
247
248	if !hideSpinner && stderrTTY {
249		t := styles.ThemeForProvider(app.config.Config().Models[config.SelectedModelTypeLarge].Provider)
250
251		// Detect background color to set the appropriate color for the
252		// spinner's 'Generating...' text. Without this, that text would be
253		// unreadable in light terminals.
254		hasDarkBG := true
255		if f, ok := output.(*os.File); ok && stdinTTY && stdoutTTY {
256			hasDarkBG = lipgloss.HasDarkBackground(os.Stdin, f)
257		}
258		defaultFG := lipgloss.LightDark(hasDarkBG)(charmtone.Pepper, t.WorkingLabelColor)
259
260		spinner = format.NewSpinner(ctx, cancel, anim.Settings{
261			Size:        10,
262			Label:       "Generating",
263			LabelColor:  defaultFG,
264			GradColorA:  t.WorkingGradFromColor,
265			GradColorB:  t.WorkingGradToColor,
266			CycleColors: true,
267		})
268		spinner.Start()
269	}
270
271	// Helper function to stop spinner once.
272	stopSpinner := func() {
273		if !hideSpinner && spinner != nil {
274			spinner.Stop()
275			spinner = nil
276		}
277	}
278
279	// Wait for MCP initialization to complete before reading MCP tools.
280	if err := mcp.WaitForInit(ctx); err != nil {
281		return fmt.Errorf("failed to wait for MCP initialization: %w", err)
282	}
283
284	// force update of agent models before running so mcp tools are loaded
285	app.AgentCoordinator.UpdateModels(ctx)
286
287	defer stopSpinner()
288
289	sess, err := app.resolveSession(ctx, continueSessionID, useLast)
290	if err != nil {
291		return fmt.Errorf("failed to create session for non-interactive mode: %w", err)
292	}
293
294	if continueSessionID != "" || useLast {
295		slog.Info("Continuing session for non-interactive run", "session_id", sess.ID)
296	} else {
297		slog.Info("Created session for non-interactive run", "session_id", sess.ID)
298	}
299
300	// Automatically approve all permission requests for this non-interactive
301	// session.
302	app.Permissions.AutoApproveSession(sess.ID)
303
304	type response struct {
305		result *fantasy.AgentResult
306		err    error
307	}
308	done := make(chan response, 1)
309
310	go func(ctx context.Context, sessionID, prompt string) {
311		result, err := app.AgentCoordinator.Run(ctx, sess.ID, prompt)
312		if err != nil {
313			done <- response{
314				err: fmt.Errorf("failed to start agent processing stream: %w", err),
315			}
316			return
317		}
318		done <- response{
319			result: result,
320		}
321	}(ctx, sess.ID, prompt)
322
323	messageEvents := app.Messages.Subscribe(ctx)
324	messageReadBytes := make(map[string]int)
325	var printed bool
326
327	defer func() {
328		if progress && stderrTTY {
329			_, _ = fmt.Fprintf(os.Stderr, ansi.ResetProgressBar)
330		}
331
332		// Always print a newline at the end. If output is a TTY this will
333		// prevent the prompt from overwriting the last line of output.
334		_, _ = fmt.Fprintln(output)
335	}()
336
337	for {
338		if progress && stderrTTY {
339			// HACK: Reinitialize the terminal progress bar on every iteration
340			// so it doesn't get hidden by the terminal due to inactivity.
341			_, _ = fmt.Fprintf(os.Stderr, ansi.SetIndeterminateProgressBar)
342		}
343
344		select {
345		case result := <-done:
346			stopSpinner()
347			if result.err != nil {
348				if errors.Is(result.err, context.Canceled) || errors.Is(result.err, agent.ErrRequestCancelled) {
349					slog.Debug("Non-interactive: agent processing cancelled", "session_id", sess.ID)
350					return nil
351				}
352				return fmt.Errorf("agent processing failed: %w", result.err)
353			}
354			return nil
355
356		case event := <-messageEvents:
357			msg := event.Payload
358			if msg.SessionID == sess.ID && msg.Role == message.Assistant && len(msg.Parts) > 0 {
359				stopSpinner()
360
361				content := msg.Content().String()
362				readBytes := messageReadBytes[msg.ID]
363
364				if len(content) < readBytes {
365					slog.Error("Non-interactive: message content is shorter than read bytes", "message_length", len(content), "read_bytes", readBytes)
366					return fmt.Errorf("message content is shorter than read bytes: %d < %d", len(content), readBytes)
367				}
368
369				part := content[readBytes:]
370				// Trim leading whitespace. Sometimes the LLM includes leading
371				// formatting and intentation, which we don't want here.
372				if readBytes == 0 {
373					part = strings.TrimLeft(part, " \t")
374				}
375				// Ignore initial whitespace-only messages.
376				if printed || strings.TrimSpace(part) != "" {
377					printed = true
378					fmt.Fprint(output, part)
379				}
380				messageReadBytes[msg.ID] = len(content)
381			}
382
383		case <-ctx.Done():
384			stopSpinner()
385			return ctx.Err()
386		}
387	}
388}
389
390func (app *App) UpdateAgentModel(ctx context.Context) error {
391	if app.AgentCoordinator == nil {
392		return fmt.Errorf("agent configuration is missing")
393	}
394	return app.AgentCoordinator.UpdateModels(ctx)
395}
396
397// overrideModelsForNonInteractive parses the model strings and temporarily
398// overrides the model configurations, then rebuilds the agent.
399// Format: "model-name" (searches all providers) or "provider/model-name".
400// Model matching is case-insensitive.
401// If largeModel is provided but smallModel is not, the small model defaults to
402// the provider's default small model.
403func (app *App) overrideModelsForNonInteractive(ctx context.Context, largeModel, smallModel string) error {
404	providers := app.config.Config().Providers.Copy()
405
406	largeMatches, smallMatches, err := findModels(providers, largeModel, smallModel)
407	if err != nil {
408		return err
409	}
410
411	var largeProviderID string
412
413	// Override large model.
414	if largeModel != "" {
415		found, err := validateMatches(largeMatches, largeModel, "large")
416		if err != nil {
417			return err
418		}
419		largeProviderID = found.provider
420		slog.Info("Overriding large model for non-interactive run", "provider", found.provider, "model", found.modelID)
421		app.config.Config().Models[config.SelectedModelTypeLarge] = config.SelectedModel{
422			Provider: found.provider,
423			Model:    found.modelID,
424		}
425	}
426
427	// Override small model.
428	switch {
429	case smallModel != "":
430		found, err := validateMatches(smallMatches, smallModel, "small")
431		if err != nil {
432			return err
433		}
434		slog.Info("Overriding small model for non-interactive run", "provider", found.provider, "model", found.modelID)
435		app.config.Config().Models[config.SelectedModelTypeSmall] = config.SelectedModel{
436			Provider: found.provider,
437			Model:    found.modelID,
438		}
439
440	case largeModel != "":
441		// No small model specified, but large model was - use provider's default.
442		smallCfg := app.GetDefaultSmallModel(largeProviderID)
443		app.config.Config().Models[config.SelectedModelTypeSmall] = smallCfg
444	}
445
446	return app.AgentCoordinator.UpdateModels(ctx)
447}
448
449// GetDefaultSmallModel returns the default small model for the given
450// provider. Falls back to the large model if no default is found.
451func (app *App) GetDefaultSmallModel(providerID string) config.SelectedModel {
452	cfg := app.config.Config()
453	largeModelCfg := cfg.Models[config.SelectedModelTypeLarge]
454
455	// Find the provider in the known providers list to get its default small model.
456	knownProviders, _ := config.Providers(cfg)
457	var knownProvider *catwalk.Provider
458	for _, p := range knownProviders {
459		if string(p.ID) == providerID {
460			knownProvider = &p
461			break
462		}
463	}
464
465	// For unknown/local providers, use the large model as small.
466	if knownProvider == nil {
467		slog.Warn("Using large model as small model for unknown provider", "provider", providerID, "model", largeModelCfg.Model)
468		return largeModelCfg
469	}
470
471	defaultSmallModelID := knownProvider.DefaultSmallModelID
472	model := cfg.GetModel(providerID, defaultSmallModelID)
473	if model == nil {
474		slog.Warn("Default small model not found, using large model", "provider", providerID, "model", largeModelCfg.Model)
475		return largeModelCfg
476	}
477
478	slog.Info("Using provider default small model", "provider", providerID, "model", defaultSmallModelID)
479	return config.SelectedModel{
480		Provider:        providerID,
481		Model:           defaultSmallModelID,
482		MaxTokens:       model.DefaultMaxTokens,
483		ReasoningEffort: model.DefaultReasoningEffort,
484	}
485}
486
487func (app *App) setupEvents() {
488	ctx, cancel := context.WithCancel(app.globalCtx)
489	app.eventsCtx = ctx
490	setupSubscriber(ctx, app.serviceEventsWG, "sessions", app.Sessions.Subscribe, app.events)
491	setupSubscriber(ctx, app.serviceEventsWG, "messages", app.Messages.Subscribe, app.events)
492	setupSubscriber(ctx, app.serviceEventsWG, "permissions", app.Permissions.Subscribe, app.events)
493	setupSubscriber(ctx, app.serviceEventsWG, "permissions-notifications", app.Permissions.SubscribeNotifications, app.events)
494	setupSubscriber(ctx, app.serviceEventsWG, "history", app.History.Subscribe, app.events)
495	setupSubscriber(ctx, app.serviceEventsWG, "agent-notifications", app.agentNotifications.Subscribe, app.events)
496	setupSubscriberMustDeliver(ctx, app.serviceEventsWG, "run-completions", app.runCompletions.Subscribe, app.events)
497	setupSubscriber(ctx, app.serviceEventsWG, "mcp", mcp.SubscribeEvents, app.events)
498	setupSubscriber(ctx, app.serviceEventsWG, "lsp", SubscribeLSPEvents, app.events)
499	if app.Skills != nil {
500		setupSubscriber(ctx, app.serviceEventsWG, "skills", app.Skills.SubscribeEvents, app.events)
501	}
502	cleanupFunc := func(context.Context) error {
503		cancel()
504		app.serviceEventsWG.Wait()
505		app.events.Shutdown()
506		return nil
507	}
508	app.cleanupFuncs = append(app.cleanupFuncs, cleanupFunc)
509}
510
511func setupSubscriber[T any](
512	ctx context.Context,
513	wg *sync.WaitGroup,
514	name string,
515	subscriber func(context.Context) <-chan pubsub.Event[T],
516	broker *pubsub.Broker[tea.Msg],
517) {
518	wg.Go(func() {
519		subCh := subscriber(ctx)
520		for {
521			select {
522			case event, ok := <-subCh:
523				if !ok {
524					slog.Debug("Subscription channel closed", "name", name)
525					return
526				}
527				broker.Publish(pubsub.UpdatedEvent, tea.Msg(event))
528			case <-ctx.Done():
529				slog.Debug("Subscription cancelled", "name", name)
530				return
531			}
532		}
533	})
534}
535
536// setupSubscriberMustDeliver is the bounded-blocking fan-in variant of
537// setupSubscriber: it re-publishes upstream events onto the shared
538// app.events broker using PublishMustDeliver instead of Publish. Use
539// this for terminal events that subscribers cannot tolerate losing —
540// notably RunComplete, which is the authoritative end-of-run signal
541// for `crush run`. A lossy fan-in here can drop the only terminal
542// event and hang non-interactive clients waiting on it.
543func setupSubscriberMustDeliver[T any](
544	ctx context.Context,
545	wg *sync.WaitGroup,
546	name string,
547	subscriber func(context.Context) <-chan pubsub.Event[T],
548	broker *pubsub.Broker[tea.Msg],
549) {
550	wg.Go(func() {
551		subCh := subscriber(ctx)
552		for {
553			select {
554			case event, ok := <-subCh:
555				if !ok {
556					slog.Debug("Subscription channel closed", "name", name)
557					return
558				}
559				broker.PublishMustDeliver(ctx, pubsub.UpdatedEvent, tea.Msg(event))
560			case <-ctx.Done():
561				slog.Debug("Subscription cancelled", "name", name)
562				return
563			}
564		}
565	})
566}
567
568func (app *App) InitCoderAgent(ctx context.Context) error {
569	coderAgentCfg := app.config.Config().Agents[config.AgentCoder]
570	if coderAgentCfg.ID == "" {
571		return fmt.Errorf("coder agent configuration is missing")
572	}
573	var err error
574	app.AgentCoordinator, err = agent.NewCoordinator(
575		ctx,
576		app.config,
577		app.Sessions,
578		app.Messages,
579		app.Permissions,
580		app.History,
581		app.FileTracker,
582		app.LSPManager,
583		app.agentNotifications,
584		app.runCompletions,
585		app.Skills,
586	)
587	if err != nil {
588		slog.Error("Failed to create coder agent", "err", err)
589		return err
590	}
591	return nil
592}
593
594// Subscribe sends events to the TUI as tea.Msgs.
595func (app *App) Subscribe(program *tea.Program) {
596	defer log.RecoverPanic("app.Subscribe", func() {
597		slog.Info("TUI subscription panic: attempting graceful shutdown")
598		program.Quit()
599	})
600
601	app.tuiWG.Add(1)
602	tuiCtx, tuiCancel := context.WithCancel(app.globalCtx)
603	app.cleanupFuncs = append(app.cleanupFuncs, func(context.Context) error {
604		slog.Debug("Cancelling TUI message handler")
605		tuiCancel()
606		app.tuiWG.Wait()
607		return nil
608	})
609	defer app.tuiWG.Done()
610
611	events := app.events.Subscribe(tuiCtx)
612	for {
613		select {
614		case <-tuiCtx.Done():
615			slog.Debug("TUI message handler shutting down")
616			return
617		case ev, ok := <-events:
618			if !ok {
619				slog.Debug("TUI message channel closed")
620				return
621			}
622			program.Send(ev.Payload)
623		}
624	}
625}
626
627// Shutdown performs a graceful shutdown of the application.
628func (app *App) Shutdown() {
629	start := time.Now()
630	defer func() { slog.Debug("Shutdown took " + time.Since(start).String()) }()
631
632	// First, cancel all agents and wait for them to finish. This must complete
633	// before closing the DB so agents can finish writing their state.
634	if app.AgentCoordinator != nil {
635		app.AgentCoordinator.CancelAll()
636	}
637
638	// Shared shutdown context for all timeout-bounded cleanup.
639	shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
640	defer cancel()
641
642	// Drain any debounced message updates before the DB-close cleanup
643	// runs in the parallel block below. message.Service buffers
644	// streaming deltas (see internal/message/message.go) and we must
645	// land them while the connection is still open.
646	if app.Messages != nil {
647		if err := app.Messages.FlushAll(shutdownCtx); err != nil {
648			slog.Error("Failed to flush pending message updates on shutdown", "error", err)
649		}
650	}
651
652	// Now run remaining cleanup tasks in parallel.
653	var wg sync.WaitGroup
654
655	// Send exit event
656	wg.Go(func() {
657		event.AppExited()
658	})
659
660	// Kill all background shells.
661	wg.Go(func() {
662		shell.GetBackgroundShellManager().KillAll(shutdownCtx)
663	})
664
665	// Shutdown all LSP clients.
666	wg.Go(func() {
667		app.LSPManager.KillAll(shutdownCtx)
668	})
669
670	// Call all cleanup functions.
671	for _, cleanup := range app.cleanupFuncs {
672		if cleanup != nil {
673			wg.Go(func() {
674				if err := cleanup(shutdownCtx); err != nil {
675					slog.Error("Failed to cleanup app properly on shutdown", "error", err)
676				}
677			})
678		}
679	}
680	wg.Wait()
681}
682
683// checkForUpdates checks for available updates.
684func (app *App) checkForUpdates(ctx context.Context) {
685	checkCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
686	defer cancel()
687
688	info, err := update.Check(checkCtx, version.Version, update.Default)
689	if err != nil || !info.Available() {
690		return
691	}
692	app.events.Publish(pubsub.UpdatedEvent, UpdateAvailableMsg{
693		CurrentVersion: info.Current,
694		LatestVersion:  info.Latest,
695		IsDevelopment:  info.IsDevelopment(),
696	})
697}