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