v0.0.71 9d0b1d0

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// maxAssistantWidth caps the rendered width of assistant prose
371// (and the code fences embedded in it) in both the finalised
372// transcript and the streaming overlay. Unbounded lines on
373// ultra-wide terminals (300+ columns) produce prose that's hard
374// to read and rule strokes that run edge-to-edge in the window.
375// Tool output (read, bash, edit diffs) is unaffected — it
376// deliberately uses the full width so long paths and diff rows
377// aren't artificially truncated.
378const maxAssistantWidth = 120
379
380// assistantBodyWidth returns the usable width for the assistant
381// message body (markdown prose + code fence rules), clamped at
382// maxAssistantWidth and at 1 so wrap helpers don't divide by
383// zero on absurdly narrow terminals. outer is the total width
384// of the column the body will sit inside (the terminal width
385// minus any surrounding indent).
386func assistantBodyWidth(outer int) int {
387	if outer > maxAssistantWidth {
388		return maxAssistantWidth
389	}
390	if outer < 1 {
391		return 1
392	}
393	return outer
394}
395
396func fnv64aWriteByte(h uint64, b byte) uint64 {
397	h ^= uint64(b)
398	h *= fnv64aPrime
399	return h
400}
401
402func fnv64aWrite(h uint64, p []byte) uint64 {
403	for _, b := range p {
404		h ^= uint64(b)
405		h *= fnv64aPrime
406	}
407	return h
408}
409
410func (v *View) renderMessage(m provider.Message, width int) []string {
411	var lines []string
412	switch m.Role {
413	case provider.RoleUser:
414		header := v.Theme.FG256(v.Theme.User, "▍ you")
415		lines = append(lines, header)
416		for _, c := range m.Content {
417			switch b := c.(type) {
418			case provider.TextBlock:
419				for _, l := range strings.Split(b.Text, "\n") {
420					for _, w := range wrapLine(l, width-2, "    ") {
421						lines = append(lines, "    "+v.Theme.FG256(v.Theme.Muted, w))
422					}
423				}
424			case provider.ImageBlock:
425				lines = append(lines, "    "+v.Theme.FG256(v.Theme.Muted, fmt.Sprintf("[image %s, %d bytes]", b.MimeType, len(b.Data))))
426			}
427		}
428	case provider.RoleAssistant:
429		header := v.Theme.FG256(v.Theme.Assistant, "▍ zot")
430		lines = append(lines, header)
431		// Indent assistant body the same 4 cells the user body uses,
432		// so the conversation column lines up vertically. The width
433		// passed into the markdown renderer / wrap is reduced by the
434		// indent so long lines wrap inside the indented column, and
435		// capped so ultra-wide terminals don't produce edge-to-edge
436		// code-fence rules or unreadably long prose lines.
437		const indent = "    "
438		inner := assistantBodyWidth(width - len(indent))
439		for _, c := range m.Content {
440			switch b := c.(type) {
441			case provider.TextBlock:
442				md := RenderMarkdown(b.Text, v.Theme, inner)
443				for _, l := range strings.Split(md, "\n") {
444					for _, w := range wrapLine(l, inner, "") {
445						lines = append(lines, indent+w)
446					}
447				}
448			case provider.ToolCallBlock:
449				// Rule above the tool header frames the call as a
450				// self-contained block separating it from the
451				// assistant prose above. The matching closing rule
452				// is emitted at the end of the tool-role message.
453				lines = append(lines, toolBlockRule(v.Theme, width))
454				lines = append(lines, indent+v.Theme.FG256(v.Theme.Tool, "▸ "+b.Name+" "+ShortArgs(b.Name, b.Arguments)))
455			}
456		}
457	case provider.RoleTool:
458		for _, c := range m.Content {
459			if tr, ok := c.(provider.ToolResultBlock); ok {
460				color := v.Theme.ToolOut
461				if tr.IsError {
462					color = v.Theme.Error
463				}
464				path := ""
465				if v.toolPaths != nil {
466					path = v.toolPaths[tr.CallID]
467				}
468				startLine := 1
469				if v.toolStartLines != nil {
470					if s := v.toolStartLines[tr.CallID]; s > 0 {
471						startLine = s
472					}
473				}
474				// Render the body directly under the tool-call
475				// header (no "result" sub-header). Errors keep a
476				// one-line header so they're distinguishable from
477				// successful output. A closing rule below the body
478				// pairs with the opening rule emitted above the
479				// tool-call header in the assistant message,
480				// framing the whole tool block.
481				if tr.IsError {
482					lines = append(lines, v.Theme.FG256(color, "  error"))
483				}
484				lines = append(lines, v.renderToolResultContent(tr.Content, width, color, path, startLine)...)
485				lines = append(lines, toolBlockRule(v.Theme, width))
486			}
487		}
488	}
489	return lines
490}
491
492func (v *View) renderToolCall(tc ToolCallView, width int) []string {
493	var lines []string
494
495	// Header. While the call is still streaming, prefer the live path
496	// extracted from the partial args so the user sees the target
497	// file as soon as it's known, even before the full JSON arrived.
498	arg := tc.Args
499	if arg == "" && tc.LivePath != "" {
500		arg = tc.LivePath
501	}
502	head := v.Theme.FG256(v.Theme.Tool, "▸ "+tc.Name+" "+arg)
503
504	// Live streaming body: pulled out of the partial JSON buffer for
505	// tools whose interesting content is a string field (currently
506	// write's `content` and edit's `new_text` chunks). The body is
507	// already framed by wrapLiveBody with top+bottom rules, so we
508	// don't add the extra toolBlockRule around it — that would
509	// produce four rules per streaming block, with a visible doubled
510	// line at the bottom.
511	if tc.Streaming && tc.Result == "" {
512		lines = append(lines, head)
513		if body := v.renderLiveToolBody(tc, width); len(body) > 0 {
514			lines = append(lines, body...)
515		}
516		return lines
517	}
518
519	// Finished tool call: frame the whole block with opening +
520	// closing rules so it stands apart from surrounding assistant
521	// prose. Matches the transcript-side framing in renderMessage.
522	lines = append(lines, toolBlockRule(v.Theme, width))
523	lines = append(lines, head)
524	if tc.Result != "" {
525		color := v.Theme.ToolOut
526		if tc.Error {
527			color = v.Theme.Error
528		}
529		body := toolResultBlock(v.Theme, tc.Result, width, color)
530		lines = append(lines, v.collapseToolBody(body, false)...)
531	}
532	lines = append(lines, toolBlockRule(v.Theme, width))
533	return lines
534}
535
536// renderLiveToolBody renders the in-flight preview of a streaming
537// tool call. Supported tools:
538//
539//   - write: shows the partial `content` field, syntax-highlighted
540//     by the target path's language.
541//   - edit:  shows the partial `newText` of the edit currently being
542//     streamed, prefixed with a "editing foo.ts (edit 2)" header so
543//     the user can see which of a multi-edit batch is in progress.
544//
545// Anything else returns nil and only the tool-call header shows.
546func (v *View) renderLiveToolBody(tc ToolCallView, width int) []string {
547	switch tc.Name {
548	case "write", "Write":
549		partial, ok, _ := ExtractPartialStringField(tc.RawJSONBuf, "content")
550		if !ok || partial == "" {
551			return nil
552		}
553		return v.wrapLiveBody(v.renderRawFile(partial, tc.LivePath, 1), width)
554	case "edit", "Edit":
555		partial, ok, _, idx := ExtractLastNewText(tc.RawJSONBuf)
556		if !ok || partial == "" {
557			return nil
558		}
559		// Header line hints which edit is streaming and, when more
560		// than one has landed, how many the model is doing.
561		hint := fmt.Sprintf("  edit %d (streaming)", idx)
562		body := []string{v.Theme.FG256(v.Theme.Muted, hint), ""}
563		body = append(body, v.renderRawFile(partial, tc.LivePath, 1)...)
564		return v.wrapLiveBody(body, width)
565	}
566	return nil
567}
568
569// wrapLiveBody wraps a list of content lines with the standard
570// wrapLiveBody wraps a list of content lines with the standard
571// tool-result rules (top + bottom), collapsing to the preview
572// height if the body is tall. Shared between write and edit
573// streaming.
574func (v *View) wrapLiveBody(body []string, width int) []string {
575	body = v.collapseToolBody(body, false)
576	rule := v.Theme.FG256(v.Theme.Muted, strings.Repeat("─", width))
577	out := make([]string, 0, len(body)+2)
578	out = append(out, rule)
579	out = append(out, body...)
580	out = append(out, rule)
581	return out
582}
583
584// toolResultBlock wraps text in thin horizontal rules (top + bottom),
585// indenting the body with four spaces. The rules span the content column.
586// toolBlockRule renders the muted horizontal separator drawn
587// above and below a tool call block. Spans the full content
588// width so it reads as a real section break in the chat
589// regardless of terminal size.
590func toolBlockRule(th Theme, width int) string {
591	w := width
592	if w < 8 {
593		w = 8
594	}
595	return th.FG256(th.Muted, strings.Repeat("─", w))
596}
597
598// renderToolResultContent renders the body of a tool result block.
599// Text blocks get the usual rules-wrapped treatment; text that looks
600// like a unified diff gets +/- coloring. Image blocks are rendered
601// inline when the terminal supports a protocol, else as a text
602// placeholder with dimensions.
603func (v *View) renderToolResultContent(blocks []provider.Content, width, color int, sourcePath string, startLine int) []string {
604	var body []string
605	hasImage := false
606	for _, b := range blocks {
607		switch bb := b.(type) {
608		case provider.TextBlock:
609			body = append(body, v.renderToolText(bb.Text, width, color, sourcePath, startLine)...)
610		case provider.ImageBlock:
611			hasImage = true
612			body = append(body, v.renderImageBlock(bb, width)...)
613		}
614	}
615	return v.collapseToolBody(body, hasImage)
616}
617
618// collapseToolBody trims lines to the configured preview size when the
619// view is not in ExpandAll mode, appending a muted "... ctrl+o to
620// expand" footer. Image blocks never collapse — they're short in text
621// rows but represent real content the user wants to see.
622func (v *View) collapseToolBody(lines []string, hasImage bool) []string {
623	if v.ExpandAll || hasImage {
624		return lines
625	}
626	if len(lines) <= ToolCollapseLines {
627		return lines
628	}
629	kept := lines[:ToolCollapsePreview]
630	hidden := len(lines) - ToolCollapsePreview
631	total := len(lines)
632	footer := fmt.Sprintf("    ... (%d more lines, %d total, ctrl+o to expand)", hidden, total)
633	footer = v.Theme.FG256(v.Theme.Muted, footer)
634	return append(append([]string(nil), kept...), footer)
635}
636
637// renderToolText renders a text block inside a tool result. If the
638// text contains a unified-diff section (lines starting with "--- " /
639// "+++ " / "+" / "-"/" "), those rows are styled with add/remove
640// colors matching git diff conventions.
641func (v *View) renderToolText(text string, width, defaultColor int, sourcePath string, startLine int) []string {
642	// Legacy path: transcripts saved before we dropped line numbers
643	// from the read tool still carry "     1\t…" prefixes. Detect and
644	// strip them, then fall through to the highlighter.
645	if looksLikeNumberedFile(text) {
646		return v.renderNumberedFile(text, sourcePath)
647	}
648	// If the result embeds a unified diff (the edit tool's output
649	// starts with a short "applied N edit(s)" line and then a
650	// standard --- / +++ / +/- patch), render the patch with
651	// add/remove coloring. This takes priority over the file-like
652	// detector below because a diff technically has many lines of
653	// "file content" but what the user cares about is what changed,
654	// not a dump of the post-edit file.
655	if looksLikeUnifiedDiff(text) {
656		return v.renderUnifiedDiff(text, width, sourcePath)
657	}
658
659	// Current path: text came from `read` as raw file bytes. When a
660	// source path is known (the call had a `path` arg), render with
661	// a synthetic line-number gutter starting at startLine so the
662	// on-screen view still looks like cat -n. Doesn't apply to non-
663	// file tool outputs (bash stdout, display notes, etc.).
664	if sourcePath != "" && looksLikeFileContent(text) {
665		return v.renderRawFile(text, sourcePath, startLine)
666	}
667
668	// No truncation — the full tool output is rendered into chat and
669	// becomes part of the scrollback you can page back through.
670	lines := strings.Split(text, "\n")
671
672	// Bash-result styling: when the first row looks like a shell
673	// prompt line ("$ ...") emitted by the bash tool, style the
674	// prompt line in accent and the trailing "[exit N]  Took X.Ys"
675	// line in muted type so the command + timing read at a glance.
676	// Everything between is left on the default tool-output color.
677	if len(lines) > 0 && strings.HasPrefix(lines[0], "$ ") {
678		return v.renderBashResult(lines, width, defaultColor)
679	}
680
681	inDiff := false
682	oldLine, newLine := 1, 1
683	var out []string
684	for _, l := range lines {
685		// Detect diff header: "--- name" followed somewhere by "+++ name".
686		if strings.HasPrefix(l, "--- ") || strings.HasPrefix(l, "+++ ") {
687			inDiff = true
688			out = append(out, "    "+v.Theme.FG256(v.Theme.Muted, l))
689			continue
690		}
691		// Hunk header "@@ -a,b +c,d @@" resets the counters so patches
692		// that skip around in the file still get correct numbering.
693		if inDiff && strings.HasPrefix(l, "@@") {
694			if o, n, ok := parseHunkHeader(l); ok {
695				oldLine, newLine = o, n
696			}
697			out = append(out, "    "+v.Theme.FG256(v.Theme.Muted, l))
698			continue
699		}
700		if inDiff && len(l) > 0 {
701			switch l[0] {
702			case '+':
703				out = append(out, v.renderDiffRow(l, width, v.Theme.Tool, newLine, '+', sourcePath))
704				newLine++
705				continue
706			case '-':
707				out = append(out, v.renderDiffRow(l, width, v.Theme.Error, oldLine, '-', sourcePath))
708				oldLine++
709				continue
710			case ' ':
711				out = append(out, v.renderDiffRow(l, width, v.Theme.Muted, newLine, ' ', sourcePath))
712				oldLine++
713				newLine++
714				continue
715			}
716		}
717		// Regular line.
718		for _, w := range wrapLine(l, width-4, "    ") {
719			out = append(out, "    "+v.Theme.FG256(defaultColor, w))
720		}
721	}
722	return out
723}
724
725// parseHunkHeader extracts the starting old/new line from a unified
726// diff hunk header ("@@ -12,5 +12,7 @@ ..."). Returns ok=false if the
727// header is malformed or missing numbers.
728func parseHunkHeader(l string) (oldStart, newStart int, ok bool) {
729	// Skip "@@ "
730	rest := strings.TrimPrefix(l, "@@")
731	rest = strings.TrimSpace(rest)
732	if !strings.HasPrefix(rest, "-") {
733		return 0, 0, false
734	}
735	rest = rest[1:]
736	space := strings.IndexByte(rest, ' ')
737	if space < 0 {
738		return 0, 0, false
739	}
740	oldPart := rest[:space]
741	rest = strings.TrimSpace(rest[space+1:])
742	if !strings.HasPrefix(rest, "+") {
743		return 0, 0, false
744	}
745	rest = rest[1:]
746	if sp := strings.IndexAny(rest, " \t"); sp >= 0 {
747		rest = rest[:sp]
748	}
749	parseStart := func(s string) (int, bool) {
750		if c := strings.IndexByte(s, ','); c >= 0 {
751			s = s[:c]
752		}
753		n, err := strconv.Atoi(s)
754		if err != nil || n < 1 {
755			return 0, false
756		}
757		return n, true
758	}
759	o, ok1 := parseStart(oldPart)
760	n, ok2 := parseStart(rest)
761	if !ok1 || !ok2 {
762		return 0, 0, false
763	}
764	return o, n, true
765}
766
767// renderDiffRow renders one unified-diff line with a read-style gutter
768// (6-cell right-aligned line number, muted) followed by the +/-/space
769// marker and the code. Code is syntax-highlighted if sourcePath hints
770// at a known language; falls back to the plain diff color otherwise.
771func (v *View) renderDiffRow(line string, width, color int, lineNo int, mark byte, sourcePath string) string {
772	if len(line) == 0 {
773		return ""
774	}
775	code := line[1:] // strip the leading marker; we re-emit it in colour
776
777	// Syntax-highlight the code half when we know the language. Use
778	// the same HighlightCode pipeline as renderNumberedFile so the
779	// palette matches.
780	lang := LanguageFromPath(sourcePath)
781	var codeRendered string
782	if lang != "" {
783		if h := HighlightCode(code, lang); len(h) == 1 {
784			codeRendered = h[0]
785		}
786	}
787	if codeRendered == "" {
788		if mark == ' ' {
789			codeRendered = v.Theme.FG256(v.Theme.Muted, code)
790		} else {
791			codeRendered = v.Theme.FG256(color, code)
792		}
793	}
794
795	// Gutter shape: sign + number share a color so they read as one
796	// visual token ("+123") instead of a neutral line number next to
797	// a stray marker. Unchanged context lines get a muted gutter and
798	// a leading space so column alignment stays consistent with +/-
799	// rows.
800	var gutterText string
801	switch mark {
802	case '+':
803		gutterText = fmt.Sprintf("+%5d\t", lineNo)
804	case '-':
805		gutterText = fmt.Sprintf("-%5d\t", lineNo)
806	default:
807		gutterText = fmt.Sprintf(" %5d\t", lineNo)
808	}
809	var gutter string
810	if mark == ' ' {
811		gutter = v.Theme.FG256(v.Theme.Muted, gutterText)
812	} else {
813		gutter = v.Theme.FG256(color, gutterText)
814	}
815	row := "    " + gutter + codeRendered
816
817	// Cheap width clamp: truncate visible text if the raw code is too
818	// long. We work on the pre-ANSI code string because measuring ansi
819	// output is unreliable.
820	maxCode := width - 4 /* indent */ - 7 /* gutter (sign+5 digits+tab) */
821	if maxCode > 0 && len(code) > maxCode {
822		trunc := code[:maxCode-1] + "…"
823		if lang != "" {
824			if h := HighlightCode(trunc, lang); len(h) == 1 {
825				codeRendered = h[0]
826			} else if mark == ' ' {
827				codeRendered = v.Theme.FG256(v.Theme.Muted, trunc)
828			} else {
829				codeRendered = v.Theme.FG256(color, trunc)
830			}
831		} else if mark == ' ' {
832			codeRendered = v.Theme.FG256(v.Theme.Muted, trunc)
833		} else {
834			codeRendered = v.Theme.FG256(color, trunc)
835		}
836		row = "    " + gutter + codeRendered
837	}
838	return row
839}
840
841// renderImageBlock returns the lines for one image, inline if possible.
842//
843// Inline image escapes paint into multiple terminal rows but the zot
844// renderer treats each slice entry as a single row. To prevent chat
845// content from being drawn on top of the image, we pad with blank rows
846// so the image's real footprint is reflected in the frame height.
847func (v *View) renderImageBlock(b provider.ImageBlock, width int) []string {
848	w, h := ImageDimensions(b.Data)
849	kb := len(b.Data) / 1024
850	info := fmt.Sprintf("  image · %s · %dx%d · %d KB", b.MimeType, w, h, kb)
851
852	if v.ImageProto != ImageProtocolNone {
853		// Clamp rendered width so the image never overflows the chat
854		// column. Subtract a 4-cell indent for the tool result block,
855		// cap at 60 cells, floor at 10.
856		cells := width - 4
857		if cells > 60 {
858			cells = 60
859		}
860		if cells < 10 {
861			cells = 10
862		}
863		const maxRows = 20
864		if seq := RenderInlineImageScaled(v.ImageProto, b.Data, b.MimeType, cells, maxRows); seq != "" {
865			rows := RowsForInlineImage(b.Data, cells, maxRows)
866			if rows < 1 {
867				rows = 1
868			}
869			out := make([]string, 0, rows+1)
870			out = append(out, "    "+seq)
871			// Reserve blank rows matching the image's on-screen height.
872			for i := 1; i < rows; i++ {
873				out = append(out, "")
874			}
875			out = append(out, v.Theme.FG256(v.Theme.Muted, info))
876			return out
877		}
878	}
879	// Text fallback.
880	return []string{v.Theme.FG256(v.Theme.Muted, info)}
881}
882
883// looksLikeNumberedFile returns true when text matches the `read`
884// tool's "     N\tcontent" format for most of its lines.
885func looksLikeNumberedFile(text string) bool {
886	lines := strings.Split(text, "\n")
887	if len(lines) == 0 {
888		return false
889	}
890	hits := 0
891	scanned := 0
892	for _, l := range lines {
893		if l == "" {
894			continue
895		}
896		scanned++
897		if scanned > 20 {
898			break
899		}
900		if numberedLineRE.MatchString(l) {
901			hits++
902		}
903	}
904	if scanned == 0 {
905		return false
906	}
907	return hits*2 >= scanned // majority of non-empty lines match
908}
909
910var numberedLineRE = regexp.MustCompile(`^\s*\d+\t`)
911
912// renderNumberedFile strips line numbers, highlights the code, and
913// re-attaches the line numbers in muted color.
914func (v *View) renderNumberedFile(text, sourcePath string) []string {
915	lines := strings.Split(text, "\n")
916	gutters := make([]string, 0, len(lines))
917	codes := make([]string, 0, len(lines))
918	for _, l := range lines {
919		idx := strings.IndexByte(l, '\t')
920		if idx < 0 || !numberedLineRE.MatchString(l) {
921			// Non-code footer (e.g. "[truncated at 2000 lines]").
922			gutters = append(gutters, "")
923			codes = append(codes, l)
924			continue
925		}
926		gutter := l[:idx+1] // keep the tab so alignment is preserved
927		code := l[idx+1:]
928		gutters = append(gutters, gutter)
929		codes = append(codes, code)
930	}
931	lang := LanguageFromPath(sourcePath)
932	var highlighted []string
933	if lang != "" {
934		highlighted = HighlightCode(strings.Join(codes, "\n"), lang)
935		// Chroma sometimes collapses the trailing empty line. Pad to
936		// align with the gutter slice so per-line zipping works.
937		for len(highlighted) < len(codes) {
938			highlighted = append(highlighted, "")
939		}
940		if len(highlighted) > len(codes) {
941			highlighted = highlighted[:len(codes)]
942		}
943	} else {
944		// No lexer for this file type — render in the ToolOut color so
945		// code is visually distinct from the muted gutter.
946		highlighted = make([]string, len(codes))
947		for i, c := range codes {
948			highlighted[i] = v.Theme.FG256(v.Theme.ToolOut, c)
949		}
950	}
951	out := make([]string, 0, len(codes))
952	for i, code := range highlighted {
953		g := gutters[i]
954		if g == "" {
955			out = append(out, "    "+v.Theme.FG256(v.Theme.Muted, code))
956			continue
957		}
958		out = append(out, "    "+v.Theme.FG256(v.Theme.Muted, g)+code)
959	}
960	return out
961}
962
963// looksLikeFileContent is a cheap guard to distinguish a read-tool
964// result from bash stdout or a status message. File content usually
965// contains characters that status messages don't (code punctuation,
966// longer lines, multiple lines) and rarely starts with the "  >"-
967// or "error:"-style prefixes tools emit. False positives are OK,
968// the worst case is a line-number gutter on something that isn't
969// really code.
970// renderBashResult styles a bash tool result: the "$ command" first
971// line in the accent color, the trailing "[exit N]  Took X.Ys" line
972// in muted type, everything else on the default tool-output color.
973// Called from renderToolText when the first line starts with "$ ".
974func (v *View) renderBashResult(lines []string, width, defaultColor int) []string {
975	// Identify the footer line (exit + timing). The bash tool writes
976	// it as the last non-empty line of the result.
977	footerIdx := -1
978	for i := len(lines) - 1; i >= 0; i-- {
979		trimmed := strings.TrimSpace(lines[i])
980		if trimmed == "" {
981			continue
982		}
983		if strings.HasPrefix(trimmed, "[exit ") {
984			footerIdx = i
985		}
986		break
987	}
988
989	var out []string
990	for i, l := range lines {
991		switch {
992		case i == 0 && strings.HasPrefix(l, "$ "):
993			// Style the $ and the command text in accent. No
994			// further processing / wrapping so the shell-style
995			// prompt reads at a glance.
996			for _, w := range wrapLine(l, width-4, "    ") {
997				out = append(out, "    "+v.Theme.FG256(v.Theme.Accent, w))
998			}
999		case i == footerIdx:
1000			out = append(out, "    "+v.Theme.FG256(v.Theme.Muted, l))
1001		default:
1002			for _, w := range wrapLine(l, width-4, "    ") {
1003				out = append(out, "    "+v.Theme.FG256(defaultColor, w))
1004			}
1005		}
1006	}
1007	return out
1008}
1009
1010// looksLikeUnifiedDiff reports whether text is a context diff as
1011// emitted by the edit tool: rows start with '+', '-', ' ', or
1012// literal "..." (context-break marker). The presence of at least
1013// one '+' or '-' row distinguishes a real diff from an ordinary
1014// file whose lines happen to begin with a space.
1015func looksLikeUnifiedDiff(text string) bool {
1016	lines := strings.Split(text, "\n")
1017	if len(lines) < 2 {
1018		return false
1019	}
1020	sawChange := false
1021	for _, l := range lines {
1022		if l == "" {
1023			continue
1024		}
1025		if l == "..." {
1026			continue
1027		}
1028		switch l[0] {
1029		case '+', '-':
1030			sawChange = true
1031		case ' ':
1032			// context, ok
1033		default:
1034			return false
1035		}
1036	}
1037	return sawChange
1038}
1039
1040// renderUnifiedDiff renders the edit tool's context diff. Each
1041// kept row shows a line-number gutter plus a marker column: '+'
1042// for additions (colored like add), '-' for deletions (colored
1043// like remove), and unmarked context in muted type. A literal
1044// "..." line between hunks renders as an ellipsis in muted type,
1045// indicating skipped unchanged rows. The old and new line
1046// counters advance so each row carries its actual position in
1047// the pre- or post-edit file. Heuristic: when we hit a "...", we
1048// can't know where the next hunk starts, so we don't reset the
1049// counters — they stay approximate in the rare multi-hunk case.
1050func (v *View) renderUnifiedDiff(text string, width int, sourcePath string) []string {
1051	lines := strings.Split(text, "\n")
1052	if n := len(lines); n > 0 && lines[n-1] == "" {
1053		lines = lines[:n-1]
1054	}
1055	oldLine, newLine := 1, 1
1056	var out []string
1057	for _, l := range lines {
1058		if l == "" {
1059			out = append(out, "")
1060			continue
1061		}
1062		if l == "..." {
1063			out = append(out, "    "+v.Theme.FG256(v.Theme.Muted, "…"))
1064			continue
1065		}
1066		switch l[0] {
1067		case '+':
1068			out = append(out, v.renderDiffRow(l, width, v.Theme.Tool, newLine, '+', sourcePath))
1069			newLine++
1070		case '-':
1071			out = append(out, v.renderDiffRow(l, width, v.Theme.Error, oldLine, '-', sourcePath))
1072			oldLine++
1073		case ' ':
1074			out = append(out, v.renderDiffRow(l, width, v.Theme.Muted, newLine, ' ', sourcePath))
1075			oldLine++
1076			newLine++
1077		default:
1078			for _, w := range wrapLine(l, width-4, "    ") {
1079				out = append(out, "    "+v.Theme.FG256(v.Theme.Muted, w))
1080			}
1081		}
1082	}
1083	return out
1084}
1085
1086func looksLikeFileContent(text string) bool {
1087	if strings.TrimSpace(text) == "" {
1088		return false
1089	}
1090	lines := strings.Split(text, "\n")
1091	return len(lines) >= 2
1092}
1093
1094// renderRawFile renders file content received without embedded line
1095// numbers (the current read-tool output). Draws a muted gutter like
1096// "%6d \t" starting at startLine, highlights the code using the
1097// source path's language, and returns the formatted lines.
1098func (v *View) renderRawFile(text, sourcePath string, startLine int) []string {
1099	lines := strings.Split(text, "\n")
1100	// Drop the trailing empty line that Split produces when text ends
1101	// in "\n" so the gutter doesn't show a phantom last number.
1102	if n := len(lines); n > 0 && lines[n-1] == "" {
1103		lines = lines[:n-1]
1104	}
1105	// Split code from trailing footer lines ("... [truncated ...]")
1106	// so we don't number the footer.
1107	codeEnd := len(lines)
1108	for i := len(lines) - 1; i >= 0; i-- {
1109		if strings.HasPrefix(lines[i], "...") {
1110			codeEnd = i
1111			continue
1112		}
1113		break
1114	}
1115	code := lines[:codeEnd]
1116	footer := lines[codeEnd:]
1117
1118	lang := LanguageFromPath(sourcePath)
1119	var highlighted []string
1120	if lang != "" {
1121		highlighted = HighlightCode(strings.Join(code, "\n"), lang)
1122		for len(highlighted) < len(code) {
1123			highlighted = append(highlighted, "")
1124		}
1125		if len(highlighted) > len(code) {
1126			highlighted = highlighted[:len(code)]
1127		}
1128	} else {
1129		highlighted = make([]string, len(code))
1130		for i, c := range code {
1131			highlighted[i] = v.Theme.FG256(v.Theme.ToolOut, c)
1132		}
1133	}
1134
1135	out := make([]string, 0, len(lines))
1136	for i, c := range highlighted {
1137		gutter := fmt.Sprintf("%6d\t", startLine+i)
1138		out = append(out, "    "+v.Theme.FG256(v.Theme.Muted, gutter)+c)
1139	}
1140	for _, f := range footer {
1141		out = append(out, "    "+v.Theme.FG256(v.Theme.Muted, f))
1142	}
1143	return out
1144}
1145
1146// toolResultBlock renders the live tool-call result body (shown
1147// while the turn is still in flight). The rules that used to
1148// bracket this block have been dropped so the live path looks
1149// identical to the transcript rendering that replaces it when
1150// the turn ends.
1151func toolResultBlock(th Theme, text string, width int, color int) []string {
1152	var out []string
1153	for _, l := range strings.Split(text, "\n") {
1154		for _, w := range wrapLine(l, width-4, "    ") {
1155			out = append(out, "    "+th.FG256(color, w))
1156		}
1157	}
1158	return out
1159}
1160
1161// ShortArgs renders a tool call's arguments into a one-line
1162// suffix for the "tool name <args>" header. tool is the tool
1163// name so we can add shape-specific decorations: for read we
1164// append the requested line range (e.g. "path:1-200") pulled
1165// from the offset/limit args, which is useful context at a
1166// glance without expanding the result body. Other tools keep
1167// the legacy "path or command, truncated at 60 cells" shape.
1168//
1169// Exported because the interactive mode pre-populates the
1170// ToolCallView.Args field with this value as soon as the tool
1171// call is announced, so the live overlay's header matches what
1172// the finalised transcript will later render.
1173func ShortArgs(tool string, raw json.RawMessage) string {
1174	var v any
1175	if err := json.Unmarshal(raw, &v); err != nil {
1176		return ""
1177	}
1178	x, ok := v.(map[string]any)
1179	if !ok {
1180		b, _ := json.Marshal(v)
1181		s := string(b)
1182		if len(s) > 60 {
1183			s = s[:57] + "..."
1184		}
1185		return s
1186	}
1187	var primary string
1188	for _, k := range []string{"path", "file_path", "command"} {
1189		if s, ok := x[k].(string); ok {
1190			primary = s
1191			break
1192		}
1193	}
1194	if primary == "" {
1195		b, _ := json.Marshal(v)
1196		s := string(b)
1197		if len(s) > 60 {
1198			s = s[:57] + "..."
1199		}
1200		return s
1201	}
1202
1203	// Tool-specific decoration. Only the read tool gets a range
1204	// suffix for now; other tools just truncate the primary arg.
1205	suffix := ""
1206	switch strings.ToLower(tool) {
1207	case "read":
1208		start := 1
1209		if n, ok := toInt(x["offset"]); ok && n >= 1 {
1210			start = n
1211		}
1212		if lim, ok := toInt(x["limit"]); ok && lim > 0 {
1213			end := start + lim - 1
1214			suffix = fmt.Sprintf(":%d-%d", start, end)
1215		} else if start > 1 {
1216			suffix = fmt.Sprintf(":%d-", start)
1217		}
1218	}
1219
1220	// Truncate the primary arg leaving room for the suffix so the
1221	// range stays visible even on absurdly long paths.
1222	max := 60 - len(suffix)
1223	if max < 10 {
1224		max = 10
1225	}
1226	if len(primary) > max {
1227		primary = primary[:max-3] + "..."
1228	}
1229	return primary + suffix
1230}
1231
1232// toInt coerces a json.Unmarshal'd number (float64) or a string
1233// containing a number into an int. Returns ok=false if the value
1234// is neither. Used by shortArgs to survive model quirks where
1235// numeric args come back as strings.
1236func toInt(v any) (int, bool) {
1237	switch n := v.(type) {
1238	case float64:
1239		return int(n), true
1240	case int:
1241		return n, true
1242	case string:
1243		i, err := strconv.Atoi(strings.TrimSpace(n))
1244		if err != nil {
1245			return 0, false
1246		}
1247		return i, true
1248	}
1249	return 0, false
1250}
1251
1252func collectText(blocks []provider.Content) string {
1253	var sb strings.Builder
1254	for _, b := range blocks {
1255		if tb, ok := b.(provider.TextBlock); ok {
1256			if sb.Len() > 0 {
1257				sb.WriteString("\n")
1258			}
1259			sb.WriteString(tb.Text)
1260		}
1261	}
1262	return sb.String()
1263}
1264
1265func truncateLines(s string, n int) string {
1266	lines := strings.Split(s, "\n")
1267	if len(lines) <= n {
1268		return s
1269	}
1270	return strings.Join(lines[:n], "\n") + "\n  … (" + fmt.Sprintf("%d", len(lines)-n) + " more)"
1271}
1272
1273// StatusBarParams groups the many bits of state the status bar needs.
1274// Grew from a flat argument list once we settled on the layout.
1275type StatusBarParams struct {
1276	Theme      Theme
1277	Provider   string
1278	Model      string
1279	Busy       bool
1280	BusyPrefix string // spinner + funny line when busy
1281	CWD        string
1282	Locked     bool // sandbox on?
1283
1284	// Cumulative session usage and cost.
1285	Usage provider.Usage
1286	// Subscription is true when the credential is an OAuth token (claude
1287	// pro/max, chatgpt plus/pro) rather than a paid api key. We still
1288	// compute a cost for visibility and append "(sub)" so the user
1289	// knows no real money moved.
1290	Subscription bool
1291
1292	// Last turn's input+cache tokens (approximates current live context).
1293	ContextUsed int
1294	ContextMax  int // model's context window; 0 disables the percentage
1295
1296	// AutoCompacting is true when the agent is currently running a
1297	// model-triggered condense pass. Surfaces as "(auto)" after the
1298	// context percentage so it's clear where the spinner is coming from.
1299	AutoCompacting bool
1300
1301	// Telegram true when the telegram bridge is connected. Adds a
1302	// small "· tg ·" tag to the cwd line so the user can tell at a
1303	// glance that dms are being mirrored into this session.
1304	Telegram bool
1305
1306	Cols int // terminal width; drives right-alignment of cwd
1307}
1308
1309// StatusBar builds the status shown above the editor. Always returns
1310// two lines when a cwd is provided: the stats on the first line, the
1311// cwd on its own line below, indented to match the stats column. This
1312// keeps the status bar stable across terminal resizes (the cwd never
1313// jumps from right-aligned-on-line-1 to flush-left-on-line-2) and
1314// makes a long cwd safe at any width.
1315//
1316// Layout:
1317//
1318//	<busyPrefix>  (provider) model  stats   <- line 1
1319//	  cwd                                   <- line 2 (2-space indent)
1320//
1321// The old "ctrl+c exit - /help" / "esc cancel" hint is gone entirely.
1322// The slash-command popup and the queued/sliding-in chips already
1323// cover the discoverability of those keybindings.
1324func StatusBar(p StatusBarParams) []string {
1325	th := p.Theme
1326
1327	// Token stats: only include each segment when non-zero. Keeps
1328	// the bar compact on brand-new sessions.
1329	var stats []string
1330	if p.Usage.InputTokens > 0 {
1331		stats = append(stats, fmt.Sprintf("↑%s", formatTokens(p.Usage.InputTokens)))
1332	}
1333	if p.Usage.OutputTokens > 0 {
1334		stats = append(stats, fmt.Sprintf("↓%s", formatTokens(p.Usage.OutputTokens)))
1335	}
1336	if p.Usage.CacheReadTokens > 0 {
1337		stats = append(stats, fmt.Sprintf("R%s", formatTokens(p.Usage.CacheReadTokens)))
1338	}
1339	if p.Usage.CacheWriteTokens > 0 {
1340		stats = append(stats, fmt.Sprintf("W%s", formatTokens(p.Usage.CacheWriteTokens)))
1341	}
1342
1343	// Cost: always show the dollar value computed from token counts,
1344	// even on subscription. Lets you see what the equivalent api cost
1345	// would be (handy for gauging subscription value). Append "(sub)"
1346	// only as a hint that no real money moved.
1347	var costStr string
1348	if p.Usage.CostUSD > 0 || p.Subscription {
1349		costStr = fmt.Sprintf("$%.3f", p.Usage.CostUSD)
1350		if p.Subscription {
1351			costStr += " (sub)"
1352		}
1353	}
1354	if costStr != "" {
1355		stats = append(stats, costStr)
1356	}
1357
1358	// Context %. Color-coded: yellow >70, red >90.
1359	ctx, ctxColor := contextUsage(th, p.ContextUsed, p.ContextMax)
1360	if ctx != "" {
1361		if p.AutoCompacting {
1362			ctx += " (auto)"
1363		}
1364		stats = append(stats, th.FG256(ctxColor, ctx))
1365	}
1366
1367	// Layout uses exactly 2 spaces of horizontal padding everywhere:
1368	//   2 spaces  (openai) gpt-5.4  $0.000 (sub) 0.0%/400k  ~/Sites/zot
1369	// matches the editor prompt's left inset so the bar lines up
1370	// vertically with the conversation column.
1371	const pad = "  " // 2 spaces
1372
1373	left := fmt.Sprintf("(%s) %s", p.Provider, p.Model)
1374	middle := strings.Join(stats, " ")
1375
1376	var leftBuilder strings.Builder
1377	if p.BusyPrefix != "" {
1378		// Don't re-color the payload itself — the caller already set
1379		// fg colors on the spinner glyph, message, and elapsed
1380		// segments. Wrapping the whole thing here would override
1381		// those choices. The pad itself needs no color (it's spaces).
1382		leftBuilder.WriteString(pad + p.BusyPrefix)
1383		leftBuilder.WriteString(pad)
1384	}
1385	leftBuilder.WriteString(pad)
1386	leftBuilder.WriteString(th.FG256(th.Muted, left))
1387	if middle != "" {
1388		leftBuilder.WriteString(pad)
1389		// `middle` already has colorized context segments; wrap the rest in muted.
1390		leftBuilder.WriteString(th.FG256(th.Muted, middle))
1391	}
1392
1393	cwd := shortenHome(p.CWD)
1394	tags := ""
1395	if p.Locked {
1396		tags += "· jailed "
1397	}
1398	if p.Telegram {
1399		tags += "· tg "
1400	}
1401	if tags != "" && cwd != "" {
1402		cwd = tags + "· " + cwd
1403	}
1404
1405	primary := leftBuilder.String()
1406	if cwd == "" {
1407		return []string{primary}
1408	}
1409
1410	// Second line: indent with the same 2-space pad so the cwd lines
1411	// up under the "(provider)" column on line 1.
1412	cwdRendered := pad + th.FG256(th.Muted, cwd)
1413	return []string{primary, cwdRendered}
1414}
1415
1416// contextUsage renders the "N%/ctxMax" fragment, returning the
1417// rendered string plus the colour to wrap it in.
1418func contextUsage(th Theme, used, max int) (string, int) {
1419	if max <= 0 {
1420		if used <= 0 {
1421			return "", th.Muted
1422		}
1423		return formatTokens(used), th.Muted
1424	}
1425	pct := float64(used) / float64(max) * 100
1426	text := fmt.Sprintf("%.1f%%/%s", pct, formatTokens(max))
1427	switch {
1428	case pct > 90:
1429		return text, th.Error
1430	case pct > 70:
1431		return text, th.Warning
1432	}
1433	return text, th.Muted
1434}
1435
1436// formatTokens footer formatter:
1437//
1438//	< 1000      -> "42"
1439//	< 10_000    -> "2.7k"
1440//	< 1_000_000 -> "35k"
1441//	< 10M       -> "1.1M"
1442//	else        -> "12M"
1443func formatTokens(n int) string {
1444	switch {
1445	case n < 0:
1446		return "0"
1447	case n < 1000:
1448		return fmt.Sprintf("%d", n)
1449	case n < 10000:
1450		return fmt.Sprintf("%.1fk", float64(n)/1000)
1451	case n < 1_000_000:
1452		return fmt.Sprintf("%dk", (n+500)/1000)
1453	case n < 10_000_000:
1454		return fmt.Sprintf("%.1fM", float64(n)/1_000_000)
1455	default:
1456		return fmt.Sprintf("%dM", (n+500_000)/1_000_000)
1457	}
1458}
1459
1460// shortenHome replaces the user's $HOME prefix with "~" for readability.
1461func shortenHome(p string) string {
1462	if p == "" {
1463		return ""
1464	}
1465	home := osUserHome()
1466	if home == "" {
1467		return p
1468	}
1469	if p == home {
1470		return "~"
1471	}
1472	if strings.HasPrefix(p, home+"/") {
1473		return "~" + p[len(home):]
1474	}
1475	return p
1476}
1477
1478// osUserHome is a tiny wrapper around os.UserHomeDir so tests can mock it.
1479var osUserHome = func() string {
1480	if h, err := osUserHomeDir(); err == nil {
1481		return h
1482	}
1483	return ""
1484}

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