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		item, ok := a.pages[a.currentPage]
213		if !ok {
214			return a, nil
215		}
216
217		// forward to page
218		updated, itemCmd := item.Update(msg)
219		a.pages[a.currentPage] = updated.(util.Model)
220		return a, itemCmd
221	case pubsub.Event[permission.PermissionRequest]:
222		return a, util.CmdHandler(dialogs.OpenDialogMsg{
223			Model: permissions.NewPermissionDialogCmp(msg.Payload, &permissions.Options{
224				DiffMode: config.Get().Options.TUI.DiffMode,
225			}),
226		})
227	case permissions.PermissionResponseMsg:
228		switch msg.Action {
229		case permissions.PermissionAllow:
230			a.app.Permissions.Grant(msg.Permission)
231		case permissions.PermissionAllowForSession:
232			a.app.Permissions.GrantPersistent(msg.Permission)
233		case permissions.PermissionDeny:
234			a.app.Permissions.Deny(msg.Permission)
235		}
236		return a, nil
237	// Agent Events
238	case pubsub.Event[agent.AgentEvent]:
239		payload := msg.Payload
240
241		// Forward agent events to dialogs
242		if a.dialog.HasDialogs() && a.dialog.ActiveDialogID() == compact.CompactDialogID {
243			u, dialogCmd := a.dialog.Update(payload)
244			a.dialog = u.(dialogs.DialogCmp)
245			cmds = append(cmds, dialogCmd)
246		}
247
248		// Handle auto-compact logic
249		if payload.Done && payload.Type == agent.AgentEventTypeResponse && a.selectedSessionID != "" {
250			// Get current session to check token usage
251			session, err := a.app.Sessions.Get(context.Background(), a.selectedSessionID)
252			if err == nil {
253				model := a.app.CoderAgent.Model()
254				contextWindow := model.ContextWindow
255				tokens := session.CompletionTokens + session.PromptTokens
256				if (tokens >= int64(float64(contextWindow)*0.95)) && !config.Get().Options.DisableAutoSummarize { // Show compact confirmation dialog
257					cmds = append(cmds, util.CmdHandler(dialogs.OpenDialogMsg{
258						Model: compact.NewCompactDialogCmp(a.app.CoderAgent, a.selectedSessionID, false),
259					}))
260				}
261			}
262		}
263
264		return a, tea.Batch(cmds...)
265	case splash.OnboardingCompleteMsg:
266		item, ok := a.pages[a.currentPage]
267		if !ok {
268			return a, nil
269		}
270
271		a.isConfigured = config.HasInitialDataConfig()
272		updated, pageCmd := item.Update(msg)
273		a.pages[a.currentPage] = updated.(util.Model)
274		cmds = append(cmds, pageCmd)
275		return a, tea.Batch(cmds...)
276
277	case tea.KeyPressMsg:
278		return a, a.handleKeyPressMsg(msg)
279
280	case tea.MouseWheelMsg:
281		if a.dialog.HasDialogs() {
282			u, dialogCmd := a.dialog.Update(msg)
283			a.dialog = u.(dialogs.DialogCmp)
284			cmds = append(cmds, dialogCmd)
285		} else {
286			item, ok := a.pages[a.currentPage]
287			if !ok {
288				return a, nil
289			}
290
291			updated, pageCmd := item.Update(msg)
292			a.pages[a.currentPage] = updated.(util.Model)
293			cmds = append(cmds, pageCmd)
294		}
295		return a, tea.Batch(cmds...)
296	case tea.PasteMsg:
297		if a.dialog.HasDialogs() {
298			u, dialogCmd := a.dialog.Update(msg)
299			a.dialog = u.(dialogs.DialogCmp)
300			cmds = append(cmds, dialogCmd)
301		} else {
302			item, ok := a.pages[a.currentPage]
303			if !ok {
304				return a, nil
305			}
306
307			updated, pageCmd := item.Update(msg)
308			a.pages[a.currentPage] = updated.(util.Model)
309			cmds = append(cmds, pageCmd)
310		}
311		return a, tea.Batch(cmds...)
312	}
313	s, _ := a.status.Update(msg)
314	a.status = s.(status.StatusCmp)
315
316	item, ok := a.pages[a.currentPage]
317	if !ok {
318		return a, nil
319	}
320	updated, cmd := item.Update(msg)
321	a.pages[a.currentPage] = updated.(util.Model)
322
323	if a.dialog.HasDialogs() {
324		u, dialogCmd := a.dialog.Update(msg)
325		a.dialog = u.(dialogs.DialogCmp)
326		cmds = append(cmds, dialogCmd)
327	}
328	cmds = append(cmds, cmd)
329	return a, tea.Batch(cmds...)
330}
331
332// handleWindowResize processes window resize events and updates all components.
333func (a *appModel) handleWindowResize(width, height int) tea.Cmd {
334	var cmds []tea.Cmd
335	if a.showingFullHelp {
336		height -= 5
337	} else {
338		height -= 2
339	}
340	a.width, a.height = width, height
341	// Update status bar
342	s, cmd := a.status.Update(tea.WindowSizeMsg{Width: width, Height: height})
343	a.status = s.(status.StatusCmp)
344	cmds = append(cmds, cmd)
345
346	// Update the current page
347	for p, page := range a.pages {
348		updated, pageCmd := page.Update(tea.WindowSizeMsg{Width: width, Height: height})
349		a.pages[p] = updated.(util.Model)
350		cmds = append(cmds, pageCmd)
351	}
352
353	// Update the dialogs
354	dialog, cmd := a.dialog.Update(tea.WindowSizeMsg{Width: width, Height: height})
355	a.dialog = dialog.(dialogs.DialogCmp)
356	cmds = append(cmds, cmd)
357
358	return tea.Batch(cmds...)
359}
360
361// handleKeyPressMsg processes keyboard input and routes to appropriate handlers.
362func (a *appModel) handleKeyPressMsg(msg tea.KeyPressMsg) tea.Cmd {
363	if a.completions.Open() {
364		// completions
365		keyMap := a.completions.KeyMap()
366		switch {
367		case key.Matches(msg, keyMap.Up), key.Matches(msg, keyMap.Down),
368			key.Matches(msg, keyMap.Select), key.Matches(msg, keyMap.Cancel),
369			key.Matches(msg, keyMap.UpInsert), key.Matches(msg, keyMap.DownInsert):
370			u, cmd := a.completions.Update(msg)
371			a.completions = u.(completions.Completions)
372			return cmd
373		}
374	}
375	switch {
376	// help
377	case key.Matches(msg, a.keyMap.Help):
378		a.status.ToggleFullHelp()
379		a.showingFullHelp = !a.showingFullHelp
380		return a.handleWindowResize(a.wWidth, a.wHeight)
381	// dialogs
382	case key.Matches(msg, a.keyMap.Quit):
383		if a.dialog.ActiveDialogID() == quit.QuitDialogID {
384			return tea.Quit
385		}
386		return util.CmdHandler(dialogs.OpenDialogMsg{
387			Model: quit.NewQuitDialog(),
388		})
389
390	case key.Matches(msg, a.keyMap.Commands):
391		// if the app is not configured show no commands
392		if !a.isConfigured {
393			return nil
394		}
395		if a.dialog.ActiveDialogID() == commands.CommandsDialogID {
396			return util.CmdHandler(dialogs.CloseDialogMsg{})
397		}
398		if a.dialog.HasDialogs() {
399			return nil
400		}
401		return util.CmdHandler(dialogs.OpenDialogMsg{
402			Model: commands.NewCommandDialog(a.selectedSessionID),
403		})
404	case key.Matches(msg, a.keyMap.Sessions):
405		// if the app is not configured show no sessions
406		if !a.isConfigured {
407			return nil
408		}
409		if a.dialog.ActiveDialogID() == sessions.SessionsDialogID {
410			return util.CmdHandler(dialogs.CloseDialogMsg{})
411		}
412		if a.dialog.HasDialogs() && a.dialog.ActiveDialogID() != commands.CommandsDialogID {
413			return nil
414		}
415		var cmds []tea.Cmd
416		if a.dialog.ActiveDialogID() == commands.CommandsDialogID {
417			// If the commands dialog is open, close it first
418			cmds = append(cmds, util.CmdHandler(dialogs.CloseDialogMsg{}))
419		}
420		cmds = append(cmds,
421			func() tea.Msg {
422				allSessions, _ := a.app.Sessions.List(context.Background())
423				return dialogs.OpenDialogMsg{
424					Model: sessions.NewSessionDialogCmp(allSessions, a.selectedSessionID),
425				}
426			},
427		)
428		return tea.Sequence(cmds...)
429	case key.Matches(msg, a.keyMap.Suspend):
430		if a.app.CoderAgent != nil && a.app.CoderAgent.IsBusy() {
431			return util.ReportWarn("Agent is busy, please wait...")
432		}
433		return tea.Suspend
434	default:
435		if a.dialog.HasDialogs() {
436			u, dialogCmd := a.dialog.Update(msg)
437			a.dialog = u.(dialogs.DialogCmp)
438			return dialogCmd
439		} else {
440			item, ok := a.pages[a.currentPage]
441			if !ok {
442				return nil
443			}
444
445			updated, cmd := item.Update(msg)
446			a.pages[a.currentPage] = updated.(util.Model)
447			return cmd
448		}
449	}
450}
451
452// moveToPage handles navigation between different pages in the application.
453func (a *appModel) moveToPage(pageID page.PageID) tea.Cmd {
454	if a.app.CoderAgent.IsBusy() {
455		// TODO: maybe remove this :  For now we don't move to any page if the agent is busy
456		return util.ReportWarn("Agent is busy, please wait...")
457	}
458
459	var cmds []tea.Cmd
460	if _, ok := a.loadedPages[pageID]; !ok {
461		cmd := a.pages[pageID].Init()
462		cmds = append(cmds, cmd)
463		a.loadedPages[pageID] = true
464	}
465	a.previousPage = a.currentPage
466	a.currentPage = pageID
467	if sizable, ok := a.pages[a.currentPage].(layout.Sizeable); ok {
468		cmd := sizable.SetSize(a.width, a.height)
469		cmds = append(cmds, cmd)
470	}
471
472	return tea.Batch(cmds...)
473}
474
475// View renders the complete application interface including pages, dialogs, and overlays.
476func (a *appModel) View() tea.View {
477	var view tea.View
478	t := styles.CurrentTheme()
479	view.BackgroundColor = t.BgBase
480	if a.wWidth < 25 || a.wHeight < 15 {
481		view.Layer = lipgloss.NewCanvas(
482			lipgloss.NewLayer(
483				t.S().Base.Width(a.wWidth).Height(a.wHeight).
484					Align(lipgloss.Center, lipgloss.Center).
485					Render(
486						t.S().Base.
487							Padding(1, 4).
488							Foreground(t.White).
489							BorderStyle(lipgloss.RoundedBorder()).
490							BorderForeground(t.Primary).
491							Render("Window too small!"),
492					),
493			),
494		)
495		return view
496	}
497
498	page := a.pages[a.currentPage]
499	if withHelp, ok := page.(core.KeyMapHelp); ok {
500		a.status.SetKeyMap(withHelp.Help())
501	}
502	pageView := page.View()
503	components := []string{
504		pageView,
505	}
506	components = append(components, a.status.View())
507
508	appView := lipgloss.JoinVertical(lipgloss.Top, components...)
509	layers := []*lipgloss.Layer{
510		lipgloss.NewLayer(appView),
511	}
512	if a.dialog.HasDialogs() {
513		layers = append(
514			layers,
515			a.dialog.GetLayers()...,
516		)
517	}
518
519	var cursor *tea.Cursor
520	if v, ok := page.(util.Cursor); ok {
521		cursor = v.Cursor()
522		// Hide the cursor if it's positioned outside the textarea
523		statusHeight := a.height - strings.Count(pageView, "\n") + 1
524		if cursor != nil && cursor.Y+statusHeight+chat.EditorHeight-2 <= a.height { // 2 for the top and bottom app padding
525			cursor = nil
526		}
527	}
528	activeView := a.dialog.ActiveModel()
529	if activeView != nil {
530		cursor = nil // Reset cursor if a dialog is active unless it implements util.Cursor
531		if v, ok := activeView.(util.Cursor); ok {
532			cursor = v.Cursor()
533		}
534	}
535
536	if a.completions.Open() && cursor != nil {
537		cmp := a.completions.View()
538		x, y := a.completions.Position()
539		layers = append(
540			layers,
541			lipgloss.NewLayer(cmp).X(x).Y(y),
542		)
543	}
544
545	canvas := lipgloss.NewCanvas(
546		layers...,
547	)
548
549	view.Layer = canvas
550	view.Cursor = cursor
551	return view
552}
553
554// New creates and initializes a new TUI application model.
555func New(app *app.App) tea.Model {
556	chatPage := chat.New(app)
557	keyMap := DefaultKeyMap()
558	keyMap.pageBindings = chatPage.Bindings()
559
560	model := &appModel{
561		currentPage: chat.ChatPageID,
562		app:         app,
563		status:      status.NewStatusCmp(),
564		loadedPages: make(map[page.PageID]bool),
565		keyMap:      keyMap,
566
567		pages: map[page.PageID]util.Model{
568			chat.ChatPageID: chatPage,
569		},
570
571		dialog:      dialogs.NewDialogCmp(),
572		completions: completions.New(),
573	}
574
575	return model
576}