v0.1.53 ae4e019

view.go RawHistoryFolder

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

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