1package app
2
3import (
4 "context"
5 "database/sql"
6 "errors"
7 "fmt"
8 "maps"
9 "sync"
10 "time"
11
12 "github.com/charmbracelet/crush/internal/config"
13 "github.com/charmbracelet/crush/internal/db"
14 "github.com/charmbracelet/crush/internal/format"
15 "github.com/charmbracelet/crush/internal/history"
16 "github.com/charmbracelet/crush/internal/llm/agent"
17 "github.com/charmbracelet/crush/internal/logging"
18 "github.com/charmbracelet/crush/internal/lsp"
19 "github.com/charmbracelet/crush/internal/message"
20 "github.com/charmbracelet/crush/internal/permission"
21 "github.com/charmbracelet/crush/internal/session"
22)
23
24type App struct {
25 Sessions session.Service
26 Messages message.Service
27 History history.Service
28 Permissions permission.Service
29
30 CoderAgent agent.Service
31
32 LSPClients map[string]*lsp.Client
33
34 clientsMutex sync.RWMutex
35
36 watcherCancelFuncs []context.CancelFunc
37 cancelFuncsMutex sync.Mutex
38 watcherWG sync.WaitGroup
39}
40
41func New(ctx context.Context, conn *sql.DB) (*App, error) {
42 q := db.New(conn)
43 sessions := session.NewService(q)
44 messages := message.NewService(q)
45 files := history.NewService(q, conn)
46
47 app := &App{
48 Sessions: sessions,
49 Messages: messages,
50 History: files,
51 Permissions: permission.NewPermissionService(),
52 LSPClients: make(map[string]*lsp.Client),
53 }
54
55 // Initialize LSP clients in the background
56 go app.initLSPClients(ctx)
57
58 var err error
59 app.CoderAgent, err = agent.NewAgent(
60 config.AgentCoder,
61 app.Sessions,
62 app.Messages,
63 agent.CoderAgentTools(
64 app.Permissions,
65 app.Sessions,
66 app.Messages,
67 app.History,
68 app.LSPClients,
69 ),
70 )
71 if err != nil {
72 logging.Error("Failed to create coder agent", err)
73 return nil, err
74 }
75
76 return app, nil
77}
78
79// RunNonInteractive handles the execution flow when a prompt is provided via CLI flag.
80func (a *App) RunNonInteractive(ctx context.Context, prompt string, outputFormat string, quiet bool) error {
81 logging.Info("Running in non-interactive mode")
82
83 // Start spinner if not in quiet mode
84 var spinner *format.Spinner
85 if !quiet {
86 spinner = format.NewSpinner("Thinking...")
87 spinner.Start()
88 defer spinner.Stop()
89 }
90
91 const maxPromptLengthForTitle = 100
92 titlePrefix := "Non-interactive: "
93 var titleSuffix string
94
95 if len(prompt) > maxPromptLengthForTitle {
96 titleSuffix = prompt[:maxPromptLengthForTitle] + "..."
97 } else {
98 titleSuffix = prompt
99 }
100 title := titlePrefix + titleSuffix
101
102 sess, err := a.Sessions.Create(ctx, title)
103 if err != nil {
104 return fmt.Errorf("failed to create session for non-interactive mode: %w", err)
105 }
106 logging.Info("Created session for non-interactive run", "session_id", sess.ID)
107
108 // Automatically approve all permission requests for this non-interactive session
109 a.Permissions.AutoApproveSession(sess.ID)
110
111 done, err := a.CoderAgent.Run(ctx, sess.ID, prompt)
112 if err != nil {
113 return fmt.Errorf("failed to start agent processing stream: %w", err)
114 }
115
116 result := <-done
117 if result.Error != nil {
118 if errors.Is(result.Error, context.Canceled) || errors.Is(result.Error, agent.ErrRequestCancelled) {
119 logging.Info("Agent processing cancelled", "session_id", sess.ID)
120 return nil
121 }
122 return fmt.Errorf("agent processing failed: %w", result.Error)
123 }
124
125 // Stop spinner before printing output
126 if !quiet && spinner != nil {
127 spinner.Stop()
128 }
129
130 // Get the text content from the response
131 content := "No content available"
132 if result.Message.Content().String() != "" {
133 content = result.Message.Content().String()
134 }
135
136 fmt.Println(format.FormatOutput(content, outputFormat))
137
138 logging.Info("Non-interactive run completed", "session_id", sess.ID)
139
140 return nil
141}
142
143// Shutdown performs a clean shutdown of the application
144func (app *App) Shutdown() {
145 // Cancel all watcher goroutines
146 app.cancelFuncsMutex.Lock()
147 for _, cancel := range app.watcherCancelFuncs {
148 cancel()
149 }
150 app.cancelFuncsMutex.Unlock()
151 app.watcherWG.Wait()
152
153 // Perform additional cleanup for LSP clients
154 app.clientsMutex.RLock()
155 clients := make(map[string]*lsp.Client, len(app.LSPClients))
156 maps.Copy(clients, app.LSPClients)
157 app.clientsMutex.RUnlock()
158
159 for name, client := range clients {
160 shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
161 if err := client.Shutdown(shutdownCtx); err != nil {
162 logging.Error("Failed to shutdown LSP client", "name", name, "error", err)
163 }
164 cancel()
165 }
166 app.CoderAgent.CancelAll()
167}