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.ShouldShowInitDialog()
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 logging.Info(
98 "Keyboard enhancements detected",
99 "Disambiguation", msg.SupportsKeyDisambiguation(),
100 "ReleaseKeys", msg.SupportsKeyReleases(),
101 "UniformKeys", msg.SupportsUniformKeyLayout(),
102 )
103 return a, nil
104 case tea.WindowSizeMsg:
105 return a, a.handleWindowResize(msg.Width, msg.Height)
106
107 // Completions messages
108 case completions.OpenCompletionsMsg, completions.FilterCompletionsMsg, completions.CloseCompletionsMsg:
109 u, completionCmd := a.completions.Update(msg)
110 a.completions = u.(completions.Completions)
111 return a, completionCmd
112
113 // Dialog messages
114 case dialogs.OpenDialogMsg, dialogs.CloseDialogMsg:
115 u, dialogCmd := a.dialog.Update(msg)
116 a.dialog = u.(dialogs.DialogCmp)
117 return a, dialogCmd
118 case commands.ShowArgumentsDialogMsg:
119 return a, util.CmdHandler(
120 dialogs.OpenDialogMsg{
121 Model: commands.NewCommandArgumentsDialog(
122 msg.CommandID,
123 msg.Content,
124 msg.ArgNames,
125 ),
126 },
127 )
128 // Page change messages
129 case page.PageChangeMsg:
130 return a, a.moveToPage(msg.ID)
131
132 // Status Messages
133 case util.InfoMsg, util.ClearStatusMsg:
134 s, statusCmd := a.status.Update(msg)
135 a.status = s.(status.StatusCmp)
136 cmds = append(cmds, statusCmd)
137 return a, tea.Batch(cmds...)
138
139 // Session
140 case cmpChat.SessionSelectedMsg:
141 a.selectedSessionID = msg.ID
142 case cmpChat.SessionClearedMsg:
143 a.selectedSessionID = ""
144 // Logs
145 case pubsub.Event[logging.LogMessage]:
146 // Send to the status component
147 s, statusCmd := a.status.Update(msg)
148 a.status = s.(status.StatusCmp)
149 cmds = append(cmds, statusCmd)
150
151 // If the current page is logs, update the logs view
152 if a.currentPage == logs.LogsPage {
153 updated, pageCmd := a.pages[a.currentPage].Update(msg)
154 a.pages[a.currentPage] = updated.(util.Model)
155 cmds = append(cmds, pageCmd)
156 }
157 return a, tea.Batch(cmds...)
158 // Commands
159 case commands.SwitchSessionsMsg:
160 return a, func() tea.Msg {
161 allSessions, _ := a.app.Sessions.List(context.Background())
162 return dialogs.OpenDialogMsg{
163 Model: sessions.NewSessionDialogCmp(allSessions, a.selectedSessionID),
164 }
165 }
166
167 case commands.SwitchModelMsg:
168 return a, util.CmdHandler(
169 dialogs.OpenDialogMsg{
170 Model: models.NewModelDialogCmp(),
171 },
172 )
173 // Compact
174 case commands.CompactMsg:
175 return a, util.CmdHandler(dialogs.OpenDialogMsg{
176 Model: compact.NewCompactDialogCmp(a.app.CoderAgent, msg.SessionID, true),
177 })
178
179 // Model Switch
180 case models.ModelSelectedMsg:
181 model, err := a.app.CoderAgent.Update(config.AgentCoder, msg.Model.ID)
182 if err != nil {
183 return a, util.ReportError(err)
184 }
185
186 return a, util.ReportInfo(fmt.Sprintf("Model changed to %s", model.Name))
187
188 // File Picker
189 case chat.OpenFilePickerMsg:
190 if a.dialog.ActiveDialogID() == filepicker.FilePickerID {
191 // If the commands dialog is already open, close it
192 return a, util.CmdHandler(dialogs.CloseDialogMsg{})
193 }
194 return a, util.CmdHandler(dialogs.OpenDialogMsg{
195 Model: filepicker.NewFilePickerCmp(),
196 })
197 // Permissions
198 case pubsub.Event[permission.PermissionRequest]:
199 return a, util.CmdHandler(dialogs.OpenDialogMsg{
200 Model: permissions.NewPermissionDialogCmp(msg.Payload),
201 })
202 case permissions.PermissionResponseMsg:
203 switch msg.Action {
204 case permissions.PermissionAllow:
205 a.app.Permissions.Grant(msg.Permission)
206 case permissions.PermissionAllowForSession:
207 a.app.Permissions.GrantPersistent(msg.Permission)
208 case permissions.PermissionDeny:
209 a.app.Permissions.Deny(msg.Permission)
210 }
211 return a, nil
212 // Agent Events
213 case pubsub.Event[agent.AgentEvent]:
214 payload := msg.Payload
215
216 // Forward agent events to dialogs
217 if a.dialog.HasDialogs() && a.dialog.ActiveDialogID() == compact.CompactDialogID {
218 u, dialogCmd := a.dialog.Update(payload)
219 a.dialog = u.(dialogs.DialogCmp)
220 cmds = append(cmds, dialogCmd)
221 }
222
223 // Handle auto-compact logic
224 if payload.Done && payload.Type == agent.AgentEventTypeResponse && a.selectedSessionID != "" {
225 // Get current session to check token usage
226 session, err := a.app.Sessions.Get(context.Background(), a.selectedSessionID)
227 if err == nil {
228 model := a.app.CoderAgent.Model()
229 contextWindow := model.ContextWindow
230 tokens := session.CompletionTokens + session.PromptTokens
231 if (tokens >= int64(float64(contextWindow)*0.95)) && config.Get().AutoCompact {
232 // 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 -= 3
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}