editor.go

  1package editor
  2
  3import (
  4	"context"
  5	"fmt"
  6	"math/rand"
  7	"net/http"
  8	"os"
  9	"os/exec"
 10	"path/filepath"
 11	"runtime"
 12	"slices"
 13	"strings"
 14	"unicode"
 15
 16	"git.secluded.site/crush/internal/app"
 17	"git.secluded.site/crush/internal/fsext"
 18	"git.secluded.site/crush/internal/message"
 19	"git.secluded.site/crush/internal/session"
 20	"git.secluded.site/crush/internal/tui/components/chat"
 21	"git.secluded.site/crush/internal/tui/components/completions"
 22	"git.secluded.site/crush/internal/tui/components/core/layout"
 23	"git.secluded.site/crush/internal/tui/components/dialogs"
 24	"git.secluded.site/crush/internal/tui/components/dialogs/commands"
 25	"git.secluded.site/crush/internal/tui/components/dialogs/filepicker"
 26	"git.secluded.site/crush/internal/tui/components/dialogs/quit"
 27	"git.secluded.site/crush/internal/tui/styles"
 28	"git.secluded.site/crush/internal/tui/util"
 29	"github.com/charmbracelet/bubbles/v2/key"
 30	"github.com/charmbracelet/bubbles/v2/textarea"
 31	tea "github.com/charmbracelet/bubbletea/v2"
 32	"github.com/charmbracelet/lipgloss/v2"
 33)
 34
 35type Editor interface {
 36	util.Model
 37	layout.Sizeable
 38	layout.Focusable
 39	layout.Help
 40	layout.Positional
 41
 42	SetSession(session session.Session) tea.Cmd
 43	IsCompletionsOpen() bool
 44	HasAttachments() bool
 45	Cursor() *tea.Cursor
 46}
 47
 48type FileCompletionItem struct {
 49	Path string // The file path
 50}
 51
 52type editorCmp struct {
 53	width              int
 54	height             int
 55	x, y               int
 56	app                *app.App
 57	session            session.Session
 58	textarea           *textarea.Model
 59	attachments        []message.Attachment
 60	deleteMode         bool
 61	readyPlaceholder   string
 62	workingPlaceholder string
 63
 64	keyMap EditorKeyMap
 65
 66	// File path completions
 67	currentQuery          string
 68	completionsStartIndex int
 69	isCompletionsOpen     bool
 70}
 71
 72var DeleteKeyMaps = DeleteAttachmentKeyMaps{
 73	AttachmentDeleteMode: key.NewBinding(
 74		key.WithKeys("ctrl+r"),
 75		key.WithHelp("ctrl+r+{i}", "delete attachment at index i"),
 76	),
 77	Escape: key.NewBinding(
 78		key.WithKeys("esc", "alt+esc"),
 79		key.WithHelp("esc", "cancel delete mode"),
 80	),
 81	DeleteAllAttachments: key.NewBinding(
 82		key.WithKeys("r"),
 83		key.WithHelp("ctrl+r+r", "delete all attachments"),
 84	),
 85}
 86
 87const (
 88	maxAttachments = 5
 89	maxFileResults = 25
 90)
 91
 92type OpenEditorMsg struct {
 93	Text string
 94}
 95
 96func (m *editorCmp) openEditor(value string) tea.Cmd {
 97	editor := os.Getenv("EDITOR")
 98	if editor == "" {
 99		// Use platform-appropriate default editor
100		if runtime.GOOS == "windows" {
101			editor = "notepad"
102		} else {
103			editor = "nvim"
104		}
105	}
106
107	tmpfile, err := os.CreateTemp("", "msg_*.md")
108	if err != nil {
109		return util.ReportError(err)
110	}
111	defer tmpfile.Close() //nolint:errcheck
112	if _, err := tmpfile.WriteString(value); err != nil {
113		return util.ReportError(err)
114	}
115	c := exec.CommandContext(context.TODO(), editor, tmpfile.Name())
116	c.Stdin = os.Stdin
117	c.Stdout = os.Stdout
118	c.Stderr = os.Stderr
119	return tea.ExecProcess(c, func(err error) tea.Msg {
120		if err != nil {
121			return util.ReportError(err)
122		}
123		content, err := os.ReadFile(tmpfile.Name())
124		if err != nil {
125			return util.ReportError(err)
126		}
127		if len(content) == 0 {
128			return util.ReportWarn("Message is empty")
129		}
130		os.Remove(tmpfile.Name())
131		return OpenEditorMsg{
132			Text: strings.TrimSpace(string(content)),
133		}
134	})
135}
136
137func (m *editorCmp) Init() tea.Cmd {
138	return nil
139}
140
141func (m *editorCmp) send() tea.Cmd {
142	value := m.textarea.Value()
143	value = strings.TrimSpace(value)
144
145	switch value {
146	case "exit", "quit":
147		m.textarea.Reset()
148		return util.CmdHandler(dialogs.OpenDialogMsg{Model: quit.NewQuitDialog()})
149	}
150
151	m.textarea.Reset()
152	attachments := m.attachments
153
154	m.attachments = nil
155	if value == "" {
156		return nil
157	}
158
159	// Change the placeholder when sending a new message.
160	m.randomizePlaceholders()
161
162	return tea.Batch(
163		util.CmdHandler(chat.SendMsg{
164			Text:        value,
165			Attachments: attachments,
166		}),
167	)
168}
169
170func (m *editorCmp) repositionCompletions() tea.Msg {
171	x, y := m.completionsPosition()
172	return completions.RepositionCompletionsMsg{X: x, Y: y}
173}
174
175func (m *editorCmp) Update(msg tea.Msg) (util.Model, tea.Cmd) {
176	var cmd tea.Cmd
177	var cmds []tea.Cmd
178	switch msg := msg.(type) {
179	case tea.WindowSizeMsg:
180		return m, m.repositionCompletions
181	case filepicker.FilePickedMsg:
182		if len(m.attachments) >= maxAttachments {
183			return m, util.ReportError(fmt.Errorf("cannot add more than %d images", maxAttachments))
184		}
185		m.attachments = append(m.attachments, msg.Attachment)
186		return m, nil
187	case completions.CompletionsOpenedMsg:
188		m.isCompletionsOpen = true
189	case completions.CompletionsClosedMsg:
190		m.isCompletionsOpen = false
191		m.currentQuery = ""
192		m.completionsStartIndex = 0
193	case completions.SelectCompletionMsg:
194		if !m.isCompletionsOpen {
195			return m, nil
196		}
197		if item, ok := msg.Value.(FileCompletionItem); ok {
198			word := m.textarea.Word()
199			// If the selected item is a file, insert its path into the textarea
200			value := m.textarea.Value()
201			value = value[:m.completionsStartIndex] + // Remove the current query
202				item.Path + // Insert the file path
203				value[m.completionsStartIndex+len(word):] // Append the rest of the value
204			// XXX: This will always move the cursor to the end of the textarea.
205			m.textarea.SetValue(value)
206			m.textarea.MoveToEnd()
207			if !msg.Insert {
208				m.isCompletionsOpen = false
209				m.currentQuery = ""
210				m.completionsStartIndex = 0
211			}
212		}
213
214	case commands.OpenExternalEditorMsg:
215		if m.app.AgentCoordinator.IsSessionBusy(m.session.ID) {
216			return m, util.ReportWarn("Agent is working, please wait...")
217		}
218		if m.app.AgentCoordinator != nil && m.app.AgentCoordinator.HasPendingCompletionNotification(m.session.ID) {
219			m.app.AgentCoordinator.CancelCompletionNotification(m.session.ID)
220		}
221		return m, m.openEditor(m.textarea.Value())
222	case OpenEditorMsg:
223		m.textarea.SetValue(msg.Text)
224		m.textarea.MoveToEnd()
225	case tea.PasteMsg:
226		// Interaction: cancel any pending turn-end notification for this session.
227		if m.app.AgentCoordinator != nil && m.app.AgentCoordinator.HasPendingCompletionNotification(m.session.ID) {
228			m.app.AgentCoordinator.CancelCompletionNotification(m.session.ID)
229		}
230		path := strings.ReplaceAll(string(msg), "\\ ", " ")
231		// try to get an image
232		path, err := filepath.Abs(strings.TrimSpace(path))
233		if err != nil {
234			m.textarea, cmd = m.textarea.Update(msg)
235			return m, cmd
236		}
237		isAllowedType := false
238		for _, ext := range filepicker.AllowedTypes {
239			if strings.HasSuffix(path, ext) {
240				isAllowedType = true
241				break
242			}
243		}
244		if !isAllowedType {
245			m.textarea, cmd = m.textarea.Update(msg)
246			return m, cmd
247		}
248		tooBig, _ := filepicker.IsFileTooBig(path, filepicker.MaxAttachmentSize)
249		if tooBig {
250			m.textarea, cmd = m.textarea.Update(msg)
251			return m, cmd
252		}
253
254		content, err := os.ReadFile(path)
255		if err != nil {
256			m.textarea, cmd = m.textarea.Update(msg)
257			return m, cmd
258		}
259		mimeBufferSize := min(512, len(content))
260		mimeType := http.DetectContentType(content[:mimeBufferSize])
261		fileName := filepath.Base(path)
262		attachment := message.Attachment{FilePath: path, FileName: fileName, MimeType: mimeType, Content: content}
263		return m, util.CmdHandler(filepicker.FilePickedMsg{
264			Attachment: attachment,
265		})
266
267	case commands.ToggleYoloModeMsg:
268		m.setEditorPrompt()
269		return m, nil
270	case tea.KeyPressMsg:
271		// Interaction: cancel any pending turn-end notification for this session.
272		if m.app.AgentCoordinator != nil && m.app.AgentCoordinator.HasPendingCompletionNotification(m.session.ID) {
273			m.app.AgentCoordinator.CancelCompletionNotification(m.session.ID)
274		}
275		cur := m.textarea.Cursor()
276		curIdx := m.textarea.Width()*cur.Y + cur.X
277		switch {
278		// Completions
279		case msg.String() == "/" && !m.isCompletionsOpen &&
280			// only show if beginning of prompt, or if previous char is a space or newline:
281			(len(m.textarea.Value()) == 0 || unicode.IsSpace(rune(m.textarea.Value()[len(m.textarea.Value())-1]))):
282			m.isCompletionsOpen = true
283			m.currentQuery = ""
284			m.completionsStartIndex = curIdx
285			cmds = append(cmds, m.startCompletions)
286		case m.isCompletionsOpen && curIdx <= m.completionsStartIndex:
287			cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
288		}
289		if key.Matches(msg, DeleteKeyMaps.AttachmentDeleteMode) {
290			m.deleteMode = true
291			return m, nil
292		}
293		if key.Matches(msg, DeleteKeyMaps.DeleteAllAttachments) && m.deleteMode {
294			m.deleteMode = false
295			m.attachments = nil
296			return m, nil
297		}
298		rune := msg.Code
299		if m.deleteMode && unicode.IsDigit(rune) {
300			num := int(rune - '0')
301			m.deleteMode = false
302			if num < 10 && len(m.attachments) > num {
303				if num == 0 {
304					m.attachments = m.attachments[num+1:]
305				} else {
306					m.attachments = slices.Delete(m.attachments, num, num+1)
307				}
308				return m, nil
309			}
310		}
311		if key.Matches(msg, m.keyMap.OpenEditor) {
312			if m.app.AgentCoordinator.IsSessionBusy(m.session.ID) {
313				return m, util.ReportWarn("Agent is working, please wait...")
314			}
315			return m, m.openEditor(m.textarea.Value())
316		}
317		if key.Matches(msg, DeleteKeyMaps.Escape) {
318			m.deleteMode = false
319			return m, nil
320		}
321		if key.Matches(msg, m.keyMap.Newline) {
322			m.textarea.InsertRune('\n')
323			cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
324		}
325		// Handle Enter key
326		if m.textarea.Focused() && key.Matches(msg, m.keyMap.SendMessage) {
327			value := m.textarea.Value()
328			if strings.HasSuffix(value, "\\") {
329				// If the last character is a backslash, remove it and add a newline.
330				m.textarea.SetValue(strings.TrimSuffix(value, "\\"))
331			} else {
332				// Otherwise, send the message
333				return m, m.send()
334			}
335		}
336	}
337
338	m.textarea, cmd = m.textarea.Update(msg)
339	cmds = append(cmds, cmd)
340
341	if m.textarea.Focused() {
342		kp, ok := msg.(tea.KeyPressMsg)
343		if ok {
344			if kp.String() == "space" || m.textarea.Value() == "" {
345				m.isCompletionsOpen = false
346				m.currentQuery = ""
347				m.completionsStartIndex = 0
348				cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
349			} else {
350				word := m.textarea.Word()
351				if strings.HasPrefix(word, "/") {
352					// XXX: wont' work if editing in the middle of the field.
353					m.completionsStartIndex = strings.LastIndex(m.textarea.Value(), word)
354					m.currentQuery = word[1:]
355					x, y := m.completionsPosition()
356					x -= len(m.currentQuery)
357					m.isCompletionsOpen = true
358					cmds = append(cmds,
359						util.CmdHandler(completions.FilterCompletionsMsg{
360							Query:  m.currentQuery,
361							Reopen: m.isCompletionsOpen,
362							X:      x,
363							Y:      y,
364						}),
365					)
366				} else if m.isCompletionsOpen {
367					m.isCompletionsOpen = false
368					m.currentQuery = ""
369					m.completionsStartIndex = 0
370					cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
371				}
372			}
373		}
374	}
375
376	return m, tea.Batch(cmds...)
377}
378
379func (m *editorCmp) setEditorPrompt() {
380	if m.app.Permissions.SkipRequests() {
381		m.textarea.SetPromptFunc(4, yoloPromptFunc)
382		return
383	}
384	m.textarea.SetPromptFunc(4, normalPromptFunc)
385}
386
387func (m *editorCmp) completionsPosition() (int, int) {
388	cur := m.textarea.Cursor()
389	if cur == nil {
390		return m.x, m.y + 1 // adjust for padding
391	}
392	x := cur.X + m.x
393	y := cur.Y + m.y + 1 // adjust for padding
394	return x, y
395}
396
397func (m *editorCmp) Cursor() *tea.Cursor {
398	cursor := m.textarea.Cursor()
399	if cursor != nil {
400		cursor.X = cursor.X + m.x + 1
401		cursor.Y = cursor.Y + m.y + 1 // adjust for padding
402	}
403	return cursor
404}
405
406var readyPlaceholders = [...]string{
407	"Ready!",
408	"Ready...",
409	"Ready?",
410	"Ready for instructions",
411}
412
413var workingPlaceholders = [...]string{
414	"Working!",
415	"Working...",
416	"Brrrrr...",
417	"Prrrrrrrr...",
418	"Processing...",
419	"Thinking...",
420}
421
422func (m *editorCmp) randomizePlaceholders() {
423	m.workingPlaceholder = workingPlaceholders[rand.Intn(len(workingPlaceholders))]
424	m.readyPlaceholder = readyPlaceholders[rand.Intn(len(readyPlaceholders))]
425}
426
427func (m *editorCmp) View() string {
428	t := styles.CurrentTheme()
429	// Update placeholder
430	if m.app.AgentCoordinator != nil && m.app.AgentCoordinator.IsBusy() {
431		m.textarea.Placeholder = m.workingPlaceholder
432	} else {
433		m.textarea.Placeholder = m.readyPlaceholder
434	}
435	if m.app.Permissions.SkipRequests() {
436		m.textarea.Placeholder = "Yolo mode!"
437	}
438	if len(m.attachments) == 0 {
439		content := t.S().Base.Padding(1).Render(
440			m.textarea.View(),
441		)
442		return content
443	}
444	content := t.S().Base.Padding(0, 1, 1, 1).Render(
445		lipgloss.JoinVertical(lipgloss.Top,
446			m.attachmentsContent(),
447			m.textarea.View(),
448		),
449	)
450	return content
451}
452
453func (m *editorCmp) SetSize(width, height int) tea.Cmd {
454	m.width = width
455	m.height = height
456	m.textarea.SetWidth(width - 2)   // adjust for padding
457	m.textarea.SetHeight(height - 2) // adjust for padding
458	return nil
459}
460
461func (m *editorCmp) GetSize() (int, int) {
462	return m.textarea.Width(), m.textarea.Height()
463}
464
465func (m *editorCmp) attachmentsContent() string {
466	var styledAttachments []string
467	t := styles.CurrentTheme()
468	attachmentStyles := t.S().Base.
469		MarginLeft(1).
470		Background(t.FgMuted).
471		Foreground(t.FgBase)
472	for i, attachment := range m.attachments {
473		var filename string
474		if len(attachment.FileName) > 10 {
475			filename = fmt.Sprintf(" %s %s...", styles.DocumentIcon, attachment.FileName[0:7])
476		} else {
477			filename = fmt.Sprintf(" %s %s", styles.DocumentIcon, attachment.FileName)
478		}
479		if m.deleteMode {
480			filename = fmt.Sprintf("%d%s", i, filename)
481		}
482		styledAttachments = append(styledAttachments, attachmentStyles.Render(filename))
483	}
484	content := lipgloss.JoinHorizontal(lipgloss.Left, styledAttachments...)
485	return content
486}
487
488func (m *editorCmp) SetPosition(x, y int) tea.Cmd {
489	m.x = x
490	m.y = y
491	return nil
492}
493
494func (m *editorCmp) startCompletions() tea.Msg {
495	ls := m.app.Config().Options.TUI.Completions
496	depth, limit := ls.Limits()
497	files, _, _ := fsext.ListDirectory(".", nil, depth, limit)
498	slices.Sort(files)
499	completionItems := make([]completions.Completion, 0, len(files))
500	for _, file := range files {
501		file = strings.TrimPrefix(file, "./")
502		completionItems = append(completionItems, completions.Completion{
503			Title: file,
504			Value: FileCompletionItem{
505				Path: file,
506			},
507		})
508	}
509
510	x, y := m.completionsPosition()
511	return completions.OpenCompletionsMsg{
512		Completions: completionItems,
513		X:           x,
514		Y:           y,
515		MaxResults:  maxFileResults,
516	}
517}
518
519// Blur implements Container.
520func (c *editorCmp) Blur() tea.Cmd {
521	c.textarea.Blur()
522	return nil
523}
524
525// Focus implements Container.
526func (c *editorCmp) Focus() tea.Cmd {
527	return c.textarea.Focus()
528}
529
530// IsFocused implements Container.
531func (c *editorCmp) IsFocused() bool {
532	return c.textarea.Focused()
533}
534
535// Bindings implements Container.
536func (c *editorCmp) Bindings() []key.Binding {
537	return c.keyMap.KeyBindings()
538}
539
540// TODO: most likely we do not need to have the session here
541// we need to move some functionality to the page level
542func (c *editorCmp) SetSession(session session.Session) tea.Cmd {
543	c.session = session
544	return nil
545}
546
547func (c *editorCmp) IsCompletionsOpen() bool {
548	return c.isCompletionsOpen
549}
550
551func (c *editorCmp) HasAttachments() bool {
552	return len(c.attachments) > 0
553}
554
555func normalPromptFunc(info textarea.PromptInfo) string {
556	t := styles.CurrentTheme()
557	if info.LineNumber == 0 {
558		return "  > "
559	}
560	if info.Focused {
561		return t.S().Base.Foreground(t.GreenDark).Render("::: ")
562	}
563	return t.S().Muted.Render("::: ")
564}
565
566func yoloPromptFunc(info textarea.PromptInfo) string {
567	t := styles.CurrentTheme()
568	if info.LineNumber == 0 {
569		if info.Focused {
570			return fmt.Sprintf("%s ", t.YoloIconFocused)
571		} else {
572			return fmt.Sprintf("%s ", t.YoloIconBlurred)
573		}
574	}
575	if info.Focused {
576		return fmt.Sprintf("%s ", t.YoloDotsFocused)
577	}
578	return fmt.Sprintf("%s ", t.YoloDotsBlurred)
579}
580
581func New(app *app.App) Editor {
582	t := styles.CurrentTheme()
583	ta := textarea.New()
584	ta.SetStyles(t.S().TextArea)
585	ta.ShowLineNumbers = false
586	ta.CharLimit = -1
587	ta.SetVirtualCursor(false)
588	ta.Focus()
589	e := &editorCmp{
590		// TODO: remove the app instance from here
591		app:      app,
592		textarea: ta,
593		keyMap:   DefaultEditorKeyMap(),
594	}
595	e.setEditorPrompt()
596
597	e.randomizePlaceholders()
598	e.textarea.Placeholder = e.readyPlaceholder
599
600	return e
601}