Skip to content

Commit 0a96085

Browse files
committed
feat(cli): add markdown rendering, rich tool display, and spinner elapsed time (#67, #70, #71)
1 parent 14244a5 commit 0a96085

4 files changed

Lines changed: 374 additions & 7 deletions

File tree

‎packages/opencode/src/cli/lite/index.ts‎

Lines changed: 67 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { cursor, clear, fg, style, write, screen } from "./terminal"
33
import { parseKey, LineEditor } from "./input"
44
import { Spinner } from "./spinner"
55
import { chat, command } from "./session"
6+
import { createMarkdownRenderer } from "./markdown"
67
import { formatTokens, formatDuration } from "../metrics"
78
import { Icons } from "../cmd/tui/util/icons"
89
import { type Task, type AgentStatus } from "./taskpanel"
@@ -20,6 +21,30 @@ import { Command } from "../../command"
2021
import { select } from "./select"
2122
import type { ChatChunk } from "./session"
2223

24+
export function summarizeInput(tool: string, input?: Record<string, unknown>): string {
25+
if (!input) return ""
26+
const str = (key: string) => String(input[key] || "")
27+
28+
if (tool === "bash") return str("command").slice(0, 60)
29+
if (tool === "read") return str("filePath").split("/").slice(-2).join("/")
30+
if (tool === "write" || tool === "edit") return str("filePath").split("/").slice(-2).join("/")
31+
if (tool === "rg" || tool === "grep") {
32+
const pattern = str("pattern").slice(0, 30)
33+
const include = str("include")
34+
return include ? `"${pattern}" in ${include}` : `"${pattern}"`
35+
}
36+
if (tool === "glob") return str("pattern").slice(0, 60)
37+
if (tool === "task") {
38+
const agent = str("subagent_type")
39+
const desc = str("description").slice(0, 40)
40+
return agent ? `@${agent}: ${desc}` : desc
41+
}
42+
if (tool === "todowrite" || tool === "todoread") return "todo list"
43+
44+
const first = Object.values(input).find((v) => typeof v === "string")
45+
return first ? String(first).slice(0, 60) : ""
46+
}
47+
2348
// UI State
2449
let tasksVisible = false
2550
let tasks: Task[] = []
@@ -357,6 +382,9 @@ async function handleCustomCommand(name: string, args: string) {
357382
let totalTokens = 0
358383
const startTime = Date.now()
359384
isOperationInProgress = true
385+
let lastChunkWasToolStart = false
386+
let lastToolSummary = ""
387+
const md = createMarkdownRenderer()
360388

361389
try {
362390
const options = {
@@ -378,18 +406,32 @@ async function handleCustomCommand(name: string, args: string) {
378406
}
379407

380408
if (chunk.type === "text" && chunk.content) {
381-
write(chunk.content)
409+
lastChunkWasToolStart = false
410+
write(md.render(chunk.content))
382411
}
383412

384413
if (chunk.type === "tool_start" && chunk.tool?.trim()) {
385-
write(`${fg.gray}${chunk.tool?.trim()} ${style.reset}`)
414+
const tool = chunk.tool.trim()
415+
lastToolSummary = summarizeInput(tool, chunk.input)
416+
const summary = lastToolSummary ? ` ${lastToolSummary}` : ""
417+
write(`${fg.gray}◇ ${style.reset}${fg.cyan}${tool}${style.reset}${fg.gray}${summary}${style.reset}\n`)
418+
lastChunkWasToolStart = true
386419
}
387420

388421
if (chunk.type === "tool_end" && chunk.tool?.trim()) {
389-
write(`${fg.gray}✓${style.reset} `)
422+
const tool = chunk.tool.trim()
423+
if (lastChunkWasToolStart && lastToolSummary === summarizeInput(tool, chunk.input)) {
424+
write(
425+
`\x1b[1A\r\x1b[2K${fg.green}✓${style.reset} ${fg.cyan}${tool}${style.reset}${fg.gray}${lastToolSummary ? ` ${lastToolSummary}` : ""}${style.reset}\n`,
426+
)
427+
} else {
428+
write(`${fg.green}✓${style.reset} ${fg.cyan}${tool}${style.reset}\n`)
429+
}
430+
lastChunkWasToolStart = false
390431
}
391432

392433
if (chunk.type === "error" && chunk.content) {
434+
lastChunkWasToolStart = false
393435
const safeContent = chunk.content.replace(/\x1b\[[0-9;]*m/g, "").replace(/[\x00-\x1f\x7f]/g, "")
394436
write(`\n${fg.red}Error: ${safeContent}${style.reset}\n`)
395437
}
@@ -399,6 +441,7 @@ async function handleCustomCommand(name: string, args: string) {
399441
}
400442
}
401443

444+
write(md.flush())
402445
const duration = Date.now() - startTime
403446
write(`\n${fg.gray}${formatDuration(duration)} · ${formatTokens(totalTokens)}${style.reset}\n`)
404447
} finally {
@@ -424,6 +467,9 @@ async function handleMessage(message: string) {
424467
let totalTokens = 0
425468
const startTime = Date.now()
426469
isOperationInProgress = true
470+
let lastChunkWasToolStart = false
471+
let lastToolSummary = ""
472+
const md = createMarkdownRenderer()
427473

428474
try {
429475
const options = {
@@ -445,18 +491,32 @@ async function handleMessage(message: string) {
445491
}
446492

447493
if (chunk.type === "text" && chunk.content) {
448-
write(chunk.content)
494+
lastChunkWasToolStart = false
495+
write(md.render(chunk.content))
449496
}
450497

451498
if (chunk.type === "tool_start" && chunk.tool?.trim()) {
452-
write(`${fg.gray}${chunk.tool?.trim()} ${style.reset}`)
499+
const tool = chunk.tool.trim()
500+
lastToolSummary = summarizeInput(tool, chunk.input)
501+
const summary = lastToolSummary ? ` ${lastToolSummary}` : ""
502+
write(`${fg.gray}◇ ${style.reset}${fg.cyan}${tool}${style.reset}${fg.gray}${summary}${style.reset}\n`)
503+
lastChunkWasToolStart = true
453504
}
454505

455506
if (chunk.type === "tool_end" && chunk.tool?.trim()) {
456-
write(`${fg.gray}✓${style.reset} `)
507+
const tool = chunk.tool.trim()
508+
if (lastChunkWasToolStart && lastToolSummary === summarizeInput(tool, chunk.input)) {
509+
write(
510+
`\x1b[1A\r\x1b[2K${fg.green}✓${style.reset} ${fg.cyan}${tool}${style.reset}${fg.gray}${lastToolSummary ? ` ${lastToolSummary}` : ""}${style.reset}\n`,
511+
)
512+
} else {
513+
write(`${fg.green}✓${style.reset} ${fg.cyan}${tool}${style.reset}\n`)
514+
}
515+
lastChunkWasToolStart = false
457516
}
458517

459518
if (chunk.type === "error" && chunk.content) {
519+
lastChunkWasToolStart = false
460520
const safeContent = chunk.content.replace(/\x1b\[[0-9;]*m/g, "").replace(/[\x00-\x1f\x7f]/g, "")
461521
write(`\n${fg.red}Error: ${safeContent}${style.reset}\n`)
462522
}
@@ -466,6 +526,7 @@ async function handleMessage(message: string) {
466526
}
467527
}
468528

529+
write(md.flush())
469530
const duration = Date.now() - startTime
470531
write(`\n${fg.gray}${formatDuration(duration)} · ${formatTokens(totalTokens)}${style.reset}\n`)
471532
} finally {
Lines changed: 173 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,173 @@
1+
import { style, fg } from "./terminal"
2+
3+
const BOLD_MARK = "**"
4+
const CODE_MARK = "`"
5+
const CODE_FENCE = "```"
6+
const RESET = style.reset
7+
8+
interface MarkdownState {
9+
buffer: string
10+
inBold: boolean
11+
inCode: boolean
12+
inCodeBlock: boolean
13+
codeBlockLang: string
14+
}
15+
16+
export function createMarkdownRenderer() {
17+
const state: MarkdownState = {
18+
buffer: "",
19+
inBold: false,
20+
inCode: false,
21+
inCodeBlock: false,
22+
codeBlockLang: "",
23+
}
24+
25+
function render(chunk: string): string {
26+
state.buffer += chunk
27+
let output = ""
28+
let i = 0
29+
30+
while (i < state.buffer.length) {
31+
// Check for code block fence (must be at line start)
32+
if (isLineStart(state.buffer, i) && state.buffer.slice(i).startsWith(CODE_FENCE)) {
33+
const endFence = state.buffer.indexOf("\n", i + CODE_FENCE.length)
34+
const fence = endFence === -1 ? state.buffer.slice(i) : state.buffer.slice(i, endFence)
35+
36+
// Incomplete fence line
37+
if (endFence === -1) {
38+
state.buffer = state.buffer.slice(i)
39+
return output
40+
}
41+
42+
if (state.inCodeBlock) {
43+
// Closing fence
44+
output += `${fg.gray}${fence}${RESET}\n`
45+
state.inCodeBlock = false
46+
state.codeBlockLang = ""
47+
i = endFence + 1
48+
} else {
49+
// Opening fence
50+
const lang = fence.slice(CODE_FENCE.length).trim()
51+
state.codeBlockLang = lang
52+
state.inCodeBlock = true
53+
output += `${fg.gray}${fence}${RESET}\n`
54+
i = endFence + 1
55+
}
56+
continue
57+
}
58+
59+
// Inside code block—pass through with styling
60+
if (state.inCodeBlock) {
61+
const lineEnd = state.buffer.indexOf("\n", i)
62+
const line = lineEnd === -1 ? state.buffer.slice(i) : state.buffer.slice(i, lineEnd + 1)
63+
64+
if (lineEnd === -1) {
65+
state.buffer = state.buffer.slice(i)
66+
return output
67+
}
68+
69+
output += `${fg.cyan}${line}${RESET}`
70+
i = lineEnd + 1
71+
continue
72+
}
73+
74+
// Check for inline code (single backtick)
75+
if (state.buffer[i] === CODE_MARK && !state.inBold) {
76+
// Need at least one more backtick to form a pair
77+
if (i + 1 >= state.buffer.length) {
78+
state.buffer = state.buffer.slice(i)
79+
return output
80+
}
81+
82+
// Find closing backtick
83+
const nextTick = state.buffer.indexOf(CODE_MARK, i + 1)
84+
if (nextTick === -1) {
85+
// Incomplete code span
86+
state.buffer = state.buffer.slice(i)
87+
return output
88+
}
89+
90+
const code = state.buffer.slice(i + 1, nextTick)
91+
output += `${fg.cyan}${code}${RESET}`
92+
i = nextTick + 1
93+
continue
94+
}
95+
96+
// Check for bold (double asterisk)
97+
if (state.buffer.slice(i, i + 2) === BOLD_MARK && !state.inCode) {
98+
state.inBold = !state.inBold
99+
output += state.inBold ? style.bold : RESET
100+
i += 2
101+
continue
102+
}
103+
104+
// Check for header (at line start with #)
105+
if (isLineStart(state.buffer, i) && state.buffer[i] === "#") {
106+
const lineEnd = state.buffer.indexOf("\n", i)
107+
const line = lineEnd === -1 ? state.buffer.slice(i) : state.buffer.slice(i, lineEnd)
108+
109+
if (lineEnd === -1) {
110+
state.buffer = state.buffer.slice(i)
111+
return output
112+
}
113+
114+
const match = line.match(/^(#{1,6})\s+(.+)/)
115+
if (match) {
116+
const header = match[2]
117+
output += `${style.bold}${fg.cyan}${header}${RESET}\n`
118+
i = lineEnd + 1
119+
continue
120+
}
121+
}
122+
123+
// Check for horizontal rule (--- at line start)
124+
if (isLineStart(state.buffer, i) && state.buffer.slice(i, i + 3) === "---") {
125+
const lineEnd = state.buffer.indexOf("\n", i)
126+
const line = lineEnd === -1 ? state.buffer.slice(i) : state.buffer.slice(i, lineEnd)
127+
128+
if (lineEnd === -1) {
129+
state.buffer = state.buffer.slice(i)
130+
return output
131+
}
132+
133+
if (/^-{3,}(\s|$)/.test(line)) {
134+
output += `${fg.gray}${line}${RESET}\n`
135+
i = lineEnd + 1
136+
continue
137+
}
138+
}
139+
140+
// Regular character
141+
output += state.buffer[i]
142+
i++
143+
}
144+
145+
state.buffer = ""
146+
return output
147+
}
148+
149+
function flush(): string {
150+
let output = state.buffer
151+
state.buffer = ""
152+
153+
// Close any open ANSI sequences
154+
if (state.inBold || state.inCode || state.inCodeBlock) {
155+
output += RESET
156+
}
157+
158+
// Reset state for safety
159+
state.inBold = false
160+
state.inCode = false
161+
state.inCodeBlock = false
162+
state.codeBlockLang = ""
163+
164+
return output
165+
}
166+
167+
return { render, flush }
168+
}
169+
170+
function isLineStart(text: string, pos: number): boolean {
171+
if (pos === 0) return true
172+
return text[pos - 1] === "\n"
173+
}

‎packages/opencode/src/cli/lite/spinner.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,16 +6,20 @@ export class Spinner {
66
private frame = 0
77
private interval: ReturnType<typeof setInterval> | null = null
88
private text: string
9+
private startTime: number = 0
910

1011
constructor(text = "Processing") {
1112
this.text = text
1213
}
1314

1415
start() {
1516
write(cursor.hide)
17+
this.startTime = Date.now()
1618
this.interval = setInterval(() => {
1719
this.frame = (this.frame + 1) % frames.length
18-
write(`\r${clear.line}${fg.cyan}${frames[this.frame]}${style.reset} ${fg.gray}${this.text}${style.reset}`)
20+
const elapsed = Math.floor((Date.now() - this.startTime) / 1000)
21+
const time = elapsed > 0 ? ` · ${elapsed}s` : ""
22+
write(`\r${clear.line}${fg.cyan}${frames[this.frame]}${style.reset} ${fg.gray}${this.text}${time}${style.reset}`)
1923
}, 50)
2024
}
2125

0 commit comments

Comments
 (0)