v0.0.79 c4150ce

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

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