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