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