tui.go

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