tui: fixed response cancelling

This commit is contained in:
Matt Low 2024-03-15 06:44:42 +00:00
parent 613aa1a552
commit 1c7ad75fd5
1 changed files with 15 additions and 7 deletions

View File

@ -44,9 +44,9 @@ type model struct {
conversation *models.Conversation
messages []models.Message
waitingForReply bool
stopSignal chan interface{}
replyChan chan models.Message
replyChunkChan chan string
replyCancelFunc context.CancelFunc
err error
persistence bool // whether we will save new messages in the conversation
@ -124,7 +124,7 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg.String() {
case "ctrl+c":
if m.waitingForReply {
m.replyCancelFunc()
m.stopSignal <- "stahp!"
} else {
return m, tea.Quit
}
@ -204,11 +204,9 @@ func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
m.updateContent()
cmds = append(cmds, m.waitForReply())
case msgResponseEnd:
m.replyCancelFunc = nil
m.waitingForReply = false
m.status = "Press ctrl+s to send"
case msgResponseError:
m.replyCancelFunc = nil
m.waitingForReply = false
m.status = "Press ctrl+s to send"
m.err = error(msg)
@ -375,6 +373,7 @@ func initialModel(ctx *lmcli.Context, convShortname string) model {
conversation: &models.Conversation{},
persistence: true,
stopSignal: make(chan interface{}),
replyChan: make(chan models.Message),
replyChunkChan: make(chan string),
}
@ -551,16 +550,25 @@ func (m *model) promptLLM() tea.Cmd {
m.replyChan <- msg
}
ctx, replyCancelFunc := context.WithCancel(context.Background())
m.replyCancelFunc = replyCancelFunc
ctx, cancel := context.WithCancel(context.Background())
canceled := false
go func() {
select {
case <-m.stopSignal:
canceled = true
cancel()
}
}()
resp, err := completionProvider.CreateChatCompletionStream(
ctx, requestParams, m.messages, replyHandler, m.replyChunkChan,
)
if err != nil {
if err != nil && !canceled {
return msgResponseError(err)
}
return msgResponseEnd(resp)
}
}