summaryrefslogtreecommitdiffhomepage
path: root/packages/tui/internal/components/dialog/permission.go
blob: bb71fc35d01d636b585240a3845d3d7c90df3ca9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
package dialog

import (
	"fmt"
	"github.com/charmbracelet/bubbles/key"
	"github.com/charmbracelet/bubbles/viewport"
	tea "github.com/charmbracelet/bubbletea"
	"github.com/charmbracelet/lipgloss"
	"github.com/sst/opencode/internal/layout"
	"github.com/sst/opencode/internal/styles"
	"github.com/sst/opencode/internal/theme"
	"github.com/sst/opencode/internal/util"
	"strings"
)

type PermissionAction string

// Permission responses
const (
	PermissionAllow           PermissionAction = "allow"
	PermissionAllowForSession PermissionAction = "allow_session"
	PermissionDeny            PermissionAction = "deny"
)

// PermissionResponseMsg represents the user's response to a permission request
type PermissionResponseMsg struct {
	// Permission permission.PermissionRequest
	Action PermissionAction
}

// PermissionDialogCmp interface for permission dialog component
type PermissionDialogCmp interface {
	tea.Model
	layout.Bindings
	// SetPermissions(permission permission.PermissionRequest) tea.Cmd
}

type permissionsMapping struct {
	Left         key.Binding
	Right        key.Binding
	EnterSpace   key.Binding
	Allow        key.Binding
	AllowSession key.Binding
	Deny         key.Binding
	Tab          key.Binding
}

var permissionsKeys = permissionsMapping{
	Left: key.NewBinding(
		key.WithKeys("left"),
		key.WithHelp("←", "switch options"),
	),
	Right: key.NewBinding(
		key.WithKeys("right"),
		key.WithHelp("→", "switch options"),
	),
	EnterSpace: key.NewBinding(
		key.WithKeys("enter", " "),
		key.WithHelp("enter/space", "confirm"),
	),
	Allow: key.NewBinding(
		key.WithKeys("a"),
		key.WithHelp("a", "allow"),
	),
	AllowSession: key.NewBinding(
		key.WithKeys("s"),
		key.WithHelp("s", "allow for session"),
	),
	Deny: key.NewBinding(
		key.WithKeys("d"),
		key.WithHelp("d", "deny"),
	),
	Tab: key.NewBinding(
		key.WithKeys("tab"),
		key.WithHelp("tab", "switch options"),
	),
}

// permissionDialogCmp is the implementation of PermissionDialog
type permissionDialogCmp struct {
	width  int
	height int
	// permission      permission.PermissionRequest
	windowSize      tea.WindowSizeMsg
	contentViewPort viewport.Model
	selectedOption  int // 0: Allow, 1: Allow for session, 2: Deny

	diffCache     map[string]string
	markdownCache map[string]string
}

func (p *permissionDialogCmp) Init() tea.Cmd {
	return p.contentViewPort.Init()
}

func (p *permissionDialogCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
	var cmds []tea.Cmd

	switch msg := msg.(type) {
	case tea.WindowSizeMsg:
		p.windowSize = msg
		cmd := p.SetSize()
		cmds = append(cmds, cmd)
		p.markdownCache = make(map[string]string)
		p.diffCache = make(map[string]string)
		// case tea.KeyMsg:
		// 	switch {
		// 	case key.Matches(msg, permissionsKeys.Right) || key.Matches(msg, permissionsKeys.Tab):
		// 		p.selectedOption = (p.selectedOption + 1) % 3
		// 		return p, nil
		// 	case key.Matches(msg, permissionsKeys.Left):
		// 		p.selectedOption = (p.selectedOption + 2) % 3
		// 	case key.Matches(msg, permissionsKeys.EnterSpace):
		// 		return p, p.selectCurrentOption()
		// 	case key.Matches(msg, permissionsKeys.Allow):
		// 		return p, util.CmdHandler(PermissionResponseMsg{Action: PermissionAllow, Permission: p.permission})
		// 	case key.Matches(msg, permissionsKeys.AllowSession):
		// 		return p, util.CmdHandler(PermissionResponseMsg{Action: PermissionAllowForSession, Permission: p.permission})
		// 	case key.Matches(msg, permissionsKeys.Deny):
		// 		return p, util.CmdHandler(PermissionResponseMsg{Action: PermissionDeny, Permission: p.permission})
		// 	default:
		// 		// Pass other keys to viewport
		// 		viewPort, cmd := p.contentViewPort.Update(msg)
		// 		p.contentViewPort = viewPort
		// 		cmds = append(cmds, cmd)
		// 	}
	}

	return p, tea.Batch(cmds...)
}

func (p *permissionDialogCmp) selectCurrentOption() tea.Cmd {
	var action PermissionAction

	switch p.selectedOption {
	case 0:
		action = PermissionAllow
	case 1:
		action = PermissionAllowForSession
	case 2:
		action = PermissionDeny
	}

	return util.CmdHandler(PermissionResponseMsg{Action: action}) // , Permission: p.permission})
}

func (p *permissionDialogCmp) renderButtons() string {
	t := theme.CurrentTheme()
	baseStyle := styles.BaseStyle()

	allowStyle := baseStyle
	allowSessionStyle := baseStyle
	denyStyle := baseStyle
	spacerStyle := baseStyle.Background(t.Background())

	// Style the selected button
	switch p.selectedOption {
	case 0:
		allowStyle = allowStyle.Background(t.Primary()).Foreground(t.Background())
		allowSessionStyle = allowSessionStyle.Background(t.Background()).Foreground(t.Primary())
		denyStyle = denyStyle.Background(t.Background()).Foreground(t.Primary())
	case 1:
		allowStyle = allowStyle.Background(t.Background()).Foreground(t.Primary())
		allowSessionStyle = allowSessionStyle.Background(t.Primary()).Foreground(t.Background())
		denyStyle = denyStyle.Background(t.Background()).Foreground(t.Primary())
	case 2:
		allowStyle = allowStyle.Background(t.Background()).Foreground(t.Primary())
		allowSessionStyle = allowSessionStyle.Background(t.Background()).Foreground(t.Primary())
		denyStyle = denyStyle.Background(t.Primary()).Foreground(t.Background())
	}

	allowButton := allowStyle.Padding(0, 1).Render("Allow (a)")
	allowSessionButton := allowSessionStyle.Padding(0, 1).Render("Allow for session (s)")
	denyButton := denyStyle.Padding(0, 1).Render("Deny (d)")

	content := lipgloss.JoinHorizontal(
		lipgloss.Left,
		allowButton,
		spacerStyle.Render("  "),
		allowSessionButton,
		spacerStyle.Render("  "),
		denyButton,
		spacerStyle.Render("  "),
	)

	remainingWidth := p.width - lipgloss.Width(content)
	if remainingWidth > 0 {
		content = spacerStyle.Render(strings.Repeat(" ", remainingWidth)) + content
	}
	return content
}

func (p *permissionDialogCmp) renderHeader() string {
	return "NOT IMPLEMENTED"
	// t := theme.CurrentTheme()
	// baseStyle := styles.BaseStyle()
	//
	// toolKey := baseStyle.Foreground(t.TextMuted()).Bold(true).Render("Tool")
	// toolValue := baseStyle.
	// 	Foreground(t.Text()).
	// 	Width(p.width - lipgloss.Width(toolKey)).
	// 	Render(fmt.Sprintf(": %s", p.permission.ToolName))
	//
	// pathKey := baseStyle.Foreground(t.TextMuted()).Bold(true).Render("Path")
	//
	// // Get the current working directory to display relative path
	// relativePath := p.permission.Path
	// if filepath.IsAbs(relativePath) {
	// 	if cwd, err := filepath.Rel(config.WorkingDirectory(), relativePath); err == nil {
	// 		relativePath = cwd
	// 	}
	// }
	//
	// pathValue := baseStyle.
	// 	Foreground(t.Text()).
	// 	Width(p.width - lipgloss.Width(pathKey)).
	// 	Render(fmt.Sprintf(": %s", relativePath))
	//
	// headerParts := []string{
	// 	lipgloss.JoinHorizontal(
	// 		lipgloss.Left,
	// 		toolKey,
	// 		toolValue,
	// 	),
	// 	baseStyle.Render(strings.Repeat(" ", p.width)),
	// 	lipgloss.JoinHorizontal(
	// 		lipgloss.Left,
	// 		pathKey,
	// 		pathValue,
	// 	),
	// 	baseStyle.Render(strings.Repeat(" ", p.width)),
	// }
	//
	// // Add tool-specific header information
	// switch p.permission.ToolName {
	// case "bash":
	// 	headerParts = append(headerParts, baseStyle.Foreground(t.TextMuted()).Width(p.width).Bold(true).Render("Command"))
	// case "edit":
	// 	headerParts = append(headerParts, baseStyle.Foreground(t.TextMuted()).Width(p.width).Bold(true).Render("Diff"))
	// case "write":
	// 	headerParts = append(headerParts, baseStyle.Foreground(t.TextMuted()).Width(p.width).Bold(true).Render("Diff"))
	// case "fetch":
	// 	headerParts = append(headerParts, baseStyle.Foreground(t.TextMuted()).Width(p.width).Bold(true).Render("URL"))
	// }
	//
	// return lipgloss.NewStyle().Background(t.Background()).Render(lipgloss.JoinVertical(lipgloss.Left, headerParts...))
}

func (p *permissionDialogCmp) renderBashContent() string {
	// t := theme.CurrentTheme()
	// baseStyle := styles.BaseStyle()
	//
	// if pr, ok := p.permission.Params.(tools.BashPermissionsParams); ok {
	// 	content := fmt.Sprintf("```bash\n%s\n```", pr.Command)
	//
	// 	// Use the cache for markdown rendering
	// 	renderedContent := p.GetOrSetMarkdown(p.permission.ID, func() (string, error) {
	// 		r := styles.GetMarkdownRenderer(p.width - 10)
	// 		s, err := r.Render(content)
	// 		return styles.ForceReplaceBackgroundWithLipgloss(s, t.Background()), err
	// 	})
	//
	// 	finalContent := baseStyle.
	// 		Width(p.contentViewPort.Width).
	// 		Render(renderedContent)
	// 	p.contentViewPort.SetContent(finalContent)
	// 	return p.styleViewport()
	// }
	return ""
}

func (p *permissionDialogCmp) renderEditContent() string {
	// if pr, ok := p.permission.Params.(tools.EditPermissionsParams); ok {
	// 	diff := p.GetOrSetDiff(p.permission.ID, func() (string, error) {
	// 		return diff.FormatDiff(pr.Diff, diff.WithTotalWidth(p.contentViewPort.Width))
	// 	})
	//
	// 	p.contentViewPort.SetContent(diff)
	// 	return p.styleViewport()
	// }
	return ""
}

func (p *permissionDialogCmp) renderPatchContent() string {
	// if pr, ok := p.permission.Params.(tools.EditPermissionsParams); ok {
	// 	diff := p.GetOrSetDiff(p.permission.ID, func() (string, error) {
	// 		return diff.FormatDiff(pr.Diff, diff.WithTotalWidth(p.contentViewPort.Width))
	// 	})
	//
	// 	p.contentViewPort.SetContent(diff)
	// 	return p.styleViewport()
	// }
	return ""
}

func (p *permissionDialogCmp) renderWriteContent() string {
	// if pr, ok := p.permission.Params.(tools.WritePermissionsParams); ok {
	// 	// Use the cache for diff rendering
	// 	diff := p.GetOrSetDiff(p.permission.ID, func() (string, error) {
	// 		return diff.FormatDiff(pr.Diff, diff.WithTotalWidth(p.contentViewPort.Width))
	// 	})
	//
	// 	p.contentViewPort.SetContent(diff)
	// 	return p.styleViewport()
	// }
	return ""
}

func (p *permissionDialogCmp) renderFetchContent() string {
	// 	t := theme.CurrentTheme()
	// 	baseStyle := styles.BaseStyle()
	//
	// 	if pr, ok := p.permission.Params.(tools.FetchPermissionsParams); ok {
	// 		content := fmt.Sprintf("```bash\n%s\n```", pr.URL)
	//
	// 		// Use the cache for markdown rendering
	// 		renderedContent := p.GetOrSetMarkdown(p.permission.ID, func() (string, error) {
	// 			r := styles.GetMarkdownRenderer(p.width - 10)
	// 			s, err := r.Render(content)
	// 			return styles.ForceReplaceBackgroundWithLipgloss(s, t.Background()), err
	// 		})
	//
	// 		finalContent := baseStyle.
	// 			Width(p.contentViewPort.Width).
	// 			Render(renderedContent)
	// 		p.contentViewPort.SetContent(finalContent)
	// 		return p.styleViewport()
	// 	}
	return ""
}

func (p *permissionDialogCmp) renderDefaultContent() string {
	// 	t := theme.CurrentTheme()
	// 	baseStyle := styles.BaseStyle()
	//
	// 	content := p.permission.Description
	//
	// 	// Use the cache for markdown rendering
	// 	renderedContent := p.GetOrSetMarkdown(p.permission.ID, func() (string, error) {
	// 		r := styles.GetMarkdownRenderer(p.width - 10)
	// 		s, err := r.Render(content)
	// 		return styles.ForceReplaceBackgroundWithLipgloss(s, t.Background()), err
	// 	})
	//
	// 	finalContent := baseStyle.
	// 		Width(p.contentViewPort.Width).
	// 		Render(renderedContent)
	// 	p.contentViewPort.SetContent(finalContent)
	//
	// 	if renderedContent == "" {
	// 		return ""
	// 	}
	//
	return p.styleViewport()
}

func (p *permissionDialogCmp) styleViewport() string {
	t := theme.CurrentTheme()
	contentStyle := lipgloss.NewStyle().
		Background(t.Background())

	return contentStyle.Render(p.contentViewPort.View())
}

func (p *permissionDialogCmp) render() string {
	return "NOT IMPLEMENTED"
	// t := theme.CurrentTheme()
	// baseStyle := styles.BaseStyle()
	//
	// title := baseStyle.
	// 	Bold(true).
	// 	Width(p.width - 4).
	// 	Foreground(t.Primary()).
	// 	Render("Permission Required")
	// // Render header
	// headerContent := p.renderHeader()
	// // Render buttons
	// buttons := p.renderButtons()
	//
	// // Calculate content height dynamically based on window size
	// p.contentViewPort.Height = p.height - lipgloss.Height(headerContent) - lipgloss.Height(buttons) - 2 - lipgloss.Height(title)
	// p.contentViewPort.Width = p.width - 4
	//
	// // Render content based on tool type
	// var contentFinal string
	// switch p.permission.ToolName {
	// case "bash":
	// 	contentFinal = p.renderBashContent()
	// case "edit":
	// 	contentFinal = p.renderEditContent()
	// case "patch":
	// 	contentFinal = p.renderPatchContent()
	// case "write":
	// 	contentFinal = p.renderWriteContent()
	// case "fetch":
	// 	contentFinal = p.renderFetchContent()
	// default:
	// 	contentFinal = p.renderDefaultContent()
	// }
	//
	// content := lipgloss.JoinVertical(
	// 	lipgloss.Top,
	// 	title,
	// 	baseStyle.Render(strings.Repeat(" ", lipgloss.Width(title))),
	// 	headerContent,
	// 	contentFinal,
	// 	buttons,
	// 	baseStyle.Render(strings.Repeat(" ", p.width-4)),
	// )
	//
	// return baseStyle.
	// 	Padding(1, 0, 0, 1).
	// 	Border(lipgloss.RoundedBorder()).
	// 	BorderBackground(t.Background()).
	// 	BorderForeground(t.TextMuted()).
	// 	Width(p.width).
	// 	Height(p.height).
	// 	Render(
	// 		content,
	// 	)
}

func (p *permissionDialogCmp) View() string {
	return p.render()
}

func (p *permissionDialogCmp) BindingKeys() []key.Binding {
	return layout.KeyMapToSlice(permissionsKeys)
}

func (p *permissionDialogCmp) SetSize() tea.Cmd {
	// if p.permission.ID == "" {
	// 	return nil
	// }
	// switch p.permission.ToolName {
	// case "bash":
	// 	p.width = int(float64(p.windowSize.Width) * 0.4)
	// 	p.height = int(float64(p.windowSize.Height) * 0.3)
	// case "edit":
	// 	p.width = int(float64(p.windowSize.Width) * 0.8)
	// 	p.height = int(float64(p.windowSize.Height) * 0.8)
	// case "write":
	// 	p.width = int(float64(p.windowSize.Width) * 0.8)
	// 	p.height = int(float64(p.windowSize.Height) * 0.8)
	// case "fetch":
	// 	p.width = int(float64(p.windowSize.Width) * 0.4)
	// 	p.height = int(float64(p.windowSize.Height) * 0.3)
	// default:
	// 	p.width = int(float64(p.windowSize.Width) * 0.7)
	// 	p.height = int(float64(p.windowSize.Height) * 0.5)
	// }
	return nil
}

// func (p *permissionDialogCmp) SetPermissions(permission permission.PermissionRequest) tea.Cmd {
// 	p.permission = permission
// 	return p.SetSize()
// }

// Helper to get or set cached diff content
func (c *permissionDialogCmp) GetOrSetDiff(key string, generator func() (string, error)) string {
	if cached, ok := c.diffCache[key]; ok {
		return cached
	}

	content, err := generator()
	if err != nil {
		return fmt.Sprintf("Error formatting diff: %v", err)
	}

	c.diffCache[key] = content

	return content
}

// Helper to get or set cached markdown content
func (c *permissionDialogCmp) GetOrSetMarkdown(key string, generator func() (string, error)) string {
	if cached, ok := c.markdownCache[key]; ok {
		return cached
	}

	content, err := generator()
	if err != nil {
		return fmt.Sprintf("Error rendering markdown: %v", err)
	}

	c.markdownCache[key] = content

	return content
}

func NewPermissionDialogCmp() PermissionDialogCmp {
	// Create viewport for content
	contentViewport := viewport.New(0, 0)

	return &permissionDialogCmp{
		contentViewPort: contentViewport,
		selectedOption:  0, // Default to "Allow"
		diffCache:       make(map[string]string),
		markdownCache:   make(map[string]string),
	}
}