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.PermissionRequest]:
216		return a, util.CmdHandler(dialogs.OpenDialogMsg{
217			Model: permissions.NewPermissionDialogCmp(msg.Payload),
218		})
219	case permissions.PermissionResponseMsg:
220		switch msg.Action {
221		case permissions.PermissionAllow:
222			a.app.Permissions.Grant(msg.Permission)
223		case permissions.PermissionAllowForSession:
224			a.app.Permissions.GrantPersistent(msg.Permission)
225		case permissions.PermissionDeny:
226			a.app.Permissions.Deny(msg.Permission)
227		}
228		return a, nil
229	// Agent Events
230	case pubsub.Event[agent.AgentEvent]:
231		payload := msg.Payload
232
233		// Forward agent events to dialogs
234		if a.dialog.HasDialogs() && a.dialog.ActiveDialogID() == compact.CompactDialogID {
235			u, dialogCmd := a.dialog.Update(payload)
236			a.dialog = u.(dialogs.DialogCmp)
237			cmds = append(cmds, dialogCmd)
238		}
239
240		// Handle auto-compact logic
241		if payload.Done && payload.Type == agent.AgentEventTypeResponse && a.selectedSessionID != "" {
242			// Get current session to check token usage
243			session, err := a.app.Sessions.Get(context.Background(), a.selectedSessionID)
244			if err == nil {
245				model := a.app.CoderAgent.Model()
246				contextWindow := model.ContextWindow
247				tokens := session.CompletionTokens + session.PromptTokens
248				if (tokens >= int64(float64(contextWindow)*0.95)) && !config.Get().Options.DisableAutoSummarize { // Show compact confirmation dialog
249					cmds = append(cmds, util.CmdHandler(dialogs.OpenDialogMsg{
250						Model: compact.NewCompactDialogCmp(a.app.CoderAgent, a.selectedSessionID, false),
251					}))
252				}
253			}
254		}
255
256		return a, tea.Batch(cmds...)
257	case splash.OnboardingCompleteMsg:
258		a.isConfigured = config.HasInitialDataConfig()
259		updated, pageCmd := a.pages[a.currentPage].Update(msg)
260		a.pages[a.currentPage] = updated.(util.Model)
261		cmds = append(cmds, pageCmd)
262		return a, tea.Batch(cmds...)
263	// Key Press Messages
264	case tea.KeyPressMsg:
265		return a, a.handleKeyPressMsg(msg)
266
267	case tea.PasteMsg:
268		if a.dialog.HasDialogs() {
269			u, dialogCmd := a.dialog.Update(msg)
270			a.dialog = u.(dialogs.DialogCmp)
271			cmds = append(cmds, dialogCmd)
272		} else {
273			updated, pageCmd := a.pages[a.currentPage].Update(msg)
274			a.pages[a.currentPage] = updated.(util.Model)
275			cmds = append(cmds, pageCmd)
276		}
277		return a, tea.Batch(cmds...)
278	}
279	s, _ := a.status.Update(msg)
280	a.status = s.(status.StatusCmp)
281	updated, cmd := a.pages[a.currentPage].Update(msg)
282	a.pages[a.currentPage] = updated.(util.Model)
283	if a.dialog.HasDialogs() {
284		u, dialogCmd := a.dialog.Update(msg)
285		a.dialog = u.(dialogs.DialogCmp)
286		cmds = append(cmds, dialogCmd)
287	}
288	cmds = append(cmds, cmd)
289	return a, tea.Batch(cmds...)
290}
291
292// handleWindowResize processes window resize events and updates all components.
293func (a *appModel) handleWindowResize(width, height int) tea.Cmd {
294	var cmds []tea.Cmd
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	var view tea.View
428	t := styles.CurrentTheme()
429	view.BackgroundColor = t.BgBase
430	if a.wWidth < 25 || a.wHeight < 15 {
431		view.Layer = lipgloss.NewCanvas(
432			lipgloss.NewLayer(
433				t.S().Base.Width(a.wWidth).Height(a.wHeight).
434					Align(lipgloss.Center, lipgloss.Center).
435					Render(
436						t.S().Base.
437							Padding(1, 4).
438							Foreground(t.White).
439							BorderStyle(lipgloss.RoundedBorder()).
440							BorderForeground(t.Primary).
441							Render("Window too small!"),
442					),
443			),
444		)
445		return view
446	}
447
448	page := a.pages[a.currentPage]
449	if withHelp, ok := page.(core.KeyMapHelp); ok {
450		a.status.SetKeyMap(withHelp.Help())
451	}
452	pageView := page.View()
453	components := []string{
454		pageView,
455	}
456	components = append(components, a.status.View())
457
458	appView := lipgloss.JoinVertical(lipgloss.Top, components...)
459	layers := []*lipgloss.Layer{
460		lipgloss.NewLayer(appView),
461	}
462	if a.dialog.HasDialogs() {
463		layers = append(
464			layers,
465			a.dialog.GetLayers()...,
466		)
467	}
468
469	var cursor *tea.Cursor
470	if v, ok := page.(util.Cursor); ok {
471		cursor = v.Cursor()
472		// Hide the cursor if it's positioned outside the textarea
473		statusHeight := a.height - strings.Count(pageView, "\n") + 1
474		if cursor != nil && cursor.Y+statusHeight+chat.EditorHeight-2 <= a.height { // 2 for the top and bottom app padding
475			cursor = nil
476		}
477	}
478	activeView := a.dialog.ActiveModel()
479	if activeView != nil {
480		cursor = nil // Reset cursor if a dialog is active unless it implements util.Cursor
481		if v, ok := activeView.(util.Cursor); ok {
482			cursor = v.Cursor()
483		}
484	}
485
486	if a.completions.Open() && cursor != nil {
487		cmp := a.completions.View()
488		x, y := a.completions.Position()
489		layers = append(
490			layers,
491			lipgloss.NewLayer(cmp).X(x).Y(y),
492		)
493	}
494
495	canvas := lipgloss.NewCanvas(
496		layers...,
497	)
498
499	view.Layer = canvas
500	view.Cursor = cursor
501	return view
502}
503
504// New creates and initializes a new TUI application model.
505func New(app *app.App) tea.Model {
506	chatPage := chat.New(app)
507	keyMap := DefaultKeyMap()
508	keyMap.pageBindings = chatPage.Bindings()
509
510	model := &appModel{
511		currentPage: chat.ChatPageID,
512		app:         app,
513		status:      status.NewStatusCmp(),
514		loadedPages: make(map[page.PageID]bool),
515		keyMap:      keyMap,
516
517		pages: map[page.PageID]util.Model{
518			chat.ChatPageID: chatPage,
519		},
520
521		dialog:      dialogs.NewDialogCmp(),
522		completions: completions.New(),
523	}
524
525	return model
526}