v0.0.88 2cf21d7

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	// Four-space indent matches every other tool-output row
845	// (renderRawFile, renderBashResult, diff rows, "... N more
846	// lines" footers). Keeps the image's metadata line vertically
847	// aligned with the file content above / below it.
848	info := fmt.Sprintf("    image - %s - %dx%d - %d KB", b.MimeType, w, h, kb)
849
850	if v.ImageProto != ImageProtocolNone {
851		// Clamp rendered width so the image never overflows the chat
852		// column. Subtract a 4-cell indent for the tool result block,
853		// cap at 60 cells, floor at 10.
854		cells := width - 4
855		if cells > 60 {
856			cells = 60
857		}
858		if cells < 10 {
859			cells = 10
860		}
861		const maxRows = 20
862		if seq := RenderInlineImageScaled(v.ImageProto, b.Data, b.MimeType, cells, maxRows); seq != "" {
863			rows := RowsForInlineImage(b.Data, cells, maxRows)
864			if rows < 1 {
865				rows = 1
866			}
867			out := make([]string, 0, rows+3)
868			out = append(out, "    "+seq)
869			// Reserve blank rows matching the image's on-screen
870			// height, plus one extra. RowsForInlineImage estimates
871			// the height from a fixed cell aspect ratio; real
872			// terminals differ enough that the image often spills
873			// one row past the estimate and repaints over the info
874			// line below. The extra row absorbs that spillover.
875			for i := 1; i < rows+1; i++ {
876				out = append(out, "")
877			}
878			out = append(out, v.Theme.FG256(v.Theme.Muted, info))
879			// Trailing blank so the closing rule / next block has
880			// some breathing room under the info line instead of
881			// sitting flush against it.
882			out = append(out, "")
883			return out
884		}
885	}
886	// Text fallback: same trailing blank for symmetry with the
887	// inline path, so a text-only image placeholder also gets
888	// a little space below before the next content.
889	return []string{v.Theme.FG256(v.Theme.Muted, info), ""}
890}
891
892// looksLikeNumberedFile returns true when text matches the `read`
893// tool's "     N\tcontent" format for most of its lines.
894func looksLikeNumberedFile(text string) bool {
895	lines := strings.Split(text, "\n")
896	if len(lines) == 0 {
897		return false
898	}
899	hits := 0
900	scanned := 0
901	for _, l := range lines {
902		if l == "" {
903			continue
904		}
905		scanned++
906		if scanned > 20 {
907			break
908		}
909		if numberedLineRE.MatchString(l) {
910			hits++
911		}
912	}
913	if scanned == 0 {
914		return false
915	}
916	return hits*2 >= scanned // majority of non-empty lines match
917}
918
919var numberedLineRE = regexp.MustCompile(`^\s*\d+\t`)
920
921// renderNumberedFile strips line numbers, highlights the code, and
922// re-attaches the line numbers in muted color.
923func (v *View) renderNumberedFile(text, sourcePath string) []string {
924	lines := strings.Split(text, "\n")
925	gutters := make([]string, 0, len(lines))
926	codes := make([]string, 0, len(lines))
927	for _, l := range lines {
928		idx := strings.IndexByte(l, '\t')
929		if idx < 0 || !numberedLineRE.MatchString(l) {
930			// Non-code footer (e.g. "[truncated at 2000 lines]").
931			gutters = append(gutters, "")
932			codes = append(codes, l)
933			continue
934		}
935		gutter := l[:idx+1] // keep the tab so alignment is preserved
936		code := l[idx+1:]
937		gutters = append(gutters, gutter)
938		codes = append(codes, code)
939	}
940	lang := LanguageFromPath(sourcePath)
941	var highlighted []string
942	if lang != "" {
943		highlighted = HighlightCode(strings.Join(codes, "\n"), lang)
944		// Chroma sometimes collapses the trailing empty line. Pad to
945		// align with the gutter slice so per-line zipping works.
946		for len(highlighted) < len(codes) {
947			highlighted = append(highlighted, "")
948		}
949		if len(highlighted) > len(codes) {
950			highlighted = highlighted[:len(codes)]
951		}
952	} else {
953		// No lexer for this file type — render in the ToolOut color so
954		// code is visually distinct from the muted gutter.
955		highlighted = make([]string, len(codes))
956		for i, c := range codes {
957			highlighted[i] = v.Theme.FG256(v.Theme.ToolOut, c)
958		}
959	}
960	out := make([]string, 0, len(codes))
961	for i, code := range highlighted {
962		g := gutters[i]
963		if g == "" {
964			out = append(out, "    "+v.Theme.FG256(v.Theme.Muted, code))
965			continue
966		}
967		out = append(out, "    "+v.Theme.FG256(v.Theme.Muted, g)+code)
968	}
969	return out
970}
971
972// looksLikeFileContent is a cheap guard to distinguish a read-tool
973// result from bash stdout or a status message. File content usually
974// contains characters that status messages don't (code punctuation,
975// longer lines, multiple lines) and rarely starts with the "  >"-
976// or "error:"-style prefixes tools emit. False positives are OK,
977// the worst case is a line-number gutter on something that isn't
978// really code.
979// renderBashResult styles a bash tool result: the "$ command" first
980// line in the accent color, the trailing "[exit N]  Took X.Ys" line
981// in muted type, everything else on the default tool-output color.
982// Called from renderToolText when the first line starts with "$ ".
983func (v *View) renderBashResult(lines []string, width, defaultColor int) []string {
984	// Identify the footer line (exit + timing). The bash tool writes
985	// it as the last non-empty line of the result.
986	footerIdx := -1
987	for i := len(lines) - 1; i >= 0; i-- {
988		trimmed := strings.TrimSpace(lines[i])
989		if trimmed == "" {
990			continue
991		}
992		if strings.HasPrefix(trimmed, "[exit ") {
993			footerIdx = i
994		}
995		break
996	}
997
998	var out []string
999	for i, l := range lines {
1000		switch {
1001		case i == 0 && strings.HasPrefix(l, "$ "):
1002			// Style the $ and the command text in accent. No
1003			// further processing / wrapping so the shell-style
1004			// prompt reads at a glance.
1005			for _, w := range wrapLine(l, width-4, "    ") {
1006				out = append(out, "    "+v.Theme.FG256(v.Theme.Accent, w))
1007			}
1008		case i == footerIdx:
1009			out = append(out, "    "+v.Theme.FG256(v.Theme.Muted, l))
1010		default:
1011			for _, w := range wrapLine(l, width-4, "    ") {
1012				out = append(out, "    "+v.Theme.FG256(defaultColor, w))
1013			}
1014		}
1015	}
1016	return out
1017}
1018
1019// looksLikeUnifiedDiff reports whether text is a context diff as
1020// emitted by the edit tool: rows start with '+', '-', ' ', or
1021// literal "..." (context-break marker). The presence of at least
1022// one '+' or '-' row distinguishes a real diff from an ordinary
1023// file whose lines happen to begin with a space.
1024func looksLikeUnifiedDiff(text string) bool {
1025	lines := strings.Split(text, "\n")
1026	if len(lines) < 2 {
1027		return false
1028	}
1029	sawChange := false
1030	for _, l := range lines {
1031		if l == "" {
1032			continue
1033		}
1034		if l == "..." {
1035			continue
1036		}
1037		switch l[0] {
1038		case '+', '-':
1039			sawChange = true
1040		case ' ':
1041			// context, ok
1042		default:
1043			return false
1044		}
1045	}
1046	return sawChange
1047}
1048
1049// renderUnifiedDiff renders the edit tool's context diff. Each
1050// kept row shows a line-number gutter plus a marker column: '+'
1051// for additions (colored like add), '-' for deletions (colored
1052// like remove), and unmarked context in muted type. A literal
1053// "..." line between hunks renders as an ellipsis in muted type,
1054// indicating skipped unchanged rows. The old and new line
1055// counters advance so each row carries its actual position in
1056// the pre- or post-edit file. Heuristic: when we hit a "...", we
1057// can't know where the next hunk starts, so we don't reset the
1058// counters — they stay approximate in the rare multi-hunk case.
1059func (v *View) renderUnifiedDiff(text string, width int, sourcePath string) []string {
1060	lines := strings.Split(text, "\n")
1061	if n := len(lines); n > 0 && lines[n-1] == "" {
1062		lines = lines[:n-1]
1063	}
1064	oldLine, newLine := 1, 1
1065	var out []string
1066	for _, l := range lines {
1067		if l == "" {
1068			out = append(out, "")
1069			continue
1070		}
1071		if l == "..." {
1072			out = append(out, "    "+v.Theme.FG256(v.Theme.Muted, "…"))
1073			continue
1074		}
1075		switch l[0] {
1076		case '+':
1077			out = append(out, v.renderDiffRow(l, width, v.Theme.Tool, newLine, '+', sourcePath))
1078			newLine++
1079		case '-':
1080			out = append(out, v.renderDiffRow(l, width, v.Theme.Error, oldLine, '-', sourcePath))
1081			oldLine++
1082		case ' ':
1083			out = append(out, v.renderDiffRow(l, width, v.Theme.Muted, newLine, ' ', sourcePath))
1084			oldLine++
1085			newLine++
1086		default:
1087			for _, w := range wrapLine(l, width-4, "    ") {
1088				out = append(out, "    "+v.Theme.FG256(v.Theme.Muted, w))
1089			}
1090		}
1091	}
1092	return out
1093}
1094
1095func looksLikeFileContent(text string) bool {
1096	if strings.TrimSpace(text) == "" {
1097		return false
1098	}
1099	lines := strings.Split(text, "\n")
1100	return len(lines) >= 2
1101}
1102
1103// renderRawFile renders file content received without embedded line
1104// numbers (the current read-tool output). Draws a muted gutter like
1105// "%6d \t" starting at startLine, highlights the code using the
1106// source path's language, and returns the formatted lines.
1107func (v *View) renderRawFile(text, sourcePath string, startLine int) []string {
1108	lines := strings.Split(text, "\n")
1109	// Drop the trailing empty line that Split produces when text ends
1110	// in "\n" so the gutter doesn't show a phantom last number.
1111	if n := len(lines); n > 0 && lines[n-1] == "" {
1112		lines = lines[:n-1]
1113	}
1114	// Split code from trailing footer lines ("... [truncated ...]")
1115	// so we don't number the footer.
1116	codeEnd := len(lines)
1117	for i := len(lines) - 1; i >= 0; i-- {
1118		if strings.HasPrefix(lines[i], "...") {
1119			codeEnd = i
1120			continue
1121		}
1122		break
1123	}
1124	code := lines[:codeEnd]
1125	footer := lines[codeEnd:]
1126
1127	lang := LanguageFromPath(sourcePath)
1128	var highlighted []string
1129	if lang != "" {
1130		highlighted = HighlightCode(strings.Join(code, "\n"), lang)
1131		for len(highlighted) < len(code) {
1132			highlighted = append(highlighted, "")
1133		}
1134		if len(highlighted) > len(code) {
1135			highlighted = highlighted[:len(code)]
1136		}
1137	} else {
1138		highlighted = make([]string, len(code))
1139		for i, c := range code {
1140			highlighted[i] = v.Theme.FG256(v.Theme.ToolOut, c)
1141		}
1142	}
1143
1144	out := make([]string, 0, len(lines))
1145	for i, c := range highlighted {
1146		gutter := fmt.Sprintf("%6d\t", startLine+i)
1147		out = append(out, "    "+v.Theme.FG256(v.Theme.Muted, gutter)+c)
1148	}
1149	for _, f := range footer {
1150		out = append(out, "    "+v.Theme.FG256(v.Theme.Muted, f))
1151	}
1152	return out
1153}
1154
1155// toolResultBlock renders the live tool-call result body (shown
1156// while the turn is still in flight). The rules that used to
1157// bracket this block have been dropped so the live path looks
1158// identical to the transcript rendering that replaces it when
1159// the turn ends.
1160func toolResultBlock(th Theme, text string, width int, color int) []string {
1161	var out []string
1162	for _, l := range strings.Split(text, "\n") {
1163		for _, w := range wrapLine(l, width-4, "    ") {
1164			out = append(out, "    "+th.FG256(color, w))
1165		}
1166	}
1167	return out
1168}
1169
1170// ShortArgs renders a tool call's arguments into a one-line
1171// suffix for the "tool name <args>" header. tool is the tool
1172// name so we can add shape-specific decorations: for read we
1173// append the requested line range (e.g. "path:1-200") pulled
1174// from the offset/limit args, which is useful context at a
1175// glance without expanding the result body. Other tools keep
1176// the legacy "path or command, truncated at 60 cells" shape.
1177//
1178// Exported because the interactive mode pre-populates the
1179// ToolCallView.Args field with this value as soon as the tool
1180// call is announced, so the live overlay's header matches what
1181// the finalised transcript will later render.
1182func ShortArgs(tool string, raw json.RawMessage) string {
1183	var v any
1184	if err := json.Unmarshal(raw, &v); err != nil {
1185		return ""
1186	}
1187	x, ok := v.(map[string]any)
1188	if !ok {
1189		b, _ := json.Marshal(v)
1190		s := string(b)
1191		if len(s) > 60 {
1192			s = s[:57] + "..."
1193		}
1194		return s
1195	}
1196	var primary string
1197	for _, k := range []string{"path", "file_path", "command"} {
1198		if s, ok := x[k].(string); ok {
1199			primary = s
1200			break
1201		}
1202	}
1203	if primary == "" {
1204		b, _ := json.Marshal(v)
1205		s := string(b)
1206		if len(s) > 60 {
1207			s = s[:57] + "..."
1208		}
1209		return s
1210	}
1211
1212	// Tool-specific decoration. Only the read tool gets a range
1213	// suffix for now; other tools just truncate the primary arg.
1214	suffix := ""
1215	switch strings.ToLower(tool) {
1216	case "read":
1217		start := 1
1218		if n, ok := toInt(x["offset"]); ok && n >= 1 {
1219			start = n
1220		}
1221		if lim, ok := toInt(x["limit"]); ok && lim > 0 {
1222			end := start + lim - 1
1223			suffix = fmt.Sprintf(":%d-%d", start, end)
1224		} else if start > 1 {
1225			suffix = fmt.Sprintf(":%d-", start)
1226		}
1227	}
1228
1229	// Truncate the primary arg leaving room for the suffix so the
1230	// range stays visible even on absurdly long paths.
1231	max := 60 - len(suffix)
1232	if max < 10 {
1233		max = 10
1234	}
1235	if len(primary) > max {
1236		primary = primary[:max-3] + "..."
1237	}
1238	return primary + suffix
1239}
1240
1241// toInt coerces a json.Unmarshal'd number (float64) or a string
1242// containing a number into an int. Returns ok=false if the value
1243// is neither. Used by shortArgs to survive model quirks where
1244// numeric args come back as strings.
1245func toInt(v any) (int, bool) {
1246	switch n := v.(type) {
1247	case float64:
1248		return int(n), true
1249	case int:
1250		return n, true
1251	case string:
1252		i, err := strconv.Atoi(strings.TrimSpace(n))
1253		if err != nil {
1254			return 0, false
1255		}
1256		return i, true
1257	}
1258	return 0, false
1259}
1260
1261func collectText(blocks []provider.Content) string {
1262	var sb strings.Builder
1263	for _, b := range blocks {
1264		if tb, ok := b.(provider.TextBlock); ok {
1265			if sb.Len() > 0 {
1266				sb.WriteString("\n")
1267			}
1268			sb.WriteString(tb.Text)
1269		}
1270	}
1271	return sb.String()
1272}
1273
1274func truncateLines(s string, n int) string {
1275	lines := strings.Split(s, "\n")
1276	if len(lines) <= n {
1277		return s
1278	}
1279	return strings.Join(lines[:n], "\n") + "\n  … (" + fmt.Sprintf("%d", len(lines)-n) + " more)"
1280}
1281
1282// StatusBarParams groups the many bits of state the status bar needs.
1283// Grew from a flat argument list once we settled on the layout.
1284type StatusBarParams struct {
1285	Theme      Theme
1286	Provider   string
1287	Model      string
1288	Busy       bool
1289	BusyPrefix string // spinner + funny line when busy
1290	CWD        string
1291	Locked     bool // sandbox on?
1292
1293	// Cumulative session usage and cost.
1294	Usage provider.Usage
1295	// Subscription is true when the credential is an OAuth token (claude
1296	// pro/max, chatgpt plus/pro) rather than a paid api key. We still
1297	// compute a cost for visibility and append "(sub)" so the user
1298	// knows no real money moved.
1299	Subscription bool
1300
1301	// Last turn's input+cache tokens (approximates current live context).
1302	ContextUsed int
1303	ContextMax  int // model's context window; 0 disables the percentage
1304
1305	// AutoCompacting is true when the agent is currently running a
1306	// model-triggered condense pass. Surfaces as "(auto)" after the
1307	// context percentage so it's clear where the spinner is coming from.
1308	AutoCompacting bool
1309
1310	// Telegram true when the telegram bridge is connected. Adds a
1311	// small "- tg -" tag to the cwd line so the user can tell at a
1312	// glance that dms are being mirrored into this session.
1313	Telegram bool
1314
1315	Cols int // terminal width; drives right-alignment of cwd
1316}
1317
1318// StatusBar builds the status shown above the editor. Always returns
1319// two lines when a cwd is provided: the stats on the first line, the
1320// cwd on its own line below, indented to match the stats column. This
1321// keeps the status bar stable across terminal resizes (the cwd never
1322// jumps from right-aligned-on-line-1 to flush-left-on-line-2) and
1323// makes a long cwd safe at any width.
1324//
1325// Layout:
1326//
1327//	<busyPrefix>  (provider) model  stats   <- line 1
1328//	  cwd                                   <- line 2 (2-space indent)
1329//
1330// The old "ctrl+c exit - /help" / "esc cancel" hint is gone entirely.
1331// The slash-command popup and the queued/sliding-in chips already
1332// cover the discoverability of those keybindings.
1333func StatusBar(p StatusBarParams) []string {
1334	th := p.Theme
1335
1336	// Token stats: only include each segment when non-zero. Keeps
1337	// the bar compact on brand-new sessions.
1338	var stats []string
1339	if p.Usage.InputTokens > 0 {
1340		stats = append(stats, fmt.Sprintf("↑%s", formatTokens(p.Usage.InputTokens)))
1341	}
1342	if p.Usage.OutputTokens > 0 {
1343		stats = append(stats, fmt.Sprintf("↓%s", formatTokens(p.Usage.OutputTokens)))
1344	}
1345	if p.Usage.CacheReadTokens > 0 {
1346		stats = append(stats, fmt.Sprintf("R%s", formatTokens(p.Usage.CacheReadTokens)))
1347	}
1348	if p.Usage.CacheWriteTokens > 0 {
1349		stats = append(stats, fmt.Sprintf("W%s", formatTokens(p.Usage.CacheWriteTokens)))
1350	}
1351
1352	// Cost: always show the dollar value computed from token counts,
1353	// even on subscription. Lets you see what the equivalent api cost
1354	// would be (handy for gauging subscription value). Append "(sub)"
1355	// only as a hint that no real money moved.
1356	var costStr string
1357	if p.Usage.CostUSD > 0 || p.Subscription {
1358		costStr = fmt.Sprintf("$%.3f", p.Usage.CostUSD)
1359		if p.Subscription {
1360			costStr += " (sub)"
1361		}
1362	}
1363	if costStr != "" {
1364		stats = append(stats, costStr)
1365	}
1366
1367	// Context %. Color-coded: yellow >70, red >90.
1368	ctx, ctxColor := contextUsage(th, p.ContextUsed, p.ContextMax)
1369	if ctx != "" {
1370		if p.AutoCompacting {
1371			ctx += " (auto)"
1372		}
1373		stats = append(stats, th.FG256(ctxColor, ctx))
1374	}
1375
1376	// Layout uses exactly 2 spaces of horizontal padding everywhere:
1377	//   2 spaces  (openai) gpt-5.4  $0.000 (sub) 0.0%/400k  ~/Sites/zot
1378	// matches the editor prompt's left inset so the bar lines up
1379	// vertically with the conversation column.
1380	const pad = "  " // 2 spaces
1381
1382	left := fmt.Sprintf("(%s) %s", p.Provider, p.Model)
1383	middle := strings.Join(stats, " ")
1384
1385	var leftBuilder strings.Builder
1386	if p.BusyPrefix != "" {
1387		// Don't re-color the payload itself — the caller already set
1388		// fg colors on the spinner glyph, message, and elapsed
1389		// segments. Wrapping the whole thing here would override
1390		// those choices. The pad itself needs no color (it's spaces).
1391		leftBuilder.WriteString(pad + p.BusyPrefix)
1392		// Exactly one pad (2 spaces) between the busy segment and
1393		// the provider/model block. The leading pad above covers
1394		// the left indent.
1395		leftBuilder.WriteString(pad)
1396	} else {
1397		// Idle path: a single pad of left inset so the line
1398		// aligns with the conversation column on its left edge
1399		// ("  you" / "  zot" message markers). Without the busy
1400		// prefix there's no trailing separator to double-pad.
1401		leftBuilder.WriteString(pad)
1402	}
1403	leftBuilder.WriteString(th.FG256(th.Muted, left))
1404	if middle != "" {
1405		leftBuilder.WriteString(pad)
1406		// `middle` already has colorized context segments; wrap the rest in muted.
1407		leftBuilder.WriteString(th.FG256(th.Muted, middle))
1408	}
1409
1410	cwd := shortenHome(p.CWD)
1411	tags := ""
1412	if p.Locked {
1413		tags += "- jailed "
1414	}
1415	if p.Telegram {
1416		tags += "- tg "
1417	}
1418	if tags != "" && cwd != "" {
1419		cwd = tags + "- " + cwd
1420	}
1421
1422	primary := leftBuilder.String()
1423	if cwd == "" {
1424		return []string{primary}
1425	}
1426
1427	// Second line: indent with the same 2-space pad so the cwd lines
1428	// up under the "(provider)" column on line 1.
1429	cwdRendered := pad + th.FG256(th.Muted, cwd)
1430	return []string{primary, cwdRendered}
1431}
1432
1433// contextUsage renders the "N%/ctxMax" fragment, returning the
1434// rendered string plus the colour to wrap it in.
1435func contextUsage(th Theme, used, max int) (string, int) {
1436	if max <= 0 {
1437		if used <= 0 {
1438			return "", th.Muted
1439		}
1440		return formatTokens(used), th.Muted
1441	}
1442	pct := float64(used) / float64(max) * 100
1443	text := fmt.Sprintf("%.1f%%/%s", pct, formatTokens(max))
1444	switch {
1445	case pct > 90:
1446		return text, th.Error
1447	case pct > 70:
1448		return text, th.Warning
1449	}
1450	return text, th.Muted
1451}
1452
1453// formatTokens footer formatter:
1454//
1455//	< 1000      -> "42"
1456//	< 10_000    -> "2.7k"
1457//	< 1_000_000 -> "35k"
1458//	< 10M       -> "1.1M"
1459//	else        -> "12M"
1460func formatTokens(n int) string {
1461	switch {
1462	case n < 0:
1463		return "0"
1464	case n < 1000:
1465		return fmt.Sprintf("%d", n)
1466	case n < 10000:
1467		return fmt.Sprintf("%.1fk", float64(n)/1000)
1468	case n < 1_000_000:
1469		return fmt.Sprintf("%dk", (n+500)/1000)
1470	case n < 10_000_000:
1471		return fmt.Sprintf("%.1fM", float64(n)/1_000_000)
1472	default:
1473		return fmt.Sprintf("%dM", (n+500_000)/1_000_000)
1474	}
1475}
1476
1477// shortenHome replaces the user's $HOME prefix with "~" for readability.
1478func shortenHome(p string) string {
1479	if p == "" {
1480		return ""
1481	}
1482	home := osUserHome()
1483	if home == "" {
1484		return p
1485	}
1486	if p == home {
1487		return "~"
1488	}
1489	if strings.HasPrefix(p, home+"/") {
1490		return "~" + p[len(home):]
1491	}
1492	return p
1493}
1494
1495// osUserHome is a tiny wrapper around os.UserHomeDir so tests can mock it.
1496var osUserHome = func() string {
1497	if h, err := osUserHomeDir(); err == nil {
1498		return h
1499	}
1500	return ""
1501}

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