v0.1.17 a81472c

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

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