v0.3.3 2d8ec25

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
805// RenderToolCall renders one live or completed tool call using the same
806// presentation as tool calls in the main transcript. Dialogs with isolated
807// agent loops use this to avoid maintaining a second tool renderer.
808func (v *View) RenderToolCall(tc ToolCallView, width int) []string {
809	if v.liveBodyHigh == nil {
810		v.liveBodyHigh = make(map[string]int)
811	}
812	return v.renderToolCall(tc, width)
813}
814
815func (v *View) renderToolCall(tc ToolCallView, width int) []string {
816	var lines []string
817
818	// Header label. While the call is still streaming, prefer the
819	// live path extracted from the partial args so the user sees
820	// the target file as soon as it's known, even before the full
821	// JSON arrived.
822	arg := tc.Args
823	if arg == "" && tc.LivePath != "" {
824		arg = tc.LivePath
825	}
826	label := tc.Name + " " + arg
827
828	// No leading blank: Build()'s inter-message separator already
829	// places one blank row between the previous transcript content
830	// and the live overlay, matching the spacing the same call has
831	// once it finalises into a transcript box. Adding another blank
832	// here would double the gap during streaming and visibly tighten
833	// when the overlay disappears.
834
835	// Live body (write/edit): keep the streamed preview visible until
836	// a proposed or real tool result arrives. The provider can finish the
837	// tool_use JSON before zot has executed the tool, so keying this on
838	// tc.Streaming makes write/edit boxes collapse for a moment between
839	// EvToolUseEnd and confirmation or EvToolResult.
840	if tc.Preview == "" && tc.Result == "" {
841		if body := v.renderLiveToolBody(tc, width); len(body) > 0 {
842			// Pad the live preview up to the call's high-water height so
843			// it never shrinks mid-stream (e.g. between edit 1 and the
844			// start of edit 2). Padding sits inside the box as real
845			// box-side rows so the surrounding layout stays put. The
846			// high-water mark is per call id and is dropped the moment a
847			// Result lands (this branch only runs while Result == "").
848			high := len(body)
849			if v.liveBodyHigh != nil {
850				if prev := v.liveBodyHigh[tc.ID]; prev > high {
851					high = prev
852				}
853				v.liveBodyHigh[tc.ID] = high
854			}
855			if v.FlatTools || v.CompactMode {
856				for len(body) < high {
857					body = append(body, "")
858				}
859				if v.CompactMode {
860					lines = append(lines, compactToolBlank(v.Theme, width))
861				}
862				lines = append(lines, toolHeaderLine(v.Theme, label, width, v.CompactMode))
863				lines = append(lines, body...)
864				if v.CompactMode {
865					lines = append(lines, compactToolBlank(v.Theme, width))
866				}
867				return lines
868			}
869			for len(body) < high {
870				body = append(body, toolBoxSide(v.Theme, "", width))
871			}
872			lines = append(lines, toolBoxTop(v.Theme, label, width))
873			lines = append(lines, toolBoxSide(v.Theme, "", width))
874			lines = append(lines, body...)
875			lines = append(lines, toolBoxSide(v.Theme, "", width))
876			lines = append(lines, toolBoxBottom(v.Theme, width))
877			return lines
878		}
879	}
880
881	bodyText := tc.Result
882	if bodyText == "" {
883		bodyText = tc.Preview
884	}
885
886	// Finished tool call with no body: just the labelled top edge
887	// directly closed by the bottom. Avoids a blank interior row
888	// for no-output tools.
889	if bodyText == "" {
890		if v.FlatTools || v.CompactMode {
891			if v.CompactMode {
892				lines = append(lines, compactToolBlank(v.Theme, width))
893			}
894			lines = append(lines, toolHeaderLine(v.Theme, label, width, v.CompactMode))
895			if v.CompactMode {
896				lines = append(lines, compactToolBlank(v.Theme, width))
897			}
898			return lines
899		}
900		lines = append(lines, toolBoxTop(v.Theme, label, width))
901		lines = append(lines, toolBoxBottom(v.Theme, width))
902		return lines
903	}
904
905	// Finished tool call with a result body. Top edge embeds the
906	// label; body lines go through toolBoxSide so each row gets
907	// vertical edges; bottom edge closes the box. Blank interior
908	// rows after the top and before the bottom give the body a bit
909	// of breathing room from the corners.
910	color := v.Theme.ToolOut
911	if tc.Error {
912		color = v.Theme.Error
913	}
914	if v.FlatTools || v.CompactMode {
915		if v.CompactMode {
916			lines = append(lines, compactToolBlank(v.Theme, width))
917		}
918		lines = append(lines, toolHeaderLine(v.Theme, label, width, v.CompactMode))
919		body := v.renderLiveToolResult(bodyText, flatToolBodyRenderWidth(width), color, tc.LivePath)
920		for _, l := range v.collapseToolBody(body, false) {
921			_, stripped := parseImageFootprint(l)
922			lines = append(lines, toolBodyLine(v.Theme, stripped, width, v.CompactMode))
923		}
924		if v.CompactMode {
925			lines = append(lines, compactToolBlank(v.Theme, width))
926		}
927		return lines
928	}
929	lines = append(lines, toolBoxTop(v.Theme, label, width))
930	lines = append(lines, toolBoxSide(v.Theme, "", width))
931	body := v.renderLiveToolResult(bodyText, toolBoxBodyRenderWidth(width), color, tc.LivePath)
932	for _, l := range v.collapseToolBody(body, false) {
933		imgCells, stripped := parseImageFootprint(l)
934		if hasImageEscapeLine(stripped) {
935			lines = append(lines, toolBoxSideWithImage(v.Theme, stripped, imgCells, width))
936			continue
937		}
938		lines = append(lines, toolBoxSide(v.Theme, stripped, width))
939	}
940	lines = append(lines, toolBoxSide(v.Theme, "", width))
941	lines = append(lines, toolBoxBottom(v.Theme, width))
942	return lines
943}
944
945// renderLiveToolResult uses the transcript's text renderer so every rich
946// confirmation preview immediately gets the same colors, numbered gutters,
947// and syntax highlighting as its final tool result.
948func (v *View) renderLiveToolResult(text string, width, color int, sourcePath string) []string {
949	return v.renderToolText(text, width, color, sourcePath, 1)
950}
951
952// renderLiveToolBody renders the in-flight preview of a streaming
953// tool call. Supported tools:
954//
955//   - write: shows the partial `content` field, syntax-highlighted
956//     by the target path's language.
957//   - edit:  shows the partial `newText` of the edit currently being
958//     streamed, prefixed with a "editing foo.ts (edit 2)" header so
959//     the user can see which of a multi-edit batch is in progress.
960//   - bash:  shows the full command as soon as the JSON args are known,
961//     before stdout/stderr has arrived, so long-running commands are legible.
962//
963// Anything else returns nil and only the tool-call header shows.
964func (v *View) renderLiveToolBody(tc ToolCallView, width int) []string {
965	switch tc.Name {
966	case "write", "Write":
967		partial, ok, _ := ExtractPartialStringField(tc.RawJSONBuf, "content")
968		if !ok || partial == "" {
969			return nil
970		}
971		return v.wrapLiveBody(v.renderRawFile(partial, tc.LivePath, 1), width)
972	case "edit", "Edit":
973		partial, ok, _, idx := ExtractLastNewText(tc.RawJSONBuf)
974		if !ok || partial == "" {
975			return nil
976		}
977		// Header line hints which edit is streaming and, when more
978		// than one has landed, how many the model is doing.
979		hint := fmt.Sprintf("edit %d (streaming)", idx)
980		body := []string{"    " + v.Theme.FG256(v.Theme.Muted, hint), ""}
981		body = append(body, v.renderRawFile(partial, tc.LivePath, 1)...)
982		return v.wrapLiveBody(body, width)
983	case "bash", "Bash":
984		command, ok, _ := ExtractPartialStringField(tc.RawJSONBuf, "command")
985		if !ok || strings.TrimSpace(command) == "" {
986			return nil
987		}
988		return v.wrapLiveBody(v.renderLiveBashCommand(command, width), width)
989	}
990	return nil
991}
992
993func (v *View) renderLiveBashCommand(command string, width int) []string {
994	inner := toolBoxBodyRenderWidth(width)
995	if v.FlatTools || v.CompactMode {
996		inner = flatToolBodyRenderWidth(width)
997	}
998	prompt := v.Theme.FG256(v.Theme.Muted, "$ ")
999	var out []string
1000	for i, line := range strings.Split(command, "\n") {
1001		firstPrefix := "    "
1002		if i == 0 {
1003			firstPrefix += prompt
1004		} else {
1005			firstPrefix += "  "
1006		}
1007		contPrefix := "      "
1008		wrapWidth := inner - visibleWidth(firstPrefix)
1009		if wrapWidth < 10 {
1010			wrapWidth = 10
1011		}
1012		for j, wrapped := range wrapANSILine(v.Theme.FG256(v.Theme.ToolOut, line), wrapWidth) {
1013			prefix := firstPrefix
1014			if j > 0 {
1015				prefix = contPrefix
1016			}
1017			out = append(out, prefix+wrapped)
1018		}
1019	}
1020	return out
1021}
1022
1023// wrapLiveBody returns the streaming body content as a list of
1024// box-side rows: each line wrapped in │ ... │ with right padding so
1025// the closing edge sits at column width-1. The caller (renderToolCall)
1026// supplies the surrounding top/bottom edges so the live overlay
1027// renders as a closed box matching the finalised transcript form.
1028func (v *View) wrapLiveBody(body []string, width int) []string {
1029	body = v.collapseToolBody(body, false)
1030	out := make([]string, 0, len(body))
1031	if v.FlatTools || v.CompactMode {
1032		for _, l := range body {
1033			_, stripped := parseImageFootprint(l)
1034			out = append(out, toolBodyLine(v.Theme, stripped, width, v.CompactMode))
1035		}
1036		return out
1037	}
1038	for _, l := range body {
1039		imgCells, stripped := parseImageFootprint(l)
1040		if hasImageEscapeLine(stripped) {
1041			out = append(out, toolBoxSideWithImage(v.Theme, stripped, imgCells, width))
1042			continue
1043		}
1044		out = append(out, toolBoxSide(v.Theme, stripped, width))
1045	}
1046	return out
1047}
1048
1049// toolResultBlock wraps text in thin horizontal rules (top + bottom),
1050// indenting the body with four spaces. The rules span the content column.
1051// toolBlockRule renders the muted horizontal separator drawn
1052// above and below a tool call block. Spans the full content
1053// width so it reads as a real section break in the chat
1054// regardless of terminal size.
1055func toolBlockRule(th Theme, width int) string {
1056	w := width
1057	if w < 8 {
1058		w = 8
1059	}
1060	return th.FG256(th.Muted, strings.Repeat("─", w))
1061}
1062
1063// toolBoxInnerPad is the number of blank cells kept between a box
1064// edge (┌, │, └) and the content inside it. One cell of breathing
1065// room makes the label read as part of the box rather than fused to
1066// the corner, and gives body lines a tiny gutter from the left side.
1067const toolBoxInnerPad = 1
1068
1069// toolBoxOuterMargin is the number of blank cells kept to the left of
1070// the opening corner and to the right of the closing corner. Aligns
1071// the box's frame with the column where user-bubble text begins, so
1072// the conversation reads as one column instead of having tool boxes
1073// running edge-to-edge while user/assistant rows sit indented.
1074const toolBoxOuterMargin = 2
1075
1076// toolBoxTop renders the labelled top edge of a tool block:
1077//
1078//	┌─  bash xcrun simctl list devices ─────────────────────────────┐
1079//
1080// The label is the tool name + short args (the same string previously
1081// shown on its own row beneath the rule). Padding fills the remainder
1082// of the line so the right corner sits at column width-1, matching the
1083// closing edge.
1084func toolBoxTop(th Theme, label string, width int) string {
1085	label = oneLineToolLabel(label)
1086	w := width - 2*toolBoxOuterMargin
1087	if w < 12 {
1088		w = 12
1089	}
1090	margin := strings.Repeat(" ", toolBoxOuterMargin)
1091	innerPad := strings.Repeat(" ", toolBoxInnerPad)
1092	// "┌─" + innerPad + " " + label + " " + innerPad = used; pad
1093	// with ─ to width-1, then "┐".
1094	prefix := "┌─" + innerPad + " "
1095	suffix := " " + innerPad
1096	used := visibleWidth(prefix) + visibleWidth(label) + visibleWidth(suffix)
1097	fill := w - used - 1 // -1 for the closing corner
1098	if fill < 0 {
1099		// Label overflows; truncate with an ellipsis so the right
1100		// corner still lands on the right edge. Rare on real
1101		// terminals (the chat column is usually wide enough).
1102		over := -fill
1103		runes := []rune(label)
1104		if over+3 < len(runes) {
1105			label = string(runes[:len(runes)-over-3]) + "..."
1106		} else {
1107			label = "..."
1108		}
1109		used = visibleWidth(prefix) + visibleWidth(label) + visibleWidth(suffix)
1110		fill = w - used - 1
1111		if fill < 0 {
1112			fill = 0
1113		}
1114	}
1115	fillStr := strings.Repeat("─", fill)
1116	name, rest := splitToolLabel(label)
1117	return margin + th.FG256(th.Muted, prefix) + th.FG256(th.FG, name) + th.FG256(th.Muted, rest+suffix+fillStr+"┐") + margin
1118}
1119
1120func oneLineToolLabel(label string) string {
1121	return strings.Join(strings.Fields(label), " ")
1122}
1123
1124func splitToolLabel(label string) (name, rest string) {
1125	label = strings.TrimLeft(label, " ")
1126	if label == "" {
1127		return "", ""
1128	}
1129	idx := strings.IndexAny(label, " \t")
1130	if idx < 0 {
1131		return label, ""
1132	}
1133	return label[:idx], label[idx:]
1134}
1135
1136// flatToolHeader renders the boxless header line for a tool call:
1137//
1138//	▌ bash xcrun simctl list devices
1139//
1140// It carries the same information as toolBoxTop (tool name + short
1141// args) but drops the frame: a single accent gutter glyph, the tool
1142// name in the foreground color, and the argument summary muted. The
1143// line is left-aligned at the same column the box's opening corner
1144// used (toolBoxOuterMargin) so flat and box renders share a column.
1145func toolHeaderLine(th Theme, label string, width int, compact bool) string {
1146	if compact {
1147		return compactToolHeader(th, label, width)
1148	}
1149	return flatToolHeader(th, label, width)
1150}
1151
1152func flatToolHeader(th Theme, label string, width int) string {
1153	label = oneLineToolLabel(label)
1154	name, rest := splitToolLabel(label)
1155	margin := strings.Repeat(" ", toolBoxOuterMargin)
1156	gutter := th.FG256(th.Assistant, "▌") + " "
1157	// Budget the visible text to the content width so a very long
1158	// argument summary doesn't run off the right edge; truncate with
1159	// an ellipsis like the box header does.
1160	avail := width - toolBoxOuterMargin - visibleWidth("▌ ")
1161	if avail < 12 {
1162		avail = 12
1163	}
1164	if visibleWidth(name+rest) > avail {
1165		over := visibleWidth(name+rest) - avail
1166		runes := []rune(rest)
1167		if over+3 < len(runes) {
1168			rest = string(runes[:len(runes)-over-3]) + "..."
1169		} else if visibleWidth(name) <= avail {
1170			rest = ""
1171		}
1172	}
1173	return margin + gutter + th.FG256(th.FG, name) + th.FG256(th.Muted, rest)
1174}
1175
1176func compactToolBlank(th Theme, width int) string {
1177	if width < 1 {
1178		width = 1
1179	}
1180	return sgrBGColor(th.UserBubbleBG) + strings.Repeat(" ", width) + reset
1181}
1182
1183func compactToolHeader(th Theme, label string, width int) string {
1184	label = oneLineToolLabel(label)
1185	name, rest := splitToolLabel(label)
1186	pad := "  "
1187	avail := width - visibleWidth(pad)*2
1188	if avail < 12 {
1189		avail = 12
1190	}
1191	if visibleWidth(name+rest) > avail {
1192		over := visibleWidth(name+rest) - avail
1193		runes := []rune(rest)
1194		if over+3 < len(runes) {
1195			rest = string(runes[:len(runes)-over-3]) + "..."
1196		} else if visibleWidth(name) <= avail {
1197			rest = ""
1198		}
1199	}
1200	plain := pad + name + rest
1201	visible := visibleWidth(plain)
1202	fill := ""
1203	if visible < width {
1204		fill = strings.Repeat(" ", width-visible)
1205	}
1206	bg := sgrBGColor(th.UserBubbleBG)
1207	return bg + pad + sgrFG(th.FG) + name + bg + sgrFG(th.Muted) + rest + bg + fill + reset
1208}
1209
1210func toolBodyLine(th Theme, line string, width int, compact bool) string {
1211	line = flatToolBody(th, line)
1212	if compact {
1213		return compactToolBody(th, line, width)
1214	}
1215	return line
1216}
1217
1218// flatToolBody indents a single body line for boxless rendering. It
1219// trims the same leading padding box bodies do, then prepends a fixed
1220// gutter indent so output sits in a readable column under the header
1221// without any vertical frame. ANSI styling in the line is preserved.
1222func flatToolBody(th Theme, line string) string {
1223	_ = th
1224	line = trimLeadingSpaces(line, toolBoxBodyTrimLeft)
1225	return strings.Repeat(" ", toolBoxOuterMargin+2) + line
1226}
1227
1228func compactToolBody(th Theme, line string, width int) string {
1229	visible := visibleWidth(line)
1230	fill := ""
1231	if visible < width {
1232		fill = strings.Repeat(" ", width-visible)
1233	}
1234	bg := sgrBGColor(th.UserBubbleBG)
1235	return bg + strings.ReplaceAll(line, reset, reset+bg) + bg + fill + reset
1236}
1237
1238// toolBoxBottom renders the bottom edge of a tool block:
1239//
1240//	└─────────────────────────────────────────────────────────────────────────────┘
1241//
1242// Spans the same width as toolBoxTop so the corners line up.
1243func toolBoxBottom(th Theme, width int) string {
1244	w := width - 2*toolBoxOuterMargin
1245	if w < 12 {
1246		w = 12
1247	}
1248	margin := strings.Repeat(" ", toolBoxOuterMargin)
1249	line := "└" + strings.Repeat("─", w-2) + "┘"
1250	return margin + th.FG256(th.Muted, line) + margin
1251}
1252
1253// hasImageEscapeLine reports whether s contains a Kitty (\x1b_G) or
1254// iTerm2 (\x1b]1337;File=) inline-image escape. Such rows draw into
1255// the terminal's graphics layer and shouldn't be wrapped with text
1256// box edges.
1257func hasImageEscapeLine(s string) bool {
1258	return strings.Contains(s, "\x1b]1337;File=") || strings.Contains(s, "\x1b_G")
1259}
1260
1261// imageFootprintSentinel marks rows that belong to an inline-image's
1262// reserved footprint — the escape row plus the blank rows below it
1263// plus the gap row before the metadata caption. Any consumer that
1264// wraps content in box edges (│ ... │) detects the sentinel, strips
1265// it, and emits the row — the image graphics rectangle paints over
1266// whatever was drawn there. Uses a non-printing C0 control byte so
1267// it can never appear in normal text or in an ANSI escape sequence
1268// body.
1269//
1270// The escape row carries an extra width hint between two sentinels:
1271// "\x1e<cells>\x1e<spaces+escape>". Wrappers parse the cells count
1272// to know how wide the image is in terminal cells and how many cells
1273// of trailing padding are needed before the closing box edge.
1274const imageFootprintSentinel = "\x1e"
1275
1276// parseImageFootprint splits a footprint-tagged row into (cellsWide,
1277// rest). cellsWide is 0 when the row carries no width hint (the
1278// reservation blanks and gap row don't, only the escape row does).
1279func parseImageFootprint(s string) (int, string) {
1280	if !strings.HasPrefix(s, imageFootprintSentinel) {
1281		return 0, s
1282	}
1283	rest := s[len(imageFootprintSentinel):]
1284	end := strings.Index(rest, imageFootprintSentinel)
1285	if end < 0 {
1286		return 0, rest
1287	}
1288	w, err := strconv.Atoi(rest[:end])
1289	if err != nil {
1290		return 0, rest
1291	}
1292	return w, rest[end+len(imageFootprintSentinel):]
1293}
1294
1295// toolBoxBodyTrimLeft is the number of leading literal spaces stripped
1296// from each body line as it enters toolBoxSide. Body renderers
1297// (renderToolText, renderRawFile, the diff/bash helpers, ...) all
1298// emit a 4-cell indent so the content aligns with the assistant body
1299// column when there's no box around it. Inside a box the box edge +
1300// inner pad already supply most of that gutter, so we drop a couple
1301// of cells from the body's own indent to keep the content from
1302// drifting too far right.
1303const toolBoxBodyTrimLeft = 2
1304
1305// toolBoxBodyRenderWidth is the width body renderers should target before
1306// their rows are wrapped by toolBoxSide. Most body renderers emit a four-cell
1307// indent; toolBoxSide trims toolBoxBodyTrimLeft cells from that indent and
1308// then adds the box edge/padding. Passing the full terminal width lets long
1309// bash/heredoc lines overrun the inner box and makes terminals soft-wrap,
1310// visually breaking the right edge. This returns the maximum renderer width
1311// whose post-trim visible width fits inside the box.
1312func toolBoxBodyRenderWidth(width int) int {
1313	w := width - 2*toolBoxOuterMargin
1314	if w < 12 {
1315		w = 12
1316	}
1317	inner := w - 2 - 2*toolBoxInnerPad
1318	if inner < 1 {
1319		inner = 1
1320	}
1321	return inner + toolBoxBodyTrimLeft
1322}
1323
1324// flatToolBodyRenderWidth is the width body renderers should target in
1325// flat mode. There's no box frame, just the flatToolBody indent
1326// (toolBoxOuterMargin+2 cells), so the renderable width is the
1327// terminal width minus that indent. Renderers emit a 4-cell indent of
1328// their own which flatToolBody trims toolBoxBodyTrimLeft cells from,
1329// so add that back like toolBoxBodyRenderWidth does.
1330func flatToolBodyRenderWidth(width int) int {
1331	inner := width - (toolBoxOuterMargin + 2)
1332	if inner < 1 {
1333		inner = 1
1334	}
1335	return inner + toolBoxBodyTrimLeft
1336}
1337
1338// toolBoxSide wraps a single body line with vertical box edges:
1339//
1340//	│  foo bar baz                                            │
1341//
1342// The middle preserves the line verbatim (including any ANSI escapes)
1343// after stripping toolBoxBodyTrimLeft leading literal spaces. One cell
1344// of inner padding sits on each side so the content breathes from the
1345// edges; the right padding fills to column width-1.
1346func toolBoxSide(th Theme, line string, width int) string {
1347	w := width - 2*toolBoxOuterMargin
1348	if w < 12 {
1349		w = 12
1350	}
1351	margin := strings.Repeat(" ", toolBoxOuterMargin)
1352	left := th.FG256(th.Muted, "│") + strings.Repeat(" ", toolBoxInnerPad)
1353	right := strings.Repeat(" ", toolBoxInnerPad) + th.FG256(th.Muted, "│")
1354	inner := w - 2 - 2*toolBoxInnerPad // available between the two pads
1355	line = trimLeadingSpaces(line, toolBoxBodyTrimLeft)
1356
1357	cur := visibleWidth(line)
1358	if cur > inner {
1359		// Last-resort truncation must retain syntax foreground escapes.
1360		// Stripping ANSI here made long read results switch from their
1361		// configured syntax color to the terminal's default foreground
1362		// whenever the window became narrow enough to clip a line.
1363		line = truncateToWidth(line, inner)
1364		cur = visibleWidth(line)
1365	}
1366	pad := inner - cur
1367	if pad < 0 {
1368		pad = 0
1369	}
1370	return margin + left + line + strings.Repeat(" ", pad) + right + margin
1371}
1372
1373// toolBoxSideWithImage wraps a row that carries an inline-image
1374// escape sequence. The image protocols are configured to not move
1375// the cursor after rendering (iTerm: doNotMoveCursor=1, kitty/
1376// ghostty: C=1), so the only visible cell advance on the row is
1377// from the leading indent spaces before the escape. We pad from
1378// there to the right edge column and draw the closing │ there.
1379// imgCells is unused (kept in the signature for compatibility with
1380// the parseImageFootprint width hint).
1381func toolBoxSideWithImage(th Theme, line string, imgCells, width int) string {
1382	_ = imgCells
1383	w := width - 2*toolBoxOuterMargin
1384	if w < 12 {
1385		w = 12
1386	}
1387	margin := strings.Repeat(" ", toolBoxOuterMargin)
1388	left := th.FG256(th.Muted, "│") + strings.Repeat(" ", toolBoxInnerPad)
1389	right := strings.Repeat(" ", toolBoxInnerPad) + th.FG256(th.Muted, "│")
1390	inner := w - 2 - 2*toolBoxInnerPad
1391
1392	line = trimLeadingSpaces(line, toolBoxBodyTrimLeft)
1393
1394	// Count leading spaces (visible cells consumed before the escape).
1395	leading := 0
1396	for leading < len(line) && line[leading] == ' ' {
1397		leading++
1398	}
1399
1400	pad := inner - leading
1401	if pad < 0 {
1402		pad = 0
1403	}
1404	return margin + left + line + strings.Repeat(" ", pad) + right + margin
1405}
1406
1407// trimLeadingSpaces removes up to n literal space characters from the
1408// start of s without touching anything else. ANSI CSI escapes that
1409// appear before the spaces are skipped over (so a coloured indent
1410// like "\x1b[2m    text" still loses its first n cells of indent).
1411// Stops as soon as it hits a non-space character.
1412func trimLeadingSpaces(s string, n int) string {
1413	if n <= 0 || s == "" {
1414		return s
1415	}
1416	var b strings.Builder
1417	b.Grow(len(s))
1418	trimmed := 0
1419	i := 0
1420	for i < len(s) {
1421		// Pass through any ANSI escape sequence verbatim.
1422		if s[i] == 0x1b && i+1 < len(s) && s[i+1] == '[' {
1423			end := i + 2
1424			for end < len(s) {
1425				c := s[end]
1426				end++
1427				if c >= 0x40 && c <= 0x7e {
1428					break
1429				}
1430			}
1431			b.WriteString(s[i:end])
1432			i = end
1433			continue
1434		}
1435		if trimmed < n && s[i] == ' ' {
1436			trimmed++
1437			i++
1438			continue
1439		}
1440		b.WriteString(s[i:])
1441		return b.String()
1442	}
1443	return b.String()
1444}
1445
1446// renderToolResultContent renders the body of a tool result block.
1447// Text blocks get the usual rules-wrapped treatment; text that looks
1448// like a unified diff gets +/- coloring. Image blocks are rendered
1449// inline when the terminal supports a protocol, else as a text
1450// placeholder with dimensions.
1451func (v *View) renderToolResultContent(blocks []provider.Content, width, color int, sourcePath string, startLine int) []string {
1452	var body []string
1453	hasImage := false
1454	for _, b := range blocks {
1455		switch bb := b.(type) {
1456		case provider.TextBlock:
1457			bodyWidth := toolBoxBodyRenderWidth(width)
1458			if v.FlatTools || v.CompactMode {
1459				bodyWidth = flatToolBodyRenderWidth(width)
1460			}
1461			body = append(body, v.renderToolText(bb.Text, bodyWidth, color, sourcePath, startLine)...)
1462		case provider.ImageBlock:
1463			hasImage = true
1464			body = append(body, v.renderImageBlock(bb, width)...)
1465		}
1466	}
1467	return v.collapseToolBody(body, hasImage)
1468}
1469
1470// collapseToolBody trims lines to the configured preview size when the
1471// view is not in ExpandAll mode, appending a muted "... ctrl+o to
1472// expand" footer. Image blocks never collapse — they're short in text
1473// rows but represent real content the user wants to see.
1474func (v *View) collapseToolBody(lines []string, hasImage bool) []string {
1475	if v.ExpandAll || hasImage {
1476		return lines
1477	}
1478	if len(lines) <= ToolCollapseLines {
1479		return lines
1480	}
1481	kept := lines[:ToolCollapsePreview]
1482	hidden := len(lines) - ToolCollapsePreview
1483	total := len(lines)
1484	footer := fmt.Sprintf("    ... (%d more lines, %d total, ctrl+o to expand)", hidden, total)
1485	footer = v.Theme.FG256(v.Theme.Muted, footer)
1486	out := append([]string(nil), kept...)
1487	out = append(out, "")
1488	return append(out, footer)
1489}
1490
1491// renderToolText renders a text block inside a tool result. If the
1492// text contains a unified-diff section (lines starting with "--- " /
1493// "+++ " / "+" / "-"/" "), those rows are styled with add/remove
1494// colors matching git diff conventions.
1495func (v *View) renderToolText(text string, width, defaultColor int, sourcePath string, startLine int) []string {
1496	// Legacy path: transcripts saved before we dropped line numbers
1497	// from the read tool still carry "     1\t..." prefixes. Detect and
1498	// strip them, then fall through to the highlighter.
1499	if looksLikeNumberedFile(text) {
1500		return v.renderNumberedFile(text, sourcePath)
1501	}
1502	// If the result embeds a unified diff (the edit tool's output
1503	// starts with a short "applied N edit(s)" line and then a
1504	// standard --- / +++ / +/- patch), render the patch with
1505	// add/remove coloring. This takes priority over the file-like
1506	// detector below because a diff technically has many lines of
1507	// "file content" but what the user cares about is what changed,
1508	// not a dump of the post-edit file.
1509	if looksLikeUnifiedDiff(text) {
1510		return v.renderUnifiedDiff(text, width, sourcePath)
1511	}
1512
1513	// Current path: text came from `read` as raw file bytes. When a
1514	// source path is known (the call had a `path` arg), render with
1515	// a synthetic line-number gutter starting at startLine so the
1516	// on-screen view still looks like cat -n. Doesn't apply to non-
1517	// file tool outputs (bash stdout, display notes, etc.).
1518	if sourcePath != "" && looksLikeFileContent(text) {
1519		return v.renderRawFile(text, sourcePath, startLine)
1520	}
1521
1522	// No truncation — the full tool output is rendered into chat and
1523	// becomes part of the scrollback you can page back through.
1524	lines := strings.Split(text, "\n")
1525
1526	// Bash-result styling: when the first row looks like a shell
1527	// prompt line ("$ ...") emitted by the bash tool, style the
1528	// prompt line in accent and the trailing "[exit N]  Took X.Ys"
1529	// line in muted type so the command + timing read at a glance.
1530	// Everything between is left on the default tool-output color.
1531	if len(lines) > 0 && strings.HasPrefix(lines[0], "$ ") {
1532		return v.renderBashResult(lines, width, defaultColor)
1533	}
1534
1535	inDiff := false
1536	oldLine, newLine := 1, 1
1537	var out []string
1538	for _, l := range lines {
1539		// Detect diff header: "--- name" followed somewhere by "+++ name".
1540		if strings.HasPrefix(l, "--- ") || strings.HasPrefix(l, "+++ ") {
1541			inDiff = true
1542			out = append(out, "    "+v.Theme.FG256(v.Theme.Muted, l))
1543			continue
1544		}
1545		// Hunk header "@@ -a,b +c,d @@" resets the counters so patches
1546		// that skip around in the file still get correct numbering.
1547		if inDiff && strings.HasPrefix(l, "@@") {
1548			if o, n, ok := parseHunkHeader(l); ok {
1549				oldLine, newLine = o, n
1550			}
1551			out = append(out, "    "+v.Theme.FG256(v.Theme.Muted, l))
1552			continue
1553		}
1554		if inDiff && strings.TrimSpace(l) == "..." {
1555			out = append(out, "")
1556			out = append(out, "    "+v.Theme.FG256(v.Theme.Muted, "..."))
1557			continue
1558		}
1559		if inDiff && len(l) > 0 {
1560			switch l[0] {
1561			case '+':
1562				out = append(out, v.renderDiffRow(l, width, v.Theme.Tool, newLine, '+', sourcePath)...)
1563				newLine++
1564				continue
1565			case '-':
1566				out = append(out, v.renderDiffRow(l, width, v.Theme.Error, oldLine, '-', sourcePath)...)
1567				oldLine++
1568				continue
1569			case ' ':
1570				out = append(out, v.renderDiffRow(l, width, v.Theme.Muted, newLine, ' ', sourcePath)...)
1571				oldLine++
1572				newLine++
1573				continue
1574			}
1575		}
1576		// Regular line.
1577		for _, w := range wrapLine(l, width-4, "    ") {
1578			out = append(out, "    "+v.Theme.FG256(defaultColor, w))
1579		}
1580	}
1581	return out
1582}
1583
1584// parseHunkHeader extracts the starting old/new line from a unified
1585// diff hunk header ("@@ -12,5 +12,7 @@ ..."). Returns ok=false if the
1586// header is malformed or missing numbers.
1587func parseHunkHeader(l string) (oldStart, newStart int, ok bool) {
1588	// Skip "@@ "
1589	rest := strings.TrimPrefix(l, "@@")
1590	rest = strings.TrimSpace(rest)
1591	if !strings.HasPrefix(rest, "-") {
1592		return 0, 0, false
1593	}
1594	rest = rest[1:]
1595	space := strings.IndexByte(rest, ' ')
1596	if space < 0 {
1597		return 0, 0, false
1598	}
1599	oldPart := rest[:space]
1600	rest = strings.TrimSpace(rest[space+1:])
1601	if !strings.HasPrefix(rest, "+") {
1602		return 0, 0, false
1603	}
1604	rest = rest[1:]
1605	if sp := strings.IndexAny(rest, " \t"); sp >= 0 {
1606		rest = rest[:sp]
1607	}
1608	parseStart := func(s string) (int, bool) {
1609		if c := strings.IndexByte(s, ','); c >= 0 {
1610			s = s[:c]
1611		}
1612		n, err := strconv.Atoi(s)
1613		if err != nil || n < 1 {
1614			return 0, false
1615		}
1616		return n, true
1617	}
1618	o, ok1 := parseStart(oldPart)
1619	n, ok2 := parseStart(rest)
1620	if !ok1 || !ok2 {
1621		return 0, 0, false
1622	}
1623	return o, n, true
1624}
1625
1626// renderDiffRow renders one unified-diff source line as one or more visual
1627// rows. The first row carries the read-style line-number gutter; continuation
1628// rows use a blank gutter so wrapped content cannot be mistaken for another
1629// source line. Code is syntax-highlighted if sourcePath hints at a known
1630// language and otherwise uses the diff color.
1631func (v *View) renderDiffRow(line string, width, color int, lineNo int, mark byte, sourcePath string) []string {
1632	if len(line) == 0 {
1633		return []string{""}
1634	}
1635	code := expandTabs(line[1:]) // strip the leading marker; expand tabs
1636
1637	// Gutter shape: sign + number share a color so they read as one
1638	// visual token ("+123") instead of a neutral line number next to
1639	// a stray marker. Unchanged context lines get a muted gutter and
1640	// a leading space so column alignment stays consistent with +/-
1641	// rows.
1642	var gutterText string
1643	switch mark {
1644	case '+':
1645		gutterText = fmt.Sprintf("+%3d ", lineNo)
1646	case '-':
1647		gutterText = fmt.Sprintf("-%3d ", lineNo)
1648	default:
1649		gutterText = fmt.Sprintf(" %3d ", lineNo)
1650	}
1651	gutterColor := color
1652	if mark == ' ' {
1653		gutterColor = v.Theme.Muted
1654	}
1655
1656	maxCode := width - visibleWidth("    "+gutterText)
1657	if maxCode < 1 {
1658		maxCode = 1
1659	}
1660	chunks := wrapCodeLine(code, maxCode)
1661	lang := LanguageFromPath(sourcePath)
1662	out := make([]string, 0, len(chunks))
1663	for i, chunk := range chunks {
1664		rowGutter := gutterText
1665		if i > 0 {
1666			rowGutter = strings.Repeat(" ", visibleWidth(gutterText))
1667		}
1668		codeRendered := ""
1669		if lang != "" {
1670			if h := v.Theme.HighlightCode(chunk, lang); len(h) == 1 {
1671				codeRendered = h[0]
1672			}
1673		}
1674		if codeRendered == "" {
1675			codeColor := color
1676			if mark == ' ' {
1677				codeColor = v.Theme.Muted
1678			}
1679			codeRendered = v.Theme.FG256(codeColor, chunk)
1680		}
1681		out = append(out, "    "+v.Theme.FG256(gutterColor, rowGutter)+codeRendered)
1682	}
1683	return out
1684}
1685
1686// wrapCodeLine splits code to a terminal cell width without dropping any
1687// characters. It prefers breaking after whitespace, then falls back to a hard
1688// rune boundary for long tokens. Keeping the whitespace on the preceding row
1689// means joining the returned chunks reconstructs the expanded source exactly.
1690func wrapCodeLine(line string, width int) []string {
1691	if width < 1 || visibleWidth(line) <= width {
1692		return []string{line}
1693	}
1694	runes := []rune(line)
1695	var out []string
1696	for start := 0; start < len(runes); {
1697		cells := 0
1698		end := start
1699		lastBreak := -1
1700		for end < len(runes) {
1701			runeWidth := runewidth.RuneWidth(runes[end])
1702			if cells+runeWidth > width && end > start {
1703				break
1704			}
1705			cells += runeWidth
1706			end++
1707			if runes[end-1] == ' ' || runes[end-1] == '\t' {
1708				lastBreak = end
1709			}
1710			if cells >= width {
1711				break
1712			}
1713		}
1714		if end == start { // A rune wider than the requested width.
1715			end++
1716		}
1717		if end < len(runes) && lastBreak > start {
1718			end = lastBreak
1719		}
1720		out = append(out, string(runes[start:end]))
1721		start = end
1722	}
1723	return out
1724}
1725
1726// renderImageBlock returns the lines for one image, inline if possible.
1727//
1728// Inline image escapes paint into multiple terminal rows but the zot
1729// renderer treats each slice entry as a single row. To prevent chat
1730// content from being drawn on top of the image, we pad with blank rows
1731// so the image's real footprint is reflected in the frame height.
1732func (v *View) renderImageBlock(b provider.ImageBlock, width int) []string {
1733	w, h := ImageDimensions(b.Data)
1734	kb := len(b.Data) / 1024
1735	// Four-space indent matches every other tool-output row
1736	// (renderRawFile, renderBashResult, diff rows, "... N more
1737	// lines" footers). Keeps the image's metadata line vertically
1738	// aligned with the file content above / below it.
1739	info := fmt.Sprintf("    image - %s - %dx%d - %d KB", b.MimeType, w, h, kb)
1740
1741	if v.ImageProto != ImageProtocolNone {
1742		// Clamp rendered width so the image never overflows the chat
1743		// column. Subtract a 4-cell indent for the tool result block,
1744		// cap at 60 cells, floor at 10.
1745		cells := width - 4
1746		if cells > 60 {
1747			cells = 60
1748		}
1749		if cells < 10 {
1750			cells = 10
1751		}
1752		const maxRows = 20
1753		if seq := RenderInlineImageScaled(v.ImageProto, b.Data, b.MimeType, cells, maxRows); seq != "" {
1754			rows, actualCells := InlineImageFootprint(b.Data, cells, maxRows)
1755			if rows < 1 {
1756				rows = 1
1757			}
1758			if actualCells < 1 {
1759				actualCells = cells
1760			}
1761			// Reserve the image footprint first, then place the escape
1762			// in the top-left of that blank rectangle. Keeping the
1763			// metadata above the image made some terminals blend text
1764			// and graphics layers during full-screen repaints; metadata
1765			// below the reserved rectangle is more stable and easier to
1766			// read. One extra blank row before the metadata gives the
1767			// caption breathing room from the image's last pixel row.
1768			//
1769			// Every footprint row (escape, reservations, gap) is tagged
1770			// with imageFootprintSentinel so callers wrapping content in
1771			// box edges can recognise these rows and emit them bare —
1772			// the image's graphics rectangle paints over them and any
1773			// │ character drawn alongside would visibly bleed through.
1774			// 4 leading cells push the escape past the box's left
1775			// edge plus a small interior gutter so the image rectangle
1776			// sits visibly inside the frame instead of kissing the │.
1777			// The escape row carries a width hint after the sentinel
1778			// ("\x1e<cells>\x1e...") so toolBoxSide knows how many
1779			// cells the image occupies and can pad to the right edge.
1780			widthHint := fmt.Sprintf("%s%d%s", imageFootprintSentinel, actualCells, imageFootprintSentinel)
1781			out := make([]string, 0, rows+3)
1782			out = append(out, widthHint+"    "+seq)
1783			for i := 1; i < rows; i++ {
1784				out = append(out, imageFootprintSentinel)
1785			}
1786			out = append(out, imageFootprintSentinel)
1787			out = append(out, v.Theme.FG256(v.Theme.Muted, info))
1788			return out
1789		}
1790	}
1791	return []string{v.Theme.FG256(v.Theme.Muted, info)}
1792}
1793
1794// looksLikeNumberedFile returns true when text matches the `read`
1795// tool's "     N\tcontent" format for most of its lines.
1796func looksLikeNumberedFile(text string) bool {
1797	lines := strings.Split(text, "\n")
1798	if len(lines) == 0 {
1799		return false
1800	}
1801	hits := 0
1802	scanned := 0
1803	for _, l := range lines {
1804		if l == "" {
1805			continue
1806		}
1807		scanned++
1808		if scanned > 20 {
1809			break
1810		}
1811		if numberedLineRE.MatchString(l) {
1812			hits++
1813		}
1814	}
1815	if scanned == 0 {
1816		return false
1817	}
1818	return hits*2 >= scanned // majority of non-empty lines match
1819}
1820
1821var numberedLineRE = regexp.MustCompile(`^\s*\d+\t`)
1822
1823// renderNumberedFile strips line numbers, highlights the code, and
1824// re-attaches the line numbers in muted color.
1825func (v *View) renderNumberedFile(text, sourcePath string) []string {
1826	lines := strings.Split(text, "\n")
1827	gutters := make([]string, 0, len(lines))
1828	codes := make([]string, 0, len(lines))
1829	for _, l := range lines {
1830		idx := strings.IndexByte(l, '\t')
1831		if idx < 0 || !numberedLineRE.MatchString(l) {
1832			// Non-code footer (e.g. "[truncated at 2000 lines]").
1833			gutters = append(gutters, "")
1834			codes = append(codes, l)
1835			continue
1836		}
1837		gutter := l[:idx] + " " // replace tab with single space
1838		code := expandTabs(l[idx+1:])
1839		gutters = append(gutters, gutter)
1840		codes = append(codes, code)
1841	}
1842	lang := LanguageFromPath(sourcePath)
1843	var highlighted []string
1844	if lang != "" {
1845		highlighted = v.Theme.HighlightCode(strings.Join(codes, "\n"), lang)
1846		// Chroma sometimes collapses the trailing empty line. Pad to
1847		// align with the gutter slice so per-line zipping works.
1848		for len(highlighted) < len(codes) {
1849			highlighted = append(highlighted, "")
1850		}
1851		if len(highlighted) > len(codes) {
1852			highlighted = highlighted[:len(codes)]
1853		}
1854	} else {
1855		// No lexer for this file type — render in the ToolOut color so
1856		// code is visually distinct from the muted gutter.
1857		highlighted = make([]string, len(codes))
1858		for i, c := range codes {
1859			highlighted[i] = v.Theme.FG256(v.Theme.ToolOut, c)
1860		}
1861	}
1862	out := make([]string, 0, len(codes))
1863	for i, code := range highlighted {
1864		g := gutters[i]
1865		if g == "" {
1866			out = append(out, "    "+v.Theme.FG256(v.Theme.Muted, code))
1867			continue
1868		}
1869		out = append(out, "    "+v.Theme.FG256(v.Theme.Muted, g)+code)
1870	}
1871	return out
1872}
1873
1874// looksLikeFileContent is a cheap guard to distinguish a read-tool
1875// result from bash stdout or a status message. File content usually
1876// contains characters that status messages don't (code punctuation,
1877// longer lines, multiple lines) and rarely starts with the "  >"-
1878// or "error:"-style prefixes tools emit. False positives are OK,
1879// the worst case is a line-number gutter on something that isn't
1880// really code.
1881// renderBashResult styles a bash tool result: the "$ command" first
1882// line in the accent color, the trailing "[exit N]  Took X.Ys" line
1883// in muted type, everything else on the default tool-output color.
1884// Called from renderToolText when the first line starts with "$ ".
1885func (v *View) renderBashResult(lines []string, width, defaultColor int) []string {
1886	lines = normalizeBashOutputLines(lines)
1887	// Identify the footer line (exit + timing). The bash tool writes
1888	// it as the last non-empty line of the result.
1889	footerIdx := -1
1890	for i := len(lines) - 1; i >= 0; i-- {
1891		trimmed := strings.TrimSpace(lines[i])
1892		if trimmed == "" {
1893			continue
1894		}
1895		if strings.HasPrefix(trimmed, "[exit ") {
1896			footerIdx = i
1897		}
1898		break
1899	}
1900
1901	var out []string
1902	for i, l := range lines {
1903		switch {
1904		case i == 0 && strings.HasPrefix(l, "$ "):
1905			// Style the $ and the command text in accent. No
1906			// further processing / wrapping so the shell-style
1907			// prompt reads at a glance.
1908			for _, w := range wrapLine(l, width-4, "    ") {
1909				out = append(out, "    "+v.Theme.FG256(v.Theme.Accent, w))
1910			}
1911		case i == footerIdx:
1912			for _, w := range wrapLine(l, width-4, "    ") {
1913				out = append(out, "    "+v.Theme.FG256(v.Theme.Muted, w))
1914			}
1915		default:
1916			for _, w := range wrapLine(l, width-4, "    ") {
1917				out = append(out, "    "+v.Theme.FG256(defaultColor, w))
1918			}
1919		}
1920	}
1921	return out
1922}
1923
1924// normalizeBashOutputLines turns arbitrary terminal output into plain,
1925// box-safe rows before wrapping. Unlike read/write/edit output, bash
1926// stdout/stderr may contain tabs, carriage returns, ANSI/OSC escapes,
1927// and other C0 controls from subprocesses. If those reach the bordered
1928// tool box, the width calculator can undercount what the terminal will
1929// draw and the right edge appears broken. Keep printable text, expand
1930// tabs to spaces, split carriage-return progress rows, and drop escape
1931// / control sequences.
1932func normalizeBashOutputLines(lines []string) []string {
1933	var out []string
1934	for _, line := range lines {
1935		for _, part := range strings.Split(strings.ReplaceAll(line, "\r", "\n"), "\n") {
1936			out = append(out, normalizeBashOutputLine(part))
1937		}
1938	}
1939	if len(out) == 0 {
1940		return []string{""}
1941	}
1942	return out
1943}
1944
1945func normalizeBashOutputLine(s string) string {
1946	var b strings.Builder
1947	col := 0
1948	for i := 0; i < len(s); {
1949		c := s[i]
1950		if c == 0x1b { // ESC: strip CSI/OSC/DCS and simple escapes.
1951			i = skipEscapeSequence(s, i)
1952			continue
1953		}
1954		r, size := utf8.DecodeRuneInString(s[i:])
1955		if r == utf8.RuneError && size == 1 {
1956			i++
1957			continue
1958		}
1959		switch r {
1960		case '\t':
1961			spaces := 8 - (col % 8)
1962			if spaces == 0 {
1963				spaces = 8
1964			}
1965			b.WriteString(strings.Repeat(" ", spaces))
1966			col += spaces
1967		case '\b':
1968			// Backspace-overstrike output is common in spinners/progress bars.
1969			// Dropping it is safer than moving the TUI cursor backwards.
1970		case '\n', '\r':
1971			// Already split by normalizeBashOutputLines.
1972		default:
1973			if r < 0x20 || r == 0x7f {
1974				// Drop non-printing controls.
1975				break
1976			}
1977			b.WriteRune(r)
1978			col += runewidth.RuneWidth(r)
1979		}
1980		i += size
1981	}
1982	return b.String()
1983}
1984
1985func skipEscapeSequence(s string, i int) int {
1986	if i >= len(s) || s[i] != 0x1b {
1987		return i + 1
1988	}
1989	if i+1 >= len(s) {
1990		return len(s)
1991	}
1992	switch s[i+1] {
1993	case '[': // CSI: ESC [ ... final byte 0x40-0x7e
1994		j := i + 2
1995		for j < len(s) {
1996			c := s[j]
1997			j++
1998			if c >= 0x40 && c <= 0x7e {
1999				break
2000			}
2001		}
2002		return j
2003	case ']': // OSC: ESC ] ... BEL or ST
2004		return skipStringEscape(s, i+2)
2005	case 'P', '_', '^', 'X': // DCS/APC/PM/SOS: ESC P ... ST, etc.
2006		return skipStringEscape(s, i+2)
2007	default:
2008		// Two-byte escape (cursor save/restore, charset select, etc.).
2009		return i + 2
2010	}
2011}
2012
2013func skipStringEscape(s string, i int) int {
2014	for i < len(s) {
2015		if s[i] == 0x07 { // BEL
2016			return i + 1
2017		}
2018		if s[i] == 0x1b && i+1 < len(s) && s[i+1] == '\\' { // ST
2019			return i + 2
2020		}
2021		i++
2022	}
2023	return len(s)
2024}
2025
2026// looksLikeUnifiedDiff reports whether text is a context diff as
2027// emitted by the edit tool: rows start with '+', '-', ' ', or
2028// literal "..." (context-break marker). The presence of at least
2029// one '+' or '-' row distinguishes a real diff from an ordinary
2030// file whose lines happen to begin with a space.
2031func looksLikeUnifiedDiff(text string) bool {
2032	lines := strings.Split(text, "\n")
2033	if len(lines) < 2 {
2034		return false
2035	}
2036	sawChange := false
2037	for _, l := range lines {
2038		if l == "" {
2039			continue
2040		}
2041		if l == "..." {
2042			continue
2043		}
2044		switch l[0] {
2045		case '+', '-':
2046			sawChange = true
2047		case ' ':
2048			// context, ok
2049		default:
2050			return false
2051		}
2052	}
2053	return sawChange
2054}
2055
2056// renderUnifiedDiff renders the edit tool's context diff. Each
2057// kept row shows a line-number gutter plus a marker column: '+'
2058// for additions (colored like add), '-' for deletions (colored
2059// like remove), and unmarked context in muted type. A literal
2060// "..." line between hunks renders as an ellipsis in muted type,
2061// indicating skipped unchanged rows. The old and new line
2062// counters advance so each row carries its actual position in
2063// the pre- or post-edit file. Heuristic: when we hit a "...", we
2064// can't know where the next hunk starts, so we don't reset the
2065// counters — they stay approximate in the rare multi-hunk case.
2066func (v *View) renderUnifiedDiff(text string, width int, sourcePath string) []string {
2067	lines := strings.Split(text, "\n")
2068	if n := len(lines); n > 0 && lines[n-1] == "" {
2069		lines = lines[:n-1]
2070	}
2071	oldLine, newLine := 1, 1
2072	var out []string
2073	for _, l := range lines {
2074		if l == "" {
2075			out = append(out, "")
2076			continue
2077		}
2078		if l == "..." {
2079			out = append(out, "    "+v.Theme.FG256(v.Theme.Muted, "..."))
2080			continue
2081		}
2082		switch l[0] {
2083		case '+':
2084			out = append(out, v.renderDiffRow(l, width, v.Theme.Tool, newLine, '+', sourcePath)...)
2085			newLine++
2086		case '-':
2087			out = append(out, v.renderDiffRow(l, width, v.Theme.Error, oldLine, '-', sourcePath)...)
2088			oldLine++
2089		case ' ':
2090			out = append(out, v.renderDiffRow(l, width, v.Theme.Muted, newLine, ' ', sourcePath)...)
2091			oldLine++
2092			newLine++
2093		default:
2094			for _, w := range wrapLine(l, width-4, "    ") {
2095				out = append(out, "    "+v.Theme.FG256(v.Theme.Muted, w))
2096			}
2097		}
2098	}
2099	return out
2100}
2101
2102func looksLikeFileContent(text string) bool {
2103	if strings.TrimSpace(text) == "" {
2104		return false
2105	}
2106	lines := strings.Split(text, "\n")
2107	return len(lines) >= 2
2108}
2109
2110// renderRawFile renders file content received without embedded line
2111// numbers (the current read-tool output). Draws a muted gutter like
2112// "%6d \t" starting at startLine, highlights the code using the
2113// source path's language, and returns the formatted lines.
2114func (v *View) renderRawFile(text, sourcePath string, startLine int) []string {
2115	lines := strings.Split(text, "\n")
2116	// Drop the trailing empty line that Split produces when text ends
2117	// in "\n" so the gutter doesn't show a phantom last number.
2118	if n := len(lines); n > 0 && lines[n-1] == "" {
2119		lines = lines[:n-1]
2120	}
2121	// Split code from trailing footer lines ("... [truncated ...]")
2122	// so we don't number the footer. A single blank separator line
2123	// immediately before the footer is also pulled out so the
2124	// gutter doesn't render a phantom number for it.
2125	codeEnd := len(lines)
2126	for i := len(lines) - 1; i >= 0; i-- {
2127		if strings.HasPrefix(lines[i], "...") {
2128			codeEnd = i
2129			continue
2130		}
2131		break
2132	}
2133	if codeEnd > 0 && codeEnd < len(lines) && lines[codeEnd-1] == "" {
2134		codeEnd--
2135	}
2136	code := lines[:codeEnd]
2137	footer := lines[codeEnd:]
2138
2139	// Expand tabs to 4 spaces so Go / Makefile code renders
2140	// at a consistent width.
2141	for i, c := range code {
2142		code[i] = expandTabs(c)
2143	}
2144
2145	lang := LanguageFromPath(sourcePath)
2146	var highlighted []string
2147	if lang != "" {
2148		highlighted = v.Theme.HighlightCode(strings.Join(code, "\n"), lang)
2149		for len(highlighted) < len(code) {
2150			highlighted = append(highlighted, "")
2151		}
2152		if len(highlighted) > len(code) {
2153			highlighted = highlighted[:len(code)]
2154		}
2155	} else {
2156		highlighted = make([]string, len(code))
2157		for i, c := range code {
2158			highlighted[i] = v.Theme.FG256(v.Theme.ToolOut, c)
2159		}
2160	}
2161
2162	out := make([]string, 0, len(lines))
2163	for i, c := range highlighted {
2164		gutter := fmt.Sprintf("%4d ", startLine+i)
2165		out = append(out, "    "+v.Theme.FG256(v.Theme.Muted, gutter)+c)
2166	}
2167	for _, f := range footer {
2168		out = append(out, "    "+v.Theme.FG256(v.Theme.Muted, f))
2169	}
2170	return out
2171}
2172
2173// toolResultBlock renders the live tool-call result body (shown
2174// while the turn is still in flight). The rules that used to
2175// bracket this block have been dropped so the live path looks
2176// identical to the transcript rendering that replaces it when
2177// the turn ends.
2178func toolResultBlock(th Theme, text string, width int, color int) []string {
2179	var out []string
2180	for _, l := range strings.Split(text, "\n") {
2181		for _, w := range wrapLine(l, width-4, "    ") {
2182			out = append(out, "    "+th.FG256(color, w))
2183		}
2184	}
2185	return out
2186}
2187
2188// defaultToolArgWidth is the number of cells the tool-call header
2189// truncates the primary argument (path/command/query) to when the
2190// ZOT_TOOL_ARG_WIDTH environment variable is unset or invalid.
2191const defaultToolArgWidth = 60
2192
2193// toolArgWidth returns the maximum cell width for the truncated
2194// primary argument shown in a tool-call header. It defaults to
2195// defaultToolArgWidth but can be raised or lowered with the
2196// ZOT_TOOL_ARG_WIDTH environment variable, which is useful for wide
2197// terminals where the default clips long queries too aggressively.
2198// Values outside the sane range [20, 500] are ignored so a stray or
2199// malformed setting can never produce an unreadable header or an
2200// out-of-range slice.
2201func toolArgWidth() int {
2202	v := strings.TrimSpace(os.Getenv("ZOT_TOOL_ARG_WIDTH"))
2203	if v == "" {
2204		return defaultToolArgWidth
2205	}
2206	n, err := strconv.Atoi(v)
2207	if err != nil || n < 20 || n > 500 {
2208		return defaultToolArgWidth
2209	}
2210	return n
2211}
2212
2213// ShortArgs renders a tool call's arguments into a one-line
2214// suffix for the "tool name <args>" header. tool is the tool
2215// name so we can add shape-specific decorations: for read we
2216// append the requested line range (e.g. "path:1-200") pulled
2217// from the offset/limit args, which is useful context at a
2218// glance without expanding the result body. Other tools keep
2219// the legacy "path or command, truncated" shape.
2220//
2221// The truncation width defaults to 60 cells but can be tuned via
2222// the ZOT_TOOL_ARG_WIDTH environment variable (see toolArgWidth).
2223//
2224// Exported because the interactive mode pre-populates the
2225// ToolCallView.Args field with this value as soon as the tool
2226// call is announced, so the live overlay's header matches what
2227// the finalised transcript will later render.
2228func ShortArgs(tool string, raw json.RawMessage) string {
2229	width := toolArgWidth()
2230	var v any
2231	if err := json.Unmarshal(raw, &v); err != nil {
2232		return ""
2233	}
2234	x, ok := v.(map[string]any)
2235	if !ok {
2236		b, _ := json.Marshal(v)
2237		s := oneLineToolLabel(string(b))
2238		if len(s) > width {
2239			s = s[:width-3] + "..."
2240		}
2241		return s
2242	}
2243	var primary string
2244	for _, k := range []string{"path", "file_path", "command"} {
2245		if s, ok := x[k].(string); ok {
2246			primary = s
2247			break
2248		}
2249	}
2250	if primary == "" {
2251		b, _ := json.Marshal(v)
2252		s := oneLineToolLabel(string(b))
2253		if len(s) > width {
2254			s = s[:width-3] + "..."
2255		}
2256		return s
2257	}
2258	primary = oneLineToolLabel(primary)
2259
2260	// Tool-specific decoration. Only the read tool gets a range
2261	// suffix for now; other tools just truncate the primary arg.
2262	suffix := ""
2263	switch strings.ToLower(tool) {
2264	case "read":
2265		start := 1
2266		if n, ok := toInt(x["offset"]); ok && n >= 1 {
2267			start = n
2268		}
2269		if lim, ok := toInt(x["limit"]); ok && lim > 0 {
2270			end := start + lim - 1
2271			suffix = fmt.Sprintf(":%d-%d", start, end)
2272		} else if start > 1 {
2273			suffix = fmt.Sprintf(":%d-", start)
2274		}
2275	}
2276
2277	// Truncate the primary arg leaving room for the suffix so the
2278	// range stays visible even on absurdly long paths.
2279	max := width - len(suffix)
2280	if max < 10 {
2281		max = 10
2282	}
2283	if len(primary) > max {
2284		primary = primary[:max-3] + "..."
2285	}
2286	return primary + suffix
2287}
2288
2289// toInt coerces a json.Unmarshal'd number (float64) or a string
2290// containing a number into an int. Returns ok=false if the value
2291// is neither. Used by shortArgs to survive model quirks where
2292// numeric args come back as strings.
2293func toInt(v any) (int, bool) {
2294	switch n := v.(type) {
2295	case float64:
2296		return int(n), true
2297	case int:
2298		return n, true
2299	case string:
2300		i, err := strconv.Atoi(strings.TrimSpace(n))
2301		if err != nil {
2302			return 0, false
2303		}
2304		return i, true
2305	}
2306	return 0, false
2307}
2308
2309func collectText(blocks []provider.Content) string {
2310	var sb strings.Builder
2311	for _, b := range blocks {
2312		if tb, ok := b.(provider.TextBlock); ok {
2313			if sb.Len() > 0 {
2314				sb.WriteString("\n")
2315			}
2316			sb.WriteString(tb.Text)
2317		}
2318	}
2319	return sb.String()
2320}
2321
2322func truncateLines(s string, n int) string {
2323	lines := strings.Split(s, "\n")
2324	if len(lines) <= n {
2325		return s
2326	}
2327	return strings.Join(lines[:n], "\n") + "\n  ... (" + fmt.Sprintf("%d", len(lines)-n) + " more)"
2328}
2329
2330// renderCompactionBlock renders a compaction summary as a distinct
2331// visual block in the chat. When collapsed it shows a one-line label
2332// with the pre-compaction token count; when expanded (ctrl+o) it
2333// shows the full summary text.
2334func (v *View) renderCompactionBlock(m provider.Message, width int) []string {
2335	th := v.Theme
2336	const indent = "    "
2337
2338	tokens := m.Meta["tokens_before"]
2339	if tokens == "" {
2340		tokens = "?"
2341	}
2342
2343	if v.ExpandAll {
2344		var lines []string
2345		header := th.FG256(th.Muted, fmt.Sprintf("compacted from ~%s tokens", tokens))
2346		lines = append(lines, indent+header)
2347		lines = append(lines, "")
2348		for _, c := range m.Content {
2349			if tb, ok := c.(provider.TextBlock); ok {
2350				text := tb.Text
2351				if idx := strings.Index(text, "\n\n"); idx >= 0 && strings.HasPrefix(text, "## Context Summary") {
2352					text = text[idx+2:]
2353				}
2354				md := RenderMarkdown(text, th, width-4)
2355				for _, l := range strings.Split(md, "\n") {
2356					if len(l) > 0 && l[0] == FlushLeftSentinel {
2357						l = l[1:]
2358					}
2359					lines = append(lines, indent+l)
2360				}
2361			}
2362		}
2363		return lines
2364	}
2365
2366	// Collapsed: single line, no banner.
2367	line := th.FG256(th.Muted, fmt.Sprintf("compacted from ~%s tokens (ctrl+o to expand)", tokens))
2368	return []string{indent + line}
2369}
2370
2371// StatusBarParams groups the many bits of state the status bar needs.
2372// Grew from a flat argument list once we settled on the layout.
2373type StatusBarParams struct {
2374	Theme      Theme
2375	Provider   string
2376	Model      string
2377	Reasoning  string // "" means thinking off
2378	Busy       bool
2379	BusyPrefix string // spinner + funny line when busy
2380	CWD        string
2381	Locked     bool // sandbox on?
2382	NoYolo     bool // confirmation mode enabled?
2383
2384	// Cumulative session usage and cost.
2385	Usage provider.Usage
2386	// Subscription is true when the credential is an OAuth token (claude
2387	// pro/max, chatgpt plus/pro) rather than a paid api key. We still
2388	// compute a cost for visibility and append "(sub)" so the user
2389	// knows no real money moved.
2390	Subscription bool
2391
2392	// Last turn's input+cache tokens (approximates current live context).
2393	ContextUsed int
2394	ContextMax  int // model's context window; 0 disables the percentage
2395
2396	// AutoCompacting is true when the agent is currently running a
2397	// model-triggered condense pass. Surfaces as "(auto)" after the
2398	// context percentage so it's clear where the spinner is coming from.
2399	AutoCompacting bool
2400
2401	// Telegram true when the telegram bridge is connected. Adds a
2402	// small "- tg -" tag to the cwd line so the user can tell at a
2403	// glance that dms are being mirrored into this session.
2404	Telegram bool
2405
2406	Cols int // terminal width; drives right-alignment of cwd
2407}
2408
2409// StatusBar builds the status shown above the editor. Always returns
2410// two lines when a cwd is provided: the stats on the first line, the
2411// cwd on its own line below, indented to match the stats column. This
2412// keeps the status bar stable across terminal resizes (the cwd never
2413// jumps from right-aligned-on-line-1 to flush-left-on-line-2) and
2414// makes a long cwd safe at any width.
2415//
2416// Layout:
2417//
2418//	<busyPrefix>  (provider) model  stats   <- line 1
2419//	  cwd                                   <- line 2 (2-space indent)
2420//
2421// The old "ctrl+c exit - /help" / "esc cancel" hint is gone entirely.
2422// The slash-command popup and the queued/sliding-in chips already
2423// cover the discoverability of those keybindings.
2424func StatusBar(p StatusBarParams) []string {
2425	th := p.Theme
2426
2427	// Token stats: only include each segment when non-zero. Keeps
2428	// the bar compact on brand-new sessions.
2429	var stats []string
2430	if p.Usage.InputTokens > 0 {
2431		stats = append(stats, fmt.Sprintf("↑%s", formatTokens(p.Usage.InputTokens)))
2432	}
2433	if p.Usage.OutputTokens > 0 {
2434		stats = append(stats, fmt.Sprintf("↓%s", formatTokens(p.Usage.OutputTokens)))
2435	}
2436	if p.Usage.CacheReadTokens > 0 {
2437		stats = append(stats, fmt.Sprintf("R%s", formatTokens(p.Usage.CacheReadTokens)))
2438	}
2439	if p.Usage.CacheWriteTokens > 0 {
2440		stats = append(stats, fmt.Sprintf("W%s", formatTokens(p.Usage.CacheWriteTokens)))
2441	}
2442
2443	// Cost: always show the dollar value computed from token counts,
2444	// even on subscription. Lets you see what the equivalent api cost
2445	// would be (handy for gauging subscription value). Append "(sub)"
2446	// only as a hint that no real money moved.
2447	var costStr string
2448	if p.Usage.CostUSD > 0 || p.Subscription {
2449		costStr = fmt.Sprintf("$%.3f", p.Usage.CostUSD)
2450		if p.Subscription {
2451			costStr += " (sub)"
2452		}
2453	}
2454	if costStr != "" {
2455		stats = append(stats, costStr)
2456	}
2457
2458	// Context %. Color-coded: yellow >70, red >90.
2459	ctx, ctxColor := contextUsage(th, p.ContextUsed, p.ContextMax)
2460	if ctx != "" {
2461		if p.AutoCompacting {
2462			ctx += " (auto)"
2463		}
2464		stats = append(stats, th.FG256(ctxColor, ctx))
2465	}
2466
2467	// Layout uses exactly 2 spaces of horizontal padding everywhere:
2468	//   2 spaces  (openai) gpt-5.4  $0.000 (sub) 0.0%/400k  ~/Sites/zot
2469	// matches the editor prompt's left inset so the bar lines up
2470	// vertically with the conversation column.
2471	const pad = "  " // 2 spaces
2472
2473	left := fmt.Sprintf("(%s) %s", p.Provider, p.Model)
2474	thinking := thinkingLevelLabel(p.Reasoning)
2475	thinkingText := ""
2476	if thinking != "" {
2477		thinkingText = "thinking: " + thinking
2478	}
2479	statsText := strings.Join(stats, " ")
2480	middleParts := make([]string, 0, 2)
2481	if thinkingText != "" {
2482		middleParts = append(middleParts, thinkingText)
2483	}
2484	if statsText != "" {
2485		middleParts = append(middleParts, statsText)
2486	}
2487	middle := strings.Join(middleParts, "  ")
2488
2489	var leftBuilder strings.Builder
2490	if p.BusyPrefix != "" {
2491		// Don't re-color the payload itself — the caller already set
2492		// fg colors on the spinner glyph, message, and elapsed
2493		// segments. Wrapping the whole thing here would override
2494		// those choices. The pad itself needs no color (it's spaces).
2495		leftBuilder.WriteString(pad + p.BusyPrefix)
2496		// Exactly one pad (2 spaces) between the busy segment and
2497		// the provider/model block. The leading pad above covers
2498		// the left indent.
2499		leftBuilder.WriteString(pad)
2500	} else {
2501		// Idle path: a single pad of left inset so the line
2502		// aligns with the conversation column on its left edge
2503		// ("  you" / "  zot" message markers). Without the busy
2504		// prefix there's no trailing separator to double-pad.
2505		leftBuilder.WriteString(pad)
2506	}
2507	leftBuilder.WriteString(th.FG256(th.Muted, left))
2508	if middle != "" {
2509		leftBuilder.WriteString(pad)
2510		// Highlight the opt-in max tier; other status information stays muted.
2511		leftBuilder.WriteString(th.FG256(thinkingStatusColor(th, thinkingText), middle))
2512	}
2513
2514	cwd := shortenHome(p.CWD)
2515	tags := ""
2516	if p.NoYolo {
2517		tags += "yolo mode disabled "
2518	}
2519	if p.Locked {
2520		tags += "jailed "
2521	}
2522	if p.Telegram {
2523		tags += "telegram connected "
2524	}
2525	if tags != "" && cwd != "" {
2526		cwd = tags + "- " + cwd
2527	}
2528
2529	primary := leftBuilder.String()
2530
2531	// On narrow terminals the single line wraps badly. If the visible
2532	// width exceeds cols and we have a busy prefix, split: keep the
2533	// busy prefix on line 1, then put model and (if still needed)
2534	// stats on their own rows. This mirrors the idle split below.
2535	if p.Cols > 0 && p.BusyPrefix != "" && visibleWidth(primary) > p.Cols {
2536		busyLine := pad + p.BusyPrefix
2537		modelLine := pad + th.FG256(th.Muted, left)
2538		lines := []string{busyLine}
2539		if middle != "" && visibleWidth(modelLine+pad+th.FG256(th.Muted, middle)) > p.Cols {
2540			lines = appendWrappedStatusLines(lines, th, pad, left, thinkingText, statsText, p.Cols)
2541		} else {
2542			var infoBuilder strings.Builder
2543			infoBuilder.WriteString(modelLine)
2544			if middle != "" {
2545				infoBuilder.WriteString(pad)
2546				infoBuilder.WriteString(th.FG256(thinkingStatusColor(th, thinkingText), middle))
2547			}
2548			lines = append(lines, infoBuilder.String())
2549		}
2550		if cwd != "" {
2551			lines = append(lines, pad+th.FG256(th.Muted, cwd))
2552		}
2553		return lines
2554	}
2555
2556	// Idle narrow split: keep provider/model on the first status line,
2557	// move usage/cost/context stats to the next, then cwd below. This
2558	// avoids the terminal's hard wrap cutting the stats or pushing cwd
2559	// into an awkward position on small widths.
2560	if p.Cols > 0 && p.BusyPrefix == "" && middle != "" && visibleWidth(primary) > p.Cols {
2561		var lines []string
2562		lines = appendWrappedStatusLines(lines, th, pad, left, thinkingText, statsText, p.Cols)
2563		if cwd != "" {
2564			lines = append(lines, pad+th.FG256(th.Muted, cwd))
2565		}
2566		return lines
2567	}
2568
2569	if cwd == "" {
2570		return []string{primary}
2571	}
2572
2573	// Second line: indent with the same 2-space pad so the cwd lines
2574	// up under the "(provider)" column on line 1.
2575	cwdRendered := pad + th.FG256(th.Muted, cwd)
2576	return []string{primary, cwdRendered}
2577}
2578
2579func appendWrappedStatusLines(lines []string, th Theme, pad, modelText, thinkingText, statsText string, cols int) []string {
2580	modelLine := pad + th.FG256(th.Muted, modelText)
2581	if thinkingText == "" {
2582		lines = append(lines, modelLine)
2583		if statsText != "" {
2584			lines = append(lines, pad+th.FG256(th.Muted, statsText))
2585		}
2586		return lines
2587	}
2588
2589	modelThinkingPlain := pad + modelText + pad + thinkingText
2590	thinkingColor := thinkingStatusColor(th, thinkingText)
2591	if cols <= 0 || visibleWidth(modelThinkingPlain) <= cols {
2592		lines = append(lines, pad+th.FG256(thinkingColor, modelText+pad+thinkingText))
2593	} else {
2594		lines = append(lines, modelLine)
2595		lines = append(lines, pad+th.FG256(thinkingColor, thinkingText))
2596	}
2597	if statsText != "" {
2598		lines = append(lines, pad+th.FG256(th.Muted, statsText))
2599	}
2600	return lines
2601}
2602
2603func thinkingStatusColor(th Theme, thinkingText string) int {
2604	if strings.HasSuffix(thinkingText, ": max") {
2605		return th.ThinkingMax
2606	}
2607	return th.Muted
2608}
2609
2610func thinkingLevelLabel(level string) string {
2611	switch strings.ToLower(strings.TrimSpace(level)) {
2612	case "", "off", "none", "no", "false", "disabled":
2613		return ""
2614	case "minimum", "minimal", "min":
2615		return "minimal"
2616	case "maximum", "xhigh":
2617		return "xhigh"
2618	case "max":
2619		return "max"
2620	default:
2621		return strings.ToLower(strings.TrimSpace(level))
2622	}
2623}
2624
2625// contextUsage renders the "N%/ctxMax" fragment, returning the
2626// rendered string plus the colour to wrap it in.
2627func contextUsage(th Theme, used, max int) (string, int) {
2628	if max <= 0 {
2629		if used <= 0 {
2630			return "", th.Muted
2631		}
2632		return formatTokens(used), th.Muted
2633	}
2634	pct := float64(used) / float64(max) * 100
2635	text := fmt.Sprintf("%.1f%%/%s", pct, formatTokens(max))
2636	switch {
2637	case pct > 90:
2638		return text, th.Error
2639	case pct > 70:
2640		return text, th.Warning
2641	}
2642	return text, th.Muted
2643}
2644
2645// formatTokens footer formatter:
2646//
2647//	< 1000      -> "42"
2648//	< 10_000    -> "2.7k"
2649//	< 1_000_000 -> "35k"
2650//	< 10M       -> "1.1M"
2651//	else        -> "12M"
2652func formatTokens(n int) string {
2653	switch {
2654	case n < 0:
2655		return "0"
2656	case n < 1000:
2657		return fmt.Sprintf("%d", n)
2658	case n < 10000:
2659		return fmt.Sprintf("%.1fk", float64(n)/1000)
2660	case n < 1_000_000:
2661		return fmt.Sprintf("%dk", (n+500)/1000)
2662	case n < 10_000_000:
2663		return fmt.Sprintf("%.1fM", float64(n)/1_000_000)
2664	default:
2665		return fmt.Sprintf("%dM", (n+500_000)/1_000_000)
2666	}
2667}
2668
2669// shortenHome replaces the user's $HOME prefix with "~" for readability.
2670func shortenHome(p string) string {
2671	if p == "" {
2672		return ""
2673	}
2674	home := osUserHome()
2675	if home == "" {
2676		return p
2677	}
2678	if p == home {
2679		return "~"
2680	}
2681	if strings.HasPrefix(p, home+"/") {
2682		return "~" + p[len(home):]
2683	}
2684	return p
2685}
2686
2687// osUserHome is a tiny wrapper around os.UserHomeDir so tests can mock it.
2688var osUserHome = func() string {
2689	if h, err := osUserHomeDir(); err == nil {
2690		return h
2691	}
2692	return ""
2693}

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