tui.go

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