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//
792// Anything else returns nil and only the tool-call header shows.
793func (v *View) renderLiveToolBody(tc ToolCallView, width int) []string {
794 switch tc.Name {
795 case "write", "Write":
796 partial, ok, _ := ExtractPartialStringField(tc.RawJSONBuf, "content")
797 if !ok || partial == "" {
798 return nil
799 }
800 return v.wrapLiveBody(v.renderRawFile(partial, tc.LivePath, 1), width)
801 case "edit", "Edit":
802 partial, ok, _, idx := ExtractLastNewText(tc.RawJSONBuf)
803 if !ok || partial == "" {
804 return nil
805 }
806 // Header line hints which edit is streaming and, when more
807 // than one has landed, how many the model is doing.
808 hint := fmt.Sprintf("edit %d (streaming)", idx)
809 body := []string{" " + v.Theme.FG256(v.Theme.Muted, hint), ""}
810 body = append(body, v.renderRawFile(partial, tc.LivePath, 1)...)
811 return v.wrapLiveBody(body, width)
812 }
813 return nil
814}
815
816// wrapLiveBody returns the streaming body content as a list of
817// box-side rows: each line wrapped in │ ... │ with right padding so
818// the closing edge sits at column width-1. The caller (renderToolCall)
819// supplies the surrounding top/bottom edges so the live overlay
820// renders as a closed box matching the finalised transcript form.
821func (v *View) wrapLiveBody(body []string, width int) []string {
822 body = v.collapseToolBody(body, false)
823 out := make([]string, 0, len(body))
824 for _, l := range body {
825 imgCells, stripped := parseImageFootprint(l)
826 if hasImageEscapeLine(stripped) {
827 out = append(out, toolBoxSideWithImage(v.Theme, stripped, imgCells, width))
828 continue
829 }
830 out = append(out, toolBoxSide(v.Theme, stripped, width))
831 }
832 return out
833}
834
835// toolResultBlock wraps text in thin horizontal rules (top + bottom),
836// indenting the body with four spaces. The rules span the content column.
837// toolBlockRule renders the muted horizontal separator drawn
838// above and below a tool call block. Spans the full content
839// width so it reads as a real section break in the chat
840// regardless of terminal size.
841func toolBlockRule(th Theme, width int) string {
842 w := width
843 if w < 8 {
844 w = 8
845 }
846 return th.FG256(th.Muted, strings.Repeat("─", w))
847}
848
849// toolBoxInnerPad is the number of blank cells kept between a box
850// edge (┌, │, └) and the content inside it. One cell of breathing
851// room makes the label read as part of the box rather than fused to
852// the corner, and gives body lines a tiny gutter from the left side.
853const toolBoxInnerPad = 1
854
855// toolBoxOuterMargin is the number of blank cells kept to the left of
856// the opening corner and to the right of the closing corner. Aligns
857// the box's frame with the column where user-bubble text begins, so
858// the conversation reads as one column instead of having tool boxes
859// running edge-to-edge while user/assistant rows sit indented.
860const toolBoxOuterMargin = 2
861
862// toolBoxTop renders the labelled top edge of a tool block:
863//
864// ┌─ bash xcrun simctl list devices ─────────────────────────────┐
865//
866// The label is the tool name + short args (the same string previously
867// shown on its own row beneath the rule). Padding fills the remainder
868// of the line so the right corner sits at column width-1, matching the
869// closing edge.
870func toolBoxTop(th Theme, label string, width int) string {
871 label = oneLineToolLabel(label)
872 w := width - 2*toolBoxOuterMargin
873 if w < 12 {
874 w = 12
875 }
876 margin := strings.Repeat(" ", toolBoxOuterMargin)
877 innerPad := strings.Repeat(" ", toolBoxInnerPad)
878 // "┌─" + innerPad + " " + label + " " + innerPad = used; pad
879 // with ─ to width-1, then "┐".
880 prefix := "┌─" + innerPad + " "
881 suffix := " " + innerPad
882 used := visibleWidth(prefix) + visibleWidth(label) + visibleWidth(suffix)
883 fill := w - used - 1 // -1 for the closing corner
884 if fill < 0 {
885 // Label overflows; truncate with an ellipsis so the right
886 // corner still lands on the right edge. Rare on real
887 // terminals (the chat column is usually wide enough).
888 over := -fill
889 runes := []rune(label)
890 if over+3 < len(runes) {
891 label = string(runes[:len(runes)-over-3]) + "..."
892 } else {
893 label = "..."
894 }
895 used = visibleWidth(prefix) + visibleWidth(label) + visibleWidth(suffix)
896 fill = w - used - 1
897 if fill < 0 {
898 fill = 0
899 }
900 }
901 fillStr := strings.Repeat("─", fill)
902 name, rest := splitToolLabel(label)
903 return margin + th.FG256(th.Muted, prefix) + th.FG256(th.FG, name) + th.FG256(th.Muted, rest+suffix+fillStr+"┐") + margin
904}
905
906func oneLineToolLabel(label string) string {
907 return strings.Join(strings.Fields(label), " ")
908}
909
910func splitToolLabel(label string) (name, rest string) {
911 label = strings.TrimLeft(label, " ")
912 if label == "" {
913 return "", ""
914 }
915 idx := strings.IndexAny(label, " \t")
916 if idx < 0 {
917 return label, ""
918 }
919 return label[:idx], label[idx:]
920}
921
922// toolBoxBottom renders the bottom edge of a tool block:
923//
924// └─────────────────────────────────────────────────────────────────────────────┘
925//
926// Spans the same width as toolBoxTop so the corners line up.
927func toolBoxBottom(th Theme, width int) string {
928 w := width - 2*toolBoxOuterMargin
929 if w < 12 {
930 w = 12
931 }
932 margin := strings.Repeat(" ", toolBoxOuterMargin)
933 line := "└" + strings.Repeat("─", w-2) + "┘"
934 return margin + th.FG256(th.Muted, line) + margin
935}
936
937// hasImageEscapeLine reports whether s contains a Kitty (\x1b_G) or
938// iTerm2 (\x1b]1337;File=) inline-image escape. Such rows draw into
939// the terminal's graphics layer and shouldn't be wrapped with text
940// box edges.
941func hasImageEscapeLine(s string) bool {
942 return strings.Contains(s, "\x1b]1337;File=") || strings.Contains(s, "\x1b_G")
943}
944
945// imageFootprintSentinel marks rows that belong to an inline-image's
946// reserved footprint — the escape row plus the blank rows below it
947// plus the gap row before the metadata caption. Any consumer that
948// wraps content in box edges (│ ... │) detects the sentinel, strips
949// it, and emits the row — the image graphics rectangle paints over
950// whatever was drawn there. Uses a non-printing C0 control byte so
951// it can never appear in normal text or in an ANSI escape sequence
952// body.
953//
954// The escape row carries an extra width hint between two sentinels:
955// "\x1e<cells>\x1e<spaces+escape>". Wrappers parse the cells count
956// to know how wide the image is in terminal cells and how many cells
957// of trailing padding are needed before the closing box edge.
958const imageFootprintSentinel = "\x1e"
959
960// parseImageFootprint splits a footprint-tagged row into (cellsWide,
961// rest). cellsWide is 0 when the row carries no width hint (the
962// reservation blanks and gap row don't, only the escape row does).
963func parseImageFootprint(s string) (int, string) {
964 if !strings.HasPrefix(s, imageFootprintSentinel) {
965 return 0, s
966 }
967 rest := s[len(imageFootprintSentinel):]
968 end := strings.Index(rest, imageFootprintSentinel)
969 if end < 0 {
970 return 0, rest
971 }
972 w, err := strconv.Atoi(rest[:end])
973 if err != nil {
974 return 0, rest
975 }
976 return w, rest[end+len(imageFootprintSentinel):]
977}
978
979// toolBoxBodyTrimLeft is the number of leading literal spaces stripped
980// from each body line as it enters toolBoxSide. Body renderers
981// (renderToolText, renderRawFile, the diff/bash helpers, ...) all
982// emit a 4-cell indent so the content aligns with the assistant body
983// column when there's no box around it. Inside a box the box edge +
984// inner pad already supply most of that gutter, so we drop a couple
985// of cells from the body's own indent to keep the content from
986// drifting too far right.
987const toolBoxBodyTrimLeft = 2
988
989// toolBoxBodyRenderWidth is the width body renderers should target before
990// their rows are wrapped by toolBoxSide. Most body renderers emit a four-cell
991// indent; toolBoxSide trims toolBoxBodyTrimLeft cells from that indent and
992// then adds the box edge/padding. Passing the full terminal width lets long
993// bash/heredoc lines overrun the inner box and makes terminals soft-wrap,
994// visually breaking the right edge. This returns the maximum renderer width
995// whose post-trim visible width fits inside the box.
996func toolBoxBodyRenderWidth(width int) int {
997 w := width - 2*toolBoxOuterMargin
998 if w < 12 {
999 w = 12
1000 }
1001 inner := w - 2 - 2*toolBoxInnerPad
1002 if inner < 1 {
1003 inner = 1
1004 }
1005 return inner + toolBoxBodyTrimLeft
1006}
1007
1008// toolBoxSide wraps a single body line with vertical box edges:
1009//
1010// │ foo bar baz │
1011//
1012// The middle preserves the line verbatim (including any ANSI escapes)
1013// after stripping toolBoxBodyTrimLeft leading literal spaces. One cell
1014// of inner padding sits on each side so the content breathes from the
1015// edges; the right padding fills to column width-1.
1016func toolBoxSide(th Theme, line string, width int) string {
1017 w := width - 2*toolBoxOuterMargin
1018 if w < 12 {
1019 w = 12
1020 }
1021 margin := strings.Repeat(" ", toolBoxOuterMargin)
1022 left := th.FG256(th.Muted, "│") + strings.Repeat(" ", toolBoxInnerPad)
1023 right := strings.Repeat(" ", toolBoxInnerPad) + th.FG256(th.Muted, "│")
1024 inner := w - 2 - 2*toolBoxInnerPad // available between the two pads
1025 line = trimLeadingSpaces(line, toolBoxBodyTrimLeft)
1026
1027 cur := visibleWidth(line)
1028 if cur > inner {
1029 // Last-resort truncation. Strips ANSI styling at the cut
1030 // point; rare path so the simpler implementation is fine.
1031 line = stripANSI(line)
1032 runes := []rune(line)
1033 if len(runes) > inner {
1034 line = string(runes[:inner])
1035 }
1036 cur = visibleWidth(line)
1037 }
1038 pad := inner - cur
1039 if pad < 0 {
1040 pad = 0
1041 }
1042 return margin + left + line + strings.Repeat(" ", pad) + right + margin
1043}
1044
1045// toolBoxSideWithImage wraps a row that carries an inline-image
1046// escape sequence. The image protocols are configured to not move
1047// the cursor after rendering (iTerm: doNotMoveCursor=1, kitty/
1048// ghostty: C=1), so the only visible cell advance on the row is
1049// from the leading indent spaces before the escape. We pad from
1050// there to the right edge column and draw the closing │ there.
1051// imgCells is unused (kept in the signature for compatibility with
1052// the parseImageFootprint width hint).
1053func toolBoxSideWithImage(th Theme, line string, imgCells, width int) string {
1054 _ = imgCells
1055 w := width - 2*toolBoxOuterMargin
1056 if w < 12 {
1057 w = 12
1058 }
1059 margin := strings.Repeat(" ", toolBoxOuterMargin)
1060 left := th.FG256(th.Muted, "│") + strings.Repeat(" ", toolBoxInnerPad)
1061 right := strings.Repeat(" ", toolBoxInnerPad) + th.FG256(th.Muted, "│")
1062 inner := w - 2 - 2*toolBoxInnerPad
1063
1064 line = trimLeadingSpaces(line, toolBoxBodyTrimLeft)
1065
1066 // Count leading spaces (visible cells consumed before the escape).
1067 leading := 0
1068 for leading < len(line) && line[leading] == ' ' {
1069 leading++
1070 }
1071
1072 pad := inner - leading
1073 if pad < 0 {
1074 pad = 0
1075 }
1076 return margin + left + line + strings.Repeat(" ", pad) + right + margin
1077}
1078
1079// trimLeadingSpaces removes up to n literal space characters from the
1080// start of s without touching anything else. ANSI CSI escapes that
1081// appear before the spaces are skipped over (so a coloured indent
1082// like "\x1b[2m text" still loses its first n cells of indent).
1083// Stops as soon as it hits a non-space character.
1084func trimLeadingSpaces(s string, n int) string {
1085 if n <= 0 || s == "" {
1086 return s
1087 }
1088 var b strings.Builder
1089 b.Grow(len(s))
1090 trimmed := 0
1091 i := 0
1092 for i < len(s) {
1093 // Pass through any ANSI escape sequence verbatim.
1094 if s[i] == 0x1b && i+1 < len(s) && s[i+1] == '[' {
1095 end := i + 2
1096 for end < len(s) {
1097 c := s[end]
1098 end++
1099 if c >= 0x40 && c <= 0x7e {
1100 break
1101 }
1102 }
1103 b.WriteString(s[i:end])
1104 i = end
1105 continue
1106 }
1107 if trimmed < n && s[i] == ' ' {
1108 trimmed++
1109 i++
1110 continue
1111 }
1112 b.WriteString(s[i:])
1113 return b.String()
1114 }
1115 return b.String()
1116}
1117
1118// renderToolResultContent renders the body of a tool result block.
1119// Text blocks get the usual rules-wrapped treatment; text that looks
1120// like a unified diff gets +/- coloring. Image blocks are rendered
1121// inline when the terminal supports a protocol, else as a text
1122// placeholder with dimensions.
1123func (v *View) renderToolResultContent(blocks []provider.Content, width, color int, sourcePath string, startLine int) []string {
1124 var body []string
1125 hasImage := false
1126 for _, b := range blocks {
1127 switch bb := b.(type) {
1128 case provider.TextBlock:
1129 bodyWidth := toolBoxBodyRenderWidth(width)
1130 body = append(body, v.renderToolText(bb.Text, bodyWidth, color, sourcePath, startLine)...)
1131 case provider.ImageBlock:
1132 hasImage = true
1133 body = append(body, v.renderImageBlock(bb, width)...)
1134 }
1135 }
1136 return v.collapseToolBody(body, hasImage)
1137}
1138
1139// collapseToolBody trims lines to the configured preview size when the
1140// view is not in ExpandAll mode, appending a muted "... ctrl+o to
1141// expand" footer. Image blocks never collapse — they're short in text
1142// rows but represent real content the user wants to see.
1143func (v *View) collapseToolBody(lines []string, hasImage bool) []string {
1144 if v.ExpandAll || hasImage {
1145 return lines
1146 }
1147 if len(lines) <= ToolCollapseLines {
1148 return lines
1149 }
1150 kept := lines[:ToolCollapsePreview]
1151 hidden := len(lines) - ToolCollapsePreview
1152 total := len(lines)
1153 footer := fmt.Sprintf(" ... (%d more lines, %d total, ctrl+o to expand)", hidden, total)
1154 footer = v.Theme.FG256(v.Theme.Muted, footer)
1155 out := append([]string(nil), kept...)
1156 out = append(out, "")
1157 return append(out, footer)
1158}
1159
1160// renderToolText renders a text block inside a tool result. If the
1161// text contains a unified-diff section (lines starting with "--- " /
1162// "+++ " / "+" / "-"/" "), those rows are styled with add/remove
1163// colors matching git diff conventions.
1164func (v *View) renderToolText(text string, width, defaultColor int, sourcePath string, startLine int) []string {
1165 // Legacy path: transcripts saved before we dropped line numbers
1166 // from the read tool still carry " 1\t..." prefixes. Detect and
1167 // strip them, then fall through to the highlighter.
1168 if looksLikeNumberedFile(text) {
1169 return v.renderNumberedFile(text, sourcePath)
1170 }
1171 // If the result embeds a unified diff (the edit tool's output
1172 // starts with a short "applied N edit(s)" line and then a
1173 // standard --- / +++ / +/- patch), render the patch with
1174 // add/remove coloring. This takes priority over the file-like
1175 // detector below because a diff technically has many lines of
1176 // "file content" but what the user cares about is what changed,
1177 // not a dump of the post-edit file.
1178 if looksLikeUnifiedDiff(text) {
1179 return v.renderUnifiedDiff(text, width, sourcePath)
1180 }
1181
1182 // Current path: text came from `read` as raw file bytes. When a
1183 // source path is known (the call had a `path` arg), render with
1184 // a synthetic line-number gutter starting at startLine so the
1185 // on-screen view still looks like cat -n. Doesn't apply to non-
1186 // file tool outputs (bash stdout, display notes, etc.).
1187 if sourcePath != "" && looksLikeFileContent(text) {
1188 return v.renderRawFile(text, sourcePath, startLine)
1189 }
1190
1191 // No truncation — the full tool output is rendered into chat and
1192 // becomes part of the scrollback you can page back through.
1193 lines := strings.Split(text, "\n")
1194
1195 // Bash-result styling: when the first row looks like a shell
1196 // prompt line ("$ ...") emitted by the bash tool, style the
1197 // prompt line in accent and the trailing "[exit N] Took X.Ys"
1198 // line in muted type so the command + timing read at a glance.
1199 // Everything between is left on the default tool-output color.
1200 if len(lines) > 0 && strings.HasPrefix(lines[0], "$ ") {
1201 return v.renderBashResult(lines, width, defaultColor)
1202 }
1203
1204 inDiff := false
1205 oldLine, newLine := 1, 1
1206 var out []string
1207 for _, l := range lines {
1208 // Detect diff header: "--- name" followed somewhere by "+++ name".
1209 if strings.HasPrefix(l, "--- ") || strings.HasPrefix(l, "+++ ") {
1210 inDiff = true
1211 out = append(out, " "+v.Theme.FG256(v.Theme.Muted, l))
1212 continue
1213 }
1214 // Hunk header "@@ -a,b +c,d @@" resets the counters so patches
1215 // that skip around in the file still get correct numbering.
1216 if inDiff && strings.HasPrefix(l, "@@") {
1217 if o, n, ok := parseHunkHeader(l); ok {
1218 oldLine, newLine = o, n
1219 }
1220 out = append(out, " "+v.Theme.FG256(v.Theme.Muted, l))
1221 continue
1222 }
1223 if inDiff && strings.TrimSpace(l) == "..." {
1224 out = append(out, "")
1225 out = append(out, " "+v.Theme.FG256(v.Theme.Muted, "..."))
1226 continue
1227 }
1228 if inDiff && len(l) > 0 {
1229 switch l[0] {
1230 case '+':
1231 out = append(out, v.renderDiffRow(l, width, v.Theme.Tool, newLine, '+', sourcePath))
1232 newLine++
1233 continue
1234 case '-':
1235 out = append(out, v.renderDiffRow(l, width, v.Theme.Error, oldLine, '-', sourcePath))
1236 oldLine++
1237 continue
1238 case ' ':
1239 out = append(out, v.renderDiffRow(l, width, v.Theme.Muted, newLine, ' ', sourcePath))
1240 oldLine++
1241 newLine++
1242 continue
1243 }
1244 }
1245 // Regular line.
1246 for _, w := range wrapLine(l, width-4, " ") {
1247 out = append(out, " "+v.Theme.FG256(defaultColor, w))
1248 }
1249 }
1250 return out
1251}
1252
1253// parseHunkHeader extracts the starting old/new line from a unified
1254// diff hunk header ("@@ -12,5 +12,7 @@ ..."). Returns ok=false if the
1255// header is malformed or missing numbers.
1256func parseHunkHeader(l string) (oldStart, newStart int, ok bool) {
1257 // Skip "@@ "
1258 rest := strings.TrimPrefix(l, "@@")
1259 rest = strings.TrimSpace(rest)
1260 if !strings.HasPrefix(rest, "-") {
1261 return 0, 0, false
1262 }
1263 rest = rest[1:]
1264 space := strings.IndexByte(rest, ' ')
1265 if space < 0 {
1266 return 0, 0, false
1267 }
1268 oldPart := rest[:space]
1269 rest = strings.TrimSpace(rest[space+1:])
1270 if !strings.HasPrefix(rest, "+") {
1271 return 0, 0, false
1272 }
1273 rest = rest[1:]
1274 if sp := strings.IndexAny(rest, " \t"); sp >= 0 {
1275 rest = rest[:sp]
1276 }
1277 parseStart := func(s string) (int, bool) {
1278 if c := strings.IndexByte(s, ','); c >= 0 {
1279 s = s[:c]
1280 }
1281 n, err := strconv.Atoi(s)
1282 if err != nil || n < 1 {
1283 return 0, false
1284 }
1285 return n, true
1286 }
1287 o, ok1 := parseStart(oldPart)
1288 n, ok2 := parseStart(rest)
1289 if !ok1 || !ok2 {
1290 return 0, 0, false
1291 }
1292 return o, n, true
1293}
1294
1295// renderDiffRow renders one unified-diff line with a read-style gutter
1296// (6-cell right-aligned line number, muted) followed by the +/-/space
1297// marker and the code. Code is syntax-highlighted if sourcePath hints
1298// at a known language; falls back to the plain diff color otherwise.
1299func (v *View) renderDiffRow(line string, width, color int, lineNo int, mark byte, sourcePath string) string {
1300 if len(line) == 0 {
1301 return ""
1302 }
1303 code := expandTabs(line[1:]) // strip the leading marker; expand tabs
1304
1305 // Syntax-highlight the code half when we know the language. Use
1306 // the same HighlightCode pipeline as renderNumberedFile so the
1307 // palette matches.
1308 lang := LanguageFromPath(sourcePath)
1309 var codeRendered string
1310 if lang != "" {
1311 if h := v.Theme.HighlightCode(code, lang); len(h) == 1 {
1312 codeRendered = h[0]
1313 }
1314 }
1315 if codeRendered == "" {
1316 if mark == ' ' {
1317 codeRendered = v.Theme.FG256(v.Theme.Muted, code)
1318 } else {
1319 codeRendered = v.Theme.FG256(color, code)
1320 }
1321 }
1322
1323 // Gutter shape: sign + number share a color so they read as one
1324 // visual token ("+123") instead of a neutral line number next to
1325 // a stray marker. Unchanged context lines get a muted gutter and
1326 // a leading space so column alignment stays consistent with +/-
1327 // rows.
1328 var gutterText string
1329 switch mark {
1330 case '+':
1331 gutterText = fmt.Sprintf("+%3d ", lineNo)
1332 case '-':
1333 gutterText = fmt.Sprintf("-%3d ", lineNo)
1334 default:
1335 gutterText = fmt.Sprintf(" %3d ", lineNo)
1336 }
1337 var gutter string
1338 if mark == ' ' {
1339 gutter = v.Theme.FG256(v.Theme.Muted, gutterText)
1340 } else {
1341 gutter = v.Theme.FG256(color, gutterText)
1342 }
1343 row := " " + gutter + codeRendered
1344
1345 // Cheap width clamp: truncate visible text if the raw code is too
1346 // long. We work on the pre-ANSI code string because measuring ansi
1347 // output is unreliable.
1348 maxCode := width - 4 /* indent */ - 7 /* gutter (sign+5 digits+tab) */
1349 if maxCode > 0 && len(code) > maxCode {
1350 trunc := strings.Repeat(".", maxCode)
1351 if maxCode > 3 {
1352 trunc = code[:maxCode-3] + "..."
1353 }
1354 if lang != "" {
1355 if h := v.Theme.HighlightCode(trunc, lang); len(h) == 1 {
1356 codeRendered = h[0]
1357 } else if mark == ' ' {
1358 codeRendered = v.Theme.FG256(v.Theme.Muted, trunc)
1359 } else {
1360 codeRendered = v.Theme.FG256(color, trunc)
1361 }
1362 } else if mark == ' ' {
1363 codeRendered = v.Theme.FG256(v.Theme.Muted, trunc)
1364 } else {
1365 codeRendered = v.Theme.FG256(color, trunc)
1366 }
1367 row = " " + gutter + codeRendered
1368 }
1369 return row
1370}
1371
1372// renderImageBlock returns the lines for one image, inline if possible.
1373//
1374// Inline image escapes paint into multiple terminal rows but the zot
1375// renderer treats each slice entry as a single row. To prevent chat
1376// content from being drawn on top of the image, we pad with blank rows
1377// so the image's real footprint is reflected in the frame height.
1378func (v *View) renderImageBlock(b provider.ImageBlock, width int) []string {
1379 w, h := ImageDimensions(b.Data)
1380 kb := len(b.Data) / 1024
1381 // Four-space indent matches every other tool-output row
1382 // (renderRawFile, renderBashResult, diff rows, "... N more
1383 // lines" footers). Keeps the image's metadata line vertically
1384 // aligned with the file content above / below it.
1385 info := fmt.Sprintf(" image - %s - %dx%d - %d KB", b.MimeType, w, h, kb)
1386
1387 if v.ImageProto != ImageProtocolNone {
1388 // Clamp rendered width so the image never overflows the chat
1389 // column. Subtract a 4-cell indent for the tool result block,
1390 // cap at 60 cells, floor at 10.
1391 cells := width - 4
1392 if cells > 60 {
1393 cells = 60
1394 }
1395 if cells < 10 {
1396 cells = 10
1397 }
1398 const maxRows = 20
1399 if seq := RenderInlineImageScaled(v.ImageProto, b.Data, b.MimeType, cells, maxRows); seq != "" {
1400 rows, actualCells := InlineImageFootprint(b.Data, cells, maxRows)
1401 if rows < 1 {
1402 rows = 1
1403 }
1404 if actualCells < 1 {
1405 actualCells = cells
1406 }
1407 // Reserve the image footprint first, then place the escape
1408 // in the top-left of that blank rectangle. Keeping the
1409 // metadata above the image made some terminals blend text
1410 // and graphics layers during full-screen repaints; metadata
1411 // below the reserved rectangle is more stable and easier to
1412 // read. One extra blank row before the metadata gives the
1413 // caption breathing room from the image's last pixel row.
1414 //
1415 // Every footprint row (escape, reservations, gap) is tagged
1416 // with imageFootprintSentinel so callers wrapping content in
1417 // box edges can recognise these rows and emit them bare —
1418 // the image's graphics rectangle paints over them and any
1419 // │ character drawn alongside would visibly bleed through.
1420 // 4 leading cells push the escape past the box's left
1421 // edge plus a small interior gutter so the image rectangle
1422 // sits visibly inside the frame instead of kissing the │.
1423 // The escape row carries a width hint after the sentinel
1424 // ("\x1e<cells>\x1e...") so toolBoxSide knows how many
1425 // cells the image occupies and can pad to the right edge.
1426 widthHint := fmt.Sprintf("%s%d%s", imageFootprintSentinel, actualCells, imageFootprintSentinel)
1427 out := make([]string, 0, rows+3)
1428 out = append(out, widthHint+" "+seq)
1429 for i := 1; i < rows; i++ {
1430 out = append(out, imageFootprintSentinel)
1431 }
1432 out = append(out, imageFootprintSentinel)
1433 out = append(out, v.Theme.FG256(v.Theme.Muted, info))
1434 return out
1435 }
1436 }
1437 return []string{v.Theme.FG256(v.Theme.Muted, info)}
1438}
1439
1440// looksLikeNumberedFile returns true when text matches the `read`
1441// tool's " N\tcontent" format for most of its lines.
1442func looksLikeNumberedFile(text string) bool {
1443 lines := strings.Split(text, "\n")
1444 if len(lines) == 0 {
1445 return false
1446 }
1447 hits := 0
1448 scanned := 0
1449 for _, l := range lines {
1450 if l == "" {
1451 continue
1452 }
1453 scanned++
1454 if scanned > 20 {
1455 break
1456 }
1457 if numberedLineRE.MatchString(l) {
1458 hits++
1459 }
1460 }
1461 if scanned == 0 {
1462 return false
1463 }
1464 return hits*2 >= scanned // majority of non-empty lines match
1465}
1466
1467var numberedLineRE = regexp.MustCompile(`^\s*\d+\t`)
1468
1469// renderNumberedFile strips line numbers, highlights the code, and
1470// re-attaches the line numbers in muted color.
1471func (v *View) renderNumberedFile(text, sourcePath string) []string {
1472 lines := strings.Split(text, "\n")
1473 gutters := make([]string, 0, len(lines))
1474 codes := make([]string, 0, len(lines))
1475 for _, l := range lines {
1476 idx := strings.IndexByte(l, '\t')
1477 if idx < 0 || !numberedLineRE.MatchString(l) {
1478 // Non-code footer (e.g. "[truncated at 2000 lines]").
1479 gutters = append(gutters, "")
1480 codes = append(codes, l)
1481 continue
1482 }
1483 gutter := l[:idx] + " " // replace tab with single space
1484 code := expandTabs(l[idx+1:])
1485 gutters = append(gutters, gutter)
1486 codes = append(codes, code)
1487 }
1488 lang := LanguageFromPath(sourcePath)
1489 var highlighted []string
1490 if lang != "" {
1491 highlighted = v.Theme.HighlightCode(strings.Join(codes, "\n"), lang)
1492 // Chroma sometimes collapses the trailing empty line. Pad to
1493 // align with the gutter slice so per-line zipping works.
1494 for len(highlighted) < len(codes) {
1495 highlighted = append(highlighted, "")
1496 }
1497 if len(highlighted) > len(codes) {
1498 highlighted = highlighted[:len(codes)]
1499 }
1500 } else {
1501 // No lexer for this file type — render in the ToolOut color so
1502 // code is visually distinct from the muted gutter.
1503 highlighted = make([]string, len(codes))
1504 for i, c := range codes {
1505 highlighted[i] = v.Theme.FG256(v.Theme.ToolOut, c)
1506 }
1507 }
1508 out := make([]string, 0, len(codes))
1509 for i, code := range highlighted {
1510 g := gutters[i]
1511 if g == "" {
1512 out = append(out, " "+v.Theme.FG256(v.Theme.Muted, code))
1513 continue
1514 }
1515 out = append(out, " "+v.Theme.FG256(v.Theme.Muted, g)+code)
1516 }
1517 return out
1518}
1519
1520// looksLikeFileContent is a cheap guard to distinguish a read-tool
1521// result from bash stdout or a status message. File content usually
1522// contains characters that status messages don't (code punctuation,
1523// longer lines, multiple lines) and rarely starts with the " >"-
1524// or "error:"-style prefixes tools emit. False positives are OK,
1525// the worst case is a line-number gutter on something that isn't
1526// really code.
1527// renderBashResult styles a bash tool result: the "$ command" first
1528// line in the accent color, the trailing "[exit N] Took X.Ys" line
1529// in muted type, everything else on the default tool-output color.
1530// Called from renderToolText when the first line starts with "$ ".
1531func (v *View) renderBashResult(lines []string, width, defaultColor int) []string {
1532 lines = normalizeBashOutputLines(lines)
1533 // Identify the footer line (exit + timing). The bash tool writes
1534 // it as the last non-empty line of the result.
1535 footerIdx := -1
1536 for i := len(lines) - 1; i >= 0; i-- {
1537 trimmed := strings.TrimSpace(lines[i])
1538 if trimmed == "" {
1539 continue
1540 }
1541 if strings.HasPrefix(trimmed, "[exit ") {
1542 footerIdx = i
1543 }
1544 break
1545 }
1546
1547 var out []string
1548 for i, l := range lines {
1549 switch {
1550 case i == 0 && strings.HasPrefix(l, "$ "):
1551 // Style the $ and the command text in accent. No
1552 // further processing / wrapping so the shell-style
1553 // prompt reads at a glance.
1554 for _, w := range wrapLine(l, width-4, " ") {
1555 out = append(out, " "+v.Theme.FG256(v.Theme.Accent, w))
1556 }
1557 case i == footerIdx:
1558 for _, w := range wrapLine(l, width-4, " ") {
1559 out = append(out, " "+v.Theme.FG256(v.Theme.Muted, w))
1560 }
1561 default:
1562 for _, w := range wrapLine(l, width-4, " ") {
1563 out = append(out, " "+v.Theme.FG256(defaultColor, w))
1564 }
1565 }
1566 }
1567 return out
1568}
1569
1570// normalizeBashOutputLines turns arbitrary terminal output into plain,
1571// box-safe rows before wrapping. Unlike read/write/edit output, bash
1572// stdout/stderr may contain tabs, carriage returns, ANSI/OSC escapes,
1573// and other C0 controls from subprocesses. If those reach the bordered
1574// tool box, the width calculator can undercount what the terminal will
1575// draw and the right edge appears broken. Keep printable text, expand
1576// tabs to spaces, split carriage-return progress rows, and drop escape
1577// / control sequences.
1578func normalizeBashOutputLines(lines []string) []string {
1579 var out []string
1580 for _, line := range lines {
1581 for _, part := range strings.Split(strings.ReplaceAll(line, "\r", "\n"), "\n") {
1582 out = append(out, normalizeBashOutputLine(part))
1583 }
1584 }
1585 if len(out) == 0 {
1586 return []string{""}
1587 }
1588 return out
1589}
1590
1591func normalizeBashOutputLine(s string) string {
1592 var b strings.Builder
1593 col := 0
1594 for i := 0; i < len(s); {
1595 c := s[i]
1596 if c == 0x1b { // ESC: strip CSI/OSC/DCS and simple escapes.
1597 i = skipEscapeSequence(s, i)
1598 continue
1599 }
1600 r, size := utf8.DecodeRuneInString(s[i:])
1601 if r == utf8.RuneError && size == 1 {
1602 i++
1603 continue
1604 }
1605 switch r {
1606 case '\t':
1607 spaces := 8 - (col % 8)
1608 if spaces == 0 {
1609 spaces = 8
1610 }
1611 b.WriteString(strings.Repeat(" ", spaces))
1612 col += spaces
1613 case '\b':
1614 // Backspace-overstrike output is common in spinners/progress bars.
1615 // Dropping it is safer than moving the TUI cursor backwards.
1616 case '\n', '\r':
1617 // Already split by normalizeBashOutputLines.
1618 default:
1619 if r < 0x20 || r == 0x7f {
1620 // Drop non-printing controls.
1621 break
1622 }
1623 b.WriteRune(r)
1624 col += runewidth.RuneWidth(r)
1625 }
1626 i += size
1627 }
1628 return b.String()
1629}
1630
1631func skipEscapeSequence(s string, i int) int {
1632 if i >= len(s) || s[i] != 0x1b {
1633 return i + 1
1634 }
1635 if i+1 >= len(s) {
1636 return len(s)
1637 }
1638 switch s[i+1] {
1639 case '[': // CSI: ESC [ ... final byte 0x40-0x7e
1640 j := i + 2
1641 for j < len(s) {
1642 c := s[j]
1643 j++
1644 if c >= 0x40 && c <= 0x7e {
1645 break
1646 }
1647 }
1648 return j
1649 case ']': // OSC: ESC ] ... BEL or ST
1650 return skipStringEscape(s, i+2)
1651 case 'P', '_', '^', 'X': // DCS/APC/PM/SOS: ESC P ... ST, etc.
1652 return skipStringEscape(s, i+2)
1653 default:
1654 // Two-byte escape (cursor save/restore, charset select, etc.).
1655 return i + 2
1656 }
1657}
1658
1659func skipStringEscape(s string, i int) int {
1660 for i < len(s) {
1661 if s[i] == 0x07 { // BEL
1662 return i + 1
1663 }
1664 if s[i] == 0x1b && i+1 < len(s) && s[i+1] == '\\' { // ST
1665 return i + 2
1666 }
1667 i++
1668 }
1669 return len(s)
1670}
1671
1672// looksLikeUnifiedDiff reports whether text is a context diff as
1673// emitted by the edit tool: rows start with '+', '-', ' ', or
1674// literal "..." (context-break marker). The presence of at least
1675// one '+' or '-' row distinguishes a real diff from an ordinary
1676// file whose lines happen to begin with a space.
1677func looksLikeUnifiedDiff(text string) bool {
1678 lines := strings.Split(text, "\n")
1679 if len(lines) < 2 {
1680 return false
1681 }
1682 sawChange := false
1683 for _, l := range lines {
1684 if l == "" {
1685 continue
1686 }
1687 if l == "..." {
1688 continue
1689 }
1690 switch l[0] {
1691 case '+', '-':
1692 sawChange = true
1693 case ' ':
1694 // context, ok
1695 default:
1696 return false
1697 }
1698 }
1699 return sawChange
1700}
1701
1702// renderUnifiedDiff renders the edit tool's context diff. Each
1703// kept row shows a line-number gutter plus a marker column: '+'
1704// for additions (colored like add), '-' for deletions (colored
1705// like remove), and unmarked context in muted type. A literal
1706// "..." line between hunks renders as an ellipsis in muted type,
1707// indicating skipped unchanged rows. The old and new line
1708// counters advance so each row carries its actual position in
1709// the pre- or post-edit file. Heuristic: when we hit a "...", we
1710// can't know where the next hunk starts, so we don't reset the
1711// counters — they stay approximate in the rare multi-hunk case.
1712func (v *View) renderUnifiedDiff(text string, width int, sourcePath string) []string {
1713 lines := strings.Split(text, "\n")
1714 if n := len(lines); n > 0 && lines[n-1] == "" {
1715 lines = lines[:n-1]
1716 }
1717 oldLine, newLine := 1, 1
1718 var out []string
1719 for _, l := range lines {
1720 if l == "" {
1721 out = append(out, "")
1722 continue
1723 }
1724 if l == "..." {
1725 out = append(out, " "+v.Theme.FG256(v.Theme.Muted, "..."))
1726 continue
1727 }
1728 switch l[0] {
1729 case '+':
1730 out = append(out, v.renderDiffRow(l, width, v.Theme.Tool, newLine, '+', sourcePath))
1731 newLine++
1732 case '-':
1733 out = append(out, v.renderDiffRow(l, width, v.Theme.Error, oldLine, '-', sourcePath))
1734 oldLine++
1735 case ' ':
1736 out = append(out, v.renderDiffRow(l, width, v.Theme.Muted, newLine, ' ', sourcePath))
1737 oldLine++
1738 newLine++
1739 default:
1740 for _, w := range wrapLine(l, width-4, " ") {
1741 out = append(out, " "+v.Theme.FG256(v.Theme.Muted, w))
1742 }
1743 }
1744 }
1745 return out
1746}
1747
1748func looksLikeFileContent(text string) bool {
1749 if strings.TrimSpace(text) == "" {
1750 return false
1751 }
1752 lines := strings.Split(text, "\n")
1753 return len(lines) >= 2
1754}
1755
1756// renderRawFile renders file content received without embedded line
1757// numbers (the current read-tool output). Draws a muted gutter like
1758// "%6d \t" starting at startLine, highlights the code using the
1759// source path's language, and returns the formatted lines.
1760func (v *View) renderRawFile(text, sourcePath string, startLine int) []string {
1761 lines := strings.Split(text, "\n")
1762 // Drop the trailing empty line that Split produces when text ends
1763 // in "\n" so the gutter doesn't show a phantom last number.
1764 if n := len(lines); n > 0 && lines[n-1] == "" {
1765 lines = lines[:n-1]
1766 }
1767 // Split code from trailing footer lines ("... [truncated ...]")
1768 // so we don't number the footer. A single blank separator line
1769 // immediately before the footer is also pulled out so the
1770 // gutter doesn't render a phantom number for it.
1771 codeEnd := len(lines)
1772 for i := len(lines) - 1; i >= 0; i-- {
1773 if strings.HasPrefix(lines[i], "...") {
1774 codeEnd = i
1775 continue
1776 }
1777 break
1778 }
1779 if codeEnd > 0 && codeEnd < len(lines) && lines[codeEnd-1] == "" {
1780 codeEnd--
1781 }
1782 code := lines[:codeEnd]
1783 footer := lines[codeEnd:]
1784
1785 // Expand tabs to 4 spaces so Go / Makefile code renders
1786 // at a consistent width.
1787 for i, c := range code {
1788 code[i] = expandTabs(c)
1789 }
1790
1791 lang := LanguageFromPath(sourcePath)
1792 var highlighted []string
1793 if lang != "" {
1794 highlighted = v.Theme.HighlightCode(strings.Join(code, "\n"), lang)
1795 for len(highlighted) < len(code) {
1796 highlighted = append(highlighted, "")
1797 }
1798 if len(highlighted) > len(code) {
1799 highlighted = highlighted[:len(code)]
1800 }
1801 } else {
1802 highlighted = make([]string, len(code))
1803 for i, c := range code {
1804 highlighted[i] = v.Theme.FG256(v.Theme.ToolOut, c)
1805 }
1806 }
1807
1808 out := make([]string, 0, len(lines))
1809 for i, c := range highlighted {
1810 gutter := fmt.Sprintf("%4d ", startLine+i)
1811 out = append(out, " "+v.Theme.FG256(v.Theme.Muted, gutter)+c)
1812 }
1813 for _, f := range footer {
1814 out = append(out, " "+v.Theme.FG256(v.Theme.Muted, f))
1815 }
1816 return out
1817}
1818
1819// toolResultBlock renders the live tool-call result body (shown
1820// while the turn is still in flight). The rules that used to
1821// bracket this block have been dropped so the live path looks
1822// identical to the transcript rendering that replaces it when
1823// the turn ends.
1824func toolResultBlock(th Theme, text string, width int, color int) []string {
1825 var out []string
1826 for _, l := range strings.Split(text, "\n") {
1827 for _, w := range wrapLine(l, width-4, " ") {
1828 out = append(out, " "+th.FG256(color, w))
1829 }
1830 }
1831 return out
1832}
1833
1834// ShortArgs renders a tool call's arguments into a one-line
1835// suffix for the "tool name <args>" header. tool is the tool
1836// name so we can add shape-specific decorations: for read we
1837// append the requested line range (e.g. "path:1-200") pulled
1838// from the offset/limit args, which is useful context at a
1839// glance without expanding the result body. Other tools keep
1840// the legacy "path or command, truncated at 60 cells" shape.
1841//
1842// Exported because the interactive mode pre-populates the
1843// ToolCallView.Args field with this value as soon as the tool
1844// call is announced, so the live overlay's header matches what
1845// the finalised transcript will later render.
1846func ShortArgs(tool string, raw json.RawMessage) string {
1847 var v any
1848 if err := json.Unmarshal(raw, &v); err != nil {
1849 return ""
1850 }
1851 x, ok := v.(map[string]any)
1852 if !ok {
1853 b, _ := json.Marshal(v)
1854 s := oneLineToolLabel(string(b))
1855 if len(s) > 60 {
1856 s = s[:57] + "..."
1857 }
1858 return s
1859 }
1860 var primary string
1861 for _, k := range []string{"path", "file_path", "command"} {
1862 if s, ok := x[k].(string); ok {
1863 primary = s
1864 break
1865 }
1866 }
1867 if primary == "" {
1868 b, _ := json.Marshal(v)
1869 s := oneLineToolLabel(string(b))
1870 if len(s) > 60 {
1871 s = s[:57] + "..."
1872 }
1873 return s
1874 }
1875 primary = oneLineToolLabel(primary)
1876
1877 // Tool-specific decoration. Only the read tool gets a range
1878 // suffix for now; other tools just truncate the primary arg.
1879 suffix := ""
1880 switch strings.ToLower(tool) {
1881 case "read":
1882 start := 1
1883 if n, ok := toInt(x["offset"]); ok && n >= 1 {
1884 start = n
1885 }
1886 if lim, ok := toInt(x["limit"]); ok && lim > 0 {
1887 end := start + lim - 1
1888 suffix = fmt.Sprintf(":%d-%d", start, end)
1889 } else if start > 1 {
1890 suffix = fmt.Sprintf(":%d-", start)
1891 }
1892 }
1893
1894 // Truncate the primary arg leaving room for the suffix so the
1895 // range stays visible even on absurdly long paths.
1896 max := 60 - len(suffix)
1897 if max < 10 {
1898 max = 10
1899 }
1900 if len(primary) > max {
1901 primary = primary[:max-3] + "..."
1902 }
1903 return primary + suffix
1904}
1905
1906// toInt coerces a json.Unmarshal'd number (float64) or a string
1907// containing a number into an int. Returns ok=false if the value
1908// is neither. Used by shortArgs to survive model quirks where
1909// numeric args come back as strings.
1910func toInt(v any) (int, bool) {
1911 switch n := v.(type) {
1912 case float64:
1913 return int(n), true
1914 case int:
1915 return n, true
1916 case string:
1917 i, err := strconv.Atoi(strings.TrimSpace(n))
1918 if err != nil {
1919 return 0, false
1920 }
1921 return i, true
1922 }
1923 return 0, false
1924}
1925
1926func collectText(blocks []provider.Content) string {
1927 var sb strings.Builder
1928 for _, b := range blocks {
1929 if tb, ok := b.(provider.TextBlock); ok {
1930 if sb.Len() > 0 {
1931 sb.WriteString("\n")
1932 }
1933 sb.WriteString(tb.Text)
1934 }
1935 }
1936 return sb.String()
1937}
1938
1939func truncateLines(s string, n int) string {
1940 lines := strings.Split(s, "\n")
1941 if len(lines) <= n {
1942 return s
1943 }
1944 return strings.Join(lines[:n], "\n") + "\n ... (" + fmt.Sprintf("%d", len(lines)-n) + " more)"
1945}
1946
1947// renderCompactionBlock renders a compaction summary as a distinct
1948// visual block in the chat. When collapsed it shows a one-line label
1949// with the pre-compaction token count; when expanded (ctrl+o) it
1950// shows the full summary text.
1951func (v *View) renderCompactionBlock(m provider.Message, width int) []string {
1952 th := v.Theme
1953 const indent = " "
1954
1955 tokens := m.Meta["tokens_before"]
1956 if tokens == "" {
1957 tokens = "?"
1958 }
1959
1960 if v.ExpandAll {
1961 var lines []string
1962 header := th.FG256(th.Muted, fmt.Sprintf("compacted from ~%s tokens", tokens))
1963 lines = append(lines, indent+header)
1964 lines = append(lines, "")
1965 for _, c := range m.Content {
1966 if tb, ok := c.(provider.TextBlock); ok {
1967 text := tb.Text
1968 if idx := strings.Index(text, "\n\n"); idx >= 0 && strings.HasPrefix(text, "## Context Summary") {
1969 text = text[idx+2:]
1970 }
1971 md := RenderMarkdown(text, th, width-4)
1972 for _, l := range strings.Split(md, "\n") {
1973 if len(l) > 0 && l[0] == FlushLeftSentinel {
1974 l = l[1:]
1975 }
1976 lines = append(lines, indent+l)
1977 }
1978 }
1979 }
1980 return lines
1981 }
1982
1983 // Collapsed: single line, no banner.
1984 line := th.FG256(th.Muted, fmt.Sprintf("compacted from ~%s tokens (ctrl+o to expand)", tokens))
1985 return []string{indent + line}
1986}
1987
1988// StatusBarParams groups the many bits of state the status bar needs.
1989// Grew from a flat argument list once we settled on the layout.
1990type StatusBarParams struct {
1991 Theme Theme
1992 Provider string
1993 Model string
1994 Reasoning string // "" means thinking off
1995 Busy bool
1996 BusyPrefix string // spinner + funny line when busy
1997 CWD string
1998 Locked bool // sandbox on?
1999 NoYolo bool // confirmation mode enabled?
2000
2001 // Cumulative session usage and cost.
2002 Usage provider.Usage
2003 // Subscription is true when the credential is an OAuth token (claude
2004 // pro/max, chatgpt plus/pro) rather than a paid api key. We still
2005 // compute a cost for visibility and append "(sub)" so the user
2006 // knows no real money moved.
2007 Subscription bool
2008
2009 // Last turn's input+cache tokens (approximates current live context).
2010 ContextUsed int
2011 ContextMax int // model's context window; 0 disables the percentage
2012
2013 // AutoCompacting is true when the agent is currently running a
2014 // model-triggered condense pass. Surfaces as "(auto)" after the
2015 // context percentage so it's clear where the spinner is coming from.
2016 AutoCompacting bool
2017
2018 // Telegram true when the telegram bridge is connected. Adds a
2019 // small "- tg -" tag to the cwd line so the user can tell at a
2020 // glance that dms are being mirrored into this session.
2021 Telegram bool
2022
2023 Cols int // terminal width; drives right-alignment of cwd
2024}
2025
2026// StatusBar builds the status shown above the editor. Always returns
2027// two lines when a cwd is provided: the stats on the first line, the
2028// cwd on its own line below, indented to match the stats column. This
2029// keeps the status bar stable across terminal resizes (the cwd never
2030// jumps from right-aligned-on-line-1 to flush-left-on-line-2) and
2031// makes a long cwd safe at any width.
2032//
2033// Layout:
2034//
2035// <busyPrefix> (provider) model stats <- line 1
2036// cwd <- line 2 (2-space indent)
2037//
2038// The old "ctrl+c exit - /help" / "esc cancel" hint is gone entirely.
2039// The slash-command popup and the queued/sliding-in chips already
2040// cover the discoverability of those keybindings.
2041func StatusBar(p StatusBarParams) []string {
2042 th := p.Theme
2043
2044 // Token stats: only include each segment when non-zero. Keeps
2045 // the bar compact on brand-new sessions.
2046 var stats []string
2047 if p.Usage.InputTokens > 0 {
2048 stats = append(stats, fmt.Sprintf("↑%s", formatTokens(p.Usage.InputTokens)))
2049 }
2050 if p.Usage.OutputTokens > 0 {
2051 stats = append(stats, fmt.Sprintf("↓%s", formatTokens(p.Usage.OutputTokens)))
2052 }
2053 if p.Usage.CacheReadTokens > 0 {
2054 stats = append(stats, fmt.Sprintf("R%s", formatTokens(p.Usage.CacheReadTokens)))
2055 }
2056 if p.Usage.CacheWriteTokens > 0 {
2057 stats = append(stats, fmt.Sprintf("W%s", formatTokens(p.Usage.CacheWriteTokens)))
2058 }
2059
2060 // Cost: always show the dollar value computed from token counts,
2061 // even on subscription. Lets you see what the equivalent api cost
2062 // would be (handy for gauging subscription value). Append "(sub)"
2063 // only as a hint that no real money moved.
2064 var costStr string
2065 if p.Usage.CostUSD > 0 || p.Subscription {
2066 costStr = fmt.Sprintf("$%.3f", p.Usage.CostUSD)
2067 if p.Subscription {
2068 costStr += " (sub)"
2069 }
2070 }
2071 if costStr != "" {
2072 stats = append(stats, costStr)
2073 }
2074
2075 // Context %. Color-coded: yellow >70, red >90.
2076 ctx, ctxColor := contextUsage(th, p.ContextUsed, p.ContextMax)
2077 if ctx != "" {
2078 if p.AutoCompacting {
2079 ctx += " (auto)"
2080 }
2081 stats = append(stats, th.FG256(ctxColor, ctx))
2082 }
2083
2084 // Layout uses exactly 2 spaces of horizontal padding everywhere:
2085 // 2 spaces (openai) gpt-5.4 $0.000 (sub) 0.0%/400k ~/Sites/zot
2086 // matches the editor prompt's left inset so the bar lines up
2087 // vertically with the conversation column.
2088 const pad = " " // 2 spaces
2089
2090 left := fmt.Sprintf("(%s) %s", p.Provider, p.Model)
2091 thinking := thinkingLevelLabel(p.Reasoning)
2092 thinkingText := ""
2093 if thinking != "" {
2094 thinkingText = "thinking: " + thinking
2095 }
2096 statsText := strings.Join(stats, " ")
2097 middleParts := make([]string, 0, 2)
2098 if thinkingText != "" {
2099 middleParts = append(middleParts, thinkingText)
2100 }
2101 if statsText != "" {
2102 middleParts = append(middleParts, statsText)
2103 }
2104 middle := strings.Join(middleParts, " ")
2105
2106 var leftBuilder strings.Builder
2107 if p.BusyPrefix != "" {
2108 // Don't re-color the payload itself — the caller already set
2109 // fg colors on the spinner glyph, message, and elapsed
2110 // segments. Wrapping the whole thing here would override
2111 // those choices. The pad itself needs no color (it's spaces).
2112 leftBuilder.WriteString(pad + p.BusyPrefix)
2113 // Exactly one pad (2 spaces) between the busy segment and
2114 // the provider/model block. The leading pad above covers
2115 // the left indent.
2116 leftBuilder.WriteString(pad)
2117 } else {
2118 // Idle path: a single pad of left inset so the line
2119 // aligns with the conversation column on its left edge
2120 // (" you" / " zot" message markers). Without the busy
2121 // prefix there's no trailing separator to double-pad.
2122 leftBuilder.WriteString(pad)
2123 }
2124 leftBuilder.WriteString(th.FG256(th.Muted, left))
2125 if middle != "" {
2126 leftBuilder.WriteString(pad)
2127 // `middle` already has colorized context segments; wrap the rest in muted.
2128 leftBuilder.WriteString(th.FG256(th.Muted, middle))
2129 }
2130
2131 cwd := shortenHome(p.CWD)
2132 tags := ""
2133 if p.NoYolo {
2134 tags += "yolo mode disabled "
2135 }
2136 if p.Locked {
2137 tags += "jailed "
2138 }
2139 if p.Telegram {
2140 tags += "telegram connected "
2141 }
2142 if tags != "" && cwd != "" {
2143 cwd = tags + "- " + cwd
2144 }
2145
2146 primary := leftBuilder.String()
2147
2148 // On narrow terminals the single line wraps badly. If the visible
2149 // width exceeds cols and we have a busy prefix, split: keep the
2150 // busy prefix on line 1, then put model and (if still needed)
2151 // stats on their own rows. This mirrors the idle split below.
2152 if p.Cols > 0 && p.BusyPrefix != "" && visibleWidth(primary) > p.Cols {
2153 busyLine := pad + p.BusyPrefix
2154 modelLine := pad + th.FG256(th.Muted, left)
2155 lines := []string{busyLine}
2156 if middle != "" && visibleWidth(modelLine+pad+th.FG256(th.Muted, middle)) > p.Cols {
2157 lines = appendWrappedStatusLines(lines, th, pad, left, thinkingText, statsText, p.Cols)
2158 } else {
2159 var infoBuilder strings.Builder
2160 infoBuilder.WriteString(modelLine)
2161 if middle != "" {
2162 infoBuilder.WriteString(pad)
2163 infoBuilder.WriteString(th.FG256(th.Muted, middle))
2164 }
2165 lines = append(lines, infoBuilder.String())
2166 }
2167 if cwd != "" {
2168 lines = append(lines, pad+th.FG256(th.Muted, cwd))
2169 }
2170 return lines
2171 }
2172
2173 // Idle narrow split: keep provider/model on the first status line,
2174 // move usage/cost/context stats to the next, then cwd below. This
2175 // avoids the terminal's hard wrap cutting the stats or pushing cwd
2176 // into an awkward position on small widths.
2177 if p.Cols > 0 && p.BusyPrefix == "" && middle != "" && visibleWidth(primary) > p.Cols {
2178 var lines []string
2179 lines = appendWrappedStatusLines(lines, th, pad, left, thinkingText, statsText, p.Cols)
2180 if cwd != "" {
2181 lines = append(lines, pad+th.FG256(th.Muted, cwd))
2182 }
2183 return lines
2184 }
2185
2186 if cwd == "" {
2187 return []string{primary}
2188 }
2189
2190 // Second line: indent with the same 2-space pad so the cwd lines
2191 // up under the "(provider)" column on line 1.
2192 cwdRendered := pad + th.FG256(th.Muted, cwd)
2193 return []string{primary, cwdRendered}
2194}
2195
2196func appendWrappedStatusLines(lines []string, th Theme, pad, modelText, thinkingText, statsText string, cols int) []string {
2197 modelLine := pad + th.FG256(th.Muted, modelText)
2198 if thinkingText == "" {
2199 lines = append(lines, modelLine)
2200 if statsText != "" {
2201 lines = append(lines, pad+th.FG256(th.Muted, statsText))
2202 }
2203 return lines
2204 }
2205
2206 modelThinkingPlain := pad + modelText + pad + thinkingText
2207 if cols <= 0 || visibleWidth(modelThinkingPlain) <= cols {
2208 lines = append(lines, pad+th.FG256(th.Muted, modelText+pad+thinkingText))
2209 } else {
2210 lines = append(lines, modelLine)
2211 lines = append(lines, pad+th.FG256(th.Muted, thinkingText))
2212 }
2213 if statsText != "" {
2214 lines = append(lines, pad+th.FG256(th.Muted, statsText))
2215 }
2216 return lines
2217}
2218
2219func thinkingLevelLabel(level string) string {
2220 switch strings.ToLower(strings.TrimSpace(level)) {
2221 case "", "off", "none", "no", "false", "disabled":
2222 return ""
2223 case "minimum", "minimal", "min":
2224 return "minimal"
2225 case "maximum", "max", "xhigh":
2226 return "maximum"
2227 default:
2228 return strings.ToLower(strings.TrimSpace(level))
2229 }
2230}
2231
2232// contextUsage renders the "N%/ctxMax" fragment, returning the
2233// rendered string plus the colour to wrap it in.
2234func contextUsage(th Theme, used, max int) (string, int) {
2235 if max <= 0 {
2236 if used <= 0 {
2237 return "", th.Muted
2238 }
2239 return formatTokens(used), th.Muted
2240 }
2241 pct := float64(used) / float64(max) * 100
2242 text := fmt.Sprintf("%.1f%%/%s", pct, formatTokens(max))
2243 switch {
2244 case pct > 90:
2245 return text, th.Error
2246 case pct > 70:
2247 return text, th.Warning
2248 }
2249 return text, th.Muted
2250}
2251
2252// formatTokens footer formatter:
2253//
2254// < 1000 -> "42"
2255// < 10_000 -> "2.7k"
2256// < 1_000_000 -> "35k"
2257// < 10M -> "1.1M"
2258// else -> "12M"
2259func formatTokens(n int) string {
2260 switch {
2261 case n < 0:
2262 return "0"
2263 case n < 1000:
2264 return fmt.Sprintf("%d", n)
2265 case n < 10000:
2266 return fmt.Sprintf("%.1fk", float64(n)/1000)
2267 case n < 1_000_000:
2268 return fmt.Sprintf("%dk", (n+500)/1000)
2269 case n < 10_000_000:
2270 return fmt.Sprintf("%.1fM", float64(n)/1_000_000)
2271 default:
2272 return fmt.Sprintf("%dM", (n+500_000)/1_000_000)
2273 }
2274}
2275
2276// shortenHome replaces the user's $HOME prefix with "~" for readability.
2277func shortenHome(p string) string {
2278 if p == "" {
2279 return ""
2280 }
2281 home := osUserHome()
2282 if home == "" {
2283 return p
2284 }
2285 if p == home {
2286 return "~"
2287 }
2288 if strings.HasPrefix(p, home+"/") {
2289 return "~" + p[len(home):]
2290 }
2291 return p
2292}
2293
2294// osUserHome is a tiny wrapper around os.UserHomeDir so tests can mock it.
2295var osUserHome = func() string {
2296 if h, err := osUserHomeDir(); err == nil {
2297 return h
2298 }
2299 return ""
2300}