v0.3.93 0192a2e

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

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