v0.1.46 6ba41f2

view.go RawHistoryFolder

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

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