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