Skip to content

Get up and running with Kimi, GLM, MiniMax, DeepSeek, gpt-oss, Qwen, Gemma and other models.

agent/tui: stream thinking traces (#17611)

Parth Sareenf91cb0d6a774
diff --git a/cmd/tui/chat/chat.go b/cmd/tui/chat/chat.go
index 56df5bccd..8606f8770 100644
--- a/cmd/tui/chat/chat.go
+++ b/cmd/tui/chat/chat.go
@@ -100,46 +100,48 @@ type chatModel struct {
entries []chatEntry
workingDir string
- input []rune
- inputCursor int
- inputCursorSet bool
- inputAttachments []chatInputAttachment
- inputPastedTexts []chatInputPastedText
- nextImageID int
- nextAudioID int
- nextPastedTextID int
- promptHistory []string
- promptCursor int
- promptDraft []rune
- promptActive bool
- running bool
- awaitingModel bool
- compacting bool
- cancel context.CancelFunc
- events <-chan tea.Msg
- compactEvents <-chan tea.Msg
- detectedToolCalls []chatEntry
- scroll int
- toolOutputMode bool
- toolOutputOpen bool
- flowPrintedLines int
- thinking bool
- thinkingTokens int
- compactingTokens int
- contextTokens int
- contextEstimate bool
- modelPicker *chatModelPicker
- modelPickerModels []ModelOption
- thinkPicker *chatThinkPicker
- promptDebug *chatPromptDebug
- approvalPrompt *chatApprovalPrompt
- approvalController *chatApprovalController
- approvalState *coreagent.ApprovalState
- cloudAuthPrompt *cloudAuthPrompt
- pendingModel string
- defaultAllowAll bool
- permissionNotice string
- selection chatSelection
+ input []rune
+ inputCursor int
+ inputCursorSet bool
+ inputAttachments []chatInputAttachment
+ inputPastedTexts []chatInputPastedText
+ nextImageID int
+ nextAudioID int
+ nextPastedTextID int
+ promptHistory []string
+ promptCursor int
+ promptDraft []rune
+ promptActive bool
+ running bool
+ awaitingModel bool
+ compacting bool
+ cancel context.CancelFunc
+ events <-chan tea.Msg
+ compactEvents <-chan tea.Msg
+ detectedToolCalls []chatEntry
+ scroll int
+ toolOutputMode bool
+ toolOutputOpen bool
+ thinkingDetailsOpen bool
+ flowPrintedLines int
+ thinking bool
+ thinkingPhaseStart int
+ thinkingTokens int
+ compactingTokens int
+ contextTokens int
+ contextEstimate bool
+ modelPicker *chatModelPicker
+ modelPickerModels []ModelOption
+ thinkPicker *chatThinkPicker
+ promptDebug *chatPromptDebug
+ approvalPrompt *chatApprovalPrompt
+ approvalController *chatApprovalController
+ approvalState *coreagent.ApprovalState
+ cloudAuthPrompt *cloudAuthPrompt
+ pendingModel string
+ defaultAllowAll bool
+ permissionNotice string
+ selection chatSelection
systemPromptDisabled bool
@@ -557,7 +559,7 @@ func (m chatModel) updateKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
return m.updatePromptDebug(msg)
}
if msg.Type == tea.KeyCtrlO {
- m.toggleInlineToolOutput()
+ m.toggleInlineTranscriptDetails()
m.disarmQuit()
m.disarmEsc()
return m.withFlowTranscriptRepaint(nil)
@@ -683,10 +685,12 @@ func (m chatModel) updateKey(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
return m, nil
}
-func (m *chatModel) toggleInlineToolOutput() {
+func (m *chatModel) toggleInlineTranscriptDetails() {
m.toolOutputMode = true
m.toolOutputOpen = !m.toolOutputOpen
m.applyToolOutputMode()
+ m.thinkingDetailsOpen = !m.thinkingDetailsOpen
+ m.applyThinkingDetails()
m.selection = chatSelection{}
m.scroll = 0
}
@@ -968,6 +972,10 @@ func (m chatModel) flowTranscriptHoldEntryIndex() int {
if isToolActiveStatus(entry.status) {
return index
}
+ case "thinking":
+ if entry.status == "running" {
+ return index
+ }
}
return -1
}
diff --git a/cmd/tui/chat/events.go b/cmd/tui/chat/events.go
index aa4df410b..f498868e2 100644
--- a/cmd/tui/chat/events.go
+++ b/cmd/tui/chat/events.go
@@ -75,15 +75,18 @@ func (m *chatModel) applyAgentEvent(event coreagent.Event) {
case coreagent.EventThinkingDelta:
m.awaitingModel = false
if event.Thinking != "" {
- m.thinking = true
if event.Tokens > 0 {
m.thinkingTokens = max(m.thinkingTokens, event.Tokens)
} else {
m.thinkingTokens += approximateTokenCount(event.Thinking)
}
idx := m.ensureLiveAssistantMessage()
+ if !m.thinking {
+ m.thinkingPhaseStart = len(m.liveMessages[idx].Thinking)
+ }
+ m.thinking = true
m.liveMessages[idx].Thinking += event.Thinking
- m.syncThinkingEntry()
+ m.syncThinkingEntry(m.liveMessages[idx].Thinking[m.thinkingPhaseStart:])
contextChanged = true
}
case coreagent.EventMessageDelta:
diff --git a/cmd/tui/chat/events_test.go b/cmd/tui/chat/events_test.go
index d4975bc46..4c57de910 100644
--- a/cmd/tui/chat/events_test.go
+++ b/cmd/tui/chat/events_test.go
@@ -22,6 +22,84 @@ func TestApplyAgentEventStreamsAssistantContent(t *testing.T) {
}
}
+func TestApplyAgentEventStreamsThinkingThenCollapsesOnAssistantOrTool(t *testing.T) {
+ m := chatModel{running: true}
+
+ m.applyAgentEvent(coreagent.Event{Type: coreagent.EventThinkingDelta, Thinking: "first "})
+ m.applyAgentEvent(coreagent.Event{Type: coreagent.EventThinkingDelta, Thinking: "second", Tokens: 7})
+ if len(m.entries) != 1 || m.entries[0].role != "thinking" || !m.entries[0].expanded || m.entries[0].content != "first second" {
+ t.Fatalf("live thinking entry = %#v", m.entries)
+ }
+ if got := m.liveMessages[0].Thinking; got != "first second" {
+ t.Fatalf("live message thinking = %q, want full streamed value", got)
+ }
+ if view := stripANSI(m.renderTranscript(100)); !strings.Contains(view, "Thinking ↓ 7 tokens") || !strings.Contains(view, "first second") {
+ t.Fatalf("live thinking trace missing from transcript:\n%s", view)
+ }
+
+ m.applyAgentEvent(coreagent.Event{Type: coreagent.EventMessageDelta, Content: "answer"})
+ if m.entries[0].status != "done" || m.entries[0].expanded {
+ t.Fatalf("assistant content should collapse thinking: %#v", m.entries[0])
+ }
+ collapsed := stripANSI(m.renderTranscript(100))
+ if !strings.Contains(collapsed, "Thought") || strings.Contains(collapsed, "7 tokens") || strings.Contains(collapsed, "first second") {
+ t.Fatalf("collapsed thinking should remain as a thought row without trace content:\n%s", collapsed)
+ }
+ if got := m.liveMessages[0].Thinking; got != "first second" {
+ t.Fatalf("collapsing display must not change request history: %q", got)
+ }
+
+ m.applyAgentEvent(coreagent.Event{Type: coreagent.EventThinkingDelta, Thinking: "tool plan"})
+ if entry := m.entries[len(m.entries)-1]; entry.role != "thinking" || entry.content != "tool plan" {
+ t.Fatalf("second thinking phase should contain only its own deltas: %#v", entry)
+ }
+ if got := m.liveMessages[0].Thinking; got != "first secondtool plan" {
+ t.Fatalf("message history should retain both thinking phases exactly: %q", got)
+ }
+ m.applyAgentEvent(coreagent.Event{Type: coreagent.EventToolStarted, ToolCallID: "call-1", ToolName: "bash"})
+ if entry := m.entries[len(m.entries)-2]; entry.role != "thinking" || entry.status != "done" || entry.expanded {
+ t.Fatalf("tool transition should collapse thinking: %#v", entry)
+ }
+}
+
+func TestApplyAgentEventDoesNotCreateThinkingEntryWithoutThinking(t *testing.T) {
+ m := chatModel{running: true}
+
+ m.applyAgentEvent(coreagent.Event{Type: coreagent.EventThinkingDelta, Tokens: 12})
+ m.applyAgentEvent(coreagent.Event{Type: coreagent.EventMessageDelta, Content: "answer"})
+ if len(m.entries) != 1 || m.entries[0].role != "assistant" {
+ t.Fatalf("empty thinking event should not create a trace: %#v", m.entries)
+ }
+ if len(m.liveMessages) != 1 || m.liveMessages[0].Thinking != "" {
+ t.Fatalf("empty thinking event should not alter message history: %#v", m.liveMessages)
+ }
+}
+
+func TestApplyAgentEventPreservesCollapsedThoughtsAcrossToolGrouping(t *testing.T) {
+ m := chatModel{running: true}
+
+ m.applyAgentEvent(coreagent.Event{Type: coreagent.EventThinkingDelta, Thinking: "first plan", Tokens: 1})
+ m.applyAgentEvent(coreagent.Event{Type: coreagent.EventToolStarted, ToolCallID: "call-1", ToolName: "bash"})
+ m.applyAgentEvent(coreagent.Event{Type: coreagent.EventToolFinished, ToolCallID: "call-1", ToolName: "bash", Content: "one"})
+ m.applyAgentEvent(coreagent.Event{Type: coreagent.EventThinkingDelta, Thinking: "second plan", Tokens: 1})
+ m.applyAgentEvent(coreagent.Event{Type: coreagent.EventToolStarted, ToolCallID: "call-2", ToolName: "bash"})
+ m.applyAgentEvent(coreagent.Event{Type: coreagent.EventToolFinished, ToolCallID: "call-2", ToolName: "bash", Content: "two"})
+ m.applyAgentEvent(coreagent.Event{Type: coreagent.EventToolStarted, ToolCallID: "call-3", ToolName: "bash"})
+
+ if len(m.entries) != 5 {
+ t.Fatalf("entries = %#v, want two thought rows and three tool rows", m.entries)
+ }
+ for _, index := range []int{0, 2} {
+ entry := m.entries[index]
+ if entry.role != "thinking" || entry.status != "done" || entry.expanded {
+ t.Fatalf("collapsed thought %d = %#v", index, entry)
+ }
+ }
+ if transcript := stripANSI(m.renderTranscript(100)); strings.Count(transcript, "Thought") != 2 || strings.Contains(transcript, "1 token") {
+ t.Fatalf("transcript should retain both thought rows:\n%s", transcript)
+ }
+}
+
func TestApplyAgentEventTracksToolLifecycle(t *testing.T) {
m := chatModel{running: true}
args := map[string]any{"command": "pwd"}
diff --git a/cmd/tui/chat/input.go b/cmd/tui/chat/input.go
index 8fda04f89..564145002 100644
--- a/cmd/tui/chat/input.go
+++ b/cmd/tui/chat/input.go
@@ -1611,6 +1611,7 @@ func (m chatModel) helpSummary() string {
"",
"- `shift+enter`: insert a newline",
"- `shift+tab`: toggle permission mode",
+ "- `ctrl+o`: toggle transcript details",
"- `↑/↓`: previous or next prompt",
"- `ctrl+a/e`: move to line start or end",
)
diff --git a/cmd/tui/chat/input_test.go b/cmd/tui/chat/input_test.go
index dedc2a890..70e9d6fab 100644
--- a/cmd/tui/chat/input_test.go
+++ b/cmd/tui/chat/input_test.go
@@ -39,6 +39,7 @@ func TestChatHelpCommandShowsV1Commands(t *testing.T) {
"**Shortcuts**",
"- `shift+enter`: insert a newline",
"- `shift+tab`: toggle permission mode",
+ "- `ctrl+o`: toggle transcript details",
} {
if !strings.Contains(fm.entries[0].content, want) {
t.Fatalf("help output missing %q:\n%s", want, fm.entries[0].content)
diff --git a/cmd/tui/chat/render.go b/cmd/tui/chat/render.go
index 6cb21bced..4ea56ecfd 100644
--- a/cmd/tui/chat/render.go
+++ b/cmd/tui/chat/render.go
@@ -4,15 +4,16 @@ import (
"context"
"encoding/json"
"fmt"
- "regexp"
"slices"
"sort"
"strconv"
"strings"
"time"
+ "unicode"
"unicode/utf8"
"github.com/charmbracelet/lipgloss"
+ "github.com/charmbracelet/x/ansi"
"github.com/mattn/go-runewidth"
coreagent "github.com/ollama/ollama/agent"
@@ -33,6 +34,7 @@ type chatEntry struct {
finishedAt time.Time
tools []chatEntry
metrics *api.Metrics
+ tokenCount int
version int
renderKey chatEntryRenderKey
@@ -43,6 +45,7 @@ const (
chatMessageIndent = " "
chatUserMessagePrefix = ""
maxCtrlOToolOutputRunes = 400
+ maxLiveThinkingRunes = 4096
defaultViewWidth = 80
defaultViewHeight = 24
@@ -384,10 +387,17 @@ func (m *chatModel) scrollBy(lines int) {
m.scroll = clamp(m.scroll+lines, 0, m.maxScroll())
}
-var chatANSISequencePattern = regexp.MustCompile(`\x1b\[[0-9;:]*[A-Za-z]`)
-
func stripChatANSI(s string) string {
- return chatANSISequencePattern.ReplaceAllString(s, "")
+ s = ansi.Strip(s)
+ return strings.Map(func(r rune) rune {
+ if r == '\n' || r == '\t' {
+ return r
+ }
+ if unicode.IsControl(r) {
+ return -1
+ }
+ return r
+ }, s)
}
func (m chatModel) normalizedSelectionRange() (chatSelectionPoint, chatSelectionPoint, bool) {
@@ -669,20 +679,71 @@ func compactionSummaryStatusLine(entry chatEntry) string {
}
func renderThinkingLines(entry chatEntry, width int) []string {
- if !entry.expanded || strings.TrimSpace(entry.content) == "" {
- return nil
- }
lines := wrapChatText(thinkingStatusLine(entry), width)
+ if !entry.expanded || entry.content == "" {
+ return lines
+ }
lines = append(lines, "")
- lines = append(lines, indentLines(splitRenderedBody(renderMarkdownForView(entry.content, width-2)), " ")...)
+ if entry.status == "running" {
+ body := styleLines(renderLiveThinkingLines(entry.content, width), chatToolOutputStyle)
+ lines = append(lines, body...)
+ return lines
+ }
+ body := styleLines(splitRenderedBody(renderMarkdownForView(stripChatANSI(entry.content), width)), chatToolOutputStyle)
+ lines = append(lines, body...)
+ return lines
+}
+
+// renderLiveThinkingLines keeps each streaming redraw bounded. Completed
+// traces use the normal Markdown renderer when explicitly reopened, but a
+// running trace is rendered as plain text so an ever-growing document is not
+// reparsed for every delta.
+func renderLiveThinkingLines(content string, width int) []string {
+ content, omitted := liveThinkingTail(content, maxLiveThinkingRunes)
+ content = stripChatANSI(content)
+ lines := wrapChatText(content, width)
+ if omitted {
+ lines = append([]string{"… earlier thinking omitted while streaming"}, lines...)
+ }
return lines
}
+func liveThinkingTail(content string, limit int) (string, bool) {
+ if limit <= 0 {
+ return content, false
+ }
+ start := len(content)
+ for range limit {
+ if start == 0 {
+ return content, false
+ }
+ _, size := utf8.DecodeLastRuneInString(content[:start])
+ start -= size
+ }
+ tail := content[start:]
+ if newline := strings.IndexByte(tail, '\n'); newline >= 0 {
+ tail = tail[newline+1:]
+ }
+ return tail, true
+}
+
func thinkingStatusLine(entry chatEntry) string {
+ if entry.status != "running" {
+ return thoughtLabel(entry.tokenCount, entry.expanded)
+ }
+
+ label := "Thinking"
if strings.TrimSpace(entry.label) != "" {
- return entry.label
+ label = entry.label
}
- return "Thinking"
+ return label
+}
+
+func thoughtLabel(tokens int, expanded bool) string {
+ if !expanded || tokens <= 0 {
+ return "Thought"
+ }
+ return "Thought (" + formatTokenCount(tokens) + ")"
}
func (m chatModel) thinkingLabel() string {
@@ -696,32 +757,35 @@ func thinkingActivityLabel(tokens int) string {
return "Thinking"
}
-func (m *chatModel) syncThinkingEntry() {
- if strings.TrimSpace(m.latestLiveThinking()) == "" {
- return
- }
+func (m *chatModel) syncThinkingEntry(content string) {
idx := -1
if len(m.entries) > 0 && m.entries[len(m.entries)-1].role == "thinking" && m.entries[len(m.entries)-1].status == "running" {
idx = len(m.entries) - 1
}
if idx < 0 {
+ if strings.TrimSpace(content) == "" {
+ return
+ }
m.entries = append(m.entries, newChatEntry(chatEntry{role: "thinking", status: "running"}))
idx = len(m.entries) - 1
}
- m.entries[idx].content = m.latestLiveThinking()
+ m.entries[idx].content = content
m.entries[idx].label = m.thinkingLabel()
m.entries[idx].status = "running"
- m.entries[idx].expanded = false
+ m.entries[idx].tokenCount = m.thinkingTokens
+ m.entries[idx].expanded = true
m.markEntryDirty(idx)
}
-func (m chatModel) latestLiveThinking() string {
- for i := len(m.liveMessages) - 1; i >= 0; i-- {
- if m.liveMessages[i].Role == "assistant" && strings.TrimSpace(m.liveMessages[i].Thinking) != "" {
- return m.liveMessages[i].Thinking
+func (m *chatModel) applyThinkingDetails() {
+ for i := range m.entries {
+ entry := &m.entries[i]
+ if entry.role != "thinking" || entry.status == "running" || strings.TrimSpace(entry.content) == "" || entry.expanded == m.thinkingDetailsOpen {
+ continue
}
+ entry.expanded = m.thinkingDetailsOpen
+ m.markEntryDirty(i)
}
- return ""
}
func (m *chatModel) finishThinkingEntry() {
@@ -734,6 +798,8 @@ func (m *chatModel) finishThinkingEntry() {
}
m.entries[idx].status = "done"
m.entries[idx].label = m.thinkingLabel()
+ m.entries[idx].tokenCount = m.thinkingTokens
+ m.entries[idx].expanded = m.thinkingDetailsOpen
m.markEntryDirty(idx)
}
@@ -1452,6 +1518,12 @@ func (m chatModel) activityLine() string {
if !m.running && !m.compacting && m.preloadingModel == "" && m.approvalPrompt == nil {
return ""
}
+ if m.thinking && len(m.entries) > 0 {
+ entry := m.entries[len(m.entries)-1]
+ if entry.role == "thinking" && entry.status == "running" {
+ return ""
+ }
+ }
label := m.activityLabel()
if label == "" {
if m.awaitingToolStart() {
@@ -1962,8 +2034,6 @@ func isInvisibleToolGroupingBoundary(entry chatEntry) bool {
strings.TrimSpace(entry.label) == "" &&
strings.TrimSpace(entry.detail) == "" &&
entry.metrics == nil
- case "thinking":
- return !entry.expanded
default:
return false
}
diff --git a/cmd/tui/chat/render_test.go b/cmd/tui/chat/render_test.go
index d6a103737..c2d911412 100644
--- a/cmd/tui/chat/render_test.go
+++ b/cmd/tui/chat/render_test.go
@@ -8,6 +8,7 @@ import (
"strings"
"testing"
"time"
+ "unicode/utf8"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
@@ -548,6 +549,24 @@ func TestChatViewKeepsInputBoxWhileRunning(t *testing.T) {
}
}
+func TestChatViewShowsActiveThinkingStatusOnce(t *testing.T) {
+ m := chatModel{
+ running: true,
+ thinking: true,
+ thinkingTokens: 42,
+ width: 60,
+ height: 16,
+ entries: []chatEntry{
+ {role: "thinking", label: "Thinking ↓ 42 tokens", status: "running", content: "streamed trace", expanded: true},
+ },
+ }
+
+ view := stripANSI(m.View())
+ if count := strings.Count(view, "Thinking ↓ 42 tokens"); count != 1 {
+ t.Fatalf("active thinking status appears %d times, want once:\n%s", count, view)
+ }
+}
+
func TestChatToolFinishedUpdatesLiveWorkingDirOnly(t *testing.T) {
root := t.TempDir()
subdir := filepath.Join(root, "sub")
@@ -1461,7 +1480,7 @@ func TestChatCompletedToolsGroupAcrossEmptyAssistantEntries(t *testing.T) {
}
}
-func TestChatCompletedToolsGroupAcrossCollapsedThinking(t *testing.T) {
+func TestChatCompletedToolsPreserveCollapsedThoughts(t *testing.T) {
entries := groupCompletedToolEntries([]chatEntry{
newChatEntry(chatEntry{role: "tool", detail: "bash", label: `Bash("pwd")`, status: "done", content: "one"}),
newChatEntry(chatEntry{role: "thinking", label: "Thinking", content: "choose next tool", status: "done"}),
@@ -1470,13 +1489,13 @@ func TestChatCompletedToolsGroupAcrossCollapsedThinking(t *testing.T) {
newChatEntry(chatEntry{role: "tool", detail: "read", label: `Read("AGENTS.md")`, status: "done", content: "instructions"}),
})
- if len(entries) != 1 {
- t.Fatalf("entries = %d, want one grouped tool entry: %#v", len(entries), entries)
+ if len(entries) != 3 {
+ t.Fatalf("entries = %d, want tool, thought, and grouped tools: %#v", len(entries), entries)
}
- if entries[0].role != "tool_group" || len(entries[0].tools) != 3 {
- t.Fatalf("tools should group across collapsed thinking: %#v", entries[0])
+ if entries[0].role != "tool" || entries[1].role != "thinking" || entries[2].role != "tool_group" || len(entries[2].tools) != 2 {
+ t.Fatalf("collapsed thought should separate tool groups: %#v", entries)
}
- if line := stripANSI(toolGroupStatusLine(entries[0])); line != "Ran 2 commands and read a file" {
+ if line := stripANSI(toolGroupStatusLine(entries[2])); line != "Ran 1 command and read a file" {
t.Fatalf("grouped tool line = %q", line)
}
}
@@ -1543,29 +1562,161 @@ func TestChatCtrlOTogglesInlineOutput(t *testing.T) {
}
}
-func TestChatCtrlODoesNotExpandThinking(t *testing.T) {
+func TestChatCtrlOTogglesCompletedThinkingDetails(t *testing.T) {
m := chatModel{
entries: []chatEntry{
- newChatEntry(chatEntry{role: "thinking", label: "Thinking", status: "done", content: "private reasoning"}),
+ newChatEntry(chatEntry{role: "thinking", label: "Thinking", status: "done", content: "private reasoning", tokenCount: 12}),
},
}
+ if view := stripANSI(m.renderTranscript(100)); !strings.Contains(view, "Thought") || strings.Contains(view, "12 tokens") {
+ t.Fatalf("collapsed thinking should hide its token count:\n%s", view)
+ }
+
updated, _ := m.Update(tea.KeyMsg{Type: tea.KeyCtrlO})
m = updated.(chatModel)
- if m.entries[0].expanded {
- t.Fatalf("ctrl+o should not expand thinking entries: %#v", m.entries[0])
+ if !m.thinkingDetailsOpen || !m.entries[0].expanded {
+ t.Fatalf("ctrl+o should expand completed thinking entries: %#v", m.entries[0])
}
- if view := stripANSI(m.renderTranscript(100)); strings.Contains(view, "private reasoning") {
- t.Fatalf("ctrl+o should not render thinking content:\n%s", view)
+ if view := stripANSI(m.renderTranscript(100)); !strings.Contains(view, "Thought (12 tokens)") || !strings.Contains(view, "private reasoning") {
+ t.Fatalf("ctrl+o should render completed thinking content:\n%s", view)
}
m.liveMessages = []api.Message{{Role: "assistant", Thinking: "live private reasoning"}}
- m.syncThinkingEntry()
- if m.entries[1].expanded {
- t.Fatalf("live thinking should not inherit ctrl+o expansion: %#v", m.entries[1])
+ m.syncThinkingEntry("live private reasoning")
+ if !m.entries[1].expanded {
+ t.Fatalf("live thinking should always be expanded: %#v", m.entries[1])
+ }
+ if view := stripANSI(m.renderTranscript(100)); !strings.Contains(view, "live private reasoning") {
+ t.Fatalf("live thinking should render while streaming:\n%s", view)
+ }
+ m.thinkingTokens = 9
+ m.finishThinkingEntry()
+ if m.entries[1].status != "done" || !m.entries[1].expanded {
+ t.Fatalf("completed thinking should honor the open details mode: %#v", m.entries[1])
+ }
+
+ updated, _ = m.Update(tea.KeyMsg{Type: tea.KeyCtrlO})
+ m = updated.(chatModel)
+ if m.thinkingDetailsOpen || m.entries[0].expanded || m.entries[1].expanded {
+ t.Fatalf("ctrl+o should collapse all completed thinking details: %#v", m.entries)
+ }
+}
+
+func TestChatThinkingBodyUsesSecondaryGrey(t *testing.T) {
+ for _, tt := range []struct {
+ entry chatEntry
+ header string
+ }{
+ {entry: chatEntry{role: "thinking", status: "running", content: "Let me inspect the files.", expanded: true}, header: "Thinking"},
+ {entry: chatEntry{role: "thinking", status: "done", content: "Let me inspect the files.", tokenCount: 15, expanded: true}, header: "Thought (15 tokens)"},
+ } {
+ lines := renderThinkingLines(tt.entry, 80)
+ if len(lines) < 3 {
+ t.Fatalf("thinking entry did not render its body: %#v", lines)
+ }
+ if lines[0] != tt.header {
+ t.Fatalf("thinking header = %q, want unmuted %q", lines[0], tt.header)
+ }
+ if got, want := lines[2], chatToolOutputStyle.Render("Let me inspect the files."); got != want {
+ t.Fatalf("thinking body = %q, want secondary grey %q", got, want)
+ }
+ }
+}
+
+func TestChatThinkingBodyAlignsWithStatusText(t *testing.T) {
+ m := chatModel{entries: []chatEntry{
+ {role: "thinking", status: "done", content: "Let me inspect the files.", tokenCount: 15, expanded: true},
+ }}
+
+ lines := strings.Split(stripANSI(m.renderTranscript(80)), "\n")
+ if len(lines) < 3 {
+ t.Fatalf("thinking entry did not render its body: %#v", lines)
+ }
+ if got, want := lines[0], "• Thought (15 tokens)"; got != want {
+ t.Fatalf("thinking header = %q, want %q", got, want)
+ }
+ if got, want := lines[2], " Let me inspect the files."; got != want {
+ t.Fatalf("thinking body = %q, want aligned with status text %q", got, want)
+ }
+}
+
+func TestChatLiveThinkingUsesBoundedSanitizedTail(t *testing.T) {
+ longThinking := "first-visible-marker\n" + strings.Repeat("x", maxLiveThinkingRunes+100) + "\nlast-visible-marker\x1b[2J"
+ m := chatModel{entries: []chatEntry{{role: "thinking", label: "Thinking ↓ 10 tokens", status: "running", content: longThinking, expanded: true}}}
+
+ view := stripANSI(m.renderTranscript(80))
+ if strings.Contains(view, "first-visible-marker") || !strings.Contains(view, "earlier thinking omitted while streaming") || !strings.Contains(view, "last-visible-marker") {
+ t.Fatalf("live thinking should render a bounded tail:\n%s", view)
+ }
+ if strings.Contains(view, "\x1b") || strings.Contains(view, "[2J") {
+ t.Fatalf("live thinking should remove terminal control sequences: %q", view)
+ }
+}
+
+func TestChatThinkingSanitizesTerminalControlsLiveAndReopened(t *testing.T) {
+ content := "safe\x1b]52;c;clipboard-payload\a visible\x1bPqdevice-control\x1b\\ done\b!\u009b31m red\a"
+ tests := []struct {
+ name string
+ entry chatEntry
+ }{
+ {name: "live", entry: chatEntry{role: "thinking", status: "running", content: content, expanded: true}},
+ {name: "reopened", entry: chatEntry{role: "thinking", status: "done", content: content, expanded: true}},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ view := chatModel{entries: []chatEntry{tt.entry}}.renderTranscript(80)
+ plain := stripANSI(view)
+ if !strings.Contains(plain, "safe") || !strings.Contains(plain, "visible") || !strings.Contains(plain, "done!") || !strings.Contains(plain, "red") {
+ t.Fatalf("sanitized thinking lost visible text: %q", plain)
+ }
+ for _, unsafe := range []string{"clipboard-payload", "device-control", "\x1b]", "\x1bP", "\a", "\b", "\u009b"} {
+ if strings.Contains(view, unsafe) {
+ t.Fatalf("sanitized thinking contains unsafe value %q: %q", unsafe, view)
+ }
+ }
+ })
+ }
+}
+
+func TestLiveThinkingTailPreservesUTF8Boundary(t *testing.T) {
+ content := strings.Repeat("🙂", maxLiveThinkingRunes+100)
+ tail, omitted := liveThinkingTail(content, maxLiveThinkingRunes)
+ if !omitted {
+ t.Fatal("long thinking trace should report an omitted prefix")
+ }
+ if !utf8.ValidString(tail) || utf8.RuneCountInString(tail) != maxLiveThinkingRunes {
+ t.Fatalf("tail should contain %d complete runes, got %d", maxLiveThinkingRunes, utf8.RuneCountInString(tail))
+ }
+}
+
+func BenchmarkRenderLiveThinkingLines(b *testing.B) {
+ content := strings.Repeat("old thinking that is outside the visible tail\n", 100_000) + "visible tail"
+ entry := chatEntry{role: "thinking", status: "running", content: content, expanded: true}
+ b.ReportAllocs()
+ for b.Loop() {
+ renderThinkingLines(entry, 80)
+ }
+}
+
+func TestChatThinkingDetailsRespectNarrowAndResizedViews(t *testing.T) {
+ m := chatModel{
+ width: 80,
+ height: 10,
+ entries: []chatEntry{
+ {role: "thinking", label: "Thinking ↓ 42 tokens", status: "running", content: "first delta\nsecond delta", expanded: true},
+ },
+ }
+
+ updated, _ := m.Update(tea.WindowSizeMsg{Width: 24, Height: 8})
+ m = updated.(chatModel)
+ transcript := stripANSI(m.renderTranscript(24))
+ if !strings.Contains(transcript, "Thinking") || !strings.Contains(transcript, "second delta") {
+ t.Fatalf("narrow transcript should retain the live thinking tail:\n%s", transcript)
}
- if view := stripANSI(m.renderTranscript(100)); strings.Contains(view, "live private reasoning") {
- t.Fatalf("ctrl+o should not render live thinking content:\n%s", view)
+ if len(m.transcriptLines(24)) == 0 {
+ t.Fatal("resized transcript should remain selectable and scrollable")
}
}
diff --git a/go.mod b/go.mod
index cd57291b7..c1525d23c 100644
--- a/go.mod
+++ b/go.mod
@@ -23,6 +23,7 @@ require (
github.com/agnivade/levenshtein v1.1.1
github.com/charmbracelet/bubbletea v1.3.10
github.com/charmbracelet/lipgloss v1.1.0
+ github.com/charmbracelet/x/ansi v0.10.1
github.com/d4l3k/go-bfloat16 v0.0.0-20211005043715-690c3bdd05f1
github.com/dlclark/regexp2 v1.11.5
github.com/emirpasic/gods/v2 v2.0.0-alpha
@@ -48,7 +49,6 @@ require (
github.com/buger/jsonparser v1.1.1 // indirect
github.com/bytedance/sonic/loader v0.1.1 // indirect
github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc // indirect
- github.com/charmbracelet/x/ansi v0.10.1 // indirect
github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd // indirect
github.com/charmbracelet/x/term v0.2.1 // indirect
github.com/chewxy/hm v1.0.0 // indirect