opencode-tui-stats 0.0.0-stage → 0.1.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 aifcoding
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.en.md ADDED
@@ -0,0 +1,29 @@
1
+ # opencode-tui-stats
2
+
3
+ A TUI plugin for OpenCode 1.x (v1) that shows a single line — `TPS | AVG | TTFT` — on the right side of the session prompt.
4
+
5
+ ## Demo
6
+
7
+ ![Demo](./assets/demo.gif)
8
+
9
+ ## Installation
10
+
11
+ ```bash
12
+ opencode plugin opencode-tui-stats --global
13
+ ```
14
+
15
+ This command writes the plugin into opencode's TUI config. You can also install the `opencode-tui-stats` package from npm.
16
+
17
+ ## Requirements
18
+
19
+ - opencode ≥ 1.3.14
20
+
21
+ ## Metrics
22
+
23
+ - `TPS`: live generation rate within the most recent ~5-second streaming window (tokens/sec); shows `-` when the session is idle or data is stale.
24
+ - `AVG`: average generation rate of completed messages in this session (tokens/sec).
25
+ - `TTFT`: average time to first token of completed messages in this session (seconds).
26
+
27
+ ## License
28
+
29
+ MIT — see [LICENSE](./LICENSE) in the repository root.
package/README.md CHANGED
@@ -1,3 +1,29 @@
1
- # Temporary Holding Version
1
+ # opencode-tui-stats
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ OpenCode 1.x(v1)的 TUI 插件,在会话提示区右侧显示一行 `TPS | AVG | TTFT`。
4
+
5
+ ## 演示
6
+
7
+ ![Demo](./assets/demo.gif)
8
+
9
+ ## 安装
10
+
11
+ ```bash
12
+ opencode plugin opencode-tui-stats --global
13
+ ```
14
+
15
+ 该命令会把插件写入 opencode 的 tui 配置。也可以从 npm 安装 `opencode-tui-stats` 包。
16
+
17
+ ## 环境要求
18
+
19
+ - opencode ≥ 1.3.14
20
+
21
+ ## 指标说明
22
+
23
+ - `TPS`:最近约 5 秒流式窗口内的实时生成速度(token/秒);会话空闲或数据过期时显示 `-`。
24
+ - `AVG`:本会话已完成消息的平均生成速度(token/秒)。
25
+ - `TTFT`:本会话已完成消息的平均首字延迟(秒)。
26
+
27
+ ## License
28
+
29
+ MIT,详见仓库根目录的 [LICENSE](./LICENSE)。
Binary file
package/package.json CHANGED
@@ -1,6 +1,39 @@
1
1
  {
2
+ "$schema": "https://json.schemastore.org/package.json",
2
3
  "name": "opencode-tui-stats",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
4
+ "version": "0.1.1",
5
+ "description": "OpenCode 1 TUI plugin that shows live TPS, average TPS, and average time to first token in the session prompt.",
6
+ "type": "module",
7
+ "exports": {
8
+ "./tui": {
9
+ "import": "./tui.tsx"
10
+ }
11
+ },
12
+ "engines": {
13
+ "opencode": ">=1.3.14"
14
+ },
15
+ "scripts": {
16
+ "typecheck": "tsc --noEmit",
17
+ "test": "bun test --conditions=browser --preload @opentui/solid/preload"
18
+ },
19
+ "peerDependencies": {
20
+ "@opencode-ai/plugin": ">=1.4.3",
21
+ "@opentui/core": ">=0.4.5",
22
+ "@opentui/solid": ">=0.4.5",
23
+ "solid-js": ">=1.9.0"
24
+ },
25
+ "devDependencies": {
26
+ "@opencode-ai/plugin": "1.18.32",
27
+ "@opentui/core": "0.5.11",
28
+ "@opentui/solid": "0.5.11",
29
+ "@types/bun": "^1.3.14",
30
+ "@types/node": "^24.0.0",
31
+ "solid-js": "^1.9.12",
32
+ "typescript": "^5.9.0"
33
+ },
34
+ "files": [
35
+ "tui.tsx",
36
+ "README.md",
37
+ "assets/"
38
+ ]
39
+ }
package/tui.tsx ADDED
@@ -0,0 +1,249 @@
1
+ /** @jsxImportSource @opentui/solid */
2
+ import type { TuiPlugin, TuiPluginApi, TuiPluginModule } from "@opencode-ai/plugin/tui"
3
+ import { createMemo, createSignal, type Accessor } from "solid-js"
4
+
5
+ type StreamSample = {
6
+ at: number
7
+ tokens: number
8
+ }
9
+
10
+ type MessageTiming = {
11
+ sessionID: string
12
+ requestStartAt: number
13
+ firstResponseAt?: number
14
+ lastToolCallAt?: number
15
+ }
16
+
17
+ type SessionAverage = {
18
+ totalTokens: number
19
+ totalDurationMs: number
20
+ totalTtftMs: number
21
+ stepCount: number
22
+ }
23
+
24
+ type Tracker = {
25
+ samples: Record<string, StreamSample[]>
26
+ timings: Record<string, MessageTiming>
27
+ averages: Record<string, SessionAverage>
28
+ }
29
+
30
+ const STREAM_WINDOW_MS = 5_000
31
+ const LIVE_STALE_MS = 1_500
32
+ const SINGLE_SAMPLE_MS = 1_000
33
+
34
+ function estimateTokens(delta: string) {
35
+ return Math.max(1, Math.ceil(Buffer.byteLength(delta, "utf8") / 5))
36
+ }
37
+
38
+ function formatRate(value: number) {
39
+ if (!Number.isFinite(value) || value <= 0) return undefined
40
+ if (value >= 100) return Math.round(value).toString()
41
+ if (value >= 10) return value.toFixed(1)
42
+ return value.toFixed(2)
43
+ }
44
+
45
+ function formatTtft(value: number) {
46
+ if (!Number.isFinite(value) || value < 0) return undefined
47
+ return `${value.toFixed(1)}s`
48
+ }
49
+
50
+ function activeDuration(samples: StreamSample[], tailAt?: number) {
51
+ if (samples.length === 0) return 0
52
+ if (samples.length === 1) {
53
+ const tailDuration = tailAt ? Math.max(0, tailAt - samples[0].at) : SINGLE_SAMPLE_MS
54
+ return Math.min(Math.max(tailDuration, 250), SINGLE_SAMPLE_MS)
55
+ }
56
+
57
+ let duration = 0
58
+ for (let index = 1; index < samples.length; index++) {
59
+ duration += Math.max(0, samples[index].at - samples[index - 1].at)
60
+ }
61
+ if (tailAt) duration += Math.max(0, tailAt - samples[samples.length - 1].at)
62
+ return Math.max(duration, SINGLE_SAMPLE_MS)
63
+ }
64
+
65
+ function averageRate(average: SessionAverage | undefined) {
66
+ if (!average || average.totalTokens <= 0 || average.totalDurationMs <= 0) return undefined
67
+ return formatRate(average.totalTokens / (average.totalDurationMs / 1_000))
68
+ }
69
+
70
+ function averageTtft(average: SessionAverage | undefined) {
71
+ if (!average || average.stepCount <= 0) return undefined
72
+ return formatTtft(average.totalTtftMs / average.stepCount / 1_000)
73
+ }
74
+
75
+ function liveRate(api: TuiPluginApi, tracker: Tracker, sessionID: string) {
76
+ const status = api.state.session.status(sessionID)
77
+ if (!status || status.type === "idle") return undefined
78
+
79
+ const now = Date.now()
80
+ const samples = (tracker.samples[sessionID] ?? []).filter((sample) => now - sample.at <= STREAM_WINDOW_MS)
81
+ const last = samples[samples.length - 1]
82
+ if (!last || now - last.at > LIVE_STALE_MS) return undefined
83
+
84
+ const tokens = samples.reduce((sum, sample) => sum + sample.tokens, 0)
85
+ return formatRate(tokens / (activeDuration(samples, now) / 1_000))
86
+ }
87
+
88
+ function statusText(api: TuiPluginApi, tracker: Tracker, sessionID: string) {
89
+ const average = tracker.averages[sessionID]
90
+ const live = liveRate(api, tracker, sessionID) ?? "-"
91
+ const avg = averageRate(average) ?? "-"
92
+ const ttft = averageTtft(average) ?? "-"
93
+ return `TPS ${live} | AVG ${avg} | TTFT ${ttft}`
94
+ }
95
+
96
+ function SessionPromptRight(props: {
97
+ api: TuiPluginApi
98
+ sessionID: string
99
+ tracker: Tracker
100
+ revision: Accessor<number>
101
+ }) {
102
+ const content = createMemo(() => {
103
+ props.revision()
104
+ return statusText(props.api, props.tracker, props.sessionID)
105
+ })
106
+
107
+ return <text fg={props.api.theme.current.textMuted}>{content()}</text>
108
+ }
109
+
110
+ const tui: TuiPlugin = async (api) => {
111
+ const tracker: Tracker = {
112
+ samples: {},
113
+ timings: {},
114
+ averages: {},
115
+ }
116
+ const [revision, setRevision] = createSignal(0)
117
+ const bump = () => setRevision((value) => value + 1)
118
+
119
+ const pruneSamples = (now = Date.now()) => {
120
+ let changed = false
121
+
122
+ for (const [sessionID, samples] of Object.entries(tracker.samples)) {
123
+ const next = samples.filter((sample) => now - sample.at <= STREAM_WINDOW_MS)
124
+ if (next.length === samples.length) continue
125
+ changed = true
126
+ if (next.length > 0) tracker.samples[sessionID] = next
127
+ else delete tracker.samples[sessionID]
128
+ }
129
+
130
+ if (changed) bump()
131
+ }
132
+
133
+ const clearLive = (sessionID: string) => {
134
+ if (!tracker.samples[sessionID]?.length) return
135
+ delete tracker.samples[sessionID]
136
+ bump()
137
+ }
138
+
139
+ const appendSample = (sessionID: string, messageID: string, sample: StreamSample) => {
140
+ tracker.samples[sessionID] = [
141
+ ...(tracker.samples[sessionID] ?? []).filter((item) => sample.at - item.at <= STREAM_WINDOW_MS),
142
+ sample,
143
+ ]
144
+ const timing = tracker.timings[messageID]
145
+ if (timing && timing.firstResponseAt === undefined) timing.firstResponseAt = sample.at
146
+ bump()
147
+ }
148
+
149
+ const onDelta = api.event.on("message.part.delta", (event) => {
150
+ if (event.properties.field !== "text") return
151
+ const part = api.state.part(event.properties.messageID).find((item) => item.id === event.properties.partID)
152
+ if (!part || (part.type !== "text" && part.type !== "reasoning")) return
153
+ appendSample(event.properties.sessionID, event.properties.messageID, {
154
+ at: Date.now(),
155
+ tokens: estimateTokens(event.properties.delta),
156
+ })
157
+ })
158
+
159
+ const onMessage = api.event.on("message.updated", (event) => {
160
+ const info = event.properties.info
161
+ if (info.role !== "assistant") return
162
+ const sessionID = event.properties.sessionID
163
+
164
+ if (!info.time.completed) {
165
+ const existing = tracker.timings[info.id]
166
+ tracker.timings[info.id] = {
167
+ sessionID,
168
+ requestStartAt: info.time.created,
169
+ firstResponseAt: existing?.firstResponseAt,
170
+ lastToolCallAt: existing?.lastToolCallAt,
171
+ }
172
+ bump()
173
+ return
174
+ }
175
+
176
+ const timing = tracker.timings[info.id]
177
+ if (timing?.sessionID === sessionID && timing.firstResponseAt !== undefined) {
178
+ const tokens = info.tokens.output + info.tokens.reasoning
179
+ const endAt = info.finish === "tool-calls" ? timing.lastToolCallAt : info.time.completed
180
+ const durationMs = endAt !== undefined ? Math.max(endAt - timing.firstResponseAt, 1) : undefined
181
+ if (tokens > 0 && durationMs !== undefined) {
182
+ const totals = tracker.averages[sessionID] ?? {
183
+ totalTokens: 0,
184
+ totalDurationMs: 0,
185
+ totalTtftMs: 0,
186
+ stepCount: 0,
187
+ }
188
+ tracker.averages[sessionID] = {
189
+ totalTokens: totals.totalTokens + tokens,
190
+ totalDurationMs: totals.totalDurationMs + durationMs,
191
+ totalTtftMs: totals.totalTtftMs + Math.max(timing.firstResponseAt - timing.requestStartAt, 0),
192
+ stepCount: totals.stepCount + 1,
193
+ }
194
+ }
195
+ }
196
+ delete tracker.timings[info.id]
197
+ pruneSamples(info.time.completed)
198
+ bump()
199
+ })
200
+
201
+ const onPart = api.event.on("message.part.updated", (event) => {
202
+ const part = event.properties.part
203
+ if (part.type !== "tool") return
204
+
205
+ if (part.state.status === "running" || part.state.status === "completed" || part.state.status === "error") {
206
+ clearLive(part.sessionID)
207
+ }
208
+
209
+ const timing = tracker.timings[part.messageID]
210
+ if (!timing) return
211
+
212
+ if (part.state.status === "pending") {
213
+ if (timing.firstResponseAt === undefined) timing.firstResponseAt = event.properties.time
214
+ bump()
215
+ return
216
+ }
217
+ if (part.state.status === "running") {
218
+ timing.lastToolCallAt = part.state.time.start
219
+ bump()
220
+ }
221
+ })
222
+
223
+ const timer = setInterval(() => {
224
+ pruneSamples()
225
+ bump()
226
+ }, 1_000)
227
+
228
+ api.lifecycle.onDispose(() => {
229
+ onDelta()
230
+ onMessage()
231
+ onPart()
232
+ clearInterval(timer)
233
+ })
234
+
235
+ api.slots.register({
236
+ slots: {
237
+ session_prompt_right(_context, props) {
238
+ return <SessionPromptRight api={api} sessionID={props.session_id} tracker={tracker} revision={revision} />
239
+ },
240
+ },
241
+ })
242
+ }
243
+
244
+ const plugin: TuiPluginModule = {
245
+ id: "opencode-tui-stats",
246
+ tui,
247
+ }
248
+
249
+ export default plugin