v0.1.51 ff1af01

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

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