1package tui
2
3import (
4 "encoding/json"
5 "fmt"
6 "os"
7 "regexp"
8 "strconv"
9 "strings"
10 "unicode/utf8"
11
12 "github.com/mattn/go-runewidth"
13 "github.com/patriceckhart/zot/packages/provider"
14)
15
16// expandTabs replaces tab characters with 4 spaces so code from
17// tab-indented languages (Go, Makefiles, etc.) renders at a
18// consistent width instead of the terminal's default 8-column tabs.
19func expandTabs(s string) string {
20 return strings.ReplaceAll(s, "\t", " ")
21}
22
23// sanitizeUserBubbleLine prepares a single user-bubble row for safe
24// rendering. Pasted content from another terminal can contain
25// embedded ANSI escape sequences, control bytes, and tabs that
26// either reset the bubble's background colour or move the cursor in
27// ways that break the bubble's painted column.
28func sanitizeUserBubbleLine(s string) string {
29 if s == "" {
30 return s
31 }
32 s = expandTabs(s)
33 var b strings.Builder
34 b.Grow(len(s))
35 for i := 0; i < len(s); {
36 c := s[i]
37 if c == 0x1b { // ESC: drop CSI/OSC/DCS and simple escapes.
38 i = skipEscapeSequence(s, i)
39 continue
40 }
41 if c == '\r' || c == '\b' || c == 0x07 {
42 i++
43 continue
44 }
45 if c < 0x20 || c == 0x7f {
46 i++
47 continue
48 }
49 b.WriteByte(c)
50 i++
51 }
52 return b.String()
53}
54
55// pathFromToolArgs returns the "path" argument from a tool_call's
56// JSON arguments, or "" if the args aren't a JSON object or don't
57// include one. Used to pick a syntax language for rendering the
58// corresponding tool_result.
59func pathFromToolArgs(raw json.RawMessage) string {
60 if len(raw) == 0 {
61 return ""
62 }
63 var m map[string]any
64 if err := json.Unmarshal(raw, &m); err != nil {
65 return ""
66 }
67 for _, k := range []string{"path", "file_path"} {
68 if s, ok := m[k].(string); ok && s != "" {
69 return s
70 }
71 }
72 return ""
73}
74
75// offsetFromToolArgs returns the read tool's 1-indexed `offset`
76// arg (the first line of the slice the tool was asked to return),
77// or 0 when the call didn't specify one. Used by the tui to draw
78// the line-number gutter aligned to the right starting row, even
79// though the tool's text content itself no longer carries line
80// numbers.
81func offsetFromToolArgs(raw json.RawMessage) int {
82 if len(raw) == 0 {
83 return 0
84 }
85 var m map[string]any
86 if err := json.Unmarshal(raw, &m); err != nil {
87 return 0
88 }
89 switch v := m["offset"].(type) {
90 case float64:
91 return int(v)
92 case int:
93 return v
94 }
95 return 0
96}
97
98// osUserHomeDir is aliased so the test file can swap it.
99var osUserHomeDir = os.UserHomeDir
100
101// View turns a transcript + live state into a slice of styled lines,
102// already wrapped to width.
103type View struct {
104 Theme Theme
105 ImageProto ImageProtocol // how to render inline images in this terminal
106 Messages []provider.Message
107 // toolPaths maps tool_use_id to the "path" argument of the call, if
108 // any, so tool_result rendering can pick the right syntax language.
109 // Rebuilt on each Build().
110 toolPaths map[string]string
111 // toolStartLines maps tool_use_id to the 1-indexed first line
112 // number of a `read` result, pulled from the call's offset arg.
113 // Used by renderNumberedFile to draw a line-number gutter over
114 // raw (unnumbered) file content the model receives. Rebuilt on
115 // each Build().
116 toolStartLines map[string]int
117 // toolCallLabels maps tool_use_id to the box label (tool name +
118 // short args) for the call, so a tool_result message can render
119 // the box top edge without having to look back at the assistant
120 // message that originated the call. Rebuilt on each Build().
121 toolCallLabels map[string]string
122 Streaming string // current assistant text delta
123 StreamingActive bool
124 ToolCalls []ToolCallView // tool calls in flight or completed
125
126 // Startup resource fields list host-loaded inputs before the transcript
127 // without creating provider messages or persisted entries.
128 StartupAgentName string
129 StartupContextPaths []string
130 StartupExtensionNames []string
131 StartupSkillNames []string
132 StatusLine string
133 Err string
134
135 // liveBodyHigh tracks the tallest live-preview body height seen
136 // per tool-call id, so a streaming edit/write/bash box never
137 // shrinks mid-stream. Keyed by ToolCallView.ID. Entries are only
138 // consulted while a call has no Result; interactive mode prunes
139 // the map when a turn ends.
140 liveBodyHigh map[string]int
141 liveBodyExpandAll bool
142
143 // FlatTools renders tool calls without the bordered panel: a quiet
144 // header line per call plus indented, frameless output. The
145 // truncation/expand behaviour and theme colors are unchanged.
146 // False (the default) keeps the bordered box.
147 FlatTools bool
148
149 // CompactUser renders sent user messages as a single quiet gutter
150 // line per wrapped row instead of a tinted bubble with a blank
151 // padding row above and below. False (the default) keeps the
152 // padded, background-tinted bubble.
153 CompactUser bool
154
155 // CompactMode reduces visual chrome in the transcript. Tool calls
156 // render with a flat header and no bordered panel, and sent user
157 // messages render without padded background bubbles. False keeps
158 // the current spacious rendering.
159 CompactMode bool
160
161 // CollapseToolCall retains each tool-call header, the final rendered
162 // preview line, and an explicit error indicator for failed calls.
163 CollapseToolCall bool
164
165 // ExpandAll forces every long tool result to render in full.
166 // Toggled from the tui by ctrl+o. When false, results longer than
167 // ToolCollapseLines collapse to ToolCollapsePreview lines plus a
168 // "... (N more lines, M total, ctrl+o to expand)" footer.
169 ExpandAll bool
170
171 // renderCache holds the per-message rendered line slices so Build
172 // doesn't re-markdown every message on every frame. Keyed by a
173 // struct of (content hash, width, expandAll) — any of those
174 // changing invalidates the entry. Messages are append-only after
175 // they finalise so keeping the cache across turns is safe.
176 //
177 // Streaming/in-flight work (v.Streaming, v.ToolCalls) is never
178 // cached because it changes every delta.
179 renderCache map[msgCacheKey][]string
180
181 // TailLimit caps how many messages from the END of Messages are
182 // rendered. Messages older than the limit emit a zero-row slice
183 // so first paint after a session resume doesn't pay the markdown
184 // / chroma cost for the entire transcript at once. 0 means no
185 // limit (render everything, the historical behaviour). Interactive
186 // raises the cap when the user scrolls past the top of the
187 // already-rendered tail.
188 TailLimit int
189}
190
191// msgCacheKey identifies a cached message render. hash is a 64-bit
192// FNV-1a of the message's content, which is cheap to compute and
193// unambiguous enough for the cache (collisions produce a stale frame,
194// not wrong data, and we recompute on invalidation anyway).
195type msgCacheKey struct {
196 hash uint64
197 width int
198 expandAll bool
199 // turnOpen is true when the previous rendered message belongs to
200 // the same agent turn (assistant tool_use, or tool result). The
201 // header ("▍ zot") is suppressed in that case so a single turn
202 // — even one that spans many assistant/tool message round-trips
203 // in the underlying API — renders under one header instead of a
204 // new one per assistant message.
205 turnOpen bool
206}
207
208// InvalidateRenderCache drops all cached message renders. The tui
209// calls this when the transcript is replaced wholesale (/compact,
210// /clear, session swap) since messages can be replaced in place and
211// a content-hash miss alone doesn't reclaim the old entries.
212func (v *View) InvalidateRenderCache() {
213 v.renderCache = nil
214}
215
216// ToolCollapsePreview is the number of lines shown before a long tool
217// result is replaced with a "... ctrl+o to expand" footer. Tool
218// results shorter than ToolCollapseLines always render in full.
219const (
220 ToolCollapsePreview = 10
221 ToolCollapseLines = 12
222)
223
224// ToolCallView is a pending tool invocation plus optional result.
225type ToolCallView struct {
226 ID string
227 Name string
228 Args string // rendered argument summary
229 Preview string // side-effect-free result shown before confirmation
230 Result string // rendered result preview (truncated)
231 Error bool
232 Done bool
233
234 // Streaming is true while the model is still typing the tool
235 // call's JSON arguments. The TUI renders a live preview of any
236 // interesting string fields (for `write`, the `content`; for
237 // `bash`, the `command`) so the user can watch the file being
238 // composed. Set to false as soon as EvToolUseEnd arrives.
239 Streaming bool
240
241 // RawJSONBuf is the accumulator of every EvToolUseArgs delta
242 // the stream has delivered for this tool call. Used by the
243 // partial-JSON extractor to peel off the live string value
244 // of one named field on each render.
245 RawJSONBuf string
246
247 // LivePath is the `path` arg extracted as soon as it parses
248 // out of RawJSONBuf. Shown next to the tool name in the header
249 // so the user can see which file is being written to.
250 LivePath string
251}
252
253// MessageAnchor records where a rendered message starts in the chat
254// line slice. Used by /jump so the dialog can scroll the viewport to
255// the row where a turn's user prompt begins.
256type MessageAnchor struct {
257 MessageIdx int // index into v.Messages
258 Row int // first row of that message in the Build() output
259}
260
261// Build returns the chat log lines for the given width.
262func (v *View) Build(width int) []string {
263 lines, _ := v.BuildWithAnchors(width)
264 return lines
265}
266
267// BuildLive renders only in-flight assistant/tool/error state. Main-screen
268// scrollback renderers can keep these rows outside the immutable transcript
269// so native scrolling stays stable while a turn streams.
270func (v *View) BuildLive(width int) []string {
271 v.prepareLiveBodyHeights()
272 var out []string
273 if v.StreamingActive && strings.TrimSpace(v.Streaming) != "" {
274 const indent = " "
275 inner := assistantBodyWidth(width - len(indent))
276 md := RenderMarkdown(v.Streaming, v.Theme, inner)
277 for _, l := range strings.Split(md, "\n") {
278 for _, w := range wrapANSILine(l, inner) {
279 out = append(out, indent+w)
280 }
281 }
282 // out = append(out, "")
283 }
284 finalised := map[string]bool{}
285 for _, m := range v.Messages {
286 for _, c := range m.Content {
287 if b, ok := c.(provider.ToolResultBlock); ok {
288 finalised[b.CallID] = true
289 }
290 }
291 }
292 insertedToolGap := false
293 for _, tc := range v.ToolCalls {
294 if finalised[tc.ID] {
295 continue
296 }
297 if !insertedToolGap && len(out) > 0 {
298 out = append(out, "")
299 }
300 insertedToolGap = true
301 out = append(out, v.renderToolCall(tc, width)...)
302 }
303 if v.Err != "" {
304 out = append(out, v.renderErr(width)...)
305 // out = append(out, "")
306 }
307 return out
308}
309
310// renderErr formats v.Err into one or more colored rows, word-wrapped
311// to width so long provider error messages (e.g. a Bedrock 400 with an
312// embedded JSON body) aren't cut off at the terminal edge. The first
313// row carries the "✖ " marker; continuation rows align under the text
314// with a two-cell indent.
315func (v *View) renderErr(width int) []string {
316 const marker = "✖ "
317 const indent = " "
318 wrapWidth := width - len([]rune(marker))
319 if wrapWidth < 8 {
320 wrapWidth = 8
321 }
322 wrapped := wrapLine(v.Err, wrapWidth, "")
323 if len(wrapped) == 0 {
324 wrapped = []string{""}
325 }
326 out := make([]string, 0, len(wrapped))
327 for idx, line := range wrapped {
328 prefix := marker
329 if idx > 0 {
330 prefix = indent
331 }
332 out = append(out, v.Theme.FG256(v.Theme.Error, prefix+line))
333 }
334 return out
335}
336
337func (v *View) renderStartupResources(width int) []string {
338 bodyWidth := width - 2
339 if bodyWidth < 8 {
340 bodyWidth = 8
341 }
342 var out []string
343 appendSection := func(label string, items []string) {
344 if len(items) == 0 {
345 return
346 }
347 out = append(out, v.Theme.FG256(v.Theme.Accent, "["+label+"]"))
348 for _, line := range wrapLine(strings.Join(items, ", "), bodyWidth, "") {
349 out = append(out, v.Theme.FG256(v.Theme.Muted, " "+line))
350 }
351 out = append(out, "")
352 }
353 if v.StartupAgentName != "" {
354 appendSection("Agent", []string{v.StartupAgentName})
355 }
356 appendSection("Context", v.StartupContextPaths)
357 appendSection("Extensions", v.StartupExtensionNames)
358 appendSection("Skills", v.StartupSkillNames)
359 return out
360}
361
362// BuildWithAnchors is like Build but additionally reports the first
363// row occupied by each message in v.Messages. Callers that need to
364// scroll to a specific turn (the /jump dialog) use the anchor slice
365// to map a message index back to a row offset.
366func (v *View) BuildWithAnchors(width int) ([]string, []MessageAnchor) {
367 v.refreshToolPaths()
368 if v.renderCache == nil {
369 v.renderCache = make(map[msgCacheKey][]string)
370 }
371 v.prepareLiveBodyHeights()
372 // Drop high-water entries for calls that are gone or finalised so
373 // the reservation never leaks into a later, shorter tool box.
374 if len(v.liveBodyHigh) > 0 {
375 active := make(map[string]bool, len(v.ToolCalls))
376 for _, tc := range v.ToolCalls {
377 if tc.Result == "" {
378 active[tc.ID] = true
379 }
380 }
381 for id := range v.liveBodyHigh {
382 if !active[id] {
383 delete(v.liveBodyHigh, id)
384 }
385 }
386 }
387
388 // Pre-render every message (hits the cache for unchanged ones) so
389 // we can allocate `out` in a single shot with the exact capacity.
390 // Growing via append on a long transcript copies the backing array
391 // log2(N) times; for a 2000-line scrollback that's enough memcpy
392 // to visibly stutter while typing.
393 rendered := make([][]string, len(v.Messages))
394 total := 0
395 // renderFrom is the first index we actually render. Anything
396 // below it emits a zero-row placeholder; the message still gets
397 // an anchor entry so /jump and scroll math keep working, and a
398 // later Build with a higher TailLimit fills the gap.
399 renderFrom := 0
400 if v.TailLimit > 0 && len(v.Messages) > v.TailLimit {
401 renderFrom = len(v.Messages) - v.TailLimit
402 }
403 for idx, m := range v.Messages {
404 if idx < renderFrom {
405 rendered[idx] = nil
406 continue
407 }
408 // A turn is "open" once the assistant has started responding
409 // to the most recent user prompt. Walk back over consecutive
410 // assistant/tool messages: if any non-user message precedes
411 // this one without a user message in between, we're inside
412 // the same turn and should not draw a new "▍ zot" header.
413 turnOpen := false
414 if m.Role == provider.RoleAssistant {
415 for j := idx - 1; j >= 0; j-- {
416 prev := v.Messages[j]
417 // Skip compaction summary messages — they're
418 // rendered as a muted footer line (or hidden
419 // entirely when collapsed) and don't open a turn.
420 if prev.Meta["compaction"] == "true" {
421 continue
422 }
423 if prev.Role == provider.RoleAssistant || prev.Role == provider.RoleTool {
424 turnOpen = true
425 }
426 break
427 }
428 }
429 lines := v.renderMessageCached(m, width, turnOpen)
430 rendered[idx] = lines
431 total += len(lines) + 1 // +1 for the blank separator row
432 }
433
434 out := make([]string, 0, total+16)
435 out = append(out, v.renderStartupResources(width)...)
436 anchors := make([]MessageAnchor, 0, len(v.Messages))
437 for idx := range v.Messages {
438 anchors = append(anchors, MessageAnchor{MessageIdx: idx, Row: len(out)})
439 out = append(out, rendered[idx]...)
440 // Skip the inter-message blank for messages that rendered
441 // to nothing. An assistant message whose only content is
442 // ToolCallBlock(s) has no rendered output of its own (each
443 // tool result owns its box now), so emitting a blank for it
444 // would compound with the blank from the next real message
445 // and produce two blank rows between adjacent tool boxes.
446 if len(rendered[idx]) == 0 {
447 continue
448 }
449 out = append(out, "")
450 }
451 // Only render the streaming header/body when there's actual
452 // text to show. An empty streaming block (streamOn=true,
453 // Streaming="") appears when a turn starts with a tool_use
454 // block instead of text — in that case the live tool-call
455 // overlay below is the real content and a naked "zot" bar
456 // above it reads as a stray empty message.
457 if v.StreamingActive && strings.TrimSpace(v.Streaming) != "" {
458 // Stream the partial assistant text through the same markdown
459 // renderer used for finalised messages so code fences, diffs,
460 // lists, and inline styles look the same while streaming and
461 // don't suddenly reflow when the turn ends. No speaker header
462 // is drawn; the indent matches the finalised assistant body in
463 // renderMessage so the column stays consistent across the
464 // stream/finalise transition. Width is capped so ultra-wide
465 // terminals don't produce edge-to-edge code-fence rules or
466 // unreadably long prose lines.
467 const indent = " "
468 inner := assistantBodyWidth(width - len(indent))
469 md := RenderMarkdown(v.Streaming, v.Theme, inner)
470 for _, l := range strings.Split(md, "\n") {
471 for _, w := range wrapANSILine(l, inner) {
472 out = append(out, indent+w)
473 }
474 }
475 out = append(out, "")
476 }
477 // Live tool-call overlay: keep the in-flight box visible after
478 // the assistant tool_use is appended, then hide it only when the
479 // matching tool_result reaches the transcript. Assistant tool_use
480 // blocks render no rows of their own, so suppressing the overlay
481 // at that point makes the box disappear while the tool is running.
482 finalised := map[string]bool{}
483 for _, m := range v.Messages {
484 for _, c := range m.Content {
485 if b, ok := c.(provider.ToolResultBlock); ok {
486 finalised[b.CallID] = true
487 }
488 }
489 }
490 for _, tc := range v.ToolCalls {
491 if finalised[tc.ID] {
492 continue
493 }
494 out = append(out, v.renderToolCall(tc, width)...)
495 out = append(out, "")
496 }
497 if v.Err != "" {
498 out = append(out, v.renderErr(width)...)
499 out = append(out, "")
500 }
501 return out, anchors
502}
503
504// prepareLiveBodyHeights resets live tool height reservations when ctrl+o
505// changes expansion state. Expanded content must not keep a collapsed box
506// padded to its former full height.
507func (v *View) prepareLiveBodyHeights() {
508 if v.liveBodyHigh == nil || v.liveBodyExpandAll != v.ExpandAll {
509 v.liveBodyHigh = make(map[string]int)
510 v.liveBodyExpandAll = v.ExpandAll
511 }
512}
513
514// refreshToolPaths rebuilds the tool_use_id -> path map from the
515// current transcript. Called once per Build() so tool result blocks
516// (which may be cached) can look up their syntax language when they
517// were originally rendered. Walking the transcript here is O(N) but
518// cheap compared to markdown/chroma work it enables.
519func (v *View) refreshToolPaths() {
520 v.toolPaths = map[string]string{}
521 v.toolStartLines = map[string]int{}
522 v.toolCallLabels = map[string]string{}
523 for _, m := range v.Messages {
524 for _, c := range m.Content {
525 if tc, ok := c.(provider.ToolCallBlock); ok {
526 if p := pathFromToolArgs(tc.Arguments); p != "" {
527 v.toolPaths[tc.ID] = p
528 }
529 if off := offsetFromToolArgs(tc.Arguments); off >= 1 {
530 v.toolStartLines[tc.ID] = off
531 }
532 v.toolCallLabels[tc.ID] = tc.Name + " " + ShortArgs(tc.Name, tc.Arguments)
533 }
534 }
535 }
536}
537
538// renderMessageCached returns the rendered line slice for m, using the
539// cache if the same (content hash, width, expandAll) combination has
540// been rendered before. The slice returned is shared — callers must
541// not mutate it; Build() only ever appends to its own `out` so the
542// shared slice is safe.
543func (v *View) renderMessageCached(m provider.Message, width int, turnOpen bool) []string {
544 key := msgCacheKey{
545 hash: hashMessage(m),
546 width: width,
547 expandAll: v.ExpandAll,
548 turnOpen: turnOpen,
549 }
550 if v.renderCache != nil {
551 if lines, ok := v.renderCache[key]; ok {
552 return lines
553 }
554 }
555 lines := v.renderMessage(m, width, turnOpen)
556 if v.renderCache != nil {
557 // Bound the cache: 4x the current message count is enough to
558 // survive /compact churn without leaking memory across a very
559 // long session.
560 max := len(v.Messages) * 4
561 if max < 32 {
562 max = 32
563 }
564 if len(v.renderCache) > max {
565 // Drop half the entries. map iteration order gives us a
566 // pseudo-LRU for free.
567 dropped := 0
568 target := len(v.renderCache) / 2
569 for k := range v.renderCache {
570 if dropped >= target {
571 break
572 }
573 delete(v.renderCache, k)
574 dropped++
575 }
576 }
577 v.renderCache[key] = lines
578 }
579 return lines
580}
581
582// hashMessage returns a 64-bit FNV-1a over the role + content blocks
583// of m. Serialising each block to its salient bytes is enough: two
584// messages with the same role and same content render identically.
585func hashMessage(m provider.Message) uint64 {
586 h := fnv64aInit
587 h = fnv64aWrite(h, []byte(m.Role))
588 h = fnv64aWriteByte(h, 0)
589 for _, c := range m.Content {
590 switch b := c.(type) {
591 case provider.TextBlock:
592 h = fnv64aWriteByte(h, 't')
593 h = fnv64aWrite(h, []byte(b.Text))
594 case provider.ImageBlock:
595 h = fnv64aWriteByte(h, 'i')
596 h = fnv64aWrite(h, []byte(b.MimeType))
597 h = fnv64aWrite(h, b.Data)
598 case provider.ToolCallBlock:
599 h = fnv64aWriteByte(h, 'c')
600 h = fnv64aWrite(h, []byte(b.ID))
601 h = fnv64aWrite(h, []byte(b.Name))
602 h = fnv64aWrite(h, []byte(b.Arguments))
603 case provider.ToolResultBlock:
604 h = fnv64aWriteByte(h, 'r')
605 h = fnv64aWrite(h, []byte(b.CallID))
606 if b.IsError {
607 h = fnv64aWriteByte(h, 'E')
608 }
609 for _, inner := range b.Content {
610 switch ib := inner.(type) {
611 case provider.TextBlock:
612 h = fnv64aWrite(h, []byte(ib.Text))
613 case provider.ImageBlock:
614 h = fnv64aWrite(h, []byte(ib.MimeType))
615 h = fnv64aWrite(h, ib.Data)
616 }
617 }
618 }
619 h = fnv64aWriteByte(h, 0)
620 }
621 return h
622}
623
624// FNV-1a implementation inlined so we don't pay the interface cost of
625// hash.Hash64 on every Build(). The whole point here is speed.
626const (
627 fnv64aInit uint64 = 0xcbf29ce484222325
628 fnv64aPrime uint64 = 0x100000001b3
629)
630
631// assistantBodyRightPad is the blank gutter kept on the right
632// side of every assistant prose line.
633const assistantBodyRightPad = 2
634
635// assistantBodyWidth returns the usable width for the assistant
636// message body (markdown prose + code fences). Uses the full
637// column width passed in minus assistantBodyRightPad, clamped
638// at 1 so wrap helpers don't divide by zero on absurdly narrow
639// terminals. The right-side padding keeps a small breathing
640// column to the terminal edge that mirrors the left indent.
641func assistantBodyWidth(outer int) int {
642 outer -= assistantBodyRightPad
643 if outer < 1 {
644 return 1
645 }
646 return outer
647}
648
649func fnv64aWriteByte(h uint64, b byte) uint64 {
650 h ^= uint64(b)
651 h *= fnv64aPrime
652 return h
653}
654
655func fnv64aWrite(h uint64, p []byte) uint64 {
656 for _, b := range p {
657 h ^= uint64(b)
658 h *= fnv64aPrime
659 }
660 return h
661}
662
663func (v *View) renderMessage(m provider.Message, width int, turnOpen bool) []string {
664 var lines []string
665
666 // Compaction summary: render as a single muted line at the end
667 // of the chat instead of as a user message.
668 if m.Meta["compaction"] == "true" {
669 if v.ExpandAll {
670 return v.renderCompactionBlock(m, width)
671 }
672 // Collapsed: skip entirely. The status bar shows the info.
673 return nil
674 }
675
676 switch m.Role {
677 case provider.RoleUser:
678 // User rows: no speaker label. Each line is painted with a
679 // faint bubble background tint (UserBubble) so the user's
680 // turns visually segment the chat without needing a header.
681 // One tinted blank row above and below approximates CSS
682 // padding-top / padding-bottom (terminals can't do fractional
683 // rows, so a full row of bubble-coloured whitespace is the
684 // closest analogue and gives the bubble visible breathing
685 // room).
686 // User rows: a 1-cell "▌" accent bar at column 0 painted on
687 // the bubble bg, so the bar's cell shares the panel tint and
688 // there is no visible gap between bar and panel. (Some terminals
689 // — iTerm2, Apple Terminal — may smear the cell-0 bg into the
690 // window inset to the left; that's a terminal-side rendering
691 // quirk we accept in exchange for a clean bar-to-panel join.)
692 const leftGutter = 0 // cells of bubble bg between bar and text
693 const rightGutter = 2 // cells of bubble bg between text and right edge
694 innerWidth := width - 2 - leftGutter - rightGutter // 2 = bar's two cells (▌ + trailing space)
695 if innerWidth < 1 {
696 innerWidth = 1
697 }
698 row := func(content string) string {
699 inner := strings.Repeat(" ", leftGutter) + content
700 padded := v.Theme.UserBubble(inner, width-2)
701 bar := v.Theme.BG(v.Theme.UserBubbleBG, v.Theme.FG256(v.Theme.Accent, "▌ "))
702 return bar + padded
703 }
704 if v.CompactUser || v.CompactMode {
705 // Compact: no tinted bubble background and no padding rows.
706 // Each wrapped row is a quiet "▌ text" gutter line, matching
707 // the flat tool-call header so user turns still segment the
708 // chat without the loud panel.
709 innerWidth = width - 2
710 if innerWidth < 1 {
711 innerWidth = 1
712 }
713 row = func(content string) string {
714 if v.CompactMode {
715 content = v.Theme.FG256(v.Theme.Muted, content)
716 }
717 return v.Theme.FG256(v.Theme.Accent, "▌ ") + content
718 }
719 }
720 var bubble []string
721 for _, c := range m.Content {
722 switch b := c.(type) {
723 case provider.TextBlock:
724 for _, l := range strings.Split(b.Text, "\n") {
725 l = sanitizeUserBubbleLine(l)
726 for _, w := range wrapLine(l, innerWidth, "") {
727 bubble = append(bubble, row(w))
728 }
729 }
730 case provider.ImageBlock:
731 bubble = append(bubble, row(fmt.Sprintf("[image %s, %d bytes]", b.MimeType, len(b.Data))))
732 }
733 }
734 if len(bubble) > 0 {
735 if v.CompactUser || v.CompactMode {
736 // No tinted padding rows in compact mode; the inter-message
737 // blank from Build() already gives the turn breathing room.
738 lines = append(lines, bubble...)
739 } else {
740 lines = append(lines, row(""))
741 lines = append(lines, bubble...)
742 lines = append(lines, row(""))
743 }
744 }
745 case provider.RoleAssistant:
746 // Assistant rows: no speaker label either. Prose still gets a
747 // small left indent so it visually aligns with tool box body
748 // content, but no "zot" header.
749 _ = turnOpen
750 const indent = " "
751 inner := assistantBodyWidth(width - len(indent))
752 for _, c := range m.Content {
753 switch b := c.(type) {
754 case provider.TextBlock:
755 md := RenderMarkdown(strings.TrimLeft(b.Text, "\n"), v.Theme, inner)
756 for _, l := range strings.Split(md, "\n") {
757 for _, w := range wrapANSILine(l, inner) {
758 lines = append(lines, indent+w)
759 }
760 }
761 case provider.ToolCallBlock:
762 // The whole box (top + body + bottom) is rendered by
763 // the matching tool_result message so a single
764 // assistant message that batches multiple tool_use
765 // blocks doesn't produce a stack of unclosed top
766 // edges. Each tool result owns its own box.
767 _ = b
768 }
769 }
770 case provider.RoleTool:
771 for _, c := range m.Content {
772 if tr, ok := c.(provider.ToolResultBlock); ok {
773 color := v.Theme.ToolOut
774 if tr.IsError {
775 color = v.Theme.Error
776 }
777 path := ""
778 if v.toolPaths != nil {
779 path = v.toolPaths[tr.CallID]
780 }
781 startLine := 1
782 if v.toolStartLines != nil {
783 if s := v.toolStartLines[tr.CallID]; s > 0 {
784 startLine = s
785 }
786 }
787 label := ""
788 if v.toolCallLabels != nil {
789 label = v.toolCallLabels[tr.CallID]
790 }
791 // Each tool result owns a complete box: top edge with
792 // the call's label, body rows wrapped in vertical
793 // edges, bottom edge to close. The label is looked up
794 // from the matching ToolCallBlock so multiple calls
795 // in one assistant message render as N adjacent boxes
796 // instead of stacking unclosed top edges.
797 if v.CollapseToolCall && !v.ExpandAll {
798 body := v.renderToolResultContent(tr.Content, width, color, path, startLine)
799 lines = append(lines, v.renderCollapsedTool(label, body, width, tr.IsError)...)
800 continue
801 }
802 if v.FlatTools || v.CompactMode {
803 if v.CompactMode {
804 lines = append(lines, compactToolBlank(v.Theme, width))
805 }
806 lines = append(lines, toolHeaderLine(v.Theme, label, width, v.CompactMode))
807 if tr.IsError {
808 lines = append(lines, toolBodyLine(v.Theme, v.Theme.FG256(color, " error"), width, v.CompactMode))
809 }
810 for _, line := range v.renderToolResultContent(tr.Content, width, color, path, startLine) {
811 _, stripped := parseImageFootprint(line)
812 lines = append(lines, toolBodyLine(v.Theme, stripped, width, v.CompactMode))
813 }
814 if v.CompactMode {
815 lines = append(lines, compactToolBlank(v.Theme, width))
816 }
817 continue
818 }
819 lines = append(lines, toolBoxTop(v.Theme, label, width))
820 lines = append(lines, toolBoxSide(v.Theme, "", width))
821 if tr.IsError {
822 lines = append(lines, toolBoxSide(v.Theme, v.Theme.FG256(color, " error"), width))
823 }
824 for _, line := range v.renderToolResultContent(tr.Content, width, color, path, startLine) {
825 // Image-footprint rows (the escape row, the blank
826 // reservation rows beneath it, and the gap row
827 // before the metadata caption) are tagged with the
828 // imageFootprintSentinel by renderImageBlock. Strip
829 // the tag, parse the optional width hint, then wrap
830 // the row in the usual │ ... │ box edges so the
831 // frame stays continuous around the image.
832 imgCells, stripped := parseImageFootprint(line)
833 if hasImageEscapeLine(stripped) {
834 lines = append(lines, toolBoxSideWithImage(v.Theme, stripped, imgCells, width))
835 } else {
836 lines = append(lines, toolBoxSide(v.Theme, stripped, width))
837 }
838 }
839 lines = append(lines, toolBoxSide(v.Theme, "", width))
840 lines = append(lines, toolBoxBottom(v.Theme, width))
841 }
842 }
843 }
844 return lines
845}
846
847// RenderToolCall renders one live or completed tool call using the same
848// presentation as tool calls in the main transcript. Dialogs with isolated
849// agent loops use this to avoid maintaining a second tool renderer.
850func (v *View) RenderToolCall(tc ToolCallView, width int) []string {
851 if v.liveBodyHigh == nil {
852 v.liveBodyHigh = make(map[string]int)
853 }
854 return v.renderToolCall(tc, width)
855}
856
857func (v *View) renderToolCall(tc ToolCallView, width int) []string {
858 var lines []string
859
860 // Header label. While the call is still streaming, prefer the
861 // live path extracted from the partial args so the user sees
862 // the target file as soon as it's known, even before the full
863 // JSON arrived.
864 arg := tc.Args
865 if arg == "" && tc.LivePath != "" {
866 arg = tc.LivePath
867 }
868 label := tc.Name + " " + arg
869
870 if v.CollapseToolCall && !v.ExpandAll {
871 bodyText := tc.Result
872 if bodyText == "" {
873 bodyText = tc.Preview
874 }
875 var body []string
876 if bodyText != "" {
877 color := v.Theme.ToolOut
878 if tc.Error {
879 color = v.Theme.Error
880 }
881 bodyWidth := toolBoxBodyRenderWidth(width)
882 if v.FlatTools || v.CompactMode {
883 bodyWidth = flatToolBodyRenderWidth(width)
884 }
885 body = v.renderLiveToolResult(bodyText, bodyWidth, color, tc.LivePath)
886 } else {
887 body = v.renderLiveToolContent(tc, width)
888 }
889 body = v.collapseToolBody(body, false)
890 return v.renderCollapsedTool(label, body, width, tc.Error)
891 }
892
893 // No leading blank: Build()'s inter-message separator already
894 // places one blank row between the previous transcript content
895 // and the live overlay, matching the spacing the same call has
896 // once it finalises into a transcript box. Adding another blank
897 // here would double the gap during streaming and visibly tighten
898 // when the overlay disappears.
899
900 // Live body (write/edit): keep the streamed preview visible until
901 // a proposed or real tool result arrives. The provider can finish the
902 // tool_use JSON before zot has executed the tool, so keying this on
903 // tc.Streaming makes write/edit boxes collapse for a moment between
904 // EvToolUseEnd and confirmation or EvToolResult.
905 if tc.Preview == "" && tc.Result == "" {
906 if body := v.renderLiveToolBody(tc, width); len(body) > 0 {
907 // Pad the live preview up to the call's high-water height so
908 // it never shrinks mid-stream (e.g. between edit 1 and the
909 // start of edit 2). Padding sits inside the box as real
910 // box-side rows so the surrounding layout stays put. The
911 // high-water mark is per call id and is dropped the moment a
912 // Result lands (this branch only runs while Result == "").
913 high := len(body)
914 if v.liveBodyHigh != nil {
915 if prev := v.liveBodyHigh[tc.ID]; prev > high {
916 high = prev
917 }
918 v.liveBodyHigh[tc.ID] = high
919 }
920 if v.FlatTools || v.CompactMode {
921 for len(body) < high {
922 body = append(body, "")
923 }
924 if v.CompactMode {
925 lines = append(lines, compactToolBlank(v.Theme, width))
926 }
927 lines = append(lines, toolHeaderLine(v.Theme, label, width, v.CompactMode))
928 lines = append(lines, body...)
929 if v.CompactMode {
930 lines = append(lines, compactToolBlank(v.Theme, width))
931 }
932 return lines
933 }
934 for len(body) < high {
935 body = append(body, toolBoxSide(v.Theme, "", width))
936 }
937 lines = append(lines, toolBoxTop(v.Theme, label, width))
938 lines = append(lines, toolBoxSide(v.Theme, "", width))
939 lines = append(lines, body...)
940 lines = append(lines, toolBoxSide(v.Theme, "", width))
941 lines = append(lines, toolBoxBottom(v.Theme, width))
942 return lines
943 }
944 }
945
946 bodyText := tc.Result
947 if bodyText == "" {
948 bodyText = tc.Preview
949 }
950
951 // Finished tool call with no body: just the labelled top edge
952 // directly closed by the bottom. Avoids a blank interior row
953 // for no-output tools.
954 if bodyText == "" {
955 if v.FlatTools || v.CompactMode {
956 if v.CompactMode {
957 lines = append(lines, compactToolBlank(v.Theme, width))
958 }
959 lines = append(lines, toolHeaderLine(v.Theme, label, width, v.CompactMode))
960 if v.CompactMode {
961 lines = append(lines, compactToolBlank(v.Theme, width))
962 }
963 return lines
964 }
965 lines = append(lines, toolBoxTop(v.Theme, label, width))
966 lines = append(lines, toolBoxBottom(v.Theme, width))
967 return lines
968 }
969
970 // Finished tool call with a result body. Top edge embeds the
971 // label; body lines go through toolBoxSide so each row gets
972 // vertical edges; bottom edge closes the box. Blank interior
973 // rows after the top and before the bottom give the body a bit
974 // of breathing room from the corners.
975 color := v.Theme.ToolOut
976 if tc.Error {
977 color = v.Theme.Error
978 }
979 if v.FlatTools || v.CompactMode {
980 if v.CompactMode {
981 lines = append(lines, compactToolBlank(v.Theme, width))
982 }
983 lines = append(lines, toolHeaderLine(v.Theme, label, width, v.CompactMode))
984 body := v.renderLiveToolResult(bodyText, flatToolBodyRenderWidth(width), color, tc.LivePath)
985 for _, l := range v.collapseToolBody(body, false) {
986 _, stripped := parseImageFootprint(l)
987 lines = append(lines, toolBodyLine(v.Theme, stripped, width, v.CompactMode))
988 }
989 if v.CompactMode {
990 lines = append(lines, compactToolBlank(v.Theme, width))
991 }
992 return lines
993 }
994 lines = append(lines, toolBoxTop(v.Theme, label, width))
995 lines = append(lines, toolBoxSide(v.Theme, "", width))
996 body := v.renderLiveToolResult(bodyText, toolBoxBodyRenderWidth(width), color, tc.LivePath)
997 for _, l := range v.collapseToolBody(body, false) {
998 imgCells, stripped := parseImageFootprint(l)
999 if hasImageEscapeLine(stripped) {
1000 lines = append(lines, toolBoxSideWithImage(v.Theme, stripped, imgCells, width))
1001 continue
1002 }
1003 lines = append(lines, toolBoxSide(v.Theme, stripped, width))
1004 }
1005 lines = append(lines, toolBoxSide(v.Theme, "", width))
1006 lines = append(lines, toolBoxBottom(v.Theme, width))
1007 return lines
1008}
1009
1010// renderLiveToolResult uses the transcript's text renderer so every rich
1011// confirmation preview immediately gets the same colors, numbered gutters,
1012// and syntax highlighting as its final tool result.
1013func (v *View) renderLiveToolResult(text string, width, color int, sourcePath string) []string {
1014 return v.renderToolText(text, width, color, sourcePath, 1)
1015}
1016
1017// renderLiveToolBody renders the in-flight preview of a streaming
1018// tool call. Supported tools:
1019//
1020// - write: shows the partial `content` field, syntax-highlighted
1021// by the target path's language.
1022// - edit: shows the partial `newText` of the edit currently being
1023// streamed, prefixed with a "editing foo.ts (edit 2)" header so
1024// the user can see which of a multi-edit batch is in progress.
1025// - bash: shows the full command as soon as the JSON args are known,
1026// before stdout/stderr has arrived, so long-running commands are legible.
1027//
1028// Anything else returns nil and only the tool-call header shows.
1029func (v *View) renderLiveToolBody(tc ToolCallView, width int) []string {
1030 return v.wrapLiveBody(v.renderLiveToolContent(tc, width), width)
1031}
1032
1033// renderLiveToolContent returns unframed preview rows so collapsed calls
1034// can select their preview before applying borders or background padding.
1035func (v *View) renderLiveToolContent(tc ToolCallView, width int) []string {
1036 switch tc.Name {
1037 case "write", "Write":
1038 partial, ok, _ := ExtractPartialStringField(tc.RawJSONBuf, "content")
1039 if !ok || partial == "" {
1040 return nil
1041 }
1042 return v.renderRawFile(partial, tc.LivePath, 1)
1043 case "edit", "Edit":
1044 partial, ok, _, idx := ExtractLastNewText(tc.RawJSONBuf)
1045 if !ok || partial == "" {
1046 return nil
1047 }
1048 // Header line hints which edit is streaming and, when more
1049 // than one has landed, how many the model is doing.
1050 hint := fmt.Sprintf("edit %d (streaming)", idx)
1051 body := []string{" " + v.Theme.FG256(v.Theme.Muted, hint), ""}
1052 body = append(body, v.renderRawFile(partial, tc.LivePath, 1)...)
1053 return body
1054 case "bash", "Bash", "powershell", "PowerShell":
1055 command, ok, _ := ExtractPartialStringField(tc.RawJSONBuf, "command")
1056 if !ok || strings.TrimSpace(command) == "" {
1057 return nil
1058 }
1059 prompt := "$ "
1060 if strings.EqualFold(tc.Name, "powershell") {
1061 prompt = "PS> "
1062 }
1063 return v.renderLiveShellCommand(command, width, prompt)
1064 }
1065 return nil
1066}
1067
1068func (v *View) renderLiveShellCommand(command string, width int, promptText string) []string {
1069 inner := toolBoxBodyRenderWidth(width)
1070 if v.FlatTools || v.CompactMode {
1071 inner = flatToolBodyRenderWidth(width)
1072 }
1073 prompt := v.Theme.FG256(v.Theme.Muted, promptText)
1074 var out []string
1075 for i, line := range strings.Split(command, "\n") {
1076 firstPrefix := " "
1077 if i == 0 {
1078 firstPrefix += prompt
1079 } else {
1080 firstPrefix += " "
1081 }
1082 contPrefix := " "
1083 wrapWidth := inner - visibleWidth(firstPrefix)
1084 if wrapWidth < 10 {
1085 wrapWidth = 10
1086 }
1087 for j, wrapped := range wrapANSILine(v.Theme.FG256(v.Theme.ToolOut, line), wrapWidth) {
1088 prefix := firstPrefix
1089 if j > 0 {
1090 prefix = contPrefix
1091 }
1092 out = append(out, prefix+wrapped)
1093 }
1094 }
1095 return out
1096}
1097
1098// wrapLiveBody returns the streaming body content as a list of
1099// box-side rows: each line wrapped in │ ... │ with right padding so
1100// the closing edge sits at column width-1. The caller (renderToolCall)
1101// supplies the surrounding top/bottom edges so the live overlay
1102// renders as a closed box matching the finalised transcript form.
1103func (v *View) wrapLiveBody(body []string, width int) []string {
1104 body = v.collapseToolBody(body, false)
1105 out := make([]string, 0, len(body))
1106 if v.FlatTools || v.CompactMode {
1107 for _, l := range body {
1108 _, stripped := parseImageFootprint(l)
1109 out = append(out, toolBodyLine(v.Theme, stripped, width, v.CompactMode))
1110 }
1111 return out
1112 }
1113 for _, l := range body {
1114 imgCells, stripped := parseImageFootprint(l)
1115 if hasImageEscapeLine(stripped) {
1116 out = append(out, toolBoxSideWithImage(v.Theme, stripped, imgCells, width))
1117 continue
1118 }
1119 out = append(out, toolBoxSide(v.Theme, stripped, width))
1120 }
1121 return out
1122}
1123
1124// toolResultBlock wraps text in thin horizontal rules (top + bottom),
1125// indenting the body with four spaces. The rules span the content column.
1126// toolBlockRule renders the muted horizontal separator drawn
1127// above and below a tool call block. Spans the full content
1128// width so it reads as a real section break in the chat
1129// regardless of terminal size.
1130func toolBlockRule(th Theme, width int) string {
1131 w := width
1132 if w < 8 {
1133 w = 8
1134 }
1135 return th.FG256(th.Muted, strings.Repeat("─", w))
1136}
1137
1138// toolBoxInnerPad is the number of blank cells kept between a box
1139// edge (┌, │, └) and the content inside it. One cell of breathing
1140// room makes the label read as part of the box rather than fused to
1141// the corner, and gives body lines a tiny gutter from the left side.
1142const toolBoxInnerPad = 1
1143
1144// toolBoxOuterMargin is the number of blank cells kept to the left of
1145// the opening corner and to the right of the closing corner. Aligns
1146// the box's frame with the column where user-bubble text begins, so
1147// the conversation reads as one column instead of having tool boxes
1148// running edge-to-edge while user/assistant rows sit indented.
1149const toolBoxOuterMargin = 2
1150
1151// renderCollapsedTool retains the final meaningful preview row and failure
1152// status, applying the configured layout once to unframed body content.
1153func (v *View) renderCollapsedTool(label string, body []string, width int, isError bool) []string {
1154 th := v.Theme
1155 last := ""
1156 for i := len(body) - 1; i >= 0; i-- {
1157 if _, line := parseImageFootprint(body[i]); visibleWidth(strings.TrimSpace(line)) > 0 {
1158 last = line
1159 break
1160 }
1161 }
1162 var preview []string
1163 if isError {
1164 preview = append(preview, th.FG256(th.Error, " error"))
1165 }
1166 if last != "" {
1167 preview = append(preview, last)
1168 }
1169 if v.FlatTools || v.CompactMode {
1170 var out []string
1171 if v.CompactMode {
1172 out = append(out, compactToolBlank(th, width))
1173 }
1174 out = append(out, toolHeaderLine(th, label, width, v.CompactMode))
1175 if v.CompactMode && len(preview) > 0 {
1176 out = append(out, compactToolBlank(th, width))
1177 }
1178 for _, line := range preview {
1179 out = append(out, toolBodyLine(th, line, width, v.CompactMode))
1180 }
1181 if v.CompactMode {
1182 out = append(out, compactToolBlank(th, width))
1183 }
1184 return out
1185 }
1186 out := []string{toolBoxTop(th, label, width), toolBoxSide(th, "", width)}
1187 for _, line := range preview {
1188 out = append(out, toolBoxSide(th, line, width))
1189 }
1190 out = append(out, toolBoxSide(th, "", width), toolBoxBottom(th, width))
1191 return out
1192}
1193
1194// toolBoxTop renders the labelled top edge of a tool block:
1195//
1196// ┌─ bash xcrun simctl list devices ─────────────────────────────┐
1197//
1198// The label is the tool name + short args (the same string previously
1199// shown on its own row beneath the rule). Padding fills the remainder
1200// of the line so the right corner sits at column width-1, matching the
1201// closing edge.
1202func toolBoxTop(th Theme, label string, width int) string {
1203 label = oneLineToolLabel(label)
1204 w := width - 2*toolBoxOuterMargin
1205 if w < 12 {
1206 w = 12
1207 }
1208 margin := strings.Repeat(" ", toolBoxOuterMargin)
1209 innerPad := strings.Repeat(" ", toolBoxInnerPad)
1210 // "┌─" + innerPad + " " + label + " " + innerPad = used; pad
1211 // with ─ to width-1, then "┐".
1212 prefix := "┌─" + innerPad + " "
1213 suffix := " " + innerPad
1214 used := visibleWidth(prefix) + visibleWidth(label) + visibleWidth(suffix)
1215 fill := w - used - 1 // -1 for the closing corner
1216 if fill < 0 {
1217 // Label overflows; truncate with an ellipsis so the right
1218 // corner still lands on the right edge. Rare on real
1219 // terminals (the chat column is usually wide enough).
1220 over := -fill
1221 runes := []rune(label)
1222 if over+3 < len(runes) {
1223 label = string(runes[:len(runes)-over-3]) + "..."
1224 } else {
1225 label = "..."
1226 }
1227 used = visibleWidth(prefix) + visibleWidth(label) + visibleWidth(suffix)
1228 fill = w - used - 1
1229 if fill < 0 {
1230 fill = 0
1231 }
1232 }
1233 fillStr := strings.Repeat("─", fill)
1234 name, rest := splitToolLabel(label)
1235 return margin + th.FG256(th.Muted, prefix) + th.FG256(th.FG, name) + th.FG256(th.Muted, rest+suffix+fillStr+"┐") + margin
1236}
1237
1238func oneLineToolLabel(label string) string {
1239 return strings.Join(strings.Fields(label), " ")
1240}
1241
1242func splitToolLabel(label string) (name, rest string) {
1243 label = strings.TrimLeft(label, " ")
1244 if label == "" {
1245 return "", ""
1246 }
1247 idx := strings.IndexAny(label, " \t")
1248 if idx < 0 {
1249 return label, ""
1250 }
1251 return label[:idx], label[idx:]
1252}
1253
1254// flatToolHeader renders the boxless header line for a tool call:
1255//
1256// ▌ bash xcrun simctl list devices
1257//
1258// It carries the same information as toolBoxTop (tool name + short
1259// args) but drops the frame: a single accent gutter glyph, the tool
1260// name in the foreground color, and the argument summary muted. The
1261// line is left-aligned at the same column the box's opening corner
1262// used (toolBoxOuterMargin) so flat and box renders share a column.
1263func toolHeaderLine(th Theme, label string, width int, compact bool) string {
1264 if compact {
1265 return compactToolHeader(th, label, width)
1266 }
1267 return flatToolHeader(th, label, width)
1268}
1269
1270func flatToolHeader(th Theme, label string, width int) string {
1271 label = oneLineToolLabel(label)
1272 name, rest := splitToolLabel(label)
1273 margin := strings.Repeat(" ", toolBoxOuterMargin)
1274 gutter := th.FG256(th.Assistant, "▌") + " "
1275 // Budget the visible text to the content width so a very long
1276 // argument summary doesn't run off the right edge; truncate with
1277 // an ellipsis like the box header does.
1278 avail := width - toolBoxOuterMargin - visibleWidth("▌ ")
1279 if avail < 12 {
1280 avail = 12
1281 }
1282 if visibleWidth(name+rest) > avail {
1283 over := visibleWidth(name+rest) - avail
1284 runes := []rune(rest)
1285 if over+3 < len(runes) {
1286 rest = string(runes[:len(runes)-over-3]) + "..."
1287 } else if visibleWidth(name) <= avail {
1288 rest = ""
1289 }
1290 }
1291 return margin + gutter + th.FG256(th.FG, name) + th.FG256(th.Muted, rest)
1292}
1293
1294func compactToolBlank(th Theme, width int) string {
1295 if width < 1 {
1296 width = 1
1297 }
1298 return sgrBGColor(th.UserBubbleBG) + strings.Repeat(" ", width) + reset
1299}
1300
1301func compactToolHeader(th Theme, label string, width int) string {
1302 label = oneLineToolLabel(label)
1303 name, rest := splitToolLabel(label)
1304 pad := " "
1305 avail := width - visibleWidth(pad)*2
1306 if avail < 12 {
1307 avail = 12
1308 }
1309 if visibleWidth(name+rest) > avail {
1310 over := visibleWidth(name+rest) - avail
1311 runes := []rune(rest)
1312 if over+3 < len(runes) {
1313 rest = string(runes[:len(runes)-over-3]) + "..."
1314 } else if visibleWidth(name) <= avail {
1315 rest = ""
1316 }
1317 }
1318 plain := pad + name + rest
1319 visible := visibleWidth(plain)
1320 fill := ""
1321 if visible < width {
1322 fill = strings.Repeat(" ", width-visible)
1323 }
1324 bg := sgrBGColor(th.UserBubbleBG)
1325 return bg + pad + sgrFG(th.FG) + name + bg + sgrFG(th.Muted) + rest + bg + fill + reset
1326}
1327
1328func toolBodyLine(th Theme, line string, width int, compact bool) string {
1329 line = flatToolBody(th, line)
1330 if compact {
1331 return compactToolBody(th, line, width)
1332 }
1333 return line
1334}
1335
1336// flatToolBody indents a single body line for boxless rendering. It
1337// trims the same leading padding box bodies do, then prepends a fixed
1338// gutter indent so output sits in a readable column under the header
1339// without any vertical frame. ANSI styling in the line is preserved.
1340func flatToolBody(th Theme, line string) string {
1341 _ = th
1342 line = trimLeadingSpaces(line, toolBoxBodyTrimLeft)
1343 return strings.Repeat(" ", toolBoxOuterMargin+2) + line
1344}
1345
1346func compactToolBody(th Theme, line string, width int) string {
1347 visible := visibleWidth(line)
1348 fill := ""
1349 if visible < width {
1350 fill = strings.Repeat(" ", width-visible)
1351 }
1352 bg := sgrBGColor(th.UserBubbleBG)
1353 return bg + strings.ReplaceAll(line, reset, reset+bg) + bg + fill + reset
1354}
1355
1356// toolBoxBottom renders the bottom edge of a tool block:
1357//
1358// └─────────────────────────────────────────────────────────────────────────────┘
1359//
1360// Spans the same width as toolBoxTop so the corners line up.
1361func toolBoxBottom(th Theme, width int) string {
1362 w := width - 2*toolBoxOuterMargin
1363 if w < 12 {
1364 w = 12
1365 }
1366 margin := strings.Repeat(" ", toolBoxOuterMargin)
1367 line := "└" + strings.Repeat("─", w-2) + "┘"
1368 return margin + th.FG256(th.Muted, line) + margin
1369}
1370
1371// hasImageEscapeLine reports whether s contains a Kitty (\x1b_G) or
1372// iTerm2 (\x1b]1337;File=) inline-image escape. Such rows draw into
1373// the terminal's graphics layer and shouldn't be wrapped with text
1374// box edges.
1375func hasImageEscapeLine(s string) bool {
1376 return strings.Contains(s, "\x1b]1337;File=") || strings.Contains(s, "\x1b_G")
1377}
1378
1379// imageFootprintSentinel marks rows that belong to an inline-image's
1380// reserved footprint — the escape row plus the blank rows below it
1381// plus the gap row before the metadata caption. Any consumer that
1382// wraps content in box edges (│ ... │) detects the sentinel, strips
1383// it, and emits the row — the image graphics rectangle paints over
1384// whatever was drawn there. Uses a non-printing C0 control byte so
1385// it can never appear in normal text or in an ANSI escape sequence
1386// body.
1387//
1388// The escape row carries an extra width hint between two sentinels:
1389// "\x1e<cells>\x1e<spaces+escape>". Wrappers parse the cells count
1390// to know how wide the image is in terminal cells and how many cells
1391// of trailing padding are needed before the closing box edge.
1392const imageFootprintSentinel = "\x1e"
1393
1394// parseImageFootprint splits a footprint-tagged row into (cellsWide,
1395// rest). cellsWide is 0 when the row carries no width hint (the
1396// reservation blanks and gap row don't, only the escape row does).
1397func parseImageFootprint(s string) (int, string) {
1398 if !strings.HasPrefix(s, imageFootprintSentinel) {
1399 return 0, s
1400 }
1401 rest := s[len(imageFootprintSentinel):]
1402 end := strings.Index(rest, imageFootprintSentinel)
1403 if end < 0 {
1404 return 0, rest
1405 }
1406 w, err := strconv.Atoi(rest[:end])
1407 if err != nil {
1408 return 0, rest
1409 }
1410 return w, rest[end+len(imageFootprintSentinel):]
1411}
1412
1413// toolBoxBodyTrimLeft is the number of leading literal spaces stripped
1414// from each body line as it enters toolBoxSide. Body renderers
1415// (renderToolText, renderRawFile, the diff/bash helpers, ...) all
1416// emit a 4-cell indent so the content aligns with the assistant body
1417// column when there's no box around it. Inside a box the box edge +
1418// inner pad already supply most of that gutter, so we drop a couple
1419// of cells from the body's own indent to keep the content from
1420// drifting too far right.
1421const toolBoxBodyTrimLeft = 2
1422
1423// toolBoxBodyRenderWidth is the width body renderers should target before
1424// their rows are wrapped by toolBoxSide. Most body renderers emit a four-cell
1425// indent; toolBoxSide trims toolBoxBodyTrimLeft cells from that indent and
1426// then adds the box edge/padding. Passing the full terminal width lets long
1427// bash/heredoc lines overrun the inner box and makes terminals soft-wrap,
1428// visually breaking the right edge. This returns the maximum renderer width
1429// whose post-trim visible width fits inside the box.
1430func toolBoxBodyRenderWidth(width int) int {
1431 w := width - 2*toolBoxOuterMargin
1432 if w < 12 {
1433 w = 12
1434 }
1435 inner := w - 2 - 2*toolBoxInnerPad
1436 if inner < 1 {
1437 inner = 1
1438 }
1439 return inner + toolBoxBodyTrimLeft
1440}
1441
1442// flatToolBodyRenderWidth is the width body renderers should target in
1443// flat mode. There's no box frame, just the flatToolBody indent
1444// (toolBoxOuterMargin+2 cells), so the renderable width is the
1445// terminal width minus that indent. Renderers emit a 4-cell indent of
1446// their own which flatToolBody trims toolBoxBodyTrimLeft cells from,
1447// so add that back like toolBoxBodyRenderWidth does.
1448func flatToolBodyRenderWidth(width int) int {
1449 inner := width - (toolBoxOuterMargin + 2)
1450 if inner < 1 {
1451 inner = 1
1452 }
1453 return inner + toolBoxBodyTrimLeft
1454}
1455
1456// toolBoxSide wraps a single body line with vertical box edges:
1457//
1458// │ foo bar baz │
1459//
1460// The middle preserves the line verbatim (including any ANSI escapes)
1461// after stripping toolBoxBodyTrimLeft leading literal spaces. One cell
1462// of inner padding sits on each side so the content breathes from the
1463// edges; the right padding fills to column width-1.
1464func toolBoxSide(th Theme, line string, width int) string {
1465 w := width - 2*toolBoxOuterMargin
1466 if w < 12 {
1467 w = 12
1468 }
1469 margin := strings.Repeat(" ", toolBoxOuterMargin)
1470 left := th.FG256(th.Muted, "│") + strings.Repeat(" ", toolBoxInnerPad)
1471 right := strings.Repeat(" ", toolBoxInnerPad) + th.FG256(th.Muted, "│")
1472 inner := w - 2 - 2*toolBoxInnerPad // available between the two pads
1473 line = trimLeadingSpaces(line, toolBoxBodyTrimLeft)
1474
1475 cur := visibleWidth(line)
1476 if cur > inner {
1477 // Last-resort truncation must retain syntax foreground escapes.
1478 // Stripping ANSI here made long read results switch from their
1479 // configured syntax color to the terminal's default foreground
1480 // whenever the window became narrow enough to clip a line.
1481 line = truncateToWidth(line, inner)
1482 cur = visibleWidth(line)
1483 }
1484 pad := inner - cur
1485 if pad < 0 {
1486 pad = 0
1487 }
1488 return margin + left + line + strings.Repeat(" ", pad) + right + margin
1489}
1490
1491// toolBoxSideWithImage wraps a row that carries an inline-image
1492// escape sequence. The image protocols are configured to not move
1493// the cursor after rendering (iTerm: doNotMoveCursor=1, kitty/
1494// ghostty: C=1), so the only visible cell advance on the row is
1495// from the leading indent spaces before the escape. We pad from
1496// there to the right edge column and draw the closing │ there.
1497// imgCells is unused (kept in the signature for compatibility with
1498// the parseImageFootprint width hint).
1499func toolBoxSideWithImage(th Theme, line string, imgCells, width int) string {
1500 _ = imgCells
1501 w := width - 2*toolBoxOuterMargin
1502 if w < 12 {
1503 w = 12
1504 }
1505 margin := strings.Repeat(" ", toolBoxOuterMargin)
1506 left := th.FG256(th.Muted, "│") + strings.Repeat(" ", toolBoxInnerPad)
1507 right := strings.Repeat(" ", toolBoxInnerPad) + th.FG256(th.Muted, "│")
1508 inner := w - 2 - 2*toolBoxInnerPad
1509
1510 line = trimLeadingSpaces(line, toolBoxBodyTrimLeft)
1511
1512 // Count leading spaces (visible cells consumed before the escape).
1513 leading := 0
1514 for leading < len(line) && line[leading] == ' ' {
1515 leading++
1516 }
1517
1518 pad := inner - leading
1519 if pad < 0 {
1520 pad = 0
1521 }
1522 return margin + left + line + strings.Repeat(" ", pad) + right + margin
1523}
1524
1525// trimLeadingSpaces removes up to n literal space characters from the
1526// start of s without touching anything else. ANSI CSI escapes that
1527// appear before the spaces are skipped over (so a coloured indent
1528// like "\x1b[2m text" still loses its first n cells of indent).
1529// Stops as soon as it hits a non-space character.
1530func trimLeadingSpaces(s string, n int) string {
1531 if n <= 0 || s == "" {
1532 return s
1533 }
1534 var b strings.Builder
1535 b.Grow(len(s))
1536 trimmed := 0
1537 i := 0
1538 for i < len(s) {
1539 // Pass through any ANSI escape sequence verbatim.
1540 if s[i] == 0x1b && i+1 < len(s) && s[i+1] == '[' {
1541 end := i + 2
1542 for end < len(s) {
1543 c := s[end]
1544 end++
1545 if c >= 0x40 && c <= 0x7e {
1546 break
1547 }
1548 }
1549 b.WriteString(s[i:end])
1550 i = end
1551 continue
1552 }
1553 if trimmed < n && s[i] == ' ' {
1554 trimmed++
1555 i++
1556 continue
1557 }
1558 b.WriteString(s[i:])
1559 return b.String()
1560 }
1561 return b.String()
1562}
1563
1564// renderToolResultContent renders the body of a tool result block.
1565// Text blocks get the usual rules-wrapped treatment; text that looks
1566// like a unified diff gets +/- coloring. Image blocks are rendered
1567// inline when the terminal supports a protocol, else as a text
1568// placeholder with dimensions.
1569func (v *View) renderToolResultContent(blocks []provider.Content, width, color int, sourcePath string, startLine int) []string {
1570 var body []string
1571 hasImage := false
1572 for _, b := range blocks {
1573 switch bb := b.(type) {
1574 case provider.TextBlock:
1575 bodyWidth := toolBoxBodyRenderWidth(width)
1576 if v.FlatTools || v.CompactMode {
1577 bodyWidth = flatToolBodyRenderWidth(width)
1578 }
1579 body = append(body, v.renderToolText(bb.Text, bodyWidth, color, sourcePath, startLine)...)
1580 case provider.ImageBlock:
1581 hasImage = true
1582 body = append(body, v.renderImageBlock(bb, width)...)
1583 }
1584 }
1585 return v.collapseToolBody(body, hasImage)
1586}
1587
1588// collapseToolBody trims lines to the configured preview size when the
1589// view is not in ExpandAll mode, appending a muted "... ctrl+o to
1590// expand" footer. Image blocks never collapse — they're short in text
1591// rows but represent real content the user wants to see.
1592func (v *View) collapseToolBody(lines []string, hasImage bool) []string {
1593 if v.ExpandAll || hasImage {
1594 return lines
1595 }
1596 if len(lines) <= ToolCollapseLines {
1597 return lines
1598 }
1599 kept := lines[:ToolCollapsePreview]
1600 hidden := len(lines) - ToolCollapsePreview
1601 total := len(lines)
1602 footer := fmt.Sprintf(" ... (%d more lines, %d total, ctrl+o to expand)", hidden, total)
1603 footer = v.Theme.FG256(v.Theme.Muted, footer)
1604 out := append([]string(nil), kept...)
1605 out = append(out, "")
1606 return append(out, footer)
1607}
1608
1609// renderToolText renders a text block inside a tool result. If the
1610// text contains a unified-diff section (lines starting with "--- " /
1611// "+++ " / "+" / "-"/" "), those rows are styled with add/remove
1612// colors matching git diff conventions.
1613func (v *View) renderToolText(text string, width, defaultColor int, sourcePath string, startLine int) []string {
1614 // Legacy path: transcripts saved before we dropped line numbers
1615 // from the read tool still carry " 1\t..." prefixes. Detect and
1616 // strip them, then fall through to the highlighter.
1617 if looksLikeNumberedFile(text) {
1618 return v.renderNumberedFile(text, sourcePath)
1619 }
1620 // If the result embeds a unified diff (the edit tool's output
1621 // starts with a short "applied N edit(s)" line and then a
1622 // standard --- / +++ / +/- patch), render the patch with
1623 // add/remove coloring. This takes priority over the file-like
1624 // detector below because a diff technically has many lines of
1625 // "file content" but what the user cares about is what changed,
1626 // not a dump of the post-edit file.
1627 if looksLikeUnifiedDiff(text) {
1628 return v.renderUnifiedDiff(text, width, sourcePath)
1629 }
1630
1631 // Current path: text came from `read` as raw file bytes. When a
1632 // source path is known (the call had a `path` arg), render with
1633 // a synthetic line-number gutter starting at startLine so the
1634 // on-screen view still looks like cat -n. Doesn't apply to non-
1635 // file tool outputs (bash stdout, display notes, etc.).
1636 if sourcePath != "" && looksLikeFileContent(text) {
1637 return v.renderRawFile(text, sourcePath, startLine)
1638 }
1639
1640 // No truncation — the full tool output is rendered into chat and
1641 // becomes part of the scrollback you can page back through.
1642 lines := strings.Split(text, "\n")
1643
1644 // Bash-result styling: when the first row looks like a shell
1645 // prompt line ("$ ...") emitted by the bash tool, style the
1646 // prompt line in accent and the trailing "[exit N] Took X.Ys"
1647 // line in muted type so the command + timing read at a glance.
1648 // Everything between is left on the default tool-output color.
1649 if len(lines) > 0 && strings.HasPrefix(lines[0], "$ ") {
1650 return v.renderBashResult(lines, width, defaultColor)
1651 }
1652
1653 inDiff := false
1654 oldLine, newLine := 1, 1
1655 var out []string
1656 for _, l := range lines {
1657 // Detect diff header: "--- name" followed somewhere by "+++ name".
1658 if strings.HasPrefix(l, "--- ") || strings.HasPrefix(l, "+++ ") {
1659 inDiff = true
1660 out = append(out, " "+v.Theme.FG256(v.Theme.Muted, l))
1661 continue
1662 }
1663 // Hunk header "@@ -a,b +c,d @@" resets the counters so patches
1664 // that skip around in the file still get correct numbering.
1665 if inDiff && strings.HasPrefix(l, "@@") {
1666 if o, n, ok := parseHunkHeader(l); ok {
1667 oldLine, newLine = o, n
1668 }
1669 out = append(out, " "+v.Theme.FG256(v.Theme.Muted, l))
1670 continue
1671 }
1672 if inDiff && strings.TrimSpace(l) == "..." {
1673 out = append(out, "")
1674 out = append(out, " "+v.Theme.FG256(v.Theme.Muted, "..."))
1675 continue
1676 }
1677 if inDiff && len(l) > 0 {
1678 switch l[0] {
1679 case '+':
1680 out = append(out, v.renderDiffRow(l, width, v.Theme.Tool, newLine, '+', sourcePath)...)
1681 newLine++
1682 continue
1683 case '-':
1684 out = append(out, v.renderDiffRow(l, width, v.Theme.Error, oldLine, '-', sourcePath)...)
1685 oldLine++
1686 continue
1687 case ' ':
1688 out = append(out, v.renderDiffRow(l, width, v.Theme.Muted, newLine, ' ', sourcePath)...)
1689 oldLine++
1690 newLine++
1691 continue
1692 }
1693 }
1694 // Regular line.
1695 for _, w := range wrapLine(l, width-4, " ") {
1696 out = append(out, " "+v.Theme.FG256(defaultColor, w))
1697 }
1698 }
1699 return out
1700}
1701
1702// parseHunkHeader extracts the starting old/new line from a unified
1703// diff hunk header ("@@ -12,5 +12,7 @@ ..."). Returns ok=false if the
1704// header is malformed or missing numbers.
1705func parseHunkHeader(l string) (oldStart, newStart int, ok bool) {
1706 // Skip "@@ "
1707 rest := strings.TrimPrefix(l, "@@")
1708 rest = strings.TrimSpace(rest)
1709 if !strings.HasPrefix(rest, "-") {
1710 return 0, 0, false
1711 }
1712 rest = rest[1:]
1713 space := strings.IndexByte(rest, ' ')
1714 if space < 0 {
1715 return 0, 0, false
1716 }
1717 oldPart := rest[:space]
1718 rest = strings.TrimSpace(rest[space+1:])
1719 if !strings.HasPrefix(rest, "+") {
1720 return 0, 0, false
1721 }
1722 rest = rest[1:]
1723 if sp := strings.IndexAny(rest, " \t"); sp >= 0 {
1724 rest = rest[:sp]
1725 }
1726 parseStart := func(s string) (int, bool) {
1727 if c := strings.IndexByte(s, ','); c >= 0 {
1728 s = s[:c]
1729 }
1730 n, err := strconv.Atoi(s)
1731 if err != nil || n < 1 {
1732 return 0, false
1733 }
1734 return n, true
1735 }
1736 o, ok1 := parseStart(oldPart)
1737 n, ok2 := parseStart(rest)
1738 if !ok1 || !ok2 {
1739 return 0, 0, false
1740 }
1741 return o, n, true
1742}
1743
1744// renderDiffRow renders one unified-diff source line as one or more visual
1745// rows. The first row carries the read-style line-number gutter; continuation
1746// rows use a blank gutter so wrapped content cannot be mistaken for another
1747// source line. Code is syntax-highlighted if sourcePath hints at a known
1748// language and otherwise uses the diff color.
1749func (v *View) renderDiffRow(line string, width, color int, lineNo int, mark byte, sourcePath string) []string {
1750 if len(line) == 0 {
1751 return []string{""}
1752 }
1753 code := expandTabs(line[1:]) // strip the leading marker; expand tabs
1754
1755 // Gutter shape: sign + number share a color so they read as one
1756 // visual token ("+123") instead of a neutral line number next to
1757 // a stray marker. Unchanged context lines get a muted gutter and
1758 // a leading space so column alignment stays consistent with +/-
1759 // rows.
1760 var gutterText string
1761 switch mark {
1762 case '+':
1763 gutterText = fmt.Sprintf("+%3d ", lineNo)
1764 case '-':
1765 gutterText = fmt.Sprintf("-%3d ", lineNo)
1766 default:
1767 gutterText = fmt.Sprintf(" %3d ", lineNo)
1768 }
1769 gutterColor := color
1770 if mark == ' ' {
1771 gutterColor = v.Theme.Muted
1772 }
1773
1774 maxCode := width - visibleWidth(" "+gutterText)
1775 if maxCode < 1 {
1776 maxCode = 1
1777 }
1778 chunks := wrapCodeLine(code, maxCode)
1779 lang := LanguageFromPath(sourcePath)
1780 out := make([]string, 0, len(chunks))
1781 for i, chunk := range chunks {
1782 rowGutter := gutterText
1783 if i > 0 {
1784 rowGutter = strings.Repeat(" ", visibleWidth(gutterText))
1785 }
1786 codeRendered := ""
1787 if lang != "" {
1788 if h := v.Theme.HighlightCode(chunk, lang); len(h) == 1 {
1789 codeRendered = h[0]
1790 }
1791 }
1792 if codeRendered == "" {
1793 codeColor := color
1794 if mark == ' ' {
1795 codeColor = v.Theme.Muted
1796 }
1797 codeRendered = v.Theme.FG256(codeColor, chunk)
1798 }
1799 out = append(out, " "+v.Theme.FG256(gutterColor, rowGutter)+codeRendered)
1800 }
1801 return out
1802}
1803
1804// wrapCodeLine splits code to a terminal cell width without dropping any
1805// characters. It prefers breaking after whitespace, then falls back to a hard
1806// rune boundary for long tokens. Keeping the whitespace on the preceding row
1807// means joining the returned chunks reconstructs the expanded source exactly.
1808func wrapCodeLine(line string, width int) []string {
1809 if width < 1 || visibleWidth(line) <= width {
1810 return []string{line}
1811 }
1812 runes := []rune(line)
1813 var out []string
1814 for start := 0; start < len(runes); {
1815 cells := 0
1816 end := start
1817 lastBreak := -1
1818 for end < len(runes) {
1819 runeWidth := runewidth.RuneWidth(runes[end])
1820 if cells+runeWidth > width && end > start {
1821 break
1822 }
1823 cells += runeWidth
1824 end++
1825 if runes[end-1] == ' ' || runes[end-1] == '\t' {
1826 lastBreak = end
1827 }
1828 if cells >= width {
1829 break
1830 }
1831 }
1832 if end == start { // A rune wider than the requested width.
1833 end++
1834 }
1835 if end < len(runes) && lastBreak > start {
1836 end = lastBreak
1837 }
1838 out = append(out, string(runes[start:end]))
1839 start = end
1840 }
1841 return out
1842}
1843
1844// renderImageBlock returns the lines for one image, inline if possible.
1845//
1846// Inline image escapes paint into multiple terminal rows but the zot
1847// renderer treats each slice entry as a single row. To prevent chat
1848// content from being drawn on top of the image, we pad with blank rows
1849// so the image's real footprint is reflected in the frame height.
1850func (v *View) renderImageBlock(b provider.ImageBlock, width int) []string {
1851 w, h := ImageDimensions(b.Data)
1852 kb := len(b.Data) / 1024
1853 // Four-space indent matches every other tool-output row
1854 // (renderRawFile, renderBashResult, diff rows, "... N more
1855 // lines" footers). Keeps the image's metadata line vertically
1856 // aligned with the file content above / below it.
1857 info := fmt.Sprintf(" image - %s - %dx%d - %d KB", b.MimeType, w, h, kb)
1858
1859 if v.ImageProto != ImageProtocolNone {
1860 // Clamp rendered width so the image never overflows the chat
1861 // column. Subtract a 4-cell indent for the tool result block,
1862 // cap at 60 cells, floor at 10.
1863 cells := width - 4
1864 if cells > 60 {
1865 cells = 60
1866 }
1867 if cells < 10 {
1868 cells = 10
1869 }
1870 const maxRows = 20
1871 if seq := RenderInlineImageScaled(v.ImageProto, b.Data, b.MimeType, cells, maxRows); seq != "" {
1872 rows, actualCells := InlineImageFootprint(b.Data, cells, maxRows)
1873 if rows < 1 {
1874 rows = 1
1875 }
1876 if actualCells < 1 {
1877 actualCells = cells
1878 }
1879 // Reserve the image footprint first, then place the escape
1880 // in the top-left of that blank rectangle. Keeping the
1881 // metadata above the image made some terminals blend text
1882 // and graphics layers during full-screen repaints; metadata
1883 // below the reserved rectangle is more stable and easier to
1884 // read. One extra blank row before the metadata gives the
1885 // caption breathing room from the image's last pixel row.
1886 //
1887 // Every footprint row (escape, reservations, gap) is tagged
1888 // with imageFootprintSentinel so callers wrapping content in
1889 // box edges can recognise these rows and emit them bare —
1890 // the image's graphics rectangle paints over them and any
1891 // │ character drawn alongside would visibly bleed through.
1892 // 4 leading cells push the escape past the box's left
1893 // edge plus a small interior gutter so the image rectangle
1894 // sits visibly inside the frame instead of kissing the │.
1895 // The escape row carries a width hint after the sentinel
1896 // ("\x1e<cells>\x1e...") so toolBoxSide knows how many
1897 // cells the image occupies and can pad to the right edge.
1898 widthHint := fmt.Sprintf("%s%d%s", imageFootprintSentinel, actualCells, imageFootprintSentinel)
1899 out := make([]string, 0, rows+3)
1900 out = append(out, widthHint+" "+seq)
1901 for i := 1; i < rows; i++ {
1902 out = append(out, imageFootprintSentinel)
1903 }
1904 out = append(out, imageFootprintSentinel)
1905 out = append(out, v.Theme.FG256(v.Theme.Muted, info))
1906 return out
1907 }
1908 }
1909 return []string{v.Theme.FG256(v.Theme.Muted, info)}
1910}
1911
1912// looksLikeNumberedFile returns true when text matches the `read`
1913// tool's " N\tcontent" format for most of its lines.
1914func looksLikeNumberedFile(text string) bool {
1915 lines := strings.Split(text, "\n")
1916 if len(lines) == 0 {
1917 return false
1918 }
1919 hits := 0
1920 scanned := 0
1921 for _, l := range lines {
1922 if l == "" {
1923 continue
1924 }
1925 scanned++
1926 if scanned > 20 {
1927 break
1928 }
1929 if numberedLineRE.MatchString(l) {
1930 hits++
1931 }
1932 }
1933 if scanned == 0 {
1934 return false
1935 }
1936 return hits*2 >= scanned // majority of non-empty lines match
1937}
1938
1939var numberedLineRE = regexp.MustCompile(`^\s*\d+\t`)
1940
1941// renderNumberedFile strips line numbers, highlights the code, and
1942// re-attaches the line numbers in muted color.
1943func (v *View) renderNumberedFile(text, sourcePath string) []string {
1944 lines := strings.Split(text, "\n")
1945 gutters := make([]string, 0, len(lines))
1946 codes := make([]string, 0, len(lines))
1947 for _, l := range lines {
1948 idx := strings.IndexByte(l, '\t')
1949 if idx < 0 || !numberedLineRE.MatchString(l) {
1950 // Non-code footer (e.g. "[truncated at 2000 lines]").
1951 gutters = append(gutters, "")
1952 codes = append(codes, l)
1953 continue
1954 }
1955 gutter := l[:idx] + " " // replace tab with single space
1956 code := expandTabs(l[idx+1:])
1957 gutters = append(gutters, gutter)
1958 codes = append(codes, code)
1959 }
1960 lang := LanguageFromPath(sourcePath)
1961 var highlighted []string
1962 if lang != "" {
1963 highlighted = v.Theme.HighlightCode(strings.Join(codes, "\n"), lang)
1964 // Chroma sometimes collapses the trailing empty line. Pad to
1965 // align with the gutter slice so per-line zipping works.
1966 for len(highlighted) < len(codes) {
1967 highlighted = append(highlighted, "")
1968 }
1969 if len(highlighted) > len(codes) {
1970 highlighted = highlighted[:len(codes)]
1971 }
1972 } else {
1973 // No lexer for this file type — render in the ToolOut color so
1974 // code is visually distinct from the muted gutter.
1975 highlighted = make([]string, len(codes))
1976 for i, c := range codes {
1977 highlighted[i] = v.Theme.FG256(v.Theme.ToolOut, c)
1978 }
1979 }
1980 out := make([]string, 0, len(codes))
1981 for i, code := range highlighted {
1982 g := gutters[i]
1983 if g == "" {
1984 out = append(out, " "+v.Theme.FG256(v.Theme.Muted, code))
1985 continue
1986 }
1987 out = append(out, " "+v.Theme.FG256(v.Theme.Muted, g)+code)
1988 }
1989 return out
1990}
1991
1992// looksLikeFileContent is a cheap guard to distinguish a read-tool
1993// result from bash stdout or a status message. File content usually
1994// contains characters that status messages don't (code punctuation,
1995// longer lines, multiple lines) and rarely starts with the " >"-
1996// or "error:"-style prefixes tools emit. False positives are OK,
1997// the worst case is a line-number gutter on something that isn't
1998// really code.
1999// renderBashResult styles a bash tool result: the "$ command" first
2000// line in the accent color, the trailing "[exit N] Took X.Ys" line
2001// in muted type, everything else on the default tool-output color.
2002// Called from renderToolText when the first line starts with "$ ".
2003func (v *View) renderBashResult(lines []string, width, defaultColor int) []string {
2004 lines = normalizeBashOutputLines(lines)
2005 // Identify the footer line (exit + timing). The bash tool writes
2006 // it as the last non-empty line of the result.
2007 footerIdx := -1
2008 for i := len(lines) - 1; i >= 0; i-- {
2009 trimmed := strings.TrimSpace(lines[i])
2010 if trimmed == "" {
2011 continue
2012 }
2013 if strings.HasPrefix(trimmed, "[exit ") {
2014 footerIdx = i
2015 }
2016 break
2017 }
2018
2019 var out []string
2020 for i, l := range lines {
2021 switch {
2022 case i == 0 && strings.HasPrefix(l, "$ "):
2023 // Style the $ and the command text in accent. No
2024 // further processing / wrapping so the shell-style
2025 // prompt reads at a glance.
2026 for _, w := range wrapLine(l, width-4, " ") {
2027 out = append(out, " "+v.Theme.FG256(v.Theme.Accent, w))
2028 }
2029 case i == footerIdx:
2030 for _, w := range wrapLine(l, width-4, " ") {
2031 out = append(out, " "+v.Theme.FG256(v.Theme.Muted, w))
2032 }
2033 default:
2034 for _, w := range wrapLine(l, width-4, " ") {
2035 out = append(out, " "+v.Theme.FG256(defaultColor, w))
2036 }
2037 }
2038 }
2039 return out
2040}
2041
2042// normalizeBashOutputLines turns arbitrary terminal output into plain,
2043// box-safe rows before wrapping. Unlike read/write/edit output, bash
2044// stdout/stderr may contain tabs, carriage returns, ANSI/OSC escapes,
2045// and other C0 controls from subprocesses. If those reach the bordered
2046// tool box, the width calculator can undercount what the terminal will
2047// draw and the right edge appears broken. Keep printable text, expand
2048// tabs to spaces, split carriage-return progress rows, and drop escape
2049// / control sequences.
2050func normalizeBashOutputLines(lines []string) []string {
2051 var out []string
2052 for _, line := range lines {
2053 for _, part := range strings.Split(strings.ReplaceAll(line, "\r", "\n"), "\n") {
2054 out = append(out, normalizeBashOutputLine(part))
2055 }
2056 }
2057 if len(out) == 0 {
2058 return []string{""}
2059 }
2060 return out
2061}
2062
2063func normalizeBashOutputLine(s string) string {
2064 var b strings.Builder
2065 col := 0
2066 for i := 0; i < len(s); {
2067 c := s[i]
2068 if c == 0x1b { // ESC: strip CSI/OSC/DCS and simple escapes.
2069 i = skipEscapeSequence(s, i)
2070 continue
2071 }
2072 r, size := utf8.DecodeRuneInString(s[i:])
2073 if r == utf8.RuneError && size == 1 {
2074 i++
2075 continue
2076 }
2077 switch r {
2078 case '\t':
2079 spaces := 8 - (col % 8)
2080 if spaces == 0 {
2081 spaces = 8
2082 }
2083 b.WriteString(strings.Repeat(" ", spaces))
2084 col += spaces
2085 case '\b':
2086 // Backspace-overstrike output is common in spinners/progress bars.
2087 // Dropping it is safer than moving the TUI cursor backwards.
2088 case '\n', '\r':
2089 // Already split by normalizeBashOutputLines.
2090 default:
2091 if r < 0x20 || r == 0x7f {
2092 // Drop non-printing controls.
2093 break
2094 }
2095 b.WriteRune(r)
2096 col += runewidth.RuneWidth(r)
2097 }
2098 i += size
2099 }
2100 return b.String()
2101}
2102
2103func skipEscapeSequence(s string, i int) int {
2104 if i >= len(s) || s[i] != 0x1b {
2105 return i + 1
2106 }
2107 if i+1 >= len(s) {
2108 return len(s)
2109 }
2110 switch s[i+1] {
2111 case '[': // CSI: ESC [ ... final byte 0x40-0x7e
2112 j := i + 2
2113 for j < len(s) {
2114 c := s[j]
2115 j++
2116 if c >= 0x40 && c <= 0x7e {
2117 break
2118 }
2119 }
2120 return j
2121 case ']': // OSC: ESC ] ... BEL or ST
2122 return skipStringEscape(s, i+2)
2123 case 'P', '_', '^', 'X': // DCS/APC/PM/SOS: ESC P ... ST, etc.
2124 return skipStringEscape(s, i+2)
2125 default:
2126 // Two-byte escape (cursor save/restore, charset select, etc.).
2127 return i + 2
2128 }
2129}
2130
2131func skipStringEscape(s string, i int) int {
2132 for i < len(s) {
2133 if s[i] == 0x07 { // BEL
2134 return i + 1
2135 }
2136 if s[i] == 0x1b && i+1 < len(s) && s[i+1] == '\\' { // ST
2137 return i + 2
2138 }
2139 i++
2140 }
2141 return len(s)
2142}
2143
2144// looksLikeUnifiedDiff reports whether text is a context diff as
2145// emitted by the edit tool: rows start with '+', '-', ' ', or
2146// literal "..." (context-break marker). The presence of at least
2147// one '+' or '-' row distinguishes a real diff from an ordinary
2148// file whose lines happen to begin with a space.
2149func looksLikeUnifiedDiff(text string) bool {
2150 lines := strings.Split(text, "\n")
2151 if len(lines) < 2 {
2152 return false
2153 }
2154 sawChange := false
2155 for _, l := range lines {
2156 if l == "" {
2157 continue
2158 }
2159 if l == "..." {
2160 continue
2161 }
2162 switch l[0] {
2163 case '+', '-':
2164 sawChange = true
2165 case ' ':
2166 // context, ok
2167 default:
2168 return false
2169 }
2170 }
2171 return sawChange
2172}
2173
2174// renderUnifiedDiff renders the edit tool's context diff. Each
2175// kept row shows a line-number gutter plus a marker column: '+'
2176// for additions (colored like add), '-' for deletions (colored
2177// like remove), and unmarked context in muted type. A literal
2178// "..." line between hunks renders as an ellipsis in muted type,
2179// indicating skipped unchanged rows. The old and new line
2180// counters advance so each row carries its actual position in
2181// the pre- or post-edit file. Heuristic: when we hit a "...", we
2182// can't know where the next hunk starts, so we don't reset the
2183// counters — they stay approximate in the rare multi-hunk case.
2184func (v *View) renderUnifiedDiff(text string, width int, sourcePath string) []string {
2185 lines := strings.Split(text, "\n")
2186 if n := len(lines); n > 0 && lines[n-1] == "" {
2187 lines = lines[:n-1]
2188 }
2189 oldLine, newLine := 1, 1
2190 var out []string
2191 for _, l := range lines {
2192 if l == "" {
2193 out = append(out, "")
2194 continue
2195 }
2196 if l == "..." {
2197 out = append(out, " "+v.Theme.FG256(v.Theme.Muted, "..."))
2198 continue
2199 }
2200 switch l[0] {
2201 case '+':
2202 out = append(out, v.renderDiffRow(l, width, v.Theme.Tool, newLine, '+', sourcePath)...)
2203 newLine++
2204 case '-':
2205 out = append(out, v.renderDiffRow(l, width, v.Theme.Error, oldLine, '-', sourcePath)...)
2206 oldLine++
2207 case ' ':
2208 out = append(out, v.renderDiffRow(l, width, v.Theme.Muted, newLine, ' ', sourcePath)...)
2209 oldLine++
2210 newLine++
2211 default:
2212 for _, w := range wrapLine(l, width-4, " ") {
2213 out = append(out, " "+v.Theme.FG256(v.Theme.Muted, w))
2214 }
2215 }
2216 }
2217 return out
2218}
2219
2220func looksLikeFileContent(text string) bool {
2221 if strings.TrimSpace(text) == "" {
2222 return false
2223 }
2224 lines := strings.Split(text, "\n")
2225 return len(lines) >= 2
2226}
2227
2228// renderRawFile renders file content received without embedded line
2229// numbers (the current read-tool output). Draws a muted gutter like
2230// "%6d \t" starting at startLine, highlights the code using the
2231// source path's language, and returns the formatted lines.
2232func (v *View) renderRawFile(text, sourcePath string, startLine int) []string {
2233 lines := strings.Split(text, "\n")
2234 // Drop the trailing empty line that Split produces when text ends
2235 // in "\n" so the gutter doesn't show a phantom last number.
2236 if n := len(lines); n > 0 && lines[n-1] == "" {
2237 lines = lines[:n-1]
2238 }
2239 // Split code from trailing footer lines ("... [truncated ...]")
2240 // so we don't number the footer. A single blank separator line
2241 // immediately before the footer is also pulled out so the
2242 // gutter doesn't render a phantom number for it.
2243 codeEnd := len(lines)
2244 for i := len(lines) - 1; i >= 0; i-- {
2245 if strings.HasPrefix(lines[i], "...") {
2246 codeEnd = i
2247 continue
2248 }
2249 break
2250 }
2251 if codeEnd > 0 && codeEnd < len(lines) && lines[codeEnd-1] == "" {
2252 codeEnd--
2253 }
2254 code := lines[:codeEnd]
2255 footer := lines[codeEnd:]
2256
2257 // Expand tabs to 4 spaces so Go / Makefile code renders
2258 // at a consistent width.
2259 for i, c := range code {
2260 code[i] = expandTabs(c)
2261 }
2262
2263 lang := LanguageFromPath(sourcePath)
2264 var highlighted []string
2265 if lang != "" {
2266 highlighted = v.Theme.HighlightCode(strings.Join(code, "\n"), lang)
2267 for len(highlighted) < len(code) {
2268 highlighted = append(highlighted, "")
2269 }
2270 if len(highlighted) > len(code) {
2271 highlighted = highlighted[:len(code)]
2272 }
2273 } else {
2274 highlighted = make([]string, len(code))
2275 for i, c := range code {
2276 highlighted[i] = v.Theme.FG256(v.Theme.ToolOut, c)
2277 }
2278 }
2279
2280 out := make([]string, 0, len(lines))
2281 for i, c := range highlighted {
2282 gutter := fmt.Sprintf("%4d ", startLine+i)
2283 out = append(out, " "+v.Theme.FG256(v.Theme.Muted, gutter)+c)
2284 }
2285 for _, f := range footer {
2286 out = append(out, " "+v.Theme.FG256(v.Theme.Muted, f))
2287 }
2288 return out
2289}
2290
2291// toolResultBlock renders the live tool-call result body (shown
2292// while the turn is still in flight). The rules that used to
2293// bracket this block have been dropped so the live path looks
2294// identical to the transcript rendering that replaces it when
2295// the turn ends.
2296func toolResultBlock(th Theme, text string, width int, color int) []string {
2297 var out []string
2298 for _, l := range strings.Split(text, "\n") {
2299 for _, w := range wrapLine(l, width-4, " ") {
2300 out = append(out, " "+th.FG256(color, w))
2301 }
2302 }
2303 return out
2304}
2305
2306// defaultToolArgWidth is the number of cells the tool-call header
2307// truncates the primary argument (path/command/query) to when the
2308// ZOT_TOOL_ARG_WIDTH environment variable is unset or invalid.
2309const defaultToolArgWidth = 60
2310
2311// toolArgWidth returns the maximum cell width for the truncated
2312// primary argument shown in a tool-call header. It defaults to
2313// defaultToolArgWidth but can be raised or lowered with the
2314// ZOT_TOOL_ARG_WIDTH environment variable, which is useful for wide
2315// terminals where the default clips long queries too aggressively.
2316// Values outside the sane range [20, 500] are ignored so a stray or
2317// malformed setting can never produce an unreadable header or an
2318// out-of-range slice.
2319func toolArgWidth() int {
2320 v := strings.TrimSpace(os.Getenv("ZOT_TOOL_ARG_WIDTH"))
2321 if v == "" {
2322 return defaultToolArgWidth
2323 }
2324 n, err := strconv.Atoi(v)
2325 if err != nil || n < 20 || n > 500 {
2326 return defaultToolArgWidth
2327 }
2328 return n
2329}
2330
2331// ShortArgs renders a tool call's arguments into a one-line
2332// suffix for the "tool name <args>" header. tool is the tool
2333// name so we can add shape-specific decorations: for read we
2334// append the requested line range (e.g. "path:1-200") pulled
2335// from the offset/limit args, which is useful context at a
2336// glance without expanding the result body. Other tools keep
2337// the legacy "path or command, truncated" shape.
2338//
2339// The truncation width defaults to 60 cells but can be tuned via
2340// the ZOT_TOOL_ARG_WIDTH environment variable (see toolArgWidth).
2341//
2342// Exported because the interactive mode pre-populates the
2343// ToolCallView.Args field with this value as soon as the tool
2344// call is announced, so the live overlay's header matches what
2345// the finalised transcript will later render.
2346func ShortArgs(tool string, raw json.RawMessage) string {
2347 width := toolArgWidth()
2348 var v any
2349 if err := json.Unmarshal(raw, &v); err != nil {
2350 return ""
2351 }
2352 x, ok := v.(map[string]any)
2353 if !ok {
2354 b, _ := json.Marshal(v)
2355 s := oneLineToolLabel(string(b))
2356 if len(s) > width {
2357 s = s[:width-3] + "..."
2358 }
2359 return s
2360 }
2361 var primary string
2362 for _, k := range []string{"pattern", "path", "file_path", "command"} {
2363 if s, ok := x[k].(string); ok {
2364 primary = s
2365 break
2366 }
2367 }
2368 if primary == "" {
2369 b, _ := json.Marshal(v)
2370 s := oneLineToolLabel(string(b))
2371 if len(s) > width {
2372 s = s[:width-3] + "..."
2373 }
2374 return s
2375 }
2376 primary = oneLineToolLabel(primary)
2377
2378 // Tool-specific decoration.
2379 suffix := ""
2380 switch strings.ToLower(tool) {
2381 case "read":
2382 start := 1
2383 if n, ok := toInt(x["offset"]); ok && n >= 1 {
2384 start = n
2385 }
2386 if lim, ok := toInt(x["limit"]); ok && lim > 0 {
2387 end := start + lim - 1
2388 suffix = fmt.Sprintf(":%d-%d", start, end)
2389 } else if start > 1 {
2390 suffix = fmt.Sprintf(":%d-", start)
2391 }
2392 case "glob":
2393 if dir, ok := x["path"].(string); ok && dir != "" && dir != "." {
2394 suffix = " in " + dir
2395 }
2396 }
2397
2398 // Truncate the primary arg leaving room for the suffix so the
2399 // range stays visible even on absurdly long paths.
2400 max := width - len(suffix)
2401 if max < 10 {
2402 max = 10
2403 }
2404 if len(primary) > max {
2405 primary = primary[:max-3] + "..."
2406 }
2407 return primary + suffix
2408}
2409
2410// toInt coerces a json.Unmarshal'd number (float64) or a string
2411// containing a number into an int. Returns ok=false if the value
2412// is neither. Used by shortArgs to survive model quirks where
2413// numeric args come back as strings.
2414func toInt(v any) (int, bool) {
2415 switch n := v.(type) {
2416 case float64:
2417 return int(n), true
2418 case int:
2419 return n, true
2420 case string:
2421 i, err := strconv.Atoi(strings.TrimSpace(n))
2422 if err != nil {
2423 return 0, false
2424 }
2425 return i, true
2426 }
2427 return 0, false
2428}
2429
2430func collectText(blocks []provider.Content) string {
2431 var sb strings.Builder
2432 for _, b := range blocks {
2433 if tb, ok := b.(provider.TextBlock); ok {
2434 if sb.Len() > 0 {
2435 sb.WriteString("\n")
2436 }
2437 sb.WriteString(tb.Text)
2438 }
2439 }
2440 return sb.String()
2441}
2442
2443func truncateLines(s string, n int) string {
2444 lines := strings.Split(s, "\n")
2445 if len(lines) <= n {
2446 return s
2447 }
2448 return strings.Join(lines[:n], "\n") + "\n ... (" + fmt.Sprintf("%d", len(lines)-n) + " more)"
2449}
2450
2451// renderCompactionBlock renders a compaction summary as a distinct
2452// visual block in the chat. When collapsed it shows a one-line label
2453// with the pre-compaction token count; when expanded (ctrl+o) it
2454// shows the full summary text.
2455func (v *View) renderCompactionBlock(m provider.Message, width int) []string {
2456 th := v.Theme
2457 const indent = " "
2458
2459 tokens := m.Meta["tokens_before"]
2460 if tokens == "" {
2461 tokens = "?"
2462 }
2463
2464 if v.ExpandAll {
2465 var lines []string
2466 header := th.FG256(th.Muted, fmt.Sprintf("compacted from ~%s tokens", tokens))
2467 lines = append(lines, indent+header)
2468 lines = append(lines, "")
2469 for _, c := range m.Content {
2470 if tb, ok := c.(provider.TextBlock); ok {
2471 text := tb.Text
2472 if idx := strings.Index(text, "\n\n"); idx >= 0 && strings.HasPrefix(text, "## Context Summary") {
2473 text = text[idx+2:]
2474 }
2475 md := RenderMarkdown(text, th, width-4)
2476 for _, l := range strings.Split(md, "\n") {
2477 if len(l) > 0 && l[0] == FlushLeftSentinel {
2478 l = l[1:]
2479 }
2480 lines = append(lines, indent+l)
2481 }
2482 }
2483 }
2484 return lines
2485 }
2486
2487 // Collapsed: single line, no banner.
2488 line := th.FG256(th.Muted, fmt.Sprintf("compacted from ~%s tokens (ctrl+o to expand)", tokens))
2489 return []string{indent + line}
2490}
2491
2492// StatusBarParams groups the many bits of state the status bar needs.
2493// Grew from a flat argument list once we settled on the layout.
2494type StatusBarParams struct {
2495 Theme Theme
2496 Provider string
2497 Model string
2498 Reasoning string // "" means thinking off
2499 Busy bool
2500 BusyPrefix string // spinner + funny line when busy
2501 CWD string
2502 Locked bool // sandbox on?
2503 NoYolo bool // confirmation mode enabled?
2504
2505 // Cumulative session usage and cost.
2506 Usage provider.Usage
2507 // Subscription is true when the credential is an OAuth token (claude
2508 // pro/max, chatgpt plus/pro) rather than a paid api key. We still
2509 // compute a cost for visibility and append "(sub)" so the user
2510 // knows no real money moved.
2511 Subscription bool
2512
2513 // Last turn's input+cache tokens (approximates current live context).
2514 ContextUsed int
2515 ContextMax int // model's context window; 0 disables the percentage
2516
2517 // AutoCompacting is true when the agent is currently running a
2518 // model-triggered condense pass. Surfaces as "(auto)" after the
2519 // context percentage so it's clear where the spinner is coming from.
2520 AutoCompacting bool
2521
2522 // Telegram true when the telegram bridge is connected. Adds a
2523 // small "- tg -" tag to the cwd line so the user can tell at a
2524 // glance that dms are being mirrored into this session.
2525 Telegram bool
2526
2527 Cols int // terminal width; drives right-alignment of cwd
2528}
2529
2530// StatusBar builds the status shown above the editor. Always returns
2531// two lines when a cwd is provided: the stats on the first line, the
2532// cwd on its own line below, indented to match the stats column. This
2533// keeps the status bar stable across terminal resizes (the cwd never
2534// jumps from right-aligned-on-line-1 to flush-left-on-line-2) and
2535// makes a long cwd safe at any width.
2536//
2537// Layout:
2538//
2539// <busyPrefix> (provider) model stats <- line 1
2540// cwd <- line 2 (2-space indent)
2541//
2542// The old "ctrl+c exit - /help" / "esc cancel" hint is gone entirely.
2543// The slash-command popup and the queued/sliding-in chips already
2544// cover the discoverability of those keybindings.
2545func StatusBar(p StatusBarParams) []string {
2546 th := p.Theme
2547
2548 // Token stats: only include each segment when non-zero. Keeps
2549 // the bar compact on brand-new sessions.
2550 var stats []string
2551 if p.Usage.InputTokens > 0 {
2552 stats = append(stats, fmt.Sprintf("↑%s", formatTokens(p.Usage.InputTokens)))
2553 }
2554 if p.Usage.OutputTokens > 0 {
2555 stats = append(stats, fmt.Sprintf("↓%s", formatTokens(p.Usage.OutputTokens)))
2556 }
2557 if p.Usage.CacheReadTokens > 0 {
2558 stats = append(stats, fmt.Sprintf("R%s", formatTokens(p.Usage.CacheReadTokens)))
2559 }
2560 if p.Usage.CacheWriteTokens > 0 {
2561 stats = append(stats, fmt.Sprintf("W%s", formatTokens(p.Usage.CacheWriteTokens)))
2562 }
2563
2564 // Cost: always show the dollar value computed from token counts,
2565 // even on subscription. Lets you see what the equivalent api cost
2566 // would be (handy for gauging subscription value). Append "(sub)"
2567 // only as a hint that no real money moved.
2568 var costStr string
2569 if p.Usage.CostUSD > 0 || p.Subscription {
2570 costStr = fmt.Sprintf("$%.3f", p.Usage.CostUSD)
2571 if p.Subscription {
2572 costStr += " (sub)"
2573 }
2574 }
2575 if costStr != "" {
2576 stats = append(stats, costStr)
2577 }
2578
2579 // Context %. Color-coded: yellow >70, red >90.
2580 ctx, ctxColor := contextUsage(th, p.ContextUsed, p.ContextMax)
2581 if ctx != "" {
2582 if p.AutoCompacting {
2583 ctx += " (auto)"
2584 }
2585 stats = append(stats, th.FG256(ctxColor, ctx))
2586 }
2587
2588 // Layout uses exactly 2 spaces of horizontal padding everywhere:
2589 // 2 spaces (openai) gpt-5.4 $0.000 (sub) 0.0%/400k ~/Sites/zot
2590 // matches the editor prompt's left inset so the bar lines up
2591 // vertically with the conversation column.
2592 const pad = " " // 2 spaces
2593
2594 left := fmt.Sprintf("(%s) %s", p.Provider, p.Model)
2595 reasoning := reasoningLevelLabel(p.Reasoning)
2596 reasoningText := ""
2597 if reasoning != "" {
2598 reasoningText = "reasoning: " + reasoning
2599 }
2600 statsText := strings.Join(stats, " ")
2601 middleParts := make([]string, 0, 2)
2602 if reasoningText != "" {
2603 middleParts = append(middleParts, reasoningText)
2604 }
2605 if statsText != "" {
2606 middleParts = append(middleParts, statsText)
2607 }
2608 middle := strings.Join(middleParts, " ")
2609
2610 var leftBuilder strings.Builder
2611 if p.BusyPrefix != "" {
2612 // Don't re-color the payload itself — the caller already set
2613 // fg colors on the spinner glyph, message, and elapsed
2614 // segments. Wrapping the whole thing here would override
2615 // those choices. The pad itself needs no color (it's spaces).
2616 leftBuilder.WriteString(pad + p.BusyPrefix)
2617 // Exactly one pad (2 spaces) between the busy segment and
2618 // the provider/model block. The leading pad above covers
2619 // the left indent.
2620 leftBuilder.WriteString(pad)
2621 } else {
2622 // Idle path: a single pad of left inset so the line
2623 // aligns with the conversation column on its left edge
2624 // (" you" / " zot" message markers). Without the busy
2625 // prefix there's no trailing separator to double-pad.
2626 leftBuilder.WriteString(pad)
2627 }
2628 leftBuilder.WriteString(th.FG256(th.Muted, left))
2629 if middle != "" {
2630 leftBuilder.WriteString(pad)
2631 // Highlight the opt-in max tier; other status information stays muted.
2632 leftBuilder.WriteString(th.FG256(reasoningStatusColor(th, reasoningText), middle))
2633 }
2634
2635 cwd := shortenHome(p.CWD)
2636 tags := ""
2637 if p.NoYolo {
2638 tags += "yolo mode disabled "
2639 }
2640 if p.Locked {
2641 tags += "jailed "
2642 }
2643 if p.Telegram {
2644 tags += "telegram connected "
2645 }
2646 if tags != "" && cwd != "" {
2647 cwd = tags + "- " + cwd
2648 }
2649
2650 primary := leftBuilder.String()
2651
2652 // On narrow terminals the single line wraps badly. If the visible
2653 // width exceeds cols and we have a busy prefix, split: keep the
2654 // busy prefix on line 1, then put model and (if still needed)
2655 // stats on their own rows. This mirrors the idle split below.
2656 if p.Cols > 0 && p.BusyPrefix != "" && visibleWidth(primary) > p.Cols {
2657 busyLine := pad + p.BusyPrefix
2658 modelLine := pad + th.FG256(th.Muted, left)
2659 lines := []string{busyLine}
2660 if middle != "" && visibleWidth(modelLine+pad+th.FG256(th.Muted, middle)) > p.Cols {
2661 lines = appendWrappedStatusLines(lines, th, pad, left, reasoningText, statsText, p.Cols)
2662 } else {
2663 var infoBuilder strings.Builder
2664 infoBuilder.WriteString(modelLine)
2665 if middle != "" {
2666 infoBuilder.WriteString(pad)
2667 infoBuilder.WriteString(th.FG256(reasoningStatusColor(th, reasoningText), middle))
2668 }
2669 lines = append(lines, infoBuilder.String())
2670 }
2671 if cwd != "" {
2672 lines = append(lines, pad+th.FG256(th.Muted, cwd))
2673 }
2674 return lines
2675 }
2676
2677 // Idle narrow split: keep provider/model on the first status line,
2678 // move usage/cost/context stats to the next, then cwd below. This
2679 // avoids the terminal's hard wrap cutting the stats or pushing cwd
2680 // into an awkward position on small widths.
2681 if p.Cols > 0 && p.BusyPrefix == "" && middle != "" && visibleWidth(primary) > p.Cols {
2682 var lines []string
2683 lines = appendWrappedStatusLines(lines, th, pad, left, reasoningText, statsText, p.Cols)
2684 if cwd != "" {
2685 lines = append(lines, pad+th.FG256(th.Muted, cwd))
2686 }
2687 return lines
2688 }
2689
2690 if cwd == "" {
2691 return []string{primary}
2692 }
2693
2694 // Second line: indent with the same 2-space pad so the cwd lines
2695 // up under the "(provider)" column on line 1.
2696 cwdRendered := pad + th.FG256(th.Muted, cwd)
2697 return []string{primary, cwdRendered}
2698}
2699
2700func appendWrappedStatusLines(lines []string, th Theme, pad, modelText, reasoningText, statsText string, cols int) []string {
2701 modelLine := pad + th.FG256(th.Muted, modelText)
2702 if reasoningText == "" {
2703 lines = append(lines, modelLine)
2704 if statsText != "" {
2705 lines = append(lines, pad+th.FG256(th.Muted, statsText))
2706 }
2707 return lines
2708 }
2709
2710 modelReasoningPlain := pad + modelText + pad + reasoningText
2711 reasoningColor := reasoningStatusColor(th, reasoningText)
2712 if cols <= 0 || visibleWidth(modelReasoningPlain) <= cols {
2713 lines = append(lines, pad+th.FG256(reasoningColor, modelText+pad+reasoningText))
2714 } else {
2715 lines = append(lines, modelLine)
2716 lines = append(lines, pad+th.FG256(reasoningColor, reasoningText))
2717 }
2718 if statsText != "" {
2719 lines = append(lines, pad+th.FG256(th.Muted, statsText))
2720 }
2721 return lines
2722}
2723
2724func reasoningStatusColor(th Theme, reasoningText string) int {
2725 if strings.HasSuffix(reasoningText, ": max") {
2726 return th.ThinkingMax
2727 }
2728 return th.Muted
2729}
2730
2731func reasoningLevelLabel(level string) string {
2732 switch strings.ToLower(strings.TrimSpace(level)) {
2733 case "", "off", "none", "no", "false", "disabled":
2734 return ""
2735 case "minimum", "minimal", "min":
2736 return "minimal"
2737 case "maximum", "xhigh":
2738 return "xhigh"
2739 case "max":
2740 return "max"
2741 default:
2742 return strings.ToLower(strings.TrimSpace(level))
2743 }
2744}
2745
2746// contextUsage renders the "N%/ctxMax" fragment, returning the
2747// rendered string plus the colour to wrap it in.
2748func contextUsage(th Theme, used, max int) (string, int) {
2749 if max <= 0 {
2750 if used <= 0 {
2751 return "", th.Muted
2752 }
2753 return formatTokens(used), th.Muted
2754 }
2755 pct := float64(used) / float64(max) * 100
2756 text := fmt.Sprintf("%.1f%%/%s", pct, formatTokens(max))
2757 switch {
2758 case pct > 90:
2759 return text, th.Error
2760 case pct > 70:
2761 return text, th.Warning
2762 }
2763 return text, th.Muted
2764}
2765
2766// formatTokens footer formatter:
2767//
2768// < 1000 -> "42"
2769// < 10_000 -> "2.7k"
2770// < 1_000_000 -> "35k"
2771// < 10M -> "1.1M"
2772// else -> "12M"
2773func formatTokens(n int) string {
2774 switch {
2775 case n < 0:
2776 return "0"
2777 case n < 1000:
2778 return fmt.Sprintf("%d", n)
2779 case n < 10000:
2780 return fmt.Sprintf("%.1fk", float64(n)/1000)
2781 case n < 1_000_000:
2782 return fmt.Sprintf("%dk", (n+500)/1000)
2783 case n < 10_000_000:
2784 return fmt.Sprintf("%.1fM", float64(n)/1_000_000)
2785 default:
2786 return fmt.Sprintf("%dM", (n+500_000)/1_000_000)
2787 }
2788}
2789
2790// shortenHome replaces the user's $HOME prefix with "~" for readability.
2791func shortenHome(p string) string {
2792 if p == "" {
2793 return ""
2794 }
2795 home := osUserHome()
2796 if home == "" {
2797 return p
2798 }
2799 if p == home {
2800 return "~"
2801 }
2802 if strings.HasPrefix(p, home+"/") {
2803 return "~" + p[len(home):]
2804 }
2805 return p
2806}
2807
2808// osUserHome is a tiny wrapper around os.UserHomeDir so tests can mock it.
2809var osUserHome = func() string {
2810 if h, err := osUserHomeDir(); err == nil {
2811 return h
2812 }
2813 return ""
2814}