1package tui
  2
  3import (
  4	"context"
  5	"fmt"
  6
  7	"github.com/charmbracelet/bubbles/v2/key"
  8	tea "github.com/charmbracelet/bubbletea/v2"
  9	"github.com/charmbracelet/crush/internal/app"
 10	"github.com/charmbracelet/crush/internal/config"
 11	"github.com/charmbracelet/crush/internal/llm/agent"
 12	"github.com/charmbracelet/crush/internal/permission"
 13	"github.com/charmbracelet/crush/internal/pubsub"
 14	cmpChat "github.com/charmbracelet/crush/internal/tui/components/chat"
 15	"github.com/charmbracelet/crush/internal/tui/components/chat/splash"
 16	"github.com/charmbracelet/crush/internal/tui/components/completions"
 17	"github.com/charmbracelet/crush/internal/tui/components/core"
 18	"github.com/charmbracelet/crush/internal/tui/components/core/layout"
 19	"github.com/charmbracelet/crush/internal/tui/components/core/status"
 20	"github.com/charmbracelet/crush/internal/tui/components/dialogs"
 21	"github.com/charmbracelet/crush/internal/tui/components/dialogs/commands"
 22	"github.com/charmbracelet/crush/internal/tui/components/dialogs/compact"
 23	"github.com/charmbracelet/crush/internal/tui/components/dialogs/filepicker"
 24	"github.com/charmbracelet/crush/internal/tui/components/dialogs/models"
 25	"github.com/charmbracelet/crush/internal/tui/components/dialogs/permissions"
 26	"github.com/charmbracelet/crush/internal/tui/components/dialogs/quit"
 27	"github.com/charmbracelet/crush/internal/tui/components/dialogs/sessions"
 28	"github.com/charmbracelet/crush/internal/tui/page"
 29	"github.com/charmbracelet/crush/internal/tui/page/chat"
 30	"github.com/charmbracelet/crush/internal/tui/styles"
 31	"github.com/charmbracelet/crush/internal/tui/util"
 32	"github.com/charmbracelet/lipgloss/v2"
 33)
 34
 35// MouseEventFilter filters mouse events based on the current focus state
 36// This is used with tea.WithFilter to prevent mouse scroll events from
 37// interfering with typing performance in the editor
 38func MouseEventFilter(m tea.Model, msg tea.Msg) tea.Msg {
 39	// Only filter mouse events
 40	switch msg.(type) {
 41	case tea.MouseWheelMsg, tea.MouseMotionMsg:
 42		// Check if we have an appModel and if editor is focused
 43		if appModel, ok := m.(*appModel); ok {
 44			if appModel.currentPage == chat.ChatPageID {
 45				if chatPage, ok := appModel.pages[appModel.currentPage].(chat.ChatPage); ok {
 46					// If editor is focused (not chatFocused), filter out mouse wheel/motion events
 47					if !chatPage.IsChatFocused() {
 48						return nil // Filter out the event
 49					}
 50				}
 51			}
 52		}
 53	}
 54	// Allow all other events to pass through
 55	return msg
 56}
 57
 58// appModel represents the main application model that manages pages, dialogs, and UI state.
 59type appModel struct {
 60	wWidth, wHeight int // Window dimensions
 61	width, height   int
 62	keyMap          KeyMap
 63
 64	currentPage  page.PageID
 65	previousPage page.PageID
 66	pages        map[page.PageID]util.Model
 67	loadedPages  map[page.PageID]bool
 68
 69	// Status
 70	status          status.StatusCmp
 71	showingFullHelp bool
 72
 73	app *app.App
 74
 75	dialog       dialogs.DialogCmp
 76	completions  completions.Completions
 77	isConfigured bool
 78
 79	// Chat Page Specific
 80	selectedSessionID string // The ID of the currently selected session
 81}
 82
 83// Init initializes the application model and returns initial commands.
 84func (a appModel) Init() tea.Cmd {
 85	var cmds []tea.Cmd
 86	cmd := a.pages[a.currentPage].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			a.pages[id] = m.(util.Model)
109			if pageCmd != nil {
110				cmds = append(cmds, pageCmd)
111			}
112		}
113		return a, tea.Batch(cmds...)
114	case tea.WindowSizeMsg:
115		a.completions.Update(msg)
116		return a, a.handleWindowResize(msg.Width, msg.Height)
117
118	// Completions messages
119	case completions.OpenCompletionsMsg, completions.FilterCompletionsMsg, completions.CloseCompletionsMsg, completions.RepositionCompletionsMsg:
120		u, completionCmd := a.completions.Update(msg)
121		a.completions = u.(completions.Completions)
122		return a, completionCmd
123
124	// Dialog messages
125	case dialogs.OpenDialogMsg, dialogs.CloseDialogMsg:
126		u, completionCmd := a.completions.Update(completions.CloseCompletionsMsg{})
127		a.completions = u.(completions.Completions)
128		u, dialogCmd := a.dialog.Update(msg)
129		a.dialog = u.(dialogs.DialogCmp)
130		return a, tea.Batch(completionCmd, dialogCmd)
131	case commands.ShowArgumentsDialogMsg:
132		return a, util.CmdHandler(
133			dialogs.OpenDialogMsg{
134				Model: commands.NewCommandArgumentsDialog(
135					msg.CommandID,
136					msg.Content,
137					msg.ArgNames,
138				),
139			},
140		)
141	// Page change messages
142	case page.PageChangeMsg:
143		return a, a.moveToPage(msg.ID)
144
145	// Status Messages
146	case util.InfoMsg, util.ClearStatusMsg:
147		s, statusCmd := a.status.Update(msg)
148		a.status = s.(status.StatusCmp)
149		cmds = append(cmds, statusCmd)
150		return a, tea.Batch(cmds...)
151
152	// Session
153	case cmpChat.SessionSelectedMsg:
154		a.selectedSessionID = msg.ID
155	case cmpChat.SessionClearedMsg:
156		a.selectedSessionID = ""
157	// Commands
158	case commands.SwitchSessionsMsg:
159		return a, func() tea.Msg {
160			allSessions, _ := a.app.Sessions.List(context.Background())
161			return dialogs.OpenDialogMsg{
162				Model: sessions.NewSessionDialogCmp(allSessions, a.selectedSessionID),
163			}
164		}
165
166	case commands.SwitchModelMsg:
167		return a, util.CmdHandler(
168			dialogs.OpenDialogMsg{
169				Model: models.NewModelDialogCmp(),
170			},
171		)
172	// Compact
173	case commands.CompactMsg:
174		return a, util.CmdHandler(dialogs.OpenDialogMsg{
175			Model: compact.NewCompactDialogCmp(a.app.CoderAgent, msg.SessionID, true),
176		})
177
178	// Model Switch
179	case models.ModelSelectedMsg:
180		config.Get().UpdatePreferredModel(msg.ModelType, msg.Model)
181
182		// Update the agent with the new model/provider configuration
183		if err := a.app.UpdateAgentModel(); err != nil {
184			return a, util.ReportError(fmt.Errorf("model changed to %s but failed to update agent: %v", msg.Model.Model, err))
185		}
186
187		modelTypeName := "large"
188		if msg.ModelType == config.SelectedModelTypeSmall {
189			modelTypeName = "small"
190		}
191		return a, util.ReportInfo(fmt.Sprintf("%s model changed to %s", modelTypeName, msg.Model.Model))
192
193	// File Picker
194	case chat.OpenFilePickerMsg:
195		if a.dialog.ActiveDialogID() == filepicker.FilePickerID {
196			// If the commands dialog is already open, close it
197			return a, util.CmdHandler(dialogs.CloseDialogMsg{})
198		}
199		return a, util.CmdHandler(dialogs.OpenDialogMsg{
200			Model: filepicker.NewFilePickerCmp(a.app.Config().WorkingDir()),
201		})
202	// Permissions
203	case pubsub.Event[permission.PermissionRequest]:
204		return a, util.CmdHandler(dialogs.OpenDialogMsg{
205			Model: permissions.NewPermissionDialogCmp(msg.Payload),
206		})
207	case permissions.PermissionResponseMsg:
208		switch msg.Action {
209		case permissions.PermissionAllow:
210			a.app.Permissions.Grant(msg.Permission)
211		case permissions.PermissionAllowForSession:
212			a.app.Permissions.GrantPersistent(msg.Permission)
213		case permissions.PermissionDeny:
214			a.app.Permissions.Deny(msg.Permission)
215		}
216		return a, nil
217	// Agent Events
218	case pubsub.Event[agent.AgentEvent]:
219		payload := msg.Payload
220
221		// Forward agent events to dialogs
222		if a.dialog.HasDialogs() && a.dialog.ActiveDialogID() == compact.CompactDialogID {
223			u, dialogCmd := a.dialog.Update(payload)
224			a.dialog = u.(dialogs.DialogCmp)
225			cmds = append(cmds, dialogCmd)
226		}
227
228		// Handle auto-compact logic
229		if payload.Done && payload.Type == agent.AgentEventTypeResponse && a.selectedSessionID != "" {
230			// Get current session to check token usage
231			session, err := a.app.Sessions.Get(context.Background(), a.selectedSessionID)
232			if err == nil {
233				model := a.app.CoderAgent.Model()
234				contextWindow := model.ContextWindow
235				tokens := session.CompletionTokens + session.PromptTokens
236				if (tokens >= int64(float64(contextWindow)*0.95)) && !config.Get().Options.DisableAutoSummarize { // Show compact confirmation dialog
237					cmds = append(cmds, util.CmdHandler(dialogs.OpenDialogMsg{
238						Model: compact.NewCompactDialogCmp(a.app.CoderAgent, a.selectedSessionID, false),
239					}))
240				}
241			}
242		}
243
244		return a, tea.Batch(cmds...)
245	case splash.OnboardingCompleteMsg:
246		a.isConfigured = config.HasInitialDataConfig()
247		updated, pageCmd := a.pages[a.currentPage].Update(msg)
248		a.pages[a.currentPage] = updated.(util.Model)
249		cmds = append(cmds, pageCmd)
250		return a, tea.Batch(cmds...)
251	// Key Press Messages
252	case tea.KeyPressMsg:
253		return a, a.handleKeyPressMsg(msg)
254
255	case tea.PasteMsg:
256		if a.dialog.HasDialogs() {
257			u, dialogCmd := a.dialog.Update(msg)
258			a.dialog = u.(dialogs.DialogCmp)
259			cmds = append(cmds, dialogCmd)
260		} else {
261			updated, pageCmd := a.pages[a.currentPage].Update(msg)
262			a.pages[a.currentPage] = updated.(util.Model)
263			cmds = append(cmds, pageCmd)
264		}
265		return a, tea.Batch(cmds...)
266	}
267	s, _ := a.status.Update(msg)
268	a.status = s.(status.StatusCmp)
269	updated, cmd := a.pages[a.currentPage].Update(msg)
270	a.pages[a.currentPage] = updated.(util.Model)
271	if a.dialog.HasDialogs() {
272		u, dialogCmd := a.dialog.Update(msg)
273		a.dialog = u.(dialogs.DialogCmp)
274		cmds = append(cmds, dialogCmd)
275	}
276	cmds = append(cmds, cmd)
277	return a, tea.Batch(cmds...)
278}
279
280// handleWindowResize processes window resize events and updates all components.
281func (a *appModel) handleWindowResize(width, height int) tea.Cmd {
282	var cmds []tea.Cmd
283	a.wWidth, a.wHeight = width, height
284	if a.showingFullHelp {
285		height -= 5
286	} else {
287		height -= 2
288	}
289	a.width, a.height = width, height
290	// Update status bar
291	s, cmd := a.status.Update(tea.WindowSizeMsg{Width: width, Height: height})
292	a.status = s.(status.StatusCmp)
293	cmds = append(cmds, cmd)
294
295	// Update the current page
296	for p, page := range a.pages {
297		updated, pageCmd := page.Update(tea.WindowSizeMsg{Width: width, Height: height})
298		a.pages[p] = updated.(util.Model)
299		cmds = append(cmds, pageCmd)
300	}
301
302	// Update the dialogs
303	dialog, cmd := a.dialog.Update(tea.WindowSizeMsg{Width: width, Height: height})
304	a.dialog = dialog.(dialogs.DialogCmp)
305	cmds = append(cmds, cmd)
306
307	return tea.Batch(cmds...)
308}
309
310// handleKeyPressMsg processes keyboard input and routes to appropriate handlers.
311func (a *appModel) handleKeyPressMsg(msg tea.KeyPressMsg) tea.Cmd {
312	if a.completions.Open() {
313		// completions
314		keyMap := a.completions.KeyMap()
315		switch {
316		case key.Matches(msg, keyMap.Up), key.Matches(msg, keyMap.Down),
317			key.Matches(msg, keyMap.Select), key.Matches(msg, keyMap.Cancel),
318			key.Matches(msg, keyMap.UpInsert), key.Matches(msg, keyMap.DownInsert):
319			u, cmd := a.completions.Update(msg)
320			a.completions = u.(completions.Completions)
321			return cmd
322		}
323	}
324	switch {
325	// help
326	case key.Matches(msg, a.keyMap.Help):
327		a.status.ToggleFullHelp()
328		a.showingFullHelp = !a.showingFullHelp
329		return a.handleWindowResize(a.wWidth, a.wHeight)
330	// dialogs
331	case key.Matches(msg, a.keyMap.Quit):
332		if a.dialog.ActiveDialogID() == quit.QuitDialogID {
333			return tea.Quit
334		}
335		return util.CmdHandler(dialogs.OpenDialogMsg{
336			Model: quit.NewQuitDialog(),
337		})
338
339	case key.Matches(msg, a.keyMap.Commands):
340		// if the app is not configured show no commands
341		if !a.isConfigured {
342			return nil
343		}
344		if a.dialog.ActiveDialogID() == commands.CommandsDialogID {
345			return util.CmdHandler(dialogs.CloseDialogMsg{})
346		}
347		if a.dialog.HasDialogs() {
348			return nil
349		}
350		return util.CmdHandler(dialogs.OpenDialogMsg{
351			Model: commands.NewCommandDialog(a.selectedSessionID),
352		})
353	case key.Matches(msg, a.keyMap.Sessions):
354		// if the app is not configured show no sessions
355		if !a.isConfigured {
356			return nil
357		}
358		if a.dialog.ActiveDialogID() == sessions.SessionsDialogID {
359			return util.CmdHandler(dialogs.CloseDialogMsg{})
360		}
361		if a.dialog.HasDialogs() && a.dialog.ActiveDialogID() != commands.CommandsDialogID {
362			return nil
363		}
364		var cmds []tea.Cmd
365		if a.dialog.ActiveDialogID() == commands.CommandsDialogID {
366			// If the commands dialog is open, close it first
367			cmds = append(cmds, util.CmdHandler(dialogs.CloseDialogMsg{}))
368		}
369		cmds = append(cmds,
370			func() tea.Msg {
371				allSessions, _ := a.app.Sessions.List(context.Background())
372				return dialogs.OpenDialogMsg{
373					Model: sessions.NewSessionDialogCmp(allSessions, a.selectedSessionID),
374				}
375			},
376		)
377		return tea.Sequence(cmds...)
378	default:
379		if a.dialog.HasDialogs() {
380			u, dialogCmd := a.dialog.Update(msg)
381			a.dialog = u.(dialogs.DialogCmp)
382			return dialogCmd
383		} else {
384			updated, cmd := a.pages[a.currentPage].Update(msg)
385			a.pages[a.currentPage] = updated.(util.Model)
386			return cmd
387		}
388	}
389}
390
391// moveToPage handles navigation between different pages in the application.
392func (a *appModel) moveToPage(pageID page.PageID) tea.Cmd {
393	if a.app.CoderAgent.IsBusy() {
394		// TODO: maybe remove this :  For now we don't move to any page if the agent is busy
395		return util.ReportWarn("Agent is busy, please wait...")
396	}
397
398	var cmds []tea.Cmd
399	if _, ok := a.loadedPages[pageID]; !ok {
400		cmd := a.pages[pageID].Init()
401		cmds = append(cmds, cmd)
402		a.loadedPages[pageID] = true
403	}
404	a.previousPage = a.currentPage
405	a.currentPage = pageID
406	if sizable, ok := a.pages[a.currentPage].(layout.Sizeable); ok {
407		cmd := sizable.SetSize(a.width, a.height)
408		cmds = append(cmds, cmd)
409	}
410
411	return tea.Batch(cmds...)
412}
413
414// View renders the complete application interface including pages, dialogs, and overlays.
415func (a *appModel) View() tea.View {
416	page := a.pages[a.currentPage]
417	if withHelp, ok := page.(core.KeyMapHelp); ok {
418		a.status.SetKeyMap(withHelp.Help())
419	}
420	pageView := page.View()
421	components := []string{
422		pageView,
423	}
424	components = append(components, a.status.View())
425
426	appView := lipgloss.JoinVertical(lipgloss.Top, components...)
427	layers := []*lipgloss.Layer{
428		lipgloss.NewLayer(appView),
429	}
430	if a.dialog.HasDialogs() {
431		layers = append(
432			layers,
433			a.dialog.GetLayers()...,
434		)
435	}
436
437	var cursor *tea.Cursor
438	if v, ok := page.(util.Cursor); ok {
439		cursor = v.Cursor()
440	}
441	activeView := a.dialog.ActiveModel()
442	if activeView != nil {
443		cursor = nil // Reset cursor if a dialog is active unless it implements util.Cursor
444		if v, ok := activeView.(util.Cursor); ok {
445			cursor = v.Cursor()
446		}
447	}
448
449	if a.completions.Open() && cursor != nil {
450		cmp := a.completions.View()
451		x, y := a.completions.Position()
452		layers = append(
453			layers,
454			lipgloss.NewLayer(cmp).X(x).Y(y),
455		)
456	}
457
458	canvas := lipgloss.NewCanvas(
459		layers...,
460	)
461
462	var view tea.View
463	t := styles.CurrentTheme()
464	view.Layer = canvas
465	view.BackgroundColor = t.BgBase
466	view.Cursor = cursor
467	return view
468}
469
470// New creates and initializes a new TUI application model.
471func New(app *app.App) tea.Model {
472	chatPage := chat.New(app)
473	keyMap := DefaultKeyMap()
474	keyMap.pageBindings = chatPage.Bindings()
475
476	model := &appModel{
477		currentPage: chat.ChatPageID,
478		app:         app,
479		status:      status.NewStatusCmp(),
480		loadedPages: make(map[page.PageID]bool),
481		keyMap:      keyMap,
482
483		pages: map[page.PageID]util.Model{
484			chat.ChatPageID: chatPage,
485		},
486
487		dialog:      dialogs.NewDialogCmp(),
488		completions: completions.New(),
489	}
490
491	return model
492}