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