@@ -6,6 +6,7 @@ import (
11 tea "github.com/charmbracelet/bubbletea/v2"
12 tea "github.com/charmbracelet/bubbletea/v2"
@@ -72,9 +73,8 @@ to assist developers in writing, debugging, and understanding code directly from
72 return err
73 return err
75− // Create main context for the application
76+ // Use the context from the command which includes signal handling
76− ctx, cancel := context.WithCancel(context.Background())
77+ ctx := cmd.Context()
79 // Connect DB, this will also run migrations
79 // Connect DB, this will also run migrations
80 conn, err := db.Connect(ctx, cfg.Options.DataDirectory)
80 conn, err := db.Connect(ctx, cfg.Options.DataDirectory)
@@ -87,8 +87,23 @@ to assist developers in writing, debugging, and understanding code directly from
87 slog.Error(fmt.Sprintf("Failed to create app instance: %v", err))
87 slog.Error(fmt.Sprintf("Failed to create app instance: %v", err))
88 return err
88 return err
90− // Defer shutdown here so it runs for both interactive and non-interactive modes
90+
91+ // Set up shutdown handling that works for both normal exit and signal interruption
92+ var shutdownOnce sync.Once
94+ shutdownOnce.Do(func() {
95+ slog.Info("Shutting down application")
91− defer app.Shutdown()
96+ app.Shutdown()
101+ // Handle context cancellation (from signals) in a goroutine
104+ slog.Info("Context cancelled, initiating shutdown")
93 // Initialize MCP tools early for both modes
108 // Initialize MCP tools early for both modes
94 initMCPTools(ctx, app, cfg)
109 initMCPTools(ctx, app, cfg)
@@ -121,7 +136,6 @@ to assist developers in writing, debugging, and understanding code directly from
121 slog.Error(fmt.Sprintf("TUI run error: %v", err))
136 slog.Error(fmt.Sprintf("TUI run error: %v", err))
122 return fmt.Errorf("TUI error: %v", err)
137 return fmt.Errorf("TUI error: %v", err)
125 return nil
139 return nil
@@ -140,9 +154,9 @@ func initMCPTools(ctx context.Context, app *app.App, cfg *config.Config) {
143−func Execute() {
157+func Execute(ctx context.Context) {
144 if err := fang.Execute(
158 if err := fang.Execute(
145− context.Background(),
159+ ctx,
147 fang.WithVersion(version.Version),
161 fang.WithVersion(version.Version),
148 ); err != nil {
162 ); err != nil {