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