v0.3.65 9ef467d

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

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