v0.0.14 ebc5dad

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// pathFromToolArgs returns the "path" argument from a tool_call's
15// JSON arguments, or "" if the args aren't a JSON object or don't
16// include one. Used to pick a syntax language for rendering the
17// corresponding tool_result.
18func pathFromToolArgs(raw json.RawMessage) string {
19	if len(raw) == 0 {
20		return ""
21	}
22	var m map[string]any
23	if err := json.Unmarshal(raw, &m); err != nil {
24		return ""
25	}
26	for _, k := range []string{"path", "file_path"} {
27		if s, ok := m[k].(string); ok && s != "" {
28			return s
29		}
30	}
31	return ""
32}
33
34// osUserHomeDir is aliased so the test file can swap it.
35var osUserHomeDir = os.UserHomeDir
36
37// View turns a transcript + live state into a slice of styled lines,
38// already wrapped to width.
39type View struct {
40	Theme      Theme
41	ImageProto ImageProtocol // how to render inline images in this terminal
42	Messages   []provider.Message
43	// toolPaths maps tool_use_id to the "path" argument of the call, if
44	// any, so tool_result rendering can pick the right syntax language.
45	// Rebuilt on each Build().
46	toolPaths       map[string]string
47	Streaming       string // current assistant text delta
48	StreamingActive bool
49	ToolCalls       []ToolCallView // tool calls in flight or completed
50	StatusLine      string
51	Err             string
52
53	// ExpandAll forces every long tool result to render in full.
54	// Toggled from the tui by ctrl+o. When false, results longer than
55	// ToolCollapseLines collapse to ToolCollapsePreview lines plus a
56	// "... (N more lines, M total, ctrl+o to expand)" footer.
57	ExpandAll bool
58
59	// renderCache holds the per-message rendered line slices so Build
60	// doesn't re-markdown every message on every frame. Keyed by a
61	// struct of (content hash, width, expandAll) — any of those
62	// changing invalidates the entry. Messages are append-only after
63	// they finalise so keeping the cache across turns is safe.
64	//
65	// Streaming/in-flight work (v.Streaming, v.ToolCalls) is never
66	// cached because it changes every delta.
67	renderCache map[msgCacheKey][]string
68}
69
70// msgCacheKey identifies a cached message render. hash is a 64-bit
71// FNV-1a of the message's content, which is cheap to compute and
72// unambiguous enough for the cache (collisions produce a stale frame,
73// not wrong data, and we recompute on invalidation anyway).
74type msgCacheKey struct {
75	hash      uint64
76	width     int
77	expandAll bool
78}
79
80// InvalidateRenderCache drops all cached message renders. The tui
81// calls this when the transcript is replaced wholesale (/compact,
82// /clear, session swap) since messages can be replaced in place and
83// a content-hash miss alone doesn't reclaim the old entries.
84func (v *View) InvalidateRenderCache() {
85	v.renderCache = nil
86}
87
88// ToolCollapsePreview is the number of lines shown before a long tool
89// result is replaced with a "... ctrl+o to expand" footer. Tool
90// results shorter than ToolCollapseLines always render in full.
91const (
92	ToolCollapsePreview = 10
93	ToolCollapseLines   = 12
94)
95
96// ToolCallView is a pending tool invocation plus optional result.
97type ToolCallView struct {
98	ID     string
99	Name   string
100	Args   string // rendered argument summary
101	Result string // rendered result preview (truncated)
102	Error  bool
103	Done   bool
104}
105
106// MessageAnchor records where a rendered message starts in the chat
107// line slice. Used by /jump so the dialog can scroll the viewport to
108// the row where a turn's user prompt begins.
109type MessageAnchor struct {
110	MessageIdx int // index into v.Messages
111	Row        int // first row of that message in the Build() output
112}
113
114// Build returns the chat log lines for the given width.
115func (v *View) Build(width int) []string {
116	lines, _ := v.BuildWithAnchors(width)
117	return lines
118}
119
120// BuildWithAnchors is like Build but additionally reports the first
121// row occupied by each message in v.Messages. Callers that need to
122// scroll to a specific turn (the /jump dialog) use the anchor slice
123// to map a message index back to a row offset.
124func (v *View) BuildWithAnchors(width int) ([]string, []MessageAnchor) {
125	v.refreshToolPaths()
126	if v.renderCache == nil {
127		v.renderCache = make(map[msgCacheKey][]string)
128	}
129
130	// Pre-render every message (hits the cache for unchanged ones) so
131	// we can allocate `out` in a single shot with the exact capacity.
132	// Growing via append on a long transcript copies the backing array
133	// log2(N) times; for a 2000-line scrollback that's enough memcpy
134	// to visibly stutter while typing.
135	rendered := make([][]string, len(v.Messages))
136	total := 0
137	for idx, m := range v.Messages {
138		lines := v.renderMessageCached(m, width)
139		rendered[idx] = lines
140		total += len(lines) + 1 // +1 for the blank separator row
141	}
142
143	out := make([]string, 0, total+16)
144	anchors := make([]MessageAnchor, 0, len(v.Messages))
145	for idx := range v.Messages {
146		anchors = append(anchors, MessageAnchor{MessageIdx: idx, Row: len(out)})
147		out = append(out, rendered[idx]...)
148		out = append(out, "")
149	}
150	if v.StreamingActive {
151		out = append(out, v.Theme.FG256(v.Theme.Assistant, "▍ zot"))
152		// Stream the partial assistant text through the same markdown
153		// renderer used for finalised messages so code fences, diffs,
154		// lists, and inline styles look the same while streaming and
155		// don't suddenly reflow when the turn ends.
156		md := RenderMarkdown(v.Streaming, v.Theme, width)
157		for _, l := range strings.Split(md, "\n") {
158			for _, w := range wrapLine(l, width, "") {
159				out = append(out, w)
160			}
161		}
162		out = append(out, "")
163	}
164	for _, tc := range v.ToolCalls {
165		out = append(out, v.renderToolCall(tc, width)...)
166		out = append(out, "")
167	}
168	if v.Err != "" {
169		out = append(out, v.Theme.FG256(v.Theme.Error, "✖ "+v.Err))
170		out = append(out, "")
171	}
172	return out, anchors
173}
174
175// refreshToolPaths rebuilds the tool_use_id -> path map from the
176// current transcript. Called once per Build() so tool result blocks
177// (which may be cached) can look up their syntax language when they
178// were originally rendered. Walking the transcript here is O(N) but
179// cheap compared to markdown/chroma work it enables.
180func (v *View) refreshToolPaths() {
181	v.toolPaths = map[string]string{}
182	for _, m := range v.Messages {
183		for _, c := range m.Content {
184			if tc, ok := c.(provider.ToolCallBlock); ok {
185				if p := pathFromToolArgs(tc.Arguments); p != "" {
186					v.toolPaths[tc.ID] = p
187				}
188			}
189		}
190	}
191}
192
193// renderMessageCached returns the rendered line slice for m, using the
194// cache if the same (content hash, width, expandAll) combination has
195// been rendered before. The slice returned is shared — callers must
196// not mutate it; Build() only ever appends to its own `out` so the
197// shared slice is safe.
198func (v *View) renderMessageCached(m provider.Message, width int) []string {
199	key := msgCacheKey{
200		hash:      hashMessage(m),
201		width:     width,
202		expandAll: v.ExpandAll,
203	}
204	if v.renderCache != nil {
205		if lines, ok := v.renderCache[key]; ok {
206			return lines
207		}
208	}
209	lines := v.renderMessage(m, width)
210	if v.renderCache != nil {
211		// Bound the cache: 4x the current message count is enough to
212		// survive /compact churn without leaking memory across a very
213		// long session.
214		max := len(v.Messages) * 4
215		if max < 32 {
216			max = 32
217		}
218		if len(v.renderCache) > max {
219			// Drop half the entries. map iteration order gives us a
220			// pseudo-LRU for free.
221			dropped := 0
222			target := len(v.renderCache) / 2
223			for k := range v.renderCache {
224				if dropped >= target {
225					break
226				}
227				delete(v.renderCache, k)
228				dropped++
229			}
230		}
231		v.renderCache[key] = lines
232	}
233	return lines
234}
235
236// hashMessage returns a 64-bit FNV-1a over the role + content blocks
237// of m. Serialising each block to its salient bytes is enough: two
238// messages with the same role and same content render identically.
239func hashMessage(m provider.Message) uint64 {
240	h := fnv64aInit
241	h = fnv64aWrite(h, []byte(m.Role))
242	h = fnv64aWriteByte(h, 0)
243	for _, c := range m.Content {
244		switch b := c.(type) {
245		case provider.TextBlock:
246			h = fnv64aWriteByte(h, 't')
247			h = fnv64aWrite(h, []byte(b.Text))
248		case provider.ImageBlock:
249			h = fnv64aWriteByte(h, 'i')
250			h = fnv64aWrite(h, []byte(b.MimeType))
251			h = fnv64aWrite(h, b.Data)
252		case provider.ToolCallBlock:
253			h = fnv64aWriteByte(h, 'c')
254			h = fnv64aWrite(h, []byte(b.ID))
255			h = fnv64aWrite(h, []byte(b.Name))
256			h = fnv64aWrite(h, []byte(b.Arguments))
257		case provider.ToolResultBlock:
258			h = fnv64aWriteByte(h, 'r')
259			h = fnv64aWrite(h, []byte(b.CallID))
260			if b.IsError {
261				h = fnv64aWriteByte(h, 'E')
262			}
263			for _, inner := range b.Content {
264				switch ib := inner.(type) {
265				case provider.TextBlock:
266					h = fnv64aWrite(h, []byte(ib.Text))
267				case provider.ImageBlock:
268					h = fnv64aWrite(h, []byte(ib.MimeType))
269					h = fnv64aWrite(h, ib.Data)
270				}
271			}
272		}
273		h = fnv64aWriteByte(h, 0)
274	}
275	return h
276}
277
278// FNV-1a implementation inlined so we don't pay the interface cost of
279// hash.Hash64 on every Build(). The whole point here is speed.
280const (
281	fnv64aInit  uint64 = 0xcbf29ce484222325
282	fnv64aPrime uint64 = 0x100000001b3
283)
284
285func fnv64aWriteByte(h uint64, b byte) uint64 {
286	h ^= uint64(b)
287	h *= fnv64aPrime
288	return h
289}
290
291func fnv64aWrite(h uint64, p []byte) uint64 {
292	for _, b := range p {
293		h ^= uint64(b)
294		h *= fnv64aPrime
295	}
296	return h
297}
298
299func (v *View) renderMessage(m provider.Message, width int) []string {
300	var lines []string
301	switch m.Role {
302	case provider.RoleUser:
303		header := v.Theme.FG256(v.Theme.User, "▍ you")
304		lines = append(lines, header)
305		for _, c := range m.Content {
306			switch b := c.(type) {
307			case provider.TextBlock:
308				for _, l := range strings.Split(b.Text, "\n") {
309					for _, w := range wrapLine(l, width-2, "  ") {
310						lines = append(lines, "  "+v.Theme.FG256(v.Theme.Muted, w))
311					}
312				}
313			case provider.ImageBlock:
314				lines = append(lines, "  "+v.Theme.FG256(v.Theme.Muted, fmt.Sprintf("[image %s, %d bytes]", b.MimeType, len(b.Data))))
315			}
316		}
317	case provider.RoleAssistant:
318		header := v.Theme.FG256(v.Theme.Assistant, "▍ zot")
319		lines = append(lines, header)
320		for _, c := range m.Content {
321			switch b := c.(type) {
322			case provider.TextBlock:
323				md := RenderMarkdown(b.Text, v.Theme, width)
324				for _, l := range strings.Split(md, "\n") {
325					for _, w := range wrapLine(l, width, "") {
326						lines = append(lines, w)
327					}
328				}
329			case provider.ToolCallBlock:
330				lines = append(lines, v.Theme.FG256(v.Theme.Tool, "▸ "+b.Name+" "+shortArgs(b.Arguments)))
331			}
332		}
333	case provider.RoleTool:
334		for _, c := range m.Content {
335			if tr, ok := c.(provider.ToolResultBlock); ok {
336				title := "  result"
337				color := v.Theme.ToolOut
338				if tr.IsError {
339					title = "  error"
340					color = v.Theme.Error
341				}
342				path := ""
343				if v.toolPaths != nil {
344					path = v.toolPaths[tr.CallID]
345				}
346				lines = append(lines, v.Theme.FG256(color, title))
347				lines = append(lines, v.renderToolResultContent(tr.Content, width, color, path)...)
348			}
349		}
350	}
351	return lines
352}
353
354func (v *View) renderToolCall(tc ToolCallView, width int) []string {
355	var lines []string
356	head := v.Theme.FG256(v.Theme.Tool, "▸ "+tc.Name+" "+tc.Args)
357	lines = append(lines, head)
358	if tc.Result != "" {
359		color := v.Theme.ToolOut
360		if tc.Error {
361			color = v.Theme.Error
362		}
363		block := toolResultBlock(v.Theme, tc.Result, width, color)
364		// Strip rules, collapse the body, put rules back on.
365		if len(block) >= 2 {
366			top, bot := block[0], block[len(block)-1]
367			body := v.collapseToolBody(block[1:len(block)-1], false)
368			block = append([]string{top}, body...)
369			block = append(block, bot)
370		}
371		lines = append(lines, block...)
372	}
373	return lines
374}
375
376// toolResultBlock wraps text in thin horizontal rules (top + bottom),
377// indenting the body with four spaces. The rules span the content column.
378// renderToolResultContent renders the body of a tool result block.
379// Text blocks get the usual rules-wrapped treatment; text that looks
380// like a unified diff gets +/- coloring. Image blocks are rendered
381// inline when the terminal supports a protocol, else as a text
382// placeholder with dimensions.
383func (v *View) renderToolResultContent(blocks []provider.Content, width, color int, sourcePath string) []string {
384	rule := v.Theme.FG256(v.Theme.Muted, strings.Repeat("─", width))
385
386	var body []string
387	hasImage := false
388	for _, b := range blocks {
389		switch bb := b.(type) {
390		case provider.TextBlock:
391			body = append(body, v.renderToolText(bb.Text, width, color, sourcePath)...)
392		case provider.ImageBlock:
393			hasImage = true
394			body = append(body, v.renderImageBlock(bb, width)...)
395		}
396	}
397	body = v.collapseToolBody(body, hasImage)
398
399	out := make([]string, 0, len(body)+2)
400	out = append(out, rule)
401	out = append(out, body...)
402	out = append(out, rule)
403	return out
404}
405
406// collapseToolBody trims lines to the configured preview size when the
407// view is not in ExpandAll mode, appending a muted "... ctrl+o to
408// expand" footer. Image blocks never collapse — they're short in text
409// rows but represent real content the user wants to see.
410func (v *View) collapseToolBody(lines []string, hasImage bool) []string {
411	if v.ExpandAll || hasImage {
412		return lines
413	}
414	if len(lines) <= ToolCollapseLines {
415		return lines
416	}
417	kept := lines[:ToolCollapsePreview]
418	hidden := len(lines) - ToolCollapsePreview
419	total := len(lines)
420	footer := fmt.Sprintf("    ... (%d more lines, %d total, ctrl+o to expand)", hidden, total)
421	footer = v.Theme.FG256(v.Theme.Muted, footer)
422	return append(append([]string(nil), kept...), footer)
423}
424
425// renderToolText renders a text block inside a tool result. If the
426// text contains a unified-diff section (lines starting with "--- " /
427// "+++ " / "+" / "-"/" "), those rows are styled with add/remove
428// colors matching git diff conventions.
429func (v *View) renderToolText(text string, width, defaultColor int, sourcePath string) []string {
430	// Detect whether the text is `read`-style numbered output
431	// ("     1\t…") so we can strip the gutter, highlight the code, and
432	// re-apply the line numbers in muted color. Runs even without a
433	// source path — language is guessed from the first line, falling
434	// back to "text" (no highlighting) if nothing obvious matches.
435	if looksLikeNumberedFile(text) {
436		return v.renderNumberedFile(text, sourcePath)
437	}
438
439	// No truncation — the full tool output is rendered into chat and
440	// becomes part of the scrollback you can page back through.
441	lines := strings.Split(text, "\n")
442
443	inDiff := false
444	oldLine, newLine := 1, 1
445	var out []string
446	for _, l := range lines {
447		// Detect diff header: "--- name" followed somewhere by "+++ name".
448		if strings.HasPrefix(l, "--- ") || strings.HasPrefix(l, "+++ ") {
449			inDiff = true
450			out = append(out, "    "+v.Theme.FG256(v.Theme.Muted, l))
451			continue
452		}
453		// Hunk header "@@ -a,b +c,d @@" resets the counters so patches
454		// that skip around in the file still get correct numbering.
455		if inDiff && strings.HasPrefix(l, "@@") {
456			if o, n, ok := parseHunkHeader(l); ok {
457				oldLine, newLine = o, n
458			}
459			out = append(out, "    "+v.Theme.FG256(v.Theme.Muted, l))
460			continue
461		}
462		if inDiff && len(l) > 0 {
463			switch l[0] {
464			case '+':
465				out = append(out, v.renderDiffRow(l, width, v.Theme.Tool, newLine, '+', sourcePath))
466				newLine++
467				continue
468			case '-':
469				out = append(out, v.renderDiffRow(l, width, v.Theme.Error, oldLine, '-', sourcePath))
470				oldLine++
471				continue
472			case ' ':
473				out = append(out, v.renderDiffRow(l, width, v.Theme.Muted, newLine, ' ', sourcePath))
474				oldLine++
475				newLine++
476				continue
477			}
478		}
479		// Regular line.
480		for _, w := range wrapLine(l, width-4, "    ") {
481			out = append(out, "    "+v.Theme.FG256(defaultColor, w))
482		}
483	}
484	return out
485}
486
487// parseHunkHeader extracts the starting old/new line from a unified
488// diff hunk header ("@@ -12,5 +12,7 @@ ..."). Returns ok=false if the
489// header is malformed or missing numbers.
490func parseHunkHeader(l string) (oldStart, newStart int, ok bool) {
491	// Skip "@@ "
492	rest := strings.TrimPrefix(l, "@@")
493	rest = strings.TrimSpace(rest)
494	if !strings.HasPrefix(rest, "-") {
495		return 0, 0, false
496	}
497	rest = rest[1:]
498	space := strings.IndexByte(rest, ' ')
499	if space < 0 {
500		return 0, 0, false
501	}
502	oldPart := rest[:space]
503	rest = strings.TrimSpace(rest[space+1:])
504	if !strings.HasPrefix(rest, "+") {
505		return 0, 0, false
506	}
507	rest = rest[1:]
508	if sp := strings.IndexAny(rest, " \t"); sp >= 0 {
509		rest = rest[:sp]
510	}
511	parseStart := func(s string) (int, bool) {
512		if c := strings.IndexByte(s, ','); c >= 0 {
513			s = s[:c]
514		}
515		n, err := strconv.Atoi(s)
516		if err != nil || n < 1 {
517			return 0, false
518		}
519		return n, true
520	}
521	o, ok1 := parseStart(oldPart)
522	n, ok2 := parseStart(rest)
523	if !ok1 || !ok2 {
524		return 0, 0, false
525	}
526	return o, n, true
527}
528
529// renderDiffRow renders one unified-diff line with a read-style gutter
530// (6-cell right-aligned line number, muted) followed by the +/-/space
531// marker and the code. Code is syntax-highlighted if sourcePath hints
532// at a known language; falls back to the plain diff color otherwise.
533func (v *View) renderDiffRow(line string, width, color int, lineNo int, mark byte, sourcePath string) string {
534	if len(line) == 0 {
535		return ""
536	}
537	code := line[1:] // strip the leading marker; we re-emit it in colour
538
539	// Syntax-highlight the code half when we know the language. Use
540	// the same HighlightCode pipeline as renderNumberedFile so the
541	// palette matches.
542	lang := LanguageFromPath(sourcePath)
543	var codeRendered string
544	if lang != "" {
545		if h := HighlightCode(code, lang); len(h) == 1 {
546			codeRendered = h[0]
547		}
548	}
549	if codeRendered == "" {
550		codeRendered = v.Theme.FG256(color, code)
551	}
552
553	gutter := v.Theme.FG256(v.Theme.Muted, fmt.Sprintf("%6d\t", lineNo))
554	marker := v.Theme.FG256(color, string(mark)+" ")
555	row := "    " + gutter + marker + codeRendered
556
557	// Cheap width clamp: truncate visible text if the raw code is too
558	// long. We work on the pre-ANSI code string because measuring ansi
559	// output is unreliable.
560	maxCode := width - 4 /* indent */ - 7 /* gutter */ - 2 /* marker */
561	if maxCode > 0 && len(code) > maxCode {
562		trunc := code[:maxCode-1] + "…"
563		if lang != "" {
564			if h := HighlightCode(trunc, lang); len(h) == 1 {
565				codeRendered = h[0]
566			} else {
567				codeRendered = v.Theme.FG256(color, trunc)
568			}
569		} else {
570			codeRendered = v.Theme.FG256(color, trunc)
571		}
572		row = "    " + gutter + marker + codeRendered
573	}
574	return row
575}
576
577// renderImageBlock returns the lines for one image, inline if possible.
578//
579// Inline image escapes paint into multiple terminal rows but the zot
580// renderer treats each slice entry as a single row. To prevent chat
581// content from being drawn on top of the image, we pad with blank rows
582// so the image's real footprint is reflected in the frame height.
583func (v *View) renderImageBlock(b provider.ImageBlock, width int) []string {
584	w, h := ImageDimensions(b.Data)
585	kb := len(b.Data) / 1024
586	info := fmt.Sprintf("  image · %s · %dx%d · %d KB", b.MimeType, w, h, kb)
587
588	if v.ImageProto != ImageProtocolNone {
589		// Clamp rendered width so the image never overflows the chat
590		// column. Subtract a 4-cell indent for the tool result block,
591		// cap at 60 cells, floor at 10.
592		cells := width - 4
593		if cells > 60 {
594			cells = 60
595		}
596		if cells < 10 {
597			cells = 10
598		}
599		const maxRows = 20
600		if seq := RenderInlineImageScaled(v.ImageProto, b.Data, b.MimeType, cells, maxRows); seq != "" {
601			rows := RowsForInlineImage(b.Data, cells, maxRows)
602			if rows < 1 {
603				rows = 1
604			}
605			out := make([]string, 0, rows+1)
606			out = append(out, "    "+seq)
607			// Reserve blank rows matching the image's on-screen height.
608			for i := 1; i < rows; i++ {
609				out = append(out, "")
610			}
611			out = append(out, v.Theme.FG256(v.Theme.Muted, info))
612			return out
613		}
614	}
615	// Text fallback.
616	return []string{v.Theme.FG256(v.Theme.Muted, info)}
617}
618
619// looksLikeNumberedFile returns true when text matches the `read`
620// tool's "     N\tcontent" format for most of its lines.
621func looksLikeNumberedFile(text string) bool {
622	lines := strings.Split(text, "\n")
623	if len(lines) == 0 {
624		return false
625	}
626	hits := 0
627	scanned := 0
628	for _, l := range lines {
629		if l == "" {
630			continue
631		}
632		scanned++
633		if scanned > 20 {
634			break
635		}
636		if numberedLineRE.MatchString(l) {
637			hits++
638		}
639	}
640	if scanned == 0 {
641		return false
642	}
643	return hits*2 >= scanned // majority of non-empty lines match
644}
645
646var numberedLineRE = regexp.MustCompile(`^\s*\d+\t`)
647
648// renderNumberedFile strips line numbers, highlights the code, and
649// re-attaches the line numbers in muted color.
650func (v *View) renderNumberedFile(text, sourcePath string) []string {
651	lines := strings.Split(text, "\n")
652	gutters := make([]string, 0, len(lines))
653	codes := make([]string, 0, len(lines))
654	for _, l := range lines {
655		idx := strings.IndexByte(l, '\t')
656		if idx < 0 || !numberedLineRE.MatchString(l) {
657			// Non-code footer (e.g. "[truncated at 2000 lines]").
658			gutters = append(gutters, "")
659			codes = append(codes, l)
660			continue
661		}
662		gutter := l[:idx+1] // keep the tab so alignment is preserved
663		code := l[idx+1:]
664		gutters = append(gutters, gutter)
665		codes = append(codes, code)
666	}
667	lang := LanguageFromPath(sourcePath)
668	var highlighted []string
669	if lang != "" {
670		highlighted = HighlightCode(strings.Join(codes, "\n"), lang)
671		// Chroma sometimes collapses the trailing empty line. Pad to
672		// align with the gutter slice so per-line zipping works.
673		for len(highlighted) < len(codes) {
674			highlighted = append(highlighted, "")
675		}
676		if len(highlighted) > len(codes) {
677			highlighted = highlighted[:len(codes)]
678		}
679	} else {
680		// No lexer for this file type — render in the ToolOut color so
681		// code is visually distinct from the muted gutter.
682		highlighted = make([]string, len(codes))
683		for i, c := range codes {
684			highlighted[i] = v.Theme.FG256(v.Theme.ToolOut, c)
685		}
686	}
687	out := make([]string, 0, len(codes))
688	for i, code := range highlighted {
689		g := gutters[i]
690		if g == "" {
691			out = append(out, "    "+v.Theme.FG256(v.Theme.Muted, code))
692			continue
693		}
694		out = append(out, "    "+v.Theme.FG256(v.Theme.Muted, g)+code)
695	}
696	return out
697}
698
699func toolResultBlock(th Theme, text string, width int, color int) []string {
700	rule := th.FG256(th.Muted, strings.Repeat("─", width))
701
702	var out []string
703	out = append(out, rule)
704	for _, l := range strings.Split(text, "\n") {
705		for _, w := range wrapLine(l, width-4, "    ") {
706			out = append(out, "    "+th.FG256(color, w))
707		}
708	}
709	out = append(out, rule)
710	return out
711}
712
713func shortArgs(raw json.RawMessage) string {
714	var v any
715	if err := json.Unmarshal(raw, &v); err != nil {
716		return ""
717	}
718	switch x := v.(type) {
719	case map[string]any:
720		for _, k := range []string{"path", "file_path", "command"} {
721			if s, ok := x[k].(string); ok {
722				if len(s) > 60 {
723					s = s[:57] + "..."
724				}
725				return s
726			}
727		}
728	}
729	b, _ := json.Marshal(v)
730	s := string(b)
731	if len(s) > 60 {
732		s = s[:57] + "..."
733	}
734	return s
735}
736
737func collectText(blocks []provider.Content) string {
738	var sb strings.Builder
739	for _, b := range blocks {
740		if tb, ok := b.(provider.TextBlock); ok {
741			if sb.Len() > 0 {
742				sb.WriteString("\n")
743			}
744			sb.WriteString(tb.Text)
745		}
746	}
747	return sb.String()
748}
749
750func truncateLines(s string, n int) string {
751	lines := strings.Split(s, "\n")
752	if len(lines) <= n {
753		return s
754	}
755	return strings.Join(lines[:n], "\n") + "\n  … (" + fmt.Sprintf("%d", len(lines)-n) + " more)"
756}
757
758// StatusBar builds the single-line status shown above the editor.
759//
760// Layout:
761//
762//	[busyPrefix]  provider-model   tokens-cost   ctrl+c hint        cwd
763//	                                                       ↑ right-aligned
764//
765// cols is the terminal width; when > 0 the cwd is placed flush-right
766// with spaces. busyPrefix, if non-empty, is injected at the far left.
767// StatusBarParams groups the many bits of state the status bar needs.
768// Grew from a flat argument list once we started matching pi's format.
769type StatusBarParams struct {
770	Theme      Theme
771	Provider   string
772	Model      string
773	Busy       bool
774	BusyPrefix string // spinner + funny line when busy
775	CWD        string
776	Locked     bool // sandbox on?
777
778	// Cumulative session usage and cost.
779	Usage provider.Usage
780	// Subscription is true when the credential is an OAuth token (claude
781	// pro/max, chatgpt plus/pro) rather than a paid api key. We still
782	// compute a cost for visibility, but pi-style we append "(sub)" so
783	// the user knows no money actually moved.
784	Subscription bool
785
786	// Last turn's input+cache tokens (approximates current live context).
787	ContextUsed int
788	ContextMax  int // model's context window; 0 disables the percentage
789
790	// AutoCompacting is true when the agent is currently running a
791	// model-triggered condense pass. Surfaces as "(auto)" after the
792	// context percentage so it's clear where the spinner is coming from.
793	AutoCompacting bool
794
795	Cols int // terminal width; drives right-alignment of cwd
796}
797
798// StatusBar builds the status shown above the editor. Returns one or
799// two lines depending on whether the (provider, model, stats, cwd)
800// payload fits the terminal width.
801//
802// Layout:
803//
804//	<busyPrefix>  (provider) model  stats   cwd   <- one line if it fits
805//
806// or, when it doesn't:
807//
808//	<busyPrefix>  (provider) model  stats        <- line 1
809//	cwd                                          <- line 2
810//
811// The right-side gap is a fixed three spaces, not a stretched-to-fill
812// fill. The old "ctrl+c exit - /help" / "esc cancel" hint is gone
813// entirely — the slash-command popup and the queued/sliding-in chips
814// already cover the discoverability of those keybindings.
815func StatusBar(p StatusBarParams) []string {
816	th := p.Theme
817
818	// Token stats: only include each segment when non-zero (pi's
819	// behavior). Keeps the bar compact on brand-new sessions.
820	var stats []string
821	if p.Usage.InputTokens > 0 {
822		stats = append(stats, fmt.Sprintf("↑%s", piFormatTokens(p.Usage.InputTokens)))
823	}
824	if p.Usage.OutputTokens > 0 {
825		stats = append(stats, fmt.Sprintf("↓%s", piFormatTokens(p.Usage.OutputTokens)))
826	}
827	if p.Usage.CacheReadTokens > 0 {
828		stats = append(stats, fmt.Sprintf("R%s", piFormatTokens(p.Usage.CacheReadTokens)))
829	}
830	if p.Usage.CacheWriteTokens > 0 {
831		stats = append(stats, fmt.Sprintf("W%s", piFormatTokens(p.Usage.CacheWriteTokens)))
832	}
833
834	// Cost: always show the dollar value computed from token counts,
835	// even on subscription — lets you see what the equivalent api cost
836	// would be (handy for gauging subscription value). Append "(sub)"
837	// only as a hint that no real money moved.
838	var costStr string
839	if p.Usage.CostUSD > 0 || p.Subscription {
840		costStr = fmt.Sprintf("$%.3f", p.Usage.CostUSD)
841		if p.Subscription {
842			costStr += " (sub)"
843		}
844	}
845	if costStr != "" {
846		stats = append(stats, costStr)
847	}
848
849	// Context %. Color-coded: yellow >70, red >90.
850	ctx, ctxColor := piContextUsage(th, p.ContextUsed, p.ContextMax)
851	if ctx != "" {
852		if p.AutoCompacting {
853			ctx += " (auto)"
854		}
855		stats = append(stats, th.FG256(ctxColor, ctx))
856	}
857
858	left := fmt.Sprintf(" (%s) %s ", p.Provider, p.Model)
859	middle := " " + strings.Join(stats, " ") + " "
860
861	var leftBuilder strings.Builder
862	if p.BusyPrefix != "" {
863		leftBuilder.WriteString(th.FG256(th.Accent, " "+p.BusyPrefix+" "))
864		leftBuilder.WriteString("  ")
865	}
866	leftBuilder.WriteString(th.FG256(th.Muted, left))
867	leftBuilder.WriteString("  ")
868	// `middle` already has colorized context segments; wrap the rest in muted.
869	leftBuilder.WriteString(th.FG256(th.Muted, middle))
870
871	cwd := shortenHome(p.CWD)
872	if p.Locked && cwd != "" {
873		cwd = "· locked · " + cwd
874	}
875
876	primary := leftBuilder.String()
877	if cwd == "" {
878		return []string{primary}
879	}
880
881	cwdRendered := th.FG256(th.Muted, cwd)
882	const gap = "   " // exactly three spaces between stats and cwd
883	combined := primary + gap + cwdRendered
884
885	// Wrap to a second line when the combined width would overflow.
886	if p.Cols > 0 && visibleWidth(combined) > p.Cols {
887		return []string{primary, cwdRendered}
888	}
889	return []string{combined}
890}
891
892// piContextUsage renders the "N%/ctxMax" fragment, returning the
893// rendered string plus the colour to wrap it in.
894func piContextUsage(th Theme, used, max int) (string, int) {
895	if max <= 0 {
896		if used <= 0 {
897			return "", th.Muted
898		}
899		return piFormatTokens(used), th.Muted
900	}
901	pct := float64(used) / float64(max) * 100
902	text := fmt.Sprintf("%.1f%%/%s", pct, piFormatTokens(max))
903	switch {
904	case pct > 90:
905		return text, th.Error
906	case pct > 70:
907		return text, th.Warning
908	}
909	return text, th.Muted
910}
911
912// piFormatTokens footer formatter:
913//
914//	< 1000      -> "42"
915//	< 10_000    -> "2.7k"
916//	< 1_000_000 -> "35k"
917//	< 10M       -> "1.1M"
918//	else        -> "12M"
919func piFormatTokens(n int) string {
920	switch {
921	case n < 0:
922		return "0"
923	case n < 1000:
924		return fmt.Sprintf("%d", n)
925	case n < 10000:
926		return fmt.Sprintf("%.1fk", float64(n)/1000)
927	case n < 1_000_000:
928		return fmt.Sprintf("%dk", (n+500)/1000)
929	case n < 10_000_000:
930		return fmt.Sprintf("%.1fM", float64(n)/1_000_000)
931	default:
932		return fmt.Sprintf("%dM", (n+500_000)/1_000_000)
933	}
934}
935
936// shortenHome replaces the user's $HOME prefix with "~" for readability.
937func shortenHome(p string) string {
938	if p == "" {
939		return ""
940	}
941	home := osUserHome()
942	if home == "" {
943		return p
944	}
945	if p == home {
946		return "~"
947	}
948	if strings.HasPrefix(p, home+"/") {
949		return "~" + p[len(home):]
950	}
951	return p
952}
953
954// osUserHome is a tiny wrapper around os.UserHomeDir so tests can mock it.
955var osUserHome = func() string {
956	if h, err := osUserHomeDir(); err == nil {
957		return h
958	}
959	return ""
960}

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