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