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