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) < 15*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 item, ok := a.pages[a.currentPage]
80 if !ok {
81 return nil
82 }
83
84 var cmds []tea.Cmd
85 cmd := item.Init()
86 cmds = append(cmds, cmd)
87 a.loadedPages[a.currentPage] = true
88
89 cmd = a.status.Init()
90 cmds = append(cmds, cmd)
91
92 cmds = append(cmds, tea.EnableMouseAllMotion)
93
94 return tea.Batch(cmds...)
95}
96
97// Update handles incoming messages and updates the application state.
98func (a *appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
99 var cmds []tea.Cmd
100 var cmd tea.Cmd
101 a.isConfigured = config.HasInitialDataConfig()
102
103 switch msg := msg.(type) {
104 case tea.KeyboardEnhancementsMsg:
105 for id, page := range a.pages {
106 m, pageCmd := page.Update(msg)
107 if model, ok := m.(util.Model); ok {
108 a.pages[id] = model
109 }
110
111 if pageCmd != nil {
112 cmds = append(cmds, pageCmd)
113 }
114 }
115 return a, tea.Batch(cmds...)
116 case tea.WindowSizeMsg:
117 a.wWidth, a.wHeight = msg.Width, msg.Height
118 a.completions.Update(msg)
119 return a, a.handleWindowResize(msg.Width, msg.Height)
120
121 // Completions messages
122 case completions.OpenCompletionsMsg, completions.FilterCompletionsMsg,
123 completions.CloseCompletionsMsg, completions.RepositionCompletionsMsg:
124 u, completionCmd := a.completions.Update(msg)
125 if model, ok := u.(completions.Completions); ok {
126 a.completions = model
127 }
128
129 return a, completionCmd
130
131 // Dialog messages
132 case dialogs.OpenDialogMsg, dialogs.CloseDialogMsg:
133 u, completionCmd := a.completions.Update(completions.CloseCompletionsMsg{})
134 a.completions = u.(completions.Completions)
135 u, dialogCmd := a.dialog.Update(msg)
136 a.dialog = u.(dialogs.DialogCmp)
137 return a, tea.Batch(completionCmd, dialogCmd)
138 case commands.ShowArgumentsDialogMsg:
139 return a, util.CmdHandler(
140 dialogs.OpenDialogMsg{
141 Model: commands.NewCommandArgumentsDialog(
142 msg.CommandID,
143 msg.Content,
144 msg.ArgNames,
145 ),
146 },
147 )
148 // Page change messages
149 case page.PageChangeMsg:
150 return a, a.moveToPage(msg.ID)
151
152 // Status Messages
153 case util.InfoMsg, util.ClearStatusMsg:
154 s, statusCmd := a.status.Update(msg)
155 a.status = s.(status.StatusCmp)
156 cmds = append(cmds, statusCmd)
157 return a, tea.Batch(cmds...)
158
159 // Session
160 case cmpChat.SessionSelectedMsg:
161 a.selectedSessionID = msg.ID
162 case cmpChat.SessionClearedMsg:
163 a.selectedSessionID = ""
164 // Commands
165 case commands.SwitchSessionsMsg:
166 return a, func() tea.Msg {
167 allSessions, _ := a.app.Sessions.List(context.Background())
168 return dialogs.OpenDialogMsg{
169 Model: sessions.NewSessionDialogCmp(allSessions, a.selectedSessionID),
170 }
171 }
172
173 case commands.SwitchModelMsg:
174 return a, util.CmdHandler(
175 dialogs.OpenDialogMsg{
176 Model: models.NewModelDialogCmp(),
177 },
178 )
179 // Compact
180 case commands.CompactMsg:
181 return a, util.CmdHandler(dialogs.OpenDialogMsg{
182 Model: compact.NewCompactDialogCmp(a.app.CoderAgent, msg.SessionID, true),
183 })
184 case commands.QuitMsg:
185 return a, util.CmdHandler(dialogs.OpenDialogMsg{
186 Model: quit.NewQuitDialog(),
187 })
188 case commands.ToggleYoloModeMsg:
189 a.app.Permissions.SetSkipRequests(!a.app.Permissions.SkipRequests())
190 case commands.ToggleHelpMsg:
191 a.status.ToggleFullHelp()
192 a.showingFullHelp = !a.showingFullHelp
193 return a, a.handleWindowResize(a.wWidth, a.wHeight)
194 // Model Switch
195 case models.ModelSelectedMsg:
196 if a.app.CoderAgent.IsBusy() {
197 return a, util.ReportWarn("Agent is busy, please wait...")
198 }
199 config.Get().UpdatePreferredModel(msg.ModelType, msg.Model)
200
201 // Update the agent with the new model/provider configuration
202 if err := a.app.UpdateAgentModel(); err != nil {
203 return a, util.ReportError(fmt.Errorf("model changed to %s but failed to update agent: %v", msg.Model.Model, err))
204 }
205
206 modelTypeName := "large"
207 if msg.ModelType == config.SelectedModelTypeSmall {
208 modelTypeName = "small"
209 }
210 return a, util.ReportInfo(fmt.Sprintf("%s model changed to %s", modelTypeName, msg.Model.Model))
211
212 // File Picker
213 case commands.OpenFilePickerMsg:
214 if a.dialog.ActiveDialogID() == filepicker.FilePickerID {
215 // If the commands dialog is already open, close it
216 return a, util.CmdHandler(dialogs.CloseDialogMsg{})
217 }
218 return a, util.CmdHandler(dialogs.OpenDialogMsg{
219 Model: filepicker.NewFilePickerCmp(a.app.Config().WorkingDir()),
220 })
221 // Permissions
222 case pubsub.Event[permission.PermissionNotification]:
223 item, ok := a.pages[a.currentPage]
224 if !ok {
225 return a, nil
226 }
227
228 // Forward to view.
229 updated, itemCmd := item.Update(msg)
230 if model, ok := updated.(util.Model); ok {
231 a.pages[a.currentPage] = model
232 }
233
234 return a, itemCmd
235 case pubsub.Event[permission.PermissionRequest]:
236 return a, util.CmdHandler(dialogs.OpenDialogMsg{
237 Model: permissions.NewPermissionDialogCmp(msg.Payload, &permissions.Options{
238 DiffMode: config.Get().Options.TUI.DiffMode,
239 }),
240 })
241 case permissions.PermissionResponseMsg:
242 switch msg.Action {
243 case permissions.PermissionAllow:
244 a.app.Permissions.Grant(msg.Permission)
245 case permissions.PermissionAllowForSession:
246 a.app.Permissions.GrantPersistent(msg.Permission)
247 case permissions.PermissionDeny:
248 a.app.Permissions.Deny(msg.Permission)
249 }
250 return a, nil
251 // Agent Events
252 case pubsub.Event[agent.AgentEvent]:
253 payload := msg.Payload
254
255 // Forward agent events to dialogs
256 if a.dialog.HasDialogs() && a.dialog.ActiveDialogID() == compact.CompactDialogID {
257 u, dialogCmd := a.dialog.Update(payload)
258 if model, ok := u.(dialogs.DialogCmp); ok {
259 a.dialog = model
260 }
261
262 cmds = append(cmds, dialogCmd)
263 }
264
265 // Handle auto-compact logic
266 if payload.Done && payload.Type == agent.AgentEventTypeResponse && a.selectedSessionID != "" {
267 // Get current session to check token usage
268 session, err := a.app.Sessions.Get(context.Background(), a.selectedSessionID)
269 if err == nil {
270 model := a.app.CoderAgent.Model()
271 contextWindow := model.ContextWindow
272 tokens := session.CompletionTokens + session.PromptTokens
273 if (tokens >= int64(float64(contextWindow)*0.95)) && !config.Get().Options.DisableAutoSummarize { // Show compact confirmation dialog
274 cmds = append(cmds, util.CmdHandler(dialogs.OpenDialogMsg{
275 Model: compact.NewCompactDialogCmp(a.app.CoderAgent, a.selectedSessionID, false),
276 }))
277 }
278 }
279 }
280
281 return a, tea.Batch(cmds...)
282 case splash.OnboardingCompleteMsg:
283 item, ok := a.pages[a.currentPage]
284 if !ok {
285 return a, nil
286 }
287
288 a.isConfigured = config.HasInitialDataConfig()
289 updated, pageCmd := item.Update(msg)
290 if model, ok := updated.(util.Model); ok {
291 a.pages[a.currentPage] = model
292 }
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 if model, ok := updated.(util.Model); ok {
313 a.pages[a.currentPage] = model
314 }
315
316 cmds = append(cmds, pageCmd)
317 }
318 return a, tea.Batch(cmds...)
319 case tea.PasteMsg:
320 if a.dialog.HasDialogs() {
321 u, dialogCmd := a.dialog.Update(msg)
322 if model, ok := u.(dialogs.DialogCmp); ok {
323 a.dialog = model
324 }
325
326 cmds = append(cmds, dialogCmd)
327 } else {
328 item, ok := a.pages[a.currentPage]
329 if !ok {
330 return a, nil
331 }
332
333 updated, pageCmd := item.Update(msg)
334 if model, ok := updated.(util.Model); ok {
335 a.pages[a.currentPage] = model
336 }
337
338 cmds = append(cmds, pageCmd)
339 }
340 return a, tea.Batch(cmds...)
341 }
342 s, _ := a.status.Update(msg)
343 a.status = s.(status.StatusCmp)
344
345 item, ok := a.pages[a.currentPage]
346 if !ok {
347 return a, nil
348 }
349
350 updated, cmd := item.Update(msg)
351 if model, ok := updated.(util.Model); ok {
352 a.pages[a.currentPage] = model
353 }
354
355 if a.dialog.HasDialogs() {
356 u, dialogCmd := a.dialog.Update(msg)
357 if model, ok := u.(dialogs.DialogCmp); ok {
358 a.dialog = model
359 }
360
361 cmds = append(cmds, dialogCmd)
362 }
363 cmds = append(cmds, cmd)
364 return a, tea.Batch(cmds...)
365}
366
367// handleWindowResize processes window resize events and updates all components.
368func (a *appModel) handleWindowResize(width, height int) tea.Cmd {
369 var cmds []tea.Cmd
370
371 // TODO: clean up these magic numbers.
372 if a.showingFullHelp {
373 height -= 5
374 } else {
375 height -= 2
376 }
377
378 a.width, a.height = width, height
379 // Update status bar
380 s, cmd := a.status.Update(tea.WindowSizeMsg{Width: width, Height: height})
381 if model, ok := s.(status.StatusCmp); ok {
382 a.status = model
383 }
384 cmds = append(cmds, cmd)
385
386 // Update the current view.
387 for p, page := range a.pages {
388 updated, pageCmd := page.Update(tea.WindowSizeMsg{Width: width, Height: height})
389 if model, ok := updated.(util.Model); ok {
390 a.pages[p] = model
391 }
392
393 cmds = append(cmds, pageCmd)
394 }
395
396 // Update the dialogs
397 dialog, cmd := a.dialog.Update(tea.WindowSizeMsg{Width: width, Height: height})
398 if model, ok := dialog.(dialogs.DialogCmp); ok {
399 a.dialog = model
400 }
401
402 cmds = append(cmds, cmd)
403
404 return tea.Batch(cmds...)
405}
406
407// handleKeyPressMsg processes keyboard input and routes to appropriate handlers.
408func (a *appModel) handleKeyPressMsg(msg tea.KeyPressMsg) tea.Cmd {
409 if a.completions.Open() {
410 // completions
411 keyMap := a.completions.KeyMap()
412 switch {
413 case key.Matches(msg, keyMap.Up), key.Matches(msg, keyMap.Down),
414 key.Matches(msg, keyMap.Select), key.Matches(msg, keyMap.Cancel),
415 key.Matches(msg, keyMap.UpInsert), key.Matches(msg, keyMap.DownInsert):
416 u, cmd := a.completions.Update(msg)
417 a.completions = u.(completions.Completions)
418 return cmd
419 }
420 }
421 if a.dialog.HasDialogs() {
422 u, dialogCmd := a.dialog.Update(msg)
423 a.dialog = u.(dialogs.DialogCmp)
424 return dialogCmd
425 }
426 switch {
427 // help
428 case key.Matches(msg, a.keyMap.Help):
429 a.status.ToggleFullHelp()
430 a.showingFullHelp = !a.showingFullHelp
431 return a.handleWindowResize(a.wWidth, a.wHeight)
432 // dialogs
433 case key.Matches(msg, a.keyMap.Quit):
434 if a.dialog.ActiveDialogID() == quit.QuitDialogID {
435 return tea.Quit
436 }
437 return util.CmdHandler(dialogs.OpenDialogMsg{
438 Model: quit.NewQuitDialog(),
439 })
440
441 case key.Matches(msg, a.keyMap.Commands):
442 // if the app is not configured show no commands
443 if !a.isConfigured {
444 return nil
445 }
446 if a.dialog.ActiveDialogID() == commands.CommandsDialogID {
447 return util.CmdHandler(dialogs.CloseDialogMsg{})
448 }
449 if a.dialog.HasDialogs() {
450 return nil
451 }
452 return util.CmdHandler(dialogs.OpenDialogMsg{
453 Model: commands.NewCommandDialog(a.selectedSessionID),
454 })
455 case key.Matches(msg, a.keyMap.Sessions):
456 // if the app is not configured show no sessions
457 if !a.isConfigured {
458 return nil
459 }
460 if a.dialog.ActiveDialogID() == sessions.SessionsDialogID {
461 return util.CmdHandler(dialogs.CloseDialogMsg{})
462 }
463 if a.dialog.HasDialogs() && a.dialog.ActiveDialogID() != commands.CommandsDialogID {
464 return nil
465 }
466 var cmds []tea.Cmd
467 if a.dialog.ActiveDialogID() == commands.CommandsDialogID {
468 // If the commands dialog is open, close it first
469 cmds = append(cmds, util.CmdHandler(dialogs.CloseDialogMsg{}))
470 }
471 cmds = append(cmds,
472 func() tea.Msg {
473 allSessions, _ := a.app.Sessions.List(context.Background())
474 return dialogs.OpenDialogMsg{
475 Model: sessions.NewSessionDialogCmp(allSessions, a.selectedSessionID),
476 }
477 },
478 )
479 return tea.Sequence(cmds...)
480 case key.Matches(msg, a.keyMap.Suspend):
481 if a.app.CoderAgent != nil && a.app.CoderAgent.IsBusy() {
482 return util.ReportWarn("Agent is busy, please wait...")
483 }
484 return tea.Suspend
485 default:
486 item, ok := a.pages[a.currentPage]
487 if !ok {
488 return nil
489 }
490
491 updated, cmd := item.Update(msg)
492 if model, ok := updated.(util.Model); ok {
493 a.pages[a.currentPage] = model
494 }
495 return cmd
496 }
497}
498
499// moveToPage handles navigation between different pages in the application.
500func (a *appModel) moveToPage(pageID page.PageID) tea.Cmd {
501 if a.app.CoderAgent.IsBusy() {
502 // TODO: maybe remove this : For now we don't move to any page if the agent is busy
503 return util.ReportWarn("Agent is busy, please wait...")
504 }
505
506 var cmds []tea.Cmd
507 if _, ok := a.loadedPages[pageID]; !ok {
508 cmd := a.pages[pageID].Init()
509 cmds = append(cmds, cmd)
510 a.loadedPages[pageID] = true
511 }
512 a.previousPage = a.currentPage
513 a.currentPage = pageID
514 if sizable, ok := a.pages[a.currentPage].(layout.Sizeable); ok {
515 cmd := sizable.SetSize(a.width, a.height)
516 cmds = append(cmds, cmd)
517 }
518
519 return tea.Batch(cmds...)
520}
521
522// View renders the complete application interface including pages, dialogs, and overlays.
523func (a *appModel) View() tea.View {
524 var view tea.View
525 t := styles.CurrentTheme()
526 view.BackgroundColor = t.BgBase
527 if a.wWidth < 25 || a.wHeight < 15 {
528 view.Layer = lipgloss.NewCanvas(
529 lipgloss.NewLayer(
530 t.S().Base.Width(a.wWidth).Height(a.wHeight).
531 Align(lipgloss.Center, lipgloss.Center).
532 Render(
533 t.S().Base.
534 Padding(1, 4).
535 Foreground(t.White).
536 BorderStyle(lipgloss.RoundedBorder()).
537 BorderForeground(t.Primary).
538 Render("Window too small!"),
539 ),
540 ),
541 )
542 return view
543 }
544
545 page := a.pages[a.currentPage]
546 if withHelp, ok := page.(core.KeyMapHelp); ok {
547 a.status.SetKeyMap(withHelp.Help())
548 }
549 pageView := page.View()
550 components := []string{
551 pageView,
552 }
553 components = append(components, a.status.View())
554
555 appView := lipgloss.JoinVertical(lipgloss.Top, components...)
556 layers := []*lipgloss.Layer{
557 lipgloss.NewLayer(appView),
558 }
559 if a.dialog.HasDialogs() {
560 layers = append(
561 layers,
562 a.dialog.GetLayers()...,
563 )
564 }
565
566 var cursor *tea.Cursor
567 if v, ok := page.(util.Cursor); ok {
568 cursor = v.Cursor()
569 // Hide the cursor if it's positioned outside the textarea
570 statusHeight := a.height - strings.Count(pageView, "\n") + 1
571 if cursor != nil && cursor.Y+statusHeight+chat.EditorHeight-2 <= a.height { // 2 for the top and bottom app padding
572 cursor = nil
573 }
574 }
575 activeView := a.dialog.ActiveModel()
576 if activeView != nil {
577 cursor = nil // Reset cursor if a dialog is active unless it implements util.Cursor
578 if v, ok := activeView.(util.Cursor); ok {
579 cursor = v.Cursor()
580 }
581 }
582
583 if a.completions.Open() && cursor != nil {
584 cmp := a.completions.View()
585 x, y := a.completions.Position()
586 layers = append(
587 layers,
588 lipgloss.NewLayer(cmp).X(x).Y(y),
589 )
590 }
591
592 canvas := lipgloss.NewCanvas(
593 layers...,
594 )
595
596 view.Layer = canvas
597 view.Cursor = cursor
598 return view
599}
600
601// New creates and initializes a new TUI application model.
602func New(app *app.App) tea.Model {
603 chatPage := chat.New(app)
604 keyMap := DefaultKeyMap()
605 keyMap.pageBindings = chatPage.Bindings()
606
607 model := &appModel{
608 currentPage: chat.ChatPageID,
609 app: app,
610 status: status.NewStatusCmp(),
611 loadedPages: make(map[page.PageID]bool),
612 keyMap: keyMap,
613
614 pages: map[page.PageID]util.Model{
615 chat.ChatPageID: chatPage,
616 },
617
618 dialog: dialogs.NewDialogCmp(),
619 completions: completions.New(),
620 }
621
622 return model
623}