1package permissions
2
3import (
4 "fmt"
5 "strings"
6
7 "github.com/charmbracelet/bubbles/v2/key"
8 "github.com/charmbracelet/bubbles/v2/viewport"
9 tea "github.com/charmbracelet/bubbletea/v2"
10 "github.com/charmbracelet/crush/internal/diff"
11 "github.com/charmbracelet/crush/internal/fileutil"
12 "github.com/charmbracelet/crush/internal/llm/tools"
13 "github.com/charmbracelet/crush/internal/permission"
14 "github.com/charmbracelet/crush/internal/tui/components/core"
15 "github.com/charmbracelet/crush/internal/tui/components/dialogs"
16 "github.com/charmbracelet/crush/internal/tui/styles"
17 "github.com/charmbracelet/crush/internal/tui/util"
18 "github.com/charmbracelet/lipgloss/v2"
19 "github.com/charmbracelet/x/ansi"
20)
21
22type PermissionAction string
23
24// Permission responses
25const (
26 PermissionAllow PermissionAction = "allow"
27 PermissionAllowForSession PermissionAction = "allow_session"
28 PermissionDeny PermissionAction = "deny"
29
30 PermissionsDialogID dialogs.DialogID = "permissions"
31)
32
33// PermissionResponseMsg represents the user's response to a permission request
34type PermissionResponseMsg struct {
35 Permission permission.PermissionRequest
36 Action PermissionAction
37}
38
39// PermissionDialogCmp interface for permission dialog component
40type PermissionDialogCmp interface {
41 dialogs.DialogModel
42}
43
44// permissionDialogCmp is the implementation of PermissionDialog
45type permissionDialogCmp struct {
46 wWidth int
47 wHeight int
48 width int
49 height int
50 permission permission.PermissionRequest
51 contentViewPort viewport.Model
52 selectedOption int // 0: Allow, 1: Allow for session, 2: Deny
53
54 keyMap KeyMap
55}
56
57func NewPermissionDialogCmp(permission permission.PermissionRequest) PermissionDialogCmp {
58 // Create viewport for content
59 contentViewport := viewport.New()
60 return &permissionDialogCmp{
61 contentViewPort: contentViewport,
62 selectedOption: 0, // Default to "Allow"
63 permission: permission,
64 keyMap: DefaultKeyMap(),
65 }
66}
67
68func (p *permissionDialogCmp) Init() tea.Cmd {
69 return p.contentViewPort.Init()
70}
71
72func (p *permissionDialogCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
73 var cmds []tea.Cmd
74
75 switch msg := msg.(type) {
76 case tea.WindowSizeMsg:
77 p.wWidth = msg.Width
78 p.wHeight = msg.Height
79 cmd := p.SetSize()
80 cmds = append(cmds, cmd)
81 case tea.KeyPressMsg:
82 switch {
83 case key.Matches(msg, p.keyMap.Right) || key.Matches(msg, p.keyMap.Tab):
84 p.selectedOption = (p.selectedOption + 1) % 3
85 return p, nil
86 case key.Matches(msg, p.keyMap.Left):
87 p.selectedOption = (p.selectedOption + 2) % 3
88 case key.Matches(msg, p.keyMap.Select):
89 return p, p.selectCurrentOption()
90 case key.Matches(msg, p.keyMap.Allow):
91 return p, tea.Batch(
92 util.CmdHandler(dialogs.CloseDialogMsg{}),
93 util.CmdHandler(PermissionResponseMsg{Action: PermissionAllow, Permission: p.permission}),
94 )
95 case key.Matches(msg, p.keyMap.AllowSession):
96 return p, tea.Batch(
97 util.CmdHandler(dialogs.CloseDialogMsg{}),
98 util.CmdHandler(PermissionResponseMsg{Action: PermissionAllowForSession, Permission: p.permission}),
99 )
100 case key.Matches(msg, p.keyMap.Deny):
101 return p, tea.Batch(
102 util.CmdHandler(dialogs.CloseDialogMsg{}),
103 util.CmdHandler(PermissionResponseMsg{Action: PermissionDeny, Permission: p.permission}),
104 )
105 default:
106 // Pass other keys to viewport
107 viewPort, cmd := p.contentViewPort.Update(msg)
108 p.contentViewPort = viewPort
109 cmds = append(cmds, cmd)
110 }
111 }
112
113 return p, tea.Batch(cmds...)
114}
115
116func (p *permissionDialogCmp) selectCurrentOption() tea.Cmd {
117 var action PermissionAction
118
119 switch p.selectedOption {
120 case 0:
121 action = PermissionAllow
122 case 1:
123 action = PermissionAllowForSession
124 case 2:
125 action = PermissionDeny
126 }
127
128 return tea.Batch(
129 util.CmdHandler(PermissionResponseMsg{Action: action, Permission: p.permission}),
130 util.CmdHandler(dialogs.CloseDialogMsg{}),
131 )
132}
133
134func (p *permissionDialogCmp) renderButtons() string {
135 t := styles.CurrentTheme()
136 baseStyle := t.S().Base
137
138 buttons := []core.ButtonOpts{
139 {
140 Text: "Allow",
141 UnderlineIndex: 0, // "A"
142 Selected: p.selectedOption == 0,
143 },
144 {
145 Text: "Allow for Session",
146 UnderlineIndex: 10, // "S" in "Session"
147 Selected: p.selectedOption == 1,
148 },
149 {
150 Text: "Deny",
151 UnderlineIndex: 0, // "D"
152 Selected: p.selectedOption == 2,
153 },
154 }
155
156 content := core.SelectableButtons(buttons, " ")
157
158 return baseStyle.AlignHorizontal(lipgloss.Right).Width(p.width - 4).Render(content)
159}
160
161func (p *permissionDialogCmp) renderHeader() string {
162 t := styles.CurrentTheme()
163 baseStyle := t.S().Base
164
165 toolKey := t.S().Muted.Render("Tool")
166 toolValue := t.S().Text.
167 Width(p.width - lipgloss.Width(toolKey)).
168 Render(fmt.Sprintf(" %s", p.permission.ToolName))
169
170 pathKey := t.S().Muted.Render("Path")
171 pathValue := t.S().Text.
172 Width(p.width - lipgloss.Width(pathKey)).
173 Render(fmt.Sprintf(" %s", fileutil.PrettyPath(p.permission.Path)))
174
175 headerParts := []string{
176 lipgloss.JoinHorizontal(
177 lipgloss.Left,
178 toolKey,
179 toolValue,
180 ),
181 baseStyle.Render(strings.Repeat(" ", p.width)),
182 lipgloss.JoinHorizontal(
183 lipgloss.Left,
184 pathKey,
185 pathValue,
186 ),
187 baseStyle.Render(strings.Repeat(" ", p.width)),
188 }
189
190 // Add tool-specific header information
191 switch p.permission.ToolName {
192 case tools.BashToolName:
193 headerParts = append(headerParts, t.S().Muted.Width(p.width).Render("Command"))
194 case tools.EditToolName:
195 params := p.permission.Params.(tools.EditPermissionsParams)
196 fileKey := t.S().Muted.Render("File")
197 filePath := t.S().Text.
198 Width(p.width - lipgloss.Width(fileKey)).
199 Render(fmt.Sprintf(" %s", fileutil.PrettyPath(params.FilePath)))
200 headerParts = append(headerParts,
201 lipgloss.JoinHorizontal(
202 lipgloss.Left,
203 fileKey,
204 filePath,
205 ),
206 baseStyle.Render(strings.Repeat(" ", p.width)),
207 )
208
209 case tools.WriteToolName:
210 params := p.permission.Params.(tools.WritePermissionsParams)
211 fileKey := t.S().Muted.Render("File")
212 filePath := t.S().Text.
213 Width(p.width - lipgloss.Width(fileKey)).
214 Render(fmt.Sprintf(" %s", fileutil.PrettyPath(params.FilePath)))
215 headerParts = append(headerParts,
216 lipgloss.JoinHorizontal(
217 lipgloss.Left,
218 fileKey,
219 filePath,
220 ),
221 baseStyle.Render(strings.Repeat(" ", p.width)),
222 )
223 case tools.FetchToolName:
224 headerParts = append(headerParts, t.S().Muted.Width(p.width).Bold(true).Render("URL"))
225 }
226
227 return baseStyle.Render(lipgloss.JoinVertical(lipgloss.Left, headerParts...))
228}
229
230func (p *permissionDialogCmp) renderBashContent() string {
231 t := styles.CurrentTheme()
232 baseStyle := t.S().Base.Background(t.BgSubtle)
233 if pr, ok := p.permission.Params.(tools.BashPermissionsParams); ok {
234 content := pr.Command
235 t := styles.CurrentTheme()
236 content = strings.TrimSpace(content)
237 content = "\n" + content + "\n"
238 lines := strings.Split(content, "\n")
239
240 width := p.width - 4
241 var out []string
242 for _, ln := range lines {
243 ln = " " + ln // left padding
244 if len(ln) > width {
245 ln = ansi.Truncate(ln, width, "…")
246 }
247 out = append(out, t.S().Muted.
248 Width(width).
249 Foreground(t.FgBase).
250 Background(t.BgSubtle).
251 Render(ln))
252 }
253
254 // Use the cache for markdown rendering
255 renderedContent := strings.Join(out, "\n")
256 finalContent := baseStyle.
257 Width(p.contentViewPort.Width()).
258 Render(renderedContent)
259
260 contentHeight := min(p.height-9, lipgloss.Height(finalContent))
261 p.contentViewPort.SetHeight(contentHeight)
262 p.contentViewPort.SetContent(finalContent)
263 return p.styleViewport()
264 }
265 return ""
266}
267
268func (p *permissionDialogCmp) renderEditContent() string {
269 if pr, ok := p.permission.Params.(tools.EditPermissionsParams); ok {
270 diff := p.GetOrSetDiff(p.permission.ID, func() (string, error) {
271 return diff.FormatDiff(pr.Diff, diff.WithTotalWidth(p.contentViewPort.Width()))
272 })
273
274 contentHeight := min(p.height-9, lipgloss.Height(diff))
275 p.contentViewPort.SetHeight(contentHeight)
276 p.contentViewPort.SetContent(diff)
277 return p.styleViewport()
278 }
279 return ""
280}
281
282func (p *permissionDialogCmp) renderWriteContent() string {
283 if pr, ok := p.permission.Params.(tools.WritePermissionsParams); ok {
284 // Use the cache for diff rendering
285 diff := p.GetOrSetDiff(p.permission.ID, func() (string, error) {
286 return diff.FormatDiff(pr.Diff, diff.WithTotalWidth(p.contentViewPort.Width()))
287 })
288
289 contentHeight := min(p.height-9, lipgloss.Height(diff))
290 p.contentViewPort.SetHeight(contentHeight)
291 p.contentViewPort.SetContent(diff)
292 return p.styleViewport()
293 }
294 return ""
295}
296
297func (p *permissionDialogCmp) renderFetchContent() string {
298 t := styles.CurrentTheme()
299 baseStyle := t.S().Base.Background(t.BgSubtle)
300 if pr, ok := p.permission.Params.(tools.FetchPermissionsParams); ok {
301 content := fmt.Sprintf("```bash\n%s\n```", pr.URL)
302
303 // Use the cache for markdown rendering
304 renderedContent := p.GetOrSetMarkdown(p.permission.ID, func() (string, error) {
305 r := styles.GetMarkdownRenderer(p.width - 4)
306 s, err := r.Render(content)
307 return s, err
308 })
309
310 finalContent := baseStyle.
311 Width(p.contentViewPort.Width()).
312 Render(renderedContent)
313
314 contentHeight := min(p.height-9, lipgloss.Height(finalContent))
315 p.contentViewPort.SetHeight(contentHeight)
316 p.contentViewPort.SetContent(finalContent)
317 return p.styleViewport()
318 }
319 return ""
320}
321
322func (p *permissionDialogCmp) renderDefaultContent() string {
323 t := styles.CurrentTheme()
324 baseStyle := t.S().Base.Background(t.BgSubtle)
325
326 content := p.permission.Description
327
328 // Use the cache for markdown rendering
329 renderedContent := p.GetOrSetMarkdown(p.permission.ID, func() (string, error) {
330 r := styles.GetMarkdownRenderer(p.width - 4)
331 s, err := r.Render(content)
332 return s, err
333 })
334
335 finalContent := baseStyle.
336 Width(p.contentViewPort.Width()).
337 Render(renderedContent)
338 p.contentViewPort.SetContent(finalContent)
339
340 if renderedContent == "" {
341 return ""
342 }
343
344 return p.styleViewport()
345}
346
347func (p *permissionDialogCmp) styleViewport() string {
348 t := styles.CurrentTheme()
349 return t.S().Base.Render(p.contentViewPort.View())
350}
351
352func (p *permissionDialogCmp) render() string {
353 t := styles.CurrentTheme()
354 baseStyle := t.S().Base
355 title := core.Title("Permission Required", p.width-4)
356 // Render header
357 headerContent := p.renderHeader()
358 // Render buttons
359 buttons := p.renderButtons()
360
361 p.contentViewPort.SetWidth(p.width - 4)
362
363 // Render content based on tool type
364 var contentFinal string
365 switch p.permission.ToolName {
366 case tools.BashToolName:
367 contentFinal = p.renderBashContent()
368 case tools.EditToolName:
369 contentFinal = p.renderEditContent()
370 case tools.WriteToolName:
371 contentFinal = p.renderWriteContent()
372 case tools.FetchToolName:
373 contentFinal = p.renderFetchContent()
374 default:
375 contentFinal = p.renderDefaultContent()
376 }
377 // Calculate content height dynamically based on window size
378
379 content := lipgloss.JoinVertical(
380 lipgloss.Top,
381 title,
382 "",
383 headerContent,
384 contentFinal,
385 "",
386 buttons,
387 "",
388 )
389
390 return baseStyle.
391 Padding(0, 1).
392 Border(lipgloss.RoundedBorder()).
393 BorderForeground(t.BorderFocus).
394 Width(p.width).
395 Render(
396 content,
397 )
398}
399
400func (p *permissionDialogCmp) View() tea.View {
401 return tea.NewView(p.render())
402}
403
404func (p *permissionDialogCmp) SetSize() tea.Cmd {
405 if p.permission.ID == "" {
406 return nil
407 }
408 switch p.permission.ToolName {
409 case tools.BashToolName:
410 p.width = int(float64(p.wWidth) * 0.4)
411 p.height = int(float64(p.wHeight) * 0.3)
412 case tools.EditToolName:
413 p.width = int(float64(p.wWidth) * 0.8)
414 p.height = int(float64(p.wHeight) * 0.8)
415 case tools.WriteToolName:
416 p.width = int(float64(p.wWidth) * 0.8)
417 p.height = int(float64(p.wHeight) * 0.8)
418 case tools.FetchToolName:
419 p.width = int(float64(p.wWidth) * 0.4)
420 p.height = int(float64(p.wHeight) * 0.3)
421 default:
422 p.width = int(float64(p.wWidth) * 0.7)
423 p.height = int(float64(p.wHeight) * 0.5)
424 }
425 return nil
426}
427
428func (c *permissionDialogCmp) GetOrSetDiff(key string, generator func() (string, error)) string {
429 content, err := generator()
430 if err != nil {
431 return fmt.Sprintf("Error formatting diff: %v", err)
432 }
433 return content
434}
435
436func (c *permissionDialogCmp) GetOrSetMarkdown(key string, generator func() (string, error)) string {
437 content, err := generator()
438 if err != nil {
439 return fmt.Sprintf("Error rendering markdown: %v", err)
440 }
441
442 return content
443}
444
445// ID implements PermissionDialogCmp.
446func (p *permissionDialogCmp) ID() dialogs.DialogID {
447 return PermissionsDialogID
448}
449
450// Position implements PermissionDialogCmp.
451func (p *permissionDialogCmp) Position() (int, int) {
452 row := (p.wHeight / 2) - 2 // Just a bit above the center
453 row -= p.height / 2
454 col := p.wWidth / 2
455 col -= p.width / 2
456 return row, col
457}