1package dialog
2
3import (
4 "os"
5 "strings"
6
7 "charm.land/bubbles/v2/help"
8 "charm.land/bubbles/v2/key"
9 "charm.land/bubbles/v2/spinner"
10 "charm.land/bubbles/v2/textinput"
11 tea "charm.land/bubbletea/v2"
12 "github.com/charmbracelet/crush/internal/commands"
13 "github.com/charmbracelet/crush/internal/config"
14 "github.com/charmbracelet/crush/internal/ui/common"
15 "github.com/charmbracelet/crush/internal/ui/list"
16 "github.com/charmbracelet/crush/internal/ui/styles"
17 uv "github.com/charmbracelet/ultraviolet"
18)
19
20// CommandsID is the identifier for the commands dialog.
21const CommandsID = "commands"
22
23// CommandType represents the type of commands being displayed.
24type CommandType uint
25
26// String returns the string representation of the CommandType.
27func (c CommandType) String() string { return []string{"System", "User", "MCP"}[c] }
28
29const (
30 sidebarCompactModeBreakpoint = 120
31)
32
33const (
34 SystemCommands CommandType = iota
35 UserCommands
36 MCPPrompts
37)
38
39// Commands represents a dialog that shows available commands.
40type Commands struct {
41 com *common.Common
42 keyMap struct {
43 Select,
44 UpDown,
45 Next,
46 Previous,
47 Tab,
48 ShiftTab,
49 Close key.Binding
50 }
51
52 sessionID string // can be empty for non-session-specific commands
53 selected CommandType
54
55 spinner spinner.Model
56 loading bool
57
58 help help.Model
59 input textinput.Model
60 list *list.FilterableList
61
62 windowWidth int
63
64 customCommands []commands.CustomCommand
65 mcpPrompts []commands.MCPPrompt
66}
67
68var _ Dialog = (*Commands)(nil)
69
70// NewCommands creates a new commands dialog.
71func NewCommands(com *common.Common, sessionID string, customCommands []commands.CustomCommand, mcpPrompts []commands.MCPPrompt) (*Commands, error) {
72 c := &Commands{
73 com: com,
74 selected: SystemCommands,
75 sessionID: sessionID,
76 customCommands: customCommands,
77 mcpPrompts: mcpPrompts,
78 }
79
80 help := help.New()
81 help.Styles = com.Styles.DialogHelpStyles()
82
83 c.help = help
84
85 c.list = list.NewFilterableList()
86 c.list.Focus()
87 c.list.SetSelected(0)
88
89 c.input = textinput.New()
90 c.input.SetVirtualCursor(false)
91 c.input.Placeholder = "Type to filter"
92 c.input.SetStyles(com.Styles.TextInput)
93 c.input.Focus()
94
95 c.keyMap.Select = key.NewBinding(
96 key.WithKeys("enter", "ctrl+y"),
97 key.WithHelp("enter", "confirm"),
98 )
99 c.keyMap.UpDown = key.NewBinding(
100 key.WithKeys("up", "down"),
101 key.WithHelp("↑/↓", "choose"),
102 )
103 c.keyMap.Next = key.NewBinding(
104 key.WithKeys("down"),
105 key.WithHelp("↓", "next item"),
106 )
107 c.keyMap.Previous = key.NewBinding(
108 key.WithKeys("up", "ctrl+p"),
109 key.WithHelp("↑", "previous item"),
110 )
111 c.keyMap.Tab = key.NewBinding(
112 key.WithKeys("tab"),
113 key.WithHelp("tab", "switch selection"),
114 )
115 c.keyMap.ShiftTab = key.NewBinding(
116 key.WithKeys("shift+tab"),
117 key.WithHelp("shift+tab", "switch selection prev"),
118 )
119 closeKey := CloseKey
120 closeKey.SetHelp("esc", "cancel")
121 c.keyMap.Close = closeKey
122
123 // Set initial commands
124 c.setCommandItems(c.selected)
125
126 s := spinner.New()
127 s.Spinner = spinner.Dot
128 s.Style = com.Styles.Dialog.Spinner
129 c.spinner = s
130
131 return c, nil
132}
133
134// ID implements Dialog.
135func (c *Commands) ID() string {
136 return CommandsID
137}
138
139// HandleMsg implements [Dialog].
140func (c *Commands) HandleMsg(msg tea.Msg) Action {
141 switch msg := msg.(type) {
142 case spinner.TickMsg:
143 if c.loading {
144 var cmd tea.Cmd
145 c.spinner, cmd = c.spinner.Update(msg)
146 return ActionCmd{Cmd: cmd}
147 }
148 case tea.KeyPressMsg:
149 switch {
150 case key.Matches(msg, c.keyMap.Close):
151 return ActionClose{}
152 case key.Matches(msg, c.keyMap.Previous):
153 c.list.Focus()
154 if c.list.IsSelectedFirst() {
155 c.list.SelectLast()
156 c.list.ScrollToBottom()
157 break
158 }
159 c.list.SelectPrev()
160 c.list.ScrollToSelected()
161 case key.Matches(msg, c.keyMap.Next):
162 c.list.Focus()
163 if c.list.IsSelectedLast() {
164 c.list.SelectFirst()
165 c.list.ScrollToTop()
166 break
167 }
168 c.list.SelectNext()
169 c.list.ScrollToSelected()
170 case key.Matches(msg, c.keyMap.Select):
171 if selectedItem := c.list.SelectedItem(); selectedItem != nil {
172 if item, ok := selectedItem.(*CommandItem); ok && item != nil {
173 return item.Action()
174 }
175 }
176 case key.Matches(msg, c.keyMap.Tab):
177 if len(c.customCommands) > 0 || len(c.mcpPrompts) > 0 {
178 c.selected = c.nextCommandType()
179 c.setCommandItems(c.selected)
180 }
181 case key.Matches(msg, c.keyMap.ShiftTab):
182 if len(c.customCommands) > 0 || len(c.mcpPrompts) > 0 {
183 c.selected = c.previousCommandType()
184 c.setCommandItems(c.selected)
185 }
186 default:
187 var cmd tea.Cmd
188 for _, item := range c.list.FilteredItems() {
189 if item, ok := item.(*CommandItem); ok && item != nil {
190 if msg.String() == item.Shortcut() {
191 return item.Action()
192 }
193 }
194 }
195 c.input, cmd = c.input.Update(msg)
196 value := c.input.Value()
197 c.list.SetFilter(value)
198 c.list.ScrollToTop()
199 c.list.SetSelected(0)
200 return ActionCmd{cmd}
201 }
202 }
203 return nil
204}
205
206// Cursor returns the cursor position relative to the dialog.
207func (c *Commands) Cursor() *tea.Cursor {
208 return InputCursor(c.com.Styles, c.input.Cursor())
209}
210
211// commandsRadioView generates the command type selector radio buttons.
212func commandsRadioView(sty *styles.Styles, selected CommandType, hasUserCmds bool, hasMCPPrompts bool) string {
213 if !hasUserCmds && !hasMCPPrompts {
214 return ""
215 }
216
217 selectedFn := func(t CommandType) string {
218 if t == selected {
219 return sty.RadioOn.Padding(0, 1).Render() + sty.HalfMuted.Render(t.String())
220 }
221 return sty.RadioOff.Padding(0, 1).Render() + sty.HalfMuted.Render(t.String())
222 }
223
224 parts := []string{
225 selectedFn(SystemCommands),
226 }
227
228 if hasUserCmds {
229 parts = append(parts, selectedFn(UserCommands))
230 }
231 if hasMCPPrompts {
232 parts = append(parts, selectedFn(MCPPrompts))
233 }
234
235 return strings.Join(parts, " ")
236}
237
238// Draw implements [Dialog].
239func (c *Commands) Draw(scr uv.Screen, area uv.Rectangle) *tea.Cursor {
240 t := c.com.Styles
241 width := max(0, min(defaultDialogMaxWidth, area.Dx()-t.Dialog.View.GetHorizontalBorderSize()))
242 height := max(0, min(defaultDialogHeight, area.Dy()-t.Dialog.View.GetVerticalBorderSize()))
243 if area.Dx() != c.windowWidth && c.selected == SystemCommands {
244 c.windowWidth = area.Dx()
245 // since some items in the list depend on width (e.g. toggle sidebar command),
246 // we need to reset the command items when width changes
247 c.setCommandItems(c.selected)
248 }
249
250 innerWidth := width - c.com.Styles.Dialog.View.GetHorizontalFrameSize()
251 heightOffset := t.Dialog.Title.GetVerticalFrameSize() + titleContentHeight +
252 t.Dialog.InputPrompt.GetVerticalFrameSize() + inputContentHeight +
253 t.Dialog.HelpView.GetVerticalFrameSize() +
254 t.Dialog.View.GetVerticalFrameSize()
255
256 c.input.SetWidth(max(0, innerWidth-t.Dialog.InputPrompt.GetHorizontalFrameSize()-1)) // (1) cursor padding
257
258 c.list.SetSize(innerWidth, height-heightOffset)
259 c.help.SetWidth(innerWidth)
260
261 rc := NewRenderContext(t, width)
262 rc.Title = "Commands"
263 rc.TitleInfo = commandsRadioView(t, c.selected, len(c.customCommands) > 0, len(c.mcpPrompts) > 0)
264 inputView := t.Dialog.InputPrompt.Render(c.input.View())
265 rc.AddPart(inputView)
266 listView := t.Dialog.List.Height(c.list.Height()).Render(c.list.Render())
267 rc.AddPart(listView)
268 rc.Help = c.help.View(c)
269
270 if c.loading {
271 rc.Help = c.spinner.View() + " Generating Prompt..."
272 }
273
274 view := rc.Render()
275
276 cur := c.Cursor()
277 DrawCenterCursor(scr, area, view, cur)
278 return cur
279}
280
281// ShortHelp implements [help.KeyMap].
282func (c *Commands) ShortHelp() []key.Binding {
283 return []key.Binding{
284 c.keyMap.Tab,
285 c.keyMap.UpDown,
286 c.keyMap.Select,
287 c.keyMap.Close,
288 }
289}
290
291// FullHelp implements [help.KeyMap].
292func (c *Commands) FullHelp() [][]key.Binding {
293 return [][]key.Binding{
294 {c.keyMap.Select, c.keyMap.Next, c.keyMap.Previous, c.keyMap.Tab},
295 {c.keyMap.Close},
296 }
297}
298
299// nextCommandType returns the next command type in the cycle.
300func (c *Commands) nextCommandType() CommandType {
301 switch c.selected {
302 case SystemCommands:
303 if len(c.customCommands) > 0 {
304 return UserCommands
305 }
306 if len(c.mcpPrompts) > 0 {
307 return MCPPrompts
308 }
309 fallthrough
310 case UserCommands:
311 if len(c.mcpPrompts) > 0 {
312 return MCPPrompts
313 }
314 fallthrough
315 case MCPPrompts:
316 return SystemCommands
317 default:
318 return SystemCommands
319 }
320}
321
322// previousCommandType returns the previous command type in the cycle.
323func (c *Commands) previousCommandType() CommandType {
324 switch c.selected {
325 case SystemCommands:
326 if len(c.mcpPrompts) > 0 {
327 return MCPPrompts
328 }
329 if len(c.customCommands) > 0 {
330 return UserCommands
331 }
332 return SystemCommands
333 case UserCommands:
334 return SystemCommands
335 case MCPPrompts:
336 if len(c.customCommands) > 0 {
337 return UserCommands
338 }
339 return SystemCommands
340 default:
341 return SystemCommands
342 }
343}
344
345// setCommandItems sets the command items based on the specified command type.
346func (c *Commands) setCommandItems(commandType CommandType) {
347 c.selected = commandType
348
349 commandItems := []list.FilterableItem{}
350 switch c.selected {
351 case SystemCommands:
352 for _, cmd := range c.defaultCommands() {
353 commandItems = append(commandItems, cmd)
354 }
355 case UserCommands:
356 for _, cmd := range c.customCommands {
357 action := ActionRunCustomCommand{
358 Content: cmd.Content,
359 Arguments: cmd.Arguments,
360 }
361 commandItems = append(commandItems, NewCommandItem(c.com.Styles, "custom_"+cmd.ID, cmd.Name, "", action))
362 }
363 case MCPPrompts:
364 for _, cmd := range c.mcpPrompts {
365 action := ActionRunMCPPrompt{
366 Title: cmd.Title,
367 Description: cmd.Description,
368 PromptID: cmd.PromptID,
369 ClientID: cmd.ClientID,
370 Arguments: cmd.Arguments,
371 }
372 commandItems = append(commandItems, NewCommandItem(c.com.Styles, "mcp_"+cmd.ID, cmd.PromptID, "", action))
373 }
374 }
375
376 c.list.SetItems(commandItems...)
377 c.list.SetFilter("")
378 c.list.ScrollToTop()
379 c.list.SetSelected(0)
380 c.input.SetValue("")
381}
382
383// defaultCommands returns the list of default system commands.
384func (c *Commands) defaultCommands() []*CommandItem {
385 commands := []*CommandItem{
386 NewCommandItem(c.com.Styles, "new_session", "New Session", "ctrl+n", ActionNewSession{}),
387 NewCommandItem(c.com.Styles, "switch_session", "Sessions", "ctrl+s", ActionOpenDialog{SessionsID}),
388 NewCommandItem(c.com.Styles, "switch_model", "Switch Model", "ctrl+l", ActionOpenDialog{ModelsID}),
389 }
390
391 // Only show compact command if there's an active session
392 if c.sessionID != "" {
393 commands = append(commands, NewCommandItem(c.com.Styles, "summarize", "Summarize Session", "", ActionSummarize{SessionID: c.sessionID}))
394 }
395
396 // Add reasoning toggle for models that support it
397 cfg := c.com.Config()
398 if agentCfg, ok := cfg.Agents[config.AgentCoder]; ok {
399 providerCfg := cfg.GetProviderForModel(agentCfg.Model)
400 model := cfg.GetModelByType(agentCfg.Model)
401 if providerCfg != nil && model != nil && model.CanReason {
402 selectedModel := cfg.Models[agentCfg.Model]
403
404 // Anthropic models: thinking toggle
405 if model.CanReason && len(model.ReasoningLevels) == 0 {
406 status := "Enable"
407 if selectedModel.Think {
408 status = "Disable"
409 }
410 commands = append(commands, NewCommandItem(c.com.Styles, "toggle_thinking", status+" Thinking Mode", "", ActionToggleThinking{}))
411 }
412
413 // OpenAI models: reasoning effort dialog
414 if len(model.ReasoningLevels) > 0 {
415 commands = append(commands, NewCommandItem(c.com.Styles, "select_reasoning_effort", "Select Reasoning Effort", "", ActionOpenDialog{
416 DialogID: ReasoningID,
417 }))
418 }
419 }
420 }
421 // Only show toggle compact mode command if window width is larger than compact breakpoint (120)
422 if c.windowWidth >= sidebarCompactModeBreakpoint && c.sessionID != "" {
423 commands = append(commands, NewCommandItem(c.com.Styles, "toggle_sidebar", "Toggle Sidebar", "", ActionToggleCompactMode{}))
424 }
425 if c.sessionID != "" {
426 cfg := c.com.Config()
427 agentCfg := cfg.Agents[config.AgentCoder]
428 model := cfg.GetModelByType(agentCfg.Model)
429 if model != nil && model.SupportsImages {
430 commands = append(commands, NewCommandItem(c.com.Styles, "file_picker", "Open File Picker", "ctrl+f", ActionOpenDialog{
431 // TODO: Pass in the file picker dialog id
432 }))
433 }
434 }
435
436 // Add external editor command if $EDITOR is available
437 // TODO: Use [tea.EnvMsg] to get environment variable instead of os.Getenv
438 if os.Getenv("EDITOR") != "" {
439 commands = append(commands, NewCommandItem(c.com.Styles, "open_external_editor", "Open External Editor", "ctrl+o", ActionExternalEditor{}))
440 }
441
442 return append(commands,
443 NewCommandItem(c.com.Styles, "toggle_yolo", "Toggle Yolo Mode", "", ActionToggleYoloMode{}),
444 NewCommandItem(c.com.Styles, "toggle_help", "Toggle Help", "ctrl+g", ActionToggleHelp{}),
445 NewCommandItem(c.com.Styles, "init", "Initialize Project", "", ActionInitializeProject{}),
446 NewCommandItem(c.com.Styles, "quit", "Quit", "ctrl+c", tea.QuitMsg{}),
447 )
448}
449
450// SetCustomCommands sets the custom commands and refreshes the view if user commands are currently displayed.
451func (c *Commands) SetCustomCommands(customCommands []commands.CustomCommand) {
452 c.customCommands = customCommands
453 if c.selected == UserCommands {
454 c.setCommandItems(c.selected)
455 }
456}
457
458// SetMCPPrompts sets the MCP prompts and refreshes the view if MCP prompts are currently displayed.
459func (c *Commands) SetMCPPrompts(mcpPrompts []commands.MCPPrompt) {
460 c.mcpPrompts = mcpPrompts
461 if c.selected == MCPPrompts {
462 c.setCommandItems(c.selected)
463 }
464}
465
466// StartLoading implements [LoadingDialog].
467func (a *Commands) StartLoading() tea.Cmd {
468 if a.loading {
469 return nil
470 }
471 a.loading = true
472 return a.spinner.Tick
473}
474
475// StopLoading implements [LoadingDialog].
476func (a *Commands) StopLoading() {
477 a.loading = false
478}