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