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// expandTabs replaces tab characters with 4 spaces so code from
15// tab-indented languages (Go, Makefiles, etc.) renders at a
16// consistent width instead of the terminal's default 8-column tabs.
17func expandTabs(s string) string {
18 return strings.ReplaceAll(s, "\t", " ")
19}
20
21// pathFromToolArgs returns the "path" argument from a tool_call's
22// JSON arguments, or "" if the args aren't a JSON object or don't
23// include one. Used to pick a syntax language for rendering the
24// corresponding tool_result.
25func pathFromToolArgs(raw json.RawMessage) string {
26 if len(raw) == 0 {
27 return ""
28 }
29 var m map[string]any
30 if err := json.Unmarshal(raw, &m); err != nil {
31 return ""
32 }
33 for _, k := range []string{"path", "file_path"} {
34 if s, ok := m[k].(string); ok && s != "" {
35 return s
36 }
37 }
38 return ""
39}
40
41// offsetFromToolArgs returns the read tool's 1-indexed `offset`
42// arg (the first line of the slice the tool was asked to return),
43// or 0 when the call didn't specify one. Used by the tui to draw
44// the line-number gutter aligned to the right starting row, even
45// though the tool's text content itself no longer carries line
46// numbers.
47func offsetFromToolArgs(raw json.RawMessage) int {
48 if len(raw) == 0 {
49 return 0
50 }
51 var m map[string]any
52 if err := json.Unmarshal(raw, &m); err != nil {
53 return 0
54 }
55 switch v := m["offset"].(type) {
56 case float64:
57 return int(v)
58 case int:
59 return v
60 }
61 return 0
62}
63
64// osUserHomeDir is aliased so the test file can swap it.
65var osUserHomeDir = os.UserHomeDir
66
67// View turns a transcript + live state into a slice of styled lines,
68// already wrapped to width.
69type View struct {
70 Theme Theme
71 ImageProto ImageProtocol // how to render inline images in this terminal
72 Messages []provider.Message
73 // toolPaths maps tool_use_id to the "path" argument of the call, if
74 // any, so tool_result rendering can pick the right syntax language.
75 // Rebuilt on each Build().
76 toolPaths map[string]string
77 // toolStartLines maps tool_use_id to the 1-indexed first line
78 // number of a `read` result, pulled from the call's offset arg.
79 // Used by renderNumberedFile to draw a line-number gutter over
80 // raw (unnumbered) file content the model receives. Rebuilt on
81 // each Build().
82 toolStartLines map[string]int
83 // toolCallLabels maps tool_use_id to the box label (tool name +
84 // short args) for the call, so a tool_result message can render
85 // the box top edge without having to look back at the assistant
86 // message that originated the call. Rebuilt on each Build().
87 toolCallLabels map[string]string
88 Streaming string // current assistant text delta
89 StreamingActive bool
90 ToolCalls []ToolCallView // tool calls in flight or completed
91 StatusLine string
92 Err string
93
94 // ExpandAll forces every long tool result to render in full.
95 // Toggled from the tui by ctrl+o. When false, results longer than
96 // ToolCollapseLines collapse to ToolCollapsePreview lines plus a
97 // "... (N more lines, M total, ctrl+o to expand)" footer.
98 ExpandAll bool
99
100 // renderCache holds the per-message rendered line slices so Build
101 // doesn't re-markdown every message on every frame. Keyed by a
102 // struct of (content hash, width, expandAll) — any of those
103 // changing invalidates the entry. Messages are append-only after
104 // they finalise so keeping the cache across turns is safe.
105 //
106 // Streaming/in-flight work (v.Streaming, v.ToolCalls) is never
107 // cached because it changes every delta.
108 renderCache map[msgCacheKey][]string
109}
110
111// msgCacheKey identifies a cached message render. hash is a 64-bit
112// FNV-1a of the message's content, which is cheap to compute and
113// unambiguous enough for the cache (collisions produce a stale frame,
114// not wrong data, and we recompute on invalidation anyway).
115type msgCacheKey struct {
116 hash uint64
117 width int
118 expandAll bool
119 // turnOpen is true when the previous rendered message belongs to
120 // the same agent turn (assistant tool_use, or tool result). The
121 // header ("▍ zot") is suppressed in that case so a single turn
122 // — even one that spans many assistant/tool message round-trips
123 // in the underlying API — renders under one header instead of a
124 // new one per assistant message.
125 turnOpen bool
126}
127
128// InvalidateRenderCache drops all cached message renders. The tui
129// calls this when the transcript is replaced wholesale (/compact,
130// /clear, session swap) since messages can be replaced in place and
131// a content-hash miss alone doesn't reclaim the old entries.
132func (v *View) InvalidateRenderCache() {
133 v.renderCache = nil
134}
135
136// ToolCollapsePreview is the number of lines shown before a long tool
137// result is replaced with a "... ctrl+o to expand" footer. Tool
138// results shorter than ToolCollapseLines always render in full.
139const (
140 ToolCollapsePreview = 10
141 ToolCollapseLines = 12
142)
143
144// ToolCallView is a pending tool invocation plus optional result.
145type ToolCallView struct {
146 ID string
147 Name string
148 Args string // rendered argument summary
149 Result string // rendered result preview (truncated)
150 Error bool
151 Done bool
152
153 // Streaming is true while the model is still typing the tool
154 // call's JSON arguments. The TUI renders a live preview of any
155 // interesting string fields (for `write`, the `content`; for
156 // `bash`, the `command`) so the user can watch the file being
157 // composed. Set to false as soon as EvToolUseEnd arrives.
158 Streaming bool
159
160 // RawJSONBuf is the accumulator of every EvToolUseArgs delta
161 // the stream has delivered for this tool call. Used by the
162 // partial-JSON extractor to peel off the live string value
163 // of one named field on each render.
164 RawJSONBuf string
165
166 // LivePath is the `path` arg extracted as soon as it parses
167 // out of RawJSONBuf. Shown next to the tool name in the header
168 // so the user can see which file is being written to.
169 LivePath string
170}
171
172// MessageAnchor records where a rendered message starts in the chat
173// line slice. Used by /jump so the dialog can scroll the viewport to
174// the row where a turn's user prompt begins.
175type MessageAnchor struct {
176 MessageIdx int // index into v.Messages
177 Row int // first row of that message in the Build() output
178}
179
180// Build returns the chat log lines for the given width.
181func (v *View) Build(width int) []string {
182 lines, _ := v.BuildWithAnchors(width)
183 return lines
184}
185
186// BuildWithAnchors is like Build but additionally reports the first
187// row occupied by each message in v.Messages. Callers that need to
188// scroll to a specific turn (the /jump dialog) use the anchor slice
189// to map a message index back to a row offset.
190func (v *View) BuildWithAnchors(width int) ([]string, []MessageAnchor) {
191 v.refreshToolPaths()
192 if v.renderCache == nil {
193 v.renderCache = make(map[msgCacheKey][]string)
194 }
195
196 // Pre-render every message (hits the cache for unchanged ones) so
197 // we can allocate `out` in a single shot with the exact capacity.
198 // Growing via append on a long transcript copies the backing array
199 // log2(N) times; for a 2000-line scrollback that's enough memcpy
200 // to visibly stutter while typing.
201 rendered := make([][]string, len(v.Messages))
202 total := 0
203 for idx, m := range v.Messages {
204 // A turn is "open" once the assistant has started responding
205 // to the most recent user prompt. Walk back over consecutive
206 // assistant/tool messages: if any non-user message precedes
207 // this one without a user message in between, we're inside
208 // the same turn and should not draw a new "▍ zot" header.
209 turnOpen := false
210 if m.Role == provider.RoleAssistant {
211 for j := idx - 1; j >= 0; j-- {
212 prev := v.Messages[j]
213 // Skip compaction summary messages — they're
214 // rendered as a muted footer line (or hidden
215 // entirely when collapsed) and don't open a turn.
216 if prev.Meta["compaction"] == "true" {
217 continue
218 }
219 if prev.Role == provider.RoleAssistant || prev.Role == provider.RoleTool {
220 turnOpen = true
221 }
222 break
223 }
224 }
225 lines := v.renderMessageCached(m, width, turnOpen)
226 rendered[idx] = lines
227 total += len(lines) + 1 // +1 for the blank separator row
228 }
229
230 out := make([]string, 0, total+16)
231 anchors := make([]MessageAnchor, 0, len(v.Messages))
232 for idx := range v.Messages {
233 anchors = append(anchors, MessageAnchor{MessageIdx: idx, Row: len(out)})
234 out = append(out, rendered[idx]...)
235 // Skip the inter-message blank for messages that rendered
236 // to nothing. An assistant message whose only content is
237 // ToolCallBlock(s) has no rendered output of its own (each
238 // tool result owns its box now), so emitting a blank for it
239 // would compound with the blank from the next real message
240 // and produce two blank rows between adjacent tool boxes.
241 if len(rendered[idx]) == 0 {
242 continue
243 }
244 out = append(out, "")
245 }
246 // Only render the streaming header/body when there's actual
247 // text to show. An empty streaming block (streamOn=true,
248 // Streaming="") appears when a turn starts with a tool_use
249 // block instead of text — in that case the live tool-call
250 // overlay below is the real content and a naked "zot" bar
251 // above it reads as a stray empty message.
252 if v.StreamingActive && strings.TrimSpace(v.Streaming) != "" {
253 // Stream the partial assistant text through the same markdown
254 // renderer used for finalised messages so code fences, diffs,
255 // lists, and inline styles look the same while streaming and
256 // don't suddenly reflow when the turn ends. No speaker header
257 // is drawn; the indent matches the finalised assistant body in
258 // renderMessage so the column stays consistent across the
259 // stream/finalise transition. Width is capped so ultra-wide
260 // terminals don't produce edge-to-edge code-fence rules or
261 // unreadably long prose lines.
262 const indent = " "
263 inner := assistantBodyWidth(width - len(indent))
264 md := RenderMarkdown(v.Streaming, v.Theme, inner)
265 for _, l := range strings.Split(md, "\n") {
266 for _, w := range wrapANSILine(l, inner) {
267 out = append(out, indent+w)
268 }
269 }
270 out = append(out, "")
271 }
272 // Live tool-call overlay: skip any entry whose assistant
273 // tool_use block OR tool_result has already made it into the
274 // transcript. The EvAssistantMessage for a tool-use turn
275 // lands BEFORE executeTools runs, so between that moment and
276 // the tool-result being appended the overlay and the
277 // finalised transcript both render the same call. Checking
278 // for either side of the pair suppresses the duplicate in
279 // both windows.
280 finalised := map[string]bool{}
281 for _, m := range v.Messages {
282 for _, c := range m.Content {
283 switch b := c.(type) {
284 case provider.ToolCallBlock:
285 finalised[b.ID] = true
286 case provider.ToolResultBlock:
287 finalised[b.CallID] = true
288 }
289 }
290 }
291 for _, tc := range v.ToolCalls {
292 if finalised[tc.ID] {
293 continue
294 }
295 out = append(out, v.renderToolCall(tc, width)...)
296 out = append(out, "")
297 }
298 if v.Err != "" {
299 out = append(out, v.Theme.FG256(v.Theme.Error, "✖ "+v.Err))
300 out = append(out, "")
301 }
302 return out, anchors
303}
304
305// refreshToolPaths rebuilds the tool_use_id -> path map from the
306// current transcript. Called once per Build() so tool result blocks
307// (which may be cached) can look up their syntax language when they
308// were originally rendered. Walking the transcript here is O(N) but
309// cheap compared to markdown/chroma work it enables.
310func (v *View) refreshToolPaths() {
311 v.toolPaths = map[string]string{}
312 v.toolStartLines = map[string]int{}
313 v.toolCallLabels = map[string]string{}
314 for _, m := range v.Messages {
315 for _, c := range m.Content {
316 if tc, ok := c.(provider.ToolCallBlock); ok {
317 if p := pathFromToolArgs(tc.Arguments); p != "" {
318 v.toolPaths[tc.ID] = p
319 }
320 if off := offsetFromToolArgs(tc.Arguments); off >= 1 {
321 v.toolStartLines[tc.ID] = off
322 }
323 v.toolCallLabels[tc.ID] = tc.Name + " " + ShortArgs(tc.Name, tc.Arguments)
324 }
325 }
326 }
327}
328
329// renderMessageCached returns the rendered line slice for m, using the
330// cache if the same (content hash, width, expandAll) combination has
331// been rendered before. The slice returned is shared — callers must
332// not mutate it; Build() only ever appends to its own `out` so the
333// shared slice is safe.
334func (v *View) renderMessageCached(m provider.Message, width int, turnOpen bool) []string {
335 key := msgCacheKey{
336 hash: hashMessage(m),
337 width: width,
338 expandAll: v.ExpandAll,
339 turnOpen: turnOpen,
340 }
341 if v.renderCache != nil {
342 if lines, ok := v.renderCache[key]; ok {
343 return lines
344 }
345 }
346 lines := v.renderMessage(m, width, turnOpen)
347 if v.renderCache != nil {
348 // Bound the cache: 4x the current message count is enough to
349 // survive /compact churn without leaking memory across a very
350 // long session.
351 max := len(v.Messages) * 4
352 if max < 32 {
353 max = 32
354 }
355 if len(v.renderCache) > max {
356 // Drop half the entries. map iteration order gives us a
357 // pseudo-LRU for free.
358 dropped := 0
359 target := len(v.renderCache) / 2
360 for k := range v.renderCache {
361 if dropped >= target {
362 break
363 }
364 delete(v.renderCache, k)
365 dropped++
366 }
367 }
368 v.renderCache[key] = lines
369 }
370 return lines
371}
372
373// hashMessage returns a 64-bit FNV-1a over the role + content blocks
374// of m. Serialising each block to its salient bytes is enough: two
375// messages with the same role and same content render identically.
376func hashMessage(m provider.Message) uint64 {
377 h := fnv64aInit
378 h = fnv64aWrite(h, []byte(m.Role))
379 h = fnv64aWriteByte(h, 0)
380 for _, c := range m.Content {
381 switch b := c.(type) {
382 case provider.TextBlock:
383 h = fnv64aWriteByte(h, 't')
384 h = fnv64aWrite(h, []byte(b.Text))
385 case provider.ImageBlock:
386 h = fnv64aWriteByte(h, 'i')
387 h = fnv64aWrite(h, []byte(b.MimeType))
388 h = fnv64aWrite(h, b.Data)
389 case provider.ToolCallBlock:
390 h = fnv64aWriteByte(h, 'c')
391 h = fnv64aWrite(h, []byte(b.ID))
392 h = fnv64aWrite(h, []byte(b.Name))
393 h = fnv64aWrite(h, []byte(b.Arguments))
394 case provider.ToolResultBlock:
395 h = fnv64aWriteByte(h, 'r')
396 h = fnv64aWrite(h, []byte(b.CallID))
397 if b.IsError {
398 h = fnv64aWriteByte(h, 'E')
399 }
400 for _, inner := range b.Content {
401 switch ib := inner.(type) {
402 case provider.TextBlock:
403 h = fnv64aWrite(h, []byte(ib.Text))
404 case provider.ImageBlock:
405 h = fnv64aWrite(h, []byte(ib.MimeType))
406 h = fnv64aWrite(h, ib.Data)
407 }
408 }
409 }
410 h = fnv64aWriteByte(h, 0)
411 }
412 return h
413}
414
415// FNV-1a implementation inlined so we don't pay the interface cost of
416// hash.Hash64 on every Build(). The whole point here is speed.
417const (
418 fnv64aInit uint64 = 0xcbf29ce484222325
419 fnv64aPrime uint64 = 0x100000001b3
420)
421
422// assistantBodyRightPad is the blank gutter kept on the right
423// side of every assistant prose line.
424const assistantBodyRightPad = 2
425
426// assistantBodyWidth returns the usable width for the assistant
427// message body (markdown prose + code fences). Uses the full
428// column width passed in minus assistantBodyRightPad, clamped
429// at 1 so wrap helpers don't divide by zero on absurdly narrow
430// terminals. The right-side padding keeps a small breathing
431// column to the terminal edge that mirrors the left indent.
432func assistantBodyWidth(outer int) int {
433 outer -= assistantBodyRightPad
434 if outer < 1 {
435 return 1
436 }
437 return outer
438}
439
440func fnv64aWriteByte(h uint64, b byte) uint64 {
441 h ^= uint64(b)
442 h *= fnv64aPrime
443 return h
444}
445
446func fnv64aWrite(h uint64, p []byte) uint64 {
447 for _, b := range p {
448 h ^= uint64(b)
449 h *= fnv64aPrime
450 }
451 return h
452}
453
454func (v *View) renderMessage(m provider.Message, width int, turnOpen bool) []string {
455 var lines []string
456
457 // Compaction summary: render as a single muted line at the end
458 // of the chat instead of as a user message.
459 if m.Meta["compaction"] == "true" {
460 if v.ExpandAll {
461 return v.renderCompactionBlock(m, width)
462 }
463 // Collapsed: skip entirely. The status bar shows the info.
464 return nil
465 }
466
467 switch m.Role {
468 case provider.RoleUser:
469 // User rows: no speaker label. Each line is painted with a
470 // faint bubble background tint (UserBubble) so the user's
471 // turns visually segment the chat without needing a header.
472 // One tinted blank row above and below approximates CSS
473 // padding-top / padding-bottom (terminals can't do fractional
474 // rows, so a full row of bubble-coloured whitespace is the
475 // closest analogue and gives the bubble visible breathing
476 // room).
477 // User rows: a 1-cell "▌" accent bar at column 0 painted on
478 // the bubble bg, so the bar's cell shares the panel tint and
479 // there is no visible gap between bar and panel. (Some terminals
480 // — iTerm2, Apple Terminal — may smear the cell-0 bg into the
481 // window inset to the left; that's a terminal-side rendering
482 // quirk we accept in exchange for a clean bar-to-panel join.)
483 const leftGutter = 0 // cells of bubble bg between bar and text
484 const rightGutter = 2 // cells of bubble bg between text and right edge
485 innerWidth := width - 2 - leftGutter - rightGutter // 2 = bar's two cells (▌ + trailing space)
486 if innerWidth < 1 {
487 innerWidth = 1
488 }
489 row := func(content string) string {
490 inner := strings.Repeat(" ", leftGutter) + content
491 padded := v.Theme.UserBubble(inner, width-2)
492 bar := v.Theme.BG(v.Theme.UserBubbleBG, v.Theme.FG256(v.Theme.Accent, "▌ "))
493 return bar + padded
494 }
495 var bubble []string
496 for _, c := range m.Content {
497 switch b := c.(type) {
498 case provider.TextBlock:
499 for _, l := range strings.Split(b.Text, "\n") {
500 for _, w := range wrapLine(l, innerWidth, "") {
501 bubble = append(bubble, row(w))
502 }
503 }
504 case provider.ImageBlock:
505 bubble = append(bubble, row(fmt.Sprintf("[image %s, %d bytes]", b.MimeType, len(b.Data))))
506 }
507 }
508 if len(bubble) > 0 {
509 lines = append(lines, row(""))
510 lines = append(lines, bubble...)
511 lines = append(lines, row(""))
512 }
513 case provider.RoleAssistant:
514 // Assistant rows: no speaker label either. Prose still gets a
515 // small left indent so it visually aligns with tool box body
516 // content, but no "zot" header.
517 _ = turnOpen
518 const indent = " "
519 inner := assistantBodyWidth(width - len(indent))
520 for _, c := range m.Content {
521 switch b := c.(type) {
522 case provider.TextBlock:
523 md := RenderMarkdown(strings.TrimLeft(b.Text, "\n"), v.Theme, inner)
524 for _, l := range strings.Split(md, "\n") {
525 for _, w := range wrapANSILine(l, inner) {
526 lines = append(lines, indent+w)
527 }
528 }
529 case provider.ToolCallBlock:
530 // The whole box (top + body + bottom) is rendered by
531 // the matching tool_result message so a single
532 // assistant message that batches multiple tool_use
533 // blocks doesn't produce a stack of unclosed top
534 // edges. Each tool result owns its own box.
535 _ = b
536 }
537 }
538 case provider.RoleTool:
539 for _, c := range m.Content {
540 if tr, ok := c.(provider.ToolResultBlock); ok {
541 color := v.Theme.ToolOut
542 if tr.IsError {
543 color = v.Theme.Error
544 }
545 path := ""
546 if v.toolPaths != nil {
547 path = v.toolPaths[tr.CallID]
548 }
549 startLine := 1
550 if v.toolStartLines != nil {
551 if s := v.toolStartLines[tr.CallID]; s > 0 {
552 startLine = s
553 }
554 }
555 label := ""
556 if v.toolCallLabels != nil {
557 label = v.toolCallLabels[tr.CallID]
558 }
559 // Each tool result owns a complete box: top edge with
560 // the call's label, body rows wrapped in vertical
561 // edges, bottom edge to close. The label is looked up
562 // from the matching ToolCallBlock so multiple calls
563 // in one assistant message render as N adjacent boxes
564 // instead of stacking unclosed top edges.
565 lines = append(lines, toolBoxTop(v.Theme, label, width))
566 lines = append(lines, toolBoxSide(v.Theme, "", width))
567 if tr.IsError {
568 lines = append(lines, toolBoxSide(v.Theme, v.Theme.FG256(color, " error"), width))
569 }
570 for _, line := range v.renderToolResultContent(tr.Content, width, color, path, startLine) {
571 // Image-footprint rows (the escape row, the blank
572 // reservation rows beneath it, and the gap row
573 // before the metadata caption) are tagged with the
574 // imageFootprintSentinel by renderImageBlock. Strip
575 // the tag, parse the optional width hint, then wrap
576 // the row in the usual │ … │ box edges so the
577 // frame stays continuous around the image.
578 imgCells, stripped := parseImageFootprint(line)
579 if hasImageEscapeLine(stripped) {
580 lines = append(lines, toolBoxSideWithImage(v.Theme, stripped, imgCells, width))
581 } else {
582 lines = append(lines, toolBoxSide(v.Theme, stripped, width))
583 }
584 }
585 lines = append(lines, toolBoxSide(v.Theme, "", width))
586 lines = append(lines, toolBoxBottom(v.Theme, width))
587 }
588 }
589 }
590 return lines
591}
592
593func (v *View) renderToolCall(tc ToolCallView, width int) []string {
594 var lines []string
595
596 // Header label. While the call is still streaming, prefer the
597 // live path extracted from the partial args so the user sees
598 // the target file as soon as it's known, even before the full
599 // JSON arrived.
600 arg := tc.Args
601 if arg == "" && tc.LivePath != "" {
602 arg = tc.LivePath
603 }
604 label := tc.Name + " " + arg
605
606 // No leading blank: Build()'s inter-message separator already
607 // places one blank row between the previous transcript content
608 // and the live overlay, matching the spacing the same call has
609 // once it finalises into a transcript box. Adding another blank
610 // here would double the gap during streaming and visibly tighten
611 // when the overlay disappears.
612
613 // Streaming body (write/edit): top edge with the label, body
614 // rows wrapped with vertical edges, bottom edge to close the
615 // box. When the call finalises, the live overlay disappears
616 // the same frame the transcript renders the closed box, so
617 // there's no visible hop.
618 if tc.Streaming && tc.Result == "" {
619 lines = append(lines, toolBoxTop(v.Theme, label, width))
620 lines = append(lines, toolBoxSide(v.Theme, "", width))
621 if body := v.renderLiveToolBody(tc, width); len(body) > 0 {
622 lines = append(lines, body...)
623 }
624 lines = append(lines, toolBoxSide(v.Theme, "", width))
625 lines = append(lines, toolBoxBottom(v.Theme, width))
626 return lines
627 }
628
629 // Finished tool call with no body: just the labelled top edge
630 // directly closed by the bottom. Avoids a blank interior row
631 // for no-output tools.
632 if tc.Result == "" {
633 lines = append(lines, toolBoxTop(v.Theme, label, width))
634 lines = append(lines, toolBoxBottom(v.Theme, width))
635 return lines
636 }
637
638 // Finished tool call with a result body. Top edge embeds the
639 // label; body lines go through toolBoxSide so each row gets
640 // vertical edges; bottom edge closes the box. Blank interior
641 // rows after the top and before the bottom give the body a bit
642 // of breathing room from the corners.
643 lines = append(lines, toolBoxTop(v.Theme, label, width))
644 lines = append(lines, toolBoxSide(v.Theme, "", width))
645 color := v.Theme.ToolOut
646 if tc.Error {
647 color = v.Theme.Error
648 }
649 body := toolResultBlock(v.Theme, tc.Result, width, color)
650 for _, l := range v.collapseToolBody(body, false) {
651 imgCells, stripped := parseImageFootprint(l)
652 if hasImageEscapeLine(stripped) {
653 lines = append(lines, toolBoxSideWithImage(v.Theme, stripped, imgCells, width))
654 continue
655 }
656 lines = append(lines, toolBoxSide(v.Theme, stripped, width))
657 }
658 lines = append(lines, toolBoxSide(v.Theme, "", width))
659 lines = append(lines, toolBoxBottom(v.Theme, width))
660 return lines
661}
662
663// renderLiveToolBody renders the in-flight preview of a streaming
664// tool call. Supported tools:
665//
666// - write: shows the partial `content` field, syntax-highlighted
667// by the target path's language.
668// - edit: shows the partial `newText` of the edit currently being
669// streamed, prefixed with a "editing foo.ts (edit 2)" header so
670// the user can see which of a multi-edit batch is in progress.
671//
672// Anything else returns nil and only the tool-call header shows.
673func (v *View) renderLiveToolBody(tc ToolCallView, width int) []string {
674 switch tc.Name {
675 case "write", "Write":
676 partial, ok, _ := ExtractPartialStringField(tc.RawJSONBuf, "content")
677 if !ok || partial == "" {
678 return nil
679 }
680 return v.wrapLiveBody(v.renderRawFile(partial, tc.LivePath, 1), width)
681 case "edit", "Edit":
682 partial, ok, _, idx := ExtractLastNewText(tc.RawJSONBuf)
683 if !ok || partial == "" {
684 return nil
685 }
686 // Header line hints which edit is streaming and, when more
687 // than one has landed, how many the model is doing.
688 hint := fmt.Sprintf("edit %d (streaming)", idx)
689 body := []string{" " + v.Theme.FG256(v.Theme.Muted, hint), ""}
690 body = append(body, v.renderRawFile(partial, tc.LivePath, 1)...)
691 return v.wrapLiveBody(body, width)
692 }
693 return nil
694}
695
696// wrapLiveBody returns the streaming body content as a list of
697// box-side rows: each line wrapped in │ … │ with right padding so
698// the closing edge sits at column width-1. The caller (renderToolCall)
699// supplies the surrounding top/bottom edges so the live overlay
700// renders as a closed box matching the finalised transcript form.
701func (v *View) wrapLiveBody(body []string, width int) []string {
702 body = v.collapseToolBody(body, false)
703 out := make([]string, 0, len(body))
704 for _, l := range body {
705 imgCells, stripped := parseImageFootprint(l)
706 if hasImageEscapeLine(stripped) {
707 out = append(out, toolBoxSideWithImage(v.Theme, stripped, imgCells, width))
708 continue
709 }
710 out = append(out, toolBoxSide(v.Theme, stripped, width))
711 }
712 return out
713}
714
715// toolResultBlock wraps text in thin horizontal rules (top + bottom),
716// indenting the body with four spaces. The rules span the content column.
717// toolBlockRule renders the muted horizontal separator drawn
718// above and below a tool call block. Spans the full content
719// width so it reads as a real section break in the chat
720// regardless of terminal size.
721func toolBlockRule(th Theme, width int) string {
722 w := width
723 if w < 8 {
724 w = 8
725 }
726 return th.FG256(th.Muted, strings.Repeat("─", w))
727}
728
729// toolBoxInnerPad is the number of blank cells kept between a box
730// edge (┌, │, └) and the content inside it. One cell of breathing
731// room makes the label read as part of the box rather than fused to
732// the corner, and gives body lines a tiny gutter from the left side.
733const toolBoxInnerPad = 1
734
735// toolBoxOuterMargin is the number of blank cells kept to the left of
736// the opening corner and to the right of the closing corner. Aligns
737// the box's frame with the column where user-bubble text begins, so
738// the conversation reads as one column instead of having tool boxes
739// running edge-to-edge while user/assistant rows sit indented.
740const toolBoxOuterMargin = 2
741
742// toolBoxTop renders the labelled top edge of a tool block:
743//
744// ┌─ bash xcrun simctl list devices ─────────────────────────────┐
745//
746// The label is the tool name + short args (the same string previously
747// shown on its own row beneath the rule). Padding fills the remainder
748// of the line so the right corner sits at column width-1, matching the
749// closing edge.
750func toolBoxTop(th Theme, label string, width int) string {
751 w := width - 2*toolBoxOuterMargin
752 if w < 12 {
753 w = 12
754 }
755 margin := strings.Repeat(" ", toolBoxOuterMargin)
756 innerPad := strings.Repeat(" ", toolBoxInnerPad)
757 // "┌─" + innerPad + " " + label + " " + innerPad = used; pad
758 // with ─ to width-1, then "┐".
759 prefix := "┌─" + innerPad + " "
760 suffix := " " + innerPad
761 used := visibleWidth(prefix) + visibleWidth(label) + visibleWidth(suffix)
762 fill := w - used - 1 // -1 for the closing corner
763 if fill < 0 {
764 // Label overflows; truncate with an ellipsis so the right
765 // corner still lands on the right edge. Rare on real
766 // terminals (the chat column is usually wide enough).
767 over := -fill
768 runes := []rune(label)
769 if over+1 < len(runes) {
770 label = string(runes[:len(runes)-over-1]) + "…"
771 } else {
772 label = "…"
773 }
774 used = visibleWidth(prefix) + visibleWidth(label) + visibleWidth(suffix)
775 fill = w - used - 1
776 if fill < 0 {
777 fill = 0
778 }
779 }
780 fillStr := strings.Repeat("─", fill)
781 name, rest := splitToolLabel(label)
782 return margin + th.FG256(th.Muted, prefix) + th.FG256(th.FG, name) + th.FG256(th.Muted, rest+suffix+fillStr+"┐") + margin
783}
784
785func splitToolLabel(label string) (name, rest string) {
786 label = strings.TrimLeft(label, " ")
787 if label == "" {
788 return "", ""
789 }
790 idx := strings.IndexAny(label, " \t")
791 if idx < 0 {
792 return label, ""
793 }
794 return label[:idx], label[idx:]
795}
796
797// toolBoxBottom renders the bottom edge of a tool block:
798//
799// └─────────────────────────────────────────────────────────────────────────────┘
800//
801// Spans the same width as toolBoxTop so the corners line up.
802func toolBoxBottom(th Theme, width int) string {
803 w := width - 2*toolBoxOuterMargin
804 if w < 12 {
805 w = 12
806 }
807 margin := strings.Repeat(" ", toolBoxOuterMargin)
808 line := "└" + strings.Repeat("─", w-2) + "┘"
809 return margin + th.FG256(th.Muted, line) + margin
810}
811
812// hasImageEscapeLine reports whether s contains a Kitty (\x1b_G) or
813// iTerm2 (\x1b]1337;File=) inline-image escape. Such rows draw into
814// the terminal's graphics layer and shouldn't be wrapped with text
815// box edges.
816func hasImageEscapeLine(s string) bool {
817 return strings.Contains(s, "\x1b]1337;File=") || strings.Contains(s, "\x1b_G")
818}
819
820// imageFootprintSentinel marks rows that belong to an inline-image's
821// reserved footprint — the escape row plus the blank rows below it
822// plus the gap row before the metadata caption. Any consumer that
823// wraps content in box edges (│ … │) detects the sentinel, strips
824// it, and emits the row — the image graphics rectangle paints over
825// whatever was drawn there. Uses a non-printing C0 control byte so
826// it can never appear in normal text or in an ANSI escape sequence
827// body.
828//
829// The escape row carries an extra width hint between two sentinels:
830// "\x1e<cells>\x1e<spaces+escape>". Wrappers parse the cells count
831// to know how wide the image is in terminal cells and how many cells
832// of trailing padding are needed before the closing box edge.
833const imageFootprintSentinel = "\x1e"
834
835// parseImageFootprint splits a footprint-tagged row into (cellsWide,
836// rest). cellsWide is 0 when the row carries no width hint (the
837// reservation blanks and gap row don't, only the escape row does).
838func parseImageFootprint(s string) (int, string) {
839 if !strings.HasPrefix(s, imageFootprintSentinel) {
840 return 0, s
841 }
842 rest := s[len(imageFootprintSentinel):]
843 end := strings.Index(rest, imageFootprintSentinel)
844 if end < 0 {
845 return 0, rest
846 }
847 w, err := strconv.Atoi(rest[:end])
848 if err != nil {
849 return 0, rest
850 }
851 return w, rest[end+len(imageFootprintSentinel):]
852}
853
854// toolBoxBodyTrimLeft is the number of leading literal spaces stripped
855// from each body line as it enters toolBoxSide. Body renderers
856// (renderToolText, renderRawFile, the diff/bash helpers, ...) all
857// emit a 4-cell indent so the content aligns with the assistant body
858// column when there's no box around it. Inside a box the box edge +
859// inner pad already supply most of that gutter, so we drop a couple
860// of cells from the body's own indent to keep the content from
861// drifting too far right.
862const toolBoxBodyTrimLeft = 2
863
864// toolBoxSide wraps a single body line with vertical box edges:
865//
866// │ foo bar baz │
867//
868// The middle preserves the line verbatim (including any ANSI escapes)
869// after stripping toolBoxBodyTrimLeft leading literal spaces. One cell
870// of inner padding sits on each side so the content breathes from the
871// edges; the right padding fills to column width-1.
872func toolBoxSide(th Theme, line string, width int) string {
873 w := width - 2*toolBoxOuterMargin
874 if w < 12 {
875 w = 12
876 }
877 margin := strings.Repeat(" ", toolBoxOuterMargin)
878 left := th.FG256(th.Muted, "│") + strings.Repeat(" ", toolBoxInnerPad)
879 right := strings.Repeat(" ", toolBoxInnerPad) + th.FG256(th.Muted, "│")
880 inner := w - 2 - 2*toolBoxInnerPad // available between the two pads
881 line = trimLeadingSpaces(line, toolBoxBodyTrimLeft)
882
883 cur := visibleWidth(line)
884 if cur > inner {
885 // Last-resort truncation. Strips ANSI styling at the cut
886 // point; rare path so the simpler implementation is fine.
887 line = stripANSI(line)
888 runes := []rune(line)
889 if len(runes) > inner {
890 line = string(runes[:inner])
891 }
892 cur = visibleWidth(line)
893 }
894 pad := inner - cur
895 if pad < 0 {
896 pad = 0
897 }
898 return margin + left + line + strings.Repeat(" ", pad) + right + margin
899}
900
901// toolBoxSideWithImage wraps a row that carries an inline-image
902// escape sequence. The image protocols are configured to not move
903// the cursor after rendering (iTerm: doNotMoveCursor=1, kitty/
904// ghostty: C=1), so the only visible cell advance on the row is
905// from the leading indent spaces before the escape. We pad from
906// there to the right edge column and draw the closing │ there.
907// imgCells is unused (kept in the signature for compatibility with
908// the parseImageFootprint width hint).
909func toolBoxSideWithImage(th Theme, line string, imgCells, width int) string {
910 _ = imgCells
911 w := width - 2*toolBoxOuterMargin
912 if w < 12 {
913 w = 12
914 }
915 margin := strings.Repeat(" ", toolBoxOuterMargin)
916 left := th.FG256(th.Muted, "│") + strings.Repeat(" ", toolBoxInnerPad)
917 right := strings.Repeat(" ", toolBoxInnerPad) + th.FG256(th.Muted, "│")
918 inner := w - 2 - 2*toolBoxInnerPad
919
920 line = trimLeadingSpaces(line, toolBoxBodyTrimLeft)
921
922 // Count leading spaces (visible cells consumed before the escape).
923 leading := 0
924 for leading < len(line) && line[leading] == ' ' {
925 leading++
926 }
927
928 pad := inner - leading
929 if pad < 0 {
930 pad = 0
931 }
932 return margin + left + line + strings.Repeat(" ", pad) + right + margin
933}
934
935// trimLeadingSpaces removes up to n literal space characters from the
936// start of s without touching anything else. ANSI CSI escapes that
937// appear before the spaces are skipped over (so a coloured indent
938// like "\x1b[2m text" still loses its first n cells of indent).
939// Stops as soon as it hits a non-space character.
940func trimLeadingSpaces(s string, n int) string {
941 if n <= 0 || s == "" {
942 return s
943 }
944 var b strings.Builder
945 b.Grow(len(s))
946 trimmed := 0
947 i := 0
948 for i < len(s) {
949 // Pass through any ANSI escape sequence verbatim.
950 if s[i] == 0x1b && i+1 < len(s) && s[i+1] == '[' {
951 end := i + 2
952 for end < len(s) {
953 c := s[end]
954 end++
955 if c >= 0x40 && c <= 0x7e {
956 break
957 }
958 }
959 b.WriteString(s[i:end])
960 i = end
961 continue
962 }
963 if trimmed < n && s[i] == ' ' {
964 trimmed++
965 i++
966 continue
967 }
968 b.WriteString(s[i:])
969 return b.String()
970 }
971 return b.String()
972}
973
974// renderToolResultContent renders the body of a tool result block.
975// Text blocks get the usual rules-wrapped treatment; text that looks
976// like a unified diff gets +/- coloring. Image blocks are rendered
977// inline when the terminal supports a protocol, else as a text
978// placeholder with dimensions.
979func (v *View) renderToolResultContent(blocks []provider.Content, width, color int, sourcePath string, startLine int) []string {
980 var body []string
981 hasImage := false
982 for _, b := range blocks {
983 switch bb := b.(type) {
984 case provider.TextBlock:
985 body = append(body, v.renderToolText(bb.Text, width, color, sourcePath, startLine)...)
986 case provider.ImageBlock:
987 hasImage = true
988 body = append(body, v.renderImageBlock(bb, width)...)
989 }
990 }
991 return v.collapseToolBody(body, hasImage)
992}
993
994// collapseToolBody trims lines to the configured preview size when the
995// view is not in ExpandAll mode, appending a muted "... ctrl+o to
996// expand" footer. Image blocks never collapse — they're short in text
997// rows but represent real content the user wants to see.
998func (v *View) collapseToolBody(lines []string, hasImage bool) []string {
999 if v.ExpandAll || hasImage {
1000 return lines
1001 }
1002 if len(lines) <= ToolCollapseLines {
1003 return lines
1004 }
1005 kept := lines[:ToolCollapsePreview]
1006 hidden := len(lines) - ToolCollapsePreview
1007 total := len(lines)
1008 footer := fmt.Sprintf(" ... (%d more lines, %d total, ctrl+o to expand)", hidden, total)
1009 footer = v.Theme.FG256(v.Theme.Muted, footer)
1010 return append(append([]string(nil), kept...), footer)
1011}
1012
1013// renderToolText renders a text block inside a tool result. If the
1014// text contains a unified-diff section (lines starting with "--- " /
1015// "+++ " / "+" / "-"/" "), those rows are styled with add/remove
1016// colors matching git diff conventions.
1017func (v *View) renderToolText(text string, width, defaultColor int, sourcePath string, startLine int) []string {
1018 // Legacy path: transcripts saved before we dropped line numbers
1019 // from the read tool still carry " 1\t…" prefixes. Detect and
1020 // strip them, then fall through to the highlighter.
1021 if looksLikeNumberedFile(text) {
1022 return v.renderNumberedFile(text, sourcePath)
1023 }
1024 // If the result embeds a unified diff (the edit tool's output
1025 // starts with a short "applied N edit(s)" line and then a
1026 // standard --- / +++ / +/- patch), render the patch with
1027 // add/remove coloring. This takes priority over the file-like
1028 // detector below because a diff technically has many lines of
1029 // "file content" but what the user cares about is what changed,
1030 // not a dump of the post-edit file.
1031 if looksLikeUnifiedDiff(text) {
1032 return v.renderUnifiedDiff(text, width, sourcePath)
1033 }
1034
1035 // Current path: text came from `read` as raw file bytes. When a
1036 // source path is known (the call had a `path` arg), render with
1037 // a synthetic line-number gutter starting at startLine so the
1038 // on-screen view still looks like cat -n. Doesn't apply to non-
1039 // file tool outputs (bash stdout, display notes, etc.).
1040 if sourcePath != "" && looksLikeFileContent(text) {
1041 return v.renderRawFile(text, sourcePath, startLine)
1042 }
1043
1044 // No truncation — the full tool output is rendered into chat and
1045 // becomes part of the scrollback you can page back through.
1046 lines := strings.Split(text, "\n")
1047
1048 // Bash-result styling: when the first row looks like a shell
1049 // prompt line ("$ ...") emitted by the bash tool, style the
1050 // prompt line in accent and the trailing "[exit N] Took X.Ys"
1051 // line in muted type so the command + timing read at a glance.
1052 // Everything between is left on the default tool-output color.
1053 if len(lines) > 0 && strings.HasPrefix(lines[0], "$ ") {
1054 return v.renderBashResult(lines, width, defaultColor)
1055 }
1056
1057 inDiff := false
1058 oldLine, newLine := 1, 1
1059 var out []string
1060 for _, l := range lines {
1061 // Detect diff header: "--- name" followed somewhere by "+++ name".
1062 if strings.HasPrefix(l, "--- ") || strings.HasPrefix(l, "+++ ") {
1063 inDiff = true
1064 out = append(out, " "+v.Theme.FG256(v.Theme.Muted, l))
1065 continue
1066 }
1067 // Hunk header "@@ -a,b +c,d @@" resets the counters so patches
1068 // that skip around in the file still get correct numbering.
1069 if inDiff && strings.HasPrefix(l, "@@") {
1070 if o, n, ok := parseHunkHeader(l); ok {
1071 oldLine, newLine = o, n
1072 }
1073 out = append(out, " "+v.Theme.FG256(v.Theme.Muted, l))
1074 continue
1075 }
1076 if inDiff && len(l) > 0 {
1077 switch l[0] {
1078 case '+':
1079 out = append(out, v.renderDiffRow(l, width, v.Theme.Tool, newLine, '+', sourcePath))
1080 newLine++
1081 continue
1082 case '-':
1083 out = append(out, v.renderDiffRow(l, width, v.Theme.Error, oldLine, '-', sourcePath))
1084 oldLine++
1085 continue
1086 case ' ':
1087 out = append(out, v.renderDiffRow(l, width, v.Theme.Muted, newLine, ' ', sourcePath))
1088 oldLine++
1089 newLine++
1090 continue
1091 }
1092 }
1093 // Regular line.
1094 for _, w := range wrapLine(l, width-4, " ") {
1095 out = append(out, " "+v.Theme.FG256(defaultColor, w))
1096 }
1097 }
1098 return out
1099}
1100
1101// parseHunkHeader extracts the starting old/new line from a unified
1102// diff hunk header ("@@ -12,5 +12,7 @@ ..."). Returns ok=false if the
1103// header is malformed or missing numbers.
1104func parseHunkHeader(l string) (oldStart, newStart int, ok bool) {
1105 // Skip "@@ "
1106 rest := strings.TrimPrefix(l, "@@")
1107 rest = strings.TrimSpace(rest)
1108 if !strings.HasPrefix(rest, "-") {
1109 return 0, 0, false
1110 }
1111 rest = rest[1:]
1112 space := strings.IndexByte(rest, ' ')
1113 if space < 0 {
1114 return 0, 0, false
1115 }
1116 oldPart := rest[:space]
1117 rest = strings.TrimSpace(rest[space+1:])
1118 if !strings.HasPrefix(rest, "+") {
1119 return 0, 0, false
1120 }
1121 rest = rest[1:]
1122 if sp := strings.IndexAny(rest, " \t"); sp >= 0 {
1123 rest = rest[:sp]
1124 }
1125 parseStart := func(s string) (int, bool) {
1126 if c := strings.IndexByte(s, ','); c >= 0 {
1127 s = s[:c]
1128 }
1129 n, err := strconv.Atoi(s)
1130 if err != nil || n < 1 {
1131 return 0, false
1132 }
1133 return n, true
1134 }
1135 o, ok1 := parseStart(oldPart)
1136 n, ok2 := parseStart(rest)
1137 if !ok1 || !ok2 {
1138 return 0, 0, false
1139 }
1140 return o, n, true
1141}
1142
1143// renderDiffRow renders one unified-diff line with a read-style gutter
1144// (6-cell right-aligned line number, muted) followed by the +/-/space
1145// marker and the code. Code is syntax-highlighted if sourcePath hints
1146// at a known language; falls back to the plain diff color otherwise.
1147func (v *View) renderDiffRow(line string, width, color int, lineNo int, mark byte, sourcePath string) string {
1148 if len(line) == 0 {
1149 return ""
1150 }
1151 code := expandTabs(line[1:]) // strip the leading marker; expand tabs
1152
1153 // Syntax-highlight the code half when we know the language. Use
1154 // the same HighlightCode pipeline as renderNumberedFile so the
1155 // palette matches.
1156 lang := LanguageFromPath(sourcePath)
1157 var codeRendered string
1158 if lang != "" {
1159 if h := HighlightCode(code, lang); len(h) == 1 {
1160 codeRendered = h[0]
1161 }
1162 }
1163 if codeRendered == "" {
1164 if mark == ' ' {
1165 codeRendered = v.Theme.FG256(v.Theme.Muted, code)
1166 } else {
1167 codeRendered = v.Theme.FG256(color, code)
1168 }
1169 }
1170
1171 // Gutter shape: sign + number share a color so they read as one
1172 // visual token ("+123") instead of a neutral line number next to
1173 // a stray marker. Unchanged context lines get a muted gutter and
1174 // a leading space so column alignment stays consistent with +/-
1175 // rows.
1176 var gutterText string
1177 switch mark {
1178 case '+':
1179 gutterText = fmt.Sprintf("+%3d ", lineNo)
1180 case '-':
1181 gutterText = fmt.Sprintf("-%3d ", lineNo)
1182 default:
1183 gutterText = fmt.Sprintf(" %3d ", lineNo)
1184 }
1185 var gutter string
1186 if mark == ' ' {
1187 gutter = v.Theme.FG256(v.Theme.Muted, gutterText)
1188 } else {
1189 gutter = v.Theme.FG256(color, gutterText)
1190 }
1191 row := " " + gutter + codeRendered
1192
1193 // Cheap width clamp: truncate visible text if the raw code is too
1194 // long. We work on the pre-ANSI code string because measuring ansi
1195 // output is unreliable.
1196 maxCode := width - 4 /* indent */ - 7 /* gutter (sign+5 digits+tab) */
1197 if maxCode > 0 && len(code) > maxCode {
1198 trunc := code[:maxCode-1] + "…"
1199 if lang != "" {
1200 if h := HighlightCode(trunc, lang); len(h) == 1 {
1201 codeRendered = h[0]
1202 } else if mark == ' ' {
1203 codeRendered = v.Theme.FG256(v.Theme.Muted, trunc)
1204 } else {
1205 codeRendered = v.Theme.FG256(color, trunc)
1206 }
1207 } else if mark == ' ' {
1208 codeRendered = v.Theme.FG256(v.Theme.Muted, trunc)
1209 } else {
1210 codeRendered = v.Theme.FG256(color, trunc)
1211 }
1212 row = " " + gutter + codeRendered
1213 }
1214 return row
1215}
1216
1217// renderImageBlock returns the lines for one image, inline if possible.
1218//
1219// Inline image escapes paint into multiple terminal rows but the zot
1220// renderer treats each slice entry as a single row. To prevent chat
1221// content from being drawn on top of the image, we pad with blank rows
1222// so the image's real footprint is reflected in the frame height.
1223func (v *View) renderImageBlock(b provider.ImageBlock, width int) []string {
1224 w, h := ImageDimensions(b.Data)
1225 kb := len(b.Data) / 1024
1226 // Four-space indent matches every other tool-output row
1227 // (renderRawFile, renderBashResult, diff rows, "... N more
1228 // lines" footers). Keeps the image's metadata line vertically
1229 // aligned with the file content above / below it.
1230 info := fmt.Sprintf(" image - %s - %dx%d - %d KB", b.MimeType, w, h, kb)
1231
1232 if v.ImageProto != ImageProtocolNone {
1233 // Clamp rendered width so the image never overflows the chat
1234 // column. Subtract a 4-cell indent for the tool result block,
1235 // cap at 60 cells, floor at 10.
1236 cells := width - 4
1237 if cells > 60 {
1238 cells = 60
1239 }
1240 if cells < 10 {
1241 cells = 10
1242 }
1243 const maxRows = 20
1244 if seq := RenderInlineImageScaled(v.ImageProto, b.Data, b.MimeType, cells, maxRows); seq != "" {
1245 rows, actualCells := InlineImageFootprint(b.Data, cells, maxRows)
1246 if rows < 1 {
1247 rows = 1
1248 }
1249 if actualCells < 1 {
1250 actualCells = cells
1251 }
1252 // Reserve the image footprint first, then place the escape
1253 // in the top-left of that blank rectangle. Keeping the
1254 // metadata above the image made some terminals blend text
1255 // and graphics layers during full-screen repaints; metadata
1256 // below the reserved rectangle is more stable and easier to
1257 // read. One extra blank row before the metadata gives the
1258 // caption breathing room from the image's last pixel row.
1259 //
1260 // Every footprint row (escape, reservations, gap) is tagged
1261 // with imageFootprintSentinel so callers wrapping content in
1262 // box edges can recognise these rows and emit them bare —
1263 // the image's graphics rectangle paints over them and any
1264 // │ character drawn alongside would visibly bleed through.
1265 // 4 leading cells push the escape past the box's left
1266 // edge plus a small interior gutter so the image rectangle
1267 // sits visibly inside the frame instead of kissing the │.
1268 // The escape row carries a width hint after the sentinel
1269 // ("\x1e<cells>\x1e\u2026") so toolBoxSide knows how many
1270 // cells the image occupies and can pad to the right edge.
1271 widthHint := fmt.Sprintf("%s%d%s", imageFootprintSentinel, actualCells, imageFootprintSentinel)
1272 out := make([]string, 0, rows+3)
1273 out = append(out, widthHint+" "+seq)
1274 for i := 1; i < rows; i++ {
1275 out = append(out, imageFootprintSentinel)
1276 }
1277 out = append(out, imageFootprintSentinel)
1278 out = append(out, v.Theme.FG256(v.Theme.Muted, info))
1279 return out
1280 }
1281 }
1282 return []string{v.Theme.FG256(v.Theme.Muted, info)}
1283}
1284
1285// looksLikeNumberedFile returns true when text matches the `read`
1286// tool's " N\tcontent" format for most of its lines.
1287func looksLikeNumberedFile(text string) bool {
1288 lines := strings.Split(text, "\n")
1289 if len(lines) == 0 {
1290 return false
1291 }
1292 hits := 0
1293 scanned := 0
1294 for _, l := range lines {
1295 if l == "" {
1296 continue
1297 }
1298 scanned++
1299 if scanned > 20 {
1300 break
1301 }
1302 if numberedLineRE.MatchString(l) {
1303 hits++
1304 }
1305 }
1306 if scanned == 0 {
1307 return false
1308 }
1309 return hits*2 >= scanned // majority of non-empty lines match
1310}
1311
1312var numberedLineRE = regexp.MustCompile(`^\s*\d+\t`)
1313
1314// renderNumberedFile strips line numbers, highlights the code, and
1315// re-attaches the line numbers in muted color.
1316func (v *View) renderNumberedFile(text, sourcePath string) []string {
1317 lines := strings.Split(text, "\n")
1318 gutters := make([]string, 0, len(lines))
1319 codes := make([]string, 0, len(lines))
1320 for _, l := range lines {
1321 idx := strings.IndexByte(l, '\t')
1322 if idx < 0 || !numberedLineRE.MatchString(l) {
1323 // Non-code footer (e.g. "[truncated at 2000 lines]").
1324 gutters = append(gutters, "")
1325 codes = append(codes, l)
1326 continue
1327 }
1328 gutter := l[:idx] + " " // replace tab with single space
1329 code := expandTabs(l[idx+1:])
1330 gutters = append(gutters, gutter)
1331 codes = append(codes, code)
1332 }
1333 lang := LanguageFromPath(sourcePath)
1334 var highlighted []string
1335 if lang != "" {
1336 highlighted = HighlightCode(strings.Join(codes, "\n"), lang)
1337 // Chroma sometimes collapses the trailing empty line. Pad to
1338 // align with the gutter slice so per-line zipping works.
1339 for len(highlighted) < len(codes) {
1340 highlighted = append(highlighted, "")
1341 }
1342 if len(highlighted) > len(codes) {
1343 highlighted = highlighted[:len(codes)]
1344 }
1345 } else {
1346 // No lexer for this file type — render in the ToolOut color so
1347 // code is visually distinct from the muted gutter.
1348 highlighted = make([]string, len(codes))
1349 for i, c := range codes {
1350 highlighted[i] = v.Theme.FG256(v.Theme.ToolOut, c)
1351 }
1352 }
1353 out := make([]string, 0, len(codes))
1354 for i, code := range highlighted {
1355 g := gutters[i]
1356 if g == "" {
1357 out = append(out, " "+v.Theme.FG256(v.Theme.Muted, code))
1358 continue
1359 }
1360 out = append(out, " "+v.Theme.FG256(v.Theme.Muted, g)+code)
1361 }
1362 return out
1363}
1364
1365// looksLikeFileContent is a cheap guard to distinguish a read-tool
1366// result from bash stdout or a status message. File content usually
1367// contains characters that status messages don't (code punctuation,
1368// longer lines, multiple lines) and rarely starts with the " >"-
1369// or "error:"-style prefixes tools emit. False positives are OK,
1370// the worst case is a line-number gutter on something that isn't
1371// really code.
1372// renderBashResult styles a bash tool result: the "$ command" first
1373// line in the accent color, the trailing "[exit N] Took X.Ys" line
1374// in muted type, everything else on the default tool-output color.
1375// Called from renderToolText when the first line starts with "$ ".
1376func (v *View) renderBashResult(lines []string, width, defaultColor int) []string {
1377 // Identify the footer line (exit + timing). The bash tool writes
1378 // it as the last non-empty line of the result.
1379 footerIdx := -1
1380 for i := len(lines) - 1; i >= 0; i-- {
1381 trimmed := strings.TrimSpace(lines[i])
1382 if trimmed == "" {
1383 continue
1384 }
1385 if strings.HasPrefix(trimmed, "[exit ") {
1386 footerIdx = i
1387 }
1388 break
1389 }
1390
1391 var out []string
1392 for i, l := range lines {
1393 switch {
1394 case i == 0 && strings.HasPrefix(l, "$ "):
1395 // Style the $ and the command text in accent. No
1396 // further processing / wrapping so the shell-style
1397 // prompt reads at a glance.
1398 for _, w := range wrapLine(l, width-4, " ") {
1399 out = append(out, " "+v.Theme.FG256(v.Theme.Accent, w))
1400 }
1401 case i == footerIdx:
1402 out = append(out, " "+v.Theme.FG256(v.Theme.Muted, l))
1403 default:
1404 for _, w := range wrapLine(l, width-4, " ") {
1405 out = append(out, " "+v.Theme.FG256(defaultColor, w))
1406 }
1407 }
1408 }
1409 return out
1410}
1411
1412// looksLikeUnifiedDiff reports whether text is a context diff as
1413// emitted by the edit tool: rows start with '+', '-', ' ', or
1414// literal "..." (context-break marker). The presence of at least
1415// one '+' or '-' row distinguishes a real diff from an ordinary
1416// file whose lines happen to begin with a space.
1417func looksLikeUnifiedDiff(text string) bool {
1418 lines := strings.Split(text, "\n")
1419 if len(lines) < 2 {
1420 return false
1421 }
1422 sawChange := false
1423 for _, l := range lines {
1424 if l == "" {
1425 continue
1426 }
1427 if l == "..." {
1428 continue
1429 }
1430 switch l[0] {
1431 case '+', '-':
1432 sawChange = true
1433 case ' ':
1434 // context, ok
1435 default:
1436 return false
1437 }
1438 }
1439 return sawChange
1440}
1441
1442// renderUnifiedDiff renders the edit tool's context diff. Each
1443// kept row shows a line-number gutter plus a marker column: '+'
1444// for additions (colored like add), '-' for deletions (colored
1445// like remove), and unmarked context in muted type. A literal
1446// "..." line between hunks renders as an ellipsis in muted type,
1447// indicating skipped unchanged rows. The old and new line
1448// counters advance so each row carries its actual position in
1449// the pre- or post-edit file. Heuristic: when we hit a "...", we
1450// can't know where the next hunk starts, so we don't reset the
1451// counters — they stay approximate in the rare multi-hunk case.
1452func (v *View) renderUnifiedDiff(text string, width int, sourcePath string) []string {
1453 lines := strings.Split(text, "\n")
1454 if n := len(lines); n > 0 && lines[n-1] == "" {
1455 lines = lines[:n-1]
1456 }
1457 oldLine, newLine := 1, 1
1458 var out []string
1459 for _, l := range lines {
1460 if l == "" {
1461 out = append(out, "")
1462 continue
1463 }
1464 if l == "..." {
1465 out = append(out, " "+v.Theme.FG256(v.Theme.Muted, "…"))
1466 continue
1467 }
1468 switch l[0] {
1469 case '+':
1470 out = append(out, v.renderDiffRow(l, width, v.Theme.Tool, newLine, '+', sourcePath))
1471 newLine++
1472 case '-':
1473 out = append(out, v.renderDiffRow(l, width, v.Theme.Error, oldLine, '-', sourcePath))
1474 oldLine++
1475 case ' ':
1476 out = append(out, v.renderDiffRow(l, width, v.Theme.Muted, newLine, ' ', sourcePath))
1477 oldLine++
1478 newLine++
1479 default:
1480 for _, w := range wrapLine(l, width-4, " ") {
1481 out = append(out, " "+v.Theme.FG256(v.Theme.Muted, w))
1482 }
1483 }
1484 }
1485 return out
1486}
1487
1488func looksLikeFileContent(text string) bool {
1489 if strings.TrimSpace(text) == "" {
1490 return false
1491 }
1492 lines := strings.Split(text, "\n")
1493 return len(lines) >= 2
1494}
1495
1496// renderRawFile renders file content received without embedded line
1497// numbers (the current read-tool output). Draws a muted gutter like
1498// "%6d \t" starting at startLine, highlights the code using the
1499// source path's language, and returns the formatted lines.
1500func (v *View) renderRawFile(text, sourcePath string, startLine int) []string {
1501 lines := strings.Split(text, "\n")
1502 // Drop the trailing empty line that Split produces when text ends
1503 // in "\n" so the gutter doesn't show a phantom last number.
1504 if n := len(lines); n > 0 && lines[n-1] == "" {
1505 lines = lines[:n-1]
1506 }
1507 // Split code from trailing footer lines ("... [truncated ...]")
1508 // so we don't number the footer.
1509 codeEnd := len(lines)
1510 for i := len(lines) - 1; i >= 0; i-- {
1511 if strings.HasPrefix(lines[i], "...") {
1512 codeEnd = i
1513 continue
1514 }
1515 break
1516 }
1517 code := lines[:codeEnd]
1518 footer := lines[codeEnd:]
1519
1520 // Expand tabs to 4 spaces so Go / Makefile code renders
1521 // at a consistent width.
1522 for i, c := range code {
1523 code[i] = expandTabs(c)
1524 }
1525
1526 lang := LanguageFromPath(sourcePath)
1527 var highlighted []string
1528 if lang != "" {
1529 highlighted = HighlightCode(strings.Join(code, "\n"), lang)
1530 for len(highlighted) < len(code) {
1531 highlighted = append(highlighted, "")
1532 }
1533 if len(highlighted) > len(code) {
1534 highlighted = highlighted[:len(code)]
1535 }
1536 } else {
1537 highlighted = make([]string, len(code))
1538 for i, c := range code {
1539 highlighted[i] = v.Theme.FG256(v.Theme.ToolOut, c)
1540 }
1541 }
1542
1543 out := make([]string, 0, len(lines))
1544 for i, c := range highlighted {
1545 gutter := fmt.Sprintf("%4d ", startLine+i)
1546 out = append(out, " "+v.Theme.FG256(v.Theme.Muted, gutter)+c)
1547 }
1548 for _, f := range footer {
1549 out = append(out, " "+v.Theme.FG256(v.Theme.Muted, f))
1550 }
1551 return out
1552}
1553
1554// toolResultBlock renders the live tool-call result body (shown
1555// while the turn is still in flight). The rules that used to
1556// bracket this block have been dropped so the live path looks
1557// identical to the transcript rendering that replaces it when
1558// the turn ends.
1559func toolResultBlock(th Theme, text string, width int, color int) []string {
1560 var out []string
1561 for _, l := range strings.Split(text, "\n") {
1562 for _, w := range wrapLine(l, width-4, " ") {
1563 out = append(out, " "+th.FG256(color, w))
1564 }
1565 }
1566 return out
1567}
1568
1569// ShortArgs renders a tool call's arguments into a one-line
1570// suffix for the "tool name <args>" header. tool is the tool
1571// name so we can add shape-specific decorations: for read we
1572// append the requested line range (e.g. "path:1-200") pulled
1573// from the offset/limit args, which is useful context at a
1574// glance without expanding the result body. Other tools keep
1575// the legacy "path or command, truncated at 60 cells" shape.
1576//
1577// Exported because the interactive mode pre-populates the
1578// ToolCallView.Args field with this value as soon as the tool
1579// call is announced, so the live overlay's header matches what
1580// the finalised transcript will later render.
1581func ShortArgs(tool string, raw json.RawMessage) string {
1582 var v any
1583 if err := json.Unmarshal(raw, &v); err != nil {
1584 return ""
1585 }
1586 x, ok := v.(map[string]any)
1587 if !ok {
1588 b, _ := json.Marshal(v)
1589 s := string(b)
1590 if len(s) > 60 {
1591 s = s[:57] + "..."
1592 }
1593 return s
1594 }
1595 var primary string
1596 for _, k := range []string{"path", "file_path", "command"} {
1597 if s, ok := x[k].(string); ok {
1598 primary = s
1599 break
1600 }
1601 }
1602 if primary == "" {
1603 b, _ := json.Marshal(v)
1604 s := string(b)
1605 if len(s) > 60 {
1606 s = s[:57] + "..."
1607 }
1608 return s
1609 }
1610
1611 // Tool-specific decoration. Only the read tool gets a range
1612 // suffix for now; other tools just truncate the primary arg.
1613 suffix := ""
1614 switch strings.ToLower(tool) {
1615 case "read":
1616 start := 1
1617 if n, ok := toInt(x["offset"]); ok && n >= 1 {
1618 start = n
1619 }
1620 if lim, ok := toInt(x["limit"]); ok && lim > 0 {
1621 end := start + lim - 1
1622 suffix = fmt.Sprintf(":%d-%d", start, end)
1623 } else if start > 1 {
1624 suffix = fmt.Sprintf(":%d-", start)
1625 }
1626 }
1627
1628 // Truncate the primary arg leaving room for the suffix so the
1629 // range stays visible even on absurdly long paths.
1630 max := 60 - len(suffix)
1631 if max < 10 {
1632 max = 10
1633 }
1634 if len(primary) > max {
1635 primary = primary[:max-3] + "..."
1636 }
1637 return primary + suffix
1638}
1639
1640// toInt coerces a json.Unmarshal'd number (float64) or a string
1641// containing a number into an int. Returns ok=false if the value
1642// is neither. Used by shortArgs to survive model quirks where
1643// numeric args come back as strings.
1644func toInt(v any) (int, bool) {
1645 switch n := v.(type) {
1646 case float64:
1647 return int(n), true
1648 case int:
1649 return n, true
1650 case string:
1651 i, err := strconv.Atoi(strings.TrimSpace(n))
1652 if err != nil {
1653 return 0, false
1654 }
1655 return i, true
1656 }
1657 return 0, false
1658}
1659
1660func collectText(blocks []provider.Content) string {
1661 var sb strings.Builder
1662 for _, b := range blocks {
1663 if tb, ok := b.(provider.TextBlock); ok {
1664 if sb.Len() > 0 {
1665 sb.WriteString("\n")
1666 }
1667 sb.WriteString(tb.Text)
1668 }
1669 }
1670 return sb.String()
1671}
1672
1673func truncateLines(s string, n int) string {
1674 lines := strings.Split(s, "\n")
1675 if len(lines) <= n {
1676 return s
1677 }
1678 return strings.Join(lines[:n], "\n") + "\n … (" + fmt.Sprintf("%d", len(lines)-n) + " more)"
1679}
1680
1681// renderCompactionBlock renders a compaction summary as a distinct
1682// visual block in the chat. When collapsed it shows a one-line label
1683// with the pre-compaction token count; when expanded (ctrl+o) it
1684// shows the full summary text.
1685func (v *View) renderCompactionBlock(m provider.Message, width int) []string {
1686 th := v.Theme
1687 const indent = " "
1688
1689 tokens := m.Meta["tokens_before"]
1690 if tokens == "" {
1691 tokens = "?"
1692 }
1693
1694 if v.ExpandAll {
1695 var lines []string
1696 header := th.FG256(th.Muted, fmt.Sprintf("compacted from ~%s tokens", tokens))
1697 lines = append(lines, indent+header)
1698 lines = append(lines, "")
1699 for _, c := range m.Content {
1700 if tb, ok := c.(provider.TextBlock); ok {
1701 text := tb.Text
1702 if idx := strings.Index(text, "\n\n"); idx >= 0 && strings.HasPrefix(text, "## Context Summary") {
1703 text = text[idx+2:]
1704 }
1705 md := RenderMarkdown(text, th, width-4)
1706 for _, l := range strings.Split(md, "\n") {
1707 if len(l) > 0 && l[0] == FlushLeftSentinel {
1708 l = l[1:]
1709 }
1710 lines = append(lines, indent+l)
1711 }
1712 }
1713 }
1714 return lines
1715 }
1716
1717 // Collapsed: single line, no banner.
1718 line := th.FG256(th.Muted, fmt.Sprintf("compacted from ~%s tokens (ctrl+o to expand)", tokens))
1719 return []string{indent + line}
1720}
1721
1722// StatusBarParams groups the many bits of state the status bar needs.
1723// Grew from a flat argument list once we settled on the layout.
1724type StatusBarParams struct {
1725 Theme Theme
1726 Provider string
1727 Model string
1728 Busy bool
1729 BusyPrefix string // spinner + funny line when busy
1730 CWD string
1731 Locked bool // sandbox on?
1732 NoYolo bool // confirmation mode enabled?
1733
1734 // Cumulative session usage and cost.
1735 Usage provider.Usage
1736 // Subscription is true when the credential is an OAuth token (claude
1737 // pro/max, chatgpt plus/pro) rather than a paid api key. We still
1738 // compute a cost for visibility and append "(sub)" so the user
1739 // knows no real money moved.
1740 Subscription bool
1741
1742 // Last turn's input+cache tokens (approximates current live context).
1743 ContextUsed int
1744 ContextMax int // model's context window; 0 disables the percentage
1745
1746 // AutoCompacting is true when the agent is currently running a
1747 // model-triggered condense pass. Surfaces as "(auto)" after the
1748 // context percentage so it's clear where the spinner is coming from.
1749 AutoCompacting bool
1750
1751 // Telegram true when the telegram bridge is connected. Adds a
1752 // small "- tg -" tag to the cwd line so the user can tell at a
1753 // glance that dms are being mirrored into this session.
1754 Telegram bool
1755
1756 Cols int // terminal width; drives right-alignment of cwd
1757}
1758
1759// StatusBar builds the status shown above the editor. Always returns
1760// two lines when a cwd is provided: the stats on the first line, the
1761// cwd on its own line below, indented to match the stats column. This
1762// keeps the status bar stable across terminal resizes (the cwd never
1763// jumps from right-aligned-on-line-1 to flush-left-on-line-2) and
1764// makes a long cwd safe at any width.
1765//
1766// Layout:
1767//
1768// <busyPrefix> (provider) model stats <- line 1
1769// cwd <- line 2 (2-space indent)
1770//
1771// The old "ctrl+c exit - /help" / "esc cancel" hint is gone entirely.
1772// The slash-command popup and the queued/sliding-in chips already
1773// cover the discoverability of those keybindings.
1774func StatusBar(p StatusBarParams) []string {
1775 th := p.Theme
1776
1777 // Token stats: only include each segment when non-zero. Keeps
1778 // the bar compact on brand-new sessions.
1779 var stats []string
1780 if p.Usage.InputTokens > 0 {
1781 stats = append(stats, fmt.Sprintf("↑%s", formatTokens(p.Usage.InputTokens)))
1782 }
1783 if p.Usage.OutputTokens > 0 {
1784 stats = append(stats, fmt.Sprintf("↓%s", formatTokens(p.Usage.OutputTokens)))
1785 }
1786 if p.Usage.CacheReadTokens > 0 {
1787 stats = append(stats, fmt.Sprintf("R%s", formatTokens(p.Usage.CacheReadTokens)))
1788 }
1789 if p.Usage.CacheWriteTokens > 0 {
1790 stats = append(stats, fmt.Sprintf("W%s", formatTokens(p.Usage.CacheWriteTokens)))
1791 }
1792
1793 // Cost: always show the dollar value computed from token counts,
1794 // even on subscription. Lets you see what the equivalent api cost
1795 // would be (handy for gauging subscription value). Append "(sub)"
1796 // only as a hint that no real money moved.
1797 var costStr string
1798 if p.Usage.CostUSD > 0 || p.Subscription {
1799 costStr = fmt.Sprintf("$%.3f", p.Usage.CostUSD)
1800 if p.Subscription {
1801 costStr += " (sub)"
1802 }
1803 }
1804 if costStr != "" {
1805 stats = append(stats, costStr)
1806 }
1807
1808 // Context %. Color-coded: yellow >70, red >90.
1809 ctx, ctxColor := contextUsage(th, p.ContextUsed, p.ContextMax)
1810 if ctx != "" {
1811 if p.AutoCompacting {
1812 ctx += " (auto)"
1813 }
1814 stats = append(stats, th.FG256(ctxColor, ctx))
1815 }
1816
1817 // Layout uses exactly 2 spaces of horizontal padding everywhere:
1818 // 2 spaces (openai) gpt-5.4 $0.000 (sub) 0.0%/400k ~/Sites/zot
1819 // matches the editor prompt's left inset so the bar lines up
1820 // vertically with the conversation column.
1821 const pad = " " // 2 spaces
1822
1823 left := fmt.Sprintf("(%s) %s", p.Provider, p.Model)
1824 middle := strings.Join(stats, " ")
1825
1826 var leftBuilder strings.Builder
1827 if p.BusyPrefix != "" {
1828 // Don't re-color the payload itself — the caller already set
1829 // fg colors on the spinner glyph, message, and elapsed
1830 // segments. Wrapping the whole thing here would override
1831 // those choices. The pad itself needs no color (it's spaces).
1832 leftBuilder.WriteString(pad + p.BusyPrefix)
1833 // Exactly one pad (2 spaces) between the busy segment and
1834 // the provider/model block. The leading pad above covers
1835 // the left indent.
1836 leftBuilder.WriteString(pad)
1837 } else {
1838 // Idle path: a single pad of left inset so the line
1839 // aligns with the conversation column on its left edge
1840 // (" you" / " zot" message markers). Without the busy
1841 // prefix there's no trailing separator to double-pad.
1842 leftBuilder.WriteString(pad)
1843 }
1844 leftBuilder.WriteString(th.FG256(th.Muted, left))
1845 if middle != "" {
1846 leftBuilder.WriteString(pad)
1847 // `middle` already has colorized context segments; wrap the rest in muted.
1848 leftBuilder.WriteString(th.FG256(th.Muted, middle))
1849 }
1850
1851 cwd := shortenHome(p.CWD)
1852 tags := ""
1853 if p.NoYolo {
1854 tags += "yolo mode disabled "
1855 }
1856 if p.Locked {
1857 tags += "jailed "
1858 }
1859 if p.Telegram {
1860 tags += "telegram connected "
1861 }
1862 if tags != "" && cwd != "" {
1863 cwd = tags + "- " + cwd
1864 }
1865
1866 primary := leftBuilder.String()
1867
1868 // On narrow terminals the single line wraps badly. If the visible
1869 // width exceeds cols and we have a busy prefix, split: keep the
1870 // busy prefix on line 1, then put model and (if still needed)
1871 // stats on their own rows. This mirrors the idle split below.
1872 if p.Cols > 0 && p.BusyPrefix != "" && visibleWidth(primary) > p.Cols {
1873 busyLine := pad + p.BusyPrefix
1874 modelLine := pad + th.FG256(th.Muted, left)
1875 lines := []string{busyLine}
1876 if middle != "" && visibleWidth(modelLine+pad+th.FG256(th.Muted, middle)) > p.Cols {
1877 lines = append(lines, modelLine)
1878 lines = append(lines, pad+th.FG256(th.Muted, middle))
1879 } else {
1880 var infoBuilder strings.Builder
1881 infoBuilder.WriteString(modelLine)
1882 if middle != "" {
1883 infoBuilder.WriteString(pad)
1884 infoBuilder.WriteString(th.FG256(th.Muted, middle))
1885 }
1886 lines = append(lines, infoBuilder.String())
1887 }
1888 if cwd != "" {
1889 lines = append(lines, pad+th.FG256(th.Muted, cwd))
1890 }
1891 return lines
1892 }
1893
1894 // Idle narrow split: keep provider/model on the first status line,
1895 // move usage/cost/context stats to the next, then cwd below. This
1896 // avoids the terminal's hard wrap cutting the stats or pushing cwd
1897 // into an awkward position on small widths.
1898 if p.Cols > 0 && p.BusyPrefix == "" && middle != "" && visibleWidth(primary) > p.Cols {
1899 lines := []string{
1900 pad + th.FG256(th.Muted, left),
1901 pad + th.FG256(th.Muted, middle),
1902 }
1903 if cwd != "" {
1904 lines = append(lines, pad+th.FG256(th.Muted, cwd))
1905 }
1906 return lines
1907 }
1908
1909 if cwd == "" {
1910 return []string{primary}
1911 }
1912
1913 // Second line: indent with the same 2-space pad so the cwd lines
1914 // up under the "(provider)" column on line 1.
1915 cwdRendered := pad + th.FG256(th.Muted, cwd)
1916 return []string{primary, cwdRendered}
1917}
1918
1919// contextUsage renders the "N%/ctxMax" fragment, returning the
1920// rendered string plus the colour to wrap it in.
1921func contextUsage(th Theme, used, max int) (string, int) {
1922 if max <= 0 {
1923 if used <= 0 {
1924 return "", th.Muted
1925 }
1926 return formatTokens(used), th.Muted
1927 }
1928 pct := float64(used) / float64(max) * 100
1929 text := fmt.Sprintf("%.1f%%/%s", pct, formatTokens(max))
1930 switch {
1931 case pct > 90:
1932 return text, th.Error
1933 case pct > 70:
1934 return text, th.Warning
1935 }
1936 return text, th.Muted
1937}
1938
1939// formatTokens footer formatter:
1940//
1941// < 1000 -> "42"
1942// < 10_000 -> "2.7k"
1943// < 1_000_000 -> "35k"
1944// < 10M -> "1.1M"
1945// else -> "12M"
1946func formatTokens(n int) string {
1947 switch {
1948 case n < 0:
1949 return "0"
1950 case n < 1000:
1951 return fmt.Sprintf("%d", n)
1952 case n < 10000:
1953 return fmt.Sprintf("%.1fk", float64(n)/1000)
1954 case n < 1_000_000:
1955 return fmt.Sprintf("%dk", (n+500)/1000)
1956 case n < 10_000_000:
1957 return fmt.Sprintf("%.1fM", float64(n)/1_000_000)
1958 default:
1959 return fmt.Sprintf("%dM", (n+500_000)/1_000_000)
1960 }
1961}
1962
1963// shortenHome replaces the user's $HOME prefix with "~" for readability.
1964func shortenHome(p string) string {
1965 if p == "" {
1966 return ""
1967 }
1968 home := osUserHome()
1969 if home == "" {
1970 return p
1971 }
1972 if p == home {
1973 return "~"
1974 }
1975 if strings.HasPrefix(p, home+"/") {
1976 return "~" + p[len(home):]
1977 }
1978 return p
1979}
1980
1981// osUserHome is a tiny wrapper around os.UserHomeDir so tests can mock it.
1982var osUserHome = func() string {
1983 if h, err := osUserHomeDir(); err == nil {
1984 return h
1985 }
1986 return ""
1987}