feat: add session history tracking and Canvas speed graph overlay

This commit is contained in:
Andrew Emelyaneko
2026-10-27 13:47:13 +03:00
parent ddda1b2829
commit eca52bbad0
8 changed files with 608 additions and 11 deletions
+3
View File
@@ -103,6 +103,9 @@ javascript:(()=>{const b="http://127.0.0.1:7878";window.__OTS_BASE__=b;const s=d
- `GET /speed` — последний снимок (JSON). - `GET /speed` — последний снимок (JSON).
- `GET /stream` — SSE-поток снимков. - `GET /stream` — SSE-поток снимков.
- `GET /health` — проверка живости + снимок. - `GET /health` — проверка живости + снимок.
- `GET /history` — история завершённых сессий и сэмплов.
- `GET /history/:sessionId` — история и статистика конкретной сессии.
- `GET /stats` — агрегированная статистика по всем сессиям.
- `GET /overlay.js`, `GET /overlay.css` — ресурсы оверлея. - `GET /overlay.js`, `GET /overlay.css` — ресурсы оверлея.
## Разработка ## Разработка
+5
View File
@@ -49,5 +49,10 @@ export function routeEvent(tracker: Tracker, event: unknown): void {
if (sessionID) tracker.onSessionIdle(sessionID) if (sessionID) tracker.onSessionIdle(sessionID)
break break
} }
case "message.completed": {
const info = properties.info as AssistantLike | undefined
if (info?.role === "assistant") tracker.onMessageUpdated(info)
break
}
} }
} }
+104
View File
@@ -50,3 +50,107 @@
animation: none; animation: none;
} }
} }
.ots-history-button {
position: fixed;
right: 16px;
bottom: 16px;
z-index: 99999;
padding: 8px 12px;
border: 1px solid var(--v2-border-border-strong, rgba(127,127,127,0.3));
border-radius: 999px;
background: var(--v2-surface-surface-raised, #1f2937);
color: var(--v2-text-text-base, #f9fafb);
font: 12px/1.2 ui-monospace, SFMono-Regular, Menlo, monospace;
cursor: pointer;
}
.ots-history-modal {
position: fixed;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
background: rgba(0, 0, 0, 0.45);
z-index: 100000;
}
.ots-history-panel {
width: min(880px, 92vw);
max-height: 88vh;
overflow: auto;
padding: 16px;
border-radius: 12px;
background: var(--v2-surface-surface-base, #111827);
color: var(--v2-text-text-base, #f9fafb);
box-shadow: 0 10px 40px rgba(0,0,0,0.4);
}
.ots-history-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 12px;
}
.ots-history-header h3 {
margin: 0;
font-size: 16px;
}
.ots-history-close {
border: 0;
background: transparent;
color: inherit;
cursor: pointer;
font-size: 16px;
}
.ots-history-layout {
display: grid;
grid-template-columns: 180px 1fr;
gap: 12px;
}
.ots-history-list {
display: flex;
flex-direction: column;
gap: 6px;
max-height: 360px;
overflow: auto;
}
.ots-history-item {
border: 1px solid var(--v2-border-border-subtle, rgba(127,127,127,0.25));
background: transparent;
color: inherit;
border-radius: 8px;
padding: 8px;
text-align: left;
cursor: pointer;
font: 11px/1.2 ui-monospace, SFMono-Regular, Menlo, monospace;
}
.ots-history-item.ots-selected {
border-color: #22c55e;
background: rgba(34,197,94,0.1);
}
.ots-history-canvas {
width: 100%;
height: auto;
border-radius: 8px;
background: rgba(127,127,127,0.08);
}
.ots-history-stats {
grid-column: 1 / -1;
margin-top: 10px;
font: 12px/1.4 ui-monospace, SFMono-Regular, Menlo, monospace;
color: var(--v2-text-text-muted, #9ca3af);
}
.ots-history-empty {
padding: 8px;
color: var(--v2-text-text-muted, #9ca3af);
}
+186
View File
@@ -20,6 +20,13 @@
} }
var current = null var current = null
var currentMsg = null var currentMsg = null
var historyData = null
var sessionStats = null
var historyButton = null
var historyModal = null
var canvas = null
var canvasCtx = null
var selectedSessionId = null
function fmt(value) { function fmt(value) {
var n = Number(value) var n = Number(value)
@@ -114,8 +121,187 @@
observer.observe(document.body, { childList: true, subtree: true }) observer.observe(document.body, { childList: true, subtree: true })
} }
function statsForSession(id) {
if (!historyData || !id) return null
return historyData[id] || null
}
function createHistoryButton() {
if (historyButton && historyButton.isConnected) return
historyButton = el("button", "ots-history-button", "История")
historyButton.type = "button"
historyButton.addEventListener("click", showHistoryModal)
document.body.appendChild(historyButton)
}
function clearHistoryModal() {
if (historyModal && historyModal.parentNode) historyModal.parentNode.removeChild(historyModal)
historyModal = null
canvas = null
canvasCtx = null
selectedSessionId = null
}
function fetchHistory() {
return fetch(BASE + "/history").then(function (res) { return res.json() }).then(function (data) {
historyData = data || {}
return historyData
}).catch(function () { historyData = {}; return historyData })
}
function fetchSessionHistory(id) {
return fetch(BASE + "/history/" + encodeURIComponent(id)).then(function (res) { return res.json() }).catch(function () { return null })
}
function fetchStats() {
return fetch(BASE + "/stats").then(function (res) { return res.json() }).catch(function () { return null })
}
function canvasDrawGrid(ctx, width, height) {
ctx.clearRect(0, 0, width, height)
ctx.strokeStyle = "rgba(127,127,127,0.2)"
ctx.lineWidth = 1
for (var i = 0; i <= 5; i++) {
var y = (height / 5) * i
ctx.beginPath()
ctx.moveTo(0, y)
ctx.lineTo(width, y)
ctx.stroke()
}
for (var j = 0; j <= 5; j++) {
var x = (width / 5) * j
ctx.beginPath()
ctx.moveTo(x, 0)
ctx.lineTo(x, height)
ctx.stroke()
}
}
function canvasDrawLine(ctx, points, color) {
if (!points || points.length < 2) return
ctx.strokeStyle = color || "#22c55e"
ctx.lineWidth = 2
ctx.beginPath()
ctx.moveTo(points[0].x, points[0].y)
for (var i = 1; i < points.length; i++) ctx.lineTo(points[i].x, points[i].y)
ctx.stroke()
}
function canvasDrawPoints(ctx, points, color) {
if (!points) return
ctx.fillStyle = color || "#22c55e"
for (var i = 0; i < points.length; i++) {
ctx.beginPath()
ctx.arc(points[i].x, points[i].y, 3, 0, Math.PI * 2)
ctx.fill()
}
}
function buildCanvasPoints(session) {
if (!session || !session.samples || !session.samples.length) return []
var startedAt = session.startedAt || session.startTime || 0
var maxx = 0
var maxy = 0
var raw = session.samples.map(function (s) {
var dt = (s.t - startedAt) / 1000
var rate = dt > 0 ? s.tokens / dt : 0
if (dt > maxx) maxx = dt
if (rate > maxy) maxy = rate
return { dt: dt, rate: rate }
})
var w = canvas ? canvas.width : 560
var h = canvas ? canvas.height : 260
var pad = 24
return raw.map(function (p) {
return {
x: pad + (maxx > 0 ? (p.dt / maxx) * (w - pad * 2) : 0),
y: h - pad - (maxy > 0 ? (p.rate / maxy) * (h - pad * 2) : 0),
}
})
}
function canvasRender() {
if (!canvas || !canvasCtx) return
var w = canvas.width
var h = canvas.height
canvasDrawGrid(canvasCtx, w, h)
var session = statsForSession(selectedSessionId)
var points = buildCanvasPoints(session)
canvasDrawLine(canvasCtx, points, "#22c55e")
canvasDrawPoints(canvasCtx, points, "#16a34a")
}
function renderHistoryModal() {
if (!historyModal) return
var list = historyModal.querySelector(".ots-history-list")
var statsEl = historyModal.querySelector(".ots-history-stats")
if (list) {
list.innerHTML = ""
var ids = historyData ? Object.keys(historyData) : []
if (!ids.length) {
list.appendChild(el("div", "ots-history-empty", "История пуста"))
} else {
ids.forEach(function (id) {
var item = el("button", "ots-history-item", id)
if (id === selectedSessionId) item.classList.add("ots-selected")
item.type = "button"
item.addEventListener("click", function () {
selectedSessionId = id
renderHistoryModal()
})
list.appendChild(item)
})
}
}
if (statsEl) {
var session = statsForSession(selectedSessionId)
if (session) {
statsEl.textContent =
"сессия " + selectedSessionId +
" | токенов: " + (session.outputTokens || session.totalTokens || 0) +
" | сред.: " + Number(session.avgTokensPerSecond || session.finalRate || 0).toFixed(1) + " ток/с" +
" | сэмплов: " + (session.sampleCount || (session.samples || []).length || 0)
} else {
statsEl.textContent = "Выберите сессию"
}
}
canvasRender()
}
function showHistoryModal() {
if (historyModal) return
historyModal = el("div", "ots-history-modal")
var panel = el("div", "ots-history-panel")
var header = el("div", "ots-history-header")
header.appendChild(el("h3", "", "История скорости"))
var closeBtn = el("button", "ots-history-close", "✕")
closeBtn.type = "button"
closeBtn.addEventListener("click", clearHistoryModal)
header.appendChild(closeBtn)
panel.appendChild(header)
var layout = el("div", "ots-history-layout")
layout.appendChild(el("div", "ots-history-list"))
canvas = document.createElement("canvas")
canvas.className = "ots-history-canvas"
canvas.width = 560
canvas.height = 260
layout.appendChild(canvas)
layout.appendChild(el("div", "ots-history-stats"))
panel.appendChild(layout)
historyModal.appendChild(panel)
document.body.appendChild(historyModal)
canvasCtx = canvas.getContext("2d")
fetchHistory().then(function (data) {
var ids = Object.keys(data || {})
if (!selectedSessionId && ids.length) selectedSessionId = ids[0]
renderHistoryModal()
})
}
function mount() { function mount() {
if (!document.body) return if (!document.body) return
createHistoryButton()
if (!document.getElementById("ots-style")) { if (!document.getElementById("ots-style")) {
var link = document.createElement("link") var link = document.createElement("link")
link.id = "ots-style" link.id = "ots-style"
+19 -3
View File
@@ -3,7 +3,7 @@ import { loadConfig } from "./config"
import { routeEvent } from "./events" import { routeEvent } from "./events"
import { startServer, type SpeedServer } from "./server" import { startServer, type SpeedServer } from "./server"
import { Tracker } from "./tracker" import { Tracker } from "./tracker"
import type { SpeedSnapshot } from "./types" import type { SpeedSnapshot, SessionStats } from "./types"
interface SharedServer { interface SharedServer {
server: SpeedServer server: SpeedServer
@@ -26,6 +26,11 @@ function acquireServer(
host: string, host: string,
port: number, port: number,
getSnapshot: () => SpeedSnapshot, getSnapshot: () => SpeedSnapshot,
providers: {
getAllSessionStats?: () => SessionStats[]
getSessionStats?: (sessionID: string) => SessionStats | null
getCurrentSessionStats?: () => SessionStats | null
} = {},
): SpeedServer { ): SpeedServer {
const reg = registry() const reg = registry()
const key = `${host}:${port}` const key = `${host}:${port}`
@@ -34,7 +39,14 @@ function acquireServer(
existing.refs += 1 existing.refs += 1
return existing.server return existing.server
} }
const server = startServer({ host, port, getSnapshot }) const server = startServer({
host,
port,
getSnapshot,
getAllSessionStats: providers.getAllSessionStats,
getSessionStats: providers.getSessionStats,
getCurrentSessionStats: providers.getCurrentSessionStats,
})
reg.set(key, { server, refs: 1 }) reg.set(key, { server, refs: 1 })
return server return server
} }
@@ -60,7 +72,11 @@ export const TokenSpeedPlugin: Plugin = async ({ client }) => {
let server: SpeedServer | null = null let server: SpeedServer | null = null
try { try {
server = acquireServer(config.host, config.port, () => tracker.snapshot()) server = acquireServer(config.host, config.port, () => tracker.snapshot(), {
getAllSessionStats: () => tracker.getAllSessionStats(),
getSessionStats: (sessionID) => tracker.getSessionStats(sessionID),
getCurrentSessionStats: () => tracker.getCurrentSessionStats(),
})
await client.app await client.app
.log({ .log({
body: { body: {
+67 -2
View File
@@ -1,11 +1,15 @@
import { readFileSync } from "node:fs" import { readFileSync } from "node:fs"
import { join } from "node:path" import { join } from "node:path"
import type { SpeedSnapshot } from "./types" import type { SpeedSnapshot, SessionStats, SpeedHistory } from "./types"
export interface SpeedServerOptions { export interface SpeedServerOptions {
host: string host: string
port: number port: number
getSnapshot: () => SpeedSnapshot getSnapshot: () => SpeedSnapshot
getHistory?: () => SpeedHistory[]
getAllSessionStats?: () => SessionStats[]
getSessionStats?: (sessionID: string) => SessionStats | null
getCurrentSessionStats?: () => SessionStats | null
} }
export interface SpeedServer { export interface SpeedServer {
@@ -33,10 +37,26 @@ function corsHeaders(): Record<string, string> {
export function startServer(opts: SpeedServerOptions): SpeedServer { export function startServer(opts: SpeedServerOptions): SpeedServer {
const encoder = new TextEncoder() const encoder = new TextEncoder()
const clients = new Set<Client>() const clients = new Set<Client>()
let latest = opts.getSnapshot() let latest: any = { ...opts.getSnapshot(), history: {}, currentSession: {} }
let lastSent = 0 let lastSent = 0
let pending: ReturnType<typeof setTimeout> | null = null let pending: ReturnType<typeof setTimeout> | null = null
function allHistoryMap(): Record<string, SessionStats> {
const map: Record<string, SessionStats> = {}
for (const session of opts.getAllSessionStats?.() ?? []) {
map[session.sessionID] = session
}
return map
}
function currentSessionSamplesMap(): Record<string, number[]> {
const session = opts.getCurrentSessionStats?.()
if (!session?.sessionID) return {}
return {
[session.sessionID]: (session.samples ?? []).map((sample) => sample.tokens),
}
}
function flush(): void { function flush(): void {
const bytes = encoder.encode(`data: ${JSON.stringify(latest)}\n\n`) const bytes = encoder.encode(`data: ${JSON.stringify(latest)}\n\n`)
for (const client of clients) { for (const client of clients) {
@@ -50,6 +70,14 @@ export function startServer(opts: SpeedServerOptions): SpeedServer {
lastSent = Date.now() lastSent = Date.now()
} }
function updateHistory() {
latest = {
...opts.getSnapshot(),
history: allHistoryMap(),
currentSession: currentSessionSamplesMap(),
}
}
function json(data: unknown, status = 200): Response { function json(data: unknown, status = 200): Response {
return new Response(JSON.stringify(data), { return new Response(JSON.stringify(data), {
status, status,
@@ -57,6 +85,36 @@ export function startServer(opts: SpeedServerOptions): SpeedServer {
}) })
} }
function stats(): Response {
updateHistory()
const sessions = opts.getAllSessionStats?.() ?? []
return json({
totalSessions: sessions.length,
currentSession: latest.currentSession,
totalSamples: sessions.reduce((sum, s) => sum + (s.sampleCount || 0), 0),
avgResponseTime:
sessions.length > 0
? sessions.reduce(
(sum, s) => sum + (s.avgTokensPerSecond || s.avgRate || 0),
0,
) / sessions.length
: 0,
})
}
function sessionHistory(sessionID: string): Response {
const session = opts.getSessionStats?.(sessionID)
if (!session) {
return json({ error: "session_not_found" }, 404)
}
return json(session)
}
function getHistory(): Response {
updateHistory()
return json(latest.history ?? {})
}
function asset(name: string, type: string): Response { function asset(name: string, type: string): Response {
try { try {
const body = readFileSync(join(overlayDir, name)) const body = readFileSync(join(overlayDir, name))
@@ -116,11 +174,18 @@ export function startServer(opts: SpeedServerOptions): SpeedServer {
if (req.method === "OPTIONS") { if (req.method === "OPTIONS") {
return new Response(null, { status: 204, headers: corsHeaders() }) return new Response(null, { status: 204, headers: corsHeaders() })
} }
const sessionMatch = url.pathname.match(/^\/(stats|history)\/([^/]+)$/)
if (sessionMatch) return sessionHistory(decodeURIComponent(sessionMatch[2]))
switch (url.pathname) { switch (url.pathname) {
case "/health": case "/health":
return json({ ok: true, snapshot: latest }) return json({ ok: true, snapshot: latest })
case "/speed": case "/speed":
return json(latest) return json(latest)
case "/stats":
return stats()
case "/history":
return getHistory()
case "/stream": case "/stream":
return stream() return stream()
case "/overlay.js": case "/overlay.js":
+167 -1
View File
@@ -4,6 +4,9 @@ import type {
SpeedSnapshot, SpeedSnapshot,
SpeedState, SpeedState,
TrackerOptions, TrackerOptions,
SpeedHistory,
SessionStats,
SpeedSample,
} from "./types" } from "./types"
interface Sample { interface Sample {
@@ -32,6 +35,11 @@ export class Tracker {
private lastActivity = 0 private lastActivity = 0
private busy = false private busy = false
private history: SpeedHistory[] = []
private sessionStartTimestamps = new Map<string, number>()
private sessionEndTimestamps = new Map<string, number>()
private sessionSampleHistory = new Map<string, Sample[]>()
private get stuckTimeoutMs(): number { private get stuckTimeoutMs(): number {
return Math.max(this.idleTimeoutMs * 15, 60000) return Math.max(this.idleTimeoutMs * 15, 60000)
} }
@@ -69,6 +77,9 @@ export class Tracker {
this.state = "streaming" this.state = "streaming"
this.busy = true this.busy = true
this.lastActivity = this.now() this.lastActivity = this.now()
if (!this.sessionSampleHistory.has(this.sessionID!)) {
this.sessionSampleHistory.set(this.sessionID!, [])
}
} }
onMessageUpdated(info: AssistantLike): void { onMessageUpdated(info: AssistantLike): void {
@@ -79,9 +90,15 @@ export class Tracker {
if (this.sessionID !== info.sessionID) { if (this.sessionID !== info.sessionID) {
if (!streaming) return if (!streaming) return
this.startMessage(info, info.time?.created ?? now) this.startMessage(info, info.time?.created ?? now)
if (!this.sessionSampleHistory.has(this.sessionID!)) {
this.sessionSampleHistory.set(this.sessionID!, [])
}
} else if (this.messageID !== info.id) { } else if (this.messageID !== info.id) {
if (this.messageID === null || streaming) { if (this.messageID === null || streaming) {
this.startMessage(info, info.time?.created ?? now) this.startMessage(info, info.time?.created ?? now)
if (!this.sessionSampleHistory.has(this.sessionID!)) {
this.sessionSampleHistory.set(this.sessionID!, [])
}
} else { } else {
return return
} }
@@ -128,6 +145,10 @@ export class Tracker {
this.realActive = false this.realActive = false
this.completedAt = null this.completedAt = null
this.finalRate = 0 this.finalRate = 0
this.sessionStartTimestamps.set(sessionID, this.startedAt)
}
if (!this.sessionSampleHistory.has(this.sessionID!)) {
this.sessionSampleHistory.set(this.sessionID!, [])
} }
this.busy = true this.busy = true
this.state = this.completedAt ? "finished" : "streaming" this.state = this.completedAt ? "finished" : "streaming"
@@ -165,12 +186,22 @@ export class Tracker {
private pushSample(tokens: number, t = this.now()): void { private pushSample(tokens: number, t = this.now()): void {
const last = this.samples[this.samples.length - 1] const last = this.samples[this.samples.length - 1]
if (last && last.tokens === tokens && t - last.t < 250) return const dedup = !!(last && last.tokens === tokens && t - last.t < 250)
if (!dedup) {
this.samples.push({ t, tokens }) this.samples.push({ t, tokens })
const cutoff = t - this.windowMs const cutoff = t - this.windowMs
while (this.samples.length > 2 && this.samples[1].t < cutoff) { while (this.samples.length > 2 && this.samples[1].t < cutoff) {
this.samples.shift() this.samples.shift()
} }
}
if (this.sessionID) {
const sessionSamples = this.sessionSampleHistory.get(this.sessionID!) ?? []
const sessionLast = sessionSamples[sessionSamples.length - 1]
if (!(sessionLast && sessionLast.tokens === tokens && t - sessionLast.t < 250)) {
sessionSamples.push({ t, tokens })
}
this.sessionSampleHistory.set(this.sessionID!, sessionSamples)
}
this.lastActivity = t this.lastActivity = t
} }
@@ -201,6 +232,27 @@ export class Tracker {
this.finalRate = duration > 0 ? output / duration : this.rate() this.finalRate = duration > 0 ? output / duration : this.rate()
this.state = "finished" this.state = "finished"
this.busy = false this.busy = false
const sessionData: SpeedHistory = {
id: this.sessionID!,
sessionID: this.sessionID!,
messageID: this.messageID,
model: this.model,
providerID: this.providerID,
startedAt: this.startedAt,
completedAt: t,
outputTokens: output,
rate: this.rate(),
finalRate: this.finalRate,
samples: [...this.samples],
tokensPerSecond: this.finalRate,
elapsedMs: t - this.startedAt,
startTime: this.startedAt,
endTime: t,
}
this.history.push(sessionData)
if (this.sessionID && this.sessionStartTimestamps.has(this.sessionID)) {
this.sessionEndTimestamps.set(this.sessionID, t)
}
this.emit() this.emit()
} }
@@ -229,4 +281,118 @@ export class Tracker {
updatedAt: now, updatedAt: now,
} }
} }
getHistory(sessionID?: string): SpeedHistory[] {
if (sessionID) {
return this.history.filter(h => h.id === sessionID)
}
return [...this.history]
}
getRecentHistory(limit: number = 20): SpeedHistory[] {
return [...this.history].reverse().slice(0, limit)
}
getSessionStats(sessionID: string): SessionStats | null {
const messages = this.history.filter(
h => h.id === sessionID || h.sessionID === sessionID,
)
if (messages.length === 0) return null
const first = messages[0]
const last = messages[messages.length - 1]
const samples =
this.sessionSampleHistory.get(sessionID) || first.samples || []
const endTime = last.completedAt || Date.now()
const durations = samples.map(s => (endTime - s.t) || 0)
const safeDurations = durations.length ? durations : [0]
const minDuration = Math.min(...safeDurations)
const maxDuration = Math.max(...safeDurations)
const avgDuration = durations.length
? durations.reduce((a, b) => a + b, 0) / durations.length
: 0
const messageRates = messages
.map(m => m.finalRate)
.filter(v => Number.isFinite(v))
const minMessageRate = messageRates.length
? Math.min(...messageRates)
: (first.finalRate ?? 0)
const maxMessageRate = messageRates.length
? Math.max(...messageRates)
: (first.finalRate ?? 0)
const avgMessageRate = messageRates.length
? messageRates.reduce((a, b) => a + b, 0) / messageRates.length
: (first.finalRate ?? 0)
const totalTokens = messages.reduce((sum, m) => sum + m.outputTokens, 0)
const totalElapsedMs = messages.reduce(
(sum, m) => sum + Math.max(0, m.completedAt - m.startedAt),
0,
)
const startTime = Math.min(...messages.map(m => m.startedAt))
const completedAt = Math.max(...messages.map(m => m.completedAt))
const samplesForRate =
first.samples && first.samples.length > 1 ? first.samples.slice(1) : []
const computedMinRate = samplesForRate.length
? Math.min(...samplesForRate.map(s => rateForSample(s, first.startedAt)))
: minMessageRate
const computedMaxRate = samplesForRate.length
? Math.max(...samplesForRate.map(s => rateForSample(s, first.startedAt)))
: maxMessageRate
const computedAvgRate = samplesForRate.length
? samplesForRate.reduce(
(acc, s) => acc + rateForSample(s, first.startedAt),
0,
) / samplesForRate.length
: avgMessageRate
return {
sessionID,
messageID: first.messageID,
model: last.model ?? first.model,
providerID: last.providerID ?? first.providerID,
startedAt: first.startedAt,
completedAt,
outputTokens: totalTokens,
finalRate: totalElapsedMs > 0 ? totalTokens / (totalElapsedMs / 1000) : avgMessageRate,
minRate: computedMinRate,
maxRate: computedMaxRate,
avgRate: computedAvgRate,
minDuration,
maxDuration,
avgDuration: avgDuration / 1000,
sampleCount: samples.length,
samples: samples as SpeedSample[],
messageCount: messages.length,
totalTokens,
totalElapsedMs,
avgTokensPerSecond:
totalElapsedMs > 0 ? totalTokens / (totalElapsedMs / 1000) : avgMessageRate,
minTokensPerSecond: computedMinRate,
maxTokensPerSecond: computedMaxRate,
startTime,
endTime: completedAt,
}
}
getCurrentSessionStats(sessionID?: string): SessionStats | null {
const targetID = sessionID || this.sessionID
if (!targetID) return null
return this.getSessionStats(targetID as string)
}
getAllSessionStats(): SessionStats[] {
const ids = Array.from(
new Set(this.history.map(session => session.sessionID || session.id)),
)
return ids
.map(id => this.getSessionStats(id))
.filter((stats): stats is SessionStats => stats !== null)
}
}
function rateForSample(sample: { t: number, tokens: number }, startedAt: number): number {
const duration = sample.t - startedAt
return duration > 0 ? sample.tokens / (duration / 1000) : 0
} }
+52
View File
@@ -12,6 +12,58 @@ export interface SpeedSnapshot {
updatedAt: number updatedAt: number
} }
export interface SpeedSample {
t: number
tokens: number
}
export interface SpeedHistory {
id: string
sessionID: string
messageID: string | null
model: string | null
providerID: string | null
startedAt: number
completedAt: number
outputTokens: number
rate: number
finalRate: number
samples: SpeedSample[]
// Compatibility aliases for aggregate consumers
tokensPerSecond: number
elapsedMs: number
startTime: number
endTime: number
}
export interface SessionStats {
sessionID: string
messageID: string | null
model: string | null
providerID: string | null
startedAt: number
completedAt: number
outputTokens: number
finalRate: number
minRate: number
maxRate: number
avgRate: number
minDuration: number
maxDuration: number
avgDuration: number
sampleCount: number
samples: SpeedSample[]
// Aggregated aliases / per-session summary fields
messageCount: number
totalTokens: number
totalElapsedMs: number
avgTokensPerSecond: number
minTokensPerSecond: number
maxTokensPerSecond: number
startTime: number
endTime: number
}
export interface TrackerOptions { export interface TrackerOptions {
windowMs?: number windowMs?: number
idleTimeoutMs?: number idleTimeoutMs?: number