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