v0.1.42 42173ed

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

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