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	"charm.land/bubbles/v2/key"
 17	"charm.land/bubbles/v2/textarea"
 18	tea "charm.land/bubbletea/v2"
 19	"charm.land/lipgloss/v2"
 20	"git.secluded.site/crush/internal/app"
 21	"git.secluded.site/crush/internal/fsext"
 22	"git.secluded.site/crush/internal/message"
 23	"git.secluded.site/crush/internal/session"
 24	"git.secluded.site/crush/internal/tui/components/chat"
 25	"git.secluded.site/crush/internal/tui/components/completions"
 26	"git.secluded.site/crush/internal/tui/components/core/layout"
 27	"git.secluded.site/crush/internal/tui/components/dialogs"
 28	"git.secluded.site/crush/internal/tui/components/dialogs/commands"
 29	"git.secluded.site/crush/internal/tui/components/dialogs/filepicker"
 30	"git.secluded.site/crush/internal/tui/components/dialogs/quit"
 31	"git.secluded.site/crush/internal/tui/styles"
 32	"git.secluded.site/crush/internal/tui/util"
 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(msg.Content, "\\ ", " ")
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		// Open command palette when "/" is pressed on empty prompt
279		case msg.String() == "/" && len(strings.TrimSpace(m.textarea.Value())) == 0:
280			return m, util.CmdHandler(dialogs.OpenDialogMsg{
281				Model: commands.NewCommandDialog(m.session.ID),
282			})
283		// Completions
284		case msg.String() == "@" && !m.isCompletionsOpen &&
285			// only show if beginning of prompt, or if previous char is a space or newline:
286			(len(m.textarea.Value()) == 0 || unicode.IsSpace(rune(m.textarea.Value()[len(m.textarea.Value())-1]))):
287			m.isCompletionsOpen = true
288			m.currentQuery = ""
289			m.completionsStartIndex = curIdx
290			cmds = append(cmds, m.startCompletions)
291		case m.isCompletionsOpen && curIdx <= m.completionsStartIndex:
292			cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
293		}
294		if key.Matches(msg, DeleteKeyMaps.AttachmentDeleteMode) {
295			m.deleteMode = true
296			return m, nil
297		}
298		if key.Matches(msg, DeleteKeyMaps.DeleteAllAttachments) && m.deleteMode {
299			m.deleteMode = false
300			m.attachments = nil
301			return m, nil
302		}
303		rune := msg.Code
304		if m.deleteMode && unicode.IsDigit(rune) {
305			num := int(rune - '0')
306			m.deleteMode = false
307			if num < 10 && len(m.attachments) > num {
308				if num == 0 {
309					m.attachments = m.attachments[num+1:]
310				} else {
311					m.attachments = slices.Delete(m.attachments, num, num+1)
312				}
313				return m, nil
314			}
315		}
316		if key.Matches(msg, m.keyMap.OpenEditor) {
317			if m.app.AgentCoordinator.IsSessionBusy(m.session.ID) {
318				return m, util.ReportWarn("Agent is working, please wait...")
319			}
320			return m, m.openEditor(m.textarea.Value())
321		}
322		if key.Matches(msg, DeleteKeyMaps.Escape) {
323			m.deleteMode = false
324			return m, nil
325		}
326		if key.Matches(msg, m.keyMap.Newline) {
327			m.textarea.InsertRune('\n')
328			cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
329		}
330		// Handle Enter key
331		if m.textarea.Focused() && key.Matches(msg, m.keyMap.SendMessage) {
332			value := m.textarea.Value()
333			if strings.HasSuffix(value, "\\") {
334				// If the last character is a backslash, remove it and add a newline.
335				m.textarea.SetValue(strings.TrimSuffix(value, "\\"))
336			} else {
337				// Otherwise, send the message
338				return m, m.send()
339			}
340		}
341	}
342
343	m.textarea, cmd = m.textarea.Update(msg)
344	cmds = append(cmds, cmd)
345
346	if m.textarea.Focused() {
347		kp, ok := msg.(tea.KeyPressMsg)
348		if ok {
349			if kp.String() == "space" || m.textarea.Value() == "" {
350				m.isCompletionsOpen = false
351				m.currentQuery = ""
352				m.completionsStartIndex = 0
353				cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
354			} else {
355				word := m.textarea.Word()
356				if strings.HasPrefix(word, "@") {
357					// XXX: wont' work if editing in the middle of the field.
358					m.completionsStartIndex = strings.LastIndex(m.textarea.Value(), word)
359					m.currentQuery = word[1:]
360					x, y := m.completionsPosition()
361					x -= len(m.currentQuery)
362					m.isCompletionsOpen = true
363					cmds = append(cmds,
364						util.CmdHandler(completions.FilterCompletionsMsg{
365							Query:  m.currentQuery,
366							Reopen: m.isCompletionsOpen,
367							X:      x,
368							Y:      y,
369						}),
370					)
371				} else if m.isCompletionsOpen {
372					m.isCompletionsOpen = false
373					m.currentQuery = ""
374					m.completionsStartIndex = 0
375					cmds = append(cmds, util.CmdHandler(completions.CloseCompletionsMsg{}))
376				}
377			}
378		}
379	}
380
381	return m, tea.Batch(cmds...)
382}
383
384func (m *editorCmp) setEditorPrompt() {
385	if m.app.Permissions.SkipRequests() {
386		m.textarea.SetPromptFunc(4, yoloPromptFunc)
387		return
388	}
389	m.textarea.SetPromptFunc(4, normalPromptFunc)
390}
391
392func (m *editorCmp) completionsPosition() (int, int) {
393	cur := m.textarea.Cursor()
394	if cur == nil {
395		return m.x, m.y + 1 // adjust for padding
396	}
397	x := cur.X + m.x
398	y := cur.Y + m.y + 1 // adjust for padding
399	return x, y
400}
401
402func (m *editorCmp) Cursor() *tea.Cursor {
403	cursor := m.textarea.Cursor()
404	if cursor != nil {
405		cursor.X = cursor.X + m.x + 1
406		cursor.Y = cursor.Y + m.y + 1 // adjust for padding
407	}
408	return cursor
409}
410
411var readyPlaceholders = [...]string{
412	"Ready!",
413	"Ready...",
414	"Ready?",
415	"Ready for instructions",
416}
417
418var workingPlaceholders = [...]string{
419	"Working!",
420	"Working...",
421	"Brrrrr...",
422	"Prrrrrrrr...",
423	"Processing...",
424	"Thinking...",
425}
426
427func (m *editorCmp) randomizePlaceholders() {
428	m.workingPlaceholder = workingPlaceholders[rand.Intn(len(workingPlaceholders))]
429	m.readyPlaceholder = readyPlaceholders[rand.Intn(len(readyPlaceholders))]
430}
431
432func (m *editorCmp) View() string {
433	t := styles.CurrentTheme()
434	// Update placeholder
435	if m.app.AgentCoordinator != nil && m.app.AgentCoordinator.IsBusy() {
436		m.textarea.Placeholder = m.workingPlaceholder
437	} else {
438		m.textarea.Placeholder = m.readyPlaceholder
439	}
440	if m.app.Permissions.SkipRequests() {
441		m.textarea.Placeholder = "Yolo mode!"
442	}
443	if len(m.attachments) == 0 {
444		content := t.S().Base.Padding(1).Render(
445			m.textarea.View(),
446		)
447		return content
448	}
449	content := t.S().Base.Padding(0, 1, 1, 1).Render(
450		lipgloss.JoinVertical(lipgloss.Top,
451			m.attachmentsContent(),
452			m.textarea.View(),
453		),
454	)
455	return content
456}
457
458func (m *editorCmp) SetSize(width, height int) tea.Cmd {
459	m.width = width
460	m.height = height
461	m.textarea.SetWidth(width - 2)   // adjust for padding
462	m.textarea.SetHeight(height - 2) // adjust for padding
463	return nil
464}
465
466func (m *editorCmp) GetSize() (int, int) {
467	return m.textarea.Width(), m.textarea.Height()
468}
469
470func (m *editorCmp) attachmentsContent() string {
471	var styledAttachments []string
472	t := styles.CurrentTheme()
473	attachmentStyles := t.S().Base.
474		MarginLeft(1).
475		Background(t.FgMuted).
476		Foreground(t.FgBase)
477	for i, attachment := range m.attachments {
478		var filename string
479		if len(attachment.FileName) > 10 {
480			filename = fmt.Sprintf(" %s %s...", styles.DocumentIcon, attachment.FileName[0:7])
481		} else {
482			filename = fmt.Sprintf(" %s %s", styles.DocumentIcon, attachment.FileName)
483		}
484		if m.deleteMode {
485			filename = fmt.Sprintf("%d%s", i, filename)
486		}
487		styledAttachments = append(styledAttachments, attachmentStyles.Render(filename))
488	}
489	content := lipgloss.JoinHorizontal(lipgloss.Left, styledAttachments...)
490	return content
491}
492
493func (m *editorCmp) SetPosition(x, y int) tea.Cmd {
494	m.x = x
495	m.y = y
496	return nil
497}
498
499func (m *editorCmp) startCompletions() tea.Msg {
500	ls := m.app.Config().Options.TUI.Completions
501	depth, limit := ls.Limits()
502	files, _, _ := fsext.ListDirectory(".", nil, depth, limit)
503	slices.Sort(files)
504	completionItems := make([]completions.Completion, 0, len(files))
505	for _, file := range files {
506		file = strings.TrimPrefix(file, "./")
507		completionItems = append(completionItems, completions.Completion{
508			Title: file,
509			Value: FileCompletionItem{
510				Path: file,
511			},
512		})
513	}
514
515	x, y := m.completionsPosition()
516	return completions.OpenCompletionsMsg{
517		Completions: completionItems,
518		X:           x,
519		Y:           y,
520		MaxResults:  maxFileResults,
521	}
522}
523
524// Blur implements Container.
525func (c *editorCmp) Blur() tea.Cmd {
526	c.textarea.Blur()
527	return nil
528}
529
530// Focus implements Container.
531func (c *editorCmp) Focus() tea.Cmd {
532	return c.textarea.Focus()
533}
534
535// IsFocused implements Container.
536func (c *editorCmp) IsFocused() bool {
537	return c.textarea.Focused()
538}
539
540// Bindings implements Container.
541func (c *editorCmp) Bindings() []key.Binding {
542	return c.keyMap.KeyBindings()
543}
544
545// TODO: most likely we do not need to have the session here
546// we need to move some functionality to the page level
547func (c *editorCmp) SetSession(session session.Session) tea.Cmd {
548	c.session = session
549	return nil
550}
551
552func (c *editorCmp) IsCompletionsOpen() bool {
553	return c.isCompletionsOpen
554}
555
556func (c *editorCmp) HasAttachments() bool {
557	return len(c.attachments) > 0
558}
559
560func normalPromptFunc(info textarea.PromptInfo) string {
561	t := styles.CurrentTheme()
562	if info.LineNumber == 0 {
563		return "  > "
564	}
565	if info.Focused {
566		return t.S().Base.Foreground(t.GreenDark).Render("::: ")
567	}
568	return t.S().Muted.Render("::: ")
569}
570
571func yoloPromptFunc(info textarea.PromptInfo) string {
572	t := styles.CurrentTheme()
573	if info.LineNumber == 0 {
574		if info.Focused {
575			return fmt.Sprintf("%s ", t.YoloIconFocused)
576		} else {
577			return fmt.Sprintf("%s ", t.YoloIconBlurred)
578		}
579	}
580	if info.Focused {
581		return fmt.Sprintf("%s ", t.YoloDotsFocused)
582	}
583	return fmt.Sprintf("%s ", t.YoloDotsBlurred)
584}
585
586func New(app *app.App) Editor {
587	t := styles.CurrentTheme()
588	ta := textarea.New()
589	ta.SetStyles(t.S().TextArea)
590	ta.ShowLineNumbers = false
591	ta.CharLimit = -1
592	ta.SetVirtualCursor(false)
593	ta.Focus()
594	e := &editorCmp{
595		// TODO: remove the app instance from here
596		app:      app,
597		textarea: ta,
598		keyMap:   DefaultEditorKeyMap(),
599	}
600	e.setEditorPrompt()
601
602	e.randomizePlaceholders()
603	e.textarea.Placeholder = e.readyPlaceholder
604
605	return e
606}