Skip to content

Commit 14358b5

Browse files
anandgupta42claude
andcommitted
fix: [AI-296] add trace history dialog and /traces command for TUI
- Add `DialogTraceList` component with error/loading states and defensive data handling for corrupted/partial trace files - Add `/traces` slash command to browse all saved trace sessions - Modify `/trace` to fall back to trace history when no active session - Extract `openTraceInBrowser()` helper to eliminate duplicated URL-opening logic - Add sidebar hint for `/traces` command - Add 6 persistence tests using project `tmpdir` fixture (multi-session, isolation, sorting, filename convention, empty state, corrupted files) Closes #225 Closes #296 Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
1 parent 1578470 commit 14358b5

4 files changed

Lines changed: 298 additions & 19 deletions

File tree

‎packages/opencode/src/cli/cmd/tui/app.tsx‎

Lines changed: 43 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ import { PromptHistoryProvider } from "./component/prompt/history"
3030
import { FrecencyProvider } from "./component/prompt/frecency"
3131
import { Tracer } from "@/altimate/observability/tracing"
3232
import { renderTraceViewer } from "@/altimate/observability/viewer"
33+
import { DialogTraceList } from "./component/dialog-trace-list"
3334
import fsAsync from "fs/promises"
3435

3536
// altimate_change start - shared trace viewer server
@@ -265,6 +266,24 @@ function App() {
265266
const exit = useExit()
266267
const promptRef = usePromptRef()
267268

269+
// altimate_change start - shared trace viewer helper
270+
function openTraceInBrowser(sessionID: string) {
271+
try {
272+
const url = getTraceViewerUrl(sessionID)
273+
const openArgs =
274+
process.platform === "darwin"
275+
? ["open", url]
276+
: process.platform === "win32"
277+
? ["cmd", "/c", "start", url]
278+
: ["xdg-open", url]
279+
Bun.spawn(openArgs, { stdout: "ignore", stderr: "ignore" })
280+
toast.show({ variant: "info", message: `Trace viewer: ${url}`, duration: 6000 })
281+
} catch {
282+
toast.show({ variant: "info", message: `Trace files: ${Tracer.getTracesDir()}`, duration: 8000 })
283+
}
284+
}
285+
// altimate_change end
286+
268287
useKeyboard((evt) => {
269288
if (!Flag.OPENCODE_EXPERIMENTAL_DISABLE_COPY_ON_SELECT) return
270289
if (!renderer.getSelection()) return
@@ -653,30 +672,35 @@ function App() {
653672
onSelect: (dialog) => {
654673
const sessionID = route.data.type === "session" ? route.data.sessionID : undefined
655674
if (!sessionID) {
656-
toast.show({ variant: "warning", message: "No active session to trace", duration: 3000 })
657-
dialog.clear()
675+
// No active session — show trace history instead
676+
dialog.replace(() => (
677+
<DialogTraceList onSelect={openTraceInBrowser} />
678+
))
658679
return
659680
}
660-
try {
661-
const url = getTraceViewerUrl(sessionID)
662-
const openArgs = process.platform === "darwin" ? ["open", url] : process.platform === "win32" ? ["cmd", "/c", "start", url] : ["xdg-open", url]
663-
Bun.spawn(openArgs, { stdout: "ignore", stderr: "ignore" })
664-
toast.show({
665-
variant: "info",
666-
message: `Trace viewer: ${url}`,
667-
duration: 6000,
668-
})
669-
} catch (e) {
670-
// Show the trace directory so user can find the file manually
671-
toast.show({
672-
variant: "info",
673-
message: `Trace files: ${Tracer.getTracesDir()}`,
674-
duration: 8000,
675-
})
676-
}
681+
openTraceInBrowser(sessionID)
677682
dialog.clear()
678683
},
679684
},
685+
// altimate_change start - trace history command
686+
{
687+
title: "View trace history",
688+
value: "trace.list",
689+
category: "Debug",
690+
slash: {
691+
name: "traces",
692+
},
693+
onSelect: (dialog) => {
694+
const currentSessionID = route.data.type === "session" ? route.data.sessionID : undefined
695+
dialog.replace(() => (
696+
<DialogTraceList
697+
currentSessionID={currentSessionID}
698+
onSelect={openTraceInBrowser}
699+
/>
700+
))
701+
},
702+
},
703+
// altimate_change end
680704
{
681705
title: "Toggle debug panel",
682706
category: "System",
Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
// altimate_change start - trace history dialog
2+
import { useDialog } from "@tui/ui/dialog"
3+
import { DialogSelect } from "@tui/ui/dialog-select"
4+
import { createMemo, createResource, onMount, Show } from "solid-js"
5+
import { Tracer } from "@/altimate/observability/tracing"
6+
import { Locale } from "@/util/locale"
7+
8+
function formatDuration(ms: number): string {
9+
if (ms < 1000) return `${ms}ms`
10+
if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`
11+
const mins = Math.floor(ms / 60000)
12+
const secs = Math.floor((ms % 60000) / 1000)
13+
return `${mins}m${secs}s`
14+
}
15+
16+
function formatCost(cost: number): string {
17+
if (cost < 0.01) return `$${cost.toFixed(4)}`
18+
return `$${cost.toFixed(2)}`
19+
}
20+
21+
export function DialogTraceList(props: {
22+
currentSessionID?: string
23+
onSelect: (sessionID: string) => void
24+
}) {
25+
const dialog = useDialog()
26+
27+
const [traces] = createResource(async () => {
28+
return Tracer.listTraces()
29+
})
30+
31+
const options = createMemo(() => {
32+
if (traces.state === "errored") {
33+
return [
34+
{
35+
title: "Failed to load traces",
36+
value: "__error__",
37+
description: `Check ${Tracer.getTracesDir()}`,
38+
disabled: true,
39+
},
40+
]
41+
}
42+
43+
const items = traces() ?? []
44+
const today = new Date().toDateString()
45+
46+
return items.slice(0, 50).map((item) => {
47+
const date = new Date(item.trace.startedAt)
48+
let category = date.toDateString()
49+
if (category === today) {
50+
category = "Today"
51+
}
52+
53+
const title = item.trace.metadata?.title || item.trace.metadata?.prompt?.slice(0, 60) || item.sessionId
54+
55+
const summary = item.trace.summary
56+
const status = summary?.status
57+
const statusLabel =
58+
status === "error" || status === "crashed"
59+
? `[${status}] `
60+
: status === "running"
61+
? "[running] "
62+
: ""
63+
64+
const duration = formatDuration(summary?.duration ?? 0)
65+
const cost = formatCost(summary?.totalCost ?? 0)
66+
const tokens = (summary?.totalTokens ?? 0).toLocaleString()
67+
const tools = summary?.totalToolCalls ?? 0
68+
69+
return {
70+
title: `${statusLabel}${title}`,
71+
value: item.sessionId,
72+
category,
73+
footer: `${Locale.time(date.getTime())} · ${duration} · ${tokens} tokens · ${cost} · ${tools} tools`,
74+
}
75+
})
76+
})
77+
78+
onMount(() => {
79+
dialog.setSize("large")
80+
})
81+
82+
return (
83+
<DialogSelect
84+
title={traces.state === "pending" ? "Trace History (loading...)" : "Trace History"}
85+
options={options()}
86+
current={props.currentSessionID}
87+
onSelect={(option) => {
88+
if (option.value === "__error__") return
89+
props.onSelect(option.value)
90+
dialog.clear()
91+
}}
92+
/>
93+
)
94+
}
95+
// altimate_change end

‎packages/opencode/src/cli/cmd/tui/routes/session/sidebar.tsx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,7 @@ export function Sidebar(props: { sessionID: string; overlay?: boolean }) {
114114
<b>Trace</b>
115115
</text>
116116
<text fg={theme.textMuted}>type <span style={{ fg: theme.accent }}>/trace</span> to view</text>
117+
<text fg={theme.textMuted}>type <span style={{ fg: theme.accent }}>/traces</span> for history</text>
117118
</box>
118119
{/* altimate_change end */}
119120
<Show when={mcpEntries().length > 0}>
Lines changed: 159 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,159 @@
1+
import { describe, expect, test } from "bun:test"
2+
import fs from "fs/promises"
3+
import path from "path"
4+
import { Tracer, FileExporter, type TraceFile } from "../../src/altimate/observability/tracing"
5+
import { tmpdir } from "../fixture/fixture"
6+
7+
function makeStepFinish(overrides?: Partial<{ id: string; cost: number }>) {
8+
return {
9+
id: overrides?.id ?? "step-1",
10+
reason: "stop",
11+
cost: overrides?.cost ?? 0.005,
12+
tokens: {
13+
input: 1500,
14+
output: 300,
15+
reasoning: 100,
16+
cache: { read: 200, write: 50 },
17+
},
18+
}
19+
}
20+
21+
describe("Trace persistence across sessions", () => {
22+
test("traces from multiple sessions are all persisted and listable", async () => {
23+
await using tmp = await tmpdir()
24+
const sessions = ["ses_first", "ses_second", "ses_third"]
25+
26+
for (const sessionId of sessions) {
27+
const exporter = new FileExporter(tmp.path)
28+
const tracer = Tracer.withExporters([exporter])
29+
tracer.startTrace(sessionId, {
30+
title: `Session ${sessionId}`,
31+
prompt: `prompt for ${sessionId}`,
32+
})
33+
34+
tracer.logStepStart({ id: "step-1" })
35+
tracer.logStepFinish(makeStepFinish())
36+
await tracer.endTrace()
37+
}
38+
39+
const files = await fs.readdir(tmp.path)
40+
const jsonFiles = files.filter((f) => f.endsWith(".json"))
41+
expect(jsonFiles.length).toBe(3)
42+
43+
const traces = await Tracer.listTraces(tmp.path)
44+
expect(traces.length).toBe(3)
45+
46+
const listedIds = traces.map((t) => t.sessionId)
47+
for (const sessionId of sessions) {
48+
expect(listedIds).toContain(sessionId)
49+
}
50+
51+
for (const { sessionId, trace } of traces) {
52+
expect(trace.metadata.title).toBe(`Session ${sessionId}`)
53+
expect(trace.metadata.prompt).toBe(`prompt for ${sessionId}`)
54+
expect(trace.summary.status).toBe("completed")
55+
}
56+
})
57+
58+
test("ending one session does not affect traces from other sessions", async () => {
59+
await using tmp = await tmpdir()
60+
61+
const exporter1 = new FileExporter(tmp.path)
62+
const tracer1 = Tracer.withExporters([exporter1])
63+
tracer1.startTrace("ses_A", { title: "Session A", prompt: "prompt A" })
64+
tracer1.logStepStart({ id: "step-1" })
65+
tracer1.logStepFinish(makeStepFinish())
66+
await tracer1.endTrace()
67+
68+
let traces = await Tracer.listTraces(tmp.path)
69+
expect(traces.length).toBe(1)
70+
expect(traces[0].sessionId).toBe("ses_A")
71+
72+
const exporter2 = new FileExporter(tmp.path)
73+
const tracer2 = Tracer.withExporters([exporter2])
74+
tracer2.startTrace("ses_B", { title: "Session B", prompt: "prompt B" })
75+
tracer2.logStepStart({ id: "step-1" })
76+
tracer2.logStepFinish(makeStepFinish())
77+
await tracer2.endTrace()
78+
79+
traces = await Tracer.listTraces(tmp.path)
80+
expect(traces.length).toBe(2)
81+
82+
const ids = traces.map((t) => t.sessionId)
83+
expect(ids).toContain("ses_A")
84+
expect(ids).toContain("ses_B")
85+
86+
const traceA = traces.find((t) => t.sessionId === "ses_A")!
87+
expect(traceA.trace.metadata.title).toBe("Session A")
88+
expect(traceA.trace.summary.status).toBe("completed")
89+
})
90+
91+
test("listTraces returns traces sorted by newest first", async () => {
92+
await using tmp = await tmpdir()
93+
94+
for (let i = 0; i < 3; i++) {
95+
const exporter = new FileExporter(tmp.path)
96+
const tracer = Tracer.withExporters([exporter])
97+
tracer.startTrace(`ses_${i}`, { title: `Session ${i}` })
98+
tracer.logStepStart({ id: "step-1" })
99+
tracer.logStepFinish(makeStepFinish())
100+
await tracer.endTrace()
101+
await new Promise((r) => setTimeout(r, 10))
102+
}
103+
104+
const traces = await Tracer.listTraces(tmp.path)
105+
expect(traces.length).toBe(3)
106+
107+
for (let i = 0; i < traces.length - 1; i++) {
108+
const dateA = new Date(traces[i].trace.startedAt).getTime()
109+
const dateB = new Date(traces[i + 1].trace.startedAt).getTime()
110+
expect(dateA).toBeGreaterThanOrEqual(dateB)
111+
}
112+
})
113+
114+
test("traces are individually accessible by session ID filename", async () => {
115+
await using tmp = await tmpdir()
116+
const sessionId = "ses_unique123"
117+
const exporter = new FileExporter(tmp.path)
118+
const tracer = Tracer.withExporters([exporter])
119+
tracer.startTrace(sessionId, { title: "Unique Session", prompt: "test prompt" })
120+
tracer.logStepStart({ id: "step-1" })
121+
tracer.logStepFinish(makeStepFinish())
122+
await tracer.endTrace()
123+
124+
const expectedFile = path.join(tmp.path, `${sessionId}.json`)
125+
const exists = await fs.stat(expectedFile).then(() => true).catch(() => false)
126+
expect(exists).toBe(true)
127+
128+
const content = await fs.readFile(expectedFile, "utf-8")
129+
const trace = JSON.parse(content) as TraceFile
130+
expect(trace.sessionId).toBe(sessionId)
131+
expect(trace.metadata.title).toBe("Unique Session")
132+
expect(trace.summary.totalTokens).toBeGreaterThan(0)
133+
})
134+
135+
test("listTraces returns empty array when no traces exist", async () => {
136+
await using tmp = await tmpdir()
137+
const traces = await Tracer.listTraces(tmp.path)
138+
expect(traces).toEqual([])
139+
})
140+
141+
test("listTraces skips corrupted JSON files gracefully", async () => {
142+
await using tmp = await tmpdir()
143+
144+
// Write a valid trace
145+
const exporter = new FileExporter(tmp.path)
146+
const tracer = Tracer.withExporters([exporter])
147+
tracer.startTrace("ses_valid", { title: "Valid Session" })
148+
tracer.logStepStart({ id: "step-1" })
149+
tracer.logStepFinish(makeStepFinish())
150+
await tracer.endTrace()
151+
152+
// Write a corrupted JSON file
153+
await fs.writeFile(path.join(tmp.path, "corrupted.json"), "not valid json{{{")
154+
155+
const traces = await Tracer.listTraces(tmp.path)
156+
expect(traces.length).toBe(1)
157+
expect(traces[0].sessionId).toBe("ses_valid")
158+
})
159+
})

0 commit comments

Comments
 (0)