1package tui
2
3import (
4 "context"
5 "fmt"
6 "math/rand"
7 "slices"
8 "strings"
9 "time"
10
11 "git.secluded.site/crush/internal/app"
12 "git.secluded.site/crush/internal/config"
13 "git.secluded.site/crush/internal/event"
14 "git.secluded.site/crush/internal/permission"
15 "git.secluded.site/crush/internal/pubsub"
16 cmpChat "git.secluded.site/crush/internal/tui/components/chat"
17 "git.secluded.site/crush/internal/tui/components/chat/splash"
18 "git.secluded.site/crush/internal/tui/components/completions"
19 "git.secluded.site/crush/internal/tui/components/core"
20 "git.secluded.site/crush/internal/tui/components/core/layout"
21 "git.secluded.site/crush/internal/tui/components/core/status"
22 "git.secluded.site/crush/internal/tui/components/dialogs"
23 "git.secluded.site/crush/internal/tui/components/dialogs/commands"
24 "git.secluded.site/crush/internal/tui/components/dialogs/filepicker"
25 "git.secluded.site/crush/internal/tui/components/dialogs/models"
26 "git.secluded.site/crush/internal/tui/components/dialogs/permissions"
27 "git.secluded.site/crush/internal/tui/components/dialogs/quit"
28 "git.secluded.site/crush/internal/tui/components/dialogs/sessions"
29 "git.secluded.site/crush/internal/tui/page"
30 "git.secluded.site/crush/internal/tui/page/chat"
31 "git.secluded.site/crush/internal/tui/styles"
32 "git.secluded.site/crush/internal/tui/util"
33 "github.com/charmbracelet/bubbles/v2/key"
34 tea "github.com/charmbracelet/bubbletea/v2"
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) < 15*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 // sendProgressBar instructs the TUI to send progress bar updates to the
78 // terminal.
79 sendProgressBar bool
80
81 // QueryVersion instructs the TUI to query for the terminal version when it
82 // starts.
83 QueryVersion bool
84}
85
86// Init initializes the application model and returns initial commands.
87func (a appModel) Init() tea.Cmd {
88 item, ok := a.pages[a.currentPage]
89 if !ok {
90 return nil
91 }
92
93 var cmds []tea.Cmd
94 cmd := item.Init()
95 cmds = append(cmds, cmd)
96 a.loadedPages[a.currentPage] = true
97
98 cmd = a.status.Init()
99 cmds = append(cmds, cmd)
100 if a.QueryVersion {
101 cmds = append(cmds, tea.RequestTerminalVersion)
102 }
103
104 return tea.Batch(cmds...)
105}
106
107// Update handles incoming messages and updates the application state.
108func (a *appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
109 var cmds []tea.Cmd
110 var cmd tea.Cmd
111 a.isConfigured = config.HasInitialDataConfig()
112
113 switch msg := msg.(type) {
114 case tea.EnvMsg:
115 // Is this Windows Terminal?
116 if !a.sendProgressBar {
117 a.sendProgressBar = slices.Contains(msg, "WT_SESSION")
118 }
119 case tea.TerminalVersionMsg:
120 termVersion := strings.ToLower(string(msg))
121 // Only enable progress bar for the following terminals.
122 if !a.sendProgressBar {
123 a.sendProgressBar = strings.Contains(termVersion, "ghostty")
124 }
125 return a, nil
126 case tea.KeyboardEnhancementsMsg:
127 for id, page := range a.pages {
128 m, pageCmd := page.Update(msg)
129 a.pages[id] = m
130
131 if pageCmd != nil {
132 cmds = append(cmds, pageCmd)
133 }
134 }
135 return a, tea.Batch(cmds...)
136 case tea.WindowSizeMsg:
137 a.wWidth, a.wHeight = msg.Width, msg.Height
138 a.completions.Update(msg)
139 return a, a.handleWindowResize(msg.Width, msg.Height)
140
141 // Completions messages
142 case completions.OpenCompletionsMsg, completions.FilterCompletionsMsg,
143 completions.CloseCompletionsMsg, completions.RepositionCompletionsMsg:
144 u, completionCmd := a.completions.Update(msg)
145 if model, ok := u.(completions.Completions); ok {
146 a.completions = model
147 }
148
149 return a, completionCmd
150
151 // Dialog messages
152 case dialogs.OpenDialogMsg, dialogs.CloseDialogMsg:
153 u, completionCmd := a.completions.Update(completions.CloseCompletionsMsg{})
154 a.completions = u.(completions.Completions)
155 u, dialogCmd := a.dialog.Update(msg)
156 a.dialog = u.(dialogs.DialogCmp)
157 return a, tea.Batch(completionCmd, dialogCmd)
158 case commands.ShowArgumentsDialogMsg:
159 return a, util.CmdHandler(
160 dialogs.OpenDialogMsg{
161 Model: commands.NewCommandArgumentsDialog(
162 msg.CommandID,
163 msg.Content,
164 msg.ArgNames,
165 ),
166 },
167 )
168 // Page change messages
169 case page.PageChangeMsg:
170 return a, a.moveToPage(msg.ID)
171
172 // Status Messages
173 case util.InfoMsg, util.ClearStatusMsg:
174 s, statusCmd := a.status.Update(msg)
175 a.status = s.(status.StatusCmp)
176 cmds = append(cmds, statusCmd)
177 return a, tea.Batch(cmds...)
178
179 // Session
180 case cmpChat.SessionSelectedMsg:
181 a.selectedSessionID = msg.ID
182 case cmpChat.SessionClearedMsg:
183 a.selectedSessionID = ""
184 // Commands
185 case commands.SwitchSessionsMsg:
186 return a, func() tea.Msg {
187 allSessions, _ := a.app.Sessions.List(context.Background())
188 return dialogs.OpenDialogMsg{
189 Model: sessions.NewSessionDialogCmp(allSessions, a.selectedSessionID),
190 }
191 }
192
193 case commands.SwitchModelMsg:
194 // Opening model dialog is interaction; cancel pending turn-end notif.
195 if a.app.AgentCoordinator != nil && a.app.AgentCoordinator.HasPendingCompletionNotification(a.selectedSessionID) {
196 a.app.AgentCoordinator.CancelCompletionNotification(a.selectedSessionID)
197 }
198 return a, util.CmdHandler(
199 dialogs.OpenDialogMsg{
200 Model: models.NewModelDialogCmp(),
201 },
202 )
203 // Compact
204 case commands.CompactMsg:
205 return a, func() tea.Msg {
206 err := a.app.AgentCoordinator.Summarize(context.Background(), msg.SessionID)
207 if err != nil {
208 return util.ReportError(err)()
209 }
210 return nil
211 }
212 case commands.QuitMsg:
213 return a, util.CmdHandler(dialogs.OpenDialogMsg{
214 Model: quit.NewQuitDialog(),
215 })
216 case commands.ToggleYoloModeMsg:
217 a.app.Permissions.SetSkipRequests(!a.app.Permissions.SkipRequests())
218 case commands.ToggleHelpMsg:
219 a.status.ToggleFullHelp()
220 a.showingFullHelp = !a.showingFullHelp
221 return a, a.handleWindowResize(a.wWidth, a.wHeight)
222 // Model Switch
223 case models.ModelSelectedMsg:
224 if a.app.AgentCoordinator.IsBusy() {
225 return a, util.ReportWarn("Agent is busy, please wait...")
226 }
227
228 config.Get().UpdatePreferredModel(msg.ModelType, msg.Model)
229
230 go a.app.UpdateAgentModel(context.TODO())
231
232 modelTypeName := "large"
233 if msg.ModelType == config.SelectedModelTypeSmall {
234 modelTypeName = "small"
235 }
236 return a, util.ReportInfo(fmt.Sprintf("%s model changed to %s", modelTypeName, msg.Model.Model))
237
238 // File Picker
239 case commands.OpenFilePickerMsg:
240 event.FilePickerOpened()
241
242 if a.dialog.ActiveDialogID() == filepicker.FilePickerID {
243 // If the commands dialog is already open, close it
244 return a, util.CmdHandler(dialogs.CloseDialogMsg{})
245 }
246 return a, util.CmdHandler(dialogs.OpenDialogMsg{
247 Model: filepicker.NewFilePickerCmp(a.app.Config().WorkingDir()),
248 })
249 // Permissions
250 case pubsub.Event[permission.PermissionNotification]:
251 item, ok := a.pages[a.currentPage]
252 if !ok {
253 return a, nil
254 }
255
256 // Forward to view.
257 updated, itemCmd := item.Update(msg)
258 a.pages[a.currentPage] = updated
259
260 return a, itemCmd
261 case pubsub.Event[permission.PermissionRequest]:
262 return a, util.CmdHandler(dialogs.OpenDialogMsg{
263 Model: permissions.NewPermissionDialogCmp(msg.Payload, &permissions.Options{
264 DiffMode: config.Get().Options.TUI.DiffMode,
265 }),
266 })
267 case permissions.PermissionResponseMsg:
268 switch msg.Action {
269 case permissions.PermissionAllow:
270 a.app.Permissions.Grant(msg.Permission)
271 case permissions.PermissionAllowForSession:
272 a.app.Permissions.GrantPersistent(msg.Permission)
273 case permissions.PermissionDeny:
274 a.app.Permissions.Deny(msg.Permission)
275 }
276 return a, nil
277 case permissions.PermissionInteractionMsg:
278 // Notify that the user interacted with the permission dialog.
279 a.app.Permissions.NotifyInteraction(msg.ToolCallID)
280 return a, nil
281 case splash.OnboardingCompleteMsg:
282 item, ok := a.pages[a.currentPage]
283 if !ok {
284 return a, nil
285 }
286
287 a.isConfigured = config.HasInitialDataConfig()
288 updated, pageCmd := item.Update(msg)
289 a.pages[a.currentPage] = updated
290
291 cmds = append(cmds, pageCmd)
292 return a, tea.Batch(cmds...)
293
294 case tea.KeyPressMsg:
295 return a, a.handleKeyPressMsg(msg)
296
297 case tea.MouseWheelMsg:
298 if a.dialog.HasDialogs() {
299 u, dialogCmd := a.dialog.Update(msg)
300 a.dialog = u.(dialogs.DialogCmp)
301 cmds = append(cmds, dialogCmd)
302 } else {
303 item, ok := a.pages[a.currentPage]
304 if !ok {
305 return a, nil
306 }
307
308 updated, pageCmd := item.Update(msg)
309 a.pages[a.currentPage] = updated
310
311 cmds = append(cmds, pageCmd)
312 }
313 return a, tea.Batch(cmds...)
314 case tea.PasteMsg:
315 if a.dialog.HasDialogs() {
316 u, dialogCmd := a.dialog.Update(msg)
317 if model, ok := u.(dialogs.DialogCmp); ok {
318 a.dialog = model
319 }
320
321 cmds = append(cmds, dialogCmd)
322 } else {
323 item, ok := a.pages[a.currentPage]
324 if !ok {
325 return a, nil
326 }
327
328 updated, pageCmd := item.Update(msg)
329 a.pages[a.currentPage] = updated
330
331 cmds = append(cmds, pageCmd)
332 }
333 return a, tea.Batch(cmds...)
334 }
335 s, _ := a.status.Update(msg)
336 a.status = s.(status.StatusCmp)
337
338 item, ok := a.pages[a.currentPage]
339 if !ok {
340 return a, nil
341 }
342
343 updated, cmd := item.Update(msg)
344 a.pages[a.currentPage] = updated
345
346 if a.dialog.HasDialogs() {
347 u, dialogCmd := a.dialog.Update(msg)
348 if model, ok := u.(dialogs.DialogCmp); ok {
349 a.dialog = model
350 }
351
352 cmds = append(cmds, dialogCmd)
353 }
354 cmds = append(cmds, cmd)
355 return a, tea.Batch(cmds...)
356}
357
358// handleWindowResize processes window resize events and updates all components.
359func (a *appModel) handleWindowResize(width, height int) tea.Cmd {
360 var cmds []tea.Cmd
361
362 // TODO: clean up these magic numbers.
363 if a.showingFullHelp {
364 height -= 5
365 } else {
366 height -= 2
367 }
368
369 a.width, a.height = width, height
370 // Update status bar
371 s, cmd := a.status.Update(tea.WindowSizeMsg{Width: width, Height: height})
372 if model, ok := s.(status.StatusCmp); ok {
373 a.status = model
374 }
375 cmds = append(cmds, cmd)
376
377 // Update the current view.
378 for p, page := range a.pages {
379 updated, pageCmd := page.Update(tea.WindowSizeMsg{Width: width, Height: height})
380 a.pages[p] = updated
381
382 cmds = append(cmds, pageCmd)
383 }
384
385 // Update the dialogs
386 dialog, cmd := a.dialog.Update(tea.WindowSizeMsg{Width: width, Height: height})
387 if model, ok := dialog.(dialogs.DialogCmp); ok {
388 a.dialog = model
389 }
390
391 cmds = append(cmds, cmd)
392
393 return tea.Batch(cmds...)
394}
395
396// handleKeyPressMsg processes keyboard input and routes to appropriate handlers.
397func (a *appModel) handleKeyPressMsg(msg tea.KeyPressMsg) tea.Cmd {
398 // Check this first as the user should be able to quit no matter what.
399 if key.Matches(msg, a.keyMap.Quit) {
400 if a.dialog.ActiveDialogID() == quit.QuitDialogID {
401 return tea.Quit
402 }
403 return util.CmdHandler(dialogs.OpenDialogMsg{
404 Model: quit.NewQuitDialog(),
405 })
406 }
407
408 if a.completions.Open() {
409 // completions
410 keyMap := a.completions.KeyMap()
411 switch {
412 case key.Matches(msg, keyMap.Up), key.Matches(msg, keyMap.Down),
413 key.Matches(msg, keyMap.Select), key.Matches(msg, keyMap.Cancel),
414 key.Matches(msg, keyMap.UpInsert), key.Matches(msg, keyMap.DownInsert):
415 u, cmd := a.completions.Update(msg)
416 a.completions = u.(completions.Completions)
417 return cmd
418 }
419 }
420 if a.dialog.HasDialogs() {
421 u, dialogCmd := a.dialog.Update(msg)
422 a.dialog = u.(dialogs.DialogCmp)
423 return dialogCmd
424 }
425 switch {
426 // help
427 case key.Matches(msg, a.keyMap.Help):
428 a.status.ToggleFullHelp()
429 a.showingFullHelp = !a.showingFullHelp
430 return a.handleWindowResize(a.wWidth, a.wHeight)
431 // dialogs
432 case key.Matches(msg, a.keyMap.Commands):
433 // Opening the command palette counts as interaction; cancel pending
434 // turn-end notification for the selected session if any.
435 if a.app.AgentCoordinator != nil && a.app.AgentCoordinator.HasPendingCompletionNotification(a.selectedSessionID) {
436 a.app.AgentCoordinator.CancelCompletionNotification(a.selectedSessionID)
437 }
438 // if the app is not configured show no commands
439 if !a.isConfigured {
440 return nil
441 }
442 if a.dialog.ActiveDialogID() == commands.CommandsDialogID {
443 return util.CmdHandler(dialogs.CloseDialogMsg{})
444 }
445 if a.dialog.HasDialogs() {
446 return nil
447 }
448 return util.CmdHandler(dialogs.OpenDialogMsg{
449 Model: commands.NewCommandDialog(a.selectedSessionID),
450 })
451 case key.Matches(msg, a.keyMap.Sessions):
452 // if the app is not configured show no sessions
453 if !a.isConfigured {
454 return nil
455 }
456 // Opening sessions dialog is interaction; cancel pending turn-end notif.
457 if a.app.AgentCoordinator != nil && a.app.AgentCoordinator.HasPendingCompletionNotification(a.selectedSessionID) {
458 a.app.AgentCoordinator.CancelCompletionNotification(a.selectedSessionID)
459 }
460 if a.dialog.ActiveDialogID() == sessions.SessionsDialogID {
461 return util.CmdHandler(dialogs.CloseDialogMsg{})
462 }
463 if a.dialog.HasDialogs() && a.dialog.ActiveDialogID() != commands.CommandsDialogID {
464 return nil
465 }
466 var cmds []tea.Cmd
467 if a.dialog.ActiveDialogID() == commands.CommandsDialogID {
468 // If the commands dialog is open, close it first
469 cmds = append(cmds, util.CmdHandler(dialogs.CloseDialogMsg{}))
470 }
471 cmds = append(cmds,
472 func() tea.Msg {
473 allSessions, _ := a.app.Sessions.List(context.Background())
474 return dialogs.OpenDialogMsg{
475 Model: sessions.NewSessionDialogCmp(allSessions, a.selectedSessionID),
476 }
477 },
478 )
479 return tea.Sequence(cmds...)
480 case key.Matches(msg, a.keyMap.Suspend):
481 if a.app.AgentCoordinator != nil && a.app.AgentCoordinator.IsBusy() {
482 return util.ReportWarn("Agent is busy, please wait...")
483 }
484 return tea.Suspend
485 default:
486 item, ok := a.pages[a.currentPage]
487 if !ok {
488 return nil
489 }
490
491 updated, cmd := item.Update(msg)
492 a.pages[a.currentPage] = updated
493 return cmd
494 }
495}
496
497// moveToPage handles navigation between different pages in the application.
498func (a *appModel) moveToPage(pageID page.PageID) tea.Cmd {
499 if a.app.AgentCoordinator.IsBusy() {
500 // TODO: maybe remove this : For now we don't move to any page if the agent is busy
501 return util.ReportWarn("Agent is busy, please wait...")
502 }
503
504 var cmds []tea.Cmd
505 if _, ok := a.loadedPages[pageID]; !ok {
506 cmd := a.pages[pageID].Init()
507 cmds = append(cmds, cmd)
508 a.loadedPages[pageID] = true
509 }
510 a.previousPage = a.currentPage
511 a.currentPage = pageID
512 if sizable, ok := a.pages[a.currentPage].(layout.Sizeable); ok {
513 cmd := sizable.SetSize(a.width, a.height)
514 cmds = append(cmds, cmd)
515 }
516
517 return tea.Batch(cmds...)
518}
519
520// View renders the complete application interface including pages, dialogs, and overlays.
521func (a *appModel) View() tea.View {
522 var view tea.View
523 view.AltScreen = true
524 t := styles.CurrentTheme()
525 view.BackgroundColor = t.BgBase
526 if a.wWidth < 25 || a.wHeight < 15 {
527 view.Layer = lipgloss.NewCanvas(
528 lipgloss.NewLayer(
529 t.S().Base.Width(a.wWidth).Height(a.wHeight).
530 Align(lipgloss.Center, lipgloss.Center).
531 Render(
532 t.S().Base.
533 Padding(1, 4).
534 Foreground(t.White).
535 BorderStyle(lipgloss.RoundedBorder()).
536 BorderForeground(t.Primary).
537 Render("Window too small!"),
538 ),
539 ),
540 )
541 return view
542 }
543
544 page := a.pages[a.currentPage]
545 if withHelp, ok := page.(core.KeyMapHelp); ok {
546 a.status.SetKeyMap(withHelp.Help())
547 }
548 pageView := page.View()
549 components := []string{
550 pageView,
551 }
552 components = append(components, a.status.View())
553
554 appView := lipgloss.JoinVertical(lipgloss.Top, components...)
555 layers := []*lipgloss.Layer{
556 lipgloss.NewLayer(appView),
557 }
558 if a.dialog.HasDialogs() {
559 layers = append(
560 layers,
561 a.dialog.GetLayers()...,
562 )
563 }
564
565 var cursor *tea.Cursor
566 if v, ok := page.(util.Cursor); ok {
567 cursor = v.Cursor()
568 // Hide the cursor if it's positioned outside the textarea
569 statusHeight := a.height - strings.Count(pageView, "\n") + 1
570 if cursor != nil && cursor.Y+statusHeight+chat.EditorHeight-2 <= a.height { // 2 for the top and bottom app padding
571 cursor = nil
572 }
573 }
574 activeView := a.dialog.ActiveModel()
575 if activeView != nil {
576 cursor = nil // Reset cursor if a dialog is active unless it implements util.Cursor
577 if v, ok := activeView.(util.Cursor); ok {
578 cursor = v.Cursor()
579 }
580 }
581
582 if a.completions.Open() && cursor != nil {
583 cmp := a.completions.View()
584 x, y := a.completions.Position()
585 layers = append(
586 layers,
587 lipgloss.NewLayer(cmp).X(x).Y(y),
588 )
589 }
590
591 canvas := lipgloss.NewCanvas(
592 layers...,
593 )
594
595 view.Layer = canvas
596 view.Cursor = cursor
597 view.MouseMode = tea.MouseModeCellMotion
598
599 if a.sendProgressBar && a.app != nil && a.app.AgentCoordinator != nil && a.app.AgentCoordinator.IsBusy() {
600 // HACK: use a random percentage to prevent ghostty from hiding it
601 // after a timeout.
602 view.ProgressBar = tea.NewProgressBar(tea.ProgressBarIndeterminate, rand.Intn(100))
603 }
604 return view
605}
606
607// New creates and initializes a new TUI application model.
608func New(app *app.App) *appModel {
609 chatPage := chat.New(app)
610 keyMap := DefaultKeyMap()
611 keyMap.pageBindings = chatPage.Bindings()
612
613 model := &appModel{
614 currentPage: chat.ChatPageID,
615 app: app,
616 status: status.NewStatusCmp(),
617 loadedPages: make(map[page.PageID]bool),
618 keyMap: keyMap,
619
620 pages: map[page.PageID]util.Model{
621 chat.ChatPageID: chatPage,
622 },
623
624 dialog: dialogs.NewDialogCmp(),
625 completions: completions.New(),
626 }
627
628 return model
629}