1package tui
2
3import (
4 "context"
5 "fmt"
6 "log/slog"
7 "strings"
8 "time"
9
10 "github.com/charmbracelet/bubbles/v2/key"
11 tea "github.com/charmbracelet/bubbletea/v2"
12 "github.com/charmbracelet/crush/internal/app"
13 "github.com/charmbracelet/crush/internal/config"
14 "github.com/charmbracelet/crush/internal/llm/agent"
15 "github.com/charmbracelet/crush/internal/permission"
16 "github.com/charmbracelet/crush/internal/pubsub"
17 cmpChat "github.com/charmbracelet/crush/internal/tui/components/chat"
18 "github.com/charmbracelet/crush/internal/tui/components/chat/splash"
19 "github.com/charmbracelet/crush/internal/tui/components/completions"
20 "github.com/charmbracelet/crush/internal/tui/components/core"
21 "github.com/charmbracelet/crush/internal/tui/components/core/layout"
22 "github.com/charmbracelet/crush/internal/tui/components/core/status"
23 "github.com/charmbracelet/crush/internal/tui/components/dialogs"
24 "github.com/charmbracelet/crush/internal/tui/components/dialogs/commands"
25 "github.com/charmbracelet/crush/internal/tui/components/dialogs/compact"
26 "github.com/charmbracelet/crush/internal/tui/components/dialogs/filepicker"
27 "github.com/charmbracelet/crush/internal/tui/components/dialogs/models"
28 "github.com/charmbracelet/crush/internal/tui/components/dialogs/permissions"
29 "github.com/charmbracelet/crush/internal/tui/components/dialogs/quit"
30 "github.com/charmbracelet/crush/internal/tui/components/dialogs/sessions"
31 "github.com/charmbracelet/crush/internal/tui/page"
32 "github.com/charmbracelet/crush/internal/tui/page/chat"
33 "github.com/charmbracelet/crush/internal/tui/styles"
34 "github.com/charmbracelet/crush/internal/tui/util"
35 "github.com/charmbracelet/lipgloss/v2"
36)
37
38var lastMouseEvent time.Time
39
40func MouseEventFilter(m tea.Model, msg tea.Msg) tea.Msg {
41 switch msg.(type) {
42 case tea.MouseWheelMsg, tea.MouseMotionMsg:
43 now := time.Now()
44 // trackpad is sending too many requests
45 if now.Sub(lastMouseEvent) < 5*time.Millisecond {
46 return nil
47 }
48 lastMouseEvent = now
49 }
50 return msg
51}
52
53// appModel represents the main application model that manages pages, dialogs, and UI state.
54type appModel struct {
55 wWidth, wHeight int // Window dimensions
56 width, height int
57 keyMap KeyMap
58
59 currentPage page.PageID
60 previousPage page.PageID
61 pages map[page.PageID]util.Model
62 loadedPages map[page.PageID]bool
63
64 // Status
65 status status.StatusCmp
66 showingFullHelp bool
67
68 app *app.App
69
70 dialog dialogs.DialogCmp
71 completions completions.Completions
72 isConfigured bool
73
74 // Chat Page Specific
75 selectedSessionID string // The ID of the currently selected session
76}
77
78// Init initializes the application model and returns initial commands.
79func (a appModel) Init() tea.Cmd {
80 var cmds []tea.Cmd
81 cmd := a.pages[a.currentPage].Init()
82 cmds = append(cmds, cmd)
83 a.loadedPages[a.currentPage] = true
84
85 cmd = a.status.Init()
86 cmds = append(cmds, cmd)
87
88 cmds = append(cmds, tea.EnableMouseAllMotion)
89
90 return tea.Batch(cmds...)
91}
92
93// Update handles incoming messages and updates the application state.
94func (a *appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
95 var cmds []tea.Cmd
96 var cmd tea.Cmd
97 a.isConfigured = config.HasInitialDataConfig()
98
99 switch msg := msg.(type) {
100 case tea.KeyboardEnhancementsMsg:
101 for id, page := range a.pages {
102 m, pageCmd := page.Update(msg)
103 a.pages[id] = m.(util.Model)
104 if pageCmd != nil {
105 cmds = append(cmds, pageCmd)
106 }
107 }
108 return a, tea.Batch(cmds...)
109 case tea.WindowSizeMsg:
110 a.wWidth, a.wHeight = msg.Width, msg.Height
111 a.completions.Update(msg)
112 return a, a.handleWindowResize(msg.Width, msg.Height)
113
114 // Completions messages
115 case completions.OpenCompletionsMsg, completions.FilterCompletionsMsg,
116 completions.CloseCompletionsMsg, completions.RepositionCompletionsMsg:
117 u, completionCmd := a.completions.Update(msg)
118 a.completions = u.(completions.Completions)
119 return a, completionCmd
120
121 // Dialog messages
122 case dialogs.OpenDialogMsg, dialogs.CloseDialogMsg:
123 u, completionCmd := a.completions.Update(completions.CloseCompletionsMsg{})
124 a.completions = u.(completions.Completions)
125 u, dialogCmd := a.dialog.Update(msg)
126 a.dialog = u.(dialogs.DialogCmp)
127 return a, tea.Batch(completionCmd, dialogCmd)
128 case commands.ShowArgumentsDialogMsg:
129 return a, util.CmdHandler(
130 dialogs.OpenDialogMsg{
131 Model: commands.NewCommandArgumentsDialog(
132 msg.CommandID,
133 msg.Content,
134 msg.ArgNames,
135 ),
136 },
137 )
138 // Page change messages
139 case page.PageChangeMsg:
140 return a, a.moveToPage(msg.ID)
141
142 // Status Messages
143 case util.InfoMsg, util.ClearStatusMsg:
144 s, statusCmd := a.status.Update(msg)
145 a.status = s.(status.StatusCmp)
146 cmds = append(cmds, statusCmd)
147 return a, tea.Batch(cmds...)
148
149 // Session
150 case cmpChat.SessionSelectedMsg:
151 a.selectedSessionID = msg.ID
152 case cmpChat.SessionClearedMsg:
153 a.selectedSessionID = ""
154 // Commands
155 case commands.SwitchSessionsMsg:
156 return a, func() tea.Msg {
157 allSessions, _ := a.app.Sessions.List(context.Background())
158 return dialogs.OpenDialogMsg{
159 Model: sessions.NewSessionDialogCmp(allSessions, a.selectedSessionID),
160 }
161 }
162
163 case commands.SwitchModelMsg:
164 return a, util.CmdHandler(
165 dialogs.OpenDialogMsg{
166 Model: models.NewModelDialogCmp(),
167 },
168 )
169 // Compact
170 case commands.CompactMsg:
171 return a, util.CmdHandler(dialogs.OpenDialogMsg{
172 Model: compact.NewCompactDialogCmp(a.app.CoderAgent, msg.SessionID, true),
173 })
174 case commands.QuitMsg:
175 return a, util.CmdHandler(dialogs.OpenDialogMsg{
176 Model: quit.NewQuitDialog(),
177 })
178 case commands.ToggleHelpMsg:
179 a.status.ToggleFullHelp()
180 a.showingFullHelp = !a.showingFullHelp
181 return a, a.handleWindowResize(a.wWidth, a.wHeight)
182 // Model Switch
183 case models.ModelSelectedMsg:
184 config.Get().UpdatePreferredModel(msg.ModelType, msg.Model)
185
186 // Update the agent with the new model/provider configuration
187 if err := a.app.UpdateAgentModel(); err != nil {
188 return a, util.ReportError(fmt.Errorf("model changed to %s but failed to update agent: %v", msg.Model.Model, err))
189 }
190
191 modelTypeName := "large"
192 if msg.ModelType == config.SelectedModelTypeSmall {
193 modelTypeName = "small"
194 }
195 return a, util.ReportInfo(fmt.Sprintf("%s model changed to %s", modelTypeName, msg.Model.Model))
196
197 // File Picker
198 case commands.OpenFilePickerMsg:
199 if a.dialog.ActiveDialogID() == filepicker.FilePickerID {
200 // If the commands dialog is already open, close it
201 return a, util.CmdHandler(dialogs.CloseDialogMsg{})
202 }
203 return a, util.CmdHandler(dialogs.OpenDialogMsg{
204 Model: filepicker.NewFilePickerCmp(a.app.Config().WorkingDir()),
205 })
206 // Permissions
207 case pubsub.Event[permission.PermissionNotification]:
208 // forward to page
209 updated, cmd := a.pages[a.currentPage].Update(msg)
210 a.pages[a.currentPage] = updated.(util.Model)
211 return a, cmd
212 case pubsub.Event[permission.PermissionRequest]:
213 return a, util.CmdHandler(dialogs.OpenDialogMsg{
214 Model: permissions.NewPermissionDialogCmp(msg.Payload),
215 })
216 case permissions.PermissionResponseMsg:
217 switch msg.Action {
218 case permissions.PermissionAllow:
219 a.app.Permissions.Grant(msg.Permission)
220 case permissions.PermissionAllowForSession:
221 a.app.Permissions.GrantPersistent(msg.Permission)
222 case permissions.PermissionDeny:
223 a.app.Permissions.Deny(msg.Permission)
224 }
225 return a, nil
226 // Agent Events
227 case pubsub.Event[agent.AgentEvent]:
228 payload := msg.Payload
229
230 // Forward agent events to dialogs
231 if a.dialog.HasDialogs() && a.dialog.ActiveDialogID() == compact.CompactDialogID {
232 u, dialogCmd := a.dialog.Update(payload)
233 a.dialog = u.(dialogs.DialogCmp)
234 cmds = append(cmds, dialogCmd)
235 }
236
237 // Handle auto-compact logic
238 if payload.Done && payload.Type == agent.AgentEventTypeResponse && a.selectedSessionID != "" {
239 // Get current session to check token usage
240 session, err := a.app.Sessions.Get(context.Background(), a.selectedSessionID)
241 if err == nil {
242 model := a.app.CoderAgent.Model()
243 contextWindow := model.ContextWindow
244 tokens := session.CompletionTokens + session.PromptTokens
245 if (tokens >= int64(float64(contextWindow)*0.95)) && !config.Get().Options.DisableAutoSummarize { // Show compact confirmation dialog
246 cmds = append(cmds, util.CmdHandler(dialogs.OpenDialogMsg{
247 Model: compact.NewCompactDialogCmp(a.app.CoderAgent, a.selectedSessionID, false),
248 }))
249 }
250 }
251 }
252
253 return a, tea.Batch(cmds...)
254 case splash.OnboardingCompleteMsg:
255 a.isConfigured = config.HasInitialDataConfig()
256 updated, pageCmd := a.pages[a.currentPage].Update(msg)
257 a.pages[a.currentPage] = updated.(util.Model)
258 cmds = append(cmds, pageCmd)
259 return a, tea.Batch(cmds...)
260 // Key Press Messages
261 case tea.KeyPressMsg:
262
263 slog.Info("TUI Update", "msg", msg, "key", msg.String())
264 return a, a.handleKeyPressMsg(msg)
265
266 case tea.MouseWheelMsg:
267 if !a.dialog.HasDialogs() {
268 updated, pageCmd := a.pages[a.currentPage].Update(msg)
269 a.pages[a.currentPage] = updated.(util.Model)
270 cmds = append(cmds, pageCmd)
271 }
272 return a, tea.Batch(cmds...)
273 case tea.PasteMsg:
274 if a.dialog.HasDialogs() {
275 u, dialogCmd := a.dialog.Update(msg)
276 a.dialog = u.(dialogs.DialogCmp)
277 cmds = append(cmds, dialogCmd)
278 } else {
279 updated, pageCmd := a.pages[a.currentPage].Update(msg)
280 a.pages[a.currentPage] = updated.(util.Model)
281 cmds = append(cmds, pageCmd)
282 }
283 return a, tea.Batch(cmds...)
284 }
285 s, _ := a.status.Update(msg)
286 a.status = s.(status.StatusCmp)
287 updated, cmd := a.pages[a.currentPage].Update(msg)
288 a.pages[a.currentPage] = updated.(util.Model)
289 if a.dialog.HasDialogs() {
290 u, dialogCmd := a.dialog.Update(msg)
291 a.dialog = u.(dialogs.DialogCmp)
292 cmds = append(cmds, dialogCmd)
293 }
294 cmds = append(cmds, cmd)
295 return a, tea.Batch(cmds...)
296}
297
298// handleWindowResize processes window resize events and updates all components.
299func (a *appModel) handleWindowResize(width, height int) tea.Cmd {
300 var cmds []tea.Cmd
301 if a.showingFullHelp {
302 height -= 5
303 } else {
304 height -= 2
305 }
306 a.width, a.height = width, height
307 // Update status bar
308 s, cmd := a.status.Update(tea.WindowSizeMsg{Width: width, Height: height})
309 a.status = s.(status.StatusCmp)
310 cmds = append(cmds, cmd)
311
312 // Update the current page
313 for p, page := range a.pages {
314 updated, pageCmd := page.Update(tea.WindowSizeMsg{Width: width, Height: height})
315 a.pages[p] = updated.(util.Model)
316 cmds = append(cmds, pageCmd)
317 }
318
319 // Update the dialogs
320 dialog, cmd := a.dialog.Update(tea.WindowSizeMsg{Width: width, Height: height})
321 a.dialog = dialog.(dialogs.DialogCmp)
322 cmds = append(cmds, cmd)
323
324 return tea.Batch(cmds...)
325}
326
327// handleKeyPressMsg processes keyboard input and routes to appropriate handlers.
328func (a *appModel) handleKeyPressMsg(msg tea.KeyPressMsg) tea.Cmd {
329 if a.completions.Open() {
330 // completions
331 keyMap := a.completions.KeyMap()
332 switch {
333 case key.Matches(msg, keyMap.Up), key.Matches(msg, keyMap.Down),
334 key.Matches(msg, keyMap.Select), key.Matches(msg, keyMap.Cancel),
335 key.Matches(msg, keyMap.UpInsert), key.Matches(msg, keyMap.DownInsert):
336 u, cmd := a.completions.Update(msg)
337 a.completions = u.(completions.Completions)
338 return cmd
339 }
340 }
341 switch {
342 // help
343 case key.Matches(msg, a.keyMap.Help):
344 a.status.ToggleFullHelp()
345 a.showingFullHelp = !a.showingFullHelp
346 return a.handleWindowResize(a.wWidth, a.wHeight)
347 // dialogs
348 case key.Matches(msg, a.keyMap.Quit):
349 if a.dialog.ActiveDialogID() == quit.QuitDialogID {
350 return tea.Quit
351 }
352 return util.CmdHandler(dialogs.OpenDialogMsg{
353 Model: quit.NewQuitDialog(),
354 })
355
356 case key.Matches(msg, a.keyMap.Commands):
357 // if the app is not configured show no commands
358 if !a.isConfigured {
359 return nil
360 }
361 if a.dialog.ActiveDialogID() == commands.CommandsDialogID {
362 return util.CmdHandler(dialogs.CloseDialogMsg{})
363 }
364 if a.dialog.HasDialogs() {
365 return nil
366 }
367 return util.CmdHandler(dialogs.OpenDialogMsg{
368 Model: commands.NewCommandDialog(a.selectedSessionID),
369 })
370 case key.Matches(msg, a.keyMap.Sessions):
371 // if the app is not configured show no sessions
372 if !a.isConfigured {
373 return nil
374 }
375 if a.dialog.ActiveDialogID() == sessions.SessionsDialogID {
376 return util.CmdHandler(dialogs.CloseDialogMsg{})
377 }
378 if a.dialog.HasDialogs() && a.dialog.ActiveDialogID() != commands.CommandsDialogID {
379 return nil
380 }
381 var cmds []tea.Cmd
382 if a.dialog.ActiveDialogID() == commands.CommandsDialogID {
383 // If the commands dialog is open, close it first
384 cmds = append(cmds, util.CmdHandler(dialogs.CloseDialogMsg{}))
385 }
386 cmds = append(cmds,
387 func() tea.Msg {
388 allSessions, _ := a.app.Sessions.List(context.Background())
389 return dialogs.OpenDialogMsg{
390 Model: sessions.NewSessionDialogCmp(allSessions, a.selectedSessionID),
391 }
392 },
393 )
394 return tea.Sequence(cmds...)
395 case key.Matches(msg, a.keyMap.Suspend):
396 if a.app.CoderAgent.IsBusy() {
397 return util.ReportWarn("Agent is busy, please wait...")
398 }
399 return tea.Suspend
400 default:
401 if a.dialog.HasDialogs() {
402 u, dialogCmd := a.dialog.Update(msg)
403 a.dialog = u.(dialogs.DialogCmp)
404 return dialogCmd
405 } else {
406 updated, cmd := a.pages[a.currentPage].Update(msg)
407 a.pages[a.currentPage] = updated.(util.Model)
408 return cmd
409 }
410 }
411}
412
413// moveToPage handles navigation between different pages in the application.
414func (a *appModel) moveToPage(pageID page.PageID) tea.Cmd {
415 if a.app.CoderAgent.IsBusy() {
416 // TODO: maybe remove this : For now we don't move to any page if the agent is busy
417 return util.ReportWarn("Agent is busy, please wait...")
418 }
419
420 var cmds []tea.Cmd
421 if _, ok := a.loadedPages[pageID]; !ok {
422 cmd := a.pages[pageID].Init()
423 cmds = append(cmds, cmd)
424 a.loadedPages[pageID] = true
425 }
426 a.previousPage = a.currentPage
427 a.currentPage = pageID
428 if sizable, ok := a.pages[a.currentPage].(layout.Sizeable); ok {
429 cmd := sizable.SetSize(a.width, a.height)
430 cmds = append(cmds, cmd)
431 }
432
433 return tea.Batch(cmds...)
434}
435
436// View renders the complete application interface including pages, dialogs, and overlays.
437func (a *appModel) View() tea.View {
438 var view tea.View
439 t := styles.CurrentTheme()
440 view.BackgroundColor = t.BgBase
441 if a.wWidth < 25 || a.wHeight < 15 {
442 view.Layer = lipgloss.NewCanvas(
443 lipgloss.NewLayer(
444 t.S().Base.Width(a.wWidth).Height(a.wHeight).
445 Align(lipgloss.Center, lipgloss.Center).
446 Render(
447 t.S().Base.
448 Padding(1, 4).
449 Foreground(t.White).
450 BorderStyle(lipgloss.RoundedBorder()).
451 BorderForeground(t.Primary).
452 Render("Window too small!"),
453 ),
454 ),
455 )
456 return view
457 }
458
459 page := a.pages[a.currentPage]
460 if withHelp, ok := page.(core.KeyMapHelp); ok {
461 a.status.SetKeyMap(withHelp.Help())
462 }
463 pageView := page.View()
464 components := []string{
465 pageView,
466 }
467 components = append(components, a.status.View())
468
469 appView := lipgloss.JoinVertical(lipgloss.Top, components...)
470 layers := []*lipgloss.Layer{
471 lipgloss.NewLayer(appView),
472 }
473 if a.dialog.HasDialogs() {
474 layers = append(
475 layers,
476 a.dialog.GetLayers()...,
477 )
478 }
479
480 var cursor *tea.Cursor
481 if v, ok := page.(util.Cursor); ok {
482 cursor = v.Cursor()
483 // Hide the cursor if it's positioned outside the textarea
484 statusHeight := a.height - strings.Count(pageView, "\n") + 1
485 if cursor != nil && cursor.Y+statusHeight+chat.EditorHeight-2 <= a.height { // 2 for the top and bottom app padding
486 cursor = nil
487 }
488 }
489 activeView := a.dialog.ActiveModel()
490 if activeView != nil {
491 cursor = nil // Reset cursor if a dialog is active unless it implements util.Cursor
492 if v, ok := activeView.(util.Cursor); ok {
493 cursor = v.Cursor()
494 }
495 }
496
497 if a.completions.Open() && cursor != nil {
498 cmp := a.completions.View()
499 x, y := a.completions.Position()
500 layers = append(
501 layers,
502 lipgloss.NewLayer(cmp).X(x).Y(y),
503 )
504 }
505
506 canvas := lipgloss.NewCanvas(
507 layers...,
508 )
509
510 view.Layer = canvas
511 view.Cursor = cursor
512 return view
513}
514
515// New creates and initializes a new TUI application model.
516func New(app *app.App) tea.Model {
517 chatPage := chat.New(app)
518 keyMap := DefaultKeyMap()
519 keyMap.pageBindings = chatPage.Bindings()
520
521 model := &appModel{
522 currentPage: chat.ChatPageID,
523 app: app,
524 status: status.NewStatusCmp(),
525 loadedPages: make(map[page.PageID]bool),
526 keyMap: keyMap,
527
528 pages: map[page.PageID]util.Model{
529 chat.ChatPageID: chatPage,
530 },
531
532 dialog: dialogs.NewDialogCmp(),
533 completions: completions.New(),
534 }
535
536 return model
537}