Compare commits
No commits in common. "58e1b84feaec1649c7207687fb521f557c756e00" and "437997872a8d831cbdcf0eb4d8b4f483cfeb05e2" have entirely different histories.
58e1b84fea
...
437997872a
@ -2,7 +2,6 @@ package util
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"os"
|
"os"
|
||||||
"strings"
|
"strings"
|
||||||
@ -150,40 +149,32 @@ func FormatForExternalPrompt(messages []model.Message, system bool) string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func GenerateTitle(ctx *lmcli.Context, messages []model.Message) (string, error) {
|
func GenerateTitle(ctx *lmcli.Context, messages []model.Message) (string, error) {
|
||||||
const systemPrompt = `You will be shown a conversation between a user and an AI assistant. Your task is to generate a short title (8 words or less) for the provided conversation that reflects the conversation's topic. Your response is expected to be in JSON in the format shown below.
|
const prompt = `Above is an excerpt from a conversation between a user and AI assistant. Please reply with a short title (no more than 8 words) that reflects the topic of the conversation, read from the user's perspective.
|
||||||
|
|
||||||
Example conversation:
|
Example conversation:
|
||||||
|
|
||||||
[{"role": "user", "content": "Can you help me with my math homework?"},{"role": "assistant", "content": "Sure, what topic are you struggling with?"}]
|
"""
|
||||||
|
User:
|
||||||
|
|
||||||
|
Hello!
|
||||||
|
|
||||||
|
Assistant:
|
||||||
|
|
||||||
|
Hello! How may I assist you?
|
||||||
|
"""
|
||||||
|
|
||||||
Example response:
|
Example response:
|
||||||
|
|
||||||
{"title": "Help with math homework"}
|
"""
|
||||||
|
Title: A brief introduction
|
||||||
|
"""
|
||||||
`
|
`
|
||||||
type msg struct {
|
conversation := FormatForExternalPrompt(messages, false)
|
||||||
Role string
|
|
||||||
Content string
|
|
||||||
}
|
|
||||||
|
|
||||||
var msgs []msg
|
|
||||||
for _, m := range messages {
|
|
||||||
msgs = append(msgs, msg{string(m.Role), m.Content})
|
|
||||||
}
|
|
||||||
|
|
||||||
// Serialize the conversation to JSON
|
|
||||||
conversation, err := json.Marshal(msgs)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
|
|
||||||
generateRequest := []model.Message{
|
generateRequest := []model.Message{
|
||||||
{
|
|
||||||
Role: model.MessageRoleSystem,
|
|
||||||
Content: systemPrompt,
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
Role: model.MessageRoleUser,
|
Role: model.MessageRoleUser,
|
||||||
Content: string(conversation),
|
Content: fmt.Sprintf("\"\"\"\n%s\n\"\"\"\n\n%s", conversation, prompt),
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -202,16 +193,11 @@ Example response:
|
|||||||
return "", err
|
return "", err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Parse the JSON response
|
response = strings.TrimPrefix(response, "Title: ")
|
||||||
var jsonResponse struct {
|
response = strings.Trim(response, "\"")
|
||||||
Title string `json:"title"`
|
response = strings.TrimSpace(response)
|
||||||
}
|
|
||||||
err = json.Unmarshal([]byte(response), &jsonResponse)
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
|
|
||||||
return jsonResponse.Title, nil
|
return response, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ShowWaitAnimation prints an animated ellipses to stdout until something is
|
// ShowWaitAnimation prints an animated ellipses to stdout until something is
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
package chat
|
package tui
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
@ -9,9 +9,6 @@ import (
|
|||||||
|
|
||||||
cmdutil "git.mlow.ca/mlow/lmcli/pkg/cmd/util"
|
cmdutil "git.mlow.ca/mlow/lmcli/pkg/cmd/util"
|
||||||
models "git.mlow.ca/mlow/lmcli/pkg/lmcli/model"
|
models "git.mlow.ca/mlow/lmcli/pkg/lmcli/model"
|
||||||
"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"
|
|
||||||
"github.com/charmbracelet/bubbles/cursor"
|
"github.com/charmbracelet/bubbles/cursor"
|
||||||
"github.com/charmbracelet/bubbles/spinner"
|
"github.com/charmbracelet/bubbles/spinner"
|
||||||
"github.com/charmbracelet/bubbles/textarea"
|
"github.com/charmbracelet/bubbles/textarea"
|
||||||
@ -43,7 +40,7 @@ type (
|
|||||||
msgResponseChunk string
|
msgResponseChunk string
|
||||||
// sent when response is finished being received
|
// sent when response is finished being received
|
||||||
msgResponseEnd string
|
msgResponseEnd string
|
||||||
// a special case of common.MsgError that stops the response waiting animation
|
// a special case of msgError that stops the response waiting animation
|
||||||
msgResponseError error
|
msgResponseError error
|
||||||
// sent on each completed reply
|
// sent on each completed reply
|
||||||
msgAssistantReply models.Message
|
msgAssistantReply models.Message
|
||||||
@ -55,13 +52,13 @@ type (
|
|||||||
msgMessagesLoaded []models.Message
|
msgMessagesLoaded []models.Message
|
||||||
)
|
)
|
||||||
|
|
||||||
type Model struct {
|
type chatModel struct {
|
||||||
shared.State
|
basemodel
|
||||||
shared.Sections
|
width int
|
||||||
|
height int
|
||||||
|
|
||||||
// app state
|
// app state
|
||||||
conversation *models.Conversation
|
conversation *models.Conversation
|
||||||
rootMessages []models.Message
|
|
||||||
messages []models.Message
|
messages []models.Message
|
||||||
selectedMessage int
|
selectedMessage int
|
||||||
waitingForReply bool
|
waitingForReply bool
|
||||||
@ -71,6 +68,10 @@ type Model struct {
|
|||||||
replyChunkChan chan string
|
replyChunkChan chan string
|
||||||
persistence bool // whether we will save new messages in the conversation
|
persistence bool // whether we will save new messages in the conversation
|
||||||
|
|
||||||
|
tokenCount uint
|
||||||
|
startTime time.Time
|
||||||
|
elapsed time.Duration
|
||||||
|
|
||||||
// ui state
|
// ui state
|
||||||
focus focusState
|
focus focusState
|
||||||
wrap bool // whether message content is wrapped to viewport width
|
wrap bool // whether message content is wrapped to viewport width
|
||||||
@ -79,10 +80,6 @@ type Model struct {
|
|||||||
messageCache []string // cache of syntax highlighted and wrapped message content
|
messageCache []string // cache of syntax highlighted and wrapped message content
|
||||||
messageOffsets []int
|
messageOffsets []int
|
||||||
|
|
||||||
tokenCount uint
|
|
||||||
startTime time.Time
|
|
||||||
elapsed time.Duration
|
|
||||||
|
|
||||||
// ui elements
|
// ui elements
|
||||||
content viewport.Model
|
content viewport.Model
|
||||||
input textarea.Model
|
input textarea.Model
|
||||||
@ -90,9 +87,13 @@ type Model struct {
|
|||||||
replyCursor cursor.Model // cursor to indicate incoming response
|
replyCursor cursor.Model // cursor to indicate incoming response
|
||||||
}
|
}
|
||||||
|
|
||||||
func Chat(state shared.State) Model {
|
func newChatModel(tui *model) chatModel {
|
||||||
m := Model{
|
m := chatModel{
|
||||||
State: state,
|
basemodel: basemodel{
|
||||||
|
opts: tui.opts,
|
||||||
|
ctx: tui.ctx,
|
||||||
|
views: tui.views,
|
||||||
|
},
|
||||||
|
|
||||||
conversation: &models.Conversation{},
|
conversation: &models.Conversation{},
|
||||||
persistence: true,
|
persistence: true,
|
||||||
@ -125,7 +126,7 @@ func Chat(state shared.State) Model {
|
|||||||
m.replyCursor.SetChar(" ")
|
m.replyCursor.SetChar(" ")
|
||||||
m.replyCursor.Focus()
|
m.replyCursor.Focus()
|
||||||
|
|
||||||
system := state.Ctx.GetSystemPrompt()
|
system := tui.ctx.GetSystemPrompt()
|
||||||
if system != "" {
|
if system != "" {
|
||||||
m.messages = []models.Message{{
|
m.messages = []models.Message{{
|
||||||
Role: models.MessageRoleSystem,
|
Role: models.MessageRoleSystem,
|
||||||
@ -150,6 +151,11 @@ func Chat(state shared.State) Model {
|
|||||||
|
|
||||||
// styles
|
// styles
|
||||||
var (
|
var (
|
||||||
|
headerStyle = lipgloss.NewStyle().
|
||||||
|
PaddingLeft(1).
|
||||||
|
PaddingRight(1).
|
||||||
|
Background(lipgloss.Color("0"))
|
||||||
|
|
||||||
messageHeadingStyle = lipgloss.NewStyle().
|
messageHeadingStyle = lipgloss.NewStyle().
|
||||||
MarginTop(1).
|
MarginTop(1).
|
||||||
MarginBottom(1).
|
MarginBottom(1).
|
||||||
@ -174,10 +180,10 @@ var (
|
|||||||
footerStyle = lipgloss.NewStyle()
|
footerStyle = lipgloss.NewStyle()
|
||||||
)
|
)
|
||||||
|
|
||||||
func (m *Model) HandleInput(msg tea.KeyMsg) (bool, tea.Cmd) {
|
func (m *chatModel) handleInput(msg tea.KeyMsg) (bool, tea.Cmd) {
|
||||||
switch m.focus {
|
switch m.focus {
|
||||||
case focusInput:
|
case focusInput:
|
||||||
consumed, cmd := m.HandleInputKey(msg)
|
consumed, cmd := m.handleInputKey(msg)
|
||||||
if consumed {
|
if consumed {
|
||||||
return true, cmd
|
return true, cmd
|
||||||
}
|
}
|
||||||
@ -195,7 +201,7 @@ func (m *Model) HandleInput(msg tea.KeyMsg) (bool, tea.Cmd) {
|
|||||||
return true, nil
|
return true, nil
|
||||||
}
|
}
|
||||||
return true, func() tea.Msg {
|
return true, func() tea.Msg {
|
||||||
return shared.MsgViewChange(shared.StateConversations)
|
return msgStateChange(stateConversations)
|
||||||
}
|
}
|
||||||
case "ctrl+c":
|
case "ctrl+c":
|
||||||
if m.waitingForReply {
|
if m.waitingForReply {
|
||||||
@ -219,15 +225,15 @@ func (m *Model) HandleInput(msg tea.KeyMsg) (bool, tea.Cmd) {
|
|||||||
return false, nil
|
return false, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m Model) Init() tea.Cmd {
|
func (m chatModel) Init() tea.Cmd {
|
||||||
return tea.Batch(
|
return tea.Batch(
|
||||||
m.waitForChunk(),
|
m.waitForChunk(),
|
||||||
m.waitForReply(),
|
m.waitForReply(),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Model) HandleResize(width, height int) {
|
func (m *chatModel) handleResize(width, height int) {
|
||||||
m.Width, m.Height = width, height
|
m.width, m.height = width, height
|
||||||
m.content.Width = width
|
m.content.Width = width
|
||||||
m.input.SetWidth(width - m.input.FocusedStyle.Base.GetHorizontalFrameSize())
|
m.input.SetWidth(width - m.input.FocusedStyle.Base.GetHorizontalFrameSize())
|
||||||
if len(m.messages) > 0 {
|
if len(m.messages) > 0 {
|
||||||
@ -236,22 +242,22 @@ func (m *Model) HandleResize(width, height int) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
|
func (m chatModel) Update(msg tea.Msg) (chatModel, tea.Cmd) {
|
||||||
var cmds []tea.Cmd
|
var cmds []tea.Cmd
|
||||||
switch msg := msg.(type) {
|
switch msg := msg.(type) {
|
||||||
case shared.MsgViewEnter:
|
case msgStateEnter:
|
||||||
// wake up spinners and cursors
|
// wake up spinners and cursors
|
||||||
cmds = append(cmds, cursor.Blink, m.spinner.Tick)
|
cmds = append(cmds, cursor.Blink, m.spinner.Tick)
|
||||||
|
|
||||||
if m.State.Values.ConvShortname != "" && m.conversation.ShortName.String != m.State.Values.ConvShortname {
|
if m.opts.convShortname != "" && m.conversation.ShortName.String != m.opts.convShortname {
|
||||||
cmds = append(cmds, m.loadConversation(m.State.Values.ConvShortname))
|
cmds = append(cmds, m.loadConversation(m.opts.convShortname))
|
||||||
}
|
}
|
||||||
|
|
||||||
m.rebuildMessageCache()
|
m.rebuildMessageCache()
|
||||||
m.updateContent()
|
m.updateContent()
|
||||||
case tea.WindowSizeMsg:
|
case tea.WindowSizeMsg:
|
||||||
m.HandleResize(msg.Width, msg.Height)
|
m.handleResize(msg.Width, msg.Height)
|
||||||
case tuiutil.MsgTempfileEditorClosed:
|
case msgTempfileEditorClosed:
|
||||||
contents := string(msg)
|
contents := string(msg)
|
||||||
switch m.editorTarget {
|
switch m.editorTarget {
|
||||||
case input:
|
case input:
|
||||||
@ -260,16 +266,15 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
|
|||||||
m.setMessageContents(m.selectedMessage, contents)
|
m.setMessageContents(m.selectedMessage, contents)
|
||||||
if m.persistence && m.messages[m.selectedMessage].ID > 0 {
|
if m.persistence && m.messages[m.selectedMessage].ID > 0 {
|
||||||
// update persisted message
|
// update persisted message
|
||||||
err := m.State.Ctx.Store.UpdateMessage(&m.messages[m.selectedMessage])
|
err := m.ctx.Store.UpdateMessage(&m.messages[m.selectedMessage])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
cmds = append(cmds, shared.WrapError(fmt.Errorf("Could not save edited message: %v", err)))
|
cmds = append(cmds, wrapError(fmt.Errorf("Could not save edited message: %v", err)))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
m.updateContent()
|
m.updateContent()
|
||||||
}
|
}
|
||||||
case msgConversationLoaded:
|
case msgConversationLoaded:
|
||||||
m.conversation = (*models.Conversation)(msg)
|
m.conversation = (*models.Conversation)(msg)
|
||||||
m.rootMessages, _ = m.State.Ctx.Store.RootMessages(m.conversation.ID)
|
|
||||||
cmds = append(cmds, m.loadMessages(m.conversation))
|
cmds = append(cmds, m.loadMessages(m.conversation))
|
||||||
case msgMessagesLoaded:
|
case msgMessagesLoaded:
|
||||||
m.selectedMessage = len(msg) - 1
|
m.selectedMessage = len(msg) - 1
|
||||||
@ -323,7 +328,7 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
|
|||||||
if m.persistence {
|
if m.persistence {
|
||||||
err := m.persistConversation()
|
err := m.persistConversation()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
cmds = append(cmds, shared.WrapError(err))
|
cmds = append(cmds, wrapError(err))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -345,15 +350,15 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
|
|||||||
case msgResponseError:
|
case msgResponseError:
|
||||||
m.waitingForReply = false
|
m.waitingForReply = false
|
||||||
m.status = "Press ctrl+s to send"
|
m.status = "Press ctrl+s to send"
|
||||||
m.State.Err = error(msg)
|
m.err = error(msg)
|
||||||
m.updateContent()
|
m.updateContent()
|
||||||
case msgConversationTitleChanged:
|
case msgConversationTitleChanged:
|
||||||
title := string(msg)
|
title := string(msg)
|
||||||
m.conversation.Title = title
|
m.conversation.Title = title
|
||||||
if m.persistence {
|
if m.persistence {
|
||||||
err := m.State.Ctx.Store.UpdateConversation(m.conversation)
|
err := m.ctx.Store.UpdateConversation(m.conversation)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
cmds = append(cmds, shared.WrapError(err))
|
cmds = append(cmds, wrapError(err))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
case cursor.BlinkMsg:
|
case cursor.BlinkMsg:
|
||||||
@ -389,21 +394,21 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// update views once window dimensions are known
|
// update views once window dimensions are known
|
||||||
if m.Width > 0 {
|
if m.width > 0 {
|
||||||
m.Header = m.headerView()
|
m.views.header = m.headerView()
|
||||||
m.Footer = m.footerView()
|
m.views.footer = m.footerView()
|
||||||
m.Error = tuiutil.ErrorBanner(m.Err, m.Width)
|
m.views.error = errorBanner(m.err, m.width)
|
||||||
fixedHeight := tuiutil.Height(m.Header) + tuiutil.Height(m.Error) + tuiutil.Height(m.Footer)
|
fixedHeight := height(m.views.header) + height(m.views.error) + height(m.views.footer)
|
||||||
|
|
||||||
// calculate clamped input height to accomodate input text
|
// calculate clamped input height to accomodate input text
|
||||||
// minimum 4 lines, maximum half of content area
|
// minimum 4 lines, maximum half of content area
|
||||||
newHeight := max(4, min((m.Height-fixedHeight-1)/2, m.input.LineCount()))
|
newHeight := max(4, min((m.height-fixedHeight-1)/2, m.input.LineCount()))
|
||||||
m.input.SetHeight(newHeight)
|
m.input.SetHeight(newHeight)
|
||||||
m.Input = m.input.View()
|
m.views.input = m.input.View()
|
||||||
|
|
||||||
// remaining height towards content
|
// remaining height towards content
|
||||||
m.content.Height = m.Height - fixedHeight - tuiutil.Height(m.Input)
|
m.content.Height = m.height - fixedHeight - height(m.views.input)
|
||||||
m.Content = m.content.View()
|
m.views.content = m.content.View()
|
||||||
}
|
}
|
||||||
|
|
||||||
// this is a pretty nasty hack to ensure the input area viewport doesn't
|
// this is a pretty nasty hack to ensure the input area viewport doesn't
|
||||||
@ -431,7 +436,7 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
|
|||||||
return m, tea.Batch(cmds...)
|
return m, tea.Batch(cmds...)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Model) handleMessagesKey(msg tea.KeyMsg) (bool, tea.Cmd) {
|
func (m *chatModel) handleMessagesKey(msg tea.KeyMsg) (bool, tea.Cmd) {
|
||||||
switch msg.String() {
|
switch msg.String() {
|
||||||
case "tab", "enter":
|
case "tab", "enter":
|
||||||
m.focus = focusInput
|
m.focus = focusInput
|
||||||
@ -440,7 +445,7 @@ func (m *Model) handleMessagesKey(msg tea.KeyMsg) (bool, tea.Cmd) {
|
|||||||
return true, nil
|
return true, nil
|
||||||
case "e":
|
case "e":
|
||||||
message := m.messages[m.selectedMessage]
|
message := m.messages[m.selectedMessage]
|
||||||
cmd := tuiutil.OpenTempfileEditor("message.*.md", message.Content, "# Edit the message below\n")
|
cmd := openTempfileEditor("message.*.md", message.Content, "# Edit the message below\n")
|
||||||
m.editorTarget = selectedMessage
|
m.editorTarget = selectedMessage
|
||||||
return true, cmd
|
return true, cmd
|
||||||
case "ctrl+k":
|
case "ctrl+k":
|
||||||
@ -448,7 +453,7 @@ func (m *Model) handleMessagesKey(msg tea.KeyMsg) (bool, tea.Cmd) {
|
|||||||
m.selectedMessage--
|
m.selectedMessage--
|
||||||
m.updateContent()
|
m.updateContent()
|
||||||
offset := m.messageOffsets[m.selectedMessage]
|
offset := m.messageOffsets[m.selectedMessage]
|
||||||
tuiutil.ScrollIntoView(&m.content, offset, m.content.Height/2)
|
scrollIntoView(&m.content, offset, m.content.Height/2)
|
||||||
}
|
}
|
||||||
return true, nil
|
return true, nil
|
||||||
case "ctrl+j":
|
case "ctrl+j":
|
||||||
@ -456,43 +461,9 @@ func (m *Model) handleMessagesKey(msg tea.KeyMsg) (bool, tea.Cmd) {
|
|||||||
m.selectedMessage++
|
m.selectedMessage++
|
||||||
m.updateContent()
|
m.updateContent()
|
||||||
offset := m.messageOffsets[m.selectedMessage]
|
offset := m.messageOffsets[m.selectedMessage]
|
||||||
tuiutil.ScrollIntoView(&m.content, offset, m.content.Height/2)
|
scrollIntoView(&m.content, offset, m.content.Height/2)
|
||||||
}
|
}
|
||||||
return true, nil
|
return true, nil
|
||||||
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 {
|
|
||||||
return true, shared.WrapError(fmt.Errorf("Could not cycle conversation root: %v", err))
|
|
||||||
}
|
|
||||||
} else if m.selectedMessage > 0 {
|
|
||||||
selected, err = m.cycleSelectedReply(&m.messages[m.selectedMessage-1], dir)
|
|
||||||
if err != nil {
|
|
||||||
return true, shared.WrapError(fmt.Errorf("Could not cycle reply: %v", err))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if selected == nil {
|
|
||||||
return false, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Retrieve updated view at this point
|
|
||||||
newPath, err := m.State.Ctx.Store.PathToLeaf(selected)
|
|
||||||
if err != nil {
|
|
||||||
m.State.Err = fmt.Errorf("Could not fetch messages: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
m.messages = append(m.messages[:m.selectedMessage], newPath...)
|
|
||||||
m.rebuildMessageCache()
|
|
||||||
m.updateContent()
|
|
||||||
return true, nil
|
|
||||||
case "ctrl+r":
|
case "ctrl+r":
|
||||||
// resubmit the conversation with all messages up until and including the selected message
|
// resubmit the conversation with all messages up until and including the selected message
|
||||||
if m.waitingForReply || len(m.messages) == 0 {
|
if m.waitingForReply || len(m.messages) == 0 {
|
||||||
@ -508,74 +479,7 @@ func (m *Model) handleMessagesKey(msg tea.KeyMsg) (bool, tea.Cmd) {
|
|||||||
return false, nil
|
return false, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
type CycleDirection int
|
func (m *chatModel) handleInputKey(msg tea.KeyMsg) (bool, tea.Cmd) {
|
||||||
|
|
||||||
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
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Model) cycleSelectedRoot(conv *models.Conversation, dir CycleDirection) (*models.Message, error) {
|
|
||||||
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
|
|
||||||
err = m.State.Ctx.Store.UpdateConversation(conv)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("Could not update conversation: %v", err)
|
|
||||||
}
|
|
||||||
return nextRoot, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Model) cycleSelectedReply(message *models.Message, dir CycleDirection) (*models.Message, error) {
|
|
||||||
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
|
|
||||||
err = m.State.Ctx.Store.UpdateMessage(message)
|
|
||||||
if err != nil {
|
|
||||||
return nil, fmt.Errorf("Could not update message: %v", err)
|
|
||||||
}
|
|
||||||
return nextReply, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Model) HandleInputKey(msg tea.KeyMsg) (bool, tea.Cmd) {
|
|
||||||
switch msg.String() {
|
switch msg.String() {
|
||||||
case "esc":
|
case "esc":
|
||||||
m.focus = focusMessages
|
m.focus = focusMessages
|
||||||
@ -584,7 +488,7 @@ func (m *Model) HandleInputKey(msg tea.KeyMsg) (bool, tea.Cmd) {
|
|||||||
m.selectedMessage = len(m.messages) - 1
|
m.selectedMessage = len(m.messages) - 1
|
||||||
}
|
}
|
||||||
offset := m.messageOffsets[m.selectedMessage]
|
offset := m.messageOffsets[m.selectedMessage]
|
||||||
tuiutil.ScrollIntoView(&m.content, offset, m.content.Height/2)
|
scrollIntoView(&m.content, offset, m.content.Height/2)
|
||||||
}
|
}
|
||||||
m.updateContent()
|
m.updateContent()
|
||||||
m.input.Blur()
|
m.input.Blur()
|
||||||
@ -600,7 +504,7 @@ func (m *Model) HandleInputKey(msg tea.KeyMsg) (bool, tea.Cmd) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if len(m.messages) > 0 && m.messages[len(m.messages)-1].Role == models.MessageRoleUser {
|
if len(m.messages) > 0 && m.messages[len(m.messages)-1].Role == models.MessageRoleUser {
|
||||||
return true, shared.WrapError(fmt.Errorf("Can't reply to a user message"))
|
return true, wrapError(fmt.Errorf("Can't reply to a user message"))
|
||||||
}
|
}
|
||||||
|
|
||||||
m.addMessage(models.Message{
|
m.addMessage(models.Message{
|
||||||
@ -613,7 +517,7 @@ func (m *Model) HandleInputKey(msg tea.KeyMsg) (bool, tea.Cmd) {
|
|||||||
if m.persistence {
|
if m.persistence {
|
||||||
err := m.persistConversation()
|
err := m.persistConversation()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return true, shared.WrapError(err)
|
return true, wrapError(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -622,37 +526,14 @@ func (m *Model) HandleInputKey(msg tea.KeyMsg) (bool, tea.Cmd) {
|
|||||||
m.content.GotoBottom()
|
m.content.GotoBottom()
|
||||||
return true, cmd
|
return true, cmd
|
||||||
case "ctrl+e":
|
case "ctrl+e":
|
||||||
cmd := tuiutil.OpenTempfileEditor("message.*.md", m.input.Value(), "# Edit your input below\n")
|
cmd := openTempfileEditor("message.*.md", m.input.Value(), "# Edit your input below\n")
|
||||||
m.editorTarget = input
|
m.editorTarget = input
|
||||||
return true, cmd
|
return true, cmd
|
||||||
}
|
}
|
||||||
return false, nil
|
return false, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m Model) View() string {
|
func (m *chatModel) renderMessageHeading(i int, message *models.Message) 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...)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Model) renderMessageHeading(i int, message *models.Message) string {
|
|
||||||
icon := ""
|
icon := ""
|
||||||
friendly := message.Role.FriendlyRole()
|
friendly := message.Role.FriendlyRole()
|
||||||
style := lipgloss.NewStyle().Faint(true).Bold(true)
|
style := lipgloss.NewStyle().Faint(true).Bold(true)
|
||||||
@ -677,29 +558,6 @@ func (m *Model) renderMessageHeading(i int, message *models.Message) string {
|
|||||||
var suffix string
|
var suffix string
|
||||||
|
|
||||||
faint := lipgloss.NewStyle().Faint(true)
|
faint := lipgloss.NewStyle().Faint(true)
|
||||||
|
|
||||||
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)))
|
|
||||||
}
|
|
||||||
|
|
||||||
if m.focus == focusMessages {
|
if m.focus == focusMessages {
|
||||||
if i == m.selectedMessage {
|
if i == m.selectedMessage {
|
||||||
prefix = "> "
|
prefix = "> "
|
||||||
@ -713,14 +571,14 @@ func (m *Model) renderMessageHeading(i int, message *models.Message) string {
|
|||||||
return messageHeadingStyle.Render(prefix + user + suffix)
|
return messageHeadingStyle.Render(prefix + user + suffix)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Model) renderMessage(i int) string {
|
func (m *chatModel) renderMessage(i int) string {
|
||||||
msg := &m.messages[i]
|
msg := &m.messages[i]
|
||||||
|
|
||||||
// Write message contents
|
// Write message contents
|
||||||
sb := &strings.Builder{}
|
sb := &strings.Builder{}
|
||||||
sb.Grow(len(msg.Content) * 2)
|
sb.Grow(len(msg.Content) * 2)
|
||||||
if msg.Content != "" {
|
if msg.Content != "" {
|
||||||
err := m.State.Ctx.Chroma.Highlight(sb, msg.Content)
|
err := m.ctx.Chroma.Highlight(sb, msg.Content)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
sb.Reset()
|
sb.Reset()
|
||||||
sb.WriteString(msg.Content)
|
sb.WriteString(msg.Content)
|
||||||
@ -784,7 +642,7 @@ func (m *Model) renderMessage(i int) string {
|
|||||||
if msg.Content != "" {
|
if msg.Content != "" {
|
||||||
sb.WriteString("\n\n")
|
sb.WriteString("\n\n")
|
||||||
}
|
}
|
||||||
_ = m.State.Ctx.Chroma.HighlightLang(sb, toolString, "yaml")
|
_ = m.ctx.Chroma.HighlightLang(sb, toolString, "yaml")
|
||||||
}
|
}
|
||||||
|
|
||||||
content := strings.TrimRight(sb.String(), "\n")
|
content := strings.TrimRight(sb.String(), "\n")
|
||||||
@ -801,7 +659,7 @@ func (m *Model) renderMessage(i int) string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// render the conversation into a string
|
// render the conversation into a string
|
||||||
func (m *Model) conversationMessagesView() string {
|
func (m *chatModel) conversationMessagesView() string {
|
||||||
sb := strings.Builder{}
|
sb := strings.Builder{}
|
||||||
|
|
||||||
m.messageOffsets = make([]int, len(m.messages))
|
m.messageOffsets = make([]int, len(m.messages))
|
||||||
@ -842,7 +700,7 @@ func (m *Model) conversationMessagesView() string {
|
|||||||
return sb.String()
|
return sb.String()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Model) headerView() string {
|
func (m *chatModel) headerView() string {
|
||||||
titleStyle := lipgloss.NewStyle().Bold(true)
|
titleStyle := lipgloss.NewStyle().Bold(true)
|
||||||
var title string
|
var title string
|
||||||
if m.conversation != nil && m.conversation.Title != "" {
|
if m.conversation != nil && m.conversation.Title != "" {
|
||||||
@ -850,12 +708,12 @@ func (m *Model) headerView() string {
|
|||||||
} else {
|
} else {
|
||||||
title = "Untitled"
|
title = "Untitled"
|
||||||
}
|
}
|
||||||
title = tuiutil.TruncateToCellWidth(title, m.Width-styles.Header.GetHorizontalPadding(), "...")
|
title = truncateToCellWidth(title, m.width-headerStyle.GetHorizontalPadding(), "...")
|
||||||
header := titleStyle.Render(title)
|
header := titleStyle.Render(title)
|
||||||
return styles.Header.Width(m.Width).Render(header)
|
return headerStyle.Width(m.width).Render(header)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Model) footerView() string {
|
func (m *chatModel) footerView() string {
|
||||||
segmentStyle := lipgloss.NewStyle().PaddingLeft(1).PaddingRight(1).Faint(true)
|
segmentStyle := lipgloss.NewStyle().PaddingLeft(1).PaddingRight(1).Faint(true)
|
||||||
segmentSeparator := "|"
|
segmentSeparator := "|"
|
||||||
|
|
||||||
@ -883,14 +741,14 @@ func (m *Model) footerView() string {
|
|||||||
rightSegments = append(rightSegments, segmentStyle.Render(throughput))
|
rightSegments = append(rightSegments, segmentStyle.Render(throughput))
|
||||||
}
|
}
|
||||||
|
|
||||||
model := fmt.Sprintf("Model: %s", *m.State.Ctx.Config.Defaults.Model)
|
model := fmt.Sprintf("Model: %s", *m.ctx.Config.Defaults.Model)
|
||||||
rightSegments = append(rightSegments, segmentStyle.Render(model))
|
rightSegments = append(rightSegments, segmentStyle.Render(model))
|
||||||
|
|
||||||
left := strings.Join(leftSegments, segmentSeparator)
|
left := strings.Join(leftSegments, segmentSeparator)
|
||||||
right := strings.Join(rightSegments, segmentSeparator)
|
right := strings.Join(rightSegments, segmentSeparator)
|
||||||
|
|
||||||
totalWidth := lipgloss.Width(left) + lipgloss.Width(right)
|
totalWidth := lipgloss.Width(left) + lipgloss.Width(right)
|
||||||
remaining := m.Width - totalWidth
|
remaining := m.width - totalWidth
|
||||||
|
|
||||||
var padding string
|
var padding string
|
||||||
if remaining > 0 {
|
if remaining > 0 {
|
||||||
@ -899,12 +757,12 @@ func (m *Model) footerView() string {
|
|||||||
|
|
||||||
footer := left + padding + right
|
footer := left + padding + right
|
||||||
if remaining < 0 {
|
if remaining < 0 {
|
||||||
footer = tuiutil.TruncateToCellWidth(footer, m.Width, "...")
|
footer = truncateToCellWidth(footer, m.width, "...")
|
||||||
}
|
}
|
||||||
return footerStyle.Width(m.Width).Render(footer)
|
return footerStyle.Width(m.width).Render(footer)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Model) setMessage(i int, msg models.Message) {
|
func (m *chatModel) setMessage(i int, msg models.Message) {
|
||||||
if i >= len(m.messages) {
|
if i >= len(m.messages) {
|
||||||
panic("i out of range")
|
panic("i out of range")
|
||||||
}
|
}
|
||||||
@ -912,12 +770,12 @@ func (m *Model) setMessage(i int, msg models.Message) {
|
|||||||
m.messageCache[i] = m.renderMessage(i)
|
m.messageCache[i] = m.renderMessage(i)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Model) addMessage(msg models.Message) {
|
func (m *chatModel) addMessage(msg models.Message) {
|
||||||
m.messages = append(m.messages, msg)
|
m.messages = append(m.messages, msg)
|
||||||
m.messageCache = append(m.messageCache, m.renderMessage(len(m.messages)-1))
|
m.messageCache = append(m.messageCache, m.renderMessage(len(m.messages)-1))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Model) setMessageContents(i int, content string) {
|
func (m *chatModel) setMessageContents(i int, content string) {
|
||||||
if i >= len(m.messages) {
|
if i >= len(m.messages) {
|
||||||
panic("i out of range")
|
panic("i out of range")
|
||||||
}
|
}
|
||||||
@ -925,14 +783,14 @@ func (m *Model) setMessageContents(i int, content string) {
|
|||||||
m.messageCache[i] = m.renderMessage(i)
|
m.messageCache[i] = m.renderMessage(i)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Model) rebuildMessageCache() {
|
func (m *chatModel) rebuildMessageCache() {
|
||||||
m.messageCache = make([]string, len(m.messages))
|
m.messageCache = make([]string, len(m.messages))
|
||||||
for i := range m.messages {
|
for i := range m.messages {
|
||||||
m.messageCache[i] = m.renderMessage(i)
|
m.messageCache[i] = m.renderMessage(i)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Model) updateContent() {
|
func (m *chatModel) updateContent() {
|
||||||
atBottom := m.content.AtBottom()
|
atBottom := m.content.AtBottom()
|
||||||
m.content.SetContent(m.conversationMessagesView())
|
m.content.SetContent(m.conversationMessagesView())
|
||||||
if atBottom {
|
if atBottom {
|
||||||
@ -941,36 +799,36 @@ func (m *Model) updateContent() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Model) loadConversation(shortname string) tea.Cmd {
|
func (m *chatModel) loadConversation(shortname string) tea.Cmd {
|
||||||
return func() tea.Msg {
|
return func() tea.Msg {
|
||||||
if shortname == "" {
|
if shortname == "" {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
c, err := m.State.Ctx.Store.ConversationByShortName(shortname)
|
c, err := m.ctx.Store.ConversationByShortName(shortname)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return shared.MsgError(fmt.Errorf("Could not lookup conversation: %v", err))
|
return msgError(fmt.Errorf("Could not lookup conversation: %v", err))
|
||||||
}
|
}
|
||||||
if c.ID == 0 {
|
if c.ID == 0 {
|
||||||
return shared.MsgError(fmt.Errorf("Conversation not found: %s", shortname))
|
return msgError(fmt.Errorf("Conversation not found: %s", shortname))
|
||||||
}
|
}
|
||||||
return msgConversationLoaded(c)
|
return msgConversationLoaded(c)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Model) loadMessages(c *models.Conversation) tea.Cmd {
|
func (m *chatModel) loadMessages(c *models.Conversation) tea.Cmd {
|
||||||
return func() tea.Msg {
|
return func() tea.Msg {
|
||||||
messages, err := m.State.Ctx.Store.PathToLeaf(c.SelectedRoot)
|
messages, err := m.ctx.Store.PathToLeaf(c.SelectedRoot)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return shared.MsgError(fmt.Errorf("Could not load conversation messages: %v\n", err))
|
return msgError(fmt.Errorf("Could not load conversation messages: %v\n", err))
|
||||||
}
|
}
|
||||||
return msgMessagesLoaded(messages)
|
return msgMessagesLoaded(messages)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Model) persistConversation() error {
|
func (m *chatModel) persistConversation() error {
|
||||||
if m.conversation.ID == 0 {
|
if m.conversation.ID == 0 {
|
||||||
// Start a new conversation with all messages so far
|
// Start a new conversation with all messages so far
|
||||||
c, messages, err := m.State.Ctx.Store.StartConversation(m.messages...)
|
c, messages, err := m.ctx.Store.StartConversation(m.messages...)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@ -985,18 +843,16 @@ func (m *Model) persistConversation() error {
|
|||||||
if m.messages[i].ID > 0 {
|
if m.messages[i].ID > 0 {
|
||||||
// message has an ID, update its contents
|
// message has an ID, update its contents
|
||||||
// TODO: check for content/tool equality before updating?
|
// TODO: check for content/tool equality before updating?
|
||||||
err := m.State.Ctx.Store.UpdateMessage(&m.messages[i])
|
err := m.ctx.Store.UpdateMessage(&m.messages[i])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
} else if i > 0 {
|
} else if i > 0 {
|
||||||
// messages is new, so add it as a reply to previous message
|
// messages is new, so add it as a reply to previous message
|
||||||
saved, err := m.State.Ctx.Store.Reply(&m.messages[i-1], m.messages[i])
|
saved, err := m.ctx.Store.Reply(&m.messages[i-1], m.messages[i])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
// add this message as a reply to the previous
|
|
||||||
m.messages[i-1].Replies = append(m.messages[i-1].Replies, saved[0])
|
|
||||||
m.messages[i] = saved[0]
|
m.messages[i] = saved[0]
|
||||||
} else {
|
} else {
|
||||||
// message has no id and no previous messages to add it to
|
// message has no id and no previous messages to add it to
|
||||||
@ -1008,29 +864,29 @@ func (m *Model) persistConversation() error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Model) generateConversationTitle() tea.Cmd {
|
func (m *chatModel) generateConversationTitle() tea.Cmd {
|
||||||
return func() tea.Msg {
|
return func() tea.Msg {
|
||||||
title, err := cmdutil.GenerateTitle(m.State.Ctx, m.messages)
|
title, err := cmdutil.GenerateTitle(m.ctx, m.messages)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return shared.MsgError(err)
|
return msgError(err)
|
||||||
}
|
}
|
||||||
return msgConversationTitleChanged(title)
|
return msgConversationTitleChanged(title)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Model) waitForReply() tea.Cmd {
|
func (m *chatModel) waitForReply() tea.Cmd {
|
||||||
return func() tea.Msg {
|
return func() tea.Msg {
|
||||||
return msgAssistantReply(<-m.replyChan)
|
return msgAssistantReply(<-m.replyChan)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Model) waitForChunk() tea.Cmd {
|
func (m *chatModel) waitForChunk() tea.Cmd {
|
||||||
return func() tea.Msg {
|
return func() tea.Msg {
|
||||||
return msgResponseChunk(<-m.replyChunkChan)
|
return msgResponseChunk(<-m.replyChunkChan)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Model) promptLLM() tea.Cmd {
|
func (m *chatModel) promptLLM() tea.Cmd {
|
||||||
m.waitingForReply = true
|
m.waitingForReply = true
|
||||||
m.replyCursor.Blink = false
|
m.replyCursor.Blink = false
|
||||||
m.status = "Press ctrl+c to cancel"
|
m.status = "Press ctrl+c to cancel"
|
||||||
@ -1050,16 +906,16 @@ func (m *Model) promptLLM() tea.Cmd {
|
|||||||
m.elapsed = 0
|
m.elapsed = 0
|
||||||
|
|
||||||
return func() tea.Msg {
|
return func() tea.Msg {
|
||||||
completionProvider, err := m.State.Ctx.GetCompletionProvider(*m.State.Ctx.Config.Defaults.Model)
|
completionProvider, err := m.ctx.GetCompletionProvider(*m.ctx.Config.Defaults.Model)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return shared.MsgError(err)
|
return msgError(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
requestParams := models.RequestParameters{
|
requestParams := models.RequestParameters{
|
||||||
Model: *m.State.Ctx.Config.Defaults.Model,
|
Model: *m.ctx.Config.Defaults.Model,
|
||||||
MaxTokens: *m.State.Ctx.Config.Defaults.MaxTokens,
|
MaxTokens: *m.ctx.Config.Defaults.MaxTokens,
|
||||||
Temperature: *m.State.Ctx.Config.Defaults.Temperature,
|
Temperature: *m.ctx.Config.Defaults.Temperature,
|
||||||
ToolBag: m.State.Ctx.EnabledTools,
|
ToolBag: m.ctx.EnabledTools,
|
||||||
}
|
}
|
||||||
|
|
||||||
replyHandler := func(msg models.Message) {
|
replyHandler := func(msg models.Message) {
|
@ -1,4 +1,4 @@
|
|||||||
package conversations
|
package tui
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
@ -6,9 +6,6 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
models "git.mlow.ca/mlow/lmcli/pkg/lmcli/model"
|
models "git.mlow.ca/mlow/lmcli/pkg/lmcli/model"
|
||||||
"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"
|
|
||||||
"git.mlow.ca/mlow/lmcli/pkg/util"
|
"git.mlow.ca/mlow/lmcli/pkg/util"
|
||||||
"github.com/charmbracelet/bubbles/viewport"
|
"github.com/charmbracelet/bubbles/viewport"
|
||||||
tea "github.com/charmbracelet/bubbletea"
|
tea "github.com/charmbracelet/bubbletea"
|
||||||
@ -27,9 +24,8 @@ type (
|
|||||||
msgConversationSelected models.Conversation
|
msgConversationSelected models.Conversation
|
||||||
)
|
)
|
||||||
|
|
||||||
type Model struct {
|
type conversationsModel struct {
|
||||||
shared.State
|
basemodel
|
||||||
shared.Sections
|
|
||||||
|
|
||||||
conversations []loadedConversation
|
conversations []loadedConversation
|
||||||
cursor int // index of the currently selected conversation
|
cursor int // index of the currently selected conversation
|
||||||
@ -38,15 +34,21 @@ type Model struct {
|
|||||||
content viewport.Model
|
content viewport.Model
|
||||||
}
|
}
|
||||||
|
|
||||||
func Conversations(state shared.State) Model {
|
func newConversationsModel(tui *model) conversationsModel {
|
||||||
m := Model{
|
m := conversationsModel{
|
||||||
State: state,
|
basemodel: basemodel{
|
||||||
|
opts: tui.opts,
|
||||||
|
ctx: tui.ctx,
|
||||||
|
views: tui.views,
|
||||||
|
width: tui.width,
|
||||||
|
height: tui.height,
|
||||||
|
},
|
||||||
content: viewport.New(0, 0),
|
content: viewport.New(0, 0),
|
||||||
}
|
}
|
||||||
return m
|
return m
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Model) HandleInput(msg tea.KeyMsg) (bool, tea.Cmd) {
|
func (m *conversationsModel) handleInput(msg tea.KeyMsg) (bool, tea.Cmd) {
|
||||||
switch msg.String() {
|
switch msg.String() {
|
||||||
case "enter":
|
case "enter":
|
||||||
if len(m.conversations) > 0 && m.cursor < len(m.conversations) {
|
if len(m.conversations) > 0 && m.cursor < len(m.conversations) {
|
||||||
@ -64,7 +66,7 @@ func (m *Model) HandleInput(msg tea.KeyMsg) (bool, tea.Cmd) {
|
|||||||
// this hack positions the *next* conversatoin slightly
|
// this hack positions the *next* conversatoin slightly
|
||||||
// *off* the screen, ensuring the entire m.cursor is shown,
|
// *off* the screen, ensuring the entire m.cursor is shown,
|
||||||
// even if its height may not be constant due to wrapping.
|
// even if its height may not be constant due to wrapping.
|
||||||
tuiutil.ScrollIntoView(&m.content, m.itemOffsets[m.cursor+1], -1)
|
scrollIntoView(&m.content, m.itemOffsets[m.cursor+1], -1)
|
||||||
}
|
}
|
||||||
m.content.SetContent(m.renderConversationList())
|
m.content.SetContent(m.renderConversationList())
|
||||||
} else {
|
} else {
|
||||||
@ -78,7 +80,7 @@ func (m *Model) HandleInput(msg tea.KeyMsg) (bool, tea.Cmd) {
|
|||||||
if m.cursor == 0 {
|
if m.cursor == 0 {
|
||||||
m.content.GotoTop()
|
m.content.GotoTop()
|
||||||
} else {
|
} else {
|
||||||
tuiutil.ScrollIntoView(&m.content, m.itemOffsets[m.cursor], 1)
|
scrollIntoView(&m.content, m.itemOffsets[m.cursor], 1)
|
||||||
}
|
}
|
||||||
m.content.SetContent(m.renderConversationList())
|
m.content.SetContent(m.renderConversationList())
|
||||||
} else {
|
} else {
|
||||||
@ -100,32 +102,27 @@ func (m *Model) HandleInput(msg tea.KeyMsg) (bool, tea.Cmd) {
|
|||||||
return false, nil
|
return false, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m Model) Init() tea.Cmd {
|
func (m conversationsModel) Init() tea.Cmd {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Model) HandleResize(width, height int) {
|
func (m *conversationsModel) handleResize(width, height int) {
|
||||||
m.Width, m.Height = width, height
|
m.width, m.height = width, height
|
||||||
m.content.Width = width
|
m.content.Width = width
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
|
func (m conversationsModel) Update(msg tea.Msg) (conversationsModel, tea.Cmd) {
|
||||||
var cmds []tea.Cmd
|
var cmds []tea.Cmd
|
||||||
switch msg := msg.(type) {
|
switch msg := msg.(type) {
|
||||||
case shared.MsgViewEnter:
|
case msgStateEnter:
|
||||||
cmds = append(cmds, m.loadConversations())
|
cmds = append(cmds, m.loadConversations())
|
||||||
m.content.SetContent(m.renderConversationList())
|
m.content.SetContent(m.renderConversationList())
|
||||||
case tea.WindowSizeMsg:
|
case tea.WindowSizeMsg:
|
||||||
m.HandleResize(msg.Width, msg.Height)
|
m.handleResize(msg.Width, msg.Height)
|
||||||
m.content.SetContent(m.renderConversationList())
|
m.content.SetContent(m.renderConversationList())
|
||||||
case msgConversationsLoaded:
|
case msgConversationsLoaded:
|
||||||
m.conversations = msg
|
m.conversations = msg
|
||||||
m.content.SetContent(m.renderConversationList())
|
m.content.SetContent(m.renderConversationList())
|
||||||
case msgConversationSelected:
|
|
||||||
m.Values.ConvShortname = msg.ShortName.String
|
|
||||||
cmds = append(cmds, func() tea.Msg {
|
|
||||||
return shared.MsgViewChange(shared.StateChat)
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var cmd tea.Cmd
|
var cmd tea.Cmd
|
||||||
@ -134,22 +131,22 @@ func (m Model) Update(msg tea.Msg) (Model, tea.Cmd) {
|
|||||||
cmds = append(cmds, cmd)
|
cmds = append(cmds, cmd)
|
||||||
}
|
}
|
||||||
|
|
||||||
if m.Width > 0 {
|
if m.width > 0 {
|
||||||
m.Header = m.headerView()
|
m.views.header = m.headerView()
|
||||||
m.Footer = "" // TODO: show /something/
|
m.views.footer = "" // TODO: show /something/
|
||||||
m.Error = tuiutil.ErrorBanner(m.Err, m.Width)
|
m.views.error = errorBanner(m.err, m.width)
|
||||||
fixedHeight := tuiutil.Height(m.Header) + tuiutil.Height(m.Error) + tuiutil.Height(m.Footer)
|
fixedHeight := height(m.views.header) + height(m.views.error) + height(m.views.footer)
|
||||||
m.content.Height = m.Height - fixedHeight
|
m.content.Height = m.height - fixedHeight
|
||||||
m.Content = m.content.View()
|
m.views.content = m.content.View()
|
||||||
}
|
}
|
||||||
return m, tea.Batch(cmds...)
|
return m, tea.Batch(cmds...)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Model) loadConversations() tea.Cmd {
|
func (m *conversationsModel) loadConversations() tea.Cmd {
|
||||||
return func() tea.Msg {
|
return func() tea.Msg {
|
||||||
messages, err := m.Ctx.Store.LatestConversationMessages()
|
messages, err := m.ctx.Store.LatestConversationMessages()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return shared.MsgError(fmt.Errorf("Could not load conversations: %v", err))
|
return msgError(fmt.Errorf("Could not load conversations: %v", err))
|
||||||
}
|
}
|
||||||
|
|
||||||
loaded := make([]loadedConversation, len(messages))
|
loaded := make([]loadedConversation, len(messages))
|
||||||
@ -162,35 +159,13 @@ func (m *Model) loadConversations() tea.Cmd {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m Model) View() string {
|
func (m *conversationsModel) headerView() 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)
|
|
||||||
}
|
|
||||||
|
|
||||||
if m.Footer != "" {
|
|
||||||
sections = append(sections, m.Footer)
|
|
||||||
}
|
|
||||||
|
|
||||||
return lipgloss.JoinVertical(lipgloss.Left, sections...)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *Model) headerView() string {
|
|
||||||
titleStyle := lipgloss.NewStyle().Bold(true)
|
titleStyle := lipgloss.NewStyle().Bold(true)
|
||||||
header := titleStyle.Render("Conversations")
|
header := titleStyle.Render("Conversations")
|
||||||
return styles.Header.Width(m.Width).Render(header)
|
return headerStyle.Width(m.width).Render(header)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Model) renderConversationList() string {
|
func (m *conversationsModel) renderConversationList() string {
|
||||||
now := time.Now()
|
now := time.Now()
|
||||||
midnight := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
|
midnight := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
|
||||||
monthStart := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, now.Location())
|
monthStart := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, now.Location())
|
||||||
@ -253,7 +228,7 @@ func (m *Model) renderConversationList() string {
|
|||||||
currentCategory = category
|
currentCategory = category
|
||||||
heading := categoryStyle.Render(currentCategory)
|
heading := categoryStyle.Render(currentCategory)
|
||||||
sb.WriteString(heading)
|
sb.WriteString(heading)
|
||||||
currentOffset += tuiutil.Height(heading)
|
currentOffset += height(heading)
|
||||||
sb.WriteRune('\n')
|
sb.WriteRune('\n')
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -265,7 +240,7 @@ func (m *Model) renderConversationList() string {
|
|||||||
tStyle = tStyle.Inherit(selectedStyle)
|
tStyle = tStyle.Inherit(selectedStyle)
|
||||||
}
|
}
|
||||||
|
|
||||||
title := tStyle.Width(m.Width - 3).PaddingLeft(2).Render(c.conv.Title)
|
title := tStyle.Width(m.width - 3).PaddingLeft(2).Render(c.conv.Title)
|
||||||
if i == m.cursor {
|
if i == m.cursor {
|
||||||
title = ">" + title[1:]
|
title = ">" + title[1:]
|
||||||
}
|
}
|
||||||
@ -277,7 +252,7 @@ func (m *Model) renderConversationList() string {
|
|||||||
ageStyle.Render(util.HumanTimeElapsedSince(lastReplyAge)),
|
ageStyle.Render(util.HumanTimeElapsedSince(lastReplyAge)),
|
||||||
))
|
))
|
||||||
sb.WriteString(item)
|
sb.WriteString(item)
|
||||||
currentOffset += tuiutil.Height(item)
|
currentOffset += height(item)
|
||||||
if i < len(m.conversations)-1 {
|
if i < len(m.conversations)-1 {
|
||||||
sb.WriteRune('\n')
|
sb.WriteRune('\n')
|
||||||
}
|
}
|
@ -1,52 +0,0 @@
|
|||||||
package shared
|
|
||||||
|
|
||||||
import (
|
|
||||||
"git.mlow.ca/mlow/lmcli/pkg/lmcli"
|
|
||||||
tea "github.com/charmbracelet/bubbletea"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Values struct {
|
|
||||||
ConvShortname string
|
|
||||||
}
|
|
||||||
|
|
||||||
type State struct {
|
|
||||||
Ctx *lmcli.Context
|
|
||||||
Values *Values
|
|
||||||
Width int
|
|
||||||
Height int
|
|
||||||
Err error
|
|
||||||
}
|
|
||||||
|
|
||||||
// a convenience struct for holding rendered content for indiviudal UI
|
|
||||||
// elements
|
|
||||||
type Sections struct {
|
|
||||||
Header string
|
|
||||||
Content string
|
|
||||||
Error string
|
|
||||||
Input string
|
|
||||||
Footer string
|
|
||||||
}
|
|
||||||
|
|
||||||
type (
|
|
||||||
// send to change the current state
|
|
||||||
MsgViewChange View
|
|
||||||
// sent to a state when it is entered
|
|
||||||
MsgViewEnter struct{}
|
|
||||||
// sent when an error occurs
|
|
||||||
MsgError error
|
|
||||||
)
|
|
||||||
|
|
||||||
func WrapError(err error) tea.Cmd {
|
|
||||||
return func() tea.Msg {
|
|
||||||
return MsgError(err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type View int
|
|
||||||
|
|
||||||
const (
|
|
||||||
StateChat View = iota
|
|
||||||
StateConversations
|
|
||||||
//StateSettings
|
|
||||||
//StateHelp
|
|
||||||
)
|
|
@ -1,8 +0,0 @@
|
|||||||
package styles
|
|
||||||
|
|
||||||
import "github.com/charmbracelet/lipgloss"
|
|
||||||
|
|
||||||
var Header = lipgloss.NewStyle().
|
|
||||||
PaddingLeft(1).
|
|
||||||
PaddingRight(1).
|
|
||||||
Background(lipgloss.Color("0"))
|
|
177
pkg/tui/tui.go
177
pkg/tui/tui.go
@ -10,60 +10,99 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
"git.mlow.ca/mlow/lmcli/pkg/lmcli"
|
"git.mlow.ca/mlow/lmcli/pkg/lmcli"
|
||||||
"git.mlow.ca/mlow/lmcli/pkg/tui/shared"
|
|
||||||
"git.mlow.ca/mlow/lmcli/pkg/tui/views/chat"
|
|
||||||
"git.mlow.ca/mlow/lmcli/pkg/tui/views/conversations"
|
|
||||||
tea "github.com/charmbracelet/bubbletea"
|
tea "github.com/charmbracelet/bubbletea"
|
||||||
|
"github.com/charmbracelet/lipgloss"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Application model
|
type state int
|
||||||
type Model struct {
|
|
||||||
shared.State
|
|
||||||
|
|
||||||
state shared.View
|
const (
|
||||||
chat chat.Model
|
stateChat = iota
|
||||||
conversations conversations.Model
|
stateConversations
|
||||||
|
//stateModelSelect // stateOptions?
|
||||||
|
//stateHelp
|
||||||
|
)
|
||||||
|
|
||||||
|
// this struct holds the final rendered content of various UI components, and
|
||||||
|
// gets populated in the application's Update() method. View() simply composes
|
||||||
|
// these elements into the final output
|
||||||
|
type views struct {
|
||||||
|
header string
|
||||||
|
content string
|
||||||
|
error string
|
||||||
|
input string
|
||||||
|
footer string
|
||||||
}
|
}
|
||||||
|
|
||||||
func initialModel(ctx *lmcli.Context, values shared.Values) Model {
|
type (
|
||||||
m := Model{
|
// send to change the current state
|
||||||
State: shared.State{
|
msgStateChange state
|
||||||
Ctx: ctx,
|
// sent to a state when it is entered
|
||||||
Values: &values,
|
msgStateEnter struct{}
|
||||||
|
// sent when an error occurs
|
||||||
|
msgError error
|
||||||
|
)
|
||||||
|
|
||||||
|
type Options struct {
|
||||||
|
convShortname string
|
||||||
|
}
|
||||||
|
|
||||||
|
type basemodel struct {
|
||||||
|
opts *Options
|
||||||
|
ctx *lmcli.Context
|
||||||
|
views *views
|
||||||
|
err error
|
||||||
|
width int
|
||||||
|
height int
|
||||||
|
}
|
||||||
|
|
||||||
|
type model struct {
|
||||||
|
basemodel
|
||||||
|
|
||||||
|
state state
|
||||||
|
chat chatModel
|
||||||
|
conversations conversationsModel
|
||||||
|
}
|
||||||
|
|
||||||
|
func initialModel(ctx *lmcli.Context, opts Options) model {
|
||||||
|
m := model{
|
||||||
|
basemodel: basemodel{
|
||||||
|
opts: &opts,
|
||||||
|
ctx: ctx,
|
||||||
|
views: &views{},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
m.state = stateChat
|
||||||
m.state = shared.StateChat
|
m.chat = newChatModel(&m)
|
||||||
m.chat = chat.Chat(m.State)
|
m.conversations = newConversationsModel(&m)
|
||||||
m.conversations = conversations.Conversations(m.State)
|
|
||||||
return m
|
return m
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m Model) Init() tea.Cmd {
|
func (m model) Init() tea.Cmd {
|
||||||
return tea.Batch(
|
return tea.Batch(
|
||||||
m.conversations.Init(),
|
m.conversations.Init(),
|
||||||
m.chat.Init(),
|
m.chat.Init(),
|
||||||
func() tea.Msg {
|
func() tea.Msg {
|
||||||
return shared.MsgViewChange(m.state)
|
return msgStateChange(m.state)
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *Model) handleGlobalInput(msg tea.KeyMsg) (bool, tea.Cmd) {
|
func (m *model) handleGlobalInput(msg tea.KeyMsg) (bool, tea.Cmd) {
|
||||||
// delegate input to the active child state first, only handling it at the
|
// delegate input to the active child state first, only handling it at the
|
||||||
// global level if the child state does not
|
// global level if the child state does not
|
||||||
var cmds []tea.Cmd
|
var cmds []tea.Cmd
|
||||||
switch m.state {
|
switch m.state {
|
||||||
case shared.StateChat:
|
case stateChat:
|
||||||
handled, cmd := m.chat.HandleInput(msg)
|
handled, cmd := m.chat.handleInput(msg)
|
||||||
cmds = append(cmds, cmd)
|
cmds = append(cmds, cmd)
|
||||||
if handled {
|
if handled {
|
||||||
m.chat, cmd = m.chat.Update(nil)
|
m.chat, cmd = m.chat.Update(nil)
|
||||||
cmds = append(cmds, cmd)
|
cmds = append(cmds, cmd)
|
||||||
return true, tea.Batch(cmds...)
|
return true, tea.Batch(cmds...)
|
||||||
}
|
}
|
||||||
case shared.StateConversations:
|
case stateConversations:
|
||||||
handled, cmd := m.conversations.HandleInput(msg)
|
handled, cmd := m.conversations.handleInput(msg)
|
||||||
cmds = append(cmds, cmd)
|
cmds = append(cmds, cmd)
|
||||||
if handled {
|
if handled {
|
||||||
m.conversations, cmd = m.conversations.Update(nil)
|
m.conversations, cmd = m.conversations.Update(nil)
|
||||||
@ -78,7 +117,7 @@ func (m *Model) handleGlobalInput(msg tea.KeyMsg) (bool, tea.Cmd) {
|
|||||||
return false, nil
|
return false, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
||||||
var cmds []tea.Cmd
|
var cmds []tea.Cmd
|
||||||
|
|
||||||
switch msg := msg.(type) {
|
switch msg := msg.(type) {
|
||||||
@ -87,24 +126,32 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
if handled {
|
if handled {
|
||||||
return m, cmd
|
return m, cmd
|
||||||
}
|
}
|
||||||
case shared.MsgViewChange:
|
case msgStateChange:
|
||||||
m.state = shared.View(msg)
|
m.state = state(msg)
|
||||||
switch m.state {
|
switch m.state {
|
||||||
case shared.StateChat:
|
case stateChat:
|
||||||
m.chat.HandleResize(m.Width, m.Height)
|
m.chat.handleResize(m.width, m.height)
|
||||||
case shared.StateConversations:
|
case stateConversations:
|
||||||
m.conversations.HandleResize(m.Width, m.Height)
|
m.conversations.handleResize(m.width, m.height)
|
||||||
}
|
}
|
||||||
return m, func() tea.Msg { return shared.MsgViewEnter(struct{}{}) }
|
return m, func() tea.Msg { return msgStateEnter(struct{}{}) }
|
||||||
|
case msgConversationSelected:
|
||||||
|
// passed up through conversation list model
|
||||||
|
m.opts.convShortname = msg.ShortName.String
|
||||||
|
cmds = append(cmds, func() tea.Msg {
|
||||||
|
return msgStateChange(stateChat)
|
||||||
|
})
|
||||||
case tea.WindowSizeMsg:
|
case tea.WindowSizeMsg:
|
||||||
m.Width, m.Height = msg.Width, msg.Height
|
m.width, m.height = msg.Width, msg.Height
|
||||||
|
case msgError:
|
||||||
|
m.err = msg
|
||||||
}
|
}
|
||||||
|
|
||||||
var cmd tea.Cmd
|
var cmd tea.Cmd
|
||||||
switch m.state {
|
switch m.state {
|
||||||
case shared.StateConversations:
|
case stateConversations:
|
||||||
m.conversations, cmd = m.conversations.Update(msg)
|
m.conversations, cmd = m.conversations.Update(msg)
|
||||||
case shared.StateChat:
|
case stateChat:
|
||||||
m.chat, cmd = m.chat.Update(msg)
|
m.chat, cmd = m.chat.Update(msg)
|
||||||
}
|
}
|
||||||
if cmd != nil {
|
if cmd != nil {
|
||||||
@ -114,18 +161,60 @@ func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
|
|||||||
return m, tea.Batch(cmds...)
|
return m, tea.Batch(cmds...)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m Model) View() string {
|
func (m model) View() string {
|
||||||
switch m.state {
|
if m.width == 0 {
|
||||||
case shared.StateConversations:
|
// this is the case upon initial startup, but it's also a safe bet that
|
||||||
return m.conversations.View()
|
// we can just skip rendering if the terminal is really 0 width...
|
||||||
case shared.StateChat:
|
// without this, the m.*View() functions may crash
|
||||||
return m.chat.View()
|
|
||||||
}
|
|
||||||
return ""
|
return ""
|
||||||
|
}
|
||||||
|
sections := make([]string, 0, 6)
|
||||||
|
|
||||||
|
if m.views.header != "" {
|
||||||
|
sections = append(sections, m.views.header)
|
||||||
|
}
|
||||||
|
|
||||||
|
switch m.state {
|
||||||
|
case stateConversations:
|
||||||
|
sections = append(sections, m.views.content)
|
||||||
|
if m.views.error != "" {
|
||||||
|
sections = append(sections, m.views.error)
|
||||||
|
}
|
||||||
|
case stateChat:
|
||||||
|
sections = append(sections, m.views.content)
|
||||||
|
if m.views.error != "" {
|
||||||
|
sections = append(sections, m.views.error)
|
||||||
|
}
|
||||||
|
sections = append(sections, m.views.input)
|
||||||
|
}
|
||||||
|
|
||||||
|
if m.views.footer != "" {
|
||||||
|
sections = append(sections, m.views.footer)
|
||||||
|
}
|
||||||
|
|
||||||
|
return lipgloss.JoinVertical(lipgloss.Left, sections...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func errorBanner(err error, width int) string {
|
||||||
|
if err == nil {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
return lipgloss.NewStyle().
|
||||||
|
Width(width).
|
||||||
|
AlignHorizontal(lipgloss.Center).
|
||||||
|
Bold(true).
|
||||||
|
Foreground(lipgloss.Color("1")).
|
||||||
|
Render(fmt.Sprintf("%s", err))
|
||||||
|
}
|
||||||
|
|
||||||
|
func wrapError(err error) tea.Cmd {
|
||||||
|
return func() tea.Msg {
|
||||||
|
return msgError(err)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func Launch(ctx *lmcli.Context, convShortname string) error {
|
func Launch(ctx *lmcli.Context, convShortname string) error {
|
||||||
p := tea.NewProgram(initialModel(ctx, shared.Values{ConvShortname: convShortname}), tea.WithAltScreen())
|
p := tea.NewProgram(initialModel(ctx, Options{convShortname}), tea.WithAltScreen())
|
||||||
if _, err := p.Run(); err != nil {
|
if _, err := p.Run(); err != nil {
|
||||||
return fmt.Errorf("Error running program: %v", err)
|
return fmt.Errorf("Error running program: %v", err)
|
||||||
}
|
}
|
||||||
|
@ -1,28 +1,26 @@
|
|||||||
package util
|
package tui
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
|
||||||
"os"
|
"os"
|
||||||
"os/exec"
|
"os/exec"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/charmbracelet/bubbles/viewport"
|
"github.com/charmbracelet/bubbles/viewport"
|
||||||
tea "github.com/charmbracelet/bubbletea"
|
tea "github.com/charmbracelet/bubbletea"
|
||||||
"github.com/charmbracelet/lipgloss"
|
|
||||||
"github.com/muesli/reflow/ansi"
|
"github.com/muesli/reflow/ansi"
|
||||||
)
|
)
|
||||||
|
|
||||||
type MsgTempfileEditorClosed string
|
type msgTempfileEditorClosed string
|
||||||
|
|
||||||
// OpenTempfileEditor opens $EDITOR on a temporary file with the given content.
|
// openTempfileEditor opens an $EDITOR on a new temporary file with the given
|
||||||
// Upon closing, the contents of the file are read and returned wrapped in a
|
// content. Upon closing, the contents of the file are read back returned
|
||||||
// MsgTempfileEditorClosed
|
// wrapped in a msgTempfileEditorClosed returned by the tea.Cmd
|
||||||
func OpenTempfileEditor(pattern string, content string, placeholder string) tea.Cmd {
|
func openTempfileEditor(pattern string, content string, placeholder string) tea.Cmd {
|
||||||
msgFile, _ := os.CreateTemp("/tmp", pattern)
|
msgFile, _ := os.CreateTemp("/tmp", pattern)
|
||||||
|
|
||||||
err := os.WriteFile(msgFile.Name(), []byte(placeholder+content), os.ModeAppend)
|
err := os.WriteFile(msgFile.Name(), []byte(placeholder+content), os.ModeAppend)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return func() tea.Msg { return err }
|
return wrapError(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
editor := os.Getenv("EDITOR")
|
editor := os.Getenv("EDITOR")
|
||||||
@ -34,7 +32,7 @@ func OpenTempfileEditor(pattern string, content string, placeholder string) tea.
|
|||||||
return tea.ExecProcess(c, func(err error) tea.Msg {
|
return tea.ExecProcess(c, func(err error) tea.Msg {
|
||||||
bytes, err := os.ReadFile(msgFile.Name())
|
bytes, err := os.ReadFile(msgFile.Name())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return msgError(err)
|
||||||
}
|
}
|
||||||
os.Remove(msgFile.Name())
|
os.Remove(msgFile.Name())
|
||||||
fileContents := string(bytes)
|
fileContents := string(bytes)
|
||||||
@ -42,12 +40,12 @@ func OpenTempfileEditor(pattern string, content string, placeholder string) tea.
|
|||||||
fileContents = fileContents[len(placeholder):]
|
fileContents = fileContents[len(placeholder):]
|
||||||
}
|
}
|
||||||
stripped := strings.Trim(fileContents, "\n \t")
|
stripped := strings.Trim(fileContents, "\n \t")
|
||||||
return MsgTempfileEditorClosed(stripped)
|
return msgTempfileEditorClosed(stripped)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// similar to lipgloss.Height, except returns 0 instead of 1 on empty strings
|
// similar to lipgloss.Height, except returns 0 on empty strings
|
||||||
func Height(str string) int {
|
func height(str string) int {
|
||||||
if str == "" {
|
if str == "" {
|
||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
@ -56,7 +54,7 @@ func Height(str string) int {
|
|||||||
|
|
||||||
// truncate a string until its rendered cell width + the provided tail fits
|
// truncate a string until its rendered cell width + the provided tail fits
|
||||||
// within the given width
|
// within the given width
|
||||||
func TruncateToCellWidth(str string, width int, tail string) string {
|
func truncateToCellWidth(str string, width int, tail string) string {
|
||||||
cellWidth := ansi.PrintableRuneWidth(str)
|
cellWidth := ansi.PrintableRuneWidth(str)
|
||||||
if cellWidth <= width {
|
if cellWidth <= width {
|
||||||
return str
|
return str
|
||||||
@ -72,7 +70,10 @@ func TruncateToCellWidth(str string, width int, tail string) string {
|
|||||||
return str + tail
|
return str + tail
|
||||||
}
|
}
|
||||||
|
|
||||||
func ScrollIntoView(vp *viewport.Model, offset int, edge int) {
|
// 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, edge int) {
|
||||||
currentOffset := vp.YOffset
|
currentOffset := vp.YOffset
|
||||||
if offset >= currentOffset && offset < currentOffset+vp.Height {
|
if offset >= currentOffset && offset < currentOffset+vp.Height {
|
||||||
return
|
return
|
||||||
@ -86,16 +87,3 @@ func ScrollIntoView(vp *viewport.Model, offset int, edge int) {
|
|||||||
vp.SetYOffset(currentOffset - distance - edge)
|
vp.SetYOffset(currentOffset - distance - edge)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func ErrorBanner(err error, width int) string {
|
|
||||||
if err == nil {
|
|
||||||
return ""
|
|
||||||
}
|
|
||||||
return lipgloss.NewStyle().
|
|
||||||
Width(width).
|
|
||||||
AlignHorizontal(lipgloss.Center).
|
|
||||||
Bold(true).
|
|
||||||
Foreground(lipgloss.Color("1")).
|
|
||||||
Render(fmt.Sprintf("%s", err))
|
|
||||||
}
|
|
||||||
|
|
Loading…
Reference in New Issue
Block a user