v0.1.96 6684724

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

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