1package tui
2
3import (
4 "context"
5 "fmt"
6 "math/rand"
7 "strings"
8 "time"
9
10 "github.com/charmbracelet/bubbles/v2/key"
11 tea "github.com/charmbracelet/bubbletea/v2"
12 "github.com/charmbracelet/crush/internal/app"
13 "github.com/charmbracelet/crush/internal/config"
14 "github.com/charmbracelet/crush/internal/event"
15 "github.com/charmbracelet/crush/internal/llm/agent"
16 "github.com/charmbracelet/crush/internal/permission"
17 "github.com/charmbracelet/crush/internal/pubsub"
18 cmpChat "github.com/charmbracelet/crush/internal/tui/components/chat"
19 "github.com/charmbracelet/crush/internal/tui/components/chat/splash"
20 "github.com/charmbracelet/crush/internal/tui/components/completions"
21 "github.com/charmbracelet/crush/internal/tui/components/core"
22 "github.com/charmbracelet/crush/internal/tui/components/core/layout"
23 "github.com/charmbracelet/crush/internal/tui/components/core/status"
24 "github.com/charmbracelet/crush/internal/tui/components/dialogs"
25 "github.com/charmbracelet/crush/internal/tui/components/dialogs/commands"
26 "github.com/charmbracelet/crush/internal/tui/components/dialogs/compact"
27 "github.com/charmbracelet/crush/internal/tui/components/dialogs/filepicker"
28 "github.com/charmbracelet/crush/internal/tui/components/dialogs/models"
29 "github.com/charmbracelet/crush/internal/tui/components/dialogs/permissions"
30 "github.com/charmbracelet/crush/internal/tui/components/dialogs/quit"
31 "github.com/charmbracelet/crush/internal/tui/components/dialogs/sessions"
32 "github.com/charmbracelet/crush/internal/tui/page"
33 "github.com/charmbracelet/crush/internal/tui/page/chat"
34 "github.com/charmbracelet/crush/internal/tui/styles"
35 "github.com/charmbracelet/crush/internal/tui/util"
36 "github.com/charmbracelet/lipgloss/v2"
37)
38
39var lastMouseEvent time.Time
40
41func MouseEventFilter(m tea.Model, msg tea.Msg) tea.Msg {
42 switch msg.(type) {
43 case tea.MouseWheelMsg, tea.MouseMotionMsg:
44 now := time.Now()
45 // trackpad is sending too many requests
46 if now.Sub(lastMouseEvent) < 15*time.Millisecond {
47 return nil
48 }
49 lastMouseEvent = now
50 }
51 return msg
52}
53
54// appModel represents the main application model that manages pages, dialogs, and UI state.
55type appModel struct {
56 wWidth, wHeight int // Window dimensions
57 width, height int
58 keyMap KeyMap
59
60 currentPage page.PageID
61 previousPage page.PageID
62 pages map[page.PageID]util.Model
63 loadedPages map[page.PageID]bool
64
65 // Status
66 status status.StatusCmp
67 showingFullHelp bool
68
69 app *app.App
70
71 dialog dialogs.DialogCmp
72 completions completions.Completions
73 isConfigured bool
74
75 // Chat Page Specific
76 selectedSessionID string // The ID of the currently selected session
77}
78
79// Init initializes the application model and returns initial commands.
80func (a appModel) Init() tea.Cmd {
81 item, ok := a.pages[a.currentPage]
82 if !ok {
83 return nil
84 }
85
86 var cmds []tea.Cmd
87 cmd := item.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 return tea.Batch(cmds...)
95}
96
97// Update handles incoming messages and updates the application state.
98func (a *appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
99 var cmds []tea.Cmd
100 var cmd tea.Cmd
101 a.isConfigured = config.HasInitialDataConfig()
102
103 switch msg := msg.(type) {
104 case tea.KeyboardEnhancementsMsg:
105 for id, page := range a.pages {
106 m, pageCmd := page.Update(msg)
107 a.pages[id] = m
108
109 if pageCmd != nil {
110 cmds = append(cmds, pageCmd)
111 }
112 }
113 return a, tea.Batch(cmds...)
114 case tea.WindowSizeMsg:
115 a.wWidth, a.wHeight = msg.Width, msg.Height
116 a.completions.Update(msg)
117 return a, a.handleWindowResize(msg.Width, msg.Height)
118
119 // Completions messages
120 case completions.OpenCompletionsMsg, completions.FilterCompletionsMsg,
121 completions.CloseCompletionsMsg, completions.RepositionCompletionsMsg:
122 u, completionCmd := a.completions.Update(msg)
123 if model, ok := u.(completions.Completions); ok {
124 a.completions = model
125 }
126
127 return a, completionCmd
128
129 // Dialog messages
130 case dialogs.OpenDialogMsg, dialogs.CloseDialogMsg:
131 u, completionCmd := a.completions.Update(completions.CloseCompletionsMsg{})
132 a.completions = u.(completions.Completions)
133 u, dialogCmd := a.dialog.Update(msg)
134 a.dialog = u.(dialogs.DialogCmp)
135 return a, tea.Batch(completionCmd, dialogCmd)
136 case commands.ShowArgumentsDialogMsg:
137 return a, util.CmdHandler(
138 dialogs.OpenDialogMsg{
139 Model: commands.NewCommandArgumentsDialog(
140 msg.CommandID,
141 msg.Content,
142 msg.ArgNames,
143 ),
144 },
145 )
146 // Page change messages
147 case page.PageChangeMsg:
148 return a, a.moveToPage(msg.ID)
149
150 // Status Messages
151 case util.InfoMsg, util.ClearStatusMsg:
152 s, statusCmd := a.status.Update(msg)
153 a.status = s.(status.StatusCmp)
154 cmds = append(cmds, statusCmd)
155 return a, tea.Batch(cmds...)
156
157 // Session
158 case cmpChat.SessionSelectedMsg:
159 a.selectedSessionID = msg.ID
160 case cmpChat.SessionClearedMsg:
161 a.selectedSessionID = ""
162 // Commands
163 case commands.SwitchSessionsMsg:
164 return a, func() tea.Msg {
165 allSessions, _ := a.app.Sessions.List(context.Background())
166 return dialogs.OpenDialogMsg{
167 Model: sessions.NewSessionDialogCmp(allSessions, a.selectedSessionID),
168 }
169 }
170
171 case commands.SwitchModelMsg:
172 return a, util.CmdHandler(
173 dialogs.OpenDialogMsg{
174 Model: models.NewModelDialogCmp(),
175 },
176 )
177 // Compact
178 case commands.CompactMsg:
179 return a, util.CmdHandler(dialogs.OpenDialogMsg{
180 Model: compact.NewCompactDialogCmp(a.app.CoderAgent, msg.SessionID, true),
181 })
182 case commands.QuitMsg:
183 return a, util.CmdHandler(dialogs.OpenDialogMsg{
184 Model: quit.NewQuitDialog(),
185 })
186 case commands.ToggleYoloModeMsg:
187 a.app.Permissions.SetSkipRequests(!a.app.Permissions.SkipRequests())
188 case commands.ToggleHelpMsg:
189 a.status.ToggleFullHelp()
190 a.showingFullHelp = !a.showingFullHelp
191 return a, a.handleWindowResize(a.wWidth, a.wHeight)
192 // Model Switch
193 case models.ModelSelectedMsg:
194 if a.app.CoderAgent.IsBusy() {
195 return a, util.ReportWarn("Agent is busy, please wait...")
196 }
197
198 config.Get().UpdatePreferredModel(msg.ModelType, msg.Model)
199
200 // Update the agent with the new model/provider configuration
201 if err := a.app.UpdateAgentModel(); err != nil {
202 return a, util.ReportError(fmt.Errorf("model changed to %s but failed to update agent: %v", msg.Model.Model, err))
203 }
204
205 modelTypeName := "large"
206 if msg.ModelType == config.SelectedModelTypeSmall {
207 modelTypeName = "small"
208 }
209 return a, util.ReportInfo(fmt.Sprintf("%s model changed to %s", modelTypeName, msg.Model.Model))
210
211 // File Picker
212 case commands.OpenFilePickerMsg:
213 event.FilePickerOpened()
214
215 if a.dialog.ActiveDialogID() == filepicker.FilePickerID {
216 // If the commands dialog is already open, close it
217 return a, util.CmdHandler(dialogs.CloseDialogMsg{})
218 }
219 return a, util.CmdHandler(dialogs.OpenDialogMsg{
220 Model: filepicker.NewFilePickerCmp(a.app.Config().WorkingDir()),
221 })
222 // Permissions
223 case pubsub.Event[permission.PermissionNotification]:
224 item, ok := a.pages[a.currentPage]
225 if !ok {
226 return a, nil
227 }
228
229 // Forward to view.
230 updated, itemCmd := item.Update(msg)
231 a.pages[a.currentPage] = updated
232
233 return a, itemCmd
234 case pubsub.Event[permission.PermissionRequest]:
235 return a, util.CmdHandler(dialogs.OpenDialogMsg{
236 Model: permissions.NewPermissionDialogCmp(msg.Payload, &permissions.Options{
237 DiffMode: config.Get().Options.TUI.DiffMode,
238 }),
239 })
240 case permissions.PermissionResponseMsg:
241 switch msg.Action {
242 case permissions.PermissionAllow:
243 a.app.Permissions.Grant(msg.Permission)
244 case permissions.PermissionAllowForSession:
245 a.app.Permissions.GrantPersistent(msg.Permission)
246 case permissions.PermissionDeny:
247 a.app.Permissions.Deny(msg.Permission)
248 }
249 return a, nil
250 // Agent Events
251 case pubsub.Event[agent.AgentEvent]:
252 payload := msg.Payload
253
254 // Forward agent events to dialogs
255 if a.dialog.HasDialogs() && a.dialog.ActiveDialogID() == compact.CompactDialogID {
256 u, dialogCmd := a.dialog.Update(payload)
257 if model, ok := u.(dialogs.DialogCmp); ok {
258 a.dialog = model
259 }
260
261 cmds = append(cmds, dialogCmd)
262 }
263
264 // Handle auto-compact logic
265 if payload.Done && payload.Type == agent.AgentEventTypeResponse && a.selectedSessionID != "" {
266 // Get current session to check token usage
267 session, err := a.app.Sessions.Get(context.Background(), a.selectedSessionID)
268 if err == nil {
269 model := a.app.CoderAgent.Model()
270 contextWindow := model.ContextWindow
271 tokens := session.CompletionTokens + session.PromptTokens
272 if (tokens >= int64(float64(contextWindow)*0.95)) && !config.Get().Options.DisableAutoSummarize { // Show compact confirmation dialog
273 cmds = append(cmds, util.CmdHandler(dialogs.OpenDialogMsg{
274 Model: compact.NewCompactDialogCmp(a.app.CoderAgent, a.selectedSessionID, false),
275 }))
276 }
277 }
278 }
279
280 return a, tea.Batch(cmds...)
281 // Update Available
282 case pubsub.UpdateAvailableMsg:
283 // Show update notification in status bar
284 statusMsg := fmt.Sprintf("🎉 New Crush version available: v%s → v%s.", msg.CurrentVersion, msg.LatestVersion)
285 s, statusCmd := a.status.Update(util.InfoMsg{
286 Type: util.InfoTypeInfo,
287 Msg: statusMsg,
288 TTL: 30 * time.Second,
289 })
290 a.status = s.(status.StatusCmp)
291 return a, statusCmd
292 case splash.OnboardingCompleteMsg:
293 item, ok := a.pages[a.currentPage]
294 if !ok {
295 return a, nil
296 }
297
298 a.isConfigured = config.HasInitialDataConfig()
299 updated, pageCmd := item.Update(msg)
300 a.pages[a.currentPage] = updated
301
302 cmds = append(cmds, pageCmd)
303 return a, tea.Batch(cmds...)
304
305 case tea.KeyPressMsg:
306 return a, a.handleKeyPressMsg(msg)
307
308 case tea.MouseWheelMsg:
309 if a.dialog.HasDialogs() {
310 u, dialogCmd := a.dialog.Update(msg)
311 a.dialog = u.(dialogs.DialogCmp)
312 cmds = append(cmds, dialogCmd)
313 } else {
314 item, ok := a.pages[a.currentPage]
315 if !ok {
316 return a, nil
317 }
318
319 updated, pageCmd := item.Update(msg)
320 a.pages[a.currentPage] = updated
321
322 cmds = append(cmds, pageCmd)
323 }
324 return a, tea.Batch(cmds...)
325 case tea.PasteMsg:
326 if a.dialog.HasDialogs() {
327 u, dialogCmd := a.dialog.Update(msg)
328 if model, ok := u.(dialogs.DialogCmp); ok {
329 a.dialog = model
330 }
331
332 cmds = append(cmds, dialogCmd)
333 } else {
334 item, ok := a.pages[a.currentPage]
335 if !ok {
336 return a, nil
337 }
338
339 updated, pageCmd := item.Update(msg)
340 a.pages[a.currentPage] = updated
341
342 cmds = append(cmds, pageCmd)
343 }
344 return a, tea.Batch(cmds...)
345 }
346 s, _ := a.status.Update(msg)
347 a.status = s.(status.StatusCmp)
348
349 item, ok := a.pages[a.currentPage]
350 if !ok {
351 return a, nil
352 }
353
354 updated, cmd := item.Update(msg)
355 a.pages[a.currentPage] = updated
356
357 if a.dialog.HasDialogs() {
358 u, dialogCmd := a.dialog.Update(msg)
359 if model, ok := u.(dialogs.DialogCmp); ok {
360 a.dialog = model
361 }
362
363 cmds = append(cmds, dialogCmd)
364 }
365 cmds = append(cmds, cmd)
366 return a, tea.Batch(cmds...)
367}
368
369// handleWindowResize processes window resize events and updates all components.
370func (a *appModel) handleWindowResize(width, height int) tea.Cmd {
371 var cmds []tea.Cmd
372
373 // TODO: clean up these magic numbers.
374 if a.showingFullHelp {
375 height -= 5
376 } else {
377 height -= 2
378 }
379
380 a.width, a.height = width, height
381 // Update status bar
382 s, cmd := a.status.Update(tea.WindowSizeMsg{Width: width, Height: height})
383 if model, ok := s.(status.StatusCmp); ok {
384 a.status = model
385 }
386 cmds = append(cmds, cmd)
387
388 // Update the current view.
389 for p, page := range a.pages {
390 updated, pageCmd := page.Update(tea.WindowSizeMsg{Width: width, Height: height})
391 a.pages[p] = updated
392
393 cmds = append(cmds, pageCmd)
394 }
395
396 // Update the dialogs
397 dialog, cmd := a.dialog.Update(tea.WindowSizeMsg{Width: width, Height: height})
398 if model, ok := dialog.(dialogs.DialogCmp); ok {
399 a.dialog = model
400 }
401
402 cmds = append(cmds, cmd)
403
404 return tea.Batch(cmds...)
405}
406
407// handleKeyPressMsg processes keyboard input and routes to appropriate handlers.
408func (a *appModel) handleKeyPressMsg(msg tea.KeyPressMsg) tea.Cmd {
409 // Check this first as the user should be able to quit no matter what.
410 if key.Matches(msg, a.keyMap.Quit) {
411 if a.dialog.ActiveDialogID() == quit.QuitDialogID {
412 return tea.Quit
413 }
414 return util.CmdHandler(dialogs.OpenDialogMsg{
415 Model: quit.NewQuitDialog(),
416 })
417 }
418
419 if a.completions.Open() {
420 // completions
421 keyMap := a.completions.KeyMap()
422 switch {
423 case key.Matches(msg, keyMap.Up), key.Matches(msg, keyMap.Down),
424 key.Matches(msg, keyMap.Select), key.Matches(msg, keyMap.Cancel),
425 key.Matches(msg, keyMap.UpInsert), key.Matches(msg, keyMap.DownInsert):
426 u, cmd := a.completions.Update(msg)
427 a.completions = u.(completions.Completions)
428 return cmd
429 }
430 }
431 if a.dialog.HasDialogs() {
432 u, dialogCmd := a.dialog.Update(msg)
433 a.dialog = u.(dialogs.DialogCmp)
434 return dialogCmd
435 }
436 switch {
437 // help
438 case key.Matches(msg, a.keyMap.Help):
439 a.status.ToggleFullHelp()
440 a.showingFullHelp = !a.showingFullHelp
441 return a.handleWindowResize(a.wWidth, a.wHeight)
442 // dialogs
443 case key.Matches(msg, a.keyMap.Commands):
444 // if the app is not configured show no commands
445 if !a.isConfigured {
446 return nil
447 }
448 if a.dialog.ActiveDialogID() == commands.CommandsDialogID {
449 return util.CmdHandler(dialogs.CloseDialogMsg{})
450 }
451 if a.dialog.HasDialogs() {
452 return nil
453 }
454 return util.CmdHandler(dialogs.OpenDialogMsg{
455 Model: commands.NewCommandDialog(a.selectedSessionID),
456 })
457 case key.Matches(msg, a.keyMap.Sessions):
458 // if the app is not configured show no sessions
459 if !a.isConfigured {
460 return nil
461 }
462 if a.dialog.ActiveDialogID() == sessions.SessionsDialogID {
463 return util.CmdHandler(dialogs.CloseDialogMsg{})
464 }
465 if a.dialog.HasDialogs() && a.dialog.ActiveDialogID() != commands.CommandsDialogID {
466 return nil
467 }
468 var cmds []tea.Cmd
469 if a.dialog.ActiveDialogID() == commands.CommandsDialogID {
470 // If the commands dialog is open, close it first
471 cmds = append(cmds, util.CmdHandler(dialogs.CloseDialogMsg{}))
472 }
473 cmds = append(cmds,
474 func() tea.Msg {
475 allSessions, _ := a.app.Sessions.List(context.Background())
476 return dialogs.OpenDialogMsg{
477 Model: sessions.NewSessionDialogCmp(allSessions, a.selectedSessionID),
478 }
479 },
480 )
481 return tea.Sequence(cmds...)
482 case key.Matches(msg, a.keyMap.Suspend):
483 if a.app.CoderAgent != nil && a.app.CoderAgent.IsBusy() {
484 return util.ReportWarn("Agent is busy, please wait...")
485 }
486 return tea.Suspend
487 default:
488 item, ok := a.pages[a.currentPage]
489 if !ok {
490 return nil
491 }
492
493 updated, cmd := item.Update(msg)
494 a.pages[a.currentPage] = updated
495 return cmd
496 }
497}
498
499// moveToPage handles navigation between different pages in the application.
500func (a *appModel) moveToPage(pageID page.PageID) tea.Cmd {
501 if a.app.CoderAgent.IsBusy() {
502 // TODO: maybe remove this : For now we don't move to any page if the agent is busy
503 return util.ReportWarn("Agent is busy, please wait...")
504 }
505
506 var cmds []tea.Cmd
507 if _, ok := a.loadedPages[pageID]; !ok {
508 cmd := a.pages[pageID].Init()
509 cmds = append(cmds, cmd)
510 a.loadedPages[pageID] = true
511 }
512 a.previousPage = a.currentPage
513 a.currentPage = pageID
514 if sizable, ok := a.pages[a.currentPage].(layout.Sizeable); ok {
515 cmd := sizable.SetSize(a.width, a.height)
516 cmds = append(cmds, cmd)
517 }
518
519 return tea.Batch(cmds...)
520}
521
522// View renders the complete application interface including pages, dialogs, and overlays.
523func (a *appModel) View() tea.View {
524 var view tea.View
525 t := styles.CurrentTheme()
526 view.BackgroundColor = t.BgBase
527 if a.wWidth < 25 || a.wHeight < 15 {
528 view.Layer = lipgloss.NewCanvas(
529 lipgloss.NewLayer(
530 t.S().Base.Width(a.wWidth).Height(a.wHeight).
531 Align(lipgloss.Center, lipgloss.Center).
532 Render(
533 t.S().Base.
534 Padding(1, 4).
535 Foreground(t.White).
536 BorderStyle(lipgloss.RoundedBorder()).
537 BorderForeground(t.Primary).
538 Render("Window too small!"),
539 ),
540 ),
541 )
542 return view
543 }
544
545 page := a.pages[a.currentPage]
546 if withHelp, ok := page.(core.KeyMapHelp); ok {
547 a.status.SetKeyMap(withHelp.Help())
548 }
549 pageView := page.View()
550 components := []string{
551 pageView,
552 }
553 components = append(components, a.status.View())
554
555 appView := lipgloss.JoinVertical(lipgloss.Top, components...)
556 layers := []*lipgloss.Layer{
557 lipgloss.NewLayer(appView),
558 }
559 if a.dialog.HasDialogs() {
560 layers = append(
561 layers,
562 a.dialog.GetLayers()...,
563 )
564 }
565
566 var cursor *tea.Cursor
567 if v, ok := page.(util.Cursor); ok {
568 cursor = v.Cursor()
569 // Hide the cursor if it's positioned outside the textarea
570 statusHeight := a.height - strings.Count(pageView, "\n") + 1
571 if cursor != nil && cursor.Y+statusHeight+chat.EditorHeight-2 <= a.height { // 2 for the top and bottom app padding
572 cursor = nil
573 }
574 }
575 activeView := a.dialog.ActiveModel()
576 if activeView != nil {
577 cursor = nil // Reset cursor if a dialog is active unless it implements util.Cursor
578 if v, ok := activeView.(util.Cursor); ok {
579 cursor = v.Cursor()
580 }
581 }
582
583 if a.completions.Open() && cursor != nil {
584 cmp := a.completions.View()
585 x, y := a.completions.Position()
586 layers = append(
587 layers,
588 lipgloss.NewLayer(cmp).X(x).Y(y),
589 )
590 }
591
592 canvas := lipgloss.NewCanvas(
593 layers...,
594 )
595
596 view.Layer = canvas
597 view.Cursor = cursor
598 view.MouseMode = tea.MouseModeCellMotion
599 view.AltScreen = true
600 if a.app != nil && a.app.CoderAgent != nil && a.app.CoderAgent.IsBusy() {
601 // HACK: use a random percentage to prevent ghostty from hiding it
602 // after a timeout.
603 view.ProgressBar = tea.NewProgressBar(tea.ProgressBarIndeterminate, rand.Intn(100))
604 }
605 return view
606}
607
608// New creates and initializes a new TUI application model.
609func New(app *app.App) tea.Model {
610 chatPage := chat.New(app)
611 keyMap := DefaultKeyMap()
612 keyMap.pageBindings = chatPage.Bindings()
613
614 model := &appModel{
615 currentPage: chat.ChatPageID,
616 app: app,
617 status: status.NewStatusCmp(),
618 loadedPages: make(map[page.PageID]bool),
619 keyMap: keyMap,
620
621 pages: map[page.PageID]util.Model{
622 chat.ChatPageID: chatPage,
623 },
624
625 dialog: dialogs.NewDialogCmp(),
626 completions: completions.New(),
627 }
628
629 return model
630}