app.go

  1package app
  2
  3import (
  4	"context"
  5	"database/sql"
  6	"errors"
  7	"fmt"
  8	"log/slog"
  9	"sync"
 10	"time"
 11
 12	"charm.land/fantasy"
 13	tea "github.com/charmbracelet/bubbletea/v2"
 14	"git.secluded.site/crush/internal/agent"
 15	"git.secluded.site/crush/internal/agent/tools"
 16	"git.secluded.site/crush/internal/config"
 17	"git.secluded.site/crush/internal/csync"
 18	"git.secluded.site/crush/internal/db"
 19	"git.secluded.site/crush/internal/format"
 20	"git.secluded.site/crush/internal/history"
 21	"git.secluded.site/crush/internal/log"
 22	"git.secluded.site/crush/internal/lsp"
 23	"git.secluded.site/crush/internal/message"
 24	"git.secluded.site/crush/internal/notification"
 25	"git.secluded.site/crush/internal/permission"
 26	"git.secluded.site/crush/internal/pubsub"
 27	"git.secluded.site/crush/internal/session"
 28	"github.com/charmbracelet/x/ansi"
 29)
 30
 31type App struct {
 32	Sessions    session.Service
 33	Messages    message.Service
 34	History     history.Service
 35	Permissions permission.Service
 36
 37	AgentCoordinator agent.Coordinator
 38	Notifier         *notification.Notifier
 39
 40	LSPClients *csync.Map[string, *lsp.Client]
 41
 42	config *config.Config
 43
 44	serviceEventsWG *sync.WaitGroup
 45	eventsCtx       context.Context
 46	events          chan tea.Msg
 47	tuiWG           *sync.WaitGroup
 48
 49	// global context and cleanup functions
 50	globalCtx    context.Context
 51	cleanupFuncs []func() error
 52}
 53
 54// New initializes a new applcation instance.
 55func New(ctx context.Context, conn *sql.DB, cfg *config.Config) (*App, error) {
 56	q := db.New(conn)
 57	sessions := session.NewService(q)
 58	messages := message.NewService(q)
 59	files := history.NewService(q, conn)
 60	skipPermissionsRequests := cfg.Permissions != nil && cfg.Permissions.SkipRequests
 61	allowedTools := []string{}
 62	if cfg.Permissions != nil && cfg.Permissions.AllowedTools != nil {
 63		allowedTools = cfg.Permissions.AllowedTools
 64	}
 65
 66	// Enable notifications by default, disable if configured.
 67	notificationsEnabled := cfg.Options == nil || !cfg.Options.DisableNotifications
 68
 69	notifier := notification.New(notificationsEnabled)
 70	permissions := permission.NewPermissionService(ctx, cfg.WorkingDir(), skipPermissionsRequests, allowedTools, notifier)
 71
 72	app := &App{
 73		Sessions:    sessions,
 74		Messages:    messages,
 75		History:     files,
 76		Permissions: permissions,
 77		Notifier:    notifier,
 78		LSPClients:  csync.NewMap[string, *lsp.Client](),
 79
 80		globalCtx: ctx,
 81
 82		config: cfg,
 83
 84		events:          make(chan tea.Msg, 100),
 85		serviceEventsWG: &sync.WaitGroup{},
 86		tuiWG:           &sync.WaitGroup{},
 87	}
 88
 89	app.setupEvents()
 90
 91	// Initialize LSP clients in the background.
 92	app.initLSPClients(ctx)
 93
 94	// cleanup database upon app shutdown
 95	app.cleanupFuncs = append(app.cleanupFuncs, conn.Close)
 96
 97	// TODO: remove the concept of agent config, most likely.
 98	if !cfg.IsConfigured() {
 99		slog.Warn("No agent configuration found")
100		return app, nil
101	}
102	if err := app.InitCoderAgent(ctx); err != nil {
103		return nil, fmt.Errorf("failed to initialize coder agent: %w", err)
104	}
105	return app, nil
106}
107
108// Config returns the application configuration.
109func (app *App) Config() *config.Config {
110	return app.config
111}
112
113// RunNonInteractive handles the execution flow when a prompt is provided via
114// CLI flag.
115func (app *App) RunNonInteractive(ctx context.Context, prompt string, quiet bool) error {
116	slog.Info("Running in non-interactive mode")
117
118	ctx, cancel := context.WithCancel(ctx)
119	defer cancel()
120
121	var spinner *format.Spinner
122	if !quiet {
123		spinner = format.NewSpinner(ctx, cancel, "Generating")
124		spinner.Start()
125	}
126
127	// Helper function to stop spinner once.
128	stopSpinner := func() {
129		if !quiet && spinner != nil {
130			spinner.Stop()
131			spinner = nil
132		}
133	}
134	defer stopSpinner()
135
136	const maxPromptLengthForTitle = 100
137	titlePrefix := "Non-interactive: "
138	var titleSuffix string
139
140	if len(prompt) > maxPromptLengthForTitle {
141		titleSuffix = prompt[:maxPromptLengthForTitle] + "..."
142	} else {
143		titleSuffix = prompt
144	}
145	title := titlePrefix + titleSuffix
146
147	sess, err := app.Sessions.Create(ctx, title)
148	if err != nil {
149		return fmt.Errorf("failed to create session for non-interactive mode: %w", err)
150	}
151	slog.Info("Created session for non-interactive run", "session_id", sess.ID)
152
153	// Automatically approve all permission requests for this non-interactive session
154	app.Permissions.AutoApproveSession(sess.ID)
155
156	type response struct {
157		result *fantasy.AgentResult
158		err    error
159	}
160	done := make(chan response, 1)
161
162	go func(ctx context.Context, sessionID, prompt string) {
163		result, err := app.AgentCoordinator.Run(ctx, sess.ID, prompt)
164		if err != nil {
165			done <- response{
166				err: fmt.Errorf("failed to start agent processing stream: %w", err),
167			}
168		}
169		done <- response{
170			result: result,
171		}
172	}(ctx, sess.ID, prompt)
173
174	messageEvents := app.Messages.Subscribe(ctx)
175	messageReadBytes := make(map[string]int)
176
177	defer fmt.Printf(ansi.ResetProgressBar)
178	for {
179		// HACK: add it again on every iteration so it doesn't get hidden by
180		// the terminal due to inactivity.
181		fmt.Printf(ansi.SetIndeterminateProgressBar)
182		select {
183		case result := <-done:
184			stopSpinner()
185			if result.err != nil {
186				if errors.Is(result.err, context.Canceled) || errors.Is(result.err, agent.ErrRequestCancelled) {
187					slog.Info("Non-interactive: agent processing cancelled", "session_id", sess.ID)
188					return nil
189				}
190				return fmt.Errorf("agent processing failed: %w", result.err)
191			}
192			return nil
193
194		case event := <-messageEvents:
195			msg := event.Payload
196			if msg.SessionID == sess.ID && msg.Role == message.Assistant && len(msg.Parts) > 0 {
197				stopSpinner()
198
199				content := msg.Content().String()
200				readBytes := messageReadBytes[msg.ID]
201
202				if len(content) < readBytes {
203					slog.Error("Non-interactive: message content is shorter than read bytes", "message_length", len(content), "read_bytes", readBytes)
204					return fmt.Errorf("message content is shorter than read bytes: %d < %d", len(content), readBytes)
205				}
206
207				part := content[readBytes:]
208				fmt.Print(part)
209				messageReadBytes[msg.ID] = len(content)
210			}
211
212		case <-ctx.Done():
213			stopSpinner()
214			return ctx.Err()
215		}
216	}
217}
218
219func (app *App) UpdateAgentModel(ctx context.Context) error {
220	return app.AgentCoordinator.UpdateModels(ctx)
221}
222
223func (app *App) setupEvents() {
224	ctx, cancel := context.WithCancel(app.globalCtx)
225	app.eventsCtx = ctx
226	setupSubscriber(ctx, app.serviceEventsWG, "sessions", app.Sessions.Subscribe, app.events)
227	setupSubscriber(ctx, app.serviceEventsWG, "messages", app.Messages.Subscribe, app.events)
228	setupSubscriber(ctx, app.serviceEventsWG, "permissions", app.Permissions.Subscribe, app.events)
229	setupSubscriber(ctx, app.serviceEventsWG, "permissions-notifications", app.Permissions.SubscribeNotifications, app.events)
230	setupSubscriber(ctx, app.serviceEventsWG, "history", app.History.Subscribe, app.events)
231	setupSubscriber(ctx, app.serviceEventsWG, "mcp", tools.SubscribeMCPEvents, app.events)
232	setupSubscriber(ctx, app.serviceEventsWG, "lsp", SubscribeLSPEvents, app.events)
233	cleanupFunc := func() error {
234		cancel()
235		app.serviceEventsWG.Wait()
236		return nil
237	}
238	app.cleanupFuncs = append(app.cleanupFuncs, cleanupFunc)
239}
240
241func setupSubscriber[T any](
242	ctx context.Context,
243	wg *sync.WaitGroup,
244	name string,
245	subscriber func(context.Context) <-chan pubsub.Event[T],
246	outputCh chan<- tea.Msg,
247) {
248	wg.Go(func() {
249		subCh := subscriber(ctx)
250		for {
251			select {
252			case event, ok := <-subCh:
253				if !ok {
254					slog.Debug("subscription channel closed", "name", name)
255					return
256				}
257				var msg tea.Msg = event
258				select {
259				case outputCh <- msg:
260				case <-time.After(2 * time.Second):
261					slog.Warn("message dropped due to slow consumer", "name", name)
262				case <-ctx.Done():
263					slog.Debug("subscription cancelled", "name", name)
264					return
265				}
266			case <-ctx.Done():
267				slog.Debug("subscription cancelled", "name", name)
268				return
269			}
270		}
271	})
272}
273
274func (app *App) InitCoderAgent(ctx context.Context) error {
275	coderAgentCfg := app.config.Agents[config.AgentCoder]
276	if coderAgentCfg.ID == "" {
277		return fmt.Errorf("coder agent configuration is missing")
278	}
279	var err error
280	app.AgentCoordinator, err = agent.NewCoordinator(
281		ctx,
282		app.config,
283		app.Sessions,
284		app.Messages,
285		app.Permissions,
286		app.History,
287		app.LSPClients,
288		app.Notifier,
289	)
290	if err != nil {
291		slog.Error("Failed to create coder agent", "err", err)
292		return err
293	}
294
295	// Add MCP client cleanup to shutdown process
296	app.cleanupFuncs = append(app.cleanupFuncs, tools.CloseMCPClients)
297	return nil
298}
299
300// Subscribe sends events to the TUI as tea.Msgs.
301func (app *App) Subscribe(program *tea.Program) {
302	defer log.RecoverPanic("app.Subscribe", func() {
303		slog.Info("TUI subscription panic: attempting graceful shutdown")
304		program.Quit()
305	})
306
307	app.tuiWG.Add(1)
308	tuiCtx, tuiCancel := context.WithCancel(app.globalCtx)
309	app.cleanupFuncs = append(app.cleanupFuncs, func() error {
310		slog.Debug("Cancelling TUI message handler")
311		tuiCancel()
312		app.tuiWG.Wait()
313		return nil
314	})
315	defer app.tuiWG.Done()
316
317	for {
318		select {
319		case <-tuiCtx.Done():
320			slog.Debug("TUI message handler shutting down")
321			return
322		case msg, ok := <-app.events:
323			if !ok {
324				slog.Debug("TUI message channel closed")
325				return
326			}
327			program.Send(msg)
328		}
329	}
330}
331
332// Shutdown performs a graceful shutdown of the application.
333func (app *App) Shutdown() {
334	if app.AgentCoordinator != nil {
335		app.AgentCoordinator.CancelAll()
336	}
337
338	// Shutdown all LSP clients.
339	for name, client := range app.LSPClients.Seq2() {
340		shutdownCtx, cancel := context.WithTimeout(app.globalCtx, 5*time.Second)
341		if err := client.Close(shutdownCtx); err != nil {
342			slog.Error("Failed to shutdown LSP client", "name", name, "error", err)
343		}
344		cancel()
345	}
346
347	// Call call cleanup functions.
348	for _, cleanup := range app.cleanupFuncs {
349		if cleanup != nil {
350			if err := cleanup(); err != nil {
351				slog.Error("Failed to cleanup app properly on shutdown", "error", err)
352			}
353		}
354	}
355}