v0.2.99 4d92b3d

view.go RawHistoryFolder

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

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