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