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.wWidth, a.wHeight = msg.Width, msg.Height
117 a.completions.Update(msg)
118 return a, a.handleWindowResize(msg.Width, msg.Height)
119
120 // Completions messages
121 case completions.OpenCompletionsMsg, completions.FilterCompletionsMsg,
122 completions.CloseCompletionsMsg, completions.RepositionCompletionsMsg:
123 u, completionCmd := a.completions.Update(msg)
124 a.completions = u.(completions.Completions)
125 return a, completionCmd
126
127 // Dialog messages
128 case dialogs.OpenDialogMsg, dialogs.CloseDialogMsg:
129 u, completionCmd := a.completions.Update(completions.CloseCompletionsMsg{})
130 a.completions = u.(completions.Completions)
131 u, dialogCmd := a.dialog.Update(msg)
132 a.dialog = u.(dialogs.DialogCmp)
133 return a, tea.Batch(completionCmd, dialogCmd)
134 case commands.ShowArgumentsDialogMsg:
135 return a, util.CmdHandler(
136 dialogs.OpenDialogMsg{
137 Model: commands.NewCommandArgumentsDialog(
138 msg.CommandID,
139 msg.Content,
140 msg.ArgNames,
141 ),
142 },
143 )
144 // Page change messages
145 case page.PageChangeMsg:
146 return a, a.moveToPage(msg.ID)
147
148 // Status Messages
149 case util.InfoMsg, util.ClearStatusMsg:
150 s, statusCmd := a.status.Update(msg)
151 a.status = s.(status.StatusCmp)
152 cmds = append(cmds, statusCmd)
153 return a, tea.Batch(cmds...)
154
155 // Session
156 case cmpChat.SessionSelectedMsg:
157 a.selectedSessionID = msg.ID
158 case cmpChat.SessionClearedMsg:
159 a.selectedSessionID = ""
160 // Commands
161 case commands.SwitchSessionsMsg:
162 return a, func() tea.Msg {
163 allSessions, _ := a.app.Sessions.List(context.Background())
164 return dialogs.OpenDialogMsg{
165 Model: sessions.NewSessionDialogCmp(allSessions, a.selectedSessionID),
166 }
167 }
168
169 case commands.SwitchModelMsg:
170 return a, util.CmdHandler(
171 dialogs.OpenDialogMsg{
172 Model: models.NewModelDialogCmp(),
173 },
174 )
175 // Compact
176 case commands.CompactMsg:
177 return a, util.CmdHandler(dialogs.OpenDialogMsg{
178 Model: compact.NewCompactDialogCmp(a.app.CoderAgent, msg.SessionID, true),
179 })
180
181 // Model Switch
182 case models.ModelSelectedMsg:
183 config.Get().UpdatePreferredModel(msg.ModelType, msg.Model)
184
185 // Update the agent with the new model/provider configuration
186 if err := a.app.UpdateAgentModel(); err != nil {
187 return a, util.ReportError(fmt.Errorf("model changed to %s but failed to update agent: %v", msg.Model.Model, err))
188 }
189
190 modelTypeName := "large"
191 if msg.ModelType == config.SelectedModelTypeSmall {
192 modelTypeName = "small"
193 }
194 return a, util.ReportInfo(fmt.Sprintf("%s model changed to %s", modelTypeName, msg.Model.Model))
195
196 // File Picker
197 case chat.OpenFilePickerMsg:
198 if a.dialog.ActiveDialogID() == filepicker.FilePickerID {
199 // If the commands dialog is already open, close it
200 return a, util.CmdHandler(dialogs.CloseDialogMsg{})
201 }
202 return a, util.CmdHandler(dialogs.OpenDialogMsg{
203 Model: filepicker.NewFilePickerCmp(a.app.Config().WorkingDir()),
204 })
205 // Permissions
206 case pubsub.Event[permission.PermissionRequest]:
207 return a, util.CmdHandler(dialogs.OpenDialogMsg{
208 Model: permissions.NewPermissionDialogCmp(msg.Payload),
209 })
210 case permissions.PermissionResponseMsg:
211 switch msg.Action {
212 case permissions.PermissionAllow:
213 a.app.Permissions.Grant(msg.Permission)
214 case permissions.PermissionAllowForSession:
215 a.app.Permissions.GrantPersistent(msg.Permission)
216 case permissions.PermissionDeny:
217 a.app.Permissions.Deny(msg.Permission)
218 }
219 return a, nil
220 // Agent Events
221 case pubsub.Event[agent.AgentEvent]:
222 payload := msg.Payload
223
224 // Forward agent events to dialogs
225 if a.dialog.HasDialogs() && a.dialog.ActiveDialogID() == compact.CompactDialogID {
226 u, dialogCmd := a.dialog.Update(payload)
227 a.dialog = u.(dialogs.DialogCmp)
228 cmds = append(cmds, dialogCmd)
229 }
230
231 // Handle auto-compact logic
232 if payload.Done && payload.Type == agent.AgentEventTypeResponse && a.selectedSessionID != "" {
233 // Get current session to check token usage
234 session, err := a.app.Sessions.Get(context.Background(), a.selectedSessionID)
235 if err == nil {
236 model := a.app.CoderAgent.Model()
237 contextWindow := model.ContextWindow
238 tokens := session.CompletionTokens + session.PromptTokens
239 if (tokens >= int64(float64(contextWindow)*0.95)) && !config.Get().Options.DisableAutoSummarize { // Show compact confirmation dialog
240 cmds = append(cmds, util.CmdHandler(dialogs.OpenDialogMsg{
241 Model: compact.NewCompactDialogCmp(a.app.CoderAgent, a.selectedSessionID, false),
242 }))
243 }
244 }
245 }
246
247 return a, tea.Batch(cmds...)
248 case splash.OnboardingCompleteMsg:
249 a.isConfigured = config.HasInitialDataConfig()
250 updated, pageCmd := a.pages[a.currentPage].Update(msg)
251 a.pages[a.currentPage] = updated.(util.Model)
252 cmds = append(cmds, pageCmd)
253 return a, tea.Batch(cmds...)
254 // Key Press Messages
255 case tea.KeyPressMsg:
256 return a, a.handleKeyPressMsg(msg)
257
258 case tea.PasteMsg:
259 if a.dialog.HasDialogs() {
260 u, dialogCmd := a.dialog.Update(msg)
261 a.dialog = u.(dialogs.DialogCmp)
262 cmds = append(cmds, dialogCmd)
263 } else {
264 updated, pageCmd := a.pages[a.currentPage].Update(msg)
265 a.pages[a.currentPage] = updated.(util.Model)
266 cmds = append(cmds, pageCmd)
267 }
268 return a, tea.Batch(cmds...)
269 }
270 s, _ := a.status.Update(msg)
271 a.status = s.(status.StatusCmp)
272 updated, cmd := a.pages[a.currentPage].Update(msg)
273 a.pages[a.currentPage] = updated.(util.Model)
274 if a.dialog.HasDialogs() {
275 u, dialogCmd := a.dialog.Update(msg)
276 a.dialog = u.(dialogs.DialogCmp)
277 cmds = append(cmds, dialogCmd)
278 }
279 cmds = append(cmds, cmd)
280 return a, tea.Batch(cmds...)
281}
282
283// handleWindowResize processes window resize events and updates all components.
284func (a *appModel) handleWindowResize(width, height int) tea.Cmd {
285 var cmds []tea.Cmd
286 if a.showingFullHelp {
287 height -= 5
288 } else {
289 height -= 2
290 }
291 a.width, a.height = width, height
292 // Update status bar
293 s, cmd := a.status.Update(tea.WindowSizeMsg{Width: width, Height: height})
294 a.status = s.(status.StatusCmp)
295 cmds = append(cmds, cmd)
296
297 // Update the current page
298 for p, page := range a.pages {
299 updated, pageCmd := page.Update(tea.WindowSizeMsg{Width: width, Height: height})
300 a.pages[p] = updated.(util.Model)
301 cmds = append(cmds, pageCmd)
302 }
303
304 // Update the dialogs
305 dialog, cmd := a.dialog.Update(tea.WindowSizeMsg{Width: width, Height: height})
306 a.dialog = dialog.(dialogs.DialogCmp)
307 cmds = append(cmds, cmd)
308
309 return tea.Batch(cmds...)
310}
311
312// handleKeyPressMsg processes keyboard input and routes to appropriate handlers.
313func (a *appModel) handleKeyPressMsg(msg tea.KeyPressMsg) tea.Cmd {
314 if a.completions.Open() {
315 // completions
316 keyMap := a.completions.KeyMap()
317 switch {
318 case key.Matches(msg, keyMap.Up), key.Matches(msg, keyMap.Down),
319 key.Matches(msg, keyMap.Select), key.Matches(msg, keyMap.Cancel),
320 key.Matches(msg, keyMap.UpInsert), key.Matches(msg, keyMap.DownInsert):
321 u, cmd := a.completions.Update(msg)
322 a.completions = u.(completions.Completions)
323 return cmd
324 }
325 }
326 switch {
327 // help
328 case key.Matches(msg, a.keyMap.Help):
329 a.status.ToggleFullHelp()
330 a.showingFullHelp = !a.showingFullHelp
331 return a.handleWindowResize(a.wWidth, a.wHeight)
332 // dialogs
333 case key.Matches(msg, a.keyMap.Quit):
334 if a.dialog.ActiveDialogID() == quit.QuitDialogID {
335 return tea.Quit
336 }
337 return util.CmdHandler(dialogs.OpenDialogMsg{
338 Model: quit.NewQuitDialog(),
339 })
340
341 case key.Matches(msg, a.keyMap.Commands):
342 // if the app is not configured show no commands
343 if !a.isConfigured {
344 return nil
345 }
346 if a.dialog.ActiveDialogID() == commands.CommandsDialogID {
347 return util.CmdHandler(dialogs.CloseDialogMsg{})
348 }
349 if a.dialog.HasDialogs() {
350 return nil
351 }
352 return util.CmdHandler(dialogs.OpenDialogMsg{
353 Model: commands.NewCommandDialog(a.selectedSessionID),
354 })
355 case key.Matches(msg, a.keyMap.Sessions):
356 // if the app is not configured show no sessions
357 if !a.isConfigured {
358 return nil
359 }
360 if a.dialog.ActiveDialogID() == sessions.SessionsDialogID {
361 return util.CmdHandler(dialogs.CloseDialogMsg{})
362 }
363 if a.dialog.HasDialogs() && a.dialog.ActiveDialogID() != commands.CommandsDialogID {
364 return nil
365 }
366 var cmds []tea.Cmd
367 if a.dialog.ActiveDialogID() == commands.CommandsDialogID {
368 // If the commands dialog is open, close it first
369 cmds = append(cmds, util.CmdHandler(dialogs.CloseDialogMsg{}))
370 }
371 cmds = append(cmds,
372 func() tea.Msg {
373 allSessions, _ := a.app.Sessions.List(context.Background())
374 return dialogs.OpenDialogMsg{
375 Model: sessions.NewSessionDialogCmp(allSessions, a.selectedSessionID),
376 }
377 },
378 )
379 return tea.Sequence(cmds...)
380 default:
381 if a.dialog.HasDialogs() {
382 u, dialogCmd := a.dialog.Update(msg)
383 a.dialog = u.(dialogs.DialogCmp)
384 return dialogCmd
385 } else {
386 updated, cmd := a.pages[a.currentPage].Update(msg)
387 a.pages[a.currentPage] = updated.(util.Model)
388 return cmd
389 }
390 }
391}
392
393// moveToPage handles navigation between different pages in the application.
394func (a *appModel) moveToPage(pageID page.PageID) tea.Cmd {
395 if a.app.CoderAgent.IsBusy() {
396 // TODO: maybe remove this : For now we don't move to any page if the agent is busy
397 return util.ReportWarn("Agent is busy, please wait...")
398 }
399
400 var cmds []tea.Cmd
401 if _, ok := a.loadedPages[pageID]; !ok {
402 cmd := a.pages[pageID].Init()
403 cmds = append(cmds, cmd)
404 a.loadedPages[pageID] = true
405 }
406 a.previousPage = a.currentPage
407 a.currentPage = pageID
408 if sizable, ok := a.pages[a.currentPage].(layout.Sizeable); ok {
409 cmd := sizable.SetSize(a.width, a.height)
410 cmds = append(cmds, cmd)
411 }
412
413 return tea.Batch(cmds...)
414}
415
416// View renders the complete application interface including pages, dialogs, and overlays.
417func (a *appModel) View() tea.View {
418 var view tea.View
419 t := styles.CurrentTheme()
420 view.BackgroundColor = t.BgBase
421 if a.wWidth < 25 || a.wHeight < 15 {
422 view.Layer = lipgloss.NewCanvas(
423 lipgloss.NewLayer(
424 t.S().Base.Width(a.wWidth).Height(a.wHeight).
425 Align(lipgloss.Center, lipgloss.Center).
426 Render(
427 t.S().Base.
428 Padding(1, 4).
429 Foreground(t.White).
430 BorderStyle(lipgloss.RoundedBorder()).
431 BorderForeground(t.Primary).
432 Render("Window too small!"),
433 ),
434 ),
435 )
436 return view
437 }
438
439 page := a.pages[a.currentPage]
440 if withHelp, ok := page.(core.KeyMapHelp); ok {
441 a.status.SetKeyMap(withHelp.Help())
442 }
443 pageView := page.View()
444 components := []string{
445 pageView,
446 }
447 components = append(components, a.status.View())
448
449 appView := lipgloss.JoinVertical(lipgloss.Top, components...)
450 layers := []*lipgloss.Layer{
451 lipgloss.NewLayer(appView),
452 }
453 if a.dialog.HasDialogs() {
454 layers = append(
455 layers,
456 a.dialog.GetLayers()...,
457 )
458 }
459
460 var cursor *tea.Cursor
461 if v, ok := page.(util.Cursor); ok {
462 cursor = v.Cursor()
463 // Hide the cursor if it's positioned outside the textarea
464 statusHeight := a.height - strings.Count(pageView, "\n") + 1
465 if cursor != nil && cursor.Y+statusHeight+chat.EditorHeight-2 <= a.height { // 2 for the top and bottom app padding
466 cursor = nil
467 }
468 }
469 activeView := a.dialog.ActiveModel()
470 if activeView != nil {
471 cursor = nil // Reset cursor if a dialog is active unless it implements util.Cursor
472 if v, ok := activeView.(util.Cursor); ok {
473 cursor = v.Cursor()
474 }
475 }
476
477 if a.completions.Open() && cursor != nil {
478 cmp := a.completions.View()
479 x, y := a.completions.Position()
480 layers = append(
481 layers,
482 lipgloss.NewLayer(cmp).X(x).Y(y),
483 )
484 }
485
486 canvas := lipgloss.NewCanvas(
487 layers...,
488 )
489
490 view.Layer = canvas
491 view.Cursor = cursor
492 return view
493}
494
495// New creates and initializes a new TUI application model.
496func New(app *app.App, initialPrompt string) tea.Model {
497 chatPage := chat.New(app, initialPrompt)
498 keyMap := DefaultKeyMap()
499 keyMap.pageBindings = chatPage.Bindings()
500
501 model := &appModel{
502 currentPage: chat.ChatPageID,
503 app: app,
504 status: status.NewStatusCmp(),
505 loadedPages: make(map[page.PageID]bool),
506 keyMap: keyMap,
507
508 pages: map[page.PageID]util.Model{
509 chat.ChatPageID: chatPage,
510 },
511
512 dialog: dialogs.NewDialogCmp(),
513 completions: completions.New(),
514 }
515
516 return model
517}