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