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