v0.1.28 955a9b7

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.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.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.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				if tr.IsError {
565					lines = append(lines, toolBoxSide(v.Theme, v.Theme.FG256(color, "  error"), width))
566				}
567				for _, body := range v.renderToolResultContent(tr.Content, width, color, path, startLine) {
568					// Image escapes paint into a graphics layer that
569					// doesn't share the text grid; wrapping such a row
570					// in │ … │ produces visible artefacts on iTerm /
571					// Kitty, so leave image rows un-bordered. The
572					// surrounding lines still close the box top + bottom.
573					if hasImageEscapeLine(body) {
574						lines = append(lines, body)
575						continue
576					}
577					lines = append(lines, toolBoxSide(v.Theme, body, width))
578				}
579				lines = append(lines, toolBoxBottom(v.Theme, width))
580			}
581		}
582	}
583	return lines
584}
585
586func (v *View) renderToolCall(tc ToolCallView, width int) []string {
587	var lines []string
588
589	// Header label. While the call is still streaming, prefer the
590	// live path extracted from the partial args so the user sees
591	// the target file as soon as it's known, even before the full
592	// JSON arrived.
593	arg := tc.Args
594	if arg == "" && tc.LivePath != "" {
595		arg = tc.LivePath
596	}
597	label := tc.Name + " " + arg
598
599	// Every box is preceded by a blank line so it doesn't sit
600	// flush against the prose / previous tool block above it.
601	// Matches the transcript-side framing in renderMessage.
602
603	// Streaming body (write/edit): top edge with the label, body
604	// rows wrapped with vertical edges, bottom edge to close the
605	// box. When the call finalises, the live overlay disappears
606	// the same frame the transcript renders the closed box, so
607	// there's no visible hop.
608	if tc.Streaming && tc.Result == "" {
609		lines = append(lines, "")
610		lines = append(lines, toolBoxTop(v.Theme, label, width))
611		if body := v.renderLiveToolBody(tc, width); len(body) > 0 {
612			lines = append(lines, body...)
613		}
614		lines = append(lines, toolBoxBottom(v.Theme, width))
615		return lines
616	}
617
618	// Finished tool call with no body: just the labelled top edge
619	// directly closed by the bottom. Avoids a blank interior row
620	// for no-output tools.
621	if tc.Result == "" {
622		lines = append(lines, "")
623		lines = append(lines, toolBoxTop(v.Theme, label, width))
624		lines = append(lines, toolBoxBottom(v.Theme, width))
625		return lines
626	}
627
628	// Finished tool call with a result body. Top edge embeds the
629	// label; body lines go through toolBoxSide so each row gets
630	// vertical edges; bottom edge closes the box.
631	lines = append(lines, "")
632	lines = append(lines, toolBoxTop(v.Theme, label, width))
633	color := v.Theme.ToolOut
634	if tc.Error {
635		color = v.Theme.Error
636	}
637	body := toolResultBlock(v.Theme, tc.Result, width, color)
638	for _, l := range v.collapseToolBody(body, false) {
639		if hasImageEscapeLine(l) {
640			lines = append(lines, l)
641			continue
642		}
643		lines = append(lines, toolBoxSide(v.Theme, l, width))
644	}
645	lines = append(lines, toolBoxBottom(v.Theme, width))
646	return lines
647}
648
649// renderLiveToolBody renders the in-flight preview of a streaming
650// tool call. Supported tools:
651//
652//   - write: shows the partial `content` field, syntax-highlighted
653//     by the target path's language.
654//   - edit:  shows the partial `newText` of the edit currently being
655//     streamed, prefixed with a "editing foo.ts (edit 2)" header so
656//     the user can see which of a multi-edit batch is in progress.
657//
658// Anything else returns nil and only the tool-call header shows.
659func (v *View) renderLiveToolBody(tc ToolCallView, width int) []string {
660	switch tc.Name {
661	case "write", "Write":
662		partial, ok, _ := ExtractPartialStringField(tc.RawJSONBuf, "content")
663		if !ok || partial == "" {
664			return nil
665		}
666		return v.wrapLiveBody(v.renderRawFile(partial, tc.LivePath, 1), width)
667	case "edit", "Edit":
668		partial, ok, _, idx := ExtractLastNewText(tc.RawJSONBuf)
669		if !ok || partial == "" {
670			return nil
671		}
672		// Header line hints which edit is streaming and, when more
673		// than one has landed, how many the model is doing.
674		hint := fmt.Sprintf("edit %d (streaming)", idx)
675		body := []string{"    " + v.Theme.FG256(v.Theme.Muted, hint), ""}
676		body = append(body, v.renderRawFile(partial, tc.LivePath, 1)...)
677		return v.wrapLiveBody(body, width)
678	}
679	return nil
680}
681
682// wrapLiveBody returns the streaming body content as a list of
683// box-side rows: each line wrapped in │ … │ with right padding so
684// the closing edge sits at column width-1. The caller (renderToolCall)
685// supplies the surrounding top/bottom edges so the live overlay
686// renders as a closed box matching the finalised transcript form.
687func (v *View) wrapLiveBody(body []string, width int) []string {
688	body = v.collapseToolBody(body, false)
689	out := make([]string, 0, len(body))
690	for _, l := range body {
691		if hasImageEscapeLine(l) {
692			out = append(out, l)
693			continue
694		}
695		out = append(out, toolBoxSide(v.Theme, l, width))
696	}
697	return out
698}
699
700// toolResultBlock wraps text in thin horizontal rules (top + bottom),
701// indenting the body with four spaces. The rules span the content column.
702// toolBlockRule renders the muted horizontal separator drawn
703// above and below a tool call block. Spans the full content
704// width so it reads as a real section break in the chat
705// regardless of terminal size.
706func toolBlockRule(th Theme, width int) string {
707	w := width
708	if w < 8 {
709		w = 8
710	}
711	return th.FG256(th.Muted, strings.Repeat("─", w))
712}
713
714// toolBoxInnerPad is the number of blank cells kept between a box
715// edge (┌, │, └) and the content inside it. One cell of breathing
716// room makes the label read as part of the box rather than fused to
717// the corner, and gives body lines a tiny gutter from the left side.
718const toolBoxInnerPad = 1
719
720// toolBoxTop renders the labelled top edge of a tool block:
721//
722//	┌─  bash xcrun simctl list devices ─────────────────────────────┐
723//
724// The label is the tool name + short args (the same string previously
725// shown on its own row beneath the rule). Padding fills the remainder
726// of the line so the right corner sits at column width-1, matching the
727// closing edge.
728func toolBoxTop(th Theme, label string, width int) string {
729	w := width
730	if w < 12 {
731		w = 12
732	}
733	innerPad := strings.Repeat(" ", toolBoxInnerPad)
734	// "┌─" + innerPad + " " + label + " " + innerPad = used; pad
735	// with ─ to width-1, then "┐".
736	prefix := "┌─" + innerPad + " "
737	suffix := " " + innerPad
738	used := visibleWidth(prefix) + visibleWidth(label) + visibleWidth(suffix)
739	fill := w - used - 1 // -1 for the closing corner
740	if fill < 0 {
741		// Label overflows; truncate with an ellipsis so the right
742		// corner still lands on the right edge. Rare on real
743		// terminals (the chat column is usually wide enough).
744		over := -fill
745		runes := []rune(label)
746		if over+1 < len(runes) {
747			label = string(runes[:len(runes)-over-1]) + "…"
748		} else {
749			label = "…"
750		}
751		used = visibleWidth(prefix) + visibleWidth(label) + visibleWidth(suffix)
752		fill = w - used - 1
753		if fill < 0 {
754			fill = 0
755		}
756	}
757	line := prefix + label + suffix + strings.Repeat("─", fill) + "┐"
758	return th.FG256(th.Muted, line)
759}
760
761// toolBoxBottom renders the bottom edge of a tool block:
762//
763//	└─────────────────────────────────────────────────────────────────────────────┘
764//
765// Spans the same width as toolBoxTop so the corners line up.
766func toolBoxBottom(th Theme, width int) string {
767	w := width
768	if w < 12 {
769		w = 12
770	}
771	line := "└" + strings.Repeat("─", w-2) + "┘"
772	return th.FG256(th.Muted, line)
773}
774
775// hasImageEscapeLine reports whether s contains a Kitty (\x1b_G) or
776// iTerm2 (\x1b]1337;File=) inline-image escape. Such rows draw into
777// the terminal's graphics layer and shouldn't be wrapped with text
778// box edges.
779func hasImageEscapeLine(s string) bool {
780	return strings.Contains(s, "\x1b]1337;File=") || strings.Contains(s, "\x1b_G")
781}
782
783// toolBoxBodyTrimLeft is the number of leading literal spaces stripped
784// from each body line as it enters toolBoxSide. Body renderers
785// (renderToolText, renderRawFile, the diff/bash helpers, ...) all
786// emit a 4-cell indent so the content aligns with the assistant body
787// column when there's no box around it. Inside a box the box edge +
788// inner pad already supply most of that gutter, so we drop a couple
789// of cells from the body's own indent to keep the content from
790// drifting too far right.
791const toolBoxBodyTrimLeft = 2
792
793// toolBoxSide wraps a single body line with vertical box edges:
794//
795//	│  foo bar baz                                            │
796//
797// The middle preserves the line verbatim (including any ANSI escapes)
798// after stripping toolBoxBodyTrimLeft leading literal spaces. One cell
799// of inner padding sits on each side so the content breathes from the
800// edges; the right padding fills to column width-1.
801func toolBoxSide(th Theme, line string, width int) string {
802	w := width
803	if w < 12 {
804		w = 12
805	}
806	left := th.FG256(th.Muted, "│") + strings.Repeat(" ", toolBoxInnerPad)
807	right := strings.Repeat(" ", toolBoxInnerPad) + th.FG256(th.Muted, "│")
808	inner := w - 2 - 2*toolBoxInnerPad // available between the two pads
809	line = trimLeadingSpaces(line, toolBoxBodyTrimLeft)
810	cur := visibleWidth(line)
811	if cur > inner {
812		// Last-resort truncation. Strips ANSI styling at the cut
813		// point; rare path so the simpler implementation is fine.
814		line = stripANSI(line)
815		runes := []rune(line)
816		if len(runes) > inner {
817			line = string(runes[:inner])
818		}
819		cur = visibleWidth(line)
820	}
821	pad := inner - cur
822	if pad < 0 {
823		pad = 0
824	}
825	return left + line + strings.Repeat(" ", pad) + right
826}
827
828// trimLeadingSpaces removes up to n literal space characters from the
829// start of s without touching anything else. ANSI CSI escapes that
830// appear before the spaces are skipped over (so a coloured indent
831// like "\x1b[2m    text" still loses its first n cells of indent).
832// Stops as soon as it hits a non-space character.
833func trimLeadingSpaces(s string, n int) string {
834	if n <= 0 || s == "" {
835		return s
836	}
837	var b strings.Builder
838	b.Grow(len(s))
839	trimmed := 0
840	i := 0
841	for i < len(s) {
842		// Pass through any ANSI escape sequence verbatim.
843		if s[i] == 0x1b && i+1 < len(s) && s[i+1] == '[' {
844			end := i + 2
845			for end < len(s) {
846				c := s[end]
847				end++
848				if c >= 0x40 && c <= 0x7e {
849					break
850				}
851			}
852			b.WriteString(s[i:end])
853			i = end
854			continue
855		}
856		if trimmed < n && s[i] == ' ' {
857			trimmed++
858			i++
859			continue
860		}
861		b.WriteString(s[i:])
862		return b.String()
863	}
864	return b.String()
865}
866
867// renderToolResultContent renders the body of a tool result block.
868// Text blocks get the usual rules-wrapped treatment; text that looks
869// like a unified diff gets +/- coloring. Image blocks are rendered
870// inline when the terminal supports a protocol, else as a text
871// placeholder with dimensions.
872func (v *View) renderToolResultContent(blocks []provider.Content, width, color int, sourcePath string, startLine int) []string {
873	var body []string
874	hasImage := false
875	for _, b := range blocks {
876		switch bb := b.(type) {
877		case provider.TextBlock:
878			body = append(body, v.renderToolText(bb.Text, width, color, sourcePath, startLine)...)
879		case provider.ImageBlock:
880			hasImage = true
881			body = append(body, v.renderImageBlock(bb, width)...)
882		}
883	}
884	return v.collapseToolBody(body, hasImage)
885}
886
887// collapseToolBody trims lines to the configured preview size when the
888// view is not in ExpandAll mode, appending a muted "... ctrl+o to
889// expand" footer. Image blocks never collapse — they're short in text
890// rows but represent real content the user wants to see.
891func (v *View) collapseToolBody(lines []string, hasImage bool) []string {
892	if v.ExpandAll || hasImage {
893		return lines
894	}
895	if len(lines) <= ToolCollapseLines {
896		return lines
897	}
898	kept := lines[:ToolCollapsePreview]
899	hidden := len(lines) - ToolCollapsePreview
900	total := len(lines)
901	footer := fmt.Sprintf("    ... (%d more lines, %d total, ctrl+o to expand)", hidden, total)
902	footer = v.Theme.FG256(v.Theme.Muted, footer)
903	return append(append([]string(nil), kept...), footer)
904}
905
906// renderToolText renders a text block inside a tool result. If the
907// text contains a unified-diff section (lines starting with "--- " /
908// "+++ " / "+" / "-"/" "), those rows are styled with add/remove
909// colors matching git diff conventions.
910func (v *View) renderToolText(text string, width, defaultColor int, sourcePath string, startLine int) []string {
911	// Legacy path: transcripts saved before we dropped line numbers
912	// from the read tool still carry "     1\t…" prefixes. Detect and
913	// strip them, then fall through to the highlighter.
914	if looksLikeNumberedFile(text) {
915		return v.renderNumberedFile(text, sourcePath)
916	}
917	// If the result embeds a unified diff (the edit tool's output
918	// starts with a short "applied N edit(s)" line and then a
919	// standard --- / +++ / +/- patch), render the patch with
920	// add/remove coloring. This takes priority over the file-like
921	// detector below because a diff technically has many lines of
922	// "file content" but what the user cares about is what changed,
923	// not a dump of the post-edit file.
924	if looksLikeUnifiedDiff(text) {
925		return v.renderUnifiedDiff(text, width, sourcePath)
926	}
927
928	// Current path: text came from `read` as raw file bytes. When a
929	// source path is known (the call had a `path` arg), render with
930	// a synthetic line-number gutter starting at startLine so the
931	// on-screen view still looks like cat -n. Doesn't apply to non-
932	// file tool outputs (bash stdout, display notes, etc.).
933	if sourcePath != "" && looksLikeFileContent(text) {
934		return v.renderRawFile(text, sourcePath, startLine)
935	}
936
937	// No truncation — the full tool output is rendered into chat and
938	// becomes part of the scrollback you can page back through.
939	lines := strings.Split(text, "\n")
940
941	// Bash-result styling: when the first row looks like a shell
942	// prompt line ("$ ...") emitted by the bash tool, style the
943	// prompt line in accent and the trailing "[exit N]  Took X.Ys"
944	// line in muted type so the command + timing read at a glance.
945	// Everything between is left on the default tool-output color.
946	if len(lines) > 0 && strings.HasPrefix(lines[0], "$ ") {
947		return v.renderBashResult(lines, width, defaultColor)
948	}
949
950	inDiff := false
951	oldLine, newLine := 1, 1
952	var out []string
953	for _, l := range lines {
954		// Detect diff header: "--- name" followed somewhere by "+++ name".
955		if strings.HasPrefix(l, "--- ") || strings.HasPrefix(l, "+++ ") {
956			inDiff = true
957			out = append(out, "    "+v.Theme.FG256(v.Theme.Muted, l))
958			continue
959		}
960		// Hunk header "@@ -a,b +c,d @@" resets the counters so patches
961		// that skip around in the file still get correct numbering.
962		if inDiff && strings.HasPrefix(l, "@@") {
963			if o, n, ok := parseHunkHeader(l); ok {
964				oldLine, newLine = o, n
965			}
966			out = append(out, "    "+v.Theme.FG256(v.Theme.Muted, l))
967			continue
968		}
969		if inDiff && len(l) > 0 {
970			switch l[0] {
971			case '+':
972				out = append(out, v.renderDiffRow(l, width, v.Theme.Tool, newLine, '+', sourcePath))
973				newLine++
974				continue
975			case '-':
976				out = append(out, v.renderDiffRow(l, width, v.Theme.Error, oldLine, '-', sourcePath))
977				oldLine++
978				continue
979			case ' ':
980				out = append(out, v.renderDiffRow(l, width, v.Theme.Muted, newLine, ' ', sourcePath))
981				oldLine++
982				newLine++
983				continue
984			}
985		}
986		// Regular line.
987		for _, w := range wrapLine(l, width-4, "    ") {
988			out = append(out, "    "+v.Theme.FG256(defaultColor, w))
989		}
990	}
991	return out
992}
993
994// parseHunkHeader extracts the starting old/new line from a unified
995// diff hunk header ("@@ -12,5 +12,7 @@ ..."). Returns ok=false if the
996// header is malformed or missing numbers.
997func parseHunkHeader(l string) (oldStart, newStart int, ok bool) {
998	// Skip "@@ "
999	rest := strings.TrimPrefix(l, "@@")
1000	rest = strings.TrimSpace(rest)
1001	if !strings.HasPrefix(rest, "-") {
1002		return 0, 0, false
1003	}
1004	rest = rest[1:]
1005	space := strings.IndexByte(rest, ' ')
1006	if space < 0 {
1007		return 0, 0, false
1008	}
1009	oldPart := rest[:space]
1010	rest = strings.TrimSpace(rest[space+1:])
1011	if !strings.HasPrefix(rest, "+") {
1012		return 0, 0, false
1013	}
1014	rest = rest[1:]
1015	if sp := strings.IndexAny(rest, " \t"); sp >= 0 {
1016		rest = rest[:sp]
1017	}
1018	parseStart := func(s string) (int, bool) {
1019		if c := strings.IndexByte(s, ','); c >= 0 {
1020			s = s[:c]
1021		}
1022		n, err := strconv.Atoi(s)
1023		if err != nil || n < 1 {
1024			return 0, false
1025		}
1026		return n, true
1027	}
1028	o, ok1 := parseStart(oldPart)
1029	n, ok2 := parseStart(rest)
1030	if !ok1 || !ok2 {
1031		return 0, 0, false
1032	}
1033	return o, n, true
1034}
1035
1036// renderDiffRow renders one unified-diff line with a read-style gutter
1037// (6-cell right-aligned line number, muted) followed by the +/-/space
1038// marker and the code. Code is syntax-highlighted if sourcePath hints
1039// at a known language; falls back to the plain diff color otherwise.
1040func (v *View) renderDiffRow(line string, width, color int, lineNo int, mark byte, sourcePath string) string {
1041	if len(line) == 0 {
1042		return ""
1043	}
1044	code := expandTabs(line[1:]) // strip the leading marker; expand tabs
1045
1046	// Syntax-highlight the code half when we know the language. Use
1047	// the same HighlightCode pipeline as renderNumberedFile so the
1048	// palette matches.
1049	lang := LanguageFromPath(sourcePath)
1050	var codeRendered string
1051	if lang != "" {
1052		if h := HighlightCode(code, lang); len(h) == 1 {
1053			codeRendered = h[0]
1054		}
1055	}
1056	if codeRendered == "" {
1057		if mark == ' ' {
1058			codeRendered = v.Theme.FG256(v.Theme.Muted, code)
1059		} else {
1060			codeRendered = v.Theme.FG256(color, code)
1061		}
1062	}
1063
1064	// Gutter shape: sign + number share a color so they read as one
1065	// visual token ("+123") instead of a neutral line number next to
1066	// a stray marker. Unchanged context lines get a muted gutter and
1067	// a leading space so column alignment stays consistent with +/-
1068	// rows.
1069	var gutterText string
1070	switch mark {
1071	case '+':
1072		gutterText = fmt.Sprintf("+%3d ", lineNo)
1073	case '-':
1074		gutterText = fmt.Sprintf("-%3d ", lineNo)
1075	default:
1076		gutterText = fmt.Sprintf(" %3d ", lineNo)
1077	}
1078	var gutter string
1079	if mark == ' ' {
1080		gutter = v.Theme.FG256(v.Theme.Muted, gutterText)
1081	} else {
1082		gutter = v.Theme.FG256(color, gutterText)
1083	}
1084	row := "    " + gutter + codeRendered
1085
1086	// Cheap width clamp: truncate visible text if the raw code is too
1087	// long. We work on the pre-ANSI code string because measuring ansi
1088	// output is unreliable.
1089	maxCode := width - 4 /* indent */ - 7 /* gutter (sign+5 digits+tab) */
1090	if maxCode > 0 && len(code) > maxCode {
1091		trunc := code[:maxCode-1] + "…"
1092		if lang != "" {
1093			if h := HighlightCode(trunc, lang); len(h) == 1 {
1094				codeRendered = h[0]
1095			} else if mark == ' ' {
1096				codeRendered = v.Theme.FG256(v.Theme.Muted, trunc)
1097			} else {
1098				codeRendered = v.Theme.FG256(color, trunc)
1099			}
1100		} else if mark == ' ' {
1101			codeRendered = v.Theme.FG256(v.Theme.Muted, trunc)
1102		} else {
1103			codeRendered = v.Theme.FG256(color, trunc)
1104		}
1105		row = "    " + gutter + codeRendered
1106	}
1107	return row
1108}
1109
1110// renderImageBlock returns the lines for one image, inline if possible.
1111//
1112// Inline image escapes paint into multiple terminal rows but the zot
1113// renderer treats each slice entry as a single row. To prevent chat
1114// content from being drawn on top of the image, we pad with blank rows
1115// so the image's real footprint is reflected in the frame height.
1116func (v *View) renderImageBlock(b provider.ImageBlock, width int) []string {
1117	w, h := ImageDimensions(b.Data)
1118	kb := len(b.Data) / 1024
1119	// Four-space indent matches every other tool-output row
1120	// (renderRawFile, renderBashResult, diff rows, "... N more
1121	// lines" footers). Keeps the image's metadata line vertically
1122	// aligned with the file content above / below it.
1123	info := fmt.Sprintf("    image - %s - %dx%d - %d KB", b.MimeType, w, h, kb)
1124
1125	if v.ImageProto != ImageProtocolNone {
1126		// Clamp rendered width so the image never overflows the chat
1127		// column. Subtract a 4-cell indent for the tool result block,
1128		// cap at 60 cells, floor at 10.
1129		cells := width - 4
1130		if cells > 60 {
1131			cells = 60
1132		}
1133		if cells < 10 {
1134			cells = 10
1135		}
1136		const maxRows = 20
1137		if seq := RenderInlineImageScaled(v.ImageProto, b.Data, b.MimeType, cells, maxRows); seq != "" {
1138			rows := RowsForInlineImage(b.Data, cells, maxRows)
1139			if rows < 1 {
1140				rows = 1
1141			}
1142			// Reserve the image footprint first, then place the escape
1143			// in the top-left of that blank rectangle. Keeping the
1144			// metadata above the image made some terminals blend text and
1145			// graphics layers during full-screen repaints; metadata below
1146			// the reserved rectangle is more stable and easier to read.
1147			out := make([]string, 0, rows+3)
1148			out = append(out, "    "+seq)
1149			for i := 1; i < rows; i++ {
1150				out = append(out, "")
1151			}
1152			out = append(out, v.Theme.FG256(v.Theme.Muted, info))
1153			return out
1154		}
1155	}
1156	return []string{v.Theme.FG256(v.Theme.Muted, info)}
1157}
1158
1159// looksLikeNumberedFile returns true when text matches the `read`
1160// tool's "     N\tcontent" format for most of its lines.
1161func looksLikeNumberedFile(text string) bool {
1162	lines := strings.Split(text, "\n")
1163	if len(lines) == 0 {
1164		return false
1165	}
1166	hits := 0
1167	scanned := 0
1168	for _, l := range lines {
1169		if l == "" {
1170			continue
1171		}
1172		scanned++
1173		if scanned > 20 {
1174			break
1175		}
1176		if numberedLineRE.MatchString(l) {
1177			hits++
1178		}
1179	}
1180	if scanned == 0 {
1181		return false
1182	}
1183	return hits*2 >= scanned // majority of non-empty lines match
1184}
1185
1186var numberedLineRE = regexp.MustCompile(`^\s*\d+\t`)
1187
1188// renderNumberedFile strips line numbers, highlights the code, and
1189// re-attaches the line numbers in muted color.
1190func (v *View) renderNumberedFile(text, sourcePath string) []string {
1191	lines := strings.Split(text, "\n")
1192	gutters := make([]string, 0, len(lines))
1193	codes := make([]string, 0, len(lines))
1194	for _, l := range lines {
1195		idx := strings.IndexByte(l, '\t')
1196		if idx < 0 || !numberedLineRE.MatchString(l) {
1197			// Non-code footer (e.g. "[truncated at 2000 lines]").
1198			gutters = append(gutters, "")
1199			codes = append(codes, l)
1200			continue
1201		}
1202		gutter := l[:idx] + " " // replace tab with single space
1203		code := expandTabs(l[idx+1:])
1204		gutters = append(gutters, gutter)
1205		codes = append(codes, code)
1206	}
1207	lang := LanguageFromPath(sourcePath)
1208	var highlighted []string
1209	if lang != "" {
1210		highlighted = HighlightCode(strings.Join(codes, "\n"), lang)
1211		// Chroma sometimes collapses the trailing empty line. Pad to
1212		// align with the gutter slice so per-line zipping works.
1213		for len(highlighted) < len(codes) {
1214			highlighted = append(highlighted, "")
1215		}
1216		if len(highlighted) > len(codes) {
1217			highlighted = highlighted[:len(codes)]
1218		}
1219	} else {
1220		// No lexer for this file type — render in the ToolOut color so
1221		// code is visually distinct from the muted gutter.
1222		highlighted = make([]string, len(codes))
1223		for i, c := range codes {
1224			highlighted[i] = v.Theme.FG256(v.Theme.ToolOut, c)
1225		}
1226	}
1227	out := make([]string, 0, len(codes))
1228	for i, code := range highlighted {
1229		g := gutters[i]
1230		if g == "" {
1231			out = append(out, "    "+v.Theme.FG256(v.Theme.Muted, code))
1232			continue
1233		}
1234		out = append(out, "    "+v.Theme.FG256(v.Theme.Muted, g)+code)
1235	}
1236	return out
1237}
1238
1239// looksLikeFileContent is a cheap guard to distinguish a read-tool
1240// result from bash stdout or a status message. File content usually
1241// contains characters that status messages don't (code punctuation,
1242// longer lines, multiple lines) and rarely starts with the "  >"-
1243// or "error:"-style prefixes tools emit. False positives are OK,
1244// the worst case is a line-number gutter on something that isn't
1245// really code.
1246// renderBashResult styles a bash tool result: the "$ command" first
1247// line in the accent color, the trailing "[exit N]  Took X.Ys" line
1248// in muted type, everything else on the default tool-output color.
1249// Called from renderToolText when the first line starts with "$ ".
1250func (v *View) renderBashResult(lines []string, width, defaultColor int) []string {
1251	// Identify the footer line (exit + timing). The bash tool writes
1252	// it as the last non-empty line of the result.
1253	footerIdx := -1
1254	for i := len(lines) - 1; i >= 0; i-- {
1255		trimmed := strings.TrimSpace(lines[i])
1256		if trimmed == "" {
1257			continue
1258		}
1259		if strings.HasPrefix(trimmed, "[exit ") {
1260			footerIdx = i
1261		}
1262		break
1263	}
1264
1265	var out []string
1266	for i, l := range lines {
1267		switch {
1268		case i == 0 && strings.HasPrefix(l, "$ "):
1269			// Style the $ and the command text in accent. No
1270			// further processing / wrapping so the shell-style
1271			// prompt reads at a glance.
1272			for _, w := range wrapLine(l, width-4, "    ") {
1273				out = append(out, "    "+v.Theme.FG256(v.Theme.Accent, w))
1274			}
1275		case i == footerIdx:
1276			out = append(out, "    "+v.Theme.FG256(v.Theme.Muted, l))
1277		default:
1278			for _, w := range wrapLine(l, width-4, "    ") {
1279				out = append(out, "    "+v.Theme.FG256(defaultColor, w))
1280			}
1281		}
1282	}
1283	return out
1284}
1285
1286// looksLikeUnifiedDiff reports whether text is a context diff as
1287// emitted by the edit tool: rows start with '+', '-', ' ', or
1288// literal "..." (context-break marker). The presence of at least
1289// one '+' or '-' row distinguishes a real diff from an ordinary
1290// file whose lines happen to begin with a space.
1291func looksLikeUnifiedDiff(text string) bool {
1292	lines := strings.Split(text, "\n")
1293	if len(lines) < 2 {
1294		return false
1295	}
1296	sawChange := false
1297	for _, l := range lines {
1298		if l == "" {
1299			continue
1300		}
1301		if l == "..." {
1302			continue
1303		}
1304		switch l[0] {
1305		case '+', '-':
1306			sawChange = true
1307		case ' ':
1308			// context, ok
1309		default:
1310			return false
1311		}
1312	}
1313	return sawChange
1314}
1315
1316// renderUnifiedDiff renders the edit tool's context diff. Each
1317// kept row shows a line-number gutter plus a marker column: '+'
1318// for additions (colored like add), '-' for deletions (colored
1319// like remove), and unmarked context in muted type. A literal
1320// "..." line between hunks renders as an ellipsis in muted type,
1321// indicating skipped unchanged rows. The old and new line
1322// counters advance so each row carries its actual position in
1323// the pre- or post-edit file. Heuristic: when we hit a "...", we
1324// can't know where the next hunk starts, so we don't reset the
1325// counters — they stay approximate in the rare multi-hunk case.
1326func (v *View) renderUnifiedDiff(text string, width int, sourcePath string) []string {
1327	lines := strings.Split(text, "\n")
1328	if n := len(lines); n > 0 && lines[n-1] == "" {
1329		lines = lines[:n-1]
1330	}
1331	oldLine, newLine := 1, 1
1332	var out []string
1333	for _, l := range lines {
1334		if l == "" {
1335			out = append(out, "")
1336			continue
1337		}
1338		if l == "..." {
1339			out = append(out, "    "+v.Theme.FG256(v.Theme.Muted, "…"))
1340			continue
1341		}
1342		switch l[0] {
1343		case '+':
1344			out = append(out, v.renderDiffRow(l, width, v.Theme.Tool, newLine, '+', sourcePath))
1345			newLine++
1346		case '-':
1347			out = append(out, v.renderDiffRow(l, width, v.Theme.Error, oldLine, '-', sourcePath))
1348			oldLine++
1349		case ' ':
1350			out = append(out, v.renderDiffRow(l, width, v.Theme.Muted, newLine, ' ', sourcePath))
1351			oldLine++
1352			newLine++
1353		default:
1354			for _, w := range wrapLine(l, width-4, "    ") {
1355				out = append(out, "    "+v.Theme.FG256(v.Theme.Muted, w))
1356			}
1357		}
1358	}
1359	return out
1360}
1361
1362func looksLikeFileContent(text string) bool {
1363	if strings.TrimSpace(text) == "" {
1364		return false
1365	}
1366	lines := strings.Split(text, "\n")
1367	return len(lines) >= 2
1368}
1369
1370// renderRawFile renders file content received without embedded line
1371// numbers (the current read-tool output). Draws a muted gutter like
1372// "%6d \t" starting at startLine, highlights the code using the
1373// source path's language, and returns the formatted lines.
1374func (v *View) renderRawFile(text, sourcePath string, startLine int) []string {
1375	lines := strings.Split(text, "\n")
1376	// Drop the trailing empty line that Split produces when text ends
1377	// in "\n" so the gutter doesn't show a phantom last number.
1378	if n := len(lines); n > 0 && lines[n-1] == "" {
1379		lines = lines[:n-1]
1380	}
1381	// Split code from trailing footer lines ("... [truncated ...]")
1382	// so we don't number the footer.
1383	codeEnd := len(lines)
1384	for i := len(lines) - 1; i >= 0; i-- {
1385		if strings.HasPrefix(lines[i], "...") {
1386			codeEnd = i
1387			continue
1388		}
1389		break
1390	}
1391	code := lines[:codeEnd]
1392	footer := lines[codeEnd:]
1393
1394	// Expand tabs to 4 spaces so Go / Makefile code renders
1395	// at a consistent width.
1396	for i, c := range code {
1397		code[i] = expandTabs(c)
1398	}
1399
1400	lang := LanguageFromPath(sourcePath)
1401	var highlighted []string
1402	if lang != "" {
1403		highlighted = HighlightCode(strings.Join(code, "\n"), lang)
1404		for len(highlighted) < len(code) {
1405			highlighted = append(highlighted, "")
1406		}
1407		if len(highlighted) > len(code) {
1408			highlighted = highlighted[:len(code)]
1409		}
1410	} else {
1411		highlighted = make([]string, len(code))
1412		for i, c := range code {
1413			highlighted[i] = v.Theme.FG256(v.Theme.ToolOut, c)
1414		}
1415	}
1416
1417	out := make([]string, 0, len(lines))
1418	for i, c := range highlighted {
1419		gutter := fmt.Sprintf("%4d ", startLine+i)
1420		out = append(out, "    "+v.Theme.FG256(v.Theme.Muted, gutter)+c)
1421	}
1422	for _, f := range footer {
1423		out = append(out, "    "+v.Theme.FG256(v.Theme.Muted, f))
1424	}
1425	return out
1426}
1427
1428// toolResultBlock renders the live tool-call result body (shown
1429// while the turn is still in flight). The rules that used to
1430// bracket this block have been dropped so the live path looks
1431// identical to the transcript rendering that replaces it when
1432// the turn ends.
1433func toolResultBlock(th Theme, text string, width int, color int) []string {
1434	var out []string
1435	for _, l := range strings.Split(text, "\n") {
1436		for _, w := range wrapLine(l, width-4, "    ") {
1437			out = append(out, "    "+th.FG256(color, w))
1438		}
1439	}
1440	return out
1441}
1442
1443// ShortArgs renders a tool call's arguments into a one-line
1444// suffix for the "tool name <args>" header. tool is the tool
1445// name so we can add shape-specific decorations: for read we
1446// append the requested line range (e.g. "path:1-200") pulled
1447// from the offset/limit args, which is useful context at a
1448// glance without expanding the result body. Other tools keep
1449// the legacy "path or command, truncated at 60 cells" shape.
1450//
1451// Exported because the interactive mode pre-populates the
1452// ToolCallView.Args field with this value as soon as the tool
1453// call is announced, so the live overlay's header matches what
1454// the finalised transcript will later render.
1455func ShortArgs(tool string, raw json.RawMessage) string {
1456	var v any
1457	if err := json.Unmarshal(raw, &v); err != nil {
1458		return ""
1459	}
1460	x, ok := v.(map[string]any)
1461	if !ok {
1462		b, _ := json.Marshal(v)
1463		s := string(b)
1464		if len(s) > 60 {
1465			s = s[:57] + "..."
1466		}
1467		return s
1468	}
1469	var primary string
1470	for _, k := range []string{"path", "file_path", "command"} {
1471		if s, ok := x[k].(string); ok {
1472			primary = s
1473			break
1474		}
1475	}
1476	if primary == "" {
1477		b, _ := json.Marshal(v)
1478		s := string(b)
1479		if len(s) > 60 {
1480			s = s[:57] + "..."
1481		}
1482		return s
1483	}
1484
1485	// Tool-specific decoration. Only the read tool gets a range
1486	// suffix for now; other tools just truncate the primary arg.
1487	suffix := ""
1488	switch strings.ToLower(tool) {
1489	case "read":
1490		start := 1
1491		if n, ok := toInt(x["offset"]); ok && n >= 1 {
1492			start = n
1493		}
1494		if lim, ok := toInt(x["limit"]); ok && lim > 0 {
1495			end := start + lim - 1
1496			suffix = fmt.Sprintf(":%d-%d", start, end)
1497		} else if start > 1 {
1498			suffix = fmt.Sprintf(":%d-", start)
1499		}
1500	}
1501
1502	// Truncate the primary arg leaving room for the suffix so the
1503	// range stays visible even on absurdly long paths.
1504	max := 60 - len(suffix)
1505	if max < 10 {
1506		max = 10
1507	}
1508	if len(primary) > max {
1509		primary = primary[:max-3] + "..."
1510	}
1511	return primary + suffix
1512}
1513
1514// toInt coerces a json.Unmarshal'd number (float64) or a string
1515// containing a number into an int. Returns ok=false if the value
1516// is neither. Used by shortArgs to survive model quirks where
1517// numeric args come back as strings.
1518func toInt(v any) (int, bool) {
1519	switch n := v.(type) {
1520	case float64:
1521		return int(n), true
1522	case int:
1523		return n, true
1524	case string:
1525		i, err := strconv.Atoi(strings.TrimSpace(n))
1526		if err != nil {
1527			return 0, false
1528		}
1529		return i, true
1530	}
1531	return 0, false
1532}
1533
1534func collectText(blocks []provider.Content) string {
1535	var sb strings.Builder
1536	for _, b := range blocks {
1537		if tb, ok := b.(provider.TextBlock); ok {
1538			if sb.Len() > 0 {
1539				sb.WriteString("\n")
1540			}
1541			sb.WriteString(tb.Text)
1542		}
1543	}
1544	return sb.String()
1545}
1546
1547func truncateLines(s string, n int) string {
1548	lines := strings.Split(s, "\n")
1549	if len(lines) <= n {
1550		return s
1551	}
1552	return strings.Join(lines[:n], "\n") + "\n  … (" + fmt.Sprintf("%d", len(lines)-n) + " more)"
1553}
1554
1555// renderCompactionBlock renders a compaction summary as a distinct
1556// visual block in the chat. When collapsed it shows a one-line label
1557// with the pre-compaction token count; when expanded (ctrl+o) it
1558// shows the full summary text.
1559func (v *View) renderCompactionBlock(m provider.Message, width int) []string {
1560	th := v.Theme
1561	const indent = "    "
1562
1563	tokens := m.Meta["tokens_before"]
1564	if tokens == "" {
1565		tokens = "?"
1566	}
1567
1568	if v.ExpandAll {
1569		var lines []string
1570		header := th.FG256(th.Muted, fmt.Sprintf("compacted from ~%s tokens", tokens))
1571		lines = append(lines, indent+header)
1572		lines = append(lines, "")
1573		for _, c := range m.Content {
1574			if tb, ok := c.(provider.TextBlock); ok {
1575				text := tb.Text
1576				if idx := strings.Index(text, "\n\n"); idx >= 0 && strings.HasPrefix(text, "## Context Summary") {
1577					text = text[idx+2:]
1578				}
1579				md := RenderMarkdown(text, th, width-4)
1580				for _, l := range strings.Split(md, "\n") {
1581					lines = append(lines, indent+l)
1582				}
1583			}
1584		}
1585		return lines
1586	}
1587
1588	// Collapsed: single line, no banner.
1589	line := th.FG256(th.Muted, fmt.Sprintf("compacted from ~%s tokens (ctrl+o to expand)", tokens))
1590	return []string{indent + line}
1591}
1592
1593// StatusBarParams groups the many bits of state the status bar needs.
1594// Grew from a flat argument list once we settled on the layout.
1595type StatusBarParams struct {
1596	Theme      Theme
1597	Provider   string
1598	Model      string
1599	Busy       bool
1600	BusyPrefix string // spinner + funny line when busy
1601	CWD        string
1602	Locked     bool // sandbox on?
1603
1604	// Cumulative session usage and cost.
1605	Usage provider.Usage
1606	// Subscription is true when the credential is an OAuth token (claude
1607	// pro/max, chatgpt plus/pro) rather than a paid api key. We still
1608	// compute a cost for visibility and append "(sub)" so the user
1609	// knows no real money moved.
1610	Subscription bool
1611
1612	// Last turn's input+cache tokens (approximates current live context).
1613	ContextUsed int
1614	ContextMax  int // model's context window; 0 disables the percentage
1615
1616	// AutoCompacting is true when the agent is currently running a
1617	// model-triggered condense pass. Surfaces as "(auto)" after the
1618	// context percentage so it's clear where the spinner is coming from.
1619	AutoCompacting bool
1620
1621	// Telegram true when the telegram bridge is connected. Adds a
1622	// small "- tg -" tag to the cwd line so the user can tell at a
1623	// glance that dms are being mirrored into this session.
1624	Telegram bool
1625
1626	Cols int // terminal width; drives right-alignment of cwd
1627}
1628
1629// StatusBar builds the status shown above the editor. Always returns
1630// two lines when a cwd is provided: the stats on the first line, the
1631// cwd on its own line below, indented to match the stats column. This
1632// keeps the status bar stable across terminal resizes (the cwd never
1633// jumps from right-aligned-on-line-1 to flush-left-on-line-2) and
1634// makes a long cwd safe at any width.
1635//
1636// Layout:
1637//
1638//	<busyPrefix>  (provider) model  stats   <- line 1
1639//	  cwd                                   <- line 2 (2-space indent)
1640//
1641// The old "ctrl+c exit - /help" / "esc cancel" hint is gone entirely.
1642// The slash-command popup and the queued/sliding-in chips already
1643// cover the discoverability of those keybindings.
1644func StatusBar(p StatusBarParams) []string {
1645	th := p.Theme
1646
1647	// Token stats: only include each segment when non-zero. Keeps
1648	// the bar compact on brand-new sessions.
1649	var stats []string
1650	if p.Usage.InputTokens > 0 {
1651		stats = append(stats, fmt.Sprintf("↑%s", formatTokens(p.Usage.InputTokens)))
1652	}
1653	if p.Usage.OutputTokens > 0 {
1654		stats = append(stats, fmt.Sprintf("↓%s", formatTokens(p.Usage.OutputTokens)))
1655	}
1656	if p.Usage.CacheReadTokens > 0 {
1657		stats = append(stats, fmt.Sprintf("R%s", formatTokens(p.Usage.CacheReadTokens)))
1658	}
1659	if p.Usage.CacheWriteTokens > 0 {
1660		stats = append(stats, fmt.Sprintf("W%s", formatTokens(p.Usage.CacheWriteTokens)))
1661	}
1662
1663	// Cost: always show the dollar value computed from token counts,
1664	// even on subscription. Lets you see what the equivalent api cost
1665	// would be (handy for gauging subscription value). Append "(sub)"
1666	// only as a hint that no real money moved.
1667	var costStr string
1668	if p.Usage.CostUSD > 0 || p.Subscription {
1669		costStr = fmt.Sprintf("$%.3f", p.Usage.CostUSD)
1670		if p.Subscription {
1671			costStr += " (sub)"
1672		}
1673	}
1674	if costStr != "" {
1675		stats = append(stats, costStr)
1676	}
1677
1678	// Context %. Color-coded: yellow >70, red >90.
1679	ctx, ctxColor := contextUsage(th, p.ContextUsed, p.ContextMax)
1680	if ctx != "" {
1681		if p.AutoCompacting {
1682			ctx += " (auto)"
1683		}
1684		stats = append(stats, th.FG256(ctxColor, ctx))
1685	}
1686
1687	// Layout uses exactly 2 spaces of horizontal padding everywhere:
1688	//   2 spaces  (openai) gpt-5.4  $0.000 (sub) 0.0%/400k  ~/Sites/zot
1689	// matches the editor prompt's left inset so the bar lines up
1690	// vertically with the conversation column.
1691	const pad = "  " // 2 spaces
1692
1693	left := fmt.Sprintf("(%s) %s", p.Provider, p.Model)
1694	middle := strings.Join(stats, " ")
1695
1696	var leftBuilder strings.Builder
1697	if p.BusyPrefix != "" {
1698		// Don't re-color the payload itself — the caller already set
1699		// fg colors on the spinner glyph, message, and elapsed
1700		// segments. Wrapping the whole thing here would override
1701		// those choices. The pad itself needs no color (it's spaces).
1702		leftBuilder.WriteString(pad + p.BusyPrefix)
1703		// Exactly one pad (2 spaces) between the busy segment and
1704		// the provider/model block. The leading pad above covers
1705		// the left indent.
1706		leftBuilder.WriteString(pad)
1707	} else {
1708		// Idle path: a single pad of left inset so the line
1709		// aligns with the conversation column on its left edge
1710		// ("  you" / "  zot" message markers). Without the busy
1711		// prefix there's no trailing separator to double-pad.
1712		leftBuilder.WriteString(pad)
1713	}
1714	leftBuilder.WriteString(th.FG256(th.Muted, left))
1715	if middle != "" {
1716		leftBuilder.WriteString(pad)
1717		// `middle` already has colorized context segments; wrap the rest in muted.
1718		leftBuilder.WriteString(th.FG256(th.Muted, middle))
1719	}
1720
1721	cwd := shortenHome(p.CWD)
1722	tags := ""
1723	if p.Locked {
1724		tags += "- jailed "
1725	}
1726	if p.Telegram {
1727		tags += "- tg "
1728	}
1729	if tags != "" && cwd != "" {
1730		cwd = tags + "- " + cwd
1731	}
1732
1733	primary := leftBuilder.String()
1734
1735	// On narrow terminals the single line wraps badly. If the visible
1736	// width exceeds cols and we have a busy prefix, split: keep the
1737	// busy prefix on line 1, put model+stats on line 2.
1738	if p.Cols > 0 && p.BusyPrefix != "" && visibleWidth(primary) > p.Cols {
1739		busyLine := pad + p.BusyPrefix
1740		var infoBuilder strings.Builder
1741		infoBuilder.WriteString(pad)
1742		infoBuilder.WriteString(th.FG256(th.Muted, left))
1743		if middle != "" {
1744			infoBuilder.WriteString(pad)
1745			infoBuilder.WriteString(th.FG256(th.Muted, middle))
1746		}
1747		lines := []string{busyLine, infoBuilder.String()}
1748		if cwd != "" {
1749			lines = append(lines, pad+th.FG256(th.Muted, cwd))
1750		}
1751		return lines
1752	}
1753
1754	if cwd == "" {
1755		return []string{primary}
1756	}
1757
1758	// Second line: indent with the same 2-space pad so the cwd lines
1759	// up under the "(provider)" column on line 1.
1760	cwdRendered := pad + th.FG256(th.Muted, cwd)
1761	return []string{primary, cwdRendered}
1762}
1763
1764// contextUsage renders the "N%/ctxMax" fragment, returning the
1765// rendered string plus the colour to wrap it in.
1766func contextUsage(th Theme, used, max int) (string, int) {
1767	if max <= 0 {
1768		if used <= 0 {
1769			return "", th.Muted
1770		}
1771		return formatTokens(used), th.Muted
1772	}
1773	pct := float64(used) / float64(max) * 100
1774	text := fmt.Sprintf("%.1f%%/%s", pct, formatTokens(max))
1775	switch {
1776	case pct > 90:
1777		return text, th.Error
1778	case pct > 70:
1779		return text, th.Warning
1780	}
1781	return text, th.Muted
1782}
1783
1784// formatTokens footer formatter:
1785//
1786//	< 1000      -> "42"
1787//	< 10_000    -> "2.7k"
1788//	< 1_000_000 -> "35k"
1789//	< 10M       -> "1.1M"
1790//	else        -> "12M"
1791func formatTokens(n int) string {
1792	switch {
1793	case n < 0:
1794		return "0"
1795	case n < 1000:
1796		return fmt.Sprintf("%d", n)
1797	case n < 10000:
1798		return fmt.Sprintf("%.1fk", float64(n)/1000)
1799	case n < 1_000_000:
1800		return fmt.Sprintf("%dk", (n+500)/1000)
1801	case n < 10_000_000:
1802		return fmt.Sprintf("%.1fM", float64(n)/1_000_000)
1803	default:
1804		return fmt.Sprintf("%dM", (n+500_000)/1_000_000)
1805	}
1806}
1807
1808// shortenHome replaces the user's $HOME prefix with "~" for readability.
1809func shortenHome(p string) string {
1810	if p == "" {
1811		return ""
1812	}
1813	home := osUserHome()
1814	if home == "" {
1815		return p
1816	}
1817	if p == home {
1818		return "~"
1819	}
1820	if strings.HasPrefix(p, home+"/") {
1821		return "~" + p[len(home):]
1822	}
1823	return p
1824}
1825
1826// osUserHome is a tiny wrapper around os.UserHomeDir so tests can mock it.
1827var osUserHome = func() string {
1828	if h, err := osUserHomeDir(); err == nil {
1829		return h
1830	}
1831	return ""
1832}

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