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