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