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