2024-05-30 00:44:40 -06:00
|
|
|
package chat
|
2024-03-30 20:03:53 -06:00
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"strings"
|
2024-03-31 17:51:45 -06:00
|
|
|
"time"
|
2024-03-30 20:03:53 -06:00
|
|
|
|
|
|
|
cmdutil "git.mlow.ca/mlow/lmcli/pkg/cmd/util"
|
|
|
|
models "git.mlow.ca/mlow/lmcli/pkg/lmcli/model"
|
2024-05-30 00:44:40 -06:00
|
|
|
"git.mlow.ca/mlow/lmcli/pkg/tui/shared"
|
|
|
|
"git.mlow.ca/mlow/lmcli/pkg/tui/styles"
|
|
|
|
tuiutil "git.mlow.ca/mlow/lmcli/pkg/tui/util"
|
2024-05-22 10:25:16 -06:00
|
|
|
"github.com/charmbracelet/bubbles/cursor"
|
2024-03-31 17:51:45 -06:00
|
|
|
"github.com/charmbracelet/bubbles/spinner"
|
|
|
|
"github.com/charmbracelet/bubbles/textarea"
|
|
|
|
"github.com/charmbracelet/bubbles/viewport"
|
2024-03-30 20:03:53 -06:00
|
|
|
tea "github.com/charmbracelet/bubbletea"
|
|
|
|
"github.com/charmbracelet/lipgloss"
|
|
|
|
"github.com/muesli/reflow/wordwrap"
|
2024-05-22 10:57:38 -06:00
|
|
|
"github.com/muesli/reflow/wrap"
|
2024-03-30 20:03:53 -06:00
|
|
|
"gopkg.in/yaml.v2"
|
|
|
|
)
|
|
|
|
|
2024-03-30 20:29:35 -06:00
|
|
|
type focusState int
|
|
|
|
|
|
|
|
const (
|
|
|
|
focusInput focusState = iota
|
|
|
|
focusMessages
|
|
|
|
)
|
|
|
|
|
|
|
|
type editorTarget int
|
|
|
|
|
|
|
|
const (
|
|
|
|
input editorTarget = iota
|
|
|
|
selectedMessage
|
|
|
|
)
|
|
|
|
|
2024-03-30 20:03:53 -06:00
|
|
|
// custom tea.Msg types
|
|
|
|
type (
|
|
|
|
// sent on each chunk received from LLM
|
|
|
|
msgResponseChunk string
|
|
|
|
// sent when response is finished being received
|
|
|
|
msgResponseEnd string
|
2024-05-30 00:44:40 -06:00
|
|
|
// a special case of common.MsgError that stops the response waiting animation
|
2024-03-30 20:03:53 -06:00
|
|
|
msgResponseError error
|
|
|
|
// sent on each completed reply
|
|
|
|
msgAssistantReply models.Message
|
|
|
|
// sent when a conversation is (re)loaded
|
|
|
|
msgConversationLoaded *models.Conversation
|
|
|
|
// sent when a new conversation title is set
|
|
|
|
msgConversationTitleChanged string
|
|
|
|
// sent when a conversation's messages are laoded
|
|
|
|
msgMessagesLoaded []models.Message
|
|
|
|
)
|
|
|
|
|
2024-05-30 00:44:40 -06:00
|
|
|
type Model struct {
|
|
|
|
shared.State
|
2024-05-30 01:04:55 -06:00
|
|
|
shared.Sections
|
2024-03-31 17:51:45 -06:00
|
|
|
|
|
|
|
// app state
|
|
|
|
conversation *models.Conversation
|
2024-05-28 00:34:11 -06:00
|
|
|
rootMessages []models.Message
|
2024-03-31 17:51:45 -06:00
|
|
|
messages []models.Message
|
|
|
|
selectedMessage int
|
|
|
|
waitingForReply bool
|
|
|
|
editorTarget editorTarget
|
|
|
|
stopSignal chan struct{}
|
|
|
|
replyChan chan models.Message
|
|
|
|
replyChunkChan chan string
|
|
|
|
persistence bool // whether we will save new messages in the conversation
|
|
|
|
|
|
|
|
// ui state
|
|
|
|
focus focusState
|
|
|
|
wrap bool // whether message content is wrapped to viewport width
|
|
|
|
status string // a general status message
|
|
|
|
showToolResults bool // whether tool calls and results are shown
|
|
|
|
messageCache []string // cache of syntax highlighted and wrapped message content
|
|
|
|
messageOffsets []int
|
|
|
|
|
2024-05-30 01:04:55 -06:00
|
|
|
tokenCount uint
|
|
|
|
startTime time.Time
|
|
|
|
elapsed time.Duration
|
|
|
|
|
2024-03-31 17:51:45 -06:00
|
|
|
// ui elements
|
2024-05-22 10:25:16 -06:00
|
|
|
content viewport.Model
|
|
|
|
input textarea.Model
|
|
|
|
spinner spinner.Model
|
|
|
|
replyCursor cursor.Model // cursor to indicate incoming response
|
2024-03-31 17:51:45 -06:00
|
|
|
}
|
|
|
|
|
2024-05-30 01:18:31 -06:00
|
|
|
func Chat(state shared.State) Model {
|
2024-05-30 00:44:40 -06:00
|
|
|
m := Model{
|
2024-05-30 01:18:31 -06:00
|
|
|
State: state,
|
2024-03-31 17:51:45 -06:00
|
|
|
|
|
|
|
conversation: &models.Conversation{},
|
|
|
|
persistence: true,
|
|
|
|
|
|
|
|
stopSignal: make(chan struct{}),
|
|
|
|
replyChan: make(chan models.Message),
|
|
|
|
replyChunkChan: make(chan string),
|
|
|
|
|
|
|
|
wrap: true,
|
|
|
|
selectedMessage: -1,
|
|
|
|
|
|
|
|
content: viewport.New(0, 0),
|
|
|
|
input: textarea.New(),
|
|
|
|
spinner: spinner.New(spinner.WithSpinner(
|
|
|
|
spinner.Spinner{
|
|
|
|
Frames: []string{
|
|
|
|
". ",
|
|
|
|
".. ",
|
|
|
|
"...",
|
|
|
|
".. ",
|
|
|
|
". ",
|
|
|
|
" ",
|
|
|
|
},
|
|
|
|
FPS: time.Second / 3,
|
|
|
|
},
|
|
|
|
)),
|
2024-05-22 10:25:16 -06:00
|
|
|
replyCursor: cursor.New(),
|
2024-03-31 17:51:45 -06:00
|
|
|
}
|
|
|
|
|
2024-05-22 10:25:16 -06:00
|
|
|
m.replyCursor.SetChar(" ")
|
|
|
|
m.replyCursor.Focus()
|
|
|
|
|
2024-05-30 01:18:31 -06:00
|
|
|
system := state.Ctx.GetSystemPrompt()
|
2024-05-07 02:07:48 -06:00
|
|
|
if system != "" {
|
|
|
|
m.messages = []models.Message{{
|
|
|
|
Role: models.MessageRoleSystem,
|
|
|
|
Content: system,
|
|
|
|
}}
|
|
|
|
}
|
|
|
|
|
2024-03-31 17:51:45 -06:00
|
|
|
m.input.Focus()
|
|
|
|
m.input.MaxHeight = 0
|
|
|
|
m.input.CharLimit = 0
|
|
|
|
m.input.ShowLineNumbers = false
|
|
|
|
m.input.Placeholder = "Enter a message"
|
|
|
|
|
|
|
|
m.input.FocusedStyle.CursorLine = lipgloss.NewStyle()
|
|
|
|
m.input.FocusedStyle.Base = inputFocusedStyle
|
|
|
|
m.input.BlurredStyle.Base = inputBlurredStyle
|
|
|
|
|
|
|
|
m.waitingForReply = false
|
|
|
|
m.status = "Press ctrl+s to send"
|
|
|
|
return m
|
|
|
|
}
|
|
|
|
|
2024-03-30 20:03:53 -06:00
|
|
|
// styles
|
|
|
|
var (
|
|
|
|
messageHeadingStyle = 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)
|
|
|
|
|
|
|
|
inputFocusedStyle = lipgloss.NewStyle().
|
|
|
|
Border(lipgloss.RoundedBorder(), true, true, true, false)
|
|
|
|
|
|
|
|
inputBlurredStyle = lipgloss.NewStyle().
|
|
|
|
Faint(true).
|
|
|
|
Border(lipgloss.RoundedBorder(), true, true, true, false)
|
|
|
|
|
|
|
|
footerStyle = lipgloss.NewStyle()
|
|
|
|
)
|
|
|
|
|
2024-05-30 00:44:40 -06:00
|
|
|
func (m *Model) HandleInput(msg tea.KeyMsg) (bool, tea.Cmd) {
|
2024-03-31 17:51:45 -06:00
|
|
|
switch m.focus {
|
|
|
|
case focusInput:
|
2024-05-30 00:44:40 -06:00
|
|
|
consumed, cmd := m.HandleInputKey(msg)
|
2024-03-31 19:06:13 -06:00
|
|
|
if consumed {
|
|
|
|
return true, cmd
|
2024-03-31 17:51:45 -06:00
|
|
|
}
|
|
|
|
case focusMessages:
|
2024-03-31 19:06:13 -06:00
|
|
|
consumed, cmd := m.handleMessagesKey(msg)
|
|
|
|
if consumed {
|
|
|
|
return true, cmd
|
2024-03-31 17:51:45 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-03-30 20:03:53 -06:00
|
|
|
switch msg.String() {
|
|
|
|
case "esc":
|
2024-05-07 02:07:48 -06:00
|
|
|
if m.waitingForReply {
|
|
|
|
m.stopSignal <- struct{}{}
|
|
|
|
return true, nil
|
|
|
|
}
|
2024-03-31 19:06:13 -06:00
|
|
|
return true, func() tea.Msg {
|
2024-05-30 00:44:40 -06:00
|
|
|
return shared.MsgViewChange(shared.StateConversations)
|
2024-03-31 19:06:13 -06:00
|
|
|
}
|
|
|
|
case "ctrl+c":
|
|
|
|
if m.waitingForReply {
|
|
|
|
m.stopSignal <- struct{}{}
|
|
|
|
return true, nil
|
|
|
|
}
|
2024-03-30 20:03:53 -06:00
|
|
|
case "ctrl+p":
|
|
|
|
m.persistence = !m.persistence
|
2024-03-31 19:06:13 -06:00
|
|
|
return true, nil
|
2024-03-30 20:03:53 -06:00
|
|
|
case "ctrl+t":
|
|
|
|
m.showToolResults = !m.showToolResults
|
|
|
|
m.rebuildMessageCache()
|
|
|
|
m.updateContent()
|
2024-03-31 19:06:13 -06:00
|
|
|
return true, nil
|
2024-03-30 20:03:53 -06:00
|
|
|
case "ctrl+w":
|
|
|
|
m.wrap = !m.wrap
|
|
|
|
m.rebuildMessageCache()
|
|
|
|
m.updateContent()
|
2024-03-31 19:06:13 -06:00
|
|
|
return true, nil
|
2024-03-30 20:03:53 -06:00
|
|
|
}
|
2024-03-31 19:06:13 -06:00
|
|
|
return false, nil
|
2024-03-30 20:03:53 -06:00
|
|
|
}
|
|
|
|
|
2024-05-30 00:44:40 -06:00
|
|
|
func (m Model) Init() tea.Cmd {
|
2024-03-31 17:51:45 -06:00
|
|
|
return tea.Batch(
|
|
|
|
m.waitForChunk(),
|
|
|
|
m.waitForReply(),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
2024-05-30 00:44:40 -06:00
|
|
|
func (m *Model) HandleResize(width, height int) {
|
2024-05-30 01:04:55 -06:00
|
|
|
m.Width, m.Height = width, height
|
2024-04-01 11:05:36 -06:00
|
|
|
m.content.Width = width
|
|
|
|
m.input.SetWidth(width - m.input.FocusedStyle.Base.GetHorizontalFrameSize())
|
|
|
|
if len(m.messages) > 0 {
|
|
|
|
m.rebuildMessageCache()
|
|
|
|
m.updateContent()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-05-30 00:44:40 -06:00
|
|
|
func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
|
2024-03-30 20:03:53 -06:00
|
|
|
var cmds []tea.Cmd
|
|
|
|
switch msg := msg.(type) {
|
2024-05-30 00:44:40 -06:00
|
|
|
case shared.MsgViewEnter:
|
2024-05-22 10:25:16 -06:00
|
|
|
// wake up spinners and cursors
|
|
|
|
cmds = append(cmds, cursor.Blink, m.spinner.Tick)
|
|
|
|
|
2024-05-30 00:44:40 -06:00
|
|
|
if m.State.Values.ConvShortname != "" && m.conversation.ShortName.String != m.State.Values.ConvShortname {
|
|
|
|
cmds = append(cmds, m.loadConversation(m.State.Values.ConvShortname))
|
2024-03-31 17:51:45 -06:00
|
|
|
}
|
2024-05-22 10:25:16 -06:00
|
|
|
|
2024-05-07 02:07:48 -06:00
|
|
|
m.rebuildMessageCache()
|
|
|
|
m.updateContent()
|
2024-03-31 17:51:45 -06:00
|
|
|
case tea.WindowSizeMsg:
|
2024-05-30 00:44:40 -06:00
|
|
|
m.HandleResize(msg.Width, msg.Height)
|
|
|
|
case tuiutil.MsgTempfileEditorClosed:
|
2024-03-30 20:03:53 -06:00
|
|
|
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
|
2024-05-30 00:44:40 -06:00
|
|
|
err := m.State.Ctx.Store.UpdateMessage(&m.messages[m.selectedMessage])
|
2024-03-30 20:03:53 -06:00
|
|
|
if err != nil {
|
2024-05-30 00:44:40 -06:00
|
|
|
cmds = append(cmds, shared.WrapError(fmt.Errorf("Could not save edited message: %v", err)))
|
2024-03-30 20:03:53 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
m.updateContent()
|
|
|
|
}
|
|
|
|
case msgConversationLoaded:
|
|
|
|
m.conversation = (*models.Conversation)(msg)
|
2024-05-30 00:44:40 -06:00
|
|
|
m.rootMessages, _ = m.State.Ctx.Store.RootMessages(m.conversation.ID)
|
2024-03-30 20:03:53 -06:00
|
|
|
cmds = append(cmds, m.loadMessages(m.conversation))
|
|
|
|
case msgMessagesLoaded:
|
2024-04-02 00:53:29 -06:00
|
|
|
m.selectedMessage = len(msg) - 1
|
2024-05-07 02:07:48 -06:00
|
|
|
m.messages = msg
|
|
|
|
m.rebuildMessageCache()
|
2024-03-30 20:03:53 -06:00
|
|
|
m.updateContent()
|
2024-04-01 16:44:29 -06:00
|
|
|
m.content.GotoBottom()
|
2024-03-30 20:03:53 -06:00
|
|
|
case msgResponseChunk:
|
2024-05-30 12:52:23 -06:00
|
|
|
cmds = append(cmds, m.waitForChunk()) // wait for the next chunk
|
|
|
|
|
2024-03-30 20:03:53 -06:00
|
|
|
chunk := string(msg)
|
2024-05-22 10:25:16 -06:00
|
|
|
if chunk == "" {
|
|
|
|
break
|
|
|
|
}
|
|
|
|
|
2024-03-30 20:03:53 -06:00
|
|
|
last := len(m.messages) - 1
|
|
|
|
if last >= 0 && m.messages[last].Role.IsAssistant() {
|
2024-05-22 10:25:16 -06:00
|
|
|
// append chunk to existing message
|
2024-03-30 20:03:53 -06:00
|
|
|
m.setMessageContents(last, m.messages[last].Content+chunk)
|
|
|
|
} else {
|
2024-05-22 10:25:16 -06:00
|
|
|
// use chunk in new message
|
2024-03-30 20:03:53 -06:00
|
|
|
m.addMessage(models.Message{
|
|
|
|
Role: models.MessageRoleAssistant,
|
|
|
|
Content: chunk,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
m.updateContent()
|
2024-05-13 21:41:19 -06:00
|
|
|
|
2024-05-22 10:25:16 -06:00
|
|
|
// show cursor and reset blink interval (simulate typing)
|
|
|
|
m.replyCursor.Blink = false
|
|
|
|
cmds = append(cmds, m.replyCursor.BlinkCmd())
|
|
|
|
|
2024-05-13 21:41:19 -06:00
|
|
|
m.tokenCount++
|
|
|
|
m.elapsed = time.Now().Sub(m.startTime)
|
2024-03-30 20:03:53 -06:00
|
|
|
case msgAssistantReply:
|
2024-05-30 12:52:23 -06:00
|
|
|
cmds = append(cmds, m.waitForReply()) // wait for the next reply
|
|
|
|
|
2024-03-30 20:03:53 -06:00
|
|
|
reply := models.Message(msg)
|
|
|
|
reply.Content = strings.TrimSpace(reply.Content)
|
|
|
|
|
|
|
|
last := len(m.messages) - 1
|
|
|
|
if last < 0 {
|
|
|
|
panic("Unexpected empty messages handling msgAssistantReply")
|
|
|
|
}
|
|
|
|
|
|
|
|
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)
|
|
|
|
} else {
|
|
|
|
m.addMessage(reply)
|
|
|
|
}
|
|
|
|
|
|
|
|
if m.persistence {
|
2024-05-20 12:12:44 -06:00
|
|
|
err := m.persistConversation()
|
2024-03-30 20:03:53 -06:00
|
|
|
if err != nil {
|
2024-05-30 00:44:40 -06:00
|
|
|
cmds = append(cmds, shared.WrapError(err))
|
2024-03-30 20:03:53 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if m.conversation.Title == "" {
|
|
|
|
cmds = append(cmds, m.generateConversationTitle())
|
|
|
|
}
|
|
|
|
|
|
|
|
m.updateContent()
|
|
|
|
case msgResponseEnd:
|
|
|
|
m.waitingForReply = false
|
|
|
|
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()
|
|
|
|
m.status = "Press ctrl+s to send"
|
|
|
|
case msgResponseError:
|
|
|
|
m.waitingForReply = false
|
|
|
|
m.status = "Press ctrl+s to send"
|
2024-05-30 00:44:40 -06:00
|
|
|
m.State.Err = error(msg)
|
2024-05-22 10:25:16 -06:00
|
|
|
m.updateContent()
|
2024-03-30 20:03:53 -06:00
|
|
|
case msgConversationTitleChanged:
|
|
|
|
title := string(msg)
|
|
|
|
m.conversation.Title = title
|
|
|
|
if m.persistence {
|
2024-05-30 00:44:40 -06:00
|
|
|
err := m.State.Ctx.Store.UpdateConversation(m.conversation)
|
2024-03-30 20:03:53 -06:00
|
|
|
if err != nil {
|
2024-05-30 00:44:40 -06:00
|
|
|
cmds = append(cmds, shared.WrapError(err))
|
2024-03-30 20:03:53 -06:00
|
|
|
}
|
|
|
|
}
|
2024-05-22 10:25:16 -06:00
|
|
|
case cursor.BlinkMsg:
|
|
|
|
if m.waitingForReply {
|
|
|
|
// ensure we show updated "wait for response" cursor blink state
|
|
|
|
m.updateContent()
|
|
|
|
}
|
2024-03-30 20:03:53 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
var cmd tea.Cmd
|
|
|
|
m.spinner, cmd = m.spinner.Update(msg)
|
|
|
|
if cmd != nil {
|
|
|
|
cmds = append(cmds, cmd)
|
|
|
|
}
|
2024-05-22 10:25:16 -06:00
|
|
|
m.replyCursor, cmd = m.replyCursor.Update(msg)
|
|
|
|
if cmd != nil {
|
|
|
|
cmds = append(cmds, cmd)
|
|
|
|
}
|
2024-03-30 20:03:53 -06:00
|
|
|
|
|
|
|
prevInputLineCnt := m.input.LineCount()
|
|
|
|
inputCaptured := false
|
|
|
|
m.input, cmd = m.input.Update(msg)
|
|
|
|
if cmd != nil {
|
|
|
|
inputCaptured = true
|
|
|
|
cmds = append(cmds, cmd)
|
|
|
|
}
|
|
|
|
|
|
|
|
if !inputCaptured {
|
|
|
|
m.content, cmd = m.content.Update(msg)
|
|
|
|
if cmd != nil {
|
|
|
|
cmds = append(cmds, cmd)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// update views once window dimensions are known
|
2024-05-30 01:04:55 -06:00
|
|
|
if m.Width > 0 {
|
|
|
|
m.Header = m.headerView()
|
|
|
|
m.Footer = m.footerView()
|
|
|
|
m.Error = tuiutil.ErrorBanner(m.Err, m.Width)
|
|
|
|
fixedHeight := tuiutil.Height(m.Header) + tuiutil.Height(m.Error) + tuiutil.Height(m.Footer)
|
2024-03-30 20:03:53 -06:00
|
|
|
|
|
|
|
// calculate clamped input height to accomodate input text
|
2024-05-07 02:07:48 -06:00
|
|
|
// minimum 4 lines, maximum half of content area
|
2024-05-30 01:04:55 -06:00
|
|
|
newHeight := max(4, min((m.Height-fixedHeight-1)/2, m.input.LineCount()))
|
2024-03-30 20:03:53 -06:00
|
|
|
m.input.SetHeight(newHeight)
|
2024-05-30 01:04:55 -06:00
|
|
|
m.Input = m.input.View()
|
2024-03-30 20:03:53 -06:00
|
|
|
|
2024-05-07 02:07:48 -06:00
|
|
|
// remaining height towards content
|
2024-05-30 01:04:55 -06:00
|
|
|
m.content.Height = m.Height - fixedHeight - tuiutil.Height(m.Input)
|
|
|
|
m.Content = m.content.View()
|
2024-03-30 20:03:53 -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)
|
|
|
|
for i := 0; i < dist; i++ {
|
|
|
|
// move cursor back down to its previous position
|
|
|
|
m.input.CursorDown()
|
|
|
|
}
|
|
|
|
m.input, cmd = m.input.Update(nil)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-03-31 17:51:45 -06:00
|
|
|
return m, tea.Batch(cmds...)
|
2024-03-30 20:03:53 -06:00
|
|
|
}
|
|
|
|
|
2024-05-30 00:44:40 -06:00
|
|
|
func (m *Model) handleMessagesKey(msg tea.KeyMsg) (bool, tea.Cmd) {
|
2024-03-30 20:03:53 -06:00
|
|
|
switch msg.String() {
|
2024-03-31 19:06:13 -06:00
|
|
|
case "tab", "enter":
|
2024-03-30 20:03:53 -06:00
|
|
|
m.focus = focusInput
|
|
|
|
m.updateContent()
|
|
|
|
m.input.Focus()
|
2024-03-31 19:06:13 -06:00
|
|
|
return true, nil
|
2024-03-30 20:03:53 -06:00
|
|
|
case "e":
|
|
|
|
message := m.messages[m.selectedMessage]
|
2024-05-30 00:44:40 -06:00
|
|
|
cmd := tuiutil.OpenTempfileEditor("message.*.md", message.Content, "# Edit the message below\n")
|
2024-03-30 20:03:53 -06:00
|
|
|
m.editorTarget = selectedMessage
|
2024-03-31 19:06:13 -06:00
|
|
|
return true, cmd
|
2024-03-30 20:03:53 -06:00
|
|
|
case "ctrl+k":
|
|
|
|
if m.selectedMessage > 0 && len(m.messages) == len(m.messageOffsets) {
|
|
|
|
m.selectedMessage--
|
|
|
|
m.updateContent()
|
|
|
|
offset := m.messageOffsets[m.selectedMessage]
|
2024-05-30 00:44:40 -06:00
|
|
|
tuiutil.ScrollIntoView(&m.content, offset, m.content.Height/2)
|
2024-03-30 20:03:53 -06:00
|
|
|
}
|
2024-03-31 19:06:13 -06:00
|
|
|
return true, nil
|
2024-03-30 20:03:53 -06:00
|
|
|
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]
|
2024-05-30 00:44:40 -06:00
|
|
|
tuiutil.ScrollIntoView(&m.content, offset, m.content.Height/2)
|
2024-03-30 20:03:53 -06:00
|
|
|
}
|
2024-03-31 19:06:13 -06:00
|
|
|
return true, nil
|
2024-05-28 00:34:11 -06:00
|
|
|
case "ctrl+h", "ctrl+l":
|
|
|
|
dir := CyclePrev
|
|
|
|
if msg.String() == "ctrl+l" {
|
|
|
|
dir = CycleNext
|
|
|
|
}
|
|
|
|
|
|
|
|
var err error
|
|
|
|
var selected *models.Message
|
|
|
|
if m.selectedMessage == 0 {
|
|
|
|
selected, err = m.cycleSelectedRoot(m.conversation, dir)
|
|
|
|
if err != nil {
|
2024-05-30 00:44:40 -06:00
|
|
|
return true, shared.WrapError(fmt.Errorf("Could not cycle conversation root: %v", err))
|
2024-05-28 00:34:11 -06:00
|
|
|
}
|
|
|
|
} else if m.selectedMessage > 0 {
|
|
|
|
selected, err = m.cycleSelectedReply(&m.messages[m.selectedMessage-1], dir)
|
|
|
|
if err != nil {
|
2024-05-30 00:44:40 -06:00
|
|
|
return true, shared.WrapError(fmt.Errorf("Could not cycle reply: %v", err))
|
2024-05-28 00:34:11 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if selected == nil {
|
|
|
|
return false, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Retrieve updated view at this point
|
2024-05-30 00:44:40 -06:00
|
|
|
newPath, err := m.State.Ctx.Store.PathToLeaf(selected)
|
2024-05-28 00:34:11 -06:00
|
|
|
if err != nil {
|
2024-05-30 00:44:40 -06:00
|
|
|
m.State.Err = fmt.Errorf("Could not fetch messages: %v", err)
|
2024-05-28 00:34:11 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
m.messages = append(m.messages[:m.selectedMessage], newPath...)
|
|
|
|
m.rebuildMessageCache()
|
|
|
|
m.updateContent()
|
|
|
|
return true, nil
|
2024-03-30 20:03:53 -06:00
|
|
|
case "ctrl+r":
|
|
|
|
// resubmit the conversation with all messages up until and including the selected message
|
|
|
|
if m.waitingForReply || len(m.messages) == 0 {
|
2024-03-31 19:06:13 -06:00
|
|
|
return true, nil
|
2024-03-30 20:03:53 -06:00
|
|
|
}
|
|
|
|
m.messages = m.messages[:m.selectedMessage+1]
|
|
|
|
m.messageCache = m.messageCache[:m.selectedMessage+1]
|
2024-05-22 10:25:16 -06:00
|
|
|
cmd := m.promptLLM()
|
2024-03-30 20:03:53 -06:00
|
|
|
m.updateContent()
|
|
|
|
m.content.GotoBottom()
|
2024-05-22 10:25:16 -06:00
|
|
|
return true, cmd
|
2024-03-30 20:03:53 -06:00
|
|
|
}
|
2024-03-31 19:06:13 -06:00
|
|
|
return false, nil
|
2024-03-30 20:03:53 -06:00
|
|
|
}
|
|
|
|
|
2024-05-28 00:34:11 -06:00
|
|
|
type CycleDirection int
|
|
|
|
|
|
|
|
const (
|
|
|
|
CycleNext CycleDirection = 1
|
|
|
|
CyclePrev CycleDirection = -1
|
|
|
|
)
|
|
|
|
|
|
|
|
func cycleMessages(m *models.Message, msgs []models.Message, dir CycleDirection) (*models.Message, error) {
|
|
|
|
currentIndex := -1
|
|
|
|
for i, reply := range msgs {
|
|
|
|
if reply.ID == m.ID {
|
|
|
|
currentIndex = i
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if currentIndex < 0 {
|
|
|
|
return nil, fmt.Errorf("message not found")
|
|
|
|
}
|
|
|
|
|
|
|
|
var next int
|
|
|
|
if dir == CyclePrev {
|
|
|
|
// Wrap around to the last reply if at the beginning
|
|
|
|
next = (currentIndex - 1 + len(msgs)) % len(msgs)
|
|
|
|
} else {
|
|
|
|
// Wrap around to the first reply if at the end
|
|
|
|
next = (currentIndex + 1) % len(msgs)
|
|
|
|
}
|
|
|
|
return &msgs[next], nil
|
|
|
|
}
|
|
|
|
|
2024-05-30 00:44:40 -06:00
|
|
|
func (m *Model) cycleSelectedRoot(conv *models.Conversation, dir CycleDirection) (*models.Message, error) {
|
2024-05-28 00:34:11 -06:00
|
|
|
if len(m.rootMessages) < 2 {
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
nextRoot, err := cycleMessages(conv.SelectedRoot, m.rootMessages, dir)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
conv.SelectedRoot = nextRoot
|
2024-05-30 00:44:40 -06:00
|
|
|
err = m.State.Ctx.Store.UpdateConversation(conv)
|
2024-05-28 00:34:11 -06:00
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("Could not update conversation: %v", err)
|
|
|
|
}
|
|
|
|
return nextRoot, nil
|
|
|
|
}
|
|
|
|
|
2024-05-30 00:44:40 -06:00
|
|
|
func (m *Model) cycleSelectedReply(message *models.Message, dir CycleDirection) (*models.Message, error) {
|
2024-05-28 00:34:11 -06:00
|
|
|
if len(message.Replies) < 2 {
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
nextReply, err := cycleMessages(message.SelectedReply, message.Replies, dir)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
message.SelectedReply = nextReply
|
2024-05-30 00:44:40 -06:00
|
|
|
err = m.State.Ctx.Store.UpdateMessage(message)
|
2024-05-28 00:34:11 -06:00
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("Could not update message: %v", err)
|
|
|
|
}
|
|
|
|
return nextReply, nil
|
|
|
|
}
|
|
|
|
|
2024-05-30 00:44:40 -06:00
|
|
|
func (m *Model) HandleInputKey(msg tea.KeyMsg) (bool, tea.Cmd) {
|
2024-03-30 20:03:53 -06:00
|
|
|
switch msg.String() {
|
|
|
|
case "esc":
|
2024-03-31 19:06:13 -06:00
|
|
|
m.focus = focusMessages
|
|
|
|
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]
|
2024-05-30 00:44:40 -06:00
|
|
|
tuiutil.ScrollIntoView(&m.content, offset, m.content.Height/2)
|
2024-03-31 17:51:45 -06:00
|
|
|
}
|
2024-03-31 19:06:13 -06:00
|
|
|
m.updateContent()
|
|
|
|
m.input.Blur()
|
|
|
|
return true, nil
|
2024-03-30 20:03:53 -06:00
|
|
|
case "ctrl+s":
|
2024-05-22 10:25:16 -06:00
|
|
|
if m.waitingForReply {
|
|
|
|
return false, nil
|
|
|
|
}
|
|
|
|
|
2024-05-20 12:12:44 -06:00
|
|
|
input := strings.TrimSpace(m.input.Value())
|
|
|
|
if input == "" {
|
2024-03-31 19:06:13 -06:00
|
|
|
return true, nil
|
2024-03-30 20:03:53 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
if len(m.messages) > 0 && m.messages[len(m.messages)-1].Role == models.MessageRoleUser {
|
2024-05-30 00:44:40 -06:00
|
|
|
return true, shared.WrapError(fmt.Errorf("Can't reply to a user message"))
|
2024-03-30 20:03:53 -06:00
|
|
|
}
|
|
|
|
|
2024-05-20 12:12:44 -06:00
|
|
|
m.addMessage(models.Message{
|
2024-03-30 20:03:53 -06:00
|
|
|
Role: models.MessageRoleUser,
|
2024-05-20 12:12:44 -06:00
|
|
|
Content: input,
|
|
|
|
})
|
2024-03-30 20:03:53 -06:00
|
|
|
|
2024-05-20 12:12:44 -06:00
|
|
|
m.input.SetValue("")
|
2024-03-30 20:03:53 -06:00
|
|
|
|
2024-05-20 12:12:44 -06:00
|
|
|
if m.persistence {
|
|
|
|
err := m.persistConversation()
|
2024-03-30 20:03:53 -06:00
|
|
|
if err != nil {
|
2024-05-30 00:44:40 -06:00
|
|
|
return true, shared.WrapError(err)
|
2024-03-30 20:03:53 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-05-22 10:25:16 -06:00
|
|
|
cmd := m.promptLLM()
|
2024-03-30 20:03:53 -06:00
|
|
|
m.updateContent()
|
|
|
|
m.content.GotoBottom()
|
2024-05-22 10:25:16 -06:00
|
|
|
return true, cmd
|
2024-03-30 20:03:53 -06:00
|
|
|
case "ctrl+e":
|
2024-05-30 00:44:40 -06:00
|
|
|
cmd := tuiutil.OpenTempfileEditor("message.*.md", m.input.Value(), "# Edit your input below\n")
|
2024-03-30 20:03:53 -06:00
|
|
|
m.editorTarget = input
|
2024-03-31 19:06:13 -06:00
|
|
|
return true, cmd
|
2024-03-30 20:03:53 -06:00
|
|
|
}
|
2024-03-31 19:06:13 -06:00
|
|
|
return false, nil
|
2024-03-30 20:03:53 -06:00
|
|
|
}
|
|
|
|
|
2024-05-30 01:04:55 -06:00
|
|
|
func (m Model) View() string {
|
|
|
|
if m.Width == 0 {
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
sections := make([]string, 0, 6)
|
|
|
|
|
|
|
|
if m.Header != "" {
|
|
|
|
sections = append(sections, m.Header)
|
|
|
|
}
|
|
|
|
|
|
|
|
sections = append(sections, m.Content)
|
|
|
|
if m.Error != "" {
|
|
|
|
sections = append(sections, m.Error)
|
|
|
|
}
|
|
|
|
sections = append(sections, m.Input)
|
|
|
|
|
|
|
|
if m.Footer != "" {
|
|
|
|
sections = append(sections, m.Footer)
|
|
|
|
}
|
|
|
|
|
|
|
|
return lipgloss.JoinVertical(lipgloss.Left, sections...)
|
|
|
|
}
|
|
|
|
|
2024-05-30 00:44:40 -06:00
|
|
|
func (m *Model) renderMessageHeading(i int, message *models.Message) string {
|
2024-03-30 20:03:53 -06:00
|
|
|
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)
|
2024-05-28 00:34:11 -06:00
|
|
|
|
|
|
|
if i == 0 && len(m.rootMessages) > 0 {
|
|
|
|
selectedRootIndex := 0
|
|
|
|
for j, reply := range m.rootMessages {
|
|
|
|
if reply.ID == *m.conversation.SelectedRootID {
|
|
|
|
selectedRootIndex = j
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
suffix += faint.Render(fmt.Sprintf(" <%d/%d>", selectedRootIndex+1, len(m.rootMessages)))
|
|
|
|
}
|
|
|
|
if i > 0 && len(m.messages[i-1].Replies) > 1 {
|
|
|
|
// Find the selected reply index
|
|
|
|
selectedReplyIndex := 0
|
|
|
|
for j, reply := range m.messages[i-1].Replies {
|
|
|
|
if reply.ID == *m.messages[i-1].SelectedReplyID {
|
|
|
|
selectedReplyIndex = j
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
suffix += faint.Render(fmt.Sprintf(" <%d/%d>", selectedReplyIndex+1, len(m.messages[i-1].Replies)))
|
|
|
|
}
|
|
|
|
|
2024-03-30 20:03:53 -06:00
|
|
|
if m.focus == focusMessages {
|
|
|
|
if i == m.selectedMessage {
|
|
|
|
prefix = "> "
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if message.ID == 0 {
|
|
|
|
suffix += faint.Render(" (not saved)")
|
|
|
|
}
|
|
|
|
|
|
|
|
return messageHeadingStyle.Render(prefix + user + suffix)
|
|
|
|
}
|
|
|
|
|
2024-05-30 00:44:40 -06:00
|
|
|
func (m *Model) renderMessage(i int) string {
|
2024-05-22 10:25:16 -06:00
|
|
|
msg := &m.messages[i]
|
|
|
|
|
|
|
|
// Write message contents
|
2024-03-30 20:03:53 -06:00
|
|
|
sb := &strings.Builder{}
|
|
|
|
sb.Grow(len(msg.Content) * 2)
|
|
|
|
if msg.Content != "" {
|
2024-05-30 00:44:40 -06:00
|
|
|
err := m.State.Ctx.Chroma.Highlight(sb, msg.Content)
|
2024-03-30 20:03:53 -06:00
|
|
|
if err != nil {
|
|
|
|
sb.Reset()
|
|
|
|
sb.WriteString(msg.Content)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-05-22 10:25:16 -06:00
|
|
|
// Show the assistant's cursor
|
|
|
|
if m.waitingForReply && i == len(m.messages)-1 {
|
|
|
|
sb.WriteString(m.replyCursor.View())
|
|
|
|
}
|
|
|
|
|
|
|
|
// Write tool call info
|
2024-03-30 20:03:53 -06:00
|
|
|
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")
|
|
|
|
}
|
2024-05-30 00:44:40 -06:00
|
|
|
_ = m.State.Ctx.Chroma.HighlightLang(sb, toolString, "yaml")
|
2024-03-30 20:03:53 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
content := strings.TrimRight(sb.String(), "\n")
|
|
|
|
|
|
|
|
if m.wrap {
|
2024-05-22 10:57:38 -06:00
|
|
|
wrapWidth := m.content.Width - messageStyle.GetHorizontalPadding()
|
|
|
|
// first we word-wrap text to slightly less than desired width (since
|
|
|
|
// wordwrap seems to have an off-by-1 issue), then hard wrap at
|
|
|
|
// desired with
|
|
|
|
content = wrap.String(wordwrap.String(content, wrapWidth-2), wrapWidth)
|
2024-03-30 20:03:53 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
return messageStyle.Width(0).Render(content)
|
|
|
|
}
|
|
|
|
|
|
|
|
// render the conversation into a string
|
2024-05-30 00:44:40 -06:00
|
|
|
func (m *Model) conversationMessagesView() string {
|
2024-03-30 20:03:53 -06:00
|
|
|
sb := strings.Builder{}
|
|
|
|
|
|
|
|
m.messageOffsets = make([]int, len(m.messages))
|
|
|
|
lineCnt := 1
|
|
|
|
for i, message := range m.messages {
|
|
|
|
m.messageOffsets[i] = lineCnt
|
|
|
|
|
|
|
|
switch message.Role {
|
|
|
|
case models.MessageRoleToolCall:
|
|
|
|
if !m.showToolResults && message.Content == "" {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
case models.MessageRoleToolResult:
|
|
|
|
if !m.showToolResults {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
heading := m.renderMessageHeading(i, &message)
|
|
|
|
sb.WriteString(heading)
|
|
|
|
sb.WriteString("\n")
|
|
|
|
lineCnt += lipgloss.Height(heading)
|
|
|
|
|
2024-05-22 10:25:16 -06:00
|
|
|
var rendered string
|
|
|
|
if m.waitingForReply && i == len(m.messages)-1 {
|
|
|
|
// do a direct render of final (assistant) message to handle the
|
|
|
|
// assistant cursor blink
|
|
|
|
rendered = m.renderMessage(i)
|
|
|
|
} else {
|
|
|
|
rendered = m.messageCache[i]
|
|
|
|
}
|
|
|
|
|
|
|
|
sb.WriteString(rendered)
|
2024-03-30 20:03:53 -06:00
|
|
|
sb.WriteString("\n")
|
2024-05-22 10:25:16 -06:00
|
|
|
lineCnt += lipgloss.Height(rendered)
|
2024-03-30 20:03:53 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
return sb.String()
|
|
|
|
}
|
|
|
|
|
2024-05-30 00:44:40 -06:00
|
|
|
func (m *Model) headerView() string {
|
2024-03-31 17:51:45 -06:00
|
|
|
titleStyle := lipgloss.NewStyle().Bold(true)
|
|
|
|
var title string
|
|
|
|
if m.conversation != nil && m.conversation.Title != "" {
|
|
|
|
title = m.conversation.Title
|
|
|
|
} else {
|
|
|
|
title = "Untitled"
|
|
|
|
}
|
2024-05-30 01:04:55 -06:00
|
|
|
title = tuiutil.TruncateToCellWidth(title, m.Width-styles.Header.GetHorizontalPadding(), "...")
|
2024-03-31 17:51:45 -06:00
|
|
|
header := titleStyle.Render(title)
|
2024-05-30 01:04:55 -06:00
|
|
|
return styles.Header.Width(m.Width).Render(header)
|
2024-03-31 17:51:45 -06:00
|
|
|
}
|
|
|
|
|
2024-05-30 00:44:40 -06:00
|
|
|
func (m *Model) footerView() string {
|
2024-03-31 17:51:45 -06:00
|
|
|
segmentStyle := lipgloss.NewStyle().PaddingLeft(1).PaddingRight(1).Faint(true)
|
|
|
|
segmentSeparator := "|"
|
|
|
|
|
|
|
|
savingStyle := segmentStyle.Copy().Bold(true)
|
|
|
|
saving := ""
|
|
|
|
if m.persistence {
|
|
|
|
saving = savingStyle.Foreground(lipgloss.Color("2")).Render("✅💾")
|
|
|
|
} else {
|
|
|
|
saving = savingStyle.Foreground(lipgloss.Color("1")).Render("❌💾")
|
|
|
|
}
|
|
|
|
|
|
|
|
status := m.status
|
|
|
|
if m.waitingForReply {
|
|
|
|
status += m.spinner.View()
|
|
|
|
}
|
|
|
|
|
|
|
|
leftSegments := []string{
|
|
|
|
saving,
|
|
|
|
segmentStyle.Render(status),
|
|
|
|
}
|
2024-05-13 21:41:19 -06:00
|
|
|
rightSegments := []string{}
|
|
|
|
|
|
|
|
if m.elapsed > 0 && m.tokenCount > 0 {
|
|
|
|
throughput := fmt.Sprintf("%.0f t/sec", float64(m.tokenCount)/m.elapsed.Seconds())
|
|
|
|
rightSegments = append(rightSegments, segmentStyle.Render(throughput))
|
2024-03-31 17:51:45 -06:00
|
|
|
}
|
|
|
|
|
2024-05-30 00:44:40 -06:00
|
|
|
model := fmt.Sprintf("Model: %s", *m.State.Ctx.Config.Defaults.Model)
|
2024-05-13 21:41:19 -06:00
|
|
|
rightSegments = append(rightSegments, segmentStyle.Render(model))
|
|
|
|
|
2024-03-31 17:51:45 -06:00
|
|
|
left := strings.Join(leftSegments, segmentSeparator)
|
|
|
|
right := strings.Join(rightSegments, segmentSeparator)
|
|
|
|
|
|
|
|
totalWidth := lipgloss.Width(left) + lipgloss.Width(right)
|
2024-05-30 01:04:55 -06:00
|
|
|
remaining := m.Width - totalWidth
|
2024-03-31 17:51:45 -06:00
|
|
|
|
|
|
|
var padding string
|
|
|
|
if remaining > 0 {
|
|
|
|
padding = strings.Repeat(" ", remaining)
|
|
|
|
}
|
|
|
|
|
|
|
|
footer := left + padding + right
|
|
|
|
if remaining < 0 {
|
2024-05-30 01:04:55 -06:00
|
|
|
footer = tuiutil.TruncateToCellWidth(footer, m.Width, "...")
|
2024-03-31 17:51:45 -06:00
|
|
|
}
|
2024-05-30 01:04:55 -06:00
|
|
|
return footerStyle.Width(m.Width).Render(footer)
|
2024-03-31 17:51:45 -06:00
|
|
|
}
|
|
|
|
|
2024-05-30 00:44:40 -06:00
|
|
|
func (m *Model) setMessage(i int, msg models.Message) {
|
2024-03-30 20:03:53 -06:00
|
|
|
if i >= len(m.messages) {
|
|
|
|
panic("i out of range")
|
|
|
|
}
|
|
|
|
m.messages[i] = msg
|
2024-05-22 10:25:16 -06:00
|
|
|
m.messageCache[i] = m.renderMessage(i)
|
2024-03-30 20:03:53 -06:00
|
|
|
}
|
|
|
|
|
2024-05-30 00:44:40 -06:00
|
|
|
func (m *Model) addMessage(msg models.Message) {
|
2024-03-30 20:03:53 -06:00
|
|
|
m.messages = append(m.messages, msg)
|
2024-05-22 10:25:16 -06:00
|
|
|
m.messageCache = append(m.messageCache, m.renderMessage(len(m.messages)-1))
|
2024-03-30 20:03:53 -06:00
|
|
|
}
|
|
|
|
|
2024-05-30 00:44:40 -06:00
|
|
|
func (m *Model) setMessageContents(i int, content string) {
|
2024-03-30 20:03:53 -06:00
|
|
|
if i >= len(m.messages) {
|
|
|
|
panic("i out of range")
|
|
|
|
}
|
|
|
|
m.messages[i].Content = content
|
2024-05-22 10:25:16 -06:00
|
|
|
m.messageCache[i] = m.renderMessage(i)
|
2024-03-30 20:03:53 -06:00
|
|
|
}
|
|
|
|
|
2024-05-30 00:44:40 -06:00
|
|
|
func (m *Model) rebuildMessageCache() {
|
2024-03-30 20:03:53 -06:00
|
|
|
m.messageCache = make([]string, len(m.messages))
|
2024-05-22 10:25:16 -06:00
|
|
|
for i := range m.messages {
|
|
|
|
m.messageCache[i] = m.renderMessage(i)
|
2024-03-30 20:03:53 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-05-30 00:44:40 -06:00
|
|
|
func (m *Model) updateContent() {
|
2024-03-30 20:03:53 -06:00
|
|
|
atBottom := m.content.AtBottom()
|
|
|
|
m.content.SetContent(m.conversationMessagesView())
|
|
|
|
if atBottom {
|
|
|
|
// if we were at bottom before the update, scroll with the output
|
|
|
|
m.content.GotoBottom()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-05-30 00:44:40 -06:00
|
|
|
func (m *Model) loadConversation(shortname string) tea.Cmd {
|
2024-03-30 20:03:53 -06:00
|
|
|
return func() tea.Msg {
|
|
|
|
if shortname == "" {
|
|
|
|
return nil
|
|
|
|
}
|
2024-05-30 00:44:40 -06:00
|
|
|
c, err := m.State.Ctx.Store.ConversationByShortName(shortname)
|
2024-03-30 20:03:53 -06:00
|
|
|
if err != nil {
|
2024-05-30 00:44:40 -06:00
|
|
|
return shared.MsgError(fmt.Errorf("Could not lookup conversation: %v", err))
|
2024-03-30 20:03:53 -06:00
|
|
|
}
|
|
|
|
if c.ID == 0 {
|
2024-05-30 00:44:40 -06:00
|
|
|
return shared.MsgError(fmt.Errorf("Conversation not found: %s", shortname))
|
2024-03-30 20:03:53 -06:00
|
|
|
}
|
|
|
|
return msgConversationLoaded(c)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-05-30 00:44:40 -06:00
|
|
|
func (m *Model) loadMessages(c *models.Conversation) tea.Cmd {
|
2024-03-30 20:03:53 -06:00
|
|
|
return func() tea.Msg {
|
2024-05-30 00:44:40 -06:00
|
|
|
messages, err := m.State.Ctx.Store.PathToLeaf(c.SelectedRoot)
|
2024-03-30 20:03:53 -06:00
|
|
|
if err != nil {
|
2024-05-30 00:44:40 -06:00
|
|
|
return shared.MsgError(fmt.Errorf("Could not load conversation messages: %v\n", err))
|
2024-03-30 20:03:53 -06:00
|
|
|
}
|
|
|
|
return msgMessagesLoaded(messages)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-05-30 00:44:40 -06:00
|
|
|
func (m *Model) persistConversation() error {
|
2024-05-20 12:12:44 -06:00
|
|
|
if m.conversation.ID == 0 {
|
|
|
|
// Start a new conversation with all messages so far
|
2024-05-30 00:44:40 -06:00
|
|
|
c, messages, err := m.State.Ctx.Store.StartConversation(m.messages...)
|
2024-05-20 12:12:44 -06:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
m.conversation = c
|
|
|
|
m.messages = messages
|
2024-03-30 20:03:53 -06:00
|
|
|
|
2024-05-20 12:12:44 -06:00
|
|
|
return nil
|
2024-03-30 20:03:53 -06:00
|
|
|
}
|
|
|
|
|
2024-05-20 12:12:44 -06:00
|
|
|
// else, we'll handle updating an existing conversation's messages
|
|
|
|
for i := 0; i < len(m.messages); i++ {
|
|
|
|
if m.messages[i].ID > 0 {
|
|
|
|
// message has an ID, update its contents
|
|
|
|
// TODO: check for content/tool equality before updating?
|
2024-05-30 00:44:40 -06:00
|
|
|
err := m.State.Ctx.Store.UpdateMessage(&m.messages[i])
|
2024-03-30 20:03:53 -06:00
|
|
|
if err != nil {
|
2024-05-20 12:12:44 -06:00
|
|
|
return err
|
2024-03-30 20:03:53 -06:00
|
|
|
}
|
2024-05-22 10:25:16 -06:00
|
|
|
} else if i > 0 {
|
2024-05-20 12:12:44 -06:00
|
|
|
// messages is new, so add it as a reply to previous message
|
2024-05-30 00:44:40 -06:00
|
|
|
saved, err := m.State.Ctx.Store.Reply(&m.messages[i-1], m.messages[i])
|
2024-03-30 20:03:53 -06:00
|
|
|
if err != nil {
|
2024-05-20 12:12:44 -06:00
|
|
|
return err
|
2024-03-30 20:03:53 -06:00
|
|
|
}
|
2024-05-28 00:34:11 -06:00
|
|
|
// add this message as a reply to the previous
|
|
|
|
m.messages[i-1].Replies = append(m.messages[i-1].Replies, saved[0])
|
2024-05-20 12:12:44 -06:00
|
|
|
m.messages[i] = saved[0]
|
|
|
|
} else {
|
|
|
|
// message has no id and no previous messages to add it to
|
|
|
|
// this shouldn't happen?
|
|
|
|
return fmt.Errorf("Error: no messages to reply to")
|
2024-03-30 20:03:53 -06:00
|
|
|
}
|
|
|
|
}
|
2024-05-20 12:12:44 -06:00
|
|
|
|
2024-03-30 20:03:53 -06:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2024-05-30 00:44:40 -06:00
|
|
|
func (m *Model) generateConversationTitle() tea.Cmd {
|
2024-03-30 20:03:53 -06:00
|
|
|
return func() tea.Msg {
|
2024-05-30 00:44:40 -06:00
|
|
|
title, err := cmdutil.GenerateTitle(m.State.Ctx, m.messages)
|
2024-03-30 20:03:53 -06:00
|
|
|
if err != nil {
|
2024-05-30 00:44:40 -06:00
|
|
|
return shared.MsgError(err)
|
2024-03-30 20:03:53 -06:00
|
|
|
}
|
|
|
|
return msgConversationTitleChanged(title)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-05-30 00:44:40 -06:00
|
|
|
func (m *Model) waitForReply() tea.Cmd {
|
2024-03-30 20:03:53 -06:00
|
|
|
return func() tea.Msg {
|
|
|
|
return msgAssistantReply(<-m.replyChan)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-05-30 00:44:40 -06:00
|
|
|
func (m *Model) waitForChunk() tea.Cmd {
|
2024-03-30 20:03:53 -06:00
|
|
|
return func() tea.Msg {
|
|
|
|
return msgResponseChunk(<-m.replyChunkChan)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-05-30 00:44:40 -06:00
|
|
|
func (m *Model) promptLLM() tea.Cmd {
|
2024-03-30 20:03:53 -06:00
|
|
|
m.waitingForReply = true
|
2024-05-22 10:25:16 -06:00
|
|
|
m.replyCursor.Blink = false
|
2024-03-30 20:03:53 -06:00
|
|
|
m.status = "Press ctrl+c to cancel"
|
|
|
|
|
2024-05-22 10:25:16 -06:00
|
|
|
toPrompt := m.messages
|
|
|
|
|
|
|
|
// Add response placeholder message
|
|
|
|
if m.messages[len(m.messages)-1].Role != models.MessageRoleAssistant {
|
|
|
|
m.addMessage(models.Message{
|
|
|
|
Role: models.MessageRoleAssistant,
|
|
|
|
Content: "",
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2024-05-13 21:41:19 -06:00
|
|
|
m.tokenCount = 0
|
|
|
|
m.startTime = time.Now()
|
|
|
|
m.elapsed = 0
|
|
|
|
|
2024-03-30 20:03:53 -06:00
|
|
|
return func() tea.Msg {
|
2024-05-30 00:44:40 -06:00
|
|
|
completionProvider, err := m.State.Ctx.GetCompletionProvider(*m.State.Ctx.Config.Defaults.Model)
|
2024-03-30 20:03:53 -06:00
|
|
|
if err != nil {
|
2024-05-30 00:44:40 -06:00
|
|
|
return shared.MsgError(err)
|
2024-03-30 20:03:53 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
requestParams := models.RequestParameters{
|
2024-05-30 00:44:40 -06:00
|
|
|
Model: *m.State.Ctx.Config.Defaults.Model,
|
|
|
|
MaxTokens: *m.State.Ctx.Config.Defaults.MaxTokens,
|
|
|
|
Temperature: *m.State.Ctx.Config.Defaults.Temperature,
|
|
|
|
ToolBag: m.State.Ctx.EnabledTools,
|
2024-03-30 20:03:53 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
replyHandler := func(msg models.Message) {
|
|
|
|
m.replyChan <- msg
|
|
|
|
}
|
|
|
|
|
|
|
|
ctx, cancel := context.WithCancel(context.Background())
|
|
|
|
|
|
|
|
canceled := false
|
|
|
|
go func() {
|
|
|
|
select {
|
|
|
|
case <-m.stopSignal:
|
|
|
|
canceled = true
|
|
|
|
cancel()
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
resp, err := completionProvider.CreateChatCompletionStream(
|
2024-05-22 10:25:16 -06:00
|
|
|
ctx, requestParams, toPrompt, replyHandler, m.replyChunkChan,
|
2024-03-30 20:03:53 -06:00
|
|
|
)
|
|
|
|
|
|
|
|
if err != nil && !canceled {
|
|
|
|
return msgResponseError(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return msgResponseEnd(resp)
|
|
|
|
}
|
|
|
|
}
|