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