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 {
233 // Show compact confirmation dialog
234 cmds = append(cmds, util.CmdHandler(dialogs.OpenDialogMsg{
235 Model: compact.NewCompactDialogCmp(a.app.CoderAgent, a.selectedSessionID, false),
236 }))
237 }
238 }
239 }
240
241 return a, tea.Batch(cmds...)
242 // Key Press Messages
243 case tea.KeyPressMsg:
244 return a, a.handleKeyPressMsg(msg)
245 }
246 s, _ := a.status.Update(msg)
247 a.status = s.(status.StatusCmp)
248 updated, cmd := a.pages[a.currentPage].Update(msg)
249 a.pages[a.currentPage] = updated.(util.Model)
250 if a.dialog.HasDialogs() {
251 u, dialogCmd := a.dialog.Update(msg)
252 a.dialog = u.(dialogs.DialogCmp)
253 cmds = append(cmds, dialogCmd)
254 }
255 cmds = append(cmds, cmd)
256 return a, tea.Batch(cmds...)
257}
258
259// handleWindowResize processes window resize events and updates all components.
260func (a *appModel) handleWindowResize(width, height int) tea.Cmd {
261 var cmds []tea.Cmd
262 a.wWidth, a.wHeight = width, height
263 if a.showingFullHelp {
264 height -= 4
265 } else {
266 height -= 2
267 }
268 a.width, a.height = width, height
269 // Update status bar
270 s, cmd := a.status.Update(tea.WindowSizeMsg{Width: width, Height: height})
271 a.status = s.(status.StatusCmp)
272 cmds = append(cmds, cmd)
273
274 // Update the current page
275 for p, page := range a.pages {
276 updated, pageCmd := page.Update(tea.WindowSizeMsg{Width: width, Height: height})
277 a.pages[p] = updated.(util.Model)
278 cmds = append(cmds, pageCmd)
279 }
280
281 // Update the dialogs
282 dialog, cmd := a.dialog.Update(tea.WindowSizeMsg{Width: width, Height: height})
283 a.dialog = dialog.(dialogs.DialogCmp)
284 cmds = append(cmds, cmd)
285
286 return tea.Batch(cmds...)
287}
288
289// handleKeyPressMsg processes keyboard input and routes to appropriate handlers.
290func (a *appModel) handleKeyPressMsg(msg tea.KeyPressMsg) tea.Cmd {
291 switch {
292 // completions
293 case a.completions.Open() && key.Matches(msg, a.completions.KeyMap().Up):
294 u, cmd := a.completions.Update(msg)
295 a.completions = u.(completions.Completions)
296 return cmd
297
298 case a.completions.Open() && key.Matches(msg, a.completions.KeyMap().Down):
299 u, cmd := a.completions.Update(msg)
300 a.completions = u.(completions.Completions)
301 return cmd
302 case a.completions.Open() && key.Matches(msg, a.completions.KeyMap().Select):
303 u, cmd := a.completions.Update(msg)
304 a.completions = u.(completions.Completions)
305 return cmd
306 case a.completions.Open() && key.Matches(msg, a.completions.KeyMap().Cancel):
307 u, cmd := a.completions.Update(msg)
308 a.completions = u.(completions.Completions)
309 return cmd
310 // help
311 case key.Matches(msg, a.keyMap.Help):
312 a.status.ToggleFullHelp()
313 a.showingFullHelp = !a.showingFullHelp
314 return a.handleWindowResize(a.wWidth, a.wHeight)
315 // dialogs
316 case key.Matches(msg, a.keyMap.Quit):
317 if a.dialog.ActiveDialogID() == quit.QuitDialogID {
318 // if the quit dialog is already open, close the app
319 return tea.Quit
320 }
321 return util.CmdHandler(dialogs.OpenDialogMsg{
322 Model: quit.NewQuitDialog(),
323 })
324
325 case key.Matches(msg, a.keyMap.Commands):
326 if a.dialog.ActiveDialogID() == commands.CommandsDialogID {
327 // If the commands dialog is already open, close it
328 return util.CmdHandler(dialogs.CloseDialogMsg{})
329 }
330 return util.CmdHandler(dialogs.OpenDialogMsg{
331 Model: commands.NewCommandDialog(a.selectedSessionID),
332 })
333 case key.Matches(msg, a.keyMap.Sessions):
334 if a.dialog.ActiveDialogID() == sessions.SessionsDialogID {
335 // If the sessions dialog is already open, close it
336 return util.CmdHandler(dialogs.CloseDialogMsg{})
337 }
338 var cmds []tea.Cmd
339 if a.dialog.ActiveDialogID() == commands.CommandsDialogID {
340 // If the commands dialog is open, close it first
341 cmds = append(cmds, util.CmdHandler(dialogs.CloseDialogMsg{}))
342 }
343 cmds = append(cmds,
344 func() tea.Msg {
345 allSessions, _ := a.app.Sessions.List(context.Background())
346 return dialogs.OpenDialogMsg{
347 Model: sessions.NewSessionDialogCmp(allSessions, a.selectedSessionID),
348 }
349 },
350 )
351 return tea.Sequence(cmds...)
352 // Page navigation
353 case key.Matches(msg, a.keyMap.Logs):
354 return a.moveToPage(logs.LogsPage)
355
356 default:
357 if a.dialog.HasDialogs() {
358 u, dialogCmd := a.dialog.Update(msg)
359 a.dialog = u.(dialogs.DialogCmp)
360 return dialogCmd
361 } else {
362 updated, cmd := a.pages[a.currentPage].Update(msg)
363 a.pages[a.currentPage] = updated.(util.Model)
364 return cmd
365 }
366 }
367}
368
369// moveToPage handles navigation between different pages in the application.
370func (a *appModel) moveToPage(pageID page.PageID) tea.Cmd {
371 if a.app.CoderAgent.IsBusy() {
372 // TODO: maybe remove this : For now we don't move to any page if the agent is busy
373 return util.ReportWarn("Agent is busy, please wait...")
374 }
375
376 var cmds []tea.Cmd
377 if _, ok := a.loadedPages[pageID]; !ok {
378 cmd := a.pages[pageID].Init()
379 cmds = append(cmds, cmd)
380 a.loadedPages[pageID] = true
381 }
382 a.previousPage = a.currentPage
383 a.currentPage = pageID
384 if sizable, ok := a.pages[a.currentPage].(layout.Sizeable); ok {
385 cmd := sizable.SetSize(a.width, a.height)
386 cmds = append(cmds, cmd)
387 }
388
389 return tea.Batch(cmds...)
390}
391
392// View renders the complete application interface including pages, dialogs, and overlays.
393func (a *appModel) View() tea.View {
394 page := a.pages[a.currentPage]
395 if withHelp, ok := page.(layout.Help); ok {
396 a.keyMap.pageBindings = withHelp.Bindings()
397 }
398 a.status.SetKeyMap(a.keyMap)
399 pageView := page.View()
400 components := []string{
401 pageView.String(),
402 }
403 components = append(components, a.status.View().String())
404
405 appView := lipgloss.JoinVertical(lipgloss.Top, components...)
406 layers := []*lipgloss.Layer{
407 lipgloss.NewLayer(appView),
408 }
409 if a.dialog.HasDialogs() {
410 layers = append(
411 layers,
412 a.dialog.GetLayers()...,
413 )
414 }
415
416 cursor := pageView.Cursor()
417 activeView := a.dialog.ActiveView()
418 if activeView != nil {
419 cursor = activeView.Cursor()
420 }
421
422 if a.completions.Open() && cursor != nil {
423 cmp := a.completions.View().String()
424 x, y := a.completions.Position()
425 layers = append(
426 layers,
427 lipgloss.NewLayer(cmp).X(x).Y(y),
428 )
429 }
430
431 canvas := lipgloss.NewCanvas(
432 layers...,
433 )
434
435 t := styles.CurrentTheme()
436 view := tea.NewView(canvas.Render())
437 view.SetBackgroundColor(t.BgBase)
438 view.SetCursor(cursor)
439 return view
440}
441
442// New creates and initializes a new TUI application model.
443func New(app *app.App) tea.Model {
444 chatPage := chat.NewChatPage(app)
445 keyMap := DefaultKeyMap()
446 keyMap.pageBindings = chatPage.Bindings()
447
448 model := &appModel{
449 currentPage: chat.ChatPageID,
450 app: app,
451 status: status.NewStatusCmp(keyMap),
452 loadedPages: make(map[page.PageID]bool),
453 keyMap: keyMap,
454
455 pages: map[page.PageID]util.Model{
456 chat.ChatPageID: chatPage,
457 logs.LogsPage: logs.NewLogsPage(),
458 },
459
460 dialog: dialogs.NewDialogCmp(),
461 completions: completions.New(),
462 }
463
464 return model
465}