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