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