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