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