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