commit changes
This commit is contained in:
@@ -0,0 +1,4 @@
|
|||||||
|
node_modules/
|
||||||
|
dist/
|
||||||
|
*.log
|
||||||
|
.DS_Store
|
||||||
@@ -0,0 +1,176 @@
|
|||||||
|
# plagin-tokens
|
||||||
|
|
||||||
|
Живой индикатор скорости генерации токенов (tokens/sec) для **opencode web**.
|
||||||
|
|
||||||
|
Плагин opencode считает скорость в реальном времени и отдаёт её по локальному
|
||||||
|
HTTP/SSE, а браузерный скрипт показывает компактную строку `ток/с` прямо в конце
|
||||||
|
ответа ассистента в ленте opencode web.
|
||||||
|
|
||||||
|
## Архитектура
|
||||||
|
|
||||||
|
```
|
||||||
|
opencode web (:4096) --events--> plugin --Bun.serve (:7878)--> overlay (browser)
|
||||||
|
message.updated / session.status /stream (SSE)
|
||||||
|
/speed (JSON)
|
||||||
|
/health
|
||||||
|
/overlay.js /overlay.css
|
||||||
|
```
|
||||||
|
|
||||||
|
- Скорость считается на серверной стороне (внутри процесса opencode).
|
||||||
|
- Учитывается **только активная сессия**.
|
||||||
|
- Живая скорость — скользящее окно по приросту `tokens.output` (окно по
|
||||||
|
умолчанию 4000 мс). Если провайдер не отдаёт `tokens.output` инкрементально,
|
||||||
|
включается оценка по `message.part.updated.delta` (≈ `len/4` токенов).
|
||||||
|
- После завершения сообщения показывается средняя скорость за сообщение.
|
||||||
|
|
||||||
|
## Установка плагина
|
||||||
|
|
||||||
|
opencode загружает плагины из `~/.config/opencode/plugins/` (или
|
||||||
|
`<project>/.opencode/plugins/`). Проще всего подключить файл симлинком:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
ln -sf "$PWD/src/plugin.ts" ~/.config/opencode/plugins/plagin-tokens.ts
|
||||||
|
```
|
||||||
|
|
||||||
|
Альтернатива без симлинка — файл-обёртка с абсолютным путём:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// ~/.config/opencode/plugins/plagin-tokens.ts
|
||||||
|
export { TokenSpeedPlugin } from "/абсолютный/путь/к/plagin_tokens/src/plugin.ts"
|
||||||
|
```
|
||||||
|
|
||||||
|
Для типов нужен `@opencode-ai/plugin` (он уже есть в
|
||||||
|
`~/.config/opencode/node_modules`, либо выполните `bun install` в этом проекте).
|
||||||
|
|
||||||
|
Перезапустите `opencode web`. В логах будет строка вида
|
||||||
|
`token speed overlay on http://127.0.0.1:7878`.
|
||||||
|
|
||||||
|
## Установка оверлея
|
||||||
|
|
||||||
|
Оверлей — обычный браузерный скрипт. Два способа:
|
||||||
|
|
||||||
|
### 1. Tampermonkey / Violentmonkey (постоянно)
|
||||||
|
|
||||||
|
Создайте userscript:
|
||||||
|
|
||||||
|
```js
|
||||||
|
// ==UserScript==
|
||||||
|
// @name opencode token speed
|
||||||
|
// @match http://localhost:4096/*
|
||||||
|
// @match http://127.0.0.1:4096/*
|
||||||
|
// ==/UserScript==
|
||||||
|
window.__OTS_BASE__ = "http://127.0.0.1:7878"
|
||||||
|
const s = document.createElement("script")
|
||||||
|
s.src = window.__OTS_BASE__ + "/overlay.js"
|
||||||
|
document.body.appendChild(s)
|
||||||
|
```
|
||||||
|
|
||||||
|
Поправьте `@match` под адрес вашего `opencode web`.
|
||||||
|
|
||||||
|
### 2. Bookmarklet (без расширений)
|
||||||
|
|
||||||
|
Добавьте закладку с URL:
|
||||||
|
|
||||||
|
```
|
||||||
|
javascript:(()=>{const b="http://127.0.0.1:7878";window.__OTS_BASE__=b;const s=document.createElement("script");s.src=b+"/overlay.js";document.body.appendChild(s)})()
|
||||||
|
```
|
||||||
|
|
||||||
|
Откройте opencode web и нажмите закладку.
|
||||||
|
|
||||||
|
## Использование оверлея
|
||||||
|
|
||||||
|
- Плагин встраивает компактную строку `● 53.4 ток/с` в конец ответа ассистента
|
||||||
|
(под последним текстовым блоком сообщения, до блока изменений файлов).
|
||||||
|
- Строка обновляется в реальном времени во время генерации, а по завершении
|
||||||
|
закрепляет итоговую среднюю скорость. Прошлые ответы сохраняют своё значение.
|
||||||
|
- Цвет точки отражает состояние: зелёный — генерация, синий — завершено,
|
||||||
|
серый — простой.
|
||||||
|
- Стиль минималистичный и наследует тему opencode web (светлая/тёмная) через
|
||||||
|
CSS-переменные `--v2-*`.
|
||||||
|
|
||||||
|
## Настройка (переменные окружения)
|
||||||
|
|
||||||
|
| Переменная | По умолчанию | Описание |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `PLAGIN_TOKENS_HOST` | `127.0.0.1` | адрес HTTP-сервера плагина |
|
||||||
|
| `PLAGIN_TOKENS_PORT` | `7878` | порт |
|
||||||
|
| `PLAGIN_TOKENS_WINDOW_MS` | `4000` | скользящее окно расчёта, мс |
|
||||||
|
| `PLAGIN_TOKENS_IDLE_MS` | `4000` | таймаут простоя, мс |
|
||||||
|
| `PLAGIN_TOKENS_URL` | `http://host:port` | базовый URL для оверлея |
|
||||||
|
|
||||||
|
## HTTP-эндпоинты
|
||||||
|
|
||||||
|
- `GET /speed` — последний снимок (JSON).
|
||||||
|
- `GET /stream` — SSE-поток снимков.
|
||||||
|
- `GET /health` — проверка живости + снимок.
|
||||||
|
- `GET /overlay.js`, `GET /overlay.css` — ресурсы оверлея.
|
||||||
|
|
||||||
|
## Разработка
|
||||||
|
|
||||||
|
```sh
|
||||||
|
bun install
|
||||||
|
bun test # тесты логики скорости
|
||||||
|
bun run typecheck # tsc --noEmit
|
||||||
|
```
|
||||||
|
|
||||||
|
## Статус
|
||||||
|
|
||||||
|
Плагин слушает поток событий opencode `message.part.delta` (`field: "text"` /
|
||||||
|
`"reasoning"`) и считает живую скорость по мере прихода текста (≈ `len/4`
|
||||||
|
токенов на дельту). Как только провайдер отдаёт реальные `tokens.output`
|
||||||
|
(обычно в финальном `message.updated`), значение уточняется, а на завершении
|
||||||
|
показывается средняя скорость за сообщение. Пока сессия `busy`, состояние
|
||||||
|
`idle` не выставляется, даже если токены приходят только в конце.
|
||||||
|
|
||||||
|
Учтите: у некоторых провайдеров (например, Selectel) `tokens.output` не растёт
|
||||||
|
инкрементально — тогда работает только оценка по дельтам текста. Окно расчёта
|
||||||
|
меняется через `PLAGIN_TOKENS_WINDOW_MS`.
|
||||||
|
|
||||||
|
## Локальные модели без поддержки инструментов
|
||||||
|
|
||||||
|
Малые локальные модели (например `gemma3:1b-it-q4_K_M` на Ollama `10.8.0.62`)
|
||||||
|
не умеют tool-calling, а агент по умолчанию `build` всегда передаёт инструменты,
|
||||||
|
из-за чего Ollama отвечает `does not support tools`. Решение — объявить модель
|
||||||
|
и завести отдельный агент без инструментов.
|
||||||
|
|
||||||
|
1. Добавить модель в `~/.config/opencode/opencode.jsonc` в
|
||||||
|
`provider."ollama-mac-62".models`:
|
||||||
|
|
||||||
|
```jsonc
|
||||||
|
"gemma3:1b-it-q4_K_M": {
|
||||||
|
"name": "Gemma3 1B IT Q4_K_M",
|
||||||
|
"tool_call": false,
|
||||||
|
"reasoning": false,
|
||||||
|
"attachment": false,
|
||||||
|
"limit": { "context": 32768, "output": 8192 }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
2. Создать `~/.config/opencode/agents/gemma-chat.md`:
|
||||||
|
|
||||||
|
```md
|
||||||
|
---
|
||||||
|
description: "Tool-less chat agent for models without tool support"
|
||||||
|
mode: primary
|
||||||
|
model: "ollama-mac-62/gemma3:1b-it-q4_K_M"
|
||||||
|
tools:
|
||||||
|
"*": false
|
||||||
|
---
|
||||||
|
```
|
||||||
|
|
||||||
|
3. Перезапустить opencode и запускать с агентом:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
opencode run --agent gemma-chat -m ollama-mac-62/gemma3:1b-it-q4_K_M "..."
|
||||||
|
```
|
||||||
|
|
||||||
|
Проверено на `gemma3:1b-it-q4_K_M` (удалённый Ollama): живая скорость растёт во
|
||||||
|
время стрима и фиксируется на завершении (≈153 tok/s, 443 токена за 2.9 c).
|
||||||
|
|
||||||
|
## Устойчивость к зависаниям
|
||||||
|
|
||||||
|
Если генерация зависла и событие `session.idle` не приходит, флаг `busy`
|
||||||
|
остаётся выставленным. Чтобы бейдж не «висел» в состоянии `streaming` вечно,
|
||||||
|
трекер принудительно уходит в `idle`, если активности не было дольше
|
||||||
|
`max(idleTimeoutMs * 15, 60s)`.
|
||||||
|
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
{
|
||||||
|
"lockfileVersion": 2,
|
||||||
|
"configVersion": 1,
|
||||||
|
"workspaces": {
|
||||||
|
"": {
|
||||||
|
"name": "plagin-tokens",
|
||||||
|
"devDependencies": {
|
||||||
|
"@opencode-ai/plugin": "1.18.32",
|
||||||
|
"@types/bun": "^1.1.0",
|
||||||
|
"typescript": "^5.6.0",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"packages": {
|
||||||
|
"@ai-sdk/provider": ["@ai-sdk/provider@3.0.8", "", { "dependencies": { "json-schema": "^0.4.0" } }, "sha512-oGMAgGoQdBXbZqNG0Ze56CHjDZ1IDYOwGYxYjO5KLSlz5HiNQ9udIXsPZ61VWaHGZ5XW/jyjmr6t2xz2jGVwbQ=="],
|
||||||
|
|
||||||
|
"@msgpackr-extract/msgpackr-extract-darwin-arm64": ["@msgpackr-extract/msgpackr-extract-darwin-arm64@3.0.4", "", { "os": "darwin", "cpu": "arm64" }, "sha512-LCkGo6JDfaBhgST7UpPWgNgLINpcpabaHfyz5OBx75nUYxBsaEPxjnyNjWpeb/xBup/682QnBfRBy2/LvPutZQ=="],
|
||||||
|
|
||||||
|
"@msgpackr-extract/msgpackr-extract-darwin-x64": ["@msgpackr-extract/msgpackr-extract-darwin-x64@3.0.4", "", { "os": "darwin", "cpu": "x64" }, "sha512-zExlW9zUJKZH/tOtVMttwjKa4Xm/3KcNjnE3dPN92uCktwavMxpgCA3MoJK/DOnTWsQgo224OaST27/mPNAf+w=="],
|
||||||
|
|
||||||
|
"@msgpackr-extract/msgpackr-extract-linux-arm": ["@msgpackr-extract/msgpackr-extract-linux-arm@3.0.4", "", { "os": "linux", "cpu": "arm" }, "sha512-Tg3yX65f5GbtXLkrYEHE5oibZG9epyYWas7FogTTEJeDEF9JlXJzKgXaNhT3UXlTOeA+AfZpYZYZ0uPj7Cfquw=="],
|
||||||
|
|
||||||
|
"@msgpackr-extract/msgpackr-extract-linux-arm64": ["@msgpackr-extract/msgpackr-extract-linux-arm64@3.0.4", "", { "os": "linux", "cpu": "arm64" }, "sha512-dgX0P/9wGPJeHFBG+ZmhgE6bmtMt7NP5CRBGyyktpopdk/mW4POnrpQsSLtKI1dwpc+pPLuXHDh6vvskyQE/sw=="],
|
||||||
|
|
||||||
|
"@msgpackr-extract/msgpackr-extract-linux-x64": ["@msgpackr-extract/msgpackr-extract-linux-x64@3.0.4", "", { "os": "linux", "cpu": "x64" }, "sha512-8TNXMEjJc3QEy7R/x1INhgiU+XakDAFUzBhaz7+Rbrs8NH5UQeHQxxmzsSBJGyV6I1jW79undiQm8tOI+D+8FQ=="],
|
||||||
|
|
||||||
|
"@msgpackr-extract/msgpackr-extract-win32-x64": ["@msgpackr-extract/msgpackr-extract-win32-x64@3.0.4", "", { "os": "win32", "cpu": "x64" }, "sha512-CmCXPQrkbwExx3j946/PtHWHbYJiCRBRDl4BlkRQcJB/YOwQxJRTpoo7aTsortjgoJ1x7opzTSxn7C+ASSLVjQ=="],
|
||||||
|
|
||||||
|
"@opencode-ai/plugin": ["@opencode-ai/plugin@1.18.32", "", { "dependencies": { "@ai-sdk/provider": "3.0.8", "@opencode-ai/sdk": "1.18.32", "effect": "4.0.0-beta.83", "zod": "4.1.8" }, "peerDependencies": { "@opentui/core": ">=0.4.5", "@opentui/keymap": ">=0.4.5", "@opentui/solid": ">=0.4.5" }, "optionalPeers": ["@opentui/core", "@opentui/keymap", "@opentui/solid"] }, "sha512-JJXaTHmkiU9EAshJOFuIkZsAuvBcLw46BAErePeER8bPeO2LL2uGyBRt4tuLJjJ2N7v1vlZgfvAD7bWKupke1A=="],
|
||||||
|
|
||||||
|
"@opencode-ai/sdk": ["@opencode-ai/sdk@1.18.32", "", { "dependencies": { "cross-spawn": "7.0.6" } }, "sha512-Wi3WtH/cLA3C0ga05lyDb7zac+SzbST9MPwCve1Ffod0xwzHdy9G2gnxvMAR4RBRhKJS32Rgk2cR+fxBhAVSQw=="],
|
||||||
|
|
||||||
|
"@standard-schema/spec": ["@standard-schema/spec@1.1.0", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="],
|
||||||
|
|
||||||
|
"@types/bun": ["@types/bun@1.4.2", "", { "dependencies": { "bun-types": "1.4.2" } }, "sha512-GimotNn7+ZV0uVArItBbriZsR1oNf0+WTzPkdcFrzShI7k2norL0uzEaJT8T33dWr7O/c9ZDuAFQrctKCi72oQ=="],
|
||||||
|
|
||||||
|
"@types/node": ["@types/node@26.6.3", "", { "dependencies": { "undici-types": "~8.9.0" } }, "sha512-dsqMQQoeTLqu9wynDD00q573mNzso3IdQOAfHRJqLCcmCFPoGo9A1bDpUcv/9tnKpErQWv9uKeGfl37EIS02Yg=="],
|
||||||
|
|
||||||
|
"bun-types": ["bun-types@1.4.2", "", { "dependencies": { "@types/node": "*" } }, "sha512-bxV1FgK7yBIzjRe5zBozIM4Bem11ZJcCXSrjWRG3YWLt8yFDePu4cLjpebO8OvPeIE9trbyPF4fuj3Cia4Fj3w=="],
|
||||||
|
|
||||||
|
"cross-spawn": ["cross-spawn@7.0.6", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA=="],
|
||||||
|
|
||||||
|
"detect-libc": ["detect-libc@2.1.2", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="],
|
||||||
|
|
||||||
|
"effect": ["effect@4.0.0-beta.83", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.8.0", "find-my-way-ts": "^0.1.6", "ini": "^7.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^2.0.1", "multipasta": "^0.2.7", "toml": "^4.1.1", "uuid": "^14.0.0", "yaml": "^2.9.0" } }, "sha512-0wsak8RtgGAr9UWSbVDgJHZcUqMSvicHcvaZv1MbMM7MCGgW4Rn/137J1MHQbwYPcwYGxT/IqehFd+UbYuj78w=="],
|
||||||
|
|
||||||
|
"fast-check": ["fast-check@4.10.2", "", { "dependencies": { "pure-rand": "^8.0.0" } }, "sha512-iK2f+YrcmoeGqk6fA0ea2bptcu/itMIm4NfEozq6N25+aG6h7s5HZbB/k1aV7b5w5sFLMCbbtRUsTVR+BgC3xw=="],
|
||||||
|
|
||||||
|
"find-my-way-ts": ["find-my-way-ts@0.1.6", "", {}, "sha512-a85L9ZoXtNAey3Y6Z+eBWW658kO/MwR7zIafkIUPUMf3isZG0NCs2pjW2wtjxAKuJPxMAsHUIP4ZPGv0o5gyTA=="],
|
||||||
|
|
||||||
|
"ini": ["ini@7.0.0", "", {}, "sha512-ifK0CgjALofS5bkrcTy4RaQ9Vx2Knf/eLeIO+NaswQEpH1UblrtTSCIvN71qQDMq0PeQ/SSPojvEJp9vvvfr+w=="],
|
||||||
|
|
||||||
|
"isexe": ["isexe@2.0.0", "", {}, "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw=="],
|
||||||
|
|
||||||
|
"json-schema": ["json-schema@0.4.0", "", {}, "sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA=="],
|
||||||
|
|
||||||
|
"kubernetes-types": ["kubernetes-types@1.30.0", "", {}, "sha512-Dew1okvhM/SQcIa2rcgujNndZwU8VnSapDgdxlYoB84ZlpAD43U6KLAFqYo17ykSFGHNPrg0qry0bP+GJd9v7Q=="],
|
||||||
|
|
||||||
|
"msgpackr": ["msgpackr@2.1.0", "", { "optionalDependencies": { "msgpackr-extract": "^3.0.4" } }, "sha512-p/pBCVO63CsvvpkomUnNNag6+n38rULuDA6HHe70o2gtC8ODI52foF/4ko2qQcp6OiErJXTmrZeXmsGGHsIQNQ=="],
|
||||||
|
|
||||||
|
"msgpackr-extract": ["msgpackr-extract@3.0.4", "", { "dependencies": { "node-gyp-build-optional-packages": "5.2.2" }, "optionalDependencies": { "@msgpackr-extract/msgpackr-extract-darwin-arm64": "3.0.4", "@msgpackr-extract/msgpackr-extract-darwin-x64": "3.0.4", "@msgpackr-extract/msgpackr-extract-linux-arm": "3.0.4", "@msgpackr-extract/msgpackr-extract-linux-arm64": "3.0.4", "@msgpackr-extract/msgpackr-extract-linux-x64": "3.0.4", "@msgpackr-extract/msgpackr-extract-win32-x64": "3.0.4" }, "bin": { "download-msgpackr-prebuilds": "bin/download-prebuilds.js" } }, "sha512-4kmO/MdyUIkLIvTPr8VHLil4AtoKIoniWPIEk5+CDy0xnWC84azhSFmuJ7PxZdsYtiP5kEeQsORAVIeMgxT+Hw=="],
|
||||||
|
|
||||||
|
"multipasta": ["multipasta@0.2.8", "", {}, "sha512-ZPWuMKyv0cSO29f7hozp+k6+crZbQijV8ipMvxNxRf2SwtYGTX1ZX89Kd20VV4H9Znonx+EQn+iy1wGQsJ+b+Q=="],
|
||||||
|
|
||||||
|
"node-gyp-build-optional-packages": ["node-gyp-build-optional-packages@5.2.2", "", { "dependencies": { "detect-libc": "^2.0.1" }, "bin": { "node-gyp-build-optional-packages": "bin.js", "node-gyp-build-optional-packages-optional": "optional.js", "node-gyp-build-optional-packages-test": "build-test.js" } }, "sha512-s+w+rBWnpTMwSFbaE0UXsRlg7hU4FjekKU4eyAih5T8nJuNZT1nNsskXpxmeqSK9UzkBl6UgRlnKc8hz8IEqOw=="],
|
||||||
|
|
||||||
|
"path-key": ["path-key@3.1.1", "", {}, "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q=="],
|
||||||
|
|
||||||
|
"pure-rand": ["pure-rand@8.4.2", "", {}, "sha512-vvuOGgcuPJAirlHvuQw1TrOiw7ptaIXXmIbNuiNOY6lNGJJH49PQ1Kj4nd783nPdQhQdicgOjVI2yI/9BD6/Ng=="],
|
||||||
|
|
||||||
|
"shebang-command": ["shebang-command@2.0.0", "", { "dependencies": { "shebang-regex": "^3.0.0" } }, "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA=="],
|
||||||
|
|
||||||
|
"shebang-regex": ["shebang-regex@3.0.0", "", {}, "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A=="],
|
||||||
|
|
||||||
|
"toml": ["toml@4.3.0", "", {}, "sha512-lVb8X9BsPVuH0M4BKeS91tXAmJvCjQ5UIyAbQFaxkKGyUFK2RPkhwaFSQH8vbpl1d23eu/IBH+dwVMHWaq9A5A=="],
|
||||||
|
|
||||||
|
"typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],
|
||||||
|
|
||||||
|
"undici-types": ["undici-types@8.9.0", "", {}, "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg=="],
|
||||||
|
|
||||||
|
"uuid": ["uuid@14.0.2", "", { "bin": { "uuid": "dist-node/bin/uuid" } }, "sha512-xZe/16rV4aa+HGSOCiY2YeLT1OybRLrrkL/Rqaq7p7GMVXjFh+6wN4oMYgjFmnSnhY8t6Xpdl2l9qmnHYuMHwQ=="],
|
||||||
|
|
||||||
|
"which": ["which@2.0.2", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="],
|
||||||
|
|
||||||
|
"yaml": ["yaml@2.9.1", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw=="],
|
||||||
|
|
||||||
|
"zod": ["zod@4.1.8", "", {}, "sha512-5R1P+WwQqmmMIEACyzSvo4JXHY5WiAFHRMg+zBZKgKS+Q1viRa0C1hmUKtHltoIFKtIdki3pRxkmpP74jnNYHQ=="],
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
{
|
||||||
|
"name": "plagin-tokens",
|
||||||
|
"version": "0.1.0",
|
||||||
|
"private": true,
|
||||||
|
"type": "module",
|
||||||
|
"description": "Live tokens/sec overlay for opencode web",
|
||||||
|
"main": "src/plugin.ts",
|
||||||
|
"scripts": {
|
||||||
|
"test": "bun test",
|
||||||
|
"typecheck": "tsc --noEmit",
|
||||||
|
"build": "bun build src/plugin.ts --target bun --outfile dist/plugin.js && cp -r src/overlay dist/overlay"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@opencode-ai/plugin": "1.18.32",
|
||||||
|
"@types/bun": "^1.1.0",
|
||||||
|
"typescript": "^5.6.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
export interface TokenSpeedConfig {
|
||||||
|
host: string
|
||||||
|
port: number
|
||||||
|
windowMs: number
|
||||||
|
idleTimeoutMs: number
|
||||||
|
overlayBaseUrl: string
|
||||||
|
}
|
||||||
|
|
||||||
|
function num(value: string | undefined, fallback: number): number {
|
||||||
|
const n = Number(value)
|
||||||
|
return Number.isFinite(n) && n > 0 ? n : fallback
|
||||||
|
}
|
||||||
|
|
||||||
|
export function loadConfig(): TokenSpeedConfig {
|
||||||
|
const host = process.env.PLAGIN_TOKENS_HOST || "127.0.0.1"
|
||||||
|
const port = num(process.env.PLAGIN_TOKENS_PORT, 7878)
|
||||||
|
const overlayBaseUrl =
|
||||||
|
process.env.PLAGIN_TOKENS_URL || `http://${host}:${port}`
|
||||||
|
return {
|
||||||
|
host,
|
||||||
|
port,
|
||||||
|
windowMs: num(process.env.PLAGIN_TOKENS_WINDOW_MS, 4000),
|
||||||
|
idleTimeoutMs: num(process.env.PLAGIN_TOKENS_IDLE_MS, 4000),
|
||||||
|
overlayBaseUrl,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
import type { Tracker } from "./tracker"
|
||||||
|
import type { AssistantLike, SessionStatusLike } from "./types"
|
||||||
|
|
||||||
|
interface RawEvent {
|
||||||
|
type: string
|
||||||
|
properties?: Record<string, unknown>
|
||||||
|
}
|
||||||
|
|
||||||
|
export function routeEvent(tracker: Tracker, event: unknown): void {
|
||||||
|
const payload = event as RawEvent
|
||||||
|
const properties = payload.properties ?? {}
|
||||||
|
switch (payload.type) {
|
||||||
|
case "message.updated": {
|
||||||
|
const info = properties.info as AssistantLike | undefined
|
||||||
|
if (info?.role === "assistant") tracker.onMessageUpdated(info)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
case "message.part.delta": {
|
||||||
|
const sessionID = properties.sessionID as string | undefined
|
||||||
|
const delta = properties.delta
|
||||||
|
const field = properties.field
|
||||||
|
if (
|
||||||
|
sessionID &&
|
||||||
|
typeof delta === "string" &&
|
||||||
|
(field === "text" || field === "reasoning")
|
||||||
|
) {
|
||||||
|
tracker.onPartDelta(sessionID, delta)
|
||||||
|
}
|
||||||
|
break
|
||||||
|
}
|
||||||
|
case "message.part.updated": {
|
||||||
|
const part = properties.part as
|
||||||
|
| { type?: string; sessionID?: string }
|
||||||
|
| undefined
|
||||||
|
const delta = properties.delta
|
||||||
|
if (part?.type === "text" && part.sessionID && typeof delta === "string") {
|
||||||
|
tracker.onPartDelta(part.sessionID, delta)
|
||||||
|
}
|
||||||
|
break
|
||||||
|
}
|
||||||
|
case "session.status": {
|
||||||
|
const sessionID = properties.sessionID as string | undefined
|
||||||
|
const status = properties.status as SessionStatusLike | undefined
|
||||||
|
if (sessionID && status) tracker.onSessionStatus(sessionID, status)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
case "session.idle": {
|
||||||
|
const sessionID = properties.sessionID as string | undefined
|
||||||
|
if (sessionID) tracker.onSessionIdle(sessionID)
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
.ots-inline {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
margin-top: 8px;
|
||||||
|
font: 12px/1.2 ui-monospace, SFMono-Regular, Menlo, monospace;
|
||||||
|
color: var(--v2-text-text-muted, #9ca3af);
|
||||||
|
user-select: none;
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ots-inline .ots-dot {
|
||||||
|
width: 7px;
|
||||||
|
height: 7px;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: var(--v2-text-text-faint, #9ca3af);
|
||||||
|
flex: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ots-inline .ots-val {
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--v2-text-text-base, currentColor);
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ots-inline .ots-unit {
|
||||||
|
color: var(--v2-text-text-faint, #9ca3af);
|
||||||
|
}
|
||||||
|
|
||||||
|
.ots-inline.ots-streaming .ots-dot {
|
||||||
|
background: var(--v2-state-fg-success, #22c55e);
|
||||||
|
animation: ots-pulse 1.4s ease-out infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ots-inline.ots-finished .ots-dot {
|
||||||
|
background: var(--v2-state-fg-info, #3b82f6);
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes ots-pulse {
|
||||||
|
0% {
|
||||||
|
box-shadow: 0 0 0 0 rgba(34, 197, 94, 0.45);
|
||||||
|
}
|
||||||
|
100% {
|
||||||
|
box-shadow: 0 0 0 7px rgba(34, 197, 94, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-reduced-motion: reduce) {
|
||||||
|
.ots-inline.ots-streaming .ots-dot {
|
||||||
|
animation: none;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
;(function () {
|
||||||
|
if (window.__OTS_LOADED__) return
|
||||||
|
window.__OTS_LOADED__ = true
|
||||||
|
|
||||||
|
var DEFAULT_BASE = "http://127.0.0.1:7878"
|
||||||
|
var script = document.currentScript
|
||||||
|
var BASE =
|
||||||
|
window.__OTS_BASE__ ||
|
||||||
|
(script && script.dataset && script.dataset.base) ||
|
||||||
|
(script && script.src ? new URL(script.src).origin : DEFAULT_BASE)
|
||||||
|
|
||||||
|
var TURN_SELECTOR = '[data-component="session-turn"]'
|
||||||
|
var ANSWER_SELECTOR = '[data-slot="session-turn-assistant-content"]'
|
||||||
|
var MARK = "data-ots-speed"
|
||||||
|
|
||||||
|
var state = {
|
||||||
|
rate: 0,
|
||||||
|
messageID: null,
|
||||||
|
state: "idle",
|
||||||
|
}
|
||||||
|
var current = null
|
||||||
|
var currentMsg = null
|
||||||
|
|
||||||
|
function fmt(value) {
|
||||||
|
var n = Number(value)
|
||||||
|
if (!isFinite(n) || n < 0) n = 0
|
||||||
|
return n.toFixed(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
function el(tag, cls, txt) {
|
||||||
|
var n = document.createElement(tag)
|
||||||
|
if (cls) n.className = cls
|
||||||
|
if (txt != null) n.textContent = txt
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
function createLine() {
|
||||||
|
var line = el("div", "ots-inline ots-idle")
|
||||||
|
line.setAttribute(MARK, "")
|
||||||
|
line.title = "opencode token speed"
|
||||||
|
line.appendChild(el("span", "ots-dot"))
|
||||||
|
line.appendChild(el("span", "ots-val", "0.0"))
|
||||||
|
line.appendChild(el("span", "ots-unit", "ток/с"))
|
||||||
|
return line
|
||||||
|
}
|
||||||
|
|
||||||
|
function hostFor(messageID) {
|
||||||
|
var turns = document.querySelectorAll(TURN_SELECTOR)
|
||||||
|
var turn = turns[turns.length - 1]
|
||||||
|
if (!turn) return null
|
||||||
|
var answer = turn.querySelector(ANSWER_SELECTOR)
|
||||||
|
if (!answer) return null
|
||||||
|
var host = answer.parentElement || answer
|
||||||
|
var existing = host.querySelector("[" + MARK + "]")
|
||||||
|
if (existing && existing.getAttribute(MARK) !== String(messageID)) return null
|
||||||
|
return { host: host, existing: existing }
|
||||||
|
}
|
||||||
|
|
||||||
|
function ensureTarget(messageID) {
|
||||||
|
if (current && current.isConnected && currentMsg === messageID) return true
|
||||||
|
var found = hostFor(messageID)
|
||||||
|
if (!found) return false
|
||||||
|
var line = found.existing
|
||||||
|
if (!line) {
|
||||||
|
line = createLine()
|
||||||
|
found.host.appendChild(line)
|
||||||
|
}
|
||||||
|
line.setAttribute(MARK, String(messageID == null ? "" : messageID))
|
||||||
|
current = line
|
||||||
|
currentMsg = messageID
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
function render() {
|
||||||
|
if (!current || !current.isConnected) return
|
||||||
|
var val = current.querySelector(".ots-val")
|
||||||
|
if (val) val.textContent = fmt(state.rate)
|
||||||
|
current.classList.remove("ots-idle", "ots-streaming", "ots-finished")
|
||||||
|
current.classList.add("ots-" + state.state)
|
||||||
|
}
|
||||||
|
|
||||||
|
function onSnapshot(data) {
|
||||||
|
state.rate = Number(data.tokensPerSecond) || 0
|
||||||
|
state.state = data.state || "idle"
|
||||||
|
state.messageID = data.messageID || null
|
||||||
|
|
||||||
|
if (state.messageID && state.state !== "idle") {
|
||||||
|
ensureTarget(state.messageID)
|
||||||
|
}
|
||||||
|
render()
|
||||||
|
}
|
||||||
|
|
||||||
|
function connect() {
|
||||||
|
try {
|
||||||
|
var es = new EventSource(BASE + "/stream")
|
||||||
|
es.onmessage = function (e) {
|
||||||
|
if (!e.data) return
|
||||||
|
try {
|
||||||
|
onSnapshot(JSON.parse(e.data))
|
||||||
|
} catch (err) {}
|
||||||
|
}
|
||||||
|
} catch (e) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
var observer = null
|
||||||
|
|
||||||
|
function watch() {
|
||||||
|
if (observer || !document.body) return
|
||||||
|
observer = new MutationObserver(function () {
|
||||||
|
if (state.state !== "streaming" || !state.messageID) return
|
||||||
|
if (current && current.isConnected) return
|
||||||
|
if (ensureTarget(state.messageID)) render()
|
||||||
|
})
|
||||||
|
observer.observe(document.body, { childList: true, subtree: true })
|
||||||
|
}
|
||||||
|
|
||||||
|
function mount() {
|
||||||
|
if (!document.body) return
|
||||||
|
if (!document.getElementById("ots-style")) {
|
||||||
|
var link = document.createElement("link")
|
||||||
|
link.id = "ots-style"
|
||||||
|
link.rel = "stylesheet"
|
||||||
|
link.href = BASE + "/overlay.css"
|
||||||
|
document.head.appendChild(link)
|
||||||
|
}
|
||||||
|
watch()
|
||||||
|
connect()
|
||||||
|
if (current && current.isConnected) render()
|
||||||
|
}
|
||||||
|
|
||||||
|
if (document.body) mount()
|
||||||
|
else document.addEventListener("DOMContentLoaded", mount)
|
||||||
|
})()
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
import type { Plugin } from "@opencode-ai/plugin"
|
||||||
|
import { loadConfig } from "./config"
|
||||||
|
import { routeEvent } from "./events"
|
||||||
|
import { startServer, type SpeedServer } from "./server"
|
||||||
|
import { Tracker } from "./tracker"
|
||||||
|
import type { SpeedSnapshot } from "./types"
|
||||||
|
|
||||||
|
interface SharedServer {
|
||||||
|
server: SpeedServer
|
||||||
|
refs: number
|
||||||
|
}
|
||||||
|
|
||||||
|
const SHARED_KEY = Symbol.for("plagin-tokens.sharedServers")
|
||||||
|
|
||||||
|
function registry(): Map<string, SharedServer> {
|
||||||
|
const g = globalThis as unknown as Record<PropertyKey, unknown>
|
||||||
|
let reg = g[SHARED_KEY] as Map<string, SharedServer> | undefined
|
||||||
|
if (!reg) {
|
||||||
|
reg = new Map()
|
||||||
|
g[SHARED_KEY] = reg
|
||||||
|
}
|
||||||
|
return reg
|
||||||
|
}
|
||||||
|
|
||||||
|
function acquireServer(
|
||||||
|
host: string,
|
||||||
|
port: number,
|
||||||
|
getSnapshot: () => SpeedSnapshot,
|
||||||
|
): SpeedServer {
|
||||||
|
const reg = registry()
|
||||||
|
const key = `${host}:${port}`
|
||||||
|
const existing = reg.get(key)
|
||||||
|
if (existing) {
|
||||||
|
existing.refs += 1
|
||||||
|
return existing.server
|
||||||
|
}
|
||||||
|
const server = startServer({ host, port, getSnapshot })
|
||||||
|
reg.set(key, { server, refs: 1 })
|
||||||
|
return server
|
||||||
|
}
|
||||||
|
|
||||||
|
function releaseServer(host: string, port: number): void {
|
||||||
|
const reg = registry()
|
||||||
|
const key = `${host}:${port}`
|
||||||
|
const entry = reg.get(key)
|
||||||
|
if (!entry) return
|
||||||
|
entry.refs -= 1
|
||||||
|
if (entry.refs <= 0) {
|
||||||
|
entry.server.stop()
|
||||||
|
reg.delete(key)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const TokenSpeedPlugin: Plugin = async ({ client }) => {
|
||||||
|
const config = loadConfig()
|
||||||
|
const tracker = new Tracker({
|
||||||
|
windowMs: config.windowMs,
|
||||||
|
idleTimeoutMs: config.idleTimeoutMs,
|
||||||
|
})
|
||||||
|
|
||||||
|
let server: SpeedServer | null = null
|
||||||
|
try {
|
||||||
|
server = acquireServer(config.host, config.port, () => tracker.snapshot())
|
||||||
|
await client.app
|
||||||
|
.log({
|
||||||
|
body: {
|
||||||
|
service: "plagin-tokens",
|
||||||
|
level: "info",
|
||||||
|
message: `token speed overlay on ${server.url}`,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.catch(() => {})
|
||||||
|
} catch (error) {
|
||||||
|
await client.app
|
||||||
|
.log({
|
||||||
|
body: {
|
||||||
|
service: "plagin-tokens",
|
||||||
|
level: "error",
|
||||||
|
message: `failed to start overlay server: ${String(error)}`,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.catch(() => {})
|
||||||
|
}
|
||||||
|
|
||||||
|
const unsubscribe = server
|
||||||
|
? tracker.onChange((snapshot) => server?.publish(snapshot))
|
||||||
|
: () => {}
|
||||||
|
const ticker = setInterval(() => tracker.refresh(), 1000)
|
||||||
|
|
||||||
|
return {
|
||||||
|
event: async ({ event }) => {
|
||||||
|
routeEvent(tracker, event)
|
||||||
|
},
|
||||||
|
dispose: async () => {
|
||||||
|
clearInterval(ticker)
|
||||||
|
unsubscribe()
|
||||||
|
releaseServer(config.host, config.port)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default TokenSpeedPlugin
|
||||||
@@ -0,0 +1,165 @@
|
|||||||
|
import { readFileSync } from "node:fs"
|
||||||
|
import { join } from "node:path"
|
||||||
|
import type { SpeedSnapshot } from "./types"
|
||||||
|
|
||||||
|
export interface SpeedServerOptions {
|
||||||
|
host: string
|
||||||
|
port: number
|
||||||
|
getSnapshot: () => SpeedSnapshot
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SpeedServer {
|
||||||
|
readonly port: number
|
||||||
|
readonly url: string
|
||||||
|
publish(snapshot: SpeedSnapshot): void
|
||||||
|
stop(): void
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Client {
|
||||||
|
controller: ReadableStreamDefaultController<Uint8Array>
|
||||||
|
keep: ReturnType<typeof setInterval>
|
||||||
|
}
|
||||||
|
|
||||||
|
const overlayDir = join(import.meta.dir, "overlay")
|
||||||
|
|
||||||
|
function corsHeaders(): Record<string, string> {
|
||||||
|
return {
|
||||||
|
"Access-Control-Allow-Origin": "*",
|
||||||
|
"Access-Control-Allow-Methods": "GET, OPTIONS",
|
||||||
|
"Access-Control-Allow-Headers": "*",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function startServer(opts: SpeedServerOptions): SpeedServer {
|
||||||
|
const encoder = new TextEncoder()
|
||||||
|
const clients = new Set<Client>()
|
||||||
|
let latest = opts.getSnapshot()
|
||||||
|
let lastSent = 0
|
||||||
|
let pending: ReturnType<typeof setTimeout> | null = null
|
||||||
|
|
||||||
|
function flush(): void {
|
||||||
|
const bytes = encoder.encode(`data: ${JSON.stringify(latest)}\n\n`)
|
||||||
|
for (const client of clients) {
|
||||||
|
try {
|
||||||
|
client.controller.enqueue(bytes)
|
||||||
|
} catch {
|
||||||
|
clearInterval(client.keep)
|
||||||
|
clients.delete(client)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
lastSent = Date.now()
|
||||||
|
}
|
||||||
|
|
||||||
|
function json(data: unknown, status = 200): Response {
|
||||||
|
return new Response(JSON.stringify(data), {
|
||||||
|
status,
|
||||||
|
headers: { ...corsHeaders(), "Content-Type": "application/json" },
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
function asset(name: string, type: string): Response {
|
||||||
|
try {
|
||||||
|
const body = readFileSync(join(overlayDir, name))
|
||||||
|
return new Response(body, {
|
||||||
|
headers: {
|
||||||
|
...corsHeaders(),
|
||||||
|
"Content-Type": `${type}; charset=utf-8`,
|
||||||
|
"Cache-Control": "no-cache",
|
||||||
|
},
|
||||||
|
})
|
||||||
|
} catch {
|
||||||
|
return new Response(`Missing asset: ${name}`, {
|
||||||
|
status: 404,
|
||||||
|
headers: corsHeaders(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function stream(): Response {
|
||||||
|
let client: Client | undefined
|
||||||
|
const body = new ReadableStream<Uint8Array>({
|
||||||
|
start(controller) {
|
||||||
|
const keep = setInterval(() => {
|
||||||
|
try {
|
||||||
|
controller.enqueue(encoder.encode(": ping\n\n"))
|
||||||
|
} catch {
|
||||||
|
clearInterval(keep)
|
||||||
|
}
|
||||||
|
}, 15000)
|
||||||
|
client = { controller, keep }
|
||||||
|
clients.add(client)
|
||||||
|
controller.enqueue(encoder.encode("retry: 3000\n\n"))
|
||||||
|
controller.enqueue(encoder.encode(`data: ${JSON.stringify(latest)}\n\n`))
|
||||||
|
},
|
||||||
|
cancel() {
|
||||||
|
if (client) {
|
||||||
|
clearInterval(client.keep)
|
||||||
|
clients.delete(client)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
})
|
||||||
|
return new Response(body, {
|
||||||
|
headers: {
|
||||||
|
...corsHeaders(),
|
||||||
|
"Content-Type": "text/event-stream",
|
||||||
|
"Cache-Control": "no-cache",
|
||||||
|
Connection: "keep-alive",
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const server = Bun.serve({
|
||||||
|
hostname: opts.host,
|
||||||
|
port: opts.port,
|
||||||
|
fetch(req) {
|
||||||
|
const url = new URL(req.url)
|
||||||
|
if (req.method === "OPTIONS") {
|
||||||
|
return new Response(null, { status: 204, headers: corsHeaders() })
|
||||||
|
}
|
||||||
|
switch (url.pathname) {
|
||||||
|
case "/health":
|
||||||
|
return json({ ok: true, snapshot: latest })
|
||||||
|
case "/speed":
|
||||||
|
return json(latest)
|
||||||
|
case "/stream":
|
||||||
|
return stream()
|
||||||
|
case "/overlay.js":
|
||||||
|
return asset("overlay.js", "text/javascript")
|
||||||
|
case "/overlay.css":
|
||||||
|
return asset("overlay.css", "text/css")
|
||||||
|
default:
|
||||||
|
return json({ error: "not_found" }, 404)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const port = server.port ?? opts.port
|
||||||
|
|
||||||
|
return {
|
||||||
|
port,
|
||||||
|
url: `http://${opts.host}:${port}`,
|
||||||
|
publish(snapshot) {
|
||||||
|
latest = snapshot
|
||||||
|
const now = Date.now()
|
||||||
|
const wait = 150 - (now - lastSent)
|
||||||
|
if (wait <= 0) {
|
||||||
|
if (pending) {
|
||||||
|
clearTimeout(pending)
|
||||||
|
pending = null
|
||||||
|
}
|
||||||
|
flush()
|
||||||
|
} else if (!pending) {
|
||||||
|
pending = setTimeout(() => {
|
||||||
|
pending = null
|
||||||
|
flush()
|
||||||
|
}, wait)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
stop() {
|
||||||
|
if (pending) clearTimeout(pending)
|
||||||
|
for (const client of clients) clearInterval(client.keep)
|
||||||
|
clients.clear()
|
||||||
|
server.stop(true)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,232 @@
|
|||||||
|
import type {
|
||||||
|
AssistantLike,
|
||||||
|
SessionStatusLike,
|
||||||
|
SpeedSnapshot,
|
||||||
|
SpeedState,
|
||||||
|
TrackerOptions,
|
||||||
|
} from "./types"
|
||||||
|
|
||||||
|
interface Sample {
|
||||||
|
t: number
|
||||||
|
tokens: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export class Tracker {
|
||||||
|
private windowMs: number
|
||||||
|
private idleTimeoutMs: number
|
||||||
|
private now: () => number
|
||||||
|
private listeners = new Set<(snapshot: SpeedSnapshot) => void>()
|
||||||
|
|
||||||
|
private sessionID: string | null = null
|
||||||
|
private messageID: string | null = null
|
||||||
|
private model: string | null = null
|
||||||
|
private providerID: string | null = null
|
||||||
|
private startedAt = 0
|
||||||
|
private samples: Sample[] = []
|
||||||
|
private lastOutput = 0
|
||||||
|
private estTokens = 0
|
||||||
|
private realActive = false
|
||||||
|
private completedAt: number | null = null
|
||||||
|
private finalRate = 0
|
||||||
|
private state: SpeedState = "idle"
|
||||||
|
private lastActivity = 0
|
||||||
|
private busy = false
|
||||||
|
|
||||||
|
private get stuckTimeoutMs(): number {
|
||||||
|
return Math.max(this.idleTimeoutMs * 15, 60000)
|
||||||
|
}
|
||||||
|
|
||||||
|
constructor(opts: TrackerOptions = {}) {
|
||||||
|
this.windowMs = opts.windowMs ?? 4000
|
||||||
|
this.idleTimeoutMs = opts.idleTimeoutMs ?? 4000
|
||||||
|
this.now = opts.now ?? Date.now
|
||||||
|
}
|
||||||
|
|
||||||
|
onChange(listener: (snapshot: SpeedSnapshot) => void): () => void {
|
||||||
|
this.listeners.add(listener)
|
||||||
|
return () => {
|
||||||
|
this.listeners.delete(listener)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private emit(): void {
|
||||||
|
const snapshot = this.snapshot()
|
||||||
|
for (const listener of this.listeners) listener(snapshot)
|
||||||
|
}
|
||||||
|
|
||||||
|
private startMessage(info: AssistantLike, created: number): void {
|
||||||
|
this.sessionID = info.sessionID
|
||||||
|
this.messageID = info.id
|
||||||
|
this.model = info.modelID ?? null
|
||||||
|
this.providerID = info.providerID ?? null
|
||||||
|
this.startedAt = created
|
||||||
|
this.samples = [{ t: created, tokens: 0 }]
|
||||||
|
this.lastOutput = 0
|
||||||
|
this.estTokens = 0
|
||||||
|
this.realActive = false
|
||||||
|
this.completedAt = null
|
||||||
|
this.finalRate = 0
|
||||||
|
this.state = "streaming"
|
||||||
|
this.busy = true
|
||||||
|
this.lastActivity = this.now()
|
||||||
|
}
|
||||||
|
|
||||||
|
onMessageUpdated(info: AssistantLike): void {
|
||||||
|
if (info.role !== "assistant") return
|
||||||
|
const now = this.now()
|
||||||
|
const streaming = !info.time?.completed
|
||||||
|
|
||||||
|
if (this.sessionID !== info.sessionID) {
|
||||||
|
if (!streaming) return
|
||||||
|
this.startMessage(info, info.time?.created ?? now)
|
||||||
|
} else if (this.messageID !== info.id) {
|
||||||
|
if (this.messageID === null || streaming) {
|
||||||
|
this.startMessage(info, info.time?.created ?? now)
|
||||||
|
} else {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
this.model = info.modelID ?? this.model
|
||||||
|
this.providerID = info.providerID ?? this.providerID
|
||||||
|
}
|
||||||
|
|
||||||
|
const output = info.tokens?.output ?? 0
|
||||||
|
if (output > this.lastOutput) {
|
||||||
|
this.lastOutput = output
|
||||||
|
this.realActive = true
|
||||||
|
}
|
||||||
|
const effective = this.realActive ? output : Math.max(output, this.estTokens)
|
||||||
|
this.pushSample(effective, now)
|
||||||
|
this.state = "streaming"
|
||||||
|
this.busy = true
|
||||||
|
|
||||||
|
if (info.time?.completed) this.finalize(info.time.completed)
|
||||||
|
this.emit()
|
||||||
|
}
|
||||||
|
|
||||||
|
onPartDelta(sessionID: string, delta: string): void {
|
||||||
|
if (this.sessionID !== sessionID) return
|
||||||
|
if (this.realActive) return
|
||||||
|
if (!delta) return
|
||||||
|
this.estTokens += delta.length / 4
|
||||||
|
this.pushSample(Math.max(this.lastOutput, this.estTokens))
|
||||||
|
this.state = "streaming"
|
||||||
|
this.emit()
|
||||||
|
}
|
||||||
|
|
||||||
|
onSessionStatus(sessionID: string, status: SessionStatusLike): void {
|
||||||
|
if (status.type === "busy") {
|
||||||
|
if (this.sessionID !== sessionID) {
|
||||||
|
this.sessionID = sessionID
|
||||||
|
this.messageID = null
|
||||||
|
this.model = null
|
||||||
|
this.providerID = null
|
||||||
|
this.startedAt = this.now()
|
||||||
|
this.samples = []
|
||||||
|
this.lastOutput = 0
|
||||||
|
this.estTokens = 0
|
||||||
|
this.realActive = false
|
||||||
|
this.completedAt = null
|
||||||
|
this.finalRate = 0
|
||||||
|
}
|
||||||
|
this.busy = true
|
||||||
|
this.state = this.completedAt ? "finished" : "streaming"
|
||||||
|
this.lastActivity = this.now()
|
||||||
|
this.emit()
|
||||||
|
} else if (status.type === "idle") {
|
||||||
|
this.onSessionIdle(sessionID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
onSessionIdle(sessionID: string): void {
|
||||||
|
if (this.sessionID !== sessionID) return
|
||||||
|
this.busy = false
|
||||||
|
if (this.state === "streaming") this.finalize()
|
||||||
|
}
|
||||||
|
|
||||||
|
refresh(): void {
|
||||||
|
const now = this.now()
|
||||||
|
const before = this.state
|
||||||
|
if (
|
||||||
|
this.state === "streaming" &&
|
||||||
|
now - this.lastActivity > this.idleTimeoutMs &&
|
||||||
|
(!this.busy || now - this.lastActivity > this.stuckTimeoutMs)
|
||||||
|
) {
|
||||||
|
this.state = "idle"
|
||||||
|
} else if (
|
||||||
|
this.state === "finished" &&
|
||||||
|
this.completedAt !== null &&
|
||||||
|
now - this.completedAt > this.idleTimeoutMs * 3
|
||||||
|
) {
|
||||||
|
this.state = "idle"
|
||||||
|
}
|
||||||
|
if (this.state !== before) this.emit()
|
||||||
|
}
|
||||||
|
|
||||||
|
private pushSample(tokens: number, t = this.now()): void {
|
||||||
|
const last = this.samples[this.samples.length - 1]
|
||||||
|
if (last && last.tokens === tokens && t - last.t < 250) return
|
||||||
|
this.samples.push({ t, tokens })
|
||||||
|
const cutoff = t - this.windowMs
|
||||||
|
while (this.samples.length > 2 && this.samples[1].t < cutoff) {
|
||||||
|
this.samples.shift()
|
||||||
|
}
|
||||||
|
this.lastActivity = t
|
||||||
|
}
|
||||||
|
|
||||||
|
private rate(): number {
|
||||||
|
const samples = this.samples
|
||||||
|
if (samples.length === 0) return 0
|
||||||
|
const cutoff = this.now() - this.windowMs
|
||||||
|
let i = 0
|
||||||
|
while (i < samples.length - 1 && samples[i + 1].t < cutoff) i++
|
||||||
|
const first = samples[i]
|
||||||
|
const last = samples[samples.length - 1]
|
||||||
|
const dt = (last.t - first.t) / 1000
|
||||||
|
if (dt <= 0) {
|
||||||
|
const total = (this.now() - this.startedAt) / 1000
|
||||||
|
return total > 0 ? last.tokens / total : 0
|
||||||
|
}
|
||||||
|
const value = (last.tokens - first.tokens) / dt
|
||||||
|
return value > 0 ? value : 0
|
||||||
|
}
|
||||||
|
|
||||||
|
private finalize(completedAt?: number): void {
|
||||||
|
if (!this.sessionID) return
|
||||||
|
const t = completedAt ?? this.now()
|
||||||
|
const output = Math.max(this.lastOutput, this.estTokens)
|
||||||
|
this.pushSample(output, t)
|
||||||
|
this.completedAt = t
|
||||||
|
const duration = (t - this.startedAt) / 1000
|
||||||
|
this.finalRate = duration > 0 ? output / duration : this.rate()
|
||||||
|
this.state = "finished"
|
||||||
|
this.busy = false
|
||||||
|
this.emit()
|
||||||
|
}
|
||||||
|
|
||||||
|
snapshot(): SpeedSnapshot {
|
||||||
|
const now = this.now()
|
||||||
|
let state = this.state
|
||||||
|
if (
|
||||||
|
state === "streaming" &&
|
||||||
|
now - this.lastActivity > this.idleTimeoutMs &&
|
||||||
|
(!this.busy || now - this.lastActivity > this.stuckTimeoutMs)
|
||||||
|
) {
|
||||||
|
state = "idle"
|
||||||
|
}
|
||||||
|
let rate = 0
|
||||||
|
if (state === "streaming") rate = this.rate()
|
||||||
|
else if (state === "finished") rate = this.finalRate
|
||||||
|
return {
|
||||||
|
sessionID: this.sessionID,
|
||||||
|
messageID: this.messageID,
|
||||||
|
model: this.model,
|
||||||
|
providerID: this.providerID,
|
||||||
|
tokensPerSecond: Math.round(rate * 10) / 10,
|
||||||
|
outputTokens: Math.max(this.lastOutput, this.estTokens),
|
||||||
|
elapsedMs: this.sessionID ? now - this.startedAt : 0,
|
||||||
|
state,
|
||||||
|
updatedAt: now,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
export type SpeedState = "idle" | "streaming" | "finished"
|
||||||
|
|
||||||
|
export interface SpeedSnapshot {
|
||||||
|
sessionID: string | null
|
||||||
|
messageID: string | null
|
||||||
|
model: string | null
|
||||||
|
providerID: string | null
|
||||||
|
tokensPerSecond: number
|
||||||
|
outputTokens: number
|
||||||
|
elapsedMs: number
|
||||||
|
state: SpeedState
|
||||||
|
updatedAt: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TrackerOptions {
|
||||||
|
windowMs?: number
|
||||||
|
idleTimeoutMs?: number
|
||||||
|
now?: () => number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AssistantLike {
|
||||||
|
id: string
|
||||||
|
sessionID: string
|
||||||
|
role: string
|
||||||
|
modelID?: string
|
||||||
|
providerID?: string
|
||||||
|
time?: { created?: number; completed?: number }
|
||||||
|
tokens?: { output?: number }
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SessionStatusLike {
|
||||||
|
type: string
|
||||||
|
[key: string]: unknown
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
import { describe, expect, test } from "bun:test"
|
||||||
|
import { routeEvent } from "../src/events"
|
||||||
|
import { Tracker } from "../src/tracker"
|
||||||
|
|
||||||
|
function assistantEvent(output: number, completed?: number) {
|
||||||
|
return {
|
||||||
|
type: "message.updated",
|
||||||
|
properties: {
|
||||||
|
info: {
|
||||||
|
id: "m1",
|
||||||
|
sessionID: "s1",
|
||||||
|
role: "assistant",
|
||||||
|
modelID: "deepseek-v4-flash",
|
||||||
|
providerID: "selectel",
|
||||||
|
time: { created: 0, ...(completed ? { completed } : {}) },
|
||||||
|
tokens: { output },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("routeEvent", () => {
|
||||||
|
test("turns message.part.delta stream into a live estimate", () => {
|
||||||
|
let t = 0
|
||||||
|
const tracker = new Tracker({ windowMs: 4000, now: () => t })
|
||||||
|
|
||||||
|
routeEvent(tracker, {
|
||||||
|
type: "session.status",
|
||||||
|
properties: { sessionID: "s1", status: { type: "busy" } },
|
||||||
|
})
|
||||||
|
routeEvent(tracker, assistantEvent(0))
|
||||||
|
for (let i = 0; i < 30; i++) {
|
||||||
|
t += 60
|
||||||
|
routeEvent(tracker, {
|
||||||
|
type: "message.part.delta",
|
||||||
|
properties: {
|
||||||
|
sessionID: "s1",
|
||||||
|
messageID: "m1",
|
||||||
|
partID: "p1",
|
||||||
|
field: "text",
|
||||||
|
delta: "x".repeat(40),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const live = tracker.snapshot()
|
||||||
|
expect(live.state).toBe("streaming")
|
||||||
|
expect(live.tokensPerSecond).toBeGreaterThan(0)
|
||||||
|
expect(live.outputTokens).toBeGreaterThan(0)
|
||||||
|
|
||||||
|
routeEvent(tracker, assistantEvent(300, t))
|
||||||
|
const done = tracker.snapshot()
|
||||||
|
expect(done.state).toBe("finished")
|
||||||
|
expect(done.tokensPerSecond).toBeGreaterThan(0)
|
||||||
|
})
|
||||||
|
|
||||||
|
test("ignores unrelated and non-text deltas", () => {
|
||||||
|
let t = 0
|
||||||
|
const tracker = new Tracker({ now: () => t })
|
||||||
|
routeEvent(tracker, assistantEvent(0))
|
||||||
|
t = 500
|
||||||
|
routeEvent(tracker, {
|
||||||
|
type: "message.part.delta",
|
||||||
|
properties: { sessionID: "s1", field: "tool", delta: "x".repeat(400) },
|
||||||
|
})
|
||||||
|
routeEvent(tracker, { type: "unknown.event", properties: {} })
|
||||||
|
expect(tracker.snapshot().outputTokens).toBe(0)
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,181 @@
|
|||||||
|
import { describe, expect, test } from "bun:test"
|
||||||
|
import { Tracker } from "../src/tracker"
|
||||||
|
import type { AssistantLike } from "../src/types"
|
||||||
|
|
||||||
|
function assistant(
|
||||||
|
overrides: Partial<AssistantLike> = {},
|
||||||
|
): AssistantLike {
|
||||||
|
return {
|
||||||
|
id: "m1",
|
||||||
|
sessionID: "s1",
|
||||||
|
role: "assistant",
|
||||||
|
modelID: "deepseek-v4-flash",
|
||||||
|
providerID: "selectel",
|
||||||
|
...overrides,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("Tracker", () => {
|
||||||
|
test("computes live tokens per second from output deltas", () => {
|
||||||
|
let t = 0
|
||||||
|
const tracker = new Tracker({ windowMs: 4000, now: () => t })
|
||||||
|
|
||||||
|
tracker.onMessageUpdated(
|
||||||
|
assistant({ time: { created: 0 }, tokens: { output: 0 } }),
|
||||||
|
)
|
||||||
|
t = 1000
|
||||||
|
tracker.onMessageUpdated(
|
||||||
|
assistant({ time: { created: 0 }, tokens: { output: 50 } }),
|
||||||
|
)
|
||||||
|
t = 2000
|
||||||
|
tracker.onMessageUpdated(
|
||||||
|
assistant({ time: { created: 0 }, tokens: { output: 100 } }),
|
||||||
|
)
|
||||||
|
|
||||||
|
const snapshot = tracker.snapshot()
|
||||||
|
expect(snapshot.state).toBe("streaming")
|
||||||
|
expect(snapshot.tokensPerSecond).toBe(50)
|
||||||
|
expect(snapshot.outputTokens).toBe(100)
|
||||||
|
expect(snapshot.elapsedMs).toBe(2000)
|
||||||
|
})
|
||||||
|
|
||||||
|
test("uses a sliding window and drops old samples", () => {
|
||||||
|
let t = 0
|
||||||
|
const tracker = new Tracker({ windowMs: 2000, now: () => t })
|
||||||
|
const feed = (output: number) => {
|
||||||
|
tracker.onMessageUpdated(
|
||||||
|
assistant({ time: { created: 0 }, tokens: { output } }),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
feed(0)
|
||||||
|
for (const [time, output] of [
|
||||||
|
[1000, 10],
|
||||||
|
[2000, 20],
|
||||||
|
[3000, 30],
|
||||||
|
[4000, 40],
|
||||||
|
] as const) {
|
||||||
|
t = time
|
||||||
|
feed(output)
|
||||||
|
}
|
||||||
|
expect(tracker.snapshot().tokensPerSecond).toBe(10)
|
||||||
|
})
|
||||||
|
|
||||||
|
test("falls back to delta estimation when output tokens do not advance", () => {
|
||||||
|
let t = 0
|
||||||
|
const tracker = new Tracker({ windowMs: 4000, now: () => t })
|
||||||
|
tracker.onMessageUpdated(
|
||||||
|
assistant({ time: { created: 0 }, tokens: { output: 0 } }),
|
||||||
|
)
|
||||||
|
t = 1000
|
||||||
|
tracker.onPartDelta("s1", "x".repeat(40))
|
||||||
|
const snapshot = tracker.snapshot()
|
||||||
|
expect(snapshot.tokensPerSecond).toBe(10)
|
||||||
|
expect(snapshot.outputTokens).toBe(10)
|
||||||
|
})
|
||||||
|
|
||||||
|
test("prefers real tokens once they start advancing", () => {
|
||||||
|
let t = 0
|
||||||
|
const tracker = new Tracker({ windowMs: 4000, now: () => t })
|
||||||
|
tracker.onMessageUpdated(
|
||||||
|
assistant({ time: { created: 0 }, tokens: { output: 0 } }),
|
||||||
|
)
|
||||||
|
t = 1000
|
||||||
|
tracker.onPartDelta("s1", "x".repeat(40))
|
||||||
|
t = 2000
|
||||||
|
tracker.onMessageUpdated(
|
||||||
|
assistant({ time: { created: 0 }, tokens: { output: 100 } }),
|
||||||
|
)
|
||||||
|
t = 3000
|
||||||
|
tracker.onPartDelta("s1", "y".repeat(4000))
|
||||||
|
expect(tracker.snapshot().outputTokens).toBe(100)
|
||||||
|
})
|
||||||
|
|
||||||
|
test("finalises with the average rate on completion", () => {
|
||||||
|
let t = 0
|
||||||
|
const tracker = new Tracker({ windowMs: 4000, now: () => t })
|
||||||
|
tracker.onMessageUpdated(
|
||||||
|
assistant({ time: { created: 0 }, tokens: { output: 0 } }),
|
||||||
|
)
|
||||||
|
t = 2000
|
||||||
|
tracker.onMessageUpdated(
|
||||||
|
assistant({ time: { created: 0, completed: 2000 }, tokens: { output: 100 } }),
|
||||||
|
)
|
||||||
|
const snapshot = tracker.snapshot()
|
||||||
|
expect(snapshot.state).toBe("finished")
|
||||||
|
expect(snapshot.tokensPerSecond).toBe(50)
|
||||||
|
})
|
||||||
|
|
||||||
|
test("stays streaming while the session is busy even without updates", () => {
|
||||||
|
let t = 0
|
||||||
|
const tracker = new Tracker({ windowMs: 4000, idleTimeoutMs: 1000, now: () => t })
|
||||||
|
tracker.onMessageUpdated(
|
||||||
|
assistant({ time: { created: 0 }, tokens: { output: 0 } }),
|
||||||
|
)
|
||||||
|
t = 5000
|
||||||
|
expect(tracker.snapshot().state).toBe("streaming")
|
||||||
|
})
|
||||||
|
|
||||||
|
test("forces idle when a busy session stalls past the stuck ceiling", () => {
|
||||||
|
let t = 0
|
||||||
|
const tracker = new Tracker({ windowMs: 4000, idleTimeoutMs: 1000, now: () => t })
|
||||||
|
tracker.onMessageUpdated(
|
||||||
|
assistant({ time: { created: 0 }, tokens: { output: 0 } }),
|
||||||
|
)
|
||||||
|
t = 10000
|
||||||
|
expect(tracker.snapshot().state).toBe("streaming")
|
||||||
|
t = 61000
|
||||||
|
tracker.refresh()
|
||||||
|
expect(tracker.snapshot().state).toBe("idle")
|
||||||
|
})
|
||||||
|
|
||||||
|
test("goes idle after a finished message expires", () => {
|
||||||
|
let t = 0
|
||||||
|
const tracker = new Tracker({ windowMs: 4000, idleTimeoutMs: 1000, now: () => t })
|
||||||
|
tracker.onMessageUpdated(
|
||||||
|
assistant({ time: { created: 0 }, tokens: { output: 0 } }),
|
||||||
|
)
|
||||||
|
t = 1000
|
||||||
|
tracker.onMessageUpdated(
|
||||||
|
assistant({ time: { created: 0 }, tokens: { output: 20 } }),
|
||||||
|
)
|
||||||
|
t = 2000
|
||||||
|
tracker.onSessionIdle("s1")
|
||||||
|
expect(tracker.snapshot().state).toBe("finished")
|
||||||
|
t = 6000
|
||||||
|
tracker.refresh()
|
||||||
|
expect(tracker.snapshot().state).toBe("idle")
|
||||||
|
})
|
||||||
|
|
||||||
|
test("switches to the newly active session", () => {
|
||||||
|
let t = 0
|
||||||
|
const tracker = new Tracker({ windowMs: 4000, now: () => t })
|
||||||
|
tracker.onMessageUpdated(
|
||||||
|
assistant({ time: { created: 0 }, tokens: { output: 0 } }),
|
||||||
|
)
|
||||||
|
t = 1000
|
||||||
|
tracker.onMessageUpdated(
|
||||||
|
assistant({ time: { created: 0 }, tokens: { output: 30 } }),
|
||||||
|
)
|
||||||
|
tracker.onSessionStatus("s2", { type: "busy" })
|
||||||
|
const snapshot = tracker.snapshot()
|
||||||
|
expect(snapshot.sessionID).toBe("s2")
|
||||||
|
expect(snapshot.outputTokens).toBe(0)
|
||||||
|
expect(snapshot.state).toBe("streaming")
|
||||||
|
})
|
||||||
|
|
||||||
|
test("emits snapshots to listeners", () => {
|
||||||
|
let t = 0
|
||||||
|
const tracker = new Tracker({ now: () => t })
|
||||||
|
const seen: number[] = []
|
||||||
|
tracker.onChange((s) => seen.push(s.outputTokens))
|
||||||
|
tracker.onMessageUpdated(
|
||||||
|
assistant({ time: { created: 0 }, tokens: { output: 0 } }),
|
||||||
|
)
|
||||||
|
t = 1000
|
||||||
|
tracker.onMessageUpdated(
|
||||||
|
assistant({ time: { created: 0 }, tokens: { output: 25 } }),
|
||||||
|
)
|
||||||
|
expect(seen.length).toBeGreaterThanOrEqual(2)
|
||||||
|
expect(seen[seen.length - 1]).toBe(25)
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ESNext",
|
||||||
|
"module": "ESNext",
|
||||||
|
"moduleResolution": "bundler",
|
||||||
|
"lib": ["ESNext", "DOM", "DOM.Iterable"],
|
||||||
|
"strict": true,
|
||||||
|
"noEmit": true,
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"allowImportingTsExtensions": true,
|
||||||
|
"verbatimModuleSyntax": true,
|
||||||
|
"esModuleInterop": true,
|
||||||
|
"resolveJsonModule": true,
|
||||||
|
"forceConsistentCasingInFileNames": true
|
||||||
|
},
|
||||||
|
"include": ["src", "test"]
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
// ==UserScript==
|
||||||
|
// @name opencode token speed
|
||||||
|
// @namespace plagin-tokens
|
||||||
|
// @version 0.2.0
|
||||||
|
// @description Compact live tokens/sec line under each response in opencode web
|
||||||
|
// @match http://localhost:4096/*
|
||||||
|
// @match http://127.0.0.1:4096/*
|
||||||
|
// @run-at document-idle
|
||||||
|
// @grant none
|
||||||
|
// ==/UserScript==
|
||||||
|
|
||||||
|
;(function () {
|
||||||
|
window.__OTS_BASE__ = "http://127.0.0.1:7878"
|
||||||
|
if (document.getElementById("ots-loader")) return
|
||||||
|
var s = document.createElement("script")
|
||||||
|
s.id = "ots-loader"
|
||||||
|
s.src = window.__OTS_BASE__ + "/overlay.js"
|
||||||
|
document.body.appendChild(s)
|
||||||
|
})()
|
||||||
Reference in New Issue
Block a user