@troed/oc-ls-stats 1.0.3
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/.npmrc.tmp +2 -0
- package/README.md +111 -0
- package/package.json +20 -0
- package/tui.tsx +525 -0
package/.npmrc.tmp
ADDED
package/README.md
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
# oc-ls-stats
|
|
2
|
+
|
|
3
|
+
A TUI plugin for OpenCode that displays live prefill rate (PP) and generation rate (TG) from a llama.cpp-based llama-server.
|
|
4
|
+
|
|
5
|
+
There are many plugins to show tokens per second, but the reason for this one is that when running a local model I often found myself not knowing what the server was currently doing, which meant constantly switching over to a console where I could see its output. Especially during prefill/prompt processing which can take more than a minute with no feedback in the UI from other plugins I tried.
|
|
6
|
+
|
|
7
|
+
Another motivation was to display the data of interest, but in a non-intrusive way with no UI elements jumping around. This plugin thus only shows a single numeric value, tokens per second, with an indicator as to whether the model is currently doing prompt processing or inference (token generation).
|
|
8
|
+
|
|
9
|
+
I'm using the llama-server /slots endpoint to get the needed data, which means if you connect opencode to another provider the plugin will just display "-" since it's not getting any data to display.
|
|
10
|
+
|
|
11
|
+
Note: As explained in further detail below the data that's displayed has to be deduced from llama-server's output. Sometimes the plugin might display PP for prompt processing while in reality the model is doing TG. If additional developments are made to the llama-server output data the plugin might be able to discern between them in a better way, but I think is as good as it gets for now.
|
|
12
|
+
|
|
13
|
+
I made this for my own usage. If you find it useful as well I'm just happy.
|
|
14
|
+
|
|
15
|
+
/Troed
|
|
16
|
+
|
|
17
|
+
_thanks to Tarquinen for their [oc-tps](https://github.com/Tarquinen/oc-tps), which I used as a base although I guess most of the code has now been replaced_
|
|
18
|
+
|
|
19
|
+
## Display Format
|
|
20
|
+
|
|
21
|
+
The plugin renders a single line in the session prompt right slot:
|
|
22
|
+
|
|
23
|
+
```
|
|
24
|
+
1247 tps (PP) -- during prefill
|
|
25
|
+
25 tps (TG) -- during generation
|
|
26
|
+
- tps (TG) -- idle
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## Detection and Calculation
|
|
30
|
+
|
|
31
|
+
### Server Discovery
|
|
32
|
+
|
|
33
|
+
The plugin discovers the llama-server URL by reading the OpenCode configuration file (parsed as JSONC) and extracting `baseURL`/`base_url` fields from provider options that contain "localhost". Falls back to `http://localhost:8080`.
|
|
34
|
+
|
|
35
|
+
### Slot Polling
|
|
36
|
+
|
|
37
|
+
Every 500ms, the plugin polls `GET /slots?model=<model>` on each discovered server. The model parameter is required by the `/slots` endpoint. If the model cannot be discovered from the current route's session, the plugin skips polling.
|
|
38
|
+
|
|
39
|
+
### State Classification
|
|
40
|
+
|
|
41
|
+
Each slot is classified as prefill or generation based on the `n_decoded` counter in `next_token[0]`. The plugin tracks a per-slot baseline value:
|
|
42
|
+
|
|
43
|
+
1. When a slot first appears as processing, the current `n_decoded` is recorded as the baseline with `hasIncreased = false`.
|
|
44
|
+
2. If `n_decoded <= baseline` and `hasIncreased` is false, the slot is classified as prefilling.
|
|
45
|
+
3. If `n_decoded > baseline`, `hasIncreased` is set to true and the slot is classified as generating.
|
|
46
|
+
|
|
47
|
+
This approach handles the case where `n_decoded` drops when a new request starts on a reused slot, and prevents generation stalls (where `n_decoded` plateaus) from being misclassified as prefill.
|
|
48
|
+
|
|
49
|
+
When no slots are processing, all tracked state for those slots is cleared.
|
|
50
|
+
|
|
51
|
+
### Prefill Rate (PP)
|
|
52
|
+
|
|
53
|
+
During prefill, the plugin calculates the instantaneous prompt processing rate:
|
|
54
|
+
|
|
55
|
+
1. On first detection of a prefill slot, the current `n_prompt_tokens` is captured as the baseline.
|
|
56
|
+
2. On subsequent polls, the delta in `n_prompt_tokens` is divided by the elapsed time in seconds.
|
|
57
|
+
3. The rate is updated only when both `dt > 0` and `delta > 0`.
|
|
58
|
+
|
|
59
|
+
The per-slot `n_prompt_tokens` field is used instead of the global `llamacpp:prompt_tokens_total` from `/metrics` because the global counter includes tokens from all slots, producing inflated values when multiple slots are active simultaneously.
|
|
60
|
+
|
|
61
|
+
### Generation Rate (TG)
|
|
62
|
+
|
|
63
|
+
During generation, the plugin calculates the instantaneous token generation rate:
|
|
64
|
+
|
|
65
|
+
1. On first detection of a generation slot, the current `n_decoded` is captured as the baseline.
|
|
66
|
+
2. On subsequent polls (same slot ID), the delta in `n_decoded` is divided by the elapsed time in seconds.
|
|
67
|
+
3. The rate is updated only when both `dt > 0` and `delta > 0`.
|
|
68
|
+
|
|
69
|
+
Slot reuse is tracked via `generateSlotId` to detect when a new generation starts on a different slot.
|
|
70
|
+
|
|
71
|
+
## Limitations
|
|
72
|
+
|
|
73
|
+
### Progress Percentage
|
|
74
|
+
|
|
75
|
+
The plugin cannot display prefill progress percentage. The `/slots` endpoint returns `n_prompt_tokens` (current prompt size) and `n_prompt_tokens_processed` (tokens processed), but not the final prompt size (`task->n_tokens()` from llama.cpp). Progress requires the ratio `n_prompt_tokens_processed / task->n_tokens()`.
|
|
76
|
+
|
|
77
|
+
### What Would Improve Compatibility
|
|
78
|
+
|
|
79
|
+
The following changes to the `/slots` endpoint would improve the plugin's functionality:
|
|
80
|
+
|
|
81
|
+
1. **Expose final prompt size**: Add `n_prompt_tokens_total` (or `n_tokens`) to the `/slots` output, representing `task->n_tokens()` from llama.cpp. This would enable prefill progress percentage calculation as `(n_prompt_tokens_processed / n_prompt_tokens_total) * 100`.
|
|
82
|
+
|
|
83
|
+
2. **Per-slot metrics endpoints**: Currently, the `/metrics` endpoint provides only global counters (`llamacpp:prompt_tokens_total`, `llamacpp:prompt_tokens_seconds`). Per-slot metrics would allow independent rate tracking without relying on slot state classification.
|
|
84
|
+
|
|
85
|
+
3. **Slot transition notifications**: The plugin polls every 500ms to detect state transitions. A WebSocket or SSE-based notification system for slot state changes would reduce polling overhead and improve detection latency.
|
|
86
|
+
|
|
87
|
+
4. **Stall detection**: When generation stalls (e.g., due to context window limits), `n_decoded` remains constant while `n_remain` stops decreasing. The plugin detects this via zero delta but has no way to distinguish a stall from normal generation. An explicit `stalled` flag in the slot output would help.
|
|
88
|
+
|
|
89
|
+
5. **Model-agnostic slot data**: The `/slots` endpoint requires a model parameter. Returning all slots without model filtering, or supporting `*` as a wildcard, would simplify discovery when multiple models are loaded.
|
|
90
|
+
|
|
91
|
+
## Installation
|
|
92
|
+
|
|
93
|
+
```bash
|
|
94
|
+
opencode plugin @troed/oc-ls-stats@latest --global
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
Requires `opencode` `1.3.14` or newer.
|
|
98
|
+
|
|
99
|
+
TUI plugins are loaded from `~/.config/opencode/tui.json`:
|
|
100
|
+
|
|
101
|
+
```json
|
|
102
|
+
{"plugin": ["@troed/oc-ls-stats@latest"]}
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
## Debug Logging
|
|
106
|
+
|
|
107
|
+
Debug logging is controlled by the `DEBUG_ENABLED` constant in `tui.tsx`. When enabled, full slot state data is written to `/tmp/oc-ls-stats-debug.log` on every poll.
|
|
108
|
+
|
|
109
|
+
## License
|
|
110
|
+
|
|
111
|
+
Creative Commons Zero (CC0 1.0 Universal)
|
package/package.json
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://json.schemastore.org/package.json",
|
|
3
|
+
"name": "@troed/oc-ls-stats",
|
|
4
|
+
"version": "1.0.3",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"exports": {
|
|
7
|
+
"./tui": {
|
|
8
|
+
"import": "./tui.tsx"
|
|
9
|
+
}
|
|
10
|
+
},
|
|
11
|
+
"engines": {
|
|
12
|
+
"opencode": ">=1.3.14"
|
|
13
|
+
},
|
|
14
|
+
"peerDependencies": {
|
|
15
|
+
"@opencode-ai/plugin": "*",
|
|
16
|
+
"@opentui/core": "*",
|
|
17
|
+
"@opentui/solid": "*",
|
|
18
|
+
"solid-js": "*"
|
|
19
|
+
}
|
|
20
|
+
}
|
package/tui.tsx
ADDED
|
@@ -0,0 +1,525 @@
|
|
|
1
|
+
/** @jsxImportSource @opentui/solid */
|
|
2
|
+
import type { TuiPlugin, TuiPluginModule } from "@opencode-ai/plugin/tui"
|
|
3
|
+
import { createMemo, createSignal } from "solid-js"
|
|
4
|
+
import { appendFileSync } from "fs"
|
|
5
|
+
|
|
6
|
+
const DEBUG_ENABLED = false
|
|
7
|
+
const DEBUG_LOG = "/tmp/oc-ls-stats-debug.log"
|
|
8
|
+
function debug(...args: unknown[]) {
|
|
9
|
+
if (!DEBUG_ENABLED) return
|
|
10
|
+
try {
|
|
11
|
+
const line = `${args.map(a => typeof a === "object" ? JSON.stringify(a) : String(a)).join(" ")}\n`
|
|
12
|
+
appendFileSync(DEBUG_LOG, line)
|
|
13
|
+
} catch {}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
type StreamSample = {
|
|
17
|
+
at: number
|
|
18
|
+
tokens: number
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const STREAM_WINDOW_MS = 5_000
|
|
22
|
+
const SLOT_POLL_MS = 500
|
|
23
|
+
type MessageTiming = {
|
|
24
|
+
sessionID: string
|
|
25
|
+
requestStartAt: number
|
|
26
|
+
firstResponseAt?: number
|
|
27
|
+
firstTokenAt?: number
|
|
28
|
+
lastTokenAt?: number
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
type TrackerState = {
|
|
32
|
+
streamSamplesBySession: Record<string, StreamSample[]>
|
|
33
|
+
messageTimingByID: Record<string, MessageTiming>
|
|
34
|
+
lastPrefillRate: number
|
|
35
|
+
lastGeneratedTps: number
|
|
36
|
+
isPrefilling: boolean
|
|
37
|
+
prefillSlotId: number | null
|
|
38
|
+
prefillCapturedTokens: number | null
|
|
39
|
+
prefillStartAt: number
|
|
40
|
+
isGenerating: boolean
|
|
41
|
+
generateSlotId: number | null
|
|
42
|
+
generatePrevNd: number
|
|
43
|
+
generateStartAt: number
|
|
44
|
+
prevNdBySlot: Record<number, { baseline: number; hasIncreased: boolean }>
|
|
45
|
+
failure: string | null
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function estimateStreamTokens(delta: string) {
|
|
49
|
+
return Math.max(1, Math.ceil(Buffer.byteLength(delta, "utf8") / 5))
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function parseJSONC(text: string): unknown {
|
|
53
|
+
let result = ""
|
|
54
|
+
let inString = false
|
|
55
|
+
let escape = false
|
|
56
|
+
let i = 0
|
|
57
|
+
|
|
58
|
+
while (i < text.length) {
|
|
59
|
+
const ch = text[i]
|
|
60
|
+
|
|
61
|
+
if (escape) {
|
|
62
|
+
result += ch
|
|
63
|
+
escape = false
|
|
64
|
+
i++
|
|
65
|
+
continue
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
if (ch === "\\") {
|
|
69
|
+
result += ch
|
|
70
|
+
escape = true
|
|
71
|
+
i++
|
|
72
|
+
continue
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
if (ch === '"') {
|
|
76
|
+
result += ch
|
|
77
|
+
inString = !inString
|
|
78
|
+
i++
|
|
79
|
+
continue
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
if (inString) {
|
|
83
|
+
result += ch
|
|
84
|
+
i++
|
|
85
|
+
continue
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
if (ch === "/" && text[i + 1] === "/") {
|
|
89
|
+
while (i < text.length && text[i] !== "\n") i++
|
|
90
|
+
continue
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
if (ch === "/" && text[i + 1] === "*") {
|
|
94
|
+
i += 2
|
|
95
|
+
while (i < text.length - 1 && !(text[i] === "*" && text[i + 1] === "/")) i++
|
|
96
|
+
i += 2
|
|
97
|
+
result += " "
|
|
98
|
+
continue
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
if (ch === ",") {
|
|
102
|
+
const next = text.indexOf(/[\s}\]]/, i + 1)
|
|
103
|
+
if (next !== -1 && /[\s}\]]/.test(text[next])) {
|
|
104
|
+
i++
|
|
105
|
+
continue
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
result += ch
|
|
110
|
+
i++
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
return JSON.parse(result)
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function stripBaseUrlPath(baseURL: string): string {
|
|
117
|
+
try {
|
|
118
|
+
const url = new URL(baseURL)
|
|
119
|
+
return `${url.origin}`
|
|
120
|
+
} catch {
|
|
121
|
+
return baseURL.replace(/\/v1(\/.*)?$/, "").replace(/\/$/, "") || baseURL
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function extractProviderUrls(config: unknown): string[] {
|
|
126
|
+
if (!config || typeof config !== "object") return []
|
|
127
|
+
const obj = config as Record<string, unknown>
|
|
128
|
+
const provider = obj.provider
|
|
129
|
+
if (!provider || typeof provider !== "object") return []
|
|
130
|
+
|
|
131
|
+
const urls: string[] = []
|
|
132
|
+
for (const [_key, val] of Object.entries(provider as Record<string, unknown>)) {
|
|
133
|
+
if (val && typeof val === "object") {
|
|
134
|
+
const opts = (val as Record<string, unknown>).options
|
|
135
|
+
if (opts && typeof opts === "object") {
|
|
136
|
+
const baseURL = (opts as Record<string, unknown>).baseURL || (opts as Record<string, unknown>).base_url
|
|
137
|
+
if (typeof baseURL === "string" && baseURL.includes("localhost")) {
|
|
138
|
+
urls.push(stripBaseUrlPath(baseURL))
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
return urls
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
async function loadConfigUrls(api: Parameters<TuiPlugin>[0]): Promise<string[]> {
|
|
147
|
+
try {
|
|
148
|
+
const configPath = api.state.path.config
|
|
149
|
+
const resp = await fetch(`file://${configPath}`)
|
|
150
|
+
if (!resp.ok) return []
|
|
151
|
+
const text = await resp.text()
|
|
152
|
+
const config = parseJSONC(text)
|
|
153
|
+
return extractProviderUrls(config)
|
|
154
|
+
} catch {
|
|
155
|
+
return []
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
async function fetchSlots(baseUrl: string, model?: string): Promise<unknown | null> {
|
|
160
|
+
try {
|
|
161
|
+
const url = model ? `${baseUrl}/slots?model=${encodeURIComponent(model)}` : `${baseUrl}/slots`
|
|
162
|
+
const resp = await fetch(url)
|
|
163
|
+
if (!resp.ok) return null
|
|
164
|
+
return await resp.json()
|
|
165
|
+
} catch {
|
|
166
|
+
return null
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function formatPps(value: number) {
|
|
171
|
+
if (!Number.isFinite(value) || value <= 0) return undefined
|
|
172
|
+
return `${Math.round(value)}`
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function formatTps(value: number) {
|
|
176
|
+
if (!Number.isFinite(value) || value <= 0) return undefined
|
|
177
|
+
return `${Math.round(value)}`
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function SessionPromptRight(props: {
|
|
181
|
+
api: Parameters<TuiPlugin>[0]
|
|
182
|
+
sessionID: string
|
|
183
|
+
tracker: TrackerState
|
|
184
|
+
version: () => number
|
|
185
|
+
clock: () => number
|
|
186
|
+
}) {
|
|
187
|
+
const liveTps = createMemo(() => {
|
|
188
|
+
props.version()
|
|
189
|
+
props.clock()
|
|
190
|
+
const rate = props.tracker.lastGeneratedTps
|
|
191
|
+
if (!Number.isFinite(rate) || rate <= 0) return undefined
|
|
192
|
+
return rate
|
|
193
|
+
})
|
|
194
|
+
|
|
195
|
+
const prefillRate = createMemo(() => {
|
|
196
|
+
props.version()
|
|
197
|
+
if (!props.tracker.isPrefilling) return undefined
|
|
198
|
+
const rate = props.tracker.lastPrefillRate
|
|
199
|
+
if (!Number.isFinite(rate) || rate <= 0) return undefined
|
|
200
|
+
return rate
|
|
201
|
+
})
|
|
202
|
+
|
|
203
|
+
const text = createMemo(() => {
|
|
204
|
+
if (props.tracker.failure) return props.tracker.failure
|
|
205
|
+
const pp = prefillRate()
|
|
206
|
+
const tps = liveTps()
|
|
207
|
+
if (props.tracker.isPrefilling && pp) {
|
|
208
|
+
return `${formatPps(pp)} tps (PP)`
|
|
209
|
+
}
|
|
210
|
+
if (props.tracker.isGenerating && tps) {
|
|
211
|
+
return `${formatTps(tps)} tps (TG)`
|
|
212
|
+
}
|
|
213
|
+
return `- tps (TG)`
|
|
214
|
+
})
|
|
215
|
+
|
|
216
|
+
return <>{text() ? <text fg={props.api.theme.current.textMuted}>{text()}</text> : null}</>
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
const tui: TuiPlugin = async (api) => {
|
|
220
|
+
console.log("[oc-ls-stats] TUI plugin loaded!")
|
|
221
|
+
const tracker: TrackerState = {
|
|
222
|
+
streamSamplesBySession: {},
|
|
223
|
+
messageTimingByID: {},
|
|
224
|
+
lastPrefillRate: 0,
|
|
225
|
+
lastGeneratedTps: 0,
|
|
226
|
+
isPrefilling: false,
|
|
227
|
+
prefillSlotId: null,
|
|
228
|
+
prefillCapturedTokens: null,
|
|
229
|
+
prefillStartAt: 0,
|
|
230
|
+
isGenerating: false,
|
|
231
|
+
generateSlotId: null,
|
|
232
|
+
generatePrevNd: 0,
|
|
233
|
+
generateStartAt: 0,
|
|
234
|
+
prevNdBySlot: {},
|
|
235
|
+
failure: null,
|
|
236
|
+
}
|
|
237
|
+
const [version, setVersion] = createSignal(0)
|
|
238
|
+
const [clock, setClock] = createSignal(Date.now())
|
|
239
|
+
|
|
240
|
+
const bump = () => setVersion((value) => value + 1)
|
|
241
|
+
|
|
242
|
+
const pruneSamples = (now = Date.now()) => {
|
|
243
|
+
let changed = false
|
|
244
|
+
|
|
245
|
+
for (const [sessionID, samples] of Object.entries(tracker.streamSamplesBySession)) {
|
|
246
|
+
const next = samples.filter((sample) => now - sample.at <= STREAM_WINDOW_MS)
|
|
247
|
+
if (next.length !== samples.length) {
|
|
248
|
+
changed = true
|
|
249
|
+
if (next.length > 0) tracker.streamSamplesBySession[sessionID] = next
|
|
250
|
+
else delete tracker.streamSamplesBySession[sessionID]
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
if (changed) bump()
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
const clearLiveSamples = (sessionID: string) => {
|
|
258
|
+
if (!tracker.streamSamplesBySession[sessionID]?.length) return
|
|
259
|
+
delete tracker.streamSamplesBySession[sessionID]
|
|
260
|
+
bump()
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
const appendSample = (sessionID: string, messageID: string, sample: StreamSample) => {
|
|
264
|
+
const now = sample.at
|
|
265
|
+
tracker.streamSamplesBySession[sessionID] = [
|
|
266
|
+
...(tracker.streamSamplesBySession[sessionID] ?? []).filter((item) => now - item.at <= STREAM_WINDOW_MS),
|
|
267
|
+
sample,
|
|
268
|
+
]
|
|
269
|
+
const timing = tracker.messageTimingByID[messageID]
|
|
270
|
+
if (timing) {
|
|
271
|
+
tracker.messageTimingByID[messageID] = timing.firstTokenAt
|
|
272
|
+
? { ...timing, lastTokenAt: now }
|
|
273
|
+
: {
|
|
274
|
+
...timing,
|
|
275
|
+
firstResponseAt: timing.firstResponseAt ?? now,
|
|
276
|
+
firstTokenAt: now,
|
|
277
|
+
lastTokenAt: now,
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
bump()
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
let llamaServerUrls: string[] = ["http://localhost:8080"]
|
|
284
|
+
let llamaServerModel: string | undefined
|
|
285
|
+
|
|
286
|
+
const pollMetrics = async () => {
|
|
287
|
+
if (!llamaServerUrls.length) return
|
|
288
|
+
|
|
289
|
+
let model = llamaServerModel
|
|
290
|
+
if (!model) {
|
|
291
|
+
const routeSessionID = api.route.current.params?.sessionID
|
|
292
|
+
if (routeSessionID) {
|
|
293
|
+
const session = api.state.session.get(routeSessionID)
|
|
294
|
+
if (session?.model?.id) {
|
|
295
|
+
model = session.model.id
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
let anyPrefilling = false
|
|
301
|
+
let anyGenerating = false
|
|
302
|
+
let genEnded = false
|
|
303
|
+
|
|
304
|
+
const prevProcessingSlotIds = new Set(Object.keys(tracker.prevNdBySlot).map(Number))
|
|
305
|
+
const currProcessingSlotIds = new Set<number>()
|
|
306
|
+
|
|
307
|
+
for (const baseUrl of llamaServerUrls) {
|
|
308
|
+
const slots = await fetchSlots(baseUrl, model)
|
|
309
|
+
const slotList = Array.isArray(slots) ? slots : slots ? Object.values(slots) : []
|
|
310
|
+
if (slotList.length === 0) {
|
|
311
|
+
tracker.failure = "n/a"
|
|
312
|
+
bump()
|
|
313
|
+
continue
|
|
314
|
+
}
|
|
315
|
+
tracker.failure = null
|
|
316
|
+
|
|
317
|
+
debug(`poll baseUrl=${baseUrl} slots=${JSON.stringify(slotList)}`)
|
|
318
|
+
|
|
319
|
+
for (const slot of slotList) {
|
|
320
|
+
if (slot?.is_processing) {
|
|
321
|
+
currProcessingSlotIds.add(slot.id)
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
for (const slotId of prevProcessingSlotIds) {
|
|
326
|
+
if (!currProcessingSlotIds.has(slotId)) {
|
|
327
|
+
delete tracker.prevNdBySlot[slotId]
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
let prefillSlot: any = null
|
|
332
|
+
let generateSlot: any = null
|
|
333
|
+
for (const slot of slotList) {
|
|
334
|
+
if (!slot?.is_processing) continue
|
|
335
|
+
const slotId = slot.id
|
|
336
|
+
const nd = slot.next_token?.[0]?.n_decoded ?? 0
|
|
337
|
+
const entry = tracker.prevNdBySlot[slotId]
|
|
338
|
+
const baseline = entry?.baseline ?? nd
|
|
339
|
+
const hasIncreased = entry?.hasIncreased ?? false
|
|
340
|
+
|
|
341
|
+
if (!hasIncreased && nd <= baseline) {
|
|
342
|
+
prefillSlot = slot
|
|
343
|
+
break
|
|
344
|
+
} else if (nd > baseline) {
|
|
345
|
+
tracker.prevNdBySlot[slotId] = { baseline, hasIncreased: true }
|
|
346
|
+
generateSlot = slot
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
for (const slot of slotList) {
|
|
351
|
+
if (slot?.is_processing) {
|
|
352
|
+
const slotId = slot.id
|
|
353
|
+
const nd = slot.next_token?.[0]?.n_decoded ?? 0
|
|
354
|
+
const entry = tracker.prevNdBySlot[slotId]
|
|
355
|
+
if (entry === undefined) {
|
|
356
|
+
tracker.prevNdBySlot[slotId] = { baseline: nd, hasIncreased: false }
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
if (prefillSlot) {
|
|
362
|
+
anyPrefilling = true
|
|
363
|
+
const slotId = prefillSlot.id
|
|
364
|
+
const now = Date.now()
|
|
365
|
+
const nt = prefillSlot.n_prompt_tokens ?? 0
|
|
366
|
+
|
|
367
|
+
if (tracker.prefillSlotId === slotId) {
|
|
368
|
+
const dt = (now - tracker.prefillStartAt) / 1000
|
|
369
|
+
const delta = nt - tracker.prefillCapturedTokens!
|
|
370
|
+
if (dt > 0 && delta > 0) {
|
|
371
|
+
tracker.lastPrefillRate = delta / dt
|
|
372
|
+
}
|
|
373
|
+
} else {
|
|
374
|
+
tracker.prefillSlotId = slotId
|
|
375
|
+
tracker.prefillCapturedTokens = nt
|
|
376
|
+
tracker.prefillStartAt = now
|
|
377
|
+
tracker.lastPrefillRate = 0
|
|
378
|
+
debug(`prefill new slot id=${slotId} nt=${nt}`)
|
|
379
|
+
}
|
|
380
|
+
} else {
|
|
381
|
+
if (tracker.isPrefilling) {
|
|
382
|
+
tracker.prefillSlotId = null
|
|
383
|
+
tracker.prefillCapturedTokens = null
|
|
384
|
+
tracker.prefillStartAt = 0
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
if (generateSlot) {
|
|
389
|
+
anyGenerating = true
|
|
390
|
+
const slotId = generateSlot.id
|
|
391
|
+
const now = Date.now()
|
|
392
|
+
const nd = generateSlot.next_token?.[0]?.n_decoded ?? 0
|
|
393
|
+
|
|
394
|
+
if (tracker.generateSlotId === slotId) {
|
|
395
|
+
const dt = (now - tracker.generateStartAt) / 1000
|
|
396
|
+
const delta = nd - tracker.generatePrevNd
|
|
397
|
+
if (dt > 0 && delta > 0) {
|
|
398
|
+
tracker.lastGeneratedTps = delta / dt
|
|
399
|
+
debug(`gen slot=${slotId} nd=${nd} prev=${tracker.generatePrevNd} delta=${delta} dt=${dt.toFixed(2)} tps=${tracker.lastGeneratedTps.toFixed(1)}`)
|
|
400
|
+
}
|
|
401
|
+
tracker.generatePrevNd = nd
|
|
402
|
+
tracker.generateStartAt = now
|
|
403
|
+
} else {
|
|
404
|
+
tracker.generateSlotId = slotId
|
|
405
|
+
tracker.generatePrevNd = nd
|
|
406
|
+
tracker.generateStartAt = now
|
|
407
|
+
tracker.lastGeneratedTps = 0
|
|
408
|
+
debug(`gen new slot id=${slotId} nd=${nd}`)
|
|
409
|
+
}
|
|
410
|
+
} else {
|
|
411
|
+
if (tracker.isGenerating) {
|
|
412
|
+
tracker.generateSlotId = null
|
|
413
|
+
tracker.generatePrevNd = 0
|
|
414
|
+
tracker.generateStartAt = 0
|
|
415
|
+
tracker.lastGeneratedTps = 0
|
|
416
|
+
genEnded = true
|
|
417
|
+
debug(`gen no slot found ending`)
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
tracker.isPrefilling = anyPrefilling
|
|
422
|
+
tracker.isGenerating = anyGenerating
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
if (tracker.lastPrefillRate > 0 || tracker.lastGeneratedTps > 0 || genEnded) {
|
|
426
|
+
bump()
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
const onDelta = api.event.on("message.part.delta", (evt) => {
|
|
431
|
+
if (evt.properties.field !== "text") return
|
|
432
|
+
const parts = api.state.part(evt.properties.messageID)
|
|
433
|
+
const part = parts.find((item) => item.id === evt.properties.partID)
|
|
434
|
+
if (!part) return
|
|
435
|
+
if (part.type !== "text" && part.type !== "reasoning") return
|
|
436
|
+
appendSample(evt.properties.sessionID, evt.properties.messageID, {
|
|
437
|
+
at: Date.now(),
|
|
438
|
+
tokens: estimateStreamTokens(evt.properties.delta),
|
|
439
|
+
})
|
|
440
|
+
})
|
|
441
|
+
|
|
442
|
+
const onMessage = api.event.on("message.updated", (evt) => {
|
|
443
|
+
if (evt.properties.info.role !== "assistant") return
|
|
444
|
+
|
|
445
|
+
if (!evt.properties.info.time.completed) {
|
|
446
|
+
const existing = tracker.messageTimingByID[evt.properties.info.id]
|
|
447
|
+
tracker.messageTimingByID[evt.properties.info.id] = {
|
|
448
|
+
sessionID: evt.properties.sessionID,
|
|
449
|
+
requestStartAt: evt.properties.info.time.created,
|
|
450
|
+
firstResponseAt: existing?.firstResponseAt,
|
|
451
|
+
firstTokenAt: existing?.firstTokenAt,
|
|
452
|
+
lastTokenAt: existing?.lastTokenAt,
|
|
453
|
+
}
|
|
454
|
+
bump()
|
|
455
|
+
return
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
delete tracker.messageTimingByID[evt.properties.info.id]
|
|
459
|
+
pruneSamples(evt.properties.info.time.completed)
|
|
460
|
+
bump()
|
|
461
|
+
})
|
|
462
|
+
|
|
463
|
+
const onPart = api.event.on("message.part.updated", (evt) => {
|
|
464
|
+
if (evt.properties.part.type !== "tool") return
|
|
465
|
+
if (
|
|
466
|
+
evt.properties.part.state.status === "running" ||
|
|
467
|
+
evt.properties.part.state.status === "completed" ||
|
|
468
|
+
evt.properties.part.state.status === "error"
|
|
469
|
+
) {
|
|
470
|
+
clearLiveSamples(evt.properties.sessionID)
|
|
471
|
+
}
|
|
472
|
+
const timing = tracker.messageTimingByID[evt.properties.part.messageID]
|
|
473
|
+
if (!timing) return
|
|
474
|
+
if (evt.properties.part.state.status === "pending") {
|
|
475
|
+
tracker.messageTimingByID[evt.properties.part.messageID] = {
|
|
476
|
+
...timing,
|
|
477
|
+
firstResponseAt: timing.firstResponseAt ?? evt.properties.time,
|
|
478
|
+
}
|
|
479
|
+
bump()
|
|
480
|
+
return
|
|
481
|
+
}
|
|
482
|
+
if (evt.properties.part.state.status !== "running") return
|
|
483
|
+
bump()
|
|
484
|
+
})
|
|
485
|
+
|
|
486
|
+
const timer = setInterval(() => {
|
|
487
|
+
setClock(Date.now())
|
|
488
|
+
pruneSamples()
|
|
489
|
+
}, 1000)
|
|
490
|
+
|
|
491
|
+
const slotTimer = setInterval(async () => {
|
|
492
|
+
await pollMetrics()
|
|
493
|
+
}, SLOT_POLL_MS)
|
|
494
|
+
|
|
495
|
+
api.lifecycle.onDispose(() => {
|
|
496
|
+
onDelta()
|
|
497
|
+
onMessage()
|
|
498
|
+
onPart()
|
|
499
|
+
clearInterval(timer)
|
|
500
|
+
clearInterval(slotTimer)
|
|
501
|
+
})
|
|
502
|
+
|
|
503
|
+
try {
|
|
504
|
+
if (!llamaServerUrls.length) {
|
|
505
|
+
llamaServerUrls = await loadConfigUrls(api)
|
|
506
|
+
}
|
|
507
|
+
} catch (e) {
|
|
508
|
+
console.error("[oc-ls-stats] loadConfigUrls error:", e)
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
api.slots.register({
|
|
512
|
+
slots: {
|
|
513
|
+
session_prompt_right(_ctx, value) {
|
|
514
|
+
return <SessionPromptRight api={api} sessionID={value.session_id} tracker={tracker} version={version} clock={clock} />
|
|
515
|
+
},
|
|
516
|
+
},
|
|
517
|
+
})
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
const plugin: TuiPluginModule & { id: string } = {
|
|
521
|
+
id: "@troed/oc-ls-stats",
|
|
522
|
+
tui,
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
export default plugin
|