@@ -50,7 +50,7 @@ type App struct {
51 // global context and cleanup functions
51 // global context and cleanup functions
52 globalCtx context.Context
52 globalCtx context.Context
53− cleanupFuncs []func()
53+ cleanupFuncs []func() error
56// New initializes a new applcation instance.
56// New initializes a new applcation instance.
@@ -88,6 +88,9 @@ func New(ctx context.Context, conn *sql.DB, cfg *config.Config) (*App, error) {
88 // Initialize LSP clients in the background.
88 // Initialize LSP clients in the background.
89 app.initLSPClients(ctx)
89 app.initLSPClients(ctx)
91+ // cleanup database upon app shutdown
92+ app.cleanupFuncs = append(app.cleanupFuncs, conn.Close)
91 // TODO: remove the concept of agent config, most likely.
94 // TODO: remove the concept of agent config, most likely.
92 if cfg.IsConfigured() {
95 if cfg.IsConfigured() {
93 if err := app.InitCoderAgent(); err != nil {
96 if err := app.InitCoderAgent(); err != nil {
@@ -221,9 +224,10 @@ func (app *App) setupEvents() {
221 setupSubscriber(ctx, app.serviceEventsWG, "history", app.History.Subscribe, app.events)
224 setupSubscriber(ctx, app.serviceEventsWG, "history", app.History.Subscribe, app.events)
222 setupSubscriber(ctx, app.serviceEventsWG, "mcp", agent.SubscribeMCPEvents, app.events)
225 setupSubscriber(ctx, app.serviceEventsWG, "mcp", agent.SubscribeMCPEvents, app.events)
223 setupSubscriber(ctx, app.serviceEventsWG, "lsp", SubscribeLSPEvents, app.events)
226 setupSubscriber(ctx, app.serviceEventsWG, "lsp", SubscribeLSPEvents, app.events)
224− cleanupFunc := func() {
227+ cleanupFunc := func() error {
226 app.serviceEventsWG.Wait()
229 app.serviceEventsWG.Wait()
228 app.cleanupFuncs = append(app.cleanupFuncs, cleanupFunc)
232 app.cleanupFuncs = append(app.cleanupFuncs, cleanupFunc)
@@ -297,10 +301,11 @@ func (app *App) Subscribe(program *tea.Program) {
298 app.tuiWG.Add(1)
302 app.tuiWG.Add(1)
299 tuiCtx, tuiCancel := context.WithCancel(app.globalCtx)
303 tuiCtx, tuiCancel := context.WithCancel(app.globalCtx)
300− app.cleanupFuncs = append(app.cleanupFuncs, func() {
304+ app.cleanupFuncs = append(app.cleanupFuncs, func() error {
301 slog.Debug("Cancelling TUI message handler")
305 slog.Debug("Cancelling TUI message handler")
302 tuiCancel()
306 tuiCancel()
303 app.tuiWG.Wait()
307 app.tuiWG.Wait()
305 defer app.tuiWG.Done()
310 defer app.tuiWG.Done()
@@ -350,7 +355,9 @@ func (app *App) Shutdown() {
350 // Call call cleanup functions.
355 // Call call cleanup functions.
351 for _, cleanup := range app.cleanupFuncs {
356 for _, cleanup := range app.cleanupFuncs {
352 if cleanup != nil {
357 if cleanup != nil {
353− cleanup()
358+ if err := cleanup(); err != nil {
359+ slog.Error("Failed to cleanup app properly on shutdown", "error", err)