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