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