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