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