tui.go

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