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