The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
feat(benchmark): measure what a run cost and whether it was right, not just its speed
purple06cd47c4ae44
diff --git a/src/components/models/BenchmarkView.tsx b/src/components/models/BenchmarkView.tsxindex 5c04472b..5b9ab41a 100644--- a/src/components/models/BenchmarkView.tsx+++ b/src/components/models/BenchmarkView.tsx@@ -147,6 +147,33 @@ export function BenchmarkView() {style={{ width: `${barWidth}%` }}/></div>+ {/* The economy row: speed is only half the story. Two models+ can tie on t/s and differ by half again in tokens spent. */}+ <div className="flex items-center flex-wrap gap-x-3 gap-y-0.5 mt-1 text-[0.55rem] font-mono text-gray-500">+ {entry.avgTokens !== null && (+ <span title="Average tokens spent per prompt, reasoning included. Fewer for the same answers is the cheaper model.">+ {entry.avgTokens} tok+ </span>+ )}+ {entry.thinkShare !== null && entry.thinkShare > 0 && (+ <span title="Share of the output spent on reasoning before the answer">+ {Math.round(entry.thinkShare * 100)}% think+ </span>+ )}+ {entry.accuracy !== null && (+ <span+ title="How often the answer matched the expected result"+ className={entry.accuracy < 1 ? 'text-amber-500' : 'text-emerald-500'}+ >+ {Math.round(entry.accuracy * 100)}% correct+ </span>+ )}+ {entry.truncated > 0 && (+ <span title="Runs the token budget cut off before the model was done. Their token counts are a floor, not a measurement." className="text-red-500">+ {entry.truncated} cut off+ </span>+ )}+ </div></div></div>)diff --git a/src/components/models/ModelBenchmark.tsx b/src/components/models/ModelBenchmark.tsxindex 6cac2ba8..accf70b5 100644--- a/src/components/models/ModelBenchmark.tsx+++ b/src/components/models/ModelBenchmark.tsx@@ -80,6 +80,15 @@ export function BenchmarkLeaderboard() {style={{ width: `${barWidth}%` }}/></div>+ <div className="flex items-center flex-wrap gap-x-2 mt-0.5 text-[0.5rem] font-mono text-gray-600">+ {entry.avgTokens !== null && <span>{entry.avgTokens} tok</span>}+ {entry.accuracy !== null && (+ <span className={entry.accuracy < 1 ? 'text-amber-400' : 'text-emerald-400'}>+ {Math.round(entry.accuracy * 100)}% correct+ </span>+ )}+ {entry.truncated > 0 && <span className="text-red-400">{entry.truncated} cut off</span>}+ </div></div></div>)diff --git a/src/hooks/useBenchmark.ts b/src/hooks/useBenchmark.tsindex 1ef63c4f..919aeef8 100644--- a/src/hooks/useBenchmark.ts+++ b/src/hooks/useBenchmark.ts@@ -3,9 +3,10 @@*/import { useCallback, useRef } from 'react'-import { useBenchmarkStore, computeGenerationTps } from '../stores/benchmarkStore'+import { useBenchmarkStore } from '../stores/benchmarkStore'import { getProviderForModel } from '../api/providers'import { BENCHMARK_PROMPTS } from '../lib/benchmark-prompts'+import { measureRun } from '../lib/benchmark-run'import type { ChatMessage } from '../api/providers/types'export function useBenchmark() {@@ -29,73 +30,23 @@ export function useBenchmark() {{ role: 'user', content: prompt.prompt },]- const startTime = performance.now()- let firstTokenTime = 0- let tokenCount = 0- let apiEvalCount: number | undefined- let apiEvalDurationMs: number | undefined-const stream = provider.chatStream(modelId, messages, {temperature: 0.7,signal: abortRef.current.signal,})- for await (const chunk of stream) {- if (chunk.content) {- if (tokenCount === 0) {- firstTokenTime = performance.now() - startTime- }- tokenCount++- }- // Bug M v2.4.7 — Ollama reports authoritative gen metrics in the- // done:true chunk. Prefer these over client-side timing because- // WebView2 release-mode buffers the response stream for fast small- // models, collapsing firstTokenTime to ~totalTime and producing- // absurd JS-measured tps values.- if (chunk.evalCount !== undefined && chunk.evalCount > 0) {- apiEvalCount = chunk.evalCount- }- if (chunk.evalDurationMs !== undefined && chunk.evalDurationMs > 0) {- apiEvalDurationMs = chunk.evalDurationMs- }- }-- const totalTime = performance.now() - startTime-- // Three-way TPS branch for Bug M (v2.4.7):- // 1. Provider returned authoritative server metrics (Ollama via- // eval_count/eval_duration) → use them. Most accurate.- // 2. JS measurement with reasonable generation phase → use the- // post-TTFT formula (the original Bug M fix). Works for- // providers that don't return server metrics but where the- // stream actually streams (proper chunk-by-chunk delivery).- // 3. JS measurement collapsed to ~0ms generation phase → the- // response was buffered (Tauri Rust proxy in release-mode- // collects all bytes before returning, or WebView2 / Edge- // aggregates TCP packets for fast small responses). The- // post-TTFT formula would divide by ~0 and produce absurd- // values like 685k tok/s. Fall back to wall-clock rate- // (tokens/totalTime). It under-counts because it includes- // load+TTFT time but at least is sane — and a real- // improvement over pre-v2.4.7 where this case also produced- // garbage just via a different formula path.- const generationTimeMs = totalTime - firstTokenTime- const hasApiMetrics = apiEvalCount !== undefined && apiEvalDurationMs !== undefined- const isBuffered = !hasApiMetrics && generationTimeMs < 100 && totalTime > 0- const reportedTokens = hasApiMetrics ? apiEvalCount! : tokenCount- const reportedTps = hasApiMetrics- ? (apiEvalCount! / apiEvalDurationMs!) * 1000- : isBuffered- ? (tokenCount / totalTime) * 1000- : computeGenerationTps(tokenCount, totalTime, firstTokenTime)+ const m = await measureRun(stream, prompt.check)store.addResult({modelName,promptId: prompt.id,- tokensPerSec: reportedTps,- timeToFirstToken: firstTokenTime,- totalTime,- totalTokens: reportedTokens,+ tokensPerSec: m.tokensPerSec,+ timeToFirstToken: m.timeToFirstToken,+ totalTime: m.totalTime,+ totalTokens: m.totalTokens,+ thinkTokens: m.thinkTokens,+ finishReason: m.finishReason,+ correct: m.correct,timestamp: Date.now(),})} catch {diff --git a/src/lib/__tests__/benchmark-prompts.test.ts b/src/lib/__tests__/benchmark-prompts.test.tsnew file mode 100644index 00000000..82e8c65e--- /dev/null+++ b/src/lib/__tests__/benchmark-prompts.test.ts@@ -0,0 +1,57 @@+import { describe, it, expect } from 'vitest'+import { BENCHMARK_PROMPTS } from '../benchmark-prompts'++/**+ * B6 (David 2026-08-05): the benchmark checks the ANSWER, not the reasoning.+ * The failure this guards against is a model that reasons its way to the right+ * number and then runs out of token budget before printing it. A speed-only+ * benchmark calls that a fast run; the check calls it wrong.+ */+const check = (id: string) => BENCHMARK_PROMPTS.find((p) => p.id === id)!.check++describe('benchmark prompt checks', () => {+ describe('speed: list 1 to 50', () => {+ const speed = check('speed')+ it('passes a full list', () => {+ expect(speed(Array.from({ length: 50 }, (_, i) => i + 1).join('\n'))).toBe(true)+ })+ it('fails a list cut off before the end', () => {+ expect(speed(Array.from({ length: 30 }, (_, i) => i + 1).join('\n'))).toBe(false)+ })+ it('fails empty output', () => {+ expect(speed('')).toBe(false)+ })+ })++ describe('reasoning: 17 sheep, all but 9 stay', () => {+ const reasoning = check('reasoning')+ it('passes when the answer ends on 9', () => {+ expect(reasoning('All but 9 stay, so the farmer has 9 sheep left.')).toBe(true)+ })+ it('passes the answer spelled out', () => {+ expect(reasoning('The farmer has nine sheep left.')).toBe(true)+ })+ it('fails the classic 17 minus 9 equals 8 slip', () => {+ expect(reasoning('17 minus 9 is 8, so 8 sheep are left.')).toBe(false)+ })+ it('fails an answer that never states the number', () => {+ // The exact case David hit: the reasoning reached 9 but the budget ran+ // out first, so the visible answer carries no number at all.+ expect(reasoning('Let me work through this carefully. A farmer keeps')).toBe(false)+ })+ })++ describe('code: a fibonacci function', () => {+ const code = check('code')+ it('passes a real definition', () => {+ expect(code('def fibonacci(n):\n """nth fib"""\n return n')).toBe(true)+ })+ it('fails prose that never defines it', () => {+ expect(code('Fibonacci numbers are a famous sequence in mathematics.')).toBe(false)+ })+ })++ it('every prompt carries a check', () => {+ for (const p of BENCHMARK_PROMPTS) expect(typeof p.check).toBe('function')+ })+})diff --git a/src/lib/__tests__/benchmark-run.test.ts b/src/lib/__tests__/benchmark-run.test.tsnew file mode 100644index 00000000..d995423b--- /dev/null+++ b/src/lib/__tests__/benchmark-run.test.ts@@ -0,0 +1,110 @@+import { describe, it, expect } from 'vitest'+import { measureRun } from '../benchmark-run'+import { BENCHMARK_PROMPTS } from '../benchmark-prompts'+import type { ChatStreamChunk } from '../../api/providers/types'++/**+ * measureRun is the accounting the benchmark hook used to bury inside a React+ * callback, where nothing could reach it. Lifted out, it can be run against a+ * scripted stream, which is the only way to reproduce the one case David cared+ * about without a live model: a reasoning model that works out the right answer+ * and then hits its token budget before printing it.+ */++async function* streamOf(chunks: Partial<ChatStreamChunk>[]): AsyncGenerator<ChatStreamChunk> {+ for (const c of chunks) yield { content: '', done: false, ...c } as ChatStreamChunk+}++/** A clock that returns each value in turn, so timing is exact in a test. */+function steppedClock(...values: number[]): () => number {+ let i = 0+ return () => {+ const v = values[Math.min(i, values.length - 1)]+ i+++ return v+ }+}++const check = (id: string) => BENCHMARK_PROMPTS.find((p) => p.id === id)!.check++describe('measureRun', () => {+ it("catches David's case: reasoning reaches the answer but the budget cuts it off", async () => {+ // The model thinks its way to 9 (visible in `thinking`), then the stream+ // ends on 'length' before any answer content. A speed-only benchmark sees+ // 50 tok/s and calls it a healthy run. The truth is a wrong, truncated one.+ const m = await measureRun(+ streamOf([+ { thinking: 'The farmer has 17 sheep. ' },+ { thinking: 'All but 9 run away, so 9 stay. ' },+ { thinking: 'Double-checking the wording... ' },+ { done: true, finishReason: 'length', evalCount: 300, evalDurationMs: 6000 },+ ]),+ check('reasoning'),+ steppedClock(0, 200, 6200),+ )+ expect(m.correct).toBe(false) // the answer was never printed+ expect(m.finishReason).toBe('length') // and this says why+ expect(m.totalTokens).toBe(300) // authoritative count, thinking included+ expect(m.thinkTokens).toBe(300) // all of it was reasoning+ expect(m.tokensPerSec).toBe(50) // fast, which is exactly the trap+ expect(m.timeToFirstToken).toBe(200)+ })++ it('scores a clean thinking run correct and splits the think tokens off', async () => {+ const m = await measureRun(+ streamOf([+ { thinking: 'Reasoning about the sheep. ' },+ { content: 'The farmer has ' },+ { content: '9 sheep left.' },+ { done: true, finishReason: 'stop', evalCount: 40, evalDurationMs: 1000 },+ ]),+ check('reasoning'),+ steppedClock(0, 120, 1120),+ )+ expect(m.correct).toBe(true)+ expect(m.finishReason).toBe('stop')+ expect(m.totalTokens).toBe(40)+ // one thinking chunk of three total chunks, scaled onto the authoritative+ // total: round(40 * 1/3) = 13+ expect(m.thinkTokens).toBe(13)+ })++ it('a model that does not think out loud spends zero think tokens', async () => {+ const m = await measureRun(+ streamOf([+ { content: 'def fibonacci(n):\n' },+ { content: ' return n\n' },+ { done: true, finishReason: 'stop' },+ ]),+ check('code'),+ steppedClock(0, 100, 1100),+ )+ expect(m.thinkTokens).toBe(0)+ expect(m.totalTokens).toBe(2) // two content chunks, JS fallback (no API metrics)+ expect(m.correct).toBe(true)+ expect(m.tokensPerSec).toBeCloseTo(2, 5) // 2 tokens / 1000ms generation+ })++ it('falls back to wall-clock rate when the stream arrives buffered', async () => {+ // No server metrics and the whole response lands in a ~0ms window: the+ // post-TTFT formula would divide by almost nothing, so measureRun uses the+ // wall-clock rate instead (the Bug M v2.4.7 guard).+ const m = await measureRun(+ streamOf([{ content: 'nine' }, { done: true, finishReason: 'stop' }]),+ check('reasoning'),+ steppedClock(0, 10, 60),+ )+ expect(m.correct).toBe(true) // spelled-out answer+ expect(m.tokensPerSec).toBeCloseTo((1 / 60) * 1000, 3)+ })++ it('carries a disconnect reason through untouched', async () => {+ const m = await measureRun(+ streamOf([{ content: 'partial ans' }, { done: true, finishReason: 'disconnect' }]),+ check('code'),+ steppedClock(0, 50, 550),+ )+ expect(m.finishReason).toBe('disconnect')+ expect(m.correct).toBe(false)+ })+})diff --git a/src/lib/benchmark-prompts.ts b/src/lib/benchmark-prompts.tsindex 72818ec9..51ef29ad 100644--- a/src/lib/benchmark-prompts.ts+++ b/src/lib/benchmark-prompts.ts@@ -1,5 +1,15 @@/*** Standardized benchmark prompts for local model testing.+ *+ * A benchmark that only times tokens hides the difference that matters. David+ * ran a 9B DeepSeek-V4-Flash-Distill against a 9B Qwen3.5, same quant, same+ * settings: 44 vs 41 tok/s, so a speed-only board would call it a tie. The real+ * gap was economy and correctness. Over eight tasks the distill spent 5480+ * tokens where the base model spent 8975 for the same answers, and on one+ * reasoning task the base model ran into its token budget with the right answer+ * still sitting in its reasoning, so it never wrote it out. So every prompt now+ * carries a check that reads the ANSWER, not the hidden reasoning, and every+ * run records how much of its output went into thinking and why it stopped.*/export interface BenchmarkPrompt {@@ -7,7 +17,41 @@ export interface BenchmarkPrompt {name: stringcategory: 'speed' | 'reasoning' | 'code'prompt: string- expectedMinTokens: number+ /**+ * Passes when the model's answer (its visible output, not its `thinking`)+ * carries the expected result. A run that spends its whole token budget+ * reasoning and never states the answer fails here even though the reasoning+ * was right, which is exactly the failure a speed-only benchmark cannot see.+ */+ check: (answer: string) => boolean+}++/** Every integer in the text, in order of appearance. */+function numbersIn(text: string): number[] {+ return (text.match(/-?\d+/g) ?? []).map(Number)+}++/** 1 to 50 on their own lines: a truncated or lazy answer drops the ends. */+function checkSpeed(answer: string): boolean {+ const seen = new Set(numbersIn(answer))+ return seen.has(1) && seen.has(25) && seen.has(50)+}++/**+ * 17 sheep, "all but 9 run away", so 9 stay. 8 is the classic 17 minus 9 slip,+ * and a run that spent its budget thinking states no number at all. The answer+ * is right when its last number is 9, with a word fallback for models that+ * spell it out.+ */+function checkReasoning(answer: string): boolean {+ const nums = numbersIn(answer)+ if (nums.length > 0 && nums[nums.length - 1] === 9) return true+ return /\bnine\b/i.test(answer) && !/\beight\b/i.test(answer)+}++/** A function named fibonacci is the thing that was asked for. */+function checkCode(answer: string): boolean {+ return /def\s+fibonacci\s*\(/i.test(answer)}export const BENCHMARK_PROMPTS: BenchmarkPrompt[] = [@@ -16,21 +60,21 @@ export const BENCHMARK_PROMPTS: BenchmarkPrompt[] = [name: 'Speed Test',category: 'speed',prompt: 'List the numbers from 1 to 50, each on a new line. Just the numbers, nothing else.',- expectedMinTokens: 50,+ check: checkSpeed,},{id: 'reasoning',name: 'Reasoning',category: 'reasoning',prompt: 'A farmer has 17 sheep. All but 9 run away. How many sheep does the farmer have left? Explain your reasoning step by step.',- expectedMinTokens: 30,+ check: checkReasoning,},{id: 'code',name: 'Code Generation',category: 'code',prompt: 'Write a Python function called `fibonacci` that returns the nth Fibonacci number using dynamic programming. Include a docstring.',- expectedMinTokens: 40,+ check: checkCode,},]@@ -40,6 +84,17 @@ export interface BenchmarkResult {tokensPerSec: numbertimeToFirstToken: numbertotalTime: number+ /** Whole output, thinking included, so a reasoning model and a terse one are+ * measured on the same axis. */totalTokens: number+ /** Reasoning tokens (Ollama `thinking` / `<think>`). 0 for a model that does+ * not think out loud. Undefined on runs recorded before 2.6.3. */+ thinkTokens?: number+ /** Why generation ended: 'stop' | 'length' | 'disconnect'. A 'length' run is+ * truncated, so its token count is a floor and its answer may be cut off.+ * Undefined on runs recorded before 2.6.3. */+ finishReason?: string+ /** Did the answer match the prompt's expected result. Undefined pre-2.6.3. */+ correct?: booleantimestamp: number}diff --git a/src/lib/benchmark-run.ts b/src/lib/benchmark-run.tsnew file mode 100644index 00000000..7ea91577--- /dev/null+++ b/src/lib/benchmark-run.ts@@ -0,0 +1,117 @@+/**+ * The per-prompt measurement, lifted out of the React hook so it can be tested+ * against a synthetic stream instead of a live model.+ *+ * It consumes one chat stream and reports not just how fast the model ran but+ * how much it spent, how much of that went into reasoning, why it stopped, and+ * whether the answer was actually right (David 2026-08-05). The clock is+ * injected so a test can make the timing deterministic; production passes+ * performance.now.+ */++import type { ChatStreamChunk } from '../api/providers/types'+import { computeGenerationTps } from '../stores/benchmarkStore'++export interface RunMeasurement {+ tokensPerSec: number+ timeToFirstToken: number+ totalTime: number+ totalTokens: number+ thinkTokens: number+ finishReason?: string+ correct: boolean+}++export async function measureRun(+ stream: AsyncIterable<ChatStreamChunk>,+ check: (answer: string) => boolean,+ clock: () => number = () => performance.now(),+): Promise<RunMeasurement> {+ const startTime = clock()+ let firstTokenTime = 0+ let contentCount = 0+ let thinkCount = 0+ let answerText = ''+ let finishReason: string | undefined+ let apiEvalCount: number | undefined+ let apiEvalDurationMs: number | undefined++ for await (const chunk of stream) {+ // Time to first token is the first output of any kind: for a model that+ // reasons out loud the thinking arrives before the answer, and starting+ // the clock only at the first answer token would hide the whole reasoning+ // phase from the generation rate below.+ if ((chunk.content || chunk.thinking) && firstTokenTime === 0) {+ firstTokenTime = clock() - startTime+ }+ if (chunk.thinking) thinkCount+++ if (chunk.content) {+ answerText += chunk.content+ contentCount+++ }+ if (chunk.finishReason) finishReason = chunk.finishReason+ // Bug M v2.4.7 — Ollama reports authoritative gen metrics in the done:true+ // chunk. Prefer these over client-side timing because WebView2 release-mode+ // buffers the response stream for fast small models, collapsing+ // firstTokenTime to ~totalTime and producing absurd JS-measured tps values.+ if (chunk.evalCount !== undefined && chunk.evalCount > 0) {+ apiEvalCount = chunk.evalCount+ }+ if (chunk.evalDurationMs !== undefined && chunk.evalDurationMs > 0) {+ apiEvalDurationMs = chunk.evalDurationMs+ }+ }++ const totalTime = clock() - startTime++ // totalTokens is the whole output, thinking included, so a model that reasons+ // out loud and one that does not are counted the same way (David 2026-08-05:+ // two 9B models tied on tok/s, one spent 8975 tokens where the other spent+ // 5480 for the same answers). Ollama's evalCount already folds thinking into+ // the count; the JS fallback adds the two chunk counters to match. thinkShare+ // is a ratio of the same chunk units on both paths, so it stays comparable+ // regardless of which branch produced the token total.+ const jsTotal = contentCount + thinkCount+ const thinkShare = jsTotal > 0 ? thinkCount / jsTotal : 0++ // Three-way TPS branch for Bug M (v2.4.7):+ // 1. Provider returned authoritative server metrics (Ollama via+ // eval_count/eval_duration) -> use them. Most accurate.+ // 2. JS measurement with a real generation phase -> use the post-TTFT+ // formula (the original Bug M fix). Works for providers that do not+ // return server metrics but where the stream actually streams.+ // 3. JS measurement collapsed to ~0ms generation phase -> the response was+ // buffered (Tauri Rust proxy in release-mode collects all bytes before+ // returning, or WebView2 aggregates TCP packets for fast responses). The+ // post-TTFT formula would divide by ~0 and produce absurd values like+ // 685k tok/s. Fall back to wall-clock rate (tokens/totalTime). It+ // under-counts because it includes load and TTFT time but at least is+ // sane, and a real improvement over pre-v2.4.7 where this case also+ // produced garbage just via a different formula path.+ const generationTimeMs = totalTime - firstTokenTime+ const hasApiMetrics = apiEvalCount !== undefined && apiEvalDurationMs !== undefined+ const isBuffered = !hasApiMetrics && generationTimeMs < 100 && totalTime > 0+ const reportedTokens = hasApiMetrics ? apiEvalCount! : jsTotal+ const reportedTps = hasApiMetrics+ ? (apiEvalCount! / apiEvalDurationMs!) * 1000+ : isBuffered+ ? (jsTotal / totalTime) * 1000+ : computeGenerationTps(jsTotal, totalTime, firstTokenTime)++ return {+ tokensPerSec: reportedTps,+ timeToFirstToken: firstTokenTime,+ totalTime,+ totalTokens: reportedTokens,+ // thinkShare is measured in chunk units; scaling the authoritative token+ // total by it keeps thinkTokens in the same unit as totalTokens, so+ // thinkTokens / totalTokens is a valid ratio even when the total came from+ // Ollama's evalCount rather than the counters.+ thinkTokens: Math.round(reportedTokens * thinkShare),+ finishReason,+ // The answer is the visible output only. A model that reasoned its way to+ // the right number but never printed it fails here, which is the whole+ // point of measuring correctness next to speed.+ correct: check(answerText),+ }+}diff --git a/src/stores/__tests__/benchmark-management.test.ts b/src/stores/__tests__/benchmark-management.test.tsindex 3c9615c5..51a939a8 100644--- a/src/stores/__tests__/benchmark-management.test.ts+++ b/src/stores/__tests__/benchmark-management.test.ts@@ -90,11 +90,14 @@ describe('markdown export', () => {expect(md).toContain('# Local model benchmark')expect(md).toContain('2026-08-01 12:00')- expect(md).toContain('| # | Model | Average t/s | Latest t/s | Runs |')+ expect(md).toContain('| # | Model | Average t/s | Latest t/s | Avg tokens | Think | Correct | Runs |')// Ranked fastest first, same order as the leaderboard on screen.expect(md.indexOf('fast:3b')).toBeLessThan(md.indexOf('slow:70b'))expect(md).toMatch(/\| 1 \| fast:3b \| 41 \|/)expect(md).toMatch(/\| 2 \| slow:70b \| 4 \|/)+ // These runs predate the economy fields, so those columns read as a dash+ // rather than a wrong number.+ expect(md).toMatch(/\| 1 \| fast:3b \| 41 \| 41 \| - \| - \| - \| 2 \|/)expect(md).toContain('3 runs across 2 models.')})diff --git a/src/stores/__tests__/benchmarkStore.test.ts b/src/stores/__tests__/benchmarkStore.test.tsindex 3defa994..99fb5208 100644--- a/src/stores/__tests__/benchmarkStore.test.ts+++ b/src/stores/__tests__/benchmarkStore.test.ts@@ -1,5 +1,8 @@import { describe, it, expect, beforeEach } from 'vitest'-import { useBenchmarkStore, getAverageSpeed, getLatestSpeed, getLeaderboard, computeGenerationTps } from '../benchmarkStore'+import {+ useBenchmarkStore, getAverageSpeed, getLatestSpeed, getLeaderboard, computeGenerationTps,+ getAverageTokens, getAccuracy, getAverageThinkShare, getTruncatedCount, toMarkdownReport,+} from '../benchmarkStore'import type { BenchmarkResult } from '../../lib/benchmark-prompts'// ── Helpers ─────────────────────────────────────────────────────@@ -333,4 +336,108 @@ describe('benchmarkStore', () => {expect(tps).toBe(100)})})++ // ── token economy (B6 — David 2026-08-05) ──────────────────++ describe('getAverageTokens', () => {+ it('averages the total token spend, rounded', () => {+ const r = {+ m: [makeResult('m', 40, { totalTokens: 5000 }), makeResult('m', 40, { totalTokens: 8000 })],+ }+ expect(getAverageTokens(r, 'm')).toBe(6500)+ })++ it('is null for a model with no runs', () => {+ expect(getAverageTokens({}, 'unknown')).toBeNull()+ })+ })++ describe('getAccuracy', () => {+ it('is the fraction correct over runs that recorded a verdict', () => {+ const r = {+ m: [+ makeResult('m', 40, { correct: true }),+ makeResult('m', 40, { correct: false }),+ makeResult('m', 40, { correct: true }),+ makeResult('m', 40, {}), // pre-2.6.3 run, no verdict, excluded+ ],+ }+ expect(getAccuracy(r, 'm')).toBeCloseTo(2 / 3, 5)+ })++ it('is null when no run recorded a verdict', () => {+ expect(getAccuracy({ m: [makeResult('m', 40)] }, 'm')).toBeNull()+ })+ })++ describe('getAverageThinkShare', () => {+ it('averages thinkTokens over totalTokens', () => {+ const r = {+ m: [+ makeResult('m', 40, { totalTokens: 100, thinkTokens: 40 }), // 0.4+ makeResult('m', 40, { totalTokens: 200, thinkTokens: 20 }), // 0.1+ ],+ }+ expect(getAverageThinkShare(r, 'm')).toBeCloseTo(0.25, 5)+ })++ it('ignores runs that recorded no think count', () => {+ expect(getAverageThinkShare({ m: [makeResult('m', 40, { totalTokens: 100 })] }, 'm')).toBeNull()+ })+ })++ describe('getTruncatedCount', () => {+ it('counts only runs cut off by the token budget', () => {+ const r = {+ m: [+ makeResult('m', 40, { finishReason: 'length' }),+ makeResult('m', 40, { finishReason: 'stop' }),+ makeResult('m', 40, { finishReason: 'length' }),+ makeResult('m', 40, {}),+ ],+ }+ expect(getTruncatedCount(r, 'm')).toBe(2)+ })+ })++ describe('getLeaderboard carries the economy stats', () => {+ it('reports tokens, accuracy, think share and truncation next to t/s', () => {+ const r = {+ m: [makeResult('m', 40, { totalTokens: 100, thinkTokens: 30, correct: true, finishReason: 'length' })],+ }+ const [entry] = getLeaderboard(r)+ expect(entry.avgTps).toBe(40)+ expect(entry.avgTokens).toBe(100)+ expect(entry.accuracy).toBe(1)+ expect(entry.thinkShare).toBeCloseTo(0.3, 5)+ expect(entry.truncated).toBe(1)+ })++ it('leaves the new stats null when the runs predate them', () => {+ const [entry] = getLeaderboard({ m: [makeResult('m', 40, { totalTokens: 200 })] })+ expect(entry.accuracy).toBeNull()+ expect(entry.thinkShare).toBeNull()+ expect(entry.truncated).toBe(0)+ })+ })+})++describe('toMarkdownReport economy columns', () => {+ it('has the economy header and fills a row', () => {+ const r = { fast: [makeResult('fast', 44, { totalTokens: 5000, thinkTokens: 1000, correct: true })] }+ const md = toMarkdownReport(r, '2026-08-05 12:00')+ expect(md).toContain('Avg tokens')+ expect(md).toContain('Think')+ expect(md).toContain('Correct')+ expect(md).toContain('| 5000 |') // avg tokens cell+ expect(md).toContain('20%') // 1000 / 5000 thinking+ expect(md).toContain('100%') // accuracy+ })++ it('marks a truncated run and dashes a stat it never recorded', () => {+ const r = { m: [makeResult('m', 40, { totalTokens: 900, finishReason: 'length' })] }+ const md = toMarkdownReport(r, '2026-08-05 12:00')+ expect(md).toContain('900 (1 cut off)')+ expect(md).toMatch(/\| 900 \(1 cut off\) \| - \| - \|/)+ })})diff --git a/src/stores/benchmarkStore.ts b/src/stores/benchmarkStore.tsindex 29ced3f8..9a589546 100644--- a/src/stores/benchmarkStore.ts+++ b/src/stores/benchmarkStore.ts@@ -103,19 +103,29 @@ export function toMarkdownReport(lines.push('No benchmark runs recorded yet.', '')return lines.join('\n')}+ const pct = (v: number | null): string => (v === null ? '-' : `${Math.round(v * 100)}%`)lines.push(- '| # | Model | Average t/s | Latest t/s | Runs |',- '| --- | --- | ---: | ---: | ---: |',+ '| # | Model | Average t/s | Latest t/s | Avg tokens | Think | Correct | Runs |',+ '| --- | --- | ---: | ---: | ---: | ---: | ---: | ---: |',)board.forEach((entry, i) => {const latest = getLatestSpeed(results, entry.model)- lines.push(`| ${i + 1} | ${entry.model} | ${entry.avgTps} | ${latest ?? '-'} | ${entry.runs} |`)+ const tokens = entry.avgTokens === null+ ? '-'+ : `${entry.avgTokens}${entry.truncated > 0 ? ` (${entry.truncated} cut off)` : ''}`+ lines.push(+ `| ${i + 1} | ${entry.model} | ${entry.avgTps} | ${latest ?? '-'} | ${tokens} | ${pct(entry.thinkShare)} | ${pct(entry.accuracy)} | ${entry.runs} |`,+ )})lines.push('',`${board.reduce((s, e) => s + e.runs, 0)} runs across ${board.length} models.`,'','Average is every recorded run. Latest is the most recent benchmark pass.',+ 'Avg tokens is the whole output including reasoning; a lower count for the',+ 'same answers is the cheaper model. Think is the share of that output spent',+ 'reasoning. Correct is how often the answer matched. A run cut off by the',+ 'token budget is marked, and its token count is a floor, not a measurement.','',)return lines.join('\n')@@ -187,13 +197,71 @@ export function computeGenerationTps(return (tokenCount / generationTimeMs) * 1000}-/** Get leaderboard sorted by avg tokens/sec */-export function getLeaderboard(results: Record<string, BenchmarkResult[]>): { model: string; avgTps: number; runs: number }[] {+/**+ * Average total tokens (thinking included) a model spent per prompt. This is+ * the axis a speed-only board is blind to: two models can tie on tok/s and+ * still differ by half again in tokens spent for the same answers (David+ * 2026-08-05). Null for a model whose runs predate the field.+ */+export function getAverageTokens(results: Record<string, BenchmarkResult[]>, modelName: string): number | null {+ const runs = (results[modelName] ?? []).filter((r) => typeof r.totalTokens === 'number')+ if (runs.length === 0) return null+ return Math.round(runs.reduce((s, r) => s + r.totalTokens, 0) / runs.length)+}++/**+ * Fraction of a model's runs whose answer matched, over the runs that recorded+ * a verdict. Null when no run carries one, which is every result from before+ * 2.6.3 and any run of a prompt with no check.+ */+export function getAccuracy(results: Record<string, BenchmarkResult[]>, modelName: string): number | null {+ const runs = (results[modelName] ?? []).filter((r) => r.correct !== undefined)+ if (runs.length === 0) return null+ return runs.filter((r) => r.correct).length / runs.length+}++/**+ * Average share of output spent on reasoning, 0..1, over runs that recorded a+ * think-token count. Null when none do. The number that explains a slow-feeling+ * model that is not actually slow, only verbose in its thinking.+ */+export function getAverageThinkShare(results: Record<string, BenchmarkResult[]>, modelName: string): number | null {+ const runs = (results[modelName] ?? []).filter((r) => r.thinkTokens !== undefined && r.totalTokens > 0)+ if (runs.length === 0) return null+ return runs.reduce((s, r) => s + r.thinkTokens! / r.totalTokens, 0) / runs.length+}++/**+ * Runs that ended on the token budget rather than the model deciding it was+ * done. Their token counts are floors and their answers may be cut off, so a+ * benchmark that shows the count without this flag invites the wrong read.+ */+export function getTruncatedCount(results: Record<string, BenchmarkResult[]>, modelName: string): number {+ return (results[modelName] ?? []).filter((r) => r.finishReason === 'length').length+}++export interface LeaderboardEntry {+ model: string+ avgTps: number+ runs: number+ avgTokens: number | null+ accuracy: number | null+ thinkShare: number | null+ truncated: number+}++/** Get leaderboard sorted by avg tokens/sec, with the economy stats alongside+ * so speed is read next to what it cost and whether the answer was right. */+export function getLeaderboard(results: Record<string, BenchmarkResult[]>): LeaderboardEntry[] {return Object.entries(results).map(([model, runs]) => ({model,avgTps: Math.round((runs.reduce((s, r) => s + r.tokensPerSec, 0) / runs.length) * 10) / 10,runs: runs.length,+ avgTokens: getAverageTokens(results, model),+ accuracy: getAccuracy(results, model),+ thinkShare: getAverageThinkShare(results, model),+ truncated: getTruncatedCount(results, model),})).sort((a, b) => b.avgTps - a.avgTps)}