editor.go

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