Skip to content

Commit 20b8102

Browse files
committed
feat(cli): add oclite UI components for task panel (#19, #20, #21)
1 parent 6981429 commit 20b8102

7 files changed

Lines changed: 299 additions & 12 deletions

File tree

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import { fg, bg, style } from "./terminal"
2+
3+
export interface BottomBarState {
4+
permissionMode: "ask" | "bypass" | "deny"
5+
fileChanges: {
6+
total: number
7+
added: number
8+
removed: number
9+
}
10+
user?: string
11+
host?: string
12+
}
13+
14+
const sanitize = (s: string): string => s.replace(/\x1b\[[0-9;]*m/g, "").replace(/[\x00-\x1f\x7f]/g, "")
15+
16+
const safeNum = (n: number): number => (Number.isFinite(n) ? n : 0)
17+
18+
const formatCount = (n: number): string => (n > 9999 ? `${(n / 1000).toFixed(1)}k` : String(n))
19+
20+
export function renderPrompt(): string {
21+
return `${fg.cyan}❯${style.reset} `
22+
}
23+
24+
export function renderBottomBar(state: BottomBarState): string {
25+
const parts: string[] = []
26+
27+
const modeText = state.permissionMode === "bypass" ? "bypass permissions on" : state.permissionMode
28+
parts.push(`${fg.yellow}▶▶${style.reset} ${modeText}`)
29+
30+
parts.push(`(shift+Tab to cycle)`)
31+
32+
const addedCount = Math.max(0, safeNum(state.fileChanges.added))
33+
const removedCount = Math.max(0, safeNum(state.fileChanges.removed))
34+
const totalCount = Math.max(0, safeNum(state.fileChanges.total))
35+
36+
const fileCount = `${formatCount(totalCount)} files`
37+
const added = `${fg.brightGreen}+${formatCount(addedCount)}${style.reset}`
38+
const removed = `${fg.red}-${formatCount(removedCount)}${style.reset}`
39+
parts.push(`${fileCount} ${added} ${removed}`)
40+
41+
let userBadge = ""
42+
if (state.user || state.host) {
43+
const sanitizedUser = state.user ? sanitize(state.user) : ""
44+
const sanitizedHost = state.host ? sanitize(state.host) : ""
45+
const userHost = [sanitizedUser, sanitizedHost].filter(Boolean).join("@")
46+
userBadge = userHost ? `${bg.cyan}${fg.black}${userHost}${style.reset}` : ""
47+
}
48+
49+
const line = parts.join(" · ")
50+
return userBadge ? `${line} ${userBadge}` : line
51+
}

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

Lines changed: 50 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,30 @@ import { cursor, clear, fg, style, write, screen } from "./terminal"
33
import { parseKey, LineEditor } from "./input"
44
import { Spinner } from "./spinner"
55
import { chat } from "./session"
6-
7-
const PROMPT = `${fg.cyan}>${style.reset} `
6+
import { formatTokens, formatDuration } from "../metrics"
7+
import { Icons } from "../cmd/tui/util/icons"
8+
import { renderTaskPanel, type Task, type AgentStatus } from "./taskpanel"
9+
import { renderStatusLine, type StatusLineState } from "./statusline"
10+
import { renderBottomBar, renderPrompt, type BottomBarState } from "./bottombar"
11+
12+
// UI State
13+
let tasksVisible = false
14+
let tasks: Task[] = []
15+
let agents: AgentStatus[] = []
16+
let statusLine: StatusLineState = {
17+
activity: "Idle",
18+
duration: 0,
19+
tokens: 0,
20+
tasksVisible: false,
21+
}
22+
let bottomBar: BottomBarState = {
23+
permissionMode: "ask",
24+
fileChanges: {
25+
total: 0,
26+
added: 0,
27+
removed: 0,
28+
},
29+
}
830

931
async function main() {
1032
// Check TTY
@@ -28,7 +50,7 @@ async function main() {
2850
process.stdin.resume()
2951

3052
// Render prompt
31-
editor.render(PROMPT)
53+
editor.render(renderPrompt())
3254

3355
// Handle input
3456
process.stdin.on("data", async (data: Buffer) => {
@@ -40,6 +62,13 @@ async function main() {
4062
process.exit(0)
4163
}
4264

65+
// Ctrl+T to toggle task panel
66+
if (key.ctrl && key.name === "t") {
67+
tasksVisible = !tasksVisible
68+
statusLine.tasksVisible = tasksVisible
69+
editor.render(renderPrompt())
70+
}
71+
4372
const result = editor.handle(key)
4473

4574
if (result !== null) {
@@ -51,9 +80,9 @@ async function main() {
5180
await handleMessage(result)
5281
}
5382

54-
editor.render(PROMPT)
83+
editor.render(renderPrompt())
5584
} else {
56-
editor.render(PROMPT)
85+
editor.render(renderPrompt())
5786
}
5887
})
5988

@@ -102,6 +131,9 @@ async function handleMessage(message: string) {
102131
spinner.start()
103132

104133
let first = true
134+
let totalTokens = 0
135+
const startTime = Date.now()
136+
105137
try {
106138
for await (const chunk of chat(message)) {
107139
if (first) {
@@ -113,18 +145,26 @@ async function handleMessage(message: string) {
113145
write(chunk.content)
114146
}
115147

116-
if (chunk.type === "tool_start" && chunk.tool) {
117-
write(`\n${fg.yellow}▶ ${chunk.tool}${style.reset}\n`)
148+
if (chunk.type === "tool_start" && chunk.tool?.trim()) {
149+
write(`\n${Icons.taskIcon("progress")} ${chunk.tool}\n`)
118150
}
119151

120-
if (chunk.type === "tool_end" && chunk.tool) {
121-
write(`${fg.green}✓ ${chunk.tool}${style.reset}\n`)
152+
if (chunk.type === "tool_end" && chunk.tool?.trim()) {
153+
write(`${Icons.taskIcon("completed")} ${chunk.tool}\n`)
122154
}
123155

124156
if (chunk.type === "error" && chunk.content) {
125-
write(`\n${fg.red}Error: ${chunk.content}${style.reset}\n`)
157+
const safeContent = chunk.content.replace(/\x1b\[[0-9;]*m/g, "").replace(/[\x00-\x1f\x7f]/g, "")
158+
write(`\n${fg.red}Error: ${safeContent}${style.reset}\n`)
159+
}
160+
161+
if (chunk.tokens !== undefined) {
162+
totalTokens += chunk.tokens
126163
}
127164
}
165+
166+
const duration = Date.now() - startTime
167+
write(`\n${fg.gray}${formatDuration(duration)} · ${formatTokens(totalTokens)}${style.reset}\n`)
128168
} catch (err) {
129169
if (first) spinner.stop(false)
130170
const msg = err instanceof Error ? err.message : String(err)

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

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ export interface ChatChunk {
1515
tool?: string
1616
input?: Record<string, unknown>
1717
output?: string
18+
tokens?: number
1819
}
1920

2021
interface ChatOptions {
@@ -35,6 +36,7 @@ export async function* chat(message: string, options?: ChatOptions): AsyncGenera
3536

3637
const buffer: ChatChunk[] = []
3738
let lastTextBuffer = ""
39+
let stepTokens = 0
3840

3941
const unsubscribe = Bus.subscribe(MessageV2.Event.PartUpdated, (event) => {
4042
const part = event.properties.part
@@ -60,6 +62,13 @@ export async function* chat(message: string, options?: ChatOptions): AsyncGenera
6062
output,
6163
})
6264
}
65+
} else if (part.type === "step-finish") {
66+
stepTokens +=
67+
part.tokens.input +
68+
part.tokens.output +
69+
part.tokens.reasoning +
70+
part.tokens.cache.read +
71+
part.tokens.cache.write
6372
}
6473
})
6574

@@ -76,7 +85,7 @@ export async function* chat(message: string, options?: ChatOptions): AsyncGenera
7685
yield chunk
7786
}
7887

79-
yield { type: "done" }
88+
yield { type: "done", tokens: stepTokens }
8089
} catch (error) {
8190
const errorMessage = error instanceof Error ? error.message : String(error)
8291
const stack = error instanceof Error ? error.stack : undefined
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import { formatTokens, formatDuration } from "../metrics"
2+
import { fg, style } from "./terminal"
3+
4+
export interface StatusLineState {
5+
activity: string
6+
duration: number
7+
tokens: number
8+
tasksVisible: boolean
9+
}
10+
11+
const sanitize = (s: string): string => s.replace(/\x1b\[[0-9;]*m/g, "").replace(/[\x00-\x1f\x7f]/g, "")
12+
13+
const safeNum = (n: number): number => (Number.isFinite(n) ? Math.max(0, n) : 0)
14+
15+
const truncate = (s: string, max: number): string => (s.length > max ? s.slice(0, max) + "…" : s)
16+
17+
export function renderStatusLine(state: StatusLineState): string {
18+
const symbol = `${fg.brightCyan}◆${style.reset}`
19+
20+
const safeDuration = safeNum(state.duration)
21+
const safeTokens = safeNum(state.tokens)
22+
const durationText = formatDuration(safeDuration)
23+
const tokensText = formatTokens(safeTokens)
24+
25+
const sanitizedActivity = sanitize(state.activity || "")
26+
const activity = sanitizedActivity.trim() || "Idle"
27+
const truncatedActivity = truncate(activity, 30)
28+
29+
const taskHint = state.tasksVisible ? "hide" : "show"
30+
31+
const hints = ["Esc to interrupt", `ctrl+t to ${taskHint} tasks`, durationText, `↓ ${tokensText}`]
32+
33+
return `${symbol} ${truncatedActivity} (${hints.join(" · ")})`
34+
}
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
import { formatTokens } from "../metrics"
2+
import { Icons } from "../cmd/tui/util/icons"
3+
import { fg, style } from "./terminal"
4+
5+
export interface Task {
6+
id: string
7+
description: string
8+
status: "pending" | "running" | "completed"
9+
blockedBy?: string
10+
}
11+
12+
export interface AgentStatus {
13+
name: string
14+
activity: string
15+
toolUses: number
16+
tokens: number
17+
}
18+
19+
const sanitize = (s: string): string => s.replace(/\x1b\[[0-9;]*m/g, "").replace(/[\x00-\x1f\x7f]/g, "")
20+
21+
const safeNum = (n: number): number => (Number.isFinite(n) ? Math.max(0, n) : 0)
22+
23+
const truncate = (s: string, max: number): string => (s.length > max ? s.slice(0, max - 1) + "…" : s)
24+
25+
export function renderTaskList(tasks: Task[]): string {
26+
if (!tasks || tasks.length === 0) return ""
27+
28+
const completed = tasks.filter((t) => t.status === "completed").length
29+
const pending = tasks.filter((t) => t.status === "pending" || t.status === "running").length
30+
31+
const header = `${fg.brightCyan}${style.bold}Tasks${style.reset} ${fg.gray}(${completed} done, ${pending} open)${style.reset}`
32+
33+
const lines = [header]
34+
35+
for (const task of tasks) {
36+
const icon = getTaskIcon(task.status)
37+
const description = truncate(sanitize(task.description), 60)
38+
39+
if (task.blockedBy) {
40+
const blockedBy = sanitize(task.blockedBy)
41+
lines.push(` ${icon} ${description} ${fg.yellow}△ blocked by #${blockedBy}${style.reset}`)
42+
} else {
43+
lines.push(` ${icon} ${description}`)
44+
}
45+
}
46+
47+
return lines.join("\n")
48+
}
49+
50+
export function renderAgentTree(agents: AgentStatus[]): string {
51+
if (!agents || agents.length === 0) return ""
52+
53+
const header = `${fg.brightCyan}${style.bold}Agents${style.reset}`
54+
const lines = [header]
55+
56+
for (let i = 0; i < agents.length; i++) {
57+
const agent = agents[i]
58+
const isLast = i === agents.length - 1
59+
const prefix = isLast ? "└─" : "├─"
60+
61+
const name = truncate(sanitize(agent.name), 30)
62+
const activity = truncate(sanitize(agent.activity), 40)
63+
const tokens = formatTokens(safeNum(agent.tokens))
64+
const tools = `${safeNum(agent.toolUses)} tool uses`
65+
66+
const line = `${prefix} ${name}: ${Icons.taskIcon("progress")} ${activity}… · ${tools} · ${tokens}`
67+
lines.push(line)
68+
}
69+
70+
return lines.join("\n")
71+
}
72+
73+
export function renderTaskPanel(tasks: Task[], agents: AgentStatus[]): string {
74+
const taskList = renderTaskList(tasks)
75+
const agentTree = renderAgentTree(agents)
76+
77+
const parts = [taskList, agentTree].filter(Boolean)
78+
return parts.join("\n\n")
79+
}
80+
81+
function getTaskIcon(status: "pending" | "running" | "completed"): string {
82+
const icon = status === "completed" ? "■" : "■"
83+
const color = status === "completed" ? fg.green : status === "running" ? fg.yellow : fg.gray
84+
85+
return `${color}${icon}${style.reset}`
86+
}

‎packages/opencode/src/tool/task.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ const parameters = z.object({
2020
command: z.string().describe("The command that triggered this task").optional(),
2121
})
2222

23-
const MAX_CONCURRENT_TASKS_PER_SESSION = 5
23+
const MAX_CONCURRENT_TASKS_PER_SESSION = 10
2424

2525
type LockCallback = (release: () => void) => void
2626
interface LockState {
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
import { describe, it, expect } from "bun:test"
2+
import type { StatusLineState } from "../../../src/cli/lite/statusline"
3+
import { renderStatusLine } from "../../../src/cli/lite/statusline"
4+
5+
describe("statusline", () => {
6+
it("renders status line with default state", () => {
7+
const state: StatusLineState = {
8+
activity: "Ruminating…",
9+
duration: 15000,
10+
tokens: 342,
11+
tasksVisible: false,
12+
}
13+
14+
const result = renderStatusLine(state)
15+
expect(result).toContain("Ruminating…")
16+
expect(result).toContain("Esc to interrupt")
17+
expect(result).toContain("ctrl+t to show tasks")
18+
expect(result).toContain("15s")
19+
expect(result).toContain("342 tokens")
20+
})
21+
22+
it("shows hide hint when tasks are visible", () => {
23+
const state: StatusLineState = {
24+
activity: "Thinking…",
25+
duration: 5000,
26+
tokens: 100,
27+
tasksVisible: true,
28+
}
29+
30+
const result = renderStatusLine(state)
31+
expect(result).toContain("ctrl+t to hide tasks")
32+
})
33+
34+
it("formats tokens correctly for large numbers", () => {
35+
const state: StatusLineState = {
36+
activity: "Working…",
37+
duration: 30000,
38+
tokens: 5000,
39+
tasksVisible: false,
40+
}
41+
42+
const result = renderStatusLine(state)
43+
expect(result).toContain("5k tokens")
44+
})
45+
46+
it("exports StatusLineState interface", () => {
47+
const state: StatusLineState = {
48+
activity: "Test",
49+
duration: 1000,
50+
tokens: 10,
51+
tasksVisible: false,
52+
}
53+
expect(state.activity).toBe("Test")
54+
})
55+
56+
it("uses cyan color for symbol", () => {
57+
const state: StatusLineState = {
58+
activity: "Test…",
59+
duration: 0,
60+
tokens: 0,
61+
tasksVisible: false,
62+
}
63+
64+
const result = renderStatusLine(state)
65+
expect(result).toContain("\x1b[96m")
66+
})
67+
})

0 commit comments

Comments
 (0)