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(config.LargeModel, msg.Model)
176 return a, util.ReportInfo(fmt.Sprintf("Model changed to %s", msg.Model.ModelID))
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().Options.DisableAutoSummarize {
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 -= 4
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}