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