1package tui
2
3import (
4 "context"
5
6 "github.com/charmbracelet/bubbles/v2/key"
7 tea "github.com/charmbracelet/bubbletea/v2"
8 "github.com/charmbracelet/crush/internal/app"
9 "github.com/charmbracelet/crush/internal/config"
10 "github.com/charmbracelet/crush/internal/llm/agent"
11 "github.com/charmbracelet/crush/internal/logging"
12 "github.com/charmbracelet/crush/internal/permission"
13 "github.com/charmbracelet/crush/internal/pubsub"
14 cmpChat "github.com/charmbracelet/crush/internal/tui/components/chat"
15 "github.com/charmbracelet/crush/internal/tui/components/completions"
16 "github.com/charmbracelet/crush/internal/tui/components/core/layout"
17 "github.com/charmbracelet/crush/internal/tui/components/core/status"
18 "github.com/charmbracelet/crush/internal/tui/components/dialogs"
19 "github.com/charmbracelet/crush/internal/tui/components/dialogs/commands"
20 "github.com/charmbracelet/crush/internal/tui/components/dialogs/compact"
21 "github.com/charmbracelet/crush/internal/tui/components/dialogs/filepicker"
22 initDialog "github.com/charmbracelet/crush/internal/tui/components/dialogs/init"
23 "github.com/charmbracelet/crush/internal/tui/components/dialogs/models"
24 "github.com/charmbracelet/crush/internal/tui/components/dialogs/permissions"
25 "github.com/charmbracelet/crush/internal/tui/components/dialogs/quit"
26 "github.com/charmbracelet/crush/internal/tui/components/dialogs/sessions"
27 "github.com/charmbracelet/crush/internal/tui/page"
28 "github.com/charmbracelet/crush/internal/tui/page/chat"
29 "github.com/charmbracelet/crush/internal/tui/page/logs"
30 "github.com/charmbracelet/crush/internal/tui/styles"
31 "github.com/charmbracelet/crush/internal/tui/util"
32 "github.com/charmbracelet/lipgloss/v2"
33)
34
35// appModel represents the main application model that manages pages, dialogs, and UI state.
36type appModel struct {
37 wWidth, wHeight int // Window dimensions
38 width, height int
39 keyMap KeyMap
40
41 currentPage page.PageID
42 previousPage page.PageID
43 pages map[page.PageID]util.Model
44 loadedPages map[page.PageID]bool
45
46 // Status
47 status status.StatusCmp
48 showingFullHelp bool
49
50 app *app.App
51
52 dialog dialogs.DialogCmp
53 completions completions.Completions
54
55 // Chat Page Specific
56 selectedSessionID string // The ID of the currently selected session
57}
58
59// Init initializes the application model and returns initial commands.
60func (a appModel) Init() tea.Cmd {
61 var cmds []tea.Cmd
62 cmd := a.pages[a.currentPage].Init()
63 cmds = append(cmds, cmd)
64 a.loadedPages[a.currentPage] = true
65
66 cmd = a.status.Init()
67 cmds = append(cmds, cmd)
68
69 // Check if we should show the init dialog
70 cmds = append(cmds, func() tea.Msg {
71 shouldShow, err := config.ShouldShowInitDialog()
72 if err != nil {
73 return util.InfoMsg{
74 Type: util.InfoTypeError,
75 Msg: "Failed to check init status: " + err.Error(),
76 }
77 }
78 if shouldShow {
79 return dialogs.OpenDialogMsg{
80 Model: initDialog.NewInitDialogCmp(),
81 }
82 }
83 return nil
84 })
85
86 return tea.Batch(cmds...)
87}
88
89// Update handles incoming messages and updates the application state.
90func (a *appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
91 var cmds []tea.Cmd
92 var cmd tea.Cmd
93
94 switch msg := msg.(type) {
95 case tea.KeyboardEnhancementsMsg:
96 logging.Info(
97 "Keyboard enhancements detected",
98 "Disambiguation", msg.SupportsKeyDisambiguation(),
99 "ReleaseKeys", msg.SupportsKeyReleases(),
100 "UniformKeys", msg.SupportsUniformKeyLayout(),
101 )
102 return a, nil
103 case tea.WindowSizeMsg:
104 return a, a.handleWindowResize(msg.Width, msg.Height)
105
106 // Completions messages
107 case completions.OpenCompletionsMsg, completions.FilterCompletionsMsg, completions.CloseCompletionsMsg:
108 u, completionCmd := a.completions.Update(msg)
109 a.completions = u.(completions.Completions)
110 return a, completionCmd
111
112 // Dialog messages
113 case dialogs.OpenDialogMsg, dialogs.CloseDialogMsg:
114 u, dialogCmd := a.dialog.Update(msg)
115 a.dialog = u.(dialogs.DialogCmp)
116 return a, dialogCmd
117 case commands.ShowArgumentsDialogMsg:
118 return a, util.CmdHandler(
119 dialogs.OpenDialogMsg{
120 Model: commands.NewCommandArgumentsDialog(
121 msg.CommandID,
122 msg.Content,
123 msg.ArgNames,
124 ),
125 },
126 )
127 // Page change messages
128 case page.PageChangeMsg:
129 return a, a.moveToPage(msg.ID)
130
131 // Status Messages
132 case util.InfoMsg, util.ClearStatusMsg:
133 s, statusCmd := a.status.Update(msg)
134 a.status = s.(status.StatusCmp)
135 cmds = append(cmds, statusCmd)
136 return a, tea.Batch(cmds...)
137
138 // Session
139 case cmpChat.SessionSelectedMsg:
140 a.selectedSessionID = msg.ID
141 case cmpChat.SessionClearedMsg:
142 a.selectedSessionID = ""
143 // Logs
144 case pubsub.Event[logging.LogMessage]:
145 // Send to the status component
146 s, statusCmd := a.status.Update(msg)
147 a.status = s.(status.StatusCmp)
148 cmds = append(cmds, statusCmd)
149
150 // If the current page is logs, update the logs view
151 if a.currentPage == logs.LogsPage {
152 updated, pageCmd := a.pages[a.currentPage].Update(msg)
153 a.pages[a.currentPage] = updated.(util.Model)
154 cmds = append(cmds, pageCmd)
155 }
156 return a, tea.Batch(cmds...)
157 // Commands
158 case commands.SwitchSessionsMsg:
159 return a, func() tea.Msg {
160 allSessions, _ := a.app.Sessions.List(context.Background())
161 return dialogs.OpenDialogMsg{
162 Model: sessions.NewSessionDialogCmp(allSessions, a.selectedSessionID),
163 }
164 }
165
166 case commands.SwitchModelMsg:
167 return a, util.CmdHandler(
168 dialogs.OpenDialogMsg{
169 Model: models.NewModelDialogCmp(),
170 },
171 )
172 // Compact
173 case commands.CompactMsg:
174 return a, util.CmdHandler(dialogs.OpenDialogMsg{
175 Model: compact.NewCompactDialogCmp(a.app.CoderAgent, msg.SessionID, true),
176 })
177
178 // File Picker
179 case chat.OpenFilePickerMsg:
180 if a.dialog.ActiveDialogID() == filepicker.FilePickerID {
181 // If the commands dialog is already open, close it
182 return a, util.CmdHandler(dialogs.CloseDialogMsg{})
183 }
184 return a, util.CmdHandler(dialogs.OpenDialogMsg{
185 Model: filepicker.NewFilePickerCmp(),
186 })
187 // Permissions
188 case pubsub.Event[permission.PermissionRequest]:
189 return a, util.CmdHandler(dialogs.OpenDialogMsg{
190 Model: permissions.NewPermissionDialogCmp(msg.Payload),
191 })
192 case permissions.PermissionResponseMsg:
193 switch msg.Action {
194 case permissions.PermissionAllow:
195 a.app.Permissions.Grant(msg.Permission)
196 case permissions.PermissionAllowForSession:
197 a.app.Permissions.GrantPersistent(msg.Permission)
198 case permissions.PermissionDeny:
199 a.app.Permissions.Deny(msg.Permission)
200 }
201 return a, nil
202 // Agent Events
203 case pubsub.Event[agent.AgentEvent]:
204 payload := msg.Payload
205
206 // Forward agent events to dialogs
207 if a.dialog.HasDialogs() && a.dialog.ActiveDialogID() == compact.CompactDialogID {
208 u, dialogCmd := a.dialog.Update(payload)
209 a.dialog = u.(dialogs.DialogCmp)
210 cmds = append(cmds, dialogCmd)
211 }
212
213 // Handle auto-compact logic
214 if payload.Done && payload.Type == agent.AgentEventTypeResponse && a.selectedSessionID != "" {
215 // Get current session to check token usage
216 session, err := a.app.Sessions.Get(context.Background(), a.selectedSessionID)
217 if err == nil {
218 model := a.app.CoderAgent.Model()
219 contextWindow := model.ContextWindow
220 tokens := session.CompletionTokens + session.PromptTokens
221 if (tokens >= int64(float64(contextWindow)*0.95)) && config.Get().AutoCompact {
222 // Show compact confirmation dialog
223 cmds = append(cmds, util.CmdHandler(dialogs.OpenDialogMsg{
224 Model: compact.NewCompactDialogCmp(a.app.CoderAgent, a.selectedSessionID, false),
225 }))
226 }
227 }
228 }
229
230 return a, tea.Batch(cmds...)
231 // Key Press Messages
232 case tea.KeyPressMsg:
233 return a, a.handleKeyPressMsg(msg)
234 }
235 s, _ := a.status.Update(msg)
236 a.status = s.(status.StatusCmp)
237 updated, cmd := a.pages[a.currentPage].Update(msg)
238 a.pages[a.currentPage] = updated.(util.Model)
239 if a.dialog.HasDialogs() {
240 u, dialogCmd := a.dialog.Update(msg)
241 a.dialog = u.(dialogs.DialogCmp)
242 cmds = append(cmds, dialogCmd)
243 }
244 cmds = append(cmds, cmd)
245 return a, tea.Batch(cmds...)
246}
247
248// handleWindowResize processes window resize events and updates all components.
249func (a *appModel) handleWindowResize(width, height int) tea.Cmd {
250 var cmds []tea.Cmd
251 a.wWidth, a.wHeight = width, height
252 if a.showingFullHelp {
253 height -= 3
254 } else {
255 height -= 2
256 }
257 a.width, a.height = width, height
258 // Update status bar
259 s, cmd := a.status.Update(tea.WindowSizeMsg{Width: width, Height: height})
260 a.status = s.(status.StatusCmp)
261 cmds = append(cmds, cmd)
262
263 // Update the current page
264 for p, page := range a.pages {
265 updated, pageCmd := page.Update(tea.WindowSizeMsg{Width: width, Height: height})
266 a.pages[p] = updated.(util.Model)
267 cmds = append(cmds, pageCmd)
268 }
269
270 // Update the dialogs
271 dialog, cmd := a.dialog.Update(tea.WindowSizeMsg{Width: width, Height: height})
272 a.dialog = dialog.(dialogs.DialogCmp)
273 cmds = append(cmds, cmd)
274
275 return tea.Batch(cmds...)
276}
277
278// handleKeyPressMsg processes keyboard input and routes to appropriate handlers.
279func (a *appModel) handleKeyPressMsg(msg tea.KeyPressMsg) tea.Cmd {
280 switch {
281 // completions
282 case a.completions.Open() && key.Matches(msg, a.completions.KeyMap().Up):
283 u, cmd := a.completions.Update(msg)
284 a.completions = u.(completions.Completions)
285 return cmd
286
287 case a.completions.Open() && key.Matches(msg, a.completions.KeyMap().Down):
288 u, cmd := a.completions.Update(msg)
289 a.completions = u.(completions.Completions)
290 return cmd
291 case a.completions.Open() && key.Matches(msg, a.completions.KeyMap().Select):
292 u, cmd := a.completions.Update(msg)
293 a.completions = u.(completions.Completions)
294 return cmd
295 case a.completions.Open() && key.Matches(msg, a.completions.KeyMap().Cancel):
296 u, cmd := a.completions.Update(msg)
297 a.completions = u.(completions.Completions)
298 return cmd
299 // help
300 case key.Matches(msg, a.keyMap.Help):
301 a.status.ToggleFullHelp()
302 a.showingFullHelp = !a.showingFullHelp
303 return a.handleWindowResize(a.wWidth, a.wHeight)
304 // dialogs
305 case key.Matches(msg, a.keyMap.Quit):
306 if a.dialog.ActiveDialogID() == quit.QuitDialogID {
307 // if the quit dialog is already open, close the app
308 return tea.Quit
309 }
310 return util.CmdHandler(dialogs.OpenDialogMsg{
311 Model: quit.NewQuitDialog(),
312 })
313
314 case key.Matches(msg, a.keyMap.Commands):
315 if a.dialog.ActiveDialogID() == commands.CommandsDialogID {
316 // If the commands dialog is already open, close it
317 return util.CmdHandler(dialogs.CloseDialogMsg{})
318 }
319 return util.CmdHandler(dialogs.OpenDialogMsg{
320 Model: commands.NewCommandDialog(a.selectedSessionID),
321 })
322 case key.Matches(msg, a.keyMap.Sessions):
323 if a.dialog.ActiveDialogID() == sessions.SessionsDialogID {
324 // If the sessions dialog is already open, close it
325 return util.CmdHandler(dialogs.CloseDialogMsg{})
326 }
327 var cmds []tea.Cmd
328 if a.dialog.ActiveDialogID() == commands.CommandsDialogID {
329 // If the commands dialog is open, close it first
330 cmds = append(cmds, util.CmdHandler(dialogs.CloseDialogMsg{}))
331 }
332 cmds = append(cmds,
333 func() tea.Msg {
334 allSessions, _ := a.app.Sessions.List(context.Background())
335 return dialogs.OpenDialogMsg{
336 Model: sessions.NewSessionDialogCmp(allSessions, a.selectedSessionID),
337 }
338 },
339 )
340 return tea.Sequence(cmds...)
341 // Page navigation
342 case key.Matches(msg, a.keyMap.Logs):
343 return a.moveToPage(logs.LogsPage)
344
345 default:
346 if a.dialog.HasDialogs() {
347 u, dialogCmd := a.dialog.Update(msg)
348 a.dialog = u.(dialogs.DialogCmp)
349 return dialogCmd
350 } else {
351 updated, cmd := a.pages[a.currentPage].Update(msg)
352 a.pages[a.currentPage] = updated.(util.Model)
353 return cmd
354 }
355 }
356}
357
358// moveToPage handles navigation between different pages in the application.
359func (a *appModel) moveToPage(pageID page.PageID) tea.Cmd {
360 if a.app.CoderAgent.IsBusy() {
361 // TODO: maybe remove this : For now we don't move to any page if the agent is busy
362 return util.ReportWarn("Agent is busy, please wait...")
363 }
364
365 var cmds []tea.Cmd
366 if _, ok := a.loadedPages[pageID]; !ok {
367 cmd := a.pages[pageID].Init()
368 cmds = append(cmds, cmd)
369 a.loadedPages[pageID] = true
370 }
371 a.previousPage = a.currentPage
372 a.currentPage = pageID
373 if sizable, ok := a.pages[a.currentPage].(layout.Sizeable); ok {
374 cmd := sizable.SetSize(a.width, a.height)
375 cmds = append(cmds, cmd)
376 }
377
378 return tea.Batch(cmds...)
379}
380
381// View renders the complete application interface including pages, dialogs, and overlays.
382func (a *appModel) View() tea.View {
383 page := a.pages[a.currentPage]
384 if withHelp, ok := page.(layout.Help); ok {
385 a.keyMap.pageBindings = withHelp.Bindings()
386 }
387 a.status.SetKeyMap(a.keyMap)
388 pageView := page.View()
389 components := []string{
390 pageView.String(),
391 }
392 components = append(components, a.status.View().String())
393
394 appView := lipgloss.JoinVertical(lipgloss.Top, components...)
395 layers := []*lipgloss.Layer{
396 lipgloss.NewLayer(appView),
397 }
398 if a.dialog.HasDialogs() {
399 layers = append(
400 layers,
401 a.dialog.GetLayers()...,
402 )
403 }
404
405 cursor := pageView.Cursor()
406 activeView := a.dialog.ActiveView()
407 if activeView != nil {
408 cursor = activeView.Cursor()
409 }
410
411 if a.completions.Open() && cursor != nil {
412 cmp := a.completions.View().String()
413 x, y := a.completions.Position()
414 layers = append(
415 layers,
416 lipgloss.NewLayer(cmp).X(x).Y(y),
417 )
418 }
419
420 canvas := lipgloss.NewCanvas(
421 layers...,
422 )
423
424 t := styles.CurrentTheme()
425 view := tea.NewView(canvas.Render())
426 view.SetBackgroundColor(t.BgBase)
427 view.SetCursor(cursor)
428 return view
429}
430
431// New creates and initializes a new TUI application model.
432func New(app *app.App) tea.Model {
433 chatPage := chat.NewChatPage(app)
434 keyMap := DefaultKeyMap()
435 keyMap.pageBindings = chatPage.Bindings()
436
437 model := &appModel{
438 currentPage: chat.ChatPageID,
439 app: app,
440 status: status.NewStatusCmp(keyMap),
441 loadedPages: make(map[page.PageID]bool),
442 keyMap: keyMap,
443
444 pages: map[page.PageID]util.Model{
445 chat.ChatPageID: chatPage,
446 logs.LogsPage: logs.NewLogsPage(),
447 },
448
449 dialog: dialogs.NewDialogCmp(),
450 completions: completions.New(),
451 }
452
453 return model
454}