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