v0.2.44 4bec50a

view.go RawHistoryFolder

1package tui
2
3import (
4	"encoding/json"
5	"fmt"
6	"os"
7	"regexp"
8	"strconv"
9	"strings"
10	"unicode/utf8"
11
12	"github.com/mattn/go-runewidth"
13	"github.com/patriceckhart/zot/packages/provider"
14)
15
16// expandTabs replaces tab characters with 4 spaces so code from
17// tab-indented languages (Go, Makefiles, etc.) renders at a
18// consistent width instead of the terminal's default 8-column tabs.
19func expandTabs(s string) string {
20	return strings.ReplaceAll(s, "\t", "    ")
21}
22
23// sanitizeUserBubbleLine prepares a single user-bubble row for safe
24// rendering. Pasted content from another terminal can contain
25// embedded ANSI escape sequences, control bytes, and tabs that
26// either reset the bubble's background colour or move the cursor in
27// ways that break the bubble's painted column.
28func sanitizeUserBubbleLine(s string) string {
29	if s == "" {
30		return s
31	}
32	s = expandTabs(s)
33	var b strings.Builder
34	b.Grow(len(s))
35	for i := 0; i < len(s); {
36		c := s[i]
37		if c == 0x1b { // ESC: drop CSI/OSC/DCS and simple escapes.
38			i = skipEscapeSequence(s, i)
39			continue
40		}
41		if c == '\r' || c == '\b' || c == 0x07 {
42			i++
43			continue
44		}
45		if c < 0x20 || c == 0x7f {
46			i++
47			continue
48		}
49		b.WriteByte(c)
50		i++
51	}
52	return b.String()
53}
54
55// pathFromToolArgs returns the "path" argument from a tool_call's
56// JSON arguments, or "" if the args aren't a JSON object or don't
57// include one. Used to pick a syntax language for rendering the
58// corresponding tool_result.
59func pathFromToolArgs(raw json.RawMessage) string {
60	if len(raw) == 0 {
61		return ""
62	}
63	var m map[string]any
64	if err := json.Unmarshal(raw, &m); err != nil {
65		return ""
66	}
67	for _, k := range []string{"path", "file_path"} {
68		if s, ok := m[k].(string); ok && s != "" {
69			return s
70		}
71	}
72	return ""
73}
74
75// offsetFromToolArgs returns the read tool's 1-indexed `offset`
76// arg (the first line of the slice the tool was asked to return),
77// or 0 when the call didn't specify one. Used by the tui to draw
78// the line-number gutter aligned to the right starting row, even
79// though the tool's text content itself no longer carries line
80// numbers.
81func offsetFromToolArgs(raw json.RawMessage) int {
82	if len(raw) == 0 {
83		return 0
84	}
85	var m map[string]any
86	if err := json.Unmarshal(raw, &m); err != nil {
87		return 0
88	}
89	switch v := m["offset"].(type) {
90	case float64:
91		return int(v)
92	case int:
93		return v
94	}
95	return 0
96}
97
98// osUserHomeDir is aliased so the test file can swap it.
99var osUserHomeDir = os.UserHomeDir
100
101// View turns a transcript + live state into a slice of styled lines,
102// already wrapped to width.
103type View struct {
104	Theme      Theme
105	ImageProto ImageProtocol // how to render inline images in this terminal
106	Messages   []provider.Message
107	// toolPaths maps tool_use_id to the "path" argument of the call, if
108	// any, so tool_result rendering can pick the right syntax language.
109	// Rebuilt on each Build().
110	toolPaths map[string]string
111	// toolStartLines maps tool_use_id to the 1-indexed first line
112	// number of a `read` result, pulled from the call's offset arg.
113	// Used by renderNumberedFile to draw a line-number gutter over
114	// raw (unnumbered) file content the model receives. Rebuilt on
115	// each Build().
116	toolStartLines map[string]int
117	// toolCallLabels maps tool_use_id to the box label (tool name +
118	// short args) for the call, so a tool_result message can render
119	// the box top edge without having to look back at the assistant
120	// message that originated the call. Rebuilt on each Build().
121	toolCallLabels  map[string]string
122	Streaming       string // current assistant text delta
123	StreamingActive bool
124	ToolCalls       []ToolCallView // tool calls in flight or completed
125	StatusLine      string
126	Err             string
127
128	// liveBodyHigh tracks the tallest live-preview body height seen
129	// per tool-call id, so a streaming edit/write/bash box never
130	// shrinks mid-stream. Keyed by ToolCallView.ID. Entries are only
131	// consulted while a call has no Result; interactive mode prunes
132	// the map when a turn ends.
133	liveBodyHigh map[string]int
134
135	// ExpandAll forces every long tool result to render in full.
136	// Toggled from the tui by ctrl+o. When false, results longer than
137	// ToolCollapseLines collapse to ToolCollapsePreview lines plus a
138	// "... (N more lines, M total, ctrl+o to expand)" footer.
139	ExpandAll bool
140
141	// renderCache holds the per-message rendered line slices so Build
142	// doesn't re-markdown every message on every frame. Keyed by a
143	// struct of (content hash, width, expandAll) — any of those
144	// changing invalidates the entry. Messages are append-only after
145	// they finalise so keeping the cache across turns is safe.
146	//
147	// Streaming/in-flight work (v.Streaming, v.ToolCalls) is never
148	// cached because it changes every delta.
149	renderCache map[msgCacheKey][]string
150
151	// TailLimit caps how many messages from the END of Messages are
152	// rendered. Messages older than the limit emit a zero-row slice
153	// so first paint after a session resume doesn't pay the markdown
154	// / chroma cost for the entire transcript at once. 0 means no
155	// limit (render everything, the historical behaviour). Interactive
156	// raises the cap when the user scrolls past the top of the
157	// already-rendered tail.
158	TailLimit int
159}
160
161// msgCacheKey identifies a cached message render. hash is a 64-bit
162// FNV-1a of the message's content, which is cheap to compute and
163// unambiguous enough for the cache (collisions produce a stale frame,
164// not wrong data, and we recompute on invalidation anyway).
165type msgCacheKey struct {
166	hash      uint64
167	width     int
168	expandAll bool
169	// turnOpen is true when the previous rendered message belongs to
170	// the same agent turn (assistant tool_use, or tool result). The
171	// header ("▍ zot") is suppressed in that case so a single turn
172	// — even one that spans many assistant/tool message round-trips
173	// in the underlying API — renders under one header instead of a
174	// new one per assistant message.
175	turnOpen bool
176}
177
178// InvalidateRenderCache drops all cached message renders. The tui
179// calls this when the transcript is replaced wholesale (/compact,
180// /clear, session swap) since messages can be replaced in place and
181// a content-hash miss alone doesn't reclaim the old entries.
182func (v *View) InvalidateRenderCache() {
183	v.renderCache = nil
184}
185
186// ToolCollapsePreview is the number of lines shown before a long tool
187// result is replaced with a "... ctrl+o to expand" footer. Tool
188// results shorter than ToolCollapseLines always render in full.
189const (
190	ToolCollapsePreview = 10
191	ToolCollapseLines   = 12
192)
193
194// ToolCallView is a pending tool invocation plus optional result.
195type ToolCallView struct {
196	ID     string
197	Name   string
198	Args   string // rendered argument summary
199	Result string // rendered result preview (truncated)
200	Error  bool
201	Done   bool
202
203	// Streaming is true while the model is still typing the tool
204	// call's JSON arguments. The TUI renders a live preview of any
205	// interesting string fields (for `write`, the `content`; for
206	// `bash`, the `command`) so the user can watch the file being
207	// composed. Set to false as soon as EvToolUseEnd arrives.
208	Streaming bool
209
210	// RawJSONBuf is the accumulator of every EvToolUseArgs delta
211	// the stream has delivered for this tool call. Used by the
212	// partial-JSON extractor to peel off the live string value
213	// of one named field on each render.
214	RawJSONBuf string
215
216	// LivePath is the `path` arg extracted as soon as it parses
217	// out of RawJSONBuf. Shown next to the tool name in the header
218	// so the user can see which file is being written to.
219	LivePath string
220}
221
222// MessageAnchor records where a rendered message starts in the chat
223// line slice. Used by /jump so the dialog can scroll the viewport to
224// the row where a turn's user prompt begins.
225type MessageAnchor struct {
226	MessageIdx int // index into v.Messages
227	Row        int // first row of that message in the Build() output
228}
229
230// Build returns the chat log lines for the given width.
231func (v *View) Build(width int) []string {
232	lines, _ := v.BuildWithAnchors(width)
233	return lines
234}
235
236// BuildLive renders only in-flight assistant/tool/error state. Main-screen
237// scrollback renderers can keep these rows outside the immutable transcript
238// so native scrolling stays stable while a turn streams.
239func (v *View) BuildLive(width int) []string {
240	var out []string
241	if v.StreamingActive && strings.TrimSpace(v.Streaming) != "" {
242		const indent = "  "
243		inner := assistantBodyWidth(width - len(indent))
244		md := RenderMarkdown(v.Streaming, v.Theme, inner)
245		for _, l := range strings.Split(md, "\n") {
246			for _, w := range wrapANSILine(l, inner) {
247				out = append(out, indent+w)
248			}
249		}
250		// out = append(out, "")
251	}
252	finalised := map[string]bool{}
253	for _, m := range v.Messages {
254		for _, c := range m.Content {
255			if b, ok := c.(provider.ToolResultBlock); ok {
256				finalised[b.CallID] = true
257			}
258		}
259	}
260	insertedToolGap := false
261	for _, tc := range v.ToolCalls {
262		if finalised[tc.ID] {
263			continue
264		}
265		if !insertedToolGap && len(out) > 0 {
266			out = append(out, "")
267		}
268		insertedToolGap = true
269		out = append(out, v.renderToolCall(tc, width)...)
270	}
271	if v.Err != "" {
272		out = append(out, v.renderErr(width)...)
273		// out = append(out, "")
274	}
275	return out
276}
277
278// renderErr formats v.Err into one or more colored rows, word-wrapped
279// to width so long provider error messages (e.g. a Bedrock 400 with an
280// embedded JSON body) aren't cut off at the terminal edge. The first
281// row carries the "✖ " marker; continuation rows align under the text
282// with a two-cell indent.
283func (v *View) renderErr(width int) []string {
284	const marker = "✖ "
285	const indent = "  "
286	wrapWidth := width - len([]rune(marker))
287	if wrapWidth < 8 {
288		wrapWidth = 8
289	}
290	wrapped := wrapLine(v.Err, wrapWidth, "")
291	if len(wrapped) == 0 {
292		wrapped = []string{""}
293	}
294	out := make([]string, 0, len(wrapped))
295	for idx, line := range wrapped {
296		prefix := marker
297		if idx > 0 {
298			prefix = indent
299		}
300		out = append(out, v.Theme.FG256(v.Theme.Error, prefix+line))
301	}
302	return out
303}
304
305// BuildWithAnchors is like Build but additionally reports the first
306// row occupied by each message in v.Messages. Callers that need to
307// scroll to a specific turn (the /jump dialog) use the anchor slice
308// to map a message index back to a row offset.
309func (v *View) BuildWithAnchors(width int) ([]string, []MessageAnchor) {
310	v.refreshToolPaths()
311	if v.renderCache == nil {
312		v.renderCache = make(map[msgCacheKey][]string)
313	}
314	if v.liveBodyHigh == nil {
315		v.liveBodyHigh = make(map[string]int)
316	}
317	// Drop high-water entries for calls that are gone or finalised so
318	// the reservation never leaks into a later, shorter tool box.
319	if len(v.liveBodyHigh) > 0 {
320		active := make(map[string]bool, len(v.ToolCalls))
321		for _, tc := range v.ToolCalls {
322			if tc.Result == "" {
323				active[tc.ID] = true
324			}
325		}
326		for id := range v.liveBodyHigh {
327			if !active[id] {
328				delete(v.liveBodyHigh, id)
329			}
330		}
331	}
332
333	// Pre-render every message (hits the cache for unchanged ones) so
334	// we can allocate `out` in a single shot with the exact capacity.
335	// Growing via append on a long transcript copies the backing array
336	// log2(N) times; for a 2000-line scrollback that's enough memcpy
337	// to visibly stutter while typing.
338	rendered := make([][]string, len(v.Messages))
339	total := 0
340	// renderFrom is the first index we actually render. Anything
341	// below it emits a zero-row placeholder; the message still gets
342	// an anchor entry so /jump and scroll math keep working, and a
343	// later Build with a higher TailLimit fills the gap.
344	renderFrom := 0
345	if v.TailLimit > 0 && len(v.Messages) > v.TailLimit {
346		renderFrom = len(v.Messages) - v.TailLimit
347	}
348	for idx, m := range v.Messages {
349		if idx < renderFrom {
350			rendered[idx] = nil
351			continue
352		}
353		// A turn is "open" once the assistant has started responding
354		// to the most recent user prompt. Walk back over consecutive
355		// assistant/tool messages: if any non-user message precedes
356		// this one without a user message in between, we're inside
357		// the same turn and should not draw a new "▍ zot" header.
358		turnOpen := false
359		if m.Role == provider.RoleAssistant {
360			for j := idx - 1; j >= 0; j-- {
361				prev := v.Messages[j]
362				// Skip compaction summary messages — they're
363				// rendered as a muted footer line (or hidden
364				// entirely when collapsed) and don't open a turn.
365				if prev.Meta["compaction"] == "true" {
366					continue
367				}
368				if prev.Role == provider.RoleAssistant || prev.Role == provider.RoleTool {
369					turnOpen = true
370				}
371				break
372			}
373		}
374		lines := v.renderMessageCached(m, width, turnOpen)
375		rendered[idx] = lines
376		total += len(lines) + 1 // +1 for the blank separator row
377	}
378
379	out := make([]string, 0, total+16)
380	anchors := make([]MessageAnchor, 0, len(v.Messages))
381	for idx := range v.Messages {
382		anchors = append(anchors, MessageAnchor{MessageIdx: idx, Row: len(out)})
383		out = append(out, rendered[idx]...)
384		// Skip the inter-message blank for messages that rendered
385		// to nothing. An assistant message whose only content is
386		// ToolCallBlock(s) has no rendered output of its own (each
387		// tool result owns its box now), so emitting a blank for it
388		// would compound with the blank from the next real message
389		// and produce two blank rows between adjacent tool boxes.
390		if len(rendered[idx]) == 0 {
391			continue
392		}
393		out = append(out, "")
394	}
395	// Only render the streaming header/body when there's actual
396	// text to show. An empty streaming block (streamOn=true,
397	// Streaming="") appears when a turn starts with a tool_use
398	// block instead of text — in that case the live tool-call
399	// overlay below is the real content and a naked "zot" bar
400	// above it reads as a stray empty message.
401	if v.StreamingActive && strings.TrimSpace(v.Streaming) != "" {
402		// Stream the partial assistant text through the same markdown
403		// renderer used for finalised messages so code fences, diffs,
404		// lists, and inline styles look the same while streaming and
405		// don't suddenly reflow when the turn ends. No speaker header
406		// is drawn; the indent matches the finalised assistant body in
407		// renderMessage so the column stays consistent across the
408		// stream/finalise transition. Width is capped so ultra-wide
409		// terminals don't produce edge-to-edge code-fence rules or
410		// unreadably long prose lines.
411		const indent = "  "
412		inner := assistantBodyWidth(width - len(indent))
413		md := RenderMarkdown(v.Streaming, v.Theme, inner)
414		for _, l := range strings.Split(md, "\n") {
415			for _, w := range wrapANSILine(l, inner) {
416				out = append(out, indent+w)
417			}
418		}
419		out = append(out, "")
420	}
421	// Live tool-call overlay: keep the in-flight box visible after
422	// the assistant tool_use is appended, then hide it only when the
423	// matching tool_result reaches the transcript. Assistant tool_use
424	// blocks render no rows of their own, so suppressing the overlay
425	// at that point makes the box disappear while the tool is running.
426	finalised := map[string]bool{}
427	for _, m := range v.Messages {
428		for _, c := range m.Content {
429			if b, ok := c.(provider.ToolResultBlock); ok {
430				finalised[b.CallID] = true
431			}
432		}
433	}
434	for _, tc := range v.ToolCalls {
435		if finalised[tc.ID] {
436			continue
437		}
438		out = append(out, v.renderToolCall(tc, width)...)
439		out = append(out, "")
440	}
441	if v.Err != "" {
442		out = append(out, v.renderErr(width)...)
443		out = append(out, "")
444	}
445	return out, anchors
446}
447
448// refreshToolPaths rebuilds the tool_use_id -> path map from the
449// current transcript. Called once per Build() so tool result blocks
450// (which may be cached) can look up their syntax language when they
451// were originally rendered. Walking the transcript here is O(N) but
452// cheap compared to markdown/chroma work it enables.
453func (v *View) refreshToolPaths() {
454	v.toolPaths = map[string]string{}
455	v.toolStartLines = map[string]int{}
456	v.toolCallLabels = map[string]string{}
457	for _, m := range v.Messages {
458		for _, c := range m.Content {
459			if tc, ok := c.(provider.ToolCallBlock); ok {
460				if p := pathFromToolArgs(tc.Arguments); p != "" {
461					v.toolPaths[tc.ID] = p
462				}
463				if off := offsetFromToolArgs(tc.Arguments); off >= 1 {
464					v.toolStartLines[tc.ID] = off
465				}
466				v.toolCallLabels[tc.ID] = tc.Name + " " + ShortArgs(tc.Name, tc.Arguments)
467			}
468		}
469	}
470}
471
472// renderMessageCached returns the rendered line slice for m, using the
473// cache if the same (content hash, width, expandAll) combination has
474// been rendered before. The slice returned is shared — callers must
475// not mutate it; Build() only ever appends to its own `out` so the
476// shared slice is safe.
477func (v *View) renderMessageCached(m provider.Message, width int, turnOpen bool) []string {
478	key := msgCacheKey{
479		hash:      hashMessage(m),
480		width:     width,
481		expandAll: v.ExpandAll,
482		turnOpen:  turnOpen,
483	}
484	if v.renderCache != nil {
485		if lines, ok := v.renderCache[key]; ok {
486			return lines
487		}
488	}
489	lines := v.renderMessage(m, width, turnOpen)
490	if v.renderCache != nil {
491		// Bound the cache: 4x the current message count is enough to
492		// survive /compact churn without leaking memory across a very
493		// long session.
494		max := len(v.Messages) * 4
495		if max < 32 {
496			max = 32
497		}
498		if len(v.renderCache) > max {
499			// Drop half the entries. map iteration order gives us a
500			// pseudo-LRU for free.
501			dropped := 0
502			target := len(v.renderCache) / 2
503			for k := range v.renderCache {
504				if dropped >= target {
505					break
506				}
507				delete(v.renderCache, k)
508				dropped++
509			}
510		}
511		v.renderCache[key] = lines
512	}
513	return lines
514}
515
516// hashMessage returns a 64-bit FNV-1a over the role + content blocks
517// of m. Serialising each block to its salient bytes is enough: two
518// messages with the same role and same content render identically.
519func hashMessage(m provider.Message) uint64 {
520	h := fnv64aInit
521	h = fnv64aWrite(h, []byte(m.Role))
522	h = fnv64aWriteByte(h, 0)
523	for _, c := range m.Content {
524		switch b := c.(type) {
525		case provider.TextBlock:
526			h = fnv64aWriteByte(h, 't')
527			h = fnv64aWrite(h, []byte(b.Text))
528		case provider.ImageBlock:
529			h = fnv64aWriteByte(h, 'i')
530			h = fnv64aWrite(h, []byte(b.MimeType))
531			h = fnv64aWrite(h, b.Data)
532		case provider.ToolCallBlock:
533			h = fnv64aWriteByte(h, 'c')
534			h = fnv64aWrite(h, []byte(b.ID))
535			h = fnv64aWrite(h, []byte(b.Name))
536			h = fnv64aWrite(h, []byte(b.Arguments))
537		case provider.ToolResultBlock:
538			h = fnv64aWriteByte(h, 'r')
539			h = fnv64aWrite(h, []byte(b.CallID))
540			if b.IsError {
541				h = fnv64aWriteByte(h, 'E')
542			}
543			for _, inner := range b.Content {
544				switch ib := inner.(type) {
545				case provider.TextBlock:
546					h = fnv64aWrite(h, []byte(ib.Text))
547				case provider.ImageBlock:
548					h = fnv64aWrite(h, []byte(ib.MimeType))
549					h = fnv64aWrite(h, ib.Data)
550				}
551			}
552		}
553		h = fnv64aWriteByte(h, 0)
554	}
555	return h
556}
557
558// FNV-1a implementation inlined so we don't pay the interface cost of
559// hash.Hash64 on every Build(). The whole point here is speed.
560const (
561	fnv64aInit  uint64 = 0xcbf29ce484222325
562	fnv64aPrime uint64 = 0x100000001b3
563)
564
565// assistantBodyRightPad is the blank gutter kept on the right
566// side of every assistant prose line.
567const assistantBodyRightPad = 2
568
569// assistantBodyWidth returns the usable width for the assistant
570// message body (markdown prose + code fences). Uses the full
571// column width passed in minus assistantBodyRightPad, clamped
572// at 1 so wrap helpers don't divide by zero on absurdly narrow
573// terminals. The right-side padding keeps a small breathing
574// column to the terminal edge that mirrors the left indent.
575func assistantBodyWidth(outer int) int {
576	outer -= assistantBodyRightPad
577	if outer < 1 {
578		return 1
579	}
580	return outer
581}
582
583func fnv64aWriteByte(h uint64, b byte) uint64 {
584	h ^= uint64(b)
585	h *= fnv64aPrime
586	return h
587}
588
589func fnv64aWrite(h uint64, p []byte) uint64 {
590	for _, b := range p {
591		h ^= uint64(b)
592		h *= fnv64aPrime
593	}
594	return h
595}
596
597func (v *View) renderMessage(m provider.Message, width int, turnOpen bool) []string {
598	var lines []string
599
600	// Compaction summary: render as a single muted line at the end
601	// of the chat instead of as a user message.
602	if m.Meta["compaction"] == "true" {
603		if v.ExpandAll {
604			return v.renderCompactionBlock(m, width)
605		}
606		// Collapsed: skip entirely. The status bar shows the info.
607		return nil
608	}
609
610	switch m.Role {
611	case provider.RoleUser:
612		// User rows: no speaker label. Each line is painted with a
613		// faint bubble background tint (UserBubble) so the user's
614		// turns visually segment the chat without needing a header.
615		// One tinted blank row above and below approximates CSS
616		// padding-top / padding-bottom (terminals can't do fractional
617		// rows, so a full row of bubble-coloured whitespace is the
618		// closest analogue and gives the bubble visible breathing
619		// room).
620		// User rows: a 1-cell "▌" accent bar at column 0 painted on
621		// the bubble bg, so the bar's cell shares the panel tint and
622		// there is no visible gap between bar and panel. (Some terminals
623		// — iTerm2, Apple Terminal — may smear the cell-0 bg into the
624		// window inset to the left; that's a terminal-side rendering
625		// quirk we accept in exchange for a clean bar-to-panel join.)
626		const leftGutter = 0                               // cells of bubble bg between bar and text
627		const rightGutter = 2                              // cells of bubble bg between text and right edge
628		innerWidth := width - 2 - leftGutter - rightGutter // 2 = bar's two cells (▌ + trailing space)
629		if innerWidth < 1 {
630			innerWidth = 1
631		}
632		row := func(content string) string {
633			inner := strings.Repeat(" ", leftGutter) + content
634			padded := v.Theme.UserBubble(inner, width-2)
635			bar := v.Theme.BG(v.Theme.UserBubbleBG, v.Theme.FG256(v.Theme.Accent, "▌ "))
636			return bar + padded
637		}
638		var bubble []string
639		for _, c := range m.Content {
640			switch b := c.(type) {
641			case provider.TextBlock:
642				for _, l := range strings.Split(b.Text, "\n") {
643					l = sanitizeUserBubbleLine(l)
644					for _, w := range wrapLine(l, innerWidth, "") {
645						bubble = append(bubble, row(w))
646					}
647				}
648			case provider.ImageBlock:
649				bubble = append(bubble, row(fmt.Sprintf("[image %s, %d bytes]", b.MimeType, len(b.Data))))
650			}
651		}
652		if len(bubble) > 0 {
653			lines = append(lines, row(""))
654			lines = append(lines, bubble...)
655			lines = append(lines, row(""))
656		}
657	case provider.RoleAssistant:
658		// Assistant rows: no speaker label either. Prose still gets a
659		// small left indent so it visually aligns with tool box body
660		// content, but no "zot" header.
661		_ = turnOpen
662		const indent = "  "
663		inner := assistantBodyWidth(width - len(indent))
664		for _, c := range m.Content {
665			switch b := c.(type) {
666			case provider.TextBlock:
667				md := RenderMarkdown(strings.TrimLeft(b.Text, "\n"), v.Theme, inner)
668				for _, l := range strings.Split(md, "\n") {
669					for _, w := range wrapANSILine(l, inner) {
670						lines = append(lines, indent+w)
671					}
672				}
673			case provider.ToolCallBlock:
674				// The whole box (top + body + bottom) is rendered by
675				// the matching tool_result message so a single
676				// assistant message that batches multiple tool_use
677				// blocks doesn't produce a stack of unclosed top
678				// edges. Each tool result owns its own box.
679				_ = b
680			}
681		}
682	case provider.RoleTool:
683		for _, c := range m.Content {
684			if tr, ok := c.(provider.ToolResultBlock); ok {
685				color := v.Theme.ToolOut
686				if tr.IsError {
687					color = v.Theme.Error
688				}
689				path := ""
690				if v.toolPaths != nil {
691					path = v.toolPaths[tr.CallID]
692				}
693				startLine := 1
694				if v.toolStartLines != nil {
695					if s := v.toolStartLines[tr.CallID]; s > 0 {
696						startLine = s
697					}
698				}
699				label := ""
700				if v.toolCallLabels != nil {
701					label = v.toolCallLabels[tr.CallID]
702				}
703				// Each tool result owns a complete box: top edge with
704				// the call's label, body rows wrapped in vertical
705				// edges, bottom edge to close. The label is looked up
706				// from the matching ToolCallBlock so multiple calls
707				// in one assistant message render as N adjacent boxes
708				// instead of stacking unclosed top edges.
709				lines = append(lines, toolBoxTop(v.Theme, label, width))
710				lines = append(lines, toolBoxSide(v.Theme, "", width))
711				if tr.IsError {
712					lines = append(lines, toolBoxSide(v.Theme, v.Theme.FG256(color, "  error"), width))
713				}
714				for _, line := range v.renderToolResultContent(tr.Content, width, color, path, startLine) {
715					// Image-footprint rows (the escape row, the blank
716					// reservation rows beneath it, and the gap row
717					// before the metadata caption) are tagged with the
718					// imageFootprintSentinel by renderImageBlock. Strip
719					// the tag, parse the optional width hint, then wrap
720					// the row in the usual │ ... │ box edges so the
721					// frame stays continuous around the image.
722					imgCells, stripped := parseImageFootprint(line)
723					if hasImageEscapeLine(stripped) {
724						lines = append(lines, toolBoxSideWithImage(v.Theme, stripped, imgCells, width))
725					} else {
726						lines = append(lines, toolBoxSide(v.Theme, stripped, width))
727					}
728				}
729				lines = append(lines, toolBoxSide(v.Theme, "", width))
730				lines = append(lines, toolBoxBottom(v.Theme, width))
731			}
732		}
733	}
734	return lines
735}
736
737func (v *View) renderToolCall(tc ToolCallView, width int) []string {
738	var lines []string
739
740	// Header label. While the call is still streaming, prefer the
741	// live path extracted from the partial args so the user sees
742	// the target file as soon as it's known, even before the full
743	// JSON arrived.
744	arg := tc.Args
745	if arg == "" && tc.LivePath != "" {
746		arg = tc.LivePath
747	}
748	label := tc.Name + " " + arg
749
750	// No leading blank: Build()'s inter-message separator already
751	// places one blank row between the previous transcript content
752	// and the live overlay, matching the spacing the same call has
753	// once it finalises into a transcript box. Adding another blank
754	// here would double the gap during streaming and visibly tighten
755	// when the overlay disappears.
756
757	// Live body (write/edit): keep the streamed preview visible until
758	// a real tool result arrives. The provider can finish the tool_use
759	// JSON before zot has executed the tool, so keying this on
760	// tc.Streaming makes write/edit boxes collapse for a moment between
761	// EvToolUseEnd and EvToolResult.
762	if tc.Result == "" {
763		if body := v.renderLiveToolBody(tc, width); len(body) > 0 {
764			// Pad the live preview up to the call's high-water height so
765			// it never shrinks mid-stream (e.g. between edit 1 and the
766			// start of edit 2). Padding sits inside the box as real
767			// box-side rows so the surrounding layout stays put. The
768			// high-water mark is per call id and is dropped the moment a
769			// Result lands (this branch only runs while Result == "").
770			high := len(body)
771			if v.liveBodyHigh != nil {
772				if prev := v.liveBodyHigh[tc.ID]; prev > high {
773					high = prev
774				}
775				v.liveBodyHigh[tc.ID] = high
776			}
777			for len(body) < high {
778				body = append(body, toolBoxSide(v.Theme, "", width))
779			}
780			lines = append(lines, toolBoxTop(v.Theme, label, width))
781			lines = append(lines, toolBoxSide(v.Theme, "", width))
782			lines = append(lines, body...)
783			lines = append(lines, toolBoxSide(v.Theme, "", width))
784			lines = append(lines, toolBoxBottom(v.Theme, width))
785			return lines
786		}
787	}
788
789	// Finished tool call with no body: just the labelled top edge
790	// directly closed by the bottom. Avoids a blank interior row
791	// for no-output tools.
792	if tc.Result == "" {
793		lines = append(lines, toolBoxTop(v.Theme, label, width))
794		lines = append(lines, toolBoxBottom(v.Theme, width))
795		return lines
796	}
797
798	// Finished tool call with a result body. Top edge embeds the
799	// label; body lines go through toolBoxSide so each row gets
800	// vertical edges; bottom edge closes the box. Blank interior
801	// rows after the top and before the bottom give the body a bit
802	// of breathing room from the corners.
803	lines = append(lines, toolBoxTop(v.Theme, label, width))
804	lines = append(lines, toolBoxSide(v.Theme, "", width))
805	color := v.Theme.ToolOut
806	if tc.Error {
807		color = v.Theme.Error
808	}
809	body := toolResultBlock(v.Theme, tc.Result, toolBoxBodyRenderWidth(width), color)
810	for _, l := range v.collapseToolBody(body, false) {
811		imgCells, stripped := parseImageFootprint(l)
812		if hasImageEscapeLine(stripped) {
813			lines = append(lines, toolBoxSideWithImage(v.Theme, stripped, imgCells, width))
814			continue
815		}
816		lines = append(lines, toolBoxSide(v.Theme, stripped, width))
817	}
818	lines = append(lines, toolBoxSide(v.Theme, "", width))
819	lines = append(lines, toolBoxBottom(v.Theme, width))
820	return lines
821}
822
823// renderLiveToolBody renders the in-flight preview of a streaming
824// tool call. Supported tools:
825//
826//   - write: shows the partial `content` field, syntax-highlighted
827//     by the target path's language.
828//   - edit:  shows the partial `newText` of the edit currently being
829//     streamed, prefixed with a "editing foo.ts (edit 2)" header so
830//     the user can see which of a multi-edit batch is in progress.
831//   - bash:  shows the full command as soon as the JSON args are known,
832//     before stdout/stderr has arrived, so long-running commands are legible.
833//
834// Anything else returns nil and only the tool-call header shows.
835func (v *View) renderLiveToolBody(tc ToolCallView, width int) []string {
836	switch tc.Name {
837	case "write", "Write":
838		partial, ok, _ := ExtractPartialStringField(tc.RawJSONBuf, "content")
839		if !ok || partial == "" {
840			return nil
841		}
842		return v.wrapLiveBody(v.renderRawFile(partial, tc.LivePath, 1), width)
843	case "edit", "Edit":
844		partial, ok, _, idx := ExtractLastNewText(tc.RawJSONBuf)
845		if !ok || partial == "" {
846			return nil
847		}
848		// Header line hints which edit is streaming and, when more
849		// than one has landed, how many the model is doing.
850		hint := fmt.Sprintf("edit %d (streaming)", idx)
851		body := []string{"    " + v.Theme.FG256(v.Theme.Muted, hint), ""}
852		body = append(body, v.renderRawFile(partial, tc.LivePath, 1)...)
853		return v.wrapLiveBody(body, width)
854	case "bash", "Bash":
855		command, ok, _ := ExtractPartialStringField(tc.RawJSONBuf, "command")
856		if !ok || strings.TrimSpace(command) == "" {
857			return nil
858		}
859		return v.wrapLiveBody(v.renderLiveBashCommand(command, width), width)
860	}
861	return nil
862}
863
864func (v *View) renderLiveBashCommand(command string, width int) []string {
865	inner := toolBoxBodyRenderWidth(width)
866	prompt := v.Theme.FG256(v.Theme.Muted, "$ ")
867	var out []string
868	for i, line := range strings.Split(command, "\n") {
869		firstPrefix := "    "
870		if i == 0 {
871			firstPrefix += prompt
872		} else {
873			firstPrefix += "  "
874		}
875		contPrefix := "      "
876		wrapWidth := inner - visibleWidth(firstPrefix)
877		if wrapWidth < 10 {
878			wrapWidth = 10
879		}
880		for j, wrapped := range wrapANSILine(v.Theme.FG256(v.Theme.ToolOut, line), wrapWidth) {
881			prefix := firstPrefix
882			if j > 0 {
883				prefix = contPrefix
884			}
885			out = append(out, prefix+wrapped)
886		}
887	}
888	return out
889}
890
891// wrapLiveBody returns the streaming body content as a list of
892// box-side rows: each line wrapped in │ ... │ with right padding so
893// the closing edge sits at column width-1. The caller (renderToolCall)
894// supplies the surrounding top/bottom edges so the live overlay
895// renders as a closed box matching the finalised transcript form.
896func (v *View) wrapLiveBody(body []string, width int) []string {
897	body = v.collapseToolBody(body, false)
898	out := make([]string, 0, len(body))
899	for _, l := range body {
900		imgCells, stripped := parseImageFootprint(l)
901		if hasImageEscapeLine(stripped) {
902			out = append(out, toolBoxSideWithImage(v.Theme, stripped, imgCells, width))
903			continue
904		}
905		out = append(out, toolBoxSide(v.Theme, stripped, width))
906	}
907	return out
908}
909
910// toolResultBlock wraps text in thin horizontal rules (top + bottom),
911// indenting the body with four spaces. The rules span the content column.
912// toolBlockRule renders the muted horizontal separator drawn
913// above and below a tool call block. Spans the full content
914// width so it reads as a real section break in the chat
915// regardless of terminal size.
916func toolBlockRule(th Theme, width int) string {
917	w := width
918	if w < 8 {
919		w = 8
920	}
921	return th.FG256(th.Muted, strings.Repeat("─", w))
922}
923
924// toolBoxInnerPad is the number of blank cells kept between a box
925// edge (┌, │, └) and the content inside it. One cell of breathing
926// room makes the label read as part of the box rather than fused to
927// the corner, and gives body lines a tiny gutter from the left side.
928const toolBoxInnerPad = 1
929
930// toolBoxOuterMargin is the number of blank cells kept to the left of
931// the opening corner and to the right of the closing corner. Aligns
932// the box's frame with the column where user-bubble text begins, so
933// the conversation reads as one column instead of having tool boxes
934// running edge-to-edge while user/assistant rows sit indented.
935const toolBoxOuterMargin = 2
936
937// toolBoxTop renders the labelled top edge of a tool block:
938//
939//	┌─  bash xcrun simctl list devices ─────────────────────────────┐
940//
941// The label is the tool name + short args (the same string previously
942// shown on its own row beneath the rule). Padding fills the remainder
943// of the line so the right corner sits at column width-1, matching the
944// closing edge.
945func toolBoxTop(th Theme, label string, width int) string {
946	label = oneLineToolLabel(label)
947	w := width - 2*toolBoxOuterMargin
948	if w < 12 {
949		w = 12
950	}
951	margin := strings.Repeat(" ", toolBoxOuterMargin)
952	innerPad := strings.Repeat(" ", toolBoxInnerPad)
953	// "┌─" + innerPad + " " + label + " " + innerPad = used; pad
954	// with ─ to width-1, then "┐".
955	prefix := "┌─" + innerPad + " "
956	suffix := " " + innerPad
957	used := visibleWidth(prefix) + visibleWidth(label) + visibleWidth(suffix)
958	fill := w - used - 1 // -1 for the closing corner
959	if fill < 0 {
960		// Label overflows; truncate with an ellipsis so the right
961		// corner still lands on the right edge. Rare on real
962		// terminals (the chat column is usually wide enough).
963		over := -fill
964		runes := []rune(label)
965		if over+3 < len(runes) {
966			label = string(runes[:len(runes)-over-3]) + "..."
967		} else {
968			label = "..."
969		}
970		used = visibleWidth(prefix) + visibleWidth(label) + visibleWidth(suffix)
971		fill = w - used - 1
972		if fill < 0 {
973			fill = 0
974		}
975	}
976	fillStr := strings.Repeat("─", fill)
977	name, rest := splitToolLabel(label)
978	return margin + th.FG256(th.Muted, prefix) + th.FG256(th.FG, name) + th.FG256(th.Muted, rest+suffix+fillStr+"┐") + margin
979}
980
981func oneLineToolLabel(label string) string {
982	return strings.Join(strings.Fields(label), " ")
983}
984
985func splitToolLabel(label string) (name, rest string) {
986	label = strings.TrimLeft(label, " ")
987	if label == "" {
988		return "", ""
989	}
990	idx := strings.IndexAny(label, " \t")
991	if idx < 0 {
992		return label, ""
993	}
994	return label[:idx], label[idx:]
995}
996
997// toolBoxBottom renders the bottom edge of a tool block:
998//
999//	└─────────────────────────────────────────────────────────────────────────────┘
1000//
1001// Spans the same width as toolBoxTop so the corners line up.
1002func toolBoxBottom(th Theme, width int) string {
1003	w := width - 2*toolBoxOuterMargin
1004	if w < 12 {
1005		w = 12
1006	}
1007	margin := strings.Repeat(" ", toolBoxOuterMargin)
1008	line := "└" + strings.Repeat("─", w-2) + "┘"
1009	return margin + th.FG256(th.Muted, line) + margin
1010}
1011
1012// hasImageEscapeLine reports whether s contains a Kitty (\x1b_G) or
1013// iTerm2 (\x1b]1337;File=) inline-image escape. Such rows draw into
1014// the terminal's graphics layer and shouldn't be wrapped with text
1015// box edges.
1016func hasImageEscapeLine(s string) bool {
1017	return strings.Contains(s, "\x1b]1337;File=") || strings.Contains(s, "\x1b_G")
1018}
1019
1020// imageFootprintSentinel marks rows that belong to an inline-image's
1021// reserved footprint — the escape row plus the blank rows below it
1022// plus the gap row before the metadata caption. Any consumer that
1023// wraps content in box edges (│ ... │) detects the sentinel, strips
1024// it, and emits the row — the image graphics rectangle paints over
1025// whatever was drawn there. Uses a non-printing C0 control byte so
1026// it can never appear in normal text or in an ANSI escape sequence
1027// body.
1028//
1029// The escape row carries an extra width hint between two sentinels:
1030// "\x1e<cells>\x1e<spaces+escape>". Wrappers parse the cells count
1031// to know how wide the image is in terminal cells and how many cells
1032// of trailing padding are needed before the closing box edge.
1033const imageFootprintSentinel = "\x1e"
1034
1035// parseImageFootprint splits a footprint-tagged row into (cellsWide,
1036// rest). cellsWide is 0 when the row carries no width hint (the
1037// reservation blanks and gap row don't, only the escape row does).
1038func parseImageFootprint(s string) (int, string) {
1039	if !strings.HasPrefix(s, imageFootprintSentinel) {
1040		return 0, s
1041	}
1042	rest := s[len(imageFootprintSentinel):]
1043	end := strings.Index(rest, imageFootprintSentinel)
1044	if end < 0 {
1045		return 0, rest
1046	}
1047	w, err := strconv.Atoi(rest[:end])
1048	if err != nil {
1049		return 0, rest
1050	}
1051	return w, rest[end+len(imageFootprintSentinel):]
1052}
1053
1054// toolBoxBodyTrimLeft is the number of leading literal spaces stripped
1055// from each body line as it enters toolBoxSide. Body renderers
1056// (renderToolText, renderRawFile, the diff/bash helpers, ...) all
1057// emit a 4-cell indent so the content aligns with the assistant body
1058// column when there's no box around it. Inside a box the box edge +
1059// inner pad already supply most of that gutter, so we drop a couple
1060// of cells from the body's own indent to keep the content from
1061// drifting too far right.
1062const toolBoxBodyTrimLeft = 2
1063
1064// toolBoxBodyRenderWidth is the width body renderers should target before
1065// their rows are wrapped by toolBoxSide. Most body renderers emit a four-cell
1066// indent; toolBoxSide trims toolBoxBodyTrimLeft cells from that indent and
1067// then adds the box edge/padding. Passing the full terminal width lets long
1068// bash/heredoc lines overrun the inner box and makes terminals soft-wrap,
1069// visually breaking the right edge. This returns the maximum renderer width
1070// whose post-trim visible width fits inside the box.
1071func toolBoxBodyRenderWidth(width int) int {
1072	w := width - 2*toolBoxOuterMargin
1073	if w < 12 {
1074		w = 12
1075	}
1076	inner := w - 2 - 2*toolBoxInnerPad
1077	if inner < 1 {
1078		inner = 1
1079	}
1080	return inner + toolBoxBodyTrimLeft
1081}
1082
1083// toolBoxSide wraps a single body line with vertical box edges:
1084//
1085//	│  foo bar baz                                            │
1086//
1087// The middle preserves the line verbatim (including any ANSI escapes)
1088// after stripping toolBoxBodyTrimLeft leading literal spaces. One cell
1089// of inner padding sits on each side so the content breathes from the
1090// edges; the right padding fills to column width-1.
1091func toolBoxSide(th Theme, line string, width int) string {
1092	w := width - 2*toolBoxOuterMargin
1093	if w < 12 {
1094		w = 12
1095	}
1096	margin := strings.Repeat(" ", toolBoxOuterMargin)
1097	left := th.FG256(th.Muted, "│") + strings.Repeat(" ", toolBoxInnerPad)
1098	right := strings.Repeat(" ", toolBoxInnerPad) + th.FG256(th.Muted, "│")
1099	inner := w - 2 - 2*toolBoxInnerPad // available between the two pads
1100	line = trimLeadingSpaces(line, toolBoxBodyTrimLeft)
1101
1102	cur := visibleWidth(line)
1103	if cur > inner {
1104		// Last-resort truncation. Strips ANSI styling at the cut
1105		// point; rare path so the simpler implementation is fine.
1106		line = stripANSI(line)
1107		runes := []rune(line)
1108		if len(runes) > inner {
1109			line = string(runes[:inner])
1110		}
1111		cur = visibleWidth(line)
1112	}
1113	pad := inner - cur
1114	if pad < 0 {
1115		pad = 0
1116	}
1117	return margin + left + line + strings.Repeat(" ", pad) + right + margin
1118}
1119
1120// toolBoxSideWithImage wraps a row that carries an inline-image
1121// escape sequence. The image protocols are configured to not move
1122// the cursor after rendering (iTerm: doNotMoveCursor=1, kitty/
1123// ghostty: C=1), so the only visible cell advance on the row is
1124// from the leading indent spaces before the escape. We pad from
1125// there to the right edge column and draw the closing │ there.
1126// imgCells is unused (kept in the signature for compatibility with
1127// the parseImageFootprint width hint).
1128func toolBoxSideWithImage(th Theme, line string, imgCells, width int) string {
1129	_ = imgCells
1130	w := width - 2*toolBoxOuterMargin
1131	if w < 12 {
1132		w = 12
1133	}
1134	margin := strings.Repeat(" ", toolBoxOuterMargin)
1135	left := th.FG256(th.Muted, "│") + strings.Repeat(" ", toolBoxInnerPad)
1136	right := strings.Repeat(" ", toolBoxInnerPad) + th.FG256(th.Muted, "│")
1137	inner := w - 2 - 2*toolBoxInnerPad
1138
1139	line = trimLeadingSpaces(line, toolBoxBodyTrimLeft)
1140
1141	// Count leading spaces (visible cells consumed before the escape).
1142	leading := 0
1143	for leading < len(line) && line[leading] == ' ' {
1144		leading++
1145	}
1146
1147	pad := inner - leading
1148	if pad < 0 {
1149		pad = 0
1150	}
1151	return margin + left + line + strings.Repeat(" ", pad) + right + margin
1152}
1153
1154// trimLeadingSpaces removes up to n literal space characters from the
1155// start of s without touching anything else. ANSI CSI escapes that
1156// appear before the spaces are skipped over (so a coloured indent
1157// like "\x1b[2m    text" still loses its first n cells of indent).
1158// Stops as soon as it hits a non-space character.
1159func trimLeadingSpaces(s string, n int) string {
1160	if n <= 0 || s == "" {
1161		return s
1162	}
1163	var b strings.Builder
1164	b.Grow(len(s))
1165	trimmed := 0
1166	i := 0
1167	for i < len(s) {
1168		// Pass through any ANSI escape sequence verbatim.
1169		if s[i] == 0x1b && i+1 < len(s) && s[i+1] == '[' {
1170			end := i + 2
1171			for end < len(s) {
1172				c := s[end]
1173				end++
1174				if c >= 0x40 && c <= 0x7e {
1175					break
1176				}
1177			}
1178			b.WriteString(s[i:end])
1179			i = end
1180			continue
1181		}
1182		if trimmed < n && s[i] == ' ' {
1183			trimmed++
1184			i++
1185			continue
1186		}
1187		b.WriteString(s[i:])
1188		return b.String()
1189	}
1190	return b.String()
1191}
1192
1193// renderToolResultContent renders the body of a tool result block.
1194// Text blocks get the usual rules-wrapped treatment; text that looks
1195// like a unified diff gets +/- coloring. Image blocks are rendered
1196// inline when the terminal supports a protocol, else as a text
1197// placeholder with dimensions.
1198func (v *View) renderToolResultContent(blocks []provider.Content, width, color int, sourcePath string, startLine int) []string {
1199	var body []string
1200	hasImage := false
1201	for _, b := range blocks {
1202		switch bb := b.(type) {
1203		case provider.TextBlock:
1204			bodyWidth := toolBoxBodyRenderWidth(width)
1205			body = append(body, v.renderToolText(bb.Text, bodyWidth, color, sourcePath, startLine)...)
1206		case provider.ImageBlock:
1207			hasImage = true
1208			body = append(body, v.renderImageBlock(bb, width)...)
1209		}
1210	}
1211	return v.collapseToolBody(body, hasImage)
1212}
1213
1214// collapseToolBody trims lines to the configured preview size when the
1215// view is not in ExpandAll mode, appending a muted "... ctrl+o to
1216// expand" footer. Image blocks never collapse — they're short in text
1217// rows but represent real content the user wants to see.
1218func (v *View) collapseToolBody(lines []string, hasImage bool) []string {
1219	if v.ExpandAll || hasImage {
1220		return lines
1221	}
1222	if len(lines) <= ToolCollapseLines {
1223		return lines
1224	}
1225	kept := lines[:ToolCollapsePreview]
1226	hidden := len(lines) - ToolCollapsePreview
1227	total := len(lines)
1228	footer := fmt.Sprintf("    ... (%d more lines, %d total, ctrl+o to expand)", hidden, total)
1229	footer = v.Theme.FG256(v.Theme.Muted, footer)
1230	out := append([]string(nil), kept...)
1231	out = append(out, "")
1232	return append(out, footer)
1233}
1234
1235// renderToolText renders a text block inside a tool result. If the
1236// text contains a unified-diff section (lines starting with "--- " /
1237// "+++ " / "+" / "-"/" "), those rows are styled with add/remove
1238// colors matching git diff conventions.
1239func (v *View) renderToolText(text string, width, defaultColor int, sourcePath string, startLine int) []string {
1240	// Legacy path: transcripts saved before we dropped line numbers
1241	// from the read tool still carry "     1\t..." prefixes. Detect and
1242	// strip them, then fall through to the highlighter.
1243	if looksLikeNumberedFile(text) {
1244		return v.renderNumberedFile(text, sourcePath)
1245	}
1246	// If the result embeds a unified diff (the edit tool's output
1247	// starts with a short "applied N edit(s)" line and then a
1248	// standard --- / +++ / +/- patch), render the patch with
1249	// add/remove coloring. This takes priority over the file-like
1250	// detector below because a diff technically has many lines of
1251	// "file content" but what the user cares about is what changed,
1252	// not a dump of the post-edit file.
1253	if looksLikeUnifiedDiff(text) {
1254		return v.renderUnifiedDiff(text, width, sourcePath)
1255	}
1256
1257	// Current path: text came from `read` as raw file bytes. When a
1258	// source path is known (the call had a `path` arg), render with
1259	// a synthetic line-number gutter starting at startLine so the
1260	// on-screen view still looks like cat -n. Doesn't apply to non-
1261	// file tool outputs (bash stdout, display notes, etc.).
1262	if sourcePath != "" && looksLikeFileContent(text) {
1263		return v.renderRawFile(text, sourcePath, startLine)
1264	}
1265
1266	// No truncation — the full tool output is rendered into chat and
1267	// becomes part of the scrollback you can page back through.
1268	lines := strings.Split(text, "\n")
1269
1270	// Bash-result styling: when the first row looks like a shell
1271	// prompt line ("$ ...") emitted by the bash tool, style the
1272	// prompt line in accent and the trailing "[exit N]  Took X.Ys"
1273	// line in muted type so the command + timing read at a glance.
1274	// Everything between is left on the default tool-output color.
1275	if len(lines) > 0 && strings.HasPrefix(lines[0], "$ ") {
1276		return v.renderBashResult(lines, width, defaultColor)
1277	}
1278
1279	inDiff := false
1280	oldLine, newLine := 1, 1
1281	var out []string
1282	for _, l := range lines {
1283		// Detect diff header: "--- name" followed somewhere by "+++ name".
1284		if strings.HasPrefix(l, "--- ") || strings.HasPrefix(l, "+++ ") {
1285			inDiff = true
1286			out = append(out, "    "+v.Theme.FG256(v.Theme.Muted, l))
1287			continue
1288		}
1289		// Hunk header "@@ -a,b +c,d @@" resets the counters so patches
1290		// that skip around in the file still get correct numbering.
1291		if inDiff && strings.HasPrefix(l, "@@") {
1292			if o, n, ok := parseHunkHeader(l); ok {
1293				oldLine, newLine = o, n
1294			}
1295			out = append(out, "    "+v.Theme.FG256(v.Theme.Muted, l))
1296			continue
1297		}
1298		if inDiff && strings.TrimSpace(l) == "..." {
1299			out = append(out, "")
1300			out = append(out, "    "+v.Theme.FG256(v.Theme.Muted, "..."))
1301			continue
1302		}
1303		if inDiff && len(l) > 0 {
1304			switch l[0] {
1305			case '+':
1306				out = append(out, v.renderDiffRow(l, width, v.Theme.Tool, newLine, '+', sourcePath))
1307				newLine++
1308				continue
1309			case '-':
1310				out = append(out, v.renderDiffRow(l, width, v.Theme.Error, oldLine, '-', sourcePath))
1311				oldLine++
1312				continue
1313			case ' ':
1314				out = append(out, v.renderDiffRow(l, width, v.Theme.Muted, newLine, ' ', sourcePath))
1315				oldLine++
1316				newLine++
1317				continue
1318			}
1319		}
1320		// Regular line.
1321		for _, w := range wrapLine(l, width-4, "    ") {
1322			out = append(out, "    "+v.Theme.FG256(defaultColor, w))
1323		}
1324	}
1325	return out
1326}
1327
1328// parseHunkHeader extracts the starting old/new line from a unified
1329// diff hunk header ("@@ -12,5 +12,7 @@ ..."). Returns ok=false if the
1330// header is malformed or missing numbers.
1331func parseHunkHeader(l string) (oldStart, newStart int, ok bool) {
1332	// Skip "@@ "
1333	rest := strings.TrimPrefix(l, "@@")
1334	rest = strings.TrimSpace(rest)
1335	if !strings.HasPrefix(rest, "-") {
1336		return 0, 0, false
1337	}
1338	rest = rest[1:]
1339	space := strings.IndexByte(rest, ' ')
1340	if space < 0 {
1341		return 0, 0, false
1342	}
1343	oldPart := rest[:space]
1344	rest = strings.TrimSpace(rest[space+1:])
1345	if !strings.HasPrefix(rest, "+") {
1346		return 0, 0, false
1347	}
1348	rest = rest[1:]
1349	if sp := strings.IndexAny(rest, " \t"); sp >= 0 {
1350		rest = rest[:sp]
1351	}
1352	parseStart := func(s string) (int, bool) {
1353		if c := strings.IndexByte(s, ','); c >= 0 {
1354			s = s[:c]
1355		}
1356		n, err := strconv.Atoi(s)
1357		if err != nil || n < 1 {
1358			return 0, false
1359		}
1360		return n, true
1361	}
1362	o, ok1 := parseStart(oldPart)
1363	n, ok2 := parseStart(rest)
1364	if !ok1 || !ok2 {
1365		return 0, 0, false
1366	}
1367	return o, n, true
1368}
1369
1370// renderDiffRow renders one unified-diff line with a read-style gutter
1371// (6-cell right-aligned line number, muted) followed by the +/-/space
1372// marker and the code. Code is syntax-highlighted if sourcePath hints
1373// at a known language; falls back to the plain diff color otherwise.
1374func (v *View) renderDiffRow(line string, width, color int, lineNo int, mark byte, sourcePath string) string {
1375	if len(line) == 0 {
1376		return ""
1377	}
1378	code := expandTabs(line[1:]) // strip the leading marker; expand tabs
1379
1380	// Syntax-highlight the code half when we know the language. Use
1381	// the same HighlightCode pipeline as renderNumberedFile so the
1382	// palette matches.
1383	lang := LanguageFromPath(sourcePath)
1384	var codeRendered string
1385	if lang != "" {
1386		if h := v.Theme.HighlightCode(code, lang); len(h) == 1 {
1387			codeRendered = h[0]
1388		}
1389	}
1390	if codeRendered == "" {
1391		if mark == ' ' {
1392			codeRendered = v.Theme.FG256(v.Theme.Muted, code)
1393		} else {
1394			codeRendered = v.Theme.FG256(color, code)
1395		}
1396	}
1397
1398	// Gutter shape: sign + number share a color so they read as one
1399	// visual token ("+123") instead of a neutral line number next to
1400	// a stray marker. Unchanged context lines get a muted gutter and
1401	// a leading space so column alignment stays consistent with +/-
1402	// rows.
1403	var gutterText string
1404	switch mark {
1405	case '+':
1406		gutterText = fmt.Sprintf("+%3d ", lineNo)
1407	case '-':
1408		gutterText = fmt.Sprintf("-%3d ", lineNo)
1409	default:
1410		gutterText = fmt.Sprintf(" %3d ", lineNo)
1411	}
1412	var gutter string
1413	if mark == ' ' {
1414		gutter = v.Theme.FG256(v.Theme.Muted, gutterText)
1415	} else {
1416		gutter = v.Theme.FG256(color, gutterText)
1417	}
1418	row := "    " + gutter + codeRendered
1419
1420	// Cheap width clamp: truncate visible text if the raw code is too
1421	// long. We work on the pre-ANSI code string because measuring ansi
1422	// output is unreliable.
1423	maxCode := width - 4 /* indent */ - 7 /* gutter (sign+5 digits+tab) */
1424	if maxCode > 0 && len(code) > maxCode {
1425		trunc := strings.Repeat(".", maxCode)
1426		if maxCode > 3 {
1427			trunc = code[:maxCode-3] + "..."
1428		}
1429		if lang != "" {
1430			if h := v.Theme.HighlightCode(trunc, lang); len(h) == 1 {
1431				codeRendered = h[0]
1432			} else if mark == ' ' {
1433				codeRendered = v.Theme.FG256(v.Theme.Muted, trunc)
1434			} else {
1435				codeRendered = v.Theme.FG256(color, trunc)
1436			}
1437		} else if mark == ' ' {
1438			codeRendered = v.Theme.FG256(v.Theme.Muted, trunc)
1439		} else {
1440			codeRendered = v.Theme.FG256(color, trunc)
1441		}
1442		row = "    " + gutter + codeRendered
1443	}
1444	return row
1445}
1446
1447// renderImageBlock returns the lines for one image, inline if possible.
1448//
1449// Inline image escapes paint into multiple terminal rows but the zot
1450// renderer treats each slice entry as a single row. To prevent chat
1451// content from being drawn on top of the image, we pad with blank rows
1452// so the image's real footprint is reflected in the frame height.
1453func (v *View) renderImageBlock(b provider.ImageBlock, width int) []string {
1454	w, h := ImageDimensions(b.Data)
1455	kb := len(b.Data) / 1024
1456	// Four-space indent matches every other tool-output row
1457	// (renderRawFile, renderBashResult, diff rows, "... N more
1458	// lines" footers). Keeps the image's metadata line vertically
1459	// aligned with the file content above / below it.
1460	info := fmt.Sprintf("    image - %s - %dx%d - %d KB", b.MimeType, w, h, kb)
1461
1462	if v.ImageProto != ImageProtocolNone {
1463		// Clamp rendered width so the image never overflows the chat
1464		// column. Subtract a 4-cell indent for the tool result block,
1465		// cap at 60 cells, floor at 10.
1466		cells := width - 4
1467		if cells > 60 {
1468			cells = 60
1469		}
1470		if cells < 10 {
1471			cells = 10
1472		}
1473		const maxRows = 20
1474		if seq := RenderInlineImageScaled(v.ImageProto, b.Data, b.MimeType, cells, maxRows); seq != "" {
1475			rows, actualCells := InlineImageFootprint(b.Data, cells, maxRows)
1476			if rows < 1 {
1477				rows = 1
1478			}
1479			if actualCells < 1 {
1480				actualCells = cells
1481			}
1482			// Reserve the image footprint first, then place the escape
1483			// in the top-left of that blank rectangle. Keeping the
1484			// metadata above the image made some terminals blend text
1485			// and graphics layers during full-screen repaints; metadata
1486			// below the reserved rectangle is more stable and easier to
1487			// read. One extra blank row before the metadata gives the
1488			// caption breathing room from the image's last pixel row.
1489			//
1490			// Every footprint row (escape, reservations, gap) is tagged
1491			// with imageFootprintSentinel so callers wrapping content in
1492			// box edges can recognise these rows and emit them bare —
1493			// the image's graphics rectangle paints over them and any
1494			// │ character drawn alongside would visibly bleed through.
1495			// 4 leading cells push the escape past the box's left
1496			// edge plus a small interior gutter so the image rectangle
1497			// sits visibly inside the frame instead of kissing the │.
1498			// The escape row carries a width hint after the sentinel
1499			// ("\x1e<cells>\x1e...") so toolBoxSide knows how many
1500			// cells the image occupies and can pad to the right edge.
1501			widthHint := fmt.Sprintf("%s%d%s", imageFootprintSentinel, actualCells, imageFootprintSentinel)
1502			out := make([]string, 0, rows+3)
1503			out = append(out, widthHint+"    "+seq)
1504			for i := 1; i < rows; i++ {
1505				out = append(out, imageFootprintSentinel)
1506			}
1507			out = append(out, imageFootprintSentinel)
1508			out = append(out, v.Theme.FG256(v.Theme.Muted, info))
1509			return out
1510		}
1511	}
1512	return []string{v.Theme.FG256(v.Theme.Muted, info)}
1513}
1514
1515// looksLikeNumberedFile returns true when text matches the `read`
1516// tool's "     N\tcontent" format for most of its lines.
1517func looksLikeNumberedFile(text string) bool {
1518	lines := strings.Split(text, "\n")
1519	if len(lines) == 0 {
1520		return false
1521	}
1522	hits := 0
1523	scanned := 0
1524	for _, l := range lines {
1525		if l == "" {
1526			continue
1527		}
1528		scanned++
1529		if scanned > 20 {
1530			break
1531		}
1532		if numberedLineRE.MatchString(l) {
1533			hits++
1534		}
1535	}
1536	if scanned == 0 {
1537		return false
1538	}
1539	return hits*2 >= scanned // majority of non-empty lines match
1540}
1541
1542var numberedLineRE = regexp.MustCompile(`^\s*\d+\t`)
1543
1544// renderNumberedFile strips line numbers, highlights the code, and
1545// re-attaches the line numbers in muted color.
1546func (v *View) renderNumberedFile(text, sourcePath string) []string {
1547	lines := strings.Split(text, "\n")
1548	gutters := make([]string, 0, len(lines))
1549	codes := make([]string, 0, len(lines))
1550	for _, l := range lines {
1551		idx := strings.IndexByte(l, '\t')
1552		if idx < 0 || !numberedLineRE.MatchString(l) {
1553			// Non-code footer (e.g. "[truncated at 2000 lines]").
1554			gutters = append(gutters, "")
1555			codes = append(codes, l)
1556			continue
1557		}
1558		gutter := l[:idx] + " " // replace tab with single space
1559		code := expandTabs(l[idx+1:])
1560		gutters = append(gutters, gutter)
1561		codes = append(codes, code)
1562	}
1563	lang := LanguageFromPath(sourcePath)
1564	var highlighted []string
1565	if lang != "" {
1566		highlighted = v.Theme.HighlightCode(strings.Join(codes, "\n"), lang)
1567		// Chroma sometimes collapses the trailing empty line. Pad to
1568		// align with the gutter slice so per-line zipping works.
1569		for len(highlighted) < len(codes) {
1570			highlighted = append(highlighted, "")
1571		}
1572		if len(highlighted) > len(codes) {
1573			highlighted = highlighted[:len(codes)]
1574		}
1575	} else {
1576		// No lexer for this file type — render in the ToolOut color so
1577		// code is visually distinct from the muted gutter.
1578		highlighted = make([]string, len(codes))
1579		for i, c := range codes {
1580			highlighted[i] = v.Theme.FG256(v.Theme.ToolOut, c)
1581		}
1582	}
1583	out := make([]string, 0, len(codes))
1584	for i, code := range highlighted {
1585		g := gutters[i]
1586		if g == "" {
1587			out = append(out, "    "+v.Theme.FG256(v.Theme.Muted, code))
1588			continue
1589		}
1590		out = append(out, "    "+v.Theme.FG256(v.Theme.Muted, g)+code)
1591	}
1592	return out
1593}
1594
1595// looksLikeFileContent is a cheap guard to distinguish a read-tool
1596// result from bash stdout or a status message. File content usually
1597// contains characters that status messages don't (code punctuation,
1598// longer lines, multiple lines) and rarely starts with the "  >"-
1599// or "error:"-style prefixes tools emit. False positives are OK,
1600// the worst case is a line-number gutter on something that isn't
1601// really code.
1602// renderBashResult styles a bash tool result: the "$ command" first
1603// line in the accent color, the trailing "[exit N]  Took X.Ys" line
1604// in muted type, everything else on the default tool-output color.
1605// Called from renderToolText when the first line starts with "$ ".
1606func (v *View) renderBashResult(lines []string, width, defaultColor int) []string {
1607	lines = normalizeBashOutputLines(lines)
1608	// Identify the footer line (exit + timing). The bash tool writes
1609	// it as the last non-empty line of the result.
1610	footerIdx := -1
1611	for i := len(lines) - 1; i >= 0; i-- {
1612		trimmed := strings.TrimSpace(lines[i])
1613		if trimmed == "" {
1614			continue
1615		}
1616		if strings.HasPrefix(trimmed, "[exit ") {
1617			footerIdx = i
1618		}
1619		break
1620	}
1621
1622	var out []string
1623	for i, l := range lines {
1624		switch {
1625		case i == 0 && strings.HasPrefix(l, "$ "):
1626			// Style the $ and the command text in accent. No
1627			// further processing / wrapping so the shell-style
1628			// prompt reads at a glance.
1629			for _, w := range wrapLine(l, width-4, "    ") {
1630				out = append(out, "    "+v.Theme.FG256(v.Theme.Accent, w))
1631			}
1632		case i == footerIdx:
1633			for _, w := range wrapLine(l, width-4, "    ") {
1634				out = append(out, "    "+v.Theme.FG256(v.Theme.Muted, w))
1635			}
1636		default:
1637			for _, w := range wrapLine(l, width-4, "    ") {
1638				out = append(out, "    "+v.Theme.FG256(defaultColor, w))
1639			}
1640		}
1641	}
1642	return out
1643}
1644
1645// normalizeBashOutputLines turns arbitrary terminal output into plain,
1646// box-safe rows before wrapping. Unlike read/write/edit output, bash
1647// stdout/stderr may contain tabs, carriage returns, ANSI/OSC escapes,
1648// and other C0 controls from subprocesses. If those reach the bordered
1649// tool box, the width calculator can undercount what the terminal will
1650// draw and the right edge appears broken. Keep printable text, expand
1651// tabs to spaces, split carriage-return progress rows, and drop escape
1652// / control sequences.
1653func normalizeBashOutputLines(lines []string) []string {
1654	var out []string
1655	for _, line := range lines {
1656		for _, part := range strings.Split(strings.ReplaceAll(line, "\r", "\n"), "\n") {
1657			out = append(out, normalizeBashOutputLine(part))
1658		}
1659	}
1660	if len(out) == 0 {
1661		return []string{""}
1662	}
1663	return out
1664}
1665
1666func normalizeBashOutputLine(s string) string {
1667	var b strings.Builder
1668	col := 0
1669	for i := 0; i < len(s); {
1670		c := s[i]
1671		if c == 0x1b { // ESC: strip CSI/OSC/DCS and simple escapes.
1672			i = skipEscapeSequence(s, i)
1673			continue
1674		}
1675		r, size := utf8.DecodeRuneInString(s[i:])
1676		if r == utf8.RuneError && size == 1 {
1677			i++
1678			continue
1679		}
1680		switch r {
1681		case '\t':
1682			spaces := 8 - (col % 8)
1683			if spaces == 0 {
1684				spaces = 8
1685			}
1686			b.WriteString(strings.Repeat(" ", spaces))
1687			col += spaces
1688		case '\b':
1689			// Backspace-overstrike output is common in spinners/progress bars.
1690			// Dropping it is safer than moving the TUI cursor backwards.
1691		case '\n', '\r':
1692			// Already split by normalizeBashOutputLines.
1693		default:
1694			if r < 0x20 || r == 0x7f {
1695				// Drop non-printing controls.
1696				break
1697			}
1698			b.WriteRune(r)
1699			col += runewidth.RuneWidth(r)
1700		}
1701		i += size
1702	}
1703	return b.String()
1704}
1705
1706func skipEscapeSequence(s string, i int) int {
1707	if i >= len(s) || s[i] != 0x1b {
1708		return i + 1
1709	}
1710	if i+1 >= len(s) {
1711		return len(s)
1712	}
1713	switch s[i+1] {
1714	case '[': // CSI: ESC [ ... final byte 0x40-0x7e
1715		j := i + 2
1716		for j < len(s) {
1717			c := s[j]
1718			j++
1719			if c >= 0x40 && c <= 0x7e {
1720				break
1721			}
1722		}
1723		return j
1724	case ']': // OSC: ESC ] ... BEL or ST
1725		return skipStringEscape(s, i+2)
1726	case 'P', '_', '^', 'X': // DCS/APC/PM/SOS: ESC P ... ST, etc.
1727		return skipStringEscape(s, i+2)
1728	default:
1729		// Two-byte escape (cursor save/restore, charset select, etc.).
1730		return i + 2
1731	}
1732}
1733
1734func skipStringEscape(s string, i int) int {
1735	for i < len(s) {
1736		if s[i] == 0x07 { // BEL
1737			return i + 1
1738		}
1739		if s[i] == 0x1b && i+1 < len(s) && s[i+1] == '\\' { // ST
1740			return i + 2
1741		}
1742		i++
1743	}
1744	return len(s)
1745}
1746
1747// looksLikeUnifiedDiff reports whether text is a context diff as
1748// emitted by the edit tool: rows start with '+', '-', ' ', or
1749// literal "..." (context-break marker). The presence of at least
1750// one '+' or '-' row distinguishes a real diff from an ordinary
1751// file whose lines happen to begin with a space.
1752func looksLikeUnifiedDiff(text string) bool {
1753	lines := strings.Split(text, "\n")
1754	if len(lines) < 2 {
1755		return false
1756	}
1757	sawChange := false
1758	for _, l := range lines {
1759		if l == "" {
1760			continue
1761		}
1762		if l == "..." {
1763			continue
1764		}
1765		switch l[0] {
1766		case '+', '-':
1767			sawChange = true
1768		case ' ':
1769			// context, ok
1770		default:
1771			return false
1772		}
1773	}
1774	return sawChange
1775}
1776
1777// renderUnifiedDiff renders the edit tool's context diff. Each
1778// kept row shows a line-number gutter plus a marker column: '+'
1779// for additions (colored like add), '-' for deletions (colored
1780// like remove), and unmarked context in muted type. A literal
1781// "..." line between hunks renders as an ellipsis in muted type,
1782// indicating skipped unchanged rows. The old and new line
1783// counters advance so each row carries its actual position in
1784// the pre- or post-edit file. Heuristic: when we hit a "...", we
1785// can't know where the next hunk starts, so we don't reset the
1786// counters — they stay approximate in the rare multi-hunk case.
1787func (v *View) renderUnifiedDiff(text string, width int, sourcePath string) []string {
1788	lines := strings.Split(text, "\n")
1789	if n := len(lines); n > 0 && lines[n-1] == "" {
1790		lines = lines[:n-1]
1791	}
1792	oldLine, newLine := 1, 1
1793	var out []string
1794	for _, l := range lines {
1795		if l == "" {
1796			out = append(out, "")
1797			continue
1798		}
1799		if l == "..." {
1800			out = append(out, "    "+v.Theme.FG256(v.Theme.Muted, "..."))
1801			continue
1802		}
1803		switch l[0] {
1804		case '+':
1805			out = append(out, v.renderDiffRow(l, width, v.Theme.Tool, newLine, '+', sourcePath))
1806			newLine++
1807		case '-':
1808			out = append(out, v.renderDiffRow(l, width, v.Theme.Error, oldLine, '-', sourcePath))
1809			oldLine++
1810		case ' ':
1811			out = append(out, v.renderDiffRow(l, width, v.Theme.Muted, newLine, ' ', sourcePath))
1812			oldLine++
1813			newLine++
1814		default:
1815			for _, w := range wrapLine(l, width-4, "    ") {
1816				out = append(out, "    "+v.Theme.FG256(v.Theme.Muted, w))
1817			}
1818		}
1819	}
1820	return out
1821}
1822
1823func looksLikeFileContent(text string) bool {
1824	if strings.TrimSpace(text) == "" {
1825		return false
1826	}
1827	lines := strings.Split(text, "\n")
1828	return len(lines) >= 2
1829}
1830
1831// renderRawFile renders file content received without embedded line
1832// numbers (the current read-tool output). Draws a muted gutter like
1833// "%6d \t" starting at startLine, highlights the code using the
1834// source path's language, and returns the formatted lines.
1835func (v *View) renderRawFile(text, sourcePath string, startLine int) []string {
1836	lines := strings.Split(text, "\n")
1837	// Drop the trailing empty line that Split produces when text ends
1838	// in "\n" so the gutter doesn't show a phantom last number.
1839	if n := len(lines); n > 0 && lines[n-1] == "" {
1840		lines = lines[:n-1]
1841	}
1842	// Split code from trailing footer lines ("... [truncated ...]")
1843	// so we don't number the footer. A single blank separator line
1844	// immediately before the footer is also pulled out so the
1845	// gutter doesn't render a phantom number for it.
1846	codeEnd := len(lines)
1847	for i := len(lines) - 1; i >= 0; i-- {
1848		if strings.HasPrefix(lines[i], "...") {
1849			codeEnd = i
1850			continue
1851		}
1852		break
1853	}
1854	if codeEnd > 0 && codeEnd < len(lines) && lines[codeEnd-1] == "" {
1855		codeEnd--
1856	}
1857	code := lines[:codeEnd]
1858	footer := lines[codeEnd:]
1859
1860	// Expand tabs to 4 spaces so Go / Makefile code renders
1861	// at a consistent width.
1862	for i, c := range code {
1863		code[i] = expandTabs(c)
1864	}
1865
1866	lang := LanguageFromPath(sourcePath)
1867	var highlighted []string
1868	if lang != "" {
1869		highlighted = v.Theme.HighlightCode(strings.Join(code, "\n"), lang)
1870		for len(highlighted) < len(code) {
1871			highlighted = append(highlighted, "")
1872		}
1873		if len(highlighted) > len(code) {
1874			highlighted = highlighted[:len(code)]
1875		}
1876	} else {
1877		highlighted = make([]string, len(code))
1878		for i, c := range code {
1879			highlighted[i] = v.Theme.FG256(v.Theme.ToolOut, c)
1880		}
1881	}
1882
1883	out := make([]string, 0, len(lines))
1884	for i, c := range highlighted {
1885		gutter := fmt.Sprintf("%4d ", startLine+i)
1886		out = append(out, "    "+v.Theme.FG256(v.Theme.Muted, gutter)+c)
1887	}
1888	for _, f := range footer {
1889		out = append(out, "    "+v.Theme.FG256(v.Theme.Muted, f))
1890	}
1891	return out
1892}
1893
1894// toolResultBlock renders the live tool-call result body (shown
1895// while the turn is still in flight). The rules that used to
1896// bracket this block have been dropped so the live path looks
1897// identical to the transcript rendering that replaces it when
1898// the turn ends.
1899func toolResultBlock(th Theme, text string, width int, color int) []string {
1900	var out []string
1901	for _, l := range strings.Split(text, "\n") {
1902		for _, w := range wrapLine(l, width-4, "    ") {
1903			out = append(out, "    "+th.FG256(color, w))
1904		}
1905	}
1906	return out
1907}
1908
1909// ShortArgs renders a tool call's arguments into a one-line
1910// suffix for the "tool name <args>" header. tool is the tool
1911// name so we can add shape-specific decorations: for read we
1912// append the requested line range (e.g. "path:1-200") pulled
1913// from the offset/limit args, which is useful context at a
1914// glance without expanding the result body. Other tools keep
1915// the legacy "path or command, truncated at 60 cells" shape.
1916//
1917// Exported because the interactive mode pre-populates the
1918// ToolCallView.Args field with this value as soon as the tool
1919// call is announced, so the live overlay's header matches what
1920// the finalised transcript will later render.
1921func ShortArgs(tool string, raw json.RawMessage) string {
1922	var v any
1923	if err := json.Unmarshal(raw, &v); err != nil {
1924		return ""
1925	}
1926	x, ok := v.(map[string]any)
1927	if !ok {
1928		b, _ := json.Marshal(v)
1929		s := oneLineToolLabel(string(b))
1930		if len(s) > 60 {
1931			s = s[:57] + "..."
1932		}
1933		return s
1934	}
1935	var primary string
1936	for _, k := range []string{"path", "file_path", "command"} {
1937		if s, ok := x[k].(string); ok {
1938			primary = s
1939			break
1940		}
1941	}
1942	if primary == "" {
1943		b, _ := json.Marshal(v)
1944		s := oneLineToolLabel(string(b))
1945		if len(s) > 60 {
1946			s = s[:57] + "..."
1947		}
1948		return s
1949	}
1950	primary = oneLineToolLabel(primary)
1951
1952	// Tool-specific decoration. Only the read tool gets a range
1953	// suffix for now; other tools just truncate the primary arg.
1954	suffix := ""
1955	switch strings.ToLower(tool) {
1956	case "read":
1957		start := 1
1958		if n, ok := toInt(x["offset"]); ok && n >= 1 {
1959			start = n
1960		}
1961		if lim, ok := toInt(x["limit"]); ok && lim > 0 {
1962			end := start + lim - 1
1963			suffix = fmt.Sprintf(":%d-%d", start, end)
1964		} else if start > 1 {
1965			suffix = fmt.Sprintf(":%d-", start)
1966		}
1967	}
1968
1969	// Truncate the primary arg leaving room for the suffix so the
1970	// range stays visible even on absurdly long paths.
1971	max := 60 - len(suffix)
1972	if max < 10 {
1973		max = 10
1974	}
1975	if len(primary) > max {
1976		primary = primary[:max-3] + "..."
1977	}
1978	return primary + suffix
1979}
1980
1981// toInt coerces a json.Unmarshal'd number (float64) or a string
1982// containing a number into an int. Returns ok=false if the value
1983// is neither. Used by shortArgs to survive model quirks where
1984// numeric args come back as strings.
1985func toInt(v any) (int, bool) {
1986	switch n := v.(type) {
1987	case float64:
1988		return int(n), true
1989	case int:
1990		return n, true
1991	case string:
1992		i, err := strconv.Atoi(strings.TrimSpace(n))
1993		if err != nil {
1994			return 0, false
1995		}
1996		return i, true
1997	}
1998	return 0, false
1999}
2000
2001func collectText(blocks []provider.Content) string {
2002	var sb strings.Builder
2003	for _, b := range blocks {
2004		if tb, ok := b.(provider.TextBlock); ok {
2005			if sb.Len() > 0 {
2006				sb.WriteString("\n")
2007			}
2008			sb.WriteString(tb.Text)
2009		}
2010	}
2011	return sb.String()
2012}
2013
2014func truncateLines(s string, n int) string {
2015	lines := strings.Split(s, "\n")
2016	if len(lines) <= n {
2017		return s
2018	}
2019	return strings.Join(lines[:n], "\n") + "\n  ... (" + fmt.Sprintf("%d", len(lines)-n) + " more)"
2020}
2021
2022// renderCompactionBlock renders a compaction summary as a distinct
2023// visual block in the chat. When collapsed it shows a one-line label
2024// with the pre-compaction token count; when expanded (ctrl+o) it
2025// shows the full summary text.
2026func (v *View) renderCompactionBlock(m provider.Message, width int) []string {
2027	th := v.Theme
2028	const indent = "    "
2029
2030	tokens := m.Meta["tokens_before"]
2031	if tokens == "" {
2032		tokens = "?"
2033	}
2034
2035	if v.ExpandAll {
2036		var lines []string
2037		header := th.FG256(th.Muted, fmt.Sprintf("compacted from ~%s tokens", tokens))
2038		lines = append(lines, indent+header)
2039		lines = append(lines, "")
2040		for _, c := range m.Content {
2041			if tb, ok := c.(provider.TextBlock); ok {
2042				text := tb.Text
2043				if idx := strings.Index(text, "\n\n"); idx >= 0 && strings.HasPrefix(text, "## Context Summary") {
2044					text = text[idx+2:]
2045				}
2046				md := RenderMarkdown(text, th, width-4)
2047				for _, l := range strings.Split(md, "\n") {
2048					if len(l) > 0 && l[0] == FlushLeftSentinel {
2049						l = l[1:]
2050					}
2051					lines = append(lines, indent+l)
2052				}
2053			}
2054		}
2055		return lines
2056	}
2057
2058	// Collapsed: single line, no banner.
2059	line := th.FG256(th.Muted, fmt.Sprintf("compacted from ~%s tokens (ctrl+o to expand)", tokens))
2060	return []string{indent + line}
2061}
2062
2063// StatusBarParams groups the many bits of state the status bar needs.
2064// Grew from a flat argument list once we settled on the layout.
2065type StatusBarParams struct {
2066	Theme      Theme
2067	Provider   string
2068	Model      string
2069	Reasoning  string // "" means thinking off
2070	Busy       bool
2071	BusyPrefix string // spinner + funny line when busy
2072	CWD        string
2073	Locked     bool // sandbox on?
2074	NoYolo     bool // confirmation mode enabled?
2075
2076	// Cumulative session usage and cost.
2077	Usage provider.Usage
2078	// Subscription is true when the credential is an OAuth token (claude
2079	// pro/max, chatgpt plus/pro) rather than a paid api key. We still
2080	// compute a cost for visibility and append "(sub)" so the user
2081	// knows no real money moved.
2082	Subscription bool
2083
2084	// Last turn's input+cache tokens (approximates current live context).
2085	ContextUsed int
2086	ContextMax  int // model's context window; 0 disables the percentage
2087
2088	// AutoCompacting is true when the agent is currently running a
2089	// model-triggered condense pass. Surfaces as "(auto)" after the
2090	// context percentage so it's clear where the spinner is coming from.
2091	AutoCompacting bool
2092
2093	// Telegram true when the telegram bridge is connected. Adds a
2094	// small "- tg -" tag to the cwd line so the user can tell at a
2095	// glance that dms are being mirrored into this session.
2096	Telegram bool
2097
2098	Cols int // terminal width; drives right-alignment of cwd
2099}
2100
2101// StatusBar builds the status shown above the editor. Always returns
2102// two lines when a cwd is provided: the stats on the first line, the
2103// cwd on its own line below, indented to match the stats column. This
2104// keeps the status bar stable across terminal resizes (the cwd never
2105// jumps from right-aligned-on-line-1 to flush-left-on-line-2) and
2106// makes a long cwd safe at any width.
2107//
2108// Layout:
2109//
2110//	<busyPrefix>  (provider) model  stats   <- line 1
2111//	  cwd                                   <- line 2 (2-space indent)
2112//
2113// The old "ctrl+c exit - /help" / "esc cancel" hint is gone entirely.
2114// The slash-command popup and the queued/sliding-in chips already
2115// cover the discoverability of those keybindings.
2116func StatusBar(p StatusBarParams) []string {
2117	th := p.Theme
2118
2119	// Token stats: only include each segment when non-zero. Keeps
2120	// the bar compact on brand-new sessions.
2121	var stats []string
2122	if p.Usage.InputTokens > 0 {
2123		stats = append(stats, fmt.Sprintf("↑%s", formatTokens(p.Usage.InputTokens)))
2124	}
2125	if p.Usage.OutputTokens > 0 {
2126		stats = append(stats, fmt.Sprintf("↓%s", formatTokens(p.Usage.OutputTokens)))
2127	}
2128	if p.Usage.CacheReadTokens > 0 {
2129		stats = append(stats, fmt.Sprintf("R%s", formatTokens(p.Usage.CacheReadTokens)))
2130	}
2131	if p.Usage.CacheWriteTokens > 0 {
2132		stats = append(stats, fmt.Sprintf("W%s", formatTokens(p.Usage.CacheWriteTokens)))
2133	}
2134
2135	// Cost: always show the dollar value computed from token counts,
2136	// even on subscription. Lets you see what the equivalent api cost
2137	// would be (handy for gauging subscription value). Append "(sub)"
2138	// only as a hint that no real money moved.
2139	var costStr string
2140	if p.Usage.CostUSD > 0 || p.Subscription {
2141		costStr = fmt.Sprintf("$%.3f", p.Usage.CostUSD)
2142		if p.Subscription {
2143			costStr += " (sub)"
2144		}
2145	}
2146	if costStr != "" {
2147		stats = append(stats, costStr)
2148	}
2149
2150	// Context %. Color-coded: yellow >70, red >90.
2151	ctx, ctxColor := contextUsage(th, p.ContextUsed, p.ContextMax)
2152	if ctx != "" {
2153		if p.AutoCompacting {
2154			ctx += " (auto)"
2155		}
2156		stats = append(stats, th.FG256(ctxColor, ctx))
2157	}
2158
2159	// Layout uses exactly 2 spaces of horizontal padding everywhere:
2160	//   2 spaces  (openai) gpt-5.4  $0.000 (sub) 0.0%/400k  ~/Sites/zot
2161	// matches the editor prompt's left inset so the bar lines up
2162	// vertically with the conversation column.
2163	const pad = "  " // 2 spaces
2164
2165	left := fmt.Sprintf("(%s) %s", p.Provider, p.Model)
2166	thinking := thinkingLevelLabel(p.Reasoning)
2167	thinkingText := ""
2168	if thinking != "" {
2169		thinkingText = "thinking: " + thinking
2170	}
2171	statsText := strings.Join(stats, " ")
2172	middleParts := make([]string, 0, 2)
2173	if thinkingText != "" {
2174		middleParts = append(middleParts, thinkingText)
2175	}
2176	if statsText != "" {
2177		middleParts = append(middleParts, statsText)
2178	}
2179	middle := strings.Join(middleParts, "  ")
2180
2181	var leftBuilder strings.Builder
2182	if p.BusyPrefix != "" {
2183		// Don't re-color the payload itself — the caller already set
2184		// fg colors on the spinner glyph, message, and elapsed
2185		// segments. Wrapping the whole thing here would override
2186		// those choices. The pad itself needs no color (it's spaces).
2187		leftBuilder.WriteString(pad + p.BusyPrefix)
2188		// Exactly one pad (2 spaces) between the busy segment and
2189		// the provider/model block. The leading pad above covers
2190		// the left indent.
2191		leftBuilder.WriteString(pad)
2192	} else {
2193		// Idle path: a single pad of left inset so the line
2194		// aligns with the conversation column on its left edge
2195		// ("  you" / "  zot" message markers). Without the busy
2196		// prefix there's no trailing separator to double-pad.
2197		leftBuilder.WriteString(pad)
2198	}
2199	leftBuilder.WriteString(th.FG256(th.Muted, left))
2200	if middle != "" {
2201		leftBuilder.WriteString(pad)
2202		// `middle` already has colorized context segments; wrap the rest in muted.
2203		leftBuilder.WriteString(th.FG256(th.Muted, middle))
2204	}
2205
2206	cwd := shortenHome(p.CWD)
2207	tags := ""
2208	if p.NoYolo {
2209		tags += "yolo mode disabled "
2210	}
2211	if p.Locked {
2212		tags += "jailed "
2213	}
2214	if p.Telegram {
2215		tags += "telegram connected "
2216	}
2217	if tags != "" && cwd != "" {
2218		cwd = tags + "- " + cwd
2219	}
2220
2221	primary := leftBuilder.String()
2222
2223	// On narrow terminals the single line wraps badly. If the visible
2224	// width exceeds cols and we have a busy prefix, split: keep the
2225	// busy prefix on line 1, then put model and (if still needed)
2226	// stats on their own rows. This mirrors the idle split below.
2227	if p.Cols > 0 && p.BusyPrefix != "" && visibleWidth(primary) > p.Cols {
2228		busyLine := pad + p.BusyPrefix
2229		modelLine := pad + th.FG256(th.Muted, left)
2230		lines := []string{busyLine}
2231		if middle != "" && visibleWidth(modelLine+pad+th.FG256(th.Muted, middle)) > p.Cols {
2232			lines = appendWrappedStatusLines(lines, th, pad, left, thinkingText, statsText, p.Cols)
2233		} else {
2234			var infoBuilder strings.Builder
2235			infoBuilder.WriteString(modelLine)
2236			if middle != "" {
2237				infoBuilder.WriteString(pad)
2238				infoBuilder.WriteString(th.FG256(th.Muted, middle))
2239			}
2240			lines = append(lines, infoBuilder.String())
2241		}
2242		if cwd != "" {
2243			lines = append(lines, pad+th.FG256(th.Muted, cwd))
2244		}
2245		return lines
2246	}
2247
2248	// Idle narrow split: keep provider/model on the first status line,
2249	// move usage/cost/context stats to the next, then cwd below. This
2250	// avoids the terminal's hard wrap cutting the stats or pushing cwd
2251	// into an awkward position on small widths.
2252	if p.Cols > 0 && p.BusyPrefix == "" && middle != "" && visibleWidth(primary) > p.Cols {
2253		var lines []string
2254		lines = appendWrappedStatusLines(lines, th, pad, left, thinkingText, statsText, p.Cols)
2255		if cwd != "" {
2256			lines = append(lines, pad+th.FG256(th.Muted, cwd))
2257		}
2258		return lines
2259	}
2260
2261	if cwd == "" {
2262		return []string{primary}
2263	}
2264
2265	// Second line: indent with the same 2-space pad so the cwd lines
2266	// up under the "(provider)" column on line 1.
2267	cwdRendered := pad + th.FG256(th.Muted, cwd)
2268	return []string{primary, cwdRendered}
2269}
2270
2271func appendWrappedStatusLines(lines []string, th Theme, pad, modelText, thinkingText, statsText string, cols int) []string {
2272	modelLine := pad + th.FG256(th.Muted, modelText)
2273	if thinkingText == "" {
2274		lines = append(lines, modelLine)
2275		if statsText != "" {
2276			lines = append(lines, pad+th.FG256(th.Muted, statsText))
2277		}
2278		return lines
2279	}
2280
2281	modelThinkingPlain := pad + modelText + pad + thinkingText
2282	if cols <= 0 || visibleWidth(modelThinkingPlain) <= cols {
2283		lines = append(lines, pad+th.FG256(th.Muted, modelText+pad+thinkingText))
2284	} else {
2285		lines = append(lines, modelLine)
2286		lines = append(lines, pad+th.FG256(th.Muted, thinkingText))
2287	}
2288	if statsText != "" {
2289		lines = append(lines, pad+th.FG256(th.Muted, statsText))
2290	}
2291	return lines
2292}
2293
2294func thinkingLevelLabel(level string) string {
2295	switch strings.ToLower(strings.TrimSpace(level)) {
2296	case "", "off", "none", "no", "false", "disabled":
2297		return ""
2298	case "minimum", "minimal", "min":
2299		return "minimal"
2300	case "maximum", "max", "xhigh":
2301		return "maximum"
2302	default:
2303		return strings.ToLower(strings.TrimSpace(level))
2304	}
2305}
2306
2307// contextUsage renders the "N%/ctxMax" fragment, returning the
2308// rendered string plus the colour to wrap it in.
2309func contextUsage(th Theme, used, max int) (string, int) {
2310	if max <= 0 {
2311		if used <= 0 {
2312			return "", th.Muted
2313		}
2314		return formatTokens(used), th.Muted
2315	}
2316	pct := float64(used) / float64(max) * 100
2317	text := fmt.Sprintf("%.1f%%/%s", pct, formatTokens(max))
2318	switch {
2319	case pct > 90:
2320		return text, th.Error
2321	case pct > 70:
2322		return text, th.Warning
2323	}
2324	return text, th.Muted
2325}
2326
2327// formatTokens footer formatter:
2328//
2329//	< 1000      -> "42"
2330//	< 10_000    -> "2.7k"
2331//	< 1_000_000 -> "35k"
2332//	< 10M       -> "1.1M"
2333//	else        -> "12M"
2334func formatTokens(n int) string {
2335	switch {
2336	case n < 0:
2337		return "0"
2338	case n < 1000:
2339		return fmt.Sprintf("%d", n)
2340	case n < 10000:
2341		return fmt.Sprintf("%.1fk", float64(n)/1000)
2342	case n < 1_000_000:
2343		return fmt.Sprintf("%dk", (n+500)/1000)
2344	case n < 10_000_000:
2345		return fmt.Sprintf("%.1fM", float64(n)/1_000_000)
2346	default:
2347		return fmt.Sprintf("%dM", (n+500_000)/1_000_000)
2348	}
2349}
2350
2351// shortenHome replaces the user's $HOME prefix with "~" for readability.
2352func shortenHome(p string) string {
2353	if p == "" {
2354		return ""
2355	}
2356	home := osUserHome()
2357	if home == "" {
2358		return p
2359	}
2360	if p == home {
2361		return "~"
2362	}
2363	if strings.HasPrefix(p, home+"/") {
2364		return "~" + p[len(home):]
2365	}
2366	return p
2367}
2368
2369// osUserHome is a tiny wrapper around os.UserHomeDir so tests can mock it.
2370var osUserHome = func() string {
2371	if h, err := osUserHomeDir(); err == nil {
2372		return h
2373	}
2374	return ""
2375}

Keyboard shortcuts

Single-key shortcuts are on. ctrl k and esc work whatever this says.

ctrl k :
go to a section, branch, tag, file or repository
?
this list
j k
move the row cursor down / up
enter
open the row under the cursor; on Files, a directory opens or closes in place
↑ ↓ ← → home end
in the file tree (focus on a row): previous / next row, close / open a directory or go to its parent / first entry, first / last row. They never open a file
l h
on Files: open a directory or a file / close a directory or go up to its parent, then to the parent page. Elsewhere: into the side panel (on a merge request, its files) / back to the content; there j k move between its controls
g g G
first / last row
/
filter the list; on Files, find a file anywhere in the repository (esc clears, enter opens the best match)
b
switch branch or tag
g s g f g c g b g m g i g r g a
tabs: summary, files, commits, branches & tags, merge requests, issues, releases, actions (when available)
g h
home
w
wide mode: use the whole width of the screen, or not (remembered)
y
copy a permalink pinned to the commit
d u x
diff: split / unified / collapse or expand all
e E
diff: the whole file in view / every file, with the lines the hunks hide
n
merge request: next note in the diff
esc
close a dialog, leave a field

Branches 1

Tags 476

↑↓ moveenter openesc close