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