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.ProjectNeedsInitialization()
 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		config.UpdatePreferredModel(msg.ModelType, msg.Model)
179
180		// Update the agent with the new model/provider configuration
181		if err := a.app.UpdateAgentModel(); err != nil {
182			logging.ErrorPersist(fmt.Sprintf("Failed to update agent model: %v", err))
183			return a, util.ReportError(fmt.Errorf("model changed to %s but failed to update agent: %v", msg.Model.ModelID, err))
184		}
185
186		modelTypeName := "large"
187		if msg.ModelType == config.SmallModel {
188			modelTypeName = "small"
189		}
190		return a, util.ReportInfo(fmt.Sprintf("%s model changed to %s", modelTypeName, msg.Model.ModelID))
191
192	// File Picker
193	case chat.OpenFilePickerMsg:
194		if a.dialog.ActiveDialogID() == filepicker.FilePickerID {
195			// If the commands dialog is already open, close it
196			return a, util.CmdHandler(dialogs.CloseDialogMsg{})
197		}
198		return a, util.CmdHandler(dialogs.OpenDialogMsg{
199			Model: filepicker.NewFilePickerCmp(),
200		})
201	// Permissions
202	case pubsub.Event[permission.PermissionRequest]:
203		return a, util.CmdHandler(dialogs.OpenDialogMsg{
204			Model: permissions.NewPermissionDialogCmp(msg.Payload),
205		})
206	case permissions.PermissionResponseMsg:
207		switch msg.Action {
208		case permissions.PermissionAllow:
209			a.app.Permissions.Grant(msg.Permission)
210		case permissions.PermissionAllowForSession:
211			a.app.Permissions.GrantPersistent(msg.Permission)
212		case permissions.PermissionDeny:
213			a.app.Permissions.Deny(msg.Permission)
214		}
215		return a, nil
216	// Agent Events
217	case pubsub.Event[agent.AgentEvent]:
218		payload := msg.Payload
219
220		// Forward agent events to dialogs
221		if a.dialog.HasDialogs() && a.dialog.ActiveDialogID() == compact.CompactDialogID {
222			u, dialogCmd := a.dialog.Update(payload)
223			a.dialog = u.(dialogs.DialogCmp)
224			cmds = append(cmds, dialogCmd)
225		}
226
227		// Handle auto-compact logic
228		if payload.Done && payload.Type == agent.AgentEventTypeResponse && a.selectedSessionID != "" {
229			// Get current session to check token usage
230			session, err := a.app.Sessions.Get(context.Background(), a.selectedSessionID)
231			if err == nil {
232				model := a.app.CoderAgent.Model()
233				contextWindow := model.ContextWindow
234				tokens := session.CompletionTokens + session.PromptTokens
235				if (tokens >= int64(float64(contextWindow)*0.95)) && !config.Get().Options.DisableAutoSummarize { // Show compact confirmation dialog
236					cmds = append(cmds, util.CmdHandler(dialogs.OpenDialogMsg{
237						Model: compact.NewCompactDialogCmp(a.app.CoderAgent, a.selectedSessionID, false),
238					}))
239				}
240			}
241		}
242
243		return a, tea.Batch(cmds...)
244	// Key Press Messages
245	case tea.KeyPressMsg:
246		return a, a.handleKeyPressMsg(msg)
247	}
248	s, _ := a.status.Update(msg)
249	a.status = s.(status.StatusCmp)
250	updated, cmd := a.pages[a.currentPage].Update(msg)
251	a.pages[a.currentPage] = updated.(util.Model)
252	if a.dialog.HasDialogs() {
253		u, dialogCmd := a.dialog.Update(msg)
254		a.dialog = u.(dialogs.DialogCmp)
255		cmds = append(cmds, dialogCmd)
256	}
257	cmds = append(cmds, cmd)
258	return a, tea.Batch(cmds...)
259}
260
261// handleWindowResize processes window resize events and updates all components.
262func (a *appModel) handleWindowResize(width, height int) tea.Cmd {
263	var cmds []tea.Cmd
264	a.wWidth, a.wHeight = width, height
265	if a.showingFullHelp {
266		height -= 4
267	} else {
268		height -= 2
269	}
270	a.width, a.height = width, height
271	// Update status bar
272	s, cmd := a.status.Update(tea.WindowSizeMsg{Width: width, Height: height})
273	a.status = s.(status.StatusCmp)
274	cmds = append(cmds, cmd)
275
276	// Update the current page
277	for p, page := range a.pages {
278		updated, pageCmd := page.Update(tea.WindowSizeMsg{Width: width, Height: height})
279		a.pages[p] = updated.(util.Model)
280		cmds = append(cmds, pageCmd)
281	}
282
283	// Update the dialogs
284	dialog, cmd := a.dialog.Update(tea.WindowSizeMsg{Width: width, Height: height})
285	a.dialog = dialog.(dialogs.DialogCmp)
286	cmds = append(cmds, cmd)
287
288	return tea.Batch(cmds...)
289}
290
291// handleKeyPressMsg processes keyboard input and routes to appropriate handlers.
292func (a *appModel) handleKeyPressMsg(msg tea.KeyPressMsg) tea.Cmd {
293	switch {
294	// completions
295	case a.completions.Open() && key.Matches(msg, a.completions.KeyMap().Up):
296		u, cmd := a.completions.Update(msg)
297		a.completions = u.(completions.Completions)
298		return cmd
299
300	case a.completions.Open() && key.Matches(msg, a.completions.KeyMap().Down):
301		u, cmd := a.completions.Update(msg)
302		a.completions = u.(completions.Completions)
303		return cmd
304	case a.completions.Open() && key.Matches(msg, a.completions.KeyMap().Select):
305		u, cmd := a.completions.Update(msg)
306		a.completions = u.(completions.Completions)
307		return cmd
308	case a.completions.Open() && key.Matches(msg, a.completions.KeyMap().Cancel):
309		u, cmd := a.completions.Update(msg)
310		a.completions = u.(completions.Completions)
311		return cmd
312		// help
313	case key.Matches(msg, a.keyMap.Help):
314		a.status.ToggleFullHelp()
315		a.showingFullHelp = !a.showingFullHelp
316		return a.handleWindowResize(a.wWidth, a.wHeight)
317	// dialogs
318	case key.Matches(msg, a.keyMap.Quit):
319		if a.dialog.ActiveDialogID() == quit.QuitDialogID {
320			// if the quit dialog is already open, close the app
321			return tea.Quit
322		}
323		return util.CmdHandler(dialogs.OpenDialogMsg{
324			Model: quit.NewQuitDialog(),
325		})
326
327	case key.Matches(msg, a.keyMap.Commands):
328		if a.dialog.ActiveDialogID() == commands.CommandsDialogID {
329			// If the commands dialog is already open, close it
330			return util.CmdHandler(dialogs.CloseDialogMsg{})
331		}
332		return util.CmdHandler(dialogs.OpenDialogMsg{
333			Model: commands.NewCommandDialog(a.selectedSessionID),
334		})
335	case key.Matches(msg, a.keyMap.Sessions):
336		if a.dialog.ActiveDialogID() == sessions.SessionsDialogID {
337			// If the sessions dialog is already open, close it
338			return util.CmdHandler(dialogs.CloseDialogMsg{})
339		}
340		var cmds []tea.Cmd
341		if a.dialog.ActiveDialogID() == commands.CommandsDialogID {
342			// If the commands dialog is open, close it first
343			cmds = append(cmds, util.CmdHandler(dialogs.CloseDialogMsg{}))
344		}
345		cmds = append(cmds,
346			func() tea.Msg {
347				allSessions, _ := a.app.Sessions.List(context.Background())
348				return dialogs.OpenDialogMsg{
349					Model: sessions.NewSessionDialogCmp(allSessions, a.selectedSessionID),
350				}
351			},
352		)
353		return tea.Sequence(cmds...)
354	// Page navigation
355	case key.Matches(msg, a.keyMap.Logs):
356		return a.moveToPage(logs.LogsPage)
357
358	default:
359		if a.dialog.HasDialogs() {
360			u, dialogCmd := a.dialog.Update(msg)
361			a.dialog = u.(dialogs.DialogCmp)
362			return dialogCmd
363		} else {
364			updated, cmd := a.pages[a.currentPage].Update(msg)
365			a.pages[a.currentPage] = updated.(util.Model)
366			return cmd
367		}
368	}
369}
370
371// moveToPage handles navigation between different pages in the application.
372func (a *appModel) moveToPage(pageID page.PageID) tea.Cmd {
373	if a.app.CoderAgent.IsBusy() {
374		// TODO: maybe remove this :  For now we don't move to any page if the agent is busy
375		return util.ReportWarn("Agent is busy, please wait...")
376	}
377
378	var cmds []tea.Cmd
379	if _, ok := a.loadedPages[pageID]; !ok {
380		cmd := a.pages[pageID].Init()
381		cmds = append(cmds, cmd)
382		a.loadedPages[pageID] = true
383	}
384	a.previousPage = a.currentPage
385	a.currentPage = pageID
386	if sizable, ok := a.pages[a.currentPage].(layout.Sizeable); ok {
387		cmd := sizable.SetSize(a.width, a.height)
388		cmds = append(cmds, cmd)
389	}
390
391	return tea.Batch(cmds...)
392}
393
394// View renders the complete application interface including pages, dialogs, and overlays.
395func (a *appModel) View() tea.View {
396	page := a.pages[a.currentPage]
397	if withHelp, ok := page.(layout.Help); ok {
398		a.keyMap.pageBindings = withHelp.Bindings()
399	}
400	a.status.SetKeyMap(a.keyMap)
401	pageView := page.View()
402	components := []string{
403		pageView,
404	}
405	components = append(components, a.status.View())
406
407	appView := lipgloss.JoinVertical(lipgloss.Top, components...)
408	layers := []*lipgloss.Layer{
409		lipgloss.NewLayer(appView),
410	}
411	if a.dialog.HasDialogs() {
412		layers = append(
413			layers,
414			a.dialog.GetLayers()...,
415		)
416	}
417
418	var cursor *tea.Cursor
419	if v, ok := page.(util.Cursor); ok {
420		cursor = v.Cursor()
421	}
422	activeView := a.dialog.ActiveModel()
423	if activeView != nil {
424		cursor = nil // Reset cursor if a dialog is active unless it implements util.Cursor
425		if v, ok := activeView.(util.Cursor); ok {
426			cursor = v.Cursor()
427		}
428	}
429
430	if a.completions.Open() && cursor != nil {
431		cmp := a.completions.View()
432		x, y := a.completions.Position()
433		layers = append(
434			layers,
435			lipgloss.NewLayer(cmp).X(x).Y(y),
436		)
437	}
438
439	canvas := lipgloss.NewCanvas(
440		layers...,
441	)
442
443	var view tea.View
444	t := styles.CurrentTheme()
445	view.Layer = canvas
446	view.BackgroundColor = t.BgBase
447	view.Cursor = cursor
448	return view
449}
450
451// New creates and initializes a new TUI application model.
452func New(app *app.App) tea.Model {
453	chatPage := chat.NewChatPage(app)
454	keyMap := DefaultKeyMap()
455	keyMap.pageBindings = chatPage.Bindings()
456
457	model := &appModel{
458		currentPage: chat.ChatPageID,
459		app:         app,
460		status:      status.NewStatusCmp(keyMap),
461		loadedPages: make(map[page.PageID]bool),
462		keyMap:      keyMap,
463
464		pages: map[page.PageID]util.Model{
465			chat.ChatPageID: chatPage,
466			logs.LogsPage:   logs.NewLogsPage(),
467		},
468
469		dialog:      dialogs.NewDialogCmp(),
470		completions: completions.New(),
471	}
472
473	return model
474}