package tui import ( "context" "errors" "slices" "strings" "albedo/cli/internal/daemon" tea "charm.land/bubbletea/v2" "github.com/charmbracelet/x/ansi" ) // btwState is the side question panel over the chat: the latest exchange for // this session, whether the panel is open, and the work it started. type btwState struct { exchange *daemon.SideQuestion notice string pending *btwAdmission continueHandle *daemon.OperationHandle continueErr string open bool continuing bool scroll int maxScroll int } type btwAdmission struct { id string question string observed bool dismissed bool } type ChatSideQuestionAskedMsg struct { Err error Result daemon.SideQuestion QuestionID string SessionID string OriginalInput string Generation int64 } type ChatSideQuestionCancelMsg struct { Err error Result daemon.SideQuestion SessionID string Generation int64 } // ChatSideQuestionContinuedMsg reports a failed Continue. A successful one // arrives as ChatSideQuestionOpenMsg, which the app opens. type ChatSideQuestionContinuedMsg struct { Err error SessionID string QuestionID string Generation int64 } type ChatSideQuestionOpenMsg struct { Session daemon.Session SessionID string Generation int64 } // BtwOpen reports whether the side question panel is open. func (m ChatModel) BtwOpen() bool { return m.btw.open } func parseBtwInput(input string) (string, bool) { trimmed := strings.TrimSpace(input) if trimmed == "/btw" { return "", true } if question, ok := strings.CutPrefix(trimmed, "/btw "); ok { return strings.TrimSpace(question), true } if question, ok := strings.CutPrefix(trimmed, "/btw\t"); ok { return strings.TrimSpace(question), true } return "", false } // startSideQuestion runs /btw. It never becomes a prompt: an unsupported // daemon, an empty question and an admission failure all stay in the panel // or the composer. func (m *ChatModel) startSideQuestion(question, original string, cmds *[]tea.Cmd) { if question == "" { if m.btw.pending != nil { m.btw.pending.dismissed = false } m.btw.open = true m.btw.scroll = 0 if m.btw.exchange == nil && m.btw.pending == nil { m.btw.notice = "No side question yet. Type /btw followed by a question to ask one." } return } if !m.client.SideQuestionsSupported() { m.TextArea.SetValue(original) m.syncLayout() m.btw.open = true m.btw.notice = "This daemon is too old for side questions. Update the daemon, then ask again." return } if m.btw.pending != nil { m.TextArea.SetValue(original) m.syncLayout() m.AddError("A side question is still being sent.") return } id, err := daemon.NewSideQuestionID() if err != nil { m.TextArea.SetValue(original) m.syncLayout() m.AddError(err.Error()) return } m.ClearNotices() m.btw.open = true m.btw.notice = "" m.btw.pending = &btwAdmission{id: id, question: question} m.btw.scroll = 0 *cmds = append(*cmds, m.btwAskCmd(id, question, original)) } func (m ChatModel) btwAskCmd(id, question, original string) tea.Cmd { session, generation, client := m.SessionID, m.Generation, m.client return func() tea.Msg { result, err := client.AskSideQuestion(context.Background(), id, question) return ChatSideQuestionAskedMsg{Err: err, Result: result, QuestionID: id, SessionID: session, OriginalInput: original, Generation: generation} } } func (m ChatModel) btwCancelCmd(id string) tea.Cmd { session, generation, client := m.SessionID, m.Generation, m.client return func() tea.Msg { result, err := client.CancelSideQuestion(context.Background(), id) return ChatSideQuestionCancelMsg{Err: err, Result: result, SessionID: session, Generation: generation} } } func (m *ChatModel) setSideQuestion(question daemon.SideQuestion) { if m.btw.exchange == nil || m.btw.exchange.ID != question.ID { m.btw.scroll = 0 m.btw.continueHandle, m.btw.continueErr, m.btw.continuing = nil, "", false } if m.btw.pending != nil { m.btw.pending.observed = true } m.btw.exchange = &question m.btw.notice = "" } func (m *ChatModel) resetSideQuestion(question *daemon.SideQuestion) { if question == nil { m.btw.pending = nil m.btw.exchange = nil m.btw.scroll, m.btw.continueHandle, m.btw.continueErr, m.btw.continuing = 0, nil, "", false return } m.setSideQuestion(*question) } // dismissBtw closes the panel. A running question is cancelled; the exchange // itself stays for /btw to reopen. func (m *ChatModel) dismissBtw() tea.Cmd { m.btw.open = false if m.btw.pending != nil { m.btw.pending.dismissed = true } if m.btw.exchange != nil && m.btw.exchange.Status == "running" { return m.btwCancelCmd(string(m.btw.exchange.ID)) } return nil } func (m *ChatModel) btwContinueCmd() tea.Cmd { exchange := m.btw.exchange if exchange == nil || exchange.Status != "answered" || m.btw.continuing { return nil } session, generation, client := m.SessionID, m.Generation, m.client questionID := string(exchange.ID) target := exchange.ContinuationSessionID if target == nil && m.btw.continueHandle == nil { handle, err := daemon.NewCreation(daemon.CreateSessionRequest{Kind: "side_question", SourceSessionID: session, SideQuestionID: questionID}) if err != nil { m.btw.continueErr = err.Error() return nil } m.btw.continueHandle = handle } handle := m.btw.continueHandle m.btw.continuing = true m.btw.continueErr = "" return func() tea.Msg { var opened daemon.Session var err error if target != nil { opened, err = client.OpenSideQuestionContinuation(context.Background(), *target) } else { opened, err = client.ContinueSideQuestion(context.Background(), handle) } if err != nil { return ChatSideQuestionContinuedMsg{Err: err, SessionID: session, QuestionID: questionID, Generation: generation} } return ChatSideQuestionOpenMsg{Session: opened, SessionID: session, Generation: generation} } } // btwKey owns every key while the panel is open. Esc closes it here, so it // never reaches the turn interrupt behind the panel. func (m *ChatModel) btwKey(msg tea.KeyPressMsg) (tea.Cmd, bool) { switch msg.String() { case "esc", "ctrl+c": return m.dismissBtw(), true case "enter": if cmd := m.btwContinueCmd(); cmd != nil { return cmd, true } return nil, true case "up", "ctrl+p": m.btw.scroll = max(0, m.btw.scroll-1) case "down", "ctrl+n": m.btw.scroll = min(m.btw.maxScroll, m.btw.scroll+1) case "pgup": m.btw.scroll = max(0, m.btw.scroll-10) case "pgdown": m.btw.scroll = min(m.btw.maxScroll, m.btw.scroll+10) } return nil, true } func (m *ChatModel) handleBtwResult(msg tea.Msg) (tea.Cmd, bool) { switch msg := msg.(type) { case ChatSideQuestionAskedMsg: if msg.SessionID != m.SessionID || msg.Generation != m.Generation { return nil, true } if m.btw.pending == nil || msg.QuestionID != m.btw.pending.id { return nil, true } observed, dismissed := m.btw.pending.observed, m.btw.pending.dismissed m.btw.pending = nil if observed { if msg.Err != nil && m.btw.exchange != nil && string(m.btw.exchange.ID) != msg.QuestionID { m.AddError(msg.Err.Error()) } if dismissed && m.btw.exchange != nil && string(m.btw.exchange.ID) == msg.QuestionID && m.btw.exchange.Status == "running" { return m.btwCancelCmd(msg.QuestionID), true } return nil, true } if msg.Err != nil { m.btw.open = false m.TextArea.SetValue(msg.OriginalInput) m.syncLayout() m.AddError(msg.Err.Error()) return nil, true } m.setSideQuestion(msg.Result) m.btw.open = !dismissed if dismissed && msg.Result.Status == "running" { return m.btwCancelCmd(msg.QuestionID), true } return nil, true case ChatSideQuestionCancelMsg: if msg.SessionID != m.SessionID || msg.Generation != m.Generation { return nil, true } if msg.Err != nil { m.AddError(msg.Err.Error()) } else if m.btw.exchange != nil && m.btw.exchange.ID == msg.Result.ID { m.setSideQuestion(msg.Result) } return nil, true case ChatSideQuestionContinuedMsg: if msg.SessionID != m.SessionID || msg.Generation != m.Generation { return nil, true } m.btw.continuing = false if msg.Err == nil { return nil, true } var apiErr *daemon.APIError if errors.As(msg.Err, &apiErr) && apiErr.Code == "side_question_continued" && m.btw.exchange != nil && string(m.btw.exchange.ID) == msg.QuestionID && m.btw.exchange.ContinuationSessionID != nil && *m.btw.exchange.ContinuationSessionID != "" { // The stream named the session the other Continue created. return m.btwContinueCmd(), true } m.btw.continueErr = msg.Err.Error() return nil, true } return nil, false } // btwPanelView draws the panel box for overlay, at most two fifths of the // terminal height. The answer scrolls inside it; the question and the hint // line stay put. func (m *ChatModel) btwPanelView(width, height int) []string { outer := cdBoxWidth(width) if width >= 96 { outer = min(84, width-4) } inner := max(10, outer-6) maxRows := max(7, height*2/5) var question, status string var answer []string switch { case m.btw.pending != nil && !m.btw.pending.observed: question, status = m.btw.pending.question, "asking…" case m.btw.exchange != nil: exchange := m.btw.exchange question = exchange.Question switch exchange.Status { case "running": status = "asking…" case "failed": status = btwText(exchange.Error) case "cancelled": status = "cancelled" case "answered": answer = strings.Split(strings.Trim(RenderMarkdownAnsi(btwText(exchange.Answer), inner), "\n"), "\n") } case m.btw.notice != "": question = m.btw.notice default: question = "No side question yet." } var head []string for line := range strings.SplitSeq(ansi.Wrap(question, inner, " "), "\n") { head = append(head, line) } if status != "" && (m.btw.exchange == nil || m.btw.exchange.Status != "answered") { style := DefaultStyles.Faint.Render if m.btw.exchange != nil && m.btw.exchange.Status == "failed" { style = DefaultStyles.Error.Render } for line := range strings.SplitSeq(ansi.Wrap(status, inner, " "), "\n") { head = append(head, style(line)) } } if m.btw.continueErr != "" { for line := range strings.SplitSeq(ansi.Wrap(m.btw.continueErr, inner, " "), "\n") { head = append(head, DefaultStyles.Error.Render(line)) } } hint := m.btwPanelHint(len(answer) > 0) // head, a blank row and the hint stay; the answer gets what is left. visible := max(1, maxRows-2-len(head)-2) m.btw.maxScroll = max(0, len(answer)-visible) m.btw.scroll = max(0, min(m.btw.scroll, m.btw.maxScroll)) body := slices.Clone(head) if len(answer) > 0 { body = append(body, "") body = append(body, answer[m.btw.scroll:min(len(answer), m.btw.scroll+visible)]...) } body = append(body, "") body = append(body, strings.Repeat(" ", max(0, inner-ansi.StringWidth(hint)))+DefaultStyles.Faint.Render(hint)) return cdFrame("/btw", body, outer) } func (m ChatModel) btwPanelHint(hasAnswer bool) string { hint := "esc close" if hasAnswer { hint = "↑↓ scroll · " + hint } if m.btw.exchange != nil && m.btw.exchange.Status == "answered" { if m.btw.continuing { hint = "opening… · " + hint } else if m.btw.exchange.ContinuationSessionID != nil && *m.btw.exchange.ContinuationSessionID != "" { hint = "enter open continued session · " + hint } else { hint = "enter continue in new session · " + hint } } return hint } func btwText(pointer *string) string { if pointer == nil { return "" } return *pointer }