v0.1.27 4b2bce3

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

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