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.DialogID {
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
471 dialog, cmd := a.dialog.Update(tea.WindowSizeMsg{Width: width, Height: height})
472 if model, ok := dialog.(dialogs.DialogCmp); ok {
473 a.dialog = model
474 }
475
476 cmds = append(cmds, cmd)
477
478 return tea.Batch(cmds...)
479}
480
481// handleKeyPressMsg processes keyboard input and routes to appropriate handlers.
482func (a *appModel) handleKeyPressMsg(msg tea.KeyPressMsg) tea.Cmd {
483 // Check this first as the user should be able to quit no matter what.
484 if key.Matches(msg, a.keyMap.Quit) {
485 if a.dialog.ActiveDialogID() == quit.QuitDialogID {
486 return tea.Quit
487 }
488 return util.CmdHandler(dialogs.OpenDialogMsg{
489 Model: quit.NewQuitDialog(),
490 })
491 }
492
493 if a.completions.Open() {
494 // completions
495 keyMap := a.completions.KeyMap()
496 switch {
497 case key.Matches(msg, keyMap.Up), key.Matches(msg, keyMap.Down),
498 key.Matches(msg, keyMap.Select), key.Matches(msg, keyMap.Cancel),
499 key.Matches(msg, keyMap.UpInsert), key.Matches(msg, keyMap.DownInsert):
500 u, cmd := a.completions.Update(msg)
501 a.completions = u.(completions.Completions)
502 return cmd
503 }
504 }
505 if a.dialog.HasDialogs() {
506 u, dialogCmd := a.dialog.Update(msg)
507 a.dialog = u.(dialogs.DialogCmp)
508 return dialogCmd
509 }
510 switch {
511 // help
512 case key.Matches(msg, a.keyMap.Help):
513 a.status.ToggleFullHelp()
514 a.showingFullHelp = !a.showingFullHelp
515 return a.handleWindowResize(a.wWidth, a.wHeight)
516 // dialogs
517 case key.Matches(msg, a.keyMap.Commands):
518 // if the app is not configured show no commands
519 if !a.isConfigured {
520 return nil
521 }
522 if a.dialog.ActiveDialogID() == commands.CommandsDialogID {
523 return util.CmdHandler(dialogs.CloseDialogMsg{})
524 }
525 if a.dialog.HasDialogs() {
526 return nil
527 }
528 return util.CmdHandler(dialogs.OpenDialogMsg{
529 Model: commands.NewCommandDialog(a.app.Context(), a.selectedSessionID),
530 })
531 case key.Matches(msg, a.keyMap.Models):
532 // if the app is not configured show no models
533 if !a.isConfigured {
534 return nil
535 }
536 if a.dialog.ActiveDialogID() == models.ModelsDialogID {
537 return util.CmdHandler(dialogs.CloseDialogMsg{})
538 }
539 if a.dialog.HasDialogs() {
540 return nil
541 }
542 return util.CmdHandler(dialogs.OpenDialogMsg{
543 Model: models.NewModelDialogCmp(),
544 })
545 case key.Matches(msg, a.keyMap.Sessions):
546 // if the app is not configured show no sessions
547 if !a.isConfigured {
548 return nil
549 }
550 if a.dialog.ActiveDialogID() == sessions.SessionsDialogID {
551 return util.CmdHandler(dialogs.CloseDialogMsg{})
552 }
553 if a.dialog.HasDialogs() && a.dialog.ActiveDialogID() != commands.CommandsDialogID {
554 return nil
555 }
556 var cmds []tea.Cmd
557 cmds = append(cmds,
558 func() tea.Msg {
559 allSessions, _ := a.app.Sessions.List(context.Background())
560 return dialogs.OpenDialogMsg{
561 Model: sessions.NewSessionDialogCmp(allSessions, a.selectedSessionID),
562 }
563 },
564 )
565 return tea.Sequence(cmds...)
566 case key.Matches(msg, a.keyMap.Suspend):
567 if a.app.AgentCoordinator != nil && a.app.AgentCoordinator.IsBusy() {
568 return util.ReportWarn("Agent is busy, please wait...")
569 }
570 return tea.Suspend
571 default:
572 item, ok := a.pages[a.currentPage]
573 if !ok {
574 return nil
575 }
576
577 updated, cmd := item.Update(msg)
578 a.pages[a.currentPage] = updated
579 return cmd
580 }
581}
582
583// moveToPage handles navigation between different pages in the application.
584func (a *appModel) moveToPage(pageID page.PageID) tea.Cmd {
585 if a.app.AgentCoordinator.IsBusy() {
586 // TODO: maybe remove this : For now we don't move to any page if the agent is busy
587 return util.ReportWarn("Agent is busy, please wait...")
588 }
589
590 var cmds []tea.Cmd
591 if _, ok := a.loadedPages[pageID]; !ok {
592 cmd := a.pages[pageID].Init()
593 cmds = append(cmds, cmd)
594 a.loadedPages[pageID] = true
595 }
596 a.previousPage = a.currentPage
597 a.currentPage = pageID
598 if sizable, ok := a.pages[a.currentPage].(layout.Sizeable); ok {
599 cmd := sizable.SetSize(a.width, a.height)
600 cmds = append(cmds, cmd)
601 }
602
603 return tea.Batch(cmds...)
604}
605
606// View renders the complete application interface including pages, dialogs, and overlays.
607func (a *appModel) View() tea.View {
608 var view tea.View
609 t := styles.CurrentTheme()
610 view.AltScreen = true
611 view.MouseMode = tea.MouseModeCellMotion
612 view.BackgroundColor = t.BgBase
613 if a.wWidth < 25 || a.wHeight < 15 {
614 view.Content = t.S().Base.Width(a.wWidth).Height(a.wHeight).
615 Align(lipgloss.Center, lipgloss.Center).
616 Render(t.S().Base.
617 Padding(1, 4).
618 Foreground(t.White).
619 BorderStyle(lipgloss.RoundedBorder()).
620 BorderForeground(t.Primary).
621 Render("Window too small!"),
622 )
623 return view
624 }
625
626 page := a.pages[a.currentPage]
627 if withHelp, ok := page.(core.KeyMapHelp); ok {
628 a.status.SetKeyMap(withHelp.Help())
629 }
630 pageView := page.View()
631 components := []string{
632 pageView,
633 }
634 components = append(components, a.status.View())
635
636 appView := lipgloss.JoinVertical(lipgloss.Top, components...)
637 layers := []*lipgloss.Layer{
638 lipgloss.NewLayer(appView),
639 }
640 if a.dialog.HasDialogs() {
641 layers = append(
642 layers,
643 a.dialog.GetLayers()...,
644 )
645 }
646
647 var cursor *tea.Cursor
648 if v, ok := page.(util.Cursor); ok {
649 cursor = v.Cursor()
650 // Hide the cursor if it's positioned outside the textarea
651 statusHeight := a.height - strings.Count(pageView, "\n") + 1
652 if cursor != nil && cursor.Y+statusHeight+chat.EditorHeight-2 <= a.height { // 2 for the top and bottom app padding
653 cursor = nil
654 }
655 }
656 activeView := a.dialog.ActiveModel()
657 if activeView != nil {
658 cursor = nil // Reset cursor if a dialog is active unless it implements util.Cursor
659 if v, ok := activeView.(util.Cursor); ok {
660 cursor = v.Cursor()
661 }
662 }
663
664 if a.completions.Open() && cursor != nil {
665 cmp := a.completions.View()
666 x, y := a.completions.Position()
667 layers = append(
668 layers,
669 lipgloss.NewLayer(cmp).X(x).Y(y),
670 )
671 }
672
673 comp := lipgloss.NewCompositor(layers...)
674 view.Content = comp.Render()
675 view.Cursor = cursor
676
677 if a.sendProgressBar && a.app != nil && a.app.AgentCoordinator != nil && a.app.AgentCoordinator.IsBusy() {
678 // HACK: use a random percentage to prevent ghostty from hiding it
679 // after a timeout.
680 view.ProgressBar = tea.NewProgressBar(tea.ProgressBarIndeterminate, rand.Intn(100))
681 }
682 return view
683}
684
685func (a *appModel) handleStateChanged(ctx context.Context) tea.Cmd {
686 return func() tea.Msg {
687 a.app.UpdateAgentModel(ctx)
688 return nil
689 }
690}
691
692func handleMCPPromptsEvent(ctx context.Context, name string) tea.Cmd {
693 return func() tea.Msg {
694 mcp.RefreshPrompts(ctx, name)
695 return nil
696 }
697}
698
699func handleMCPToolsEvent(ctx context.Context, name string) tea.Cmd {
700 return func() tea.Msg {
701 mcp.RefreshTools(ctx, name)
702 return nil
703 }
704}
705
706// New creates and initializes a new TUI application model.
707func New(app *app.App) *appModel {
708 chatPage := chat.New(app)
709 keyMap := DefaultKeyMap()
710 keyMap.pageBindings = chatPage.Bindings()
711
712 model := &appModel{
713 currentPage: chat.ChatPageID,
714 app: app,
715 status: status.NewStatusCmp(),
716 loadedPages: make(map[page.PageID]bool),
717 keyMap: keyMap,
718
719 pages: map[page.PageID]util.Model{
720 chat.ChatPageID: chatPage,
721 },
722
723 dialog: dialogs.NewDialogCmp(),
724 completions: completions.New(),
725 }
726
727 return model
728}