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