1package tui
2
3import (
4 "context"
5 "fmt"
6
7 "github.com/charmbracelet/bubbles/v2/key"
8 tea "github.com/charmbracelet/bubbletea/v2"
9 "github.com/charmbracelet/crush/internal/app"
10 "github.com/charmbracelet/crush/internal/config"
11 "github.com/charmbracelet/crush/internal/llm/agent"
12 "github.com/charmbracelet/crush/internal/permission"
13 "github.com/charmbracelet/crush/internal/pubsub"
14 cmpChat "github.com/charmbracelet/crush/internal/tui/components/chat"
15 "github.com/charmbracelet/crush/internal/tui/components/completions"
16 "github.com/charmbracelet/crush/internal/tui/components/core/layout"
17 "github.com/charmbracelet/crush/internal/tui/components/core/status"
18 "github.com/charmbracelet/crush/internal/tui/components/dialogs"
19 "github.com/charmbracelet/crush/internal/tui/components/dialogs/commands"
20 "github.com/charmbracelet/crush/internal/tui/components/dialogs/compact"
21 "github.com/charmbracelet/crush/internal/tui/components/dialogs/filepicker"
22 "github.com/charmbracelet/crush/internal/tui/components/dialogs/models"
23 "github.com/charmbracelet/crush/internal/tui/components/dialogs/permissions"
24 "github.com/charmbracelet/crush/internal/tui/components/dialogs/quit"
25 "github.com/charmbracelet/crush/internal/tui/components/dialogs/sessions"
26 "github.com/charmbracelet/crush/internal/tui/page"
27 "github.com/charmbracelet/crush/internal/tui/page/chat"
28 "github.com/charmbracelet/crush/internal/tui/styles"
29 "github.com/charmbracelet/crush/internal/tui/util"
30 "github.com/charmbracelet/lipgloss/v2"
31)
32
33// MouseEventFilter filters mouse events based on the current focus state
34// This is used with tea.WithFilter to prevent mouse scroll events from
35// interfering with typing performance in the editor
36func MouseEventFilter(m tea.Model, msg tea.Msg) tea.Msg {
37 // Only filter mouse events
38 switch msg.(type) {
39 case tea.MouseWheelMsg, tea.MouseMotionMsg:
40 // Check if we have an appModel and if editor is focused
41 if appModel, ok := m.(*appModel); ok {
42 if appModel.currentPage == chat.ChatPageID {
43 if chatPage, ok := appModel.pages[appModel.currentPage].(chat.ChatPage); ok {
44 // If editor is focused (not chatFocused), filter out mouse wheel/motion events
45 if !chatPage.IsChatFocused() {
46 return nil // Filter out the event
47 }
48 }
49 }
50 }
51 }
52 // Allow all other events to pass through
53 return msg
54}
55
56// appModel represents the main application model that manages pages, dialogs, and UI state.
57type appModel struct {
58 wWidth, wHeight int // Window dimensions
59 width, height int
60 keyMap KeyMap
61
62 currentPage page.PageID
63 previousPage page.PageID
64 pages map[page.PageID]util.Model
65 loadedPages map[page.PageID]bool
66
67 // Status
68 status status.StatusCmp
69 showingFullHelp bool
70
71 app *app.App
72
73 dialog dialogs.DialogCmp
74 completions completions.Completions
75
76 // Chat Page Specific
77 selectedSessionID string // The ID of the currently selected session
78}
79
80// Init initializes the application model and returns initial commands.
81func (a appModel) Init() tea.Cmd {
82 var cmds []tea.Cmd
83 cmd := a.pages[a.currentPage].Init()
84 cmds = append(cmds, cmd)
85 a.loadedPages[a.currentPage] = true
86
87 cmd = a.status.Init()
88 cmds = append(cmds, cmd)
89
90 cmds = append(cmds, tea.EnableMouseAllMotion)
91
92 return tea.Batch(cmds...)
93}
94
95// Update handles incoming messages and updates the application state.
96func (a *appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
97 var cmds []tea.Cmd
98 var cmd tea.Cmd
99
100 switch msg := msg.(type) {
101 case tea.KeyboardEnhancementsMsg:
102 for id, page := range a.pages {
103 m, pageCmd := page.Update(msg)
104 a.pages[id] = m.(util.Model)
105 if pageCmd != nil {
106 cmds = append(cmds, pageCmd)
107 }
108 }
109 return a, tea.Batch(cmds...)
110 case tea.WindowSizeMsg:
111 return a, a.handleWindowResize(msg.Width, msg.Height)
112
113 // Completions messages
114 case completions.OpenCompletionsMsg, completions.FilterCompletionsMsg, completions.CloseCompletionsMsg:
115 u, completionCmd := a.completions.Update(msg)
116 a.completions = u.(completions.Completions)
117 return a, completionCmd
118
119 // Dialog messages
120 case dialogs.OpenDialogMsg, dialogs.CloseDialogMsg:
121 u, dialogCmd := a.dialog.Update(msg)
122 a.dialog = u.(dialogs.DialogCmp)
123 return a, dialogCmd
124 case commands.ShowArgumentsDialogMsg:
125 return a, util.CmdHandler(
126 dialogs.OpenDialogMsg{
127 Model: commands.NewCommandArgumentsDialog(
128 msg.CommandID,
129 msg.Content,
130 msg.ArgNames,
131 ),
132 },
133 )
134 // Page change messages
135 case page.PageChangeMsg:
136 return a, a.moveToPage(msg.ID)
137
138 // Status Messages
139 case util.InfoMsg, util.ClearStatusMsg:
140 s, statusCmd := a.status.Update(msg)
141 a.status = s.(status.StatusCmp)
142 cmds = append(cmds, statusCmd)
143 return a, tea.Batch(cmds...)
144
145 // Session
146 case cmpChat.SessionSelectedMsg:
147 a.selectedSessionID = msg.ID
148 case cmpChat.SessionClearedMsg:
149 a.selectedSessionID = ""
150 // Commands
151 case commands.SwitchSessionsMsg:
152 return a, func() tea.Msg {
153 allSessions, _ := a.app.Sessions.List(context.Background())
154 return dialogs.OpenDialogMsg{
155 Model: sessions.NewSessionDialogCmp(allSessions, a.selectedSessionID),
156 }
157 }
158
159 case commands.SwitchModelMsg:
160 return a, util.CmdHandler(
161 dialogs.OpenDialogMsg{
162 Model: models.NewModelDialogCmp(),
163 },
164 )
165 // Compact
166 case commands.CompactMsg:
167 return a, util.CmdHandler(dialogs.OpenDialogMsg{
168 Model: compact.NewCompactDialogCmp(a.app.CoderAgent, msg.SessionID, true),
169 })
170
171 // Model Switch
172 case models.ModelSelectedMsg:
173 config.Get().UpdatePreferredModel(msg.ModelType, msg.Model)
174
175 // Update the agent with the new model/provider configuration
176 if err := a.app.UpdateAgentModel(); err != nil {
177 return a, util.ReportError(fmt.Errorf("model changed to %s but failed to update agent: %v", msg.Model.Model, err))
178 }
179
180 modelTypeName := "large"
181 if msg.ModelType == config.SelectedModelTypeSmall {
182 modelTypeName = "small"
183 }
184 return a, util.ReportInfo(fmt.Sprintf("%s model changed to %s", modelTypeName, msg.Model.Model))
185
186 // File Picker
187 case chat.OpenFilePickerMsg:
188 if a.dialog.ActiveDialogID() == filepicker.FilePickerID {
189 // If the commands dialog is already open, close it
190 return a, util.CmdHandler(dialogs.CloseDialogMsg{})
191 }
192 return a, util.CmdHandler(dialogs.OpenDialogMsg{
193 Model: filepicker.NewFilePickerCmp(),
194 })
195 // Permissions
196 case pubsub.Event[permission.PermissionRequest]:
197 return a, util.CmdHandler(dialogs.OpenDialogMsg{
198 Model: permissions.NewPermissionDialogCmp(msg.Payload),
199 })
200 case permissions.PermissionResponseMsg:
201 switch msg.Action {
202 case permissions.PermissionAllow:
203 a.app.Permissions.Grant(msg.Permission)
204 case permissions.PermissionAllowForSession:
205 a.app.Permissions.GrantPersistent(msg.Permission)
206 case permissions.PermissionDeny:
207 a.app.Permissions.Deny(msg.Permission)
208 }
209 return a, nil
210 // Agent Events
211 case pubsub.Event[agent.AgentEvent]:
212 payload := msg.Payload
213
214 // Forward agent events to dialogs
215 if a.dialog.HasDialogs() && a.dialog.ActiveDialogID() == compact.CompactDialogID {
216 u, dialogCmd := a.dialog.Update(payload)
217 a.dialog = u.(dialogs.DialogCmp)
218 cmds = append(cmds, dialogCmd)
219 }
220
221 // Handle auto-compact logic
222 if payload.Done && payload.Type == agent.AgentEventTypeResponse && a.selectedSessionID != "" {
223 // Get current session to check token usage
224 session, err := a.app.Sessions.Get(context.Background(), a.selectedSessionID)
225 if err == nil {
226 model := a.app.CoderAgent.Model()
227 contextWindow := model.ContextWindow
228 tokens := session.CompletionTokens + session.PromptTokens
229 if (tokens >= int64(float64(contextWindow)*0.95)) && !config.Get().Options.DisableAutoSummarize { // Show compact confirmation dialog
230 cmds = append(cmds, util.CmdHandler(dialogs.OpenDialogMsg{
231 Model: compact.NewCompactDialogCmp(a.app.CoderAgent, a.selectedSessionID, false),
232 }))
233 }
234 }
235 }
236
237 return a, tea.Batch(cmds...)
238 // Key Press Messages
239 case tea.KeyPressMsg:
240 return a, a.handleKeyPressMsg(msg)
241 }
242 s, _ := a.status.Update(msg)
243 a.status = s.(status.StatusCmp)
244 updated, cmd := a.pages[a.currentPage].Update(msg)
245 a.pages[a.currentPage] = updated.(util.Model)
246 if a.dialog.HasDialogs() {
247 u, dialogCmd := a.dialog.Update(msg)
248 a.dialog = u.(dialogs.DialogCmp)
249 cmds = append(cmds, dialogCmd)
250 }
251 cmds = append(cmds, cmd)
252 return a, tea.Batch(cmds...)
253}
254
255// handleWindowResize processes window resize events and updates all components.
256func (a *appModel) handleWindowResize(width, height int) tea.Cmd {
257 var cmds []tea.Cmd
258 a.wWidth, a.wHeight = width, height
259 if a.showingFullHelp {
260 height -= 4
261 } else {
262 height -= 2
263 }
264 a.width, a.height = width, height
265 // Update status bar
266 s, cmd := a.status.Update(tea.WindowSizeMsg{Width: width, Height: height})
267 a.status = s.(status.StatusCmp)
268 cmds = append(cmds, cmd)
269
270 // Update the current page
271 for p, page := range a.pages {
272 updated, pageCmd := page.Update(tea.WindowSizeMsg{Width: width, Height: height})
273 a.pages[p] = updated.(util.Model)
274 cmds = append(cmds, pageCmd)
275 }
276
277 // Update the dialogs
278 dialog, cmd := a.dialog.Update(tea.WindowSizeMsg{Width: width, Height: height})
279 a.dialog = dialog.(dialogs.DialogCmp)
280 cmds = append(cmds, cmd)
281
282 return tea.Batch(cmds...)
283}
284
285// handleKeyPressMsg processes keyboard input and routes to appropriate handlers.
286func (a *appModel) handleKeyPressMsg(msg tea.KeyPressMsg) tea.Cmd {
287 switch {
288 // completions
289 case a.completions.Open() && key.Matches(msg, a.completions.KeyMap().Up):
290 u, cmd := a.completions.Update(msg)
291 a.completions = u.(completions.Completions)
292 return cmd
293
294 case a.completions.Open() && key.Matches(msg, a.completions.KeyMap().Down):
295 u, cmd := a.completions.Update(msg)
296 a.completions = u.(completions.Completions)
297 return cmd
298 case a.completions.Open() && key.Matches(msg, a.completions.KeyMap().Select):
299 u, cmd := a.completions.Update(msg)
300 a.completions = u.(completions.Completions)
301 return cmd
302 case a.completions.Open() && key.Matches(msg, a.completions.KeyMap().Cancel):
303 u, cmd := a.completions.Update(msg)
304 a.completions = u.(completions.Completions)
305 return cmd
306 // help
307 case key.Matches(msg, a.keyMap.Help):
308 a.status.ToggleFullHelp()
309 a.showingFullHelp = !a.showingFullHelp
310 return a.handleWindowResize(a.wWidth, a.wHeight)
311 // dialogs
312 case key.Matches(msg, a.keyMap.Quit):
313 if a.dialog.ActiveDialogID() == quit.QuitDialogID {
314 // if the quit dialog is already open, close the app
315 return tea.Quit
316 }
317 return util.CmdHandler(dialogs.OpenDialogMsg{
318 Model: quit.NewQuitDialog(),
319 })
320
321 case key.Matches(msg, a.keyMap.Commands):
322 if a.dialog.ActiveDialogID() == commands.CommandsDialogID {
323 // If the commands dialog is already open, close it
324 return util.CmdHandler(dialogs.CloseDialogMsg{})
325 }
326 return util.CmdHandler(dialogs.OpenDialogMsg{
327 Model: commands.NewCommandDialog(a.selectedSessionID),
328 })
329 case key.Matches(msg, a.keyMap.Sessions):
330 if a.dialog.ActiveDialogID() == sessions.SessionsDialogID {
331 // If the sessions dialog is already open, close it
332 return util.CmdHandler(dialogs.CloseDialogMsg{})
333 }
334 var cmds []tea.Cmd
335 if a.dialog.ActiveDialogID() == commands.CommandsDialogID {
336 // If the commands dialog is open, close it first
337 cmds = append(cmds, util.CmdHandler(dialogs.CloseDialogMsg{}))
338 }
339 cmds = append(cmds,
340 func() tea.Msg {
341 allSessions, _ := a.app.Sessions.List(context.Background())
342 return dialogs.OpenDialogMsg{
343 Model: sessions.NewSessionDialogCmp(allSessions, a.selectedSessionID),
344 }
345 },
346 )
347 return tea.Sequence(cmds...)
348 default:
349 if a.dialog.HasDialogs() {
350 u, dialogCmd := a.dialog.Update(msg)
351 a.dialog = u.(dialogs.DialogCmp)
352 return dialogCmd
353 } else {
354 updated, cmd := a.pages[a.currentPage].Update(msg)
355 a.pages[a.currentPage] = updated.(util.Model)
356 return cmd
357 }
358 }
359}
360
361// moveToPage handles navigation between different pages in the application.
362func (a *appModel) moveToPage(pageID page.PageID) tea.Cmd {
363 if a.app.CoderAgent.IsBusy() {
364 // TODO: maybe remove this : For now we don't move to any page if the agent is busy
365 return util.ReportWarn("Agent is busy, please wait...")
366 }
367
368 var cmds []tea.Cmd
369 if _, ok := a.loadedPages[pageID]; !ok {
370 cmd := a.pages[pageID].Init()
371 cmds = append(cmds, cmd)
372 a.loadedPages[pageID] = true
373 }
374 a.previousPage = a.currentPage
375 a.currentPage = pageID
376 if sizable, ok := a.pages[a.currentPage].(layout.Sizeable); ok {
377 cmd := sizable.SetSize(a.width, a.height)
378 cmds = append(cmds, cmd)
379 }
380
381 return tea.Batch(cmds...)
382}
383
384// View renders the complete application interface including pages, dialogs, and overlays.
385func (a *appModel) View() tea.View {
386 page := a.pages[a.currentPage]
387 if withHelp, ok := page.(layout.Help); ok {
388 a.keyMap.pageBindings = withHelp.Bindings()
389 }
390 a.status.SetKeyMap(a.keyMap)
391 pageView := page.View()
392 components := []string{
393 pageView,
394 }
395 components = append(components, a.status.View())
396
397 appView := lipgloss.JoinVertical(lipgloss.Top, components...)
398 layers := []*lipgloss.Layer{
399 lipgloss.NewLayer(appView),
400 }
401 if a.dialog.HasDialogs() {
402 layers = append(
403 layers,
404 a.dialog.GetLayers()...,
405 )
406 }
407
408 var cursor *tea.Cursor
409 if v, ok := page.(util.Cursor); ok {
410 cursor = v.Cursor()
411 }
412 activeView := a.dialog.ActiveModel()
413 if activeView != nil {
414 cursor = nil // Reset cursor if a dialog is active unless it implements util.Cursor
415 if v, ok := activeView.(util.Cursor); ok {
416 cursor = v.Cursor()
417 }
418 }
419
420 if a.completions.Open() && cursor != nil {
421 cmp := a.completions.View()
422 x, y := a.completions.Position()
423 layers = append(
424 layers,
425 lipgloss.NewLayer(cmp).X(x).Y(y),
426 )
427 }
428
429 canvas := lipgloss.NewCanvas(
430 layers...,
431 )
432
433 var view tea.View
434 t := styles.CurrentTheme()
435 view.Layer = canvas
436 view.BackgroundColor = t.BgBase
437 view.Cursor = cursor
438 return view
439}
440
441// New creates and initializes a new TUI application model.
442func New(app *app.App) tea.Model {
443 chatPage := chat.New(app)
444 keyMap := DefaultKeyMap()
445 keyMap.pageBindings = chatPage.Bindings()
446
447 model := &appModel{
448 currentPage: chat.ChatPageID,
449 app: app,
450 status: status.NewStatusCmp(keyMap),
451 loadedPages: make(map[page.PageID]bool),
452 keyMap: keyMap,
453
454 pages: map[page.PageID]util.Model{
455 chat.ChatPageID: chatPage,
456 },
457
458 dialog: dialogs.NewDialogCmp(),
459 completions: completions.New(),
460 }
461
462 return model
463}