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