tui.go

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