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