1package tui
2
3import (
4 "context"
5
6 "github.com/charmbracelet/bubbles/v2/key"
7 tea "github.com/charmbracelet/bubbletea/v2"
8 "github.com/charmbracelet/crush/internal/app"
9 "github.com/charmbracelet/crush/internal/config"
10 "github.com/charmbracelet/crush/internal/llm/agent"
11 "github.com/charmbracelet/crush/internal/logging"
12 "github.com/charmbracelet/crush/internal/permission"
13 "github.com/charmbracelet/crush/internal/pubsub"
14 cmpChat "github.com/charmbracelet/crush/internal/tui/components/chat"
15 "github.com/charmbracelet/crush/internal/tui/components/completions"
16 "github.com/charmbracelet/crush/internal/tui/components/core/layout"
17 "github.com/charmbracelet/crush/internal/tui/components/core/status"
18 "github.com/charmbracelet/crush/internal/tui/components/dialogs"
19 "github.com/charmbracelet/crush/internal/tui/components/dialogs/commands"
20 "github.com/charmbracelet/crush/internal/tui/components/dialogs/compact"
21 "github.com/charmbracelet/crush/internal/tui/components/dialogs/filepicker"
22 initDialog "github.com/charmbracelet/crush/internal/tui/components/dialogs/init"
23 "github.com/charmbracelet/crush/internal/tui/components/dialogs/models"
24 "github.com/charmbracelet/crush/internal/tui/components/dialogs/permissions"
25 "github.com/charmbracelet/crush/internal/tui/components/dialogs/quit"
26 "github.com/charmbracelet/crush/internal/tui/components/dialogs/sessions"
27 "github.com/charmbracelet/crush/internal/tui/page"
28 "github.com/charmbracelet/crush/internal/tui/page/chat"
29 "github.com/charmbracelet/crush/internal/tui/page/logs"
30 "github.com/charmbracelet/crush/internal/tui/styles"
31 "github.com/charmbracelet/crush/internal/tui/util"
32 "github.com/charmbracelet/lipgloss/v2"
33)
34
35// appModel represents the main application model that manages pages, dialogs, and UI state.
36type appModel struct {
37 width, height int
38 keyMap KeyMap
39
40 currentPage page.PageID
41 previousPage page.PageID
42 pages map[page.PageID]util.Model
43 loadedPages map[page.PageID]bool
44
45 status status.StatusCmp
46
47 app *app.App
48
49 dialog dialogs.DialogCmp
50 completions completions.Completions
51
52 // Session
53 selectedSessionID string // The ID of the currently selected session
54 fullHelp bool // Whether to show full help text
55}
56
57// Init initializes the application model and returns initial commands.
58func (a appModel) Init() tea.Cmd {
59 var cmds []tea.Cmd
60 cmd := a.pages[a.currentPage].Init()
61 cmds = append(cmds, cmd)
62 a.loadedPages[a.currentPage] = true
63
64 cmd = a.status.Init()
65 cmds = append(cmds, cmd)
66
67 // Check if we should show the init dialog
68 cmds = append(cmds, func() tea.Msg {
69 shouldShow, err := config.ShouldShowInitDialog()
70 if err != nil {
71 return util.InfoMsg{
72 Type: util.InfoTypeError,
73 Msg: "Failed to check init status: " + err.Error(),
74 }
75 }
76 if shouldShow {
77 return dialogs.OpenDialogMsg{
78 Model: initDialog.NewInitDialogCmp(),
79 }
80 }
81 return nil
82 })
83
84 return tea.Batch(cmds...)
85}
86
87// Update handles incoming messages and updates the application state.
88func (a *appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
89 var cmds []tea.Cmd
90 var cmd tea.Cmd
91
92 switch msg := msg.(type) {
93 case tea.KeyboardEnhancementsMsg:
94 logging.Info(
95 "Keyboard enhancements detected",
96 "Disambiguation", msg.SupportsKeyDisambiguation(),
97 "ReleaseKeys", msg.SupportsKeyReleases(),
98 "UniformKeys", msg.SupportsUniformKeyLayout(),
99 )
100 return a, nil
101 case tea.WindowSizeMsg:
102 return a, a.handleWindowResize(msg)
103
104 // Completions messages
105 case completions.OpenCompletionsMsg, completions.FilterCompletionsMsg, completions.CloseCompletionsMsg:
106 u, completionCmd := a.completions.Update(msg)
107 a.completions = u.(completions.Completions)
108 return a, completionCmd
109
110 // Dialog messages
111 case dialogs.OpenDialogMsg, dialogs.CloseDialogMsg:
112 u, dialogCmd := a.dialog.Update(msg)
113 a.dialog = u.(dialogs.DialogCmp)
114 return a, dialogCmd
115 case commands.ShowArgumentsDialogMsg:
116 return a, util.CmdHandler(
117 dialogs.OpenDialogMsg{
118 Model: commands.NewCommandArgumentsDialog(
119 msg.CommandID,
120 msg.Content,
121 msg.ArgNames,
122 ),
123 },
124 )
125 // Page change messages
126 case page.PageChangeMsg:
127 return a, a.moveToPage(msg.ID)
128
129 // Status Messages
130 case util.InfoMsg, util.ClearStatusMsg:
131 s, statusCmd := a.status.Update(msg)
132 a.status = s.(status.StatusCmp)
133 cmds = append(cmds, statusCmd)
134 return a, tea.Batch(cmds...)
135
136 // Session
137 case cmpChat.SessionSelectedMsg:
138 a.selectedSessionID = msg.ID
139 case cmpChat.SessionClearedMsg:
140 a.selectedSessionID = ""
141 // Logs
142 case pubsub.Event[logging.LogMessage]:
143 // Send to the status component
144 s, statusCmd := a.status.Update(msg)
145 a.status = s.(status.StatusCmp)
146 cmds = append(cmds, statusCmd)
147
148 // If the current page is logs, update the logs view
149 if a.currentPage == logs.LogsPage {
150 updated, pageCmd := a.pages[a.currentPage].Update(msg)
151 a.pages[a.currentPage] = updated.(util.Model)
152 cmds = append(cmds, pageCmd)
153 }
154 return a, tea.Batch(cmds...)
155 // Commands
156 case commands.SwitchSessionsMsg:
157 return a, func() tea.Msg {
158 allSessions, _ := a.app.Sessions.List(context.Background())
159 return dialogs.OpenDialogMsg{
160 Model: sessions.NewSessionDialogCmp(allSessions, a.selectedSessionID),
161 }
162 }
163
164 case commands.SwitchModelMsg:
165 return a, util.CmdHandler(
166 dialogs.OpenDialogMsg{
167 Model: models.NewModelDialogCmp(),
168 },
169 )
170 // Compact
171 case commands.CompactMsg:
172 return a, util.CmdHandler(dialogs.OpenDialogMsg{
173 Model: compact.NewCompactDialogCmp(a.app.CoderAgent, msg.SessionID, true),
174 })
175
176 // File Picker
177 case chat.OpenFilePickerMsg:
178 if a.dialog.ActiveDialogID() == filepicker.FilePickerID {
179 // If the commands dialog is already open, close it
180 return a, util.CmdHandler(dialogs.CloseDialogMsg{})
181 }
182 return a, util.CmdHandler(dialogs.OpenDialogMsg{
183 Model: filepicker.NewFilePickerCmp(),
184 })
185 // Permissions
186 case pubsub.Event[permission.PermissionRequest]:
187 return a, util.CmdHandler(dialogs.OpenDialogMsg{
188 Model: permissions.NewPermissionDialogCmp(msg.Payload),
189 })
190 case permissions.PermissionResponseMsg:
191 switch msg.Action {
192 case permissions.PermissionAllow:
193 a.app.Permissions.Grant(msg.Permission)
194 case permissions.PermissionAllowForSession:
195 a.app.Permissions.GrantPersistent(msg.Permission)
196 case permissions.PermissionDeny:
197 a.app.Permissions.Deny(msg.Permission)
198 }
199 return a, nil
200 // Agent Events
201 case pubsub.Event[agent.AgentEvent]:
202 payload := msg.Payload
203
204 // Forward agent events to dialogs
205 if a.dialog.HasDialogs() && a.dialog.ActiveDialogID() == compact.CompactDialogID {
206 u, dialogCmd := a.dialog.Update(payload)
207 a.dialog = u.(dialogs.DialogCmp)
208 cmds = append(cmds, dialogCmd)
209 }
210
211 // Handle auto-compact logic
212 if payload.Done && payload.Type == agent.AgentEventTypeResponse && a.selectedSessionID != "" {
213 // Get current session to check token usage
214 session, err := a.app.Sessions.Get(context.Background(), a.selectedSessionID)
215 if err == nil {
216 model := a.app.CoderAgent.Model()
217 contextWindow := model.ContextWindow
218 tokens := session.CompletionTokens + session.PromptTokens
219 if (tokens >= int64(float64(contextWindow)*0.95)) && config.Get().AutoCompact {
220 // Show compact confirmation dialog
221 cmds = append(cmds, util.CmdHandler(dialogs.OpenDialogMsg{
222 Model: compact.NewCompactDialogCmp(a.app.CoderAgent, a.selectedSessionID, false),
223 }))
224 }
225 }
226 }
227
228 return a, tea.Batch(cmds...)
229 // Key Press Messages
230 case tea.KeyPressMsg:
231 return a, a.handleKeyPressMsg(msg)
232 }
233 s, _ := a.status.Update(msg)
234 a.status = s.(status.StatusCmp)
235 updated, cmd := a.pages[a.currentPage].Update(msg)
236 a.pages[a.currentPage] = updated.(util.Model)
237 if a.dialog.HasDialogs() {
238 u, dialogCmd := a.dialog.Update(msg)
239 a.dialog = u.(dialogs.DialogCmp)
240 cmds = append(cmds, dialogCmd)
241 }
242 cmds = append(cmds, cmd)
243 return a, tea.Batch(cmds...)
244}
245
246// handleWindowResize processes window resize events and updates all components.
247func (a *appModel) handleWindowResize(msg tea.WindowSizeMsg) tea.Cmd {
248 var cmds []tea.Cmd
249 msg.Height -= 2 // Make space for the status bar
250 a.width, a.height = msg.Width, msg.Height
251
252 // Update status bar
253 s, cmd := a.status.Update(msg)
254 a.status = s.(status.StatusCmp)
255 cmds = append(cmds, cmd)
256
257 // Update the current page
258 updated, cmd := a.pages[a.currentPage].Update(msg)
259 a.pages[a.currentPage] = updated.(util.Model)
260 cmds = append(cmds, cmd)
261
262 // Update the dialogs
263 dialog, cmd := a.dialog.Update(msg)
264 a.dialog = dialog.(dialogs.DialogCmp)
265 cmds = append(cmds, cmd)
266
267 return tea.Batch(cmds...)
268}
269
270// handleKeyPressMsg processes keyboard input and routes to appropriate handlers.
271func (a *appModel) handleKeyPressMsg(msg tea.KeyPressMsg) tea.Cmd {
272 switch {
273 // completions
274 case a.completions.Open() && key.Matches(msg, a.completions.KeyMap().Up):
275 u, cmd := a.completions.Update(msg)
276 a.completions = u.(completions.Completions)
277 return cmd
278
279 case a.completions.Open() && key.Matches(msg, a.completions.KeyMap().Down):
280 u, cmd := a.completions.Update(msg)
281 a.completions = u.(completions.Completions)
282 return cmd
283 case a.completions.Open() && key.Matches(msg, a.completions.KeyMap().Select):
284 u, cmd := a.completions.Update(msg)
285 a.completions = u.(completions.Completions)
286 return cmd
287 case a.completions.Open() && key.Matches(msg, a.completions.KeyMap().Cancel):
288 u, cmd := a.completions.Update(msg)
289 a.completions = u.(completions.Completions)
290 return cmd
291 // dialogs
292 case key.Matches(msg, a.keyMap.Quit):
293 if a.dialog.ActiveDialogID() == quit.QuitDialogID {
294 // if the quit dialog is already open, close the app
295 return tea.Quit
296 }
297 return util.CmdHandler(dialogs.OpenDialogMsg{
298 Model: quit.NewQuitDialog(),
299 })
300
301 case key.Matches(msg, a.keyMap.Commands):
302 if a.dialog.ActiveDialogID() == commands.CommandsDialogID {
303 // If the commands dialog is already open, close it
304 return util.CmdHandler(dialogs.CloseDialogMsg{})
305 }
306 return util.CmdHandler(dialogs.OpenDialogMsg{
307 Model: commands.NewCommandDialog(a.selectedSessionID),
308 })
309 case key.Matches(msg, a.keyMap.Sessions):
310 if a.dialog.ActiveDialogID() == sessions.SessionsDialogID {
311 // If the sessions dialog is already open, close it
312 return util.CmdHandler(dialogs.CloseDialogMsg{})
313 }
314 var cmds []tea.Cmd
315 if a.dialog.ActiveDialogID() == commands.CommandsDialogID {
316 // If the commands dialog is open, close it first
317 cmds = append(cmds, util.CmdHandler(dialogs.CloseDialogMsg{}))
318 }
319 cmds = append(cmds,
320 func() tea.Msg {
321 allSessions, _ := a.app.Sessions.List(context.Background())
322 return dialogs.OpenDialogMsg{
323 Model: sessions.NewSessionDialogCmp(allSessions, a.selectedSessionID),
324 }
325 },
326 )
327 return tea.Sequence(cmds...)
328 // Page navigation
329 case key.Matches(msg, a.keyMap.Logs):
330 return a.moveToPage(logs.LogsPage)
331
332 default:
333 if a.dialog.HasDialogs() {
334 u, dialogCmd := a.dialog.Update(msg)
335 a.dialog = u.(dialogs.DialogCmp)
336 return dialogCmd
337 } else {
338 updated, cmd := a.pages[a.currentPage].Update(msg)
339 a.pages[a.currentPage] = updated.(util.Model)
340 return cmd
341 }
342 }
343}
344
345// moveToPage handles navigation between different pages in the application.
346func (a *appModel) moveToPage(pageID page.PageID) tea.Cmd {
347 if a.app.CoderAgent.IsBusy() {
348 // For now we don't move to any page if the agent is busy
349 return util.ReportWarn("Agent is busy, please wait...")
350 }
351
352 var cmds []tea.Cmd
353 if _, ok := a.loadedPages[pageID]; !ok {
354 cmd := a.pages[pageID].Init()
355 cmds = append(cmds, cmd)
356 a.loadedPages[pageID] = true
357 }
358 a.previousPage = a.currentPage
359 a.currentPage = pageID
360 if sizable, ok := a.pages[a.currentPage].(layout.Sizeable); ok {
361 cmd := sizable.SetSize(a.width, a.height)
362 cmds = append(cmds, cmd)
363 }
364
365 return tea.Batch(cmds...)
366}
367
368// View renders the complete application interface including pages, dialogs, and overlays.
369func (a *appModel) View() tea.View {
370 pageView := a.pages[a.currentPage].View()
371 components := []string{
372 pageView.String(),
373 }
374 components = append(components, a.status.View().String())
375
376 appView := lipgloss.JoinVertical(lipgloss.Top, components...)
377 layers := []*lipgloss.Layer{
378 lipgloss.NewLayer(appView),
379 }
380 if a.dialog.HasDialogs() {
381 layers = append(
382 layers,
383 a.dialog.GetLayers()...,
384 )
385 }
386
387 cursor := pageView.Cursor()
388 activeView := a.dialog.ActiveView()
389 if activeView != nil {
390 cursor = activeView.Cursor()
391 }
392
393 if a.completions.Open() && cursor != nil {
394 cmp := a.completions.View().String()
395 x, y := a.completions.Position()
396 layers = append(
397 layers,
398 lipgloss.NewLayer(cmp).X(x).Y(y),
399 )
400 }
401
402 canvas := lipgloss.NewCanvas(
403 layers...,
404 )
405
406 t := styles.CurrentTheme()
407 view := tea.NewView(canvas.Render())
408 view.SetBackgroundColor(t.BgBase)
409 view.SetCursor(cursor)
410 return view
411}
412
413// New creates and initializes a new TUI application model.
414func New(app *app.App) tea.Model {
415 startPage := chat.ChatPage
416 model := &appModel{
417 currentPage: startPage,
418 app: app,
419 status: status.NewStatusCmp(),
420 loadedPages: make(map[page.PageID]bool),
421 keyMap: DefaultKeyMap(),
422
423 pages: map[page.PageID]util.Model{
424 chat.ChatPage: chat.NewChatPage(app),
425 logs.LogsPage: logs.NewLogsPage(),
426 },
427
428 dialog: dialogs.NewDialogCmp(),
429 completions: completions.New(),
430 }
431
432 return model
433}