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