oc-metricboard 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,137 @@
1
+ # oc-metricboard
2
+
3
+ OpenCode TUI sidebar plugin for real-time LLM metrics (TPS / TTFT / token usage) with **sub-agent aggregation** and **per-model breakdown**.
4
+
5
+ Based on [opencode-metrics](https://github.com/nxxxsooo/opencode-metrics) with a streamlined display, sub-agent × model grouping, and production-hardening fixes.
6
+
7
+ ## Features
8
+
9
+ - **Real-time TPS** — live rolling-window rate while streaming, frozen average on completion (sanity-gated against absurd values)
10
+ - **TTFT** — time to first token, anchored to the user message (not the lazy `step.started` event)
11
+ - **Token usage** — exact input/output counts from provider (estimated fallback)
12
+ - **Sub-agent aggregation** (`scope: "tree"`) — merges all descendant sub-agent sessions
13
+ - **Per-model breakdown** — one row per distinct model with `×N` session count
14
+ - **Collapsed quick-view** — keeps a compact TPS + Session summary while collapsed
15
+ - **Compact layout** — no vertical gaps, no value truncation in narrow sidebars
16
+
17
+ ### Display
18
+
19
+ ```
20
+ ▼ MetricBoard
21
+ TPS ⚡ 116.9 t/s
22
+ Elapsed ▹ 1m5s
23
+ TTFT ⏱ 57.8s
24
+ Tokens ↓ 603.1K in ↑ 3.9K out
25
+ Session ◷ 1m49s
26
+
27
+ deepseek-v4-flash
28
+ ⚡116.9 ⏱7.8s ↓595.9K ↑902
29
+ mimo-v2.5-free ×4
30
+ ⚡67.3 ⏱2.1s ↓78.3K ↑5.0K
31
+ ```
32
+
33
+ ## Installation
34
+
35
+ ### From npm (after publishing)
36
+
37
+ ```bash
38
+ opencode plugin oc-metricboard --global
39
+ ```
40
+
41
+ or add to your config:
42
+
43
+ ```json
44
+ {
45
+ "plugin": ["oc-metricboard"]
46
+ }
47
+ ```
48
+
49
+ ### Local development (tarball)
50
+
51
+ ```json
52
+ {
53
+ "plugin": ["file:///absolute/path/to/oc-metricboard-0.1.4.tgz"]
54
+ }
55
+ ```
56
+
57
+ Restart OpenCode TUI afterwards. Plugins load at TUI startup and are not hot-reloaded.
58
+
59
+ ## Configuration
60
+
61
+ Preferences live in `~/.config/opencode/tui-preferences.jsonc` under the `oc-metricboard` key:
62
+
63
+ ```jsonc
64
+ {
65
+ "oc-metricboard": {
66
+ "scope": "tree", // "current" | "tree" — tree enables sub-agent aggregation
67
+ "section": {
68
+ "enabled": true,
69
+ "collapsed": false,
70
+ "rememberCollapsed": true,
71
+ "label": "MetricBoard"
72
+ },
73
+ "rows": {
74
+ "tps": true, // TPS row (renamed from "speed")
75
+ "ttft": true, // Time to first token
76
+ "input": true, // Input tokens
77
+ "output": true, // Output tokens
78
+ "cache": false, // Cache read tokens (off by default)
79
+ "elapsed": true, // Request elapsed time
80
+ "session": true, // Session cumulative time
81
+ "modelBreakdown": true // Per-model rows in tree scope
82
+ }
83
+ }
84
+ }
85
+ ```
86
+
87
+ Runtime behavior (`refreshIntervalMs`, `holdDurationMs`, `estimationRatio`, `enableLogging`) is read from `~/.config/opencode/opencode-bar.json`:
88
+
89
+ ```jsonc
90
+ {
91
+ "refreshIntervalMs": 200,
92
+ "holdDurationMs": 0,
93
+ "estimationRatio": 4.0,
94
+ "enableLogging": false
95
+ }
96
+ ```
97
+
98
+ ## How it works
99
+
100
+ The plugin subscribes to OpenCode events:
101
+
102
+ - `session.created/updated/status` — builds the session tree
103
+ - `message.part.delta`, `session.next.text.delta` — live token estimation and TPS window
104
+ - `session.next.step.started/ended` — exact token counts from provider
105
+ - `message.updated` — model attribution and exact counts
106
+ - `session.idle` — request completion
107
+
108
+ For **tree scope** it additionally:
109
+
110
+ 1. Queries `session.children` (SDK client) to build the sub-agent hierarchy
111
+ 2. Hydrates descendant sessions via the async SDK client (`session.messages` / `session.status`)
112
+ 3. Groups requests by `(modelID, providerID)`, summing tokens and pooling sessions into a `×N` count
113
+ 4. Renders one compact two-line entry per model group
114
+
115
+ ### Design notes
116
+
117
+ - **Aggregate cache** (150 ms TTL): multiple sidebar rows share one aggregation pass per render tick to avoid redundant O(tree) work and UI jank.
118
+ - **TTFT anchor**: uses the preceding user message's created time — opencode 1.18.x stamps `step.started` lazily at the first token, which would otherwise collapse TTFT to ~0.
119
+ - **Timing sanity**: negative timestamps (from hydrating messages older than the TUI process) and implausible spans are reported as `--`, not garbage numbers.
120
+ - **Hydration bounds**: at most 5 attempts per session; a session with no token history is not retried forever.
121
+
122
+ ## Development
123
+
124
+ ```bash
125
+ npm install
126
+ npm run build # tsup bundle check
127
+ npm test # bun test (requires bun)
128
+ npm pack --dry-run # verify publish contents
129
+ ```
130
+
131
+ ## Credits
132
+
133
+ Forked from [opencode-metrics](https://github.com/nxxxsooo/opencode-metrics) by nxxxsooo, itself a rewrite of [Icicno/opencodeBar](https://github.com/Icicno/opencodeBar).
134
+
135
+ ## License
136
+
137
+ MIT
package/package.json ADDED
@@ -0,0 +1,92 @@
1
+ {
2
+ "name": "oc-metricboard",
3
+ "version": "0.1.4",
4
+ "description": "OpenCode TUI sidebar plugin showing real-time LLM metrics (TPS, TTFT, tokens) with sub-agent × model breakdown",
5
+ "keywords": [
6
+ "opencode",
7
+ "opencode-plugin",
8
+ "tui",
9
+ "metrics",
10
+ "tps",
11
+ "ttft",
12
+ "tokens",
13
+ "monitoring",
14
+ "sub-agent",
15
+ "llm"
16
+ ],
17
+ "license": "MIT",
18
+ "repository": {
19
+ "type": "git",
20
+ "url": "git+https://github.com/JasonJason-oy/oc-metricboard.git"
21
+ },
22
+ "bugs": {
23
+ "url": "https://github.com/JasonJason-oy/oc-metricboard/issues"
24
+ },
25
+ "homepage": "https://github.com/JasonJason-oy/oc-metricboard#readme",
26
+ "engines": {
27
+ "opencode": ">=1.14.22",
28
+ "node": ">=20.11"
29
+ },
30
+ "type": "module",
31
+ "main": "./src/tui.tsx",
32
+ "exports": {
33
+ ".": {
34
+ "import": "./src/tui.tsx"
35
+ },
36
+ "./tui": {
37
+ "import": "./src/tui.tsx"
38
+ }
39
+ },
40
+ "oc-plugin": [
41
+ "tui"
42
+ ],
43
+ "files": [
44
+ "src/tui.tsx",
45
+ "src/tui-preferences.ts",
46
+ "src/tui-prefs-io.ts",
47
+ "src/badge-contrast.ts",
48
+ "src/assistant-progress.ts",
49
+ "src/collector.ts",
50
+ "src/collector-state.ts",
51
+ "src/config.ts",
52
+ "src/event-bus.ts",
53
+ "src/event-handlers.ts",
54
+ "src/logger.ts",
55
+ "src/metrics.ts",
56
+ "src/live-speed.ts",
57
+ "src/turn-state.ts",
58
+ "src/request-state.ts",
59
+ "src/request-updates.ts",
60
+ "src/session-hydration.ts",
61
+ "src/session-timing.ts",
62
+ "src/session-tree.ts",
63
+ "src/types.ts",
64
+ "src/event-shapes.ts",
65
+ "src/components/SidebarMetrics.tsx",
66
+ "src/components/StatRow.tsx",
67
+ "src/scripts/init-tui-preferences.ts",
68
+ "README.md"
69
+ ],
70
+ "scripts": {
71
+ "test": "bun test",
72
+ "init:prefs": "OPENCODE_TUI_PREFERENCES_FILE=${OPENCODE_TUI_PREFERENCES_FILE:-$HOME/.config/opencode/tui-preferences.jsonc} bun run src/scripts/init-tui-preferences.ts",
73
+ "prepublishOnly": "npm pack --dry-run"
74
+ },
75
+ "devDependencies": {
76
+ "@opencode-ai/plugin": "1.18.4",
77
+ "@opencode-ai/sdk": "1.18.4",
78
+ "@types/bun": "latest",
79
+ "tsup": "^8.0.0",
80
+ "typescript": "^5.0.0"
81
+ },
82
+ "dependencies": {
83
+ "@opentui/core": "0.4.5",
84
+ "@opentui/solid": "0.4.5",
85
+ "comment-json": "^5.0.0",
86
+ "solid-js": "^1.9.12"
87
+ },
88
+ "peerDependencies": {
89
+ "@opencode-ai/plugin": "*",
90
+ "@opencode-ai/sdk": "*"
91
+ }
92
+ }
@@ -0,0 +1,99 @@
1
+ import { estimateTokens } from "./metrics"
2
+ import { parseAssistantTextDelta } from "./event-shapes"
3
+ import { currentRequest } from "./request-state"
4
+ import { eventAggregateID, eventID, eventProperties, stringEventProperty } from "./event-bus"
5
+ import type { EventHandlerContext } from "./collector-state"
6
+ import { recordLiveTokens } from "./live-speed"
7
+
8
+ export interface AssistantProgressPart {
9
+ readonly partID: string
10
+ readonly messageID: string
11
+ readonly text: string
12
+ }
13
+
14
+ function partEstimateKey(sessionID: string, messageID: string, partID: string): string {
15
+ return `${sessionID}:${messageID}:${partID}`
16
+ }
17
+
18
+ function applyTokenDelta(
19
+ ctx: EventHandlerContext,
20
+ sessionID: string,
21
+ messageID: string,
22
+ deltaTokens: number,
23
+ now: number,
24
+ ): void {
25
+ const { actions, state } = ctx
26
+ if (state.turns.get(sessionID)?.finalizedSteps.has(messageID)) return
27
+ const current = currentRequest({ state, actions, sessionID, messageID, now })
28
+ if (current.firstTokenTime === null) current.firstTokenTime = now
29
+ if (deltaTokens > 0) {
30
+ current.estimatedOutputTokens += deltaTokens
31
+ current.lastDeltaTime = now
32
+ recordLiveTokens(state.liveSpeeds, sessionID, messageID, deltaTokens, now)
33
+ }
34
+ current.isStreaming = true
35
+ actions.notify()
36
+ }
37
+
38
+ function applyAssistantText(
39
+ ctx: EventHandlerContext,
40
+ sessionID: string,
41
+ messageID: string,
42
+ partID: string,
43
+ text: string,
44
+ now: number,
45
+ ): void {
46
+ const { actions, config, state } = ctx
47
+ const key = partEstimateKey(sessionID, messageID, partID)
48
+ const nextTokens = estimateTokens(text, config.estimationRatio)
49
+ const previousTokens = state.partTokenEstimates.get(key) ?? 0
50
+ const deltaTokens = Math.max(0, nextTokens - previousTokens)
51
+ state.partTokenEstimates.set(key, Math.max(previousTokens, nextTokens))
52
+ applyTokenDelta(ctx, sessionID, messageID, deltaTokens, now)
53
+ }
54
+
55
+ export function applyAssistantProgress(
56
+ ctx: EventHandlerContext,
57
+ sessionID: string,
58
+ part: AssistantProgressPart,
59
+ now: number,
60
+ ): void {
61
+ applyAssistantText(ctx, sessionID, part.messageID, part.partID, part.text, now)
62
+ }
63
+
64
+ export function applyAssistantDelta(ctx: EventHandlerContext, event: unknown): void {
65
+ const { actions, state } = ctx
66
+ const sessionID = stringEventProperty(event, "sessionID")
67
+ const fallbackMessageID = sessionID.length > 0 ? state.assistantMessageIds.get(sessionID) ?? eventID(event) : eventID(event)
68
+ const text = parseAssistantTextDelta(eventProperties(event), fallbackMessageID)
69
+ if (!text) return
70
+ const aggregateID = eventAggregateID(event)
71
+ if (aggregateID.length > 0 && aggregateID !== text.sessionID) {
72
+ const aggregateAliases = state.sessionAliases.get(aggregateID) ?? new Set<string>()
73
+ aggregateAliases.add(text.sessionID)
74
+ state.sessionAliases.set(aggregateID, aggregateAliases)
75
+ const sessionAliases = state.sessionAliases.get(text.sessionID) ?? new Set<string>()
76
+ sessionAliases.add(aggregateID)
77
+ state.sessionAliases.set(text.sessionID, sessionAliases)
78
+ }
79
+ const now = performance.now()
80
+ actions.startSessionTiming(text.sessionID, now)
81
+ const key = partEstimateKey(text.sessionID, text.messageID, text.partID)
82
+ const deltaTokens = estimateTokens(text.delta, ctx.config.estimationRatio)
83
+ state.partTokenEstimates.set(key, (state.partTokenEstimates.get(key) ?? 0) + deltaTokens)
84
+ applyTokenDelta(ctx, text.sessionID, text.messageID, deltaTokens, now)
85
+ }
86
+
87
+ export function applyAssistantPartDelta(
88
+ ctx: EventHandlerContext,
89
+ sessionID: string,
90
+ messageID: string,
91
+ partID: string,
92
+ delta: string,
93
+ now: number,
94
+ ): void {
95
+ const key = partEstimateKey(sessionID, messageID, partID)
96
+ const deltaTokens = estimateTokens(delta, ctx.config.estimationRatio)
97
+ ctx.state.partTokenEstimates.set(key, (ctx.state.partTokenEstimates.get(key) ?? 0) + deltaTokens)
98
+ applyTokenDelta(ctx, sessionID, messageID, deltaTokens, now)
99
+ }
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Pick the text color for the sidebar header badge (a bold label drawn on a
3
+ * `theme.accent` background).
4
+ *
5
+ * Primary rule: paint the theme's own `background` color as the label, giving
6
+ * the inverse-of-panel look consistent with other sidebar plugins.
7
+ *
8
+ * Fallback rule: `theme.background` can be unusable as a label color when:
9
+ * 1. Transparent background (alpha < 0.5). Drawing transparent text on the
10
+ * accent renders the label invisible.
11
+ * 2. Background ~= accent (per-channel distance < 0.06). No contrast.
12
+ * In either case we fall back to a black/white pick by accent luminance.
13
+ *
14
+ * Accepts the minimal `{ r, g, b, a? }` shape so this stays a pure, trivially
15
+ * testable function independent of the native color class.
16
+ */
17
+
18
+ export type Color = { r: number; g: number; b: number; a?: number }
19
+
20
+ const MIN_OPAQUE_ALPHA = 0.5
21
+ const MIN_CHANNEL_DISTANCE = 0.06
22
+ const LIGHT_ACCENT_LUMINANCE = 0.5
23
+
24
+ function srgbChannelToLinear(c: number): number {
25
+ return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4
26
+ }
27
+
28
+ function relativeLuminance(bg: Color): number {
29
+ return (
30
+ 0.2126 * srgbChannelToLinear(bg.r) +
31
+ 0.7152 * srgbChannelToLinear(bg.g) +
32
+ 0.0722 * srgbChannelToLinear(bg.b)
33
+ )
34
+ }
35
+
36
+ function nearlyEqual(a: Color, b: Color): boolean {
37
+ return (
38
+ Math.abs(a.r - b.r) < MIN_CHANNEL_DISTANCE &&
39
+ Math.abs(a.g - b.g) < MIN_CHANNEL_DISTANCE &&
40
+ Math.abs(a.b - b.b) < MIN_CHANNEL_DISTANCE
41
+ )
42
+ }
43
+
44
+ /**
45
+ * Pure black/white pick by accent luminance. Used as the badge fallback.
46
+ */
47
+ export function readableTextColorOn(bg: Color): string {
48
+ return relativeLuminance(bg) < LIGHT_ACCENT_LUMINANCE ? "#ffffff" : "#000000"
49
+ }
50
+
51
+ /**
52
+ * Badge label color on the accent: the theme background when it is usable,
53
+ * else a guaranteed-visible black/white fallback. Returns the passed-in
54
+ * `background` reference unchanged on the primary path.
55
+ */
56
+ export function badgeTextColor<T extends Color>(accent: T, background: T): T | string {
57
+ const alpha = background.a ?? 1
58
+ if (alpha >= MIN_OPAQUE_ALPHA && !nearlyEqual(accent, background)) {
59
+ return background
60
+ }
61
+ return readableTextColorOn(accent)
62
+ }
@@ -0,0 +1,36 @@
1
+ import type { BarConfig, LiveSpeedState, RequestMetrics, TurnMetrics } from "./types"
2
+ import type { SessionTree } from "./session-tree"
3
+ import type { MetricsEventApi } from "./event-bus"
4
+ import type { SessionTiming } from "./session-timing"
5
+
6
+ export interface CollectorState {
7
+ requests: Map<string, RequestMetrics>
8
+ turns: Map<string, TurnMetrics>
9
+ liveSpeeds: Map<string, LiveSpeedState>
10
+ holdTimers: Map<string, ReturnType<typeof setTimeout>>
11
+ sessionTree: SessionTree
12
+ sessionModels: Map<string, { readonly modelID: string; readonly providerID: string }>
13
+ sessionTimings: Map<string, SessionTiming>
14
+ userMessageIds: Map<string, Set<string>>
15
+ assistantMessageIds: Map<string, string>
16
+ partTokenEstimates: Map<string, number>
17
+ sessionAliases: Map<string, Set<string>>
18
+ seenEventKeys: Set<string>
19
+ seenEventOrder: string[]
20
+ lastRequestSessionID: string | null
21
+ }
22
+
23
+ export interface CollectorActions {
24
+ notify: () => void
25
+ startSessionTiming: (sessionID: string, now: number) => void
26
+ stopSessionTiming: (sessionID: string, now: number) => void
27
+ clearHoldTimer: (sessionID: string) => void
28
+ }
29
+
30
+ export interface EventHandlerContext {
31
+ readonly api: MetricsEventApi
32
+ readonly config: BarConfig
33
+ readonly log: (msg: string) => void
34
+ readonly state: CollectorState
35
+ readonly actions: CollectorActions
36
+ }