v0.1.84 ad93054

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

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