v0.1.34 cead9fd

view.go RawHistoryFolder

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

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