v0.2.88 24f1547

view.go RawHistoryFolder

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

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