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.MouseWheelMsg:
257 if !a.dialog.HasDialogs() {
258 updated, pageCmd := a.pages[a.currentPage].Update(msg)
259 a.pages[a.currentPage] = updated.(util.Model)
260 cmds = append(cmds, pageCmd)
261 }
262 return a, tea.Batch(cmds...)
263 case tea.PasteMsg:
264 if a.dialog.HasDialogs() {
265 u, dialogCmd := a.dialog.Update(msg)
266 a.dialog = u.(dialogs.DialogCmp)
267 cmds = append(cmds, dialogCmd)
268 } else {
269 updated, pageCmd := a.pages[a.currentPage].Update(msg)
270 a.pages[a.currentPage] = updated.(util.Model)
271 cmds = append(cmds, pageCmd)
272 }
273 return a, tea.Batch(cmds...)
274 }
275 s, _ := a.status.Update(msg)
276 a.status = s.(status.StatusCmp)
277 updated, cmd := a.pages[a.currentPage].Update(msg)
278 a.pages[a.currentPage] = updated.(util.Model)
279 if a.dialog.HasDialogs() {
280 u, dialogCmd := a.dialog.Update(msg)
281 a.dialog = u.(dialogs.DialogCmp)
282 cmds = append(cmds, dialogCmd)
283 }
284 cmds = append(cmds, cmd)
285 return a, tea.Batch(cmds...)
286}
287
288// handleWindowResize processes window resize events and updates all components.
289func (a *appModel) handleWindowResize(width, height int) tea.Cmd {
290 var cmds []tea.Cmd
291 if a.showingFullHelp {
292 height -= 5
293 } else {
294 height -= 2
295 }
296 a.width, a.height = width, height
297 // Update status bar
298 s, cmd := a.status.Update(tea.WindowSizeMsg{Width: width, Height: height})
299 a.status = s.(status.StatusCmp)
300 cmds = append(cmds, cmd)
301
302 // Update the current page
303 for p, page := range a.pages {
304 updated, pageCmd := page.Update(tea.WindowSizeMsg{Width: width, Height: height})
305 a.pages[p] = updated.(util.Model)
306 cmds = append(cmds, pageCmd)
307 }
308
309 // Update the dialogs
310 dialog, cmd := a.dialog.Update(tea.WindowSizeMsg{Width: width, Height: height})
311 a.dialog = dialog.(dialogs.DialogCmp)
312 cmds = append(cmds, cmd)
313
314 return tea.Batch(cmds...)
315}
316
317// handleKeyPressMsg processes keyboard input and routes to appropriate handlers.
318func (a *appModel) handleKeyPressMsg(msg tea.KeyPressMsg) tea.Cmd {
319 if a.completions.Open() {
320 // completions
321 keyMap := a.completions.KeyMap()
322 switch {
323 case key.Matches(msg, keyMap.Up), key.Matches(msg, keyMap.Down),
324 key.Matches(msg, keyMap.Select), key.Matches(msg, keyMap.Cancel),
325 key.Matches(msg, keyMap.UpInsert), key.Matches(msg, keyMap.DownInsert):
326 u, cmd := a.completions.Update(msg)
327 a.completions = u.(completions.Completions)
328 return cmd
329 }
330 }
331 switch {
332 // help
333 case key.Matches(msg, a.keyMap.Help):
334 a.status.ToggleFullHelp()
335 a.showingFullHelp = !a.showingFullHelp
336 return a.handleWindowResize(a.wWidth, a.wHeight)
337 // dialogs
338 case key.Matches(msg, a.keyMap.Quit):
339 if a.dialog.ActiveDialogID() == quit.QuitDialogID {
340 return tea.Quit
341 }
342 return util.CmdHandler(dialogs.OpenDialogMsg{
343 Model: quit.NewQuitDialog(),
344 })
345
346 case key.Matches(msg, a.keyMap.Commands):
347 // if the app is not configured show no commands
348 if !a.isConfigured {
349 return nil
350 }
351 if a.dialog.ActiveDialogID() == commands.CommandsDialogID {
352 return util.CmdHandler(dialogs.CloseDialogMsg{})
353 }
354 if a.dialog.HasDialogs() {
355 return nil
356 }
357 return util.CmdHandler(dialogs.OpenDialogMsg{
358 Model: commands.NewCommandDialog(a.selectedSessionID),
359 })
360 case key.Matches(msg, a.keyMap.Sessions):
361 // if the app is not configured show no sessions
362 if !a.isConfigured {
363 return nil
364 }
365 if a.dialog.ActiveDialogID() == sessions.SessionsDialogID {
366 return util.CmdHandler(dialogs.CloseDialogMsg{})
367 }
368 if a.dialog.HasDialogs() && a.dialog.ActiveDialogID() != commands.CommandsDialogID {
369 return nil
370 }
371 var cmds []tea.Cmd
372 if a.dialog.ActiveDialogID() == commands.CommandsDialogID {
373 // If the commands dialog is open, close it first
374 cmds = append(cmds, util.CmdHandler(dialogs.CloseDialogMsg{}))
375 }
376 cmds = append(cmds,
377 func() tea.Msg {
378 allSessions, _ := a.app.Sessions.List(context.Background())
379 return dialogs.OpenDialogMsg{
380 Model: sessions.NewSessionDialogCmp(allSessions, a.selectedSessionID),
381 }
382 },
383 )
384 return tea.Sequence(cmds...)
385 case key.Matches(msg, a.keyMap.Suspend):
386 if a.app.CoderAgent.IsBusy() {
387 return util.ReportWarn("Agent is busy, please wait...")
388 }
389 return tea.Suspend
390 default:
391 if a.dialog.HasDialogs() {
392 u, dialogCmd := a.dialog.Update(msg)
393 a.dialog = u.(dialogs.DialogCmp)
394 return dialogCmd
395 } else {
396 updated, cmd := a.pages[a.currentPage].Update(msg)
397 a.pages[a.currentPage] = updated.(util.Model)
398 return cmd
399 }
400 }
401}
402
403// moveToPage handles navigation between different pages in the application.
404func (a *appModel) moveToPage(pageID page.PageID) tea.Cmd {
405 if a.app.CoderAgent.IsBusy() {
406 // TODO: maybe remove this : For now we don't move to any page if the agent is busy
407 return util.ReportWarn("Agent is busy, please wait...")
408 }
409
410 var cmds []tea.Cmd
411 if _, ok := a.loadedPages[pageID]; !ok {
412 cmd := a.pages[pageID].Init()
413 cmds = append(cmds, cmd)
414 a.loadedPages[pageID] = true
415 }
416 a.previousPage = a.currentPage
417 a.currentPage = pageID
418 if sizable, ok := a.pages[a.currentPage].(layout.Sizeable); ok {
419 cmd := sizable.SetSize(a.width, a.height)
420 cmds = append(cmds, cmd)
421 }
422
423 return tea.Batch(cmds...)
424}
425
426// View renders the complete application interface including pages, dialogs, and overlays.
427func (a *appModel) View() tea.View {
428 var view tea.View
429 t := styles.CurrentTheme()
430 view.BackgroundColor = t.BgBase
431 if a.wWidth < 25 || a.wHeight < 15 {
432 view.Layer = lipgloss.NewCanvas(
433 lipgloss.NewLayer(
434 t.S().Base.Width(a.wWidth).Height(a.wHeight).
435 Align(lipgloss.Center, lipgloss.Center).
436 Render(
437 t.S().Base.
438 Padding(1, 4).
439 Foreground(t.White).
440 BorderStyle(lipgloss.RoundedBorder()).
441 BorderForeground(t.Primary).
442 Render("Window too small!"),
443 ),
444 ),
445 )
446 return view
447 }
448
449 page := a.pages[a.currentPage]
450 if withHelp, ok := page.(core.KeyMapHelp); ok {
451 a.status.SetKeyMap(withHelp.Help())
452 }
453 pageView := page.View()
454 components := []string{
455 pageView,
456 }
457 components = append(components, a.status.View())
458
459 appView := lipgloss.JoinVertical(lipgloss.Top, components...)
460 layers := []*lipgloss.Layer{
461 lipgloss.NewLayer(appView),
462 }
463 if a.dialog.HasDialogs() {
464 layers = append(
465 layers,
466 a.dialog.GetLayers()...,
467 )
468 }
469
470 var cursor *tea.Cursor
471 if v, ok := page.(util.Cursor); ok {
472 cursor = v.Cursor()
473 // Hide the cursor if it's positioned outside the textarea
474 statusHeight := a.height - strings.Count(pageView, "\n") + 1
475 if cursor != nil && cursor.Y+statusHeight+chat.EditorHeight-2 <= a.height { // 2 for the top and bottom app padding
476 cursor = nil
477 }
478 }
479 activeView := a.dialog.ActiveModel()
480 if activeView != nil {
481 cursor = nil // Reset cursor if a dialog is active unless it implements util.Cursor
482 if v, ok := activeView.(util.Cursor); ok {
483 cursor = v.Cursor()
484 }
485 }
486
487 if a.completions.Open() && cursor != nil {
488 cmp := a.completions.View()
489 x, y := a.completions.Position()
490 layers = append(
491 layers,
492 lipgloss.NewLayer(cmp).X(x).Y(y),
493 )
494 }
495
496 canvas := lipgloss.NewCanvas(
497 layers...,
498 )
499
500 view.Layer = canvas
501 view.Cursor = cursor
502 return view
503}
504
505// New creates and initializes a new TUI application model.
506func New(app *app.App) tea.Model {
507 chatPage := chat.New(app)
508 keyMap := DefaultKeyMap()
509 keyMap.pageBindings = chatPage.Bindings()
510
511 model := &appModel{
512 currentPage: chat.ChatPageID,
513 app: app,
514 status: status.NewStatusCmp(),
515 loadedPages: make(map[page.PageID]bool),
516 keyMap: keyMap,
517
518 pages: map[page.PageID]util.Model{
519 chat.ChatPageID: chatPage,
520 },
521
522 dialog: dialogs.NewDialogCmp(),
523 completions: completions.New(),
524 }
525
526 return model
527}