tui.go

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