tui.go

  1package tui
  2
  3import (
  4	"context"
  5	"fmt"
  6	"math/rand"
  7	"slices"
  8	"strings"
  9	"time"
 10
 11	"git.secluded.site/crush/internal/app"
 12	"git.secluded.site/crush/internal/config"
 13	"git.secluded.site/crush/internal/event"
 14	"git.secluded.site/crush/internal/permission"
 15	"git.secluded.site/crush/internal/pubsub"
 16	cmpChat "git.secluded.site/crush/internal/tui/components/chat"
 17	"git.secluded.site/crush/internal/tui/components/chat/splash"
 18	"git.secluded.site/crush/internal/tui/components/completions"
 19	"git.secluded.site/crush/internal/tui/components/core"
 20	"git.secluded.site/crush/internal/tui/components/core/layout"
 21	"git.secluded.site/crush/internal/tui/components/core/status"
 22	"git.secluded.site/crush/internal/tui/components/dialogs"
 23	"git.secluded.site/crush/internal/tui/components/dialogs/commands"
 24	"git.secluded.site/crush/internal/tui/components/dialogs/filepicker"
 25	"git.secluded.site/crush/internal/tui/components/dialogs/models"
 26	"git.secluded.site/crush/internal/tui/components/dialogs/permissions"
 27	"git.secluded.site/crush/internal/tui/components/dialogs/quit"
 28	"git.secluded.site/crush/internal/tui/components/dialogs/sessions"
 29	"git.secluded.site/crush/internal/tui/page"
 30	"git.secluded.site/crush/internal/tui/page/chat"
 31	"git.secluded.site/crush/internal/tui/styles"
 32	"git.secluded.site/crush/internal/tui/util"
 33	"github.com/charmbracelet/bubbles/v2/key"
 34	tea "github.com/charmbracelet/bubbletea/v2"
 35	"github.com/charmbracelet/lipgloss/v2"
 36)
 37
 38var lastMouseEvent time.Time
 39
 40func MouseEventFilter(m tea.Model, msg tea.Msg) tea.Msg {
 41	switch msg.(type) {
 42	case tea.MouseWheelMsg, tea.MouseMotionMsg:
 43		now := time.Now()
 44		// trackpad is sending too many requests
 45		if now.Sub(lastMouseEvent) < 15*time.Millisecond {
 46			return nil
 47		}
 48		lastMouseEvent = now
 49	}
 50	return msg
 51}
 52
 53// appModel represents the main application model that manages pages, dialogs, and UI state.
 54type appModel struct {
 55	wWidth, wHeight int // Window dimensions
 56	width, height   int
 57	keyMap          KeyMap
 58
 59	currentPage  page.PageID
 60	previousPage page.PageID
 61	pages        map[page.PageID]util.Model
 62	loadedPages  map[page.PageID]bool
 63
 64	// Status
 65	status          status.StatusCmp
 66	showingFullHelp bool
 67
 68	app *app.App
 69
 70	dialog       dialogs.DialogCmp
 71	completions  completions.Completions
 72	isConfigured bool
 73
 74	// Chat Page Specific
 75	selectedSessionID string // The ID of the currently selected session
 76
 77	// sendProgressBar instructs the TUI to send progress bar updates to the
 78	// terminal.
 79	sendProgressBar bool
 80
 81	// QueryVersion instructs the TUI to query for the terminal version when it
 82	// starts.
 83	QueryVersion bool
 84}
 85
 86// Init initializes the application model and returns initial commands.
 87func (a appModel) Init() tea.Cmd {
 88	item, ok := a.pages[a.currentPage]
 89	if !ok {
 90		return nil
 91	}
 92
 93	var cmds []tea.Cmd
 94	cmd := item.Init()
 95	cmds = append(cmds, cmd)
 96	a.loadedPages[a.currentPage] = true
 97
 98	cmd = a.status.Init()
 99	cmds = append(cmds, cmd)
100	if a.QueryVersion {
101		cmds = append(cmds, tea.RequestTerminalVersion)
102	}
103
104	return tea.Batch(cmds...)
105}
106
107// Update handles incoming messages and updates the application state.
108func (a *appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
109	var cmds []tea.Cmd
110	var cmd tea.Cmd
111	a.isConfigured = config.HasInitialDataConfig()
112
113	switch msg := msg.(type) {
114	case tea.EnvMsg:
115		// Is this Windows Terminal?
116		if !a.sendProgressBar {
117			a.sendProgressBar = slices.Contains(msg, "WT_SESSION")
118		}
119	case tea.TerminalVersionMsg:
120		termVersion := strings.ToLower(string(msg))
121		// Only enable progress bar for the following terminals.
122		if !a.sendProgressBar {
123			a.sendProgressBar = strings.Contains(termVersion, "ghostty")
124		}
125		return a, nil
126	case tea.KeyboardEnhancementsMsg:
127		for id, page := range a.pages {
128			m, pageCmd := page.Update(msg)
129			a.pages[id] = m
130
131			if pageCmd != nil {
132				cmds = append(cmds, pageCmd)
133			}
134		}
135		return a, tea.Batch(cmds...)
136	case tea.WindowSizeMsg:
137		a.wWidth, a.wHeight = msg.Width, msg.Height
138		a.completions.Update(msg)
139		return a, a.handleWindowResize(msg.Width, msg.Height)
140
141	// Completions messages
142	case completions.OpenCompletionsMsg, completions.FilterCompletionsMsg,
143		completions.CloseCompletionsMsg, completions.RepositionCompletionsMsg:
144		u, completionCmd := a.completions.Update(msg)
145		if model, ok := u.(completions.Completions); ok {
146			a.completions = model
147		}
148
149		return a, completionCmd
150
151	// Dialog messages
152	case dialogs.OpenDialogMsg, dialogs.CloseDialogMsg:
153		u, completionCmd := a.completions.Update(completions.CloseCompletionsMsg{})
154		a.completions = u.(completions.Completions)
155		u, dialogCmd := a.dialog.Update(msg)
156		a.dialog = u.(dialogs.DialogCmp)
157		return a, tea.Batch(completionCmd, dialogCmd)
158	case commands.ShowArgumentsDialogMsg:
159		return a, util.CmdHandler(
160			dialogs.OpenDialogMsg{
161				Model: commands.NewCommandArgumentsDialog(
162					msg.CommandID,
163					msg.Content,
164					msg.ArgNames,
165				),
166			},
167		)
168	// Page change messages
169	case page.PageChangeMsg:
170		return a, a.moveToPage(msg.ID)
171
172	// Status Messages
173	case util.InfoMsg, util.ClearStatusMsg:
174		s, statusCmd := a.status.Update(msg)
175		a.status = s.(status.StatusCmp)
176		cmds = append(cmds, statusCmd)
177		return a, tea.Batch(cmds...)
178
179	// Session
180	case cmpChat.SessionSelectedMsg:
181		a.selectedSessionID = msg.ID
182	case cmpChat.SessionClearedMsg:
183		a.selectedSessionID = ""
184	// Commands
185	case commands.SwitchSessionsMsg:
186		return a, func() tea.Msg {
187			allSessions, _ := a.app.Sessions.List(context.Background())
188			return dialogs.OpenDialogMsg{
189				Model: sessions.NewSessionDialogCmp(allSessions, a.selectedSessionID),
190			}
191		}
192
193	case commands.SwitchModelMsg:
194		// Opening model dialog is interaction; cancel pending turn-end notif.
195		if a.app.AgentCoordinator != nil && a.app.AgentCoordinator.HasPendingCompletionNotification(a.selectedSessionID) {
196			a.app.AgentCoordinator.CancelCompletionNotification(a.selectedSessionID)
197		}
198		return a, util.CmdHandler(
199			dialogs.OpenDialogMsg{
200				Model: models.NewModelDialogCmp(),
201			},
202		)
203	// Compact
204	case commands.CompactMsg:
205		return a, func() tea.Msg {
206			err := a.app.AgentCoordinator.Summarize(context.Background(), msg.SessionID)
207			if err != nil {
208				return util.ReportError(err)()
209			}
210			return nil
211		}
212	case commands.QuitMsg:
213		return a, util.CmdHandler(dialogs.OpenDialogMsg{
214			Model: quit.NewQuitDialog(),
215		})
216	case commands.ToggleYoloModeMsg:
217		a.app.Permissions.SetSkipRequests(!a.app.Permissions.SkipRequests())
218	case commands.ToggleHelpMsg:
219		a.status.ToggleFullHelp()
220		a.showingFullHelp = !a.showingFullHelp
221		return a, a.handleWindowResize(a.wWidth, a.wHeight)
222	// Model Switch
223	case models.ModelSelectedMsg:
224		if a.app.AgentCoordinator.IsBusy() {
225			return a, util.ReportWarn("Agent is busy, please wait...")
226		}
227
228		cfg := config.Get()
229		if err := cfg.UpdatePreferredModel(msg.ModelType, msg.Model); err != nil {
230			return a, util.ReportError(err)
231		}
232
233		go a.app.UpdateAgentModel(context.TODO())
234
235		modelTypeName := "large"
236		if msg.ModelType == config.SelectedModelTypeSmall {
237			modelTypeName = "small"
238		}
239		return a, util.ReportInfo(fmt.Sprintf("%s model changed to %s", modelTypeName, msg.Model.Model))
240
241	// File Picker
242	case commands.OpenFilePickerMsg:
243		event.FilePickerOpened()
244
245		if a.dialog.ActiveDialogID() == filepicker.FilePickerID {
246			// If the commands dialog is already open, close it
247			return a, util.CmdHandler(dialogs.CloseDialogMsg{})
248		}
249		return a, util.CmdHandler(dialogs.OpenDialogMsg{
250			Model: filepicker.NewFilePickerCmp(a.app.Config().WorkingDir()),
251		})
252	// Permissions
253	case pubsub.Event[permission.PermissionNotification]:
254		item, ok := a.pages[a.currentPage]
255		if !ok {
256			return a, nil
257		}
258
259		// Forward to view.
260		updated, itemCmd := item.Update(msg)
261		a.pages[a.currentPage] = updated
262
263		return a, itemCmd
264	case pubsub.Event[permission.PermissionRequest]:
265		return a, util.CmdHandler(dialogs.OpenDialogMsg{
266			Model: permissions.NewPermissionDialogCmp(msg.Payload, &permissions.Options{
267				DiffMode: config.Get().Options.TUI.DiffMode,
268			}),
269		})
270	case permissions.PermissionResponseMsg:
271		switch msg.Action {
272		case permissions.PermissionAllow:
273			a.app.Permissions.Grant(msg.Permission)
274		case permissions.PermissionAllowForSession:
275			a.app.Permissions.GrantPersistent(msg.Permission)
276		case permissions.PermissionDeny:
277			a.app.Permissions.Deny(msg.Permission)
278		}
279		return a, nil
280	case permissions.PermissionInteractionMsg:
281		// Notify that the user interacted with the permission dialog.
282		a.app.Permissions.NotifyInteraction(msg.ToolCallID)
283		return a, nil
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		return util.CmdHandler(dialogs.OpenDialogMsg{
407			Model: quit.NewQuitDialog(),
408		})
409	}
410
411	if a.completions.Open() {
412		// completions
413		keyMap := a.completions.KeyMap()
414		switch {
415		case key.Matches(msg, keyMap.Up), key.Matches(msg, keyMap.Down),
416			key.Matches(msg, keyMap.Select), key.Matches(msg, keyMap.Cancel),
417			key.Matches(msg, keyMap.UpInsert), key.Matches(msg, keyMap.DownInsert):
418			u, cmd := a.completions.Update(msg)
419			a.completions = u.(completions.Completions)
420			return cmd
421		}
422	}
423	if a.dialog.HasDialogs() {
424		u, dialogCmd := a.dialog.Update(msg)
425		a.dialog = u.(dialogs.DialogCmp)
426		return dialogCmd
427	}
428	switch {
429	// help
430	case key.Matches(msg, a.keyMap.Help):
431		a.status.ToggleFullHelp()
432		a.showingFullHelp = !a.showingFullHelp
433		return a.handleWindowResize(a.wWidth, a.wHeight)
434		// dialogs
435	case key.Matches(msg, a.keyMap.Commands):
436		// Opening the command palette counts as interaction; cancel pending
437		// turn-end notification for the selected session if any.
438		if a.app.AgentCoordinator != nil && a.app.AgentCoordinator.HasPendingCompletionNotification(a.selectedSessionID) {
439			a.app.AgentCoordinator.CancelCompletionNotification(a.selectedSessionID)
440		}
441		// if the app is not configured show no commands
442		if !a.isConfigured {
443			return nil
444		}
445		if a.dialog.ActiveDialogID() == commands.CommandsDialogID {
446			return util.CmdHandler(dialogs.CloseDialogMsg{})
447		}
448		if a.dialog.HasDialogs() {
449			return nil
450		}
451		return util.CmdHandler(dialogs.OpenDialogMsg{
452			Model: commands.NewCommandDialog(a.selectedSessionID),
453		})
454	case key.Matches(msg, a.keyMap.Sessions):
455		// if the app is not configured show no sessions
456		if !a.isConfigured {
457			return nil
458		}
459		// Opening sessions dialog is interaction; cancel pending turn-end notif.
460		if a.app.AgentCoordinator != nil && a.app.AgentCoordinator.HasPendingCompletionNotification(a.selectedSessionID) {
461			a.app.AgentCoordinator.CancelCompletionNotification(a.selectedSessionID)
462		}
463		if a.dialog.ActiveDialogID() == sessions.SessionsDialogID {
464			return util.CmdHandler(dialogs.CloseDialogMsg{})
465		}
466		if a.dialog.HasDialogs() && a.dialog.ActiveDialogID() != commands.CommandsDialogID {
467			return nil
468		}
469		var cmds []tea.Cmd
470		if a.dialog.ActiveDialogID() == commands.CommandsDialogID {
471			// If the commands dialog is open, close it first
472			cmds = append(cmds, util.CmdHandler(dialogs.CloseDialogMsg{}))
473		}
474		cmds = append(cmds,
475			func() tea.Msg {
476				allSessions, _ := a.app.Sessions.List(context.Background())
477				return dialogs.OpenDialogMsg{
478					Model: sessions.NewSessionDialogCmp(allSessions, a.selectedSessionID),
479				}
480			},
481		)
482		return tea.Sequence(cmds...)
483	case key.Matches(msg, a.keyMap.Suspend):
484		if a.app.AgentCoordinator != nil && a.app.AgentCoordinator.IsBusy() {
485			return util.ReportWarn("Agent is busy, please wait...")
486		}
487		return tea.Suspend
488	default:
489		item, ok := a.pages[a.currentPage]
490		if !ok {
491			return nil
492		}
493
494		updated, cmd := item.Update(msg)
495		a.pages[a.currentPage] = updated
496		return cmd
497	}
498}
499
500// moveToPage handles navigation between different pages in the application.
501func (a *appModel) moveToPage(pageID page.PageID) tea.Cmd {
502	if a.app.AgentCoordinator.IsBusy() {
503		// TODO: maybe remove this :  For now we don't move to any page if the agent is busy
504		return util.ReportWarn("Agent is busy, please wait...")
505	}
506
507	var cmds []tea.Cmd
508	if _, ok := a.loadedPages[pageID]; !ok {
509		cmd := a.pages[pageID].Init()
510		cmds = append(cmds, cmd)
511		a.loadedPages[pageID] = true
512	}
513	a.previousPage = a.currentPage
514	a.currentPage = pageID
515	if sizable, ok := a.pages[a.currentPage].(layout.Sizeable); ok {
516		cmd := sizable.SetSize(a.width, a.height)
517		cmds = append(cmds, cmd)
518	}
519
520	return tea.Batch(cmds...)
521}
522
523// View renders the complete application interface including pages, dialogs, and overlays.
524func (a *appModel) View() tea.View {
525	var view tea.View
526	view.AltScreen = true
527	t := styles.CurrentTheme()
528	view.BackgroundColor = t.BgBase
529	if a.wWidth < 25 || a.wHeight < 15 {
530		view.Layer = lipgloss.NewCanvas(
531			lipgloss.NewLayer(
532				t.S().Base.Width(a.wWidth).Height(a.wHeight).
533					Align(lipgloss.Center, lipgloss.Center).
534					Render(
535						t.S().Base.
536							Padding(1, 4).
537							Foreground(t.White).
538							BorderStyle(lipgloss.RoundedBorder()).
539							BorderForeground(t.Primary).
540							Render("Window too small!"),
541					),
542			),
543		)
544		return view
545	}
546
547	page := a.pages[a.currentPage]
548	if withHelp, ok := page.(core.KeyMapHelp); ok {
549		a.status.SetKeyMap(withHelp.Help())
550	}
551	pageView := page.View()
552	components := []string{
553		pageView,
554	}
555	components = append(components, a.status.View())
556
557	appView := lipgloss.JoinVertical(lipgloss.Top, components...)
558	layers := []*lipgloss.Layer{
559		lipgloss.NewLayer(appView),
560	}
561	if a.dialog.HasDialogs() {
562		layers = append(
563			layers,
564			a.dialog.GetLayers()...,
565		)
566	}
567
568	var cursor *tea.Cursor
569	if v, ok := page.(util.Cursor); ok {
570		cursor = v.Cursor()
571		// Hide the cursor if it's positioned outside the textarea
572		statusHeight := a.height - strings.Count(pageView, "\n") + 1
573		if cursor != nil && cursor.Y+statusHeight+chat.EditorHeight-2 <= a.height { // 2 for the top and bottom app padding
574			cursor = nil
575		}
576	}
577	activeView := a.dialog.ActiveModel()
578	if activeView != nil {
579		cursor = nil // Reset cursor if a dialog is active unless it implements util.Cursor
580		if v, ok := activeView.(util.Cursor); ok {
581			cursor = v.Cursor()
582		}
583	}
584
585	if a.completions.Open() && cursor != nil {
586		cmp := a.completions.View()
587		x, y := a.completions.Position()
588		layers = append(
589			layers,
590			lipgloss.NewLayer(cmp).X(x).Y(y),
591		)
592	}
593
594	canvas := lipgloss.NewCanvas(
595		layers...,
596	)
597
598	view.Layer = canvas
599	view.Cursor = cursor
600	view.MouseMode = tea.MouseModeCellMotion
601
602	if a.sendProgressBar && a.app != nil && a.app.AgentCoordinator != nil && a.app.AgentCoordinator.IsBusy() {
603		// HACK: use a random percentage to prevent ghostty from hiding it
604		// after a timeout.
605		view.ProgressBar = tea.NewProgressBar(tea.ProgressBarIndeterminate, rand.Intn(100))
606	}
607	return view
608}
609
610// New creates and initializes a new TUI application model.
611func New(app *app.App) *appModel {
612	chatPage := chat.New(app)
613	keyMap := DefaultKeyMap()
614	keyMap.pageBindings = chatPage.Bindings()
615
616	model := &appModel{
617		currentPage: chat.ChatPageID,
618		app:         app,
619		status:      status.NewStatusCmp(),
620		loadedPages: make(map[page.PageID]bool),
621		keyMap:      keyMap,
622
623		pages: map[page.PageID]util.Model{
624			chat.ChatPageID: chatPage,
625		},
626
627		dialog:      dialogs.NewDialogCmp(),
628		completions: completions.New(),
629	}
630
631	return model
632}