editor.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. package chat
  2. import (
  3. "fmt"
  4. "log/slog"
  5. "os"
  6. "os/exec"
  7. "slices"
  8. "strings"
  9. "unicode"
  10. "github.com/charmbracelet/bubbles/key"
  11. "github.com/charmbracelet/bubbles/textarea"
  12. tea "github.com/charmbracelet/bubbletea"
  13. "github.com/charmbracelet/lipgloss"
  14. "github.com/sst/opencode/internal/app"
  15. "github.com/sst/opencode/internal/message"
  16. "github.com/sst/opencode/internal/status"
  17. "github.com/sst/opencode/internal/tui/components/dialog"
  18. "github.com/sst/opencode/internal/tui/image"
  19. "github.com/sst/opencode/internal/tui/layout"
  20. "github.com/sst/opencode/internal/tui/styles"
  21. "github.com/sst/opencode/internal/tui/theme"
  22. "github.com/sst/opencode/internal/tui/util"
  23. )
  24. type editorCmp struct {
  25. width int
  26. height int
  27. app *app.App
  28. textarea textarea.Model
  29. attachments []message.Attachment
  30. deleteMode bool
  31. history []string
  32. historyIndex int
  33. currentMessage string
  34. }
  35. type EditorKeyMaps struct {
  36. Send key.Binding
  37. OpenEditor key.Binding
  38. Paste key.Binding
  39. HistoryUp key.Binding
  40. HistoryDown key.Binding
  41. }
  42. type bluredEditorKeyMaps struct {
  43. Send key.Binding
  44. Focus key.Binding
  45. OpenEditor key.Binding
  46. }
  47. type DeleteAttachmentKeyMaps struct {
  48. AttachmentDeleteMode key.Binding
  49. Escape key.Binding
  50. DeleteAllAttachments key.Binding
  51. }
  52. var editorMaps = EditorKeyMaps{
  53. Send: key.NewBinding(
  54. key.WithKeys("enter", "ctrl+s"),
  55. key.WithHelp("enter", "send message"),
  56. ),
  57. OpenEditor: key.NewBinding(
  58. key.WithKeys("ctrl+e"),
  59. key.WithHelp("ctrl+e", "open editor"),
  60. ),
  61. Paste: key.NewBinding(
  62. key.WithKeys("ctrl+v"),
  63. key.WithHelp("ctrl+v", "paste content"),
  64. ),
  65. HistoryUp: key.NewBinding(
  66. key.WithKeys("up"),
  67. key.WithHelp("up", "previous message"),
  68. ),
  69. HistoryDown: key.NewBinding(
  70. key.WithKeys("down"),
  71. key.WithHelp("down", "next message"),
  72. ),
  73. }
  74. var 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"),
  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. const (
  89. maxAttachments = 5
  90. )
  91. func (m *editorCmp) openEditor(value string) tea.Cmd {
  92. editor := os.Getenv("EDITOR")
  93. if editor == "" {
  94. editor = "nvim"
  95. }
  96. tmpfile, err := os.CreateTemp("", "msg_*.md")
  97. tmpfile.WriteString(value)
  98. if err != nil {
  99. status.Error(err.Error())
  100. return nil
  101. }
  102. tmpfile.Close()
  103. c := exec.Command(editor, tmpfile.Name()) //nolint:gosec
  104. c.Stdin = os.Stdin
  105. c.Stdout = os.Stdout
  106. c.Stderr = os.Stderr
  107. return tea.ExecProcess(c, func(err error) tea.Msg {
  108. if err != nil {
  109. status.Error(err.Error())
  110. return nil
  111. }
  112. content, err := os.ReadFile(tmpfile.Name())
  113. if err != nil {
  114. status.Error(err.Error())
  115. return nil
  116. }
  117. if len(content) == 0 {
  118. status.Warn("Message is empty")
  119. return nil
  120. }
  121. os.Remove(tmpfile.Name())
  122. attachments := m.attachments
  123. m.attachments = nil
  124. return SendMsg{
  125. Text: string(content),
  126. Attachments: attachments,
  127. }
  128. })
  129. }
  130. func (m *editorCmp) Init() tea.Cmd {
  131. return textarea.Blink
  132. }
  133. func (m *editorCmp) send() tea.Cmd {
  134. if m.app.PrimaryAgent.IsSessionBusy(m.app.CurrentSession.ID) {
  135. status.Warn("Agent is working, please wait...")
  136. return nil
  137. }
  138. value := m.textarea.Value()
  139. m.textarea.Reset()
  140. attachments := m.attachments
  141. // Save to history if not empty and not a duplicate of the last entry
  142. if value != "" {
  143. if len(m.history) == 0 || m.history[len(m.history)-1] != value {
  144. m.history = append(m.history, value)
  145. }
  146. m.historyIndex = len(m.history)
  147. m.currentMessage = ""
  148. }
  149. m.attachments = nil
  150. if value == "" {
  151. return nil
  152. }
  153. return tea.Batch(
  154. util.CmdHandler(SendMsg{
  155. Text: value,
  156. Attachments: attachments,
  157. }),
  158. )
  159. }
  160. func (m *editorCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
  161. var cmd tea.Cmd
  162. switch msg := msg.(type) {
  163. case dialog.ThemeChangedMsg:
  164. m.textarea = CreateTextArea(&m.textarea)
  165. case dialog.CompletionSelectedMsg:
  166. existingValue := m.textarea.Value()
  167. modifiedValue := strings.Replace(existingValue, msg.SearchString, msg.CompletionValue, 1)
  168. m.textarea.SetValue(modifiedValue)
  169. return m, nil
  170. case dialog.AttachmentAddedMsg:
  171. if len(m.attachments) >= maxAttachments {
  172. status.Error(fmt.Sprintf("cannot add more than %d images", maxAttachments))
  173. return m, cmd
  174. }
  175. m.attachments = append(m.attachments, msg.Attachment)
  176. case tea.KeyMsg:
  177. if key.Matches(msg, DeleteKeyMaps.AttachmentDeleteMode) {
  178. m.deleteMode = true
  179. return m, nil
  180. }
  181. if key.Matches(msg, DeleteKeyMaps.DeleteAllAttachments) && m.deleteMode {
  182. m.deleteMode = false
  183. m.attachments = nil
  184. return m, nil
  185. }
  186. if m.deleteMode && len(msg.Runes) > 0 && unicode.IsDigit(msg.Runes[0]) {
  187. num := int(msg.Runes[0] - '0')
  188. m.deleteMode = false
  189. if num < 10 && len(m.attachments) > num {
  190. if num == 0 {
  191. m.attachments = m.attachments[num+1:]
  192. } else {
  193. m.attachments = slices.Delete(m.attachments, num, num+1)
  194. }
  195. return m, nil
  196. }
  197. }
  198. if key.Matches(msg, messageKeys.PageUp) || key.Matches(msg, messageKeys.PageDown) ||
  199. key.Matches(msg, messageKeys.HalfPageUp) || key.Matches(msg, messageKeys.HalfPageDown) {
  200. return m, nil
  201. }
  202. if key.Matches(msg, editorMaps.OpenEditor) {
  203. if m.app.PrimaryAgent.IsSessionBusy(m.app.CurrentSession.ID) {
  204. status.Warn("Agent is working, please wait...")
  205. return m, nil
  206. }
  207. value := m.textarea.Value()
  208. m.textarea.Reset()
  209. return m, m.openEditor(value)
  210. }
  211. if key.Matches(msg, DeleteKeyMaps.Escape) {
  212. m.deleteMode = false
  213. return m, nil
  214. }
  215. if key.Matches(msg, editorMaps.Paste) {
  216. imageBytes, text, err := image.GetImageFromClipboard()
  217. if err != nil {
  218. slog.Error(err.Error())
  219. return m, cmd
  220. }
  221. if len(imageBytes) != 0 {
  222. attachmentName := fmt.Sprintf("clipboard-image-%d", len(m.attachments))
  223. attachment := message.Attachment{FilePath: attachmentName, FileName: attachmentName, Content: imageBytes, MimeType: "image/png"}
  224. m.attachments = append(m.attachments, attachment)
  225. } else {
  226. m.textarea.SetValue(m.textarea.Value() + text)
  227. }
  228. return m, cmd
  229. }
  230. // Handle history navigation with up/down arrow keys
  231. if m.textarea.Focused() && key.Matches(msg, editorMaps.HistoryUp) {
  232. // Get the current line number
  233. currentLine := m.textarea.Line()
  234. // Only navigate history if we're at the first line
  235. if currentLine == 0 && len(m.history) > 0 {
  236. // Save current message if we're just starting to navigate
  237. if m.historyIndex == len(m.history) {
  238. m.currentMessage = m.textarea.Value()
  239. }
  240. // Go to previous message in history
  241. if m.historyIndex > 0 {
  242. m.historyIndex--
  243. m.textarea.SetValue(m.history[m.historyIndex])
  244. }
  245. return m, nil
  246. }
  247. }
  248. if m.textarea.Focused() && key.Matches(msg, editorMaps.HistoryDown) {
  249. // Get the current line number and total lines
  250. currentLine := m.textarea.Line()
  251. value := m.textarea.Value()
  252. lines := strings.Split(value, "\n")
  253. totalLines := len(lines)
  254. // Only navigate history if we're at the last line
  255. if currentLine == totalLines-1 {
  256. if m.historyIndex < len(m.history)-1 {
  257. // Go to next message in history
  258. m.historyIndex++
  259. m.textarea.SetValue(m.history[m.historyIndex])
  260. } else if m.historyIndex == len(m.history)-1 {
  261. // Return to the current message being composed
  262. m.historyIndex = len(m.history)
  263. m.textarea.SetValue(m.currentMessage)
  264. }
  265. return m, nil
  266. }
  267. }
  268. // Handle Enter key
  269. if m.textarea.Focused() && key.Matches(msg, editorMaps.Send) {
  270. value := m.textarea.Value()
  271. if len(value) > 0 && value[len(value)-1] == '\\' {
  272. // If the last character is a backslash, remove it and add a newline
  273. m.textarea.SetValue(value[:len(value)-1] + "\n")
  274. return m, nil
  275. } else {
  276. // Otherwise, send the message
  277. return m, m.send()
  278. }
  279. }
  280. }
  281. m.textarea, cmd = m.textarea.Update(msg)
  282. return m, cmd
  283. }
  284. func (m *editorCmp) View() string {
  285. t := theme.CurrentTheme()
  286. // Style the prompt with theme colors
  287. style := lipgloss.NewStyle().
  288. Padding(0, 0, 0, 1).
  289. Bold(true).
  290. Foreground(t.Primary())
  291. if len(m.attachments) == 0 {
  292. return lipgloss.JoinHorizontal(lipgloss.Top, style.Render(">"), m.textarea.View())
  293. }
  294. m.textarea.SetHeight(m.height - 1)
  295. return lipgloss.JoinVertical(lipgloss.Top,
  296. m.attachmentsContent(),
  297. lipgloss.JoinHorizontal(lipgloss.Top, style.Render(">"),
  298. m.textarea.View()),
  299. )
  300. }
  301. func (m *editorCmp) SetSize(width, height int) tea.Cmd {
  302. m.width = width
  303. m.height = height
  304. m.textarea.SetWidth(width - 3) // account for the prompt and padding right
  305. m.textarea.SetHeight(height)
  306. return nil
  307. }
  308. func (m *editorCmp) GetSize() (int, int) {
  309. return m.textarea.Width(), m.textarea.Height()
  310. }
  311. func (m *editorCmp) attachmentsContent() string {
  312. var styledAttachments []string
  313. t := theme.CurrentTheme()
  314. attachmentStyles := styles.BaseStyle().
  315. MarginLeft(1).
  316. Background(t.TextMuted()).
  317. Foreground(t.Text())
  318. for i, attachment := range m.attachments {
  319. var filename string
  320. if len(attachment.FileName) > 10 {
  321. filename = fmt.Sprintf(" %s %s...", styles.DocumentIcon, attachment.FileName[0:7])
  322. } else {
  323. filename = fmt.Sprintf(" %s %s", styles.DocumentIcon, attachment.FileName)
  324. }
  325. if m.deleteMode {
  326. filename = fmt.Sprintf("%d%s", i, filename)
  327. }
  328. styledAttachments = append(styledAttachments, attachmentStyles.Render(filename))
  329. }
  330. content := lipgloss.JoinHorizontal(lipgloss.Left, styledAttachments...)
  331. return content
  332. }
  333. func (m *editorCmp) BindingKeys() []key.Binding {
  334. bindings := []key.Binding{}
  335. bindings = append(bindings, layout.KeyMapToSlice(editorMaps)...)
  336. bindings = append(bindings, layout.KeyMapToSlice(DeleteKeyMaps)...)
  337. return bindings
  338. }
  339. func CreateTextArea(existing *textarea.Model) textarea.Model {
  340. t := theme.CurrentTheme()
  341. bgColor := t.Background()
  342. textColor := t.Text()
  343. textMutedColor := t.TextMuted()
  344. ta := textarea.New()
  345. ta.BlurredStyle.Base = styles.BaseStyle().Background(bgColor).Foreground(textColor)
  346. ta.BlurredStyle.CursorLine = styles.BaseStyle().Background(bgColor)
  347. ta.BlurredStyle.Placeholder = styles.BaseStyle().Background(bgColor).Foreground(textMutedColor)
  348. ta.BlurredStyle.Text = styles.BaseStyle().Background(bgColor).Foreground(textColor)
  349. ta.FocusedStyle.Base = styles.BaseStyle().Background(bgColor).Foreground(textColor)
  350. ta.FocusedStyle.CursorLine = styles.BaseStyle().Background(bgColor)
  351. ta.FocusedStyle.Placeholder = styles.BaseStyle().Background(bgColor).Foreground(textMutedColor)
  352. ta.FocusedStyle.Text = styles.BaseStyle().Background(bgColor).Foreground(textColor)
  353. ta.Prompt = " "
  354. ta.ShowLineNumbers = false
  355. ta.CharLimit = -1
  356. if existing != nil {
  357. ta.SetValue(existing.Value())
  358. ta.SetWidth(existing.Width())
  359. ta.SetHeight(existing.Height())
  360. }
  361. ta.Focus()
  362. return ta
  363. }
  364. func NewEditorCmp(app *app.App) tea.Model {
  365. ta := CreateTextArea(nil)
  366. return &editorCmp{
  367. app: app,
  368. textarea: ta,
  369. history: []string{},
  370. historyIndex: 0,
  371. currentMessage: "",
  372. }
  373. }