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