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