tui.go

  1package tui
  2
  3import (
  4	"context"
  5	"fmt"
  6
  7	"github.com/charmbracelet/bubbles/v2/key"
  8	tea "github.com/charmbracelet/bubbletea/v2"
  9	"github.com/charmbracelet/crush/internal/app"
 10	"github.com/charmbracelet/crush/internal/config"
 11	"github.com/charmbracelet/crush/internal/llm/agent"
 12	"github.com/charmbracelet/crush/internal/logging"
 13	"github.com/charmbracelet/crush/internal/permission"
 14	"github.com/charmbracelet/crush/internal/pubsub"
 15	cmpChat "github.com/charmbracelet/crush/internal/tui/components/chat"
 16	"github.com/charmbracelet/crush/internal/tui/components/completions"
 17	"github.com/charmbracelet/crush/internal/tui/components/core/layout"
 18	"github.com/charmbracelet/crush/internal/tui/components/core/status"
 19	"github.com/charmbracelet/crush/internal/tui/components/dialogs"
 20	"github.com/charmbracelet/crush/internal/tui/components/dialogs/commands"
 21	"github.com/charmbracelet/crush/internal/tui/components/dialogs/compact"
 22	"github.com/charmbracelet/crush/internal/tui/components/dialogs/filepicker"
 23	initDialog "github.com/charmbracelet/crush/internal/tui/components/dialogs/init"
 24	"github.com/charmbracelet/crush/internal/tui/components/dialogs/models"
 25	"github.com/charmbracelet/crush/internal/tui/components/dialogs/permissions"
 26	"github.com/charmbracelet/crush/internal/tui/components/dialogs/quit"
 27	"github.com/charmbracelet/crush/internal/tui/components/dialogs/sessions"
 28	"github.com/charmbracelet/crush/internal/tui/page"
 29	"github.com/charmbracelet/crush/internal/tui/page/chat"
 30	"github.com/charmbracelet/crush/internal/tui/page/logs"
 31	"github.com/charmbracelet/crush/internal/tui/styles"
 32	"github.com/charmbracelet/crush/internal/tui/util"
 33	"github.com/charmbracelet/lipgloss/v2"
 34)
 35
 36// appModel represents the main application model that manages pages, dialogs, and UI state.
 37type appModel struct {
 38	wWidth, wHeight int // Window dimensions
 39	width, height   int
 40	keyMap          KeyMap
 41
 42	currentPage  page.PageID
 43	previousPage page.PageID
 44	pages        map[page.PageID]util.Model
 45	loadedPages  map[page.PageID]bool
 46
 47	// Status
 48	status          status.StatusCmp
 49	showingFullHelp bool
 50
 51	app *app.App
 52
 53	dialog      dialogs.DialogCmp
 54	completions completions.Completions
 55
 56	// Chat Page Specific
 57	selectedSessionID string // The ID of the currently selected session
 58}
 59
 60// Init initializes the application model and returns initial commands.
 61func (a appModel) Init() tea.Cmd {
 62	var cmds []tea.Cmd
 63	cmd := a.pages[a.currentPage].Init()
 64	cmds = append(cmds, cmd)
 65	a.loadedPages[a.currentPage] = true
 66
 67	cmd = a.status.Init()
 68	cmds = append(cmds, cmd)
 69
 70	// Check if we should show the init dialog
 71	cmds = append(cmds, func() tea.Msg {
 72		shouldShow, err := config.ShouldShowInitDialog()
 73		if err != nil {
 74			return util.InfoMsg{
 75				Type: util.InfoTypeError,
 76				Msg:  "Failed to check init status: " + err.Error(),
 77			}
 78		}
 79		if shouldShow {
 80			return dialogs.OpenDialogMsg{
 81				Model: initDialog.NewInitDialogCmp(),
 82			}
 83		}
 84		return nil
 85	})
 86
 87	// Enable mouse support.
 88	cmds = append(cmds, tea.EnableMouseAllMotion)
 89
 90	return tea.Batch(cmds...)
 91}
 92
 93// Update handles incoming messages and updates the application state.
 94func (a *appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
 95	var cmds []tea.Cmd
 96	var cmd tea.Cmd
 97
 98	switch msg := msg.(type) {
 99	case tea.KeyboardEnhancementsMsg:
100		return a, nil
101	case tea.WindowSizeMsg:
102		return a, a.handleWindowResize(msg.Width, msg.Height)
103
104	// Completions messages
105	case completions.OpenCompletionsMsg, completions.FilterCompletionsMsg, completions.CloseCompletionsMsg:
106		u, completionCmd := a.completions.Update(msg)
107		a.completions = u.(completions.Completions)
108		return a, completionCmd
109
110	// Dialog messages
111	case dialogs.OpenDialogMsg, dialogs.CloseDialogMsg:
112		u, dialogCmd := a.dialog.Update(msg)
113		a.dialog = u.(dialogs.DialogCmp)
114		return a, dialogCmd
115	case commands.ShowArgumentsDialogMsg:
116		return a, util.CmdHandler(
117			dialogs.OpenDialogMsg{
118				Model: commands.NewCommandArgumentsDialog(
119					msg.CommandID,
120					msg.Content,
121					msg.ArgNames,
122				),
123			},
124		)
125	// Page change messages
126	case page.PageChangeMsg:
127		return a, a.moveToPage(msg.ID)
128
129	// Status Messages
130	case util.InfoMsg, util.ClearStatusMsg:
131		s, statusCmd := a.status.Update(msg)
132		a.status = s.(status.StatusCmp)
133		cmds = append(cmds, statusCmd)
134		return a, tea.Batch(cmds...)
135
136	// Session
137	case cmpChat.SessionSelectedMsg:
138		a.selectedSessionID = msg.ID
139	case cmpChat.SessionClearedMsg:
140		a.selectedSessionID = ""
141	// Logs
142	case pubsub.Event[logging.LogMessage]:
143		// Send to the status component
144		s, statusCmd := a.status.Update(msg)
145		a.status = s.(status.StatusCmp)
146		cmds = append(cmds, statusCmd)
147
148		// If the current page is logs, update the logs view
149		if a.currentPage == logs.LogsPage {
150			updated, pageCmd := a.pages[a.currentPage].Update(msg)
151			a.pages[a.currentPage] = updated.(util.Model)
152			cmds = append(cmds, pageCmd)
153		}
154		return a, tea.Batch(cmds...)
155	// Commands
156	case commands.SwitchSessionsMsg:
157		return a, func() tea.Msg {
158			allSessions, _ := a.app.Sessions.List(context.Background())
159			return dialogs.OpenDialogMsg{
160				Model: sessions.NewSessionDialogCmp(allSessions, a.selectedSessionID),
161			}
162		}
163
164	case commands.SwitchModelMsg:
165		return a, util.CmdHandler(
166			dialogs.OpenDialogMsg{
167				Model: models.NewModelDialogCmp(),
168			},
169		)
170	// Compact
171	case commands.CompactMsg:
172		return a, util.CmdHandler(dialogs.OpenDialogMsg{
173			Model: compact.NewCompactDialogCmp(a.app.CoderAgent, msg.SessionID, true),
174		})
175
176	// Model Switch
177	case models.ModelSelectedMsg:
178		model, err := a.app.CoderAgent.Update(config.AgentCoder, msg.Model.ID)
179		if err != nil {
180			return a, util.ReportError(err)
181		}
182
183		return a, util.ReportInfo(fmt.Sprintf("Model changed to %s", model.Name))
184
185	// File Picker
186	case chat.OpenFilePickerMsg:
187		if a.dialog.ActiveDialogID() == filepicker.FilePickerID {
188			// If the commands dialog is already open, close it
189			return a, util.CmdHandler(dialogs.CloseDialogMsg{})
190		}
191		return a, util.CmdHandler(dialogs.OpenDialogMsg{
192			Model: filepicker.NewFilePickerCmp(),
193		})
194	// Permissions
195	case pubsub.Event[permission.PermissionRequest]:
196		return a, util.CmdHandler(dialogs.OpenDialogMsg{
197			Model: permissions.NewPermissionDialogCmp(msg.Payload),
198		})
199	case permissions.PermissionResponseMsg:
200		switch msg.Action {
201		case permissions.PermissionAllow:
202			a.app.Permissions.Grant(msg.Permission)
203		case permissions.PermissionAllowForSession:
204			a.app.Permissions.GrantPersistent(msg.Permission)
205		case permissions.PermissionDeny:
206			a.app.Permissions.Deny(msg.Permission)
207		}
208		return a, nil
209	// Agent Events
210	case pubsub.Event[agent.AgentEvent]:
211		payload := msg.Payload
212
213		// Forward agent events to dialogs
214		if a.dialog.HasDialogs() && a.dialog.ActiveDialogID() == compact.CompactDialogID {
215			u, dialogCmd := a.dialog.Update(payload)
216			a.dialog = u.(dialogs.DialogCmp)
217			cmds = append(cmds, dialogCmd)
218		}
219
220		// Handle auto-compact logic
221		if payload.Done && payload.Type == agent.AgentEventTypeResponse && a.selectedSessionID != "" {
222			// Get current session to check token usage
223			session, err := a.app.Sessions.Get(context.Background(), a.selectedSessionID)
224			if err == nil {
225				model := a.app.CoderAgent.Model()
226				contextWindow := model.ContextWindow
227				tokens := session.CompletionTokens + session.PromptTokens
228				if (tokens >= int64(float64(contextWindow)*0.95)) && config.Get().AutoCompact {
229					// Show compact confirmation dialog
230					cmds = append(cmds, util.CmdHandler(dialogs.OpenDialogMsg{
231						Model: compact.NewCompactDialogCmp(a.app.CoderAgent, a.selectedSessionID, false),
232					}))
233				}
234			}
235		}
236
237		return a, tea.Batch(cmds...)
238	// Key Press Messages
239	case tea.KeyPressMsg:
240		return a, a.handleKeyPressMsg(msg)
241	}
242	s, _ := a.status.Update(msg)
243	a.status = s.(status.StatusCmp)
244	updated, cmd := a.pages[a.currentPage].Update(msg)
245	a.pages[a.currentPage] = updated.(util.Model)
246	if a.dialog.HasDialogs() {
247		u, dialogCmd := a.dialog.Update(msg)
248		a.dialog = u.(dialogs.DialogCmp)
249		cmds = append(cmds, dialogCmd)
250	}
251	cmds = append(cmds, cmd)
252	return a, tea.Batch(cmds...)
253}
254
255// handleWindowResize processes window resize events and updates all components.
256func (a *appModel) handleWindowResize(width, height int) tea.Cmd {
257	var cmds []tea.Cmd
258	a.wWidth, a.wHeight = width, height
259	if a.showingFullHelp {
260		height -= 4
261	} else {
262		height -= 2
263	}
264	a.width, a.height = width, height
265	// Update status bar
266	s, cmd := a.status.Update(tea.WindowSizeMsg{Width: width, Height: height})
267	a.status = s.(status.StatusCmp)
268	cmds = append(cmds, cmd)
269
270	// Update the current page
271	for p, page := range a.pages {
272		updated, pageCmd := page.Update(tea.WindowSizeMsg{Width: width, Height: height})
273		a.pages[p] = updated.(util.Model)
274		cmds = append(cmds, pageCmd)
275	}
276
277	// Update the dialogs
278	dialog, cmd := a.dialog.Update(tea.WindowSizeMsg{Width: width, Height: height})
279	a.dialog = dialog.(dialogs.DialogCmp)
280	cmds = append(cmds, cmd)
281
282	return tea.Batch(cmds...)
283}
284
285// handleKeyPressMsg processes keyboard input and routes to appropriate handlers.
286func (a *appModel) handleKeyPressMsg(msg tea.KeyPressMsg) tea.Cmd {
287	switch {
288	// completions
289	case a.completions.Open() && key.Matches(msg, a.completions.KeyMap().Up):
290		u, cmd := a.completions.Update(msg)
291		a.completions = u.(completions.Completions)
292		return cmd
293
294	case a.completions.Open() && key.Matches(msg, a.completions.KeyMap().Down):
295		u, cmd := a.completions.Update(msg)
296		a.completions = u.(completions.Completions)
297		return cmd
298	case a.completions.Open() && key.Matches(msg, a.completions.KeyMap().Select):
299		u, cmd := a.completions.Update(msg)
300		a.completions = u.(completions.Completions)
301		return cmd
302	case a.completions.Open() && key.Matches(msg, a.completions.KeyMap().Cancel):
303		u, cmd := a.completions.Update(msg)
304		a.completions = u.(completions.Completions)
305		return cmd
306		// help
307	case key.Matches(msg, a.keyMap.Help):
308		a.status.ToggleFullHelp()
309		a.showingFullHelp = !a.showingFullHelp
310		return a.handleWindowResize(a.wWidth, a.wHeight)
311	// dialogs
312	case key.Matches(msg, a.keyMap.Quit):
313		if a.dialog.ActiveDialogID() == quit.QuitDialogID {
314			// if the quit dialog is already open, close the app
315			return tea.Quit
316		}
317		return util.CmdHandler(dialogs.OpenDialogMsg{
318			Model: quit.NewQuitDialog(),
319		})
320
321	case key.Matches(msg, a.keyMap.Commands):
322		if a.dialog.ActiveDialogID() == commands.CommandsDialogID {
323			// If the commands dialog is already open, close it
324			return util.CmdHandler(dialogs.CloseDialogMsg{})
325		}
326		return util.CmdHandler(dialogs.OpenDialogMsg{
327			Model: commands.NewCommandDialog(a.selectedSessionID),
328		})
329	case key.Matches(msg, a.keyMap.Sessions):
330		if a.dialog.ActiveDialogID() == sessions.SessionsDialogID {
331			// If the sessions dialog is already open, close it
332			return util.CmdHandler(dialogs.CloseDialogMsg{})
333		}
334		var cmds []tea.Cmd
335		if a.dialog.ActiveDialogID() == commands.CommandsDialogID {
336			// If the commands dialog is open, close it first
337			cmds = append(cmds, util.CmdHandler(dialogs.CloseDialogMsg{}))
338		}
339		cmds = append(cmds,
340			func() tea.Msg {
341				allSessions, _ := a.app.Sessions.List(context.Background())
342				return dialogs.OpenDialogMsg{
343					Model: sessions.NewSessionDialogCmp(allSessions, a.selectedSessionID),
344				}
345			},
346		)
347		return tea.Sequence(cmds...)
348	// Page navigation
349	case key.Matches(msg, a.keyMap.Logs):
350		return a.moveToPage(logs.LogsPage)
351
352	default:
353		if a.dialog.HasDialogs() {
354			u, dialogCmd := a.dialog.Update(msg)
355			a.dialog = u.(dialogs.DialogCmp)
356			return dialogCmd
357		} else {
358			updated, cmd := a.pages[a.currentPage].Update(msg)
359			a.pages[a.currentPage] = updated.(util.Model)
360			return cmd
361		}
362	}
363}
364
365// moveToPage handles navigation between different pages in the application.
366func (a *appModel) moveToPage(pageID page.PageID) tea.Cmd {
367	if a.app.CoderAgent.IsBusy() {
368		// TODO: maybe remove this :  For now we don't move to any page if the agent is busy
369		return util.ReportWarn("Agent is busy, please wait...")
370	}
371
372	var cmds []tea.Cmd
373	if _, ok := a.loadedPages[pageID]; !ok {
374		cmd := a.pages[pageID].Init()
375		cmds = append(cmds, cmd)
376		a.loadedPages[pageID] = true
377	}
378	a.previousPage = a.currentPage
379	a.currentPage = pageID
380	if sizable, ok := a.pages[a.currentPage].(layout.Sizeable); ok {
381		cmd := sizable.SetSize(a.width, a.height)
382		cmds = append(cmds, cmd)
383	}
384
385	return tea.Batch(cmds...)
386}
387
388// View renders the complete application interface including pages, dialogs, and overlays.
389func (a *appModel) View() tea.View {
390	page := a.pages[a.currentPage]
391	if withHelp, ok := page.(layout.Help); ok {
392		a.keyMap.pageBindings = withHelp.Bindings()
393	}
394	a.status.SetKeyMap(a.keyMap)
395	pageView := page.View()
396	components := []string{
397		pageView,
398	}
399	components = append(components, a.status.View())
400
401	appView := lipgloss.JoinVertical(lipgloss.Top, components...)
402	layers := []*lipgloss.Layer{
403		lipgloss.NewLayer(appView),
404	}
405	if a.dialog.HasDialogs() {
406		layers = append(
407			layers,
408			a.dialog.GetLayers()...,
409		)
410	}
411
412	var cursor *tea.Cursor
413	if v, ok := page.(util.Cursor); ok {
414		cursor = v.Cursor()
415	}
416	activeView := a.dialog.ActiveModel()
417	if activeView != nil {
418		cursor = nil // Reset cursor if a dialog is active unless it implements util.Cursor
419		if v, ok := activeView.(util.Cursor); ok {
420			cursor = v.Cursor()
421		}
422	}
423
424	if a.completions.Open() && cursor != nil {
425		cmp := a.completions.View()
426		x, y := a.completions.Position()
427		layers = append(
428			layers,
429			lipgloss.NewLayer(cmp).X(x).Y(y),
430		)
431	}
432
433	canvas := lipgloss.NewCanvas(
434		layers...,
435	)
436
437	var view tea.View
438	t := styles.CurrentTheme()
439	view.Layer = canvas
440	view.BackgroundColor = t.BgBase
441	view.Cursor = cursor
442	return view
443}
444
445// New creates and initializes a new TUI application model.
446func New(app *app.App) tea.Model {
447	chatPage := chat.NewChatPage(app)
448	keyMap := DefaultKeyMap()
449	keyMap.pageBindings = chatPage.Bindings()
450
451	model := &appModel{
452		currentPage: chat.ChatPageID,
453		app:         app,
454		status:      status.NewStatusCmp(keyMap),
455		loadedPages: make(map[page.PageID]bool),
456		keyMap:      keyMap,
457
458		pages: map[page.PageID]util.Model{
459			chat.ChatPageID: chatPage,
460			logs.LogsPage:   logs.NewLogsPage(),
461		},
462
463		dialog:      dialogs.NewDialogCmp(),
464		completions: completions.New(),
465	}
466
467	return model
468}