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