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