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 := v.renderLiveToolResult(bodyText, flatToolBodyRenderWidth(width), color, tc.LivePath)
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 := v.renderLiveToolResult(bodyText, toolBoxBodyRenderWidth(width), color, tc.LivePath)
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// renderLiveToolResult uses the transcript's text renderer so every rich
936// confirmation preview immediately gets the same colors, numbered gutters,
937// and syntax highlighting as its final tool result.
938func (v *View) renderLiveToolResult(text string, width, color int, sourcePath string) []string {
939 return v.renderToolText(text, width, color, sourcePath, 1)
940}
941
942// renderLiveToolBody renders the in-flight preview of a streaming
943// tool call. Supported tools:
944//
945// - write: shows the partial `content` field, syntax-highlighted
946// by the target path's language.
947// - edit: shows the partial `newText` of the edit currently being
948// streamed, prefixed with a "editing foo.ts (edit 2)" header so
949// the user can see which of a multi-edit batch is in progress.
950// - bash: shows the full command as soon as the JSON args are known,
951// before stdout/stderr has arrived, so long-running commands are legible.
952//
953// Anything else returns nil and only the tool-call header shows.
954func (v *View) renderLiveToolBody(tc ToolCallView, width int) []string {
955 switch tc.Name {
956 case "write", "Write":
957 partial, ok, _ := ExtractPartialStringField(tc.RawJSONBuf, "content")
958 if !ok || partial == "" {
959 return nil
960 }
961 return v.wrapLiveBody(v.renderRawFile(partial, tc.LivePath, 1), width)
962 case "edit", "Edit":
963 partial, ok, _, idx := ExtractLastNewText(tc.RawJSONBuf)
964 if !ok || partial == "" {
965 return nil
966 }
967 // Header line hints which edit is streaming and, when more
968 // than one has landed, how many the model is doing.
969 hint := fmt.Sprintf("edit %d (streaming)", idx)
970 body := []string{" " + v.Theme.FG256(v.Theme.Muted, hint), ""}
971 body = append(body, v.renderRawFile(partial, tc.LivePath, 1)...)
972 return v.wrapLiveBody(body, width)
973 case "bash", "Bash":
974 command, ok, _ := ExtractPartialStringField(tc.RawJSONBuf, "command")
975 if !ok || strings.TrimSpace(command) == "" {
976 return nil
977 }
978 return v.wrapLiveBody(v.renderLiveBashCommand(command, width), width)
979 }
980 return nil
981}
982
983func (v *View) renderLiveBashCommand(command string, width int) []string {
984 inner := toolBoxBodyRenderWidth(width)
985 if v.FlatTools || v.CompactMode {
986 inner = flatToolBodyRenderWidth(width)
987 }
988 prompt := v.Theme.FG256(v.Theme.Muted, "$ ")
989 var out []string
990 for i, line := range strings.Split(command, "\n") {
991 firstPrefix := " "
992 if i == 0 {
993 firstPrefix += prompt
994 } else {
995 firstPrefix += " "
996 }
997 contPrefix := " "
998 wrapWidth := inner - visibleWidth(firstPrefix)
999 if wrapWidth < 10 {
1000 wrapWidth = 10
1001 }
1002 for j, wrapped := range wrapANSILine(v.Theme.FG256(v.Theme.ToolOut, line), wrapWidth) {
1003 prefix := firstPrefix
1004 if j > 0 {
1005 prefix = contPrefix
1006 }
1007 out = append(out, prefix+wrapped)
1008 }
1009 }
1010 return out
1011}
1012
1013// wrapLiveBody returns the streaming body content as a list of
1014// box-side rows: each line wrapped in │ ... │ with right padding so
1015// the closing edge sits at column width-1. The caller (renderToolCall)
1016// supplies the surrounding top/bottom edges so the live overlay
1017// renders as a closed box matching the finalised transcript form.
1018func (v *View) wrapLiveBody(body []string, width int) []string {
1019 body = v.collapseToolBody(body, false)
1020 out := make([]string, 0, len(body))
1021 if v.FlatTools || v.CompactMode {
1022 for _, l := range body {
1023 _, stripped := parseImageFootprint(l)
1024 out = append(out, toolBodyLine(v.Theme, stripped, width, v.CompactMode))
1025 }
1026 return out
1027 }
1028 for _, l := range body {
1029 imgCells, stripped := parseImageFootprint(l)
1030 if hasImageEscapeLine(stripped) {
1031 out = append(out, toolBoxSideWithImage(v.Theme, stripped, imgCells, width))
1032 continue
1033 }
1034 out = append(out, toolBoxSide(v.Theme, stripped, width))
1035 }
1036 return out
1037}
1038
1039// toolResultBlock wraps text in thin horizontal rules (top + bottom),
1040// indenting the body with four spaces. The rules span the content column.
1041// toolBlockRule renders the muted horizontal separator drawn
1042// above and below a tool call block. Spans the full content
1043// width so it reads as a real section break in the chat
1044// regardless of terminal size.
1045func toolBlockRule(th Theme, width int) string {
1046 w := width
1047 if w < 8 {
1048 w = 8
1049 }
1050 return th.FG256(th.Muted, strings.Repeat("─", w))
1051}
1052
1053// toolBoxInnerPad is the number of blank cells kept between a box
1054// edge (┌, │, └) and the content inside it. One cell of breathing
1055// room makes the label read as part of the box rather than fused to
1056// the corner, and gives body lines a tiny gutter from the left side.
1057const toolBoxInnerPad = 1
1058
1059// toolBoxOuterMargin is the number of blank cells kept to the left of
1060// the opening corner and to the right of the closing corner. Aligns
1061// the box's frame with the column where user-bubble text begins, so
1062// the conversation reads as one column instead of having tool boxes
1063// running edge-to-edge while user/assistant rows sit indented.
1064const toolBoxOuterMargin = 2
1065
1066// toolBoxTop renders the labelled top edge of a tool block:
1067//
1068// ┌─ bash xcrun simctl list devices ─────────────────────────────┐
1069//
1070// The label is the tool name + short args (the same string previously
1071// shown on its own row beneath the rule). Padding fills the remainder
1072// of the line so the right corner sits at column width-1, matching the
1073// closing edge.
1074func toolBoxTop(th Theme, label string, width int) string {
1075 label = oneLineToolLabel(label)
1076 w := width - 2*toolBoxOuterMargin
1077 if w < 12 {
1078 w = 12
1079 }
1080 margin := strings.Repeat(" ", toolBoxOuterMargin)
1081 innerPad := strings.Repeat(" ", toolBoxInnerPad)
1082 // "┌─" + innerPad + " " + label + " " + innerPad = used; pad
1083 // with ─ to width-1, then "┐".
1084 prefix := "┌─" + innerPad + " "
1085 suffix := " " + innerPad
1086 used := visibleWidth(prefix) + visibleWidth(label) + visibleWidth(suffix)
1087 fill := w - used - 1 // -1 for the closing corner
1088 if fill < 0 {
1089 // Label overflows; truncate with an ellipsis so the right
1090 // corner still lands on the right edge. Rare on real
1091 // terminals (the chat column is usually wide enough).
1092 over := -fill
1093 runes := []rune(label)
1094 if over+3 < len(runes) {
1095 label = string(runes[:len(runes)-over-3]) + "..."
1096 } else {
1097 label = "..."
1098 }
1099 used = visibleWidth(prefix) + visibleWidth(label) + visibleWidth(suffix)
1100 fill = w - used - 1
1101 if fill < 0 {
1102 fill = 0
1103 }
1104 }
1105 fillStr := strings.Repeat("─", fill)
1106 name, rest := splitToolLabel(label)
1107 return margin + th.FG256(th.Muted, prefix) + th.FG256(th.FG, name) + th.FG256(th.Muted, rest+suffix+fillStr+"┐") + margin
1108}
1109
1110func oneLineToolLabel(label string) string {
1111 return strings.Join(strings.Fields(label), " ")
1112}
1113
1114func splitToolLabel(label string) (name, rest string) {
1115 label = strings.TrimLeft(label, " ")
1116 if label == "" {
1117 return "", ""
1118 }
1119 idx := strings.IndexAny(label, " \t")
1120 if idx < 0 {
1121 return label, ""
1122 }
1123 return label[:idx], label[idx:]
1124}
1125
1126// flatToolHeader renders the boxless header line for a tool call:
1127//
1128// ▌ bash xcrun simctl list devices
1129//
1130// It carries the same information as toolBoxTop (tool name + short
1131// args) but drops the frame: a single accent gutter glyph, the tool
1132// name in the foreground color, and the argument summary muted. The
1133// line is left-aligned at the same column the box's opening corner
1134// used (toolBoxOuterMargin) so flat and box renders share a column.
1135func toolHeaderLine(th Theme, label string, width int, compact bool) string {
1136 if compact {
1137 return compactToolHeader(th, label, width)
1138 }
1139 return flatToolHeader(th, label, width)
1140}
1141
1142func flatToolHeader(th Theme, label string, width int) string {
1143 label = oneLineToolLabel(label)
1144 name, rest := splitToolLabel(label)
1145 margin := strings.Repeat(" ", toolBoxOuterMargin)
1146 gutter := th.FG256(th.Assistant, "▌") + " "
1147 // Budget the visible text to the content width so a very long
1148 // argument summary doesn't run off the right edge; truncate with
1149 // an ellipsis like the box header does.
1150 avail := width - toolBoxOuterMargin - visibleWidth("▌ ")
1151 if avail < 12 {
1152 avail = 12
1153 }
1154 if visibleWidth(name+rest) > avail {
1155 over := visibleWidth(name+rest) - avail
1156 runes := []rune(rest)
1157 if over+3 < len(runes) {
1158 rest = string(runes[:len(runes)-over-3]) + "..."
1159 } else if visibleWidth(name) <= avail {
1160 rest = ""
1161 }
1162 }
1163 return margin + gutter + th.FG256(th.FG, name) + th.FG256(th.Muted, rest)
1164}
1165
1166func compactToolBlank(th Theme, width int) string {
1167 if width < 1 {
1168 width = 1
1169 }
1170 return sgrBGColor(th.UserBubbleBG) + strings.Repeat(" ", width) + reset
1171}
1172
1173func compactToolHeader(th Theme, label string, width int) string {
1174 label = oneLineToolLabel(label)
1175 name, rest := splitToolLabel(label)
1176 pad := " "
1177 avail := width - visibleWidth(pad)*2
1178 if avail < 12 {
1179 avail = 12
1180 }
1181 if visibleWidth(name+rest) > avail {
1182 over := visibleWidth(name+rest) - avail
1183 runes := []rune(rest)
1184 if over+3 < len(runes) {
1185 rest = string(runes[:len(runes)-over-3]) + "..."
1186 } else if visibleWidth(name) <= avail {
1187 rest = ""
1188 }
1189 }
1190 plain := pad + name + rest
1191 visible := visibleWidth(plain)
1192 fill := ""
1193 if visible < width {
1194 fill = strings.Repeat(" ", width-visible)
1195 }
1196 bg := sgrBGColor(th.UserBubbleBG)
1197 return bg + pad + sgrFG(th.FG) + name + bg + sgrFG(th.Muted) + rest + bg + fill + reset
1198}
1199
1200func toolBodyLine(th Theme, line string, width int, compact bool) string {
1201 line = flatToolBody(th, line)
1202 if compact {
1203 return compactToolBody(th, line, width)
1204 }
1205 return line
1206}
1207
1208// flatToolBody indents a single body line for boxless rendering. It
1209// trims the same leading padding box bodies do, then prepends a fixed
1210// gutter indent so output sits in a readable column under the header
1211// without any vertical frame. ANSI styling in the line is preserved.
1212func flatToolBody(th Theme, line string) string {
1213 _ = th
1214 line = trimLeadingSpaces(line, toolBoxBodyTrimLeft)
1215 return strings.Repeat(" ", toolBoxOuterMargin+2) + line
1216}
1217
1218func compactToolBody(th Theme, line string, width int) string {
1219 visible := visibleWidth(line)
1220 fill := ""
1221 if visible < width {
1222 fill = strings.Repeat(" ", width-visible)
1223 }
1224 bg := sgrBGColor(th.UserBubbleBG)
1225 return bg + strings.ReplaceAll(line, reset, reset+bg) + bg + fill + reset
1226}
1227
1228// toolBoxBottom renders the bottom edge of a tool block:
1229//
1230// └─────────────────────────────────────────────────────────────────────────────┘
1231//
1232// Spans the same width as toolBoxTop so the corners line up.
1233func toolBoxBottom(th Theme, width int) string {
1234 w := width - 2*toolBoxOuterMargin
1235 if w < 12 {
1236 w = 12
1237 }
1238 margin := strings.Repeat(" ", toolBoxOuterMargin)
1239 line := "└" + strings.Repeat("─", w-2) + "┘"
1240 return margin + th.FG256(th.Muted, line) + margin
1241}
1242
1243// hasImageEscapeLine reports whether s contains a Kitty (\x1b_G) or
1244// iTerm2 (\x1b]1337;File=) inline-image escape. Such rows draw into
1245// the terminal's graphics layer and shouldn't be wrapped with text
1246// box edges.
1247func hasImageEscapeLine(s string) bool {
1248 return strings.Contains(s, "\x1b]1337;File=") || strings.Contains(s, "\x1b_G")
1249}
1250
1251// imageFootprintSentinel marks rows that belong to an inline-image's
1252// reserved footprint — the escape row plus the blank rows below it
1253// plus the gap row before the metadata caption. Any consumer that
1254// wraps content in box edges (│ ... │) detects the sentinel, strips
1255// it, and emits the row — the image graphics rectangle paints over
1256// whatever was drawn there. Uses a non-printing C0 control byte so
1257// it can never appear in normal text or in an ANSI escape sequence
1258// body.
1259//
1260// The escape row carries an extra width hint between two sentinels:
1261// "\x1e<cells>\x1e<spaces+escape>". Wrappers parse the cells count
1262// to know how wide the image is in terminal cells and how many cells
1263// of trailing padding are needed before the closing box edge.
1264const imageFootprintSentinel = "\x1e"
1265
1266// parseImageFootprint splits a footprint-tagged row into (cellsWide,
1267// rest). cellsWide is 0 when the row carries no width hint (the
1268// reservation blanks and gap row don't, only the escape row does).
1269func parseImageFootprint(s string) (int, string) {
1270 if !strings.HasPrefix(s, imageFootprintSentinel) {
1271 return 0, s
1272 }
1273 rest := s[len(imageFootprintSentinel):]
1274 end := strings.Index(rest, imageFootprintSentinel)
1275 if end < 0 {
1276 return 0, rest
1277 }
1278 w, err := strconv.Atoi(rest[:end])
1279 if err != nil {
1280 return 0, rest
1281 }
1282 return w, rest[end+len(imageFootprintSentinel):]
1283}
1284
1285// toolBoxBodyTrimLeft is the number of leading literal spaces stripped
1286// from each body line as it enters toolBoxSide. Body renderers
1287// (renderToolText, renderRawFile, the diff/bash helpers, ...) all
1288// emit a 4-cell indent so the content aligns with the assistant body
1289// column when there's no box around it. Inside a box the box edge +
1290// inner pad already supply most of that gutter, so we drop a couple
1291// of cells from the body's own indent to keep the content from
1292// drifting too far right.
1293const toolBoxBodyTrimLeft = 2
1294
1295// toolBoxBodyRenderWidth is the width body renderers should target before
1296// their rows are wrapped by toolBoxSide. Most body renderers emit a four-cell
1297// indent; toolBoxSide trims toolBoxBodyTrimLeft cells from that indent and
1298// then adds the box edge/padding. Passing the full terminal width lets long
1299// bash/heredoc lines overrun the inner box and makes terminals soft-wrap,
1300// visually breaking the right edge. This returns the maximum renderer width
1301// whose post-trim visible width fits inside the box.
1302func toolBoxBodyRenderWidth(width int) int {
1303 w := width - 2*toolBoxOuterMargin
1304 if w < 12 {
1305 w = 12
1306 }
1307 inner := w - 2 - 2*toolBoxInnerPad
1308 if inner < 1 {
1309 inner = 1
1310 }
1311 return inner + toolBoxBodyTrimLeft
1312}
1313
1314// flatToolBodyRenderWidth is the width body renderers should target in
1315// flat mode. There's no box frame, just the flatToolBody indent
1316// (toolBoxOuterMargin+2 cells), so the renderable width is the
1317// terminal width minus that indent. Renderers emit a 4-cell indent of
1318// their own which flatToolBody trims toolBoxBodyTrimLeft cells from,
1319// so add that back like toolBoxBodyRenderWidth does.
1320func flatToolBodyRenderWidth(width int) int {
1321 inner := width - (toolBoxOuterMargin + 2)
1322 if inner < 1 {
1323 inner = 1
1324 }
1325 return inner + toolBoxBodyTrimLeft
1326}
1327
1328// toolBoxSide wraps a single body line with vertical box edges:
1329//
1330// │ foo bar baz │
1331//
1332// The middle preserves the line verbatim (including any ANSI escapes)
1333// after stripping toolBoxBodyTrimLeft leading literal spaces. One cell
1334// of inner padding sits on each side so the content breathes from the
1335// edges; the right padding fills to column width-1.
1336func toolBoxSide(th Theme, line string, width int) string {
1337 w := width - 2*toolBoxOuterMargin
1338 if w < 12 {
1339 w = 12
1340 }
1341 margin := strings.Repeat(" ", toolBoxOuterMargin)
1342 left := th.FG256(th.Muted, "│") + strings.Repeat(" ", toolBoxInnerPad)
1343 right := strings.Repeat(" ", toolBoxInnerPad) + th.FG256(th.Muted, "│")
1344 inner := w - 2 - 2*toolBoxInnerPad // available between the two pads
1345 line = trimLeadingSpaces(line, toolBoxBodyTrimLeft)
1346
1347 cur := visibleWidth(line)
1348 if cur > inner {
1349 // Last-resort truncation must retain syntax foreground escapes.
1350 // Stripping ANSI here made long read results switch from their
1351 // configured syntax color to the terminal's default foreground
1352 // whenever the window became narrow enough to clip a line.
1353 line = truncateToWidth(line, inner)
1354 cur = visibleWidth(line)
1355 }
1356 pad := inner - cur
1357 if pad < 0 {
1358 pad = 0
1359 }
1360 return margin + left + line + strings.Repeat(" ", pad) + right + margin
1361}
1362
1363// toolBoxSideWithImage wraps a row that carries an inline-image
1364// escape sequence. The image protocols are configured to not move
1365// the cursor after rendering (iTerm: doNotMoveCursor=1, kitty/
1366// ghostty: C=1), so the only visible cell advance on the row is
1367// from the leading indent spaces before the escape. We pad from
1368// there to the right edge column and draw the closing │ there.
1369// imgCells is unused (kept in the signature for compatibility with
1370// the parseImageFootprint width hint).
1371func toolBoxSideWithImage(th Theme, line string, imgCells, width int) string {
1372 _ = imgCells
1373 w := width - 2*toolBoxOuterMargin
1374 if w < 12 {
1375 w = 12
1376 }
1377 margin := strings.Repeat(" ", toolBoxOuterMargin)
1378 left := th.FG256(th.Muted, "│") + strings.Repeat(" ", toolBoxInnerPad)
1379 right := strings.Repeat(" ", toolBoxInnerPad) + th.FG256(th.Muted, "│")
1380 inner := w - 2 - 2*toolBoxInnerPad
1381
1382 line = trimLeadingSpaces(line, toolBoxBodyTrimLeft)
1383
1384 // Count leading spaces (visible cells consumed before the escape).
1385 leading := 0
1386 for leading < len(line) && line[leading] == ' ' {
1387 leading++
1388 }
1389
1390 pad := inner - leading
1391 if pad < 0 {
1392 pad = 0
1393 }
1394 return margin + left + line + strings.Repeat(" ", pad) + right + margin
1395}
1396
1397// trimLeadingSpaces removes up to n literal space characters from the
1398// start of s without touching anything else. ANSI CSI escapes that
1399// appear before the spaces are skipped over (so a coloured indent
1400// like "\x1b[2m text" still loses its first n cells of indent).
1401// Stops as soon as it hits a non-space character.
1402func trimLeadingSpaces(s string, n int) string {
1403 if n <= 0 || s == "" {
1404 return s
1405 }
1406 var b strings.Builder
1407 b.Grow(len(s))
1408 trimmed := 0
1409 i := 0
1410 for i < len(s) {
1411 // Pass through any ANSI escape sequence verbatim.
1412 if s[i] == 0x1b && i+1 < len(s) && s[i+1] == '[' {
1413 end := i + 2
1414 for end < len(s) {
1415 c := s[end]
1416 end++
1417 if c >= 0x40 && c <= 0x7e {
1418 break
1419 }
1420 }
1421 b.WriteString(s[i:end])
1422 i = end
1423 continue
1424 }
1425 if trimmed < n && s[i] == ' ' {
1426 trimmed++
1427 i++
1428 continue
1429 }
1430 b.WriteString(s[i:])
1431 return b.String()
1432 }
1433 return b.String()
1434}
1435
1436// renderToolResultContent renders the body of a tool result block.
1437// Text blocks get the usual rules-wrapped treatment; text that looks
1438// like a unified diff gets +/- coloring. Image blocks are rendered
1439// inline when the terminal supports a protocol, else as a text
1440// placeholder with dimensions.
1441func (v *View) renderToolResultContent(blocks []provider.Content, width, color int, sourcePath string, startLine int) []string {
1442 var body []string
1443 hasImage := false
1444 for _, b := range blocks {
1445 switch bb := b.(type) {
1446 case provider.TextBlock:
1447 bodyWidth := toolBoxBodyRenderWidth(width)
1448 if v.FlatTools || v.CompactMode {
1449 bodyWidth = flatToolBodyRenderWidth(width)
1450 }
1451 body = append(body, v.renderToolText(bb.Text, bodyWidth, color, sourcePath, startLine)...)
1452 case provider.ImageBlock:
1453 hasImage = true
1454 body = append(body, v.renderImageBlock(bb, width)...)
1455 }
1456 }
1457 return v.collapseToolBody(body, hasImage)
1458}
1459
1460// collapseToolBody trims lines to the configured preview size when the
1461// view is not in ExpandAll mode, appending a muted "... ctrl+o to
1462// expand" footer. Image blocks never collapse — they're short in text
1463// rows but represent real content the user wants to see.
1464func (v *View) collapseToolBody(lines []string, hasImage bool) []string {
1465 if v.ExpandAll || hasImage {
1466 return lines
1467 }
1468 if len(lines) <= ToolCollapseLines {
1469 return lines
1470 }
1471 kept := lines[:ToolCollapsePreview]
1472 hidden := len(lines) - ToolCollapsePreview
1473 total := len(lines)
1474 footer := fmt.Sprintf(" ... (%d more lines, %d total, ctrl+o to expand)", hidden, total)
1475 footer = v.Theme.FG256(v.Theme.Muted, footer)
1476 out := append([]string(nil), kept...)
1477 out = append(out, "")
1478 return append(out, footer)
1479}
1480
1481// renderToolText renders a text block inside a tool result. If the
1482// text contains a unified-diff section (lines starting with "--- " /
1483// "+++ " / "+" / "-"/" "), those rows are styled with add/remove
1484// colors matching git diff conventions.
1485func (v *View) renderToolText(text string, width, defaultColor int, sourcePath string, startLine int) []string {
1486 // Legacy path: transcripts saved before we dropped line numbers
1487 // from the read tool still carry " 1\t..." prefixes. Detect and
1488 // strip them, then fall through to the highlighter.
1489 if looksLikeNumberedFile(text) {
1490 return v.renderNumberedFile(text, sourcePath)
1491 }
1492 // If the result embeds a unified diff (the edit tool's output
1493 // starts with a short "applied N edit(s)" line and then a
1494 // standard --- / +++ / +/- patch), render the patch with
1495 // add/remove coloring. This takes priority over the file-like
1496 // detector below because a diff technically has many lines of
1497 // "file content" but what the user cares about is what changed,
1498 // not a dump of the post-edit file.
1499 if looksLikeUnifiedDiff(text) {
1500 return v.renderUnifiedDiff(text, width, sourcePath)
1501 }
1502
1503 // Current path: text came from `read` as raw file bytes. When a
1504 // source path is known (the call had a `path` arg), render with
1505 // a synthetic line-number gutter starting at startLine so the
1506 // on-screen view still looks like cat -n. Doesn't apply to non-
1507 // file tool outputs (bash stdout, display notes, etc.).
1508 if sourcePath != "" && looksLikeFileContent(text) {
1509 return v.renderRawFile(text, sourcePath, startLine)
1510 }
1511
1512 // No truncation — the full tool output is rendered into chat and
1513 // becomes part of the scrollback you can page back through.
1514 lines := strings.Split(text, "\n")
1515
1516 // Bash-result styling: when the first row looks like a shell
1517 // prompt line ("$ ...") emitted by the bash tool, style the
1518 // prompt line in accent and the trailing "[exit N] Took X.Ys"
1519 // line in muted type so the command + timing read at a glance.
1520 // Everything between is left on the default tool-output color.
1521 if len(lines) > 0 && strings.HasPrefix(lines[0], "$ ") {
1522 return v.renderBashResult(lines, width, defaultColor)
1523 }
1524
1525 inDiff := false
1526 oldLine, newLine := 1, 1
1527 var out []string
1528 for _, l := range lines {
1529 // Detect diff header: "--- name" followed somewhere by "+++ name".
1530 if strings.HasPrefix(l, "--- ") || strings.HasPrefix(l, "+++ ") {
1531 inDiff = true
1532 out = append(out, " "+v.Theme.FG256(v.Theme.Muted, l))
1533 continue
1534 }
1535 // Hunk header "@@ -a,b +c,d @@" resets the counters so patches
1536 // that skip around in the file still get correct numbering.
1537 if inDiff && strings.HasPrefix(l, "@@") {
1538 if o, n, ok := parseHunkHeader(l); ok {
1539 oldLine, newLine = o, n
1540 }
1541 out = append(out, " "+v.Theme.FG256(v.Theme.Muted, l))
1542 continue
1543 }
1544 if inDiff && strings.TrimSpace(l) == "..." {
1545 out = append(out, "")
1546 out = append(out, " "+v.Theme.FG256(v.Theme.Muted, "..."))
1547 continue
1548 }
1549 if inDiff && len(l) > 0 {
1550 switch l[0] {
1551 case '+':
1552 out = append(out, v.renderDiffRow(l, width, v.Theme.Tool, newLine, '+', sourcePath)...)
1553 newLine++
1554 continue
1555 case '-':
1556 out = append(out, v.renderDiffRow(l, width, v.Theme.Error, oldLine, '-', sourcePath)...)
1557 oldLine++
1558 continue
1559 case ' ':
1560 out = append(out, v.renderDiffRow(l, width, v.Theme.Muted, newLine, ' ', sourcePath)...)
1561 oldLine++
1562 newLine++
1563 continue
1564 }
1565 }
1566 // Regular line.
1567 for _, w := range wrapLine(l, width-4, " ") {
1568 out = append(out, " "+v.Theme.FG256(defaultColor, w))
1569 }
1570 }
1571 return out
1572}
1573
1574// parseHunkHeader extracts the starting old/new line from a unified
1575// diff hunk header ("@@ -12,5 +12,7 @@ ..."). Returns ok=false if the
1576// header is malformed or missing numbers.
1577func parseHunkHeader(l string) (oldStart, newStart int, ok bool) {
1578 // Skip "@@ "
1579 rest := strings.TrimPrefix(l, "@@")
1580 rest = strings.TrimSpace(rest)
1581 if !strings.HasPrefix(rest, "-") {
1582 return 0, 0, false
1583 }
1584 rest = rest[1:]
1585 space := strings.IndexByte(rest, ' ')
1586 if space < 0 {
1587 return 0, 0, false
1588 }
1589 oldPart := rest[:space]
1590 rest = strings.TrimSpace(rest[space+1:])
1591 if !strings.HasPrefix(rest, "+") {
1592 return 0, 0, false
1593 }
1594 rest = rest[1:]
1595 if sp := strings.IndexAny(rest, " \t"); sp >= 0 {
1596 rest = rest[:sp]
1597 }
1598 parseStart := func(s string) (int, bool) {
1599 if c := strings.IndexByte(s, ','); c >= 0 {
1600 s = s[:c]
1601 }
1602 n, err := strconv.Atoi(s)
1603 if err != nil || n < 1 {
1604 return 0, false
1605 }
1606 return n, true
1607 }
1608 o, ok1 := parseStart(oldPart)
1609 n, ok2 := parseStart(rest)
1610 if !ok1 || !ok2 {
1611 return 0, 0, false
1612 }
1613 return o, n, true
1614}
1615
1616// renderDiffRow renders one unified-diff source line as one or more visual
1617// rows. The first row carries the read-style line-number gutter; continuation
1618// rows use a blank gutter so wrapped content cannot be mistaken for another
1619// source line. Code is syntax-highlighted if sourcePath hints at a known
1620// language and otherwise uses the diff color.
1621func (v *View) renderDiffRow(line string, width, color int, lineNo int, mark byte, sourcePath string) []string {
1622 if len(line) == 0 {
1623 return []string{""}
1624 }
1625 code := expandTabs(line[1:]) // strip the leading marker; expand tabs
1626
1627 // Gutter shape: sign + number share a color so they read as one
1628 // visual token ("+123") instead of a neutral line number next to
1629 // a stray marker. Unchanged context lines get a muted gutter and
1630 // a leading space so column alignment stays consistent with +/-
1631 // rows.
1632 var gutterText string
1633 switch mark {
1634 case '+':
1635 gutterText = fmt.Sprintf("+%3d ", lineNo)
1636 case '-':
1637 gutterText = fmt.Sprintf("-%3d ", lineNo)
1638 default:
1639 gutterText = fmt.Sprintf(" %3d ", lineNo)
1640 }
1641 gutterColor := color
1642 if mark == ' ' {
1643 gutterColor = v.Theme.Muted
1644 }
1645
1646 maxCode := width - visibleWidth(" "+gutterText)
1647 if maxCode < 1 {
1648 maxCode = 1
1649 }
1650 chunks := wrapCodeLine(code, maxCode)
1651 lang := LanguageFromPath(sourcePath)
1652 out := make([]string, 0, len(chunks))
1653 for i, chunk := range chunks {
1654 rowGutter := gutterText
1655 if i > 0 {
1656 rowGutter = strings.Repeat(" ", visibleWidth(gutterText))
1657 }
1658 codeRendered := ""
1659 if lang != "" {
1660 if h := v.Theme.HighlightCode(chunk, lang); len(h) == 1 {
1661 codeRendered = h[0]
1662 }
1663 }
1664 if codeRendered == "" {
1665 codeColor := color
1666 if mark == ' ' {
1667 codeColor = v.Theme.Muted
1668 }
1669 codeRendered = v.Theme.FG256(codeColor, chunk)
1670 }
1671 out = append(out, " "+v.Theme.FG256(gutterColor, rowGutter)+codeRendered)
1672 }
1673 return out
1674}
1675
1676// wrapCodeLine splits code to a terminal cell width without dropping any
1677// characters. It prefers breaking after whitespace, then falls back to a hard
1678// rune boundary for long tokens. Keeping the whitespace on the preceding row
1679// means joining the returned chunks reconstructs the expanded source exactly.
1680func wrapCodeLine(line string, width int) []string {
1681 if width < 1 || visibleWidth(line) <= width {
1682 return []string{line}
1683 }
1684 runes := []rune(line)
1685 var out []string
1686 for start := 0; start < len(runes); {
1687 cells := 0
1688 end := start
1689 lastBreak := -1
1690 for end < len(runes) {
1691 runeWidth := runewidth.RuneWidth(runes[end])
1692 if cells+runeWidth > width && end > start {
1693 break
1694 }
1695 cells += runeWidth
1696 end++
1697 if runes[end-1] == ' ' || runes[end-1] == '\t' {
1698 lastBreak = end
1699 }
1700 if cells >= width {
1701 break
1702 }
1703 }
1704 if end == start { // A rune wider than the requested width.
1705 end++
1706 }
1707 if end < len(runes) && lastBreak > start {
1708 end = lastBreak
1709 }
1710 out = append(out, string(runes[start:end]))
1711 start = end
1712 }
1713 return out
1714}
1715
1716// renderImageBlock returns the lines for one image, inline if possible.
1717//
1718// Inline image escapes paint into multiple terminal rows but the zot
1719// renderer treats each slice entry as a single row. To prevent chat
1720// content from being drawn on top of the image, we pad with blank rows
1721// so the image's real footprint is reflected in the frame height.
1722func (v *View) renderImageBlock(b provider.ImageBlock, width int) []string {
1723 w, h := ImageDimensions(b.Data)
1724 kb := len(b.Data) / 1024
1725 // Four-space indent matches every other tool-output row
1726 // (renderRawFile, renderBashResult, diff rows, "... N more
1727 // lines" footers). Keeps the image's metadata line vertically
1728 // aligned with the file content above / below it.
1729 info := fmt.Sprintf(" image - %s - %dx%d - %d KB", b.MimeType, w, h, kb)
1730
1731 if v.ImageProto != ImageProtocolNone {
1732 // Clamp rendered width so the image never overflows the chat
1733 // column. Subtract a 4-cell indent for the tool result block,
1734 // cap at 60 cells, floor at 10.
1735 cells := width - 4
1736 if cells > 60 {
1737 cells = 60
1738 }
1739 if cells < 10 {
1740 cells = 10
1741 }
1742 const maxRows = 20
1743 if seq := RenderInlineImageScaled(v.ImageProto, b.Data, b.MimeType, cells, maxRows); seq != "" {
1744 rows, actualCells := InlineImageFootprint(b.Data, cells, maxRows)
1745 if rows < 1 {
1746 rows = 1
1747 }
1748 if actualCells < 1 {
1749 actualCells = cells
1750 }
1751 // Reserve the image footprint first, then place the escape
1752 // in the top-left of that blank rectangle. Keeping the
1753 // metadata above the image made some terminals blend text
1754 // and graphics layers during full-screen repaints; metadata
1755 // below the reserved rectangle is more stable and easier to
1756 // read. One extra blank row before the metadata gives the
1757 // caption breathing room from the image's last pixel row.
1758 //
1759 // Every footprint row (escape, reservations, gap) is tagged
1760 // with imageFootprintSentinel so callers wrapping content in
1761 // box edges can recognise these rows and emit them bare —
1762 // the image's graphics rectangle paints over them and any
1763 // │ character drawn alongside would visibly bleed through.
1764 // 4 leading cells push the escape past the box's left
1765 // edge plus a small interior gutter so the image rectangle
1766 // sits visibly inside the frame instead of kissing the │.
1767 // The escape row carries a width hint after the sentinel
1768 // ("\x1e<cells>\x1e...") so toolBoxSide knows how many
1769 // cells the image occupies and can pad to the right edge.
1770 widthHint := fmt.Sprintf("%s%d%s", imageFootprintSentinel, actualCells, imageFootprintSentinel)
1771 out := make([]string, 0, rows+3)
1772 out = append(out, widthHint+" "+seq)
1773 for i := 1; i < rows; i++ {
1774 out = append(out, imageFootprintSentinel)
1775 }
1776 out = append(out, imageFootprintSentinel)
1777 out = append(out, v.Theme.FG256(v.Theme.Muted, info))
1778 return out
1779 }
1780 }
1781 return []string{v.Theme.FG256(v.Theme.Muted, info)}
1782}
1783
1784// looksLikeNumberedFile returns true when text matches the `read`
1785// tool's " N\tcontent" format for most of its lines.
1786func looksLikeNumberedFile(text string) bool {
1787 lines := strings.Split(text, "\n")
1788 if len(lines) == 0 {
1789 return false
1790 }
1791 hits := 0
1792 scanned := 0
1793 for _, l := range lines {
1794 if l == "" {
1795 continue
1796 }
1797 scanned++
1798 if scanned > 20 {
1799 break
1800 }
1801 if numberedLineRE.MatchString(l) {
1802 hits++
1803 }
1804 }
1805 if scanned == 0 {
1806 return false
1807 }
1808 return hits*2 >= scanned // majority of non-empty lines match
1809}
1810
1811var numberedLineRE = regexp.MustCompile(`^\s*\d+\t`)
1812
1813// renderNumberedFile strips line numbers, highlights the code, and
1814// re-attaches the line numbers in muted color.
1815func (v *View) renderNumberedFile(text, sourcePath string) []string {
1816 lines := strings.Split(text, "\n")
1817 gutters := make([]string, 0, len(lines))
1818 codes := make([]string, 0, len(lines))
1819 for _, l := range lines {
1820 idx := strings.IndexByte(l, '\t')
1821 if idx < 0 || !numberedLineRE.MatchString(l) {
1822 // Non-code footer (e.g. "[truncated at 2000 lines]").
1823 gutters = append(gutters, "")
1824 codes = append(codes, l)
1825 continue
1826 }
1827 gutter := l[:idx] + " " // replace tab with single space
1828 code := expandTabs(l[idx+1:])
1829 gutters = append(gutters, gutter)
1830 codes = append(codes, code)
1831 }
1832 lang := LanguageFromPath(sourcePath)
1833 var highlighted []string
1834 if lang != "" {
1835 highlighted = v.Theme.HighlightCode(strings.Join(codes, "\n"), lang)
1836 // Chroma sometimes collapses the trailing empty line. Pad to
1837 // align with the gutter slice so per-line zipping works.
1838 for len(highlighted) < len(codes) {
1839 highlighted = append(highlighted, "")
1840 }
1841 if len(highlighted) > len(codes) {
1842 highlighted = highlighted[:len(codes)]
1843 }
1844 } else {
1845 // No lexer for this file type — render in the ToolOut color so
1846 // code is visually distinct from the muted gutter.
1847 highlighted = make([]string, len(codes))
1848 for i, c := range codes {
1849 highlighted[i] = v.Theme.FG256(v.Theme.ToolOut, c)
1850 }
1851 }
1852 out := make([]string, 0, len(codes))
1853 for i, code := range highlighted {
1854 g := gutters[i]
1855 if g == "" {
1856 out = append(out, " "+v.Theme.FG256(v.Theme.Muted, code))
1857 continue
1858 }
1859 out = append(out, " "+v.Theme.FG256(v.Theme.Muted, g)+code)
1860 }
1861 return out
1862}
1863
1864// looksLikeFileContent is a cheap guard to distinguish a read-tool
1865// result from bash stdout or a status message. File content usually
1866// contains characters that status messages don't (code punctuation,
1867// longer lines, multiple lines) and rarely starts with the " >"-
1868// or "error:"-style prefixes tools emit. False positives are OK,
1869// the worst case is a line-number gutter on something that isn't
1870// really code.
1871// renderBashResult styles a bash tool result: the "$ command" first
1872// line in the accent color, the trailing "[exit N] Took X.Ys" line
1873// in muted type, everything else on the default tool-output color.
1874// Called from renderToolText when the first line starts with "$ ".
1875func (v *View) renderBashResult(lines []string, width, defaultColor int) []string {
1876 lines = normalizeBashOutputLines(lines)
1877 // Identify the footer line (exit + timing). The bash tool writes
1878 // it as the last non-empty line of the result.
1879 footerIdx := -1
1880 for i := len(lines) - 1; i >= 0; i-- {
1881 trimmed := strings.TrimSpace(lines[i])
1882 if trimmed == "" {
1883 continue
1884 }
1885 if strings.HasPrefix(trimmed, "[exit ") {
1886 footerIdx = i
1887 }
1888 break
1889 }
1890
1891 var out []string
1892 for i, l := range lines {
1893 switch {
1894 case i == 0 && strings.HasPrefix(l, "$ "):
1895 // Style the $ and the command text in accent. No
1896 // further processing / wrapping so the shell-style
1897 // prompt reads at a glance.
1898 for _, w := range wrapLine(l, width-4, " ") {
1899 out = append(out, " "+v.Theme.FG256(v.Theme.Accent, w))
1900 }
1901 case i == footerIdx:
1902 for _, w := range wrapLine(l, width-4, " ") {
1903 out = append(out, " "+v.Theme.FG256(v.Theme.Muted, w))
1904 }
1905 default:
1906 for _, w := range wrapLine(l, width-4, " ") {
1907 out = append(out, " "+v.Theme.FG256(defaultColor, w))
1908 }
1909 }
1910 }
1911 return out
1912}
1913
1914// normalizeBashOutputLines turns arbitrary terminal output into plain,
1915// box-safe rows before wrapping. Unlike read/write/edit output, bash
1916// stdout/stderr may contain tabs, carriage returns, ANSI/OSC escapes,
1917// and other C0 controls from subprocesses. If those reach the bordered
1918// tool box, the width calculator can undercount what the terminal will
1919// draw and the right edge appears broken. Keep printable text, expand
1920// tabs to spaces, split carriage-return progress rows, and drop escape
1921// / control sequences.
1922func normalizeBashOutputLines(lines []string) []string {
1923 var out []string
1924 for _, line := range lines {
1925 for _, part := range strings.Split(strings.ReplaceAll(line, "\r", "\n"), "\n") {
1926 out = append(out, normalizeBashOutputLine(part))
1927 }
1928 }
1929 if len(out) == 0 {
1930 return []string{""}
1931 }
1932 return out
1933}
1934
1935func normalizeBashOutputLine(s string) string {
1936 var b strings.Builder
1937 col := 0
1938 for i := 0; i < len(s); {
1939 c := s[i]
1940 if c == 0x1b { // ESC: strip CSI/OSC/DCS and simple escapes.
1941 i = skipEscapeSequence(s, i)
1942 continue
1943 }
1944 r, size := utf8.DecodeRuneInString(s[i:])
1945 if r == utf8.RuneError && size == 1 {
1946 i++
1947 continue
1948 }
1949 switch r {
1950 case '\t':
1951 spaces := 8 - (col % 8)
1952 if spaces == 0 {
1953 spaces = 8
1954 }
1955 b.WriteString(strings.Repeat(" ", spaces))
1956 col += spaces
1957 case '\b':
1958 // Backspace-overstrike output is common in spinners/progress bars.
1959 // Dropping it is safer than moving the TUI cursor backwards.
1960 case '\n', '\r':
1961 // Already split by normalizeBashOutputLines.
1962 default:
1963 if r < 0x20 || r == 0x7f {
1964 // Drop non-printing controls.
1965 break
1966 }
1967 b.WriteRune(r)
1968 col += runewidth.RuneWidth(r)
1969 }
1970 i += size
1971 }
1972 return b.String()
1973}
1974
1975func skipEscapeSequence(s string, i int) int {
1976 if i >= len(s) || s[i] != 0x1b {
1977 return i + 1
1978 }
1979 if i+1 >= len(s) {
1980 return len(s)
1981 }
1982 switch s[i+1] {
1983 case '[': // CSI: ESC [ ... final byte 0x40-0x7e
1984 j := i + 2
1985 for j < len(s) {
1986 c := s[j]
1987 j++
1988 if c >= 0x40 && c <= 0x7e {
1989 break
1990 }
1991 }
1992 return j
1993 case ']': // OSC: ESC ] ... BEL or ST
1994 return skipStringEscape(s, i+2)
1995 case 'P', '_', '^', 'X': // DCS/APC/PM/SOS: ESC P ... ST, etc.
1996 return skipStringEscape(s, i+2)
1997 default:
1998 // Two-byte escape (cursor save/restore, charset select, etc.).
1999 return i + 2
2000 }
2001}
2002
2003func skipStringEscape(s string, i int) int {
2004 for i < len(s) {
2005 if s[i] == 0x07 { // BEL
2006 return i + 1
2007 }
2008 if s[i] == 0x1b && i+1 < len(s) && s[i+1] == '\\' { // ST
2009 return i + 2
2010 }
2011 i++
2012 }
2013 return len(s)
2014}
2015
2016// looksLikeUnifiedDiff reports whether text is a context diff as
2017// emitted by the edit tool: rows start with '+', '-', ' ', or
2018// literal "..." (context-break marker). The presence of at least
2019// one '+' or '-' row distinguishes a real diff from an ordinary
2020// file whose lines happen to begin with a space.
2021func looksLikeUnifiedDiff(text string) bool {
2022 lines := strings.Split(text, "\n")
2023 if len(lines) < 2 {
2024 return false
2025 }
2026 sawChange := false
2027 for _, l := range lines {
2028 if l == "" {
2029 continue
2030 }
2031 if l == "..." {
2032 continue
2033 }
2034 switch l[0] {
2035 case '+', '-':
2036 sawChange = true
2037 case ' ':
2038 // context, ok
2039 default:
2040 return false
2041 }
2042 }
2043 return sawChange
2044}
2045
2046// renderUnifiedDiff renders the edit tool's context diff. Each
2047// kept row shows a line-number gutter plus a marker column: '+'
2048// for additions (colored like add), '-' for deletions (colored
2049// like remove), and unmarked context in muted type. A literal
2050// "..." line between hunks renders as an ellipsis in muted type,
2051// indicating skipped unchanged rows. The old and new line
2052// counters advance so each row carries its actual position in
2053// the pre- or post-edit file. Heuristic: when we hit a "...", we
2054// can't know where the next hunk starts, so we don't reset the
2055// counters — they stay approximate in the rare multi-hunk case.
2056func (v *View) renderUnifiedDiff(text string, width int, sourcePath string) []string {
2057 lines := strings.Split(text, "\n")
2058 if n := len(lines); n > 0 && lines[n-1] == "" {
2059 lines = lines[:n-1]
2060 }
2061 oldLine, newLine := 1, 1
2062 var out []string
2063 for _, l := range lines {
2064 if l == "" {
2065 out = append(out, "")
2066 continue
2067 }
2068 if l == "..." {
2069 out = append(out, " "+v.Theme.FG256(v.Theme.Muted, "..."))
2070 continue
2071 }
2072 switch l[0] {
2073 case '+':
2074 out = append(out, v.renderDiffRow(l, width, v.Theme.Tool, newLine, '+', sourcePath)...)
2075 newLine++
2076 case '-':
2077 out = append(out, v.renderDiffRow(l, width, v.Theme.Error, oldLine, '-', sourcePath)...)
2078 oldLine++
2079 case ' ':
2080 out = append(out, v.renderDiffRow(l, width, v.Theme.Muted, newLine, ' ', sourcePath)...)
2081 oldLine++
2082 newLine++
2083 default:
2084 for _, w := range wrapLine(l, width-4, " ") {
2085 out = append(out, " "+v.Theme.FG256(v.Theme.Muted, w))
2086 }
2087 }
2088 }
2089 return out
2090}
2091
2092func looksLikeFileContent(text string) bool {
2093 if strings.TrimSpace(text) == "" {
2094 return false
2095 }
2096 lines := strings.Split(text, "\n")
2097 return len(lines) >= 2
2098}
2099
2100// renderRawFile renders file content received without embedded line
2101// numbers (the current read-tool output). Draws a muted gutter like
2102// "%6d \t" starting at startLine, highlights the code using the
2103// source path's language, and returns the formatted lines.
2104func (v *View) renderRawFile(text, sourcePath string, startLine int) []string {
2105 lines := strings.Split(text, "\n")
2106 // Drop the trailing empty line that Split produces when text ends
2107 // in "\n" so the gutter doesn't show a phantom last number.
2108 if n := len(lines); n > 0 && lines[n-1] == "" {
2109 lines = lines[:n-1]
2110 }
2111 // Split code from trailing footer lines ("... [truncated ...]")
2112 // so we don't number the footer. A single blank separator line
2113 // immediately before the footer is also pulled out so the
2114 // gutter doesn't render a phantom number for it.
2115 codeEnd := len(lines)
2116 for i := len(lines) - 1; i >= 0; i-- {
2117 if strings.HasPrefix(lines[i], "...") {
2118 codeEnd = i
2119 continue
2120 }
2121 break
2122 }
2123 if codeEnd > 0 && codeEnd < len(lines) && lines[codeEnd-1] == "" {
2124 codeEnd--
2125 }
2126 code := lines[:codeEnd]
2127 footer := lines[codeEnd:]
2128
2129 // Expand tabs to 4 spaces so Go / Makefile code renders
2130 // at a consistent width.
2131 for i, c := range code {
2132 code[i] = expandTabs(c)
2133 }
2134
2135 lang := LanguageFromPath(sourcePath)
2136 var highlighted []string
2137 if lang != "" {
2138 highlighted = v.Theme.HighlightCode(strings.Join(code, "\n"), lang)
2139 for len(highlighted) < len(code) {
2140 highlighted = append(highlighted, "")
2141 }
2142 if len(highlighted) > len(code) {
2143 highlighted = highlighted[:len(code)]
2144 }
2145 } else {
2146 highlighted = make([]string, len(code))
2147 for i, c := range code {
2148 highlighted[i] = v.Theme.FG256(v.Theme.ToolOut, c)
2149 }
2150 }
2151
2152 out := make([]string, 0, len(lines))
2153 for i, c := range highlighted {
2154 gutter := fmt.Sprintf("%4d ", startLine+i)
2155 out = append(out, " "+v.Theme.FG256(v.Theme.Muted, gutter)+c)
2156 }
2157 for _, f := range footer {
2158 out = append(out, " "+v.Theme.FG256(v.Theme.Muted, f))
2159 }
2160 return out
2161}
2162
2163// toolResultBlock renders the live tool-call result body (shown
2164// while the turn is still in flight). The rules that used to
2165// bracket this block have been dropped so the live path looks
2166// identical to the transcript rendering that replaces it when
2167// the turn ends.
2168func toolResultBlock(th Theme, text string, width int, color int) []string {
2169 var out []string
2170 for _, l := range strings.Split(text, "\n") {
2171 for _, w := range wrapLine(l, width-4, " ") {
2172 out = append(out, " "+th.FG256(color, w))
2173 }
2174 }
2175 return out
2176}
2177
2178// defaultToolArgWidth is the number of cells the tool-call header
2179// truncates the primary argument (path/command/query) to when the
2180// ZOT_TOOL_ARG_WIDTH environment variable is unset or invalid.
2181const defaultToolArgWidth = 60
2182
2183// toolArgWidth returns the maximum cell width for the truncated
2184// primary argument shown in a tool-call header. It defaults to
2185// defaultToolArgWidth but can be raised or lowered with the
2186// ZOT_TOOL_ARG_WIDTH environment variable, which is useful for wide
2187// terminals where the default clips long queries too aggressively.
2188// Values outside the sane range [20, 500] are ignored so a stray or
2189// malformed setting can never produce an unreadable header or an
2190// out-of-range slice.
2191func toolArgWidth() int {
2192 v := strings.TrimSpace(os.Getenv("ZOT_TOOL_ARG_WIDTH"))
2193 if v == "" {
2194 return defaultToolArgWidth
2195 }
2196 n, err := strconv.Atoi(v)
2197 if err != nil || n < 20 || n > 500 {
2198 return defaultToolArgWidth
2199 }
2200 return n
2201}
2202
2203// ShortArgs renders a tool call's arguments into a one-line
2204// suffix for the "tool name <args>" header. tool is the tool
2205// name so we can add shape-specific decorations: for read we
2206// append the requested line range (e.g. "path:1-200") pulled
2207// from the offset/limit args, which is useful context at a
2208// glance without expanding the result body. Other tools keep
2209// the legacy "path or command, truncated" shape.
2210//
2211// The truncation width defaults to 60 cells but can be tuned via
2212// the ZOT_TOOL_ARG_WIDTH environment variable (see toolArgWidth).
2213//
2214// Exported because the interactive mode pre-populates the
2215// ToolCallView.Args field with this value as soon as the tool
2216// call is announced, so the live overlay's header matches what
2217// the finalised transcript will later render.
2218func ShortArgs(tool string, raw json.RawMessage) string {
2219 width := toolArgWidth()
2220 var v any
2221 if err := json.Unmarshal(raw, &v); err != nil {
2222 return ""
2223 }
2224 x, ok := v.(map[string]any)
2225 if !ok {
2226 b, _ := json.Marshal(v)
2227 s := oneLineToolLabel(string(b))
2228 if len(s) > width {
2229 s = s[:width-3] + "..."
2230 }
2231 return s
2232 }
2233 var primary string
2234 for _, k := range []string{"path", "file_path", "command"} {
2235 if s, ok := x[k].(string); ok {
2236 primary = s
2237 break
2238 }
2239 }
2240 if primary == "" {
2241 b, _ := json.Marshal(v)
2242 s := oneLineToolLabel(string(b))
2243 if len(s) > width {
2244 s = s[:width-3] + "..."
2245 }
2246 return s
2247 }
2248 primary = oneLineToolLabel(primary)
2249
2250 // Tool-specific decoration. Only the read tool gets a range
2251 // suffix for now; other tools just truncate the primary arg.
2252 suffix := ""
2253 switch strings.ToLower(tool) {
2254 case "read":
2255 start := 1
2256 if n, ok := toInt(x["offset"]); ok && n >= 1 {
2257 start = n
2258 }
2259 if lim, ok := toInt(x["limit"]); ok && lim > 0 {
2260 end := start + lim - 1
2261 suffix = fmt.Sprintf(":%d-%d", start, end)
2262 } else if start > 1 {
2263 suffix = fmt.Sprintf(":%d-", start)
2264 }
2265 }
2266
2267 // Truncate the primary arg leaving room for the suffix so the
2268 // range stays visible even on absurdly long paths.
2269 max := width - len(suffix)
2270 if max < 10 {
2271 max = 10
2272 }
2273 if len(primary) > max {
2274 primary = primary[:max-3] + "..."
2275 }
2276 return primary + suffix
2277}
2278
2279// toInt coerces a json.Unmarshal'd number (float64) or a string
2280// containing a number into an int. Returns ok=false if the value
2281// is neither. Used by shortArgs to survive model quirks where
2282// numeric args come back as strings.
2283func toInt(v any) (int, bool) {
2284 switch n := v.(type) {
2285 case float64:
2286 return int(n), true
2287 case int:
2288 return n, true
2289 case string:
2290 i, err := strconv.Atoi(strings.TrimSpace(n))
2291 if err != nil {
2292 return 0, false
2293 }
2294 return i, true
2295 }
2296 return 0, false
2297}
2298
2299func collectText(blocks []provider.Content) string {
2300 var sb strings.Builder
2301 for _, b := range blocks {
2302 if tb, ok := b.(provider.TextBlock); ok {
2303 if sb.Len() > 0 {
2304 sb.WriteString("\n")
2305 }
2306 sb.WriteString(tb.Text)
2307 }
2308 }
2309 return sb.String()
2310}
2311
2312func truncateLines(s string, n int) string {
2313 lines := strings.Split(s, "\n")
2314 if len(lines) <= n {
2315 return s
2316 }
2317 return strings.Join(lines[:n], "\n") + "\n ... (" + fmt.Sprintf("%d", len(lines)-n) + " more)"
2318}
2319
2320// renderCompactionBlock renders a compaction summary as a distinct
2321// visual block in the chat. When collapsed it shows a one-line label
2322// with the pre-compaction token count; when expanded (ctrl+o) it
2323// shows the full summary text.
2324func (v *View) renderCompactionBlock(m provider.Message, width int) []string {
2325 th := v.Theme
2326 const indent = " "
2327
2328 tokens := m.Meta["tokens_before"]
2329 if tokens == "" {
2330 tokens = "?"
2331 }
2332
2333 if v.ExpandAll {
2334 var lines []string
2335 header := th.FG256(th.Muted, fmt.Sprintf("compacted from ~%s tokens", tokens))
2336 lines = append(lines, indent+header)
2337 lines = append(lines, "")
2338 for _, c := range m.Content {
2339 if tb, ok := c.(provider.TextBlock); ok {
2340 text := tb.Text
2341 if idx := strings.Index(text, "\n\n"); idx >= 0 && strings.HasPrefix(text, "## Context Summary") {
2342 text = text[idx+2:]
2343 }
2344 md := RenderMarkdown(text, th, width-4)
2345 for _, l := range strings.Split(md, "\n") {
2346 if len(l) > 0 && l[0] == FlushLeftSentinel {
2347 l = l[1:]
2348 }
2349 lines = append(lines, indent+l)
2350 }
2351 }
2352 }
2353 return lines
2354 }
2355
2356 // Collapsed: single line, no banner.
2357 line := th.FG256(th.Muted, fmt.Sprintf("compacted from ~%s tokens (ctrl+o to expand)", tokens))
2358 return []string{indent + line}
2359}
2360
2361// StatusBarParams groups the many bits of state the status bar needs.
2362// Grew from a flat argument list once we settled on the layout.
2363type StatusBarParams struct {
2364 Theme Theme
2365 Provider string
2366 Model string
2367 Reasoning string // "" means thinking off
2368 Busy bool
2369 BusyPrefix string // spinner + funny line when busy
2370 CWD string
2371 Locked bool // sandbox on?
2372 NoYolo bool // confirmation mode enabled?
2373
2374 // Cumulative session usage and cost.
2375 Usage provider.Usage
2376 // Subscription is true when the credential is an OAuth token (claude
2377 // pro/max, chatgpt plus/pro) rather than a paid api key. We still
2378 // compute a cost for visibility and append "(sub)" so the user
2379 // knows no real money moved.
2380 Subscription bool
2381
2382 // Last turn's input+cache tokens (approximates current live context).
2383 ContextUsed int
2384 ContextMax int // model's context window; 0 disables the percentage
2385
2386 // AutoCompacting is true when the agent is currently running a
2387 // model-triggered condense pass. Surfaces as "(auto)" after the
2388 // context percentage so it's clear where the spinner is coming from.
2389 AutoCompacting bool
2390
2391 // Telegram true when the telegram bridge is connected. Adds a
2392 // small "- tg -" tag to the cwd line so the user can tell at a
2393 // glance that dms are being mirrored into this session.
2394 Telegram bool
2395
2396 Cols int // terminal width; drives right-alignment of cwd
2397}
2398
2399// StatusBar builds the status shown above the editor. Always returns
2400// two lines when a cwd is provided: the stats on the first line, the
2401// cwd on its own line below, indented to match the stats column. This
2402// keeps the status bar stable across terminal resizes (the cwd never
2403// jumps from right-aligned-on-line-1 to flush-left-on-line-2) and
2404// makes a long cwd safe at any width.
2405//
2406// Layout:
2407//
2408// <busyPrefix> (provider) model stats <- line 1
2409// cwd <- line 2 (2-space indent)
2410//
2411// The old "ctrl+c exit - /help" / "esc cancel" hint is gone entirely.
2412// The slash-command popup and the queued/sliding-in chips already
2413// cover the discoverability of those keybindings.
2414func StatusBar(p StatusBarParams) []string {
2415 th := p.Theme
2416
2417 // Token stats: only include each segment when non-zero. Keeps
2418 // the bar compact on brand-new sessions.
2419 var stats []string
2420 if p.Usage.InputTokens > 0 {
2421 stats = append(stats, fmt.Sprintf("↑%s", formatTokens(p.Usage.InputTokens)))
2422 }
2423 if p.Usage.OutputTokens > 0 {
2424 stats = append(stats, fmt.Sprintf("↓%s", formatTokens(p.Usage.OutputTokens)))
2425 }
2426 if p.Usage.CacheReadTokens > 0 {
2427 stats = append(stats, fmt.Sprintf("R%s", formatTokens(p.Usage.CacheReadTokens)))
2428 }
2429 if p.Usage.CacheWriteTokens > 0 {
2430 stats = append(stats, fmt.Sprintf("W%s", formatTokens(p.Usage.CacheWriteTokens)))
2431 }
2432
2433 // Cost: always show the dollar value computed from token counts,
2434 // even on subscription. Lets you see what the equivalent api cost
2435 // would be (handy for gauging subscription value). Append "(sub)"
2436 // only as a hint that no real money moved.
2437 var costStr string
2438 if p.Usage.CostUSD > 0 || p.Subscription {
2439 costStr = fmt.Sprintf("$%.3f", p.Usage.CostUSD)
2440 if p.Subscription {
2441 costStr += " (sub)"
2442 }
2443 }
2444 if costStr != "" {
2445 stats = append(stats, costStr)
2446 }
2447
2448 // Context %. Color-coded: yellow >70, red >90.
2449 ctx, ctxColor := contextUsage(th, p.ContextUsed, p.ContextMax)
2450 if ctx != "" {
2451 if p.AutoCompacting {
2452 ctx += " (auto)"
2453 }
2454 stats = append(stats, th.FG256(ctxColor, ctx))
2455 }
2456
2457 // Layout uses exactly 2 spaces of horizontal padding everywhere:
2458 // 2 spaces (openai) gpt-5.4 $0.000 (sub) 0.0%/400k ~/Sites/zot
2459 // matches the editor prompt's left inset so the bar lines up
2460 // vertically with the conversation column.
2461 const pad = " " // 2 spaces
2462
2463 left := fmt.Sprintf("(%s) %s", p.Provider, p.Model)
2464 thinking := thinkingLevelLabel(p.Reasoning)
2465 thinkingText := ""
2466 if thinking != "" {
2467 thinkingText = "thinking: " + thinking
2468 }
2469 statsText := strings.Join(stats, " ")
2470 middleParts := make([]string, 0, 2)
2471 if thinkingText != "" {
2472 middleParts = append(middleParts, thinkingText)
2473 }
2474 if statsText != "" {
2475 middleParts = append(middleParts, statsText)
2476 }
2477 middle := strings.Join(middleParts, " ")
2478
2479 var leftBuilder strings.Builder
2480 if p.BusyPrefix != "" {
2481 // Don't re-color the payload itself — the caller already set
2482 // fg colors on the spinner glyph, message, and elapsed
2483 // segments. Wrapping the whole thing here would override
2484 // those choices. The pad itself needs no color (it's spaces).
2485 leftBuilder.WriteString(pad + p.BusyPrefix)
2486 // Exactly one pad (2 spaces) between the busy segment and
2487 // the provider/model block. The leading pad above covers
2488 // the left indent.
2489 leftBuilder.WriteString(pad)
2490 } else {
2491 // Idle path: a single pad of left inset so the line
2492 // aligns with the conversation column on its left edge
2493 // (" you" / " zot" message markers). Without the busy
2494 // prefix there's no trailing separator to double-pad.
2495 leftBuilder.WriteString(pad)
2496 }
2497 leftBuilder.WriteString(th.FG256(th.Muted, left))
2498 if middle != "" {
2499 leftBuilder.WriteString(pad)
2500 // Highlight the opt-in max tier; other status information stays muted.
2501 leftBuilder.WriteString(th.FG256(thinkingStatusColor(th, thinkingText), middle))
2502 }
2503
2504 cwd := shortenHome(p.CWD)
2505 tags := ""
2506 if p.NoYolo {
2507 tags += "yolo mode disabled "
2508 }
2509 if p.Locked {
2510 tags += "jailed "
2511 }
2512 if p.Telegram {
2513 tags += "telegram connected "
2514 }
2515 if tags != "" && cwd != "" {
2516 cwd = tags + "- " + cwd
2517 }
2518
2519 primary := leftBuilder.String()
2520
2521 // On narrow terminals the single line wraps badly. If the visible
2522 // width exceeds cols and we have a busy prefix, split: keep the
2523 // busy prefix on line 1, then put model and (if still needed)
2524 // stats on their own rows. This mirrors the idle split below.
2525 if p.Cols > 0 && p.BusyPrefix != "" && visibleWidth(primary) > p.Cols {
2526 busyLine := pad + p.BusyPrefix
2527 modelLine := pad + th.FG256(th.Muted, left)
2528 lines := []string{busyLine}
2529 if middle != "" && visibleWidth(modelLine+pad+th.FG256(th.Muted, middle)) > p.Cols {
2530 lines = appendWrappedStatusLines(lines, th, pad, left, thinkingText, statsText, p.Cols)
2531 } else {
2532 var infoBuilder strings.Builder
2533 infoBuilder.WriteString(modelLine)
2534 if middle != "" {
2535 infoBuilder.WriteString(pad)
2536 infoBuilder.WriteString(th.FG256(thinkingStatusColor(th, thinkingText), middle))
2537 }
2538 lines = append(lines, infoBuilder.String())
2539 }
2540 if cwd != "" {
2541 lines = append(lines, pad+th.FG256(th.Muted, cwd))
2542 }
2543 return lines
2544 }
2545
2546 // Idle narrow split: keep provider/model on the first status line,
2547 // move usage/cost/context stats to the next, then cwd below. This
2548 // avoids the terminal's hard wrap cutting the stats or pushing cwd
2549 // into an awkward position on small widths.
2550 if p.Cols > 0 && p.BusyPrefix == "" && middle != "" && visibleWidth(primary) > p.Cols {
2551 var lines []string
2552 lines = appendWrappedStatusLines(lines, th, pad, left, thinkingText, statsText, p.Cols)
2553 if cwd != "" {
2554 lines = append(lines, pad+th.FG256(th.Muted, cwd))
2555 }
2556 return lines
2557 }
2558
2559 if cwd == "" {
2560 return []string{primary}
2561 }
2562
2563 // Second line: indent with the same 2-space pad so the cwd lines
2564 // up under the "(provider)" column on line 1.
2565 cwdRendered := pad + th.FG256(th.Muted, cwd)
2566 return []string{primary, cwdRendered}
2567}
2568
2569func appendWrappedStatusLines(lines []string, th Theme, pad, modelText, thinkingText, statsText string, cols int) []string {
2570 modelLine := pad + th.FG256(th.Muted, modelText)
2571 if thinkingText == "" {
2572 lines = append(lines, modelLine)
2573 if statsText != "" {
2574 lines = append(lines, pad+th.FG256(th.Muted, statsText))
2575 }
2576 return lines
2577 }
2578
2579 modelThinkingPlain := pad + modelText + pad + thinkingText
2580 thinkingColor := thinkingStatusColor(th, thinkingText)
2581 if cols <= 0 || visibleWidth(modelThinkingPlain) <= cols {
2582 lines = append(lines, pad+th.FG256(thinkingColor, modelText+pad+thinkingText))
2583 } else {
2584 lines = append(lines, modelLine)
2585 lines = append(lines, pad+th.FG256(thinkingColor, thinkingText))
2586 }
2587 if statsText != "" {
2588 lines = append(lines, pad+th.FG256(th.Muted, statsText))
2589 }
2590 return lines
2591}
2592
2593func thinkingStatusColor(th Theme, thinkingText string) int {
2594 if strings.HasSuffix(thinkingText, ": max") {
2595 return th.ThinkingMax
2596 }
2597 return th.Muted
2598}
2599
2600func thinkingLevelLabel(level string) string {
2601 switch strings.ToLower(strings.TrimSpace(level)) {
2602 case "", "off", "none", "no", "false", "disabled":
2603 return ""
2604 case "minimum", "minimal", "min":
2605 return "minimal"
2606 case "maximum", "xhigh":
2607 return "xhigh"
2608 case "max":
2609 return "max"
2610 default:
2611 return strings.ToLower(strings.TrimSpace(level))
2612 }
2613}
2614
2615// contextUsage renders the "N%/ctxMax" fragment, returning the
2616// rendered string plus the colour to wrap it in.
2617func contextUsage(th Theme, used, max int) (string, int) {
2618 if max <= 0 {
2619 if used <= 0 {
2620 return "", th.Muted
2621 }
2622 return formatTokens(used), th.Muted
2623 }
2624 pct := float64(used) / float64(max) * 100
2625 text := fmt.Sprintf("%.1f%%/%s", pct, formatTokens(max))
2626 switch {
2627 case pct > 90:
2628 return text, th.Error
2629 case pct > 70:
2630 return text, th.Warning
2631 }
2632 return text, th.Muted
2633}
2634
2635// formatTokens footer formatter:
2636//
2637// < 1000 -> "42"
2638// < 10_000 -> "2.7k"
2639// < 1_000_000 -> "35k"
2640// < 10M -> "1.1M"
2641// else -> "12M"
2642func formatTokens(n int) string {
2643 switch {
2644 case n < 0:
2645 return "0"
2646 case n < 1000:
2647 return fmt.Sprintf("%d", n)
2648 case n < 10000:
2649 return fmt.Sprintf("%.1fk", float64(n)/1000)
2650 case n < 1_000_000:
2651 return fmt.Sprintf("%dk", (n+500)/1000)
2652 case n < 10_000_000:
2653 return fmt.Sprintf("%.1fM", float64(n)/1_000_000)
2654 default:
2655 return fmt.Sprintf("%dM", (n+500_000)/1_000_000)
2656 }
2657}
2658
2659// shortenHome replaces the user's $HOME prefix with "~" for readability.
2660func shortenHome(p string) string {
2661 if p == "" {
2662 return ""
2663 }
2664 home := osUserHome()
2665 if home == "" {
2666 return p
2667 }
2668 if p == home {
2669 return "~"
2670 }
2671 if strings.HasPrefix(p, home+"/") {
2672 return "~" + p[len(home):]
2673 }
2674 return p
2675}
2676
2677// osUserHome is a tiny wrapper around os.UserHomeDir so tests can mock it.
2678var osUserHome = func() string {
2679 if h, err := osUserHomeDir(); err == nil {
2680 return h
2681 }
2682 return ""
2683}