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 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 model, err := a.app.CoderAgent.Update(config.AgentCoder, msg.Model.ID)
176 if err != nil {
177 return a, util.ReportError(err)
178 }
179
180 return a, util.ReportInfo(fmt.Sprintf("Model changed to %s", model.Name))
181
182 // File Picker
183 case chat.OpenFilePickerMsg:
184 if a.dialog.ActiveDialogID() == filepicker.FilePickerID {
185 // If the commands dialog is already open, close it
186 return a, util.CmdHandler(dialogs.CloseDialogMsg{})
187 }
188 return a, util.CmdHandler(dialogs.OpenDialogMsg{
189 Model: filepicker.NewFilePickerCmp(),
190 })
191 // Permissions
192 case pubsub.Event[permission.PermissionRequest]:
193 return a, util.CmdHandler(dialogs.OpenDialogMsg{
194 Model: permissions.NewPermissionDialogCmp(msg.Payload),
195 })
196 case permissions.PermissionResponseMsg:
197 switch msg.Action {
198 case permissions.PermissionAllow:
199 a.app.Permissions.Grant(msg.Permission)
200 case permissions.PermissionAllowForSession:
201 a.app.Permissions.GrantPersistent(msg.Permission)
202 case permissions.PermissionDeny:
203 a.app.Permissions.Deny(msg.Permission)
204 }
205 return a, nil
206 // Agent Events
207 case pubsub.Event[agent.AgentEvent]:
208 payload := msg.Payload
209
210 // Forward agent events to dialogs
211 if a.dialog.HasDialogs() && a.dialog.ActiveDialogID() == compact.CompactDialogID {
212 u, dialogCmd := a.dialog.Update(payload)
213 a.dialog = u.(dialogs.DialogCmp)
214 cmds = append(cmds, dialogCmd)
215 }
216
217 // Handle auto-compact logic
218 if payload.Done && payload.Type == agent.AgentEventTypeResponse && a.selectedSessionID != "" {
219 // Get current session to check token usage
220 session, err := a.app.Sessions.Get(context.Background(), a.selectedSessionID)
221 if err == nil {
222 model := a.app.CoderAgent.Model()
223 contextWindow := model.ContextWindow
224 tokens := session.CompletionTokens + session.PromptTokens
225 if (tokens >= int64(float64(contextWindow)*0.95)) && config.Get().AutoCompact {
226 // Show compact confirmation dialog
227 cmds = append(cmds, util.CmdHandler(dialogs.OpenDialogMsg{
228 Model: compact.NewCompactDialogCmp(a.app.CoderAgent, a.selectedSessionID, false),
229 }))
230 }
231 }
232 }
233
234 return a, tea.Batch(cmds...)
235 // Key Press Messages
236 case tea.KeyPressMsg:
237 return a, a.handleKeyPressMsg(msg)
238 }
239 s, _ := a.status.Update(msg)
240 a.status = s.(status.StatusCmp)
241 updated, cmd := a.pages[a.currentPage].Update(msg)
242 a.pages[a.currentPage] = updated.(util.Model)
243 if a.dialog.HasDialogs() {
244 u, dialogCmd := a.dialog.Update(msg)
245 a.dialog = u.(dialogs.DialogCmp)
246 cmds = append(cmds, dialogCmd)
247 }
248 cmds = append(cmds, cmd)
249 return a, tea.Batch(cmds...)
250}
251
252// handleWindowResize processes window resize events and updates all components.
253func (a *appModel) handleWindowResize(width, height int) tea.Cmd {
254 var cmds []tea.Cmd
255 a.wWidth, a.wHeight = width, height
256 if a.showingFullHelp {
257 height -= 4
258 } else {
259 height -= 2
260 }
261 a.width, a.height = width, height
262 // Update status bar
263 s, cmd := a.status.Update(tea.WindowSizeMsg{Width: width, Height: height})
264 a.status = s.(status.StatusCmp)
265 cmds = append(cmds, cmd)
266
267 // Update the current page
268 for p, page := range a.pages {
269 updated, pageCmd := page.Update(tea.WindowSizeMsg{Width: width, Height: height})
270 a.pages[p] = updated.(util.Model)
271 cmds = append(cmds, pageCmd)
272 }
273
274 // Update the dialogs
275 dialog, cmd := a.dialog.Update(tea.WindowSizeMsg{Width: width, Height: height})
276 a.dialog = dialog.(dialogs.DialogCmp)
277 cmds = append(cmds, cmd)
278
279 return tea.Batch(cmds...)
280}
281
282// handleKeyPressMsg processes keyboard input and routes to appropriate handlers.
283func (a *appModel) handleKeyPressMsg(msg tea.KeyPressMsg) tea.Cmd {
284 switch {
285 // completions
286 case a.completions.Open() && key.Matches(msg, a.completions.KeyMap().Up):
287 u, cmd := a.completions.Update(msg)
288 a.completions = u.(completions.Completions)
289 return cmd
290
291 case a.completions.Open() && key.Matches(msg, a.completions.KeyMap().Down):
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().Select):
296 u, cmd := a.completions.Update(msg)
297 a.completions = u.(completions.Completions)
298 return cmd
299 case a.completions.Open() && key.Matches(msg, a.completions.KeyMap().Cancel):
300 u, cmd := a.completions.Update(msg)
301 a.completions = u.(completions.Completions)
302 return cmd
303 // help
304 case key.Matches(msg, a.keyMap.Help):
305 a.status.ToggleFullHelp()
306 a.showingFullHelp = !a.showingFullHelp
307 return a.handleWindowResize(a.wWidth, a.wHeight)
308 // dialogs
309 case key.Matches(msg, a.keyMap.Quit):
310 if a.dialog.ActiveDialogID() == quit.QuitDialogID {
311 // if the quit dialog is already open, close the app
312 return tea.Quit
313 }
314 return util.CmdHandler(dialogs.OpenDialogMsg{
315 Model: quit.NewQuitDialog(),
316 })
317
318 case key.Matches(msg, a.keyMap.Commands):
319 if a.dialog.ActiveDialogID() == commands.CommandsDialogID {
320 // If the commands dialog is already open, close it
321 return util.CmdHandler(dialogs.CloseDialogMsg{})
322 }
323 return util.CmdHandler(dialogs.OpenDialogMsg{
324 Model: commands.NewCommandDialog(a.selectedSessionID),
325 })
326 case key.Matches(msg, a.keyMap.Sessions):
327 if a.dialog.ActiveDialogID() == sessions.SessionsDialogID {
328 // If the sessions dialog is already open, close it
329 return util.CmdHandler(dialogs.CloseDialogMsg{})
330 }
331 var cmds []tea.Cmd
332 if a.dialog.ActiveDialogID() == commands.CommandsDialogID {
333 // If the commands dialog is open, close it first
334 cmds = append(cmds, util.CmdHandler(dialogs.CloseDialogMsg{}))
335 }
336 cmds = append(cmds,
337 func() tea.Msg {
338 allSessions, _ := a.app.Sessions.List(context.Background())
339 return dialogs.OpenDialogMsg{
340 Model: sessions.NewSessionDialogCmp(allSessions, a.selectedSessionID),
341 }
342 },
343 )
344 return tea.Sequence(cmds...)
345 // Page navigation
346 case key.Matches(msg, a.keyMap.Logs):
347 return a.moveToPage(logs.LogsPage)
348
349 default:
350 if a.dialog.HasDialogs() {
351 u, dialogCmd := a.dialog.Update(msg)
352 a.dialog = u.(dialogs.DialogCmp)
353 return dialogCmd
354 } else {
355 updated, cmd := a.pages[a.currentPage].Update(msg)
356 a.pages[a.currentPage] = updated.(util.Model)
357 return cmd
358 }
359 }
360}
361
362// moveToPage handles navigation between different pages in the application.
363func (a *appModel) moveToPage(pageID page.PageID) tea.Cmd {
364 if a.app.CoderAgent.IsBusy() {
365 // TODO: maybe remove this : For now we don't move to any page if the agent is busy
366 return util.ReportWarn("Agent is busy, please wait...")
367 }
368
369 var cmds []tea.Cmd
370 if _, ok := a.loadedPages[pageID]; !ok {
371 cmd := a.pages[pageID].Init()
372 cmds = append(cmds, cmd)
373 a.loadedPages[pageID] = true
374 }
375 a.previousPage = a.currentPage
376 a.currentPage = pageID
377 if sizable, ok := a.pages[a.currentPage].(layout.Sizeable); ok {
378 cmd := sizable.SetSize(a.width, a.height)
379 cmds = append(cmds, cmd)
380 }
381
382 return tea.Batch(cmds...)
383}
384
385// View renders the complete application interface including pages, dialogs, and overlays.
386func (a *appModel) View() tea.View {
387 page := a.pages[a.currentPage]
388 if withHelp, ok := page.(layout.Help); ok {
389 a.keyMap.pageBindings = withHelp.Bindings()
390 }
391 a.status.SetKeyMap(a.keyMap)
392 pageView := page.View()
393 components := []string{
394 pageView.String(),
395 }
396 components = append(components, a.status.View().String())
397
398 appView := lipgloss.JoinVertical(lipgloss.Top, components...)
399 layers := []*lipgloss.Layer{
400 lipgloss.NewLayer(appView),
401 }
402 if a.dialog.HasDialogs() {
403 layers = append(
404 layers,
405 a.dialog.GetLayers()...,
406 )
407 }
408
409 cursor := pageView.Cursor()
410 activeView := a.dialog.ActiveView()
411 if activeView != nil {
412 cursor = activeView.Cursor()
413 }
414
415 if a.completions.Open() && cursor != nil {
416 cmp := a.completions.View().String()
417 x, y := a.completions.Position()
418 layers = append(
419 layers,
420 lipgloss.NewLayer(cmp).X(x).Y(y),
421 )
422 }
423
424 canvas := lipgloss.NewCanvas(
425 layers...,
426 )
427
428 t := styles.CurrentTheme()
429 view := tea.NewView(canvas.Render())
430 view.SetBackgroundColor(t.BgBase)
431 view.SetCursor(cursor)
432 return view
433}
434
435// New creates and initializes a new TUI application model.
436func New(app *app.App) tea.Model {
437 chatPage := chat.NewChatPage(app)
438 keyMap := DefaultKeyMap()
439 keyMap.pageBindings = chatPage.Bindings()
440
441 model := &appModel{
442 currentPage: chat.ChatPageID,
443 app: app,
444 status: status.NewStatusCmp(keyMap),
445 loadedPages: make(map[page.PageID]bool),
446 keyMap: keyMap,
447
448 pages: map[page.PageID]util.Model{
449 chat.ChatPageID: chatPage,
450 logs.LogsPage: logs.NewLogsPage(),
451 },
452
453 dialog: dialogs.NewDialogCmp(),
454 completions: completions.New(),
455 }
456
457 return model
458}