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	"git.secluded.site/crush/internal/agent/tools/mcp"
 16	"git.secluded.site/crush/internal/app"
 17	"git.secluded.site/crush/internal/config"
 18	"git.secluded.site/crush/internal/event"
 19	"git.secluded.site/crush/internal/home"
 20	"git.secluded.site/crush/internal/permission"
 21	"git.secluded.site/crush/internal/pubsub"
 22	cmpChat "git.secluded.site/crush/internal/tui/components/chat"
 23	"git.secluded.site/crush/internal/tui/components/chat/splash"
 24	"git.secluded.site/crush/internal/tui/components/completions"
 25	"git.secluded.site/crush/internal/tui/components/core"
 26	"git.secluded.site/crush/internal/tui/components/core/layout"
 27	"git.secluded.site/crush/internal/tui/components/core/status"
 28	"git.secluded.site/crush/internal/tui/components/dialogs"
 29	"git.secluded.site/crush/internal/tui/components/dialogs/commands"
 30	"git.secluded.site/crush/internal/tui/components/dialogs/filepicker"
 31	"git.secluded.site/crush/internal/tui/components/dialogs/models"
 32	"git.secluded.site/crush/internal/tui/components/dialogs/permissions"
 33	"git.secluded.site/crush/internal/tui/components/dialogs/quit"
 34	"git.secluded.site/crush/internal/tui/components/dialogs/sessions"
 35	"git.secluded.site/crush/internal/tui/page"
 36	"git.secluded.site/crush/internal/tui/page/chat"
 37	"git.secluded.site/crush/internal/tui/styles"
 38	"git.secluded.site/crush/internal/tui/util"
 39	xstrings "github.com/charmbracelet/x/exp/strings"
 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 xstrings.ContainsAnyOf(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	// Permissions
308	case pubsub.Event[permission.PermissionNotification]:
309		item, ok := a.pages[a.currentPage]
310		if !ok {
311			return a, nil
312		}
313
314		// Forward to view.
315		updated, itemCmd := item.Update(msg)
316		a.pages[a.currentPage] = updated
317
318		return a, itemCmd
319	case pubsub.Event[permission.PermissionRequest]:
320		return a, util.CmdHandler(dialogs.OpenDialogMsg{
321			Model: permissions.NewPermissionDialogCmp(msg.Payload, &permissions.Options{
322				DiffMode: config.Get().Options.TUI.DiffMode,
323			}),
324		})
325	case permissions.PermissionResponseMsg:
326		switch msg.Action {
327		case permissions.PermissionAllow:
328			a.app.Permissions.Grant(msg.Permission)
329		case permissions.PermissionAllowForSession:
330			a.app.Permissions.GrantPersistent(msg.Permission)
331		case permissions.PermissionDeny:
332			a.app.Permissions.Deny(msg.Permission)
333		}
334		return a, nil
335	case splash.OnboardingCompleteMsg:
336		item, ok := a.pages[a.currentPage]
337		if !ok {
338			return a, nil
339		}
340
341		a.isConfigured = config.HasInitialDataConfig()
342		updated, pageCmd := item.Update(msg)
343		a.pages[a.currentPage] = updated
344
345		cmds = append(cmds, pageCmd)
346		return a, tea.Batch(cmds...)
347
348	case tea.KeyPressMsg:
349		return a, a.handleKeyPressMsg(msg)
350
351	case tea.MouseWheelMsg:
352		if a.dialog.HasDialogs() {
353			u, dialogCmd := a.dialog.Update(msg)
354			a.dialog = u.(dialogs.DialogCmp)
355			cmds = append(cmds, dialogCmd)
356		} else {
357			item, ok := a.pages[a.currentPage]
358			if !ok {
359				return a, nil
360			}
361
362			updated, pageCmd := item.Update(msg)
363			a.pages[a.currentPage] = updated
364
365			cmds = append(cmds, pageCmd)
366		}
367		return a, tea.Batch(cmds...)
368	case tea.PasteMsg:
369		if a.dialog.HasDialogs() {
370			u, dialogCmd := a.dialog.Update(msg)
371			if model, ok := u.(dialogs.DialogCmp); ok {
372				a.dialog = model
373			}
374
375			cmds = append(cmds, dialogCmd)
376		} else {
377			item, ok := a.pages[a.currentPage]
378			if !ok {
379				return a, nil
380			}
381
382			updated, pageCmd := item.Update(msg)
383			a.pages[a.currentPage] = updated
384
385			cmds = append(cmds, pageCmd)
386		}
387		return a, tea.Batch(cmds...)
388	// Update Available
389	case app.UpdateAvailableMsg:
390		// Show update notification in status bar
391		statusMsg := fmt.Sprintf("Crush update available: v%s → v%s.", msg.CurrentVersion, msg.LatestVersion)
392		if msg.IsDevelopment {
393			statusMsg = fmt.Sprintf("This is a development version of Crush. The latest version is v%s.", msg.LatestVersion)
394		}
395		s, statusCmd := a.status.Update(util.InfoMsg{
396			Type: util.InfoTypeUpdate,
397			Msg:  statusMsg,
398			TTL:  10 * time.Second,
399		})
400		a.status = s.(status.StatusCmp)
401		return a, statusCmd
402	}
403	s, _ := a.status.Update(msg)
404	a.status = s.(status.StatusCmp)
405
406	item, ok := a.pages[a.currentPage]
407	if !ok {
408		return a, nil
409	}
410
411	updated, cmd := item.Update(msg)
412	a.pages[a.currentPage] = updated
413
414	if a.dialog.HasDialogs() {
415		u, dialogCmd := a.dialog.Update(msg)
416		if model, ok := u.(dialogs.DialogCmp); ok {
417			a.dialog = model
418		}
419
420		cmds = append(cmds, dialogCmd)
421	}
422	cmds = append(cmds, cmd)
423	return a, tea.Batch(cmds...)
424}
425
426// handleWindowResize processes window resize events and updates all components.
427func (a *appModel) handleWindowResize(width, height int) tea.Cmd {
428	var cmds []tea.Cmd
429
430	// TODO: clean up these magic numbers.
431	if a.showingFullHelp {
432		height -= 5
433	} else {
434		height -= 2
435	}
436
437	a.width, a.height = width, height
438	// Update status bar
439	s, cmd := a.status.Update(tea.WindowSizeMsg{Width: width, Height: height})
440	if model, ok := s.(status.StatusCmp); ok {
441		a.status = model
442	}
443	cmds = append(cmds, cmd)
444
445	// Update the current view.
446	for p, page := range a.pages {
447		updated, pageCmd := page.Update(tea.WindowSizeMsg{Width: width, Height: height})
448		a.pages[p] = updated
449
450		cmds = append(cmds, pageCmd)
451	}
452
453	// Update the dialogs
454	dialog, cmd := a.dialog.Update(tea.WindowSizeMsg{Width: width, Height: height})
455	if model, ok := dialog.(dialogs.DialogCmp); ok {
456		a.dialog = model
457	}
458
459	cmds = append(cmds, cmd)
460
461	return tea.Batch(cmds...)
462}
463
464// handleKeyPressMsg processes keyboard input and routes to appropriate handlers.
465func (a *appModel) handleKeyPressMsg(msg tea.KeyPressMsg) tea.Cmd {
466	// Check this first as the user should be able to quit no matter what.
467	if key.Matches(msg, a.keyMap.Quit) {
468		if a.dialog.ActiveDialogID() == quit.QuitDialogID {
469			return tea.Quit
470		}
471		return util.CmdHandler(dialogs.OpenDialogMsg{
472			Model: quit.NewQuitDialog(),
473		})
474	}
475
476	if a.completions.Open() {
477		// completions
478		keyMap := a.completions.KeyMap()
479		switch {
480		case key.Matches(msg, keyMap.Up), key.Matches(msg, keyMap.Down),
481			key.Matches(msg, keyMap.Select), key.Matches(msg, keyMap.Cancel),
482			key.Matches(msg, keyMap.UpInsert), key.Matches(msg, keyMap.DownInsert):
483			u, cmd := a.completions.Update(msg)
484			a.completions = u.(completions.Completions)
485			return cmd
486		}
487	}
488	if a.dialog.HasDialogs() {
489		u, dialogCmd := a.dialog.Update(msg)
490		a.dialog = u.(dialogs.DialogCmp)
491		return dialogCmd
492	}
493	switch {
494	// help
495	case key.Matches(msg, a.keyMap.Help):
496		a.status.ToggleFullHelp()
497		a.showingFullHelp = !a.showingFullHelp
498		return a.handleWindowResize(a.wWidth, a.wHeight)
499	// dialogs
500	case key.Matches(msg, a.keyMap.Commands):
501		// if the app is not configured show no commands
502		if !a.isConfigured {
503			return nil
504		}
505		if a.dialog.ActiveDialogID() == commands.CommandsDialogID {
506			return util.CmdHandler(dialogs.CloseDialogMsg{})
507		}
508		if a.dialog.HasDialogs() {
509			return nil
510		}
511		return util.CmdHandler(dialogs.OpenDialogMsg{
512			Model: commands.NewCommandDialog(a.selectedSessionID),
513		})
514	case key.Matches(msg, a.keyMap.Models):
515		// if the app is not configured show no models
516		if !a.isConfigured {
517			return nil
518		}
519		if a.dialog.ActiveDialogID() == models.ModelsDialogID {
520			return util.CmdHandler(dialogs.CloseDialogMsg{})
521		}
522		if a.dialog.HasDialogs() {
523			return nil
524		}
525		return util.CmdHandler(dialogs.OpenDialogMsg{
526			Model: models.NewModelDialogCmp(),
527		})
528	case key.Matches(msg, a.keyMap.Sessions):
529		// if the app is not configured show no sessions
530		if !a.isConfigured {
531			return nil
532		}
533		if a.dialog.ActiveDialogID() == sessions.SessionsDialogID {
534			return util.CmdHandler(dialogs.CloseDialogMsg{})
535		}
536		if a.dialog.HasDialogs() && a.dialog.ActiveDialogID() != commands.CommandsDialogID {
537			return nil
538		}
539		var cmds []tea.Cmd
540		cmds = append(cmds,
541			func() tea.Msg {
542				allSessions, _ := a.app.Sessions.List(context.Background())
543				return dialogs.OpenDialogMsg{
544					Model: sessions.NewSessionDialogCmp(allSessions, a.selectedSessionID),
545				}
546			},
547		)
548		return tea.Sequence(cmds...)
549	case key.Matches(msg, a.keyMap.Suspend):
550		if a.app.AgentCoordinator != nil && a.app.AgentCoordinator.IsBusy() {
551			return util.ReportWarn("Agent is busy, please wait...")
552		}
553		return tea.Suspend
554	default:
555		item, ok := a.pages[a.currentPage]
556		if !ok {
557			return nil
558		}
559
560		updated, cmd := item.Update(msg)
561		a.pages[a.currentPage] = updated
562		return cmd
563	}
564}
565
566// moveToPage handles navigation between different pages in the application.
567func (a *appModel) moveToPage(pageID page.PageID) tea.Cmd {
568	if a.app.AgentCoordinator.IsBusy() {
569		// TODO: maybe remove this :  For now we don't move to any page if the agent is busy
570		return util.ReportWarn("Agent is busy, please wait...")
571	}
572
573	var cmds []tea.Cmd
574	if _, ok := a.loadedPages[pageID]; !ok {
575		cmd := a.pages[pageID].Init()
576		cmds = append(cmds, cmd)
577		a.loadedPages[pageID] = true
578	}
579	a.previousPage = a.currentPage
580	a.currentPage = pageID
581	if sizable, ok := a.pages[a.currentPage].(layout.Sizeable); ok {
582		cmd := sizable.SetSize(a.width, a.height)
583		cmds = append(cmds, cmd)
584	}
585
586	return tea.Batch(cmds...)
587}
588
589// View renders the complete application interface including pages, dialogs, and overlays.
590func (a *appModel) View() tea.View {
591	var view tea.View
592	t := styles.CurrentTheme()
593	view.AltScreen = true
594	view.MouseMode = tea.MouseModeCellMotion
595	view.BackgroundColor = t.BgBase
596	view.WindowTitle = "crush " + home.Short(config.Get().WorkingDir())
597	view.ReportFocus = true
598	if a.wWidth < 25 || a.wHeight < 15 {
599		view.Content = t.S().Base.Width(a.wWidth).Height(a.wHeight).
600			Align(lipgloss.Center, lipgloss.Center).
601			Render(t.S().Base.
602				Padding(1, 4).
603				Foreground(t.White).
604				BorderStyle(lipgloss.RoundedBorder()).
605				BorderForeground(t.Primary).
606				Render("Window too small!"),
607			)
608		return view
609	}
610
611	page := a.pages[a.currentPage]
612	if withHelp, ok := page.(core.KeyMapHelp); ok {
613		a.status.SetKeyMap(withHelp.Help())
614	}
615	pageView := page.View()
616	components := []string{
617		pageView,
618	}
619	components = append(components, a.status.View())
620
621	appView := lipgloss.JoinVertical(lipgloss.Top, components...)
622	layers := []*lipgloss.Layer{
623		lipgloss.NewLayer(appView),
624	}
625	if a.dialog.HasDialogs() {
626		layers = append(
627			layers,
628			a.dialog.GetLayers()...,
629		)
630	}
631
632	var cursor *tea.Cursor
633	if v, ok := page.(util.Cursor); ok {
634		cursor = v.Cursor()
635		// Hide the cursor if it's positioned outside the textarea
636		statusHeight := a.height - strings.Count(pageView, "\n") + 1
637		if cursor != nil && cursor.Y+statusHeight+chat.EditorHeight-2 <= a.height { // 2 for the top and bottom app padding
638			cursor = nil
639		}
640	}
641	activeView := a.dialog.ActiveModel()
642	if activeView != nil {
643		cursor = nil // Reset cursor if a dialog is active unless it implements util.Cursor
644		if v, ok := activeView.(util.Cursor); ok {
645			cursor = v.Cursor()
646		}
647	}
648
649	if a.completions.Open() && cursor != nil {
650		cmp := a.completions.View()
651		x, y := a.completions.Position()
652		layers = append(
653			layers,
654			lipgloss.NewLayer(cmp).X(x).Y(y),
655		)
656	}
657
658	comp := lipgloss.NewCompositor(layers...)
659	view.Content = comp.Render()
660	view.Cursor = cursor
661
662	if a.sendProgressBar && a.app != nil && a.app.AgentCoordinator != nil && a.app.AgentCoordinator.IsBusy() {
663		// HACK: use a random percentage to prevent ghostty from hiding it
664		// after a timeout.
665		view.ProgressBar = tea.NewProgressBar(tea.ProgressBarIndeterminate, rand.Intn(100))
666	}
667	return view
668}
669
670func (a *appModel) handleStateChanged(ctx context.Context) tea.Cmd {
671	return func() tea.Msg {
672		a.app.UpdateAgentModel(ctx)
673		return nil
674	}
675}
676
677func handleMCPPromptsEvent(ctx context.Context, name string) tea.Cmd {
678	return func() tea.Msg {
679		mcp.RefreshPrompts(ctx, name)
680		return nil
681	}
682}
683
684func handleMCPToolsEvent(ctx context.Context, name string) tea.Cmd {
685	return func() tea.Msg {
686		mcp.RefreshTools(ctx, name)
687		return nil
688	}
689}
690
691// New creates and initializes a new TUI application model.
692func New(app *app.App) *appModel {
693	chatPage := chat.New(app)
694	keyMap := DefaultKeyMap()
695	keyMap.pageBindings = chatPage.Bindings()
696
697	model := &appModel{
698		currentPage: chat.ChatPageID,
699		app:         app,
700		status:      status.NewStatusCmp(),
701		loadedPages: make(map[page.PageID]bool),
702		keyMap:      keyMap,
703
704		pages: map[page.PageID]util.Model{
705			chat.ChatPageID: chatPage,
706		},
707
708		dialog:      dialogs.NewDialogCmp(),
709		completions: completions.New(),
710	}
711
712	return model
713}