1package tui
2
3import (
4 "encoding/json"
5 "fmt"
6 "os"
7 "regexp"
8 "strconv"
9 "strings"
10
11 "github.com/patriceckhart/zot/internal/provider"
12)
13
14// pathFromToolArgs returns the "path" argument from a tool_call's
15// JSON arguments, or "" if the args aren't a JSON object or don't
16// include one. Used to pick a syntax language for rendering the
17// corresponding tool_result.
18func pathFromToolArgs(raw json.RawMessage) string {
19 if len(raw) == 0 {
20 return ""
21 }
22 var m map[string]any
23 if err := json.Unmarshal(raw, &m); err != nil {
24 return ""
25 }
26 for _, k := range []string{"path", "file_path"} {
27 if s, ok := m[k].(string); ok && s != "" {
28 return s
29 }
30 }
31 return ""
32}
33
34// osUserHomeDir is aliased so the test file can swap it.
35var osUserHomeDir = os.UserHomeDir
36
37// View turns a transcript + live state into a slice of styled lines,
38// already wrapped to width.
39type View struct {
40 Theme Theme
41 ImageProto ImageProtocol // how to render inline images in this terminal
42 Messages []provider.Message
43 // toolPaths maps tool_use_id to the "path" argument of the call, if
44 // any, so tool_result rendering can pick the right syntax language.
45 // Rebuilt on each Build().
46 toolPaths map[string]string
47 Streaming string // current assistant text delta
48 StreamingActive bool
49 ToolCalls []ToolCallView // tool calls in flight or completed
50 StatusLine string
51 Err string
52
53 // ExpandAll forces every long tool result to render in full.
54 // Toggled from the tui by ctrl+o. When false, results longer than
55 // ToolCollapseLines collapse to ToolCollapsePreview lines plus a
56 // "... (N more lines, M total, ctrl+o to expand)" footer.
57 ExpandAll bool
58}
59
60// ToolCollapsePreview is the number of lines shown before a long tool
61// result is replaced with a "... ctrl+o to expand" footer. Tool
62// results shorter than ToolCollapseLines always render in full.
63const (
64 ToolCollapsePreview = 10
65 ToolCollapseLines = 12
66)
67
68// ToolCallView is a pending tool invocation plus optional result.
69type ToolCallView struct {
70 ID string
71 Name string
72 Args string // rendered argument summary
73 Result string // rendered result preview (truncated)
74 Error bool
75 Done bool
76}
77
78// Build returns the chat log lines for the given width.
79func (v *View) Build(width int) []string {
80 // Map tool_use_id -> path argument, if any, so tool results can be
81 // rendered with the file's language for syntax highlighting.
82 v.toolPaths = map[string]string{}
83 for _, m := range v.Messages {
84 for _, c := range m.Content {
85 if tc, ok := c.(provider.ToolCallBlock); ok {
86 if p := pathFromToolArgs(tc.Arguments); p != "" {
87 v.toolPaths[tc.ID] = p
88 }
89 }
90 }
91 }
92
93 var out []string
94 for _, m := range v.Messages {
95 out = append(out, v.renderMessage(m, width)...)
96 out = append(out, "")
97 }
98 if v.StreamingActive {
99 out = append(out, v.Theme.FG256(v.Theme.Assistant, "▍ zot"))
100 // Stream the partial assistant text through the same markdown
101 // renderer used for finalised messages so code fences, diffs,
102 // lists, and inline styles look the same while streaming and
103 // don't suddenly reflow when the turn ends.
104 md := RenderMarkdown(v.Streaming, v.Theme, width)
105 for _, l := range strings.Split(md, "\n") {
106 for _, w := range wrapLine(l, width, "") {
107 out = append(out, w)
108 }
109 }
110 out = append(out, "")
111 }
112 for _, tc := range v.ToolCalls {
113 out = append(out, v.renderToolCall(tc, width)...)
114 out = append(out, "")
115 }
116 if v.Err != "" {
117 out = append(out, v.Theme.FG256(v.Theme.Error, "✖ "+v.Err))
118 out = append(out, "")
119 }
120 return out
121}
122
123func (v *View) renderMessage(m provider.Message, width int) []string {
124 var lines []string
125 switch m.Role {
126 case provider.RoleUser:
127 header := v.Theme.FG256(v.Theme.User, "▍ you")
128 lines = append(lines, header)
129 for _, c := range m.Content {
130 switch b := c.(type) {
131 case provider.TextBlock:
132 for _, l := range strings.Split(b.Text, "\n") {
133 for _, w := range wrapLine(l, width-2, " ") {
134 lines = append(lines, " "+v.Theme.FG256(v.Theme.Muted, w))
135 }
136 }
137 case provider.ImageBlock:
138 lines = append(lines, " "+v.Theme.FG256(v.Theme.Muted, fmt.Sprintf("[image %s, %d bytes]", b.MimeType, len(b.Data))))
139 }
140 }
141 case provider.RoleAssistant:
142 header := v.Theme.FG256(v.Theme.Assistant, "▍ zot")
143 lines = append(lines, header)
144 for _, c := range m.Content {
145 switch b := c.(type) {
146 case provider.TextBlock:
147 md := RenderMarkdown(b.Text, v.Theme, width)
148 for _, l := range strings.Split(md, "\n") {
149 for _, w := range wrapLine(l, width, "") {
150 lines = append(lines, w)
151 }
152 }
153 case provider.ToolCallBlock:
154 lines = append(lines, v.Theme.FG256(v.Theme.Tool, "▸ "+b.Name+" "+shortArgs(b.Arguments)))
155 }
156 }
157 case provider.RoleTool:
158 for _, c := range m.Content {
159 if tr, ok := c.(provider.ToolResultBlock); ok {
160 title := " result"
161 color := v.Theme.ToolOut
162 if tr.IsError {
163 title = " error"
164 color = v.Theme.Error
165 }
166 path := ""
167 if v.toolPaths != nil {
168 path = v.toolPaths[tr.CallID]
169 }
170 lines = append(lines, v.Theme.FG256(color, title))
171 lines = append(lines, v.renderToolResultContent(tr.Content, width, color, path)...)
172 }
173 }
174 }
175 return lines
176}
177
178func (v *View) renderToolCall(tc ToolCallView, width int) []string {
179 var lines []string
180 head := v.Theme.FG256(v.Theme.Tool, "▸ "+tc.Name+" "+tc.Args)
181 lines = append(lines, head)
182 if tc.Result != "" {
183 color := v.Theme.ToolOut
184 if tc.Error {
185 color = v.Theme.Error
186 }
187 block := toolResultBlock(v.Theme, tc.Result, width, color)
188 // Strip rules, collapse the body, put rules back on.
189 if len(block) >= 2 {
190 top, bot := block[0], block[len(block)-1]
191 body := v.collapseToolBody(block[1:len(block)-1], false)
192 block = append([]string{top}, body...)
193 block = append(block, bot)
194 }
195 lines = append(lines, block...)
196 }
197 return lines
198}
199
200// toolResultBlock wraps text in thin horizontal rules (top + bottom),
201// indenting the body with four spaces. The rules span the content column.
202// renderToolResultContent renders the body of a tool result block.
203// Text blocks get the usual rules-wrapped treatment; text that looks
204// like a unified diff gets +/- coloring. Image blocks are rendered
205// inline when the terminal supports a protocol, else as a text
206// placeholder with dimensions.
207func (v *View) renderToolResultContent(blocks []provider.Content, width, color int, sourcePath string) []string {
208 rule := v.Theme.FG256(v.Theme.Muted, strings.Repeat("─", width))
209
210 var body []string
211 hasImage := false
212 for _, b := range blocks {
213 switch bb := b.(type) {
214 case provider.TextBlock:
215 body = append(body, v.renderToolText(bb.Text, width, color, sourcePath)...)
216 case provider.ImageBlock:
217 hasImage = true
218 body = append(body, v.renderImageBlock(bb, width)...)
219 }
220 }
221 body = v.collapseToolBody(body, hasImage)
222
223 out := make([]string, 0, len(body)+2)
224 out = append(out, rule)
225 out = append(out, body...)
226 out = append(out, rule)
227 return out
228}
229
230// collapseToolBody trims lines to the configured preview size when the
231// view is not in ExpandAll mode, appending a muted "... ctrl+o to
232// expand" footer. Image blocks never collapse — they're short in text
233// rows but represent real content the user wants to see.
234func (v *View) collapseToolBody(lines []string, hasImage bool) []string {
235 if v.ExpandAll || hasImage {
236 return lines
237 }
238 if len(lines) <= ToolCollapseLines {
239 return lines
240 }
241 kept := lines[:ToolCollapsePreview]
242 hidden := len(lines) - ToolCollapsePreview
243 total := len(lines)
244 footer := fmt.Sprintf(" ... (%d more lines, %d total, ctrl+o to expand)", hidden, total)
245 footer = v.Theme.FG256(v.Theme.Muted, footer)
246 return append(append([]string(nil), kept...), footer)
247}
248
249// renderToolText renders a text block inside a tool result. If the
250// text contains a unified-diff section (lines starting with "--- " /
251// "+++ " / "+" / "-"/" "), those rows are styled with add/remove
252// colors matching git diff conventions.
253func (v *View) renderToolText(text string, width, defaultColor int, sourcePath string) []string {
254 // Detect whether the text is `read`-style numbered output
255 // (" 1\t…") so we can strip the gutter, highlight the code, and
256 // re-apply the line numbers in muted color. Runs even without a
257 // source path — language is guessed from the first line, falling
258 // back to "text" (no highlighting) if nothing obvious matches.
259 if looksLikeNumberedFile(text) {
260 return v.renderNumberedFile(text, sourcePath)
261 }
262
263 // No truncation — the full tool output is rendered into chat and
264 // becomes part of the scrollback you can page back through.
265 lines := strings.Split(text, "\n")
266
267 inDiff := false
268 oldLine, newLine := 1, 1
269 var out []string
270 for _, l := range lines {
271 // Detect diff header: "--- name" followed somewhere by "+++ name".
272 if strings.HasPrefix(l, "--- ") || strings.HasPrefix(l, "+++ ") {
273 inDiff = true
274 out = append(out, " "+v.Theme.FG256(v.Theme.Muted, l))
275 continue
276 }
277 // Hunk header "@@ -a,b +c,d @@" resets the counters so patches
278 // that skip around in the file still get correct numbering.
279 if inDiff && strings.HasPrefix(l, "@@") {
280 if o, n, ok := parseHunkHeader(l); ok {
281 oldLine, newLine = o, n
282 }
283 out = append(out, " "+v.Theme.FG256(v.Theme.Muted, l))
284 continue
285 }
286 if inDiff && len(l) > 0 {
287 switch l[0] {
288 case '+':
289 out = append(out, v.renderDiffRow(l, width, v.Theme.Tool, newLine, '+', sourcePath))
290 newLine++
291 continue
292 case '-':
293 out = append(out, v.renderDiffRow(l, width, v.Theme.Error, oldLine, '-', sourcePath))
294 oldLine++
295 continue
296 case ' ':
297 out = append(out, v.renderDiffRow(l, width, v.Theme.Muted, newLine, ' ', sourcePath))
298 oldLine++
299 newLine++
300 continue
301 }
302 }
303 // Regular line.
304 for _, w := range wrapLine(l, width-4, " ") {
305 out = append(out, " "+v.Theme.FG256(defaultColor, w))
306 }
307 }
308 return out
309}
310
311// parseHunkHeader extracts the starting old/new line from a unified
312// diff hunk header ("@@ -12,5 +12,7 @@ ..."). Returns ok=false if the
313// header is malformed or missing numbers.
314func parseHunkHeader(l string) (oldStart, newStart int, ok bool) {
315 // Skip "@@ "
316 rest := strings.TrimPrefix(l, "@@")
317 rest = strings.TrimSpace(rest)
318 if !strings.HasPrefix(rest, "-") {
319 return 0, 0, false
320 }
321 rest = rest[1:]
322 space := strings.IndexByte(rest, ' ')
323 if space < 0 {
324 return 0, 0, false
325 }
326 oldPart := rest[:space]
327 rest = strings.TrimSpace(rest[space+1:])
328 if !strings.HasPrefix(rest, "+") {
329 return 0, 0, false
330 }
331 rest = rest[1:]
332 if sp := strings.IndexAny(rest, " \t"); sp >= 0 {
333 rest = rest[:sp]
334 }
335 parseStart := func(s string) (int, bool) {
336 if c := strings.IndexByte(s, ','); c >= 0 {
337 s = s[:c]
338 }
339 n, err := strconv.Atoi(s)
340 if err != nil || n < 1 {
341 return 0, false
342 }
343 return n, true
344 }
345 o, ok1 := parseStart(oldPart)
346 n, ok2 := parseStart(rest)
347 if !ok1 || !ok2 {
348 return 0, 0, false
349 }
350 return o, n, true
351}
352
353// renderDiffRow renders one unified-diff line with a read-style gutter
354// (6-cell right-aligned line number, muted) followed by the +/-/space
355// marker and the code. Code is syntax-highlighted if sourcePath hints
356// at a known language; falls back to the plain diff color otherwise.
357func (v *View) renderDiffRow(line string, width, color int, lineNo int, mark byte, sourcePath string) string {
358 if len(line) == 0 {
359 return ""
360 }
361 code := line[1:] // strip the leading marker; we re-emit it in colour
362
363 // Syntax-highlight the code half when we know the language. Use
364 // the same HighlightCode pipeline as renderNumberedFile so the
365 // palette matches.
366 lang := LanguageFromPath(sourcePath)
367 var codeRendered string
368 if lang != "" {
369 if h := HighlightCode(code, lang); len(h) == 1 {
370 codeRendered = h[0]
371 }
372 }
373 if codeRendered == "" {
374 codeRendered = v.Theme.FG256(color, code)
375 }
376
377 gutter := v.Theme.FG256(v.Theme.Muted, fmt.Sprintf("%6d\t", lineNo))
378 marker := v.Theme.FG256(color, string(mark)+" ")
379 row := " " + gutter + marker + codeRendered
380
381 // Cheap width clamp: truncate visible text if the raw code is too
382 // long. We work on the pre-ANSI code string because measuring ansi
383 // output is unreliable.
384 maxCode := width - 4 /* indent */ - 7 /* gutter */ - 2 /* marker */
385 if maxCode > 0 && len(code) > maxCode {
386 trunc := code[:maxCode-1] + "…"
387 if lang != "" {
388 if h := HighlightCode(trunc, lang); len(h) == 1 {
389 codeRendered = h[0]
390 } else {
391 codeRendered = v.Theme.FG256(color, trunc)
392 }
393 } else {
394 codeRendered = v.Theme.FG256(color, trunc)
395 }
396 row = " " + gutter + marker + codeRendered
397 }
398 return row
399}
400
401// renderImageBlock returns the lines for one image, inline if possible.
402//
403// Inline image escapes paint into multiple terminal rows but the zot
404// renderer treats each slice entry as a single row. To prevent chat
405// content from being drawn on top of the image, we pad with blank rows
406// so the image's real footprint is reflected in the frame height.
407func (v *View) renderImageBlock(b provider.ImageBlock, width int) []string {
408 w, h := ImageDimensions(b.Data)
409 kb := len(b.Data) / 1024
410 info := fmt.Sprintf(" image · %s · %dx%d · %d KB", b.MimeType, w, h, kb)
411
412 if v.ImageProto != ImageProtocolNone {
413 // Clamp rendered width so the image never overflows the chat
414 // column. Subtract a 4-cell indent for the tool result block,
415 // cap at 60 cells, floor at 10.
416 cells := width - 4
417 if cells > 60 {
418 cells = 60
419 }
420 if cells < 10 {
421 cells = 10
422 }
423 const maxRows = 20
424 if seq := RenderInlineImageScaled(v.ImageProto, b.Data, b.MimeType, cells, maxRows); seq != "" {
425 rows := RowsForInlineImage(b.Data, cells, maxRows)
426 if rows < 1 {
427 rows = 1
428 }
429 out := make([]string, 0, rows+1)
430 out = append(out, " "+seq)
431 // Reserve blank rows matching the image's on-screen height.
432 for i := 1; i < rows; i++ {
433 out = append(out, "")
434 }
435 out = append(out, v.Theme.FG256(v.Theme.Muted, info))
436 return out
437 }
438 }
439 // Text fallback.
440 return []string{v.Theme.FG256(v.Theme.Muted, info)}
441}
442
443// looksLikeNumberedFile returns true when text matches the `read`
444// tool's " N\tcontent" format for most of its lines.
445func looksLikeNumberedFile(text string) bool {
446 lines := strings.Split(text, "\n")
447 if len(lines) == 0 {
448 return false
449 }
450 hits := 0
451 scanned := 0
452 for _, l := range lines {
453 if l == "" {
454 continue
455 }
456 scanned++
457 if scanned > 20 {
458 break
459 }
460 if numberedLineRE.MatchString(l) {
461 hits++
462 }
463 }
464 if scanned == 0 {
465 return false
466 }
467 return hits*2 >= scanned // majority of non-empty lines match
468}
469
470var numberedLineRE = regexp.MustCompile(`^\s*\d+\t`)
471
472// renderNumberedFile strips line numbers, highlights the code, and
473// re-attaches the line numbers in muted color.
474func (v *View) renderNumberedFile(text, sourcePath string) []string {
475 lines := strings.Split(text, "\n")
476 gutters := make([]string, 0, len(lines))
477 codes := make([]string, 0, len(lines))
478 for _, l := range lines {
479 idx := strings.IndexByte(l, '\t')
480 if idx < 0 || !numberedLineRE.MatchString(l) {
481 // Non-code footer (e.g. "[truncated at 2000 lines]").
482 gutters = append(gutters, "")
483 codes = append(codes, l)
484 continue
485 }
486 gutter := l[:idx+1] // keep the tab so alignment is preserved
487 code := l[idx+1:]
488 gutters = append(gutters, gutter)
489 codes = append(codes, code)
490 }
491 lang := LanguageFromPath(sourcePath)
492 var highlighted []string
493 if lang != "" {
494 highlighted = HighlightCode(strings.Join(codes, "\n"), lang)
495 // Chroma sometimes collapses the trailing empty line. Pad to
496 // align with the gutter slice so per-line zipping works.
497 for len(highlighted) < len(codes) {
498 highlighted = append(highlighted, "")
499 }
500 if len(highlighted) > len(codes) {
501 highlighted = highlighted[:len(codes)]
502 }
503 } else {
504 // No lexer for this file type — render in the ToolOut color so
505 // code is visually distinct from the muted gutter.
506 highlighted = make([]string, len(codes))
507 for i, c := range codes {
508 highlighted[i] = v.Theme.FG256(v.Theme.ToolOut, c)
509 }
510 }
511 out := make([]string, 0, len(codes))
512 for i, code := range highlighted {
513 g := gutters[i]
514 if g == "" {
515 out = append(out, " "+v.Theme.FG256(v.Theme.Muted, code))
516 continue
517 }
518 out = append(out, " "+v.Theme.FG256(v.Theme.Muted, g)+code)
519 }
520 return out
521}
522
523func toolResultBlock(th Theme, text string, width int, color int) []string {
524 rule := th.FG256(th.Muted, strings.Repeat("─", width))
525
526 var out []string
527 out = append(out, rule)
528 for _, l := range strings.Split(text, "\n") {
529 for _, w := range wrapLine(l, width-4, " ") {
530 out = append(out, " "+th.FG256(color, w))
531 }
532 }
533 out = append(out, rule)
534 return out
535}
536
537func shortArgs(raw json.RawMessage) string {
538 var v any
539 if err := json.Unmarshal(raw, &v); err != nil {
540 return ""
541 }
542 switch x := v.(type) {
543 case map[string]any:
544 for _, k := range []string{"path", "file_path", "command"} {
545 if s, ok := x[k].(string); ok {
546 if len(s) > 60 {
547 s = s[:57] + "..."
548 }
549 return s
550 }
551 }
552 }
553 b, _ := json.Marshal(v)
554 s := string(b)
555 if len(s) > 60 {
556 s = s[:57] + "..."
557 }
558 return s
559}
560
561func collectText(blocks []provider.Content) string {
562 var sb strings.Builder
563 for _, b := range blocks {
564 if tb, ok := b.(provider.TextBlock); ok {
565 if sb.Len() > 0 {
566 sb.WriteString("\n")
567 }
568 sb.WriteString(tb.Text)
569 }
570 }
571 return sb.String()
572}
573
574func truncateLines(s string, n int) string {
575 lines := strings.Split(s, "\n")
576 if len(lines) <= n {
577 return s
578 }
579 return strings.Join(lines[:n], "\n") + "\n … (" + fmt.Sprintf("%d", len(lines)-n) + " more)"
580}
581
582// StatusBar builds the single-line status shown above the editor.
583//
584// Layout:
585//
586// [busyPrefix] provider-model tokens-cost ctrl+c hint cwd
587// ↑ right-aligned
588//
589// cols is the terminal width; when > 0 the cwd is placed flush-right
590// with spaces. busyPrefix, if non-empty, is injected at the far left.
591// StatusBarParams groups the many bits of state the status bar needs.
592// Grew from a flat argument list once we started matching pi's format.
593type StatusBarParams struct {
594 Theme Theme
595 Provider string
596 Model string
597 Busy bool
598 BusyPrefix string // spinner + funny line when busy
599 CWD string
600 Locked bool // sandbox on?
601
602 // Cumulative session usage and cost.
603 Usage provider.Usage
604 // Subscription is true when the credential is an OAuth token (claude
605 // pro/max, chatgpt plus/pro) rather than a paid api key. We still
606 // compute a cost for visibility, but pi-style we append "(sub)" so
607 // the user knows no money actually moved.
608 Subscription bool
609
610 // Last turn's input+cache tokens (approximates current live context).
611 ContextUsed int
612 ContextMax int // model's context window; 0 disables the percentage
613
614 // AutoCompacting is true when the agent is currently running a
615 // model-triggered condense pass. Surfaces as "(auto)" after the
616 // context percentage so it's clear where the spinner is coming from.
617 AutoCompacting bool
618
619 Cols int // terminal width; drives right-alignment of cwd
620}
621
622// StatusBar builds the single-line status shown above the editor.
623// Format: ↑N ↓N RN WN $cost[(sub)] pct%/ctxMax
624func StatusBar(p StatusBarParams) string {
625 th := p.Theme
626 sep := " - "
627
628 // Token stats: only include each segment when non-zero (pi's
629 // behavior). Keeps the bar compact on brand-new sessions.
630 var stats []string
631 if p.Usage.InputTokens > 0 {
632 stats = append(stats, fmt.Sprintf("↑%s", piFormatTokens(p.Usage.InputTokens)))
633 }
634 if p.Usage.OutputTokens > 0 {
635 stats = append(stats, fmt.Sprintf("↓%s", piFormatTokens(p.Usage.OutputTokens)))
636 }
637 if p.Usage.CacheReadTokens > 0 {
638 stats = append(stats, fmt.Sprintf("R%s", piFormatTokens(p.Usage.CacheReadTokens)))
639 }
640 if p.Usage.CacheWriteTokens > 0 {
641 stats = append(stats, fmt.Sprintf("W%s", piFormatTokens(p.Usage.CacheWriteTokens)))
642 }
643
644 var costStr string
645 if p.Subscription {
646 costStr = "$0.000 (sub)"
647 } else if p.Usage.CostUSD > 0 {
648 costStr = fmt.Sprintf("$%.3f", p.Usage.CostUSD)
649 }
650 if costStr != "" {
651 stats = append(stats, costStr)
652 }
653
654 // Context %. Color-coded: yellow >70, red >90.
655 ctx, ctxColor := piContextUsage(th, p.ContextUsed, p.ContextMax)
656 if ctx != "" {
657 if p.AutoCompacting {
658 ctx += " (auto)"
659 }
660 stats = append(stats, th.FG256(ctxColor, ctx))
661 }
662
663 left := fmt.Sprintf(" (%s) %s ", p.Provider, p.Model)
664 middle := " " + strings.Join(stats, " ") + " "
665
666 var hint string
667 if p.Busy {
668 hint = " esc cancel "
669 } else {
670 hint = " ctrl+c exit " + sep + " /help "
671 }
672
673 var leftBuilder strings.Builder
674 if p.BusyPrefix != "" {
675 leftBuilder.WriteString(th.FG256(th.Accent, " "+p.BusyPrefix+" "))
676 leftBuilder.WriteString(" ")
677 }
678 leftBuilder.WriteString(th.FG256(th.Muted, left))
679 leftBuilder.WriteString(" ")
680 // `middle` already has colorized context segments; wrap the rest in muted.
681 leftBuilder.WriteString(th.FG256(th.Muted, middle))
682 leftBuilder.WriteString(" ")
683 leftBuilder.WriteString(th.FG256(th.Muted, hint))
684
685 // Compose cwd on the right side. shortenHome abbreviates $HOME to "~".
686 right := shortenHome(p.CWD)
687 if p.Locked && right != "" {
688 right = "· locked · " + right
689 }
690 if right == "" || p.Cols <= 0 {
691 return leftBuilder.String()
692 }
693
694 leftRendered := leftBuilder.String()
695 leftWidth := visibleWidth(leftRendered)
696 rightStr := " " + right + " "
697 rightWidth := visibleWidth(rightStr)
698
699 gap := p.Cols - leftWidth - rightWidth
700 if gap < 1 {
701 return leftRendered
702 }
703 return leftRendered + strings.Repeat(" ", gap) + th.FG256(th.Muted, rightStr)
704}
705
706// piContextUsage renders the "N%/ctxMax" fragment, returning the
707// rendered string plus the colour to wrap it in.
708func piContextUsage(th Theme, used, max int) (string, int) {
709 if max <= 0 {
710 if used <= 0 {
711 return "", th.Muted
712 }
713 return piFormatTokens(used), th.Muted
714 }
715 pct := float64(used) / float64(max) * 100
716 text := fmt.Sprintf("%.1f%%/%s", pct, piFormatTokens(max))
717 switch {
718 case pct > 90:
719 return text, th.Error
720 case pct > 70:
721 return text, th.Warning
722 }
723 return text, th.Muted
724}
725
726// piFormatTokens footer formatter:
727//
728// < 1000 -> "42"
729// < 10_000 -> "2.7k"
730// < 1_000_000 -> "35k"
731// < 10M -> "1.1M"
732// else -> "12M"
733func piFormatTokens(n int) string {
734 switch {
735 case n < 0:
736 return "0"
737 case n < 1000:
738 return fmt.Sprintf("%d", n)
739 case n < 10000:
740 return fmt.Sprintf("%.1fk", float64(n)/1000)
741 case n < 1_000_000:
742 return fmt.Sprintf("%dk", (n+500)/1000)
743 case n < 10_000_000:
744 return fmt.Sprintf("%.1fM", float64(n)/1_000_000)
745 default:
746 return fmt.Sprintf("%dM", (n+500_000)/1_000_000)
747 }
748}
749
750// shortenHome replaces the user's $HOME prefix with "~" for readability.
751func shortenHome(p string) string {
752 if p == "" {
753 return ""
754 }
755 home := osUserHome()
756 if home == "" {
757 return p
758 }
759 if p == home {
760 return "~"
761 }
762 if strings.HasPrefix(p, home+"/") {
763 return "~" + p[len(home):]
764 }
765 return p
766}
767
768// osUserHome is a tiny wrapper around os.UserHomeDir so tests can mock it.
769var osUserHome = func() string {
770 if h, err := osUserHomeDir(); err == nil {
771 return h
772 }
773 return ""
774}