v0.2.51 92241f6

view.go RawHistoryFolder

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

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