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