2024-03-12 01:10:54 -06:00
|
|
|
package tui
|
|
|
|
|
|
|
|
// The terminal UI for lmcli, launched from the `lmcli chat` command
|
|
|
|
// TODO:
|
2024-03-12 23:15:50 -06:00
|
|
|
// - conversation list view
|
2024-03-14 00:01:16 -06:00
|
|
|
// - change model
|
|
|
|
// - rename conversation
|
|
|
|
// - set system prompt
|
|
|
|
// - system prompt library?
|
2024-03-12 01:10:54 -06:00
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2024-03-26 01:59:39 -06:00
|
|
|
"encoding/json"
|
2024-03-12 01:10:54 -06:00
|
|
|
"fmt"
|
|
|
|
"strings"
|
2024-03-13 23:58:31 -06:00
|
|
|
"time"
|
2024-03-12 01:10:54 -06:00
|
|
|
|
2024-03-13 17:07:29 -06:00
|
|
|
cmdutil "git.mlow.ca/mlow/lmcli/pkg/cmd/util"
|
2024-03-12 01:10:54 -06:00
|
|
|
"git.mlow.ca/mlow/lmcli/pkg/lmcli"
|
|
|
|
models "git.mlow.ca/mlow/lmcli/pkg/lmcli/model"
|
2024-03-13 23:58:31 -06:00
|
|
|
"github.com/charmbracelet/bubbles/spinner"
|
2024-03-12 01:10:54 -06:00
|
|
|
"github.com/charmbracelet/bubbles/textarea"
|
|
|
|
"github.com/charmbracelet/bubbles/viewport"
|
|
|
|
tea "github.com/charmbracelet/bubbletea"
|
|
|
|
"github.com/charmbracelet/lipgloss"
|
2024-03-22 21:59:02 -06:00
|
|
|
"github.com/muesli/reflow/ansi"
|
2024-03-16 18:25:42 -06:00
|
|
|
"github.com/muesli/reflow/wordwrap"
|
2024-03-26 01:59:39 -06:00
|
|
|
"gopkg.in/yaml.v2"
|
2024-03-12 01:10:54 -06:00
|
|
|
)
|
|
|
|
|
2024-03-12 11:50:10 -06:00
|
|
|
type focusState int
|
|
|
|
|
|
|
|
const (
|
|
|
|
focusInput focusState = iota
|
|
|
|
focusMessages
|
|
|
|
)
|
|
|
|
|
2024-03-16 15:56:45 -06:00
|
|
|
type editorTarget int
|
|
|
|
|
|
|
|
const (
|
|
|
|
input editorTarget = iota
|
|
|
|
selectedMessage
|
|
|
|
)
|
|
|
|
|
2024-03-22 20:52:56 -06:00
|
|
|
type uiCache struct {
|
|
|
|
header string
|
|
|
|
content string
|
|
|
|
error string
|
|
|
|
input string
|
|
|
|
footer string
|
|
|
|
}
|
|
|
|
|
2024-03-12 01:10:54 -06:00
|
|
|
type model struct {
|
2024-03-13 20:54:25 -06:00
|
|
|
width int
|
|
|
|
height int
|
|
|
|
|
2024-03-12 01:10:54 -06:00
|
|
|
ctx *lmcli.Context
|
|
|
|
convShortname string
|
|
|
|
|
|
|
|
// application state
|
2024-03-12 12:33:57 -06:00
|
|
|
conversation *models.Conversation
|
|
|
|
messages []models.Message
|
|
|
|
waitingForReply bool
|
2024-03-16 15:56:45 -06:00
|
|
|
editorTarget editorTarget
|
2024-03-15 00:44:42 -06:00
|
|
|
stopSignal chan interface{}
|
2024-03-12 20:05:48 -06:00
|
|
|
replyChan chan models.Message
|
|
|
|
replyChunkChan chan string
|
2024-03-13 15:20:03 -06:00
|
|
|
persistence bool // whether we will save new messages in the conversation
|
2024-03-15 23:49:04 -06:00
|
|
|
err error
|
2024-03-12 01:10:54 -06:00
|
|
|
|
|
|
|
// ui state
|
2024-03-15 23:49:04 -06:00
|
|
|
focus focusState
|
2024-03-16 18:25:42 -06:00
|
|
|
wrap bool // whether message content is wrapped to viewport width
|
2024-03-15 23:49:04 -06:00
|
|
|
status string // a general status message
|
2024-03-26 01:59:39 -06:00
|
|
|
showToolResults bool // whether tool calls and results are shown
|
|
|
|
messageCache []string // cache of syntax highlighted and wrapped message content
|
2024-03-15 23:49:04 -06:00
|
|
|
messageOffsets []int
|
|
|
|
selectedMessage int
|
2024-03-12 01:10:54 -06:00
|
|
|
|
|
|
|
// ui elements
|
|
|
|
content viewport.Model
|
|
|
|
input textarea.Model
|
2024-03-13 23:58:31 -06:00
|
|
|
spinner spinner.Model
|
2024-03-22 20:52:56 -06:00
|
|
|
|
|
|
|
cache *uiCache
|
2024-03-12 01:10:54 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
type message struct {
|
|
|
|
role string
|
|
|
|
content string
|
|
|
|
}
|
|
|
|
|
|
|
|
// custom tea.Msg types
|
|
|
|
type (
|
|
|
|
// sent on each chunk received from LLM
|
|
|
|
msgResponseChunk string
|
|
|
|
// sent when response is finished being received
|
|
|
|
msgResponseEnd string
|
2024-03-13 21:07:41 -06:00
|
|
|
// a special case of msgError that stops the response waiting animation
|
|
|
|
msgResponseError error
|
2024-03-12 20:05:48 -06:00
|
|
|
// sent on each completed reply
|
2024-03-13 17:05:42 -06:00
|
|
|
msgAssistantReply models.Message
|
2024-03-12 01:10:54 -06:00
|
|
|
// sent when a conversation is (re)loaded
|
|
|
|
msgConversationLoaded *models.Conversation
|
2024-03-13 17:07:29 -06:00
|
|
|
// sent when a new conversation title is set
|
|
|
|
msgConversationTitleChanged string
|
2024-03-12 01:10:54 -06:00
|
|
|
// send when a conversation's messages are laoded
|
|
|
|
msgMessagesLoaded []models.Message
|
|
|
|
// sent when an error occurs
|
|
|
|
msgError error
|
|
|
|
)
|
|
|
|
|
|
|
|
// styles
|
|
|
|
var (
|
2024-03-26 01:59:39 -06:00
|
|
|
headingStyle = lipgloss.NewStyle().
|
|
|
|
MarginTop(1).
|
|
|
|
MarginBottom(1).
|
|
|
|
PaddingLeft(1).
|
|
|
|
Bold(true)
|
|
|
|
userStyle = lipgloss.NewStyle().Faint(true).Foreground(lipgloss.Color("10"))
|
|
|
|
assistantStyle = lipgloss.NewStyle().Faint(true).Foreground(lipgloss.Color("12"))
|
|
|
|
messageStyle = lipgloss.NewStyle().
|
|
|
|
PaddingLeft(2).
|
|
|
|
PaddingRight(2)
|
|
|
|
headerStyle = lipgloss.NewStyle().
|
2024-03-29 09:48:50 -06:00
|
|
|
PaddingLeft(1).
|
|
|
|
PaddingRight(1).
|
2024-03-12 23:01:36 -06:00
|
|
|
Background(lipgloss.Color("0"))
|
2024-03-29 13:25:16 -06:00
|
|
|
footerStyle = lipgloss.NewStyle()
|
2024-03-12 01:10:54 -06:00
|
|
|
)
|
|
|
|
|
|
|
|
func (m model) Init() tea.Cmd {
|
|
|
|
return tea.Batch(
|
|
|
|
textarea.Blink,
|
2024-03-13 23:58:31 -06:00
|
|
|
m.spinner.Tick,
|
2024-03-12 01:10:54 -06:00
|
|
|
m.loadConversation(m.convShortname),
|
2024-03-12 20:05:48 -06:00
|
|
|
m.waitForChunk(),
|
|
|
|
m.waitForReply(),
|
2024-03-12 01:10:54 -06:00
|
|
|
)
|
|
|
|
}
|
|
|
|
|
2024-03-13 15:20:03 -06:00
|
|
|
func wrapError(err error) tea.Cmd {
|
|
|
|
return func() tea.Msg {
|
|
|
|
return msgError(err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-03-12 01:10:54 -06:00
|
|
|
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
2024-03-13 15:20:03 -06:00
|
|
|
var cmds []tea.Cmd
|
2024-03-12 01:10:54 -06:00
|
|
|
|
|
|
|
switch msg := msg.(type) {
|
2024-03-16 15:56:45 -06:00
|
|
|
case msgTempfileEditorClosed:
|
|
|
|
contents := string(msg)
|
|
|
|
switch m.editorTarget {
|
|
|
|
case input:
|
|
|
|
m.input.SetValue(contents)
|
|
|
|
case selectedMessage:
|
|
|
|
m.setMessageContents(m.selectedMessage, contents)
|
|
|
|
if m.persistence && m.messages[m.selectedMessage].ID > 0 {
|
|
|
|
// update persisted message
|
|
|
|
err := m.ctx.Store.UpdateMessage(&m.messages[m.selectedMessage])
|
|
|
|
if err != nil {
|
|
|
|
cmds = append(cmds, wrapError(fmt.Errorf("Could not save edited message: %v", err)))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
m.updateContent()
|
|
|
|
}
|
2024-03-12 01:10:54 -06:00
|
|
|
case tea.KeyMsg:
|
2024-03-12 11:50:10 -06:00
|
|
|
switch msg.String() {
|
|
|
|
case "ctrl+c":
|
2024-03-12 12:33:57 -06:00
|
|
|
if m.waitingForReply {
|
2024-03-17 12:16:10 -06:00
|
|
|
m.stopSignal <- ""
|
2024-03-22 11:51:01 -06:00
|
|
|
return m, nil
|
2024-03-12 12:33:57 -06:00
|
|
|
} else {
|
|
|
|
return m, tea.Quit
|
|
|
|
}
|
2024-03-13 15:20:03 -06:00
|
|
|
case "ctrl+p":
|
|
|
|
m.persistence = !m.persistence
|
2024-03-16 18:25:42 -06:00
|
|
|
case "ctrl+w":
|
|
|
|
m.wrap = !m.wrap
|
2024-03-26 01:59:39 -06:00
|
|
|
m.rebuildMessageCache()
|
|
|
|
m.updateContent()
|
|
|
|
case "ctrl+t":
|
|
|
|
m.showToolResults = !m.showToolResults
|
|
|
|
m.rebuildMessageCache()
|
2024-03-16 18:25:42 -06:00
|
|
|
m.updateContent()
|
2024-03-12 11:50:10 -06:00
|
|
|
case "q":
|
|
|
|
if m.focus != focusInput {
|
|
|
|
return m, tea.Quit
|
|
|
|
}
|
|
|
|
default:
|
|
|
|
var inputHandled tea.Cmd
|
|
|
|
switch m.focus {
|
|
|
|
case focusInput:
|
|
|
|
inputHandled = m.handleInputKey(msg)
|
|
|
|
case focusMessages:
|
|
|
|
inputHandled = m.handleMessagesKey(msg)
|
|
|
|
}
|
|
|
|
if inputHandled != nil {
|
|
|
|
return m, inputHandled
|
|
|
|
}
|
|
|
|
}
|
2024-03-12 01:10:54 -06:00
|
|
|
case tea.WindowSizeMsg:
|
2024-03-13 20:54:25 -06:00
|
|
|
m.width = msg.Width
|
|
|
|
m.height = msg.Height
|
2024-03-12 01:10:54 -06:00
|
|
|
m.content.Width = msg.Width
|
2024-03-29 13:25:16 -06:00
|
|
|
m.input.SetWidth(msg.Width-m.input.FocusedStyle.Base.GetHorizontalBorderSize())
|
2024-03-26 01:59:39 -06:00
|
|
|
m.rebuildMessageCache()
|
2024-03-12 01:10:54 -06:00
|
|
|
m.updateContent()
|
|
|
|
case msgConversationLoaded:
|
2024-03-12 23:15:41 -06:00
|
|
|
m.conversation = (*models.Conversation)(msg)
|
2024-03-13 15:20:03 -06:00
|
|
|
cmds = append(cmds, m.loadMessages(m.conversation))
|
2024-03-12 01:10:54 -06:00
|
|
|
case msgMessagesLoaded:
|
2024-03-13 10:29:06 -06:00
|
|
|
m.setMessages(msg)
|
2024-03-12 01:10:54 -06:00
|
|
|
m.updateContent()
|
|
|
|
case msgResponseChunk:
|
|
|
|
chunk := string(msg)
|
2024-03-12 17:31:48 -06:00
|
|
|
last := len(m.messages) - 1
|
2024-03-22 11:51:01 -06:00
|
|
|
if last >= 0 && m.messages[last].Role.IsAssistant() {
|
2024-03-13 10:29:06 -06:00
|
|
|
m.setMessageContents(last, m.messages[last].Content+chunk)
|
2024-03-12 17:31:48 -06:00
|
|
|
} else {
|
2024-03-13 10:29:06 -06:00
|
|
|
m.addMessage(models.Message{
|
2024-03-12 17:31:48 -06:00
|
|
|
Role: models.MessageRoleAssistant,
|
|
|
|
Content: chunk,
|
|
|
|
})
|
2024-03-12 01:10:54 -06:00
|
|
|
}
|
2024-03-12 17:31:48 -06:00
|
|
|
m.updateContent()
|
2024-03-13 15:20:03 -06:00
|
|
|
cmds = append(cmds, m.waitForChunk()) // wait for the next chunk
|
2024-03-13 17:05:42 -06:00
|
|
|
case msgAssistantReply:
|
2024-03-12 20:05:48 -06:00
|
|
|
// the last reply that was being worked on is finished
|
|
|
|
reply := models.Message(msg)
|
2024-03-22 11:51:01 -06:00
|
|
|
reply.Content = strings.TrimSpace(reply.Content)
|
|
|
|
|
2024-03-12 20:05:48 -06:00
|
|
|
last := len(m.messages) - 1
|
|
|
|
if last < 0 {
|
2024-03-22 11:51:01 -06:00
|
|
|
panic("Unexpected empty messages handling msgAssistantReply")
|
2024-03-12 20:05:48 -06:00
|
|
|
}
|
2024-03-22 11:51:01 -06:00
|
|
|
|
|
|
|
if reply.Role.IsAssistant() && m.messages[last].Role.IsAssistant() {
|
|
|
|
// this was a continuation, so replace the previous message with the completed reply
|
|
|
|
m.setMessage(last, reply)
|
2024-03-17 12:16:10 -06:00
|
|
|
} else {
|
2024-03-13 10:29:06 -06:00
|
|
|
m.addMessage(reply)
|
2024-03-12 20:05:48 -06:00
|
|
|
}
|
2024-03-13 15:20:03 -06:00
|
|
|
|
2024-03-13 17:05:42 -06:00
|
|
|
if m.persistence {
|
|
|
|
var err error
|
|
|
|
if m.conversation.ID == 0 {
|
|
|
|
err = m.ctx.Store.SaveConversation(m.conversation)
|
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
cmds = append(cmds, wrapError(err))
|
|
|
|
} else {
|
2024-03-17 12:16:10 -06:00
|
|
|
cmds = append(cmds, m.persistConversation())
|
2024-03-13 17:05:42 -06:00
|
|
|
}
|
2024-03-13 15:20:03 -06:00
|
|
|
}
|
|
|
|
|
2024-03-13 17:07:29 -06:00
|
|
|
if m.conversation.Title == "" {
|
|
|
|
cmds = append(cmds, m.generateConversationTitle())
|
|
|
|
}
|
|
|
|
|
2024-03-12 20:05:48 -06:00
|
|
|
m.updateContent()
|
2024-03-13 15:20:03 -06:00
|
|
|
cmds = append(cmds, m.waitForReply())
|
2024-03-12 01:10:54 -06:00
|
|
|
case msgResponseEnd:
|
2024-03-12 12:33:57 -06:00
|
|
|
m.waitingForReply = false
|
2024-03-17 12:16:10 -06:00
|
|
|
last := len(m.messages) - 1
|
|
|
|
if last < 0 {
|
|
|
|
panic("Unexpected empty messages handling msgResponseEnd")
|
|
|
|
}
|
|
|
|
m.setMessageContents(last, strings.TrimSpace(m.messages[last].Content))
|
|
|
|
m.updateContent()
|
2024-03-12 11:10:40 -06:00
|
|
|
m.status = "Press ctrl+s to send"
|
2024-03-13 21:07:41 -06:00
|
|
|
case msgResponseError:
|
|
|
|
m.waitingForReply = false
|
|
|
|
m.status = "Press ctrl+s to send"
|
|
|
|
m.err = error(msg)
|
2024-03-13 17:07:29 -06:00
|
|
|
case msgConversationTitleChanged:
|
|
|
|
title := string(msg)
|
|
|
|
m.conversation.Title = title
|
|
|
|
if m.persistence {
|
|
|
|
err := m.ctx.Store.SaveConversation(m.conversation)
|
|
|
|
if err != nil {
|
|
|
|
cmds = append(cmds, wrapError(err))
|
|
|
|
}
|
|
|
|
}
|
2024-03-13 20:54:25 -06:00
|
|
|
case msgError:
|
|
|
|
m.err = error(msg)
|
2024-03-12 01:10:54 -06:00
|
|
|
}
|
|
|
|
|
2024-03-13 15:20:03 -06:00
|
|
|
var cmd tea.Cmd
|
2024-03-13 23:58:31 -06:00
|
|
|
m.spinner, cmd = m.spinner.Update(msg)
|
2024-03-12 01:10:54 -06:00
|
|
|
if cmd != nil {
|
2024-03-13 23:58:31 -06:00
|
|
|
cmds = append(cmds, cmd)
|
2024-03-12 01:10:54 -06:00
|
|
|
}
|
|
|
|
|
2024-03-29 13:25:16 -06:00
|
|
|
|
|
|
|
prevInputLineCnt := m.input.LineCount()
|
2024-03-13 23:58:31 -06:00
|
|
|
inputCaptured := false
|
|
|
|
m.input, cmd = m.input.Update(msg)
|
2024-03-12 01:10:54 -06:00
|
|
|
if cmd != nil {
|
2024-03-13 23:58:31 -06:00
|
|
|
inputCaptured = true
|
|
|
|
cmds = append(cmds, cmd)
|
|
|
|
}
|
|
|
|
|
|
|
|
if !inputCaptured {
|
|
|
|
m.content, cmd = m.content.Update(msg)
|
|
|
|
if cmd != nil {
|
|
|
|
cmds = append(cmds, cmd)
|
|
|
|
}
|
2024-03-12 01:10:54 -06:00
|
|
|
}
|
|
|
|
|
2024-03-22 20:52:56 -06:00
|
|
|
if m.width > 0 {
|
|
|
|
m.cache.header = m.headerView()
|
|
|
|
m.cache.footer = m.footerView()
|
|
|
|
m.cache.error = m.errorView()
|
2024-03-29 13:25:16 -06:00
|
|
|
|
|
|
|
fixedHeight := height(m.cache.header) + height(m.cache.error) + height(m.cache.footer)
|
|
|
|
|
|
|
|
// calculate clamped input height to accomodate input text
|
|
|
|
newHeight := max(4, min((m.height-fixedHeight-1)/2, m.input.LineCount()))
|
|
|
|
m.input.SetHeight(newHeight)
|
2024-03-22 20:52:56 -06:00
|
|
|
m.cache.input = m.inputView()
|
2024-03-29 13:25:16 -06:00
|
|
|
|
|
|
|
m.content.Height = m.height - height(m.cache.input) - fixedHeight
|
2024-03-22 20:52:56 -06:00
|
|
|
m.cache.content = m.contentView()
|
|
|
|
}
|
|
|
|
|
2024-03-29 13:25:16 -06:00
|
|
|
// this is a pretty nasty hack to ensure the input area viewport doesn't
|
|
|
|
// scroll below its content, which can happen when the input viewport
|
|
|
|
// height has grown, or previously entered lines have been deleted
|
|
|
|
if prevInputLineCnt != m.input.LineCount() {
|
|
|
|
// dist is the distance we'd need to scroll up from the current cursor
|
|
|
|
// position to position the last input line at the bottom of the
|
|
|
|
// viewport. if negative, we're already scrolled above the bottom
|
|
|
|
dist := m.input.Line() - (m.input.LineCount() - m.input.Height())
|
|
|
|
if dist > 0 {
|
|
|
|
for i := 0; i < dist; i++ {
|
|
|
|
// move cursor up until content reaches the bottom of the viewport
|
|
|
|
m.input.CursorUp()
|
|
|
|
}
|
|
|
|
m.input, cmd = m.input.Update(nil)
|
|
|
|
cmds = append(cmds, cmd)
|
|
|
|
for i := 0; i < dist; i++ {
|
|
|
|
// move cursor back down to its previous position
|
|
|
|
m.input.CursorDown()
|
|
|
|
}
|
|
|
|
m.input, cmd = m.input.Update(nil)
|
|
|
|
cmds = append(cmds, cmd)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-03-13 23:58:31 -06:00
|
|
|
return m, tea.Batch(cmds...)
|
2024-03-12 01:10:54 -06:00
|
|
|
}
|
|
|
|
|
2024-03-22 20:52:56 -06:00
|
|
|
func height(str string) int {
|
|
|
|
if str == "" {
|
|
|
|
return 0
|
|
|
|
}
|
|
|
|
return strings.Count(str, "\n") + 1
|
|
|
|
}
|
|
|
|
|
2024-03-29 09:48:50 -06:00
|
|
|
func truncateToCellWidth(str string, width int, tail string) string {
|
|
|
|
cellWidth := ansi.PrintableRuneWidth(str)
|
|
|
|
if cellWidth <= width {
|
|
|
|
return str
|
|
|
|
}
|
|
|
|
tailWidth := ansi.PrintableRuneWidth(tail)
|
|
|
|
for {
|
|
|
|
str = str[:len(str)-((cellWidth+tailWidth)-width)]
|
|
|
|
cellWidth = ansi.PrintableRuneWidth(str)
|
|
|
|
if cellWidth+tailWidth <= max(width, 0) {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return str + tail
|
|
|
|
}
|
|
|
|
|
2024-03-12 01:10:54 -06:00
|
|
|
func (m model) View() string {
|
2024-03-14 11:55:21 -06:00
|
|
|
if m.width == 0 {
|
2024-03-13 13:52:41 -06:00
|
|
|
// this is the case upon initial startup, but it's also a safe bet that
|
|
|
|
// we can just skip rendering if the terminal is really 0 width...
|
2024-03-14 00:39:25 -06:00
|
|
|
// without this, the m.*View() functions may crash
|
2024-03-13 13:52:41 -06:00
|
|
|
return ""
|
|
|
|
}
|
2024-03-13 20:54:25 -06:00
|
|
|
|
|
|
|
sections := make([]string, 0, 6)
|
2024-03-22 20:52:56 -06:00
|
|
|
sections = append(sections, m.cache.header)
|
|
|
|
sections = append(sections, m.cache.content)
|
|
|
|
if m.cache.error != "" {
|
|
|
|
sections = append(sections, m.cache.error)
|
2024-03-13 20:54:25 -06:00
|
|
|
}
|
2024-03-22 20:52:56 -06:00
|
|
|
sections = append(sections, m.cache.input)
|
|
|
|
sections = append(sections, m.cache.footer)
|
2024-03-13 20:54:25 -06:00
|
|
|
|
2024-03-12 01:10:54 -06:00
|
|
|
return lipgloss.JoinVertical(
|
|
|
|
lipgloss.Left,
|
2024-03-13 20:54:25 -06:00
|
|
|
sections...,
|
2024-03-12 01:10:54 -06:00
|
|
|
)
|
|
|
|
}
|
|
|
|
|
2024-03-13 13:14:03 -06:00
|
|
|
func (m *model) headerView() string {
|
2024-03-29 09:48:50 -06:00
|
|
|
titleStyle := lipgloss.NewStyle().Bold(true)
|
2024-03-13 13:14:03 -06:00
|
|
|
var title string
|
|
|
|
if m.conversation != nil && m.conversation.Title != "" {
|
|
|
|
title = m.conversation.Title
|
|
|
|
} else {
|
|
|
|
title = "Untitled"
|
|
|
|
}
|
2024-03-29 09:48:50 -06:00
|
|
|
title = truncateToCellWidth(title, m.width-headerStyle.GetHorizontalPadding(), "...")
|
2024-03-13 13:14:03 -06:00
|
|
|
part := titleStyle.Render(title)
|
2024-03-13 21:07:41 -06:00
|
|
|
return headerStyle.Width(m.width).Render(part)
|
2024-03-13 13:14:03 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
func (m *model) contentView() string {
|
|
|
|
return m.content.View()
|
|
|
|
}
|
|
|
|
|
2024-03-13 20:54:25 -06:00
|
|
|
func (m *model) errorView() string {
|
|
|
|
if m.err == nil {
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
return lipgloss.NewStyle().
|
2024-03-13 21:07:41 -06:00
|
|
|
Width(m.width).
|
|
|
|
AlignHorizontal(lipgloss.Center).
|
2024-03-13 20:54:25 -06:00
|
|
|
Bold(true).
|
|
|
|
Foreground(lipgloss.Color("1")).
|
|
|
|
Render(fmt.Sprintf("%s", m.err))
|
|
|
|
}
|
|
|
|
|
2024-03-13 13:14:03 -06:00
|
|
|
func (m *model) inputView() string {
|
|
|
|
return m.input.View()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *model) footerView() string {
|
2024-03-13 15:20:03 -06:00
|
|
|
segmentStyle := lipgloss.NewStyle().PaddingLeft(1).PaddingRight(1).Faint(true)
|
2024-03-13 13:52:41 -06:00
|
|
|
segmentSeparator := "|"
|
|
|
|
|
2024-03-14 00:39:25 -06:00
|
|
|
savingStyle := segmentStyle.Copy().Bold(true)
|
2024-03-13 15:20:03 -06:00
|
|
|
saving := ""
|
|
|
|
if m.persistence {
|
2024-03-14 00:39:25 -06:00
|
|
|
saving = savingStyle.Foreground(lipgloss.Color("2")).Render("✅💾")
|
2024-03-13 15:20:03 -06:00
|
|
|
} else {
|
2024-03-14 00:39:25 -06:00
|
|
|
saving = savingStyle.Foreground(lipgloss.Color("1")).Render("❌💾")
|
2024-03-13 15:20:03 -06:00
|
|
|
}
|
|
|
|
|
2024-03-13 23:58:31 -06:00
|
|
|
status := m.status
|
|
|
|
if m.waitingForReply {
|
|
|
|
status += m.spinner.View()
|
|
|
|
}
|
|
|
|
|
2024-03-13 13:52:41 -06:00
|
|
|
leftSegments := []string{
|
2024-03-13 15:20:03 -06:00
|
|
|
saving,
|
2024-03-14 11:55:31 -06:00
|
|
|
segmentStyle.Render(status),
|
2024-03-13 13:52:41 -06:00
|
|
|
}
|
|
|
|
rightSegments := []string{
|
|
|
|
segmentStyle.Render(fmt.Sprintf("Model: %s", *m.ctx.Config.Defaults.Model)),
|
|
|
|
}
|
|
|
|
|
|
|
|
left := strings.Join(leftSegments, segmentSeparator)
|
|
|
|
right := strings.Join(rightSegments, segmentSeparator)
|
2024-03-13 13:14:03 -06:00
|
|
|
|
2024-03-13 20:54:25 -06:00
|
|
|
totalWidth := lipgloss.Width(left) + lipgloss.Width(right)
|
|
|
|
remaining := m.width - totalWidth
|
2024-03-13 13:52:41 -06:00
|
|
|
|
2024-03-13 13:14:03 -06:00
|
|
|
var padding string
|
2024-03-13 13:52:41 -06:00
|
|
|
if remaining > 0 {
|
|
|
|
padding = strings.Repeat(" ", remaining)
|
2024-03-13 13:14:03 -06:00
|
|
|
}
|
|
|
|
|
2024-03-13 13:52:41 -06:00
|
|
|
footer := left + padding + right
|
|
|
|
if remaining < 0 {
|
2024-03-29 09:48:50 -06:00
|
|
|
footer = truncateToCellWidth(footer, m.width, "...")
|
2024-03-13 13:52:41 -06:00
|
|
|
}
|
2024-03-14 00:39:25 -06:00
|
|
|
return footerStyle.Width(m.width).Render(footer)
|
2024-03-13 13:14:03 -06:00
|
|
|
}
|
|
|
|
|
2024-03-12 01:10:54 -06:00
|
|
|
func initialModel(ctx *lmcli.Context, convShortname string) model {
|
|
|
|
m := model{
|
|
|
|
ctx: ctx,
|
|
|
|
convShortname: convShortname,
|
2024-03-13 17:05:42 -06:00
|
|
|
conversation: &models.Conversation{},
|
|
|
|
persistence: true,
|
2024-03-12 01:10:54 -06:00
|
|
|
|
2024-03-15 00:44:42 -06:00
|
|
|
stopSignal: make(chan interface{}),
|
2024-03-12 20:05:48 -06:00
|
|
|
replyChan: make(chan models.Message),
|
|
|
|
replyChunkChan: make(chan string),
|
2024-03-15 23:49:04 -06:00
|
|
|
|
2024-03-16 18:25:42 -06:00
|
|
|
wrap: true,
|
2024-03-15 23:49:04 -06:00
|
|
|
selectedMessage: -1,
|
2024-03-22 20:52:56 -06:00
|
|
|
|
|
|
|
cache: &uiCache{},
|
2024-03-12 01:10:54 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
m.content = viewport.New(0, 0)
|
|
|
|
|
|
|
|
m.input = textarea.New()
|
2024-03-15 18:37:08 -06:00
|
|
|
m.input.CharLimit = 0
|
2024-03-12 01:10:54 -06:00
|
|
|
m.input.Placeholder = "Enter a message"
|
|
|
|
|
|
|
|
m.input.ShowLineNumbers = false
|
|
|
|
m.input.Focus()
|
2024-03-28 00:53:39 -06:00
|
|
|
m.input.FocusedStyle.CursorLine = lipgloss.NewStyle()
|
|
|
|
m.input.FocusedStyle.Base = lipgloss.NewStyle().
|
2024-03-29 13:25:16 -06:00
|
|
|
Border(lipgloss.RoundedBorder(), true, true, true, false)
|
2024-03-28 00:53:39 -06:00
|
|
|
m.input.BlurredStyle.Base = lipgloss.NewStyle().
|
|
|
|
Faint(true).
|
2024-03-29 13:25:16 -06:00
|
|
|
Border(lipgloss.RoundedBorder(), true, true, true, false)
|
2024-03-12 01:10:54 -06:00
|
|
|
|
2024-03-13 23:58:31 -06:00
|
|
|
m.spinner = spinner.New(spinner.WithSpinner(
|
|
|
|
spinner.Spinner{
|
|
|
|
Frames: []string{
|
|
|
|
". ",
|
|
|
|
".. ",
|
|
|
|
"...",
|
|
|
|
".. ",
|
|
|
|
". ",
|
|
|
|
" ",
|
|
|
|
},
|
|
|
|
FPS: time.Second / 3,
|
|
|
|
},
|
|
|
|
))
|
2024-03-12 01:10:54 -06:00
|
|
|
|
2024-03-12 12:33:57 -06:00
|
|
|
m.waitingForReply = false
|
2024-03-12 11:10:40 -06:00
|
|
|
m.status = "Press ctrl+s to send"
|
2024-03-12 01:10:54 -06:00
|
|
|
return m
|
|
|
|
}
|
|
|
|
|
2024-03-15 23:49:04 -06:00
|
|
|
// fraction is the fraction of the total screen height into view the offset
|
|
|
|
// should be scrolled into view. 0.5 = items will be snapped to middle of
|
|
|
|
// view
|
|
|
|
func scrollIntoView(vp *viewport.Model, offset int, fraction float32) {
|
|
|
|
currentOffset := vp.YOffset
|
|
|
|
if offset >= currentOffset && offset < currentOffset+vp.Height {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
distance := currentOffset - offset
|
|
|
|
if distance < 0 {
|
|
|
|
// we should scroll down until it just comes into view
|
|
|
|
vp.SetYOffset(currentOffset - (distance + (vp.Height - int(float32(vp.Height)*fraction))) + 1)
|
|
|
|
} else {
|
|
|
|
// we should scroll up
|
|
|
|
vp.SetYOffset(currentOffset - distance - int(float32(vp.Height)*fraction))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-03-12 11:50:10 -06:00
|
|
|
func (m *model) handleMessagesKey(msg tea.KeyMsg) tea.Cmd {
|
2024-03-12 01:10:54 -06:00
|
|
|
switch msg.String() {
|
2024-03-12 11:50:10 -06:00
|
|
|
case "tab":
|
|
|
|
m.focus = focusInput
|
2024-03-15 23:49:04 -06:00
|
|
|
m.updateContent()
|
2024-03-12 11:50:10 -06:00
|
|
|
m.input.Focus()
|
2024-03-16 15:56:45 -06:00
|
|
|
case "e":
|
|
|
|
message := m.messages[m.selectedMessage]
|
|
|
|
cmd := openTempfileEditor("message.*.md", message.Content, "# Edit the message below\n")
|
|
|
|
m.editorTarget = selectedMessage
|
|
|
|
return cmd
|
2024-03-15 23:49:04 -06:00
|
|
|
case "ctrl+k":
|
|
|
|
if m.selectedMessage > 0 && len(m.messages) == len(m.messageOffsets) {
|
|
|
|
m.selectedMessage--
|
|
|
|
m.updateContent()
|
|
|
|
offset := m.messageOffsets[m.selectedMessage]
|
|
|
|
scrollIntoView(&m.content, offset, 0.1)
|
|
|
|
}
|
|
|
|
case "ctrl+j":
|
|
|
|
if m.selectedMessage < len(m.messages)-1 && len(m.messages) == len(m.messageOffsets) {
|
|
|
|
m.selectedMessage++
|
|
|
|
m.updateContent()
|
|
|
|
offset := m.messageOffsets[m.selectedMessage]
|
|
|
|
scrollIntoView(&m.content, offset, 0.1)
|
|
|
|
}
|
2024-03-17 12:16:10 -06:00
|
|
|
case "ctrl+r":
|
2024-03-22 11:51:01 -06:00
|
|
|
// resubmit the conversation with all messages up until and including the selected message
|
|
|
|
if m.waitingForReply || len(m.messages) == 0 {
|
2024-03-17 12:16:10 -06:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
m.messages = m.messages[:m.selectedMessage+1]
|
2024-03-26 01:59:39 -06:00
|
|
|
m.messageCache = m.messageCache[:m.selectedMessage+1]
|
2024-03-17 12:16:10 -06:00
|
|
|
m.updateContent()
|
|
|
|
m.content.GotoBottom()
|
|
|
|
return m.promptLLM()
|
2024-03-12 11:50:10 -06:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *model) handleInputKey(msg tea.KeyMsg) tea.Cmd {
|
|
|
|
switch msg.String() {
|
|
|
|
case "esc":
|
|
|
|
m.focus = focusMessages
|
2024-03-26 01:59:39 -06:00
|
|
|
if len(m.messages) > 0 {
|
|
|
|
if m.selectedMessage < 0 || m.selectedMessage >= len(m.messages) {
|
|
|
|
m.selectedMessage = len(m.messages) - 1
|
|
|
|
}
|
|
|
|
offset := m.messageOffsets[m.selectedMessage]
|
|
|
|
scrollIntoView(&m.content, offset, 0.1)
|
2024-03-15 23:49:04 -06:00
|
|
|
}
|
|
|
|
m.updateContent()
|
2024-03-12 11:50:10 -06:00
|
|
|
m.input.Blur()
|
2024-03-12 01:10:54 -06:00
|
|
|
case "ctrl+s":
|
2024-03-12 11:10:40 -06:00
|
|
|
userInput := strings.TrimSpace(m.input.Value())
|
|
|
|
if strings.TrimSpace(userInput) == "" {
|
2024-03-12 01:10:54 -06:00
|
|
|
return nil
|
|
|
|
}
|
2024-03-13 15:20:03 -06:00
|
|
|
|
2024-03-14 11:56:03 -06:00
|
|
|
if len(m.messages) > 0 && m.messages[len(m.messages)-1].Role == models.MessageRoleUser {
|
|
|
|
return wrapError(fmt.Errorf("Can't reply to a user message"))
|
|
|
|
}
|
|
|
|
|
2024-03-13 15:20:03 -06:00
|
|
|
reply := models.Message{
|
2024-03-12 11:10:40 -06:00
|
|
|
Role: models.MessageRoleUser,
|
|
|
|
Content: userInput,
|
2024-03-13 15:20:03 -06:00
|
|
|
}
|
|
|
|
|
2024-03-13 17:05:42 -06:00
|
|
|
if m.persistence {
|
|
|
|
var err error
|
|
|
|
if m.conversation.ID == 0 {
|
|
|
|
err = m.ctx.Store.SaveConversation(m.conversation)
|
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
return wrapError(err)
|
|
|
|
}
|
|
|
|
|
2024-03-22 11:51:01 -06:00
|
|
|
// ensure all messages up to the one we're about to add are persisted
|
2024-03-17 12:16:10 -06:00
|
|
|
cmd := m.persistConversation()
|
2024-03-13 15:20:03 -06:00
|
|
|
if cmd != nil {
|
|
|
|
return cmd
|
|
|
|
}
|
2024-03-22 11:51:01 -06:00
|
|
|
|
2024-03-13 15:20:03 -06:00
|
|
|
savedReply, err := m.ctx.Store.AddReply(m.conversation, reply)
|
|
|
|
if err != nil {
|
|
|
|
return wrapError(err)
|
|
|
|
}
|
|
|
|
reply = *savedReply
|
|
|
|
}
|
|
|
|
|
|
|
|
m.input.SetValue("")
|
|
|
|
m.addMessage(reply)
|
2024-03-12 11:10:40 -06:00
|
|
|
|
|
|
|
m.updateContent()
|
|
|
|
m.content.GotoBottom()
|
2024-03-14 11:56:03 -06:00
|
|
|
return m.promptLLM()
|
2024-03-16 15:56:45 -06:00
|
|
|
case "ctrl+e":
|
|
|
|
cmd := openTempfileEditor("message.*.md", m.input.Value(), "# Edit your input below\n")
|
|
|
|
m.editorTarget = input
|
|
|
|
return cmd
|
2024-03-12 01:10:54 -06:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *model) loadConversation(shortname string) tea.Cmd {
|
|
|
|
return func() tea.Msg {
|
|
|
|
if shortname == "" {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
c, err := m.ctx.Store.ConversationByShortName(shortname)
|
|
|
|
if err != nil {
|
2024-03-13 21:07:41 -06:00
|
|
|
return msgError(fmt.Errorf("Could not lookup conversation: %v", err))
|
2024-03-12 01:10:54 -06:00
|
|
|
}
|
|
|
|
if c.ID == 0 {
|
2024-03-13 21:07:41 -06:00
|
|
|
return msgError(fmt.Errorf("Conversation not found: %s", shortname))
|
2024-03-12 01:10:54 -06:00
|
|
|
}
|
|
|
|
return msgConversationLoaded(c)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *model) loadMessages(c *models.Conversation) tea.Cmd {
|
|
|
|
return func() tea.Msg {
|
|
|
|
messages, err := m.ctx.Store.Messages(c)
|
|
|
|
if err != nil {
|
|
|
|
return msgError(fmt.Errorf("Could not load conversation messages: %v\n", err))
|
|
|
|
}
|
|
|
|
return msgMessagesLoaded(messages)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-03-12 20:05:48 -06:00
|
|
|
func (m *model) waitForReply() tea.Cmd {
|
|
|
|
return func() tea.Msg {
|
2024-03-13 17:05:42 -06:00
|
|
|
return msgAssistantReply(<-m.replyChan)
|
2024-03-12 20:05:48 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *model) waitForChunk() tea.Cmd {
|
2024-03-12 01:10:54 -06:00
|
|
|
return func() tea.Msg {
|
2024-03-12 20:05:48 -06:00
|
|
|
return msgResponseChunk(<-m.replyChunkChan)
|
2024-03-12 01:10:54 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-03-13 17:07:29 -06:00
|
|
|
func (m *model) generateConversationTitle() tea.Cmd {
|
|
|
|
return func() tea.Msg {
|
|
|
|
title, err := cmdutil.GenerateTitle(m.ctx, m.conversation)
|
|
|
|
if err != nil {
|
|
|
|
return msgError(err)
|
|
|
|
}
|
|
|
|
return msgConversationTitleChanged(title)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-03-12 01:10:54 -06:00
|
|
|
func (m *model) promptLLM() tea.Cmd {
|
2024-03-14 11:56:03 -06:00
|
|
|
m.waitingForReply = true
|
|
|
|
m.status = "Press ctrl+c to cancel"
|
|
|
|
|
2024-03-12 01:10:54 -06:00
|
|
|
return func() tea.Msg {
|
|
|
|
completionProvider, err := m.ctx.GetCompletionProvider(*m.ctx.Config.Defaults.Model)
|
|
|
|
if err != nil {
|
|
|
|
return msgError(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
requestParams := models.RequestParameters{
|
|
|
|
Model: *m.ctx.Config.Defaults.Model,
|
|
|
|
MaxTokens: *m.ctx.Config.Defaults.MaxTokens,
|
|
|
|
Temperature: *m.ctx.Config.Defaults.Temperature,
|
2024-03-12 23:09:55 -06:00
|
|
|
ToolBag: m.ctx.EnabledTools,
|
2024-03-12 01:10:54 -06:00
|
|
|
}
|
|
|
|
|
2024-03-12 20:05:48 -06:00
|
|
|
replyHandler := func(msg models.Message) {
|
|
|
|
m.replyChan <- msg
|
|
|
|
}
|
|
|
|
|
2024-03-15 00:44:42 -06:00
|
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
|
|
|
|
|
|
canceled := false
|
|
|
|
go func() {
|
|
|
|
select {
|
|
|
|
case <-m.stopSignal:
|
|
|
|
canceled = true
|
|
|
|
cancel()
|
|
|
|
}
|
|
|
|
}()
|
2024-03-12 12:33:57 -06:00
|
|
|
|
2024-03-13 21:07:41 -06:00
|
|
|
resp, err := completionProvider.CreateChatCompletionStream(
|
2024-03-12 20:05:48 -06:00
|
|
|
ctx, requestParams, m.messages, replyHandler, m.replyChunkChan,
|
2024-03-12 01:10:54 -06:00
|
|
|
)
|
|
|
|
|
2024-03-15 00:44:42 -06:00
|
|
|
if err != nil && !canceled {
|
2024-03-13 21:07:41 -06:00
|
|
|
return msgResponseError(err)
|
|
|
|
}
|
2024-03-15 00:44:42 -06:00
|
|
|
|
2024-03-12 01:10:54 -06:00
|
|
|
return msgResponseEnd(resp)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-03-17 12:16:10 -06:00
|
|
|
func (m *model) persistConversation() tea.Cmd {
|
|
|
|
existingMessages, err := m.ctx.Store.Messages(m.conversation)
|
|
|
|
if err != nil {
|
|
|
|
return wrapError(fmt.Errorf("Could not retrieve existing conversation messages while trying to save: %v", err))
|
|
|
|
}
|
|
|
|
|
|
|
|
existingById := make(map[uint]*models.Message, len(existingMessages))
|
|
|
|
for _, msg := range existingMessages {
|
|
|
|
existingById[msg.ID] = &msg
|
|
|
|
}
|
|
|
|
|
|
|
|
currentById := make(map[uint]*models.Message, len(m.messages))
|
|
|
|
for _, msg := range m.messages {
|
|
|
|
currentById[msg.ID] = &msg
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, msg := range existingMessages {
|
|
|
|
_, ok := currentById[msg.ID]
|
|
|
|
if !ok {
|
|
|
|
err := m.ctx.Store.DeleteMessage(&msg)
|
|
|
|
if err != nil {
|
|
|
|
return wrapError(fmt.Errorf("Failed to remove messages: %v", err))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-03-13 15:20:03 -06:00
|
|
|
for i, msg := range m.messages {
|
|
|
|
if msg.ID > 0 {
|
2024-03-17 12:16:10 -06:00
|
|
|
exist, ok := existingById[msg.ID]
|
|
|
|
if ok {
|
|
|
|
if msg.Content == exist.Content {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
// update message when contents don't match that of store
|
|
|
|
err := m.ctx.Store.UpdateMessage(&msg)
|
|
|
|
if err != nil {
|
|
|
|
return wrapError(err)
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
// this would be quite odd... and I'm not sure how to handle
|
|
|
|
// it at the time of writing this
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
newMessage, err := m.ctx.Store.AddReply(m.conversation, msg)
|
|
|
|
if err != nil {
|
|
|
|
return wrapError(err)
|
|
|
|
}
|
|
|
|
m.setMessage(i, *newMessage)
|
2024-03-13 15:20:03 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2024-03-26 01:59:39 -06:00
|
|
|
func (m *model) renderMessageHeading(i int, message *models.Message) string {
|
|
|
|
icon := ""
|
|
|
|
friendly := message.Role.FriendlyRole()
|
|
|
|
style := lipgloss.NewStyle().Faint(true).Bold(true)
|
|
|
|
|
|
|
|
switch message.Role {
|
|
|
|
case models.MessageRoleSystem:
|
|
|
|
icon = "⚙️"
|
|
|
|
case models.MessageRoleUser:
|
|
|
|
style = userStyle
|
|
|
|
case models.MessageRoleAssistant:
|
|
|
|
style = assistantStyle
|
|
|
|
case models.MessageRoleToolCall:
|
|
|
|
style = assistantStyle
|
|
|
|
friendly = models.MessageRoleAssistant.FriendlyRole()
|
|
|
|
case models.MessageRoleToolResult:
|
|
|
|
icon = "🔧"
|
|
|
|
}
|
|
|
|
|
|
|
|
user := style.Render(icon + friendly)
|
|
|
|
|
|
|
|
var prefix string
|
|
|
|
var suffix string
|
|
|
|
|
|
|
|
faint := lipgloss.NewStyle().Faint(true)
|
|
|
|
if m.focus == focusMessages {
|
|
|
|
if i == m.selectedMessage {
|
|
|
|
prefix = "> "
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if message.ID == 0 {
|
|
|
|
suffix += faint.Render(" (not saved)")
|
|
|
|
}
|
|
|
|
|
|
|
|
return headingStyle.Render(prefix + user + suffix)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *model) renderMessage(msg *models.Message) string {
|
|
|
|
sb := &strings.Builder{}
|
|
|
|
sb.Grow(len(msg.Content) * 2)
|
|
|
|
if msg.Content != "" {
|
|
|
|
err := m.ctx.Chroma.Highlight(sb, msg.Content)
|
|
|
|
if err != nil {
|
|
|
|
sb.Reset()
|
|
|
|
sb.WriteString(msg.Content)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
var toolString string
|
|
|
|
switch msg.Role {
|
|
|
|
case models.MessageRoleToolCall:
|
|
|
|
bytes, err := yaml.Marshal(msg.ToolCalls)
|
|
|
|
if err != nil {
|
|
|
|
toolString = "Could not serialize ToolCalls"
|
|
|
|
} else {
|
|
|
|
toolString = "tool_calls:\n" + string(bytes)
|
|
|
|
}
|
|
|
|
case models.MessageRoleToolResult:
|
|
|
|
if !m.showToolResults {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
|
|
|
|
type renderedResult struct {
|
|
|
|
ToolName string `yaml:"tool"`
|
|
|
|
Result any
|
|
|
|
}
|
|
|
|
|
|
|
|
var toolResults []renderedResult
|
|
|
|
for _, result := range msg.ToolResults {
|
|
|
|
var jsonResult interface{}
|
|
|
|
err := json.Unmarshal([]byte(result.Result), &jsonResult)
|
|
|
|
if err != nil {
|
|
|
|
// If parsing as JSON fails, treat Result as a plain string
|
|
|
|
toolResults = append(toolResults, renderedResult{
|
|
|
|
ToolName: result.ToolName,
|
|
|
|
Result: result.Result,
|
|
|
|
})
|
|
|
|
} else {
|
|
|
|
// If parsing as JSON succeeds, marshal the parsed JSON into YAML
|
|
|
|
toolResults = append(toolResults, renderedResult{
|
|
|
|
ToolName: result.ToolName,
|
|
|
|
Result: &jsonResult,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
bytes, err := yaml.Marshal(toolResults)
|
|
|
|
if err != nil {
|
|
|
|
toolString = "Could not serialize ToolResults"
|
|
|
|
} else {
|
|
|
|
toolString = "tool_results:\n" + string(bytes)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if toolString != "" {
|
|
|
|
toolString = strings.TrimRight(toolString, "\n")
|
|
|
|
if msg.Content != "" {
|
|
|
|
sb.WriteString("\n\n")
|
|
|
|
}
|
|
|
|
_ = m.ctx.Chroma.HighlightLang(sb, toolString, "yaml")
|
|
|
|
}
|
|
|
|
|
|
|
|
content := strings.TrimRight(sb.String(), "\n")
|
|
|
|
|
|
|
|
if m.wrap {
|
|
|
|
wrapWidth := m.content.Width - messageStyle.GetHorizontalPadding() - 2
|
|
|
|
content = wordwrap.String(content, wrapWidth)
|
|
|
|
}
|
|
|
|
|
|
|
|
return messageStyle.Width(0).Render(content)
|
|
|
|
}
|
|
|
|
|
2024-03-13 10:29:06 -06:00
|
|
|
func (m *model) setMessages(messages []models.Message) {
|
|
|
|
m.messages = messages
|
2024-03-26 01:59:39 -06:00
|
|
|
m.rebuildMessageCache()
|
2024-03-13 10:29:06 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
func (m *model) setMessage(i int, msg models.Message) {
|
|
|
|
if i >= len(m.messages) {
|
|
|
|
panic("i out of range")
|
|
|
|
}
|
|
|
|
m.messages[i] = msg
|
2024-03-26 01:59:39 -06:00
|
|
|
m.messageCache[i] = m.renderMessage(&msg)
|
2024-03-13 10:29:06 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
func (m *model) addMessage(msg models.Message) {
|
|
|
|
m.messages = append(m.messages, msg)
|
2024-03-26 01:59:39 -06:00
|
|
|
m.messageCache = append(m.messageCache, m.renderMessage(&msg))
|
2024-03-13 10:29:06 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
func (m *model) setMessageContents(i int, content string) {
|
|
|
|
if i >= len(m.messages) {
|
|
|
|
panic("i out of range")
|
|
|
|
}
|
|
|
|
m.messages[i].Content = content
|
2024-03-26 01:59:39 -06:00
|
|
|
m.messageCache[i] = m.renderMessage(&m.messages[i])
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *model) rebuildMessageCache() {
|
|
|
|
m.messageCache = make([]string, len(m.messages))
|
|
|
|
for i, msg := range m.messages {
|
|
|
|
m.messageCache[i] = m.renderMessage(&msg)
|
|
|
|
}
|
2024-03-13 10:29:06 -06:00
|
|
|
}
|
|
|
|
|
2024-03-12 01:10:54 -06:00
|
|
|
func (m *model) updateContent() {
|
2024-03-15 18:37:08 -06:00
|
|
|
atBottom := m.content.AtBottom()
|
2024-03-16 18:25:42 -06:00
|
|
|
m.content.SetContent(m.conversationView())
|
2024-03-15 18:37:08 -06:00
|
|
|
if atBottom {
|
|
|
|
// if we were at bottom before the update, scroll with the output
|
|
|
|
m.content.GotoBottom()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// render the conversation into a string
|
|
|
|
func (m *model) conversationView() string {
|
2024-03-12 01:10:54 -06:00
|
|
|
sb := strings.Builder{}
|
2024-03-15 23:49:04 -06:00
|
|
|
|
|
|
|
m.messageOffsets = make([]int, len(m.messages))
|
2024-03-26 01:59:39 -06:00
|
|
|
lineCnt := 1
|
2024-03-12 01:10:54 -06:00
|
|
|
for i, message := range m.messages {
|
2024-03-15 23:49:04 -06:00
|
|
|
m.messageOffsets[i] = lineCnt
|
|
|
|
|
2024-03-13 09:56:23 -06:00
|
|
|
switch message.Role {
|
2024-03-26 01:59:39 -06:00
|
|
|
case models.MessageRoleToolCall:
|
|
|
|
if !m.showToolResults && message.Content == "" {
|
|
|
|
continue
|
2024-03-15 18:37:08 -06:00
|
|
|
}
|
2024-03-26 01:59:39 -06:00
|
|
|
case models.MessageRoleToolResult:
|
|
|
|
if !m.showToolResults {
|
|
|
|
continue
|
2024-03-16 18:25:42 -06:00
|
|
|
}
|
2024-03-13 10:29:06 -06:00
|
|
|
}
|
2024-03-12 01:10:54 -06:00
|
|
|
|
2024-03-26 01:59:39 -06:00
|
|
|
heading := m.renderMessageHeading(i, &message)
|
|
|
|
sb.WriteString(heading)
|
|
|
|
sb.WriteString("\n")
|
|
|
|
lineCnt += lipgloss.Height(heading)
|
|
|
|
|
|
|
|
cached := m.messageCache[i]
|
|
|
|
sb.WriteString(cached)
|
|
|
|
sb.WriteString("\n")
|
|
|
|
lineCnt += lipgloss.Height(cached)
|
2024-03-12 01:10:54 -06:00
|
|
|
}
|
2024-03-26 01:59:39 -06:00
|
|
|
|
|
|
|
return sb.String()
|
2024-03-12 01:10:54 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
func Launch(ctx *lmcli.Context, convShortname string) error {
|
|
|
|
p := tea.NewProgram(initialModel(ctx, convShortname), tea.WithAltScreen())
|
|
|
|
if _, err := p.Run(); err != nil {
|
|
|
|
return fmt.Errorf("Error running program: %v", err)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|