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