tui.go

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