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